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