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