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