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