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

usb_dev.c 27KB

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