usb.c 33 KB

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