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