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.

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