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.

1063 lines
27KB

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