No puede seleccionar más de 25 temas Los temas deben comenzar con una letra o número, pueden incluir guiones ('-') y pueden tener hasta 35 caracteres de largo.

1273 líneas
42KB

  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 1
  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. #ifdef USBHOST_PRINT_DEBUG
  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. static uint32_t QH_capabilities1(uint32_t nak_count_reload, uint32_t control_endpoint_flag,
  426. uint32_t max_packet_length, uint32_t head_of_list, uint32_t data_toggle_control,
  427. uint32_t speed, uint32_t endpoint_number, uint32_t inactivate, uint32_t address)
  428. {
  429. return ( (nak_count_reload << 28) | (control_endpoint_flag << 27) |
  430. (max_packet_length << 16) | (head_of_list << 15) |
  431. (data_toggle_control << 14) | (speed << 12) | (endpoint_number << 8) |
  432. (inactivate << 7) | (address << 0) );
  433. }
  434. static uint32_t QH_capabilities2(uint32_t high_bw_mult, uint32_t hub_port_number,
  435. uint32_t hub_address, uint32_t split_completion_mask, uint32_t interrupt_schedule_mask)
  436. {
  437. return ( (high_bw_mult << 30) | (hub_port_number << 23) | (hub_address << 16) |
  438. (split_completion_mask << 8) | (interrupt_schedule_mask << 0) );
  439. }
  440. // Create a new pipe. It's QH is added to the async or periodic schedule,
  441. // and a halt qTD is added to the QH, so we can grow the qTD list later.
  442. // dev: device owning this pipe/endpoint
  443. // type: 0=control, 2=bulk, 3=interrupt
  444. // endpoint: 0 for control, 1-15 for bulk or interrupt
  445. // direction: 0=OUT, 1=IN (unused for control)
  446. // maxlen: maximum packet size
  447. // interval: polling interval for interrupt, power of 2, unused if control or bulk
  448. //
  449. Pipe_t * USBHost::new_Pipe(Device_t *dev, uint32_t type, uint32_t endpoint,
  450. uint32_t direction, uint32_t maxlen, uint32_t interval)
  451. {
  452. Pipe_t *pipe;
  453. Transfer_t *halt;
  454. uint32_t c=0, dtc=0;
  455. println("new_Pipe");
  456. pipe = allocate_Pipe();
  457. if (!pipe) return NULL;
  458. halt = allocate_Transfer();
  459. if (!halt) {
  460. free_Pipe(pipe);
  461. return NULL;
  462. }
  463. memset(pipe, 0, sizeof(Pipe_t));
  464. memset(halt, 0, sizeof(Transfer_t));
  465. halt->qtd.next = 1;
  466. halt->qtd.token = 0x40;
  467. pipe->device = dev;
  468. pipe->qh.next = (uint32_t)halt;
  469. pipe->qh.alt_next = 1;
  470. pipe->direction = direction;
  471. pipe->type = type;
  472. if (type == 3) {
  473. // interrupt transfers require bandwidth & microframe scheduling
  474. if (!allocate_interrupt_pipe_bandwidth(pipe, maxlen, interval)) {
  475. free_Transfer(halt);
  476. free_Pipe(pipe);
  477. return NULL;
  478. }
  479. }
  480. if (endpoint > 0) {
  481. // if non-control pipe, update dev->data_pipes list
  482. Pipe_t *p = dev->data_pipes;
  483. if (p == NULL) {
  484. dev->data_pipes = pipe;
  485. } else {
  486. while (p->next) p = p->next;
  487. p->next = pipe;
  488. }
  489. }
  490. if (type == 0) {
  491. // control
  492. if (dev->speed < 2) c = 1;
  493. dtc = 1;
  494. } else if (type == 2) {
  495. // bulk
  496. } else if (type == 3) {
  497. // interrupt
  498. //pipe->qh.token = 0x80000000; // TODO: OUT starts with DATA0 or DATA1?
  499. }
  500. pipe->qh.capabilities[0] = QH_capabilities1(15, c, maxlen, 0,
  501. dtc, dev->speed, endpoint, 0, dev->address);
  502. pipe->qh.capabilities[1] = QH_capabilities2(1, dev->hub_port,
  503. dev->hub_address, pipe->complete_mask, pipe->start_mask);
  504. if (type == 0 || type == 2) {
  505. // control or bulk: add to async queue
  506. Pipe_t *list = (Pipe_t *)USBHS_ASYNCLISTADDR;
  507. if (list == NULL) {
  508. pipe->qh.capabilities[0] |= 0x8000; // H bit
  509. pipe->qh.horizontal_link = (uint32_t)&(pipe->qh) | 2; // 2=QH
  510. USBHS_ASYNCLISTADDR = (uint32_t)&(pipe->qh);
  511. USBHS_USBCMD |= USBHS_USBCMD_ASE; // enable async schedule
  512. //println(" first in async list");
  513. } else {
  514. // EHCI 1.0: section 4.8.1, page 72
  515. pipe->qh.horizontal_link = list->qh.horizontal_link;
  516. list->qh.horizontal_link = (uint32_t)&(pipe->qh) | 2;
  517. //println(" added to async list");
  518. }
  519. } else if (type == 3) {
  520. // interrupt: add to periodic schedule
  521. add_qh_to_periodic_schedule(pipe);
  522. }
  523. return pipe;
  524. }
  525. // Fill in the qTD fields (token & data)
  526. // t the Transfer qTD to initialize
  527. // buf data to transfer
  528. // len length of data
  529. // pid type of packet: 0=OUT, 1=IN, 2=SETUP
  530. // data01 value of DATA0/DATA1 toggle on 1st packet
  531. // irq whether to generate an interrupt when transfer complete
  532. //
  533. static void init_qTD(volatile Transfer_t *t, void *buf, uint32_t len,
  534. uint32_t pid, uint32_t data01, bool irq)
  535. {
  536. t->qtd.alt_next = 1; // 1=terminate
  537. if (data01) data01 = 0x80000000;
  538. t->qtd.token = data01 | (len << 16) | (irq ? 0x8000 : 0) | (pid << 8) | 0x80;
  539. uint32_t addr = (uint32_t)buf;
  540. t->qtd.buffer[0] = addr;
  541. addr &= 0xFFFFF000;
  542. t->qtd.buffer[1] = addr + 0x1000;
  543. t->qtd.buffer[2] = addr + 0x2000;
  544. t->qtd.buffer[3] = addr + 0x3000;
  545. t->qtd.buffer[4] = addr + 0x4000;
  546. }
  547. // Create a Control Transfer and queue it
  548. //
  549. bool USBHost::queue_Control_Transfer(Device_t *dev, setup_t *setup, void *buf, USBDriver *driver)
  550. {
  551. Transfer_t *transfer, *data, *status;
  552. uint32_t status_direction;
  553. println("new_Control_Transfer");
  554. if (setup->wLength > 16384) return false; // max 16K data for control
  555. transfer = allocate_Transfer();
  556. if (!transfer) {
  557. println(" error allocating setup transfer");
  558. return false;
  559. }
  560. status = allocate_Transfer();
  561. if (!status) {
  562. println(" error allocating status transfer");
  563. free_Transfer(transfer);
  564. return false;
  565. }
  566. if (setup->wLength > 0) {
  567. data = allocate_Transfer();
  568. if (!data) {
  569. println(" error allocating data transfer");
  570. free_Transfer(transfer);
  571. free_Transfer(status);
  572. return false;
  573. }
  574. uint32_t pid = (setup->bmRequestType & 0x80) ? 1 : 0;
  575. init_qTD(data, buf, setup->wLength, pid, 1, false);
  576. transfer->qtd.next = (uint32_t)data;
  577. data->qtd.next = (uint32_t)status;
  578. status_direction = pid ^ 1;
  579. } else {
  580. transfer->qtd.next = (uint32_t)status;
  581. status_direction = 1; // always IN, USB 2.0 page 226
  582. }
  583. //println("setup address ", (uint32_t)setup, HEX);
  584. init_qTD(transfer, setup, 8, 2, 0, false);
  585. init_qTD(status, NULL, 0, status_direction, 1, true);
  586. status->pipe = dev->control_pipe;
  587. status->buffer = buf;
  588. status->length = setup->wLength;
  589. status->setup.word1 = setup->word1;
  590. status->setup.word2 = setup->word2;
  591. status->driver = driver;
  592. status->qtd.next = 1;
  593. return queue_Transfer(dev->control_pipe, transfer);
  594. }
  595. // Create a Bulk or Interrupt Transfer and queue it
  596. //
  597. bool USBHost::queue_Data_Transfer(Pipe_t *pipe, void *buffer, uint32_t len, USBDriver *driver)
  598. {
  599. Transfer_t *transfer, *data, *next;
  600. uint8_t *p = (uint8_t *)buffer;
  601. uint32_t count;
  602. bool last = false;
  603. // TODO: option for zero length packet? Maybe in Pipe_t fields?
  604. println("new_Data_Transfer");
  605. // allocate qTDs
  606. transfer = allocate_Transfer();
  607. if (!transfer) return false;
  608. data = transfer;
  609. for (count=(len >> 14); count; count--) {
  610. next = allocate_Transfer();
  611. if (!next) {
  612. // free already-allocated qTDs
  613. while (1) {
  614. next = (Transfer_t *)transfer->qtd.next;
  615. free_Transfer(transfer);
  616. if (transfer == data) break;
  617. transfer = next;
  618. }
  619. return false;
  620. }
  621. data->qtd.next = (uint32_t)next;
  622. data = next;
  623. }
  624. // last qTD needs info for followup
  625. data->qtd.next = 1;
  626. data->pipe = pipe;
  627. data->buffer = buffer;
  628. data->length = len;
  629. data->setup.word1 = 0;
  630. data->setup.word2 = 0;
  631. data->driver = driver;
  632. // initialize all qTDs
  633. data = transfer;
  634. while (1) {
  635. uint32_t count = len;
  636. if (count > 16384) {
  637. count = 16384;
  638. } else {
  639. last = true;
  640. }
  641. init_qTD(data, p, count, pipe->direction, 0, last);
  642. if (last) break;
  643. p += count;
  644. len -= count;
  645. data = (Transfer_t *)(data->qtd.next);
  646. }
  647. return queue_Transfer(pipe, transfer);
  648. }
  649. bool USBHost::queue_Transfer(Pipe_t *pipe, Transfer_t *transfer)
  650. {
  651. // find halt qTD
  652. Transfer_t *halt = (Transfer_t *)(pipe->qh.next);
  653. while (!(halt->qtd.token & 0x40)) halt = (Transfer_t *)(halt->qtd.next);
  654. // transfer's token
  655. uint32_t token = transfer->qtd.token;
  656. // transfer becomes new halt qTD
  657. transfer->qtd.token = 0x40;
  658. // copy transfer non-token fields to halt
  659. halt->qtd.next = transfer->qtd.next;
  660. halt->qtd.alt_next = transfer->qtd.alt_next;
  661. halt->qtd.buffer[0] = transfer->qtd.buffer[0]; // TODO: optimize memcpy, all
  662. halt->qtd.buffer[1] = transfer->qtd.buffer[1]; // fields except token
  663. halt->qtd.buffer[2] = transfer->qtd.buffer[2];
  664. halt->qtd.buffer[3] = transfer->qtd.buffer[3];
  665. halt->qtd.buffer[4] = transfer->qtd.buffer[4];
  666. halt->pipe = pipe;
  667. halt->buffer = transfer->buffer;
  668. halt->length = transfer->length;
  669. halt->setup = transfer->setup;
  670. halt->driver = transfer->driver;
  671. // find the last qTD we're adding
  672. Transfer_t *last = halt;
  673. while ((uint32_t)(last->qtd.next) != 1) last = (Transfer_t *)(last->qtd.next);
  674. // last points to transfer (which becomes new halt)
  675. last->qtd.next = (uint32_t)transfer;
  676. transfer->qtd.next = 1;
  677. // link all the new qTD by next_followup & prev_followup
  678. Transfer_t *prev = NULL;
  679. Transfer_t *p = halt;
  680. while (p->qtd.next != (uint32_t)transfer) {
  681. Transfer_t *next = (Transfer_t *)p->qtd.next;
  682. p->prev_followup = prev;
  683. p->next_followup = next;
  684. prev = p;
  685. p = next;
  686. }
  687. p->prev_followup = prev;
  688. p->next_followup = NULL;
  689. //print(halt, p);
  690. // add them to a followup list
  691. if (pipe->type == 0 || pipe->type == 2) {
  692. // control or bulk
  693. add_to_async_followup_list(halt, p);
  694. } else {
  695. // interrupt
  696. add_to_periodic_followup_list(halt, p);
  697. }
  698. // old halt becomes new transfer, this commits all new qTDs to QH
  699. halt->qtd.token = token;
  700. return true;
  701. }
  702. bool USBHost::followup_Transfer(Transfer_t *transfer)
  703. {
  704. print(" Followup ", (uint32_t)transfer, HEX);
  705. println(" token=", transfer->qtd.token, HEX);
  706. if (!(transfer->qtd.token & 0x80)) {
  707. // TODO: check error status
  708. if (transfer->qtd.token & 0x8000) {
  709. // this transfer caused an interrupt
  710. if (transfer->pipe->callback_function) {
  711. // do the callback
  712. (*(transfer->pipe->callback_function))(transfer);
  713. }
  714. }
  715. // do callback function...
  716. //println(" completed");
  717. return true;
  718. }
  719. return false;
  720. }
  721. void USBHost::followup_Error(void)
  722. {
  723. println("ERROR Followup");
  724. Transfer_t *p = async_followup_first;
  725. while (p) {
  726. if (followup_Transfer(p)) {
  727. // transfer completed
  728. Transfer_t *next = p->next_followup;
  729. remove_from_async_followup_list(p);
  730. println(" remove from followup list");
  731. if (p->qtd.token & 0x40) {
  732. Pipe_t *haltedpipe = p->pipe;
  733. free_Transfer(p);
  734. // traverse the rest of the list for unfinished work
  735. // from this halted pipe. Remove from the followup
  736. // list and put onto our own temporary list
  737. Transfer_t *first = NULL;
  738. Transfer_t *last = NULL;
  739. p = next;
  740. while (p) {
  741. Transfer_t *next2 = p->next_followup;
  742. if (p->pipe == haltedpipe) {
  743. println(" stray halted ", (uint32_t)p, HEX);
  744. remove_from_async_followup_list(p);
  745. if (first == NULL) {
  746. first = p;
  747. last = p;
  748. } else {
  749. last->next_followup = p;
  750. }
  751. p->next_followup = NULL;
  752. if (next == p) next = next2;
  753. }
  754. p = next2;
  755. }
  756. // halted pipe (probably) still has unfinished transfers
  757. // find the halted pipe's dummy halt transfer
  758. p = (Transfer_t *)(haltedpipe->qh.next & ~0x1F);
  759. while (p && ((p->qtd.token & 0x40) == 0)) {
  760. print(" qtd: ", (uint32_t)p, HEX);
  761. print(", token=", (uint32_t)p->qtd.token, HEX);
  762. println(", next=", (uint32_t)p->qtd.next, HEX);
  763. p = (Transfer_t *)(p->qtd.next & ~0x1F);
  764. }
  765. if (p) {
  766. // unhalt the pipe, "forget" unfinished transfers
  767. // hopefully they're all on the list we made!
  768. println(" dummy halt: ", (uint32_t)p, HEX);
  769. haltedpipe->qh.next = (uint32_t)p;
  770. haltedpipe->qh.current = 0;
  771. haltedpipe->qh.token = 0;
  772. } else {
  773. println(" no dummy halt found, yikes!");
  774. // TODO: this should never happen, but what if it does?
  775. }
  776. // Do any driver callbacks belonging to the unfinished
  777. // transfers. This is done last, after retoring the
  778. // pipe to a working state (if possible) so the driver
  779. // callback can use the pipe.
  780. p = first;
  781. while (p) {
  782. uint32_t token = p->qtd.token;
  783. if (token & 0x8000 && haltedpipe->callback_function) {
  784. // driver expects a callback
  785. p->qtd.token = token | 0x40;
  786. (*(p->pipe->callback_function))(p);
  787. }
  788. Transfer_t *next2 = p->next_followup;
  789. free_Transfer(p);
  790. p = next2;
  791. }
  792. } else {
  793. free_Transfer(p);
  794. }
  795. p = next;
  796. } else {
  797. // transfer still pending
  798. println(" remain on followup list");
  799. p = p->next_followup;
  800. }
  801. }
  802. // TODO: handle errors from periodic schedule!
  803. }
  804. static void add_to_async_followup_list(Transfer_t *first, Transfer_t *last)
  805. {
  806. last->next_followup = NULL; // always add to end of list
  807. if (async_followup_last == NULL) {
  808. first->prev_followup = NULL;
  809. async_followup_first = first;
  810. } else {
  811. first->prev_followup = async_followup_last;
  812. async_followup_last->next_followup = first;
  813. }
  814. async_followup_last = last;
  815. }
  816. static void remove_from_async_followup_list(Transfer_t *transfer)
  817. {
  818. Transfer_t *next = transfer->next_followup;
  819. Transfer_t *prev = transfer->prev_followup;
  820. if (prev) {
  821. prev->next_followup = next;
  822. } else {
  823. async_followup_first = next;
  824. }
  825. if (next) {
  826. next->prev_followup = prev;
  827. } else {
  828. async_followup_last = prev;
  829. }
  830. }
  831. static void add_to_periodic_followup_list(Transfer_t *first, Transfer_t *last)
  832. {
  833. last->next_followup = NULL; // always add to end of list
  834. if (periodic_followup_last == NULL) {
  835. first->prev_followup = NULL;
  836. periodic_followup_first = first;
  837. } else {
  838. first->prev_followup = periodic_followup_last;
  839. periodic_followup_last->next_followup = first;
  840. }
  841. periodic_followup_last = last;
  842. }
  843. static void remove_from_periodic_followup_list(Transfer_t *transfer)
  844. {
  845. Transfer_t *next = transfer->next_followup;
  846. Transfer_t *prev = transfer->prev_followup;
  847. if (prev) {
  848. prev->next_followup = next;
  849. } else {
  850. periodic_followup_first = next;
  851. }
  852. if (next) {
  853. next->prev_followup = prev;
  854. } else {
  855. periodic_followup_last = prev;
  856. }
  857. }
  858. static uint32_t max4(uint32_t n1, uint32_t n2, uint32_t n3, uint32_t n4)
  859. {
  860. if (n1 > n2) {
  861. // can't be n2
  862. if (n1 > n3) {
  863. // can't be n3
  864. if (n1 > n4) return n1;
  865. } else {
  866. // can't be n1
  867. if (n3 > n4) return n3;
  868. }
  869. } else {
  870. // can't be n1
  871. if (n2 > n3) {
  872. // can't be n3
  873. if (n2 > n4) return n2;
  874. } else {
  875. // can't be n2
  876. if (n3 > n4) return n3;
  877. }
  878. }
  879. return n4;
  880. }
  881. static uint32_t round_to_power_of_two(uint32_t n, uint32_t maxnum)
  882. {
  883. for (uint32_t pow2num=1; pow2num < maxnum; pow2num <<= 1) {
  884. if (n <= (pow2num | (pow2num >> 1))) return pow2num;
  885. }
  886. return maxnum;
  887. }
  888. // Allocate bandwidth for an interrupt pipe. Given the packet size
  889. // and other parameters, find the best place to schedule this pipe.
  890. // Returns true if enough bandwidth is available, and the best
  891. // frame offset, smask and cmask. Or returns false if no group
  892. // of microframes has enough bandwidth available.
  893. //
  894. // pipe:
  895. // device->speed [in] 0=full speed, 1=low speed, 2=high speed
  896. // direction [in] 0=OUT, 1=IN
  897. // start_mask [out] uframes to start transfer
  898. // complete_mask [out] uframes to complete transfer (FS & LS only)
  899. // periodic_interval [out] fream repeat level: 1, 2, 4, 8... PERIODIC_LIST_SIZE
  900. // periodic_offset [out] frame repeat offset: 0 to periodic_interval-1
  901. // maxlen: [in] maximum packet length
  902. // interval: [in] polling interval: LS+FS: frames, HS: 2^(n-1) uframes
  903. //
  904. bool USBHost::allocate_interrupt_pipe_bandwidth(Pipe_t *pipe, uint32_t maxlen, uint32_t interval)
  905. {
  906. println("allocate_interrupt_pipe_bandwidth");
  907. if (interval == 0) interval = 1;
  908. maxlen = (maxlen * 76459) >> 16; // worst case bit stuffing
  909. if (pipe->device->speed == 2) {
  910. // high speed 480 Mbit/sec
  911. println(" ep interval = ", interval);
  912. if (interval > 15) interval = 15;
  913. interval = 1 << (interval - 1);
  914. if (interval > PERIODIC_LIST_SIZE*8) interval = PERIODIC_LIST_SIZE*8;
  915. println(" interval = ", interval);
  916. uint32_t pinterval = interval >> 3;
  917. pipe->periodic_interval = (pinterval > 0) ? pinterval : 1;
  918. uint32_t stime = (55 + 32 + maxlen) >> 5; // time units: 32 bytes or 533 ns
  919. uint32_t best_offset = 0xFFFFFFFF;
  920. uint32_t best_bandwidth = 0xFFFFFFFF;
  921. for (uint32_t offset=0; offset < interval; offset++) {
  922. // for each possible uframe offset, find the worst uframe bandwidth
  923. uint32_t max_bandwidth = 0;
  924. for (uint32_t i=offset; i < PERIODIC_LIST_SIZE*8; i += interval) {
  925. uint32_t bandwidth = uframe_bandwidth[i] + stime;
  926. if (bandwidth > max_bandwidth) max_bandwidth = bandwidth;
  927. }
  928. // remember which uframe offset is the best
  929. if (max_bandwidth < best_bandwidth) {
  930. best_bandwidth = max_bandwidth;
  931. best_offset = offset;
  932. }
  933. }
  934. print(" best_bandwidth = ");
  935. print(best_bandwidth);
  936. print(", at offset = ");
  937. println(best_offset);
  938. // a 125 us micro frame can fit 7500 bytes, or 234 of our 32-byte units
  939. // fail if the best found needs more than 80% (234 * 0.8) in any uframe
  940. if (best_bandwidth > 187) return false;
  941. for (uint32_t i=best_offset; i < PERIODIC_LIST_SIZE*8; i += interval) {
  942. uframe_bandwidth[i] += stime;
  943. }
  944. if (interval == 1) {
  945. pipe->start_mask = 0xFF;
  946. } else if (interval == 2) {
  947. pipe->start_mask = 0x55 << (best_offset & 1);
  948. } else if (interval <= 4) {
  949. pipe->start_mask = 0x11 << (best_offset & 3);
  950. } else {
  951. pipe->start_mask = 0x01 << (best_offset & 7);
  952. }
  953. pipe->periodic_offset = best_offset >> 3;
  954. pipe->complete_mask = 0;
  955. } else {
  956. // full speed 12 Mbit/sec or low speed 1.5 Mbit/sec
  957. interval = round_to_power_of_two(interval, PERIODIC_LIST_SIZE);
  958. pipe->periodic_interval = interval;
  959. uint32_t stime, ctime;
  960. if (pipe->direction == 0) {
  961. // for OUT direction, SSPLIT will carry the data payload
  962. // TODO: how much time to SSPLIT & CSPLIT actually take?
  963. // they're not documented in 5.7 or 5.11.3.
  964. stime = (100 + 32 + maxlen) >> 5;
  965. ctime = (55 + 32) >> 5;
  966. } else {
  967. // for IN direction, data payload in CSPLIT
  968. stime = (40 + 32) >> 5;
  969. ctime = (70 + 32 + maxlen) >> 5;
  970. }
  971. // TODO: should we take Single-TT hubs into account, avoid
  972. // scheduling overlapping SSPLIT & CSPLIT to the same hub?
  973. // TODO: even if Multi-TT, do we need to worry about packing
  974. // too many into the same uframe?
  975. uint32_t best_shift = 0;
  976. uint32_t best_offset = 0xFFFFFFFF;
  977. uint32_t best_bandwidth = 0xFFFFFFFF;
  978. for (uint32_t offset=0; offset < interval; offset++) {
  979. // for each 1ms frame offset, compute the worst uframe usage
  980. uint32_t max_bandwidth = 0;
  981. for (uint32_t i=offset; i < PERIODIC_LIST_SIZE; i += interval) {
  982. for (uint32_t j=0; j <= 3; j++) { // max 3 without FSTN
  983. // at each location, find worst uframe usage
  984. // for SSPLIT+CSPLITs
  985. uint32_t n = (i << 3) + j;
  986. uint32_t bw1 = uframe_bandwidth[n+0] + stime;
  987. uint32_t bw2 = uframe_bandwidth[n+2] + ctime;
  988. uint32_t bw3 = uframe_bandwidth[n+3] + ctime;
  989. uint32_t bw4 = uframe_bandwidth[n+4] + ctime;
  990. max_bandwidth = max4(bw1, bw2, bw3, bw4);
  991. // remember the best usage found
  992. if (max_bandwidth < best_bandwidth) {
  993. best_bandwidth = max_bandwidth;
  994. best_offset = i;
  995. best_shift = j;
  996. }
  997. }
  998. }
  999. }
  1000. print(" best_bandwidth = ");
  1001. println(best_bandwidth);
  1002. print(", at offset = ");
  1003. print(best_offset);
  1004. print(", shift= ");
  1005. println(best_shift);
  1006. // a 125 us micro frame can fit 7500 bytes, or 234 of our 32-byte units
  1007. // fail if the best found needs more than 80% (234 * 0.8) in any uframe
  1008. if (best_bandwidth > 187) return false;
  1009. for (uint32_t i=best_offset; i < PERIODIC_LIST_SIZE; i += interval) {
  1010. uint32_t n = (i << 3) + best_shift;
  1011. uframe_bandwidth[n+0] += stime;
  1012. uframe_bandwidth[n+2] += ctime;
  1013. uframe_bandwidth[n+3] += ctime;
  1014. uframe_bandwidth[n+4] += ctime;
  1015. }
  1016. pipe->start_mask = 0x01 << best_shift;
  1017. pipe->complete_mask = 0x1C << best_shift;
  1018. pipe->periodic_offset = best_offset;
  1019. }
  1020. return true;
  1021. }
  1022. // put a new pipe into the periodic schedule tree
  1023. // according to periodic_interval and periodic_offset
  1024. //
  1025. void USBHost::add_qh_to_periodic_schedule(Pipe_t *pipe)
  1026. {
  1027. // quick hack for testing, just put it into the first table entry
  1028. println("add_qh_to_periodic_schedule: ", (uint32_t)pipe, HEX);
  1029. #if 0
  1030. pipe->qh.horizontal_link = periodictable[0];
  1031. periodictable[0] = (uint32_t)&(pipe->qh) | 2; // 2=QH
  1032. println("init periodictable with ", periodictable[0], HEX);
  1033. #else
  1034. uint32_t interval = pipe->periodic_interval;
  1035. uint32_t offset = pipe->periodic_offset;
  1036. println(" interval = ", interval);
  1037. println(" offset = ", offset);
  1038. // By an interative miracle, hopefully make an inverted tree of EHCI figure 4-18, page 93
  1039. for (uint32_t i=offset; i < PERIODIC_LIST_SIZE; i += interval) {
  1040. print(" old slot ", i);
  1041. print(": ");
  1042. print_qh_list((Pipe_t *)(periodictable[i] & 0xFFFFFFE0));
  1043. uint32_t num = periodictable[i];
  1044. Pipe_t *node = (Pipe_t *)(num & 0xFFFFFFE0);
  1045. if ((num & 1) || ((num & 6) == 2 && node->periodic_interval < interval)) {
  1046. println(" add to slot ", i);
  1047. pipe->qh.horizontal_link = num;
  1048. periodictable[i] = (uint32_t)&(pipe->qh) | 2; // 2=QH
  1049. } else {
  1050. println(" traverse list ", i);
  1051. // TODO: skip past iTD, siTD when/if we support isochronous
  1052. while (node->periodic_interval >= interval) {
  1053. if (node == pipe) goto nextslot;
  1054. print(" num ", num, HEX);
  1055. print(" node ", (uint32_t)node, HEX);
  1056. println("->", node->qh.horizontal_link, HEX);
  1057. if (node->qh.horizontal_link & 1) break;
  1058. num = node->qh.horizontal_link;
  1059. node = (Pipe_t *)(num & 0xFFFFFFE0);
  1060. }
  1061. Pipe_t *n = node;
  1062. do {
  1063. if (n == pipe) goto nextslot;
  1064. n = (Pipe_t *)(n->qh.horizontal_link & 0xFFFFFFE0);
  1065. } while (n != NULL);
  1066. print(" adding at node ", (uint32_t)node, HEX);
  1067. print(", num=", num, HEX);
  1068. println(", node->qh.horizontal_link=", node->qh.horizontal_link, HEX);
  1069. pipe->qh.horizontal_link = node->qh.horizontal_link;
  1070. node->qh.horizontal_link = (uint32_t)pipe | 2; // 2=QH
  1071. // TODO: is it really necessary to keep doing the outer
  1072. // loop? Does adding it here satisfy all cases? If so
  1073. // we could avoid extra work by just returning here.
  1074. }
  1075. nextslot:
  1076. print(" new slot ", i);
  1077. print(": ");
  1078. print_qh_list((Pipe_t *)(periodictable[i] & 0xFFFFFFE0));
  1079. }
  1080. #endif
  1081. #if 1
  1082. println("Periodic Schedule:");
  1083. for (uint32_t i=0; i < PERIODIC_LIST_SIZE; i++) {
  1084. if (i < 10) print(" ");
  1085. print(i);
  1086. print(": ");
  1087. print_qh_list((Pipe_t *)(periodictable[i] & 0xFFFFFFE0));
  1088. }
  1089. #endif
  1090. }
  1091. void USBHost::delete_Pipe(Pipe_t *pipe)
  1092. {
  1093. println("delete_Pipe ", (uint32_t)pipe, HEX);
  1094. // halt pipe, find and free all Transfer_t
  1095. // EHCI 1.0, 4.8.2 page 72: "Software should first deactivate
  1096. // all active qTDs, wait for the queue head to go inactive"
  1097. //
  1098. // http://www.spinics.net/lists/linux-usb/msg131607.html
  1099. // http://www.spinics.net/lists/linux-usb/msg131936.html
  1100. //
  1101. // In practice it's not feasible to wait for an active QH to become
  1102. // inactive before removing it, for several reasons. For one, the QH may
  1103. // _never_ become inactive (if the endpoint NAKs indefinitely). For
  1104. // another, the procedure given in the spec (deactivate the qTDs on the
  1105. // queue) is racy, since the controller can perform a new overlay or
  1106. // writeback at any time.
  1107. bool isasync = (pipe->type == 0 || pipe->type == 2);
  1108. if (isasync) {
  1109. // find the next QH in the async schedule loop
  1110. Pipe_t *next = (Pipe_t *)(pipe->qh.horizontal_link & 0xFFFFFFE0);
  1111. if (next == pipe) {
  1112. // removing the only QH, so just shut down the async schedule
  1113. println(" shut down async schedule");
  1114. USBHS_USBCMD &= ~USBHS_USBCMD_ASE; // disable async schedule
  1115. while (USBHS_USBSTS & USBHS_USBSTS_AS) ; // busy loop wait
  1116. USBHS_ASYNCLISTADDR = 0;
  1117. } else {
  1118. // find the previous QH in the async schedule loop
  1119. println(" remove QH from async schedule");
  1120. Pipe_t *prev = next;
  1121. while (1) {
  1122. Pipe_t *n = (Pipe_t *)(prev->qh.horizontal_link & 0xFFFFFFE0);
  1123. if (n == pipe) break;
  1124. prev = n;
  1125. }
  1126. // if removing the one with H bit, set another
  1127. if (pipe->qh.capabilities[0] & 0x8000) {
  1128. prev->qh.capabilities[0] |= 0x8000; // set H bit
  1129. }
  1130. // link the previous QH, we're no longer in the loop
  1131. prev->qh.horizontal_link = pipe->qh.horizontal_link;
  1132. // do the Async Advance Doorbell handshake to wait to be
  1133. // sure the EHCI no longer references the removed QH
  1134. USBHS_USBCMD |= USBHS_USBCMD_IAA;
  1135. while (!(USBHS_USBSTS & USBHS_USBSTS_AAI)) ; // busy loop wait
  1136. USBHS_USBSTS = USBHS_USBSTS_AAI;
  1137. // TODO: does this write interfere UPI & UAI (bits 18 & 19) ??
  1138. }
  1139. // find & free all the transfers which completed
  1140. Transfer_t *t = async_followup_first;
  1141. while (t) {
  1142. Transfer_t *next = t->next_followup;
  1143. if (t->pipe == pipe) {
  1144. remove_from_async_followup_list(t);
  1145. free_Transfer(t);
  1146. }
  1147. t = next;
  1148. }
  1149. } else {
  1150. // remove from the periodic schedule
  1151. for (uint32_t i=0; i < PERIODIC_LIST_SIZE; i++) {
  1152. uint32_t num = periodictable[i];
  1153. if (num & 1) continue;
  1154. Pipe_t *node = (Pipe_t *)(num & 0xFFFFFFE0);
  1155. if (node == pipe) {
  1156. periodictable[i] = pipe->qh.horizontal_link;
  1157. continue;
  1158. }
  1159. Pipe_t *prev = node;
  1160. while (1) {
  1161. num = node->qh.horizontal_link;
  1162. if (num & 1) break;
  1163. node = (Pipe_t *)(num & 0xFFFFFFE0);
  1164. if (node == pipe) {
  1165. prev->qh.horizontal_link = node->qh.horizontal_link;
  1166. break;
  1167. }
  1168. prev = node;
  1169. }
  1170. }
  1171. // TODO: subtract bandwidth from uframe_bandwidth array
  1172. // find & free all the transfers which completed
  1173. Transfer_t *t = periodic_followup_first;
  1174. while (t) {
  1175. Transfer_t *next = t->next_followup;
  1176. if (t->pipe == pipe) {
  1177. remove_from_periodic_followup_list(t);
  1178. free_Transfer(t);
  1179. }
  1180. t = next;
  1181. }
  1182. }
  1183. //
  1184. // TODO: do we need to look at pipe->qh.current ??
  1185. //
  1186. // free all the transfers still attached to the QH
  1187. Transfer_t *tr = (Transfer_t *)(pipe->qh.next);
  1188. while ((uint32_t)tr & 0xFFFFFFE0) {
  1189. Transfer_t *next = (Transfer_t *)(tr->qtd.next);
  1190. free_Transfer(tr);
  1191. tr = next;
  1192. }
  1193. // hopefully we found everything...
  1194. free_Pipe(pipe);
  1195. }