File Index
Files and directories
Sign in
FILE

hub.c

File preview with syntax highlighting.

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