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