]> git.donarmstrong.com Git - kiibohd-controller.git/blob - Output/pjrcUSB/arm/usb_dev.c
e913006e615d06970ed8e5408f0ced007a2b7af9
[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                 // Interface
428                 switch ( setup.wIndex & 0xFF )
429                 {
430                 // Keyboard Interface
431                 case KEYBOARD_INTERFACE:
432                         break;
433                 // NKRO Keyboard Interface
434                 case NKRO_KEYBOARD_INTERFACE:
435                         break;
436                 default:
437                         warn_msg("Unknown interface - ");
438                         printHex( setup.wIndex );
439                         print( NL );
440                         endpoint0_stall();
441                         break;
442                 }
443
444                 return;
445
446         case 0x01A1: // HID GET_REPORT
447                 #ifdef UART_DEBUG
448                 print("GET_REPORT - ");
449                 printHex( setup.wIndex );
450                 print(NL);
451                 #endif
452                 // Search through descriptors returning necessary info
453                 for ( list = usb_descriptor_list; 1; list++ )
454                 {
455                         if ( list->addr == NULL )
456                                 break;
457                         if ( list->wValue != 0x2200 )
458                                 continue;
459                         if ( setup.wIndex == list->wIndex )
460                         {
461                                 data = list->addr;
462                                 datalen = list->length;
463                                 goto send;
464                         }
465                 }
466                 endpoint0_stall();
467                 return;
468
469         case 0x0A21: // HID SET_IDLE
470                 #ifdef UART_DEBUG
471                 print("SET_IDLE - ");
472                 printHex( setup.wValue );
473                 print(NL);
474                 #endif
475                 USBKeys_Idle_Config = (setup.wValue >> 8);
476                 USBKeys_Idle_Count = 0;
477                 goto send;
478
479         case 0x0B21: // HID SET_PROTOCOL
480                 #ifdef UART_DEBUG
481                 print("SET_PROTOCOL - ");
482                 printHex( setup.wValue );
483                 print(" - ");
484                 printHex( setup.wValue & 0xFF );
485                 print(NL);
486                 #endif
487                 USBKeys_Protocol = setup.wValue & 0xFF; // 0 - Boot Mode, 1 - NKRO Mode
488                 goto send;
489
490         // case 0xC940:
491         default:
492                 #ifdef UART_DEBUG_UNKNOWN
493                 print("UNKNOWN");
494                 #endif
495                 endpoint0_stall();
496                 return;
497         }
498
499 send:
500         #ifdef UART_DEBUG
501         print("setup send ");
502         printHex32( (uint32_t)data );
503         print(",");
504         for ( uint8_t c = 0; c < datalen; c++ )
505         {
506                 printHex( data[c] );
507                 print(" ");
508         }
509         print(",");
510         printHex( datalen );
511         print( NL );
512         #endif
513
514         if ( datalen > setup.wLength )
515                 datalen = setup.wLength;
516
517         size = datalen;
518         if ( size > EP0_SIZE )
519                 size = EP0_SIZE;
520
521         endpoint0_transmit(data, size);
522         data += size;
523         datalen -= size;
524
525         // See if transmit has finished
526         if ( datalen == 0 && size < EP0_SIZE )
527                 return;
528
529         size = datalen;
530         if ( size > EP0_SIZE )
531                 size = EP0_SIZE;
532         endpoint0_transmit(data, size);
533         data += size;
534         datalen -= size;
535
536         // See if transmit has finished
537         if ( datalen == 0 && size < EP0_SIZE )
538                 return;
539
540         // Save rest of transfer for later? XXX
541         ep0_tx_ptr = data;
542         ep0_tx_len = datalen;
543 }
544
545
546 //A bulk endpoint's toggle sequence is initialized to DATA0 when the endpoint
547 //experiences any configuration event (configuration events are explained in
548 //Sections 9.1.1.5 and 9.4.5).
549
550 //Configuring a device or changing an alternate setting causes all of the status
551 //and configuration values associated with endpoints in the affected interfaces
552 //to be set to their default values. This includes setting the data toggle of
553 //any endpoint using data toggles to the value DATA0.
554
555 //For endpoints using data toggle, regardless of whether an endpoint has the
556 //Halt feature set, a ClearFeature(ENDPOINT_HALT) request always results in the
557 //data toggle being reinitialized to DATA0.
558
559 static void usb_control( uint32_t stat )
560 {
561         #ifdef UART_DEBUG
562         print("CONTROL - ");
563         #endif
564         bdt_t *b;
565         uint32_t pid, size;
566         uint8_t *buf;
567         const uint8_t *data;
568
569         b = stat2bufferdescriptor( stat );
570         pid = BDT_PID( b->desc );
571         buf = b->addr;
572         #ifdef UART_DEBUG
573         print("pid:");
574         printHex(pid);
575         print(", count:");
576         printHex32(b->desc);
577         print(" - ");
578         #endif
579
580         switch (pid)
581         {
582         case 0x0D: // Setup received from host
583                 //serial_print("PID=Setup\n");
584                 //if (count != 8) ; // panic?
585                 // grab the 8 byte setup info
586                 setup.word1 = *(uint32_t *)(buf);
587                 setup.word2 = *(uint32_t *)(buf + 4);
588
589                 // give the buffer back
590                 b->desc = BDT_DESC( EP0_SIZE, DATA1 );
591                 //table[index(0, RX, EVEN)].desc = BDT_DESC(EP0_SIZE, 1);
592                 //table[index(0, RX, ODD)].desc = BDT_DESC(EP0_SIZE, 1);
593
594                 // clear any leftover pending IN transactions
595                 ep0_tx_ptr = NULL;
596                 if ( ep0_tx_data_toggle )
597                 {
598                 }
599                 //if (table[index(0, TX, EVEN)].desc & 0x80) {
600                         //serial_print("leftover tx even\n");
601                 //}
602                 //if (table[index(0, TX, ODD)].desc & 0x80) {
603                         //serial_print("leftover tx odd\n");
604                 //}
605                 table[index(0, TX, EVEN)].desc = 0;
606                 table[index(0, TX, ODD)].desc = 0;
607                 // first IN after Setup is always DATA1
608                 ep0_tx_data_toggle = 1;
609
610                 #ifdef UART_DEBUG_UNKNOWN
611                 print("bmRequestType:");
612                 printHex(setup.bmRequestType);
613                 print(", bRequest:");
614                 printHex(setup.bRequest);
615                 print(", wValue:");
616                 printHex(setup.wValue);
617                 print(", wIndex:");
618                 printHex(setup.wIndex);
619                 print(", len:");
620                 printHex(setup.wLength);
621                 print(" -- ");
622                 printHex32(setup.word1);
623                 print(" ");
624                 printHex32(setup.word2);
625                 print(NL);
626                 #endif
627                 // actually "do" the setup request
628                 usb_setup();
629                 // unfreeze the USB, now that we're ready
630                 USB0_CTL = USB_CTL_USBENSOFEN; // clear TXSUSPENDTOKENBUSY bit
631                 break;
632
633         case 0x01:  // OUT transaction received from host
634         case 0x02:
635                 #ifdef UART_DEBUG_UNKNOWN
636                 print("PID=OUT wRequestAndType:");
637                 printHex(setup.wRequestAndType);
638                 print(", wValue:");
639                 printHex(setup.wValue);
640                 print(", wIndex:");
641                 printHex(setup.wIndex);
642                 print(", len:");
643                 printHex(setup.wLength);
644                 print(" -- ");
645                 printHex32(setup.word1);
646                 print(" ");
647                 printHex32(setup.word2);
648                 print(NL);
649                 #endif
650
651                 // CDC Interface
652                 if ( setup.wRequestAndType == 0x2021 /*CDC_SET_LINE_CODING*/ )
653                 {
654                         int i;
655                         uint8_t *dst = (uint8_t *)usb_cdc_line_coding;
656                         //serial_print("set line coding ");
657                         for ( i = 0; i < 7; i++ )
658                         {
659                                 //serial_phex(*buf);
660                                 *dst++ = *buf++;
661                         }
662                         //serial_phex32(usb_cdc_line_coding[0]);
663                         //serial_print("\n");
664                         if ( usb_cdc_line_coding[0] == 134 )
665                                 usb_reboot_timer = 15;
666                         endpoint0_transmit( NULL, 0 );
667                 }
668
669                 // Keyboard SET_REPORT
670                 if ( setup.wRequestAndType == 0x921 && setup.wValue & 0x200 )
671                 {
672                         // Interface
673                         switch ( setup.wIndex & 0xFF )
674                         {
675                         // Keyboard Interface
676                         case KEYBOARD_INTERFACE:
677                                 USBKeys_LEDs = buf[0];
678                                 endpoint0_transmit( NULL, 0 );
679                                 break;
680                         // NKRO Keyboard Interface
681                         case NKRO_KEYBOARD_INTERFACE:
682                                 // Only use 2nd byte, first byte is the report id
683                                 USBKeys_LEDs = buf[1];
684                                 endpoint0_transmit( NULL, 0 );
685                                 break;
686                         default:
687                                 warn_msg("Unknown interface - ");
688                                 printHex( setup.wIndex );
689                                 print( NL );
690                                 break;
691                         }
692
693                         #ifdef UART_DEBUG
694                         for ( size_t len = 0; len < setup.wLength; len++ )
695                         {
696                                 printHex( buf[ len ] );
697                                 print(" ");
698                         }
699                         print( NL );
700                         #endif
701                 }
702
703                 // give the buffer back
704                 b->desc = BDT_DESC( EP0_SIZE, DATA1 );
705                 break;
706
707         case 0x09: // IN transaction completed to host
708                 #ifdef UART_DEBUG
709                 print("PID=IN:");
710                 printHex(stat);
711                 print(NL);
712                 #endif
713
714                 // send remaining data, if any...
715                 data = ep0_tx_ptr;
716                 if ( data )
717                 {
718                         size = ep0_tx_len;
719                         if (size > EP0_SIZE) size = EP0_SIZE;
720                         endpoint0_transmit(data, size);
721                         data += size;
722                         ep0_tx_len -= size;
723                         ep0_tx_ptr = (ep0_tx_len > 0 || size == EP0_SIZE) ? data : NULL;
724                 }
725
726                 if ( setup.bRequest == 5 && setup.bmRequestType == 0 )
727                 {
728                         setup.bRequest = 0;
729                         #ifdef UART_DEBUG
730                         print("set address: ");
731                         printHex(setup.wValue);
732                         print(NL);
733                         #endif
734                         USB0_ADDR = setup.wValue;
735                 }
736
737                 break;
738
739         default:
740                 #ifdef UART_DEBUG
741                 print("PID=unknown:");
742                 printHex(pid);
743                 print(NL);
744                 #endif
745                 break;
746         }
747         USB0_CTL = USB_CTL_USBENSOFEN; // clear TXSUSPENDTOKENBUSY bit
748 }
749
750 usb_packet_t *usb_rx( uint32_t endpoint )
751 {
752         //print("USB RX");
753         usb_packet_t *ret;
754         endpoint--;
755         if ( endpoint >= NUM_ENDPOINTS )
756                 return NULL;
757         __disable_irq();
758         ret = rx_first[endpoint];
759         if ( ret )
760                 rx_first[ endpoint ] = ret->next;
761         usb_rx_byte_count_data[ endpoint ] -= ret->len;
762         __enable_irq();
763         //serial_print("rx, epidx=");
764         //serial_phex(endpoint);
765         //serial_print(", packet=");
766         //serial_phex32(ret);
767         //serial_print("\n");
768         return ret;
769 }
770
771 static uint32_t usb_queue_byte_count( const usb_packet_t *p )
772 {
773         uint32_t count=0;
774
775         __disable_irq();
776         for ( ; p; p = p->next )
777         {
778                 count += p->len;
779         }
780         __enable_irq();
781         return count;
782 }
783
784 uint32_t usb_tx_byte_count( uint32_t endpoint )
785 {
786         endpoint--;
787         if ( endpoint >= NUM_ENDPOINTS )
788                 return 0;
789         return usb_queue_byte_count( tx_first[ endpoint ] );
790 }
791
792 uint32_t usb_tx_packet_count( uint32_t endpoint )
793 {
794         const usb_packet_t *p;
795         uint32_t count=0;
796
797         endpoint--;
798         if ( endpoint >= NUM_ENDPOINTS )
799                 return 0;
800         __disable_irq();
801         for ( p = tx_first[ endpoint ]; p; p = p->next )
802                 count++;
803         __enable_irq();
804         return count;
805 }
806
807
808 // Called from usb_free, but only when usb_rx_memory_needed > 0, indicating
809 // receive endpoints are starving for memory.  The intention is to give
810 // endpoints needing receive memory priority over the user's code, which is
811 // likely calling usb_malloc to obtain memory for transmitting.  When the
812 // user is creating data very quickly, their consumption could starve reception
813 // without this prioritization.  The packet buffer (input) is assigned to the
814 // first endpoint needing memory.
815 //
816 void usb_rx_memory( usb_packet_t *packet )
817 {
818         //print("USB RX MEMORY");
819         unsigned int i;
820         const uint8_t *cfg;
821
822         cfg = usb_endpoint_config_table;
823         //serial_print("rx_mem:");
824         __disable_irq();
825         for ( i = 1; i <= NUM_ENDPOINTS; i++ )
826         {
827                 if ( *cfg++ & USB_ENDPT_EPRXEN )
828                 {
829                         if ( table[ index( i, RX, EVEN ) ].desc == 0 )
830                         {
831                                 table[ index( i, RX, EVEN ) ].addr = packet->buf;
832                                 table[ index( i, RX, EVEN ) ].desc = BDT_DESC( 64, 0 );
833                                 usb_rx_memory_needed--;
834                                 __enable_irq();
835                                 //serial_phex(i);
836                                 //serial_print(",even\n");
837                                 return;
838                         }
839                         if ( table[ index( i, RX, ODD ) ].desc == 0 )
840                         {
841                                 table[ index( i, RX, ODD ) ].addr = packet->buf;
842                                 table[ index( i, RX, ODD ) ].desc = BDT_DESC( 64, 1 );
843                                 usb_rx_memory_needed--;
844                                 __enable_irq();
845                                 //serial_phex(i);
846                                 //serial_print(",odd\n");
847                                 return;
848                         }
849                 }
850         }
851         __enable_irq();
852         // we should never reach this point.  If we get here, it means
853         // usb_rx_memory_needed was set greater than zero, but no memory
854         // was actually needed.
855         usb_rx_memory_needed = 0;
856         usb_free( packet );
857         return;
858 }
859
860 //#define index(endpoint, tx, odd) (((endpoint) << 2) | ((tx) << 1) | (odd))
861 //#define stat2bufferdescriptor(stat) (table + ((stat) >> 2))
862
863 void usb_tx( uint32_t endpoint, usb_packet_t *packet )
864 {
865         bdt_t *b = &table[ index( endpoint, TX, EVEN ) ];
866         uint8_t next;
867
868         endpoint--;
869         if ( endpoint >= NUM_ENDPOINTS )
870                 return;
871         __disable_irq();
872         //serial_print("txstate=");
873         //serial_phex(tx_state[ endpoint ]);
874         //serial_print("\n");
875         switch ( tx_state[ endpoint ] )
876         {
877         case TX_STATE_BOTH_FREE_EVEN_FIRST:
878                 next = TX_STATE_ODD_FREE;
879                 break;
880         case TX_STATE_BOTH_FREE_ODD_FIRST:
881                 b++;
882                 next = TX_STATE_EVEN_FREE;
883                 break;
884         case TX_STATE_EVEN_FREE:
885                 next = TX_STATE_NONE_FREE_ODD_FIRST;
886                 break;
887         case TX_STATE_ODD_FREE:
888                 b++;
889                 next = TX_STATE_NONE_FREE_EVEN_FIRST;
890                 break;
891         default:
892                 if (tx_first[ endpoint ] == NULL)
893                 {
894                         tx_first[ endpoint ] = packet;
895                 }
896                 else
897                 {
898                         tx_last[ endpoint ]->next = packet;
899                 }
900                 tx_last[ endpoint ] = packet;
901                 __enable_irq();
902                 return;
903         }
904
905         tx_state[ endpoint ] = next;
906         b->addr = packet->buf;
907         b->desc = BDT_DESC( packet->len, ((uint32_t)b & 8) ? DATA1 : DATA0 );
908         __enable_irq();
909 }
910
911
912 void usb_device_reload()
913 {
914         if ( flashModeEnabled_define == 0 )
915         {
916                 print( NL );
917                 warn_print("flashModeEnabled not set, cancelling firmware reload...");
918                 info_msg("Set flashModeEnabled to 1 in your kll configuration.");
919                 return;
920         }
921
922 // MCHCK
923 #if defined(_mk20dx128vlf5_)
924
925         // MCHCK Kiibohd Variant
926         // Check to see if PTA3 (has a pull-up) is connected to GND (usually via jumper)
927         // Only allow reload if the jumper is present (security)
928         GPIOA_PDDR &= ~(1<<3); // Input
929         PORTA_PCR3 = PORT_PCR_PFE | PORT_PCR_MUX(1); // Internal pull-up
930
931         // Check for jumper
932         if ( GPIOA_PDIR & (1<<3) && flashModeEnabled_define != 0 )
933         {
934                 print( NL );
935                 warn_print("Security jumper not present, cancelling firmware reload...");
936                 info_msg("Replace jumper on middle 2 pins, or manually press the firmware reload button.");
937         }
938         else
939         {
940                 // Copies variable into the VBAT register, must be identical to the variable in the bootloader to jump to the bootloader flash mode
941                 for ( int pos = 0; pos < sizeof(sys_reset_to_loader_magic); pos++ )
942                         (&VBAT)[ pos ] = sys_reset_to_loader_magic[ pos ];
943                 SOFTWARE_RESET();
944         }
945
946 // Kiibohd mk20dx256vlh7
947 #elif defined(_mk20dx256vlh7_)
948         // Copies variable into the VBAT register, must be identical to the variable in the bootloader to jump to the bootloader flash mode
949         for ( int pos = 0; pos < sizeof(sys_reset_to_loader_magic); pos++ )
950                 (&VBAT)[ pos ] = sys_reset_to_loader_magic[ pos ];
951         SOFTWARE_RESET();
952
953 // Teensy 3.0 and 3.1
954 #else
955         asm volatile("bkpt");
956 #endif
957 }
958
959
960 void usb_isr()
961 {
962         uint8_t status, stat, t;
963
964         //serial_print("isr");
965         //status = USB0_ISTAT;
966         //serial_phex(status);
967         //serial_print("\n");
968 restart:
969         status = USB0_ISTAT;
970         /*
971         print("USB ISR STATUS: ");
972         printHex( status );
973         print( NL );
974         */
975
976         if ( (status & USB_INTEN_SOFTOKEN /* 04 */ ) )
977         {
978                 if ( usb_configuration )
979                 {
980                         t = usb_reboot_timer;
981                         if ( t )
982                         {
983                                 usb_reboot_timer = --t;
984                                 if ( !t )
985                                         usb_device_reload();
986                         }
987
988                         // CDC Interface
989                         t = usb_cdc_transmit_flush_timer;
990                         if ( t )
991                         {
992                                 usb_cdc_transmit_flush_timer = --t;
993                                 if ( t == 0 )
994                                         usb_serial_flush_callback();
995                         }
996
997                 }
998                 USB0_ISTAT = USB_INTEN_SOFTOKEN;
999         }
1000
1001         if ( (status & USB_ISTAT_TOKDNE /* 08 */ ) )
1002         {
1003                 uint8_t endpoint;
1004                 stat = USB0_STAT;
1005                 //serial_print("token: ep=");
1006                 //serial_phex(stat >> 4);
1007                 //serial_print(stat & 0x08 ? ",tx" : ",rx");
1008                 //serial_print(stat & 0x04 ? ",odd\n" : ",even\n");
1009                 endpoint = stat >> 4;
1010                 if ( endpoint == 0 )
1011                 {
1012                         usb_control( stat );
1013                 }
1014                 else
1015                 {
1016                         bdt_t *b = stat2bufferdescriptor(stat);
1017                         usb_packet_t *packet = (usb_packet_t *)((uint8_t *)(b->addr) - 8);
1018 #if 0
1019                         serial_print("ep:");
1020                         serial_phex(endpoint);
1021                         serial_print(", pid:");
1022                         serial_phex(BDT_PID(b->desc));
1023                         serial_print(((uint32_t)b & 8) ? ", odd" : ", even");
1024                         serial_print(", count:");
1025                         serial_phex(b->desc >> 16);
1026                         serial_print("\n");
1027 #endif
1028                         endpoint--;     // endpoint is index to zero-based arrays
1029
1030                         if ( stat & 0x08 )
1031                         { // transmit
1032                                 usb_free( packet );
1033                                 packet = tx_first[ endpoint ];
1034                                 if ( packet )
1035                                 {
1036                                         //serial_print("tx packet\n");
1037                                         tx_first[endpoint] = packet->next;
1038                                         b->addr = packet->buf;
1039                                         switch ( tx_state[ endpoint ] )
1040                                         {
1041                                         case TX_STATE_BOTH_FREE_EVEN_FIRST:
1042                                                 tx_state[ endpoint ] = TX_STATE_ODD_FREE;
1043                                                 break;
1044                                         case TX_STATE_BOTH_FREE_ODD_FIRST:
1045                                                 tx_state[ endpoint ] = TX_STATE_EVEN_FREE;
1046                                                 break;
1047                                         case TX_STATE_EVEN_FREE:
1048                                                 tx_state[ endpoint ] = TX_STATE_NONE_FREE_ODD_FIRST;
1049                                                 break;
1050                                         case TX_STATE_ODD_FREE:
1051                                                 tx_state[ endpoint ] = TX_STATE_NONE_FREE_EVEN_FIRST;
1052                                                 break;
1053                                         default:
1054                                                 break;
1055                                         }
1056                                         b->desc = BDT_DESC( packet->len, ((uint32_t)b & 8) ? DATA1 : DATA0 );
1057                                 } else {
1058                                         //serial_print("tx no packet\n");
1059                                         switch ( tx_state[ endpoint ] )
1060                                         {
1061                                         case TX_STATE_BOTH_FREE_EVEN_FIRST:
1062                                         case TX_STATE_BOTH_FREE_ODD_FIRST:
1063                                                 break;
1064                                         case TX_STATE_EVEN_FREE:
1065                                                 tx_state[ endpoint ] = TX_STATE_BOTH_FREE_EVEN_FIRST;
1066                                                 break;
1067                                         case TX_STATE_ODD_FREE:
1068                                                 tx_state[ endpoint ] = TX_STATE_BOTH_FREE_ODD_FIRST;
1069                                                 break;
1070                                         default:
1071                                                 tx_state[ endpoint ] = ((uint32_t)b & 8)
1072                                                         ? TX_STATE_ODD_FREE
1073                                                         : TX_STATE_EVEN_FREE;
1074                                                 break;
1075                                         }
1076                                 }
1077                         }
1078                         else
1079                         { // receive
1080                                 packet->len = b->desc >> 16;
1081                                 if ( packet->len > 0 )
1082                                 {
1083                                         packet->index = 0;
1084                                         packet->next = NULL;
1085                                         if ( rx_first[ endpoint ] == NULL )
1086                                         {
1087                                                 //serial_print("rx 1st, epidx=");
1088                                                 //serial_phex(endpoint);
1089                                                 //serial_print(", packet=");
1090                                                 //serial_phex32((uint32_t)packet);
1091                                                 //serial_print("\n");
1092                                                 rx_first[ endpoint ] = packet;
1093                                         }
1094                                         else
1095                                         {
1096                                                 //serial_print("rx Nth, epidx=");
1097                                                 //serial_phex(endpoint);
1098                                                 //serial_print(", packet=");
1099                                                 //serial_phex32((uint32_t)packet);
1100                                                 //serial_print("\n");
1101                                                 rx_last[ endpoint ]->next = packet;
1102                                         }
1103                                         rx_last[ endpoint ] = packet;
1104                                         usb_rx_byte_count_data[ endpoint ] += packet->len;
1105                                         // TODO: implement a per-endpoint maximum # of allocated packets
1106                                         // so a flood of incoming data on 1 endpoint doesn't starve
1107                                         // the others if the user isn't reading it regularly
1108                                         packet = usb_malloc();
1109                                         if ( packet )
1110                                         {
1111                                                 b->addr = packet->buf;
1112                                                 b->desc = BDT_DESC( 64, ((uint32_t)b & 8) ? DATA1 : DATA0 );
1113                                         }
1114                                         else
1115                                         {
1116                                                 //serial_print("starving ");
1117                                                 //serial_phex(endpoint + 1);
1118                                                 //serial_print(((uint32_t)b & 8) ? ",odd\n" : ",even\n");
1119                                                 b->desc = 0;
1120                                                 usb_rx_memory_needed++;
1121                                         }
1122                                 }
1123                                 else
1124                                 {
1125                                         b->desc = BDT_DESC( 64, ((uint32_t)b & 8) ? DATA1 : DATA0 );
1126                                 }
1127                         }
1128
1129
1130
1131
1132                 }
1133                 USB0_ISTAT = USB_ISTAT_TOKDNE;
1134                 goto restart;
1135         }
1136
1137
1138         if ( status & USB_ISTAT_USBRST /* 01 */ )
1139         {
1140                 //serial_print("reset\n");
1141
1142                 // initialize BDT toggle bits
1143                 USB0_CTL = USB_CTL_ODDRST;
1144                 ep0_tx_bdt_bank = 0;
1145
1146                 // set up buffers to receive Setup and OUT packets
1147                 table[index( 0, RX, EVEN ) ].desc = BDT_DESC( EP0_SIZE, 0 );
1148                 table[index( 0, RX, EVEN ) ].addr = ep0_rx0_buf;
1149                 table[index( 0, RX, ODD ) ].desc = BDT_DESC( EP0_SIZE, 0 );
1150                 table[index( 0, RX, ODD ) ].addr = ep0_rx1_buf;
1151                 table[index( 0, TX, EVEN ) ].desc = 0;
1152                 table[index( 0, TX, ODD ) ].desc = 0;
1153
1154                 // activate endpoint 0
1155                 USB0_ENDPT0 = USB_ENDPT_EPRXEN | USB_ENDPT_EPTXEN | USB_ENDPT_EPHSHK;
1156
1157                 // clear all ending interrupts
1158                 USB0_ERRSTAT = 0xFF;
1159                 USB0_ISTAT = 0xFF;
1160
1161                 // set the address to zero during enumeration
1162                 USB0_ADDR = 0;
1163
1164                 // enable other interrupts
1165                 USB0_ERREN = 0xFF;
1166                 USB0_INTEN = USB_INTEN_TOKDNEEN |
1167                         USB_INTEN_SOFTOKEN |
1168                         USB_INTEN_STALLEN |
1169                         USB_INTEN_ERROREN |
1170                         USB_INTEN_USBRSTEN |
1171                         USB_INTEN_SLEEPEN;
1172
1173                 // is this necessary?
1174                 USB0_CTL = USB_CTL_USBENSOFEN;
1175                 return;
1176         }
1177
1178
1179         if ( (status & USB_ISTAT_STALL /* 80 */ ) )
1180         {
1181                 //serial_print("stall:\n");
1182                 USB0_ENDPT0 = USB_ENDPT_EPRXEN | USB_ENDPT_EPTXEN | USB_ENDPT_EPHSHK;
1183                 USB0_ISTAT = USB_ISTAT_STALL;
1184         }
1185         if ( (status & USB_ISTAT_ERROR /* 02 */ ) )
1186         {
1187                 uint8_t err = USB0_ERRSTAT;
1188                 USB0_ERRSTAT = err;
1189                 //serial_print("err:");
1190                 //serial_phex(err);
1191                 //serial_print("\n");
1192                 USB0_ISTAT = USB_ISTAT_ERROR;
1193         }
1194
1195         if ( (status & USB_ISTAT_SLEEP /* 10 */ ) )
1196         {
1197                 //serial_print("sleep\n");
1198                 USB0_ISTAT = USB_ISTAT_SLEEP;
1199         }
1200 }
1201
1202
1203
1204 uint8_t usb_init()
1205 {
1206         #ifdef UART_DEBUG
1207         print("USB INIT"NL);
1208         #endif
1209
1210         // Clear out endpoints table
1211         for ( int i = 0; i <= NUM_ENDPOINTS * 4; i++ )
1212         {
1213                 table[i].desc = 0;
1214                 table[i].addr = 0;
1215         }
1216
1217         // this basically follows the flowchart in the Kinetis
1218         // Quick Reference User Guide, Rev. 1, 03/2012, page 141
1219
1220         // assume 48 MHz clock already running
1221         // SIM - enable clock
1222         SIM_SCGC4 |= SIM_SCGC4_USBOTG;
1223
1224         // reset USB module
1225         USB0_USBTRC0 = USB_USBTRC_USBRESET;
1226         while ( (USB0_USBTRC0 & USB_USBTRC_USBRESET) != 0 ); // wait for reset to end
1227
1228         // set desc table base addr
1229         USB0_BDTPAGE1 = ((uint32_t)table) >> 8;
1230         USB0_BDTPAGE2 = ((uint32_t)table) >> 16;
1231         USB0_BDTPAGE3 = ((uint32_t)table) >> 24;
1232
1233         // clear all ISR flags
1234         USB0_ISTAT = 0xFF;
1235         USB0_ERRSTAT = 0xFF;
1236         USB0_OTGISTAT = 0xFF;
1237
1238         USB0_USBTRC0 |= 0x40; // undocumented bit
1239
1240         // enable USB
1241         USB0_CTL = USB_CTL_USBENSOFEN;
1242         USB0_USBCTRL = 0;
1243
1244         // enable reset interrupt
1245         USB0_INTEN = USB_INTEN_USBRSTEN;
1246
1247         // enable interrupt in NVIC...
1248         NVIC_SET_PRIORITY( IRQ_USBOTG, 112 );
1249         NVIC_ENABLE_IRQ( IRQ_USBOTG );
1250
1251         // enable d+ pullup
1252         USB0_CONTROL = USB_CONTROL_DPPULLUPNONOTG;
1253
1254         return 1;
1255 }
1256
1257 // return 0 if the USB is not configured, or the configuration
1258 // number selected by the HOST
1259 uint8_t usb_configured()
1260 {
1261         return usb_configuration;
1262 }
1263