usb.c 34 KB

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