usb.c 31 KB

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