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.

1234 line
32KB

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