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