Merge branch "preempt" in "trunk".
[bertos.git] / bertos / cpu / avr / drv / ser_avr.c
1 /**
2  * \file
3  * <!--
4  * This file is part of BeRTOS.
5  *
6  * Bertos is free software; you can redistribute it and/or modify
7  * it under the terms of the GNU General Public License as published by
8  * the Free Software Foundation; either version 2 of the License, or
9  * (at your option) any later version.
10  *
11  * This program is distributed in the hope that it will be useful,
12  * but WITHOUT ANY WARRANTY; without even the implied warranty of
13  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14  * GNU General Public License for more details.
15  *
16  * You should have received a copy of the GNU General Public License
17  * along with this program; if not, write to the Free Software
18  * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
19  *
20  * As a special exception, you may use this file as part of a free software
21  * library without restriction.  Specifically, if other files instantiate
22  * templates or use macros or inline functions from this file, or you compile
23  * this file and link it with other files to produce an executable, this
24  * file does not by itself cause the resulting executable to be covered by
25  * the GNU General Public License.  This exception does not however
26  * invalidate any other reasons why the executable file might be covered by
27  * the GNU General Public License.
28  *
29  * Copyright 2003, 2004 Develer S.r.l. (http://www.develer.com/)
30  * Copyright 2000 Bernie Innocenti <bernie@codewiz.org>
31  *
32  * -->
33  *
34  * \brief AVR UART and SPI I/O driver (Implementation)
35  *
36  * \version $Id$
37  *
38  * \author Bernie Innocenti <bernie@codewiz.org>
39  * \author Stefano Fedrigo <aleph@develer.com>
40  */
41
42 #include "hw/hw_ser.h"  /* Required for bus macros overrides */
43 #include <hw/hw_cpufreq.h>  /* CPU_FREQ */
44
45 #include "cfg/cfg_ser.h"
46
47 #include <cfg/macros.h> /* DIV_ROUND */
48 #include <cfg/debug.h>
49 #include <cfg/cfg_arch.h> // ARCH_NIGHTTEST
50
51 #include <drv/ser.h>
52 #include <drv/ser_p.h>
53 #include <drv/timer.h>
54
55 #include <struct/fifobuf.h>
56
57 #include <avr/io.h>
58
59 #if defined(__AVR_LIBC_VERSION__) && (__AVR_LIBC_VERSION__ >= 10400UL)
60         #include <avr/interrupt.h>
61 #else
62         #include <avr/signal.h>
63 #endif
64
65
66 #if !CONFIG_SER_HWHANDSHAKE
67         /**
68          * \name Hardware handshake (RTS/CTS).
69          * \{
70          */
71         #define RTS_ON      do {} while (0)
72         #define RTS_OFF     do {} while (0)
73         #define IS_CTS_ON   true
74         #define EIMSKF_CTS  0 /**< Dummy value, must be overridden */
75         /*\}*/
76 #endif
77
78 #if CPU_AVR_ATMEGA1281
79         #define BIT_RXCIE0 RXCIE0
80         #define BIT_RXEN0  RXEN0
81         #define BIT_TXEN0  TXEN0
82         #define BIT_UDRIE0 UDRIE0
83
84         #define BIT_RXCIE1 RXCIE1
85         #define BIT_RXEN1  RXEN1
86         #define BIT_TXEN1  TXEN1
87         #define BIT_UDRIE1 UDRIE1
88 #else
89         #define BIT_RXCIE0 RXCIE
90         #define BIT_RXEN0  RXEN
91         #define BIT_TXEN0  TXEN
92         #define BIT_UDRIE0 UDRIE
93
94         #define BIT_RXCIE1 RXCIE
95         #define BIT_RXEN1  RXEN
96         #define BIT_TXEN1  TXEN
97         #define BIT_UDRIE1 UDRIE
98 #endif
99
100
101 /**
102  * \name Overridable serial bus hooks
103  *
104  * These can be redefined in hw.h to implement
105  * special bus policies such as half-duplex, 485, etc.
106  *
107  *
108  * \code
109  *  TXBEGIN      TXCHAR      TXEND  TXOFF
110  *    |   __________|__________ |     |
111  *    |   |   |   |   |   |   | |     |
112  *    v   v   v   v   v   v   v v     v
113  * ______  __  __  __  __  __  __  ________________
114  *       \/  \/  \/  \/  \/  \/  \/
115  * ______/\__/\__/\__/\__/\__/\__/
116  *
117  * \endcode
118  *
119  * \{
120  */
121 #ifndef SER_UART0_BUS_TXINIT
122         /**
123          * Default TXINIT macro - invoked in uart0_init()
124          *
125          * - Enable both the receiver and the transmitter
126          * - Enable only the RX complete interrupt
127          */
128         #define SER_UART0_BUS_TXINIT do { \
129                 UCSR0B = BV(BIT_RXCIE0) | BV(BIT_RXEN0) | BV(BIT_TXEN0); \
130         } while (0)
131 #endif
132
133 #ifndef SER_UART0_BUS_TXBEGIN
134         /**
135          * Invoked before starting a transmission
136          *
137          * - Enable both the receiver and the transmitter
138          * - Enable both the RX complete and UDR empty interrupts
139          */
140         #define SER_UART0_BUS_TXBEGIN do { \
141                 UCSR0B = BV(BIT_RXCIE0) | BV(BIT_UDRIE0) | BV(BIT_RXEN0) | BV(BIT_TXEN0); \
142         } while (0)
143 #endif
144
145 #ifndef SER_UART0_BUS_TXCHAR
146         /**
147          * Invoked to send one character.
148          */
149         #define SER_UART0_BUS_TXCHAR(c) do { \
150                 UDR0 = (c); \
151         } while (0)
152 #endif
153
154 #ifndef SER_UART0_BUS_TXEND
155         /**
156          * Invoked as soon as the txfifo becomes empty
157          *
158          * - Keep both the receiver and the transmitter enabled
159          * - Keep the RX complete interrupt enabled
160          * - Disable the UDR empty interrupt
161          */
162         #define SER_UART0_BUS_TXEND do { \
163                 UCSR0B = BV(BIT_RXCIE0) | BV(BIT_RXEN0) | BV(BIT_TXEN0); \
164         } while (0)
165 #endif
166
167 #ifndef SER_UART0_BUS_TXOFF
168         /**
169          * \def SER_UART0_BUS_TXOFF
170          *
171          * Invoked after the last character has been transmitted
172          *
173          * The default is no action.
174          */
175         #ifdef __doxygen__
176         #define SER_UART0_BUS_TXOFF
177         #endif
178 #endif
179
180 #ifndef SER_UART1_BUS_TXINIT
181         /** \sa SER_UART0_BUS_TXINIT */
182         #define SER_UART1_BUS_TXINIT do { \
183                 UCSR1B = BV(BIT_RXCIE1) | BV(BIT_RXEN1) | BV(BIT_TXEN1); \
184         } while (0)
185 #endif
186 #ifndef SER_UART1_BUS_TXBEGIN
187         /** \sa SER_UART0_BUS_TXBEGIN */
188         #define SER_UART1_BUS_TXBEGIN do { \
189                 UCSR1B = BV(BIT_RXCIE1) | BV(BIT_UDRIE1) | BV(BIT_RXEN1) | BV(BIT_TXEN1); \
190         } while (0)
191 #endif
192 #ifndef SER_UART1_BUS_TXCHAR
193         /** \sa SER_UART0_BUS_TXCHAR */
194         #define SER_UART1_BUS_TXCHAR(c) do { \
195                 UDR1 = (c); \
196         } while (0)
197 #endif
198 #ifndef SER_UART1_BUS_TXEND
199         /** \sa SER_UART0_BUS_TXEND */
200         #define SER_UART1_BUS_TXEND do { \
201                 UCSR1B = BV(BIT_RXCIE1) | BV(BIT_RXEN1) | BV(BIT_TXEN1); \
202         } while (0)
203 #endif
204 #ifndef SER_UART1_BUS_TXOFF
205         /**
206          * \def SER_UART1_BUS_TXOFF
207          *
208          * \see SER_UART0_BUS_TXOFF
209          */
210         #ifdef __doxygen__
211         #define SER_UART1_BUS_TXOFF
212         #endif
213 #endif
214 /*\}*/
215
216
217 /**
218  * \name Overridable SPI hooks
219  *
220  * These can be redefined in hw.h to implement
221  * special bus policies such as slave select pin handling, etc.
222  *
223  * \{
224  */
225 #ifndef SER_SPI_BUS_TXINIT
226         /**
227          * Default TXINIT macro - invoked in spi_init()
228          * The default is no action.
229          */
230         #define SER_SPI_BUS_TXINIT
231 #endif
232
233 #ifndef SER_SPI_BUS_TXCLOSE
234         /**
235          * Invoked after the last character has been transmitted.
236          * The default is no action.
237          */
238         #define SER_SPI_BUS_TXCLOSE
239 #endif
240 /*\}*/
241
242
243 /* SPI port and pin configuration */
244 #if CPU_AVR_ATMEGA64 || CPU_AVR_ATMEGA128 || CPU_AVR_ATMEGA103 || CPU_AVR_ATMEGA1281
245         #define SPI_PORT      PORTB
246         #define SPI_DDR       DDRB
247         #define SPI_SS_BIT    PB0
248         #define SPI_SCK_BIT   PB1
249         #define SPI_MOSI_BIT  PB2
250         #define SPI_MISO_BIT  PB3
251 #elif CPU_AVR_ATMEGA8
252         #define SPI_PORT      PORTB
253         #define SPI_DDR       DDRB
254         #define SPI_SS_BIT    PB2
255         #define SPI_SCK_BIT   PB5
256         #define SPI_MOSI_BIT  PB3
257         #define SPI_MISO_BIT  PB4
258 #else
259         #error Unknown architecture
260 #endif
261
262 /* USART register definitions */
263 #if CPU_AVR_ATMEGA64 || CPU_AVR_ATMEGA128 || CPU_AVR_ATMEGA1281
264         #define AVR_HAS_UART1 1
265 #elif CPU_AVR_ATMEGA8
266         #define AVR_HAS_UART1 0
267         #define UCSR0A UCSRA
268         #define UCSR0B UCSRB
269         #define UCSR0C UCSRC
270         #define UDR0   UDR
271         #define UBRR0L UBRRL
272         #define UBRR0H UBRRH
273         #define SIG_UART0_DATA SIG_UART_DATA
274         #define SIG_UART0_RECV SIG_UART_RECV
275         #define SIG_UART0_TRANS SIG_UART_TRANS
276 #elif CPU_AVR_ATMEGA103
277         #define AVR_HAS_UART1 0
278         #define UCSR0B UCR
279         #define UDR0   UDR
280         #define UCSR0A USR
281         #define UBRR0L UBRR
282         #define SIG_UART0_DATA SIG_UART_DATA
283         #define SIG_UART0_RECV SIG_UART_RECV
284         #define SIG_UART0_TRANS SIG_UART_TRANS
285 #else
286         #error Unknown architecture
287 #endif
288
289
290 /* From the high-level serial driver */
291 extern struct Serial *ser_handles[SER_CNT];
292
293 /* TX and RX buffers */
294 static unsigned char uart0_txbuffer[CONFIG_UART0_TXBUFSIZE];
295 static unsigned char uart0_rxbuffer[CONFIG_UART0_RXBUFSIZE];
296 #if AVR_HAS_UART1
297         static unsigned char uart1_txbuffer[CONFIG_UART1_TXBUFSIZE];
298         static unsigned char uart1_rxbuffer[CONFIG_UART1_RXBUFSIZE];
299 #endif
300 static unsigned char spi_txbuffer[CONFIG_SPI_TXBUFSIZE];
301 static unsigned char spi_rxbuffer[CONFIG_SPI_RXBUFSIZE];
302
303
304 /**
305  * Internal hardware state structure
306  *
307  * The \a sending variable is true while the transmission
308  * interrupt is retriggering itself.
309  *
310  * For the USARTs the \a sending flag is useful for taking specific
311  * actions before sending a burst of data, at the start of a trasmission
312  * but not before every char sent.
313  *
314  * For the SPI, this flag is necessary because the SPI sends and receives
315  * bytes at the same time and the SPI IRQ is unique for send/receive.
316  * The only way to start transmission is to write data in SPDR (this
317  * is done by spi_starttx()). We do this *only* if a transfer is
318  * not already started.
319  */
320 struct AvrSerial
321 {
322         struct SerialHardware hw;
323         volatile bool sending;
324 };
325
326
327
328 /*
329  * Callbacks
330  */
331 static void uart0_init(
332         UNUSED_ARG(struct SerialHardware *, _hw),
333         UNUSED_ARG(struct Serial *, ser))
334 {
335         SER_UART0_BUS_TXINIT;
336         RTS_ON;
337         SER_STROBE_INIT;
338 }
339
340 static void uart0_cleanup(UNUSED_ARG(struct SerialHardware *, _hw))
341 {
342         UCSR0B = 0;
343 }
344
345 static void uart0_enabletxirq(struct SerialHardware *_hw)
346 {
347         struct AvrSerial *hw = (struct AvrSerial *)_hw;
348
349         /*
350          * WARNING: racy code here!  The tx interrupt sets hw->sending to false
351          * when it runs with an empty fifo.  The order of statements in the
352          * if-block matters.
353          */
354         if (!hw->sending)
355         {
356                 hw->sending = true;
357                 SER_UART0_BUS_TXBEGIN;
358         }
359 }
360
361 static void uart0_setbaudrate(UNUSED_ARG(struct SerialHardware *, _hw), unsigned long rate)
362 {
363         /* Compute baud-rate period */
364         uint16_t period = DIV_ROUND(CPU_FREQ / 16UL, rate) - 1;
365
366 #if !CPU_AVR_ATMEGA103
367         UBRR0H = (period) >> 8;
368 #endif
369         UBRR0L = (period);
370
371         //DB(kprintf("uart0_setbaudrate(rate=%lu): period=%d\n", rate, period);)
372 }
373
374 static void uart0_setparity(UNUSED_ARG(struct SerialHardware *, _hw), int parity)
375 {
376 #if !CPU_AVR_ATMEGA103
377         UCSR0C = (UCSR0C & ~(BV(UPM01) | BV(UPM00))) | ((parity) << UPM00);
378 #endif
379 }
380
381 #if AVR_HAS_UART1
382
383 static void uart1_init(
384         UNUSED_ARG(struct SerialHardware *, _hw),
385         UNUSED_ARG(struct Serial *, ser))
386 {
387         SER_UART1_BUS_TXINIT;
388         RTS_ON;
389         SER_STROBE_INIT;
390 }
391
392 static void uart1_cleanup(UNUSED_ARG(struct SerialHardware *, _hw))
393 {
394         UCSR1B = 0;
395 }
396
397 static void uart1_enabletxirq(struct SerialHardware *_hw)
398 {
399         struct AvrSerial *hw = (struct AvrSerial *)_hw;
400
401         /*
402          * WARNING: racy code here!  The tx interrupt
403          * sets hw->sending to false when it runs with
404          * an empty fifo.  The order of the statements
405          * in the if-block matters.
406          */
407         if (!hw->sending)
408         {
409                 hw->sending = true;
410                 SER_UART1_BUS_TXBEGIN;
411         }
412 }
413
414 static void uart1_setbaudrate(UNUSED_ARG(struct SerialHardware *, _hw), unsigned long rate)
415 {
416         /* Compute baud-rate period */
417         uint16_t period = DIV_ROUND(CPU_FREQ / 16UL, rate) - 1;
418
419         UBRR1H = (period) >> 8;
420         UBRR1L = (period);
421
422         //DB(kprintf("uart1_setbaudrate(rate=%ld): period=%d\n", rate, period);)
423 }
424
425 static void uart1_setparity(UNUSED_ARG(struct SerialHardware *, _hw), int parity)
426 {
427         UCSR1C = (UCSR1C & ~(BV(UPM11) | BV(UPM10))) | ((parity) << UPM10);
428 }
429
430 #endif // AVR_HAS_UART1
431
432 static void spi_init(UNUSED_ARG(struct SerialHardware *, _hw), UNUSED_ARG(struct Serial *, ser))
433 {
434         /*
435          * Set MOSI and SCK ports out, MISO in.
436          *
437          * The ATmega64/128 datasheet explicitly states that the input/output
438          * state of the SPI pins is not significant, as when the SPI is
439          * active the I/O port are overrided.
440          * This is *blatantly FALSE*.
441          *
442          * Moreover, the MISO pin on the board_kc *must* be in high impedance
443          * state even when the SPI is off, because the line is wired together
444          * with the KBus serial RX, and the transmitter of the slave boards
445          * would be unable to drive the line.
446          */
447         ATOMIC(SPI_DDR |= (BV(SPI_MOSI_BIT) | BV(SPI_SCK_BIT)));
448
449         /*
450          * If the SPI master mode is activated and the SS pin is in input and tied low,
451          * the SPI hardware will automatically switch to slave mode!
452          * For proper communication this pins should therefore be:
453          * - as output
454          * - as input but tied high forever!
455          * This driver set the pin as output.
456          */
457         #warning FIXME:SPI SS pin set as output for proper operation, check schematics for possible conflicts.
458         ATOMIC(SPI_DDR |= BV(SPI_SS_BIT));
459
460         ATOMIC(SPI_DDR &= ~BV(SPI_MISO_BIT));
461         /* Enable SPI, IRQ on, Master */
462         SPCR = BV(SPE) | BV(SPIE) | BV(MSTR);
463
464         /* Set data order */
465         #if CONFIG_SPI_DATA_ORDER == SER_LSB_FIRST
466                 SPCR |= BV(DORD);
467         #endif
468
469         /* Set SPI clock rate */
470         #if CONFIG_SPI_CLOCK_DIV == 128
471                 SPCR |= (BV(SPR1) | BV(SPR0));
472         #elif (CONFIG_SPI_CLOCK_DIV == 64 || CONFIG_SPI_CLOCK_DIV == 32)
473                 SPCR |= BV(SPR1);
474         #elif (CONFIG_SPI_CLOCK_DIV == 16 || CONFIG_SPI_CLOCK_DIV == 8)
475                 SPCR |= BV(SPR0);
476         #elif (CONFIG_SPI_CLOCK_DIV == 4 || CONFIG_SPI_CLOCK_DIV == 2)
477                 // SPR0 & SDPR1 both at 0
478         #else
479                 #error Unsupported SPI clock division factor.
480         #endif
481
482         /* Set SPI2X bit (spi double frequency) */
483         #if (CONFIG_SPI_CLOCK_DIV == 128 || CONFIG_SPI_CLOCK_DIV == 64 \
484           || CONFIG_SPI_CLOCK_DIV == 16 || CONFIG_SPI_CLOCK_DIV == 4)
485                 SPSR &= ~BV(SPI2X);
486         #elif (CONFIG_SPI_CLOCK_DIV == 32 || CONFIG_SPI_CLOCK_DIV == 8 || CONFIG_SPI_CLOCK_DIV == 2)
487                 SPSR |= BV(SPI2X);
488         #else
489                 #error Unsupported SPI clock division factor.
490         #endif
491
492         /* Set clock polarity */
493         #if CONFIG_SPI_CLOCK_POL == 1
494                 SPCR |= BV(CPOL);
495         #endif
496
497         /* Set clock phase */
498         #if CONFIG_SPI_CLOCK_PHASE == 1
499                 SPCR |= BV(CPHA);
500         #endif
501         SER_SPI_BUS_TXINIT;
502
503         SER_STROBE_INIT;
504 }
505
506 static void spi_cleanup(UNUSED_ARG(struct SerialHardware *, _hw))
507 {
508         SPCR = 0;
509
510         SER_SPI_BUS_TXCLOSE;
511
512         /* Set all pins as inputs */
513         ATOMIC(SPI_DDR &= ~(BV(SPI_MISO_BIT) | BV(SPI_MOSI_BIT) | BV(SPI_SCK_BIT) | BV(SPI_SS_BIT)));
514 }
515
516 static void spi_starttx(struct SerialHardware *_hw)
517 {
518         struct AvrSerial *hw = (struct AvrSerial *)_hw;
519
520         cpu_flags_t flags;
521         IRQ_SAVE_DISABLE(flags);
522
523         /* Send data only if the SPI is not already transmitting */
524         if (!hw->sending && !fifo_isempty(&ser_handles[SER_SPI]->txfifo))
525         {
526                 hw->sending = true;
527                 SPDR = fifo_pop(&ser_handles[SER_SPI]->txfifo);
528         }
529
530         IRQ_RESTORE(flags);
531 }
532
533 static void spi_setbaudrate(
534         UNUSED_ARG(struct SerialHardware *, _hw),
535         UNUSED_ARG(unsigned long, rate))
536 {
537         // nop
538 }
539
540 static void spi_setparity(UNUSED_ARG(struct SerialHardware *, _hw), UNUSED_ARG(int, parity))
541 {
542         // nop
543 }
544
545 static bool tx_sending(struct SerialHardware* _hw)
546 {
547         struct AvrSerial *hw = (struct AvrSerial *)_hw;
548         return hw->sending;
549 }
550
551
552
553 // FIXME: move into compiler.h?  Ditch?
554 #if COMPILER_C99
555         #define C99INIT(name,val) .name = val
556 #elif defined(__GNUC__)
557         #define C99INIT(name,val) name: val
558 #else
559         #warning No designated initializers, double check your code
560         #define C99INIT(name,val) (val)
561 #endif
562
563 /*
564  * High-level interface data structures
565  */
566 static const struct SerialHardwareVT UART0_VT =
567 {
568         C99INIT(init, uart0_init),
569         C99INIT(cleanup, uart0_cleanup),
570         C99INIT(setBaudrate, uart0_setbaudrate),
571         C99INIT(setParity, uart0_setparity),
572         C99INIT(txStart, uart0_enabletxirq),
573         C99INIT(txSending, tx_sending),
574 };
575
576 #if AVR_HAS_UART1
577 static const struct SerialHardwareVT UART1_VT =
578 {
579         C99INIT(init, uart1_init),
580         C99INIT(cleanup, uart1_cleanup),
581         C99INIT(setBaudrate, uart1_setbaudrate),
582         C99INIT(setParity, uart1_setparity),
583         C99INIT(txStart, uart1_enabletxirq),
584         C99INIT(txSending, tx_sending),
585 };
586 #endif // AVR_HAS_UART1
587
588 static const struct SerialHardwareVT SPI_VT =
589 {
590         C99INIT(init, spi_init),
591         C99INIT(cleanup, spi_cleanup),
592         C99INIT(setBaudrate, spi_setbaudrate),
593         C99INIT(setParity, spi_setparity),
594         C99INIT(txStart, spi_starttx),
595         C99INIT(txSending, tx_sending),
596 };
597
598 static struct AvrSerial UARTDescs[SER_CNT] =
599 {
600         {
601                 C99INIT(hw, /**/) {
602                         C99INIT(table, &UART0_VT),
603                         C99INIT(txbuffer, uart0_txbuffer),
604                         C99INIT(rxbuffer, uart0_rxbuffer),
605                         C99INIT(txbuffer_size, sizeof(uart0_txbuffer)),
606                         C99INIT(rxbuffer_size, sizeof(uart0_rxbuffer)),
607                 },
608                 C99INIT(sending, false),
609         },
610 #if AVR_HAS_UART1
611         {
612                 C99INIT(hw, /**/) {
613                         C99INIT(table, &UART1_VT),
614                         C99INIT(txbuffer, uart1_txbuffer),
615                         C99INIT(rxbuffer, uart1_rxbuffer),
616                         C99INIT(txbuffer_size, sizeof(uart1_txbuffer)),
617                         C99INIT(rxbuffer_size, sizeof(uart1_rxbuffer)),
618                 },
619                 C99INIT(sending, false),
620         },
621 #endif
622         {
623                 C99INIT(hw, /**/) {
624                         C99INIT(table, &SPI_VT),
625                         C99INIT(txbuffer, spi_txbuffer),
626                         C99INIT(rxbuffer, spi_rxbuffer),
627                         C99INIT(txbuffer_size, sizeof(spi_txbuffer)),
628                         C99INIT(rxbuffer_size, sizeof(spi_rxbuffer)),
629                 },
630                 C99INIT(sending, false),
631         }
632 };
633
634 struct SerialHardware *ser_hw_getdesc(int unit)
635 {
636         ASSERT(unit < SER_CNT);
637         return &UARTDescs[unit].hw;
638 }
639
640
641 /*
642  * Interrupt handlers
643  */
644
645 #if CONFIG_SER_HWHANDSHAKE
646
647 /// This interrupt is triggered when the CTS line goes high
648 DECLARE_ISR(SIG_CTS)
649 {
650         // Re-enable UDR empty interrupt and TX, then disable CTS interrupt
651         UCSR0B = BV(BIT_RXCIE0) | BV(BIT_UDRIE0) | BV(BIT_RXEN0) | BV(BIT_TXEN0);
652         EIMSK &= ~EIMSKF_CTS;
653 }
654
655 #endif // CONFIG_SER_HWHANDSHAKE
656
657
658 /**
659  * Serial 0 TX interrupt handler
660  */
661 DECLARE_ISR(USART0_UDRE_vect)
662 {
663         SER_STROBE_ON;
664
665         struct FIFOBuffer * const txfifo = &ser_handles[SER_UART0]->txfifo;
666
667         if (fifo_isempty(txfifo))
668         {
669                 SER_UART0_BUS_TXEND;
670 #ifndef SER_UART0_BUS_TXOFF
671                 UARTDescs[SER_UART0].sending = false;
672 #endif
673         }
674 #if CPU_AVR_ATMEGA64 || CPU_AVR_ATMEGA128 || CPU_AVR_ATMEGA103
675         else if (!IS_CTS_ON)
676         {
677                 // Disable rx interrupt and tx, enable CTS interrupt
678                 // UNTESTED
679                 UCSR0B = BV(BIT_RXCIE0) | BV(BIT_RXEN0) | BV(BIT_TXEN0);
680                 EIFR |= EIMSKF_CTS;
681                 EIMSK |= EIMSKF_CTS;
682         }
683 #endif
684         else
685         {
686                 char c = fifo_pop(txfifo);
687                 SER_UART0_BUS_TXCHAR(c);
688         }
689
690         SER_STROBE_OFF;
691 }
692
693 #ifdef SER_UART0_BUS_TXOFF
694 /**
695  * Serial port 0 TX complete interrupt handler.
696  *
697  * This IRQ is usually disabled.  The UDR-empty interrupt
698  * enables it when there's no more data to transmit.
699  * We need to wait until the last character has been
700  * transmitted before switching the 485 transceiver to
701  * receive mode.
702  *
703  * The txfifo might have been refilled by putchar() while
704  * we were waiting for the transmission complete interrupt.
705  * In this case, we must restart the UDR empty interrupt,
706  * otherwise we'd stop the serial port with some data
707  * still pending in the buffer.
708  */
709 DECLARE_ISR(SIG_UART0_TRANS)
710 {
711         SER_STROBE_ON;
712
713         struct FIFOBuffer * const txfifo = &ser_handles[SER_UART0]->txfifo;
714         if (fifo_isempty(txfifo))
715         {
716                 SER_UART0_BUS_TXOFF;
717                 UARTDescs[SER_UART0].sending = false;
718         }
719         else
720                 UCSR0B = BV(BIT_RXCIE0) | BV(BIT_UDRIE0) | BV(BIT_RXEN0) | BV(BIT_TXEN0);
721
722         SER_STROBE_OFF;
723 }
724 #endif /* SER_UART0_BUS_TXOFF */
725
726
727 #if AVR_HAS_UART1
728
729 /**
730  * Serial 1 TX interrupt handler
731  */
732 DECLARE_ISR(USART1_UDRE_vect)
733 {
734         SER_STROBE_ON;
735
736         struct FIFOBuffer * const txfifo = &ser_handles[SER_UART1]->txfifo;
737
738         if (fifo_isempty(txfifo))
739         {
740                 SER_UART1_BUS_TXEND;
741 #ifndef SER_UART1_BUS_TXOFF
742                 UARTDescs[SER_UART1].sending = false;
743 #endif
744         }
745 #if CPU_AVR_ATMEGA64 || CPU_AVR_ATMEGA128 || CPU_AVR_ATMEGA103
746         else if (!IS_CTS_ON)
747         {
748                 // Disable rx interrupt and tx, enable CTS interrupt
749                 // UNTESTED
750                 UCSR1B = BV(BIT_RXCIE1) | BV(BIT_RXEN1) | BV(BIT_TXEN1);
751                 EIFR |= EIMSKF_CTS;
752                 EIMSK |= EIMSKF_CTS;
753         }
754 #endif
755         else
756         {
757                 char c = fifo_pop(txfifo);
758                 SER_UART1_BUS_TXCHAR(c);
759         }
760
761         SER_STROBE_OFF;
762 }
763
764 #ifdef SER_UART1_BUS_TXOFF
765 /**
766  * Serial port 1 TX complete interrupt handler.
767  *
768  * \sa port 0 TX complete handler.
769  */
770 DECLARE_ISR(USART1_TX_vect)
771 {
772         SER_STROBE_ON;
773
774         struct FIFOBuffer * const txfifo = &ser_handles[SER_UART1]->txfifo;
775         if (fifo_isempty(txfifo))
776         {
777                 SER_UART1_BUS_TXOFF;
778                 UARTDescs[SER_UART1].sending = false;
779         }
780         else
781                 UCSR1B = BV(BIT_RXCIE1) | BV(BIT_UDRIE1) | BV(BIT_RXEN1) | BV(BIT_TXEN1);
782
783         SER_STROBE_OFF;
784 }
785 #endif /* SER_UART1_BUS_TXOFF */
786
787 #endif // AVR_HAS_UART1
788
789
790 /**
791  * Serial 0 RX complete interrupt handler.
792  *
793  * This handler is interruptible.
794  * Interrupt are reenabled as soon as recv complete interrupt is
795  * disabled. Using INTERRUPT() is troublesome when the serial
796  * is heavily loaded, because an interrupt could be retriggered
797  * when executing the handler prologue before RXCIE is disabled.
798  *
799  * \note The code that re-enables interrupts is commented out
800  *       because in some nasty cases the interrupt is retriggered.
801  *       This is probably due to the RXC flag being set before
802  *       RXCIE is cleared.  Unfortunately the RXC flag is read-only
803  *       and can't be cleared by code.
804  */
805 DECLARE_ISR(USART0_RX_vect)
806 {
807         SER_STROBE_ON;
808
809         /* Disable Recv complete IRQ */
810         //UCSR0B &= ~BV(RXCIE);
811         //IRQ_ENABLE;
812
813         /* Should be read before UDR */
814         ser_handles[SER_UART0]->status |= UCSR0A & (SERRF_RXSROVERRUN | SERRF_FRAMEERROR);
815
816         /* To clear the RXC flag we must _always_ read the UDR even when we're
817          * not going to accept the incoming data, otherwise a new interrupt
818          * will occur once the handler terminates.
819          */
820         char c = UDR0;
821         struct FIFOBuffer * const rxfifo = &ser_handles[SER_UART0]->rxfifo;
822
823         if (fifo_isfull(rxfifo))
824                 ser_handles[SER_UART0]->status |= SERRF_RXFIFOOVERRUN;
825         else
826         {
827                 fifo_push(rxfifo, c);
828 #if CONFIG_SER_HWHANDSHAKE
829                 if (fifo_isfull(rxfifo))
830                         RTS_OFF;
831 #endif
832         }
833
834         /* Reenable receive complete int */
835         //IRQ_DISABLE;
836         //UCSR0B |= BV(RXCIE);
837
838         SER_STROBE_OFF;
839 }
840
841
842 #if AVR_HAS_UART1
843
844 /**
845  * Serial 1 RX complete interrupt handler.
846  *
847  * This handler is interruptible.
848  * Interrupt are reenabled as soon as recv complete interrupt is
849  * disabled. Using INTERRUPT() is troublesome when the serial
850  * is heavily loaded, because an interrupt could be retriggered
851  * when executing the handler prologue before RXCIE is disabled.
852  *
853  * \see DECLARE_ISR(USART1_RX_vect)
854  */
855 DECLARE_ISR(USART1_RX_vect)
856 {
857         SER_STROBE_ON;
858
859         /* Disable Recv complete IRQ */
860         //UCSR1B &= ~BV(RXCIE);
861         //IRQ_ENABLE;
862
863         /* Should be read before UDR */
864         ser_handles[SER_UART1]->status |= UCSR1A & (SERRF_RXSROVERRUN | SERRF_FRAMEERROR);
865
866         /* To avoid an IRQ storm, we must _always_ read the UDR even when we're
867          * not going to accept the incoming data
868          */
869         char c = UDR1;
870         struct FIFOBuffer * const rxfifo = &ser_handles[SER_UART1]->rxfifo;
871         //ASSERT_VALID_FIFO(rxfifo);
872
873         if (UNLIKELY(fifo_isfull(rxfifo)))
874                 ser_handles[SER_UART1]->status |= SERRF_RXFIFOOVERRUN;
875         else
876         {
877                 fifo_push(rxfifo, c);
878 #if CONFIG_SER_HWHANDSHAKE
879                 if (fifo_isfull(rxfifo))
880                         RTS_OFF;
881 #endif
882         }
883         /* Re-enable receive complete int */
884         //IRQ_DISABLE;
885         //UCSR1B |= BV(RXCIE);
886
887         SER_STROBE_OFF;
888 }
889
890 #endif // AVR_HAS_UART1
891
892
893 /**
894  * SPI interrupt handler
895  */
896 DECLARE_ISR(SIG_SPI)
897 {
898         SER_STROBE_ON;
899
900         /* Read incoming byte. */
901         if (!fifo_isfull(&ser_handles[SER_SPI]->rxfifo))
902                 fifo_push(&ser_handles[SER_SPI]->rxfifo, SPDR);
903         /*
904          * FIXME
905         else
906                 ser_handles[SER_SPI]->status |= SERRF_RXFIFOOVERRUN;
907         */
908
909         /* Send */
910         if (!fifo_isempty(&ser_handles[SER_SPI]->txfifo))
911                 SPDR = fifo_pop(&ser_handles[SER_SPI]->txfifo);
912         else
913                 UARTDescs[SER_SPI].sending = false;
914
915         SER_STROBE_OFF;
916 }