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