usb.c 34 KB

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