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

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