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