1 /* Teensyduino Core Library
2 * http://www.pjrc.com/teensy/
3 * Copyright (c) 2013 PJRC.COM, LLC.
4 * Modifications by Jacob Alexander (2013-2016)
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:
14 * 1. The above copyright notice and this permission notice shall be
15 * included in all copies or substantial portions of the Software.
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.
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
32 // ----- Includes -----
35 #include <Lib/OutputLib.h>
45 // ----- Defines -----
48 // XXX - Only use when using usbMuxUart Module
49 // Delay causes issues initializing more than 1 hid device (i.e. NKRO keyboard)
50 //#define UART_DEBUG 1
51 // Debug Unknown USB requests, usually what you want to debug USB issues
52 //#define UART_DEBUG_UNKNOWN 1
55 #define TX_STATE_BOTH_FREE_EVEN_FIRST 0
56 #define TX_STATE_BOTH_FREE_ODD_FIRST 1
57 #define TX_STATE_EVEN_FREE 2
58 #define TX_STATE_ODD_FREE 3
59 #define TX_STATE_NONE_FREE_EVEN_FIRST 4
60 #define TX_STATE_NONE_FREE_ODD_FIRST 5
63 #define BDT_DATA1 0x40
64 #define BDT_DATA0 0x00
66 #define BDT_STALL 0x04
77 #define CLEAR_FEATURE 1
80 #define GET_DESCRIPTOR 6
81 #define SET_DESCRIPTOR 7
82 #define GET_CONFIGURATION 8
83 #define SET_CONFIGURATION 9
84 #define GET_INTERFACE 10
85 #define SET_INTERFACE 11
86 #define SYNCH_FRAME 12
88 #define TX_STATE_BOTH_FREE_EVEN_FIRST 0
89 #define TX_STATE_BOTH_FREE_ODD_FIRST 1
90 #define TX_STATE_EVEN_FREE 2
91 #define TX_STATE_ODD_FREE 3
92 #define TX_STATE_NONE_FREE 4
100 #define BDT_PID(n) (((n) >> 2) & 15)
102 #define BDT_DESC(count, data) (BDT_OWN | BDT_DTS \
103 | ((data) ? BDT_DATA1 : BDT_DATA0) \
106 #define index(endpoint, tx, odd) (((endpoint) << 2) | ((tx) << 1) | (odd))
107 #define stat2bufferdescriptor(stat) (table + ((stat) >> 2))
111 // ----- Structs -----
113 // buffer descriptor table
124 uint8_t bmRequestType;
127 uint16_t wRequestAndType;
141 // ----- Variables -----
143 __attribute__ ((section(".usbdescriptortable"), used))
144 static bdt_t table[ (NUM_ENDPOINTS + 1) * 4 ];
146 static usb_packet_t *rx_first [ NUM_ENDPOINTS ];
147 static usb_packet_t *rx_last [ NUM_ENDPOINTS ];
148 static usb_packet_t *tx_first [ NUM_ENDPOINTS ];
149 static usb_packet_t *tx_last [ NUM_ENDPOINTS ];
150 uint16_t usb_rx_byte_count_data[ NUM_ENDPOINTS ];
152 static uint8_t tx_state[NUM_ENDPOINTS];
154 // SETUP always uses a DATA0 PID for the data field of the SETUP transaction.
155 // transactions in the data phase start with DATA1 and toggle (figure 8-12, USB1.1)
156 // Status stage uses a DATA1 PID.
158 static uint8_t ep0_rx0_buf[EP0_SIZE] __attribute__ ((aligned (4)));
159 static uint8_t ep0_rx1_buf[EP0_SIZE] __attribute__ ((aligned (4)));
160 static const uint8_t *ep0_tx_ptr = NULL;
161 static uint16_t ep0_tx_len;
162 static uint8_t ep0_tx_bdt_bank = 0;
163 static uint8_t ep0_tx_data_toggle = 0;
164 uint8_t usb_rx_memory_needed = 0;
166 volatile uint8_t usb_configuration = 0;
167 volatile uint8_t usb_reboot_timer = 0;
169 static uint8_t reply_buffer[8];
171 static uint8_t power_neg_delay;
172 static uint32_t power_neg_time;
176 // ----- Functions -----
178 static void endpoint0_stall()
180 #ifdef UART_DEBUG_UNKNOWN
183 USB0_ENDPT0 = USB_ENDPT_EPSTALL | USB_ENDPT_EPRXEN | USB_ENDPT_EPTXEN | USB_ENDPT_EPHSHK;
186 static void endpoint0_transmit( const void *data, uint32_t len )
188 table[index(0, TX, ep0_tx_bdt_bank)].addr = (void *)data;
189 table[index(0, TX, ep0_tx_bdt_bank)].desc = BDT_DESC(len, ep0_tx_data_toggle);
190 ep0_tx_data_toggle ^= 1;
191 ep0_tx_bdt_bank ^= 1;
194 // Used to check any USB state changes that may not have a proper interrupt
195 // Called once per scan loop, should take minimal processing time or it may affect other modules
196 void usb_device_check()
198 // Check to see if we're still waiting for the next USB request after Get Configuration Descriptor
199 // If still waiting, restart the USB initialization with a lower power requirement
200 if ( power_neg_delay )
202 // Check if 100 ms has elapsed
203 if ( systick_millis_count - power_neg_time > 100 )
206 // The value set is in increments of 2 mA
207 // So 50 * 2 mA = 100 mA
208 // XXX Currently only transitions to 100 mA
209 // It may be possible to transition down again to 20 mA
214 usb_configuration = 0; // Clear USB configuration if we have one
215 USB0_CONTROL = 0; // Disable D+ Pullup to simulate disconnect
216 delay(10); // Delay is necessary to simulate disconnect
222 static void usb_setup()
224 const uint8_t *data = NULL;
225 uint32_t datalen = 0;
226 const usb_descriptor_list_t *list;
228 volatile uint8_t *reg;
233 // If another request is made, disable the power negotiation check
234 // See GET_DESCRIPTOR - Configuration
235 if ( power_neg_delay )
240 switch ( setup.wRequestAndType )
242 case 0x0500: // SET_ADDRESS
245 case 0x0900: // SET_CONFIGURATION
247 print("CONFIGURE - ");
249 usb_configuration = setup.wValue;
250 Output_Available = usb_configuration;
252 cfg = usb_endpoint_config_table;
254 // Now configured so we can utilize bMaxPower now
255 Output_update_usb_current( *usb_bMaxPower * 2 );
257 // clear all BDT entries, free any allocated memory...
258 for ( i = 4; i < ( NUM_ENDPOINTS + 1) * 4; i++ )
260 if ( table[i].desc & BDT_OWN )
262 usb_free( (usb_packet_t *)((uint8_t *)(table[ i ].addr) - 8) );
265 // free all queued packets
266 for ( i = 0; i < NUM_ENDPOINTS; i++ )
276 rx_first[ i ] = NULL;
285 tx_first[ i ] = NULL;
287 usb_rx_byte_count_data[i] = 0;
289 switch ( tx_state[ i ] )
291 case TX_STATE_EVEN_FREE:
292 case TX_STATE_NONE_FREE_EVEN_FIRST:
293 tx_state[ i ] = TX_STATE_BOTH_FREE_EVEN_FIRST;
295 case TX_STATE_ODD_FREE:
296 case TX_STATE_NONE_FREE_ODD_FIRST:
297 tx_state[ i ] = TX_STATE_BOTH_FREE_ODD_FIRST;
303 usb_rx_memory_needed = 0;
304 for ( i = 1; i <= NUM_ENDPOINTS; i++ )
309 if ( epconf & USB_ENDPT_EPRXEN )
315 table[ index( i, RX, EVEN ) ].addr = p->buf;
316 table[ index( i, RX, EVEN ) ].desc = BDT_DESC( 64, 0 );
320 table[ index( i, RX, EVEN ) ].desc = 0;
321 usb_rx_memory_needed++;
326 table[ index( i, RX, ODD ) ].addr = p->buf;
327 table[ index( i, RX, ODD ) ].desc = BDT_DESC( 64, 1 );
331 table[ index( i, RX, ODD ) ].desc = 0;
332 usb_rx_memory_needed++;
335 table[ index( i, TX, EVEN ) ].desc = 0;
336 table[ index( i, TX, ODD ) ].desc = 0;
340 case 0x0880: // GET_CONFIGURATION
341 reply_buffer[0] = usb_configuration;
346 case 0x0080: // GET_STATUS (device)
353 case 0x0082: // GET_STATUS (endpoint)
354 if ( setup.wIndex > NUM_ENDPOINTS )
356 // TODO: do we need to handle IN vs OUT here?
362 if ( *(uint8_t *)(&USB0_ENDPT0 + setup.wIndex * 4) & 0x02 )
368 case 0x0100: // CLEAR_FEATURE (device)
369 switch ( setup.wValue )
371 // CLEAR_FEATURE(DEVICE_REMOTE_WAKEUP)
372 // See SET_FEATURE(DEVICE_REMOTE_WAKEUP) for details
377 warn_msg("SET_FEATURE - Device wValue(");
378 printHex( setup.wValue );
383 case 0x0101: // CLEAR_FEATURE (interface)
384 // TODO: Currently ignoring, perhaps useful? -HaaTa
385 warn_msg("CLEAR_FEATURE - Interface wValue(");
386 printHex( setup.wValue );
388 printHex( setup.wIndex );
393 case 0x0102: // CLEAR_FEATURE (endpoint)
394 i = setup.wIndex & 0x7F;
395 if ( i > NUM_ENDPOINTS || setup.wValue != 0 )
400 (*(uint8_t *)(&USB0_ENDPT0 + setup.wIndex * 4)) &= ~0x02;
401 // TODO: do we need to clear the data toggle here?
404 case 0x0300: // SET_FEATURE (device)
405 switch ( setup.wValue )
407 // SET_FEATURE(DEVICE_REMOTE_WAKEUP)
408 // XXX: Only used to confirm Remote Wake
409 // Used on Mac OSX and Windows not on Linux
410 // Good post on the behaviour:
411 // http://community.silabs.com/t5/8-bit-MCU/Remote-wakeup-HID/m-p/74957#M30802
416 warn_msg("SET_FEATURE - Device wValue(");
417 printHex( setup.wValue );
422 case 0x0301: // SET_FEATURE (interface)
423 // TODO: Currently ignoring, perhaps useful? -HaaTa
424 warn_msg("SET_FEATURE - Interface wValue(");
425 printHex( setup.wValue );
427 printHex( setup.wIndex );
432 case 0x0302: // SET_FEATURE (endpoint)
433 i = setup.wIndex & 0x7F;
434 if ( i > NUM_ENDPOINTS || setup.wValue != 0 )
436 // TODO: do we need to handle IN vs OUT here?
440 (*(uint8_t *)(&USB0_ENDPT0 + setup.wIndex * 4)) |= 0x02;
441 // TODO: do we need to clear the data toggle here?
444 case 0x0680: // GET_DESCRIPTOR
448 printHex( setup.wValue );
451 for ( list = usb_descriptor_list; 1; list++ )
453 if ( list->addr == NULL )
455 if ( setup.wValue == list->wValue && setup.wIndex == list->wIndex )
458 if ( (setup.wValue >> 8) == 3 )
460 // for string descriptors, use the descriptor's
461 // length field, allowing runtime configured
463 datalen = *(list->addr);
467 datalen = list->length;
470 // XXX Power negotiation hack -HaaTa
471 // Some devices such as the Apple Ipad do not support bMaxPower greater than 100 mA
472 // However, there is no provision in the basic USB 2.0 stack for power negotiation
473 // To get around this:
474 // * Attempt to set bMaxPower to 500 mA first
475 // * If more than 100 ms passes since retrieving a Get Configuration Descriptor
476 // (Descriptor with bMaxPower in it)
477 // * Change usb_bMaxPower to 50 (100 mA)
478 // * Restart the USB init process
479 // According to notes online, it says that some Apple devices can only do 20 mA
480 // However, in my testing this hasn't been the case
481 // (you can also draw as much current as you want if you just lie in the descriptor :P)
482 // If this becomes an issue we can use this hack a second time to negotiate down to 20 mA
483 // (which should be fine for just the mcu)
484 if ( setup.wValue == 0x0200 && setup.wIndex == 0x0 )
487 power_neg_time = systick_millis_count;
491 print("Desc found, ");
492 printHex32( (uint32_t)data );
496 printHex_op( data[0], 2 );
497 printHex_op( data[1], 2 );
498 printHex_op( data[2], 2 );
499 printHex_op( data[3], 2 );
500 printHex_op( data[4], 2 );
501 printHex_op( data[5], 2 );
508 print( "desc: not found" NL );
513 case 0x2221: // CDC_SET_CONTROL_LINE_STATE
514 usb_cdc_line_rtsdtr = setup.wValue;
515 //serial_print("set control line state\n");
518 case 0x21A1: // CDC_GET_LINE_CODING
519 data = (uint8_t*)usb_cdc_line_coding;
520 datalen = sizeof( usb_cdc_line_coding );
523 case 0x2021: // CDC_SET_LINE_CODING
525 //serial_print("set coding, waiting...\n");
528 case 0x0921: // HID SET_REPORT
530 switch ( setup.wIndex & 0xFF )
532 // Keyboard Interface
533 case KEYBOARD_INTERFACE:
535 // NKRO Keyboard Interface
536 case NKRO_KEYBOARD_INTERFACE:
539 warn_msg("Unknown interface - ");
540 printHex( setup.wIndex );
548 case 0x01A1: // HID GET_REPORT
550 print("GET_REPORT - ");
551 printHex( setup.wIndex );
554 // Search through descriptors returning necessary info
555 for ( list = usb_descriptor_list; 1; list++ )
557 if ( list->addr == NULL )
559 if ( list->wValue != 0x2200 )
561 if ( setup.wIndex == list->wIndex )
564 datalen = list->length;
571 case 0x0A21: // HID SET_IDLE
573 print("SET_IDLE - ");
574 printHex( setup.wValue );
577 USBKeys_Idle_Config = (setup.wValue >> 8);
578 USBKeys_Idle_Count = 0;
581 case 0x0B21: // HID SET_PROTOCOL
583 print("SET_PROTOCOL - ");
584 printHex( setup.wValue );
586 printHex( setup.wValue & 0xFF );
589 USBKeys_Protocol = setup.wValue & 0xFF; // 0 - Boot Mode, 1 - NKRO Mode
594 #ifdef UART_DEBUG_UNKNOWN
603 print("setup send ");
604 printHex32( (uint32_t)data );
606 for ( uint8_t c = 0; c < datalen; c++ )
616 if ( datalen > setup.wLength )
617 datalen = setup.wLength;
620 if ( size > EP0_SIZE )
623 endpoint0_transmit(data, size);
627 // See if transmit has finished
628 if ( datalen == 0 && size < EP0_SIZE )
632 if ( size > EP0_SIZE )
634 endpoint0_transmit(data, size);
638 // See if transmit has finished
639 if ( datalen == 0 && size < EP0_SIZE )
642 // Save rest of transfer for later? XXX
644 ep0_tx_len = datalen;
648 //A bulk endpoint's toggle sequence is initialized to DATA0 when the endpoint
649 //experiences any configuration event (configuration events are explained in
650 //Sections 9.1.1.5 and 9.4.5).
652 //Configuring a device or changing an alternate setting causes all of the status
653 //and configuration values associated with endpoints in the affected interfaces
654 //to be set to their default values. This includes setting the data toggle of
655 //any endpoint using data toggles to the value DATA0.
657 //For endpoints using data toggle, regardless of whether an endpoint has the
658 //Halt feature set, a ClearFeature(ENDPOINT_HALT) request always results in the
659 //data toggle being reinitialized to DATA0.
661 static void usb_control( uint32_t stat )
671 b = stat2bufferdescriptor( stat );
672 pid = BDT_PID( b->desc );
684 case 0x0D: // Setup received from host
685 //serial_print("PID=Setup\n");
686 //if (count != 8) ; // panic?
687 // grab the 8 byte setup info
688 setup.word1 = *(uint32_t *)(buf);
689 setup.word2 = *(uint32_t *)(buf + 4);
691 // give the buffer back
692 b->desc = BDT_DESC( EP0_SIZE, DATA1 );
693 //table[index(0, RX, EVEN)].desc = BDT_DESC(EP0_SIZE, 1);
694 //table[index(0, RX, ODD)].desc = BDT_DESC(EP0_SIZE, 1);
696 // clear any leftover pending IN transactions
698 if ( ep0_tx_data_toggle )
701 //if (table[index(0, TX, EVEN)].desc & 0x80) {
702 //serial_print("leftover tx even\n");
704 //if (table[index(0, TX, ODD)].desc & 0x80) {
705 //serial_print("leftover tx odd\n");
707 table[index(0, TX, EVEN)].desc = 0;
708 table[index(0, TX, ODD)].desc = 0;
709 // first IN after Setup is always DATA1
710 ep0_tx_data_toggle = 1;
712 #ifdef UART_DEBUG_UNKNOWN
713 print("bmRequestType:");
714 printHex(setup.bmRequestType);
715 print(", bRequest:");
716 printHex(setup.bRequest);
718 printHex(setup.wValue);
720 printHex(setup.wIndex);
722 printHex(setup.wLength);
724 printHex32(setup.word1);
726 printHex32(setup.word2);
729 // actually "do" the setup request
731 // unfreeze the USB, now that we're ready
732 USB0_CTL = USB_CTL_USBENSOFEN; // clear TXSUSPENDTOKENBUSY bit
735 case 0x01: // OUT transaction received from host
737 #ifdef UART_DEBUG_UNKNOWN
738 print("PID=OUT wRequestAndType:");
739 printHex(setup.wRequestAndType);
741 printHex(setup.wValue);
743 printHex(setup.wIndex);
745 printHex(setup.wLength);
747 printHex32(setup.word1);
749 printHex32(setup.word2);
754 if ( setup.wRequestAndType == 0x2021 /*CDC_SET_LINE_CODING*/ )
757 uint8_t *dst = (uint8_t *)usb_cdc_line_coding;
758 //serial_print("set line coding ");
759 for ( i = 0; i < 7; i++ )
764 //serial_phex32(usb_cdc_line_coding[0]);
765 //serial_print("\n");
766 if ( usb_cdc_line_coding[0] == 134 )
767 usb_reboot_timer = 15;
768 endpoint0_transmit( NULL, 0 );
771 // Keyboard SET_REPORT
772 if ( setup.wRequestAndType == 0x921 && setup.wValue & 0x200 )
775 switch ( setup.wIndex & 0xFF )
777 // Keyboard Interface
778 case KEYBOARD_INTERFACE:
779 USBKeys_LEDs = buf[0];
780 endpoint0_transmit( NULL, 0 );
782 // NKRO Keyboard Interface
783 case NKRO_KEYBOARD_INTERFACE:
784 // Only use 2nd byte, first byte is the report id
785 USBKeys_LEDs = buf[1];
786 endpoint0_transmit( NULL, 0 );
789 warn_msg("Unknown interface - ");
790 printHex( setup.wIndex );
796 for ( size_t len = 0; len < setup.wLength; len++ )
798 printHex( buf[ len ] );
805 // give the buffer back
806 b->desc = BDT_DESC( EP0_SIZE, DATA1 );
809 case 0x09: // IN transaction completed to host
816 // send remaining data, if any...
821 if (size > EP0_SIZE) size = EP0_SIZE;
822 endpoint0_transmit(data, size);
825 ep0_tx_ptr = (ep0_tx_len > 0 || size == EP0_SIZE) ? data : NULL;
828 if ( setup.bRequest == 5 && setup.bmRequestType == 0 )
832 print("set address: ");
833 printHex(setup.wValue);
836 USB0_ADDR = setup.wValue;
843 print("PID=unknown:");
849 USB0_CTL = USB_CTL_USBENSOFEN; // clear TXSUSPENDTOKENBUSY bit
852 usb_packet_t *usb_rx( uint32_t endpoint )
857 if ( endpoint >= NUM_ENDPOINTS )
860 ret = rx_first[endpoint];
862 rx_first[ endpoint ] = ret->next;
863 usb_rx_byte_count_data[ endpoint ] -= ret->len;
865 //serial_print("rx, epidx=");
866 //serial_phex(endpoint);
867 //serial_print(", packet=");
868 //serial_phex32(ret);
869 //serial_print("\n");
873 static uint32_t usb_queue_byte_count( const usb_packet_t *p )
878 for ( ; p; p = p->next )
886 uint32_t usb_tx_byte_count( uint32_t endpoint )
889 if ( endpoint >= NUM_ENDPOINTS )
891 return usb_queue_byte_count( tx_first[ endpoint ] );
894 uint32_t usb_tx_packet_count( uint32_t endpoint )
896 const usb_packet_t *p;
900 if ( endpoint >= NUM_ENDPOINTS )
903 for ( p = tx_first[ endpoint ]; p; p = p->next )
910 // Called from usb_free, but only when usb_rx_memory_needed > 0, indicating
911 // receive endpoints are starving for memory. The intention is to give
912 // endpoints needing receive memory priority over the user's code, which is
913 // likely calling usb_malloc to obtain memory for transmitting. When the
914 // user is creating data very quickly, their consumption could starve reception
915 // without this prioritization. The packet buffer (input) is assigned to the
916 // first endpoint needing memory.
918 void usb_rx_memory( usb_packet_t *packet )
920 //print("USB RX MEMORY");
924 cfg = usb_endpoint_config_table;
925 //serial_print("rx_mem:");
927 for ( i = 1; i <= NUM_ENDPOINTS; i++ )
929 if ( *cfg++ & USB_ENDPT_EPRXEN )
931 if ( table[ index( i, RX, EVEN ) ].desc == 0 )
933 table[ index( i, RX, EVEN ) ].addr = packet->buf;
934 table[ index( i, RX, EVEN ) ].desc = BDT_DESC( 64, 0 );
935 usb_rx_memory_needed--;
938 //serial_print(",even\n");
941 if ( table[ index( i, RX, ODD ) ].desc == 0 )
943 table[ index( i, RX, ODD ) ].addr = packet->buf;
944 table[ index( i, RX, ODD ) ].desc = BDT_DESC( 64, 1 );
945 usb_rx_memory_needed--;
948 //serial_print(",odd\n");
954 // we should never reach this point. If we get here, it means
955 // usb_rx_memory_needed was set greater than zero, but no memory
956 // was actually needed.
957 usb_rx_memory_needed = 0;
962 //#define index(endpoint, tx, odd) (((endpoint) << 2) | ((tx) << 1) | (odd))
963 //#define stat2bufferdescriptor(stat) (table + ((stat) >> 2))
965 void usb_tx( uint32_t endpoint, usb_packet_t *packet )
967 // Since we are transmitting data, USB will be brought out of sleep/suspend
968 // if it's in that state
969 // Use the currently set descriptor value
970 Output_update_usb_current( *usb_bMaxPower * 2 );
972 bdt_t *b = &table[ index( endpoint, TX, EVEN ) ];
976 if ( endpoint >= NUM_ENDPOINTS )
979 //serial_print("txstate=");
980 //serial_phex(tx_state[ endpoint ]);
981 //serial_print("\n");
982 switch ( tx_state[ endpoint ] )
984 case TX_STATE_BOTH_FREE_EVEN_FIRST:
985 next = TX_STATE_ODD_FREE;
987 case TX_STATE_BOTH_FREE_ODD_FIRST:
989 next = TX_STATE_EVEN_FREE;
991 case TX_STATE_EVEN_FREE:
992 next = TX_STATE_NONE_FREE_ODD_FIRST;
994 case TX_STATE_ODD_FREE:
996 next = TX_STATE_NONE_FREE_EVEN_FIRST;
999 if (tx_first[ endpoint ] == NULL)
1001 tx_first[ endpoint ] = packet;
1005 tx_last[ endpoint ]->next = packet;
1007 tx_last[ endpoint ] = packet;
1012 tx_state[ endpoint ] = next;
1013 b->addr = packet->buf;
1014 b->desc = BDT_DESC( packet->len, ((uint32_t)b & 8) ? DATA1 : DATA0 );
1019 void usb_device_reload()
1022 // Kiibohd mk20dx256vlh7
1023 #if defined(_mk20dx128vlf5_) || defined(_mk20dx256vlh7_)
1024 // Copies variable into the VBAT register, must be identical to the variable in the bootloader to jump to the bootloader flash mode
1025 for ( int pos = 0; pos < sizeof(sys_reset_to_loader_magic); pos++ )
1026 (&VBAT)[ pos ] = sys_reset_to_loader_magic[ pos ];
1029 // Teensy 3.0 and 3.1
1031 asm volatile("bkpt");
1038 uint8_t status, stat, t;
1040 //serial_print("isr");
1041 //status = USB0_ISTAT;
1042 //serial_phex(status);
1043 //serial_print("\n");
1045 status = USB0_ISTAT;
1047 print("USB ISR STATUS: ");
1052 if ( (status & USB_INTEN_SOFTOKEN /* 04 */ ) )
1054 if ( usb_configuration )
1056 t = usb_reboot_timer;
1059 usb_reboot_timer = --t;
1061 usb_device_reload();
1065 t = usb_cdc_transmit_flush_timer;
1068 usb_cdc_transmit_flush_timer = --t;
1070 usb_serial_flush_callback();
1074 USB0_ISTAT = USB_INTEN_SOFTOKEN;
1077 if ( (status & USB_ISTAT_TOKDNE /* 08 */ ) )
1081 //serial_print("token: ep=");
1082 //serial_phex(stat >> 4);
1083 //serial_print(stat & 0x08 ? ",tx" : ",rx");
1084 //serial_print(stat & 0x04 ? ",odd\n" : ",even\n");
1085 endpoint = stat >> 4;
1086 if ( endpoint == 0 )
1088 usb_control( stat );
1092 bdt_t *b = stat2bufferdescriptor(stat);
1093 usb_packet_t *packet = (usb_packet_t *)((uint8_t *)(b->addr) - 8);
1095 serial_print("ep:");
1096 serial_phex(endpoint);
1097 serial_print(", pid:");
1098 serial_phex(BDT_PID(b->desc));
1099 serial_print(((uint32_t)b & 8) ? ", odd" : ", even");
1100 serial_print(", count:");
1101 serial_phex(b->desc >> 16);
1104 endpoint--; // endpoint is index to zero-based arrays
1109 packet = tx_first[ endpoint ];
1112 //serial_print("tx packet\n");
1113 tx_first[endpoint] = packet->next;
1114 b->addr = packet->buf;
1115 switch ( tx_state[ endpoint ] )
1117 case TX_STATE_BOTH_FREE_EVEN_FIRST:
1118 tx_state[ endpoint ] = TX_STATE_ODD_FREE;
1120 case TX_STATE_BOTH_FREE_ODD_FIRST:
1121 tx_state[ endpoint ] = TX_STATE_EVEN_FREE;
1123 case TX_STATE_EVEN_FREE:
1124 tx_state[ endpoint ] = TX_STATE_NONE_FREE_ODD_FIRST;
1126 case TX_STATE_ODD_FREE:
1127 tx_state[ endpoint ] = TX_STATE_NONE_FREE_EVEN_FIRST;
1132 b->desc = BDT_DESC( packet->len, ((uint32_t)b & 8) ? DATA1 : DATA0 );
1134 //serial_print("tx no packet\n");
1135 switch ( tx_state[ endpoint ] )
1137 case TX_STATE_BOTH_FREE_EVEN_FIRST:
1138 case TX_STATE_BOTH_FREE_ODD_FIRST:
1140 case TX_STATE_EVEN_FREE:
1141 tx_state[ endpoint ] = TX_STATE_BOTH_FREE_EVEN_FIRST;
1143 case TX_STATE_ODD_FREE:
1144 tx_state[ endpoint ] = TX_STATE_BOTH_FREE_ODD_FIRST;
1147 tx_state[ endpoint ] = ((uint32_t)b & 8)
1149 : TX_STATE_EVEN_FREE;
1156 packet->len = b->desc >> 16;
1157 if ( packet->len > 0 )
1160 packet->next = NULL;
1161 if ( rx_first[ endpoint ] == NULL )
1163 //serial_print("rx 1st, epidx=");
1164 //serial_phex(endpoint);
1165 //serial_print(", packet=");
1166 //serial_phex32((uint32_t)packet);
1167 //serial_print("\n");
1168 rx_first[ endpoint ] = packet;
1172 //serial_print("rx Nth, epidx=");
1173 //serial_phex(endpoint);
1174 //serial_print(", packet=");
1175 //serial_phex32((uint32_t)packet);
1176 //serial_print("\n");
1177 rx_last[ endpoint ]->next = packet;
1179 rx_last[ endpoint ] = packet;
1180 usb_rx_byte_count_data[ endpoint ] += packet->len;
1181 // TODO: implement a per-endpoint maximum # of allocated packets
1182 // so a flood of incoming data on 1 endpoint doesn't starve
1183 // the others if the user isn't reading it regularly
1184 packet = usb_malloc();
1187 b->addr = packet->buf;
1188 b->desc = BDT_DESC( 64, ((uint32_t)b & 8) ? DATA1 : DATA0 );
1192 //serial_print("starving ");
1193 //serial_phex(endpoint + 1);
1194 //serial_print(((uint32_t)b & 8) ? ",odd\n" : ",even\n");
1196 usb_rx_memory_needed++;
1201 b->desc = BDT_DESC( 64, ((uint32_t)b & 8) ? DATA1 : DATA0 );
1209 USB0_ISTAT = USB_ISTAT_TOKDNE;
1214 if ( status & USB_ISTAT_USBRST /* 01 */ )
1216 //serial_print("reset\n");
1218 // initialize BDT toggle bits
1219 USB0_CTL = USB_CTL_ODDRST;
1220 ep0_tx_bdt_bank = 0;
1222 // set up buffers to receive Setup and OUT packets
1223 table[index( 0, RX, EVEN ) ].desc = BDT_DESC( EP0_SIZE, 0 );
1224 table[index( 0, RX, EVEN ) ].addr = ep0_rx0_buf;
1225 table[index( 0, RX, ODD ) ].desc = BDT_DESC( EP0_SIZE, 0 );
1226 table[index( 0, RX, ODD ) ].addr = ep0_rx1_buf;
1227 table[index( 0, TX, EVEN ) ].desc = 0;
1228 table[index( 0, TX, ODD ) ].desc = 0;
1230 // activate endpoint 0
1231 USB0_ENDPT0 = USB_ENDPT_EPRXEN | USB_ENDPT_EPTXEN | USB_ENDPT_EPHSHK;
1233 // clear all ending interrupts
1234 USB0_ERRSTAT = 0xFF;
1237 // set the address to zero during enumeration
1240 // enable other interrupts
1242 USB0_INTEN = USB_INTEN_TOKDNEEN |
1243 USB_INTEN_SOFTOKEN |
1246 USB_INTEN_USBRSTEN |
1249 // is this necessary?
1250 USB0_CTL = USB_CTL_USBENSOFEN;
1255 if ( (status & USB_ISTAT_STALL /* 80 */ ) )
1257 //serial_print("stall:\n");
1258 USB0_ENDPT0 = USB_ENDPT_EPRXEN | USB_ENDPT_EPTXEN | USB_ENDPT_EPHSHK;
1259 USB0_ISTAT = USB_ISTAT_STALL;
1261 if ( (status & USB_ISTAT_ERROR /* 02 */ ) )
1263 uint8_t err = USB0_ERRSTAT;
1265 //serial_print("err:");
1267 //serial_print("\n");
1268 USB0_ISTAT = USB_ISTAT_ERROR;
1271 // USB Host signalling device to enter 'sleep' state
1272 // The USB Module triggers this interrupt when it detects the bus has been idle for 3 ms
1273 if ( (status & USB_ISTAT_SLEEP /* 10 */ ) )
1275 info_print("Host has requested USB sleep/suspend state");
1276 Output_update_usb_current( 100 ); // Set to 100 mA
1277 USB0_ISTAT = USB_ISTAT_SLEEP;
1286 print("USB INIT"NL);
1289 // Clear out endpoints table
1290 for ( int i = 0; i <= NUM_ENDPOINTS * 4; i++ )
1296 // this basically follows the flowchart in the Kinetis
1297 // Quick Reference User Guide, Rev. 1, 03/2012, page 141
1299 // assume 48 MHz clock already running
1300 // SIM - enable clock
1301 SIM_SCGC4 |= SIM_SCGC4_USBOTG;
1304 USB0_USBTRC0 = USB_USBTRC_USBRESET;
1305 while ( (USB0_USBTRC0 & USB_USBTRC_USBRESET) != 0 ); // wait for reset to end
1307 // set desc table base addr
1308 USB0_BDTPAGE1 = ((uint32_t)table) >> 8;
1309 USB0_BDTPAGE2 = ((uint32_t)table) >> 16;
1310 USB0_BDTPAGE3 = ((uint32_t)table) >> 24;
1312 // clear all ISR flags
1314 USB0_ERRSTAT = 0xFF;
1315 USB0_OTGISTAT = 0xFF;
1317 USB0_USBTRC0 |= 0x40; // undocumented bit
1320 USB0_CTL = USB_CTL_USBENSOFEN;
1323 // enable reset interrupt
1324 USB0_INTEN = USB_INTEN_USBRSTEN;
1326 // enable interrupt in NVIC...
1327 NVIC_SET_PRIORITY( IRQ_USBOTG, 112 );
1328 NVIC_ENABLE_IRQ( IRQ_USBOTG );
1331 USB0_CONTROL = USB_CONTROL_DPPULLUPNONOTG;
1333 // Do not check for power negotiation delay until Get Configuration Descriptor
1334 power_neg_delay = 0;
1339 // return 0 if the USB is not configured, or the configuration
1340 // number selected by the HOST
1341 uint8_t usb_configured()
1343 return usb_configuration;