Teensy 4.1 core updated for C++20
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.

1217 lines
31KB

  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. }
  346. //serial_print("set control line state\n");
  347. break;
  348. #ifdef CDC_STATUS_INTERFACE
  349. case 0x2321: // CDC_SEND_BREAK
  350. break;
  351. case 0x2021: // CDC_SET_LINE_CODING
  352. //serial_print("set coding, waiting...\n");
  353. return;
  354. #endif
  355. #if defined(MTP_INTERFACE)
  356. case 0x64A1: // Cancel Request (PTP spec, 5.2.1, page 8)
  357. // TODO: required by PTP spec
  358. endpoint0_stall();
  359. return;
  360. case 0x66A1: // Device Reset (PTP spec, 5.2.3, page 10)
  361. // TODO: required by PTP spec
  362. endpoint0_stall();
  363. return;
  364. case 0x67A1: // Get Device Statis (PTP spec, 5.2.4, page 10)
  365. // For now, always respond with status ok.
  366. reply_buffer[0] = 0x4;
  367. reply_buffer[1] = 0;
  368. reply_buffer[2] = 0x01;
  369. reply_buffer[3] = 0x20;
  370. data = reply_buffer;
  371. datalen = 4;
  372. break;
  373. #endif
  374. // TODO: this does not work... why?
  375. #if defined(SEREMU_INTERFACE) || defined(KEYBOARD_INTERFACE)
  376. case 0x0921: // HID SET_REPORT
  377. //serial_print(":)\n");
  378. return;
  379. case 0x0A21: // HID SET_IDLE
  380. break;
  381. // case 0xC940:
  382. #endif
  383. #if defined(AUDIO_INTERFACE)
  384. case 0x0B01: // SET_INTERFACE (alternate setting)
  385. if (setup.wIndex == AUDIO_INTERFACE+1) {
  386. usb_audio_transmit_setting = setup.wValue;
  387. if (usb_audio_transmit_setting > 0) {
  388. bdt_t *b = &table[index(AUDIO_TX_ENDPOINT, TX, EVEN)];
  389. uint8_t state = tx_state[AUDIO_TX_ENDPOINT-1];
  390. if (state) b++;
  391. if (!(b->desc & BDT_OWN)) {
  392. memset(usb_audio_transmit_buffer, 0, 176);
  393. b->addr = usb_audio_transmit_buffer;
  394. b->desc = (176 << 16) | BDT_OWN;
  395. tx_state[AUDIO_TX_ENDPOINT-1] = state ^ 1;
  396. }
  397. }
  398. } else if (setup.wIndex == AUDIO_INTERFACE+2) {
  399. usb_audio_receive_setting = setup.wValue;
  400. } else {
  401. endpoint0_stall();
  402. return;
  403. }
  404. break;
  405. case 0x0A81: // GET_INTERFACE (alternate setting)
  406. datalen = 1;
  407. data = reply_buffer;
  408. if (setup.wIndex == AUDIO_INTERFACE+1) {
  409. reply_buffer[0] = usb_audio_transmit_setting;
  410. } else if (setup.wIndex == AUDIO_INTERFACE+2) {
  411. reply_buffer[0] = usb_audio_receive_setting;
  412. } else {
  413. endpoint0_stall();
  414. return;
  415. }
  416. break;
  417. case 0x0121: // SET FEATURE
  418. case 0x0221:
  419. case 0x0321:
  420. case 0x0421:
  421. // handle these on the next packet. See usb_audio_set_feature()
  422. return;
  423. case 0x81A1: // GET FEATURE
  424. case 0x82A1:
  425. case 0x83A1:
  426. case 0x84A1:
  427. if (usb_audio_get_feature(&setup, reply_buffer, &datalen)) {
  428. data = reply_buffer;
  429. }
  430. else {
  431. endpoint0_stall();
  432. return;
  433. }
  434. break;
  435. case 0x81A2: // GET_CUR (wValue=0, wIndex=interface, wLength=len)
  436. if (setup.wLength >= 3) {
  437. reply_buffer[0] = 44100 & 255;
  438. reply_buffer[1] = 44100 >> 8;
  439. reply_buffer[2] = 0;
  440. datalen = 3;
  441. data = reply_buffer;
  442. } else {
  443. endpoint0_stall();
  444. return;
  445. }
  446. break;
  447. #endif
  448. #if defined(MULTITOUCH_INTERFACE)
  449. case 0x01A1:
  450. if (setup.wValue == 0x0300 && setup.wIndex == MULTITOUCH_INTERFACE) {
  451. reply_buffer[0] = MULTITOUCH_FINGERS;
  452. data = reply_buffer;
  453. datalen = 1;
  454. } else if (setup.wValue == 0x0100 && setup.wIndex == MULTITOUCH_INTERFACE) {
  455. memset(reply_buffer, 0, 8);
  456. data = reply_buffer;
  457. datalen = 8;
  458. } else {
  459. endpoint0_stall();
  460. return;
  461. }
  462. break;
  463. #endif
  464. default:
  465. endpoint0_stall();
  466. return;
  467. }
  468. send:
  469. //serial_print("setup send ");
  470. //serial_phex32(data);
  471. //serial_print(",");
  472. //serial_phex16(datalen);
  473. //serial_print("\n");
  474. if (datalen > setup.wLength) datalen = setup.wLength;
  475. size = datalen;
  476. if (size > EP0_SIZE) size = EP0_SIZE;
  477. endpoint0_transmit(data, size);
  478. data += size;
  479. datalen -= size;
  480. if (datalen == 0 && size < EP0_SIZE) return;
  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. ep0_tx_ptr = data;
  488. ep0_tx_len = datalen;
  489. }
  490. //A bulk endpoint's toggle sequence is initialized to DATA0 when the endpoint
  491. //experiences any configuration event (configuration events are explained in
  492. //Sections 9.1.1.5 and 9.4.5).
  493. //Configuring a device or changing an alternate setting causes all of the status
  494. //and configuration values associated with endpoints in the affected interfaces
  495. //to be set to their default values. This includes setting the data toggle of
  496. //any endpoint using data toggles to the value DATA0.
  497. //For endpoints using data toggle, regardless of whether an endpoint has the
  498. //Halt feature set, a ClearFeature(ENDPOINT_HALT) request always results in the
  499. //data toggle being reinitialized to DATA0.
  500. // #define stat2bufferdescriptor(stat) (table + ((stat) >> 2))
  501. static void usb_control(uint32_t stat)
  502. {
  503. bdt_t *b;
  504. uint32_t pid, size;
  505. uint8_t *buf;
  506. const uint8_t *data;
  507. b = stat2bufferdescriptor(stat);
  508. pid = BDT_PID(b->desc);
  509. //count = b->desc >> 16;
  510. buf = b->addr;
  511. //serial_print("pid:");
  512. //serial_phex(pid);
  513. //serial_print(", count:");
  514. //serial_phex(count);
  515. //serial_print("\n");
  516. switch (pid) {
  517. case 0x0D: // Setup received from host
  518. //serial_print("PID=Setup\n");
  519. //if (count != 8) ; // panic?
  520. // grab the 8 byte setup info
  521. setup.word1 = *(uint32_t *)(buf);
  522. setup.word2 = *(uint32_t *)(buf + 4);
  523. // give the buffer back
  524. b->desc = BDT_DESC(EP0_SIZE, DATA1);
  525. //table[index(0, RX, EVEN)].desc = BDT_DESC(EP0_SIZE, 1);
  526. //table[index(0, RX, ODD)].desc = BDT_DESC(EP0_SIZE, 1);
  527. // clear any leftover pending IN transactions
  528. ep0_tx_ptr = NULL;
  529. if (ep0_tx_data_toggle) {
  530. }
  531. //if (table[index(0, TX, EVEN)].desc & 0x80) {
  532. //serial_print("leftover tx even\n");
  533. //}
  534. //if (table[index(0, TX, ODD)].desc & 0x80) {
  535. //serial_print("leftover tx odd\n");
  536. //}
  537. table[index(0, TX, EVEN)].desc = 0;
  538. table[index(0, TX, ODD)].desc = 0;
  539. // first IN after Setup is always DATA1
  540. ep0_tx_data_toggle = 1;
  541. #if 0
  542. serial_print("bmRequestType:");
  543. serial_phex(setup.bmRequestType);
  544. serial_print(", bRequest:");
  545. serial_phex(setup.bRequest);
  546. serial_print(", wValue:");
  547. serial_phex16(setup.wValue);
  548. serial_print(", wIndex:");
  549. serial_phex16(setup.wIndex);
  550. serial_print(", len:");
  551. serial_phex16(setup.wLength);
  552. serial_print("\n");
  553. #endif
  554. // actually "do" the setup request
  555. usb_setup();
  556. // unfreeze the USB, now that we're ready
  557. USB0_CTL = USB_CTL_USBENSOFEN; // clear TXSUSPENDTOKENBUSY bit
  558. break;
  559. case 0x01: // OUT transaction received from host
  560. case 0x02:
  561. //serial_print("PID=OUT\n");
  562. if (setup.wRequestAndType == 0x2021 /*CDC_SET_LINE_CODING*/) {
  563. int i;
  564. uint8_t *dst = NULL;
  565. switch (setup.wIndex) {
  566. #ifdef CDC_STATUS_INTERFACE
  567. case CDC_STATUS_INTERFACE:
  568. dst = (uint8_t *)usb_cdc_line_coding;
  569. break;
  570. #endif
  571. #ifdef CDC2_STATUS_INTERFACE
  572. case CDC2_STATUS_INTERFACE:
  573. dst = (uint8_t *)usb_cdc2_line_coding;
  574. break;
  575. #endif
  576. }
  577. if (!dst)
  578. break;
  579. //serial_print("set line coding ");
  580. for (i=0; i<7; i++) {
  581. //serial_phex(*buf);
  582. *dst++ = *buf++;
  583. }
  584. //serial_phex32(usb_cdc_line_coding[0]);
  585. //serial_print("\n");
  586. #ifdef CDC_STATUS_INTERFACE
  587. if (setup.wIndex == CDC_STATUS_INTERFACE &&
  588. usb_cdc_line_coding[0] == 134)
  589. usb_reboot_timer = 15;
  590. #endif
  591. endpoint0_transmit(NULL, 0);
  592. }
  593. #ifdef KEYBOARD_INTERFACE
  594. if (setup.word1 == 0x02000921 && setup.word2 == ((1<<16)|KEYBOARD_INTERFACE)) {
  595. keyboard_leds = buf[0];
  596. endpoint0_transmit(NULL, 0);
  597. }
  598. #endif
  599. #ifdef SEREMU_INTERFACE
  600. if (setup.word1 == 0x03000921 && setup.word2 == ((4<<16)|SEREMU_INTERFACE)
  601. && buf[0] == 0xA9 && buf[1] == 0x45 && buf[2] == 0xC2 && buf[3] == 0x6B) {
  602. usb_reboot_timer = 5;
  603. endpoint0_transmit(NULL, 0);
  604. }
  605. #endif
  606. #ifdef AUDIO_INTERFACE
  607. if (usb_audio_set_feature(&setup, buf)) {
  608. endpoint0_transmit(NULL, 0);
  609. }
  610. #endif
  611. // give the buffer back
  612. b->desc = BDT_DESC(EP0_SIZE, DATA1);
  613. break;
  614. case 0x09: // IN transaction completed to host
  615. //serial_print("PID=IN:");
  616. //serial_phex(stat);
  617. //serial_print("\n");
  618. // send remaining data, if any...
  619. data = ep0_tx_ptr;
  620. if (data) {
  621. size = ep0_tx_len;
  622. if (size > EP0_SIZE) size = EP0_SIZE;
  623. endpoint0_transmit(data, size);
  624. data += size;
  625. ep0_tx_len -= size;
  626. ep0_tx_ptr = (ep0_tx_len > 0 || size == EP0_SIZE) ? data : NULL;
  627. }
  628. if (setup.bRequest == 5 && setup.bmRequestType == 0) {
  629. setup.bRequest = 0;
  630. //serial_print("set address: ");
  631. //serial_phex16(setup.wValue);
  632. //serial_print("\n");
  633. USB0_ADDR = setup.wValue;
  634. }
  635. break;
  636. //default:
  637. //serial_print("PID=unknown:");
  638. //serial_phex(pid);
  639. //serial_print("\n");
  640. }
  641. USB0_CTL = USB_CTL_USBENSOFEN; // clear TXSUSPENDTOKENBUSY bit
  642. }
  643. usb_packet_t *usb_rx(uint32_t endpoint)
  644. {
  645. usb_packet_t *ret;
  646. endpoint--;
  647. if (endpoint >= NUM_ENDPOINTS) return NULL;
  648. __disable_irq();
  649. ret = rx_first[endpoint];
  650. if (ret) {
  651. rx_first[endpoint] = ret->next;
  652. usb_rx_byte_count_data[endpoint] -= ret->len;
  653. }
  654. __enable_irq();
  655. //serial_print("rx, epidx=");
  656. //serial_phex(endpoint);
  657. //serial_print(", packet=");
  658. //serial_phex32(ret);
  659. //serial_print("\n");
  660. return ret;
  661. }
  662. static uint32_t usb_queue_byte_count(const usb_packet_t *p)
  663. {
  664. uint32_t count=0;
  665. __disable_irq();
  666. for ( ; p; p = p->next) {
  667. count += p->len;
  668. }
  669. __enable_irq();
  670. return count;
  671. }
  672. // TODO: make this an inline function...
  673. /*
  674. uint32_t usb_rx_byte_count(uint32_t endpoint)
  675. {
  676. endpoint--;
  677. if (endpoint >= NUM_ENDPOINTS) return 0;
  678. return usb_rx_byte_count_data[endpoint];
  679. //return usb_queue_byte_count(rx_first[endpoint]);
  680. }
  681. */
  682. uint32_t usb_tx_byte_count(uint32_t endpoint)
  683. {
  684. endpoint--;
  685. if (endpoint >= NUM_ENDPOINTS) return 0;
  686. return usb_queue_byte_count(tx_first[endpoint]);
  687. }
  688. // Discussion about using this function and USB transmit latency
  689. // https://forum.pjrc.com/threads/58663?p=223513&viewfull=1#post223513
  690. //
  691. uint32_t usb_tx_packet_count(uint32_t endpoint)
  692. {
  693. const usb_packet_t *p;
  694. uint32_t count=0;
  695. endpoint--;
  696. if (endpoint >= NUM_ENDPOINTS) return 0;
  697. __disable_irq();
  698. for (p = tx_first[endpoint]; p; p = p->next) count++;
  699. __enable_irq();
  700. return count;
  701. }
  702. // Called from usb_free, but only when usb_rx_memory_needed > 0, indicating
  703. // receive endpoints are starving for memory. The intention is to give
  704. // endpoints needing receive memory priority over the user's code, which is
  705. // likely calling usb_malloc to obtain memory for transmitting. When the
  706. // user is creating data very quickly, their consumption could starve reception
  707. // without this prioritization. The packet buffer (input) is assigned to the
  708. // first endpoint needing memory.
  709. //
  710. void usb_rx_memory(usb_packet_t *packet)
  711. {
  712. unsigned int i;
  713. const uint8_t *cfg;
  714. cfg = usb_endpoint_config_table;
  715. //serial_print("rx_mem:");
  716. __disable_irq();
  717. for (i=1; i <= NUM_ENDPOINTS; i++) {
  718. #ifdef AUDIO_INTERFACE
  719. if (i == AUDIO_RX_ENDPOINT) continue;
  720. #endif
  721. if (*cfg++ & USB_ENDPT_EPRXEN) {
  722. if (table[index(i, RX, EVEN)].desc == 0) {
  723. table[index(i, RX, EVEN)].addr = packet->buf;
  724. table[index(i, RX, EVEN)].desc = BDT_DESC(64, 0);
  725. usb_rx_memory_needed--;
  726. __enable_irq();
  727. //serial_phex(i);
  728. //serial_print(",even\n");
  729. return;
  730. }
  731. if (table[index(i, RX, ODD)].desc == 0) {
  732. table[index(i, RX, ODD)].addr = packet->buf;
  733. table[index(i, RX, ODD)].desc = BDT_DESC(64, 1);
  734. usb_rx_memory_needed--;
  735. __enable_irq();
  736. //serial_phex(i);
  737. //serial_print(",odd\n");
  738. return;
  739. }
  740. }
  741. }
  742. __enable_irq();
  743. // we should never reach this point. If we get here, it means
  744. // usb_rx_memory_needed was set greater than zero, but no memory
  745. // was actually needed.
  746. usb_rx_memory_needed = 0;
  747. usb_free(packet);
  748. return;
  749. }
  750. //#define index(endpoint, tx, odd) (((endpoint) << 2) | ((tx) << 1) | (odd))
  751. //#define stat2bufferdescriptor(stat) (table + ((stat) >> 2))
  752. void usb_tx(uint32_t endpoint, usb_packet_t *packet)
  753. {
  754. bdt_t *b = &table[index(endpoint, TX, EVEN)];
  755. uint8_t next;
  756. endpoint--;
  757. if (endpoint >= NUM_ENDPOINTS) return;
  758. __disable_irq();
  759. //serial_print("txstate=");
  760. //serial_phex(tx_state[endpoint]);
  761. //serial_print("\n");
  762. switch (tx_state[endpoint]) {
  763. case TX_STATE_BOTH_FREE_EVEN_FIRST:
  764. next = TX_STATE_ODD_FREE;
  765. break;
  766. case TX_STATE_BOTH_FREE_ODD_FIRST:
  767. b++;
  768. next = TX_STATE_EVEN_FREE;
  769. break;
  770. case TX_STATE_EVEN_FREE:
  771. next = TX_STATE_NONE_FREE_ODD_FIRST;
  772. break;
  773. case TX_STATE_ODD_FREE:
  774. b++;
  775. next = TX_STATE_NONE_FREE_EVEN_FIRST;
  776. break;
  777. default:
  778. if (tx_first[endpoint] == NULL) {
  779. tx_first[endpoint] = packet;
  780. } else {
  781. tx_last[endpoint]->next = packet;
  782. }
  783. tx_last[endpoint] = packet;
  784. __enable_irq();
  785. return;
  786. }
  787. tx_state[endpoint] = next;
  788. b->addr = packet->buf;
  789. b->desc = BDT_DESC(packet->len, ((uint32_t)b & 8) ? DATA1 : DATA0);
  790. __enable_irq();
  791. }
  792. void usb_tx_isochronous(uint32_t endpoint, void *data, uint32_t len)
  793. {
  794. bdt_t *b = &table[index(endpoint, TX, EVEN)];
  795. uint8_t next, state;
  796. endpoint--;
  797. if (endpoint >= NUM_ENDPOINTS) return;
  798. __disable_irq();
  799. state = tx_state[endpoint];
  800. if (state == 0) {
  801. next = 1;
  802. } else {
  803. b++;
  804. next = 0;
  805. }
  806. tx_state[endpoint] = next;
  807. b->addr = data;
  808. b->desc = (len << 16) | BDT_OWN;
  809. __enable_irq();
  810. }
  811. void _reboot_Teensyduino_(void)
  812. {
  813. // TODO: initialize R0 with a code....
  814. __asm__ volatile("bkpt");
  815. __builtin_unreachable();
  816. }
  817. void usb_isr(void)
  818. {
  819. uint8_t status, stat, t;
  820. //serial_print("isr");
  821. //status = USB0_ISTAT;
  822. //serial_phex(status);
  823. //serial_print("\n");
  824. restart:
  825. status = USB0_ISTAT;
  826. if ((status & USB_ISTAT_SOFTOK /* 04 */ )) {
  827. if (usb_configuration) {
  828. t = usb_reboot_timer;
  829. if (t) {
  830. usb_reboot_timer = --t;
  831. if (!t) _reboot_Teensyduino_();
  832. }
  833. #ifdef CDC_DATA_INTERFACE
  834. t = usb_cdc_transmit_flush_timer;
  835. if (t) {
  836. usb_cdc_transmit_flush_timer = --t;
  837. if (t == 0) usb_serial_flush_callback();
  838. }
  839. #endif
  840. #ifdef CDC2_DATA_INTERFACE
  841. t = usb_cdc2_transmit_flush_timer;
  842. if (t) {
  843. usb_cdc2_transmit_flush_timer = --t;
  844. if (t == 0) usb_serial2_flush_callback();
  845. }
  846. #endif
  847. #ifdef SEREMU_INTERFACE
  848. t = usb_seremu_transmit_flush_timer;
  849. if (t) {
  850. usb_seremu_transmit_flush_timer = --t;
  851. if (t == 0) usb_seremu_flush_callback();
  852. }
  853. #endif
  854. #ifdef MIDI_INTERFACE
  855. usb_midi_flush_output();
  856. #endif
  857. #ifdef FLIGHTSIM_INTERFACE
  858. usb_flightsim_flush_callback();
  859. #endif
  860. #ifdef MULTITOUCH_INTERFACE
  861. usb_touchscreen_update_callback();
  862. #endif
  863. }
  864. USB0_ISTAT = USB_ISTAT_SOFTOK;
  865. }
  866. if ((status & USB_ISTAT_TOKDNE /* 08 */ )) {
  867. uint8_t endpoint;
  868. stat = USB0_STAT;
  869. //serial_print("token: ep=");
  870. //serial_phex(stat >> 4);
  871. //serial_print(stat & 0x08 ? ",tx" : ",rx");
  872. //serial_print(stat & 0x04 ? ",odd\n" : ",even\n");
  873. endpoint = stat >> 4;
  874. if (endpoint == 0) {
  875. usb_control(stat);
  876. } else {
  877. bdt_t *b = stat2bufferdescriptor(stat);
  878. usb_packet_t *packet = (usb_packet_t *)((uint8_t *)(b->addr) - 8);
  879. #if 0
  880. serial_print("ep:");
  881. serial_phex(endpoint);
  882. serial_print(", pid:");
  883. serial_phex(BDT_PID(b->desc));
  884. serial_print(((uint32_t)b & 8) ? ", odd" : ", even");
  885. serial_print(", count:");
  886. serial_phex(b->desc >> 16);
  887. serial_print("\n");
  888. #endif
  889. endpoint--; // endpoint is index to zero-based arrays
  890. #ifdef AUDIO_INTERFACE
  891. if ((endpoint == AUDIO_TX_ENDPOINT-1) && (stat & 0x08)) {
  892. unsigned int len;
  893. len = usb_audio_transmit_callback();
  894. if (len > 0) {
  895. b = (bdt_t *)((uint32_t)b ^ 8);
  896. b->addr = usb_audio_transmit_buffer;
  897. b->desc = (len << 16) | BDT_OWN;
  898. tx_state[endpoint] ^= 1;
  899. }
  900. } else if ((endpoint == AUDIO_RX_ENDPOINT-1) && !(stat & 0x08)) {
  901. usb_audio_receive_callback(b->desc >> 16);
  902. b->addr = usb_audio_receive_buffer;
  903. b->desc = (AUDIO_RX_SIZE << 16) | BDT_OWN;
  904. } else if ((endpoint == AUDIO_SYNC_ENDPOINT-1) && (stat & 0x08)) {
  905. b = (bdt_t *)((uint32_t)b ^ 8);
  906. b->addr = &usb_audio_sync_feedback;
  907. b->desc = (3 << 16) | BDT_OWN;
  908. tx_state[endpoint] ^= 1;
  909. } else
  910. #endif
  911. if (stat & 0x08) { // transmit
  912. usb_free(packet);
  913. packet = tx_first[endpoint];
  914. if (packet) {
  915. //serial_print("tx packet\n");
  916. tx_first[endpoint] = packet->next;
  917. b->addr = packet->buf;
  918. switch (tx_state[endpoint]) {
  919. case TX_STATE_BOTH_FREE_EVEN_FIRST:
  920. tx_state[endpoint] = TX_STATE_ODD_FREE;
  921. break;
  922. case TX_STATE_BOTH_FREE_ODD_FIRST:
  923. tx_state[endpoint] = TX_STATE_EVEN_FREE;
  924. break;
  925. case TX_STATE_EVEN_FREE:
  926. tx_state[endpoint] = TX_STATE_NONE_FREE_ODD_FIRST;
  927. break;
  928. case TX_STATE_ODD_FREE:
  929. tx_state[endpoint] = TX_STATE_NONE_FREE_EVEN_FIRST;
  930. break;
  931. default:
  932. break;
  933. }
  934. b->desc = BDT_DESC(packet->len,
  935. ((uint32_t)b & 8) ? DATA1 : DATA0);
  936. } else {
  937. //serial_print("tx no packet\n");
  938. switch (tx_state[endpoint]) {
  939. case TX_STATE_BOTH_FREE_EVEN_FIRST:
  940. case TX_STATE_BOTH_FREE_ODD_FIRST:
  941. break;
  942. case TX_STATE_EVEN_FREE:
  943. tx_state[endpoint] = TX_STATE_BOTH_FREE_EVEN_FIRST;
  944. break;
  945. case TX_STATE_ODD_FREE:
  946. tx_state[endpoint] = TX_STATE_BOTH_FREE_ODD_FIRST;
  947. break;
  948. default:
  949. tx_state[endpoint] = ((uint32_t)b & 8) ?
  950. TX_STATE_ODD_FREE : TX_STATE_EVEN_FREE;
  951. break;
  952. }
  953. }
  954. } else { // receive
  955. packet->len = b->desc >> 16;
  956. if (packet->len > 0) {
  957. packet->index = 0;
  958. packet->next = NULL;
  959. if (rx_first[endpoint] == NULL) {
  960. //serial_print("rx 1st, epidx=");
  961. //serial_phex(endpoint);
  962. //serial_print(", packet=");
  963. //serial_phex32((uint32_t)packet);
  964. //serial_print("\n");
  965. rx_first[endpoint] = packet;
  966. } else {
  967. //serial_print("rx Nth, epidx=");
  968. //serial_phex(endpoint);
  969. //serial_print(", packet=");
  970. //serial_phex32((uint32_t)packet);
  971. //serial_print("\n");
  972. rx_last[endpoint]->next = packet;
  973. }
  974. rx_last[endpoint] = packet;
  975. usb_rx_byte_count_data[endpoint] += packet->len;
  976. // TODO: implement a per-endpoint maximum # of allocated
  977. // packets, so a flood of incoming data on 1 endpoint
  978. // doesn't starve the others if the user isn't reading
  979. // it regularly
  980. packet = usb_malloc();
  981. if (packet) {
  982. b->addr = packet->buf;
  983. b->desc = BDT_DESC(64,
  984. ((uint32_t)b & 8) ? DATA1 : DATA0);
  985. } else {
  986. //serial_print("starving ");
  987. //serial_phex(endpoint + 1);
  988. b->desc = 0;
  989. usb_rx_memory_needed++;
  990. }
  991. } else {
  992. b->desc = BDT_DESC(64, ((uint32_t)b & 8) ? DATA1 : DATA0);
  993. }
  994. }
  995. }
  996. USB0_ISTAT = USB_ISTAT_TOKDNE;
  997. goto restart;
  998. }
  999. if (status & USB_ISTAT_USBRST /* 01 */ ) {
  1000. //serial_print("reset\n");
  1001. // initialize BDT toggle bits
  1002. USB0_CTL = USB_CTL_ODDRST;
  1003. ep0_tx_bdt_bank = 0;
  1004. // set up buffers to receive Setup and OUT packets
  1005. table[index(0, RX, EVEN)].desc = BDT_DESC(EP0_SIZE, 0);
  1006. table[index(0, RX, EVEN)].addr = ep0_rx0_buf;
  1007. table[index(0, RX, ODD)].desc = BDT_DESC(EP0_SIZE, 0);
  1008. table[index(0, RX, ODD)].addr = ep0_rx1_buf;
  1009. table[index(0, TX, EVEN)].desc = 0;
  1010. table[index(0, TX, ODD)].desc = 0;
  1011. // activate endpoint 0
  1012. USB0_ENDPT0 = USB_ENDPT_EPRXEN | USB_ENDPT_EPTXEN | USB_ENDPT_EPHSHK;
  1013. // clear all ending interrupts
  1014. USB0_ERRSTAT = 0xFF;
  1015. USB0_ISTAT = 0xFF;
  1016. // set the address to zero during enumeration
  1017. USB0_ADDR = 0;
  1018. // enable other interrupts
  1019. USB0_ERREN = 0xFF;
  1020. USB0_INTEN = USB_INTEN_TOKDNEEN |
  1021. USB_INTEN_SOFTOKEN |
  1022. USB_INTEN_STALLEN |
  1023. USB_INTEN_ERROREN |
  1024. USB_INTEN_USBRSTEN |
  1025. USB_INTEN_SLEEPEN;
  1026. // is this necessary?
  1027. USB0_CTL = USB_CTL_USBENSOFEN;
  1028. return;
  1029. }
  1030. if ((status & USB_ISTAT_STALL /* 80 */ )) {
  1031. //serial_print("stall:\n");
  1032. USB0_ENDPT0 = USB_ENDPT_EPRXEN | USB_ENDPT_EPTXEN | USB_ENDPT_EPHSHK;
  1033. USB0_ISTAT = USB_ISTAT_STALL;
  1034. }
  1035. if ((status & USB_ISTAT_ERROR /* 02 */ )) {
  1036. uint8_t err = USB0_ERRSTAT;
  1037. USB0_ERRSTAT = err;
  1038. //serial_print("err:");
  1039. //serial_phex(err);
  1040. //serial_print("\n");
  1041. USB0_ISTAT = USB_ISTAT_ERROR;
  1042. }
  1043. if ((status & USB_ISTAT_SLEEP /* 10 */ )) {
  1044. //serial_print("sleep\n");
  1045. USB0_ISTAT = USB_ISTAT_SLEEP;
  1046. }
  1047. }
  1048. void usb_init(void)
  1049. {
  1050. int i;
  1051. //serial_begin(BAUD2DIV(115200));
  1052. //serial_print("usb_init\n");
  1053. usb_init_serialnumber();
  1054. for (i=0; i <= NUM_ENDPOINTS*4; i++) {
  1055. table[i].desc = 0;
  1056. table[i].addr = 0;
  1057. }
  1058. // this basically follows the flowchart in the Kinetis
  1059. // Quick Reference User Guide, Rev. 1, 03/2012, page 141
  1060. // assume 48 MHz clock already running
  1061. // SIM - enable clock
  1062. SIM_SCGC4 |= SIM_SCGC4_USBOTG;
  1063. #ifdef HAS_KINETIS_MPU
  1064. MPU_RGDAAC0 |= 0x03000000;
  1065. #endif
  1066. #if F_CPU == 180000000 || F_CPU == 216000000 || F_CPU == 256000000
  1067. // if using IRC48M, turn on the USB clock recovery hardware
  1068. USB0_CLK_RECOVER_IRC_EN = USB_CLK_RECOVER_IRC_EN_IRC_EN | USB_CLK_RECOVER_IRC_EN_REG_EN;
  1069. USB0_CLK_RECOVER_CTRL = USB_CLK_RECOVER_CTRL_CLOCK_RECOVER_EN |
  1070. USB_CLK_RECOVER_CTRL_RESTART_IFRTRIM_EN;
  1071. #endif
  1072. // reset USB module
  1073. //USB0_USBTRC0 = USB_USBTRC_USBRESET;
  1074. //while ((USB0_USBTRC0 & USB_USBTRC_USBRESET) != 0) ; // wait for reset to end
  1075. // set desc table base addr
  1076. USB0_BDTPAGE1 = ((uint32_t)table) >> 8;
  1077. USB0_BDTPAGE2 = ((uint32_t)table) >> 16;
  1078. USB0_BDTPAGE3 = ((uint32_t)table) >> 24;
  1079. // clear all ISR flags
  1080. USB0_ISTAT = 0xFF;
  1081. USB0_ERRSTAT = 0xFF;
  1082. USB0_OTGISTAT = 0xFF;
  1083. //USB0_USBTRC0 |= 0x40; // undocumented bit
  1084. // enable USB
  1085. USB0_CTL = USB_CTL_USBENSOFEN;
  1086. USB0_USBCTRL = 0;
  1087. // enable reset interrupt
  1088. USB0_INTEN = USB_INTEN_USBRSTEN;
  1089. // enable interrupt in NVIC...
  1090. NVIC_SET_PRIORITY(IRQ_USBOTG, 112);
  1091. NVIC_ENABLE_IRQ(IRQ_USBOTG);
  1092. // enable d+ pullup
  1093. USB0_CONTROL = USB_CONTROL_DPPULLUPNONOTG;
  1094. }
  1095. #else // F_CPU < 20 MHz && defined(NUM_ENDPOINTS)
  1096. void usb_init(void)
  1097. {
  1098. }
  1099. #endif // F_CPU >= 20 MHz && defined(NUM_ENDPOINTS)