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