usb.c 32 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203
  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 transfered length if OK or -1 if error. The transfered 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 configuration cfgno and store it in the buffer
  507. */
  508. int usb_get_configuration_no(struct usb_device *dev,
  509. unsigned char *buffer, int cfgno)
  510. {
  511. int result;
  512. unsigned int length;
  513. struct usb_config_descriptor *config;
  514. config = (struct usb_config_descriptor *)&buffer[0];
  515. result = usb_get_descriptor(dev, USB_DT_CONFIG, cfgno, buffer, 9);
  516. if (result < 9) {
  517. if (result < 0)
  518. printf("unable to get descriptor, error %lX\n",
  519. dev->status);
  520. else
  521. printf("config descriptor too short " \
  522. "(expected %i, got %i)\n", 9, result);
  523. return -EIO;
  524. }
  525. length = le16_to_cpu(config->wTotalLength);
  526. if (length > USB_BUFSIZ) {
  527. printf("%s: failed to get descriptor - too long: %d\n",
  528. __func__, length);
  529. return -EIO;
  530. }
  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, length);
  533. config->wTotalLength = length; /* validated, with CPU byte order */
  534. return result;
  535. }
  536. /********************************************************************
  537. * set address of a device to the value in dev->devnum.
  538. * This can only be done by addressing the device via the default address (0)
  539. */
  540. static int usb_set_address(struct usb_device *dev)
  541. {
  542. int res;
  543. debug("set address %d\n", dev->devnum);
  544. res = usb_control_msg(dev, usb_snddefctrl(dev),
  545. USB_REQ_SET_ADDRESS, 0,
  546. (dev->devnum), 0,
  547. NULL, 0, USB_CNTL_TIMEOUT);
  548. return res;
  549. }
  550. /********************************************************************
  551. * set interface number to interface
  552. */
  553. int usb_set_interface(struct usb_device *dev, int interface, int alternate)
  554. {
  555. struct usb_interface *if_face = NULL;
  556. int ret, i;
  557. for (i = 0; i < dev->config.desc.bNumInterfaces; i++) {
  558. if (dev->config.if_desc[i].desc.bInterfaceNumber == interface) {
  559. if_face = &dev->config.if_desc[i];
  560. break;
  561. }
  562. }
  563. if (!if_face) {
  564. printf("selecting invalid interface %d", interface);
  565. return -EINVAL;
  566. }
  567. /*
  568. * We should return now for devices with only one alternate setting.
  569. * According to 9.4.10 of the Universal Serial Bus Specification
  570. * Revision 2.0 such devices can return with a STALL. This results in
  571. * some USB sticks timeouting during initialization and then being
  572. * unusable in U-Boot.
  573. */
  574. if (if_face->num_altsetting == 1)
  575. return 0;
  576. ret = usb_control_msg(dev, usb_sndctrlpipe(dev, 0),
  577. USB_REQ_SET_INTERFACE, USB_RECIP_INTERFACE,
  578. alternate, interface, NULL, 0,
  579. USB_CNTL_TIMEOUT * 5);
  580. if (ret < 0)
  581. return ret;
  582. return 0;
  583. }
  584. /********************************************************************
  585. * set configuration number to configuration
  586. */
  587. static int usb_set_configuration(struct usb_device *dev, int configuration)
  588. {
  589. int res;
  590. debug("set configuration %d\n", configuration);
  591. /* set setup command */
  592. res = usb_control_msg(dev, usb_sndctrlpipe(dev, 0),
  593. USB_REQ_SET_CONFIGURATION, 0,
  594. configuration, 0,
  595. NULL, 0, USB_CNTL_TIMEOUT);
  596. if (res == 0) {
  597. dev->toggle[0] = 0;
  598. dev->toggle[1] = 0;
  599. return 0;
  600. } else
  601. return -EIO;
  602. }
  603. /********************************************************************
  604. * set protocol to protocol
  605. */
  606. int usb_set_protocol(struct usb_device *dev, int ifnum, int protocol)
  607. {
  608. return usb_control_msg(dev, usb_sndctrlpipe(dev, 0),
  609. USB_REQ_SET_PROTOCOL, USB_TYPE_CLASS | USB_RECIP_INTERFACE,
  610. protocol, ifnum, NULL, 0, USB_CNTL_TIMEOUT);
  611. }
  612. /********************************************************************
  613. * set idle
  614. */
  615. int usb_set_idle(struct usb_device *dev, int ifnum, int duration, int report_id)
  616. {
  617. return usb_control_msg(dev, usb_sndctrlpipe(dev, 0),
  618. USB_REQ_SET_IDLE, USB_TYPE_CLASS | USB_RECIP_INTERFACE,
  619. (duration << 8) | report_id, ifnum, NULL, 0, USB_CNTL_TIMEOUT);
  620. }
  621. /********************************************************************
  622. * get report
  623. */
  624. int usb_get_report(struct usb_device *dev, int ifnum, unsigned char type,
  625. unsigned char id, void *buf, int size)
  626. {
  627. return usb_control_msg(dev, usb_rcvctrlpipe(dev, 0),
  628. USB_REQ_GET_REPORT,
  629. USB_DIR_IN | USB_TYPE_CLASS | USB_RECIP_INTERFACE,
  630. (type << 8) + id, ifnum, buf, size, USB_CNTL_TIMEOUT);
  631. }
  632. /********************************************************************
  633. * get class descriptor
  634. */
  635. int usb_get_class_descriptor(struct usb_device *dev, int ifnum,
  636. unsigned char type, unsigned char id, void *buf, int size)
  637. {
  638. return usb_control_msg(dev, usb_rcvctrlpipe(dev, 0),
  639. USB_REQ_GET_DESCRIPTOR, USB_RECIP_INTERFACE | USB_DIR_IN,
  640. (type << 8) + id, ifnum, buf, size, USB_CNTL_TIMEOUT);
  641. }
  642. /********************************************************************
  643. * get string index in buffer
  644. */
  645. static int usb_get_string(struct usb_device *dev, unsigned short langid,
  646. unsigned char index, void *buf, int size)
  647. {
  648. int i;
  649. int result;
  650. for (i = 0; i < 3; ++i) {
  651. /* some devices are flaky */
  652. result = usb_control_msg(dev, usb_rcvctrlpipe(dev, 0),
  653. USB_REQ_GET_DESCRIPTOR, USB_DIR_IN,
  654. (USB_DT_STRING << 8) + index, langid, buf, size,
  655. USB_CNTL_TIMEOUT);
  656. if (result > 0)
  657. break;
  658. }
  659. return result;
  660. }
  661. static void usb_try_string_workarounds(unsigned char *buf, int *length)
  662. {
  663. int newlength, oldlength = *length;
  664. for (newlength = 2; newlength + 1 < oldlength; newlength += 2)
  665. if (!isprint(buf[newlength]) || buf[newlength + 1])
  666. break;
  667. if (newlength > 2) {
  668. buf[0] = newlength;
  669. *length = newlength;
  670. }
  671. }
  672. static int usb_string_sub(struct usb_device *dev, unsigned int langid,
  673. unsigned int index, unsigned char *buf)
  674. {
  675. int rc;
  676. /* Try to read the string descriptor by asking for the maximum
  677. * possible number of bytes */
  678. rc = usb_get_string(dev, langid, index, buf, 255);
  679. /* If that failed try to read the descriptor length, then
  680. * ask for just that many bytes */
  681. if (rc < 2) {
  682. rc = usb_get_string(dev, langid, index, buf, 2);
  683. if (rc == 2)
  684. rc = usb_get_string(dev, langid, index, buf, buf[0]);
  685. }
  686. if (rc >= 2) {
  687. if (!buf[0] && !buf[1])
  688. usb_try_string_workarounds(buf, &rc);
  689. /* There might be extra junk at the end of the descriptor */
  690. if (buf[0] < rc)
  691. rc = buf[0];
  692. rc = rc - (rc & 1); /* force a multiple of two */
  693. }
  694. if (rc < 2)
  695. rc = -EINVAL;
  696. return rc;
  697. }
  698. /********************************************************************
  699. * usb_string:
  700. * Get string index and translate it to ascii.
  701. * returns string length (> 0) or error (< 0)
  702. */
  703. int usb_string(struct usb_device *dev, int index, char *buf, size_t size)
  704. {
  705. ALLOC_CACHE_ALIGN_BUFFER(unsigned char, mybuf, USB_BUFSIZ);
  706. unsigned char *tbuf;
  707. int err;
  708. unsigned int u, idx;
  709. if (size <= 0 || !buf || !index)
  710. return -EINVAL;
  711. buf[0] = 0;
  712. tbuf = &mybuf[0];
  713. /* get langid for strings if it's not yet known */
  714. if (!dev->have_langid) {
  715. err = usb_string_sub(dev, 0, 0, tbuf);
  716. if (err < 0) {
  717. debug("error getting string descriptor 0 " \
  718. "(error=%lx)\n", dev->status);
  719. return -EIO;
  720. } else if (tbuf[0] < 4) {
  721. debug("string descriptor 0 too short\n");
  722. return -EIO;
  723. } else {
  724. dev->have_langid = -1;
  725. dev->string_langid = tbuf[2] | (tbuf[3] << 8);
  726. /* always use the first langid listed */
  727. debug("USB device number %d default " \
  728. "language ID 0x%x\n",
  729. dev->devnum, dev->string_langid);
  730. }
  731. }
  732. err = usb_string_sub(dev, dev->string_langid, index, tbuf);
  733. if (err < 0)
  734. return err;
  735. size--; /* leave room for trailing NULL char in output buffer */
  736. for (idx = 0, u = 2; u < err; u += 2) {
  737. if (idx >= size)
  738. break;
  739. if (tbuf[u+1]) /* high byte */
  740. buf[idx++] = '?'; /* non-ASCII character */
  741. else
  742. buf[idx++] = tbuf[u];
  743. }
  744. buf[idx] = 0;
  745. err = idx;
  746. return err;
  747. }
  748. /********************************************************************
  749. * USB device handling:
  750. * the USB device are static allocated [USB_MAX_DEVICE].
  751. */
  752. #ifndef CONFIG_DM_USB
  753. /* returns a pointer to the device with the index [index].
  754. * if the device is not assigned (dev->devnum==-1) returns NULL
  755. */
  756. struct usb_device *usb_get_dev_index(int index)
  757. {
  758. if (usb_dev[index].devnum == -1)
  759. return NULL;
  760. else
  761. return &usb_dev[index];
  762. }
  763. int usb_alloc_new_device(struct udevice *controller, struct usb_device **devp)
  764. {
  765. int i;
  766. debug("New Device %d\n", dev_index);
  767. if (dev_index == USB_MAX_DEVICE) {
  768. printf("ERROR, too many USB Devices, max=%d\n", USB_MAX_DEVICE);
  769. return -ENOSPC;
  770. }
  771. /* default Address is 0, real addresses start with 1 */
  772. usb_dev[dev_index].devnum = dev_index + 1;
  773. usb_dev[dev_index].maxchild = 0;
  774. for (i = 0; i < USB_MAXCHILDREN; i++)
  775. usb_dev[dev_index].children[i] = NULL;
  776. usb_dev[dev_index].parent = NULL;
  777. usb_dev[dev_index].controller = controller;
  778. dev_index++;
  779. *devp = &usb_dev[dev_index - 1];
  780. return 0;
  781. }
  782. /*
  783. * Free the newly created device node.
  784. * Called in error cases where configuring a newly attached
  785. * device fails for some reason.
  786. */
  787. void usb_free_device(struct udevice *controller)
  788. {
  789. dev_index--;
  790. debug("Freeing device node: %d\n", dev_index);
  791. memset(&usb_dev[dev_index], 0, sizeof(struct usb_device));
  792. usb_dev[dev_index].devnum = -1;
  793. }
  794. /*
  795. * XHCI issues Enable Slot command and thereafter
  796. * allocates device contexts. Provide a weak alias
  797. * function for the purpose, so that XHCI overrides it
  798. * and EHCI/OHCI just work out of the box.
  799. */
  800. __weak int usb_alloc_device(struct usb_device *udev)
  801. {
  802. return 0;
  803. }
  804. #endif /* !CONFIG_DM_USB */
  805. static int usb_hub_port_reset(struct usb_device *dev, struct usb_device *hub)
  806. {
  807. if (hub) {
  808. unsigned short portstatus;
  809. int err;
  810. /* reset the port for the second time */
  811. err = legacy_hub_port_reset(hub, dev->portnr - 1, &portstatus);
  812. if (err < 0) {
  813. printf("\n Couldn't reset port %i\n", dev->portnr);
  814. return err;
  815. }
  816. } else {
  817. usb_reset_root_port(dev);
  818. }
  819. return 0;
  820. }
  821. static int get_descriptor_len(struct usb_device *dev, int len, int expect_len)
  822. {
  823. __maybe_unused struct usb_device_descriptor *desc;
  824. ALLOC_CACHE_ALIGN_BUFFER(unsigned char, tmpbuf, USB_BUFSIZ);
  825. int err;
  826. desc = (struct usb_device_descriptor *)tmpbuf;
  827. err = usb_get_descriptor(dev, USB_DT_DEVICE, 0, desc, len);
  828. if (err < expect_len) {
  829. if (err < 0) {
  830. printf("unable to get device descriptor (error=%d)\n",
  831. err);
  832. return err;
  833. } else {
  834. printf("USB device descriptor short read (expected %i, got %i)\n",
  835. expect_len, err);
  836. return -EIO;
  837. }
  838. }
  839. memcpy(&dev->descriptor, tmpbuf, sizeof(dev->descriptor));
  840. return 0;
  841. }
  842. static int usb_setup_descriptor(struct usb_device *dev, bool do_read)
  843. {
  844. /*
  845. * This is a Windows scheme of initialization sequence, with double
  846. * reset of the device (Linux uses the same sequence)
  847. * Some equipment is said to work only with such init sequence; this
  848. * patch is based on the work by Alan Stern:
  849. * http://sourceforge.net/mailarchive/forum.php?
  850. * thread_id=5729457&forum_id=5398
  851. */
  852. /*
  853. * send 64-byte GET-DEVICE-DESCRIPTOR request. Since the descriptor is
  854. * only 18 bytes long, this will terminate with a short packet. But if
  855. * the maxpacket size is 8 or 16 the device may be waiting to transmit
  856. * some more, or keeps on retransmitting the 8 byte header.
  857. */
  858. if (dev->speed == USB_SPEED_LOW) {
  859. dev->descriptor.bMaxPacketSize0 = 8;
  860. dev->maxpacketsize = PACKET_SIZE_8;
  861. } else {
  862. dev->descriptor.bMaxPacketSize0 = 64;
  863. dev->maxpacketsize = PACKET_SIZE_64;
  864. }
  865. dev->epmaxpacketin[0] = dev->descriptor.bMaxPacketSize0;
  866. dev->epmaxpacketout[0] = dev->descriptor.bMaxPacketSize0;
  867. if (do_read) {
  868. int err;
  869. /*
  870. * Validate we've received only at least 8 bytes, not that we've
  871. * received the entire descriptor. The reasoning is:
  872. * - The code only uses fields in the first 8 bytes, so that's all we
  873. * need to have fetched at this stage.
  874. * - The smallest maxpacket size is 8 bytes. Before we know the actual
  875. * maxpacket the device uses, the USB controller may only accept a
  876. * single packet. Consequently we are only guaranteed to receive 1
  877. * packet (at least 8 bytes) even in a non-error case.
  878. *
  879. * At least the DWC2 controller needs to be programmed with the number
  880. * of packets in addition to the number of bytes. A request for 64
  881. * bytes of data with the maxpacket guessed as 64 (above) yields a
  882. * request for 1 packet.
  883. */
  884. err = get_descriptor_len(dev, 64, 8);
  885. if (err)
  886. return err;
  887. }
  888. dev->epmaxpacketin[0] = dev->descriptor.bMaxPacketSize0;
  889. dev->epmaxpacketout[0] = dev->descriptor.bMaxPacketSize0;
  890. switch (dev->descriptor.bMaxPacketSize0) {
  891. case 8:
  892. dev->maxpacketsize = PACKET_SIZE_8;
  893. break;
  894. case 16:
  895. dev->maxpacketsize = PACKET_SIZE_16;
  896. break;
  897. case 32:
  898. dev->maxpacketsize = PACKET_SIZE_32;
  899. break;
  900. case 64:
  901. dev->maxpacketsize = PACKET_SIZE_64;
  902. break;
  903. default:
  904. printf("usb_new_device: invalid max packet size\n");
  905. return -EIO;
  906. }
  907. return 0;
  908. }
  909. static int usb_prepare_device(struct usb_device *dev, int addr, bool do_read,
  910. struct usb_device *parent)
  911. {
  912. int err;
  913. /*
  914. * Allocate usb 3.0 device context.
  915. * USB 3.0 (xHCI) protocol tries to allocate device slot
  916. * and related data structures first. This call does that.
  917. * Refer to sec 4.3.2 in xHCI spec rev1.0
  918. */
  919. err = usb_alloc_device(dev);
  920. if (err) {
  921. printf("Cannot allocate device context to get SLOT_ID\n");
  922. return err;
  923. }
  924. err = usb_setup_descriptor(dev, do_read);
  925. if (err)
  926. return err;
  927. err = usb_hub_port_reset(dev, parent);
  928. if (err)
  929. return err;
  930. dev->devnum = addr;
  931. err = usb_set_address(dev); /* set address */
  932. if (err < 0) {
  933. printf("\n USB device not accepting new address " \
  934. "(error=%lX)\n", dev->status);
  935. return err;
  936. }
  937. mdelay(10); /* Let the SET_ADDRESS settle */
  938. return 0;
  939. }
  940. int usb_select_config(struct usb_device *dev)
  941. {
  942. ALLOC_CACHE_ALIGN_BUFFER(unsigned char, tmpbuf, USB_BUFSIZ);
  943. int err;
  944. err = get_descriptor_len(dev, USB_DT_DEVICE_SIZE, USB_DT_DEVICE_SIZE);
  945. if (err)
  946. return err;
  947. /* correct le values */
  948. le16_to_cpus(&dev->descriptor.bcdUSB);
  949. le16_to_cpus(&dev->descriptor.idVendor);
  950. le16_to_cpus(&dev->descriptor.idProduct);
  951. le16_to_cpus(&dev->descriptor.bcdDevice);
  952. /* only support for one config for now */
  953. err = usb_get_configuration_no(dev, tmpbuf, 0);
  954. if (err < 0) {
  955. printf("usb_new_device: Cannot read configuration, " \
  956. "skipping device %04x:%04x\n",
  957. dev->descriptor.idVendor, dev->descriptor.idProduct);
  958. return err;
  959. }
  960. usb_parse_config(dev, tmpbuf, 0);
  961. usb_set_maxpacket(dev);
  962. /*
  963. * we set the default configuration here
  964. * This seems premature. If the driver wants a different configuration
  965. * it will need to select itself.
  966. */
  967. err = usb_set_configuration(dev, dev->config.desc.bConfigurationValue);
  968. if (err < 0) {
  969. printf("failed to set default configuration " \
  970. "len %d, status %lX\n", dev->act_len, dev->status);
  971. return err;
  972. }
  973. debug("new device strings: Mfr=%d, Product=%d, SerialNumber=%d\n",
  974. dev->descriptor.iManufacturer, dev->descriptor.iProduct,
  975. dev->descriptor.iSerialNumber);
  976. memset(dev->mf, 0, sizeof(dev->mf));
  977. memset(dev->prod, 0, sizeof(dev->prod));
  978. memset(dev->serial, 0, sizeof(dev->serial));
  979. if (dev->descriptor.iManufacturer)
  980. usb_string(dev, dev->descriptor.iManufacturer,
  981. dev->mf, sizeof(dev->mf));
  982. if (dev->descriptor.iProduct)
  983. usb_string(dev, dev->descriptor.iProduct,
  984. dev->prod, sizeof(dev->prod));
  985. if (dev->descriptor.iSerialNumber)
  986. usb_string(dev, dev->descriptor.iSerialNumber,
  987. dev->serial, sizeof(dev->serial));
  988. debug("Manufacturer %s\n", dev->mf);
  989. debug("Product %s\n", dev->prod);
  990. debug("SerialNumber %s\n", dev->serial);
  991. return 0;
  992. }
  993. int usb_setup_device(struct usb_device *dev, bool do_read,
  994. struct usb_device *parent)
  995. {
  996. int addr;
  997. int ret;
  998. /* We still haven't set the Address yet */
  999. addr = dev->devnum;
  1000. dev->devnum = 0;
  1001. ret = usb_prepare_device(dev, addr, do_read, parent);
  1002. if (ret)
  1003. return ret;
  1004. ret = usb_select_config(dev);
  1005. return ret;
  1006. }
  1007. #ifndef CONFIG_DM_USB
  1008. /*
  1009. * By the time we get here, the device has gotten a new device ID
  1010. * and is in the default state. We need to identify the thing and
  1011. * get the ball rolling..
  1012. *
  1013. * Returns 0 for success, != 0 for error.
  1014. */
  1015. int usb_new_device(struct usb_device *dev)
  1016. {
  1017. bool do_read = true;
  1018. int err;
  1019. /*
  1020. * XHCI needs to issue a Address device command to setup
  1021. * proper device context structures, before it can interact
  1022. * with the device. So a get_descriptor will fail before any
  1023. * of that is done for XHCI unlike EHCI.
  1024. */
  1025. #ifdef CONFIG_USB_XHCI
  1026. do_read = false;
  1027. #endif
  1028. err = usb_setup_device(dev, do_read, dev->parent);
  1029. if (err)
  1030. return err;
  1031. /* Now probe if the device is a hub */
  1032. err = usb_hub_probe(dev, 0);
  1033. if (err < 0)
  1034. return err;
  1035. return 0;
  1036. }
  1037. #endif
  1038. __weak
  1039. int board_usb_init(int index, enum usb_init_type init)
  1040. {
  1041. return 0;
  1042. }
  1043. __weak
  1044. int board_usb_cleanup(int index, enum usb_init_type init)
  1045. {
  1046. return 0;
  1047. }
  1048. bool usb_device_has_child_on_port(struct usb_device *parent, int port)
  1049. {
  1050. #ifdef CONFIG_DM_USB
  1051. return false;
  1052. #else
  1053. return parent->children[port] != NULL;
  1054. #endif
  1055. }
  1056. /* EOF */