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