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

1428 行
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. //USBHDBGSerial.print("remain = ");
  434. //USBHDBGSerial.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. if (len) {
  691. for (count=((len-1) >> 14); count; count--) {
  692. next = allocate_Transfer();
  693. if (!next) {
  694. // free already-allocated qTDs
  695. while (1) {
  696. next = (Transfer_t *)transfer->qtd.next;
  697. free_Transfer(transfer);
  698. if (transfer == data) break;
  699. transfer = next;
  700. }
  701. return false;
  702. }
  703. data->qtd.next = (uint32_t)next;
  704. data = next;
  705. }
  706. }
  707. // last qTD needs info for followup
  708. data->qtd.next = 1;
  709. data->pipe = pipe;
  710. data->buffer = buffer;
  711. data->length = len;
  712. data->setup.word1 = 0;
  713. data->setup.word2 = 0;
  714. data->driver = driver;
  715. // initialize all qTDs
  716. data = transfer;
  717. while (1) {
  718. uint32_t count = len;
  719. if (count > 16384) {
  720. count = 16384;
  721. } else {
  722. last = true;
  723. }
  724. init_qTD(data, p, count, pipe->direction, 0, last);
  725. if (last) break;
  726. p += count;
  727. len -= count;
  728. data = (Transfer_t *)(data->qtd.next);
  729. }
  730. return queue_Transfer(pipe, transfer);
  731. }
  732. bool USBHost::queue_Transfer(Pipe_t *pipe, Transfer_t *transfer)
  733. {
  734. // find halt qTD
  735. Transfer_t *halt = (Transfer_t *)(pipe->qh.next);
  736. while (!(halt->qtd.token & 0x40)) halt = (Transfer_t *)(halt->qtd.next);
  737. // transfer's token
  738. uint32_t token = transfer->qtd.token;
  739. // transfer becomes new halt qTD
  740. transfer->qtd.token = 0x40;
  741. // copy transfer non-token fields to halt
  742. halt->qtd.next = transfer->qtd.next;
  743. halt->qtd.alt_next = transfer->qtd.alt_next;
  744. halt->qtd.buffer[0] = transfer->qtd.buffer[0]; // TODO: optimize memcpy, all
  745. halt->qtd.buffer[1] = transfer->qtd.buffer[1]; // fields except token
  746. halt->qtd.buffer[2] = transfer->qtd.buffer[2];
  747. halt->qtd.buffer[3] = transfer->qtd.buffer[3];
  748. halt->qtd.buffer[4] = transfer->qtd.buffer[4];
  749. halt->pipe = pipe;
  750. halt->buffer = transfer->buffer;
  751. halt->length = transfer->length;
  752. halt->setup = transfer->setup;
  753. halt->driver = transfer->driver;
  754. // find the last qTD we're adding
  755. Transfer_t *last = halt;
  756. while ((uint32_t)(last->qtd.next) != 1) last = (Transfer_t *)(last->qtd.next);
  757. // last points to transfer (which becomes new halt)
  758. last->qtd.next = (uint32_t)transfer;
  759. transfer->qtd.next = 1;
  760. // link all the new qTD by next_followup & prev_followup
  761. Transfer_t *prev = NULL;
  762. Transfer_t *p = halt;
  763. while (p->qtd.next != (uint32_t)transfer) {
  764. Transfer_t *next = (Transfer_t *)p->qtd.next;
  765. p->prev_followup = prev;
  766. p->next_followup = next;
  767. prev = p;
  768. p = next;
  769. }
  770. p->prev_followup = prev;
  771. p->next_followup = NULL;
  772. //print(halt, p);
  773. // add them to a followup list
  774. if (pipe->type == 0 || pipe->type == 2) {
  775. // control or bulk
  776. add_to_async_followup_list(halt, p);
  777. } else {
  778. // interrupt
  779. add_to_periodic_followup_list(halt, p);
  780. }
  781. // old halt becomes new transfer, this commits all new qTDs to QH
  782. halt->qtd.token = token;
  783. return true;
  784. }
  785. bool USBHost::followup_Transfer(Transfer_t *transfer)
  786. {
  787. //print(" Followup ", (uint32_t)transfer, HEX);
  788. //println(" token=", transfer->qtd.token, HEX);
  789. if (!(transfer->qtd.token & 0x80)) {
  790. // TODO: check error status
  791. if (transfer->qtd.token & 0x8000) {
  792. // this transfer caused an interrupt
  793. if (transfer->pipe->callback_function) {
  794. // do the callback
  795. (*(transfer->pipe->callback_function))(transfer);
  796. }
  797. }
  798. // do callback function...
  799. //println(" completed");
  800. return true;
  801. }
  802. return false;
  803. }
  804. void USBHost::followup_Error(void)
  805. {
  806. println("ERROR Followup");
  807. Transfer_t *p = async_followup_first;
  808. while (p) {
  809. if (followup_Transfer(p)) {
  810. // transfer completed
  811. Transfer_t *next = p->next_followup;
  812. remove_from_async_followup_list(p);
  813. println(" remove from followup list");
  814. if (p->qtd.token & 0x40) {
  815. Pipe_t *haltedpipe = p->pipe;
  816. free_Transfer(p);
  817. // traverse the rest of the list for unfinished work
  818. // from this halted pipe. Remove from the followup
  819. // list and put onto our own temporary list
  820. Transfer_t *first = NULL;
  821. Transfer_t *last = NULL;
  822. p = next;
  823. while (p) {
  824. Transfer_t *next2 = p->next_followup;
  825. if (p->pipe == haltedpipe) {
  826. println(" stray halted ", (uint32_t)p, HEX);
  827. remove_from_async_followup_list(p);
  828. if (first == NULL) {
  829. first = p;
  830. last = p;
  831. } else {
  832. last->next_followup = p;
  833. }
  834. p->next_followup = NULL;
  835. if (next == p) next = next2;
  836. }
  837. p = next2;
  838. }
  839. // halted pipe (probably) still has unfinished transfers
  840. // find the halted pipe's dummy halt transfer
  841. p = (Transfer_t *)(haltedpipe->qh.next & ~0x1F);
  842. while (p && ((p->qtd.token & 0x40) == 0)) {
  843. print(" qtd: ", (uint32_t)p, HEX);
  844. print(", token=", (uint32_t)p->qtd.token, HEX);
  845. println(", next=", (uint32_t)p->qtd.next, HEX);
  846. p = (Transfer_t *)(p->qtd.next & ~0x1F);
  847. }
  848. if (p) {
  849. // unhalt the pipe, "forget" unfinished transfers
  850. // hopefully they're all on the list we made!
  851. println(" dummy halt: ", (uint32_t)p, HEX);
  852. haltedpipe->qh.next = (uint32_t)p;
  853. haltedpipe->qh.current = 0;
  854. haltedpipe->qh.token = 0;
  855. } else {
  856. println(" no dummy halt found, yikes!");
  857. // TODO: this should never happen, but what if it does?
  858. }
  859. // Do any driver callbacks belonging to the unfinished
  860. // transfers. This is done last, after retoring the
  861. // pipe to a working state (if possible) so the driver
  862. // callback can use the pipe.
  863. p = first;
  864. while (p) {
  865. uint32_t token = p->qtd.token;
  866. if (token & 0x8000 && haltedpipe->callback_function) {
  867. // driver expects a callback
  868. p->qtd.token = token | 0x40;
  869. (*(p->pipe->callback_function))(p);
  870. }
  871. Transfer_t *next2 = p->next_followup;
  872. free_Transfer(p);
  873. p = next2;
  874. }
  875. } else {
  876. free_Transfer(p);
  877. }
  878. p = next;
  879. } else {
  880. // transfer still pending
  881. println(" remain on followup list");
  882. p = p->next_followup;
  883. }
  884. }
  885. // TODO: handle errors from periodic schedule!
  886. }
  887. static void add_to_async_followup_list(Transfer_t *first, Transfer_t *last)
  888. {
  889. last->next_followup = NULL; // always add to end of list
  890. if (async_followup_last == NULL) {
  891. first->prev_followup = NULL;
  892. async_followup_first = first;
  893. } else {
  894. first->prev_followup = async_followup_last;
  895. async_followup_last->next_followup = first;
  896. }
  897. async_followup_last = last;
  898. }
  899. static void remove_from_async_followup_list(Transfer_t *transfer)
  900. {
  901. Transfer_t *next = transfer->next_followup;
  902. Transfer_t *prev = transfer->prev_followup;
  903. if (prev) {
  904. prev->next_followup = next;
  905. } else {
  906. async_followup_first = next;
  907. }
  908. if (next) {
  909. next->prev_followup = prev;
  910. } else {
  911. async_followup_last = prev;
  912. }
  913. }
  914. static void add_to_periodic_followup_list(Transfer_t *first, Transfer_t *last)
  915. {
  916. last->next_followup = NULL; // always add to end of list
  917. if (periodic_followup_last == NULL) {
  918. first->prev_followup = NULL;
  919. periodic_followup_first = first;
  920. } else {
  921. first->prev_followup = periodic_followup_last;
  922. periodic_followup_last->next_followup = first;
  923. }
  924. periodic_followup_last = last;
  925. }
  926. static void remove_from_periodic_followup_list(Transfer_t *transfer)
  927. {
  928. Transfer_t *next = transfer->next_followup;
  929. Transfer_t *prev = transfer->prev_followup;
  930. if (prev) {
  931. prev->next_followup = next;
  932. } else {
  933. periodic_followup_first = next;
  934. }
  935. if (next) {
  936. next->prev_followup = prev;
  937. } else {
  938. periodic_followup_last = prev;
  939. }
  940. }
  941. static uint32_t max4(uint32_t n1, uint32_t n2, uint32_t n3, uint32_t n4)
  942. {
  943. if (n1 > n2) {
  944. // can't be n2
  945. if (n1 > n3) {
  946. // can't be n3
  947. if (n1 > n4) return n1;
  948. } else {
  949. // can't be n1
  950. if (n3 > n4) return n3;
  951. }
  952. } else {
  953. // can't be n1
  954. if (n2 > n3) {
  955. // can't be n3
  956. if (n2 > n4) return n2;
  957. } else {
  958. // can't be n2
  959. if (n3 > n4) return n3;
  960. }
  961. }
  962. return n4;
  963. }
  964. static uint32_t round_to_power_of_two(uint32_t n, uint32_t maxnum)
  965. {
  966. for (uint32_t pow2num=1; pow2num < maxnum; pow2num <<= 1) {
  967. if (n <= (pow2num | (pow2num >> 1))) return pow2num;
  968. }
  969. return maxnum;
  970. }
  971. // Allocate bandwidth for an interrupt pipe. Given the packet size
  972. // and other parameters, find the best place to schedule this pipe.
  973. // Returns true if enough bandwidth is available, and the best
  974. // frame offset, smask and cmask. Or returns false if no group
  975. // of microframes has enough bandwidth available.
  976. //
  977. // pipe:
  978. // device->speed [in] 0=full speed, 1=low speed, 2=high speed
  979. // direction [in] 0=OUT, 1=IN
  980. // start_mask [out] uframes to start transfer
  981. // complete_mask [out] uframes to complete transfer (FS & LS only)
  982. // periodic_interval [out] fream repeat level: 1, 2, 4, 8... PERIODIC_LIST_SIZE
  983. // periodic_offset [out] frame repeat offset: 0 to periodic_interval-1
  984. // maxlen: [in] maximum packet length
  985. // interval: [in] polling interval: LS+FS: frames, HS: 2^(n-1) uframes
  986. //
  987. bool USBHost::allocate_interrupt_pipe_bandwidth(Pipe_t *pipe, uint32_t maxlen, uint32_t interval)
  988. {
  989. println("allocate_interrupt_pipe_bandwidth");
  990. if (interval == 0) interval = 1;
  991. maxlen = (maxlen * 76459) >> 16; // worst case bit stuffing
  992. if (pipe->device->speed == 2) {
  993. // high speed 480 Mbit/sec
  994. println(" ep interval = ", interval);
  995. if (interval > 15) interval = 15;
  996. interval = 1 << (interval - 1);
  997. if (interval > PERIODIC_LIST_SIZE*8) interval = PERIODIC_LIST_SIZE*8;
  998. println(" interval = ", interval);
  999. uint32_t pinterval = interval >> 3;
  1000. pipe->periodic_interval = (pinterval > 0) ? pinterval : 1;
  1001. uint32_t stime = (55 + 32 + maxlen) >> 5; // time units: 32 bytes or 533 ns
  1002. uint32_t best_offset = 0xFFFFFFFF;
  1003. uint32_t best_bandwidth = 0xFFFFFFFF;
  1004. for (uint32_t offset=0; offset < interval; offset++) {
  1005. // for each possible uframe offset, find the worst uframe bandwidth
  1006. uint32_t max_bandwidth = 0;
  1007. for (uint32_t i=offset; i < PERIODIC_LIST_SIZE*8; i += interval) {
  1008. uint32_t bandwidth = uframe_bandwidth[i] + stime;
  1009. if (bandwidth > max_bandwidth) max_bandwidth = bandwidth;
  1010. }
  1011. // remember which uframe offset is the best
  1012. if (max_bandwidth < best_bandwidth) {
  1013. best_bandwidth = max_bandwidth;
  1014. best_offset = offset;
  1015. }
  1016. }
  1017. print(" best_bandwidth = ", best_bandwidth);
  1018. //print(best_bandwidth);
  1019. println(", at offset = ", best_offset);
  1020. //println(best_offset);
  1021. // a 125 us micro frame can fit 7500 bytes, or 234 of our 32-byte units
  1022. // fail if the best found needs more than 80% (234 * 0.8) in any uframe
  1023. if (best_bandwidth > 187) return false;
  1024. // save essential bandwidth specs, for cleanup in delete_Pipe
  1025. pipe->bandwidth_interval = interval;
  1026. pipe->bandwidth_offset = best_offset;
  1027. pipe->bandwidth_stime = stime;
  1028. for (uint32_t i=best_offset; i < PERIODIC_LIST_SIZE*8; i += interval) {
  1029. uframe_bandwidth[i] += stime;
  1030. }
  1031. if (interval == 1) {
  1032. pipe->start_mask = 0xFF;
  1033. } else if (interval == 2) {
  1034. pipe->start_mask = 0x55 << (best_offset & 1);
  1035. } else if (interval <= 4) {
  1036. pipe->start_mask = 0x11 << (best_offset & 3);
  1037. } else {
  1038. pipe->start_mask = 0x01 << (best_offset & 7);
  1039. }
  1040. pipe->periodic_offset = best_offset >> 3;
  1041. pipe->complete_mask = 0;
  1042. } else {
  1043. // full speed 12 Mbit/sec or low speed 1.5 Mbit/sec
  1044. interval = round_to_power_of_two(interval, PERIODIC_LIST_SIZE);
  1045. pipe->periodic_interval = interval;
  1046. uint32_t stime, ctime;
  1047. if (pipe->direction == 0) {
  1048. // for OUT direction, SSPLIT will carry the data payload
  1049. // TODO: how much time to SSPLIT & CSPLIT actually take?
  1050. // they're not documented in 5.7 or 5.11.3.
  1051. stime = (100 + 32 + maxlen) >> 5;
  1052. ctime = (55 + 32) >> 5;
  1053. } else {
  1054. // for IN direction, data payload in CSPLIT
  1055. stime = (40 + 32) >> 5;
  1056. ctime = (70 + 32 + maxlen) >> 5;
  1057. }
  1058. // TODO: should we take Single-TT hubs into account, avoid
  1059. // scheduling overlapping SSPLIT & CSPLIT to the same hub?
  1060. // TODO: even if Multi-TT, do we need to worry about packing
  1061. // too many into the same uframe?
  1062. uint32_t best_shift = 0;
  1063. uint32_t best_offset = 0xFFFFFFFF;
  1064. uint32_t best_bandwidth = 0xFFFFFFFF;
  1065. for (uint32_t offset=0; offset < interval; offset++) {
  1066. // for each 1ms frame offset, compute the worst uframe usage
  1067. uint32_t max_bandwidth = 0;
  1068. for (uint32_t i=offset; i < PERIODIC_LIST_SIZE; i += interval) {
  1069. for (uint32_t j=0; j <= 3; j++) { // max 3 without FSTN
  1070. // at each location, find worst uframe usage
  1071. // for SSPLIT+CSPLITs
  1072. uint32_t n = (i << 3) + j;
  1073. uint32_t bw1 = uframe_bandwidth[n+0] + stime;
  1074. uint32_t bw2 = uframe_bandwidth[n+2] + ctime;
  1075. uint32_t bw3 = uframe_bandwidth[n+3] + ctime;
  1076. uint32_t bw4 = uframe_bandwidth[n+4] + ctime;
  1077. max_bandwidth = max4(bw1, bw2, bw3, bw4);
  1078. // remember the best usage found
  1079. if (max_bandwidth < best_bandwidth) {
  1080. best_bandwidth = max_bandwidth;
  1081. best_offset = i;
  1082. best_shift = j;
  1083. }
  1084. }
  1085. }
  1086. }
  1087. print(" best_bandwidth = ", best_bandwidth);
  1088. //println(best_bandwidth);
  1089. print(", at offset = ", best_offset);
  1090. //print(best_offset);
  1091. println(", shift= ", best_shift);
  1092. //println(best_shift);
  1093. // a 125 us micro frame can fit 7500 bytes, or 234 of our 32-byte units
  1094. // fail if the best found needs more than 80% (234 * 0.8) in any uframe
  1095. if (best_bandwidth > 187) return false;
  1096. // save essential bandwidth specs, for cleanup in delete_Pipe
  1097. pipe->bandwidth_interval = interval;
  1098. pipe->bandwidth_offset = best_offset;
  1099. pipe->bandwidth_shift = best_shift;
  1100. pipe->bandwidth_stime = stime;
  1101. pipe->bandwidth_ctime = ctime;
  1102. for (uint32_t i=best_offset; i < PERIODIC_LIST_SIZE; i += interval) {
  1103. uint32_t n = (i << 3) + best_shift;
  1104. uframe_bandwidth[n+0] += stime;
  1105. uframe_bandwidth[n+2] += ctime;
  1106. uframe_bandwidth[n+3] += ctime;
  1107. uframe_bandwidth[n+4] += ctime;
  1108. }
  1109. pipe->start_mask = 0x01 << best_shift;
  1110. pipe->complete_mask = 0x1C << best_shift;
  1111. pipe->periodic_offset = best_offset;
  1112. }
  1113. return true;
  1114. }
  1115. // put a new pipe into the periodic schedule tree
  1116. // according to periodic_interval and periodic_offset
  1117. //
  1118. void USBHost::add_qh_to_periodic_schedule(Pipe_t *pipe)
  1119. {
  1120. // quick hack for testing, just put it into the first table entry
  1121. //println("add_qh_to_periodic_schedule: ", (uint32_t)pipe, HEX);
  1122. #if 0
  1123. pipe->qh.horizontal_link = periodictable[0];
  1124. periodictable[0] = (uint32_t)&(pipe->qh) | 2; // 2=QH
  1125. println("init periodictable with ", periodictable[0], HEX);
  1126. #else
  1127. uint32_t interval = pipe->periodic_interval;
  1128. uint32_t offset = pipe->periodic_offset;
  1129. //println(" interval = ", interval);
  1130. //println(" offset = ", offset);
  1131. // By an interative miracle, hopefully make an inverted tree of EHCI figure 4-18, page 93
  1132. for (uint32_t i=offset; i < PERIODIC_LIST_SIZE; i += interval) {
  1133. //print(" old slot ", i);
  1134. //print(": ");
  1135. //print_qh_list((Pipe_t *)(periodictable[i] & 0xFFFFFFE0));
  1136. uint32_t num = periodictable[i];
  1137. Pipe_t *node = (Pipe_t *)(num & 0xFFFFFFE0);
  1138. if ((num & 1) || ((num & 6) == 2 && node->periodic_interval < interval)) {
  1139. //println(" add to slot ", i);
  1140. pipe->qh.horizontal_link = num;
  1141. periodictable[i] = (uint32_t)&(pipe->qh) | 2; // 2=QH
  1142. } else {
  1143. //println(" traverse list ", i);
  1144. // TODO: skip past iTD, siTD when/if we support isochronous
  1145. while (node->periodic_interval >= interval) {
  1146. if (node == pipe) goto nextslot;
  1147. //print(" num ", num, HEX);
  1148. //print(" node ", (uint32_t)node, HEX);
  1149. //println("->", node->qh.horizontal_link, HEX);
  1150. if (node->qh.horizontal_link & 1) break;
  1151. num = node->qh.horizontal_link;
  1152. node = (Pipe_t *)(num & 0xFFFFFFE0);
  1153. }
  1154. Pipe_t *n = node;
  1155. do {
  1156. if (n == pipe) goto nextslot;
  1157. n = (Pipe_t *)(n->qh.horizontal_link & 0xFFFFFFE0);
  1158. } while (n != NULL);
  1159. //print(" adding at node ", (uint32_t)node, HEX);
  1160. //print(", num=", num, HEX);
  1161. //println(", node->qh.horizontal_link=", node->qh.horizontal_link, HEX);
  1162. pipe->qh.horizontal_link = node->qh.horizontal_link;
  1163. node->qh.horizontal_link = (uint32_t)pipe | 2; // 2=QH
  1164. // TODO: is it really necessary to keep doing the outer
  1165. // loop? Does adding it here satisfy all cases? If so
  1166. // we could avoid extra work by just returning here.
  1167. }
  1168. nextslot:
  1169. //print(" new slot ", i);
  1170. //print(": ");
  1171. //print_qh_list((Pipe_t *)(periodictable[i] & 0xFFFFFFE0));
  1172. {}
  1173. }
  1174. #endif
  1175. #if 0
  1176. println("Periodic Schedule:");
  1177. for (uint32_t i=0; i < PERIODIC_LIST_SIZE; i++) {
  1178. if (i < 10) print(" ");
  1179. print(i);
  1180. print(": ");
  1181. print_qh_list((Pipe_t *)(periodictable[i] & 0xFFFFFFE0));
  1182. }
  1183. #endif
  1184. }
  1185. void USBHost::delete_Pipe(Pipe_t *pipe)
  1186. {
  1187. println("delete_Pipe ", (uint32_t)pipe, HEX);
  1188. // halt pipe, find and free all Transfer_t
  1189. // EHCI 1.0, 4.8.2 page 72: "Software should first deactivate
  1190. // all active qTDs, wait for the queue head to go inactive"
  1191. //
  1192. // http://www.spinics.net/lists/linux-usb/msg131607.html
  1193. // http://www.spinics.net/lists/linux-usb/msg131936.html
  1194. //
  1195. // In practice it's not feasible to wait for an active QH to become
  1196. // inactive before removing it, for several reasons. For one, the QH may
  1197. // _never_ become inactive (if the endpoint NAKs indefinitely). For
  1198. // another, the procedure given in the spec (deactivate the qTDs on the
  1199. // queue) is racy, since the controller can perform a new overlay or
  1200. // writeback at any time.
  1201. bool isasync = (pipe->type == 0 || pipe->type == 2);
  1202. if (isasync) {
  1203. // find the next QH in the async schedule loop
  1204. Pipe_t *next = (Pipe_t *)(pipe->qh.horizontal_link & 0xFFFFFFE0);
  1205. if (next == pipe) {
  1206. // removing the only QH, so just shut down the async schedule
  1207. println(" shut down async schedule");
  1208. USBHS_USBCMD &= ~USBHS_USBCMD_ASE; // disable async schedule
  1209. while (USBHS_USBSTS & USBHS_USBSTS_AS) ; // busy loop wait
  1210. USBHS_ASYNCLISTADDR = 0;
  1211. } else {
  1212. // find the previous QH in the async schedule loop
  1213. println(" remove QH from async schedule");
  1214. Pipe_t *prev = next;
  1215. while (1) {
  1216. Pipe_t *n = (Pipe_t *)(prev->qh.horizontal_link & 0xFFFFFFE0);
  1217. if (n == pipe) break;
  1218. prev = n;
  1219. }
  1220. // if removing the one with H bit, set another
  1221. if (pipe->qh.capabilities[0] & 0x8000) {
  1222. prev->qh.capabilities[0] |= 0x8000; // set H bit
  1223. }
  1224. // link the previous QH, we're no longer in the loop
  1225. prev->qh.horizontal_link = pipe->qh.horizontal_link;
  1226. // do the Async Advance Doorbell handshake to wait to be
  1227. // sure the EHCI no longer references the removed QH
  1228. USBHS_USBCMD |= USBHS_USBCMD_IAA;
  1229. while (!(USBHS_USBSTS & USBHS_USBSTS_AAI)) ; // busy loop wait
  1230. USBHS_USBSTS = USBHS_USBSTS_AAI;
  1231. // TODO: does this write interfere UPI & UAI (bits 18 & 19) ??
  1232. }
  1233. // find & free all the transfers which completed
  1234. println(" Free transfers");
  1235. Transfer_t *t = async_followup_first;
  1236. while (t) {
  1237. print(" * ", (uint32_t)t);
  1238. Transfer_t *next = t->next_followup;
  1239. if (t->pipe == pipe) {
  1240. print(" * remove");
  1241. remove_from_async_followup_list(t);
  1242. // Only free if not in QH list
  1243. Transfer_t *tr = (Transfer_t *)(pipe->qh.next);
  1244. while (((uint32_t)tr & 0xFFFFFFE0) && (tr != t)){
  1245. tr = (Transfer_t *)(tr->qtd.next);
  1246. }
  1247. if (tr == t) {
  1248. println(" * defer free until QH");
  1249. } else {
  1250. println(" * free");
  1251. free_Transfer(t); // The later code should actually free it...
  1252. }
  1253. } else {
  1254. println("");
  1255. }
  1256. t = next;
  1257. }
  1258. } else {
  1259. // remove from the periodic schedule
  1260. for (uint32_t i=0; i < PERIODIC_LIST_SIZE; i++) {
  1261. uint32_t num = periodictable[i];
  1262. if (num & 1) continue;
  1263. Pipe_t *node = (Pipe_t *)(num & 0xFFFFFFE0);
  1264. if (node == pipe) {
  1265. periodictable[i] = pipe->qh.horizontal_link;
  1266. continue;
  1267. }
  1268. Pipe_t *prev = node;
  1269. while (1) {
  1270. num = node->qh.horizontal_link;
  1271. if (num & 1) break;
  1272. node = (Pipe_t *)(num & 0xFFFFFFE0);
  1273. if (node == pipe) {
  1274. prev->qh.horizontal_link = node->qh.horizontal_link;
  1275. break;
  1276. }
  1277. prev = node;
  1278. }
  1279. }
  1280. // subtract bandwidth from uframe_bandwidth array
  1281. if (pipe->device->speed == 2) {
  1282. uint32_t interval = pipe->bandwidth_interval;
  1283. uint32_t offset = pipe->bandwidth_offset;
  1284. uint32_t stime = pipe->bandwidth_stime;
  1285. for (uint32_t i=offset; i < PERIODIC_LIST_SIZE*8; i += interval) {
  1286. uframe_bandwidth[i] -= stime;
  1287. }
  1288. } else {
  1289. uint32_t interval = pipe->bandwidth_interval;
  1290. uint32_t offset = pipe->bandwidth_offset;
  1291. uint32_t shift = pipe->bandwidth_shift;
  1292. uint32_t stime = pipe->bandwidth_stime;
  1293. uint32_t ctime = pipe->bandwidth_ctime;
  1294. for (uint32_t i=offset; i < PERIODIC_LIST_SIZE; i += interval) {
  1295. uint32_t n = (i << 3) + shift;
  1296. uframe_bandwidth[n+0] -= stime;
  1297. uframe_bandwidth[n+2] -= ctime;
  1298. uframe_bandwidth[n+3] -= ctime;
  1299. uframe_bandwidth[n+4] -= ctime;
  1300. }
  1301. }
  1302. // find & free all the transfers which completed
  1303. println(" Free transfers");
  1304. Transfer_t *t = periodic_followup_first;
  1305. while (t) {
  1306. print(" * ", (uint32_t)t);
  1307. Transfer_t *next = t->next_followup;
  1308. if (t->pipe == pipe) {
  1309. print(" * remove");
  1310. remove_from_periodic_followup_list(t);
  1311. // Only free if not in QH list
  1312. Transfer_t *tr = (Transfer_t *)(pipe->qh.next);
  1313. while (((uint32_t)tr & 0xFFFFFFE0) && (tr != t)){
  1314. tr = (Transfer_t *)(tr->qtd.next);
  1315. }
  1316. if (tr == t) {
  1317. println(" * defer free until QH");
  1318. } else {
  1319. println(" * free");
  1320. free_Transfer(t); // The later code should actually free it...
  1321. }
  1322. } else {
  1323. println("");
  1324. }
  1325. t = next;
  1326. }
  1327. }
  1328. //
  1329. // TODO: do we need to look at pipe->qh.current ??
  1330. //
  1331. // free all the transfers still attached to the QH
  1332. println(" Free transfers attached to QH");
  1333. Transfer_t *tr = (Transfer_t *)(pipe->qh.next);
  1334. while ((uint32_t)tr & 0xFFFFFFE0) {
  1335. println(" * ", (uint32_t)tr);
  1336. Transfer_t *next = (Transfer_t *)(tr->qtd.next);
  1337. free_Transfer(tr);
  1338. tr = next;
  1339. }
  1340. // hopefully we found everything...
  1341. free_Pipe(pipe);
  1342. println("* Delete Pipe completed");
  1343. }