Add values for new-style CONFIG_PRINTF option.
[bertos.git] / drv / ser_avr.c
1 /*!
2  * \file
3  * <!--
4  * Copyright 2000 Bernardo Innocenti <bernie@codewiz.org>
5  * Copyright 2003,2004 Develer S.r.l. (http://www.develer.com/)
6  * This file is part of DevLib - See devlib/README for information.
7  * -->
8  *
9  * \brief AVR UART and SPI I/O driver
10  *
11  * Rationale for project_ks hardware.
12  *
13  * The serial 0 on the board_kf board is used to communicate with the
14  * smart card, which has the TX and RX lines connected together. To
15  * allow the smart card to drive the RX line of the CPU the CPU TX has
16  * to be in a high impedance state.
17  * Whenever a transmission is done and there is nothing more to send
18  * the transmitter is turn off. The output pin is held in input with
19  * pull-up enabled, to avoid capturing noise from the nearby RX line.
20  *
21  * The line on the KBus port must keep sending data, even when
22  * there is nothing to transmit, because a burst data transfer
23  * generates noise on the audio channels.
24  * This is accomplished using the multiprocessor mode of the
25  * ATmega64/128 serial.
26  *
27  * The receiver keeps the MPCM bit always on. When useful data
28  * is trasmitted the address bit is set. The receiver hardware
29  * consider the frame as address info and receive it.
30  * When useless fill bytes are sent the address bit is cleared
31  * and the receiver will ignore them, avoiding useless triggering
32  * of RXC interrupt.
33  *
34  * \version $Id$
35  * \author Bernardo Innocenti <bernie@develer.com>
36  * \author Stefano Fedrigo <aleph@develer.com>
37  */
38
39 /*
40  * $Log$
41  * Revision 1.8  2004/07/29 22:57:09  bernie
42  * Several tweaks to reduce code size on ATmega8.
43  *
44  * Revision 1.7  2004/07/18 21:54:23  bernie
45  * Add ATmega8 support.
46  *
47  * Revision 1.5  2004/06/27 15:25:40  aleph
48  * Add missing callbacks for SPI;
49  * Change UNUSED() macro to new version with two args;
50  * Use TX line filling only on the correct KBUS serial port;
51  * Fix nasty IRQ disabling bug in recv complete hander for port 1.
52  *
53  * Revision 1.4  2004/06/03 11:27:09  bernie
54  * Add dual-license information.
55  *
56  * Revision 1.3  2004/06/02 21:35:24  aleph
57  * Serial enhancements: interruptible receive handler and 8 bit serial status for AVR; remove volatile attribute to FIFOBuffer, useless for new fifobuf routens
58  *
59  * Revision 1.2  2004/05/23 18:21:53  bernie
60  * Trim CVS logs and cleanup header info.
61  *
62  */
63
64 #include "ser.h"
65 #include "ser_p.h"
66 #include "kdebug.h"
67 #include "config.h"
68 #include "hw.h"
69 #include <mware/fifobuf.h>
70
71 #include <avr/signal.h>
72
73
74 /* Hardware handshake (RTS/CTS).  */
75 #ifndef RTS_ON
76 #define RTS_ON      do {} while (0)
77 #endif
78 #ifndef RTS_OFF
79 #define RTS_OFF     do {} while (0)
80 #endif
81 #ifndef IS_CTS_ON
82 #define IS_CTS_ON   true
83 #endif
84
85 /* External 485 transceiver on UART0 (to be overridden in "hw.h").  */
86 #ifndef SER_UART0_485_INIT
87 #define SER_UART0_485_INIT  do {} while (0)
88 #endif
89 #ifndef SER_UART0_485_TX
90 #define SER_UART0_485_TX    do {} while (0)
91 #endif
92
93
94 /* SPI port and pin configuration */
95 #define SPI_PORT      PORTB
96 #define SPI_DDR       DDRB
97 #define SPI_SCK_BIT   PORTB1
98 #define SPI_MOSI_BIT  PORTB2
99 #define SPI_MISO_BIT  PORTB3
100
101
102 #if defined(__AVR_ATmega64__) || defined(__AVR_ATmega128__)
103         #define AVR_HAS_UART1 1
104 #elif defined(__AVR_ATmega8__)
105         #define AVR_HAS_UART1 0
106         #define UCSR0A UCSRA
107         #define UCSR0B UCSRB
108         #define UCSR0C UCSRC
109         #define UDR0   UDR
110         #define UBRR0L UBRRL
111         #define UBRR0H UBRRH
112         #define SIG_UART0_DATA SIG_UART_DATA
113         #define SIG_UART0_RECV SIG_UART_RECV
114 #elif defined(__AVR_ATmega103__)
115         #define AVR_HAS_UART1 0
116         #define UCSR0B UCR
117         #define UDR0   UDR
118         #define UCSR0A USR
119         #define UBRR0L UBRR
120         #define SIG_UART0_DATA SIG_UART_DATA
121         #define SIG_UART0_RECV SIG_UART_RECV
122 #else
123         #error Unknown architecture
124 #endif
125
126
127 /* Transmission fill byte */
128 #define SER_FILL_BYTE 0xAA
129
130
131 /* From the high-level serial driver */
132 extern struct Serial ser_handles[SER_CNT];
133
134 /*
135  * These are to trick GCC into *not* using
136  * absolute addressing mode when accessing
137  * ser_handles, which is very expensive.
138  *
139  * Accessing through these pointers generates
140  * much shorter (and hopefully faster) code.
141  */
142 struct Serial *ser_uart0 = &ser_handles[SER_UART0];
143 #if AVR_HAS_UART1
144 struct Serial *ser_uart1 = &ser_handles[SER_UART1];
145 #endif
146 struct Serial *ser_spi = &ser_handles[SER_SPI];
147
148
149 static void uart0_enabletxirq(UNUSED(struct SerialHardware *, ctx))
150 {
151 #if CONFIG_SER_TXFILL && (CONFIG_KBUS_PORT == 0)
152         UCSR0B = BV(RXCIE) | BV(UDRIE) | BV(RXEN) | BV(TXEN) | BV(UCSZ2);
153 #elif defined(SER_UART0_485_TX)
154         /* Disable receiver, enable transmitter, switch 485 transceiver. */
155         UCSR0B = BV(UDRIE) | BV(TXEN);
156         SER_UART0_485_TX;
157 #else
158         UCSR0B = BV(RXCIE) | BV(UDRIE) | BV(RXEN) | BV(TXEN);
159 #endif
160 }
161
162 static void uart0_init(UNUSED(struct SerialHardware *, _hw), UNUSED(struct Serial *, ser))
163 {
164 #if defined(ARCH_BOARD_KS) && (ARCH & ARCH_BOARD_KS)
165         /* Set TX port as input with pull-up enabled to avoid
166            noise on the remote RX when TX is disabled. */
167         cpuflags_t flags;
168         DISABLE_IRQSAVE(flags);
169         DDRE &= ~BV(PORTE1);
170         PORTE |= BV(PORTE1);
171         ENABLE_IRQRESTORE(flags);
172 #endif /* ARCH_BOARD_KS */
173
174 #if CONFIG_SER_TXFILL && (CONFIG_KBUS_PORT == 0)
175         /*!
176          * Set multiprocessor mode and 9 bit data frame.
177          * The receiver keep MPCM bit always on. When useful data
178          * is trasmitted the ninth bit is set and the receiver receive
179          * the frame.
180          * When useless fill bytes are sent the ninth bit is cleared
181          * and the receiver will ignore them.
182          */
183         UCSR0A = BV(MPCM);
184         UCSR0B = BV(RXCIE) | BV(RXEN) | BV(UCSZ2);
185 #else
186         UCSR0B = BV(RXCIE) | BV(RXEN);
187 #endif
188
189         SER_UART0_485_INIT;
190         RTS_ON;
191 }
192
193 static void uart0_cleanup(UNUSED(struct SerialHardware *, _hw))
194 {
195         UCSR0B = 0;
196 }
197
198 static void uart0_setbaudrate(UNUSED(struct SerialHardware *, _hw), unsigned long rate)
199 {
200         /* Compute baud-rate period */
201         uint16_t period = (((CLOCK_FREQ / 16UL) + (rate / 2)) / rate) - 1;
202         DB(kprintf("uart0_setbaudrate(rate=%lu): period=%d\n", rate, period);)
203
204 #ifndef __AVR_ATmega103__
205         UBRR0H = (period) >> 8;
206 #endif
207         UBRR0L = (period);
208 }
209
210 static void uart0_setparity(UNUSED(struct SerialHardware *, _hw), int parity)
211 {
212 #ifndef __AVR_ATmega103__
213         UCSR0C |= (parity) << UPM0;
214 #endif
215 }
216
217 #if AVR_HAS_UART1
218
219 static void uart1_enabletxirq(UNUSED(struct SerialHardware *, _hw))
220 {
221 #if CONFIG_SER_TXFILL && (CONFIG_KBUS_PORT == 1)
222         UCSR1B = BV(RXCIE) | BV(UDRIE) | BV(RXEN) | BV(TXEN) | BV(UCSZ2);
223 #else
224         UCSR1B = BV(RXCIE) | BV(UDRIE) | BV(RXEN) | BV(TXEN);
225 #endif
226 }
227
228 static void uart1_init(UNUSED(struct SerialHardware *, _hw), UNUSED(struct Serial *, ser))
229 {
230         /* Set TX port as input with pull-up enabled to avoid
231          * noise on the remote RX when TX is disabled */
232         cpuflags_t flags;
233         DISABLE_IRQSAVE(flags);
234         DDRD &= ~BV(PORTD3);
235         PORTD |= BV(PORTD3);
236         ENABLE_IRQRESTORE(flags);
237
238 #if CONFIG_SER_TXFILL && (CONFIG_KBUS_PORT == 1)
239         /*! See comment in uart0_init() */
240         UCSR1A = BV(MPCM);
241         UCSR1B = BV(RXCIE) | BV(RXEN) | BV(UCSZ2);
242 #else
243         UCSR1B = BV(RXCIE) | BV(RXEN);
244 #endif
245
246         RTS_ON;
247 }
248
249 static void uart1_cleanup(UNUSED(struct SerialHardware *, _hw))
250 {
251         UCSR1B = 0;
252 }
253
254 static void uart1_setbaudrate(UNUSED(struct SerialHardware *, _hw), unsigned long rate)
255 {
256         /* Compute baud-rate period */
257         uint16_t period = (((CLOCK_FREQ / 16UL) + (rate / 2)) / rate) - 1;
258         DB(kprintf("uart1_setbaudrate(rate=%ld): period=%d\n", rate, period);)
259
260         UBRR1H = (period) >> 8;
261         UBRR1L = (period);
262 }
263
264 static void uart1_setparity(UNUSED(struct SerialHardware *, _hw), int parity)
265 {
266         UCSR1C |= (parity) << UPM0;
267 }
268
269 #endif // AVR_HAS_UART1
270
271
272 static void spi_init(UNUSED(struct SerialHardware *, _hw), UNUSED(struct Serial *, ser))
273 {
274         /*
275          * Set MOSI and SCK ports out, MISO in.
276          *
277          * The ATmega64/128 datasheet explicitly states that the input/output
278          * state of the SPI pins is not significant, as when the SPI is
279          * active the I/O port are overrided.
280          * This is *blatantly FALSE*.
281          *
282          * Moreover, the MISO pin on the board_kc *must* be in high impedance
283          * state even when the SPI is off, because the line is wired together
284          * with the KBus serial RX, and the transmitter of the slave boards
285          * would be unable to drive the line.
286          */
287         SPI_DDR |= BV(SPI_MOSI_BIT) | BV(SPI_SCK_BIT);
288         SPI_DDR &= ~BV(SPI_MISO_BIT);
289         /* Enable SPI, IRQ on, Master, CPU_CLOCK/16 */
290         SPCR = BV(SPE) | BV(SPIE) | BV(MSTR) | BV(SPR0);
291 }
292
293 static void spi_cleanup(UNUSED(struct SerialHardware *, _hw))
294 {
295         SPCR = 0;
296         /* Set all pins as inputs */
297         SPI_DDR &= ~(BV(SPI_MISO_BIT) | BV(SPI_MOSI_BIT) | BV(SPI_SCK_BIT));
298 }
299
300 static void spi_setbaudrate(UNUSED(struct SerialHardware *, _hw), UNUSED(unsigned long, rate))
301 {
302         // nop
303 }
304
305 static void spi_setparity(UNUSED(struct SerialHardware *, _hw), UNUSED(int, parity))
306 {
307         // nop
308 }
309
310
311 #if CONFIG_SER_HWHANDSHAKE
312
313 //! This interrupt is triggered when the CTS line goes high
314 SIGNAL(SIG_CTS)
315 {
316         // Re-enable UDR empty interrupt and TX, then disable CTS interrupt
317         UCSR0B = BV(RXCIE) | BV(UDRIE) | BV(RXEN) | BV(TXEN);
318         cbi(EIMSK, EIMSKB_CTS);
319 }
320
321 #endif // CONFIG_SER_HWHANDSHAKE
322
323
324 /*!
325  * Serial 0 TX interrupt handler
326  */
327 SIGNAL(SIG_UART0_DATA)
328 {
329         struct FIFOBuffer * const txfifo = &ser_uart0->txfifo;
330
331         if (fifo_isempty(txfifo))
332         {
333 #if CONFIG_SER_TXFILL && (CONFIG_KBUS_PORT == 0)
334                 /*
335                  * To avoid audio interference: always transmit useless char.
336                  * Send the byte with the ninth bit cleared, the receiver in MCPM mode
337                  * will ignore it.
338                  */
339                 UCSR0B &= ~BV(TXB8);
340                 UDR0 = SER_FILL_BYTE;
341 #elif defined(SER_UART0_485_RX)
342                 /*
343                  * - Disable UDR empty interrupt
344                  * - Disable the transmitter (the in-progress transfer will complete)
345                  * - Enable the transmit complete interrupt for the 485 tranceiver.
346                  */
347                 UCSR0B = BV(TXCIE);
348 #else
349                 /* Disable UDR empty interrupt and transmitter */
350                 UCSR0B = BV(RXCIE) | BV(RXEN);
351 #endif
352         }
353 #if CONFIG_SER_HWHANDSHAKE
354         else if (!IS_CTS_ON)
355         {
356                 // Disable rx interrupt and tx, enable CTS interrupt
357                 UCSR0B = BV(RXCIE) | BV(RXEN);
358                 sbi(EIFR, EIMSKB_CTS);
359                 sbi(EIMSK, EIMSKB_CTS);
360         }
361 #endif // CONFIG_SER_HWHANDSHAKE
362         else
363         {
364 #if CONFIG_SER_TXFILL && (CONFIG_KBUS_PORT == 0)
365                 /* Send with ninth bit set. Receiver in MCPM mode will receive it */
366                 UCSR0B |= BV(TXB8);
367 #endif
368                 UDR0 = fifo_pop(txfifo);
369         }
370 }
371
372 #ifdef SER_UART0_485_RX
373 /*!
374  * Serial port 0 TX complete interrupt handler.
375  *
376  * This IRQ is usually disabled.  The UDR-empty interrupt
377  * enables it when there's no more data to transmit.
378  * We need to wait until the last character has been
379  * transmitted before switching the 485 transceiver to
380  * receive mode.
381  */
382 SIGNAL(SIG_UART0_TRANS)
383 {
384         /* Turn the 485 tranceiver into receive mode. */
385         SER_UART0_485_RX;
386
387         /* Enable UART receiver and receive interrupt. */
388         UCSR0B = BV(RXCIE) | BV(RXEN);
389 }
390 #endif /* SER_UART0_485_RX */
391
392
393 #if AVR_HAS_UART1
394
395 /*!
396  * Serial 1 TX interrupt handler
397  */
398 SIGNAL(SIG_UART1_DATA)
399 {
400         struct FIFOBuffer * const txfifo = &ser_uart1->txfifo;
401
402         if (fifo_isempty(txfifo))
403         {
404 #if CONFIG_SER_TXFILL && (CONFIG_KBUS_PORT == 1)
405                 /*
406                  * To avoid audio interference: always transmit useless char.
407                  * Send the byte with the ninth bit cleared, the receiver in MCPM mode
408                  * will ignore it.
409                  */
410                 UCSR1B &= ~BV(TXB8);
411                 UDR1 = SER_FILL_BYTE;
412 #else
413                 /* Disable UDR empty interrupt and transmitter */
414                 UCSR1B = BV(RXCIE) | BV(RXEN);
415 #endif
416         }
417 #if CONFIG_SER_HWHANDSHAKE
418         else if (IS_CTS_OFF)
419         {
420                 // Disable rx interrupt and tx, enable CTS interrupt
421                 UCSR1B = BV(RXCIE) | BV(RXEN);
422                 sbi(EIFR, EIMSKB_CTS);
423                 sbi(EIMSK, EIMSKB_CTS);
424         }
425 #endif // CONFIG_SER_HWHANDSHAKE
426         else
427         {
428 #if CONFIG_SER_TXFILL && (CONFIG_KBUS_PORT == 1)
429                 /* Send with ninth bit set. Receiver in MCPM mode will receive it */
430                 UCSR1B |= BV(TXB8);
431 #endif
432                 UDR1 = fifo_pop(txfifo);
433         }
434 }
435 #endif // AVR_HAS_UART1
436
437
438 /*!
439  * Serial 0 RX complete interrupt handler.
440  *
441  * This handler is interruptible.
442  * Interrupt are reenabled as soon as recv complete interrupt is
443  * disabled. Using INTERRUPT() is troublesome when the serial
444  * is heavily loaded, because an interrupt could be retriggered
445  * when executing the handler prologue before RXCIE is disabled.
446  */
447 SIGNAL(SIG_UART0_RECV)
448 {
449         /* Disable Recv complete IRQ */
450         UCSR0B &= ~BV(RXCIE);
451         ENABLE_INTS;
452
453         /* Should be read before UDR */
454         ser_uart0->status |= UCSR0A & (SERRF_RXSROVERRUN | SERRF_FRAMEERROR);
455
456         /* To clear the RXC flag we must _always_ read the UDR even when we're
457          * not going to accept the incoming data, otherwise a new interrupt
458          * will occur once the handler terminates.
459          */
460         char c = UDR0;
461         struct FIFOBuffer * const rxfifo = &ser_uart0->rxfifo;
462
463         if (fifo_isfull(rxfifo))
464                 ser_uart0->status |= SERRF_RXFIFOOVERRUN;
465         else
466         {
467                 fifo_push(rxfifo, c);
468 #if CONFIG_SER_HWHANDSHAKE
469                 if (fifo_isfull(rxfifo))
470                         RTS_OFF;
471 #endif
472         }
473
474         /* Reenable receive complete int */
475         UCSR0B |= BV(RXCIE);
476 }
477
478
479 #if AVR_HAS_UART1
480
481 /*!
482  * Serial 1 RX complete interrupt handler.
483  *
484  * This handler is interruptible.
485  * Interrupt are reenabled as soon as recv complete interrupt is
486  * disabled. Using INTERRUPT() is troublesome when the serial
487  * is heavily loaded, because an interrupt could be retriggered
488  * when executing the handler prologue before RXCIE is disabled.
489  */
490 SIGNAL(SIG_UART1_RECV)
491 {
492         /* Disable Recv complete IRQ */
493         UCSR1B &= ~BV(RXCIE);
494         ENABLE_INTS;
495
496         /* Should be read before UDR */
497         ser_uart1->status |= UCSR1A & (SERRF_RXSROVERRUN | SERRF_FRAMEERROR);
498
499         /* To avoid an IRQ storm, we must _always_ read the UDR even when we're
500          * not going to accept the incoming data
501          */
502         char c = UDR1;
503         struct FIFOBuffer * const rxfifo = &ser_uart1->rxfifo;
504
505         if (fifo_isfull(rxfifo))
506                 ser_uart1->status |= SERRF_RXFIFOOVERRUN;
507         else
508         {
509                 fifo_push(rxfifo, c);
510 #if CONFIG_SER_HWHANDSHAKE
511                 if (fifo_isfull(rxfifo))
512                         RTS_OFF;
513 #endif
514         }
515         /* Reenable receive complete int */
516         UCSR1B |= BV(RXCIE);
517 }
518
519 #endif // AVR_HAS_UART1
520
521
522 /*
523  * SPI Flag: true if we are transmitting/receiving with the SPI.
524  *
525  * This kludge is necessary because the SPI sends and receives bytes
526  * at the same time and the SPI IRQ is unique for send/receive.
527  * The only way to start transmission is to write data in SPDR (this
528  * is done by spi_starttx()). We do this *only* if a transfer is
529  * not already started.
530  */
531 static volatile bool spi_sending = false;
532
533 static void spi_starttx(UNUSED(struct SerialHardware *, ctx))
534 {
535         cpuflags_t flags;
536
537         DISABLE_IRQSAVE(flags);
538
539         /* Send data only if the SPI is not already transmitting */
540         if (!spi_sending && !fifo_isempty(&ser_spi->txfifo))
541         {
542                 SPDR = fifo_pop(&ser_spi->txfifo);
543                 spi_sending = true;
544         }
545
546         ENABLE_IRQRESTORE(flags);
547 }
548
549 /*!
550  * SPI interrupt handler
551  */
552 SIGNAL(SIG_SPI)
553 {
554         /* Read incoming byte. */
555         if (!fifo_isfull(&ser_spi->rxfifo))
556                 fifo_push(&ser_spi->rxfifo, SPDR);
557         /*
558          * FIXME
559         else
560                 ser_spi->status |= SERRF_RXFIFOOVERRUN;
561         */
562
563         /* Send */
564         if (!fifo_isempty(&ser_spi->txfifo))
565                 SPDR = fifo_pop(&ser_spi->txfifo);
566         else
567                 spi_sending = false;
568 }
569
570
571 static const struct SerialHardwareVT UART0_VT =
572 {
573         .init = uart0_init,
574         .cleanup = uart0_cleanup,
575         .setbaudrate = uart0_setbaudrate,
576         .setparity = uart0_setparity,
577         .enabletxirq = uart0_enabletxirq,
578 };
579
580 #if AVR_HAS_UART1
581 static const struct SerialHardwareVT UART1_VT =
582 {
583         .init = uart1_init,
584         .cleanup = uart1_cleanup,
585         .setbaudrate = uart1_setbaudrate,
586         .setparity = uart1_setparity,
587         .enabletxirq = uart1_enabletxirq,
588 };
589 #endif // AVR_HAS_UART1
590
591 static const struct SerialHardwareVT SPI_VT =
592 {
593         .init = spi_init,
594         .cleanup = spi_cleanup,
595         .setbaudrate = spi_setbaudrate,
596         .setparity = spi_setparity,
597         .enabletxirq = spi_starttx,
598 };
599
600 static struct SerialHardware UARTDescs[SER_CNT] =
601 {
602         { .table = &UART0_VT },
603 #if AVR_HAS_UART1
604         { .table = &UART1_VT },
605 #endif
606         { .table = &SPI_VT   },
607 };
608
609 struct SerialHardware* ser_hw_getdesc(int unit)
610 {
611         ASSERT(unit < SER_CNT);
612         return &UARTDescs[unit];
613 }