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