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