altos/samd21: Get USB driver working in AltOS
[fw/altos] / src / samd21 / ao_usb_samd21.c
1 /*
2  * Copyright © 2012 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; either version 2 of the License, or
7  * (at your option) any later version.
8  *
9  * This program is distributed in the hope that it will be useful, but
10  * WITHOUT ANY WARRANTY; without even the implied warranty of
11  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
12  * General Public License for more details.
13  *
14  * You should have received a copy of the GNU General Public License along
15  * with this program; if not, write to the Free Software Foundation, Inc.,
16  * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA.
17  */
18
19 #include "ao.h"
20 #include "ao_usb.h"
21 #include "ao_product.h"
22
23 #ifndef AO_POWER_MANAGEMENT
24 #define AO_POWER_MANAGEMENT     0
25 #endif
26
27 #ifndef AO_USB_DEVICE_ID_SERIAL
28 #define AO_USB_DEVICE_ID_SERIAL 0
29 #endif
30
31 #if USE_USB_FIFO
32 static struct ao_fifo   ao_usb_rx_fifo;
33 #endif
34
35 #if USE_USB_STDIO
36 #define AO_USB_OUT_SLEEP_ADDR   (&ao_stdin_ready)
37 #else
38 #define AO_USB_OUT_SLEEP_ADDR   (&ao_usb_out_avail)
39 #endif
40
41 #define SAMD21_USB_ALIGN        __attribute__ ((aligned(4)))
42
43 struct ao_usb_setup {
44         uint8_t         dir_type_recip;
45         uint8_t         request;
46         uint16_t        value;
47         uint16_t        index;
48         uint16_t        length;
49 } ao_usb_setup;
50
51 static uint8_t  ao_usb_ep0_state;
52
53 struct samd21_usb_desc  samd21_usb_desc[8] SAMD21_USB_ALIGN;
54
55 /* Pending EP0 IN data */
56 static uint8_t          ao_usb_ep0_in_tmp[2];   /* small buffer */
57 static const uint8_t    *ao_usb_ep0_in_data;    /* Remaining data */
58 static uint8_t          ao_usb_ep0_in_len;      /* Remaining amount */
59
60 /* Pending EP0 OUT data */
61 static uint8_t *ao_usb_ep0_out_data;
62 static uint8_t  ao_usb_ep0_out_len;
63
64 /* Endpoint 0 buffers */
65 static uint8_t ao_usb_ep0_in_buf[AO_USB_CONTROL_SIZE] SAMD21_USB_ALIGN;
66 static uint8_t ao_usb_ep0_out_buf[AO_USB_CONTROL_SIZE]  SAMD21_USB_ALIGN;
67
68 #if AO_USB_HAS_INT
69 /* Pointer to interrupt buffer in USB memory */
70 static uint8_t ao_usb_int_buf[AO_USB_INT_SIZE]  SAMD21_USB_ALIGN;
71 #endif
72
73 /* Buffers in DRAM */
74 #if AO_USB_HAS_IN
75 static uint8_t  ao_usb_in_tx_which;
76 static uint8_t  ao_usb_tx_count;
77 static uint8_t  ao_usb_in_buf[2][AO_USB_IN_SIZE]  SAMD21_USB_ALIGN;
78
79 #endif
80 #if AO_USB_HAS_OUT
81 static uint8_t  ao_usb_out_rx_which;
82 #if !USE_USB_FIFO
83 static uint8_t  ao_usb_rx_count, ao_usb_rx_pos;
84 #endif
85 static uint8_t  ao_usb_out_buf[2][AO_USB_OUT_SIZE]  SAMD21_USB_ALIGN;
86
87 #endif
88
89 /* Marks when we don't need to send an IN packet.
90  * This happens only when the last IN packet is not full,
91  * otherwise the host will expect to keep seeing packets.
92  * Send a zero-length packet as required
93  */
94 static uint8_t  ao_usb_in_flushed;
95
96 /* Marks when we have delivered an IN packet to the hardware
97  * and it has not been received yet. ao_sleep on this address
98  * to wait for it to be delivered.
99  */
100 static uint8_t  ao_usb_in_pending;
101
102 /* Marks when an OUT packet has been received by the hardware
103  * but not pulled to the shadow buffer.
104  */
105 static uint8_t  ao_usb_out_avail;
106 uint8_t         ao_usb_running;
107 static uint8_t  ao_usb_configuration;
108
109 #define AO_USB_EP0_GOT_SETUP    1
110 #define AO_USB_EP0_GOT_RX_DATA  2
111 #define AO_USB_EP0_GOT_TX_ACK   4
112
113 static uint8_t  ao_usb_ep0_receive;
114 static uint8_t  ao_usb_address;
115 static uint8_t  ao_usb_address_pending;
116
117 /*
118  * Set current device address and mark the
119  * interface as active
120  */
121 static void
122 ao_usb_set_address(uint8_t address)
123 {
124         samd21_usb.dadd = (1 << SAMD21_USB_DADD_ADDEN) | (address << SAMD21_USB_DADD_DADD);
125         ao_usb_address_pending = 0;
126 }
127
128 /*
129  * Initialize an entpoint
130  */
131
132 static void
133 ao_usb_init_bank(struct samd21_usb_desc_bank *bank,
134                  uint8_t *buf,
135                  uint16_t size)
136 {
137         bank->addr = (uint32_t) buf;
138
139         uint32_t size_bits = 0;
140         switch (size) {
141         case 8: size_bits = SAMD21_USB_DESC_PCKSIZE_SIZE_8; break;
142         case 16: size_bits = SAMD21_USB_DESC_PCKSIZE_SIZE_16; break;
143         case 32: size_bits = SAMD21_USB_DESC_PCKSIZE_SIZE_32; break;
144         case 64: size_bits = SAMD21_USB_DESC_PCKSIZE_SIZE_64; break;
145         case 128: size_bits = SAMD21_USB_DESC_PCKSIZE_SIZE_128; break;
146         case 256: size_bits = SAMD21_USB_DESC_PCKSIZE_SIZE_256; break;
147         case 512: size_bits = SAMD21_USB_DESC_PCKSIZE_SIZE_512; break;
148         case 1023: size_bits = SAMD21_USB_DESC_PCKSIZE_SIZE_1023; break;
149         }
150         bank->pcksize = ((0 << SAMD21_USB_DESC_PCKSIZE_BYTE_COUNT) |
151                          (0 << SAMD21_USB_DESC_PCKSIZE_MULTI_PACKET_SIZE) |
152                          (size_bits << SAMD21_USB_DESC_PCKSIZE_SIZE) |
153                          (0 << SAMD21_USB_DESC_PCKSIZE_AUTO_ZLP));
154 }
155
156 static void
157 ao_usb_init_ep(uint8_t ep,
158                uint8_t type_out, void *out_buf, uint16_t out_size,
159                uint8_t type_in, void *in_buf, uint16_t in_size)
160 {
161         /* set up descriptors */
162         ao_usb_init_bank(&samd21_usb_desc[ep].bank[0],
163                          out_buf, out_size);
164
165         ao_usb_init_bank(&samd21_usb_desc[ep].bank[1],
166                          in_buf, in_size);
167
168         samd21_usb.ep[ep].epcfg = (uint8_t) ((type_out << SAMD21_USB_EP_EPCFG_EP_TYPE_OUT) |
169                                              (type_in << SAMD21_USB_EP_EPCFG_EP_TYPE_IN));
170
171         /* Clear all status bits */
172         samd21_usb.ep[ep].epstatusclr = 0xff;
173
174         /* Select interrupts */
175         uint8_t epinten = 0;
176         if (out_buf)
177                 epinten |= (1 << SAMD21_USB_EP_EPINTFLAG_TRCPT0);
178         if (in_buf)
179                 epinten |= (1 << SAMD21_USB_EP_EPINTFLAG_TRCPT1);
180         if (ep == 0)
181                 epinten |= (1 << SAMD21_USB_EP_EPINTFLAG_RXSTP);
182         samd21_usb.ep[ep].epintenset = epinten;
183 }
184
185 static void
186 ao_usb_set_ep0(void)
187 {
188         ao_usb_init_ep(AO_USB_CONTROL_EP,
189                        SAMD21_USB_EP_EPCFG_EP_TYPE_OUT_CONTROL,
190                        ao_usb_ep0_out_buf, AO_USB_CONTROL_SIZE,
191                        SAMD21_USB_EP_EPCFG_EP_TYPE_IN_CONTROL,
192                        ao_usb_ep0_in_buf, AO_USB_CONTROL_SIZE);
193
194         ao_usb_running = 0;
195
196         /* Reset our internal state
197          */
198
199         ao_usb_ep0_state = AO_USB_EP0_IDLE;
200
201         ao_usb_ep0_in_data = NULL;
202         ao_usb_ep0_in_len = 0;
203
204         ao_usb_ep0_out_data = NULL;
205         ao_usb_ep0_out_len = 0;
206 }
207
208 static void
209 ao_usb_set_configuration(void)
210 {
211 #if AO_USB_HAS_INT
212         ao_usb_init_ep(AO_USB_INT_EP,
213                        SAMD21_USB_EP_EPCFG_EP_TYPE_OUT_DISABLED,
214                        NULL, 0,
215                        SAMD21_USB_EP_EPCFG_EP_TYPE_IN_INTERRUPT,
216                        ao_usb_int_buf, AO_USB_INT_SIZE);
217 #endif
218
219 #if AO_USB_HAS_OUT
220         ao_usb_init_ep(AO_USB_OUT_EP,
221                        SAMD21_USB_EP_EPCFG_EP_TYPE_OUT_BULK,
222                        &ao_usb_out_buf[0][0], AO_USB_OUT_SIZE,
223                        SAMD21_USB_EP_EPCFG_EP_TYPE_IN_DUAL_BANK,
224                        &ao_usb_out_buf[1][0], AO_USB_OUT_SIZE);
225
226         /* At first receive, we'll flip this back to 0 */
227         ao_usb_out_rx_which = 1;
228 #endif
229
230 #if AO_USB_HAS_IN
231         /* Set up the IN end point */
232         ao_usb_init_ep(AO_USB_IN_EP,
233                        SAMD21_USB_EP_EPCFG_EP_TYPE_OUT_DUAL_BANK,
234                        &ao_usb_in_buf[0][0], AO_USB_IN_SIZE,
235                        SAMD21_USB_EP_EPCFG_EP_TYPE_IN_BULK,
236                        &ao_usb_in_buf[1][0], AO_USB_IN_SIZE);
237
238         /* First transmit data goes to buffer 0 */
239         ao_usb_in_tx_which = 0;
240 #endif
241
242         ao_usb_in_flushed = 1;
243         ao_usb_in_pending = 0;
244         ao_wakeup(&ao_usb_in_pending);
245
246         ao_usb_out_avail = 0;
247         ao_usb_configuration = 0;
248
249         ao_wakeup(AO_USB_OUT_SLEEP_ADDR);
250 }
251
252 /* Send an IN data packet */
253 static void
254 ao_usb_ep0_flush(void)
255 {
256         uint8_t this_len;
257
258         /* Check to see if the endpoint is still busy */
259         if ((samd21_usb.ep[0].epstatus & (1 << (SAMD21_USB_EP_EPSTATUS_BK1RDY))) != 0)
260                 return;
261
262         this_len = ao_usb_ep0_in_len;
263         if (this_len > AO_USB_CONTROL_SIZE)
264                 this_len = AO_USB_CONTROL_SIZE;
265
266         if (this_len < AO_USB_CONTROL_SIZE)
267                 ao_usb_ep0_state = AO_USB_EP0_IDLE;
268
269         ao_usb_ep0_in_len -= this_len;
270
271         memcpy(ao_usb_ep0_in_buf, ao_usb_ep0_in_data, this_len);
272         ao_usb_ep0_in_data += this_len;
273
274         /* Mark the endpoint as TX valid to send the packet */
275         samd21_usb_desc_set_byte_count(AO_USB_CONTROL_EP, 1, this_len);
276         samd21_usb_ep_set_ready(AO_USB_CONTROL_EP, 1);
277 }
278
279 /* Read data from the ep0 OUT fifo */
280 static void
281 ao_usb_ep0_fill(void)
282 {
283         uint16_t        len = samd21_usb_desc_get_byte_count(AO_USB_CONTROL_EP, 0);
284
285         if (len > ao_usb_ep0_out_len)
286                 len = ao_usb_ep0_out_len;
287         ao_usb_ep0_out_len -= (uint8_t) len;
288
289         /* Pull all of the data out of the packet */
290         memcpy(ao_usb_ep0_out_data, ao_usb_ep0_out_buf, len);
291         ao_usb_ep0_out_data += len;
292
293         /* ACK the packet */
294         samd21_usb_ep_clr_ready(AO_USB_CONTROL_EP, 0);
295 }
296
297 static void
298 ao_usb_ep0_in_reset(void)
299 {
300         ao_usb_ep0_in_data = ao_usb_ep0_in_tmp;
301         ao_usb_ep0_in_len = 0;
302 }
303
304 static void
305 ao_usb_ep0_in_queue_byte(uint8_t a)
306 {
307         if (ao_usb_ep0_in_len < sizeof (ao_usb_ep0_in_tmp))
308                 ao_usb_ep0_in_tmp[ao_usb_ep0_in_len++] = a;
309 }
310
311 static void
312 ao_usb_ep0_in_set(const uint8_t *data, uint8_t len)
313 {
314         ao_usb_ep0_in_data = data;
315         ao_usb_ep0_in_len = len;
316 }
317
318 static void
319 ao_usb_ep0_out_set(uint8_t *data, uint8_t len)
320 {
321         ao_usb_ep0_out_data = data;
322         ao_usb_ep0_out_len = len;
323 }
324
325 static void
326 ao_usb_ep0_in_start(uint16_t max)
327 {
328         /* Don't send more than asked for */
329         if (ao_usb_ep0_in_len > max)
330                 ao_usb_ep0_in_len = (uint8_t) max;
331         ao_usb_ep0_flush();
332 }
333
334 struct ao_usb_line_coding ao_usb_line_coding = {115200, 0, 0, 8};
335
336 #if AO_USB_DEVICE_ID_SERIAL
337 static uint8_t ao_usb_serial[2 + 64];
338
339 /* Convert a 32-bit value to 8 hexidecimal UCS2 characters */
340 static void
341 hex_to_ucs2(uint32_t in, uint8_t *out)
342 {
343         int     i;
344
345         for (i = 28; i >= 0; i -= 4) {
346                 uint8_t bits = (in >> i) & 0xf;
347                 *out++ = ((bits < 10) ? '0' : ('a' - 10)) + bits;
348                 *out++ = 0;
349         }
350 }
351
352 /* Encode the device ID (128 bits) in hexidecimal to use as a device
353  * serial number
354  */
355 static void
356 ao_usb_serial_init(void)
357 {
358         ao_usb_serial[0] = 66;  /* length */
359         ao_usb_serial[1] = AO_USB_DESC_STRING;
360         hex_to_ucs2(samd21_serial.word0, ao_usb_serial + 2 + 0);
361         hex_to_ucs2(samd21_serial.word1, ao_usb_serial + 2 + 16);
362         hex_to_ucs2(samd21_serial.word2, ao_usb_serial + 2 + 32);
363         hex_to_ucs2(samd21_serial.word3, ao_usb_serial + 2 + 48);
364 }
365 #endif
366
367 /* Walk through the list of descriptors and find a match
368  */
369 static void
370 ao_usb_get_descriptor(uint16_t value, uint16_t length)
371 {
372         const uint8_t           *descriptor;
373         uint8_t         type = (uint8_t) (value >> 8);
374         uint8_t         index = (uint8_t) value;
375
376         descriptor = ao_usb_descriptors;
377         while (descriptor[0] != 0) {
378                 if (descriptor[1] == type && index-- == 0) {
379                         uint8_t len;
380                         if (type == AO_USB_DESC_CONFIGURATION)
381                                 len = descriptor[2];
382                         else
383                                 len = descriptor[0];
384 #if AO_USB_DEVICE_ID_SERIAL
385                         /* Slightly hacky - the serial number is string 3 */
386                         if (type == AO_USB_DESC_STRING && (value & 0xff) == 3) {
387                                 descriptor = ao_usb_serial;
388                                 len = sizeof (ao_usb_serial);
389                         }
390 #endif
391                         if (len > length)
392                                 len = (uint8_t) length;
393                         ao_usb_ep0_in_set(descriptor, len);
394                         break;
395                 }
396                 descriptor += descriptor[0];
397         }
398 }
399
400 static void
401 ao_usb_ep0_setup(void)
402 {
403         /* Pull the setup packet out of the fifo */
404         ao_usb_ep0_out_set((uint8_t *) &ao_usb_setup, 8);
405         ao_usb_ep0_fill();
406         if (ao_usb_ep0_out_len != 0)
407                 return;
408
409         if ((ao_usb_setup.dir_type_recip & AO_USB_DIR_IN) || ao_usb_setup.length == 0)
410                 ao_usb_ep0_state = AO_USB_EP0_DATA_IN;
411         else
412                 ao_usb_ep0_state = AO_USB_EP0_DATA_OUT;
413
414         ao_usb_ep0_in_reset();
415
416         switch(ao_usb_setup.dir_type_recip & AO_USB_SETUP_TYPE_MASK) {
417         case AO_USB_TYPE_STANDARD:
418                 switch(ao_usb_setup.dir_type_recip & AO_USB_SETUP_RECIP_MASK) {
419                 case AO_USB_RECIP_DEVICE:
420                         switch(ao_usb_setup.request) {
421                         case AO_USB_REQ_GET_STATUS:
422                                 ao_usb_ep0_in_queue_byte(0);
423                                 ao_usb_ep0_in_queue_byte(0);
424                                 break;
425                         case AO_USB_REQ_SET_ADDRESS:
426                                 ao_usb_address = (uint8_t) ao_usb_setup.value;
427                                 ao_usb_address_pending = 1;
428                                 break;
429                         case AO_USB_REQ_GET_DESCRIPTOR:
430                                 ao_usb_get_descriptor(ao_usb_setup.value, ao_usb_setup.length);
431                                 break;
432                         case AO_USB_REQ_GET_CONFIGURATION:
433                                 ao_usb_ep0_in_queue_byte(ao_usb_configuration);
434                                 break;
435                         case AO_USB_REQ_SET_CONFIGURATION:
436                                 ao_usb_configuration = (uint8_t) ao_usb_setup.value;
437                                 ao_usb_set_configuration();
438                                 break;
439                         }
440                         break;
441                 case AO_USB_RECIP_INTERFACE:
442                         switch(ao_usb_setup.request) {
443                         case AO_USB_REQ_GET_STATUS:
444                                 ao_usb_ep0_in_queue_byte(0);
445                                 ao_usb_ep0_in_queue_byte(0);
446                                 break;
447                         case AO_USB_REQ_GET_INTERFACE:
448                                 ao_usb_ep0_in_queue_byte(0);
449                                 break;
450                         case AO_USB_REQ_SET_INTERFACE:
451                                 break;
452                         }
453                         break;
454                 case AO_USB_RECIP_ENDPOINT:
455                         switch(ao_usb_setup.request) {
456                         case AO_USB_REQ_GET_STATUS:
457                                 ao_usb_ep0_in_queue_byte(0);
458                                 ao_usb_ep0_in_queue_byte(0);
459                                 break;
460                         }
461                         break;
462                 }
463                 break;
464         case AO_USB_TYPE_CLASS:
465                 switch (ao_usb_setup.request) {
466                 case AO_USB_SET_LINE_CODING:
467                         ao_usb_ep0_out_set((uint8_t *) &ao_usb_line_coding, 7);
468                         break;
469                 case AO_USB_GET_LINE_CODING:
470                         ao_usb_ep0_in_set((const uint8_t *) &ao_usb_line_coding, 7);
471                         break;
472                 case AO_USB_SET_CONTROL_LINE_STATE:
473                         break;
474                 }
475                 break;
476         }
477
478         /* If we're not waiting to receive data from the host,
479          * queue an IN response
480          */
481         if (ao_usb_ep0_state == AO_USB_EP0_DATA_IN)
482                 ao_usb_ep0_in_start(ao_usb_setup.length);
483 }
484
485 static void
486 ao_usb_ep0_handle(uint8_t receive)
487 {
488         ao_usb_ep0_receive = 0;
489         if (receive & AO_USB_EP0_GOT_SETUP) {
490                 ao_usb_ep0_setup();
491         }
492         if (receive & AO_USB_EP0_GOT_RX_DATA) {
493                 if (ao_usb_ep0_state == AO_USB_EP0_DATA_OUT) {
494                         ao_usb_ep0_fill();
495                         if (ao_usb_ep0_out_len == 0) {
496                                 ao_usb_ep0_state = AO_USB_EP0_DATA_IN;
497                                 ao_usb_ep0_in_start(0);
498                         }
499                 }
500         }
501         if (receive & AO_USB_EP0_GOT_TX_ACK) {
502
503 #if HAS_FLIGHT && AO_USB_FORCE_IDLE
504                 ao_flight_force_idle = 1;
505 #endif
506                 if (ao_usb_ep0_state == AO_USB_EP0_DATA_IN)
507                         ao_usb_ep0_flush();
508                 /* Wait until the IN packet is received from addr 0
509                  * before assigning our local address
510                  */
511                 if (ao_usb_address_pending)
512                         ao_usb_set_address(ao_usb_address);
513         }
514 }
515
516 #if AO_POWER_MANAGEMENT
517 static void
518 ao_usb_suspend(void)
519 {
520         stm_usb.cntr |= (1 << STM_USB_CNTR_FSUSP);
521         ao_power_suspend();
522         stm_usb.cntr |= (1 << STM_USB_CNTR_LP_MODE);
523         ao_clock_suspend();
524 }
525
526 static void
527 ao_usb_wakeup(void)
528 {
529         ao_clock_resume();
530         stm_usb.cntr &= ~(1 << STM_USB_CNTR_FSUSP);
531         ao_power_resume();
532 }
533 #endif
534
535 #if USE_USB_FIFO
536 static void
537 ao_usb_fifo_check(void)
538 {
539         uint8_t next_which = 1 - ao_usb_out_rx_which;
540         if (ao_usb_out_avail & (1 << next_which)) {
541                 uint8_t *buf = ao_usb_out_buf[next_which];
542                 uint16_t len = samd21_usb_desc_get_byte_count(AO_USB_OUT_EP, next_which);
543
544                 if (ao_fifo_has_space(&ao_usb_rx_fifo, len)) {
545                         uint16_t        i;
546
547                         for (i = 0; i < len; i++)
548                                 ao_fifo_insert(&ao_usb_rx_fifo, buf[i]);
549                         samd21_usb_ep_clr_ready(AO_USB_OUT_EP, next_which);
550                         ao_usb_out_avail &= ~(1 << next_which);
551                         ao_usb_out_rx_which = next_which;
552                         ao_wakeup(AO_USB_OUT_SLEEP_ADDR);
553                 }
554 #if AO_USB_OUT_HOOK
555                 ao_usb_out_hook(buf, len);
556 #endif
557         }
558 }
559 #endif
560
561 void
562 samd21_usb_isr(void)
563 {
564         uint16_t        intflag = samd21_usb.intflag;
565         uint16_t        epintsmry = samd21_usb.epintsmry;
566
567         samd21_usb.intflag = intflag;
568
569         if (epintsmry & (1 << 0)) {
570                 uint8_t epintflag = samd21_usb.ep[0].epintflag;
571                 samd21_usb.ep[0].epintflag = epintflag;
572
573                 if (epintflag & (1 << SAMD21_USB_EP_EPINTFLAG_RXSTP))
574                         ao_usb_ep0_receive |= AO_USB_EP0_GOT_SETUP;
575                 else if (epintflag & (1 << SAMD21_USB_EP_EPINTFLAG_TRCPT0))
576                         ao_usb_ep0_receive |= AO_USB_EP0_GOT_RX_DATA;
577                 if (epintflag & (1 << SAMD21_USB_EP_EPINTFLAG_TRCPT1))
578                         ao_usb_ep0_receive |= AO_USB_EP0_GOT_TX_ACK;
579                 ao_usb_ep0_handle(ao_usb_ep0_receive);
580         }
581 #if AO_USB_HAS_OUT
582         if (epintsmry & (1 << AO_USB_OUT_EP)) {
583                 uint8_t epintflag = samd21_usb.ep[AO_USB_OUT_EP].epintflag;
584                 samd21_usb.ep[AO_USB_OUT_EP].epintflag = epintflag;
585                 uint8_t avail = (epintflag >> SAMD21_USB_EP_EPINTFLAG_TRCPT0) & 3;
586                 if (avail) {
587                         ao_usb_out_avail |= avail;
588                         ao_usb_running = 1;
589 #if USE_USB_FIFO
590                         ao_usb_fifo_check();
591 #else
592                         ao_wakeup(AO_USB_OUT_SLEEP_ADDR);
593 #endif
594                 }
595         }
596 #endif
597 #if AO_USB_HAS_IN
598         if (epintsmry & (1 << AO_USB_IN_EP)) {
599                 uint8_t epintflag = samd21_usb.ep[AO_USB_IN_EP].epintflag;
600                 samd21_usb.ep[AO_USB_IN_EP].epintflag = epintflag;
601                 uint8_t done = (epintflag >> SAMD21_USB_EP_EPINTFLAG_TRCPT0) & 3;
602                 if (done) {
603                         ao_usb_in_pending &= (uint8_t) ~done;
604                         ao_wakeup(&ao_usb_in_pending);
605                 }
606         }
607 #endif
608 #if AO_USB_HAS_INT
609         if (epintsmry & (1 << AO_USB_INT_EP)) {
610         }
611 #endif
612         if (intflag & (1 << SAMD21_USB_INTFLAG_EORST)) {
613                 ao_usb_set_ep0();
614         }
615 #if AO_POWER_MANAGEMENT
616         if (istr & (1 << STM_USB_ISTR_SUSP))
617                 ao_usb_suspend();
618
619         if (istr & (1 << STM_USB_ISTR_WKUP))
620                 ao_usb_wakeup();
621 #endif
622 }
623
624 #if AO_USB_HAS_IN
625 /* Queue the current IN buffer for transmission */
626 static void
627 _ao_usb_in_send(void)
628 {
629         ao_usb_in_pending |= (uint8_t) (1 << ao_usb_in_tx_which);
630         if (ao_usb_tx_count != AO_USB_IN_SIZE)
631                 ao_usb_in_flushed = 1;
632
633         samd21_usb_desc_set_byte_count(AO_USB_IN_EP, ao_usb_in_tx_which, ao_usb_tx_count);
634         samd21_usb_ep_set_ready(AO_USB_IN_EP, ao_usb_in_tx_which);
635
636         /* Toggle our usage */
637         ao_usb_in_tx_which = 1 - ao_usb_in_tx_which;
638         ao_usb_tx_count = 0;
639 }
640
641 /* Wait for a free IN buffer. Interrupts are blocked */
642 static void
643 _ao_usb_in_wait(void)
644 {
645         /* Wait for an IN buffer to be ready */
646         while ((ao_usb_in_pending & (1 << ao_usb_in_tx_which)) != 0)
647                 ao_sleep(&ao_usb_in_pending);
648 }
649
650 void
651 ao_usb_flush(void)
652 {
653         if (!ao_usb_running)
654                 return;
655
656         /* Anytime we've sent a character since
657          * the last time we flushed, we'll need
658          * to send a packet -- the only other time
659          * we would send a packet is when that
660          * packet was full, in which case we now
661          * want to send an empty packet
662          */
663         ao_arch_block_interrupts();
664         if (!ao_usb_in_flushed) {
665                 _ao_usb_in_wait();
666                 if (!ao_usb_in_flushed)
667                         _ao_usb_in_send();
668         }
669         ao_arch_release_interrupts();
670 }
671
672 void
673 ao_usb_putchar(char c)
674 {
675         if (!ao_usb_running)
676                 return;
677
678         ao_arch_block_interrupts();
679         _ao_usb_in_wait();
680
681         ao_usb_in_flushed = 0;
682         ao_usb_in_buf[ao_usb_in_tx_which][ao_usb_tx_count++] = c;
683
684         /* Send the packet when full */
685         if (ao_usb_tx_count == AO_USB_IN_SIZE)
686                 _ao_usb_in_send();
687
688         ao_arch_release_interrupts();
689         if (c == '\n')
690                 ao_usb_flush();
691 }
692 #endif
693
694 #if AO_USB_HAS_OUT
695 #if !USE_USB_FIFO
696 static bool
697 _ao_usb_out_recv(void)
698 {
699         uint8_t next_which = 1 - ao_usb_out_rx_which;
700
701         if ((ao_usb_out_avail & (1 << next_which)) != 0) {
702                 /* switch current buffer */
703                 ao_usb_out_rx_which = next_which;
704                 ao_usb_out_avail &= (uint8_t) ~(1 << ao_usb_out_rx_which);
705
706                 ao_usb_rx_count = (uint8_t) samd21_usb_desc_get_byte_count(AO_USB_OUT_EP, ao_usb_out_rx_which);
707                 ao_usb_rx_pos = 0;
708                 return true;
709         }
710         return false;
711 }
712 #endif
713
714 static int
715 _ao_usb_pollchar(void)
716 {
717         uint8_t c;
718
719         if (!ao_usb_running)
720                 return AO_READ_AGAIN;
721
722 #if USE_USB_FIFO
723         if (ao_fifo_empty(&ao_usb_rx_fifo))
724                 return AO_READ_AGAIN;
725         c = ao_fifo_remove(&ao_usb_rx_fifo);
726         ao_usb_fifo_check();
727 #else
728         for (;;) {
729                 if (ao_usb_rx_pos != ao_usb_rx_count)
730                         break;
731
732                 /* Check for packet */
733                 if (!_ao_usb_out_recv())
734                         return AO_READ_AGAIN;
735         }
736
737         /* Pull a character out of the fifo */
738         c = ao_usb_out_buf[ao_usb_out_rx_which][ao_usb_rx_pos++];
739
740         if (ao_usb_rx_pos == ao_usb_rx_count)
741                 samd21_usb_ep_clr_ready(AO_USB_OUT_EP, ao_usb_out_rx_which);
742 #endif
743
744         return c;
745 }
746
747 char
748 ao_usb_getchar(void)
749 {
750         int     c;
751
752         ao_arch_block_interrupts();
753         while ((c = _ao_usb_pollchar()) == AO_READ_AGAIN)
754                 ao_sleep(AO_USB_OUT_SLEEP_ADDR);
755         ao_arch_release_interrupts();
756         return (char) c;
757 }
758
759 #endif
760
761 void
762 ao_usb_disable(void)
763 {
764         ao_arch_block_interrupts();
765         samd21_nvic_clear_enable(SAMD21_NVIC_ISR_USB_POS);
766
767         /* Disable USB pull-up */
768         samd21_usb.ctrlb |= (1 << SAMD21_USB_CTRLB_DETACH);
769
770         /* Switch off the device */
771         samd21_usb.ctrla &= (uint8_t) ~(1 << SAMD21_USB_CTRLA_ENABLE);
772
773         /* Disable the interface */
774         samd21_pm.apbbmask &= ~(1UL << SAMD21_PM_APBBMASK_USB);
775         ao_arch_release_interrupts();
776 }
777
778 void
779 ao_usb_enable(void)
780 {
781         int     t;
782
783         ao_enable_port(&samd21_port_a);
784
785         /* Set up USB DM/DP pins */
786         samd21_port_pmux_set(&samd21_port_a, 24, SAMD21_PORT_PMUX_FUNC_G);
787         samd21_port_pmux_set(&samd21_port_a, 25, SAMD21_PORT_PMUX_FUNC_G);
788
789         /* Assign gclk 0 to USB reference */
790         samd21_gclk_clkctrl(AO_GCLK_USB, SAMD21_GCLK_CLKCTRL_ID_USB);
791
792         /* Enable USB clock */
793         samd21_pm.apbbmask |= (1 << SAMD21_PM_APBBMASK_USB);
794
795         /* Reset USB Device */
796
797         samd21_usb.ctrla |= (1 << SAMD21_USB_CTRLA_SWRST);
798
799         while ((samd21_usb.ctrla & (1 << SAMD21_USB_CTRLA_SWRST)) != 0)
800                 ;
801
802         while ((samd21_usb.syncbusy & (1 << SAMD21_USB_SYNCBUSY_SWRST)) != 0)
803                 ;
804
805         memset(&samd21_usb_desc, 0, sizeof (samd21_usb_desc));
806
807         /* Detach */
808         samd21_usb.ctrlb |= (1 << SAMD21_USB_CTRLB_DETACH);
809
810         samd21_usb.descadd = (uint32_t) &samd21_usb_desc;
811
812         /* Load calibration values */
813         uint32_t transn = ((samd21_aux1.calibration >> SAMD21_AUX1_CALIBRATION_USB_TRANSN) &
814                            SAMD21_AUX1_CALIBRATION_USB_TRANSN_MASK);
815         if (transn == 0x1f)
816                 transn = 5;
817         uint32_t transp = ((samd21_aux1.calibration >> SAMD21_AUX1_CALIBRATION_USB_TRANSP) &
818                            SAMD21_AUX1_CALIBRATION_USB_TRANSP_MASK);
819         if (transp == 0x1f)
820                 transp = 29;
821         uint32_t trim   = ((samd21_aux1.calibration >> SAMD21_AUX1_CALIBRATION_USB_TRIM) &
822                            SAMD21_AUX1_CALIBRATION_USB_TRIM_MASK);
823         if (trim == 7)
824                 trim = 3;
825
826         samd21_usb.padcal = (uint16_t) ((transn << SAMD21_USB_PADCAL_TRANSN) |
827                                         (transp << SAMD21_USB_PADCAL_TRANSP) |
828                                         (trim << SAMD21_USB_PADCAL_TRIM));
829
830         samd21_usb.qosctrl = ((3 << SAMD21_USB_QOSCTRL_CQOS) |
831                               (3 << SAMD21_USB_QOSCTRL_DQOS));
832
833         ao_arch_block_interrupts();
834
835         /* set full speed */
836         samd21_usb.ctrlb = (SAMD21_USB_CTRLB_SPDCONF_FS << SAMD21_USB_CTRLB_SPDCONF);
837
838         /* Set device mode */
839         samd21_usb.ctrla = ((0 << SAMD21_USB_CTRLA_MODE) |
840                             (1 << SAMD21_USB_CTRLA_RUNSTDBY) |
841                             (1 << SAMD21_USB_CTRLA_ENABLE));
842
843         while ((samd21_usb.syncbusy & (1 << SAMD21_USB_SYNCBUSY_ENABLE)) != 0)
844                 ;
845
846         /* configure interrupts */
847         samd21_nvic_set_enable(SAMD21_NVIC_ISR_USB_POS);
848         samd21_nvic_set_priority(SAMD21_NVIC_ISR_USB_POS, 2);
849
850         samd21_usb.intenset = ((1 << SAMD21_USB_INTFLAG_EORST));
851
852         ao_arch_release_interrupts();
853
854         for (t = 0; t < 50000; t++)
855                 ao_arch_nop();
856
857         /* Attach */
858         samd21_usb.ctrlb &= (uint16_t) ~(1 << SAMD21_USB_CTRLB_DETACH);
859 }
860
861 void
862 ao_usb_init(void)
863 {
864         ao_usb_enable();
865
866 #if AO_USB_DEVICE_ID_SERIAL
867         ao_usb_serial_init();
868 #endif
869
870         ao_usb_ep0_state = AO_USB_EP0_IDLE;
871
872 #if USE_USB_STDIO
873         ao_add_stdio(_ao_usb_pollchar, ao_usb_putchar, ao_usb_flush);
874 #endif
875 }