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