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