691c2d56d830f11b5e3dadf7a8523430077bf560
[fw/altos] / src / stmf0 / ao_usb_stm.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; version 2 of the License.
7  *
8  * This program is distributed in the hope that it will be useful, but
9  * WITHOUT ANY WARRANTY; without even the implied warranty of
10  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
11  * General Public License for more details.
12  *
13  * You should have received a copy of the GNU General Public License along
14  * with this program; if not, write to the Free Software Foundation, Inc.,
15  * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA.
16  */
17
18 #include "ao.h"
19 #include "ao_usb.h"
20 #include "ao_product.h"
21 #include "ao_power.h"
22
23 #define USB_DEBUG       0
24 #define USB_STATUS      0
25 #define USB_DEBUG_DATA  0
26 #define USB_ECHO        0
27
28 #ifndef AO_PA11_PA12_RMP
29 #error "must define AO_PA11_PA12_RMP"
30 #endif
31
32 #ifndef USE_USB_STDIO
33 #define USE_USB_STDIO   1
34 #endif
35
36 #if USE_USB_STDIO
37 #define AO_USB_OUT_SLEEP_ADDR   (&ao_stdin_ready)
38 #else
39 #define AO_USB_OUT_SLEEP_ADDR   (&ao_usb_out_avail)
40 #endif
41
42 #if USB_DEBUG
43 #define debug(format, args...)  printf(format, ## args);
44 #else
45 #define debug(format, args...)
46 #endif
47
48 #if USB_DEBUG_DATA
49 #define debug_data(format, args...)     printf(format, ## args);
50 #else
51 #define debug_data(format, args...)
52 #endif
53
54 struct ao_usb_setup {
55         uint8_t         dir_type_recip;
56         uint8_t         request;
57         uint16_t        value;
58         uint16_t        index;
59         uint16_t        length;
60 } ao_usb_setup;
61
62 static uint8_t  ao_usb_ep0_state;
63
64 /* Pending EP0 IN data */
65 static const uint8_t    *ao_usb_ep0_in_data;    /* Remaining data */
66 static uint8_t          ao_usb_ep0_in_len;      /* Remaining amount */
67
68 /* Temp buffer for smaller EP0 in data */
69 static uint8_t  ao_usb_ep0_in_buf[2];
70
71 /* Pending EP0 OUT data */
72 static uint8_t *ao_usb_ep0_out_data;
73 static uint8_t  ao_usb_ep0_out_len;
74
75 /*
76  * Objects allocated in special USB memory
77  */
78
79 /* Buffer description tables */
80 static union stm_usb_bdt        *ao_usb_bdt;
81 /* USB address of end of allocated storage */
82 static uint16_t ao_usb_sram_addr;
83
84 /* Pointer to ep0 tx/rx buffers in USB memory */
85 static uint16_t *ao_usb_ep0_tx_buffer;
86 static uint16_t *ao_usb_ep0_rx_buffer;
87
88 /* Pointer to interrupt buffer in USB memory */
89 static uint16_t ao_usb_int_tx_offset;
90
91 /* Pointer to bulk data tx/rx buffers in USB memory */
92 static uint16_t ao_usb_in_tx_offset;
93 static uint16_t *ao_usb_in_tx_buffer;
94 static uint16_t ao_usb_out_rx_offset;
95 static uint16_t *ao_usb_out_rx_buffer;
96
97 /* System ram shadow of USB buffer; writing individual bytes is
98  * too much of a pain (sigh) */
99 static uint8_t  ao_usb_tx_buffer[AO_USB_IN_SIZE];
100 static uint8_t  ao_usb_tx_count;
101
102 static uint8_t  ao_usb_rx_buffer[AO_USB_OUT_SIZE];
103 static uint8_t  ao_usb_rx_count, ao_usb_rx_pos;
104
105 /*
106  * End point register indices
107  */
108
109 #define AO_USB_CONTROL_EPR      0
110 #define AO_USB_INT_EPR          1
111 #define AO_USB_OUT_EPR          2
112 #define AO_USB_IN_EPR           3
113
114 /* Marks when we don't need to send an IN packet.
115  * This happens only when the last IN packet is not full,
116  * otherwise the host will expect to keep seeing packets.
117  * Send a zero-length packet as required
118  */
119 static uint8_t  ao_usb_in_flushed;
120
121 /* Marks when we have delivered an IN packet to the hardware
122  * and it has not been received yet. ao_sleep on this address
123  * to wait for it to be delivered.
124  */
125 static uint8_t  ao_usb_in_pending;
126
127 /* Marks when an OUT packet has been received by the hardware
128  * but not pulled to the shadow buffer.
129  */
130 static uint8_t  ao_usb_out_avail;
131 uint8_t         ao_usb_running;
132 static uint8_t  ao_usb_configuration;
133
134 #define AO_USB_EP0_GOT_SETUP    1
135 #define AO_USB_EP0_GOT_RX_DATA  2
136 #define AO_USB_EP0_GOT_TX_ACK   4
137
138 static uint8_t  ao_usb_ep0_receive;
139 static uint8_t  ao_usb_address;
140 static uint8_t  ao_usb_address_pending;
141
142 static inline uint32_t set_toggle(uint32_t      current_value,
143                                    uint32_t     mask,
144                                    uint32_t     desired_value)
145 {
146         return (current_value ^ desired_value) & mask;
147 }
148
149 static inline uint16_t *ao_usb_packet_buffer_addr(uint16_t sram_addr)
150 {
151         return (uint16_t *) (stm_usb_sram + sram_addr);
152 }
153
154 static inline uint16_t ao_usb_packet_buffer_offset(uint16_t *addr)
155 {
156         return (uint16_t) ((uint8_t *) addr - stm_usb_sram);
157 }
158
159 static inline uint32_t ao_usb_epr_stat_rx(uint32_t epr) {
160         return (epr >> STM_USB_EPR_STAT_RX) & STM_USB_EPR_STAT_RX_MASK;
161 }
162
163 static inline uint32_t ao_usb_epr_stat_tx(uint32_t epr) {
164         return (epr >> STM_USB_EPR_STAT_TX) & STM_USB_EPR_STAT_TX_MASK;
165 }
166
167 static inline uint32_t ao_usb_epr_ctr_rx(uint32_t epr) {
168         return (epr >> STM_USB_EPR_CTR_RX) & 1;
169 }
170
171 static inline uint32_t ao_usb_epr_ctr_tx(uint32_t epr) {
172         return (epr >> STM_USB_EPR_CTR_TX) & 1;
173 }
174
175 static inline uint32_t ao_usb_epr_setup(uint32_t epr) {
176         return (epr >> STM_USB_EPR_SETUP) & 1;
177 }
178
179 static inline uint32_t ao_usb_epr_dtog_rx(uint32_t epr) {
180         return (epr >> STM_USB_EPR_DTOG_RX) & 1;
181 }
182
183 static inline uint32_t ao_usb_epr_dtog_tx(uint32_t epr) {
184         return (epr >> STM_USB_EPR_DTOG_TX) & 1;
185 }
186
187 /*
188  * Set current device address and mark the
189  * interface as active
190  */
191 void
192 ao_usb_set_address(uint8_t address)
193 {
194         debug("ao_usb_set_address %02x\n", address);
195         stm_usb.daddr = (1 << STM_USB_DADDR_EF) | address;
196         ao_usb_address_pending = 0;
197 }
198
199 /*
200  * Write these values to preserve register contents under HW changes
201  */
202
203 #define STM_USB_EPR_INVARIANT   ((1 << STM_USB_EPR_CTR_RX) |            \
204                                  (STM_USB_EPR_DTOG_RX_WRITE_INVARIANT << STM_USB_EPR_DTOG_RX) | \
205                                  (STM_USB_EPR_STAT_RX_WRITE_INVARIANT << STM_USB_EPR_STAT_RX) | \
206                                  (1 << STM_USB_EPR_CTR_TX) |            \
207                                  (STM_USB_EPR_DTOG_TX_WRITE_INVARIANT << STM_USB_EPR_DTOG_TX) | \
208                                  (STM_USB_EPR_STAT_TX_WRITE_INVARIANT << STM_USB_EPR_STAT_TX))
209
210 #define STM_USB_EPR_INVARIANT_MASK      ((1 << STM_USB_EPR_CTR_RX) |    \
211                                          (STM_USB_EPR_DTOG_RX_MASK << STM_USB_EPR_DTOG_RX) | \
212                                          (STM_USB_EPR_STAT_RX_MASK << STM_USB_EPR_STAT_RX) | \
213                                          (1 << STM_USB_EPR_CTR_TX) |    \
214                                          (STM_USB_EPR_DTOG_TX_MASK << STM_USB_EPR_DTOG_TX) | \
215                                          (STM_USB_EPR_STAT_TX_MASK << STM_USB_EPR_STAT_TX))
216
217 /*
218  * These bits are purely under sw control, so preserve them in the
219  * register by re-writing what was read
220  */
221 #define STM_USB_EPR_PRESERVE_MASK       ((STM_USB_EPR_EP_TYPE_MASK << STM_USB_EPR_EP_TYPE) | \
222                                          (1 << STM_USB_EPR_EP_KIND) |   \
223                                          (STM_USB_EPR_EA_MASK << STM_USB_EPR_EA))
224
225 #define TX_DBG 0
226 #define RX_DBG 0
227
228 #if TX_DBG
229 #define _tx_dbg0(msg) _dbg(__LINE__,msg,0)
230 #define _tx_dbg1(msg,value) _dbg(__LINE__,msg,value)
231 #else
232 #define _tx_dbg0(msg)
233 #define _tx_dbg1(msg,value)
234 #endif
235
236 #if RX_DBG
237 #define _rx_dbg0(msg) _dbg(__LINE__,msg,0)
238 #define _rx_dbg1(msg,value) _dbg(__LINE__,msg,value)
239 #else
240 #define _rx_dbg0(msg)
241 #define _rx_dbg1(msg,value)
242 #endif
243
244 #if TX_DBG || RX_DBG
245 static void _dbg(int line, char *msg, uint32_t value);
246 #endif
247
248 /*
249  * Set the state of the specified endpoint register to a new
250  * value. This is tricky because the bits toggle where the new
251  * value is one, and we need to write invariant values in other
252  * spots of the register. This hardware is strange...
253  */
254 static void
255 _ao_usb_set_stat_tx(int ep, uint32_t stat_tx)
256 {
257         uint16_t        epr_write, epr_old;
258
259         _tx_dbg1("set_stat_tx top", stat_tx);
260         epr_old = epr_write = stm_usb.epr[ep].r;
261         epr_write &= STM_USB_EPR_PRESERVE_MASK;
262         epr_write |= STM_USB_EPR_INVARIANT;
263         epr_write |= set_toggle(epr_old,
264                               STM_USB_EPR_STAT_TX_MASK << STM_USB_EPR_STAT_TX,
265                               stat_tx << STM_USB_EPR_STAT_TX);
266         stm_usb.epr[ep].r = epr_write;
267         _tx_dbg1("set_stat_tx bottom", epr_write);
268 }
269
270 static void
271 ao_usb_set_stat_tx(int ep, uint32_t stat_tx)
272 {
273         ao_arch_block_interrupts();
274         _ao_usb_set_stat_tx(ep, stat_tx);
275         ao_arch_release_interrupts();
276 }
277
278 static void
279 _ao_usb_set_stat_rx(int ep, uint32_t stat_rx) {
280         uint16_t        epr_write, epr_old;
281
282         epr_write = epr_old = stm_usb.epr[ep].r;
283         epr_write &= STM_USB_EPR_PRESERVE_MASK;
284         epr_write |= STM_USB_EPR_INVARIANT;
285         epr_write |= set_toggle(epr_old,
286                               STM_USB_EPR_STAT_RX_MASK << STM_USB_EPR_STAT_RX,
287                               stat_rx << STM_USB_EPR_STAT_RX);
288         stm_usb.epr[ep].r = epr_write;
289 }
290
291 static void
292 ao_usb_set_stat_rx(int ep, uint32_t stat_rx) {
293         ao_arch_block_interrupts();
294         _ao_usb_set_stat_rx(ep, stat_rx);
295         ao_arch_release_interrupts();
296 }
297
298 /*
299  * Set just endpoint 0, for use during startup
300  */
301
302 static void
303 ao_usb_init_ep(uint8_t ep, uint32_t addr, uint32_t type, uint32_t stat_rx, uint32_t stat_tx)
304 {
305         uint16_t                epr;
306
307         ao_arch_block_interrupts();
308         epr = stm_usb.epr[ep].r;
309         epr = ((0 << STM_USB_EPR_CTR_RX) |
310                (epr & (1 << STM_USB_EPR_DTOG_RX)) |
311                set_toggle(epr,
312                           (STM_USB_EPR_STAT_RX_MASK << STM_USB_EPR_STAT_RX),
313                           (stat_rx << STM_USB_EPR_STAT_RX)) |
314                (type << STM_USB_EPR_EP_TYPE) |
315                (0 << STM_USB_EPR_EP_KIND) |
316                (0 << STM_USB_EPR_CTR_TX) |
317                (epr & (1 << STM_USB_EPR_DTOG_TX)) |
318                set_toggle(epr,
319                           (STM_USB_EPR_STAT_TX_MASK << STM_USB_EPR_STAT_TX),
320                           (stat_tx << STM_USB_EPR_STAT_TX)) |
321                (addr << STM_USB_EPR_EA));
322         stm_usb.epr[ep].r = epr;
323         ao_arch_release_interrupts();
324         debug ("writing epr[%d] 0x%04x wrote 0x%04x\n",
325                ep, epr, stm_usb.epr[ep].r);
326 }
327
328 static void
329 ao_usb_alloc_buffers(void)
330 {
331         ao_usb_sram_addr = 0;
332
333         ao_usb_bdt = (void *) stm_usb_sram;
334         ao_usb_sram_addr += 8 * STM_USB_BDT_SIZE;
335
336         ao_usb_ep0_tx_buffer = ao_usb_packet_buffer_addr(ao_usb_sram_addr);
337         ao_usb_sram_addr += AO_USB_CONTROL_SIZE;
338
339         ao_usb_ep0_rx_buffer = ao_usb_packet_buffer_addr(ao_usb_sram_addr);
340         ao_usb_sram_addr += AO_USB_CONTROL_SIZE;
341
342         ao_usb_int_tx_offset = ao_usb_sram_addr;
343         ao_usb_sram_addr += AO_USB_INT_SIZE;
344
345         ao_usb_out_rx_buffer = ao_usb_packet_buffer_addr(ao_usb_sram_addr);
346         ao_usb_out_rx_offset = ao_usb_sram_addr;
347         ao_usb_sram_addr += AO_USB_OUT_SIZE;
348
349         ao_usb_in_tx_buffer = ao_usb_packet_buffer_addr(ao_usb_sram_addr);
350         ao_usb_in_tx_offset = ao_usb_sram_addr;
351         ao_usb_sram_addr += AO_USB_IN_SIZE;
352 }
353
354 static void
355 ao_usb_init_btable(void)
356 {
357         /* Set up EP 0 - a Control end point with 32 bytes of in and out buffers */
358
359         ao_usb_bdt[0].single.addr_tx = ao_usb_packet_buffer_offset(ao_usb_ep0_tx_buffer);
360         ao_usb_bdt[0].single.count_tx = 0;
361
362         ao_usb_bdt[0].single.addr_rx = ao_usb_packet_buffer_offset(ao_usb_ep0_rx_buffer);
363         ao_usb_bdt[0].single.count_rx = ((1 << STM_USB_BDT_COUNT_RX_BL_SIZE) |
364                                   (((AO_USB_CONTROL_SIZE / 32) - 1) << STM_USB_BDT_COUNT_RX_NUM_BLOCK));
365 }
366
367 static void
368 ao_usb_set_ep0(void)
369 {
370         int                     e;
371
372         ao_usb_init_btable();
373
374         /* buffer table is at the start of USB memory */
375         stm_usb.btable = 0;
376
377         ao_usb_init_ep(AO_USB_CONTROL_EPR, AO_USB_CONTROL_EP,
378                        STM_USB_EPR_EP_TYPE_CONTROL,
379                        STM_USB_EPR_STAT_RX_VALID,
380                        STM_USB_EPR_STAT_TX_NAK);
381
382         /* Clear all of the other endpoints */
383         for (e = 1; e < 8; e++) {
384                 ao_usb_init_ep(e, 0,
385                                STM_USB_EPR_EP_TYPE_CONTROL,
386                                STM_USB_EPR_STAT_RX_DISABLED,
387                                STM_USB_EPR_STAT_TX_DISABLED);
388         }
389
390         ao_usb_set_address(0);
391
392         ao_usb_running = 0;
393 }
394
395 static void
396 ao_usb_set_configuration(void)
397 {
398         debug ("ao_usb_set_configuration\n");
399
400         /* Set up the INT end point */
401         ao_usb_bdt[AO_USB_INT_EPR].single.addr_tx = ao_usb_int_tx_offset;
402         ao_usb_bdt[AO_USB_INT_EPR].single.count_tx = 0;
403
404         ao_usb_init_ep(AO_USB_INT_EPR,
405                        AO_USB_INT_EP,
406                        STM_USB_EPR_EP_TYPE_INTERRUPT,
407                        STM_USB_EPR_STAT_RX_DISABLED,
408                        STM_USB_EPR_STAT_TX_NAK);
409
410         /* Set up the OUT end point */
411         ao_usb_bdt[AO_USB_OUT_EPR].single.addr_rx = ao_usb_out_rx_offset;
412         ao_usb_bdt[AO_USB_OUT_EPR].single.count_rx = ((1 << STM_USB_BDT_COUNT_RX_BL_SIZE) |
413                                                       (((AO_USB_OUT_SIZE / 32) - 1) << STM_USB_BDT_COUNT_RX_NUM_BLOCK));
414
415         ao_usb_init_ep(AO_USB_OUT_EPR,
416                        AO_USB_OUT_EP,
417                        STM_USB_EPR_EP_TYPE_BULK,
418                        STM_USB_EPR_STAT_RX_VALID,
419                        STM_USB_EPR_STAT_TX_DISABLED);
420
421         /* Set up the IN end point */
422         ao_usb_bdt[AO_USB_IN_EPR].single.addr_tx = ao_usb_in_tx_offset;
423         ao_usb_bdt[AO_USB_IN_EPR].single.count_tx = 0;
424
425         ao_usb_init_ep(AO_USB_IN_EPR,
426                        AO_USB_IN_EP,
427                        STM_USB_EPR_EP_TYPE_BULK,
428                        STM_USB_EPR_STAT_RX_DISABLED,
429                        STM_USB_EPR_STAT_TX_NAK);
430
431         ao_usb_running = 1;
432 #if AO_USB_DIRECTIO
433         ao_wakeup(&ao_usb_running);
434 #endif
435 }
436
437 static uint16_t control_count;
438 static uint16_t int_count;
439 static uint16_t in_count;
440 static uint16_t out_count;
441 static uint16_t reset_count;
442 static uint16_t suspend_count;
443
444 /* The USB memory must be accessed in 16-bit units
445  */
446
447 static void
448 ao_usb_copy_tx(const uint8_t *src, uint16_t *base, uint16_t bytes)
449 {
450         while (bytes >= 2) {
451                 *base++ = src[0] | (src[1] << 8);
452                 src += 2;
453                 bytes -= 2;
454         }
455         if (bytes)
456                 *base = *src;
457 }
458
459 static void
460 ao_usb_copy_rx(uint8_t *dst, uint16_t *base, uint16_t bytes)
461 {
462         while (bytes >= 2) {
463                 uint16_t s = *base++;
464                 dst[0] = s;
465                 dst[1] = s >> 8;
466                 dst += 2;
467                 bytes -= 2;
468         }
469         if (bytes)
470                 *dst = *base;
471 }
472
473 /* Send an IN data packet */
474 static void
475 ao_usb_ep0_flush(void)
476 {
477         uint8_t this_len;
478
479         /* Check to see if the endpoint is still busy */
480         if (ao_usb_epr_stat_tx(stm_usb.epr[0].r) == STM_USB_EPR_STAT_TX_VALID) {
481                 debug("EP0 not accepting IN data\n");
482                 return;
483         }
484
485         this_len = ao_usb_ep0_in_len;
486         if (this_len > AO_USB_CONTROL_SIZE)
487                 this_len = AO_USB_CONTROL_SIZE;
488
489         if (this_len < AO_USB_CONTROL_SIZE)
490                 ao_usb_ep0_state = AO_USB_EP0_IDLE;
491
492         ao_usb_ep0_in_len -= this_len;
493
494         debug_data ("Flush EP0 len %d:", this_len);
495         ao_usb_copy_tx(ao_usb_ep0_in_data, ao_usb_ep0_tx_buffer, this_len);
496         debug_data ("\n");
497         ao_usb_ep0_in_data += this_len;
498
499         /* Mark the endpoint as TX valid to send the packet */
500         ao_usb_bdt[AO_USB_CONTROL_EPR].single.count_tx = this_len;
501         ao_usb_set_stat_tx(AO_USB_CONTROL_EPR, STM_USB_EPR_STAT_TX_VALID);
502         debug ("queue tx. epr 0 now %08x\n", stm_usb.epr[AO_USB_CONTROL_EPR]);
503 }
504
505 /* Read data from the ep0 OUT fifo */
506 static void
507 ao_usb_ep0_fill(void)
508 {
509         uint16_t        len = ao_usb_bdt[0].single.count_rx & STM_USB_BDT_COUNT_RX_COUNT_RX_MASK;
510
511         if (len > ao_usb_ep0_out_len)
512                 len = ao_usb_ep0_out_len;
513         ao_usb_ep0_out_len -= len;
514
515         /* Pull all of the data out of the packet */
516         debug_data ("Fill EP0 len %d:", len);
517         ao_usb_copy_rx(ao_usb_ep0_out_data, ao_usb_ep0_rx_buffer, len);
518         debug_data ("\n");
519         ao_usb_ep0_out_data += len;
520
521         /* ACK the packet */
522         ao_usb_set_stat_rx(0, STM_USB_EPR_STAT_RX_VALID);
523 }
524
525 static void
526 ao_usb_ep0_in_reset(void)
527 {
528         ao_usb_ep0_in_data = ao_usb_ep0_in_buf;
529         ao_usb_ep0_in_len = 0;
530 }
531
532 static void
533 ao_usb_ep0_in_queue_byte(uint8_t a)
534 {
535         if (ao_usb_ep0_in_len < sizeof (ao_usb_ep0_in_buf))
536                 ao_usb_ep0_in_buf[ao_usb_ep0_in_len++] = a;
537 }
538
539 static void
540 ao_usb_ep0_in_set(const uint8_t *data, uint8_t len)
541 {
542         ao_usb_ep0_in_data = data;
543         ao_usb_ep0_in_len = len;
544 }
545
546 static void
547 ao_usb_ep0_out_set(uint8_t *data, uint8_t len)
548 {
549         ao_usb_ep0_out_data = data;
550         ao_usb_ep0_out_len = len;
551 }
552
553 static void
554 ao_usb_ep0_in_start(uint16_t max)
555 {
556         /* Don't send more than asked for */
557         if (ao_usb_ep0_in_len > max)
558                 ao_usb_ep0_in_len = max;
559         ao_usb_ep0_flush();
560 }
561
562 static struct ao_usb_line_coding ao_usb_line_coding = {115200, 0, 0, 8};
563
564 /* Walk through the list of descriptors and find a match
565  */
566 static void
567 ao_usb_get_descriptor(uint16_t value)
568 {
569         const uint8_t           *descriptor;
570         uint8_t         type = value >> 8;
571         uint8_t         index = value;
572
573         descriptor = ao_usb_descriptors;
574         while (descriptor[0] != 0) {
575                 if (descriptor[1] == type && index-- == 0) {
576                         uint8_t len;
577                         if (type == AO_USB_DESC_CONFIGURATION)
578                                 len = descriptor[2];
579                         else
580                                 len = descriptor[0];
581                         ao_usb_ep0_in_set(descriptor, len);
582                         break;
583                 }
584                 descriptor += descriptor[0];
585         }
586 }
587
588 static void
589 ao_usb_ep0_setup(void)
590 {
591         /* Pull the setup packet out of the fifo */
592         ao_usb_ep0_out_set((uint8_t *) &ao_usb_setup, 8);
593         ao_usb_ep0_fill();
594         if (ao_usb_ep0_out_len != 0) {
595                 debug ("invalid setup packet length\n");
596                 return;
597         }
598
599         if ((ao_usb_setup.dir_type_recip & AO_USB_DIR_IN) || ao_usb_setup.length == 0)
600                 ao_usb_ep0_state = AO_USB_EP0_DATA_IN;
601         else
602                 ao_usb_ep0_state = AO_USB_EP0_DATA_OUT;
603
604         ao_usb_ep0_in_reset();
605
606         switch(ao_usb_setup.dir_type_recip & AO_USB_SETUP_TYPE_MASK) {
607         case AO_USB_TYPE_STANDARD:
608                 debug ("Standard setup packet\n");
609                 switch(ao_usb_setup.dir_type_recip & AO_USB_SETUP_RECIP_MASK) {
610                 case AO_USB_RECIP_DEVICE:
611                         debug ("Device setup packet\n");
612                         switch(ao_usb_setup.request) {
613                         case AO_USB_REQ_GET_STATUS:
614                                 debug ("get status\n");
615                                 ao_usb_ep0_in_queue_byte(0);
616                                 ao_usb_ep0_in_queue_byte(0);
617                                 break;
618                         case AO_USB_REQ_SET_ADDRESS:
619                                 debug ("set address %d\n", ao_usb_setup.value);
620                                 ao_usb_address = ao_usb_setup.value;
621                                 ao_usb_address_pending = 1;
622                                 break;
623                         case AO_USB_REQ_GET_DESCRIPTOR:
624                                 debug ("get descriptor %d\n", ao_usb_setup.value);
625                                 ao_usb_get_descriptor(ao_usb_setup.value);
626                                 break;
627                         case AO_USB_REQ_GET_CONFIGURATION:
628                                 debug ("get configuration %d\n", ao_usb_configuration);
629                                 ao_usb_ep0_in_queue_byte(ao_usb_configuration);
630                                 break;
631                         case AO_USB_REQ_SET_CONFIGURATION:
632                                 ao_usb_configuration = ao_usb_setup.value;
633                                 debug ("set configuration %d\n", ao_usb_configuration);
634                                 ao_usb_set_configuration();
635                                 break;
636                         }
637                         break;
638                 case AO_USB_RECIP_INTERFACE:
639                         debug ("Interface setup packet\n");
640                         switch(ao_usb_setup.request) {
641                         case AO_USB_REQ_GET_STATUS:
642                                 ao_usb_ep0_in_queue_byte(0);
643                                 ao_usb_ep0_in_queue_byte(0);
644                                 break;
645                         case AO_USB_REQ_GET_INTERFACE:
646                                 ao_usb_ep0_in_queue_byte(0);
647                                 break;
648                         case AO_USB_REQ_SET_INTERFACE:
649                                 break;
650                         }
651                         break;
652                 case AO_USB_RECIP_ENDPOINT:
653                         debug ("Endpoint setup packet\n");
654                         switch(ao_usb_setup.request) {
655                         case AO_USB_REQ_GET_STATUS:
656                                 ao_usb_ep0_in_queue_byte(0);
657                                 ao_usb_ep0_in_queue_byte(0);
658                                 break;
659                         }
660                         break;
661                 }
662                 break;
663         case AO_USB_TYPE_CLASS:
664                 debug ("Class setup packet\n");
665                 switch (ao_usb_setup.request) {
666                 case AO_USB_SET_LINE_CODING:
667                         debug ("set line coding\n");
668                         ao_usb_ep0_out_set((uint8_t *) &ao_usb_line_coding, 7);
669                         break;
670                 case AO_USB_GET_LINE_CODING:
671                         debug ("get line coding\n");
672                         ao_usb_ep0_in_set((const uint8_t *) &ao_usb_line_coding, 7);
673                         break;
674                 case AO_USB_SET_CONTROL_LINE_STATE:
675                         break;
676                 }
677                 break;
678         }
679
680         /* If we're not waiting to receive data from the host,
681          * queue an IN response
682          */
683         if (ao_usb_ep0_state == AO_USB_EP0_DATA_IN)
684                 ao_usb_ep0_in_start(ao_usb_setup.length);
685 }
686
687 static void
688 ao_usb_ep0_handle(uint8_t receive)
689 {
690         ao_usb_ep0_receive = 0;
691         if (receive & AO_USB_EP0_GOT_SETUP) {
692                 debug ("\tsetup\n");
693                 ao_usb_ep0_setup();
694         }
695         if (receive & AO_USB_EP0_GOT_RX_DATA) {
696                 debug ("\tgot rx data\n");
697                 if (ao_usb_ep0_state == AO_USB_EP0_DATA_OUT) {
698                         ao_usb_ep0_fill();
699                         if (ao_usb_ep0_out_len == 0) {
700                                 ao_usb_ep0_state = AO_USB_EP0_DATA_IN;
701                                 ao_usb_ep0_in_start(0);
702                         }
703                 }
704         }
705         if (receive & AO_USB_EP0_GOT_TX_ACK) {
706                 debug ("\tgot tx ack\n");
707
708 #if HAS_FLIGHT && AO_USB_FORCE_IDLE
709                 ao_flight_force_idle = 1;
710 #endif
711                 /* Wait until the IN packet is received from addr 0
712                  * before assigning our local address
713                  */
714                 if (ao_usb_address_pending)
715                         ao_usb_set_address(ao_usb_address);
716                 if (ao_usb_ep0_state == AO_USB_EP0_DATA_IN)
717                         ao_usb_ep0_flush();
718         }
719 }
720
721 void
722 ao_usb_suspend(void)
723 {
724         stm_usb.cntr |= (1 << STM_USB_CNTR_FSUSP);
725         ao_power_suspend();
726         stm_usb.cntr |= (1 << STM_USB_CNTR_LP_MODE);
727         ao_clock_suspend();
728 }
729
730 void
731 ao_usb_wakeup(void)
732 {
733         ao_clock_resume();
734         stm_usb.cntr &= ~(1 << STM_USB_CNTR_FSUSP);
735         ao_power_resume();
736 }
737
738 void
739 stm_usb_isr(void)
740 {
741         uint32_t        istr = stm_usb.istr;
742
743         stm_usb.istr = ~istr;
744         if (istr & (1 << STM_USB_ISTR_CTR)) {
745                 uint8_t         ep = istr & STM_USB_ISTR_EP_ID_MASK;
746                 uint16_t        epr, epr_write;
747
748                 /* Preserve the SW write bits, don't mess with most HW writable bits,
749                  * clear the CTR_RX and CTR_TX bits
750                  */
751                 epr = stm_usb.epr[ep].r;
752                 epr_write = epr;
753                 epr_write &= STM_USB_EPR_PRESERVE_MASK;
754                 epr_write |= STM_USB_EPR_INVARIANT;
755                 epr_write &= ~(1 << STM_USB_EPR_CTR_RX);
756                 epr_write &= ~(1 << STM_USB_EPR_CTR_TX);
757                 stm_usb.epr[ep].r = epr_write;
758
759                 switch (ep) {
760                 case 0:
761                         ++control_count;
762                         if (ao_usb_epr_ctr_rx(epr)) {
763                                 if (ao_usb_epr_setup(epr))
764                                         ao_usb_ep0_receive |= AO_USB_EP0_GOT_SETUP;
765                                 else
766                                         ao_usb_ep0_receive |= AO_USB_EP0_GOT_RX_DATA;
767                         }
768                         if (ao_usb_epr_ctr_tx(epr))
769                                 ao_usb_ep0_receive |= AO_USB_EP0_GOT_TX_ACK;
770                         ao_usb_ep0_handle(ao_usb_ep0_receive);
771                         break;
772                 case AO_USB_OUT_EPR:
773                         ++out_count;
774                         if (ao_usb_epr_ctr_rx(epr)) {
775                                 _rx_dbg1("RX ISR", epr);
776                                 ao_usb_out_avail = 1;
777                                 _rx_dbg0("out avail set");
778                                 ao_wakeup(AO_USB_OUT_SLEEP_ADDR);
779                                 _rx_dbg0("stdin awoken");
780                         }
781                         break;
782                 case AO_USB_IN_EPR:
783                         ++in_count;
784                         _tx_dbg1("TX ISR", epr);
785                         if (ao_usb_epr_ctr_tx(epr)) {
786                                 ao_usb_in_pending = 0;
787                                 ao_wakeup(&ao_usb_in_pending);
788                         }
789                         break;
790                 case AO_USB_INT_EPR:
791                         ++int_count;
792                         if (ao_usb_epr_ctr_tx(epr))
793                                 _ao_usb_set_stat_tx(AO_USB_INT_EPR, STM_USB_EPR_STAT_TX_NAK);
794                         break;
795                 }
796                 return;
797         }
798
799         if (istr & (1 << STM_USB_ISTR_RESET)) {
800                 ++reset_count;
801                 debug ("\treset\n");
802                 ao_usb_set_ep0();
803         }
804         if (istr & (1 << STM_USB_ISTR_SUSP)) {
805                 ++suspend_count;
806                 debug ("\tsuspend\n");
807                 ao_usb_suspend();
808         }
809         if (istr & (1 << STM_USB_ISTR_WKUP)) {
810                 debug ("\twakeup\n");
811                 ao_usb_wakeup();
812         }
813 }
814
815 /* Queue the current IN buffer for transmission */
816 static void
817 _ao_usb_in_send(void)
818 {
819         _tx_dbg0("in_send start");
820         debug ("send %d\n", ao_usb_tx_count);
821         while (ao_usb_in_pending)
822                 ao_sleep(&ao_usb_in_pending);
823         ao_usb_in_pending = 1;
824         if (ao_usb_tx_count != AO_USB_IN_SIZE)
825                 ao_usb_in_flushed = 1;
826         ao_usb_copy_tx(ao_usb_tx_buffer, ao_usb_in_tx_buffer, ao_usb_tx_count);
827         ao_usb_bdt[AO_USB_IN_EPR].single.addr_tx = ao_usb_in_tx_offset;
828         ao_usb_bdt[AO_USB_IN_EPR].single.count_tx = ao_usb_tx_count;
829         ao_usb_tx_count = 0;
830         _ao_usb_set_stat_tx(AO_USB_IN_EPR, STM_USB_EPR_STAT_TX_VALID);
831         _tx_dbg0("in_send end");
832 }
833
834 /* Wait for a free IN buffer. Interrupts are blocked */
835 static void
836 _ao_usb_in_wait(void)
837 {
838         for (;;) {
839                 /* Check if the current buffer is writable */
840                 if (ao_usb_tx_count < AO_USB_IN_SIZE)
841                         break;
842
843                 _tx_dbg0("in_wait top");
844                 /* Wait for an IN buffer to be ready */
845                 while (ao_usb_in_pending)
846                         ao_sleep(&ao_usb_in_pending);
847                 _tx_dbg0("in_wait bottom");
848         }
849 }
850
851 void
852 ao_usb_flush(void)
853 {
854         if (!ao_usb_running)
855                 return;
856
857         /* Anytime we've sent a character since
858          * the last time we flushed, we'll need
859          * to send a packet -- the only other time
860          * we would send a packet is when that
861          * packet was full, in which case we now
862          * want to send an empty packet
863          */
864         ao_arch_block_interrupts();
865         while (!ao_usb_in_flushed) {
866                 _tx_dbg0("flush top");
867                 _ao_usb_in_send();
868                 _tx_dbg0("flush end");
869         }
870         ao_arch_release_interrupts();
871 }
872
873 void
874 ao_usb_putchar(char c)
875 {
876         if (!ao_usb_running)
877                 return;
878
879         ao_arch_block_interrupts();
880         _ao_usb_in_wait();
881
882         ao_usb_in_flushed = 0;
883         ao_usb_tx_buffer[ao_usb_tx_count++] = (uint8_t) c;
884
885         /* Send the packet when full */
886         if (ao_usb_tx_count == AO_USB_IN_SIZE) {
887                 _tx_dbg0("putchar full");
888                 _ao_usb_in_send();
889                 _tx_dbg0("putchar flushed");
890         }
891         ao_arch_release_interrupts();
892 }
893
894 static void
895 _ao_usb_out_recv(void)
896 {
897         _rx_dbg0("out_recv top");
898         ao_usb_out_avail = 0;
899
900         ao_usb_rx_count = ao_usb_bdt[AO_USB_OUT_EPR].single.count_rx & STM_USB_BDT_COUNT_RX_COUNT_RX_MASK;
901
902         _rx_dbg1("out_recv count", ao_usb_rx_count);
903         debug ("recv %d\n", ao_usb_rx_count);
904         debug_data("Fill OUT len %d:", ao_usb_rx_count);
905         ao_usb_copy_rx(ao_usb_rx_buffer, ao_usb_out_rx_buffer, ao_usb_rx_count);
906         debug_data("\n");
907         ao_usb_rx_pos = 0;
908
909         /* ACK the packet */
910         _ao_usb_set_stat_rx(AO_USB_OUT_EPR, STM_USB_EPR_STAT_RX_VALID);
911 }
912
913 int
914 _ao_usb_pollchar(void)
915 {
916         uint8_t c;
917
918         if (!ao_usb_running)
919                 return AO_READ_AGAIN;
920
921         for (;;) {
922                 if (ao_usb_rx_pos != ao_usb_rx_count)
923                         break;
924
925                 _rx_dbg0("poll check");
926                 /* Check to see if a packet has arrived */
927                 if (!ao_usb_out_avail) {
928                         _rx_dbg0("poll none");
929                         return AO_READ_AGAIN;
930                 }
931                 _ao_usb_out_recv();
932         }
933
934         /* Pull a character out of the fifo */
935         c = ao_usb_rx_buffer[ao_usb_rx_pos++];
936         return c;
937 }
938
939 char
940 ao_usb_getchar(void)
941 {
942         int     c;
943
944         ao_arch_block_interrupts();
945         while ((c = _ao_usb_pollchar()) == AO_READ_AGAIN)
946                 ao_sleep(AO_USB_OUT_SLEEP_ADDR);
947         ao_arch_release_interrupts();
948         return c;
949 }
950
951 #if AO_USB_DIRECTIO
952 uint16_t *
953 ao_usb_alloc(void)
954 {
955         uint16_t        *buffer;
956
957         buffer = ao_usb_packet_buffer_addr(ao_usb_sram_addr);
958         ao_usb_sram_addr += AO_USB_IN_SIZE;
959         return buffer;
960 }
961
962 void
963 ao_usb_free(uint16_t *addr)
964 {
965         uint16_t        offset = ao_usb_packet_buffer_offset(addr);
966         if (offset < ao_usb_sram_addr)
967                 ao_usb_sram_addr = offset;
968 }
969
970 void
971 ao_usb_write(uint16_t *buffer, uint16_t len)
972 {
973         ao_arch_block_interrupts();
974
975         /* Wait for everything to be ready at the same time */
976         for (;;) {
977                 /* Make sure USB is connected */
978                 if (!ao_usb_running) {
979                         ao_sleep(&ao_usb_running);
980                         continue;
981                 }
982
983                 /* Flush any pending regular I/O */
984                 if (ao_usb_tx_count) {
985                         _ao_usb_in_send();
986                         continue;
987                 }
988
989                 /* Wait for an idle IN buffer */
990                 if (ao_usb_in_pending) {
991                         ao_sleep(&ao_usb_in_pending);
992                         continue;
993                 }
994                 break;
995         }
996
997         ao_usb_in_pending = 1;
998         ao_usb_in_flushed = (len != AO_USB_IN_SIZE);
999         ao_usb_bdt[AO_USB_IN_EPR].single.addr_tx = ao_usb_packet_buffer_offset(buffer);
1000         ao_usb_bdt[AO_USB_IN_EPR].single.count_tx = len;
1001         _ao_usb_set_stat_tx(AO_USB_IN_EPR, STM_USB_EPR_STAT_TX_VALID);
1002         ao_arch_release_interrupts();
1003 }
1004 #endif
1005
1006 void
1007 ao_usb_disable(void)
1008 {
1009         ao_arch_block_interrupts();
1010         stm_usb.cntr = (1 << STM_USB_CNTR_FRES);
1011         stm_usb.istr = 0;
1012
1013         /* Disable USB pull-up */
1014         stm_usb.bcdr &= ~(1 << STM_USB_BCDR_DPPU);
1015
1016         /* Switch off the device */
1017         stm_usb.cntr = (1 << STM_USB_CNTR_PDWN) | (1 << STM_USB_CNTR_FRES);
1018
1019         /* Disable the interface */
1020         stm_rcc.apb1enr &= ~(1 << STM_RCC_APB1ENR_USBEN);
1021         ao_arch_release_interrupts();
1022 }
1023
1024 void
1025 ao_usb_enable(void)
1026 {
1027         int     t;
1028
1029         /* Select HSI48 as USB clock source */
1030         stm_rcc.cfgr3 &= ~(1 << STM_RCC_CFGR3_USBSW);
1031
1032         /* Enable USB device */
1033         stm_rcc.apb1enr |= (1 << STM_RCC_APB1ENR_USBEN);
1034
1035         /* Clear reset condition */
1036         stm_rcc.apb1rstr &= ~(1 << STM_RCC_APB1RSTR_USBRST);
1037
1038         /* Disable USB pull-up */
1039         stm_usb.bcdr &= ~(1 << STM_USB_BCDR_DPPU);
1040
1041         /* Do not touch the GPIOA configuration; USB takes priority
1042          * over GPIO on pins A11 and A12, but if you select alternate
1043          * input 10 (the documented correct selection), then USB is
1044          * pulled low and doesn't work at all
1045          */
1046
1047         ao_arch_block_interrupts();
1048
1049         /* Route interrupts */
1050         stm_nvic_set_enable(STM_ISR_USB_POS);
1051         stm_nvic_set_priority(STM_ISR_USB_POS, 3);
1052
1053         ao_usb_configuration = 0;
1054
1055         /* Set up buffer descriptors */
1056         ao_usb_init_btable();
1057
1058         /* Reset the USB controller */
1059         stm_usb.cntr = (1 << STM_USB_CNTR_FRES);
1060
1061         /* Clear the reset bit */
1062         stm_usb.cntr = 0;
1063
1064         /* Clear any spurious interrupts */
1065         stm_usb.istr = 0;
1066
1067         ao_usb_set_ep0();
1068
1069         debug ("ao_usb_enable\n");
1070
1071         /* Enable interrupts */
1072         stm_usb.cntr = ((1 << STM_USB_CNTR_CTRM) |
1073                         (0 << STM_USB_CNTR_PMAOVRM) |
1074                         (0 << STM_USB_CNTR_ERRM) |
1075                         (1 << STM_USB_CNTR_WKUPM) |
1076                         (1 << STM_USB_CNTR_SUSPM) |
1077                         (1 << STM_USB_CNTR_RESETM) |
1078                         (0 << STM_USB_CNTR_SOFM) |
1079                         (0 << STM_USB_CNTR_ESOFM) |
1080                         (0 << STM_USB_CNTR_RESUME) |
1081                         (0 << STM_USB_CNTR_FSUSP) |
1082                         (0 << STM_USB_CNTR_LP_MODE) |
1083                         (0 << STM_USB_CNTR_PDWN) |
1084                         (0 << STM_USB_CNTR_FRES));
1085
1086         ao_arch_release_interrupts();
1087
1088         for (t = 0; t < 1000; t++)
1089                 ao_arch_nop();
1090
1091         /* Enable USB pull-up */
1092         stm_usb.bcdr |= (1 << STM_USB_BCDR_DPPU);
1093 }
1094
1095 #if USB_ECHO
1096 struct ao_task ao_usb_echo_task;
1097
1098 static void
1099 ao_usb_echo(void)
1100 {
1101         char    c;
1102
1103         for (;;) {
1104                 c = ao_usb_getchar();
1105                 ao_usb_putchar(c);
1106                 ao_usb_flush();
1107         }
1108 }
1109 #endif
1110
1111 #if USB_STATUS
1112 static void
1113 ao_usb_irq(void)
1114 {
1115         printf ("control: %d out: %d in: %d int: %d reset: %d suspend %d\n",
1116                 control_count, out_count, in_count, int_count, reset_count, suspend_count);
1117 }
1118
1119 __code struct ao_cmds ao_usb_cmds[] = {
1120         { ao_usb_irq, "I\0Show USB interrupt counts" },
1121         { 0, NULL }
1122 };
1123 #endif
1124
1125 void
1126 ao_usb_init(void)
1127 {
1128         /* Turn on syscfg */
1129         stm_rcc.apb2enr |= (1 << STM_RCC_APB2ENR_SYSCFGCOMPEN);
1130
1131         /* Set PA11/PA12 remapping bit */
1132         stm_syscfg.cfgr1 |= (AO_PA11_PA12_RMP << STM_SYSCFG_CFGR1_PA11_PA12_RMP);
1133
1134         ao_usb_enable();
1135
1136         debug ("ao_usb_init\n");
1137         ao_usb_ep0_state = AO_USB_EP0_IDLE;
1138
1139         ao_usb_alloc_buffers();
1140
1141 #if USB_ECHO
1142         ao_add_task(&ao_usb_echo_task, ao_usb_echo, "usb echo");
1143 #endif
1144 #if USB_STATUS
1145         ao_cmd_register(&ao_usb_cmds[0]);
1146 #endif
1147 #if !USB_ECHO
1148 #if USE_USB_STDIO
1149         ao_add_stdio(_ao_usb_pollchar, ao_usb_putchar, ao_usb_flush);
1150 #endif
1151 #endif
1152 }
1153
1154 #if TX_DBG || RX_DBG
1155
1156 struct ao_usb_dbg {
1157         int             line;
1158         char            *msg;
1159         uint32_t        value;
1160         uint32_t        primask;
1161 #if TX_DBG
1162         uint16_t        in_count;
1163         uint32_t        in_epr;
1164         uint32_t        in_pending;
1165         uint32_t        tx_count;
1166         uint32_t        in_flushed;
1167 #endif
1168 #if RX_DBG
1169         uint8_t         rx_count;
1170         uint8_t         rx_pos;
1171         uint8_t         out_avail;
1172         uint32_t        out_epr;
1173 #endif
1174 };
1175
1176 #define NUM_USB_DBG     128
1177
1178 static struct ao_usb_dbg dbg[128];
1179 static int dbg_i;
1180
1181 static void _dbg(int line, char *msg, uint32_t value)
1182 {
1183         uint32_t        primask;
1184         dbg[dbg_i].line = line;
1185         dbg[dbg_i].msg = msg;
1186         dbg[dbg_i].value = value;
1187         asm("mrs %0,primask" : "=&r" (primask));
1188         dbg[dbg_i].primask = primask;
1189 #if TX_DBG
1190         dbg[dbg_i].in_count = in_count;
1191         dbg[dbg_i].in_epr = stm_usb.epr[AO_USB_IN_EPR];
1192         dbg[dbg_i].in_pending = ao_usb_in_pending;
1193         dbg[dbg_i].tx_count = ao_usb_tx_count;
1194         dbg[dbg_i].in_flushed = ao_usb_in_flushed;
1195 #endif
1196 #if RX_DBG
1197         dbg[dbg_i].rx_count = ao_usb_rx_count;
1198         dbg[dbg_i].rx_pos = ao_usb_rx_pos;
1199         dbg[dbg_i].out_avail = ao_usb_out_avail;
1200         dbg[dbg_i].out_epr = stm_usb.epr[AO_USB_OUT_EPR];
1201 #endif
1202         if (++dbg_i == NUM_USB_DBG)
1203                 dbg_i = 0;
1204 }
1205 #endif