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