usb.c 34 KB

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