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