Kiibohd Controller
選択できるのは25トピックまでです。 トピックは、先頭が英数字で、英数字とダッシュ('-')を使用した35文字以内のものにしてください。
このリポジトリはアーカイブされています。 ファイルの閲覧とクローンは可能ですが、プッシュや、課題・プルリクエストのオープンはできません。

usb_dev.c 28KB

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