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