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