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