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