]> git.donarmstrong.com Git - kiibohd-controller.git/blob - Output/pjrcUSB/arm/usb_dev.c
Fixing default ErgoDox layout and adding FlashMode button
[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 (interface)
334                 i = setup.wIndex & 0x7F;
335                 if ( i > NUM_ENDPOINTS || setup.wValue != 0 )
336                 {
337                         endpoint0_stall();
338                         return;
339                 }
340                 warn_print("CLEAR_FEATURE - Interface");
341                 //(*(uint8_t *)(&USB0_ENDPT0 + setup.wIndex * 4)) &= ~0x02;
342                 // TODO: do we need to clear the data toggle here?
343                 //break;
344
345                 // FIXME: Clearing causes keyboard to freeze, likely an invalid clear
346                 // XXX: Ignoring seems to work, though this may not be the ideal behaviour -HaaTa
347                 endpoint0_stall();
348                 return;
349
350         case 0x0300: // SET_FEATURE (device)
351         case 0x0301: // SET_FEATURE (interface)
352                 // TODO: Currently ignoring, perhaps useful? -HaaTa
353                 warn_print("SET_FEATURE");
354                 endpoint0_stall();
355                 return;
356
357         case 0x0302: // SET_FEATURE (endpoint)
358                 i = setup.wIndex & 0x7F;
359                 if ( i > NUM_ENDPOINTS || setup.wValue != 0 )
360                 {
361                         // TODO: do we need to handle IN vs OUT here?
362                         endpoint0_stall();
363                         return;
364                 }
365                 (*(uint8_t *)(&USB0_ENDPT0 + setup.wIndex * 4)) |= 0x02;
366                 // TODO: do we need to clear the data toggle here?
367                 goto send;
368
369         case 0x0680: // GET_DESCRIPTOR
370         case 0x0681:
371                 #ifdef UART_DEBUG
372                 print("desc:");
373                 printHex( setup.wValue );
374                 print( NL );
375                 #endif
376                 for ( list = usb_descriptor_list; 1; list++ )
377                 {
378                         if ( list->addr == NULL )
379                                 break;
380                         if ( setup.wValue == list->wValue && setup.wIndex == list->wIndex )
381                         {
382                                 data = list->addr;
383                                 if ( (setup.wValue >> 8) == 3 )
384                                 {
385                                         // for string descriptors, use the descriptor's
386                                         // length field, allowing runtime configured
387                                         // length.
388                                         datalen = *(list->addr);
389                                 }
390                                 else
391                                 {
392                                         datalen = list->length;
393                                 }
394                                 #if UART_DEBUG
395                                 print("Desc found, ");
396                                 printHex32( (uint32_t)data );
397                                 print(",");
398                                 printHex( datalen );
399                                 print(",");
400                                 printHex_op( data[0], 2 );
401                                 printHex_op( data[1], 2 );
402                                 printHex_op( data[2], 2 );
403                                 printHex_op( data[3], 2 );
404                                 printHex_op( data[4], 2 );
405                                 printHex_op( data[5], 2 );
406                                 print( NL );
407                                 #endif
408                                 goto send;
409                         }
410                 }
411                 #ifdef UART_DEBUG
412                 print( "desc: not found" NL );
413                 #endif
414                 endpoint0_stall();
415                 return;
416
417         case 0x2221: // CDC_SET_CONTROL_LINE_STATE
418                 usb_cdc_line_rtsdtr = setup.wValue;
419                 //serial_print("set control line state\n");
420                 goto send;
421
422         case 0x21A1: // CDC_GET_LINE_CODING
423                 data = (uint8_t*)usb_cdc_line_coding;
424                 datalen = sizeof( usb_cdc_line_coding );
425                 goto send;
426
427         case 0x2021: // CDC_SET_LINE_CODING
428                 // XXX Needed?
429                 //serial_print("set coding, waiting...\n");
430                 return;
431
432         case 0x0921: // HID SET_REPORT
433                 #ifdef UART_DEBUG
434                 warn_msg("SET_REPORT - ");
435                 printHex( setup.wValue );
436                 print(" - ");
437                 printHex( setup.wValue & 0xFF );
438                 print( NL );
439                 #endif
440                 USBKeys_LEDs = setup.wValue & 0xFF;
441
442                 // Must be stall for some reason... -HaaTa
443                 endpoint0_stall();
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(NL);
622                 #endif
623                 // actually "do" the setup request
624                 usb_setup();
625                 // unfreeze the USB, now that we're ready
626                 USB0_CTL = USB_CTL_USBENSOFEN; // clear TXSUSPENDTOKENBUSY bit
627                 break;
628
629         case 0x01:  // OUT transaction received from host
630         case 0x02:
631                 #ifdef UART_DEBUG
632                 print("PID=OUT"NL);
633                 #endif
634                 // CDC Interface
635                 if ( setup.wRequestAndType == 0x2021 /*CDC_SET_LINE_CODING*/ )
636                 {
637                         int i;
638                         uint8_t *dst = (uint8_t *)usb_cdc_line_coding;
639                         //serial_print("set line coding ");
640                         for ( i = 0; i < 7; i++ )
641                         {
642                                 //serial_phex(*buf);
643                                 *dst++ = *buf++;
644                         }
645                         //serial_phex32(usb_cdc_line_coding[0]);
646                         //serial_print("\n");
647                         if ( usb_cdc_line_coding[0] == 134 )
648                                 usb_reboot_timer = 15;
649                         endpoint0_transmit( NULL, 0 );
650                 }
651
652                 // Keyboard Interface
653                 if ( setup.word1 == 0x02000921 && setup.word2 == ( (1<<16) | KEYBOARD_INTERFACE ) )
654                 {
655                         USBKeys_LEDs = buf[0];
656                         endpoint0_transmit( NULL, 0 );
657                 }
658                 // NKRO Keyboard Interface
659                 if ( setup.word1 == 0x02000921 && setup.word2 == ( (1<<16) | NKRO_KEYBOARD_INTERFACE ) )
660                 {
661                         USBKeys_LEDs = buf[0];
662                         endpoint0_transmit( NULL, 0 );
663                 }
664
665                 // give the buffer back
666                 b->desc = BDT_DESC( EP0_SIZE, DATA1 );
667                 break;
668
669         case 0x09: // IN transaction completed to host
670                 #ifdef UART_DEBUG
671                 print("PID=IN:");
672                 printHex(stat);
673                 print(NL);
674                 #endif
675
676                 // send remaining data, if any...
677                 data = ep0_tx_ptr;
678                 if ( data )
679                 {
680                         size = ep0_tx_len;
681                         if (size > EP0_SIZE) size = EP0_SIZE;
682                         endpoint0_transmit(data, size);
683                         data += size;
684                         ep0_tx_len -= size;
685                         ep0_tx_ptr = (ep0_tx_len > 0 || size == EP0_SIZE) ? data : NULL;
686                 }
687
688                 if ( setup.bRequest == 5 && setup.bmRequestType == 0 )
689                 {
690                         setup.bRequest = 0;
691                         #ifdef UART_DEBUG
692                         print("set address: ");
693                         printHex(setup.wValue);
694                         print(NL);
695                         #endif
696                         USB0_ADDR = setup.wValue;
697                 }
698
699                 break;
700
701         default:
702                 #ifdef UART_DEBUG
703                 print("PID=unknown:");
704                 printHex(pid);
705                 print(NL);
706                 #endif
707                 break;
708         }
709         USB0_CTL = USB_CTL_USBENSOFEN; // clear TXSUSPENDTOKENBUSY bit
710 }
711
712 usb_packet_t *usb_rx( uint32_t endpoint )
713 {
714         //print("USB RX");
715         usb_packet_t *ret;
716         endpoint--;
717         if ( endpoint >= NUM_ENDPOINTS )
718                 return NULL;
719         __disable_irq();
720         ret = rx_first[endpoint];
721         if ( ret )
722                 rx_first[ endpoint ] = ret->next;
723         usb_rx_byte_count_data[ endpoint ] -= ret->len;
724         __enable_irq();
725         //serial_print("rx, epidx=");
726         //serial_phex(endpoint);
727         //serial_print(", packet=");
728         //serial_phex32(ret);
729         //serial_print("\n");
730         return ret;
731 }
732
733 static uint32_t usb_queue_byte_count( const usb_packet_t *p )
734 {
735         uint32_t count=0;
736
737         __disable_irq();
738         for ( ; p; p = p->next )
739         {
740                 count += p->len;
741         }
742         __enable_irq();
743         return count;
744 }
745
746 uint32_t usb_tx_byte_count( uint32_t endpoint )
747 {
748         endpoint--;
749         if ( endpoint >= NUM_ENDPOINTS )
750                 return 0;
751         return usb_queue_byte_count( tx_first[ endpoint ] );
752 }
753
754 uint32_t usb_tx_packet_count( uint32_t endpoint )
755 {
756         const usb_packet_t *p;
757         uint32_t count=0;
758
759         endpoint--;
760         if ( endpoint >= NUM_ENDPOINTS )
761                 return 0;
762         __disable_irq();
763         for ( p = tx_first[ endpoint ]; p; p = p->next )
764                 count++;
765         __enable_irq();
766         return count;
767 }
768
769
770 // Called from usb_free, but only when usb_rx_memory_needed > 0, indicating
771 // receive endpoints are starving for memory.  The intention is to give
772 // endpoints needing receive memory priority over the user's code, which is
773 // likely calling usb_malloc to obtain memory for transmitting.  When the
774 // user is creating data very quickly, their consumption could starve reception
775 // without this prioritization.  The packet buffer (input) is assigned to the
776 // first endpoint needing memory.
777 //
778 void usb_rx_memory( usb_packet_t *packet )
779 {
780         //print("USB RX MEMORY");
781         unsigned int i;
782         const uint8_t *cfg;
783
784         cfg = usb_endpoint_config_table;
785         //serial_print("rx_mem:");
786         __disable_irq();
787         for ( i = 1; i <= NUM_ENDPOINTS; i++ )
788         {
789                 if ( *cfg++ & USB_ENDPT_EPRXEN )
790                 {
791                         if ( table[ index( i, RX, EVEN ) ].desc == 0 )
792                         {
793                                 table[ index( i, RX, EVEN ) ].addr = packet->buf;
794                                 table[ index( i, RX, EVEN ) ].desc = BDT_DESC( 64, 0 );
795                                 usb_rx_memory_needed--;
796                                 __enable_irq();
797                                 //serial_phex(i);
798                                 //serial_print(",even\n");
799                                 return;
800                         }
801                         if ( table[ index( i, RX, ODD ) ].desc == 0 )
802                         {
803                                 table[ index( i, RX, ODD ) ].addr = packet->buf;
804                                 table[ index( i, RX, ODD ) ].desc = BDT_DESC( 64, 1 );
805                                 usb_rx_memory_needed--;
806                                 __enable_irq();
807                                 //serial_phex(i);
808                                 //serial_print(",odd\n");
809                                 return;
810                         }
811                 }
812         }
813         __enable_irq();
814         // we should never reach this point.  If we get here, it means
815         // usb_rx_memory_needed was set greater than zero, but no memory
816         // was actually needed.
817         usb_rx_memory_needed = 0;
818         usb_free( packet );
819         return;
820 }
821
822 //#define index(endpoint, tx, odd) (((endpoint) << 2) | ((tx) << 1) | (odd))
823 //#define stat2bufferdescriptor(stat) (table + ((stat) >> 2))
824
825 void usb_tx( uint32_t endpoint, usb_packet_t *packet )
826 {
827         bdt_t *b = &table[ index( endpoint, TX, EVEN ) ];
828         uint8_t next;
829
830         endpoint--;
831         if ( endpoint >= NUM_ENDPOINTS )
832                 return;
833         __disable_irq();
834         //serial_print("txstate=");
835         //serial_phex(tx_state[ endpoint ]);
836         //serial_print("\n");
837         switch ( tx_state[ endpoint ] )
838         {
839         case TX_STATE_BOTH_FREE_EVEN_FIRST:
840                 next = TX_STATE_ODD_FREE;
841                 break;
842         case TX_STATE_BOTH_FREE_ODD_FIRST:
843                 b++;
844                 next = TX_STATE_EVEN_FREE;
845                 break;
846         case TX_STATE_EVEN_FREE:
847                 next = TX_STATE_NONE_FREE_ODD_FIRST;
848                 break;
849         case TX_STATE_ODD_FREE:
850                 b++;
851                 next = TX_STATE_NONE_FREE_EVEN_FIRST;
852                 break;
853         default:
854                 if (tx_first[ endpoint ] == NULL)
855                 {
856                         tx_first[ endpoint ] = packet;
857                 }
858                 else
859                 {
860                         tx_last[ endpoint ]->next = packet;
861                 }
862                 tx_last[ endpoint ] = packet;
863                 __enable_irq();
864                 return;
865         }
866
867         tx_state[ endpoint ] = next;
868         b->addr = packet->buf;
869         b->desc = BDT_DESC( packet->len, ((uint32_t)b & 8) ? DATA1 : DATA0 );
870         __enable_irq();
871 }
872
873
874 void usb_device_reload()
875 {
876         if ( flashModeEnabled_define == 0 )
877         {
878                 print( NL );
879                 warn_print("flashModeEnabled not set, cancelling firmware reload...");
880                 info_msg("Set flashModeEnabled to 1 in your kll configuration.");
881                 return;
882         }
883
884 // MCHCK
885 #if defined(_mk20dx128vlf5_)
886
887         // MCHCK Kiibohd Variant
888         // Check to see if PTA3 (has a pull-up) is connected to GND (usually via jumper)
889         // Only allow reload if the jumper is present (security)
890         GPIOA_PDDR &= ~(1<<3); // Input
891         PORTA_PCR3 = PORT_PCR_PFE | PORT_PCR_MUX(1); // Internal pull-up
892
893         // Check for jumper
894         if ( GPIOA_PDIR & (1<<3) && flashModeEnabled_define != 0 )
895         {
896                 print( NL );
897                 warn_print("Security jumper not present, cancelling firmware reload...");
898                 info_msg("Replace jumper on middle 2 pins, or manually press the firmware reload button.");
899         }
900         else
901         {
902                 // Copies variable into the VBAT register, must be identical to the variable in the bootloader to jump to the bootloader flash mode
903                 for ( int pos = 0; pos < sizeof(sys_reset_to_loader_magic); pos++ )
904                         (&VBAT)[ pos ] = sys_reset_to_loader_magic[ pos ];
905                 SOFTWARE_RESET();
906         }
907
908 // Kiibohd mk20dx256vlh7
909 #elif defined(_mk20dx256vlh7_)
910         // Copies variable into the VBAT register, must be identical to the variable in the bootloader to jump to the bootloader flash mode
911         for ( int pos = 0; pos < sizeof(sys_reset_to_loader_magic); pos++ )
912                 (&VBAT)[ pos ] = sys_reset_to_loader_magic[ pos ];
913         SOFTWARE_RESET();
914
915 // Teensy 3.0 and 3.1
916 #else
917         asm volatile("bkpt");
918 #endif
919 }
920
921
922 void usb_isr()
923 {
924         uint8_t status, stat, t;
925
926         //serial_print("isr");
927         //status = USB0_ISTAT;
928         //serial_phex(status);
929         //serial_print("\n");
930 restart:
931         status = USB0_ISTAT;
932         /*
933         print("USB ISR STATUS: ");
934         printHex( status );
935         print( NL );
936         */
937
938         if ( (status & USB_INTEN_SOFTOKEN /* 04 */ ) )
939         {
940                 if ( usb_configuration )
941                 {
942                         t = usb_reboot_timer;
943                         if ( t )
944                         {
945                                 usb_reboot_timer = --t;
946                                 if ( !t )
947                                         usb_device_reload();
948                         }
949
950                         // CDC Interface
951                         t = usb_cdc_transmit_flush_timer;
952                         if ( t )
953                         {
954                                 usb_cdc_transmit_flush_timer = --t;
955                                 if ( t == 0 )
956                                         usb_serial_flush_callback();
957                         }
958
959                 }
960                 USB0_ISTAT = USB_INTEN_SOFTOKEN;
961         }
962
963         if ( (status & USB_ISTAT_TOKDNE /* 08 */ ) )
964         {
965                 uint8_t endpoint;
966                 stat = USB0_STAT;
967                 //serial_print("token: ep=");
968                 //serial_phex(stat >> 4);
969                 //serial_print(stat & 0x08 ? ",tx" : ",rx");
970                 //serial_print(stat & 0x04 ? ",odd\n" : ",even\n");
971                 endpoint = stat >> 4;
972                 if ( endpoint == 0 )
973                 {
974                         usb_control( stat );
975                 }
976                 else
977                 {
978                         bdt_t *b = stat2bufferdescriptor(stat);
979                         usb_packet_t *packet = (usb_packet_t *)((uint8_t *)(b->addr) - 8);
980 #if 0
981                         serial_print("ep:");
982                         serial_phex(endpoint);
983                         serial_print(", pid:");
984                         serial_phex(BDT_PID(b->desc));
985                         serial_print(((uint32_t)b & 8) ? ", odd" : ", even");
986                         serial_print(", count:");
987                         serial_phex(b->desc >> 16);
988                         serial_print("\n");
989 #endif
990                         endpoint--;     // endpoint is index to zero-based arrays
991
992                         if ( stat & 0x08 )
993                         { // transmit
994                                 usb_free( packet );
995                                 packet = tx_first[ endpoint ];
996                                 if ( packet )
997                                 {
998                                         //serial_print("tx packet\n");
999                                         tx_first[endpoint] = packet->next;
1000                                         b->addr = packet->buf;
1001                                         switch ( tx_state[ endpoint ] )
1002                                         {
1003                                         case TX_STATE_BOTH_FREE_EVEN_FIRST:
1004                                                 tx_state[ endpoint ] = TX_STATE_ODD_FREE;
1005                                                 break;
1006                                         case TX_STATE_BOTH_FREE_ODD_FIRST:
1007                                                 tx_state[ endpoint ] = TX_STATE_EVEN_FREE;
1008                                                 break;
1009                                         case TX_STATE_EVEN_FREE:
1010                                                 tx_state[ endpoint ] = TX_STATE_NONE_FREE_ODD_FIRST;
1011                                                 break;
1012                                         case TX_STATE_ODD_FREE:
1013                                                 tx_state[ endpoint ] = TX_STATE_NONE_FREE_EVEN_FIRST;
1014                                                 break;
1015                                         default:
1016                                                 break;
1017                                         }
1018                                         b->desc = BDT_DESC( packet->len, ((uint32_t)b & 8) ? DATA1 : DATA0 );
1019                                 } else {
1020                                         //serial_print("tx no packet\n");
1021                                         switch ( tx_state[ endpoint ] )
1022                                         {
1023                                         case TX_STATE_BOTH_FREE_EVEN_FIRST:
1024                                         case TX_STATE_BOTH_FREE_ODD_FIRST:
1025                                                 break;
1026                                         case TX_STATE_EVEN_FREE:
1027                                                 tx_state[ endpoint ] = TX_STATE_BOTH_FREE_EVEN_FIRST;
1028                                                 break;
1029                                         case TX_STATE_ODD_FREE:
1030                                                 tx_state[ endpoint ] = TX_STATE_BOTH_FREE_ODD_FIRST;
1031                                                 break;
1032                                         default:
1033                                                 tx_state[ endpoint ] = ((uint32_t)b & 8)
1034                                                   ? TX_STATE_ODD_FREE
1035                                                   : TX_STATE_EVEN_FREE;
1036                                                 break;
1037                                         }
1038                                 }
1039                         }
1040                         else
1041                         { // receive
1042                                 packet->len = b->desc >> 16;
1043                                 if ( packet->len > 0 )
1044                                 {
1045                                         packet->index = 0;
1046                                         packet->next = NULL;
1047                                         if ( rx_first[ endpoint ] == NULL )
1048                                         {
1049                                                 //serial_print("rx 1st, epidx=");
1050                                                 //serial_phex(endpoint);
1051                                                 //serial_print(", packet=");
1052                                                 //serial_phex32((uint32_t)packet);
1053                                                 //serial_print("\n");
1054                                                 rx_first[ endpoint ] = packet;
1055                                         }
1056                                         else
1057                                         {
1058                                                 //serial_print("rx Nth, epidx=");
1059                                                 //serial_phex(endpoint);
1060                                                 //serial_print(", packet=");
1061                                                 //serial_phex32((uint32_t)packet);
1062                                                 //serial_print("\n");
1063                                                 rx_last[ endpoint ]->next = packet;
1064                                         }
1065                                         rx_last[ endpoint ] = packet;
1066                                         usb_rx_byte_count_data[ endpoint ] += packet->len;
1067                                         // TODO: implement a per-endpoint maximum # of allocated packets
1068                                         // so a flood of incoming data on 1 endpoint doesn't starve
1069                                         // the others if the user isn't reading it regularly
1070                                         packet = usb_malloc();
1071                                         if ( packet )
1072                                         {
1073                                                 b->addr = packet->buf;
1074                                                 b->desc = BDT_DESC( 64, ((uint32_t)b & 8) ? DATA1 : DATA0 );
1075                                         }
1076                                         else
1077                                         {
1078                                                 //serial_print("starving ");
1079                                                 //serial_phex(endpoint + 1);
1080                                                 //serial_print(((uint32_t)b & 8) ? ",odd\n" : ",even\n");
1081                                                 b->desc = 0;
1082                                                 usb_rx_memory_needed++;
1083                                         }
1084                                 }
1085                                 else
1086                                 {
1087                                         b->desc = BDT_DESC( 64, ((uint32_t)b & 8) ? DATA1 : DATA0 );
1088                                 }
1089                         }
1090
1091
1092
1093
1094                 }
1095                 USB0_ISTAT = USB_ISTAT_TOKDNE;
1096                 goto restart;
1097         }
1098
1099
1100         if ( status & USB_ISTAT_USBRST /* 01 */ )
1101         {
1102                 //serial_print("reset\n");
1103
1104                 // initialize BDT toggle bits
1105                 USB0_CTL = USB_CTL_ODDRST;
1106                 ep0_tx_bdt_bank = 0;
1107
1108                 // set up buffers to receive Setup and OUT packets
1109                 table[index( 0, RX, EVEN ) ].desc = BDT_DESC( EP0_SIZE, 0 );
1110                 table[index( 0, RX, EVEN ) ].addr = ep0_rx0_buf;
1111                 table[index( 0, RX, ODD ) ].desc = BDT_DESC( EP0_SIZE, 0 );
1112                 table[index( 0, RX, ODD ) ].addr = ep0_rx1_buf;
1113                 table[index( 0, TX, EVEN ) ].desc = 0;
1114                 table[index( 0, TX, ODD ) ].desc = 0;
1115
1116                 // activate endpoint 0
1117                 USB0_ENDPT0 = USB_ENDPT_EPRXEN | USB_ENDPT_EPTXEN | USB_ENDPT_EPHSHK;
1118
1119                 // clear all ending interrupts
1120                 USB0_ERRSTAT = 0xFF;
1121                 USB0_ISTAT = 0xFF;
1122
1123                 // set the address to zero during enumeration
1124                 USB0_ADDR = 0;
1125
1126                 // enable other interrupts
1127                 USB0_ERREN = 0xFF;
1128                 USB0_INTEN = USB_INTEN_TOKDNEEN |
1129                         USB_INTEN_SOFTOKEN |
1130                         USB_INTEN_STALLEN |
1131                         USB_INTEN_ERROREN |
1132                         USB_INTEN_USBRSTEN |
1133                         USB_INTEN_SLEEPEN;
1134
1135                 // is this necessary?
1136                 USB0_CTL = USB_CTL_USBENSOFEN;
1137                 return;
1138         }
1139
1140
1141         if ( (status & USB_ISTAT_STALL /* 80 */ ) )
1142         {
1143                 //serial_print("stall:\n");
1144                 USB0_ENDPT0 = USB_ENDPT_EPRXEN | USB_ENDPT_EPTXEN | USB_ENDPT_EPHSHK;
1145                 USB0_ISTAT = USB_ISTAT_STALL;
1146         }
1147         if ( (status & USB_ISTAT_ERROR /* 02 */ ) )
1148         {
1149                 uint8_t err = USB0_ERRSTAT;
1150                 USB0_ERRSTAT = err;
1151                 //serial_print("err:");
1152                 //serial_phex(err);
1153                 //serial_print("\n");
1154                 USB0_ISTAT = USB_ISTAT_ERROR;
1155         }
1156
1157         if ( (status & USB_ISTAT_SLEEP /* 10 */ ) )
1158         {
1159                 //serial_print("sleep\n");
1160                 USB0_ISTAT = USB_ISTAT_SLEEP;
1161         }
1162 }
1163
1164
1165
1166 uint8_t usb_init()
1167 {
1168         #ifdef UART_DEBUG
1169         print("USB INIT"NL);
1170         #endif
1171
1172         // Clear out endpoints table
1173         for ( int i = 0; i <= NUM_ENDPOINTS * 4; i++ )
1174         {
1175                 table[i].desc = 0;
1176                 table[i].addr = 0;
1177         }
1178
1179         // this basically follows the flowchart in the Kinetis
1180         // Quick Reference User Guide, Rev. 1, 03/2012, page 141
1181
1182         // assume 48 MHz clock already running
1183         // SIM - enable clock
1184         SIM_SCGC4 |= SIM_SCGC4_USBOTG;
1185
1186         // reset USB module
1187         USB0_USBTRC0 = USB_USBTRC_USBRESET;
1188         while ( (USB0_USBTRC0 & USB_USBTRC_USBRESET) != 0 ); // wait for reset to end
1189
1190         // set desc table base addr
1191         USB0_BDTPAGE1 = ((uint32_t)table) >> 8;
1192         USB0_BDTPAGE2 = ((uint32_t)table) >> 16;
1193         USB0_BDTPAGE3 = ((uint32_t)table) >> 24;
1194
1195         // clear all ISR flags
1196         USB0_ISTAT = 0xFF;
1197         USB0_ERRSTAT = 0xFF;
1198         USB0_OTGISTAT = 0xFF;
1199
1200         USB0_USBTRC0 |= 0x40; // undocumented bit
1201
1202         // enable USB
1203         USB0_CTL = USB_CTL_USBENSOFEN;
1204         USB0_USBCTRL = 0;
1205
1206         // enable reset interrupt
1207         USB0_INTEN = USB_INTEN_USBRSTEN;
1208
1209         // enable interrupt in NVIC...
1210         NVIC_SET_PRIORITY( IRQ_USBOTG, 112 );
1211         NVIC_ENABLE_IRQ( IRQ_USBOTG );
1212
1213         // enable d+ pullup
1214         USB0_CONTROL = USB_CONTROL_DPPULLUPNONOTG;
1215
1216         return 1;
1217 }
1218
1219 // return 0 if the USB is not configured, or the configuration
1220 // number selected by the HOST
1221 uint8_t usb_configured()
1222 {
1223         return usb_configuration;
1224 }
1225