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