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.

828 lines
27KB

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