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