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