usb.c 32 KB

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