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