xref: /openbmc/linux/drivers/usb/core/hub.c (revision 6396bb22)
1aa1f3bb5SGreg Kroah-Hartman // SPDX-License-Identifier: GPL-2.0
21da177e4SLinus Torvalds /*
31da177e4SLinus Torvalds  * USB hub driver.
41da177e4SLinus Torvalds  *
51da177e4SLinus Torvalds  * (C) Copyright 1999 Linus Torvalds
61da177e4SLinus Torvalds  * (C) Copyright 1999 Johannes Erdfelt
71da177e4SLinus Torvalds  * (C) Copyright 1999 Gregory P. Smith
81da177e4SLinus Torvalds  * (C) Copyright 2001 Brad Hards (bhards@bigpond.net.au)
91da177e4SLinus Torvalds  *
10b65fba3dSGreg Kroah-Hartman  * Released under the GPLv2 only.
111da177e4SLinus Torvalds  */
121da177e4SLinus Torvalds 
131da177e4SLinus Torvalds #include <linux/kernel.h>
141da177e4SLinus Torvalds #include <linux/errno.h>
151da177e4SLinus Torvalds #include <linux/module.h>
161da177e4SLinus Torvalds #include <linux/moduleparam.h>
171da177e4SLinus Torvalds #include <linux/completion.h>
185b3cc15aSIngo Molnar #include <linux/sched/mm.h>
191da177e4SLinus Torvalds #include <linux/list.h>
201da177e4SLinus Torvalds #include <linux/slab.h>
211da177e4SLinus Torvalds #include <linux/ioctl.h>
221da177e4SLinus Torvalds #include <linux/usb.h>
231da177e4SLinus Torvalds #include <linux/usbdevice_fs.h>
2427729aadSEric Lescouet #include <linux/usb/hcd.h>
25925aa46bSRichard Zhao #include <linux/usb/otg.h>
2693362a87SPhil Dibowitz #include <linux/usb/quirks.h>
2732a69589SPetr Mladek #include <linux/workqueue.h>
284186ecf8SArjan van de Ven #include <linux/mutex.h>
29b04b3156STheodore Ts'o #include <linux/random.h>
30ad493e5eSLan Tianyu #include <linux/pm_qos.h>
311da177e4SLinus Torvalds 
327c0f6ba6SLinus Torvalds #include <linux/uaccess.h>
331da177e4SLinus Torvalds #include <asm/byteorder.h>
341da177e4SLinus Torvalds 
356e30d7cbSLan Tianyu #include "hub.h"
36026f3fcbSPeter Chen #include "otg_whitelist.h"
371da177e4SLinus Torvalds 
38e6f30deaSMing Lei #define USB_VENDOR_GENESYS_LOGIC		0x05e3
39e6f30deaSMing Lei #define HUB_QUIRK_CHECK_PORT_AUTOSUSPEND	0x01
40e6f30deaSMing Lei 
41886ee36eSFelipe Balbi #define USB_TP_TRANSMISSION_DELAY	40	/* ns */
42886ee36eSFelipe Balbi #define USB_TP_TRANSMISSION_DELAY_MAX	65535	/* ns */
43886ee36eSFelipe Balbi 
44fa286188SGreg Kroah-Hartman /* Protect struct usb_device->state and ->children members
459ad3d6ccSAlan Stern  * Note: Both are also protected by ->dev.sem, except that ->state can
461da177e4SLinus Torvalds  * change to USB_STATE_NOTATTACHED even when the semaphore isn't held. */
471da177e4SLinus Torvalds static DEFINE_SPINLOCK(device_state_lock);
481da177e4SLinus Torvalds 
4932a69589SPetr Mladek /* workqueue to process hub events */
5032a69589SPetr Mladek static struct workqueue_struct *hub_wq;
5132a69589SPetr Mladek static void hub_event(struct work_struct *work);
521da177e4SLinus Torvalds 
53d8521afeSDan Williams /* synchronize hub-port add/remove and peering operations */
54d8521afeSDan Williams DEFINE_MUTEX(usb_port_peer_mutex);
55d8521afeSDan Williams 
561da177e4SLinus Torvalds /* cycle leds on hubs that aren't blinking for attention */
57a44007a4SSaurabh Sengar static bool blinkenlights;
581da177e4SLinus Torvalds module_param(blinkenlights, bool, S_IRUGO);
591da177e4SLinus Torvalds MODULE_PARM_DESC(blinkenlights, "true to cycle leds on hubs");
601da177e4SLinus Torvalds 
611da177e4SLinus Torvalds /*
62fd7c519dSJaroslav Kysela  * Device SATA8000 FW1.0 from DATAST0R Technology Corp requires about
63fd7c519dSJaroslav Kysela  * 10 seconds to send reply for the initial 64-byte descriptor request.
64fd7c519dSJaroslav Kysela  */
65fd7c519dSJaroslav Kysela /* define initial 64-byte descriptor request timeout in milliseconds */
66fd7c519dSJaroslav Kysela static int initial_descriptor_timeout = USB_CTRL_GET_TIMEOUT;
67fd7c519dSJaroslav Kysela module_param(initial_descriptor_timeout, int, S_IRUGO|S_IWUSR);
68b9cef6c3SWu Fengguang MODULE_PARM_DESC(initial_descriptor_timeout,
69b9cef6c3SWu Fengguang 		"initial 64-byte descriptor request timeout in milliseconds "
70b9cef6c3SWu Fengguang 		"(default 5000 - 5.0 seconds)");
71fd7c519dSJaroslav Kysela 
72fd7c519dSJaroslav Kysela /*
731da177e4SLinus Torvalds  * As of 2.6.10 we introduce a new USB device initialization scheme which
741da177e4SLinus Torvalds  * closely resembles the way Windows works.  Hopefully it will be compatible
751da177e4SLinus Torvalds  * with a wider range of devices than the old scheme.  However some previously
761da177e4SLinus Torvalds  * working devices may start giving rise to "device not accepting address"
771da177e4SLinus Torvalds  * errors; if that happens the user can try the old scheme by adjusting the
781da177e4SLinus Torvalds  * following module parameters.
791da177e4SLinus Torvalds  *
801da177e4SLinus Torvalds  * For maximum flexibility there are two boolean parameters to control the
811da177e4SLinus Torvalds  * hub driver's behavior.  On the first initialization attempt, if the
821da177e4SLinus Torvalds  * "old_scheme_first" parameter is set then the old scheme will be used,
831da177e4SLinus Torvalds  * otherwise the new scheme is used.  If that fails and "use_both_schemes"
841da177e4SLinus Torvalds  * is set, then the driver will make another attempt, using the other scheme.
851da177e4SLinus Torvalds  */
86a44007a4SSaurabh Sengar static bool old_scheme_first;
871da177e4SLinus Torvalds module_param(old_scheme_first, bool, S_IRUGO | S_IWUSR);
881da177e4SLinus Torvalds MODULE_PARM_DESC(old_scheme_first,
891da177e4SLinus Torvalds 		 "start with the old device initialization scheme");
901da177e4SLinus Torvalds 
9190ab5ee9SRusty Russell static bool use_both_schemes = 1;
921da177e4SLinus Torvalds module_param(use_both_schemes, bool, S_IRUGO | S_IWUSR);
931da177e4SLinus Torvalds MODULE_PARM_DESC(use_both_schemes,
941da177e4SLinus Torvalds 		"try the other device initialization scheme if the "
951da177e4SLinus Torvalds 		"first one fails");
961da177e4SLinus Torvalds 
9732fe0198SAlan Stern /* Mutual exclusion for EHCI CF initialization.  This interferes with
9832fe0198SAlan Stern  * port reset on some companion controllers.
9932fe0198SAlan Stern  */
10032fe0198SAlan Stern DECLARE_RWSEM(ehci_cf_port_reset_rwsem);
10132fe0198SAlan Stern EXPORT_SYMBOL_GPL(ehci_cf_port_reset_rwsem);
10232fe0198SAlan Stern 
103ad493e5eSLan Tianyu #define HUB_DEBOUNCE_TIMEOUT	2000
104948fea37SAlan Stern #define HUB_DEBOUNCE_STEP	  25
105948fea37SAlan Stern #define HUB_DEBOUNCE_STABLE	 100
106948fea37SAlan Stern 
10732a69589SPetr Mladek static void hub_release(struct kref *kref);
108742120c6SMing Lei static int usb_reset_and_verify_device(struct usb_device *udev);
1093bc02bceSGeert Uytterhoeven static int hub_port_disable(struct usb_hub *hub, int port1, int set_state);
110742120c6SMing Lei 
111131dec34SSarah Sharp static inline char *portspeed(struct usb_hub *hub, int portstatus)
1121da177e4SLinus Torvalds {
113d64aab0cSOliver Neukum 	if (hub_is_superspeedplus(hub->hdev))
114d64aab0cSOliver Neukum 		return "10.0 Gb/s";
115131dec34SSarah Sharp 	if (hub_is_superspeed(hub->hdev))
116131dec34SSarah Sharp 		return "5.0 Gb/s";
117288ead45SAlan Stern 	if (portstatus & USB_PORT_STAT_HIGH_SPEED)
1181da177e4SLinus Torvalds 		return "480 Mb/s";
119288ead45SAlan Stern 	else if (portstatus & USB_PORT_STAT_LOW_SPEED)
1201da177e4SLinus Torvalds 		return "1.5 Mb/s";
1211da177e4SLinus Torvalds 	else
1221da177e4SLinus Torvalds 		return "12 Mb/s";
1231da177e4SLinus Torvalds }
1241da177e4SLinus Torvalds 
1251da177e4SLinus Torvalds /* Note that hdev or one of its children must be locked! */
126ad493e5eSLan Tianyu struct usb_hub *usb_hub_to_struct_hub(struct usb_device *hdev)
1271da177e4SLinus Torvalds {
128ff823c79SLan Tianyu 	if (!hdev || !hdev->actconfig || !hdev->maxchild)
12925118084SAlan Stern 		return NULL;
1301da177e4SLinus Torvalds 	return usb_get_intfdata(hdev->actconfig->interface[0]);
1311da177e4SLinus Torvalds }
1321da177e4SLinus Torvalds 
1332d2a3167SLu Baolu int usb_device_supports_lpm(struct usb_device *udev)
134d9b2099cSSarah Sharp {
135ad87e032SAlan Stern 	/* Some devices have trouble with LPM */
136ad87e032SAlan Stern 	if (udev->quirks & USB_QUIRK_NO_LPM)
137ad87e032SAlan Stern 		return 0;
138ad87e032SAlan Stern 
139d9b2099cSSarah Sharp 	/* USB 2.1 (and greater) devices indicate LPM support through
140d9b2099cSSarah Sharp 	 * their USB 2.0 Extended Capabilities BOS descriptor.
141d9b2099cSSarah Sharp 	 */
142a8425292SRupesh Tatiya 	if (udev->speed == USB_SPEED_HIGH || udev->speed == USB_SPEED_FULL) {
143d9b2099cSSarah Sharp 		if (udev->bos->ext_cap &&
144d9b2099cSSarah Sharp 			(USB_LPM_SUPPORT &
145d9b2099cSSarah Sharp 			 le32_to_cpu(udev->bos->ext_cap->bmAttributes)))
146d9b2099cSSarah Sharp 			return 1;
147d9b2099cSSarah Sharp 		return 0;
148d9b2099cSSarah Sharp 	}
14951e0a012SSarah Sharp 
15025cd2882SSarah Sharp 	/*
15125cd2882SSarah Sharp 	 * According to the USB 3.0 spec, all USB 3.0 devices must support LPM.
15225cd2882SSarah Sharp 	 * However, there are some that don't, and they set the U1/U2 exit
15325cd2882SSarah Sharp 	 * latencies to zero.
15451e0a012SSarah Sharp 	 */
15551e0a012SSarah Sharp 	if (!udev->bos->ss_cap) {
15625cd2882SSarah Sharp 		dev_info(&udev->dev, "No LPM exit latency info found, disabling LPM.\n");
157d9b2099cSSarah Sharp 		return 0;
158d9b2099cSSarah Sharp 	}
15951e0a012SSarah Sharp 
16025cd2882SSarah Sharp 	if (udev->bos->ss_cap->bU1devExitLat == 0 &&
16125cd2882SSarah Sharp 			udev->bos->ss_cap->bU2DevExitLat == 0) {
16225cd2882SSarah Sharp 		if (udev->parent)
16325cd2882SSarah Sharp 			dev_info(&udev->dev, "LPM exit latency is zeroed, disabling LPM.\n");
16425cd2882SSarah Sharp 		else
16525cd2882SSarah Sharp 			dev_info(&udev->dev, "We don't know the algorithms for LPM for this host, disabling LPM.\n");
16625cd2882SSarah Sharp 		return 0;
16725cd2882SSarah Sharp 	}
16825cd2882SSarah Sharp 
16925cd2882SSarah Sharp 	if (!udev->parent || udev->parent->lpm_capable)
17025cd2882SSarah Sharp 		return 1;
17151e0a012SSarah Sharp 	return 0;
17251e0a012SSarah Sharp }
17351e0a012SSarah Sharp 
17451e0a012SSarah Sharp /*
17551e0a012SSarah Sharp  * Set the Maximum Exit Latency (MEL) for the host to initiate a transition from
17651e0a012SSarah Sharp  * either U1 or U2.
17751e0a012SSarah Sharp  */
17851e0a012SSarah Sharp static void usb_set_lpm_mel(struct usb_device *udev,
17951e0a012SSarah Sharp 		struct usb3_lpm_parameters *udev_lpm_params,
18051e0a012SSarah Sharp 		unsigned int udev_exit_latency,
18151e0a012SSarah Sharp 		struct usb_hub *hub,
18251e0a012SSarah Sharp 		struct usb3_lpm_parameters *hub_lpm_params,
18351e0a012SSarah Sharp 		unsigned int hub_exit_latency)
18451e0a012SSarah Sharp {
18551e0a012SSarah Sharp 	unsigned int total_mel;
18651e0a012SSarah Sharp 	unsigned int device_mel;
18751e0a012SSarah Sharp 	unsigned int hub_mel;
18851e0a012SSarah Sharp 
18951e0a012SSarah Sharp 	/*
19051e0a012SSarah Sharp 	 * Calculate the time it takes to transition all links from the roothub
19151e0a012SSarah Sharp 	 * to the parent hub into U0.  The parent hub must then decode the
19251e0a012SSarah Sharp 	 * packet (hub header decode latency) to figure out which port it was
19351e0a012SSarah Sharp 	 * bound for.
19451e0a012SSarah Sharp 	 *
19551e0a012SSarah Sharp 	 * The Hub Header decode latency is expressed in 0.1us intervals (0x1
19651e0a012SSarah Sharp 	 * means 0.1us).  Multiply that by 100 to get nanoseconds.
19751e0a012SSarah Sharp 	 */
19851e0a012SSarah Sharp 	total_mel = hub_lpm_params->mel +
19951e0a012SSarah Sharp 		(hub->descriptor->u.ss.bHubHdrDecLat * 100);
20051e0a012SSarah Sharp 
20151e0a012SSarah Sharp 	/*
20251e0a012SSarah Sharp 	 * How long will it take to transition the downstream hub's port into
20351e0a012SSarah Sharp 	 * U0?  The greater of either the hub exit latency or the device exit
20451e0a012SSarah Sharp 	 * latency.
20551e0a012SSarah Sharp 	 *
20651e0a012SSarah Sharp 	 * The BOS U1/U2 exit latencies are expressed in 1us intervals.
20751e0a012SSarah Sharp 	 * Multiply that by 1000 to get nanoseconds.
20851e0a012SSarah Sharp 	 */
20951e0a012SSarah Sharp 	device_mel = udev_exit_latency * 1000;
21051e0a012SSarah Sharp 	hub_mel = hub_exit_latency * 1000;
21151e0a012SSarah Sharp 	if (device_mel > hub_mel)
21251e0a012SSarah Sharp 		total_mel += device_mel;
21351e0a012SSarah Sharp 	else
21451e0a012SSarah Sharp 		total_mel += hub_mel;
21551e0a012SSarah Sharp 
21651e0a012SSarah Sharp 	udev_lpm_params->mel = total_mel;
21751e0a012SSarah Sharp }
21851e0a012SSarah Sharp 
21951e0a012SSarah Sharp /*
22051e0a012SSarah Sharp  * Set the maximum Device to Host Exit Latency (PEL) for the device to initiate
22151e0a012SSarah Sharp  * a transition from either U1 or U2.
22251e0a012SSarah Sharp  */
22351e0a012SSarah Sharp static void usb_set_lpm_pel(struct usb_device *udev,
22451e0a012SSarah Sharp 		struct usb3_lpm_parameters *udev_lpm_params,
22551e0a012SSarah Sharp 		unsigned int udev_exit_latency,
22651e0a012SSarah Sharp 		struct usb_hub *hub,
22751e0a012SSarah Sharp 		struct usb3_lpm_parameters *hub_lpm_params,
22851e0a012SSarah Sharp 		unsigned int hub_exit_latency,
22951e0a012SSarah Sharp 		unsigned int port_to_port_exit_latency)
23051e0a012SSarah Sharp {
23151e0a012SSarah Sharp 	unsigned int first_link_pel;
23251e0a012SSarah Sharp 	unsigned int hub_pel;
23351e0a012SSarah Sharp 
23451e0a012SSarah Sharp 	/*
23551e0a012SSarah Sharp 	 * First, the device sends an LFPS to transition the link between the
23651e0a012SSarah Sharp 	 * device and the parent hub into U0.  The exit latency is the bigger of
23751e0a012SSarah Sharp 	 * the device exit latency or the hub exit latency.
23851e0a012SSarah Sharp 	 */
23951e0a012SSarah Sharp 	if (udev_exit_latency > hub_exit_latency)
24051e0a012SSarah Sharp 		first_link_pel = udev_exit_latency * 1000;
24151e0a012SSarah Sharp 	else
24251e0a012SSarah Sharp 		first_link_pel = hub_exit_latency * 1000;
24351e0a012SSarah Sharp 
24451e0a012SSarah Sharp 	/*
24551e0a012SSarah Sharp 	 * When the hub starts to receive the LFPS, there is a slight delay for
24651e0a012SSarah Sharp 	 * it to figure out that one of the ports is sending an LFPS.  Then it
24751e0a012SSarah Sharp 	 * will forward the LFPS to its upstream link.  The exit latency is the
24851e0a012SSarah Sharp 	 * delay, plus the PEL that we calculated for this hub.
24951e0a012SSarah Sharp 	 */
25051e0a012SSarah Sharp 	hub_pel = port_to_port_exit_latency * 1000 + hub_lpm_params->pel;
25151e0a012SSarah Sharp 
25251e0a012SSarah Sharp 	/*
25351e0a012SSarah Sharp 	 * According to figure C-7 in the USB 3.0 spec, the PEL for this device
25451e0a012SSarah Sharp 	 * is the greater of the two exit latencies.
25551e0a012SSarah Sharp 	 */
25651e0a012SSarah Sharp 	if (first_link_pel > hub_pel)
25751e0a012SSarah Sharp 		udev_lpm_params->pel = first_link_pel;
25851e0a012SSarah Sharp 	else
25951e0a012SSarah Sharp 		udev_lpm_params->pel = hub_pel;
26051e0a012SSarah Sharp }
26151e0a012SSarah Sharp 
26251e0a012SSarah Sharp /*
26351e0a012SSarah Sharp  * Set the System Exit Latency (SEL) to indicate the total worst-case time from
26451e0a012SSarah Sharp  * when a device initiates a transition to U0, until when it will receive the
26551e0a012SSarah Sharp  * first packet from the host controller.
26651e0a012SSarah Sharp  *
26751e0a012SSarah Sharp  * Section C.1.5.1 describes the four components to this:
26851e0a012SSarah Sharp  *  - t1: device PEL
26951e0a012SSarah Sharp  *  - t2: time for the ERDY to make it from the device to the host.
27051e0a012SSarah Sharp  *  - t3: a host-specific delay to process the ERDY.
27151e0a012SSarah Sharp  *  - t4: time for the packet to make it from the host to the device.
27251e0a012SSarah Sharp  *
27351e0a012SSarah Sharp  * t3 is specific to both the xHCI host and the platform the host is integrated
27451e0a012SSarah Sharp  * into.  The Intel HW folks have said it's negligible, FIXME if a different
27551e0a012SSarah Sharp  * vendor says otherwise.
27651e0a012SSarah Sharp  */
27751e0a012SSarah Sharp static void usb_set_lpm_sel(struct usb_device *udev,
27851e0a012SSarah Sharp 		struct usb3_lpm_parameters *udev_lpm_params)
27951e0a012SSarah Sharp {
28051e0a012SSarah Sharp 	struct usb_device *parent;
28151e0a012SSarah Sharp 	unsigned int num_hubs;
28251e0a012SSarah Sharp 	unsigned int total_sel;
28351e0a012SSarah Sharp 
28451e0a012SSarah Sharp 	/* t1 = device PEL */
28551e0a012SSarah Sharp 	total_sel = udev_lpm_params->pel;
28651e0a012SSarah Sharp 	/* How many external hubs are in between the device & the root port. */
28751e0a012SSarah Sharp 	for (parent = udev->parent, num_hubs = 0; parent->parent;
28851e0a012SSarah Sharp 			parent = parent->parent)
28951e0a012SSarah Sharp 		num_hubs++;
29051e0a012SSarah Sharp 	/* t2 = 2.1us + 250ns * (num_hubs - 1) */
29151e0a012SSarah Sharp 	if (num_hubs > 0)
29251e0a012SSarah Sharp 		total_sel += 2100 + 250 * (num_hubs - 1);
29351e0a012SSarah Sharp 
29451e0a012SSarah Sharp 	/* t4 = 250ns * num_hubs */
29551e0a012SSarah Sharp 	total_sel += 250 * num_hubs;
29651e0a012SSarah Sharp 
29751e0a012SSarah Sharp 	udev_lpm_params->sel = total_sel;
29851e0a012SSarah Sharp }
29951e0a012SSarah Sharp 
30051e0a012SSarah Sharp static void usb_set_lpm_parameters(struct usb_device *udev)
30151e0a012SSarah Sharp {
30251e0a012SSarah Sharp 	struct usb_hub *hub;
30351e0a012SSarah Sharp 	unsigned int port_to_port_delay;
30451e0a012SSarah Sharp 	unsigned int udev_u1_del;
30551e0a012SSarah Sharp 	unsigned int udev_u2_del;
30651e0a012SSarah Sharp 	unsigned int hub_u1_del;
30751e0a012SSarah Sharp 	unsigned int hub_u2_del;
30851e0a012SSarah Sharp 
3098a1b2725SMathias Nyman 	if (!udev->lpm_capable || udev->speed < USB_SPEED_SUPER)
31051e0a012SSarah Sharp 		return;
31151e0a012SSarah Sharp 
312ad493e5eSLan Tianyu 	hub = usb_hub_to_struct_hub(udev->parent);
31351e0a012SSarah Sharp 	/* It doesn't take time to transition the roothub into U0, since it
31451e0a012SSarah Sharp 	 * doesn't have an upstream link.
31551e0a012SSarah Sharp 	 */
31651e0a012SSarah Sharp 	if (!hub)
31751e0a012SSarah Sharp 		return;
31851e0a012SSarah Sharp 
31951e0a012SSarah Sharp 	udev_u1_del = udev->bos->ss_cap->bU1devExitLat;
3204d967995SXenia Ragiadakou 	udev_u2_del = le16_to_cpu(udev->bos->ss_cap->bU2DevExitLat);
32151e0a012SSarah Sharp 	hub_u1_del = udev->parent->bos->ss_cap->bU1devExitLat;
3224d967995SXenia Ragiadakou 	hub_u2_del = le16_to_cpu(udev->parent->bos->ss_cap->bU2DevExitLat);
32351e0a012SSarah Sharp 
32451e0a012SSarah Sharp 	usb_set_lpm_mel(udev, &udev->u1_params, udev_u1_del,
32551e0a012SSarah Sharp 			hub, &udev->parent->u1_params, hub_u1_del);
32651e0a012SSarah Sharp 
32751e0a012SSarah Sharp 	usb_set_lpm_mel(udev, &udev->u2_params, udev_u2_del,
32851e0a012SSarah Sharp 			hub, &udev->parent->u2_params, hub_u2_del);
32951e0a012SSarah Sharp 
33051e0a012SSarah Sharp 	/*
33151e0a012SSarah Sharp 	 * Appendix C, section C.2.2.2, says that there is a slight delay from
33251e0a012SSarah Sharp 	 * when the parent hub notices the downstream port is trying to
33351e0a012SSarah Sharp 	 * transition to U0 to when the hub initiates a U0 transition on its
33451e0a012SSarah Sharp 	 * upstream port.  The section says the delays are tPort2PortU1EL and
33551e0a012SSarah Sharp 	 * tPort2PortU2EL, but it doesn't define what they are.
33651e0a012SSarah Sharp 	 *
33751e0a012SSarah Sharp 	 * The hub chapter, sections 10.4.2.4 and 10.4.2.5 seem to be talking
33851e0a012SSarah Sharp 	 * about the same delays.  Use the maximum delay calculations from those
33951e0a012SSarah Sharp 	 * sections.  For U1, it's tHubPort2PortExitLat, which is 1us max.  For
34051e0a012SSarah Sharp 	 * U2, it's tHubPort2PortExitLat + U2DevExitLat - U1DevExitLat.  I
34151e0a012SSarah Sharp 	 * assume the device exit latencies they are talking about are the hub
34251e0a012SSarah Sharp 	 * exit latencies.
34351e0a012SSarah Sharp 	 *
34451e0a012SSarah Sharp 	 * What do we do if the U2 exit latency is less than the U1 exit
34551e0a012SSarah Sharp 	 * latency?  It's possible, although not likely...
34651e0a012SSarah Sharp 	 */
34751e0a012SSarah Sharp 	port_to_port_delay = 1;
34851e0a012SSarah Sharp 
34951e0a012SSarah Sharp 	usb_set_lpm_pel(udev, &udev->u1_params, udev_u1_del,
35051e0a012SSarah Sharp 			hub, &udev->parent->u1_params, hub_u1_del,
35151e0a012SSarah Sharp 			port_to_port_delay);
35251e0a012SSarah Sharp 
35351e0a012SSarah Sharp 	if (hub_u2_del > hub_u1_del)
35451e0a012SSarah Sharp 		port_to_port_delay = 1 + hub_u2_del - hub_u1_del;
35551e0a012SSarah Sharp 	else
35651e0a012SSarah Sharp 		port_to_port_delay = 1 + hub_u1_del;
35751e0a012SSarah Sharp 
35851e0a012SSarah Sharp 	usb_set_lpm_pel(udev, &udev->u2_params, udev_u2_del,
35951e0a012SSarah Sharp 			hub, &udev->parent->u2_params, hub_u2_del,
36051e0a012SSarah Sharp 			port_to_port_delay);
36151e0a012SSarah Sharp 
36251e0a012SSarah Sharp 	/* Now that we've got PEL, calculate SEL. */
36351e0a012SSarah Sharp 	usb_set_lpm_sel(udev, &udev->u1_params);
36451e0a012SSarah Sharp 	usb_set_lpm_sel(udev, &udev->u2_params);
36551e0a012SSarah Sharp }
366d9b2099cSSarah Sharp 
3671da177e4SLinus Torvalds /* USB 2.0 spec Section 11.24.4.5 */
368bec444cdSJohan Hovold static int get_hub_descriptor(struct usb_device *hdev,
369bec444cdSJohan Hovold 		struct usb_hub_descriptor *desc)
3701da177e4SLinus Torvalds {
371dbe79bbeSJohn Youn 	int i, ret, size;
372dbe79bbeSJohn Youn 	unsigned dtype;
373dbe79bbeSJohn Youn 
374dbe79bbeSJohn Youn 	if (hub_is_superspeed(hdev)) {
375dbe79bbeSJohn Youn 		dtype = USB_DT_SS_HUB;
376dbe79bbeSJohn Youn 		size = USB_DT_SS_HUB_SIZE;
377dbe79bbeSJohn Youn 	} else {
378dbe79bbeSJohn Youn 		dtype = USB_DT_HUB;
379dbe79bbeSJohn Youn 		size = sizeof(struct usb_hub_descriptor);
380dbe79bbeSJohn Youn 	}
3811da177e4SLinus Torvalds 
3821da177e4SLinus Torvalds 	for (i = 0; i < 3; i++) {
3831da177e4SLinus Torvalds 		ret = usb_control_msg(hdev, usb_rcvctrlpipe(hdev, 0),
3841da177e4SLinus Torvalds 			USB_REQ_GET_DESCRIPTOR, USB_DIR_IN | USB_RT_HUB,
385bec444cdSJohan Hovold 			dtype << 8, 0, desc, size,
3861da177e4SLinus Torvalds 			USB_CTRL_GET_TIMEOUT);
3872c25a2c8SJohan Hovold 		if (hub_is_superspeed(hdev)) {
3882c25a2c8SJohan Hovold 			if (ret == size)
3891da177e4SLinus Torvalds 				return ret;
390bec444cdSJohan Hovold 		} else if (ret >= USB_DT_HUB_NONVAR_SIZE + 2) {
391bec444cdSJohan Hovold 			/* Make sure we have the DeviceRemovable field. */
392bec444cdSJohan Hovold 			size = USB_DT_HUB_NONVAR_SIZE + desc->bNbrPorts / 8 + 1;
393bec444cdSJohan Hovold 			if (ret < size)
394bec444cdSJohan Hovold 				return -EMSGSIZE;
3952c25a2c8SJohan Hovold 			return ret;
3962c25a2c8SJohan Hovold 		}
3971da177e4SLinus Torvalds 	}
3981da177e4SLinus Torvalds 	return -EINVAL;
3991da177e4SLinus Torvalds }
4001da177e4SLinus Torvalds 
4011da177e4SLinus Torvalds /*
4021da177e4SLinus Torvalds  * USB 2.0 spec Section 11.24.2.1
4031da177e4SLinus Torvalds  */
4041da177e4SLinus Torvalds static int clear_hub_feature(struct usb_device *hdev, int feature)
4051da177e4SLinus Torvalds {
4061da177e4SLinus Torvalds 	return usb_control_msg(hdev, usb_sndctrlpipe(hdev, 0),
4071da177e4SLinus Torvalds 		USB_REQ_CLEAR_FEATURE, USB_RT_HUB, feature, 0, NULL, 0, 1000);
4081da177e4SLinus Torvalds }
4091da177e4SLinus Torvalds 
4101da177e4SLinus Torvalds /*
4111da177e4SLinus Torvalds  * USB 2.0 spec Section 11.24.2.2
4121da177e4SLinus Torvalds  */
413ad493e5eSLan Tianyu int usb_clear_port_feature(struct usb_device *hdev, int port1, int feature)
4141da177e4SLinus Torvalds {
4151da177e4SLinus Torvalds 	return usb_control_msg(hdev, usb_sndctrlpipe(hdev, 0),
4161da177e4SLinus Torvalds 		USB_REQ_CLEAR_FEATURE, USB_RT_PORT, feature, port1,
4171da177e4SLinus Torvalds 		NULL, 0, 1000);
4181da177e4SLinus Torvalds }
4191da177e4SLinus Torvalds 
4201da177e4SLinus Torvalds /*
4211da177e4SLinus Torvalds  * USB 2.0 spec Section 11.24.2.13
4221da177e4SLinus Torvalds  */
4231da177e4SLinus Torvalds static int set_port_feature(struct usb_device *hdev, int port1, int feature)
4241da177e4SLinus Torvalds {
4251da177e4SLinus Torvalds 	return usb_control_msg(hdev, usb_sndctrlpipe(hdev, 0),
4261da177e4SLinus Torvalds 		USB_REQ_SET_FEATURE, USB_RT_PORT, feature, port1,
4271da177e4SLinus Torvalds 		NULL, 0, 1000);
4281da177e4SLinus Torvalds }
4291da177e4SLinus Torvalds 
430d99f6b41SDan Williams static char *to_led_name(int selector)
431d99f6b41SDan Williams {
432d99f6b41SDan Williams 	switch (selector) {
433d99f6b41SDan Williams 	case HUB_LED_AMBER:
434d99f6b41SDan Williams 		return "amber";
435d99f6b41SDan Williams 	case HUB_LED_GREEN:
436d99f6b41SDan Williams 		return "green";
437d99f6b41SDan Williams 	case HUB_LED_OFF:
438d99f6b41SDan Williams 		return "off";
439d99f6b41SDan Williams 	case HUB_LED_AUTO:
440d99f6b41SDan Williams 		return "auto";
441d99f6b41SDan Williams 	default:
442d99f6b41SDan Williams 		return "??";
443d99f6b41SDan Williams 	}
444d99f6b41SDan Williams }
445d99f6b41SDan Williams 
4461da177e4SLinus Torvalds /*
4471da177e4SLinus Torvalds  * USB 2.0 spec Section 11.24.2.7.1.10 and table 11-7
4481da177e4SLinus Torvalds  * for info about using port indicators
4491da177e4SLinus Torvalds  */
450d99f6b41SDan Williams static void set_port_led(struct usb_hub *hub, int port1, int selector)
4511da177e4SLinus Torvalds {
452d99f6b41SDan Williams 	struct usb_port *port_dev = hub->ports[port1 - 1];
453d99f6b41SDan Williams 	int status;
454d99f6b41SDan Williams 
455d99f6b41SDan Williams 	status = set_port_feature(hub->hdev, (selector << 8) | port1,
4561da177e4SLinus Torvalds 			USB_PORT_FEAT_INDICATOR);
457d99f6b41SDan Williams 	dev_dbg(&port_dev->dev, "indicator %s status %d\n",
458d99f6b41SDan Williams 		to_led_name(selector), status);
4591da177e4SLinus Torvalds }
4601da177e4SLinus Torvalds 
4611da177e4SLinus Torvalds #define	LED_CYCLE_PERIOD	((2*HZ)/3)
4621da177e4SLinus Torvalds 
463c4028958SDavid Howells static void led_work(struct work_struct *work)
4641da177e4SLinus Torvalds {
465c4028958SDavid Howells 	struct usb_hub		*hub =
466c4028958SDavid Howells 		container_of(work, struct usb_hub, leds.work);
4671da177e4SLinus Torvalds 	struct usb_device	*hdev = hub->hdev;
4681da177e4SLinus Torvalds 	unsigned		i;
4691da177e4SLinus Torvalds 	unsigned		changed = 0;
4701da177e4SLinus Torvalds 	int			cursor = -1;
4711da177e4SLinus Torvalds 
4721da177e4SLinus Torvalds 	if (hdev->state != USB_STATE_CONFIGURED || hub->quiescing)
4731da177e4SLinus Torvalds 		return;
4741da177e4SLinus Torvalds 
4753bbc47d8SKrzysztof Mazur 	for (i = 0; i < hdev->maxchild; i++) {
4761da177e4SLinus Torvalds 		unsigned	selector, mode;
4771da177e4SLinus Torvalds 
4781da177e4SLinus Torvalds 		/* 30%-50% duty cycle */
4791da177e4SLinus Torvalds 
4801da177e4SLinus Torvalds 		switch (hub->indicator[i]) {
4811da177e4SLinus Torvalds 		/* cycle marker */
4821da177e4SLinus Torvalds 		case INDICATOR_CYCLE:
4831da177e4SLinus Torvalds 			cursor = i;
4841da177e4SLinus Torvalds 			selector = HUB_LED_AUTO;
4851da177e4SLinus Torvalds 			mode = INDICATOR_AUTO;
4861da177e4SLinus Torvalds 			break;
4871da177e4SLinus Torvalds 		/* blinking green = sw attention */
4881da177e4SLinus Torvalds 		case INDICATOR_GREEN_BLINK:
4891da177e4SLinus Torvalds 			selector = HUB_LED_GREEN;
4901da177e4SLinus Torvalds 			mode = INDICATOR_GREEN_BLINK_OFF;
4911da177e4SLinus Torvalds 			break;
4921da177e4SLinus Torvalds 		case INDICATOR_GREEN_BLINK_OFF:
4931da177e4SLinus Torvalds 			selector = HUB_LED_OFF;
4941da177e4SLinus Torvalds 			mode = INDICATOR_GREEN_BLINK;
4951da177e4SLinus Torvalds 			break;
4961da177e4SLinus Torvalds 		/* blinking amber = hw attention */
4971da177e4SLinus Torvalds 		case INDICATOR_AMBER_BLINK:
4981da177e4SLinus Torvalds 			selector = HUB_LED_AMBER;
4991da177e4SLinus Torvalds 			mode = INDICATOR_AMBER_BLINK_OFF;
5001da177e4SLinus Torvalds 			break;
5011da177e4SLinus Torvalds 		case INDICATOR_AMBER_BLINK_OFF:
5021da177e4SLinus Torvalds 			selector = HUB_LED_OFF;
5031da177e4SLinus Torvalds 			mode = INDICATOR_AMBER_BLINK;
5041da177e4SLinus Torvalds 			break;
5051da177e4SLinus Torvalds 		/* blink green/amber = reserved */
5061da177e4SLinus Torvalds 		case INDICATOR_ALT_BLINK:
5071da177e4SLinus Torvalds 			selector = HUB_LED_GREEN;
5081da177e4SLinus Torvalds 			mode = INDICATOR_ALT_BLINK_OFF;
5091da177e4SLinus Torvalds 			break;
5101da177e4SLinus Torvalds 		case INDICATOR_ALT_BLINK_OFF:
5111da177e4SLinus Torvalds 			selector = HUB_LED_AMBER;
5121da177e4SLinus Torvalds 			mode = INDICATOR_ALT_BLINK;
5131da177e4SLinus Torvalds 			break;
5141da177e4SLinus Torvalds 		default:
5151da177e4SLinus Torvalds 			continue;
5161da177e4SLinus Torvalds 		}
5171da177e4SLinus Torvalds 		if (selector != HUB_LED_AUTO)
5181da177e4SLinus Torvalds 			changed = 1;
5191da177e4SLinus Torvalds 		set_port_led(hub, i + 1, selector);
5201da177e4SLinus Torvalds 		hub->indicator[i] = mode;
5211da177e4SLinus Torvalds 	}
5221da177e4SLinus Torvalds 	if (!changed && blinkenlights) {
5231da177e4SLinus Torvalds 		cursor++;
5243bbc47d8SKrzysztof Mazur 		cursor %= hdev->maxchild;
5251da177e4SLinus Torvalds 		set_port_led(hub, cursor + 1, HUB_LED_GREEN);
5261da177e4SLinus Torvalds 		hub->indicator[cursor] = INDICATOR_CYCLE;
5271da177e4SLinus Torvalds 		changed++;
5281da177e4SLinus Torvalds 	}
5291da177e4SLinus Torvalds 	if (changed)
53022f6a0f0SShaibal Dutta 		queue_delayed_work(system_power_efficient_wq,
53122f6a0f0SShaibal Dutta 				&hub->leds, LED_CYCLE_PERIOD);
5321da177e4SLinus Torvalds }
5331da177e4SLinus Torvalds 
5341da177e4SLinus Torvalds /* use a short timeout for hub/port status fetches */
5351da177e4SLinus Torvalds #define	USB_STS_TIMEOUT		1000
5361da177e4SLinus Torvalds #define	USB_STS_RETRIES		5
5371da177e4SLinus Torvalds 
5381da177e4SLinus Torvalds /*
5391da177e4SLinus Torvalds  * USB 2.0 spec Section 11.24.2.6
5401da177e4SLinus Torvalds  */
5411da177e4SLinus Torvalds static int get_hub_status(struct usb_device *hdev,
5421da177e4SLinus Torvalds 		struct usb_hub_status *data)
5431da177e4SLinus Torvalds {
5441da177e4SLinus Torvalds 	int i, status = -ETIMEDOUT;
5451da177e4SLinus Torvalds 
5463824c1ddSLibor Pechacek 	for (i = 0; i < USB_STS_RETRIES &&
5473824c1ddSLibor Pechacek 			(status == -ETIMEDOUT || status == -EPIPE); i++) {
5481da177e4SLinus Torvalds 		status = usb_control_msg(hdev, usb_rcvctrlpipe(hdev, 0),
5491da177e4SLinus Torvalds 			USB_REQ_GET_STATUS, USB_DIR_IN | USB_RT_HUB, 0, 0,
5501da177e4SLinus Torvalds 			data, sizeof(*data), USB_STS_TIMEOUT);
5511da177e4SLinus Torvalds 	}
5521da177e4SLinus Torvalds 	return status;
5531da177e4SLinus Torvalds }
5541da177e4SLinus Torvalds 
5551da177e4SLinus Torvalds /*
5561da177e4SLinus Torvalds  * USB 2.0 spec Section 11.24.2.7
5570cdd49a1SMathias Nyman  * USB 3.1 takes into use the wValue and wLength fields, spec Section 10.16.2.6
5581da177e4SLinus Torvalds  */
5591da177e4SLinus Torvalds static int get_port_status(struct usb_device *hdev, int port1,
5600cdd49a1SMathias Nyman 			   void *data, u16 value, u16 length)
5611da177e4SLinus Torvalds {
5621da177e4SLinus Torvalds 	int i, status = -ETIMEDOUT;
5631da177e4SLinus Torvalds 
5643824c1ddSLibor Pechacek 	for (i = 0; i < USB_STS_RETRIES &&
5653824c1ddSLibor Pechacek 			(status == -ETIMEDOUT || status == -EPIPE); i++) {
5661da177e4SLinus Torvalds 		status = usb_control_msg(hdev, usb_rcvctrlpipe(hdev, 0),
5670cdd49a1SMathias Nyman 			USB_REQ_GET_STATUS, USB_DIR_IN | USB_RT_PORT, value,
5680cdd49a1SMathias Nyman 			port1, data, length, USB_STS_TIMEOUT);
5691da177e4SLinus Torvalds 	}
5701da177e4SLinus Torvalds 	return status;
5711da177e4SLinus Torvalds }
5721da177e4SLinus Torvalds 
5730cdd49a1SMathias Nyman static int hub_ext_port_status(struct usb_hub *hub, int port1, int type,
5740cdd49a1SMathias Nyman 			       u16 *status, u16 *change, u32 *ext_status)
5753eb14915SAlan Stern {
5763eb14915SAlan Stern 	int ret;
5770cdd49a1SMathias Nyman 	int len = 4;
5780cdd49a1SMathias Nyman 
5790cdd49a1SMathias Nyman 	if (type != HUB_PORT_STATUS)
5800cdd49a1SMathias Nyman 		len = 8;
5813eb14915SAlan Stern 
5823eb14915SAlan Stern 	mutex_lock(&hub->status_mutex);
5830cdd49a1SMathias Nyman 	ret = get_port_status(hub->hdev, port1, &hub->status->port, type, len);
5840cdd49a1SMathias Nyman 	if (ret < len) {
585e9e88fb7SAlan Stern 		if (ret != -ENODEV)
5863eb14915SAlan Stern 			dev_err(hub->intfdev,
5873eb14915SAlan Stern 				"%s failed (err = %d)\n", __func__, ret);
5883eb14915SAlan Stern 		if (ret >= 0)
5893eb14915SAlan Stern 			ret = -EIO;
5903eb14915SAlan Stern 	} else {
5913eb14915SAlan Stern 		*status = le16_to_cpu(hub->status->port.wPortStatus);
5923eb14915SAlan Stern 		*change = le16_to_cpu(hub->status->port.wPortChange);
5930cdd49a1SMathias Nyman 		if (type != HUB_PORT_STATUS && ext_status)
5940cdd49a1SMathias Nyman 			*ext_status = le32_to_cpu(
5950cdd49a1SMathias Nyman 				hub->status->port.dwExtPortStatus);
5963eb14915SAlan Stern 		ret = 0;
5973eb14915SAlan Stern 	}
5983eb14915SAlan Stern 	mutex_unlock(&hub->status_mutex);
5993eb14915SAlan Stern 	return ret;
6003eb14915SAlan Stern }
6013eb14915SAlan Stern 
6020cdd49a1SMathias Nyman static int hub_port_status(struct usb_hub *hub, int port1,
6030cdd49a1SMathias Nyman 		u16 *status, u16 *change)
6040cdd49a1SMathias Nyman {
6050cdd49a1SMathias Nyman 	return hub_ext_port_status(hub, port1, HUB_PORT_STATUS,
6060cdd49a1SMathias Nyman 				   status, change, NULL);
6070cdd49a1SMathias Nyman }
6080cdd49a1SMathias Nyman 
60932a69589SPetr Mladek static void kick_hub_wq(struct usb_hub *hub)
6101da177e4SLinus Torvalds {
61132a69589SPetr Mladek 	struct usb_interface *intf;
6121da177e4SLinus Torvalds 
61332a69589SPetr Mladek 	if (hub->disconnected || work_pending(&hub->events))
61432a69589SPetr Mladek 		return;
6158e4ceb38SAlan Stern 
61632a69589SPetr Mladek 	/*
61732a69589SPetr Mladek 	 * Suppress autosuspend until the event is proceed.
61832a69589SPetr Mladek 	 *
61932a69589SPetr Mladek 	 * Be careful and make sure that the symmetric operation is
62032a69589SPetr Mladek 	 * always called. We are here only when there is no pending
62132a69589SPetr Mladek 	 * work for this hub. Therefore put the interface either when
62232a69589SPetr Mladek 	 * the new work is called or when it is canceled.
62332a69589SPetr Mladek 	 */
62432a69589SPetr Mladek 	intf = to_usb_interface(hub->intfdev);
62532a69589SPetr Mladek 	usb_autopm_get_interface_no_resume(intf);
62632a69589SPetr Mladek 	kref_get(&hub->kref);
62732a69589SPetr Mladek 
62832a69589SPetr Mladek 	if (queue_work(hub_wq, &hub->events))
62932a69589SPetr Mladek 		return;
63032a69589SPetr Mladek 
63132a69589SPetr Mladek 	/* the work has already been scheduled */
63232a69589SPetr Mladek 	usb_autopm_put_interface_async(intf);
63332a69589SPetr Mladek 	kref_put(&hub->kref, hub_release);
6341da177e4SLinus Torvalds }
6351da177e4SLinus Torvalds 
63659d48b3fSPetr Mladek void usb_kick_hub_wq(struct usb_device *hdev)
6371da177e4SLinus Torvalds {
638ad493e5eSLan Tianyu 	struct usb_hub *hub = usb_hub_to_struct_hub(hdev);
63925118084SAlan Stern 
64025118084SAlan Stern 	if (hub)
64132a69589SPetr Mladek 		kick_hub_wq(hub);
6421da177e4SLinus Torvalds }
6431da177e4SLinus Torvalds 
6444ee823b8SSarah Sharp /*
6454ee823b8SSarah Sharp  * Let the USB core know that a USB 3.0 device has sent a Function Wake Device
6464ee823b8SSarah Sharp  * Notification, which indicates it had initiated remote wakeup.
6474ee823b8SSarah Sharp  *
6484ee823b8SSarah Sharp  * USB 3.0 hubs do not report the port link state change from U3 to U0 when the
6494ee823b8SSarah Sharp  * device initiates resume, so the USB core will not receive notice of the
6504ee823b8SSarah Sharp  * resume through the normal hub interrupt URB.
6514ee823b8SSarah Sharp  */
6524ee823b8SSarah Sharp void usb_wakeup_notification(struct usb_device *hdev,
6534ee823b8SSarah Sharp 		unsigned int portnum)
6544ee823b8SSarah Sharp {
6554ee823b8SSarah Sharp 	struct usb_hub *hub;
65683a62c51SRavi Chandra Sadineni 	struct usb_port *port_dev;
6574ee823b8SSarah Sharp 
6584ee823b8SSarah Sharp 	if (!hdev)
6594ee823b8SSarah Sharp 		return;
6604ee823b8SSarah Sharp 
661ad493e5eSLan Tianyu 	hub = usb_hub_to_struct_hub(hdev);
6624ee823b8SSarah Sharp 	if (hub) {
66383a62c51SRavi Chandra Sadineni 		port_dev = hub->ports[portnum - 1];
66483a62c51SRavi Chandra Sadineni 		if (port_dev && port_dev->child)
66583a62c51SRavi Chandra Sadineni 			pm_wakeup_event(&port_dev->child->dev, 0);
66683a62c51SRavi Chandra Sadineni 
6674ee823b8SSarah Sharp 		set_bit(portnum, hub->wakeup_bits);
66832a69589SPetr Mladek 		kick_hub_wq(hub);
6694ee823b8SSarah Sharp 	}
6704ee823b8SSarah Sharp }
6714ee823b8SSarah Sharp EXPORT_SYMBOL_GPL(usb_wakeup_notification);
6721da177e4SLinus Torvalds 
6731da177e4SLinus Torvalds /* completion function, fires on port status changes and various faults */
6747d12e780SDavid Howells static void hub_irq(struct urb *urb)
6751da177e4SLinus Torvalds {
676ec17cf1cSTobias Klauser 	struct usb_hub *hub = urb->context;
677e015268dSAlan Stern 	int status = urb->status;
67871d2718fSRoel Kluin 	unsigned i;
6791da177e4SLinus Torvalds 	unsigned long bits;
6801da177e4SLinus Torvalds 
681e015268dSAlan Stern 	switch (status) {
6821da177e4SLinus Torvalds 	case -ENOENT:		/* synchronous unlink */
6831da177e4SLinus Torvalds 	case -ECONNRESET:	/* async unlink */
6841da177e4SLinus Torvalds 	case -ESHUTDOWN:	/* hardware going away */
6851da177e4SLinus Torvalds 		return;
6861da177e4SLinus Torvalds 
6871da177e4SLinus Torvalds 	default:		/* presumably an error */
6881da177e4SLinus Torvalds 		/* Cause a hub reset after 10 consecutive errors */
689e015268dSAlan Stern 		dev_dbg(hub->intfdev, "transfer --> %d\n", status);
6901da177e4SLinus Torvalds 		if ((++hub->nerrors < 10) || hub->error)
6911da177e4SLinus Torvalds 			goto resubmit;
692e015268dSAlan Stern 		hub->error = status;
6931da177e4SLinus Torvalds 		/* FALL THROUGH */
6941da177e4SLinus Torvalds 
69537ebb549SPetr Mladek 	/* let hub_wq handle things */
6961da177e4SLinus Torvalds 	case 0:			/* we got data:  port status changed */
6971da177e4SLinus Torvalds 		bits = 0;
6981da177e4SLinus Torvalds 		for (i = 0; i < urb->actual_length; ++i)
6991da177e4SLinus Torvalds 			bits |= ((unsigned long) ((*hub->buffer)[i]))
7001da177e4SLinus Torvalds 					<< (i*8);
7011da177e4SLinus Torvalds 		hub->event_bits[0] = bits;
7021da177e4SLinus Torvalds 		break;
7031da177e4SLinus Torvalds 	}
7041da177e4SLinus Torvalds 
7051da177e4SLinus Torvalds 	hub->nerrors = 0;
7061da177e4SLinus Torvalds 
70737ebb549SPetr Mladek 	/* Something happened, let hub_wq figure it out */
70832a69589SPetr Mladek 	kick_hub_wq(hub);
7091da177e4SLinus Torvalds 
7101da177e4SLinus Torvalds resubmit:
7111da177e4SLinus Torvalds 	if (hub->quiescing)
7121da177e4SLinus Torvalds 		return;
7131da177e4SLinus Torvalds 
714088a3daeSKris Borer 	status = usb_submit_urb(hub->urb, GFP_ATOMIC);
715088a3daeSKris Borer 	if (status != 0 && status != -ENODEV && status != -EPERM)
7161da177e4SLinus Torvalds 		dev_err(hub->intfdev, "resubmit --> %d\n", status);
7171da177e4SLinus Torvalds }
7181da177e4SLinus Torvalds 
7191da177e4SLinus Torvalds /* USB 2.0 spec Section 11.24.2.3 */
7201da177e4SLinus Torvalds static inline int
7211da177e4SLinus Torvalds hub_clear_tt_buffer(struct usb_device *hdev, u16 devinfo, u16 tt)
7221da177e4SLinus Torvalds {
7232c7b871bSWilliam Gulland 	/* Need to clear both directions for control ep */
7242c7b871bSWilliam Gulland 	if (((devinfo >> 11) & USB_ENDPOINT_XFERTYPE_MASK) ==
7252c7b871bSWilliam Gulland 			USB_ENDPOINT_XFER_CONTROL) {
7262c7b871bSWilliam Gulland 		int status = usb_control_msg(hdev, usb_sndctrlpipe(hdev, 0),
7272c7b871bSWilliam Gulland 				HUB_CLEAR_TT_BUFFER, USB_RT_PORT,
7282c7b871bSWilliam Gulland 				devinfo ^ 0x8000, tt, NULL, 0, 1000);
7292c7b871bSWilliam Gulland 		if (status)
7302c7b871bSWilliam Gulland 			return status;
7312c7b871bSWilliam Gulland 	}
732c2f6595fSAlan Stern 	return usb_control_msg(hdev, usb_sndctrlpipe(hdev, 0),
7331da177e4SLinus Torvalds 			       HUB_CLEAR_TT_BUFFER, USB_RT_PORT, devinfo,
7341da177e4SLinus Torvalds 			       tt, NULL, 0, 1000);
7351da177e4SLinus Torvalds }
7361da177e4SLinus Torvalds 
7371da177e4SLinus Torvalds /*
73837ebb549SPetr Mladek  * enumeration blocks hub_wq for a long time. we use keventd instead, since
7391da177e4SLinus Torvalds  * long blocking there is the exception, not the rule.  accordingly, HCDs
7401da177e4SLinus Torvalds  * talking to TTs must queue control transfers (not just bulk and iso), so
7411da177e4SLinus Torvalds  * both can talk to the same hub concurrently.
7421da177e4SLinus Torvalds  */
743cb88a1b8SAlan Stern static void hub_tt_work(struct work_struct *work)
7441da177e4SLinus Torvalds {
745c4028958SDavid Howells 	struct usb_hub		*hub =
746cb88a1b8SAlan Stern 		container_of(work, struct usb_hub, tt.clear_work);
7471da177e4SLinus Torvalds 	unsigned long		flags;
7481da177e4SLinus Torvalds 
7491da177e4SLinus Torvalds 	spin_lock_irqsave(&hub->tt.lock, flags);
7503b6054daSOctavian Purdila 	while (!list_empty(&hub->tt.clear_list)) {
751d0f830d3SH Hartley Sweeten 		struct list_head	*next;
7521da177e4SLinus Torvalds 		struct usb_tt_clear	*clear;
7531da177e4SLinus Torvalds 		struct usb_device	*hdev = hub->hdev;
754cb88a1b8SAlan Stern 		const struct hc_driver	*drv;
7551da177e4SLinus Torvalds 		int			status;
7561da177e4SLinus Torvalds 
757d0f830d3SH Hartley Sweeten 		next = hub->tt.clear_list.next;
758d0f830d3SH Hartley Sweeten 		clear = list_entry(next, struct usb_tt_clear, clear_list);
7591da177e4SLinus Torvalds 		list_del(&clear->clear_list);
7601da177e4SLinus Torvalds 
7611da177e4SLinus Torvalds 		/* drop lock so HCD can concurrently report other TT errors */
7621da177e4SLinus Torvalds 		spin_unlock_irqrestore(&hub->tt.lock, flags);
7631da177e4SLinus Torvalds 		status = hub_clear_tt_buffer(hdev, clear->devinfo, clear->tt);
764e9e88fb7SAlan Stern 		if (status && status != -ENODEV)
7651da177e4SLinus Torvalds 			dev_err(&hdev->dev,
7661da177e4SLinus Torvalds 				"clear tt %d (%04x) error %d\n",
7671da177e4SLinus Torvalds 				clear->tt, clear->devinfo, status);
768cb88a1b8SAlan Stern 
769cb88a1b8SAlan Stern 		/* Tell the HCD, even if the operation failed */
770cb88a1b8SAlan Stern 		drv = clear->hcd->driver;
771cb88a1b8SAlan Stern 		if (drv->clear_tt_buffer_complete)
772cb88a1b8SAlan Stern 			(drv->clear_tt_buffer_complete)(clear->hcd, clear->ep);
773cb88a1b8SAlan Stern 
7741da177e4SLinus Torvalds 		kfree(clear);
775cb88a1b8SAlan Stern 		spin_lock_irqsave(&hub->tt.lock, flags);
7761da177e4SLinus Torvalds 	}
7771da177e4SLinus Torvalds 	spin_unlock_irqrestore(&hub->tt.lock, flags);
7781da177e4SLinus Torvalds }
7791da177e4SLinus Torvalds 
7801da177e4SLinus Torvalds /**
781971fcd49SLan Tianyu  * usb_hub_set_port_power - control hub port's power state
78241341261SMathias Nyman  * @hdev: USB device belonging to the usb hub
78341341261SMathias Nyman  * @hub: target hub
784971fcd49SLan Tianyu  * @port1: port index
785971fcd49SLan Tianyu  * @set: expected status
786971fcd49SLan Tianyu  *
787971fcd49SLan Tianyu  * call this function to control port's power via setting or
788971fcd49SLan Tianyu  * clearing the port's PORT_POWER feature.
789626f090cSYacine Belkadi  *
790626f090cSYacine Belkadi  * Return: 0 if successful. A negative error code otherwise.
791971fcd49SLan Tianyu  */
79241341261SMathias Nyman int usb_hub_set_port_power(struct usb_device *hdev, struct usb_hub *hub,
79341341261SMathias Nyman 			   int port1, bool set)
794971fcd49SLan Tianyu {
795971fcd49SLan Tianyu 	int ret;
796971fcd49SLan Tianyu 
797971fcd49SLan Tianyu 	if (set)
798971fcd49SLan Tianyu 		ret = set_port_feature(hdev, port1, USB_PORT_FEAT_POWER);
799971fcd49SLan Tianyu 	else
800ad493e5eSLan Tianyu 		ret = usb_clear_port_feature(hdev, port1, USB_PORT_FEAT_POWER);
801ad493e5eSLan Tianyu 
802d5c3834eSDan Williams 	if (ret)
803971fcd49SLan Tianyu 		return ret;
804d5c3834eSDan Williams 
805d5c3834eSDan Williams 	if (set)
806d5c3834eSDan Williams 		set_bit(port1, hub->power_bits);
807d5c3834eSDan Williams 	else
808d5c3834eSDan Williams 		clear_bit(port1, hub->power_bits);
809d5c3834eSDan Williams 	return 0;
810971fcd49SLan Tianyu }
811971fcd49SLan Tianyu 
812971fcd49SLan Tianyu /**
813cb88a1b8SAlan Stern  * usb_hub_clear_tt_buffer - clear control/bulk TT state in high speed hub
814cb88a1b8SAlan Stern  * @urb: an URB associated with the failed or incomplete split transaction
8151da177e4SLinus Torvalds  *
8161da177e4SLinus Torvalds  * High speed HCDs use this to tell the hub driver that some split control or
8171da177e4SLinus Torvalds  * bulk transaction failed in a way that requires clearing internal state of
8181da177e4SLinus Torvalds  * a transaction translator.  This is normally detected (and reported) from
8191da177e4SLinus Torvalds  * interrupt context.
8201da177e4SLinus Torvalds  *
8211da177e4SLinus Torvalds  * It may not be possible for that hub to handle additional full (or low)
8221da177e4SLinus Torvalds  * speed transactions until that state is fully cleared out.
823626f090cSYacine Belkadi  *
824626f090cSYacine Belkadi  * Return: 0 if successful. A negative error code otherwise.
8251da177e4SLinus Torvalds  */
826cb88a1b8SAlan Stern int usb_hub_clear_tt_buffer(struct urb *urb)
8271da177e4SLinus Torvalds {
828cb88a1b8SAlan Stern 	struct usb_device	*udev = urb->dev;
829cb88a1b8SAlan Stern 	int			pipe = urb->pipe;
8301da177e4SLinus Torvalds 	struct usb_tt		*tt = udev->tt;
8311da177e4SLinus Torvalds 	unsigned long		flags;
8321da177e4SLinus Torvalds 	struct usb_tt_clear	*clear;
8331da177e4SLinus Torvalds 
8341da177e4SLinus Torvalds 	/* we've got to cope with an arbitrary number of pending TT clears,
8351da177e4SLinus Torvalds 	 * since each TT has "at least two" buffers that can need it (and
8361da177e4SLinus Torvalds 	 * there can be many TTs per hub).  even if they're uncommon.
8371da177e4SLinus Torvalds 	 */
838d544d273SGreg Kroah-Hartman 	clear = kmalloc(sizeof *clear, GFP_ATOMIC);
839d544d273SGreg Kroah-Hartman 	if (clear == NULL) {
8401da177e4SLinus Torvalds 		dev_err(&udev->dev, "can't save CLEAR_TT_BUFFER state\n");
8411da177e4SLinus Torvalds 		/* FIXME recover somehow ... RESET_TT? */
842cb88a1b8SAlan Stern 		return -ENOMEM;
8431da177e4SLinus Torvalds 	}
8441da177e4SLinus Torvalds 
8451da177e4SLinus Torvalds 	/* info that CLEAR_TT_BUFFER needs */
8461da177e4SLinus Torvalds 	clear->tt = tt->multi ? udev->ttport : 1;
8471da177e4SLinus Torvalds 	clear->devinfo = usb_pipeendpoint (pipe);
8481da177e4SLinus Torvalds 	clear->devinfo |= udev->devnum << 4;
8491da177e4SLinus Torvalds 	clear->devinfo |= usb_pipecontrol(pipe)
8501da177e4SLinus Torvalds 			? (USB_ENDPOINT_XFER_CONTROL << 11)
8511da177e4SLinus Torvalds 			: (USB_ENDPOINT_XFER_BULK << 11);
8521da177e4SLinus Torvalds 	if (usb_pipein(pipe))
8531da177e4SLinus Torvalds 		clear->devinfo |= 1 << 15;
8541da177e4SLinus Torvalds 
855cb88a1b8SAlan Stern 	/* info for completion callback */
856cb88a1b8SAlan Stern 	clear->hcd = bus_to_hcd(udev->bus);
857cb88a1b8SAlan Stern 	clear->ep = urb->ep;
858cb88a1b8SAlan Stern 
8591da177e4SLinus Torvalds 	/* tell keventd to clear state for this TT */
8601da177e4SLinus Torvalds 	spin_lock_irqsave(&tt->lock, flags);
8611da177e4SLinus Torvalds 	list_add_tail(&clear->clear_list, &tt->clear_list);
862cb88a1b8SAlan Stern 	schedule_work(&tt->clear_work);
8631da177e4SLinus Torvalds 	spin_unlock_irqrestore(&tt->lock, flags);
864cb88a1b8SAlan Stern 	return 0;
8651da177e4SLinus Torvalds }
866cb88a1b8SAlan Stern EXPORT_SYMBOL_GPL(usb_hub_clear_tt_buffer);
8671da177e4SLinus Torvalds 
8687ad3c470SDan Williams static void hub_power_on(struct usb_hub *hub, bool do_delay)
8691da177e4SLinus Torvalds {
8701da177e4SLinus Torvalds 	int port1;
8711da177e4SLinus Torvalds 
8724489a571SAlan Stern 	/* Enable power on each port.  Some hubs have reserved values
8734489a571SAlan Stern 	 * of LPSM (> 2) in their descriptors, even though they are
8744489a571SAlan Stern 	 * USB 2.0 hubs.  Some hubs do not implement port-power switching
8754489a571SAlan Stern 	 * but only emulate it.  In all cases, the ports won't work
8764489a571SAlan Stern 	 * unless we send these messages to the hub.
8774489a571SAlan Stern 	 */
8789262c19dSDan Williams 	if (hub_is_port_power_switchable(hub))
8791da177e4SLinus Torvalds 		dev_dbg(hub->intfdev, "enabling power on all ports\n");
8804489a571SAlan Stern 	else
8814489a571SAlan Stern 		dev_dbg(hub->intfdev, "trying to enable port power on "
8824489a571SAlan Stern 				"non-switchable hub\n");
8833bbc47d8SKrzysztof Mazur 	for (port1 = 1; port1 <= hub->hdev->maxchild; port1++)
884d5c3834eSDan Williams 		if (test_bit(port1, hub->power_bits))
8854489a571SAlan Stern 			set_port_feature(hub->hdev, port1, USB_PORT_FEAT_POWER);
886ad493e5eSLan Tianyu 		else
887ad493e5eSLan Tianyu 			usb_clear_port_feature(hub->hdev, port1,
888ad493e5eSLan Tianyu 						USB_PORT_FEAT_POWER);
8898520f380SAlan Stern 	if (do_delay)
8907ad3c470SDan Williams 		msleep(hub_power_on_good_delay(hub));
8911da177e4SLinus Torvalds }
8921da177e4SLinus Torvalds 
8931da177e4SLinus Torvalds static int hub_hub_status(struct usb_hub *hub,
8941da177e4SLinus Torvalds 		u16 *status, u16 *change)
8951da177e4SLinus Torvalds {
8961da177e4SLinus Torvalds 	int ret;
8971da177e4SLinus Torvalds 
898db90e7a1SAlan Stern 	mutex_lock(&hub->status_mutex);
8991da177e4SLinus Torvalds 	ret = get_hub_status(hub->hdev, &hub->status->hub);
900e9e88fb7SAlan Stern 	if (ret < 0) {
901e9e88fb7SAlan Stern 		if (ret != -ENODEV)
9021da177e4SLinus Torvalds 			dev_err(hub->intfdev,
903441b62c1SHarvey Harrison 				"%s failed (err = %d)\n", __func__, ret);
904e9e88fb7SAlan Stern 	} else {
9051da177e4SLinus Torvalds 		*status = le16_to_cpu(hub->status->hub.wHubStatus);
9061da177e4SLinus Torvalds 		*change = le16_to_cpu(hub->status->hub.wHubChange);
9071da177e4SLinus Torvalds 		ret = 0;
9081da177e4SLinus Torvalds 	}
909db90e7a1SAlan Stern 	mutex_unlock(&hub->status_mutex);
9101da177e4SLinus Torvalds 	return ret;
9111da177e4SLinus Torvalds }
9121da177e4SLinus Torvalds 
91341e7e056SSarah Sharp static int hub_set_port_link_state(struct usb_hub *hub, int port1,
91441e7e056SSarah Sharp 			unsigned int link_status)
91541e7e056SSarah Sharp {
91641e7e056SSarah Sharp 	return set_port_feature(hub->hdev,
91741e7e056SSarah Sharp 			port1 | (link_status << 3),
91841e7e056SSarah Sharp 			USB_PORT_FEAT_LINK_STATE);
91941e7e056SSarah Sharp }
92041e7e056SSarah Sharp 
92141e7e056SSarah Sharp /*
9226d42fcdbSJustin P. Mattock  * Disable a port and mark a logical connect-change event, so that some
92337ebb549SPetr Mladek  * time later hub_wq will disconnect() any existing usb_device on the port
9240458d5b4SAlan Stern  * and will re-enumerate if there actually is a device attached.
9250458d5b4SAlan Stern  */
9260458d5b4SAlan Stern static void hub_port_logical_disconnect(struct usb_hub *hub, int port1)
9277d069b7dSAlan Stern {
928d99f6b41SDan Williams 	dev_dbg(&hub->ports[port1 - 1]->dev, "logical disconnect\n");
9290458d5b4SAlan Stern 	hub_port_disable(hub, port1, 1);
9300458d5b4SAlan Stern 
9310458d5b4SAlan Stern 	/* FIXME let caller ask to power down the port:
9320458d5b4SAlan Stern 	 *  - some devices won't enumerate without a VBUS power cycle
9330458d5b4SAlan Stern 	 *  - SRP saves power that way
9340458d5b4SAlan Stern 	 *  - ... new call, TBD ...
9350458d5b4SAlan Stern 	 * That's easy if this hub can switch power per-port, and
93637ebb549SPetr Mladek 	 * hub_wq reactivates the port later (timer, SRP, etc).
9370458d5b4SAlan Stern 	 * Powerdown must be optional, because of reset/DFU.
9380458d5b4SAlan Stern 	 */
9390458d5b4SAlan Stern 
9400458d5b4SAlan Stern 	set_bit(port1, hub->change_bits);
94132a69589SPetr Mladek 	kick_hub_wq(hub);
9420458d5b4SAlan Stern }
9430458d5b4SAlan Stern 
944253e0572SAlan Stern /**
945253e0572SAlan Stern  * usb_remove_device - disable a device's port on its parent hub
946253e0572SAlan Stern  * @udev: device to be disabled and removed
947253e0572SAlan Stern  * Context: @udev locked, must be able to sleep.
948253e0572SAlan Stern  *
94937ebb549SPetr Mladek  * After @udev's port has been disabled, hub_wq is notified and it will
950253e0572SAlan Stern  * see that the device has been disconnected.  When the device is
951253e0572SAlan Stern  * physically unplugged and something is plugged in, the events will
952253e0572SAlan Stern  * be received and processed normally.
953626f090cSYacine Belkadi  *
954626f090cSYacine Belkadi  * Return: 0 if successful. A negative error code otherwise.
955253e0572SAlan Stern  */
956253e0572SAlan Stern int usb_remove_device(struct usb_device *udev)
957253e0572SAlan Stern {
958253e0572SAlan Stern 	struct usb_hub *hub;
959253e0572SAlan Stern 	struct usb_interface *intf;
960253e0572SAlan Stern 
961253e0572SAlan Stern 	if (!udev->parent)	/* Can't remove a root hub */
962253e0572SAlan Stern 		return -EINVAL;
963ad493e5eSLan Tianyu 	hub = usb_hub_to_struct_hub(udev->parent);
964253e0572SAlan Stern 	intf = to_usb_interface(hub->intfdev);
965253e0572SAlan Stern 
966253e0572SAlan Stern 	usb_autopm_get_interface(intf);
967253e0572SAlan Stern 	set_bit(udev->portnum, hub->removed_bits);
968253e0572SAlan Stern 	hub_port_logical_disconnect(hub, udev->portnum);
969253e0572SAlan Stern 	usb_autopm_put_interface(intf);
970253e0572SAlan Stern 	return 0;
971253e0572SAlan Stern }
972253e0572SAlan Stern 
9736ee0b270SAlan Stern enum hub_activation_type {
9748e4ceb38SAlan Stern 	HUB_INIT, HUB_INIT2, HUB_INIT3,		/* INITs must come first */
9758520f380SAlan Stern 	HUB_POST_RESET, HUB_RESUME, HUB_RESET_RESUME,
9766ee0b270SAlan Stern };
9775e6effaeSAlan Stern 
9788520f380SAlan Stern static void hub_init_func2(struct work_struct *ws);
9798520f380SAlan Stern static void hub_init_func3(struct work_struct *ws);
9808520f380SAlan Stern 
981f2835219SAlan Stern static void hub_activate(struct usb_hub *hub, enum hub_activation_type type)
9825e6effaeSAlan Stern {
9835e6effaeSAlan Stern 	struct usb_device *hdev = hub->hdev;
984653a39d1SSarah Sharp 	struct usb_hcd *hcd;
985653a39d1SSarah Sharp 	int ret;
9865e6effaeSAlan Stern 	int port1;
987f2835219SAlan Stern 	int status;
988948fea37SAlan Stern 	bool need_debounce_delay = false;
9898520f380SAlan Stern 	unsigned delay;
9908520f380SAlan Stern 
9918520f380SAlan Stern 	/* Continue a partial initialization */
992e50293efSAlan Stern 	if (type == HUB_INIT2 || type == HUB_INIT3) {
99307d316a2SAlan Stern 		device_lock(&hdev->dev);
994e50293efSAlan Stern 
995e50293efSAlan Stern 		/* Was the hub disconnected while we were waiting? */
996ca5cbc8bSAlan Stern 		if (hub->disconnected)
997ca5cbc8bSAlan Stern 			goto disconnected;
9988520f380SAlan Stern 		if (type == HUB_INIT2)
9998520f380SAlan Stern 			goto init2;
10008520f380SAlan Stern 		goto init3;
1001e50293efSAlan Stern 	}
1002e50293efSAlan Stern 	kref_get(&hub->kref);
10035e6effaeSAlan Stern 
1004a45aa3b3SElric Fu 	/* The superspeed hub except for root hub has to use Hub Depth
1005a45aa3b3SElric Fu 	 * value as an offset into the route string to locate the bits
1006a45aa3b3SElric Fu 	 * it uses to determine the downstream port number. So hub driver
1007a45aa3b3SElric Fu 	 * should send a set hub depth request to superspeed hub after
1008a45aa3b3SElric Fu 	 * the superspeed hub is set configuration in initialization or
1009a45aa3b3SElric Fu 	 * reset procedure.
1010a45aa3b3SElric Fu 	 *
1011a45aa3b3SElric Fu 	 * After a resume, port power should still be on.
1012f2835219SAlan Stern 	 * For any other type of activation, turn it on.
1013f2835219SAlan Stern 	 */
10148520f380SAlan Stern 	if (type != HUB_RESUME) {
1015a45aa3b3SElric Fu 		if (hdev->parent && hub_is_superspeed(hdev)) {
1016a45aa3b3SElric Fu 			ret = usb_control_msg(hdev, usb_sndctrlpipe(hdev, 0),
1017a45aa3b3SElric Fu 					HUB_SET_DEPTH, USB_RT_HUB,
1018a45aa3b3SElric Fu 					hdev->level - 1, 0, NULL, 0,
1019a45aa3b3SElric Fu 					USB_CTRL_SET_TIMEOUT);
1020a45aa3b3SElric Fu 			if (ret < 0)
1021a45aa3b3SElric Fu 				dev_err(hub->intfdev,
1022a45aa3b3SElric Fu 						"set hub depth failed\n");
1023a45aa3b3SElric Fu 		}
10248520f380SAlan Stern 
10258520f380SAlan Stern 		/* Speed up system boot by using a delayed_work for the
10268520f380SAlan Stern 		 * hub's initial power-up delays.  This is pretty awkward
10278520f380SAlan Stern 		 * and the implementation looks like a home-brewed sort of
10288520f380SAlan Stern 		 * setjmp/longjmp, but it saves at least 100 ms for each
10298520f380SAlan Stern 		 * root hub (assuming usbcore is compiled into the kernel
10308520f380SAlan Stern 		 * rather than as a module).  It adds up.
10318520f380SAlan Stern 		 *
10328520f380SAlan Stern 		 * This can't be done for HUB_RESUME or HUB_RESET_RESUME
10338520f380SAlan Stern 		 * because for those activation types the ports have to be
10348520f380SAlan Stern 		 * operational when we return.  In theory this could be done
10358520f380SAlan Stern 		 * for HUB_POST_RESET, but it's easier not to.
10368520f380SAlan Stern 		 */
10378520f380SAlan Stern 		if (type == HUB_INIT) {
103817a364e2SKris Borer 			delay = hub_power_on_good_delay(hub);
10397ad3c470SDan Williams 
10407ad3c470SDan Williams 			hub_power_on(hub, false);
104177fa83cfSTejun Heo 			INIT_DELAYED_WORK(&hub->init_work, hub_init_func2);
104222f6a0f0SShaibal Dutta 			queue_delayed_work(system_power_efficient_wq,
104322f6a0f0SShaibal Dutta 					&hub->init_work,
10448520f380SAlan Stern 					msecs_to_jiffies(delay));
104561fbeba1SAlan Stern 
104661fbeba1SAlan Stern 			/* Suppress autosuspend until init is done */
10478e4ceb38SAlan Stern 			usb_autopm_get_interface_no_resume(
10488e4ceb38SAlan Stern 					to_usb_interface(hub->intfdev));
10498520f380SAlan Stern 			return;		/* Continues at init2: below */
1050653a39d1SSarah Sharp 		} else if (type == HUB_RESET_RESUME) {
1051653a39d1SSarah Sharp 			/* The internal host controller state for the hub device
1052653a39d1SSarah Sharp 			 * may be gone after a host power loss on system resume.
1053653a39d1SSarah Sharp 			 * Update the device's info so the HW knows it's a hub.
1054653a39d1SSarah Sharp 			 */
1055653a39d1SSarah Sharp 			hcd = bus_to_hcd(hdev->bus);
1056653a39d1SSarah Sharp 			if (hcd->driver->update_hub_device) {
1057653a39d1SSarah Sharp 				ret = hcd->driver->update_hub_device(hcd, hdev,
1058653a39d1SSarah Sharp 						&hub->tt, GFP_NOIO);
1059653a39d1SSarah Sharp 				if (ret < 0) {
10601ccc417eSJoe Perches 					dev_err(hub->intfdev,
10611ccc417eSJoe Perches 						"Host not accepting hub info update\n");
10621ccc417eSJoe Perches 					dev_err(hub->intfdev,
10631ccc417eSJoe Perches 						"LS/FS devices and hubs may not work under this hub\n");
1064653a39d1SSarah Sharp 				}
1065653a39d1SSarah Sharp 			}
1066653a39d1SSarah Sharp 			hub_power_on(hub, true);
10678520f380SAlan Stern 		} else {
10688520f380SAlan Stern 			hub_power_on(hub, true);
10698520f380SAlan Stern 		}
10708520f380SAlan Stern 	}
10718520f380SAlan Stern  init2:
1072f2835219SAlan Stern 
1073d99f6b41SDan Williams 	/*
107437ebb549SPetr Mladek 	 * Check each port and set hub->change_bits to let hub_wq know
10756ee0b270SAlan Stern 	 * which ports need attention.
10765e6effaeSAlan Stern 	 */
10775e6effaeSAlan Stern 	for (port1 = 1; port1 <= hdev->maxchild; ++port1) {
1078d99f6b41SDan Williams 		struct usb_port *port_dev = hub->ports[port1 - 1];
1079d99f6b41SDan Williams 		struct usb_device *udev = port_dev->child;
10805e6effaeSAlan Stern 		u16 portstatus, portchange;
10815e6effaeSAlan Stern 
10826ee0b270SAlan Stern 		portstatus = portchange = 0;
10836ee0b270SAlan Stern 		status = hub_port_status(hub, port1, &portstatus, &portchange);
1084245b2eecSGuenter Roeck 		if (status)
1085245b2eecSGuenter Roeck 			goto abort;
1086245b2eecSGuenter Roeck 
10876ee0b270SAlan Stern 		if (udev || (portstatus & USB_PORT_STAT_CONNECTION))
1088d99f6b41SDan Williams 			dev_dbg(&port_dev->dev, "status %04x change %04x\n",
1089d99f6b41SDan Williams 					portstatus, portchange);
10905e6effaeSAlan Stern 
1091d99f6b41SDan Williams 		/*
1092d99f6b41SDan Williams 		 * After anything other than HUB_RESUME (i.e., initialization
10936ee0b270SAlan Stern 		 * or any sort of reset), every port should be disabled.
10946ee0b270SAlan Stern 		 * Unconnected ports should likewise be disabled (paranoia),
10956ee0b270SAlan Stern 		 * and so should ports for which we have no usb_device.
10965e6effaeSAlan Stern 		 */
10976ee0b270SAlan Stern 		if ((portstatus & USB_PORT_STAT_ENABLE) && (
10986ee0b270SAlan Stern 				type != HUB_RESUME ||
10996ee0b270SAlan Stern 				!(portstatus & USB_PORT_STAT_CONNECTION) ||
11006ee0b270SAlan Stern 				!udev ||
11016ee0b270SAlan Stern 				udev->state == USB_STATE_NOTATTACHED)) {
11029f0a6cd3SAndiry Xu 			/*
11039f0a6cd3SAndiry Xu 			 * USB3 protocol ports will automatically transition
11049f0a6cd3SAndiry Xu 			 * to Enabled state when detect an USB3.0 device attach.
1105fd1ac4cfSDan Williams 			 * Do not disable USB3 protocol ports, just pretend
1106fd1ac4cfSDan Williams 			 * power was lost
11079f0a6cd3SAndiry Xu 			 */
1108fd1ac4cfSDan Williams 			portstatus &= ~USB_PORT_STAT_ENABLE;
1109fd1ac4cfSDan Williams 			if (!hub_is_superspeed(hdev))
1110ad493e5eSLan Tianyu 				usb_clear_port_feature(hdev, port1,
11119f0a6cd3SAndiry Xu 						   USB_PORT_FEAT_ENABLE);
11129f0a6cd3SAndiry Xu 		}
11136ee0b270SAlan Stern 
1114948fea37SAlan Stern 		/* Clear status-change flags; we'll debounce later */
1115948fea37SAlan Stern 		if (portchange & USB_PORT_STAT_C_CONNECTION) {
1116948fea37SAlan Stern 			need_debounce_delay = true;
1117ad493e5eSLan Tianyu 			usb_clear_port_feature(hub->hdev, port1,
1118948fea37SAlan Stern 					USB_PORT_FEAT_C_CONNECTION);
1119948fea37SAlan Stern 		}
1120948fea37SAlan Stern 		if (portchange & USB_PORT_STAT_C_ENABLE) {
1121948fea37SAlan Stern 			need_debounce_delay = true;
1122ad493e5eSLan Tianyu 			usb_clear_port_feature(hub->hdev, port1,
1123948fea37SAlan Stern 					USB_PORT_FEAT_C_ENABLE);
1124948fea37SAlan Stern 		}
1125e92aee33SJulius Werner 		if (portchange & USB_PORT_STAT_C_RESET) {
1126e92aee33SJulius Werner 			need_debounce_delay = true;
1127e92aee33SJulius Werner 			usb_clear_port_feature(hub->hdev, port1,
1128e92aee33SJulius Werner 					USB_PORT_FEAT_C_RESET);
1129e92aee33SJulius Werner 		}
113079c3dd81SDon Zickus 		if ((portchange & USB_PORT_STAT_C_BH_RESET) &&
113179c3dd81SDon Zickus 				hub_is_superspeed(hub->hdev)) {
113279c3dd81SDon Zickus 			need_debounce_delay = true;
1133ad493e5eSLan Tianyu 			usb_clear_port_feature(hub->hdev, port1,
113479c3dd81SDon Zickus 					USB_PORT_FEAT_C_BH_PORT_RESET);
113579c3dd81SDon Zickus 		}
1136253e0572SAlan Stern 		/* We can forget about a "removed" device when there's a
1137253e0572SAlan Stern 		 * physical disconnect or the connect status changes.
1138253e0572SAlan Stern 		 */
1139253e0572SAlan Stern 		if (!(portstatus & USB_PORT_STAT_CONNECTION) ||
1140253e0572SAlan Stern 				(portchange & USB_PORT_STAT_C_CONNECTION))
1141253e0572SAlan Stern 			clear_bit(port1, hub->removed_bits);
1142253e0572SAlan Stern 
11436ee0b270SAlan Stern 		if (!udev || udev->state == USB_STATE_NOTATTACHED) {
114437ebb549SPetr Mladek 			/* Tell hub_wq to disconnect the device or
11456ee0b270SAlan Stern 			 * check for a new connection
11466ee0b270SAlan Stern 			 */
114708d1dec6SShen Guang 			if (udev || (portstatus & USB_PORT_STAT_CONNECTION) ||
114808d1dec6SShen Guang 			    (portstatus & USB_PORT_STAT_OVERCURRENT))
11496ee0b270SAlan Stern 				set_bit(port1, hub->change_bits);
11506ee0b270SAlan Stern 
11516ee0b270SAlan Stern 		} else if (portstatus & USB_PORT_STAT_ENABLE) {
115272937e1eSSarah Sharp 			bool port_resumed = (portstatus &
115372937e1eSSarah Sharp 					USB_PORT_STAT_LINK_STATE) ==
115472937e1eSSarah Sharp 				USB_SS_PORT_LS_U0;
11556ee0b270SAlan Stern 			/* The power session apparently survived the resume.
11566ee0b270SAlan Stern 			 * If there was an overcurrent or suspend change
115737ebb549SPetr Mladek 			 * (i.e., remote wakeup request), have hub_wq
115872937e1eSSarah Sharp 			 * take care of it.  Look at the port link state
115972937e1eSSarah Sharp 			 * for USB 3.0 hubs, since they don't have a suspend
116072937e1eSSarah Sharp 			 * change bit, and they don't set the port link change
116172937e1eSSarah Sharp 			 * bit on device-initiated resume.
11626ee0b270SAlan Stern 			 */
116372937e1eSSarah Sharp 			if (portchange || (hub_is_superspeed(hub->hdev) &&
116472937e1eSSarah Sharp 						port_resumed))
11656ee0b270SAlan Stern 				set_bit(port1, hub->change_bits);
11666ee0b270SAlan Stern 
11676ee0b270SAlan Stern 		} else if (udev->persist_enabled) {
11686ee0b270SAlan Stern #ifdef CONFIG_PM
11695e6effaeSAlan Stern 			udev->reset_resume = 1;
11706ee0b270SAlan Stern #endif
1171ad493e5eSLan Tianyu 			/* Don't set the change_bits when the device
1172ad493e5eSLan Tianyu 			 * was powered off.
1173ad493e5eSLan Tianyu 			 */
1174d5c3834eSDan Williams 			if (test_bit(port1, hub->power_bits))
11758808f00cSAlan Stern 				set_bit(port1, hub->change_bits);
11768808f00cSAlan Stern 
11776ee0b270SAlan Stern 		} else {
117837ebb549SPetr Mladek 			/* The power session is gone; tell hub_wq */
11796ee0b270SAlan Stern 			usb_set_device_state(udev, USB_STATE_NOTATTACHED);
11806ee0b270SAlan Stern 			set_bit(port1, hub->change_bits);
11815e6effaeSAlan Stern 		}
11825e6effaeSAlan Stern 	}
11835e6effaeSAlan Stern 
1184948fea37SAlan Stern 	/* If no port-status-change flags were set, we don't need any
1185948fea37SAlan Stern 	 * debouncing.  If flags were set we can try to debounce the
118637ebb549SPetr Mladek 	 * ports all at once right now, instead of letting hub_wq do them
1187948fea37SAlan Stern 	 * one at a time later on.
1188948fea37SAlan Stern 	 *
118937ebb549SPetr Mladek 	 * If any port-status changes do occur during this delay, hub_wq
1190948fea37SAlan Stern 	 * will see them later and handle them normally.
1191948fea37SAlan Stern 	 */
11928520f380SAlan Stern 	if (need_debounce_delay) {
11938520f380SAlan Stern 		delay = HUB_DEBOUNCE_STABLE;
1194f2835219SAlan Stern 
11958520f380SAlan Stern 		/* Don't do a long sleep inside a workqueue routine */
11968520f380SAlan Stern 		if (type == HUB_INIT2) {
119777fa83cfSTejun Heo 			INIT_DELAYED_WORK(&hub->init_work, hub_init_func3);
119822f6a0f0SShaibal Dutta 			queue_delayed_work(system_power_efficient_wq,
119922f6a0f0SShaibal Dutta 					&hub->init_work,
12008520f380SAlan Stern 					msecs_to_jiffies(delay));
120107d316a2SAlan Stern 			device_unlock(&hdev->dev);
12028520f380SAlan Stern 			return;		/* Continues at init3: below */
12038520f380SAlan Stern 		} else {
12048520f380SAlan Stern 			msleep(delay);
12058520f380SAlan Stern 		}
12068520f380SAlan Stern 	}
12078520f380SAlan Stern  init3:
1208f2835219SAlan Stern 	hub->quiescing = 0;
1209f2835219SAlan Stern 
1210f2835219SAlan Stern 	status = usb_submit_urb(hub->urb, GFP_NOIO);
1211f2835219SAlan Stern 	if (status < 0)
1212f2835219SAlan Stern 		dev_err(hub->intfdev, "activate --> %d\n", status);
1213f2835219SAlan Stern 	if (hub->has_indicators && blinkenlights)
121422f6a0f0SShaibal Dutta 		queue_delayed_work(system_power_efficient_wq,
121522f6a0f0SShaibal Dutta 				&hub->leds, LED_CYCLE_PERIOD);
1216f2835219SAlan Stern 
1217f2835219SAlan Stern 	/* Scan all ports that need attention */
121832a69589SPetr Mladek 	kick_hub_wq(hub);
1219245b2eecSGuenter Roeck  abort:
1220ca5cbc8bSAlan Stern 	if (type == HUB_INIT2 || type == HUB_INIT3) {
12218e4ceb38SAlan Stern 		/* Allow autosuspend if it was suppressed */
1222ca5cbc8bSAlan Stern  disconnected:
12238e4ceb38SAlan Stern 		usb_autopm_put_interface_async(to_usb_interface(hub->intfdev));
122407d316a2SAlan Stern 		device_unlock(&hdev->dev);
1225ca5cbc8bSAlan Stern 	}
1226e50293efSAlan Stern 
1227e50293efSAlan Stern 	kref_put(&hub->kref, hub_release);
12285e6effaeSAlan Stern }
12295e6effaeSAlan Stern 
12308520f380SAlan Stern /* Implement the continuations for the delays above */
12318520f380SAlan Stern static void hub_init_func2(struct work_struct *ws)
12328520f380SAlan Stern {
12338520f380SAlan Stern 	struct usb_hub *hub = container_of(ws, struct usb_hub, init_work.work);
12348520f380SAlan Stern 
12358520f380SAlan Stern 	hub_activate(hub, HUB_INIT2);
12368520f380SAlan Stern }
12378520f380SAlan Stern 
12388520f380SAlan Stern static void hub_init_func3(struct work_struct *ws)
12398520f380SAlan Stern {
12408520f380SAlan Stern 	struct usb_hub *hub = container_of(ws, struct usb_hub, init_work.work);
12418520f380SAlan Stern 
12428520f380SAlan Stern 	hub_activate(hub, HUB_INIT3);
12438520f380SAlan Stern }
12448520f380SAlan Stern 
12454330354fSAlan Stern enum hub_quiescing_type {
12464330354fSAlan Stern 	HUB_DISCONNECT, HUB_PRE_RESET, HUB_SUSPEND
12474330354fSAlan Stern };
12484330354fSAlan Stern 
12494330354fSAlan Stern static void hub_quiesce(struct usb_hub *hub, enum hub_quiescing_type type)
12504330354fSAlan Stern {
12514330354fSAlan Stern 	struct usb_device *hdev = hub->hdev;
12524330354fSAlan Stern 	int i;
12534330354fSAlan Stern 
125437ebb549SPetr Mladek 	/* hub_wq and related activity won't re-trigger */
12554330354fSAlan Stern 	hub->quiescing = 1;
12564330354fSAlan Stern 
12574330354fSAlan Stern 	if (type != HUB_SUSPEND) {
12584330354fSAlan Stern 		/* Disconnect all the children */
12594330354fSAlan Stern 		for (i = 0; i < hdev->maxchild; ++i) {
1260ff823c79SLan Tianyu 			if (hub->ports[i]->child)
1261ff823c79SLan Tianyu 				usb_disconnect(&hub->ports[i]->child);
12624330354fSAlan Stern 		}
12634330354fSAlan Stern 	}
12644330354fSAlan Stern 
126537ebb549SPetr Mladek 	/* Stop hub_wq and related activity */
12664330354fSAlan Stern 	usb_kill_urb(hub->urb);
12674330354fSAlan Stern 	if (hub->has_indicators)
12684330354fSAlan Stern 		cancel_delayed_work_sync(&hub->leds);
12694330354fSAlan Stern 	if (hub->tt.hub)
1270036546bfSOctavian Purdila 		flush_work(&hub->tt.clear_work);
12714330354fSAlan Stern }
12724330354fSAlan Stern 
1273600856c2SAlan Stern static void hub_pm_barrier_for_all_ports(struct usb_hub *hub)
1274600856c2SAlan Stern {
1275600856c2SAlan Stern 	int i;
1276600856c2SAlan Stern 
1277600856c2SAlan Stern 	for (i = 0; i < hub->hdev->maxchild; ++i)
1278600856c2SAlan Stern 		pm_runtime_barrier(&hub->ports[i]->dev);
1279600856c2SAlan Stern }
1280600856c2SAlan Stern 
12813eb14915SAlan Stern /* caller has locked the hub device */
12823eb14915SAlan Stern static int hub_pre_reset(struct usb_interface *intf)
12833eb14915SAlan Stern {
12843eb14915SAlan Stern 	struct usb_hub *hub = usb_get_intfdata(intf);
12853eb14915SAlan Stern 
12864330354fSAlan Stern 	hub_quiesce(hub, HUB_PRE_RESET);
1287600856c2SAlan Stern 	hub->in_reset = 1;
1288600856c2SAlan Stern 	hub_pm_barrier_for_all_ports(hub);
1289f07600cfSAlan Stern 	return 0;
12907d069b7dSAlan Stern }
12917d069b7dSAlan Stern 
12927d069b7dSAlan Stern /* caller has locked the hub device */
1293f07600cfSAlan Stern static int hub_post_reset(struct usb_interface *intf)
12947d069b7dSAlan Stern {
12957de18d8bSAlan Stern 	struct usb_hub *hub = usb_get_intfdata(intf);
12967de18d8bSAlan Stern 
1297600856c2SAlan Stern 	hub->in_reset = 0;
1298600856c2SAlan Stern 	hub_pm_barrier_for_all_ports(hub);
1299f2835219SAlan Stern 	hub_activate(hub, HUB_POST_RESET);
1300f07600cfSAlan Stern 	return 0;
13017d069b7dSAlan Stern }
13027d069b7dSAlan Stern 
13031da177e4SLinus Torvalds static int hub_configure(struct usb_hub *hub,
13041da177e4SLinus Torvalds 	struct usb_endpoint_descriptor *endpoint)
13051da177e4SLinus Torvalds {
1306b356b7c7SSarah Sharp 	struct usb_hcd *hcd;
13071da177e4SLinus Torvalds 	struct usb_device *hdev = hub->hdev;
13081da177e4SLinus Torvalds 	struct device *hub_dev = hub->intfdev;
13091da177e4SLinus Torvalds 	u16 hubstatus, hubchange;
131074ad9bd2SGreg Kroah-Hartman 	u16 wHubCharacteristics;
13111da177e4SLinus Torvalds 	unsigned int pipe;
1312fa2a9566SLan Tianyu 	int maxp, ret, i;
13137cbe5dcaSAlan Stern 	char *message = "out of memory";
1314430ee58eSSebastian Andrzej Siewior 	unsigned unit_load;
1315430ee58eSSebastian Andrzej Siewior 	unsigned full_load;
1316d8521afeSDan Williams 	unsigned maxchild;
13171da177e4SLinus Torvalds 
1318d697cddaSAlan Stern 	hub->buffer = kmalloc(sizeof(*hub->buffer), GFP_KERNEL);
13191da177e4SLinus Torvalds 	if (!hub->buffer) {
13201da177e4SLinus Torvalds 		ret = -ENOMEM;
13211da177e4SLinus Torvalds 		goto fail;
13221da177e4SLinus Torvalds 	}
13231da177e4SLinus Torvalds 
13241da177e4SLinus Torvalds 	hub->status = kmalloc(sizeof(*hub->status), GFP_KERNEL);
13251da177e4SLinus Torvalds 	if (!hub->status) {
13261da177e4SLinus Torvalds 		ret = -ENOMEM;
13271da177e4SLinus Torvalds 		goto fail;
13281da177e4SLinus Torvalds 	}
1329db90e7a1SAlan Stern 	mutex_init(&hub->status_mutex);
13301da177e4SLinus Torvalds 
1331bec444cdSJohan Hovold 	hub->descriptor = kzalloc(sizeof(*hub->descriptor), GFP_KERNEL);
13321da177e4SLinus Torvalds 	if (!hub->descriptor) {
13331da177e4SLinus Torvalds 		ret = -ENOMEM;
13341da177e4SLinus Torvalds 		goto fail;
13351da177e4SLinus Torvalds 	}
13361da177e4SLinus Torvalds 
13371da177e4SLinus Torvalds 	/* Request the entire hub descriptor.
13381da177e4SLinus Torvalds 	 * hub->descriptor can handle USB_MAXCHILDREN ports,
13392c25a2c8SJohan Hovold 	 * but a (non-SS) hub can/will return fewer bytes here.
13401da177e4SLinus Torvalds 	 */
1341dbe79bbeSJohn Youn 	ret = get_hub_descriptor(hdev, hub->descriptor);
13421da177e4SLinus Torvalds 	if (ret < 0) {
13431da177e4SLinus Torvalds 		message = "can't read hub descriptor";
13441da177e4SLinus Torvalds 		goto fail;
134593491cedSJohan Hovold 	}
134693491cedSJohan Hovold 
134793491cedSJohan Hovold 	maxchild = USB_MAXCHILDREN;
134893491cedSJohan Hovold 	if (hub_is_superspeed(hdev))
134993491cedSJohan Hovold 		maxchild = min_t(unsigned, maxchild, USB_SS_MAXPORTS);
135093491cedSJohan Hovold 
135193491cedSJohan Hovold 	if (hub->descriptor->bNbrPorts > maxchild) {
13521da177e4SLinus Torvalds 		message = "hub has too many ports!";
13531da177e4SLinus Torvalds 		ret = -ENODEV;
13541da177e4SLinus Torvalds 		goto fail;
1355769d7368SDavid Linares 	} else if (hub->descriptor->bNbrPorts == 0) {
1356769d7368SDavid Linares 		message = "hub doesn't have any ports!";
1357769d7368SDavid Linares 		ret = -ENODEV;
1358769d7368SDavid Linares 		goto fail;
13591da177e4SLinus Torvalds 	}
13601da177e4SLinus Torvalds 
1361886ee36eSFelipe Balbi 	/*
1362886ee36eSFelipe Balbi 	 * Accumulate wHubDelay + 40ns for every hub in the tree of devices.
1363886ee36eSFelipe Balbi 	 * The resulting value will be used for SetIsochDelay() request.
1364886ee36eSFelipe Balbi 	 */
1365886ee36eSFelipe Balbi 	if (hub_is_superspeed(hdev) || hub_is_superspeedplus(hdev)) {
1366886ee36eSFelipe Balbi 		u32 delay = __le16_to_cpu(hub->descriptor->u.ss.wHubDelay);
1367886ee36eSFelipe Balbi 
1368886ee36eSFelipe Balbi 		if (hdev->parent)
1369886ee36eSFelipe Balbi 			delay += hdev->parent->hub_delay;
1370886ee36eSFelipe Balbi 
1371886ee36eSFelipe Balbi 		delay += USB_TP_TRANSMISSION_DELAY;
1372886ee36eSFelipe Balbi 		hdev->hub_delay = min_t(u32, delay, USB_TP_TRANSMISSION_DELAY_MAX);
1373886ee36eSFelipe Balbi 	}
1374886ee36eSFelipe Balbi 
1375d8521afeSDan Williams 	maxchild = hub->descriptor->bNbrPorts;
1376d8521afeSDan Williams 	dev_info(hub_dev, "%d port%s detected\n", maxchild,
1377d8521afeSDan Williams 			(maxchild == 1) ? "" : "s");
13781da177e4SLinus Torvalds 
13796396bb22SKees Cook 	hub->ports = kcalloc(maxchild, sizeof(struct usb_port *), GFP_KERNEL);
1380ff823c79SLan Tianyu 	if (!hub->ports) {
13817cbe5dcaSAlan Stern 		ret = -ENOMEM;
13827cbe5dcaSAlan Stern 		goto fail;
13837cbe5dcaSAlan Stern 	}
13847cbe5dcaSAlan Stern 
138574ad9bd2SGreg Kroah-Hartman 	wHubCharacteristics = le16_to_cpu(hub->descriptor->wHubCharacteristics);
1386430ee58eSSebastian Andrzej Siewior 	if (hub_is_superspeed(hdev)) {
1387430ee58eSSebastian Andrzej Siewior 		unit_load = 150;
1388430ee58eSSebastian Andrzej Siewior 		full_load = 900;
1389430ee58eSSebastian Andrzej Siewior 	} else {
1390430ee58eSSebastian Andrzej Siewior 		unit_load = 100;
1391430ee58eSSebastian Andrzej Siewior 		full_load = 500;
1392430ee58eSSebastian Andrzej Siewior 	}
13931da177e4SLinus Torvalds 
1394dbe79bbeSJohn Youn 	/* FIXME for USB 3.0, skip for now */
1395dbe79bbeSJohn Youn 	if ((wHubCharacteristics & HUB_CHAR_COMPOUND) &&
1396dbe79bbeSJohn Youn 			!(hub_is_superspeed(hdev))) {
13971da177e4SLinus Torvalds 		char	portstr[USB_MAXCHILDREN + 1];
13981da177e4SLinus Torvalds 
1399d8521afeSDan Williams 		for (i = 0; i < maxchild; i++)
1400dbe79bbeSJohn Youn 			portstr[i] = hub->descriptor->u.hs.DeviceRemovable
14011da177e4SLinus Torvalds 				    [((i + 1) / 8)] & (1 << ((i + 1) % 8))
14021da177e4SLinus Torvalds 				? 'F' : 'R';
1403d8521afeSDan Williams 		portstr[maxchild] = 0;
14041da177e4SLinus Torvalds 		dev_dbg(hub_dev, "compound device; port removable status: %s\n", portstr);
14051da177e4SLinus Torvalds 	} else
14061da177e4SLinus Torvalds 		dev_dbg(hub_dev, "standalone hub\n");
14071da177e4SLinus Torvalds 
140874ad9bd2SGreg Kroah-Hartman 	switch (wHubCharacteristics & HUB_CHAR_LPSM) {
14097bf01185SAman Deep 	case HUB_CHAR_COMMON_LPSM:
14101da177e4SLinus Torvalds 		dev_dbg(hub_dev, "ganged power switching\n");
14111da177e4SLinus Torvalds 		break;
14127bf01185SAman Deep 	case HUB_CHAR_INDV_PORT_LPSM:
14131da177e4SLinus Torvalds 		dev_dbg(hub_dev, "individual port power switching\n");
14141da177e4SLinus Torvalds 		break;
14157bf01185SAman Deep 	case HUB_CHAR_NO_LPSM:
14167bf01185SAman Deep 	case HUB_CHAR_LPSM:
14171da177e4SLinus Torvalds 		dev_dbg(hub_dev, "no power switching (usb 1.0)\n");
14181da177e4SLinus Torvalds 		break;
14191da177e4SLinus Torvalds 	}
14201da177e4SLinus Torvalds 
142174ad9bd2SGreg Kroah-Hartman 	switch (wHubCharacteristics & HUB_CHAR_OCPM) {
14227bf01185SAman Deep 	case HUB_CHAR_COMMON_OCPM:
14231da177e4SLinus Torvalds 		dev_dbg(hub_dev, "global over-current protection\n");
14241da177e4SLinus Torvalds 		break;
14257bf01185SAman Deep 	case HUB_CHAR_INDV_PORT_OCPM:
14261da177e4SLinus Torvalds 		dev_dbg(hub_dev, "individual port over-current protection\n");
14271da177e4SLinus Torvalds 		break;
14287bf01185SAman Deep 	case HUB_CHAR_NO_OCPM:
14297bf01185SAman Deep 	case HUB_CHAR_OCPM:
14301da177e4SLinus Torvalds 		dev_dbg(hub_dev, "no over-current protection\n");
14311da177e4SLinus Torvalds 		break;
14321da177e4SLinus Torvalds 	}
14331da177e4SLinus Torvalds 
14341da177e4SLinus Torvalds 	spin_lock_init(&hub->tt.lock);
14351da177e4SLinus Torvalds 	INIT_LIST_HEAD(&hub->tt.clear_list);
1436cb88a1b8SAlan Stern 	INIT_WORK(&hub->tt.clear_work, hub_tt_work);
14371da177e4SLinus Torvalds 	switch (hdev->descriptor.bDeviceProtocol) {
14387bf01185SAman Deep 	case USB_HUB_PR_FS:
14391da177e4SLinus Torvalds 		break;
14407bf01185SAman Deep 	case USB_HUB_PR_HS_SINGLE_TT:
14411da177e4SLinus Torvalds 		dev_dbg(hub_dev, "Single TT\n");
14421da177e4SLinus Torvalds 		hub->tt.hub = hdev;
14431da177e4SLinus Torvalds 		break;
14447bf01185SAman Deep 	case USB_HUB_PR_HS_MULTI_TT:
14451da177e4SLinus Torvalds 		ret = usb_set_interface(hdev, 0, 1);
14461da177e4SLinus Torvalds 		if (ret == 0) {
14471da177e4SLinus Torvalds 			dev_dbg(hub_dev, "TT per port\n");
14481da177e4SLinus Torvalds 			hub->tt.multi = 1;
14491da177e4SLinus Torvalds 		} else
14501da177e4SLinus Torvalds 			dev_err(hub_dev, "Using single TT (err %d)\n",
14511da177e4SLinus Torvalds 				ret);
14521da177e4SLinus Torvalds 		hub->tt.hub = hdev;
14531da177e4SLinus Torvalds 		break;
14547bf01185SAman Deep 	case USB_HUB_PR_SS:
1455d2e9b4d6SSarah Sharp 		/* USB 3.0 hubs don't have a TT */
1456d2e9b4d6SSarah Sharp 		break;
14571da177e4SLinus Torvalds 	default:
14581da177e4SLinus Torvalds 		dev_dbg(hub_dev, "Unrecognized hub protocol %d\n",
14591da177e4SLinus Torvalds 			hdev->descriptor.bDeviceProtocol);
14601da177e4SLinus Torvalds 		break;
14611da177e4SLinus Torvalds 	}
14621da177e4SLinus Torvalds 
1463e09711aeSdavid-b@pacbell.net 	/* Note 8 FS bit times == (8 bits / 12000000 bps) ~= 666ns */
146474ad9bd2SGreg Kroah-Hartman 	switch (wHubCharacteristics & HUB_CHAR_TTTT) {
1465e09711aeSdavid-b@pacbell.net 	case HUB_TTTT_8_BITS:
1466e09711aeSdavid-b@pacbell.net 		if (hdev->descriptor.bDeviceProtocol != 0) {
1467e09711aeSdavid-b@pacbell.net 			hub->tt.think_time = 666;
1468e09711aeSdavid-b@pacbell.net 			dev_dbg(hub_dev, "TT requires at most %d "
1469e09711aeSdavid-b@pacbell.net 					"FS bit times (%d ns)\n",
1470e09711aeSdavid-b@pacbell.net 				8, hub->tt.think_time);
1471e09711aeSdavid-b@pacbell.net 		}
14721da177e4SLinus Torvalds 		break;
1473e09711aeSdavid-b@pacbell.net 	case HUB_TTTT_16_BITS:
1474e09711aeSdavid-b@pacbell.net 		hub->tt.think_time = 666 * 2;
1475e09711aeSdavid-b@pacbell.net 		dev_dbg(hub_dev, "TT requires at most %d "
1476e09711aeSdavid-b@pacbell.net 				"FS bit times (%d ns)\n",
1477e09711aeSdavid-b@pacbell.net 			16, hub->tt.think_time);
14781da177e4SLinus Torvalds 		break;
1479e09711aeSdavid-b@pacbell.net 	case HUB_TTTT_24_BITS:
1480e09711aeSdavid-b@pacbell.net 		hub->tt.think_time = 666 * 3;
1481e09711aeSdavid-b@pacbell.net 		dev_dbg(hub_dev, "TT requires at most %d "
1482e09711aeSdavid-b@pacbell.net 				"FS bit times (%d ns)\n",
1483e09711aeSdavid-b@pacbell.net 			24, hub->tt.think_time);
14841da177e4SLinus Torvalds 		break;
1485e09711aeSdavid-b@pacbell.net 	case HUB_TTTT_32_BITS:
1486e09711aeSdavid-b@pacbell.net 		hub->tt.think_time = 666 * 4;
1487e09711aeSdavid-b@pacbell.net 		dev_dbg(hub_dev, "TT requires at most %d "
1488e09711aeSdavid-b@pacbell.net 				"FS bit times (%d ns)\n",
1489e09711aeSdavid-b@pacbell.net 			32, hub->tt.think_time);
14901da177e4SLinus Torvalds 		break;
14911da177e4SLinus Torvalds 	}
14921da177e4SLinus Torvalds 
14931da177e4SLinus Torvalds 	/* probe() zeroes hub->indicator[] */
149474ad9bd2SGreg Kroah-Hartman 	if (wHubCharacteristics & HUB_CHAR_PORTIND) {
14951da177e4SLinus Torvalds 		hub->has_indicators = 1;
14961da177e4SLinus Torvalds 		dev_dbg(hub_dev, "Port indicators are supported\n");
14971da177e4SLinus Torvalds 	}
14981da177e4SLinus Torvalds 
14991da177e4SLinus Torvalds 	dev_dbg(hub_dev, "power on to power good time: %dms\n",
15001da177e4SLinus Torvalds 		hub->descriptor->bPwrOn2PwrGood * 2);
15011da177e4SLinus Torvalds 
15021da177e4SLinus Torvalds 	/* power budgeting mostly matters with bus-powered hubs,
15031da177e4SLinus Torvalds 	 * and battery-powered root hubs (may provide just 8 mA).
15041da177e4SLinus Torvalds 	 */
1505d9e1e148SFelipe Balbi 	ret = usb_get_std_status(hdev, USB_RECIP_DEVICE, 0, &hubstatus);
150615b7336eSAlan Stern 	if (ret) {
15071da177e4SLinus Torvalds 		message = "can't get hub status";
15081da177e4SLinus Torvalds 		goto fail;
15091da177e4SLinus Torvalds 	}
1510430ee58eSSebastian Andrzej Siewior 	hcd = bus_to_hcd(hdev->bus);
15117d35b929SAlan Stern 	if (hdev == hdev->bus->root_hub) {
1512430ee58eSSebastian Andrzej Siewior 		if (hcd->power_budget > 0)
1513430ee58eSSebastian Andrzej Siewior 			hdev->bus_mA = hcd->power_budget;
1514430ee58eSSebastian Andrzej Siewior 		else
1515d8521afeSDan Williams 			hdev->bus_mA = full_load * maxchild;
1516430ee58eSSebastian Andrzej Siewior 		if (hdev->bus_mA >= full_load)
1517430ee58eSSebastian Andrzej Siewior 			hub->mA_per_port = full_load;
151855c52718SAlan Stern 		else {
151955c52718SAlan Stern 			hub->mA_per_port = hdev->bus_mA;
152055c52718SAlan Stern 			hub->limited_power = 1;
152155c52718SAlan Stern 		}
15227d35b929SAlan Stern 	} else if ((hubstatus & (1 << USB_DEVICE_SELF_POWERED)) == 0) {
152355c52718SAlan Stern 		int remaining = hdev->bus_mA -
152455c52718SAlan Stern 			hub->descriptor->bHubContrCurrent;
15251da177e4SLinus Torvalds 
1526430ee58eSSebastian Andrzej Siewior 		dev_dbg(hub_dev, "hub controller current requirement: %dmA\n",
1527430ee58eSSebastian Andrzej Siewior 			hub->descriptor->bHubContrCurrent);
1528430ee58eSSebastian Andrzej Siewior 		hub->limited_power = 1;
1529430ee58eSSebastian Andrzej Siewior 
1530d8521afeSDan Williams 		if (remaining < maxchild * unit_load)
153155c52718SAlan Stern 			dev_warn(hub_dev,
153255c52718SAlan Stern 					"insufficient power available "
153355c52718SAlan Stern 					"to use all downstream ports\n");
1534430ee58eSSebastian Andrzej Siewior 		hub->mA_per_port = unit_load;	/* 7.2.1 */
1535430ee58eSSebastian Andrzej Siewior 
153655c52718SAlan Stern 	} else {	/* Self-powered external hub */
153755c52718SAlan Stern 		/* FIXME: What about battery-powered external hubs that
153855c52718SAlan Stern 		 * provide less current per port? */
1539430ee58eSSebastian Andrzej Siewior 		hub->mA_per_port = full_load;
154055c52718SAlan Stern 	}
1541430ee58eSSebastian Andrzej Siewior 	if (hub->mA_per_port < full_load)
154255c52718SAlan Stern 		dev_dbg(hub_dev, "%umA bus power budget for each child\n",
154355c52718SAlan Stern 				hub->mA_per_port);
15441da177e4SLinus Torvalds 
15451da177e4SLinus Torvalds 	ret = hub_hub_status(hub, &hubstatus, &hubchange);
15461da177e4SLinus Torvalds 	if (ret < 0) {
15471da177e4SLinus Torvalds 		message = "can't get hub status";
15481da177e4SLinus Torvalds 		goto fail;
15491da177e4SLinus Torvalds 	}
15501da177e4SLinus Torvalds 
15511da177e4SLinus Torvalds 	/* local power status reports aren't always correct */
15521da177e4SLinus Torvalds 	if (hdev->actconfig->desc.bmAttributes & USB_CONFIG_ATT_SELFPOWER)
15531da177e4SLinus Torvalds 		dev_dbg(hub_dev, "local power source is %s\n",
15541da177e4SLinus Torvalds 			(hubstatus & HUB_STATUS_LOCAL_POWER)
15551da177e4SLinus Torvalds 			? "lost (inactive)" : "good");
15561da177e4SLinus Torvalds 
155774ad9bd2SGreg Kroah-Hartman 	if ((wHubCharacteristics & HUB_CHAR_OCPM) == 0)
15581da177e4SLinus Torvalds 		dev_dbg(hub_dev, "%sover-current condition exists\n",
15591da177e4SLinus Torvalds 			(hubstatus & HUB_STATUS_OVERCURRENT) ? "" : "no ");
15601da177e4SLinus Torvalds 
156188fafff9Sinaky@linux.intel.com 	/* set up the interrupt endpoint
156288fafff9Sinaky@linux.intel.com 	 * We use the EP's maxpacket size instead of (PORTS+1+7)/8
156388fafff9Sinaky@linux.intel.com 	 * bytes as USB2.0[11.12.3] says because some hubs are known
156488fafff9Sinaky@linux.intel.com 	 * to send more data (and thus cause overflow). For root hubs,
156588fafff9Sinaky@linux.intel.com 	 * maxpktsize is defined in hcd.c's fake endpoint descriptors
156688fafff9Sinaky@linux.intel.com 	 * to be big enough for at least USB_MAXCHILDREN ports. */
15671da177e4SLinus Torvalds 	pipe = usb_rcvintpipe(hdev, endpoint->bEndpointAddress);
15681da177e4SLinus Torvalds 	maxp = usb_maxpacket(hdev, pipe, usb_pipeout(pipe));
15691da177e4SLinus Torvalds 
15701da177e4SLinus Torvalds 	if (maxp > sizeof(*hub->buffer))
15711da177e4SLinus Torvalds 		maxp = sizeof(*hub->buffer);
15721da177e4SLinus Torvalds 
15731da177e4SLinus Torvalds 	hub->urb = usb_alloc_urb(0, GFP_KERNEL);
15741da177e4SLinus Torvalds 	if (!hub->urb) {
15751da177e4SLinus Torvalds 		ret = -ENOMEM;
15761da177e4SLinus Torvalds 		goto fail;
15771da177e4SLinus Torvalds 	}
15781da177e4SLinus Torvalds 
15791da177e4SLinus Torvalds 	usb_fill_int_urb(hub->urb, hdev, pipe, *hub->buffer, maxp, hub_irq,
15801da177e4SLinus Torvalds 		hub, endpoint->bInterval);
15811da177e4SLinus Torvalds 
15821da177e4SLinus Torvalds 	/* maybe cycle the hub leds */
15831da177e4SLinus Torvalds 	if (hub->has_indicators && blinkenlights)
15841da177e4SLinus Torvalds 		hub->indicator[0] = INDICATOR_CYCLE;
15851da177e4SLinus Torvalds 
1586d8521afeSDan Williams 	mutex_lock(&usb_port_peer_mutex);
1587d8521afeSDan Williams 	for (i = 0; i < maxchild; i++) {
1588e58547ebSKrzysztof Mazur 		ret = usb_hub_create_port_device(hub, i + 1);
1589e58547ebSKrzysztof Mazur 		if (ret < 0) {
1590fa2a9566SLan Tianyu 			dev_err(hub->intfdev,
1591fa2a9566SLan Tianyu 				"couldn't create port%d device.\n", i + 1);
1592d8521afeSDan Williams 			break;
1593d8521afeSDan Williams 		}
1594d8521afeSDan Williams 	}
1595e58547ebSKrzysztof Mazur 	hdev->maxchild = i;
1596e3d10505SDan Williams 	for (i = 0; i < hdev->maxchild; i++) {
1597e3d10505SDan Williams 		struct usb_port *port_dev = hub->ports[i];
1598e3d10505SDan Williams 
1599e3d10505SDan Williams 		pm_runtime_put(&port_dev->dev);
1600e3d10505SDan Williams 	}
1601e3d10505SDan Williams 
1602d8521afeSDan Williams 	mutex_unlock(&usb_port_peer_mutex);
1603d8521afeSDan Williams 	if (ret < 0)
1604d8521afeSDan Williams 		goto fail;
1605fa2a9566SLan Tianyu 
160637ebb549SPetr Mladek 	/* Update the HCD's internal representation of this hub before hub_wq
1607e3d95580SDan Williams 	 * starts getting port status changes for devices under the hub.
1608e3d95580SDan Williams 	 */
1609e3d95580SDan Williams 	if (hcd->driver->update_hub_device) {
1610e3d95580SDan Williams 		ret = hcd->driver->update_hub_device(hcd, hdev,
1611e3d95580SDan Williams 				&hub->tt, GFP_KERNEL);
1612e3d95580SDan Williams 		if (ret < 0) {
1613e3d95580SDan Williams 			message = "can't update HCD hub info";
1614e3d95580SDan Williams 			goto fail;
1615e3d95580SDan Williams 		}
1616e3d95580SDan Williams 	}
1617e3d95580SDan Williams 
1618d2123fd9SLan Tianyu 	usb_hub_adjust_deviceremovable(hdev, hub->descriptor);
1619d2123fd9SLan Tianyu 
1620f2835219SAlan Stern 	hub_activate(hub, HUB_INIT);
16211da177e4SLinus Torvalds 	return 0;
16221da177e4SLinus Torvalds 
16231da177e4SLinus Torvalds fail:
16241da177e4SLinus Torvalds 	dev_err(hub_dev, "config failed, %s (err %d)\n",
16251da177e4SLinus Torvalds 			message, ret);
16261da177e4SLinus Torvalds 	/* hub_disconnect() frees urb and descriptor */
16271da177e4SLinus Torvalds 	return ret;
16281da177e4SLinus Torvalds }
16291da177e4SLinus Torvalds 
1630e8054854SAlan Stern static void hub_release(struct kref *kref)
1631e8054854SAlan Stern {
1632e8054854SAlan Stern 	struct usb_hub *hub = container_of(kref, struct usb_hub, kref);
1633e8054854SAlan Stern 
16345d14f323SPetr Mladek 	usb_put_dev(hub->hdev);
1635e8054854SAlan Stern 	usb_put_intf(to_usb_interface(hub->intfdev));
1636e8054854SAlan Stern 	kfree(hub);
1637e8054854SAlan Stern }
1638e8054854SAlan Stern 
16391da177e4SLinus Torvalds static unsigned highspeed_hubs;
16401da177e4SLinus Torvalds 
16411da177e4SLinus Torvalds static void hub_disconnect(struct usb_interface *intf)
16421da177e4SLinus Torvalds {
16431da177e4SLinus Torvalds 	struct usb_hub *hub = usb_get_intfdata(intf);
1644fa286188SGreg Kroah-Hartman 	struct usb_device *hdev = interface_to_usbdev(intf);
1645543d7784SAlan Stern 	int port1;
1646fa2a9566SLan Tianyu 
164732a69589SPetr Mladek 	/*
164832a69589SPetr Mladek 	 * Stop adding new hub events. We do not want to block here and thus
164932a69589SPetr Mladek 	 * will not try to remove any pending work item.
165032a69589SPetr Mladek 	 */
1651e8054854SAlan Stern 	hub->disconnected = 1;
16521da177e4SLinus Torvalds 
16537de18d8bSAlan Stern 	/* Disconnect all children and quiesce the hub */
16547de18d8bSAlan Stern 	hub->error = 0;
16554330354fSAlan Stern 	hub_quiesce(hub, HUB_DISCONNECT);
16567de18d8bSAlan Stern 
1657d8521afeSDan Williams 	mutex_lock(&usb_port_peer_mutex);
1658d8521afeSDan Williams 
1659543d7784SAlan Stern 	/* Avoid races with recursively_mark_NOTATTACHED() */
1660543d7784SAlan Stern 	spin_lock_irq(&device_state_lock);
1661543d7784SAlan Stern 	port1 = hdev->maxchild;
1662543d7784SAlan Stern 	hdev->maxchild = 0;
16638b28c752SAlan Stern 	usb_set_intfdata(intf, NULL);
1664543d7784SAlan Stern 	spin_unlock_irq(&device_state_lock);
16651f2235b8SAlexander Shishkin 
1666543d7784SAlan Stern 	for (; port1 > 0; --port1)
1667543d7784SAlan Stern 		usb_hub_remove_port_device(hub, port1);
16681da177e4SLinus Torvalds 
1669d8521afeSDan Williams 	mutex_unlock(&usb_port_peer_mutex);
1670d8521afeSDan Williams 
1671e8054854SAlan Stern 	if (hub->hdev->speed == USB_SPEED_HIGH)
16721da177e4SLinus Torvalds 		highspeed_hubs--;
16731da177e4SLinus Torvalds 
16741da177e4SLinus Torvalds 	usb_free_urb(hub->urb);
1675fa2a9566SLan Tianyu 	kfree(hub->ports);
16761da177e4SLinus Torvalds 	kfree(hub->descriptor);
16771da177e4SLinus Torvalds 	kfree(hub->status);
1678d697cddaSAlan Stern 	kfree(hub->buffer);
16791da177e4SLinus Torvalds 
1680971fcd49SLan Tianyu 	pm_suspend_ignore_children(&intf->dev, false);
1681e8054854SAlan Stern 	kref_put(&hub->kref, hub_release);
16821da177e4SLinus Torvalds }
16831da177e4SLinus Torvalds 
1684c94dc34fSEugene Korenevsky static bool hub_descriptor_is_sane(struct usb_host_interface *desc)
1685c94dc34fSEugene Korenevsky {
1686c94dc34fSEugene Korenevsky 	/* Some hubs have a subclass of 1, which AFAICT according to the */
1687c94dc34fSEugene Korenevsky 	/*  specs is not defined, but it works */
1688c94dc34fSEugene Korenevsky 	if (desc->desc.bInterfaceSubClass != 0 &&
1689c94dc34fSEugene Korenevsky 	    desc->desc.bInterfaceSubClass != 1)
1690c94dc34fSEugene Korenevsky 		return false;
1691c94dc34fSEugene Korenevsky 
1692c94dc34fSEugene Korenevsky 	/* Multiple endpoints? What kind of mutant ninja-hub is this? */
1693c94dc34fSEugene Korenevsky 	if (desc->desc.bNumEndpoints != 1)
1694c94dc34fSEugene Korenevsky 		return false;
1695c94dc34fSEugene Korenevsky 
1696c94dc34fSEugene Korenevsky 	/* If the first endpoint is not interrupt IN, we'd better punt! */
1697c94dc34fSEugene Korenevsky 	if (!usb_endpoint_is_int_in(&desc->endpoint[0].desc))
1698c94dc34fSEugene Korenevsky 		return false;
1699c94dc34fSEugene Korenevsky 
1700c94dc34fSEugene Korenevsky         return true;
1701c94dc34fSEugene Korenevsky }
1702c94dc34fSEugene Korenevsky 
17031da177e4SLinus Torvalds static int hub_probe(struct usb_interface *intf, const struct usb_device_id *id)
17041da177e4SLinus Torvalds {
17051da177e4SLinus Torvalds 	struct usb_host_interface *desc;
17061da177e4SLinus Torvalds 	struct usb_device *hdev;
17071da177e4SLinus Torvalds 	struct usb_hub *hub;
17081da177e4SLinus Torvalds 
17091da177e4SLinus Torvalds 	desc = intf->cur_altsetting;
17101da177e4SLinus Torvalds 	hdev = interface_to_usbdev(intf);
17111da177e4SLinus Torvalds 
1712596d789aSMing Lei 	/*
1713596d789aSMing Lei 	 * Set default autosuspend delay as 0 to speedup bus suspend,
1714596d789aSMing Lei 	 * based on the below considerations:
1715596d789aSMing Lei 	 *
1716596d789aSMing Lei 	 * - Unlike other drivers, the hub driver does not rely on the
1717596d789aSMing Lei 	 *   autosuspend delay to provide enough time to handle a wakeup
1718596d789aSMing Lei 	 *   event, and the submitted status URB is just to check future
1719596d789aSMing Lei 	 *   change on hub downstream ports, so it is safe to do it.
1720596d789aSMing Lei 	 *
1721596d789aSMing Lei 	 * - The patch might cause one or more auto supend/resume for
1722596d789aSMing Lei 	 *   below very rare devices when they are plugged into hub
1723596d789aSMing Lei 	 *   first time:
1724596d789aSMing Lei 	 *
1725596d789aSMing Lei 	 *   	devices having trouble initializing, and disconnect
1726596d789aSMing Lei 	 *   	themselves from the bus and then reconnect a second
1727596d789aSMing Lei 	 *   	or so later
1728596d789aSMing Lei 	 *
1729596d789aSMing Lei 	 *   	devices just for downloading firmware, and disconnects
1730596d789aSMing Lei 	 *   	themselves after completing it
1731596d789aSMing Lei 	 *
1732596d789aSMing Lei 	 *   For these quite rare devices, their drivers may change the
1733596d789aSMing Lei 	 *   autosuspend delay of their parent hub in the probe() to one
1734596d789aSMing Lei 	 *   appropriate value to avoid the subtle problem if someone
1735596d789aSMing Lei 	 *   does care it.
1736596d789aSMing Lei 	 *
1737596d789aSMing Lei 	 * - The patch may cause one or more auto suspend/resume on
1738596d789aSMing Lei 	 *   hub during running 'lsusb', but it is probably too
1739596d789aSMing Lei 	 *   infrequent to worry about.
1740596d789aSMing Lei 	 *
1741596d789aSMing Lei 	 * - Change autosuspend delay of hub can avoid unnecessary auto
1742596d789aSMing Lei 	 *   suspend timer for hub, also may decrease power consumption
1743596d789aSMing Lei 	 *   of USB bus.
1744bdd405d2SRoger Quadros 	 *
1745bdd405d2SRoger Quadros 	 * - If user has indicated to prevent autosuspend by passing
1746bdd405d2SRoger Quadros 	 *   usbcore.autosuspend = -1 then keep autosuspend disabled.
1747596d789aSMing Lei 	 */
1748ceb6c9c8SRafael J. Wysocki #ifdef CONFIG_PM
1749bdd405d2SRoger Quadros 	if (hdev->dev.power.autosuspend_delay >= 0)
1750596d789aSMing Lei 		pm_runtime_set_autosuspend_delay(&hdev->dev, 0);
1751a9ef803dSGreg Kroah-Hartman #endif
1752596d789aSMing Lei 
17538ef42dddSAlan Stern 	/*
17548ef42dddSAlan Stern 	 * Hubs have proper suspend/resume support, except for root hubs
17558ef42dddSAlan Stern 	 * where the controller driver doesn't have bus_suspend and
17568ef42dddSAlan Stern 	 * bus_resume methods.
17578ef42dddSAlan Stern 	 */
17588ef42dddSAlan Stern 	if (hdev->parent) {		/* normal device */
1759088f7fecSAlan Stern 		usb_enable_autosuspend(hdev);
17608ef42dddSAlan Stern 	} else {			/* root hub */
17618ef42dddSAlan Stern 		const struct hc_driver *drv = bus_to_hcd(hdev->bus)->driver;
17628ef42dddSAlan Stern 
17638ef42dddSAlan Stern 		if (drv->bus_suspend && drv->bus_resume)
17648ef42dddSAlan Stern 			usb_enable_autosuspend(hdev);
17658ef42dddSAlan Stern 	}
1766088f7fecSAlan Stern 
176738f3ad5eSFelipe Balbi 	if (hdev->level == MAX_TOPO_LEVEL) {
1768b9cef6c3SWu Fengguang 		dev_err(&intf->dev,
1769b9cef6c3SWu Fengguang 			"Unsupported bus topology: hub nested too deep\n");
177038f3ad5eSFelipe Balbi 		return -E2BIG;
177138f3ad5eSFelipe Balbi 	}
177238f3ad5eSFelipe Balbi 
177389ccbdc9SDavid Brownell #ifdef	CONFIG_USB_OTG_BLACKLIST_HUB
177489ccbdc9SDavid Brownell 	if (hdev->parent) {
177589ccbdc9SDavid Brownell 		dev_warn(&intf->dev, "ignoring external hub\n");
177689ccbdc9SDavid Brownell 		return -ENODEV;
177789ccbdc9SDavid Brownell 	}
177889ccbdc9SDavid Brownell #endif
177989ccbdc9SDavid Brownell 
1780c94dc34fSEugene Korenevsky 	if (!hub_descriptor_is_sane(desc)) {
17811da177e4SLinus Torvalds 		dev_err(&intf->dev, "bad descriptor, ignoring hub\n");
17821da177e4SLinus Torvalds 		return -EIO;
17831da177e4SLinus Torvalds 	}
17841da177e4SLinus Torvalds 
17851da177e4SLinus Torvalds 	/* We found a hub */
17861da177e4SLinus Torvalds 	dev_info(&intf->dev, "USB hub found\n");
17871da177e4SLinus Torvalds 
17880a1ef3b5SAlan Stern 	hub = kzalloc(sizeof(*hub), GFP_KERNEL);
1789b74e7062SWolfram Sang 	if (!hub)
17901da177e4SLinus Torvalds 		return -ENOMEM;
17911da177e4SLinus Torvalds 
1792e8054854SAlan Stern 	kref_init(&hub->kref);
17931da177e4SLinus Torvalds 	hub->intfdev = &intf->dev;
17941da177e4SLinus Torvalds 	hub->hdev = hdev;
1795c4028958SDavid Howells 	INIT_DELAYED_WORK(&hub->leds, led_work);
17968520f380SAlan Stern 	INIT_DELAYED_WORK(&hub->init_work, NULL);
179732a69589SPetr Mladek 	INIT_WORK(&hub->events, hub_event);
1798e8054854SAlan Stern 	usb_get_intf(intf);
17995d14f323SPetr Mladek 	usb_get_dev(hdev);
18001da177e4SLinus Torvalds 
18011da177e4SLinus Torvalds 	usb_set_intfdata(intf, hub);
180240f122f3SAlan Stern 	intf->needs_remote_wakeup = 1;
1803971fcd49SLan Tianyu 	pm_suspend_ignore_children(&intf->dev, true);
18041da177e4SLinus Torvalds 
18051da177e4SLinus Torvalds 	if (hdev->speed == USB_SPEED_HIGH)
18061da177e4SLinus Torvalds 		highspeed_hubs++;
18071da177e4SLinus Torvalds 
1808e6f30deaSMing Lei 	if (id->driver_info & HUB_QUIRK_CHECK_PORT_AUTOSUSPEND)
1809e6f30deaSMing Lei 		hub->quirk_check_port_auto_suspend = 1;
1810e6f30deaSMing Lei 
1811c94dc34fSEugene Korenevsky 	if (hub_configure(hub, &desc->endpoint[0].desc) >= 0)
18121da177e4SLinus Torvalds 		return 0;
18131da177e4SLinus Torvalds 
18141da177e4SLinus Torvalds 	hub_disconnect(intf);
18151da177e4SLinus Torvalds 	return -ENODEV;
18161da177e4SLinus Torvalds }
18171da177e4SLinus Torvalds 
18181da177e4SLinus Torvalds static int
18191da177e4SLinus Torvalds hub_ioctl(struct usb_interface *intf, unsigned int code, void *user_data)
18201da177e4SLinus Torvalds {
18211da177e4SLinus Torvalds 	struct usb_device *hdev = interface_to_usbdev(intf);
1822ad493e5eSLan Tianyu 	struct usb_hub *hub = usb_hub_to_struct_hub(hdev);
18231da177e4SLinus Torvalds 
18241da177e4SLinus Torvalds 	/* assert ifno == 0 (part of hub spec) */
18251da177e4SLinus Torvalds 	switch (code) {
18261da177e4SLinus Torvalds 	case USBDEVFS_HUB_PORTINFO: {
18271da177e4SLinus Torvalds 		struct usbdevfs_hub_portinfo *info = user_data;
18281da177e4SLinus Torvalds 		int i;
18291da177e4SLinus Torvalds 
18301da177e4SLinus Torvalds 		spin_lock_irq(&device_state_lock);
18311da177e4SLinus Torvalds 		if (hdev->devnum <= 0)
18321da177e4SLinus Torvalds 			info->nports = 0;
18331da177e4SLinus Torvalds 		else {
18341da177e4SLinus Torvalds 			info->nports = hdev->maxchild;
18351da177e4SLinus Torvalds 			for (i = 0; i < info->nports; i++) {
1836ff823c79SLan Tianyu 				if (hub->ports[i]->child == NULL)
18371da177e4SLinus Torvalds 					info->port[i] = 0;
18381da177e4SLinus Torvalds 				else
18391da177e4SLinus Torvalds 					info->port[i] =
1840ff823c79SLan Tianyu 						hub->ports[i]->child->devnum;
18411da177e4SLinus Torvalds 			}
18421da177e4SLinus Torvalds 		}
18431da177e4SLinus Torvalds 		spin_unlock_irq(&device_state_lock);
18441da177e4SLinus Torvalds 
18451da177e4SLinus Torvalds 		return info->nports + 1;
18461da177e4SLinus Torvalds 		}
18471da177e4SLinus Torvalds 
18481da177e4SLinus Torvalds 	default:
18491da177e4SLinus Torvalds 		return -ENOSYS;
18501da177e4SLinus Torvalds 	}
18511da177e4SLinus Torvalds }
18521da177e4SLinus Torvalds 
18537cbe5dcaSAlan Stern /*
18547cbe5dcaSAlan Stern  * Allow user programs to claim ports on a hub.  When a device is attached
18557cbe5dcaSAlan Stern  * to one of these "claimed" ports, the program will "own" the device.
18567cbe5dcaSAlan Stern  */
18577cbe5dcaSAlan Stern static int find_port_owner(struct usb_device *hdev, unsigned port1,
18589b6f0c4bSValentina Manea 		struct usb_dev_state ***ppowner)
18597cbe5dcaSAlan Stern {
186041341261SMathias Nyman 	struct usb_hub *hub = usb_hub_to_struct_hub(hdev);
186141341261SMathias Nyman 
18627cbe5dcaSAlan Stern 	if (hdev->state == USB_STATE_NOTATTACHED)
18637cbe5dcaSAlan Stern 		return -ENODEV;
18647cbe5dcaSAlan Stern 	if (port1 == 0 || port1 > hdev->maxchild)
18657cbe5dcaSAlan Stern 		return -EINVAL;
18667cbe5dcaSAlan Stern 
186741341261SMathias Nyman 	/* Devices not managed by the hub driver
18687cbe5dcaSAlan Stern 	 * will always have maxchild equal to 0.
18697cbe5dcaSAlan Stern 	 */
187041341261SMathias Nyman 	*ppowner = &(hub->ports[port1 - 1]->port_owner);
18717cbe5dcaSAlan Stern 	return 0;
18727cbe5dcaSAlan Stern }
18737cbe5dcaSAlan Stern 
18747cbe5dcaSAlan Stern /* In the following three functions, the caller must hold hdev's lock */
1875336c5c31SLan Tianyu int usb_hub_claim_port(struct usb_device *hdev, unsigned port1,
18769b6f0c4bSValentina Manea 		       struct usb_dev_state *owner)
18777cbe5dcaSAlan Stern {
18787cbe5dcaSAlan Stern 	int rc;
18799b6f0c4bSValentina Manea 	struct usb_dev_state **powner;
18807cbe5dcaSAlan Stern 
18817cbe5dcaSAlan Stern 	rc = find_port_owner(hdev, port1, &powner);
18827cbe5dcaSAlan Stern 	if (rc)
18837cbe5dcaSAlan Stern 		return rc;
18847cbe5dcaSAlan Stern 	if (*powner)
18857cbe5dcaSAlan Stern 		return -EBUSY;
18867cbe5dcaSAlan Stern 	*powner = owner;
18877cbe5dcaSAlan Stern 	return rc;
18887cbe5dcaSAlan Stern }
18896080cd0eSValentina Manea EXPORT_SYMBOL_GPL(usb_hub_claim_port);
18907cbe5dcaSAlan Stern 
1891336c5c31SLan Tianyu int usb_hub_release_port(struct usb_device *hdev, unsigned port1,
18929b6f0c4bSValentina Manea 			 struct usb_dev_state *owner)
18937cbe5dcaSAlan Stern {
18947cbe5dcaSAlan Stern 	int rc;
18959b6f0c4bSValentina Manea 	struct usb_dev_state **powner;
18967cbe5dcaSAlan Stern 
18977cbe5dcaSAlan Stern 	rc = find_port_owner(hdev, port1, &powner);
18987cbe5dcaSAlan Stern 	if (rc)
18997cbe5dcaSAlan Stern 		return rc;
19007cbe5dcaSAlan Stern 	if (*powner != owner)
19017cbe5dcaSAlan Stern 		return -ENOENT;
19027cbe5dcaSAlan Stern 	*powner = NULL;
19037cbe5dcaSAlan Stern 	return rc;
19047cbe5dcaSAlan Stern }
19056080cd0eSValentina Manea EXPORT_SYMBOL_GPL(usb_hub_release_port);
19067cbe5dcaSAlan Stern 
19079b6f0c4bSValentina Manea void usb_hub_release_all_ports(struct usb_device *hdev, struct usb_dev_state *owner)
19087cbe5dcaSAlan Stern {
1909ad493e5eSLan Tianyu 	struct usb_hub *hub = usb_hub_to_struct_hub(hdev);
19107cbe5dcaSAlan Stern 	int n;
19117cbe5dcaSAlan Stern 
1912fa2a9566SLan Tianyu 	for (n = 0; n < hdev->maxchild; n++) {
1913fa2a9566SLan Tianyu 		if (hub->ports[n]->port_owner == owner)
1914fa2a9566SLan Tianyu 			hub->ports[n]->port_owner = NULL;
19157cbe5dcaSAlan Stern 	}
1916fa2a9566SLan Tianyu 
19177cbe5dcaSAlan Stern }
19187cbe5dcaSAlan Stern 
19197cbe5dcaSAlan Stern /* The caller must hold udev's lock */
19207cbe5dcaSAlan Stern bool usb_device_is_owned(struct usb_device *udev)
19217cbe5dcaSAlan Stern {
19227cbe5dcaSAlan Stern 	struct usb_hub *hub;
19237cbe5dcaSAlan Stern 
19247cbe5dcaSAlan Stern 	if (udev->state == USB_STATE_NOTATTACHED || !udev->parent)
19257cbe5dcaSAlan Stern 		return false;
1926ad493e5eSLan Tianyu 	hub = usb_hub_to_struct_hub(udev->parent);
1927fa2a9566SLan Tianyu 	return !!hub->ports[udev->portnum - 1]->port_owner;
19287cbe5dcaSAlan Stern }
19297cbe5dcaSAlan Stern 
19301da177e4SLinus Torvalds static void recursively_mark_NOTATTACHED(struct usb_device *udev)
19311da177e4SLinus Torvalds {
1932ad493e5eSLan Tianyu 	struct usb_hub *hub = usb_hub_to_struct_hub(udev);
19331da177e4SLinus Torvalds 	int i;
19341da177e4SLinus Torvalds 
19351da177e4SLinus Torvalds 	for (i = 0; i < udev->maxchild; ++i) {
1936ff823c79SLan Tianyu 		if (hub->ports[i]->child)
1937ff823c79SLan Tianyu 			recursively_mark_NOTATTACHED(hub->ports[i]->child);
19381da177e4SLinus Torvalds 	}
19399bbdf1e0SAlan Stern 	if (udev->state == USB_STATE_SUSPENDED)
194015123006SSarah Sharp 		udev->active_duration -= jiffies;
19411da177e4SLinus Torvalds 	udev->state = USB_STATE_NOTATTACHED;
19421da177e4SLinus Torvalds }
19431da177e4SLinus Torvalds 
19441da177e4SLinus Torvalds /**
19451da177e4SLinus Torvalds  * usb_set_device_state - change a device's current state (usbcore, hcds)
19461da177e4SLinus Torvalds  * @udev: pointer to device whose state should be changed
19471da177e4SLinus Torvalds  * @new_state: new state value to be stored
19481da177e4SLinus Torvalds  *
19491da177e4SLinus Torvalds  * udev->state is _not_ fully protected by the device lock.  Although
19501da177e4SLinus Torvalds  * most transitions are made only while holding the lock, the state can
19511da177e4SLinus Torvalds  * can change to USB_STATE_NOTATTACHED at almost any time.  This
19521da177e4SLinus Torvalds  * is so that devices can be marked as disconnected as soon as possible,
19531da177e4SLinus Torvalds  * without having to wait for any semaphores to be released.  As a result,
19541da177e4SLinus Torvalds  * all changes to any device's state must be protected by the
19551da177e4SLinus Torvalds  * device_state_lock spinlock.
19561da177e4SLinus Torvalds  *
19571da177e4SLinus Torvalds  * Once a device has been added to the device tree, all changes to its state
19581da177e4SLinus Torvalds  * should be made using this routine.  The state should _not_ be set directly.
19591da177e4SLinus Torvalds  *
19601da177e4SLinus Torvalds  * If udev->state is already USB_STATE_NOTATTACHED then no change is made.
19611da177e4SLinus Torvalds  * Otherwise udev->state is set to new_state, and if new_state is
19621da177e4SLinus Torvalds  * USB_STATE_NOTATTACHED then all of udev's descendants' states are also set
19631da177e4SLinus Torvalds  * to USB_STATE_NOTATTACHED.
19641da177e4SLinus Torvalds  */
19651da177e4SLinus Torvalds void usb_set_device_state(struct usb_device *udev,
19661da177e4SLinus Torvalds 		enum usb_device_state new_state)
19671da177e4SLinus Torvalds {
19681da177e4SLinus Torvalds 	unsigned long flags;
19694681b171SRafael J. Wysocki 	int wakeup = -1;
19701da177e4SLinus Torvalds 
19711da177e4SLinus Torvalds 	spin_lock_irqsave(&device_state_lock, flags);
19721da177e4SLinus Torvalds 	if (udev->state == USB_STATE_NOTATTACHED)
19731da177e4SLinus Torvalds 		;	/* do nothing */
1974b94dc6b5SDavid Brownell 	else if (new_state != USB_STATE_NOTATTACHED) {
1975fb669cc0SDavid Brownell 
1976fb669cc0SDavid Brownell 		/* root hub wakeup capabilities are managed out-of-band
1977fb669cc0SDavid Brownell 		 * and may involve silicon errata ... ignore them here.
1978fb669cc0SDavid Brownell 		 */
1979fb669cc0SDavid Brownell 		if (udev->parent) {
1980645daaabSAlan Stern 			if (udev->state == USB_STATE_SUSPENDED
1981645daaabSAlan Stern 					|| new_state == USB_STATE_SUSPENDED)
1982645daaabSAlan Stern 				;	/* No change to wakeup settings */
1983645daaabSAlan Stern 			else if (new_state == USB_STATE_CONFIGURED)
1984ddbe1fcaSLu Baolu 				wakeup = (udev->quirks &
1985ddbe1fcaSLu Baolu 					USB_QUIRK_IGNORE_REMOTE_WAKEUP) ? 0 :
1986ddbe1fcaSLu Baolu 					udev->actconfig->desc.bmAttributes &
1987ddbe1fcaSLu Baolu 					USB_CONFIG_ATT_WAKEUP;
1988645daaabSAlan Stern 			else
19894681b171SRafael J. Wysocki 				wakeup = 0;
1990fb669cc0SDavid Brownell 		}
199115123006SSarah Sharp 		if (udev->state == USB_STATE_SUSPENDED &&
199215123006SSarah Sharp 			new_state != USB_STATE_SUSPENDED)
199315123006SSarah Sharp 			udev->active_duration -= jiffies;
199415123006SSarah Sharp 		else if (new_state == USB_STATE_SUSPENDED &&
199515123006SSarah Sharp 				udev->state != USB_STATE_SUSPENDED)
199615123006SSarah Sharp 			udev->active_duration += jiffies;
1997645daaabSAlan Stern 		udev->state = new_state;
1998b94dc6b5SDavid Brownell 	} else
19991da177e4SLinus Torvalds 		recursively_mark_NOTATTACHED(udev);
20001da177e4SLinus Torvalds 	spin_unlock_irqrestore(&device_state_lock, flags);
20014681b171SRafael J. Wysocki 	if (wakeup >= 0)
20024681b171SRafael J. Wysocki 		device_set_wakeup_capable(&udev->dev, wakeup);
20031da177e4SLinus Torvalds }
20046da9c990SDavid Vrabel EXPORT_SYMBOL_GPL(usb_set_device_state);
20051da177e4SLinus Torvalds 
20068af548dcSInaky Perez-Gonzalez /*
20073b29b68bSAlan Stern  * Choose a device number.
20083b29b68bSAlan Stern  *
20093b29b68bSAlan Stern  * Device numbers are used as filenames in usbfs.  On USB-1.1 and
20103b29b68bSAlan Stern  * USB-2.0 buses they are also used as device addresses, however on
20113b29b68bSAlan Stern  * USB-3.0 buses the address is assigned by the controller hardware
20123b29b68bSAlan Stern  * and it usually is not the same as the device number.
20133b29b68bSAlan Stern  *
20148af548dcSInaky Perez-Gonzalez  * WUSB devices are simple: they have no hubs behind, so the mapping
20158af548dcSInaky Perez-Gonzalez  * device <-> virtual port number becomes 1:1. Why? to simplify the
20168af548dcSInaky Perez-Gonzalez  * life of the device connection logic in
20178af548dcSInaky Perez-Gonzalez  * drivers/usb/wusbcore/devconnect.c. When we do the initial secret
20188af548dcSInaky Perez-Gonzalez  * handshake we need to assign a temporary address in the unauthorized
20198af548dcSInaky Perez-Gonzalez  * space. For simplicity we use the first virtual port number found to
20208af548dcSInaky Perez-Gonzalez  * be free [drivers/usb/wusbcore/devconnect.c:wusbhc_devconnect_ack()]
20218af548dcSInaky Perez-Gonzalez  * and that becomes it's address [X < 128] or its unauthorized address
20228af548dcSInaky Perez-Gonzalez  * [X | 0x80].
20238af548dcSInaky Perez-Gonzalez  *
20248af548dcSInaky Perez-Gonzalez  * We add 1 as an offset to the one-based USB-stack port number
20258af548dcSInaky Perez-Gonzalez  * (zero-based wusb virtual port index) for two reasons: (a) dev addr
20268af548dcSInaky Perez-Gonzalez  * 0 is reserved by USB for default address; (b) Linux's USB stack
20278af548dcSInaky Perez-Gonzalez  * uses always #1 for the root hub of the controller. So USB stack's
20288af548dcSInaky Perez-Gonzalez  * port #1, which is wusb virtual-port #0 has address #2.
2029c6515272SSarah Sharp  *
2030c6515272SSarah Sharp  * Devices connected under xHCI are not as simple.  The host controller
2031c6515272SSarah Sharp  * supports virtualization, so the hardware assigns device addresses and
2032c6515272SSarah Sharp  * the HCD must setup data structures before issuing a set address
2033c6515272SSarah Sharp  * command to the hardware.
20348af548dcSInaky Perez-Gonzalez  */
20353b29b68bSAlan Stern static void choose_devnum(struct usb_device *udev)
20361da177e4SLinus Torvalds {
20371da177e4SLinus Torvalds 	int		devnum;
20381da177e4SLinus Torvalds 	struct usb_bus	*bus = udev->bus;
20391da177e4SLinus Torvalds 
2040638139ebSPetr Mladek 	/* be safe when more hub events are proceed in parallel */
2041feb26ac3SChris Bainbridge 	mutex_lock(&bus->devnum_next_mutex);
20428af548dcSInaky Perez-Gonzalez 	if (udev->wusb) {
20438af548dcSInaky Perez-Gonzalez 		devnum = udev->portnum + 1;
20448af548dcSInaky Perez-Gonzalez 		BUG_ON(test_bit(devnum, bus->devmap.devicemap));
20458af548dcSInaky Perez-Gonzalez 	} else {
20468af548dcSInaky Perez-Gonzalez 		/* Try to allocate the next devnum beginning at
20478af548dcSInaky Perez-Gonzalez 		 * bus->devnum_next. */
20481da177e4SLinus Torvalds 		devnum = find_next_zero_bit(bus->devmap.devicemap, 128,
20491da177e4SLinus Torvalds 					    bus->devnum_next);
20501da177e4SLinus Torvalds 		if (devnum >= 128)
20518af548dcSInaky Perez-Gonzalez 			devnum = find_next_zero_bit(bus->devmap.devicemap,
20528af548dcSInaky Perez-Gonzalez 						    128, 1);
20531da177e4SLinus Torvalds 		bus->devnum_next = (devnum >= 127 ? 1 : devnum + 1);
20548af548dcSInaky Perez-Gonzalez 	}
20551da177e4SLinus Torvalds 	if (devnum < 128) {
20561da177e4SLinus Torvalds 		set_bit(devnum, bus->devmap.devicemap);
20571da177e4SLinus Torvalds 		udev->devnum = devnum;
20581da177e4SLinus Torvalds 	}
2059feb26ac3SChris Bainbridge 	mutex_unlock(&bus->devnum_next_mutex);
20601da177e4SLinus Torvalds }
20611da177e4SLinus Torvalds 
20623b29b68bSAlan Stern static void release_devnum(struct usb_device *udev)
20631da177e4SLinus Torvalds {
20641da177e4SLinus Torvalds 	if (udev->devnum > 0) {
20651da177e4SLinus Torvalds 		clear_bit(udev->devnum, udev->bus->devmap.devicemap);
20661da177e4SLinus Torvalds 		udev->devnum = -1;
20671da177e4SLinus Torvalds 	}
20681da177e4SLinus Torvalds }
20691da177e4SLinus Torvalds 
20703b29b68bSAlan Stern static void update_devnum(struct usb_device *udev, int devnum)
20714953d141SDavid Vrabel {
20724953d141SDavid Vrabel 	/* The address for a WUSB device is managed by wusbcore. */
20734953d141SDavid Vrabel 	if (!udev->wusb)
20744953d141SDavid Vrabel 		udev->devnum = devnum;
20754953d141SDavid Vrabel }
20764953d141SDavid Vrabel 
2077f7410cedSHerbert Xu static void hub_free_dev(struct usb_device *udev)
2078f7410cedSHerbert Xu {
2079f7410cedSHerbert Xu 	struct usb_hcd *hcd = bus_to_hcd(udev->bus);
2080f7410cedSHerbert Xu 
2081f7410cedSHerbert Xu 	/* Root hubs aren't real devices, so don't free HCD resources */
2082f7410cedSHerbert Xu 	if (hcd->driver->free_dev && udev->parent)
2083f7410cedSHerbert Xu 		hcd->driver->free_dev(hcd, udev);
2084f7410cedSHerbert Xu }
2085f7410cedSHerbert Xu 
20867027df36SDan Williams static void hub_disconnect_children(struct usb_device *udev)
20877027df36SDan Williams {
20887027df36SDan Williams 	struct usb_hub *hub = usb_hub_to_struct_hub(udev);
20897027df36SDan Williams 	int i;
20907027df36SDan Williams 
20917027df36SDan Williams 	/* Free up all the children before we remove this device */
20927027df36SDan Williams 	for (i = 0; i < udev->maxchild; i++) {
20937027df36SDan Williams 		if (hub->ports[i]->child)
20947027df36SDan Williams 			usb_disconnect(&hub->ports[i]->child);
20957027df36SDan Williams 	}
20967027df36SDan Williams }
20977027df36SDan Williams 
20981da177e4SLinus Torvalds /**
20991da177e4SLinus Torvalds  * usb_disconnect - disconnect a device (usbcore-internal)
21001da177e4SLinus Torvalds  * @pdev: pointer to device being disconnected
21011da177e4SLinus Torvalds  * Context: !in_interrupt ()
21021da177e4SLinus Torvalds  *
21031da177e4SLinus Torvalds  * Something got disconnected. Get rid of it and all of its children.
21041da177e4SLinus Torvalds  *
21051da177e4SLinus Torvalds  * If *pdev is a normal device then the parent hub must already be locked.
2106a4b5d606SHeiner Kallweit  * If *pdev is a root hub then the caller must hold the usb_bus_idr_lock,
2107db8f2aa3SBjorn Helgaas  * which protects the set of root hubs as well as the list of buses.
21081da177e4SLinus Torvalds  *
21091da177e4SLinus Torvalds  * Only hub drivers (including virtual root hub drivers for host
21101da177e4SLinus Torvalds  * controllers) should ever call this.
21111da177e4SLinus Torvalds  *
21121da177e4SLinus Torvalds  * This call is synchronous, and may not be used in an interrupt context.
21131da177e4SLinus Torvalds  */
21141da177e4SLinus Torvalds void usb_disconnect(struct usb_device **pdev)
21151da177e4SLinus Torvalds {
21167027df36SDan Williams 	struct usb_port *port_dev = NULL;
21171da177e4SLinus Torvalds 	struct usb_device *udev = *pdev;
21185b1dc209SPeter Chen 	struct usb_hub *hub = NULL;
21195b1dc209SPeter Chen 	int port1 = 1;
21201da177e4SLinus Torvalds 
21211da177e4SLinus Torvalds 	/* mark the device as inactive, so any further urb submissions for
21221da177e4SLinus Torvalds 	 * this device (and any of its children) will fail immediately.
212325985edcSLucas De Marchi 	 * this quiesces everything except pending urbs.
21241da177e4SLinus Torvalds 	 */
21251da177e4SLinus Torvalds 	usb_set_device_state(udev, USB_STATE_NOTATTACHED);
21263b29b68bSAlan Stern 	dev_info(&udev->dev, "USB disconnect, device number %d\n",
21273b29b68bSAlan Stern 			udev->devnum);
21281da177e4SLinus Torvalds 
2129f5cccf49SGuenter Roeck 	/*
2130f5cccf49SGuenter Roeck 	 * Ensure that the pm runtime code knows that the USB device
2131f5cccf49SGuenter Roeck 	 * is in the process of being disconnected.
2132f5cccf49SGuenter Roeck 	 */
2133f5cccf49SGuenter Roeck 	pm_runtime_barrier(&udev->dev);
2134f5cccf49SGuenter Roeck 
21359ad3d6ccSAlan Stern 	usb_lock_device(udev);
21369ad3d6ccSAlan Stern 
21377027df36SDan Williams 	hub_disconnect_children(udev);
21381da177e4SLinus Torvalds 
21391da177e4SLinus Torvalds 	/* deallocate hcd/hardware state ... nuking all pending urbs and
21401da177e4SLinus Torvalds 	 * cleaning up all state associated with the current configuration
21411da177e4SLinus Torvalds 	 * so that the hardware is now fully quiesced.
21421da177e4SLinus Torvalds 	 */
2143782da727SAlan Stern 	dev_dbg(&udev->dev, "unregistering device\n");
21441da177e4SLinus Torvalds 	usb_disable_device(udev, 0);
2145cde217a5SAlan Stern 	usb_hcd_synchronize_unlinks(udev);
21461da177e4SLinus Torvalds 
2147fde26380SLan Tianyu 	if (udev->parent) {
21487027df36SDan Williams 		port1 = udev->portnum;
21497027df36SDan Williams 		hub = usb_hub_to_struct_hub(udev->parent);
21507027df36SDan Williams 		port_dev = hub->ports[port1 - 1];
2151fde26380SLan Tianyu 
2152fde26380SLan Tianyu 		sysfs_remove_link(&udev->dev.kobj, "port");
2153fde26380SLan Tianyu 		sysfs_remove_link(&port_dev->dev.kobj, "device");
2154971fcd49SLan Tianyu 
21557027df36SDan Williams 		/*
21567027df36SDan Williams 		 * As usb_port_runtime_resume() de-references udev, make
21577027df36SDan Williams 		 * sure no resumes occur during removal
21587027df36SDan Williams 		 */
21597027df36SDan Williams 		if (!test_and_set_bit(port1, hub->child_usage_bits))
21607027df36SDan Williams 			pm_runtime_get_sync(&port_dev->dev);
2161fde26380SLan Tianyu 	}
2162fde26380SLan Tianyu 
21633b23dd6fSAlan Stern 	usb_remove_ep_devs(&udev->ep0);
2164782da727SAlan Stern 	usb_unlock_device(udev);
21653099e75aSGreg Kroah-Hartman 
2166782da727SAlan Stern 	/* Unregister the device.  The device driver is responsible
21673b23dd6fSAlan Stern 	 * for de-configuring the device and invoking the remove-device
21683b23dd6fSAlan Stern 	 * notifier chain (used by usbfs and possibly others).
2169782da727SAlan Stern 	 */
2170782da727SAlan Stern 	device_del(&udev->dev);
2171782da727SAlan Stern 
2172782da727SAlan Stern 	/* Free the device number and delete the parent's children[]
21731da177e4SLinus Torvalds 	 * (or root_hub) pointer.
21741da177e4SLinus Torvalds 	 */
21753b29b68bSAlan Stern 	release_devnum(udev);
21761da177e4SLinus Torvalds 
21771da177e4SLinus Torvalds 	/* Avoid races with recursively_mark_NOTATTACHED() */
21781da177e4SLinus Torvalds 	spin_lock_irq(&device_state_lock);
21791da177e4SLinus Torvalds 	*pdev = NULL;
21801da177e4SLinus Torvalds 	spin_unlock_irq(&device_state_lock);
21811da177e4SLinus Torvalds 
21827027df36SDan Williams 	if (port_dev && test_and_clear_bit(port1, hub->child_usage_bits))
21837027df36SDan Williams 		pm_runtime_put(&port_dev->dev);
21847027df36SDan Williams 
2185f7410cedSHerbert Xu 	hub_free_dev(udev);
2186f7410cedSHerbert Xu 
2187782da727SAlan Stern 	put_device(&udev->dev);
21881da177e4SLinus Torvalds }
21891da177e4SLinus Torvalds 
2190f2a383e4SGreg Kroah-Hartman #ifdef CONFIG_USB_ANNOUNCE_NEW_DEVICES
21911da177e4SLinus Torvalds static void show_string(struct usb_device *udev, char *id, char *string)
21921da177e4SLinus Torvalds {
21931da177e4SLinus Torvalds 	if (!string)
21941da177e4SLinus Torvalds 		return;
2195f2ec522eSJoe Perches 	dev_info(&udev->dev, "%s: %s\n", id, string);
21961da177e4SLinus Torvalds }
21971da177e4SLinus Torvalds 
2198f2a383e4SGreg Kroah-Hartman static void announce_device(struct usb_device *udev)
2199f2a383e4SGreg Kroah-Hartman {
220073c6d3b2SBenson Leung 	u16 bcdDevice = le16_to_cpu(udev->descriptor.bcdDevice);
220173c6d3b2SBenson Leung 
220273c6d3b2SBenson Leung 	dev_info(&udev->dev,
220373c6d3b2SBenson Leung 		"New USB device found, idVendor=%04x, idProduct=%04x, bcdDevice=%2x.%02x\n",
2204f2a383e4SGreg Kroah-Hartman 		le16_to_cpu(udev->descriptor.idVendor),
220573c6d3b2SBenson Leung 		le16_to_cpu(udev->descriptor.idProduct),
220673c6d3b2SBenson Leung 		bcdDevice >> 8, bcdDevice & 0xff);
2207b9cef6c3SWu Fengguang 	dev_info(&udev->dev,
2208b9cef6c3SWu Fengguang 		"New USB device strings: Mfr=%d, Product=%d, SerialNumber=%d\n",
2209f2a383e4SGreg Kroah-Hartman 		udev->descriptor.iManufacturer,
2210f2a383e4SGreg Kroah-Hartman 		udev->descriptor.iProduct,
2211f2a383e4SGreg Kroah-Hartman 		udev->descriptor.iSerialNumber);
2212f2a383e4SGreg Kroah-Hartman 	show_string(udev, "Product", udev->product);
2213f2a383e4SGreg Kroah-Hartman 	show_string(udev, "Manufacturer", udev->manufacturer);
2214f2a383e4SGreg Kroah-Hartman 	show_string(udev, "SerialNumber", udev->serial);
2215f2a383e4SGreg Kroah-Hartman }
22161da177e4SLinus Torvalds #else
2217f2a383e4SGreg Kroah-Hartman static inline void announce_device(struct usb_device *udev) { }
22181da177e4SLinus Torvalds #endif
22191da177e4SLinus Torvalds 
22201da177e4SLinus Torvalds 
22213ede760fSOliver Neukum /**
22228d8558d1SAlan Stern  * usb_enumerate_device_otg - FIXME (usbcore-internal)
22233ede760fSOliver Neukum  * @udev: newly addressed device (in ADDRESS state)
22243ede760fSOliver Neukum  *
22258d8558d1SAlan Stern  * Finish enumeration for On-The-Go devices
2226626f090cSYacine Belkadi  *
2227626f090cSYacine Belkadi  * Return: 0 if successful. A negative error code otherwise.
22283ede760fSOliver Neukum  */
22298d8558d1SAlan Stern static int usb_enumerate_device_otg(struct usb_device *udev)
22301da177e4SLinus Torvalds {
2231d9d16e8aSInaky Perez-Gonzalez 	int err = 0;
22321da177e4SLinus Torvalds 
22331da177e4SLinus Torvalds #ifdef	CONFIG_USB_OTG
22341da177e4SLinus Torvalds 	/*
22351da177e4SLinus Torvalds 	 * OTG-aware devices on OTG-capable root hubs may be able to use SRP,
22361da177e4SLinus Torvalds 	 * to wake us after we've powered off VBUS; and HNP, switching roles
22371da177e4SLinus Torvalds 	 * "host" to "peripheral".  The OTG descriptor helps figure this out.
22381da177e4SLinus Torvalds 	 */
22391da177e4SLinus Torvalds 	if (!udev->bus->is_b_host
22401da177e4SLinus Torvalds 			&& udev->config
22411da177e4SLinus Torvalds 			&& udev->parent == udev->bus->root_hub) {
22422eb5052eSFelipe Balbi 		struct usb_otg_descriptor	*desc = NULL;
22431da177e4SLinus Torvalds 		struct usb_bus			*bus = udev->bus;
224412c3da34SAlan Stern 		unsigned			port1 = udev->portnum;
22451da177e4SLinus Torvalds 
22467d2d641cSLi Jun 		/* descriptor may appear anywhere in config */
22477d2d641cSLi Jun 		err = __usb_get_extra_descriptor(udev->rawdescriptors[0],
22487d2d641cSLi Jun 				le16_to_cpu(udev->config[0].desc.wTotalLength),
22497d2d641cSLi Jun 				USB_DT_OTG, (void **) &desc);
22507d2d641cSLi Jun 		if (err || !(desc->bmAttributes & USB_OTG_HNP))
22517d2d641cSLi Jun 			return 0;
22527d2d641cSLi Jun 
22537d2d641cSLi Jun 		dev_info(&udev->dev, "Dual-Role OTG device on %sHNP port\n",
22547d2d641cSLi Jun 					(port1 == bus->otg_port) ? "" : "non-");
22551da177e4SLinus Torvalds 
22561da177e4SLinus Torvalds 		/* enable HNP before suspend, it's simpler */
22577d2d641cSLi Jun 		if (port1 == bus->otg_port) {
22581da177e4SLinus Torvalds 			bus->b_hnp_enable = 1;
22591da177e4SLinus Torvalds 			err = usb_control_msg(udev,
22601da177e4SLinus Torvalds 				usb_sndctrlpipe(udev, 0),
22611da177e4SLinus Torvalds 				USB_REQ_SET_FEATURE, 0,
22627d2d641cSLi Jun 				USB_DEVICE_B_HNP_ENABLE,
22637d2d641cSLi Jun 				0, NULL, 0,
22647d2d641cSLi Jun 				USB_CTRL_SET_TIMEOUT);
22651da177e4SLinus Torvalds 			if (err < 0) {
22667d2d641cSLi Jun 				/*
22677d2d641cSLi Jun 				 * OTG MESSAGE: report errors here,
22681da177e4SLinus Torvalds 				 * customize to match your product.
22691da177e4SLinus Torvalds 				 */
22707d2d641cSLi Jun 				dev_err(&udev->dev, "can't set HNP mode: %d\n",
22711da177e4SLinus Torvalds 									err);
22721da177e4SLinus Torvalds 				bus->b_hnp_enable = 0;
22731da177e4SLinus Torvalds 			}
22747d2d641cSLi Jun 		} else if (desc->bLength == sizeof
22757d2d641cSLi Jun 				(struct usb_otg_descriptor)) {
22767d2d641cSLi Jun 			/* Set a_alt_hnp_support for legacy otg device */
22777d2d641cSLi Jun 			err = usb_control_msg(udev,
22787d2d641cSLi Jun 				usb_sndctrlpipe(udev, 0),
22797d2d641cSLi Jun 				USB_REQ_SET_FEATURE, 0,
22807d2d641cSLi Jun 				USB_DEVICE_A_ALT_HNP_SUPPORT,
22817d2d641cSLi Jun 				0, NULL, 0,
22827d2d641cSLi Jun 				USB_CTRL_SET_TIMEOUT);
22837d2d641cSLi Jun 			if (err < 0)
22847d2d641cSLi Jun 				dev_err(&udev->dev,
22857d2d641cSLi Jun 					"set a_alt_hnp_support failed: %d\n",
22867d2d641cSLi Jun 					err);
22871da177e4SLinus Torvalds 		}
22881da177e4SLinus Torvalds 	}
22891da177e4SLinus Torvalds #endif
2290d9d16e8aSInaky Perez-Gonzalez 	return err;
2291d9d16e8aSInaky Perez-Gonzalez }
22921da177e4SLinus Torvalds 
2293d9d16e8aSInaky Perez-Gonzalez 
2294d9d16e8aSInaky Perez-Gonzalez /**
22958d8558d1SAlan Stern  * usb_enumerate_device - Read device configs/intfs/otg (usbcore-internal)
2296d9d16e8aSInaky Perez-Gonzalez  * @udev: newly addressed device (in ADDRESS state)
2297d9d16e8aSInaky Perez-Gonzalez  *
2298d9d16e8aSInaky Perez-Gonzalez  * This is only called by usb_new_device() and usb_authorize_device()
2299d9d16e8aSInaky Perez-Gonzalez  * and FIXME -- all comments that apply to them apply here wrt to
2300d9d16e8aSInaky Perez-Gonzalez  * environment.
2301d9d16e8aSInaky Perez-Gonzalez  *
2302d9d16e8aSInaky Perez-Gonzalez  * If the device is WUSB and not authorized, we don't attempt to read
2303d9d16e8aSInaky Perez-Gonzalez  * the string descriptors, as they will be errored out by the device
2304d9d16e8aSInaky Perez-Gonzalez  * until it has been authorized.
2305626f090cSYacine Belkadi  *
2306626f090cSYacine Belkadi  * Return: 0 if successful. A negative error code otherwise.
2307d9d16e8aSInaky Perez-Gonzalez  */
23088d8558d1SAlan Stern static int usb_enumerate_device(struct usb_device *udev)
2309d9d16e8aSInaky Perez-Gonzalez {
2310d9d16e8aSInaky Perez-Gonzalez 	int err;
2311026f3fcbSPeter Chen 	struct usb_hcd *hcd = bus_to_hcd(udev->bus);
2312d9d16e8aSInaky Perez-Gonzalez 
2313d9d16e8aSInaky Perez-Gonzalez 	if (udev->config == NULL) {
2314d9d16e8aSInaky Perez-Gonzalez 		err = usb_get_configuration(udev);
2315d9d16e8aSInaky Perez-Gonzalez 		if (err < 0) {
2316e9e88fb7SAlan Stern 			if (err != -ENODEV)
2317d9d16e8aSInaky Perez-Gonzalez 				dev_err(&udev->dev, "can't read configurations, error %d\n",
2318d9d16e8aSInaky Perez-Gonzalez 						err);
231980da2e0dSLaurent Pinchart 			return err;
2320d9d16e8aSInaky Perez-Gonzalez 		}
2321d9d16e8aSInaky Perez-Gonzalez 	}
232283e83ecbSThomas Pugliese 
2323d9d16e8aSInaky Perez-Gonzalez 	/* read the standard strings and cache them if present */
2324d9d16e8aSInaky Perez-Gonzalez 	udev->product = usb_cache_string(udev, udev->descriptor.iProduct);
2325d9d16e8aSInaky Perez-Gonzalez 	udev->manufacturer = usb_cache_string(udev,
2326d9d16e8aSInaky Perez-Gonzalez 					      udev->descriptor.iManufacturer);
2327d9d16e8aSInaky Perez-Gonzalez 	udev->serial = usb_cache_string(udev, udev->descriptor.iSerialNumber);
232883e83ecbSThomas Pugliese 
23298d8558d1SAlan Stern 	err = usb_enumerate_device_otg(udev);
233080da2e0dSLaurent Pinchart 	if (err < 0)
2331d9d16e8aSInaky Perez-Gonzalez 		return err;
233280da2e0dSLaurent Pinchart 
2333026f3fcbSPeter Chen 	if (IS_ENABLED(CONFIG_USB_OTG_WHITELIST) && hcd->tpl_support &&
2334e5a9d621SPeter Chen 		!is_targeted(udev)) {
2335026f3fcbSPeter Chen 		/* Maybe it can talk to us, though we can't talk to it.
2336026f3fcbSPeter Chen 		 * (Includes HNP test device.)
2337026f3fcbSPeter Chen 		 */
2338e5a9d621SPeter Chen 		if (IS_ENABLED(CONFIG_USB_OTG) && (udev->bus->b_hnp_enable
2339e5a9d621SPeter Chen 			|| udev->bus->is_b_host)) {
2340026f3fcbSPeter Chen 			err = usb_port_suspend(udev, PMSG_AUTO_SUSPEND);
2341026f3fcbSPeter Chen 			if (err < 0)
2342026f3fcbSPeter Chen 				dev_dbg(&udev->dev, "HNP fail, %d\n", err);
2343026f3fcbSPeter Chen 		}
2344026f3fcbSPeter Chen 		return -ENOTSUPP;
2345026f3fcbSPeter Chen 	}
2346026f3fcbSPeter Chen 
234780da2e0dSLaurent Pinchart 	usb_detect_interface_quirks(udev);
234880da2e0dSLaurent Pinchart 
234980da2e0dSLaurent Pinchart 	return 0;
2350d9d16e8aSInaky Perez-Gonzalez }
2351d9d16e8aSInaky Perez-Gonzalez 
2352d35e70d5SMatthew Garrett static void set_usb_port_removable(struct usb_device *udev)
2353d35e70d5SMatthew Garrett {
2354d35e70d5SMatthew Garrett 	struct usb_device *hdev = udev->parent;
2355d35e70d5SMatthew Garrett 	struct usb_hub *hub;
2356d35e70d5SMatthew Garrett 	u8 port = udev->portnum;
2357d35e70d5SMatthew Garrett 	u16 wHubCharacteristics;
2358d35e70d5SMatthew Garrett 	bool removable = true;
2359d35e70d5SMatthew Garrett 
2360d35e70d5SMatthew Garrett 	if (!hdev)
2361d35e70d5SMatthew Garrett 		return;
2362d35e70d5SMatthew Garrett 
2363ad493e5eSLan Tianyu 	hub = usb_hub_to_struct_hub(udev->parent);
2364d35e70d5SMatthew Garrett 
236592bfbf71SMatthew Garrett 	/*
236692bfbf71SMatthew Garrett 	 * If the platform firmware has provided information about a port,
236792bfbf71SMatthew Garrett 	 * use that to determine whether it's removable.
236892bfbf71SMatthew Garrett 	 */
236992bfbf71SMatthew Garrett 	switch (hub->ports[udev->portnum - 1]->connect_type) {
237092bfbf71SMatthew Garrett 	case USB_PORT_CONNECT_TYPE_HOT_PLUG:
237192bfbf71SMatthew Garrett 		udev->removable = USB_DEVICE_REMOVABLE;
237292bfbf71SMatthew Garrett 		return;
237392bfbf71SMatthew Garrett 	case USB_PORT_CONNECT_TYPE_HARD_WIRED:
237458339c2eSMatthew Garrett 	case USB_PORT_NOT_USED:
237592bfbf71SMatthew Garrett 		udev->removable = USB_DEVICE_FIXED;
237692bfbf71SMatthew Garrett 		return;
237758339c2eSMatthew Garrett 	default:
237858339c2eSMatthew Garrett 		break;
237992bfbf71SMatthew Garrett 	}
238092bfbf71SMatthew Garrett 
238192bfbf71SMatthew Garrett 	/*
238292bfbf71SMatthew Garrett 	 * Otherwise, check whether the hub knows whether a port is removable
238392bfbf71SMatthew Garrett 	 * or not
238492bfbf71SMatthew Garrett 	 */
2385d35e70d5SMatthew Garrett 	wHubCharacteristics = le16_to_cpu(hub->descriptor->wHubCharacteristics);
2386d35e70d5SMatthew Garrett 
2387d35e70d5SMatthew Garrett 	if (!(wHubCharacteristics & HUB_CHAR_COMPOUND))
2388d35e70d5SMatthew Garrett 		return;
2389d35e70d5SMatthew Garrett 
2390d35e70d5SMatthew Garrett 	if (hub_is_superspeed(hdev)) {
2391ca3c1539SLan Tianyu 		if (le16_to_cpu(hub->descriptor->u.ss.DeviceRemovable)
2392ca3c1539SLan Tianyu 				& (1 << port))
2393d35e70d5SMatthew Garrett 			removable = false;
2394d35e70d5SMatthew Garrett 	} else {
2395d35e70d5SMatthew Garrett 		if (hub->descriptor->u.hs.DeviceRemovable[port / 8] & (1 << (port % 8)))
2396d35e70d5SMatthew Garrett 			removable = false;
2397d35e70d5SMatthew Garrett 	}
2398d35e70d5SMatthew Garrett 
2399d35e70d5SMatthew Garrett 	if (removable)
2400d35e70d5SMatthew Garrett 		udev->removable = USB_DEVICE_REMOVABLE;
2401d35e70d5SMatthew Garrett 	else
2402d35e70d5SMatthew Garrett 		udev->removable = USB_DEVICE_FIXED;
2403a4204ff0SDan Williams 
2404d35e70d5SMatthew Garrett }
2405d9d16e8aSInaky Perez-Gonzalez 
2406d9d16e8aSInaky Perez-Gonzalez /**
2407d9d16e8aSInaky Perez-Gonzalez  * usb_new_device - perform initial device setup (usbcore-internal)
2408d9d16e8aSInaky Perez-Gonzalez  * @udev: newly addressed device (in ADDRESS state)
2409d9d16e8aSInaky Perez-Gonzalez  *
24108d8558d1SAlan Stern  * This is called with devices which have been detected but not fully
24118d8558d1SAlan Stern  * enumerated.  The device descriptor is available, but not descriptors
2412d9d16e8aSInaky Perez-Gonzalez  * for any device configuration.  The caller must have locked either
2413d9d16e8aSInaky Perez-Gonzalez  * the parent hub (if udev is a normal device) or else the
2414a4b5d606SHeiner Kallweit  * usb_bus_idr_lock (if udev is a root hub).  The parent's pointer to
2415d9d16e8aSInaky Perez-Gonzalez  * udev has already been installed, but udev is not yet visible through
2416d9d16e8aSInaky Perez-Gonzalez  * sysfs or other filesystem code.
2417d9d16e8aSInaky Perez-Gonzalez  *
2418d9d16e8aSInaky Perez-Gonzalez  * This call is synchronous, and may not be used in an interrupt context.
2419d9d16e8aSInaky Perez-Gonzalez  *
2420d9d16e8aSInaky Perez-Gonzalez  * Only the hub driver or root-hub registrar should ever call this.
2421626f090cSYacine Belkadi  *
2422626f090cSYacine Belkadi  * Return: Whether the device is configured properly or not. Zero if the
2423626f090cSYacine Belkadi  * interface was registered with the driver core; else a negative errno
2424626f090cSYacine Belkadi  * value.
2425626f090cSYacine Belkadi  *
2426d9d16e8aSInaky Perez-Gonzalez  */
2427d9d16e8aSInaky Perez-Gonzalez int usb_new_device(struct usb_device *udev)
2428d9d16e8aSInaky Perez-Gonzalez {
2429d9d16e8aSInaky Perez-Gonzalez 	int err;
2430d9d16e8aSInaky Perez-Gonzalez 
243116985408SDan Streetman 	if (udev->parent) {
243216985408SDan Streetman 		/* Initialize non-root-hub device wakeup to disabled;
243316985408SDan Streetman 		 * device (un)configuration controls wakeup capable
243416985408SDan Streetman 		 * sysfs power/wakeup controls wakeup enabled/disabled
243516985408SDan Streetman 		 */
243616985408SDan Streetman 		device_init_wakeup(&udev->dev, 0);
243716985408SDan Streetman 	}
243816985408SDan Streetman 
24399bbdf1e0SAlan Stern 	/* Tell the runtime-PM framework the device is active */
24409bbdf1e0SAlan Stern 	pm_runtime_set_active(&udev->dev);
2441c08512c7SAlan Stern 	pm_runtime_get_noresume(&udev->dev);
2442fcc4a01eSAlan Stern 	pm_runtime_use_autosuspend(&udev->dev);
24439bbdf1e0SAlan Stern 	pm_runtime_enable(&udev->dev);
24449bbdf1e0SAlan Stern 
2445c08512c7SAlan Stern 	/* By default, forbid autosuspend for all devices.  It will be
2446c08512c7SAlan Stern 	 * allowed for hubs during binding.
2447c08512c7SAlan Stern 	 */
2448c08512c7SAlan Stern 	usb_disable_autosuspend(udev);
2449c08512c7SAlan Stern 
24508d8558d1SAlan Stern 	err = usb_enumerate_device(udev);	/* Read descriptors */
2451d9d16e8aSInaky Perez-Gonzalez 	if (err < 0)
2452d9d16e8aSInaky Perez-Gonzalez 		goto fail;
2453c6515272SSarah Sharp 	dev_dbg(&udev->dev, "udev %d, busnum %d, minor = %d\n",
2454c6515272SSarah Sharp 			udev->devnum, udev->bus->busnum,
2455c6515272SSarah Sharp 			(((udev->bus->busnum-1) * 128) + (udev->devnum-1)));
24569f8b17e6SKay Sievers 	/* export the usbdev device-node for libusb */
24579f8b17e6SKay Sievers 	udev->dev.devt = MKDEV(USB_DEVICE_MAJOR,
24589f8b17e6SKay Sievers 			(((udev->bus->busnum-1) * 128) + (udev->devnum-1)));
24599f8b17e6SKay Sievers 
24606cd13201SAlan Stern 	/* Tell the world! */
24616cd13201SAlan Stern 	announce_device(udev);
2462195af2ccSAlan Stern 
2463b04b3156STheodore Ts'o 	if (udev->serial)
2464b04b3156STheodore Ts'o 		add_device_randomness(udev->serial, strlen(udev->serial));
2465b04b3156STheodore Ts'o 	if (udev->product)
2466b04b3156STheodore Ts'o 		add_device_randomness(udev->product, strlen(udev->product));
2467b04b3156STheodore Ts'o 	if (udev->manufacturer)
2468b04b3156STheodore Ts'o 		add_device_randomness(udev->manufacturer,
2469b04b3156STheodore Ts'o 				      strlen(udev->manufacturer));
2470b04b3156STheodore Ts'o 
2471927bc916SRafael J. Wysocki 	device_enable_async_suspend(&udev->dev);
2472d35e70d5SMatthew Garrett 
2473a4204ff0SDan Williams 	/* check whether the hub or firmware marks this port as non-removable */
2474d35e70d5SMatthew Garrett 	if (udev->parent)
2475d35e70d5SMatthew Garrett 		set_usb_port_removable(udev);
2476d35e70d5SMatthew Garrett 
2477782da727SAlan Stern 	/* Register the device.  The device driver is responsible
24783b23dd6fSAlan Stern 	 * for configuring the device and invoking the add-device
24793b23dd6fSAlan Stern 	 * notifier chain (used by usbfs and possibly others).
2480782da727SAlan Stern 	 */
24811da177e4SLinus Torvalds 	err = device_add(&udev->dev);
24821da177e4SLinus Torvalds 	if (err) {
24831da177e4SLinus Torvalds 		dev_err(&udev->dev, "can't device_add, error %d\n", err);
24841da177e4SLinus Torvalds 		goto fail;
24851da177e4SLinus Torvalds 	}
24869ad3d6ccSAlan Stern 
2487fde26380SLan Tianyu 	/* Create link files between child device and usb port device. */
2488fde26380SLan Tianyu 	if (udev->parent) {
2489ad493e5eSLan Tianyu 		struct usb_hub *hub = usb_hub_to_struct_hub(udev->parent);
2490d5c3834eSDan Williams 		int port1 = udev->portnum;
2491d5c3834eSDan Williams 		struct usb_port	*port_dev = hub->ports[port1 - 1];
2492fde26380SLan Tianyu 
2493fde26380SLan Tianyu 		err = sysfs_create_link(&udev->dev.kobj,
2494fde26380SLan Tianyu 				&port_dev->dev.kobj, "port");
2495fde26380SLan Tianyu 		if (err)
2496fde26380SLan Tianyu 			goto fail;
2497fde26380SLan Tianyu 
2498fde26380SLan Tianyu 		err = sysfs_create_link(&port_dev->dev.kobj,
2499fde26380SLan Tianyu 				&udev->dev.kobj, "device");
2500fde26380SLan Tianyu 		if (err) {
2501fde26380SLan Tianyu 			sysfs_remove_link(&udev->dev.kobj, "port");
2502fde26380SLan Tianyu 			goto fail;
2503fde26380SLan Tianyu 		}
2504971fcd49SLan Tianyu 
2505d5c3834eSDan Williams 		if (!test_and_set_bit(port1, hub->child_usage_bits))
2506971fcd49SLan Tianyu 			pm_runtime_get_sync(&port_dev->dev);
2507fde26380SLan Tianyu 	}
2508fde26380SLan Tianyu 
25093b23dd6fSAlan Stern 	(void) usb_create_ep_devs(&udev->dev, &udev->ep0, udev);
2510c08512c7SAlan Stern 	usb_mark_last_busy(udev);
2511c08512c7SAlan Stern 	pm_runtime_put_sync_autosuspend(&udev->dev);
2512c066475eSGreg Kroah-Hartman 	return err;
25131da177e4SLinus Torvalds 
25141da177e4SLinus Torvalds fail:
25151da177e4SLinus Torvalds 	usb_set_device_state(udev, USB_STATE_NOTATTACHED);
25169bbdf1e0SAlan Stern 	pm_runtime_disable(&udev->dev);
25179bbdf1e0SAlan Stern 	pm_runtime_set_suspended(&udev->dev);
2518d9d16e8aSInaky Perez-Gonzalez 	return err;
25191da177e4SLinus Torvalds }
25201da177e4SLinus Torvalds 
252193993a0aSInaky Perez-Gonzalez 
252293993a0aSInaky Perez-Gonzalez /**
2523fd39c86bSRandy Dunlap  * usb_deauthorize_device - deauthorize a device (usbcore-internal)
2524fd39c86bSRandy Dunlap  * @usb_dev: USB device
2525fd39c86bSRandy Dunlap  *
2526fd39c86bSRandy Dunlap  * Move the USB device to a very basic state where interfaces are disabled
2527fd39c86bSRandy Dunlap  * and the device is in fact unconfigured and unusable.
252893993a0aSInaky Perez-Gonzalez  *
252993993a0aSInaky Perez-Gonzalez  * We share a lock (that we have) with device_del(), so we need to
253093993a0aSInaky Perez-Gonzalez  * defer its call.
2531626f090cSYacine Belkadi  *
2532626f090cSYacine Belkadi  * Return: 0.
253393993a0aSInaky Perez-Gonzalez  */
253493993a0aSInaky Perez-Gonzalez int usb_deauthorize_device(struct usb_device *usb_dev)
253593993a0aSInaky Perez-Gonzalez {
253693993a0aSInaky Perez-Gonzalez 	usb_lock_device(usb_dev);
253793993a0aSInaky Perez-Gonzalez 	if (usb_dev->authorized == 0)
253893993a0aSInaky Perez-Gonzalez 		goto out_unauthorized;
2539da307123SAlan Stern 
254093993a0aSInaky Perez-Gonzalez 	usb_dev->authorized = 0;
254193993a0aSInaky Perez-Gonzalez 	usb_set_configuration(usb_dev, -1);
2542da307123SAlan Stern 
254393993a0aSInaky Perez-Gonzalez out_unauthorized:
254493993a0aSInaky Perez-Gonzalez 	usb_unlock_device(usb_dev);
254593993a0aSInaky Perez-Gonzalez 	return 0;
254693993a0aSInaky Perez-Gonzalez }
254793993a0aSInaky Perez-Gonzalez 
254893993a0aSInaky Perez-Gonzalez 
254993993a0aSInaky Perez-Gonzalez int usb_authorize_device(struct usb_device *usb_dev)
255093993a0aSInaky Perez-Gonzalez {
255193993a0aSInaky Perez-Gonzalez 	int result = 0, c;
2552da307123SAlan Stern 
255393993a0aSInaky Perez-Gonzalez 	usb_lock_device(usb_dev);
255493993a0aSInaky Perez-Gonzalez 	if (usb_dev->authorized == 1)
255593993a0aSInaky Perez-Gonzalez 		goto out_authorized;
2556da307123SAlan Stern 
255793993a0aSInaky Perez-Gonzalez 	result = usb_autoresume_device(usb_dev);
255893993a0aSInaky Perez-Gonzalez 	if (result < 0) {
255993993a0aSInaky Perez-Gonzalez 		dev_err(&usb_dev->dev,
256093993a0aSInaky Perez-Gonzalez 			"can't autoresume for authorization: %d\n", result);
256193993a0aSInaky Perez-Gonzalez 		goto error_autoresume;
256293993a0aSInaky Perez-Gonzalez 	}
2563e50a322eSJosef Gajdusek 
2564e50a322eSJosef Gajdusek 	if (usb_dev->wusb) {
256593993a0aSInaky Perez-Gonzalez 		result = usb_get_device_descriptor(usb_dev, sizeof(usb_dev->descriptor));
256693993a0aSInaky Perez-Gonzalez 		if (result < 0) {
256793993a0aSInaky Perez-Gonzalez 			dev_err(&usb_dev->dev, "can't re-read device descriptor for "
256893993a0aSInaky Perez-Gonzalez 				"authorization: %d\n", result);
256993993a0aSInaky Perez-Gonzalez 			goto error_device_descriptor;
257093993a0aSInaky Perez-Gonzalez 		}
2571e50a322eSJosef Gajdusek 	}
2572da307123SAlan Stern 
257393993a0aSInaky Perez-Gonzalez 	usb_dev->authorized = 1;
257493993a0aSInaky Perez-Gonzalez 	/* Choose and set the configuration.  This registers the interfaces
257593993a0aSInaky Perez-Gonzalez 	 * with the driver core and lets interface drivers bind to them.
257693993a0aSInaky Perez-Gonzalez 	 */
2577b5ea060fSGreg Kroah-Hartman 	c = usb_choose_configuration(usb_dev);
257893993a0aSInaky Perez-Gonzalez 	if (c >= 0) {
257993993a0aSInaky Perez-Gonzalez 		result = usb_set_configuration(usb_dev, c);
258093993a0aSInaky Perez-Gonzalez 		if (result) {
258193993a0aSInaky Perez-Gonzalez 			dev_err(&usb_dev->dev,
258293993a0aSInaky Perez-Gonzalez 				"can't set config #%d, error %d\n", c, result);
258393993a0aSInaky Perez-Gonzalez 			/* This need not be fatal.  The user can try to
258493993a0aSInaky Perez-Gonzalez 			 * set other configurations. */
258593993a0aSInaky Perez-Gonzalez 		}
258693993a0aSInaky Perez-Gonzalez 	}
258793993a0aSInaky Perez-Gonzalez 	dev_info(&usb_dev->dev, "authorized to connect\n");
2588da307123SAlan Stern 
258993993a0aSInaky Perez-Gonzalez error_device_descriptor:
2590da307123SAlan Stern 	usb_autosuspend_device(usb_dev);
259193993a0aSInaky Perez-Gonzalez error_autoresume:
259293993a0aSInaky Perez-Gonzalez out_authorized:
2593781b2137SMatthias Beyer 	usb_unlock_device(usb_dev);	/* complements locktree */
259493993a0aSInaky Perez-Gonzalez 	return result;
259593993a0aSInaky Perez-Gonzalez }
259693993a0aSInaky Perez-Gonzalez 
25970cdd49a1SMathias Nyman /*
25980cdd49a1SMathias Nyman  * Return 1 if port speed is SuperSpeedPlus, 0 otherwise
25990cdd49a1SMathias Nyman  * check it from the link protocol field of the current speed ID attribute.
26000cdd49a1SMathias Nyman  * current speed ID is got from ext port status request. Sublink speed attribute
26010cdd49a1SMathias Nyman  * table is returned with the hub BOS SSP device capability descriptor
26020cdd49a1SMathias Nyman  */
26030cdd49a1SMathias Nyman static int port_speed_is_ssp(struct usb_device *hdev, int speed_id)
26040cdd49a1SMathias Nyman {
26050cdd49a1SMathias Nyman 	int ssa_count;
26060cdd49a1SMathias Nyman 	u32 ss_attr;
26070cdd49a1SMathias Nyman 	int i;
26080cdd49a1SMathias Nyman 	struct usb_ssp_cap_descriptor *ssp_cap = hdev->bos->ssp_cap;
26090cdd49a1SMathias Nyman 
26100cdd49a1SMathias Nyman 	if (!ssp_cap)
26110cdd49a1SMathias Nyman 		return 0;
26120cdd49a1SMathias Nyman 
26130cdd49a1SMathias Nyman 	ssa_count = le32_to_cpu(ssp_cap->bmAttributes) &
26140cdd49a1SMathias Nyman 		USB_SSP_SUBLINK_SPEED_ATTRIBS;
26150cdd49a1SMathias Nyman 
26160cdd49a1SMathias Nyman 	for (i = 0; i <= ssa_count; i++) {
26170cdd49a1SMathias Nyman 		ss_attr = le32_to_cpu(ssp_cap->bmSublinkSpeedAttr[i]);
26180cdd49a1SMathias Nyman 		if (speed_id == (ss_attr & USB_SSP_SUBLINK_SPEED_SSID))
26190cdd49a1SMathias Nyman 			return !!(ss_attr & USB_SSP_SUBLINK_SPEED_LP);
26200cdd49a1SMathias Nyman 	}
26210cdd49a1SMathias Nyman 	return 0;
26220cdd49a1SMathias Nyman }
262393993a0aSInaky Perez-Gonzalez 
26240165de09SInaky Perez-Gonzalez /* Returns 1 if @hub is a WUSB root hub, 0 otherwise */
26250165de09SInaky Perez-Gonzalez static unsigned hub_is_wusb(struct usb_hub *hub)
26260165de09SInaky Perez-Gonzalez {
26270165de09SInaky Perez-Gonzalez 	struct usb_hcd *hcd;
26280165de09SInaky Perez-Gonzalez 	if (hub->hdev->parent != NULL)  /* not a root hub? */
26290165de09SInaky Perez-Gonzalez 		return 0;
26306ae706aeSGeliang Tang 	hcd = bus_to_hcd(hub->hdev->bus);
26310165de09SInaky Perez-Gonzalez 	return hcd->wireless;
26320165de09SInaky Perez-Gonzalez }
26330165de09SInaky Perez-Gonzalez 
26340165de09SInaky Perez-Gonzalez 
26351da177e4SLinus Torvalds #define PORT_RESET_TRIES	5
26361da177e4SLinus Torvalds #define SET_ADDRESS_TRIES	2
26371da177e4SLinus Torvalds #define GET_DESCRIPTOR_TRIES	2
26381da177e4SLinus Torvalds #define SET_CONFIG_TRIES	(2 * (use_both_schemes + 1))
263925244227SNicolas Boichat #define USE_NEW_SCHEME(i, scheme)	((i) / 2 == (int)scheme)
26401da177e4SLinus Torvalds 
264174072baeSMathias Nyman #define HUB_ROOT_RESET_TIME	60	/* times are in msec */
26421da177e4SLinus Torvalds #define HUB_SHORT_RESET_TIME	10
264375d7cf72SAndiry Xu #define HUB_BH_RESET_TIME	50
26441da177e4SLinus Torvalds #define HUB_LONG_RESET_TIME	200
264577c7f072SSarah Sharp #define HUB_RESET_TIMEOUT	800
26461da177e4SLinus Torvalds 
264748fc7dbdSDan Williams /*
264848fc7dbdSDan Williams  * "New scheme" enumeration causes an extra state transition to be
264948fc7dbdSDan Williams  * exposed to an xhci host and causes USB3 devices to receive control
265048fc7dbdSDan Williams  * commands in the default state.  This has been seen to cause
265148fc7dbdSDan Williams  * enumeration failures, so disable this enumeration scheme for USB3
265248fc7dbdSDan Williams  * devices.
265348fc7dbdSDan Williams  */
265425244227SNicolas Boichat static bool use_new_scheme(struct usb_device *udev, int retry,
265525244227SNicolas Boichat 			   struct usb_port *port_dev)
265648fc7dbdSDan Williams {
265725244227SNicolas Boichat 	int old_scheme_first_port =
265825244227SNicolas Boichat 		port_dev->quirks & USB_PORT_QUIRK_OLD_SCHEME;
265925244227SNicolas Boichat 
26608a1b2725SMathias Nyman 	if (udev->speed >= USB_SPEED_SUPER)
266148fc7dbdSDan Williams 		return false;
266248fc7dbdSDan Williams 
266325244227SNicolas Boichat 	return USE_NEW_SCHEME(retry, old_scheme_first_port || old_scheme_first);
266448fc7dbdSDan Williams }
266548fc7dbdSDan Williams 
2666025d4430SRahul Bedarkar /* Is a USB 3.0 port in the Inactive or Compliance Mode state?
26678bea2bd3SStanislaw Ledwon  * Port worm reset is required to recover
26688bea2bd3SStanislaw Ledwon  */
26693cd12f91SDan Williams static bool hub_port_warm_reset_required(struct usb_hub *hub, int port1,
26703cd12f91SDan Williams 		u16 portstatus)
267110d674a8SSarah Sharp {
26723cd12f91SDan Williams 	u16 link_state;
26733cd12f91SDan Williams 
26743cd12f91SDan Williams 	if (!hub_is_superspeed(hub->hdev))
26753cd12f91SDan Williams 		return false;
26763cd12f91SDan Williams 
26773cd12f91SDan Williams 	if (test_bit(port1, hub->warm_reset_bits))
26783cd12f91SDan Williams 		return true;
26793cd12f91SDan Williams 
26803cd12f91SDan Williams 	link_state = portstatus & USB_PORT_STAT_LINK_STATE;
26813cd12f91SDan Williams 	return link_state == USB_SS_PORT_LS_SS_INACTIVE
26823cd12f91SDan Williams 		|| link_state == USB_SS_PORT_LS_COMP_MOD;
268310d674a8SSarah Sharp }
268410d674a8SSarah Sharp 
26851da177e4SLinus Torvalds static int hub_port_wait_reset(struct usb_hub *hub, int port1,
268675d7cf72SAndiry Xu 			struct usb_device *udev, unsigned int delay, bool warm)
26871da177e4SLinus Torvalds {
26881da177e4SLinus Torvalds 	int delay_time, ret;
26891da177e4SLinus Torvalds 	u16 portstatus;
26901da177e4SLinus Torvalds 	u16 portchange;
26910cdd49a1SMathias Nyman 	u32 ext_portstatus = 0;
26921da177e4SLinus Torvalds 
26931da177e4SLinus Torvalds 	for (delay_time = 0;
26941da177e4SLinus Torvalds 			delay_time < HUB_RESET_TIMEOUT;
26951da177e4SLinus Torvalds 			delay_time += delay) {
26961da177e4SLinus Torvalds 		/* wait to give the device a chance to reset */
26971da177e4SLinus Torvalds 		msleep(delay);
26981da177e4SLinus Torvalds 
26991da177e4SLinus Torvalds 		/* read and decode port status */
27000cdd49a1SMathias Nyman 		if (hub_is_superspeedplus(hub->hdev))
27010cdd49a1SMathias Nyman 			ret = hub_ext_port_status(hub, port1,
27020cdd49a1SMathias Nyman 						  HUB_EXT_PORT_STATUS,
27030cdd49a1SMathias Nyman 						  &portstatus, &portchange,
27040cdd49a1SMathias Nyman 						  &ext_portstatus);
27050cdd49a1SMathias Nyman 		else
27060cdd49a1SMathias Nyman 			ret = hub_port_status(hub, port1, &portstatus,
27070cdd49a1SMathias Nyman 					      &portchange);
27081da177e4SLinus Torvalds 		if (ret < 0)
27091da177e4SLinus Torvalds 			return ret;
27101da177e4SLinus Torvalds 
271122547c4cSGuenter Roeck 		/*
271222547c4cSGuenter Roeck 		 * The port state is unknown until the reset completes.
271322547c4cSGuenter Roeck 		 *
271422547c4cSGuenter Roeck 		 * On top of that, some chips may require additional time
271522547c4cSGuenter Roeck 		 * to re-establish a connection after the reset is complete,
271622547c4cSGuenter Roeck 		 * so also wait for the connection to be re-established.
271722547c4cSGuenter Roeck 		 */
271822547c4cSGuenter Roeck 		if (!(portstatus & USB_PORT_STAT_RESET) &&
271922547c4cSGuenter Roeck 		    (portstatus & USB_PORT_STAT_CONNECTION))
2720470f0be8SSarah Sharp 			break;
2721470f0be8SSarah Sharp 
2722470f0be8SSarah Sharp 		/* switch to the long delay after two short delay failures */
2723470f0be8SSarah Sharp 		if (delay_time >= 2 * HUB_SHORT_RESET_TIME)
2724470f0be8SSarah Sharp 			delay = HUB_LONG_RESET_TIME;
2725470f0be8SSarah Sharp 
2726d99f6b41SDan Williams 		dev_dbg(&hub->ports[port1 - 1]->dev,
2727d99f6b41SDan Williams 				"not %sreset yet, waiting %dms\n",
2728d99f6b41SDan Williams 				warm ? "warm " : "", delay);
2729470f0be8SSarah Sharp 	}
2730470f0be8SSarah Sharp 
27314f43447eSSarah Sharp 	if ((portstatus & USB_PORT_STAT_RESET))
2732470f0be8SSarah Sharp 		return -EBUSY;
27334f43447eSSarah Sharp 
27343cd12f91SDan Williams 	if (hub_port_warm_reset_required(hub, port1, portstatus))
2735a24a6078SSarah Sharp 		return -ENOTCONN;
273610d674a8SSarah Sharp 
27371da177e4SLinus Torvalds 	/* Device went away? */
27381da177e4SLinus Torvalds 	if (!(portstatus & USB_PORT_STAT_CONNECTION))
27391da177e4SLinus Torvalds 		return -ENOTCONN;
27401da177e4SLinus Torvalds 
27411ac7db63SMathias Nyman 	/* Retry if connect change is set but status is still connected.
27421ac7db63SMathias Nyman 	 * A USB 3.0 connection may bounce if multiple warm resets were issued,
2743a24a6078SSarah Sharp 	 * but the device may have successfully re-connected. Ignore it.
2744a24a6078SSarah Sharp 	 */
2745a24a6078SSarah Sharp 	if (!hub_is_superspeed(hub->hdev) &&
27461ac7db63SMathias Nyman 	    (portchange & USB_PORT_STAT_C_CONNECTION)) {
27471ac7db63SMathias Nyman 		usb_clear_port_feature(hub->hdev, port1,
27481ac7db63SMathias Nyman 				       USB_PORT_FEAT_C_CONNECTION);
27491ac7db63SMathias Nyman 		return -EAGAIN;
27501ac7db63SMathias Nyman 	}
27511da177e4SLinus Torvalds 
2752470f0be8SSarah Sharp 	if (!(portstatus & USB_PORT_STAT_ENABLE))
2753470f0be8SSarah Sharp 		return -EBUSY;
2754470f0be8SSarah Sharp 
27552d4fa940SSarah Sharp 	if (!udev)
27562d4fa940SSarah Sharp 		return 0;
27572d4fa940SSarah Sharp 
2758013eedb8SMathias Nyman 	if (hub_is_superspeedplus(hub->hdev)) {
2759013eedb8SMathias Nyman 		/* extended portstatus Rx and Tx lane count are zero based */
2760013eedb8SMathias Nyman 		udev->rx_lanes = USB_EXT_PORT_RX_LANES(ext_portstatus) + 1;
2761013eedb8SMathias Nyman 		udev->tx_lanes = USB_EXT_PORT_TX_LANES(ext_portstatus) + 1;
2762013eedb8SMathias Nyman 	} else {
2763013eedb8SMathias Nyman 		udev->rx_lanes = 1;
2764013eedb8SMathias Nyman 		udev->tx_lanes = 1;
2765013eedb8SMathias Nyman 	}
27660165de09SInaky Perez-Gonzalez 	if (hub_is_wusb(hub))
2767551cdbbeSGreg Kroah-Hartman 		udev->speed = USB_SPEED_WIRELESS;
27680cdd49a1SMathias Nyman 	else if (hub_is_superspeedplus(hub->hdev) &&
27690cdd49a1SMathias Nyman 		 port_speed_is_ssp(hub->hdev, ext_portstatus &
27700cdd49a1SMathias Nyman 				   USB_EXT_PORT_STAT_RX_SPEED_ID))
27710cdd49a1SMathias Nyman 		udev->speed = USB_SPEED_SUPER_PLUS;
2772131dec34SSarah Sharp 	else if (hub_is_superspeed(hub->hdev))
2773809cd1cbSSarah Sharp 		udev->speed = USB_SPEED_SUPER;
27740165de09SInaky Perez-Gonzalez 	else if (portstatus & USB_PORT_STAT_HIGH_SPEED)
27751da177e4SLinus Torvalds 		udev->speed = USB_SPEED_HIGH;
27761da177e4SLinus Torvalds 	else if (portstatus & USB_PORT_STAT_LOW_SPEED)
27771da177e4SLinus Torvalds 		udev->speed = USB_SPEED_LOW;
27781da177e4SLinus Torvalds 	else
27791da177e4SLinus Torvalds 		udev->speed = USB_SPEED_FULL;
27801da177e4SLinus Torvalds 	return 0;
27811da177e4SLinus Torvalds }
27821da177e4SLinus Torvalds 
278375d7cf72SAndiry Xu /* Handle port reset and port warm(BH) reset (for USB3 protocol ports) */
278475d7cf72SAndiry Xu static int hub_port_reset(struct usb_hub *hub, int port1,
278575d7cf72SAndiry Xu 			struct usb_device *udev, unsigned int delay, bool warm)
278675d7cf72SAndiry Xu {
278775d7cf72SAndiry Xu 	int i, status;
2788a24a6078SSarah Sharp 	u16 portchange, portstatus;
2789d99f6b41SDan Williams 	struct usb_port *port_dev = hub->ports[port1 - 1];
279075d7cf72SAndiry Xu 
279175d7cf72SAndiry Xu 	if (!hub_is_superspeed(hub->hdev)) {
27920fe51aa5SSarah Sharp 		if (warm) {
279375d7cf72SAndiry Xu 			dev_err(hub->intfdev, "only USB3 hub support "
279475d7cf72SAndiry Xu 						"warm reset\n");
279575d7cf72SAndiry Xu 			return -EINVAL;
279675d7cf72SAndiry Xu 		}
27970fe51aa5SSarah Sharp 		/* Block EHCI CF initialization during the port reset.
27980fe51aa5SSarah Sharp 		 * Some companion controllers don't like it when they mix.
27990fe51aa5SSarah Sharp 		 */
28000fe51aa5SSarah Sharp 		down_read(&ehci_cf_port_reset_rwsem);
2801d3b9d7a9SSarah Sharp 	} else if (!warm) {
2802d3b9d7a9SSarah Sharp 		/*
2803d3b9d7a9SSarah Sharp 		 * If the caller hasn't explicitly requested a warm reset,
2804d3b9d7a9SSarah Sharp 		 * double check and see if one is needed.
2805d3b9d7a9SSarah Sharp 		 */
2806fb6d1f7dSRobert Schlabbach 		if (hub_port_status(hub, port1, &portstatus, &portchange) == 0)
2807fb6d1f7dSRobert Schlabbach 			if (hub_port_warm_reset_required(hub, port1,
2808fb6d1f7dSRobert Schlabbach 							portstatus))
2809d3b9d7a9SSarah Sharp 				warm = true;
281075d7cf72SAndiry Xu 	}
28113cd12f91SDan Williams 	clear_bit(port1, hub->warm_reset_bits);
281275d7cf72SAndiry Xu 
281375d7cf72SAndiry Xu 	/* Reset the port */
281475d7cf72SAndiry Xu 	for (i = 0; i < PORT_RESET_TRIES; i++) {
281575d7cf72SAndiry Xu 		status = set_port_feature(hub->hdev, port1, (warm ?
281675d7cf72SAndiry Xu 					USB_PORT_FEAT_BH_PORT_RESET :
281775d7cf72SAndiry Xu 					USB_PORT_FEAT_RESET));
2818e9e88fb7SAlan Stern 		if (status == -ENODEV) {
2819e9e88fb7SAlan Stern 			;	/* The hub is gone */
2820e9e88fb7SAlan Stern 		} else if (status) {
2821d99f6b41SDan Williams 			dev_err(&port_dev->dev,
2822d99f6b41SDan Williams 					"cannot %sreset (err = %d)\n",
2823d99f6b41SDan Williams 					warm ? "warm " : "", status);
282475d7cf72SAndiry Xu 		} else {
282575d7cf72SAndiry Xu 			status = hub_port_wait_reset(hub, port1, udev, delay,
282675d7cf72SAndiry Xu 								warm);
2827e9e88fb7SAlan Stern 			if (status && status != -ENOTCONN && status != -ENODEV)
282875d7cf72SAndiry Xu 				dev_dbg(hub->intfdev,
282975d7cf72SAndiry Xu 						"port_wait_reset: err = %d\n",
283075d7cf72SAndiry Xu 						status);
283175d7cf72SAndiry Xu 		}
283275d7cf72SAndiry Xu 
2833a24a6078SSarah Sharp 		/* Check for disconnect or reset */
283475d7cf72SAndiry Xu 		if (status == 0 || status == -ENOTCONN || status == -ENODEV) {
2835fb6d1f7dSRobert Schlabbach 			usb_clear_port_feature(hub->hdev, port1,
2836fb6d1f7dSRobert Schlabbach 					USB_PORT_FEAT_C_RESET);
2837a24a6078SSarah Sharp 
2838a24a6078SSarah Sharp 			if (!hub_is_superspeed(hub->hdev))
283932fe0198SAlan Stern 				goto done;
2840a24a6078SSarah Sharp 
2841fb6d1f7dSRobert Schlabbach 			usb_clear_port_feature(hub->hdev, port1,
2842fb6d1f7dSRobert Schlabbach 					USB_PORT_FEAT_C_BH_PORT_RESET);
2843fb6d1f7dSRobert Schlabbach 			usb_clear_port_feature(hub->hdev, port1,
2844fb6d1f7dSRobert Schlabbach 					USB_PORT_FEAT_C_PORT_LINK_STATE);
2845fb6d1f7dSRobert Schlabbach 			usb_clear_port_feature(hub->hdev, port1,
2846fb6d1f7dSRobert Schlabbach 					USB_PORT_FEAT_C_CONNECTION);
2847fb6d1f7dSRobert Schlabbach 
2848a24a6078SSarah Sharp 			/*
2849a24a6078SSarah Sharp 			 * If a USB 3.0 device migrates from reset to an error
2850a24a6078SSarah Sharp 			 * state, re-issue the warm reset.
2851a24a6078SSarah Sharp 			 */
2852a24a6078SSarah Sharp 			if (hub_port_status(hub, port1,
2853a24a6078SSarah Sharp 					&portstatus, &portchange) < 0)
2854a24a6078SSarah Sharp 				goto done;
2855a24a6078SSarah Sharp 
28563cd12f91SDan Williams 			if (!hub_port_warm_reset_required(hub, port1,
28573cd12f91SDan Williams 					portstatus))
2858a24a6078SSarah Sharp 				goto done;
2859a24a6078SSarah Sharp 
2860a24a6078SSarah Sharp 			/*
2861a24a6078SSarah Sharp 			 * If the port is in SS.Inactive or Compliance Mode, the
2862a24a6078SSarah Sharp 			 * hot or warm reset failed.  Try another warm reset.
2863a24a6078SSarah Sharp 			 */
2864a24a6078SSarah Sharp 			if (!warm) {
2865d99f6b41SDan Williams 				dev_dbg(&port_dev->dev,
2866d99f6b41SDan Williams 						"hot reset failed, warm reset\n");
2867a24a6078SSarah Sharp 				warm = true;
2868a24a6078SSarah Sharp 			}
28691da177e4SLinus Torvalds 		}
28701da177e4SLinus Torvalds 
2871d99f6b41SDan Williams 		dev_dbg(&port_dev->dev,
2872d99f6b41SDan Williams 				"not enabled, trying %sreset again...\n",
2873d99f6b41SDan Williams 				warm ? "warm " : "");
28741da177e4SLinus Torvalds 		delay = HUB_LONG_RESET_TIME;
28751da177e4SLinus Torvalds 	}
28761da177e4SLinus Torvalds 
2877d99f6b41SDan Williams 	dev_err(&port_dev->dev, "Cannot enable. Maybe the USB cable is bad?\n");
28781da177e4SLinus Torvalds 
287932fe0198SAlan Stern done:
2880fb6d1f7dSRobert Schlabbach 	if (status == 0) {
2881fb6d1f7dSRobert Schlabbach 		/* TRSTRCY = 10 ms; plus some extra */
2882aa071a92SNicolas Boichat 		if (port_dev->quirks & USB_PORT_QUIRK_FAST_ENUM)
2883aa071a92SNicolas Boichat 			usleep_range(10000, 12000);
2884aa071a92SNicolas Boichat 		else
2885fb6d1f7dSRobert Schlabbach 			msleep(10 + 40);
2886aa071a92SNicolas Boichat 
2887fb6d1f7dSRobert Schlabbach 		if (udev) {
2888fb6d1f7dSRobert Schlabbach 			struct usb_hcd *hcd = bus_to_hcd(udev->bus);
2889fb6d1f7dSRobert Schlabbach 
2890fb6d1f7dSRobert Schlabbach 			update_devnum(udev, 0);
2891fb6d1f7dSRobert Schlabbach 			/* The xHC may think the device is already reset,
2892fb6d1f7dSRobert Schlabbach 			 * so ignore the status.
2893fb6d1f7dSRobert Schlabbach 			 */
2894fb6d1f7dSRobert Schlabbach 			if (hcd->driver->reset_device)
2895fb6d1f7dSRobert Schlabbach 				hcd->driver->reset_device(hcd, udev);
2896fb6d1f7dSRobert Schlabbach 
2897fb6d1f7dSRobert Schlabbach 			usb_set_device_state(udev, USB_STATE_DEFAULT);
2898fb6d1f7dSRobert Schlabbach 		}
2899fb6d1f7dSRobert Schlabbach 	} else {
2900fb6d1f7dSRobert Schlabbach 		if (udev)
2901fb6d1f7dSRobert Schlabbach 			usb_set_device_state(udev, USB_STATE_NOTATTACHED);
2902fb6d1f7dSRobert Schlabbach 	}
2903fb6d1f7dSRobert Schlabbach 
29040fe51aa5SSarah Sharp 	if (!hub_is_superspeed(hub->hdev))
290532fe0198SAlan Stern 		up_read(&ehci_cf_port_reset_rwsem);
290675d7cf72SAndiry Xu 
29071da177e4SLinus Torvalds 	return status;
29081da177e4SLinus Torvalds }
29091da177e4SLinus Torvalds 
29100ed9a57eSAndiry Xu /* Check if a port is power on */
29110ed9a57eSAndiry Xu static int port_is_power_on(struct usb_hub *hub, unsigned portstatus)
29120ed9a57eSAndiry Xu {
29130ed9a57eSAndiry Xu 	int ret = 0;
29140ed9a57eSAndiry Xu 
29150ed9a57eSAndiry Xu 	if (hub_is_superspeed(hub->hdev)) {
29160ed9a57eSAndiry Xu 		if (portstatus & USB_SS_PORT_STAT_POWER)
29170ed9a57eSAndiry Xu 			ret = 1;
29180ed9a57eSAndiry Xu 	} else {
29190ed9a57eSAndiry Xu 		if (portstatus & USB_PORT_STAT_POWER)
29200ed9a57eSAndiry Xu 			ret = 1;
29210ed9a57eSAndiry Xu 	}
29220ed9a57eSAndiry Xu 
29230ed9a57eSAndiry Xu 	return ret;
29240ed9a57eSAndiry Xu }
29250ed9a57eSAndiry Xu 
29265c79a1e3SDan Williams static void usb_lock_port(struct usb_port *port_dev)
29275c79a1e3SDan Williams 		__acquires(&port_dev->status_lock)
29285c79a1e3SDan Williams {
29295c79a1e3SDan Williams 	mutex_lock(&port_dev->status_lock);
29305c79a1e3SDan Williams 	__acquire(&port_dev->status_lock);
29315c79a1e3SDan Williams }
29325c79a1e3SDan Williams 
29335c79a1e3SDan Williams static void usb_unlock_port(struct usb_port *port_dev)
29345c79a1e3SDan Williams 		__releases(&port_dev->status_lock)
29355c79a1e3SDan Williams {
29365c79a1e3SDan Williams 	mutex_unlock(&port_dev->status_lock);
29375c79a1e3SDan Williams 	__release(&port_dev->status_lock);
29385c79a1e3SDan Williams }
29395c79a1e3SDan Williams 
2940d388dab7SAlan Stern #ifdef	CONFIG_PM
29411da177e4SLinus Torvalds 
29420ed9a57eSAndiry Xu /* Check if a port is suspended(USB2.0 port) or in U3 state(USB3.0 port) */
29430ed9a57eSAndiry Xu static int port_is_suspended(struct usb_hub *hub, unsigned portstatus)
29440ed9a57eSAndiry Xu {
29450ed9a57eSAndiry Xu 	int ret = 0;
29460ed9a57eSAndiry Xu 
29470ed9a57eSAndiry Xu 	if (hub_is_superspeed(hub->hdev)) {
29480ed9a57eSAndiry Xu 		if ((portstatus & USB_PORT_STAT_LINK_STATE)
29490ed9a57eSAndiry Xu 				== USB_SS_PORT_LS_U3)
29500ed9a57eSAndiry Xu 			ret = 1;
29510ed9a57eSAndiry Xu 	} else {
29520ed9a57eSAndiry Xu 		if (portstatus & USB_PORT_STAT_SUSPEND)
29530ed9a57eSAndiry Xu 			ret = 1;
29540ed9a57eSAndiry Xu 	}
29550ed9a57eSAndiry Xu 
29560ed9a57eSAndiry Xu 	return ret;
29570ed9a57eSAndiry Xu }
2958b01b03f3SAlan Stern 
2959b01b03f3SAlan Stern /* Determine whether the device on a port is ready for a normal resume,
2960b01b03f3SAlan Stern  * is ready for a reset-resume, or should be disconnected.
2961b01b03f3SAlan Stern  */
2962b01b03f3SAlan Stern static int check_port_resume_type(struct usb_device *udev,
2963b01b03f3SAlan Stern 		struct usb_hub *hub, int port1,
29647fa40910SJulius Werner 		int status, u16 portchange, u16 portstatus)
2965b01b03f3SAlan Stern {
2966d99f6b41SDan Williams 	struct usb_port *port_dev = hub->ports[port1 - 1];
29677fa40910SJulius Werner 	int retries = 3;
2968d99f6b41SDan Williams 
29697fa40910SJulius Werner  retry:
29703cd12f91SDan Williams 	/* Is a warm reset needed to recover the connection? */
29713cd12f91SDan Williams 	if (status == 0 && udev->reset_resume
29723cd12f91SDan Williams 		&& hub_port_warm_reset_required(hub, port1, portstatus)) {
29733cd12f91SDan Williams 		/* pass */;
29743cd12f91SDan Williams 	}
2975b01b03f3SAlan Stern 	/* Is the device still present? */
29763cd12f91SDan Williams 	else if (status || port_is_suspended(hub, portstatus) ||
29777fa40910SJulius Werner 			!port_is_power_on(hub, portstatus)) {
2978b01b03f3SAlan Stern 		if (status >= 0)
2979b01b03f3SAlan Stern 			status = -ENODEV;
29807fa40910SJulius Werner 	} else if (!(portstatus & USB_PORT_STAT_CONNECTION)) {
29817fa40910SJulius Werner 		if (retries--) {
29827fa40910SJulius Werner 			usleep_range(200, 300);
29837fa40910SJulius Werner 			status = hub_port_status(hub, port1, &portstatus,
29847fa40910SJulius Werner 							     &portchange);
29857fa40910SJulius Werner 			goto retry;
29867fa40910SJulius Werner 		}
29877fa40910SJulius Werner 		status = -ENODEV;
2988b01b03f3SAlan Stern 	}
2989b01b03f3SAlan Stern 
299086c57edfSAlan Stern 	/* Can't do a normal resume if the port isn't enabled,
299186c57edfSAlan Stern 	 * so try a reset-resume instead.
299286c57edfSAlan Stern 	 */
299386c57edfSAlan Stern 	else if (!(portstatus & USB_PORT_STAT_ENABLE) && !udev->reset_resume) {
299486c57edfSAlan Stern 		if (udev->persist_enabled)
299586c57edfSAlan Stern 			udev->reset_resume = 1;
299686c57edfSAlan Stern 		else
2997b01b03f3SAlan Stern 			status = -ENODEV;
299886c57edfSAlan Stern 	}
2999b01b03f3SAlan Stern 
3000b01b03f3SAlan Stern 	if (status) {
3001d99f6b41SDan Williams 		dev_dbg(&port_dev->dev, "status %04x.%04x after resume, %d\n",
3002d99f6b41SDan Williams 				portchange, portstatus, status);
3003b01b03f3SAlan Stern 	} else if (udev->reset_resume) {
3004b01b03f3SAlan Stern 
3005b01b03f3SAlan Stern 		/* Late port handoff can set status-change bits */
3006b01b03f3SAlan Stern 		if (portchange & USB_PORT_STAT_C_CONNECTION)
3007ad493e5eSLan Tianyu 			usb_clear_port_feature(hub->hdev, port1,
3008b01b03f3SAlan Stern 					USB_PORT_FEAT_C_CONNECTION);
3009b01b03f3SAlan Stern 		if (portchange & USB_PORT_STAT_C_ENABLE)
3010ad493e5eSLan Tianyu 			usb_clear_port_feature(hub->hdev, port1,
3011b01b03f3SAlan Stern 					USB_PORT_FEAT_C_ENABLE);
3012b01b03f3SAlan Stern 	}
3013b01b03f3SAlan Stern 
3014b01b03f3SAlan Stern 	return status;
3015b01b03f3SAlan Stern }
3016b01b03f3SAlan Stern 
3017f74631e3SSarah Sharp int usb_disable_ltm(struct usb_device *udev)
3018f74631e3SSarah Sharp {
3019f74631e3SSarah Sharp 	struct usb_hcd *hcd = bus_to_hcd(udev->bus);
3020f74631e3SSarah Sharp 
3021f74631e3SSarah Sharp 	/* Check if the roothub and device supports LTM. */
3022f74631e3SSarah Sharp 	if (!usb_device_supports_ltm(hcd->self.root_hub) ||
3023f74631e3SSarah Sharp 			!usb_device_supports_ltm(udev))
3024f74631e3SSarah Sharp 		return 0;
3025f74631e3SSarah Sharp 
3026f74631e3SSarah Sharp 	/* Clear Feature LTM Enable can only be sent if the device is
3027f74631e3SSarah Sharp 	 * configured.
3028f74631e3SSarah Sharp 	 */
3029f74631e3SSarah Sharp 	if (!udev->actconfig)
3030f74631e3SSarah Sharp 		return 0;
3031f74631e3SSarah Sharp 
3032f74631e3SSarah Sharp 	return usb_control_msg(udev, usb_sndctrlpipe(udev, 0),
3033f74631e3SSarah Sharp 			USB_REQ_CLEAR_FEATURE, USB_RECIP_DEVICE,
3034f74631e3SSarah Sharp 			USB_DEVICE_LTM_ENABLE, 0, NULL, 0,
3035f74631e3SSarah Sharp 			USB_CTRL_SET_TIMEOUT);
3036f74631e3SSarah Sharp }
3037f74631e3SSarah Sharp EXPORT_SYMBOL_GPL(usb_disable_ltm);
3038f74631e3SSarah Sharp 
3039f74631e3SSarah Sharp void usb_enable_ltm(struct usb_device *udev)
3040f74631e3SSarah Sharp {
3041f74631e3SSarah Sharp 	struct usb_hcd *hcd = bus_to_hcd(udev->bus);
3042f74631e3SSarah Sharp 
3043f74631e3SSarah Sharp 	/* Check if the roothub and device supports LTM. */
3044f74631e3SSarah Sharp 	if (!usb_device_supports_ltm(hcd->self.root_hub) ||
3045f74631e3SSarah Sharp 			!usb_device_supports_ltm(udev))
3046f74631e3SSarah Sharp 		return;
3047f74631e3SSarah Sharp 
3048f74631e3SSarah Sharp 	/* Set Feature LTM Enable can only be sent if the device is
3049f74631e3SSarah Sharp 	 * configured.
3050f74631e3SSarah Sharp 	 */
3051f74631e3SSarah Sharp 	if (!udev->actconfig)
3052f74631e3SSarah Sharp 		return;
3053f74631e3SSarah Sharp 
3054f74631e3SSarah Sharp 	usb_control_msg(udev, usb_sndctrlpipe(udev, 0),
3055f74631e3SSarah Sharp 			USB_REQ_SET_FEATURE, USB_RECIP_DEVICE,
3056f74631e3SSarah Sharp 			USB_DEVICE_LTM_ENABLE, 0, NULL, 0,
3057f74631e3SSarah Sharp 			USB_CTRL_SET_TIMEOUT);
3058f74631e3SSarah Sharp }
3059f74631e3SSarah Sharp EXPORT_SYMBOL_GPL(usb_enable_ltm);
3060f74631e3SSarah Sharp 
306154a3ac0cSLan Tianyu /*
306228e86165SAlan Stern  * usb_enable_remote_wakeup - enable remote wakeup for a device
306354a3ac0cSLan Tianyu  * @udev: target device
306454a3ac0cSLan Tianyu  *
306528e86165SAlan Stern  * For USB-2 devices: Set the device's remote wakeup feature.
306628e86165SAlan Stern  *
306728e86165SAlan Stern  * For USB-3 devices: Assume there's only one function on the device and
306828e86165SAlan Stern  * enable remote wake for the first interface.  FIXME if the interface
306928e86165SAlan Stern  * association descriptor shows there's more than one function.
307054a3ac0cSLan Tianyu  */
307128e86165SAlan Stern static int usb_enable_remote_wakeup(struct usb_device *udev)
307254a3ac0cSLan Tianyu {
307328e86165SAlan Stern 	if (udev->speed < USB_SPEED_SUPER)
307428e86165SAlan Stern 		return usb_control_msg(udev, usb_sndctrlpipe(udev, 0),
307528e86165SAlan Stern 				USB_REQ_SET_FEATURE, USB_RECIP_DEVICE,
307628e86165SAlan Stern 				USB_DEVICE_REMOTE_WAKEUP, 0, NULL, 0,
307728e86165SAlan Stern 				USB_CTRL_SET_TIMEOUT);
307828e86165SAlan Stern 	else
307928e86165SAlan Stern 		return usb_control_msg(udev, usb_sndctrlpipe(udev, 0),
308028e86165SAlan Stern 				USB_REQ_SET_FEATURE, USB_RECIP_INTERFACE,
308128e86165SAlan Stern 				USB_INTRF_FUNC_SUSPEND,
308228e86165SAlan Stern 				USB_INTRF_FUNC_SUSPEND_RW |
308328e86165SAlan Stern 					USB_INTRF_FUNC_SUSPEND_LP,
308428e86165SAlan Stern 				NULL, 0, USB_CTRL_SET_TIMEOUT);
308528e86165SAlan Stern }
308628e86165SAlan Stern 
308728e86165SAlan Stern /*
308828e86165SAlan Stern  * usb_disable_remote_wakeup - disable remote wakeup for a device
308928e86165SAlan Stern  * @udev: target device
309028e86165SAlan Stern  *
309128e86165SAlan Stern  * For USB-2 devices: Clear the device's remote wakeup feature.
309228e86165SAlan Stern  *
309328e86165SAlan Stern  * For USB-3 devices: Assume there's only one function on the device and
309428e86165SAlan Stern  * disable remote wake for the first interface.  FIXME if the interface
309528e86165SAlan Stern  * association descriptor shows there's more than one function.
309628e86165SAlan Stern  */
309728e86165SAlan Stern static int usb_disable_remote_wakeup(struct usb_device *udev)
309828e86165SAlan Stern {
309928e86165SAlan Stern 	if (udev->speed < USB_SPEED_SUPER)
310028e86165SAlan Stern 		return usb_control_msg(udev, usb_sndctrlpipe(udev, 0),
310128e86165SAlan Stern 				USB_REQ_CLEAR_FEATURE, USB_RECIP_DEVICE,
310228e86165SAlan Stern 				USB_DEVICE_REMOTE_WAKEUP, 0, NULL, 0,
310328e86165SAlan Stern 				USB_CTRL_SET_TIMEOUT);
310428e86165SAlan Stern 	else
310554a3ac0cSLan Tianyu 		return usb_control_msg(udev, usb_sndctrlpipe(udev, 0),
31064e248000SYonglong Wu 				USB_REQ_SET_FEATURE, USB_RECIP_INTERFACE,
310754a3ac0cSLan Tianyu 				USB_INTRF_FUNC_SUSPEND,	0, NULL, 0,
310854a3ac0cSLan Tianyu 				USB_CTRL_SET_TIMEOUT);
310954a3ac0cSLan Tianyu }
31101da177e4SLinus Torvalds 
3111e583d9dbSAlan Stern /* Count of wakeup-enabled devices at or below udev */
3112e583d9dbSAlan Stern static unsigned wakeup_enabled_descendants(struct usb_device *udev)
3113e583d9dbSAlan Stern {
3114e583d9dbSAlan Stern 	struct usb_hub *hub = usb_hub_to_struct_hub(udev);
3115e583d9dbSAlan Stern 
3116e583d9dbSAlan Stern 	return udev->do_remote_wakeup +
3117e583d9dbSAlan Stern 			(hub ? hub->wakeup_enabled_descendants : 0);
3118e583d9dbSAlan Stern }
3119e583d9dbSAlan Stern 
31201da177e4SLinus Torvalds /*
3121140d8f68SAlan Stern  * usb_port_suspend - suspend a usb device's upstream port
3122624d6c07SAlan Stern  * @udev: device that's no longer in active use, not a root hub
31235edbfb7cSDavid Brownell  * Context: must be able to sleep; device not locked; pm locks held
31241da177e4SLinus Torvalds  *
31251da177e4SLinus Torvalds  * Suspends a USB device that isn't in active use, conserving power.
31261da177e4SLinus Torvalds  * Devices may wake out of a suspend, if anything important happens,
31271da177e4SLinus Torvalds  * using the remote wakeup mechanism.  They may also be taken out of
3128140d8f68SAlan Stern  * suspend by the host, using usb_port_resume().  It's also routine
31291da177e4SLinus Torvalds  * to disconnect devices while they are suspended.
31301da177e4SLinus Torvalds  *
3131390a8c34SDavid Brownell  * This only affects the USB hardware for a device; its interfaces
3132390a8c34SDavid Brownell  * (and, for hubs, child devices) must already have been suspended.
3133390a8c34SDavid Brownell  *
3134624d6c07SAlan Stern  * Selective port suspend reduces power; most suspended devices draw
3135624d6c07SAlan Stern  * less than 500 uA.  It's also used in OTG, along with remote wakeup.
3136624d6c07SAlan Stern  * All devices below the suspended port are also suspended.
3137624d6c07SAlan Stern  *
3138624d6c07SAlan Stern  * Devices leave suspend state when the host wakes them up.  Some devices
3139624d6c07SAlan Stern  * also support "remote wakeup", where the device can activate the USB
3140624d6c07SAlan Stern  * tree above them to deliver data, such as a keypress or packet.  In
3141624d6c07SAlan Stern  * some cases, this wakes the USB host.
3142624d6c07SAlan Stern  *
31431da177e4SLinus Torvalds  * Suspending OTG devices may trigger HNP, if that's been enabled
31441da177e4SLinus Torvalds  * between a pair of dual-role devices.  That will change roles, such
31451da177e4SLinus Torvalds  * as from A-Host to A-Peripheral or from B-Host back to B-Peripheral.
31461da177e4SLinus Torvalds  *
31474956eccdSAlan Stern  * Devices on USB hub ports have only one "suspend" state, corresponding
31484956eccdSAlan Stern  * to ACPI D2, "may cause the device to lose some context".
31494956eccdSAlan Stern  * State transitions include:
31504956eccdSAlan Stern  *
31514956eccdSAlan Stern  *   - suspend, resume ... when the VBUS power link stays live
31524956eccdSAlan Stern  *   - suspend, disconnect ... VBUS lost
31534956eccdSAlan Stern  *
31544956eccdSAlan Stern  * Once VBUS drop breaks the circuit, the port it's using has to go through
31554956eccdSAlan Stern  * normal re-enumeration procedures, starting with enabling VBUS power.
31564956eccdSAlan Stern  * Other than re-initializing the hub (plug/unplug, except for root hubs),
315737ebb549SPetr Mladek  * Linux (2.6) currently has NO mechanisms to initiate that:  no hub_wq
31584956eccdSAlan Stern  * timer, no SRP, no requests through sysfs.
31594956eccdSAlan Stern  *
3160e583d9dbSAlan Stern  * If Runtime PM isn't enabled or used, non-SuperSpeed devices may not get
3161e583d9dbSAlan Stern  * suspended until their bus goes into global suspend (i.e., the root
31620aa2832dSAlan Stern  * hub is suspended).  Nevertheless, we change @udev->state to
31630aa2832dSAlan Stern  * USB_STATE_SUSPENDED as this is the device's "logical" state.  The actual
31640aa2832dSAlan Stern  * upstream port setting is stored in @udev->port_is_suspended.
31654956eccdSAlan Stern  *
31661da177e4SLinus Torvalds  * Returns 0 on success, else negative errno.
31671da177e4SLinus Torvalds  */
316865bfd296SAlan Stern int usb_port_suspend(struct usb_device *udev, pm_message_t msg)
31691da177e4SLinus Torvalds {
3170ad493e5eSLan Tianyu 	struct usb_hub	*hub = usb_hub_to_struct_hub(udev->parent);
3171ad493e5eSLan Tianyu 	struct usb_port *port_dev = hub->ports[udev->portnum - 1];
3172624d6c07SAlan Stern 	int		port1 = udev->portnum;
3173624d6c07SAlan Stern 	int		status;
31740aa2832dSAlan Stern 	bool		really_suspend = true;
31754956eccdSAlan Stern 
31765c79a1e3SDan Williams 	usb_lock_port(port_dev);
31775c79a1e3SDan Williams 
3178624d6c07SAlan Stern 	/* enable remote wakeup when appropriate; this lets the device
3179624d6c07SAlan Stern 	 * wake up the upstream hub (including maybe the root hub).
3180624d6c07SAlan Stern 	 *
3181624d6c07SAlan Stern 	 * NOTE:  OTG devices may issue remote wakeup (or SRP) even when
3182624d6c07SAlan Stern 	 * we don't explicitly enable it here.
3183624d6c07SAlan Stern 	 */
3184624d6c07SAlan Stern 	if (udev->do_remote_wakeup) {
318528e86165SAlan Stern 		status = usb_enable_remote_wakeup(udev);
31860c487206SOliver Neukum 		if (status) {
3187624d6c07SAlan Stern 			dev_dbg(&udev->dev, "won't remote wakeup, status %d\n",
3188624d6c07SAlan Stern 					status);
31890c487206SOliver Neukum 			/* bail if autosuspend is requested */
31905b1b0b81SAlan Stern 			if (PMSG_IS_AUTO(msg))
31914fae6f0fSAlan Stern 				goto err_wakeup;
31920c487206SOliver Neukum 		}
3193624d6c07SAlan Stern 	}
3194624d6c07SAlan Stern 
319565580b43SAndiry Xu 	/* disable USB2 hardware LPM */
319665580b43SAndiry Xu 	if (udev->usb2_hw_lpm_enabled == 1)
319765580b43SAndiry Xu 		usb_set_usb2_hardware_lpm(udev, 0);
319865580b43SAndiry Xu 
3199f74631e3SSarah Sharp 	if (usb_disable_ltm(udev)) {
32001ccc417eSJoe Perches 		dev_err(&udev->dev, "Failed to disable LTM before suspend\n");
32014fae6f0fSAlan Stern 		status = -ENOMEM;
32024fae6f0fSAlan Stern 		if (PMSG_IS_AUTO(msg))
32034fae6f0fSAlan Stern 			goto err_ltm;
3204f74631e3SSarah Sharp 	}
32058306095fSSarah Sharp 
3206624d6c07SAlan Stern 	/* see 7.1.7.6 */
3207a7114230SAndiry Xu 	if (hub_is_superspeed(hub->hdev))
3208c2f60db7SSarah Sharp 		status = hub_set_port_link_state(hub, port1, USB_SS_PORT_LS_U3);
3209e583d9dbSAlan Stern 
32100aa2832dSAlan Stern 	/*
32110aa2832dSAlan Stern 	 * For system suspend, we do not need to enable the suspend feature
32120aa2832dSAlan Stern 	 * on individual USB-2 ports.  The devices will automatically go
32130aa2832dSAlan Stern 	 * into suspend a few ms after the root hub stops sending packets.
32140aa2832dSAlan Stern 	 * The USB 2.0 spec calls this "global suspend".
3215e583d9dbSAlan Stern 	 *
3216e583d9dbSAlan Stern 	 * However, many USB hubs have a bug: They don't relay wakeup requests
3217e583d9dbSAlan Stern 	 * from a downstream port if the port's suspend feature isn't on.
3218e583d9dbSAlan Stern 	 * Therefore we will turn on the suspend feature if udev or any of its
3219e583d9dbSAlan Stern 	 * descendants is enabled for remote wakeup.
32200aa2832dSAlan Stern 	 */
3221e583d9dbSAlan Stern 	else if (PMSG_IS_AUTO(msg) || wakeup_enabled_descendants(udev) > 0)
3222e583d9dbSAlan Stern 		status = set_port_feature(hub->hdev, port1,
3223e583d9dbSAlan Stern 				USB_PORT_FEAT_SUSPEND);
32240aa2832dSAlan Stern 	else {
32250aa2832dSAlan Stern 		really_suspend = false;
32260aa2832dSAlan Stern 		status = 0;
32270aa2832dSAlan Stern 	}
3228624d6c07SAlan Stern 	if (status) {
3229d99f6b41SDan Williams 		dev_dbg(&port_dev->dev, "can't suspend, status %d\n", status);
3230cbb33004SAlan Stern 
3231d590c231SMathias Nyman 		/* Try to enable USB3 LTM again */
32324fae6f0fSAlan Stern 		usb_enable_ltm(udev);
32334fae6f0fSAlan Stern  err_ltm:
3234c3e751e4SAndiry Xu 		/* Try to enable USB2 hardware LPM again */
3235c3e751e4SAndiry Xu 		if (udev->usb2_hw_lpm_capable == 1)
3236c3e751e4SAndiry Xu 			usb_set_usb2_hardware_lpm(udev, 1);
3237c3e751e4SAndiry Xu 
32384fae6f0fSAlan Stern 		if (udev->do_remote_wakeup)
32394fae6f0fSAlan Stern 			(void) usb_disable_remote_wakeup(udev);
32404fae6f0fSAlan Stern  err_wakeup:
32418306095fSSarah Sharp 
3242cbb33004SAlan Stern 		/* System sleep transitions should never fail */
32435b1b0b81SAlan Stern 		if (!PMSG_IS_AUTO(msg))
3244cbb33004SAlan Stern 			status = 0;
3245624d6c07SAlan Stern 	} else {
324630b1a7a3SAlan Stern 		dev_dbg(&udev->dev, "usb %ssuspend, wakeup %d\n",
324730b1a7a3SAlan Stern 				(PMSG_IS_AUTO(msg) ? "auto-" : ""),
324830b1a7a3SAlan Stern 				udev->do_remote_wakeup);
32490aa2832dSAlan Stern 		if (really_suspend) {
3250bfd1e910SAlan Stern 			udev->port_is_suspended = 1;
3251e583d9dbSAlan Stern 
3252e583d9dbSAlan Stern 			/* device has up to 10 msec to fully suspend */
3253624d6c07SAlan Stern 			msleep(10);
3254624d6c07SAlan Stern 		}
3255e583d9dbSAlan Stern 		usb_set_device_state(udev, USB_STATE_SUSPENDED);
32560aa2832dSAlan Stern 	}
3257ad493e5eSLan Tianyu 
3258d5c3834eSDan Williams 	if (status == 0 && !udev->do_remote_wakeup && udev->persist_enabled
3259d5c3834eSDan Williams 			&& test_and_clear_bit(port1, hub->child_usage_bits))
3260ad493e5eSLan Tianyu 		pm_runtime_put_sync(&port_dev->dev);
3261ad493e5eSLan Tianyu 
3262c08512c7SAlan Stern 	usb_mark_last_busy(hub->hdev);
32635c79a1e3SDan Williams 
32645c79a1e3SDan Williams 	usb_unlock_port(port_dev);
32654956eccdSAlan Stern 	return status;
32661da177e4SLinus Torvalds }
3267f3f3253dSDavid Brownell 
32681da177e4SLinus Torvalds /*
3269390a8c34SDavid Brownell  * If the USB "suspend" state is in use (rather than "global suspend"),
3270390a8c34SDavid Brownell  * many devices will be individually taken out of suspend state using
327154515fe5SAlan Stern  * special "resume" signaling.  This routine kicks in shortly after
32721da177e4SLinus Torvalds  * hardware resume signaling is finished, either because of selective
32731da177e4SLinus Torvalds  * resume (by host) or remote wakeup (by device) ... now see what changed
32741da177e4SLinus Torvalds  * in the tree that's rooted at this device.
327554515fe5SAlan Stern  *
327654515fe5SAlan Stern  * If @udev->reset_resume is set then the device is reset before the
327754515fe5SAlan Stern  * status check is done.
32781da177e4SLinus Torvalds  */
3279140d8f68SAlan Stern static int finish_port_resume(struct usb_device *udev)
32801da177e4SLinus Torvalds {
328154515fe5SAlan Stern 	int	status = 0;
328207e72b95SOliver Neukum 	u16	devstatus = 0;
32831da177e4SLinus Torvalds 
32841da177e4SLinus Torvalds 	/* caller owns the udev device lock */
3285b9cef6c3SWu Fengguang 	dev_dbg(&udev->dev, "%s\n",
3286b9cef6c3SWu Fengguang 		udev->reset_resume ? "finish reset-resume" : "finish resume");
32871da177e4SLinus Torvalds 
32881da177e4SLinus Torvalds 	/* usb ch9 identifies four variants of SUSPENDED, based on what
32891da177e4SLinus Torvalds 	 * state the device resumes to.  Linux currently won't see the
32901da177e4SLinus Torvalds 	 * first two on the host side; they'd be inside hub_port_init()
329137ebb549SPetr Mladek 	 * during many timeouts, but hub_wq can't suspend until later.
32921da177e4SLinus Torvalds 	 */
32931da177e4SLinus Torvalds 	usb_set_device_state(udev, udev->actconfig
32941da177e4SLinus Torvalds 			? USB_STATE_CONFIGURED
32951da177e4SLinus Torvalds 			: USB_STATE_ADDRESS);
32961da177e4SLinus Torvalds 
329754515fe5SAlan Stern 	/* 10.5.4.5 says not to reset a suspended port if the attached
329854515fe5SAlan Stern 	 * device is enabled for remote wakeup.  Hence the reset
329954515fe5SAlan Stern 	 * operation is carried out here, after the port has been
330054515fe5SAlan Stern 	 * resumed.
330154515fe5SAlan Stern 	 */
33021d10255cSAlan Stern 	if (udev->reset_resume) {
33031d10255cSAlan Stern 		/*
33041d10255cSAlan Stern 		 * If the device morphs or switches modes when it is reset,
33051d10255cSAlan Stern 		 * we don't want to perform a reset-resume.  We'll fail the
33061d10255cSAlan Stern 		 * resume, which will cause a logical disconnect, and then
33071d10255cSAlan Stern 		 * the device will be rediscovered.
33081d10255cSAlan Stern 		 */
330986c57edfSAlan Stern  retry_reset_resume:
33101d10255cSAlan Stern 		if (udev->quirks & USB_QUIRK_RESET)
33111d10255cSAlan Stern 			status = -ENODEV;
33121d10255cSAlan Stern 		else
3313742120c6SMing Lei 			status = usb_reset_and_verify_device(udev);
33141d10255cSAlan Stern 	}
331554515fe5SAlan Stern 
33161da177e4SLinus Torvalds 	/* 10.5.4.5 says be sure devices in the tree are still there.
33171da177e4SLinus Torvalds 	 * For now let's assume the device didn't go crazy on resume,
33181da177e4SLinus Torvalds 	 * and device drivers will know about any resume quirks.
33191da177e4SLinus Torvalds 	 */
332054515fe5SAlan Stern 	if (status == 0) {
332146dede46SAlan Stern 		devstatus = 0;
3322d9e1e148SFelipe Balbi 		status = usb_get_std_status(udev, USB_RECIP_DEVICE, 0, &devstatus);
332386c57edfSAlan Stern 
332486c57edfSAlan Stern 		/* If a normal resume failed, try doing a reset-resume */
332586c57edfSAlan Stern 		if (status && !udev->reset_resume && udev->persist_enabled) {
332686c57edfSAlan Stern 			dev_dbg(&udev->dev, "retry with reset-resume\n");
332786c57edfSAlan Stern 			udev->reset_resume = 1;
332886c57edfSAlan Stern 			goto retry_reset_resume;
332986c57edfSAlan Stern 		}
333054515fe5SAlan Stern 	}
3331b40b7a90SAlan Stern 
3332624d6c07SAlan Stern 	if (status) {
3333624d6c07SAlan Stern 		dev_dbg(&udev->dev, "gone after usb resume? status %d\n",
33341da177e4SLinus Torvalds 				status);
333507e72b95SOliver Neukum 	/*
333607e72b95SOliver Neukum 	 * There are a few quirky devices which violate the standard
333707e72b95SOliver Neukum 	 * by claiming to have remote wakeup enabled after a reset,
333807e72b95SOliver Neukum 	 * which crash if the feature is cleared, hence check for
333907e72b95SOliver Neukum 	 * udev->reset_resume
334007e72b95SOliver Neukum 	 */
334107e72b95SOliver Neukum 	} else if (udev->actconfig && !udev->reset_resume) {
334228e86165SAlan Stern 		if (udev->speed < USB_SPEED_SUPER) {
334354a3ac0cSLan Tianyu 			if (devstatus & (1 << USB_DEVICE_REMOTE_WAKEUP))
334428e86165SAlan Stern 				status = usb_disable_remote_wakeup(udev);
334554a3ac0cSLan Tianyu 		} else {
3346d9e1e148SFelipe Balbi 			status = usb_get_std_status(udev, USB_RECIP_INTERFACE, 0,
334754a3ac0cSLan Tianyu 					&devstatus);
334854a3ac0cSLan Tianyu 			if (!status && devstatus & (USB_INTRF_STAT_FUNC_RW_CAP
334954a3ac0cSLan Tianyu 					| USB_INTRF_STAT_FUNC_RW))
335028e86165SAlan Stern 				status = usb_disable_remote_wakeup(udev);
335154a3ac0cSLan Tianyu 		}
335254a3ac0cSLan Tianyu 
3353a8e7c565SAlan Stern 		if (status)
3354b9cef6c3SWu Fengguang 			dev_dbg(&udev->dev,
3355b9cef6c3SWu Fengguang 				"disable remote wakeup, status %d\n",
3356b9cef6c3SWu Fengguang 				status);
33571da177e4SLinus Torvalds 		status = 0;
33581da177e4SLinus Torvalds 	}
33591da177e4SLinus Torvalds 	return status;
33601da177e4SLinus Torvalds }
33611da177e4SLinus Torvalds 
3362624d6c07SAlan Stern /*
3363a40178b2SPratyush Anand  * There are some SS USB devices which take longer time for link training.
3364a40178b2SPratyush Anand  * XHCI specs 4.19.4 says that when Link training is successful, port
33656b82b122SAl Cooper  * sets CCS bit to 1. So if SW reads port status before successful link
3366a40178b2SPratyush Anand  * training, then it will not find device to be present.
3367a40178b2SPratyush Anand  * USB Analyzer log with such buggy devices show that in some cases
3368a40178b2SPratyush Anand  * device switch on the RX termination after long delay of host enabling
3369a40178b2SPratyush Anand  * the VBUS. In few other cases it has been seen that device fails to
3370a40178b2SPratyush Anand  * negotiate link training in first attempt. It has been
3371a40178b2SPratyush Anand  * reported till now that few devices take as long as 2000 ms to train
3372a40178b2SPratyush Anand  * the link after host enabling its VBUS and termination. Following
3373a40178b2SPratyush Anand  * routine implements a 2000 ms timeout for link training. If in a case
3374a40178b2SPratyush Anand  * link trains before timeout, loop will exit earlier.
3375a40178b2SPratyush Anand  *
33766b82b122SAl Cooper  * There are also some 2.0 hard drive based devices and 3.0 thumb
33776b82b122SAl Cooper  * drives that, when plugged into a 2.0 only port, take a long
33786b82b122SAl Cooper  * time to set CCS after VBUS enable.
33796b82b122SAl Cooper  *
3380a40178b2SPratyush Anand  * FIXME: If a device was connected before suspend, but was removed
3381a40178b2SPratyush Anand  * while system was asleep, then the loop in the following routine will
3382a40178b2SPratyush Anand  * only exit at timeout.
3383a40178b2SPratyush Anand  *
33846b82b122SAl Cooper  * This routine should only be called when persist is enabled.
3385a40178b2SPratyush Anand  */
33866b82b122SAl Cooper static int wait_for_connected(struct usb_device *udev,
3387a40178b2SPratyush Anand 		struct usb_hub *hub, int *port1,
3388a40178b2SPratyush Anand 		u16 *portchange, u16 *portstatus)
3389a40178b2SPratyush Anand {
3390a40178b2SPratyush Anand 	int status = 0, delay_ms = 0;
3391a40178b2SPratyush Anand 
3392a40178b2SPratyush Anand 	while (delay_ms < 2000) {
3393a40178b2SPratyush Anand 		if (status || *portstatus & USB_PORT_STAT_CONNECTION)
3394a40178b2SPratyush Anand 			break;
33955d111f51SDominik Bozek 		if (!port_is_power_on(hub, *portstatus)) {
33965d111f51SDominik Bozek 			status = -ENODEV;
33975d111f51SDominik Bozek 			break;
33985d111f51SDominik Bozek 		}
3399a40178b2SPratyush Anand 		msleep(20);
3400a40178b2SPratyush Anand 		delay_ms += 20;
3401a40178b2SPratyush Anand 		status = hub_port_status(hub, *port1, portstatus, portchange);
3402a40178b2SPratyush Anand 	}
34036b82b122SAl Cooper 	dev_dbg(&udev->dev, "Waited %dms for CONNECT\n", delay_ms);
3404a40178b2SPratyush Anand 	return status;
3405a40178b2SPratyush Anand }
3406a40178b2SPratyush Anand 
3407a40178b2SPratyush Anand /*
3408624d6c07SAlan Stern  * usb_port_resume - re-activate a suspended usb device's upstream port
3409624d6c07SAlan Stern  * @udev: device to re-activate, not a root hub
3410624d6c07SAlan Stern  * Context: must be able to sleep; device not locked; pm locks held
3411624d6c07SAlan Stern  *
3412624d6c07SAlan Stern  * This will re-activate the suspended device, increasing power usage
3413624d6c07SAlan Stern  * while letting drivers communicate again with its endpoints.
3414624d6c07SAlan Stern  * USB resume explicitly guarantees that the power session between
3415624d6c07SAlan Stern  * the host and the device is the same as it was when the device
3416624d6c07SAlan Stern  * suspended.
3417624d6c07SAlan Stern  *
3418feccc30dSAlan Stern  * If @udev->reset_resume is set then this routine won't check that the
3419feccc30dSAlan Stern  * port is still enabled.  Furthermore, finish_port_resume() above will
342054515fe5SAlan Stern  * reset @udev.  The end result is that a broken power session can be
342154515fe5SAlan Stern  * recovered and @udev will appear to persist across a loss of VBUS power.
342254515fe5SAlan Stern  *
342354515fe5SAlan Stern  * For example, if a host controller doesn't maintain VBUS suspend current
342454515fe5SAlan Stern  * during a system sleep or is reset when the system wakes up, all the USB
342554515fe5SAlan Stern  * power sessions below it will be broken.  This is especially troublesome
342654515fe5SAlan Stern  * for mass-storage devices containing mounted filesystems, since the
342754515fe5SAlan Stern  * device will appear to have disconnected and all the memory mappings
342854515fe5SAlan Stern  * to it will be lost.  Using the USB_PERSIST facility, the device can be
342954515fe5SAlan Stern  * made to appear as if it had not disconnected.
343054515fe5SAlan Stern  *
3431742120c6SMing Lei  * This facility can be dangerous.  Although usb_reset_and_verify_device() makes
3432feccc30dSAlan Stern  * every effort to insure that the same device is present after the
343354515fe5SAlan Stern  * reset as before, it cannot provide a 100% guarantee.  Furthermore it's
343454515fe5SAlan Stern  * quite possible for a device to remain unaltered but its media to be
343554515fe5SAlan Stern  * changed.  If the user replaces a flash memory card while the system is
343654515fe5SAlan Stern  * asleep, he will have only himself to blame when the filesystem on the
343754515fe5SAlan Stern  * new card is corrupted and the system crashes.
343854515fe5SAlan Stern  *
3439624d6c07SAlan Stern  * Returns 0 on success, else negative errno.
3440624d6c07SAlan Stern  */
344165bfd296SAlan Stern int usb_port_resume(struct usb_device *udev, pm_message_t msg)
34421da177e4SLinus Torvalds {
3443ad493e5eSLan Tianyu 	struct usb_hub	*hub = usb_hub_to_struct_hub(udev->parent);
3444ad493e5eSLan Tianyu 	struct usb_port *port_dev = hub->ports[udev->portnum  - 1];
3445624d6c07SAlan Stern 	int		port1 = udev->portnum;
34461da177e4SLinus Torvalds 	int		status;
3447d25450c6SAlan Stern 	u16		portchange, portstatus;
3448d25450c6SAlan Stern 
3449d5c3834eSDan Williams 	if (!test_and_set_bit(port1, hub->child_usage_bits)) {
3450ad493e5eSLan Tianyu 		status = pm_runtime_get_sync(&port_dev->dev);
3451ad493e5eSLan Tianyu 		if (status < 0) {
3452ad493e5eSLan Tianyu 			dev_dbg(&udev->dev, "can't resume usb port, status %d\n",
3453ad493e5eSLan Tianyu 					status);
3454ad493e5eSLan Tianyu 			return status;
3455ad493e5eSLan Tianyu 		}
3456ad493e5eSLan Tianyu 	}
3457ad493e5eSLan Tianyu 
34585c79a1e3SDan Williams 	usb_lock_port(port_dev);
34595c79a1e3SDan Williams 
3460d25450c6SAlan Stern 	/* Skip the initial Clear-Suspend step for a remote wakeup */
3461d25450c6SAlan Stern 	status = hub_port_status(hub, port1, &portstatus, &portchange);
346283a62c51SRavi Chandra Sadineni 	if (status == 0 && !port_is_suspended(hub, portstatus)) {
346383a62c51SRavi Chandra Sadineni 		if (portchange & USB_PORT_STAT_C_SUSPEND)
346483a62c51SRavi Chandra Sadineni 			pm_wakeup_event(&udev->dev, 0);
3465d25450c6SAlan Stern 		goto SuspendCleared;
346683a62c51SRavi Chandra Sadineni 	}
34671da177e4SLinus Torvalds 
34681da177e4SLinus Torvalds 	/* see 7.1.7.7; affects power usage, but not budgeting */
3469a7114230SAndiry Xu 	if (hub_is_superspeed(hub->hdev))
3470c2f60db7SSarah Sharp 		status = hub_set_port_link_state(hub, port1, USB_SS_PORT_LS_U0);
3471a7114230SAndiry Xu 	else
3472ad493e5eSLan Tianyu 		status = usb_clear_port_feature(hub->hdev,
34731da177e4SLinus Torvalds 				port1, USB_PORT_FEAT_SUSPEND);
34741da177e4SLinus Torvalds 	if (status) {
3475d99f6b41SDan Williams 		dev_dbg(&port_dev->dev, "can't resume, status %d\n", status);
34761da177e4SLinus Torvalds 	} else {
3477bbc78c07SFelipe Balbi 		/* drive resume for USB_RESUME_TIMEOUT msec */
3478645daaabSAlan Stern 		dev_dbg(&udev->dev, "usb %sresume\n",
34795b1b0b81SAlan Stern 				(PMSG_IS_AUTO(msg) ? "auto-" : ""));
3480bbc78c07SFelipe Balbi 		msleep(USB_RESUME_TIMEOUT);
34811da177e4SLinus Torvalds 
34821da177e4SLinus Torvalds 		/* Virtual root hubs can trigger on GET_PORT_STATUS to
34831da177e4SLinus Torvalds 		 * stop resume signaling.  Then finish the resume
34841da177e4SLinus Torvalds 		 * sequence.
34851da177e4SLinus Torvalds 		 */
3486d25450c6SAlan Stern 		status = hub_port_status(hub, port1, &portstatus, &portchange);
348754515fe5SAlan Stern 
34881da177e4SLinus Torvalds 		/* TRSMRCY = 10 msec */
34891da177e4SLinus Torvalds 		msleep(10);
34901da177e4SLinus Torvalds 	}
3491b01b03f3SAlan Stern 
3492b01b03f3SAlan Stern  SuspendCleared:
3493b01b03f3SAlan Stern 	if (status == 0) {
3494bfd1e910SAlan Stern 		udev->port_is_suspended = 0;
3495a7114230SAndiry Xu 		if (hub_is_superspeed(hub->hdev)) {
3496a7114230SAndiry Xu 			if (portchange & USB_PORT_STAT_C_LINK_STATE)
3497ad493e5eSLan Tianyu 				usb_clear_port_feature(hub->hdev, port1,
3498a7114230SAndiry Xu 					USB_PORT_FEAT_C_PORT_LINK_STATE);
3499a7114230SAndiry Xu 		} else {
3500b01b03f3SAlan Stern 			if (portchange & USB_PORT_STAT_C_SUSPEND)
3501ad493e5eSLan Tianyu 				usb_clear_port_feature(hub->hdev, port1,
3502b01b03f3SAlan Stern 						USB_PORT_FEAT_C_SUSPEND);
35031da177e4SLinus Torvalds 		}
3504a7114230SAndiry Xu 	}
35051da177e4SLinus Torvalds 
35066b82b122SAl Cooper 	if (udev->persist_enabled)
35076b82b122SAl Cooper 		status = wait_for_connected(udev, hub, &port1, &portchange,
3508a40178b2SPratyush Anand 				&portstatus);
3509a40178b2SPratyush Anand 
3510b01b03f3SAlan Stern 	status = check_port_resume_type(udev,
3511b01b03f3SAlan Stern 			hub, port1, status, portchange, portstatus);
351254515fe5SAlan Stern 	if (status == 0)
351354515fe5SAlan Stern 		status = finish_port_resume(udev);
351454515fe5SAlan Stern 	if (status < 0) {
351554515fe5SAlan Stern 		dev_dbg(&udev->dev, "can't resume, status %d\n", status);
351654515fe5SAlan Stern 		hub_port_logical_disconnect(hub, port1);
351765580b43SAndiry Xu 	} else  {
351865580b43SAndiry Xu 		/* Try to enable USB2 hardware LPM */
351965580b43SAndiry Xu 		if (udev->usb2_hw_lpm_capable == 1)
352065580b43SAndiry Xu 			usb_set_usb2_hardware_lpm(udev, 1);
35218306095fSSarah Sharp 
3522d590c231SMathias Nyman 		/* Try to enable USB3 LTM */
3523f74631e3SSarah Sharp 		usb_enable_ltm(udev);
352454515fe5SAlan Stern 	}
352565580b43SAndiry Xu 
35265c79a1e3SDan Williams 	usb_unlock_port(port_dev);
35275c79a1e3SDan Williams 
35281da177e4SLinus Torvalds 	return status;
35291da177e4SLinus Torvalds }
35301da177e4SLinus Torvalds 
35310534d468SAlan Stern int usb_remote_wakeup(struct usb_device *udev)
35321da177e4SLinus Torvalds {
35331da177e4SLinus Torvalds 	int	status = 0;
35341da177e4SLinus Torvalds 
35355c79a1e3SDan Williams 	usb_lock_device(udev);
35361da177e4SLinus Torvalds 	if (udev->state == USB_STATE_SUSPENDED) {
3537645daaabSAlan Stern 		dev_dbg(&udev->dev, "usb %sresume\n", "wakeup-");
35389bbdf1e0SAlan Stern 		status = usb_autoresume_device(udev);
35399bbdf1e0SAlan Stern 		if (status == 0) {
35409bbdf1e0SAlan Stern 			/* Let the drivers do their thing, then... */
35419bbdf1e0SAlan Stern 			usb_autosuspend_device(udev);
35429bbdf1e0SAlan Stern 		}
3543d25450c6SAlan Stern 	}
35445c79a1e3SDan Williams 	usb_unlock_device(udev);
35451da177e4SLinus Torvalds 	return status;
35461da177e4SLinus Torvalds }
35471da177e4SLinus Torvalds 
35487e73be22SDan Williams /* Returns 1 if there was a remote wakeup and a connect status change. */
35497e73be22SDan Williams static int hub_handle_remote_wakeup(struct usb_hub *hub, unsigned int port,
35507e73be22SDan Williams 		u16 portstatus, u16 portchange)
35517e73be22SDan Williams 		__must_hold(&port_dev->status_lock)
35527e73be22SDan Williams {
35537e73be22SDan Williams 	struct usb_port *port_dev = hub->ports[port - 1];
35547e73be22SDan Williams 	struct usb_device *hdev;
35557e73be22SDan Williams 	struct usb_device *udev;
35567e73be22SDan Williams 	int connect_change = 0;
35577e73be22SDan Williams 	int ret;
35587e73be22SDan Williams 
35597e73be22SDan Williams 	hdev = hub->hdev;
35607e73be22SDan Williams 	udev = port_dev->child;
35617e73be22SDan Williams 	if (!hub_is_superspeed(hdev)) {
35627e73be22SDan Williams 		if (!(portchange & USB_PORT_STAT_C_SUSPEND))
35637e73be22SDan Williams 			return 0;
35647e73be22SDan Williams 		usb_clear_port_feature(hdev, port, USB_PORT_FEAT_C_SUSPEND);
35657e73be22SDan Williams 	} else {
35667e73be22SDan Williams 		if (!udev || udev->state != USB_STATE_SUSPENDED ||
35677e73be22SDan Williams 				 (portstatus & USB_PORT_STAT_LINK_STATE) !=
35687e73be22SDan Williams 				 USB_SS_PORT_LS_U0)
35697e73be22SDan Williams 			return 0;
35707e73be22SDan Williams 	}
35717e73be22SDan Williams 
35727e73be22SDan Williams 	if (udev) {
35737e73be22SDan Williams 		/* TRSMRCY = 10 msec */
35747e73be22SDan Williams 		msleep(10);
35757e73be22SDan Williams 
35767e73be22SDan Williams 		usb_unlock_port(port_dev);
35777e73be22SDan Williams 		ret = usb_remote_wakeup(udev);
35787e73be22SDan Williams 		usb_lock_port(port_dev);
35797e73be22SDan Williams 		if (ret < 0)
35807e73be22SDan Williams 			connect_change = 1;
35817e73be22SDan Williams 	} else {
35827e73be22SDan Williams 		ret = -ENODEV;
35837e73be22SDan Williams 		hub_port_disable(hub, port, 1);
35847e73be22SDan Williams 	}
35857e73be22SDan Williams 	dev_dbg(&port_dev->dev, "resume, status %d\n", ret);
35867e73be22SDan Williams 	return connect_change;
35877e73be22SDan Williams }
35887e73be22SDan Williams 
3589e6f30deaSMing Lei static int check_ports_changed(struct usb_hub *hub)
3590e6f30deaSMing Lei {
3591e6f30deaSMing Lei 	int port1;
3592e6f30deaSMing Lei 
3593e6f30deaSMing Lei 	for (port1 = 1; port1 <= hub->hdev->maxchild; ++port1) {
3594e6f30deaSMing Lei 		u16 portstatus, portchange;
3595e6f30deaSMing Lei 		int status;
3596e6f30deaSMing Lei 
3597e6f30deaSMing Lei 		status = hub_port_status(hub, port1, &portstatus, &portchange);
3598e6f30deaSMing Lei 		if (!status && portchange)
3599e6f30deaSMing Lei 			return 1;
3600e6f30deaSMing Lei 	}
3601e6f30deaSMing Lei 	return 0;
3602e6f30deaSMing Lei }
3603e6f30deaSMing Lei 
3604db690874SDavid Brownell static int hub_suspend(struct usb_interface *intf, pm_message_t msg)
36051da177e4SLinus Torvalds {
36061da177e4SLinus Torvalds 	struct usb_hub		*hub = usb_get_intfdata(intf);
36071da177e4SLinus Torvalds 	struct usb_device	*hdev = hub->hdev;
36081da177e4SLinus Torvalds 	unsigned		port1;
36094296c70aSSarah Sharp 	int			status;
36101da177e4SLinus Torvalds 
3611e583d9dbSAlan Stern 	/*
3612e583d9dbSAlan Stern 	 * Warn if children aren't already suspended.
3613e583d9dbSAlan Stern 	 * Also, add up the number of wakeup-enabled descendants.
3614e583d9dbSAlan Stern 	 */
3615e583d9dbSAlan Stern 	hub->wakeup_enabled_descendants = 0;
36161da177e4SLinus Torvalds 	for (port1 = 1; port1 <= hdev->maxchild; port1++) {
3617d99f6b41SDan Williams 		struct usb_port *port_dev = hub->ports[port1 - 1];
3618d99f6b41SDan Williams 		struct usb_device *udev = port_dev->child;
36191da177e4SLinus Torvalds 
36206840d255SAlan Stern 		if (udev && udev->can_submit) {
3621b658b8f5SDan Williams 			dev_warn(&port_dev->dev, "device %s not suspended yet\n",
3622b658b8f5SDan Williams 					dev_name(&udev->dev));
36235b1b0b81SAlan Stern 			if (PMSG_IS_AUTO(msg))
3624c9f89fa4SDavid Brownell 				return -EBUSY;
3625c9f89fa4SDavid Brownell 		}
3626e583d9dbSAlan Stern 		if (udev)
3627e583d9dbSAlan Stern 			hub->wakeup_enabled_descendants +=
3628e583d9dbSAlan Stern 					wakeup_enabled_descendants(udev);
36291da177e4SLinus Torvalds 	}
3630e6f30deaSMing Lei 
3631e6f30deaSMing Lei 	if (hdev->do_remote_wakeup && hub->quirk_check_port_auto_suspend) {
3632e6f30deaSMing Lei 		/* check if there are changes pending on hub ports */
3633e6f30deaSMing Lei 		if (check_ports_changed(hub)) {
3634e6f30deaSMing Lei 			if (PMSG_IS_AUTO(msg))
3635e6f30deaSMing Lei 				return -EBUSY;
3636e6f30deaSMing Lei 			pm_wakeup_event(&hdev->dev, 2000);
3637e6f30deaSMing Lei 		}
3638e6f30deaSMing Lei 	}
3639e6f30deaSMing Lei 
36404296c70aSSarah Sharp 	if (hub_is_superspeed(hdev) && hdev->do_remote_wakeup) {
36414296c70aSSarah Sharp 		/* Enable hub to send remote wakeup for all ports. */
36424296c70aSSarah Sharp 		for (port1 = 1; port1 <= hdev->maxchild; port1++) {
36434296c70aSSarah Sharp 			status = set_port_feature(hdev,
36444296c70aSSarah Sharp 					port1 |
36454296c70aSSarah Sharp 					USB_PORT_FEAT_REMOTE_WAKE_CONNECT |
36464296c70aSSarah Sharp 					USB_PORT_FEAT_REMOTE_WAKE_DISCONNECT |
36474296c70aSSarah Sharp 					USB_PORT_FEAT_REMOTE_WAKE_OVER_CURRENT,
36484296c70aSSarah Sharp 					USB_PORT_FEAT_REMOTE_WAKE_MASK);
36494296c70aSSarah Sharp 		}
36504296c70aSSarah Sharp 	}
36511da177e4SLinus Torvalds 
3652441b62c1SHarvey Harrison 	dev_dbg(&intf->dev, "%s\n", __func__);
365340f122f3SAlan Stern 
365437ebb549SPetr Mladek 	/* stop hub_wq and related activity */
36554330354fSAlan Stern 	hub_quiesce(hub, HUB_SUSPEND);
3656b6f6436dSAlan Stern 	return 0;
36571da177e4SLinus Torvalds }
36581da177e4SLinus Torvalds 
36591da177e4SLinus Torvalds static int hub_resume(struct usb_interface *intf)
36601da177e4SLinus Torvalds {
36611da177e4SLinus Torvalds 	struct usb_hub *hub = usb_get_intfdata(intf);
36621da177e4SLinus Torvalds 
36635e6effaeSAlan Stern 	dev_dbg(&intf->dev, "%s\n", __func__);
3664f2835219SAlan Stern 	hub_activate(hub, HUB_RESUME);
36651da177e4SLinus Torvalds 	return 0;
36661da177e4SLinus Torvalds }
36671da177e4SLinus Torvalds 
3668b41a60ecSAlan Stern static int hub_reset_resume(struct usb_interface *intf)
3669f07600cfSAlan Stern {
3670b41a60ecSAlan Stern 	struct usb_hub *hub = usb_get_intfdata(intf);
3671f07600cfSAlan Stern 
36725e6effaeSAlan Stern 	dev_dbg(&intf->dev, "%s\n", __func__);
3673f2835219SAlan Stern 	hub_activate(hub, HUB_RESET_RESUME);
3674f07600cfSAlan Stern 	return 0;
3675f07600cfSAlan Stern }
3676f07600cfSAlan Stern 
367754515fe5SAlan Stern /**
367854515fe5SAlan Stern  * usb_root_hub_lost_power - called by HCD if the root hub lost Vbus power
367954515fe5SAlan Stern  * @rhdev: struct usb_device for the root hub
368054515fe5SAlan Stern  *
368154515fe5SAlan Stern  * The USB host controller driver calls this function when its root hub
368254515fe5SAlan Stern  * is resumed and Vbus power has been interrupted or the controller
3683feccc30dSAlan Stern  * has been reset.  The routine marks @rhdev as having lost power.
3684feccc30dSAlan Stern  * When the hub driver is resumed it will take notice and carry out
3685feccc30dSAlan Stern  * power-session recovery for all the "USB-PERSIST"-enabled child devices;
3686feccc30dSAlan Stern  * the others will be disconnected.
368754515fe5SAlan Stern  */
368854515fe5SAlan Stern void usb_root_hub_lost_power(struct usb_device *rhdev)
368954515fe5SAlan Stern {
36900442d7b0STomeu Vizoso 	dev_notice(&rhdev->dev, "root hub lost power or was reset\n");
369154515fe5SAlan Stern 	rhdev->reset_resume = 1;
369254515fe5SAlan Stern }
369354515fe5SAlan Stern EXPORT_SYMBOL_GPL(usb_root_hub_lost_power);
369454515fe5SAlan Stern 
36951ea7e0e8SSarah Sharp static const char * const usb3_lpm_names[]  = {
36961ea7e0e8SSarah Sharp 	"U0",
36971ea7e0e8SSarah Sharp 	"U1",
36981ea7e0e8SSarah Sharp 	"U2",
36991ea7e0e8SSarah Sharp 	"U3",
37001ea7e0e8SSarah Sharp };
37011ea7e0e8SSarah Sharp 
37021ea7e0e8SSarah Sharp /*
37031ea7e0e8SSarah Sharp  * Send a Set SEL control transfer to the device, prior to enabling
37041ea7e0e8SSarah Sharp  * device-initiated U1 or U2.  This lets the device know the exit latencies from
37051ea7e0e8SSarah Sharp  * the time the device initiates a U1 or U2 exit, to the time it will receive a
37061ea7e0e8SSarah Sharp  * packet from the host.
37071ea7e0e8SSarah Sharp  *
37081ea7e0e8SSarah Sharp  * This function will fail if the SEL or PEL values for udev are greater than
37091ea7e0e8SSarah Sharp  * the maximum allowed values for the link state to be enabled.
37101ea7e0e8SSarah Sharp  */
37111ea7e0e8SSarah Sharp static int usb_req_set_sel(struct usb_device *udev, enum usb3_link_state state)
37121ea7e0e8SSarah Sharp {
37131ea7e0e8SSarah Sharp 	struct usb_set_sel_req *sel_values;
37141ea7e0e8SSarah Sharp 	unsigned long long u1_sel;
37151ea7e0e8SSarah Sharp 	unsigned long long u1_pel;
37161ea7e0e8SSarah Sharp 	unsigned long long u2_sel;
37171ea7e0e8SSarah Sharp 	unsigned long long u2_pel;
37181ea7e0e8SSarah Sharp 	int ret;
37191ea7e0e8SSarah Sharp 
372038d7f688SXenia Ragiadakou 	if (udev->state != USB_STATE_CONFIGURED)
372138d7f688SXenia Ragiadakou 		return 0;
372238d7f688SXenia Ragiadakou 
37231ea7e0e8SSarah Sharp 	/* Convert SEL and PEL stored in ns to us */
37241ea7e0e8SSarah Sharp 	u1_sel = DIV_ROUND_UP(udev->u1_params.sel, 1000);
37251ea7e0e8SSarah Sharp 	u1_pel = DIV_ROUND_UP(udev->u1_params.pel, 1000);
37261ea7e0e8SSarah Sharp 	u2_sel = DIV_ROUND_UP(udev->u2_params.sel, 1000);
37271ea7e0e8SSarah Sharp 	u2_pel = DIV_ROUND_UP(udev->u2_params.pel, 1000);
37281ea7e0e8SSarah Sharp 
37291ea7e0e8SSarah Sharp 	/*
37301ea7e0e8SSarah Sharp 	 * Make sure that the calculated SEL and PEL values for the link
37311ea7e0e8SSarah Sharp 	 * state we're enabling aren't bigger than the max SEL/PEL
37321ea7e0e8SSarah Sharp 	 * value that will fit in the SET SEL control transfer.
37331ea7e0e8SSarah Sharp 	 * Otherwise the device would get an incorrect idea of the exit
37341ea7e0e8SSarah Sharp 	 * latency for the link state, and could start a device-initiated
37351ea7e0e8SSarah Sharp 	 * U1/U2 when the exit latencies are too high.
37361ea7e0e8SSarah Sharp 	 */
37371ea7e0e8SSarah Sharp 	if ((state == USB3_LPM_U1 &&
37381ea7e0e8SSarah Sharp 				(u1_sel > USB3_LPM_MAX_U1_SEL_PEL ||
37391ea7e0e8SSarah Sharp 				 u1_pel > USB3_LPM_MAX_U1_SEL_PEL)) ||
37401ea7e0e8SSarah Sharp 			(state == USB3_LPM_U2 &&
37411ea7e0e8SSarah Sharp 			 (u2_sel > USB3_LPM_MAX_U2_SEL_PEL ||
37421ea7e0e8SSarah Sharp 			  u2_pel > USB3_LPM_MAX_U2_SEL_PEL))) {
37431510a1a2SSarah Sharp 		dev_dbg(&udev->dev, "Device-initiated %s disabled due to long SEL %llu us or PEL %llu us\n",
37441ea7e0e8SSarah Sharp 				usb3_lpm_names[state], u1_sel, u1_pel);
37451ea7e0e8SSarah Sharp 		return -EINVAL;
37461ea7e0e8SSarah Sharp 	}
37471ea7e0e8SSarah Sharp 
37481ea7e0e8SSarah Sharp 	/*
37491ea7e0e8SSarah Sharp 	 * If we're enabling device-initiated LPM for one link state,
37501ea7e0e8SSarah Sharp 	 * but the other link state has a too high SEL or PEL value,
37511ea7e0e8SSarah Sharp 	 * just set those values to the max in the Set SEL request.
37521ea7e0e8SSarah Sharp 	 */
37531ea7e0e8SSarah Sharp 	if (u1_sel > USB3_LPM_MAX_U1_SEL_PEL)
37541ea7e0e8SSarah Sharp 		u1_sel = USB3_LPM_MAX_U1_SEL_PEL;
37551ea7e0e8SSarah Sharp 
37561ea7e0e8SSarah Sharp 	if (u1_pel > USB3_LPM_MAX_U1_SEL_PEL)
37571ea7e0e8SSarah Sharp 		u1_pel = USB3_LPM_MAX_U1_SEL_PEL;
37581ea7e0e8SSarah Sharp 
37591ea7e0e8SSarah Sharp 	if (u2_sel > USB3_LPM_MAX_U2_SEL_PEL)
37601ea7e0e8SSarah Sharp 		u2_sel = USB3_LPM_MAX_U2_SEL_PEL;
37611ea7e0e8SSarah Sharp 
37621ea7e0e8SSarah Sharp 	if (u2_pel > USB3_LPM_MAX_U2_SEL_PEL)
37631ea7e0e8SSarah Sharp 		u2_pel = USB3_LPM_MAX_U2_SEL_PEL;
37641ea7e0e8SSarah Sharp 
37651ea7e0e8SSarah Sharp 	/*
37661ea7e0e8SSarah Sharp 	 * usb_enable_lpm() can be called as part of a failed device reset,
37671ea7e0e8SSarah Sharp 	 * which may be initiated by an error path of a mass storage driver.
37681ea7e0e8SSarah Sharp 	 * Therefore, use GFP_NOIO.
37691ea7e0e8SSarah Sharp 	 */
37701ea7e0e8SSarah Sharp 	sel_values = kmalloc(sizeof *(sel_values), GFP_NOIO);
37711ea7e0e8SSarah Sharp 	if (!sel_values)
37721ea7e0e8SSarah Sharp 		return -ENOMEM;
37731ea7e0e8SSarah Sharp 
37741ea7e0e8SSarah Sharp 	sel_values->u1_sel = u1_sel;
37751ea7e0e8SSarah Sharp 	sel_values->u1_pel = u1_pel;
37761ea7e0e8SSarah Sharp 	sel_values->u2_sel = cpu_to_le16(u2_sel);
37771ea7e0e8SSarah Sharp 	sel_values->u2_pel = cpu_to_le16(u2_pel);
37781ea7e0e8SSarah Sharp 
37791ea7e0e8SSarah Sharp 	ret = usb_control_msg(udev, usb_sndctrlpipe(udev, 0),
37801ea7e0e8SSarah Sharp 			USB_REQ_SET_SEL,
37811ea7e0e8SSarah Sharp 			USB_RECIP_DEVICE,
37821ea7e0e8SSarah Sharp 			0, 0,
37831ea7e0e8SSarah Sharp 			sel_values, sizeof *(sel_values),
37841ea7e0e8SSarah Sharp 			USB_CTRL_SET_TIMEOUT);
37851ea7e0e8SSarah Sharp 	kfree(sel_values);
37861ea7e0e8SSarah Sharp 	return ret;
37871ea7e0e8SSarah Sharp }
37881ea7e0e8SSarah Sharp 
37891ea7e0e8SSarah Sharp /*
37901ea7e0e8SSarah Sharp  * Enable or disable device-initiated U1 or U2 transitions.
37911ea7e0e8SSarah Sharp  */
37921ea7e0e8SSarah Sharp static int usb_set_device_initiated_lpm(struct usb_device *udev,
37931ea7e0e8SSarah Sharp 		enum usb3_link_state state, bool enable)
37941ea7e0e8SSarah Sharp {
37951ea7e0e8SSarah Sharp 	int ret;
37961ea7e0e8SSarah Sharp 	int feature;
37971ea7e0e8SSarah Sharp 
37981ea7e0e8SSarah Sharp 	switch (state) {
37991ea7e0e8SSarah Sharp 	case USB3_LPM_U1:
38001ea7e0e8SSarah Sharp 		feature = USB_DEVICE_U1_ENABLE;
38011ea7e0e8SSarah Sharp 		break;
38021ea7e0e8SSarah Sharp 	case USB3_LPM_U2:
38031ea7e0e8SSarah Sharp 		feature = USB_DEVICE_U2_ENABLE;
38041ea7e0e8SSarah Sharp 		break;
38051ea7e0e8SSarah Sharp 	default:
38061ea7e0e8SSarah Sharp 		dev_warn(&udev->dev, "%s: Can't %s non-U1 or U2 state.\n",
38071ea7e0e8SSarah Sharp 				__func__, enable ? "enable" : "disable");
38081ea7e0e8SSarah Sharp 		return -EINVAL;
38091ea7e0e8SSarah Sharp 	}
38101ea7e0e8SSarah Sharp 
38111ea7e0e8SSarah Sharp 	if (udev->state != USB_STATE_CONFIGURED) {
38121ea7e0e8SSarah Sharp 		dev_dbg(&udev->dev, "%s: Can't %s %s state "
38131ea7e0e8SSarah Sharp 				"for unconfigured device.\n",
38141ea7e0e8SSarah Sharp 				__func__, enable ? "enable" : "disable",
38151ea7e0e8SSarah Sharp 				usb3_lpm_names[state]);
38161ea7e0e8SSarah Sharp 		return 0;
38171ea7e0e8SSarah Sharp 	}
38181ea7e0e8SSarah Sharp 
38191ea7e0e8SSarah Sharp 	if (enable) {
38201ea7e0e8SSarah Sharp 		/*
38211ea7e0e8SSarah Sharp 		 * Now send the control transfer to enable device-initiated LPM
38221ea7e0e8SSarah Sharp 		 * for either U1 or U2.
38231ea7e0e8SSarah Sharp 		 */
38241ea7e0e8SSarah Sharp 		ret = usb_control_msg(udev, usb_sndctrlpipe(udev, 0),
38251ea7e0e8SSarah Sharp 				USB_REQ_SET_FEATURE,
38261ea7e0e8SSarah Sharp 				USB_RECIP_DEVICE,
38271ea7e0e8SSarah Sharp 				feature,
38281ea7e0e8SSarah Sharp 				0, NULL, 0,
38291ea7e0e8SSarah Sharp 				USB_CTRL_SET_TIMEOUT);
38301ea7e0e8SSarah Sharp 	} else {
38311ea7e0e8SSarah Sharp 		ret = usb_control_msg(udev, usb_sndctrlpipe(udev, 0),
38321ea7e0e8SSarah Sharp 				USB_REQ_CLEAR_FEATURE,
38331ea7e0e8SSarah Sharp 				USB_RECIP_DEVICE,
38341ea7e0e8SSarah Sharp 				feature,
38351ea7e0e8SSarah Sharp 				0, NULL, 0,
38361ea7e0e8SSarah Sharp 				USB_CTRL_SET_TIMEOUT);
38371ea7e0e8SSarah Sharp 	}
38381ea7e0e8SSarah Sharp 	if (ret < 0) {
38391ea7e0e8SSarah Sharp 		dev_warn(&udev->dev, "%s of device-initiated %s failed.\n",
38401ea7e0e8SSarah Sharp 				enable ? "Enable" : "Disable",
38411ea7e0e8SSarah Sharp 				usb3_lpm_names[state]);
38421ea7e0e8SSarah Sharp 		return -EBUSY;
38431ea7e0e8SSarah Sharp 	}
38441ea7e0e8SSarah Sharp 	return 0;
38451ea7e0e8SSarah Sharp }
38461ea7e0e8SSarah Sharp 
38471ea7e0e8SSarah Sharp static int usb_set_lpm_timeout(struct usb_device *udev,
38481ea7e0e8SSarah Sharp 		enum usb3_link_state state, int timeout)
38491ea7e0e8SSarah Sharp {
38501ea7e0e8SSarah Sharp 	int ret;
38511ea7e0e8SSarah Sharp 	int feature;
38521ea7e0e8SSarah Sharp 
38531ea7e0e8SSarah Sharp 	switch (state) {
38541ea7e0e8SSarah Sharp 	case USB3_LPM_U1:
38551ea7e0e8SSarah Sharp 		feature = USB_PORT_FEAT_U1_TIMEOUT;
38561ea7e0e8SSarah Sharp 		break;
38571ea7e0e8SSarah Sharp 	case USB3_LPM_U2:
38581ea7e0e8SSarah Sharp 		feature = USB_PORT_FEAT_U2_TIMEOUT;
38591ea7e0e8SSarah Sharp 		break;
38601ea7e0e8SSarah Sharp 	default:
38611ea7e0e8SSarah Sharp 		dev_warn(&udev->dev, "%s: Can't set timeout for non-U1 or U2 state.\n",
38621ea7e0e8SSarah Sharp 				__func__);
38631ea7e0e8SSarah Sharp 		return -EINVAL;
38641ea7e0e8SSarah Sharp 	}
38651ea7e0e8SSarah Sharp 
38661ea7e0e8SSarah Sharp 	if (state == USB3_LPM_U1 && timeout > USB3_LPM_U1_MAX_TIMEOUT &&
38671ea7e0e8SSarah Sharp 			timeout != USB3_LPM_DEVICE_INITIATED) {
38681ea7e0e8SSarah Sharp 		dev_warn(&udev->dev, "Failed to set %s timeout to 0x%x, "
38691ea7e0e8SSarah Sharp 				"which is a reserved value.\n",
38701ea7e0e8SSarah Sharp 				usb3_lpm_names[state], timeout);
38711ea7e0e8SSarah Sharp 		return -EINVAL;
38721ea7e0e8SSarah Sharp 	}
38731ea7e0e8SSarah Sharp 
38741ea7e0e8SSarah Sharp 	ret = set_port_feature(udev->parent,
38751ea7e0e8SSarah Sharp 			USB_PORT_LPM_TIMEOUT(timeout) | udev->portnum,
38761ea7e0e8SSarah Sharp 			feature);
38771ea7e0e8SSarah Sharp 	if (ret < 0) {
38781ea7e0e8SSarah Sharp 		dev_warn(&udev->dev, "Failed to set %s timeout to 0x%x,"
38791ea7e0e8SSarah Sharp 				"error code %i\n", usb3_lpm_names[state],
38801ea7e0e8SSarah Sharp 				timeout, ret);
38811ea7e0e8SSarah Sharp 		return -EBUSY;
38821ea7e0e8SSarah Sharp 	}
38831ea7e0e8SSarah Sharp 	if (state == USB3_LPM_U1)
38841ea7e0e8SSarah Sharp 		udev->u1_params.timeout = timeout;
38851ea7e0e8SSarah Sharp 	else
38861ea7e0e8SSarah Sharp 		udev->u2_params.timeout = timeout;
38871ea7e0e8SSarah Sharp 	return 0;
38881ea7e0e8SSarah Sharp }
38891ea7e0e8SSarah Sharp 
38901ea7e0e8SSarah Sharp /*
38911ea7e0e8SSarah Sharp  * Enable the hub-initiated U1/U2 idle timeouts, and enable device-initiated
38921ea7e0e8SSarah Sharp  * U1/U2 entry.
38931ea7e0e8SSarah Sharp  *
38941ea7e0e8SSarah Sharp  * We will attempt to enable U1 or U2, but there are no guarantees that the
38951ea7e0e8SSarah Sharp  * control transfers to set the hub timeout or enable device-initiated U1/U2
38961ea7e0e8SSarah Sharp  * will be successful.
38971ea7e0e8SSarah Sharp  *
38981ea7e0e8SSarah Sharp  * If we cannot set the parent hub U1/U2 timeout, we attempt to let the xHCI
38991ea7e0e8SSarah Sharp  * driver know about it.  If that call fails, it should be harmless, and just
39001ea7e0e8SSarah Sharp  * take up more slightly more bus bandwidth for unnecessary U1/U2 exit latency.
39011ea7e0e8SSarah Sharp  */
39021ea7e0e8SSarah Sharp static void usb_enable_link_state(struct usb_hcd *hcd, struct usb_device *udev,
39031ea7e0e8SSarah Sharp 		enum usb3_link_state state)
39041ea7e0e8SSarah Sharp {
390565a95b75SSarah Sharp 	int timeout, ret;
3906ae8963adSSarah Sharp 	__u8 u1_mel = udev->bos->ss_cap->bU1devExitLat;
3907ae8963adSSarah Sharp 	__le16 u2_mel = udev->bos->ss_cap->bU2DevExitLat;
3908ae8963adSSarah Sharp 
3909ae8963adSSarah Sharp 	/* If the device says it doesn't have *any* exit latency to come out of
3910ae8963adSSarah Sharp 	 * U1 or U2, it's probably lying.  Assume it doesn't implement that link
3911ae8963adSSarah Sharp 	 * state.
3912ae8963adSSarah Sharp 	 */
3913ae8963adSSarah Sharp 	if ((state == USB3_LPM_U1 && u1_mel == 0) ||
3914ae8963adSSarah Sharp 			(state == USB3_LPM_U2 && u2_mel == 0))
3915ae8963adSSarah Sharp 		return;
39161ea7e0e8SSarah Sharp 
391765a95b75SSarah Sharp 	/*
391865a95b75SSarah Sharp 	 * First, let the device know about the exit latencies
391965a95b75SSarah Sharp 	 * associated with the link state we're about to enable.
392065a95b75SSarah Sharp 	 */
392165a95b75SSarah Sharp 	ret = usb_req_set_sel(udev, state);
392265a95b75SSarah Sharp 	if (ret < 0) {
392365a95b75SSarah Sharp 		dev_warn(&udev->dev, "Set SEL for device-initiated %s failed.\n",
392465a95b75SSarah Sharp 				usb3_lpm_names[state]);
392565a95b75SSarah Sharp 		return;
392665a95b75SSarah Sharp 	}
392765a95b75SSarah Sharp 
39281ea7e0e8SSarah Sharp 	/* We allow the host controller to set the U1/U2 timeout internally
39291ea7e0e8SSarah Sharp 	 * first, so that it can change its schedule to account for the
39301ea7e0e8SSarah Sharp 	 * additional latency to send data to a device in a lower power
39311ea7e0e8SSarah Sharp 	 * link state.
39321ea7e0e8SSarah Sharp 	 */
39331ea7e0e8SSarah Sharp 	timeout = hcd->driver->enable_usb3_lpm_timeout(hcd, udev, state);
39341ea7e0e8SSarah Sharp 
39351ea7e0e8SSarah Sharp 	/* xHCI host controller doesn't want to enable this LPM state. */
39361ea7e0e8SSarah Sharp 	if (timeout == 0)
39371ea7e0e8SSarah Sharp 		return;
39381ea7e0e8SSarah Sharp 
39391ea7e0e8SSarah Sharp 	if (timeout < 0) {
39401ea7e0e8SSarah Sharp 		dev_warn(&udev->dev, "Could not enable %s link state, "
39411ea7e0e8SSarah Sharp 				"xHCI error %i.\n", usb3_lpm_names[state],
39421ea7e0e8SSarah Sharp 				timeout);
39431ea7e0e8SSarah Sharp 		return;
39441ea7e0e8SSarah Sharp 	}
39451ea7e0e8SSarah Sharp 
3946bf5ce5bfSLu Baolu 	if (usb_set_lpm_timeout(udev, state, timeout)) {
39471ea7e0e8SSarah Sharp 		/* If we can't set the parent hub U1/U2 timeout,
39481ea7e0e8SSarah Sharp 		 * device-initiated LPM won't be allowed either, so let the xHCI
39491ea7e0e8SSarah Sharp 		 * host know that this link state won't be enabled.
39501ea7e0e8SSarah Sharp 		 */
39511ea7e0e8SSarah Sharp 		hcd->driver->disable_usb3_lpm_timeout(hcd, udev, state);
3952bf5ce5bfSLu Baolu 	} else {
3953bf5ce5bfSLu Baolu 		/* Only a configured device will accept the Set Feature
3954bf5ce5bfSLu Baolu 		 * U1/U2_ENABLE
3955bf5ce5bfSLu Baolu 		 */
3956bf5ce5bfSLu Baolu 		if (udev->actconfig)
39571ea7e0e8SSarah Sharp 			usb_set_device_initiated_lpm(udev, state, true);
39581ea7e0e8SSarah Sharp 
3959bf5ce5bfSLu Baolu 		/* As soon as usb_set_lpm_timeout(timeout) returns 0, the
3960bf5ce5bfSLu Baolu 		 * hub-initiated LPM is enabled. Thus, LPM is enabled no
3961bf5ce5bfSLu Baolu 		 * matter the result of usb_set_device_initiated_lpm().
3962bf5ce5bfSLu Baolu 		 * The only difference is whether device is able to initiate
3963bf5ce5bfSLu Baolu 		 * LPM.
3964bf5ce5bfSLu Baolu 		 */
3965bf5ce5bfSLu Baolu 		if (state == USB3_LPM_U1)
3966bf5ce5bfSLu Baolu 			udev->usb3_lpm_u1_enabled = 1;
3967bf5ce5bfSLu Baolu 		else if (state == USB3_LPM_U2)
3968bf5ce5bfSLu Baolu 			udev->usb3_lpm_u2_enabled = 1;
3969bf5ce5bfSLu Baolu 	}
39701ea7e0e8SSarah Sharp }
39711ea7e0e8SSarah Sharp 
39721ea7e0e8SSarah Sharp /*
39731ea7e0e8SSarah Sharp  * Disable the hub-initiated U1/U2 idle timeouts, and disable device-initiated
39741ea7e0e8SSarah Sharp  * U1/U2 entry.
39751ea7e0e8SSarah Sharp  *
39761ea7e0e8SSarah Sharp  * If this function returns -EBUSY, the parent hub will still allow U1/U2 entry.
39771ea7e0e8SSarah Sharp  * If zero is returned, the parent will not allow the link to go into U1/U2.
39781ea7e0e8SSarah Sharp  *
39791ea7e0e8SSarah Sharp  * If zero is returned, device-initiated U1/U2 entry may still be enabled, but
39801ea7e0e8SSarah Sharp  * it won't have an effect on the bus link state because the parent hub will
39811ea7e0e8SSarah Sharp  * still disallow device-initiated U1/U2 entry.
39821ea7e0e8SSarah Sharp  *
39831ea7e0e8SSarah Sharp  * If zero is returned, the xHCI host controller may still think U1/U2 entry is
39841ea7e0e8SSarah Sharp  * possible.  The result will be slightly more bus bandwidth will be taken up
39851ea7e0e8SSarah Sharp  * (to account for U1/U2 exit latency), but it should be harmless.
39861ea7e0e8SSarah Sharp  */
39871ea7e0e8SSarah Sharp static int usb_disable_link_state(struct usb_hcd *hcd, struct usb_device *udev,
39881ea7e0e8SSarah Sharp 		enum usb3_link_state state)
39891ea7e0e8SSarah Sharp {
39901ea7e0e8SSarah Sharp 	switch (state) {
39911ea7e0e8SSarah Sharp 	case USB3_LPM_U1:
39921ea7e0e8SSarah Sharp 	case USB3_LPM_U2:
39931ea7e0e8SSarah Sharp 		break;
39941ea7e0e8SSarah Sharp 	default:
39951ea7e0e8SSarah Sharp 		dev_warn(&udev->dev, "%s: Can't disable non-U1 or U2 state.\n",
39961ea7e0e8SSarah Sharp 				__func__);
39971ea7e0e8SSarah Sharp 		return -EINVAL;
39981ea7e0e8SSarah Sharp 	}
39991ea7e0e8SSarah Sharp 
40001ea7e0e8SSarah Sharp 	if (usb_set_lpm_timeout(udev, state, 0))
40011ea7e0e8SSarah Sharp 		return -EBUSY;
40021ea7e0e8SSarah Sharp 
40031ea7e0e8SSarah Sharp 	usb_set_device_initiated_lpm(udev, state, false);
40041ea7e0e8SSarah Sharp 
40051ea7e0e8SSarah Sharp 	if (hcd->driver->disable_usb3_lpm_timeout(hcd, udev, state))
40061ea7e0e8SSarah Sharp 		dev_warn(&udev->dev, "Could not disable xHCI %s timeout, "
40071ea7e0e8SSarah Sharp 				"bus schedule bandwidth may be impacted.\n",
40081ea7e0e8SSarah Sharp 				usb3_lpm_names[state]);
4009bf5ce5bfSLu Baolu 
4010bf5ce5bfSLu Baolu 	/* As soon as usb_set_lpm_timeout(0) return 0, hub initiated LPM
4011bf5ce5bfSLu Baolu 	 * is disabled. Hub will disallows link to enter U1/U2 as well,
4012bf5ce5bfSLu Baolu 	 * even device is initiating LPM. Hence LPM is disabled if hub LPM
4013bf5ce5bfSLu Baolu 	 * timeout set to 0, no matter device-initiated LPM is disabled or
4014bf5ce5bfSLu Baolu 	 * not.
4015bf5ce5bfSLu Baolu 	 */
4016bf5ce5bfSLu Baolu 	if (state == USB3_LPM_U1)
4017bf5ce5bfSLu Baolu 		udev->usb3_lpm_u1_enabled = 0;
4018bf5ce5bfSLu Baolu 	else if (state == USB3_LPM_U2)
4019bf5ce5bfSLu Baolu 		udev->usb3_lpm_u2_enabled = 0;
4020bf5ce5bfSLu Baolu 
40211ea7e0e8SSarah Sharp 	return 0;
40221ea7e0e8SSarah Sharp }
40231ea7e0e8SSarah Sharp 
40241ea7e0e8SSarah Sharp /*
40251ea7e0e8SSarah Sharp  * Disable hub-initiated and device-initiated U1 and U2 entry.
40261ea7e0e8SSarah Sharp  * Caller must own the bandwidth_mutex.
40271ea7e0e8SSarah Sharp  *
40281ea7e0e8SSarah Sharp  * This will call usb_enable_lpm() on failure, which will decrement
40291ea7e0e8SSarah Sharp  * lpm_disable_count, and will re-enable LPM if lpm_disable_count reaches zero.
40301ea7e0e8SSarah Sharp  */
40311ea7e0e8SSarah Sharp int usb_disable_lpm(struct usb_device *udev)
40321ea7e0e8SSarah Sharp {
40331ea7e0e8SSarah Sharp 	struct usb_hcd *hcd;
40341ea7e0e8SSarah Sharp 
40351ea7e0e8SSarah Sharp 	if (!udev || !udev->parent ||
40368a1b2725SMathias Nyman 			udev->speed < USB_SPEED_SUPER ||
403751df62ffSPratyush Anand 			!udev->lpm_capable ||
403851df62ffSPratyush Anand 			udev->state < USB_STATE_DEFAULT)
40391ea7e0e8SSarah Sharp 		return 0;
40401ea7e0e8SSarah Sharp 
40411ea7e0e8SSarah Sharp 	hcd = bus_to_hcd(udev->bus);
40421ea7e0e8SSarah Sharp 	if (!hcd || !hcd->driver->disable_usb3_lpm_timeout)
40431ea7e0e8SSarah Sharp 		return 0;
40441ea7e0e8SSarah Sharp 
40451ea7e0e8SSarah Sharp 	udev->lpm_disable_count++;
404655558c33SDan Carpenter 	if ((udev->u1_params.timeout == 0 && udev->u2_params.timeout == 0))
40471ea7e0e8SSarah Sharp 		return 0;
40481ea7e0e8SSarah Sharp 
40491ea7e0e8SSarah Sharp 	/* If LPM is enabled, attempt to disable it. */
40501ea7e0e8SSarah Sharp 	if (usb_disable_link_state(hcd, udev, USB3_LPM_U1))
40511ea7e0e8SSarah Sharp 		goto enable_lpm;
40521ea7e0e8SSarah Sharp 	if (usb_disable_link_state(hcd, udev, USB3_LPM_U2))
40531ea7e0e8SSarah Sharp 		goto enable_lpm;
40541ea7e0e8SSarah Sharp 
40551ea7e0e8SSarah Sharp 	return 0;
40561ea7e0e8SSarah Sharp 
40571ea7e0e8SSarah Sharp enable_lpm:
40581ea7e0e8SSarah Sharp 	usb_enable_lpm(udev);
40591ea7e0e8SSarah Sharp 	return -EBUSY;
40601ea7e0e8SSarah Sharp }
40611ea7e0e8SSarah Sharp EXPORT_SYMBOL_GPL(usb_disable_lpm);
40621ea7e0e8SSarah Sharp 
40631ea7e0e8SSarah Sharp /* Grab the bandwidth_mutex before calling usb_disable_lpm() */
40641ea7e0e8SSarah Sharp int usb_unlocked_disable_lpm(struct usb_device *udev)
40651ea7e0e8SSarah Sharp {
40661ea7e0e8SSarah Sharp 	struct usb_hcd *hcd = bus_to_hcd(udev->bus);
40671ea7e0e8SSarah Sharp 	int ret;
40681ea7e0e8SSarah Sharp 
40691ea7e0e8SSarah Sharp 	if (!hcd)
40701ea7e0e8SSarah Sharp 		return -EINVAL;
40711ea7e0e8SSarah Sharp 
40721ea7e0e8SSarah Sharp 	mutex_lock(hcd->bandwidth_mutex);
40731ea7e0e8SSarah Sharp 	ret = usb_disable_lpm(udev);
40741ea7e0e8SSarah Sharp 	mutex_unlock(hcd->bandwidth_mutex);
40751ea7e0e8SSarah Sharp 
40761ea7e0e8SSarah Sharp 	return ret;
40771ea7e0e8SSarah Sharp }
40781ea7e0e8SSarah Sharp EXPORT_SYMBOL_GPL(usb_unlocked_disable_lpm);
40791ea7e0e8SSarah Sharp 
40801ea7e0e8SSarah Sharp /*
40811ea7e0e8SSarah Sharp  * Attempt to enable device-initiated and hub-initiated U1 and U2 entry.  The
40821ea7e0e8SSarah Sharp  * xHCI host policy may prevent U1 or U2 from being enabled.
40831ea7e0e8SSarah Sharp  *
40841ea7e0e8SSarah Sharp  * Other callers may have disabled link PM, so U1 and U2 entry will be disabled
40851ea7e0e8SSarah Sharp  * until the lpm_disable_count drops to zero.  Caller must own the
40861ea7e0e8SSarah Sharp  * bandwidth_mutex.
40871ea7e0e8SSarah Sharp  */
40881ea7e0e8SSarah Sharp void usb_enable_lpm(struct usb_device *udev)
40891ea7e0e8SSarah Sharp {
40901ea7e0e8SSarah Sharp 	struct usb_hcd *hcd;
4091513072d9SLu Baolu 	struct usb_hub *hub;
4092513072d9SLu Baolu 	struct usb_port *port_dev;
40931ea7e0e8SSarah Sharp 
40941ea7e0e8SSarah Sharp 	if (!udev || !udev->parent ||
40958a1b2725SMathias Nyman 			udev->speed < USB_SPEED_SUPER ||
409651df62ffSPratyush Anand 			!udev->lpm_capable ||
409751df62ffSPratyush Anand 			udev->state < USB_STATE_DEFAULT)
40981ea7e0e8SSarah Sharp 		return;
40991ea7e0e8SSarah Sharp 
41001ea7e0e8SSarah Sharp 	udev->lpm_disable_count--;
41011ea7e0e8SSarah Sharp 	hcd = bus_to_hcd(udev->bus);
41021ea7e0e8SSarah Sharp 	/* Double check that we can both enable and disable LPM.
41031ea7e0e8SSarah Sharp 	 * Device must be configured to accept set feature U1/U2 timeout.
41041ea7e0e8SSarah Sharp 	 */
41051ea7e0e8SSarah Sharp 	if (!hcd || !hcd->driver->enable_usb3_lpm_timeout ||
41061ea7e0e8SSarah Sharp 			!hcd->driver->disable_usb3_lpm_timeout)
41071ea7e0e8SSarah Sharp 		return;
41081ea7e0e8SSarah Sharp 
41091ea7e0e8SSarah Sharp 	if (udev->lpm_disable_count > 0)
41101ea7e0e8SSarah Sharp 		return;
41111ea7e0e8SSarah Sharp 
4112513072d9SLu Baolu 	hub = usb_hub_to_struct_hub(udev->parent);
4113513072d9SLu Baolu 	if (!hub)
4114513072d9SLu Baolu 		return;
4115513072d9SLu Baolu 
4116513072d9SLu Baolu 	port_dev = hub->ports[udev->portnum - 1];
4117513072d9SLu Baolu 
4118513072d9SLu Baolu 	if (port_dev->usb3_lpm_u1_permit)
41191ea7e0e8SSarah Sharp 		usb_enable_link_state(hcd, udev, USB3_LPM_U1);
4120513072d9SLu Baolu 
4121513072d9SLu Baolu 	if (port_dev->usb3_lpm_u2_permit)
41221ea7e0e8SSarah Sharp 		usb_enable_link_state(hcd, udev, USB3_LPM_U2);
41231ea7e0e8SSarah Sharp }
41241ea7e0e8SSarah Sharp EXPORT_SYMBOL_GPL(usb_enable_lpm);
41251ea7e0e8SSarah Sharp 
41261ea7e0e8SSarah Sharp /* Grab the bandwidth_mutex before calling usb_enable_lpm() */
41271ea7e0e8SSarah Sharp void usb_unlocked_enable_lpm(struct usb_device *udev)
41281ea7e0e8SSarah Sharp {
41291ea7e0e8SSarah Sharp 	struct usb_hcd *hcd = bus_to_hcd(udev->bus);
41301ea7e0e8SSarah Sharp 
41311ea7e0e8SSarah Sharp 	if (!hcd)
41321ea7e0e8SSarah Sharp 		return;
41331ea7e0e8SSarah Sharp 
41341ea7e0e8SSarah Sharp 	mutex_lock(hcd->bandwidth_mutex);
41351ea7e0e8SSarah Sharp 	usb_enable_lpm(udev);
41361ea7e0e8SSarah Sharp 	mutex_unlock(hcd->bandwidth_mutex);
41371ea7e0e8SSarah Sharp }
41381ea7e0e8SSarah Sharp EXPORT_SYMBOL_GPL(usb_unlocked_enable_lpm);
41391ea7e0e8SSarah Sharp 
414037be6676SMathias Nyman /* usb3 devices use U3 for disabled, make sure remote wakeup is disabled */
414137be6676SMathias Nyman static void hub_usb3_port_prepare_disable(struct usb_hub *hub,
414237be6676SMathias Nyman 					  struct usb_port *port_dev)
414337be6676SMathias Nyman {
414437be6676SMathias Nyman 	struct usb_device *udev = port_dev->child;
414537be6676SMathias Nyman 	int ret;
414637be6676SMathias Nyman 
414737be6676SMathias Nyman 	if (udev && udev->port_is_suspended && udev->do_remote_wakeup) {
414837be6676SMathias Nyman 		ret = hub_set_port_link_state(hub, port_dev->portnum,
414937be6676SMathias Nyman 					      USB_SS_PORT_LS_U0);
415037be6676SMathias Nyman 		if (!ret) {
415137be6676SMathias Nyman 			msleep(USB_RESUME_TIMEOUT);
415237be6676SMathias Nyman 			ret = usb_disable_remote_wakeup(udev);
415337be6676SMathias Nyman 		}
415437be6676SMathias Nyman 		if (ret)
415537be6676SMathias Nyman 			dev_warn(&udev->dev,
415637be6676SMathias Nyman 				 "Port disable: can't disable remote wake\n");
415737be6676SMathias Nyman 		udev->do_remote_wakeup = 0;
415837be6676SMathias Nyman 	}
415937be6676SMathias Nyman }
41601ea7e0e8SSarah Sharp 
4161d388dab7SAlan Stern #else	/* CONFIG_PM */
4162d388dab7SAlan Stern 
4163511366daSAndrew Morton #define hub_suspend		NULL
4164511366daSAndrew Morton #define hub_resume		NULL
4165f07600cfSAlan Stern #define hub_reset_resume	NULL
41661ea7e0e8SSarah Sharp 
416737be6676SMathias Nyman static inline void hub_usb3_port_prepare_disable(struct usb_hub *hub,
416837be6676SMathias Nyman 						 struct usb_port *port_dev) { }
416937be6676SMathias Nyman 
41701ea7e0e8SSarah Sharp int usb_disable_lpm(struct usb_device *udev)
41711ea7e0e8SSarah Sharp {
41721ea7e0e8SSarah Sharp 	return 0;
41731ea7e0e8SSarah Sharp }
4174e9261fb6SSarah Sharp EXPORT_SYMBOL_GPL(usb_disable_lpm);
41751ea7e0e8SSarah Sharp 
41761ea7e0e8SSarah Sharp void usb_enable_lpm(struct usb_device *udev) { }
4177e9261fb6SSarah Sharp EXPORT_SYMBOL_GPL(usb_enable_lpm);
41781ea7e0e8SSarah Sharp 
41791ea7e0e8SSarah Sharp int usb_unlocked_disable_lpm(struct usb_device *udev)
41801ea7e0e8SSarah Sharp {
41811ea7e0e8SSarah Sharp 	return 0;
41821ea7e0e8SSarah Sharp }
4183e9261fb6SSarah Sharp EXPORT_SYMBOL_GPL(usb_unlocked_disable_lpm);
41841ea7e0e8SSarah Sharp 
41851ea7e0e8SSarah Sharp void usb_unlocked_enable_lpm(struct usb_device *udev) { }
4186e9261fb6SSarah Sharp EXPORT_SYMBOL_GPL(usb_unlocked_enable_lpm);
4187f74631e3SSarah Sharp 
4188f74631e3SSarah Sharp int usb_disable_ltm(struct usb_device *udev)
4189f74631e3SSarah Sharp {
4190f74631e3SSarah Sharp 	return 0;
4191f74631e3SSarah Sharp }
4192f74631e3SSarah Sharp EXPORT_SYMBOL_GPL(usb_disable_ltm);
4193f74631e3SSarah Sharp 
4194f74631e3SSarah Sharp void usb_enable_ltm(struct usb_device *udev) { }
4195f74631e3SSarah Sharp EXPORT_SYMBOL_GPL(usb_enable_ltm);
4196c4b51a43SAlan Stern 
41974a95b1fcSStephen Rothwell static int hub_handle_remote_wakeup(struct usb_hub *hub, unsigned int port,
41984a95b1fcSStephen Rothwell 		u16 portstatus, u16 portchange)
41994a95b1fcSStephen Rothwell {
42004a95b1fcSStephen Rothwell 	return 0;
42014a95b1fcSStephen Rothwell }
42024a95b1fcSStephen Rothwell 
4203c4b51a43SAlan Stern #endif	/* CONFIG_PM */
4204d388dab7SAlan Stern 
42053bc02bceSGeert Uytterhoeven /*
42063bc02bceSGeert Uytterhoeven  * USB-3 does not have a similar link state as USB-2 that will avoid negotiating
42073bc02bceSGeert Uytterhoeven  * a connection with a plugged-in cable but will signal the host when the cable
42083bc02bceSGeert Uytterhoeven  * is unplugged. Disable remote wake and set link state to U3 for USB-3 devices
42093bc02bceSGeert Uytterhoeven  */
42103bc02bceSGeert Uytterhoeven static int hub_port_disable(struct usb_hub *hub, int port1, int set_state)
42113bc02bceSGeert Uytterhoeven {
42123bc02bceSGeert Uytterhoeven 	struct usb_port *port_dev = hub->ports[port1 - 1];
42133bc02bceSGeert Uytterhoeven 	struct usb_device *hdev = hub->hdev;
42143bc02bceSGeert Uytterhoeven 	int ret = 0;
42153bc02bceSGeert Uytterhoeven 
42163bc02bceSGeert Uytterhoeven 	if (!hub->error) {
42173bc02bceSGeert Uytterhoeven 		if (hub_is_superspeed(hub->hdev)) {
42183bc02bceSGeert Uytterhoeven 			hub_usb3_port_prepare_disable(hub, port_dev);
42193bc02bceSGeert Uytterhoeven 			ret = hub_set_port_link_state(hub, port_dev->portnum,
42203bc02bceSGeert Uytterhoeven 						      USB_SS_PORT_LS_U3);
42213bc02bceSGeert Uytterhoeven 		} else {
42223bc02bceSGeert Uytterhoeven 			ret = usb_clear_port_feature(hdev, port1,
42233bc02bceSGeert Uytterhoeven 					USB_PORT_FEAT_ENABLE);
42243bc02bceSGeert Uytterhoeven 		}
42253bc02bceSGeert Uytterhoeven 	}
42263bc02bceSGeert Uytterhoeven 	if (port_dev->child && set_state)
42273bc02bceSGeert Uytterhoeven 		usb_set_device_state(port_dev->child, USB_STATE_NOTATTACHED);
42283bc02bceSGeert Uytterhoeven 	if (ret && ret != -ENODEV)
42293bc02bceSGeert Uytterhoeven 		dev_err(&port_dev->dev, "cannot disable (err = %d)\n", ret);
42303bc02bceSGeert Uytterhoeven 	return ret;
42313bc02bceSGeert Uytterhoeven }
42323bc02bceSGeert Uytterhoeven 
42338dd8d2c9SDaniel Drake /*
42348dd8d2c9SDaniel Drake  * usb_port_disable - disable a usb device's upstream port
42358dd8d2c9SDaniel Drake  * @udev: device to disable
42368dd8d2c9SDaniel Drake  * Context: @udev locked, must be able to sleep.
42378dd8d2c9SDaniel Drake  *
42388dd8d2c9SDaniel Drake  * Disables a USB device that isn't in active use.
42398dd8d2c9SDaniel Drake  */
42408dd8d2c9SDaniel Drake int usb_port_disable(struct usb_device *udev)
42418dd8d2c9SDaniel Drake {
42428dd8d2c9SDaniel Drake 	struct usb_hub *hub = usb_hub_to_struct_hub(udev->parent);
42438dd8d2c9SDaniel Drake 
42448dd8d2c9SDaniel Drake 	return hub_port_disable(hub, udev->portnum, 0);
42458dd8d2c9SDaniel Drake }
42461da177e4SLinus Torvalds 
42471da177e4SLinus Torvalds /* USB 2.0 spec, 7.1.7.3 / fig 7-29:
42481da177e4SLinus Torvalds  *
42491da177e4SLinus Torvalds  * Between connect detection and reset signaling there must be a delay
42501da177e4SLinus Torvalds  * of 100ms at least for debounce and power-settling.  The corresponding
42511da177e4SLinus Torvalds  * timer shall restart whenever the downstream port detects a disconnect.
42521da177e4SLinus Torvalds  *
42531da177e4SLinus Torvalds  * Apparently there are some bluetooth and irda-dongles and a number of
42541da177e4SLinus Torvalds  * low-speed devices for which this debounce period may last over a second.
42551da177e4SLinus Torvalds  * Not covered by the spec - but easy to deal with.
42561da177e4SLinus Torvalds  *
42571da177e4SLinus Torvalds  * This implementation uses a 1500ms total debounce timeout; if the
42581da177e4SLinus Torvalds  * connection isn't stable by then it returns -ETIMEDOUT.  It checks
42591da177e4SLinus Torvalds  * every 25ms for transient disconnects.  When the port status has been
42601da177e4SLinus Torvalds  * unchanged for 100ms it returns the port status.
42611da177e4SLinus Torvalds  */
4262ad493e5eSLan Tianyu int hub_port_debounce(struct usb_hub *hub, int port1, bool must_be_connected)
42631da177e4SLinus Torvalds {
42641da177e4SLinus Torvalds 	int ret;
42651da177e4SLinus Torvalds 	u16 portchange, portstatus;
42661da177e4SLinus Torvalds 	unsigned connection = 0xffff;
4267d99f6b41SDan Williams 	int total_time, stable_time = 0;
4268d99f6b41SDan Williams 	struct usb_port *port_dev = hub->ports[port1 - 1];
42691da177e4SLinus Torvalds 
42701da177e4SLinus Torvalds 	for (total_time = 0; ; total_time += HUB_DEBOUNCE_STEP) {
42711da177e4SLinus Torvalds 		ret = hub_port_status(hub, port1, &portstatus, &portchange);
42721da177e4SLinus Torvalds 		if (ret < 0)
42731da177e4SLinus Torvalds 			return ret;
42741da177e4SLinus Torvalds 
42751da177e4SLinus Torvalds 		if (!(portchange & USB_PORT_STAT_C_CONNECTION) &&
42761da177e4SLinus Torvalds 		     (portstatus & USB_PORT_STAT_CONNECTION) == connection) {
4277ad493e5eSLan Tianyu 			if (!must_be_connected ||
4278ad493e5eSLan Tianyu 			     (connection == USB_PORT_STAT_CONNECTION))
42791da177e4SLinus Torvalds 				stable_time += HUB_DEBOUNCE_STEP;
42801da177e4SLinus Torvalds 			if (stable_time >= HUB_DEBOUNCE_STABLE)
42811da177e4SLinus Torvalds 				break;
42821da177e4SLinus Torvalds 		} else {
42831da177e4SLinus Torvalds 			stable_time = 0;
42841da177e4SLinus Torvalds 			connection = portstatus & USB_PORT_STAT_CONNECTION;
42851da177e4SLinus Torvalds 		}
42861da177e4SLinus Torvalds 
42871da177e4SLinus Torvalds 		if (portchange & USB_PORT_STAT_C_CONNECTION) {
4288ad493e5eSLan Tianyu 			usb_clear_port_feature(hub->hdev, port1,
42891da177e4SLinus Torvalds 					USB_PORT_FEAT_C_CONNECTION);
42901da177e4SLinus Torvalds 		}
42911da177e4SLinus Torvalds 
42921da177e4SLinus Torvalds 		if (total_time >= HUB_DEBOUNCE_TIMEOUT)
42931da177e4SLinus Torvalds 			break;
42941da177e4SLinus Torvalds 		msleep(HUB_DEBOUNCE_STEP);
42951da177e4SLinus Torvalds 	}
42961da177e4SLinus Torvalds 
4297d99f6b41SDan Williams 	dev_dbg(&port_dev->dev, "debounce total %dms stable %dms status 0x%x\n",
4298d99f6b41SDan Williams 			total_time, stable_time, portstatus);
42991da177e4SLinus Torvalds 
43001da177e4SLinus Torvalds 	if (stable_time < HUB_DEBOUNCE_STABLE)
43011da177e4SLinus Torvalds 		return -ETIMEDOUT;
43021da177e4SLinus Torvalds 	return portstatus;
43031da177e4SLinus Torvalds }
43041da177e4SLinus Torvalds 
4305fc721f51SInaky Perez-Gonzalez void usb_ep0_reinit(struct usb_device *udev)
43061da177e4SLinus Torvalds {
4307ddeac4e7SAlan Stern 	usb_disable_endpoint(udev, 0 + USB_DIR_IN, true);
4308ddeac4e7SAlan Stern 	usb_disable_endpoint(udev, 0 + USB_DIR_OUT, true);
43092caf7fcdSAlan Stern 	usb_enable_endpoint(udev, &udev->ep0, true);
43101da177e4SLinus Torvalds }
4311fc721f51SInaky Perez-Gonzalez EXPORT_SYMBOL_GPL(usb_ep0_reinit);
43121da177e4SLinus Torvalds 
43131da177e4SLinus Torvalds #define usb_sndaddr0pipe()	(PIPE_CONTROL << 30)
43141da177e4SLinus Torvalds #define usb_rcvaddr0pipe()	((PIPE_CONTROL << 30) | USB_DIR_IN)
43151da177e4SLinus Torvalds 
43164326ed0bSAlan Stern static int hub_set_address(struct usb_device *udev, int devnum)
43171da177e4SLinus Torvalds {
43181da177e4SLinus Torvalds 	int retval;
4319c6515272SSarah Sharp 	struct usb_hcd *hcd = bus_to_hcd(udev->bus);
43201da177e4SLinus Torvalds 
4321c6515272SSarah Sharp 	/*
4322c6515272SSarah Sharp 	 * The host controller will choose the device address,
4323c6515272SSarah Sharp 	 * instead of the core having chosen it earlier
4324c6515272SSarah Sharp 	 */
4325c6515272SSarah Sharp 	if (!hcd->driver->address_device && devnum <= 1)
43261da177e4SLinus Torvalds 		return -EINVAL;
43271da177e4SLinus Torvalds 	if (udev->state == USB_STATE_ADDRESS)
43281da177e4SLinus Torvalds 		return 0;
43291da177e4SLinus Torvalds 	if (udev->state != USB_STATE_DEFAULT)
43301da177e4SLinus Torvalds 		return -EINVAL;
4331c8d4af8eSAndiry Xu 	if (hcd->driver->address_device)
4332c6515272SSarah Sharp 		retval = hcd->driver->address_device(hcd, udev);
4333c8d4af8eSAndiry Xu 	else
43341da177e4SLinus Torvalds 		retval = usb_control_msg(udev, usb_sndaddr0pipe(),
43354326ed0bSAlan Stern 				USB_REQ_SET_ADDRESS, 0, devnum, 0,
43361da177e4SLinus Torvalds 				NULL, 0, USB_CTRL_SET_TIMEOUT);
43371da177e4SLinus Torvalds 	if (retval == 0) {
43383b29b68bSAlan Stern 		update_devnum(udev, devnum);
43394953d141SDavid Vrabel 		/* Device now using proper address. */
43401da177e4SLinus Torvalds 		usb_set_device_state(udev, USB_STATE_ADDRESS);
4341fc721f51SInaky Perez-Gonzalez 		usb_ep0_reinit(udev);
43421da177e4SLinus Torvalds 	}
43431da177e4SLinus Torvalds 	return retval;
43441da177e4SLinus Torvalds }
43451da177e4SLinus Torvalds 
4346890dae88SMathias Nyman /*
4347890dae88SMathias Nyman  * There are reports of USB 3.0 devices that say they support USB 2.0 Link PM
4348890dae88SMathias Nyman  * when they're plugged into a USB 2.0 port, but they don't work when LPM is
4349890dae88SMathias Nyman  * enabled.
4350890dae88SMathias Nyman  *
4351890dae88SMathias Nyman  * Only enable USB 2.0 Link PM if the port is internal (hardwired), or the
4352890dae88SMathias Nyman  * device says it supports the new USB 2.0 Link PM errata by setting the BESL
4353890dae88SMathias Nyman  * support bit in the BOS descriptor.
4354890dae88SMathias Nyman  */
4355890dae88SMathias Nyman static void hub_set_initial_usb2_lpm_policy(struct usb_device *udev)
4356890dae88SMathias Nyman {
4357d99f6b41SDan Williams 	struct usb_hub *hub = usb_hub_to_struct_hub(udev->parent);
4358d99f6b41SDan Williams 	int connect_type = USB_PORT_CONNECT_TYPE_UNKNOWN;
4359890dae88SMathias Nyman 
43607b2db29fSGuenter Roeck 	if (!udev->usb2_hw_lpm_capable || !udev->bos)
4361890dae88SMathias Nyman 		return;
4362890dae88SMathias Nyman 
4363d99f6b41SDan Williams 	if (hub)
4364d99f6b41SDan Williams 		connect_type = hub->ports[udev->portnum - 1]->connect_type;
4365890dae88SMathias Nyman 
436623c05820SBjørn Mork 	if ((udev->bos->ext_cap->bmAttributes & cpu_to_le32(USB_BESL_SUPPORT)) ||
4367890dae88SMathias Nyman 			connect_type == USB_PORT_CONNECT_TYPE_HARD_WIRED) {
4368890dae88SMathias Nyman 		udev->usb2_hw_lpm_allowed = 1;
4369890dae88SMathias Nyman 		usb_set_usb2_hardware_lpm(udev, 1);
4370890dae88SMathias Nyman 	}
4371890dae88SMathias Nyman }
4372890dae88SMathias Nyman 
437348fc7dbdSDan Williams static int hub_enable_device(struct usb_device *udev)
437448fc7dbdSDan Williams {
437548fc7dbdSDan Williams 	struct usb_hcd *hcd = bus_to_hcd(udev->bus);
437648fc7dbdSDan Williams 
437748fc7dbdSDan Williams 	if (!hcd->driver->enable_device)
437848fc7dbdSDan Williams 		return 0;
437948fc7dbdSDan Williams 	if (udev->state == USB_STATE_ADDRESS)
438048fc7dbdSDan Williams 		return 0;
438148fc7dbdSDan Williams 	if (udev->state != USB_STATE_DEFAULT)
438248fc7dbdSDan Williams 		return -EINVAL;
438348fc7dbdSDan Williams 
438448fc7dbdSDan Williams 	return hcd->driver->enable_device(hcd, udev);
438548fc7dbdSDan Williams }
438648fc7dbdSDan Williams 
43871da177e4SLinus Torvalds /* Reset device, (re)assign address, get device descriptor.
43881da177e4SLinus Torvalds  * Device connection must be stable, no more debouncing needed.
43891da177e4SLinus Torvalds  * Returns device in USB_STATE_ADDRESS, except on error.
43901da177e4SLinus Torvalds  *
43911da177e4SLinus Torvalds  * If this is called for an already-existing device (as part of
43925c79a1e3SDan Williams  * usb_reset_and_verify_device), the caller must own the device lock and
43935c79a1e3SDan Williams  * the port lock.  For a newly detected device that is not accessible
43945c79a1e3SDan Williams  * through any global pointers, it's not necessary to lock the device,
43955c79a1e3SDan Williams  * but it is still necessary to lock the port.
43961da177e4SLinus Torvalds  */
43971da177e4SLinus Torvalds static int
43981da177e4SLinus Torvalds hub_port_init(struct usb_hub *hub, struct usb_device *udev, int port1,
43991da177e4SLinus Torvalds 		int retry_counter)
44001da177e4SLinus Torvalds {
44011da177e4SLinus Torvalds 	struct usb_device	*hdev = hub->hdev;
4402e7b77172SSarah Sharp 	struct usb_hcd		*hcd = bus_to_hcd(hdev->bus);
440325244227SNicolas Boichat 	struct usb_port		*port_dev = hub->ports[port1 - 1];
44040d5ce778SOliver Neukum 	int			retries, operations, retval, i;
44051da177e4SLinus Torvalds 	unsigned		delay = HUB_SHORT_RESET_TIME;
44061da177e4SLinus Torvalds 	enum usb_device_speed	oldspeed = udev->speed;
4407e538dfdaSMichal Nazarewicz 	const char		*speed;
44084326ed0bSAlan Stern 	int			devnum = udev->devnum;
44091bb90cf0SPeter Chen 	const char		*driver_name;
44101da177e4SLinus Torvalds 
44111da177e4SLinus Torvalds 	/* root hub ports have a slightly longer reset period
44121da177e4SLinus Torvalds 	 * (from USB 2.0 spec, section 7.1.7.5)
44131da177e4SLinus Torvalds 	 */
44141da177e4SLinus Torvalds 	if (!hdev->parent) {
44151da177e4SLinus Torvalds 		delay = HUB_ROOT_RESET_TIME;
44161da177e4SLinus Torvalds 		if (port1 == hdev->bus->otg_port)
44171da177e4SLinus Torvalds 			hdev->bus->b_hnp_enable = 0;
44181da177e4SLinus Torvalds 	}
44191da177e4SLinus Torvalds 
44201da177e4SLinus Torvalds 	/* Some low speed devices have problems with the quick delay, so */
44211da177e4SLinus Torvalds 	/*  be a bit pessimistic with those devices. RHbug #23670 */
44221da177e4SLinus Torvalds 	if (oldspeed == USB_SPEED_LOW)
44231da177e4SLinus Torvalds 		delay = HUB_LONG_RESET_TIME;
44241da177e4SLinus Torvalds 
4425feb26ac3SChris Bainbridge 	mutex_lock(hcd->address0_mutex);
44261da177e4SLinus Torvalds 
44271da177e4SLinus Torvalds 	/* Reset the device; full speed may morph to high speed */
4428e7b77172SSarah Sharp 	/* FIXME a USB 2.0 device may morph into SuperSpeed on reset. */
442975d7cf72SAndiry Xu 	retval = hub_port_reset(hub, port1, udev, delay, false);
44301da177e4SLinus Torvalds 	if (retval < 0)		/* error or disconnect */
44311da177e4SLinus Torvalds 		goto fail;
44321da177e4SLinus Torvalds 	/* success, speed is known */
443307194ab7SLuben Tuikov 
44341da177e4SLinus Torvalds 	retval = -ENODEV;
44351da177e4SLinus Torvalds 
44368a1b2725SMathias Nyman 	/* Don't allow speed changes at reset, except usb 3.0 to faster */
44378a1b2725SMathias Nyman 	if (oldspeed != USB_SPEED_UNKNOWN && oldspeed != udev->speed &&
44388a1b2725SMathias Nyman 	    !(oldspeed == USB_SPEED_SUPER && udev->speed > oldspeed)) {
44391da177e4SLinus Torvalds 		dev_dbg(&udev->dev, "device reset changed speed!\n");
44401da177e4SLinus Torvalds 		goto fail;
44411da177e4SLinus Torvalds 	}
44421da177e4SLinus Torvalds 	oldspeed = udev->speed;
44431da177e4SLinus Torvalds 
44441da177e4SLinus Torvalds 	/* USB 2.0 section 5.5.3 talks about ep0 maxpacket ...
44451da177e4SLinus Torvalds 	 * it's fixed size except for full speed devices.
44465bb6e0aeSInaky Perez-Gonzalez 	 * For Wireless USB devices, ep0 max packet is always 512 (tho
44475bb6e0aeSInaky Perez-Gonzalez 	 * reported as 0xff in the device descriptor). WUSB1.0[4.8.1].
44481da177e4SLinus Torvalds 	 */
44491da177e4SLinus Torvalds 	switch (udev->speed) {
44508a1b2725SMathias Nyman 	case USB_SPEED_SUPER_PLUS:
44516b403b02SSarah Sharp 	case USB_SPEED_SUPER:
4452551cdbbeSGreg Kroah-Hartman 	case USB_SPEED_WIRELESS:	/* fixed at 512 */
4453551509d2SHarvey Harrison 		udev->ep0.desc.wMaxPacketSize = cpu_to_le16(512);
44545bb6e0aeSInaky Perez-Gonzalez 		break;
44551da177e4SLinus Torvalds 	case USB_SPEED_HIGH:		/* fixed at 64 */
4456551509d2SHarvey Harrison 		udev->ep0.desc.wMaxPacketSize = cpu_to_le16(64);
44571da177e4SLinus Torvalds 		break;
44581da177e4SLinus Torvalds 	case USB_SPEED_FULL:		/* 8, 16, 32, or 64 */
44591da177e4SLinus Torvalds 		/* to determine the ep0 maxpacket size, try to read
44601da177e4SLinus Torvalds 		 * the device descriptor to get bMaxPacketSize0 and
44611da177e4SLinus Torvalds 		 * then correct our initial guess.
44621da177e4SLinus Torvalds 		 */
4463551509d2SHarvey Harrison 		udev->ep0.desc.wMaxPacketSize = cpu_to_le16(64);
44641da177e4SLinus Torvalds 		break;
44651da177e4SLinus Torvalds 	case USB_SPEED_LOW:		/* fixed at 8 */
4466551509d2SHarvey Harrison 		udev->ep0.desc.wMaxPacketSize = cpu_to_le16(8);
44671da177e4SLinus Torvalds 		break;
44681da177e4SLinus Torvalds 	default:
44691da177e4SLinus Torvalds 		goto fail;
44701da177e4SLinus Torvalds 	}
44711da177e4SLinus Torvalds 
4472e538dfdaSMichal Nazarewicz 	if (udev->speed == USB_SPEED_WIRELESS)
4473e538dfdaSMichal Nazarewicz 		speed = "variable speed Wireless";
4474e538dfdaSMichal Nazarewicz 	else
4475e538dfdaSMichal Nazarewicz 		speed = usb_speed_string(udev->speed);
4476e538dfdaSMichal Nazarewicz 
44771bb90cf0SPeter Chen 	/*
44781bb90cf0SPeter Chen 	 * The controller driver may be NULL if the controller device
44791bb90cf0SPeter Chen 	 * is the middle device between platform device and roothub.
44801bb90cf0SPeter Chen 	 * This middle device may not need a device driver due to
44811bb90cf0SPeter Chen 	 * all hardware control can be at platform device driver, this
44821bb90cf0SPeter Chen 	 * platform device is usually a dual-role USB controller device.
44831bb90cf0SPeter Chen 	 */
44841bb90cf0SPeter Chen 	if (udev->bus->controller->driver)
44851bb90cf0SPeter Chen 		driver_name = udev->bus->controller->driver->name;
44861bb90cf0SPeter Chen 	else
44871bb90cf0SPeter Chen 		driver_name = udev->bus->sysdev->driver->name;
44881bb90cf0SPeter Chen 
44898a1b2725SMathias Nyman 	if (udev->speed < USB_SPEED_SUPER)
449083a07196SInaky Perez-Gonzalez 		dev_info(&udev->dev,
4491e538dfdaSMichal Nazarewicz 				"%s %s USB device number %d using %s\n",
4492e538dfdaSMichal Nazarewicz 				(udev->config) ? "reset" : "new", speed,
44931bb90cf0SPeter Chen 				devnum, driver_name);
44941da177e4SLinus Torvalds 
44951da177e4SLinus Torvalds 	/* Set up TT records, if needed  */
44961da177e4SLinus Torvalds 	if (hdev->tt) {
44971da177e4SLinus Torvalds 		udev->tt = hdev->tt;
44981da177e4SLinus Torvalds 		udev->ttport = hdev->ttport;
44991da177e4SLinus Torvalds 	} else if (udev->speed != USB_SPEED_HIGH
45001da177e4SLinus Torvalds 			&& hdev->speed == USB_SPEED_HIGH) {
4501d199c96dSAlan Stern 		if (!hub->tt.hub) {
4502d199c96dSAlan Stern 			dev_err(&udev->dev, "parent hub has no TT\n");
4503d199c96dSAlan Stern 			retval = -EINVAL;
4504d199c96dSAlan Stern 			goto fail;
4505d199c96dSAlan Stern 		}
45061da177e4SLinus Torvalds 		udev->tt = &hub->tt;
45071da177e4SLinus Torvalds 		udev->ttport = port1;
45081da177e4SLinus Torvalds 	}
45091da177e4SLinus Torvalds 
45101da177e4SLinus Torvalds 	/* Why interleave GET_DESCRIPTOR and SET_ADDRESS this way?
45111da177e4SLinus Torvalds 	 * Because device hardware and firmware is sometimes buggy in
45121da177e4SLinus Torvalds 	 * this area, and this is how Linux has done it for ages.
45131da177e4SLinus Torvalds 	 * Change it cautiously.
45141da177e4SLinus Torvalds 	 *
451548fc7dbdSDan Williams 	 * NOTE:  If use_new_scheme() is true we will start by issuing
45161da177e4SLinus Torvalds 	 * a 64-byte GET_DESCRIPTOR request.  This is what Windows does,
45171da177e4SLinus Torvalds 	 * so it may help with some non-standards-compliant devices.
45181da177e4SLinus Torvalds 	 * Otherwise we start with SET_ADDRESS and then try to read the
45191da177e4SLinus Torvalds 	 * first 8 bytes of the device descriptor to get the ep0 maxpacket
45201da177e4SLinus Torvalds 	 * value.
45211da177e4SLinus Torvalds 	 */
45220d5ce778SOliver Neukum 	for (retries = 0; retries < GET_DESCRIPTOR_TRIES; (++retries, msleep(100))) {
452348fc7dbdSDan Williams 		bool did_new_scheme = false;
452448fc7dbdSDan Williams 
452525244227SNicolas Boichat 		if (use_new_scheme(udev, retry_counter, port_dev)) {
45261da177e4SLinus Torvalds 			struct usb_device_descriptor *buf;
45271da177e4SLinus Torvalds 			int r = 0;
45281da177e4SLinus Torvalds 
452948fc7dbdSDan Williams 			did_new_scheme = true;
453048fc7dbdSDan Williams 			retval = hub_enable_device(udev);
4531938569ebSOliver Neukum 			if (retval < 0) {
4532938569ebSOliver Neukum 				dev_err(&udev->dev,
4533938569ebSOliver Neukum 					"hub failed to enable device, error %d\n",
4534938569ebSOliver Neukum 					retval);
453548fc7dbdSDan Williams 				goto fail;
4536938569ebSOliver Neukum 			}
453748fc7dbdSDan Williams 
45381da177e4SLinus Torvalds #define GET_DESCRIPTOR_BUFSIZE	64
45391da177e4SLinus Torvalds 			buf = kmalloc(GET_DESCRIPTOR_BUFSIZE, GFP_NOIO);
45401da177e4SLinus Torvalds 			if (!buf) {
45411da177e4SLinus Torvalds 				retval = -ENOMEM;
45421da177e4SLinus Torvalds 				continue;
45431da177e4SLinus Torvalds 			}
45441da177e4SLinus Torvalds 
4545b89ee19aSAlan Stern 			/* Retry on all errors; some devices are flakey.
4546b89ee19aSAlan Stern 			 * 255 is for WUSB devices, we actually need to use
4547b89ee19aSAlan Stern 			 * 512 (WUSB1.0[4.8.1]).
45481da177e4SLinus Torvalds 			 */
45490d5ce778SOliver Neukum 			for (operations = 0; operations < 3; ++operations) {
45501da177e4SLinus Torvalds 				buf->bMaxPacketSize0 = 0;
45511da177e4SLinus Torvalds 				r = usb_control_msg(udev, usb_rcvaddr0pipe(),
45521da177e4SLinus Torvalds 					USB_REQ_GET_DESCRIPTOR, USB_DIR_IN,
45531da177e4SLinus Torvalds 					USB_DT_DEVICE << 8, 0,
45541da177e4SLinus Torvalds 					buf, GET_DESCRIPTOR_BUFSIZE,
4555fd7c519dSJaroslav Kysela 					initial_descriptor_timeout);
45561da177e4SLinus Torvalds 				switch (buf->bMaxPacketSize0) {
45575bb6e0aeSInaky Perez-Gonzalez 				case 8: case 16: case 32: case 64: case 255:
45581da177e4SLinus Torvalds 					if (buf->bDescriptorType ==
45591da177e4SLinus Torvalds 							USB_DT_DEVICE) {
45601da177e4SLinus Torvalds 						r = 0;
45611da177e4SLinus Torvalds 						break;
45621da177e4SLinus Torvalds 					}
45631da177e4SLinus Torvalds 					/* FALL THROUGH */
45641da177e4SLinus Torvalds 				default:
45651da177e4SLinus Torvalds 					if (r == 0)
45661da177e4SLinus Torvalds 						r = -EPROTO;
45671da177e4SLinus Torvalds 					break;
45681da177e4SLinus Torvalds 				}
4569264904ccSOliver Neukum 				/*
4570264904ccSOliver Neukum 				 * Some devices time out if they are powered on
4571264904ccSOliver Neukum 				 * when already connected. They need a second
4572264904ccSOliver Neukum 				 * reset. But only on the first attempt,
4573264904ccSOliver Neukum 				 * lest we get into a time out/reset loop
4574264904ccSOliver Neukum 				 */
45756e01827eSMaxim Moseychuk 				if (r == 0 || (r == -ETIMEDOUT &&
45766e01827eSMaxim Moseychuk 						retries == 0 &&
45776e01827eSMaxim Moseychuk 						udev->speed > USB_SPEED_FULL))
45781da177e4SLinus Torvalds 					break;
45791da177e4SLinus Torvalds 			}
45801da177e4SLinus Torvalds 			udev->descriptor.bMaxPacketSize0 =
45811da177e4SLinus Torvalds 					buf->bMaxPacketSize0;
45821da177e4SLinus Torvalds 			kfree(buf);
45831da177e4SLinus Torvalds 
458475d7cf72SAndiry Xu 			retval = hub_port_reset(hub, port1, udev, delay, false);
45851da177e4SLinus Torvalds 			if (retval < 0)		/* error or disconnect */
45861da177e4SLinus Torvalds 				goto fail;
45871da177e4SLinus Torvalds 			if (oldspeed != udev->speed) {
45881da177e4SLinus Torvalds 				dev_dbg(&udev->dev,
45891da177e4SLinus Torvalds 					"device reset changed speed!\n");
45901da177e4SLinus Torvalds 				retval = -ENODEV;
45911da177e4SLinus Torvalds 				goto fail;
45921da177e4SLinus Torvalds 			}
45931da177e4SLinus Torvalds 			if (r) {
4594e9e88fb7SAlan Stern 				if (r != -ENODEV)
4595e9e88fb7SAlan Stern 					dev_err(&udev->dev, "device descriptor read/64, error %d\n",
4596b9cef6c3SWu Fengguang 							r);
45971da177e4SLinus Torvalds 				retval = -EMSGSIZE;
45981da177e4SLinus Torvalds 				continue;
45991da177e4SLinus Torvalds 			}
46001da177e4SLinus Torvalds #undef GET_DESCRIPTOR_BUFSIZE
46011da177e4SLinus Torvalds 		}
46021da177e4SLinus Torvalds 
46036c529cdcSInaky Perez-Gonzalez 		/*
46046c529cdcSInaky Perez-Gonzalez 		 * If device is WUSB, we already assigned an
46056c529cdcSInaky Perez-Gonzalez 		 * unauthorized address in the Connect Ack sequence;
46066c529cdcSInaky Perez-Gonzalez 		 * authorization will assign the final address.
46076c529cdcSInaky Perez-Gonzalez 		 */
46086c529cdcSInaky Perez-Gonzalez 		if (udev->wusb == 0) {
46090d5ce778SOliver Neukum 			for (operations = 0; operations < SET_ADDRESS_TRIES; ++operations) {
46104326ed0bSAlan Stern 				retval = hub_set_address(udev, devnum);
46111da177e4SLinus Torvalds 				if (retval >= 0)
46121da177e4SLinus Torvalds 					break;
46131da177e4SLinus Torvalds 				msleep(200);
46141da177e4SLinus Torvalds 			}
46151da177e4SLinus Torvalds 			if (retval < 0) {
4616e9e88fb7SAlan Stern 				if (retval != -ENODEV)
4617e9e88fb7SAlan Stern 					dev_err(&udev->dev, "device not accepting address %d, error %d\n",
46184326ed0bSAlan Stern 							devnum, retval);
46191da177e4SLinus Torvalds 				goto fail;
46201da177e4SLinus Torvalds 			}
46218a1b2725SMathias Nyman 			if (udev->speed >= USB_SPEED_SUPER) {
4622c6515272SSarah Sharp 				devnum = udev->devnum;
4623c6515272SSarah Sharp 				dev_info(&udev->dev,
462445455e4dSMathias Nyman 						"%s SuperSpeed%s%s USB device number %d using %s\n",
4625c6515272SSarah Sharp 						(udev->config) ? "reset" : "new",
462645455e4dSMathias Nyman 					 (udev->speed == USB_SPEED_SUPER_PLUS) ?
462745455e4dSMathias Nyman 							"Plus Gen 2" : " Gen 1",
462845455e4dSMathias Nyman 					 (udev->rx_lanes == 2 && udev->tx_lanes == 2) ?
462945455e4dSMathias Nyman 							"x2" : "",
46301bb90cf0SPeter Chen 					 devnum, driver_name);
4631c6515272SSarah Sharp 			}
46321da177e4SLinus Torvalds 
46331da177e4SLinus Torvalds 			/* cope with hardware quirkiness:
46341da177e4SLinus Torvalds 			 *  - let SET_ADDRESS settle, some device hardware wants it
46351da177e4SLinus Torvalds 			 *  - read ep0 maxpacket even for high and low speed,
46361da177e4SLinus Torvalds 			 */
46371da177e4SLinus Torvalds 			msleep(10);
463848fc7dbdSDan Williams 			/* use_new_scheme() checks the speed which may have
463948fc7dbdSDan Williams 			 * changed since the initial look so we cache the result
464048fc7dbdSDan Williams 			 * in did_new_scheme
464148fc7dbdSDan Williams 			 */
464248fc7dbdSDan Williams 			if (did_new_scheme)
46431da177e4SLinus Torvalds 				break;
46446c529cdcSInaky Perez-Gonzalez 		}
46451da177e4SLinus Torvalds 
46461da177e4SLinus Torvalds 		retval = usb_get_device_descriptor(udev, 8);
46471da177e4SLinus Torvalds 		if (retval < 8) {
4648e9e88fb7SAlan Stern 			if (retval != -ENODEV)
4649b9cef6c3SWu Fengguang 				dev_err(&udev->dev,
4650b9cef6c3SWu Fengguang 					"device descriptor read/8, error %d\n",
4651b9cef6c3SWu Fengguang 					retval);
46521da177e4SLinus Torvalds 			if (retval >= 0)
46531da177e4SLinus Torvalds 				retval = -EMSGSIZE;
46541da177e4SLinus Torvalds 		} else {
4655886ee36eSFelipe Balbi 			u32 delay;
4656886ee36eSFelipe Balbi 
46571da177e4SLinus Torvalds 			retval = 0;
4658886ee36eSFelipe Balbi 
4659886ee36eSFelipe Balbi 			delay = udev->parent->hub_delay;
4660886ee36eSFelipe Balbi 			udev->hub_delay = min_t(u32, delay,
4661886ee36eSFelipe Balbi 						USB_TP_TRANSMISSION_DELAY_MAX);
4662886ee36eSFelipe Balbi 			retval = usb_set_isoch_delay(udev);
4663886ee36eSFelipe Balbi 			if (retval) {
4664886ee36eSFelipe Balbi 				dev_dbg(&udev->dev,
4665886ee36eSFelipe Balbi 					"Failed set isoch delay, error %d\n",
4666886ee36eSFelipe Balbi 					retval);
4667886ee36eSFelipe Balbi 				retval = 0;
4668886ee36eSFelipe Balbi 			}
46691da177e4SLinus Torvalds 			break;
46701da177e4SLinus Torvalds 		}
46711da177e4SLinus Torvalds 	}
46721da177e4SLinus Torvalds 	if (retval)
46731da177e4SLinus Torvalds 		goto fail;
46741da177e4SLinus Torvalds 
4675d8aec3dbSElric Fu 	/*
4676d8aec3dbSElric Fu 	 * Some superspeed devices have finished the link training process
4677d8aec3dbSElric Fu 	 * and attached to a superspeed hub port, but the device descriptor
4678d8aec3dbSElric Fu 	 * got from those devices show they aren't superspeed devices. Warm
4679d8aec3dbSElric Fu 	 * reset the port attached by the devices can fix them.
4680d8aec3dbSElric Fu 	 */
46818a1b2725SMathias Nyman 	if ((udev->speed >= USB_SPEED_SUPER) &&
4682d8aec3dbSElric Fu 			(le16_to_cpu(udev->descriptor.bcdUSB) < 0x0300)) {
4683d8aec3dbSElric Fu 		dev_err(&udev->dev, "got a wrong device descriptor, "
4684d8aec3dbSElric Fu 				"warm reset device\n");
4685d8aec3dbSElric Fu 		hub_port_reset(hub, port1, udev,
4686d8aec3dbSElric Fu 				HUB_BH_RESET_TIME, true);
4687d8aec3dbSElric Fu 		retval = -EINVAL;
4688d8aec3dbSElric Fu 		goto fail;
4689d8aec3dbSElric Fu 	}
4690d8aec3dbSElric Fu 
46916b403b02SSarah Sharp 	if (udev->descriptor.bMaxPacketSize0 == 0xff ||
46928a1b2725SMathias Nyman 			udev->speed >= USB_SPEED_SUPER)
46936b403b02SSarah Sharp 		i = 512;
46946b403b02SSarah Sharp 	else
46956b403b02SSarah Sharp 		i = udev->descriptor.bMaxPacketSize0;
469629cc8897SKuninori Morimoto 	if (usb_endpoint_maxp(&udev->ep0.desc) != i) {
469756626a72SAlan Stern 		if (udev->speed == USB_SPEED_LOW ||
46981da177e4SLinus Torvalds 				!(i == 8 || i == 16 || i == 32 || i == 64)) {
469956626a72SAlan Stern 			dev_err(&udev->dev, "Invalid ep0 maxpacket: %d\n", i);
47001da177e4SLinus Torvalds 			retval = -EMSGSIZE;
47011da177e4SLinus Torvalds 			goto fail;
47021da177e4SLinus Torvalds 		}
470356626a72SAlan Stern 		if (udev->speed == USB_SPEED_FULL)
47041da177e4SLinus Torvalds 			dev_dbg(&udev->dev, "ep0 maxpacket = %d\n", i);
470556626a72SAlan Stern 		else
470656626a72SAlan Stern 			dev_warn(&udev->dev, "Using ep0 maxpacket: %d\n", i);
47071da177e4SLinus Torvalds 		udev->ep0.desc.wMaxPacketSize = cpu_to_le16(i);
4708fc721f51SInaky Perez-Gonzalez 		usb_ep0_reinit(udev);
47091da177e4SLinus Torvalds 	}
47101da177e4SLinus Torvalds 
47111da177e4SLinus Torvalds 	retval = usb_get_device_descriptor(udev, USB_DT_DEVICE_SIZE);
47121da177e4SLinus Torvalds 	if (retval < (signed)sizeof(udev->descriptor)) {
4713e9e88fb7SAlan Stern 		if (retval != -ENODEV)
4714b9cef6c3SWu Fengguang 			dev_err(&udev->dev, "device descriptor read/all, error %d\n",
4715b9cef6c3SWu Fengguang 					retval);
47161da177e4SLinus Torvalds 		if (retval >= 0)
47171da177e4SLinus Torvalds 			retval = -ENOMSG;
47181da177e4SLinus Torvalds 		goto fail;
47191da177e4SLinus Torvalds 	}
47201da177e4SLinus Torvalds 
4721ad87e032SAlan Stern 	usb_detect_quirks(udev);
4722ad87e032SAlan Stern 
47231ff4df56SAndiry Xu 	if (udev->wusb == 0 && le16_to_cpu(udev->descriptor.bcdUSB) >= 0x0201) {
47241ff4df56SAndiry Xu 		retval = usb_get_bos_descriptor(udev);
472551e0a012SSarah Sharp 		if (!retval) {
4726d9b2099cSSarah Sharp 			udev->lpm_capable = usb_device_supports_lpm(udev);
472751e0a012SSarah Sharp 			usb_set_lpm_parameters(udev);
472851e0a012SSarah Sharp 		}
47291ff4df56SAndiry Xu 	}
47303148bf04SAndiry Xu 
47311da177e4SLinus Torvalds 	retval = 0;
473248f24970SAlek Du 	/* notify HCD that we have a device connected and addressed */
473348f24970SAlek Du 	if (hcd->driver->update_device)
473448f24970SAlek Du 		hcd->driver->update_device(hcd, udev);
4735890dae88SMathias Nyman 	hub_set_initial_usb2_lpm_policy(udev);
47361da177e4SLinus Torvalds fail:
47374326ed0bSAlan Stern 	if (retval) {
47381da177e4SLinus Torvalds 		hub_port_disable(hub, port1, 0);
47393b29b68bSAlan Stern 		update_devnum(udev, devnum);	/* for disconnect processing */
47404326ed0bSAlan Stern 	}
4741feb26ac3SChris Bainbridge 	mutex_unlock(hcd->address0_mutex);
47421da177e4SLinus Torvalds 	return retval;
47431da177e4SLinus Torvalds }
47441da177e4SLinus Torvalds 
47451da177e4SLinus Torvalds static void
47461da177e4SLinus Torvalds check_highspeed(struct usb_hub *hub, struct usb_device *udev, int port1)
47471da177e4SLinus Torvalds {
47481da177e4SLinus Torvalds 	struct usb_qualifier_descriptor	*qual;
47491da177e4SLinus Torvalds 	int				status;
47501da177e4SLinus Torvalds 
47512a159389SJohan Hovold 	if (udev->quirks & USB_QUIRK_DEVICE_QUALIFIER)
47522a159389SJohan Hovold 		return;
47532a159389SJohan Hovold 
4754e94b1766SChristoph Lameter 	qual = kmalloc(sizeof *qual, GFP_KERNEL);
47551da177e4SLinus Torvalds 	if (qual == NULL)
47561da177e4SLinus Torvalds 		return;
47571da177e4SLinus Torvalds 
47581da177e4SLinus Torvalds 	status = usb_get_descriptor(udev, USB_DT_DEVICE_QUALIFIER, 0,
47591da177e4SLinus Torvalds 			qual, sizeof *qual);
47601da177e4SLinus Torvalds 	if (status == sizeof *qual) {
47611da177e4SLinus Torvalds 		dev_info(&udev->dev, "not running at top speed; "
47621da177e4SLinus Torvalds 			"connect to a high speed hub\n");
47631da177e4SLinus Torvalds 		/* hub LEDs are probably harder to miss than syslog */
47641da177e4SLinus Torvalds 		if (hub->has_indicators) {
47651da177e4SLinus Torvalds 			hub->indicator[port1-1] = INDICATOR_GREEN_BLINK;
476622f6a0f0SShaibal Dutta 			queue_delayed_work(system_power_efficient_wq,
476722f6a0f0SShaibal Dutta 					&hub->leds, 0);
47681da177e4SLinus Torvalds 		}
47691da177e4SLinus Torvalds 	}
47701da177e4SLinus Torvalds 	kfree(qual);
47711da177e4SLinus Torvalds }
47721da177e4SLinus Torvalds 
47731da177e4SLinus Torvalds static unsigned
47741da177e4SLinus Torvalds hub_power_remaining(struct usb_hub *hub)
47751da177e4SLinus Torvalds {
47761da177e4SLinus Torvalds 	struct usb_device *hdev = hub->hdev;
47771da177e4SLinus Torvalds 	int remaining;
477855c52718SAlan Stern 	int port1;
47791da177e4SLinus Torvalds 
478055c52718SAlan Stern 	if (!hub->limited_power)
47811da177e4SLinus Torvalds 		return 0;
47821da177e4SLinus Torvalds 
478355c52718SAlan Stern 	remaining = hdev->bus_mA - hub->descriptor->bHubContrCurrent;
478455c52718SAlan Stern 	for (port1 = 1; port1 <= hdev->maxchild; ++port1) {
4785d99f6b41SDan Williams 		struct usb_port *port_dev = hub->ports[port1 - 1];
4786d99f6b41SDan Williams 		struct usb_device *udev = port_dev->child;
4787430ee58eSSebastian Andrzej Siewior 		unsigned unit_load;
4788d99f6b41SDan Williams 		int delta;
47891da177e4SLinus Torvalds 
47901da177e4SLinus Torvalds 		if (!udev)
47911da177e4SLinus Torvalds 			continue;
4792430ee58eSSebastian Andrzej Siewior 		if (hub_is_superspeed(udev))
4793430ee58eSSebastian Andrzej Siewior 			unit_load = 150;
4794430ee58eSSebastian Andrzej Siewior 		else
4795430ee58eSSebastian Andrzej Siewior 			unit_load = 100;
47961da177e4SLinus Torvalds 
4797430ee58eSSebastian Andrzej Siewior 		/*
4798430ee58eSSebastian Andrzej Siewior 		 * Unconfigured devices may not use more than one unit load,
4799430ee58eSSebastian Andrzej Siewior 		 * or 8mA for OTG ports
4800430ee58eSSebastian Andrzej Siewior 		 */
48011da177e4SLinus Torvalds 		if (udev->actconfig)
48028d8479dbSSebastian Andrzej Siewior 			delta = usb_get_max_power(udev, udev->actconfig);
480355c52718SAlan Stern 		else if (port1 != udev->bus->otg_port || hdev->parent)
4804430ee58eSSebastian Andrzej Siewior 			delta = unit_load;
48051da177e4SLinus Torvalds 		else
480655c52718SAlan Stern 			delta = 8;
480755c52718SAlan Stern 		if (delta > hub->mA_per_port)
4808d99f6b41SDan Williams 			dev_warn(&port_dev->dev, "%dmA is over %umA budget!\n",
4809d99f6b41SDan Williams 					delta, hub->mA_per_port);
48101da177e4SLinus Torvalds 		remaining -= delta;
48111da177e4SLinus Torvalds 	}
48121da177e4SLinus Torvalds 	if (remaining < 0) {
481355c52718SAlan Stern 		dev_warn(hub->intfdev, "%dmA over power budget!\n",
481455c52718SAlan Stern 			-remaining);
48151da177e4SLinus Torvalds 		remaining = 0;
48161da177e4SLinus Torvalds 	}
48171da177e4SLinus Torvalds 	return remaining;
48181da177e4SLinus Torvalds }
48191da177e4SLinus Torvalds 
4820af376a46SDan Williams static void hub_port_connect(struct usb_hub *hub, int port1, u16 portstatus,
4821af376a46SDan Williams 		u16 portchange)
48221da177e4SLinus Torvalds {
482394c43b98SAlan Stern 	int status = -ENODEV;
482494c43b98SAlan Stern 	int i;
4825430ee58eSSebastian Andrzej Siewior 	unsigned unit_load;
48261da177e4SLinus Torvalds 	struct usb_device *hdev = hub->hdev;
48271da177e4SLinus Torvalds 	struct usb_hcd *hcd = bus_to_hcd(hdev->bus);
4828d99f6b41SDan Williams 	struct usb_port *port_dev = hub->ports[port1 - 1];
4829af376a46SDan Williams 	struct usb_device *udev = port_dev->child;
48305ee0f803SOliver Neukum 	static int unreliable_port = -1;
48318808f00cSAlan Stern 
483224618b0cSAlan Stern 	/* Disconnect any existing devices under this port */
4833b76baa81SPeter Chen 	if (udev) {
4834b2108f1eSPeter Chen 		if (hcd->usb_phy && !hdev->parent)
48353d46e73dSAntoine Tenart 			usb_phy_notify_disconnect(hcd->usb_phy, udev->speed);
4836d99f6b41SDan Williams 		usb_disconnect(&port_dev->child);
4837b76baa81SPeter Chen 	}
483824618b0cSAlan Stern 
4839253e0572SAlan Stern 	/* We can forget about a "removed" device when there's a physical
4840253e0572SAlan Stern 	 * disconnect or the connect status changes.
4841253e0572SAlan Stern 	 */
4842253e0572SAlan Stern 	if (!(portstatus & USB_PORT_STAT_CONNECTION) ||
4843253e0572SAlan Stern 			(portchange & USB_PORT_STAT_C_CONNECTION))
4844253e0572SAlan Stern 		clear_bit(port1, hub->removed_bits);
4845253e0572SAlan Stern 
48465257d97aSAlan Stern 	if (portchange & (USB_PORT_STAT_C_CONNECTION |
48475257d97aSAlan Stern 				USB_PORT_STAT_C_ENABLE)) {
4848ad493e5eSLan Tianyu 		status = hub_port_debounce_be_stable(hub, port1);
48495257d97aSAlan Stern 		if (status < 0) {
48505ee0f803SOliver Neukum 			if (status != -ENODEV &&
48515ee0f803SOliver Neukum 				port1 != unreliable_port &&
48525ee0f803SOliver Neukum 				printk_ratelimit())
4853dd5f5006STakashi Iwai 				dev_err(&port_dev->dev, "connect-debounce failed\n");
48545257d97aSAlan Stern 			portstatus &= ~USB_PORT_STAT_CONNECTION;
48555ee0f803SOliver Neukum 			unreliable_port = port1;
48565257d97aSAlan Stern 		} else {
48575257d97aSAlan Stern 			portstatus = status;
48585257d97aSAlan Stern 		}
48595257d97aSAlan Stern 	}
48605257d97aSAlan Stern 
4861253e0572SAlan Stern 	/* Return now if debouncing failed or nothing is connected or
4862253e0572SAlan Stern 	 * the device was "removed".
4863253e0572SAlan Stern 	 */
4864253e0572SAlan Stern 	if (!(portstatus & USB_PORT_STAT_CONNECTION) ||
4865253e0572SAlan Stern 			test_bit(port1, hub->removed_bits)) {
48661da177e4SLinus Torvalds 
4867fbaecff0SDeepak Das 		/*
4868fbaecff0SDeepak Das 		 * maybe switch power back on (e.g. root hub was reset)
4869fbaecff0SDeepak Das 		 * but only if the port isn't owned by someone else.
4870fbaecff0SDeepak Das 		 */
48719262c19dSDan Williams 		if (hub_is_port_power_switchable(hub)
4872fbaecff0SDeepak Das 				&& !port_is_power_on(hub, portstatus)
4873fbaecff0SDeepak Das 				&& !port_dev->port_owner)
48741da177e4SLinus Torvalds 			set_port_feature(hdev, port1, USB_PORT_FEAT_POWER);
48751da177e4SLinus Torvalds 
48761da177e4SLinus Torvalds 		if (portstatus & USB_PORT_STAT_ENABLE)
48771da177e4SLinus Torvalds 			goto done;
48781da177e4SLinus Torvalds 		return;
48791da177e4SLinus Torvalds 	}
4880430ee58eSSebastian Andrzej Siewior 	if (hub_is_superspeed(hub->hdev))
4881430ee58eSSebastian Andrzej Siewior 		unit_load = 150;
4882430ee58eSSebastian Andrzej Siewior 	else
4883430ee58eSSebastian Andrzej Siewior 		unit_load = 100;
48841da177e4SLinus Torvalds 
4885e9e88fb7SAlan Stern 	status = 0;
48861da177e4SLinus Torvalds 	for (i = 0; i < SET_CONFIG_TRIES; i++) {
48871da177e4SLinus Torvalds 
48881da177e4SLinus Torvalds 		/* reallocate for each attempt, since references
48891da177e4SLinus Torvalds 		 * to the previous one can escape in various ways
48901da177e4SLinus Torvalds 		 */
48911da177e4SLinus Torvalds 		udev = usb_alloc_dev(hdev, hdev->bus, port1);
48921da177e4SLinus Torvalds 		if (!udev) {
4893d99f6b41SDan Williams 			dev_err(&port_dev->dev,
4894d99f6b41SDan Williams 					"couldn't allocate usb_device\n");
48951da177e4SLinus Torvalds 			goto done;
48961da177e4SLinus Torvalds 		}
48971da177e4SLinus Torvalds 
48981da177e4SLinus Torvalds 		usb_set_device_state(udev, USB_STATE_POWERED);
489955c52718SAlan Stern 		udev->bus_mA = hub->mA_per_port;
4900b6956ffaSAlan Stern 		udev->level = hdev->level + 1;
49018af548dcSInaky Perez-Gonzalez 		udev->wusb = hub_is_wusb(hub);
49021da177e4SLinus Torvalds 
49038a1b2725SMathias Nyman 		/* Devices connected to SuperSpeed hubs are USB 3.0 or later */
4904131dec34SSarah Sharp 		if (hub_is_superspeed(hub->hdev))
4905e7b77172SSarah Sharp 			udev->speed = USB_SPEED_SUPER;
4906e7b77172SSarah Sharp 		else
4907e7b77172SSarah Sharp 			udev->speed = USB_SPEED_UNKNOWN;
4908e7b77172SSarah Sharp 
49093b29b68bSAlan Stern 		choose_devnum(udev);
4910c6515272SSarah Sharp 		if (udev->devnum <= 0) {
4911c6515272SSarah Sharp 			status = -ENOTCONN;	/* Don't retry */
4912c6515272SSarah Sharp 			goto loop;
4913c6515272SSarah Sharp 		}
4914c6515272SSarah Sharp 
4915e7b77172SSarah Sharp 		/* reset (non-USB 3.0 devices) and get descriptor */
49165c79a1e3SDan Williams 		usb_lock_port(port_dev);
49171da177e4SLinus Torvalds 		status = hub_port_init(hub, udev, port1, i);
49185c79a1e3SDan Williams 		usb_unlock_port(port_dev);
49191da177e4SLinus Torvalds 		if (status < 0)
49201da177e4SLinus Torvalds 			goto loop;
49211da177e4SLinus Torvalds 
492293362a87SPhil Dibowitz 		if (udev->quirks & USB_QUIRK_DELAY_INIT)
4923b2a542bbSDmitry Fleytman 			msleep(2000);
492493362a87SPhil Dibowitz 
49251da177e4SLinus Torvalds 		/* consecutive bus-powered hubs aren't reliable; they can
49261da177e4SLinus Torvalds 		 * violate the voltage drop budget.  if the new child has
49271da177e4SLinus Torvalds 		 * a "powered" LED, users should notice we didn't enable it
49281da177e4SLinus Torvalds 		 * (without reading syslog), even without per-port LEDs
49291da177e4SLinus Torvalds 		 * on the parent.
49301da177e4SLinus Torvalds 		 */
49311da177e4SLinus Torvalds 		if (udev->descriptor.bDeviceClass == USB_CLASS_HUB
4932430ee58eSSebastian Andrzej Siewior 				&& udev->bus_mA <= unit_load) {
49331da177e4SLinus Torvalds 			u16	devstat;
49341da177e4SLinus Torvalds 
4935d9e1e148SFelipe Balbi 			status = usb_get_std_status(udev, USB_RECIP_DEVICE, 0,
49361da177e4SLinus Torvalds 					&devstat);
493715b7336eSAlan Stern 			if (status) {
49381da177e4SLinus Torvalds 				dev_dbg(&udev->dev, "get status %d ?\n", status);
49391da177e4SLinus Torvalds 				goto loop_disable;
49401da177e4SLinus Torvalds 			}
49411da177e4SLinus Torvalds 			if ((devstat & (1 << USB_DEVICE_SELF_POWERED)) == 0) {
49421da177e4SLinus Torvalds 				dev_err(&udev->dev,
49431da177e4SLinus Torvalds 					"can't connect bus-powered hub "
49441da177e4SLinus Torvalds 					"to this port\n");
49451da177e4SLinus Torvalds 				if (hub->has_indicators) {
49461da177e4SLinus Torvalds 					hub->indicator[port1-1] =
49471da177e4SLinus Torvalds 						INDICATOR_AMBER_BLINK;
494822f6a0f0SShaibal Dutta 					queue_delayed_work(
494922f6a0f0SShaibal Dutta 						system_power_efficient_wq,
495022f6a0f0SShaibal Dutta 						&hub->leds, 0);
49511da177e4SLinus Torvalds 				}
49521da177e4SLinus Torvalds 				status = -ENOTCONN;	/* Don't retry */
49531da177e4SLinus Torvalds 				goto loop_disable;
49541da177e4SLinus Torvalds 			}
49551da177e4SLinus Torvalds 		}
49561da177e4SLinus Torvalds 
49571da177e4SLinus Torvalds 		/* check for devices running slower than they could */
49581da177e4SLinus Torvalds 		if (le16_to_cpu(udev->descriptor.bcdUSB) >= 0x0200
49591da177e4SLinus Torvalds 				&& udev->speed == USB_SPEED_FULL
49601da177e4SLinus Torvalds 				&& highspeed_hubs != 0)
49611da177e4SLinus Torvalds 			check_highspeed(hub, udev, port1);
49621da177e4SLinus Torvalds 
4963fa286188SGreg Kroah-Hartman 		/* Store the parent's children[] pointer.  At this point
49641da177e4SLinus Torvalds 		 * udev becomes globally accessible, although presumably
49651da177e4SLinus Torvalds 		 * no one will look at it until hdev is unlocked.
49661da177e4SLinus Torvalds 		 */
49671da177e4SLinus Torvalds 		status = 0;
49681da177e4SLinus Torvalds 
4969d8521afeSDan Williams 		mutex_lock(&usb_port_peer_mutex);
4970d8521afeSDan Williams 
49711da177e4SLinus Torvalds 		/* We mustn't add new devices if the parent hub has
49721da177e4SLinus Torvalds 		 * been disconnected; we would race with the
49731da177e4SLinus Torvalds 		 * recursively_mark_NOTATTACHED() routine.
49741da177e4SLinus Torvalds 		 */
49751da177e4SLinus Torvalds 		spin_lock_irq(&device_state_lock);
49761da177e4SLinus Torvalds 		if (hdev->state == USB_STATE_NOTATTACHED)
49771da177e4SLinus Torvalds 			status = -ENOTCONN;
49781da177e4SLinus Torvalds 		else
4979d99f6b41SDan Williams 			port_dev->child = udev;
49801da177e4SLinus Torvalds 		spin_unlock_irq(&device_state_lock);
4981d8521afeSDan Williams 		mutex_unlock(&usb_port_peer_mutex);
49821da177e4SLinus Torvalds 
49831da177e4SLinus Torvalds 		/* Run it through the hoops (find a driver, etc) */
49841da177e4SLinus Torvalds 		if (!status) {
49851da177e4SLinus Torvalds 			status = usb_new_device(udev);
49861da177e4SLinus Torvalds 			if (status) {
4987d8521afeSDan Williams 				mutex_lock(&usb_port_peer_mutex);
49881da177e4SLinus Torvalds 				spin_lock_irq(&device_state_lock);
4989d99f6b41SDan Williams 				port_dev->child = NULL;
49901da177e4SLinus Torvalds 				spin_unlock_irq(&device_state_lock);
4991d8521afeSDan Williams 				mutex_unlock(&usb_port_peer_mutex);
499201ed67dcSTony Zheng 			} else {
499301ed67dcSTony Zheng 				if (hcd->usb_phy && !hdev->parent)
499401ed67dcSTony Zheng 					usb_phy_notify_connect(hcd->usb_phy,
499501ed67dcSTony Zheng 							udev->speed);
49961da177e4SLinus Torvalds 			}
49971da177e4SLinus Torvalds 		}
49981da177e4SLinus Torvalds 
49991da177e4SLinus Torvalds 		if (status)
50001da177e4SLinus Torvalds 			goto loop_disable;
50011da177e4SLinus Torvalds 
50021da177e4SLinus Torvalds 		status = hub_power_remaining(hub);
50031da177e4SLinus Torvalds 		if (status)
5004d99f6b41SDan Williams 			dev_dbg(hub->intfdev, "%dmA power budget left\n", status);
50051da177e4SLinus Torvalds 
50061da177e4SLinus Torvalds 		return;
50071da177e4SLinus Torvalds 
50081da177e4SLinus Torvalds loop_disable:
50091da177e4SLinus Torvalds 		hub_port_disable(hub, port1, 1);
50101da177e4SLinus Torvalds loop:
5011fc721f51SInaky Perez-Gonzalez 		usb_ep0_reinit(udev);
50123b29b68bSAlan Stern 		release_devnum(udev);
5013f7410cedSHerbert Xu 		hub_free_dev(udev);
50141da177e4SLinus Torvalds 		usb_put_dev(udev);
5015ffcdc18dSVikram Pandita 		if ((status == -ENOTCONN) || (status == -ENOTSUPP))
50161da177e4SLinus Torvalds 			break;
5017973593a9SMike Looijmans 
5018973593a9SMike Looijmans 		/* When halfway through our retry count, power-cycle the port */
5019973593a9SMike Looijmans 		if (i == (SET_CONFIG_TRIES / 2) - 1) {
5020973593a9SMike Looijmans 			dev_info(&port_dev->dev, "attempt power cycle\n");
5021973593a9SMike Looijmans 			usb_hub_set_port_power(hdev, hub, port1, false);
5022973593a9SMike Looijmans 			msleep(2 * hub_power_on_good_delay(hub));
5023973593a9SMike Looijmans 			usb_hub_set_port_power(hdev, hub, port1, true);
5024973593a9SMike Looijmans 			msleep(hub_power_on_good_delay(hub));
5025973593a9SMike Looijmans 		}
50261da177e4SLinus Torvalds 	}
50273a31155cSAlan Stern 	if (hub->hdev->parent ||
50283a31155cSAlan Stern 			!hcd->driver->port_handed_over ||
5029e9e88fb7SAlan Stern 			!(hcd->driver->port_handed_over)(hcd, port1)) {
5030e9e88fb7SAlan Stern 		if (status != -ENOTCONN && status != -ENODEV)
5031d99f6b41SDan Williams 			dev_err(&port_dev->dev,
5032d99f6b41SDan Williams 					"unable to enumerate USB device\n");
5033e9e88fb7SAlan Stern 	}
50341da177e4SLinus Torvalds 
50351da177e4SLinus Torvalds done:
50361da177e4SLinus Torvalds 	hub_port_disable(hub, port1, 1);
503794c43b98SAlan Stern 	if (hcd->driver->relinquish_port && !hub->hdev->parent) {
503894c43b98SAlan Stern 		if (status != -ENOTCONN && status != -ENODEV)
503990da096eSBalaji Rao 			hcd->driver->relinquish_port(hcd, port1);
504094c43b98SAlan Stern 	}
50411da177e4SLinus Torvalds }
50421da177e4SLinus Torvalds 
5043af376a46SDan Williams /* Handle physical or logical connection change events.
5044af376a46SDan Williams  * This routine is called when:
5045af376a46SDan Williams  *	a port connection-change occurs;
5046af376a46SDan Williams  *	a port enable-change occurs (often caused by EMI);
5047af376a46SDan Williams  *	usb_reset_and_verify_device() encounters changed descriptors (as from
5048af376a46SDan Williams  *		a firmware download)
5049af376a46SDan Williams  * caller already locked the hub
5050af376a46SDan Williams  */
5051af376a46SDan Williams static void hub_port_connect_change(struct usb_hub *hub, int port1,
505272937e1eSSarah Sharp 					u16 portstatus, u16 portchange)
50535c79a1e3SDan Williams 		__must_hold(&port_dev->status_lock)
5054714b07beSSarah Sharp {
5055af376a46SDan Williams 	struct usb_port *port_dev = hub->ports[port1 - 1];
5056af376a46SDan Williams 	struct usb_device *udev = port_dev->child;
5057af376a46SDan Williams 	int status = -ENODEV;
5058714b07beSSarah Sharp 
5059af376a46SDan Williams 	dev_dbg(&port_dev->dev, "status %04x, change %04x, %s\n", portstatus,
5060af376a46SDan Williams 			portchange, portspeed(hub, portstatus));
5061af376a46SDan Williams 
5062af376a46SDan Williams 	if (hub->has_indicators) {
5063af376a46SDan Williams 		set_port_led(hub, port1, HUB_LED_AUTO);
5064af376a46SDan Williams 		hub->indicator[port1-1] = INDICATOR_AUTO;
50654ee823b8SSarah Sharp 	}
5066714b07beSSarah Sharp 
5067af376a46SDan Williams #ifdef	CONFIG_USB_OTG
5068af376a46SDan Williams 	/* during HNP, don't repeat the debounce */
5069af376a46SDan Williams 	if (hub->hdev->bus->is_b_host)
5070af376a46SDan Williams 		portchange &= ~(USB_PORT_STAT_C_CONNECTION |
5071af376a46SDan Williams 				USB_PORT_STAT_C_ENABLE);
5072af376a46SDan Williams #endif
5073714b07beSSarah Sharp 
5074af376a46SDan Williams 	/* Try to resuscitate an existing device */
5075af376a46SDan Williams 	if ((portstatus & USB_PORT_STAT_CONNECTION) && udev &&
5076af376a46SDan Williams 			udev->state != USB_STATE_NOTATTACHED) {
5077af376a46SDan Williams 		if (portstatus & USB_PORT_STAT_ENABLE) {
5078af376a46SDan Williams 			status = 0;		/* Nothing to do */
5079ceb6c9c8SRafael J. Wysocki #ifdef CONFIG_PM
5080af376a46SDan Williams 		} else if (udev->state == USB_STATE_SUSPENDED &&
5081af376a46SDan Williams 				udev->persist_enabled) {
5082af376a46SDan Williams 			/* For a suspended device, treat this as a
5083af376a46SDan Williams 			 * remote wakeup event.
5084af376a46SDan Williams 			 */
50855c79a1e3SDan Williams 			usb_unlock_port(port_dev);
5086af376a46SDan Williams 			status = usb_remote_wakeup(udev);
50875c79a1e3SDan Williams 			usb_lock_port(port_dev);
5088af376a46SDan Williams #endif
5089af376a46SDan Williams 		} else {
5090af376a46SDan Williams 			/* Don't resuscitate */;
5091af376a46SDan Williams 		}
5092af376a46SDan Williams 	}
5093af376a46SDan Williams 	clear_bit(port1, hub->change_bits);
5094af376a46SDan Williams 
50955c79a1e3SDan Williams 	/* successfully revalidated the connection */
5096af376a46SDan Williams 	if (status == 0)
5097af376a46SDan Williams 		return;
5098af376a46SDan Williams 
50995c79a1e3SDan Williams 	usb_unlock_port(port_dev);
5100af376a46SDan Williams 	hub_port_connect(hub, port1, portstatus, portchange);
51015c79a1e3SDan Williams 	usb_lock_port(port_dev);
51021da177e4SLinus Torvalds }
51031da177e4SLinus Torvalds 
5104af376a46SDan Williams static void port_event(struct usb_hub *hub, int port1)
51055c79a1e3SDan Williams 		__must_hold(&port_dev->status_lock)
5106af376a46SDan Williams {
51077671bd1eSZhuang Jin Can 	int connect_change;
5108af376a46SDan Williams 	struct usb_port *port_dev = hub->ports[port1 - 1];
5109af376a46SDan Williams 	struct usb_device *udev = port_dev->child;
5110af376a46SDan Williams 	struct usb_device *hdev = hub->hdev;
5111af376a46SDan Williams 	u16 portstatus, portchange;
5112af376a46SDan Williams 
5113af376a46SDan Williams 	connect_change = test_bit(port1, hub->change_bits);
5114af376a46SDan Williams 	clear_bit(port1, hub->event_bits);
5115af376a46SDan Williams 	clear_bit(port1, hub->wakeup_bits);
5116af376a46SDan Williams 
5117af376a46SDan Williams 	if (hub_port_status(hub, port1, &portstatus, &portchange) < 0)
5118af376a46SDan Williams 		return;
5119af376a46SDan Williams 
5120af376a46SDan Williams 	if (portchange & USB_PORT_STAT_C_CONNECTION) {
5121af376a46SDan Williams 		usb_clear_port_feature(hdev, port1, USB_PORT_FEAT_C_CONNECTION);
5122714b07beSSarah Sharp 		connect_change = 1;
5123714b07beSSarah Sharp 	}
5124af376a46SDan Williams 
5125af376a46SDan Williams 	if (portchange & USB_PORT_STAT_C_ENABLE) {
5126af376a46SDan Williams 		if (!connect_change)
5127af376a46SDan Williams 			dev_dbg(&port_dev->dev, "enable change, status %08x\n",
5128af376a46SDan Williams 					portstatus);
5129af376a46SDan Williams 		usb_clear_port_feature(hdev, port1, USB_PORT_FEAT_C_ENABLE);
5130af376a46SDan Williams 
5131af376a46SDan Williams 		/*
5132af376a46SDan Williams 		 * EM interference sometimes causes badly shielded USB devices
5133af376a46SDan Williams 		 * to be shutdown by the hub, this hack enables them again.
5134af376a46SDan Williams 		 * Works at least with mouse driver.
5135af376a46SDan Williams 		 */
5136af376a46SDan Williams 		if (!(portstatus & USB_PORT_STAT_ENABLE)
5137af376a46SDan Williams 		    && !connect_change && udev) {
5138af376a46SDan Williams 			dev_err(&port_dev->dev, "disabled by hub (EMI?), re-enabling...\n");
5139af376a46SDan Williams 			connect_change = 1;
5140714b07beSSarah Sharp 		}
5141af376a46SDan Williams 	}
5142af376a46SDan Williams 
5143af376a46SDan Williams 	if (portchange & USB_PORT_STAT_C_OVERCURRENT) {
5144af376a46SDan Williams 		u16 status = 0, unused;
51451cbd53c8SRichard Leitner 		port_dev->over_current_count++;
5146af376a46SDan Williams 
51471cbd53c8SRichard Leitner 		dev_dbg(&port_dev->dev, "over-current change #%u\n",
51481cbd53c8SRichard Leitner 			port_dev->over_current_count);
5149af376a46SDan Williams 		usb_clear_port_feature(hdev, port1,
5150af376a46SDan Williams 				USB_PORT_FEAT_C_OVER_CURRENT);
5151af376a46SDan Williams 		msleep(100);	/* Cool down */
5152af376a46SDan Williams 		hub_power_on(hub, true);
5153af376a46SDan Williams 		hub_port_status(hub, port1, &status, &unused);
5154af376a46SDan Williams 		if (status & USB_PORT_STAT_OVERCURRENT)
5155af376a46SDan Williams 			dev_err(&port_dev->dev, "over-current condition\n");
5156af376a46SDan Williams 	}
5157af376a46SDan Williams 
5158af376a46SDan Williams 	if (portchange & USB_PORT_STAT_C_RESET) {
5159af376a46SDan Williams 		dev_dbg(&port_dev->dev, "reset change\n");
5160af376a46SDan Williams 		usb_clear_port_feature(hdev, port1, USB_PORT_FEAT_C_RESET);
5161af376a46SDan Williams 	}
5162af376a46SDan Williams 	if ((portchange & USB_PORT_STAT_C_BH_RESET)
5163af376a46SDan Williams 	    && hub_is_superspeed(hdev)) {
5164af376a46SDan Williams 		dev_dbg(&port_dev->dev, "warm reset change\n");
5165af376a46SDan Williams 		usb_clear_port_feature(hdev, port1,
5166af376a46SDan Williams 				USB_PORT_FEAT_C_BH_PORT_RESET);
5167af376a46SDan Williams 	}
5168af376a46SDan Williams 	if (portchange & USB_PORT_STAT_C_LINK_STATE) {
5169af376a46SDan Williams 		dev_dbg(&port_dev->dev, "link state change\n");
5170af376a46SDan Williams 		usb_clear_port_feature(hdev, port1,
5171af376a46SDan Williams 				USB_PORT_FEAT_C_PORT_LINK_STATE);
5172af376a46SDan Williams 	}
5173af376a46SDan Williams 	if (portchange & USB_PORT_STAT_C_CONFIG_ERROR) {
5174af376a46SDan Williams 		dev_warn(&port_dev->dev, "config error\n");
5175af376a46SDan Williams 		usb_clear_port_feature(hdev, port1,
5176af376a46SDan Williams 				USB_PORT_FEAT_C_PORT_CONFIG_ERROR);
5177af376a46SDan Williams 	}
5178af376a46SDan Williams 
5179097a155fSDan Williams 	/* skip port actions that require the port to be powered on */
5180097a155fSDan Williams 	if (!pm_runtime_active(&port_dev->dev))
5181097a155fSDan Williams 		return;
5182097a155fSDan Williams 
5183af376a46SDan Williams 	if (hub_handle_remote_wakeup(hub, port1, portstatus, portchange))
5184af376a46SDan Williams 		connect_change = 1;
5185af376a46SDan Williams 
5186af376a46SDan Williams 	/*
5187af376a46SDan Williams 	 * Warm reset a USB3 protocol port if it's in
5188af376a46SDan Williams 	 * SS.Inactive state.
5189af376a46SDan Williams 	 */
51903cd12f91SDan Williams 	if (hub_port_warm_reset_required(hub, port1, portstatus)) {
5191af376a46SDan Williams 		dev_dbg(&port_dev->dev, "do warm reset\n");
5192af376a46SDan Williams 		if (!udev || !(portstatus & USB_PORT_STAT_CONNECTION)
5193af376a46SDan Williams 				|| udev->state == USB_STATE_NOTATTACHED) {
5194af376a46SDan Williams 			if (hub_port_reset(hub, port1, NULL,
5195af376a46SDan Williams 					HUB_BH_RESET_TIME, true) < 0)
5196af376a46SDan Williams 				hub_port_disable(hub, port1, 1);
51977671bd1eSZhuang Jin Can 		} else {
51985c79a1e3SDan Williams 			usb_unlock_port(port_dev);
5199af376a46SDan Williams 			usb_lock_device(udev);
5200af376a46SDan Williams 			usb_reset_device(udev);
5201af376a46SDan Williams 			usb_unlock_device(udev);
52025c79a1e3SDan Williams 			usb_lock_port(port_dev);
5203af376a46SDan Williams 			connect_change = 0;
5204af376a46SDan Williams 		}
52057671bd1eSZhuang Jin Can 	}
5206af376a46SDan Williams 
5207af376a46SDan Williams 	if (connect_change)
5208af376a46SDan Williams 		hub_port_connect_change(hub, port1, portstatus, portchange);
5209af376a46SDan Williams }
5210af376a46SDan Williams 
521132a69589SPetr Mladek static void hub_event(struct work_struct *work)
52121da177e4SLinus Torvalds {
52131da177e4SLinus Torvalds 	struct usb_device *hdev;
52141da177e4SLinus Torvalds 	struct usb_interface *intf;
52151da177e4SLinus Torvalds 	struct usb_hub *hub;
52161da177e4SLinus Torvalds 	struct device *hub_dev;
52171da177e4SLinus Torvalds 	u16 hubstatus;
52181da177e4SLinus Torvalds 	u16 hubchange;
52191da177e4SLinus Torvalds 	int i, ret;
52201da177e4SLinus Torvalds 
522132a69589SPetr Mladek 	hub = container_of(work, struct usb_hub, events);
52225d14f323SPetr Mladek 	hdev = hub->hdev;
5223e8054854SAlan Stern 	hub_dev = hub->intfdev;
5224e8054854SAlan Stern 	intf = to_usb_interface(hub_dev);
522532a69589SPetr Mladek 
522640f122f3SAlan Stern 	dev_dbg(hub_dev, "state %d ports %d chg %04x evt %04x\n",
52273bbc47d8SKrzysztof Mazur 			hdev->state, hdev->maxchild,
52281da177e4SLinus Torvalds 			/* NOTE: expects max 15 ports... */
52291da177e4SLinus Torvalds 			(u16) hub->change_bits[0],
523040f122f3SAlan Stern 			(u16) hub->event_bits[0]);
52311da177e4SLinus Torvalds 
52321da177e4SLinus Torvalds 	/* Lock the device, then check to see if we were
52331da177e4SLinus Torvalds 	 * disconnected while waiting for the lock to succeed. */
523406b84e8aSAlan Stern 	usb_lock_device(hdev);
5235e8054854SAlan Stern 	if (unlikely(hub->disconnected))
523632a69589SPetr Mladek 		goto out_hdev_lock;
52371da177e4SLinus Torvalds 
52381da177e4SLinus Torvalds 	/* If the hub has died, clean up after it */
52391da177e4SLinus Torvalds 	if (hdev->state == USB_STATE_NOTATTACHED) {
52407de18d8bSAlan Stern 		hub->error = -ENODEV;
52414330354fSAlan Stern 		hub_quiesce(hub, HUB_DISCONNECT);
524232a69589SPetr Mladek 		goto out_hdev_lock;
52431da177e4SLinus Torvalds 	}
52441da177e4SLinus Torvalds 
524540f122f3SAlan Stern 	/* Autoresume */
524640f122f3SAlan Stern 	ret = usb_autopm_get_interface(intf);
524740f122f3SAlan Stern 	if (ret) {
524840f122f3SAlan Stern 		dev_dbg(hub_dev, "Can't autoresume: %d\n", ret);
524932a69589SPetr Mladek 		goto out_hdev_lock;
525040f122f3SAlan Stern 	}
525140f122f3SAlan Stern 
525240f122f3SAlan Stern 	/* If this is an inactive hub, do nothing */
525340f122f3SAlan Stern 	if (hub->quiescing)
5254eb6e2924SPetr Mladek 		goto out_autopm;
52551da177e4SLinus Torvalds 
52561da177e4SLinus Torvalds 	if (hub->error) {
5257eb6e2924SPetr Mladek 		dev_dbg(hub_dev, "resetting for error %d\n", hub->error);
52581da177e4SLinus Torvalds 
5259742120c6SMing Lei 		ret = usb_reset_device(hdev);
52601da177e4SLinus Torvalds 		if (ret) {
5261eb6e2924SPetr Mladek 			dev_dbg(hub_dev, "error resetting hub: %d\n", ret);
5262eb6e2924SPetr Mladek 			goto out_autopm;
52631da177e4SLinus Torvalds 		}
52641da177e4SLinus Torvalds 
52651da177e4SLinus Torvalds 		hub->nerrors = 0;
52661da177e4SLinus Torvalds 		hub->error = 0;
52671da177e4SLinus Torvalds 	}
52681da177e4SLinus Torvalds 
52691da177e4SLinus Torvalds 	/* deal with port status changes */
52703bbc47d8SKrzysztof Mazur 	for (i = 1; i <= hdev->maxchild; i++) {
5271097a155fSDan Williams 		struct usb_port *port_dev = hub->ports[i - 1];
5272a82b76f7SHans de Goede 
52735c79a1e3SDan Williams 		if (test_bit(i, hub->event_bits)
5274af376a46SDan Williams 				|| test_bit(i, hub->change_bits)
52755c79a1e3SDan Williams 				|| test_bit(i, hub->wakeup_bits)) {
52761da177e4SLinus Torvalds 			/*
5277097a155fSDan Williams 			 * The get_noresume and barrier ensure that if
5278097a155fSDan Williams 			 * the port was in the process of resuming, we
5279097a155fSDan Williams 			 * flush that work and keep the port active for
5280097a155fSDan Williams 			 * the duration of the port_event().  However,
5281097a155fSDan Williams 			 * if the port is runtime pm suspended
5282097a155fSDan Williams 			 * (powered-off), we leave it in that state, run
5283097a155fSDan Williams 			 * an abbreviated port_event(), and move on.
52841da177e4SLinus Torvalds 			 */
5285097a155fSDan Williams 			pm_runtime_get_noresume(&port_dev->dev);
5286097a155fSDan Williams 			pm_runtime_barrier(&port_dev->dev);
52875c79a1e3SDan Williams 			usb_lock_port(port_dev);
5288af376a46SDan Williams 			port_event(hub, i);
52895c79a1e3SDan Williams 			usb_unlock_port(port_dev);
5290097a155fSDan Williams 			pm_runtime_put_sync(&port_dev->dev);
52911da177e4SLinus Torvalds 		}
52921da177e4SLinus Torvalds 	}
52931da177e4SLinus Torvalds 
52941da177e4SLinus Torvalds 	/* deal with hub status changes */
52951da177e4SLinus Torvalds 	if (test_and_clear_bit(0, hub->event_bits) == 0)
52961da177e4SLinus Torvalds 		;	/* do nothing */
52971da177e4SLinus Torvalds 	else if (hub_hub_status(hub, &hubstatus, &hubchange) < 0)
52981da177e4SLinus Torvalds 		dev_err(hub_dev, "get_hub_status failed\n");
52991da177e4SLinus Torvalds 	else {
53001da177e4SLinus Torvalds 		if (hubchange & HUB_CHANGE_LOCAL_POWER) {
53011da177e4SLinus Torvalds 			dev_dbg(hub_dev, "power change\n");
53021da177e4SLinus Torvalds 			clear_hub_feature(hdev, C_HUB_LOCAL_POWER);
530355c52718SAlan Stern 			if (hubstatus & HUB_STATUS_LOCAL_POWER)
530455c52718SAlan Stern 				/* FIXME: Is this always true? */
530555c52718SAlan Stern 				hub->limited_power = 1;
5306403fae78Sjidong xiao 			else
5307403fae78Sjidong xiao 				hub->limited_power = 0;
53081da177e4SLinus Torvalds 		}
53091da177e4SLinus Torvalds 		if (hubchange & HUB_CHANGE_OVERCURRENT) {
5310752d57a8SPaul Bolle 			u16 status = 0;
5311752d57a8SPaul Bolle 			u16 unused;
5312752d57a8SPaul Bolle 
5313752d57a8SPaul Bolle 			dev_dbg(hub_dev, "over-current change\n");
53141da177e4SLinus Torvalds 			clear_hub_feature(hdev, C_HUB_OVER_CURRENT);
5315752d57a8SPaul Bolle 			msleep(500);	/* Cool down */
53168520f380SAlan Stern 			hub_power_on(hub, true);
5317752d57a8SPaul Bolle 			hub_hub_status(hub, &status, &unused);
5318752d57a8SPaul Bolle 			if (status & HUB_STATUS_OVERCURRENT)
5319eb6e2924SPetr Mladek 				dev_err(hub_dev, "over-current condition\n");
53201da177e4SLinus Torvalds 		}
53211da177e4SLinus Torvalds 	}
53221da177e4SLinus Torvalds 
5323eb6e2924SPetr Mladek out_autopm:
53248e4ceb38SAlan Stern 	/* Balance the usb_autopm_get_interface() above */
53258e4ceb38SAlan Stern 	usb_autopm_put_interface_no_suspend(intf);
532632a69589SPetr Mladek out_hdev_lock:
53271da177e4SLinus Torvalds 	usb_unlock_device(hdev);
532832a69589SPetr Mladek 
532932a69589SPetr Mladek 	/* Balance the stuff in kick_hub_wq() and allow autosuspend */
533032a69589SPetr Mladek 	usb_autopm_put_interface(intf);
5331e8054854SAlan Stern 	kref_put(&hub->kref, hub_release);
53321da177e4SLinus Torvalds }
53331da177e4SLinus Torvalds 
53341e927d96SNémeth Márton static const struct usb_device_id hub_id_table[] = {
5335e6f30deaSMing Lei     { .match_flags = USB_DEVICE_ID_MATCH_VENDOR
5336e6f30deaSMing Lei 			| USB_DEVICE_ID_MATCH_INT_CLASS,
5337e6f30deaSMing Lei       .idVendor = USB_VENDOR_GENESYS_LOGIC,
5338e6f30deaSMing Lei       .bInterfaceClass = USB_CLASS_HUB,
5339e6f30deaSMing Lei       .driver_info = HUB_QUIRK_CHECK_PORT_AUTOSUSPEND},
53401da177e4SLinus Torvalds     { .match_flags = USB_DEVICE_ID_MATCH_DEV_CLASS,
53411da177e4SLinus Torvalds       .bDeviceClass = USB_CLASS_HUB},
53421da177e4SLinus Torvalds     { .match_flags = USB_DEVICE_ID_MATCH_INT_CLASS,
53431da177e4SLinus Torvalds       .bInterfaceClass = USB_CLASS_HUB},
53441da177e4SLinus Torvalds     { }						/* Terminating entry */
53451da177e4SLinus Torvalds };
53461da177e4SLinus Torvalds 
53471da177e4SLinus Torvalds MODULE_DEVICE_TABLE(usb, hub_id_table);
53481da177e4SLinus Torvalds 
53491da177e4SLinus Torvalds static struct usb_driver hub_driver = {
53501da177e4SLinus Torvalds 	.name =		"hub",
53511da177e4SLinus Torvalds 	.probe =	hub_probe,
53521da177e4SLinus Torvalds 	.disconnect =	hub_disconnect,
53531da177e4SLinus Torvalds 	.suspend =	hub_suspend,
53541da177e4SLinus Torvalds 	.resume =	hub_resume,
5355f07600cfSAlan Stern 	.reset_resume =	hub_reset_resume,
53567de18d8bSAlan Stern 	.pre_reset =	hub_pre_reset,
53577de18d8bSAlan Stern 	.post_reset =	hub_post_reset,
5358c532b29aSAndi Kleen 	.unlocked_ioctl = hub_ioctl,
53591da177e4SLinus Torvalds 	.id_table =	hub_id_table,
536040f122f3SAlan Stern 	.supports_autosuspend =	1,
53611da177e4SLinus Torvalds };
53621da177e4SLinus Torvalds 
53631da177e4SLinus Torvalds int usb_hub_init(void)
53641da177e4SLinus Torvalds {
53651da177e4SLinus Torvalds 	if (usb_register(&hub_driver) < 0) {
53661da177e4SLinus Torvalds 		printk(KERN_ERR "%s: can't register hub driver\n",
53671da177e4SLinus Torvalds 			usbcore_name);
53681da177e4SLinus Torvalds 		return -1;
53691da177e4SLinus Torvalds 	}
53701da177e4SLinus Torvalds 
537132a69589SPetr Mladek 	/*
537232a69589SPetr Mladek 	 * The workqueue needs to be freezable to avoid interfering with
537332a69589SPetr Mladek 	 * USB-PERSIST port handover. Otherwise it might see that a full-speed
537432a69589SPetr Mladek 	 * device was gone before the EHCI controller had handed its port
537532a69589SPetr Mladek 	 * over to the companion full-speed controller.
537632a69589SPetr Mladek 	 */
5377638139ebSPetr Mladek 	hub_wq = alloc_workqueue("usb_hub_wq", WQ_FREEZABLE, 0);
537832a69589SPetr Mladek 	if (hub_wq)
53791da177e4SLinus Torvalds 		return 0;
53801da177e4SLinus Torvalds 
53811da177e4SLinus Torvalds 	/* Fall through if kernel_thread failed */
53821da177e4SLinus Torvalds 	usb_deregister(&hub_driver);
538332a69589SPetr Mladek 	pr_err("%s: can't allocate workqueue for usb hub\n", usbcore_name);
53841da177e4SLinus Torvalds 
53851da177e4SLinus Torvalds 	return -1;
53861da177e4SLinus Torvalds }
53871da177e4SLinus Torvalds 
53881da177e4SLinus Torvalds void usb_hub_cleanup(void)
53891da177e4SLinus Torvalds {
539032a69589SPetr Mladek 	destroy_workqueue(hub_wq);
53911da177e4SLinus Torvalds 
53921da177e4SLinus Torvalds 	/*
53931da177e4SLinus Torvalds 	 * Hub resources are freed for us by usb_deregister. It calls
53941da177e4SLinus Torvalds 	 * usb_driver_purge on every device which in turn calls that
53951da177e4SLinus Torvalds 	 * devices disconnect function if it is using this driver.
53961da177e4SLinus Torvalds 	 * The hub_disconnect function takes care of releasing the
53971da177e4SLinus Torvalds 	 * individual hub resources. -greg
53981da177e4SLinus Torvalds 	 */
53991da177e4SLinus Torvalds 	usb_deregister(&hub_driver);
54001da177e4SLinus Torvalds } /* usb_hub_cleanup() */
54011da177e4SLinus Torvalds 
5402eb764c4bSAlan Stern static int descriptors_changed(struct usb_device *udev,
5403e3376d6cSXenia Ragiadakou 		struct usb_device_descriptor *old_device_descriptor,
5404e3376d6cSXenia Ragiadakou 		struct usb_host_bos *old_bos)
54051da177e4SLinus Torvalds {
5406eb764c4bSAlan Stern 	int		changed = 0;
54071da177e4SLinus Torvalds 	unsigned	index;
5408eb764c4bSAlan Stern 	unsigned	serial_len = 0;
5409eb764c4bSAlan Stern 	unsigned	len;
5410eb764c4bSAlan Stern 	unsigned	old_length;
5411eb764c4bSAlan Stern 	int		length;
5412eb764c4bSAlan Stern 	char		*buf;
54131da177e4SLinus Torvalds 
5414eb764c4bSAlan Stern 	if (memcmp(&udev->descriptor, old_device_descriptor,
5415eb764c4bSAlan Stern 			sizeof(*old_device_descriptor)) != 0)
5416eb764c4bSAlan Stern 		return 1;
5417eb764c4bSAlan Stern 
5418e3376d6cSXenia Ragiadakou 	if ((old_bos && !udev->bos) || (!old_bos && udev->bos))
5419e3376d6cSXenia Ragiadakou 		return 1;
5420e3376d6cSXenia Ragiadakou 	if (udev->bos) {
5421b9a10481SXenia Ragiadakou 		len = le16_to_cpu(udev->bos->desc->wTotalLength);
5422b9a10481SXenia Ragiadakou 		if (len != le16_to_cpu(old_bos->desc->wTotalLength))
5423e3376d6cSXenia Ragiadakou 			return 1;
5424b9a10481SXenia Ragiadakou 		if (memcmp(udev->bos->desc, old_bos->desc, len))
5425e3376d6cSXenia Ragiadakou 			return 1;
5426e3376d6cSXenia Ragiadakou 	}
5427e3376d6cSXenia Ragiadakou 
5428eb764c4bSAlan Stern 	/* Since the idVendor, idProduct, and bcdDevice values in the
5429eb764c4bSAlan Stern 	 * device descriptor haven't changed, we will assume the
5430eb764c4bSAlan Stern 	 * Manufacturer and Product strings haven't changed either.
5431eb764c4bSAlan Stern 	 * But the SerialNumber string could be different (e.g., a
5432eb764c4bSAlan Stern 	 * different flash card of the same brand).
5433eb764c4bSAlan Stern 	 */
5434eb764c4bSAlan Stern 	if (udev->serial)
5435eb764c4bSAlan Stern 		serial_len = strlen(udev->serial) + 1;
5436eb764c4bSAlan Stern 
5437eb764c4bSAlan Stern 	len = serial_len;
54381da177e4SLinus Torvalds 	for (index = 0; index < udev->descriptor.bNumConfigurations; index++) {
5439eb764c4bSAlan Stern 		old_length = le16_to_cpu(udev->config[index].desc.wTotalLength);
5440eb764c4bSAlan Stern 		len = max(len, old_length);
54411da177e4SLinus Torvalds 	}
5442eb764c4bSAlan Stern 
54430cc1a51fSOliver Neukum 	buf = kmalloc(len, GFP_NOIO);
5444b74e7062SWolfram Sang 	if (!buf)
54451da177e4SLinus Torvalds 		/* assume the worst */
54461da177e4SLinus Torvalds 		return 1;
5447b74e7062SWolfram Sang 
54481da177e4SLinus Torvalds 	for (index = 0; index < udev->descriptor.bNumConfigurations; index++) {
5449eb764c4bSAlan Stern 		old_length = le16_to_cpu(udev->config[index].desc.wTotalLength);
54501da177e4SLinus Torvalds 		length = usb_get_descriptor(udev, USB_DT_CONFIG, index, buf,
54511da177e4SLinus Torvalds 				old_length);
5452eb764c4bSAlan Stern 		if (length != old_length) {
54531da177e4SLinus Torvalds 			dev_dbg(&udev->dev, "config index %d, error %d\n",
54541da177e4SLinus Torvalds 					index, length);
5455eb764c4bSAlan Stern 			changed = 1;
54561da177e4SLinus Torvalds 			break;
54571da177e4SLinus Torvalds 		}
54581da177e4SLinus Torvalds 		if (memcmp(buf, udev->rawdescriptors[index], old_length)
54591da177e4SLinus Torvalds 				!= 0) {
54601da177e4SLinus Torvalds 			dev_dbg(&udev->dev, "config index %d changed (#%d)\n",
5461eb764c4bSAlan Stern 				index,
5462eb764c4bSAlan Stern 				((struct usb_config_descriptor *) buf)->
5463eb764c4bSAlan Stern 					bConfigurationValue);
5464eb764c4bSAlan Stern 			changed = 1;
54651da177e4SLinus Torvalds 			break;
54661da177e4SLinus Torvalds 		}
54671da177e4SLinus Torvalds 	}
5468eb764c4bSAlan Stern 
5469eb764c4bSAlan Stern 	if (!changed && serial_len) {
5470eb764c4bSAlan Stern 		length = usb_string(udev, udev->descriptor.iSerialNumber,
5471eb764c4bSAlan Stern 				buf, serial_len);
5472eb764c4bSAlan Stern 		if (length + 1 != serial_len) {
5473eb764c4bSAlan Stern 			dev_dbg(&udev->dev, "serial string error %d\n",
5474eb764c4bSAlan Stern 					length);
5475eb764c4bSAlan Stern 			changed = 1;
5476eb764c4bSAlan Stern 		} else if (memcmp(buf, udev->serial, length) != 0) {
5477eb764c4bSAlan Stern 			dev_dbg(&udev->dev, "serial string changed\n");
5478eb764c4bSAlan Stern 			changed = 1;
5479eb764c4bSAlan Stern 		}
5480eb764c4bSAlan Stern 	}
5481eb764c4bSAlan Stern 
54821da177e4SLinus Torvalds 	kfree(buf);
5483eb764c4bSAlan Stern 	return changed;
54841da177e4SLinus Torvalds }
54851da177e4SLinus Torvalds 
54861da177e4SLinus Torvalds /**
5487742120c6SMing Lei  * usb_reset_and_verify_device - perform a USB port reset to reinitialize a device
54881da177e4SLinus Torvalds  * @udev: device to reset (not in SUSPENDED or NOTATTACHED state)
54891da177e4SLinus Torvalds  *
549079efa097SAlan Stern  * WARNING - don't use this routine to reset a composite device
549179efa097SAlan Stern  * (one with multiple interfaces owned by separate drivers)!
5492742120c6SMing Lei  * Use usb_reset_device() instead.
54931da177e4SLinus Torvalds  *
54941da177e4SLinus Torvalds  * Do a port reset, reassign the device's address, and establish its
54951da177e4SLinus Torvalds  * former operating configuration.  If the reset fails, or the device's
54961da177e4SLinus Torvalds  * descriptors change from their values before the reset, or the original
54971da177e4SLinus Torvalds  * configuration and altsettings cannot be restored, a flag will be set
549837ebb549SPetr Mladek  * telling hub_wq to pretend the device has been disconnected and then
54991da177e4SLinus Torvalds  * re-connected.  All drivers will be unbound, and the device will be
55001da177e4SLinus Torvalds  * re-enumerated and probed all over again.
55011da177e4SLinus Torvalds  *
5502626f090cSYacine Belkadi  * Return: 0 if the reset succeeded, -ENODEV if the device has been
55031da177e4SLinus Torvalds  * flagged for logical disconnection, or some other negative error code
55041da177e4SLinus Torvalds  * if the reset wasn't even attempted.
55051da177e4SLinus Torvalds  *
5506626f090cSYacine Belkadi  * Note:
55075c79a1e3SDan Williams  * The caller must own the device lock and the port lock, the latter is
55085c79a1e3SDan Williams  * taken by usb_reset_device().  For example, it's safe to use
55095c79a1e3SDan Williams  * usb_reset_device() from a driver probe() routine after downloading
55105c79a1e3SDan Williams  * new firmware.  For calls that might not occur during probe(), drivers
55115c79a1e3SDan Williams  * should lock the device using usb_lock_device_for_reset().
55126bc6cff5SAlan Stern  *
55136bc6cff5SAlan Stern  * Locking exception: This routine may also be called from within an
55146bc6cff5SAlan Stern  * autoresume handler.  Such usage won't conflict with other tasks
55156bc6cff5SAlan Stern  * holding the device lock because these tasks should always call
55165c79a1e3SDan Williams  * usb_autopm_resume_device(), thereby preventing any unwanted
55175c79a1e3SDan Williams  * autoresume.  The autoresume handler is expected to have already
55185c79a1e3SDan Williams  * acquired the port lock before calling this routine.
55191da177e4SLinus Torvalds  */
5520742120c6SMing Lei static int usb_reset_and_verify_device(struct usb_device *udev)
55211da177e4SLinus Torvalds {
55221da177e4SLinus Torvalds 	struct usb_device		*parent_hdev = udev->parent;
55231da177e4SLinus Torvalds 	struct usb_hub			*parent_hub;
55243f0479e0SSarah Sharp 	struct usb_hcd			*hcd = bus_to_hcd(udev->bus);
55251da177e4SLinus Torvalds 	struct usb_device_descriptor	descriptor = udev->descriptor;
5526e3376d6cSXenia Ragiadakou 	struct usb_host_bos		*bos;
55277a7b562dSHans de Goede 	int				i, j, ret = 0;
552812c3da34SAlan Stern 	int				port1 = udev->portnum;
55291da177e4SLinus Torvalds 
55301da177e4SLinus Torvalds 	if (udev->state == USB_STATE_NOTATTACHED ||
55311da177e4SLinus Torvalds 			udev->state == USB_STATE_SUSPENDED) {
55321da177e4SLinus Torvalds 		dev_dbg(&udev->dev, "device reset not allowed in state %d\n",
55331da177e4SLinus Torvalds 				udev->state);
55341da177e4SLinus Torvalds 		return -EINVAL;
55351da177e4SLinus Torvalds 	}
55361da177e4SLinus Torvalds 
55375c79a1e3SDan Williams 	if (!parent_hdev)
55381da177e4SLinus Torvalds 		return -EISDIR;
55395c79a1e3SDan Williams 
5540ad493e5eSLan Tianyu 	parent_hub = usb_hub_to_struct_hub(parent_hdev);
55411da177e4SLinus Torvalds 
5542dcc01c08SSarah Sharp 	/* Disable USB2 hardware LPM.
5543dcc01c08SSarah Sharp 	 * It will be re-enabled by the enumeration process.
5544dcc01c08SSarah Sharp 	 */
5545dcc01c08SSarah Sharp 	if (udev->usb2_hw_lpm_enabled == 1)
5546dcc01c08SSarah Sharp 		usb_set_usb2_hardware_lpm(udev, 0);
5547dcc01c08SSarah Sharp 
554857edd462SMathias Nyman 	/* Disable LPM while we reset the device and reinstall the alt settings.
554957edd462SMathias Nyman 	 * Device-initiated LPM, and system exit latency settings are cleared
555057edd462SMathias Nyman 	 * when the device is reset, so we have to set them up again.
55516d1d0513SSarah Sharp 	 */
55526d1d0513SSarah Sharp 	ret = usb_unlocked_disable_lpm(udev);
55536d1d0513SSarah Sharp 	if (ret) {
55541ccc417eSJoe Perches 		dev_err(&udev->dev, "%s Failed to disable LPM\n", __func__);
5555464ad8c4SHans Yang 		goto re_enumerate_no_bos;
55566d1d0513SSarah Sharp 	}
55576d1d0513SSarah Sharp 
5558464ad8c4SHans Yang 	bos = udev->bos;
5559e5bdfd50SGreg Kroah-Hartman 	udev->bos = NULL;
5560464ad8c4SHans Yang 
55611da177e4SLinus Torvalds 	for (i = 0; i < SET_CONFIG_TRIES; ++i) {
55621da177e4SLinus Torvalds 
55631da177e4SLinus Torvalds 		/* ep0 maxpacket size may change; let the HCD know about it.
55641da177e4SLinus Torvalds 		 * Other endpoints will be handled by re-enumeration. */
5565fc721f51SInaky Perez-Gonzalez 		usb_ep0_reinit(udev);
55661da177e4SLinus Torvalds 		ret = hub_port_init(parent_hub, udev, port1, i);
5567dd4dd19eSAlan Stern 		if (ret >= 0 || ret == -ENOTCONN || ret == -ENODEV)
55681da177e4SLinus Torvalds 			break;
55691da177e4SLinus Torvalds 	}
5570d5cbad4bSAlan Stern 
55711da177e4SLinus Torvalds 	if (ret < 0)
55721da177e4SLinus Torvalds 		goto re_enumerate;
55731da177e4SLinus Torvalds 
55741da177e4SLinus Torvalds 	/* Device might have changed firmware (DFU or similar) */
5575e3376d6cSXenia Ragiadakou 	if (descriptors_changed(udev, &descriptor, bos)) {
55761da177e4SLinus Torvalds 		dev_info(&udev->dev, "device firmware changed\n");
55771da177e4SLinus Torvalds 		udev->descriptor = descriptor;	/* for disconnect() calls */
55781da177e4SLinus Torvalds 		goto re_enumerate;
55791da177e4SLinus Torvalds 	}
55801da177e4SLinus Torvalds 
55814fe0387aSAlan Stern 	/* Restore the device's previous configuration */
55821da177e4SLinus Torvalds 	if (!udev->actconfig)
55831da177e4SLinus Torvalds 		goto done;
55843f0479e0SSarah Sharp 
5585d673bfcbSSarah Sharp 	mutex_lock(hcd->bandwidth_mutex);
55863f0479e0SSarah Sharp 	ret = usb_hcd_alloc_bandwidth(udev, udev->actconfig, NULL, NULL);
55873f0479e0SSarah Sharp 	if (ret < 0) {
55883f0479e0SSarah Sharp 		dev_warn(&udev->dev,
55893f0479e0SSarah Sharp 				"Busted HC?  Not enough HCD resources for "
55903f0479e0SSarah Sharp 				"old configuration.\n");
5591d673bfcbSSarah Sharp 		mutex_unlock(hcd->bandwidth_mutex);
55923f0479e0SSarah Sharp 		goto re_enumerate;
55933f0479e0SSarah Sharp 	}
55941da177e4SLinus Torvalds 	ret = usb_control_msg(udev, usb_sndctrlpipe(udev, 0),
55951da177e4SLinus Torvalds 			USB_REQ_SET_CONFIGURATION, 0,
55961da177e4SLinus Torvalds 			udev->actconfig->desc.bConfigurationValue, 0,
55971da177e4SLinus Torvalds 			NULL, 0, USB_CTRL_SET_TIMEOUT);
55981da177e4SLinus Torvalds 	if (ret < 0) {
55991da177e4SLinus Torvalds 		dev_err(&udev->dev,
56001da177e4SLinus Torvalds 			"can't restore configuration #%d (error=%d)\n",
56011da177e4SLinus Torvalds 			udev->actconfig->desc.bConfigurationValue, ret);
5602d673bfcbSSarah Sharp 		mutex_unlock(hcd->bandwidth_mutex);
56031da177e4SLinus Torvalds 		goto re_enumerate;
56041da177e4SLinus Torvalds 	}
5605d673bfcbSSarah Sharp 	mutex_unlock(hcd->bandwidth_mutex);
56061da177e4SLinus Torvalds 	usb_set_device_state(udev, USB_STATE_CONFIGURED);
56071da177e4SLinus Torvalds 
56084fe0387aSAlan Stern 	/* Put interfaces back into the same altsettings as before.
56094fe0387aSAlan Stern 	 * Don't bother to send the Set-Interface request for interfaces
56104fe0387aSAlan Stern 	 * that were already in altsetting 0; besides being unnecessary,
56114fe0387aSAlan Stern 	 * many devices can't handle it.  Instead just reset the host-side
56124fe0387aSAlan Stern 	 * endpoint state.
56134fe0387aSAlan Stern 	 */
56141da177e4SLinus Torvalds 	for (i = 0; i < udev->actconfig->desc.bNumInterfaces; i++) {
56153f0479e0SSarah Sharp 		struct usb_host_config *config = udev->actconfig;
56163f0479e0SSarah Sharp 		struct usb_interface *intf = config->interface[i];
56171da177e4SLinus Torvalds 		struct usb_interface_descriptor *desc;
56181da177e4SLinus Torvalds 
56191da177e4SLinus Torvalds 		desc = &intf->cur_altsetting->desc;
56204fe0387aSAlan Stern 		if (desc->bAlternateSetting == 0) {
56214fe0387aSAlan Stern 			usb_disable_interface(udev, intf, true);
56224fe0387aSAlan Stern 			usb_enable_interface(udev, intf, true);
56234fe0387aSAlan Stern 			ret = 0;
56244fe0387aSAlan Stern 		} else {
562504a723eaSSarah Sharp 			/* Let the bandwidth allocation function know that this
562604a723eaSSarah Sharp 			 * device has been reset, and it will have to use
562704a723eaSSarah Sharp 			 * alternate setting 0 as the current alternate setting.
56283f0479e0SSarah Sharp 			 */
562904a723eaSSarah Sharp 			intf->resetting_device = 1;
56301da177e4SLinus Torvalds 			ret = usb_set_interface(udev, desc->bInterfaceNumber,
56311da177e4SLinus Torvalds 					desc->bAlternateSetting);
563204a723eaSSarah Sharp 			intf->resetting_device = 0;
56334fe0387aSAlan Stern 		}
56341da177e4SLinus Torvalds 		if (ret < 0) {
56351da177e4SLinus Torvalds 			dev_err(&udev->dev, "failed to restore interface %d "
56361da177e4SLinus Torvalds 				"altsetting %d (error=%d)\n",
56371da177e4SLinus Torvalds 				desc->bInterfaceNumber,
56381da177e4SLinus Torvalds 				desc->bAlternateSetting,
56391da177e4SLinus Torvalds 				ret);
56401da177e4SLinus Torvalds 			goto re_enumerate;
56411da177e4SLinus Torvalds 		}
56427a7b562dSHans de Goede 		/* Resetting also frees any allocated streams */
56437a7b562dSHans de Goede 		for (j = 0; j < intf->cur_altsetting->desc.bNumEndpoints; j++)
56447a7b562dSHans de Goede 			intf->cur_altsetting->endpoint[j].streams = 0;
56451da177e4SLinus Torvalds 	}
56461da177e4SLinus Torvalds 
56471da177e4SLinus Torvalds done:
5648f74631e3SSarah Sharp 	/* Now that the alt settings are re-installed, enable LTM and LPM. */
5649de68bab4SSarah Sharp 	usb_set_usb2_hardware_lpm(udev, 1);
565078d9a487SAlan Stern 	usb_unlocked_enable_lpm(udev);
5651f74631e3SSarah Sharp 	usb_enable_ltm(udev);
5652e3376d6cSXenia Ragiadakou 	usb_release_bos_descriptor(udev);
5653e3376d6cSXenia Ragiadakou 	udev->bos = bos;
56541da177e4SLinus Torvalds 	return 0;
56551da177e4SLinus Torvalds 
56561da177e4SLinus Torvalds re_enumerate:
5657e3376d6cSXenia Ragiadakou 	usb_release_bos_descriptor(udev);
5658e3376d6cSXenia Ragiadakou 	udev->bos = bos;
5659464ad8c4SHans Yang re_enumerate_no_bos:
5660464ad8c4SHans Yang 	/* LPM state doesn't matter when we're about to destroy the device. */
5661464ad8c4SHans Yang 	hub_port_logical_disconnect(parent_hub, port1);
56621da177e4SLinus Torvalds 	return -ENODEV;
56631da177e4SLinus Torvalds }
56641da177e4SLinus Torvalds 
56651da177e4SLinus Torvalds /**
56661da177e4SLinus Torvalds  * usb_reset_device - warn interface drivers and perform a USB port reset
56671da177e4SLinus Torvalds  * @udev: device to reset (not in SUSPENDED or NOTATTACHED state)
56681da177e4SLinus Torvalds  *
566979efa097SAlan Stern  * Warns all drivers bound to registered interfaces (using their pre_reset
567079efa097SAlan Stern  * method), performs the port reset, and then lets the drivers know that
5671742120c6SMing Lei  * the reset is over (using their post_reset method).
567279efa097SAlan Stern  *
5673626f090cSYacine Belkadi  * Return: The same as for usb_reset_and_verify_device().
567479efa097SAlan Stern  *
5675626f090cSYacine Belkadi  * Note:
567679efa097SAlan Stern  * The caller must own the device lock.  For example, it's safe to use
567779efa097SAlan Stern  * this from a driver probe() routine after downloading new firmware.
567879efa097SAlan Stern  * For calls that might not occur during probe(), drivers should lock
5679742120c6SMing Lei  * the device using usb_lock_device_for_reset().
568079efa097SAlan Stern  *
568179efa097SAlan Stern  * If an interface is currently being probed or disconnected, we assume
568279efa097SAlan Stern  * its driver knows how to handle resets.  For all other interfaces,
568379efa097SAlan Stern  * if the driver doesn't have pre_reset and post_reset methods then
568479efa097SAlan Stern  * we attempt to unbind it and rebind afterward.
568579efa097SAlan Stern  */
5686742120c6SMing Lei int usb_reset_device(struct usb_device *udev)
568779efa097SAlan Stern {
568879efa097SAlan Stern 	int ret;
5689852c4b43SAlan Stern 	int i;
56904d769defSMing Lei 	unsigned int noio_flag;
56915c79a1e3SDan Williams 	struct usb_port *port_dev;
569279efa097SAlan Stern 	struct usb_host_config *config = udev->actconfig;
56935c79a1e3SDan Williams 	struct usb_hub *hub = usb_hub_to_struct_hub(udev->parent);
569479efa097SAlan Stern 
569579efa097SAlan Stern 	if (udev->state == USB_STATE_NOTATTACHED ||
569679efa097SAlan Stern 			udev->state == USB_STATE_SUSPENDED) {
569779efa097SAlan Stern 		dev_dbg(&udev->dev, "device reset not allowed in state %d\n",
569879efa097SAlan Stern 				udev->state);
569979efa097SAlan Stern 		return -EINVAL;
570079efa097SAlan Stern 	}
570179efa097SAlan Stern 
57025c79a1e3SDan Williams 	if (!udev->parent) {
57035c79a1e3SDan Williams 		/* this requires hcd-specific logic; see ohci_restart() */
57045c79a1e3SDan Williams 		dev_dbg(&udev->dev, "%s for root hub!\n", __func__);
57055c79a1e3SDan Williams 		return -EISDIR;
57065c79a1e3SDan Williams 	}
57075c79a1e3SDan Williams 
57085c79a1e3SDan Williams 	port_dev = hub->ports[udev->portnum - 1];
57095c79a1e3SDan Williams 
57104d769defSMing Lei 	/*
57114d769defSMing Lei 	 * Don't allocate memory with GFP_KERNEL in current
57124d769defSMing Lei 	 * context to avoid possible deadlock if usb mass
57134d769defSMing Lei 	 * storage interface or usbnet interface(iSCSI case)
57144d769defSMing Lei 	 * is included in current configuration. The easist
57154d769defSMing Lei 	 * approach is to do it for every device reset,
57164d769defSMing Lei 	 * because the device 'memalloc_noio' flag may have
57174d769defSMing Lei 	 * not been set before reseting the usb device.
57184d769defSMing Lei 	 */
57194d769defSMing Lei 	noio_flag = memalloc_noio_save();
57204d769defSMing Lei 
5721645daaabSAlan Stern 	/* Prevent autosuspend during the reset */
572294fcda1fSAlan Stern 	usb_autoresume_device(udev);
5723645daaabSAlan Stern 
572479efa097SAlan Stern 	if (config) {
5725852c4b43SAlan Stern 		for (i = 0; i < config->desc.bNumInterfaces; ++i) {
5726852c4b43SAlan Stern 			struct usb_interface *cintf = config->interface[i];
572779efa097SAlan Stern 			struct usb_driver *drv;
572878d9a487SAlan Stern 			int unbind = 0;
572979efa097SAlan Stern 
5730852c4b43SAlan Stern 			if (cintf->dev.driver) {
573179efa097SAlan Stern 				drv = to_usb_driver(cintf->dev.driver);
573278d9a487SAlan Stern 				if (drv->pre_reset && drv->post_reset)
573378d9a487SAlan Stern 					unbind = (drv->pre_reset)(cintf);
573478d9a487SAlan Stern 				else if (cintf->condition ==
573578d9a487SAlan Stern 						USB_INTERFACE_BOUND)
573678d9a487SAlan Stern 					unbind = 1;
573778d9a487SAlan Stern 				if (unbind)
573878d9a487SAlan Stern 					usb_forced_unbind_intf(cintf);
573979efa097SAlan Stern 			}
574079efa097SAlan Stern 		}
574179efa097SAlan Stern 	}
574279efa097SAlan Stern 
57435c79a1e3SDan Williams 	usb_lock_port(port_dev);
5744742120c6SMing Lei 	ret = usb_reset_and_verify_device(udev);
57455c79a1e3SDan Williams 	usb_unlock_port(port_dev);
574679efa097SAlan Stern 
574779efa097SAlan Stern 	if (config) {
5748852c4b43SAlan Stern 		for (i = config->desc.bNumInterfaces - 1; i >= 0; --i) {
5749852c4b43SAlan Stern 			struct usb_interface *cintf = config->interface[i];
575079efa097SAlan Stern 			struct usb_driver *drv;
575178d9a487SAlan Stern 			int rebind = cintf->needs_binding;
575279efa097SAlan Stern 
575378d9a487SAlan Stern 			if (!rebind && cintf->dev.driver) {
575479efa097SAlan Stern 				drv = to_usb_driver(cintf->dev.driver);
575579efa097SAlan Stern 				if (drv->post_reset)
575678d9a487SAlan Stern 					rebind = (drv->post_reset)(cintf);
575778d9a487SAlan Stern 				else if (cintf->condition ==
575878d9a487SAlan Stern 						USB_INTERFACE_BOUND)
575978d9a487SAlan Stern 					rebind = 1;
57606aec044cSAlan Stern 				if (rebind)
57616aec044cSAlan Stern 					cintf->needs_binding = 1;
576279efa097SAlan Stern 			}
576379efa097SAlan Stern 		}
57646aec044cSAlan Stern 		usb_unbind_and_rebind_marked_interfaces(udev);
576579efa097SAlan Stern 	}
576679efa097SAlan Stern 
576794fcda1fSAlan Stern 	usb_autosuspend_device(udev);
57684d769defSMing Lei 	memalloc_noio_restore(noio_flag);
576979efa097SAlan Stern 	return ret;
577079efa097SAlan Stern }
5771742120c6SMing Lei EXPORT_SYMBOL_GPL(usb_reset_device);
5772dc023dceSInaky Perez-Gonzalez 
5773dc023dceSInaky Perez-Gonzalez 
5774dc023dceSInaky Perez-Gonzalez /**
5775dc023dceSInaky Perez-Gonzalez  * usb_queue_reset_device - Reset a USB device from an atomic context
5776dc023dceSInaky Perez-Gonzalez  * @iface: USB interface belonging to the device to reset
5777dc023dceSInaky Perez-Gonzalez  *
5778dc023dceSInaky Perez-Gonzalez  * This function can be used to reset a USB device from an atomic
5779dc023dceSInaky Perez-Gonzalez  * context, where usb_reset_device() won't work (as it blocks).
5780dc023dceSInaky Perez-Gonzalez  *
5781dc023dceSInaky Perez-Gonzalez  * Doing a reset via this method is functionally equivalent to calling
5782dc023dceSInaky Perez-Gonzalez  * usb_reset_device(), except for the fact that it is delayed to a
5783dc023dceSInaky Perez-Gonzalez  * workqueue. This means that any drivers bound to other interfaces
5784dc023dceSInaky Perez-Gonzalez  * might be unbound, as well as users from usbfs in user space.
5785dc023dceSInaky Perez-Gonzalez  *
5786dc023dceSInaky Perez-Gonzalez  * Corner cases:
5787dc023dceSInaky Perez-Gonzalez  *
5788dc023dceSInaky Perez-Gonzalez  * - Scheduling two resets at the same time from two different drivers
5789dc023dceSInaky Perez-Gonzalez  *   attached to two different interfaces of the same device is
5790dc023dceSInaky Perez-Gonzalez  *   possible; depending on how the driver attached to each interface
5791dc023dceSInaky Perez-Gonzalez  *   handles ->pre_reset(), the second reset might happen or not.
5792dc023dceSInaky Perez-Gonzalez  *
5793524134d4SAlan Stern  * - If the reset is delayed so long that the interface is unbound from
5794524134d4SAlan Stern  *   its driver, the reset will be skipped.
5795dc023dceSInaky Perez-Gonzalez  *
5796524134d4SAlan Stern  * - This function can be called during .probe().  It can also be called
5797524134d4SAlan Stern  *   during .disconnect(), but doing so is pointless because the reset
5798524134d4SAlan Stern  *   will not occur.  If you really want to reset the device during
5799524134d4SAlan Stern  *   .disconnect(), call usb_reset_device() directly -- but watch out
5800524134d4SAlan Stern  *   for nested unbinding issues!
5801dc023dceSInaky Perez-Gonzalez  */
5802dc023dceSInaky Perez-Gonzalez void usb_queue_reset_device(struct usb_interface *iface)
5803dc023dceSInaky Perez-Gonzalez {
5804524134d4SAlan Stern 	if (schedule_work(&iface->reset_ws))
5805524134d4SAlan Stern 		usb_get_intf(iface);
5806dc023dceSInaky Perez-Gonzalez }
5807dc023dceSInaky Perez-Gonzalez EXPORT_SYMBOL_GPL(usb_queue_reset_device);
5808ff823c79SLan Tianyu 
5809ff823c79SLan Tianyu /**
5810ff823c79SLan Tianyu  * usb_hub_find_child - Get the pointer of child device
5811ff823c79SLan Tianyu  * attached to the port which is specified by @port1.
5812ff823c79SLan Tianyu  * @hdev: USB device belonging to the usb hub
5813ff823c79SLan Tianyu  * @port1: port num to indicate which port the child device
5814ff823c79SLan Tianyu  *	is attached to.
5815ff823c79SLan Tianyu  *
5816ff823c79SLan Tianyu  * USB drivers call this function to get hub's child device
5817ff823c79SLan Tianyu  * pointer.
5818ff823c79SLan Tianyu  *
5819626f090cSYacine Belkadi  * Return: %NULL if input param is invalid and
5820ff823c79SLan Tianyu  * child's usb_device pointer if non-NULL.
5821ff823c79SLan Tianyu  */
5822ff823c79SLan Tianyu struct usb_device *usb_hub_find_child(struct usb_device *hdev,
5823ff823c79SLan Tianyu 		int port1)
5824ff823c79SLan Tianyu {
5825ad493e5eSLan Tianyu 	struct usb_hub *hub = usb_hub_to_struct_hub(hdev);
5826ff823c79SLan Tianyu 
5827ff823c79SLan Tianyu 	if (port1 < 1 || port1 > hdev->maxchild)
5828ff823c79SLan Tianyu 		return NULL;
5829ff823c79SLan Tianyu 	return hub->ports[port1 - 1]->child;
5830ff823c79SLan Tianyu }
5831ff823c79SLan Tianyu EXPORT_SYMBOL_GPL(usb_hub_find_child);
5832d5575424SLan Tianyu 
5833d2123fd9SLan Tianyu void usb_hub_adjust_deviceremovable(struct usb_device *hdev,
5834d2123fd9SLan Tianyu 		struct usb_hub_descriptor *desc)
5835d2123fd9SLan Tianyu {
5836d99f6b41SDan Williams 	struct usb_hub *hub = usb_hub_to_struct_hub(hdev);
5837d2123fd9SLan Tianyu 	enum usb_port_connect_type connect_type;
5838d2123fd9SLan Tianyu 	int i;
5839d2123fd9SLan Tianyu 
5840d99f6b41SDan Williams 	if (!hub)
5841d99f6b41SDan Williams 		return;
5842d99f6b41SDan Williams 
5843d2123fd9SLan Tianyu 	if (!hub_is_superspeed(hdev)) {
5844d2123fd9SLan Tianyu 		for (i = 1; i <= hdev->maxchild; i++) {
5845d99f6b41SDan Williams 			struct usb_port *port_dev = hub->ports[i - 1];
5846d2123fd9SLan Tianyu 
5847d99f6b41SDan Williams 			connect_type = port_dev->connect_type;
5848d2123fd9SLan Tianyu 			if (connect_type == USB_PORT_CONNECT_TYPE_HARD_WIRED) {
5849d2123fd9SLan Tianyu 				u8 mask = 1 << (i%8);
5850d2123fd9SLan Tianyu 
5851d2123fd9SLan Tianyu 				if (!(desc->u.hs.DeviceRemovable[i/8] & mask)) {
5852d99f6b41SDan Williams 					dev_dbg(&port_dev->dev, "DeviceRemovable is changed to 1 according to platform information.\n");
5853d2123fd9SLan Tianyu 					desc->u.hs.DeviceRemovable[i/8]	|= mask;
5854d2123fd9SLan Tianyu 				}
5855d2123fd9SLan Tianyu 			}
5856d2123fd9SLan Tianyu 		}
5857d2123fd9SLan Tianyu 	} else {
5858d2123fd9SLan Tianyu 		u16 port_removable = le16_to_cpu(desc->u.ss.DeviceRemovable);
5859d2123fd9SLan Tianyu 
5860d2123fd9SLan Tianyu 		for (i = 1; i <= hdev->maxchild; i++) {
5861d99f6b41SDan Williams 			struct usb_port *port_dev = hub->ports[i - 1];
5862d2123fd9SLan Tianyu 
5863d99f6b41SDan Williams 			connect_type = port_dev->connect_type;
5864d2123fd9SLan Tianyu 			if (connect_type == USB_PORT_CONNECT_TYPE_HARD_WIRED) {
5865d2123fd9SLan Tianyu 				u16 mask = 1 << i;
5866d2123fd9SLan Tianyu 
5867d2123fd9SLan Tianyu 				if (!(port_removable & mask)) {
5868d99f6b41SDan Williams 					dev_dbg(&port_dev->dev, "DeviceRemovable is changed to 1 according to platform information.\n");
5869d2123fd9SLan Tianyu 					port_removable |= mask;
5870d2123fd9SLan Tianyu 				}
5871d2123fd9SLan Tianyu 			}
5872d2123fd9SLan Tianyu 		}
5873d2123fd9SLan Tianyu 
5874d2123fd9SLan Tianyu 		desc->u.ss.DeviceRemovable = cpu_to_le16(port_removable);
5875d2123fd9SLan Tianyu 	}
5876d2123fd9SLan Tianyu }
5877d2123fd9SLan Tianyu 
5878d5575424SLan Tianyu #ifdef CONFIG_ACPI
5879d5575424SLan Tianyu /**
5880d5575424SLan Tianyu  * usb_get_hub_port_acpi_handle - Get the usb port's acpi handle
5881d5575424SLan Tianyu  * @hdev: USB device belonging to the usb hub
5882d5575424SLan Tianyu  * @port1: port num of the port
5883d5575424SLan Tianyu  *
5884626f090cSYacine Belkadi  * Return: Port's acpi handle if successful, %NULL if params are
5885626f090cSYacine Belkadi  * invalid.
5886d5575424SLan Tianyu  */
5887d5575424SLan Tianyu acpi_handle usb_get_hub_port_acpi_handle(struct usb_device *hdev,
5888d5575424SLan Tianyu 	int port1)
5889d5575424SLan Tianyu {
5890ad493e5eSLan Tianyu 	struct usb_hub *hub = usb_hub_to_struct_hub(hdev);
5891d5575424SLan Tianyu 
589241341261SMathias Nyman 	if (!hub)
589341341261SMathias Nyman 		return NULL;
589441341261SMathias Nyman 
58953a83f992SRafael J. Wysocki 	return ACPI_HANDLE(&hub->ports[port1 - 1]->dev);
5896d5575424SLan Tianyu }
5897d5575424SLan Tianyu #endif
5898