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