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.

1081 lines
34KB

  1. /* USB EHCI Host for Teensy 3.6
  2. * Copyright 2017 Paul Stoffregen (paul@pjrc.com)
  3. *
  4. * Permission is hereby granted, free of charge, to any person obtaining a
  5. * copy of this software and associated documentation files (the
  6. * "Software"), to deal in the Software without restriction, including
  7. * without limitation the rights to use, copy, modify, merge, publish,
  8. * distribute, sublicense, and/or sell copies of the Software, and to
  9. * permit persons to whom the Software is furnished to do so, subject to
  10. * the following conditions:
  11. *
  12. * The above copyright notice and this permission notice shall be included
  13. * in all copies or substantial portions of the Software.
  14. *
  15. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
  16. * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  17. * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
  18. * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
  19. * CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
  20. * TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
  21. * SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
  22. */
  23. #include <Arduino.h>
  24. #include "USBHost.h"
  25. // Size of the periodic list, in milliseconds. This determines the
  26. // slowest rate we can poll interrupt endpoints. Each entry uses
  27. // 12 bytes (4 for a pointer, 8 for bandwidth management).
  28. // may be 8, 16, 32, 64, 128, 256, 512, 1024
  29. #define PERIODIC_LIST_SIZE 32
  30. static uint32_t periodictable[PERIODIC_LIST_SIZE] __attribute__ ((aligned(4096), used));
  31. static uint8_t uframe_bandwidth[PERIODIC_LIST_SIZE*8];
  32. static uint8_t port_state;
  33. #define PORT_STATE_DISCONNECTED 0
  34. #define PORT_STATE_DEBOUNCE 1
  35. #define PORT_STATE_RESET 2
  36. #define PORT_STATE_RECOVERY 3
  37. #define PORT_STATE_ACTIVE 4
  38. static Device_t *rootdev=NULL;
  39. static Transfer_t *async_followup_first=NULL;
  40. static Transfer_t *async_followup_last=NULL;
  41. static Transfer_t *periodic_followup_first=NULL;
  42. static Transfer_t *periodic_followup_last=NULL;
  43. static USBDriverTimer *active_timers=NULL;
  44. static void init_qTD(volatile Transfer_t *t, void *buf, uint32_t len,
  45. uint32_t pid, uint32_t data01, bool irq);
  46. static bool followup_Transfer(Transfer_t *transfer);
  47. static void add_to_async_followup_list(Transfer_t *first, Transfer_t *last);
  48. static void remove_from_async_followup_list(Transfer_t *transfer);
  49. static void add_to_periodic_followup_list(Transfer_t *first, Transfer_t *last);
  50. static void remove_from_periodic_followup_list(Transfer_t *transfer);
  51. void USBHost::begin()
  52. {
  53. // Teensy 3.6 has USB host power controlled by PTE6
  54. PORTE_PCR6 = PORT_PCR_MUX(1);
  55. GPIOE_PDDR |= (1<<6);
  56. GPIOE_PSOR = (1<<6); // turn on USB host power
  57. delay(10);
  58. println("sizeof Device = ", sizeof(Device_t));
  59. println("sizeof Pipe = ", sizeof(Pipe_t));
  60. println("sizeof Transfer = ", sizeof(Transfer_t));
  61. if ((sizeof(Pipe_t) & 0x1F) || (sizeof(Transfer_t) & 0x1F)) {
  62. println("ERROR: Pipe_t & Transfer_t must be multiples of 32 bytes!");
  63. while (1) ; // die here
  64. }
  65. // configure the MPU to allow USBHS DMA to access memory
  66. MPU_RGDAAC0 |= 0x30000000;
  67. //println("MPU_RGDAAC0 = ", MPU_RGDAAC0, HEX);
  68. // turn on clocks
  69. MCG_C1 |= MCG_C1_IRCLKEN; // enable MCGIRCLK 32kHz
  70. OSC0_CR |= OSC_ERCLKEN;
  71. SIM_SOPT2 |= SIM_SOPT2_USBREGEN; // turn on USB regulator
  72. SIM_SOPT2 &= ~SIM_SOPT2_USBSLSRC; // use IRC for slow clock
  73. println("power up USBHS PHY");
  74. SIM_USBPHYCTL |= SIM_USBPHYCTL_USBDISILIM; // disable USB current limit
  75. //SIM_USBPHYCTL = SIM_USBPHYCTL_USBDISILIM | SIM_USBPHYCTL_USB3VOUTTRG(6); // pg 237
  76. SIM_SCGC3 |= SIM_SCGC3_USBHSDCD | SIM_SCGC3_USBHSPHY | SIM_SCGC3_USBHS;
  77. USBHSDCD_CLOCK = 33 << 2;
  78. //print("init USBHS PHY & PLL");
  79. // init process: page 1681-1682
  80. USBPHY_CTRL_CLR = (USBPHY_CTRL_SFTRST | USBPHY_CTRL_CLKGATE); // // CTRL pg 1698
  81. USBPHY_CTRL_SET = USBPHY_CTRL_ENUTMILEVEL2 | USBPHY_CTRL_ENUTMILEVEL3;
  82. //USBPHY_CTRL_SET = USBPHY_CTRL_FSDLL_RST_EN; // TODO: what does this do??
  83. USBPHY_TRIM_OVERRIDE_EN_SET = 1;
  84. USBPHY_PLL_SIC = USBPHY_PLL_SIC_PLL_POWER | USBPHY_PLL_SIC_PLL_ENABLE |
  85. USBPHY_PLL_SIC_PLL_DIV_SEL(1) | USBPHY_PLL_SIC_PLL_EN_USB_CLKS;
  86. // wait for the PLL to lock
  87. int count=0;
  88. while ((USBPHY_PLL_SIC & USBPHY_PLL_SIC_PLL_LOCK) == 0) {
  89. count++;
  90. }
  91. //println("PLL locked, waited ", count);
  92. // turn on power to PHY
  93. USBPHY_PWD = 0;
  94. delay(10);
  95. // sanity check, connect 470K pullup & 100K pulldown and watch D+ voltage change
  96. //USBPHY_ANACTRL_CLR = (1<<10); // turn off both 15K pulldowns... works! :)
  97. // sanity check, output clocks on pin 9 for testing
  98. //SIM_SOPT2 = SIM_SOPT2 & (~SIM_SOPT2_CLKOUTSEL(7)) | SIM_SOPT2_CLKOUTSEL(3); // LPO 1kHz
  99. //SIM_SOPT2 = SIM_SOPT2 & (~SIM_SOPT2_CLKOUTSEL(7)) | SIM_SOPT2_CLKOUTSEL(2); // Flash
  100. //SIM_SOPT2 = SIM_SOPT2 & (~SIM_SOPT2_CLKOUTSEL(7)) | SIM_SOPT2_CLKOUTSEL(6); // XTAL
  101. //SIM_SOPT2 = SIM_SOPT2 & (~SIM_SOPT2_CLKOUTSEL(7)) | SIM_SOPT2_CLKOUTSEL(7); // IRC 48MHz
  102. //SIM_SOPT2 = SIM_SOPT2 & (~SIM_SOPT2_CLKOUTSEL(7)) | SIM_SOPT2_CLKOUTSEL(4); // MCGIRCLK
  103. //CORE_PIN9_CONFIG = PORT_PCR_MUX(5); // CLKOUT on PTC3 Alt5 (Arduino pin 9)
  104. // now with the PHY up and running, start up USBHS
  105. //print("begin ehci reset");
  106. USBHS_USBCMD |= USBHS_USBCMD_RST;
  107. //count = 0;
  108. while (USBHS_USBCMD & USBHS_USBCMD_RST) {
  109. //count++;
  110. }
  111. //println(" reset waited ", count);
  112. init_Device_Pipe_Transfer_memory();
  113. for (int i=0; i < 32; i++) {
  114. periodictable[i] = 1;
  115. }
  116. memset(uframe_bandwidth, 0, sizeof(uframe_bandwidth));
  117. port_state = PORT_STATE_DISCONNECTED;
  118. USBHS_USB_SBUSCFG = 1; // System Bus Interface Configuration
  119. // turn on the USBHS controller
  120. //USBHS_USBMODE = USBHS_USBMODE_TXHSD(5) | USBHS_USBMODE_CM(3); // host mode
  121. USBHS_USBMODE = USBHS_USBMODE_CM(3); // host mode
  122. USBHS_USBINTR = 0;
  123. USBHS_PERIODICLISTBASE = (uint32_t)periodictable;
  124. USBHS_FRINDEX = 0;
  125. USBHS_ASYNCLISTADDR = 0;
  126. USBHS_USBCMD = USBHS_USBCMD_ITC(8) | USBHS_USBCMD_RS |
  127. USBHS_USBCMD_ASP(3) | USBHS_USBCMD_ASPE | USBHS_USBCMD_PSE |
  128. #if PERIODIC_LIST_SIZE == 8
  129. USBHS_USBCMD_FS2 | USBHS_USBCMD_FS(3);
  130. #elif PERIODIC_LIST_SIZE == 16
  131. USBHS_USBCMD_FS2 | USBHS_USBCMD_FS(2);
  132. #elif PERIODIC_LIST_SIZE == 32
  133. USBHS_USBCMD_FS2 | USBHS_USBCMD_FS(1);
  134. #elif PERIODIC_LIST_SIZE == 64
  135. USBHS_USBCMD_FS2 | USBHS_USBCMD_FS(0);
  136. #elif PERIODIC_LIST_SIZE == 128
  137. USBHS_USBCMD_FS(3);
  138. #elif PERIODIC_LIST_SIZE == 256
  139. USBHS_USBCMD_FS(2);
  140. #elif PERIODIC_LIST_SIZE == 512
  141. USBHS_USBCMD_FS(1);
  142. #elif PERIODIC_LIST_SIZE == 1024
  143. USBHS_USBCMD_FS(0);
  144. #else
  145. #error "Unsupported PERIODIC_LIST_SIZE"
  146. #endif
  147. // turn on the USB port
  148. //USBHS_PORTSC1 = USBHS_PORTSC_PP;
  149. USBHS_PORTSC1 |= USBHS_PORTSC_PP;
  150. //USBHS_PORTSC1 |= USBHS_PORTSC_PFSC; // force 12 Mbit/sec
  151. //USBHS_PORTSC1 |= USBHS_PORTSC_PHCD; // phy off
  152. //println("USBHS_ASYNCLISTADDR = ", USBHS_ASYNCLISTADDR, HEX);
  153. //println("USBHS_PERIODICLISTBASE = ", USBHS_PERIODICLISTBASE, HEX);
  154. //println("periodictable = ", (uint32_t)periodictable, HEX);
  155. // enable interrupts, after this point interruts to all the work
  156. attachInterruptVector(IRQ_USBHS, isr);
  157. NVIC_ENABLE_IRQ(IRQ_USBHS);
  158. USBHS_USBINTR = USBHS_USBINTR_PCE | USBHS_USBINTR_TIE0 | USBHS_USBINTR_TIE1;
  159. USBHS_USBINTR |= USBHS_USBINTR_UEE | USBHS_USBINTR_SEE;
  160. USBHS_USBINTR |= USBHS_USBINTR_AAE;
  161. USBHS_USBINTR |= USBHS_USBINTR_UPIE | USBHS_USBINTR_UAIE;
  162. }
  163. // EHCI registers page default
  164. // -------------- ---- -------
  165. // USBHS_USBCMD 1599 00080000 USB Command
  166. // USBHS_USBSTS 1602 00000000 USB Status
  167. // USBHS_USBINTR 1606 00000000 USB Interrupt Enable
  168. // USBHS_FRINDEX 1609 00000000 Frame Index Register
  169. // USBHS_PERIODICLISTBASE 1610 undefine Periodic Frame List Base Address
  170. // USBHS_ASYNCLISTADDR 1612 undefine Asynchronous List Address
  171. // USBHS_PORTSC1 1619 00002000 Port Status and Control
  172. // USBHS_USBMODE 1629 00005000 USB Mode
  173. // USBHS_GPTIMERnCTL 1591 00000000 General Purpose Timer n Control
  174. // PORT_STATE_DISCONNECTED 0
  175. // PORT_STATE_DEBOUNCE 1
  176. // PORT_STATE_RESET 2
  177. // PORT_STATE_RECOVERY 3
  178. // PORT_STATE_ACTIVE 4
  179. void USBHost::isr()
  180. {
  181. uint32_t stat = USBHS_USBSTS;
  182. USBHS_USBSTS = stat; // clear pending interrupts
  183. //stat &= USBHS_USBINTR; // mask away unwanted interrupts
  184. println();
  185. println("ISR: ", stat, HEX);
  186. //if (stat & USBHS_USBSTS_UI) println(" USB Interrupt");
  187. if (stat & USBHS_USBSTS_UEI) println(" USB Error");
  188. if (stat & USBHS_USBSTS_PCI) println(" Port Change");
  189. //if (stat & USBHS_USBSTS_FRI) println(" Frame List Rollover");
  190. if (stat & USBHS_USBSTS_SEI) println(" System Error");
  191. //if (stat & USBHS_USBSTS_AAI) println(" Async Advance (doorbell)");
  192. if (stat & USBHS_USBSTS_URI) println(" Reset Recv");
  193. //if (stat & USBHS_USBSTS_SRI) println(" SOF");
  194. if (stat & USBHS_USBSTS_SLI) println(" Suspend");
  195. if (stat & USBHS_USBSTS_HCH) println(" Host Halted");
  196. //if (stat & USBHS_USBSTS_RCL) println(" Reclamation");
  197. //if (stat & USBHS_USBSTS_PS) println(" Periodic Sched En");
  198. //if (stat & USBHS_USBSTS_AS) println(" Async Sched En");
  199. if (stat & USBHS_USBSTS_NAKI) println(" NAK");
  200. if (stat & USBHS_USBSTS_UAI) println(" USB Async");
  201. if (stat & USBHS_USBSTS_UPI) println(" USB Periodic");
  202. if (stat & USBHS_USBSTS_TI0) println(" Timer0");
  203. if (stat & USBHS_USBSTS_TI1) println(" Timer1");
  204. if (stat & USBHS_USBSTS_UAI) { // completed qTD(s) from the async schedule
  205. println("Async Followup");
  206. //print(async_followup_first, async_followup_last);
  207. Transfer_t *p = async_followup_first;
  208. while (p) {
  209. if (followup_Transfer(p)) {
  210. // transfer completed
  211. Transfer_t *next = p->next_followup;
  212. remove_from_async_followup_list(p);
  213. free_Transfer(p);
  214. p = next;
  215. } else {
  216. // transfer still pending
  217. p = p->next_followup;
  218. }
  219. }
  220. //print(async_followup_first, async_followup_last);
  221. }
  222. if (stat & USBHS_USBSTS_UPI) { // completed qTD(s) from the periodic schedule
  223. println("Periodic Followup");
  224. Transfer_t *p = periodic_followup_first;
  225. while (p) {
  226. if (followup_Transfer(p)) {
  227. // transfer completed
  228. Transfer_t *next = p->next_followup;
  229. remove_from_periodic_followup_list(p);
  230. free_Transfer(p);
  231. p = next;
  232. } else {
  233. // transfer still pending
  234. p = p->next_followup;
  235. }
  236. }
  237. }
  238. if (stat & USBHS_USBSTS_PCI) { // port change detected
  239. const uint32_t portstat = USBHS_PORTSC1;
  240. println("port change: ", portstat, HEX);
  241. USBHS_PORTSC1 = portstat | (USBHS_PORTSC_OCC|USBHS_PORTSC_PEC|USBHS_PORTSC_CSC);
  242. if (portstat & USBHS_PORTSC_OCC) {
  243. println(" overcurrent change");
  244. }
  245. if (portstat & USBHS_PORTSC_CSC) {
  246. if (portstat & USBHS_PORTSC_CCS) {
  247. println(" connect");
  248. if (port_state == PORT_STATE_DISCONNECTED
  249. || port_state == PORT_STATE_DEBOUNCE) {
  250. // 100 ms debounce (USB 2.0: TATTDB, page 150 & 188)
  251. port_state = PORT_STATE_DEBOUNCE;
  252. USBHS_GPTIMER0LD = 100000; // microseconds
  253. USBHS_GPTIMER0CTL =
  254. USBHS_GPTIMERCTL_RST | USBHS_GPTIMERCTL_RUN;
  255. stat &= ~USBHS_USBSTS_TI0;
  256. }
  257. } else {
  258. println(" disconnect");
  259. port_state = PORT_STATE_DISCONNECTED;
  260. USBPHY_CTRL_CLR = USBPHY_CTRL_ENHOSTDISCONDETECT;
  261. disconnect_Device(rootdev);
  262. rootdev = NULL;
  263. }
  264. }
  265. if (portstat & USBHS_PORTSC_PEC) {
  266. // PEC bit only detects disable
  267. println(" disable");
  268. } else if (port_state == PORT_STATE_RESET && portstat & USBHS_PORTSC_PE) {
  269. println(" port enabled");
  270. port_state = PORT_STATE_RECOVERY;
  271. // 10 ms reset recover (USB 2.0: TRSTRCY, page 151 & 188)
  272. USBHS_GPTIMER0LD = 10000; // microseconds
  273. USBHS_GPTIMER0CTL = USBHS_GPTIMERCTL_RST | USBHS_GPTIMERCTL_RUN;
  274. if (USBHS_PORTSC1 & USBHS_PORTSC_HSP) {
  275. // turn on high-speed disconnect detector
  276. USBPHY_CTRL_SET = USBPHY_CTRL_ENHOSTDISCONDETECT;
  277. }
  278. }
  279. if (portstat & USBHS_PORTSC_FPR) {
  280. println(" force resume");
  281. }
  282. }
  283. if (stat & USBHS_USBSTS_TI0) { // timer 0 - used for built-in port events
  284. println("timer0");
  285. if (port_state == PORT_STATE_DEBOUNCE) {
  286. port_state = PORT_STATE_RESET;
  287. USBHS_PORTSC1 |= USBHS_PORTSC_PR; // begin reset sequence
  288. println(" begin reset");
  289. } else if (port_state == PORT_STATE_RECOVERY) {
  290. port_state = PORT_STATE_ACTIVE;
  291. println(" end recovery");
  292. // HCSPARAMS TTCTRL page 1671
  293. uint32_t speed = (USBHS_PORTSC1 >> 26) & 3;
  294. rootdev = new_Device(speed, 0, 0);
  295. }
  296. }
  297. if (stat & USBHS_USBSTS_TI1) { // timer 1 - used for USBDriverTimer
  298. println("timer1");
  299. }
  300. }
  301. void USBDriverTimer::start(uint32_t microseconds)
  302. {
  303. Serial.print("start_timer, usec = ");
  304. Serial.print(usec);
  305. Serial.print(", driver = ");
  306. Serial.print((uint32_t)driver, HEX);
  307. Serial.print(", this = ");
  308. Serial.println((uint32_t)this, HEX);
  309. #if 1
  310. if (!driver) return;
  311. if (microseconds < 100) return; // minimum timer duration
  312. if (active_timers == NULL) {
  313. usec = microseconds;
  314. next = NULL;
  315. prev = NULL;
  316. active_timers = this;
  317. USBHS_GPTIMER1LD = microseconds - 1;
  318. USBHS_GPTIMER1CTL = USBHS_GPTIMERCTL_RST | USBHS_GPTIMERCTL_RUN;
  319. return;
  320. }
  321. #endif
  322. // TODO, add to active_timers list
  323. //uint32_t remain = USBHS_GPTIMER1CTL & 0xFFFFFF;
  324. }
  325. static uint32_t QH_capabilities1(uint32_t nak_count_reload, uint32_t control_endpoint_flag,
  326. uint32_t max_packet_length, uint32_t head_of_list, uint32_t data_toggle_control,
  327. uint32_t speed, uint32_t endpoint_number, uint32_t inactivate, uint32_t address)
  328. {
  329. return ( (nak_count_reload << 28) | (control_endpoint_flag << 27) |
  330. (max_packet_length << 16) | (head_of_list << 15) |
  331. (data_toggle_control << 14) | (speed << 12) | (endpoint_number << 8) |
  332. (inactivate << 7) | (address << 0) );
  333. }
  334. static uint32_t QH_capabilities2(uint32_t high_bw_mult, uint32_t hub_port_number,
  335. uint32_t hub_address, uint32_t split_completion_mask, uint32_t interrupt_schedule_mask)
  336. {
  337. return ( (high_bw_mult << 30) | (hub_port_number << 23) | (hub_address << 16) |
  338. (split_completion_mask << 8) | (interrupt_schedule_mask << 0) );
  339. }
  340. // Create a new pipe. It's QH is added to the async or periodic schedule,
  341. // and a halt qTD is added to the QH, so we can grow the qTD list later.
  342. // dev: device owning this pipe/endpoint
  343. // type: 0=control, 2=bulk, 3=interrupt
  344. // endpoint: 0 for control, 1-15 for bulk or interrupt
  345. // direction: 0=OUT, 1=IN (unused for control)
  346. // maxlen: maximum packet size
  347. // interval: polling interval for interrupt, power of 2, unused if control or bulk
  348. //
  349. Pipe_t * USBHost::new_Pipe(Device_t *dev, uint32_t type, uint32_t endpoint,
  350. uint32_t direction, uint32_t maxlen, uint32_t interval)
  351. {
  352. Pipe_t *pipe;
  353. Transfer_t *halt;
  354. uint32_t c=0, dtc=0;
  355. println("new_Pipe");
  356. pipe = allocate_Pipe();
  357. if (!pipe) return NULL;
  358. halt = allocate_Transfer();
  359. if (!halt) {
  360. free_Pipe(pipe);
  361. return NULL;
  362. }
  363. memset(pipe, 0, sizeof(Pipe_t));
  364. memset(halt, 0, sizeof(Transfer_t));
  365. halt->qtd.next = 1;
  366. halt->qtd.token = 0x40;
  367. pipe->device = dev;
  368. pipe->qh.next = (uint32_t)halt;
  369. pipe->qh.alt_next = 1;
  370. pipe->direction = direction;
  371. pipe->type = type;
  372. if (type == 3) {
  373. // interrupt transfers require bandwidth & microframe scheduling
  374. if (!allocate_interrupt_pipe_bandwidth(pipe, maxlen, interval)) {
  375. free_Transfer(halt);
  376. free_Pipe(pipe);
  377. return NULL;
  378. }
  379. }
  380. if (endpoint > 0) {
  381. // if non-control pipe, update dev->data_pipes list
  382. Pipe_t *p = dev->data_pipes;
  383. if (p == NULL) {
  384. dev->data_pipes = pipe;
  385. } else {
  386. while (p->next) p = p->next;
  387. p->next = pipe;
  388. }
  389. }
  390. if (type == 0) {
  391. // control
  392. if (dev->speed < 2) c = 1;
  393. dtc = 1;
  394. } else if (type == 2) {
  395. // bulk
  396. } else if (type == 3) {
  397. // interrupt
  398. //pipe->qh.token = 0x80000000; // TODO: OUT starts with DATA0 or DATA1?
  399. }
  400. pipe->qh.capabilities[0] = QH_capabilities1(15, c, maxlen, 0,
  401. dtc, dev->speed, endpoint, 0, dev->address);
  402. pipe->qh.capabilities[1] = QH_capabilities2(1, dev->hub_port,
  403. dev->hub_address, pipe->complete_mask, pipe->start_mask);
  404. if (type == 0 || type == 2) {
  405. // control or bulk: add to async queue
  406. Pipe_t *list = (Pipe_t *)USBHS_ASYNCLISTADDR;
  407. if (list == NULL) {
  408. pipe->qh.capabilities[0] |= 0x8000; // H bit
  409. pipe->qh.horizontal_link = (uint32_t)&(pipe->qh) | 2; // 2=QH
  410. USBHS_ASYNCLISTADDR = (uint32_t)&(pipe->qh);
  411. USBHS_USBCMD |= USBHS_USBCMD_ASE; // enable async schedule
  412. //println(" first in async list");
  413. } else {
  414. // EHCI 1.0: section 4.8.1, page 72
  415. pipe->qh.horizontal_link = list->qh.horizontal_link;
  416. list->qh.horizontal_link = (uint32_t)&(pipe->qh) | 2;
  417. //println(" added to async list");
  418. }
  419. } else if (type == 3) {
  420. // interrupt: add to periodic schedule
  421. add_qh_to_periodic_schedule(pipe);
  422. }
  423. return pipe;
  424. }
  425. // Fill in the qTD fields (token & data)
  426. // t the Transfer qTD to initialize
  427. // buf data to transfer
  428. // len length of data
  429. // pid type of packet: 0=OUT, 1=IN, 2=SETUP
  430. // data01 value of DATA0/DATA1 toggle on 1st packet
  431. // irq whether to generate an interrupt when transfer complete
  432. //
  433. static void init_qTD(volatile Transfer_t *t, void *buf, uint32_t len,
  434. uint32_t pid, uint32_t data01, bool irq)
  435. {
  436. t->qtd.alt_next = 1; // 1=terminate
  437. if (data01) data01 = 0x80000000;
  438. t->qtd.token = data01 | (len << 16) | (irq ? 0x8000 : 0) | (pid << 8) | 0x80;
  439. uint32_t addr = (uint32_t)buf;
  440. t->qtd.buffer[0] = addr;
  441. addr &= 0xFFFFF000;
  442. t->qtd.buffer[1] = addr + 0x1000;
  443. t->qtd.buffer[2] = addr + 0x2000;
  444. t->qtd.buffer[3] = addr + 0x3000;
  445. t->qtd.buffer[4] = addr + 0x4000;
  446. }
  447. // Create a Control Transfer and queue it
  448. //
  449. bool USBHost::queue_Control_Transfer(Device_t *dev, setup_t *setup, void *buf, USBDriver *driver)
  450. {
  451. Transfer_t *transfer, *data, *status;
  452. uint32_t status_direction;
  453. println("new_Control_Transfer");
  454. if (setup->wLength > 16384) return false; // max 16K data for control
  455. transfer = allocate_Transfer();
  456. if (!transfer) return false;
  457. status = allocate_Transfer();
  458. if (!status) {
  459. free_Transfer(transfer);
  460. return false;
  461. }
  462. if (setup->wLength > 0) {
  463. data = allocate_Transfer();
  464. if (!data) {
  465. free_Transfer(transfer);
  466. free_Transfer(status);
  467. return false;
  468. }
  469. uint32_t pid = (setup->bmRequestType & 0x80) ? 1 : 0;
  470. init_qTD(data, buf, setup->wLength, pid, 1, false);
  471. transfer->qtd.next = (uint32_t)data;
  472. data->qtd.next = (uint32_t)status;
  473. status_direction = pid ^ 1;
  474. } else {
  475. transfer->qtd.next = (uint32_t)status;
  476. status_direction = 1; // always IN, USB 2.0 page 226
  477. }
  478. //println("setup address ", (uint32_t)setup, HEX);
  479. init_qTD(transfer, setup, 8, 2, 0, false);
  480. init_qTD(status, NULL, 0, status_direction, 1, true);
  481. status->pipe = dev->control_pipe;
  482. status->buffer = buf;
  483. status->length = setup->wLength;
  484. status->setup = setup;
  485. status->driver = driver;
  486. status->qtd.next = 1;
  487. return queue_Transfer(dev->control_pipe, transfer);
  488. }
  489. // Create a Bulk or Interrupt Transfer and queue it
  490. //
  491. bool USBHost::queue_Data_Transfer(Pipe_t *pipe, void *buffer, uint32_t len, USBDriver *driver)
  492. {
  493. Transfer_t *transfer, *data, *next;
  494. uint8_t *p = (uint8_t *)buffer;
  495. uint32_t count;
  496. bool last = false;
  497. // TODO: option for zero length packet? Maybe in Pipe_t fields?
  498. println("new_Data_Transfer");
  499. // allocate qTDs
  500. transfer = allocate_Transfer();
  501. if (!transfer) return false;
  502. data = transfer;
  503. for (count=(len >> 14); count; count--) {
  504. next = allocate_Transfer();
  505. if (!next) {
  506. // free already-allocated qTDs
  507. while (1) {
  508. next = (Transfer_t *)transfer->qtd.next;
  509. free_Transfer(transfer);
  510. if (transfer == data) break;
  511. transfer = next;
  512. }
  513. return false;
  514. }
  515. data->qtd.next = (uint32_t)next;
  516. data = next;
  517. }
  518. // last qTD needs info for followup
  519. data->qtd.next = 1;
  520. data->pipe = pipe;
  521. data->buffer = buffer;
  522. data->length = len;
  523. data->setup = NULL;
  524. data->driver = driver;
  525. // initialize all qTDs
  526. data = transfer;
  527. while (1) {
  528. uint32_t count = len;
  529. if (count > 16384) {
  530. count = 16384;
  531. } else {
  532. last = true;
  533. }
  534. init_qTD(data, p, count, pipe->direction, 0, last);
  535. if (last) break;
  536. p += count;
  537. len -= count;
  538. data = (Transfer_t *)(data->qtd.next);
  539. }
  540. return queue_Transfer(pipe, transfer);
  541. }
  542. bool USBHost::queue_Transfer(Pipe_t *pipe, Transfer_t *transfer)
  543. {
  544. // find halt qTD
  545. Transfer_t *halt = (Transfer_t *)(pipe->qh.next);
  546. while (!(halt->qtd.token & 0x40)) halt = (Transfer_t *)(halt->qtd.next);
  547. // transfer's token
  548. uint32_t token = transfer->qtd.token;
  549. // transfer becomes new halt qTD
  550. transfer->qtd.token = 0x40;
  551. // copy transfer non-token fields to halt
  552. halt->qtd.next = transfer->qtd.next;
  553. halt->qtd.alt_next = transfer->qtd.alt_next;
  554. halt->qtd.buffer[0] = transfer->qtd.buffer[0]; // TODO: optimize memcpy, all
  555. halt->qtd.buffer[1] = transfer->qtd.buffer[1]; // fields except token
  556. halt->qtd.buffer[2] = transfer->qtd.buffer[2];
  557. halt->qtd.buffer[3] = transfer->qtd.buffer[3];
  558. halt->qtd.buffer[4] = transfer->qtd.buffer[4];
  559. halt->pipe = pipe;
  560. halt->buffer = transfer->buffer;
  561. halt->length = transfer->length;
  562. halt->setup = transfer->setup;
  563. halt->driver = transfer->driver;
  564. // find the last qTD we're adding
  565. Transfer_t *last = halt;
  566. while ((uint32_t)(last->qtd.next) != 1) last = (Transfer_t *)(last->qtd.next);
  567. // last points to transfer (which becomes new halt)
  568. last->qtd.next = (uint32_t)transfer;
  569. transfer->qtd.next = 1;
  570. // link all the new qTD by next_followup & prev_followup
  571. Transfer_t *prev = NULL;
  572. Transfer_t *p = halt;
  573. while (p->qtd.next != (uint32_t)transfer) {
  574. Transfer_t *next = (Transfer_t *)p->qtd.next;
  575. p->prev_followup = prev;
  576. p->next_followup = next;
  577. prev = p;
  578. p = next;
  579. }
  580. p->prev_followup = prev;
  581. p->next_followup = NULL;
  582. //print(halt, p);
  583. // add them to a followup list
  584. if (pipe->type == 0 || pipe->type == 2) {
  585. // control or bulk
  586. add_to_async_followup_list(halt, p);
  587. } else {
  588. // interrupt
  589. add_to_periodic_followup_list(halt, p);
  590. }
  591. // old halt becomes new transfer, this commits all new qTDs to QH
  592. halt->qtd.token = token;
  593. return true;
  594. }
  595. static bool followup_Transfer(Transfer_t *transfer)
  596. {
  597. //println(" Followup ", (uint32_t)transfer, HEX);
  598. if (!(transfer->qtd.token & 0x80)) {
  599. // TODO: check error status
  600. if (transfer->qtd.token & 0x8000) {
  601. // this transfer caused an interrupt
  602. if (transfer->pipe->callback_function) {
  603. // do the callback
  604. (*(transfer->pipe->callback_function))(transfer);
  605. }
  606. }
  607. // do callback function...
  608. //println(" completed");
  609. return true;
  610. }
  611. return false;
  612. }
  613. static void add_to_async_followup_list(Transfer_t *first, Transfer_t *last)
  614. {
  615. last->next_followup = NULL; // always add to end of list
  616. if (async_followup_last == NULL) {
  617. first->prev_followup = NULL;
  618. async_followup_first = first;
  619. } else {
  620. first->prev_followup = async_followup_last;
  621. async_followup_last->next_followup = first;
  622. }
  623. async_followup_last = last;
  624. }
  625. static void remove_from_async_followup_list(Transfer_t *transfer)
  626. {
  627. Transfer_t *next = transfer->next_followup;
  628. Transfer_t *prev = transfer->prev_followup;
  629. if (prev) {
  630. prev->next_followup = next;
  631. } else {
  632. async_followup_first = next;
  633. }
  634. if (next) {
  635. next->prev_followup = prev;
  636. } else {
  637. async_followup_last = prev;
  638. }
  639. }
  640. static void add_to_periodic_followup_list(Transfer_t *first, Transfer_t *last)
  641. {
  642. last->next_followup = NULL; // always add to end of list
  643. if (periodic_followup_last == NULL) {
  644. first->prev_followup = NULL;
  645. periodic_followup_first = first;
  646. } else {
  647. first->prev_followup = periodic_followup_last;
  648. periodic_followup_last->next_followup = first;
  649. }
  650. periodic_followup_last = last;
  651. }
  652. static void remove_from_periodic_followup_list(Transfer_t *transfer)
  653. {
  654. Transfer_t *next = transfer->next_followup;
  655. Transfer_t *prev = transfer->prev_followup;
  656. if (prev) {
  657. prev->next_followup = next;
  658. } else {
  659. periodic_followup_first = next;
  660. }
  661. if (next) {
  662. next->prev_followup = prev;
  663. } else {
  664. periodic_followup_last = prev;
  665. }
  666. }
  667. static uint32_t max4(uint32_t n1, uint32_t n2, uint32_t n3, uint32_t n4)
  668. {
  669. if (n1 > n2) {
  670. // can't be n2
  671. if (n1 > n3) {
  672. // can't be n3
  673. if (n1 > n4) return n1;
  674. } else {
  675. // can't be n1
  676. if (n3 > n4) return n3;
  677. }
  678. } else {
  679. // can't be n1
  680. if (n2 > n3) {
  681. // can't be n3
  682. if (n2 > n4) return n2;
  683. } else {
  684. // can't be n2
  685. if (n3 > n4) return n3;
  686. }
  687. }
  688. return n4;
  689. }
  690. static uint32_t round_to_power_of_two(uint32_t n, uint32_t maxnum)
  691. {
  692. for (uint32_t pow2num=1; pow2num < maxnum; pow2num <<= 1) {
  693. if (n <= (pow2num | (pow2num >> 1))) return pow2num;
  694. }
  695. return maxnum;
  696. }
  697. // Allocate bandwidth for an interrupt pipe. Given the packet size
  698. // and other parameters, find the best place to schedule this pipe.
  699. // Returns true if enough bandwidth is available, and the best
  700. // frame offset, smask and cmask. Or returns false if no group
  701. // of microframes has enough bandwidth available.
  702. //
  703. // pipe:
  704. // device->speed [in] 0=full speed, 1=low speed, 2=high speed
  705. // direction [in] 0=OUT, 1=IN
  706. // start_mask [out] uframes to start transfer
  707. // complete_mask [out] uframes to complete transfer (FS & LS only)
  708. // periodic_interval [out] fream repeat level: 1, 2, 4, 8... PERIODIC_LIST_SIZE
  709. // periodic_offset [out] frame repeat offset: 0 to periodic_interval-1
  710. // maxlen: [in] maximum packet length
  711. // interval: [in] polling interval: LS+FS: frames, HS: 2^(n-1) uframes
  712. //
  713. bool USBHost::allocate_interrupt_pipe_bandwidth(Pipe_t *pipe, uint32_t maxlen, uint32_t interval)
  714. {
  715. println("allocate_interrupt_pipe_bandwidth");
  716. if (interval == 0) interval = 1;
  717. maxlen = (maxlen * 76459) >> 16; // worst case bit stuffing
  718. if (pipe->device->speed == 2) {
  719. // high speed 480 Mbit/sec
  720. if (interval > 15) interval = 15;
  721. interval = 1 << (interval - 1);
  722. if (interval > PERIODIC_LIST_SIZE*8) interval = PERIODIC_LIST_SIZE*8;
  723. uint32_t stime = (55 + 32 + maxlen) >> 5; // time units: 32 bytes or 533 ns
  724. uint32_t best_offset = 0xFFFFFFFF;
  725. uint32_t best_bandwidth = 0xFFFFFFFF;
  726. for (uint32_t offset=0; offset < interval; offset++) {
  727. // for each possible uframe offset, find the worst uframe bandwidth
  728. uint32_t max_bandwidth = 0;
  729. for (uint32_t i=offset; i < PERIODIC_LIST_SIZE*8; i += interval) {
  730. uint32_t bandwidth = uframe_bandwidth[i] + stime;
  731. if (bandwidth > max_bandwidth) max_bandwidth = bandwidth;
  732. }
  733. // remember which uframe offset is the best
  734. if (max_bandwidth < best_bandwidth) {
  735. best_bandwidth = max_bandwidth;
  736. best_offset = offset;
  737. }
  738. }
  739. print(" best_bandwidth = ");
  740. print(best_bandwidth);
  741. print(", at offset = ");
  742. println(best_offset);
  743. // a 125 us micro frame can fit 7500 bytes, or 234 of our 32-byte units
  744. // fail if the best found needs more than 80% (234 * 0.8) in any uframe
  745. if (best_bandwidth > 187) return false;
  746. for (uint32_t i=best_offset; i < PERIODIC_LIST_SIZE*8; i += interval) {
  747. uframe_bandwidth[i] += stime;
  748. }
  749. if (interval == 1) {
  750. pipe->start_mask = 0xFF;
  751. } else if (interval == 2) {
  752. pipe->start_mask = 0x55 << (best_offset & 1);
  753. } else if (interval <= 4) {
  754. pipe->start_mask = 0x11 << (best_offset & 3);
  755. } else {
  756. pipe->start_mask = 0x01 << (best_offset & 7);
  757. }
  758. uint32_t poffset = best_offset >> 3;
  759. pipe->periodic_offset = (poffset > 0) ? poffset : 1;
  760. pipe->complete_mask = 0;
  761. } else {
  762. // full speed 12 Mbit/sec or low speed 1.5 Mbit/sec
  763. interval = round_to_power_of_two(interval, PERIODIC_LIST_SIZE);
  764. pipe->periodic_interval = interval;
  765. uint32_t stime, ctime;
  766. if (pipe->direction == 0) {
  767. // for OUT direction, SSPLIT will carry the data payload
  768. // TODO: how much time to SSPLIT & CSPLIT actually take?
  769. // they're not documented in 5.7 or 5.11.3.
  770. stime = (100 + 32 + maxlen) >> 5;
  771. ctime = (55 + 32) >> 5;
  772. } else {
  773. // for IN direction, data payload in CSPLIT
  774. stime = (40 + 32) >> 5;
  775. ctime = (70 + 32 + maxlen) >> 5;
  776. }
  777. // TODO: should we take Single-TT hubs into account, avoid
  778. // scheduling overlapping SSPLIT & CSPLIT to the same hub?
  779. // TODO: even if Multi-TT, do we need to worry about packing
  780. // too many into the same uframe?
  781. uint32_t best_shift = 0;
  782. uint32_t best_offset = 0xFFFFFFFF;
  783. uint32_t best_bandwidth = 0xFFFFFFFF;
  784. for (uint32_t offset=0; offset < interval; offset++) {
  785. // for each 1ms frame offset, compute the worst uframe usage
  786. uint32_t max_bandwidth = 0;
  787. for (uint32_t i=offset; i < PERIODIC_LIST_SIZE; i += interval) {
  788. for (uint32_t j=0; j <= 3; j++) { // max 3 without FSTN
  789. // at each location, find worst uframe usage
  790. // for SSPLIT+CSPLITs
  791. uint32_t n = (i << 3) + j;
  792. uint32_t bw1 = uframe_bandwidth[n+0] + stime;
  793. uint32_t bw2 = uframe_bandwidth[n+2] + ctime;
  794. uint32_t bw3 = uframe_bandwidth[n+3] + ctime;
  795. uint32_t bw4 = uframe_bandwidth[n+4] + ctime;
  796. max_bandwidth = max4(bw1, bw2, bw3, bw4);
  797. // remember the best usage found
  798. if (max_bandwidth < best_bandwidth) {
  799. best_bandwidth = max_bandwidth;
  800. best_offset = i;
  801. best_shift = j;
  802. }
  803. }
  804. }
  805. }
  806. print(" best_bandwidth = ");
  807. println(best_bandwidth);
  808. print(", at offset = ");
  809. print(best_offset);
  810. print(", shift= ");
  811. println(best_shift);
  812. // a 125 us micro frame can fit 7500 bytes, or 234 of our 32-byte units
  813. // fail if the best found needs more than 80% (234 * 0.8) in any uframe
  814. if (best_bandwidth > 187) return false;
  815. for (uint32_t i=best_offset; i < PERIODIC_LIST_SIZE; i += interval) {
  816. uint32_t n = (i << 3) + best_shift;
  817. uframe_bandwidth[n+0] += stime;
  818. uframe_bandwidth[n+2] += ctime;
  819. uframe_bandwidth[n+3] += ctime;
  820. uframe_bandwidth[n+4] += ctime;
  821. }
  822. pipe->start_mask = 0x01 << best_shift;
  823. pipe->complete_mask = 0x1C << best_shift;
  824. pipe->periodic_offset = best_offset;
  825. }
  826. return true;
  827. }
  828. // put a new pipe into the periodic schedule tree
  829. // according to periodic_interval and periodic_offset
  830. //
  831. void USBHost::add_qh_to_periodic_schedule(Pipe_t *pipe)
  832. {
  833. // quick hack for testing, just put it into the first table entry
  834. println("add_qh_to_periodic_schedule:");
  835. #if 0
  836. pipe->qh.horizontal_link = periodictable[0];
  837. periodictable[0] = (uint32_t)&(pipe->qh) | 2; // 2=QH
  838. println("init periodictable with ", periodictable[0], HEX);
  839. #else
  840. uint32_t interval = pipe->periodic_interval;
  841. uint32_t offset = pipe->periodic_offset;
  842. println(" interval = ", interval);
  843. println(" offset = ", offset);
  844. // TODO: does this really make an inverted tree like EHCI figure 4-18, page 93
  845. for (uint32_t i=offset; i < PERIODIC_LIST_SIZE; i += interval) {
  846. uint32_t num = periodictable[i];
  847. Pipe_t *node = (Pipe_t *)(num & 0xFFFFFFE0);
  848. if ((num & 1) || ((num & 6) == 2 && node->periodic_interval < interval)) {
  849. println(" add to slot ", i);
  850. pipe->qh.horizontal_link = num;
  851. periodictable[i] = (uint32_t)&(pipe->qh) | 2; // 2=QH
  852. } else {
  853. println(" traverse list ", i);
  854. // TODO: skip past iTD, siTD when/if we support isochronous
  855. while (node->periodic_interval >= interval) {
  856. if (node->qh.horizontal_link & 1) break;
  857. num = node->qh.horizontal_link;
  858. node = (Pipe_t *)(num & 0xFFFFFFE0);
  859. }
  860. pipe->qh.horizontal_link = num;
  861. node->qh.horizontal_link = (uint32_t)pipe | 2; // 2=QH
  862. }
  863. }
  864. #endif
  865. println("Periodic Schedule:");
  866. for (uint32_t i=0; i < PERIODIC_LIST_SIZE; i++) {
  867. if (i < 10) print(" ");
  868. print(i);
  869. print(": ");
  870. print_qh_list((Pipe_t *)(periodictable[i] & 0xFFFFFFE0));
  871. }
  872. }
  873. void USBHost::delete_Pipe(Pipe_t *pipe)
  874. {
  875. println("delete_Pipe ", (uint32_t)pipe, HEX);
  876. // halt pipe, find and free all Transfer_t
  877. // EHCI 1.0, 4.8.2 page 72: "Software should first deactivate
  878. // all active qTDs, wait for the queue head to go inactive"
  879. //
  880. // http://www.spinics.net/lists/linux-usb/msg131607.html
  881. // http://www.spinics.net/lists/linux-usb/msg131936.html
  882. //
  883. // In practice it's not feasible to wait for an active QH to become
  884. // inactive before removing it, for several reasons. For one, the QH may
  885. // _never_ become inactive (if the endpoint NAKs indefinitely). For
  886. // another, the procedure given in the spec (deactivate the qTDs on the
  887. // queue) is racy, since the controller can perform a new overlay or
  888. // writeback at any time.
  889. bool isasync = (pipe->type == 0 || pipe->type == 2);
  890. if (isasync) {
  891. // find the next QH in the async schedule loop
  892. Pipe_t *next = (Pipe_t *)(pipe->qh.horizontal_link & 0xFFFFFFE0);
  893. if (next == pipe) {
  894. // removing the only QH, so just shut down the async schedule
  895. println(" shut down async schedule");
  896. USBHS_USBCMD &= ~USBHS_USBCMD_ASE; // disable async schedule
  897. while (USBHS_USBSTS & USBHS_USBSTS_AS) ; // busy loop wait
  898. USBHS_ASYNCLISTADDR = 0;
  899. } else {
  900. // find the previous QH in the async schedule loop
  901. println(" remove QH from async schedule");
  902. Pipe_t *prev = next;
  903. while (1) {
  904. Pipe_t *n = (Pipe_t *)(prev->qh.horizontal_link & 0xFFFFFFE0);
  905. if (n == pipe) break;
  906. prev = n;
  907. }
  908. // if removing the one with H bit, set another
  909. if (pipe->qh.capabilities[0] & 0x8000) {
  910. prev->qh.capabilities[0] |= 0x8000; // set H bit
  911. }
  912. // link the previous QH, we're no longer in the loop
  913. prev->qh.horizontal_link = pipe->qh.horizontal_link;
  914. // do the Async Advance Doorbell handshake to wait to be
  915. // sure the EHCI no longer references the removed QH
  916. USBHS_USBCMD |= USBHS_USBCMD_IAA;
  917. while (!(USBHS_USBSTS & USBHS_USBSTS_AAI)) ; // busy loop wait
  918. USBHS_USBSTS = USBHS_USBSTS_AAI;
  919. // TODO: does this write interfere UPI & UAI (bits 18 & 19) ??
  920. }
  921. // find & free all the transfers which completed
  922. Transfer_t *t = async_followup_first;
  923. while (t) {
  924. Transfer_t *next = t->next_followup;
  925. if (t->pipe == pipe) {
  926. remove_from_async_followup_list(t);
  927. free_Transfer(t);
  928. }
  929. t = next;
  930. }
  931. } else {
  932. // remove from the periodic schedule
  933. for (uint32_t i=0; i < PERIODIC_LIST_SIZE; i++) {
  934. uint32_t num = periodictable[i];
  935. if (num & 1) continue;
  936. Pipe_t *node = (Pipe_t *)(num & 0xFFFFFFE0);
  937. if (node == pipe) {
  938. periodictable[i] = pipe->qh.horizontal_link;
  939. continue;
  940. }
  941. Pipe_t *prev = node;
  942. while (1) {
  943. num = node->qh.horizontal_link;
  944. if (num & 1) break;
  945. node = (Pipe_t *)(num & 0xFFFFFFE0);
  946. if (node == pipe) {
  947. prev->qh.horizontal_link = node->qh.horizontal_link;
  948. break;
  949. }
  950. prev = node;
  951. }
  952. }
  953. // TODO: subtract bandwidth from uframe_bandwidth array
  954. // find & free all the transfers which completed
  955. Transfer_t *t = periodic_followup_first;
  956. while (t) {
  957. Transfer_t *next = t->next_followup;
  958. if (t->pipe == pipe) {
  959. remove_from_periodic_followup_list(t);
  960. free_Transfer(t);
  961. }
  962. t = next;
  963. }
  964. }
  965. //
  966. // TODO: do we need to look at pipe->qh.current ??
  967. //
  968. // free all the transfers still attached to the QH
  969. Transfer_t *tr = (Transfer_t *)(pipe->qh.next);
  970. while ((uint32_t)tr & 0xFFFFFFE0) {
  971. Transfer_t *next = (Transfer_t *)(tr->qtd.next);
  972. free_Transfer(tr);
  973. tr = next;
  974. }
  975. // hopefully we found everything...
  976. free_Pipe(pipe);
  977. }