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.

usb_dev.c 26KB

9 vuotta sitten
12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007
  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 = setup.wValue;
  311. //serial_print("set control line state\n");
  312. break;
  313. case 0x2321: // CDC_SEND_BREAK
  314. break;
  315. case 0x2021: // CDC_SET_LINE_CODING
  316. //serial_print("set coding, waiting...\n");
  317. return;
  318. #endif
  319. #if defined(MTP_INTERFACE)
  320. case 0x2164: // Cancel Request (PTP spec, 5.2.1, page 8)
  321. // TODO: required by PTP spec
  322. endpoint0_stall();
  323. return;
  324. case 0x2166: // Device Reset (PTP spec, 5.2.3, page 10)
  325. // TODO: required by PTP spec
  326. endpoint0_stall();
  327. return;
  328. case 0x2167: // Get Device Statis (PTP spec, 5.2.4, page 10)
  329. // TODO: required by PTP spec
  330. endpoint0_stall();
  331. return;
  332. #endif
  333. // TODO: this does not work... why?
  334. #if defined(SEREMU_INTERFACE) || defined(KEYBOARD_INTERFACE)
  335. case 0x0921: // HID SET_REPORT
  336. //serial_print(":)\n");
  337. return;
  338. case 0x0A21: // HID SET_IDLE
  339. break;
  340. // case 0xC940:
  341. #endif
  342. default:
  343. endpoint0_stall();
  344. return;
  345. }
  346. send:
  347. //serial_print("setup send ");
  348. //serial_phex32(data);
  349. //serial_print(",");
  350. //serial_phex16(datalen);
  351. //serial_print("\n");
  352. if (datalen > setup.wLength) datalen = setup.wLength;
  353. size = datalen;
  354. if (size > EP0_SIZE) size = EP0_SIZE;
  355. endpoint0_transmit(data, size);
  356. data += size;
  357. datalen -= size;
  358. if (datalen == 0 && size < EP0_SIZE) return;
  359. size = datalen;
  360. if (size > EP0_SIZE) size = EP0_SIZE;
  361. endpoint0_transmit(data, size);
  362. data += size;
  363. datalen -= size;
  364. if (datalen == 0 && size < EP0_SIZE) return;
  365. ep0_tx_ptr = data;
  366. ep0_tx_len = datalen;
  367. }
  368. //A bulk endpoint's toggle sequence is initialized to DATA0 when the endpoint
  369. //experiences any configuration event (configuration events are explained in
  370. //Sections 9.1.1.5 and 9.4.5).
  371. //Configuring a device or changing an alternate setting causes all of the status
  372. //and configuration values associated with endpoints in the affected interfaces
  373. //to be set to their default values. This includes setting the data toggle of
  374. //any endpoint using data toggles to the value DATA0.
  375. //For endpoints using data toggle, regardless of whether an endpoint has the
  376. //Halt feature set, a ClearFeature(ENDPOINT_HALT) request always results in the
  377. //data toggle being reinitialized to DATA0.
  378. // #define stat2bufferdescriptor(stat) (table + ((stat) >> 2))
  379. static void usb_control(uint32_t stat)
  380. {
  381. bdt_t *b;
  382. uint32_t pid, size;
  383. uint8_t *buf;
  384. const uint8_t *data;
  385. b = stat2bufferdescriptor(stat);
  386. pid = BDT_PID(b->desc);
  387. //count = b->desc >> 16;
  388. buf = b->addr;
  389. //serial_print("pid:");
  390. //serial_phex(pid);
  391. //serial_print(", count:");
  392. //serial_phex(count);
  393. //serial_print("\n");
  394. switch (pid) {
  395. case 0x0D: // Setup received from host
  396. //serial_print("PID=Setup\n");
  397. //if (count != 8) ; // panic?
  398. // grab the 8 byte setup info
  399. setup.word1 = *(uint32_t *)(buf);
  400. setup.word2 = *(uint32_t *)(buf + 4);
  401. // give the buffer back
  402. b->desc = BDT_DESC(EP0_SIZE, DATA1);
  403. //table[index(0, RX, EVEN)].desc = BDT_DESC(EP0_SIZE, 1);
  404. //table[index(0, RX, ODD)].desc = BDT_DESC(EP0_SIZE, 1);
  405. // clear any leftover pending IN transactions
  406. ep0_tx_ptr = NULL;
  407. if (ep0_tx_data_toggle) {
  408. }
  409. //if (table[index(0, TX, EVEN)].desc & 0x80) {
  410. //serial_print("leftover tx even\n");
  411. //}
  412. //if (table[index(0, TX, ODD)].desc & 0x80) {
  413. //serial_print("leftover tx odd\n");
  414. //}
  415. table[index(0, TX, EVEN)].desc = 0;
  416. table[index(0, TX, ODD)].desc = 0;
  417. // first IN after Setup is always DATA1
  418. ep0_tx_data_toggle = 1;
  419. #if 0
  420. serial_print("bmRequestType:");
  421. serial_phex(setup.bmRequestType);
  422. serial_print(", bRequest:");
  423. serial_phex(setup.bRequest);
  424. serial_print(", wValue:");
  425. serial_phex16(setup.wValue);
  426. serial_print(", wIndex:");
  427. serial_phex16(setup.wIndex);
  428. serial_print(", len:");
  429. serial_phex16(setup.wLength);
  430. serial_print("\n");
  431. #endif
  432. // actually "do" the setup request
  433. usb_setup();
  434. // unfreeze the USB, now that we're ready
  435. USB0_CTL = USB_CTL_USBENSOFEN; // clear TXSUSPENDTOKENBUSY bit
  436. break;
  437. case 0x01: // OUT transaction received from host
  438. case 0x02:
  439. //serial_print("PID=OUT\n");
  440. #ifdef CDC_STATUS_INTERFACE
  441. if (setup.wRequestAndType == 0x2021 /*CDC_SET_LINE_CODING*/) {
  442. int i;
  443. uint8_t *dst = (uint8_t *)usb_cdc_line_coding;
  444. //serial_print("set line coding ");
  445. for (i=0; i<7; i++) {
  446. //serial_phex(*buf);
  447. *dst++ = *buf++;
  448. }
  449. //serial_phex32(usb_cdc_line_coding[0]);
  450. //serial_print("\n");
  451. if (usb_cdc_line_coding[0] == 134) usb_reboot_timer = 15;
  452. endpoint0_transmit(NULL, 0);
  453. }
  454. #endif
  455. #ifdef KEYBOARD_INTERFACE
  456. if (setup.word1 == 0x02000921 && setup.word2 == ((1<<16)|KEYBOARD_INTERFACE)) {
  457. keyboard_leds = buf[0];
  458. endpoint0_transmit(NULL, 0);
  459. }
  460. #endif
  461. #ifdef SEREMU_INTERFACE
  462. if (setup.word1 == 0x03000921 && setup.word2 == ((4<<16)|SEREMU_INTERFACE)
  463. && buf[0] == 0xA9 && buf[1] == 0x45 && buf[2] == 0xC2 && buf[3] == 0x6B) {
  464. usb_reboot_timer = 5;
  465. endpoint0_transmit(NULL, 0);
  466. }
  467. #endif
  468. // give the buffer back
  469. b->desc = BDT_DESC(EP0_SIZE, DATA1);
  470. break;
  471. case 0x09: // IN transaction completed to host
  472. //serial_print("PID=IN:");
  473. //serial_phex(stat);
  474. //serial_print("\n");
  475. // send remaining data, if any...
  476. data = ep0_tx_ptr;
  477. if (data) {
  478. size = ep0_tx_len;
  479. if (size > EP0_SIZE) size = EP0_SIZE;
  480. endpoint0_transmit(data, size);
  481. data += size;
  482. ep0_tx_len -= size;
  483. ep0_tx_ptr = (ep0_tx_len > 0 || size == EP0_SIZE) ? data : NULL;
  484. }
  485. if (setup.bRequest == 5 && setup.bmRequestType == 0) {
  486. setup.bRequest = 0;
  487. //serial_print("set address: ");
  488. //serial_phex16(setup.wValue);
  489. //serial_print("\n");
  490. USB0_ADDR = setup.wValue;
  491. }
  492. break;
  493. //default:
  494. //serial_print("PID=unknown:");
  495. //serial_phex(pid);
  496. //serial_print("\n");
  497. }
  498. USB0_CTL = USB_CTL_USBENSOFEN; // clear TXSUSPENDTOKENBUSY bit
  499. }
  500. usb_packet_t *usb_rx(uint32_t endpoint)
  501. {
  502. usb_packet_t *ret;
  503. endpoint--;
  504. if (endpoint >= NUM_ENDPOINTS) return NULL;
  505. __disable_irq();
  506. ret = rx_first[endpoint];
  507. if (ret) {
  508. rx_first[endpoint] = ret->next;
  509. usb_rx_byte_count_data[endpoint] -= ret->len;
  510. }
  511. __enable_irq();
  512. //serial_print("rx, epidx=");
  513. //serial_phex(endpoint);
  514. //serial_print(", packet=");
  515. //serial_phex32(ret);
  516. //serial_print("\n");
  517. return ret;
  518. }
  519. static uint32_t usb_queue_byte_count(const usb_packet_t *p)
  520. {
  521. uint32_t count=0;
  522. __disable_irq();
  523. for ( ; p; p = p->next) {
  524. count += p->len;
  525. }
  526. __enable_irq();
  527. return count;
  528. }
  529. // TODO: make this an inline function...
  530. /*
  531. uint32_t usb_rx_byte_count(uint32_t endpoint)
  532. {
  533. endpoint--;
  534. if (endpoint >= NUM_ENDPOINTS) return 0;
  535. return usb_rx_byte_count_data[endpoint];
  536. //return usb_queue_byte_count(rx_first[endpoint]);
  537. }
  538. */
  539. uint32_t usb_tx_byte_count(uint32_t endpoint)
  540. {
  541. endpoint--;
  542. if (endpoint >= NUM_ENDPOINTS) return 0;
  543. return usb_queue_byte_count(tx_first[endpoint]);
  544. }
  545. uint32_t usb_tx_packet_count(uint32_t endpoint)
  546. {
  547. const usb_packet_t *p;
  548. uint32_t count=0;
  549. endpoint--;
  550. if (endpoint >= NUM_ENDPOINTS) return 0;
  551. __disable_irq();
  552. for (p = tx_first[endpoint]; p; p = p->next) count++;
  553. __enable_irq();
  554. return count;
  555. }
  556. // Called from usb_free, but only when usb_rx_memory_needed > 0, indicating
  557. // receive endpoints are starving for memory. The intention is to give
  558. // endpoints needing receive memory priority over the user's code, which is
  559. // likely calling usb_malloc to obtain memory for transmitting. When the
  560. // user is creating data very quickly, their consumption could starve reception
  561. // without this prioritization. The packet buffer (input) is assigned to the
  562. // first endpoint needing memory.
  563. //
  564. void usb_rx_memory(usb_packet_t *packet)
  565. {
  566. unsigned int i;
  567. const uint8_t *cfg;
  568. cfg = usb_endpoint_config_table;
  569. //serial_print("rx_mem:");
  570. __disable_irq();
  571. for (i=1; i <= NUM_ENDPOINTS; i++) {
  572. if (*cfg++ & USB_ENDPT_EPRXEN) {
  573. if (table[index(i, RX, EVEN)].desc == 0) {
  574. table[index(i, RX, EVEN)].addr = packet->buf;
  575. table[index(i, RX, EVEN)].desc = BDT_DESC(64, 0);
  576. usb_rx_memory_needed--;
  577. __enable_irq();
  578. //serial_phex(i);
  579. //serial_print(",even\n");
  580. return;
  581. }
  582. if (table[index(i, RX, ODD)].desc == 0) {
  583. table[index(i, RX, ODD)].addr = packet->buf;
  584. table[index(i, RX, ODD)].desc = BDT_DESC(64, 1);
  585. usb_rx_memory_needed--;
  586. __enable_irq();
  587. //serial_phex(i);
  588. //serial_print(",odd\n");
  589. return;
  590. }
  591. }
  592. }
  593. __enable_irq();
  594. // we should never reach this point. If we get here, it means
  595. // usb_rx_memory_needed was set greater than zero, but no memory
  596. // was actually needed.
  597. usb_rx_memory_needed = 0;
  598. usb_free(packet);
  599. return;
  600. }
  601. //#define index(endpoint, tx, odd) (((endpoint) << 2) | ((tx) << 1) | (odd))
  602. //#define stat2bufferdescriptor(stat) (table + ((stat) >> 2))
  603. void usb_tx(uint32_t endpoint, usb_packet_t *packet)
  604. {
  605. bdt_t *b = &table[index(endpoint, TX, EVEN)];
  606. uint8_t next;
  607. endpoint--;
  608. if (endpoint >= NUM_ENDPOINTS) return;
  609. __disable_irq();
  610. //serial_print("txstate=");
  611. //serial_phex(tx_state[endpoint]);
  612. //serial_print("\n");
  613. switch (tx_state[endpoint]) {
  614. case TX_STATE_BOTH_FREE_EVEN_FIRST:
  615. next = TX_STATE_ODD_FREE;
  616. break;
  617. case TX_STATE_BOTH_FREE_ODD_FIRST:
  618. b++;
  619. next = TX_STATE_EVEN_FREE;
  620. break;
  621. case TX_STATE_EVEN_FREE:
  622. next = TX_STATE_NONE_FREE_ODD_FIRST;
  623. break;
  624. case TX_STATE_ODD_FREE:
  625. b++;
  626. next = TX_STATE_NONE_FREE_EVEN_FIRST;
  627. break;
  628. default:
  629. if (tx_first[endpoint] == NULL) {
  630. tx_first[endpoint] = packet;
  631. } else {
  632. tx_last[endpoint]->next = packet;
  633. }
  634. tx_last[endpoint] = packet;
  635. __enable_irq();
  636. return;
  637. }
  638. tx_state[endpoint] = next;
  639. b->addr = packet->buf;
  640. b->desc = BDT_DESC(packet->len, ((uint32_t)b & 8) ? DATA1 : DATA0);
  641. __enable_irq();
  642. }
  643. void _reboot_Teensyduino_(void)
  644. {
  645. // TODO: initialize R0 with a code....
  646. __asm__ volatile("bkpt");
  647. }
  648. void usb_isr(void)
  649. {
  650. uint8_t status, stat, t;
  651. //serial_print("isr");
  652. //status = USB0_ISTAT;
  653. //serial_phex(status);
  654. //serial_print("\n");
  655. restart:
  656. status = USB0_ISTAT;
  657. if ((status & USB_ISTAT_SOFTOK /* 04 */ )) {
  658. if (usb_configuration) {
  659. t = usb_reboot_timer;
  660. if (t) {
  661. usb_reboot_timer = --t;
  662. if (!t) _reboot_Teensyduino_();
  663. }
  664. #ifdef CDC_DATA_INTERFACE
  665. t = usb_cdc_transmit_flush_timer;
  666. if (t) {
  667. usb_cdc_transmit_flush_timer = --t;
  668. if (t == 0) usb_serial_flush_callback();
  669. }
  670. #endif
  671. #ifdef SEREMU_INTERFACE
  672. t = usb_seremu_transmit_flush_timer;
  673. if (t) {
  674. usb_seremu_transmit_flush_timer = --t;
  675. if (t == 0) usb_seremu_flush_callback();
  676. }
  677. #endif
  678. #ifdef MIDI_INTERFACE
  679. usb_midi_flush_output();
  680. #endif
  681. #ifdef FLIGHTSIM_INTERFACE
  682. usb_flightsim_flush_callback();
  683. #endif
  684. }
  685. USB0_ISTAT = USB_ISTAT_SOFTOK;
  686. }
  687. if ((status & USB_ISTAT_TOKDNE /* 08 */ )) {
  688. uint8_t endpoint;
  689. stat = USB0_STAT;
  690. //serial_print("token: ep=");
  691. //serial_phex(stat >> 4);
  692. //serial_print(stat & 0x08 ? ",tx" : ",rx");
  693. //serial_print(stat & 0x04 ? ",odd\n" : ",even\n");
  694. endpoint = stat >> 4;
  695. if (endpoint == 0) {
  696. usb_control(stat);
  697. } else {
  698. bdt_t *b = stat2bufferdescriptor(stat);
  699. usb_packet_t *packet = (usb_packet_t *)((uint8_t *)(b->addr) - 8);
  700. #if 0
  701. serial_print("ep:");
  702. serial_phex(endpoint);
  703. serial_print(", pid:");
  704. serial_phex(BDT_PID(b->desc));
  705. serial_print(((uint32_t)b & 8) ? ", odd" : ", even");
  706. serial_print(", count:");
  707. serial_phex(b->desc >> 16);
  708. serial_print("\n");
  709. #endif
  710. endpoint--; // endpoint is index to zero-based arrays
  711. if (stat & 0x08) { // transmit
  712. usb_free(packet);
  713. packet = tx_first[endpoint];
  714. if (packet) {
  715. //serial_print("tx packet\n");
  716. tx_first[endpoint] = packet->next;
  717. b->addr = packet->buf;
  718. switch (tx_state[endpoint]) {
  719. case TX_STATE_BOTH_FREE_EVEN_FIRST:
  720. tx_state[endpoint] = TX_STATE_ODD_FREE;
  721. break;
  722. case TX_STATE_BOTH_FREE_ODD_FIRST:
  723. tx_state[endpoint] = TX_STATE_EVEN_FREE;
  724. break;
  725. case TX_STATE_EVEN_FREE:
  726. tx_state[endpoint] = TX_STATE_NONE_FREE_ODD_FIRST;
  727. break;
  728. case TX_STATE_ODD_FREE:
  729. tx_state[endpoint] = TX_STATE_NONE_FREE_EVEN_FIRST;
  730. break;
  731. default:
  732. break;
  733. }
  734. b->desc = BDT_DESC(packet->len, ((uint32_t)b & 8) ? DATA1 : DATA0);
  735. } else {
  736. //serial_print("tx no packet\n");
  737. switch (tx_state[endpoint]) {
  738. case TX_STATE_BOTH_FREE_EVEN_FIRST:
  739. case TX_STATE_BOTH_FREE_ODD_FIRST:
  740. break;
  741. case TX_STATE_EVEN_FREE:
  742. tx_state[endpoint] = TX_STATE_BOTH_FREE_EVEN_FIRST;
  743. break;
  744. case TX_STATE_ODD_FREE:
  745. tx_state[endpoint] = TX_STATE_BOTH_FREE_ODD_FIRST;
  746. break;
  747. default:
  748. tx_state[endpoint] = ((uint32_t)b & 8) ?
  749. TX_STATE_ODD_FREE : TX_STATE_EVEN_FREE;
  750. break;
  751. }
  752. }
  753. } else { // receive
  754. packet->len = b->desc >> 16;
  755. if (packet->len > 0) {
  756. packet->index = 0;
  757. packet->next = NULL;
  758. if (rx_first[endpoint] == NULL) {
  759. //serial_print("rx 1st, epidx=");
  760. //serial_phex(endpoint);
  761. //serial_print(", packet=");
  762. //serial_phex32((uint32_t)packet);
  763. //serial_print("\n");
  764. rx_first[endpoint] = packet;
  765. } else {
  766. //serial_print("rx Nth, epidx=");
  767. //serial_phex(endpoint);
  768. //serial_print(", packet=");
  769. //serial_phex32((uint32_t)packet);
  770. //serial_print("\n");
  771. rx_last[endpoint]->next = packet;
  772. }
  773. rx_last[endpoint] = packet;
  774. usb_rx_byte_count_data[endpoint] += packet->len;
  775. // TODO: implement a per-endpoint maximum # of allocated packets
  776. // so a flood of incoming data on 1 endpoint doesn't starve
  777. // the others if the user isn't reading it regularly
  778. packet = usb_malloc();
  779. if (packet) {
  780. b->addr = packet->buf;
  781. b->desc = BDT_DESC(64, ((uint32_t)b & 8) ? DATA1 : DATA0);
  782. } else {
  783. //serial_print("starving ");
  784. //serial_phex(endpoint + 1);
  785. //serial_print(((uint32_t)b & 8) ? ",odd\n" : ",even\n");
  786. b->desc = 0;
  787. usb_rx_memory_needed++;
  788. }
  789. } else {
  790. b->desc = BDT_DESC(64, ((uint32_t)b & 8) ? DATA1 : DATA0);
  791. }
  792. }
  793. }
  794. USB0_ISTAT = USB_ISTAT_TOKDNE;
  795. goto restart;
  796. }
  797. if (status & USB_ISTAT_USBRST /* 01 */ ) {
  798. //serial_print("reset\n");
  799. // initialize BDT toggle bits
  800. USB0_CTL = USB_CTL_ODDRST;
  801. ep0_tx_bdt_bank = 0;
  802. // set up buffers to receive Setup and OUT packets
  803. table[index(0, RX, EVEN)].desc = BDT_DESC(EP0_SIZE, 0);
  804. table[index(0, RX, EVEN)].addr = ep0_rx0_buf;
  805. table[index(0, RX, ODD)].desc = BDT_DESC(EP0_SIZE, 0);
  806. table[index(0, RX, ODD)].addr = ep0_rx1_buf;
  807. table[index(0, TX, EVEN)].desc = 0;
  808. table[index(0, TX, ODD)].desc = 0;
  809. // activate endpoint 0
  810. USB0_ENDPT0 = USB_ENDPT_EPRXEN | USB_ENDPT_EPTXEN | USB_ENDPT_EPHSHK;
  811. // clear all ending interrupts
  812. USB0_ERRSTAT = 0xFF;
  813. USB0_ISTAT = 0xFF;
  814. // set the address to zero during enumeration
  815. USB0_ADDR = 0;
  816. // enable other interrupts
  817. USB0_ERREN = 0xFF;
  818. USB0_INTEN = USB_INTEN_TOKDNEEN |
  819. USB_INTEN_SOFTOKEN |
  820. USB_INTEN_STALLEN |
  821. USB_INTEN_ERROREN |
  822. USB_INTEN_USBRSTEN |
  823. USB_INTEN_SLEEPEN;
  824. // is this necessary?
  825. USB0_CTL = USB_CTL_USBENSOFEN;
  826. return;
  827. }
  828. if ((status & USB_ISTAT_STALL /* 80 */ )) {
  829. //serial_print("stall:\n");
  830. USB0_ENDPT0 = USB_ENDPT_EPRXEN | USB_ENDPT_EPTXEN | USB_ENDPT_EPHSHK;
  831. USB0_ISTAT = USB_ISTAT_STALL;
  832. }
  833. if ((status & USB_ISTAT_ERROR /* 02 */ )) {
  834. uint8_t err = USB0_ERRSTAT;
  835. USB0_ERRSTAT = err;
  836. //serial_print("err:");
  837. //serial_phex(err);
  838. //serial_print("\n");
  839. USB0_ISTAT = USB_ISTAT_ERROR;
  840. }
  841. if ((status & USB_ISTAT_SLEEP /* 10 */ )) {
  842. //serial_print("sleep\n");
  843. USB0_ISTAT = USB_ISTAT_SLEEP;
  844. }
  845. }
  846. void usb_init(void)
  847. {
  848. int i;
  849. //serial_begin(BAUD2DIV(115200));
  850. //serial_print("usb_init\n");
  851. usb_init_serialnumber();
  852. for (i=0; i <= NUM_ENDPOINTS*4; i++) {
  853. table[i].desc = 0;
  854. table[i].addr = 0;
  855. }
  856. // this basically follows the flowchart in the Kinetis
  857. // Quick Reference User Guide, Rev. 1, 03/2012, page 141
  858. // assume 48 MHz clock already running
  859. // SIM - enable clock
  860. SIM_SCGC4 |= SIM_SCGC4_USBOTG;
  861. #ifdef HAS_KINETIS_MPU
  862. MPU_RGDAAC0 |= 0x03000000;
  863. #endif
  864. // reset USB module
  865. //USB0_USBTRC0 = USB_USBTRC_USBRESET;
  866. //while ((USB0_USBTRC0 & USB_USBTRC_USBRESET) != 0) ; // wait for reset to end
  867. // set desc table base addr
  868. USB0_BDTPAGE1 = ((uint32_t)table) >> 8;
  869. USB0_BDTPAGE2 = ((uint32_t)table) >> 16;
  870. USB0_BDTPAGE3 = ((uint32_t)table) >> 24;
  871. // clear all ISR flags
  872. USB0_ISTAT = 0xFF;
  873. USB0_ERRSTAT = 0xFF;
  874. USB0_OTGISTAT = 0xFF;
  875. //USB0_USBTRC0 |= 0x40; // undocumented bit
  876. // enable USB
  877. USB0_CTL = USB_CTL_USBENSOFEN;
  878. USB0_USBCTRL = 0;
  879. // enable reset interrupt
  880. USB0_INTEN = USB_INTEN_USBRSTEN;
  881. // enable interrupt in NVIC...
  882. NVIC_SET_PRIORITY(IRQ_USBOTG, 112);
  883. NVIC_ENABLE_IRQ(IRQ_USBOTG);
  884. // enable d+ pullup
  885. USB0_CONTROL = USB_CONTROL_DPPULLUPNONOTG;
  886. }
  887. #else // F_CPU < 20 MHz && defined(NUM_ENDPOINTS)
  888. void usb_init(void)
  889. {
  890. }
  891. #endif // F_CPU >= 20 MHz && defined(NUM_ENDPOINTS)