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