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