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