src-avr: Disable USB interrupts while we're not interested
[fw/altos] / src-avr / ao_usb_avr.c
1 /*
2  * Copyright © 2011 Keith Packard <keithp@keithp.com>
3  *
4  * This program is free software; you can redistribute it and/or modify
5  * it under the terms of the GNU General Public License as published by
6  * the Free Software Foundation; version 2 of the License.
7  *
8  * This program is distributed in the hope that it will be useful, but
9  * WITHOUT ANY WARRANTY; without even the implied warranty of
10  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
11  * General Public License for more details.
12  *
13  * You should have received a copy of the GNU General Public License along
14  * with this program; if not, write to the Free Software Foundation, Inc.,
15  * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA.
16  */
17
18 #include "ao.h"
19 #include "ao_usb.h"
20
21 #define USB_DEBUG 0
22
23 #if USB_DEBUG
24 #define debug(format, args...)  printf(format, ## args)
25 #else
26 #define debug(format, args...)
27 #endif
28
29 struct ao_task __xdata ao_usb_task;
30
31 struct ao_usb_setup {
32         uint8_t         dir_type_recip;
33         uint8_t         request;
34         uint16_t        value;
35         uint16_t        index;
36         uint16_t        length;
37 } __xdata ao_usb_setup;
38
39 static __xdata uint8_t  ao_usb_ep0_state;
40 static const uint8_t * __xdata ao_usb_ep0_in_data;
41 static __xdata uint8_t  ao_usb_ep0_in_len;
42 static __xdata uint8_t  ao_usb_ep0_in_pending;
43 static __xdata uint8_t  ao_usb_addr_pending;
44 static __xdata uint8_t  ao_usb_ep0_in_buf[2];
45 static __xdata uint8_t  ao_usb_ep0_out_len;
46 static __xdata uint8_t *__xdata ao_usb_ep0_out_data;
47
48 static __xdata uint8_t  ao_usb_in_flushed;
49 static __xdata uint8_t  ao_usb_running;
50 static __xdata uint8_t  ao_usb_configuration;
51
52 void
53 ao_usb_set_address(uint8_t address)
54 {
55         UDADDR = (0 << ADDEN) | address;
56         ao_usb_addr_pending = 1;
57 }
58
59 #define EP_SIZE(s)      ((s) == 64 ? 0x30 :     \
60                         ((s) == 32 ? 0x20 :     \
61                         ((s) == 16 ? 0x10 :     \
62                                      0x00)))
63
64 static void
65 ao_usb_dump_ep(uint8_t ep)
66 {
67         UENUM = ep;
68         debug ("EP %d: UECONX %02x UECFG0X %02x UECFG1X %02x UEIENX %02x UESTA0X %02x UESTA1X %02X\n",
69                 ep, UECONX, UECFG0X, UECFG1X, UEIENX, UESTA0X, UESTA1X);
70 }
71
72 static void
73 ao_usb_set_ep0(void)
74 {
75         debug ("set_ep0\n");
76         /* Set the CONTROL max packet size, single buffered */
77         UENUM = 0;
78         UECONX = (1 << EPEN);                                   /* Enable */
79
80         UECFG0X = ((0 << EPTYPE0) |                             /* Control */
81                    (0 << EPDIR));                               /* Out (ish) */
82
83         UECFG1X = (EP_SIZE(AO_USB_CONTROL_SIZE) |               /* Size */
84                    (0 << EPBK0) |                               /* Single bank */
85                    (1 << ALLOC));
86
87         UEIENX = ((1 << RXSTPE) |                               /* Enable SETUP interrupt */
88                   (1 << RXOUTE));                               /* Enable OUT interrupt */
89
90 //      ao_usb_dump_ep(0);
91         ao_usb_addr_pending = 0;
92 }
93
94 static void
95 ao_usb_set_configuration(void)
96 {
97         /* Set the IN max packet size, double buffered */
98         UENUM = AO_USB_IN_EP;
99         UECONX = (1 << EPEN);                                   /* Enable */
100
101         UECFG0X = ((2 << EPTYPE0) |                             /* Bulk */
102                    (1 << EPDIR));                               /* In */
103
104         UECFG1X = (EP_SIZE(AO_USB_IN_SIZE) |                    /* Size */
105                    (1 << EPBK0) |                               /* Double bank */
106                    (1 << ALLOC));                               /* Allocate */
107
108 #if 0
109         UEIENX = ((1 << TXINE));                                /* Enable IN complete interrupt */
110 #endif
111
112         ao_usb_dump_ep(AO_USB_IN_EP);
113
114         /* Set the OUT max packet size, double buffered */
115         UENUM = AO_USB_OUT_EP;
116         UECONX |= (1 << EPEN);                                  /* Enable */
117
118         UECFG0X = ((2 << EPTYPE0) |                             /* Bulk */
119                    (0 << EPDIR));                               /* Out */
120
121         UECFG1X = (EP_SIZE(AO_USB_OUT_SIZE) |                   /* Size */
122                    (1 << EPBK0) |                               /* Double bank */
123                    (1 << ALLOC));                               /* Allocate */
124
125         UEIENX = ((1 << RXOUTE));                               /* Enable OUT complete interrupt */
126
127         ao_usb_dump_ep(AO_USB_OUT_EP);
128         ao_usb_running = 1;
129 }
130
131 ISR(USB_GEN_vect)
132 {
133         ao_wakeup(&ao_usb_task);
134 }
135
136
137 __xdata static struct ao_usb_line_coding ao_usb_line_coding = {115200, 0, 0, 8};
138
139 /* Walk through the list of descriptors and find a match
140  */
141 static void
142 ao_usb_get_descriptor(uint16_t value)
143 {
144         const uint8_t           *__xdata descriptor;
145         __xdata uint8_t         type = value >> 8;
146         __xdata uint8_t         index = value;
147
148         descriptor = ao_usb_descriptors;
149         while (descriptor[0] != 0) {
150                 if (descriptor[1] == type && index-- == 0) {
151                         if (type == AO_USB_DESC_CONFIGURATION)
152                                 ao_usb_ep0_in_len = descriptor[2];
153                         else
154                                 ao_usb_ep0_in_len = descriptor[0];
155                         ao_usb_ep0_in_data = descriptor;
156                         break;
157                 }
158                 descriptor += descriptor[0];
159         }
160 }
161
162 static void
163 ao_usb_ep0_set_in_pending(uint8_t in_pending)
164 {
165         ao_usb_ep0_in_pending = in_pending;
166
167         if (in_pending) {
168                 UENUM = 0;
169                 UEIENX = ((1 << RXSTPE) | (1 << RXOUTE) | (1 << TXINE));        /* Enable IN interrupt */
170         }
171 }
172
173 /* Send an IN data packet */
174 static void
175 ao_usb_ep0_flush(void)
176 {
177         __xdata uint8_t this_len;
178
179         cli();
180         UENUM = 0;
181         if (!(UEINTX & (1 << TXINI))) {
182                 debug("EP0 not accepting IN data\n");
183                 ao_usb_ep0_set_in_pending(1);
184         } else {
185                 this_len = ao_usb_ep0_in_len;
186                 if (this_len > AO_USB_CONTROL_SIZE)
187                         this_len = AO_USB_CONTROL_SIZE;
188
189                 ao_usb_ep0_in_len -= this_len;
190
191                 /* Set IN interrupt enable */
192                 if (ao_usb_ep0_in_len == 0 && this_len != AO_USB_CONTROL_SIZE)
193                         ao_usb_ep0_set_in_pending(0);
194                 else
195                         ao_usb_ep0_set_in_pending(1);
196
197                 debug ("Flush EP0 len %d:", this_len);
198                 while (this_len--) {
199                         uint8_t c = *ao_usb_ep0_in_data++;
200                         debug(" %02x", c);
201                         UEDATX = c;
202                 }
203                 debug ("\n");
204
205                 /* Clear the TXINI bit to send the packet */
206                 UEINTX &= ~(1 << TXINI);
207         }
208         sei();
209 }
210
211 /* Read data from the ep0 OUT fifo */
212 static void
213 ao_usb_ep0_fill(uint8_t len, uint8_t ack)
214 {
215         if (len > ao_usb_ep0_out_len)
216                 len = ao_usb_ep0_out_len;
217         ao_usb_ep0_out_len -= len;
218
219 //      debug ("EP0 UEINTX %02x UEBCLX %d UEBCHX %d\n",
220 //              UEINTX, UEBCLX, UEBCHX);
221         /* Pull all of the data out of the packet */
222         debug ("Fill EP0 len %d:", len);
223         UENUM = 0;
224         while (len--) {
225                 uint8_t c = UEDATX;
226                 *ao_usb_ep0_out_data++ = c;
227                 debug (" %02x", c);
228         }
229         debug ("\n");
230
231         /* ACK the packet */
232         UEINTX &= ~ack;
233 }
234
235 void
236 ao_usb_ep0_queue_byte(uint8_t a)
237 {
238         ao_usb_ep0_in_buf[ao_usb_ep0_in_len++] = a;
239 }
240
241 static void
242 ao_usb_ep0_setup(void)
243 {
244         /* Pull the setup packet out of the fifo */
245         ao_usb_ep0_out_data = (__xdata uint8_t *) &ao_usb_setup;
246         ao_usb_ep0_out_len = 8;
247         ao_usb_ep0_fill(8, (1 << RXSTPI) | (1 << RXOUTI) | (1 << TXINI));
248         if (ao_usb_ep0_out_len != 0) {
249                 debug ("invalid setup packet length\n");
250                 return;
251         }
252
253         /* Figure out how to ACK the setup packet */
254         if (ao_usb_setup.dir_type_recip & AO_USB_DIR_IN) {
255                 if (ao_usb_setup.length)
256                         ao_usb_ep0_state = AO_USB_EP0_DATA_IN;
257                 else
258                         ao_usb_ep0_state = AO_USB_EP0_IDLE;
259         } else {
260                 if (ao_usb_setup.length)
261                         ao_usb_ep0_state = AO_USB_EP0_DATA_OUT;
262                 else
263                         ao_usb_ep0_state = AO_USB_EP0_IDLE;
264         }
265 /*
266         UENUM = 0;
267         if (ao_usb_ep0_state == AO_USB_EP0_IDLE)
268                 USBCS0 = USBCS0_CLR_OUTPKT_RDY | USBCS0_DATA_END;
269         else
270                 USBCS0 = USBCS0_CLR_OUTPKT_RDY;
271 */
272
273         ao_usb_ep0_in_data = ao_usb_ep0_in_buf;
274         ao_usb_ep0_in_len = 0;
275         switch(ao_usb_setup.dir_type_recip & AO_USB_SETUP_TYPE_MASK) {
276         case AO_USB_TYPE_STANDARD:
277                 debug ("Standard setup packet\n");
278                 switch(ao_usb_setup.dir_type_recip & AO_USB_SETUP_RECIP_MASK) {
279                 case AO_USB_RECIP_DEVICE:
280                         debug ("Device setup packet\n");
281                         switch(ao_usb_setup.request) {
282                         case AO_USB_REQ_GET_STATUS:
283                                 debug ("get status\n");
284                                 ao_usb_ep0_queue_byte(0);
285                                 ao_usb_ep0_queue_byte(0);
286                                 break;
287                         case AO_USB_REQ_SET_ADDRESS:
288                                 debug ("set address %d\n", ao_usb_setup.value);
289                                 ao_usb_set_address(ao_usb_setup.value);
290                                 break;
291                         case AO_USB_REQ_GET_DESCRIPTOR:
292                                 debug ("get descriptor %d\n", ao_usb_setup.value);
293                                 ao_usb_get_descriptor(ao_usb_setup.value);
294                                 break;
295                         case AO_USB_REQ_GET_CONFIGURATION:
296                                 debug ("get configuration %d\n", ao_usb_configuration);
297                                 ao_usb_ep0_queue_byte(ao_usb_configuration);
298                                 break;
299                         case AO_USB_REQ_SET_CONFIGURATION:
300                                 ao_usb_configuration = ao_usb_setup.value;
301                                 debug ("set configuration %d\n", ao_usb_configuration);
302                                 ao_usb_set_configuration();
303                                 break;
304                         }
305                         break;
306                 case AO_USB_RECIP_INTERFACE:
307 #ifndef AVR
308                         #pragma disable_warning 110
309 #endif
310                         debug ("Interface setup packet\n");
311                         switch(ao_usb_setup.request) {
312                         case AO_USB_REQ_GET_STATUS:
313                                 ao_usb_ep0_queue_byte(0);
314                                 ao_usb_ep0_queue_byte(0);
315                                 break;
316                         case AO_USB_REQ_GET_INTERFACE:
317                                 ao_usb_ep0_queue_byte(0);
318                                 break;
319                         case AO_USB_REQ_SET_INTERFACE:
320                                 break;
321                         }
322                         break;
323                 case AO_USB_RECIP_ENDPOINT:
324                         debug ("Endpoint setup packet\n");
325                         switch(ao_usb_setup.request) {
326                         case AO_USB_REQ_GET_STATUS:
327                                 ao_usb_ep0_queue_byte(0);
328                                 ao_usb_ep0_queue_byte(0);
329                                 break;
330                         }
331                         break;
332                 }
333                 break;
334         case AO_USB_TYPE_CLASS:
335                 debug ("Class setup packet\n");
336                 switch (ao_usb_setup.request) {
337                 case SET_LINE_CODING:
338                         debug ("set line coding\n");
339                         ao_usb_ep0_out_len = 7;
340                         ao_usb_ep0_out_data = (__xdata uint8_t *) &ao_usb_line_coding;
341                         break;
342                 case GET_LINE_CODING:
343                         debug ("get line coding\n");
344                         ao_usb_ep0_in_len = 7;
345                         ao_usb_ep0_in_data = (uint8_t *) &ao_usb_line_coding;
346                         break;
347                 case SET_CONTROL_LINE_STATE:
348                         break;
349                 }
350                 break;
351         }
352         if (ao_usb_ep0_state != AO_USB_EP0_DATA_OUT) {
353                 if (ao_usb_setup.length < ao_usb_ep0_in_len)
354                         ao_usb_ep0_in_len = ao_usb_setup.length;
355                 debug ("Start ep0 in delivery %d\n", ao_usb_ep0_in_len);
356                 ao_usb_ep0_set_in_pending(1);
357         }
358 }
359
360 /* End point 0 receives all of the control messages. */
361 static void
362 ao_usb_ep0(void)
363 {
364         uint8_t intx, udint;
365
366         debug ("usb task started\n");
367         ao_usb_ep0_state = AO_USB_EP0_IDLE;
368         for (;;) {
369                 cli();
370                 for (;;) {
371                         udint = UDINT;
372                         UDINT = 0;
373 //                      debug ("UDINT %02x\n", udint);
374                         if (udint & (1 << EORSTI)) {
375                                 ao_usb_configuration = 0;
376                                 ao_usb_set_ep0();
377                         }
378                         UENUM = 0;
379                         intx = UEINTX;
380 //                      debug ("UEINTX %02x\n", intx);
381                         if (intx & ((1 << RXSTPI) | (1 << RXOUTI)))
382                                 break;
383                         if ((intx & (1 << TXINI))) {
384                                 if (ao_usb_ep0_in_pending)
385                                         break;
386                                 else
387                                 {
388                                         if (ao_usb_addr_pending) {
389                                                 UDADDR |= (1 << ADDEN);
390                                                 ao_usb_addr_pending = 0;
391                                         }
392                                         UEIENX = ((1 << RXSTPE) | (1 << RXOUTE));       /* Disable IN interrupt */
393                                 }
394                         }
395 //                      debug ("usb task sleeping...\n");
396                         ao_sleep(&ao_usb_task);
397                 }
398                 sei();
399 //              debug ("UEINTX for ep0 is %02x\n", intx);
400                 if (intx & (1 << RXSTPI)) {
401                         ao_usb_ep0_setup();
402                 }
403                 if (intx & (1 << RXOUTI)) {
404                         ao_usb_ep0_fill(UEBCLX, (1 << RXOUTI));
405                         ao_usb_ep0_set_in_pending(1);
406                 }
407                 if (intx & (1 << TXINI) && ao_usb_ep0_in_pending) {
408                         debug ("continue sending ep0 IN data\n");
409                         ao_usb_ep0_flush();
410                 }
411         }
412 }
413
414 /* Wait for a free IN buffer */
415 static void
416 ao_usb_in_wait(void)
417 {
418         for (;;) {
419                 /* Check if the current buffer is writable */
420                 UENUM = AO_USB_IN_EP;
421                 if (UEINTX & (1 << RWAL))
422                         break;
423
424                 cli();
425                 /* Wait for an IN buffer to be ready */
426                 for (;;) {
427                         UENUM = AO_USB_IN_EP;
428                         if ((UEINTX & (1 << TXINI)))
429                                 break;
430                         UEIENX = (1 << TXINE);
431                         ao_sleep(&ao_usb_in_flushed);
432                 }
433                 /* Ack the interrupt */
434                 UEINTX &= ~(1 << TXINI);
435                 sei();
436         }
437 }
438
439 /* Queue the current IN buffer for transmission */
440 static void
441 ao_usb_in_send(void)
442 {
443         UENUM = AO_USB_IN_EP;
444         UEINTX &= ~(1 << FIFOCON);
445 }
446
447 void
448 ao_usb_flush(void) __critical
449 {
450         if (!ao_usb_running)
451                 return;
452
453         /* Anytime we've sent a character since
454          * the last time we flushed, we'll need
455          * to send a packet -- the only other time
456          * we would send a packet is when that
457          * packet was full, in which case we now
458          * want to send an empty packet
459          */
460         if (!ao_usb_in_flushed) {
461                 ao_usb_in_flushed = 1;
462                 ao_usb_in_wait();
463                 ao_usb_in_send();
464         }
465 }
466
467 void
468 ao_usb_putchar(char c) __critical __reentrant
469 {
470         if (!ao_usb_running)
471                 return;
472
473         ao_usb_in_wait();
474
475         /* Queue a byte */
476         UENUM = AO_USB_IN_EP;
477         UEDATX = c;
478
479         /* Send the packet when full */
480         if ((UEINTX & (1 << RWAL)) == 0)
481                 ao_usb_in_send();
482         ao_usb_in_flushed = 0;
483 }
484
485 static char
486 _ao_usb_pollchar(void)
487 {
488         char c;
489         uint8_t intx;
490
491         if (!ao_usb_running)
492                 return AO_READ_AGAIN;
493
494         for (;;) {
495                 UENUM = AO_USB_OUT_EP;
496                 intx = UEINTX;
497                 debug("usb_pollchar UEINTX %02d\n", intx);
498                 if (intx & (1 << RWAL))
499                         break;
500
501                 if (intx & (1 << FIFOCON)) {
502                         /* Ack the last packet */
503                         UEINTX = (uint8_t) ~(1 << FIFOCON);
504                 }
505
506                 /* Check to see if a packet has arrived */
507                 if ((intx & (1 << RXOUTI)) == 0) {
508                         UENUM = AO_USB_OUT_EP;
509                         UEIENX = (1 << RXOUTE);
510                         return AO_READ_AGAIN;
511                 }
512
513                 /* Ack the interrupt */
514                 UEINTX = ~(1 << RXOUTI);
515         }
516
517         /* Pull a character out of the fifo */
518         c = UEDATX;
519         return c;
520 }
521
522 char
523 ao_usb_pollchar(void)
524 {
525         char    c;
526         cli();
527         c = _ao_usb_pollchar();
528         sei();
529         return c;
530 }
531
532 char
533 ao_usb_getchar(void) __critical
534 {
535         char    c;
536
537         cli();
538         while ((c = _ao_usb_pollchar()) == AO_READ_AGAIN)
539                 ao_sleep(&ao_stdin_ready);
540         sei();
541         return c;
542 }
543
544 uint16_t        control_count;
545 uint16_t        in_count;
546 uint16_t        out_count;
547
548 /* Endpoint interrupt */
549 ISR(USB_COM_vect)
550 {
551         uint8_t old_num = UENUM;
552         uint8_t i = UEINT;
553
554 #ifdef AO_LED_RED
555         ao_led_toggle(AO_LED_RED);
556 #endif
557         UEINT = 0;
558         if (i & (1 << 0)) {
559                 ao_wakeup(&ao_usb_task);
560                 ++control_count;
561         }
562         if (i & (1 << AO_USB_IN_EP)) {
563                 UENUM = AO_USB_IN_EP;
564                 UEIENX = 0;
565                 ao_wakeup(&ao_usb_in_flushed);
566                 in_count++;
567         }
568         if (i & (1 << AO_USB_OUT_EP)) {
569                 UENUM = AO_USB_OUT_EP;
570                 UEIENX = 0;
571                 ao_wakeup(&ao_stdin_ready);
572                 ++out_count;
573         }
574         UENUM = old_num;
575 }
576
577 #if AVR_VCC_5V
578 #define AO_PAD_REGULATOR_INIT   (1 << UVREGE)   /* Turn on pad regulator */
579 #endif
580 #if AVR_VCC_3V3
581 /* TeleScience V0.1 has a hardware bug -- UVcc is hooked up, but UCap is not
582  * Make this work by running power through UVcc to the USB system
583  */
584 #define AO_PAD_REGULATOR_INIT   (1 << UVREGE)   /* Turn off pad regulator */
585 #endif
586
587 #if AVR_CLOCK == 16000000UL
588 #define AO_USB_PLL_INPUT_PRESCALER      (1 << PINDIV)   /* Divide 16MHz clock by 2 */
589 #endif
590 #if AVR_CLOCK == 8000000UL
591 #define AO_USB_PLL_INPUT_PRESCALER      0               /* Don't divide clock */
592 #endif
593
594 void
595 ao_usb_disable(void)
596 {
597         /* Unplug from the bus */
598         UDCON = (1 << DETACH);
599
600         /* Disable the interface */
601         USBCON = 0;
602
603         /* Disable the PLL */
604         PLLCSR = 0;
605
606         /* Turn off the pad regulator */
607         UHWCON = 0;
608 }
609
610 #define AO_USB_CON ((1 << USBE) |       /* USB enable */ \
611                     (0 << RSTCPU) |     /* do not reset CPU */  \
612                     (0 << LSM) |        /* Full speed mode */   \
613                     (0 << RMWKUP))      /* no remote wake-up */ \
614
615 void
616 ao_usb_enable(void)
617 {
618         /* Configure pad regulator */
619         UHWCON = AO_PAD_REGULATOR_INIT;
620
621         /* Enable USB device, but freeze the clocks until initialized */
622         USBCON = AO_USB_CON | (1 <<FRZCLK);
623
624         /* Enable PLL with appropriate divider */
625         PLLCSR = AO_USB_PLL_INPUT_PRESCALER | (1 << PLLE);
626
627         /* Wait for PLL to lock */
628         loop_until_bit_is_set(PLLCSR, (1 << PLOCK));
629
630         /* Enable USB, enable the VBUS pad */
631         USBCON = AO_USB_CON | (1 << OTGPADE);
632
633         /* Enable global interrupts */
634         UDIEN = (1 << EORSTE);          /* End of reset interrupt */
635
636         ao_usb_configuration = 0;
637
638         debug ("ao_usb_enable\n");
639
640         debug ("UHWCON %02x USBCON %02x PLLCSR %02x UDIEN %02x\n",
641                UHWCON, USBCON, PLLCSR, UDIEN);
642         UDCON = (0 << DETACH);  /* Clear the DETACH bit to plug into the bus */
643 }
644
645 #if USB_DEBUG
646 struct ao_task __xdata ao_usb_echo_task;
647
648 static void
649 ao_usb_echo(void)
650 {
651         char    c;
652
653         for (;;) {
654                 c = ao_usb_getchar();
655                 ao_usb_putchar(c);
656                 ao_usb_flush();
657         }
658 }
659 #endif
660
661 static void
662 ao_usb_irq(void)
663 {
664         printf ("control: %d out: %d in: %d\n",
665                 control_count, out_count, in_count);
666 }
667
668 __code struct ao_cmds ao_usb_cmds[] = {
669         { ao_usb_irq, "i\0Show USB interrupt counts" },
670         { 0, NULL }
671 };
672
673 void
674 ao_usb_init(void)
675 {
676         ao_usb_enable();
677
678         debug ("ao_usb_init\n");
679         ao_add_task(&ao_usb_task, ao_usb_ep0, "usb");
680 //      ao_add_task(&ao_usb_echo_task, ao_usb_echo, "usb echo");
681         ao_cmd_register(&ao_usb_cmds[0]);
682         ao_add_stdio(ao_usb_pollchar, ao_usb_putchar, ao_usb_flush);
683 }