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