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