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

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