New time handling based on TIMER_TICKS_PER_SEC to support slow timers with ticks...
[bertos.git] / drv / ser_avr.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 AVR UART and SPI I/O driver
10  *
11  * Rationale for project_ks hardware.
12  *
13  * The serial 0 on the board_kf board is used to communicate with the
14  * smart card, which has the TX and RX lines connected together. To
15  * allow the smart card to drive the RX line of the CPU the CPU TX has
16  * to be in a high impedance state.
17  * Whenever a transmission is done and there is nothing more to send
18  * the transmitter is turn off. The output pin is held in input with
19  * pull-up enabled, to avoid capturing noise from the nearby RX line.
20  *
21  * The line on the KBus port must keep sending data, even when
22  * there is nothing to transmit, because a burst data transfer
23  * generates noise on the audio channels.
24  * This is accomplished using the multiprocessor mode of the
25  * ATmega64/128 serial.
26  *
27  * The receiver keeps the MPCM bit always on. When useful data
28  * is trasmitted the address bit is set. The receiver hardware
29  * consider the frame as address info and receive it.
30  * When useless fill bytes are sent the address bit is cleared
31  * and the receiver will ignore them, avoiding useless triggering
32  * of RXC interrupt.
33  *
34  * \version $Id$
35  * \author Bernardo Innocenti <bernie@develer.com>
36  * \author Stefano Fedrigo <aleph@develer.com>
37  */
38
39 /*#*
40  *#* $Log$
41  *#* Revision 1.30  2006/02/17 22:23:06  bernie
42  *#* Update POSIX serial emulator.
43  *#*
44  *#* Revision 1.29  2005/11/27 23:31:48  bernie
45  *#* Support avr-libc 1.4.
46  *#*
47  *#* Revision 1.28  2005/11/04 16:20:02  bernie
48  *#* Fix reference to README.devlib in header.
49  *#*
50  *#* Revision 1.27  2005/07/03 15:19:31  bernie
51  *#* Doxygen fix.
52  *#*
53  *#* Revision 1.26  2005/04/11 19:10:27  bernie
54  *#* Include top-level headers from cfg/ subdir.
55  *#*
56  *#* Revision 1.25  2005/01/25 08:37:26  bernie
57  *#* CONFIG_SER_HWHANDSHAKE fixes.
58  *#*
59  *#* Revision 1.24  2005/01/14 00:49:16  aleph
60  *#* Rename callbacks; SerialHardwareVT.txSending: New callback; Add SPI_BUS macros.
61  *#*
62  *#* Revision 1.23  2005/01/11 18:09:07  aleph
63  *#* Add ATmega8 SPI port definitions; Fix transmit complete IRQ bug; add strobe macros to uart1 and spi
64  *#*
65  *#* Revision 1.22  2004/12/31 17:47:45  bernie
66  *#* Rename UNUSED() to UNUSED_ARG().
67  *#*
68  *#* Revision 1.21  2004/12/13 12:07:06  bernie
69  *#* DISABLE_IRQSAVE/ENABLE_IRQRESTORE: Convert to IRQ_SAVE_DISABLE/IRQ_RESTORE.
70  *#*
71  *#* Revision 1.20  2004/12/13 11:51:43  bernie
72  *#* Fix a latent bug with reentrant serial IRQs.
73  *#*
74  *#* Revision 1.19  2004/12/13 11:51:08  bernie
75  *#* DISABLE_INTS/ENABLE_INTS: Convert to IRQ_DISABLE/IRQ_ENABLE.
76  *#*
77  *#* Revision 1.18  2004/12/08 08:03:48  bernie
78  *#* Doxygen fixes.
79  *#*
80  *#* Revision 1.17  2004/10/19 07:52:35  bernie
81  *#* Reset parity bits before overwriting them (Fixed by batt in project_ks).
82  *#*
83  *#* Revision 1.16  2004/10/03 18:45:48  bernie
84  *#* Convert to new-style config macros; Allow compiling with a C++ compiler (mostly).
85  *#*
86  *#* Revision 1.15  2004/09/14 21:05:36  bernie
87  *#* Use debug.h instead of kdebug.h; Use new AVR pin names; Spelling fixes.
88  *#*
89  *#* Revision 1.14  2004/09/06 21:50:00  bernie
90  *#* Spelling fixes.
91  *#*
92  *#* Revision 1.13  2004/09/06 21:40:50  bernie
93  *#* Move buffer handling in chip-specific driver.
94  *#*
95  *#* Revision 1.12  2004/08/29 22:06:10  bernie
96  *#* Fix a bug in the (unused) RTS/CTS code; Clarify documentation.
97  *#*
98  *#* Revision 1.10  2004/08/10 06:30:41  bernie
99  *#* Major redesign of serial bus policy handling.
100  *#*
101  *#* Revision 1.9  2004/08/02 20:20:29  aleph
102  *#* Merge from project_ks
103  *#*
104  *#* Revision 1.8  2004/07/29 22:57:09  bernie
105  *#* Several tweaks to reduce code size on ATmega8.
106  *#*
107  *#* Revision 1.7  2004/07/18 21:54:23  bernie
108  *#* Add ATmega8 support.
109  *#*
110  *#* Revision 1.5  2004/06/27 15:25:40  aleph
111  *#* Add missing callbacks for SPI;
112  *#* Change UNUSED() macro to new version with two args;
113  *#* Use TX line filling only on the correct KBUS serial port;
114  *#* Fix nasty IRQ disabling bug in recv complete hander for port 1.
115  *#*
116  *#* Revision 1.4  2004/06/03 11:27:09  bernie
117  *#* Add dual-license information.
118  *#*
119  *#* Revision 1.3  2004/06/02 21:35:24  aleph
120  *#* Serial enhancements: interruptible receive handler and 8 bit serial status for AVR; remove volatile attribute to FIFOBuffer, useless for new fifobuf routens
121  *#*
122  *#* Revision 1.2  2004/05/23 18:21:53  bernie
123  *#* Trim CVS logs and cleanup header info.
124  *#*
125  *#*/
126
127 #include "ser.h"
128 #include "ser_p.h"
129 #include "hw.h"  /* Required for bus macros overrides */
130 #include <appconfig.h>
131
132 #include <cfg/debug.h>
133 #include <drv/timer.h>
134 #include <mware/fifobuf.h>
135
136 #include <avr/io.h>
137 #if defined(__AVR_LIBC_VERSION__) && (__AVR_LIBC_VERSION__ >= 10400UL)
138         #include <avr/interrupt.h>
139 #else
140         #include <avr/signal.h>
141 #endif
142
143
144 #if !CONFIG_SER_HWHANDSHAKE
145         /*!
146          * \name Hardware handshake (RTS/CTS).
147          * \{
148          */
149         #define RTS_ON      do {} while (0)
150         #define RTS_OFF     do {} while (0)
151         #define IS_CTS_ON   true
152         #define EIMSKF_CTS  0 /*!< Dummy value, must be overridden */
153         /*\}*/
154 #endif
155
156
157 /*!
158  * \name Overridable serial bus hooks
159  *
160  * These can be redefined in hw.h to implement
161  * special bus policies such as half-duplex, 485, etc.
162  *
163  *
164  * \code
165  *  TXBEGIN      TXCHAR      TXEND  TXOFF
166  *    |   __________|__________ |     |
167  *    |   |   |   |   |   |   | |     |
168  *    v   v   v   v   v   v   v v     v
169  * ______  __  __  __  __  __  __  ________________
170  *       \/  \/  \/  \/  \/  \/  \/
171  * ______/\__/\__/\__/\__/\__/\__/
172  *
173  * \endcode
174  *
175  * \{
176  */
177 #ifndef SER_UART0_BUS_TXINIT
178         /*!
179          * Default TXINIT macro - invoked in uart0_init()
180          *
181          * - Enable both the receiver and the transmitter
182          * - Enable only the RX complete interrupt
183          */
184         #define SER_UART0_BUS_TXINIT do { \
185                 UCSR0B = BV(RXCIE) | BV(RXEN) | BV(TXEN); \
186         } while (0)
187 #endif
188
189 #ifndef SER_UART0_BUS_TXBEGIN
190         /*!
191          * Invoked before starting a transmission
192          *
193          * - Enable both the receiver and the transmitter
194          * - Enable both the RX complete and UDR empty interrupts
195          */
196         #define SER_UART0_BUS_TXBEGIN do { \
197                 UCSR0B = BV(RXCIE) | BV(UDRIE) | BV(RXEN) | BV(TXEN); \
198         } while (0)
199 #endif
200
201 #ifndef SER_UART0_BUS_TXCHAR
202         /*!
203          * Invoked to send one character.
204          */
205         #define SER_UART0_BUS_TXCHAR(c) do { \
206                 UDR0 = (c); \
207         } while (0)
208 #endif
209
210 #ifndef SER_UART0_BUS_TXEND
211         /*!
212          * Invoked as soon as the txfifo becomes empty
213          *
214          * - Keep both the receiver and the transmitter enabled
215          * - Keep the RX complete interrupt enabled
216          * - Disable the UDR empty interrupt
217          */
218         #define SER_UART0_BUS_TXEND do { \
219                 UCSR0B = BV(RXCIE) | BV(RXEN) | BV(TXEN); \
220         } while (0)
221 #endif
222
223 #ifndef SER_UART0_BUS_TXOFF
224         /*!
225          * \def SER_UART0_BUS_TXOFF
226          *
227          * Invoked after the last character has been transmitted
228          *
229          * The default is no action.
230          */
231         #ifdef __doxygen__
232         #define SER_UART0_BUS_TXOFF
233         #endif
234 #endif
235
236 #ifndef SER_UART1_BUS_TXINIT
237         /*! \sa SER_UART0_BUS_TXINIT */
238         #define SER_UART1_BUS_TXINIT do { \
239                 UCSR1B = BV(RXCIE) | BV(RXEN) | BV(TXEN); \
240         } while (0)
241 #endif
242 #ifndef SER_UART1_BUS_TXBEGIN
243         /*! \sa SER_UART0_BUS_TXBEGIN */
244         #define SER_UART1_BUS_TXBEGIN do { \
245                 UCSR1B = BV(RXCIE) | BV(UDRIE) | BV(RXEN) | BV(TXEN); \
246         } while (0)
247 #endif
248 #ifndef SER_UART1_BUS_TXCHAR
249         /*! \sa SER_UART0_BUS_TXCHAR */
250         #define SER_UART1_BUS_TXCHAR(c) do { \
251                 UDR1 = (c); \
252         } while (0)
253 #endif
254 #ifndef SER_UART1_BUS_TXEND
255         /*! \sa SER_UART0_BUS_TXEND */
256         #define SER_UART1_BUS_TXEND do { \
257                 UCSR1B = BV(RXCIE) | BV(RXEN) | BV(TXEN); \
258         } while (0)
259 #endif
260 #ifndef SER_UART1_BUS_TXOFF
261         /*!
262          * \def SER_UART1_BUS_TXOFF
263          *
264          * \see SER_UART0_BUS_TXOFF
265          */
266         #ifdef __doxygen__
267         #define SER_UART1_BUS_TXOFF
268         #endif
269 #endif
270 /*\}*/
271
272
273 /*!
274  * \name Overridable SPI hooks
275  *
276  * These can be redefined in hw.h to implement
277  * special bus policies such as slave select pin handling, etc.
278  *
279  * \{
280  */
281 #ifndef SER_SPI_BUS_TXINIT
282         /*!
283          * Default TXINIT macro - invoked in spi_init()
284          * The default is no action.
285          */
286         #define SER_SPI_BUS_TXINIT
287 #endif
288
289 #ifndef SER_SPI_BUS_TXCLOSE
290         /*!
291          * Invoked after the last character has been transmitted.
292          * The default is no action.
293          */
294         #define SER_SPI_BUS_TXCLOSE
295 #endif
296 /*\}*/
297
298
299 /* SPI port and pin configuration */
300 #if CPU_AVR_ATMEGA64 || CPU_AVR_ATMEGA128 || CPU_AVR_ATMEGA103
301         #define SPI_PORT      PORTB
302         #define SPI_DDR       DDRB
303         #define SPI_SCK_BIT   PB1
304         #define SPI_MOSI_BIT  PB2
305         #define SPI_MISO_BIT  PB3
306 #elif CPU_AVR_ATMEGA8
307         #define SPI_PORT      PORTB
308         #define SPI_DDR       DDRB
309         #define SPI_SCK_BIT   PB5
310         #define SPI_MOSI_BIT  PB3
311         #define SPI_MISO_BIT  PB4
312 #else
313         #error Unknown architecture
314 #endif
315
316 /* USART register definitions */
317 #if CPU_AVR_ATMEGA64 || CPU_AVR_ATMEGA128
318         #define AVR_HAS_UART1 1
319 #elif CPU_AVR_ATMEGA8
320         #define AVR_HAS_UART1 0
321         #define UCSR0A UCSRA
322         #define UCSR0B UCSRB
323         #define UCSR0C UCSRC
324         #define UDR0   UDR
325         #define UBRR0L UBRRL
326         #define UBRR0H UBRRH
327         #define SIG_UART0_DATA SIG_UART_DATA
328         #define SIG_UART0_RECV SIG_UART_RECV
329         #define SIG_UART0_TRANS SIG_UART_TRANS
330 #elif CPU_AVR_ATMEGA103
331         #define AVR_HAS_UART1 0
332         #define UCSR0B UCR
333         #define UDR0   UDR
334         #define UCSR0A USR
335         #define UBRR0L UBRR
336         #define SIG_UART0_DATA SIG_UART_DATA
337         #define SIG_UART0_RECV SIG_UART_RECV
338         #define SIG_UART0_TRANS SIG_UART_TRANS
339 #else
340         #error Unknown architecture
341 #endif
342
343
344 /*!
345  * \def CONFIG_SER_STROBE
346  *
347  * This is a debug facility that can be used to
348  * monitor SER interrupt activity on an external pin.
349  *
350  * To use strobes, redefine the macros SER_STROBE_ON,
351  * SER_STROBE_OFF and SER_STROBE_INIT and set
352  * CONFIG_SER_STROBE to 1.
353  */
354 #if !defined(CONFIG_SER_STROBE) || !CONFIG_SER_STROBE
355         #define SER_STROBE_ON    do {/*nop*/} while(0)
356         #define SER_STROBE_OFF   do {/*nop*/} while(0)
357         #define SER_STROBE_INIT  do {/*nop*/} while(0)
358 #endif
359
360
361 /* From the high-level serial driver */
362 extern struct Serial ser_handles[SER_CNT];
363
364 /* TX and RX buffers */
365 static unsigned char uart0_txbuffer[CONFIG_UART0_TXBUFSIZE];
366 static unsigned char uart0_rxbuffer[CONFIG_UART0_RXBUFSIZE];
367 #if AVR_HAS_UART1
368         static unsigned char uart1_txbuffer[CONFIG_UART1_TXBUFSIZE];
369         static unsigned char uart1_rxbuffer[CONFIG_UART1_RXBUFSIZE];
370 #endif
371 static unsigned char spi_txbuffer[CONFIG_SPI_TXBUFSIZE];
372 static unsigned char spi_rxbuffer[CONFIG_SPI_RXBUFSIZE];
373
374
375 /*!
376  * Internal hardware state structure
377  *
378  * The \a sending variable is true while the transmission
379  * interrupt is retriggering itself.
380  *
381  * For the USARTs the \a sending flag is useful for taking specific
382  * actions before sending a burst of data, at the start of a trasmission
383  * but not before every char sent.
384  *
385  * For the SPI, this flag is necessary because the SPI sends and receives
386  * bytes at the same time and the SPI IRQ is unique for send/receive.
387  * The only way to start transmission is to write data in SPDR (this
388  * is done by spi_starttx()). We do this *only* if a transfer is
389  * not already started.
390  */
391 struct AvrSerial
392 {
393         struct SerialHardware hw;
394         volatile bool sending;
395 };
396
397
398 /*
399  * These are to trick GCC into *not* using absolute addressing mode
400  * when accessing ser_handles, which is very expensive.
401  *
402  * Accessing through these pointers generates much shorter
403  * (and hopefully faster) code.
404  */
405 struct Serial *ser_uart0 = &ser_handles[SER_UART0];
406 #if AVR_HAS_UART1
407 struct Serial *ser_uart1 = &ser_handles[SER_UART1];
408 #endif
409 struct Serial *ser_spi = &ser_handles[SER_SPI];
410
411
412
413 /*
414  * Callbacks
415  */
416 static void uart0_init(
417         UNUSED_ARG(struct SerialHardware *, _hw),
418         UNUSED_ARG(struct Serial *, ser))
419 {
420         SER_UART0_BUS_TXINIT;
421         RTS_ON;
422         SER_STROBE_INIT;
423 }
424
425 static void uart0_cleanup(UNUSED_ARG(struct SerialHardware *, _hw))
426 {
427         UCSR0B = 0;
428 }
429
430 static void uart0_enabletxirq(struct SerialHardware *_hw)
431 {
432         struct AvrSerial *hw = (struct AvrSerial *)_hw;
433
434         /*
435          * WARNING: racy code here!  The tx interrupt sets hw->sending to false
436          * when it runs with an empty fifo.  The order of statements in the
437          * if-block matters.
438          */
439         if (!hw->sending)
440         {
441                 hw->sending = true;
442                 SER_UART0_BUS_TXBEGIN;
443         }
444 }
445
446 static void uart0_setbaudrate(UNUSED_ARG(struct SerialHardware *, _hw), unsigned long rate)
447 {
448         /* Compute baud-rate period */
449         uint16_t period = (((CLOCK_FREQ / 16UL) + (rate / 2)) / rate) - 1;
450
451 #if !CPU_AVR_ATMEGA103
452         UBRR0H = (period) >> 8;
453 #endif
454         UBRR0L = (period);
455
456         //DB(kprintf("uart0_setbaudrate(rate=%lu): period=%d\n", rate, period);)
457 }
458
459 static void uart0_setparity(UNUSED_ARG(struct SerialHardware *, _hw), int parity)
460 {
461 #if !CPU_AVR_ATMEGA103
462         UCSR0C = (UCSR0C & ~(BV(UPM1) | BV(UPM0))) | ((parity) << UPM0);
463 #endif
464 }
465
466 #if AVR_HAS_UART1
467
468 static void uart1_init(
469         UNUSED_ARG(struct SerialHardware *, _hw),
470         UNUSED_ARG(struct Serial *, ser))
471 {
472         SER_UART1_BUS_TXINIT;
473         RTS_ON;
474         SER_STROBE_INIT;
475 }
476
477 static void uart1_cleanup(UNUSED_ARG(struct SerialHardware *, _hw))
478 {
479         UCSR1B = 0;
480 }
481
482 static void uart1_enabletxirq(struct SerialHardware *_hw)
483 {
484         struct AvrSerial *hw = (struct AvrSerial *)_hw;
485
486         /*
487          * WARNING: racy code here!  The tx interrupt
488          * sets hw->sending to false when it runs with
489          * an empty fifo.  The order of the statements
490          * in the if-block matters.
491          */
492         if (!hw->sending)
493         {
494                 hw->sending = true;
495                 SER_UART1_BUS_TXBEGIN;
496         }
497 }
498
499 static void uart1_setbaudrate(UNUSED_ARG(struct SerialHardware *, _hw), unsigned long rate)
500 {
501         /* Compute baud-rate period */
502         uint16_t period = (((CLOCK_FREQ / 16UL) + (rate / 2)) / rate) - 1;
503
504         UBRR1H = (period) >> 8;
505         UBRR1L = (period);
506
507         //DB(kprintf("uart1_setbaudrate(rate=%ld): period=%d\n", rate, period);)
508 }
509
510 static void uart1_setparity(UNUSED_ARG(struct SerialHardware *, _hw), int parity)
511 {
512         UCSR1C = (UCSR1C & ~(BV(UPM1) | BV(UPM0))) | ((parity) << UPM0);
513 }
514
515 #endif // AVR_HAS_UART1
516
517 static void spi_init(UNUSED_ARG(struct SerialHardware *, _hw), UNUSED_ARG(struct Serial *, ser))
518 {
519         /*
520          * Set MOSI and SCK ports out, MISO in.
521          *
522          * The ATmega64/128 datasheet explicitly states that the input/output
523          * state of the SPI pins is not significant, as when the SPI is
524          * active the I/O port are overrided.
525          * This is *blatantly FALSE*.
526          *
527          * Moreover, the MISO pin on the board_kc *must* be in high impedance
528          * state even when the SPI is off, because the line is wired together
529          * with the KBus serial RX, and the transmitter of the slave boards
530          * would be unable to drive the line.
531          */
532         SPI_DDR |= BV(SPI_MOSI_BIT) | BV(SPI_SCK_BIT);
533         SPI_DDR &= ~BV(SPI_MISO_BIT);
534         /* Enable SPI, IRQ on, Master, CPU_CLOCK/16 */
535         SPCR = BV(SPE) | BV(SPIE) | BV(MSTR) | BV(SPR0);
536
537         SER_SPI_BUS_TXINIT;
538
539         SER_STROBE_INIT;
540 }
541
542 static void spi_cleanup(UNUSED_ARG(struct SerialHardware *, _hw))
543 {
544         SPCR = 0;
545
546         SER_SPI_BUS_TXCLOSE;
547
548         /* Set all pins as inputs */
549         SPI_DDR &= ~(BV(SPI_MISO_BIT) | BV(SPI_MOSI_BIT) | BV(SPI_SCK_BIT));
550 }
551
552 static void spi_starttx(struct SerialHardware *_hw)
553 {
554         struct AvrSerial *hw = (struct AvrSerial *)_hw;
555
556         cpuflags_t flags;
557         IRQ_SAVE_DISABLE(flags);
558
559         /* Send data only if the SPI is not already transmitting */
560         if (!hw->sending && !fifo_isempty(&ser_spi->txfifo))
561         {
562                 hw->sending = true;
563                 SPDR = fifo_pop(&ser_spi->txfifo);
564         }
565
566         IRQ_RESTORE(flags);
567 }
568
569 static void spi_setbaudrate(
570         UNUSED_ARG(struct SerialHardware *, _hw),
571         UNUSED_ARG(unsigned long, rate))
572 {
573         // nop
574 }
575
576 static void spi_setparity(UNUSED_ARG(struct SerialHardware *, _hw), UNUSED_ARG(int, parity))
577 {
578         // nop
579 }
580
581 static bool tx_sending(struct SerialHardware* _hw)
582 {
583         struct AvrSerial *hw = (struct AvrSerial *)_hw;
584         return hw->sending;
585 }
586
587
588
589 // FIXME: move into compiler.h?  Ditch?
590 #if COMPILER_C99
591         #define C99INIT(name,val) .name = val
592 #elif defined(__GNUC__)
593         #define C99INIT(name,val) name: val
594 #else
595         #warning No designated initializers, double check your code
596         #define C99INIT(name,val) (val)
597 #endif
598
599 /*
600  * High-level interface data structures
601  */
602 static const struct SerialHardwareVT UART0_VT =
603 {
604         C99INIT(init, uart0_init),
605         C99INIT(cleanup, uart0_cleanup),
606         C99INIT(setBaudrate, uart0_setbaudrate),
607         C99INIT(setParity, uart0_setparity),
608         C99INIT(txStart, uart0_enabletxirq),
609         C99INIT(txSending, tx_sending),
610 };
611
612 #if AVR_HAS_UART1
613 static const struct SerialHardwareVT UART1_VT =
614 {
615         C99INIT(init, uart1_init),
616         C99INIT(cleanup, uart1_cleanup),
617         C99INIT(setBaudrate, uart1_setbaudrate),
618         C99INIT(setParity, uart1_setparity),
619         C99INIT(txStart, uart1_enabletxirq),
620         C99INIT(txSending, tx_sending),
621 };
622 #endif // AVR_HAS_UART1
623
624 static const struct SerialHardwareVT SPI_VT =
625 {
626         C99INIT(init, spi_init),
627         C99INIT(cleanup, spi_cleanup),
628         C99INIT(setBaudrate, spi_setbaudrate),
629         C99INIT(setParity, spi_setparity),
630         C99INIT(txStart, spi_starttx),
631         C99INIT(txSending, tx_sending),
632 };
633
634 static struct AvrSerial UARTDescs[SER_CNT] =
635 {
636         {
637                 C99INIT(hw, /**/) {
638                         C99INIT(table, &UART0_VT),
639                         C99INIT(txbuffer, uart0_txbuffer),
640                         C99INIT(rxbuffer, uart0_rxbuffer),
641                         C99INIT(txbuffer_size, sizeof(uart0_txbuffer)),
642                         C99INIT(rxbuffer_size, sizeof(uart0_rxbuffer)),
643                 },
644                 C99INIT(sending, false),
645         },
646 #if AVR_HAS_UART1
647         {
648                 C99INIT(hw, /**/) {
649                         C99INIT(table, &UART1_VT),
650                         C99INIT(txbuffer, uart1_txbuffer),
651                         C99INIT(rxbuffer, uart1_rxbuffer),
652                         C99INIT(txbuffer_size, sizeof(uart1_txbuffer)),
653                         C99INIT(rxbuffer_size, sizeof(uart1_rxbuffer)),
654                 },
655                 C99INIT(sending, false),
656         },
657 #endif
658         {
659                 C99INIT(hw, /**/) {
660                         C99INIT(table, &SPI_VT),
661                         C99INIT(txbuffer, spi_txbuffer),
662                         C99INIT(rxbuffer, spi_rxbuffer),
663                         C99INIT(txbuffer_size, sizeof(spi_txbuffer)),
664                         C99INIT(rxbuffer_size, sizeof(spi_rxbuffer)),
665                 },
666                 C99INIT(sending, false),
667         }
668 };
669
670 struct SerialHardware *ser_hw_getdesc(int unit)
671 {
672         ASSERT(unit < SER_CNT);
673         return &UARTDescs[unit].hw;
674 }
675
676
677 /*
678  * Interrupt handlers
679  */
680
681 #if CONFIG_SER_HWHANDSHAKE
682
683 //! This interrupt is triggered when the CTS line goes high
684 SIGNAL(SIG_CTS)
685 {
686         // Re-enable UDR empty interrupt and TX, then disable CTS interrupt
687         UCSR0B = BV(RXCIE) | BV(UDRIE) | BV(RXEN) | BV(TXEN);
688         EIMSK &= ~EIMSKF_CTS;
689 }
690
691 #endif // CONFIG_SER_HWHANDSHAKE
692
693
694 /*!
695  * Serial 0 TX interrupt handler
696  */
697 SIGNAL(SIG_UART0_DATA)
698 {
699         SER_STROBE_ON;
700
701         struct FIFOBuffer * const txfifo = &ser_uart0->txfifo;
702
703         if (fifo_isempty(txfifo))
704         {
705                 SER_UART0_BUS_TXEND;
706 #ifndef SER_UART0_BUS_TXOFF
707                 UARTDescs[SER_UART0].sending = false;
708 #endif
709         }
710 #if CPU_AVR_ATMEGA64 || CPU_AVR_ATMEGA128 || CPU_AVR_ATMEGA103
711         else if (!IS_CTS_ON)
712         {
713                 // Disable rx interrupt and tx, enable CTS interrupt
714                 // UNTESTED
715                 UCSR0B = BV(RXCIE) | BV(RXEN) | BV(TXEN);
716                 EIFR |= EIMSKF_CTS;
717                 EIMSK |= EIMSKF_CTS;
718         }
719 #endif
720         else
721         {
722                 char c = fifo_pop(txfifo);
723                 SER_UART0_BUS_TXCHAR(c);
724         }
725
726         SER_STROBE_OFF;
727 }
728
729 #ifdef SER_UART0_BUS_TXOFF
730 /*!
731  * Serial port 0 TX complete interrupt handler.
732  *
733  * This IRQ is usually disabled.  The UDR-empty interrupt
734  * enables it when there's no more data to transmit.
735  * We need to wait until the last character has been
736  * transmitted before switching the 485 transceiver to
737  * receive mode.
738  *
739  * The txfifo might have been refilled by putchar() while
740  * we were waiting for the transmission complete interrupt.
741  * In this case, we must restart the UDR empty interrupt,
742  * otherwise we'd stop the serial port with some data
743  * still pending in the buffer.
744  */
745 SIGNAL(SIG_UART0_TRANS)
746 {
747         SER_STROBE_ON;
748
749         struct FIFOBuffer * const txfifo = &ser_uart0->txfifo;
750         if (fifo_isempty(txfifo))
751         {
752                 SER_UART0_BUS_TXOFF;
753                 UARTDescs[SER_UART0].sending = false;
754         }
755         else
756                 UCSR0B = BV(RXCIE) | BV(UDRIE) | BV(RXEN) | BV(TXEN);
757
758         SER_STROBE_OFF;
759 }
760 #endif /* SER_UART0_BUS_TXOFF */
761
762
763 #if AVR_HAS_UART1
764
765 /*!
766  * Serial 1 TX interrupt handler
767  */
768 SIGNAL(SIG_UART1_DATA)
769 {
770         SER_STROBE_ON;
771
772         struct FIFOBuffer * const txfifo = &ser_uart1->txfifo;
773
774         if (fifo_isempty(txfifo))
775         {
776                 SER_UART1_BUS_TXEND;
777 #ifndef SER_UART1_BUS_TXOFF
778                 UARTDescs[SER_UART1].sending = false;
779 #endif
780         }
781 #if CPU_AVR_ATMEGA64 || CPU_AVR_ATMEGA128 || CPU_AVR_ATMEGA103
782         else if (!IS_CTS_ON)
783         {
784                 // Disable rx interrupt and tx, enable CTS interrupt
785                 // UNTESTED
786                 UCSR1B = BV(RXCIE) | BV(RXEN) | BV(TXEN);
787                 EIFR |= EIMSKF_CTS;
788                 EIMSK |= EIMSKF_CTS;
789         }
790 #endif
791         else
792         {
793                 char c = fifo_pop(txfifo);
794                 SER_UART1_BUS_TXCHAR(c);
795         }
796
797         SER_STROBE_OFF;
798 }
799
800 #ifdef SER_UART1_BUS_TXOFF
801 /*!
802  * Serial port 1 TX complete interrupt handler.
803  *
804  * \sa port 0 TX complete handler.
805  */
806 SIGNAL(SIG_UART1_TRANS)
807 {
808         SER_STROBE_ON;
809
810         struct FIFOBuffer * const txfifo = &ser_uart1->txfifo;
811         if (fifo_isempty(txfifo))
812         {
813                 SER_UART1_BUS_TXOFF;
814                 UARTDescs[SER_UART1].sending = false;
815         }
816         else
817                 UCSR1B = BV(RXCIE) | BV(UDRIE) | BV(RXEN) | BV(TXEN);
818
819         SER_STROBE_OFF;
820 }
821 #endif /* SER_UART1_BUS_TXOFF */
822
823 #endif // AVR_HAS_UART1
824
825
826 /*!
827  * Serial 0 RX complete interrupt handler.
828  *
829  * This handler is interruptible.
830  * Interrupt are reenabled as soon as recv complete interrupt is
831  * disabled. Using INTERRUPT() is troublesome when the serial
832  * is heavily loaded, because an interrupt could be retriggered
833  * when executing the handler prologue before RXCIE is disabled.
834  *
835  * \note The code that re-enables interrupts is commented out
836  *       because in some nasty cases the interrupt is retriggered.
837  *       This is probably due to the RXC flag being set before
838  *       RXCIE is cleared.  Unfortunately the RXC flag is read-only
839  *       and can't be cleared by code.
840  */
841 SIGNAL(SIG_UART0_RECV)
842 {
843         SER_STROBE_ON;
844
845         /* Disable Recv complete IRQ */
846         //UCSR0B &= ~BV(RXCIE);
847         //IRQ_ENABLE;
848
849         /* Should be read before UDR */
850         ser_uart0->status |= UCSR0A & (SERRF_RXSROVERRUN | SERRF_FRAMEERROR);
851
852         /* To clear the RXC flag we must _always_ read the UDR even when we're
853          * not going to accept the incoming data, otherwise a new interrupt
854          * will occur once the handler terminates.
855          */
856         char c = UDR0;
857         struct FIFOBuffer * const rxfifo = &ser_uart0->rxfifo;
858
859         if (fifo_isfull(rxfifo))
860                 ser_uart0->status |= SERRF_RXFIFOOVERRUN;
861         else
862         {
863                 fifo_push(rxfifo, c);
864 #if CONFIG_SER_HWHANDSHAKE
865                 if (fifo_isfull(rxfifo))
866                         RTS_OFF;
867 #endif
868         }
869
870         /* Reenable receive complete int */
871         //IRQ_DISABLE;
872         //UCSR0B |= BV(RXCIE);
873
874         SER_STROBE_OFF;
875 }
876
877
878 #if AVR_HAS_UART1
879
880 /*!
881  * Serial 1 RX complete interrupt handler.
882  *
883  * This handler is interruptible.
884  * Interrupt are reenabled as soon as recv complete interrupt is
885  * disabled. Using INTERRUPT() is troublesome when the serial
886  * is heavily loaded, because an interrupt could be retriggered
887  * when executing the handler prologue before RXCIE is disabled.
888  *
889  * \see SIGNAL(SIG_UART0_RECV)
890  */
891 SIGNAL(SIG_UART1_RECV)
892 {
893         SER_STROBE_ON;
894
895         /* Disable Recv complete IRQ */
896         //UCSR1B &= ~BV(RXCIE);
897         //IRQ_ENABLE;
898
899         /* Should be read before UDR */
900         ser_uart1->status |= UCSR1A & (SERRF_RXSROVERRUN | SERRF_FRAMEERROR);
901
902         /* To avoid an IRQ storm, we must _always_ read the UDR even when we're
903          * not going to accept the incoming data
904          */
905         char c = UDR1;
906         struct FIFOBuffer * const rxfifo = &ser_uart1->rxfifo;
907         //ASSERT_VALID_FIFO(rxfifo);
908
909         if (UNLIKELY(fifo_isfull(rxfifo)))
910                 ser_uart1->status |= SERRF_RXFIFOOVERRUN;
911         else
912         {
913                 fifo_push(rxfifo, c);
914 #if CONFIG_SER_HWHANDSHAKE
915                 if (fifo_isfull(rxfifo))
916                         RTS_OFF;
917 #endif
918         }
919         /* Re-enable receive complete int */
920         //IRQ_DISABLE;
921         //UCSR1B |= BV(RXCIE);
922
923         SER_STROBE_OFF;
924 }
925
926 #endif // AVR_HAS_UART1
927
928
929 /*!
930  * SPI interrupt handler
931  */
932 SIGNAL(SIG_SPI)
933 {
934         SER_STROBE_ON;
935
936         /* Read incoming byte. */
937         if (!fifo_isfull(&ser_spi->rxfifo))
938                 fifo_push(&ser_spi->rxfifo, SPDR);
939         /*
940          * FIXME
941         else
942                 ser_spi->status |= SERRF_RXFIFOOVERRUN;
943         */
944
945         /* Send */
946         if (!fifo_isempty(&ser_spi->txfifo))
947                 SPDR = fifo_pop(&ser_spi->txfifo);
948         else
949                 UARTDescs[SER_SPI].sending = false;
950
951         SER_STROBE_OFF;
952 }