1 // SPDX-License-Identifier: GPL-2.0
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)
10 * Released under the GPLv2 only.
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/mutex.h>
32 #include <linux/random.h>
33 #include <linux/pm_qos.h>
34 #include <linux/kobject.h>
36 #include <linux/bitfield.h>
37 #include <linux/uaccess.h>
38 #include <asm/byteorder.h>
42 #include "otg_productlist.h"
44 #define USB_VENDOR_GENESYS_LOGIC 0x05e3
45 #define USB_VENDOR_SMSC 0x0424
46 #define USB_PRODUCT_USB5534B 0x5534
47 #define USB_VENDOR_CYPRESS 0x04b4
48 #define USB_PRODUCT_CY7C65632 0x6570
49 #define USB_VENDOR_TEXAS_INSTRUMENTS 0x0451
50 #define USB_PRODUCT_TUSB8041_USB3 0x8140
51 #define USB_PRODUCT_TUSB8041_USB2 0x8142
52 #define USB_VENDOR_MICROCHIP 0x0424
53 #define USB_PRODUCT_USB4913 0x4913
54 #define USB_PRODUCT_USB4914 0x4914
55 #define USB_PRODUCT_USB4915 0x4915
56 #define HUB_QUIRK_CHECK_PORT_AUTOSUSPEND BIT(0)
57 #define HUB_QUIRK_DISABLE_AUTOSUSPEND BIT(1)
58 #define HUB_QUIRK_REDUCE_FRAME_INTR_BINTERVAL BIT(2)
60 #define USB_TP_TRANSMISSION_DELAY 40 /* ns */
61 #define USB_TP_TRANSMISSION_DELAY_MAX 65535 /* ns */
62 #define USB_PING_RESPONSE_TIME 400 /* ns */
63 #define USB_REDUCE_FRAME_INTR_BINTERVAL 9
66 * The SET_ADDRESS request timeout will be 500 ms when
67 * USB_QUIRK_SHORT_SET_ADDRESS_REQ_TIMEOUT quirk flag is set.
69 #define USB_SHORT_SET_ADDRESS_REQ_TIMEOUT 500 /* ms */
72 * Give SS hubs 200ms time after wake to train downstream links before
73 * assuming no port activity and allowing hub to runtime suspend back.
75 #define USB_SS_PORT_U0_WAKE_TIME 200 /* ms */
77 /* Protect struct usb_device->state and ->children members
78 * Note: Both are also protected by ->dev.sem, except that ->state can
79 * change to USB_STATE_NOTATTACHED even when the semaphore isn't held. */
80 static DEFINE_SPINLOCK(device_state_lock);
82 /* workqueue to process hub events */
83 static struct workqueue_struct *hub_wq;
84 static void hub_event(struct work_struct *work);
86 /* synchronize hub-port add/remove and peering operations */
87 DEFINE_MUTEX(usb_port_peer_mutex);
89 /* cycle leds on hubs that aren't blinking for attention */
90 static bool blinkenlights;
91 module_param(blinkenlights, bool, S_IRUGO);
92 MODULE_PARM_DESC(blinkenlights, "true to cycle leds on hubs");
95 * Device SATA8000 FW1.0 from DATAST0R Technology Corp requires about
96 * 10 seconds to send reply for the initial 64-byte descriptor request.
98 /* define initial 64-byte descriptor request timeout in milliseconds */
99 static int initial_descriptor_timeout = USB_CTRL_GET_TIMEOUT;
100 module_param(initial_descriptor_timeout, int, S_IRUGO|S_IWUSR);
101 MODULE_PARM_DESC(initial_descriptor_timeout,
102 "initial 64-byte descriptor request timeout in milliseconds "
103 "(default 5000 - 5.0 seconds)");
106 * As of 2.6.10 we introduce a new USB device initialization scheme which
107 * closely resembles the way Windows works. Hopefully it will be compatible
108 * with a wider range of devices than the old scheme. However some previously
109 * working devices may start giving rise to "device not accepting address"
110 * errors; if that happens the user can try the old scheme by adjusting the
111 * following module parameters.
113 * For maximum flexibility there are two boolean parameters to control the
114 * hub driver's behavior. On the first initialization attempt, if the
115 * "old_scheme_first" parameter is set then the old scheme will be used,
116 * otherwise the new scheme is used. If that fails and "use_both_schemes"
117 * is set, then the driver will make another attempt, using the other scheme.
119 static bool old_scheme_first;
120 module_param(old_scheme_first, bool, S_IRUGO | S_IWUSR);
121 MODULE_PARM_DESC(old_scheme_first,
122 "start with the old device initialization scheme");
124 static bool use_both_schemes = true;
125 module_param(use_both_schemes, bool, S_IRUGO | S_IWUSR);
126 MODULE_PARM_DESC(use_both_schemes,
127 "try the other device initialization scheme if the "
130 /* Mutual exclusion for EHCI CF initialization. This interferes with
131 * port reset on some companion controllers.
133 DECLARE_RWSEM(ehci_cf_port_reset_rwsem);
134 EXPORT_SYMBOL_GPL(ehci_cf_port_reset_rwsem);
136 #define HUB_DEBOUNCE_TIMEOUT 2000
137 #define HUB_DEBOUNCE_STEP 25
138 #define HUB_DEBOUNCE_STABLE 100
140 static int usb_reset_and_verify_device(struct usb_device *udev);
141 static int hub_port_disable(struct usb_hub *hub, int port1, int set_state);
142 static bool hub_port_warm_reset_required(struct usb_hub *hub, int port1,
145 static inline char *portspeed(struct usb_hub *hub, int portstatus)
147 if (hub_is_superspeedplus(hub->hdev))
149 if (hub_is_superspeed(hub->hdev))
151 if (portstatus & USB_PORT_STAT_HIGH_SPEED)
153 else if (portstatus & USB_PORT_STAT_LOW_SPEED)
159 /* Note that hdev or one of its children must be locked! */
160 struct usb_hub *usb_hub_to_struct_hub(struct usb_device *hdev)
162 if (!hdev || !hdev->actconfig || !hdev->maxchild)
164 return usb_get_intfdata(hdev->actconfig->interface[0]);
167 int usb_device_supports_lpm(struct usb_device *udev)
169 /* Some devices have trouble with LPM */
170 if (udev->quirks & USB_QUIRK_NO_LPM)
173 /* Skip if the device BOS descriptor couldn't be read */
177 /* USB 2.1 (and greater) devices indicate LPM support through
178 * their USB 2.0 Extended Capabilities BOS descriptor.
180 if (udev->speed == USB_SPEED_HIGH || udev->speed == USB_SPEED_FULL) {
181 if (udev->bos->ext_cap &&
183 le32_to_cpu(udev->bos->ext_cap->bmAttributes)))
189 * According to the USB 3.0 spec, all USB 3.0 devices must support LPM.
190 * However, there are some that don't, and they set the U1/U2 exit
193 if (!udev->bos->ss_cap) {
194 dev_info(&udev->dev, "No LPM exit latency info found, disabling LPM.\n");
198 if (udev->bos->ss_cap->bU1devExitLat == 0 &&
199 udev->bos->ss_cap->bU2DevExitLat == 0) {
201 dev_info(&udev->dev, "LPM exit latency is zeroed, disabling LPM.\n");
203 dev_info(&udev->dev, "We don't know the algorithms for LPM for this host, disabling LPM.\n");
207 if (!udev->parent || udev->parent->lpm_capable)
213 * Set the Maximum Exit Latency (MEL) for the host to wakup up the path from
214 * U1/U2, send a PING to the device and receive a PING_RESPONSE.
215 * See USB 3.1 section C.1.5.2
217 static void usb_set_lpm_mel(struct usb_device *udev,
218 struct usb3_lpm_parameters *udev_lpm_params,
219 unsigned int udev_exit_latency,
221 struct usb3_lpm_parameters *hub_lpm_params,
222 unsigned int hub_exit_latency)
224 unsigned int total_mel;
227 * tMEL1. time to transition path from host to device into U0.
228 * MEL for parent already contains the delay up to parent, so only add
229 * the exit latency for the last link (pick the slower exit latency),
230 * and the hub header decode latency. See USB 3.1 section C 2.2.1
231 * Store MEL in nanoseconds
233 total_mel = hub_lpm_params->mel +
234 max(udev_exit_latency, hub_exit_latency) * 1000 +
235 hub->descriptor->u.ss.bHubHdrDecLat * 100;
238 * tMEL2. Time to submit PING packet. Sum of tTPTransmissionDelay for
239 * each link + wHubDelay for each hub. Add only for last link.
240 * tMEL4, the time for PING_RESPONSE to traverse upstream is similar.
241 * Multiply by 2 to include it as well.
243 total_mel += (__le16_to_cpu(hub->descriptor->u.ss.wHubDelay) +
244 USB_TP_TRANSMISSION_DELAY) * 2;
247 * tMEL3, tPingResponse. Time taken by device to generate PING_RESPONSE
248 * after receiving PING. Also add 2100ns as stated in USB 3.1 C 1.5.2.4
249 * to cover the delay if the PING_RESPONSE is queued behind a Max Packet
251 * Note these delays should be added only once for the entire path, so
252 * add them to the MEL of the device connected to the roothub.
254 if (!hub->hdev->parent)
255 total_mel += USB_PING_RESPONSE_TIME + 2100;
257 udev_lpm_params->mel = total_mel;
261 * Set the maximum Device to Host Exit Latency (PEL) for the device to initiate
262 * a transition from either U1 or U2.
264 static void usb_set_lpm_pel(struct usb_device *udev,
265 struct usb3_lpm_parameters *udev_lpm_params,
266 unsigned int udev_exit_latency,
268 struct usb3_lpm_parameters *hub_lpm_params,
269 unsigned int hub_exit_latency,
270 unsigned int port_to_port_exit_latency)
272 unsigned int first_link_pel;
273 unsigned int hub_pel;
276 * First, the device sends an LFPS to transition the link between the
277 * device and the parent hub into U0. The exit latency is the bigger of
278 * the device exit latency or the hub exit latency.
280 if (udev_exit_latency > hub_exit_latency)
281 first_link_pel = udev_exit_latency * 1000;
283 first_link_pel = hub_exit_latency * 1000;
286 * When the hub starts to receive the LFPS, there is a slight delay for
287 * it to figure out that one of the ports is sending an LFPS. Then it
288 * will forward the LFPS to its upstream link. The exit latency is the
289 * delay, plus the PEL that we calculated for this hub.
291 hub_pel = port_to_port_exit_latency * 1000 + hub_lpm_params->pel;
294 * According to figure C-7 in the USB 3.0 spec, the PEL for this device
295 * is the greater of the two exit latencies.
297 if (first_link_pel > hub_pel)
298 udev_lpm_params->pel = first_link_pel;
300 udev_lpm_params->pel = hub_pel;
304 * Set the System Exit Latency (SEL) to indicate the total worst-case time from
305 * when a device initiates a transition to U0, until when it will receive the
306 * first packet from the host controller.
308 * Section C.1.5.1 describes the four components to this:
310 * - t2: time for the ERDY to make it from the device to the host.
311 * - t3: a host-specific delay to process the ERDY.
312 * - t4: time for the packet to make it from the host to the device.
314 * t3 is specific to both the xHCI host and the platform the host is integrated
315 * into. The Intel HW folks have said it's negligible, FIXME if a different
316 * vendor says otherwise.
318 static void usb_set_lpm_sel(struct usb_device *udev,
319 struct usb3_lpm_parameters *udev_lpm_params)
321 struct usb_device *parent;
322 unsigned int num_hubs;
323 unsigned int total_sel;
325 /* t1 = device PEL */
326 total_sel = udev_lpm_params->pel;
327 /* How many external hubs are in between the device & the root port. */
328 for (parent = udev->parent, num_hubs = 0; parent->parent;
329 parent = parent->parent)
331 /* t2 = 2.1us + 250ns * (num_hubs - 1) */
333 total_sel += 2100 + 250 * (num_hubs - 1);
335 /* t4 = 250ns * num_hubs */
336 total_sel += 250 * num_hubs;
338 udev_lpm_params->sel = total_sel;
341 static void usb_set_lpm_parameters(struct usb_device *udev)
344 unsigned int port_to_port_delay;
345 unsigned int udev_u1_del;
346 unsigned int udev_u2_del;
347 unsigned int hub_u1_del;
348 unsigned int hub_u2_del;
350 if (!udev->lpm_capable || udev->speed < USB_SPEED_SUPER)
353 /* Skip if the device BOS descriptor couldn't be read */
357 hub = usb_hub_to_struct_hub(udev->parent);
358 /* It doesn't take time to transition the roothub into U0, since it
359 * doesn't have an upstream link.
364 udev_u1_del = udev->bos->ss_cap->bU1devExitLat;
365 udev_u2_del = le16_to_cpu(udev->bos->ss_cap->bU2DevExitLat);
366 hub_u1_del = udev->parent->bos->ss_cap->bU1devExitLat;
367 hub_u2_del = le16_to_cpu(udev->parent->bos->ss_cap->bU2DevExitLat);
369 usb_set_lpm_mel(udev, &udev->u1_params, udev_u1_del,
370 hub, &udev->parent->u1_params, hub_u1_del);
372 usb_set_lpm_mel(udev, &udev->u2_params, udev_u2_del,
373 hub, &udev->parent->u2_params, hub_u2_del);
376 * Appendix C, section C.2.2.2, says that there is a slight delay from
377 * when the parent hub notices the downstream port is trying to
378 * transition to U0 to when the hub initiates a U0 transition on its
379 * upstream port. The section says the delays are tPort2PortU1EL and
380 * tPort2PortU2EL, but it doesn't define what they are.
382 * The hub chapter, sections 10.4.2.4 and 10.4.2.5 seem to be talking
383 * about the same delays. Use the maximum delay calculations from those
384 * sections. For U1, it's tHubPort2PortExitLat, which is 1us max. For
385 * U2, it's tHubPort2PortExitLat + U2DevExitLat - U1DevExitLat. I
386 * assume the device exit latencies they are talking about are the hub
389 * What do we do if the U2 exit latency is less than the U1 exit
390 * latency? It's possible, although not likely...
392 port_to_port_delay = 1;
394 usb_set_lpm_pel(udev, &udev->u1_params, udev_u1_del,
395 hub, &udev->parent->u1_params, hub_u1_del,
398 if (hub_u2_del > hub_u1_del)
399 port_to_port_delay = 1 + hub_u2_del - hub_u1_del;
401 port_to_port_delay = 1 + hub_u1_del;
403 usb_set_lpm_pel(udev, &udev->u2_params, udev_u2_del,
404 hub, &udev->parent->u2_params, hub_u2_del,
407 /* Now that we've got PEL, calculate SEL. */
408 usb_set_lpm_sel(udev, &udev->u1_params);
409 usb_set_lpm_sel(udev, &udev->u2_params);
412 /* USB 2.0 spec Section 11.24.4.5 */
413 static int get_hub_descriptor(struct usb_device *hdev,
414 struct usb_hub_descriptor *desc)
419 if (hub_is_superspeed(hdev)) {
420 dtype = USB_DT_SS_HUB;
421 size = USB_DT_SS_HUB_SIZE;
424 size = sizeof(struct usb_hub_descriptor);
427 for (i = 0; i < 3; i++) {
428 ret = usb_control_msg(hdev, usb_rcvctrlpipe(hdev, 0),
429 USB_REQ_GET_DESCRIPTOR, USB_DIR_IN | USB_RT_HUB,
430 dtype << 8, 0, desc, size,
431 USB_CTRL_GET_TIMEOUT);
432 if (hub_is_superspeed(hdev)) {
435 } else if (ret >= USB_DT_HUB_NONVAR_SIZE + 2) {
436 /* Make sure we have the DeviceRemovable field. */
437 size = USB_DT_HUB_NONVAR_SIZE + desc->bNbrPorts / 8 + 1;
447 * USB 2.0 spec Section 11.24.2.1
449 static int clear_hub_feature(struct usb_device *hdev, int feature)
451 return usb_control_msg(hdev, usb_sndctrlpipe(hdev, 0),
452 USB_REQ_CLEAR_FEATURE, USB_RT_HUB, feature, 0, NULL, 0, 1000);
456 * USB 2.0 spec Section 11.24.2.2
458 int usb_clear_port_feature(struct usb_device *hdev, int port1, int feature)
460 return usb_control_msg(hdev, usb_sndctrlpipe(hdev, 0),
461 USB_REQ_CLEAR_FEATURE, USB_RT_PORT, feature, port1,
466 * USB 2.0 spec Section 11.24.2.13
468 static int set_port_feature(struct usb_device *hdev, int port1, int feature)
470 return usb_control_msg(hdev, usb_sndctrlpipe(hdev, 0),
471 USB_REQ_SET_FEATURE, USB_RT_PORT, feature, port1,
475 static char *to_led_name(int selector)
492 * USB 2.0 spec Section 11.24.2.7.1.10 and table 11-7
493 * for info about using port indicators
495 static void set_port_led(struct usb_hub *hub, int port1, int selector)
497 struct usb_port *port_dev = hub->ports[port1 - 1];
500 status = set_port_feature(hub->hdev, (selector << 8) | port1,
501 USB_PORT_FEAT_INDICATOR);
502 dev_dbg(&port_dev->dev, "indicator %s status %d\n",
503 to_led_name(selector), status);
506 #define LED_CYCLE_PERIOD ((2*HZ)/3)
508 static void led_work(struct work_struct *work)
510 struct usb_hub *hub =
511 container_of(work, struct usb_hub, leds.work);
512 struct usb_device *hdev = hub->hdev;
514 unsigned changed = 0;
517 if (hdev->state != USB_STATE_CONFIGURED || hub->quiescing)
520 for (i = 0; i < hdev->maxchild; i++) {
521 unsigned selector, mode;
523 /* 30%-50% duty cycle */
525 switch (hub->indicator[i]) {
527 case INDICATOR_CYCLE:
529 selector = HUB_LED_AUTO;
530 mode = INDICATOR_AUTO;
532 /* blinking green = sw attention */
533 case INDICATOR_GREEN_BLINK:
534 selector = HUB_LED_GREEN;
535 mode = INDICATOR_GREEN_BLINK_OFF;
537 case INDICATOR_GREEN_BLINK_OFF:
538 selector = HUB_LED_OFF;
539 mode = INDICATOR_GREEN_BLINK;
541 /* blinking amber = hw attention */
542 case INDICATOR_AMBER_BLINK:
543 selector = HUB_LED_AMBER;
544 mode = INDICATOR_AMBER_BLINK_OFF;
546 case INDICATOR_AMBER_BLINK_OFF:
547 selector = HUB_LED_OFF;
548 mode = INDICATOR_AMBER_BLINK;
550 /* blink green/amber = reserved */
551 case INDICATOR_ALT_BLINK:
552 selector = HUB_LED_GREEN;
553 mode = INDICATOR_ALT_BLINK_OFF;
555 case INDICATOR_ALT_BLINK_OFF:
556 selector = HUB_LED_AMBER;
557 mode = INDICATOR_ALT_BLINK;
562 if (selector != HUB_LED_AUTO)
564 set_port_led(hub, i + 1, selector);
565 hub->indicator[i] = mode;
567 if (!changed && blinkenlights) {
569 cursor %= hdev->maxchild;
570 set_port_led(hub, cursor + 1, HUB_LED_GREEN);
571 hub->indicator[cursor] = INDICATOR_CYCLE;
575 queue_delayed_work(system_power_efficient_wq,
576 &hub->leds, LED_CYCLE_PERIOD);
579 /* use a short timeout for hub/port status fetches */
580 #define USB_STS_TIMEOUT 1000
581 #define USB_STS_RETRIES 5
584 * USB 2.0 spec Section 11.24.2.6
586 static int get_hub_status(struct usb_device *hdev,
587 struct usb_hub_status *data)
589 int i, status = -ETIMEDOUT;
591 for (i = 0; i < USB_STS_RETRIES &&
592 (status == -ETIMEDOUT || status == -EPIPE); i++) {
593 status = usb_control_msg(hdev, usb_rcvctrlpipe(hdev, 0),
594 USB_REQ_GET_STATUS, USB_DIR_IN | USB_RT_HUB, 0, 0,
595 data, sizeof(*data), USB_STS_TIMEOUT);
601 * USB 2.0 spec Section 11.24.2.7
602 * USB 3.1 takes into use the wValue and wLength fields, spec Section 10.16.2.6
604 static int get_port_status(struct usb_device *hdev, int port1,
605 void *data, u16 value, u16 length)
607 int i, status = -ETIMEDOUT;
609 for (i = 0; i < USB_STS_RETRIES &&
610 (status == -ETIMEDOUT || status == -EPIPE); i++) {
611 status = usb_control_msg(hdev, usb_rcvctrlpipe(hdev, 0),
612 USB_REQ_GET_STATUS, USB_DIR_IN | USB_RT_PORT, value,
613 port1, data, length, USB_STS_TIMEOUT);
618 static int hub_ext_port_status(struct usb_hub *hub, int port1, int type,
619 u16 *status, u16 *change, u32 *ext_status)
624 if (type != HUB_PORT_STATUS)
627 mutex_lock(&hub->status_mutex);
628 ret = get_port_status(hub->hdev, port1, &hub->status->port, type, len);
631 dev_err(hub->intfdev,
632 "%s failed (err = %d)\n", __func__, ret);
636 *status = le16_to_cpu(hub->status->port.wPortStatus);
637 *change = le16_to_cpu(hub->status->port.wPortChange);
638 if (type != HUB_PORT_STATUS && ext_status)
639 *ext_status = le32_to_cpu(
640 hub->status->port.dwExtPortStatus);
643 mutex_unlock(&hub->status_mutex);
646 * There is no need to lock status_mutex here, because status_mutex
647 * protects hub->status, and the phy driver only checks the port
648 * status without changing the status.
651 struct usb_device *hdev = hub->hdev;
654 * Only roothub will be notified of connection changes,
655 * since the USB PHY only cares about changes at the next
658 if (is_root_hub(hdev)) {
659 struct usb_hcd *hcd = bus_to_hcd(hdev->bus);
663 connect_change = *change & USB_PORT_STAT_C_CONNECTION;
664 connect = *status & USB_PORT_STAT_CONNECTION;
665 if (connect_change && connect)
666 usb_phy_roothub_notify_connect(hcd->phy_roothub, port1 - 1);
667 else if (connect_change)
668 usb_phy_roothub_notify_disconnect(hcd->phy_roothub, port1 - 1);
675 int usb_hub_port_status(struct usb_hub *hub, int port1,
676 u16 *status, u16 *change)
678 return hub_ext_port_status(hub, port1, HUB_PORT_STATUS,
679 status, change, NULL);
682 static void hub_resubmit_irq_urb(struct usb_hub *hub)
687 spin_lock_irqsave(&hub->irq_urb_lock, flags);
689 if (hub->quiescing) {
690 spin_unlock_irqrestore(&hub->irq_urb_lock, flags);
694 status = usb_submit_urb(hub->urb, GFP_ATOMIC);
695 if (status && status != -ENODEV && status != -EPERM &&
696 status != -ESHUTDOWN) {
697 dev_err(hub->intfdev, "resubmit --> %d\n", status);
698 mod_timer(&hub->irq_urb_retry, jiffies + HZ);
701 spin_unlock_irqrestore(&hub->irq_urb_lock, flags);
704 static void hub_retry_irq_urb(struct timer_list *t)
706 struct usb_hub *hub = timer_container_of(hub, t, irq_urb_retry);
708 hub_resubmit_irq_urb(hub);
712 static void kick_hub_wq(struct usb_hub *hub)
714 struct usb_interface *intf;
716 if (hub->disconnected || work_pending(&hub->events))
720 * Suppress autosuspend until the event is proceed.
722 * Be careful and make sure that the symmetric operation is
723 * always called. We are here only when there is no pending
724 * work for this hub. Therefore put the interface either when
725 * the new work is called or when it is canceled.
727 intf = to_usb_interface(hub->intfdev);
728 usb_autopm_get_interface_no_resume(intf);
731 if (queue_work(hub_wq, &hub->events))
734 /* the work has already been scheduled */
735 usb_autopm_put_interface_async(intf);
739 void usb_kick_hub_wq(struct usb_device *hdev)
741 struct usb_hub *hub = usb_hub_to_struct_hub(hdev);
748 * Let the USB core know that a USB 3.0 device has sent a Function Wake Device
749 * Notification, which indicates it had initiated remote wakeup.
751 * USB 3.0 hubs do not report the port link state change from U3 to U0 when the
752 * device initiates resume, so the USB core will not receive notice of the
753 * resume through the normal hub interrupt URB.
755 void usb_wakeup_notification(struct usb_device *hdev,
756 unsigned int portnum)
759 struct usb_port *port_dev;
764 hub = usb_hub_to_struct_hub(hdev);
766 port_dev = hub->ports[portnum - 1];
767 if (port_dev && port_dev->child)
768 pm_wakeup_event(&port_dev->child->dev, 0);
770 set_bit(portnum, hub->wakeup_bits);
774 EXPORT_SYMBOL_GPL(usb_wakeup_notification);
776 /* completion function, fires on port status changes and various faults */
777 static void hub_irq(struct urb *urb)
779 struct usb_hub *hub = urb->context;
780 int status = urb->status;
785 case -ENOENT: /* synchronous unlink */
786 case -ECONNRESET: /* async unlink */
787 case -ESHUTDOWN: /* hardware going away */
790 default: /* presumably an error */
791 /* Cause a hub reset after 10 consecutive errors */
792 dev_dbg(hub->intfdev, "transfer --> %d\n", status);
793 if ((++hub->nerrors < 10) || hub->error)
798 /* let hub_wq handle things */
799 case 0: /* we got data: port status changed */
801 for (i = 0; i < urb->actual_length; ++i)
802 bits |= ((unsigned long) ((*hub->buffer)[i]))
804 hub->event_bits[0] = bits;
810 /* Something happened, let hub_wq figure it out */
814 hub_resubmit_irq_urb(hub);
817 /* USB 2.0 spec Section 11.24.2.3 */
819 hub_clear_tt_buffer(struct usb_device *hdev, u16 devinfo, u16 tt)
821 /* Need to clear both directions for control ep */
822 if (((devinfo >> 11) & USB_ENDPOINT_XFERTYPE_MASK) ==
823 USB_ENDPOINT_XFER_CONTROL) {
824 int status = usb_control_msg(hdev, usb_sndctrlpipe(hdev, 0),
825 HUB_CLEAR_TT_BUFFER, USB_RT_PORT,
826 devinfo ^ 0x8000, tt, NULL, 0, 1000);
830 return usb_control_msg(hdev, usb_sndctrlpipe(hdev, 0),
831 HUB_CLEAR_TT_BUFFER, USB_RT_PORT, devinfo,
836 * enumeration blocks hub_wq for a long time. we use keventd instead, since
837 * long blocking there is the exception, not the rule. accordingly, HCDs
838 * talking to TTs must queue control transfers (not just bulk and iso), so
839 * both can talk to the same hub concurrently.
841 static void hub_tt_work(struct work_struct *work)
843 struct usb_hub *hub =
844 container_of(work, struct usb_hub, tt.clear_work);
847 spin_lock_irqsave(&hub->tt.lock, flags);
848 while (!list_empty(&hub->tt.clear_list)) {
849 struct list_head *next;
850 struct usb_tt_clear *clear;
851 struct usb_device *hdev = hub->hdev;
852 const struct hc_driver *drv;
855 next = hub->tt.clear_list.next;
856 clear = list_entry(next, struct usb_tt_clear, clear_list);
857 list_del(&clear->clear_list);
859 /* drop lock so HCD can concurrently report other TT errors */
860 spin_unlock_irqrestore(&hub->tt.lock, flags);
861 status = hub_clear_tt_buffer(hdev, clear->devinfo, clear->tt);
862 if (status && status != -ENODEV)
864 "clear tt %d (%04x) error %d\n",
865 clear->tt, clear->devinfo, status);
867 /* Tell the HCD, even if the operation failed */
868 drv = clear->hcd->driver;
869 if (drv->clear_tt_buffer_complete)
870 (drv->clear_tt_buffer_complete)(clear->hcd, clear->ep);
873 spin_lock_irqsave(&hub->tt.lock, flags);
875 spin_unlock_irqrestore(&hub->tt.lock, flags);
879 * usb_hub_set_port_power - control hub port's power state
880 * @hdev: USB device belonging to the usb hub
883 * @set: expected status
885 * call this function to control port's power via setting or
886 * clearing the port's PORT_POWER feature.
888 * Return: 0 if successful. A negative error code otherwise.
890 int usb_hub_set_port_power(struct usb_device *hdev, struct usb_hub *hub,
896 ret = set_port_feature(hdev, port1, USB_PORT_FEAT_POWER);
898 ret = usb_clear_port_feature(hdev, port1, USB_PORT_FEAT_POWER);
904 set_bit(port1, hub->power_bits);
906 clear_bit(port1, hub->power_bits);
911 * usb_hub_clear_tt_buffer - clear control/bulk TT state in high speed hub
912 * @urb: an URB associated with the failed or incomplete split transaction
914 * High speed HCDs use this to tell the hub driver that some split control or
915 * bulk transaction failed in a way that requires clearing internal state of
916 * a transaction translator. This is normally detected (and reported) from
919 * It may not be possible for that hub to handle additional full (or low)
920 * speed transactions until that state is fully cleared out.
922 * Return: 0 if successful. A negative error code otherwise.
924 int usb_hub_clear_tt_buffer(struct urb *urb)
926 struct usb_device *udev = urb->dev;
927 int pipe = urb->pipe;
928 struct usb_tt *tt = udev->tt;
930 struct usb_tt_clear *clear;
932 /* we've got to cope with an arbitrary number of pending TT clears,
933 * since each TT has "at least two" buffers that can need it (and
934 * there can be many TTs per hub). even if they're uncommon.
936 clear = kmalloc(sizeof *clear, GFP_ATOMIC);
938 dev_err(&udev->dev, "can't save CLEAR_TT_BUFFER state\n");
939 /* FIXME recover somehow ... RESET_TT? */
943 /* info that CLEAR_TT_BUFFER needs */
944 clear->tt = tt->multi ? udev->ttport : 1;
945 clear->devinfo = usb_pipeendpoint (pipe);
946 clear->devinfo |= ((u16)udev->devaddr) << 4;
947 clear->devinfo |= usb_pipecontrol(pipe)
948 ? (USB_ENDPOINT_XFER_CONTROL << 11)
949 : (USB_ENDPOINT_XFER_BULK << 11);
950 if (usb_pipein(pipe))
951 clear->devinfo |= 1 << 15;
953 /* info for completion callback */
954 clear->hcd = bus_to_hcd(udev->bus);
957 /* tell keventd to clear state for this TT */
958 spin_lock_irqsave(&tt->lock, flags);
959 list_add_tail(&clear->clear_list, &tt->clear_list);
960 schedule_work(&tt->clear_work);
961 spin_unlock_irqrestore(&tt->lock, flags);
964 EXPORT_SYMBOL_GPL(usb_hub_clear_tt_buffer);
966 static void hub_power_on(struct usb_hub *hub, bool do_delay)
970 /* Enable power on each port. Some hubs have reserved values
971 * of LPSM (> 2) in their descriptors, even though they are
972 * USB 2.0 hubs. Some hubs do not implement port-power switching
973 * but only emulate it. In all cases, the ports won't work
974 * unless we send these messages to the hub.
976 if (hub_is_port_power_switchable(hub))
977 dev_dbg(hub->intfdev, "enabling power on all ports\n");
979 dev_dbg(hub->intfdev, "trying to enable port power on "
980 "non-switchable hub\n");
981 for (port1 = 1; port1 <= hub->hdev->maxchild; port1++)
982 if (test_bit(port1, hub->power_bits))
983 set_port_feature(hub->hdev, port1, USB_PORT_FEAT_POWER);
985 usb_clear_port_feature(hub->hdev, port1,
986 USB_PORT_FEAT_POWER);
988 msleep(hub_power_on_good_delay(hub));
991 static int hub_hub_status(struct usb_hub *hub,
992 u16 *status, u16 *change)
996 mutex_lock(&hub->status_mutex);
997 ret = get_hub_status(hub->hdev, &hub->status->hub);
1000 dev_err(hub->intfdev,
1001 "%s failed (err = %d)\n", __func__, ret);
1003 *status = le16_to_cpu(hub->status->hub.wHubStatus);
1004 *change = le16_to_cpu(hub->status->hub.wHubChange);
1007 mutex_unlock(&hub->status_mutex);
1011 static int hub_set_port_link_state(struct usb_hub *hub, int port1,
1012 unsigned int link_status)
1014 return set_port_feature(hub->hdev,
1015 port1 | (link_status << 3),
1016 USB_PORT_FEAT_LINK_STATE);
1020 * Disable a port and mark a logical connect-change event, so that some
1021 * time later hub_wq will disconnect() any existing usb_device on the port
1022 * and will re-enumerate if there actually is a device attached.
1024 static void hub_port_logical_disconnect(struct usb_hub *hub, int port1)
1026 dev_dbg(&hub->ports[port1 - 1]->dev, "logical disconnect\n");
1027 hub_port_disable(hub, port1, 1);
1029 /* FIXME let caller ask to power down the port:
1030 * - some devices won't enumerate without a VBUS power cycle
1031 * - SRP saves power that way
1032 * - ... new call, TBD ...
1033 * That's easy if this hub can switch power per-port, and
1034 * hub_wq reactivates the port later (timer, SRP, etc).
1035 * Powerdown must be optional, because of reset/DFU.
1038 set_bit(port1, hub->change_bits);
1043 * usb_remove_device - disable a device's port on its parent hub
1044 * @udev: device to be disabled and removed
1045 * Context: @udev locked, must be able to sleep.
1047 * After @udev's port has been disabled, hub_wq is notified and it will
1048 * see that the device has been disconnected. When the device is
1049 * physically unplugged and something is plugged in, the events will
1050 * be received and processed normally.
1052 * Return: 0 if successful. A negative error code otherwise.
1054 int usb_remove_device(struct usb_device *udev)
1056 struct usb_hub *hub;
1057 struct usb_interface *intf;
1060 if (!udev->parent) /* Can't remove a root hub */
1062 hub = usb_hub_to_struct_hub(udev->parent);
1063 intf = to_usb_interface(hub->intfdev);
1065 ret = usb_autopm_get_interface(intf);
1069 set_bit(udev->portnum, hub->removed_bits);
1070 hub_port_logical_disconnect(hub, udev->portnum);
1071 usb_autopm_put_interface(intf);
1075 enum hub_activation_type {
1076 HUB_INIT, HUB_INIT2, HUB_INIT3, /* INITs must come first */
1077 HUB_POST_RESET, HUB_RESUME, HUB_RESET_RESUME,
1080 static void hub_init_func2(struct work_struct *ws);
1081 static void hub_init_func3(struct work_struct *ws);
1083 static void hub_activate(struct usb_hub *hub, enum hub_activation_type type)
1085 struct usb_device *hdev = hub->hdev;
1086 struct usb_hcd *hcd;
1090 bool need_debounce_delay = false;
1093 /* Continue a partial initialization */
1094 if (type == HUB_INIT2 || type == HUB_INIT3) {
1095 device_lock(&hdev->dev);
1097 /* Was the hub disconnected while we were waiting? */
1098 if (hub->disconnected)
1100 if (type == HUB_INIT2)
1107 /* The superspeed hub except for root hub has to use Hub Depth
1108 * value as an offset into the route string to locate the bits
1109 * it uses to determine the downstream port number. So hub driver
1110 * should send a set hub depth request to superspeed hub after
1111 * the superspeed hub is set configuration in initialization or
1114 * After a resume, port power should still be on.
1115 * For any other type of activation, turn it on.
1117 if (type != HUB_RESUME) {
1118 if (hdev->parent && hub_is_superspeed(hdev)) {
1119 ret = usb_control_msg(hdev, usb_sndctrlpipe(hdev, 0),
1120 HUB_SET_DEPTH, USB_RT_HUB,
1121 hdev->level - 1, 0, NULL, 0,
1122 USB_CTRL_SET_TIMEOUT);
1124 dev_err(hub->intfdev,
1125 "set hub depth failed\n");
1128 /* Speed up system boot by using a delayed_work for the
1129 * hub's initial power-up delays. This is pretty awkward
1130 * and the implementation looks like a home-brewed sort of
1131 * setjmp/longjmp, but it saves at least 100 ms for each
1132 * root hub (assuming usbcore is compiled into the kernel
1133 * rather than as a module). It adds up.
1135 * This can't be done for HUB_RESUME or HUB_RESET_RESUME
1136 * because for those activation types the ports have to be
1137 * operational when we return. In theory this could be done
1138 * for HUB_POST_RESET, but it's easier not to.
1140 if (type == HUB_INIT) {
1141 delay = hub_power_on_good_delay(hub);
1143 hub_power_on(hub, false);
1144 INIT_DELAYED_WORK(&hub->init_work, hub_init_func2);
1145 queue_delayed_work(system_power_efficient_wq,
1147 msecs_to_jiffies(delay));
1149 /* Suppress autosuspend until init is done */
1150 usb_autopm_get_interface_no_resume(
1151 to_usb_interface(hub->intfdev));
1152 return; /* Continues at init2: below */
1153 } else if (type == HUB_RESET_RESUME) {
1154 /* The internal host controller state for the hub device
1155 * may be gone after a host power loss on system resume.
1156 * Update the device's info so the HW knows it's a hub.
1158 hcd = bus_to_hcd(hdev->bus);
1159 if (hcd->driver->update_hub_device) {
1160 ret = hcd->driver->update_hub_device(hcd, hdev,
1161 &hub->tt, GFP_NOIO);
1163 dev_err(hub->intfdev,
1164 "Host not accepting hub info update\n");
1165 dev_err(hub->intfdev,
1166 "LS/FS devices and hubs may not work under this hub\n");
1169 hub_power_on(hub, true);
1171 hub_power_on(hub, true);
1173 /* Give some time on remote wakeup to let links to transit to U0 */
1174 } else if (hub_is_superspeed(hub->hdev))
1180 * Check each port and set hub->change_bits to let hub_wq know
1181 * which ports need attention.
1183 for (port1 = 1; port1 <= hdev->maxchild; ++port1) {
1184 struct usb_port *port_dev = hub->ports[port1 - 1];
1185 struct usb_device *udev = port_dev->child;
1186 u16 portstatus, portchange;
1188 portstatus = portchange = 0;
1189 status = usb_hub_port_status(hub, port1, &portstatus, &portchange);
1193 if (udev || (portstatus & USB_PORT_STAT_CONNECTION))
1194 dev_dbg(&port_dev->dev, "status %04x change %04x\n",
1195 portstatus, portchange);
1198 * After anything other than HUB_RESUME (i.e., initialization
1199 * or any sort of reset), every port should be disabled.
1200 * Unconnected ports should likewise be disabled (paranoia),
1201 * and so should ports for which we have no usb_device.
1203 if ((portstatus & USB_PORT_STAT_ENABLE) && (
1204 type != HUB_RESUME ||
1205 !(portstatus & USB_PORT_STAT_CONNECTION) ||
1207 udev->state == USB_STATE_NOTATTACHED)) {
1209 * USB3 protocol ports will automatically transition
1210 * to Enabled state when detect an USB3.0 device attach.
1211 * Do not disable USB3 protocol ports, just pretend
1214 portstatus &= ~USB_PORT_STAT_ENABLE;
1215 if (!hub_is_superspeed(hdev))
1216 usb_clear_port_feature(hdev, port1,
1217 USB_PORT_FEAT_ENABLE);
1220 /* Make sure a warm-reset request is handled by port_event */
1221 if (type == HUB_RESUME &&
1222 hub_port_warm_reset_required(hub, port1, portstatus))
1223 set_bit(port1, hub->event_bits);
1226 * Add debounce if USB3 link is in polling/link training state.
1227 * Link will automatically transition to Enabled state after
1228 * link training completes.
1230 if (hub_is_superspeed(hdev) &&
1231 ((portstatus & USB_PORT_STAT_LINK_STATE) ==
1232 USB_SS_PORT_LS_POLLING))
1233 need_debounce_delay = true;
1235 /* Clear status-change flags; we'll debounce later */
1236 if (portchange & USB_PORT_STAT_C_CONNECTION) {
1237 need_debounce_delay = true;
1238 usb_clear_port_feature(hub->hdev, port1,
1239 USB_PORT_FEAT_C_CONNECTION);
1241 if (portchange & USB_PORT_STAT_C_ENABLE) {
1242 need_debounce_delay = true;
1243 usb_clear_port_feature(hub->hdev, port1,
1244 USB_PORT_FEAT_C_ENABLE);
1246 if (portchange & USB_PORT_STAT_C_RESET) {
1247 need_debounce_delay = true;
1248 usb_clear_port_feature(hub->hdev, port1,
1249 USB_PORT_FEAT_C_RESET);
1251 if ((portchange & USB_PORT_STAT_C_BH_RESET) &&
1252 hub_is_superspeed(hub->hdev)) {
1253 need_debounce_delay = true;
1254 usb_clear_port_feature(hub->hdev, port1,
1255 USB_PORT_FEAT_C_BH_PORT_RESET);
1257 /* We can forget about a "removed" device when there's a
1258 * physical disconnect or the connect status changes.
1260 if (!(portstatus & USB_PORT_STAT_CONNECTION) ||
1261 (portchange & USB_PORT_STAT_C_CONNECTION))
1262 clear_bit(port1, hub->removed_bits);
1264 if (!udev || udev->state == USB_STATE_NOTATTACHED) {
1265 /* Tell hub_wq to disconnect the device or
1266 * check for a new connection or over current condition.
1267 * Based on USB2.0 Spec Section 11.12.5,
1268 * C_PORT_OVER_CURRENT could be set while
1269 * PORT_OVER_CURRENT is not. So check for any of them.
1271 if (udev || (portstatus & USB_PORT_STAT_CONNECTION) ||
1272 (portchange & USB_PORT_STAT_C_CONNECTION) ||
1273 (portstatus & USB_PORT_STAT_OVERCURRENT) ||
1274 (portchange & USB_PORT_STAT_C_OVERCURRENT))
1275 set_bit(port1, hub->change_bits);
1277 } else if (portstatus & USB_PORT_STAT_ENABLE) {
1278 bool port_resumed = (portstatus &
1279 USB_PORT_STAT_LINK_STATE) ==
1281 /* The power session apparently survived the resume.
1282 * If there was an overcurrent or suspend change
1283 * (i.e., remote wakeup request), have hub_wq
1284 * take care of it. Look at the port link state
1285 * for USB 3.0 hubs, since they don't have a suspend
1286 * change bit, and they don't set the port link change
1287 * bit on device-initiated resume.
1289 if (portchange || (hub_is_superspeed(hub->hdev) &&
1291 set_bit(port1, hub->event_bits);
1293 } else if (udev->persist_enabled) {
1295 udev->reset_resume = 1;
1297 /* Don't set the change_bits when the device
1300 if (test_bit(port1, hub->power_bits))
1301 set_bit(port1, hub->change_bits);
1304 /* The power session is gone; tell hub_wq */
1305 usb_set_device_state(udev, USB_STATE_NOTATTACHED);
1306 set_bit(port1, hub->change_bits);
1310 /* If no port-status-change flags were set, we don't need any
1311 * debouncing. If flags were set we can try to debounce the
1312 * ports all at once right now, instead of letting hub_wq do them
1313 * one at a time later on.
1315 * If any port-status changes do occur during this delay, hub_wq
1316 * will see them later and handle them normally.
1318 if (need_debounce_delay) {
1319 delay = HUB_DEBOUNCE_STABLE;
1321 /* Don't do a long sleep inside a workqueue routine */
1322 if (type == HUB_INIT2) {
1323 INIT_DELAYED_WORK(&hub->init_work, hub_init_func3);
1324 queue_delayed_work(system_power_efficient_wq,
1326 msecs_to_jiffies(delay));
1327 device_unlock(&hdev->dev);
1328 return; /* Continues at init3: below */
1336 status = usb_submit_urb(hub->urb, GFP_NOIO);
1338 dev_err(hub->intfdev, "activate --> %d\n", status);
1339 if (hub->has_indicators && blinkenlights)
1340 queue_delayed_work(system_power_efficient_wq,
1341 &hub->leds, LED_CYCLE_PERIOD);
1343 /* Scan all ports that need attention */
1346 if (type == HUB_INIT2 || type == HUB_INIT3) {
1347 /* Allow autosuspend if it was suppressed */
1349 usb_autopm_put_interface_async(to_usb_interface(hub->intfdev));
1350 device_unlock(&hdev->dev);
1353 if (type == HUB_RESUME && hub_is_superspeed(hub->hdev)) {
1354 /* give usb3 downstream links training time after hub resume */
1355 usb_autopm_get_interface_no_resume(
1356 to_usb_interface(hub->intfdev));
1358 queue_delayed_work(system_power_efficient_wq,
1359 &hub->post_resume_work,
1360 msecs_to_jiffies(USB_SS_PORT_U0_WAKE_TIME));
1367 /* Implement the continuations for the delays above */
1368 static void hub_init_func2(struct work_struct *ws)
1370 struct usb_hub *hub = container_of(ws, struct usb_hub, init_work.work);
1372 hub_activate(hub, HUB_INIT2);
1375 static void hub_init_func3(struct work_struct *ws)
1377 struct usb_hub *hub = container_of(ws, struct usb_hub, init_work.work);
1379 hub_activate(hub, HUB_INIT3);
1382 static void hub_post_resume(struct work_struct *ws)
1384 struct usb_hub *hub = container_of(ws, struct usb_hub, post_resume_work.work);
1386 usb_autopm_put_interface_async(to_usb_interface(hub->intfdev));
1390 enum hub_quiescing_type {
1391 HUB_DISCONNECT, HUB_PRE_RESET, HUB_SUSPEND
1394 static void hub_quiesce(struct usb_hub *hub, enum hub_quiescing_type type)
1396 struct usb_device *hdev = hub->hdev;
1397 unsigned long flags;
1400 /* hub_wq and related activity won't re-trigger */
1401 spin_lock_irqsave(&hub->irq_urb_lock, flags);
1403 spin_unlock_irqrestore(&hub->irq_urb_lock, flags);
1405 if (type != HUB_SUSPEND) {
1406 /* Disconnect all the children */
1407 for (i = 0; i < hdev->maxchild; ++i) {
1408 if (hub->ports[i]->child)
1409 usb_disconnect(&hub->ports[i]->child);
1413 /* Stop hub_wq and related activity */
1414 timer_delete_sync(&hub->irq_urb_retry);
1415 flush_delayed_work(&hub->post_resume_work);
1416 usb_kill_urb(hub->urb);
1417 if (hub->has_indicators)
1418 cancel_delayed_work_sync(&hub->leds);
1420 flush_work(&hub->tt.clear_work);
1423 static void hub_pm_barrier_for_all_ports(struct usb_hub *hub)
1427 for (i = 0; i < hub->hdev->maxchild; ++i)
1428 pm_runtime_barrier(&hub->ports[i]->dev);
1431 /* caller has locked the hub device */
1432 static int hub_pre_reset(struct usb_interface *intf)
1434 struct usb_hub *hub = usb_get_intfdata(intf);
1436 hub_quiesce(hub, HUB_PRE_RESET);
1438 hub_pm_barrier_for_all_ports(hub);
1442 /* caller has locked the hub device */
1443 static int hub_post_reset(struct usb_interface *intf)
1445 struct usb_hub *hub = usb_get_intfdata(intf);
1448 hub_pm_barrier_for_all_ports(hub);
1449 hub_activate(hub, HUB_POST_RESET);
1453 static int hub_configure(struct usb_hub *hub,
1454 struct usb_endpoint_descriptor *endpoint)
1456 struct usb_hcd *hcd;
1457 struct usb_device *hdev = hub->hdev;
1458 struct device *hub_dev = hub->intfdev;
1459 u16 hubstatus, hubchange;
1460 u16 wHubCharacteristics;
1463 char *message = "out of memory";
1468 hub->buffer = kmalloc(sizeof(*hub->buffer), GFP_KERNEL);
1474 hub->status = kmalloc(sizeof(*hub->status), GFP_KERNEL);
1479 mutex_init(&hub->status_mutex);
1481 hub->descriptor = kzalloc(sizeof(*hub->descriptor), GFP_KERNEL);
1482 if (!hub->descriptor) {
1487 /* Request the entire hub descriptor.
1488 * hub->descriptor can handle USB_MAXCHILDREN ports,
1489 * but a (non-SS) hub can/will return fewer bytes here.
1491 ret = get_hub_descriptor(hdev, hub->descriptor);
1493 message = "can't read hub descriptor";
1497 maxchild = USB_MAXCHILDREN;
1498 if (hub_is_superspeed(hdev))
1499 maxchild = min_t(unsigned, maxchild, USB_SS_MAXPORTS);
1501 if (hub->descriptor->bNbrPorts > maxchild) {
1502 message = "hub has too many ports!";
1505 } else if (hub->descriptor->bNbrPorts == 0) {
1506 message = "hub doesn't have any ports!";
1512 * Accumulate wHubDelay + 40ns for every hub in the tree of devices.
1513 * The resulting value will be used for SetIsochDelay() request.
1515 if (hub_is_superspeed(hdev) || hub_is_superspeedplus(hdev)) {
1516 u32 delay = __le16_to_cpu(hub->descriptor->u.ss.wHubDelay);
1519 delay += hdev->parent->hub_delay;
1521 delay += USB_TP_TRANSMISSION_DELAY;
1522 hdev->hub_delay = min_t(u32, delay, USB_TP_TRANSMISSION_DELAY_MAX);
1525 maxchild = hub->descriptor->bNbrPorts;
1526 dev_info(hub_dev, "%d port%s detected\n", maxchild,
1527 str_plural(maxchild));
1529 hub->ports = kcalloc(maxchild, sizeof(struct usb_port *), GFP_KERNEL);
1535 wHubCharacteristics = le16_to_cpu(hub->descriptor->wHubCharacteristics);
1536 if (hub_is_superspeed(hdev)) {
1544 /* FIXME for USB 3.0, skip for now */
1545 if ((wHubCharacteristics & HUB_CHAR_COMPOUND) &&
1546 !(hub_is_superspeed(hdev))) {
1547 char portstr[USB_MAXCHILDREN + 1];
1549 for (i = 0; i < maxchild; i++)
1550 portstr[i] = hub->descriptor->u.hs.DeviceRemovable
1551 [((i + 1) / 8)] & (1 << ((i + 1) % 8))
1553 portstr[maxchild] = 0;
1554 dev_dbg(hub_dev, "compound device; port removable status: %s\n", portstr);
1556 dev_dbg(hub_dev, "standalone hub\n");
1558 switch (wHubCharacteristics & HUB_CHAR_LPSM) {
1559 case HUB_CHAR_COMMON_LPSM:
1560 dev_dbg(hub_dev, "ganged power switching\n");
1562 case HUB_CHAR_INDV_PORT_LPSM:
1563 dev_dbg(hub_dev, "individual port power switching\n");
1565 case HUB_CHAR_NO_LPSM:
1567 dev_dbg(hub_dev, "no power switching (usb 1.0)\n");
1571 switch (wHubCharacteristics & HUB_CHAR_OCPM) {
1572 case HUB_CHAR_COMMON_OCPM:
1573 dev_dbg(hub_dev, "global over-current protection\n");
1575 case HUB_CHAR_INDV_PORT_OCPM:
1576 dev_dbg(hub_dev, "individual port over-current protection\n");
1578 case HUB_CHAR_NO_OCPM:
1580 dev_dbg(hub_dev, "no over-current protection\n");
1584 spin_lock_init(&hub->tt.lock);
1585 INIT_LIST_HEAD(&hub->tt.clear_list);
1586 INIT_WORK(&hub->tt.clear_work, hub_tt_work);
1587 switch (hdev->descriptor.bDeviceProtocol) {
1590 case USB_HUB_PR_HS_SINGLE_TT:
1591 dev_dbg(hub_dev, "Single TT\n");
1594 case USB_HUB_PR_HS_MULTI_TT:
1595 ret = usb_set_interface(hdev, 0, 1);
1597 dev_dbg(hub_dev, "TT per port\n");
1600 dev_err(hub_dev, "Using single TT (err %d)\n",
1605 /* USB 3.0 hubs don't have a TT */
1608 dev_dbg(hub_dev, "Unrecognized hub protocol %d\n",
1609 hdev->descriptor.bDeviceProtocol);
1613 /* Note 8 FS bit times == (8 bits / 12000000 bps) ~= 666ns */
1614 switch (wHubCharacteristics & HUB_CHAR_TTTT) {
1615 case HUB_TTTT_8_BITS:
1616 if (hdev->descriptor.bDeviceProtocol != 0) {
1617 hub->tt.think_time = 666;
1618 dev_dbg(hub_dev, "TT requires at most %d "
1619 "FS bit times (%d ns)\n",
1620 8, hub->tt.think_time);
1623 case HUB_TTTT_16_BITS:
1624 hub->tt.think_time = 666 * 2;
1625 dev_dbg(hub_dev, "TT requires at most %d "
1626 "FS bit times (%d ns)\n",
1627 16, hub->tt.think_time);
1629 case HUB_TTTT_24_BITS:
1630 hub->tt.think_time = 666 * 3;
1631 dev_dbg(hub_dev, "TT requires at most %d "
1632 "FS bit times (%d ns)\n",
1633 24, hub->tt.think_time);
1635 case HUB_TTTT_32_BITS:
1636 hub->tt.think_time = 666 * 4;
1637 dev_dbg(hub_dev, "TT requires at most %d "
1638 "FS bit times (%d ns)\n",
1639 32, hub->tt.think_time);
1643 /* probe() zeroes hub->indicator[] */
1644 if (wHubCharacteristics & HUB_CHAR_PORTIND) {
1645 hub->has_indicators = 1;
1646 dev_dbg(hub_dev, "Port indicators are supported\n");
1649 dev_dbg(hub_dev, "power on to power good time: %dms\n",
1650 hub->descriptor->bPwrOn2PwrGood * 2);
1652 /* power budgeting mostly matters with bus-powered hubs,
1653 * and battery-powered root hubs (may provide just 8 mA).
1655 ret = usb_get_std_status(hdev, USB_RECIP_DEVICE, 0, &hubstatus);
1657 message = "can't get hub status";
1660 hcd = bus_to_hcd(hdev->bus);
1661 if (hdev == hdev->bus->root_hub) {
1662 if (hcd->power_budget > 0)
1663 hdev->bus_mA = hcd->power_budget;
1665 hdev->bus_mA = full_load * maxchild;
1666 if (hdev->bus_mA >= full_load)
1667 hub->mA_per_port = full_load;
1669 hub->mA_per_port = hdev->bus_mA;
1670 hub->limited_power = 1;
1672 } else if ((hubstatus & (1 << USB_DEVICE_SELF_POWERED)) == 0) {
1673 int remaining = hdev->bus_mA -
1674 hub->descriptor->bHubContrCurrent;
1676 dev_dbg(hub_dev, "hub controller current requirement: %dmA\n",
1677 hub->descriptor->bHubContrCurrent);
1678 hub->limited_power = 1;
1680 if (remaining < maxchild * unit_load)
1682 "insufficient power available "
1683 "to use all downstream ports\n");
1684 hub->mA_per_port = unit_load; /* 7.2.1 */
1686 } else { /* Self-powered external hub */
1687 /* FIXME: What about battery-powered external hubs that
1688 * provide less current per port? */
1689 hub->mA_per_port = full_load;
1691 if (hub->mA_per_port < full_load)
1692 dev_dbg(hub_dev, "%umA bus power budget for each child\n",
1695 ret = hub_hub_status(hub, &hubstatus, &hubchange);
1697 message = "can't get hub status";
1701 /* local power status reports aren't always correct */
1702 if (hdev->actconfig->desc.bmAttributes & USB_CONFIG_ATT_SELFPOWER)
1703 dev_dbg(hub_dev, "local power source is %s\n",
1704 (hubstatus & HUB_STATUS_LOCAL_POWER)
1705 ? "lost (inactive)" : "good");
1707 if ((wHubCharacteristics & HUB_CHAR_OCPM) == 0)
1708 dev_dbg(hub_dev, "%sover-current condition exists\n",
1709 (hubstatus & HUB_STATUS_OVERCURRENT) ? "" : "no ");
1711 /* set up the interrupt endpoint
1712 * We use the EP's maxpacket size instead of (PORTS+1+7)/8
1713 * bytes as USB2.0[11.12.3] says because some hubs are known
1714 * to send more data (and thus cause overflow). For root hubs,
1715 * maxpktsize is defined in hcd.c's fake endpoint descriptors
1716 * to be big enough for at least USB_MAXCHILDREN ports. */
1717 pipe = usb_rcvintpipe(hdev, endpoint->bEndpointAddress);
1718 maxp = usb_maxpacket(hdev, pipe);
1720 if (maxp > sizeof(*hub->buffer))
1721 maxp = sizeof(*hub->buffer);
1723 hub->urb = usb_alloc_urb(0, GFP_KERNEL);
1729 usb_fill_int_urb(hub->urb, hdev, pipe, *hub->buffer, maxp, hub_irq,
1730 hub, endpoint->bInterval);
1732 /* maybe cycle the hub leds */
1733 if (hub->has_indicators && blinkenlights)
1734 hub->indicator[0] = INDICATOR_CYCLE;
1736 mutex_lock(&usb_port_peer_mutex);
1737 for (i = 0; i < maxchild; i++) {
1738 ret = usb_hub_create_port_device(hub, i + 1);
1740 dev_err(hub->intfdev,
1741 "couldn't create port%d device.\n", i + 1);
1746 for (i = 0; i < hdev->maxchild; i++) {
1747 struct usb_port *port_dev = hub->ports[i];
1749 pm_runtime_put(&port_dev->dev);
1752 mutex_unlock(&usb_port_peer_mutex);
1756 /* Update the HCD's internal representation of this hub before hub_wq
1757 * starts getting port status changes for devices under the hub.
1759 if (hcd->driver->update_hub_device) {
1760 ret = hcd->driver->update_hub_device(hcd, hdev,
1761 &hub->tt, GFP_KERNEL);
1763 message = "can't update HCD hub info";
1768 usb_hub_adjust_deviceremovable(hdev, hub->descriptor);
1770 hub_activate(hub, HUB_INIT);
1774 dev_err(hub_dev, "config failed, %s (err %d)\n",
1776 /* hub_disconnect() frees urb and descriptor */
1780 static void hub_release(struct kref *kref)
1782 struct usb_hub *hub = container_of(kref, struct usb_hub, kref);
1784 usb_put_dev(hub->hdev);
1785 usb_put_intf(to_usb_interface(hub->intfdev));
1789 void hub_get(struct usb_hub *hub)
1791 kref_get(&hub->kref);
1794 void hub_put(struct usb_hub *hub)
1796 kref_put(&hub->kref, hub_release);
1799 static unsigned highspeed_hubs;
1801 static void hub_disconnect(struct usb_interface *intf)
1803 struct usb_hub *hub = usb_get_intfdata(intf);
1804 struct usb_device *hdev = interface_to_usbdev(intf);
1808 * Stop adding new hub events. We do not want to block here and thus
1809 * will not try to remove any pending work item.
1811 hub->disconnected = 1;
1813 /* Disconnect all children and quiesce the hub */
1815 hub_quiesce(hub, HUB_DISCONNECT);
1817 mutex_lock(&usb_port_peer_mutex);
1819 /* Avoid races with recursively_mark_NOTATTACHED() */
1820 spin_lock_irq(&device_state_lock);
1821 port1 = hdev->maxchild;
1823 usb_set_intfdata(intf, NULL);
1824 spin_unlock_irq(&device_state_lock);
1826 for (; port1 > 0; --port1)
1827 usb_hub_remove_port_device(hub, port1);
1829 mutex_unlock(&usb_port_peer_mutex);
1831 if (hub->hdev->speed == USB_SPEED_HIGH)
1834 usb_free_urb(hub->urb);
1836 kfree(hub->descriptor);
1840 pm_suspend_ignore_children(&intf->dev, false);
1842 if (hub->quirk_disable_autosuspend)
1843 usb_autopm_put_interface(intf);
1845 onboard_dev_destroy_pdevs(&hub->onboard_devs);
1850 static bool hub_descriptor_is_sane(struct usb_host_interface *desc)
1852 /* Some hubs have a subclass of 1, which AFAICT according to the */
1853 /* specs is not defined, but it works */
1854 if (desc->desc.bInterfaceSubClass != 0 &&
1855 desc->desc.bInterfaceSubClass != 1)
1858 /* Multiple endpoints? What kind of mutant ninja-hub is this? */
1859 if (desc->desc.bNumEndpoints != 1)
1862 /* If the first endpoint is not interrupt IN, we'd better punt! */
1863 if (!usb_endpoint_is_int_in(&desc->endpoint[0].desc))
1869 static int hub_probe(struct usb_interface *intf, const struct usb_device_id *id)
1871 struct usb_host_interface *desc;
1872 struct usb_device *hdev;
1873 struct usb_hub *hub;
1875 desc = intf->cur_altsetting;
1876 hdev = interface_to_usbdev(intf);
1879 * The USB 2.0 spec prohibits hubs from having more than one
1880 * configuration or interface, and we rely on this prohibition.
1881 * Refuse to accept a device that violates it.
1883 if (hdev->descriptor.bNumConfigurations > 1 ||
1884 hdev->actconfig->desc.bNumInterfaces > 1) {
1885 dev_err(&intf->dev, "Invalid hub with more than one config or interface\n");
1890 * Set default autosuspend delay as 0 to speedup bus suspend,
1891 * based on the below considerations:
1893 * - Unlike other drivers, the hub driver does not rely on the
1894 * autosuspend delay to provide enough time to handle a wakeup
1895 * event, and the submitted status URB is just to check future
1896 * change on hub downstream ports, so it is safe to do it.
1898 * - The patch might cause one or more auto supend/resume for
1899 * below very rare devices when they are plugged into hub
1902 * devices having trouble initializing, and disconnect
1903 * themselves from the bus and then reconnect a second
1906 * devices just for downloading firmware, and disconnects
1907 * themselves after completing it
1909 * For these quite rare devices, their drivers may change the
1910 * autosuspend delay of their parent hub in the probe() to one
1911 * appropriate value to avoid the subtle problem if someone
1914 * - The patch may cause one or more auto suspend/resume on
1915 * hub during running 'lsusb', but it is probably too
1916 * infrequent to worry about.
1918 * - Change autosuspend delay of hub can avoid unnecessary auto
1919 * suspend timer for hub, also may decrease power consumption
1922 * - If user has indicated to prevent autosuspend by passing
1923 * usbcore.autosuspend = -1 then keep autosuspend disabled.
1926 if (hdev->dev.power.autosuspend_delay >= 0)
1927 pm_runtime_set_autosuspend_delay(&hdev->dev, 0);
1931 * Hubs have proper suspend/resume support, except for root hubs
1932 * where the controller driver doesn't have bus_suspend and
1933 * bus_resume methods.
1935 if (hdev->parent) { /* normal device */
1936 usb_enable_autosuspend(hdev);
1937 } else { /* root hub */
1938 const struct hc_driver *drv = bus_to_hcd(hdev->bus)->driver;
1940 if (drv->bus_suspend && drv->bus_resume)
1941 usb_enable_autosuspend(hdev);
1944 if (hdev->level == MAX_TOPO_LEVEL) {
1946 "Unsupported bus topology: hub nested too deep\n");
1950 #ifdef CONFIG_USB_OTG_DISABLE_EXTERNAL_HUB
1952 dev_warn(&intf->dev, "ignoring external hub\n");
1957 if (!hub_descriptor_is_sane(desc)) {
1958 dev_err(&intf->dev, "bad descriptor, ignoring hub\n");
1962 /* We found a hub */
1963 dev_info(&intf->dev, "USB hub found\n");
1965 hub = kzalloc(sizeof(*hub), GFP_KERNEL);
1969 kref_init(&hub->kref);
1970 hub->intfdev = &intf->dev;
1972 INIT_DELAYED_WORK(&hub->leds, led_work);
1973 INIT_DELAYED_WORK(&hub->init_work, NULL);
1974 INIT_DELAYED_WORK(&hub->post_resume_work, hub_post_resume);
1975 INIT_WORK(&hub->events, hub_event);
1976 INIT_LIST_HEAD(&hub->onboard_devs);
1977 spin_lock_init(&hub->irq_urb_lock);
1978 timer_setup(&hub->irq_urb_retry, hub_retry_irq_urb, 0);
1982 usb_set_intfdata(intf, hub);
1983 intf->needs_remote_wakeup = 1;
1984 pm_suspend_ignore_children(&intf->dev, true);
1986 if (hdev->speed == USB_SPEED_HIGH)
1989 if (id->driver_info & HUB_QUIRK_CHECK_PORT_AUTOSUSPEND)
1990 hub->quirk_check_port_auto_suspend = 1;
1992 if (id->driver_info & HUB_QUIRK_DISABLE_AUTOSUSPEND) {
1993 hub->quirk_disable_autosuspend = 1;
1994 usb_autopm_get_interface_no_resume(intf);
1997 if ((id->driver_info & HUB_QUIRK_REDUCE_FRAME_INTR_BINTERVAL) &&
1998 desc->endpoint[0].desc.bInterval > USB_REDUCE_FRAME_INTR_BINTERVAL) {
1999 desc->endpoint[0].desc.bInterval =
2000 USB_REDUCE_FRAME_INTR_BINTERVAL;
2001 /* Tell the HCD about the interrupt ep's new bInterval */
2002 usb_set_interface(hdev, 0, 0);
2005 if (hub_configure(hub, &desc->endpoint[0].desc) >= 0) {
2006 onboard_dev_create_pdevs(hdev, &hub->onboard_devs);
2011 hub_disconnect(intf);
2016 hub_ioctl(struct usb_interface *intf, unsigned int code, void *user_data)
2018 struct usb_device *hdev = interface_to_usbdev(intf);
2019 struct usb_hub *hub = usb_hub_to_struct_hub(hdev);
2021 /* assert ifno == 0 (part of hub spec) */
2023 case USBDEVFS_HUB_PORTINFO: {
2024 struct usbdevfs_hub_portinfo *info = user_data;
2027 spin_lock_irq(&device_state_lock);
2028 if (hdev->devnum <= 0)
2031 info->nports = hdev->maxchild;
2032 for (i = 0; i < info->nports; i++) {
2033 if (hub->ports[i]->child == NULL)
2037 hub->ports[i]->child->devnum;
2040 spin_unlock_irq(&device_state_lock);
2042 return info->nports + 1;
2051 * Allow user programs to claim ports on a hub. When a device is attached
2052 * to one of these "claimed" ports, the program will "own" the device.
2054 static int find_port_owner(struct usb_device *hdev, unsigned port1,
2055 struct usb_dev_state ***ppowner)
2057 struct usb_hub *hub = usb_hub_to_struct_hub(hdev);
2059 if (hdev->state == USB_STATE_NOTATTACHED)
2061 if (port1 == 0 || port1 > hdev->maxchild)
2064 /* Devices not managed by the hub driver
2065 * will always have maxchild equal to 0.
2067 *ppowner = &(hub->ports[port1 - 1]->port_owner);
2071 /* In the following three functions, the caller must hold hdev's lock */
2072 int usb_hub_claim_port(struct usb_device *hdev, unsigned port1,
2073 struct usb_dev_state *owner)
2076 struct usb_dev_state **powner;
2078 rc = find_port_owner(hdev, port1, &powner);
2086 EXPORT_SYMBOL_GPL(usb_hub_claim_port);
2088 int usb_hub_release_port(struct usb_device *hdev, unsigned port1,
2089 struct usb_dev_state *owner)
2092 struct usb_dev_state **powner;
2094 rc = find_port_owner(hdev, port1, &powner);
2097 if (*powner != owner)
2102 EXPORT_SYMBOL_GPL(usb_hub_release_port);
2104 void usb_hub_release_all_ports(struct usb_device *hdev, struct usb_dev_state *owner)
2106 struct usb_hub *hub = usb_hub_to_struct_hub(hdev);
2109 for (n = 0; n < hdev->maxchild; n++) {
2110 if (hub->ports[n]->port_owner == owner)
2111 hub->ports[n]->port_owner = NULL;
2116 /* The caller must hold udev's lock */
2117 bool usb_device_is_owned(struct usb_device *udev)
2119 struct usb_hub *hub;
2121 if (udev->state == USB_STATE_NOTATTACHED || !udev->parent)
2123 hub = usb_hub_to_struct_hub(udev->parent);
2124 return !!hub->ports[udev->portnum - 1]->port_owner;
2127 static void update_port_device_state(struct usb_device *udev)
2129 struct usb_hub *hub;
2130 struct usb_port *port_dev;
2133 hub = usb_hub_to_struct_hub(udev->parent);
2136 * The Link Layer Validation System Driver (lvstest)
2137 * has a test step to unbind the hub before running the
2138 * rest of the procedure. This triggers hub_disconnect
2139 * which will set the hub's maxchild to 0, further
2140 * resulting in usb_hub_to_struct_hub returning NULL.
2143 port_dev = hub->ports[udev->portnum - 1];
2144 WRITE_ONCE(port_dev->state, udev->state);
2145 sysfs_notify_dirent(port_dev->state_kn);
2150 static void recursively_mark_NOTATTACHED(struct usb_device *udev)
2152 struct usb_hub *hub = usb_hub_to_struct_hub(udev);
2155 for (i = 0; i < udev->maxchild; ++i) {
2156 if (hub->ports[i]->child)
2157 recursively_mark_NOTATTACHED(hub->ports[i]->child);
2159 if (udev->state == USB_STATE_SUSPENDED)
2160 udev->active_duration -= jiffies;
2161 udev->state = USB_STATE_NOTATTACHED;
2162 update_port_device_state(udev);
2166 * usb_set_device_state - change a device's current state (usbcore, hcds)
2167 * @udev: pointer to device whose state should be changed
2168 * @new_state: new state value to be stored
2170 * udev->state is _not_ fully protected by the device lock. Although
2171 * most transitions are made only while holding the lock, the state can
2172 * can change to USB_STATE_NOTATTACHED at almost any time. This
2173 * is so that devices can be marked as disconnected as soon as possible,
2174 * without having to wait for any semaphores to be released. As a result,
2175 * all changes to any device's state must be protected by the
2176 * device_state_lock spinlock.
2178 * Once a device has been added to the device tree, all changes to its state
2179 * should be made using this routine. The state should _not_ be set directly.
2181 * If udev->state is already USB_STATE_NOTATTACHED then no change is made.
2182 * Otherwise udev->state is set to new_state, and if new_state is
2183 * USB_STATE_NOTATTACHED then all of udev's descendants' states are also set
2184 * to USB_STATE_NOTATTACHED.
2186 void usb_set_device_state(struct usb_device *udev,
2187 enum usb_device_state new_state)
2189 unsigned long flags;
2192 spin_lock_irqsave(&device_state_lock, flags);
2193 if (udev->state == USB_STATE_NOTATTACHED)
2195 else if (new_state != USB_STATE_NOTATTACHED) {
2197 /* root hub wakeup capabilities are managed out-of-band
2198 * and may involve silicon errata ... ignore them here.
2201 if (udev->state == USB_STATE_SUSPENDED
2202 || new_state == USB_STATE_SUSPENDED)
2203 ; /* No change to wakeup settings */
2204 else if (new_state == USB_STATE_CONFIGURED)
2205 wakeup = (udev->quirks &
2206 USB_QUIRK_IGNORE_REMOTE_WAKEUP) ? 0 :
2207 udev->actconfig->desc.bmAttributes &
2208 USB_CONFIG_ATT_WAKEUP;
2212 if (udev->state == USB_STATE_SUSPENDED &&
2213 new_state != USB_STATE_SUSPENDED)
2214 udev->active_duration -= jiffies;
2215 else if (new_state == USB_STATE_SUSPENDED &&
2216 udev->state != USB_STATE_SUSPENDED)
2217 udev->active_duration += jiffies;
2218 udev->state = new_state;
2219 update_port_device_state(udev);
2221 recursively_mark_NOTATTACHED(udev);
2222 spin_unlock_irqrestore(&device_state_lock, flags);
2224 device_set_wakeup_capable(&udev->dev, wakeup);
2226 EXPORT_SYMBOL_GPL(usb_set_device_state);
2229 * Choose a device number.
2231 * Device numbers are used as filenames in usbfs. On USB-1.1 and
2232 * USB-2.0 buses they are also used as device addresses, however on
2233 * USB-3.0 buses the address is assigned by the controller hardware
2234 * and it usually is not the same as the device number.
2236 * Devices connected under xHCI are not as simple. The host controller
2237 * supports virtualization, so the hardware assigns device addresses and
2238 * the HCD must setup data structures before issuing a set address
2239 * command to the hardware.
2241 static void choose_devnum(struct usb_device *udev)
2244 struct usb_bus *bus = udev->bus;
2246 /* be safe when more hub events are proceed in parallel */
2247 mutex_lock(&bus->devnum_next_mutex);
2249 /* Try to allocate the next devnum beginning at bus->devnum_next. */
2250 devnum = find_next_zero_bit(bus->devmap, 128, bus->devnum_next);
2252 devnum = find_next_zero_bit(bus->devmap, 128, 1);
2253 bus->devnum_next = (devnum >= 127 ? 1 : devnum + 1);
2255 set_bit(devnum, bus->devmap);
2256 udev->devnum = devnum;
2258 mutex_unlock(&bus->devnum_next_mutex);
2261 static void release_devnum(struct usb_device *udev)
2263 if (udev->devnum > 0) {
2264 clear_bit(udev->devnum, udev->bus->devmap);
2269 static void update_devnum(struct usb_device *udev, int devnum)
2271 udev->devnum = devnum;
2273 udev->devaddr = (u8)devnum;
2276 static void hub_free_dev(struct usb_device *udev)
2278 struct usb_hcd *hcd = bus_to_hcd(udev->bus);
2280 /* Root hubs aren't real devices, so don't free HCD resources */
2281 if (hcd->driver->free_dev && udev->parent)
2282 hcd->driver->free_dev(hcd, udev);
2285 static void hub_disconnect_children(struct usb_device *udev)
2287 struct usb_hub *hub = usb_hub_to_struct_hub(udev);
2290 /* Free up all the children before we remove this device */
2291 for (i = 0; i < udev->maxchild; i++) {
2292 if (hub->ports[i]->child)
2293 usb_disconnect(&hub->ports[i]->child);
2298 * usb_disconnect - disconnect a device (usbcore-internal)
2299 * @pdev: pointer to device being disconnected
2301 * Context: task context, might sleep
2303 * Something got disconnected. Get rid of it and all of its children.
2305 * If *pdev is a normal device then the parent hub must already be locked.
2306 * If *pdev is a root hub then the caller must hold the usb_bus_idr_lock,
2307 * which protects the set of root hubs as well as the list of buses.
2309 * Only hub drivers (including virtual root hub drivers for host
2310 * controllers) should ever call this.
2312 * This call is synchronous, and may not be used in an interrupt context.
2314 void usb_disconnect(struct usb_device **pdev)
2316 struct usb_port *port_dev = NULL;
2317 struct usb_device *udev = *pdev;
2318 struct usb_hub *hub = NULL;
2321 /* mark the device as inactive, so any further urb submissions for
2322 * this device (and any of its children) will fail immediately.
2323 * this quiesces everything except pending urbs.
2325 usb_set_device_state(udev, USB_STATE_NOTATTACHED);
2326 dev_info(&udev->dev, "USB disconnect, device number %d\n",
2330 * Ensure that the pm runtime code knows that the USB device
2331 * is in the process of being disconnected.
2333 pm_runtime_barrier(&udev->dev);
2335 usb_lock_device(udev);
2337 hub_disconnect_children(udev);
2339 /* deallocate hcd/hardware state ... nuking all pending urbs and
2340 * cleaning up all state associated with the current configuration
2341 * so that the hardware is now fully quiesced.
2343 dev_dbg(&udev->dev, "unregistering device\n");
2344 usb_disable_device(udev, 0);
2345 usb_hcd_synchronize_unlinks(udev);
2348 port1 = udev->portnum;
2349 hub = usb_hub_to_struct_hub(udev->parent);
2350 port_dev = hub->ports[port1 - 1];
2352 sysfs_remove_link(&udev->dev.kobj, "port");
2353 sysfs_remove_link(&port_dev->dev.kobj, "device");
2356 * As usb_port_runtime_resume() de-references udev, make
2357 * sure no resumes occur during removal
2359 if (!test_and_set_bit(port1, hub->child_usage_bits))
2360 pm_runtime_get_sync(&port_dev->dev);
2362 typec_deattach(port_dev->connector, &udev->dev);
2365 usb_remove_ep_devs(&udev->ep0);
2366 usb_unlock_device(udev);
2368 if (udev->usb4_link)
2369 device_link_del(udev->usb4_link);
2371 /* Unregister the device. The device driver is responsible
2372 * for de-configuring the device and invoking the remove-device
2373 * notifier chain (used by usbfs and possibly others).
2375 device_del(&udev->dev);
2377 /* Free the device number and delete the parent's children[]
2378 * (or root_hub) pointer.
2380 release_devnum(udev);
2382 /* Avoid races with recursively_mark_NOTATTACHED() */
2383 spin_lock_irq(&device_state_lock);
2385 spin_unlock_irq(&device_state_lock);
2387 if (port_dev && test_and_clear_bit(port1, hub->child_usage_bits))
2388 pm_runtime_put(&port_dev->dev);
2392 put_device(&udev->dev);
2395 #ifdef CONFIG_USB_ANNOUNCE_NEW_DEVICES
2396 static void show_string(struct usb_device *udev, char *id, char *string)
2400 dev_info(&udev->dev, "%s: %s\n", id, string);
2403 static void announce_device(struct usb_device *udev)
2405 u16 bcdDevice = le16_to_cpu(udev->descriptor.bcdDevice);
2407 dev_info(&udev->dev,
2408 "New USB device found, idVendor=%04x, idProduct=%04x, bcdDevice=%2x.%02x\n",
2409 le16_to_cpu(udev->descriptor.idVendor),
2410 le16_to_cpu(udev->descriptor.idProduct),
2411 bcdDevice >> 8, bcdDevice & 0xff);
2412 dev_info(&udev->dev,
2413 "New USB device strings: Mfr=%d, Product=%d, SerialNumber=%d\n",
2414 udev->descriptor.iManufacturer,
2415 udev->descriptor.iProduct,
2416 udev->descriptor.iSerialNumber);
2417 show_string(udev, "Product", udev->product);
2418 show_string(udev, "Manufacturer", udev->manufacturer);
2419 show_string(udev, "SerialNumber", udev->serial);
2422 static inline void announce_device(struct usb_device *udev) { }
2427 * usb_enumerate_device_otg - FIXME (usbcore-internal)
2428 * @udev: newly addressed device (in ADDRESS state)
2430 * Finish enumeration for On-The-Go devices
2432 * Return: 0 if successful. A negative error code otherwise.
2434 static int usb_enumerate_device_otg(struct usb_device *udev)
2438 #ifdef CONFIG_USB_OTG
2440 * OTG-aware devices on OTG-capable root hubs may be able to use SRP,
2441 * to wake us after we've powered off VBUS; and HNP, switching roles
2442 * "host" to "peripheral". The OTG descriptor helps figure this out.
2444 if (!udev->bus->is_b_host
2446 && udev->parent == udev->bus->root_hub) {
2447 struct usb_otg_descriptor *desc = NULL;
2448 struct usb_bus *bus = udev->bus;
2449 unsigned port1 = udev->portnum;
2451 /* descriptor may appear anywhere in config */
2452 err = __usb_get_extra_descriptor(udev->rawdescriptors[0],
2453 le16_to_cpu(udev->config[0].desc.wTotalLength),
2454 USB_DT_OTG, (void **) &desc, sizeof(*desc));
2455 if (err || !(desc->bmAttributes & USB_OTG_HNP))
2458 dev_info(&udev->dev, "Dual-Role OTG device on %sHNP port\n",
2459 (port1 == bus->otg_port) ? "" : "non-");
2461 /* enable HNP before suspend, it's simpler */
2462 if (port1 == bus->otg_port) {
2463 bus->b_hnp_enable = 1;
2464 err = usb_control_msg(udev,
2465 usb_sndctrlpipe(udev, 0),
2466 USB_REQ_SET_FEATURE, 0,
2467 USB_DEVICE_B_HNP_ENABLE,
2469 USB_CTRL_SET_TIMEOUT);
2472 * OTG MESSAGE: report errors here,
2473 * customize to match your product.
2475 dev_err(&udev->dev, "can't set HNP mode: %d\n",
2477 bus->b_hnp_enable = 0;
2479 } else if (desc->bLength == sizeof
2480 (struct usb_otg_descriptor)) {
2482 * We are operating on a legacy OTP device
2483 * These should be told that they are operating
2484 * on the wrong port if we have another port that does
2487 if (bus->otg_port != 0) {
2488 /* Set a_alt_hnp_support for legacy otg device */
2489 err = usb_control_msg(udev,
2490 usb_sndctrlpipe(udev, 0),
2491 USB_REQ_SET_FEATURE, 0,
2492 USB_DEVICE_A_ALT_HNP_SUPPORT,
2494 USB_CTRL_SET_TIMEOUT);
2497 "set a_alt_hnp_support failed: %d\n",
2508 * usb_enumerate_device - Read device configs/intfs/otg (usbcore-internal)
2509 * @udev: newly addressed device (in ADDRESS state)
2511 * This is only called by usb_new_device() -- all comments that apply there
2512 * apply here wrt to environment.
2514 * If the device is WUSB and not authorized, we don't attempt to read
2515 * the string descriptors, as they will be errored out by the device
2516 * until it has been authorized.
2518 * Return: 0 if successful. A negative error code otherwise.
2520 static int usb_enumerate_device(struct usb_device *udev)
2523 struct usb_hcd *hcd = bus_to_hcd(udev->bus);
2525 if (udev->config == NULL) {
2526 err = usb_get_configuration(udev);
2529 dev_err(&udev->dev, "can't read configurations, error %d\n",
2535 /* read the standard strings and cache them if present */
2536 udev->product = usb_cache_string(udev, udev->descriptor.iProduct);
2537 udev->manufacturer = usb_cache_string(udev,
2538 udev->descriptor.iManufacturer);
2539 udev->serial = usb_cache_string(udev, udev->descriptor.iSerialNumber);
2541 err = usb_enumerate_device_otg(udev);
2545 if (IS_ENABLED(CONFIG_USB_OTG_PRODUCTLIST) && hcd->tpl_support &&
2546 !is_targeted(udev)) {
2547 /* Maybe it can talk to us, though we can't talk to it.
2548 * (Includes HNP test device.)
2550 if (IS_ENABLED(CONFIG_USB_OTG) && (udev->bus->b_hnp_enable
2551 || udev->bus->is_b_host)) {
2552 err = usb_port_suspend(udev, PMSG_AUTO_SUSPEND);
2554 dev_dbg(&udev->dev, "HNP fail, %d\n", err);
2559 usb_detect_interface_quirks(udev);
2564 static void set_usb_port_removable(struct usb_device *udev)
2566 struct usb_device *hdev = udev->parent;
2567 struct usb_hub *hub;
2568 u8 port = udev->portnum;
2569 u16 wHubCharacteristics;
2570 bool removable = true;
2572 dev_set_removable(&udev->dev, DEVICE_REMOVABLE_UNKNOWN);
2577 hub = usb_hub_to_struct_hub(udev->parent);
2580 * If the platform firmware has provided information about a port,
2581 * use that to determine whether it's removable.
2583 switch (hub->ports[udev->portnum - 1]->connect_type) {
2584 case USB_PORT_CONNECT_TYPE_HOT_PLUG:
2585 dev_set_removable(&udev->dev, DEVICE_REMOVABLE);
2587 case USB_PORT_CONNECT_TYPE_HARD_WIRED:
2588 case USB_PORT_NOT_USED:
2589 dev_set_removable(&udev->dev, DEVICE_FIXED);
2596 * Otherwise, check whether the hub knows whether a port is removable
2599 wHubCharacteristics = le16_to_cpu(hub->descriptor->wHubCharacteristics);
2601 if (!(wHubCharacteristics & HUB_CHAR_COMPOUND))
2604 if (hub_is_superspeed(hdev)) {
2605 if (le16_to_cpu(hub->descriptor->u.ss.DeviceRemovable)
2609 if (hub->descriptor->u.hs.DeviceRemovable[port / 8] & (1 << (port % 8)))
2614 dev_set_removable(&udev->dev, DEVICE_REMOVABLE);
2616 dev_set_removable(&udev->dev, DEVICE_FIXED);
2621 * usb_new_device - perform initial device setup (usbcore-internal)
2622 * @udev: newly addressed device (in ADDRESS state)
2624 * This is called with devices which have been detected but not fully
2625 * enumerated. The device descriptor is available, but not descriptors
2626 * for any device configuration. The caller must have locked either
2627 * the parent hub (if udev is a normal device) or else the
2628 * usb_bus_idr_lock (if udev is a root hub). The parent's pointer to
2629 * udev has already been installed, but udev is not yet visible through
2630 * sysfs or other filesystem code.
2632 * This call is synchronous, and may not be used in an interrupt context.
2634 * Only the hub driver or root-hub registrar should ever call this.
2636 * Return: Whether the device is configured properly or not. Zero if the
2637 * interface was registered with the driver core; else a negative errno
2641 int usb_new_device(struct usb_device *udev)
2646 /* Initialize non-root-hub device wakeup to disabled;
2647 * device (un)configuration controls wakeup capable
2648 * sysfs power/wakeup controls wakeup enabled/disabled
2650 device_init_wakeup(&udev->dev, 0);
2653 /* Tell the runtime-PM framework the device is active */
2654 pm_runtime_set_active(&udev->dev);
2655 pm_runtime_get_noresume(&udev->dev);
2656 pm_runtime_use_autosuspend(&udev->dev);
2657 pm_runtime_enable(&udev->dev);
2659 /* By default, forbid autosuspend for all devices. It will be
2660 * allowed for hubs during binding.
2662 usb_disable_autosuspend(udev);
2664 err = usb_enumerate_device(udev); /* Read descriptors */
2667 dev_dbg(&udev->dev, "udev %d, busnum %d, minor = %d\n",
2668 udev->devnum, udev->bus->busnum,
2669 (((udev->bus->busnum-1) * 128) + (udev->devnum-1)));
2670 /* export the usbdev device-node for libusb */
2671 udev->dev.devt = MKDEV(USB_DEVICE_MAJOR,
2672 (((udev->bus->busnum-1) * 128) + (udev->devnum-1)));
2674 /* Tell the world! */
2675 announce_device(udev);
2678 add_device_randomness(udev->serial, strlen(udev->serial));
2680 add_device_randomness(udev->product, strlen(udev->product));
2681 if (udev->manufacturer)
2682 add_device_randomness(udev->manufacturer,
2683 strlen(udev->manufacturer));
2685 device_enable_async_suspend(&udev->dev);
2687 /* check whether the hub or firmware marks this port as non-removable */
2688 set_usb_port_removable(udev);
2690 /* Register the device. The device driver is responsible
2691 * for configuring the device and invoking the add-device
2692 * notifier chain (used by usbfs and possibly others).
2694 err = device_add(&udev->dev);
2696 dev_err(&udev->dev, "can't device_add, error %d\n", err);
2700 /* Create link files between child device and usb port device. */
2702 struct usb_hub *hub = usb_hub_to_struct_hub(udev->parent);
2703 int port1 = udev->portnum;
2704 struct usb_port *port_dev = hub->ports[port1 - 1];
2706 err = sysfs_create_link(&udev->dev.kobj,
2707 &port_dev->dev.kobj, "port");
2711 err = sysfs_create_link(&port_dev->dev.kobj,
2712 &udev->dev.kobj, "device");
2714 sysfs_remove_link(&udev->dev.kobj, "port");
2718 if (!test_and_set_bit(port1, hub->child_usage_bits))
2719 pm_runtime_get_sync(&port_dev->dev);
2721 typec_attach(port_dev->connector, &udev->dev);
2724 (void) usb_create_ep_devs(&udev->dev, &udev->ep0, udev);
2725 usb_mark_last_busy(udev);
2726 pm_runtime_put_sync_autosuspend(&udev->dev);
2730 device_del(&udev->dev);
2732 usb_set_device_state(udev, USB_STATE_NOTATTACHED);
2733 pm_runtime_disable(&udev->dev);
2734 pm_runtime_set_suspended(&udev->dev);
2740 * usb_deauthorize_device - deauthorize a device (usbcore-internal)
2741 * @usb_dev: USB device
2743 * Move the USB device to a very basic state where interfaces are disabled
2744 * and the device is in fact unconfigured and unusable.
2746 * We share a lock (that we have) with device_del(), so we need to
2751 int usb_deauthorize_device(struct usb_device *usb_dev)
2753 usb_lock_device(usb_dev);
2754 if (usb_dev->authorized == 0)
2755 goto out_unauthorized;
2757 usb_dev->authorized = 0;
2758 usb_set_configuration(usb_dev, -1);
2761 usb_unlock_device(usb_dev);
2766 int usb_authorize_device(struct usb_device *usb_dev)
2770 usb_lock_device(usb_dev);
2771 if (usb_dev->authorized == 1)
2772 goto out_authorized;
2774 result = usb_autoresume_device(usb_dev);
2776 dev_err(&usb_dev->dev,
2777 "can't autoresume for authorization: %d\n", result);
2778 goto error_autoresume;
2781 usb_dev->authorized = 1;
2782 /* Choose and set the configuration. This registers the interfaces
2783 * with the driver core and lets interface drivers bind to them.
2785 c = usb_choose_configuration(usb_dev);
2787 result = usb_set_configuration(usb_dev, c);
2789 dev_err(&usb_dev->dev,
2790 "can't set config #%d, error %d\n", c, result);
2791 /* This need not be fatal. The user can try to
2792 * set other configurations. */
2795 dev_info(&usb_dev->dev, "authorized to connect\n");
2797 usb_autosuspend_device(usb_dev);
2800 usb_unlock_device(usb_dev); /* complements locktree */
2805 * get_port_ssp_rate - Match the extended port status to SSP rate
2806 * @hdev: The hub device
2807 * @ext_portstatus: extended port status
2809 * Match the extended port status speed id to the SuperSpeed Plus sublink speed
2810 * capability attributes. Base on the number of connected lanes and speed,
2811 * return the corresponding enum usb_ssp_rate.
2813 static enum usb_ssp_rate get_port_ssp_rate(struct usb_device *hdev,
2816 struct usb_ssp_cap_descriptor *ssp_cap;
2826 ssp_cap = hdev->bos->ssp_cap;
2830 speed_id = ext_portstatus & USB_EXT_PORT_STAT_RX_SPEED_ID;
2831 lanes = USB_EXT_PORT_RX_LANES(ext_portstatus) + 1;
2833 ssac = le32_to_cpu(ssp_cap->bmAttributes) &
2834 USB_SSP_SUBLINK_SPEED_ATTRIBS;
2836 for (i = 0; i <= ssac; i++) {
2839 attr = le32_to_cpu(ssp_cap->bmSublinkSpeedAttr[i]);
2840 ssid = FIELD_GET(USB_SSP_SUBLINK_SPEED_SSID, attr);
2841 if (speed_id == ssid) {
2847 * Note: currently asymmetric lane types are only
2848 * applicable for SSIC operate in SuperSpeed protocol
2850 type = FIELD_GET(USB_SSP_SUBLINK_SPEED_ST, attr);
2851 if (type == USB_SSP_SUBLINK_SPEED_ST_ASYM_RX ||
2852 type == USB_SSP_SUBLINK_SPEED_ST_ASYM_TX)
2855 if (FIELD_GET(USB_SSP_SUBLINK_SPEED_LP, attr) !=
2856 USB_SSP_SUBLINK_SPEED_LP_SSP)
2859 lse = FIELD_GET(USB_SSP_SUBLINK_SPEED_LSE, attr);
2860 mantissa = FIELD_GET(USB_SSP_SUBLINK_SPEED_LSM, attr);
2862 /* Convert to Gbps */
2863 for (; lse < USB_SSP_SUBLINK_SPEED_LSE_GBPS; lse++)
2866 if (mantissa >= 10 && lanes == 1)
2867 return USB_SSP_GEN_2x1;
2869 if (mantissa >= 10 && lanes == 2)
2870 return USB_SSP_GEN_2x2;
2872 if (mantissa >= 5 && lanes == 2)
2873 return USB_SSP_GEN_1x2;
2880 return USB_SSP_GEN_UNKNOWN;
2883 #ifdef CONFIG_USB_FEW_INIT_RETRIES
2884 #define PORT_RESET_TRIES 2
2885 #define SET_ADDRESS_TRIES 1
2886 #define GET_DESCRIPTOR_TRIES 1
2887 #define GET_MAXPACKET0_TRIES 1
2888 #define PORT_INIT_TRIES 4
2891 #define PORT_RESET_TRIES 5
2892 #define SET_ADDRESS_TRIES 2
2893 #define GET_DESCRIPTOR_TRIES 2
2894 #define GET_MAXPACKET0_TRIES 3
2895 #define PORT_INIT_TRIES 4
2896 #endif /* CONFIG_USB_FEW_INIT_RETRIES */
2898 #define DETECT_DISCONNECT_TRIES 5
2900 #define HUB_ROOT_RESET_TIME 60 /* times are in msec */
2901 #define HUB_SHORT_RESET_TIME 10
2902 #define HUB_BH_RESET_TIME 50
2903 #define HUB_LONG_RESET_TIME 200
2904 #define HUB_RESET_TIMEOUT 800
2906 static bool use_new_scheme(struct usb_device *udev, int retry,
2907 struct usb_port *port_dev)
2909 int old_scheme_first_port =
2910 (port_dev->quirks & USB_PORT_QUIRK_OLD_SCHEME) ||
2914 * "New scheme" enumeration causes an extra state transition to be
2915 * exposed to an xhci host and causes USB3 devices to receive control
2916 * commands in the default state. This has been seen to cause
2917 * enumeration failures, so disable this enumeration scheme for USB3
2920 if (udev->speed >= USB_SPEED_SUPER)
2924 * If use_both_schemes is set, use the first scheme (whichever
2925 * it is) for the larger half of the retries, then use the other
2926 * scheme. Otherwise, use the first scheme for all the retries.
2928 if (use_both_schemes && retry >= (PORT_INIT_TRIES + 1) / 2)
2929 return old_scheme_first_port; /* Second half */
2930 return !old_scheme_first_port; /* First half or all */
2933 /* Is a USB 3.0 port in the Inactive or Compliance Mode state?
2934 * Port warm reset is required to recover
2936 static bool hub_port_warm_reset_required(struct usb_hub *hub, int port1,
2941 if (!hub_is_superspeed(hub->hdev))
2944 if (test_bit(port1, hub->warm_reset_bits))
2947 link_state = portstatus & USB_PORT_STAT_LINK_STATE;
2948 return link_state == USB_SS_PORT_LS_SS_INACTIVE
2949 || link_state == USB_SS_PORT_LS_COMP_MOD;
2952 static int hub_port_wait_reset(struct usb_hub *hub, int port1,
2953 struct usb_device *udev, unsigned int delay, bool warm)
2955 int delay_time, ret;
2958 u32 ext_portstatus = 0;
2960 for (delay_time = 0;
2961 delay_time < HUB_RESET_TIMEOUT;
2962 delay_time += delay) {
2963 /* wait to give the device a chance to reset */
2966 /* read and decode port status */
2967 if (hub_is_superspeedplus(hub->hdev))
2968 ret = hub_ext_port_status(hub, port1,
2969 HUB_EXT_PORT_STATUS,
2970 &portstatus, &portchange,
2973 ret = usb_hub_port_status(hub, port1, &portstatus,
2979 * The port state is unknown until the reset completes.
2981 * On top of that, some chips may require additional time
2982 * to re-establish a connection after the reset is complete,
2983 * so also wait for the connection to be re-established.
2985 if (!(portstatus & USB_PORT_STAT_RESET) &&
2986 (portstatus & USB_PORT_STAT_CONNECTION))
2989 /* switch to the long delay after two short delay failures */
2990 if (delay_time >= 2 * HUB_SHORT_RESET_TIME)
2991 delay = HUB_LONG_RESET_TIME;
2993 dev_dbg(&hub->ports[port1 - 1]->dev,
2994 "not %sreset yet, waiting %dms\n",
2995 warm ? "warm " : "", delay);
2998 if ((portstatus & USB_PORT_STAT_RESET))
3001 if (hub_port_warm_reset_required(hub, port1, portstatus))
3004 /* Device went away? */
3005 if (!(portstatus & USB_PORT_STAT_CONNECTION))
3008 /* Retry if connect change is set but status is still connected.
3009 * A USB 3.0 connection may bounce if multiple warm resets were issued,
3010 * but the device may have successfully re-connected. Ignore it.
3012 if (!hub_is_superspeed(hub->hdev) &&
3013 (portchange & USB_PORT_STAT_C_CONNECTION)) {
3014 usb_clear_port_feature(hub->hdev, port1,
3015 USB_PORT_FEAT_C_CONNECTION);
3019 if (!(portstatus & USB_PORT_STAT_ENABLE))
3025 if (hub_is_superspeedplus(hub->hdev)) {
3026 /* extended portstatus Rx and Tx lane count are zero based */
3027 udev->rx_lanes = USB_EXT_PORT_RX_LANES(ext_portstatus) + 1;
3028 udev->tx_lanes = USB_EXT_PORT_TX_LANES(ext_portstatus) + 1;
3029 udev->ssp_rate = get_port_ssp_rate(hub->hdev, ext_portstatus);
3033 udev->ssp_rate = USB_SSP_GEN_UNKNOWN;
3035 if (udev->ssp_rate != USB_SSP_GEN_UNKNOWN)
3036 udev->speed = USB_SPEED_SUPER_PLUS;
3037 else if (hub_is_superspeed(hub->hdev))
3038 udev->speed = USB_SPEED_SUPER;
3039 else if (portstatus & USB_PORT_STAT_HIGH_SPEED)
3040 udev->speed = USB_SPEED_HIGH;
3041 else if (portstatus & USB_PORT_STAT_LOW_SPEED)
3042 udev->speed = USB_SPEED_LOW;
3044 udev->speed = USB_SPEED_FULL;
3048 /* Handle port reset and port warm(BH) reset (for USB3 protocol ports) */
3049 static int hub_port_reset(struct usb_hub *hub, int port1,
3050 struct usb_device *udev, unsigned int delay, bool warm)
3053 u16 portchange, portstatus;
3054 struct usb_port *port_dev = hub->ports[port1 - 1];
3055 int reset_recovery_time;
3057 if (!hub_is_superspeed(hub->hdev)) {
3059 dev_err(hub->intfdev, "only USB3 hub support "
3063 /* Block EHCI CF initialization during the port reset.
3064 * Some companion controllers don't like it when they mix.
3066 down_read(&ehci_cf_port_reset_rwsem);
3069 * If the caller hasn't explicitly requested a warm reset,
3070 * double check and see if one is needed.
3072 if (usb_hub_port_status(hub, port1, &portstatus,
3074 if (hub_port_warm_reset_required(hub, port1,
3078 clear_bit(port1, hub->warm_reset_bits);
3080 /* Reset the port */
3081 for (i = 0; i < PORT_RESET_TRIES; i++) {
3082 status = set_port_feature(hub->hdev, port1, (warm ?
3083 USB_PORT_FEAT_BH_PORT_RESET :
3084 USB_PORT_FEAT_RESET));
3085 if (status == -ENODEV) {
3086 ; /* The hub is gone */
3087 } else if (status) {
3088 dev_err(&port_dev->dev,
3089 "cannot %sreset (err = %d)\n",
3090 warm ? "warm " : "", status);
3092 status = hub_port_wait_reset(hub, port1, udev, delay,
3094 if (status && status != -ENOTCONN && status != -ENODEV)
3095 dev_dbg(hub->intfdev,
3096 "port_wait_reset: err = %d\n",
3101 * Check for disconnect or reset, and bail out after several
3102 * reset attempts to avoid warm reset loop.
3104 if (status == 0 || status == -ENOTCONN || status == -ENODEV ||
3105 (status == -EBUSY && i == PORT_RESET_TRIES - 1)) {
3106 usb_clear_port_feature(hub->hdev, port1,
3107 USB_PORT_FEAT_C_RESET);
3109 if (!hub_is_superspeed(hub->hdev))
3112 usb_clear_port_feature(hub->hdev, port1,
3113 USB_PORT_FEAT_C_BH_PORT_RESET);
3114 usb_clear_port_feature(hub->hdev, port1,
3115 USB_PORT_FEAT_C_PORT_LINK_STATE);
3118 usb_clear_port_feature(hub->hdev, port1,
3119 USB_PORT_FEAT_C_CONNECTION);
3122 * If a USB 3.0 device migrates from reset to an error
3123 * state, re-issue the warm reset.
3125 if (usb_hub_port_status(hub, port1,
3126 &portstatus, &portchange) < 0)
3129 if (!hub_port_warm_reset_required(hub, port1,
3134 * If the port is in SS.Inactive or Compliance Mode, the
3135 * hot or warm reset failed. Try another warm reset.
3138 dev_dbg(&port_dev->dev,
3139 "hot reset failed, warm reset\n");
3144 dev_dbg(&port_dev->dev,
3145 "not enabled, trying %sreset again...\n",
3146 warm ? "warm " : "");
3147 delay = HUB_LONG_RESET_TIME;
3150 dev_err(&port_dev->dev, "Cannot enable. Maybe the USB cable is bad?\n");
3154 if (port_dev->quirks & USB_PORT_QUIRK_FAST_ENUM)
3155 usleep_range(10000, 12000);
3157 /* TRSTRCY = 10 ms; plus some extra */
3158 reset_recovery_time = 10 + 40;
3160 /* Hub needs extra delay after resetting its port. */
3161 if (hub->hdev->quirks & USB_QUIRK_HUB_SLOW_RESET)
3162 reset_recovery_time += 100;
3164 msleep(reset_recovery_time);
3168 struct usb_hcd *hcd = bus_to_hcd(udev->bus);
3170 update_devnum(udev, 0);
3171 /* The xHC may think the device is already reset,
3172 * so ignore the status.
3174 if (hcd->driver->reset_device)
3175 hcd->driver->reset_device(hcd, udev);
3177 usb_set_device_state(udev, USB_STATE_DEFAULT);
3181 usb_set_device_state(udev, USB_STATE_NOTATTACHED);
3184 if (!hub_is_superspeed(hub->hdev))
3185 up_read(&ehci_cf_port_reset_rwsem);
3191 * hub_port_stop_enumerate - stop USB enumeration or ignore port events
3193 * @port1: port num of the port
3194 * @retries: port retries number of hub_port_init()
3197 * true: ignore port actions/events or give up connection attempts.
3198 * false: keep original behavior.
3200 * This function will be based on retries to check whether the port which is
3201 * marked with early_stop attribute would stop enumeration or ignore events.
3204 * This function didn't change anything if early_stop is not set, and it will
3205 * prevent all connection attempts when early_stop is set and the attempts of
3206 * the port are more than 1.
3208 static bool hub_port_stop_enumerate(struct usb_hub *hub, int port1, int retries)
3210 struct usb_port *port_dev = hub->ports[port1 - 1];
3212 if (port_dev->early_stop) {
3213 if (port_dev->ignore_event)
3217 * We want unsuccessful attempts to fail quickly.
3218 * Since some devices may need one failure during
3219 * port initialization, we allow two tries but no
3225 port_dev->ignore_event = 1;
3227 port_dev->ignore_event = 0;
3229 return port_dev->ignore_event;
3232 /* Check if a port is power on */
3233 int usb_port_is_power_on(struct usb_hub *hub, unsigned int portstatus)
3237 if (hub_is_superspeed(hub->hdev)) {
3238 if (portstatus & USB_SS_PORT_STAT_POWER)
3241 if (portstatus & USB_PORT_STAT_POWER)
3248 static void usb_lock_port(struct usb_port *port_dev)
3249 __acquires(&port_dev->status_lock)
3251 mutex_lock(&port_dev->status_lock);
3252 __acquire(&port_dev->status_lock);
3255 static void usb_unlock_port(struct usb_port *port_dev)
3256 __releases(&port_dev->status_lock)
3258 mutex_unlock(&port_dev->status_lock);
3259 __release(&port_dev->status_lock);
3264 /* Check if a port is suspended(USB2.0 port) or in U3 state(USB3.0 port) */
3265 static int port_is_suspended(struct usb_hub *hub, unsigned portstatus)
3269 if (hub_is_superspeed(hub->hdev)) {
3270 if ((portstatus & USB_PORT_STAT_LINK_STATE)
3271 == USB_SS_PORT_LS_U3)
3274 if (portstatus & USB_PORT_STAT_SUSPEND)
3281 /* Determine whether the device on a port is ready for a normal resume,
3282 * is ready for a reset-resume, or should be disconnected.
3284 static int check_port_resume_type(struct usb_device *udev,
3285 struct usb_hub *hub, int port1,
3286 int status, u16 portchange, u16 portstatus)
3288 struct usb_port *port_dev = hub->ports[port1 - 1];
3292 /* Is a warm reset needed to recover the connection? */
3293 if (status == 0 && udev->reset_resume
3294 && hub_port_warm_reset_required(hub, port1, portstatus)) {
3297 /* Is the device still present? */
3298 else if (status || port_is_suspended(hub, portstatus) ||
3299 !usb_port_is_power_on(hub, portstatus)) {
3302 } else if (!(portstatus & USB_PORT_STAT_CONNECTION)) {
3304 usleep_range(200, 300);
3305 status = usb_hub_port_status(hub, port1, &portstatus,
3312 /* Can't do a normal resume if the port isn't enabled,
3313 * so try a reset-resume instead.
3315 else if (!(portstatus & USB_PORT_STAT_ENABLE) && !udev->reset_resume) {
3316 if (udev->persist_enabled)
3317 udev->reset_resume = 1;
3323 dev_dbg(&port_dev->dev, "status %04x.%04x after resume, %d\n",
3324 portchange, portstatus, status);
3325 } else if (udev->reset_resume) {
3327 /* Late port handoff can set status-change bits */
3328 if (portchange & USB_PORT_STAT_C_CONNECTION)
3329 usb_clear_port_feature(hub->hdev, port1,
3330 USB_PORT_FEAT_C_CONNECTION);
3331 if (portchange & USB_PORT_STAT_C_ENABLE)
3332 usb_clear_port_feature(hub->hdev, port1,
3333 USB_PORT_FEAT_C_ENABLE);
3336 * Whatever made this reset-resume necessary may have
3337 * turned on the port1 bit in hub->change_bits. But after
3338 * a successful reset-resume we want the bit to be clear;
3339 * if it was on it would indicate that something happened
3340 * following the reset-resume.
3342 clear_bit(port1, hub->change_bits);
3348 int usb_disable_ltm(struct usb_device *udev)
3350 struct usb_hcd *hcd = bus_to_hcd(udev->bus);
3352 /* Check if the roothub and device supports LTM. */
3353 if (!usb_device_supports_ltm(hcd->self.root_hub) ||
3354 !usb_device_supports_ltm(udev))
3357 /* Clear Feature LTM Enable can only be sent if the device is
3360 if (!udev->actconfig)
3363 return usb_control_msg(udev, usb_sndctrlpipe(udev, 0),
3364 USB_REQ_CLEAR_FEATURE, USB_RECIP_DEVICE,
3365 USB_DEVICE_LTM_ENABLE, 0, NULL, 0,
3366 USB_CTRL_SET_TIMEOUT);
3368 EXPORT_SYMBOL_GPL(usb_disable_ltm);
3370 void usb_enable_ltm(struct usb_device *udev)
3372 struct usb_hcd *hcd = bus_to_hcd(udev->bus);
3374 /* Check if the roothub and device supports LTM. */
3375 if (!usb_device_supports_ltm(hcd->self.root_hub) ||
3376 !usb_device_supports_ltm(udev))
3379 /* Set Feature LTM Enable can only be sent if the device is
3382 if (!udev->actconfig)
3385 usb_control_msg(udev, usb_sndctrlpipe(udev, 0),
3386 USB_REQ_SET_FEATURE, USB_RECIP_DEVICE,
3387 USB_DEVICE_LTM_ENABLE, 0, NULL, 0,
3388 USB_CTRL_SET_TIMEOUT);
3390 EXPORT_SYMBOL_GPL(usb_enable_ltm);
3393 * usb_enable_remote_wakeup - enable remote wakeup for a device
3394 * @udev: target device
3396 * For USB-2 devices: Set the device's remote wakeup feature.
3398 * For USB-3 devices: Assume there's only one function on the device and
3399 * enable remote wake for the first interface. FIXME if the interface
3400 * association descriptor shows there's more than one function.
3402 static int usb_enable_remote_wakeup(struct usb_device *udev)
3404 if (udev->speed < USB_SPEED_SUPER)
3405 return usb_control_msg(udev, usb_sndctrlpipe(udev, 0),
3406 USB_REQ_SET_FEATURE, USB_RECIP_DEVICE,
3407 USB_DEVICE_REMOTE_WAKEUP, 0, NULL, 0,
3408 USB_CTRL_SET_TIMEOUT);
3410 return usb_control_msg(udev, usb_sndctrlpipe(udev, 0),
3411 USB_REQ_SET_FEATURE, USB_RECIP_INTERFACE,
3412 USB_INTRF_FUNC_SUSPEND,
3413 USB_INTRF_FUNC_SUSPEND_RW |
3414 USB_INTRF_FUNC_SUSPEND_LP,
3415 NULL, 0, USB_CTRL_SET_TIMEOUT);
3419 * usb_disable_remote_wakeup - disable remote wakeup for a device
3420 * @udev: target device
3422 * For USB-2 devices: Clear the device's remote wakeup feature.
3424 * For USB-3 devices: Assume there's only one function on the device and
3425 * disable remote wake for the first interface. FIXME if the interface
3426 * association descriptor shows there's more than one function.
3428 static int usb_disable_remote_wakeup(struct usb_device *udev)
3430 if (udev->speed < USB_SPEED_SUPER)
3431 return usb_control_msg(udev, usb_sndctrlpipe(udev, 0),
3432 USB_REQ_CLEAR_FEATURE, USB_RECIP_DEVICE,
3433 USB_DEVICE_REMOTE_WAKEUP, 0, NULL, 0,
3434 USB_CTRL_SET_TIMEOUT);
3436 return usb_control_msg(udev, usb_sndctrlpipe(udev, 0),
3437 USB_REQ_SET_FEATURE, USB_RECIP_INTERFACE,
3438 USB_INTRF_FUNC_SUSPEND, 0, NULL, 0,
3439 USB_CTRL_SET_TIMEOUT);
3442 /* Count of wakeup-enabled devices at or below udev */
3443 unsigned usb_wakeup_enabled_descendants(struct usb_device *udev)
3445 struct usb_hub *hub = usb_hub_to_struct_hub(udev);
3447 return udev->do_remote_wakeup +
3448 (hub ? hub->wakeup_enabled_descendants : 0);
3450 EXPORT_SYMBOL_GPL(usb_wakeup_enabled_descendants);
3453 * usb_port_suspend - suspend a usb device's upstream port
3454 * @udev: device that's no longer in active use, not a root hub
3455 * Context: must be able to sleep; device not locked; pm locks held
3457 * Suspends a USB device that isn't in active use, conserving power.
3458 * Devices may wake out of a suspend, if anything important happens,
3459 * using the remote wakeup mechanism. They may also be taken out of
3460 * suspend by the host, using usb_port_resume(). It's also routine
3461 * to disconnect devices while they are suspended.
3463 * This only affects the USB hardware for a device; its interfaces
3464 * (and, for hubs, child devices) must already have been suspended.
3466 * Selective port suspend reduces power; most suspended devices draw
3467 * less than 500 uA. It's also used in OTG, along with remote wakeup.
3468 * All devices below the suspended port are also suspended.
3470 * Devices leave suspend state when the host wakes them up. Some devices
3471 * also support "remote wakeup", where the device can activate the USB
3472 * tree above them to deliver data, such as a keypress or packet. In
3473 * some cases, this wakes the USB host.
3475 * Suspending OTG devices may trigger HNP, if that's been enabled
3476 * between a pair of dual-role devices. That will change roles, such
3477 * as from A-Host to A-Peripheral or from B-Host back to B-Peripheral.
3479 * Devices on USB hub ports have only one "suspend" state, corresponding
3480 * to ACPI D2, "may cause the device to lose some context".
3481 * State transitions include:
3483 * - suspend, resume ... when the VBUS power link stays live
3484 * - suspend, disconnect ... VBUS lost
3486 * Once VBUS drop breaks the circuit, the port it's using has to go through
3487 * normal re-enumeration procedures, starting with enabling VBUS power.
3488 * Other than re-initializing the hub (plug/unplug, except for root hubs),
3489 * Linux (2.6) currently has NO mechanisms to initiate that: no hub_wq
3490 * timer, no SRP, no requests through sysfs.
3492 * If Runtime PM isn't enabled or used, non-SuperSpeed devices may not get
3493 * suspended until their bus goes into global suspend (i.e., the root
3494 * hub is suspended). Nevertheless, we change @udev->state to
3495 * USB_STATE_SUSPENDED as this is the device's "logical" state. The actual
3496 * upstream port setting is stored in @udev->port_is_suspended.
3498 * Returns 0 on success, else negative errno.
3500 int usb_port_suspend(struct usb_device *udev, pm_message_t msg)
3502 struct usb_hub *hub = usb_hub_to_struct_hub(udev->parent);
3503 struct usb_port *port_dev = hub->ports[udev->portnum - 1];
3504 int port1 = udev->portnum;
3506 bool really_suspend = true;
3508 usb_lock_port(port_dev);
3510 /* enable remote wakeup when appropriate; this lets the device
3511 * wake up the upstream hub (including maybe the root hub).
3513 * NOTE: OTG devices may issue remote wakeup (or SRP) even when
3514 * we don't explicitly enable it here.
3516 if (udev->do_remote_wakeup) {
3517 status = usb_enable_remote_wakeup(udev);
3519 dev_dbg(&udev->dev, "won't remote wakeup, status %d\n",
3521 /* bail if autosuspend is requested */
3522 if (PMSG_IS_AUTO(msg))
3527 /* disable USB2 hardware LPM */
3528 usb_disable_usb2_hardware_lpm(udev);
3530 if (usb_disable_ltm(udev)) {
3531 dev_err(&udev->dev, "Failed to disable LTM before suspend\n");
3533 if (PMSG_IS_AUTO(msg))
3538 if (hub_is_superspeed(hub->hdev))
3539 status = hub_set_port_link_state(hub, port1, USB_SS_PORT_LS_U3);
3542 * For system suspend, we do not need to enable the suspend feature
3543 * on individual USB-2 ports. The devices will automatically go
3544 * into suspend a few ms after the root hub stops sending packets.
3545 * The USB 2.0 spec calls this "global suspend".
3547 * However, many USB hubs have a bug: They don't relay wakeup requests
3548 * from a downstream port if the port's suspend feature isn't on.
3549 * Therefore we will turn on the suspend feature if udev or any of its
3550 * descendants is enabled for remote wakeup.
3552 else if (PMSG_IS_AUTO(msg) || usb_wakeup_enabled_descendants(udev) > 0)
3553 status = set_port_feature(hub->hdev, port1,
3554 USB_PORT_FEAT_SUSPEND);
3556 really_suspend = false;
3560 /* Check if the port has been suspended for the timeout case
3561 * to prevent the suspended port from incorrect handling.
3563 if (status == -ETIMEDOUT) {
3565 u16 portstatus, portchange;
3567 portstatus = portchange = 0;
3568 ret = usb_hub_port_status(hub, port1, &portstatus,
3571 dev_dbg(&port_dev->dev,
3572 "suspend timeout, status %04x\n", portstatus);
3574 if (ret == 0 && port_is_suspended(hub, portstatus)) {
3580 dev_dbg(&port_dev->dev, "can't suspend, status %d\n", status);
3582 /* Try to enable USB3 LTM again */
3583 usb_enable_ltm(udev);
3585 /* Try to enable USB2 hardware LPM again */
3586 usb_enable_usb2_hardware_lpm(udev);
3588 if (udev->do_remote_wakeup)
3589 (void) usb_disable_remote_wakeup(udev);
3592 /* System sleep transitions should never fail */
3593 if (!PMSG_IS_AUTO(msg))
3597 dev_dbg(&udev->dev, "usb %ssuspend, wakeup %d\n",
3598 (PMSG_IS_AUTO(msg) ? "auto-" : ""),
3599 udev->do_remote_wakeup);
3600 if (really_suspend) {
3601 udev->port_is_suspended = 1;
3603 /* device has up to 10 msec to fully suspend */
3606 usb_set_device_state(udev, USB_STATE_SUSPENDED);
3609 if (status == 0 && !udev->do_remote_wakeup && udev->persist_enabled
3610 && test_and_clear_bit(port1, hub->child_usage_bits))
3611 pm_runtime_put_sync(&port_dev->dev);
3613 usb_mark_last_busy(hub->hdev);
3615 usb_unlock_port(port_dev);
3620 * If the USB "suspend" state is in use (rather than "global suspend"),
3621 * many devices will be individually taken out of suspend state using
3622 * special "resume" signaling. This routine kicks in shortly after
3623 * hardware resume signaling is finished, either because of selective
3624 * resume (by host) or remote wakeup (by device) ... now see what changed
3625 * in the tree that's rooted at this device.
3627 * If @udev->reset_resume is set then the device is reset before the
3628 * status check is done.
3630 static int finish_port_resume(struct usb_device *udev)
3635 /* caller owns the udev device lock */
3636 dev_dbg(&udev->dev, "%s\n",
3637 udev->reset_resume ? "finish reset-resume" : "finish resume");
3639 /* usb ch9 identifies four variants of SUSPENDED, based on what
3640 * state the device resumes to. Linux currently won't see the
3641 * first two on the host side; they'd be inside hub_port_init()
3642 * during many timeouts, but hub_wq can't suspend until later.
3644 usb_set_device_state(udev, udev->actconfig
3645 ? USB_STATE_CONFIGURED
3646 : USB_STATE_ADDRESS);
3648 /* 10.5.4.5 says not to reset a suspended port if the attached
3649 * device is enabled for remote wakeup. Hence the reset
3650 * operation is carried out here, after the port has been
3653 if (udev->reset_resume) {
3655 * If the device morphs or switches modes when it is reset,
3656 * we don't want to perform a reset-resume. We'll fail the
3657 * resume, which will cause a logical disconnect, and then
3658 * the device will be rediscovered.
3661 if (udev->quirks & USB_QUIRK_RESET)
3664 status = usb_reset_and_verify_device(udev);
3667 /* 10.5.4.5 says be sure devices in the tree are still there.
3668 * For now let's assume the device didn't go crazy on resume,
3669 * and device drivers will know about any resume quirks.
3673 status = usb_get_std_status(udev, USB_RECIP_DEVICE, 0, &devstatus);
3675 /* If a normal resume failed, try doing a reset-resume */
3676 if (status && !udev->reset_resume && udev->persist_enabled) {
3677 dev_dbg(&udev->dev, "retry with reset-resume\n");
3678 udev->reset_resume = 1;
3679 goto retry_reset_resume;
3684 dev_dbg(&udev->dev, "gone after usb resume? status %d\n",
3687 * There are a few quirky devices which violate the standard
3688 * by claiming to have remote wakeup enabled after a reset,
3689 * which crash if the feature is cleared, hence check for
3690 * udev->reset_resume
3692 } else if (udev->actconfig && !udev->reset_resume) {
3693 if (udev->speed < USB_SPEED_SUPER) {
3694 if (devstatus & (1 << USB_DEVICE_REMOTE_WAKEUP))
3695 status = usb_disable_remote_wakeup(udev);
3697 status = usb_get_std_status(udev, USB_RECIP_INTERFACE, 0,
3699 if (!status && devstatus & (USB_INTRF_STAT_FUNC_RW_CAP
3700 | USB_INTRF_STAT_FUNC_RW))
3701 status = usb_disable_remote_wakeup(udev);
3706 "disable remote wakeup, status %d\n",
3714 * There are some SS USB devices which take longer time for link training.
3715 * XHCI specs 4.19.4 says that when Link training is successful, port
3716 * sets CCS bit to 1. So if SW reads port status before successful link
3717 * training, then it will not find device to be present.
3718 * USB Analyzer log with such buggy devices show that in some cases
3719 * device switch on the RX termination after long delay of host enabling
3720 * the VBUS. In few other cases it has been seen that device fails to
3721 * negotiate link training in first attempt. It has been
3722 * reported till now that few devices take as long as 2000 ms to train
3723 * the link after host enabling its VBUS and termination. Following
3724 * routine implements a 2000 ms timeout for link training. If in a case
3725 * link trains before timeout, loop will exit earlier.
3727 * There are also some 2.0 hard drive based devices and 3.0 thumb
3728 * drives that, when plugged into a 2.0 only port, take a long
3729 * time to set CCS after VBUS enable.
3731 * FIXME: If a device was connected before suspend, but was removed
3732 * while system was asleep, then the loop in the following routine will
3733 * only exit at timeout.
3735 * This routine should only be called when persist is enabled.
3737 static int wait_for_connected(struct usb_device *udev,
3738 struct usb_hub *hub, int port1,
3739 u16 *portchange, u16 *portstatus)
3741 int status = 0, delay_ms = 0;
3743 while (delay_ms < 2000) {
3744 if (status || *portstatus & USB_PORT_STAT_CONNECTION)
3746 if (!usb_port_is_power_on(hub, *portstatus)) {
3752 status = usb_hub_port_status(hub, port1, portstatus, portchange);
3754 dev_dbg(&udev->dev, "Waited %dms for CONNECT\n", delay_ms);
3759 * usb_port_resume - re-activate a suspended usb device's upstream port
3760 * @udev: device to re-activate, not a root hub
3761 * Context: must be able to sleep; device not locked; pm locks held
3763 * This will re-activate the suspended device, increasing power usage
3764 * while letting drivers communicate again with its endpoints.
3765 * USB resume explicitly guarantees that the power session between
3766 * the host and the device is the same as it was when the device
3769 * If @udev->reset_resume is set then this routine won't check that the
3770 * port is still enabled. Furthermore, finish_port_resume() above will
3771 * reset @udev. The end result is that a broken power session can be
3772 * recovered and @udev will appear to persist across a loss of VBUS power.
3774 * For example, if a host controller doesn't maintain VBUS suspend current
3775 * during a system sleep or is reset when the system wakes up, all the USB
3776 * power sessions below it will be broken. This is especially troublesome
3777 * for mass-storage devices containing mounted filesystems, since the
3778 * device will appear to have disconnected and all the memory mappings
3779 * to it will be lost. Using the USB_PERSIST facility, the device can be
3780 * made to appear as if it had not disconnected.
3782 * This facility can be dangerous. Although usb_reset_and_verify_device() makes
3783 * every effort to insure that the same device is present after the
3784 * reset as before, it cannot provide a 100% guarantee. Furthermore it's
3785 * quite possible for a device to remain unaltered but its media to be
3786 * changed. If the user replaces a flash memory card while the system is
3787 * asleep, he will have only himself to blame when the filesystem on the
3788 * new card is corrupted and the system crashes.
3790 * Returns 0 on success, else negative errno.
3792 int usb_port_resume(struct usb_device *udev, pm_message_t msg)
3794 struct usb_hub *hub = usb_hub_to_struct_hub(udev->parent);
3795 struct usb_port *port_dev = hub->ports[udev->portnum - 1];
3796 int port1 = udev->portnum;
3798 u16 portchange, portstatus;
3800 if (!test_and_set_bit(port1, hub->child_usage_bits)) {
3801 status = pm_runtime_resume_and_get(&port_dev->dev);
3803 dev_dbg(&udev->dev, "can't resume usb port, status %d\n",
3809 usb_lock_port(port_dev);
3811 /* Skip the initial Clear-Suspend step for a remote wakeup */
3812 status = usb_hub_port_status(hub, port1, &portstatus, &portchange);
3813 if (status == 0 && !port_is_suspended(hub, portstatus)) {
3814 if (portchange & USB_PORT_STAT_C_SUSPEND)
3815 pm_wakeup_event(&udev->dev, 0);
3816 goto SuspendCleared;
3819 /* see 7.1.7.7; affects power usage, but not budgeting */
3820 if (hub_is_superspeed(hub->hdev))
3821 status = hub_set_port_link_state(hub, port1, USB_SS_PORT_LS_U0);
3823 status = usb_clear_port_feature(hub->hdev,
3824 port1, USB_PORT_FEAT_SUSPEND);
3826 dev_dbg(&port_dev->dev, "can't resume, status %d\n", status);
3828 /* drive resume for USB_RESUME_TIMEOUT msec */
3829 dev_dbg(&udev->dev, "usb %sresume\n",
3830 (PMSG_IS_AUTO(msg) ? "auto-" : ""));
3831 msleep(USB_RESUME_TIMEOUT);
3833 /* Virtual root hubs can trigger on GET_PORT_STATUS to
3834 * stop resume signaling. Then finish the resume
3837 status = usb_hub_port_status(hub, port1, &portstatus, &portchange);
3842 udev->port_is_suspended = 0;
3843 if (hub_is_superspeed(hub->hdev)) {
3844 if (portchange & USB_PORT_STAT_C_LINK_STATE)
3845 usb_clear_port_feature(hub->hdev, port1,
3846 USB_PORT_FEAT_C_PORT_LINK_STATE);
3848 if (portchange & USB_PORT_STAT_C_SUSPEND)
3849 usb_clear_port_feature(hub->hdev, port1,
3850 USB_PORT_FEAT_C_SUSPEND);
3853 /* TRSMRCY = 10 msec */
3857 if (udev->persist_enabled)
3858 status = wait_for_connected(udev, hub, port1, &portchange,
3861 status = check_port_resume_type(udev,
3862 hub, port1, status, portchange, portstatus);
3864 status = finish_port_resume(udev);
3866 dev_dbg(&udev->dev, "can't resume, status %d\n", status);
3867 hub_port_logical_disconnect(hub, port1);
3869 /* Try to enable USB2 hardware LPM */
3870 usb_enable_usb2_hardware_lpm(udev);
3872 /* Try to enable USB3 LTM */
3873 usb_enable_ltm(udev);
3876 usb_unlock_port(port_dev);
3881 int usb_remote_wakeup(struct usb_device *udev)
3885 usb_lock_device(udev);
3886 if (udev->state == USB_STATE_SUSPENDED) {
3887 dev_dbg(&udev->dev, "usb %sresume\n", "wakeup-");
3888 status = usb_autoresume_device(udev);
3890 /* Let the drivers do their thing, then... */
3891 usb_autosuspend_device(udev);
3894 usb_unlock_device(udev);
3898 /* Returns 1 if there was a remote wakeup and a connect status change. */
3899 static int hub_handle_remote_wakeup(struct usb_hub *hub, unsigned int port,
3900 u16 portstatus, u16 portchange)
3901 __must_hold(&port_dev->status_lock)
3903 struct usb_port *port_dev = hub->ports[port - 1];
3904 struct usb_device *hdev;
3905 struct usb_device *udev;
3906 int connect_change = 0;
3911 udev = port_dev->child;
3912 if (!hub_is_superspeed(hdev)) {
3913 if (!(portchange & USB_PORT_STAT_C_SUSPEND))
3915 usb_clear_port_feature(hdev, port, USB_PORT_FEAT_C_SUSPEND);
3917 link_state = portstatus & USB_PORT_STAT_LINK_STATE;
3918 if (!udev || udev->state != USB_STATE_SUSPENDED ||
3919 (link_state != USB_SS_PORT_LS_U0 &&
3920 link_state != USB_SS_PORT_LS_U1 &&
3921 link_state != USB_SS_PORT_LS_U2))
3926 /* TRSMRCY = 10 msec */
3929 usb_unlock_port(port_dev);
3930 ret = usb_remote_wakeup(udev);
3931 usb_lock_port(port_dev);
3936 hub_port_disable(hub, port, 1);
3938 dev_dbg(&port_dev->dev, "resume, status %d\n", ret);
3939 return connect_change;
3942 static int check_ports_changed(struct usb_hub *hub)
3946 for (port1 = 1; port1 <= hub->hdev->maxchild; ++port1) {
3947 u16 portstatus, portchange;
3950 status = usb_hub_port_status(hub, port1, &portstatus, &portchange);
3951 if (!status && portchange)
3957 static int hub_suspend(struct usb_interface *intf, pm_message_t msg)
3959 struct usb_hub *hub = usb_get_intfdata(intf);
3960 struct usb_device *hdev = hub->hdev;
3964 * Warn if children aren't already suspended.
3965 * Also, add up the number of wakeup-enabled descendants.
3967 hub->wakeup_enabled_descendants = 0;
3968 for (port1 = 1; port1 <= hdev->maxchild; port1++) {
3969 struct usb_port *port_dev = hub->ports[port1 - 1];
3970 struct usb_device *udev = port_dev->child;
3972 if (udev && udev->can_submit) {
3973 dev_warn(&port_dev->dev, "device %s not suspended yet\n",
3974 dev_name(&udev->dev));
3975 if (PMSG_IS_AUTO(msg))
3979 hub->wakeup_enabled_descendants +=
3980 usb_wakeup_enabled_descendants(udev);
3983 if (hdev->do_remote_wakeup && hub->quirk_check_port_auto_suspend) {
3984 /* check if there are changes pending on hub ports */
3985 if (check_ports_changed(hub)) {
3986 if (PMSG_IS_AUTO(msg))
3988 pm_wakeup_event(&hdev->dev, 2000);
3992 if (hub_is_superspeed(hdev) && hdev->do_remote_wakeup) {
3993 /* Enable hub to send remote wakeup for all ports. */
3994 for (port1 = 1; port1 <= hdev->maxchild; port1++) {
3995 set_port_feature(hdev,
3997 USB_PORT_FEAT_REMOTE_WAKE_CONNECT |
3998 USB_PORT_FEAT_REMOTE_WAKE_DISCONNECT |
3999 USB_PORT_FEAT_REMOTE_WAKE_OVER_CURRENT,
4000 USB_PORT_FEAT_REMOTE_WAKE_MASK);
4004 dev_dbg(&intf->dev, "%s\n", __func__);
4006 /* stop hub_wq and related activity */
4007 hub_quiesce(hub, HUB_SUSPEND);
4011 /* Report wakeup requests from the ports of a resuming root hub */
4012 static void report_wakeup_requests(struct usb_hub *hub)
4014 struct usb_device *hdev = hub->hdev;
4015 struct usb_device *udev;
4016 struct usb_hcd *hcd;
4017 unsigned long resuming_ports;
4021 return; /* Not a root hub */
4023 hcd = bus_to_hcd(hdev->bus);
4024 if (hcd->driver->get_resuming_ports) {
4027 * The get_resuming_ports() method returns a bitmap (origin 0)
4028 * of ports which have started wakeup signaling but have not
4029 * yet finished resuming. During system resume we will
4030 * resume all the enabled ports, regardless of any wakeup
4031 * signals, which means the wakeup requests would be lost.
4032 * To prevent this, report them to the PM core here.
4034 resuming_ports = hcd->driver->get_resuming_ports(hcd);
4035 for (i = 0; i < hdev->maxchild; ++i) {
4036 if (test_bit(i, &resuming_ports)) {
4037 udev = hub->ports[i]->child;
4039 pm_wakeup_event(&udev->dev, 0);
4045 static int hub_resume(struct usb_interface *intf)
4047 struct usb_hub *hub = usb_get_intfdata(intf);
4049 dev_dbg(&intf->dev, "%s\n", __func__);
4050 hub_activate(hub, HUB_RESUME);
4053 * This should be called only for system resume, not runtime resume.
4054 * We can't tell the difference here, so some wakeup requests will be
4055 * reported at the wrong time or more than once. This shouldn't
4056 * matter much, so long as they do get reported.
4058 report_wakeup_requests(hub);
4062 static int hub_reset_resume(struct usb_interface *intf)
4064 struct usb_hub *hub = usb_get_intfdata(intf);
4066 dev_dbg(&intf->dev, "%s\n", __func__);
4067 hub_activate(hub, HUB_RESET_RESUME);
4072 * usb_root_hub_lost_power - called by HCD if the root hub lost Vbus power
4073 * @rhdev: struct usb_device for the root hub
4075 * The USB host controller driver calls this function when its root hub
4076 * is resumed and Vbus power has been interrupted or the controller
4077 * has been reset. The routine marks @rhdev as having lost power.
4078 * When the hub driver is resumed it will take notice and carry out
4079 * power-session recovery for all the "USB-PERSIST"-enabled child devices;
4080 * the others will be disconnected.
4082 void usb_root_hub_lost_power(struct usb_device *rhdev)
4084 dev_notice(&rhdev->dev, "root hub lost power or was reset\n");
4085 rhdev->reset_resume = 1;
4087 EXPORT_SYMBOL_GPL(usb_root_hub_lost_power);
4089 static const char * const usb3_lpm_names[] = {
4097 * Send a Set SEL control transfer to the device, prior to enabling
4098 * device-initiated U1 or U2. This lets the device know the exit latencies from
4099 * the time the device initiates a U1 or U2 exit, to the time it will receive a
4100 * packet from the host.
4102 * This function will fail if the SEL or PEL values for udev are greater than
4103 * the maximum allowed values for the link state to be enabled.
4105 static int usb_req_set_sel(struct usb_device *udev)
4107 struct usb_set_sel_req *sel_values;
4108 unsigned long long u1_sel;
4109 unsigned long long u1_pel;
4110 unsigned long long u2_sel;
4111 unsigned long long u2_pel;
4114 if (!udev->parent || udev->speed < USB_SPEED_SUPER || !udev->lpm_capable)
4117 /* Convert SEL and PEL stored in ns to us */
4118 u1_sel = DIV_ROUND_UP(udev->u1_params.sel, 1000);
4119 u1_pel = DIV_ROUND_UP(udev->u1_params.pel, 1000);
4120 u2_sel = DIV_ROUND_UP(udev->u2_params.sel, 1000);
4121 u2_pel = DIV_ROUND_UP(udev->u2_params.pel, 1000);
4124 * Make sure that the calculated SEL and PEL values for the link
4125 * state we're enabling aren't bigger than the max SEL/PEL
4126 * value that will fit in the SET SEL control transfer.
4127 * Otherwise the device would get an incorrect idea of the exit
4128 * latency for the link state, and could start a device-initiated
4129 * U1/U2 when the exit latencies are too high.
4131 if (u1_sel > USB3_LPM_MAX_U1_SEL_PEL ||
4132 u1_pel > USB3_LPM_MAX_U1_SEL_PEL ||
4133 u2_sel > USB3_LPM_MAX_U2_SEL_PEL ||
4134 u2_pel > USB3_LPM_MAX_U2_SEL_PEL) {
4135 dev_dbg(&udev->dev, "Device-initiated U1/U2 disabled due to long SEL or PEL\n");
4140 * usb_enable_lpm() can be called as part of a failed device reset,
4141 * which may be initiated by an error path of a mass storage driver.
4142 * Therefore, use GFP_NOIO.
4144 sel_values = kmalloc(sizeof *(sel_values), GFP_NOIO);
4148 sel_values->u1_sel = u1_sel;
4149 sel_values->u1_pel = u1_pel;
4150 sel_values->u2_sel = cpu_to_le16(u2_sel);
4151 sel_values->u2_pel = cpu_to_le16(u2_pel);
4153 ret = usb_control_msg(udev, usb_sndctrlpipe(udev, 0),
4157 sel_values, sizeof *(sel_values),
4158 USB_CTRL_SET_TIMEOUT);
4162 udev->lpm_devinit_allow = 1;
4168 * Enable or disable device-initiated U1 or U2 transitions.
4170 static int usb_set_device_initiated_lpm(struct usb_device *udev,
4171 enum usb3_link_state state, bool enable)
4178 feature = USB_DEVICE_U1_ENABLE;
4181 feature = USB_DEVICE_U2_ENABLE;
4184 dev_warn(&udev->dev, "%s: Can't %s non-U1 or U2 state.\n",
4185 __func__, str_enable_disable(enable));
4189 if (udev->state != USB_STATE_CONFIGURED) {
4190 dev_dbg(&udev->dev, "%s: Can't %s %s state "
4191 "for unconfigured device.\n",
4192 __func__, str_enable_disable(enable),
4193 usb3_lpm_names[state]);
4199 * Now send the control transfer to enable device-initiated LPM
4200 * for either U1 or U2.
4202 ret = usb_control_msg(udev, usb_sndctrlpipe(udev, 0),
4203 USB_REQ_SET_FEATURE,
4207 USB_CTRL_SET_TIMEOUT);
4209 ret = usb_control_msg(udev, usb_sndctrlpipe(udev, 0),
4210 USB_REQ_CLEAR_FEATURE,
4214 USB_CTRL_SET_TIMEOUT);
4217 dev_warn(&udev->dev, "%s of device-initiated %s failed.\n",
4218 str_enable_disable(enable), usb3_lpm_names[state]);
4224 static int usb_set_lpm_timeout(struct usb_device *udev,
4225 enum usb3_link_state state, int timeout)
4232 feature = USB_PORT_FEAT_U1_TIMEOUT;
4235 feature = USB_PORT_FEAT_U2_TIMEOUT;
4238 dev_warn(&udev->dev, "%s: Can't set timeout for non-U1 or U2 state.\n",
4243 if (state == USB3_LPM_U1 && timeout > USB3_LPM_U1_MAX_TIMEOUT &&
4244 timeout != USB3_LPM_DEVICE_INITIATED) {
4245 dev_warn(&udev->dev, "Failed to set %s timeout to 0x%x, "
4246 "which is a reserved value.\n",
4247 usb3_lpm_names[state], timeout);
4251 ret = set_port_feature(udev->parent,
4252 USB_PORT_LPM_TIMEOUT(timeout) | udev->portnum,
4255 dev_warn(&udev->dev, "Failed to set %s timeout to 0x%x,"
4256 "error code %i\n", usb3_lpm_names[state],
4260 if (state == USB3_LPM_U1)
4261 udev->u1_params.timeout = timeout;
4263 udev->u2_params.timeout = timeout;
4268 * Don't allow device intiated U1/U2 if device isn't in the configured state,
4269 * or the system exit latency + one bus interval is greater than the minimum
4270 * service interval of any active periodic endpoint. See USB 3.2 section 9.4.9
4272 static bool usb_device_may_initiate_lpm(struct usb_device *udev,
4273 enum usb3_link_state state)
4275 unsigned int sel; /* us */
4278 if (!udev->lpm_devinit_allow || !udev->actconfig)
4281 if (state == USB3_LPM_U1)
4282 sel = DIV_ROUND_UP(udev->u1_params.sel, 1000);
4283 else if (state == USB3_LPM_U2)
4284 sel = DIV_ROUND_UP(udev->u2_params.sel, 1000);
4288 for (i = 0; i < udev->actconfig->desc.bNumInterfaces; i++) {
4289 struct usb_interface *intf;
4290 struct usb_endpoint_descriptor *desc;
4291 unsigned int interval;
4293 intf = udev->actconfig->interface[i];
4297 for (j = 0; j < intf->cur_altsetting->desc.bNumEndpoints; j++) {
4298 desc = &intf->cur_altsetting->endpoint[j].desc;
4300 if (usb_endpoint_xfer_int(desc) ||
4301 usb_endpoint_xfer_isoc(desc)) {
4302 interval = (1 << (desc->bInterval - 1)) * 125;
4303 if (sel + 125 > interval)
4312 * Enable the hub-initiated U1/U2 idle timeouts, and enable device-initiated
4315 * We will attempt to enable U1 or U2, but there are no guarantees that the
4316 * control transfers to set the hub timeout or enable device-initiated U1/U2
4317 * will be successful.
4319 * If the control transfer to enable device-initiated U1/U2 entry fails, then
4320 * hub-initiated U1/U2 will be disabled.
4322 * If we cannot set the parent hub U1/U2 timeout, we attempt to let the xHCI
4323 * driver know about it. If that call fails, it should be harmless, and just
4324 * take up more slightly more bus bandwidth for unnecessary U1/U2 exit latency.
4326 static int usb_enable_link_state(struct usb_hcd *hcd, struct usb_device *udev,
4327 enum usb3_link_state state)
4333 /* Skip if the device BOS descriptor couldn't be read */
4337 u1_mel = udev->bos->ss_cap->bU1devExitLat;
4338 u2_mel = udev->bos->ss_cap->bU2DevExitLat;
4340 /* If the device says it doesn't have *any* exit latency to come out of
4341 * U1 or U2, it's probably lying. Assume it doesn't implement that link
4344 if ((state == USB3_LPM_U1 && u1_mel == 0) ||
4345 (state == USB3_LPM_U2 && u2_mel == 0))
4348 /* We allow the host controller to set the U1/U2 timeout internally
4349 * first, so that it can change its schedule to account for the
4350 * additional latency to send data to a device in a lower power
4353 timeout = hcd->driver->enable_usb3_lpm_timeout(hcd, udev, state);
4355 /* xHCI host controller doesn't want to enable this LPM state. */
4360 dev_warn(&udev->dev, "Could not enable %s link state, "
4361 "xHCI error %i.\n", usb3_lpm_names[state],
4366 if (usb_set_lpm_timeout(udev, state, timeout)) {
4367 /* If we can't set the parent hub U1/U2 timeout,
4368 * device-initiated LPM won't be allowed either, so let the xHCI
4369 * host know that this link state won't be enabled.
4371 hcd->driver->disable_usb3_lpm_timeout(hcd, udev, state);
4375 if (state == USB3_LPM_U1)
4376 udev->usb3_lpm_u1_enabled = 1;
4377 else if (state == USB3_LPM_U2)
4378 udev->usb3_lpm_u2_enabled = 1;
4383 * Disable the hub-initiated U1/U2 idle timeouts, and disable device-initiated
4386 * If this function returns -EBUSY, the parent hub will still allow U1/U2 entry.
4387 * If zero is returned, the parent will not allow the link to go into U1/U2.
4389 * If zero is returned, device-initiated U1/U2 entry may still be enabled, but
4390 * it won't have an effect on the bus link state because the parent hub will
4391 * still disallow device-initiated U1/U2 entry.
4393 * If zero is returned, the xHCI host controller may still think U1/U2 entry is
4394 * possible. The result will be slightly more bus bandwidth will be taken up
4395 * (to account for U1/U2 exit latency), but it should be harmless.
4397 static int usb_disable_link_state(struct usb_hcd *hcd, struct usb_device *udev,
4398 enum usb3_link_state state)
4405 dev_warn(&udev->dev, "%s: Can't disable non-U1 or U2 state.\n",
4410 if (usb_set_lpm_timeout(udev, state, 0))
4413 if (hcd->driver->disable_usb3_lpm_timeout(hcd, udev, state))
4414 dev_warn(&udev->dev, "Could not disable xHCI %s timeout, "
4415 "bus schedule bandwidth may be impacted.\n",
4416 usb3_lpm_names[state]);
4418 /* As soon as usb_set_lpm_timeout(0) return 0, hub initiated LPM
4419 * is disabled. Hub will disallows link to enter U1/U2 as well,
4420 * even device is initiating LPM. Hence LPM is disabled if hub LPM
4421 * timeout set to 0, no matter device-initiated LPM is disabled or
4424 if (state == USB3_LPM_U1)
4425 udev->usb3_lpm_u1_enabled = 0;
4426 else if (state == USB3_LPM_U2)
4427 udev->usb3_lpm_u2_enabled = 0;
4433 * Disable hub-initiated and device-initiated U1 and U2 entry.
4434 * Caller must own the bandwidth_mutex.
4436 * This will call usb_enable_lpm() on failure, which will decrement
4437 * lpm_disable_count, and will re-enable LPM if lpm_disable_count reaches zero.
4439 int usb_disable_lpm(struct usb_device *udev)
4441 struct usb_hcd *hcd;
4444 if (!udev || !udev->parent ||
4445 udev->speed < USB_SPEED_SUPER ||
4446 !udev->lpm_capable ||
4447 udev->state < USB_STATE_CONFIGURED)
4450 hcd = bus_to_hcd(udev->bus);
4451 if (!hcd || !hcd->driver->disable_usb3_lpm_timeout)
4454 udev->lpm_disable_count++;
4455 if ((udev->u1_params.timeout == 0 && udev->u2_params.timeout == 0))
4458 /* If LPM is enabled, attempt to disable it. */
4459 if (usb_disable_link_state(hcd, udev, USB3_LPM_U1))
4460 goto disable_failed;
4461 if (usb_disable_link_state(hcd, udev, USB3_LPM_U2))
4462 goto disable_failed;
4464 err = usb_set_device_initiated_lpm(udev, USB3_LPM_U1, false);
4466 usb_set_device_initiated_lpm(udev, USB3_LPM_U2, false);
4471 udev->lpm_disable_count--;
4475 EXPORT_SYMBOL_GPL(usb_disable_lpm);
4477 /* Grab the bandwidth_mutex before calling usb_disable_lpm() */
4478 int usb_unlocked_disable_lpm(struct usb_device *udev)
4480 struct usb_hcd *hcd = bus_to_hcd(udev->bus);
4486 mutex_lock(hcd->bandwidth_mutex);
4487 ret = usb_disable_lpm(udev);
4488 mutex_unlock(hcd->bandwidth_mutex);
4492 EXPORT_SYMBOL_GPL(usb_unlocked_disable_lpm);
4495 * Attempt to enable device-initiated and hub-initiated U1 and U2 entry. The
4496 * xHCI host policy may prevent U1 or U2 from being enabled.
4498 * Other callers may have disabled link PM, so U1 and U2 entry will be disabled
4499 * until the lpm_disable_count drops to zero. Caller must own the
4502 void usb_enable_lpm(struct usb_device *udev)
4504 struct usb_hcd *hcd;
4505 struct usb_hub *hub;
4506 struct usb_port *port_dev;
4508 if (!udev || !udev->parent ||
4509 udev->speed < USB_SPEED_SUPER ||
4510 !udev->lpm_capable ||
4511 udev->state < USB_STATE_CONFIGURED)
4514 udev->lpm_disable_count--;
4515 hcd = bus_to_hcd(udev->bus);
4516 /* Double check that we can both enable and disable LPM.
4517 * Device must be configured to accept set feature U1/U2 timeout.
4519 if (!hcd || !hcd->driver->enable_usb3_lpm_timeout ||
4520 !hcd->driver->disable_usb3_lpm_timeout)
4523 if (udev->lpm_disable_count > 0)
4526 hub = usb_hub_to_struct_hub(udev->parent);
4530 port_dev = hub->ports[udev->portnum - 1];
4532 if (port_dev->usb3_lpm_u1_permit)
4533 if (usb_enable_link_state(hcd, udev, USB3_LPM_U1))
4536 if (port_dev->usb3_lpm_u2_permit)
4537 if (usb_enable_link_state(hcd, udev, USB3_LPM_U2))
4541 * Enable device initiated U1/U2 with a SetFeature(U1/U2_ENABLE) request
4542 * if system exit latency is short enough and device is configured
4544 if (usb_device_may_initiate_lpm(udev, USB3_LPM_U1)) {
4545 if (usb_set_device_initiated_lpm(udev, USB3_LPM_U1, true))
4548 if (usb_device_may_initiate_lpm(udev, USB3_LPM_U2))
4549 usb_set_device_initiated_lpm(udev, USB3_LPM_U2, true);
4552 EXPORT_SYMBOL_GPL(usb_enable_lpm);
4554 /* Grab the bandwidth_mutex before calling usb_enable_lpm() */
4555 void usb_unlocked_enable_lpm(struct usb_device *udev)
4557 struct usb_hcd *hcd = bus_to_hcd(udev->bus);
4562 mutex_lock(hcd->bandwidth_mutex);
4563 usb_enable_lpm(udev);
4564 mutex_unlock(hcd->bandwidth_mutex);
4566 EXPORT_SYMBOL_GPL(usb_unlocked_enable_lpm);
4568 /* usb3 devices use U3 for disabled, make sure remote wakeup is disabled */
4569 static void hub_usb3_port_prepare_disable(struct usb_hub *hub,
4570 struct usb_port *port_dev)
4572 struct usb_device *udev = port_dev->child;
4575 if (udev && udev->port_is_suspended && udev->do_remote_wakeup) {
4576 ret = hub_set_port_link_state(hub, port_dev->portnum,
4579 msleep(USB_RESUME_TIMEOUT);
4580 ret = usb_disable_remote_wakeup(udev);
4583 dev_warn(&udev->dev,
4584 "Port disable: can't disable remote wake\n");
4585 udev->do_remote_wakeup = 0;
4589 #else /* CONFIG_PM */
4591 #define hub_suspend NULL
4592 #define hub_resume NULL
4593 #define hub_reset_resume NULL
4595 static inline void hub_usb3_port_prepare_disable(struct usb_hub *hub,
4596 struct usb_port *port_dev) { }
4598 int usb_disable_lpm(struct usb_device *udev)
4602 EXPORT_SYMBOL_GPL(usb_disable_lpm);
4604 void usb_enable_lpm(struct usb_device *udev) { }
4605 EXPORT_SYMBOL_GPL(usb_enable_lpm);
4607 int usb_unlocked_disable_lpm(struct usb_device *udev)
4611 EXPORT_SYMBOL_GPL(usb_unlocked_disable_lpm);
4613 void usb_unlocked_enable_lpm(struct usb_device *udev) { }
4614 EXPORT_SYMBOL_GPL(usb_unlocked_enable_lpm);
4616 int usb_disable_ltm(struct usb_device *udev)
4620 EXPORT_SYMBOL_GPL(usb_disable_ltm);
4622 void usb_enable_ltm(struct usb_device *udev) { }
4623 EXPORT_SYMBOL_GPL(usb_enable_ltm);
4625 static int hub_handle_remote_wakeup(struct usb_hub *hub, unsigned int port,
4626 u16 portstatus, u16 portchange)
4631 static int usb_req_set_sel(struct usb_device *udev)
4636 #endif /* CONFIG_PM */
4639 * USB-3 does not have a similar link state as USB-2 that will avoid negotiating
4640 * a connection with a plugged-in cable but will signal the host when the cable
4641 * is unplugged. Disable remote wake and set link state to U3 for USB-3 devices
4643 static int hub_port_disable(struct usb_hub *hub, int port1, int set_state)
4645 struct usb_port *port_dev = hub->ports[port1 - 1];
4646 struct usb_device *hdev = hub->hdev;
4650 if (hub_is_superspeed(hub->hdev)) {
4651 hub_usb3_port_prepare_disable(hub, port_dev);
4652 ret = hub_set_port_link_state(hub, port_dev->portnum,
4655 ret = usb_clear_port_feature(hdev, port1,
4656 USB_PORT_FEAT_ENABLE);
4659 if (port_dev->child && set_state)
4660 usb_set_device_state(port_dev->child, USB_STATE_NOTATTACHED);
4661 if (ret && ret != -ENODEV)
4662 dev_err(&port_dev->dev, "cannot disable (err = %d)\n", ret);
4667 * usb_port_disable - disable a usb device's upstream port
4668 * @udev: device to disable
4669 * Context: @udev locked, must be able to sleep.
4671 * Disables a USB device that isn't in active use.
4673 int usb_port_disable(struct usb_device *udev)
4675 struct usb_hub *hub = usb_hub_to_struct_hub(udev->parent);
4677 return hub_port_disable(hub, udev->portnum, 0);
4680 /* USB 2.0 spec, 7.1.7.3 / fig 7-29:
4682 * Between connect detection and reset signaling there must be a delay
4683 * of 100ms at least for debounce and power-settling. The corresponding
4684 * timer shall restart whenever the downstream port detects a disconnect.
4686 * Apparently there are some bluetooth and irda-dongles and a number of
4687 * low-speed devices for which this debounce period may last over a second.
4688 * Not covered by the spec - but easy to deal with.
4690 * This implementation uses a 1500ms total debounce timeout; if the
4691 * connection isn't stable by then it returns -ETIMEDOUT. It checks
4692 * every 25ms for transient disconnects. When the port status has been
4693 * unchanged for 100ms it returns the port status.
4695 int hub_port_debounce(struct usb_hub *hub, int port1, bool must_be_connected)
4698 u16 portchange, portstatus;
4699 unsigned connection = 0xffff;
4700 int total_time, stable_time = 0;
4701 struct usb_port *port_dev = hub->ports[port1 - 1];
4703 for (total_time = 0; ; total_time += HUB_DEBOUNCE_STEP) {
4704 ret = usb_hub_port_status(hub, port1, &portstatus, &portchange);
4708 if (!(portchange & USB_PORT_STAT_C_CONNECTION) &&
4709 (portstatus & USB_PORT_STAT_CONNECTION) == connection) {
4710 if (!must_be_connected ||
4711 (connection == USB_PORT_STAT_CONNECTION))
4712 stable_time += HUB_DEBOUNCE_STEP;
4713 if (stable_time >= HUB_DEBOUNCE_STABLE)
4717 connection = portstatus & USB_PORT_STAT_CONNECTION;
4720 if (portchange & USB_PORT_STAT_C_CONNECTION) {
4721 usb_clear_port_feature(hub->hdev, port1,
4722 USB_PORT_FEAT_C_CONNECTION);
4725 if (total_time >= HUB_DEBOUNCE_TIMEOUT)
4727 msleep(HUB_DEBOUNCE_STEP);
4730 dev_dbg(&port_dev->dev, "debounce total %dms stable %dms status 0x%x\n",
4731 total_time, stable_time, portstatus);
4733 if (stable_time < HUB_DEBOUNCE_STABLE)
4738 void usb_ep0_reinit(struct usb_device *udev)
4740 usb_disable_endpoint(udev, 0 + USB_DIR_IN, true);
4741 usb_disable_endpoint(udev, 0 + USB_DIR_OUT, true);
4742 usb_enable_endpoint(udev, &udev->ep0, true);
4744 EXPORT_SYMBOL_GPL(usb_ep0_reinit);
4746 static int hub_set_address(struct usb_device *udev, int devnum)
4749 unsigned int timeout_ms = USB_CTRL_SET_TIMEOUT;
4750 struct usb_hcd *hcd = bus_to_hcd(udev->bus);
4751 struct usb_hub *hub = usb_hub_to_struct_hub(udev->parent);
4753 if (hub->hdev->quirks & USB_QUIRK_SHORT_SET_ADDRESS_REQ_TIMEOUT)
4754 timeout_ms = USB_SHORT_SET_ADDRESS_REQ_TIMEOUT;
4757 * The host controller will choose the device address,
4758 * instead of the core having chosen it earlier
4760 if (!hcd->driver->address_device && devnum <= 1)
4762 if (udev->state == USB_STATE_ADDRESS)
4764 if (udev->state != USB_STATE_DEFAULT)
4766 if (hcd->driver->address_device)
4767 retval = hcd->driver->address_device(hcd, udev, timeout_ms);
4769 retval = usb_control_msg(udev, usb_sndctrlpipe(udev, 0),
4770 USB_REQ_SET_ADDRESS, 0, devnum, 0,
4771 NULL, 0, timeout_ms);
4773 update_devnum(udev, devnum);
4774 /* Device now using proper address. */
4775 usb_set_device_state(udev, USB_STATE_ADDRESS);
4776 usb_ep0_reinit(udev);
4782 * There are reports of USB 3.0 devices that say they support USB 2.0 Link PM
4783 * when they're plugged into a USB 2.0 port, but they don't work when LPM is
4786 * Only enable USB 2.0 Link PM if the port is internal (hardwired), or the
4787 * device says it supports the new USB 2.0 Link PM errata by setting the BESL
4788 * support bit in the BOS descriptor.
4790 static void hub_set_initial_usb2_lpm_policy(struct usb_device *udev)
4792 struct usb_hub *hub = usb_hub_to_struct_hub(udev->parent);
4793 int connect_type = USB_PORT_CONNECT_TYPE_UNKNOWN;
4795 if (!udev->usb2_hw_lpm_capable || !udev->bos)
4799 connect_type = hub->ports[udev->portnum - 1]->connect_type;
4801 if ((udev->bos->ext_cap->bmAttributes & cpu_to_le32(USB_BESL_SUPPORT)) ||
4802 connect_type == USB_PORT_CONNECT_TYPE_HARD_WIRED) {
4803 udev->usb2_hw_lpm_allowed = 1;
4804 usb_enable_usb2_hardware_lpm(udev);
4808 static int hub_enable_device(struct usb_device *udev)
4810 struct usb_hcd *hcd = bus_to_hcd(udev->bus);
4812 if (!hcd->driver->enable_device)
4814 if (udev->state == USB_STATE_ADDRESS)
4816 if (udev->state != USB_STATE_DEFAULT)
4819 return hcd->driver->enable_device(hcd, udev);
4823 * Get the bMaxPacketSize0 value during initialization by reading the
4824 * device's device descriptor. Since we don't already know this value,
4825 * the transfer is unsafe and it ignores I/O errors, only testing for
4826 * reasonable received values.
4828 * For "old scheme" initialization, size will be 8 so we read just the
4829 * start of the device descriptor, which should work okay regardless of
4830 * the actual bMaxPacketSize0 value. For "new scheme" initialization,
4831 * size will be 64 (and buf will point to a sufficiently large buffer),
4832 * which might not be kosher according to the USB spec but it's what
4833 * Windows does and what many devices expect.
4835 * Returns: bMaxPacketSize0 or a negative error code.
4837 static int get_bMaxPacketSize0(struct usb_device *udev,
4838 struct usb_device_descriptor *buf, int size, bool first_time)
4843 * Retry on all errors; some devices are flakey.
4844 * 255 is for WUSB devices, we actually need to use
4845 * 512 (WUSB1.0[4.8.1]).
4847 for (i = 0; i < GET_MAXPACKET0_TRIES; ++i) {
4848 /* Start with invalid values in case the transfer fails */
4849 buf->bDescriptorType = buf->bMaxPacketSize0 = 0;
4850 rc = usb_control_msg(udev, usb_rcvctrlpipe(udev, 0),
4851 USB_REQ_GET_DESCRIPTOR, USB_DIR_IN,
4852 USB_DT_DEVICE << 8, 0,
4854 initial_descriptor_timeout);
4855 switch (buf->bMaxPacketSize0) {
4856 case 8: case 16: case 32: case 64: case 9:
4857 if (buf->bDescriptorType == USB_DT_DEVICE) {
4858 rc = buf->bMaxPacketSize0;
4869 * Some devices time out if they are powered on
4870 * when already connected. They need a second
4871 * reset, so return early. But only on the first
4872 * attempt, lest we get into a time-out/reset loop.
4874 if (rc > 0 || (rc == -ETIMEDOUT && first_time &&
4875 udev->speed > USB_SPEED_FULL))
4881 #define GET_DESCRIPTOR_BUFSIZE 64
4883 /* Reset device, (re)assign address, get device descriptor.
4884 * Device connection must be stable, no more debouncing needed.
4885 * Returns device in USB_STATE_ADDRESS, except on error.
4887 * If this is called for an already-existing device (as part of
4888 * usb_reset_and_verify_device), the caller must own the device lock and
4889 * the port lock. For a newly detected device that is not accessible
4890 * through any global pointers, it's not necessary to lock the device,
4891 * but it is still necessary to lock the port.
4893 * For a newly detected device, @dev_descr must be NULL. The device
4894 * descriptor retrieved from the device will then be stored in
4895 * @udev->descriptor. For an already existing device, @dev_descr
4896 * must be non-NULL. The device descriptor will be stored there,
4897 * not in @udev->descriptor, because descriptors for registered
4898 * devices are meant to be immutable.
4901 hub_port_init(struct usb_hub *hub, struct usb_device *udev, int port1,
4902 int retry_counter, struct usb_device_descriptor *dev_descr)
4904 struct usb_device *hdev = hub->hdev;
4905 struct usb_hcd *hcd = bus_to_hcd(hdev->bus);
4906 struct usb_port *port_dev = hub->ports[port1 - 1];
4907 int retries, operations, retval, i;
4908 unsigned delay = HUB_SHORT_RESET_TIME;
4909 enum usb_device_speed oldspeed = udev->speed;
4911 int devnum = udev->devnum;
4912 const char *driver_name;
4914 const bool initial = !dev_descr;
4916 struct usb_device_descriptor *buf, *descr;
4918 buf = kmalloc(GET_DESCRIPTOR_BUFSIZE, GFP_NOIO);
4922 /* root hub ports have a slightly longer reset period
4923 * (from USB 2.0 spec, section 7.1.7.5)
4925 if (!hdev->parent) {
4926 delay = HUB_ROOT_RESET_TIME;
4927 if (port1 == hdev->bus->otg_port)
4928 hdev->bus->b_hnp_enable = 0;
4931 /* Some low speed devices have problems with the quick delay, so */
4932 /* be a bit pessimistic with those devices. RHbug #23670 */
4933 if (oldspeed == USB_SPEED_LOW)
4934 delay = HUB_LONG_RESET_TIME;
4936 /* Reset the device; full speed may morph to high speed */
4937 /* FIXME a USB 2.0 device may morph into SuperSpeed on reset. */
4938 retval = hub_port_reset(hub, port1, udev, delay, false);
4939 if (retval < 0) /* error or disconnect */
4941 /* success, speed is known */
4945 /* Don't allow speed changes at reset, except usb 3.0 to faster */
4946 if (oldspeed != USB_SPEED_UNKNOWN && oldspeed != udev->speed &&
4947 !(oldspeed == USB_SPEED_SUPER && udev->speed > oldspeed)) {
4948 dev_dbg(&udev->dev, "device reset changed speed!\n");
4951 oldspeed = udev->speed;
4954 /* USB 2.0 section 5.5.3 talks about ep0 maxpacket ...
4955 * it's fixed size except for full speed devices.
4957 switch (udev->speed) {
4958 case USB_SPEED_SUPER_PLUS:
4959 case USB_SPEED_SUPER:
4960 udev->ep0.desc.wMaxPacketSize = cpu_to_le16(512);
4962 case USB_SPEED_HIGH: /* fixed at 64 */
4963 udev->ep0.desc.wMaxPacketSize = cpu_to_le16(64);
4965 case USB_SPEED_FULL: /* 8, 16, 32, or 64 */
4966 /* to determine the ep0 maxpacket size, try to read
4967 * the device descriptor to get bMaxPacketSize0 and
4968 * then correct our initial guess.
4970 udev->ep0.desc.wMaxPacketSize = cpu_to_le16(64);
4972 case USB_SPEED_LOW: /* fixed at 8 */
4973 udev->ep0.desc.wMaxPacketSize = cpu_to_le16(8);
4980 speed = usb_speed_string(udev->speed);
4983 * The controller driver may be NULL if the controller device
4984 * is the middle device between platform device and roothub.
4985 * This middle device may not need a device driver due to
4986 * all hardware control can be at platform device driver, this
4987 * platform device is usually a dual-role USB controller device.
4989 if (udev->bus->controller->driver)
4990 driver_name = udev->bus->controller->driver->name;
4992 driver_name = udev->bus->sysdev->driver->name;
4994 if (udev->speed < USB_SPEED_SUPER)
4995 dev_info(&udev->dev,
4996 "%s %s USB device number %d using %s\n",
4997 (initial ? "new" : "reset"), speed,
4998 devnum, driver_name);
5001 /* Set up TT records, if needed */
5003 udev->tt = hdev->tt;
5004 udev->ttport = hdev->ttport;
5005 } else if (udev->speed != USB_SPEED_HIGH
5006 && hdev->speed == USB_SPEED_HIGH) {
5008 dev_err(&udev->dev, "parent hub has no TT\n");
5012 udev->tt = &hub->tt;
5013 udev->ttport = port1;
5017 /* Why interleave GET_DESCRIPTOR and SET_ADDRESS this way?
5018 * Because device hardware and firmware is sometimes buggy in
5019 * this area, and this is how Linux has done it for ages.
5020 * Change it cautiously.
5022 * NOTE: If use_new_scheme() is true we will start by issuing
5023 * a 64-byte GET_DESCRIPTOR request. This is what Windows does,
5024 * so it may help with some non-standards-compliant devices.
5025 * Otherwise we start with SET_ADDRESS and then try to read the
5026 * first 8 bytes of the device descriptor to get the ep0 maxpacket
5029 do_new_scheme = use_new_scheme(udev, retry_counter, port_dev);
5031 for (retries = 0; retries < GET_DESCRIPTOR_TRIES; (++retries, msleep(100))) {
5032 if (hub_port_stop_enumerate(hub, port1, retries)) {
5037 if (do_new_scheme) {
5038 retval = hub_enable_device(udev);
5041 "hub failed to enable device, error %d\n",
5046 maxp0 = get_bMaxPacketSize0(udev, buf,
5047 GET_DESCRIPTOR_BUFSIZE, retries == 0);
5048 if (maxp0 > 0 && !initial &&
5049 maxp0 != udev->descriptor.bMaxPacketSize0) {
5050 dev_err(&udev->dev, "device reset changed ep0 maxpacket size!\n");
5055 retval = hub_port_reset(hub, port1, udev, delay, false);
5056 if (retval < 0) /* error or disconnect */
5058 if (oldspeed != udev->speed) {
5060 "device reset changed speed!\n");
5065 if (maxp0 != -ENODEV)
5066 dev_err(&udev->dev, "device descriptor read/64, error %d\n",
5073 for (operations = 0; operations < SET_ADDRESS_TRIES; ++operations) {
5074 retval = hub_set_address(udev, devnum);
5080 if (retval != -ENODEV)
5081 dev_err(&udev->dev, "device not accepting address %d, error %d\n",
5085 if (udev->speed >= USB_SPEED_SUPER) {
5086 devnum = udev->devnum;
5087 dev_info(&udev->dev,
5088 "%s SuperSpeed%s%s USB device number %d using %s\n",
5089 (udev->config) ? "reset" : "new",
5090 (udev->speed == USB_SPEED_SUPER_PLUS) ?
5092 (udev->ssp_rate == USB_SSP_GEN_2x2) ?
5094 (udev->ssp_rate == USB_SSP_GEN_2x1) ?
5096 (udev->ssp_rate == USB_SSP_GEN_1x2) ?
5098 devnum, driver_name);
5102 * cope with hardware quirkiness:
5103 * - let SET_ADDRESS settle, some device hardware wants it
5104 * - read ep0 maxpacket even for high and low speed,
5111 maxp0 = get_bMaxPacketSize0(udev, buf, 8, retries == 0);
5114 if (retval != -ENODEV)
5116 "device descriptor read/8, error %d\n",
5121 if (!initial && maxp0 != udev->descriptor.bMaxPacketSize0) {
5122 dev_err(&udev->dev, "device reset changed ep0 maxpacket size!\n");
5127 delay = udev->parent->hub_delay;
5128 udev->hub_delay = min_t(u32, delay,
5129 USB_TP_TRANSMISSION_DELAY_MAX);
5130 retval = usb_set_isoch_delay(udev);
5133 "Failed set isoch delay, error %d\n",
5144 * Check the ep0 maxpacket guess and correct it if necessary.
5145 * maxp0 is the value stored in the device descriptor;
5146 * i is the value it encodes (logarithmic for SuperSpeed or greater).
5149 if (udev->speed >= USB_SPEED_SUPER) {
5153 i = 0; /* Invalid */
5155 if (usb_endpoint_maxp(&udev->ep0.desc) == i) {
5156 ; /* Initial ep0 maxpacket guess is right */
5157 } else if (((udev->speed == USB_SPEED_FULL ||
5158 udev->speed == USB_SPEED_HIGH) &&
5159 (i == 8 || i == 16 || i == 32 || i == 64)) ||
5160 (udev->speed >= USB_SPEED_SUPER && i > 0)) {
5161 /* Initial guess is wrong; use the descriptor's value */
5162 if (udev->speed == USB_SPEED_FULL)
5163 dev_dbg(&udev->dev, "ep0 maxpacket = %d\n", i);
5165 dev_warn(&udev->dev, "Using ep0 maxpacket: %d\n", i);
5166 udev->ep0.desc.wMaxPacketSize = cpu_to_le16(i);
5167 usb_ep0_reinit(udev);
5169 /* Initial guess is wrong and descriptor's value is invalid */
5170 dev_err(&udev->dev, "Invalid ep0 maxpacket: %d\n", maxp0);
5175 descr = usb_get_device_descriptor(udev);
5176 if (IS_ERR(descr)) {
5177 retval = PTR_ERR(descr);
5178 if (retval != -ENODEV)
5179 dev_err(&udev->dev, "device descriptor read/all, error %d\n",
5184 udev->descriptor = *descr;
5186 *dev_descr = *descr;
5190 * Some superspeed devices have finished the link training process
5191 * and attached to a superspeed hub port, but the device descriptor
5192 * got from those devices show they aren't superspeed devices. Warm
5193 * reset the port attached by the devices can fix them.
5195 if ((udev->speed >= USB_SPEED_SUPER) &&
5196 (le16_to_cpu(udev->descriptor.bcdUSB) < 0x0300)) {
5197 dev_err(&udev->dev, "got a wrong device descriptor, warm reset device\n");
5198 hub_port_reset(hub, port1, udev, HUB_BH_RESET_TIME, true);
5203 usb_detect_quirks(udev);
5205 if (le16_to_cpu(udev->descriptor.bcdUSB) >= 0x0201) {
5206 retval = usb_get_bos_descriptor(udev);
5208 udev->lpm_capable = usb_device_supports_lpm(udev);
5209 udev->lpm_disable_count = 1;
5210 usb_set_lpm_parameters(udev);
5211 usb_req_set_sel(udev);
5216 /* notify HCD that we have a device connected and addressed */
5217 if (hcd->driver->update_device)
5218 hcd->driver->update_device(hcd, udev);
5219 hub_set_initial_usb2_lpm_policy(udev);
5222 hub_port_disable(hub, port1, 0);
5223 update_devnum(udev, devnum); /* for disconnect processing */
5230 check_highspeed(struct usb_hub *hub, struct usb_device *udev, int port1)
5232 struct usb_qualifier_descriptor *qual;
5235 if (udev->quirks & USB_QUIRK_DEVICE_QUALIFIER)
5238 qual = kmalloc(sizeof *qual, GFP_KERNEL);
5242 status = usb_get_descriptor(udev, USB_DT_DEVICE_QUALIFIER, 0,
5243 qual, sizeof *qual);
5244 if (status == sizeof *qual) {
5245 dev_info(&udev->dev, "not running at top speed; "
5246 "connect to a high speed hub\n");
5247 /* hub LEDs are probably harder to miss than syslog */
5248 if (hub->has_indicators) {
5249 hub->indicator[port1-1] = INDICATOR_GREEN_BLINK;
5250 queue_delayed_work(system_power_efficient_wq,
5258 hub_power_remaining(struct usb_hub *hub)
5260 struct usb_device *hdev = hub->hdev;
5264 if (!hub->limited_power)
5267 remaining = hdev->bus_mA - hub->descriptor->bHubContrCurrent;
5268 for (port1 = 1; port1 <= hdev->maxchild; ++port1) {
5269 struct usb_port *port_dev = hub->ports[port1 - 1];
5270 struct usb_device *udev = port_dev->child;
5276 if (hub_is_superspeed(udev))
5282 * Unconfigured devices may not use more than one unit load,
5283 * or 8mA for OTG ports
5285 if (udev->actconfig)
5286 delta = usb_get_max_power(udev, udev->actconfig);
5287 else if (port1 != udev->bus->otg_port || hdev->parent)
5291 if (delta > hub->mA_per_port)
5292 dev_warn(&port_dev->dev, "%dmA is over %umA budget!\n",
5293 delta, hub->mA_per_port);
5296 if (remaining < 0) {
5297 dev_warn(hub->intfdev, "%dmA over power budget!\n",
5305 static int descriptors_changed(struct usb_device *udev,
5306 struct usb_device_descriptor *new_device_descriptor,
5307 struct usb_host_bos *old_bos)
5311 unsigned serial_len = 0;
5313 unsigned old_length;
5317 if (memcmp(&udev->descriptor, new_device_descriptor,
5318 sizeof(*new_device_descriptor)) != 0)
5321 if ((old_bos && !udev->bos) || (!old_bos && udev->bos))
5324 len = le16_to_cpu(udev->bos->desc->wTotalLength);
5325 if (len != le16_to_cpu(old_bos->desc->wTotalLength))
5327 if (memcmp(udev->bos->desc, old_bos->desc, len))
5331 /* Since the idVendor, idProduct, and bcdDevice values in the
5332 * device descriptor haven't changed, we will assume the
5333 * Manufacturer and Product strings haven't changed either.
5334 * But the SerialNumber string could be different (e.g., a
5335 * different flash card of the same brand).
5338 serial_len = strlen(udev->serial) + 1;
5341 for (index = 0; index < udev->descriptor.bNumConfigurations; index++) {
5342 old_length = le16_to_cpu(udev->config[index].desc.wTotalLength);
5343 len = max(len, old_length);
5346 buf = kmalloc(len, GFP_NOIO);
5348 /* assume the worst */
5351 for (index = 0; index < udev->descriptor.bNumConfigurations; index++) {
5352 old_length = le16_to_cpu(udev->config[index].desc.wTotalLength);
5353 length = usb_get_descriptor(udev, USB_DT_CONFIG, index, buf,
5355 if (length != old_length) {
5356 dev_dbg(&udev->dev, "config index %d, error %d\n",
5361 if (memcmp(buf, udev->rawdescriptors[index], old_length)
5363 dev_dbg(&udev->dev, "config index %d changed (#%d)\n",
5365 ((struct usb_config_descriptor *) buf)->
5366 bConfigurationValue);
5372 if (!changed && serial_len) {
5373 length = usb_string(udev, udev->descriptor.iSerialNumber,
5375 if (length + 1 != serial_len) {
5376 dev_dbg(&udev->dev, "serial string error %d\n",
5379 } else if (memcmp(buf, udev->serial, length) != 0) {
5380 dev_dbg(&udev->dev, "serial string changed\n");
5389 static void hub_port_connect(struct usb_hub *hub, int port1, u16 portstatus,
5392 int status = -ENODEV;
5395 struct usb_device *hdev = hub->hdev;
5396 struct usb_hcd *hcd = bus_to_hcd(hdev->bus);
5397 struct usb_port *port_dev = hub->ports[port1 - 1];
5398 struct usb_device *udev = port_dev->child;
5399 static int unreliable_port = -1;
5402 /* Disconnect any existing devices under this port */
5404 if (hcd->usb_phy && !hdev->parent)
5405 usb_phy_notify_disconnect(hcd->usb_phy, udev->speed);
5406 usb_disconnect(&port_dev->child);
5409 /* We can forget about a "removed" device when there's a physical
5410 * disconnect or the connect status changes.
5412 if (!(portstatus & USB_PORT_STAT_CONNECTION) ||
5413 (portchange & USB_PORT_STAT_C_CONNECTION))
5414 clear_bit(port1, hub->removed_bits);
5416 if (portchange & (USB_PORT_STAT_C_CONNECTION |
5417 USB_PORT_STAT_C_ENABLE)) {
5418 status = hub_port_debounce_be_stable(hub, port1);
5420 if (status != -ENODEV &&
5421 port1 != unreliable_port &&
5423 dev_err(&port_dev->dev, "connect-debounce failed\n");
5424 portstatus &= ~USB_PORT_STAT_CONNECTION;
5425 unreliable_port = port1;
5427 portstatus = status;
5431 /* Return now if debouncing failed or nothing is connected or
5432 * the device was "removed".
5434 if (!(portstatus & USB_PORT_STAT_CONNECTION) ||
5435 test_bit(port1, hub->removed_bits)) {
5438 * maybe switch power back on (e.g. root hub was reset)
5439 * but only if the port isn't owned by someone else.
5441 if (hub_is_port_power_switchable(hub)
5442 && !usb_port_is_power_on(hub, portstatus)
5443 && !port_dev->port_owner)
5444 set_port_feature(hdev, port1, USB_PORT_FEAT_POWER);
5446 if (portstatus & USB_PORT_STAT_ENABLE)
5450 if (hub_is_superspeed(hub->hdev))
5457 for (i = 0; i < PORT_INIT_TRIES; i++) {
5458 if (hub_port_stop_enumerate(hub, port1, i)) {
5463 usb_lock_port(port_dev);
5464 mutex_lock(hcd->address0_mutex);
5465 retry_locked = true;
5466 /* reallocate for each attempt, since references
5467 * to the previous one can escape in various ways
5469 udev = usb_alloc_dev(hdev, hdev->bus, port1);
5471 dev_err(&port_dev->dev,
5472 "couldn't allocate usb_device\n");
5473 mutex_unlock(hcd->address0_mutex);
5474 usb_unlock_port(port_dev);
5478 usb_set_device_state(udev, USB_STATE_POWERED);
5479 udev->bus_mA = hub->mA_per_port;
5480 udev->level = hdev->level + 1;
5482 /* Devices connected to SuperSpeed hubs are USB 3.0 or later */
5483 if (hub_is_superspeed(hub->hdev))
5484 udev->speed = USB_SPEED_SUPER;
5486 udev->speed = USB_SPEED_UNKNOWN;
5488 choose_devnum(udev);
5489 if (udev->devnum <= 0) {
5490 status = -ENOTCONN; /* Don't retry */
5494 /* reset (non-USB 3.0 devices) and get descriptor */
5495 status = hub_port_init(hub, udev, port1, i, NULL);
5499 mutex_unlock(hcd->address0_mutex);
5500 usb_unlock_port(port_dev);
5501 retry_locked = false;
5503 if (udev->quirks & USB_QUIRK_DELAY_INIT)
5506 /* consecutive bus-powered hubs aren't reliable; they can
5507 * violate the voltage drop budget. if the new child has
5508 * a "powered" LED, users should notice we didn't enable it
5509 * (without reading syslog), even without per-port LEDs
5512 if (udev->descriptor.bDeviceClass == USB_CLASS_HUB
5513 && udev->bus_mA <= unit_load) {
5516 status = usb_get_std_status(udev, USB_RECIP_DEVICE, 0,
5519 dev_dbg(&udev->dev, "get status %d ?\n", status);
5522 if ((devstat & (1 << USB_DEVICE_SELF_POWERED)) == 0) {
5524 "can't connect bus-powered hub "
5526 if (hub->has_indicators) {
5527 hub->indicator[port1-1] =
5528 INDICATOR_AMBER_BLINK;
5530 system_power_efficient_wq,
5533 status = -ENOTCONN; /* Don't retry */
5538 /* check for devices running slower than they could */
5539 if (le16_to_cpu(udev->descriptor.bcdUSB) >= 0x0200
5540 && udev->speed == USB_SPEED_FULL
5541 && highspeed_hubs != 0)
5542 check_highspeed(hub, udev, port1);
5544 /* Store the parent's children[] pointer. At this point
5545 * udev becomes globally accessible, although presumably
5546 * no one will look at it until hdev is unlocked.
5550 mutex_lock(&usb_port_peer_mutex);
5552 /* We mustn't add new devices if the parent hub has
5553 * been disconnected; we would race with the
5554 * recursively_mark_NOTATTACHED() routine.
5556 spin_lock_irq(&device_state_lock);
5557 if (hdev->state == USB_STATE_NOTATTACHED)
5560 port_dev->child = udev;
5561 spin_unlock_irq(&device_state_lock);
5562 mutex_unlock(&usb_port_peer_mutex);
5564 /* Run it through the hoops (find a driver, etc) */
5566 status = usb_new_device(udev);
5568 mutex_lock(&usb_port_peer_mutex);
5569 spin_lock_irq(&device_state_lock);
5570 port_dev->child = NULL;
5571 spin_unlock_irq(&device_state_lock);
5572 mutex_unlock(&usb_port_peer_mutex);
5574 if (hcd->usb_phy && !hdev->parent)
5575 usb_phy_notify_connect(hcd->usb_phy,
5583 status = hub_power_remaining(hub);
5585 dev_dbg(hub->intfdev, "%dmA power budget left\n", status);
5590 hub_port_disable(hub, port1, 1);
5592 usb_ep0_reinit(udev);
5593 release_devnum(udev);
5596 mutex_unlock(hcd->address0_mutex);
5597 usb_unlock_port(port_dev);
5600 if ((status == -ENOTCONN) || (status == -ENOTSUPP))
5603 /* When halfway through our retry count, power-cycle the port */
5604 if (i == (PORT_INIT_TRIES - 1) / 2) {
5605 dev_info(&port_dev->dev, "attempt power cycle\n");
5606 usb_hub_set_port_power(hdev, hub, port1, false);
5607 msleep(2 * hub_power_on_good_delay(hub));
5608 usb_hub_set_port_power(hdev, hub, port1, true);
5609 msleep(hub_power_on_good_delay(hub));
5612 if (hub->hdev->parent ||
5613 !hcd->driver->port_handed_over ||
5614 !(hcd->driver->port_handed_over)(hcd, port1)) {
5615 if (status != -ENOTCONN && status != -ENODEV)
5616 dev_err(&port_dev->dev,
5617 "unable to enumerate USB device\n");
5621 hub_port_disable(hub, port1, 1);
5622 if (hcd->driver->relinquish_port && !hub->hdev->parent) {
5623 if (status != -ENOTCONN && status != -ENODEV)
5624 hcd->driver->relinquish_port(hcd, port1);
5628 /* Handle physical or logical connection change events.
5629 * This routine is called when:
5630 * a port connection-change occurs;
5631 * a port enable-change occurs (often caused by EMI);
5632 * usb_reset_and_verify_device() encounters changed descriptors (as from
5633 * a firmware download)
5634 * caller already locked the hub
5636 static void hub_port_connect_change(struct usb_hub *hub, int port1,
5637 u16 portstatus, u16 portchange)
5638 __must_hold(&port_dev->status_lock)
5640 struct usb_port *port_dev = hub->ports[port1 - 1];
5641 struct usb_device *udev = port_dev->child;
5642 struct usb_device_descriptor *descr;
5643 int status = -ENODEV;
5645 dev_dbg(&port_dev->dev, "status %04x, change %04x, %s\n", portstatus,
5646 portchange, portspeed(hub, portstatus));
5648 if (hub->has_indicators) {
5649 set_port_led(hub, port1, HUB_LED_AUTO);
5650 hub->indicator[port1-1] = INDICATOR_AUTO;
5653 #ifdef CONFIG_USB_OTG
5654 /* during HNP, don't repeat the debounce */
5655 if (hub->hdev->bus->is_b_host)
5656 portchange &= ~(USB_PORT_STAT_C_CONNECTION |
5657 USB_PORT_STAT_C_ENABLE);
5660 /* Try to resuscitate an existing device */
5661 if ((portstatus & USB_PORT_STAT_CONNECTION) && udev &&
5662 udev->state != USB_STATE_NOTATTACHED) {
5663 if (portstatus & USB_PORT_STAT_ENABLE) {
5665 * USB-3 connections are initialized automatically by
5666 * the hostcontroller hardware. Therefore check for
5667 * changed device descriptors before resuscitating the
5670 descr = usb_get_device_descriptor(udev);
5671 if (IS_ERR(descr)) {
5673 "can't read device descriptor %ld\n",
5676 if (descriptors_changed(udev, descr,
5679 "device descriptor has changed\n");
5681 status = 0; /* Nothing to do */
5686 } else if (udev->state == USB_STATE_SUSPENDED &&
5687 udev->persist_enabled) {
5688 /* For a suspended device, treat this as a
5689 * remote wakeup event.
5691 usb_unlock_port(port_dev);
5692 status = usb_remote_wakeup(udev);
5693 usb_lock_port(port_dev);
5696 /* Don't resuscitate */;
5699 clear_bit(port1, hub->change_bits);
5701 /* successfully revalidated the connection */
5705 usb_unlock_port(port_dev);
5706 hub_port_connect(hub, port1, portstatus, portchange);
5707 usb_lock_port(port_dev);
5710 /* Handle notifying userspace about hub over-current events */
5711 static void port_over_current_notify(struct usb_port *port_dev)
5713 char *envp[3] = { NULL, NULL, NULL };
5714 struct device *hub_dev;
5715 char *port_dev_path;
5717 sysfs_notify(&port_dev->dev.kobj, NULL, "over_current_count");
5719 hub_dev = port_dev->dev.parent;
5724 port_dev_path = kobject_get_path(&port_dev->dev.kobj, GFP_KERNEL);
5728 envp[0] = kasprintf(GFP_KERNEL, "OVER_CURRENT_PORT=%s", port_dev_path);
5732 envp[1] = kasprintf(GFP_KERNEL, "OVER_CURRENT_COUNT=%u",
5733 port_dev->over_current_count);
5737 kobject_uevent_env(&hub_dev->kobj, KOBJ_CHANGE, envp);
5742 kfree(port_dev_path);
5745 static void port_event(struct usb_hub *hub, int port1)
5746 __must_hold(&port_dev->status_lock)
5749 struct usb_port *port_dev = hub->ports[port1 - 1];
5750 struct usb_device *udev = port_dev->child;
5751 struct usb_device *hdev = hub->hdev;
5752 u16 portstatus, portchange;
5755 connect_change = test_bit(port1, hub->change_bits);
5756 clear_bit(port1, hub->event_bits);
5757 clear_bit(port1, hub->wakeup_bits);
5759 if (usb_hub_port_status(hub, port1, &portstatus, &portchange) < 0)
5762 if (portchange & USB_PORT_STAT_C_CONNECTION) {
5763 usb_clear_port_feature(hdev, port1, USB_PORT_FEAT_C_CONNECTION);
5767 if (portchange & USB_PORT_STAT_C_ENABLE) {
5768 if (!connect_change)
5769 dev_dbg(&port_dev->dev, "enable change, status %08x\n",
5771 usb_clear_port_feature(hdev, port1, USB_PORT_FEAT_C_ENABLE);
5774 * EM interference sometimes causes badly shielded USB devices
5775 * to be shutdown by the hub, this hack enables them again.
5776 * Works at least with mouse driver.
5778 if (!(portstatus & USB_PORT_STAT_ENABLE)
5779 && !connect_change && udev) {
5780 dev_err(&port_dev->dev, "disabled by hub (EMI?), re-enabling...\n");
5785 if (portchange & USB_PORT_STAT_C_OVERCURRENT) {
5786 u16 status = 0, unused;
5787 port_dev->over_current_count++;
5788 port_over_current_notify(port_dev);
5790 dev_dbg(&port_dev->dev, "over-current change #%u\n",
5791 port_dev->over_current_count);
5792 usb_clear_port_feature(hdev, port1,
5793 USB_PORT_FEAT_C_OVER_CURRENT);
5794 msleep(100); /* Cool down */
5795 hub_power_on(hub, true);
5796 usb_hub_port_status(hub, port1, &status, &unused);
5797 if (status & USB_PORT_STAT_OVERCURRENT)
5798 dev_err(&port_dev->dev, "over-current condition\n");
5801 if (portchange & USB_PORT_STAT_C_RESET) {
5802 dev_dbg(&port_dev->dev, "reset change\n");
5803 usb_clear_port_feature(hdev, port1, USB_PORT_FEAT_C_RESET);
5805 if ((portchange & USB_PORT_STAT_C_BH_RESET)
5806 && hub_is_superspeed(hdev)) {
5807 dev_dbg(&port_dev->dev, "warm reset change\n");
5808 usb_clear_port_feature(hdev, port1,
5809 USB_PORT_FEAT_C_BH_PORT_RESET);
5811 if (portchange & USB_PORT_STAT_C_LINK_STATE) {
5812 dev_dbg(&port_dev->dev, "link state change\n");
5813 usb_clear_port_feature(hdev, port1,
5814 USB_PORT_FEAT_C_PORT_LINK_STATE);
5816 if (portchange & USB_PORT_STAT_C_CONFIG_ERROR) {
5817 dev_warn(&port_dev->dev, "config error\n");
5818 usb_clear_port_feature(hdev, port1,
5819 USB_PORT_FEAT_C_PORT_CONFIG_ERROR);
5822 /* skip port actions that require the port to be powered on */
5823 if (!pm_runtime_active(&port_dev->dev))
5826 /* skip port actions if ignore_event and early_stop are true */
5827 if (port_dev->ignore_event && port_dev->early_stop)
5830 if (hub_handle_remote_wakeup(hub, port1, portstatus, portchange))
5834 * Avoid trying to recover a USB3 SS.Inactive port with a warm reset if
5835 * the device was disconnected. A 12ms disconnect detect timer in
5836 * SS.Inactive state transitions the port to RxDetect automatically.
5837 * SS.Inactive link error state is common during device disconnect.
5839 while (hub_port_warm_reset_required(hub, port1, portstatus)) {
5840 if ((i++ < DETECT_DISCONNECT_TRIES) && udev) {
5844 usb_hub_port_status(hub, port1, &portstatus, &unused);
5845 dev_dbg(&port_dev->dev, "Wait for inactive link disconnect detect\n");
5847 } else if (!udev || !(portstatus & USB_PORT_STAT_CONNECTION)
5848 || udev->state == USB_STATE_NOTATTACHED) {
5849 dev_dbg(&port_dev->dev, "do warm reset, port only\n");
5850 if (hub_port_reset(hub, port1, NULL,
5851 HUB_BH_RESET_TIME, true) < 0)
5852 hub_port_disable(hub, port1, 1);
5854 dev_dbg(&port_dev->dev, "do warm reset, full device\n");
5855 usb_unlock_port(port_dev);
5856 usb_lock_device(udev);
5857 usb_reset_device(udev);
5858 usb_unlock_device(udev);
5859 usb_lock_port(port_dev);
5866 hub_port_connect_change(hub, port1, portstatus, portchange);
5869 static void hub_event(struct work_struct *work)
5871 struct usb_device *hdev;
5872 struct usb_interface *intf;
5873 struct usb_hub *hub;
5874 struct device *hub_dev;
5879 hub = container_of(work, struct usb_hub, events);
5881 hub_dev = hub->intfdev;
5882 intf = to_usb_interface(hub_dev);
5884 kcov_remote_start_usb((u64)hdev->bus->busnum);
5886 dev_dbg(hub_dev, "state %d ports %d chg %04x evt %04x\n",
5887 hdev->state, hdev->maxchild,
5888 /* NOTE: expects max 15 ports... */
5889 (u16) hub->change_bits[0],
5890 (u16) hub->event_bits[0]);
5892 /* Lock the device, then check to see if we were
5893 * disconnected while waiting for the lock to succeed. */
5894 usb_lock_device(hdev);
5895 if (unlikely(hub->disconnected))
5898 /* If the hub has died, clean up after it */
5899 if (hdev->state == USB_STATE_NOTATTACHED) {
5900 hub->error = -ENODEV;
5901 hub_quiesce(hub, HUB_DISCONNECT);
5906 ret = usb_autopm_get_interface(intf);
5908 dev_dbg(hub_dev, "Can't autoresume: %d\n", ret);
5912 /* If this is an inactive hub, do nothing */
5917 dev_dbg(hub_dev, "resetting for error %d\n", hub->error);
5919 ret = usb_reset_device(hdev);
5921 dev_dbg(hub_dev, "error resetting hub: %d\n", ret);
5929 /* deal with port status changes */
5930 for (i = 1; i <= hdev->maxchild; i++) {
5931 struct usb_port *port_dev = hub->ports[i - 1];
5933 if (test_bit(i, hub->event_bits)
5934 || test_bit(i, hub->change_bits)
5935 || test_bit(i, hub->wakeup_bits)) {
5937 * The get_noresume and barrier ensure that if
5938 * the port was in the process of resuming, we
5939 * flush that work and keep the port active for
5940 * the duration of the port_event(). However,
5941 * if the port is runtime pm suspended
5942 * (powered-off), we leave it in that state, run
5943 * an abbreviated port_event(), and move on.
5945 pm_runtime_get_noresume(&port_dev->dev);
5946 pm_runtime_barrier(&port_dev->dev);
5947 usb_lock_port(port_dev);
5949 usb_unlock_port(port_dev);
5950 pm_runtime_put_sync(&port_dev->dev);
5954 /* deal with hub status changes */
5955 if (test_and_clear_bit(0, hub->event_bits) == 0)
5957 else if (hub_hub_status(hub, &hubstatus, &hubchange) < 0)
5958 dev_err(hub_dev, "get_hub_status failed\n");
5960 if (hubchange & HUB_CHANGE_LOCAL_POWER) {
5961 dev_dbg(hub_dev, "power change\n");
5962 clear_hub_feature(hdev, C_HUB_LOCAL_POWER);
5963 if (hubstatus & HUB_STATUS_LOCAL_POWER)
5964 /* FIXME: Is this always true? */
5965 hub->limited_power = 1;
5967 hub->limited_power = 0;
5969 if (hubchange & HUB_CHANGE_OVERCURRENT) {
5973 dev_dbg(hub_dev, "over-current change\n");
5974 clear_hub_feature(hdev, C_HUB_OVER_CURRENT);
5975 msleep(500); /* Cool down */
5976 hub_power_on(hub, true);
5977 hub_hub_status(hub, &status, &unused);
5978 if (status & HUB_STATUS_OVERCURRENT)
5979 dev_err(hub_dev, "over-current condition\n");
5984 /* Balance the usb_autopm_get_interface() above */
5985 usb_autopm_put_interface_no_suspend(intf);
5987 usb_unlock_device(hdev);
5989 /* Balance the stuff in kick_hub_wq() and allow autosuspend */
5990 usb_autopm_put_interface(intf);
5996 static const struct usb_device_id hub_id_table[] = {
5997 { .match_flags = USB_DEVICE_ID_MATCH_VENDOR
5998 | USB_DEVICE_ID_MATCH_PRODUCT
5999 | USB_DEVICE_ID_MATCH_INT_CLASS,
6000 .idVendor = USB_VENDOR_SMSC,
6001 .idProduct = USB_PRODUCT_USB5534B,
6002 .bInterfaceClass = USB_CLASS_HUB,
6003 .driver_info = HUB_QUIRK_DISABLE_AUTOSUSPEND},
6004 { .match_flags = USB_DEVICE_ID_MATCH_VENDOR
6005 | USB_DEVICE_ID_MATCH_PRODUCT,
6006 .idVendor = USB_VENDOR_CYPRESS,
6007 .idProduct = USB_PRODUCT_CY7C65632,
6008 .driver_info = HUB_QUIRK_DISABLE_AUTOSUSPEND},
6009 { .match_flags = USB_DEVICE_ID_MATCH_VENDOR
6010 | USB_DEVICE_ID_MATCH_INT_CLASS,
6011 .idVendor = USB_VENDOR_GENESYS_LOGIC,
6012 .bInterfaceClass = USB_CLASS_HUB,
6013 .driver_info = HUB_QUIRK_CHECK_PORT_AUTOSUSPEND},
6014 { .match_flags = USB_DEVICE_ID_MATCH_VENDOR
6015 | USB_DEVICE_ID_MATCH_PRODUCT,
6016 .idVendor = USB_VENDOR_TEXAS_INSTRUMENTS,
6017 .idProduct = USB_PRODUCT_TUSB8041_USB2,
6018 .driver_info = HUB_QUIRK_DISABLE_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_USB3,
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_MICROCHIP,
6027 .idProduct = USB_PRODUCT_USB4913,
6028 .driver_info = HUB_QUIRK_REDUCE_FRAME_INTR_BINTERVAL},
6029 { .match_flags = USB_DEVICE_ID_MATCH_VENDOR
6030 | USB_DEVICE_ID_MATCH_PRODUCT,
6031 .idVendor = USB_VENDOR_MICROCHIP,
6032 .idProduct = USB_PRODUCT_USB4914,
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_USB4915,
6038 .driver_info = HUB_QUIRK_REDUCE_FRAME_INTR_BINTERVAL},
6039 { .match_flags = USB_DEVICE_ID_MATCH_DEV_CLASS,
6040 .bDeviceClass = USB_CLASS_HUB},
6041 { .match_flags = USB_DEVICE_ID_MATCH_INT_CLASS,
6042 .bInterfaceClass = USB_CLASS_HUB},
6043 { } /* Terminating entry */
6046 MODULE_DEVICE_TABLE(usb, hub_id_table);
6048 static struct usb_driver hub_driver = {
6051 .disconnect = hub_disconnect,
6052 .suspend = hub_suspend,
6053 .resume = hub_resume,
6054 .reset_resume = hub_reset_resume,
6055 .pre_reset = hub_pre_reset,
6056 .post_reset = hub_post_reset,
6057 .unlocked_ioctl = hub_ioctl,
6058 .id_table = hub_id_table,
6059 .supports_autosuspend = 1,
6062 int usb_hub_init(void)
6064 if (usb_register(&hub_driver) < 0) {
6065 printk(KERN_ERR "%s: can't register hub driver\n",
6071 * The workqueue needs to be freezable to avoid interfering with
6072 * USB-PERSIST port handover. Otherwise it might see that a full-speed
6073 * device was gone before the EHCI controller had handed its port
6074 * over to the companion full-speed controller.
6076 hub_wq = alloc_workqueue("usb_hub_wq", WQ_FREEZABLE, 0);
6080 /* Fall through if kernel_thread failed */
6081 usb_deregister(&hub_driver);
6082 pr_err("%s: can't allocate workqueue for usb hub\n", usbcore_name);
6087 void usb_hub_cleanup(void)
6089 destroy_workqueue(hub_wq);
6092 * Hub resources are freed for us by usb_deregister. It calls
6093 * usb_driver_purge on every device which in turn calls that
6094 * devices disconnect function if it is using this driver.
6095 * The hub_disconnect function takes care of releasing the
6096 * individual hub resources. -greg
6098 usb_deregister(&hub_driver);
6099 } /* usb_hub_cleanup() */
6102 * hub_hc_release_resources - clear resources used by host controller
6103 * @udev: pointer to device being released
6105 * Context: task context, might sleep
6107 * Function releases the host controller resources in correct order before
6108 * making any operation on resuming usb device. The host controller resources
6109 * allocated for devices in tree should be released starting from the last
6110 * usb device in tree toward the root hub. This function is used only during
6111 * resuming device when usb device require reinitialization – that is, when
6112 * flag udev->reset_resume is set.
6114 * This call is synchronous, and may not be used in an interrupt context.
6116 static void hub_hc_release_resources(struct usb_device *udev)
6118 struct usb_hub *hub = usb_hub_to_struct_hub(udev);
6119 struct usb_hcd *hcd = bus_to_hcd(udev->bus);
6122 /* Release up resources for all children before this device */
6123 for (i = 0; i < udev->maxchild; i++)
6124 if (hub->ports[i]->child)
6125 hub_hc_release_resources(hub->ports[i]->child);
6127 if (hcd->driver->reset_device)
6128 hcd->driver->reset_device(hcd, udev);
6132 * usb_reset_and_verify_device - perform a USB port reset to reinitialize a device
6133 * @udev: device to reset (not in SUSPENDED or NOTATTACHED state)
6135 * WARNING - don't use this routine to reset a composite device
6136 * (one with multiple interfaces owned by separate drivers)!
6137 * Use usb_reset_device() instead.
6139 * Do a port reset, reassign the device's address, and establish its
6140 * former operating configuration. If the reset fails, or the device's
6141 * descriptors change from their values before the reset, or the original
6142 * configuration and altsettings cannot be restored, a flag will be set
6143 * telling hub_wq to pretend the device has been disconnected and then
6144 * re-connected. All drivers will be unbound, and the device will be
6145 * re-enumerated and probed all over again.
6147 * Return: 0 if the reset succeeded, -ENODEV if the device has been
6148 * flagged for logical disconnection, or some other negative error code
6149 * if the reset wasn't even attempted.
6152 * The caller must own the device lock and the port lock, the latter is
6153 * taken by usb_reset_device(). For example, it's safe to use
6154 * usb_reset_device() from a driver probe() routine after downloading
6155 * new firmware. For calls that might not occur during probe(), drivers
6156 * should lock the device using usb_lock_device_for_reset().
6158 * Locking exception: This routine may also be called from within an
6159 * autoresume handler. Such usage won't conflict with other tasks
6160 * holding the device lock because these tasks should always call
6161 * usb_autopm_resume_device(), thereby preventing any unwanted
6162 * autoresume. The autoresume handler is expected to have already
6163 * acquired the port lock before calling this routine.
6165 static int usb_reset_and_verify_device(struct usb_device *udev)
6167 struct usb_device *parent_hdev = udev->parent;
6168 struct usb_hub *parent_hub;
6169 struct usb_hcd *hcd = bus_to_hcd(udev->bus);
6170 struct usb_device_descriptor descriptor;
6171 struct usb_interface *intf;
6172 struct usb_host_bos *bos;
6174 int port1 = udev->portnum;
6176 if (udev->state == USB_STATE_NOTATTACHED ||
6177 udev->state == USB_STATE_SUSPENDED) {
6178 dev_dbg(&udev->dev, "device reset not allowed in state %d\n",
6186 parent_hub = usb_hub_to_struct_hub(parent_hdev);
6188 /* Disable USB2 hardware LPM.
6189 * It will be re-enabled by the enumeration process.
6191 usb_disable_usb2_hardware_lpm(udev);
6196 if (udev->reset_resume)
6197 hub_hc_release_resources(udev);
6199 mutex_lock(hcd->address0_mutex);
6201 for (i = 0; i < PORT_INIT_TRIES; ++i) {
6202 if (hub_port_stop_enumerate(parent_hub, port1, i)) {
6207 /* ep0 maxpacket size may change; let the HCD know about it.
6208 * Other endpoints will be handled by re-enumeration. */
6209 usb_ep0_reinit(udev);
6210 ret = hub_port_init(parent_hub, udev, port1, i, &descriptor);
6211 if (ret >= 0 || ret == -ENOTCONN || ret == -ENODEV)
6214 mutex_unlock(hcd->address0_mutex);
6219 /* Device might have changed firmware (DFU or similar) */
6220 if (descriptors_changed(udev, &descriptor, bos)) {
6221 dev_info(&udev->dev, "device firmware changed\n");
6225 /* Restore the device's previous configuration */
6226 if (!udev->actconfig)
6230 * Some devices can't handle setting default altsetting 0 with a
6231 * Set-Interface request. Disable host-side endpoints of those
6232 * interfaces here. Enable and reset them back after host has set
6233 * its internal endpoint structures during usb_hcd_alloc_bandwith()
6235 for (i = 0; i < udev->actconfig->desc.bNumInterfaces; i++) {
6236 intf = udev->actconfig->interface[i];
6237 if (intf->cur_altsetting->desc.bAlternateSetting == 0)
6238 usb_disable_interface(udev, intf, true);
6241 mutex_lock(hcd->bandwidth_mutex);
6242 ret = usb_hcd_alloc_bandwidth(udev, udev->actconfig, NULL, NULL);
6244 dev_warn(&udev->dev,
6245 "Busted HC? Not enough HCD resources for "
6246 "old configuration.\n");
6247 mutex_unlock(hcd->bandwidth_mutex);
6250 ret = usb_control_msg(udev, usb_sndctrlpipe(udev, 0),
6251 USB_REQ_SET_CONFIGURATION, 0,
6252 udev->actconfig->desc.bConfigurationValue, 0,
6253 NULL, 0, USB_CTRL_SET_TIMEOUT);
6256 "can't restore configuration #%d (error=%d)\n",
6257 udev->actconfig->desc.bConfigurationValue, ret);
6258 mutex_unlock(hcd->bandwidth_mutex);
6261 mutex_unlock(hcd->bandwidth_mutex);
6262 usb_set_device_state(udev, USB_STATE_CONFIGURED);
6264 /* Put interfaces back into the same altsettings as before.
6265 * Don't bother to send the Set-Interface request for interfaces
6266 * that were already in altsetting 0; besides being unnecessary,
6267 * many devices can't handle it. Instead just reset the host-side
6270 for (i = 0; i < udev->actconfig->desc.bNumInterfaces; i++) {
6271 struct usb_host_config *config = udev->actconfig;
6272 struct usb_interface_descriptor *desc;
6274 intf = config->interface[i];
6275 desc = &intf->cur_altsetting->desc;
6276 if (desc->bAlternateSetting == 0) {
6277 usb_enable_interface(udev, intf, true);
6280 /* Let the bandwidth allocation function know that this
6281 * device has been reset, and it will have to use
6282 * alternate setting 0 as the current alternate setting.
6284 intf->resetting_device = 1;
6285 ret = usb_set_interface(udev, desc->bInterfaceNumber,
6286 desc->bAlternateSetting);
6287 intf->resetting_device = 0;
6290 dev_err(&udev->dev, "failed to restore interface %d "
6291 "altsetting %d (error=%d)\n",
6292 desc->bInterfaceNumber,
6293 desc->bAlternateSetting,
6297 /* Resetting also frees any allocated streams */
6298 for (j = 0; j < intf->cur_altsetting->desc.bNumEndpoints; j++)
6299 intf->cur_altsetting->endpoint[j].streams = 0;
6303 /* Now that the alt settings are re-installed, enable LTM and LPM. */
6304 usb_enable_usb2_hardware_lpm(udev);
6305 usb_unlocked_enable_lpm(udev);
6306 usb_enable_ltm(udev);
6307 usb_release_bos_descriptor(udev);
6312 usb_release_bos_descriptor(udev);
6314 hub_port_logical_disconnect(parent_hub, port1);
6319 * usb_reset_device - warn interface drivers and perform a USB port reset
6320 * @udev: device to reset (not in NOTATTACHED state)
6322 * Warns all drivers bound to registered interfaces (using their pre_reset
6323 * method), performs the port reset, and then lets the drivers know that
6324 * the reset is over (using their post_reset method).
6326 * Return: The same as for usb_reset_and_verify_device().
6327 * However, if a reset is already in progress (for instance, if a
6328 * driver doesn't have pre_reset() or post_reset() callbacks, and while
6329 * being unbound or re-bound during the ongoing reset its disconnect()
6330 * or probe() routine tries to perform a second, nested reset), the
6331 * routine returns -EINPROGRESS.
6334 * The caller must own the device lock. For example, it's safe to use
6335 * this from a driver probe() routine after downloading new firmware.
6336 * For calls that might not occur during probe(), drivers should lock
6337 * the device using usb_lock_device_for_reset().
6339 * If an interface is currently being probed or disconnected, we assume
6340 * its driver knows how to handle resets. For all other interfaces,
6341 * if the driver doesn't have pre_reset and post_reset methods then
6342 * we attempt to unbind it and rebind afterward.
6344 int usb_reset_device(struct usb_device *udev)
6348 unsigned int noio_flag;
6349 struct usb_port *port_dev;
6350 struct usb_host_config *config = udev->actconfig;
6351 struct usb_hub *hub = usb_hub_to_struct_hub(udev->parent);
6353 if (udev->state == USB_STATE_NOTATTACHED) {
6354 dev_dbg(&udev->dev, "device reset not allowed in state %d\n",
6359 if (!udev->parent) {
6360 /* this requires hcd-specific logic; see ohci_restart() */
6361 dev_dbg(&udev->dev, "%s for root hub!\n", __func__);
6365 if (udev->reset_in_progress)
6366 return -EINPROGRESS;
6367 udev->reset_in_progress = 1;
6369 port_dev = hub->ports[udev->portnum - 1];
6372 * Don't allocate memory with GFP_KERNEL in current
6373 * context to avoid possible deadlock if usb mass
6374 * storage interface or usbnet interface(iSCSI case)
6375 * is included in current configuration. The easist
6376 * approach is to do it for every device reset,
6377 * because the device 'memalloc_noio' flag may have
6378 * not been set before reseting the usb device.
6380 noio_flag = memalloc_noio_save();
6382 /* Prevent autosuspend during the reset */
6383 usb_autoresume_device(udev);
6386 for (i = 0; i < config->desc.bNumInterfaces; ++i) {
6387 struct usb_interface *cintf = config->interface[i];
6388 struct usb_driver *drv;
6391 if (cintf->dev.driver) {
6392 drv = to_usb_driver(cintf->dev.driver);
6393 if (drv->pre_reset && drv->post_reset)
6394 unbind = (drv->pre_reset)(cintf);
6395 else if (cintf->condition ==
6396 USB_INTERFACE_BOUND)
6399 usb_forced_unbind_intf(cintf);
6404 usb_lock_port(port_dev);
6405 ret = usb_reset_and_verify_device(udev);
6406 usb_unlock_port(port_dev);
6409 for (i = config->desc.bNumInterfaces - 1; i >= 0; --i) {
6410 struct usb_interface *cintf = config->interface[i];
6411 struct usb_driver *drv;
6412 int rebind = cintf->needs_binding;
6414 if (!rebind && cintf->dev.driver) {
6415 drv = to_usb_driver(cintf->dev.driver);
6416 if (drv->post_reset)
6417 rebind = (drv->post_reset)(cintf);
6418 else if (cintf->condition ==
6419 USB_INTERFACE_BOUND)
6422 cintf->needs_binding = 1;
6426 /* If the reset failed, hub_wq will unbind drivers later */
6428 usb_unbind_and_rebind_marked_interfaces(udev);
6431 usb_autosuspend_device(udev);
6432 memalloc_noio_restore(noio_flag);
6433 udev->reset_in_progress = 0;
6436 EXPORT_SYMBOL_GPL(usb_reset_device);
6440 * usb_queue_reset_device - Reset a USB device from an atomic context
6441 * @iface: USB interface belonging to the device to reset
6443 * This function can be used to reset a USB device from an atomic
6444 * context, where usb_reset_device() won't work (as it blocks).
6446 * Doing a reset via this method is functionally equivalent to calling
6447 * usb_reset_device(), except for the fact that it is delayed to a
6448 * workqueue. This means that any drivers bound to other interfaces
6449 * might be unbound, as well as users from usbfs in user space.
6453 * - Scheduling two resets at the same time from two different drivers
6454 * attached to two different interfaces of the same device is
6455 * possible; depending on how the driver attached to each interface
6456 * handles ->pre_reset(), the second reset might happen or not.
6458 * - If the reset is delayed so long that the interface is unbound from
6459 * its driver, the reset will be skipped.
6461 * - This function can be called during .probe(). It can also be called
6462 * during .disconnect(), but doing so is pointless because the reset
6463 * will not occur. If you really want to reset the device during
6464 * .disconnect(), call usb_reset_device() directly -- but watch out
6465 * for nested unbinding issues!
6467 void usb_queue_reset_device(struct usb_interface *iface)
6469 if (schedule_work(&iface->reset_ws))
6470 usb_get_intf(iface);
6472 EXPORT_SYMBOL_GPL(usb_queue_reset_device);
6475 * usb_hub_find_child - Get the pointer of child device
6476 * attached to the port which is specified by @port1.
6477 * @hdev: USB device belonging to the usb hub
6478 * @port1: port num to indicate which port the child device
6481 * USB drivers call this function to get hub's child device
6484 * Return: %NULL if input param is invalid and
6485 * child's usb_device pointer if non-NULL.
6487 struct usb_device *usb_hub_find_child(struct usb_device *hdev,
6490 struct usb_hub *hub = usb_hub_to_struct_hub(hdev);
6492 if (port1 < 1 || port1 > hdev->maxchild)
6494 return hub->ports[port1 - 1]->child;
6496 EXPORT_SYMBOL_GPL(usb_hub_find_child);
6498 void usb_hub_adjust_deviceremovable(struct usb_device *hdev,
6499 struct usb_hub_descriptor *desc)
6501 struct usb_hub *hub = usb_hub_to_struct_hub(hdev);
6502 enum usb_port_connect_type connect_type;
6508 if (!hub_is_superspeed(hdev)) {
6509 for (i = 1; i <= hdev->maxchild; i++) {
6510 struct usb_port *port_dev = hub->ports[i - 1];
6512 connect_type = port_dev->connect_type;
6513 if (connect_type == USB_PORT_CONNECT_TYPE_HARD_WIRED) {
6514 u8 mask = 1 << (i%8);
6516 if (!(desc->u.hs.DeviceRemovable[i/8] & mask)) {
6517 dev_dbg(&port_dev->dev, "DeviceRemovable is changed to 1 according to platform information.\n");
6518 desc->u.hs.DeviceRemovable[i/8] |= mask;
6523 u16 port_removable = le16_to_cpu(desc->u.ss.DeviceRemovable);
6525 for (i = 1; i <= hdev->maxchild; i++) {
6526 struct usb_port *port_dev = hub->ports[i - 1];
6528 connect_type = port_dev->connect_type;
6529 if (connect_type == USB_PORT_CONNECT_TYPE_HARD_WIRED) {
6532 if (!(port_removable & mask)) {
6533 dev_dbg(&port_dev->dev, "DeviceRemovable is changed to 1 according to platform information.\n");
6534 port_removable |= mask;
6539 desc->u.ss.DeviceRemovable = cpu_to_le16(port_removable);
6545 * usb_get_hub_port_acpi_handle - Get the usb port's acpi handle
6546 * @hdev: USB device belonging to the usb hub
6547 * @port1: port num of the port
6549 * Return: Port's acpi handle if successful, %NULL if params are
6552 acpi_handle usb_get_hub_port_acpi_handle(struct usb_device *hdev,
6555 struct usb_hub *hub = usb_hub_to_struct_hub(hdev);
6560 return ACPI_HANDLE(&hub->ports[port1 - 1]->dev);