altos/lpc: Handle USB reset by resetting internal state
[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 static 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, uint8_t i)
236 {
237         return &lpc_usb_endpoint.epn[n-1].out[i];
238 }
239
240 static inline vuint32_t *
241 ao_usb_epn_in(uint8_t n, uint8_t i)
242 {
243         return &lpc_usb_endpoint.epn[n-1].in[i];
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, 0), 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, 0));
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, 0));
270 }
271
272 static void
273 ao_usb_enable_ep(vuint32_t *ep, uint8_t *addr, uint16_t set_nbytes)
274 {
275         ao_usb_set_ep(ep, addr, set_nbytes);
276 }
277
278 static void
279 ao_usb_disable_ep(vuint32_t *ep)
280 {
281         *ep = ((0 << LPC_USB_EP_OFFSET) |
282                (0 << LPC_USB_EP_NBYTES) |
283                (0 << LPC_USB_EP_ENDPOINT_ISO) |
284                (0 << LPC_USB_EP_RATE_FEEDBACK) |
285                (0 << LPC_USB_EP_TOGGLE_RESET) |
286                (0 << LPC_USB_EP_STALL) |
287                (1 << LPC_USB_EP_DISABLED) |
288                (0 << LPC_USB_EP_ACTIVE));
289 }
290
291 static void
292 ao_usb_enable_epn(uint8_t n,
293                   uint16_t out_bytes, uint8_t *out_addr,
294                   uint8_t *in_addr)
295 {
296         ao_usb_enable_ep(ao_usb_epn_out(n, 0), out_addr, out_bytes);
297         ao_usb_disable_ep(ao_usb_epn_out(n, 1));
298
299         ao_usb_enable_ep(ao_usb_epn_in(n, 0), in_addr, 0);
300         ao_usb_disable_ep(ao_usb_epn_in(n, 1));
301 }
302
303 static void
304 ao_usb_disable_epn(uint8_t n)
305 {
306         ao_usb_disable_ep(ao_usb_epn_out(n, 0));
307         ao_usb_disable_ep(ao_usb_epn_out(n, 1));
308         ao_usb_disable_ep(ao_usb_epn_in(n, 0));
309         ao_usb_disable_ep(ao_usb_epn_in(n, 1));
310 }
311
312 static void
313 ao_usb_reset(void)
314 {
315         ao_usb_set_address(0);
316         ao_usb_configuration = 0;
317
318         ao_usb_ep0_state = AO_USB_EP0_IDLE;
319         ao_usb_ep0_in_data = NULL;
320         ao_usb_ep0_in_len = 0;
321         ao_usb_ep0_in_max = 0;
322
323         ao_usb_ep0_out_data = NULL;
324         ao_usb_ep0_out_len = 0;
325 }
326
327 static void
328 ao_usb_set_ep0(void)
329 {
330         int                     e;
331
332         /* Everything is single buffered for now */
333         lpc_usb.epbufcfg = 0;
334         lpc_usb.epinuse = 0;
335         lpc_usb.epskip = 0xffffffff;
336
337         lpc_usb.intstat = 0xc00003ff;
338
339         lpc_usb.epliststart = (uint32_t) (intptr_t) &lpc_usb_endpoint;
340         lpc_usb.databufstart = ((uint32_t) (intptr_t) ao_usb_sram) & 0xffc00000;
341
342         /* Set up EP 0 - a Control end point with 32 bytes of in and out buffers */
343
344         ao_usb_enable_ep(ao_usb_ep0_out(), ao_usb_ep0_rx_buffer, AO_USB_CONTROL_SIZE);
345         lpc_usb_endpoint.setup = ao_usb_sram_offset(ao_usb_ep0_setup_buffer);
346         ao_usb_enable_ep(ao_usb_ep0_in(), ao_usb_ep0_tx_buffer, 0);
347
348         /* Clear all of the other endpoints */
349         for (e = 1; e <= 4; e++)
350                 ao_usb_disable_epn(e);
351         ao_usb_reset();
352 }
353
354 static void
355 ao_usb_set_configuration(void)
356 {
357         debug ("ao_usb_set_configuration\n");
358
359         /* Set up the INT end point */
360         ao_usb_enable_epn(AO_USB_INT_EP, 0, NULL, NULL);
361
362         /* Set up the OUT end point */
363         ao_usb_enable_epn(AO_USB_OUT_EP, AO_USB_OUT_SIZE, ao_usb_out_rx_buffer[0], NULL);
364
365         /* Set the current RX pointer to the *other* buffer so that when buffer 0 gets
366          * data, we'll switch to it and pull bytes from there
367          */
368         ao_usb_out_rx_cur = 1;
369
370         /* Set up the IN end point */
371         ao_usb_enable_epn(AO_USB_IN_EP, 0, NULL, ao_usb_in_tx_buffer[0]);
372         ao_usb_in_tx_cur = 0;
373
374         ao_usb_in_flushed = 0;
375         ao_usb_in_pending = 0;
376         ao_wakeup(&ao_usb_in_pending);
377
378         ao_usb_out_avail = 0;
379         ao_usb_configuration = 0;
380
381         ao_usb_running = 1;
382         ao_wakeup(&ao_usb_running);
383 }
384
385 /* Send an IN data packet */
386 static void
387 ao_usb_ep0_flush(void)
388 {
389         uint8_t this_len;
390
391         this_len = ao_usb_ep0_in_len;
392         if (this_len > AO_USB_CONTROL_SIZE)
393                 this_len = AO_USB_CONTROL_SIZE;
394
395         ao_usb_ep0_in_len -= this_len;
396         ao_usb_ep0_in_max -= this_len;
397
398         if (this_len < AO_USB_CONTROL_SIZE || ao_usb_ep0_in_max == 0)
399                 ao_usb_ep0_state = AO_USB_EP0_IDLE;
400
401         debug_data ("Flush EP0 len %d:", this_len);
402         memcpy(ao_usb_ep0_tx_buffer, ao_usb_ep0_in_data, this_len);
403         debug_data ("\n");
404         ao_usb_ep0_in_data += this_len;
405
406         /* Mark the endpoint as TX valid to send the packet */
407         ao_usb_set_ep(ao_usb_ep0_in(), ao_usb_ep0_tx_buffer, this_len);
408         debug ("queue tx.  0 now %08x\n", *ao_usb_ep0_in());
409 }
410
411 /* Read data from the ep0 OUT fifo */
412 static void
413 ao_usb_ep0_fill(void)
414 {
415         uint16_t        len;
416         uint8_t         *rx_buffer;
417
418         /* Pull all of the data out of the packet */
419         if (lpc_usb.devcmdstat & (1 << LPC_USB_DEVCMDSTAT_SETUP)) {
420                 rx_buffer = ao_usb_ep0_setup_buffer;
421                 len = 8;
422         } else {
423                 rx_buffer = ao_usb_ep0_rx_buffer;
424                 len = AO_USB_CONTROL_SIZE - ao_usb_ep_count(ao_usb_ep0_out());
425         }
426
427         if (len > ao_usb_ep0_out_len)
428                 len = ao_usb_ep0_out_len;
429         ao_usb_ep0_out_len -= len;
430
431         debug_data ("Fill EP0 len %d:", len);
432         memcpy(ao_usb_ep0_out_data, rx_buffer, len);
433         debug_data ("\n");
434         ao_usb_ep0_out_data += len;
435
436         /* ACK the packet */
437         ao_usb_set_ep(ao_usb_ep0_out(), ao_usb_ep0_rx_buffer, AO_USB_CONTROL_SIZE);
438         lpc_usb.devcmdstat |= (1 << LPC_USB_DEVCMDSTAT_SETUP);
439 }
440
441 static void
442 ao_usb_ep0_in_reset(void)
443 {
444         ao_usb_ep0_in_data = ao_usb_ep0_in_buf;
445         ao_usb_ep0_in_len = 0;
446 }
447
448 static void
449 ao_usb_ep0_in_queue_byte(uint8_t a)
450 {
451         if (ao_usb_ep0_in_len < sizeof (ao_usb_ep0_in_buf))
452                 ao_usb_ep0_in_buf[ao_usb_ep0_in_len++] = a;
453 }
454
455 static void
456 ao_usb_ep0_in_set(const uint8_t *data, uint8_t len)
457 {
458         ao_usb_ep0_in_data = data;
459         ao_usb_ep0_in_len = len;
460 }
461
462 static void
463 ao_usb_ep0_out_set(uint8_t *data, uint8_t len)
464 {
465         ao_usb_ep0_out_data = data;
466         ao_usb_ep0_out_len = len;
467 }
468
469 static void
470 ao_usb_ep0_in_start(uint16_t max)
471 {
472         ao_usb_ep0_in_max = max;
473         /* Don't send more than asked for */
474         if (ao_usb_ep0_in_len > max)
475                 ao_usb_ep0_in_len = max;
476         ao_usb_ep0_flush();
477 }
478
479 static struct ao_usb_line_coding ao_usb_line_coding = {115200, 0, 0, 8};
480
481 /* Walk through the list of descriptors and find a match
482  */
483 static void
484 ao_usb_get_descriptor(uint16_t value, uint16_t length)
485 {
486         const uint8_t           *descriptor;
487         uint8_t         type = value >> 8;
488         uint8_t         index = value;
489
490         descriptor = ao_usb_descriptors;
491         while (descriptor[0] != 0) {
492                 if (descriptor[1] == type && index-- == 0) {
493                         uint8_t len;
494                         if (type == AO_USB_DESC_CONFIGURATION)
495                                 len = descriptor[2];
496                         else
497                                 len = descriptor[0];
498                         if (len > length)
499                                 len = length;
500                         ao_usb_ep0_in_set(descriptor, len);
501                         break;
502                 }
503                 descriptor += descriptor[0];
504         }
505 }
506
507 static void
508 ao_usb_ep0_setup(void)
509 {
510         /* Pull the setup packet out of the fifo */
511         ao_usb_ep0_out_set((uint8_t *) &ao_usb_setup, 8);
512         ao_usb_ep0_fill();
513         if (ao_usb_ep0_out_len != 0) {
514                 debug ("invalid setup packet length\n");
515                 return;
516         }
517
518         if ((ao_usb_setup.dir_type_recip & AO_USB_DIR_IN) || ao_usb_setup.length == 0)
519                 ao_usb_ep0_state = AO_USB_EP0_DATA_IN;
520         else
521                 ao_usb_ep0_state = AO_USB_EP0_DATA_OUT;
522
523         ao_usb_ep0_in_reset();
524
525         switch(ao_usb_setup.dir_type_recip & AO_USB_SETUP_TYPE_MASK) {
526         case AO_USB_TYPE_STANDARD:
527                 debug ("Standard setup packet\n");
528                 switch(ao_usb_setup.dir_type_recip & AO_USB_SETUP_RECIP_MASK) {
529                 case AO_USB_RECIP_DEVICE:
530                         debug ("Device setup packet\n");
531                         switch(ao_usb_setup.request) {
532                         case AO_USB_REQ_GET_STATUS:
533                                 debug ("get status\n");
534                                 ao_usb_ep0_in_queue_byte(0);
535                                 ao_usb_ep0_in_queue_byte(0);
536                                 break;
537                         case AO_USB_REQ_SET_ADDRESS:
538                                 debug ("set address %d\n", ao_usb_setup.value);
539                                 ao_usb_address = ao_usb_setup.value;
540                                 ao_usb_address_pending = 1;
541                                 break;
542                         case AO_USB_REQ_GET_DESCRIPTOR:
543                                 debug ("get descriptor %d\n", ao_usb_setup.value);
544                                 ao_usb_get_descriptor(ao_usb_setup.value, ao_usb_setup.length);
545                                 break;
546                         case AO_USB_REQ_GET_CONFIGURATION:
547                                 debug ("get configuration %d\n", ao_usb_configuration);
548                                 ao_usb_ep0_in_queue_byte(ao_usb_configuration);
549                                 break;
550                         case AO_USB_REQ_SET_CONFIGURATION:
551                                 ao_usb_configuration = ao_usb_setup.value;
552                                 debug ("set configuration %d\n", ao_usb_configuration);
553                                 ao_usb_set_configuration();
554                                 break;
555                         }
556                         break;
557                 case AO_USB_RECIP_INTERFACE:
558                         debug ("Interface setup packet\n");
559                         switch(ao_usb_setup.request) {
560                         case AO_USB_REQ_GET_STATUS:
561                                 ao_usb_ep0_in_queue_byte(0);
562                                 ao_usb_ep0_in_queue_byte(0);
563                                 break;
564                         case AO_USB_REQ_GET_INTERFACE:
565                                 ao_usb_ep0_in_queue_byte(0);
566                                 break;
567                         case AO_USB_REQ_SET_INTERFACE:
568                                 break;
569                         }
570                         break;
571                 case AO_USB_RECIP_ENDPOINT:
572                         debug ("Endpoint setup packet\n");
573                         switch(ao_usb_setup.request) {
574                         case AO_USB_REQ_GET_STATUS:
575                                 ao_usb_ep0_in_queue_byte(0);
576                                 ao_usb_ep0_in_queue_byte(0);
577                                 break;
578                         }
579                         break;
580                 }
581                 break;
582         case AO_USB_TYPE_CLASS:
583                 debug ("Class setup packet\n");
584                 switch (ao_usb_setup.request) {
585                 case AO_USB_SET_LINE_CODING:
586                         debug ("set line coding\n");
587                         ao_usb_ep0_out_set((uint8_t *) &ao_usb_line_coding, 7);
588                         break;
589                 case AO_USB_GET_LINE_CODING:
590                         debug ("get line coding\n");
591                         ao_usb_ep0_in_set((const uint8_t *) &ao_usb_line_coding, 7);
592                         break;
593                 case AO_USB_SET_CONTROL_LINE_STATE:
594                         break;
595                 }
596                 break;
597         }
598
599         /* If we're not waiting to receive data from the host,
600          * queue an IN response
601          */
602         if (ao_usb_ep0_state == AO_USB_EP0_DATA_IN)
603                 ao_usb_ep0_in_start(ao_usb_setup.length);
604 }
605
606 static void
607 ao_usb_ep0_handle(uint8_t receive)
608 {
609         ao_usb_ep0_receive = 0;
610
611         if (receive & AO_USB_EP0_GOT_RESET) {
612                 debug ("\treset\n");
613                 ao_usb_reset();
614                 return;
615         }
616         if (receive & AO_USB_EP0_GOT_SETUP) {
617                 debug ("\tsetup\n");
618                 ao_usb_ep0_setup();
619         }
620         if (receive & AO_USB_EP0_GOT_RX_DATA) {
621                 debug ("\tgot rx data\n");
622                 if (ao_usb_ep0_state == AO_USB_EP0_DATA_OUT) {
623                         ao_usb_ep0_fill();
624                         if (ao_usb_ep0_out_len == 0) {
625                                 ao_usb_ep0_state = AO_USB_EP0_DATA_IN;
626                                 ao_usb_ep0_in_start(0);
627                         }
628                 }
629         }
630         if (receive & AO_USB_EP0_GOT_TX_ACK) {
631                 debug ("\tgot tx ack\n");
632
633                 /* Wait until the IN packet is received from addr 0
634                  * before assigning our local address
635                  */
636                 if (ao_usb_address_pending) {
637 #if HAS_FLIGHT
638                         /* Go to idle mode if USB is connected
639                          */
640                         ao_flight_force_idle = 1;
641 #endif
642                         ao_usb_set_address(ao_usb_address);
643                 }
644                 if (ao_usb_ep0_state == AO_USB_EP0_DATA_IN)
645                         ao_usb_ep0_flush();
646         }
647 }
648
649 #if USB_DEBUG
650 static uint16_t int_count;
651 static uint16_t in_count;
652 static uint16_t out_count;
653 static uint16_t reset_count;
654 #endif
655
656 void
657 lpc_usb_irq_isr(void)
658 {
659         uint32_t        intstat = lpc_usb.intstat & lpc_usb.inten;
660
661         lpc_usb.intstat = intstat;
662         /* Handle EP0 OUT packets */
663         if (intstat & (1 << LPC_USB_INT_EPOUT(0))) {
664                 if (lpc_usb.devcmdstat & (1 << LPC_USB_DEVCMDSTAT_SETUP))
665                         ao_usb_ep0_receive |= AO_USB_EP0_GOT_SETUP;
666                 else
667                         ao_usb_ep0_receive |= AO_USB_EP0_GOT_RX_DATA;
668
669                 ao_usb_ep0_handle(ao_usb_ep0_receive);
670         }
671
672         /* Handle EP0 IN packets */
673         if (intstat & (1 << LPC_USB_INT_EPIN(0))) {
674                 ao_usb_ep0_receive |= AO_USB_EP0_GOT_TX_ACK;
675
676                 ao_usb_ep0_handle(ao_usb_ep0_receive);
677         }
678
679
680         /* Handle OUT packets */
681         if (intstat & (1 << LPC_USB_INT_EPOUT(AO_USB_OUT_EP))) {
682 #if USB_DEBUG
683                 ++out_count;
684 #endif
685                 _rx_dbg1("RX ISR", *ao_usb_epn_out(AO_USB_OUT_EP));
686                 ao_usb_out_avail = 1;
687                 _rx_dbg0("out avail set");
688                 ao_wakeup(AO_USB_OUT_SLEEP_ADDR)
689                 _rx_dbg0("stdin awoken");
690         }
691
692         /* Handle IN packets */
693         if (intstat & (1 << LPC_USB_INT_EPIN(AO_USB_IN_EP))) {
694 #if USB_DEBUG
695                 ++in_count;
696 #endif
697                 _tx_dbg1("TX ISR", *ao_usb_epn_in(AO_USB_IN_EP));
698                 ao_usb_in_pending = 0;
699                 ao_wakeup(&ao_usb_in_pending);
700         }
701
702         /* NAK all INT EP IN packets */
703         if (intstat & (1 << LPC_USB_INT_EPIN(AO_USB_INT_EP))) {
704                 ;
705         }
706
707         /* Check for reset */
708         if (intstat & (1 << LPC_USB_INT_DEV)) {
709                 if (lpc_usb.devcmdstat & (1 << LPC_USB_DEVCMDSTAT_DRES_C))
710                 {
711                         lpc_usb.devcmdstat |= (1 << LPC_USB_DEVCMDSTAT_DRES_C);
712                         ao_usb_ep0_receive |= AO_USB_EP0_GOT_RESET;
713                         ao_usb_ep0_handle(ao_usb_ep0_receive);
714                 }
715         }
716 }
717
718
719
720 /* Queue the current IN buffer for transmission */
721 static void
722 _ao_usb_in_send(void)
723 {
724         _tx_dbg0("in_send start");
725         debug ("send %d\n", ao_usb_tx_count);
726         while (ao_usb_in_pending)
727                 ao_sleep(&ao_usb_in_pending);
728         ao_usb_in_pending = 1;
729         if (ao_usb_tx_count != AO_USB_IN_SIZE)
730                 ao_usb_in_flushed = 1;
731         ao_usb_set_ep(ao_usb_epn_in(AO_USB_IN_EP, 0), ao_usb_in_tx_buffer[ao_usb_in_tx_cur], ao_usb_tx_count);
732         ao_usb_in_tx_cur = 1 - ao_usb_in_tx_cur;
733         ao_usb_tx_count = 0;
734         _tx_dbg0("in_send end");
735 }
736
737 /* Wait for a free IN buffer. Interrupts are blocked */
738 static void
739 _ao_usb_in_wait(void)
740 {
741         for (;;) {
742                 /* Check if the current buffer is writable */
743                 if (ao_usb_tx_count < AO_USB_IN_SIZE)
744                         break;
745
746                 _tx_dbg0("in_wait top");
747                 /* Wait for an IN buffer to be ready */
748                 while (ao_usb_in_pending)
749                         ao_sleep(&ao_usb_in_pending);
750                 _tx_dbg0("in_wait bottom");
751         }
752 }
753
754 void
755 ao_usb_flush(void)
756 {
757         if (!ao_usb_running)
758                 return;
759
760         /* Anytime we've sent a character since
761          * the last time we flushed, we'll need
762          * to send a packet -- the only other time
763          * we would send a packet is when that
764          * packet was full, in which case we now
765          * want to send an empty packet
766          */
767         ao_arch_block_interrupts();
768         while (!ao_usb_in_flushed) {
769                 _tx_dbg0("flush top");
770                 _ao_usb_in_send();
771                 _tx_dbg0("flush end");
772         }
773         ao_arch_release_interrupts();
774 }
775
776 void
777 ao_usb_putchar(char c)
778 {
779         if (!ao_usb_running)
780                 return;
781
782         ao_arch_block_interrupts();
783         _ao_usb_in_wait();
784
785         ao_usb_in_flushed = 0;
786         ao_usb_in_tx_buffer[ao_usb_in_tx_cur][ao_usb_tx_count++] = (uint8_t) c;
787
788         /* Send the packet when full */
789         if (ao_usb_tx_count == AO_USB_IN_SIZE) {
790                 _tx_dbg0("putchar full");
791                 _ao_usb_in_send();
792                 _tx_dbg0("putchar flushed");
793         }
794         ao_arch_release_interrupts();
795 }
796
797 static void
798 _ao_usb_out_recv(void)
799 {
800         _rx_dbg0("out_recv top");
801         ao_usb_out_avail = 0;
802
803         ao_usb_rx_count = AO_USB_OUT_SIZE - ao_usb_epn_out_count(AO_USB_OUT_EP);
804
805         _rx_dbg1("out_recv count", ao_usb_rx_count);
806         debug ("recv %d\n", ao_usb_rx_count);
807         debug_data("Fill OUT len %d\n", ao_usb_rx_count);
808         ao_usb_rx_pos = 0;
809         ao_usb_out_rx_cur = 1 - ao_usb_out_rx_cur;
810
811         /* ACK the packet */
812         ao_usb_set_epn_out(AO_USB_OUT_EP, ao_usb_out_rx_buffer[1-ao_usb_out_rx_cur], AO_USB_OUT_SIZE);
813 }
814
815 int
816 _ao_usb_pollchar(void)
817 {
818         uint8_t c;
819
820         if (!ao_usb_running)
821                 return AO_READ_AGAIN;
822
823         for (;;) {
824                 if (ao_usb_rx_pos != ao_usb_rx_count)
825                         break;
826
827                 _rx_dbg0("poll check");
828                 /* Check to see if a packet has arrived */
829                 if (!ao_usb_out_avail) {
830                         _rx_dbg0("poll none");
831                         return AO_READ_AGAIN;
832                 }
833                 _ao_usb_out_recv();
834         }
835
836         /* Pull a character out of the fifo */
837         c = ao_usb_out_rx_buffer[ao_usb_out_rx_cur][ao_usb_rx_pos++];
838         return c;
839 }
840
841 char
842 ao_usb_getchar(void)
843 {
844         int     c;
845
846         ao_arch_block_interrupts();
847         while ((c = _ao_usb_pollchar()) == AO_READ_AGAIN)
848                 ao_sleep(AO_USB_OUT_SLEEP_ADDR);
849         ao_arch_release_interrupts();
850         return c;
851 }
852
853 void
854 ao_usb_disable(void)
855 {
856         ao_arch_block_interrupts();
857
858 #if HAS_USB_PULLUP
859         ao_gpio_set(AO_USB_PULLUP_PORT, AO_USB_PULLUP_PIN, AO_USB_PULLUP, 0);
860 #endif
861         /* Disable interrupts */
862         lpc_usb.inten = 0;
863
864         lpc_nvic_clear_enable(LPC_ISR_USB_IRQ_POS);
865
866         /* Disable the device */
867         lpc_usb.devcmdstat = 0;
868
869         /* Turn off USB clock */
870         lpc_scb.usbclkdiv = 0;
871
872         /* Disable USB PHY and PLL */
873         lpc_scb.pdruncfg |= ((1 << LPC_SCB_PDRUNCFG_USBPAD_PD) |
874                              (1 << LPC_SCB_PDRUNCFG_USBPLL_PD));
875
876         /* Disable USB registers and RAM */
877         lpc_scb.sysahbclkctrl &= ~((1 << LPC_SCB_SYSAHBCLKCTRL_USB) |
878                                    (1 << LPC_SCB_SYSAHBCLKCTRL_USBRAM));
879
880         ao_arch_release_interrupts();
881 }
882
883 void
884 ao_usb_enable(void)
885 {
886         int     t;
887
888         /* Enable USB pins */
889 #if HAS_LPC_USB_CONNECT
890         lpc_ioconf.pio0_6 = ((LPC_IOCONF_FUNC_USB_CONNECT << LPC_IOCONF_FUNC) |
891                              (LPC_IOCONF_MODE_INACTIVE << LPC_IOCONF_MODE) |
892                              (0 << LPC_IOCONF_HYS) |
893                              (0 << LPC_IOCONF_INV) |
894                              (0 << LPC_IOCONF_OD) |
895                              0x80);
896 #endif
897 #if HAS_USB_VBUS
898         lpc_ioconf.pio0_3 = ((LPC_IOCONF_FUNC_USB_VBUS << LPC_IOCONF_FUNC) |
899                              (LPC_IOCONF_MODE_INACTIVE << LPC_IOCONF_MODE) |
900                              (0 << LPC_IOCONF_HYS) |
901                              (0 << LPC_IOCONF_INV) |
902                              (0 << LPC_IOCONF_OD) |
903                              0x80);
904 #endif
905         /* Enable USB registers and RAM */
906         lpc_scb.sysahbclkctrl |= ((1 << LPC_SCB_SYSAHBCLKCTRL_USB) |
907                                   (1 << LPC_SCB_SYSAHBCLKCTRL_USBRAM));
908
909         /* Enable USB PHY */
910         lpc_scb.pdruncfg &= ~(1 << LPC_SCB_PDRUNCFG_USBPAD_PD);
911
912         /* Turn on USB PLL */
913         lpc_scb.pdruncfg &= ~(1 << LPC_SCB_PDRUNCFG_USBPLL_PD);
914
915         lpc_scb.usbpllclksel = (LPC_SCB_SYSPLLCLKSEL_SEL_SYSOSC << LPC_SCB_SYSPLLCLKSEL_SEL);
916         lpc_scb.usbpllclkuen = (0 << LPC_SCB_USBPLLCLKUEN_ENA);
917         lpc_scb.usbpllclkuen = (1 << LPC_SCB_USBPLLCLKUEN_ENA);
918         while (!(lpc_scb.usbpllclkuen & (1 << LPC_SCB_USBPLLCLKUEN_ENA)))
919                 ;
920         lpc_scb.usbpllctrl = 0x23;
921         while (!(lpc_scb.usbpllstat & 1))
922                 ;
923
924         lpc_scb.usbclksel = 0;
925         lpc_scb.usbclkuen = (0 << LPC_SCB_USBCLKUEN_ENA);
926         lpc_scb.usbclkuen = (1 << LPC_SCB_USBCLKUEN_ENA);
927         while (!(lpc_scb.usbclkuen & (1 << LPC_SCB_USBCLKUEN_ENA)))
928                 ;
929
930         /* Turn on USB clock, use 48MHz clock unchanged */
931         lpc_scb.usbclkdiv = 1;
932
933         /* Configure interrupts */
934         ao_arch_block_interrupts();
935
936         /* Route all interrupts to the main isr */
937         lpc_usb.introuting = 0;
938
939         /* Configure NVIC */
940
941         lpc_nvic_set_enable(LPC_ISR_USB_IRQ_POS);
942         lpc_nvic_set_priority(LPC_ISR_USB_IRQ_POS, 0);
943
944         /* Clear any spurious interrupts */
945         lpc_usb.intstat = 0xffffffff;
946
947         debug ("ao_usb_enable\n");
948
949         /* Enable interrupts */
950         lpc_usb.inten = ((1 << LPC_USB_INT_EPOUT(0)) |
951                          (1 << LPC_USB_INT_EPIN(0)) |
952                          (1 << LPC_USB_INT_EPIN(AO_USB_INT_EP)) |
953                          (1 << LPC_USB_INT_EPOUT(AO_USB_OUT_EP)) |
954                          (1 << LPC_USB_INT_EPIN(AO_USB_IN_EP)) |
955                          (1 << LPC_USB_INT_DEV));
956
957         ao_arch_release_interrupts();
958
959         lpc_usb.devcmdstat = 0;
960         for (t = 0; t < 1000; t++)
961                 ao_arch_nop();
962
963         ao_usb_sram = lpc_usb_sram;
964
965         ao_usb_ep0_rx_buffer    = ao_usb_alloc_sram(AO_USB_CONTROL_SIZE);
966         ao_usb_ep0_tx_buffer    = ao_usb_alloc_sram(AO_USB_CONTROL_SIZE);
967         ao_usb_ep0_setup_buffer = ao_usb_alloc_sram(AO_USB_CONTROL_SIZE);
968
969         ao_usb_out_rx_buffer[0] = ao_usb_alloc_sram(AO_USB_OUT_SIZE);
970         ao_usb_out_rx_buffer[1] = ao_usb_alloc_sram(AO_USB_OUT_SIZE);
971         ao_usb_in_tx_buffer[0]  = ao_usb_alloc_sram(AO_USB_IN_SIZE);
972         ao_usb_in_tx_buffer[1]  = ao_usb_alloc_sram(AO_USB_IN_SIZE);
973
974         ao_usb_set_ep0();
975
976 #if HAS_USB_PULLUP
977         ao_gpio_set(AO_USB_PULLUP_PORT, AO_USB_PULLUP_PIN, AO_USB_PULLUP, 1);
978 #endif
979 }
980
981 #if USB_ECHO
982 struct ao_task ao_usb_echo_task;
983
984 static void
985 ao_usb_echo(void)
986 {
987         char    c;
988
989         for (;;) {
990                 c = ao_usb_getchar();
991                 ao_usb_putchar(c);
992                 ao_usb_flush();
993         }
994 }
995 #endif
996
997 #if USB_DEBUG
998 static void
999 ao_usb_irq(void)
1000 {
1001         printf ("control: %d out: %d in: %d int: %d reset: %d\n",
1002                 control_count, out_count, in_count, int_count, reset_count);
1003 }
1004
1005 __code struct ao_cmds ao_usb_cmds[] = {
1006         { ao_usb_irq, "I\0Show USB interrupt counts" },
1007         { 0, NULL }
1008 };
1009 #endif
1010
1011 void
1012 ao_usb_init(void)
1013 {
1014 #if HAS_USB_PULLUP
1015         ao_enable_output(AO_USB_PULLUP_PORT, AO_USB_PULLUP_PIN, AO_USB_PULLUP, 0);
1016 #endif
1017         ao_usb_enable();
1018
1019         debug ("ao_usb_init\n");
1020 #if USB_ECHO
1021         ao_add_task(&ao_usb_echo_task, ao_usb_echo, "usb echo");
1022 #endif
1023 #if USB_DEBUG
1024         ao_cmd_register(&ao_usb_cmds[0]);
1025 #endif
1026 #if USE_USB_STDIO
1027         ao_add_stdio(_ao_usb_pollchar, ao_usb_putchar, ao_usb_flush);
1028 #endif
1029 }
1030
1031 #if TX_DBG || RX_DBG
1032
1033 struct ao_usb_dbg {
1034         int             line;
1035         char            *msg;
1036         uint32_t        value;
1037         uint32_t        primask;
1038 #if TX_DBG
1039         uint16_t        in_count;
1040         uint32_t        in_ep;
1041         uint32_t        in_pending;
1042         uint32_t        tx_count;
1043         uint32_t        in_flushed;
1044 #endif
1045 #if RX_DBG
1046         uint8_t         rx_count;
1047         uint8_t         rx_pos;
1048         uint8_t         out_avail;
1049         uint32_t        out_ep;
1050 #endif
1051 };
1052
1053 #define NUM_USB_DBG     8
1054
1055 static struct ao_usb_dbg dbg[NUM_USB_DBG];
1056 static int dbg_i;
1057
1058 static void _dbg(int line, char *msg, uint32_t value)
1059 {
1060         uint32_t        primask;
1061         dbg[dbg_i].line = line;
1062         dbg[dbg_i].msg = msg;
1063         dbg[dbg_i].value = value;
1064         asm("mrs %0,primask" : "=&r" (primask));
1065         dbg[dbg_i].primask = primask;
1066 #if TX_DBG
1067         dbg[dbg_i].in_count = in_count;
1068         dbg[dbg_i].in_ep = *ao_usb_epn_in(AO_USB_IN_EP, 0);
1069         dbg[dbg_i].in_pending = ao_usb_in_pending;
1070         dbg[dbg_i].tx_count = ao_usb_tx_count;
1071         dbg[dbg_i].in_flushed = ao_usb_in_flushed;
1072 #endif
1073 #if RX_DBG
1074         dbg[dbg_i].rx_count = ao_usb_rx_count;
1075         dbg[dbg_i].rx_pos = ao_usb_rx_pos;
1076         dbg[dbg_i].out_avail = ao_usb_out_avail;
1077         dbg[dbg_i].out_ep = *ao_usb_epn_out(AO_USB_OUT_EP, 0);
1078 #endif
1079         if (++dbg_i == NUM_USB_DBG)
1080                 dbg_i = 0;
1081 }
1082 #endif