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 25KB

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