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