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