PlatformIO package of the Teensy core framework compatible with GCC 10 & C++20
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

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