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