usb.c 32 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204
  1. /*
  2. * Most of this source has been derived from the Linux USB
  3. * project:
  4. * (C) Copyright Linus Torvalds 1999
  5. * (C) Copyright Johannes Erdfelt 1999-2001
  6. * (C) Copyright Andreas Gal 1999
  7. * (C) Copyright Gregory P. Smith 1999
  8. * (C) Copyright Deti Fliegl 1999 (new USB architecture)
  9. * (C) Copyright Randy Dunlap 2000
  10. * (C) Copyright David Brownell 2000 (kernel hotplug, usb_device_id)
  11. * (C) Copyright Yggdrasil Computing, Inc. 2000
  12. * (usb_device_id matching changes by Adam J. Richter)
  13. *
  14. * Adapted for U-Boot:
  15. * (C) Copyright 2001 Denis Peter, MPL AG Switzerland
  16. *
  17. * SPDX-License-Identifier: GPL-2.0+
  18. */
  19. /*
  20. * How it works:
  21. *
  22. * Since this is a bootloader, the devices will not be automatic
  23. * (re)configured on hotplug, but after a restart of the USB the
  24. * device should work.
  25. *
  26. * For each transfer (except "Interrupt") we wait for completion.
  27. */
  28. #include <common.h>
  29. #include <command.h>
  30. #include <dm.h>
  31. #include <asm/processor.h>
  32. #include <linux/compiler.h>
  33. #include <linux/ctype.h>
  34. #include <asm/byteorder.h>
  35. #include <asm/unaligned.h>
  36. #include <errno.h>
  37. #include <usb.h>
  38. #ifdef CONFIG_4xx
  39. #include <asm/4xx_pci.h>
  40. #endif
  41. #define USB_BUFSIZ 512
  42. static int asynch_allowed;
  43. char usb_started; /* flag for the started/stopped USB status */
  44. #ifndef CONFIG_DM_USB
  45. static struct usb_device usb_dev[USB_MAX_DEVICE];
  46. static int dev_index;
  47. #ifndef CONFIG_USB_MAX_CONTROLLER_COUNT
  48. #define CONFIG_USB_MAX_CONTROLLER_COUNT 1
  49. #endif
  50. /***************************************************************************
  51. * Init USB Device
  52. */
  53. int usb_init(void)
  54. {
  55. void *ctrl;
  56. struct usb_device *dev;
  57. int i, start_index = 0;
  58. int controllers_initialized = 0;
  59. int ret;
  60. dev_index = 0;
  61. asynch_allowed = 1;
  62. usb_hub_reset();
  63. /* first make all devices unknown */
  64. for (i = 0; i < USB_MAX_DEVICE; i++) {
  65. memset(&usb_dev[i], 0, sizeof(struct usb_device));
  66. usb_dev[i].devnum = -1;
  67. }
  68. /* init low_level USB */
  69. for (i = 0; i < CONFIG_USB_MAX_CONTROLLER_COUNT; i++) {
  70. /* init low_level USB */
  71. printf("USB%d: ", i);
  72. ret = usb_lowlevel_init(i, USB_INIT_HOST, &ctrl);
  73. if (ret == -ENODEV) { /* No such device. */
  74. puts("Port not available.\n");
  75. controllers_initialized++;
  76. continue;
  77. }
  78. if (ret) { /* Other error. */
  79. puts("lowlevel init failed\n");
  80. continue;
  81. }
  82. /*
  83. * lowlevel init is OK, now scan the bus for devices
  84. * i.e. search HUBs and configure them
  85. */
  86. controllers_initialized++;
  87. start_index = dev_index;
  88. printf("scanning bus %d for devices... ", i);
  89. ret = usb_alloc_new_device(ctrl, &dev);
  90. if (ret)
  91. break;
  92. /*
  93. * device 0 is always present
  94. * (root hub, so let it analyze)
  95. */
  96. ret = usb_new_device(dev);
  97. if (ret)
  98. usb_free_device(dev->controller);
  99. if (start_index == dev_index) {
  100. puts("No USB Device found\n");
  101. continue;
  102. } else {
  103. printf("%d USB Device(s) found\n",
  104. dev_index - start_index);
  105. }
  106. usb_started = 1;
  107. }
  108. debug("scan end\n");
  109. /* if we were not able to find at least one working bus, bail out */
  110. if (controllers_initialized == 0)
  111. puts("USB error: all controllers failed lowlevel init\n");
  112. return usb_started ? 0 : -ENODEV;
  113. }
  114. /******************************************************************************
  115. * Stop USB this stops the LowLevel Part and deregisters USB devices.
  116. */
  117. int usb_stop(void)
  118. {
  119. int i;
  120. if (usb_started) {
  121. asynch_allowed = 1;
  122. usb_started = 0;
  123. usb_hub_reset();
  124. for (i = 0; i < CONFIG_USB_MAX_CONTROLLER_COUNT; i++) {
  125. if (usb_lowlevel_stop(i))
  126. printf("failed to stop USB controller %d\n", i);
  127. }
  128. }
  129. return 0;
  130. }
  131. /******************************************************************************
  132. * Detect if a USB device has been plugged or unplugged.
  133. */
  134. int usb_detect_change(void)
  135. {
  136. int i, j;
  137. int change = 0;
  138. for (j = 0; j < USB_MAX_DEVICE; j++) {
  139. for (i = 0; i < usb_dev[j].maxchild; i++) {
  140. struct usb_port_status status;
  141. if (usb_get_port_status(&usb_dev[j], i + 1,
  142. &status) < 0)
  143. /* USB request failed */
  144. continue;
  145. if (le16_to_cpu(status.wPortChange) &
  146. USB_PORT_STAT_C_CONNECTION)
  147. change++;
  148. }
  149. }
  150. return change;
  151. }
  152. /*
  153. * disables the asynch behaviour of the control message. This is used for data
  154. * transfers that uses the exclusiv access to the control and bulk messages.
  155. * Returns the old value so it can be restored later.
  156. */
  157. int usb_disable_asynch(int disable)
  158. {
  159. int old_value = asynch_allowed;
  160. asynch_allowed = !disable;
  161. return old_value;
  162. }
  163. #endif /* !CONFIG_DM_USB */
  164. /*-------------------------------------------------------------------
  165. * Message wrappers.
  166. *
  167. */
  168. /*
  169. * submits an Interrupt Message
  170. */
  171. int usb_submit_int_msg(struct usb_device *dev, unsigned long pipe,
  172. void *buffer, int transfer_len, int interval)
  173. {
  174. return submit_int_msg(dev, pipe, buffer, transfer_len, interval);
  175. }
  176. /*
  177. * submits a control message and waits for comletion (at least timeout * 1ms)
  178. * If timeout is 0, we don't wait for completion (used as example to set and
  179. * clear keyboards LEDs). For data transfers, (storage transfers) we don't
  180. * allow control messages with 0 timeout, by previousely resetting the flag
  181. * asynch_allowed (usb_disable_asynch(1)).
  182. * returns the transfered length if OK or -1 if error. The transfered length
  183. * and the current status are stored in the dev->act_len and dev->status.
  184. */
  185. int usb_control_msg(struct usb_device *dev, unsigned int pipe,
  186. unsigned char request, unsigned char requesttype,
  187. unsigned short value, unsigned short index,
  188. void *data, unsigned short size, int timeout)
  189. {
  190. ALLOC_CACHE_ALIGN_BUFFER(struct devrequest, setup_packet, 1);
  191. int err;
  192. if ((timeout == 0) && (!asynch_allowed)) {
  193. /* request for a asynch control pipe is not allowed */
  194. return -EINVAL;
  195. }
  196. /* set setup command */
  197. setup_packet->requesttype = requesttype;
  198. setup_packet->request = request;
  199. setup_packet->value = cpu_to_le16(value);
  200. setup_packet->index = cpu_to_le16(index);
  201. setup_packet->length = cpu_to_le16(size);
  202. debug("usb_control_msg: request: 0x%X, requesttype: 0x%X, " \
  203. "value 0x%X index 0x%X length 0x%X\n",
  204. request, requesttype, value, index, size);
  205. dev->status = USB_ST_NOT_PROC; /*not yet processed */
  206. err = submit_control_msg(dev, pipe, data, size, setup_packet);
  207. if (err < 0)
  208. return err;
  209. if (timeout == 0)
  210. return (int)size;
  211. /*
  212. * Wait for status to update until timeout expires, USB driver
  213. * interrupt handler may set the status when the USB operation has
  214. * been completed.
  215. */
  216. while (timeout--) {
  217. if (!((volatile unsigned long)dev->status & USB_ST_NOT_PROC))
  218. break;
  219. mdelay(1);
  220. }
  221. if (dev->status)
  222. return -1;
  223. return dev->act_len;
  224. }
  225. /*-------------------------------------------------------------------
  226. * submits bulk message, and waits for completion. returns 0 if Ok or
  227. * negative if Error.
  228. * synchronous behavior
  229. */
  230. int usb_bulk_msg(struct usb_device *dev, unsigned int pipe,
  231. void *data, int len, int *actual_length, int timeout)
  232. {
  233. if (len < 0)
  234. return -EINVAL;
  235. dev->status = USB_ST_NOT_PROC; /*not yet processed */
  236. if (submit_bulk_msg(dev, pipe, data, len) < 0)
  237. return -EIO;
  238. while (timeout--) {
  239. if (!((volatile unsigned long)dev->status & USB_ST_NOT_PROC))
  240. break;
  241. mdelay(1);
  242. }
  243. *actual_length = dev->act_len;
  244. if (dev->status == 0)
  245. return 0;
  246. else
  247. return -EIO;
  248. }
  249. /*-------------------------------------------------------------------
  250. * Max Packet stuff
  251. */
  252. /*
  253. * returns the max packet size, depending on the pipe direction and
  254. * the configurations values
  255. */
  256. int usb_maxpacket(struct usb_device *dev, unsigned long pipe)
  257. {
  258. /* direction is out -> use emaxpacket out */
  259. if ((pipe & USB_DIR_IN) == 0)
  260. return dev->epmaxpacketout[((pipe>>15) & 0xf)];
  261. else
  262. return dev->epmaxpacketin[((pipe>>15) & 0xf)];
  263. }
  264. /*
  265. * The routine usb_set_maxpacket_ep() is extracted from the loop of routine
  266. * usb_set_maxpacket(), because the optimizer of GCC 4.x chokes on this routine
  267. * when it is inlined in 1 single routine. What happens is that the register r3
  268. * is used as loop-count 'i', but gets overwritten later on.
  269. * This is clearly a compiler bug, but it is easier to workaround it here than
  270. * to update the compiler (Occurs with at least several GCC 4.{1,2},x
  271. * CodeSourcery compilers like e.g. 2007q3, 2008q1, 2008q3 lite editions on ARM)
  272. *
  273. * NOTE: Similar behaviour was observed with GCC4.6 on ARMv5.
  274. */
  275. static void noinline
  276. usb_set_maxpacket_ep(struct usb_device *dev, int if_idx, int ep_idx)
  277. {
  278. int b;
  279. struct usb_endpoint_descriptor *ep;
  280. u16 ep_wMaxPacketSize;
  281. ep = &dev->config.if_desc[if_idx].ep_desc[ep_idx];
  282. b = ep->bEndpointAddress & USB_ENDPOINT_NUMBER_MASK;
  283. ep_wMaxPacketSize = get_unaligned(&ep->wMaxPacketSize);
  284. if ((ep->bmAttributes & USB_ENDPOINT_XFERTYPE_MASK) ==
  285. USB_ENDPOINT_XFER_CONTROL) {
  286. /* Control => bidirectional */
  287. dev->epmaxpacketout[b] = ep_wMaxPacketSize;
  288. dev->epmaxpacketin[b] = ep_wMaxPacketSize;
  289. debug("##Control EP epmaxpacketout/in[%d] = %d\n",
  290. b, dev->epmaxpacketin[b]);
  291. } else {
  292. if ((ep->bEndpointAddress & 0x80) == 0) {
  293. /* OUT Endpoint */
  294. if (ep_wMaxPacketSize > dev->epmaxpacketout[b]) {
  295. dev->epmaxpacketout[b] = ep_wMaxPacketSize;
  296. debug("##EP epmaxpacketout[%d] = %d\n",
  297. b, dev->epmaxpacketout[b]);
  298. }
  299. } else {
  300. /* IN Endpoint */
  301. if (ep_wMaxPacketSize > dev->epmaxpacketin[b]) {
  302. dev->epmaxpacketin[b] = ep_wMaxPacketSize;
  303. debug("##EP epmaxpacketin[%d] = %d\n",
  304. b, dev->epmaxpacketin[b]);
  305. }
  306. } /* if out */
  307. } /* if control */
  308. }
  309. /*
  310. * set the max packed value of all endpoints in the given configuration
  311. */
  312. static int usb_set_maxpacket(struct usb_device *dev)
  313. {
  314. int i, ii;
  315. for (i = 0; i < dev->config.desc.bNumInterfaces; i++)
  316. for (ii = 0; ii < dev->config.if_desc[i].desc.bNumEndpoints; ii++)
  317. usb_set_maxpacket_ep(dev, i, ii);
  318. return 0;
  319. }
  320. /*******************************************************************************
  321. * Parse the config, located in buffer, and fills the dev->config structure.
  322. * Note that all little/big endian swapping are done automatically.
  323. * (wTotalLength has already been swapped and sanitized when it was read.)
  324. */
  325. static int usb_parse_config(struct usb_device *dev,
  326. unsigned char *buffer, int cfgno)
  327. {
  328. struct usb_descriptor_header *head;
  329. int index, ifno, epno, curr_if_num;
  330. u16 ep_wMaxPacketSize;
  331. struct usb_interface *if_desc = NULL;
  332. ifno = -1;
  333. epno = -1;
  334. curr_if_num = -1;
  335. dev->configno = cfgno;
  336. head = (struct usb_descriptor_header *) &buffer[0];
  337. if (head->bDescriptorType != USB_DT_CONFIG) {
  338. printf(" ERROR: NOT USB_CONFIG_DESC %x\n",
  339. head->bDescriptorType);
  340. return -EINVAL;
  341. }
  342. if (head->bLength != USB_DT_CONFIG_SIZE) {
  343. printf("ERROR: Invalid USB CFG length (%d)\n", head->bLength);
  344. return -EINVAL;
  345. }
  346. memcpy(&dev->config, head, USB_DT_CONFIG_SIZE);
  347. dev->config.no_of_if = 0;
  348. index = dev->config.desc.bLength;
  349. /* Ok the first entry must be a configuration entry,
  350. * now process the others */
  351. head = (struct usb_descriptor_header *) &buffer[index];
  352. while (index + 1 < dev->config.desc.wTotalLength && head->bLength) {
  353. switch (head->bDescriptorType) {
  354. case USB_DT_INTERFACE:
  355. if (head->bLength != USB_DT_INTERFACE_SIZE) {
  356. printf("ERROR: Invalid USB IF length (%d)\n",
  357. head->bLength);
  358. break;
  359. }
  360. if (index + USB_DT_INTERFACE_SIZE >
  361. dev->config.desc.wTotalLength) {
  362. puts("USB IF descriptor overflowed buffer!\n");
  363. break;
  364. }
  365. if (((struct usb_interface_descriptor *) \
  366. head)->bInterfaceNumber != curr_if_num) {
  367. /* this is a new interface, copy new desc */
  368. ifno = dev->config.no_of_if;
  369. if (ifno >= USB_MAXINTERFACES) {
  370. puts("Too many USB interfaces!\n");
  371. /* try to go on with what we have */
  372. return -EINVAL;
  373. }
  374. if_desc = &dev->config.if_desc[ifno];
  375. dev->config.no_of_if++;
  376. memcpy(if_desc, head,
  377. USB_DT_INTERFACE_SIZE);
  378. if_desc->no_of_ep = 0;
  379. if_desc->num_altsetting = 1;
  380. curr_if_num =
  381. if_desc->desc.bInterfaceNumber;
  382. } else {
  383. /* found alternate setting for the interface */
  384. if (ifno >= 0) {
  385. if_desc = &dev->config.if_desc[ifno];
  386. if_desc->num_altsetting++;
  387. }
  388. }
  389. break;
  390. case USB_DT_ENDPOINT:
  391. if (head->bLength != USB_DT_ENDPOINT_SIZE) {
  392. printf("ERROR: Invalid USB EP length (%d)\n",
  393. head->bLength);
  394. break;
  395. }
  396. if (index + USB_DT_ENDPOINT_SIZE >
  397. dev->config.desc.wTotalLength) {
  398. puts("USB EP descriptor overflowed buffer!\n");
  399. break;
  400. }
  401. if (ifno < 0) {
  402. puts("Endpoint descriptor out of order!\n");
  403. break;
  404. }
  405. epno = dev->config.if_desc[ifno].no_of_ep;
  406. if_desc = &dev->config.if_desc[ifno];
  407. if (epno > USB_MAXENDPOINTS) {
  408. printf("Interface %d has too many endpoints!\n",
  409. if_desc->desc.bInterfaceNumber);
  410. return -EINVAL;
  411. }
  412. /* found an endpoint */
  413. if_desc->no_of_ep++;
  414. memcpy(&if_desc->ep_desc[epno], head,
  415. USB_DT_ENDPOINT_SIZE);
  416. ep_wMaxPacketSize = get_unaligned(&dev->config.\
  417. if_desc[ifno].\
  418. ep_desc[epno].\
  419. wMaxPacketSize);
  420. put_unaligned(le16_to_cpu(ep_wMaxPacketSize),
  421. &dev->config.\
  422. if_desc[ifno].\
  423. ep_desc[epno].\
  424. wMaxPacketSize);
  425. debug("if %d, ep %d\n", ifno, epno);
  426. break;
  427. case USB_DT_SS_ENDPOINT_COMP:
  428. if (head->bLength != USB_DT_SS_EP_COMP_SIZE) {
  429. printf("ERROR: Invalid USB EPC length (%d)\n",
  430. head->bLength);
  431. break;
  432. }
  433. if (index + USB_DT_SS_EP_COMP_SIZE >
  434. dev->config.desc.wTotalLength) {
  435. puts("USB EPC descriptor overflowed buffer!\n");
  436. break;
  437. }
  438. if (ifno < 0 || epno < 0) {
  439. puts("EPC descriptor out of order!\n");
  440. break;
  441. }
  442. if_desc = &dev->config.if_desc[ifno];
  443. memcpy(&if_desc->ss_ep_comp_desc[epno], head,
  444. USB_DT_SS_EP_COMP_SIZE);
  445. break;
  446. default:
  447. if (head->bLength == 0)
  448. return -EINVAL;
  449. debug("unknown Description Type : %x\n",
  450. head->bDescriptorType);
  451. #ifdef DEBUG
  452. {
  453. unsigned char *ch = (unsigned char *)head;
  454. int i;
  455. for (i = 0; i < head->bLength; i++)
  456. debug("%02X ", *ch++);
  457. debug("\n\n\n");
  458. }
  459. #endif
  460. break;
  461. }
  462. index += head->bLength;
  463. head = (struct usb_descriptor_header *)&buffer[index];
  464. }
  465. return 0;
  466. }
  467. /***********************************************************************
  468. * Clears an endpoint
  469. * endp: endpoint number in bits 0-3;
  470. * direction flag in bit 7 (1 = IN, 0 = OUT)
  471. */
  472. int usb_clear_halt(struct usb_device *dev, int pipe)
  473. {
  474. int result;
  475. int endp = usb_pipeendpoint(pipe)|(usb_pipein(pipe)<<7);
  476. result = usb_control_msg(dev, usb_sndctrlpipe(dev, 0),
  477. USB_REQ_CLEAR_FEATURE, USB_RECIP_ENDPOINT, 0,
  478. endp, NULL, 0, USB_CNTL_TIMEOUT * 3);
  479. /* don't clear if failed */
  480. if (result < 0)
  481. return result;
  482. /*
  483. * NOTE: we do not get status and verify reset was successful
  484. * as some devices are reported to lock up upon this check..
  485. */
  486. usb_endpoint_running(dev, usb_pipeendpoint(pipe), usb_pipeout(pipe));
  487. /* toggle is reset on clear */
  488. usb_settoggle(dev, usb_pipeendpoint(pipe), usb_pipeout(pipe), 0);
  489. return 0;
  490. }
  491. /**********************************************************************
  492. * get_descriptor type
  493. */
  494. static int usb_get_descriptor(struct usb_device *dev, unsigned char type,
  495. unsigned char index, void *buf, int size)
  496. {
  497. int res;
  498. res = usb_control_msg(dev, usb_rcvctrlpipe(dev, 0),
  499. USB_REQ_GET_DESCRIPTOR, USB_DIR_IN,
  500. (type << 8) + index, 0,
  501. buf, size, USB_CNTL_TIMEOUT);
  502. return res;
  503. }
  504. /**********************************************************************
  505. * gets configuration cfgno and store it in the buffer
  506. */
  507. int usb_get_configuration_no(struct usb_device *dev,
  508. unsigned char *buffer, int cfgno)
  509. {
  510. int result;
  511. unsigned int length;
  512. struct usb_config_descriptor *config;
  513. config = (struct usb_config_descriptor *)&buffer[0];
  514. result = usb_get_descriptor(dev, USB_DT_CONFIG, cfgno, buffer, 9);
  515. if (result < 9) {
  516. if (result < 0)
  517. printf("unable to get descriptor, error %lX\n",
  518. dev->status);
  519. else
  520. printf("config descriptor too short " \
  521. "(expected %i, got %i)\n", 9, result);
  522. return -EIO;
  523. }
  524. length = le16_to_cpu(config->wTotalLength);
  525. if (length > USB_BUFSIZ) {
  526. printf("%s: failed to get descriptor - too long: %d\n",
  527. __func__, length);
  528. return -EIO;
  529. }
  530. result = usb_get_descriptor(dev, USB_DT_CONFIG, cfgno, buffer, length);
  531. debug("get_conf_no %d Result %d, wLength %d\n", cfgno, result, length);
  532. config->wTotalLength = length; /* validated, with CPU byte order */
  533. return result;
  534. }
  535. /********************************************************************
  536. * set address of a device to the value in dev->devnum.
  537. * This can only be done by addressing the device via the default address (0)
  538. */
  539. static int usb_set_address(struct usb_device *dev)
  540. {
  541. int res;
  542. debug("set address %d\n", dev->devnum);
  543. res = usb_control_msg(dev, usb_snddefctrl(dev),
  544. USB_REQ_SET_ADDRESS, 0,
  545. (dev->devnum), 0,
  546. NULL, 0, USB_CNTL_TIMEOUT);
  547. return res;
  548. }
  549. /********************************************************************
  550. * set interface number to interface
  551. */
  552. int usb_set_interface(struct usb_device *dev, int interface, int alternate)
  553. {
  554. struct usb_interface *if_face = NULL;
  555. int ret, i;
  556. for (i = 0; i < dev->config.desc.bNumInterfaces; i++) {
  557. if (dev->config.if_desc[i].desc.bInterfaceNumber == interface) {
  558. if_face = &dev->config.if_desc[i];
  559. break;
  560. }
  561. }
  562. if (!if_face) {
  563. printf("selecting invalid interface %d", interface);
  564. return -EINVAL;
  565. }
  566. /*
  567. * We should return now for devices with only one alternate setting.
  568. * According to 9.4.10 of the Universal Serial Bus Specification
  569. * Revision 2.0 such devices can return with a STALL. This results in
  570. * some USB sticks timeouting during initialization and then being
  571. * unusable in U-Boot.
  572. */
  573. if (if_face->num_altsetting == 1)
  574. return 0;
  575. ret = usb_control_msg(dev, usb_sndctrlpipe(dev, 0),
  576. USB_REQ_SET_INTERFACE, USB_RECIP_INTERFACE,
  577. alternate, interface, NULL, 0,
  578. USB_CNTL_TIMEOUT * 5);
  579. if (ret < 0)
  580. return ret;
  581. return 0;
  582. }
  583. /********************************************************************
  584. * set configuration number to configuration
  585. */
  586. static int usb_set_configuration(struct usb_device *dev, int configuration)
  587. {
  588. int res;
  589. debug("set configuration %d\n", configuration);
  590. /* set setup command */
  591. res = usb_control_msg(dev, usb_sndctrlpipe(dev, 0),
  592. USB_REQ_SET_CONFIGURATION, 0,
  593. configuration, 0,
  594. NULL, 0, USB_CNTL_TIMEOUT);
  595. if (res == 0) {
  596. dev->toggle[0] = 0;
  597. dev->toggle[1] = 0;
  598. return 0;
  599. } else
  600. return -EIO;
  601. }
  602. /********************************************************************
  603. * set protocol to protocol
  604. */
  605. int usb_set_protocol(struct usb_device *dev, int ifnum, int protocol)
  606. {
  607. return usb_control_msg(dev, usb_sndctrlpipe(dev, 0),
  608. USB_REQ_SET_PROTOCOL, USB_TYPE_CLASS | USB_RECIP_INTERFACE,
  609. protocol, ifnum, NULL, 0, USB_CNTL_TIMEOUT);
  610. }
  611. /********************************************************************
  612. * set idle
  613. */
  614. int usb_set_idle(struct usb_device *dev, int ifnum, int duration, int report_id)
  615. {
  616. return usb_control_msg(dev, usb_sndctrlpipe(dev, 0),
  617. USB_REQ_SET_IDLE, USB_TYPE_CLASS | USB_RECIP_INTERFACE,
  618. (duration << 8) | report_id, ifnum, NULL, 0, USB_CNTL_TIMEOUT);
  619. }
  620. /********************************************************************
  621. * get report
  622. */
  623. int usb_get_report(struct usb_device *dev, int ifnum, unsigned char type,
  624. unsigned char id, void *buf, int size)
  625. {
  626. return usb_control_msg(dev, usb_rcvctrlpipe(dev, 0),
  627. USB_REQ_GET_REPORT,
  628. USB_DIR_IN | USB_TYPE_CLASS | USB_RECIP_INTERFACE,
  629. (type << 8) + id, ifnum, buf, size, USB_CNTL_TIMEOUT);
  630. }
  631. /********************************************************************
  632. * get class descriptor
  633. */
  634. int usb_get_class_descriptor(struct usb_device *dev, int ifnum,
  635. unsigned char type, unsigned char id, void *buf, int size)
  636. {
  637. return usb_control_msg(dev, usb_rcvctrlpipe(dev, 0),
  638. USB_REQ_GET_DESCRIPTOR, USB_RECIP_INTERFACE | USB_DIR_IN,
  639. (type << 8) + id, ifnum, buf, size, USB_CNTL_TIMEOUT);
  640. }
  641. /********************************************************************
  642. * get string index in buffer
  643. */
  644. static int usb_get_string(struct usb_device *dev, unsigned short langid,
  645. unsigned char index, void *buf, int size)
  646. {
  647. int i;
  648. int result;
  649. for (i = 0; i < 3; ++i) {
  650. /* some devices are flaky */
  651. result = usb_control_msg(dev, usb_rcvctrlpipe(dev, 0),
  652. USB_REQ_GET_DESCRIPTOR, USB_DIR_IN,
  653. (USB_DT_STRING << 8) + index, langid, buf, size,
  654. USB_CNTL_TIMEOUT);
  655. if (result > 0)
  656. break;
  657. }
  658. return result;
  659. }
  660. static void usb_try_string_workarounds(unsigned char *buf, int *length)
  661. {
  662. int newlength, oldlength = *length;
  663. for (newlength = 2; newlength + 1 < oldlength; newlength += 2)
  664. if (!isprint(buf[newlength]) || buf[newlength + 1])
  665. break;
  666. if (newlength > 2) {
  667. buf[0] = newlength;
  668. *length = newlength;
  669. }
  670. }
  671. static int usb_string_sub(struct usb_device *dev, unsigned int langid,
  672. unsigned int index, unsigned char *buf)
  673. {
  674. int rc;
  675. /* Try to read the string descriptor by asking for the maximum
  676. * possible number of bytes */
  677. rc = usb_get_string(dev, langid, index, buf, 255);
  678. /* If that failed try to read the descriptor length, then
  679. * ask for just that many bytes */
  680. if (rc < 2) {
  681. rc = usb_get_string(dev, langid, index, buf, 2);
  682. if (rc == 2)
  683. rc = usb_get_string(dev, langid, index, buf, buf[0]);
  684. }
  685. if (rc >= 2) {
  686. if (!buf[0] && !buf[1])
  687. usb_try_string_workarounds(buf, &rc);
  688. /* There might be extra junk at the end of the descriptor */
  689. if (buf[0] < rc)
  690. rc = buf[0];
  691. rc = rc - (rc & 1); /* force a multiple of two */
  692. }
  693. if (rc < 2)
  694. rc = -EINVAL;
  695. return rc;
  696. }
  697. /********************************************************************
  698. * usb_string:
  699. * Get string index and translate it to ascii.
  700. * returns string length (> 0) or error (< 0)
  701. */
  702. int usb_string(struct usb_device *dev, int index, char *buf, size_t size)
  703. {
  704. ALLOC_CACHE_ALIGN_BUFFER(unsigned char, mybuf, USB_BUFSIZ);
  705. unsigned char *tbuf;
  706. int err;
  707. unsigned int u, idx;
  708. if (size <= 0 || !buf || !index)
  709. return -EINVAL;
  710. buf[0] = 0;
  711. tbuf = &mybuf[0];
  712. /* get langid for strings if it's not yet known */
  713. if (!dev->have_langid) {
  714. err = usb_string_sub(dev, 0, 0, tbuf);
  715. if (err < 0) {
  716. debug("error getting string descriptor 0 " \
  717. "(error=%lx)\n", dev->status);
  718. return -EIO;
  719. } else if (tbuf[0] < 4) {
  720. debug("string descriptor 0 too short\n");
  721. return -EIO;
  722. } else {
  723. dev->have_langid = -1;
  724. dev->string_langid = tbuf[2] | (tbuf[3] << 8);
  725. /* always use the first langid listed */
  726. debug("USB device number %d default " \
  727. "language ID 0x%x\n",
  728. dev->devnum, dev->string_langid);
  729. }
  730. }
  731. err = usb_string_sub(dev, dev->string_langid, index, tbuf);
  732. if (err < 0)
  733. return err;
  734. size--; /* leave room for trailing NULL char in output buffer */
  735. for (idx = 0, u = 2; u < err; u += 2) {
  736. if (idx >= size)
  737. break;
  738. if (tbuf[u+1]) /* high byte */
  739. buf[idx++] = '?'; /* non-ASCII character */
  740. else
  741. buf[idx++] = tbuf[u];
  742. }
  743. buf[idx] = 0;
  744. err = idx;
  745. return err;
  746. }
  747. /********************************************************************
  748. * USB device handling:
  749. * the USB device are static allocated [USB_MAX_DEVICE].
  750. */
  751. #ifndef CONFIG_DM_USB
  752. /* returns a pointer to the device with the index [index].
  753. * if the device is not assigned (dev->devnum==-1) returns NULL
  754. */
  755. struct usb_device *usb_get_dev_index(int index)
  756. {
  757. if (usb_dev[index].devnum == -1)
  758. return NULL;
  759. else
  760. return &usb_dev[index];
  761. }
  762. int usb_alloc_new_device(struct udevice *controller, struct usb_device **devp)
  763. {
  764. int i;
  765. debug("New Device %d\n", dev_index);
  766. if (dev_index == USB_MAX_DEVICE) {
  767. printf("ERROR, too many USB Devices, max=%d\n", USB_MAX_DEVICE);
  768. return -ENOSPC;
  769. }
  770. /* default Address is 0, real addresses start with 1 */
  771. usb_dev[dev_index].devnum = dev_index + 1;
  772. usb_dev[dev_index].maxchild = 0;
  773. for (i = 0; i < USB_MAXCHILDREN; i++)
  774. usb_dev[dev_index].children[i] = NULL;
  775. usb_dev[dev_index].parent = NULL;
  776. usb_dev[dev_index].controller = controller;
  777. dev_index++;
  778. *devp = &usb_dev[dev_index - 1];
  779. return 0;
  780. }
  781. /*
  782. * Free the newly created device node.
  783. * Called in error cases where configuring a newly attached
  784. * device fails for some reason.
  785. */
  786. void usb_free_device(struct udevice *controller)
  787. {
  788. dev_index--;
  789. debug("Freeing device node: %d\n", dev_index);
  790. memset(&usb_dev[dev_index], 0, sizeof(struct usb_device));
  791. usb_dev[dev_index].devnum = -1;
  792. }
  793. /*
  794. * XHCI issues Enable Slot command and thereafter
  795. * allocates device contexts. Provide a weak alias
  796. * function for the purpose, so that XHCI overrides it
  797. * and EHCI/OHCI just work out of the box.
  798. */
  799. __weak int usb_alloc_device(struct usb_device *udev)
  800. {
  801. return 0;
  802. }
  803. #endif /* !CONFIG_DM_USB */
  804. #ifndef CONFIG_DM_USB
  805. int usb_legacy_port_reset(struct usb_device *hub, int portnr)
  806. {
  807. if (hub) {
  808. unsigned short portstatus;
  809. int err;
  810. /* reset the port for the second time */
  811. err = legacy_hub_port_reset(hub, portnr - 1, &portstatus);
  812. if (err < 0) {
  813. printf("\n Couldn't reset port %i\n", portnr);
  814. return err;
  815. }
  816. } else {
  817. usb_reset_root_port();
  818. }
  819. return 0;
  820. }
  821. #endif
  822. static int get_descriptor_len(struct usb_device *dev, int len, int expect_len)
  823. {
  824. __maybe_unused struct usb_device_descriptor *desc;
  825. ALLOC_CACHE_ALIGN_BUFFER(unsigned char, tmpbuf, USB_BUFSIZ);
  826. int err;
  827. desc = (struct usb_device_descriptor *)tmpbuf;
  828. err = usb_get_descriptor(dev, USB_DT_DEVICE, 0, desc, len);
  829. if (err < expect_len) {
  830. if (err < 0) {
  831. printf("unable to get device descriptor (error=%d)\n",
  832. err);
  833. return err;
  834. } else {
  835. printf("USB device descriptor short read (expected %i, got %i)\n",
  836. expect_len, err);
  837. return -EIO;
  838. }
  839. }
  840. memcpy(&dev->descriptor, tmpbuf, sizeof(dev->descriptor));
  841. return 0;
  842. }
  843. static int usb_setup_descriptor(struct usb_device *dev, bool do_read)
  844. {
  845. /*
  846. * This is a Windows scheme of initialization sequence, with double
  847. * reset of the device (Linux uses the same sequence)
  848. * Some equipment is said to work only with such init sequence; this
  849. * patch is based on the work by Alan Stern:
  850. * http://sourceforge.net/mailarchive/forum.php?
  851. * thread_id=5729457&forum_id=5398
  852. */
  853. /*
  854. * send 64-byte GET-DEVICE-DESCRIPTOR request. Since the descriptor is
  855. * only 18 bytes long, this will terminate with a short packet. But if
  856. * the maxpacket size is 8 or 16 the device may be waiting to transmit
  857. * some more, or keeps on retransmitting the 8 byte header.
  858. */
  859. if (dev->speed == USB_SPEED_LOW) {
  860. dev->descriptor.bMaxPacketSize0 = 8;
  861. dev->maxpacketsize = PACKET_SIZE_8;
  862. } else {
  863. dev->descriptor.bMaxPacketSize0 = 64;
  864. dev->maxpacketsize = PACKET_SIZE_64;
  865. }
  866. dev->epmaxpacketin[0] = dev->descriptor.bMaxPacketSize0;
  867. dev->epmaxpacketout[0] = dev->descriptor.bMaxPacketSize0;
  868. if (do_read) {
  869. int err;
  870. /*
  871. * Validate we've received only at least 8 bytes, not that we've
  872. * received the entire descriptor. The reasoning is:
  873. * - The code only uses fields in the first 8 bytes, so that's all we
  874. * need to have fetched at this stage.
  875. * - The smallest maxpacket size is 8 bytes. Before we know the actual
  876. * maxpacket the device uses, the USB controller may only accept a
  877. * single packet. Consequently we are only guaranteed to receive 1
  878. * packet (at least 8 bytes) even in a non-error case.
  879. *
  880. * At least the DWC2 controller needs to be programmed with the number
  881. * of packets in addition to the number of bytes. A request for 64
  882. * bytes of data with the maxpacket guessed as 64 (above) yields a
  883. * request for 1 packet.
  884. */
  885. err = get_descriptor_len(dev, 64, 8);
  886. if (err)
  887. return err;
  888. }
  889. dev->epmaxpacketin[0] = dev->descriptor.bMaxPacketSize0;
  890. dev->epmaxpacketout[0] = dev->descriptor.bMaxPacketSize0;
  891. switch (dev->descriptor.bMaxPacketSize0) {
  892. case 8:
  893. dev->maxpacketsize = PACKET_SIZE_8;
  894. break;
  895. case 16:
  896. dev->maxpacketsize = PACKET_SIZE_16;
  897. break;
  898. case 32:
  899. dev->maxpacketsize = PACKET_SIZE_32;
  900. break;
  901. case 64:
  902. dev->maxpacketsize = PACKET_SIZE_64;
  903. break;
  904. default:
  905. printf("usb_new_device: invalid max packet size\n");
  906. return -EIO;
  907. }
  908. return 0;
  909. }
  910. static int usb_prepare_device(struct usb_device *dev, int addr, bool do_read,
  911. struct usb_device *parent, int portnr)
  912. {
  913. int err;
  914. /*
  915. * Allocate usb 3.0 device context.
  916. * USB 3.0 (xHCI) protocol tries to allocate device slot
  917. * and related data structures first. This call does that.
  918. * Refer to sec 4.3.2 in xHCI spec rev1.0
  919. */
  920. err = usb_alloc_device(dev);
  921. if (err) {
  922. printf("Cannot allocate device context to get SLOT_ID\n");
  923. return err;
  924. }
  925. err = usb_setup_descriptor(dev, do_read);
  926. if (err)
  927. return err;
  928. err = usb_legacy_port_reset(parent, portnr);
  929. if (err)
  930. return err;
  931. dev->devnum = addr;
  932. err = usb_set_address(dev); /* set address */
  933. if (err < 0) {
  934. printf("\n USB device not accepting new address " \
  935. "(error=%lX)\n", dev->status);
  936. return err;
  937. }
  938. mdelay(10); /* Let the SET_ADDRESS settle */
  939. return 0;
  940. }
  941. int usb_select_config(struct usb_device *dev)
  942. {
  943. ALLOC_CACHE_ALIGN_BUFFER(unsigned char, tmpbuf, USB_BUFSIZ);
  944. int err;
  945. err = get_descriptor_len(dev, USB_DT_DEVICE_SIZE, USB_DT_DEVICE_SIZE);
  946. if (err)
  947. return err;
  948. /* correct le values */
  949. le16_to_cpus(&dev->descriptor.bcdUSB);
  950. le16_to_cpus(&dev->descriptor.idVendor);
  951. le16_to_cpus(&dev->descriptor.idProduct);
  952. le16_to_cpus(&dev->descriptor.bcdDevice);
  953. /* only support for one config for now */
  954. err = usb_get_configuration_no(dev, tmpbuf, 0);
  955. if (err < 0) {
  956. printf("usb_new_device: Cannot read configuration, " \
  957. "skipping device %04x:%04x\n",
  958. dev->descriptor.idVendor, dev->descriptor.idProduct);
  959. return err;
  960. }
  961. usb_parse_config(dev, tmpbuf, 0);
  962. usb_set_maxpacket(dev);
  963. /*
  964. * we set the default configuration here
  965. * This seems premature. If the driver wants a different configuration
  966. * it will need to select itself.
  967. */
  968. err = usb_set_configuration(dev, dev->config.desc.bConfigurationValue);
  969. if (err < 0) {
  970. printf("failed to set default configuration " \
  971. "len %d, status %lX\n", dev->act_len, dev->status);
  972. return err;
  973. }
  974. debug("new device strings: Mfr=%d, Product=%d, SerialNumber=%d\n",
  975. dev->descriptor.iManufacturer, dev->descriptor.iProduct,
  976. dev->descriptor.iSerialNumber);
  977. memset(dev->mf, 0, sizeof(dev->mf));
  978. memset(dev->prod, 0, sizeof(dev->prod));
  979. memset(dev->serial, 0, sizeof(dev->serial));
  980. if (dev->descriptor.iManufacturer)
  981. usb_string(dev, dev->descriptor.iManufacturer,
  982. dev->mf, sizeof(dev->mf));
  983. if (dev->descriptor.iProduct)
  984. usb_string(dev, dev->descriptor.iProduct,
  985. dev->prod, sizeof(dev->prod));
  986. if (dev->descriptor.iSerialNumber)
  987. usb_string(dev, dev->descriptor.iSerialNumber,
  988. dev->serial, sizeof(dev->serial));
  989. debug("Manufacturer %s\n", dev->mf);
  990. debug("Product %s\n", dev->prod);
  991. debug("SerialNumber %s\n", dev->serial);
  992. return 0;
  993. }
  994. int usb_setup_device(struct usb_device *dev, bool do_read,
  995. struct usb_device *parent, int portnr)
  996. {
  997. int addr;
  998. int ret;
  999. /* We still haven't set the Address yet */
  1000. addr = dev->devnum;
  1001. dev->devnum = 0;
  1002. ret = usb_prepare_device(dev, addr, do_read, parent, portnr);
  1003. if (ret)
  1004. return ret;
  1005. ret = usb_select_config(dev);
  1006. return ret;
  1007. }
  1008. #ifndef CONFIG_DM_USB
  1009. /*
  1010. * By the time we get here, the device has gotten a new device ID
  1011. * and is in the default state. We need to identify the thing and
  1012. * get the ball rolling..
  1013. *
  1014. * Returns 0 for success, != 0 for error.
  1015. */
  1016. int usb_new_device(struct usb_device *dev)
  1017. {
  1018. bool do_read = true;
  1019. int err;
  1020. /*
  1021. * XHCI needs to issue a Address device command to setup
  1022. * proper device context structures, before it can interact
  1023. * with the device. So a get_descriptor will fail before any
  1024. * of that is done for XHCI unlike EHCI.
  1025. */
  1026. #ifdef CONFIG_USB_XHCI
  1027. do_read = false;
  1028. #endif
  1029. err = usb_setup_device(dev, do_read, dev->parent, dev->portnr);
  1030. if (err)
  1031. return err;
  1032. /* Now probe if the device is a hub */
  1033. err = usb_hub_probe(dev, 0);
  1034. if (err < 0)
  1035. return err;
  1036. return 0;
  1037. }
  1038. #endif
  1039. __weak
  1040. int board_usb_init(int index, enum usb_init_type init)
  1041. {
  1042. return 0;
  1043. }
  1044. __weak
  1045. int board_usb_cleanup(int index, enum usb_init_type init)
  1046. {
  1047. return 0;
  1048. }
  1049. bool usb_device_has_child_on_port(struct usb_device *parent, int port)
  1050. {
  1051. #ifdef CONFIG_DM_USB
  1052. return false;
  1053. #else
  1054. return parent->children[port] != NULL;
  1055. #endif
  1056. }
  1057. /* EOF */