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