xref: /openbmc/linux/drivers/usb/core/hub.c (revision 54d8c1d3)
1 // SPDX-License-Identifier: GPL-2.0
2 /*
3  * USB hub driver.
4  *
5  * (C) Copyright 1999 Linus Torvalds
6  * (C) Copyright 1999 Johannes Erdfelt
7  * (C) Copyright 1999 Gregory P. Smith
8  * (C) Copyright 2001 Brad Hards (bhards@bigpond.net.au)
9  *
10  * Released under the GPLv2 only.
11  */
12 
13 #include <linux/kernel.h>
14 #include <linux/errno.h>
15 #include <linux/module.h>
16 #include <linux/moduleparam.h>
17 #include <linux/completion.h>
18 #include <linux/sched/mm.h>
19 #include <linux/list.h>
20 #include <linux/slab.h>
21 #include <linux/kcov.h>
22 #include <linux/ioctl.h>
23 #include <linux/usb.h>
24 #include <linux/usbdevice_fs.h>
25 #include <linux/usb/hcd.h>
26 #include <linux/usb/onboard_hub.h>
27 #include <linux/usb/otg.h>
28 #include <linux/usb/quirks.h>
29 #include <linux/workqueue.h>
30 #include <linux/mutex.h>
31 #include <linux/random.h>
32 #include <linux/pm_qos.h>
33 #include <linux/kobject.h>
34 
35 #include <linux/bitfield.h>
36 #include <linux/uaccess.h>
37 #include <asm/byteorder.h>
38 
39 #include "hub.h"
40 #include "otg_productlist.h"
41 
42 #define USB_VENDOR_GENESYS_LOGIC		0x05e3
43 #define USB_VENDOR_SMSC				0x0424
44 #define USB_PRODUCT_USB5534B			0x5534
45 #define USB_VENDOR_CYPRESS			0x04b4
46 #define USB_PRODUCT_CY7C65632			0x6570
47 #define USB_VENDOR_TEXAS_INSTRUMENTS		0x0451
48 #define USB_PRODUCT_TUSB8041_USB3		0x8140
49 #define USB_PRODUCT_TUSB8041_USB2		0x8142
50 #define HUB_QUIRK_CHECK_PORT_AUTOSUSPEND	0x01
51 #define HUB_QUIRK_DISABLE_AUTOSUSPEND		0x02
52 
53 #define USB_TP_TRANSMISSION_DELAY	40	/* ns */
54 #define USB_TP_TRANSMISSION_DELAY_MAX	65535	/* ns */
55 #define USB_PING_RESPONSE_TIME		400	/* ns */
56 
57 /* Protect struct usb_device->state and ->children members
58  * Note: Both are also protected by ->dev.sem, except that ->state can
59  * change to USB_STATE_NOTATTACHED even when the semaphore isn't held. */
60 static DEFINE_SPINLOCK(device_state_lock);
61 
62 /* workqueue to process hub events */
63 static struct workqueue_struct *hub_wq;
64 static void hub_event(struct work_struct *work);
65 
66 /* synchronize hub-port add/remove and peering operations */
67 DEFINE_MUTEX(usb_port_peer_mutex);
68 
69 /* cycle leds on hubs that aren't blinking for attention */
70 static bool blinkenlights;
71 module_param(blinkenlights, bool, S_IRUGO);
72 MODULE_PARM_DESC(blinkenlights, "true to cycle leds on hubs");
73 
74 /*
75  * Device SATA8000 FW1.0 from DATAST0R Technology Corp requires about
76  * 10 seconds to send reply for the initial 64-byte descriptor request.
77  */
78 /* define initial 64-byte descriptor request timeout in milliseconds */
79 static int initial_descriptor_timeout = USB_CTRL_GET_TIMEOUT;
80 module_param(initial_descriptor_timeout, int, S_IRUGO|S_IWUSR);
81 MODULE_PARM_DESC(initial_descriptor_timeout,
82 		"initial 64-byte descriptor request timeout in milliseconds "
83 		"(default 5000 - 5.0 seconds)");
84 
85 /*
86  * As of 2.6.10 we introduce a new USB device initialization scheme which
87  * closely resembles the way Windows works.  Hopefully it will be compatible
88  * with a wider range of devices than the old scheme.  However some previously
89  * working devices may start giving rise to "device not accepting address"
90  * errors; if that happens the user can try the old scheme by adjusting the
91  * following module parameters.
92  *
93  * For maximum flexibility there are two boolean parameters to control the
94  * hub driver's behavior.  On the first initialization attempt, if the
95  * "old_scheme_first" parameter is set then the old scheme will be used,
96  * otherwise the new scheme is used.  If that fails and "use_both_schemes"
97  * is set, then the driver will make another attempt, using the other scheme.
98  */
99 static bool old_scheme_first;
100 module_param(old_scheme_first, bool, S_IRUGO | S_IWUSR);
101 MODULE_PARM_DESC(old_scheme_first,
102 		 "start with the old device initialization scheme");
103 
104 static bool use_both_schemes = true;
105 module_param(use_both_schemes, bool, S_IRUGO | S_IWUSR);
106 MODULE_PARM_DESC(use_both_schemes,
107 		"try the other device initialization scheme if the "
108 		"first one fails");
109 
110 /* Mutual exclusion for EHCI CF initialization.  This interferes with
111  * port reset on some companion controllers.
112  */
113 DECLARE_RWSEM(ehci_cf_port_reset_rwsem);
114 EXPORT_SYMBOL_GPL(ehci_cf_port_reset_rwsem);
115 
116 #define HUB_DEBOUNCE_TIMEOUT	2000
117 #define HUB_DEBOUNCE_STEP	  25
118 #define HUB_DEBOUNCE_STABLE	 100
119 
120 static void hub_release(struct kref *kref);
121 static int usb_reset_and_verify_device(struct usb_device *udev);
122 static int hub_port_disable(struct usb_hub *hub, int port1, int set_state);
123 static bool hub_port_warm_reset_required(struct usb_hub *hub, int port1,
124 		u16 portstatus);
125 
126 static inline char *portspeed(struct usb_hub *hub, int portstatus)
127 {
128 	if (hub_is_superspeedplus(hub->hdev))
129 		return "10.0 Gb/s";
130 	if (hub_is_superspeed(hub->hdev))
131 		return "5.0 Gb/s";
132 	if (portstatus & USB_PORT_STAT_HIGH_SPEED)
133 		return "480 Mb/s";
134 	else if (portstatus & USB_PORT_STAT_LOW_SPEED)
135 		return "1.5 Mb/s";
136 	else
137 		return "12 Mb/s";
138 }
139 
140 /* Note that hdev or one of its children must be locked! */
141 struct usb_hub *usb_hub_to_struct_hub(struct usb_device *hdev)
142 {
143 	if (!hdev || !hdev->actconfig || !hdev->maxchild)
144 		return NULL;
145 	return usb_get_intfdata(hdev->actconfig->interface[0]);
146 }
147 
148 int usb_device_supports_lpm(struct usb_device *udev)
149 {
150 	/* Some devices have trouble with LPM */
151 	if (udev->quirks & USB_QUIRK_NO_LPM)
152 		return 0;
153 
154 	/* Skip if the device BOS descriptor couldn't be read */
155 	if (!udev->bos)
156 		return 0;
157 
158 	/* USB 2.1 (and greater) devices indicate LPM support through
159 	 * their USB 2.0 Extended Capabilities BOS descriptor.
160 	 */
161 	if (udev->speed == USB_SPEED_HIGH || udev->speed == USB_SPEED_FULL) {
162 		if (udev->bos->ext_cap &&
163 			(USB_LPM_SUPPORT &
164 			 le32_to_cpu(udev->bos->ext_cap->bmAttributes)))
165 			return 1;
166 		return 0;
167 	}
168 
169 	/*
170 	 * According to the USB 3.0 spec, all USB 3.0 devices must support LPM.
171 	 * However, there are some that don't, and they set the U1/U2 exit
172 	 * latencies to zero.
173 	 */
174 	if (!udev->bos->ss_cap) {
175 		dev_info(&udev->dev, "No LPM exit latency info found, disabling LPM.\n");
176 		return 0;
177 	}
178 
179 	if (udev->bos->ss_cap->bU1devExitLat == 0 &&
180 			udev->bos->ss_cap->bU2DevExitLat == 0) {
181 		if (udev->parent)
182 			dev_info(&udev->dev, "LPM exit latency is zeroed, disabling LPM.\n");
183 		else
184 			dev_info(&udev->dev, "We don't know the algorithms for LPM for this host, disabling LPM.\n");
185 		return 0;
186 	}
187 
188 	if (!udev->parent || udev->parent->lpm_capable)
189 		return 1;
190 	return 0;
191 }
192 
193 /*
194  * Set the Maximum Exit Latency (MEL) for the host to wakup up the path from
195  * U1/U2, send a PING to the device and receive a PING_RESPONSE.
196  * See USB 3.1 section C.1.5.2
197  */
198 static void usb_set_lpm_mel(struct usb_device *udev,
199 		struct usb3_lpm_parameters *udev_lpm_params,
200 		unsigned int udev_exit_latency,
201 		struct usb_hub *hub,
202 		struct usb3_lpm_parameters *hub_lpm_params,
203 		unsigned int hub_exit_latency)
204 {
205 	unsigned int total_mel;
206 
207 	/*
208 	 * tMEL1. time to transition path from host to device into U0.
209 	 * MEL for parent already contains the delay up to parent, so only add
210 	 * the exit latency for the last link (pick the slower exit latency),
211 	 * and the hub header decode latency. See USB 3.1 section C 2.2.1
212 	 * Store MEL in nanoseconds
213 	 */
214 	total_mel = hub_lpm_params->mel +
215 		max(udev_exit_latency, hub_exit_latency) * 1000 +
216 		hub->descriptor->u.ss.bHubHdrDecLat * 100;
217 
218 	/*
219 	 * tMEL2. Time to submit PING packet. Sum of tTPTransmissionDelay for
220 	 * each link + wHubDelay for each hub. Add only for last link.
221 	 * tMEL4, the time for PING_RESPONSE to traverse upstream is similar.
222 	 * Multiply by 2 to include it as well.
223 	 */
224 	total_mel += (__le16_to_cpu(hub->descriptor->u.ss.wHubDelay) +
225 		      USB_TP_TRANSMISSION_DELAY) * 2;
226 
227 	/*
228 	 * tMEL3, tPingResponse. Time taken by device to generate PING_RESPONSE
229 	 * after receiving PING. Also add 2100ns as stated in USB 3.1 C 1.5.2.4
230 	 * to cover the delay if the PING_RESPONSE is queued behind a Max Packet
231 	 * Size DP.
232 	 * Note these delays should be added only once for the entire path, so
233 	 * add them to the MEL of the device connected to the roothub.
234 	 */
235 	if (!hub->hdev->parent)
236 		total_mel += USB_PING_RESPONSE_TIME + 2100;
237 
238 	udev_lpm_params->mel = total_mel;
239 }
240 
241 /*
242  * Set the maximum Device to Host Exit Latency (PEL) for the device to initiate
243  * a transition from either U1 or U2.
244  */
245 static void usb_set_lpm_pel(struct usb_device *udev,
246 		struct usb3_lpm_parameters *udev_lpm_params,
247 		unsigned int udev_exit_latency,
248 		struct usb_hub *hub,
249 		struct usb3_lpm_parameters *hub_lpm_params,
250 		unsigned int hub_exit_latency,
251 		unsigned int port_to_port_exit_latency)
252 {
253 	unsigned int first_link_pel;
254 	unsigned int hub_pel;
255 
256 	/*
257 	 * First, the device sends an LFPS to transition the link between the
258 	 * device and the parent hub into U0.  The exit latency is the bigger of
259 	 * the device exit latency or the hub exit latency.
260 	 */
261 	if (udev_exit_latency > hub_exit_latency)
262 		first_link_pel = udev_exit_latency * 1000;
263 	else
264 		first_link_pel = hub_exit_latency * 1000;
265 
266 	/*
267 	 * When the hub starts to receive the LFPS, there is a slight delay for
268 	 * it to figure out that one of the ports is sending an LFPS.  Then it
269 	 * will forward the LFPS to its upstream link.  The exit latency is the
270 	 * delay, plus the PEL that we calculated for this hub.
271 	 */
272 	hub_pel = port_to_port_exit_latency * 1000 + hub_lpm_params->pel;
273 
274 	/*
275 	 * According to figure C-7 in the USB 3.0 spec, the PEL for this device
276 	 * is the greater of the two exit latencies.
277 	 */
278 	if (first_link_pel > hub_pel)
279 		udev_lpm_params->pel = first_link_pel;
280 	else
281 		udev_lpm_params->pel = hub_pel;
282 }
283 
284 /*
285  * Set the System Exit Latency (SEL) to indicate the total worst-case time from
286  * when a device initiates a transition to U0, until when it will receive the
287  * first packet from the host controller.
288  *
289  * Section C.1.5.1 describes the four components to this:
290  *  - t1: device PEL
291  *  - t2: time for the ERDY to make it from the device to the host.
292  *  - t3: a host-specific delay to process the ERDY.
293  *  - t4: time for the packet to make it from the host to the device.
294  *
295  * t3 is specific to both the xHCI host and the platform the host is integrated
296  * into.  The Intel HW folks have said it's negligible, FIXME if a different
297  * vendor says otherwise.
298  */
299 static void usb_set_lpm_sel(struct usb_device *udev,
300 		struct usb3_lpm_parameters *udev_lpm_params)
301 {
302 	struct usb_device *parent;
303 	unsigned int num_hubs;
304 	unsigned int total_sel;
305 
306 	/* t1 = device PEL */
307 	total_sel = udev_lpm_params->pel;
308 	/* How many external hubs are in between the device & the root port. */
309 	for (parent = udev->parent, num_hubs = 0; parent->parent;
310 			parent = parent->parent)
311 		num_hubs++;
312 	/* t2 = 2.1us + 250ns * (num_hubs - 1) */
313 	if (num_hubs > 0)
314 		total_sel += 2100 + 250 * (num_hubs - 1);
315 
316 	/* t4 = 250ns * num_hubs */
317 	total_sel += 250 * num_hubs;
318 
319 	udev_lpm_params->sel = total_sel;
320 }
321 
322 static void usb_set_lpm_parameters(struct usb_device *udev)
323 {
324 	struct usb_hub *hub;
325 	unsigned int port_to_port_delay;
326 	unsigned int udev_u1_del;
327 	unsigned int udev_u2_del;
328 	unsigned int hub_u1_del;
329 	unsigned int hub_u2_del;
330 
331 	if (!udev->lpm_capable || udev->speed < USB_SPEED_SUPER)
332 		return;
333 
334 	/* Skip if the device BOS descriptor couldn't be read */
335 	if (!udev->bos)
336 		return;
337 
338 	hub = usb_hub_to_struct_hub(udev->parent);
339 	/* It doesn't take time to transition the roothub into U0, since it
340 	 * doesn't have an upstream link.
341 	 */
342 	if (!hub)
343 		return;
344 
345 	udev_u1_del = udev->bos->ss_cap->bU1devExitLat;
346 	udev_u2_del = le16_to_cpu(udev->bos->ss_cap->bU2DevExitLat);
347 	hub_u1_del = udev->parent->bos->ss_cap->bU1devExitLat;
348 	hub_u2_del = le16_to_cpu(udev->parent->bos->ss_cap->bU2DevExitLat);
349 
350 	usb_set_lpm_mel(udev, &udev->u1_params, udev_u1_del,
351 			hub, &udev->parent->u1_params, hub_u1_del);
352 
353 	usb_set_lpm_mel(udev, &udev->u2_params, udev_u2_del,
354 			hub, &udev->parent->u2_params, hub_u2_del);
355 
356 	/*
357 	 * Appendix C, section C.2.2.2, says that there is a slight delay from
358 	 * when the parent hub notices the downstream port is trying to
359 	 * transition to U0 to when the hub initiates a U0 transition on its
360 	 * upstream port.  The section says the delays are tPort2PortU1EL and
361 	 * tPort2PortU2EL, but it doesn't define what they are.
362 	 *
363 	 * The hub chapter, sections 10.4.2.4 and 10.4.2.5 seem to be talking
364 	 * about the same delays.  Use the maximum delay calculations from those
365 	 * sections.  For U1, it's tHubPort2PortExitLat, which is 1us max.  For
366 	 * U2, it's tHubPort2PortExitLat + U2DevExitLat - U1DevExitLat.  I
367 	 * assume the device exit latencies they are talking about are the hub
368 	 * exit latencies.
369 	 *
370 	 * What do we do if the U2 exit latency is less than the U1 exit
371 	 * latency?  It's possible, although not likely...
372 	 */
373 	port_to_port_delay = 1;
374 
375 	usb_set_lpm_pel(udev, &udev->u1_params, udev_u1_del,
376 			hub, &udev->parent->u1_params, hub_u1_del,
377 			port_to_port_delay);
378 
379 	if (hub_u2_del > hub_u1_del)
380 		port_to_port_delay = 1 + hub_u2_del - hub_u1_del;
381 	else
382 		port_to_port_delay = 1 + hub_u1_del;
383 
384 	usb_set_lpm_pel(udev, &udev->u2_params, udev_u2_del,
385 			hub, &udev->parent->u2_params, hub_u2_del,
386 			port_to_port_delay);
387 
388 	/* Now that we've got PEL, calculate SEL. */
389 	usb_set_lpm_sel(udev, &udev->u1_params);
390 	usb_set_lpm_sel(udev, &udev->u2_params);
391 }
392 
393 /* USB 2.0 spec Section 11.24.4.5 */
394 static int get_hub_descriptor(struct usb_device *hdev,
395 		struct usb_hub_descriptor *desc)
396 {
397 	int i, ret, size;
398 	unsigned dtype;
399 
400 	if (hub_is_superspeed(hdev)) {
401 		dtype = USB_DT_SS_HUB;
402 		size = USB_DT_SS_HUB_SIZE;
403 	} else {
404 		dtype = USB_DT_HUB;
405 		size = sizeof(struct usb_hub_descriptor);
406 	}
407 
408 	for (i = 0; i < 3; i++) {
409 		ret = usb_control_msg(hdev, usb_rcvctrlpipe(hdev, 0),
410 			USB_REQ_GET_DESCRIPTOR, USB_DIR_IN | USB_RT_HUB,
411 			dtype << 8, 0, desc, size,
412 			USB_CTRL_GET_TIMEOUT);
413 		if (hub_is_superspeed(hdev)) {
414 			if (ret == size)
415 				return ret;
416 		} else if (ret >= USB_DT_HUB_NONVAR_SIZE + 2) {
417 			/* Make sure we have the DeviceRemovable field. */
418 			size = USB_DT_HUB_NONVAR_SIZE + desc->bNbrPorts / 8 + 1;
419 			if (ret < size)
420 				return -EMSGSIZE;
421 			return ret;
422 		}
423 	}
424 	return -EINVAL;
425 }
426 
427 /*
428  * USB 2.0 spec Section 11.24.2.1
429  */
430 static int clear_hub_feature(struct usb_device *hdev, int feature)
431 {
432 	return usb_control_msg(hdev, usb_sndctrlpipe(hdev, 0),
433 		USB_REQ_CLEAR_FEATURE, USB_RT_HUB, feature, 0, NULL, 0, 1000);
434 }
435 
436 /*
437  * USB 2.0 spec Section 11.24.2.2
438  */
439 int usb_clear_port_feature(struct usb_device *hdev, int port1, int feature)
440 {
441 	return usb_control_msg(hdev, usb_sndctrlpipe(hdev, 0),
442 		USB_REQ_CLEAR_FEATURE, USB_RT_PORT, feature, port1,
443 		NULL, 0, 1000);
444 }
445 
446 /*
447  * USB 2.0 spec Section 11.24.2.13
448  */
449 static int set_port_feature(struct usb_device *hdev, int port1, int feature)
450 {
451 	return usb_control_msg(hdev, usb_sndctrlpipe(hdev, 0),
452 		USB_REQ_SET_FEATURE, USB_RT_PORT, feature, port1,
453 		NULL, 0, 1000);
454 }
455 
456 static char *to_led_name(int selector)
457 {
458 	switch (selector) {
459 	case HUB_LED_AMBER:
460 		return "amber";
461 	case HUB_LED_GREEN:
462 		return "green";
463 	case HUB_LED_OFF:
464 		return "off";
465 	case HUB_LED_AUTO:
466 		return "auto";
467 	default:
468 		return "??";
469 	}
470 }
471 
472 /*
473  * USB 2.0 spec Section 11.24.2.7.1.10 and table 11-7
474  * for info about using port indicators
475  */
476 static void set_port_led(struct usb_hub *hub, int port1, int selector)
477 {
478 	struct usb_port *port_dev = hub->ports[port1 - 1];
479 	int status;
480 
481 	status = set_port_feature(hub->hdev, (selector << 8) | port1,
482 			USB_PORT_FEAT_INDICATOR);
483 	dev_dbg(&port_dev->dev, "indicator %s status %d\n",
484 		to_led_name(selector), status);
485 }
486 
487 #define	LED_CYCLE_PERIOD	((2*HZ)/3)
488 
489 static void led_work(struct work_struct *work)
490 {
491 	struct usb_hub		*hub =
492 		container_of(work, struct usb_hub, leds.work);
493 	struct usb_device	*hdev = hub->hdev;
494 	unsigned		i;
495 	unsigned		changed = 0;
496 	int			cursor = -1;
497 
498 	if (hdev->state != USB_STATE_CONFIGURED || hub->quiescing)
499 		return;
500 
501 	for (i = 0; i < hdev->maxchild; i++) {
502 		unsigned	selector, mode;
503 
504 		/* 30%-50% duty cycle */
505 
506 		switch (hub->indicator[i]) {
507 		/* cycle marker */
508 		case INDICATOR_CYCLE:
509 			cursor = i;
510 			selector = HUB_LED_AUTO;
511 			mode = INDICATOR_AUTO;
512 			break;
513 		/* blinking green = sw attention */
514 		case INDICATOR_GREEN_BLINK:
515 			selector = HUB_LED_GREEN;
516 			mode = INDICATOR_GREEN_BLINK_OFF;
517 			break;
518 		case INDICATOR_GREEN_BLINK_OFF:
519 			selector = HUB_LED_OFF;
520 			mode = INDICATOR_GREEN_BLINK;
521 			break;
522 		/* blinking amber = hw attention */
523 		case INDICATOR_AMBER_BLINK:
524 			selector = HUB_LED_AMBER;
525 			mode = INDICATOR_AMBER_BLINK_OFF;
526 			break;
527 		case INDICATOR_AMBER_BLINK_OFF:
528 			selector = HUB_LED_OFF;
529 			mode = INDICATOR_AMBER_BLINK;
530 			break;
531 		/* blink green/amber = reserved */
532 		case INDICATOR_ALT_BLINK:
533 			selector = HUB_LED_GREEN;
534 			mode = INDICATOR_ALT_BLINK_OFF;
535 			break;
536 		case INDICATOR_ALT_BLINK_OFF:
537 			selector = HUB_LED_AMBER;
538 			mode = INDICATOR_ALT_BLINK;
539 			break;
540 		default:
541 			continue;
542 		}
543 		if (selector != HUB_LED_AUTO)
544 			changed = 1;
545 		set_port_led(hub, i + 1, selector);
546 		hub->indicator[i] = mode;
547 	}
548 	if (!changed && blinkenlights) {
549 		cursor++;
550 		cursor %= hdev->maxchild;
551 		set_port_led(hub, cursor + 1, HUB_LED_GREEN);
552 		hub->indicator[cursor] = INDICATOR_CYCLE;
553 		changed++;
554 	}
555 	if (changed)
556 		queue_delayed_work(system_power_efficient_wq,
557 				&hub->leds, LED_CYCLE_PERIOD);
558 }
559 
560 /* use a short timeout for hub/port status fetches */
561 #define	USB_STS_TIMEOUT		1000
562 #define	USB_STS_RETRIES		5
563 
564 /*
565  * USB 2.0 spec Section 11.24.2.6
566  */
567 static int get_hub_status(struct usb_device *hdev,
568 		struct usb_hub_status *data)
569 {
570 	int i, status = -ETIMEDOUT;
571 
572 	for (i = 0; i < USB_STS_RETRIES &&
573 			(status == -ETIMEDOUT || status == -EPIPE); i++) {
574 		status = usb_control_msg(hdev, usb_rcvctrlpipe(hdev, 0),
575 			USB_REQ_GET_STATUS, USB_DIR_IN | USB_RT_HUB, 0, 0,
576 			data, sizeof(*data), USB_STS_TIMEOUT);
577 	}
578 	return status;
579 }
580 
581 /*
582  * USB 2.0 spec Section 11.24.2.7
583  * USB 3.1 takes into use the wValue and wLength fields, spec Section 10.16.2.6
584  */
585 static int get_port_status(struct usb_device *hdev, int port1,
586 			   void *data, u16 value, u16 length)
587 {
588 	int i, status = -ETIMEDOUT;
589 
590 	for (i = 0; i < USB_STS_RETRIES &&
591 			(status == -ETIMEDOUT || status == -EPIPE); i++) {
592 		status = usb_control_msg(hdev, usb_rcvctrlpipe(hdev, 0),
593 			USB_REQ_GET_STATUS, USB_DIR_IN | USB_RT_PORT, value,
594 			port1, data, length, USB_STS_TIMEOUT);
595 	}
596 	return status;
597 }
598 
599 static int hub_ext_port_status(struct usb_hub *hub, int port1, int type,
600 			       u16 *status, u16 *change, u32 *ext_status)
601 {
602 	int ret;
603 	int len = 4;
604 
605 	if (type != HUB_PORT_STATUS)
606 		len = 8;
607 
608 	mutex_lock(&hub->status_mutex);
609 	ret = get_port_status(hub->hdev, port1, &hub->status->port, type, len);
610 	if (ret < len) {
611 		if (ret != -ENODEV)
612 			dev_err(hub->intfdev,
613 				"%s failed (err = %d)\n", __func__, ret);
614 		if (ret >= 0)
615 			ret = -EIO;
616 	} else {
617 		*status = le16_to_cpu(hub->status->port.wPortStatus);
618 		*change = le16_to_cpu(hub->status->port.wPortChange);
619 		if (type != HUB_PORT_STATUS && ext_status)
620 			*ext_status = le32_to_cpu(
621 				hub->status->port.dwExtPortStatus);
622 		ret = 0;
623 	}
624 	mutex_unlock(&hub->status_mutex);
625 	return ret;
626 }
627 
628 int usb_hub_port_status(struct usb_hub *hub, int port1,
629 		u16 *status, u16 *change)
630 {
631 	return hub_ext_port_status(hub, port1, HUB_PORT_STATUS,
632 				   status, change, NULL);
633 }
634 
635 static void hub_resubmit_irq_urb(struct usb_hub *hub)
636 {
637 	unsigned long flags;
638 	int status;
639 
640 	spin_lock_irqsave(&hub->irq_urb_lock, flags);
641 
642 	if (hub->quiescing) {
643 		spin_unlock_irqrestore(&hub->irq_urb_lock, flags);
644 		return;
645 	}
646 
647 	status = usb_submit_urb(hub->urb, GFP_ATOMIC);
648 	if (status && status != -ENODEV && status != -EPERM &&
649 	    status != -ESHUTDOWN) {
650 		dev_err(hub->intfdev, "resubmit --> %d\n", status);
651 		mod_timer(&hub->irq_urb_retry, jiffies + HZ);
652 	}
653 
654 	spin_unlock_irqrestore(&hub->irq_urb_lock, flags);
655 }
656 
657 static void hub_retry_irq_urb(struct timer_list *t)
658 {
659 	struct usb_hub *hub = from_timer(hub, t, irq_urb_retry);
660 
661 	hub_resubmit_irq_urb(hub);
662 }
663 
664 
665 static void kick_hub_wq(struct usb_hub *hub)
666 {
667 	struct usb_interface *intf;
668 
669 	if (hub->disconnected || work_pending(&hub->events))
670 		return;
671 
672 	/*
673 	 * Suppress autosuspend until the event is proceed.
674 	 *
675 	 * Be careful and make sure that the symmetric operation is
676 	 * always called. We are here only when there is no pending
677 	 * work for this hub. Therefore put the interface either when
678 	 * the new work is called or when it is canceled.
679 	 */
680 	intf = to_usb_interface(hub->intfdev);
681 	usb_autopm_get_interface_no_resume(intf);
682 	kref_get(&hub->kref);
683 
684 	if (queue_work(hub_wq, &hub->events))
685 		return;
686 
687 	/* the work has already been scheduled */
688 	usb_autopm_put_interface_async(intf);
689 	kref_put(&hub->kref, hub_release);
690 }
691 
692 void usb_kick_hub_wq(struct usb_device *hdev)
693 {
694 	struct usb_hub *hub = usb_hub_to_struct_hub(hdev);
695 
696 	if (hub)
697 		kick_hub_wq(hub);
698 }
699 
700 /*
701  * Let the USB core know that a USB 3.0 device has sent a Function Wake Device
702  * Notification, which indicates it had initiated remote wakeup.
703  *
704  * USB 3.0 hubs do not report the port link state change from U3 to U0 when the
705  * device initiates resume, so the USB core will not receive notice of the
706  * resume through the normal hub interrupt URB.
707  */
708 void usb_wakeup_notification(struct usb_device *hdev,
709 		unsigned int portnum)
710 {
711 	struct usb_hub *hub;
712 	struct usb_port *port_dev;
713 
714 	if (!hdev)
715 		return;
716 
717 	hub = usb_hub_to_struct_hub(hdev);
718 	if (hub) {
719 		port_dev = hub->ports[portnum - 1];
720 		if (port_dev && port_dev->child)
721 			pm_wakeup_event(&port_dev->child->dev, 0);
722 
723 		set_bit(portnum, hub->wakeup_bits);
724 		kick_hub_wq(hub);
725 	}
726 }
727 EXPORT_SYMBOL_GPL(usb_wakeup_notification);
728 
729 /* completion function, fires on port status changes and various faults */
730 static void hub_irq(struct urb *urb)
731 {
732 	struct usb_hub *hub = urb->context;
733 	int status = urb->status;
734 	unsigned i;
735 	unsigned long bits;
736 
737 	switch (status) {
738 	case -ENOENT:		/* synchronous unlink */
739 	case -ECONNRESET:	/* async unlink */
740 	case -ESHUTDOWN:	/* hardware going away */
741 		return;
742 
743 	default:		/* presumably an error */
744 		/* Cause a hub reset after 10 consecutive errors */
745 		dev_dbg(hub->intfdev, "transfer --> %d\n", status);
746 		if ((++hub->nerrors < 10) || hub->error)
747 			goto resubmit;
748 		hub->error = status;
749 		fallthrough;
750 
751 	/* let hub_wq handle things */
752 	case 0:			/* we got data:  port status changed */
753 		bits = 0;
754 		for (i = 0; i < urb->actual_length; ++i)
755 			bits |= ((unsigned long) ((*hub->buffer)[i]))
756 					<< (i*8);
757 		hub->event_bits[0] = bits;
758 		break;
759 	}
760 
761 	hub->nerrors = 0;
762 
763 	/* Something happened, let hub_wq figure it out */
764 	kick_hub_wq(hub);
765 
766 resubmit:
767 	hub_resubmit_irq_urb(hub);
768 }
769 
770 /* USB 2.0 spec Section 11.24.2.3 */
771 static inline int
772 hub_clear_tt_buffer(struct usb_device *hdev, u16 devinfo, u16 tt)
773 {
774 	/* Need to clear both directions for control ep */
775 	if (((devinfo >> 11) & USB_ENDPOINT_XFERTYPE_MASK) ==
776 			USB_ENDPOINT_XFER_CONTROL) {
777 		int status = usb_control_msg(hdev, usb_sndctrlpipe(hdev, 0),
778 				HUB_CLEAR_TT_BUFFER, USB_RT_PORT,
779 				devinfo ^ 0x8000, tt, NULL, 0, 1000);
780 		if (status)
781 			return status;
782 	}
783 	return usb_control_msg(hdev, usb_sndctrlpipe(hdev, 0),
784 			       HUB_CLEAR_TT_BUFFER, USB_RT_PORT, devinfo,
785 			       tt, NULL, 0, 1000);
786 }
787 
788 /*
789  * enumeration blocks hub_wq for a long time. we use keventd instead, since
790  * long blocking there is the exception, not the rule.  accordingly, HCDs
791  * talking to TTs must queue control transfers (not just bulk and iso), so
792  * both can talk to the same hub concurrently.
793  */
794 static void hub_tt_work(struct work_struct *work)
795 {
796 	struct usb_hub		*hub =
797 		container_of(work, struct usb_hub, tt.clear_work);
798 	unsigned long		flags;
799 
800 	spin_lock_irqsave(&hub->tt.lock, flags);
801 	while (!list_empty(&hub->tt.clear_list)) {
802 		struct list_head	*next;
803 		struct usb_tt_clear	*clear;
804 		struct usb_device	*hdev = hub->hdev;
805 		const struct hc_driver	*drv;
806 		int			status;
807 
808 		next = hub->tt.clear_list.next;
809 		clear = list_entry(next, struct usb_tt_clear, clear_list);
810 		list_del(&clear->clear_list);
811 
812 		/* drop lock so HCD can concurrently report other TT errors */
813 		spin_unlock_irqrestore(&hub->tt.lock, flags);
814 		status = hub_clear_tt_buffer(hdev, clear->devinfo, clear->tt);
815 		if (status && status != -ENODEV)
816 			dev_err(&hdev->dev,
817 				"clear tt %d (%04x) error %d\n",
818 				clear->tt, clear->devinfo, status);
819 
820 		/* Tell the HCD, even if the operation failed */
821 		drv = clear->hcd->driver;
822 		if (drv->clear_tt_buffer_complete)
823 			(drv->clear_tt_buffer_complete)(clear->hcd, clear->ep);
824 
825 		kfree(clear);
826 		spin_lock_irqsave(&hub->tt.lock, flags);
827 	}
828 	spin_unlock_irqrestore(&hub->tt.lock, flags);
829 }
830 
831 /**
832  * usb_hub_set_port_power - control hub port's power state
833  * @hdev: USB device belonging to the usb hub
834  * @hub: target hub
835  * @port1: port index
836  * @set: expected status
837  *
838  * call this function to control port's power via setting or
839  * clearing the port's PORT_POWER feature.
840  *
841  * Return: 0 if successful. A negative error code otherwise.
842  */
843 int usb_hub_set_port_power(struct usb_device *hdev, struct usb_hub *hub,
844 			   int port1, bool set)
845 {
846 	int ret;
847 
848 	if (set)
849 		ret = set_port_feature(hdev, port1, USB_PORT_FEAT_POWER);
850 	else
851 		ret = usb_clear_port_feature(hdev, port1, USB_PORT_FEAT_POWER);
852 
853 	if (ret)
854 		return ret;
855 
856 	if (set)
857 		set_bit(port1, hub->power_bits);
858 	else
859 		clear_bit(port1, hub->power_bits);
860 	return 0;
861 }
862 
863 /**
864  * usb_hub_clear_tt_buffer - clear control/bulk TT state in high speed hub
865  * @urb: an URB associated with the failed or incomplete split transaction
866  *
867  * High speed HCDs use this to tell the hub driver that some split control or
868  * bulk transaction failed in a way that requires clearing internal state of
869  * a transaction translator.  This is normally detected (and reported) from
870  * interrupt context.
871  *
872  * It may not be possible for that hub to handle additional full (or low)
873  * speed transactions until that state is fully cleared out.
874  *
875  * Return: 0 if successful. A negative error code otherwise.
876  */
877 int usb_hub_clear_tt_buffer(struct urb *urb)
878 {
879 	struct usb_device	*udev = urb->dev;
880 	int			pipe = urb->pipe;
881 	struct usb_tt		*tt = udev->tt;
882 	unsigned long		flags;
883 	struct usb_tt_clear	*clear;
884 
885 	/* we've got to cope with an arbitrary number of pending TT clears,
886 	 * since each TT has "at least two" buffers that can need it (and
887 	 * there can be many TTs per hub).  even if they're uncommon.
888 	 */
889 	clear = kmalloc(sizeof *clear, GFP_ATOMIC);
890 	if (clear == NULL) {
891 		dev_err(&udev->dev, "can't save CLEAR_TT_BUFFER state\n");
892 		/* FIXME recover somehow ... RESET_TT? */
893 		return -ENOMEM;
894 	}
895 
896 	/* info that CLEAR_TT_BUFFER needs */
897 	clear->tt = tt->multi ? udev->ttport : 1;
898 	clear->devinfo = usb_pipeendpoint (pipe);
899 	clear->devinfo |= ((u16)udev->devaddr) << 4;
900 	clear->devinfo |= usb_pipecontrol(pipe)
901 			? (USB_ENDPOINT_XFER_CONTROL << 11)
902 			: (USB_ENDPOINT_XFER_BULK << 11);
903 	if (usb_pipein(pipe))
904 		clear->devinfo |= 1 << 15;
905 
906 	/* info for completion callback */
907 	clear->hcd = bus_to_hcd(udev->bus);
908 	clear->ep = urb->ep;
909 
910 	/* tell keventd to clear state for this TT */
911 	spin_lock_irqsave(&tt->lock, flags);
912 	list_add_tail(&clear->clear_list, &tt->clear_list);
913 	schedule_work(&tt->clear_work);
914 	spin_unlock_irqrestore(&tt->lock, flags);
915 	return 0;
916 }
917 EXPORT_SYMBOL_GPL(usb_hub_clear_tt_buffer);
918 
919 static void hub_power_on(struct usb_hub *hub, bool do_delay)
920 {
921 	int port1;
922 
923 	/* Enable power on each port.  Some hubs have reserved values
924 	 * of LPSM (> 2) in their descriptors, even though they are
925 	 * USB 2.0 hubs.  Some hubs do not implement port-power switching
926 	 * but only emulate it.  In all cases, the ports won't work
927 	 * unless we send these messages to the hub.
928 	 */
929 	if (hub_is_port_power_switchable(hub))
930 		dev_dbg(hub->intfdev, "enabling power on all ports\n");
931 	else
932 		dev_dbg(hub->intfdev, "trying to enable port power on "
933 				"non-switchable hub\n");
934 	for (port1 = 1; port1 <= hub->hdev->maxchild; port1++)
935 		if (test_bit(port1, hub->power_bits))
936 			set_port_feature(hub->hdev, port1, USB_PORT_FEAT_POWER);
937 		else
938 			usb_clear_port_feature(hub->hdev, port1,
939 						USB_PORT_FEAT_POWER);
940 	if (do_delay)
941 		msleep(hub_power_on_good_delay(hub));
942 }
943 
944 static int hub_hub_status(struct usb_hub *hub,
945 		u16 *status, u16 *change)
946 {
947 	int ret;
948 
949 	mutex_lock(&hub->status_mutex);
950 	ret = get_hub_status(hub->hdev, &hub->status->hub);
951 	if (ret < 0) {
952 		if (ret != -ENODEV)
953 			dev_err(hub->intfdev,
954 				"%s failed (err = %d)\n", __func__, ret);
955 	} else {
956 		*status = le16_to_cpu(hub->status->hub.wHubStatus);
957 		*change = le16_to_cpu(hub->status->hub.wHubChange);
958 		ret = 0;
959 	}
960 	mutex_unlock(&hub->status_mutex);
961 	return ret;
962 }
963 
964 static int hub_set_port_link_state(struct usb_hub *hub, int port1,
965 			unsigned int link_status)
966 {
967 	return set_port_feature(hub->hdev,
968 			port1 | (link_status << 3),
969 			USB_PORT_FEAT_LINK_STATE);
970 }
971 
972 /*
973  * Disable a port and mark a logical connect-change event, so that some
974  * time later hub_wq will disconnect() any existing usb_device on the port
975  * and will re-enumerate if there actually is a device attached.
976  */
977 static void hub_port_logical_disconnect(struct usb_hub *hub, int port1)
978 {
979 	dev_dbg(&hub->ports[port1 - 1]->dev, "logical disconnect\n");
980 	hub_port_disable(hub, port1, 1);
981 
982 	/* FIXME let caller ask to power down the port:
983 	 *  - some devices won't enumerate without a VBUS power cycle
984 	 *  - SRP saves power that way
985 	 *  - ... new call, TBD ...
986 	 * That's easy if this hub can switch power per-port, and
987 	 * hub_wq reactivates the port later (timer, SRP, etc).
988 	 * Powerdown must be optional, because of reset/DFU.
989 	 */
990 
991 	set_bit(port1, hub->change_bits);
992 	kick_hub_wq(hub);
993 }
994 
995 /**
996  * usb_remove_device - disable a device's port on its parent hub
997  * @udev: device to be disabled and removed
998  * Context: @udev locked, must be able to sleep.
999  *
1000  * After @udev's port has been disabled, hub_wq is notified and it will
1001  * see that the device has been disconnected.  When the device is
1002  * physically unplugged and something is plugged in, the events will
1003  * be received and processed normally.
1004  *
1005  * Return: 0 if successful. A negative error code otherwise.
1006  */
1007 int usb_remove_device(struct usb_device *udev)
1008 {
1009 	struct usb_hub *hub;
1010 	struct usb_interface *intf;
1011 	int ret;
1012 
1013 	if (!udev->parent)	/* Can't remove a root hub */
1014 		return -EINVAL;
1015 	hub = usb_hub_to_struct_hub(udev->parent);
1016 	intf = to_usb_interface(hub->intfdev);
1017 
1018 	ret = usb_autopm_get_interface(intf);
1019 	if (ret < 0)
1020 		return ret;
1021 
1022 	set_bit(udev->portnum, hub->removed_bits);
1023 	hub_port_logical_disconnect(hub, udev->portnum);
1024 	usb_autopm_put_interface(intf);
1025 	return 0;
1026 }
1027 
1028 enum hub_activation_type {
1029 	HUB_INIT, HUB_INIT2, HUB_INIT3,		/* INITs must come first */
1030 	HUB_POST_RESET, HUB_RESUME, HUB_RESET_RESUME,
1031 };
1032 
1033 static void hub_init_func2(struct work_struct *ws);
1034 static void hub_init_func3(struct work_struct *ws);
1035 
1036 static void hub_activate(struct usb_hub *hub, enum hub_activation_type type)
1037 {
1038 	struct usb_device *hdev = hub->hdev;
1039 	struct usb_hcd *hcd;
1040 	int ret;
1041 	int port1;
1042 	int status;
1043 	bool need_debounce_delay = false;
1044 	unsigned delay;
1045 
1046 	/* Continue a partial initialization */
1047 	if (type == HUB_INIT2 || type == HUB_INIT3) {
1048 		device_lock(&hdev->dev);
1049 
1050 		/* Was the hub disconnected while we were waiting? */
1051 		if (hub->disconnected)
1052 			goto disconnected;
1053 		if (type == HUB_INIT2)
1054 			goto init2;
1055 		goto init3;
1056 	}
1057 	kref_get(&hub->kref);
1058 
1059 	/* The superspeed hub except for root hub has to use Hub Depth
1060 	 * value as an offset into the route string to locate the bits
1061 	 * it uses to determine the downstream port number. So hub driver
1062 	 * should send a set hub depth request to superspeed hub after
1063 	 * the superspeed hub is set configuration in initialization or
1064 	 * reset procedure.
1065 	 *
1066 	 * After a resume, port power should still be on.
1067 	 * For any other type of activation, turn it on.
1068 	 */
1069 	if (type != HUB_RESUME) {
1070 		if (hdev->parent && hub_is_superspeed(hdev)) {
1071 			ret = usb_control_msg(hdev, usb_sndctrlpipe(hdev, 0),
1072 					HUB_SET_DEPTH, USB_RT_HUB,
1073 					hdev->level - 1, 0, NULL, 0,
1074 					USB_CTRL_SET_TIMEOUT);
1075 			if (ret < 0)
1076 				dev_err(hub->intfdev,
1077 						"set hub depth failed\n");
1078 		}
1079 
1080 		/* Speed up system boot by using a delayed_work for the
1081 		 * hub's initial power-up delays.  This is pretty awkward
1082 		 * and the implementation looks like a home-brewed sort of
1083 		 * setjmp/longjmp, but it saves at least 100 ms for each
1084 		 * root hub (assuming usbcore is compiled into the kernel
1085 		 * rather than as a module).  It adds up.
1086 		 *
1087 		 * This can't be done for HUB_RESUME or HUB_RESET_RESUME
1088 		 * because for those activation types the ports have to be
1089 		 * operational when we return.  In theory this could be done
1090 		 * for HUB_POST_RESET, but it's easier not to.
1091 		 */
1092 		if (type == HUB_INIT) {
1093 			delay = hub_power_on_good_delay(hub);
1094 
1095 			hub_power_on(hub, false);
1096 			INIT_DELAYED_WORK(&hub->init_work, hub_init_func2);
1097 			queue_delayed_work(system_power_efficient_wq,
1098 					&hub->init_work,
1099 					msecs_to_jiffies(delay));
1100 
1101 			/* Suppress autosuspend until init is done */
1102 			usb_autopm_get_interface_no_resume(
1103 					to_usb_interface(hub->intfdev));
1104 			return;		/* Continues at init2: below */
1105 		} else if (type == HUB_RESET_RESUME) {
1106 			/* The internal host controller state for the hub device
1107 			 * may be gone after a host power loss on system resume.
1108 			 * Update the device's info so the HW knows it's a hub.
1109 			 */
1110 			hcd = bus_to_hcd(hdev->bus);
1111 			if (hcd->driver->update_hub_device) {
1112 				ret = hcd->driver->update_hub_device(hcd, hdev,
1113 						&hub->tt, GFP_NOIO);
1114 				if (ret < 0) {
1115 					dev_err(hub->intfdev,
1116 						"Host not accepting hub info update\n");
1117 					dev_err(hub->intfdev,
1118 						"LS/FS devices and hubs may not work under this hub\n");
1119 				}
1120 			}
1121 			hub_power_on(hub, true);
1122 		} else {
1123 			hub_power_on(hub, true);
1124 		}
1125 	/* Give some time on remote wakeup to let links to transit to U0 */
1126 	} else if (hub_is_superspeed(hub->hdev))
1127 		msleep(20);
1128 
1129  init2:
1130 
1131 	/*
1132 	 * Check each port and set hub->change_bits to let hub_wq know
1133 	 * which ports need attention.
1134 	 */
1135 	for (port1 = 1; port1 <= hdev->maxchild; ++port1) {
1136 		struct usb_port *port_dev = hub->ports[port1 - 1];
1137 		struct usb_device *udev = port_dev->child;
1138 		u16 portstatus, portchange;
1139 
1140 		portstatus = portchange = 0;
1141 		status = usb_hub_port_status(hub, port1, &portstatus, &portchange);
1142 		if (status)
1143 			goto abort;
1144 
1145 		if (udev || (portstatus & USB_PORT_STAT_CONNECTION))
1146 			dev_dbg(&port_dev->dev, "status %04x change %04x\n",
1147 					portstatus, portchange);
1148 
1149 		/*
1150 		 * After anything other than HUB_RESUME (i.e., initialization
1151 		 * or any sort of reset), every port should be disabled.
1152 		 * Unconnected ports should likewise be disabled (paranoia),
1153 		 * and so should ports for which we have no usb_device.
1154 		 */
1155 		if ((portstatus & USB_PORT_STAT_ENABLE) && (
1156 				type != HUB_RESUME ||
1157 				!(portstatus & USB_PORT_STAT_CONNECTION) ||
1158 				!udev ||
1159 				udev->state == USB_STATE_NOTATTACHED)) {
1160 			/*
1161 			 * USB3 protocol ports will automatically transition
1162 			 * to Enabled state when detect an USB3.0 device attach.
1163 			 * Do not disable USB3 protocol ports, just pretend
1164 			 * power was lost
1165 			 */
1166 			portstatus &= ~USB_PORT_STAT_ENABLE;
1167 			if (!hub_is_superspeed(hdev))
1168 				usb_clear_port_feature(hdev, port1,
1169 						   USB_PORT_FEAT_ENABLE);
1170 		}
1171 
1172 		/* Make sure a warm-reset request is handled by port_event */
1173 		if (type == HUB_RESUME &&
1174 		    hub_port_warm_reset_required(hub, port1, portstatus))
1175 			set_bit(port1, hub->event_bits);
1176 
1177 		/*
1178 		 * Add debounce if USB3 link is in polling/link training state.
1179 		 * Link will automatically transition to Enabled state after
1180 		 * link training completes.
1181 		 */
1182 		if (hub_is_superspeed(hdev) &&
1183 		    ((portstatus & USB_PORT_STAT_LINK_STATE) ==
1184 						USB_SS_PORT_LS_POLLING))
1185 			need_debounce_delay = true;
1186 
1187 		/* Clear status-change flags; we'll debounce later */
1188 		if (portchange & USB_PORT_STAT_C_CONNECTION) {
1189 			need_debounce_delay = true;
1190 			usb_clear_port_feature(hub->hdev, port1,
1191 					USB_PORT_FEAT_C_CONNECTION);
1192 		}
1193 		if (portchange & USB_PORT_STAT_C_ENABLE) {
1194 			need_debounce_delay = true;
1195 			usb_clear_port_feature(hub->hdev, port1,
1196 					USB_PORT_FEAT_C_ENABLE);
1197 		}
1198 		if (portchange & USB_PORT_STAT_C_RESET) {
1199 			need_debounce_delay = true;
1200 			usb_clear_port_feature(hub->hdev, port1,
1201 					USB_PORT_FEAT_C_RESET);
1202 		}
1203 		if ((portchange & USB_PORT_STAT_C_BH_RESET) &&
1204 				hub_is_superspeed(hub->hdev)) {
1205 			need_debounce_delay = true;
1206 			usb_clear_port_feature(hub->hdev, port1,
1207 					USB_PORT_FEAT_C_BH_PORT_RESET);
1208 		}
1209 		/* We can forget about a "removed" device when there's a
1210 		 * physical disconnect or the connect status changes.
1211 		 */
1212 		if (!(portstatus & USB_PORT_STAT_CONNECTION) ||
1213 				(portchange & USB_PORT_STAT_C_CONNECTION))
1214 			clear_bit(port1, hub->removed_bits);
1215 
1216 		if (!udev || udev->state == USB_STATE_NOTATTACHED) {
1217 			/* Tell hub_wq to disconnect the device or
1218 			 * check for a new connection or over current condition.
1219 			 * Based on USB2.0 Spec Section 11.12.5,
1220 			 * C_PORT_OVER_CURRENT could be set while
1221 			 * PORT_OVER_CURRENT is not. So check for any of them.
1222 			 */
1223 			if (udev || (portstatus & USB_PORT_STAT_CONNECTION) ||
1224 			    (portchange & USB_PORT_STAT_C_CONNECTION) ||
1225 			    (portstatus & USB_PORT_STAT_OVERCURRENT) ||
1226 			    (portchange & USB_PORT_STAT_C_OVERCURRENT))
1227 				set_bit(port1, hub->change_bits);
1228 
1229 		} else if (portstatus & USB_PORT_STAT_ENABLE) {
1230 			bool port_resumed = (portstatus &
1231 					USB_PORT_STAT_LINK_STATE) ==
1232 				USB_SS_PORT_LS_U0;
1233 			/* The power session apparently survived the resume.
1234 			 * If there was an overcurrent or suspend change
1235 			 * (i.e., remote wakeup request), have hub_wq
1236 			 * take care of it.  Look at the port link state
1237 			 * for USB 3.0 hubs, since they don't have a suspend
1238 			 * change bit, and they don't set the port link change
1239 			 * bit on device-initiated resume.
1240 			 */
1241 			if (portchange || (hub_is_superspeed(hub->hdev) &&
1242 						port_resumed))
1243 				set_bit(port1, hub->event_bits);
1244 
1245 		} else if (udev->persist_enabled) {
1246 #ifdef CONFIG_PM
1247 			udev->reset_resume = 1;
1248 #endif
1249 			/* Don't set the change_bits when the device
1250 			 * was powered off.
1251 			 */
1252 			if (test_bit(port1, hub->power_bits))
1253 				set_bit(port1, hub->change_bits);
1254 
1255 		} else {
1256 			/* The power session is gone; tell hub_wq */
1257 			usb_set_device_state(udev, USB_STATE_NOTATTACHED);
1258 			set_bit(port1, hub->change_bits);
1259 		}
1260 	}
1261 
1262 	/* If no port-status-change flags were set, we don't need any
1263 	 * debouncing.  If flags were set we can try to debounce the
1264 	 * ports all at once right now, instead of letting hub_wq do them
1265 	 * one at a time later on.
1266 	 *
1267 	 * If any port-status changes do occur during this delay, hub_wq
1268 	 * will see them later and handle them normally.
1269 	 */
1270 	if (need_debounce_delay) {
1271 		delay = HUB_DEBOUNCE_STABLE;
1272 
1273 		/* Don't do a long sleep inside a workqueue routine */
1274 		if (type == HUB_INIT2) {
1275 			INIT_DELAYED_WORK(&hub->init_work, hub_init_func3);
1276 			queue_delayed_work(system_power_efficient_wq,
1277 					&hub->init_work,
1278 					msecs_to_jiffies(delay));
1279 			device_unlock(&hdev->dev);
1280 			return;		/* Continues at init3: below */
1281 		} else {
1282 			msleep(delay);
1283 		}
1284 	}
1285  init3:
1286 	hub->quiescing = 0;
1287 
1288 	status = usb_submit_urb(hub->urb, GFP_NOIO);
1289 	if (status < 0)
1290 		dev_err(hub->intfdev, "activate --> %d\n", status);
1291 	if (hub->has_indicators && blinkenlights)
1292 		queue_delayed_work(system_power_efficient_wq,
1293 				&hub->leds, LED_CYCLE_PERIOD);
1294 
1295 	/* Scan all ports that need attention */
1296 	kick_hub_wq(hub);
1297  abort:
1298 	if (type == HUB_INIT2 || type == HUB_INIT3) {
1299 		/* Allow autosuspend if it was suppressed */
1300  disconnected:
1301 		usb_autopm_put_interface_async(to_usb_interface(hub->intfdev));
1302 		device_unlock(&hdev->dev);
1303 	}
1304 
1305 	kref_put(&hub->kref, hub_release);
1306 }
1307 
1308 /* Implement the continuations for the delays above */
1309 static void hub_init_func2(struct work_struct *ws)
1310 {
1311 	struct usb_hub *hub = container_of(ws, struct usb_hub, init_work.work);
1312 
1313 	hub_activate(hub, HUB_INIT2);
1314 }
1315 
1316 static void hub_init_func3(struct work_struct *ws)
1317 {
1318 	struct usb_hub *hub = container_of(ws, struct usb_hub, init_work.work);
1319 
1320 	hub_activate(hub, HUB_INIT3);
1321 }
1322 
1323 enum hub_quiescing_type {
1324 	HUB_DISCONNECT, HUB_PRE_RESET, HUB_SUSPEND
1325 };
1326 
1327 static void hub_quiesce(struct usb_hub *hub, enum hub_quiescing_type type)
1328 {
1329 	struct usb_device *hdev = hub->hdev;
1330 	unsigned long flags;
1331 	int i;
1332 
1333 	/* hub_wq and related activity won't re-trigger */
1334 	spin_lock_irqsave(&hub->irq_urb_lock, flags);
1335 	hub->quiescing = 1;
1336 	spin_unlock_irqrestore(&hub->irq_urb_lock, flags);
1337 
1338 	if (type != HUB_SUSPEND) {
1339 		/* Disconnect all the children */
1340 		for (i = 0; i < hdev->maxchild; ++i) {
1341 			if (hub->ports[i]->child)
1342 				usb_disconnect(&hub->ports[i]->child);
1343 		}
1344 	}
1345 
1346 	/* Stop hub_wq and related activity */
1347 	del_timer_sync(&hub->irq_urb_retry);
1348 	usb_kill_urb(hub->urb);
1349 	if (hub->has_indicators)
1350 		cancel_delayed_work_sync(&hub->leds);
1351 	if (hub->tt.hub)
1352 		flush_work(&hub->tt.clear_work);
1353 }
1354 
1355 static void hub_pm_barrier_for_all_ports(struct usb_hub *hub)
1356 {
1357 	int i;
1358 
1359 	for (i = 0; i < hub->hdev->maxchild; ++i)
1360 		pm_runtime_barrier(&hub->ports[i]->dev);
1361 }
1362 
1363 /* caller has locked the hub device */
1364 static int hub_pre_reset(struct usb_interface *intf)
1365 {
1366 	struct usb_hub *hub = usb_get_intfdata(intf);
1367 
1368 	hub_quiesce(hub, HUB_PRE_RESET);
1369 	hub->in_reset = 1;
1370 	hub_pm_barrier_for_all_ports(hub);
1371 	return 0;
1372 }
1373 
1374 /* caller has locked the hub device */
1375 static int hub_post_reset(struct usb_interface *intf)
1376 {
1377 	struct usb_hub *hub = usb_get_intfdata(intf);
1378 
1379 	hub->in_reset = 0;
1380 	hub_pm_barrier_for_all_ports(hub);
1381 	hub_activate(hub, HUB_POST_RESET);
1382 	return 0;
1383 }
1384 
1385 static int hub_configure(struct usb_hub *hub,
1386 	struct usb_endpoint_descriptor *endpoint)
1387 {
1388 	struct usb_hcd *hcd;
1389 	struct usb_device *hdev = hub->hdev;
1390 	struct device *hub_dev = hub->intfdev;
1391 	u16 hubstatus, hubchange;
1392 	u16 wHubCharacteristics;
1393 	unsigned int pipe;
1394 	int maxp, ret, i;
1395 	char *message = "out of memory";
1396 	unsigned unit_load;
1397 	unsigned full_load;
1398 	unsigned maxchild;
1399 
1400 	hub->buffer = kmalloc(sizeof(*hub->buffer), GFP_KERNEL);
1401 	if (!hub->buffer) {
1402 		ret = -ENOMEM;
1403 		goto fail;
1404 	}
1405 
1406 	hub->status = kmalloc(sizeof(*hub->status), GFP_KERNEL);
1407 	if (!hub->status) {
1408 		ret = -ENOMEM;
1409 		goto fail;
1410 	}
1411 	mutex_init(&hub->status_mutex);
1412 
1413 	hub->descriptor = kzalloc(sizeof(*hub->descriptor), GFP_KERNEL);
1414 	if (!hub->descriptor) {
1415 		ret = -ENOMEM;
1416 		goto fail;
1417 	}
1418 
1419 	/* Request the entire hub descriptor.
1420 	 * hub->descriptor can handle USB_MAXCHILDREN ports,
1421 	 * but a (non-SS) hub can/will return fewer bytes here.
1422 	 */
1423 	ret = get_hub_descriptor(hdev, hub->descriptor);
1424 	if (ret < 0) {
1425 		message = "can't read hub descriptor";
1426 		goto fail;
1427 	}
1428 
1429 	maxchild = USB_MAXCHILDREN;
1430 	if (hub_is_superspeed(hdev))
1431 		maxchild = min_t(unsigned, maxchild, USB_SS_MAXPORTS);
1432 
1433 	if (hub->descriptor->bNbrPorts > maxchild) {
1434 		message = "hub has too many ports!";
1435 		ret = -ENODEV;
1436 		goto fail;
1437 	} else if (hub->descriptor->bNbrPorts == 0) {
1438 		message = "hub doesn't have any ports!";
1439 		ret = -ENODEV;
1440 		goto fail;
1441 	}
1442 
1443 	/*
1444 	 * Accumulate wHubDelay + 40ns for every hub in the tree of devices.
1445 	 * The resulting value will be used for SetIsochDelay() request.
1446 	 */
1447 	if (hub_is_superspeed(hdev) || hub_is_superspeedplus(hdev)) {
1448 		u32 delay = __le16_to_cpu(hub->descriptor->u.ss.wHubDelay);
1449 
1450 		if (hdev->parent)
1451 			delay += hdev->parent->hub_delay;
1452 
1453 		delay += USB_TP_TRANSMISSION_DELAY;
1454 		hdev->hub_delay = min_t(u32, delay, USB_TP_TRANSMISSION_DELAY_MAX);
1455 	}
1456 
1457 	maxchild = hub->descriptor->bNbrPorts;
1458 	dev_info(hub_dev, "%d port%s detected\n", maxchild,
1459 			(maxchild == 1) ? "" : "s");
1460 
1461 	hub->ports = kcalloc(maxchild, sizeof(struct usb_port *), GFP_KERNEL);
1462 	if (!hub->ports) {
1463 		ret = -ENOMEM;
1464 		goto fail;
1465 	}
1466 
1467 	wHubCharacteristics = le16_to_cpu(hub->descriptor->wHubCharacteristics);
1468 	if (hub_is_superspeed(hdev)) {
1469 		unit_load = 150;
1470 		full_load = 900;
1471 	} else {
1472 		unit_load = 100;
1473 		full_load = 500;
1474 	}
1475 
1476 	/* FIXME for USB 3.0, skip for now */
1477 	if ((wHubCharacteristics & HUB_CHAR_COMPOUND) &&
1478 			!(hub_is_superspeed(hdev))) {
1479 		char	portstr[USB_MAXCHILDREN + 1];
1480 
1481 		for (i = 0; i < maxchild; i++)
1482 			portstr[i] = hub->descriptor->u.hs.DeviceRemovable
1483 				    [((i + 1) / 8)] & (1 << ((i + 1) % 8))
1484 				? 'F' : 'R';
1485 		portstr[maxchild] = 0;
1486 		dev_dbg(hub_dev, "compound device; port removable status: %s\n", portstr);
1487 	} else
1488 		dev_dbg(hub_dev, "standalone hub\n");
1489 
1490 	switch (wHubCharacteristics & HUB_CHAR_LPSM) {
1491 	case HUB_CHAR_COMMON_LPSM:
1492 		dev_dbg(hub_dev, "ganged power switching\n");
1493 		break;
1494 	case HUB_CHAR_INDV_PORT_LPSM:
1495 		dev_dbg(hub_dev, "individual port power switching\n");
1496 		break;
1497 	case HUB_CHAR_NO_LPSM:
1498 	case HUB_CHAR_LPSM:
1499 		dev_dbg(hub_dev, "no power switching (usb 1.0)\n");
1500 		break;
1501 	}
1502 
1503 	switch (wHubCharacteristics & HUB_CHAR_OCPM) {
1504 	case HUB_CHAR_COMMON_OCPM:
1505 		dev_dbg(hub_dev, "global over-current protection\n");
1506 		break;
1507 	case HUB_CHAR_INDV_PORT_OCPM:
1508 		dev_dbg(hub_dev, "individual port over-current protection\n");
1509 		break;
1510 	case HUB_CHAR_NO_OCPM:
1511 	case HUB_CHAR_OCPM:
1512 		dev_dbg(hub_dev, "no over-current protection\n");
1513 		break;
1514 	}
1515 
1516 	spin_lock_init(&hub->tt.lock);
1517 	INIT_LIST_HEAD(&hub->tt.clear_list);
1518 	INIT_WORK(&hub->tt.clear_work, hub_tt_work);
1519 	switch (hdev->descriptor.bDeviceProtocol) {
1520 	case USB_HUB_PR_FS:
1521 		break;
1522 	case USB_HUB_PR_HS_SINGLE_TT:
1523 		dev_dbg(hub_dev, "Single TT\n");
1524 		hub->tt.hub = hdev;
1525 		break;
1526 	case USB_HUB_PR_HS_MULTI_TT:
1527 		ret = usb_set_interface(hdev, 0, 1);
1528 		if (ret == 0) {
1529 			dev_dbg(hub_dev, "TT per port\n");
1530 			hub->tt.multi = 1;
1531 		} else
1532 			dev_err(hub_dev, "Using single TT (err %d)\n",
1533 				ret);
1534 		hub->tt.hub = hdev;
1535 		break;
1536 	case USB_HUB_PR_SS:
1537 		/* USB 3.0 hubs don't have a TT */
1538 		break;
1539 	default:
1540 		dev_dbg(hub_dev, "Unrecognized hub protocol %d\n",
1541 			hdev->descriptor.bDeviceProtocol);
1542 		break;
1543 	}
1544 
1545 	/* Note 8 FS bit times == (8 bits / 12000000 bps) ~= 666ns */
1546 	switch (wHubCharacteristics & HUB_CHAR_TTTT) {
1547 	case HUB_TTTT_8_BITS:
1548 		if (hdev->descriptor.bDeviceProtocol != 0) {
1549 			hub->tt.think_time = 666;
1550 			dev_dbg(hub_dev, "TT requires at most %d "
1551 					"FS bit times (%d ns)\n",
1552 				8, hub->tt.think_time);
1553 		}
1554 		break;
1555 	case HUB_TTTT_16_BITS:
1556 		hub->tt.think_time = 666 * 2;
1557 		dev_dbg(hub_dev, "TT requires at most %d "
1558 				"FS bit times (%d ns)\n",
1559 			16, hub->tt.think_time);
1560 		break;
1561 	case HUB_TTTT_24_BITS:
1562 		hub->tt.think_time = 666 * 3;
1563 		dev_dbg(hub_dev, "TT requires at most %d "
1564 				"FS bit times (%d ns)\n",
1565 			24, hub->tt.think_time);
1566 		break;
1567 	case HUB_TTTT_32_BITS:
1568 		hub->tt.think_time = 666 * 4;
1569 		dev_dbg(hub_dev, "TT requires at most %d "
1570 				"FS bit times (%d ns)\n",
1571 			32, hub->tt.think_time);
1572 		break;
1573 	}
1574 
1575 	/* probe() zeroes hub->indicator[] */
1576 	if (wHubCharacteristics & HUB_CHAR_PORTIND) {
1577 		hub->has_indicators = 1;
1578 		dev_dbg(hub_dev, "Port indicators are supported\n");
1579 	}
1580 
1581 	dev_dbg(hub_dev, "power on to power good time: %dms\n",
1582 		hub->descriptor->bPwrOn2PwrGood * 2);
1583 
1584 	/* power budgeting mostly matters with bus-powered hubs,
1585 	 * and battery-powered root hubs (may provide just 8 mA).
1586 	 */
1587 	ret = usb_get_std_status(hdev, USB_RECIP_DEVICE, 0, &hubstatus);
1588 	if (ret) {
1589 		message = "can't get hub status";
1590 		goto fail;
1591 	}
1592 	hcd = bus_to_hcd(hdev->bus);
1593 	if (hdev == hdev->bus->root_hub) {
1594 		if (hcd->power_budget > 0)
1595 			hdev->bus_mA = hcd->power_budget;
1596 		else
1597 			hdev->bus_mA = full_load * maxchild;
1598 		if (hdev->bus_mA >= full_load)
1599 			hub->mA_per_port = full_load;
1600 		else {
1601 			hub->mA_per_port = hdev->bus_mA;
1602 			hub->limited_power = 1;
1603 		}
1604 	} else if ((hubstatus & (1 << USB_DEVICE_SELF_POWERED)) == 0) {
1605 		int remaining = hdev->bus_mA -
1606 			hub->descriptor->bHubContrCurrent;
1607 
1608 		dev_dbg(hub_dev, "hub controller current requirement: %dmA\n",
1609 			hub->descriptor->bHubContrCurrent);
1610 		hub->limited_power = 1;
1611 
1612 		if (remaining < maxchild * unit_load)
1613 			dev_warn(hub_dev,
1614 					"insufficient power available "
1615 					"to use all downstream ports\n");
1616 		hub->mA_per_port = unit_load;	/* 7.2.1 */
1617 
1618 	} else {	/* Self-powered external hub */
1619 		/* FIXME: What about battery-powered external hubs that
1620 		 * provide less current per port? */
1621 		hub->mA_per_port = full_load;
1622 	}
1623 	if (hub->mA_per_port < full_load)
1624 		dev_dbg(hub_dev, "%umA bus power budget for each child\n",
1625 				hub->mA_per_port);
1626 
1627 	ret = hub_hub_status(hub, &hubstatus, &hubchange);
1628 	if (ret < 0) {
1629 		message = "can't get hub status";
1630 		goto fail;
1631 	}
1632 
1633 	/* local power status reports aren't always correct */
1634 	if (hdev->actconfig->desc.bmAttributes & USB_CONFIG_ATT_SELFPOWER)
1635 		dev_dbg(hub_dev, "local power source is %s\n",
1636 			(hubstatus & HUB_STATUS_LOCAL_POWER)
1637 			? "lost (inactive)" : "good");
1638 
1639 	if ((wHubCharacteristics & HUB_CHAR_OCPM) == 0)
1640 		dev_dbg(hub_dev, "%sover-current condition exists\n",
1641 			(hubstatus & HUB_STATUS_OVERCURRENT) ? "" : "no ");
1642 
1643 	/* set up the interrupt endpoint
1644 	 * We use the EP's maxpacket size instead of (PORTS+1+7)/8
1645 	 * bytes as USB2.0[11.12.3] says because some hubs are known
1646 	 * to send more data (and thus cause overflow). For root hubs,
1647 	 * maxpktsize is defined in hcd.c's fake endpoint descriptors
1648 	 * to be big enough for at least USB_MAXCHILDREN ports. */
1649 	pipe = usb_rcvintpipe(hdev, endpoint->bEndpointAddress);
1650 	maxp = usb_maxpacket(hdev, pipe);
1651 
1652 	if (maxp > sizeof(*hub->buffer))
1653 		maxp = sizeof(*hub->buffer);
1654 
1655 	hub->urb = usb_alloc_urb(0, GFP_KERNEL);
1656 	if (!hub->urb) {
1657 		ret = -ENOMEM;
1658 		goto fail;
1659 	}
1660 
1661 	usb_fill_int_urb(hub->urb, hdev, pipe, *hub->buffer, maxp, hub_irq,
1662 		hub, endpoint->bInterval);
1663 
1664 	/* maybe cycle the hub leds */
1665 	if (hub->has_indicators && blinkenlights)
1666 		hub->indicator[0] = INDICATOR_CYCLE;
1667 
1668 	mutex_lock(&usb_port_peer_mutex);
1669 	for (i = 0; i < maxchild; i++) {
1670 		ret = usb_hub_create_port_device(hub, i + 1);
1671 		if (ret < 0) {
1672 			dev_err(hub->intfdev,
1673 				"couldn't create port%d device.\n", i + 1);
1674 			break;
1675 		}
1676 	}
1677 	hdev->maxchild = i;
1678 	for (i = 0; i < hdev->maxchild; i++) {
1679 		struct usb_port *port_dev = hub->ports[i];
1680 
1681 		pm_runtime_put(&port_dev->dev);
1682 	}
1683 
1684 	mutex_unlock(&usb_port_peer_mutex);
1685 	if (ret < 0)
1686 		goto fail;
1687 
1688 	/* Update the HCD's internal representation of this hub before hub_wq
1689 	 * starts getting port status changes for devices under the hub.
1690 	 */
1691 	if (hcd->driver->update_hub_device) {
1692 		ret = hcd->driver->update_hub_device(hcd, hdev,
1693 				&hub->tt, GFP_KERNEL);
1694 		if (ret < 0) {
1695 			message = "can't update HCD hub info";
1696 			goto fail;
1697 		}
1698 	}
1699 
1700 	usb_hub_adjust_deviceremovable(hdev, hub->descriptor);
1701 
1702 	hub_activate(hub, HUB_INIT);
1703 	return 0;
1704 
1705 fail:
1706 	dev_err(hub_dev, "config failed, %s (err %d)\n",
1707 			message, ret);
1708 	/* hub_disconnect() frees urb and descriptor */
1709 	return ret;
1710 }
1711 
1712 static void hub_release(struct kref *kref)
1713 {
1714 	struct usb_hub *hub = container_of(kref, struct usb_hub, kref);
1715 
1716 	usb_put_dev(hub->hdev);
1717 	usb_put_intf(to_usb_interface(hub->intfdev));
1718 	kfree(hub);
1719 }
1720 
1721 static unsigned highspeed_hubs;
1722 
1723 static void hub_disconnect(struct usb_interface *intf)
1724 {
1725 	struct usb_hub *hub = usb_get_intfdata(intf);
1726 	struct usb_device *hdev = interface_to_usbdev(intf);
1727 	int port1;
1728 
1729 	/*
1730 	 * Stop adding new hub events. We do not want to block here and thus
1731 	 * will not try to remove any pending work item.
1732 	 */
1733 	hub->disconnected = 1;
1734 
1735 	/* Disconnect all children and quiesce the hub */
1736 	hub->error = 0;
1737 	hub_quiesce(hub, HUB_DISCONNECT);
1738 
1739 	mutex_lock(&usb_port_peer_mutex);
1740 
1741 	/* Avoid races with recursively_mark_NOTATTACHED() */
1742 	spin_lock_irq(&device_state_lock);
1743 	port1 = hdev->maxchild;
1744 	hdev->maxchild = 0;
1745 	usb_set_intfdata(intf, NULL);
1746 	spin_unlock_irq(&device_state_lock);
1747 
1748 	for (; port1 > 0; --port1)
1749 		usb_hub_remove_port_device(hub, port1);
1750 
1751 	mutex_unlock(&usb_port_peer_mutex);
1752 
1753 	if (hub->hdev->speed == USB_SPEED_HIGH)
1754 		highspeed_hubs--;
1755 
1756 	usb_free_urb(hub->urb);
1757 	kfree(hub->ports);
1758 	kfree(hub->descriptor);
1759 	kfree(hub->status);
1760 	kfree(hub->buffer);
1761 
1762 	pm_suspend_ignore_children(&intf->dev, false);
1763 
1764 	if (hub->quirk_disable_autosuspend)
1765 		usb_autopm_put_interface(intf);
1766 
1767 	onboard_hub_destroy_pdevs(&hub->onboard_hub_devs);
1768 
1769 	kref_put(&hub->kref, hub_release);
1770 }
1771 
1772 static bool hub_descriptor_is_sane(struct usb_host_interface *desc)
1773 {
1774 	/* Some hubs have a subclass of 1, which AFAICT according to the */
1775 	/*  specs is not defined, but it works */
1776 	if (desc->desc.bInterfaceSubClass != 0 &&
1777 	    desc->desc.bInterfaceSubClass != 1)
1778 		return false;
1779 
1780 	/* Multiple endpoints? What kind of mutant ninja-hub is this? */
1781 	if (desc->desc.bNumEndpoints != 1)
1782 		return false;
1783 
1784 	/* If the first endpoint is not interrupt IN, we'd better punt! */
1785 	if (!usb_endpoint_is_int_in(&desc->endpoint[0].desc))
1786 		return false;
1787 
1788         return true;
1789 }
1790 
1791 static int hub_probe(struct usb_interface *intf, const struct usb_device_id *id)
1792 {
1793 	struct usb_host_interface *desc;
1794 	struct usb_device *hdev;
1795 	struct usb_hub *hub;
1796 
1797 	desc = intf->cur_altsetting;
1798 	hdev = interface_to_usbdev(intf);
1799 
1800 	/*
1801 	 * Set default autosuspend delay as 0 to speedup bus suspend,
1802 	 * based on the below considerations:
1803 	 *
1804 	 * - Unlike other drivers, the hub driver does not rely on the
1805 	 *   autosuspend delay to provide enough time to handle a wakeup
1806 	 *   event, and the submitted status URB is just to check future
1807 	 *   change on hub downstream ports, so it is safe to do it.
1808 	 *
1809 	 * - The patch might cause one or more auto supend/resume for
1810 	 *   below very rare devices when they are plugged into hub
1811 	 *   first time:
1812 	 *
1813 	 *   	devices having trouble initializing, and disconnect
1814 	 *   	themselves from the bus and then reconnect a second
1815 	 *   	or so later
1816 	 *
1817 	 *   	devices just for downloading firmware, and disconnects
1818 	 *   	themselves after completing it
1819 	 *
1820 	 *   For these quite rare devices, their drivers may change the
1821 	 *   autosuspend delay of their parent hub in the probe() to one
1822 	 *   appropriate value to avoid the subtle problem if someone
1823 	 *   does care it.
1824 	 *
1825 	 * - The patch may cause one or more auto suspend/resume on
1826 	 *   hub during running 'lsusb', but it is probably too
1827 	 *   infrequent to worry about.
1828 	 *
1829 	 * - Change autosuspend delay of hub can avoid unnecessary auto
1830 	 *   suspend timer for hub, also may decrease power consumption
1831 	 *   of USB bus.
1832 	 *
1833 	 * - If user has indicated to prevent autosuspend by passing
1834 	 *   usbcore.autosuspend = -1 then keep autosuspend disabled.
1835 	 */
1836 #ifdef CONFIG_PM
1837 	if (hdev->dev.power.autosuspend_delay >= 0)
1838 		pm_runtime_set_autosuspend_delay(&hdev->dev, 0);
1839 #endif
1840 
1841 	/*
1842 	 * Hubs have proper suspend/resume support, except for root hubs
1843 	 * where the controller driver doesn't have bus_suspend and
1844 	 * bus_resume methods.
1845 	 */
1846 	if (hdev->parent) {		/* normal device */
1847 		usb_enable_autosuspend(hdev);
1848 	} else {			/* root hub */
1849 		const struct hc_driver *drv = bus_to_hcd(hdev->bus)->driver;
1850 
1851 		if (drv->bus_suspend && drv->bus_resume)
1852 			usb_enable_autosuspend(hdev);
1853 	}
1854 
1855 	if (hdev->level == MAX_TOPO_LEVEL) {
1856 		dev_err(&intf->dev,
1857 			"Unsupported bus topology: hub nested too deep\n");
1858 		return -E2BIG;
1859 	}
1860 
1861 #ifdef	CONFIG_USB_OTG_DISABLE_EXTERNAL_HUB
1862 	if (hdev->parent) {
1863 		dev_warn(&intf->dev, "ignoring external hub\n");
1864 		return -ENODEV;
1865 	}
1866 #endif
1867 
1868 	if (!hub_descriptor_is_sane(desc)) {
1869 		dev_err(&intf->dev, "bad descriptor, ignoring hub\n");
1870 		return -EIO;
1871 	}
1872 
1873 	/* We found a hub */
1874 	dev_info(&intf->dev, "USB hub found\n");
1875 
1876 	hub = kzalloc(sizeof(*hub), GFP_KERNEL);
1877 	if (!hub)
1878 		return -ENOMEM;
1879 
1880 	kref_init(&hub->kref);
1881 	hub->intfdev = &intf->dev;
1882 	hub->hdev = hdev;
1883 	INIT_DELAYED_WORK(&hub->leds, led_work);
1884 	INIT_DELAYED_WORK(&hub->init_work, NULL);
1885 	INIT_WORK(&hub->events, hub_event);
1886 	INIT_LIST_HEAD(&hub->onboard_hub_devs);
1887 	spin_lock_init(&hub->irq_urb_lock);
1888 	timer_setup(&hub->irq_urb_retry, hub_retry_irq_urb, 0);
1889 	usb_get_intf(intf);
1890 	usb_get_dev(hdev);
1891 
1892 	usb_set_intfdata(intf, hub);
1893 	intf->needs_remote_wakeup = 1;
1894 	pm_suspend_ignore_children(&intf->dev, true);
1895 
1896 	if (hdev->speed == USB_SPEED_HIGH)
1897 		highspeed_hubs++;
1898 
1899 	if (id->driver_info & HUB_QUIRK_CHECK_PORT_AUTOSUSPEND)
1900 		hub->quirk_check_port_auto_suspend = 1;
1901 
1902 	if (id->driver_info & HUB_QUIRK_DISABLE_AUTOSUSPEND) {
1903 		hub->quirk_disable_autosuspend = 1;
1904 		usb_autopm_get_interface_no_resume(intf);
1905 	}
1906 
1907 	if (hub_configure(hub, &desc->endpoint[0].desc) >= 0) {
1908 		onboard_hub_create_pdevs(hdev, &hub->onboard_hub_devs);
1909 
1910 		return 0;
1911 	}
1912 
1913 	hub_disconnect(intf);
1914 	return -ENODEV;
1915 }
1916 
1917 static int
1918 hub_ioctl(struct usb_interface *intf, unsigned int code, void *user_data)
1919 {
1920 	struct usb_device *hdev = interface_to_usbdev(intf);
1921 	struct usb_hub *hub = usb_hub_to_struct_hub(hdev);
1922 
1923 	/* assert ifno == 0 (part of hub spec) */
1924 	switch (code) {
1925 	case USBDEVFS_HUB_PORTINFO: {
1926 		struct usbdevfs_hub_portinfo *info = user_data;
1927 		int i;
1928 
1929 		spin_lock_irq(&device_state_lock);
1930 		if (hdev->devnum <= 0)
1931 			info->nports = 0;
1932 		else {
1933 			info->nports = hdev->maxchild;
1934 			for (i = 0; i < info->nports; i++) {
1935 				if (hub->ports[i]->child == NULL)
1936 					info->port[i] = 0;
1937 				else
1938 					info->port[i] =
1939 						hub->ports[i]->child->devnum;
1940 			}
1941 		}
1942 		spin_unlock_irq(&device_state_lock);
1943 
1944 		return info->nports + 1;
1945 		}
1946 
1947 	default:
1948 		return -ENOSYS;
1949 	}
1950 }
1951 
1952 /*
1953  * Allow user programs to claim ports on a hub.  When a device is attached
1954  * to one of these "claimed" ports, the program will "own" the device.
1955  */
1956 static int find_port_owner(struct usb_device *hdev, unsigned port1,
1957 		struct usb_dev_state ***ppowner)
1958 {
1959 	struct usb_hub *hub = usb_hub_to_struct_hub(hdev);
1960 
1961 	if (hdev->state == USB_STATE_NOTATTACHED)
1962 		return -ENODEV;
1963 	if (port1 == 0 || port1 > hdev->maxchild)
1964 		return -EINVAL;
1965 
1966 	/* Devices not managed by the hub driver
1967 	 * will always have maxchild equal to 0.
1968 	 */
1969 	*ppowner = &(hub->ports[port1 - 1]->port_owner);
1970 	return 0;
1971 }
1972 
1973 /* In the following three functions, the caller must hold hdev's lock */
1974 int usb_hub_claim_port(struct usb_device *hdev, unsigned port1,
1975 		       struct usb_dev_state *owner)
1976 {
1977 	int rc;
1978 	struct usb_dev_state **powner;
1979 
1980 	rc = find_port_owner(hdev, port1, &powner);
1981 	if (rc)
1982 		return rc;
1983 	if (*powner)
1984 		return -EBUSY;
1985 	*powner = owner;
1986 	return rc;
1987 }
1988 EXPORT_SYMBOL_GPL(usb_hub_claim_port);
1989 
1990 int usb_hub_release_port(struct usb_device *hdev, unsigned port1,
1991 			 struct usb_dev_state *owner)
1992 {
1993 	int rc;
1994 	struct usb_dev_state **powner;
1995 
1996 	rc = find_port_owner(hdev, port1, &powner);
1997 	if (rc)
1998 		return rc;
1999 	if (*powner != owner)
2000 		return -ENOENT;
2001 	*powner = NULL;
2002 	return rc;
2003 }
2004 EXPORT_SYMBOL_GPL(usb_hub_release_port);
2005 
2006 void usb_hub_release_all_ports(struct usb_device *hdev, struct usb_dev_state *owner)
2007 {
2008 	struct usb_hub *hub = usb_hub_to_struct_hub(hdev);
2009 	int n;
2010 
2011 	for (n = 0; n < hdev->maxchild; n++) {
2012 		if (hub->ports[n]->port_owner == owner)
2013 			hub->ports[n]->port_owner = NULL;
2014 	}
2015 
2016 }
2017 
2018 /* The caller must hold udev's lock */
2019 bool usb_device_is_owned(struct usb_device *udev)
2020 {
2021 	struct usb_hub *hub;
2022 
2023 	if (udev->state == USB_STATE_NOTATTACHED || !udev->parent)
2024 		return false;
2025 	hub = usb_hub_to_struct_hub(udev->parent);
2026 	return !!hub->ports[udev->portnum - 1]->port_owner;
2027 }
2028 
2029 static void update_port_device_state(struct usb_device *udev)
2030 {
2031 	struct usb_hub *hub;
2032 	struct usb_port *port_dev;
2033 
2034 	if (udev->parent) {
2035 		hub = usb_hub_to_struct_hub(udev->parent);
2036 		port_dev = hub->ports[udev->portnum - 1];
2037 		WRITE_ONCE(port_dev->state, udev->state);
2038 		sysfs_notify_dirent(port_dev->state_kn);
2039 	}
2040 }
2041 
2042 static void recursively_mark_NOTATTACHED(struct usb_device *udev)
2043 {
2044 	struct usb_hub *hub = usb_hub_to_struct_hub(udev);
2045 	int i;
2046 
2047 	for (i = 0; i < udev->maxchild; ++i) {
2048 		if (hub->ports[i]->child)
2049 			recursively_mark_NOTATTACHED(hub->ports[i]->child);
2050 	}
2051 	if (udev->state == USB_STATE_SUSPENDED)
2052 		udev->active_duration -= jiffies;
2053 	udev->state = USB_STATE_NOTATTACHED;
2054 	update_port_device_state(udev);
2055 }
2056 
2057 /**
2058  * usb_set_device_state - change a device's current state (usbcore, hcds)
2059  * @udev: pointer to device whose state should be changed
2060  * @new_state: new state value to be stored
2061  *
2062  * udev->state is _not_ fully protected by the device lock.  Although
2063  * most transitions are made only while holding the lock, the state can
2064  * can change to USB_STATE_NOTATTACHED at almost any time.  This
2065  * is so that devices can be marked as disconnected as soon as possible,
2066  * without having to wait for any semaphores to be released.  As a result,
2067  * all changes to any device's state must be protected by the
2068  * device_state_lock spinlock.
2069  *
2070  * Once a device has been added to the device tree, all changes to its state
2071  * should be made using this routine.  The state should _not_ be set directly.
2072  *
2073  * If udev->state is already USB_STATE_NOTATTACHED then no change is made.
2074  * Otherwise udev->state is set to new_state, and if new_state is
2075  * USB_STATE_NOTATTACHED then all of udev's descendants' states are also set
2076  * to USB_STATE_NOTATTACHED.
2077  */
2078 void usb_set_device_state(struct usb_device *udev,
2079 		enum usb_device_state new_state)
2080 {
2081 	unsigned long flags;
2082 	int wakeup = -1;
2083 
2084 	spin_lock_irqsave(&device_state_lock, flags);
2085 	if (udev->state == USB_STATE_NOTATTACHED)
2086 		;	/* do nothing */
2087 	else if (new_state != USB_STATE_NOTATTACHED) {
2088 
2089 		/* root hub wakeup capabilities are managed out-of-band
2090 		 * and may involve silicon errata ... ignore them here.
2091 		 */
2092 		if (udev->parent) {
2093 			if (udev->state == USB_STATE_SUSPENDED
2094 					|| new_state == USB_STATE_SUSPENDED)
2095 				;	/* No change to wakeup settings */
2096 			else if (new_state == USB_STATE_CONFIGURED)
2097 				wakeup = (udev->quirks &
2098 					USB_QUIRK_IGNORE_REMOTE_WAKEUP) ? 0 :
2099 					udev->actconfig->desc.bmAttributes &
2100 					USB_CONFIG_ATT_WAKEUP;
2101 			else
2102 				wakeup = 0;
2103 		}
2104 		if (udev->state == USB_STATE_SUSPENDED &&
2105 			new_state != USB_STATE_SUSPENDED)
2106 			udev->active_duration -= jiffies;
2107 		else if (new_state == USB_STATE_SUSPENDED &&
2108 				udev->state != USB_STATE_SUSPENDED)
2109 			udev->active_duration += jiffies;
2110 		udev->state = new_state;
2111 		update_port_device_state(udev);
2112 	} else
2113 		recursively_mark_NOTATTACHED(udev);
2114 	spin_unlock_irqrestore(&device_state_lock, flags);
2115 	if (wakeup >= 0)
2116 		device_set_wakeup_capable(&udev->dev, wakeup);
2117 }
2118 EXPORT_SYMBOL_GPL(usb_set_device_state);
2119 
2120 /*
2121  * Choose a device number.
2122  *
2123  * Device numbers are used as filenames in usbfs.  On USB-1.1 and
2124  * USB-2.0 buses they are also used as device addresses, however on
2125  * USB-3.0 buses the address is assigned by the controller hardware
2126  * and it usually is not the same as the device number.
2127  *
2128  * Devices connected under xHCI are not as simple.  The host controller
2129  * supports virtualization, so the hardware assigns device addresses and
2130  * the HCD must setup data structures before issuing a set address
2131  * command to the hardware.
2132  */
2133 static void choose_devnum(struct usb_device *udev)
2134 {
2135 	int		devnum;
2136 	struct usb_bus	*bus = udev->bus;
2137 
2138 	/* be safe when more hub events are proceed in parallel */
2139 	mutex_lock(&bus->devnum_next_mutex);
2140 
2141 	/* Try to allocate the next devnum beginning at bus->devnum_next. */
2142 	devnum = find_next_zero_bit(bus->devmap.devicemap, 128,
2143 			bus->devnum_next);
2144 	if (devnum >= 128)
2145 		devnum = find_next_zero_bit(bus->devmap.devicemap, 128, 1);
2146 	bus->devnum_next = (devnum >= 127 ? 1 : devnum + 1);
2147 	if (devnum < 128) {
2148 		set_bit(devnum, bus->devmap.devicemap);
2149 		udev->devnum = devnum;
2150 	}
2151 	mutex_unlock(&bus->devnum_next_mutex);
2152 }
2153 
2154 static void release_devnum(struct usb_device *udev)
2155 {
2156 	if (udev->devnum > 0) {
2157 		clear_bit(udev->devnum, udev->bus->devmap.devicemap);
2158 		udev->devnum = -1;
2159 	}
2160 }
2161 
2162 static void update_devnum(struct usb_device *udev, int devnum)
2163 {
2164 	udev->devnum = devnum;
2165 	if (!udev->devaddr)
2166 		udev->devaddr = (u8)devnum;
2167 }
2168 
2169 static void hub_free_dev(struct usb_device *udev)
2170 {
2171 	struct usb_hcd *hcd = bus_to_hcd(udev->bus);
2172 
2173 	/* Root hubs aren't real devices, so don't free HCD resources */
2174 	if (hcd->driver->free_dev && udev->parent)
2175 		hcd->driver->free_dev(hcd, udev);
2176 }
2177 
2178 static void hub_disconnect_children(struct usb_device *udev)
2179 {
2180 	struct usb_hub *hub = usb_hub_to_struct_hub(udev);
2181 	int i;
2182 
2183 	/* Free up all the children before we remove this device */
2184 	for (i = 0; i < udev->maxchild; i++) {
2185 		if (hub->ports[i]->child)
2186 			usb_disconnect(&hub->ports[i]->child);
2187 	}
2188 }
2189 
2190 /**
2191  * usb_disconnect - disconnect a device (usbcore-internal)
2192  * @pdev: pointer to device being disconnected
2193  *
2194  * Context: task context, might sleep
2195  *
2196  * Something got disconnected. Get rid of it and all of its children.
2197  *
2198  * If *pdev is a normal device then the parent hub must already be locked.
2199  * If *pdev is a root hub then the caller must hold the usb_bus_idr_lock,
2200  * which protects the set of root hubs as well as the list of buses.
2201  *
2202  * Only hub drivers (including virtual root hub drivers for host
2203  * controllers) should ever call this.
2204  *
2205  * This call is synchronous, and may not be used in an interrupt context.
2206  */
2207 void usb_disconnect(struct usb_device **pdev)
2208 {
2209 	struct usb_port *port_dev = NULL;
2210 	struct usb_device *udev = *pdev;
2211 	struct usb_hub *hub = NULL;
2212 	int port1 = 1;
2213 
2214 	/* mark the device as inactive, so any further urb submissions for
2215 	 * this device (and any of its children) will fail immediately.
2216 	 * this quiesces everything except pending urbs.
2217 	 */
2218 	usb_set_device_state(udev, USB_STATE_NOTATTACHED);
2219 	dev_info(&udev->dev, "USB disconnect, device number %d\n",
2220 			udev->devnum);
2221 
2222 	/*
2223 	 * Ensure that the pm runtime code knows that the USB device
2224 	 * is in the process of being disconnected.
2225 	 */
2226 	pm_runtime_barrier(&udev->dev);
2227 
2228 	usb_lock_device(udev);
2229 
2230 	hub_disconnect_children(udev);
2231 
2232 	/* deallocate hcd/hardware state ... nuking all pending urbs and
2233 	 * cleaning up all state associated with the current configuration
2234 	 * so that the hardware is now fully quiesced.
2235 	 */
2236 	dev_dbg(&udev->dev, "unregistering device\n");
2237 	usb_disable_device(udev, 0);
2238 	usb_hcd_synchronize_unlinks(udev);
2239 
2240 	if (udev->parent) {
2241 		port1 = udev->portnum;
2242 		hub = usb_hub_to_struct_hub(udev->parent);
2243 		port_dev = hub->ports[port1 - 1];
2244 
2245 		sysfs_remove_link(&udev->dev.kobj, "port");
2246 		sysfs_remove_link(&port_dev->dev.kobj, "device");
2247 
2248 		/*
2249 		 * As usb_port_runtime_resume() de-references udev, make
2250 		 * sure no resumes occur during removal
2251 		 */
2252 		if (!test_and_set_bit(port1, hub->child_usage_bits))
2253 			pm_runtime_get_sync(&port_dev->dev);
2254 	}
2255 
2256 	usb_remove_ep_devs(&udev->ep0);
2257 	usb_unlock_device(udev);
2258 
2259 	/* Unregister the device.  The device driver is responsible
2260 	 * for de-configuring the device and invoking the remove-device
2261 	 * notifier chain (used by usbfs and possibly others).
2262 	 */
2263 	device_del(&udev->dev);
2264 
2265 	/* Free the device number and delete the parent's children[]
2266 	 * (or root_hub) pointer.
2267 	 */
2268 	release_devnum(udev);
2269 
2270 	/* Avoid races with recursively_mark_NOTATTACHED() */
2271 	spin_lock_irq(&device_state_lock);
2272 	*pdev = NULL;
2273 	spin_unlock_irq(&device_state_lock);
2274 
2275 	if (port_dev && test_and_clear_bit(port1, hub->child_usage_bits))
2276 		pm_runtime_put(&port_dev->dev);
2277 
2278 	hub_free_dev(udev);
2279 
2280 	put_device(&udev->dev);
2281 }
2282 
2283 #ifdef CONFIG_USB_ANNOUNCE_NEW_DEVICES
2284 static void show_string(struct usb_device *udev, char *id, char *string)
2285 {
2286 	if (!string)
2287 		return;
2288 	dev_info(&udev->dev, "%s: %s\n", id, string);
2289 }
2290 
2291 static void announce_device(struct usb_device *udev)
2292 {
2293 	u16 bcdDevice = le16_to_cpu(udev->descriptor.bcdDevice);
2294 
2295 	dev_info(&udev->dev,
2296 		"New USB device found, idVendor=%04x, idProduct=%04x, bcdDevice=%2x.%02x\n",
2297 		le16_to_cpu(udev->descriptor.idVendor),
2298 		le16_to_cpu(udev->descriptor.idProduct),
2299 		bcdDevice >> 8, bcdDevice & 0xff);
2300 	dev_info(&udev->dev,
2301 		"New USB device strings: Mfr=%d, Product=%d, SerialNumber=%d\n",
2302 		udev->descriptor.iManufacturer,
2303 		udev->descriptor.iProduct,
2304 		udev->descriptor.iSerialNumber);
2305 	show_string(udev, "Product", udev->product);
2306 	show_string(udev, "Manufacturer", udev->manufacturer);
2307 	show_string(udev, "SerialNumber", udev->serial);
2308 }
2309 #else
2310 static inline void announce_device(struct usb_device *udev) { }
2311 #endif
2312 
2313 
2314 /**
2315  * usb_enumerate_device_otg - FIXME (usbcore-internal)
2316  * @udev: newly addressed device (in ADDRESS state)
2317  *
2318  * Finish enumeration for On-The-Go devices
2319  *
2320  * Return: 0 if successful. A negative error code otherwise.
2321  */
2322 static int usb_enumerate_device_otg(struct usb_device *udev)
2323 {
2324 	int err = 0;
2325 
2326 #ifdef	CONFIG_USB_OTG
2327 	/*
2328 	 * OTG-aware devices on OTG-capable root hubs may be able to use SRP,
2329 	 * to wake us after we've powered off VBUS; and HNP, switching roles
2330 	 * "host" to "peripheral".  The OTG descriptor helps figure this out.
2331 	 */
2332 	if (!udev->bus->is_b_host
2333 			&& udev->config
2334 			&& udev->parent == udev->bus->root_hub) {
2335 		struct usb_otg_descriptor	*desc = NULL;
2336 		struct usb_bus			*bus = udev->bus;
2337 		unsigned			port1 = udev->portnum;
2338 
2339 		/* descriptor may appear anywhere in config */
2340 		err = __usb_get_extra_descriptor(udev->rawdescriptors[0],
2341 				le16_to_cpu(udev->config[0].desc.wTotalLength),
2342 				USB_DT_OTG, (void **) &desc, sizeof(*desc));
2343 		if (err || !(desc->bmAttributes & USB_OTG_HNP))
2344 			return 0;
2345 
2346 		dev_info(&udev->dev, "Dual-Role OTG device on %sHNP port\n",
2347 					(port1 == bus->otg_port) ? "" : "non-");
2348 
2349 		/* enable HNP before suspend, it's simpler */
2350 		if (port1 == bus->otg_port) {
2351 			bus->b_hnp_enable = 1;
2352 			err = usb_control_msg(udev,
2353 				usb_sndctrlpipe(udev, 0),
2354 				USB_REQ_SET_FEATURE, 0,
2355 				USB_DEVICE_B_HNP_ENABLE,
2356 				0, NULL, 0,
2357 				USB_CTRL_SET_TIMEOUT);
2358 			if (err < 0) {
2359 				/*
2360 				 * OTG MESSAGE: report errors here,
2361 				 * customize to match your product.
2362 				 */
2363 				dev_err(&udev->dev, "can't set HNP mode: %d\n",
2364 									err);
2365 				bus->b_hnp_enable = 0;
2366 			}
2367 		} else if (desc->bLength == sizeof
2368 				(struct usb_otg_descriptor)) {
2369 			/* Set a_alt_hnp_support for legacy otg device */
2370 			err = usb_control_msg(udev,
2371 				usb_sndctrlpipe(udev, 0),
2372 				USB_REQ_SET_FEATURE, 0,
2373 				USB_DEVICE_A_ALT_HNP_SUPPORT,
2374 				0, NULL, 0,
2375 				USB_CTRL_SET_TIMEOUT);
2376 			if (err < 0)
2377 				dev_err(&udev->dev,
2378 					"set a_alt_hnp_support failed: %d\n",
2379 					err);
2380 		}
2381 	}
2382 #endif
2383 	return err;
2384 }
2385 
2386 
2387 /**
2388  * usb_enumerate_device - Read device configs/intfs/otg (usbcore-internal)
2389  * @udev: newly addressed device (in ADDRESS state)
2390  *
2391  * This is only called by usb_new_device() -- all comments that apply there
2392  * apply here wrt to environment.
2393  *
2394  * If the device is WUSB and not authorized, we don't attempt to read
2395  * the string descriptors, as they will be errored out by the device
2396  * until it has been authorized.
2397  *
2398  * Return: 0 if successful. A negative error code otherwise.
2399  */
2400 static int usb_enumerate_device(struct usb_device *udev)
2401 {
2402 	int err;
2403 	struct usb_hcd *hcd = bus_to_hcd(udev->bus);
2404 
2405 	if (udev->config == NULL) {
2406 		err = usb_get_configuration(udev);
2407 		if (err < 0) {
2408 			if (err != -ENODEV)
2409 				dev_err(&udev->dev, "can't read configurations, error %d\n",
2410 						err);
2411 			return err;
2412 		}
2413 	}
2414 
2415 	/* read the standard strings and cache them if present */
2416 	udev->product = usb_cache_string(udev, udev->descriptor.iProduct);
2417 	udev->manufacturer = usb_cache_string(udev,
2418 					      udev->descriptor.iManufacturer);
2419 	udev->serial = usb_cache_string(udev, udev->descriptor.iSerialNumber);
2420 
2421 	err = usb_enumerate_device_otg(udev);
2422 	if (err < 0)
2423 		return err;
2424 
2425 	if (IS_ENABLED(CONFIG_USB_OTG_PRODUCTLIST) && hcd->tpl_support &&
2426 		!is_targeted(udev)) {
2427 		/* Maybe it can talk to us, though we can't talk to it.
2428 		 * (Includes HNP test device.)
2429 		 */
2430 		if (IS_ENABLED(CONFIG_USB_OTG) && (udev->bus->b_hnp_enable
2431 			|| udev->bus->is_b_host)) {
2432 			err = usb_port_suspend(udev, PMSG_AUTO_SUSPEND);
2433 			if (err < 0)
2434 				dev_dbg(&udev->dev, "HNP fail, %d\n", err);
2435 		}
2436 		return -ENOTSUPP;
2437 	}
2438 
2439 	usb_detect_interface_quirks(udev);
2440 
2441 	return 0;
2442 }
2443 
2444 static void set_usb_port_removable(struct usb_device *udev)
2445 {
2446 	struct usb_device *hdev = udev->parent;
2447 	struct usb_hub *hub;
2448 	u8 port = udev->portnum;
2449 	u16 wHubCharacteristics;
2450 	bool removable = true;
2451 
2452 	dev_set_removable(&udev->dev, DEVICE_REMOVABLE_UNKNOWN);
2453 
2454 	if (!hdev)
2455 		return;
2456 
2457 	hub = usb_hub_to_struct_hub(udev->parent);
2458 
2459 	/*
2460 	 * If the platform firmware has provided information about a port,
2461 	 * use that to determine whether it's removable.
2462 	 */
2463 	switch (hub->ports[udev->portnum - 1]->connect_type) {
2464 	case USB_PORT_CONNECT_TYPE_HOT_PLUG:
2465 		dev_set_removable(&udev->dev, DEVICE_REMOVABLE);
2466 		return;
2467 	case USB_PORT_CONNECT_TYPE_HARD_WIRED:
2468 	case USB_PORT_NOT_USED:
2469 		dev_set_removable(&udev->dev, DEVICE_FIXED);
2470 		return;
2471 	default:
2472 		break;
2473 	}
2474 
2475 	/*
2476 	 * Otherwise, check whether the hub knows whether a port is removable
2477 	 * or not
2478 	 */
2479 	wHubCharacteristics = le16_to_cpu(hub->descriptor->wHubCharacteristics);
2480 
2481 	if (!(wHubCharacteristics & HUB_CHAR_COMPOUND))
2482 		return;
2483 
2484 	if (hub_is_superspeed(hdev)) {
2485 		if (le16_to_cpu(hub->descriptor->u.ss.DeviceRemovable)
2486 				& (1 << port))
2487 			removable = false;
2488 	} else {
2489 		if (hub->descriptor->u.hs.DeviceRemovable[port / 8] & (1 << (port % 8)))
2490 			removable = false;
2491 	}
2492 
2493 	if (removable)
2494 		dev_set_removable(&udev->dev, DEVICE_REMOVABLE);
2495 	else
2496 		dev_set_removable(&udev->dev, DEVICE_FIXED);
2497 
2498 }
2499 
2500 /**
2501  * usb_new_device - perform initial device setup (usbcore-internal)
2502  * @udev: newly addressed device (in ADDRESS state)
2503  *
2504  * This is called with devices which have been detected but not fully
2505  * enumerated.  The device descriptor is available, but not descriptors
2506  * for any device configuration.  The caller must have locked either
2507  * the parent hub (if udev is a normal device) or else the
2508  * usb_bus_idr_lock (if udev is a root hub).  The parent's pointer to
2509  * udev has already been installed, but udev is not yet visible through
2510  * sysfs or other filesystem code.
2511  *
2512  * This call is synchronous, and may not be used in an interrupt context.
2513  *
2514  * Only the hub driver or root-hub registrar should ever call this.
2515  *
2516  * Return: Whether the device is configured properly or not. Zero if the
2517  * interface was registered with the driver core; else a negative errno
2518  * value.
2519  *
2520  */
2521 int usb_new_device(struct usb_device *udev)
2522 {
2523 	int err;
2524 
2525 	if (udev->parent) {
2526 		/* Initialize non-root-hub device wakeup to disabled;
2527 		 * device (un)configuration controls wakeup capable
2528 		 * sysfs power/wakeup controls wakeup enabled/disabled
2529 		 */
2530 		device_init_wakeup(&udev->dev, 0);
2531 	}
2532 
2533 	/* Tell the runtime-PM framework the device is active */
2534 	pm_runtime_set_active(&udev->dev);
2535 	pm_runtime_get_noresume(&udev->dev);
2536 	pm_runtime_use_autosuspend(&udev->dev);
2537 	pm_runtime_enable(&udev->dev);
2538 
2539 	/* By default, forbid autosuspend for all devices.  It will be
2540 	 * allowed for hubs during binding.
2541 	 */
2542 	usb_disable_autosuspend(udev);
2543 
2544 	err = usb_enumerate_device(udev);	/* Read descriptors */
2545 	if (err < 0)
2546 		goto fail;
2547 	dev_dbg(&udev->dev, "udev %d, busnum %d, minor = %d\n",
2548 			udev->devnum, udev->bus->busnum,
2549 			(((udev->bus->busnum-1) * 128) + (udev->devnum-1)));
2550 	/* export the usbdev device-node for libusb */
2551 	udev->dev.devt = MKDEV(USB_DEVICE_MAJOR,
2552 			(((udev->bus->busnum-1) * 128) + (udev->devnum-1)));
2553 
2554 	/* Tell the world! */
2555 	announce_device(udev);
2556 
2557 	if (udev->serial)
2558 		add_device_randomness(udev->serial, strlen(udev->serial));
2559 	if (udev->product)
2560 		add_device_randomness(udev->product, strlen(udev->product));
2561 	if (udev->manufacturer)
2562 		add_device_randomness(udev->manufacturer,
2563 				      strlen(udev->manufacturer));
2564 
2565 	device_enable_async_suspend(&udev->dev);
2566 
2567 	/* check whether the hub or firmware marks this port as non-removable */
2568 	set_usb_port_removable(udev);
2569 
2570 	/* Register the device.  The device driver is responsible
2571 	 * for configuring the device and invoking the add-device
2572 	 * notifier chain (used by usbfs and possibly others).
2573 	 */
2574 	err = device_add(&udev->dev);
2575 	if (err) {
2576 		dev_err(&udev->dev, "can't device_add, error %d\n", err);
2577 		goto fail;
2578 	}
2579 
2580 	/* Create link files between child device and usb port device. */
2581 	if (udev->parent) {
2582 		struct usb_hub *hub = usb_hub_to_struct_hub(udev->parent);
2583 		int port1 = udev->portnum;
2584 		struct usb_port	*port_dev = hub->ports[port1 - 1];
2585 
2586 		err = sysfs_create_link(&udev->dev.kobj,
2587 				&port_dev->dev.kobj, "port");
2588 		if (err)
2589 			goto fail;
2590 
2591 		err = sysfs_create_link(&port_dev->dev.kobj,
2592 				&udev->dev.kobj, "device");
2593 		if (err) {
2594 			sysfs_remove_link(&udev->dev.kobj, "port");
2595 			goto fail;
2596 		}
2597 
2598 		if (!test_and_set_bit(port1, hub->child_usage_bits))
2599 			pm_runtime_get_sync(&port_dev->dev);
2600 	}
2601 
2602 	(void) usb_create_ep_devs(&udev->dev, &udev->ep0, udev);
2603 	usb_mark_last_busy(udev);
2604 	pm_runtime_put_sync_autosuspend(&udev->dev);
2605 	return err;
2606 
2607 fail:
2608 	usb_set_device_state(udev, USB_STATE_NOTATTACHED);
2609 	pm_runtime_disable(&udev->dev);
2610 	pm_runtime_set_suspended(&udev->dev);
2611 	return err;
2612 }
2613 
2614 
2615 /**
2616  * usb_deauthorize_device - deauthorize a device (usbcore-internal)
2617  * @usb_dev: USB device
2618  *
2619  * Move the USB device to a very basic state where interfaces are disabled
2620  * and the device is in fact unconfigured and unusable.
2621  *
2622  * We share a lock (that we have) with device_del(), so we need to
2623  * defer its call.
2624  *
2625  * Return: 0.
2626  */
2627 int usb_deauthorize_device(struct usb_device *usb_dev)
2628 {
2629 	usb_lock_device(usb_dev);
2630 	if (usb_dev->authorized == 0)
2631 		goto out_unauthorized;
2632 
2633 	usb_dev->authorized = 0;
2634 	usb_set_configuration(usb_dev, -1);
2635 
2636 out_unauthorized:
2637 	usb_unlock_device(usb_dev);
2638 	return 0;
2639 }
2640 
2641 
2642 int usb_authorize_device(struct usb_device *usb_dev)
2643 {
2644 	int result = 0, c;
2645 
2646 	usb_lock_device(usb_dev);
2647 	if (usb_dev->authorized == 1)
2648 		goto out_authorized;
2649 
2650 	result = usb_autoresume_device(usb_dev);
2651 	if (result < 0) {
2652 		dev_err(&usb_dev->dev,
2653 			"can't autoresume for authorization: %d\n", result);
2654 		goto error_autoresume;
2655 	}
2656 
2657 	usb_dev->authorized = 1;
2658 	/* Choose and set the configuration.  This registers the interfaces
2659 	 * with the driver core and lets interface drivers bind to them.
2660 	 */
2661 	c = usb_choose_configuration(usb_dev);
2662 	if (c >= 0) {
2663 		result = usb_set_configuration(usb_dev, c);
2664 		if (result) {
2665 			dev_err(&usb_dev->dev,
2666 				"can't set config #%d, error %d\n", c, result);
2667 			/* This need not be fatal.  The user can try to
2668 			 * set other configurations. */
2669 		}
2670 	}
2671 	dev_info(&usb_dev->dev, "authorized to connect\n");
2672 
2673 	usb_autosuspend_device(usb_dev);
2674 error_autoresume:
2675 out_authorized:
2676 	usb_unlock_device(usb_dev);	/* complements locktree */
2677 	return result;
2678 }
2679 
2680 /**
2681  * get_port_ssp_rate - Match the extended port status to SSP rate
2682  * @hdev: The hub device
2683  * @ext_portstatus: extended port status
2684  *
2685  * Match the extended port status speed id to the SuperSpeed Plus sublink speed
2686  * capability attributes. Base on the number of connected lanes and speed,
2687  * return the corresponding enum usb_ssp_rate.
2688  */
2689 static enum usb_ssp_rate get_port_ssp_rate(struct usb_device *hdev,
2690 					   u32 ext_portstatus)
2691 {
2692 	struct usb_ssp_cap_descriptor *ssp_cap;
2693 	u32 attr;
2694 	u8 speed_id;
2695 	u8 ssac;
2696 	u8 lanes;
2697 	int i;
2698 
2699 	if (!hdev->bos)
2700 		goto out;
2701 
2702 	ssp_cap = hdev->bos->ssp_cap;
2703 	if (!ssp_cap)
2704 		goto out;
2705 
2706 	speed_id = ext_portstatus & USB_EXT_PORT_STAT_RX_SPEED_ID;
2707 	lanes = USB_EXT_PORT_RX_LANES(ext_portstatus) + 1;
2708 
2709 	ssac = le32_to_cpu(ssp_cap->bmAttributes) &
2710 		USB_SSP_SUBLINK_SPEED_ATTRIBS;
2711 
2712 	for (i = 0; i <= ssac; i++) {
2713 		u8 ssid;
2714 
2715 		attr = le32_to_cpu(ssp_cap->bmSublinkSpeedAttr[i]);
2716 		ssid = FIELD_GET(USB_SSP_SUBLINK_SPEED_SSID, attr);
2717 		if (speed_id == ssid) {
2718 			u16 mantissa;
2719 			u8 lse;
2720 			u8 type;
2721 
2722 			/*
2723 			 * Note: currently asymmetric lane types are only
2724 			 * applicable for SSIC operate in SuperSpeed protocol
2725 			 */
2726 			type = FIELD_GET(USB_SSP_SUBLINK_SPEED_ST, attr);
2727 			if (type == USB_SSP_SUBLINK_SPEED_ST_ASYM_RX ||
2728 			    type == USB_SSP_SUBLINK_SPEED_ST_ASYM_TX)
2729 				goto out;
2730 
2731 			if (FIELD_GET(USB_SSP_SUBLINK_SPEED_LP, attr) !=
2732 			    USB_SSP_SUBLINK_SPEED_LP_SSP)
2733 				goto out;
2734 
2735 			lse = FIELD_GET(USB_SSP_SUBLINK_SPEED_LSE, attr);
2736 			mantissa = FIELD_GET(USB_SSP_SUBLINK_SPEED_LSM, attr);
2737 
2738 			/* Convert to Gbps */
2739 			for (; lse < USB_SSP_SUBLINK_SPEED_LSE_GBPS; lse++)
2740 				mantissa /= 1000;
2741 
2742 			if (mantissa >= 10 && lanes == 1)
2743 				return USB_SSP_GEN_2x1;
2744 
2745 			if (mantissa >= 10 && lanes == 2)
2746 				return USB_SSP_GEN_2x2;
2747 
2748 			if (mantissa >= 5 && lanes == 2)
2749 				return USB_SSP_GEN_1x2;
2750 
2751 			goto out;
2752 		}
2753 	}
2754 
2755 out:
2756 	return USB_SSP_GEN_UNKNOWN;
2757 }
2758 
2759 #ifdef CONFIG_USB_FEW_INIT_RETRIES
2760 #define PORT_RESET_TRIES	2
2761 #define SET_ADDRESS_TRIES	1
2762 #define GET_DESCRIPTOR_TRIES	1
2763 #define GET_MAXPACKET0_TRIES	1
2764 #define PORT_INIT_TRIES		4
2765 
2766 #else
2767 #define PORT_RESET_TRIES	5
2768 #define SET_ADDRESS_TRIES	2
2769 #define GET_DESCRIPTOR_TRIES	2
2770 #define GET_MAXPACKET0_TRIES	3
2771 #define PORT_INIT_TRIES		4
2772 #endif	/* CONFIG_USB_FEW_INIT_RETRIES */
2773 
2774 #define DETECT_DISCONNECT_TRIES 5
2775 
2776 #define HUB_ROOT_RESET_TIME	60	/* times are in msec */
2777 #define HUB_SHORT_RESET_TIME	10
2778 #define HUB_BH_RESET_TIME	50
2779 #define HUB_LONG_RESET_TIME	200
2780 #define HUB_RESET_TIMEOUT	800
2781 
2782 static bool use_new_scheme(struct usb_device *udev, int retry,
2783 			   struct usb_port *port_dev)
2784 {
2785 	int old_scheme_first_port =
2786 		(port_dev->quirks & USB_PORT_QUIRK_OLD_SCHEME) ||
2787 		old_scheme_first;
2788 
2789 	/*
2790 	 * "New scheme" enumeration causes an extra state transition to be
2791 	 * exposed to an xhci host and causes USB3 devices to receive control
2792 	 * commands in the default state.  This has been seen to cause
2793 	 * enumeration failures, so disable this enumeration scheme for USB3
2794 	 * devices.
2795 	 */
2796 	if (udev->speed >= USB_SPEED_SUPER)
2797 		return false;
2798 
2799 	/*
2800 	 * If use_both_schemes is set, use the first scheme (whichever
2801 	 * it is) for the larger half of the retries, then use the other
2802 	 * scheme.  Otherwise, use the first scheme for all the retries.
2803 	 */
2804 	if (use_both_schemes && retry >= (PORT_INIT_TRIES + 1) / 2)
2805 		return old_scheme_first_port;	/* Second half */
2806 	return !old_scheme_first_port;		/* First half or all */
2807 }
2808 
2809 /* Is a USB 3.0 port in the Inactive or Compliance Mode state?
2810  * Port warm reset is required to recover
2811  */
2812 static bool hub_port_warm_reset_required(struct usb_hub *hub, int port1,
2813 		u16 portstatus)
2814 {
2815 	u16 link_state;
2816 
2817 	if (!hub_is_superspeed(hub->hdev))
2818 		return false;
2819 
2820 	if (test_bit(port1, hub->warm_reset_bits))
2821 		return true;
2822 
2823 	link_state = portstatus & USB_PORT_STAT_LINK_STATE;
2824 	return link_state == USB_SS_PORT_LS_SS_INACTIVE
2825 		|| link_state == USB_SS_PORT_LS_COMP_MOD;
2826 }
2827 
2828 static int hub_port_wait_reset(struct usb_hub *hub, int port1,
2829 			struct usb_device *udev, unsigned int delay, bool warm)
2830 {
2831 	int delay_time, ret;
2832 	u16 portstatus;
2833 	u16 portchange;
2834 	u32 ext_portstatus = 0;
2835 
2836 	for (delay_time = 0;
2837 			delay_time < HUB_RESET_TIMEOUT;
2838 			delay_time += delay) {
2839 		/* wait to give the device a chance to reset */
2840 		msleep(delay);
2841 
2842 		/* read and decode port status */
2843 		if (hub_is_superspeedplus(hub->hdev))
2844 			ret = hub_ext_port_status(hub, port1,
2845 						  HUB_EXT_PORT_STATUS,
2846 						  &portstatus, &portchange,
2847 						  &ext_portstatus);
2848 		else
2849 			ret = usb_hub_port_status(hub, port1, &portstatus,
2850 					      &portchange);
2851 		if (ret < 0)
2852 			return ret;
2853 
2854 		/*
2855 		 * The port state is unknown until the reset completes.
2856 		 *
2857 		 * On top of that, some chips may require additional time
2858 		 * to re-establish a connection after the reset is complete,
2859 		 * so also wait for the connection to be re-established.
2860 		 */
2861 		if (!(portstatus & USB_PORT_STAT_RESET) &&
2862 		    (portstatus & USB_PORT_STAT_CONNECTION))
2863 			break;
2864 
2865 		/* switch to the long delay after two short delay failures */
2866 		if (delay_time >= 2 * HUB_SHORT_RESET_TIME)
2867 			delay = HUB_LONG_RESET_TIME;
2868 
2869 		dev_dbg(&hub->ports[port1 - 1]->dev,
2870 				"not %sreset yet, waiting %dms\n",
2871 				warm ? "warm " : "", delay);
2872 	}
2873 
2874 	if ((portstatus & USB_PORT_STAT_RESET))
2875 		return -EBUSY;
2876 
2877 	if (hub_port_warm_reset_required(hub, port1, portstatus))
2878 		return -ENOTCONN;
2879 
2880 	/* Device went away? */
2881 	if (!(portstatus & USB_PORT_STAT_CONNECTION))
2882 		return -ENOTCONN;
2883 
2884 	/* Retry if connect change is set but status is still connected.
2885 	 * A USB 3.0 connection may bounce if multiple warm resets were issued,
2886 	 * but the device may have successfully re-connected. Ignore it.
2887 	 */
2888 	if (!hub_is_superspeed(hub->hdev) &&
2889 	    (portchange & USB_PORT_STAT_C_CONNECTION)) {
2890 		usb_clear_port_feature(hub->hdev, port1,
2891 				       USB_PORT_FEAT_C_CONNECTION);
2892 		return -EAGAIN;
2893 	}
2894 
2895 	if (!(portstatus & USB_PORT_STAT_ENABLE))
2896 		return -EBUSY;
2897 
2898 	if (!udev)
2899 		return 0;
2900 
2901 	if (hub_is_superspeedplus(hub->hdev)) {
2902 		/* extended portstatus Rx and Tx lane count are zero based */
2903 		udev->rx_lanes = USB_EXT_PORT_RX_LANES(ext_portstatus) + 1;
2904 		udev->tx_lanes = USB_EXT_PORT_TX_LANES(ext_portstatus) + 1;
2905 		udev->ssp_rate = get_port_ssp_rate(hub->hdev, ext_portstatus);
2906 	} else {
2907 		udev->rx_lanes = 1;
2908 		udev->tx_lanes = 1;
2909 		udev->ssp_rate = USB_SSP_GEN_UNKNOWN;
2910 	}
2911 	if (udev->ssp_rate != USB_SSP_GEN_UNKNOWN)
2912 		udev->speed = USB_SPEED_SUPER_PLUS;
2913 	else if (hub_is_superspeed(hub->hdev))
2914 		udev->speed = USB_SPEED_SUPER;
2915 	else if (portstatus & USB_PORT_STAT_HIGH_SPEED)
2916 		udev->speed = USB_SPEED_HIGH;
2917 	else if (portstatus & USB_PORT_STAT_LOW_SPEED)
2918 		udev->speed = USB_SPEED_LOW;
2919 	else
2920 		udev->speed = USB_SPEED_FULL;
2921 	return 0;
2922 }
2923 
2924 /* Handle port reset and port warm(BH) reset (for USB3 protocol ports) */
2925 static int hub_port_reset(struct usb_hub *hub, int port1,
2926 			struct usb_device *udev, unsigned int delay, bool warm)
2927 {
2928 	int i, status;
2929 	u16 portchange, portstatus;
2930 	struct usb_port *port_dev = hub->ports[port1 - 1];
2931 	int reset_recovery_time;
2932 
2933 	if (!hub_is_superspeed(hub->hdev)) {
2934 		if (warm) {
2935 			dev_err(hub->intfdev, "only USB3 hub support "
2936 						"warm reset\n");
2937 			return -EINVAL;
2938 		}
2939 		/* Block EHCI CF initialization during the port reset.
2940 		 * Some companion controllers don't like it when they mix.
2941 		 */
2942 		down_read(&ehci_cf_port_reset_rwsem);
2943 	} else if (!warm) {
2944 		/*
2945 		 * If the caller hasn't explicitly requested a warm reset,
2946 		 * double check and see if one is needed.
2947 		 */
2948 		if (usb_hub_port_status(hub, port1, &portstatus,
2949 					&portchange) == 0)
2950 			if (hub_port_warm_reset_required(hub, port1,
2951 							portstatus))
2952 				warm = true;
2953 	}
2954 	clear_bit(port1, hub->warm_reset_bits);
2955 
2956 	/* Reset the port */
2957 	for (i = 0; i < PORT_RESET_TRIES; i++) {
2958 		status = set_port_feature(hub->hdev, port1, (warm ?
2959 					USB_PORT_FEAT_BH_PORT_RESET :
2960 					USB_PORT_FEAT_RESET));
2961 		if (status == -ENODEV) {
2962 			;	/* The hub is gone */
2963 		} else if (status) {
2964 			dev_err(&port_dev->dev,
2965 					"cannot %sreset (err = %d)\n",
2966 					warm ? "warm " : "", status);
2967 		} else {
2968 			status = hub_port_wait_reset(hub, port1, udev, delay,
2969 								warm);
2970 			if (status && status != -ENOTCONN && status != -ENODEV)
2971 				dev_dbg(hub->intfdev,
2972 						"port_wait_reset: err = %d\n",
2973 						status);
2974 		}
2975 
2976 		/*
2977 		 * Check for disconnect or reset, and bail out after several
2978 		 * reset attempts to avoid warm reset loop.
2979 		 */
2980 		if (status == 0 || status == -ENOTCONN || status == -ENODEV ||
2981 		    (status == -EBUSY && i == PORT_RESET_TRIES - 1)) {
2982 			usb_clear_port_feature(hub->hdev, port1,
2983 					USB_PORT_FEAT_C_RESET);
2984 
2985 			if (!hub_is_superspeed(hub->hdev))
2986 				goto done;
2987 
2988 			usb_clear_port_feature(hub->hdev, port1,
2989 					USB_PORT_FEAT_C_BH_PORT_RESET);
2990 			usb_clear_port_feature(hub->hdev, port1,
2991 					USB_PORT_FEAT_C_PORT_LINK_STATE);
2992 
2993 			if (udev)
2994 				usb_clear_port_feature(hub->hdev, port1,
2995 					USB_PORT_FEAT_C_CONNECTION);
2996 
2997 			/*
2998 			 * If a USB 3.0 device migrates from reset to an error
2999 			 * state, re-issue the warm reset.
3000 			 */
3001 			if (usb_hub_port_status(hub, port1,
3002 					&portstatus, &portchange) < 0)
3003 				goto done;
3004 
3005 			if (!hub_port_warm_reset_required(hub, port1,
3006 					portstatus))
3007 				goto done;
3008 
3009 			/*
3010 			 * If the port is in SS.Inactive or Compliance Mode, the
3011 			 * hot or warm reset failed.  Try another warm reset.
3012 			 */
3013 			if (!warm) {
3014 				dev_dbg(&port_dev->dev,
3015 						"hot reset failed, warm reset\n");
3016 				warm = true;
3017 			}
3018 		}
3019 
3020 		dev_dbg(&port_dev->dev,
3021 				"not enabled, trying %sreset again...\n",
3022 				warm ? "warm " : "");
3023 		delay = HUB_LONG_RESET_TIME;
3024 	}
3025 
3026 	dev_err(&port_dev->dev, "Cannot enable. Maybe the USB cable is bad?\n");
3027 
3028 done:
3029 	if (status == 0) {
3030 		if (port_dev->quirks & USB_PORT_QUIRK_FAST_ENUM)
3031 			usleep_range(10000, 12000);
3032 		else {
3033 			/* TRSTRCY = 10 ms; plus some extra */
3034 			reset_recovery_time = 10 + 40;
3035 
3036 			/* Hub needs extra delay after resetting its port. */
3037 			if (hub->hdev->quirks & USB_QUIRK_HUB_SLOW_RESET)
3038 				reset_recovery_time += 100;
3039 
3040 			msleep(reset_recovery_time);
3041 		}
3042 
3043 		if (udev) {
3044 			struct usb_hcd *hcd = bus_to_hcd(udev->bus);
3045 
3046 			update_devnum(udev, 0);
3047 			/* The xHC may think the device is already reset,
3048 			 * so ignore the status.
3049 			 */
3050 			if (hcd->driver->reset_device)
3051 				hcd->driver->reset_device(hcd, udev);
3052 
3053 			usb_set_device_state(udev, USB_STATE_DEFAULT);
3054 		}
3055 	} else {
3056 		if (udev)
3057 			usb_set_device_state(udev, USB_STATE_NOTATTACHED);
3058 	}
3059 
3060 	if (!hub_is_superspeed(hub->hdev))
3061 		up_read(&ehci_cf_port_reset_rwsem);
3062 
3063 	return status;
3064 }
3065 
3066 /*
3067  * hub_port_stop_enumerate - stop USB enumeration or ignore port events
3068  * @hub: target hub
3069  * @port1: port num of the port
3070  * @retries: port retries number of hub_port_init()
3071  *
3072  * Return:
3073  *    true: ignore port actions/events or give up connection attempts.
3074  *    false: keep original behavior.
3075  *
3076  * This function will be based on retries to check whether the port which is
3077  * marked with early_stop attribute would stop enumeration or ignore events.
3078  *
3079  * Note:
3080  * This function didn't change anything if early_stop is not set, and it will
3081  * prevent all connection attempts when early_stop is set and the attempts of
3082  * the port are more than 1.
3083  */
3084 static bool hub_port_stop_enumerate(struct usb_hub *hub, int port1, int retries)
3085 {
3086 	struct usb_port *port_dev = hub->ports[port1 - 1];
3087 
3088 	if (port_dev->early_stop) {
3089 		if (port_dev->ignore_event)
3090 			return true;
3091 
3092 		/*
3093 		 * We want unsuccessful attempts to fail quickly.
3094 		 * Since some devices may need one failure during
3095 		 * port initialization, we allow two tries but no
3096 		 * more.
3097 		 */
3098 		if (retries < 2)
3099 			return false;
3100 
3101 		port_dev->ignore_event = 1;
3102 	} else
3103 		port_dev->ignore_event = 0;
3104 
3105 	return port_dev->ignore_event;
3106 }
3107 
3108 /* Check if a port is power on */
3109 int usb_port_is_power_on(struct usb_hub *hub, unsigned int portstatus)
3110 {
3111 	int ret = 0;
3112 
3113 	if (hub_is_superspeed(hub->hdev)) {
3114 		if (portstatus & USB_SS_PORT_STAT_POWER)
3115 			ret = 1;
3116 	} else {
3117 		if (portstatus & USB_PORT_STAT_POWER)
3118 			ret = 1;
3119 	}
3120 
3121 	return ret;
3122 }
3123 
3124 static void usb_lock_port(struct usb_port *port_dev)
3125 		__acquires(&port_dev->status_lock)
3126 {
3127 	mutex_lock(&port_dev->status_lock);
3128 	__acquire(&port_dev->status_lock);
3129 }
3130 
3131 static void usb_unlock_port(struct usb_port *port_dev)
3132 		__releases(&port_dev->status_lock)
3133 {
3134 	mutex_unlock(&port_dev->status_lock);
3135 	__release(&port_dev->status_lock);
3136 }
3137 
3138 #ifdef	CONFIG_PM
3139 
3140 /* Check if a port is suspended(USB2.0 port) or in U3 state(USB3.0 port) */
3141 static int port_is_suspended(struct usb_hub *hub, unsigned portstatus)
3142 {
3143 	int ret = 0;
3144 
3145 	if (hub_is_superspeed(hub->hdev)) {
3146 		if ((portstatus & USB_PORT_STAT_LINK_STATE)
3147 				== USB_SS_PORT_LS_U3)
3148 			ret = 1;
3149 	} else {
3150 		if (portstatus & USB_PORT_STAT_SUSPEND)
3151 			ret = 1;
3152 	}
3153 
3154 	return ret;
3155 }
3156 
3157 /* Determine whether the device on a port is ready for a normal resume,
3158  * is ready for a reset-resume, or should be disconnected.
3159  */
3160 static int check_port_resume_type(struct usb_device *udev,
3161 		struct usb_hub *hub, int port1,
3162 		int status, u16 portchange, u16 portstatus)
3163 {
3164 	struct usb_port *port_dev = hub->ports[port1 - 1];
3165 	int retries = 3;
3166 
3167  retry:
3168 	/* Is a warm reset needed to recover the connection? */
3169 	if (status == 0 && udev->reset_resume
3170 		&& hub_port_warm_reset_required(hub, port1, portstatus)) {
3171 		/* pass */;
3172 	}
3173 	/* Is the device still present? */
3174 	else if (status || port_is_suspended(hub, portstatus) ||
3175 			!usb_port_is_power_on(hub, portstatus)) {
3176 		if (status >= 0)
3177 			status = -ENODEV;
3178 	} else if (!(portstatus & USB_PORT_STAT_CONNECTION)) {
3179 		if (retries--) {
3180 			usleep_range(200, 300);
3181 			status = usb_hub_port_status(hub, port1, &portstatus,
3182 							     &portchange);
3183 			goto retry;
3184 		}
3185 		status = -ENODEV;
3186 	}
3187 
3188 	/* Can't do a normal resume if the port isn't enabled,
3189 	 * so try a reset-resume instead.
3190 	 */
3191 	else if (!(portstatus & USB_PORT_STAT_ENABLE) && !udev->reset_resume) {
3192 		if (udev->persist_enabled)
3193 			udev->reset_resume = 1;
3194 		else
3195 			status = -ENODEV;
3196 	}
3197 
3198 	if (status) {
3199 		dev_dbg(&port_dev->dev, "status %04x.%04x after resume, %d\n",
3200 				portchange, portstatus, status);
3201 	} else if (udev->reset_resume) {
3202 
3203 		/* Late port handoff can set status-change bits */
3204 		if (portchange & USB_PORT_STAT_C_CONNECTION)
3205 			usb_clear_port_feature(hub->hdev, port1,
3206 					USB_PORT_FEAT_C_CONNECTION);
3207 		if (portchange & USB_PORT_STAT_C_ENABLE)
3208 			usb_clear_port_feature(hub->hdev, port1,
3209 					USB_PORT_FEAT_C_ENABLE);
3210 
3211 		/*
3212 		 * Whatever made this reset-resume necessary may have
3213 		 * turned on the port1 bit in hub->change_bits.  But after
3214 		 * a successful reset-resume we want the bit to be clear;
3215 		 * if it was on it would indicate that something happened
3216 		 * following the reset-resume.
3217 		 */
3218 		clear_bit(port1, hub->change_bits);
3219 	}
3220 
3221 	return status;
3222 }
3223 
3224 int usb_disable_ltm(struct usb_device *udev)
3225 {
3226 	struct usb_hcd *hcd = bus_to_hcd(udev->bus);
3227 
3228 	/* Check if the roothub and device supports LTM. */
3229 	if (!usb_device_supports_ltm(hcd->self.root_hub) ||
3230 			!usb_device_supports_ltm(udev))
3231 		return 0;
3232 
3233 	/* Clear Feature LTM Enable can only be sent if the device is
3234 	 * configured.
3235 	 */
3236 	if (!udev->actconfig)
3237 		return 0;
3238 
3239 	return usb_control_msg(udev, usb_sndctrlpipe(udev, 0),
3240 			USB_REQ_CLEAR_FEATURE, USB_RECIP_DEVICE,
3241 			USB_DEVICE_LTM_ENABLE, 0, NULL, 0,
3242 			USB_CTRL_SET_TIMEOUT);
3243 }
3244 EXPORT_SYMBOL_GPL(usb_disable_ltm);
3245 
3246 void usb_enable_ltm(struct usb_device *udev)
3247 {
3248 	struct usb_hcd *hcd = bus_to_hcd(udev->bus);
3249 
3250 	/* Check if the roothub and device supports LTM. */
3251 	if (!usb_device_supports_ltm(hcd->self.root_hub) ||
3252 			!usb_device_supports_ltm(udev))
3253 		return;
3254 
3255 	/* Set Feature LTM Enable can only be sent if the device is
3256 	 * configured.
3257 	 */
3258 	if (!udev->actconfig)
3259 		return;
3260 
3261 	usb_control_msg(udev, usb_sndctrlpipe(udev, 0),
3262 			USB_REQ_SET_FEATURE, USB_RECIP_DEVICE,
3263 			USB_DEVICE_LTM_ENABLE, 0, NULL, 0,
3264 			USB_CTRL_SET_TIMEOUT);
3265 }
3266 EXPORT_SYMBOL_GPL(usb_enable_ltm);
3267 
3268 /*
3269  * usb_enable_remote_wakeup - enable remote wakeup for a device
3270  * @udev: target device
3271  *
3272  * For USB-2 devices: Set the device's remote wakeup feature.
3273  *
3274  * For USB-3 devices: Assume there's only one function on the device and
3275  * enable remote wake for the first interface.  FIXME if the interface
3276  * association descriptor shows there's more than one function.
3277  */
3278 static int usb_enable_remote_wakeup(struct usb_device *udev)
3279 {
3280 	if (udev->speed < USB_SPEED_SUPER)
3281 		return usb_control_msg(udev, usb_sndctrlpipe(udev, 0),
3282 				USB_REQ_SET_FEATURE, USB_RECIP_DEVICE,
3283 				USB_DEVICE_REMOTE_WAKEUP, 0, NULL, 0,
3284 				USB_CTRL_SET_TIMEOUT);
3285 	else
3286 		return usb_control_msg(udev, usb_sndctrlpipe(udev, 0),
3287 				USB_REQ_SET_FEATURE, USB_RECIP_INTERFACE,
3288 				USB_INTRF_FUNC_SUSPEND,
3289 				USB_INTRF_FUNC_SUSPEND_RW |
3290 					USB_INTRF_FUNC_SUSPEND_LP,
3291 				NULL, 0, USB_CTRL_SET_TIMEOUT);
3292 }
3293 
3294 /*
3295  * usb_disable_remote_wakeup - disable remote wakeup for a device
3296  * @udev: target device
3297  *
3298  * For USB-2 devices: Clear the device's remote wakeup feature.
3299  *
3300  * For USB-3 devices: Assume there's only one function on the device and
3301  * disable remote wake for the first interface.  FIXME if the interface
3302  * association descriptor shows there's more than one function.
3303  */
3304 static int usb_disable_remote_wakeup(struct usb_device *udev)
3305 {
3306 	if (udev->speed < USB_SPEED_SUPER)
3307 		return usb_control_msg(udev, usb_sndctrlpipe(udev, 0),
3308 				USB_REQ_CLEAR_FEATURE, USB_RECIP_DEVICE,
3309 				USB_DEVICE_REMOTE_WAKEUP, 0, NULL, 0,
3310 				USB_CTRL_SET_TIMEOUT);
3311 	else
3312 		return usb_control_msg(udev, usb_sndctrlpipe(udev, 0),
3313 				USB_REQ_SET_FEATURE, USB_RECIP_INTERFACE,
3314 				USB_INTRF_FUNC_SUSPEND,	0, NULL, 0,
3315 				USB_CTRL_SET_TIMEOUT);
3316 }
3317 
3318 /* Count of wakeup-enabled devices at or below udev */
3319 unsigned usb_wakeup_enabled_descendants(struct usb_device *udev)
3320 {
3321 	struct usb_hub *hub = usb_hub_to_struct_hub(udev);
3322 
3323 	return udev->do_remote_wakeup +
3324 			(hub ? hub->wakeup_enabled_descendants : 0);
3325 }
3326 EXPORT_SYMBOL_GPL(usb_wakeup_enabled_descendants);
3327 
3328 /*
3329  * usb_port_suspend - suspend a usb device's upstream port
3330  * @udev: device that's no longer in active use, not a root hub
3331  * Context: must be able to sleep; device not locked; pm locks held
3332  *
3333  * Suspends a USB device that isn't in active use, conserving power.
3334  * Devices may wake out of a suspend, if anything important happens,
3335  * using the remote wakeup mechanism.  They may also be taken out of
3336  * suspend by the host, using usb_port_resume().  It's also routine
3337  * to disconnect devices while they are suspended.
3338  *
3339  * This only affects the USB hardware for a device; its interfaces
3340  * (and, for hubs, child devices) must already have been suspended.
3341  *
3342  * Selective port suspend reduces power; most suspended devices draw
3343  * less than 500 uA.  It's also used in OTG, along with remote wakeup.
3344  * All devices below the suspended port are also suspended.
3345  *
3346  * Devices leave suspend state when the host wakes them up.  Some devices
3347  * also support "remote wakeup", where the device can activate the USB
3348  * tree above them to deliver data, such as a keypress or packet.  In
3349  * some cases, this wakes the USB host.
3350  *
3351  * Suspending OTG devices may trigger HNP, if that's been enabled
3352  * between a pair of dual-role devices.  That will change roles, such
3353  * as from A-Host to A-Peripheral or from B-Host back to B-Peripheral.
3354  *
3355  * Devices on USB hub ports have only one "suspend" state, corresponding
3356  * to ACPI D2, "may cause the device to lose some context".
3357  * State transitions include:
3358  *
3359  *   - suspend, resume ... when the VBUS power link stays live
3360  *   - suspend, disconnect ... VBUS lost
3361  *
3362  * Once VBUS drop breaks the circuit, the port it's using has to go through
3363  * normal re-enumeration procedures, starting with enabling VBUS power.
3364  * Other than re-initializing the hub (plug/unplug, except for root hubs),
3365  * Linux (2.6) currently has NO mechanisms to initiate that:  no hub_wq
3366  * timer, no SRP, no requests through sysfs.
3367  *
3368  * If Runtime PM isn't enabled or used, non-SuperSpeed devices may not get
3369  * suspended until their bus goes into global suspend (i.e., the root
3370  * hub is suspended).  Nevertheless, we change @udev->state to
3371  * USB_STATE_SUSPENDED as this is the device's "logical" state.  The actual
3372  * upstream port setting is stored in @udev->port_is_suspended.
3373  *
3374  * Returns 0 on success, else negative errno.
3375  */
3376 int usb_port_suspend(struct usb_device *udev, pm_message_t msg)
3377 {
3378 	struct usb_hub	*hub = usb_hub_to_struct_hub(udev->parent);
3379 	struct usb_port *port_dev = hub->ports[udev->portnum - 1];
3380 	int		port1 = udev->portnum;
3381 	int		status;
3382 	bool		really_suspend = true;
3383 
3384 	usb_lock_port(port_dev);
3385 
3386 	/* enable remote wakeup when appropriate; this lets the device
3387 	 * wake up the upstream hub (including maybe the root hub).
3388 	 *
3389 	 * NOTE:  OTG devices may issue remote wakeup (or SRP) even when
3390 	 * we don't explicitly enable it here.
3391 	 */
3392 	if (udev->do_remote_wakeup) {
3393 		status = usb_enable_remote_wakeup(udev);
3394 		if (status) {
3395 			dev_dbg(&udev->dev, "won't remote wakeup, status %d\n",
3396 					status);
3397 			/* bail if autosuspend is requested */
3398 			if (PMSG_IS_AUTO(msg))
3399 				goto err_wakeup;
3400 		}
3401 	}
3402 
3403 	/* disable USB2 hardware LPM */
3404 	usb_disable_usb2_hardware_lpm(udev);
3405 
3406 	if (usb_disable_ltm(udev)) {
3407 		dev_err(&udev->dev, "Failed to disable LTM before suspend\n");
3408 		status = -ENOMEM;
3409 		if (PMSG_IS_AUTO(msg))
3410 			goto err_ltm;
3411 	}
3412 
3413 	/* see 7.1.7.6 */
3414 	if (hub_is_superspeed(hub->hdev))
3415 		status = hub_set_port_link_state(hub, port1, USB_SS_PORT_LS_U3);
3416 
3417 	/*
3418 	 * For system suspend, we do not need to enable the suspend feature
3419 	 * on individual USB-2 ports.  The devices will automatically go
3420 	 * into suspend a few ms after the root hub stops sending packets.
3421 	 * The USB 2.0 spec calls this "global suspend".
3422 	 *
3423 	 * However, many USB hubs have a bug: They don't relay wakeup requests
3424 	 * from a downstream port if the port's suspend feature isn't on.
3425 	 * Therefore we will turn on the suspend feature if udev or any of its
3426 	 * descendants is enabled for remote wakeup.
3427 	 */
3428 	else if (PMSG_IS_AUTO(msg) || usb_wakeup_enabled_descendants(udev) > 0)
3429 		status = set_port_feature(hub->hdev, port1,
3430 				USB_PORT_FEAT_SUSPEND);
3431 	else {
3432 		really_suspend = false;
3433 		status = 0;
3434 	}
3435 	if (status) {
3436 		/* Check if the port has been suspended for the timeout case
3437 		 * to prevent the suspended port from incorrect handling.
3438 		 */
3439 		if (status == -ETIMEDOUT) {
3440 			int ret;
3441 			u16 portstatus, portchange;
3442 
3443 			portstatus = portchange = 0;
3444 			ret = usb_hub_port_status(hub, port1, &portstatus,
3445 					&portchange);
3446 
3447 			dev_dbg(&port_dev->dev,
3448 				"suspend timeout, status %04x\n", portstatus);
3449 
3450 			if (ret == 0 && port_is_suspended(hub, portstatus)) {
3451 				status = 0;
3452 				goto suspend_done;
3453 			}
3454 		}
3455 
3456 		dev_dbg(&port_dev->dev, "can't suspend, status %d\n", status);
3457 
3458 		/* Try to enable USB3 LTM again */
3459 		usb_enable_ltm(udev);
3460  err_ltm:
3461 		/* Try to enable USB2 hardware LPM again */
3462 		usb_enable_usb2_hardware_lpm(udev);
3463 
3464 		if (udev->do_remote_wakeup)
3465 			(void) usb_disable_remote_wakeup(udev);
3466  err_wakeup:
3467 
3468 		/* System sleep transitions should never fail */
3469 		if (!PMSG_IS_AUTO(msg))
3470 			status = 0;
3471 	} else {
3472  suspend_done:
3473 		dev_dbg(&udev->dev, "usb %ssuspend, wakeup %d\n",
3474 				(PMSG_IS_AUTO(msg) ? "auto-" : ""),
3475 				udev->do_remote_wakeup);
3476 		if (really_suspend) {
3477 			udev->port_is_suspended = 1;
3478 
3479 			/* device has up to 10 msec to fully suspend */
3480 			msleep(10);
3481 		}
3482 		usb_set_device_state(udev, USB_STATE_SUSPENDED);
3483 	}
3484 
3485 	if (status == 0 && !udev->do_remote_wakeup && udev->persist_enabled
3486 			&& test_and_clear_bit(port1, hub->child_usage_bits))
3487 		pm_runtime_put_sync(&port_dev->dev);
3488 
3489 	usb_mark_last_busy(hub->hdev);
3490 
3491 	usb_unlock_port(port_dev);
3492 	return status;
3493 }
3494 
3495 /*
3496  * If the USB "suspend" state is in use (rather than "global suspend"),
3497  * many devices will be individually taken out of suspend state using
3498  * special "resume" signaling.  This routine kicks in shortly after
3499  * hardware resume signaling is finished, either because of selective
3500  * resume (by host) or remote wakeup (by device) ... now see what changed
3501  * in the tree that's rooted at this device.
3502  *
3503  * If @udev->reset_resume is set then the device is reset before the
3504  * status check is done.
3505  */
3506 static int finish_port_resume(struct usb_device *udev)
3507 {
3508 	int	status = 0;
3509 	u16	devstatus = 0;
3510 
3511 	/* caller owns the udev device lock */
3512 	dev_dbg(&udev->dev, "%s\n",
3513 		udev->reset_resume ? "finish reset-resume" : "finish resume");
3514 
3515 	/* usb ch9 identifies four variants of SUSPENDED, based on what
3516 	 * state the device resumes to.  Linux currently won't see the
3517 	 * first two on the host side; they'd be inside hub_port_init()
3518 	 * during many timeouts, but hub_wq can't suspend until later.
3519 	 */
3520 	usb_set_device_state(udev, udev->actconfig
3521 			? USB_STATE_CONFIGURED
3522 			: USB_STATE_ADDRESS);
3523 
3524 	/* 10.5.4.5 says not to reset a suspended port if the attached
3525 	 * device is enabled for remote wakeup.  Hence the reset
3526 	 * operation is carried out here, after the port has been
3527 	 * resumed.
3528 	 */
3529 	if (udev->reset_resume) {
3530 		/*
3531 		 * If the device morphs or switches modes when it is reset,
3532 		 * we don't want to perform a reset-resume.  We'll fail the
3533 		 * resume, which will cause a logical disconnect, and then
3534 		 * the device will be rediscovered.
3535 		 */
3536  retry_reset_resume:
3537 		if (udev->quirks & USB_QUIRK_RESET)
3538 			status = -ENODEV;
3539 		else
3540 			status = usb_reset_and_verify_device(udev);
3541 	}
3542 
3543 	/* 10.5.4.5 says be sure devices in the tree are still there.
3544 	 * For now let's assume the device didn't go crazy on resume,
3545 	 * and device drivers will know about any resume quirks.
3546 	 */
3547 	if (status == 0) {
3548 		devstatus = 0;
3549 		status = usb_get_std_status(udev, USB_RECIP_DEVICE, 0, &devstatus);
3550 
3551 		/* If a normal resume failed, try doing a reset-resume */
3552 		if (status && !udev->reset_resume && udev->persist_enabled) {
3553 			dev_dbg(&udev->dev, "retry with reset-resume\n");
3554 			udev->reset_resume = 1;
3555 			goto retry_reset_resume;
3556 		}
3557 	}
3558 
3559 	if (status) {
3560 		dev_dbg(&udev->dev, "gone after usb resume? status %d\n",
3561 				status);
3562 	/*
3563 	 * There are a few quirky devices which violate the standard
3564 	 * by claiming to have remote wakeup enabled after a reset,
3565 	 * which crash if the feature is cleared, hence check for
3566 	 * udev->reset_resume
3567 	 */
3568 	} else if (udev->actconfig && !udev->reset_resume) {
3569 		if (udev->speed < USB_SPEED_SUPER) {
3570 			if (devstatus & (1 << USB_DEVICE_REMOTE_WAKEUP))
3571 				status = usb_disable_remote_wakeup(udev);
3572 		} else {
3573 			status = usb_get_std_status(udev, USB_RECIP_INTERFACE, 0,
3574 					&devstatus);
3575 			if (!status && devstatus & (USB_INTRF_STAT_FUNC_RW_CAP
3576 					| USB_INTRF_STAT_FUNC_RW))
3577 				status = usb_disable_remote_wakeup(udev);
3578 		}
3579 
3580 		if (status)
3581 			dev_dbg(&udev->dev,
3582 				"disable remote wakeup, status %d\n",
3583 				status);
3584 		status = 0;
3585 	}
3586 	return status;
3587 }
3588 
3589 /*
3590  * There are some SS USB devices which take longer time for link training.
3591  * XHCI specs 4.19.4 says that when Link training is successful, port
3592  * sets CCS bit to 1. So if SW reads port status before successful link
3593  * training, then it will not find device to be present.
3594  * USB Analyzer log with such buggy devices show that in some cases
3595  * device switch on the RX termination after long delay of host enabling
3596  * the VBUS. In few other cases it has been seen that device fails to
3597  * negotiate link training in first attempt. It has been
3598  * reported till now that few devices take as long as 2000 ms to train
3599  * the link after host enabling its VBUS and termination. Following
3600  * routine implements a 2000 ms timeout for link training. If in a case
3601  * link trains before timeout, loop will exit earlier.
3602  *
3603  * There are also some 2.0 hard drive based devices and 3.0 thumb
3604  * drives that, when plugged into a 2.0 only port, take a long
3605  * time to set CCS after VBUS enable.
3606  *
3607  * FIXME: If a device was connected before suspend, but was removed
3608  * while system was asleep, then the loop in the following routine will
3609  * only exit at timeout.
3610  *
3611  * This routine should only be called when persist is enabled.
3612  */
3613 static int wait_for_connected(struct usb_device *udev,
3614 		struct usb_hub *hub, int port1,
3615 		u16 *portchange, u16 *portstatus)
3616 {
3617 	int status = 0, delay_ms = 0;
3618 
3619 	while (delay_ms < 2000) {
3620 		if (status || *portstatus & USB_PORT_STAT_CONNECTION)
3621 			break;
3622 		if (!usb_port_is_power_on(hub, *portstatus)) {
3623 			status = -ENODEV;
3624 			break;
3625 		}
3626 		msleep(20);
3627 		delay_ms += 20;
3628 		status = usb_hub_port_status(hub, port1, portstatus, portchange);
3629 	}
3630 	dev_dbg(&udev->dev, "Waited %dms for CONNECT\n", delay_ms);
3631 	return status;
3632 }
3633 
3634 /*
3635  * usb_port_resume - re-activate a suspended usb device's upstream port
3636  * @udev: device to re-activate, not a root hub
3637  * Context: must be able to sleep; device not locked; pm locks held
3638  *
3639  * This will re-activate the suspended device, increasing power usage
3640  * while letting drivers communicate again with its endpoints.
3641  * USB resume explicitly guarantees that the power session between
3642  * the host and the device is the same as it was when the device
3643  * suspended.
3644  *
3645  * If @udev->reset_resume is set then this routine won't check that the
3646  * port is still enabled.  Furthermore, finish_port_resume() above will
3647  * reset @udev.  The end result is that a broken power session can be
3648  * recovered and @udev will appear to persist across a loss of VBUS power.
3649  *
3650  * For example, if a host controller doesn't maintain VBUS suspend current
3651  * during a system sleep or is reset when the system wakes up, all the USB
3652  * power sessions below it will be broken.  This is especially troublesome
3653  * for mass-storage devices containing mounted filesystems, since the
3654  * device will appear to have disconnected and all the memory mappings
3655  * to it will be lost.  Using the USB_PERSIST facility, the device can be
3656  * made to appear as if it had not disconnected.
3657  *
3658  * This facility can be dangerous.  Although usb_reset_and_verify_device() makes
3659  * every effort to insure that the same device is present after the
3660  * reset as before, it cannot provide a 100% guarantee.  Furthermore it's
3661  * quite possible for a device to remain unaltered but its media to be
3662  * changed.  If the user replaces a flash memory card while the system is
3663  * asleep, he will have only himself to blame when the filesystem on the
3664  * new card is corrupted and the system crashes.
3665  *
3666  * Returns 0 on success, else negative errno.
3667  */
3668 int usb_port_resume(struct usb_device *udev, pm_message_t msg)
3669 {
3670 	struct usb_hub	*hub = usb_hub_to_struct_hub(udev->parent);
3671 	struct usb_port *port_dev = hub->ports[udev->portnum  - 1];
3672 	int		port1 = udev->portnum;
3673 	int		status;
3674 	u16		portchange, portstatus;
3675 
3676 	if (!test_and_set_bit(port1, hub->child_usage_bits)) {
3677 		status = pm_runtime_resume_and_get(&port_dev->dev);
3678 		if (status < 0) {
3679 			dev_dbg(&udev->dev, "can't resume usb port, status %d\n",
3680 					status);
3681 			return status;
3682 		}
3683 	}
3684 
3685 	usb_lock_port(port_dev);
3686 
3687 	/* Skip the initial Clear-Suspend step for a remote wakeup */
3688 	status = usb_hub_port_status(hub, port1, &portstatus, &portchange);
3689 	if (status == 0 && !port_is_suspended(hub, portstatus)) {
3690 		if (portchange & USB_PORT_STAT_C_SUSPEND)
3691 			pm_wakeup_event(&udev->dev, 0);
3692 		goto SuspendCleared;
3693 	}
3694 
3695 	/* see 7.1.7.7; affects power usage, but not budgeting */
3696 	if (hub_is_superspeed(hub->hdev))
3697 		status = hub_set_port_link_state(hub, port1, USB_SS_PORT_LS_U0);
3698 	else
3699 		status = usb_clear_port_feature(hub->hdev,
3700 				port1, USB_PORT_FEAT_SUSPEND);
3701 	if (status) {
3702 		dev_dbg(&port_dev->dev, "can't resume, status %d\n", status);
3703 	} else {
3704 		/* drive resume for USB_RESUME_TIMEOUT msec */
3705 		dev_dbg(&udev->dev, "usb %sresume\n",
3706 				(PMSG_IS_AUTO(msg) ? "auto-" : ""));
3707 		msleep(USB_RESUME_TIMEOUT);
3708 
3709 		/* Virtual root hubs can trigger on GET_PORT_STATUS to
3710 		 * stop resume signaling.  Then finish the resume
3711 		 * sequence.
3712 		 */
3713 		status = usb_hub_port_status(hub, port1, &portstatus, &portchange);
3714 	}
3715 
3716  SuspendCleared:
3717 	if (status == 0) {
3718 		udev->port_is_suspended = 0;
3719 		if (hub_is_superspeed(hub->hdev)) {
3720 			if (portchange & USB_PORT_STAT_C_LINK_STATE)
3721 				usb_clear_port_feature(hub->hdev, port1,
3722 					USB_PORT_FEAT_C_PORT_LINK_STATE);
3723 		} else {
3724 			if (portchange & USB_PORT_STAT_C_SUSPEND)
3725 				usb_clear_port_feature(hub->hdev, port1,
3726 						USB_PORT_FEAT_C_SUSPEND);
3727 		}
3728 
3729 		/* TRSMRCY = 10 msec */
3730 		msleep(10);
3731 	}
3732 
3733 	if (udev->persist_enabled)
3734 		status = wait_for_connected(udev, hub, port1, &portchange,
3735 				&portstatus);
3736 
3737 	status = check_port_resume_type(udev,
3738 			hub, port1, status, portchange, portstatus);
3739 	if (status == 0)
3740 		status = finish_port_resume(udev);
3741 	if (status < 0) {
3742 		dev_dbg(&udev->dev, "can't resume, status %d\n", status);
3743 		hub_port_logical_disconnect(hub, port1);
3744 	} else  {
3745 		/* Try to enable USB2 hardware LPM */
3746 		usb_enable_usb2_hardware_lpm(udev);
3747 
3748 		/* Try to enable USB3 LTM */
3749 		usb_enable_ltm(udev);
3750 	}
3751 
3752 	usb_unlock_port(port_dev);
3753 
3754 	return status;
3755 }
3756 
3757 int usb_remote_wakeup(struct usb_device *udev)
3758 {
3759 	int	status = 0;
3760 
3761 	usb_lock_device(udev);
3762 	if (udev->state == USB_STATE_SUSPENDED) {
3763 		dev_dbg(&udev->dev, "usb %sresume\n", "wakeup-");
3764 		status = usb_autoresume_device(udev);
3765 		if (status == 0) {
3766 			/* Let the drivers do their thing, then... */
3767 			usb_autosuspend_device(udev);
3768 		}
3769 	}
3770 	usb_unlock_device(udev);
3771 	return status;
3772 }
3773 
3774 /* Returns 1 if there was a remote wakeup and a connect status change. */
3775 static int hub_handle_remote_wakeup(struct usb_hub *hub, unsigned int port,
3776 		u16 portstatus, u16 portchange)
3777 		__must_hold(&port_dev->status_lock)
3778 {
3779 	struct usb_port *port_dev = hub->ports[port - 1];
3780 	struct usb_device *hdev;
3781 	struct usb_device *udev;
3782 	int connect_change = 0;
3783 	u16 link_state;
3784 	int ret;
3785 
3786 	hdev = hub->hdev;
3787 	udev = port_dev->child;
3788 	if (!hub_is_superspeed(hdev)) {
3789 		if (!(portchange & USB_PORT_STAT_C_SUSPEND))
3790 			return 0;
3791 		usb_clear_port_feature(hdev, port, USB_PORT_FEAT_C_SUSPEND);
3792 	} else {
3793 		link_state = portstatus & USB_PORT_STAT_LINK_STATE;
3794 		if (!udev || udev->state != USB_STATE_SUSPENDED ||
3795 				(link_state != USB_SS_PORT_LS_U0 &&
3796 				 link_state != USB_SS_PORT_LS_U1 &&
3797 				 link_state != USB_SS_PORT_LS_U2))
3798 			return 0;
3799 	}
3800 
3801 	if (udev) {
3802 		/* TRSMRCY = 10 msec */
3803 		msleep(10);
3804 
3805 		usb_unlock_port(port_dev);
3806 		ret = usb_remote_wakeup(udev);
3807 		usb_lock_port(port_dev);
3808 		if (ret < 0)
3809 			connect_change = 1;
3810 	} else {
3811 		ret = -ENODEV;
3812 		hub_port_disable(hub, port, 1);
3813 	}
3814 	dev_dbg(&port_dev->dev, "resume, status %d\n", ret);
3815 	return connect_change;
3816 }
3817 
3818 static int check_ports_changed(struct usb_hub *hub)
3819 {
3820 	int port1;
3821 
3822 	for (port1 = 1; port1 <= hub->hdev->maxchild; ++port1) {
3823 		u16 portstatus, portchange;
3824 		int status;
3825 
3826 		status = usb_hub_port_status(hub, port1, &portstatus, &portchange);
3827 		if (!status && portchange)
3828 			return 1;
3829 	}
3830 	return 0;
3831 }
3832 
3833 static int hub_suspend(struct usb_interface *intf, pm_message_t msg)
3834 {
3835 	struct usb_hub		*hub = usb_get_intfdata(intf);
3836 	struct usb_device	*hdev = hub->hdev;
3837 	unsigned		port1;
3838 
3839 	/*
3840 	 * Warn if children aren't already suspended.
3841 	 * Also, add up the number of wakeup-enabled descendants.
3842 	 */
3843 	hub->wakeup_enabled_descendants = 0;
3844 	for (port1 = 1; port1 <= hdev->maxchild; port1++) {
3845 		struct usb_port *port_dev = hub->ports[port1 - 1];
3846 		struct usb_device *udev = port_dev->child;
3847 
3848 		if (udev && udev->can_submit) {
3849 			dev_warn(&port_dev->dev, "device %s not suspended yet\n",
3850 					dev_name(&udev->dev));
3851 			if (PMSG_IS_AUTO(msg))
3852 				return -EBUSY;
3853 		}
3854 		if (udev)
3855 			hub->wakeup_enabled_descendants +=
3856 					usb_wakeup_enabled_descendants(udev);
3857 	}
3858 
3859 	if (hdev->do_remote_wakeup && hub->quirk_check_port_auto_suspend) {
3860 		/* check if there are changes pending on hub ports */
3861 		if (check_ports_changed(hub)) {
3862 			if (PMSG_IS_AUTO(msg))
3863 				return -EBUSY;
3864 			pm_wakeup_event(&hdev->dev, 2000);
3865 		}
3866 	}
3867 
3868 	if (hub_is_superspeed(hdev) && hdev->do_remote_wakeup) {
3869 		/* Enable hub to send remote wakeup for all ports. */
3870 		for (port1 = 1; port1 <= hdev->maxchild; port1++) {
3871 			set_port_feature(hdev,
3872 					 port1 |
3873 					 USB_PORT_FEAT_REMOTE_WAKE_CONNECT |
3874 					 USB_PORT_FEAT_REMOTE_WAKE_DISCONNECT |
3875 					 USB_PORT_FEAT_REMOTE_WAKE_OVER_CURRENT,
3876 					 USB_PORT_FEAT_REMOTE_WAKE_MASK);
3877 		}
3878 	}
3879 
3880 	dev_dbg(&intf->dev, "%s\n", __func__);
3881 
3882 	/* stop hub_wq and related activity */
3883 	hub_quiesce(hub, HUB_SUSPEND);
3884 	return 0;
3885 }
3886 
3887 /* Report wakeup requests from the ports of a resuming root hub */
3888 static void report_wakeup_requests(struct usb_hub *hub)
3889 {
3890 	struct usb_device	*hdev = hub->hdev;
3891 	struct usb_device	*udev;
3892 	struct usb_hcd		*hcd;
3893 	unsigned long		resuming_ports;
3894 	int			i;
3895 
3896 	if (hdev->parent)
3897 		return;		/* Not a root hub */
3898 
3899 	hcd = bus_to_hcd(hdev->bus);
3900 	if (hcd->driver->get_resuming_ports) {
3901 
3902 		/*
3903 		 * The get_resuming_ports() method returns a bitmap (origin 0)
3904 		 * of ports which have started wakeup signaling but have not
3905 		 * yet finished resuming.  During system resume we will
3906 		 * resume all the enabled ports, regardless of any wakeup
3907 		 * signals, which means the wakeup requests would be lost.
3908 		 * To prevent this, report them to the PM core here.
3909 		 */
3910 		resuming_ports = hcd->driver->get_resuming_ports(hcd);
3911 		for (i = 0; i < hdev->maxchild; ++i) {
3912 			if (test_bit(i, &resuming_ports)) {
3913 				udev = hub->ports[i]->child;
3914 				if (udev)
3915 					pm_wakeup_event(&udev->dev, 0);
3916 			}
3917 		}
3918 	}
3919 }
3920 
3921 static int hub_resume(struct usb_interface *intf)
3922 {
3923 	struct usb_hub *hub = usb_get_intfdata(intf);
3924 
3925 	dev_dbg(&intf->dev, "%s\n", __func__);
3926 	hub_activate(hub, HUB_RESUME);
3927 
3928 	/*
3929 	 * This should be called only for system resume, not runtime resume.
3930 	 * We can't tell the difference here, so some wakeup requests will be
3931 	 * reported at the wrong time or more than once.  This shouldn't
3932 	 * matter much, so long as they do get reported.
3933 	 */
3934 	report_wakeup_requests(hub);
3935 	return 0;
3936 }
3937 
3938 static int hub_reset_resume(struct usb_interface *intf)
3939 {
3940 	struct usb_hub *hub = usb_get_intfdata(intf);
3941 
3942 	dev_dbg(&intf->dev, "%s\n", __func__);
3943 	hub_activate(hub, HUB_RESET_RESUME);
3944 	return 0;
3945 }
3946 
3947 /**
3948  * usb_root_hub_lost_power - called by HCD if the root hub lost Vbus power
3949  * @rhdev: struct usb_device for the root hub
3950  *
3951  * The USB host controller driver calls this function when its root hub
3952  * is resumed and Vbus power has been interrupted or the controller
3953  * has been reset.  The routine marks @rhdev as having lost power.
3954  * When the hub driver is resumed it will take notice and carry out
3955  * power-session recovery for all the "USB-PERSIST"-enabled child devices;
3956  * the others will be disconnected.
3957  */
3958 void usb_root_hub_lost_power(struct usb_device *rhdev)
3959 {
3960 	dev_notice(&rhdev->dev, "root hub lost power or was reset\n");
3961 	rhdev->reset_resume = 1;
3962 }
3963 EXPORT_SYMBOL_GPL(usb_root_hub_lost_power);
3964 
3965 static const char * const usb3_lpm_names[]  = {
3966 	"U0",
3967 	"U1",
3968 	"U2",
3969 	"U3",
3970 };
3971 
3972 /*
3973  * Send a Set SEL control transfer to the device, prior to enabling
3974  * device-initiated U1 or U2.  This lets the device know the exit latencies from
3975  * the time the device initiates a U1 or U2 exit, to the time it will receive a
3976  * packet from the host.
3977  *
3978  * This function will fail if the SEL or PEL values for udev are greater than
3979  * the maximum allowed values for the link state to be enabled.
3980  */
3981 static int usb_req_set_sel(struct usb_device *udev)
3982 {
3983 	struct usb_set_sel_req *sel_values;
3984 	unsigned long long u1_sel;
3985 	unsigned long long u1_pel;
3986 	unsigned long long u2_sel;
3987 	unsigned long long u2_pel;
3988 	int ret;
3989 
3990 	if (!udev->parent || udev->speed < USB_SPEED_SUPER || !udev->lpm_capable)
3991 		return 0;
3992 
3993 	/* Convert SEL and PEL stored in ns to us */
3994 	u1_sel = DIV_ROUND_UP(udev->u1_params.sel, 1000);
3995 	u1_pel = DIV_ROUND_UP(udev->u1_params.pel, 1000);
3996 	u2_sel = DIV_ROUND_UP(udev->u2_params.sel, 1000);
3997 	u2_pel = DIV_ROUND_UP(udev->u2_params.pel, 1000);
3998 
3999 	/*
4000 	 * Make sure that the calculated SEL and PEL values for the link
4001 	 * state we're enabling aren't bigger than the max SEL/PEL
4002 	 * value that will fit in the SET SEL control transfer.
4003 	 * Otherwise the device would get an incorrect idea of the exit
4004 	 * latency for the link state, and could start a device-initiated
4005 	 * U1/U2 when the exit latencies are too high.
4006 	 */
4007 	if (u1_sel > USB3_LPM_MAX_U1_SEL_PEL ||
4008 	    u1_pel > USB3_LPM_MAX_U1_SEL_PEL ||
4009 	    u2_sel > USB3_LPM_MAX_U2_SEL_PEL ||
4010 	    u2_pel > USB3_LPM_MAX_U2_SEL_PEL) {
4011 		dev_dbg(&udev->dev, "Device-initiated U1/U2 disabled due to long SEL or PEL\n");
4012 		return -EINVAL;
4013 	}
4014 
4015 	/*
4016 	 * usb_enable_lpm() can be called as part of a failed device reset,
4017 	 * which may be initiated by an error path of a mass storage driver.
4018 	 * Therefore, use GFP_NOIO.
4019 	 */
4020 	sel_values = kmalloc(sizeof *(sel_values), GFP_NOIO);
4021 	if (!sel_values)
4022 		return -ENOMEM;
4023 
4024 	sel_values->u1_sel = u1_sel;
4025 	sel_values->u1_pel = u1_pel;
4026 	sel_values->u2_sel = cpu_to_le16(u2_sel);
4027 	sel_values->u2_pel = cpu_to_le16(u2_pel);
4028 
4029 	ret = usb_control_msg(udev, usb_sndctrlpipe(udev, 0),
4030 			USB_REQ_SET_SEL,
4031 			USB_RECIP_DEVICE,
4032 			0, 0,
4033 			sel_values, sizeof *(sel_values),
4034 			USB_CTRL_SET_TIMEOUT);
4035 	kfree(sel_values);
4036 
4037 	if (ret > 0)
4038 		udev->lpm_devinit_allow = 1;
4039 
4040 	return ret;
4041 }
4042 
4043 /*
4044  * Enable or disable device-initiated U1 or U2 transitions.
4045  */
4046 static int usb_set_device_initiated_lpm(struct usb_device *udev,
4047 		enum usb3_link_state state, bool enable)
4048 {
4049 	int ret;
4050 	int feature;
4051 
4052 	switch (state) {
4053 	case USB3_LPM_U1:
4054 		feature = USB_DEVICE_U1_ENABLE;
4055 		break;
4056 	case USB3_LPM_U2:
4057 		feature = USB_DEVICE_U2_ENABLE;
4058 		break;
4059 	default:
4060 		dev_warn(&udev->dev, "%s: Can't %s non-U1 or U2 state.\n",
4061 				__func__, enable ? "enable" : "disable");
4062 		return -EINVAL;
4063 	}
4064 
4065 	if (udev->state != USB_STATE_CONFIGURED) {
4066 		dev_dbg(&udev->dev, "%s: Can't %s %s state "
4067 				"for unconfigured device.\n",
4068 				__func__, enable ? "enable" : "disable",
4069 				usb3_lpm_names[state]);
4070 		return 0;
4071 	}
4072 
4073 	if (enable) {
4074 		/*
4075 		 * Now send the control transfer to enable device-initiated LPM
4076 		 * for either U1 or U2.
4077 		 */
4078 		ret = usb_control_msg(udev, usb_sndctrlpipe(udev, 0),
4079 				USB_REQ_SET_FEATURE,
4080 				USB_RECIP_DEVICE,
4081 				feature,
4082 				0, NULL, 0,
4083 				USB_CTRL_SET_TIMEOUT);
4084 	} else {
4085 		ret = usb_control_msg(udev, usb_sndctrlpipe(udev, 0),
4086 				USB_REQ_CLEAR_FEATURE,
4087 				USB_RECIP_DEVICE,
4088 				feature,
4089 				0, NULL, 0,
4090 				USB_CTRL_SET_TIMEOUT);
4091 	}
4092 	if (ret < 0) {
4093 		dev_warn(&udev->dev, "%s of device-initiated %s failed.\n",
4094 				enable ? "Enable" : "Disable",
4095 				usb3_lpm_names[state]);
4096 		return -EBUSY;
4097 	}
4098 	return 0;
4099 }
4100 
4101 static int usb_set_lpm_timeout(struct usb_device *udev,
4102 		enum usb3_link_state state, int timeout)
4103 {
4104 	int ret;
4105 	int feature;
4106 
4107 	switch (state) {
4108 	case USB3_LPM_U1:
4109 		feature = USB_PORT_FEAT_U1_TIMEOUT;
4110 		break;
4111 	case USB3_LPM_U2:
4112 		feature = USB_PORT_FEAT_U2_TIMEOUT;
4113 		break;
4114 	default:
4115 		dev_warn(&udev->dev, "%s: Can't set timeout for non-U1 or U2 state.\n",
4116 				__func__);
4117 		return -EINVAL;
4118 	}
4119 
4120 	if (state == USB3_LPM_U1 && timeout > USB3_LPM_U1_MAX_TIMEOUT &&
4121 			timeout != USB3_LPM_DEVICE_INITIATED) {
4122 		dev_warn(&udev->dev, "Failed to set %s timeout to 0x%x, "
4123 				"which is a reserved value.\n",
4124 				usb3_lpm_names[state], timeout);
4125 		return -EINVAL;
4126 	}
4127 
4128 	ret = set_port_feature(udev->parent,
4129 			USB_PORT_LPM_TIMEOUT(timeout) | udev->portnum,
4130 			feature);
4131 	if (ret < 0) {
4132 		dev_warn(&udev->dev, "Failed to set %s timeout to 0x%x,"
4133 				"error code %i\n", usb3_lpm_names[state],
4134 				timeout, ret);
4135 		return -EBUSY;
4136 	}
4137 	if (state == USB3_LPM_U1)
4138 		udev->u1_params.timeout = timeout;
4139 	else
4140 		udev->u2_params.timeout = timeout;
4141 	return 0;
4142 }
4143 
4144 /*
4145  * Don't allow device intiated U1/U2 if the system exit latency + one bus
4146  * interval is greater than the minimum service interval of any active
4147  * periodic endpoint. See USB 3.2 section 9.4.9
4148  */
4149 static bool usb_device_may_initiate_lpm(struct usb_device *udev,
4150 					enum usb3_link_state state)
4151 {
4152 	unsigned int sel;		/* us */
4153 	int i, j;
4154 
4155 	if (!udev->lpm_devinit_allow)
4156 		return false;
4157 
4158 	if (state == USB3_LPM_U1)
4159 		sel = DIV_ROUND_UP(udev->u1_params.sel, 1000);
4160 	else if (state == USB3_LPM_U2)
4161 		sel = DIV_ROUND_UP(udev->u2_params.sel, 1000);
4162 	else
4163 		return false;
4164 
4165 	for (i = 0; i < udev->actconfig->desc.bNumInterfaces; i++) {
4166 		struct usb_interface *intf;
4167 		struct usb_endpoint_descriptor *desc;
4168 		unsigned int interval;
4169 
4170 		intf = udev->actconfig->interface[i];
4171 		if (!intf)
4172 			continue;
4173 
4174 		for (j = 0; j < intf->cur_altsetting->desc.bNumEndpoints; j++) {
4175 			desc = &intf->cur_altsetting->endpoint[j].desc;
4176 
4177 			if (usb_endpoint_xfer_int(desc) ||
4178 			    usb_endpoint_xfer_isoc(desc)) {
4179 				interval = (1 << (desc->bInterval - 1)) * 125;
4180 				if (sel + 125 > interval)
4181 					return false;
4182 			}
4183 		}
4184 	}
4185 	return true;
4186 }
4187 
4188 /*
4189  * Enable the hub-initiated U1/U2 idle timeouts, and enable device-initiated
4190  * U1/U2 entry.
4191  *
4192  * We will attempt to enable U1 or U2, but there are no guarantees that the
4193  * control transfers to set the hub timeout or enable device-initiated U1/U2
4194  * will be successful.
4195  *
4196  * If the control transfer to enable device-initiated U1/U2 entry fails, then
4197  * hub-initiated U1/U2 will be disabled.
4198  *
4199  * If we cannot set the parent hub U1/U2 timeout, we attempt to let the xHCI
4200  * driver know about it.  If that call fails, it should be harmless, and just
4201  * take up more slightly more bus bandwidth for unnecessary U1/U2 exit latency.
4202  */
4203 static void usb_enable_link_state(struct usb_hcd *hcd, struct usb_device *udev,
4204 		enum usb3_link_state state)
4205 {
4206 	int timeout;
4207 	__u8 u1_mel;
4208 	__le16 u2_mel;
4209 
4210 	/* Skip if the device BOS descriptor couldn't be read */
4211 	if (!udev->bos)
4212 		return;
4213 
4214 	u1_mel = udev->bos->ss_cap->bU1devExitLat;
4215 	u2_mel = udev->bos->ss_cap->bU2DevExitLat;
4216 
4217 	/* If the device says it doesn't have *any* exit latency to come out of
4218 	 * U1 or U2, it's probably lying.  Assume it doesn't implement that link
4219 	 * state.
4220 	 */
4221 	if ((state == USB3_LPM_U1 && u1_mel == 0) ||
4222 			(state == USB3_LPM_U2 && u2_mel == 0))
4223 		return;
4224 
4225 	/* We allow the host controller to set the U1/U2 timeout internally
4226 	 * first, so that it can change its schedule to account for the
4227 	 * additional latency to send data to a device in a lower power
4228 	 * link state.
4229 	 */
4230 	timeout = hcd->driver->enable_usb3_lpm_timeout(hcd, udev, state);
4231 
4232 	/* xHCI host controller doesn't want to enable this LPM state. */
4233 	if (timeout == 0)
4234 		return;
4235 
4236 	if (timeout < 0) {
4237 		dev_warn(&udev->dev, "Could not enable %s link state, "
4238 				"xHCI error %i.\n", usb3_lpm_names[state],
4239 				timeout);
4240 		return;
4241 	}
4242 
4243 	if (usb_set_lpm_timeout(udev, state, timeout)) {
4244 		/* If we can't set the parent hub U1/U2 timeout,
4245 		 * device-initiated LPM won't be allowed either, so let the xHCI
4246 		 * host know that this link state won't be enabled.
4247 		 */
4248 		hcd->driver->disable_usb3_lpm_timeout(hcd, udev, state);
4249 		return;
4250 	}
4251 
4252 	/* Only a configured device will accept the Set Feature
4253 	 * U1/U2_ENABLE
4254 	 */
4255 	if (udev->actconfig &&
4256 	    usb_device_may_initiate_lpm(udev, state)) {
4257 		if (usb_set_device_initiated_lpm(udev, state, true)) {
4258 			/*
4259 			 * Request to enable device initiated U1/U2 failed,
4260 			 * better to turn off lpm in this case.
4261 			 */
4262 			usb_set_lpm_timeout(udev, state, 0);
4263 			hcd->driver->disable_usb3_lpm_timeout(hcd, udev, state);
4264 			return;
4265 		}
4266 	}
4267 
4268 	if (state == USB3_LPM_U1)
4269 		udev->usb3_lpm_u1_enabled = 1;
4270 	else if (state == USB3_LPM_U2)
4271 		udev->usb3_lpm_u2_enabled = 1;
4272 }
4273 /*
4274  * Disable the hub-initiated U1/U2 idle timeouts, and disable device-initiated
4275  * U1/U2 entry.
4276  *
4277  * If this function returns -EBUSY, the parent hub will still allow U1/U2 entry.
4278  * If zero is returned, the parent will not allow the link to go into U1/U2.
4279  *
4280  * If zero is returned, device-initiated U1/U2 entry may still be enabled, but
4281  * it won't have an effect on the bus link state because the parent hub will
4282  * still disallow device-initiated U1/U2 entry.
4283  *
4284  * If zero is returned, the xHCI host controller may still think U1/U2 entry is
4285  * possible.  The result will be slightly more bus bandwidth will be taken up
4286  * (to account for U1/U2 exit latency), but it should be harmless.
4287  */
4288 static int usb_disable_link_state(struct usb_hcd *hcd, struct usb_device *udev,
4289 		enum usb3_link_state state)
4290 {
4291 	switch (state) {
4292 	case USB3_LPM_U1:
4293 	case USB3_LPM_U2:
4294 		break;
4295 	default:
4296 		dev_warn(&udev->dev, "%s: Can't disable non-U1 or U2 state.\n",
4297 				__func__);
4298 		return -EINVAL;
4299 	}
4300 
4301 	if (usb_set_lpm_timeout(udev, state, 0))
4302 		return -EBUSY;
4303 
4304 	usb_set_device_initiated_lpm(udev, state, false);
4305 
4306 	if (hcd->driver->disable_usb3_lpm_timeout(hcd, udev, state))
4307 		dev_warn(&udev->dev, "Could not disable xHCI %s timeout, "
4308 				"bus schedule bandwidth may be impacted.\n",
4309 				usb3_lpm_names[state]);
4310 
4311 	/* As soon as usb_set_lpm_timeout(0) return 0, hub initiated LPM
4312 	 * is disabled. Hub will disallows link to enter U1/U2 as well,
4313 	 * even device is initiating LPM. Hence LPM is disabled if hub LPM
4314 	 * timeout set to 0, no matter device-initiated LPM is disabled or
4315 	 * not.
4316 	 */
4317 	if (state == USB3_LPM_U1)
4318 		udev->usb3_lpm_u1_enabled = 0;
4319 	else if (state == USB3_LPM_U2)
4320 		udev->usb3_lpm_u2_enabled = 0;
4321 
4322 	return 0;
4323 }
4324 
4325 /*
4326  * Disable hub-initiated and device-initiated U1 and U2 entry.
4327  * Caller must own the bandwidth_mutex.
4328  *
4329  * This will call usb_enable_lpm() on failure, which will decrement
4330  * lpm_disable_count, and will re-enable LPM if lpm_disable_count reaches zero.
4331  */
4332 int usb_disable_lpm(struct usb_device *udev)
4333 {
4334 	struct usb_hcd *hcd;
4335 
4336 	if (!udev || !udev->parent ||
4337 			udev->speed < USB_SPEED_SUPER ||
4338 			!udev->lpm_capable ||
4339 			udev->state < USB_STATE_CONFIGURED)
4340 		return 0;
4341 
4342 	hcd = bus_to_hcd(udev->bus);
4343 	if (!hcd || !hcd->driver->disable_usb3_lpm_timeout)
4344 		return 0;
4345 
4346 	udev->lpm_disable_count++;
4347 	if ((udev->u1_params.timeout == 0 && udev->u2_params.timeout == 0))
4348 		return 0;
4349 
4350 	/* If LPM is enabled, attempt to disable it. */
4351 	if (usb_disable_link_state(hcd, udev, USB3_LPM_U1))
4352 		goto enable_lpm;
4353 	if (usb_disable_link_state(hcd, udev, USB3_LPM_U2))
4354 		goto enable_lpm;
4355 
4356 	return 0;
4357 
4358 enable_lpm:
4359 	usb_enable_lpm(udev);
4360 	return -EBUSY;
4361 }
4362 EXPORT_SYMBOL_GPL(usb_disable_lpm);
4363 
4364 /* Grab the bandwidth_mutex before calling usb_disable_lpm() */
4365 int usb_unlocked_disable_lpm(struct usb_device *udev)
4366 {
4367 	struct usb_hcd *hcd = bus_to_hcd(udev->bus);
4368 	int ret;
4369 
4370 	if (!hcd)
4371 		return -EINVAL;
4372 
4373 	mutex_lock(hcd->bandwidth_mutex);
4374 	ret = usb_disable_lpm(udev);
4375 	mutex_unlock(hcd->bandwidth_mutex);
4376 
4377 	return ret;
4378 }
4379 EXPORT_SYMBOL_GPL(usb_unlocked_disable_lpm);
4380 
4381 /*
4382  * Attempt to enable device-initiated and hub-initiated U1 and U2 entry.  The
4383  * xHCI host policy may prevent U1 or U2 from being enabled.
4384  *
4385  * Other callers may have disabled link PM, so U1 and U2 entry will be disabled
4386  * until the lpm_disable_count drops to zero.  Caller must own the
4387  * bandwidth_mutex.
4388  */
4389 void usb_enable_lpm(struct usb_device *udev)
4390 {
4391 	struct usb_hcd *hcd;
4392 	struct usb_hub *hub;
4393 	struct usb_port *port_dev;
4394 
4395 	if (!udev || !udev->parent ||
4396 			udev->speed < USB_SPEED_SUPER ||
4397 			!udev->lpm_capable ||
4398 			udev->state < USB_STATE_CONFIGURED)
4399 		return;
4400 
4401 	udev->lpm_disable_count--;
4402 	hcd = bus_to_hcd(udev->bus);
4403 	/* Double check that we can both enable and disable LPM.
4404 	 * Device must be configured to accept set feature U1/U2 timeout.
4405 	 */
4406 	if (!hcd || !hcd->driver->enable_usb3_lpm_timeout ||
4407 			!hcd->driver->disable_usb3_lpm_timeout)
4408 		return;
4409 
4410 	if (udev->lpm_disable_count > 0)
4411 		return;
4412 
4413 	hub = usb_hub_to_struct_hub(udev->parent);
4414 	if (!hub)
4415 		return;
4416 
4417 	port_dev = hub->ports[udev->portnum - 1];
4418 
4419 	if (port_dev->usb3_lpm_u1_permit)
4420 		usb_enable_link_state(hcd, udev, USB3_LPM_U1);
4421 
4422 	if (port_dev->usb3_lpm_u2_permit)
4423 		usb_enable_link_state(hcd, udev, USB3_LPM_U2);
4424 }
4425 EXPORT_SYMBOL_GPL(usb_enable_lpm);
4426 
4427 /* Grab the bandwidth_mutex before calling usb_enable_lpm() */
4428 void usb_unlocked_enable_lpm(struct usb_device *udev)
4429 {
4430 	struct usb_hcd *hcd = bus_to_hcd(udev->bus);
4431 
4432 	if (!hcd)
4433 		return;
4434 
4435 	mutex_lock(hcd->bandwidth_mutex);
4436 	usb_enable_lpm(udev);
4437 	mutex_unlock(hcd->bandwidth_mutex);
4438 }
4439 EXPORT_SYMBOL_GPL(usb_unlocked_enable_lpm);
4440 
4441 /* usb3 devices use U3 for disabled, make sure remote wakeup is disabled */
4442 static void hub_usb3_port_prepare_disable(struct usb_hub *hub,
4443 					  struct usb_port *port_dev)
4444 {
4445 	struct usb_device *udev = port_dev->child;
4446 	int ret;
4447 
4448 	if (udev && udev->port_is_suspended && udev->do_remote_wakeup) {
4449 		ret = hub_set_port_link_state(hub, port_dev->portnum,
4450 					      USB_SS_PORT_LS_U0);
4451 		if (!ret) {
4452 			msleep(USB_RESUME_TIMEOUT);
4453 			ret = usb_disable_remote_wakeup(udev);
4454 		}
4455 		if (ret)
4456 			dev_warn(&udev->dev,
4457 				 "Port disable: can't disable remote wake\n");
4458 		udev->do_remote_wakeup = 0;
4459 	}
4460 }
4461 
4462 #else	/* CONFIG_PM */
4463 
4464 #define hub_suspend		NULL
4465 #define hub_resume		NULL
4466 #define hub_reset_resume	NULL
4467 
4468 static inline void hub_usb3_port_prepare_disable(struct usb_hub *hub,
4469 						 struct usb_port *port_dev) { }
4470 
4471 int usb_disable_lpm(struct usb_device *udev)
4472 {
4473 	return 0;
4474 }
4475 EXPORT_SYMBOL_GPL(usb_disable_lpm);
4476 
4477 void usb_enable_lpm(struct usb_device *udev) { }
4478 EXPORT_SYMBOL_GPL(usb_enable_lpm);
4479 
4480 int usb_unlocked_disable_lpm(struct usb_device *udev)
4481 {
4482 	return 0;
4483 }
4484 EXPORT_SYMBOL_GPL(usb_unlocked_disable_lpm);
4485 
4486 void usb_unlocked_enable_lpm(struct usb_device *udev) { }
4487 EXPORT_SYMBOL_GPL(usb_unlocked_enable_lpm);
4488 
4489 int usb_disable_ltm(struct usb_device *udev)
4490 {
4491 	return 0;
4492 }
4493 EXPORT_SYMBOL_GPL(usb_disable_ltm);
4494 
4495 void usb_enable_ltm(struct usb_device *udev) { }
4496 EXPORT_SYMBOL_GPL(usb_enable_ltm);
4497 
4498 static int hub_handle_remote_wakeup(struct usb_hub *hub, unsigned int port,
4499 		u16 portstatus, u16 portchange)
4500 {
4501 	return 0;
4502 }
4503 
4504 static int usb_req_set_sel(struct usb_device *udev)
4505 {
4506 	return 0;
4507 }
4508 
4509 #endif	/* CONFIG_PM */
4510 
4511 /*
4512  * USB-3 does not have a similar link state as USB-2 that will avoid negotiating
4513  * a connection with a plugged-in cable but will signal the host when the cable
4514  * is unplugged. Disable remote wake and set link state to U3 for USB-3 devices
4515  */
4516 static int hub_port_disable(struct usb_hub *hub, int port1, int set_state)
4517 {
4518 	struct usb_port *port_dev = hub->ports[port1 - 1];
4519 	struct usb_device *hdev = hub->hdev;
4520 	int ret = 0;
4521 
4522 	if (!hub->error) {
4523 		if (hub_is_superspeed(hub->hdev)) {
4524 			hub_usb3_port_prepare_disable(hub, port_dev);
4525 			ret = hub_set_port_link_state(hub, port_dev->portnum,
4526 						      USB_SS_PORT_LS_U3);
4527 		} else {
4528 			ret = usb_clear_port_feature(hdev, port1,
4529 					USB_PORT_FEAT_ENABLE);
4530 		}
4531 	}
4532 	if (port_dev->child && set_state)
4533 		usb_set_device_state(port_dev->child, USB_STATE_NOTATTACHED);
4534 	if (ret && ret != -ENODEV)
4535 		dev_err(&port_dev->dev, "cannot disable (err = %d)\n", ret);
4536 	return ret;
4537 }
4538 
4539 /*
4540  * usb_port_disable - disable a usb device's upstream port
4541  * @udev: device to disable
4542  * Context: @udev locked, must be able to sleep.
4543  *
4544  * Disables a USB device that isn't in active use.
4545  */
4546 int usb_port_disable(struct usb_device *udev)
4547 {
4548 	struct usb_hub *hub = usb_hub_to_struct_hub(udev->parent);
4549 
4550 	return hub_port_disable(hub, udev->portnum, 0);
4551 }
4552 
4553 /* USB 2.0 spec, 7.1.7.3 / fig 7-29:
4554  *
4555  * Between connect detection and reset signaling there must be a delay
4556  * of 100ms at least for debounce and power-settling.  The corresponding
4557  * timer shall restart whenever the downstream port detects a disconnect.
4558  *
4559  * Apparently there are some bluetooth and irda-dongles and a number of
4560  * low-speed devices for which this debounce period may last over a second.
4561  * Not covered by the spec - but easy to deal with.
4562  *
4563  * This implementation uses a 1500ms total debounce timeout; if the
4564  * connection isn't stable by then it returns -ETIMEDOUT.  It checks
4565  * every 25ms for transient disconnects.  When the port status has been
4566  * unchanged for 100ms it returns the port status.
4567  */
4568 int hub_port_debounce(struct usb_hub *hub, int port1, bool must_be_connected)
4569 {
4570 	int ret;
4571 	u16 portchange, portstatus;
4572 	unsigned connection = 0xffff;
4573 	int total_time, stable_time = 0;
4574 	struct usb_port *port_dev = hub->ports[port1 - 1];
4575 
4576 	for (total_time = 0; ; total_time += HUB_DEBOUNCE_STEP) {
4577 		ret = usb_hub_port_status(hub, port1, &portstatus, &portchange);
4578 		if (ret < 0)
4579 			return ret;
4580 
4581 		if (!(portchange & USB_PORT_STAT_C_CONNECTION) &&
4582 		     (portstatus & USB_PORT_STAT_CONNECTION) == connection) {
4583 			if (!must_be_connected ||
4584 			     (connection == USB_PORT_STAT_CONNECTION))
4585 				stable_time += HUB_DEBOUNCE_STEP;
4586 			if (stable_time >= HUB_DEBOUNCE_STABLE)
4587 				break;
4588 		} else {
4589 			stable_time = 0;
4590 			connection = portstatus & USB_PORT_STAT_CONNECTION;
4591 		}
4592 
4593 		if (portchange & USB_PORT_STAT_C_CONNECTION) {
4594 			usb_clear_port_feature(hub->hdev, port1,
4595 					USB_PORT_FEAT_C_CONNECTION);
4596 		}
4597 
4598 		if (total_time >= HUB_DEBOUNCE_TIMEOUT)
4599 			break;
4600 		msleep(HUB_DEBOUNCE_STEP);
4601 	}
4602 
4603 	dev_dbg(&port_dev->dev, "debounce total %dms stable %dms status 0x%x\n",
4604 			total_time, stable_time, portstatus);
4605 
4606 	if (stable_time < HUB_DEBOUNCE_STABLE)
4607 		return -ETIMEDOUT;
4608 	return portstatus;
4609 }
4610 
4611 void usb_ep0_reinit(struct usb_device *udev)
4612 {
4613 	usb_disable_endpoint(udev, 0 + USB_DIR_IN, true);
4614 	usb_disable_endpoint(udev, 0 + USB_DIR_OUT, true);
4615 	usb_enable_endpoint(udev, &udev->ep0, true);
4616 }
4617 EXPORT_SYMBOL_GPL(usb_ep0_reinit);
4618 
4619 #define usb_sndaddr0pipe()	(PIPE_CONTROL << 30)
4620 #define usb_rcvaddr0pipe()	((PIPE_CONTROL << 30) | USB_DIR_IN)
4621 
4622 static int hub_set_address(struct usb_device *udev, int devnum)
4623 {
4624 	int retval;
4625 	struct usb_hcd *hcd = bus_to_hcd(udev->bus);
4626 
4627 	/*
4628 	 * The host controller will choose the device address,
4629 	 * instead of the core having chosen it earlier
4630 	 */
4631 	if (!hcd->driver->address_device && devnum <= 1)
4632 		return -EINVAL;
4633 	if (udev->state == USB_STATE_ADDRESS)
4634 		return 0;
4635 	if (udev->state != USB_STATE_DEFAULT)
4636 		return -EINVAL;
4637 	if (hcd->driver->address_device)
4638 		retval = hcd->driver->address_device(hcd, udev);
4639 	else
4640 		retval = usb_control_msg(udev, usb_sndaddr0pipe(),
4641 				USB_REQ_SET_ADDRESS, 0, devnum, 0,
4642 				NULL, 0, USB_CTRL_SET_TIMEOUT);
4643 	if (retval == 0) {
4644 		update_devnum(udev, devnum);
4645 		/* Device now using proper address. */
4646 		usb_set_device_state(udev, USB_STATE_ADDRESS);
4647 		usb_ep0_reinit(udev);
4648 	}
4649 	return retval;
4650 }
4651 
4652 /*
4653  * There are reports of USB 3.0 devices that say they support USB 2.0 Link PM
4654  * when they're plugged into a USB 2.0 port, but they don't work when LPM is
4655  * enabled.
4656  *
4657  * Only enable USB 2.0 Link PM if the port is internal (hardwired), or the
4658  * device says it supports the new USB 2.0 Link PM errata by setting the BESL
4659  * support bit in the BOS descriptor.
4660  */
4661 static void hub_set_initial_usb2_lpm_policy(struct usb_device *udev)
4662 {
4663 	struct usb_hub *hub = usb_hub_to_struct_hub(udev->parent);
4664 	int connect_type = USB_PORT_CONNECT_TYPE_UNKNOWN;
4665 
4666 	if (!udev->usb2_hw_lpm_capable || !udev->bos)
4667 		return;
4668 
4669 	if (hub)
4670 		connect_type = hub->ports[udev->portnum - 1]->connect_type;
4671 
4672 	if ((udev->bos->ext_cap->bmAttributes & cpu_to_le32(USB_BESL_SUPPORT)) ||
4673 			connect_type == USB_PORT_CONNECT_TYPE_HARD_WIRED) {
4674 		udev->usb2_hw_lpm_allowed = 1;
4675 		usb_enable_usb2_hardware_lpm(udev);
4676 	}
4677 }
4678 
4679 static int hub_enable_device(struct usb_device *udev)
4680 {
4681 	struct usb_hcd *hcd = bus_to_hcd(udev->bus);
4682 
4683 	if (!hcd->driver->enable_device)
4684 		return 0;
4685 	if (udev->state == USB_STATE_ADDRESS)
4686 		return 0;
4687 	if (udev->state != USB_STATE_DEFAULT)
4688 		return -EINVAL;
4689 
4690 	return hcd->driver->enable_device(hcd, udev);
4691 }
4692 
4693 /*
4694  * Get the bMaxPacketSize0 value during initialization by reading the
4695  * device's device descriptor.  Since we don't already know this value,
4696  * the transfer is unsafe and it ignores I/O errors, only testing for
4697  * reasonable received values.
4698  *
4699  * For "old scheme" initialization, size will be 8 so we read just the
4700  * start of the device descriptor, which should work okay regardless of
4701  * the actual bMaxPacketSize0 value.  For "new scheme" initialization,
4702  * size will be 64 (and buf will point to a sufficiently large buffer),
4703  * which might not be kosher according to the USB spec but it's what
4704  * Windows does and what many devices expect.
4705  *
4706  * Returns: bMaxPacketSize0 or a negative error code.
4707  */
4708 static int get_bMaxPacketSize0(struct usb_device *udev,
4709 		struct usb_device_descriptor *buf, int size, bool first_time)
4710 {
4711 	int i, rc;
4712 
4713 	/*
4714 	 * Retry on all errors; some devices are flakey.
4715 	 * 255 is for WUSB devices, we actually need to use
4716 	 * 512 (WUSB1.0[4.8.1]).
4717 	 */
4718 	for (i = 0; i < GET_MAXPACKET0_TRIES; ++i) {
4719 		/* Start with invalid values in case the transfer fails */
4720 		buf->bDescriptorType = buf->bMaxPacketSize0 = 0;
4721 		rc = usb_control_msg(udev, usb_rcvaddr0pipe(),
4722 				USB_REQ_GET_DESCRIPTOR, USB_DIR_IN,
4723 				USB_DT_DEVICE << 8, 0,
4724 				buf, size,
4725 				initial_descriptor_timeout);
4726 		switch (buf->bMaxPacketSize0) {
4727 		case 8: case 16: case 32: case 64: case 9:
4728 			if (buf->bDescriptorType == USB_DT_DEVICE) {
4729 				rc = buf->bMaxPacketSize0;
4730 				break;
4731 			}
4732 			fallthrough;
4733 		default:
4734 			if (rc >= 0)
4735 				rc = -EPROTO;
4736 			break;
4737 		}
4738 
4739 		/*
4740 		 * Some devices time out if they are powered on
4741 		 * when already connected. They need a second
4742 		 * reset, so return early. But only on the first
4743 		 * attempt, lest we get into a time-out/reset loop.
4744 		 */
4745 		if (rc > 0 || (rc == -ETIMEDOUT && first_time &&
4746 				udev->speed > USB_SPEED_FULL))
4747 			break;
4748 	}
4749 	return rc;
4750 }
4751 
4752 #define GET_DESCRIPTOR_BUFSIZE	64
4753 
4754 /* Reset device, (re)assign address, get device descriptor.
4755  * Device connection must be stable, no more debouncing needed.
4756  * Returns device in USB_STATE_ADDRESS, except on error.
4757  *
4758  * If this is called for an already-existing device (as part of
4759  * usb_reset_and_verify_device), the caller must own the device lock and
4760  * the port lock.  For a newly detected device that is not accessible
4761  * through any global pointers, it's not necessary to lock the device,
4762  * but it is still necessary to lock the port.
4763  *
4764  * For a newly detected device, @dev_descr must be NULL.  The device
4765  * descriptor retrieved from the device will then be stored in
4766  * @udev->descriptor.  For an already existing device, @dev_descr
4767  * must be non-NULL.  The device descriptor will be stored there,
4768  * not in @udev->descriptor, because descriptors for registered
4769  * devices are meant to be immutable.
4770  */
4771 static int
4772 hub_port_init(struct usb_hub *hub, struct usb_device *udev, int port1,
4773 		int retry_counter, struct usb_device_descriptor *dev_descr)
4774 {
4775 	struct usb_device	*hdev = hub->hdev;
4776 	struct usb_hcd		*hcd = bus_to_hcd(hdev->bus);
4777 	struct usb_port		*port_dev = hub->ports[port1 - 1];
4778 	int			retries, operations, retval, i;
4779 	unsigned		delay = HUB_SHORT_RESET_TIME;
4780 	enum usb_device_speed	oldspeed = udev->speed;
4781 	const char		*speed;
4782 	int			devnum = udev->devnum;
4783 	const char		*driver_name;
4784 	bool			do_new_scheme;
4785 	const bool		initial = !dev_descr;
4786 	int			maxp0;
4787 	struct usb_device_descriptor	*buf, *descr;
4788 
4789 	buf = kmalloc(GET_DESCRIPTOR_BUFSIZE, GFP_NOIO);
4790 	if (!buf)
4791 		return -ENOMEM;
4792 
4793 	/* root hub ports have a slightly longer reset period
4794 	 * (from USB 2.0 spec, section 7.1.7.5)
4795 	 */
4796 	if (!hdev->parent) {
4797 		delay = HUB_ROOT_RESET_TIME;
4798 		if (port1 == hdev->bus->otg_port)
4799 			hdev->bus->b_hnp_enable = 0;
4800 	}
4801 
4802 	/* Some low speed devices have problems with the quick delay, so */
4803 	/*  be a bit pessimistic with those devices. RHbug #23670 */
4804 	if (oldspeed == USB_SPEED_LOW)
4805 		delay = HUB_LONG_RESET_TIME;
4806 
4807 	/* Reset the device; full speed may morph to high speed */
4808 	/* FIXME a USB 2.0 device may morph into SuperSpeed on reset. */
4809 	retval = hub_port_reset(hub, port1, udev, delay, false);
4810 	if (retval < 0)		/* error or disconnect */
4811 		goto fail;
4812 	/* success, speed is known */
4813 
4814 	retval = -ENODEV;
4815 
4816 	/* Don't allow speed changes at reset, except usb 3.0 to faster */
4817 	if (oldspeed != USB_SPEED_UNKNOWN && oldspeed != udev->speed &&
4818 	    !(oldspeed == USB_SPEED_SUPER && udev->speed > oldspeed)) {
4819 		dev_dbg(&udev->dev, "device reset changed speed!\n");
4820 		goto fail;
4821 	}
4822 	oldspeed = udev->speed;
4823 
4824 	if (initial) {
4825 		/* USB 2.0 section 5.5.3 talks about ep0 maxpacket ...
4826 		 * it's fixed size except for full speed devices.
4827 		 */
4828 		switch (udev->speed) {
4829 		case USB_SPEED_SUPER_PLUS:
4830 		case USB_SPEED_SUPER:
4831 			udev->ep0.desc.wMaxPacketSize = cpu_to_le16(512);
4832 			break;
4833 		case USB_SPEED_HIGH:		/* fixed at 64 */
4834 			udev->ep0.desc.wMaxPacketSize = cpu_to_le16(64);
4835 			break;
4836 		case USB_SPEED_FULL:		/* 8, 16, 32, or 64 */
4837 			/* to determine the ep0 maxpacket size, try to read
4838 			 * the device descriptor to get bMaxPacketSize0 and
4839 			 * then correct our initial guess.
4840 			 */
4841 			udev->ep0.desc.wMaxPacketSize = cpu_to_le16(64);
4842 			break;
4843 		case USB_SPEED_LOW:		/* fixed at 8 */
4844 			udev->ep0.desc.wMaxPacketSize = cpu_to_le16(8);
4845 			break;
4846 		default:
4847 			goto fail;
4848 		}
4849 	}
4850 
4851 	speed = usb_speed_string(udev->speed);
4852 
4853 	/*
4854 	 * The controller driver may be NULL if the controller device
4855 	 * is the middle device between platform device and roothub.
4856 	 * This middle device may not need a device driver due to
4857 	 * all hardware control can be at platform device driver, this
4858 	 * platform device is usually a dual-role USB controller device.
4859 	 */
4860 	if (udev->bus->controller->driver)
4861 		driver_name = udev->bus->controller->driver->name;
4862 	else
4863 		driver_name = udev->bus->sysdev->driver->name;
4864 
4865 	if (udev->speed < USB_SPEED_SUPER)
4866 		dev_info(&udev->dev,
4867 				"%s %s USB device number %d using %s\n",
4868 				(initial ? "new" : "reset"), speed,
4869 				devnum, driver_name);
4870 
4871 	if (initial) {
4872 		/* Set up TT records, if needed  */
4873 		if (hdev->tt) {
4874 			udev->tt = hdev->tt;
4875 			udev->ttport = hdev->ttport;
4876 		} else if (udev->speed != USB_SPEED_HIGH
4877 				&& hdev->speed == USB_SPEED_HIGH) {
4878 			if (!hub->tt.hub) {
4879 				dev_err(&udev->dev, "parent hub has no TT\n");
4880 				retval = -EINVAL;
4881 				goto fail;
4882 			}
4883 			udev->tt = &hub->tt;
4884 			udev->ttport = port1;
4885 		}
4886 	}
4887 
4888 	/* Why interleave GET_DESCRIPTOR and SET_ADDRESS this way?
4889 	 * Because device hardware and firmware is sometimes buggy in
4890 	 * this area, and this is how Linux has done it for ages.
4891 	 * Change it cautiously.
4892 	 *
4893 	 * NOTE:  If use_new_scheme() is true we will start by issuing
4894 	 * a 64-byte GET_DESCRIPTOR request.  This is what Windows does,
4895 	 * so it may help with some non-standards-compliant devices.
4896 	 * Otherwise we start with SET_ADDRESS and then try to read the
4897 	 * first 8 bytes of the device descriptor to get the ep0 maxpacket
4898 	 * value.
4899 	 */
4900 	do_new_scheme = use_new_scheme(udev, retry_counter, port_dev);
4901 
4902 	for (retries = 0; retries < GET_DESCRIPTOR_TRIES; (++retries, msleep(100))) {
4903 		if (hub_port_stop_enumerate(hub, port1, retries)) {
4904 			retval = -ENODEV;
4905 			break;
4906 		}
4907 
4908 		if (do_new_scheme) {
4909 			retval = hub_enable_device(udev);
4910 			if (retval < 0) {
4911 				dev_err(&udev->dev,
4912 					"hub failed to enable device, error %d\n",
4913 					retval);
4914 				goto fail;
4915 			}
4916 
4917 			maxp0 = get_bMaxPacketSize0(udev, buf,
4918 					GET_DESCRIPTOR_BUFSIZE, retries == 0);
4919 			if (maxp0 > 0 && !initial &&
4920 					maxp0 != udev->descriptor.bMaxPacketSize0) {
4921 				dev_err(&udev->dev, "device reset changed ep0 maxpacket size!\n");
4922 				retval = -ENODEV;
4923 				goto fail;
4924 			}
4925 
4926 			retval = hub_port_reset(hub, port1, udev, delay, false);
4927 			if (retval < 0)		/* error or disconnect */
4928 				goto fail;
4929 			if (oldspeed != udev->speed) {
4930 				dev_dbg(&udev->dev,
4931 					"device reset changed speed!\n");
4932 				retval = -ENODEV;
4933 				goto fail;
4934 			}
4935 			if (maxp0 < 0) {
4936 				if (maxp0 != -ENODEV)
4937 					dev_err(&udev->dev, "device descriptor read/64, error %d\n",
4938 							maxp0);
4939 				retval = maxp0;
4940 				continue;
4941 			}
4942 		}
4943 
4944 		for (operations = 0; operations < SET_ADDRESS_TRIES; ++operations) {
4945 			retval = hub_set_address(udev, devnum);
4946 			if (retval >= 0)
4947 				break;
4948 			msleep(200);
4949 		}
4950 		if (retval < 0) {
4951 			if (retval != -ENODEV)
4952 				dev_err(&udev->dev, "device not accepting address %d, error %d\n",
4953 						devnum, retval);
4954 			goto fail;
4955 		}
4956 		if (udev->speed >= USB_SPEED_SUPER) {
4957 			devnum = udev->devnum;
4958 			dev_info(&udev->dev,
4959 					"%s SuperSpeed%s%s USB device number %d using %s\n",
4960 					(udev->config) ? "reset" : "new",
4961 				 (udev->speed == USB_SPEED_SUPER_PLUS) ?
4962 						" Plus" : "",
4963 				 (udev->ssp_rate == USB_SSP_GEN_2x2) ?
4964 						" Gen 2x2" :
4965 				 (udev->ssp_rate == USB_SSP_GEN_2x1) ?
4966 						" Gen 2x1" :
4967 				 (udev->ssp_rate == USB_SSP_GEN_1x2) ?
4968 						" Gen 1x2" : "",
4969 				 devnum, driver_name);
4970 		}
4971 
4972 		/*
4973 		 * cope with hardware quirkiness:
4974 		 *  - let SET_ADDRESS settle, some device hardware wants it
4975 		 *  - read ep0 maxpacket even for high and low speed,
4976 		 */
4977 		msleep(10);
4978 
4979 		if (do_new_scheme)
4980 			break;
4981 
4982 		maxp0 = get_bMaxPacketSize0(udev, buf, 8, retries == 0);
4983 		if (maxp0 < 0) {
4984 			retval = maxp0;
4985 			if (retval != -ENODEV)
4986 				dev_err(&udev->dev,
4987 					"device descriptor read/8, error %d\n",
4988 					retval);
4989 		} else {
4990 			u32 delay;
4991 
4992 			if (!initial && maxp0 != udev->descriptor.bMaxPacketSize0) {
4993 				dev_err(&udev->dev, "device reset changed ep0 maxpacket size!\n");
4994 				retval = -ENODEV;
4995 				goto fail;
4996 			}
4997 
4998 			delay = udev->parent->hub_delay;
4999 			udev->hub_delay = min_t(u32, delay,
5000 						USB_TP_TRANSMISSION_DELAY_MAX);
5001 			retval = usb_set_isoch_delay(udev);
5002 			if (retval) {
5003 				dev_dbg(&udev->dev,
5004 					"Failed set isoch delay, error %d\n",
5005 					retval);
5006 				retval = 0;
5007 			}
5008 			break;
5009 		}
5010 	}
5011 	if (retval)
5012 		goto fail;
5013 
5014 	/*
5015 	 * Check the ep0 maxpacket guess and correct it if necessary.
5016 	 * maxp0 is the value stored in the device descriptor;
5017 	 * i is the value it encodes (logarithmic for SuperSpeed or greater).
5018 	 */
5019 	i = maxp0;
5020 	if (udev->speed >= USB_SPEED_SUPER) {
5021 		if (maxp0 <= 16)
5022 			i = 1 << maxp0;
5023 		else
5024 			i = 0;		/* Invalid */
5025 	}
5026 	if (usb_endpoint_maxp(&udev->ep0.desc) == i) {
5027 		;	/* Initial ep0 maxpacket guess is right */
5028 	} else if ((udev->speed == USB_SPEED_FULL ||
5029 				udev->speed == USB_SPEED_HIGH) &&
5030 			(i == 8 || i == 16 || i == 32 || i == 64)) {
5031 		/* Initial guess is wrong; use the descriptor's value */
5032 		if (udev->speed == USB_SPEED_FULL)
5033 			dev_dbg(&udev->dev, "ep0 maxpacket = %d\n", i);
5034 		else
5035 			dev_warn(&udev->dev, "Using ep0 maxpacket: %d\n", i);
5036 		udev->ep0.desc.wMaxPacketSize = cpu_to_le16(i);
5037 		usb_ep0_reinit(udev);
5038 	} else {
5039 		/* Initial guess is wrong and descriptor's value is invalid */
5040 		dev_err(&udev->dev, "Invalid ep0 maxpacket: %d\n", maxp0);
5041 		retval = -EMSGSIZE;
5042 		goto fail;
5043 	}
5044 
5045 	descr = usb_get_device_descriptor(udev);
5046 	if (IS_ERR(descr)) {
5047 		retval = PTR_ERR(descr);
5048 		if (retval != -ENODEV)
5049 			dev_err(&udev->dev, "device descriptor read/all, error %d\n",
5050 					retval);
5051 		goto fail;
5052 	}
5053 	if (initial)
5054 		udev->descriptor = *descr;
5055 	else
5056 		*dev_descr = *descr;
5057 	kfree(descr);
5058 
5059 	/*
5060 	 * Some superspeed devices have finished the link training process
5061 	 * and attached to a superspeed hub port, but the device descriptor
5062 	 * got from those devices show they aren't superspeed devices. Warm
5063 	 * reset the port attached by the devices can fix them.
5064 	 */
5065 	if ((udev->speed >= USB_SPEED_SUPER) &&
5066 			(le16_to_cpu(udev->descriptor.bcdUSB) < 0x0300)) {
5067 		dev_err(&udev->dev, "got a wrong device descriptor, warm reset device\n");
5068 		hub_port_reset(hub, port1, udev, HUB_BH_RESET_TIME, true);
5069 		retval = -EINVAL;
5070 		goto fail;
5071 	}
5072 
5073 	usb_detect_quirks(udev);
5074 
5075 	if (le16_to_cpu(udev->descriptor.bcdUSB) >= 0x0201) {
5076 		retval = usb_get_bos_descriptor(udev);
5077 		if (!retval) {
5078 			udev->lpm_capable = usb_device_supports_lpm(udev);
5079 			udev->lpm_disable_count = 1;
5080 			usb_set_lpm_parameters(udev);
5081 			usb_req_set_sel(udev);
5082 		}
5083 	}
5084 
5085 	retval = 0;
5086 	/* notify HCD that we have a device connected and addressed */
5087 	if (hcd->driver->update_device)
5088 		hcd->driver->update_device(hcd, udev);
5089 	hub_set_initial_usb2_lpm_policy(udev);
5090 fail:
5091 	if (retval) {
5092 		hub_port_disable(hub, port1, 0);
5093 		update_devnum(udev, devnum);	/* for disconnect processing */
5094 	}
5095 	kfree(buf);
5096 	return retval;
5097 }
5098 
5099 static void
5100 check_highspeed(struct usb_hub *hub, struct usb_device *udev, int port1)
5101 {
5102 	struct usb_qualifier_descriptor	*qual;
5103 	int				status;
5104 
5105 	if (udev->quirks & USB_QUIRK_DEVICE_QUALIFIER)
5106 		return;
5107 
5108 	qual = kmalloc(sizeof *qual, GFP_KERNEL);
5109 	if (qual == NULL)
5110 		return;
5111 
5112 	status = usb_get_descriptor(udev, USB_DT_DEVICE_QUALIFIER, 0,
5113 			qual, sizeof *qual);
5114 	if (status == sizeof *qual) {
5115 		dev_info(&udev->dev, "not running at top speed; "
5116 			"connect to a high speed hub\n");
5117 		/* hub LEDs are probably harder to miss than syslog */
5118 		if (hub->has_indicators) {
5119 			hub->indicator[port1-1] = INDICATOR_GREEN_BLINK;
5120 			queue_delayed_work(system_power_efficient_wq,
5121 					&hub->leds, 0);
5122 		}
5123 	}
5124 	kfree(qual);
5125 }
5126 
5127 static unsigned
5128 hub_power_remaining(struct usb_hub *hub)
5129 {
5130 	struct usb_device *hdev = hub->hdev;
5131 	int remaining;
5132 	int port1;
5133 
5134 	if (!hub->limited_power)
5135 		return 0;
5136 
5137 	remaining = hdev->bus_mA - hub->descriptor->bHubContrCurrent;
5138 	for (port1 = 1; port1 <= hdev->maxchild; ++port1) {
5139 		struct usb_port *port_dev = hub->ports[port1 - 1];
5140 		struct usb_device *udev = port_dev->child;
5141 		unsigned unit_load;
5142 		int delta;
5143 
5144 		if (!udev)
5145 			continue;
5146 		if (hub_is_superspeed(udev))
5147 			unit_load = 150;
5148 		else
5149 			unit_load = 100;
5150 
5151 		/*
5152 		 * Unconfigured devices may not use more than one unit load,
5153 		 * or 8mA for OTG ports
5154 		 */
5155 		if (udev->actconfig)
5156 			delta = usb_get_max_power(udev, udev->actconfig);
5157 		else if (port1 != udev->bus->otg_port || hdev->parent)
5158 			delta = unit_load;
5159 		else
5160 			delta = 8;
5161 		if (delta > hub->mA_per_port)
5162 			dev_warn(&port_dev->dev, "%dmA is over %umA budget!\n",
5163 					delta, hub->mA_per_port);
5164 		remaining -= delta;
5165 	}
5166 	if (remaining < 0) {
5167 		dev_warn(hub->intfdev, "%dmA over power budget!\n",
5168 			-remaining);
5169 		remaining = 0;
5170 	}
5171 	return remaining;
5172 }
5173 
5174 
5175 static int descriptors_changed(struct usb_device *udev,
5176 		struct usb_device_descriptor *new_device_descriptor,
5177 		struct usb_host_bos *old_bos)
5178 {
5179 	int		changed = 0;
5180 	unsigned	index;
5181 	unsigned	serial_len = 0;
5182 	unsigned	len;
5183 	unsigned	old_length;
5184 	int		length;
5185 	char		*buf;
5186 
5187 	if (memcmp(&udev->descriptor, new_device_descriptor,
5188 			sizeof(*new_device_descriptor)) != 0)
5189 		return 1;
5190 
5191 	if ((old_bos && !udev->bos) || (!old_bos && udev->bos))
5192 		return 1;
5193 	if (udev->bos) {
5194 		len = le16_to_cpu(udev->bos->desc->wTotalLength);
5195 		if (len != le16_to_cpu(old_bos->desc->wTotalLength))
5196 			return 1;
5197 		if (memcmp(udev->bos->desc, old_bos->desc, len))
5198 			return 1;
5199 	}
5200 
5201 	/* Since the idVendor, idProduct, and bcdDevice values in the
5202 	 * device descriptor haven't changed, we will assume the
5203 	 * Manufacturer and Product strings haven't changed either.
5204 	 * But the SerialNumber string could be different (e.g., a
5205 	 * different flash card of the same brand).
5206 	 */
5207 	if (udev->serial)
5208 		serial_len = strlen(udev->serial) + 1;
5209 
5210 	len = serial_len;
5211 	for (index = 0; index < udev->descriptor.bNumConfigurations; index++) {
5212 		old_length = le16_to_cpu(udev->config[index].desc.wTotalLength);
5213 		len = max(len, old_length);
5214 	}
5215 
5216 	buf = kmalloc(len, GFP_NOIO);
5217 	if (!buf)
5218 		/* assume the worst */
5219 		return 1;
5220 
5221 	for (index = 0; index < udev->descriptor.bNumConfigurations; index++) {
5222 		old_length = le16_to_cpu(udev->config[index].desc.wTotalLength);
5223 		length = usb_get_descriptor(udev, USB_DT_CONFIG, index, buf,
5224 				old_length);
5225 		if (length != old_length) {
5226 			dev_dbg(&udev->dev, "config index %d, error %d\n",
5227 					index, length);
5228 			changed = 1;
5229 			break;
5230 		}
5231 		if (memcmp(buf, udev->rawdescriptors[index], old_length)
5232 				!= 0) {
5233 			dev_dbg(&udev->dev, "config index %d changed (#%d)\n",
5234 				index,
5235 				((struct usb_config_descriptor *) buf)->
5236 					bConfigurationValue);
5237 			changed = 1;
5238 			break;
5239 		}
5240 	}
5241 
5242 	if (!changed && serial_len) {
5243 		length = usb_string(udev, udev->descriptor.iSerialNumber,
5244 				buf, serial_len);
5245 		if (length + 1 != serial_len) {
5246 			dev_dbg(&udev->dev, "serial string error %d\n",
5247 					length);
5248 			changed = 1;
5249 		} else if (memcmp(buf, udev->serial, length) != 0) {
5250 			dev_dbg(&udev->dev, "serial string changed\n");
5251 			changed = 1;
5252 		}
5253 	}
5254 
5255 	kfree(buf);
5256 	return changed;
5257 }
5258 
5259 static void hub_port_connect(struct usb_hub *hub, int port1, u16 portstatus,
5260 		u16 portchange)
5261 {
5262 	int status = -ENODEV;
5263 	int i;
5264 	unsigned unit_load;
5265 	struct usb_device *hdev = hub->hdev;
5266 	struct usb_hcd *hcd = bus_to_hcd(hdev->bus);
5267 	struct usb_port *port_dev = hub->ports[port1 - 1];
5268 	struct usb_device *udev = port_dev->child;
5269 	static int unreliable_port = -1;
5270 	bool retry_locked;
5271 
5272 	/* Disconnect any existing devices under this port */
5273 	if (udev) {
5274 		if (hcd->usb_phy && !hdev->parent)
5275 			usb_phy_notify_disconnect(hcd->usb_phy, udev->speed);
5276 		usb_disconnect(&port_dev->child);
5277 	}
5278 
5279 	/* We can forget about a "removed" device when there's a physical
5280 	 * disconnect or the connect status changes.
5281 	 */
5282 	if (!(portstatus & USB_PORT_STAT_CONNECTION) ||
5283 			(portchange & USB_PORT_STAT_C_CONNECTION))
5284 		clear_bit(port1, hub->removed_bits);
5285 
5286 	if (portchange & (USB_PORT_STAT_C_CONNECTION |
5287 				USB_PORT_STAT_C_ENABLE)) {
5288 		status = hub_port_debounce_be_stable(hub, port1);
5289 		if (status < 0) {
5290 			if (status != -ENODEV &&
5291 				port1 != unreliable_port &&
5292 				printk_ratelimit())
5293 				dev_err(&port_dev->dev, "connect-debounce failed\n");
5294 			portstatus &= ~USB_PORT_STAT_CONNECTION;
5295 			unreliable_port = port1;
5296 		} else {
5297 			portstatus = status;
5298 		}
5299 	}
5300 
5301 	/* Return now if debouncing failed or nothing is connected or
5302 	 * the device was "removed".
5303 	 */
5304 	if (!(portstatus & USB_PORT_STAT_CONNECTION) ||
5305 			test_bit(port1, hub->removed_bits)) {
5306 
5307 		/*
5308 		 * maybe switch power back on (e.g. root hub was reset)
5309 		 * but only if the port isn't owned by someone else.
5310 		 */
5311 		if (hub_is_port_power_switchable(hub)
5312 				&& !usb_port_is_power_on(hub, portstatus)
5313 				&& !port_dev->port_owner)
5314 			set_port_feature(hdev, port1, USB_PORT_FEAT_POWER);
5315 
5316 		if (portstatus & USB_PORT_STAT_ENABLE)
5317 			goto done;
5318 		return;
5319 	}
5320 	if (hub_is_superspeed(hub->hdev))
5321 		unit_load = 150;
5322 	else
5323 		unit_load = 100;
5324 
5325 	status = 0;
5326 
5327 	for (i = 0; i < PORT_INIT_TRIES; i++) {
5328 		if (hub_port_stop_enumerate(hub, port1, i)) {
5329 			status = -ENODEV;
5330 			break;
5331 		}
5332 
5333 		usb_lock_port(port_dev);
5334 		mutex_lock(hcd->address0_mutex);
5335 		retry_locked = true;
5336 		/* reallocate for each attempt, since references
5337 		 * to the previous one can escape in various ways
5338 		 */
5339 		udev = usb_alloc_dev(hdev, hdev->bus, port1);
5340 		if (!udev) {
5341 			dev_err(&port_dev->dev,
5342 					"couldn't allocate usb_device\n");
5343 			mutex_unlock(hcd->address0_mutex);
5344 			usb_unlock_port(port_dev);
5345 			goto done;
5346 		}
5347 
5348 		usb_set_device_state(udev, USB_STATE_POWERED);
5349 		udev->bus_mA = hub->mA_per_port;
5350 		udev->level = hdev->level + 1;
5351 
5352 		/* Devices connected to SuperSpeed hubs are USB 3.0 or later */
5353 		if (hub_is_superspeed(hub->hdev))
5354 			udev->speed = USB_SPEED_SUPER;
5355 		else
5356 			udev->speed = USB_SPEED_UNKNOWN;
5357 
5358 		choose_devnum(udev);
5359 		if (udev->devnum <= 0) {
5360 			status = -ENOTCONN;	/* Don't retry */
5361 			goto loop;
5362 		}
5363 
5364 		/* reset (non-USB 3.0 devices) and get descriptor */
5365 		status = hub_port_init(hub, udev, port1, i, NULL);
5366 		if (status < 0)
5367 			goto loop;
5368 
5369 		mutex_unlock(hcd->address0_mutex);
5370 		usb_unlock_port(port_dev);
5371 		retry_locked = false;
5372 
5373 		if (udev->quirks & USB_QUIRK_DELAY_INIT)
5374 			msleep(2000);
5375 
5376 		/* consecutive bus-powered hubs aren't reliable; they can
5377 		 * violate the voltage drop budget.  if the new child has
5378 		 * a "powered" LED, users should notice we didn't enable it
5379 		 * (without reading syslog), even without per-port LEDs
5380 		 * on the parent.
5381 		 */
5382 		if (udev->descriptor.bDeviceClass == USB_CLASS_HUB
5383 				&& udev->bus_mA <= unit_load) {
5384 			u16	devstat;
5385 
5386 			status = usb_get_std_status(udev, USB_RECIP_DEVICE, 0,
5387 					&devstat);
5388 			if (status) {
5389 				dev_dbg(&udev->dev, "get status %d ?\n", status);
5390 				goto loop_disable;
5391 			}
5392 			if ((devstat & (1 << USB_DEVICE_SELF_POWERED)) == 0) {
5393 				dev_err(&udev->dev,
5394 					"can't connect bus-powered hub "
5395 					"to this port\n");
5396 				if (hub->has_indicators) {
5397 					hub->indicator[port1-1] =
5398 						INDICATOR_AMBER_BLINK;
5399 					queue_delayed_work(
5400 						system_power_efficient_wq,
5401 						&hub->leds, 0);
5402 				}
5403 				status = -ENOTCONN;	/* Don't retry */
5404 				goto loop_disable;
5405 			}
5406 		}
5407 
5408 		/* check for devices running slower than they could */
5409 		if (le16_to_cpu(udev->descriptor.bcdUSB) >= 0x0200
5410 				&& udev->speed == USB_SPEED_FULL
5411 				&& highspeed_hubs != 0)
5412 			check_highspeed(hub, udev, port1);
5413 
5414 		/* Store the parent's children[] pointer.  At this point
5415 		 * udev becomes globally accessible, although presumably
5416 		 * no one will look at it until hdev is unlocked.
5417 		 */
5418 		status = 0;
5419 
5420 		mutex_lock(&usb_port_peer_mutex);
5421 
5422 		/* We mustn't add new devices if the parent hub has
5423 		 * been disconnected; we would race with the
5424 		 * recursively_mark_NOTATTACHED() routine.
5425 		 */
5426 		spin_lock_irq(&device_state_lock);
5427 		if (hdev->state == USB_STATE_NOTATTACHED)
5428 			status = -ENOTCONN;
5429 		else
5430 			port_dev->child = udev;
5431 		spin_unlock_irq(&device_state_lock);
5432 		mutex_unlock(&usb_port_peer_mutex);
5433 
5434 		/* Run it through the hoops (find a driver, etc) */
5435 		if (!status) {
5436 			status = usb_new_device(udev);
5437 			if (status) {
5438 				mutex_lock(&usb_port_peer_mutex);
5439 				spin_lock_irq(&device_state_lock);
5440 				port_dev->child = NULL;
5441 				spin_unlock_irq(&device_state_lock);
5442 				mutex_unlock(&usb_port_peer_mutex);
5443 			} else {
5444 				if (hcd->usb_phy && !hdev->parent)
5445 					usb_phy_notify_connect(hcd->usb_phy,
5446 							udev->speed);
5447 			}
5448 		}
5449 
5450 		if (status)
5451 			goto loop_disable;
5452 
5453 		status = hub_power_remaining(hub);
5454 		if (status)
5455 			dev_dbg(hub->intfdev, "%dmA power budget left\n", status);
5456 
5457 		return;
5458 
5459 loop_disable:
5460 		hub_port_disable(hub, port1, 1);
5461 loop:
5462 		usb_ep0_reinit(udev);
5463 		release_devnum(udev);
5464 		hub_free_dev(udev);
5465 		if (retry_locked) {
5466 			mutex_unlock(hcd->address0_mutex);
5467 			usb_unlock_port(port_dev);
5468 		}
5469 		usb_put_dev(udev);
5470 		if ((status == -ENOTCONN) || (status == -ENOTSUPP))
5471 			break;
5472 
5473 		/* When halfway through our retry count, power-cycle the port */
5474 		if (i == (PORT_INIT_TRIES - 1) / 2) {
5475 			dev_info(&port_dev->dev, "attempt power cycle\n");
5476 			usb_hub_set_port_power(hdev, hub, port1, false);
5477 			msleep(2 * hub_power_on_good_delay(hub));
5478 			usb_hub_set_port_power(hdev, hub, port1, true);
5479 			msleep(hub_power_on_good_delay(hub));
5480 		}
5481 	}
5482 	if (hub->hdev->parent ||
5483 			!hcd->driver->port_handed_over ||
5484 			!(hcd->driver->port_handed_over)(hcd, port1)) {
5485 		if (status != -ENOTCONN && status != -ENODEV)
5486 			dev_err(&port_dev->dev,
5487 					"unable to enumerate USB device\n");
5488 	}
5489 
5490 done:
5491 	hub_port_disable(hub, port1, 1);
5492 	if (hcd->driver->relinquish_port && !hub->hdev->parent) {
5493 		if (status != -ENOTCONN && status != -ENODEV)
5494 			hcd->driver->relinquish_port(hcd, port1);
5495 	}
5496 }
5497 
5498 /* Handle physical or logical connection change events.
5499  * This routine is called when:
5500  *	a port connection-change occurs;
5501  *	a port enable-change occurs (often caused by EMI);
5502  *	usb_reset_and_verify_device() encounters changed descriptors (as from
5503  *		a firmware download)
5504  * caller already locked the hub
5505  */
5506 static void hub_port_connect_change(struct usb_hub *hub, int port1,
5507 					u16 portstatus, u16 portchange)
5508 		__must_hold(&port_dev->status_lock)
5509 {
5510 	struct usb_port *port_dev = hub->ports[port1 - 1];
5511 	struct usb_device *udev = port_dev->child;
5512 	struct usb_device_descriptor *descr;
5513 	int status = -ENODEV;
5514 
5515 	dev_dbg(&port_dev->dev, "status %04x, change %04x, %s\n", portstatus,
5516 			portchange, portspeed(hub, portstatus));
5517 
5518 	if (hub->has_indicators) {
5519 		set_port_led(hub, port1, HUB_LED_AUTO);
5520 		hub->indicator[port1-1] = INDICATOR_AUTO;
5521 	}
5522 
5523 #ifdef	CONFIG_USB_OTG
5524 	/* during HNP, don't repeat the debounce */
5525 	if (hub->hdev->bus->is_b_host)
5526 		portchange &= ~(USB_PORT_STAT_C_CONNECTION |
5527 				USB_PORT_STAT_C_ENABLE);
5528 #endif
5529 
5530 	/* Try to resuscitate an existing device */
5531 	if ((portstatus & USB_PORT_STAT_CONNECTION) && udev &&
5532 			udev->state != USB_STATE_NOTATTACHED) {
5533 		if (portstatus & USB_PORT_STAT_ENABLE) {
5534 			/*
5535 			 * USB-3 connections are initialized automatically by
5536 			 * the hostcontroller hardware. Therefore check for
5537 			 * changed device descriptors before resuscitating the
5538 			 * device.
5539 			 */
5540 			descr = usb_get_device_descriptor(udev);
5541 			if (IS_ERR(descr)) {
5542 				dev_dbg(&udev->dev,
5543 						"can't read device descriptor %ld\n",
5544 						PTR_ERR(descr));
5545 			} else {
5546 				if (descriptors_changed(udev, descr,
5547 						udev->bos)) {
5548 					dev_dbg(&udev->dev,
5549 							"device descriptor has changed\n");
5550 				} else {
5551 					status = 0; /* Nothing to do */
5552 				}
5553 				kfree(descr);
5554 			}
5555 #ifdef CONFIG_PM
5556 		} else if (udev->state == USB_STATE_SUSPENDED &&
5557 				udev->persist_enabled) {
5558 			/* For a suspended device, treat this as a
5559 			 * remote wakeup event.
5560 			 */
5561 			usb_unlock_port(port_dev);
5562 			status = usb_remote_wakeup(udev);
5563 			usb_lock_port(port_dev);
5564 #endif
5565 		} else {
5566 			/* Don't resuscitate */;
5567 		}
5568 	}
5569 	clear_bit(port1, hub->change_bits);
5570 
5571 	/* successfully revalidated the connection */
5572 	if (status == 0)
5573 		return;
5574 
5575 	usb_unlock_port(port_dev);
5576 	hub_port_connect(hub, port1, portstatus, portchange);
5577 	usb_lock_port(port_dev);
5578 }
5579 
5580 /* Handle notifying userspace about hub over-current events */
5581 static void port_over_current_notify(struct usb_port *port_dev)
5582 {
5583 	char *envp[3] = { NULL, NULL, NULL };
5584 	struct device *hub_dev;
5585 	char *port_dev_path;
5586 
5587 	sysfs_notify(&port_dev->dev.kobj, NULL, "over_current_count");
5588 
5589 	hub_dev = port_dev->dev.parent;
5590 
5591 	if (!hub_dev)
5592 		return;
5593 
5594 	port_dev_path = kobject_get_path(&port_dev->dev.kobj, GFP_KERNEL);
5595 	if (!port_dev_path)
5596 		return;
5597 
5598 	envp[0] = kasprintf(GFP_KERNEL, "OVER_CURRENT_PORT=%s", port_dev_path);
5599 	if (!envp[0])
5600 		goto exit;
5601 
5602 	envp[1] = kasprintf(GFP_KERNEL, "OVER_CURRENT_COUNT=%u",
5603 			port_dev->over_current_count);
5604 	if (!envp[1])
5605 		goto exit;
5606 
5607 	kobject_uevent_env(&hub_dev->kobj, KOBJ_CHANGE, envp);
5608 
5609 exit:
5610 	kfree(envp[1]);
5611 	kfree(envp[0]);
5612 	kfree(port_dev_path);
5613 }
5614 
5615 static void port_event(struct usb_hub *hub, int port1)
5616 		__must_hold(&port_dev->status_lock)
5617 {
5618 	int connect_change;
5619 	struct usb_port *port_dev = hub->ports[port1 - 1];
5620 	struct usb_device *udev = port_dev->child;
5621 	struct usb_device *hdev = hub->hdev;
5622 	u16 portstatus, portchange;
5623 	int i = 0;
5624 
5625 	connect_change = test_bit(port1, hub->change_bits);
5626 	clear_bit(port1, hub->event_bits);
5627 	clear_bit(port1, hub->wakeup_bits);
5628 
5629 	if (usb_hub_port_status(hub, port1, &portstatus, &portchange) < 0)
5630 		return;
5631 
5632 	if (portchange & USB_PORT_STAT_C_CONNECTION) {
5633 		usb_clear_port_feature(hdev, port1, USB_PORT_FEAT_C_CONNECTION);
5634 		connect_change = 1;
5635 	}
5636 
5637 	if (portchange & USB_PORT_STAT_C_ENABLE) {
5638 		if (!connect_change)
5639 			dev_dbg(&port_dev->dev, "enable change, status %08x\n",
5640 					portstatus);
5641 		usb_clear_port_feature(hdev, port1, USB_PORT_FEAT_C_ENABLE);
5642 
5643 		/*
5644 		 * EM interference sometimes causes badly shielded USB devices
5645 		 * to be shutdown by the hub, this hack enables them again.
5646 		 * Works at least with mouse driver.
5647 		 */
5648 		if (!(portstatus & USB_PORT_STAT_ENABLE)
5649 		    && !connect_change && udev) {
5650 			dev_err(&port_dev->dev, "disabled by hub (EMI?), re-enabling...\n");
5651 			connect_change = 1;
5652 		}
5653 	}
5654 
5655 	if (portchange & USB_PORT_STAT_C_OVERCURRENT) {
5656 		u16 status = 0, unused;
5657 		port_dev->over_current_count++;
5658 		port_over_current_notify(port_dev);
5659 
5660 		dev_dbg(&port_dev->dev, "over-current change #%u\n",
5661 			port_dev->over_current_count);
5662 		usb_clear_port_feature(hdev, port1,
5663 				USB_PORT_FEAT_C_OVER_CURRENT);
5664 		msleep(100);	/* Cool down */
5665 		hub_power_on(hub, true);
5666 		usb_hub_port_status(hub, port1, &status, &unused);
5667 		if (status & USB_PORT_STAT_OVERCURRENT)
5668 			dev_err(&port_dev->dev, "over-current condition\n");
5669 	}
5670 
5671 	if (portchange & USB_PORT_STAT_C_RESET) {
5672 		dev_dbg(&port_dev->dev, "reset change\n");
5673 		usb_clear_port_feature(hdev, port1, USB_PORT_FEAT_C_RESET);
5674 	}
5675 	if ((portchange & USB_PORT_STAT_C_BH_RESET)
5676 	    && hub_is_superspeed(hdev)) {
5677 		dev_dbg(&port_dev->dev, "warm reset change\n");
5678 		usb_clear_port_feature(hdev, port1,
5679 				USB_PORT_FEAT_C_BH_PORT_RESET);
5680 	}
5681 	if (portchange & USB_PORT_STAT_C_LINK_STATE) {
5682 		dev_dbg(&port_dev->dev, "link state change\n");
5683 		usb_clear_port_feature(hdev, port1,
5684 				USB_PORT_FEAT_C_PORT_LINK_STATE);
5685 	}
5686 	if (portchange & USB_PORT_STAT_C_CONFIG_ERROR) {
5687 		dev_warn(&port_dev->dev, "config error\n");
5688 		usb_clear_port_feature(hdev, port1,
5689 				USB_PORT_FEAT_C_PORT_CONFIG_ERROR);
5690 	}
5691 
5692 	/* skip port actions that require the port to be powered on */
5693 	if (!pm_runtime_active(&port_dev->dev))
5694 		return;
5695 
5696 	/* skip port actions if ignore_event and early_stop are true */
5697 	if (port_dev->ignore_event && port_dev->early_stop)
5698 		return;
5699 
5700 	if (hub_handle_remote_wakeup(hub, port1, portstatus, portchange))
5701 		connect_change = 1;
5702 
5703 	/*
5704 	 * Avoid trying to recover a USB3 SS.Inactive port with a warm reset if
5705 	 * the device was disconnected. A 12ms disconnect detect timer in
5706 	 * SS.Inactive state transitions the port to RxDetect automatically.
5707 	 * SS.Inactive link error state is common during device disconnect.
5708 	 */
5709 	while (hub_port_warm_reset_required(hub, port1, portstatus)) {
5710 		if ((i++ < DETECT_DISCONNECT_TRIES) && udev) {
5711 			u16 unused;
5712 
5713 			msleep(20);
5714 			usb_hub_port_status(hub, port1, &portstatus, &unused);
5715 			dev_dbg(&port_dev->dev, "Wait for inactive link disconnect detect\n");
5716 			continue;
5717 		} else if (!udev || !(portstatus & USB_PORT_STAT_CONNECTION)
5718 				|| udev->state == USB_STATE_NOTATTACHED) {
5719 			dev_dbg(&port_dev->dev, "do warm reset, port only\n");
5720 			if (hub_port_reset(hub, port1, NULL,
5721 					HUB_BH_RESET_TIME, true) < 0)
5722 				hub_port_disable(hub, port1, 1);
5723 		} else {
5724 			dev_dbg(&port_dev->dev, "do warm reset, full device\n");
5725 			usb_unlock_port(port_dev);
5726 			usb_lock_device(udev);
5727 			usb_reset_device(udev);
5728 			usb_unlock_device(udev);
5729 			usb_lock_port(port_dev);
5730 			connect_change = 0;
5731 		}
5732 		break;
5733 	}
5734 
5735 	if (connect_change)
5736 		hub_port_connect_change(hub, port1, portstatus, portchange);
5737 }
5738 
5739 static void hub_event(struct work_struct *work)
5740 {
5741 	struct usb_device *hdev;
5742 	struct usb_interface *intf;
5743 	struct usb_hub *hub;
5744 	struct device *hub_dev;
5745 	u16 hubstatus;
5746 	u16 hubchange;
5747 	int i, ret;
5748 
5749 	hub = container_of(work, struct usb_hub, events);
5750 	hdev = hub->hdev;
5751 	hub_dev = hub->intfdev;
5752 	intf = to_usb_interface(hub_dev);
5753 
5754 	kcov_remote_start_usb((u64)hdev->bus->busnum);
5755 
5756 	dev_dbg(hub_dev, "state %d ports %d chg %04x evt %04x\n",
5757 			hdev->state, hdev->maxchild,
5758 			/* NOTE: expects max 15 ports... */
5759 			(u16) hub->change_bits[0],
5760 			(u16) hub->event_bits[0]);
5761 
5762 	/* Lock the device, then check to see if we were
5763 	 * disconnected while waiting for the lock to succeed. */
5764 	usb_lock_device(hdev);
5765 	if (unlikely(hub->disconnected))
5766 		goto out_hdev_lock;
5767 
5768 	/* If the hub has died, clean up after it */
5769 	if (hdev->state == USB_STATE_NOTATTACHED) {
5770 		hub->error = -ENODEV;
5771 		hub_quiesce(hub, HUB_DISCONNECT);
5772 		goto out_hdev_lock;
5773 	}
5774 
5775 	/* Autoresume */
5776 	ret = usb_autopm_get_interface(intf);
5777 	if (ret) {
5778 		dev_dbg(hub_dev, "Can't autoresume: %d\n", ret);
5779 		goto out_hdev_lock;
5780 	}
5781 
5782 	/* If this is an inactive hub, do nothing */
5783 	if (hub->quiescing)
5784 		goto out_autopm;
5785 
5786 	if (hub->error) {
5787 		dev_dbg(hub_dev, "resetting for error %d\n", hub->error);
5788 
5789 		ret = usb_reset_device(hdev);
5790 		if (ret) {
5791 			dev_dbg(hub_dev, "error resetting hub: %d\n", ret);
5792 			goto out_autopm;
5793 		}
5794 
5795 		hub->nerrors = 0;
5796 		hub->error = 0;
5797 	}
5798 
5799 	/* deal with port status changes */
5800 	for (i = 1; i <= hdev->maxchild; i++) {
5801 		struct usb_port *port_dev = hub->ports[i - 1];
5802 
5803 		if (test_bit(i, hub->event_bits)
5804 				|| test_bit(i, hub->change_bits)
5805 				|| test_bit(i, hub->wakeup_bits)) {
5806 			/*
5807 			 * The get_noresume and barrier ensure that if
5808 			 * the port was in the process of resuming, we
5809 			 * flush that work and keep the port active for
5810 			 * the duration of the port_event().  However,
5811 			 * if the port is runtime pm suspended
5812 			 * (powered-off), we leave it in that state, run
5813 			 * an abbreviated port_event(), and move on.
5814 			 */
5815 			pm_runtime_get_noresume(&port_dev->dev);
5816 			pm_runtime_barrier(&port_dev->dev);
5817 			usb_lock_port(port_dev);
5818 			port_event(hub, i);
5819 			usb_unlock_port(port_dev);
5820 			pm_runtime_put_sync(&port_dev->dev);
5821 		}
5822 	}
5823 
5824 	/* deal with hub status changes */
5825 	if (test_and_clear_bit(0, hub->event_bits) == 0)
5826 		;	/* do nothing */
5827 	else if (hub_hub_status(hub, &hubstatus, &hubchange) < 0)
5828 		dev_err(hub_dev, "get_hub_status failed\n");
5829 	else {
5830 		if (hubchange & HUB_CHANGE_LOCAL_POWER) {
5831 			dev_dbg(hub_dev, "power change\n");
5832 			clear_hub_feature(hdev, C_HUB_LOCAL_POWER);
5833 			if (hubstatus & HUB_STATUS_LOCAL_POWER)
5834 				/* FIXME: Is this always true? */
5835 				hub->limited_power = 1;
5836 			else
5837 				hub->limited_power = 0;
5838 		}
5839 		if (hubchange & HUB_CHANGE_OVERCURRENT) {
5840 			u16 status = 0;
5841 			u16 unused;
5842 
5843 			dev_dbg(hub_dev, "over-current change\n");
5844 			clear_hub_feature(hdev, C_HUB_OVER_CURRENT);
5845 			msleep(500);	/* Cool down */
5846 			hub_power_on(hub, true);
5847 			hub_hub_status(hub, &status, &unused);
5848 			if (status & HUB_STATUS_OVERCURRENT)
5849 				dev_err(hub_dev, "over-current condition\n");
5850 		}
5851 	}
5852 
5853 out_autopm:
5854 	/* Balance the usb_autopm_get_interface() above */
5855 	usb_autopm_put_interface_no_suspend(intf);
5856 out_hdev_lock:
5857 	usb_unlock_device(hdev);
5858 
5859 	/* Balance the stuff in kick_hub_wq() and allow autosuspend */
5860 	usb_autopm_put_interface(intf);
5861 	kref_put(&hub->kref, hub_release);
5862 
5863 	kcov_remote_stop();
5864 }
5865 
5866 static const struct usb_device_id hub_id_table[] = {
5867     { .match_flags = USB_DEVICE_ID_MATCH_VENDOR
5868                    | USB_DEVICE_ID_MATCH_PRODUCT
5869                    | USB_DEVICE_ID_MATCH_INT_CLASS,
5870       .idVendor = USB_VENDOR_SMSC,
5871       .idProduct = USB_PRODUCT_USB5534B,
5872       .bInterfaceClass = USB_CLASS_HUB,
5873       .driver_info = HUB_QUIRK_DISABLE_AUTOSUSPEND},
5874     { .match_flags = USB_DEVICE_ID_MATCH_VENDOR
5875                    | USB_DEVICE_ID_MATCH_PRODUCT,
5876       .idVendor = USB_VENDOR_CYPRESS,
5877       .idProduct = USB_PRODUCT_CY7C65632,
5878       .driver_info = HUB_QUIRK_DISABLE_AUTOSUSPEND},
5879     { .match_flags = USB_DEVICE_ID_MATCH_VENDOR
5880 			| USB_DEVICE_ID_MATCH_INT_CLASS,
5881       .idVendor = USB_VENDOR_GENESYS_LOGIC,
5882       .bInterfaceClass = USB_CLASS_HUB,
5883       .driver_info = HUB_QUIRK_CHECK_PORT_AUTOSUSPEND},
5884     { .match_flags = USB_DEVICE_ID_MATCH_VENDOR
5885 			| USB_DEVICE_ID_MATCH_PRODUCT,
5886       .idVendor = USB_VENDOR_TEXAS_INSTRUMENTS,
5887       .idProduct = USB_PRODUCT_TUSB8041_USB2,
5888       .driver_info = HUB_QUIRK_DISABLE_AUTOSUSPEND},
5889     { .match_flags = USB_DEVICE_ID_MATCH_VENDOR
5890 			| USB_DEVICE_ID_MATCH_PRODUCT,
5891       .idVendor = USB_VENDOR_TEXAS_INSTRUMENTS,
5892       .idProduct = USB_PRODUCT_TUSB8041_USB3,
5893       .driver_info = HUB_QUIRK_DISABLE_AUTOSUSPEND},
5894     { .match_flags = USB_DEVICE_ID_MATCH_DEV_CLASS,
5895       .bDeviceClass = USB_CLASS_HUB},
5896     { .match_flags = USB_DEVICE_ID_MATCH_INT_CLASS,
5897       .bInterfaceClass = USB_CLASS_HUB},
5898     { }						/* Terminating entry */
5899 };
5900 
5901 MODULE_DEVICE_TABLE(usb, hub_id_table);
5902 
5903 static struct usb_driver hub_driver = {
5904 	.name =		"hub",
5905 	.probe =	hub_probe,
5906 	.disconnect =	hub_disconnect,
5907 	.suspend =	hub_suspend,
5908 	.resume =	hub_resume,
5909 	.reset_resume =	hub_reset_resume,
5910 	.pre_reset =	hub_pre_reset,
5911 	.post_reset =	hub_post_reset,
5912 	.unlocked_ioctl = hub_ioctl,
5913 	.id_table =	hub_id_table,
5914 	.supports_autosuspend =	1,
5915 };
5916 
5917 int usb_hub_init(void)
5918 {
5919 	if (usb_register(&hub_driver) < 0) {
5920 		printk(KERN_ERR "%s: can't register hub driver\n",
5921 			usbcore_name);
5922 		return -1;
5923 	}
5924 
5925 	/*
5926 	 * The workqueue needs to be freezable to avoid interfering with
5927 	 * USB-PERSIST port handover. Otherwise it might see that a full-speed
5928 	 * device was gone before the EHCI controller had handed its port
5929 	 * over to the companion full-speed controller.
5930 	 */
5931 	hub_wq = alloc_workqueue("usb_hub_wq", WQ_FREEZABLE, 0);
5932 	if (hub_wq)
5933 		return 0;
5934 
5935 	/* Fall through if kernel_thread failed */
5936 	usb_deregister(&hub_driver);
5937 	pr_err("%s: can't allocate workqueue for usb hub\n", usbcore_name);
5938 
5939 	return -1;
5940 }
5941 
5942 void usb_hub_cleanup(void)
5943 {
5944 	destroy_workqueue(hub_wq);
5945 
5946 	/*
5947 	 * Hub resources are freed for us by usb_deregister. It calls
5948 	 * usb_driver_purge on every device which in turn calls that
5949 	 * devices disconnect function if it is using this driver.
5950 	 * The hub_disconnect function takes care of releasing the
5951 	 * individual hub resources. -greg
5952 	 */
5953 	usb_deregister(&hub_driver);
5954 } /* usb_hub_cleanup() */
5955 
5956 /**
5957  * usb_reset_and_verify_device - perform a USB port reset to reinitialize a device
5958  * @udev: device to reset (not in SUSPENDED or NOTATTACHED state)
5959  *
5960  * WARNING - don't use this routine to reset a composite device
5961  * (one with multiple interfaces owned by separate drivers)!
5962  * Use usb_reset_device() instead.
5963  *
5964  * Do a port reset, reassign the device's address, and establish its
5965  * former operating configuration.  If the reset fails, or the device's
5966  * descriptors change from their values before the reset, or the original
5967  * configuration and altsettings cannot be restored, a flag will be set
5968  * telling hub_wq to pretend the device has been disconnected and then
5969  * re-connected.  All drivers will be unbound, and the device will be
5970  * re-enumerated and probed all over again.
5971  *
5972  * Return: 0 if the reset succeeded, -ENODEV if the device has been
5973  * flagged for logical disconnection, or some other negative error code
5974  * if the reset wasn't even attempted.
5975  *
5976  * Note:
5977  * The caller must own the device lock and the port lock, the latter is
5978  * taken by usb_reset_device().  For example, it's safe to use
5979  * usb_reset_device() from a driver probe() routine after downloading
5980  * new firmware.  For calls that might not occur during probe(), drivers
5981  * should lock the device using usb_lock_device_for_reset().
5982  *
5983  * Locking exception: This routine may also be called from within an
5984  * autoresume handler.  Such usage won't conflict with other tasks
5985  * holding the device lock because these tasks should always call
5986  * usb_autopm_resume_device(), thereby preventing any unwanted
5987  * autoresume.  The autoresume handler is expected to have already
5988  * acquired the port lock before calling this routine.
5989  */
5990 static int usb_reset_and_verify_device(struct usb_device *udev)
5991 {
5992 	struct usb_device		*parent_hdev = udev->parent;
5993 	struct usb_hub			*parent_hub;
5994 	struct usb_hcd			*hcd = bus_to_hcd(udev->bus);
5995 	struct usb_device_descriptor	descriptor;
5996 	struct usb_host_bos		*bos;
5997 	int				i, j, ret = 0;
5998 	int				port1 = udev->portnum;
5999 
6000 	if (udev->state == USB_STATE_NOTATTACHED ||
6001 			udev->state == USB_STATE_SUSPENDED) {
6002 		dev_dbg(&udev->dev, "device reset not allowed in state %d\n",
6003 				udev->state);
6004 		return -EINVAL;
6005 	}
6006 
6007 	if (!parent_hdev)
6008 		return -EISDIR;
6009 
6010 	parent_hub = usb_hub_to_struct_hub(parent_hdev);
6011 
6012 	/* Disable USB2 hardware LPM.
6013 	 * It will be re-enabled by the enumeration process.
6014 	 */
6015 	usb_disable_usb2_hardware_lpm(udev);
6016 
6017 	bos = udev->bos;
6018 	udev->bos = NULL;
6019 
6020 	mutex_lock(hcd->address0_mutex);
6021 
6022 	for (i = 0; i < PORT_INIT_TRIES; ++i) {
6023 		if (hub_port_stop_enumerate(parent_hub, port1, i)) {
6024 			ret = -ENODEV;
6025 			break;
6026 		}
6027 
6028 		/* ep0 maxpacket size may change; let the HCD know about it.
6029 		 * Other endpoints will be handled by re-enumeration. */
6030 		usb_ep0_reinit(udev);
6031 		ret = hub_port_init(parent_hub, udev, port1, i, &descriptor);
6032 		if (ret >= 0 || ret == -ENOTCONN || ret == -ENODEV)
6033 			break;
6034 	}
6035 	mutex_unlock(hcd->address0_mutex);
6036 
6037 	if (ret < 0)
6038 		goto re_enumerate;
6039 
6040 	/* Device might have changed firmware (DFU or similar) */
6041 	if (descriptors_changed(udev, &descriptor, bos)) {
6042 		dev_info(&udev->dev, "device firmware changed\n");
6043 		goto re_enumerate;
6044 	}
6045 
6046 	/* Restore the device's previous configuration */
6047 	if (!udev->actconfig)
6048 		goto done;
6049 
6050 	mutex_lock(hcd->bandwidth_mutex);
6051 	ret = usb_hcd_alloc_bandwidth(udev, udev->actconfig, NULL, NULL);
6052 	if (ret < 0) {
6053 		dev_warn(&udev->dev,
6054 				"Busted HC?  Not enough HCD resources for "
6055 				"old configuration.\n");
6056 		mutex_unlock(hcd->bandwidth_mutex);
6057 		goto re_enumerate;
6058 	}
6059 	ret = usb_control_msg(udev, usb_sndctrlpipe(udev, 0),
6060 			USB_REQ_SET_CONFIGURATION, 0,
6061 			udev->actconfig->desc.bConfigurationValue, 0,
6062 			NULL, 0, USB_CTRL_SET_TIMEOUT);
6063 	if (ret < 0) {
6064 		dev_err(&udev->dev,
6065 			"can't restore configuration #%d (error=%d)\n",
6066 			udev->actconfig->desc.bConfigurationValue, ret);
6067 		mutex_unlock(hcd->bandwidth_mutex);
6068 		goto re_enumerate;
6069 	}
6070 	mutex_unlock(hcd->bandwidth_mutex);
6071 	usb_set_device_state(udev, USB_STATE_CONFIGURED);
6072 
6073 	/* Put interfaces back into the same altsettings as before.
6074 	 * Don't bother to send the Set-Interface request for interfaces
6075 	 * that were already in altsetting 0; besides being unnecessary,
6076 	 * many devices can't handle it.  Instead just reset the host-side
6077 	 * endpoint state.
6078 	 */
6079 	for (i = 0; i < udev->actconfig->desc.bNumInterfaces; i++) {
6080 		struct usb_host_config *config = udev->actconfig;
6081 		struct usb_interface *intf = config->interface[i];
6082 		struct usb_interface_descriptor *desc;
6083 
6084 		desc = &intf->cur_altsetting->desc;
6085 		if (desc->bAlternateSetting == 0) {
6086 			usb_disable_interface(udev, intf, true);
6087 			usb_enable_interface(udev, intf, true);
6088 			ret = 0;
6089 		} else {
6090 			/* Let the bandwidth allocation function know that this
6091 			 * device has been reset, and it will have to use
6092 			 * alternate setting 0 as the current alternate setting.
6093 			 */
6094 			intf->resetting_device = 1;
6095 			ret = usb_set_interface(udev, desc->bInterfaceNumber,
6096 					desc->bAlternateSetting);
6097 			intf->resetting_device = 0;
6098 		}
6099 		if (ret < 0) {
6100 			dev_err(&udev->dev, "failed to restore interface %d "
6101 				"altsetting %d (error=%d)\n",
6102 				desc->bInterfaceNumber,
6103 				desc->bAlternateSetting,
6104 				ret);
6105 			goto re_enumerate;
6106 		}
6107 		/* Resetting also frees any allocated streams */
6108 		for (j = 0; j < intf->cur_altsetting->desc.bNumEndpoints; j++)
6109 			intf->cur_altsetting->endpoint[j].streams = 0;
6110 	}
6111 
6112 done:
6113 	/* Now that the alt settings are re-installed, enable LTM and LPM. */
6114 	usb_enable_usb2_hardware_lpm(udev);
6115 	usb_unlocked_enable_lpm(udev);
6116 	usb_enable_ltm(udev);
6117 	usb_release_bos_descriptor(udev);
6118 	udev->bos = bos;
6119 	return 0;
6120 
6121 re_enumerate:
6122 	usb_release_bos_descriptor(udev);
6123 	udev->bos = bos;
6124 	hub_port_logical_disconnect(parent_hub, port1);
6125 	return -ENODEV;
6126 }
6127 
6128 /**
6129  * usb_reset_device - warn interface drivers and perform a USB port reset
6130  * @udev: device to reset (not in NOTATTACHED state)
6131  *
6132  * Warns all drivers bound to registered interfaces (using their pre_reset
6133  * method), performs the port reset, and then lets the drivers know that
6134  * the reset is over (using their post_reset method).
6135  *
6136  * Return: The same as for usb_reset_and_verify_device().
6137  * However, if a reset is already in progress (for instance, if a
6138  * driver doesn't have pre_reset() or post_reset() callbacks, and while
6139  * being unbound or re-bound during the ongoing reset its disconnect()
6140  * or probe() routine tries to perform a second, nested reset), the
6141  * routine returns -EINPROGRESS.
6142  *
6143  * Note:
6144  * The caller must own the device lock.  For example, it's safe to use
6145  * this from a driver probe() routine after downloading new firmware.
6146  * For calls that might not occur during probe(), drivers should lock
6147  * the device using usb_lock_device_for_reset().
6148  *
6149  * If an interface is currently being probed or disconnected, we assume
6150  * its driver knows how to handle resets.  For all other interfaces,
6151  * if the driver doesn't have pre_reset and post_reset methods then
6152  * we attempt to unbind it and rebind afterward.
6153  */
6154 int usb_reset_device(struct usb_device *udev)
6155 {
6156 	int ret;
6157 	int i;
6158 	unsigned int noio_flag;
6159 	struct usb_port *port_dev;
6160 	struct usb_host_config *config = udev->actconfig;
6161 	struct usb_hub *hub = usb_hub_to_struct_hub(udev->parent);
6162 
6163 	if (udev->state == USB_STATE_NOTATTACHED) {
6164 		dev_dbg(&udev->dev, "device reset not allowed in state %d\n",
6165 				udev->state);
6166 		return -EINVAL;
6167 	}
6168 
6169 	if (!udev->parent) {
6170 		/* this requires hcd-specific logic; see ohci_restart() */
6171 		dev_dbg(&udev->dev, "%s for root hub!\n", __func__);
6172 		return -EISDIR;
6173 	}
6174 
6175 	if (udev->reset_in_progress)
6176 		return -EINPROGRESS;
6177 	udev->reset_in_progress = 1;
6178 
6179 	port_dev = hub->ports[udev->portnum - 1];
6180 
6181 	/*
6182 	 * Don't allocate memory with GFP_KERNEL in current
6183 	 * context to avoid possible deadlock if usb mass
6184 	 * storage interface or usbnet interface(iSCSI case)
6185 	 * is included in current configuration. The easist
6186 	 * approach is to do it for every device reset,
6187 	 * because the device 'memalloc_noio' flag may have
6188 	 * not been set before reseting the usb device.
6189 	 */
6190 	noio_flag = memalloc_noio_save();
6191 
6192 	/* Prevent autosuspend during the reset */
6193 	usb_autoresume_device(udev);
6194 
6195 	if (config) {
6196 		for (i = 0; i < config->desc.bNumInterfaces; ++i) {
6197 			struct usb_interface *cintf = config->interface[i];
6198 			struct usb_driver *drv;
6199 			int unbind = 0;
6200 
6201 			if (cintf->dev.driver) {
6202 				drv = to_usb_driver(cintf->dev.driver);
6203 				if (drv->pre_reset && drv->post_reset)
6204 					unbind = (drv->pre_reset)(cintf);
6205 				else if (cintf->condition ==
6206 						USB_INTERFACE_BOUND)
6207 					unbind = 1;
6208 				if (unbind)
6209 					usb_forced_unbind_intf(cintf);
6210 			}
6211 		}
6212 	}
6213 
6214 	usb_lock_port(port_dev);
6215 	ret = usb_reset_and_verify_device(udev);
6216 	usb_unlock_port(port_dev);
6217 
6218 	if (config) {
6219 		for (i = config->desc.bNumInterfaces - 1; i >= 0; --i) {
6220 			struct usb_interface *cintf = config->interface[i];
6221 			struct usb_driver *drv;
6222 			int rebind = cintf->needs_binding;
6223 
6224 			if (!rebind && cintf->dev.driver) {
6225 				drv = to_usb_driver(cintf->dev.driver);
6226 				if (drv->post_reset)
6227 					rebind = (drv->post_reset)(cintf);
6228 				else if (cintf->condition ==
6229 						USB_INTERFACE_BOUND)
6230 					rebind = 1;
6231 				if (rebind)
6232 					cintf->needs_binding = 1;
6233 			}
6234 		}
6235 
6236 		/* If the reset failed, hub_wq will unbind drivers later */
6237 		if (ret == 0)
6238 			usb_unbind_and_rebind_marked_interfaces(udev);
6239 	}
6240 
6241 	usb_autosuspend_device(udev);
6242 	memalloc_noio_restore(noio_flag);
6243 	udev->reset_in_progress = 0;
6244 	return ret;
6245 }
6246 EXPORT_SYMBOL_GPL(usb_reset_device);
6247 
6248 
6249 /**
6250  * usb_queue_reset_device - Reset a USB device from an atomic context
6251  * @iface: USB interface belonging to the device to reset
6252  *
6253  * This function can be used to reset a USB device from an atomic
6254  * context, where usb_reset_device() won't work (as it blocks).
6255  *
6256  * Doing a reset via this method is functionally equivalent to calling
6257  * usb_reset_device(), except for the fact that it is delayed to a
6258  * workqueue. This means that any drivers bound to other interfaces
6259  * might be unbound, as well as users from usbfs in user space.
6260  *
6261  * Corner cases:
6262  *
6263  * - Scheduling two resets at the same time from two different drivers
6264  *   attached to two different interfaces of the same device is
6265  *   possible; depending on how the driver attached to each interface
6266  *   handles ->pre_reset(), the second reset might happen or not.
6267  *
6268  * - If the reset is delayed so long that the interface is unbound from
6269  *   its driver, the reset will be skipped.
6270  *
6271  * - This function can be called during .probe().  It can also be called
6272  *   during .disconnect(), but doing so is pointless because the reset
6273  *   will not occur.  If you really want to reset the device during
6274  *   .disconnect(), call usb_reset_device() directly -- but watch out
6275  *   for nested unbinding issues!
6276  */
6277 void usb_queue_reset_device(struct usb_interface *iface)
6278 {
6279 	if (schedule_work(&iface->reset_ws))
6280 		usb_get_intf(iface);
6281 }
6282 EXPORT_SYMBOL_GPL(usb_queue_reset_device);
6283 
6284 /**
6285  * usb_hub_find_child - Get the pointer of child device
6286  * attached to the port which is specified by @port1.
6287  * @hdev: USB device belonging to the usb hub
6288  * @port1: port num to indicate which port the child device
6289  *	is attached to.
6290  *
6291  * USB drivers call this function to get hub's child device
6292  * pointer.
6293  *
6294  * Return: %NULL if input param is invalid and
6295  * child's usb_device pointer if non-NULL.
6296  */
6297 struct usb_device *usb_hub_find_child(struct usb_device *hdev,
6298 		int port1)
6299 {
6300 	struct usb_hub *hub = usb_hub_to_struct_hub(hdev);
6301 
6302 	if (port1 < 1 || port1 > hdev->maxchild)
6303 		return NULL;
6304 	return hub->ports[port1 - 1]->child;
6305 }
6306 EXPORT_SYMBOL_GPL(usb_hub_find_child);
6307 
6308 void usb_hub_adjust_deviceremovable(struct usb_device *hdev,
6309 		struct usb_hub_descriptor *desc)
6310 {
6311 	struct usb_hub *hub = usb_hub_to_struct_hub(hdev);
6312 	enum usb_port_connect_type connect_type;
6313 	int i;
6314 
6315 	if (!hub)
6316 		return;
6317 
6318 	if (!hub_is_superspeed(hdev)) {
6319 		for (i = 1; i <= hdev->maxchild; i++) {
6320 			struct usb_port *port_dev = hub->ports[i - 1];
6321 
6322 			connect_type = port_dev->connect_type;
6323 			if (connect_type == USB_PORT_CONNECT_TYPE_HARD_WIRED) {
6324 				u8 mask = 1 << (i%8);
6325 
6326 				if (!(desc->u.hs.DeviceRemovable[i/8] & mask)) {
6327 					dev_dbg(&port_dev->dev, "DeviceRemovable is changed to 1 according to platform information.\n");
6328 					desc->u.hs.DeviceRemovable[i/8]	|= mask;
6329 				}
6330 			}
6331 		}
6332 	} else {
6333 		u16 port_removable = le16_to_cpu(desc->u.ss.DeviceRemovable);
6334 
6335 		for (i = 1; i <= hdev->maxchild; i++) {
6336 			struct usb_port *port_dev = hub->ports[i - 1];
6337 
6338 			connect_type = port_dev->connect_type;
6339 			if (connect_type == USB_PORT_CONNECT_TYPE_HARD_WIRED) {
6340 				u16 mask = 1 << i;
6341 
6342 				if (!(port_removable & mask)) {
6343 					dev_dbg(&port_dev->dev, "DeviceRemovable is changed to 1 according to platform information.\n");
6344 					port_removable |= mask;
6345 				}
6346 			}
6347 		}
6348 
6349 		desc->u.ss.DeviceRemovable = cpu_to_le16(port_removable);
6350 	}
6351 }
6352 
6353 #ifdef CONFIG_ACPI
6354 /**
6355  * usb_get_hub_port_acpi_handle - Get the usb port's acpi handle
6356  * @hdev: USB device belonging to the usb hub
6357  * @port1: port num of the port
6358  *
6359  * Return: Port's acpi handle if successful, %NULL if params are
6360  * invalid.
6361  */
6362 acpi_handle usb_get_hub_port_acpi_handle(struct usb_device *hdev,
6363 	int port1)
6364 {
6365 	struct usb_hub *hub = usb_hub_to_struct_hub(hdev);
6366 
6367 	if (!hub)
6368 		return NULL;
6369 
6370 	return ACPI_HANDLE(&hub->ports[port1 - 1]->dev);
6371 }
6372 #endif
6373