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