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 29KB

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