Kiibohd Controller
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
This repo is archived. You can view files and clone it, but cannot push or open issues/pull-requests.

usb_dev.c 28KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179
  1. /* Teensyduino Core Library
  2. * http://www.pjrc.com/teensy/
  3. * Copyright (c) 2013 PJRC.COM, LLC.
  4. * Modifications by Jacob Alexander (2013-2014)
  5. *
  6. * Permission is hereby granted, free of charge, to any person obtaining
  7. * a copy of this software and associated documentation files (the
  8. * "Software"), to deal in the Software without restriction, including
  9. * without limitation the rights to use, copy, modify, merge, publish,
  10. * distribute, sublicense, and/or sell copies of the Software, and to
  11. * permit persons to whom the Software is furnished to do so, subject to
  12. * the following conditions:
  13. *
  14. * 1. The above copyright notice and this permission notice shall be
  15. * included in all copies or substantial portions of the Software.
  16. *
  17. * 2. If the Software is incorporated into a build system that allows
  18. * selection among a list of target devices, then similar target
  19. * devices manufactured by PJRC.COM must be included in the list of
  20. * target devices and selectable in the same manner.
  21. *
  22. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
  23. * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  24. * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
  25. * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
  26. * BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
  27. * ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
  28. * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
  29. * SOFTWARE.
  30. */
  31. // ----- Includes -----
  32. // Project Includes
  33. #include <Lib/OutputLib.h>
  34. #include <print.h>
  35. // Local Includes
  36. #include "usb_dev.h"
  37. #include "usb_mem.h"
  38. // ----- Defines -----
  39. // DEBUG Mode
  40. // XXX - Only use when using usbMuxUart Module
  41. // Delay causes issues initializing more than 1 hid device (i.e. NKRO keyboard)
  42. //#define UART_DEBUG 1
  43. // Debug Unknown USB requests, usually what you want to debug USB issues
  44. //#define UART_DEBUG_UNKNOWN 1
  45. #define TX_STATE_BOTH_FREE_EVEN_FIRST 0
  46. #define TX_STATE_BOTH_FREE_ODD_FIRST 1
  47. #define TX_STATE_EVEN_FREE 2
  48. #define TX_STATE_ODD_FREE 3
  49. #define TX_STATE_NONE_FREE_EVEN_FIRST 4
  50. #define TX_STATE_NONE_FREE_ODD_FIRST 5
  51. #define BDT_OWN 0x80
  52. #define BDT_DATA1 0x40
  53. #define BDT_DATA0 0x00
  54. #define BDT_DTS 0x08
  55. #define BDT_STALL 0x04
  56. #define TX 1
  57. #define RX 0
  58. #define ODD 1
  59. #define EVEN 0
  60. #define DATA0 0
  61. #define DATA1 1
  62. #define GET_STATUS 0
  63. #define CLEAR_FEATURE 1
  64. #define SET_FEATURE 3
  65. #define SET_ADDRESS 5
  66. #define GET_DESCRIPTOR 6
  67. #define SET_DESCRIPTOR 7
  68. #define GET_CONFIGURATION 8
  69. #define SET_CONFIGURATION 9
  70. #define GET_INTERFACE 10
  71. #define SET_INTERFACE 11
  72. #define SYNCH_FRAME 12
  73. #define TX_STATE_BOTH_FREE_EVEN_FIRST 0
  74. #define TX_STATE_BOTH_FREE_ODD_FIRST 1
  75. #define TX_STATE_EVEN_FREE 2
  76. #define TX_STATE_ODD_FREE 3
  77. #define TX_STATE_NONE_FREE 4
  78. // ----- Macros -----
  79. #define BDT_PID(n) (((n) >> 2) & 15)
  80. #define BDT_DESC(count, data) (BDT_OWN | BDT_DTS \
  81. | ((data) ? BDT_DATA1 : BDT_DATA0) \
  82. | ((count) << 16))
  83. #define index(endpoint, tx, odd) (((endpoint) << 2) | ((tx) << 1) | (odd))
  84. #define stat2bufferdescriptor(stat) (table + ((stat) >> 2))
  85. // ----- Structs -----
  86. // buffer descriptor table
  87. typedef struct {
  88. uint32_t desc;
  89. void * addr;
  90. } bdt_t;
  91. static union {
  92. struct {
  93. union {
  94. struct {
  95. uint8_t bmRequestType;
  96. uint8_t bRequest;
  97. };
  98. uint16_t wRequestAndType;
  99. };
  100. uint16_t wValue;
  101. uint16_t wIndex;
  102. uint16_t wLength;
  103. };
  104. struct {
  105. uint32_t word1;
  106. uint32_t word2;
  107. };
  108. } setup;
  109. // ----- Variables -----
  110. __attribute__ ((section(".usbdescriptortable"), used))
  111. static bdt_t table[ (NUM_ENDPOINTS + 1) * 4 ];
  112. static usb_packet_t *rx_first [ NUM_ENDPOINTS ];
  113. static usb_packet_t *rx_last [ NUM_ENDPOINTS ];
  114. static usb_packet_t *tx_first [ NUM_ENDPOINTS ];
  115. static usb_packet_t *tx_last [ NUM_ENDPOINTS ];
  116. uint16_t usb_rx_byte_count_data[ NUM_ENDPOINTS ];
  117. static uint8_t tx_state[NUM_ENDPOINTS];
  118. // SETUP always uses a DATA0 PID for the data field of the SETUP transaction.
  119. // transactions in the data phase start with DATA1 and toggle (figure 8-12, USB1.1)
  120. // Status stage uses a DATA1 PID.
  121. static uint8_t ep0_rx0_buf[EP0_SIZE] __attribute__ ((aligned (4)));
  122. static uint8_t ep0_rx1_buf[EP0_SIZE] __attribute__ ((aligned (4)));
  123. static const uint8_t *ep0_tx_ptr = NULL;
  124. static uint16_t ep0_tx_len;
  125. static uint8_t ep0_tx_bdt_bank = 0;
  126. static uint8_t ep0_tx_data_toggle = 0;
  127. uint8_t usb_rx_memory_needed = 0;
  128. volatile uint8_t usb_configuration = 0;
  129. volatile uint8_t usb_reboot_timer = 0;
  130. static uint8_t reply_buffer[8];
  131. // ----- Functions -----
  132. static void endpoint0_stall()
  133. {
  134. USB0_ENDPT0 = USB_ENDPT_EPSTALL | USB_ENDPT_EPRXEN | USB_ENDPT_EPTXEN | USB_ENDPT_EPHSHK;
  135. }
  136. static void endpoint0_transmit( const void *data, uint32_t len )
  137. {
  138. table[index(0, TX, ep0_tx_bdt_bank)].addr = (void *)data;
  139. table[index(0, TX, ep0_tx_bdt_bank)].desc = BDT_DESC(len, ep0_tx_data_toggle);
  140. ep0_tx_data_toggle ^= 1;
  141. ep0_tx_bdt_bank ^= 1;
  142. }
  143. static void usb_setup()
  144. {
  145. const uint8_t *data = NULL;
  146. uint32_t datalen = 0;
  147. const usb_descriptor_list_t *list;
  148. uint32_t size;
  149. volatile uint8_t *reg;
  150. uint8_t epconf;
  151. const uint8_t *cfg;
  152. int i;
  153. switch ( setup.wRequestAndType )
  154. {
  155. case 0x0500: // SET_ADDRESS
  156. break;
  157. case 0x0900: // SET_CONFIGURATION
  158. #ifdef UART_DEBUG
  159. print("CONFIGURE - ");
  160. #endif
  161. usb_configuration = setup.wValue;
  162. reg = &USB0_ENDPT1;
  163. cfg = usb_endpoint_config_table;
  164. // clear all BDT entries, free any allocated memory...
  165. for ( i = 4; i < ( NUM_ENDPOINTS + 1) * 4; i++ )
  166. {
  167. if ( table[i].desc & BDT_OWN )
  168. {
  169. usb_free( (usb_packet_t *)((uint8_t *)(table[ i ].addr) - 8) );
  170. }
  171. }
  172. // free all queued packets
  173. for ( i = 0; i < NUM_ENDPOINTS; i++ )
  174. {
  175. usb_packet_t *p, *n;
  176. p = rx_first[i];
  177. while ( p )
  178. {
  179. n = p->next;
  180. usb_free(p);
  181. p = n;
  182. }
  183. rx_first[ i ] = NULL;
  184. rx_last[ i ] = NULL;
  185. p = tx_first[i];
  186. while (p)
  187. {
  188. n = p->next;
  189. usb_free(p);
  190. p = n;
  191. }
  192. tx_first[ i ] = NULL;
  193. tx_last[ i ] = NULL;
  194. usb_rx_byte_count_data[i] = 0;
  195. switch ( tx_state[ i ] )
  196. {
  197. case TX_STATE_EVEN_FREE:
  198. case TX_STATE_NONE_FREE_EVEN_FIRST:
  199. tx_state[ i ] = TX_STATE_BOTH_FREE_EVEN_FIRST;
  200. break;
  201. case TX_STATE_ODD_FREE:
  202. case TX_STATE_NONE_FREE_ODD_FIRST:
  203. tx_state[ i ] = TX_STATE_BOTH_FREE_ODD_FIRST;
  204. break;
  205. default:
  206. break;
  207. }
  208. }
  209. usb_rx_memory_needed = 0;
  210. for ( i = 1; i <= NUM_ENDPOINTS; i++ )
  211. {
  212. epconf = *cfg++;
  213. *reg = epconf;
  214. reg += 4;
  215. if ( epconf & USB_ENDPT_EPRXEN )
  216. {
  217. usb_packet_t *p;
  218. p = usb_malloc();
  219. if ( p )
  220. {
  221. table[ index( i, RX, EVEN ) ].addr = p->buf;
  222. table[ index( i, RX, EVEN ) ].desc = BDT_DESC( 64, 0 );
  223. }
  224. else
  225. {
  226. table[ index( i, RX, EVEN ) ].desc = 0;
  227. usb_rx_memory_needed++;
  228. }
  229. p = usb_malloc();
  230. if ( p )
  231. {
  232. table[ index( i, RX, ODD ) ].addr = p->buf;
  233. table[ index( i, RX, ODD ) ].desc = BDT_DESC( 64, 1 );
  234. }
  235. else
  236. {
  237. table[ index( i, RX, ODD ) ].desc = 0;
  238. usb_rx_memory_needed++;
  239. }
  240. }
  241. table[ index( i, TX, EVEN ) ].desc = 0;
  242. table[ index( i, TX, ODD ) ].desc = 0;
  243. }
  244. break;
  245. case 0x0880: // GET_CONFIGURATION
  246. reply_buffer[0] = usb_configuration;
  247. datalen = 1;
  248. data = reply_buffer;
  249. break;
  250. case 0x0080: // GET_STATUS (device)
  251. reply_buffer[0] = 0;
  252. reply_buffer[1] = 0;
  253. datalen = 2;
  254. data = reply_buffer;
  255. break;
  256. case 0x0082: // GET_STATUS (endpoint)
  257. if ( setup.wIndex > NUM_ENDPOINTS )
  258. {
  259. // TODO: do we need to handle IN vs OUT here?
  260. endpoint0_stall();
  261. return;
  262. }
  263. reply_buffer[0] = 0;
  264. reply_buffer[1] = 0;
  265. if ( *(uint8_t *)(&USB0_ENDPT0 + setup.wIndex * 4) & 0x02 )
  266. reply_buffer[0] = 1;
  267. data = reply_buffer;
  268. datalen = 2;
  269. break;
  270. case 0x0100: // CLEAR_FEATURE (device)
  271. case 0x0101: // CLEAR_FEATURE (interface)
  272. // TODO: Currently ignoring, perhaps useful? -HaaTa
  273. endpoint0_stall();
  274. return;
  275. case 0x0102: // CLEAR_FEATURE (interface)
  276. i = setup.wIndex & 0x7F;
  277. if ( i > NUM_ENDPOINTS || setup.wValue != 0 )
  278. {
  279. endpoint0_stall();
  280. return;
  281. }
  282. //(*(uint8_t *)(&USB0_ENDPT0 + setup.wIndex * 4)) &= ~0x02;
  283. // TODO: do we need to clear the data toggle here?
  284. //break;
  285. // FIXME: Clearing causes keyboard to freeze, likely an invalid clear
  286. // XXX: Ignoring seems to work, though this may not be the ideal behaviour -HaaTa
  287. endpoint0_stall();
  288. return;
  289. case 0x0300: // SET_FEATURE (device)
  290. case 0x0301: // SET_FEATURE (interface)
  291. // TODO: Currently ignoring, perhaps useful? -HaaTa
  292. endpoint0_stall();
  293. return;
  294. case 0x0302: // SET_FEATURE (endpoint)
  295. i = setup.wIndex & 0x7F;
  296. if ( i > NUM_ENDPOINTS || setup.wValue != 0 )
  297. {
  298. // TODO: do we need to handle IN vs OUT here?
  299. endpoint0_stall();
  300. return;
  301. }
  302. (*(uint8_t *)(&USB0_ENDPT0 + setup.wIndex * 4)) |= 0x02;
  303. // TODO: do we need to clear the data toggle here?
  304. break;
  305. case 0x0680: // GET_DESCRIPTOR
  306. case 0x0681:
  307. #ifdef UART_DEBUG
  308. print("desc:");
  309. printHex( setup.wValue );
  310. print( NL );
  311. #endif
  312. for ( list = usb_descriptor_list; 1; list++ )
  313. {
  314. if ( list->addr == NULL )
  315. break;
  316. if ( setup.wValue == list->wValue && setup.wIndex == list->wIndex )
  317. {
  318. data = list->addr;
  319. if ( (setup.wValue >> 8) == 3 )
  320. {
  321. // for string descriptors, use the descriptor's
  322. // length field, allowing runtime configured
  323. // length.
  324. datalen = *(list->addr);
  325. }
  326. else
  327. {
  328. datalen = list->length;
  329. }
  330. #if UART_DEBUG
  331. print("Desc found, ");
  332. printHex32( (uint32_t)data );
  333. print(",");
  334. printHex( datalen );
  335. print(",");
  336. printHex_op( data[0], 2 );
  337. printHex_op( data[1], 2 );
  338. printHex_op( data[2], 2 );
  339. printHex_op( data[3], 2 );
  340. printHex_op( data[4], 2 );
  341. printHex_op( data[5], 2 );
  342. print( NL );
  343. #endif
  344. goto send;
  345. }
  346. }
  347. #ifdef UART_DEBUG
  348. print( "desc: not found" NL );
  349. #endif
  350. endpoint0_stall();
  351. return;
  352. case 0x2221: // CDC_SET_CONTROL_LINE_STATE
  353. usb_cdc_line_rtsdtr = setup.wValue;
  354. //serial_print("set control line state\n");
  355. endpoint0_stall();
  356. return;
  357. case 0x21A1: // CDC_GET_LINE_CODING
  358. data = (uint8_t*)usb_cdc_line_coding;
  359. datalen = sizeof( usb_cdc_line_coding );
  360. goto send;
  361. case 0x2021: // CDC_SET_LINE_CODING
  362. // XXX Needed?
  363. //serial_print("set coding, waiting...\n");
  364. endpoint0_stall();
  365. return; // Cannot stall here (causes issues)
  366. case 0x0921: // HID SET_REPORT
  367. #ifdef UART_DEBUG
  368. print("SET_REPORT - ");
  369. printHex( setup.wValue );
  370. print(" - ");
  371. printHex( setup.wValue & 0xFF );
  372. print( NL );
  373. #endif
  374. USBKeys_LEDs = setup.wValue & 0xFF;
  375. endpoint0_stall();
  376. return;
  377. case 0x01A1: // HID GET_REPORT
  378. #ifdef UART_DEBUG
  379. print("GET_REPORT - ");
  380. printHex( USBKeys_LEDs );
  381. print(NL);
  382. #endif
  383. data = (uint8_t*)&USBKeys_LEDs;
  384. datalen = 1;
  385. goto send;
  386. case 0x0A21: // HID SET_IDLE
  387. #ifdef UART_DEBUG
  388. print("SET_IDLE - ");
  389. printHex( setup.wValue );
  390. print(NL);
  391. #endif
  392. USBKeys_Idle_Config = (setup.wValue >> 8);
  393. USBKeys_Idle_Count = 0;
  394. endpoint0_stall();
  395. return;
  396. case 0x0B21: // HID SET_PROTOCOL
  397. #ifdef UART_DEBUG
  398. print("SET_PROTOCOL - ");
  399. printHex( setup.wValue );
  400. print(" - ");
  401. printHex( setup.wValue & 0xFF );
  402. print(NL);
  403. #endif
  404. USBKeys_Protocol = setup.wValue & 0xFF; // 0 - Boot Mode, 1 - NKRO Mode
  405. endpoint0_stall();
  406. return;
  407. // case 0xC940:
  408. default:
  409. #ifdef UART_DEBUG_UNKNOWN
  410. print("UNKNOWN");
  411. #endif
  412. endpoint0_stall();
  413. return;
  414. }
  415. send:
  416. #ifdef UART_DEBUG
  417. print("setup send ");
  418. printHex32((uint32_t)data);
  419. print(",");
  420. printHex(datalen);
  421. print(NL);
  422. #endif
  423. if ( datalen > setup.wLength )
  424. datalen = setup.wLength;
  425. size = datalen;
  426. if ( size > EP0_SIZE )
  427. size = EP0_SIZE;
  428. endpoint0_transmit(data, size);
  429. data += size;
  430. datalen -= size;
  431. // See if transmit has finished
  432. if ( datalen == 0 && size < EP0_SIZE )
  433. return;
  434. size = datalen;
  435. if ( size > EP0_SIZE )
  436. size = EP0_SIZE;
  437. endpoint0_transmit(data, size);
  438. data += size;
  439. datalen -= size;
  440. // See if transmit has finished
  441. if ( datalen == 0 && size < EP0_SIZE )
  442. return;
  443. // Save rest of transfer for later? XXX
  444. ep0_tx_ptr = data;
  445. ep0_tx_len = datalen;
  446. }
  447. //A bulk endpoint's toggle sequence is initialized to DATA0 when the endpoint
  448. //experiences any configuration event (configuration events are explained in
  449. //Sections 9.1.1.5 and 9.4.5).
  450. //Configuring a device or changing an alternate setting causes all of the status
  451. //and configuration values associated with endpoints in the affected interfaces
  452. //to be set to their default values. This includes setting the data toggle of
  453. //any endpoint using data toggles to the value DATA0.
  454. //For endpoints using data toggle, regardless of whether an endpoint has the
  455. //Halt feature set, a ClearFeature(ENDPOINT_HALT) request always results in the
  456. //data toggle being reinitialized to DATA0.
  457. static void usb_control( uint32_t stat )
  458. {
  459. #ifdef UART_DEBUG
  460. print("CONTROL - ");
  461. #endif
  462. bdt_t *b;
  463. uint32_t pid, size;
  464. uint8_t *buf;
  465. const uint8_t *data;
  466. b = stat2bufferdescriptor( stat );
  467. pid = BDT_PID( b->desc );
  468. buf = b->addr;
  469. #ifdef UART_DEBUG
  470. print("pid:");
  471. printHex(pid);
  472. print(", count:");
  473. printHex32(b->desc);
  474. print(" - ");
  475. #endif
  476. switch (pid)
  477. {
  478. case 0x0D: // Setup received from host
  479. //serial_print("PID=Setup\n");
  480. //if (count != 8) ; // panic?
  481. // grab the 8 byte setup info
  482. setup.word1 = *(uint32_t *)(buf);
  483. setup.word2 = *(uint32_t *)(buf + 4);
  484. // give the buffer back
  485. b->desc = BDT_DESC( EP0_SIZE, DATA1 );
  486. //table[index(0, RX, EVEN)].desc = BDT_DESC(EP0_SIZE, 1);
  487. //table[index(0, RX, ODD)].desc = BDT_DESC(EP0_SIZE, 1);
  488. // clear any leftover pending IN transactions
  489. ep0_tx_ptr = NULL;
  490. if ( ep0_tx_data_toggle )
  491. {
  492. }
  493. //if (table[index(0, TX, EVEN)].desc & 0x80) {
  494. //serial_print("leftover tx even\n");
  495. //}
  496. //if (table[index(0, TX, ODD)].desc & 0x80) {
  497. //serial_print("leftover tx odd\n");
  498. //}
  499. table[index(0, TX, EVEN)].desc = 0;
  500. table[index(0, TX, ODD)].desc = 0;
  501. // first IN after Setup is always DATA1
  502. ep0_tx_data_toggle = 1;
  503. #ifdef UART_DEBUG_UNKNOWN
  504. print("bmRequestType:");
  505. printHex(setup.bmRequestType);
  506. print(", bRequest:");
  507. printHex(setup.bRequest);
  508. print(", wValue:");
  509. printHex(setup.wValue);
  510. print(", wIndex:");
  511. printHex(setup.wIndex);
  512. print(", len:");
  513. printHex(setup.wLength);
  514. print(NL);
  515. #endif
  516. // actually "do" the setup request
  517. usb_setup();
  518. // unfreeze the USB, now that we're ready
  519. USB0_CTL = USB_CTL_USBENSOFEN; // clear TXSUSPENDTOKENBUSY bit
  520. break;
  521. case 0x01: // OUT transaction received from host
  522. case 0x02:
  523. #ifdef UART_DEBUG
  524. print("PID=OUT"NL);
  525. #endif
  526. // CDC Interface
  527. if ( setup.wRequestAndType == 0x2021 /*CDC_SET_LINE_CODING*/ )
  528. {
  529. int i;
  530. uint8_t *dst = (uint8_t *)usb_cdc_line_coding;
  531. //serial_print("set line coding ");
  532. for ( i = 0; i < 7; i++ )
  533. {
  534. //serial_phex(*buf);
  535. *dst++ = *buf++;
  536. }
  537. //serial_phex32(usb_cdc_line_coding[0]);
  538. //serial_print("\n");
  539. if ( usb_cdc_line_coding[0] == 134 )
  540. usb_reboot_timer = 15;
  541. endpoint0_transmit( NULL, 0 );
  542. }
  543. // Keyboard Interface
  544. if ( setup.word1 == 0x02000921 && setup.word2 == ( (1<<16) | KEYBOARD_INTERFACE ) )
  545. {
  546. USBKeys_LEDs = buf[0];
  547. endpoint0_transmit( NULL, 0 );
  548. }
  549. // NKRO Keyboard Interface
  550. if ( setup.word1 == 0x02000921 && setup.word2 == ( (1<<16) | NKRO_KEYBOARD_INTERFACE ) )
  551. {
  552. USBKeys_LEDs = buf[0];
  553. endpoint0_transmit( NULL, 0 );
  554. }
  555. // give the buffer back
  556. b->desc = BDT_DESC( EP0_SIZE, DATA1 );
  557. break;
  558. case 0x09: // IN transaction completed to host
  559. #ifdef UART_DEBUG
  560. print("PID=IN:");
  561. printHex(stat);
  562. print(NL);
  563. #endif
  564. // send remaining data, if any...
  565. data = ep0_tx_ptr;
  566. if ( data )
  567. {
  568. size = ep0_tx_len;
  569. if (size > EP0_SIZE) size = EP0_SIZE;
  570. endpoint0_transmit(data, size);
  571. data += size;
  572. ep0_tx_len -= size;
  573. ep0_tx_ptr = (ep0_tx_len > 0 || size == EP0_SIZE) ? data : NULL;
  574. }
  575. if ( setup.bRequest == 5 && setup.bmRequestType == 0 )
  576. {
  577. setup.bRequest = 0;
  578. #ifdef UART_DEBUG
  579. print("set address: ");
  580. printHex(setup.wValue);
  581. print(NL);
  582. #endif
  583. USB0_ADDR = setup.wValue;
  584. }
  585. break;
  586. default:
  587. #ifdef UART_DEBUG
  588. print("PID=unknown:");
  589. printHex(pid);
  590. print(NL);
  591. #endif
  592. break;
  593. }
  594. USB0_CTL = USB_CTL_USBENSOFEN; // clear TXSUSPENDTOKENBUSY bit
  595. }
  596. usb_packet_t *usb_rx( uint32_t endpoint )
  597. {
  598. //print("USB RX");
  599. usb_packet_t *ret;
  600. endpoint--;
  601. if ( endpoint >= NUM_ENDPOINTS )
  602. return NULL;
  603. __disable_irq();
  604. ret = rx_first[endpoint];
  605. if ( ret )
  606. rx_first[ endpoint ] = ret->next;
  607. usb_rx_byte_count_data[ endpoint ] -= ret->len;
  608. __enable_irq();
  609. //serial_print("rx, epidx=");
  610. //serial_phex(endpoint);
  611. //serial_print(", packet=");
  612. //serial_phex32(ret);
  613. //serial_print("\n");
  614. return ret;
  615. }
  616. static uint32_t usb_queue_byte_count( const usb_packet_t *p )
  617. {
  618. uint32_t count=0;
  619. __disable_irq();
  620. for ( ; p; p = p->next )
  621. {
  622. count += p->len;
  623. }
  624. __enable_irq();
  625. return count;
  626. }
  627. uint32_t usb_tx_byte_count( uint32_t endpoint )
  628. {
  629. endpoint--;
  630. if ( endpoint >= NUM_ENDPOINTS )
  631. return 0;
  632. return usb_queue_byte_count( tx_first[ endpoint ] );
  633. }
  634. uint32_t usb_tx_packet_count( uint32_t endpoint )
  635. {
  636. const usb_packet_t *p;
  637. uint32_t count=0;
  638. endpoint--;
  639. if ( endpoint >= NUM_ENDPOINTS )
  640. return 0;
  641. __disable_irq();
  642. for ( p = tx_first[ endpoint ]; p; p = p->next )
  643. count++;
  644. __enable_irq();
  645. return count;
  646. }
  647. // Called from usb_free, but only when usb_rx_memory_needed > 0, indicating
  648. // receive endpoints are starving for memory. The intention is to give
  649. // endpoints needing receive memory priority over the user's code, which is
  650. // likely calling usb_malloc to obtain memory for transmitting. When the
  651. // user is creating data very quickly, their consumption could starve reception
  652. // without this prioritization. The packet buffer (input) is assigned to the
  653. // first endpoint needing memory.
  654. //
  655. void usb_rx_memory( usb_packet_t *packet )
  656. {
  657. //print("USB RX MEMORY");
  658. unsigned int i;
  659. const uint8_t *cfg;
  660. cfg = usb_endpoint_config_table;
  661. //serial_print("rx_mem:");
  662. __disable_irq();
  663. for ( i = 1; i <= NUM_ENDPOINTS; i++ )
  664. {
  665. if ( *cfg++ & USB_ENDPT_EPRXEN )
  666. {
  667. if ( table[ index( i, RX, EVEN ) ].desc == 0 )
  668. {
  669. table[ index( i, RX, EVEN ) ].addr = packet->buf;
  670. table[ index( i, RX, EVEN ) ].desc = BDT_DESC( 64, 0 );
  671. usb_rx_memory_needed--;
  672. __enable_irq();
  673. //serial_phex(i);
  674. //serial_print(",even\n");
  675. return;
  676. }
  677. if ( table[ index( i, RX, ODD ) ].desc == 0 )
  678. {
  679. table[ index( i, RX, ODD ) ].addr = packet->buf;
  680. table[ index( i, RX, ODD ) ].desc = BDT_DESC( 64, 1 );
  681. usb_rx_memory_needed--;
  682. __enable_irq();
  683. //serial_phex(i);
  684. //serial_print(",odd\n");
  685. return;
  686. }
  687. }
  688. }
  689. __enable_irq();
  690. // we should never reach this point. If we get here, it means
  691. // usb_rx_memory_needed was set greater than zero, but no memory
  692. // was actually needed.
  693. usb_rx_memory_needed = 0;
  694. usb_free( packet );
  695. return;
  696. }
  697. //#define index(endpoint, tx, odd) (((endpoint) << 2) | ((tx) << 1) | (odd))
  698. //#define stat2bufferdescriptor(stat) (table + ((stat) >> 2))
  699. void usb_tx( uint32_t endpoint, usb_packet_t *packet )
  700. {
  701. bdt_t *b = &table[ index( endpoint, TX, EVEN ) ];
  702. uint8_t next;
  703. endpoint--;
  704. if ( endpoint >= NUM_ENDPOINTS )
  705. return;
  706. __disable_irq();
  707. //serial_print("txstate=");
  708. //serial_phex(tx_state[ endpoint ]);
  709. //serial_print("\n");
  710. switch ( tx_state[ endpoint ] )
  711. {
  712. case TX_STATE_BOTH_FREE_EVEN_FIRST:
  713. next = TX_STATE_ODD_FREE;
  714. break;
  715. case TX_STATE_BOTH_FREE_ODD_FIRST:
  716. b++;
  717. next = TX_STATE_EVEN_FREE;
  718. break;
  719. case TX_STATE_EVEN_FREE:
  720. next = TX_STATE_NONE_FREE_ODD_FIRST;
  721. break;
  722. case TX_STATE_ODD_FREE:
  723. b++;
  724. next = TX_STATE_NONE_FREE_EVEN_FIRST;
  725. break;
  726. default:
  727. if (tx_first[ endpoint ] == NULL)
  728. {
  729. tx_first[ endpoint ] = packet;
  730. }
  731. else
  732. {
  733. tx_last[ endpoint ]->next = packet;
  734. }
  735. tx_last[ endpoint ] = packet;
  736. __enable_irq();
  737. return;
  738. }
  739. tx_state[ endpoint ] = next;
  740. b->addr = packet->buf;
  741. b->desc = BDT_DESC( packet->len, ((uint32_t)b & 8) ? DATA1 : DATA0 );
  742. __enable_irq();
  743. }
  744. void usb_device_reload()
  745. {
  746. // MCHCK
  747. #if defined(_mk20dx128vlf5_)
  748. // MCHCK Kiibohd Variant
  749. // Check to see if PTA3 (has a pull-up) is connected to GND (usually via jumper)
  750. // Only allow reload if the jumper is present (security)
  751. GPIOA_PDDR &= ~(1<<3); // Input
  752. PORTA_PCR3 = PORT_PCR_PFE | PORT_PCR_MUX(1); // Internal pull-up
  753. // Check for jumper
  754. if ( GPIOA_PDIR & (1<<3) )
  755. {
  756. print( NL );
  757. warn_print("Security jumper not present, cancelling firmware reload...");
  758. info_msg("Replace jumper on middle 2 pins, or manually press the firmware reload button.");
  759. }
  760. else
  761. {
  762. // Copies variable into the VBAT register, must be identical to the variable in the bootloader to jump to the bootloader flash mode
  763. for ( int pos = 0; pos < sizeof(sys_reset_to_loader_magic); pos++ )
  764. (&VBAT)[ pos ] = sys_reset_to_loader_magic[ pos ];
  765. SOFTWARE_RESET();
  766. }
  767. // Teensy 3.0 and 3.1
  768. #else
  769. asm volatile("bkpt");
  770. #endif
  771. }
  772. void usb_isr()
  773. {
  774. uint8_t status, stat, t;
  775. //serial_print("isr");
  776. //status = USB0_ISTAT;
  777. //serial_phex(status);
  778. //serial_print("\n");
  779. restart:
  780. status = USB0_ISTAT;
  781. /*
  782. print("USB ISR STATUS: ");
  783. printHex( status );
  784. print( NL );
  785. */
  786. if ( (status & USB_INTEN_SOFTOKEN /* 04 */ ) )
  787. {
  788. if ( usb_configuration )
  789. {
  790. t = usb_reboot_timer;
  791. if ( t )
  792. {
  793. usb_reboot_timer = --t;
  794. if ( !t )
  795. usb_device_reload();
  796. }
  797. // CDC Interface
  798. t = usb_cdc_transmit_flush_timer;
  799. if ( t )
  800. {
  801. usb_cdc_transmit_flush_timer = --t;
  802. if ( t == 0 )
  803. usb_serial_flush_callback();
  804. }
  805. }
  806. USB0_ISTAT = USB_INTEN_SOFTOKEN;
  807. }
  808. if ( (status & USB_ISTAT_TOKDNE /* 08 */ ) )
  809. {
  810. uint8_t endpoint;
  811. stat = USB0_STAT;
  812. //serial_print("token: ep=");
  813. //serial_phex(stat >> 4);
  814. //serial_print(stat & 0x08 ? ",tx" : ",rx");
  815. //serial_print(stat & 0x04 ? ",odd\n" : ",even\n");
  816. endpoint = stat >> 4;
  817. if ( endpoint == 0 )
  818. {
  819. usb_control( stat );
  820. }
  821. else
  822. {
  823. bdt_t *b = stat2bufferdescriptor(stat);
  824. usb_packet_t *packet = (usb_packet_t *)((uint8_t *)(b->addr) - 8);
  825. #if 0
  826. serial_print("ep:");
  827. serial_phex(endpoint);
  828. serial_print(", pid:");
  829. serial_phex(BDT_PID(b->desc));
  830. serial_print(((uint32_t)b & 8) ? ", odd" : ", even");
  831. serial_print(", count:");
  832. serial_phex(b->desc >> 16);
  833. serial_print("\n");
  834. #endif
  835. endpoint--; // endpoint is index to zero-based arrays
  836. if ( stat & 0x08 )
  837. { // transmit
  838. usb_free( packet );
  839. packet = tx_first[ endpoint ];
  840. if ( packet )
  841. {
  842. //serial_print("tx packet\n");
  843. tx_first[endpoint] = packet->next;
  844. b->addr = packet->buf;
  845. switch ( tx_state[ endpoint ] )
  846. {
  847. case TX_STATE_BOTH_FREE_EVEN_FIRST:
  848. tx_state[ endpoint ] = TX_STATE_ODD_FREE;
  849. break;
  850. case TX_STATE_BOTH_FREE_ODD_FIRST:
  851. tx_state[ endpoint ] = TX_STATE_EVEN_FREE;
  852. break;
  853. case TX_STATE_EVEN_FREE:
  854. tx_state[ endpoint ] = TX_STATE_NONE_FREE_ODD_FIRST;
  855. break;
  856. case TX_STATE_ODD_FREE:
  857. tx_state[ endpoint ] = TX_STATE_NONE_FREE_EVEN_FIRST;
  858. break;
  859. default:
  860. break;
  861. }
  862. b->desc = BDT_DESC( packet->len, ((uint32_t)b & 8) ? DATA1 : DATA0 );
  863. } else {
  864. //serial_print("tx no packet\n");
  865. switch ( tx_state[ endpoint ] )
  866. {
  867. case TX_STATE_BOTH_FREE_EVEN_FIRST:
  868. case TX_STATE_BOTH_FREE_ODD_FIRST:
  869. break;
  870. case TX_STATE_EVEN_FREE:
  871. tx_state[ endpoint ] = TX_STATE_BOTH_FREE_EVEN_FIRST;
  872. break;
  873. case TX_STATE_ODD_FREE:
  874. tx_state[ endpoint ] = TX_STATE_BOTH_FREE_ODD_FIRST;
  875. break;
  876. default:
  877. tx_state[ endpoint ] = ((uint32_t)b & 8)
  878. ? TX_STATE_ODD_FREE
  879. : TX_STATE_EVEN_FREE;
  880. break;
  881. }
  882. }
  883. }
  884. else
  885. { // receive
  886. packet->len = b->desc >> 16;
  887. if ( packet->len > 0 )
  888. {
  889. packet->index = 0;
  890. packet->next = NULL;
  891. if ( rx_first[ endpoint ] == NULL )
  892. {
  893. //serial_print("rx 1st, epidx=");
  894. //serial_phex(endpoint);
  895. //serial_print(", packet=");
  896. //serial_phex32((uint32_t)packet);
  897. //serial_print("\n");
  898. rx_first[ endpoint ] = packet;
  899. }
  900. else
  901. {
  902. //serial_print("rx Nth, epidx=");
  903. //serial_phex(endpoint);
  904. //serial_print(", packet=");
  905. //serial_phex32((uint32_t)packet);
  906. //serial_print("\n");
  907. rx_last[ endpoint ]->next = packet;
  908. }
  909. rx_last[ endpoint ] = packet;
  910. usb_rx_byte_count_data[ endpoint ] += packet->len;
  911. // TODO: implement a per-endpoint maximum # of allocated packets
  912. // so a flood of incoming data on 1 endpoint doesn't starve
  913. // the others if the user isn't reading it regularly
  914. packet = usb_malloc();
  915. if ( packet )
  916. {
  917. b->addr = packet->buf;
  918. b->desc = BDT_DESC( 64, ((uint32_t)b & 8) ? DATA1 : DATA0 );
  919. }
  920. else
  921. {
  922. //serial_print("starving ");
  923. //serial_phex(endpoint + 1);
  924. //serial_print(((uint32_t)b & 8) ? ",odd\n" : ",even\n");
  925. b->desc = 0;
  926. usb_rx_memory_needed++;
  927. }
  928. }
  929. else
  930. {
  931. b->desc = BDT_DESC( 64, ((uint32_t)b & 8) ? DATA1 : DATA0 );
  932. }
  933. }
  934. }
  935. USB0_ISTAT = USB_ISTAT_TOKDNE;
  936. goto restart;
  937. }
  938. if ( status & USB_ISTAT_USBRST /* 01 */ )
  939. {
  940. //serial_print("reset\n");
  941. // initialize BDT toggle bits
  942. USB0_CTL = USB_CTL_ODDRST;
  943. ep0_tx_bdt_bank = 0;
  944. // set up buffers to receive Setup and OUT packets
  945. table[index( 0, RX, EVEN ) ].desc = BDT_DESC( EP0_SIZE, 0 );
  946. table[index( 0, RX, EVEN ) ].addr = ep0_rx0_buf;
  947. table[index( 0, RX, ODD ) ].desc = BDT_DESC( EP0_SIZE, 0 );
  948. table[index( 0, RX, ODD ) ].addr = ep0_rx1_buf;
  949. table[index( 0, TX, EVEN ) ].desc = 0;
  950. table[index( 0, TX, ODD ) ].desc = 0;
  951. // activate endpoint 0
  952. USB0_ENDPT0 = USB_ENDPT_EPRXEN | USB_ENDPT_EPTXEN | USB_ENDPT_EPHSHK;
  953. // clear all ending interrupts
  954. USB0_ERRSTAT = 0xFF;
  955. USB0_ISTAT = 0xFF;
  956. // set the address to zero during enumeration
  957. USB0_ADDR = 0;
  958. // enable other interrupts
  959. USB0_ERREN = 0xFF;
  960. USB0_INTEN = USB_INTEN_TOKDNEEN |
  961. USB_INTEN_SOFTOKEN |
  962. USB_INTEN_STALLEN |
  963. USB_INTEN_ERROREN |
  964. USB_INTEN_USBRSTEN |
  965. USB_INTEN_SLEEPEN;
  966. // is this necessary?
  967. USB0_CTL = USB_CTL_USBENSOFEN;
  968. return;
  969. }
  970. if ( (status & USB_ISTAT_STALL /* 80 */ ) )
  971. {
  972. //serial_print("stall:\n");
  973. USB0_ENDPT0 = USB_ENDPT_EPRXEN | USB_ENDPT_EPTXEN | USB_ENDPT_EPHSHK;
  974. USB0_ISTAT = USB_ISTAT_STALL;
  975. }
  976. if ( (status & USB_ISTAT_ERROR /* 02 */ ) )
  977. {
  978. uint8_t err = USB0_ERRSTAT;
  979. USB0_ERRSTAT = err;
  980. //serial_print("err:");
  981. //serial_phex(err);
  982. //serial_print("\n");
  983. USB0_ISTAT = USB_ISTAT_ERROR;
  984. }
  985. if ( (status & USB_ISTAT_SLEEP /* 10 */ ) )
  986. {
  987. //serial_print("sleep\n");
  988. USB0_ISTAT = USB_ISTAT_SLEEP;
  989. }
  990. }
  991. uint8_t usb_init()
  992. {
  993. #ifdef UART_DEBUG
  994. print("USB INIT"NL);
  995. #endif
  996. // If no USB cable is attached, do not initialize usb
  997. // XXX Test -HaaTa
  998. //if ( USB0_OTGISTAT & USB_OTGSTAT_ID )
  999. // return 0;
  1000. // Clear out endpoints table
  1001. for ( int i = 0; i <= NUM_ENDPOINTS * 4; i++ )
  1002. {
  1003. table[i].desc = 0;
  1004. table[i].addr = 0;
  1005. }
  1006. // this basically follows the flowchart in the Kinetis
  1007. // Quick Reference User Guide, Rev. 1, 03/2012, page 141
  1008. // assume 48 MHz clock already running
  1009. // SIM - enable clock
  1010. SIM_SCGC4 |= SIM_SCGC4_USBOTG;
  1011. // reset USB module
  1012. USB0_USBTRC0 = USB_USBTRC_USBRESET;
  1013. while ( (USB0_USBTRC0 & USB_USBTRC_USBRESET) != 0 ); // wait for reset to end
  1014. // set desc table base addr
  1015. USB0_BDTPAGE1 = ((uint32_t)table) >> 8;
  1016. USB0_BDTPAGE2 = ((uint32_t)table) >> 16;
  1017. USB0_BDTPAGE3 = ((uint32_t)table) >> 24;
  1018. // clear all ISR flags
  1019. USB0_ISTAT = 0xFF;
  1020. USB0_ERRSTAT = 0xFF;
  1021. USB0_OTGISTAT = 0xFF;
  1022. USB0_USBTRC0 |= 0x40; // undocumented bit
  1023. // enable USB
  1024. USB0_CTL = USB_CTL_USBENSOFEN;
  1025. USB0_USBCTRL = 0;
  1026. // enable reset interrupt
  1027. USB0_INTEN = USB_INTEN_USBRSTEN;
  1028. // enable interrupt in NVIC...
  1029. NVIC_SET_PRIORITY( IRQ_USBOTG, 112 );
  1030. NVIC_ENABLE_IRQ( IRQ_USBOTG );
  1031. // enable d+ pullup
  1032. USB0_CONTROL = USB_CONTROL_DPPULLUPNONOTG;
  1033. return 1;
  1034. }
  1035. // return 0 if the USB is not configured, or the configuration
  1036. // number selected by the HOST
  1037. uint8_t usb_configured()
  1038. {
  1039. return usb_configuration;
  1040. }