Set version to 1.5.9.1
[fw/altos] / src / lpc / ao_usb_lpc.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 #ifndef USE_USB_STDIO
23 #define USE_USB_STDIO   1
24 #endif
25
26 #if USE_USB_STDIO
27 #define AO_USB_OUT_SLEEP_ADDR   (&ao_stdin_ready)
28 #else
29 #define AO_USB_OUT_SLEEP_ADDR   (&ao_usb_out_avail)
30 #endif
31
32 #define USB_DEBUG       0
33 #define USB_DEBUG_DATA  0
34 #define USB_ECHO        0
35
36 #if USB_DEBUG
37 #define debug(format, args...)  printf(format, ## args);
38 #else
39 #define debug(format, args...)
40 #endif
41
42 #if USB_DEBUG_DATA
43 #define debug_data(format, args...)     printf(format, ## args);
44 #else
45 #define debug_data(format, args...)
46 #endif
47
48 struct ao_usb_setup {
49         uint8_t         dir_type_recip;
50         uint8_t         request;
51         uint16_t        value;
52         uint16_t        index;
53         uint16_t        length;
54 } ao_usb_setup;
55
56 static uint8_t  ao_usb_ep0_state;
57
58 /* Pending EP0 IN data */
59 static const uint8_t    *ao_usb_ep0_in_data;    /* Remaining data */
60 static uint8_t          ao_usb_ep0_in_len;      /* Remaining amount */
61 static uint16_t         ao_usb_ep0_in_max;      /* Requested amount from host */
62
63 /* Temp buffer for smaller EP0 in data */
64 static uint8_t  ao_usb_ep0_in_buf[2];
65
66 /* Pending EP0 OUT data */
67 static uint8_t *ao_usb_ep0_out_data;
68 static uint8_t  ao_usb_ep0_out_len;
69
70 /*
71  * Objects allocated in special USB memory
72  */
73
74 /* USB address of end of allocated storage */
75 static uint8_t  *ao_usb_sram;
76
77 /* Pointer to ep0 tx/rx buffers in USB memory */
78 static uint8_t  *ao_usb_ep0_tx_buffer;
79 static uint8_t  *ao_usb_ep0_setup_buffer;
80 static uint8_t  *ao_usb_ep0_rx_buffer;
81
82 /* Pointer to bulk data tx/rx buffers in USB memory */
83 static uint8_t  *ao_usb_in_tx_buffer[2];
84 static uint8_t  ao_usb_in_tx_cur;
85 static uint8_t  ao_usb_tx_count;
86
87 static uint8_t  *ao_usb_out_rx_buffer[2];
88 static uint8_t  ao_usb_out_rx_cur;
89 static uint8_t  ao_usb_rx_count, ao_usb_rx_pos;
90
91 extern struct lpc_usb_endpoint lpc_usb_endpoint;
92
93 /* Marks when we don't need to send an IN packet.
94  * This happens only when the last IN packet is not full,
95  * otherwise the host will expect to keep seeing packets.
96  * Send a zero-length packet as required
97  */
98 static uint8_t  ao_usb_in_flushed;
99
100 /* Marks when we have delivered an IN packet to the hardware
101  * and it has not been received yet. ao_sleep on this address
102  * to wait for it to be delivered.
103  */
104 static uint8_t  ao_usb_in_pending;
105
106 /* Marks when an OUT packet has been received by the hardware
107  * but not pulled to the shadow buffer.
108  */
109 uint8_t         ao_usb_out_avail;
110 uint8_t         ao_usb_running;
111 static uint8_t  ao_usb_configuration;
112
113 #define AO_USB_EP0_GOT_RESET    1
114 #define AO_USB_EP0_GOT_SETUP    2
115 #define AO_USB_EP0_GOT_RX_DATA  4
116 #define AO_USB_EP0_GOT_TX_ACK   8
117
118 static uint8_t  ao_usb_ep0_receive;
119 static uint8_t  ao_usb_address;
120 static uint8_t  ao_usb_address_pending;
121
122 static inline uint32_t set_toggle(uint32_t      current_value,
123                                    uint32_t     mask,
124                                    uint32_t     desired_value)
125 {
126         return (current_value ^ desired_value) & mask;
127 }
128
129 /*
130  * Set current device address and mark the
131  * interface as active
132  */
133 void
134 ao_usb_set_address(uint8_t address)
135 {
136         debug("ao_usb_set_address %02x\n", address);
137         lpc_usb.devcmdstat = ((address << LPC_USB_DEVCMDSTAT_DEV_ADDR) |
138                               (1 << LPC_USB_DEVCMDSTAT_DEV_EN) |
139                               (0 << LPC_USB_DEVCMDSTAT_SETUP) |
140                               (0 << LPC_USB_DEVCMDSTAT_PLL_ON) |
141                               (0 << LPC_USB_DEVCMDSTAT_LPM_SUP) |
142                               (0 << LPC_USB_DEVCMDSTAT_INTONNAK_AO) |
143                               (0 << LPC_USB_DEVCMDSTAT_INTONNAK_AI) |
144                               (0 << LPC_USB_DEVCMDSTAT_INTONNAK_CO) |
145                               (0 << LPC_USB_DEVCMDSTAT_INTONNAK_CI) |
146                               (1 << LPC_USB_DEVCMDSTAT_DCON) |
147                               (0 << LPC_USB_DEVCMDSTAT_DSUS) |
148                               (0 << LPC_USB_DEVCMDSTAT_DCON_C) |
149                               (0 << LPC_USB_DEVCMDSTAT_DSUS_C) |
150                               (0 << LPC_USB_DEVCMDSTAT_DRES_C) |
151                               (0 << LPC_USB_DEVCMDSTAT_VBUSDEBOUNCED));
152         ao_usb_address_pending = 0;
153 }
154
155 #define TX_DBG 0
156 #define RX_DBG 0
157
158 #if TX_DBG
159 #define _tx_dbg0(msg) _dbg(__LINE__,msg,0)
160 #define _tx_dbg1(msg,value) _dbg(__LINE__,msg,value)
161 #else
162 #define _tx_dbg0(msg)
163 #define _tx_dbg1(msg,value)
164 #endif
165
166 #if RX_DBG
167 #define _rx_dbg0(msg) _dbg(__LINE__,msg,0)
168 #define _rx_dbg1(msg,value) _dbg(__LINE__,msg,value)
169 #else
170 #define _rx_dbg0(msg)
171 #define _rx_dbg1(msg,value)
172 #endif
173
174 #if TX_DBG || RX_DBG
175 static void _dbg(int line, char *msg, uint32_t value);
176 #endif
177
178 /*
179  * Set just endpoint 0, for use during startup
180  */
181
182 static uint8_t *
183 ao_usb_alloc_sram(uint16_t size)
184 {
185         uint8_t *addr = ao_usb_sram;
186
187         ao_usb_sram += (size + 63) & ~63;
188         return addr;
189 }
190
191 static uint16_t
192 ao_usb_sram_offset(uint8_t *addr)
193 {
194         return (uint16_t) ((intptr_t) addr >> 6);
195 }
196
197 static void
198 ao_usb_set_ep(vuint32_t *ep, uint8_t *addr, uint16_t nbytes)
199 {
200         *ep = ((ao_usb_sram_offset(addr) << LPC_USB_EP_OFFSET) |
201                (nbytes << LPC_USB_EP_NBYTES) |
202                (0 << LPC_USB_EP_ENDPOINT_ISO) |
203                (0 << LPC_USB_EP_RATE_FEEDBACK) |
204                (0 << LPC_USB_EP_TOGGLE_RESET) |
205                (0 << LPC_USB_EP_STALL) |
206                (0 << LPC_USB_EP_DISABLED) |
207                (1 << LPC_USB_EP_ACTIVE));
208 }
209
210 static inline uint16_t
211 ao_usb_ep_count(vuint32_t *ep)
212 {
213         return (*ep >> LPC_USB_EP_NBYTES) & LPC_USB_EP_NBYTES_MASK;
214 }
215
216 static inline uint8_t
217 ao_usb_ep_stall(vuint32_t *ep)
218 {
219         return (*ep >> LPC_USB_EP_STALL) & 1;
220 }
221
222 static inline vuint32_t *
223 ao_usb_ep0_out(void)
224 {
225         return &lpc_usb_endpoint.ep0_out;
226 }
227
228 static inline vuint32_t *
229 ao_usb_ep0_in(void)
230 {
231         return &lpc_usb_endpoint.ep0_in;
232 }
233
234 static inline vuint32_t *
235 ao_usb_epn_out(uint8_t n)
236 {
237         return &lpc_usb_endpoint.epn[n-1].out[0];
238 }
239
240 static inline vuint32_t *
241 ao_usb_epn_in(uint8_t n)
242 {
243         return &lpc_usb_endpoint.epn[n-1].in[0];
244 }
245
246 #if UNUSED
247 static void
248 ao_usb_set_epn_in(uint8_t n, uint8_t *addr, uint16_t nbytes)
249 {
250         ao_usb_set_ep(ao_usb_epn_in(n), addr, nbytes);
251 }
252 #endif
253
254 static void
255 ao_usb_set_epn_out(uint8_t n, uint8_t *addr, uint16_t nbytes)
256 {
257         ao_usb_set_ep(ao_usb_epn_out(n), addr, nbytes);
258 }
259
260 static inline uint16_t
261 ao_usb_epn_out_count(uint8_t n)
262 {
263         return ao_usb_ep_count(ao_usb_epn_out(n));
264 }
265
266 static inline uint16_t
267 ao_usb_epn_in_count(uint8_t n)
268 {
269         return ao_usb_ep_count(ao_usb_epn_in(n));
270 }
271
272 static uint8_t *
273 ao_usb_enable_ep(vuint32_t *ep, uint16_t nbytes, uint16_t set_nbytes)
274 {
275         uint8_t *addr = ao_usb_alloc_sram(nbytes);
276         
277         ao_usb_set_ep(ep, addr, set_nbytes);
278         return addr;
279 }
280
281 static void
282 ao_usb_disable_ep(vuint32_t *ep)
283 {
284         *ep = ((0 << LPC_USB_EP_OFFSET) |
285                (0 << LPC_USB_EP_NBYTES) |
286                (0 << LPC_USB_EP_ENDPOINT_ISO) |
287                (0 << LPC_USB_EP_RATE_FEEDBACK) |
288                (0 << LPC_USB_EP_TOGGLE_RESET) |
289                (0 << LPC_USB_EP_STALL) |
290                (1 << LPC_USB_EP_DISABLED) |
291                (0 << LPC_USB_EP_ACTIVE));
292 }
293
294 static void
295 ao_usb_enable_epn(uint8_t n, uint16_t out_bytes, uint8_t **out_addr, uint16_t in_bytes, uint8_t **in_addr)
296 {
297         uint8_t *addr;
298
299         addr = ao_usb_enable_ep(ao_usb_epn_out(n), out_bytes, out_bytes);
300         if (out_addr)
301                 *out_addr = addr;
302         ao_usb_disable_ep(&lpc_usb_endpoint.epn[n-1].out[1]);
303
304         addr = ao_usb_enable_ep(ao_usb_epn_in(n), in_bytes, 0);
305         if (in_addr)
306                 *in_addr = addr;
307         ao_usb_disable_ep(&lpc_usb_endpoint.epn[n-1].in[1]);
308 }
309
310 static void
311 ao_usb_disable_epn(uint8_t n)
312 {
313         ao_usb_disable_ep(ao_usb_epn_out(n));
314         ao_usb_disable_ep(&lpc_usb_endpoint.epn[n-1].out[1]);
315         ao_usb_disable_ep(ao_usb_epn_in(n));
316         ao_usb_disable_ep(&lpc_usb_endpoint.epn[n-1].in[1]);
317 }
318
319 static void
320 ao_usb_reset(void)
321 {
322         ao_usb_set_address(0);
323         ao_usb_configuration = 0;
324 }
325
326 static void
327 ao_usb_set_ep0(void)
328 {
329         int                     e;
330
331         /* Everything is single buffered for now */
332         lpc_usb.epbufcfg = 0;
333         lpc_usb.epinuse = 0;
334         lpc_usb.epskip = 0xffffffff;
335
336         lpc_usb.intstat = 0xc00003ff;
337
338         ao_usb_sram = lpc_usb_sram;
339
340         lpc_usb.epliststart = (uint32_t) (intptr_t) &lpc_usb_endpoint;
341         lpc_usb.databufstart = ((uint32_t) (intptr_t) ao_usb_sram) & 0xffc00000;
342
343         /* Set up EP 0 - a Control end point with 32 bytes of in and out buffers */
344
345         ao_usb_ep0_rx_buffer = ao_usb_enable_ep(ao_usb_ep0_out(), AO_USB_CONTROL_SIZE, AO_USB_CONTROL_SIZE);
346         ao_usb_ep0_setup_buffer = ao_usb_alloc_sram(AO_USB_CONTROL_SIZE);
347         lpc_usb_endpoint.setup = ao_usb_sram_offset(ao_usb_ep0_setup_buffer);
348         ao_usb_ep0_tx_buffer = ao_usb_enable_ep(ao_usb_ep0_in(), AO_USB_CONTROL_SIZE, 0);
349
350         /* Clear all of the other endpoints */
351         for (e = 1; e <= 4; e++)
352                 ao_usb_disable_epn(e);
353         ao_usb_reset();
354 }
355
356 static void
357 ao_usb_set_configuration(void)
358 {
359         debug ("ao_usb_set_configuration\n");
360
361         /* Set up the INT end point */
362         ao_usb_enable_epn(AO_USB_INT_EP, 0, NULL, 0, NULL);
363
364         /* Set up the OUT end point */
365         ao_usb_enable_epn(AO_USB_OUT_EP, AO_USB_OUT_SIZE * 2, &ao_usb_out_rx_buffer[0], 0, NULL);
366         ao_usb_out_rx_buffer[1] = ao_usb_out_rx_buffer[0] + AO_USB_OUT_SIZE;
367         ao_usb_out_rx_cur = 0;
368
369         /* Set up the IN end point */
370         ao_usb_enable_epn(AO_USB_IN_EP, 0, NULL, AO_USB_IN_SIZE * 2, &ao_usb_in_tx_buffer[0]);
371         ao_usb_in_tx_buffer[1] = ao_usb_in_tx_buffer[0] + AO_USB_IN_SIZE;
372         ao_usb_in_tx_cur = 0;
373
374         ao_usb_running = 1;
375 }
376
377 /* Send an IN data packet */
378 static void
379 ao_usb_ep0_flush(void)
380 {
381         uint8_t this_len;
382
383         this_len = ao_usb_ep0_in_len;
384         if (this_len > AO_USB_CONTROL_SIZE)
385                 this_len = AO_USB_CONTROL_SIZE;
386
387         ao_usb_ep0_in_len -= this_len;
388         ao_usb_ep0_in_max -= this_len;
389
390         if (this_len < AO_USB_CONTROL_SIZE || ao_usb_ep0_in_max == 0)
391                 ao_usb_ep0_state = AO_USB_EP0_IDLE;
392
393         debug_data ("Flush EP0 len %d:", this_len);
394         memcpy(ao_usb_ep0_tx_buffer, ao_usb_ep0_in_data, this_len);
395         debug_data ("\n");
396         ao_usb_ep0_in_data += this_len;
397
398         /* Mark the endpoint as TX valid to send the packet */
399         ao_usb_set_ep(ao_usb_ep0_in(), ao_usb_ep0_tx_buffer, this_len);
400         debug ("queue tx.  0 now %08x\n", *ao_usb_ep0_in());
401 }
402
403 /* Read data from the ep0 OUT fifo */
404 static void
405 ao_usb_ep0_fill(void)
406 {
407         uint16_t        len;
408         uint8_t         *rx_buffer;
409
410         /* Pull all of the data out of the packet */
411         if (lpc_usb.devcmdstat & (1 << LPC_USB_DEVCMDSTAT_SETUP)) {
412                 rx_buffer = ao_usb_ep0_setup_buffer;
413                 len = 8;
414         } else {
415                 rx_buffer = ao_usb_ep0_rx_buffer;
416                 len = AO_USB_CONTROL_SIZE - ao_usb_ep_count(ao_usb_ep0_out());
417         }
418
419         if (len > ao_usb_ep0_out_len)
420                 len = ao_usb_ep0_out_len;
421         ao_usb_ep0_out_len -= len;
422
423         debug_data ("Fill EP0 len %d:", len);
424         memcpy(ao_usb_ep0_out_data, rx_buffer, len);
425         debug_data ("\n");
426         ao_usb_ep0_out_data += len;
427
428         /* ACK the packet */
429         ao_usb_set_ep(ao_usb_ep0_out(), ao_usb_ep0_rx_buffer, AO_USB_CONTROL_SIZE);
430         lpc_usb.devcmdstat |= (1 << LPC_USB_DEVCMDSTAT_SETUP);
431 }
432
433 static void
434 ao_usb_ep0_in_reset(void)
435 {
436         ao_usb_ep0_in_data = ao_usb_ep0_in_buf;
437         ao_usb_ep0_in_len = 0;
438 }
439
440 static void
441 ao_usb_ep0_in_queue_byte(uint8_t a)
442 {
443         if (ao_usb_ep0_in_len < sizeof (ao_usb_ep0_in_buf))
444                 ao_usb_ep0_in_buf[ao_usb_ep0_in_len++] = a;
445 }
446
447 static void
448 ao_usb_ep0_in_set(const uint8_t *data, uint8_t len)
449 {
450         ao_usb_ep0_in_data = data;
451         ao_usb_ep0_in_len = len;
452 }
453
454 static void
455 ao_usb_ep0_out_set(uint8_t *data, uint8_t len)
456 {
457         ao_usb_ep0_out_data = data;
458         ao_usb_ep0_out_len = len;
459 }
460
461 static void
462 ao_usb_ep0_in_start(uint16_t max)
463 {
464         ao_usb_ep0_in_max = max;
465         /* Don't send more than asked for */
466         if (ao_usb_ep0_in_len > max)
467                 ao_usb_ep0_in_len = max;
468         ao_usb_ep0_flush();
469 }
470
471 static struct ao_usb_line_coding ao_usb_line_coding = {115200, 0, 0, 8};
472
473 /* Walk through the list of descriptors and find a match
474  */
475 static void
476 ao_usb_get_descriptor(uint16_t value)
477 {
478         const uint8_t           *descriptor;
479         uint8_t         type = value >> 8;
480         uint8_t         index = value;
481
482         descriptor = ao_usb_descriptors;
483         while (descriptor[0] != 0) {
484                 if (descriptor[1] == type && index-- == 0) {
485                         uint8_t len;
486                         if (type == AO_USB_DESC_CONFIGURATION)
487                                 len = descriptor[2];
488                         else
489                                 len = descriptor[0];
490                         ao_usb_ep0_in_set(descriptor, len);
491                         break;
492                 }
493                 descriptor += descriptor[0];
494         }
495 }
496
497 static void
498 ao_usb_ep0_setup(void)
499 {
500         /* Pull the setup packet out of the fifo */
501         ao_usb_ep0_out_set((uint8_t *) &ao_usb_setup, 8);
502         ao_usb_ep0_fill();
503         if (ao_usb_ep0_out_len != 0) {
504                 debug ("invalid setup packet length\n");
505                 return;
506         }
507
508         if ((ao_usb_setup.dir_type_recip & AO_USB_DIR_IN) || ao_usb_setup.length == 0)
509                 ao_usb_ep0_state = AO_USB_EP0_DATA_IN;
510         else
511                 ao_usb_ep0_state = AO_USB_EP0_DATA_OUT;
512
513         ao_usb_ep0_in_reset();
514
515         switch(ao_usb_setup.dir_type_recip & AO_USB_SETUP_TYPE_MASK) {
516         case AO_USB_TYPE_STANDARD:
517                 debug ("Standard setup packet\n");
518                 switch(ao_usb_setup.dir_type_recip & AO_USB_SETUP_RECIP_MASK) {
519                 case AO_USB_RECIP_DEVICE:
520                         debug ("Device setup packet\n");
521                         switch(ao_usb_setup.request) {
522                         case AO_USB_REQ_GET_STATUS:
523                                 debug ("get status\n");
524                                 ao_usb_ep0_in_queue_byte(0);
525                                 ao_usb_ep0_in_queue_byte(0);
526                                 break;
527                         case AO_USB_REQ_SET_ADDRESS:
528                                 debug ("set address %d\n", ao_usb_setup.value);
529                                 ao_usb_address = ao_usb_setup.value;
530                                 ao_usb_address_pending = 1;
531                                 break;
532                         case AO_USB_REQ_GET_DESCRIPTOR:
533                                 debug ("get descriptor %d\n", ao_usb_setup.value);
534                                 ao_usb_get_descriptor(ao_usb_setup.value);
535                                 break;
536                         case AO_USB_REQ_GET_CONFIGURATION:
537                                 debug ("get configuration %d\n", ao_usb_configuration);
538                                 ao_usb_ep0_in_queue_byte(ao_usb_configuration);
539                                 break;
540                         case AO_USB_REQ_SET_CONFIGURATION:
541                                 ao_usb_configuration = ao_usb_setup.value;
542                                 debug ("set configuration %d\n", ao_usb_configuration);
543                                 ao_usb_set_configuration();
544                                 break;
545                         }
546                         break;
547                 case AO_USB_RECIP_INTERFACE:
548                         debug ("Interface setup packet\n");
549                         switch(ao_usb_setup.request) {
550                         case AO_USB_REQ_GET_STATUS:
551                                 ao_usb_ep0_in_queue_byte(0);
552                                 ao_usb_ep0_in_queue_byte(0);
553                                 break;
554                         case AO_USB_REQ_GET_INTERFACE:
555                                 ao_usb_ep0_in_queue_byte(0);
556                                 break;
557                         case AO_USB_REQ_SET_INTERFACE:
558                                 break;
559                         }
560                         break;
561                 case AO_USB_RECIP_ENDPOINT:
562                         debug ("Endpoint setup packet\n");
563                         switch(ao_usb_setup.request) {
564                         case AO_USB_REQ_GET_STATUS:
565                                 ao_usb_ep0_in_queue_byte(0);
566                                 ao_usb_ep0_in_queue_byte(0);
567                                 break;
568                         }
569                         break;
570                 }
571                 break;
572         case AO_USB_TYPE_CLASS:
573                 debug ("Class setup packet\n");
574                 switch (ao_usb_setup.request) {
575                 case AO_USB_SET_LINE_CODING:
576                         debug ("set line coding\n");
577                         ao_usb_ep0_out_set((uint8_t *) &ao_usb_line_coding, 7);
578                         break;
579                 case AO_USB_GET_LINE_CODING:
580                         debug ("get line coding\n");
581                         ao_usb_ep0_in_set((const uint8_t *) &ao_usb_line_coding, 7);
582                         break;
583                 case AO_USB_SET_CONTROL_LINE_STATE:
584                         break;
585                 }
586                 break;
587         }
588
589         /* If we're not waiting to receive data from the host,
590          * queue an IN response
591          */
592         if (ao_usb_ep0_state == AO_USB_EP0_DATA_IN)
593                 ao_usb_ep0_in_start(ao_usb_setup.length);
594 }
595
596 static void
597 ao_usb_ep0_handle(uint8_t receive)
598 {
599         ao_usb_ep0_receive = 0;
600
601         if (receive & AO_USB_EP0_GOT_RESET) {
602                 debug ("\treset\n");
603                 ao_usb_reset();
604                 return;
605         }
606         if (receive & AO_USB_EP0_GOT_SETUP) {
607                 debug ("\tsetup\n");
608                 ao_usb_ep0_setup();
609         }
610         if (receive & AO_USB_EP0_GOT_RX_DATA) {
611                 debug ("\tgot rx data\n");
612                 if (ao_usb_ep0_state == AO_USB_EP0_DATA_OUT) {
613                         ao_usb_ep0_fill();
614                         if (ao_usb_ep0_out_len == 0) {
615                                 ao_usb_ep0_state = AO_USB_EP0_DATA_IN;
616                                 ao_usb_ep0_in_start(0);
617                         }
618                 }
619         }
620         if (receive & AO_USB_EP0_GOT_TX_ACK) {
621                 debug ("\tgot tx ack\n");
622
623                 /* Wait until the IN packet is received from addr 0
624                  * before assigning our local address
625                  */
626                 if (ao_usb_address_pending) {
627 #if HAS_FLIGHT
628                         /* Go to idle mode if USB is connected
629                          */
630                         ao_flight_force_idle = 1;
631 #endif
632                         ao_usb_set_address(ao_usb_address);
633                 }
634                 if (ao_usb_ep0_state == AO_USB_EP0_DATA_IN)
635                         ao_usb_ep0_flush();
636         }
637 }
638
639 #if USB_DEBUG
640 static uint16_t int_count;
641 static uint16_t in_count;
642 static uint16_t out_count;
643 static uint16_t reset_count;
644 #endif
645
646 void
647 lpc_usb_irq_isr(void)
648 {
649         uint32_t        intstat = lpc_usb.intstat & lpc_usb.inten;
650
651         lpc_usb.intstat = intstat;
652         /* Handle EP0 OUT packets */
653         if (intstat & (1 << LPC_USB_INT_EPOUT(0))) {
654                 if (lpc_usb.devcmdstat & (1 << LPC_USB_DEVCMDSTAT_SETUP))
655                         ao_usb_ep0_receive |= AO_USB_EP0_GOT_SETUP;
656                 else
657                         ao_usb_ep0_receive |= AO_USB_EP0_GOT_RX_DATA;
658
659                 ao_usb_ep0_handle(ao_usb_ep0_receive);
660         }
661
662         /* Handle EP0 IN packets */
663         if (intstat & (1 << LPC_USB_INT_EPIN(0))) {
664                 ao_usb_ep0_receive |= AO_USB_EP0_GOT_TX_ACK;
665
666                 ao_usb_ep0_handle(ao_usb_ep0_receive);
667         }
668
669
670         /* Handle OUT packets */
671         if (intstat & (1 << LPC_USB_INT_EPOUT(AO_USB_OUT_EP))) {
672 #if USB_DEBUG
673                 ++out_count;
674 #endif
675                 _rx_dbg1("RX ISR", *ao_usb_epn_out(AO_USB_OUT_EP));
676                 ao_usb_out_avail = 1;
677                 _rx_dbg0("out avail set");
678                 ao_wakeup(AO_USB_OUT_SLEEP_ADDR)
679                 _rx_dbg0("stdin awoken");
680         }
681
682         /* Handle IN packets */
683         if (intstat & (1 << LPC_USB_INT_EPIN(AO_USB_IN_EP))) {
684 #if USB_DEBUG
685                 ++in_count;
686 #endif
687                 _tx_dbg1("TX ISR", *ao_usb_epn_in(AO_USB_IN_EP));
688                 ao_usb_in_pending = 0;
689                 ao_wakeup(&ao_usb_in_pending);
690         }
691
692         /* NAK all INT EP IN packets */
693         if (intstat & (1 << LPC_USB_INT_EPIN(AO_USB_INT_EP))) {
694                 ;
695         }
696
697         /* Check for reset */
698         if (intstat & (1 << LPC_USB_INT_DEV)) {
699                 if (lpc_usb.devcmdstat & (1 << LPC_USB_DEVCMDSTAT_DRES_C))
700                 {
701                         lpc_usb.devcmdstat |= (1 << LPC_USB_DEVCMDSTAT_DRES_C);
702                         ao_usb_ep0_receive |= AO_USB_EP0_GOT_RESET;
703                         ao_usb_ep0_handle(ao_usb_ep0_receive);
704                 }
705         }
706 }
707
708
709
710 /* Queue the current IN buffer for transmission */
711 static void
712 _ao_usb_in_send(void)
713 {
714         _tx_dbg0("in_send start");
715         debug ("send %d\n", ao_usb_tx_count);
716         while (ao_usb_in_pending)
717                 ao_sleep(&ao_usb_in_pending);
718         ao_usb_in_pending = 1;
719         if (ao_usb_tx_count != AO_USB_IN_SIZE)
720                 ao_usb_in_flushed = 1;
721         ao_usb_set_ep(ao_usb_epn_in(AO_USB_IN_EP), ao_usb_in_tx_buffer[ao_usb_in_tx_cur], ao_usb_tx_count);
722         ao_usb_in_tx_cur = 1 - ao_usb_in_tx_cur;
723         ao_usb_tx_count = 0;
724         _tx_dbg0("in_send end");
725 }
726
727 /* Wait for a free IN buffer. Interrupts are blocked */
728 static void
729 _ao_usb_in_wait(void)
730 {
731         for (;;) {
732                 /* Check if the current buffer is writable */
733                 if (ao_usb_tx_count < AO_USB_IN_SIZE)
734                         break;
735
736                 _tx_dbg0("in_wait top");
737                 /* Wait for an IN buffer to be ready */
738                 while (ao_usb_in_pending)
739                         ao_sleep(&ao_usb_in_pending);
740                 _tx_dbg0("in_wait bottom");
741         }
742 }
743
744 void
745 ao_usb_flush(void)
746 {
747         if (!ao_usb_running)
748                 return;
749
750         /* Anytime we've sent a character since
751          * the last time we flushed, we'll need
752          * to send a packet -- the only other time
753          * we would send a packet is when that
754          * packet was full, in which case we now
755          * want to send an empty packet
756          */
757         ao_arch_block_interrupts();
758         while (!ao_usb_in_flushed) {
759                 _tx_dbg0("flush top");
760                 _ao_usb_in_send();
761                 _tx_dbg0("flush end");
762         }
763         ao_arch_release_interrupts();
764 }
765
766 void
767 ao_usb_putchar(char c)
768 {
769         if (!ao_usb_running)
770                 return;
771
772         ao_arch_block_interrupts();
773         _ao_usb_in_wait();
774         ao_arch_release_interrupts();
775
776         ao_usb_in_flushed = 0;
777         ao_usb_in_tx_buffer[ao_usb_in_tx_cur][ao_usb_tx_count++] = (uint8_t) c;
778
779         ao_arch_block_interrupts();
780         /* Send the packet when full */
781         if (ao_usb_tx_count == AO_USB_IN_SIZE) {
782                 _tx_dbg0("putchar full");
783                 _ao_usb_in_send();
784                 _tx_dbg0("putchar flushed");
785         }
786         ao_arch_release_interrupts();
787 }
788
789 void *
790 ao_usb_alloc(uint16_t len)
791 {
792         return ao_usb_alloc_sram(len);
793 }
794
795 void
796 ao_usb_write(void *block, int len)
797 {
798         uint8_t *b = block;
799         int this_time;
800
801         if (!ao_usb_running)
802                 return;
803
804         if (!ao_usb_in_flushed)
805                 ao_usb_flush();
806
807         while (len) {
808                 ao_usb_in_flushed = 0;
809                 this_time = AO_USB_IN_SIZE;
810                 if (this_time > len)
811                         this_time = len;
812                 b += this_time;
813                 len -= this_time;
814
815                 ao_arch_block_interrupts();
816                 while (ao_usb_in_pending)
817                         ao_sleep(&ao_usb_in_pending);
818                 ao_usb_in_pending = 1;
819                 if (this_time != AO_USB_IN_SIZE)
820                         ao_usb_in_flushed = 1;
821                 ao_usb_set_ep(ao_usb_epn_in(AO_USB_IN_EP), b, this_time);
822                 ao_arch_release_interrupts();
823         }
824 }
825
826 static void
827 _ao_usb_out_recv(void)
828 {
829         _rx_dbg0("out_recv top");
830         ao_usb_out_avail = 0;
831
832         ao_usb_rx_count = AO_USB_OUT_SIZE - ao_usb_epn_out_count(AO_USB_OUT_EP);
833
834         _rx_dbg1("out_recv count", ao_usb_rx_count);
835         debug ("recv %d\n", ao_usb_rx_count);
836         debug_data("Fill OUT len %d\n", ao_usb_rx_count);
837         ao_usb_rx_pos = 0;
838         ao_usb_rx_out_cur = 1 - ao_usb_rx_out_cur;
839
840         /* ACK the packet */
841         ao_usb_set_epn_out(AO_USB_OUT_EP, ao_usb_out_rx_buffer[1-ao_usb_rx_out_cur], AO_USB_OUT_SIZE);
842 }
843
844 int
845 _ao_usb_pollchar(void)
846 {
847         uint8_t c;
848
849         if (!ao_usb_running)
850                 return AO_READ_AGAIN;
851
852         for (;;) {
853                 if (ao_usb_rx_pos != ao_usb_rx_count)
854                         break;
855
856                 _rx_dbg0("poll check");
857                 /* Check to see if a packet has arrived */
858                 if (!ao_usb_out_avail) {
859                         _rx_dbg0("poll none");
860                         return AO_READ_AGAIN;
861                 }
862                 _ao_usb_out_recv();
863         }
864
865         /* Pull a character out of the fifo */
866         c = ao_usb_rx_buffer[ao_usb_rx_out_cur][ao_usb_rx_pos++];
867         return c;
868 }
869
870 char
871 ao_usb_getchar(void)
872 {
873         int     c;
874
875         ao_arch_block_interrupts();
876         while ((c = _ao_usb_pollchar()) == AO_READ_AGAIN)
877                 ao_sleep(AO_USB_OUT_SLEEP_ADDR);
878         ao_arch_release_interrupts();
879         return c;
880 }
881
882 void
883 ao_usb_disable(void)
884 {
885         ao_arch_block_interrupts();
886
887 #if HAS_USB_PULLUP
888         ao_gpio_set(AO_USB_PULLUP_PORT, AO_USB_PULLUP_PIN, AO_USB_PULLUP, 0);
889 #endif
890         /* Disable interrupts */
891         lpc_usb.inten = 0;
892
893         lpc_nvic_clear_enable(LPC_ISR_USB_IRQ_POS);
894
895         /* Disable the device */
896         lpc_usb.devcmdstat = 0;
897
898         /* Turn off USB clock */
899         lpc_scb.usbclkdiv = 0;
900
901         /* Disable USB PHY and PLL */
902         lpc_scb.pdruncfg |= ((1 << LPC_SCB_PDRUNCFG_USBPAD_PD) |
903                              (1 << LPC_SCB_PDRUNCFG_USBPLL_PD));
904
905         /* Disable USB registers and RAM */
906         lpc_scb.sysahbclkctrl &= ~((1 << LPC_SCB_SYSAHBCLKCTRL_USB) |
907                                    (1 << LPC_SCB_SYSAHBCLKCTRL_USBRAM));
908
909         ao_arch_release_interrupts();
910 }
911
912 void
913 ao_usb_enable(void)
914 {
915         int     t;
916
917         /* Enable USB pins */
918 #if HAS_LPC_USB_CONNECT
919         lpc_ioconf.pio0_6 = ((LPC_IOCONF_FUNC_USB_CONNECT << LPC_IOCONF_FUNC) |
920                              (LPC_IOCONF_MODE_INACTIVE << LPC_IOCONF_MODE) |
921                              (0 << LPC_IOCONF_HYS) |
922                              (0 << LPC_IOCONF_INV) |
923                              (0 << LPC_IOCONF_OD) |
924                              0x80);
925 #endif
926 #if HAS_USB_VBUS
927         lpc_ioconf.pio0_3 = ((LPC_IOCONF_FUNC_USB_VBUS << LPC_IOCONF_FUNC) |
928                              (LPC_IOCONF_MODE_INACTIVE << LPC_IOCONF_MODE) |
929                              (0 << LPC_IOCONF_HYS) |
930                              (0 << LPC_IOCONF_INV) |
931                              (0 << LPC_IOCONF_OD) |
932                              0x80);
933 #endif
934         /* Enable USB registers and RAM */
935         lpc_scb.sysahbclkctrl |= ((1 << LPC_SCB_SYSAHBCLKCTRL_USB) |
936                                   (1 << LPC_SCB_SYSAHBCLKCTRL_USBRAM));
937
938         /* Enable USB PHY */
939         lpc_scb.pdruncfg &= ~(1 << LPC_SCB_PDRUNCFG_USBPAD_PD);
940         
941         /* Turn on USB PLL */
942         lpc_scb.pdruncfg &= ~(1 << LPC_SCB_PDRUNCFG_USBPLL_PD);
943
944         lpc_scb.usbpllclksel = (LPC_SCB_SYSPLLCLKSEL_SEL_SYSOSC << LPC_SCB_SYSPLLCLKSEL_SEL);
945         lpc_scb.usbpllclkuen = (0 << LPC_SCB_USBPLLCLKUEN_ENA);
946         lpc_scb.usbpllclkuen = (1 << LPC_SCB_USBPLLCLKUEN_ENA);
947         while (!(lpc_scb.usbpllclkuen & (1 << LPC_SCB_USBPLLCLKUEN_ENA)))
948                 ;
949         lpc_scb.usbpllctrl = 0x23;
950         while (!(lpc_scb.usbpllstat & 1))
951                 ;
952
953         lpc_scb.usbclksel = 0;
954         lpc_scb.usbclkuen = (0 << LPC_SCB_USBCLKUEN_ENA);
955         lpc_scb.usbclkuen = (1 << LPC_SCB_USBCLKUEN_ENA);
956         while (!(lpc_scb.usbclkuen & (1 << LPC_SCB_USBCLKUEN_ENA)))
957                 ;
958
959         /* Turn on USB clock, use 48MHz clock unchanged */
960         lpc_scb.usbclkdiv = 1;
961
962         /* Configure interrupts */
963         ao_arch_block_interrupts();
964
965         /* Route all interrupts to the main isr */
966         lpc_usb.introuting = 0;
967
968         /* Configure NVIC */
969
970         lpc_nvic_set_enable(LPC_ISR_USB_IRQ_POS);
971         lpc_nvic_set_priority(LPC_ISR_USB_IRQ_POS, 0);
972
973         /* Clear any spurious interrupts */
974         lpc_usb.intstat = 0xffffffff;
975
976         debug ("ao_usb_enable\n");
977
978         /* Enable interrupts */
979         lpc_usb.inten = ((1 << LPC_USB_INT_EPOUT(0)) |
980                          (1 << LPC_USB_INT_EPIN(0)) |
981                          (1 << LPC_USB_INT_EPIN(AO_USB_INT_EP)) |
982                          (1 << LPC_USB_INT_EPOUT(AO_USB_OUT_EP)) |
983                          (1 << LPC_USB_INT_EPIN(AO_USB_IN_EP)) |
984                          (1 << LPC_USB_INT_DEV));
985
986         ao_arch_release_interrupts();
987
988         lpc_usb.devcmdstat = 0;
989         for (t = 0; t < 1000; t++)
990                 ao_arch_nop();
991
992         ao_usb_set_ep0();
993
994 #if HAS_USB_PULLUP
995         ao_gpio_set(AO_USB_PULLUP_PORT, AO_USB_PULLUP_PIN, AO_USB_PULLUP, 1);
996 #endif
997 }
998
999 #if USB_ECHO
1000 struct ao_task ao_usb_echo_task;
1001
1002 static void
1003 ao_usb_echo(void)
1004 {
1005         char    c;
1006
1007         for (;;) {
1008                 c = ao_usb_getchar();
1009                 ao_usb_putchar(c);
1010                 ao_usb_flush();
1011         }
1012 }
1013 #endif
1014
1015 #if USB_DEBUG
1016 static void
1017 ao_usb_irq(void)
1018 {
1019         printf ("control: %d out: %d in: %d int: %d reset: %d\n",
1020                 control_count, out_count, in_count, int_count, reset_count);
1021 }
1022
1023 __code struct ao_cmds ao_usb_cmds[] = {
1024         { ao_usb_irq, "I\0Show USB interrupt counts" },
1025         { 0, NULL }
1026 };
1027 #endif
1028
1029 void
1030 ao_usb_init(void)
1031 {
1032 #if HAS_USB_PULLUP
1033         ao_enable_output(AO_USB_PULLUP_PORT, AO_USB_PULLUP_PIN, AO_USB_PULLUP, 0);
1034 #endif
1035
1036         ao_usb_enable();
1037
1038         debug ("ao_usb_init\n");
1039 #if USB_ECHO
1040         ao_add_task(&ao_usb_echo_task, ao_usb_echo, "usb echo");
1041 #endif
1042 #if USB_DEBUG
1043         ao_cmd_register(&ao_usb_cmds[0]);
1044 #endif
1045 #if USE_USB_STDIO
1046         ao_add_stdio(_ao_usb_pollchar, ao_usb_putchar, ao_usb_flush);
1047 #endif
1048 }
1049
1050 #if TX_DBG || RX_DBG
1051
1052 struct ao_usb_dbg {
1053         int             line;
1054         char            *msg;
1055         uint32_t        value;
1056         uint32_t        primask;
1057 #if TX_DBG
1058         uint16_t        in_count;
1059         uint32_t        in_ep;
1060         uint32_t        in_pending;
1061         uint32_t        tx_count;
1062         uint32_t        in_flushed;
1063 #endif
1064 #if RX_DBG
1065         uint8_t         rx_count;
1066         uint8_t         rx_pos;
1067         uint8_t         out_avail;
1068         uint32_t        out_ep;
1069 #endif
1070 };
1071
1072 #define NUM_USB_DBG     8
1073
1074 static struct ao_usb_dbg dbg[NUM_USB_DBG];
1075 static int dbg_i;
1076
1077 static void _dbg(int line, char *msg, uint32_t value)
1078 {
1079         uint32_t        primask;
1080         dbg[dbg_i].line = line;
1081         dbg[dbg_i].msg = msg;
1082         dbg[dbg_i].value = value;
1083         asm("mrs %0,primask" : "=&r" (primask));
1084         dbg[dbg_i].primask = primask;
1085 #if TX_DBG
1086         dbg[dbg_i].in_count = in_count;
1087         dbg[dbg_i].in_ep = *ao_usb_epn_in(AO_USB_IN_EP);
1088         dbg[dbg_i].in_pending = ao_usb_in_pending;
1089         dbg[dbg_i].tx_count = ao_usb_tx_count;
1090         dbg[dbg_i].in_flushed = ao_usb_in_flushed;
1091 #endif
1092 #if RX_DBG
1093         dbg[dbg_i].rx_count = ao_usb_rx_count;
1094         dbg[dbg_i].rx_pos = ao_usb_rx_pos;
1095         dbg[dbg_i].out_avail = ao_usb_out_avail;
1096         dbg[dbg_i].out_ep = *ao_usb_epn_out(AO_USB_OUT_EP);
1097 #endif
1098         if (++dbg_i == NUM_USB_DBG)
1099                 dbg_i = 0;
1100 }
1101 #endif