選択できるのは25トピックまでです。 トピックは、先頭が英数字で、英数字とダッシュ('-')を使用した35文字以内のものにしてください。

1426 行
47KB

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