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 USB0_ENDPT0 = USB_ENDPT_EPSTALL | USB_ENDPT_EPRXEN | USB_ENDPT_EPTXEN | USB_ENDPT_EPHSHK;
179 static void endpoint0_transmit( const void *data, uint32_t len )
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;
187 static void usb_setup()
189 const uint8_t *data = NULL;
190 uint32_t datalen = 0;
191 const usb_descriptor_list_t *list;
193 volatile uint8_t *reg;
198 switch ( setup.wRequestAndType )
200 case 0x0500: // SET_ADDRESS
202 case 0x0900: // SET_CONFIGURATION
204 print("CONFIGURE - ");
206 usb_configuration = setup.wValue;
207 Output_Available = usb_configuration;
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++ )
213 if ( table[i].desc & BDT_OWN )
215 usb_free( (usb_packet_t *)((uint8_t *)(table[ i ].addr) - 8) );
218 // free all queued packets
219 for ( i = 0; i < NUM_ENDPOINTS; i++ )
229 rx_first[ i ] = NULL;
238 tx_first[ i ] = NULL;
240 usb_rx_byte_count_data[i] = 0;
242 switch ( tx_state[ i ] )
244 case TX_STATE_EVEN_FREE:
245 case TX_STATE_NONE_FREE_EVEN_FIRST:
246 tx_state[ i ] = TX_STATE_BOTH_FREE_EVEN_FIRST;
248 case TX_STATE_ODD_FREE:
249 case TX_STATE_NONE_FREE_ODD_FIRST:
250 tx_state[ i ] = TX_STATE_BOTH_FREE_ODD_FIRST;
256 usb_rx_memory_needed = 0;
257 for ( i = 1; i <= NUM_ENDPOINTS; i++ )
262 if ( epconf & USB_ENDPT_EPRXEN )
268 table[ index( i, RX, EVEN ) ].addr = p->buf;
269 table[ index( i, RX, EVEN ) ].desc = BDT_DESC( 64, 0 );
273 table[ index( i, RX, EVEN ) ].desc = 0;
274 usb_rx_memory_needed++;
279 table[ index( i, RX, ODD ) ].addr = p->buf;
280 table[ index( i, RX, ODD ) ].desc = BDT_DESC( 64, 1 );
284 table[ index( i, RX, ODD ) ].desc = 0;
285 usb_rx_memory_needed++;
288 table[ index( i, TX, EVEN ) ].desc = 0;
289 table[ index( i, TX, ODD ) ].desc = 0;
292 case 0x0880: // GET_CONFIGURATION
293 reply_buffer[0] = usb_configuration;
297 case 0x0080: // GET_STATUS (device)
303 case 0x0082: // GET_STATUS (endpoint)
304 if ( setup.wIndex > NUM_ENDPOINTS )
306 // TODO: do we need to handle IN vs OUT here?
312 if ( *(uint8_t *)(&USB0_ENDPT0 + setup.wIndex * 4) & 0x02 )
317 case 0x0100: // CLEAR_FEATURE (device)
318 case 0x0101: // CLEAR_FEATURE (interface)
319 // TODO: Currently ignoring, perhaps useful? -HaaTa
322 case 0x0102: // CLEAR_FEATURE (interface)
323 i = setup.wIndex & 0x7F;
324 if ( i > NUM_ENDPOINTS || setup.wValue != 0 )
329 //(*(uint8_t *)(&USB0_ENDPT0 + setup.wIndex * 4)) &= ~0x02;
330 // TODO: do we need to clear the data toggle here?
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
337 case 0x0300: // SET_FEATURE (device)
338 case 0x0301: // SET_FEATURE (interface)
339 // TODO: Currently ignoring, perhaps useful? -HaaTa
342 case 0x0302: // SET_FEATURE (endpoint)
343 i = setup.wIndex & 0x7F;
344 if ( i > NUM_ENDPOINTS || setup.wValue != 0 )
346 // TODO: do we need to handle IN vs OUT here?
350 (*(uint8_t *)(&USB0_ENDPT0 + setup.wIndex * 4)) |= 0x02;
351 // TODO: do we need to clear the data toggle here?
353 case 0x0680: // GET_DESCRIPTOR
357 printHex( setup.wValue );
360 for ( list = usb_descriptor_list; 1; list++ )
362 if ( list->addr == NULL )
364 if ( setup.wValue == list->wValue && setup.wIndex == list->wIndex )
367 if ( (setup.wValue >> 8) == 3 )
369 // for string descriptors, use the descriptor's
370 // length field, allowing runtime configured
372 datalen = *(list->addr);
376 datalen = list->length;
379 print("Desc found, ");
380 printHex32( (uint32_t)data );
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 );
396 print( "desc: not found" NL );
401 case 0x2221: // CDC_SET_CONTROL_LINE_STATE
402 usb_cdc_line_rtsdtr = setup.wValue;
403 //serial_print("set control line state\n");
407 case 0x21A1: // CDC_GET_LINE_CODING
408 data = (uint8_t*)usb_cdc_line_coding;
409 datalen = sizeof( usb_cdc_line_coding );
412 case 0x2021: // CDC_SET_LINE_CODING
414 //serial_print("set coding, waiting...\n");
416 return; // Cannot stall here (causes issues)
418 case 0x0921: // HID SET_REPORT
420 print("SET_REPORT - ");
421 printHex( setup.wValue );
423 printHex( setup.wValue & 0xFF );
426 USBKeys_LEDs = setup.wValue & 0xFF;
430 case 0x01A1: // HID GET_REPORT
432 print("GET_REPORT - ");
433 printHex( USBKeys_LEDs );
436 data = (uint8_t*)&USBKeys_LEDs;
440 case 0x0A21: // HID SET_IDLE
442 print("SET_IDLE - ");
443 printHex( setup.wValue );
446 USBKeys_Idle_Config = (setup.wValue >> 8);
447 USBKeys_Idle_Count = 0;
451 case 0x0B21: // HID SET_PROTOCOL
453 print("SET_PROTOCOL - ");
454 printHex( setup.wValue );
456 printHex( setup.wValue & 0xFF );
459 USBKeys_Protocol = setup.wValue & 0xFF; // 0 - Boot Mode, 1 - NKRO Mode
465 #ifdef UART_DEBUG_UNKNOWN
474 print("setup send ");
475 printHex32((uint32_t)data);
481 if ( datalen > setup.wLength )
482 datalen = setup.wLength;
485 if ( size > EP0_SIZE )
488 endpoint0_transmit(data, size);
492 // See if transmit has finished
493 if ( datalen == 0 && size < EP0_SIZE )
497 if ( size > EP0_SIZE )
499 endpoint0_transmit(data, size);
503 // See if transmit has finished
504 if ( datalen == 0 && size < EP0_SIZE )
507 // Save rest of transfer for later? XXX
509 ep0_tx_len = datalen;
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).
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.
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.
526 static void usb_control( uint32_t stat )
536 b = stat2bufferdescriptor( stat );
537 pid = BDT_PID( b->desc );
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);
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);
561 // clear any leftover pending IN transactions
563 if ( ep0_tx_data_toggle )
566 //if (table[index(0, TX, EVEN)].desc & 0x80) {
567 //serial_print("leftover tx even\n");
569 //if (table[index(0, TX, ODD)].desc & 0x80) {
570 //serial_print("leftover tx odd\n");
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;
577 #ifdef UART_DEBUG_UNKNOWN
578 print("bmRequestType:");
579 printHex(setup.bmRequestType);
580 print(", bRequest:");
581 printHex(setup.bRequest);
583 printHex(setup.wValue);
585 printHex(setup.wIndex);
587 printHex(setup.wLength);
590 // actually "do" the setup request
592 // unfreeze the USB, now that we're ready
593 USB0_CTL = USB_CTL_USBENSOFEN; // clear TXSUSPENDTOKENBUSY bit
595 case 0x01: // OUT transaction received from host
601 if ( setup.wRequestAndType == 0x2021 /*CDC_SET_LINE_CODING*/ )
604 uint8_t *dst = (uint8_t *)usb_cdc_line_coding;
605 //serial_print("set line coding ");
606 for ( i = 0; i < 7; i++ )
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 );
618 // Keyboard Interface
619 if ( setup.word1 == 0x02000921 && setup.word2 == ( (1<<16) | KEYBOARD_INTERFACE ) )
621 USBKeys_LEDs = buf[0];
622 endpoint0_transmit( NULL, 0 );
624 // NKRO Keyboard Interface
625 if ( setup.word1 == 0x02000921 && setup.word2 == ( (1<<16) | NKRO_KEYBOARD_INTERFACE ) )
627 USBKeys_LEDs = buf[0];
628 endpoint0_transmit( NULL, 0 );
631 // give the buffer back
632 b->desc = BDT_DESC( EP0_SIZE, DATA1 );
635 case 0x09: // IN transaction completed to host
642 // send remaining data, if any...
647 if (size > EP0_SIZE) size = EP0_SIZE;
648 endpoint0_transmit(data, size);
651 ep0_tx_ptr = (ep0_tx_len > 0 || size == EP0_SIZE) ? data : NULL;
654 if ( setup.bRequest == 5 && setup.bmRequestType == 0 )
658 print("set address: ");
659 printHex(setup.wValue);
662 USB0_ADDR = setup.wValue;
668 print("PID=unknown:");
674 USB0_CTL = USB_CTL_USBENSOFEN; // clear TXSUSPENDTOKENBUSY bit
677 usb_packet_t *usb_rx( uint32_t endpoint )
682 if ( endpoint >= NUM_ENDPOINTS )
685 ret = rx_first[endpoint];
687 rx_first[ endpoint ] = ret->next;
688 usb_rx_byte_count_data[ endpoint ] -= ret->len;
690 //serial_print("rx, epidx=");
691 //serial_phex(endpoint);
692 //serial_print(", packet=");
693 //serial_phex32(ret);
694 //serial_print("\n");
698 static uint32_t usb_queue_byte_count( const usb_packet_t *p )
703 for ( ; p; p = p->next )
711 uint32_t usb_tx_byte_count( uint32_t endpoint )
714 if ( endpoint >= NUM_ENDPOINTS )
716 return usb_queue_byte_count( tx_first[ endpoint ] );
719 uint32_t usb_tx_packet_count( uint32_t endpoint )
721 const usb_packet_t *p;
725 if ( endpoint >= NUM_ENDPOINTS )
728 for ( p = tx_first[ endpoint ]; p; p = p->next )
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.
743 void usb_rx_memory( usb_packet_t *packet )
745 //print("USB RX MEMORY");
749 cfg = usb_endpoint_config_table;
750 //serial_print("rx_mem:");
752 for ( i = 1; i <= NUM_ENDPOINTS; i++ )
754 if ( *cfg++ & USB_ENDPT_EPRXEN )
756 if ( table[ index( i, RX, EVEN ) ].desc == 0 )
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--;
763 //serial_print(",even\n");
766 if ( table[ index( i, RX, ODD ) ].desc == 0 )
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--;
773 //serial_print(",odd\n");
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;
787 //#define index(endpoint, tx, odd) (((endpoint) << 2) | ((tx) << 1) | (odd))
788 //#define stat2bufferdescriptor(stat) (table + ((stat) >> 2))
790 void usb_tx( uint32_t endpoint, usb_packet_t *packet )
792 bdt_t *b = &table[ index( endpoint, TX, EVEN ) ];
796 if ( endpoint >= NUM_ENDPOINTS )
799 //serial_print("txstate=");
800 //serial_phex(tx_state[ endpoint ]);
801 //serial_print("\n");
802 switch ( tx_state[ endpoint ] )
804 case TX_STATE_BOTH_FREE_EVEN_FIRST:
805 next = TX_STATE_ODD_FREE;
807 case TX_STATE_BOTH_FREE_ODD_FIRST:
809 next = TX_STATE_EVEN_FREE;
811 case TX_STATE_EVEN_FREE:
812 next = TX_STATE_NONE_FREE_ODD_FIRST;
814 case TX_STATE_ODD_FREE:
816 next = TX_STATE_NONE_FREE_EVEN_FIRST;
819 if (tx_first[ endpoint ] == NULL)
821 tx_first[ endpoint ] = packet;
825 tx_last[ endpoint ]->next = packet;
827 tx_last[ endpoint ] = packet;
832 tx_state[ endpoint ] = next;
833 b->addr = packet->buf;
834 b->desc = BDT_DESC( packet->len, ((uint32_t)b & 8) ? DATA1 : DATA0 );
839 void usb_device_reload()
842 #if defined(_mk20dx128vlf5_)
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
851 if ( GPIOA_PDIR & (1<<3) )
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.");
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 ];
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 ];
872 // Teensy 3.0 and 3.1
874 asm volatile("bkpt");
881 uint8_t status, stat, t;
883 //serial_print("isr");
884 //status = USB0_ISTAT;
885 //serial_phex(status);
886 //serial_print("\n");
890 print("USB ISR STATUS: ");
895 if ( (status & USB_INTEN_SOFTOKEN /* 04 */ ) )
897 if ( usb_configuration )
899 t = usb_reboot_timer;
902 usb_reboot_timer = --t;
908 t = usb_cdc_transmit_flush_timer;
911 usb_cdc_transmit_flush_timer = --t;
913 usb_serial_flush_callback();
917 USB0_ISTAT = USB_INTEN_SOFTOKEN;
920 if ( (status & USB_ISTAT_TOKDNE /* 08 */ ) )
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;
935 bdt_t *b = stat2bufferdescriptor(stat);
936 usb_packet_t *packet = (usb_packet_t *)((uint8_t *)(b->addr) - 8);
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);
947 endpoint--; // endpoint is index to zero-based arrays
952 packet = tx_first[ endpoint ];
955 //serial_print("tx packet\n");
956 tx_first[endpoint] = packet->next;
957 b->addr = packet->buf;
958 switch ( tx_state[ endpoint ] )
960 case TX_STATE_BOTH_FREE_EVEN_FIRST:
961 tx_state[ endpoint ] = TX_STATE_ODD_FREE;
963 case TX_STATE_BOTH_FREE_ODD_FIRST:
964 tx_state[ endpoint ] = TX_STATE_EVEN_FREE;
966 case TX_STATE_EVEN_FREE:
967 tx_state[ endpoint ] = TX_STATE_NONE_FREE_ODD_FIRST;
969 case TX_STATE_ODD_FREE:
970 tx_state[ endpoint ] = TX_STATE_NONE_FREE_EVEN_FIRST;
975 b->desc = BDT_DESC( packet->len, ((uint32_t)b & 8) ? DATA1 : DATA0 );
977 //serial_print("tx no packet\n");
978 switch ( tx_state[ endpoint ] )
980 case TX_STATE_BOTH_FREE_EVEN_FIRST:
981 case TX_STATE_BOTH_FREE_ODD_FIRST:
983 case TX_STATE_EVEN_FREE:
984 tx_state[ endpoint ] = TX_STATE_BOTH_FREE_EVEN_FIRST;
986 case TX_STATE_ODD_FREE:
987 tx_state[ endpoint ] = TX_STATE_BOTH_FREE_ODD_FIRST;
990 tx_state[ endpoint ] = ((uint32_t)b & 8)
992 : TX_STATE_EVEN_FREE;
999 packet->len = b->desc >> 16;
1000 if ( packet->len > 0 )
1003 packet->next = NULL;
1004 if ( rx_first[ endpoint ] == NULL )
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;
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;
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();
1030 b->addr = packet->buf;
1031 b->desc = BDT_DESC( 64, ((uint32_t)b & 8) ? DATA1 : DATA0 );
1035 //serial_print("starving ");
1036 //serial_phex(endpoint + 1);
1037 //serial_print(((uint32_t)b & 8) ? ",odd\n" : ",even\n");
1039 usb_rx_memory_needed++;
1044 b->desc = BDT_DESC( 64, ((uint32_t)b & 8) ? DATA1 : DATA0 );
1052 USB0_ISTAT = USB_ISTAT_TOKDNE;
1057 if ( status & USB_ISTAT_USBRST /* 01 */ )
1059 //serial_print("reset\n");
1061 // initialize BDT toggle bits
1062 USB0_CTL = USB_CTL_ODDRST;
1063 ep0_tx_bdt_bank = 0;
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;
1073 // activate endpoint 0
1074 USB0_ENDPT0 = USB_ENDPT_EPRXEN | USB_ENDPT_EPTXEN | USB_ENDPT_EPHSHK;
1076 // clear all ending interrupts
1077 USB0_ERRSTAT = 0xFF;
1080 // set the address to zero during enumeration
1083 // enable other interrupts
1085 USB0_INTEN = USB_INTEN_TOKDNEEN |
1086 USB_INTEN_SOFTOKEN |
1089 USB_INTEN_USBRSTEN |
1092 // is this necessary?
1093 USB0_CTL = USB_CTL_USBENSOFEN;
1098 if ( (status & USB_ISTAT_STALL /* 80 */ ) )
1100 //serial_print("stall:\n");
1101 USB0_ENDPT0 = USB_ENDPT_EPRXEN | USB_ENDPT_EPTXEN | USB_ENDPT_EPHSHK;
1102 USB0_ISTAT = USB_ISTAT_STALL;
1104 if ( (status & USB_ISTAT_ERROR /* 02 */ ) )
1106 uint8_t err = USB0_ERRSTAT;
1108 //serial_print("err:");
1110 //serial_print("\n");
1111 USB0_ISTAT = USB_ISTAT_ERROR;
1114 if ( (status & USB_ISTAT_SLEEP /* 10 */ ) )
1116 //serial_print("sleep\n");
1117 USB0_ISTAT = USB_ISTAT_SLEEP;
1126 print("USB INIT"NL);
1129 // Clear out endpoints table
1130 for ( int i = 0; i <= NUM_ENDPOINTS * 4; i++ )
1136 // this basically follows the flowchart in the Kinetis
1137 // Quick Reference User Guide, Rev. 1, 03/2012, page 141
1139 // assume 48 MHz clock already running
1140 // SIM - enable clock
1141 SIM_SCGC4 |= SIM_SCGC4_USBOTG;
1144 USB0_USBTRC0 = USB_USBTRC_USBRESET;
1145 while ( (USB0_USBTRC0 & USB_USBTRC_USBRESET) != 0 ); // wait for reset to end
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;
1152 // clear all ISR flags
1154 USB0_ERRSTAT = 0xFF;
1155 USB0_OTGISTAT = 0xFF;
1157 USB0_USBTRC0 |= 0x40; // undocumented bit
1160 USB0_CTL = USB_CTL_USBENSOFEN;
1163 // enable reset interrupt
1164 USB0_INTEN = USB_INTEN_USBRSTEN;
1166 // enable interrupt in NVIC...
1167 NVIC_SET_PRIORITY( IRQ_USBOTG, 112 );
1168 NVIC_ENABLE_IRQ( IRQ_USBOTG );
1171 USB0_CONTROL = USB_CONTROL_DPPULLUPNONOTG;
1176 // return 0 if the USB is not configured, or the configuration
1177 // number selected by the HOST
1178 uint8_t usb_configured()
1180 return usb_configuration;