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