]> git.donarmstrong.com Git - kiibohd-controller.git/blob - Output/pjrcUSB/arm/usb_dev.c
Adding McHCK flash reload function and some cleanup.
[kiibohd-controller.git] / Output / pjrcUSB / arm / usb_dev.c
1 /* Teensyduino Core Library
2  * http://www.pjrc.com/teensy/
3  * Copyright (c) 2013 PJRC.COM, LLC.
4  * Modified by Jacob Alexander 2013-2014
5  *
6  * Permission is hereby granted, free of charge, to any person obtaining
7  * a copy of this software and associated documentation files (the
8  * "Software"), to deal in the Software without restriction, including
9  * without limitation the rights to use, copy, modify, merge, publish,
10  * distribute, sublicense, and/or sell copies of the Software, and to
11  * permit persons to whom the Software is furnished to do so, subject to
12  * the following conditions:
13  *
14  * 1. The above copyright notice and this permission notice shall be
15  * included in all copies or substantial portions of the Software.
16  *
17  * 2. If the Software is incorporated into a build system that allows
18  * selection among a list of target devices, then similar target
19  * devices manufactured by PJRC.COM must be included in the list of
20  * target devices and selectable in the same manner.
21  *
22  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
23  * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
24  * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
25  * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
26  * BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
27  * ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
28  * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
29  * SOFTWARE.
30  */
31
32 // Project Includes
33 #include <Lib/OutputLib.h>
34 #include <print.h>
35
36 // Local Includes
37 #include "usb_dev.h"
38 #include "usb_mem.h"
39
40 // buffer descriptor table
41
42 typedef struct {
43         uint32_t desc;
44         void * addr;
45 } bdt_t;
46
47 __attribute__ ((section(".usbdescriptortable"), used))
48 static bdt_t table[(NUM_ENDPOINTS+1)*4];
49
50 static usb_packet_t *rx_first[NUM_ENDPOINTS];
51 static usb_packet_t *rx_last[NUM_ENDPOINTS];
52 static usb_packet_t *tx_first[NUM_ENDPOINTS];
53 static usb_packet_t *tx_last[NUM_ENDPOINTS];
54 uint16_t usb_rx_byte_count_data[NUM_ENDPOINTS];
55
56 static uint8_t tx_state[NUM_ENDPOINTS];
57 #define TX_STATE_BOTH_FREE_EVEN_FIRST   0
58 #define TX_STATE_BOTH_FREE_ODD_FIRST    1
59 #define TX_STATE_EVEN_FREE              2
60 #define TX_STATE_ODD_FREE               3
61 #define TX_STATE_NONE_FREE_EVEN_FIRST   4
62 #define TX_STATE_NONE_FREE_ODD_FIRST    5
63
64 #define BDT_OWN         0x80
65 #define BDT_DATA1       0x40
66 #define BDT_DATA0       0x00
67 #define BDT_DTS         0x08
68 #define BDT_STALL       0x04
69 #define BDT_PID(n)      (((n) >> 2) & 15)
70
71 #define BDT_DESC(count, data)   (BDT_OWN | BDT_DTS \
72                                 | ((data) ? BDT_DATA1 : BDT_DATA0) \
73                                 | ((count) << 16))
74
75 #define TX   1
76 #define RX   0
77 #define ODD  1
78 #define EVEN 0
79 #define DATA0 0
80 #define DATA1 1
81 #define index(endpoint, tx, odd) (((endpoint) << 2) | ((tx) << 1) | (odd))
82 #define stat2bufferdescriptor(stat) (table + ((stat) >> 2))
83
84
85 static union {
86  struct {
87   union {
88    struct {
89         uint8_t bmRequestType;
90         uint8_t bRequest;
91    };
92         uint16_t wRequestAndType;
93   };
94         uint16_t wValue;
95         uint16_t wIndex;
96         uint16_t wLength;
97  };
98  struct {
99         uint32_t word1;
100         uint32_t word2;
101  };
102 } setup;
103
104
105 #define GET_STATUS              0
106 #define CLEAR_FEATURE           1
107 #define SET_FEATURE             3
108 #define SET_ADDRESS             5
109 #define GET_DESCRIPTOR          6
110 #define SET_DESCRIPTOR          7
111 #define GET_CONFIGURATION       8
112 #define SET_CONFIGURATION       9
113 #define GET_INTERFACE           10
114 #define SET_INTERFACE           11
115 #define SYNCH_FRAME             12
116
117 // SETUP always uses a DATA0 PID for the data field of the SETUP transaction.
118 // transactions in the data phase start with DATA1 and toggle (figure 8-12, USB1.1)
119 // Status stage uses a DATA1 PID.
120
121 static uint8_t ep0_rx0_buf[EP0_SIZE] __attribute__ ((aligned (4)));
122 static uint8_t ep0_rx1_buf[EP0_SIZE] __attribute__ ((aligned (4)));
123 static const uint8_t *ep0_tx_ptr = NULL;
124 static uint16_t ep0_tx_len;
125 static uint8_t ep0_tx_bdt_bank = 0;
126 static uint8_t ep0_tx_data_toggle = 0;
127 uint8_t usb_rx_memory_needed = 0;
128
129 volatile uint8_t usb_configuration = 0;
130 volatile uint8_t usb_reboot_timer = 0;
131
132
133 static void endpoint0_stall()
134 {
135         //print("STALL");
136         USB0_ENDPT0 = USB_ENDPT_EPSTALL | USB_ENDPT_EPRXEN | USB_ENDPT_EPTXEN | USB_ENDPT_EPHSHK;
137 }
138
139
140 static void endpoint0_transmit(const void *data, uint32_t len)
141 {
142         //print("TRANSMIT");
143 #if 0
144         serial_print("tx0:");
145         serial_phex32((uint32_t)data);
146         serial_print(",");
147         serial_phex16(len);
148         serial_print(ep0_tx_bdt_bank ? ", odd" : ", even");
149         serial_print(ep0_tx_data_toggle ? ", d1\n" : ", d0\n");
150 #endif
151         table[index(0, TX, ep0_tx_bdt_bank)].addr = (void *)data;
152         table[index(0, TX, ep0_tx_bdt_bank)].desc = BDT_DESC(len, ep0_tx_data_toggle);
153         ep0_tx_data_toggle ^= 1;
154         ep0_tx_bdt_bank ^= 1;
155 }
156
157 static uint8_t reply_buffer[8];
158
159 static void usb_setup()
160 {
161         //print("SETUP");
162         const uint8_t *data = NULL;
163         uint32_t datalen = 0;
164         const usb_descriptor_list_t *list;
165         uint32_t size;
166         volatile uint8_t *reg;
167         uint8_t epconf;
168         const uint8_t *cfg;
169         int i;
170
171         switch (setup.wRequestAndType) {
172           case 0x0500: // SET_ADDRESS
173                 break;
174           case 0x0900: // SET_CONFIGURATION
175                 //serial_print("configure\n");
176                 usb_configuration = setup.wValue;
177                 reg = &USB0_ENDPT1;
178                 cfg = usb_endpoint_config_table;
179                 // clear all BDT entries, free any allocated memory...
180                 for (i=4; i < (NUM_ENDPOINTS+1)*4; i++) {
181                         if (table[i].desc & BDT_OWN) {
182                                 usb_free((usb_packet_t *)((uint8_t *)(table[i].addr) - 8));
183                         }
184                 }
185                 // free all queued packets
186                 for (i=0; i < NUM_ENDPOINTS; i++) {
187                         usb_packet_t *p, *n;
188                         p = rx_first[i];
189                         while (p) {
190                                 n = p->next;
191                                 usb_free(p);
192                                 p = n;
193                         }
194                         rx_first[i] = NULL;
195                         rx_last[i] = NULL;
196                         p = tx_first[i];
197                         while (p) {
198                                 n = p->next;
199                                 usb_free(p);
200                                 p = n;
201                         }
202                         tx_first[i] = NULL;
203                         tx_last[i] = NULL;
204                         usb_rx_byte_count_data[i] = 0;
205                         switch (tx_state[i]) {
206                           case TX_STATE_EVEN_FREE:
207                           case TX_STATE_NONE_FREE_EVEN_FIRST:
208                                 tx_state[i] = TX_STATE_BOTH_FREE_EVEN_FIRST;
209                                 break;
210                           case TX_STATE_ODD_FREE:
211                           case TX_STATE_NONE_FREE_ODD_FIRST:
212                                 tx_state[i] = TX_STATE_BOTH_FREE_ODD_FIRST;
213                                 break;
214                           default:
215                                 break;
216                         }
217                 }
218                 usb_rx_memory_needed = 0;
219                 for (i=1; i <= NUM_ENDPOINTS; i++) {
220                         epconf = *cfg++;
221                         *reg = epconf;
222                         reg += 4;
223                         if (epconf & USB_ENDPT_EPRXEN) {
224                                 usb_packet_t *p;
225                                 p = usb_malloc();
226                                 if (p) {
227                                         table[index(i, RX, EVEN)].addr = p->buf;
228                                         table[index(i, RX, EVEN)].desc = BDT_DESC(64, 0);
229                                 } else {
230                                         table[index(i, RX, EVEN)].desc = 0;
231                                         usb_rx_memory_needed++;
232                                 }
233                                 p = usb_malloc();
234                                 if (p) {
235                                         table[index(i, RX, ODD)].addr = p->buf;
236                                         table[index(i, RX, ODD)].desc = BDT_DESC(64, 1);
237                                 } else {
238                                         table[index(i, RX, ODD)].desc = 0;
239                                         usb_rx_memory_needed++;
240                                 }
241                         }
242                         table[index(i, TX, EVEN)].desc = 0;
243                         table[index(i, TX, ODD)].desc = 0;
244                 }
245                 break;
246           case 0x0880: // GET_CONFIGURATION
247                 reply_buffer[0] = usb_configuration;
248                 datalen = 1;
249                 data = reply_buffer;
250                 break;
251           case 0x0080: // GET_STATUS (device)
252                 reply_buffer[0] = 0;
253                 reply_buffer[1] = 0;
254                 datalen = 2;
255                 data = reply_buffer;
256                 break;
257           case 0x0082: // GET_STATUS (endpoint)
258                 if (setup.wIndex > NUM_ENDPOINTS) {
259                         // TODO: do we need to handle IN vs OUT here?
260                         endpoint0_stall();
261                         return;
262                 }
263                 reply_buffer[0] = 0;
264                 reply_buffer[1] = 0;
265                 if (*(uint8_t *)(&USB0_ENDPT0 + setup.wIndex * 4) & 0x02) reply_buffer[0] = 1;
266                 data = reply_buffer;
267                 datalen = 2;
268                 break;
269           case 0x0102: // CLEAR_FEATURE (endpoint)
270                 i = setup.wIndex & 0x7F;
271                 if (i > NUM_ENDPOINTS || setup.wValue != 0) {
272                         // TODO: do we need to handle IN vs OUT here?
273                         endpoint0_stall();
274                         return;
275                 }
276                 (*(uint8_t *)(&USB0_ENDPT0 + setup.wIndex * 4)) &= ~0x02;
277                 // TODO: do we need to clear the data toggle here?
278                 break;
279           case 0x0302: // SET_FEATURE (endpoint)
280                 i = setup.wIndex & 0x7F;
281                 if (i > NUM_ENDPOINTS || setup.wValue != 0) {
282                         // TODO: do we need to handle IN vs OUT here?
283                         endpoint0_stall();
284                         return;
285                 }
286                 (*(uint8_t *)(&USB0_ENDPT0 + setup.wIndex * 4)) |= 0x02;
287                 // TODO: do we need to clear the data toggle here?
288                 break;
289           case 0x0680: // GET_DESCRIPTOR
290           case 0x0681:
291                 //serial_print("desc:");
292                 //serial_phex16(setup.wValue);
293                 //serial_print("\n");
294                 for (list = usb_descriptor_list; 1; list++) {
295                         if (list->addr == NULL) break;
296                         //if (setup.wValue == list->wValue && 
297                         //(setup.wIndex == list->wIndex) || ((setup.wValue >> 8) == 3)) {
298                         if (setup.wValue == list->wValue && setup.wIndex == list->wIndex) {
299                                 data = list->addr;
300                                 if ((setup.wValue >> 8) == 3) {
301                                         // for string descriptors, use the descriptor's
302                                         // length field, allowing runtime configured
303                                         // length.
304                                         datalen = *(list->addr);
305                                 } else {
306                                         datalen = list->length;
307                                 }
308 #if 0
309                                 serial_print("Desc found, ");
310                                 serial_phex32((uint32_t)data);
311                                 serial_print(",");
312                                 serial_phex16(datalen);
313                                 serial_print(",");
314                                 serial_phex(data[0]);
315                                 serial_phex(data[1]);
316                                 serial_phex(data[2]);
317                                 serial_phex(data[3]);
318                                 serial_phex(data[4]);
319                                 serial_phex(data[5]);
320                                 serial_print("\n");
321 #endif
322                                 goto send;
323                         }
324                 }
325                 //serial_print("desc: not found\n");
326                 endpoint0_stall();
327                 return;
328 #if defined(CDC_STATUS_INTERFACE)
329           case 0x2221: // CDC_SET_CONTROL_LINE_STATE
330                 usb_cdc_line_rtsdtr = setup.wValue;
331                 //serial_print("set control line state\n");
332                 break;
333           case 0x2021: // CDC_SET_LINE_CODING
334                 //serial_print("set coding, waiting...\n");
335                 return;
336 #endif
337
338 // TODO: this does not work... why?
339 #if defined(SEREMU_INTERFACE) || defined(KEYBOARD_INTERFACE)
340           case 0x0921: // HID SET_REPORT
341                 //serial_print(":)\n");
342                 return;
343           case 0x0A21: // HID SET_IDLE
344                 break;
345           // case 0xC940:
346 #endif
347           default:
348                 endpoint0_stall();
349                 return;
350         }
351         send:
352         //serial_print("setup send ");
353         //serial_phex32(data);
354         //serial_print(",");
355         //serial_phex16(datalen);
356         //serial_print("\n");
357
358         if (datalen > setup.wLength) datalen = setup.wLength;
359         size = datalen;
360         if (size > EP0_SIZE) size = EP0_SIZE;
361         endpoint0_transmit(data, size);
362         data += size;
363         datalen -= size;
364         if (datalen == 0 && size < EP0_SIZE) return;
365
366         size = datalen;
367         if (size > EP0_SIZE) size = EP0_SIZE;
368         endpoint0_transmit(data, size);
369         data += size;
370         datalen -= size;
371         if (datalen == 0 && size < EP0_SIZE) return;
372
373         ep0_tx_ptr = data;
374         ep0_tx_len = datalen;
375 }
376
377
378
379 //A bulk endpoint's toggle sequence is initialized to DATA0 when the endpoint
380 //experiences any configuration event (configuration events are explained in
381 //Sections 9.1.1.5 and 9.4.5).
382
383 //Configuring a device or changing an alternate setting causes all of the status
384 //and configuration values associated with endpoints in the affected interfaces
385 //to be set to their default values. This includes setting the data toggle of
386 //any endpoint using data toggles to the value DATA0.
387
388 //For endpoints using data toggle, regardless of whether an endpoint has the
389 //Halt feature set, a ClearFeature(ENDPOINT_HALT) request always results in the
390 //data toggle being reinitialized to DATA0.
391
392
393
394 // #define stat2bufferdescriptor(stat) (table + ((stat) >> 2))
395
396 static void usb_control(uint32_t stat)
397 {
398         //print("CONTROL");
399         bdt_t *b;
400         uint32_t pid, size;
401         uint8_t *buf;
402         const uint8_t *data;
403
404         b = stat2bufferdescriptor(stat);
405         pid = BDT_PID(b->desc);
406         //count = b->desc >> 16;
407         buf = b->addr;
408         //serial_print("pid:");
409         //serial_phex(pid);
410         //serial_print(", count:");
411         //serial_phex(count);
412         //serial_print("\n");
413
414         switch (pid) {
415         case 0x0D: // Setup received from host
416                 //serial_print("PID=Setup\n");
417                 //if (count != 8) ; // panic?
418                 // grab the 8 byte setup info
419                 setup.word1 = *(uint32_t *)(buf);
420                 setup.word2 = *(uint32_t *)(buf + 4);
421
422                 // give the buffer back
423                 b->desc = BDT_DESC(EP0_SIZE, DATA1);
424                 //table[index(0, RX, EVEN)].desc = BDT_DESC(EP0_SIZE, 1);
425                 //table[index(0, RX, ODD)].desc = BDT_DESC(EP0_SIZE, 1);
426
427                 // clear any leftover pending IN transactions
428                 ep0_tx_ptr = NULL;
429                 if (ep0_tx_data_toggle) {
430                 }
431                 //if (table[index(0, TX, EVEN)].desc & 0x80) {
432                         //serial_print("leftover tx even\n");
433                 //}
434                 //if (table[index(0, TX, ODD)].desc & 0x80) {
435                         //serial_print("leftover tx odd\n");
436                 //}
437                 table[index(0, TX, EVEN)].desc = 0;
438                 table[index(0, TX, ODD)].desc = 0;
439                 // first IN after Setup is always DATA1
440                 ep0_tx_data_toggle = 1;
441
442 #if 0
443                 serial_print("bmRequestType:");
444                 serial_phex(setup.bmRequestType);
445                 serial_print(", bRequest:");
446                 serial_phex(setup.bRequest);
447                 serial_print(", wValue:");
448                 serial_phex16(setup.wValue);
449                 serial_print(", wIndex:");
450                 serial_phex16(setup.wIndex);
451                 serial_print(", len:");
452                 serial_phex16(setup.wLength);
453                 serial_print("\n");
454 #endif
455                 // actually "do" the setup request
456                 usb_setup();
457                 // unfreeze the USB, now that we're ready
458                 USB0_CTL = USB_CTL_USBENSOFEN; // clear TXSUSPENDTOKENBUSY bit
459                 break;
460         case 0x01:  // OUT transaction received from host
461         case 0x02:
462                 //serial_print("PID=OUT\n");
463 #ifdef CDC_STATUS_INTERFACE
464                 if (setup.wRequestAndType == 0x2021 /*CDC_SET_LINE_CODING*/) {
465                         int i;
466                         uint8_t *dst = (uint8_t *)usb_cdc_line_coding;
467                         //serial_print("set line coding ");
468                         for (i=0; i<7; i++) {
469                                 //serial_phex(*buf);
470                                 *dst++ = *buf++;
471                         }
472                         //serial_phex32(usb_cdc_line_coding[0]);
473                         //serial_print("\n");
474                         if (usb_cdc_line_coding[0] == 134) usb_reboot_timer = 15;
475                         endpoint0_transmit(NULL, 0);
476                 }
477 #endif
478 #ifdef KEYBOARD_INTERFACE
479                 if (setup.word1 == 0x02000921 && setup.word2 == ((1<<16)|KEYBOARD_INTERFACE)) {
480                         USBKeys_LEDs = buf[0];
481                         endpoint0_transmit(NULL, 0);
482                 }
483 #endif
484                 // give the buffer back
485                 b->desc = BDT_DESC(EP0_SIZE, DATA1);
486                 break;
487
488         case 0x09: // IN transaction completed to host
489                 //serial_print("PID=IN:");
490                 //serial_phex(stat);
491                 //serial_print("\n");
492
493                 // send remaining data, if any...
494                 data = ep0_tx_ptr;
495                 if (data) {
496                         size = ep0_tx_len;
497                         if (size > EP0_SIZE) size = EP0_SIZE;
498                         endpoint0_transmit(data, size);
499                         data += size;
500                         ep0_tx_len -= size;
501                         ep0_tx_ptr = (ep0_tx_len > 0 || size == EP0_SIZE) ? data : NULL;
502                 }
503
504                 if (setup.bRequest == 5 && setup.bmRequestType == 0) {
505                         setup.bRequest = 0;
506                         //serial_print("set address: ");
507                         //serial_phex16(setup.wValue);
508                         //serial_print("\n");
509                         USB0_ADDR = setup.wValue;
510                 }
511
512                 break;
513         //default:
514                 //serial_print("PID=unknown:");
515                 //serial_phex(pid);
516                 //serial_print("\n");
517         }
518         USB0_CTL = USB_CTL_USBENSOFEN; // clear TXSUSPENDTOKENBUSY bit
519 }
520
521
522
523 static usb_packet_t *rx_first[NUM_ENDPOINTS];
524 static usb_packet_t *rx_last[NUM_ENDPOINTS];
525 static usb_packet_t *tx_first[NUM_ENDPOINTS];
526 static usb_packet_t *tx_last[NUM_ENDPOINTS];
527
528 static uint8_t tx_state[NUM_ENDPOINTS];
529 #define TX_STATE_BOTH_FREE_EVEN_FIRST   0
530 #define TX_STATE_BOTH_FREE_ODD_FIRST    1
531 #define TX_STATE_EVEN_FREE              2
532 #define TX_STATE_ODD_FREE               3
533 #define TX_STATE_NONE_FREE              4
534
535
536
537 usb_packet_t *usb_rx(uint32_t endpoint)
538 {
539         //print("USB RX");
540         usb_packet_t *ret;
541         endpoint--;
542         if (endpoint >= NUM_ENDPOINTS) return NULL;
543         __disable_irq();
544         ret = rx_first[endpoint];
545         if (ret) rx_first[endpoint] = ret->next;
546         usb_rx_byte_count_data[endpoint] -= ret->len;
547         __enable_irq();
548         //serial_print("rx, epidx=");
549         //serial_phex(endpoint);
550         //serial_print(", packet=");
551         //serial_phex32(ret);
552         //serial_print("\n");
553         return ret;
554 }
555
556 static uint32_t usb_queue_byte_count(const usb_packet_t *p)
557 {
558         uint32_t count=0;
559
560         __disable_irq();
561         for ( ; p; p = p->next) {
562                 count += p->len;
563         }
564         __enable_irq();
565         return count;
566 }
567
568 uint32_t usb_tx_byte_count(uint32_t endpoint)
569 {
570         endpoint--;
571         if (endpoint >= NUM_ENDPOINTS) return 0;
572         return usb_queue_byte_count(tx_first[endpoint]);
573 }
574
575 uint32_t usb_tx_packet_count(uint32_t endpoint)
576 {
577         const usb_packet_t *p;
578         uint32_t count=0;
579
580         endpoint--;
581         if (endpoint >= NUM_ENDPOINTS) return 0;
582         __disable_irq();
583         for (p = tx_first[endpoint]; p; p = p->next) count++;
584         __enable_irq();
585         return count;
586 }
587
588
589 // Called from usb_free, but only when usb_rx_memory_needed > 0, indicating
590 // receive endpoints are starving for memory.  The intention is to give
591 // endpoints needing receive memory priority over the user's code, which is
592 // likely calling usb_malloc to obtain memory for transmitting.  When the
593 // user is creating data very quickly, their consumption could starve reception
594 // without this prioritization.  The packet buffer (input) is assigned to the
595 // first endpoint needing memory.
596 //
597 void usb_rx_memory(usb_packet_t *packet)
598 {
599         //print("USB RX MEMORY");
600         unsigned int i;
601         const uint8_t *cfg;
602
603         cfg = usb_endpoint_config_table;
604         //serial_print("rx_mem:");
605         __disable_irq();
606         for (i=1; i <= NUM_ENDPOINTS; i++) {
607                 if (*cfg++ & USB_ENDPT_EPRXEN) {
608                         if (table[index(i, RX, EVEN)].desc == 0) {
609                                 table[index(i, RX, EVEN)].addr = packet->buf;
610                                 table[index(i, RX, EVEN)].desc = BDT_DESC(64, 0);
611                                 usb_rx_memory_needed--;
612                                 __enable_irq();
613                                 //serial_phex(i);
614                                 //serial_print(",even\n");
615                                 return;
616                         }
617                         if (table[index(i, RX, ODD)].desc == 0) {
618                                 table[index(i, RX, ODD)].addr = packet->buf;
619                                 table[index(i, RX, ODD)].desc = BDT_DESC(64, 1);
620                                 usb_rx_memory_needed--;
621                                 __enable_irq();
622                                 //serial_phex(i);
623                                 //serial_print(",odd\n");
624                                 return;
625                         }
626                 }
627         }
628         __enable_irq();
629         // we should never reach this point.  If we get here, it means
630         // usb_rx_memory_needed was set greater than zero, but no memory
631         // was actually needed.
632         usb_rx_memory_needed = 0;
633         usb_free(packet);
634         return;
635 }
636
637 //#define index(endpoint, tx, odd) (((endpoint) << 2) | ((tx) << 1) | (odd))
638 //#define stat2bufferdescriptor(stat) (table + ((stat) >> 2))
639
640 void usb_tx(uint32_t endpoint, usb_packet_t *packet)
641 {
642         bdt_t *b = &table[index(endpoint, TX, EVEN)];
643         uint8_t next;
644
645         endpoint--;
646         if (endpoint >= NUM_ENDPOINTS) return;
647         __disable_irq();
648         //serial_print("txstate=");
649         //serial_phex(tx_state[endpoint]);
650         //serial_print("\n");
651         switch (tx_state[endpoint]) {
652           case TX_STATE_BOTH_FREE_EVEN_FIRST:
653                 next = TX_STATE_ODD_FREE;
654                 break;
655           case TX_STATE_BOTH_FREE_ODD_FIRST:
656                 b++;
657                 next = TX_STATE_EVEN_FREE;
658                 break;
659           case TX_STATE_EVEN_FREE:
660                 next = TX_STATE_NONE_FREE_ODD_FIRST;
661                 break;
662           case TX_STATE_ODD_FREE:
663                 b++;
664                 next = TX_STATE_NONE_FREE_EVEN_FIRST;
665                 break;
666           default:
667                 if (tx_first[endpoint] == NULL) {
668                         tx_first[endpoint] = packet;
669                 } else {
670                         tx_last[endpoint]->next = packet;
671                 }
672                 tx_last[endpoint] = packet;
673                 __enable_irq();
674                 return;
675         }
676         tx_state[endpoint] = next;
677         b->addr = packet->buf;
678         b->desc = BDT_DESC(packet->len, ((uint32_t)b & 8) ? DATA1 : DATA0);
679         __enable_irq();
680 }
681
682
683 void usb_device_reload()
684 {
685 // MCHCK
686 #if defined(_mk20dx128vlf5_)
687         // This line must be exactly the same in the bootloader
688         const uint8_t sys_reset_to_loader_magic[] = "\xff\x00\x7fRESET TO LOADER\x7f\x00\xff";
689         for ( int pos = 0; pos < sizeof(sys_reset_to_loader_magic); pos++ )(&VBAT)[pos] = sys_reset_to_loader_magic[ pos ];
690
691         SOFTWARE_RESET();
692 // Teensy 3.0 and 3.1
693 #else
694         asm volatile("bkpt");
695 #endif
696 }
697
698
699 void usb_isr()
700 {
701         uint8_t status, stat, t;
702
703         //serial_print("isr");
704         //status = USB0_ISTAT;
705         //serial_phex(status);
706         //serial_print("\n");
707         restart:
708         status = USB0_ISTAT;
709         /*
710         print("USB ISR STATUS: ");
711         printHex( status );
712         print( NL );
713         */
714
715         if ((status & USB_INTEN_SOFTOKEN /* 04 */ )) {
716                 if (usb_configuration) {
717                         t = usb_reboot_timer;
718                         if (t) {
719                                 usb_reboot_timer = --t;
720                                 if (!t) usb_device_reload();
721                         }
722 #ifdef CDC_DATA_INTERFACE
723                         t = usb_cdc_transmit_flush_timer;
724                         if (t) {
725                                 usb_cdc_transmit_flush_timer = --t;
726                                 if (t == 0) usb_serial_flush_callback();
727                         }
728 #endif
729                 }
730                 USB0_ISTAT = USB_INTEN_SOFTOKEN;
731         }
732
733         if ((status & USB_ISTAT_TOKDNE /* 08 */ )) {
734                 uint8_t endpoint;
735                 stat = USB0_STAT;
736                 //serial_print("token: ep=");
737                 //serial_phex(stat >> 4);
738                 //serial_print(stat & 0x08 ? ",tx" : ",rx");
739                 //serial_print(stat & 0x04 ? ",odd\n" : ",even\n");
740                 endpoint = stat >> 4;
741                 if (endpoint == 0) {
742                         usb_control(stat);
743                 } else {
744                         bdt_t *b = stat2bufferdescriptor(stat);
745                         usb_packet_t *packet = (usb_packet_t *)((uint8_t *)(b->addr) - 8);
746 #if 0
747                         serial_print("ep:");
748                         serial_phex(endpoint);
749                         serial_print(", pid:");
750                         serial_phex(BDT_PID(b->desc));
751                         serial_print(((uint32_t)b & 8) ? ", odd" : ", even");
752                         serial_print(", count:");
753                         serial_phex(b->desc >> 16);
754                         serial_print("\n");
755 #endif
756                         endpoint--;     // endpoint is index to zero-based arrays
757
758                         if (stat & 0x08) { // transmit
759                                 usb_free(packet);
760                                 packet = tx_first[endpoint];
761                                 if (packet) {
762                                         //serial_print("tx packet\n");
763                                         tx_first[endpoint] = packet->next;
764                                         b->addr = packet->buf;
765                                         switch (tx_state[endpoint]) {
766                                           case TX_STATE_BOTH_FREE_EVEN_FIRST:
767                                                 tx_state[endpoint] = TX_STATE_ODD_FREE;
768                                                 break;
769                                           case TX_STATE_BOTH_FREE_ODD_FIRST:
770                                                 tx_state[endpoint] = TX_STATE_EVEN_FREE;
771                                                 break;
772                                           case TX_STATE_EVEN_FREE:
773                                                 tx_state[endpoint] = TX_STATE_NONE_FREE_ODD_FIRST;
774                                                 break;
775                                           case TX_STATE_ODD_FREE:
776                                                 tx_state[endpoint] = TX_STATE_NONE_FREE_EVEN_FIRST;
777                                                 break;
778                                           default:
779                                                 break;
780                                         }
781                                         b->desc = BDT_DESC(packet->len, ((uint32_t)b & 8) ? DATA1 : DATA0);
782                                 } else {
783                                         //serial_print("tx no packet\n");
784                                         switch (tx_state[endpoint]) {
785                                           case TX_STATE_BOTH_FREE_EVEN_FIRST:
786                                           case TX_STATE_BOTH_FREE_ODD_FIRST:
787                                                 break;
788                                           case TX_STATE_EVEN_FREE:
789                                                 tx_state[endpoint] = TX_STATE_BOTH_FREE_EVEN_FIRST;
790                                                 break;
791                                           case TX_STATE_ODD_FREE:
792                                                 tx_state[endpoint] = TX_STATE_BOTH_FREE_ODD_FIRST;
793                                                 break;
794                                           default:
795                                                 tx_state[endpoint] = ((uint32_t)b & 8) ?
796                                                   TX_STATE_ODD_FREE : TX_STATE_EVEN_FREE;
797                                                 break;
798                                         }
799                                 }
800                         } else { // receive
801                                 packet->len = b->desc >> 16;
802                                 if (packet->len > 0) {
803                                         packet->index = 0;
804                                         packet->next = NULL;
805                                         if (rx_first[endpoint] == NULL) {
806                                                 //serial_print("rx 1st, epidx=");
807                                                 //serial_phex(endpoint);
808                                                 //serial_print(", packet=");
809                                                 //serial_phex32((uint32_t)packet);
810                                                 //serial_print("\n");
811                                                 rx_first[endpoint] = packet;
812                                         } else {
813                                                 //serial_print("rx Nth, epidx=");
814                                                 //serial_phex(endpoint);
815                                                 //serial_print(", packet=");
816                                                 //serial_phex32((uint32_t)packet);
817                                                 //serial_print("\n");
818                                                 rx_last[endpoint]->next = packet;
819                                         }
820                                         rx_last[endpoint] = packet;
821                                         usb_rx_byte_count_data[endpoint] += packet->len;
822                                         // TODO: implement a per-endpoint maximum # of allocated packets
823                                         // so a flood of incoming data on 1 endpoint doesn't starve
824                                         // the others if the user isn't reading it regularly
825                                         packet = usb_malloc();
826                                         if (packet) {
827                                                 b->addr = packet->buf;
828                                                 b->desc = BDT_DESC(64, ((uint32_t)b & 8) ? DATA1 : DATA0);
829                                         } else {
830                                                 //serial_print("starving ");
831                                                 //serial_phex(endpoint + 1);
832                                                 //serial_print(((uint32_t)b & 8) ? ",odd\n" : ",even\n");
833                                                 b->desc = 0;
834                                                 usb_rx_memory_needed++;
835                                         }
836                                 } else {
837                                         b->desc = BDT_DESC(64, ((uint32_t)b & 8) ? DATA1 : DATA0);
838                                 }
839                         }
840
841
842
843
844                 }
845                 USB0_ISTAT = USB_ISTAT_TOKDNE;
846                 goto restart;
847         }
848
849
850
851         if (status & USB_ISTAT_USBRST /* 01 */ ) {
852                 //serial_print("reset\n");
853
854                 // initialize BDT toggle bits
855                 USB0_CTL = USB_CTL_ODDRST;
856                 ep0_tx_bdt_bank = 0;
857
858                 // set up buffers to receive Setup and OUT packets
859                 table[index(0, RX, EVEN)].desc = BDT_DESC(EP0_SIZE, 0);
860                 table[index(0, RX, EVEN)].addr = ep0_rx0_buf;
861                 table[index(0, RX, ODD)].desc = BDT_DESC(EP0_SIZE, 0);
862                 table[index(0, RX, ODD)].addr = ep0_rx1_buf;
863                 table[index(0, TX, EVEN)].desc = 0;
864                 table[index(0, TX, ODD)].desc = 0;
865
866                 // activate endpoint 0
867                 USB0_ENDPT0 = USB_ENDPT_EPRXEN | USB_ENDPT_EPTXEN | USB_ENDPT_EPHSHK;
868
869                 // clear all ending interrupts
870                 USB0_ERRSTAT = 0xFF;
871                 USB0_ISTAT = 0xFF;
872
873                 // set the address to zero during enumeration
874                 USB0_ADDR = 0;
875
876                 // enable other interrupts
877                 USB0_ERREN = 0xFF;
878                 USB0_INTEN = USB_INTEN_TOKDNEEN |
879                         USB_INTEN_SOFTOKEN |
880                         USB_INTEN_STALLEN |
881                         USB_INTEN_ERROREN |
882                         USB_INTEN_USBRSTEN |
883                         USB_INTEN_SLEEPEN;
884
885                 // is this necessary?
886                 USB0_CTL = USB_CTL_USBENSOFEN;
887                 return;
888         }
889
890
891         if ((status & USB_ISTAT_STALL /* 80 */ )) {
892                 //serial_print("stall:\n");
893                 USB0_ENDPT0 = USB_ENDPT_EPRXEN | USB_ENDPT_EPTXEN | USB_ENDPT_EPHSHK;
894                 USB0_ISTAT = USB_ISTAT_STALL;
895         }
896         if ((status & USB_ISTAT_ERROR /* 02 */ )) {
897                 uint8_t err = USB0_ERRSTAT;
898                 USB0_ERRSTAT = err;
899                 //serial_print("err:");
900                 //serial_phex(err);
901                 //serial_print("\n");
902                 USB0_ISTAT = USB_ISTAT_ERROR;
903         }
904
905         if ((status & USB_ISTAT_SLEEP /* 10 */ )) {
906                 //serial_print("sleep\n");
907                 USB0_ISTAT = USB_ISTAT_SLEEP;
908         }
909
910 }
911
912
913
914 void usb_init()
915 {
916         //print("USB INIT");
917
918         // Clear out endpoints table
919         for ( int i = 0; i <= NUM_ENDPOINTS * 4; i++ )
920         {
921                 table[i].desc = 0;
922                 table[i].addr = 0;
923         }
924
925         // this basically follows the flowchart in the Kinetis
926         // Quick Reference User Guide, Rev. 1, 03/2012, page 141
927
928         // assume 48 MHz clock already running
929         // SIM - enable clock
930         SIM_SCGC4 |= SIM_SCGC4_USBOTG;
931
932         // reset USB module
933         USB0_USBTRC0 = USB_USBTRC_USBRESET;
934         while ( (USB0_USBTRC0 & USB_USBTRC_USBRESET) != 0 ); // wait for reset to end
935
936         // set desc table base addr
937         USB0_BDTPAGE1 = ((uint32_t)table) >> 8;
938         USB0_BDTPAGE2 = ((uint32_t)table) >> 16;
939         USB0_BDTPAGE3 = ((uint32_t)table) >> 24;
940
941         // clear all ISR flags
942         USB0_ISTAT = 0xFF;
943         USB0_ERRSTAT = 0xFF;
944         USB0_OTGISTAT = 0xFF;
945
946         USB0_USBTRC0 |= 0x40; // undocumented bit
947
948         // enable USB
949         USB0_CTL = USB_CTL_USBENSOFEN;
950         USB0_USBCTRL = 0;
951
952         // enable reset interrupt
953         USB0_INTEN = USB_INTEN_USBRSTEN;
954
955         // enable interrupt in NVIC...
956         NVIC_SET_PRIORITY( IRQ_USBOTG, 112 );
957         NVIC_ENABLE_IRQ( IRQ_USBOTG );
958
959         // enable d+ pullup
960         USB0_CONTROL = USB_CONTROL_DPPULLUPNONOTG;
961 }
962
963 // return 0 if the USB is not configured, or the configuration
964 // number selected by the HOST
965 uint8_t usb_configured()
966 {
967         return usb_configuration;
968 }
969