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