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