4 * This file is part of BeRTOS.
6 * Bertos is free software; you can redistribute it and/or modify
7 * it under the terms of the GNU General Public License as published by
8 * the Free Software Foundation; either version 2 of the License, or
9 * (at your option) any later version.
11 * This program is distributed in the hope that it will be useful,
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 * GNU General Public License for more details.
16 * You should have received a copy of the GNU General Public License
17 * along with this program; if not, write to the Free Software
18 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
20 * As a special exception, you may use this file as part of a free software
21 * library without restriction. Specifically, if other files instantiate
22 * templates or use macros or inline functions from this file, or you compile
23 * this file and link it with other files to produce an executable, this
24 * file does not by itself cause the resulting executable to be covered by
25 * the GNU General Public License. This exception does not however
26 * invalidate any other reasons why the executable file might be covered by
27 * the GNU General Public License.
29 * Copyright 2003, 2004, 2006 Develer S.r.l. (http://www.develer.com/)
30 * Copyright 2000 Bernardo Innocenti <bernie@codewiz.org>
34 * \brief Buffered serial I/O driver
36 * The serial rx interrupt buffers incoming data in a software FIFO
37 * to decouple the higher level protocols from the line speed.
38 * Outgoing data is buffered as well for better performance.
39 * This driver is not optimized for best performance, but it
40 * has proved to be fast enough to handle transfer rates up to
41 * 38400bps on a 16MHz 80196.
43 * MODULE CONFIGURATION
45 * \li \c CONFIG_SER_HWHANDSHAKE - set to 1 to enable RTS/CTS handshake.
46 * Support is incomplete/untested.
47 * \li \c CONFIG_SER_TXTIMEOUT - Enable software serial transmission timeouts
51 * \author Bernardo Innocenti <bernie@develer.com>
56 *#* Revision 1.38 2007/06/21 17:07:21 batt
57 *#* Remove CONFIG_WATCHDOG stuff: watchdog macros expand to nothing when wdt is active.
59 *#* Revision 1.37 2007/06/07 14:35:12 batt
60 *#* Merge from project_ks.
62 *#* Revision 1.36 2007/01/29 11:30:29 batt
63 *#* Reimplement ser_clearstatus as a macro.
65 *#* Revision 1.35 2007/01/27 20:47:12 batt
68 *#* Revision 1.34 2006/11/20 15:07:40 batt
69 *#* Revert unneeded locked functions.
71 *#* Revision 1.33 2006/11/17 18:15:55 batt
72 *#* Avoid race conditions.
74 *#* Revision 1.32 2006/11/17 17:03:58 batt
75 *#* Implement ser_setstatus and ser_getstatus as functions to avoid race conditions.
77 *#* Revision 1.31 2006/07/21 10:58:00 batt
78 *#* Use timer_clock() instead of obsolete timer_ticks().
80 *#* Revision 1.30 2006/07/19 12:56:26 bernie
81 *#* Convert to new Doxygen style.
83 *#* Revision 1.29 2006/05/18 00:39:30 bernie
84 *#* ser_open(): Document a bit more.
86 *#* Revision 1.28 2006/02/17 22:23:06 bernie
87 *#* Update POSIX serial emulator.
89 *#* Revision 1.27 2005/11/27 23:33:40 bernie
90 *#* Use appconfig.h instead of cfg/config.h.
92 *#* Revision 1.26 2005/11/04 16:20:02 bernie
93 *#* Fix reference to README.devlib in header.
95 *#* Revision 1.25 2005/04/11 19:10:27 bernie
96 *#* Include top-level headers from cfg/ subdir.
98 *#* Revision 1.24 2005/01/21 20:13:15 aleph
99 *#* Fix drain at ser_close()
101 *#* Revision 1.23 2005/01/14 00:47:07 aleph
102 *#* ser_drain(): Wait for hw transmission complete.
104 *#* Revision 1.22 2004/12/08 08:56:14 bernie
105 *#* Rename time_t to mtime_t.
107 *#* Revision 1.21 2004/11/16 18:10:13 bernie
108 *#* Add sanity checks for missing configuration parameters.
110 *#* Revision 1.20 2004/10/19 11:48:00 bernie
111 *#* Remove unused variable.
113 *#* Revision 1.19 2004/10/19 08:14:13 bernie
114 *#* Fix a few longstanding bugs wrt status handling (made by rasky on scfirm).
116 *#* Revision 1.18 2004/09/20 03:31:15 bernie
117 *#* Sanitize for C++.
119 *#* Revision 1.17 2004/09/14 21:06:07 bernie
120 *#* Use debug.h instead of kdebug.h; Spelling fixes.
122 *#* Revision 1.16 2004/09/06 21:40:50 bernie
123 *#* Move buffer handling in chip-specific driver.
125 *#* Revision 1.15 2004/08/25 14:12:08 rasky
126 *#* Aggiornato il comment block dei log RCS
128 *#* Revision 1.14 2004/08/24 16:22:57 bernie
129 *#* Thinkos; Doxygen fixes
131 *#* Revision 1.13 2004/08/24 16:20:48 bernie
132 *#* ser_read(): Make buffer argument void *#* for consistency with ANSI C and ser_write()
134 *#* Revision 1.12 2004/08/24 13:49:39 bernie
137 *#* Revision 1.11 2004/08/15 05:32:22 bernie
138 *#* ser_resync(): New function.
140 *#* Revision 1.10 2004/08/10 06:29:50 bernie
141 *#* Rename timer_gettick() to timer_ticks().
143 *#* Revision 1.9 2004/08/08 06:06:20 bernie
144 *#* Use new-style CONFIG_ idiom; Fix module-wide documentation.
146 *#* Revision 1.8 2004/07/29 22:57:09 bernie
147 *#* ser_drain(): New function; Make Serial::is_open a debug-only feature; Switch to new-style CONFIG_* macros.
149 *#* Revision 1.7 2004/07/18 21:49:03 bernie
150 *#* Make CONFIG_SER_DEFBAUDRATE optional.
152 *#* Revision 1.6 2004/06/07 15:56:28 aleph
153 *#* Remove cast-as-lvalue extension abuse
155 *#* Revision 1.5 2004/06/06 16:41:44 bernie
156 *#* ser_putchar(): Use fifo_push_locked() to fix potential race on 8bit processors.
158 *#* Revision 1.4 2004/06/03 11:27:09 bernie
159 *#* Add dual-license information.
161 *#* Revision 1.3 2004/06/02 21:35:24 aleph
162 *#* Serial enhancements: interruptible receive handler and 8 bit serial status for AVR; remove volatile attribute to FIFOBuffer, useless for new fifobuf routens
164 *#* Revision 1.2 2004/05/23 18:21:53 bernie
165 *#* Trim CVS logs and cleanup header info.
174 #include <mware/formatwr.h>
175 #include <cfg/debug.h>
176 #include <appconfig.h>
179 * Sanity check for config parameters required by this module.
181 #if !defined(CONFIG_KERNEL) || ((CONFIG_KERNEL != 0) && CONFIG_KERNEL != 1)
182 #error CONFIG_KERNEL must be set to either 0 or 1 in config.h
184 #if !defined(CONFIG_SER_RXTIMEOUT)
185 #error CONFIG_SER_TXTIMEOUT missing in config.h
187 #if !defined(CONFIG_SER_RXTIMEOUT)
188 #error CONFIG_SER_RXTIMEOUT missing in config.h
190 #if !defined(CONFIG_SER_GETS) || ((CONFIG_SER_GETS != 0) && CONFIG_SER_GETS != 1)
191 #error CONFIG_SER_GETS must be set to either 0 or 1 in config.h
193 #if !defined(CONFIG_SER_DEFBAUDRATE)
194 #error CONFIG_SER_DEFBAUDRATE missing in config.h
196 #if !defined(CONFIG_PRINTF)
197 #error CONFIG_PRINTF missing in config.h
201 #include <kern/proc.h>
204 #if CONFIG_SER_TXTIMEOUT != -1 || CONFIG_SER_RXTIMEOUT != -1
205 #include <drv/timer.h>
209 /* Serial configuration parameters */
210 #define SER_CTSDELAY 70 /**< CTS line retry interval (ms) */
211 #define SER_TXPOLLDELAY 2 /**< Transmit buffer full retry interval (ms) */
212 #define SER_RXPOLLDELAY 2 /**< Receive buffer empty retry interval (ms) */
215 struct Serial ser_handles[SER_CNT];
219 * Inserisce il carattere c nel buffer di trasmissione.
220 * Questa funzione mette il processo chiamante in attesa
221 * quando il buffer e' pieno.
223 * \return EOF in caso di errore o timeout, altrimenti
224 * il carattere inviato.
226 int ser_putchar(int c, struct Serial *port)
228 //ASSERT_VALID_FIFO(&port->txfifo);
229 if (fifo_isfull_locked(&port->txfifo))
231 #if CONFIG_SER_TXTIMEOUT != -1
232 ticks_t start_time = timer_clock();
235 /* Attende finche' il buffer e' pieno... */
239 #if CONFIG_KERNEL && CONFIG_KERN_SCHED
240 /* Give up timeslice to other processes. */
243 #if CONFIG_SER_TXTIMEOUT != -1
244 if (timer_clock() - start_time >= port->txtimeout)
246 ATOMIC(port->status |= SERRF_TXTIMEOUT);
249 #endif /* CONFIG_SER_TXTIMEOUT */
251 while (fifo_isfull_locked(&port->txfifo));
254 fifo_push_locked(&port->txfifo, (unsigned char)c);
256 /* (re)trigger tx interrupt */
257 port->hw->table->txStart(port->hw);
259 /* Avoid returning signed extended char */
260 return (int)((unsigned char)c);
265 * Preleva un carattere dal buffer di ricezione.
266 * Questa funzione mette il processo chiamante in attesa
267 * quando il buffer e' vuoto. L'attesa ha un timeout
268 * di ser_rxtimeout millisecondi.
270 * \return EOF in caso di errore o timeout, altrimenti
271 * il carattere ricevuto.
273 int ser_getchar(struct Serial *port)
275 if (fifo_isempty_locked(&port->rxfifo))
277 #if CONFIG_SER_RXTIMEOUT != -1
278 ticks_t start_time = timer_clock();
280 /* Wait while buffer is empty */
284 #if CONFIG_KERNEL && CONFIG_KERN_SCHED
285 /* Give up timeslice to other processes. */
288 #if CONFIG_SER_RXTIMEOUT != -1
289 if (timer_clock() - start_time >= port->rxtimeout)
291 ATOMIC(port->status |= SERRF_RXTIMEOUT);
294 #endif /* CONFIG_SER_RXTIMEOUT */
296 while (fifo_isempty_locked(&port->rxfifo) && (ser_getstatus(port) & SERRF_RX) == 0);
300 * Get a byte from the FIFO (avoiding sign-extension),
301 * re-enable RTS, then return result.
303 if (ser_getstatus(port) & SERRF_RX)
305 return (int)(unsigned char)fifo_pop_locked(&port->rxfifo);
310 * Preleva un carattere dal buffer di ricezione.
311 * Se il buffer e' vuoto, ser_getchar_nowait() ritorna
312 * immediatamente EOF.
314 int ser_getchar_nowait(struct Serial *port)
316 if (fifo_isempty_locked(&port->rxfifo))
319 /* NOTE: the double cast prevents unwanted sign extension */
320 return (int)(unsigned char)fifo_pop_locked(&port->rxfifo);
326 * Read a line long at most as size and put it
328 * \return number of chars read or EOF in case
331 int ser_gets(struct Serial *port, char *buf, int size)
333 return ser_gets_echo(port, buf, size, false);
338 * Read a line long at most as size and put it
339 * in buf, with optional echo.
341 * \return number of chars read, or EOF in case
344 int ser_gets_echo(struct Serial *port, char *buf, int size, bool echo)
351 if ((c = ser_getchar(port)) == EOF)
358 if (c == '\r' || c == '\n' || i >= size-1)
362 ser_print(port, "\r\n");
367 ser_putchar(c, port);
372 #endif /* !CONFIG_SER_GETS */
376 * Read at most \a size bytes from \a port and put them in \a buf
378 * \return number of bytes actually read, or EOF in
381 int ser_read(struct Serial *port, void *buf, size_t size)
384 char *_buf = (char *)buf;
389 if ((c = ser_getchar(port)) == EOF)
399 * Write a string to serial.
400 * \return 0 if OK, EOF in case of error.
402 int ser_print(struct Serial *port, const char *s)
406 if (ser_putchar(*s++, port) == EOF)
414 * \brief Write a buffer to serial.
416 * \return 0 if OK, EOF in case of error.
418 * \todo Optimize with fifo_pushblock()
420 int ser_write(struct Serial *port, const void *_buf, size_t len)
422 const char *buf = (const char *)_buf;
426 if (ser_putchar(*buf++, port) == EOF)
437 int ser_printf(struct Serial *port, const char *format, ...)
442 va_start(ap, format);
443 len = _formatted_write(format, (void (*)(char, void *))ser_putchar, port, ap);
448 #endif /* CONFIG_PRINTF */
451 #if CONFIG_SER_RXTIMEOUT != -1 || CONFIG_SER_TXTIMEOUT != -1
452 void ser_settimeouts(struct Serial *port, mtime_t rxtimeout, mtime_t txtimeout)
454 port->rxtimeout = ms_to_ticks(rxtimeout);
455 port->txtimeout = ms_to_ticks(txtimeout);
457 #endif /* CONFIG_SER_RXTIMEOUT || CONFIG_SER_TXTIMEOUT */
459 #if CONFIG_SER_RXTIMEOUT != -1
461 * Discard input to resynchronize with remote end.
463 * Discard incoming data until the port stops receiving
464 * characters for at least \a delay milliseconds.
466 * \note Serial errors are reset before and after executing the purge.
468 void ser_resync(struct Serial *port, mtime_t delay)
470 mtime_t old_rxtimeout = ticks_to_ms(port->rxtimeout);
472 ser_settimeouts(port, delay, ticks_to_ms(port->txtimeout));
475 ser_setstatus(port, 0);
478 while (!(ser_getstatus(port) & SERRF_RXTIMEOUT));
480 /* Restore port to an usable status */
481 ser_setstatus(port, 0);
482 ser_settimeouts(port, old_rxtimeout, ticks_to_ms(port->txtimeout));
484 #endif /* CONFIG_SER_RXTIMEOUT */
487 void ser_setbaudrate(struct Serial *port, unsigned long rate)
489 port->hw->table->setBaudrate(port->hw, rate);
493 void ser_setparity(struct Serial *port, int parity)
495 port->hw->table->setParity(port->hw, parity);
500 * Flush both the RX and TX buffers.
502 void ser_purge(struct Serial *port)
504 fifo_flush_locked(&port->rxfifo);
505 fifo_flush_locked(&port->txfifo);
510 * Wait until all pending output is completely
511 * transmitted to the other end.
513 * \note The current implementation only checks the
514 * software transmission queue. Any hardware
517 void ser_drain(struct Serial *ser)
520 * Wait until the FIFO becomes empty, and then until the byte currently in
521 * the hardware register gets shifted out.
523 while (!fifo_isempty(&ser->txfifo)
524 || ser->hw->table->txSending(ser->hw))
526 #if CONFIG_KERNEL && CONFIG_KERN_SCHED
527 /* Give up timeslice to other processes. */
536 * Initialize a serial port.
538 * \param unit Serial unit to open. Possible values are architecture dependant.
540 struct Serial *ser_open(unsigned int unit)
544 ASSERT(unit < countof(ser_handles));
545 port = &ser_handles[unit];
547 ASSERT(!port->is_open);
548 DB(port->is_open = true;)
552 port->hw = ser_hw_getdesc(unit);
554 /* Initialize circular buffers */
555 ASSERT(port->hw->txbuffer);
556 ASSERT(port->hw->rxbuffer);
557 fifo_init(&port->txfifo, port->hw->txbuffer, port->hw->txbuffer_size);
558 fifo_init(&port->rxfifo, port->hw->rxbuffer, port->hw->rxbuffer_size);
560 port->hw->table->init(port->hw, port);
562 /* Set default values */
563 #if CONFIG_SER_RXTIMEOUT != -1 || CONFIG_SER_TXTIMEOUT != -1
564 ser_settimeouts(port, CONFIG_SER_RXTIMEOUT, CONFIG_SER_TXTIMEOUT);
566 #if CONFIG_SER_DEFBAUDRATE
567 ser_setbaudrate(port, CONFIG_SER_DEFBAUDRATE);
570 /* Clear error flags */
571 ser_setstatus(port, 0);
578 * Clean up serial port, disabling the associated hardware.
580 void ser_close(struct Serial *port)
582 ASSERT(port->is_open);
583 DB(port->is_open = false;)
585 // Wait until we finish sending everything
588 port->hw->table->cleanup(port->hw);
592 * We purge the FIFO buffer only after the low-level cleanup, so that
593 * we are sure that there are no more interrupts.