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