1 /* Teensyduino Core Library
2 * http://www.pjrc.com/teensy/
3 * Copyright (c) 2013 PJRC.COM, LLC.
4 * Modifications by Jacob Alexander (2013-2015)
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>
44 // ----- Defines -----
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
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
62 #define BDT_DATA1 0x40
63 #define BDT_DATA0 0x00
65 #define BDT_STALL 0x04
76 #define CLEAR_FEATURE 1
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
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
99 #define BDT_PID(n) (((n) >> 2) & 15)
101 #define BDT_DESC(count, data) (BDT_OWN | BDT_DTS \
102 | ((data) ? BDT_DATA1 : BDT_DATA0) \
105 #define index(endpoint, tx, odd) (((endpoint) << 2) | ((tx) << 1) | (odd))
106 #define stat2bufferdescriptor(stat) (table + ((stat) >> 2))
110 // ----- Structs -----
112 // buffer descriptor table
123 uint8_t bmRequestType;
126 uint16_t wRequestAndType;
140 // ----- Variables -----
142 __attribute__ ((section(".usbdescriptortable"), used))
143 static bdt_t table[ (NUM_ENDPOINTS + 1) * 4 ];
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 ];
151 static uint8_t tx_state[NUM_ENDPOINTS];
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.
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;
165 volatile uint8_t usb_configuration = 0;
166 volatile uint8_t usb_reboot_timer = 0;
168 static uint8_t reply_buffer[8];
172 // ----- Functions -----
174 static void endpoint0_stall()
176 #ifdef UART_DEBUG_UNKNOWN
179 USB0_ENDPT0 = USB_ENDPT_EPSTALL | USB_ENDPT_EPRXEN | USB_ENDPT_EPTXEN | USB_ENDPT_EPHSHK;
182 static void endpoint0_transmit( const void *data, uint32_t len )
184 table[index(0, TX, ep0_tx_bdt_bank)].addr = (void *)data;
185 table[index(0, TX, ep0_tx_bdt_bank)].desc = BDT_DESC(len, ep0_tx_data_toggle);
186 ep0_tx_data_toggle ^= 1;
187 ep0_tx_bdt_bank ^= 1;
190 static void usb_setup()
192 const uint8_t *data = NULL;
193 uint32_t datalen = 0;
194 const usb_descriptor_list_t *list;
196 volatile uint8_t *reg;
201 switch ( setup.wRequestAndType )
203 case 0x0500: // SET_ADDRESS
206 case 0x0900: // SET_CONFIGURATION
208 print("CONFIGURE - ");
210 usb_configuration = setup.wValue;
211 Output_Available = usb_configuration;
213 cfg = usb_endpoint_config_table;
214 // clear all BDT entries, free any allocated memory...
215 for ( i = 4; i < ( NUM_ENDPOINTS + 1) * 4; i++ )
217 if ( table[i].desc & BDT_OWN )
219 usb_free( (usb_packet_t *)((uint8_t *)(table[ i ].addr) - 8) );
222 // free all queued packets
223 for ( i = 0; i < NUM_ENDPOINTS; i++ )
233 rx_first[ i ] = NULL;
242 tx_first[ i ] = NULL;
244 usb_rx_byte_count_data[i] = 0;
246 switch ( tx_state[ i ] )
248 case TX_STATE_EVEN_FREE:
249 case TX_STATE_NONE_FREE_EVEN_FIRST:
250 tx_state[ i ] = TX_STATE_BOTH_FREE_EVEN_FIRST;
252 case TX_STATE_ODD_FREE:
253 case TX_STATE_NONE_FREE_ODD_FIRST:
254 tx_state[ i ] = TX_STATE_BOTH_FREE_ODD_FIRST;
260 usb_rx_memory_needed = 0;
261 for ( i = 1; i <= NUM_ENDPOINTS; i++ )
266 if ( epconf & USB_ENDPT_EPRXEN )
272 table[ index( i, RX, EVEN ) ].addr = p->buf;
273 table[ index( i, RX, EVEN ) ].desc = BDT_DESC( 64, 0 );
277 table[ index( i, RX, EVEN ) ].desc = 0;
278 usb_rx_memory_needed++;
283 table[ index( i, RX, ODD ) ].addr = p->buf;
284 table[ index( i, RX, ODD ) ].desc = BDT_DESC( 64, 1 );
288 table[ index( i, RX, ODD ) ].desc = 0;
289 usb_rx_memory_needed++;
292 table[ index( i, TX, EVEN ) ].desc = 0;
293 table[ index( i, TX, ODD ) ].desc = 0;
297 case 0x0880: // GET_CONFIGURATION
298 reply_buffer[0] = usb_configuration;
303 case 0x0080: // GET_STATUS (device)
310 case 0x0082: // GET_STATUS (endpoint)
311 if ( setup.wIndex > NUM_ENDPOINTS )
313 // TODO: do we need to handle IN vs OUT here?
319 if ( *(uint8_t *)(&USB0_ENDPT0 + setup.wIndex * 4) & 0x02 )
325 case 0x0100: // CLEAR_FEATURE (device)
326 case 0x0101: // CLEAR_FEATURE (interface)
327 // TODO: Currently ignoring, perhaps useful? -HaaTa
328 warn_print("CLEAR_FEATURE - Device/Interface");
332 case 0x0102: // CLEAR_FEATURE (interface)
333 i = setup.wIndex & 0x7F;
334 if ( i > NUM_ENDPOINTS || setup.wValue != 0 )
339 warn_print("CLEAR_FEATURE - Interface");
340 //(*(uint8_t *)(&USB0_ENDPT0 + setup.wIndex * 4)) &= ~0x02;
341 // TODO: do we need to clear the data toggle here?
344 // FIXME: Clearing causes keyboard to freeze, likely an invalid clear
345 // XXX: Ignoring seems to work, though this may not be the ideal behaviour -HaaTa
349 case 0x0300: // SET_FEATURE (device)
350 case 0x0301: // SET_FEATURE (interface)
351 // TODO: Currently ignoring, perhaps useful? -HaaTa
352 warn_print("SET_FEATURE");
356 case 0x0302: // SET_FEATURE (endpoint)
357 i = setup.wIndex & 0x7F;
358 if ( i > NUM_ENDPOINTS || setup.wValue != 0 )
360 // TODO: do we need to handle IN vs OUT here?
364 (*(uint8_t *)(&USB0_ENDPT0 + setup.wIndex * 4)) |= 0x02;
365 // TODO: do we need to clear the data toggle here?
368 case 0x0680: // GET_DESCRIPTOR
372 printHex( setup.wValue );
375 for ( list = usb_descriptor_list; 1; list++ )
377 if ( list->addr == NULL )
379 if ( setup.wValue == list->wValue && setup.wIndex == list->wIndex )
382 if ( (setup.wValue >> 8) == 3 )
384 // for string descriptors, use the descriptor's
385 // length field, allowing runtime configured
387 datalen = *(list->addr);
391 datalen = list->length;
394 print("Desc found, ");
395 printHex32( (uint32_t)data );
399 printHex_op( data[0], 2 );
400 printHex_op( data[1], 2 );
401 printHex_op( data[2], 2 );
402 printHex_op( data[3], 2 );
403 printHex_op( data[4], 2 );
404 printHex_op( data[5], 2 );
411 print( "desc: not found" NL );
416 case 0x2221: // CDC_SET_CONTROL_LINE_STATE
417 usb_cdc_line_rtsdtr = setup.wValue;
418 //serial_print("set control line state\n");
421 case 0x21A1: // CDC_GET_LINE_CODING
422 data = (uint8_t*)usb_cdc_line_coding;
423 datalen = sizeof( usb_cdc_line_coding );
426 case 0x2021: // CDC_SET_LINE_CODING
428 //serial_print("set coding, waiting...\n");
431 case 0x0921: // HID SET_REPORT
433 warn_msg("SET_REPORT - ");
434 printHex( setup.wValue );
436 printHex( setup.wValue & 0xFF );
439 USBKeys_LEDs = setup.wValue & 0xFF;
441 // Must be stall for some reason... -HaaTa
445 case 0x01A1: // HID GET_REPORT
447 print("GET_REPORT - ");
448 printHex( setup.wIndex );
451 // Search through descriptors returning necessary info
452 for ( list = usb_descriptor_list; 1; list++ )
454 if ( list->addr == NULL )
456 if ( list->wValue != 0x2200 )
458 if ( setup.wIndex == list->wIndex )
461 datalen = list->length;
468 case 0x0A21: // HID SET_IDLE
470 print("SET_IDLE - ");
471 printHex( setup.wValue );
474 USBKeys_Idle_Config = (setup.wValue >> 8);
475 USBKeys_Idle_Count = 0;
478 case 0x0B21: // HID SET_PROTOCOL
480 print("SET_PROTOCOL - ");
481 printHex( setup.wValue );
483 printHex( setup.wValue & 0xFF );
486 USBKeys_Protocol = setup.wValue & 0xFF; // 0 - Boot Mode, 1 - NKRO Mode
491 #ifdef UART_DEBUG_UNKNOWN
500 print("setup send ");
501 printHex32( (uint32_t)data );
503 for ( uint8_t c = 0; c < datalen; c++ )
513 if ( datalen > setup.wLength )
514 datalen = setup.wLength;
517 if ( size > EP0_SIZE )
520 endpoint0_transmit(data, size);
524 // See if transmit has finished
525 if ( datalen == 0 && size < EP0_SIZE )
529 if ( size > EP0_SIZE )
531 endpoint0_transmit(data, size);
535 // See if transmit has finished
536 if ( datalen == 0 && size < EP0_SIZE )
539 // Save rest of transfer for later? XXX
541 ep0_tx_len = datalen;
545 //A bulk endpoint's toggle sequence is initialized to DATA0 when the endpoint
546 //experiences any configuration event (configuration events are explained in
547 //Sections 9.1.1.5 and 9.4.5).
549 //Configuring a device or changing an alternate setting causes all of the status
550 //and configuration values associated with endpoints in the affected interfaces
551 //to be set to their default values. This includes setting the data toggle of
552 //any endpoint using data toggles to the value DATA0.
554 //For endpoints using data toggle, regardless of whether an endpoint has the
555 //Halt feature set, a ClearFeature(ENDPOINT_HALT) request always results in the
556 //data toggle being reinitialized to DATA0.
558 static void usb_control( uint32_t stat )
568 b = stat2bufferdescriptor( stat );
569 pid = BDT_PID( b->desc );
581 case 0x0D: // Setup received from host
582 //serial_print("PID=Setup\n");
583 //if (count != 8) ; // panic?
584 // grab the 8 byte setup info
585 setup.word1 = *(uint32_t *)(buf);
586 setup.word2 = *(uint32_t *)(buf + 4);
588 // give the buffer back
589 b->desc = BDT_DESC( EP0_SIZE, DATA1 );
590 //table[index(0, RX, EVEN)].desc = BDT_DESC(EP0_SIZE, 1);
591 //table[index(0, RX, ODD)].desc = BDT_DESC(EP0_SIZE, 1);
593 // clear any leftover pending IN transactions
595 if ( ep0_tx_data_toggle )
598 //if (table[index(0, TX, EVEN)].desc & 0x80) {
599 //serial_print("leftover tx even\n");
601 //if (table[index(0, TX, ODD)].desc & 0x80) {
602 //serial_print("leftover tx odd\n");
604 table[index(0, TX, EVEN)].desc = 0;
605 table[index(0, TX, ODD)].desc = 0;
606 // first IN after Setup is always DATA1
607 ep0_tx_data_toggle = 1;
609 #ifdef UART_DEBUG_UNKNOWN
610 print("bmRequestType:");
611 printHex(setup.bmRequestType);
612 print(", bRequest:");
613 printHex(setup.bRequest);
615 printHex(setup.wValue);
617 printHex(setup.wIndex);
619 printHex(setup.wLength);
622 // actually "do" the setup request
624 // unfreeze the USB, now that we're ready
625 USB0_CTL = USB_CTL_USBENSOFEN; // clear TXSUSPENDTOKENBUSY bit
628 case 0x01: // OUT transaction received from host
634 if ( setup.wRequestAndType == 0x2021 /*CDC_SET_LINE_CODING*/ )
637 uint8_t *dst = (uint8_t *)usb_cdc_line_coding;
638 //serial_print("set line coding ");
639 for ( i = 0; i < 7; i++ )
644 //serial_phex32(usb_cdc_line_coding[0]);
645 //serial_print("\n");
646 if ( usb_cdc_line_coding[0] == 134 )
647 usb_reboot_timer = 15;
648 endpoint0_transmit( NULL, 0 );
651 // Keyboard Interface
652 if ( setup.word1 == 0x02000921 && setup.word2 == ( (1<<16) | KEYBOARD_INTERFACE ) )
654 USBKeys_LEDs = buf[0];
655 endpoint0_transmit( NULL, 0 );
657 // NKRO Keyboard Interface
658 if ( setup.word1 == 0x02000921 && setup.word2 == ( (1<<16) | NKRO_KEYBOARD_INTERFACE ) )
660 USBKeys_LEDs = buf[0];
661 endpoint0_transmit( NULL, 0 );
664 // give the buffer back
665 b->desc = BDT_DESC( EP0_SIZE, DATA1 );
668 case 0x09: // IN transaction completed to host
675 // send remaining data, if any...
680 if (size > EP0_SIZE) size = EP0_SIZE;
681 endpoint0_transmit(data, size);
684 ep0_tx_ptr = (ep0_tx_len > 0 || size == EP0_SIZE) ? data : NULL;
687 if ( setup.bRequest == 5 && setup.bmRequestType == 0 )
691 print("set address: ");
692 printHex(setup.wValue);
695 USB0_ADDR = setup.wValue;
702 print("PID=unknown:");
708 USB0_CTL = USB_CTL_USBENSOFEN; // clear TXSUSPENDTOKENBUSY bit
711 usb_packet_t *usb_rx( uint32_t endpoint )
716 if ( endpoint >= NUM_ENDPOINTS )
719 ret = rx_first[endpoint];
721 rx_first[ endpoint ] = ret->next;
722 usb_rx_byte_count_data[ endpoint ] -= ret->len;
724 //serial_print("rx, epidx=");
725 //serial_phex(endpoint);
726 //serial_print(", packet=");
727 //serial_phex32(ret);
728 //serial_print("\n");
732 static uint32_t usb_queue_byte_count( const usb_packet_t *p )
737 for ( ; p; p = p->next )
745 uint32_t usb_tx_byte_count( uint32_t endpoint )
748 if ( endpoint >= NUM_ENDPOINTS )
750 return usb_queue_byte_count( tx_first[ endpoint ] );
753 uint32_t usb_tx_packet_count( uint32_t endpoint )
755 const usb_packet_t *p;
759 if ( endpoint >= NUM_ENDPOINTS )
762 for ( p = tx_first[ endpoint ]; p; p = p->next )
769 // Called from usb_free, but only when usb_rx_memory_needed > 0, indicating
770 // receive endpoints are starving for memory. The intention is to give
771 // endpoints needing receive memory priority over the user's code, which is
772 // likely calling usb_malloc to obtain memory for transmitting. When the
773 // user is creating data very quickly, their consumption could starve reception
774 // without this prioritization. The packet buffer (input) is assigned to the
775 // first endpoint needing memory.
777 void usb_rx_memory( usb_packet_t *packet )
779 //print("USB RX MEMORY");
783 cfg = usb_endpoint_config_table;
784 //serial_print("rx_mem:");
786 for ( i = 1; i <= NUM_ENDPOINTS; i++ )
788 if ( *cfg++ & USB_ENDPT_EPRXEN )
790 if ( table[ index( i, RX, EVEN ) ].desc == 0 )
792 table[ index( i, RX, EVEN ) ].addr = packet->buf;
793 table[ index( i, RX, EVEN ) ].desc = BDT_DESC( 64, 0 );
794 usb_rx_memory_needed--;
797 //serial_print(",even\n");
800 if ( table[ index( i, RX, ODD ) ].desc == 0 )
802 table[ index( i, RX, ODD ) ].addr = packet->buf;
803 table[ index( i, RX, ODD ) ].desc = BDT_DESC( 64, 1 );
804 usb_rx_memory_needed--;
807 //serial_print(",odd\n");
813 // we should never reach this point. If we get here, it means
814 // usb_rx_memory_needed was set greater than zero, but no memory
815 // was actually needed.
816 usb_rx_memory_needed = 0;
821 //#define index(endpoint, tx, odd) (((endpoint) << 2) | ((tx) << 1) | (odd))
822 //#define stat2bufferdescriptor(stat) (table + ((stat) >> 2))
824 void usb_tx( uint32_t endpoint, usb_packet_t *packet )
826 bdt_t *b = &table[ index( endpoint, TX, EVEN ) ];
830 if ( endpoint >= NUM_ENDPOINTS )
833 //serial_print("txstate=");
834 //serial_phex(tx_state[ endpoint ]);
835 //serial_print("\n");
836 switch ( tx_state[ endpoint ] )
838 case TX_STATE_BOTH_FREE_EVEN_FIRST:
839 next = TX_STATE_ODD_FREE;
841 case TX_STATE_BOTH_FREE_ODD_FIRST:
843 next = TX_STATE_EVEN_FREE;
845 case TX_STATE_EVEN_FREE:
846 next = TX_STATE_NONE_FREE_ODD_FIRST;
848 case TX_STATE_ODD_FREE:
850 next = TX_STATE_NONE_FREE_EVEN_FIRST;
853 if (tx_first[ endpoint ] == NULL)
855 tx_first[ endpoint ] = packet;
859 tx_last[ endpoint ]->next = packet;
861 tx_last[ endpoint ] = packet;
866 tx_state[ endpoint ] = next;
867 b->addr = packet->buf;
868 b->desc = BDT_DESC( packet->len, ((uint32_t)b & 8) ? DATA1 : DATA0 );
873 void usb_device_reload()
876 #if defined(_mk20dx128vlf5_)
878 // MCHCK Kiibohd Variant
879 // Check to see if PTA3 (has a pull-up) is connected to GND (usually via jumper)
880 // Only allow reload if the jumper is present (security)
881 GPIOA_PDDR &= ~(1<<3); // Input
882 PORTA_PCR3 = PORT_PCR_PFE | PORT_PCR_MUX(1); // Internal pull-up
885 if ( GPIOA_PDIR & (1<<3) )
888 warn_print("Security jumper not present, cancelling firmware reload...");
889 info_msg("Replace jumper on middle 2 pins, or manually press the firmware reload button.");
893 // Copies variable into the VBAT register, must be identical to the variable in the bootloader to jump to the bootloader flash mode
894 for ( int pos = 0; pos < sizeof(sys_reset_to_loader_magic); pos++ )
895 (&VBAT)[ pos ] = sys_reset_to_loader_magic[ pos ];
899 // Kiibohd mk20dx256vlh7
900 #elif defined(_mk20dx256vlh7_)
901 // Copies variable into the VBAT register, must be identical to the variable in the bootloader to jump to the bootloader flash mode
902 for ( int pos = 0; pos < sizeof(sys_reset_to_loader_magic); pos++ )
903 (&VBAT)[ pos ] = sys_reset_to_loader_magic[ pos ];
906 // Teensy 3.0 and 3.1
908 asm volatile("bkpt");
915 uint8_t status, stat, t;
917 //serial_print("isr");
918 //status = USB0_ISTAT;
919 //serial_phex(status);
920 //serial_print("\n");
924 print("USB ISR STATUS: ");
929 if ( (status & USB_INTEN_SOFTOKEN /* 04 */ ) )
931 if ( usb_configuration )
933 t = usb_reboot_timer;
936 usb_reboot_timer = --t;
942 t = usb_cdc_transmit_flush_timer;
945 usb_cdc_transmit_flush_timer = --t;
947 usb_serial_flush_callback();
951 USB0_ISTAT = USB_INTEN_SOFTOKEN;
954 if ( (status & USB_ISTAT_TOKDNE /* 08 */ ) )
958 //serial_print("token: ep=");
959 //serial_phex(stat >> 4);
960 //serial_print(stat & 0x08 ? ",tx" : ",rx");
961 //serial_print(stat & 0x04 ? ",odd\n" : ",even\n");
962 endpoint = stat >> 4;
969 bdt_t *b = stat2bufferdescriptor(stat);
970 usb_packet_t *packet = (usb_packet_t *)((uint8_t *)(b->addr) - 8);
973 serial_phex(endpoint);
974 serial_print(", pid:");
975 serial_phex(BDT_PID(b->desc));
976 serial_print(((uint32_t)b & 8) ? ", odd" : ", even");
977 serial_print(", count:");
978 serial_phex(b->desc >> 16);
981 endpoint--; // endpoint is index to zero-based arrays
986 packet = tx_first[ endpoint ];
989 //serial_print("tx packet\n");
990 tx_first[endpoint] = packet->next;
991 b->addr = packet->buf;
992 switch ( tx_state[ endpoint ] )
994 case TX_STATE_BOTH_FREE_EVEN_FIRST:
995 tx_state[ endpoint ] = TX_STATE_ODD_FREE;
997 case TX_STATE_BOTH_FREE_ODD_FIRST:
998 tx_state[ endpoint ] = TX_STATE_EVEN_FREE;
1000 case TX_STATE_EVEN_FREE:
1001 tx_state[ endpoint ] = TX_STATE_NONE_FREE_ODD_FIRST;
1003 case TX_STATE_ODD_FREE:
1004 tx_state[ endpoint ] = TX_STATE_NONE_FREE_EVEN_FIRST;
1009 b->desc = BDT_DESC( packet->len, ((uint32_t)b & 8) ? DATA1 : DATA0 );
1011 //serial_print("tx no packet\n");
1012 switch ( tx_state[ endpoint ] )
1014 case TX_STATE_BOTH_FREE_EVEN_FIRST:
1015 case TX_STATE_BOTH_FREE_ODD_FIRST:
1017 case TX_STATE_EVEN_FREE:
1018 tx_state[ endpoint ] = TX_STATE_BOTH_FREE_EVEN_FIRST;
1020 case TX_STATE_ODD_FREE:
1021 tx_state[ endpoint ] = TX_STATE_BOTH_FREE_ODD_FIRST;
1024 tx_state[ endpoint ] = ((uint32_t)b & 8)
1026 : TX_STATE_EVEN_FREE;
1033 packet->len = b->desc >> 16;
1034 if ( packet->len > 0 )
1037 packet->next = NULL;
1038 if ( rx_first[ endpoint ] == NULL )
1040 //serial_print("rx 1st, epidx=");
1041 //serial_phex(endpoint);
1042 //serial_print(", packet=");
1043 //serial_phex32((uint32_t)packet);
1044 //serial_print("\n");
1045 rx_first[ endpoint ] = packet;
1049 //serial_print("rx Nth, epidx=");
1050 //serial_phex(endpoint);
1051 //serial_print(", packet=");
1052 //serial_phex32((uint32_t)packet);
1053 //serial_print("\n");
1054 rx_last[ endpoint ]->next = packet;
1056 rx_last[ endpoint ] = packet;
1057 usb_rx_byte_count_data[ endpoint ] += packet->len;
1058 // TODO: implement a per-endpoint maximum # of allocated packets
1059 // so a flood of incoming data on 1 endpoint doesn't starve
1060 // the others if the user isn't reading it regularly
1061 packet = usb_malloc();
1064 b->addr = packet->buf;
1065 b->desc = BDT_DESC( 64, ((uint32_t)b & 8) ? DATA1 : DATA0 );
1069 //serial_print("starving ");
1070 //serial_phex(endpoint + 1);
1071 //serial_print(((uint32_t)b & 8) ? ",odd\n" : ",even\n");
1073 usb_rx_memory_needed++;
1078 b->desc = BDT_DESC( 64, ((uint32_t)b & 8) ? DATA1 : DATA0 );
1086 USB0_ISTAT = USB_ISTAT_TOKDNE;
1091 if ( status & USB_ISTAT_USBRST /* 01 */ )
1093 //serial_print("reset\n");
1095 // initialize BDT toggle bits
1096 USB0_CTL = USB_CTL_ODDRST;
1097 ep0_tx_bdt_bank = 0;
1099 // set up buffers to receive Setup and OUT packets
1100 table[index( 0, RX, EVEN ) ].desc = BDT_DESC( EP0_SIZE, 0 );
1101 table[index( 0, RX, EVEN ) ].addr = ep0_rx0_buf;
1102 table[index( 0, RX, ODD ) ].desc = BDT_DESC( EP0_SIZE, 0 );
1103 table[index( 0, RX, ODD ) ].addr = ep0_rx1_buf;
1104 table[index( 0, TX, EVEN ) ].desc = 0;
1105 table[index( 0, TX, ODD ) ].desc = 0;
1107 // activate endpoint 0
1108 USB0_ENDPT0 = USB_ENDPT_EPRXEN | USB_ENDPT_EPTXEN | USB_ENDPT_EPHSHK;
1110 // clear all ending interrupts
1111 USB0_ERRSTAT = 0xFF;
1114 // set the address to zero during enumeration
1117 // enable other interrupts
1119 USB0_INTEN = USB_INTEN_TOKDNEEN |
1120 USB_INTEN_SOFTOKEN |
1123 USB_INTEN_USBRSTEN |
1126 // is this necessary?
1127 USB0_CTL = USB_CTL_USBENSOFEN;
1132 if ( (status & USB_ISTAT_STALL /* 80 */ ) )
1134 //serial_print("stall:\n");
1135 USB0_ENDPT0 = USB_ENDPT_EPRXEN | USB_ENDPT_EPTXEN | USB_ENDPT_EPHSHK;
1136 USB0_ISTAT = USB_ISTAT_STALL;
1138 if ( (status & USB_ISTAT_ERROR /* 02 */ ) )
1140 uint8_t err = USB0_ERRSTAT;
1142 //serial_print("err:");
1144 //serial_print("\n");
1145 USB0_ISTAT = USB_ISTAT_ERROR;
1148 if ( (status & USB_ISTAT_SLEEP /* 10 */ ) )
1150 //serial_print("sleep\n");
1151 USB0_ISTAT = USB_ISTAT_SLEEP;
1160 print("USB INIT"NL);
1163 // Clear out endpoints table
1164 for ( int i = 0; i <= NUM_ENDPOINTS * 4; i++ )
1170 // this basically follows the flowchart in the Kinetis
1171 // Quick Reference User Guide, Rev. 1, 03/2012, page 141
1173 // assume 48 MHz clock already running
1174 // SIM - enable clock
1175 SIM_SCGC4 |= SIM_SCGC4_USBOTG;
1178 USB0_USBTRC0 = USB_USBTRC_USBRESET;
1179 while ( (USB0_USBTRC0 & USB_USBTRC_USBRESET) != 0 ); // wait for reset to end
1181 // set desc table base addr
1182 USB0_BDTPAGE1 = ((uint32_t)table) >> 8;
1183 USB0_BDTPAGE2 = ((uint32_t)table) >> 16;
1184 USB0_BDTPAGE3 = ((uint32_t)table) >> 24;
1186 // clear all ISR flags
1188 USB0_ERRSTAT = 0xFF;
1189 USB0_OTGISTAT = 0xFF;
1191 USB0_USBTRC0 |= 0x40; // undocumented bit
1194 USB0_CTL = USB_CTL_USBENSOFEN;
1197 // enable reset interrupt
1198 USB0_INTEN = USB_INTEN_USBRSTEN;
1200 // enable interrupt in NVIC...
1201 NVIC_SET_PRIORITY( IRQ_USBOTG, 112 );
1202 NVIC_ENABLE_IRQ( IRQ_USBOTG );
1205 USB0_CONTROL = USB_CONTROL_DPPULLUPNONOTG;
1210 // return 0 if the USB is not configured, or the configuration
1211 // number selected by the HOST
1212 uint8_t usb_configured()
1214 return usb_configuration;