b9d863685230383d111b3f64ad514e5211e5cc82
[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
22 #define USB_DEBUG       0
23 #define USB_DEBUG_DATA  0
24 #define USB_ECHO        0
25
26 #ifndef USE_USB_STDIO
27 #define USE_USB_STDIO   1
28 #endif
29
30 #if USE_USB_STDIO
31 #define AO_USB_OUT_SLEEP_ADDR   (&ao_stdin_ready)
32 #else
33 #define AO_USB_OUT_SLEEP_ADDR   (&ao_usb_out_avail)
34 #endif
35
36 #if USB_DEBUG
37 #define debug(format, args...)  printf(format, ## args);
38 #else
39 #define debug(format, args...)
40 #endif
41
42 #if USB_DEBUG_DATA
43 #define debug_data(format, args...)     printf(format, ## args);
44 #else
45 #define debug_data(format, args...)
46 #endif
47
48 struct ao_usb_setup {
49         uint8_t         dir_type_recip;
50         uint8_t         request;
51         uint16_t        value;
52         uint16_t        index;
53         uint16_t        length;
54 } ao_usb_setup;
55
56 static uint8_t  ao_usb_ep0_state;
57
58 /* Pending EP0 IN data */
59 static const uint8_t    *ao_usb_ep0_in_data;    /* Remaining data */
60 static uint8_t          ao_usb_ep0_in_len;      /* Remaining amount */
61
62 /* Temp buffer for smaller EP0 in data */
63 static uint8_t  ao_usb_ep0_in_buf[2];
64
65 /* Pending EP0 OUT data */
66 static uint8_t *ao_usb_ep0_out_data;
67 static uint8_t  ao_usb_ep0_out_len;
68
69 /*
70  * Objects allocated in special USB memory
71  */
72
73 /* Buffer description tables */
74 static union stm_usb_bdt        *ao_usb_bdt;
75 /* USB address of end of allocated storage */
76 static uint16_t ao_usb_sram_addr;
77
78 /* Pointer to ep0 tx/rx buffers in USB memory */
79 static uint16_t *ao_usb_ep0_tx_buffer;
80 static uint16_t *ao_usb_ep0_rx_buffer;
81
82 /* Pointer to bulk data tx/rx buffers in USB memory */
83 static uint16_t *ao_usb_in_tx_buffer;
84 static uint16_t *ao_usb_out_rx_buffer;
85
86 /* System ram shadow of USB buffer; writing individual bytes is
87  * too much of a pain (sigh) */
88 static uint8_t  ao_usb_tx_buffer[AO_USB_IN_SIZE];
89 static uint8_t  ao_usb_tx_count;
90
91 static uint8_t  ao_usb_rx_buffer[AO_USB_OUT_SIZE];
92 static uint8_t  ao_usb_rx_count, ao_usb_rx_pos;
93
94 /*
95  * End point register indices
96  */
97
98 #define AO_USB_CONTROL_EPR      0
99 #define AO_USB_INT_EPR          1
100 #define AO_USB_OUT_EPR          2
101 #define AO_USB_IN_EPR           3
102
103 /* Marks when we don't need to send an IN packet.
104  * This happens only when the last IN packet is not full,
105  * otherwise the host will expect to keep seeing packets.
106  * Send a zero-length packet as required
107  */
108 static uint8_t  ao_usb_in_flushed;
109
110 /* Marks when we have delivered an IN packet to the hardware
111  * and it has not been received yet. ao_sleep on this address
112  * to wait for it to be delivered.
113  */
114 static uint8_t  ao_usb_in_pending;
115
116 /* Marks when an OUT packet has been received by the hardware
117  * but not pulled to the shadow buffer.
118  */
119 static uint8_t  ao_usb_out_avail;
120 uint8_t         ao_usb_running;
121 static uint8_t  ao_usb_configuration;
122
123 #define AO_USB_EP0_GOT_RESET    1
124 #define AO_USB_EP0_GOT_SETUP    2
125 #define AO_USB_EP0_GOT_RX_DATA  4
126 #define AO_USB_EP0_GOT_TX_ACK   8
127
128 static uint8_t  ao_usb_ep0_receive;
129 static uint8_t  ao_usb_address;
130 static uint8_t  ao_usb_address_pending;
131
132 static inline uint32_t set_toggle(uint32_t      current_value,
133                                    uint32_t     mask,
134                                    uint32_t     desired_value)
135 {
136         return (current_value ^ desired_value) & mask;
137 }
138
139 static inline uint16_t *ao_usb_packet_buffer_addr(uint16_t sram_addr)
140 {
141         return (uint16_t *) (stm_usb_sram + sram_addr);
142 }
143
144 static inline uint32_t ao_usb_epr_stat_rx(uint32_t epr) {
145         return (epr >> STM_USB_EPR_STAT_RX) & STM_USB_EPR_STAT_RX_MASK;
146 }
147
148 static inline uint32_t ao_usb_epr_stat_tx(uint32_t epr) {
149         return (epr >> STM_USB_EPR_STAT_TX) & STM_USB_EPR_STAT_TX_MASK;
150 }
151
152 static inline uint32_t ao_usb_epr_ctr_rx(uint32_t epr) {
153         return (epr >> STM_USB_EPR_CTR_RX) & 1;
154 }
155
156 static inline uint32_t ao_usb_epr_ctr_tx(uint32_t epr) {
157         return (epr >> STM_USB_EPR_CTR_TX) & 1;
158 }
159
160 static inline uint32_t ao_usb_epr_setup(uint32_t epr) {
161         return (epr >> STM_USB_EPR_SETUP) & 1;
162 }
163
164 static inline uint32_t ao_usb_epr_dtog_rx(uint32_t epr) {
165         return (epr >> STM_USB_EPR_DTOG_RX) & 1;
166 }
167
168 static inline uint32_t ao_usb_epr_dtog_tx(uint32_t epr) {
169         return (epr >> STM_USB_EPR_DTOG_TX) & 1;
170 }
171
172 /*
173  * Set current device address and mark the
174  * interface as active
175  */
176 void
177 ao_usb_set_address(uint8_t address)
178 {
179         debug("ao_usb_set_address %02x\n", address);
180         stm_usb.daddr = (1 << STM_USB_DADDR_EF) | address;
181         ao_usb_address_pending = 0;
182 }
183
184 /*
185  * Write these values to preserve register contents under HW changes
186  */
187
188 #define STM_USB_EPR_INVARIANT   ((1 << STM_USB_EPR_CTR_RX) |            \
189                                  (STM_USB_EPR_DTOG_RX_WRITE_INVARIANT << STM_USB_EPR_DTOG_RX) | \
190                                  (STM_USB_EPR_STAT_RX_WRITE_INVARIANT << STM_USB_EPR_STAT_RX) | \
191                                  (1 << STM_USB_EPR_CTR_TX) |            \
192                                  (STM_USB_EPR_DTOG_TX_WRITE_INVARIANT << STM_USB_EPR_DTOG_TX) | \
193                                  (STM_USB_EPR_STAT_TX_WRITE_INVARIANT << STM_USB_EPR_STAT_TX))
194
195 #define STM_USB_EPR_INVARIANT_MASK      ((1 << STM_USB_EPR_CTR_RX) |    \
196                                          (STM_USB_EPR_DTOG_RX_MASK << STM_USB_EPR_DTOG_RX) | \
197                                          (STM_USB_EPR_STAT_RX_MASK << STM_USB_EPR_STAT_RX) | \
198                                          (1 << STM_USB_EPR_CTR_TX) |    \
199                                          (STM_USB_EPR_DTOG_TX_MASK << STM_USB_EPR_DTOG_TX) | \
200                                          (STM_USB_EPR_STAT_TX_MASK << STM_USB_EPR_STAT_TX))
201
202 /*
203  * These bits are purely under sw control, so preserve them in the
204  * register by re-writing what was read
205  */
206 #define STM_USB_EPR_PRESERVE_MASK       ((STM_USB_EPR_EP_TYPE_MASK << STM_USB_EPR_EP_TYPE) | \
207                                          (1 << STM_USB_EPR_EP_KIND) |   \
208                                          (STM_USB_EPR_EA_MASK << STM_USB_EPR_EA))
209
210 #define TX_DBG 0
211 #define RX_DBG 0
212
213 #if TX_DBG
214 #define _tx_dbg0(msg) _dbg(__LINE__,msg,0)
215 #define _tx_dbg1(msg,value) _dbg(__LINE__,msg,value)
216 #else
217 #define _tx_dbg0(msg)
218 #define _tx_dbg1(msg,value)
219 #endif
220
221 #if RX_DBG
222 #define _rx_dbg0(msg) _dbg(__LINE__,msg,0)
223 #define _rx_dbg1(msg,value) _dbg(__LINE__,msg,value)
224 #else
225 #define _rx_dbg0(msg)
226 #define _rx_dbg1(msg,value)
227 #endif
228
229 #if TX_DBG || RX_DBG
230 static void _dbg(int line, char *msg, uint32_t value);
231 #endif
232
233 /*
234  * Set the state of the specified endpoint register to a new
235  * value. This is tricky because the bits toggle where the new
236  * value is one, and we need to write invariant values in other
237  * spots of the register. This hardware is strange...
238  */
239 static void
240 _ao_usb_set_stat_tx(int ep, uint32_t stat_tx)
241 {
242         uint16_t        epr_write, epr_old;
243
244         _tx_dbg1("set_stat_tx top", stat_tx);
245         epr_old = epr_write = stm_usb.epr[ep].r;
246         epr_write &= STM_USB_EPR_PRESERVE_MASK;
247         epr_write |= STM_USB_EPR_INVARIANT;
248         epr_write |= set_toggle(epr_old,
249                               STM_USB_EPR_STAT_TX_MASK << STM_USB_EPR_STAT_TX,
250                               stat_tx << STM_USB_EPR_STAT_TX);
251         stm_usb.epr[ep].r = epr_write;
252         _tx_dbg1("set_stat_tx bottom", epr_write);
253 }
254
255 static void
256 ao_usb_set_stat_tx(int ep, uint32_t stat_tx)
257 {
258         ao_arch_block_interrupts();
259         _ao_usb_set_stat_tx(ep, stat_tx);
260         ao_arch_release_interrupts();
261 }
262
263 static void
264 _ao_usb_set_stat_rx(int ep, uint32_t stat_rx) {
265         uint16_t        epr_write, epr_old;
266
267         epr_write = epr_old = stm_usb.epr[ep].r;
268         epr_write &= STM_USB_EPR_PRESERVE_MASK;
269         epr_write |= STM_USB_EPR_INVARIANT;
270         epr_write |= set_toggle(epr_old,
271                               STM_USB_EPR_STAT_RX_MASK << STM_USB_EPR_STAT_RX,
272                               stat_rx << STM_USB_EPR_STAT_RX);
273         stm_usb.epr[ep].r = epr_write;
274 }
275
276 static void
277 ao_usb_set_stat_rx(int ep, uint32_t stat_rx) {
278         ao_arch_block_interrupts();
279         _ao_usb_set_stat_rx(ep, stat_rx);
280         ao_arch_release_interrupts();
281 }
282
283 /*
284  * Set just endpoint 0, for use during startup
285  */
286
287 static void
288 ao_usb_init_ep(uint8_t ep, uint32_t addr, uint32_t type, uint32_t stat_rx, uint32_t stat_tx)
289 {
290         uint16_t                epr;
291
292         ao_arch_block_interrupts();
293         epr = stm_usb.epr[ep].r;
294         epr = ((0 << STM_USB_EPR_CTR_RX) |
295                (epr & (1 << STM_USB_EPR_DTOG_RX)) |
296                set_toggle(epr,
297                           (STM_USB_EPR_STAT_RX_MASK << STM_USB_EPR_STAT_RX),
298                           (stat_rx << STM_USB_EPR_STAT_RX)) |
299                (type << STM_USB_EPR_EP_TYPE) |
300                (0 << STM_USB_EPR_EP_KIND) |
301                (0 << STM_USB_EPR_CTR_TX) |
302                (epr & (1 << STM_USB_EPR_DTOG_TX)) |
303                set_toggle(epr,
304                           (STM_USB_EPR_STAT_TX_MASK << STM_USB_EPR_STAT_TX),
305                           (stat_tx << STM_USB_EPR_STAT_TX)) |
306                (addr << STM_USB_EPR_EA));
307         stm_usb.epr[ep].r = epr;
308         ao_arch_release_interrupts();
309         debug ("writing epr[%d] 0x%04x wrote 0x%04x\n",
310                ep, epr, stm_usb.epr[ep].r);
311 }
312
313 static void
314 ao_usb_init_btable(void)
315 {
316         ao_usb_sram_addr = 0;
317
318         ao_usb_bdt = (void *) stm_usb_sram;
319
320         ao_usb_sram_addr += 8 * STM_USB_BDT_SIZE;
321
322         /* Set up EP 0 - a Control end point with 32 bytes of in and out buffers */
323
324         ao_usb_bdt[0].single.addr_tx = ao_usb_sram_addr;
325         ao_usb_bdt[0].single.count_tx = 0;
326         ao_usb_ep0_tx_buffer = ao_usb_packet_buffer_addr(ao_usb_sram_addr);
327         ao_usb_sram_addr += AO_USB_CONTROL_SIZE;
328
329         ao_usb_bdt[0].single.addr_rx = ao_usb_sram_addr;
330         ao_usb_bdt[0].single.count_rx = ((1 << STM_USB_BDT_COUNT_RX_BL_SIZE) |
331                                   (((AO_USB_CONTROL_SIZE / 32) - 1) << STM_USB_BDT_COUNT_RX_NUM_BLOCK));
332         ao_usb_ep0_rx_buffer = ao_usb_packet_buffer_addr(ao_usb_sram_addr);
333         ao_usb_sram_addr += AO_USB_CONTROL_SIZE;
334
335 }
336
337 static void
338 ao_usb_set_ep0(void)
339 {
340         int                     e;
341
342         ao_usb_init_btable();
343
344         /* buffer table is at the start of USB memory */
345         stm_usb.btable = 0;
346
347         ao_usb_init_ep(AO_USB_CONTROL_EPR, AO_USB_CONTROL_EP,
348                        STM_USB_EPR_EP_TYPE_CONTROL,
349                        STM_USB_EPR_STAT_RX_VALID,
350                        STM_USB_EPR_STAT_TX_NAK);
351
352         /* Clear all of the other endpoints */
353         for (e = 1; e < 8; e++) {
354                 ao_usb_init_ep(e, 0,
355                                STM_USB_EPR_EP_TYPE_CONTROL,
356                                STM_USB_EPR_STAT_RX_DISABLED,
357                                STM_USB_EPR_STAT_TX_DISABLED);
358         }
359
360         ao_usb_set_address(0);
361 }
362
363 static void
364 ao_usb_set_configuration(void)
365 {
366         debug ("ao_usb_set_configuration\n");
367
368         /* Set up the INT end point */
369         ao_usb_bdt[AO_USB_INT_EPR].single.addr_tx = ao_usb_sram_addr;
370         ao_usb_bdt[AO_USB_INT_EPR].single.count_tx = 0;
371         ao_usb_in_tx_buffer = ao_usb_packet_buffer_addr(ao_usb_sram_addr);
372         ao_usb_sram_addr += AO_USB_INT_SIZE;
373
374         ao_usb_init_ep(AO_USB_INT_EPR,
375                        AO_USB_INT_EP,
376                        STM_USB_EPR_EP_TYPE_INTERRUPT,
377                        STM_USB_EPR_STAT_RX_DISABLED,
378                        STM_USB_EPR_STAT_TX_NAK);
379
380         /* Set up the OUT end point */
381         ao_usb_bdt[AO_USB_OUT_EPR].single.addr_rx = ao_usb_sram_addr;
382         ao_usb_bdt[AO_USB_OUT_EPR].single.count_rx = ((1 << STM_USB_BDT_COUNT_RX_BL_SIZE) |
383                                                       (((AO_USB_OUT_SIZE / 32) - 1) << STM_USB_BDT_COUNT_RX_NUM_BLOCK));
384         ao_usb_out_rx_buffer = ao_usb_packet_buffer_addr(ao_usb_sram_addr);
385         ao_usb_sram_addr += AO_USB_OUT_SIZE;
386
387         ao_usb_init_ep(AO_USB_OUT_EPR,
388                        AO_USB_OUT_EP,
389                        STM_USB_EPR_EP_TYPE_BULK,
390                        STM_USB_EPR_STAT_RX_VALID,
391                        STM_USB_EPR_STAT_TX_DISABLED);
392
393         /* Set up the IN end point */
394         ao_usb_bdt[AO_USB_IN_EPR].single.addr_tx = ao_usb_sram_addr;
395         ao_usb_bdt[AO_USB_IN_EPR].single.count_tx = 0;
396         ao_usb_in_tx_buffer = ao_usb_packet_buffer_addr(ao_usb_sram_addr);
397         ao_usb_sram_addr += AO_USB_IN_SIZE;
398
399         ao_usb_init_ep(AO_USB_IN_EPR,
400                        AO_USB_IN_EP,
401                        STM_USB_EPR_EP_TYPE_BULK,
402                        STM_USB_EPR_STAT_RX_DISABLED,
403                        STM_USB_EPR_STAT_TX_NAK);
404
405         ao_usb_running = 1;
406 }
407
408 static uint16_t control_count;
409 static uint16_t int_count;
410 static uint16_t in_count;
411 static uint16_t out_count;
412 static uint16_t reset_count;
413
414 /* The USB memory must be accessed in 16-bit units
415  */
416
417 static void
418 ao_usb_write(const uint8_t *src, uint16_t *base, uint16_t bytes)
419 {
420         while (bytes >= 2) {
421                 *base++ = src[0] | (src[1] << 8);
422                 src += 2;
423                 bytes -= 2;
424         }
425         if (bytes)
426                 *base = *src;
427 }
428
429 static void
430 ao_usb_read(uint8_t *dst, uint16_t *base, uint16_t bytes)
431 {
432         while (bytes >= 2) {
433                 uint16_t s = *base++;
434                 dst[0] = s;
435                 dst[1] = s >> 8;
436                 dst += 2;
437                 bytes -= 2;
438         }
439         if (bytes)
440                 *dst = *base;
441 }
442
443 /* Send an IN data packet */
444 static void
445 ao_usb_ep0_flush(void)
446 {
447         uint8_t this_len;
448
449         /* Check to see if the endpoint is still busy */
450         if (ao_usb_epr_stat_tx(stm_usb.epr[0].r) == STM_USB_EPR_STAT_TX_VALID) {
451                 debug("EP0 not accepting IN data\n");
452                 return;
453         }
454
455         this_len = ao_usb_ep0_in_len;
456         if (this_len > AO_USB_CONTROL_SIZE)
457                 this_len = AO_USB_CONTROL_SIZE;
458
459         if (this_len < AO_USB_CONTROL_SIZE)
460                 ao_usb_ep0_state = AO_USB_EP0_IDLE;
461
462         ao_usb_ep0_in_len -= this_len;
463
464         debug_data ("Flush EP0 len %d:", this_len);
465         ao_usb_write(ao_usb_ep0_in_data, ao_usb_ep0_tx_buffer, this_len);
466         debug_data ("\n");
467         ao_usb_ep0_in_data += this_len;
468
469         /* Mark the endpoint as TX valid to send the packet */
470         ao_usb_bdt[AO_USB_CONTROL_EPR].single.count_tx = this_len;
471         ao_usb_set_stat_tx(AO_USB_CONTROL_EPR, STM_USB_EPR_STAT_TX_VALID);
472         debug ("queue tx. epr 0 now %08x\n", stm_usb.epr[AO_USB_CONTROL_EPR]);
473 }
474
475 /* Read data from the ep0 OUT fifo */
476 static void
477 ao_usb_ep0_fill(void)
478 {
479         uint16_t        len = ao_usb_bdt[0].single.count_rx & STM_USB_BDT_COUNT_RX_COUNT_RX_MASK;
480
481         if (len > ao_usb_ep0_out_len)
482                 len = ao_usb_ep0_out_len;
483         ao_usb_ep0_out_len -= len;
484
485         /* Pull all of the data out of the packet */
486         debug_data ("Fill EP0 len %d:", len);
487         ao_usb_read(ao_usb_ep0_out_data, ao_usb_ep0_rx_buffer, len);
488         debug_data ("\n");
489         ao_usb_ep0_out_data += len;
490
491         /* ACK the packet */
492         ao_usb_set_stat_rx(0, STM_USB_EPR_STAT_RX_VALID);
493 }
494
495 static void
496 ao_usb_ep0_in_reset(void)
497 {
498         ao_usb_ep0_in_data = ao_usb_ep0_in_buf;
499         ao_usb_ep0_in_len = 0;
500 }
501
502 static void
503 ao_usb_ep0_in_queue_byte(uint8_t a)
504 {
505         if (ao_usb_ep0_in_len < sizeof (ao_usb_ep0_in_buf))
506                 ao_usb_ep0_in_buf[ao_usb_ep0_in_len++] = a;
507 }
508
509 static void
510 ao_usb_ep0_in_set(const uint8_t *data, uint8_t len)
511 {
512         ao_usb_ep0_in_data = data;
513         ao_usb_ep0_in_len = len;
514 }
515
516 static void
517 ao_usb_ep0_out_set(uint8_t *data, uint8_t len)
518 {
519         ao_usb_ep0_out_data = data;
520         ao_usb_ep0_out_len = len;
521 }
522
523 static void
524 ao_usb_ep0_in_start(uint16_t max)
525 {
526         /* Don't send more than asked for */
527         if (ao_usb_ep0_in_len > max)
528                 ao_usb_ep0_in_len = max;
529         ao_usb_ep0_flush();
530 }
531
532 static struct ao_usb_line_coding ao_usb_line_coding = {115200, 0, 0, 8};
533
534 /* Walk through the list of descriptors and find a match
535  */
536 static void
537 ao_usb_get_descriptor(uint16_t value)
538 {
539         const uint8_t           *descriptor;
540         uint8_t         type = value >> 8;
541         uint8_t         index = value;
542
543         descriptor = ao_usb_descriptors;
544         while (descriptor[0] != 0) {
545                 if (descriptor[1] == type && index-- == 0) {
546                         uint8_t len;
547                         if (type == AO_USB_DESC_CONFIGURATION)
548                                 len = descriptor[2];
549                         else
550                                 len = descriptor[0];
551                         ao_usb_ep0_in_set(descriptor, len);
552                         break;
553                 }
554                 descriptor += descriptor[0];
555         }
556 }
557
558 static void
559 ao_usb_ep0_setup(void)
560 {
561         /* Pull the setup packet out of the fifo */
562         ao_usb_ep0_out_set((uint8_t *) &ao_usb_setup, 8);
563         ao_usb_ep0_fill();
564         if (ao_usb_ep0_out_len != 0) {
565                 debug ("invalid setup packet length\n");
566                 return;
567         }
568
569         if ((ao_usb_setup.dir_type_recip & AO_USB_DIR_IN) || ao_usb_setup.length == 0)
570                 ao_usb_ep0_state = AO_USB_EP0_DATA_IN;
571         else
572                 ao_usb_ep0_state = AO_USB_EP0_DATA_OUT;
573
574         ao_usb_ep0_in_reset();
575
576         switch(ao_usb_setup.dir_type_recip & AO_USB_SETUP_TYPE_MASK) {
577         case AO_USB_TYPE_STANDARD:
578                 debug ("Standard setup packet\n");
579                 switch(ao_usb_setup.dir_type_recip & AO_USB_SETUP_RECIP_MASK) {
580                 case AO_USB_RECIP_DEVICE:
581                         debug ("Device setup packet\n");
582                         switch(ao_usb_setup.request) {
583                         case AO_USB_REQ_GET_STATUS:
584                                 debug ("get status\n");
585                                 ao_usb_ep0_in_queue_byte(0);
586                                 ao_usb_ep0_in_queue_byte(0);
587                                 break;
588                         case AO_USB_REQ_SET_ADDRESS:
589                                 debug ("set address %d\n", ao_usb_setup.value);
590                                 ao_usb_address = ao_usb_setup.value;
591                                 ao_usb_address_pending = 1;
592                                 break;
593                         case AO_USB_REQ_GET_DESCRIPTOR:
594                                 debug ("get descriptor %d\n", ao_usb_setup.value);
595                                 ao_usb_get_descriptor(ao_usb_setup.value);
596                                 break;
597                         case AO_USB_REQ_GET_CONFIGURATION:
598                                 debug ("get configuration %d\n", ao_usb_configuration);
599                                 ao_usb_ep0_in_queue_byte(ao_usb_configuration);
600                                 break;
601                         case AO_USB_REQ_SET_CONFIGURATION:
602                                 ao_usb_configuration = ao_usb_setup.value;
603                                 debug ("set configuration %d\n", ao_usb_configuration);
604                                 ao_usb_set_configuration();
605                                 break;
606                         }
607                         break;
608                 case AO_USB_RECIP_INTERFACE:
609                         debug ("Interface setup packet\n");
610                         switch(ao_usb_setup.request) {
611                         case AO_USB_REQ_GET_STATUS:
612                                 ao_usb_ep0_in_queue_byte(0);
613                                 ao_usb_ep0_in_queue_byte(0);
614                                 break;
615                         case AO_USB_REQ_GET_INTERFACE:
616                                 ao_usb_ep0_in_queue_byte(0);
617                                 break;
618                         case AO_USB_REQ_SET_INTERFACE:
619                                 break;
620                         }
621                         break;
622                 case AO_USB_RECIP_ENDPOINT:
623                         debug ("Endpoint setup packet\n");
624                         switch(ao_usb_setup.request) {
625                         case AO_USB_REQ_GET_STATUS:
626                                 ao_usb_ep0_in_queue_byte(0);
627                                 ao_usb_ep0_in_queue_byte(0);
628                                 break;
629                         }
630                         break;
631                 }
632                 break;
633         case AO_USB_TYPE_CLASS:
634                 debug ("Class setup packet\n");
635                 switch (ao_usb_setup.request) {
636                 case AO_USB_SET_LINE_CODING:
637                         debug ("set line coding\n");
638                         ao_usb_ep0_out_set((uint8_t *) &ao_usb_line_coding, 7);
639                         break;
640                 case AO_USB_GET_LINE_CODING:
641                         debug ("get line coding\n");
642                         ao_usb_ep0_in_set((const uint8_t *) &ao_usb_line_coding, 7);
643                         break;
644                 case AO_USB_SET_CONTROL_LINE_STATE:
645                         break;
646                 }
647                 break;
648         }
649
650         /* If we're not waiting to receive data from the host,
651          * queue an IN response
652          */
653         if (ao_usb_ep0_state == AO_USB_EP0_DATA_IN)
654                 ao_usb_ep0_in_start(ao_usb_setup.length);
655 }
656
657 static void
658 ao_usb_ep0_handle(uint8_t receive)
659 {
660         ao_usb_ep0_receive = 0;
661         if (receive & AO_USB_EP0_GOT_RESET) {
662                 debug ("\treset\n");
663                 ao_usb_set_ep0();
664                 return;
665         }
666         if (receive & AO_USB_EP0_GOT_SETUP) {
667                 debug ("\tsetup\n");
668                 ao_usb_ep0_setup();
669         }
670         if (receive & AO_USB_EP0_GOT_RX_DATA) {
671                 debug ("\tgot rx data\n");
672                 if (ao_usb_ep0_state == AO_USB_EP0_DATA_OUT) {
673                         ao_usb_ep0_fill();
674                         if (ao_usb_ep0_out_len == 0) {
675                                 ao_usb_ep0_state = AO_USB_EP0_DATA_IN;
676                                 ao_usb_ep0_in_start(0);
677                         }
678                 }
679         }
680         if (receive & AO_USB_EP0_GOT_TX_ACK) {
681                 debug ("\tgot tx ack\n");
682
683 #if HAS_FLIGHT && AO_USB_FORCE_IDLE
684                 ao_flight_force_idle = 1;
685 #endif
686                 /* Wait until the IN packet is received from addr 0
687                  * before assigning our local address
688                  */
689                 if (ao_usb_address_pending)
690                         ao_usb_set_address(ao_usb_address);
691                 if (ao_usb_ep0_state == AO_USB_EP0_DATA_IN)
692                         ao_usb_ep0_flush();
693         }
694 }
695
696 void
697 stm_usb_isr(void)
698 {
699         uint32_t        istr = stm_usb.istr;
700
701         stm_usb.istr = ~istr;
702         if (istr & (1 << STM_USB_ISTR_CTR)) {
703                 uint8_t         ep = istr & STM_USB_ISTR_EP_ID_MASK;
704                 uint16_t        epr, epr_write;
705
706                 /* Preserve the SW write bits, don't mess with most HW writable bits,
707                  * clear the CTR_RX and CTR_TX bits
708                  */
709                 epr = stm_usb.epr[ep].r;
710                 epr_write = epr;
711                 epr_write &= STM_USB_EPR_PRESERVE_MASK;
712                 epr_write |= STM_USB_EPR_INVARIANT;
713                 epr_write &= ~(1 << STM_USB_EPR_CTR_RX);
714                 epr_write &= ~(1 << STM_USB_EPR_CTR_TX);
715                 stm_usb.epr[ep].r = epr_write;
716
717                 switch (ep) {
718                 case 0:
719                         ++control_count;
720                         if (ao_usb_epr_ctr_rx(epr)) {
721                                 if (ao_usb_epr_setup(epr))
722                                         ao_usb_ep0_receive |= AO_USB_EP0_GOT_SETUP;
723                                 else
724                                         ao_usb_ep0_receive |= AO_USB_EP0_GOT_RX_DATA;
725                         }
726                         if (ao_usb_epr_ctr_tx(epr))
727                                 ao_usb_ep0_receive |= AO_USB_EP0_GOT_TX_ACK;
728                         ao_usb_ep0_handle(ao_usb_ep0_receive);
729                         break;
730                 case AO_USB_OUT_EPR:
731                         ++out_count;
732                         if (ao_usb_epr_ctr_rx(epr)) {
733                                 _rx_dbg1("RX ISR", epr);
734                                 ao_usb_out_avail = 1;
735                                 _rx_dbg0("out avail set");
736                                 ao_wakeup(AO_USB_OUT_SLEEP_ADDR);
737                                 _rx_dbg0("stdin awoken");
738                         }
739                         break;
740                 case AO_USB_IN_EPR:
741                         ++in_count;
742                         _tx_dbg1("TX ISR", epr);
743                         if (ao_usb_epr_ctr_tx(epr)) {
744                                 ao_usb_in_pending = 0;
745                                 ao_wakeup(&ao_usb_in_pending);
746                         }
747                         break;
748                 case AO_USB_INT_EPR:
749                         ++int_count;
750                         if (ao_usb_epr_ctr_tx(epr))
751                                 _ao_usb_set_stat_tx(AO_USB_INT_EPR, STM_USB_EPR_STAT_TX_NAK);
752                         break;
753                 }
754                 return;
755         }
756
757         if (istr & (1 << STM_USB_ISTR_RESET)) {
758                 ++reset_count;
759                 ao_usb_ep0_receive |= AO_USB_EP0_GOT_RESET;
760                 ao_usb_ep0_handle(ao_usb_ep0_receive);
761         }
762
763 }
764
765 /* Queue the current IN buffer for transmission */
766 static void
767 _ao_usb_in_send(void)
768 {
769         _tx_dbg0("in_send start");
770         debug ("send %d\n", ao_usb_tx_count);
771         while (ao_usb_in_pending)
772                 ao_sleep(&ao_usb_in_pending);
773         ao_usb_in_pending = 1;
774         if (ao_usb_tx_count != AO_USB_IN_SIZE)
775                 ao_usb_in_flushed = 1;
776         ao_usb_write(ao_usb_tx_buffer, ao_usb_in_tx_buffer, ao_usb_tx_count);
777         ao_usb_bdt[AO_USB_IN_EPR].single.count_tx = ao_usb_tx_count;
778         ao_usb_tx_count = 0;
779         _ao_usb_set_stat_tx(AO_USB_IN_EPR, STM_USB_EPR_STAT_TX_VALID);
780         _tx_dbg0("in_send end");
781 }
782
783 /* Wait for a free IN buffer. Interrupts are blocked */
784 static void
785 _ao_usb_in_wait(void)
786 {
787         for (;;) {
788                 /* Check if the current buffer is writable */
789                 if (ao_usb_tx_count < AO_USB_IN_SIZE)
790                         break;
791
792                 _tx_dbg0("in_wait top");
793                 /* Wait for an IN buffer to be ready */
794                 while (ao_usb_in_pending)
795                         ao_sleep(&ao_usb_in_pending);
796                 _tx_dbg0("in_wait bottom");
797         }
798 }
799
800 void
801 ao_usb_flush(void)
802 {
803         if (!ao_usb_running)
804                 return;
805
806         /* Anytime we've sent a character since
807          * the last time we flushed, we'll need
808          * to send a packet -- the only other time
809          * we would send a packet is when that
810          * packet was full, in which case we now
811          * want to send an empty packet
812          */
813         ao_arch_block_interrupts();
814         while (!ao_usb_in_flushed) {
815                 _tx_dbg0("flush top");
816                 _ao_usb_in_send();
817                 _tx_dbg0("flush end");
818         }
819         ao_arch_release_interrupts();
820 }
821
822 void
823 ao_usb_putchar(char c)
824 {
825         if (!ao_usb_running)
826                 return;
827
828         ao_arch_block_interrupts();
829         _ao_usb_in_wait();
830
831         ao_usb_in_flushed = 0;
832         ao_usb_tx_buffer[ao_usb_tx_count++] = (uint8_t) c;
833
834         /* Send the packet when full */
835         if (ao_usb_tx_count == AO_USB_IN_SIZE) {
836                 _tx_dbg0("putchar full");
837                 _ao_usb_in_send();
838                 _tx_dbg0("putchar flushed");
839         }
840         ao_arch_release_interrupts();
841 }
842
843 static void
844 _ao_usb_out_recv(void)
845 {
846         _rx_dbg0("out_recv top");
847         ao_usb_out_avail = 0;
848
849         ao_usb_rx_count = ao_usb_bdt[AO_USB_OUT_EPR].single.count_rx & STM_USB_BDT_COUNT_RX_COUNT_RX_MASK;
850
851         _rx_dbg1("out_recv count", ao_usb_rx_count);
852         debug ("recv %d\n", ao_usb_rx_count);
853         debug_data("Fill OUT len %d:", ao_usb_rx_count);
854         ao_usb_read(ao_usb_rx_buffer, ao_usb_out_rx_buffer, ao_usb_rx_count);
855         debug_data("\n");
856         ao_usb_rx_pos = 0;
857
858         /* ACK the packet */
859         _ao_usb_set_stat_rx(AO_USB_OUT_EPR, STM_USB_EPR_STAT_RX_VALID);
860 }
861
862 int
863 _ao_usb_pollchar(void)
864 {
865         uint8_t c;
866
867         if (!ao_usb_running)
868                 return AO_READ_AGAIN;
869
870         for (;;) {
871                 if (ao_usb_rx_pos != ao_usb_rx_count)
872                         break;
873
874                 _rx_dbg0("poll check");
875                 /* Check to see if a packet has arrived */
876                 if (!ao_usb_out_avail) {
877                         _rx_dbg0("poll none");
878                         return AO_READ_AGAIN;
879                 }
880                 _ao_usb_out_recv();
881         }
882
883         /* Pull a character out of the fifo */
884         c = ao_usb_rx_buffer[ao_usb_rx_pos++];
885         return c;
886 }
887
888 char
889 ao_usb_getchar(void)
890 {
891         int     c;
892
893         ao_arch_block_interrupts();
894         while ((c = _ao_usb_pollchar()) == AO_READ_AGAIN)
895                 ao_sleep(AO_USB_OUT_SLEEP_ADDR);
896         ao_arch_release_interrupts();
897         return c;
898 }
899
900 void
901 ao_usb_disable(void)
902 {
903         ao_arch_block_interrupts();
904         stm_usb.cntr = (1 << STM_USB_CNTR_FRES);
905         stm_usb.istr = 0;
906
907         /* Disable USB pull-up */
908         stm_usb.bcdr &= ~(1 << STM_USB_BCDR_DPPU);
909
910         /* Switch off the device */
911         stm_usb.cntr = (1 << STM_USB_CNTR_PDWN) | (1 << STM_USB_CNTR_FRES);
912
913         /* Disable the interface */
914         stm_rcc.apb1enr &= ~(1 << STM_RCC_APB1ENR_USBEN);
915         ao_arch_release_interrupts();
916 }
917
918 void
919 ao_usb_enable(void)
920 {
921         int     t;
922
923         /* Select HSI48 as USB clock source */
924         stm_rcc.cfgr3 &= ~(1 << STM_RCC_CFGR3_USBSW);
925
926         /* Enable USB device */
927         stm_rcc.apb1enr |= (1 << STM_RCC_APB1ENR_USBEN);
928
929         /* Clear reset condition */
930         stm_rcc.apb1rstr &= ~(1 << STM_RCC_APB1RSTR_USBRST);
931
932         /* Disable USB pull-up */
933         stm_usb.bcdr &= ~(1 << STM_USB_BCDR_DPPU);
934
935         /* Do not touch the GPIOA configuration; USB takes priority
936          * over GPIO on pins A11 and A12, but if you select alternate
937          * input 10 (the documented correct selection), then USB is
938          * pulled low and doesn't work at all
939          */
940
941         ao_arch_block_interrupts();
942
943         /* Route interrupts */
944         stm_nvic_set_enable(STM_ISR_USB_POS);
945         stm_nvic_set_priority(STM_ISR_USB_POS, 3);
946
947         ao_usb_configuration = 0;
948
949         /* Set up buffer descriptors */
950         ao_usb_init_btable();
951
952         /* Reset the USB controller */
953         stm_usb.cntr = (1 << STM_USB_CNTR_FRES);
954
955         /* Clear the reset bit */
956         stm_usb.cntr = 0;
957
958         /* Clear any spurious interrupts */
959         stm_usb.istr = 0;
960
961         ao_usb_set_ep0();
962
963         debug ("ao_usb_enable\n");
964
965         /* Enable interrupts */
966         stm_usb.cntr = ((1 << STM_USB_CNTR_CTRM) |
967                         (0 << STM_USB_CNTR_PMAOVRM) |
968                         (0 << STM_USB_CNTR_ERRM) |
969                         (0 << STM_USB_CNTR_WKUPM) |
970                         (0 << STM_USB_CNTR_SUSPM) |
971                         (1 << STM_USB_CNTR_RESETM) |
972                         (0 << STM_USB_CNTR_SOFM) |
973                         (0 << STM_USB_CNTR_ESOFM) |
974                         (0 << STM_USB_CNTR_RESUME) |
975                         (0 << STM_USB_CNTR_FSUSP) |
976                         (0 << STM_USB_CNTR_LP_MODE) |
977                         (0 << STM_USB_CNTR_PDWN) |
978                         (0 << STM_USB_CNTR_FRES));
979
980         ao_arch_release_interrupts();
981
982         for (t = 0; t < 1000; t++)
983                 ao_arch_nop();
984
985         /* Enable USB pull-up */
986         stm_usb.bcdr |= (1 << STM_USB_BCDR_DPPU);
987 }
988
989 #if USB_ECHO
990 struct ao_task ao_usb_echo_task;
991
992 static void
993 ao_usb_echo(void)
994 {
995         char    c;
996
997         for (;;) {
998                 c = ao_usb_getchar();
999                 ao_usb_putchar(c);
1000                 ao_usb_flush();
1001         }
1002 }
1003 #endif
1004
1005 #if USB_DEBUG
1006 static void
1007 ao_usb_irq(void)
1008 {
1009         printf ("control: %d out: %d in: %d int: %d reset: %d\n",
1010                 control_count, out_count, in_count, int_count, reset_count);
1011 }
1012
1013 __code struct ao_cmds ao_usb_cmds[] = {
1014         { ao_usb_irq, "I\0Show USB interrupt counts" },
1015         { 0, NULL }
1016 };
1017 #endif
1018
1019 void
1020 ao_usb_init(void)
1021 {
1022         ao_usb_enable();
1023
1024         debug ("ao_usb_init\n");
1025         ao_usb_ep0_state = AO_USB_EP0_IDLE;
1026 #if USB_ECHO
1027         ao_add_task(&ao_usb_echo_task, ao_usb_echo, "usb echo");
1028 #endif
1029 #if USB_DEBUG
1030         ao_cmd_register(&ao_usb_cmds[0]);
1031 #endif
1032 #if !USB_ECHO
1033 #if USE_USB_STDIO
1034         ao_add_stdio(_ao_usb_pollchar, ao_usb_putchar, ao_usb_flush);
1035 #endif
1036 #endif
1037 }
1038
1039 #if TX_DBG || RX_DBG
1040
1041 struct ao_usb_dbg {
1042         int             line;
1043         char            *msg;
1044         uint32_t        value;
1045         uint32_t        primask;
1046 #if TX_DBG
1047         uint16_t        in_count;
1048         uint32_t        in_epr;
1049         uint32_t        in_pending;
1050         uint32_t        tx_count;
1051         uint32_t        in_flushed;
1052 #endif
1053 #if RX_DBG
1054         uint8_t         rx_count;
1055         uint8_t         rx_pos;
1056         uint8_t         out_avail;
1057         uint32_t        out_epr;
1058 #endif
1059 };
1060
1061 #define NUM_USB_DBG     128
1062
1063 static struct ao_usb_dbg dbg[128];
1064 static int dbg_i;
1065
1066 static void _dbg(int line, char *msg, uint32_t value)
1067 {
1068         uint32_t        primask;
1069         dbg[dbg_i].line = line;
1070         dbg[dbg_i].msg = msg;
1071         dbg[dbg_i].value = value;
1072         asm("mrs %0,primask" : "=&r" (primask));
1073         dbg[dbg_i].primask = primask;
1074 #if TX_DBG
1075         dbg[dbg_i].in_count = in_count;
1076         dbg[dbg_i].in_epr = stm_usb.epr[AO_USB_IN_EPR];
1077         dbg[dbg_i].in_pending = ao_usb_in_pending;
1078         dbg[dbg_i].tx_count = ao_usb_tx_count;
1079         dbg[dbg_i].in_flushed = ao_usb_in_flushed;
1080 #endif
1081 #if RX_DBG
1082         dbg[dbg_i].rx_count = ao_usb_rx_count;
1083         dbg[dbg_i].rx_pos = ao_usb_rx_pos;
1084         dbg[dbg_i].out_avail = ao_usb_out_avail;
1085         dbg[dbg_i].out_epr = stm_usb.epr[AO_USB_OUT_EPR];
1086 #endif
1087         if (++dbg_i == NUM_USB_DBG)
1088                 dbg_i = 0;
1089 }
1090 #endif