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