usb.c 31 KB

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