Updated copiright notice.
[bertos.git] / drv / ser.c
1 /**
2  * \file
3  * <!--
4  * This file is part of BeRTOS.
5  *
6  * Bertos is free software; you can redistribute it and/or modify
7  * it under the terms of the GNU General Public License as published by
8  * the Free Software Foundation; either version 2 of the License, or
9  * (at your option) any later version.
10  *
11  * This program is distributed in the hope that it will be useful,
12  * but WITHOUT ANY WARRANTY; without even the implied warranty of
13  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14  * GNU General Public License for more details.
15  *
16  * You should have received a copy of the GNU General Public License
17  * along with this program; if not, write to the Free Software
18  * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
19  *
20  * As a special exception, you may use this file as part of a free software
21  * library without restriction.  Specifically, if other files instantiate
22  * templates or use macros or inline functions from this file, or you compile
23  * this file and link it with other files to produce an executable, this
24  * file does not by itself cause the resulting executable to be covered by
25  * the GNU General Public License.  This exception does not however
26  * invalidate any other reasons why the executable file might be covered by
27  * the GNU General Public License.
28  *
29  * Copyright 2003, 2004, 2006 Develer S.r.l. (http://www.develer.com/)
30  * Copyright 2000 Bernardo Innocenti <bernie@codewiz.org>
31  * This file is part of DevLib - See README.devlib for information.
32  * -->
33  *
34  * \brief Buffered serial I/O driver
35  *
36  * The serial rx interrupt buffers incoming data in a software FIFO
37  * to decouple the higher level protocols from the line speed.
38  * Outgoing data is buffered as well for better performance.
39  * This driver is not optimized for best performance, but it
40  * has proved to be fast enough to handle transfer rates up to
41  * 38400bps on a 16MHz 80196.
42  *
43  * MODULE CONFIGURATION
44  *
45  *  \li \c CONFIG_SER_HWHANDSHAKE - set to 1 to enable RTS/CTS handshake.
46  *         Support is incomplete/untested.
47  *  \li \c CONFIG_SER_TXTIMEOUT - Enable software serial transmission timeouts
48  *
49  *
50  * \version $Id$
51  * \author Bernardo Innocenti <bernie@develer.com>
52  */
53
54 /*#*
55  *#* $Log$
56  *#* Revision 1.38  2007/06/21 17:07:21  batt
57  *#* Remove CONFIG_WATCHDOG stuff: watchdog macros expand to nothing when wdt is active.
58  *#*
59  *#* Revision 1.37  2007/06/07 14:35:12  batt
60  *#* Merge from project_ks.
61  *#*
62  *#* Revision 1.36  2007/01/29 11:30:29  batt
63  *#* Reimplement ser_clearstatus as a macro.
64  *#*
65  *#* Revision 1.35  2007/01/27 20:47:12  batt
66  *#* Add clear status.
67  *#*
68  *#* Revision 1.34  2006/11/20 15:07:40  batt
69  *#* Revert unneeded locked functions.
70  *#*
71  *#* Revision 1.33  2006/11/17 18:15:55  batt
72  *#* Avoid race conditions.
73  *#*
74  *#* Revision 1.32  2006/11/17 17:03:58  batt
75  *#* Implement ser_setstatus and ser_getstatus as functions to avoid race conditions.
76  *#*
77  *#* Revision 1.31  2006/07/21 10:58:00  batt
78  *#* Use timer_clock() instead of obsolete timer_ticks().
79  *#*
80  *#* Revision 1.30  2006/07/19 12:56:26  bernie
81  *#* Convert to new Doxygen style.
82  *#*
83  *#* Revision 1.29  2006/05/18 00:39:30  bernie
84  *#* ser_open(): Document a bit more.
85  *#*
86  *#* Revision 1.28  2006/02/17 22:23:06  bernie
87  *#* Update POSIX serial emulator.
88  *#*
89  *#* Revision 1.27  2005/11/27 23:33:40  bernie
90  *#* Use appconfig.h instead of cfg/config.h.
91  *#*
92  *#* Revision 1.26  2005/11/04 16:20:02  bernie
93  *#* Fix reference to README.devlib in header.
94  *#*
95  *#* Revision 1.25  2005/04/11 19:10:27  bernie
96  *#* Include top-level headers from cfg/ subdir.
97  *#*
98  *#* Revision 1.24  2005/01/21 20:13:15  aleph
99  *#* Fix drain at ser_close()
100  *#*
101  *#* Revision 1.23  2005/01/14 00:47:07  aleph
102  *#* ser_drain(): Wait for hw transmission complete.
103  *#*
104  *#* Revision 1.22  2004/12/08 08:56:14  bernie
105  *#* Rename time_t to mtime_t.
106  *#*
107  *#* Revision 1.21  2004/11/16 18:10:13  bernie
108  *#* Add sanity checks for missing configuration parameters.
109  *#*
110  *#* Revision 1.20  2004/10/19 11:48:00  bernie
111  *#* Remove unused variable.
112  *#*
113  *#* Revision 1.19  2004/10/19 08:14:13  bernie
114  *#* Fix a few longstanding bugs wrt status handling (made by rasky on scfirm).
115  *#*
116  *#* Revision 1.18  2004/09/20 03:31:15  bernie
117  *#* Sanitize for C++.
118  *#*
119  *#* Revision 1.17  2004/09/14 21:06:07  bernie
120  *#* Use debug.h instead of kdebug.h; Spelling fixes.
121  *#*
122  *#* Revision 1.16  2004/09/06 21:40:50  bernie
123  *#* Move buffer handling in chip-specific driver.
124  *#*
125  *#* Revision 1.15  2004/08/25 14:12:08  rasky
126  *#* Aggiornato il comment block dei log RCS
127  *#*
128  *#* Revision 1.14  2004/08/24 16:22:57  bernie
129  *#* Thinkos; Doxygen fixes
130  *#*
131  *#* Revision 1.13  2004/08/24 16:20:48  bernie
132  *#* ser_read(): Make buffer argument void *#* for consistency with ANSI C and ser_write()
133  *#*
134  *#* Revision 1.12  2004/08/24 13:49:39  bernie
135  *#* Fix thinko.
136  *#*
137  *#* Revision 1.11  2004/08/15 05:32:22  bernie
138  *#* ser_resync(): New function.
139  *#*
140  *#* Revision 1.10  2004/08/10 06:29:50  bernie
141  *#* Rename timer_gettick() to timer_ticks().
142  *#*
143  *#* Revision 1.9  2004/08/08 06:06:20  bernie
144  *#* Use new-style CONFIG_ idiom; Fix module-wide documentation.
145  *#*
146  *#* Revision 1.8  2004/07/29 22:57:09  bernie
147  *#* ser_drain(): New function; Make Serial::is_open a debug-only feature; Switch to new-style CONFIG_* macros.
148  *#*
149  *#* Revision 1.7  2004/07/18 21:49:03  bernie
150  *#* Make CONFIG_SER_DEFBAUDRATE optional.
151  *#*
152  *#* Revision 1.6  2004/06/07 15:56:28  aleph
153  *#* Remove cast-as-lvalue extension abuse
154  *#*
155  *#* Revision 1.5  2004/06/06 16:41:44  bernie
156  *#* ser_putchar(): Use fifo_push_locked() to fix potential race on 8bit processors.
157  *#*
158  *#* Revision 1.4  2004/06/03 11:27:09  bernie
159  *#* Add dual-license information.
160  *#*
161  *#* Revision 1.3  2004/06/02 21:35:24  aleph
162  *#* Serial enhancements: interruptible receive handler and 8 bit serial status for AVR; remove volatile attribute to FIFOBuffer, useless for new fifobuf routens
163  *#*
164  *#* Revision 1.2  2004/05/23 18:21:53  bernie
165  *#* Trim CVS logs and cleanup header info.
166  *#*
167  *#*/
168
169 #include "ser.h"
170
171 #include "wdt.h"
172
173 #include "ser_p.h"
174 #include <mware/formatwr.h>
175 #include <cfg/debug.h>
176 #include <appconfig.h>
177
178 /*
179  * Sanity check for config parameters required by this module.
180  */
181 #if !defined(CONFIG_KERNEL) || ((CONFIG_KERNEL != 0) && CONFIG_KERNEL != 1)
182         #error CONFIG_KERNEL must be set to either 0 or 1 in config.h
183 #endif
184 #if !defined(CONFIG_SER_RXTIMEOUT)
185         #error CONFIG_SER_TXTIMEOUT missing in config.h
186 #endif
187 #if !defined(CONFIG_SER_RXTIMEOUT)
188         #error CONFIG_SER_RXTIMEOUT missing in config.h
189 #endif
190 #if !defined(CONFIG_SER_GETS) || ((CONFIG_SER_GETS != 0) && CONFIG_SER_GETS != 1)
191         #error CONFIG_SER_GETS must be set to either 0 or 1 in config.h
192 #endif
193 #if !defined(CONFIG_SER_DEFBAUDRATE)
194         #error CONFIG_SER_DEFBAUDRATE missing in config.h
195 #endif
196 #if !defined(CONFIG_PRINTF)
197         #error CONFIG_PRINTF missing in config.h
198 #endif
199
200 #if CONFIG_KERNEL
201         #include <kern/proc.h>
202 #endif
203
204 #if CONFIG_SER_TXTIMEOUT != -1 || CONFIG_SER_RXTIMEOUT != -1
205         #include <drv/timer.h>
206 #endif
207
208
209 /* Serial configuration parameters */
210 #define SER_CTSDELAY        70  /**< CTS line retry interval (ms) */
211 #define SER_TXPOLLDELAY      2  /**< Transmit buffer full retry interval (ms) */
212 #define SER_RXPOLLDELAY      2  /**< Receive buffer empty retry interval (ms) */
213
214
215 struct Serial ser_handles[SER_CNT];
216
217
218 /**
219  * Inserisce il carattere c nel buffer di trasmissione.
220  * Questa funzione mette il processo chiamante in attesa
221  * quando il buffer e' pieno.
222  *
223  * \return EOF in caso di errore o timeout, altrimenti
224  *         il carattere inviato.
225  */
226 int ser_putchar(int c, struct Serial *port)
227 {
228         //ASSERT_VALID_FIFO(&port->txfifo);
229         if (fifo_isfull_locked(&port->txfifo))
230         {
231 #if CONFIG_SER_TXTIMEOUT != -1
232                 ticks_t start_time = timer_clock();
233 #endif
234
235                 /* Attende finche' il buffer e' pieno... */
236                 do
237                 {
238                         wdt_reset();
239 #if CONFIG_KERNEL && CONFIG_KERN_SCHED
240                         /* Give up timeslice to other processes. */
241                         proc_switch();
242 #endif
243 #if CONFIG_SER_TXTIMEOUT != -1
244                         if (timer_clock() - start_time >= port->txtimeout)
245                         {
246                                 ATOMIC(port->status |= SERRF_TXTIMEOUT);
247                                 return EOF;
248                         }
249 #endif /* CONFIG_SER_TXTIMEOUT */
250                 }
251                 while (fifo_isfull_locked(&port->txfifo));
252         }
253
254         fifo_push_locked(&port->txfifo, (unsigned char)c);
255
256         /* (re)trigger tx interrupt */
257         port->hw->table->txStart(port->hw);
258
259         /* Avoid returning signed extended char */
260         return (int)((unsigned char)c);
261 }
262
263
264 /**
265  * Preleva un carattere dal buffer di ricezione.
266  * Questa funzione mette il processo chiamante in attesa
267  * quando il buffer e' vuoto. L'attesa ha un timeout
268  * di ser_rxtimeout millisecondi.
269  *
270  * \return EOF in caso di errore o timeout, altrimenti
271  *         il carattere ricevuto.
272  */
273 int ser_getchar(struct Serial *port)
274 {
275         if (fifo_isempty_locked(&port->rxfifo))
276         {
277 #if CONFIG_SER_RXTIMEOUT != -1
278                 ticks_t start_time = timer_clock();
279 #endif
280                 /* Wait while buffer is empty */
281                 do
282                 {
283                         wdt_reset();
284 #if CONFIG_KERNEL && CONFIG_KERN_SCHED
285                         /* Give up timeslice to other processes. */
286                         proc_switch();
287 #endif
288 #if CONFIG_SER_RXTIMEOUT != -1
289                         if (timer_clock() - start_time >= port->rxtimeout)
290                         {
291                                 ATOMIC(port->status |= SERRF_RXTIMEOUT);
292                                 return EOF;
293                         }
294 #endif /* CONFIG_SER_RXTIMEOUT */
295                 }
296                 while (fifo_isempty_locked(&port->rxfifo) && (ser_getstatus(port) & SERRF_RX) == 0);
297         }
298
299         /*
300          * Get a byte from the FIFO (avoiding sign-extension),
301          * re-enable RTS, then return result.
302          */
303         if (ser_getstatus(port) & SERRF_RX)
304                 return EOF;
305         return (int)(unsigned char)fifo_pop_locked(&port->rxfifo);
306 }
307
308
309 /**
310  * Preleva un carattere dal buffer di ricezione.
311  * Se il buffer e' vuoto, ser_getchar_nowait() ritorna
312  * immediatamente EOF.
313  */
314 int ser_getchar_nowait(struct Serial *port)
315 {
316         if (fifo_isempty_locked(&port->rxfifo))
317                 return EOF;
318
319         /* NOTE: the double cast prevents unwanted sign extension */
320         return (int)(unsigned char)fifo_pop_locked(&port->rxfifo);
321 }
322
323
324 #if CONFIG_SER_GETS
325 /**
326  * Read a line long at most as size and put it
327  * in buf.
328  * \return number of chars read or EOF in case
329  *         of error.
330  */
331 int ser_gets(struct Serial *port, char *buf, int size)
332 {
333         return ser_gets_echo(port, buf, size, false);
334 }
335
336
337 /**
338  * Read a line long at most as size and put it
339  * in buf, with optional echo.
340  *
341  * \return number of chars read, or EOF in case
342  *         of error.
343  */
344 int ser_gets_echo(struct Serial *port, char *buf, int size, bool echo)
345 {
346         int i = 0;
347         int c;
348
349         for (;;)
350         {
351                 if ((c = ser_getchar(port)) == EOF)
352                 {
353                         buf[i] = '\0';
354                         return -1;
355                 }
356
357                 /* FIXME */
358                 if (c == '\r' || c == '\n' || i >= size-1)
359                 {
360                         buf[i] = '\0';
361                         if (echo)
362                                 ser_print(port, "\r\n");
363                         break;
364                 }
365                 buf[i++] = c;
366                 if (echo)
367                         ser_putchar(c, port);
368         }
369
370         return i;
371 }
372 #endif /* !CONFIG_SER_GETS */
373
374
375 /**
376  * Read at most \a size bytes from \a port and put them in \a buf
377  *
378  * \return number of bytes actually read, or EOF in
379  *         case of error.
380  */
381 int ser_read(struct Serial *port, void *buf, size_t size)
382 {
383         size_t i = 0;
384         char *_buf = (char *)buf;
385         int c;
386
387         while (i < size)
388         {
389                 if ((c = ser_getchar(port)) == EOF)
390                         return EOF;
391                 _buf[i++] = c;
392         }
393
394         return i;
395 }
396
397
398 /**
399  * Write a string to serial.
400  * \return 0 if OK, EOF in case of error.
401  */
402 int ser_print(struct Serial *port, const char *s)
403 {
404         while (*s)
405         {
406                 if (ser_putchar(*s++, port) == EOF)
407                         return EOF;
408         }
409         return 0;
410 }
411
412
413 /**
414  * \brief Write a buffer to serial.
415  *
416  * \return 0 if OK, EOF in case of error.
417  *
418  * \todo Optimize with fifo_pushblock()
419  */
420 int ser_write(struct Serial *port, const void *_buf, size_t len)
421 {
422         const char *buf = (const char *)_buf;
423
424         while (len--)
425         {
426                 if (ser_putchar(*buf++, port) == EOF)
427                         return EOF;
428         }
429         return 0;
430 }
431
432
433 #if CONFIG_PRINTF
434 /**
435  * Formatted write
436  */
437 int ser_printf(struct Serial *port, const char *format, ...)
438 {
439         va_list ap;
440         int len;
441
442         va_start(ap, format);
443         len = _formatted_write(format, (void (*)(char, void *))ser_putchar, port, ap);
444         va_end(ap);
445
446         return len;
447 }
448 #endif /* CONFIG_PRINTF */
449
450
451 #if CONFIG_SER_RXTIMEOUT != -1 || CONFIG_SER_TXTIMEOUT != -1
452 void ser_settimeouts(struct Serial *port, mtime_t rxtimeout, mtime_t txtimeout)
453 {
454         port->rxtimeout = ms_to_ticks(rxtimeout);
455         port->txtimeout = ms_to_ticks(txtimeout);
456 }
457 #endif /* CONFIG_SER_RXTIMEOUT || CONFIG_SER_TXTIMEOUT */
458
459 #if CONFIG_SER_RXTIMEOUT != -1
460 /**
461  * Discard input to resynchronize with remote end.
462  *
463  * Discard incoming data until the port stops receiving
464  * characters for at least \a delay milliseconds.
465  *
466  * \note Serial errors are reset before and after executing the purge.
467  */
468 void ser_resync(struct Serial *port, mtime_t delay)
469 {
470         mtime_t old_rxtimeout = ticks_to_ms(port->rxtimeout);
471
472         ser_settimeouts(port, delay, ticks_to_ms(port->txtimeout));
473         do
474         {
475                 ser_setstatus(port, 0);
476                 ser_getchar(port);
477         }
478         while (!(ser_getstatus(port) & SERRF_RXTIMEOUT));
479
480         /* Restore port to an usable status */
481         ser_setstatus(port, 0);
482         ser_settimeouts(port, old_rxtimeout, ticks_to_ms(port->txtimeout));
483 }
484 #endif /* CONFIG_SER_RXTIMEOUT */
485
486
487 void ser_setbaudrate(struct Serial *port, unsigned long rate)
488 {
489         port->hw->table->setBaudrate(port->hw, rate);
490 }
491
492
493 void ser_setparity(struct Serial *port, int parity)
494 {
495         port->hw->table->setParity(port->hw, parity);
496 }
497
498
499 /**
500  * Flush both the RX and TX buffers.
501  */
502 void ser_purge(struct Serial *port)
503 {
504         fifo_flush_locked(&port->rxfifo);
505         fifo_flush_locked(&port->txfifo);
506 }
507
508
509 /**
510  * Wait until all pending output is completely
511  * transmitted to the other end.
512  *
513  * \note The current implementation only checks the
514  *       software transmission queue. Any hardware
515  *       FIFOs are ignored.
516  */
517 void ser_drain(struct Serial *ser)
518 {
519         /*
520          * Wait until the FIFO becomes empty, and then until the byte currently in
521          * the hardware register gets shifted out.
522          */
523         while (!fifo_isempty(&ser->txfifo)
524                || ser->hw->table->txSending(ser->hw))
525         {
526                 #if CONFIG_KERNEL && CONFIG_KERN_SCHED
527                         /* Give up timeslice to other processes. */
528                         proc_switch();
529                 #endif
530                         wdt_reset();
531         }
532 }
533
534
535 /**
536  * Initialize a serial port.
537  *
538  * \param unit  Serial unit to open. Possible values are architecture dependant.
539  */
540 struct Serial *ser_open(unsigned int unit)
541 {
542         struct Serial *port;
543
544         ASSERT(unit < countof(ser_handles));
545         port = &ser_handles[unit];
546
547         ASSERT(!port->is_open);
548         DB(port->is_open = true;)
549
550         port->unit = unit;
551
552         port->hw = ser_hw_getdesc(unit);
553
554         /* Initialize circular buffers */
555         ASSERT(port->hw->txbuffer);
556         ASSERT(port->hw->rxbuffer);
557         fifo_init(&port->txfifo, port->hw->txbuffer, port->hw->txbuffer_size);
558         fifo_init(&port->rxfifo, port->hw->rxbuffer, port->hw->rxbuffer_size);
559
560         port->hw->table->init(port->hw, port);
561
562         /* Set default values */
563 #if CONFIG_SER_RXTIMEOUT != -1 || CONFIG_SER_TXTIMEOUT != -1
564         ser_settimeouts(port, CONFIG_SER_RXTIMEOUT, CONFIG_SER_TXTIMEOUT);
565 #endif
566 #if CONFIG_SER_DEFBAUDRATE
567         ser_setbaudrate(port, CONFIG_SER_DEFBAUDRATE);
568 #endif
569
570         /* Clear error flags */
571         ser_setstatus(port, 0);
572
573         return port;
574 }
575
576
577 /**
578  * Clean up serial port, disabling the associated hardware.
579  */
580 void ser_close(struct Serial *port)
581 {
582         ASSERT(port->is_open);
583         DB(port->is_open = false;)
584
585         // Wait until we finish sending everything
586         ser_drain(port);
587
588         port->hw->table->cleanup(port->hw);
589         DB(port->hw = NULL;)
590
591         /*
592          * We purge the FIFO buffer only after the low-level cleanup, so that
593          * we are sure that there are no more interrupts.
594          */
595         ser_purge(port);
596 }