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