]> git.donarmstrong.com Git - kiibohd-controller.git/blob - Output/pjrcUSB/arm/usb_dev.c
More preparation for NKRO USB for arm
[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  * Modifications 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 // ----- Includes -----
33
34 // Project Includes
35 #include <Lib/OutputLib.h>
36 #include <print.h>
37
38 // Local Includes
39 #include "usb_dev.h"
40 #include "usb_mem.h"
41
42
43
44 // ----- Defines -----
45
46 // DEBUG Mode
47 // XXX - Only use when using usbMuxUart Module
48 // Delay causes issues initializing more than 1 hid device (i.e. NKRO keyboard)
49 //#define UART_DEBUG 1
50 // Debug Unknown USB requests, usually what you want to debug USB issues
51 //#define UART_DEBUG_UNKNOWN 1
52
53
54 #define TX_STATE_BOTH_FREE_EVEN_FIRST   0
55 #define TX_STATE_BOTH_FREE_ODD_FIRST    1
56 #define TX_STATE_EVEN_FREE              2
57 #define TX_STATE_ODD_FREE               3
58 #define TX_STATE_NONE_FREE_EVEN_FIRST   4
59 #define TX_STATE_NONE_FREE_ODD_FIRST    5
60
61 #define BDT_OWN         0x80
62 #define BDT_DATA1       0x40
63 #define BDT_DATA0       0x00
64 #define BDT_DTS         0x08
65 #define BDT_STALL       0x04
66
67 #define TX    1
68 #define RX    0
69 #define ODD   1
70 #define EVEN  0
71 #define DATA0 0
72 #define DATA1 1
73
74
75 #define GET_STATUS              0
76 #define CLEAR_FEATURE           1
77 #define SET_FEATURE             3
78 #define SET_ADDRESS             5
79 #define GET_DESCRIPTOR          6
80 #define SET_DESCRIPTOR          7
81 #define GET_CONFIGURATION       8
82 #define SET_CONFIGURATION       9
83 #define GET_INTERFACE           10
84 #define SET_INTERFACE           11
85 #define SYNCH_FRAME             12
86
87 #define TX_STATE_BOTH_FREE_EVEN_FIRST   0
88 #define TX_STATE_BOTH_FREE_ODD_FIRST    1
89 #define TX_STATE_EVEN_FREE              2
90 #define TX_STATE_ODD_FREE               3
91 #define TX_STATE_NONE_FREE              4
92
93
94
95
96
97 // ----- Macros -----
98
99 #define BDT_PID(n)      (((n) >> 2) & 15)
100
101 #define BDT_DESC(count, data)   (BDT_OWN | BDT_DTS \
102                                 | ((data) ? BDT_DATA1 : BDT_DATA0) \
103                                 | ((count) << 16))
104
105 #define index(endpoint, tx, odd) (((endpoint) << 2) | ((tx) << 1) | (odd))
106 #define stat2bufferdescriptor(stat) (table + ((stat) >> 2))
107
108
109
110 // ----- Structs -----
111
112 // buffer descriptor table
113
114 typedef struct {
115         uint32_t desc;
116         void * addr;
117 } bdt_t;
118
119 static union {
120         struct {
121                 union {
122                         struct {
123                                 uint8_t bmRequestType;
124                                 uint8_t bRequest;
125                         };
126                         uint16_t wRequestAndType;
127                 };
128                 uint16_t wValue;
129                 uint16_t wIndex;
130                 uint16_t wLength;
131         };
132         struct {
133                 uint32_t word1;
134                 uint32_t word2;
135         };
136 } setup;
137
138
139
140 // ----- Variables -----
141
142 __attribute__ ((section(".usbdescriptortable"), used))
143 static bdt_t table[ (NUM_ENDPOINTS + 1) * 4 ];
144
145 static usb_packet_t *rx_first  [ NUM_ENDPOINTS ];
146 static usb_packet_t *rx_last   [ NUM_ENDPOINTS ];
147 static usb_packet_t *tx_first  [ NUM_ENDPOINTS ];
148 static usb_packet_t *tx_last   [ NUM_ENDPOINTS ];
149 uint16_t usb_rx_byte_count_data[ NUM_ENDPOINTS ];
150
151 static uint8_t tx_state[NUM_ENDPOINTS];
152
153 // SETUP always uses a DATA0 PID for the data field of the SETUP transaction.
154 // transactions in the data phase start with DATA1 and toggle (figure 8-12, USB1.1)
155 // Status stage uses a DATA1 PID.
156
157 static uint8_t ep0_rx0_buf[EP0_SIZE] __attribute__ ((aligned (4)));
158 static uint8_t ep0_rx1_buf[EP0_SIZE] __attribute__ ((aligned (4)));
159 static const uint8_t *ep0_tx_ptr = NULL;
160 static uint16_t ep0_tx_len;
161 static uint8_t ep0_tx_bdt_bank = 0;
162 static uint8_t ep0_tx_data_toggle = 0;
163 uint8_t usb_rx_memory_needed = 0;
164
165 volatile uint8_t usb_configuration = 0;
166 volatile uint8_t usb_reboot_timer = 0;
167
168 static uint8_t reply_buffer[8];
169
170
171
172 // ----- Functions -----
173
174 static void endpoint0_stall()
175 {
176         USB0_ENDPT0 = USB_ENDPT_EPSTALL | USB_ENDPT_EPRXEN | USB_ENDPT_EPTXEN | USB_ENDPT_EPHSHK;
177 }
178
179 static void endpoint0_transmit( const void *data, uint32_t len )
180 {
181         table[index(0, TX, ep0_tx_bdt_bank)].addr = (void *)data;
182         table[index(0, TX, ep0_tx_bdt_bank)].desc = BDT_DESC(len, ep0_tx_data_toggle);
183         ep0_tx_data_toggle ^= 1;
184         ep0_tx_bdt_bank ^= 1;
185 }
186
187 static void usb_setup()
188 {
189         const uint8_t *data = NULL;
190         uint32_t datalen = 0;
191         const usb_descriptor_list_t *list;
192         uint32_t size;
193         volatile uint8_t *reg;
194         uint8_t epconf;
195         const uint8_t *cfg;
196         int i;
197
198         switch ( setup.wRequestAndType )
199         {
200         case 0x0500: // SET_ADDRESS
201                 break;
202         case 0x0900: // SET_CONFIGURATION
203                 #ifdef UART_DEBUG
204                 print("CONFIGURE - ");
205                 #endif
206                 usb_configuration = setup.wValue;
207                 reg = &USB0_ENDPT1;
208                 cfg = usb_endpoint_config_table;
209                 // clear all BDT entries, free any allocated memory...
210                 for ( i = 4; i < ( NUM_ENDPOINTS + 1) * 4; i++ )
211                 {
212                         if ( table[i].desc & BDT_OWN )
213                         {
214                                 usb_free( (usb_packet_t *)((uint8_t *)(table[ i ].addr) - 8) );
215                         }
216                 }
217                 // free all queued packets
218                 for ( i = 0; i < NUM_ENDPOINTS; i++ )
219                 {
220                         usb_packet_t *p, *n;
221                         p = rx_first[i];
222                         while ( p )
223                         {
224                                 n = p->next;
225                                 usb_free(p);
226                                 p = n;
227                         }
228                         rx_first[i] = NULL;
229                         rx_last[i] = NULL;
230                         p = tx_first[i];
231                         while (p)
232                         {
233                                 n = p->next;
234                                 usb_free(p);
235                                 p = n;
236                         }
237                         tx_first[i] = NULL;
238                         tx_last[i] = NULL;
239                         usb_rx_byte_count_data[i] = 0;
240
241                         switch (tx_state[i]) {
242                         case TX_STATE_EVEN_FREE:
243                         case TX_STATE_NONE_FREE_EVEN_FIRST:
244                                 tx_state[i] = TX_STATE_BOTH_FREE_EVEN_FIRST;
245                                 break;
246                         case TX_STATE_ODD_FREE:
247                         case TX_STATE_NONE_FREE_ODD_FIRST:
248                                 tx_state[i] = TX_STATE_BOTH_FREE_ODD_FIRST;
249                                 break;
250                         default:
251                                 break;
252                         }
253                 }
254                 usb_rx_memory_needed = 0;
255                 for ( i = 1; i <= NUM_ENDPOINTS; i++ )
256                 {
257                         epconf = *cfg++;
258                         *reg = epconf;
259                         reg += 4;
260                         if ( epconf & USB_ENDPT_EPRXEN )
261                         {
262                                 usb_packet_t *p;
263                                 p = usb_malloc();
264                                 if ( p )
265                                 {
266                                         table[index(i, RX, EVEN)].addr = p->buf;
267                                         table[index(i, RX, EVEN)].desc = BDT_DESC(64, 0);
268                                 }
269                                 else
270                                 {
271                                         table[index(i, RX, EVEN)].desc = 0;
272                                         usb_rx_memory_needed++;
273                                 }
274                                 p = usb_malloc();
275                                 if ( p )
276                                 {
277                                         table[index(i, RX, ODD)].addr = p->buf;
278                                         table[index(i, RX, ODD)].desc = BDT_DESC(64, 1);
279                                 }
280                                 else
281                                 {
282                                         table[index(i, RX, ODD)].desc = 0;
283                                         usb_rx_memory_needed++;
284                                 }
285                         }
286                         table[index(i, TX, EVEN)].desc = 0;
287                         table[index(i, TX, ODD)].desc = 0;
288                 }
289                 break;
290         case 0x0880: // GET_CONFIGURATION
291                 reply_buffer[0] = usb_configuration;
292                 datalen = 1;
293                 data = reply_buffer;
294                 break;
295         case 0x0080: // GET_STATUS (device)
296                 reply_buffer[0] = 0;
297                 reply_buffer[1] = 0;
298                 datalen = 2;
299                 data = reply_buffer;
300                 break;
301         case 0x0082: // GET_STATUS (endpoint)
302                 if (setup.wIndex > NUM_ENDPOINTS)
303                 {
304                         // TODO: do we need to handle IN vs OUT here?
305                         endpoint0_stall();
306                         return;
307                 }
308                 reply_buffer[0] = 0;
309                 reply_buffer[1] = 0;
310                 if ( *(uint8_t *)(&USB0_ENDPT0 + setup.wIndex * 4) & 0x02 )
311                         reply_buffer[0] = 1;
312                 data = reply_buffer;
313                 datalen = 2;
314                 break;
315         case 0x0102: // CLEAR_FEATURE (endpoint)
316                 i = setup.wIndex & 0x7F;
317                 if ( i > NUM_ENDPOINTS || setup.wValue != 0 )
318                 {
319                         // TODO: do we need to handle IN vs OUT here?
320                         endpoint0_stall();
321                         return;
322                 }
323                 (*(uint8_t *)(&USB0_ENDPT0 + setup.wIndex * 4)) &= ~0x02;
324                 // TODO: do we need to clear the data toggle here?
325                 break;
326         case 0x0302: // SET_FEATURE (endpoint)
327                 i = setup.wIndex & 0x7F;
328                 if ( i > NUM_ENDPOINTS || setup.wValue != 0 )
329                 {
330                         // TODO: do we need to handle IN vs OUT here?
331                         endpoint0_stall();
332                         return;
333                 }
334                 (*(uint8_t *)(&USB0_ENDPT0 + setup.wIndex * 4)) |= 0x02;
335                 // TODO: do we need to clear the data toggle here?
336                 break;
337         case 0x0680: // GET_DESCRIPTOR
338         case 0x0681:
339                 #ifdef UART_DEBUG
340                 print("desc:");
341                 printHex(setup.wValue);
342                 print(NL);
343                 #endif
344                 for ( list = usb_descriptor_list; 1; list++ )
345                 {
346                         if ( list->addr == NULL )
347                                 break;
348                         //if (setup.wValue == list->wValue &&
349                         //(setup.wIndex == list->wIndex) || ((setup.wValue >> 8) == 3)) {
350                         if ( setup.wValue == list->wValue && setup.wIndex == list->wIndex )
351                         {
352                                 data = list->addr;
353                                 if ( (setup.wValue >> 8) == 3 )
354                                 {
355                                         // for string descriptors, use the descriptor's
356                                         // length field, allowing runtime configured
357                                         // length.
358                                         datalen = *(list->addr);
359                                 }
360                                 else
361                                 {
362                                         datalen = list->length;
363                                 }
364                                 #if UART_DEBUG
365                                 print("Desc found, ");
366                                 printHex32((uint32_t)data);
367                                 print(",");
368                                 printHex(datalen);
369                                 print(",");
370                                 printHex_op(data[0], 2);
371                                 printHex_op(data[1], 2);
372                                 printHex_op(data[2], 2);
373                                 printHex_op(data[3], 2);
374                                 printHex_op(data[4], 2);
375                                 printHex_op(data[5], 2);
376                                 print(NL);
377                                 #endif
378                                 goto send;
379                         }
380                 }
381                 #ifdef UART_DEBUG
382                 print("desc: not found"NL);
383                 #endif
384                 endpoint0_stall();
385                 return;
386
387         case 0x2221: // CDC_SET_CONTROL_LINE_STATE
388                 usb_cdc_line_rtsdtr = setup.wValue;
389                 //serial_print("set control line state\n");
390                 endpoint0_stall();
391                 return;
392
393         case 0x21A1: // CDC_GET_LINE_CODING
394                 data = (uint8_t*)usb_cdc_line_coding;
395                 datalen = sizeof( usb_cdc_line_coding );
396                 goto send;
397
398         case 0x2021: // CDC_SET_LINE_CODING
399                 // XXX Needed?
400                 //serial_print("set coding, waiting...\n");
401                 return; // Cannot stall here (causes issues)
402
403         case 0x0921: // HID SET_REPORT
404                 #ifdef UART_DEBUG
405                 print("SET_REPORT - ");
406                 printHex( setup.wValue );
407                 print(" - ");
408                 printHex( setup.wValue & 0xFF );
409                 print(NL);
410                 #endif
411                 USBKeys_LEDs = setup.wValue & 0xFF;
412                 endpoint0_stall();
413                 return;
414
415         case 0x01A1: // HID GET_REPORT
416                 #ifdef UART_DEBUG
417                 print("GET_REPORT - ");
418                 printHex( USBKeys_LEDs );
419                 print(NL);
420                 #endif
421                 data = (uint8_t*)&USBKeys_LEDs;
422                 datalen = 1;
423                 goto send;
424
425         case 0x0A21: // HID SET_IDLE
426                 #ifdef UART_DEBUG
427                 print("SET_IDLE - ");
428                 printHex( setup.wValue );
429                 print(NL);
430                 #endif
431                 USBKeys_Idle_Config = (setup.wValue >> 8);
432                 USBKeys_Idle_Count = 0;
433                 endpoint0_stall();
434                 return;
435
436         case 0x0B21: // HID SET_PROTOCOL
437                 #ifdef UART_DEBUG
438                 print("SET_PROTOCOL - ");
439                 printHex( setup.wValue );
440                 print(" - ");
441                 printHex( setup.wValue & 0xFF );
442                 print(NL);
443                 #endif
444                 USBKeys_Protocol = setup.wValue & 0xFF; // 0 - Boot Mode, 1 - NKRO Mode
445                 endpoint0_stall();
446                 return;
447
448         // case 0xC940:
449         default:
450                 #ifdef UART_DEBUG_UNKNOWN
451                 print("UNKNOWN");
452                 #endif
453                 endpoint0_stall();
454                 return;
455         }
456
457 send:
458         #ifdef UART_DEBUG
459         print("setup send ");
460         printHex32((uint32_t)data);
461         print(",");
462         printHex(datalen);
463         print(NL);
464         #endif
465
466         if ( datalen > setup.wLength )
467                 datalen = setup.wLength;
468
469         size = datalen;
470         if ( size > EP0_SIZE )
471                 size = EP0_SIZE;
472
473         endpoint0_transmit(data, size);
474         data += size;
475         datalen -= size;
476
477         // See if transmit has finished
478         if ( datalen == 0 && size < EP0_SIZE )
479                 return;
480
481         size = datalen;
482         if ( size > EP0_SIZE )
483                 size = EP0_SIZE;
484         endpoint0_transmit(data, size);
485         data += size;
486         datalen -= size;
487
488         // See if transmit has finished
489         if ( datalen == 0 && size < EP0_SIZE )
490                 return;
491
492         // Save rest of transfer for later? XXX
493         ep0_tx_ptr = data;
494         ep0_tx_len = datalen;
495 }
496
497
498 //A bulk endpoint's toggle sequence is initialized to DATA0 when the endpoint
499 //experiences any configuration event (configuration events are explained in
500 //Sections 9.1.1.5 and 9.4.5).
501
502 //Configuring a device or changing an alternate setting causes all of the status
503 //and configuration values associated with endpoints in the affected interfaces
504 //to be set to their default values. This includes setting the data toggle of
505 //any endpoint using data toggles to the value DATA0.
506
507 //For endpoints using data toggle, regardless of whether an endpoint has the
508 //Halt feature set, a ClearFeature(ENDPOINT_HALT) request always results in the
509 //data toggle being reinitialized to DATA0.
510
511 static void usb_control( uint32_t stat )
512 {
513         #ifdef UART_DEBUG
514         print("CONTROL - ");
515         #endif
516         bdt_t *b;
517         uint32_t pid, size;
518         uint8_t *buf;
519         const uint8_t *data;
520
521         b = stat2bufferdescriptor( stat );
522         pid = BDT_PID( b->desc );
523         buf = b->addr;
524         #ifdef UART_DEBUG
525         print("pid:");
526         printHex(pid);
527         print(", count:");
528         printHex32(b->desc);
529         print(" - ");
530         #endif
531
532         switch (pid)
533         {
534         case 0x0D: // Setup received from host
535                 //serial_print("PID=Setup\n");
536                 //if (count != 8) ; // panic?
537                 // grab the 8 byte setup info
538                 setup.word1 = *(uint32_t *)(buf);
539                 setup.word2 = *(uint32_t *)(buf + 4);
540
541                 // give the buffer back
542                 b->desc = BDT_DESC( EP0_SIZE, DATA1 );
543                 //table[index(0, RX, EVEN)].desc = BDT_DESC(EP0_SIZE, 1);
544                 //table[index(0, RX, ODD)].desc = BDT_DESC(EP0_SIZE, 1);
545
546                 // clear any leftover pending IN transactions
547                 ep0_tx_ptr = NULL;
548                 if ( ep0_tx_data_toggle )
549                 {
550                 }
551                 //if (table[index(0, TX, EVEN)].desc & 0x80) {
552                         //serial_print("leftover tx even\n");
553                 //}
554                 //if (table[index(0, TX, ODD)].desc & 0x80) {
555                         //serial_print("leftover tx odd\n");
556                 //}
557                 table[index(0, TX, EVEN)].desc = 0;
558                 table[index(0, TX, ODD)].desc = 0;
559                 // first IN after Setup is always DATA1
560                 ep0_tx_data_toggle = 1;
561
562                 #ifdef UART_DEBUG_UNKNOWN
563                 print("bmRequestType:");
564                 printHex(setup.bmRequestType);
565                 print(", bRequest:");
566                 printHex(setup.bRequest);
567                 print(", wValue:");
568                 printHex(setup.wValue);
569                 print(", wIndex:");
570                 printHex(setup.wIndex);
571                 print(", len:");
572                 printHex(setup.wLength);
573                 print(NL);
574                 #endif
575                 // actually "do" the setup request
576                 usb_setup();
577                 // unfreeze the USB, now that we're ready
578                 USB0_CTL = USB_CTL_USBENSOFEN; // clear TXSUSPENDTOKENBUSY bit
579                 break;
580         case 0x01:  // OUT transaction received from host
581         case 0x02:
582                 #ifdef UART_DEBUG
583                 print("PID=OUT"NL);
584                 #endif
585                 // CDC Interface
586                 if ( setup.wRequestAndType == 0x2021 /*CDC_SET_LINE_CODING*/ )
587                 {
588                         int i;
589                         uint8_t *dst = (uint8_t *)usb_cdc_line_coding;
590                         //serial_print("set line coding ");
591                         for ( i = 0; i < 7; i++ )
592                         {
593                                 //serial_phex(*buf);
594                                 *dst++ = *buf++;
595                         }
596                         //serial_phex32(usb_cdc_line_coding[0]);
597                         //serial_print("\n");
598                         if ( usb_cdc_line_coding[0] == 134 )
599                                 usb_reboot_timer = 15;
600                         endpoint0_transmit( NULL, 0 );
601                 }
602
603                 // Keyboard Interface
604                 if ( setup.word1 == 0x02000921 && setup.word2 == ( (1<<16) | KEYBOARD_INTERFACE ) )
605                 {
606                         USBKeys_LEDs = buf[0];
607                         endpoint0_transmit( NULL, 0 );
608                 }
609                 // NKRO Keyboard Interface
610                 if ( setup.word1 == 0x02000921 && setup.word2 == ( (1<<16) | NKRO_KEYBOARD_INTERFACE ) )
611                 {
612                         USBKeys_LEDs = buf[0];
613                         endpoint0_transmit( NULL, 0 );
614                 }
615
616                 // give the buffer back
617                 b->desc = BDT_DESC( EP0_SIZE, DATA1 );
618                 break;
619
620         case 0x09: // IN transaction completed to host
621                 #ifdef UART_DEBUG
622                 print("PID=IN:");
623                 printHex(stat);
624                 print(NL);
625                 #endif
626
627                 // send remaining data, if any...
628                 data = ep0_tx_ptr;
629                 if ( data )
630                 {
631                         size = ep0_tx_len;
632                         if (size > EP0_SIZE) size = EP0_SIZE;
633                         endpoint0_transmit(data, size);
634                         data += size;
635                         ep0_tx_len -= size;
636                         ep0_tx_ptr = (ep0_tx_len > 0 || size == EP0_SIZE) ? data : NULL;
637                 }
638
639                 if ( setup.bRequest == 5 && setup.bmRequestType == 0 )
640                 {
641                         setup.bRequest = 0;
642                         #ifdef UART_DEBUG
643                         print("set address: ");
644                         printHex(setup.wValue);
645                         print(NL);
646                         #endif
647                         USB0_ADDR = setup.wValue;
648                 }
649
650                 break;
651         default:
652                 #ifdef UART_DEBUG
653                 print("PID=unknown:");
654                 printHex(pid);
655                 print(NL);
656                 #endif
657                 break;
658         }
659         USB0_CTL = USB_CTL_USBENSOFEN; // clear TXSUSPENDTOKENBUSY bit
660 }
661
662 usb_packet_t *usb_rx( uint32_t endpoint )
663 {
664         //print("USB RX");
665         usb_packet_t *ret;
666         endpoint--;
667         if ( endpoint >= NUM_ENDPOINTS )
668                 return NULL;
669         __disable_irq();
670         ret = rx_first[endpoint];
671         if ( ret )
672                 rx_first[ endpoint ] = ret->next;
673         usb_rx_byte_count_data[ endpoint ] -= ret->len;
674         __enable_irq();
675         //serial_print("rx, epidx=");
676         //serial_phex(endpoint);
677         //serial_print(", packet=");
678         //serial_phex32(ret);
679         //serial_print("\n");
680         return ret;
681 }
682
683 static uint32_t usb_queue_byte_count( const usb_packet_t *p )
684 {
685         uint32_t count=0;
686
687         __disable_irq();
688         for ( ; p; p = p->next )
689         {
690                 count += p->len;
691         }
692         __enable_irq();
693         return count;
694 }
695
696 uint32_t usb_tx_byte_count( uint32_t endpoint )
697 {
698         endpoint--;
699         if ( endpoint >= NUM_ENDPOINTS )
700                 return 0;
701         return usb_queue_byte_count( tx_first[ endpoint ] );
702 }
703
704 uint32_t usb_tx_packet_count( uint32_t endpoint )
705 {
706         const usb_packet_t *p;
707         uint32_t count=0;
708
709         endpoint--;
710         if ( endpoint >= NUM_ENDPOINTS )
711                 return 0;
712         __disable_irq();
713         for ( p = tx_first[ endpoint ]; p; p = p->next )
714                 count++;
715         __enable_irq();
716         return count;
717 }
718
719
720 // Called from usb_free, but only when usb_rx_memory_needed > 0, indicating
721 // receive endpoints are starving for memory.  The intention is to give
722 // endpoints needing receive memory priority over the user's code, which is
723 // likely calling usb_malloc to obtain memory for transmitting.  When the
724 // user is creating data very quickly, their consumption could starve reception
725 // without this prioritization.  The packet buffer (input) is assigned to the
726 // first endpoint needing memory.
727 //
728 void usb_rx_memory( usb_packet_t *packet )
729 {
730         //print("USB RX MEMORY");
731         unsigned int i;
732         const uint8_t *cfg;
733
734         cfg = usb_endpoint_config_table;
735         //serial_print("rx_mem:");
736         __disable_irq();
737         for (i=1; i <= NUM_ENDPOINTS; i++) {
738                 if (*cfg++ & USB_ENDPT_EPRXEN) {
739                         if ( table[ index( i, RX, EVEN ) ].desc == 0 )
740                         {
741                                 table[index(i, RX, EVEN)].addr = packet->buf;
742                                 table[index(i, RX, EVEN)].desc = BDT_DESC( 64, 0 );
743                                 usb_rx_memory_needed--;
744                                 __enable_irq();
745                                 //serial_phex(i);
746                                 //serial_print(",even\n");
747                                 return;
748                         }
749                         if ( table[ index( i, RX, ODD ) ].desc == 0 )
750                         {
751                                 table[ index( i, RX, ODD ) ].addr = packet->buf;
752                                 table[ index( i, RX, ODD ) ].desc = BDT_DESC( 64, 1 );
753                                 usb_rx_memory_needed--;
754                                 __enable_irq();
755                                 //serial_phex(i);
756                                 //serial_print(",odd\n");
757                                 return;
758                         }
759                 }
760         }
761         __enable_irq();
762         // we should never reach this point.  If we get here, it means
763         // usb_rx_memory_needed was set greater than zero, but no memory
764         // was actually needed.
765         usb_rx_memory_needed = 0;
766         usb_free( packet );
767         return;
768 }
769
770 //#define index(endpoint, tx, odd) (((endpoint) << 2) | ((tx) << 1) | (odd))
771 //#define stat2bufferdescriptor(stat) (table + ((stat) >> 2))
772
773 void usb_tx( uint32_t endpoint, usb_packet_t *packet )
774 {
775         bdt_t *b = &table[ index( endpoint, TX, EVEN ) ];
776         uint8_t next;
777
778         endpoint--;
779         if ( endpoint >= NUM_ENDPOINTS )
780                 return;
781         __disable_irq();
782         //serial_print("txstate=");
783         //serial_phex(tx_state[ endpoint ]);
784         //serial_print("\n");
785         switch ( tx_state[ endpoint ] )
786         {
787         case TX_STATE_BOTH_FREE_EVEN_FIRST:
788                 next = TX_STATE_ODD_FREE;
789                 break;
790         case TX_STATE_BOTH_FREE_ODD_FIRST:
791                 b++;
792                 next = TX_STATE_EVEN_FREE;
793                 break;
794         case TX_STATE_EVEN_FREE:
795                 next = TX_STATE_NONE_FREE_ODD_FIRST;
796                 break;
797         case TX_STATE_ODD_FREE:
798                 b++;
799                 next = TX_STATE_NONE_FREE_EVEN_FIRST;
800                 break;
801         default:
802                 if (tx_first[ endpoint ] == NULL)
803                 {
804                         tx_first[ endpoint ] = packet;
805                 }
806                 else
807                 {
808                         tx_last[ endpoint ]->next = packet;
809                 }
810                 tx_last[ endpoint ] = packet;
811                 __enable_irq();
812                 return;
813         }
814
815         tx_state[ endpoint ] = next;
816         b->addr = packet->buf;
817         b->desc = BDT_DESC( packet->len, ((uint32_t)b & 8) ? DATA1 : DATA0 );
818         __enable_irq();
819 }
820
821
822 void usb_device_reload()
823 {
824 // MCHCK
825 #if defined(_mk20dx128vlf5_)
826
827         // MCHCK Kiibohd Variant
828         // Check to see if PTA3 (has a pull-up) is connected to GND (usually via jumper)
829         // Only allow reload if the jumper is present (security)
830         GPIOA_PDDR &= ~(1<<3); // Input
831         PORTA_PCR3 = PORT_PCR_PFE | PORT_PCR_MUX(1); // Internal pull-up
832
833         // Check for jumper
834         if ( GPIOA_PDIR & (1<<3) )
835         {
836                 print( NL );
837                 warn_print("Security jumper not present, cancelling firmware reload...");
838                 info_msg("Replace jumper on middle 2 pins, or manually press the firmware reload button.");
839         }
840         else
841         {
842                 // Copies variable into the VBAT register, must be identical to the variable in the bootloader to jump to the bootloader flash mode
843                 for ( int pos = 0; pos < sizeof(sys_reset_to_loader_magic); pos++ )
844                         (&VBAT)[ pos ] = sys_reset_to_loader_magic[ pos ];
845                 SOFTWARE_RESET();
846         }
847
848 // Teensy 3.0 and 3.1
849 #else
850         asm volatile("bkpt");
851 #endif
852 }
853
854
855 void usb_isr()
856 {
857         uint8_t status, stat, t;
858
859         //serial_print("isr");
860         //status = USB0_ISTAT;
861         //serial_phex(status);
862         //serial_print("\n");
863         restart:
864         status = USB0_ISTAT;
865         /*
866         print("USB ISR STATUS: ");
867         printHex( status );
868         print( NL );
869         */
870
871         if ( (status & USB_INTEN_SOFTOKEN /* 04 */ ) )
872         {
873                 if ( usb_configuration )
874                 {
875                         t = usb_reboot_timer;
876                         if ( t )
877                         {
878                                 usb_reboot_timer = --t;
879                                 if ( !t )
880                                         usb_device_reload();
881                         }
882
883                         // CDC Interface
884                         t = usb_cdc_transmit_flush_timer;
885                         if ( t )
886                         {
887                                 usb_cdc_transmit_flush_timer = --t;
888                                 if ( t == 0 )
889                                         usb_serial_flush_callback();
890                         }
891
892                 }
893                 USB0_ISTAT = USB_INTEN_SOFTOKEN;
894         }
895
896         if ( (status & USB_ISTAT_TOKDNE /* 08 */ ) )
897         {
898                 uint8_t endpoint;
899                 stat = USB0_STAT;
900                 //serial_print("token: ep=");
901                 //serial_phex(stat >> 4);
902                 //serial_print(stat & 0x08 ? ",tx" : ",rx");
903                 //serial_print(stat & 0x04 ? ",odd\n" : ",even\n");
904                 endpoint = stat >> 4;
905                 if ( endpoint == 0 )
906                 {
907                         usb_control( stat );
908                 }
909                 else
910                 {
911                         bdt_t *b = stat2bufferdescriptor(stat);
912                         usb_packet_t *packet = (usb_packet_t *)((uint8_t *)(b->addr) - 8);
913 #if 0
914                         serial_print("ep:");
915                         serial_phex(endpoint);
916                         serial_print(", pid:");
917                         serial_phex(BDT_PID(b->desc));
918                         serial_print(((uint32_t)b & 8) ? ", odd" : ", even");
919                         serial_print(", count:");
920                         serial_phex(b->desc >> 16);
921                         serial_print("\n");
922 #endif
923                         endpoint--;     // endpoint is index to zero-based arrays
924
925                         if ( stat & 0x08 )
926                         { // transmit
927                                 usb_free( packet );
928                                 packet = tx_first[endpoint];
929                                 if ( packet )
930                                 {
931                                         //serial_print("tx packet\n");
932                                         tx_first[endpoint] = packet->next;
933                                         b->addr = packet->buf;
934                                         switch ( tx_state[ endpoint ] )
935                                         {
936                                         case TX_STATE_BOTH_FREE_EVEN_FIRST:
937                                                 tx_state[endpoint] = TX_STATE_ODD_FREE;
938                                                 break;
939                                         case TX_STATE_BOTH_FREE_ODD_FIRST:
940                                                 tx_state[endpoint] = TX_STATE_EVEN_FREE;
941                                                 break;
942                                         case TX_STATE_EVEN_FREE:
943                                                 tx_state[endpoint] = TX_STATE_NONE_FREE_ODD_FIRST;
944                                                 break;
945                                         case TX_STATE_ODD_FREE:
946                                                 tx_state[endpoint] = TX_STATE_NONE_FREE_EVEN_FIRST;
947                                                 break;
948                                         default:
949                                                 break;
950                                         }
951                                         b->desc = BDT_DESC(packet->len, ((uint32_t)b & 8) ? DATA1 : DATA0);
952                                 } else {
953                                         //serial_print("tx no packet\n");
954                                         switch ( tx_state[ endpoint ] )
955                                         {
956                                         case TX_STATE_BOTH_FREE_EVEN_FIRST:
957                                         case TX_STATE_BOTH_FREE_ODD_FIRST:
958                                                 break;
959                                         case TX_STATE_EVEN_FREE:
960                                                 tx_state[endpoint] = TX_STATE_BOTH_FREE_EVEN_FIRST;
961                                                 break;
962                                         case TX_STATE_ODD_FREE:
963                                                 tx_state[endpoint] = TX_STATE_BOTH_FREE_ODD_FIRST;
964                                                 break;
965                                         default:
966                                                 tx_state[endpoint] = ((uint32_t)b & 8)
967                                                   ? TX_STATE_ODD_FREE
968                                                   : TX_STATE_EVEN_FREE;
969                                                 break;
970                                         }
971                                 }
972                         }
973                         else
974                         { // receive
975                                 packet->len = b->desc >> 16;
976                                 if (packet->len > 0) {
977                                         packet->index = 0;
978                                         packet->next = NULL;
979                                         if (rx_first[endpoint] == NULL)
980                                         {
981                                                 //serial_print("rx 1st, epidx=");
982                                                 //serial_phex(endpoint);
983                                                 //serial_print(", packet=");
984                                                 //serial_phex32((uint32_t)packet);
985                                                 //serial_print("\n");
986                                                 rx_first[endpoint] = packet;
987                                         }
988                                         else
989                                         {
990                                                 //serial_print("rx Nth, epidx=");
991                                                 //serial_phex(endpoint);
992                                                 //serial_print(", packet=");
993                                                 //serial_phex32((uint32_t)packet);
994                                                 //serial_print("\n");
995                                                 rx_last[endpoint]->next = packet;
996                                         }
997                                         rx_last[endpoint] = packet;
998                                         usb_rx_byte_count_data[endpoint] += packet->len;
999                                         // TODO: implement a per-endpoint maximum # of allocated packets
1000                                         // so a flood of incoming data on 1 endpoint doesn't starve
1001                                         // the others if the user isn't reading it regularly
1002                                         packet = usb_malloc();
1003                                         if ( packet )
1004                                         {
1005                                                 b->addr = packet->buf;
1006                                                 b->desc = BDT_DESC(64, ((uint32_t)b & 8) ? DATA1 : DATA0);
1007                                         }
1008                                         else
1009                                         {
1010                                                 //serial_print("starving ");
1011                                                 //serial_phex(endpoint + 1);
1012                                                 //serial_print(((uint32_t)b & 8) ? ",odd\n" : ",even\n");
1013                                                 b->desc = 0;
1014                                                 usb_rx_memory_needed++;
1015                                         }
1016                                 }
1017                                 else
1018                                 {
1019                                         b->desc = BDT_DESC(64, ((uint32_t)b & 8) ? DATA1 : DATA0);
1020                                 }
1021                         }
1022
1023
1024
1025
1026                 }
1027                 USB0_ISTAT = USB_ISTAT_TOKDNE;
1028                 goto restart;
1029         }
1030
1031
1032         if ( status & USB_ISTAT_USBRST /* 01 */ )
1033         {
1034                 //serial_print("reset\n");
1035
1036                 // initialize BDT toggle bits
1037                 USB0_CTL = USB_CTL_ODDRST;
1038                 ep0_tx_bdt_bank = 0;
1039
1040                 // set up buffers to receive Setup and OUT packets
1041                 table[index(0, RX, EVEN)].desc = BDT_DESC(EP0_SIZE, 0);
1042                 table[index(0, RX, EVEN)].addr = ep0_rx0_buf;
1043                 table[index(0, RX, ODD)].desc = BDT_DESC(EP0_SIZE, 0);
1044                 table[index(0, RX, ODD)].addr = ep0_rx1_buf;
1045                 table[index(0, TX, EVEN)].desc = 0;
1046                 table[index(0, TX, ODD)].desc = 0;
1047
1048                 // activate endpoint 0
1049                 USB0_ENDPT0 = USB_ENDPT_EPRXEN | USB_ENDPT_EPTXEN | USB_ENDPT_EPHSHK;
1050
1051                 // clear all ending interrupts
1052                 USB0_ERRSTAT = 0xFF;
1053                 USB0_ISTAT = 0xFF;
1054
1055                 // set the address to zero during enumeration
1056                 USB0_ADDR = 0;
1057
1058                 // enable other interrupts
1059                 USB0_ERREN = 0xFF;
1060                 USB0_INTEN = USB_INTEN_TOKDNEEN |
1061                         USB_INTEN_SOFTOKEN |
1062                         USB_INTEN_STALLEN |
1063                         USB_INTEN_ERROREN |
1064                         USB_INTEN_USBRSTEN |
1065                         USB_INTEN_SLEEPEN;
1066
1067                 // is this necessary?
1068                 USB0_CTL = USB_CTL_USBENSOFEN;
1069                 return;
1070         }
1071
1072
1073         if ( (status & USB_ISTAT_STALL /* 80 */ ) )
1074         {
1075                 //serial_print("stall:\n");
1076                 USB0_ENDPT0 = USB_ENDPT_EPRXEN | USB_ENDPT_EPTXEN | USB_ENDPT_EPHSHK;
1077                 USB0_ISTAT = USB_ISTAT_STALL;
1078         }
1079         if ( (status & USB_ISTAT_ERROR /* 02 */ ) )
1080         {
1081                 uint8_t err = USB0_ERRSTAT;
1082                 USB0_ERRSTAT = err;
1083                 //serial_print("err:");
1084                 //serial_phex(err);
1085                 //serial_print("\n");
1086                 USB0_ISTAT = USB_ISTAT_ERROR;
1087         }
1088
1089         if ( (status & USB_ISTAT_SLEEP /* 10 */ ) )
1090         {
1091                 //serial_print("sleep\n");
1092                 USB0_ISTAT = USB_ISTAT_SLEEP;
1093         }
1094
1095 }
1096
1097
1098
1099 void usb_init()
1100 {
1101         #ifdef UART_DEBUG
1102         print("USB INIT"NL);
1103         #endif
1104
1105         // Clear out endpoints table
1106         for ( int i = 0; i <= NUM_ENDPOINTS * 4; i++ )
1107         {
1108                 table[i].desc = 0;
1109                 table[i].addr = 0;
1110         }
1111
1112         // this basically follows the flowchart in the Kinetis
1113         // Quick Reference User Guide, Rev. 1, 03/2012, page 141
1114
1115         // assume 48 MHz clock already running
1116         // SIM - enable clock
1117         SIM_SCGC4 |= SIM_SCGC4_USBOTG;
1118
1119         // reset USB module
1120         USB0_USBTRC0 = USB_USBTRC_USBRESET;
1121         while ( (USB0_USBTRC0 & USB_USBTRC_USBRESET) != 0 ); // wait for reset to end
1122
1123         // set desc table base addr
1124         USB0_BDTPAGE1 = ((uint32_t)table) >> 8;
1125         USB0_BDTPAGE2 = ((uint32_t)table) >> 16;
1126         USB0_BDTPAGE3 = ((uint32_t)table) >> 24;
1127
1128         // clear all ISR flags
1129         USB0_ISTAT = 0xFF;
1130         USB0_ERRSTAT = 0xFF;
1131         USB0_OTGISTAT = 0xFF;
1132
1133         USB0_USBTRC0 |= 0x40; // undocumented bit
1134
1135         // enable USB
1136         USB0_CTL = USB_CTL_USBENSOFEN;
1137         USB0_USBCTRL = 0;
1138
1139         // enable reset interrupt
1140         USB0_INTEN = USB_INTEN_USBRSTEN;
1141
1142         // enable interrupt in NVIC...
1143         NVIC_SET_PRIORITY( IRQ_USBOTG, 112 );
1144         NVIC_ENABLE_IRQ( IRQ_USBOTG );
1145
1146         // enable d+ pullup
1147         USB0_CONTROL = USB_CONTROL_DPPULLUPNONOTG;
1148 }
1149
1150 // return 0 if the USB is not configured, or the configuration
1151 // number selected by the HOST
1152 uint8_t usb_configured()
1153 {
1154         return usb_configuration;
1155 }
1156