You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

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