altos/stmf0: use double buffering for USB rx data
[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; either version 2 of the License, or
7  * (at your option) any later version.
8  *
9  * This program is distributed in the hope that it will be useful, but
10  * WITHOUT ANY WARRANTY; without even the implied warranty of
11  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
12  * General Public License for more details.
13  *
14  * You should have received a copy of the GNU General Public License along
15  * with this program; if not, write to the Free Software Foundation, Inc.,
16  * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA.
17  */
18
19 #include "ao.h"
20 #include "ao_usb.h"
21 #include "ao_product.h"
22 #include "ao_power.h"
23
24 #define USB_DEBUG       0
25 #define USB_STATUS      0
26 #define USB_DEBUG_DATA  0
27 #define USB_ECHO        0
28
29 #ifndef AO_PA11_PA12_RMP
30 #error "must define AO_PA11_PA12_RMP"
31 #endif
32
33 #ifndef AO_POWER_MANAGEMENT
34 #define AO_POWER_MANAGEMENT     0
35 #endif
36
37 #ifndef USE_USB_STDIO
38 #define USE_USB_STDIO   1
39 #endif
40
41 #if USE_USB_STDIO
42 #define AO_USB_OUT_SLEEP_ADDR   (&ao_stdin_ready)
43 #else
44 #define AO_USB_OUT_SLEEP_ADDR   (&ao_usb_out_avail)
45 #endif
46
47 #if USB_DEBUG
48 #define debug(format, args...)  printf(format, ## args);
49 #else
50 #define debug(format, args...)
51 #endif
52
53 #if USB_DEBUG_DATA
54 #define debug_data(format, args...)     printf(format, ## args);
55 #else
56 #define debug_data(format, args...)
57 #endif
58
59 struct ao_usb_setup {
60         uint8_t         dir_type_recip;
61         uint8_t         request;
62         uint16_t        value;
63         uint16_t        index;
64         uint16_t        length;
65 } ao_usb_setup;
66
67 static uint8_t  ao_usb_ep0_state;
68
69 /* Pending EP0 IN data */
70 static const uint8_t    *ao_usb_ep0_in_data;    /* Remaining data */
71 static uint8_t          ao_usb_ep0_in_len;      /* Remaining amount */
72
73 /* Temp buffer for smaller EP0 in data */
74 static uint8_t  ao_usb_ep0_in_buf[2];
75
76 /* Pending EP0 OUT data */
77 static uint8_t *ao_usb_ep0_out_data;
78 static uint8_t  ao_usb_ep0_out_len;
79
80 /*
81  * Objects allocated in special USB memory
82  */
83
84 /* Buffer description tables */
85 static union stm_usb_bdt        *ao_usb_bdt;
86 /* USB address of end of allocated storage */
87 #if AO_USB_DIRECTIO
88 static uint16_t ao_usb_sram_addr;
89 #endif
90
91 /* Pointer to ep0 tx/rx buffers in USB memory */
92 static uint16_t *ao_usb_ep0_tx_buffer;
93 static uint16_t *ao_usb_ep0_rx_buffer;
94
95 #if AO_USB_HAS_INT
96 /* Pointer to interrupt buffer in USB memory */
97 static uint16_t ao_usb_int_tx_offset;
98 #endif
99
100 /* Pointer to bulk data tx/rx buffers in USB memory */
101 #if AO_USB_HAS_IN
102 static uint16_t ao_usb_in_tx_offset[2];
103 static uint16_t *ao_usb_in_tx_buffer[2];
104 static uint8_t  ao_usb_in_tx_which;
105 static uint8_t  ao_usb_tx_count;
106
107 #endif
108 #if AO_USB_HAS_OUT
109 static uint16_t ao_usb_out_rx_offset[2];
110 static uint16_t *ao_usb_out_rx_buffer[2];
111 static uint8_t  ao_usb_out_rx_which;
112 static uint8_t  ao_usb_rx_count, ao_usb_rx_pos;
113
114 #endif
115 #if AO_USB_HAS_IN2
116 static uint16_t ao_usb_in2_tx_offset[2];
117 static uint16_t *ao_usb_in2_tx_buffer[2];
118 static uint8_t  ao_usb_in_tx2_which;
119 static uint8_t  ao_usb_tx2_count;
120 #endif
121
122 /*
123  * End point register indices
124  */
125
126 #define AO_USB_CONTROL_EPR      0
127 #define AO_USB_INT_EPR          1
128 #define AO_USB_OUT_EPR          2
129 #define AO_USB_IN_EPR           3
130 #define AO_USB_IN2_EPR          4
131
132 /* Marks when we don't need to send an IN packet.
133  * This happens only when the last IN packet is not full,
134  * otherwise the host will expect to keep seeing packets.
135  * Send a zero-length packet as required
136  */
137 static uint8_t  ao_usb_in_flushed;
138
139 /* Marks when we have delivered an IN packet to the hardware
140  * and it has not been received yet. ao_sleep on this address
141  * to wait for it to be delivered.
142  */
143 static uint8_t  ao_usb_in_pending;
144
145 #if AO_USB_HAS_IN2
146 /* Marks when we have delivered an IN packet to the hardware
147  * and it has not been received yet. ao_sleep on this address
148  * to wait for it to be delivered.
149  */
150 static uint8_t  ao_usb_in2_pending;
151 static uint16_t in2_count;
152 static uint8_t  ao_usb_in2_flushed;
153 #endif
154
155 /* Marks when an OUT packet has been received by the hardware
156  * but not pulled to the shadow buffer.
157  */
158 static uint8_t  ao_usb_out_avail;
159 uint8_t         ao_usb_running;
160 static uint8_t  ao_usb_configuration;
161
162 #define AO_USB_EP0_GOT_SETUP    1
163 #define AO_USB_EP0_GOT_RX_DATA  2
164 #define AO_USB_EP0_GOT_TX_ACK   4
165
166 static uint8_t  ao_usb_ep0_receive;
167 static uint8_t  ao_usb_address;
168 static uint8_t  ao_usb_address_pending;
169
170 static inline uint32_t set_toggle(uint32_t      current_value,
171                                    uint32_t     mask,
172                                    uint32_t     desired_value)
173 {
174         return (current_value ^ desired_value) & mask;
175 }
176
177 static inline uint16_t *ao_usb_packet_buffer_addr(uint16_t sram_addr)
178 {
179         return (uint16_t *) (void *) (stm_usb_sram + sram_addr);
180 }
181
182 static inline uint16_t ao_usb_packet_buffer_offset(uint16_t *addr)
183 {
184         return (uint16_t) ((uint8_t *) addr - stm_usb_sram);
185 }
186
187 static inline uint32_t ao_usb_epr_stat_rx(uint32_t epr) {
188         return (epr >> STM_USB_EPR_STAT_RX) & STM_USB_EPR_STAT_RX_MASK;
189 }
190
191 static inline uint32_t ao_usb_epr_stat_tx(uint32_t epr) {
192         return (epr >> STM_USB_EPR_STAT_TX) & STM_USB_EPR_STAT_TX_MASK;
193 }
194
195 static inline uint32_t ao_usb_epr_ctr_rx(uint32_t epr) {
196         return (epr >> STM_USB_EPR_CTR_RX) & 1;
197 }
198
199 static inline uint32_t ao_usb_epr_ctr_tx(uint32_t epr) {
200         return (epr >> STM_USB_EPR_CTR_TX) & 1;
201 }
202
203 static inline uint32_t ao_usb_epr_setup(uint32_t epr) {
204         return (epr >> STM_USB_EPR_SETUP) & 1;
205 }
206
207 static inline uint32_t ao_usb_epr_dtog_rx(uint32_t epr) {
208         return (epr >> STM_USB_EPR_DTOG_RX) & 1;
209 }
210
211 static inline uint32_t ao_usb_epr_sw_buf_tx(uint32_t epr) {
212         return (epr >> STM_USB_EPR_SW_BUF_TX) & 1;
213 }
214
215 static inline uint32_t ao_usb_epr_dtog_tx(uint32_t epr) {
216         return (epr >> STM_USB_EPR_DTOG_TX) & 1;
217 }
218
219 static inline uint32_t ao_usb_epr_sw_buf_rx(uint32_t epr) {
220         return (epr >> STM_USB_EPR_SW_BUF_RX) & 1;
221 }
222
223 /*
224  * Set current device address and mark the
225  * interface as active
226  */
227 void
228 ao_usb_set_address(uint8_t address)
229 {
230         debug("ao_usb_set_address %02x\n", address);
231         stm_usb.daddr = (1 << STM_USB_DADDR_EF) | address;
232         ao_usb_address_pending = 0;
233 }
234
235 /*
236  * Write these values to preserve register contents under HW changes
237  */
238
239 #define STM_USB_EPR_INVARIANT   ((1 << STM_USB_EPR_CTR_RX) |            \
240                                  (STM_USB_EPR_DTOG_RX_WRITE_INVARIANT << STM_USB_EPR_DTOG_RX) | \
241                                  (STM_USB_EPR_STAT_RX_WRITE_INVARIANT << STM_USB_EPR_STAT_RX) | \
242                                  (1 << STM_USB_EPR_CTR_TX) |            \
243                                  (STM_USB_EPR_DTOG_TX_WRITE_INVARIANT << STM_USB_EPR_DTOG_TX) | \
244                                  (STM_USB_EPR_STAT_TX_WRITE_INVARIANT << STM_USB_EPR_STAT_TX))
245
246 #define STM_USB_EPR_INVARIANT_MASK      ((1 << STM_USB_EPR_CTR_RX) |    \
247                                          (STM_USB_EPR_DTOG_RX_MASK << STM_USB_EPR_DTOG_RX) | \
248                                          (STM_USB_EPR_STAT_RX_MASK << STM_USB_EPR_STAT_RX) | \
249                                          (1 << STM_USB_EPR_CTR_TX) |    \
250                                          (STM_USB_EPR_DTOG_TX_MASK << STM_USB_EPR_DTOG_TX) | \
251                                          (STM_USB_EPR_STAT_TX_MASK << STM_USB_EPR_STAT_TX))
252
253 /*
254  * These bits are purely under sw control, so preserve them in the
255  * register by re-writing what was read
256  */
257 #define STM_USB_EPR_PRESERVE_MASK       ((STM_USB_EPR_EP_TYPE_MASK << STM_USB_EPR_EP_TYPE) | \
258                                          (1 << STM_USB_EPR_EP_KIND) |   \
259                                          (STM_USB_EPR_EA_MASK << STM_USB_EPR_EA))
260
261 #define TX_DBG 0
262 #define RX_DBG 0
263
264 #if TX_DBG
265 #define _tx_dbg0(msg) _dbg(__LINE__,msg,0)
266 #define _tx_dbg1(msg,value) _dbg(__LINE__,msg,value)
267 #else
268 #define _tx_dbg0(msg)
269 #define _tx_dbg1(msg,value)
270 #endif
271
272 #if RX_DBG
273 #define _rx_dbg0(msg) _dbg(__LINE__,msg,0)
274 #define _rx_dbg1(msg,value) _dbg(__LINE__,msg,value)
275 #else
276 #define _rx_dbg0(msg)
277 #define _rx_dbg1(msg,value)
278 #endif
279
280 #if TX_DBG || RX_DBG
281 static void _dbg(int line, char *msg, uint32_t value);
282 #endif
283
284 /*
285  * Set the state of the specified endpoint register to a new
286  * value. This is tricky because the bits toggle where the new
287  * value is one, and we need to write invariant values in other
288  * spots of the register. This hardware is strange...
289  */
290 static void
291 _ao_usb_set_stat_tx(int ep, uint32_t stat_tx)
292 {
293         uint16_t        epr_write, epr_old;
294
295         _tx_dbg1("set_stat_tx top", stat_tx);
296         epr_old = epr_write = stm_usb.epr[ep].r;
297         epr_write &= STM_USB_EPR_PRESERVE_MASK;
298         epr_write |= STM_USB_EPR_INVARIANT;
299         epr_write |= set_toggle(epr_old,
300                                 STM_USB_EPR_STAT_TX_MASK << STM_USB_EPR_STAT_TX,
301                                 stat_tx << STM_USB_EPR_STAT_TX);
302         stm_usb.epr[ep].r = epr_write;
303         _tx_dbg1("set_stat_tx bottom", epr_write);
304 }
305
306 static void
307 ao_usb_set_stat_tx(int ep, uint32_t stat_tx)
308 {
309         ao_arch_block_interrupts();
310         _ao_usb_set_stat_tx(ep, stat_tx);
311         ao_arch_release_interrupts();
312 }
313
314 static void
315 _ao_usb_toggle_dtog(int ep, uint32_t dtog_rx, uint32_t dtog_tx)
316 {
317         uint16_t        epr_write;
318
319         _tx_dbg1("toggle_dtog top", dtog_rx);
320         epr_write = stm_usb.epr[ep].r;
321         epr_write &= STM_USB_EPR_PRESERVE_MASK;
322         epr_write |= STM_USB_EPR_INVARIANT;
323         epr_write |= ((dtog_rx << STM_USB_EPR_DTOG_RX) |
324                       (dtog_tx << STM_USB_EPR_DTOG_TX));
325         stm_usb.epr[ep].r = epr_write;
326         _tx_dbg1("toggle_dtog bottom", epr_write);
327 }
328
329 static void
330 _ao_usb_set_stat_rx(int ep, uint32_t stat_rx) {
331         uint16_t        epr_write, epr_old;
332
333         epr_write = epr_old = stm_usb.epr[ep].r;
334         epr_write &= STM_USB_EPR_PRESERVE_MASK;
335         epr_write |= STM_USB_EPR_INVARIANT;
336         epr_write |= set_toggle(epr_old,
337                               STM_USB_EPR_STAT_RX_MASK << STM_USB_EPR_STAT_RX,
338                               stat_rx << STM_USB_EPR_STAT_RX);
339         stm_usb.epr[ep].r = epr_write;
340 }
341
342 static void
343 ao_usb_set_stat_rx(int ep, uint32_t stat_rx) {
344         ao_arch_block_interrupts();
345         _ao_usb_set_stat_rx(ep, stat_rx);
346         ao_arch_release_interrupts();
347 }
348
349 /*
350  * Initialize an entpoint
351  */
352
353 static void
354 ao_usb_init_ep(uint8_t ep, uint16_t addr, uint16_t type,
355                uint16_t stat_rx, uint16_t stat_tx,
356                uint16_t kind,
357                uint16_t dtog_rx, uint16_t dtog_tx)
358 {
359         uint16_t                epr;
360
361         ao_arch_block_interrupts();
362         epr = stm_usb.epr[ep].r;
363         epr = ((0 << STM_USB_EPR_CTR_RX) |
364                (type << STM_USB_EPR_EP_TYPE) |
365                (kind << STM_USB_EPR_EP_KIND) |
366                (0 << STM_USB_EPR_CTR_TX) |
367                (addr << STM_USB_EPR_EA) |
368                set_toggle(epr,
369
370                           (1 << STM_USB_EPR_DTOG_RX) |
371                           (STM_USB_EPR_STAT_RX_MASK << STM_USB_EPR_STAT_RX) |
372                           (1 << STM_USB_EPR_DTOG_TX) |
373                           (STM_USB_EPR_STAT_TX_MASK << STM_USB_EPR_STAT_TX),
374
375                           (dtog_rx << STM_USB_EPR_DTOG_RX) |
376                           (stat_rx << STM_USB_EPR_STAT_RX) |
377                           (dtog_tx << STM_USB_EPR_DTOG_TX) |
378                           (stat_tx << STM_USB_EPR_STAT_TX)));
379         stm_usb.epr[ep].r = epr;
380         ao_arch_release_interrupts();
381         debug ("writing epr[%d] 0x%04x wrote 0x%04x\n",
382                ep, epr, stm_usb.epr[ep].r);
383 }
384
385 static void
386 ao_usb_alloc_buffers(void)
387 {
388         uint16_t sram_addr = 0;
389
390         ao_usb_bdt = (void *) stm_usb_sram;
391         sram_addr += 8 * STM_USB_BDT_SIZE;
392
393         ao_usb_ep0_tx_buffer = ao_usb_packet_buffer_addr(sram_addr);
394         sram_addr += AO_USB_CONTROL_SIZE;
395
396         ao_usb_ep0_rx_buffer = ao_usb_packet_buffer_addr(sram_addr);
397         sram_addr += AO_USB_CONTROL_SIZE;
398
399
400 #if AO_USB_HAS_INT
401         sram_addr += (sram_addr & 1);
402         ao_usb_int_tx_offset = sram_addr;
403         sram_addr += AO_USB_INT_SIZE;
404 #endif
405
406 #if AO_USB_HAS_OUT
407         sram_addr += (sram_addr & 1);
408         ao_usb_out_rx_buffer[0] = ao_usb_packet_buffer_addr(sram_addr);
409         ao_usb_out_rx_offset[0] = sram_addr;
410         sram_addr += AO_USB_OUT_SIZE;
411         sram_addr += (sram_addr & 1);
412         ao_usb_out_rx_buffer[1] = ao_usb_packet_buffer_addr(sram_addr);
413         ao_usb_out_rx_offset[1] = sram_addr;
414         sram_addr += AO_USB_OUT_SIZE;
415         ao_usb_out_rx_which = 1;
416 #endif
417
418 #if AO_USB_HAS_IN
419         sram_addr += (sram_addr & 1);
420         ao_usb_in_tx_buffer[0] = ao_usb_packet_buffer_addr(sram_addr);
421         ao_usb_in_tx_offset[0] = sram_addr;
422         sram_addr += AO_USB_IN_SIZE;
423         ao_usb_in_tx_buffer[1] = ao_usb_packet_buffer_addr(sram_addr);
424         ao_usb_in_tx_offset[1] = sram_addr;
425         sram_addr += AO_USB_IN_SIZE;
426         ao_usb_in_tx_which = 0;
427 #endif
428
429 #if AO_USB_HAS_IN2
430         sram_addr += (sram_addr & 1);
431         ao_usb_in2_tx_buffer[0] = ao_usb_packet_buffer_addr(sram_addr);
432         ao_usb_in2_tx_offset[0] = sram_addr;
433         sram_addr += AO_USB_IN_SIZE;
434
435         sram_addr += (sram_addr & 1);
436         ao_usb_in2_tx_buffer[1] = ao_usb_packet_buffer_addr(sram_addr);
437         ao_usb_in2_tx_offset[1] = sram_addr;
438         sram_addr += AO_USB_IN_SIZE;
439         ao_usb_in2_tx_which = 0;
440 #endif
441
442 #if AO_USB_DIRECTIO
443         sram_addr += (sram_addr & 1);
444         ao_usb_sram_addr = sram_addr;
445 #endif
446 }
447
448 static void
449 ao_usb_init_btable(void)
450 {
451         /* Set up EP 0 - a Control end point with 32 bytes of in and out buffers */
452
453         ao_usb_bdt[0].single.addr_tx = ao_usb_packet_buffer_offset(ao_usb_ep0_tx_buffer);
454         ao_usb_bdt[0].single.count_tx = 0;
455
456         ao_usb_bdt[0].single.addr_rx = ao_usb_packet_buffer_offset(ao_usb_ep0_rx_buffer);
457         ao_usb_bdt[0].single.count_rx = ((1 << STM_USB_BDT_COUNT_RX_BL_SIZE) |
458                                   (((AO_USB_CONTROL_SIZE / 32) - 1) << STM_USB_BDT_COUNT_RX_NUM_BLOCK));
459 }
460
461 static void
462 ao_usb_set_ep0(void)
463 {
464         int                     e;
465
466         ao_usb_init_btable();
467
468         /* buffer table is at the start of USB memory */
469         stm_usb.btable = 0;
470
471         ao_usb_init_ep(AO_USB_CONTROL_EPR, AO_USB_CONTROL_EP,
472                        STM_USB_EPR_EP_TYPE_CONTROL,
473                        STM_USB_EPR_STAT_RX_VALID,
474                        STM_USB_EPR_STAT_TX_NAK,
475                        STM_USB_EPR_EP_KIND_NO_STATUS_OUT, 0, 0);
476
477         /* Clear all of the other endpoints */
478         for (e = 1; e < 8; e++) {
479                 ao_usb_init_ep(e, 0,
480                                STM_USB_EPR_EP_TYPE_CONTROL,
481                                STM_USB_EPR_STAT_RX_DISABLED,
482                                STM_USB_EPR_STAT_TX_DISABLED,
483                                STM_USB_EPR_EP_KIND_SNGL_BUF, 0, 0);
484         }
485
486         ao_usb_set_address(0);
487
488         ao_usb_running = 0;
489
490         /* Reset our internal state
491          */
492
493         ao_usb_ep0_state = AO_USB_EP0_IDLE;
494
495         ao_usb_ep0_in_data = NULL;
496         ao_usb_ep0_in_len = 0;
497
498         ao_usb_ep0_out_data = 0;
499         ao_usb_ep0_out_len = 0;
500 }
501
502 static void
503 ao_usb_set_configuration(void)
504 {
505         debug ("ao_usb_set_configuration\n");
506
507 #if AO_USB_HAS_INT
508         /* Set up the INT end point */
509         ao_usb_bdt[AO_USB_INT_EPR].single.addr_tx = ao_usb_int_tx_offset;
510         ao_usb_bdt[AO_USB_INT_EPR].single.count_tx = 0;
511
512         ao_usb_init_ep(AO_USB_INT_EPR,
513                        AO_USB_INT_EP,
514                        STM_USB_EPR_EP_TYPE_INTERRUPT,
515                        STM_USB_EPR_STAT_RX_DISABLED,
516                        STM_USB_EPR_STAT_TX_NAK,
517                        STM_USB_EPR_EP_KIND_SNGL_BUF, 0, 0);
518 #endif
519
520 #if AO_USB_HAS_OUT
521         /* Set up the OUT end point */
522         ao_usb_bdt[AO_USB_OUT_EPR].double_rx[0].addr = ao_usb_out_rx_offset[0];
523         ao_usb_bdt[AO_USB_OUT_EPR].double_rx[0].count = ((1 << STM_USB_BDT_COUNT_RX_BL_SIZE) |
524                                                          (((AO_USB_OUT_SIZE / 32) - 1) << STM_USB_BDT_COUNT_RX_NUM_BLOCK));
525
526         ao_usb_bdt[AO_USB_OUT_EPR].double_rx[1].addr = ao_usb_out_rx_offset[1];
527         ao_usb_bdt[AO_USB_OUT_EPR].double_rx[1].count = ((1 << STM_USB_BDT_COUNT_RX_BL_SIZE) |
528                                                          (((AO_USB_OUT_SIZE / 32) - 1) << STM_USB_BDT_COUNT_RX_NUM_BLOCK));
529
530         /* set 'our' buffer to one, and the device buffer to 0 */
531         ao_usb_init_ep(AO_USB_OUT_EPR,
532                        AO_USB_OUT_EP,
533                        STM_USB_EPR_EP_TYPE_BULK,
534                        STM_USB_EPR_STAT_RX_VALID,
535                        STM_USB_EPR_STAT_TX_DISABLED,
536                        STM_USB_EPR_EP_KIND_DBL_BUF, 0, 1);
537 #endif
538
539 #if AO_USB_HAS_IN
540         /* Set up the IN end point */
541         ao_usb_bdt[AO_USB_IN_EPR].double_tx[0].addr = ao_usb_in_tx_offset[0];
542         ao_usb_bdt[AO_USB_IN_EPR].double_tx[0].count = 0;
543         ao_usb_bdt[AO_USB_IN_EPR].double_tx[1].addr = ao_usb_in_tx_offset[1];
544         ao_usb_bdt[AO_USB_IN_EPR].double_tx[1].count = 0;
545
546         /* set 'our' buffer to 0, and the device buffer to 1 */
547         ao_usb_init_ep(AO_USB_IN_EPR,
548                        AO_USB_IN_EP,
549                        STM_USB_EPR_EP_TYPE_BULK,
550                        STM_USB_EPR_STAT_RX_DISABLED,
551                        STM_USB_EPR_STAT_TX_NAK,
552                        STM_USB_EPR_EP_KIND_DBL_BUF,
553                        0, 1);
554 #endif
555
556 #if AO_USB_HAS_IN2
557         /* Set up the IN2 end point */
558         ao_usb_bdt[AO_USB_IN2_EPR].single.addr_tx = 0;
559         ao_usb_bdt[AO_USB_IN2_EPR].single.count_tx = 0;
560
561         ao_usb_init_ep(AO_USB_IN2_EPR,
562                        AO_USB_IN2_EP,
563                        STM_USB_EPR_EP_TYPE_BULK,
564                        STM_USB_EPR_STAT_RX_DISABLED,
565                        STM_USB_EPR_STAT_TX_NAK,
566                        STM_USB_EPR_EP_KIND_DBL_BUF,
567                        0, 1);
568 #endif
569
570         ao_usb_in_flushed = 0;
571         ao_usb_in_pending = 0;
572         ao_wakeup(&ao_usb_in_pending);
573 #if AO_USB_HAS_IN2
574         ao_usb_in2_flushed = 0;
575         ao_usb_in2_pending = 0;
576         ao_wakeup(&ao_usb_in2_pending);
577 #endif
578
579         ao_usb_out_avail = 0;
580         ao_usb_configuration = 0;
581
582         ao_wakeup(AO_USB_OUT_SLEEP_ADDR);
583
584         ao_usb_running = 1;
585 #if AO_USB_DIRECTIO
586         ao_wakeup(&ao_usb_running);
587 #endif
588 }
589
590 #if USB_STATUS
591 static uint16_t control_count;
592 static uint16_t int_count;
593 static uint16_t in_count;
594 static uint16_t out_count;
595 static uint16_t reset_count;
596 #endif
597
598 /* The USB memory must be accessed in 16-bit units
599  */
600
601 static void
602 ao_usb_copy_tx(const uint8_t *src, uint16_t *base, uint16_t bytes)
603 {
604         while (bytes >= 2) {
605                 *base++ = src[0] | (src[1] << 8);
606                 src += 2;
607                 bytes -= 2;
608         }
609         if (bytes)
610                 *base = *src;
611 }
612
613 static void
614 ao_usb_copy_rx(uint8_t *dst, uint16_t *base, uint16_t bytes)
615 {
616         while (bytes >= 2) {
617                 uint16_t s = *base++;
618                 dst[0] = s;
619                 dst[1] = s >> 8;
620                 dst += 2;
621                 bytes -= 2;
622         }
623         if (bytes)
624                 *dst = *base;
625 }
626
627 static inline void
628 ao_usb_tx_byte(uint16_t *base, uint8_t tx_count, char byte)
629 {
630         if (tx_count & 1)
631                 base[tx_count >> 1] |= ((uint16_t) byte) << 8;
632         else
633                 base[tx_count >> 1] = (uint16_t) (uint8_t) byte;
634 }
635
636 static inline char
637 ao_usb_rx_byte(uint16_t *base, uint8_t rx_count)
638 {
639         if (rx_count & 1)
640                 return (char) (base[rx_count>>1] >> 8);
641         else
642                 return (char) base[rx_count>>1];
643 }
644
645 /* Send an IN data packet */
646 static void
647 ao_usb_ep0_flush(void)
648 {
649         uint8_t this_len;
650
651         /* Check to see if the endpoint is still busy */
652         if (ao_usb_epr_stat_tx(stm_usb.epr[0].r) == STM_USB_EPR_STAT_TX_VALID) {
653                 debug("EP0 not accepting IN data\n");
654                 return;
655         }
656
657         this_len = ao_usb_ep0_in_len;
658         if (this_len > AO_USB_CONTROL_SIZE)
659                 this_len = AO_USB_CONTROL_SIZE;
660
661         if (this_len < AO_USB_CONTROL_SIZE)
662                 ao_usb_ep0_state = AO_USB_EP0_IDLE;
663
664         ao_usb_ep0_in_len -= this_len;
665
666         debug_data ("Flush EP0 len %d:", this_len);
667         ao_usb_copy_tx(ao_usb_ep0_in_data, ao_usb_ep0_tx_buffer, this_len);
668         debug_data ("\n");
669         ao_usb_ep0_in_data += this_len;
670
671         /* Mark the endpoint as TX valid to send the packet */
672         ao_usb_bdt[AO_USB_CONTROL_EPR].single.count_tx = this_len;
673         ao_usb_set_stat_tx(AO_USB_CONTROL_EPR, STM_USB_EPR_STAT_TX_VALID);
674         debug ("queue tx. epr 0 now %08x\n", stm_usb.epr[AO_USB_CONTROL_EPR]);
675 }
676
677 /* Read data from the ep0 OUT fifo */
678 static void
679 ao_usb_ep0_fill(void)
680 {
681         uint16_t        len = ao_usb_bdt[0].single.count_rx & STM_USB_BDT_COUNT_RX_COUNT_RX_MASK;
682
683         if (len > ao_usb_ep0_out_len)
684                 len = ao_usb_ep0_out_len;
685         ao_usb_ep0_out_len -= len;
686
687         /* Pull all of the data out of the packet */
688         debug_data ("Fill EP0 len %d:", len);
689         ao_usb_copy_rx(ao_usb_ep0_out_data, ao_usb_ep0_rx_buffer, len);
690         debug_data ("\n");
691         ao_usb_ep0_out_data += len;
692
693         /* ACK the packet */
694         ao_usb_set_stat_rx(0, STM_USB_EPR_STAT_RX_VALID);
695 }
696
697 static void
698 ao_usb_ep0_in_reset(void)
699 {
700         ao_usb_ep0_in_data = ao_usb_ep0_in_buf;
701         ao_usb_ep0_in_len = 0;
702 }
703
704 static void
705 ao_usb_ep0_in_queue_byte(uint8_t a)
706 {
707         if (ao_usb_ep0_in_len < sizeof (ao_usb_ep0_in_buf))
708                 ao_usb_ep0_in_buf[ao_usb_ep0_in_len++] = a;
709 }
710
711 static void
712 ao_usb_ep0_in_set(const uint8_t *data, uint8_t len)
713 {
714         ao_usb_ep0_in_data = data;
715         ao_usb_ep0_in_len = len;
716 }
717
718 static void
719 ao_usb_ep0_out_set(uint8_t *data, uint8_t len)
720 {
721         ao_usb_ep0_out_data = data;
722         ao_usb_ep0_out_len = len;
723 }
724
725 static void
726 ao_usb_ep0_in_start(uint16_t max)
727 {
728         /* Don't send more than asked for */
729         if (ao_usb_ep0_in_len > max)
730                 ao_usb_ep0_in_len = max;
731         ao_usb_ep0_flush();
732 }
733
734 struct ao_usb_line_coding ao_usb_line_coding = {115200, 0, 0, 8};
735
736 #if AO_USB_DEVICE_ID_SERIAL
737 static uint8_t ao_usb_serial[2 + 48];
738
739 /* Convert a 32-bit value to 8 hexidecimal UCS2 characters */
740 static void
741 hex_to_ucs2(uint32_t in, uint8_t *out)
742 {
743         int     i;
744
745         for (i = 28; i >= 0; i -= 4) {
746                 uint8_t bits = (in >> i) & 0xf;
747                 *out++ = ((bits < 10) ? '0' : ('a' - 10)) + bits;
748                 *out++ = 0;
749         }
750 }
751
752 /* Encode the device ID (96 bits) in hexidecimal to use as a device
753  * serial number
754  */
755 static void
756 ao_usb_serial_init(void)
757 {
758         ao_usb_serial[0] = 50;  /* length */
759         ao_usb_serial[1] = AO_USB_DESC_STRING;
760         hex_to_ucs2(stm_device_id.u_id0, ao_usb_serial + 2 + 0);
761         hex_to_ucs2(stm_device_id.u_id1, ao_usb_serial + 2 + 16);
762         hex_to_ucs2(stm_device_id.u_id2, ao_usb_serial + 2 + 32);
763 }
764 #endif
765
766 /* Walk through the list of descriptors and find a match
767  */
768 static void
769 ao_usb_get_descriptor(uint16_t value, uint16_t length)
770 {
771         const uint8_t           *descriptor;
772         uint8_t         type = value >> 8;
773         uint8_t         index = value;
774
775         descriptor = ao_usb_descriptors;
776         while (descriptor[0] != 0) {
777                 if (descriptor[1] == type && index-- == 0) {
778                         uint8_t len;
779                         if (type == AO_USB_DESC_CONFIGURATION)
780                                 len = descriptor[2];
781                         else
782                                 len = descriptor[0];
783 #if AO_USB_DEVICE_ID_SERIAL
784                         /* Slightly hacky - the serial number is string 3 */
785                         if (type == AO_USB_DESC_STRING && (value & 0xff) == 3) {
786                                 descriptor = ao_usb_serial;
787                                 len = sizeof (ao_usb_serial);
788                         }
789 #endif
790                         if (len > length)
791                                 len = length;
792                         ao_usb_ep0_in_set(descriptor, len);
793                         break;
794                 }
795                 descriptor += descriptor[0];
796         }
797 }
798
799 static void
800 ao_usb_ep0_setup(void)
801 {
802         /* Pull the setup packet out of the fifo */
803         ao_usb_ep0_out_set((uint8_t *) &ao_usb_setup, 8);
804         ao_usb_ep0_fill();
805         if (ao_usb_ep0_out_len != 0) {
806                 debug ("invalid setup packet length\n");
807                 return;
808         }
809
810         if ((ao_usb_setup.dir_type_recip & AO_USB_DIR_IN) || ao_usb_setup.length == 0)
811                 ao_usb_ep0_state = AO_USB_EP0_DATA_IN;
812         else
813                 ao_usb_ep0_state = AO_USB_EP0_DATA_OUT;
814
815         ao_usb_ep0_in_reset();
816
817         switch(ao_usb_setup.dir_type_recip & AO_USB_SETUP_TYPE_MASK) {
818         case AO_USB_TYPE_STANDARD:
819                 debug ("Standard setup packet\n");
820                 switch(ao_usb_setup.dir_type_recip & AO_USB_SETUP_RECIP_MASK) {
821                 case AO_USB_RECIP_DEVICE:
822                         debug ("Device setup packet\n");
823                         switch(ao_usb_setup.request) {
824                         case AO_USB_REQ_GET_STATUS:
825                                 debug ("get status\n");
826                                 ao_usb_ep0_in_queue_byte(0);
827                                 ao_usb_ep0_in_queue_byte(0);
828                                 break;
829                         case AO_USB_REQ_SET_ADDRESS:
830                                 debug ("set address %d\n", ao_usb_setup.value);
831                                 ao_usb_address = ao_usb_setup.value;
832                                 ao_usb_address_pending = 1;
833                                 break;
834                         case AO_USB_REQ_GET_DESCRIPTOR:
835                                 debug ("get descriptor %d\n", ao_usb_setup.value);
836                                 ao_usb_get_descriptor(ao_usb_setup.value, ao_usb_setup.length);
837                                 break;
838                         case AO_USB_REQ_GET_CONFIGURATION:
839                                 debug ("get configuration %d\n", ao_usb_configuration);
840                                 ao_usb_ep0_in_queue_byte(ao_usb_configuration);
841                                 break;
842                         case AO_USB_REQ_SET_CONFIGURATION:
843                                 ao_usb_configuration = ao_usb_setup.value;
844                                 debug ("set configuration %d\n", ao_usb_configuration);
845                                 ao_usb_set_configuration();
846                                 break;
847                         }
848                         break;
849                 case AO_USB_RECIP_INTERFACE:
850                         debug ("Interface setup packet\n");
851                         switch(ao_usb_setup.request) {
852                         case AO_USB_REQ_GET_STATUS:
853                                 ao_usb_ep0_in_queue_byte(0);
854                                 ao_usb_ep0_in_queue_byte(0);
855                                 break;
856                         case AO_USB_REQ_GET_INTERFACE:
857                                 ao_usb_ep0_in_queue_byte(0);
858                                 break;
859                         case AO_USB_REQ_SET_INTERFACE:
860                                 break;
861                         }
862                         break;
863                 case AO_USB_RECIP_ENDPOINT:
864                         debug ("Endpoint setup packet\n");
865                         switch(ao_usb_setup.request) {
866                         case AO_USB_REQ_GET_STATUS:
867                                 ao_usb_ep0_in_queue_byte(0);
868                                 ao_usb_ep0_in_queue_byte(0);
869                                 break;
870                         }
871                         break;
872                 }
873                 break;
874         case AO_USB_TYPE_CLASS:
875                 debug ("Class setup packet\n");
876                 switch (ao_usb_setup.request) {
877                 case AO_USB_SET_LINE_CODING:
878                         debug ("set line coding\n");
879                         ao_usb_ep0_out_set((uint8_t *) &ao_usb_line_coding, 7);
880                         break;
881                 case AO_USB_GET_LINE_CODING:
882                         debug ("get line coding\n");
883                         ao_usb_ep0_in_set((const uint8_t *) &ao_usb_line_coding, 7);
884                         break;
885                 case AO_USB_SET_CONTROL_LINE_STATE:
886                         break;
887                 }
888                 break;
889         }
890
891         /* If we're not waiting to receive data from the host,
892          * queue an IN response
893          */
894         if (ao_usb_ep0_state == AO_USB_EP0_DATA_IN)
895                 ao_usb_ep0_in_start(ao_usb_setup.length);
896 }
897
898 static void
899 ao_usb_ep0_handle(uint8_t receive)
900 {
901         ao_usb_ep0_receive = 0;
902         if (receive & AO_USB_EP0_GOT_SETUP) {
903                 debug ("\tsetup\n");
904                 ao_usb_ep0_setup();
905         }
906         if (receive & AO_USB_EP0_GOT_RX_DATA) {
907                 debug ("\tgot rx data\n");
908                 if (ao_usb_ep0_state == AO_USB_EP0_DATA_OUT) {
909                         ao_usb_ep0_fill();
910                         if (ao_usb_ep0_out_len == 0) {
911                                 ao_usb_ep0_state = AO_USB_EP0_DATA_IN;
912                                 ao_usb_ep0_in_start(0);
913                         }
914                 }
915         }
916         if (receive & AO_USB_EP0_GOT_TX_ACK) {
917                 debug ("\tgot tx ack\n");
918
919 #if HAS_FLIGHT && AO_USB_FORCE_IDLE
920                 ao_flight_force_idle = 1;
921 #endif
922                 /* Wait until the IN packet is received from addr 0
923                  * before assigning our local address
924                  */
925                 if (ao_usb_address_pending)
926                         ao_usb_set_address(ao_usb_address);
927                 if (ao_usb_ep0_state == AO_USB_EP0_DATA_IN)
928                         ao_usb_ep0_flush();
929         }
930 }
931
932 #if AO_POWER_MANAGEMENT
933 void
934 ao_usb_suspend(void)
935 {
936         stm_usb.cntr |= (1 << STM_USB_CNTR_FSUSP);
937         ao_power_suspend();
938         stm_usb.cntr |= (1 << STM_USB_CNTR_LP_MODE);
939         ao_clock_suspend();
940 }
941
942 void
943 ao_usb_wakeup(void)
944 {
945         ao_clock_resume();
946         stm_usb.cntr &= ~(1 << STM_USB_CNTR_FSUSP);
947         ao_power_resume();
948 }
949 #endif
950
951 void
952 stm_usb_isr(void)
953 {
954         uint32_t        istr = stm_usb.istr;
955
956         stm_usb.istr = ~istr;
957         if (istr & (1 << STM_USB_ISTR_CTR)) {
958                 uint8_t         ep = istr & STM_USB_ISTR_EP_ID_MASK;
959                 uint16_t        epr, epr_write;
960
961                 /* Preserve the SW write bits, don't mess with most HW writable bits,
962                  * clear the CTR_RX and CTR_TX bits
963                  */
964                 epr = stm_usb.epr[ep].r;
965                 epr_write = epr;
966                 epr_write &= STM_USB_EPR_PRESERVE_MASK;
967                 epr_write |= STM_USB_EPR_INVARIANT;
968                 epr_write &= ~(1 << STM_USB_EPR_CTR_RX);
969                 epr_write &= ~(1 << STM_USB_EPR_CTR_TX);
970                 stm_usb.epr[ep].r = epr_write;
971
972                 switch (ep) {
973                 case 0:
974 #if USB_STATUS
975                         ++control_count;
976 #endif
977                         if (ao_usb_epr_ctr_rx(epr)) {
978                                 if (ao_usb_epr_setup(epr))
979                                         ao_usb_ep0_receive |= AO_USB_EP0_GOT_SETUP;
980                                 else
981                                         ao_usb_ep0_receive |= AO_USB_EP0_GOT_RX_DATA;
982                         }
983                         if (ao_usb_epr_ctr_tx(epr))
984                                 ao_usb_ep0_receive |= AO_USB_EP0_GOT_TX_ACK;
985                         ao_usb_ep0_handle(ao_usb_ep0_receive);
986                         break;
987                 case AO_USB_OUT_EPR:
988 #if USB_STATUS
989                         ++out_count;
990 #endif
991                         if (ao_usb_epr_ctr_rx(epr)) {
992                                 _rx_dbg1("RX ISR", epr);
993                                 ao_usb_out_avail = 1;
994                                 _rx_dbg0("out avail set");
995                                 ao_wakeup(AO_USB_OUT_SLEEP_ADDR);
996                                 _rx_dbg0("stdin awoken");
997                         }
998                         break;
999                 case AO_USB_IN_EPR:
1000 #if USB_STATUS
1001                         ++in_count;
1002 #endif
1003                         _tx_dbg1("TX ISR", epr);
1004                         if (ao_usb_epr_ctr_tx(epr)) {
1005                                 ao_usb_in_pending = 0;
1006                                 ao_wakeup(&ao_usb_in_pending);
1007                         }
1008                         break;
1009 #if AO_USB_HAS_IN2
1010                 case AO_USB_IN2_EPR:
1011                         ++in2_count;
1012                         _tx_dbg1("TX2 ISR", epr);
1013                         if (ao_usb_epr_ctr_tx(epr)) {
1014                                 ao_usb_in2_pending = 0;
1015                                 ao_wakeup(&ao_usb_in2_pending);
1016                         }
1017                         break;
1018 #endif
1019                 case AO_USB_INT_EPR:
1020 #if USB_STATUS
1021                         ++int_count;
1022 #endif
1023                         if (ao_usb_epr_ctr_tx(epr))
1024                                 _ao_usb_set_stat_tx(AO_USB_INT_EPR, STM_USB_EPR_STAT_TX_NAK);
1025                         break;
1026                 }
1027                 return;
1028         }
1029
1030         if (istr & (1 << STM_USB_ISTR_RESET)) {
1031 #if USB_STATUS
1032                 ++reset_count;
1033 #endif
1034                 debug ("\treset\n");
1035                 ao_usb_set_ep0();
1036         }
1037 #if AO_POWER_MANAGEMENT
1038         if (istr & (1 << STM_USB_ISTR_SUSP)) {
1039                 debug ("\tsuspend\n");
1040                 ao_usb_suspend();
1041         }
1042         if (istr & (1 << STM_USB_ISTR_WKUP)) {
1043                 debug ("\twakeup\n");
1044                 ao_usb_wakeup();
1045         }
1046 #endif
1047 }
1048
1049 #if AO_USB_HAS_IN
1050 /* Queue the current IN buffer for transmission */
1051 static void
1052 _ao_usb_in_send(void)
1053 {
1054         _tx_dbg0("in_send start");
1055         debug ("send %d\n", ao_usb_tx_count);
1056         while (ao_usb_in_pending)
1057                 ao_sleep(&ao_usb_in_pending);
1058         ao_usb_in_pending = 1;
1059         if (ao_usb_tx_count != AO_USB_IN_SIZE)
1060                 ao_usb_in_flushed = 1;
1061         ao_usb_bdt[AO_USB_IN_EPR].double_tx[ao_usb_in_tx_which].count = ao_usb_tx_count;
1062         ao_usb_tx_count = 0;
1063
1064         /* Toggle our usage */
1065         ao_usb_in_tx_which = 1 - ao_usb_in_tx_which;
1066
1067         /* Toggle the SW_BUF flag */
1068         _ao_usb_toggle_dtog(AO_USB_IN_EPR, 1, 0);
1069
1070         /* Mark the outgoing buffer as valid */
1071         _ao_usb_set_stat_tx(AO_USB_IN_EPR, STM_USB_EPR_STAT_TX_VALID);
1072
1073         _tx_dbg0("in_send end");
1074 }
1075
1076 /* Wait for a free IN buffer. Interrupts are blocked */
1077 static void
1078 _ao_usb_in_wait(void)
1079 {
1080         for (;;) {
1081                 /* Check if the current buffer is writable */
1082                 if (ao_usb_tx_count < AO_USB_IN_SIZE)
1083                         break;
1084
1085                 _tx_dbg0("in_wait top");
1086                 /* Wait for an IN buffer to be ready */
1087                 while (ao_usb_in_pending)
1088                         ao_sleep(&ao_usb_in_pending);
1089                 _tx_dbg0("in_wait bottom");
1090         }
1091 }
1092
1093 void
1094 ao_usb_flush(void)
1095 {
1096         if (!ao_usb_running)
1097                 return;
1098
1099         /* Anytime we've sent a character since
1100          * the last time we flushed, we'll need
1101          * to send a packet -- the only other time
1102          * we would send a packet is when that
1103          * packet was full, in which case we now
1104          * want to send an empty packet
1105          */
1106         ao_arch_block_interrupts();
1107         while (!ao_usb_in_flushed) {
1108                 _tx_dbg0("flush top");
1109                 _ao_usb_in_send();
1110                 _tx_dbg0("flush end");
1111         }
1112         ao_arch_release_interrupts();
1113 }
1114
1115 void
1116 ao_usb_putchar(char c)
1117 {
1118         if (!ao_usb_running)
1119                 return;
1120
1121         ao_arch_block_interrupts();
1122         _ao_usb_in_wait();
1123
1124         ao_usb_in_flushed = 0;
1125         ao_usb_tx_byte(ao_usb_in_tx_buffer[ao_usb_in_tx_which], ao_usb_tx_count++, c);
1126
1127         /* Send the packet when full */
1128         if (ao_usb_tx_count == AO_USB_IN_SIZE) {
1129                 _tx_dbg0("putchar full");
1130                 _ao_usb_in_send();
1131                 _tx_dbg0("putchar flushed");
1132         }
1133         ao_arch_release_interrupts();
1134 }
1135 #endif
1136
1137 #if AO_USB_HAS_IN2
1138 /* Queue the current IN buffer for transmission */
1139 static void
1140 _ao_usb_in2_send(void)
1141 {
1142         _tx_dbg0("in2_send start");
1143         debug ("send2 %d\n", ao_usb_tx_count);
1144         while (ao_usb_in2_pending)
1145                 ao_sleep(&ao_usb_in2_pending);
1146         ao_usb_in2_pending = 1;
1147         if (ao_usb_tx2_count != AO_USB_IN_SIZE)
1148                 ao_usb_in2_flushed = 1;
1149         ao_usb_bdt[AO_USB_IN2_EPR].single.addr_tx = ao_usb_in2_tx_offset[ao_usb_in2_tx_which];
1150         ao_usb_bdt[AO_USB_IN2_EPR].single.count_tx = ao_usb_tx2_count;
1151         ao_usb_tx2_count = 0;
1152         ao_usb_in2_tx_which = 1 - ao_usb_in2_tx_which;
1153         _ao_usb_set_stat_tx(AO_USB_IN2_EPR, STM_USB_EPR_STAT_TX_VALID);
1154         _tx_dbg0("in2_send end");
1155 }
1156
1157 /* Wait for a free IN buffer. Interrupts are blocked */
1158 static void
1159 _ao_usb_in2_wait(void)
1160 {
1161         for (;;) {
1162                 /* Check if the current buffer is writable */
1163                 if (ao_usb_tx2_count < AO_USB_IN_SIZE)
1164                         break;
1165
1166                 _tx_dbg0("in2_wait top");
1167                 /* Wait for an IN buffer to be ready */
1168                 while (ao_usb_in2_pending)
1169                         ao_sleep(&ao_usb_in2_pending);
1170                 _tx_dbg0("in_wait bottom");
1171         }
1172 }
1173
1174 void
1175 ao_usb_flush2(void)
1176 {
1177         if (!ao_usb_running)
1178                 return;
1179
1180         /* Anytime we've sent a character since
1181          * the last time we flushed, we'll need
1182          * to send a packet -- the only other time
1183          * we would send a packet is when that
1184          * packet was full, in which case we now
1185          * want to send an empty packet
1186          */
1187         ao_arch_block_interrupts();
1188         while (!ao_usb_in2_flushed) {
1189                 _tx_dbg0("flush2 top");
1190                 _ao_usb_in2_send();
1191                 _tx_dbg0("flush2 end");
1192         }
1193         ao_arch_release_interrupts();
1194 }
1195
1196 void
1197 ao_usb_putchar2(char c)
1198 {
1199         if (!ao_usb_running)
1200                 return;
1201
1202         ao_arch_block_interrupts();
1203         _ao_usb_in2_wait();
1204
1205         ao_usb_in2_flushed = 0;
1206         ao_usb_tx_byte(ao_usb_in2_tx_buffer[ao_usb_in2_tx_which], ao_usb_tx2_count, c);
1207         ao_usb_tx2_count++;
1208
1209         /* Send the packet when full */
1210         if (ao_usb_tx2_count == AO_USB_IN_SIZE) {
1211                 _tx_dbg0("putchar2 full");
1212                 _ao_usb_in2_send();
1213                 _tx_dbg0("putchar2 flushed");
1214         }
1215         ao_arch_release_interrupts();
1216 }
1217 #endif
1218
1219 #if AO_USB_HAS_OUT
1220 static void
1221 _ao_usb_out_recv(void)
1222 {
1223         _rx_dbg1("out_recv top", stm_usb.epr[AO_USB_OUT_EPR].r);
1224
1225         /* Clear packet available field until we get another interrupt */
1226         ao_usb_out_avail = 0;
1227
1228         /* Switch to new buffer */
1229         ao_usb_out_rx_which = 1 - ao_usb_out_rx_which;
1230
1231         ao_usb_rx_count = ao_usb_bdt[AO_USB_OUT_EPR].double_rx[ao_usb_out_rx_which].count & STM_USB_BDT_COUNT_RX_COUNT_RX_MASK;
1232         ao_usb_rx_pos = 0;
1233
1234         /* Toggle the SW_BUF_RX bit */
1235         _ao_usb_toggle_dtog(AO_USB_OUT_EPR, 0, 1);
1236
1237 //      /* Ack the packet */
1238 //      _ao_usb_set_stat_rx(AO_USB_OUT_EPR, STM_USB_EPR_STAT_RX_VALID);
1239
1240         _rx_dbg1("out_recv count", ao_usb_rx_count);
1241 }
1242
1243 int
1244 _ao_usb_pollchar(void)
1245 {
1246         uint8_t c;
1247
1248         if (!ao_usb_running)
1249                 return AO_READ_AGAIN;
1250
1251         for (;;) {
1252                 if (ao_usb_rx_pos != ao_usb_rx_count)
1253                         break;
1254
1255 //              _rx_dbg0("poll check");
1256                 /* Check to see if a packet has arrived */
1257                 if (!ao_usb_out_avail) {
1258 //                      _rx_dbg0("poll none");
1259                         return AO_READ_AGAIN;
1260                 }
1261                 _ao_usb_out_recv();
1262         }
1263
1264         /* Pull a character out of the fifo */
1265         c = ao_usb_rx_byte(ao_usb_out_rx_buffer[ao_usb_out_rx_which], ao_usb_rx_pos++);
1266         _rx_dbg1("char", c);
1267         return c;
1268 }
1269
1270 char
1271 ao_usb_getchar(void)
1272 {
1273         int     c;
1274
1275         ao_arch_block_interrupts();
1276         while ((c = _ao_usb_pollchar()) == AO_READ_AGAIN)
1277                 ao_sleep(AO_USB_OUT_SLEEP_ADDR);
1278         ao_arch_release_interrupts();
1279         return c;
1280 }
1281 #endif
1282
1283 #if AO_USB_DIRECTIO
1284 uint16_t *
1285 ao_usb_alloc(void)
1286 {
1287         uint16_t        *buffer;
1288
1289         buffer = ao_usb_packet_buffer_addr(ao_usb_sram_addr);
1290         ao_usb_sram_addr += AO_USB_IN_SIZE;
1291         return buffer;
1292 }
1293
1294 void
1295 ao_usb_write(uint16_t *buffer, uint16_t len)
1296 {
1297         ao_arch_block_interrupts();
1298
1299         /* Wait for everything to be ready at the same time */
1300         for (;;) {
1301                 /* Make sure USB is connected */
1302                 if (!ao_usb_running) {
1303                         ao_sleep(&ao_usb_running);
1304                         continue;
1305                 }
1306
1307                 /* Flush any pending regular I/O */
1308                 if (ao_usb_tx_count) {
1309                         _ao_usb_in_send();
1310                         continue;
1311                 }
1312
1313                 /* Wait for an idle IN buffer */
1314                 if (ao_usb_in_pending) {
1315                         ao_sleep(&ao_usb_in_pending);
1316                         continue;
1317                 }
1318                 break;
1319         }
1320
1321         ao_usb_in_pending = 1;
1322         ao_usb_in_flushed = (len != AO_USB_IN_SIZE);
1323         ao_usb_bdt[AO_USB_IN_EPR].single.addr_tx = ao_usb_packet_buffer_offset(buffer);
1324         ao_usb_bdt[AO_USB_IN_EPR].single.count_tx = len;
1325         _ao_usb_set_stat_tx(AO_USB_IN_EPR, STM_USB_EPR_STAT_TX_VALID);
1326         ao_arch_release_interrupts();
1327 }
1328
1329 #if AO_USB_HAS_IN2
1330 void
1331 ao_usb_write2(uint16_t *buffer, uint16_t len)
1332 {
1333         ao_arch_block_interrupts();
1334
1335         /* Wait for everything to be ready at the same time */
1336         for (;;) {
1337                 /* Make sure USB is connected */
1338                 if (!ao_usb_running) {
1339                         ao_sleep(&ao_usb_running);
1340                         continue;
1341                 }
1342
1343                 /* Flush any pending regular I/O */
1344                 if (ao_usb_tx2_count) {
1345                         _ao_usb_in2_send();
1346                         continue;
1347                 }
1348
1349                 /* Wait for an idle IN buffer */
1350                 if (ao_usb_in2_pending) {
1351                         ao_sleep(&ao_usb_in2_pending);
1352                         continue;
1353                 }
1354                 break;
1355         }
1356
1357         ao_usb_in2_pending = 1;
1358         ao_usb_in2_flushed = (len != AO_USB_IN_SIZE);
1359         ao_usb_bdt[AO_USB_IN2_EPR].single.addr_tx = ao_usb_packet_buffer_offset(buffer);
1360         ao_usb_bdt[AO_USB_IN2_EPR].single.count_tx = len;
1361         _ao_usb_set_stat_tx(AO_USB_IN2_EPR, STM_USB_EPR_STAT_TX_VALID);
1362         ao_arch_release_interrupts();
1363 }
1364 #endif
1365 #endif
1366
1367 void
1368 ao_usb_disable(void)
1369 {
1370         ao_arch_block_interrupts();
1371         stm_usb.cntr = (1 << STM_USB_CNTR_FRES);
1372         stm_usb.istr = 0;
1373
1374         /* Disable USB pull-up */
1375         stm_usb.bcdr &= ~(1 << STM_USB_BCDR_DPPU);
1376
1377         /* Switch off the device */
1378         stm_usb.cntr = (1 << STM_USB_CNTR_PDWN) | (1 << STM_USB_CNTR_FRES);
1379
1380         /* Disable the interface */
1381         stm_rcc.apb1enr &= ~(1 << STM_RCC_APB1ENR_USBEN);
1382         ao_arch_release_interrupts();
1383 }
1384
1385 void
1386 ao_usb_enable(void)
1387 {
1388         int     t;
1389
1390         /* Select HSI48 as USB clock source */
1391         stm_rcc.cfgr3 &= ~(1 << STM_RCC_CFGR3_USBSW);
1392
1393         /* Enable USB device */
1394         stm_rcc.apb1enr |= (1 << STM_RCC_APB1ENR_USBEN);
1395
1396         /* Clear reset condition */
1397         stm_rcc.apb1rstr &= ~(1 << STM_RCC_APB1RSTR_USBRST);
1398
1399         /* Disable USB pull-up */
1400         stm_usb.bcdr &= ~(1 << STM_USB_BCDR_DPPU);
1401
1402         /* Do not touch the GPIOA configuration; USB takes priority
1403          * over GPIO on pins A11 and A12, but if you select alternate
1404          * input 10 (the documented correct selection), then USB is
1405          * pulled low and doesn't work at all
1406          */
1407
1408         ao_arch_block_interrupts();
1409
1410         /* Route interrupts */
1411         stm_nvic_set_enable(STM_ISR_USB_POS);
1412         stm_nvic_set_priority(STM_ISR_USB_POS, 3);
1413
1414         ao_usb_configuration = 0;
1415
1416         /* Set up buffer descriptors */
1417         ao_usb_init_btable();
1418
1419         /* Reset the USB controller */
1420         stm_usb.cntr = (1 << STM_USB_CNTR_FRES);
1421
1422         /* Clear the reset bit */
1423         stm_usb.cntr = 0;
1424
1425         /* Clear any spurious interrupts */
1426         stm_usb.istr = 0;
1427
1428         ao_usb_set_ep0();
1429
1430         debug ("ao_usb_enable\n");
1431
1432         /* Enable interrupts */
1433         stm_usb.cntr = ((1 << STM_USB_CNTR_CTRM) |
1434                         (0 << STM_USB_CNTR_PMAOVRM) |
1435                         (0 << STM_USB_CNTR_ERRM) |
1436                         (AO_POWER_MANAGEMENT << STM_USB_CNTR_WKUPM) |
1437                         (AO_POWER_MANAGEMENT << STM_USB_CNTR_SUSPM) |
1438                         (1 << STM_USB_CNTR_RESETM) |
1439                         (0 << STM_USB_CNTR_SOFM) |
1440                         (0 << STM_USB_CNTR_ESOFM) |
1441                         (0 << STM_USB_CNTR_RESUME) |
1442                         (0 << STM_USB_CNTR_FSUSP) |
1443                         (0 << STM_USB_CNTR_LP_MODE) |
1444                         (0 << STM_USB_CNTR_PDWN) |
1445                         (0 << STM_USB_CNTR_FRES));
1446
1447         ao_arch_release_interrupts();
1448
1449         for (t = 0; t < 1000; t++)
1450                 ao_arch_nop();
1451
1452         /* Enable USB pull-up */
1453         stm_usb.bcdr |= (1 << STM_USB_BCDR_DPPU);
1454 }
1455
1456 #if USB_ECHO
1457 struct ao_task ao_usb_echo_task;
1458
1459 static void
1460 ao_usb_echo(void)
1461 {
1462         char    c;
1463
1464         for (;;) {
1465                 c = ao_usb_getchar();
1466                 ao_usb_putchar(c);
1467                 ao_usb_flush();
1468         }
1469 }
1470 #endif
1471
1472 #if USB_STATUS
1473 static void
1474 ao_usb_irq(void)
1475 {
1476         printf ("control: %d out: %d in: %d int: %d reset: %d\n",
1477                 control_count, out_count, in_count, int_count, reset_count);
1478 }
1479
1480 __code struct ao_cmds ao_usb_cmds[] = {
1481         { ao_usb_irq, "I\0Show USB interrupt counts" },
1482         { 0, NULL }
1483 };
1484 #endif
1485
1486 void
1487 ao_usb_init(void)
1488 {
1489         /* Turn on syscfg */
1490         stm_rcc.apb2enr |= (1 << STM_RCC_APB2ENR_SYSCFGCOMPEN);
1491
1492         /* Set PA11/PA12 remapping bit */
1493         stm_syscfg.cfgr1 |= (AO_PA11_PA12_RMP << STM_SYSCFG_CFGR1_PA11_PA12_RMP);
1494
1495 #ifndef AO_USB_START_DISABLED
1496         ao_usb_enable();
1497 #endif
1498
1499 #if AO_USB_DEVICE_ID_SERIAL
1500         ao_usb_serial_init();
1501 #endif
1502
1503         debug ("ao_usb_init\n");
1504         ao_usb_ep0_state = AO_USB_EP0_IDLE;
1505
1506         ao_usb_alloc_buffers();
1507
1508 #if USB_ECHO
1509         ao_add_task(&ao_usb_echo_task, ao_usb_echo, "usb echo");
1510 #endif
1511 #if USB_STATUS
1512         ao_cmd_register(&ao_usb_cmds[0]);
1513 #endif
1514 #if !USB_ECHO
1515 #if USE_USB_STDIO
1516         ao_add_stdio(_ao_usb_pollchar, ao_usb_putchar, ao_usb_flush);
1517 #endif
1518 #endif
1519 }
1520
1521 #if TX_DBG || RX_DBG
1522
1523 struct ao_usb_dbg {
1524         int             line;
1525         char            *msg;
1526         uint32_t        value;
1527         uint32_t        primask;
1528 #if TX_DBG
1529         uint16_t        in_count;
1530         uint32_t        in_epr;
1531         uint32_t        in_pending;
1532         uint32_t        tx_count;
1533         uint32_t        in_flushed;
1534 #endif
1535 #if RX_DBG
1536         uint8_t         rx_count;
1537         uint8_t         rx_pos;
1538         uint8_t         out_avail;
1539         uint32_t        out_epr;
1540 #endif
1541 };
1542
1543 #define NUM_USB_DBG     128
1544
1545 struct ao_usb_dbg dbg[128];
1546 int dbg_i;
1547
1548 static void _dbg(int line, char *msg, uint32_t value)
1549 {
1550         uint32_t        primask;
1551         dbg[dbg_i].line = line;
1552         dbg[dbg_i].msg = msg;
1553         dbg[dbg_i].value = value;
1554         asm("mrs %0,primask" : "=&r" (primask));
1555         dbg[dbg_i].primask = primask;
1556 #if TX_DBG
1557         dbg[dbg_i].in_count = in_count;
1558         dbg[dbg_i].in_epr = stm_usb.epr[AO_USB_IN_EPR];
1559         dbg[dbg_i].in_pending = ao_usb_in_pending;
1560         dbg[dbg_i].tx_count = ao_usb_tx_count;
1561         dbg[dbg_i].in_flushed = ao_usb_in_flushed;
1562 #endif
1563 #if RX_DBG
1564         dbg[dbg_i].rx_count = ao_usb_rx_count;
1565         dbg[dbg_i].rx_pos = ao_usb_rx_pos;
1566         dbg[dbg_i].out_avail = ao_usb_out_avail;
1567         dbg[dbg_i].out_epr = stm_usb.epr[AO_USB_OUT_EPR].r;
1568 #endif
1569         if (++dbg_i == NUM_USB_DBG)
1570                 dbg_i = 0;
1571 }
1572 #endif