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