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