您最多选择25个主题 主题必须以字母或数字开头,可以包含连字符 (-),并且长度不得超过35个字符

1163 行
38KB

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