usb.c 31 KB

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