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