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