Du kan inte välja fler än 25 ämnen Ämnen måste starta med en bokstav eller siffra, kan innehålla bindestreck ('-') och vara max 35 tecken långa.

1380 lines
45KB

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