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