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