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