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