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

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156
  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. case TX_STATE_EVEN_FREE:
  197. case TX_STATE_NONE_FREE_EVEN_FIRST:
  198. tx_state[i] = TX_STATE_BOTH_FREE_EVEN_FIRST;
  199. break;
  200. case TX_STATE_ODD_FREE:
  201. case TX_STATE_NONE_FREE_ODD_FIRST:
  202. tx_state[i] = TX_STATE_BOTH_FREE_ODD_FIRST;
  203. break;
  204. default:
  205. break;
  206. }
  207. }
  208. usb_rx_memory_needed = 0;
  209. for ( i = 1; i <= NUM_ENDPOINTS; i++ )
  210. {
  211. epconf = *cfg++;
  212. *reg = epconf;
  213. reg += 4;
  214. if ( epconf & USB_ENDPT_EPRXEN )
  215. {
  216. usb_packet_t *p;
  217. p = usb_malloc();
  218. if ( p )
  219. {
  220. table[index(i, RX, EVEN)].addr = p->buf;
  221. table[index(i, RX, EVEN)].desc = BDT_DESC(64, 0);
  222. }
  223. else
  224. {
  225. table[index(i, RX, EVEN)].desc = 0;
  226. usb_rx_memory_needed++;
  227. }
  228. p = usb_malloc();
  229. if ( p )
  230. {
  231. table[index(i, RX, ODD)].addr = p->buf;
  232. table[index(i, RX, ODD)].desc = BDT_DESC(64, 1);
  233. }
  234. else
  235. {
  236. table[index(i, RX, ODD)].desc = 0;
  237. usb_rx_memory_needed++;
  238. }
  239. }
  240. table[index(i, TX, EVEN)].desc = 0;
  241. table[index(i, TX, ODD)].desc = 0;
  242. }
  243. break;
  244. case 0x0880: // GET_CONFIGURATION
  245. reply_buffer[0] = usb_configuration;
  246. datalen = 1;
  247. data = reply_buffer;
  248. break;
  249. case 0x0080: // GET_STATUS (device)
  250. reply_buffer[0] = 0;
  251. reply_buffer[1] = 0;
  252. datalen = 2;
  253. data = reply_buffer;
  254. break;
  255. case 0x0082: // GET_STATUS (endpoint)
  256. if (setup.wIndex > NUM_ENDPOINTS)
  257. {
  258. // TODO: do we need to handle IN vs OUT here?
  259. endpoint0_stall();
  260. return;
  261. }
  262. reply_buffer[0] = 0;
  263. reply_buffer[1] = 0;
  264. if ( *(uint8_t *)(&USB0_ENDPT0 + setup.wIndex * 4) & 0x02 )
  265. reply_buffer[0] = 1;
  266. data = reply_buffer;
  267. datalen = 2;
  268. break;
  269. case 0x0102: // CLEAR_FEATURE (endpoint)
  270. i = setup.wIndex & 0x7F;
  271. if ( i > NUM_ENDPOINTS || setup.wValue != 0 )
  272. {
  273. // TODO: do we need to handle IN vs OUT here?
  274. endpoint0_stall();
  275. return;
  276. }
  277. (*(uint8_t *)(&USB0_ENDPT0 + setup.wIndex * 4)) &= ~0x02;
  278. // TODO: do we need to clear the data toggle here?
  279. break;
  280. case 0x0302: // SET_FEATURE (endpoint)
  281. i = setup.wIndex & 0x7F;
  282. if ( i > NUM_ENDPOINTS || setup.wValue != 0 )
  283. {
  284. // TODO: do we need to handle IN vs OUT here?
  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. break;
  291. case 0x0680: // GET_DESCRIPTOR
  292. case 0x0681:
  293. #ifdef UART_DEBUG
  294. print("desc:");
  295. printHex(setup.wValue);
  296. print(NL);
  297. #endif
  298. for ( list = usb_descriptor_list; 1; list++ )
  299. {
  300. if ( list->addr == NULL )
  301. break;
  302. //if (setup.wValue == list->wValue &&
  303. //(setup.wIndex == list->wIndex) || ((setup.wValue >> 8) == 3)) {
  304. if ( setup.wValue == list->wValue && setup.wIndex == list->wIndex )
  305. {
  306. data = list->addr;
  307. if ( (setup.wValue >> 8) == 3 )
  308. {
  309. // for string descriptors, use the descriptor's
  310. // length field, allowing runtime configured
  311. // length.
  312. datalen = *(list->addr);
  313. }
  314. else
  315. {
  316. datalen = list->length;
  317. }
  318. #if UART_DEBUG
  319. print("Desc found, ");
  320. printHex32((uint32_t)data);
  321. print(",");
  322. printHex(datalen);
  323. print(",");
  324. printHex_op(data[0], 2);
  325. printHex_op(data[1], 2);
  326. printHex_op(data[2], 2);
  327. printHex_op(data[3], 2);
  328. printHex_op(data[4], 2);
  329. printHex_op(data[5], 2);
  330. print(NL);
  331. #endif
  332. goto send;
  333. }
  334. }
  335. #ifdef UART_DEBUG
  336. print("desc: not found"NL);
  337. #endif
  338. endpoint0_stall();
  339. return;
  340. case 0x2221: // CDC_SET_CONTROL_LINE_STATE
  341. usb_cdc_line_rtsdtr = setup.wValue;
  342. //serial_print("set control line state\n");
  343. endpoint0_stall();
  344. return;
  345. case 0x21A1: // CDC_GET_LINE_CODING
  346. data = (uint8_t*)usb_cdc_line_coding;
  347. datalen = sizeof( usb_cdc_line_coding );
  348. goto send;
  349. case 0x2021: // CDC_SET_LINE_CODING
  350. // XXX Needed?
  351. //serial_print("set coding, waiting...\n");
  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. if (*cfg++ & USB_ENDPT_EPRXEN) {
  652. if ( table[ index( i, RX, EVEN ) ].desc == 0 )
  653. {
  654. table[index(i, RX, EVEN)].addr = packet->buf;
  655. table[index(i, RX, EVEN)].desc = BDT_DESC( 64, 0 );
  656. usb_rx_memory_needed--;
  657. __enable_irq();
  658. //serial_phex(i);
  659. //serial_print(",even\n");
  660. return;
  661. }
  662. if ( table[ index( i, RX, ODD ) ].desc == 0 )
  663. {
  664. table[ index( i, RX, ODD ) ].addr = packet->buf;
  665. table[ index( i, RX, ODD ) ].desc = BDT_DESC( 64, 1 );
  666. usb_rx_memory_needed--;
  667. __enable_irq();
  668. //serial_phex(i);
  669. //serial_print(",odd\n");
  670. return;
  671. }
  672. }
  673. }
  674. __enable_irq();
  675. // we should never reach this point. If we get here, it means
  676. // usb_rx_memory_needed was set greater than zero, but no memory
  677. // was actually needed.
  678. usb_rx_memory_needed = 0;
  679. usb_free( packet );
  680. return;
  681. }
  682. //#define index(endpoint, tx, odd) (((endpoint) << 2) | ((tx) << 1) | (odd))
  683. //#define stat2bufferdescriptor(stat) (table + ((stat) >> 2))
  684. void usb_tx( uint32_t endpoint, usb_packet_t *packet )
  685. {
  686. bdt_t *b = &table[ index( endpoint, TX, EVEN ) ];
  687. uint8_t next;
  688. endpoint--;
  689. if ( endpoint >= NUM_ENDPOINTS )
  690. return;
  691. __disable_irq();
  692. //serial_print("txstate=");
  693. //serial_phex(tx_state[ endpoint ]);
  694. //serial_print("\n");
  695. switch ( tx_state[ endpoint ] )
  696. {
  697. case TX_STATE_BOTH_FREE_EVEN_FIRST:
  698. next = TX_STATE_ODD_FREE;
  699. break;
  700. case TX_STATE_BOTH_FREE_ODD_FIRST:
  701. b++;
  702. next = TX_STATE_EVEN_FREE;
  703. break;
  704. case TX_STATE_EVEN_FREE:
  705. next = TX_STATE_NONE_FREE_ODD_FIRST;
  706. break;
  707. case TX_STATE_ODD_FREE:
  708. b++;
  709. next = TX_STATE_NONE_FREE_EVEN_FIRST;
  710. break;
  711. default:
  712. if (tx_first[ endpoint ] == NULL)
  713. {
  714. tx_first[ endpoint ] = packet;
  715. }
  716. else
  717. {
  718. tx_last[ endpoint ]->next = packet;
  719. }
  720. tx_last[ endpoint ] = packet;
  721. __enable_irq();
  722. return;
  723. }
  724. tx_state[ endpoint ] = next;
  725. b->addr = packet->buf;
  726. b->desc = BDT_DESC( packet->len, ((uint32_t)b & 8) ? DATA1 : DATA0 );
  727. __enable_irq();
  728. }
  729. void usb_device_reload()
  730. {
  731. // MCHCK
  732. #if defined(_mk20dx128vlf5_)
  733. // MCHCK Kiibohd Variant
  734. // Check to see if PTA3 (has a pull-up) is connected to GND (usually via jumper)
  735. // Only allow reload if the jumper is present (security)
  736. GPIOA_PDDR &= ~(1<<3); // Input
  737. PORTA_PCR3 = PORT_PCR_PFE | PORT_PCR_MUX(1); // Internal pull-up
  738. // Check for jumper
  739. if ( GPIOA_PDIR & (1<<3) )
  740. {
  741. print( NL );
  742. warn_print("Security jumper not present, cancelling firmware reload...");
  743. info_msg("Replace jumper on middle 2 pins, or manually press the firmware reload button.");
  744. }
  745. else
  746. {
  747. // Copies variable into the VBAT register, must be identical to the variable in the bootloader to jump to the bootloader flash mode
  748. for ( int pos = 0; pos < sizeof(sys_reset_to_loader_magic); pos++ )
  749. (&VBAT)[ pos ] = sys_reset_to_loader_magic[ pos ];
  750. SOFTWARE_RESET();
  751. }
  752. // Teensy 3.0 and 3.1
  753. #else
  754. asm volatile("bkpt");
  755. #endif
  756. }
  757. void usb_isr()
  758. {
  759. uint8_t status, stat, t;
  760. //serial_print("isr");
  761. //status = USB0_ISTAT;
  762. //serial_phex(status);
  763. //serial_print("\n");
  764. restart:
  765. status = USB0_ISTAT;
  766. /*
  767. print("USB ISR STATUS: ");
  768. printHex( status );
  769. print( NL );
  770. */
  771. if ( (status & USB_INTEN_SOFTOKEN /* 04 */ ) )
  772. {
  773. if ( usb_configuration )
  774. {
  775. t = usb_reboot_timer;
  776. if ( t )
  777. {
  778. usb_reboot_timer = --t;
  779. if ( !t )
  780. usb_device_reload();
  781. }
  782. // CDC Interface
  783. t = usb_cdc_transmit_flush_timer;
  784. if ( t )
  785. {
  786. usb_cdc_transmit_flush_timer = --t;
  787. if ( t == 0 )
  788. usb_serial_flush_callback();
  789. }
  790. }
  791. USB0_ISTAT = USB_INTEN_SOFTOKEN;
  792. }
  793. if ( (status & USB_ISTAT_TOKDNE /* 08 */ ) )
  794. {
  795. uint8_t endpoint;
  796. stat = USB0_STAT;
  797. //serial_print("token: ep=");
  798. //serial_phex(stat >> 4);
  799. //serial_print(stat & 0x08 ? ",tx" : ",rx");
  800. //serial_print(stat & 0x04 ? ",odd\n" : ",even\n");
  801. endpoint = stat >> 4;
  802. if ( endpoint == 0 )
  803. {
  804. usb_control( stat );
  805. }
  806. else
  807. {
  808. bdt_t *b = stat2bufferdescriptor(stat);
  809. usb_packet_t *packet = (usb_packet_t *)((uint8_t *)(b->addr) - 8);
  810. #if 0
  811. serial_print("ep:");
  812. serial_phex(endpoint);
  813. serial_print(", pid:");
  814. serial_phex(BDT_PID(b->desc));
  815. serial_print(((uint32_t)b & 8) ? ", odd" : ", even");
  816. serial_print(", count:");
  817. serial_phex(b->desc >> 16);
  818. serial_print("\n");
  819. #endif
  820. endpoint--; // endpoint is index to zero-based arrays
  821. if ( stat & 0x08 )
  822. { // transmit
  823. usb_free( packet );
  824. packet = tx_first[endpoint];
  825. if ( packet )
  826. {
  827. //serial_print("tx packet\n");
  828. tx_first[endpoint] = packet->next;
  829. b->addr = packet->buf;
  830. switch ( tx_state[ endpoint ] )
  831. {
  832. case TX_STATE_BOTH_FREE_EVEN_FIRST:
  833. tx_state[endpoint] = TX_STATE_ODD_FREE;
  834. break;
  835. case TX_STATE_BOTH_FREE_ODD_FIRST:
  836. tx_state[endpoint] = TX_STATE_EVEN_FREE;
  837. break;
  838. case TX_STATE_EVEN_FREE:
  839. tx_state[endpoint] = TX_STATE_NONE_FREE_ODD_FIRST;
  840. break;
  841. case TX_STATE_ODD_FREE:
  842. tx_state[endpoint] = TX_STATE_NONE_FREE_EVEN_FIRST;
  843. break;
  844. default:
  845. break;
  846. }
  847. b->desc = BDT_DESC(packet->len, ((uint32_t)b & 8) ? DATA1 : DATA0);
  848. } else {
  849. //serial_print("tx no packet\n");
  850. switch ( tx_state[ endpoint ] )
  851. {
  852. case TX_STATE_BOTH_FREE_EVEN_FIRST:
  853. case TX_STATE_BOTH_FREE_ODD_FIRST:
  854. break;
  855. case TX_STATE_EVEN_FREE:
  856. tx_state[endpoint] = TX_STATE_BOTH_FREE_EVEN_FIRST;
  857. break;
  858. case TX_STATE_ODD_FREE:
  859. tx_state[endpoint] = TX_STATE_BOTH_FREE_ODD_FIRST;
  860. break;
  861. default:
  862. tx_state[endpoint] = ((uint32_t)b & 8)
  863. ? TX_STATE_ODD_FREE
  864. : TX_STATE_EVEN_FREE;
  865. break;
  866. }
  867. }
  868. }
  869. else
  870. { // receive
  871. packet->len = b->desc >> 16;
  872. if (packet->len > 0) {
  873. packet->index = 0;
  874. packet->next = NULL;
  875. if (rx_first[endpoint] == NULL)
  876. {
  877. //serial_print("rx 1st, epidx=");
  878. //serial_phex(endpoint);
  879. //serial_print(", packet=");
  880. //serial_phex32((uint32_t)packet);
  881. //serial_print("\n");
  882. rx_first[endpoint] = packet;
  883. }
  884. else
  885. {
  886. //serial_print("rx Nth, epidx=");
  887. //serial_phex(endpoint);
  888. //serial_print(", packet=");
  889. //serial_phex32((uint32_t)packet);
  890. //serial_print("\n");
  891. rx_last[endpoint]->next = packet;
  892. }
  893. rx_last[endpoint] = packet;
  894. usb_rx_byte_count_data[endpoint] += packet->len;
  895. // TODO: implement a per-endpoint maximum # of allocated packets
  896. // so a flood of incoming data on 1 endpoint doesn't starve
  897. // the others if the user isn't reading it regularly
  898. packet = usb_malloc();
  899. if ( packet )
  900. {
  901. b->addr = packet->buf;
  902. b->desc = BDT_DESC(64, ((uint32_t)b & 8) ? DATA1 : DATA0);
  903. }
  904. else
  905. {
  906. //serial_print("starving ");
  907. //serial_phex(endpoint + 1);
  908. //serial_print(((uint32_t)b & 8) ? ",odd\n" : ",even\n");
  909. b->desc = 0;
  910. usb_rx_memory_needed++;
  911. }
  912. }
  913. else
  914. {
  915. b->desc = BDT_DESC(64, ((uint32_t)b & 8) ? DATA1 : DATA0);
  916. }
  917. }
  918. }
  919. USB0_ISTAT = USB_ISTAT_TOKDNE;
  920. goto restart;
  921. }
  922. if ( status & USB_ISTAT_USBRST /* 01 */ )
  923. {
  924. //serial_print("reset\n");
  925. // initialize BDT toggle bits
  926. USB0_CTL = USB_CTL_ODDRST;
  927. ep0_tx_bdt_bank = 0;
  928. // set up buffers to receive Setup and OUT packets
  929. table[index(0, RX, EVEN)].desc = BDT_DESC(EP0_SIZE, 0);
  930. table[index(0, RX, EVEN)].addr = ep0_rx0_buf;
  931. table[index(0, RX, ODD)].desc = BDT_DESC(EP0_SIZE, 0);
  932. table[index(0, RX, ODD)].addr = ep0_rx1_buf;
  933. table[index(0, TX, EVEN)].desc = 0;
  934. table[index(0, TX, ODD)].desc = 0;
  935. // activate endpoint 0
  936. USB0_ENDPT0 = USB_ENDPT_EPRXEN | USB_ENDPT_EPTXEN | USB_ENDPT_EPHSHK;
  937. // clear all ending interrupts
  938. USB0_ERRSTAT = 0xFF;
  939. USB0_ISTAT = 0xFF;
  940. // set the address to zero during enumeration
  941. USB0_ADDR = 0;
  942. // enable other interrupts
  943. USB0_ERREN = 0xFF;
  944. USB0_INTEN = USB_INTEN_TOKDNEEN |
  945. USB_INTEN_SOFTOKEN |
  946. USB_INTEN_STALLEN |
  947. USB_INTEN_ERROREN |
  948. USB_INTEN_USBRSTEN |
  949. USB_INTEN_SLEEPEN;
  950. // is this necessary?
  951. USB0_CTL = USB_CTL_USBENSOFEN;
  952. return;
  953. }
  954. if ( (status & USB_ISTAT_STALL /* 80 */ ) )
  955. {
  956. //serial_print("stall:\n");
  957. USB0_ENDPT0 = USB_ENDPT_EPRXEN | USB_ENDPT_EPTXEN | USB_ENDPT_EPHSHK;
  958. USB0_ISTAT = USB_ISTAT_STALL;
  959. }
  960. if ( (status & USB_ISTAT_ERROR /* 02 */ ) )
  961. {
  962. uint8_t err = USB0_ERRSTAT;
  963. USB0_ERRSTAT = err;
  964. //serial_print("err:");
  965. //serial_phex(err);
  966. //serial_print("\n");
  967. USB0_ISTAT = USB_ISTAT_ERROR;
  968. }
  969. if ( (status & USB_ISTAT_SLEEP /* 10 */ ) )
  970. {
  971. //serial_print("sleep\n");
  972. USB0_ISTAT = USB_ISTAT_SLEEP;
  973. }
  974. }
  975. void usb_init()
  976. {
  977. #ifdef UART_DEBUG
  978. print("USB INIT"NL);
  979. #endif
  980. // Clear out endpoints table
  981. for ( int i = 0; i <= NUM_ENDPOINTS * 4; i++ )
  982. {
  983. table[i].desc = 0;
  984. table[i].addr = 0;
  985. }
  986. // this basically follows the flowchart in the Kinetis
  987. // Quick Reference User Guide, Rev. 1, 03/2012, page 141
  988. // assume 48 MHz clock already running
  989. // SIM - enable clock
  990. SIM_SCGC4 |= SIM_SCGC4_USBOTG;
  991. // reset USB module
  992. USB0_USBTRC0 = USB_USBTRC_USBRESET;
  993. while ( (USB0_USBTRC0 & USB_USBTRC_USBRESET) != 0 ); // wait for reset to end
  994. // set desc table base addr
  995. USB0_BDTPAGE1 = ((uint32_t)table) >> 8;
  996. USB0_BDTPAGE2 = ((uint32_t)table) >> 16;
  997. USB0_BDTPAGE3 = ((uint32_t)table) >> 24;
  998. // clear all ISR flags
  999. USB0_ISTAT = 0xFF;
  1000. USB0_ERRSTAT = 0xFF;
  1001. USB0_OTGISTAT = 0xFF;
  1002. USB0_USBTRC0 |= 0x40; // undocumented bit
  1003. // enable USB
  1004. USB0_CTL = USB_CTL_USBENSOFEN;
  1005. USB0_USBCTRL = 0;
  1006. // enable reset interrupt
  1007. USB0_INTEN = USB_INTEN_USBRSTEN;
  1008. // enable interrupt in NVIC...
  1009. NVIC_SET_PRIORITY( IRQ_USBOTG, 112 );
  1010. NVIC_ENABLE_IRQ( IRQ_USBOTG );
  1011. // enable d+ pullup
  1012. USB0_CONTROL = USB_CONTROL_DPPULLUPNONOTG;
  1013. }
  1014. // return 0 if the USB is not configured, or the configuration
  1015. // number selected by the HOST
  1016. uint8_t usb_configured()
  1017. {
  1018. return usb_configuration;
  1019. }