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

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