proc_yield(): Rename from proc_switch()
[bertos.git] / bertos / drv / ser.c
1 /**
2  * \file
3  * <!--
4  * This file is part of BeRTOS.
5  *
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.
10  *
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.
15  *
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
19  *
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.
28  *
29  * Copyright 2003, 2004, 2006 Develer S.r.l. (http://www.develer.com/)
30  * Copyright 2000 Bernie Innocenti <bernie@codewiz.org>
31  * -->
32  *
33  * \brief Buffered serial I/O driver
34  *
35  * The serial rx interrupt buffers incoming data in a software FIFO
36  * to decouple the higher level protocols from the line speed.
37  * Outgoing data is buffered as well for better performance.
38  * This driver is not optimized for best performance, but it
39  * has proved to be fast enough to handle transfer rates up to
40  * 38400bps on a 16MHz 80196.
41  *
42  * MODULE CONFIGURATION
43  *
44  *  \li \c CONFIG_SER_HWHANDSHAKE - set to 1 to enable RTS/CTS handshake.
45  *         Support is incomplete/untested.
46  *  \li \c CONFIG_SER_TXTIMEOUT - Enable software serial transmission timeouts
47  *
48  *
49  * \version $Id$
50  * \author Bernie Innocenti <bernie@codewiz.org>
51  */
52
53 #include "ser.h"
54 #include "wdt.h"
55 #include "ser_p.h"
56
57 #include "cfg/cfg_ser.h"
58 #include "cfg/cfg_kern.h"
59 #include <cfg/debug.h>
60
61 #include <mware/formatwr.h>
62
63 #include <string.h> /* memset */
64
65 /*
66  * Sanity check for config parameters required by this module.
67  */
68 #if !defined(CONFIG_KERNEL) || ((CONFIG_KERNEL != 0) && CONFIG_KERNEL != 1)
69         #error CONFIG_KERNEL must be set to either 0 or 1 in config.h
70 #endif
71 #if !defined(CONFIG_SER_RXTIMEOUT)
72         #error CONFIG_SER_TXTIMEOUT missing in config.h
73 #endif
74 #if !defined(CONFIG_SER_RXTIMEOUT)
75         #error CONFIG_SER_RXTIMEOUT missing in config.h
76 #endif
77 #if !defined(CONFIG_SER_DEFBAUDRATE)
78         #error CONFIG_SER_DEFBAUDRATE missing in config.h
79 #endif
80
81 #if CONFIG_KERNEL && CONFIG_KERN_SCHED
82         #include <kern/proc.h>
83 #else
84         #define proc_yield() do {} while(0)
85 #endif
86
87 #if CONFIG_SER_TXTIMEOUT != -1 || CONFIG_SER_RXTIMEOUT != -1
88         #include <drv/timer.h>
89 #endif
90
91
92 struct Serial *ser_handles[SER_CNT];
93
94 /**
95  * Insert \a c in tx FIFO buffer.
96  * \note This function will switch out the calling process
97  * if the tx buffer is full. If the buffer is full
98  * and \a port->txtimeout is 0 return EOF immediatly.
99  *
100  * \return EOF on error or timeout, \a c otherwise.
101  */
102 static int ser_putchar(int c, struct Serial *port)
103 {
104         if (fifo_isfull_locked(&port->txfifo))
105         {
106 #if CONFIG_SER_TXTIMEOUT != -1
107                 /* If timeout == 0 we don't want to wait */
108                 if (port->txtimeout == 0)
109                         return EOF;
110
111                 ticks_t start_time = timer_clock();
112 #endif
113
114                 /* Wait while buffer is full... */
115                 do
116                 {
117                         /* Give up timeslice to other processes. */
118                         proc_yield();
119                         wdt_reset();
120
121 #if CONFIG_SER_TXTIMEOUT != -1
122                         if (timer_clock() - start_time >= port->txtimeout)
123                         {
124                                 ATOMIC(port->status |= SERRF_TXTIMEOUT);
125                                 return EOF;
126                         }
127 #endif /* CONFIG_SER_TXTIMEOUT */
128                 }
129                 while (fifo_isfull_locked(&port->txfifo));
130         }
131
132         fifo_push_locked(&port->txfifo, (unsigned char)c);
133
134         /* (re)trigger tx interrupt */
135         port->hw->table->txStart(port->hw);
136
137         /* Avoid returning signed extended char */
138         return (int)((unsigned char)c);
139 }
140
141
142 /**
143  * Fetch a character from the rx FIFO buffer.
144  * \note This function will switch out the calling process
145  * if the rx buffer is empty. If the buffer is empty
146  * and \a port->rxtimeout is 0 return EOF immediatly.
147  *
148  * \return EOF on error or timeout, \a c otherwise.
149  */
150 static int ser_getchar(struct Serial *port)
151 {
152         if (fifo_isempty_locked(&port->rxfifo))
153         {
154 #if CONFIG_SER_RXTIMEOUT != -1
155                 /* If timeout == 0 we don't want to wait for chars */
156                 if (port->rxtimeout == 0)
157                         return EOF;
158
159                 ticks_t start_time = timer_clock();
160 #endif
161
162                 /* Wait while buffer is empty */
163                 do
164                 {
165                         /* Give up timeslice to other processes. */
166                         proc_yield();
167                         wdt_reset();
168
169 #if CONFIG_SER_RXTIMEOUT != -1
170                         if (timer_clock() - start_time >= port->rxtimeout)
171                         {
172                                 ATOMIC(port->status |= SERRF_RXTIMEOUT);
173                                 return EOF;
174                         }
175 #endif /* CONFIG_SER_RXTIMEOUT */
176                 }
177                 while (fifo_isempty_locked(&port->rxfifo) && (ser_getstatus(port) & SERRF_RX) == 0);
178         }
179
180         /*
181          * Get a byte from the FIFO (avoiding sign-extension),
182          * re-enable RTS, then return result.
183          */
184         if (ser_getstatus(port) & SERRF_RX)
185                 return EOF;
186         return (int)(unsigned char)fifo_pop_locked(&port->rxfifo);
187 }
188
189 /**
190  * Fetch a character from the rx FIFO buffer.
191  * If the buffer is empty, ser_getchar_nowait() returns
192  * EOF immediatly.
193  * \note Deprecated, use ser_getchar with rx_timeout set to 0.
194  */
195 int ser_getchar_nowait(struct Serial *fd)
196 {
197         if (fifo_isempty_locked(&fd->rxfifo))
198                 return EOF;
199
200         /* NOTE: the double cast prevents unwanted sign extension */
201         return (int)(unsigned char)fifo_pop_locked(&fd->rxfifo);
202 }
203
204
205
206 /**
207  * Read at most \a size bytes from \a port and put them in \a buf
208  *
209  * \return number of bytes actually read.
210  */
211 static size_t ser_read(struct KFile *fd, void *_buf, size_t size)
212 {
213         Serial *fds = SERIAL_CAST(fd);
214
215         size_t i = 0;
216         char *buf = (char *)_buf;
217         int c;
218
219         while (i < size)
220         {
221                 if ((c = ser_getchar(fds)) == EOF)
222                         break;
223                 buf[i++] = c;
224         }
225
226         return i;
227 }
228
229 /**
230  * \brief Write a buffer to serial.
231  *
232  * \return 0 if OK, EOF in case of error.
233  *
234  * \todo Optimize with fifo_pushblock()
235  */
236 static size_t ser_write(struct KFile *fd, const void *_buf, size_t size)
237 {
238         Serial *fds = SERIAL_CAST(fd);
239         const char *buf = (const char *)_buf;
240         size_t i = 0;
241
242         while (size--)
243         {
244                 if (ser_putchar(*buf++, fds) == EOF)
245                         break;
246                 i++;
247         }
248         return i;
249 }
250
251
252 #if CONFIG_SER_RXTIMEOUT != -1 || CONFIG_SER_TXTIMEOUT != -1
253 void ser_settimeouts(struct Serial *fd, mtime_t rxtimeout, mtime_t txtimeout)
254 {
255         fd->rxtimeout = ms_to_ticks(rxtimeout);
256         fd->txtimeout = ms_to_ticks(txtimeout);
257 }
258 #endif /* CONFIG_SER_RXTIMEOUT || CONFIG_SER_TXTIMEOUT */
259
260 #if CONFIG_SER_RXTIMEOUT != -1
261 /**
262  * Discard input to resynchronize with remote end.
263  *
264  * Discard incoming data until the port stops receiving
265  * characters for at least \a delay milliseconds.
266  *
267  * \note Serial errors are reset before and after executing the purge.
268  */
269 void ser_resync(struct Serial *fd, mtime_t delay)
270 {
271         mtime_t old_rxtimeout = ticks_to_ms(fd->rxtimeout);
272
273         ser_settimeouts(fd, delay, ticks_to_ms(fd->txtimeout));
274         do
275         {
276                 ser_setstatus(fd, 0);
277                 ser_getchar(fd);
278         }
279         while (!(ser_getstatus(fd) & SERRF_RXTIMEOUT));
280
281         /* Restore port to an usable status */
282         ser_setstatus(fd, 0);
283         ser_settimeouts(fd, old_rxtimeout, ticks_to_ms(fd->txtimeout));
284 }
285 #endif /* CONFIG_SER_RXTIMEOUT */
286
287
288 void ser_setbaudrate(struct Serial *fd, unsigned long rate)
289 {
290         fd->hw->table->setBaudrate(fd->hw, rate);
291 }
292
293
294 void ser_setparity(struct Serial *fd, int parity)
295 {
296         fd->hw->table->setParity(fd->hw, parity);
297 }
298
299 static int ser_error(struct KFile *fd)
300 {
301         Serial *fds = SERIAL_CAST(fd);
302         return ser_getstatus(fds);
303 }
304
305 static void ser_clearerr(struct KFile *fd)
306 {
307         Serial *fds = SERIAL_CAST(fd);
308         ser_setstatus(fds, 0);
309 }
310
311
312
313 /**
314  * Flush both the RX and TX buffers.
315  */
316 void ser_purge(struct Serial *fd)
317 {
318         ser_purgeRx(fd);
319         ser_purgeTx(fd);
320 }
321
322 /**
323  * Flush RX buffer.
324  */
325 void ser_purgeRx(struct Serial *fd)
326 {
327         fifo_flush_locked(&fd->rxfifo);
328 }
329
330 /**
331  * Flush TX buffer.
332  */
333 void ser_purgeTx(struct Serial *fd)
334 {
335         fifo_flush_locked(&fd->txfifo);
336 }
337
338
339 /**
340  * Wait until all pending output is completely
341  * transmitted to the other end.
342  *
343  * \note The current implementation only checks the
344  *       software transmission queue. Any hardware
345  *       FIFOs are ignored.
346  */
347 static int ser_flush(struct KFile *fd)
348 {
349         Serial *fds = SERIAL_CAST(fd);
350
351         /*
352          * Wait until the FIFO becomes empty, and then until the byte currently in
353          * the hardware register gets shifted out.
354          */
355         while (!fifo_isempty(&fds->txfifo)
356                || fds->hw->table->txSending(fds->hw))
357         {
358                         /* Give up timeslice to other processes. */
359                         proc_yield();
360                         wdt_reset();
361         }
362         return 0;
363 }
364
365
366 /**
367  * Initialize a serial port.
368  *
369  * \param fd KFile Serial struct interface.
370  * \param unit  Serial unit to open. Possible values are architecture dependant.
371  */
372 static struct Serial *ser_open(struct Serial *fd, unsigned int unit)
373 {
374         ASSERT(unit < countof(ser_handles));
375
376         ser_handles[unit] = fd;
377         ASSERT(!fd->is_open);
378         DB(fd->is_open = true);
379
380         fd->unit = unit;
381
382         fd->hw = ser_hw_getdesc(unit);
383
384         /* Initialize circular buffers */
385         ASSERT(fd->hw->txbuffer);
386         ASSERT(fd->hw->rxbuffer);
387         fifo_init(&fd->txfifo, fd->hw->txbuffer, fd->hw->txbuffer_size);
388         fifo_init(&fd->rxfifo, fd->hw->rxbuffer, fd->hw->rxbuffer_size);
389
390         fd->hw->table->init(fd->hw, fd);
391
392         /* Set default values */
393 #if CONFIG_SER_RXTIMEOUT != -1 || CONFIG_SER_TXTIMEOUT != -1
394         ser_settimeouts(fd, CONFIG_SER_RXTIMEOUT, CONFIG_SER_TXTIMEOUT);
395 #endif
396 #if CONFIG_SER_DEFBAUDRATE
397         ser_setbaudrate(fd, CONFIG_SER_DEFBAUDRATE);
398 #endif
399
400         /* Clear error flags */
401         ser_setstatus(fd, 0);
402
403         return fd;
404 }
405
406
407 /**
408  * Clean up serial port, disabling the associated hardware.
409  */
410 static int ser_close(struct KFile *fd)
411 {
412         Serial *fds = SERIAL_CAST(fd);
413         Serial *port = fds;
414
415         ASSERT(port->is_open);
416         DB(port->is_open = false);
417
418         // Wait until we finish sending everything
419         ser_flush(fd);
420
421         port->hw->table->cleanup(port->hw);
422         DB(port->hw = NULL);
423
424         /*
425          * We purge the FIFO buffer only after the low-level cleanup, so that
426          * we are sure that there are no more interrupts.
427          */
428         ser_purge(fds);
429         return 0;
430 }
431
432 /**
433  * Reopen serial port.
434  */
435 static struct KFile *ser_reopen(struct KFile *fd)
436 {
437         Serial *fds = SERIAL_CAST(fd);
438
439         ser_close(fd);
440         ser_open(fds, fds->unit);
441         return (KFile *)fds;
442 }
443
444 /**
445  * Init serial driver for \a unit.
446  */
447 void ser_init(struct Serial *fds, unsigned int unit)
448 {
449         memset(fds, 0, sizeof(*fds));
450
451         DB(fds->fd._type = KFT_SERIAL);
452         fds->fd.reopen = ser_reopen;
453         fds->fd.close = ser_close;
454         fds->fd.read = ser_read;
455         fds->fd.write = ser_write;
456         fds->fd.flush = ser_flush;
457         fds->fd.error = ser_error;
458         fds->fd.clearerr = ser_clearerr;
459         ser_open(fds, unit);
460 }
461
462
463 /**
464  * Read data from SPI bus.
465  * Since we are master, we have to trigger slave by sending
466  * fake chars on the bus.
467  */
468 static size_t spimaster_read(struct KFile *fd, void *_buf, size_t size)
469 {
470         Serial *fd_spi = SERIAL_CAST(fd);
471
472         ser_flush(&fd_spi->fd);
473         ser_purgeRx(fd_spi);
474
475         size_t total_rd = 0;
476         uint8_t *buf = (uint8_t *)_buf;
477         int c;
478
479         while (size--)
480         {
481                 /*
482                  * Send and receive chars 1 by 1, otherwise the rxfifo
483                  * will overrun.
484                  */
485                 ser_putchar(0, fd_spi);
486
487                 if ((c = ser_getchar(fd_spi)) == EOF)
488                         break;
489
490                 *buf++ = c;
491                 total_rd++;
492         }
493         return total_rd;
494 }
495
496 /**
497  * Write data to SPI bus.
498  */
499 static size_t spimaster_write(struct KFile *fd, const void *buf, size_t size)
500 {
501         Serial *fd_spi = SERIAL_CAST(fd);
502
503         ser_purgeRx(fd_spi);
504
505         return ser_write(&fd_spi->fd, buf, size);
506 }
507
508
509 /**
510  * Init SPI serial driver \a unit in master mode.
511  *
512  * This interface implements the SPI master protocol over a serial SPI
513  * driver. This is needed because normal serial driver send/receive data
514  * at the same time. SPI slaves like memories and other peripherals
515  * first receive and *then* send response back instead.
516  * To achieve this, when we are master and we are *sending*,
517  * we have to discard all incoming data. Then, when we want to
518  * receive, we must write fake data to SPI to trigger slave devices.
519  */
520 void spimaster_init(Serial *fds, unsigned int unit)
521 {
522         ser_init(fds, unit);
523         fds->fd.read = spimaster_read;
524         fds->fd.write = spimaster_write;
525 }
526
527