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