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

989 行
31KB

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