Ви не можете вибрати більше 25 тем Теми мають розпочинатися з літери або цифри, можуть містити дефіси (-) і не повинні перевищувати 35 символів.

1051 lines
33KB

  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.h"
  25. // Size of the periodic list, in milliseconds. This determines the
  26. // slowest rate we can poll interrupt endpoints. Each entry uses
  27. // 12 bytes (4 for a pointer, 8 for bandwidth management).
  28. // may be 8, 16, 32, 64, 128, 256, 512, 1024
  29. #define PERIODIC_LIST_SIZE 32
  30. static uint32_t periodictable[PERIODIC_LIST_SIZE] __attribute__ ((aligned(4096), used));
  31. static uint8_t uframe_bandwidth[PERIODIC_LIST_SIZE*8];
  32. static uint8_t port_state;
  33. #define PORT_STATE_DISCONNECTED 0
  34. #define PORT_STATE_DEBOUNCE 1
  35. #define PORT_STATE_RESET 2
  36. #define PORT_STATE_RECOVERY 3
  37. #define PORT_STATE_ACTIVE 4
  38. static Device_t *rootdev=NULL;
  39. static Transfer_t *async_followup_first=NULL;
  40. static Transfer_t *async_followup_last=NULL;
  41. static Transfer_t *periodic_followup_first=NULL;
  42. static Transfer_t *periodic_followup_last=NULL;
  43. static void init_qTD(volatile Transfer_t *t, void *buf, uint32_t len,
  44. uint32_t pid, uint32_t data01, bool irq);
  45. static bool followup_Transfer(Transfer_t *transfer);
  46. static void add_to_async_followup_list(Transfer_t *first, Transfer_t *last);
  47. static void remove_from_async_followup_list(Transfer_t *transfer);
  48. static void add_to_periodic_followup_list(Transfer_t *first, Transfer_t *last);
  49. static void remove_from_periodic_followup_list(Transfer_t *transfer);
  50. void USBHost::begin()
  51. {
  52. // Teensy 3.6 has USB host power controlled by PTE6
  53. PORTE_PCR6 = PORT_PCR_MUX(1);
  54. GPIOE_PDDR |= (1<<6);
  55. GPIOE_PSOR = (1<<6); // turn on USB host power
  56. delay(10);
  57. println("sizeof Device = ", sizeof(Device_t));
  58. println("sizeof Pipe = ", sizeof(Pipe_t));
  59. println("sizeof Transfer = ", sizeof(Transfer_t));
  60. if ((sizeof(Pipe_t) & 0x1F) || (sizeof(Transfer_t) & 0x1F)) {
  61. println("ERROR: Pipe_t & Transfer_t must be multiples of 32 bytes!");
  62. while (1) ; // die here
  63. }
  64. // configure the MPU to allow USBHS DMA to access memory
  65. MPU_RGDAAC0 |= 0x30000000;
  66. //println("MPU_RGDAAC0 = ", MPU_RGDAAC0, HEX);
  67. // turn on clocks
  68. MCG_C1 |= MCG_C1_IRCLKEN; // enable MCGIRCLK 32kHz
  69. OSC0_CR |= OSC_ERCLKEN;
  70. SIM_SOPT2 |= SIM_SOPT2_USBREGEN; // turn on USB regulator
  71. SIM_SOPT2 &= ~SIM_SOPT2_USBSLSRC; // use IRC for slow clock
  72. println("power up USBHS PHY");
  73. SIM_USBPHYCTL |= SIM_USBPHYCTL_USBDISILIM; // disable USB current limit
  74. //SIM_USBPHYCTL = SIM_USBPHYCTL_USBDISILIM | SIM_USBPHYCTL_USB3VOUTTRG(6); // pg 237
  75. SIM_SCGC3 |= SIM_SCGC3_USBHSDCD | SIM_SCGC3_USBHSPHY | SIM_SCGC3_USBHS;
  76. USBHSDCD_CLOCK = 33 << 2;
  77. //print("init USBHS PHY & PLL");
  78. // init process: page 1681-1682
  79. USBPHY_CTRL_CLR = (USBPHY_CTRL_SFTRST | USBPHY_CTRL_CLKGATE); // // CTRL pg 1698
  80. USBPHY_CTRL_SET = USBPHY_CTRL_ENUTMILEVEL2 | USBPHY_CTRL_ENUTMILEVEL3;
  81. //USBPHY_CTRL_SET = USBPHY_CTRL_FSDLL_RST_EN; // TODO: what does this do??
  82. USBPHY_TRIM_OVERRIDE_EN_SET = 1;
  83. USBPHY_PLL_SIC = USBPHY_PLL_SIC_PLL_POWER | USBPHY_PLL_SIC_PLL_ENABLE |
  84. USBPHY_PLL_SIC_PLL_DIV_SEL(1) | USBPHY_PLL_SIC_PLL_EN_USB_CLKS;
  85. // wait for the PLL to lock
  86. int count=0;
  87. while ((USBPHY_PLL_SIC & USBPHY_PLL_SIC_PLL_LOCK) == 0) {
  88. count++;
  89. }
  90. //println("PLL locked, waited ", count);
  91. // turn on power to PHY
  92. USBPHY_PWD = 0;
  93. delay(10);
  94. // sanity check, connect 470K pullup & 100K pulldown and watch D+ voltage change
  95. //USBPHY_ANACTRL_CLR = (1<<10); // turn off both 15K pulldowns... works! :)
  96. // sanity check, output clocks on pin 9 for testing
  97. //SIM_SOPT2 = SIM_SOPT2 & (~SIM_SOPT2_CLKOUTSEL(7)) | SIM_SOPT2_CLKOUTSEL(3); // LPO 1kHz
  98. //SIM_SOPT2 = SIM_SOPT2 & (~SIM_SOPT2_CLKOUTSEL(7)) | SIM_SOPT2_CLKOUTSEL(2); // Flash
  99. //SIM_SOPT2 = SIM_SOPT2 & (~SIM_SOPT2_CLKOUTSEL(7)) | SIM_SOPT2_CLKOUTSEL(6); // XTAL
  100. //SIM_SOPT2 = SIM_SOPT2 & (~SIM_SOPT2_CLKOUTSEL(7)) | SIM_SOPT2_CLKOUTSEL(7); // IRC 48MHz
  101. //SIM_SOPT2 = SIM_SOPT2 & (~SIM_SOPT2_CLKOUTSEL(7)) | SIM_SOPT2_CLKOUTSEL(4); // MCGIRCLK
  102. //CORE_PIN9_CONFIG = PORT_PCR_MUX(5); // CLKOUT on PTC3 Alt5 (Arduino pin 9)
  103. // now with the PHY up and running, start up USBHS
  104. //print("begin ehci reset");
  105. USBHS_USBCMD |= USBHS_USBCMD_RST;
  106. //count = 0;
  107. while (USBHS_USBCMD & USBHS_USBCMD_RST) {
  108. //count++;
  109. }
  110. //println(" reset waited ", count);
  111. init_Device_Pipe_Transfer_memory();
  112. for (int i=0; i < 32; i++) {
  113. periodictable[i] = 1;
  114. }
  115. memset(uframe_bandwidth, 0, sizeof(uframe_bandwidth));
  116. port_state = PORT_STATE_DISCONNECTED;
  117. USBHS_USB_SBUSCFG = 1; // System Bus Interface Configuration
  118. // turn on the USBHS controller
  119. //USBHS_USBMODE = USBHS_USBMODE_TXHSD(5) | USBHS_USBMODE_CM(3); // host mode
  120. USBHS_USBMODE = USBHS_USBMODE_CM(3); // host mode
  121. USBHS_USBINTR = 0;
  122. USBHS_PERIODICLISTBASE = (uint32_t)periodictable;
  123. USBHS_FRINDEX = 0;
  124. USBHS_ASYNCLISTADDR = 0;
  125. USBHS_USBCMD = USBHS_USBCMD_ITC(8) | USBHS_USBCMD_RS |
  126. USBHS_USBCMD_ASP(3) | USBHS_USBCMD_ASPE | USBHS_USBCMD_PSE |
  127. #if PERIODIC_LIST_SIZE == 8
  128. USBHS_USBCMD_FS2 | USBHS_USBCMD_FS(3);
  129. #elif PERIODIC_LIST_SIZE == 16
  130. USBHS_USBCMD_FS2 | USBHS_USBCMD_FS(2);
  131. #elif PERIODIC_LIST_SIZE == 32
  132. USBHS_USBCMD_FS2 | USBHS_USBCMD_FS(1);
  133. #elif PERIODIC_LIST_SIZE == 64
  134. USBHS_USBCMD_FS2 | USBHS_USBCMD_FS(0);
  135. #elif PERIODIC_LIST_SIZE == 128
  136. USBHS_USBCMD_FS(3);
  137. #elif PERIODIC_LIST_SIZE == 256
  138. USBHS_USBCMD_FS(2);
  139. #elif PERIODIC_LIST_SIZE == 512
  140. USBHS_USBCMD_FS(1);
  141. #elif PERIODIC_LIST_SIZE == 1024
  142. USBHS_USBCMD_FS(0);
  143. #else
  144. #error "Unsupported PERIODIC_LIST_SIZE"
  145. #endif
  146. // turn on the USB port
  147. //USBHS_PORTSC1 = USBHS_PORTSC_PP;
  148. USBHS_PORTSC1 |= USBHS_PORTSC_PP;
  149. //USBHS_PORTSC1 |= USBHS_PORTSC_PFSC; // force 12 Mbit/sec
  150. //USBHS_PORTSC1 |= USBHS_PORTSC_PHCD; // phy off
  151. //println("USBHS_ASYNCLISTADDR = ", USBHS_ASYNCLISTADDR, HEX);
  152. //println("USBHS_PERIODICLISTBASE = ", USBHS_PERIODICLISTBASE, HEX);
  153. //println("periodictable = ", (uint32_t)periodictable, HEX);
  154. // enable interrupts, after this point interruts to all the work
  155. attachInterruptVector(IRQ_USBHS, isr);
  156. NVIC_ENABLE_IRQ(IRQ_USBHS);
  157. USBHS_USBINTR = USBHS_USBINTR_PCE | USBHS_USBINTR_TIE0;
  158. USBHS_USBINTR |= USBHS_USBINTR_UEE | USBHS_USBINTR_SEE;
  159. USBHS_USBINTR |= USBHS_USBINTR_AAE;
  160. USBHS_USBINTR |= USBHS_USBINTR_UPIE | USBHS_USBINTR_UAIE;
  161. }
  162. // EHCI registers page default
  163. // -------------- ---- -------
  164. // USBHS_USBCMD 1599 00080000 USB Command
  165. // USBHS_USBSTS 1602 00000000 USB Status
  166. // USBHS_USBINTR 1606 00000000 USB Interrupt Enable
  167. // USBHS_FRINDEX 1609 00000000 Frame Index Register
  168. // USBHS_PERIODICLISTBASE 1610 undefine Periodic Frame List Base Address
  169. // USBHS_ASYNCLISTADDR 1612 undefine Asynchronous List Address
  170. // USBHS_PORTSC1 1619 00002000 Port Status and Control
  171. // USBHS_USBMODE 1629 00005000 USB Mode
  172. // USBHS_GPTIMERnCTL 1591 00000000 General Purpose Timer n Control
  173. // PORT_STATE_DISCONNECTED 0
  174. // PORT_STATE_DEBOUNCE 1
  175. // PORT_STATE_RESET 2
  176. // PORT_STATE_RECOVERY 3
  177. // PORT_STATE_ACTIVE 4
  178. void USBHost::isr()
  179. {
  180. uint32_t stat = USBHS_USBSTS;
  181. USBHS_USBSTS = stat; // clear pending interrupts
  182. //stat &= USBHS_USBINTR; // mask away unwanted interrupts
  183. println();
  184. println("ISR: ", stat, HEX);
  185. //if (stat & USBHS_USBSTS_UI) println(" USB Interrupt");
  186. if (stat & USBHS_USBSTS_UEI) println(" USB Error");
  187. if (stat & USBHS_USBSTS_PCI) println(" Port Change");
  188. //if (stat & USBHS_USBSTS_FRI) println(" Frame List Rollover");
  189. if (stat & USBHS_USBSTS_SEI) println(" System Error");
  190. //if (stat & USBHS_USBSTS_AAI) println(" Async Advance (doorbell)");
  191. if (stat & USBHS_USBSTS_URI) println(" Reset Recv");
  192. //if (stat & USBHS_USBSTS_SRI) println(" SOF");
  193. if (stat & USBHS_USBSTS_SLI) println(" Suspend");
  194. if (stat & USBHS_USBSTS_HCH) println(" Host Halted");
  195. //if (stat & USBHS_USBSTS_RCL) println(" Reclamation");
  196. //if (stat & USBHS_USBSTS_PS) println(" Periodic Sched En");
  197. //if (stat & USBHS_USBSTS_AS) println(" Async Sched En");
  198. if (stat & USBHS_USBSTS_NAKI) println(" NAK");
  199. if (stat & USBHS_USBSTS_UAI) println(" USB Async");
  200. if (stat & USBHS_USBSTS_UPI) println(" USB Periodic");
  201. if (stat & USBHS_USBSTS_TI0) println(" Timer0");
  202. if (stat & USBHS_USBSTS_TI1) println(" Timer1");
  203. if (stat & USBHS_USBSTS_UAI) { // completed qTD(s) from the async schedule
  204. println("Async Followup");
  205. //print(async_followup_first, async_followup_last);
  206. Transfer_t *p = async_followup_first;
  207. while (p) {
  208. if (followup_Transfer(p)) {
  209. // transfer completed
  210. Transfer_t *next = p->next_followup;
  211. remove_from_async_followup_list(p);
  212. free_Transfer(p);
  213. p = next;
  214. } else {
  215. // transfer still pending
  216. p = p->next_followup;
  217. }
  218. }
  219. //print(async_followup_first, async_followup_last);
  220. }
  221. if (stat & USBHS_USBSTS_UPI) { // completed qTD(s) from the periodic schedule
  222. println("Periodic Followup");
  223. Transfer_t *p = periodic_followup_first;
  224. while (p) {
  225. if (followup_Transfer(p)) {
  226. // transfer completed
  227. Transfer_t *next = p->next_followup;
  228. remove_from_periodic_followup_list(p);
  229. free_Transfer(p);
  230. p = next;
  231. } else {
  232. // transfer still pending
  233. p = p->next_followup;
  234. }
  235. }
  236. }
  237. if (stat & USBHS_USBSTS_PCI) { // port change detected
  238. const uint32_t portstat = USBHS_PORTSC1;
  239. println("port change: ", portstat, HEX);
  240. USBHS_PORTSC1 = portstat | (USBHS_PORTSC_OCC|USBHS_PORTSC_PEC|USBHS_PORTSC_CSC);
  241. if (portstat & USBHS_PORTSC_OCC) {
  242. println(" overcurrent change");
  243. }
  244. if (portstat & USBHS_PORTSC_CSC) {
  245. if (portstat & USBHS_PORTSC_CCS) {
  246. println(" connect");
  247. if (port_state == PORT_STATE_DISCONNECTED
  248. || port_state == PORT_STATE_DEBOUNCE) {
  249. // 100 ms debounce (USB 2.0: TATTDB, page 150 & 188)
  250. port_state = PORT_STATE_DEBOUNCE;
  251. USBHS_GPTIMER0LD = 100000; // microseconds
  252. USBHS_GPTIMER0CTL =
  253. USBHS_GPTIMERCTL_RST | USBHS_GPTIMERCTL_RUN;
  254. stat &= ~USBHS_USBSTS_TI0;
  255. }
  256. } else {
  257. println(" disconnect");
  258. port_state = PORT_STATE_DISCONNECTED;
  259. USBPHY_CTRL_CLR = USBPHY_CTRL_ENHOSTDISCONDETECT;
  260. disconnect_Device(rootdev);
  261. rootdev = NULL;
  262. }
  263. }
  264. if (portstat & USBHS_PORTSC_PEC) {
  265. // PEC bit only detects disable
  266. println(" disable");
  267. } else if (port_state == PORT_STATE_RESET && portstat & USBHS_PORTSC_PE) {
  268. println(" port enabled");
  269. port_state = PORT_STATE_RECOVERY;
  270. // 10 ms reset recover (USB 2.0: TRSTRCY, page 151 & 188)
  271. USBHS_GPTIMER0LD = 10000; // microseconds
  272. USBHS_GPTIMER0CTL = USBHS_GPTIMERCTL_RST | USBHS_GPTIMERCTL_RUN;
  273. if (USBHS_PORTSC1 & USBHS_PORTSC_HSP) {
  274. // turn on high-speed disconnect detector
  275. USBPHY_CTRL_SET = USBPHY_CTRL_ENHOSTDISCONDETECT;
  276. }
  277. }
  278. if (portstat & USBHS_PORTSC_FPR) {
  279. println(" force resume");
  280. }
  281. }
  282. if (stat & USBHS_USBSTS_TI0) { // timer 0
  283. println("timer");
  284. if (port_state == PORT_STATE_DEBOUNCE) {
  285. port_state = PORT_STATE_RESET;
  286. USBHS_PORTSC1 |= USBHS_PORTSC_PR; // begin reset sequence
  287. println(" begin reset");
  288. } else if (port_state == PORT_STATE_RECOVERY) {
  289. port_state = PORT_STATE_ACTIVE;
  290. println(" end recovery");
  291. // HCSPARAMS TTCTRL page 1671
  292. uint32_t speed = (USBHS_PORTSC1 >> 26) & 3;
  293. rootdev = new_Device(speed, 0, 0);
  294. }
  295. }
  296. }
  297. static uint32_t QH_capabilities1(uint32_t nak_count_reload, uint32_t control_endpoint_flag,
  298. uint32_t max_packet_length, uint32_t head_of_list, uint32_t data_toggle_control,
  299. uint32_t speed, uint32_t endpoint_number, uint32_t inactivate, uint32_t address)
  300. {
  301. return ( (nak_count_reload << 28) | (control_endpoint_flag << 27) |
  302. (max_packet_length << 16) | (head_of_list << 15) |
  303. (data_toggle_control << 14) | (speed << 12) | (endpoint_number << 8) |
  304. (inactivate << 7) | (address << 0) );
  305. }
  306. static uint32_t QH_capabilities2(uint32_t high_bw_mult, uint32_t hub_port_number,
  307. uint32_t hub_address, uint32_t split_completion_mask, uint32_t interrupt_schedule_mask)
  308. {
  309. return ( (high_bw_mult << 30) | (hub_port_number << 23) | (hub_address << 16) |
  310. (split_completion_mask << 8) | (interrupt_schedule_mask << 0) );
  311. }
  312. // Create a new pipe. It's QH is added to the async or periodic schedule,
  313. // and a halt qTD is added to the QH, so we can grow the qTD list later.
  314. // dev: device owning this pipe/endpoint
  315. // type: 0=control, 2=bulk, 3=interrupt
  316. // endpoint: 0 for control, 1-15 for bulk or interrupt
  317. // direction: 0=OUT, 1=IN (unused for control)
  318. // maxlen: maximum packet size
  319. // interval: polling interval for interrupt, power of 2, unused if control or bulk
  320. //
  321. Pipe_t * USBHost::new_Pipe(Device_t *dev, uint32_t type, uint32_t endpoint,
  322. uint32_t direction, uint32_t maxlen, uint32_t interval)
  323. {
  324. Pipe_t *pipe;
  325. Transfer_t *halt;
  326. uint32_t c=0, dtc=0;
  327. println("new_Pipe");
  328. pipe = allocate_Pipe();
  329. if (!pipe) return NULL;
  330. halt = allocate_Transfer();
  331. if (!halt) {
  332. free_Pipe(pipe);
  333. return NULL;
  334. }
  335. memset(pipe, 0, sizeof(Pipe_t));
  336. memset(halt, 0, sizeof(Transfer_t));
  337. halt->qtd.next = 1;
  338. halt->qtd.token = 0x40;
  339. pipe->device = dev;
  340. pipe->qh.next = (uint32_t)halt;
  341. pipe->qh.alt_next = 1;
  342. pipe->direction = direction;
  343. pipe->type = type;
  344. if (type == 3) {
  345. // interrupt transfers require bandwidth & microframe scheduling
  346. if (!allocate_interrupt_pipe_bandwidth(pipe, maxlen, interval)) {
  347. free_Transfer(halt);
  348. free_Pipe(pipe);
  349. return NULL;
  350. }
  351. }
  352. if (endpoint > 0) {
  353. // if non-control pipe, update dev->data_pipes list
  354. Pipe_t *p = dev->data_pipes;
  355. if (p == NULL) {
  356. dev->data_pipes = pipe;
  357. } else {
  358. while (p->next) p = p->next;
  359. p->next = pipe;
  360. }
  361. }
  362. if (type == 0) {
  363. // control
  364. if (dev->speed < 2) c = 1;
  365. dtc = 1;
  366. } else if (type == 2) {
  367. // bulk
  368. } else if (type == 3) {
  369. // interrupt
  370. }
  371. pipe->qh.capabilities[0] = QH_capabilities1(15, c, maxlen, 0,
  372. dtc, dev->speed, endpoint, 0, dev->address);
  373. pipe->qh.capabilities[1] = QH_capabilities2(1, dev->hub_port,
  374. dev->hub_address, pipe->complete_mask, pipe->start_mask);
  375. if (type == 0 || type == 2) {
  376. // control or bulk: add to async queue
  377. Pipe_t *list = (Pipe_t *)USBHS_ASYNCLISTADDR;
  378. if (list == NULL) {
  379. pipe->qh.capabilities[0] |= 0x8000; // H bit
  380. pipe->qh.horizontal_link = (uint32_t)&(pipe->qh) | 2; // 2=QH
  381. USBHS_ASYNCLISTADDR = (uint32_t)&(pipe->qh);
  382. USBHS_USBCMD |= USBHS_USBCMD_ASE; // enable async schedule
  383. //println(" first in async list");
  384. } else {
  385. // EHCI 1.0: section 4.8.1, page 72
  386. pipe->qh.horizontal_link = list->qh.horizontal_link;
  387. list->qh.horizontal_link = (uint32_t)&(pipe->qh) | 2;
  388. //println(" added to async list");
  389. }
  390. } else if (type == 3) {
  391. // interrupt: add to periodic schedule
  392. add_qh_to_periodic_schedule(pipe);
  393. }
  394. return pipe;
  395. }
  396. // Fill in the qTD fields (token & data)
  397. // t the Transfer qTD to initialize
  398. // buf data to transfer
  399. // len length of data
  400. // pid type of packet: 0=OUT, 1=IN, 2=SETUP
  401. // data01 value of DATA0/DATA1 toggle on 1st packet
  402. // irq whether to generate an interrupt when transfer complete
  403. //
  404. static void init_qTD(volatile Transfer_t *t, void *buf, uint32_t len,
  405. uint32_t pid, uint32_t data01, bool irq)
  406. {
  407. t->qtd.alt_next = 1; // 1=terminate
  408. if (data01) data01 = 0x80000000;
  409. t->qtd.token = data01 | (len << 16) | (irq ? 0x8000 : 0) | (pid << 8) | 0x80;
  410. uint32_t addr = (uint32_t)buf;
  411. t->qtd.buffer[0] = addr;
  412. addr &= 0xFFFFF000;
  413. t->qtd.buffer[1] = addr + 0x1000;
  414. t->qtd.buffer[2] = addr + 0x2000;
  415. t->qtd.buffer[3] = addr + 0x3000;
  416. t->qtd.buffer[4] = addr + 0x4000;
  417. }
  418. // Create a Control Transfer and queue it
  419. //
  420. bool USBHost::queue_Control_Transfer(Device_t *dev, setup_t *setup, void *buf, USBDriver *driver)
  421. {
  422. Transfer_t *transfer, *data, *status;
  423. uint32_t status_direction;
  424. println("new_Control_Transfer");
  425. if (setup->wLength > 16384) return false; // max 16K data for control
  426. transfer = allocate_Transfer();
  427. if (!transfer) return false;
  428. status = allocate_Transfer();
  429. if (!status) {
  430. free_Transfer(transfer);
  431. return false;
  432. }
  433. if (setup->wLength > 0) {
  434. data = allocate_Transfer();
  435. if (!data) {
  436. free_Transfer(transfer);
  437. free_Transfer(status);
  438. return false;
  439. }
  440. uint32_t pid = (setup->bmRequestType & 0x80) ? 1 : 0;
  441. init_qTD(data, buf, setup->wLength, pid, 1, false);
  442. transfer->qtd.next = (uint32_t)data;
  443. data->qtd.next = (uint32_t)status;
  444. status_direction = pid ^ 1;
  445. } else {
  446. transfer->qtd.next = (uint32_t)status;
  447. status_direction = 1; // always IN, USB 2.0 page 226
  448. }
  449. //println("setup address ", (uint32_t)setup, HEX);
  450. init_qTD(transfer, setup, 8, 2, 0, false);
  451. init_qTD(status, NULL, 0, status_direction, 1, true);
  452. status->pipe = dev->control_pipe;
  453. status->buffer = buf;
  454. status->length = setup->wLength;
  455. status->setup = setup;
  456. status->driver = driver;
  457. status->qtd.next = 1;
  458. return queue_Transfer(dev->control_pipe, transfer);
  459. }
  460. // Create a Bulk or Interrupt Transfer and queue it
  461. //
  462. bool USBHost::queue_Data_Transfer(Pipe_t *pipe, void *buffer, uint32_t len, USBDriver *driver)
  463. {
  464. Transfer_t *transfer, *data, *next;
  465. uint8_t *p = (uint8_t *)buffer;
  466. uint32_t count;
  467. bool last = false;
  468. // TODO: option for zero length packet? Maybe in Pipe_t fields?
  469. println("new_Data_Transfer");
  470. // allocate qTDs
  471. transfer = allocate_Transfer();
  472. if (!transfer) return false;
  473. data = transfer;
  474. for (count=(len >> 14); count; count--) {
  475. next = allocate_Transfer();
  476. if (!next) {
  477. // free already-allocated qTDs
  478. while (1) {
  479. next = (Transfer_t *)transfer->qtd.next;
  480. free_Transfer(transfer);
  481. if (transfer == data) break;
  482. transfer = next;
  483. }
  484. return false;
  485. }
  486. data->qtd.next = (uint32_t)next;
  487. data = next;
  488. }
  489. // last qTD needs info for followup
  490. data->qtd.next = 1;
  491. data->pipe = pipe;
  492. data->buffer = buffer;
  493. data->length = len;
  494. data->setup = NULL;
  495. data->driver = driver;
  496. // initialize all qTDs
  497. data = transfer;
  498. while (1) {
  499. uint32_t count = len;
  500. if (count > 16384) {
  501. count = 16384;
  502. } else {
  503. last = true;
  504. }
  505. init_qTD(data, p, count, pipe->direction, 0, last);
  506. if (last) break;
  507. p += count;
  508. len -= count;
  509. data = (Transfer_t *)(data->qtd.next);
  510. }
  511. return queue_Transfer(pipe, transfer);
  512. }
  513. bool USBHost::queue_Transfer(Pipe_t *pipe, Transfer_t *transfer)
  514. {
  515. // find halt qTD
  516. Transfer_t *halt = (Transfer_t *)(pipe->qh.next);
  517. while (!(halt->qtd.token & 0x40)) halt = (Transfer_t *)(halt->qtd.next);
  518. // transfer's token
  519. uint32_t token = transfer->qtd.token;
  520. // transfer becomes new halt qTD
  521. transfer->qtd.token = 0x40;
  522. // copy transfer non-token fields to halt
  523. halt->qtd.next = transfer->qtd.next;
  524. halt->qtd.alt_next = transfer->qtd.alt_next;
  525. halt->qtd.buffer[0] = transfer->qtd.buffer[0]; // TODO: optimize memcpy, all
  526. halt->qtd.buffer[1] = transfer->qtd.buffer[1]; // fields except token
  527. halt->qtd.buffer[2] = transfer->qtd.buffer[2];
  528. halt->qtd.buffer[3] = transfer->qtd.buffer[3];
  529. halt->qtd.buffer[4] = transfer->qtd.buffer[4];
  530. halt->pipe = pipe;
  531. halt->buffer = transfer->buffer;
  532. halt->length = transfer->length;
  533. halt->setup = transfer->setup;
  534. halt->driver = transfer->driver;
  535. // find the last qTD we're adding
  536. Transfer_t *last = halt;
  537. while ((uint32_t)(last->qtd.next) != 1) last = (Transfer_t *)(last->qtd.next);
  538. // last points to transfer (which becomes new halt)
  539. last->qtd.next = (uint32_t)transfer;
  540. transfer->qtd.next = 1;
  541. // link all the new qTD by next_followup & prev_followup
  542. Transfer_t *prev = NULL;
  543. Transfer_t *p = halt;
  544. while (p->qtd.next != (uint32_t)transfer) {
  545. Transfer_t *next = (Transfer_t *)p->qtd.next;
  546. p->prev_followup = prev;
  547. p->next_followup = next;
  548. prev = p;
  549. p = next;
  550. }
  551. p->prev_followup = prev;
  552. p->next_followup = NULL;
  553. //print(halt, p);
  554. // add them to a followup list
  555. if (pipe->type == 0 || pipe->type == 2) {
  556. // control or bulk
  557. add_to_async_followup_list(halt, p);
  558. } else {
  559. // interrupt
  560. add_to_periodic_followup_list(halt, p);
  561. }
  562. // old halt becomes new transfer, this commits all new qTDs to QH
  563. halt->qtd.token = token;
  564. return true;
  565. }
  566. static bool followup_Transfer(Transfer_t *transfer)
  567. {
  568. //println(" Followup ", (uint32_t)transfer, HEX);
  569. if (!(transfer->qtd.token & 0x80)) {
  570. // TODO: check error status
  571. if (transfer->qtd.token & 0x8000) {
  572. // this transfer caused an interrupt
  573. if (transfer->pipe->callback_function) {
  574. // do the callback
  575. (*(transfer->pipe->callback_function))(transfer);
  576. }
  577. }
  578. // do callback function...
  579. //println(" completed");
  580. return true;
  581. }
  582. return false;
  583. }
  584. static void add_to_async_followup_list(Transfer_t *first, Transfer_t *last)
  585. {
  586. last->next_followup = NULL; // always add to end of list
  587. if (async_followup_last == NULL) {
  588. first->prev_followup = NULL;
  589. async_followup_first = first;
  590. } else {
  591. first->prev_followup = async_followup_last;
  592. async_followup_last->next_followup = first;
  593. }
  594. async_followup_last = last;
  595. }
  596. static void remove_from_async_followup_list(Transfer_t *transfer)
  597. {
  598. Transfer_t *next = transfer->next_followup;
  599. Transfer_t *prev = transfer->prev_followup;
  600. if (prev) {
  601. prev->next_followup = next;
  602. } else {
  603. async_followup_first = next;
  604. }
  605. if (next) {
  606. next->prev_followup = prev;
  607. } else {
  608. async_followup_last = prev;
  609. }
  610. }
  611. static void add_to_periodic_followup_list(Transfer_t *first, Transfer_t *last)
  612. {
  613. last->next_followup = NULL; // always add to end of list
  614. if (periodic_followup_last == NULL) {
  615. first->prev_followup = NULL;
  616. periodic_followup_first = first;
  617. } else {
  618. first->prev_followup = periodic_followup_last;
  619. periodic_followup_last->next_followup = first;
  620. }
  621. periodic_followup_last = last;
  622. }
  623. static void remove_from_periodic_followup_list(Transfer_t *transfer)
  624. {
  625. Transfer_t *next = transfer->next_followup;
  626. Transfer_t *prev = transfer->prev_followup;
  627. if (prev) {
  628. prev->next_followup = next;
  629. } else {
  630. periodic_followup_first = next;
  631. }
  632. if (next) {
  633. next->prev_followup = prev;
  634. } else {
  635. periodic_followup_last = prev;
  636. }
  637. }
  638. static uint32_t max4(uint32_t n1, uint32_t n2, uint32_t n3, uint32_t n4)
  639. {
  640. if (n1 > n2) {
  641. // can't be n2
  642. if (n1 > n3) {
  643. // can't be n3
  644. if (n1 > n4) return n1;
  645. } else {
  646. // can't be n1
  647. if (n3 > n4) return n3;
  648. }
  649. } else {
  650. // can't be n1
  651. if (n2 > n3) {
  652. // can't be n3
  653. if (n2 > n4) return n2;
  654. } else {
  655. // can't be n2
  656. if (n3 > n4) return n3;
  657. }
  658. }
  659. return n4;
  660. }
  661. static uint32_t round_to_power_of_two(uint32_t n, uint32_t maxnum)
  662. {
  663. for (uint32_t pow2num=1; pow2num < maxnum; pow2num <<= 1) {
  664. if (n <= (pow2num | (pow2num >> 1))) return pow2num;
  665. }
  666. return maxnum;
  667. }
  668. // Allocate bandwidth for an interrupt pipe. Given the packet size
  669. // and other parameters, find the best place to schedule this pipe.
  670. // Returns true if enough bandwidth is available, and the best
  671. // frame offset, smask and cmask. Or returns false if no group
  672. // of microframes has enough bandwidth available.
  673. //
  674. // pipe:
  675. // device->speed [in] 0=full speed, 1=low speed, 2=high speed
  676. // direction [in] 0=OUT, 1=IN
  677. // start_mask [out] uframes to start transfer
  678. // complete_mask [out] uframes to complete transfer (FS & LS only)
  679. // periodic_interval [out] fream repeat level: 1, 2, 4, 8... PERIODIC_LIST_SIZE
  680. // periodic_offset [out] frame repeat offset: 0 to periodic_interval-1
  681. // maxlen: [in] maximum packet length
  682. // interval: [in] polling interval: LS+FS: frames, HS: 2^(n-1) uframes
  683. //
  684. bool USBHost::allocate_interrupt_pipe_bandwidth(Pipe_t *pipe, uint32_t maxlen, uint32_t interval)
  685. {
  686. println("allocate_interrupt_pipe_bandwidth");
  687. if (interval == 0) interval = 1;
  688. maxlen = (maxlen * 76459) >> 16; // worst case bit stuffing
  689. if (pipe->device->speed == 2) {
  690. // high speed 480 Mbit/sec
  691. if (interval > 15) interval = 15;
  692. interval = 1 << (interval - 1);
  693. if (interval > PERIODIC_LIST_SIZE*8) interval = PERIODIC_LIST_SIZE*8;
  694. uint32_t stime = (55 + 32 + maxlen) >> 5; // time units: 32 bytes or 533 ns
  695. uint32_t best_offset = 0xFFFFFFFF;
  696. uint32_t best_bandwidth = 0xFFFFFFFF;
  697. for (uint32_t offset=0; offset < interval; offset++) {
  698. // for each possible uframe offset, find the worst uframe bandwidth
  699. uint32_t max_bandwidth = 0;
  700. for (uint32_t i=offset; i < PERIODIC_LIST_SIZE*8; i += interval) {
  701. uint32_t bandwidth = uframe_bandwidth[i] + stime;
  702. if (bandwidth > max_bandwidth) max_bandwidth = bandwidth;
  703. }
  704. // remember which uframe offset is the best
  705. if (max_bandwidth < best_bandwidth) {
  706. best_bandwidth = max_bandwidth;
  707. best_offset = offset;
  708. }
  709. }
  710. print(" best_bandwidth = ");
  711. print(best_bandwidth);
  712. print(", at offset = ");
  713. println(best_offset);
  714. // a 125 us micro frame can fit 7500 bytes, or 234 of our 32-byte units
  715. // fail if the best found needs more than 80% (234 * 0.8) in any uframe
  716. if (best_bandwidth > 187) return false;
  717. for (uint32_t i=best_offset; i < PERIODIC_LIST_SIZE*8; i += interval) {
  718. uframe_bandwidth[i] += stime;
  719. }
  720. if (interval == 1) {
  721. pipe->start_mask = 0xFF;
  722. } else if (interval == 2) {
  723. pipe->start_mask = 0x55 << (best_offset & 1);
  724. } else if (interval <= 4) {
  725. pipe->start_mask = 0x11 << (best_offset & 3);
  726. } else {
  727. pipe->start_mask = 0x01 << (best_offset & 7);
  728. }
  729. uint32_t poffset = best_offset >> 3;
  730. pipe->periodic_offset = (poffset > 0) ? poffset : 1;
  731. pipe->complete_mask = 0;
  732. } else {
  733. // full speed 12 Mbit/sec or low speed 1.5 Mbit/sec
  734. interval = round_to_power_of_two(interval, PERIODIC_LIST_SIZE);
  735. pipe->periodic_interval = interval;
  736. uint32_t stime, ctime;
  737. if (pipe->direction == 0) {
  738. // for OUT direction, SSPLIT will carry the data payload
  739. // TODO: how much time to SSPLIT & CSPLIT actually take?
  740. // they're not documented in 5.7 or 5.11.3.
  741. stime = (100 + 32 + maxlen) >> 5;
  742. ctime = (55 + 32) >> 5;
  743. } else {
  744. // for IN direction, data payload in CSPLIT
  745. stime = (40 + 32) >> 5;
  746. ctime = (70 + 32 + maxlen) >> 5;
  747. }
  748. // TODO: should we take Single-TT hubs into account, avoid
  749. // scheduling overlapping SSPLIT & CSPLIT to the same hub?
  750. // TODO: even if Multi-TT, do we need to worry about packing
  751. // too many into the same uframe?
  752. uint32_t best_shift = 0;
  753. uint32_t best_offset = 0xFFFFFFFF;
  754. uint32_t best_bandwidth = 0xFFFFFFFF;
  755. for (uint32_t offset=0; offset < interval; offset++) {
  756. // for each 1ms frame offset, compute the worst uframe usage
  757. uint32_t max_bandwidth = 0;
  758. for (uint32_t i=offset; i < PERIODIC_LIST_SIZE; i += interval) {
  759. for (uint32_t j=0; j <= 3; j++) { // max 3 without FSTN
  760. // at each location, find worst uframe usage
  761. // for SSPLIT+CSPLITs
  762. uint32_t n = (i << 3) + j;
  763. uint32_t bw1 = uframe_bandwidth[n+0] + stime;
  764. uint32_t bw2 = uframe_bandwidth[n+2] + ctime;
  765. uint32_t bw3 = uframe_bandwidth[n+3] + ctime;
  766. uint32_t bw4 = uframe_bandwidth[n+4] + ctime;
  767. max_bandwidth = max4(bw1, bw2, bw3, bw4);
  768. // remember the best usage found
  769. if (max_bandwidth < best_bandwidth) {
  770. best_bandwidth = max_bandwidth;
  771. best_offset = i;
  772. best_shift = j;
  773. }
  774. }
  775. }
  776. }
  777. print(" best_bandwidth = ");
  778. println(best_bandwidth);
  779. print(", at offset = ");
  780. print(best_offset);
  781. print(", shift= ");
  782. println(best_shift);
  783. // a 125 us micro frame can fit 7500 bytes, or 234 of our 32-byte units
  784. // fail if the best found needs more than 80% (234 * 0.8) in any uframe
  785. if (best_bandwidth > 187) return false;
  786. for (uint32_t i=best_offset; i < PERIODIC_LIST_SIZE; i += interval) {
  787. uint32_t n = (i << 3) + best_shift;
  788. uframe_bandwidth[n+0] += stime;
  789. uframe_bandwidth[n+2] += ctime;
  790. uframe_bandwidth[n+3] += ctime;
  791. uframe_bandwidth[n+4] += ctime;
  792. }
  793. pipe->start_mask = 0x01 << best_shift;
  794. pipe->complete_mask = 0x1C << best_shift;
  795. pipe->periodic_offset = best_offset;
  796. }
  797. return true;
  798. }
  799. // put a new pipe into the periodic schedule tree
  800. // according to periodic_interval and periodic_offset
  801. //
  802. void USBHost::add_qh_to_periodic_schedule(Pipe_t *pipe)
  803. {
  804. // quick hack for testing, just put it into the first table entry
  805. println("add_qh_to_periodic_schedule:");
  806. #if 0
  807. pipe->qh.horizontal_link = periodictable[0];
  808. periodictable[0] = (uint32_t)&(pipe->qh) | 2; // 2=QH
  809. println("init periodictable with ", periodictable[0], HEX);
  810. #else
  811. uint32_t interval = pipe->periodic_interval;
  812. uint32_t offset = pipe->periodic_offset;
  813. println(" interval = ", interval);
  814. println(" offset = ", offset);
  815. // TODO: does this really make an inverted tree like EHCI figure 4-18, page 93
  816. for (uint32_t i=offset; i < PERIODIC_LIST_SIZE; i += interval) {
  817. uint32_t num = periodictable[i];
  818. Pipe_t *node = (Pipe_t *)(num & 0xFFFFFFE0);
  819. if ((num & 1) || ((num & 6) == 2 && node->periodic_interval < interval)) {
  820. println(" add to slot ", i);
  821. pipe->qh.horizontal_link = num;
  822. periodictable[i] = (uint32_t)&(pipe->qh) | 2; // 2=QH
  823. } else {
  824. println(" traverse list ", i);
  825. // TODO: skip past iTD, siTD when/if we support isochronous
  826. while (node->periodic_interval >= interval) {
  827. if (node->qh.horizontal_link & 1) break;
  828. num = node->qh.horizontal_link;
  829. node = (Pipe_t *)(num & 0xFFFFFFE0);
  830. }
  831. pipe->qh.horizontal_link = num;
  832. node->qh.horizontal_link = (uint32_t)pipe | 2; // 2=QH
  833. }
  834. }
  835. #endif
  836. println("Periodic Schedule:");
  837. for (uint32_t i=0; i < PERIODIC_LIST_SIZE; i++) {
  838. if (i < 10) print(" ");
  839. print(i);
  840. print(": ");
  841. print_qh_list((Pipe_t *)(periodictable[i] & 0xFFFFFFE0));
  842. }
  843. }
  844. void USBHost::delete_Pipe(Pipe_t *pipe)
  845. {
  846. println("delete_Pipe ", (uint32_t)pipe, HEX);
  847. // halt pipe, find and free all Transfer_t
  848. // EHCI 1.0, 4.8.2 page 72: "Software should first deactivate
  849. // all active qTDs, wait for the queue head to go inactive"
  850. //
  851. // http://www.spinics.net/lists/linux-usb/msg131607.html
  852. // http://www.spinics.net/lists/linux-usb/msg131936.html
  853. //
  854. // In practice it's not feasible to wait for an active QH to become
  855. // inactive before removing it, for several reasons. For one, the QH may
  856. // _never_ become inactive (if the endpoint NAKs indefinitely). For
  857. // another, the procedure given in the spec (deactivate the qTDs on the
  858. // queue) is racy, since the controller can perform a new overlay or
  859. // writeback at any time.
  860. bool isasync = (pipe->type == 0 || pipe->type == 2);
  861. if (isasync) {
  862. // find the next QH in the async schedule loop
  863. Pipe_t *next = (Pipe_t *)(pipe->qh.horizontal_link & 0xFFFFFFE0);
  864. if (next == pipe) {
  865. // removing the only QH, so just shut down the async schedule
  866. println(" shut down async schedule");
  867. USBHS_USBCMD &= ~USBHS_USBCMD_ASE; // disable async schedule
  868. while (USBHS_USBSTS & USBHS_USBSTS_AS) ; // busy loop wait
  869. USBHS_ASYNCLISTADDR = 0;
  870. } else {
  871. // find the previous QH in the async schedule loop
  872. println(" remove QH from async schedule");
  873. Pipe_t *prev = next;
  874. while (1) {
  875. Pipe_t *n = (Pipe_t *)(prev->qh.horizontal_link & 0xFFFFFFE0);
  876. if (n == pipe) break;
  877. prev = n;
  878. }
  879. // if removing the one with H bit, set another
  880. if (pipe->qh.capabilities[0] & 0x8000) {
  881. prev->qh.capabilities[0] |= 0x8000; // set H bit
  882. }
  883. // link the previous QH, we're no longer in the loop
  884. prev->qh.horizontal_link = pipe->qh.horizontal_link;
  885. // do the Async Advance Doorbell handshake to wait to be
  886. // sure the EHCI no longer references the removed QH
  887. USBHS_USBCMD |= USBHS_USBCMD_IAA;
  888. while (!(USBHS_USBSTS & USBHS_USBSTS_AAI)) ; // busy loop wait
  889. USBHS_USBSTS = USBHS_USBSTS_AAI;
  890. // TODO: does this write interfere UPI & UAI (bits 18 & 19) ??
  891. }
  892. // find & free all the transfers which completed
  893. Transfer_t *t = async_followup_first;
  894. while (t) {
  895. Transfer_t *next = t->next_followup;
  896. if (t->pipe == pipe) {
  897. remove_from_async_followup_list(t);
  898. free_Transfer(t);
  899. }
  900. t = next;
  901. }
  902. } else {
  903. // remove from the periodic schedule
  904. for (uint32_t i=0; i < PERIODIC_LIST_SIZE; i++) {
  905. uint32_t num = periodictable[i];
  906. if (num & 1) continue;
  907. Pipe_t *node = (Pipe_t *)(num & 0xFFFFFFE0);
  908. if (node == pipe) {
  909. periodictable[i] = pipe->qh.horizontal_link;
  910. continue;
  911. }
  912. Pipe_t *prev = node;
  913. while (1) {
  914. num = node->qh.horizontal_link;
  915. if (num & 1) break;
  916. node = (Pipe_t *)(num & 0xFFFFFFE0);
  917. if (node == pipe) {
  918. prev->qh.horizontal_link = node->qh.horizontal_link;
  919. break;
  920. }
  921. prev = node;
  922. }
  923. }
  924. // TODO: subtract bandwidth from uframe_bandwidth array
  925. // find & free all the transfers which completed
  926. Transfer_t *t = periodic_followup_first;
  927. while (t) {
  928. Transfer_t *next = t->next_followup;
  929. if (t->pipe == pipe) {
  930. remove_from_periodic_followup_list(t);
  931. free_Transfer(t);
  932. }
  933. t = next;
  934. }
  935. }
  936. //
  937. // TODO: do we need to look at pipe->qh.current ??
  938. //
  939. // free all the transfers still attached to the QH
  940. Transfer_t *tr = (Transfer_t *)(pipe->qh.next);
  941. while ((uint32_t)tr & 0xFFFFFFE0) {
  942. Transfer_t *next = (Transfer_t *)(tr->qtd.next);
  943. free_Transfer(tr);
  944. tr = next;
  945. }
  946. // hopefully we found everything...
  947. free_Pipe(pipe);
  948. }