Вы не можете выбрать более 25 тем Темы должны начинаться с буквы или цифры, могут содержать дефисы(-) и должны содержать не более 35 символов.

1310 lines
43KB

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