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