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