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