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

usb_dev.c 29KB

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