USB delay init quirk for logitech Harmony 700-series devices
[linux-2.6/linux-acpi-2.6/ibm-acpi-2.6.git] / drivers / usb / core / hub.c
blob91ddeba1339e30e0a781f15e816a56508fcaf82d
1 /*
2 * USB hub driver.
4 * (C) Copyright 1999 Linus Torvalds
5 * (C) Copyright 1999 Johannes Erdfelt
6 * (C) Copyright 1999 Gregory P. Smith
7 * (C) Copyright 2001 Brad Hards (bhards@bigpond.net.au)
9 */
11 #include <linux/kernel.h>
12 #include <linux/errno.h>
13 #include <linux/module.h>
14 #include <linux/moduleparam.h>
15 #include <linux/completion.h>
16 #include <linux/sched.h>
17 #include <linux/list.h>
18 #include <linux/slab.h>
19 #include <linux/ioctl.h>
20 #include <linux/usb.h>
21 #include <linux/usbdevice_fs.h>
22 #include <linux/kthread.h>
23 #include <linux/mutex.h>
24 #include <linux/freezer.h>
25 #include <linux/pm_runtime.h>
26 #include <linux/usb/quirks.h>
28 #include <asm/uaccess.h>
29 #include <asm/byteorder.h>
31 #include "usb.h"
32 #include "hcd.h"
33 #include "hub.h"
35 /* if we are in debug mode, always announce new devices */
36 #ifdef DEBUG
37 #ifndef CONFIG_USB_ANNOUNCE_NEW_DEVICES
38 #define CONFIG_USB_ANNOUNCE_NEW_DEVICES
39 #endif
40 #endif
42 struct usb_hub {
43 struct device *intfdev; /* the "interface" device */
44 struct usb_device *hdev;
45 struct kref kref;
46 struct urb *urb; /* for interrupt polling pipe */
48 /* buffer for urb ... with extra space in case of babble */
49 char (*buffer)[8];
50 union {
51 struct usb_hub_status hub;
52 struct usb_port_status port;
53 } *status; /* buffer for status reports */
54 struct mutex status_mutex; /* for the status buffer */
56 int error; /* last reported error */
57 int nerrors; /* track consecutive errors */
59 struct list_head event_list; /* hubs w/data or errs ready */
60 unsigned long event_bits[1]; /* status change bitmask */
61 unsigned long change_bits[1]; /* ports with logical connect
62 status change */
63 unsigned long busy_bits[1]; /* ports being reset or
64 resumed */
65 unsigned long removed_bits[1]; /* ports with a "removed"
66 device present */
67 #if USB_MAXCHILDREN > 31 /* 8*sizeof(unsigned long) - 1 */
68 #error event_bits[] is too short!
69 #endif
71 struct usb_hub_descriptor *descriptor; /* class descriptor */
72 struct usb_tt tt; /* Transaction Translator */
74 unsigned mA_per_port; /* current for each child */
76 unsigned limited_power:1;
77 unsigned quiescing:1;
78 unsigned disconnected:1;
80 unsigned has_indicators:1;
81 u8 indicator[USB_MAXCHILDREN];
82 struct delayed_work leds;
83 struct delayed_work init_work;
84 void **port_owners;
88 /* Protect struct usb_device->state and ->children members
89 * Note: Both are also protected by ->dev.sem, except that ->state can
90 * change to USB_STATE_NOTATTACHED even when the semaphore isn't held. */
91 static DEFINE_SPINLOCK(device_state_lock);
93 /* khubd's worklist and its lock */
94 static DEFINE_SPINLOCK(hub_event_lock);
95 static LIST_HEAD(hub_event_list); /* List of hubs needing servicing */
97 /* Wakes up khubd */
98 static DECLARE_WAIT_QUEUE_HEAD(khubd_wait);
100 static struct task_struct *khubd_task;
102 /* cycle leds on hubs that aren't blinking for attention */
103 static int blinkenlights = 0;
104 module_param (blinkenlights, bool, S_IRUGO);
105 MODULE_PARM_DESC (blinkenlights, "true to cycle leds on hubs");
108 * Device SATA8000 FW1.0 from DATAST0R Technology Corp requires about
109 * 10 seconds to send reply for the initial 64-byte descriptor request.
111 /* define initial 64-byte descriptor request timeout in milliseconds */
112 static int initial_descriptor_timeout = USB_CTRL_GET_TIMEOUT;
113 module_param(initial_descriptor_timeout, int, S_IRUGO|S_IWUSR);
114 MODULE_PARM_DESC(initial_descriptor_timeout,
115 "initial 64-byte descriptor request timeout in milliseconds "
116 "(default 5000 - 5.0 seconds)");
119 * As of 2.6.10 we introduce a new USB device initialization scheme which
120 * closely resembles the way Windows works. Hopefully it will be compatible
121 * with a wider range of devices than the old scheme. However some previously
122 * working devices may start giving rise to "device not accepting address"
123 * errors; if that happens the user can try the old scheme by adjusting the
124 * following module parameters.
126 * For maximum flexibility there are two boolean parameters to control the
127 * hub driver's behavior. On the first initialization attempt, if the
128 * "old_scheme_first" parameter is set then the old scheme will be used,
129 * otherwise the new scheme is used. If that fails and "use_both_schemes"
130 * is set, then the driver will make another attempt, using the other scheme.
132 static int old_scheme_first = 0;
133 module_param(old_scheme_first, bool, S_IRUGO | S_IWUSR);
134 MODULE_PARM_DESC(old_scheme_first,
135 "start with the old device initialization scheme");
137 static int use_both_schemes = 1;
138 module_param(use_both_schemes, bool, S_IRUGO | S_IWUSR);
139 MODULE_PARM_DESC(use_both_schemes,
140 "try the other device initialization scheme if the "
141 "first one fails");
143 /* Mutual exclusion for EHCI CF initialization. This interferes with
144 * port reset on some companion controllers.
146 DECLARE_RWSEM(ehci_cf_port_reset_rwsem);
147 EXPORT_SYMBOL_GPL(ehci_cf_port_reset_rwsem);
149 #define HUB_DEBOUNCE_TIMEOUT 1500
150 #define HUB_DEBOUNCE_STEP 25
151 #define HUB_DEBOUNCE_STABLE 100
154 static int usb_reset_and_verify_device(struct usb_device *udev);
156 static inline char *portspeed(int portstatus)
158 if (portstatus & (1 << USB_PORT_FEAT_HIGHSPEED))
159 return "480 Mb/s";
160 else if (portstatus & (1 << USB_PORT_FEAT_LOWSPEED))
161 return "1.5 Mb/s";
162 else if (portstatus & (1 << USB_PORT_FEAT_SUPERSPEED))
163 return "5.0 Gb/s";
164 else
165 return "12 Mb/s";
168 /* Note that hdev or one of its children must be locked! */
169 static struct usb_hub *hdev_to_hub(struct usb_device *hdev)
171 if (!hdev || !hdev->actconfig)
172 return NULL;
173 return usb_get_intfdata(hdev->actconfig->interface[0]);
176 /* USB 2.0 spec Section 11.24.4.5 */
177 static int get_hub_descriptor(struct usb_device *hdev, void *data, int size)
179 int i, ret;
181 for (i = 0; i < 3; i++) {
182 ret = usb_control_msg(hdev, usb_rcvctrlpipe(hdev, 0),
183 USB_REQ_GET_DESCRIPTOR, USB_DIR_IN | USB_RT_HUB,
184 USB_DT_HUB << 8, 0, data, size,
185 USB_CTRL_GET_TIMEOUT);
186 if (ret >= (USB_DT_HUB_NONVAR_SIZE + 2))
187 return ret;
189 return -EINVAL;
193 * USB 2.0 spec Section 11.24.2.1
195 static int clear_hub_feature(struct usb_device *hdev, int feature)
197 return usb_control_msg(hdev, usb_sndctrlpipe(hdev, 0),
198 USB_REQ_CLEAR_FEATURE, USB_RT_HUB, feature, 0, NULL, 0, 1000);
202 * USB 2.0 spec Section 11.24.2.2
204 static int clear_port_feature(struct usb_device *hdev, int port1, int feature)
206 return usb_control_msg(hdev, usb_sndctrlpipe(hdev, 0),
207 USB_REQ_CLEAR_FEATURE, USB_RT_PORT, feature, port1,
208 NULL, 0, 1000);
212 * USB 2.0 spec Section 11.24.2.13
214 static int set_port_feature(struct usb_device *hdev, int port1, int feature)
216 return usb_control_msg(hdev, usb_sndctrlpipe(hdev, 0),
217 USB_REQ_SET_FEATURE, USB_RT_PORT, feature, port1,
218 NULL, 0, 1000);
222 * USB 2.0 spec Section 11.24.2.7.1.10 and table 11-7
223 * for info about using port indicators
225 static void set_port_led(
226 struct usb_hub *hub,
227 int port1,
228 int selector
231 int status = set_port_feature(hub->hdev, (selector << 8) | port1,
232 USB_PORT_FEAT_INDICATOR);
233 if (status < 0)
234 dev_dbg (hub->intfdev,
235 "port %d indicator %s status %d\n",
236 port1,
237 ({ char *s; switch (selector) {
238 case HUB_LED_AMBER: s = "amber"; break;
239 case HUB_LED_GREEN: s = "green"; break;
240 case HUB_LED_OFF: s = "off"; break;
241 case HUB_LED_AUTO: s = "auto"; break;
242 default: s = "??"; break;
243 }; s; }),
244 status);
247 #define LED_CYCLE_PERIOD ((2*HZ)/3)
249 static void led_work (struct work_struct *work)
251 struct usb_hub *hub =
252 container_of(work, struct usb_hub, leds.work);
253 struct usb_device *hdev = hub->hdev;
254 unsigned i;
255 unsigned changed = 0;
256 int cursor = -1;
258 if (hdev->state != USB_STATE_CONFIGURED || hub->quiescing)
259 return;
261 for (i = 0; i < hub->descriptor->bNbrPorts; i++) {
262 unsigned selector, mode;
264 /* 30%-50% duty cycle */
266 switch (hub->indicator[i]) {
267 /* cycle marker */
268 case INDICATOR_CYCLE:
269 cursor = i;
270 selector = HUB_LED_AUTO;
271 mode = INDICATOR_AUTO;
272 break;
273 /* blinking green = sw attention */
274 case INDICATOR_GREEN_BLINK:
275 selector = HUB_LED_GREEN;
276 mode = INDICATOR_GREEN_BLINK_OFF;
277 break;
278 case INDICATOR_GREEN_BLINK_OFF:
279 selector = HUB_LED_OFF;
280 mode = INDICATOR_GREEN_BLINK;
281 break;
282 /* blinking amber = hw attention */
283 case INDICATOR_AMBER_BLINK:
284 selector = HUB_LED_AMBER;
285 mode = INDICATOR_AMBER_BLINK_OFF;
286 break;
287 case INDICATOR_AMBER_BLINK_OFF:
288 selector = HUB_LED_OFF;
289 mode = INDICATOR_AMBER_BLINK;
290 break;
291 /* blink green/amber = reserved */
292 case INDICATOR_ALT_BLINK:
293 selector = HUB_LED_GREEN;
294 mode = INDICATOR_ALT_BLINK_OFF;
295 break;
296 case INDICATOR_ALT_BLINK_OFF:
297 selector = HUB_LED_AMBER;
298 mode = INDICATOR_ALT_BLINK;
299 break;
300 default:
301 continue;
303 if (selector != HUB_LED_AUTO)
304 changed = 1;
305 set_port_led(hub, i + 1, selector);
306 hub->indicator[i] = mode;
308 if (!changed && blinkenlights) {
309 cursor++;
310 cursor %= hub->descriptor->bNbrPorts;
311 set_port_led(hub, cursor + 1, HUB_LED_GREEN);
312 hub->indicator[cursor] = INDICATOR_CYCLE;
313 changed++;
315 if (changed)
316 schedule_delayed_work(&hub->leds, LED_CYCLE_PERIOD);
319 /* use a short timeout for hub/port status fetches */
320 #define USB_STS_TIMEOUT 1000
321 #define USB_STS_RETRIES 5
324 * USB 2.0 spec Section 11.24.2.6
326 static int get_hub_status(struct usb_device *hdev,
327 struct usb_hub_status *data)
329 int i, status = -ETIMEDOUT;
331 for (i = 0; i < USB_STS_RETRIES && status == -ETIMEDOUT; i++) {
332 status = usb_control_msg(hdev, usb_rcvctrlpipe(hdev, 0),
333 USB_REQ_GET_STATUS, USB_DIR_IN | USB_RT_HUB, 0, 0,
334 data, sizeof(*data), USB_STS_TIMEOUT);
336 return status;
340 * USB 2.0 spec Section 11.24.2.7
342 static int get_port_status(struct usb_device *hdev, int port1,
343 struct usb_port_status *data)
345 int i, status = -ETIMEDOUT;
347 for (i = 0; i < USB_STS_RETRIES && status == -ETIMEDOUT; i++) {
348 status = usb_control_msg(hdev, usb_rcvctrlpipe(hdev, 0),
349 USB_REQ_GET_STATUS, USB_DIR_IN | USB_RT_PORT, 0, port1,
350 data, sizeof(*data), USB_STS_TIMEOUT);
352 return status;
355 static int hub_port_status(struct usb_hub *hub, int port1,
356 u16 *status, u16 *change)
358 int ret;
360 mutex_lock(&hub->status_mutex);
361 ret = get_port_status(hub->hdev, port1, &hub->status->port);
362 if (ret < 4) {
363 dev_err(hub->intfdev,
364 "%s failed (err = %d)\n", __func__, ret);
365 if (ret >= 0)
366 ret = -EIO;
367 } else {
368 *status = le16_to_cpu(hub->status->port.wPortStatus);
369 *change = le16_to_cpu(hub->status->port.wPortChange);
370 ret = 0;
372 mutex_unlock(&hub->status_mutex);
373 return ret;
376 static void kick_khubd(struct usb_hub *hub)
378 unsigned long flags;
380 spin_lock_irqsave(&hub_event_lock, flags);
381 if (!hub->disconnected && list_empty(&hub->event_list)) {
382 list_add_tail(&hub->event_list, &hub_event_list);
384 /* Suppress autosuspend until khubd runs */
385 usb_autopm_get_interface_no_resume(
386 to_usb_interface(hub->intfdev));
387 wake_up(&khubd_wait);
389 spin_unlock_irqrestore(&hub_event_lock, flags);
392 void usb_kick_khubd(struct usb_device *hdev)
394 struct usb_hub *hub = hdev_to_hub(hdev);
396 if (hub)
397 kick_khubd(hub);
401 /* completion function, fires on port status changes and various faults */
402 static void hub_irq(struct urb *urb)
404 struct usb_hub *hub = urb->context;
405 int status = urb->status;
406 unsigned i;
407 unsigned long bits;
409 switch (status) {
410 case -ENOENT: /* synchronous unlink */
411 case -ECONNRESET: /* async unlink */
412 case -ESHUTDOWN: /* hardware going away */
413 return;
415 default: /* presumably an error */
416 /* Cause a hub reset after 10 consecutive errors */
417 dev_dbg (hub->intfdev, "transfer --> %d\n", status);
418 if ((++hub->nerrors < 10) || hub->error)
419 goto resubmit;
420 hub->error = status;
421 /* FALL THROUGH */
423 /* let khubd handle things */
424 case 0: /* we got data: port status changed */
425 bits = 0;
426 for (i = 0; i < urb->actual_length; ++i)
427 bits |= ((unsigned long) ((*hub->buffer)[i]))
428 << (i*8);
429 hub->event_bits[0] = bits;
430 break;
433 hub->nerrors = 0;
435 /* Something happened, let khubd figure it out */
436 kick_khubd(hub);
438 resubmit:
439 if (hub->quiescing)
440 return;
442 if ((status = usb_submit_urb (hub->urb, GFP_ATOMIC)) != 0
443 && status != -ENODEV && status != -EPERM)
444 dev_err (hub->intfdev, "resubmit --> %d\n", status);
447 /* USB 2.0 spec Section 11.24.2.3 */
448 static inline int
449 hub_clear_tt_buffer (struct usb_device *hdev, u16 devinfo, u16 tt)
451 return usb_control_msg(hdev, usb_sndctrlpipe(hdev, 0),
452 HUB_CLEAR_TT_BUFFER, USB_RT_PORT, devinfo,
453 tt, NULL, 0, 1000);
457 * enumeration blocks khubd for a long time. we use keventd instead, since
458 * long blocking there is the exception, not the rule. accordingly, HCDs
459 * talking to TTs must queue control transfers (not just bulk and iso), so
460 * both can talk to the same hub concurrently.
462 static void hub_tt_work(struct work_struct *work)
464 struct usb_hub *hub =
465 container_of(work, struct usb_hub, tt.clear_work);
466 unsigned long flags;
467 int limit = 100;
469 spin_lock_irqsave (&hub->tt.lock, flags);
470 while (--limit && !list_empty (&hub->tt.clear_list)) {
471 struct list_head *next;
472 struct usb_tt_clear *clear;
473 struct usb_device *hdev = hub->hdev;
474 const struct hc_driver *drv;
475 int status;
477 next = hub->tt.clear_list.next;
478 clear = list_entry (next, struct usb_tt_clear, clear_list);
479 list_del (&clear->clear_list);
481 /* drop lock so HCD can concurrently report other TT errors */
482 spin_unlock_irqrestore (&hub->tt.lock, flags);
483 status = hub_clear_tt_buffer (hdev, clear->devinfo, clear->tt);
484 if (status)
485 dev_err (&hdev->dev,
486 "clear tt %d (%04x) error %d\n",
487 clear->tt, clear->devinfo, status);
489 /* Tell the HCD, even if the operation failed */
490 drv = clear->hcd->driver;
491 if (drv->clear_tt_buffer_complete)
492 (drv->clear_tt_buffer_complete)(clear->hcd, clear->ep);
494 kfree(clear);
495 spin_lock_irqsave(&hub->tt.lock, flags);
497 spin_unlock_irqrestore (&hub->tt.lock, flags);
501 * usb_hub_clear_tt_buffer - clear control/bulk TT state in high speed hub
502 * @urb: an URB associated with the failed or incomplete split transaction
504 * High speed HCDs use this to tell the hub driver that some split control or
505 * bulk transaction failed in a way that requires clearing internal state of
506 * a transaction translator. This is normally detected (and reported) from
507 * interrupt context.
509 * It may not be possible for that hub to handle additional full (or low)
510 * speed transactions until that state is fully cleared out.
512 int usb_hub_clear_tt_buffer(struct urb *urb)
514 struct usb_device *udev = urb->dev;
515 int pipe = urb->pipe;
516 struct usb_tt *tt = udev->tt;
517 unsigned long flags;
518 struct usb_tt_clear *clear;
520 /* we've got to cope with an arbitrary number of pending TT clears,
521 * since each TT has "at least two" buffers that can need it (and
522 * there can be many TTs per hub). even if they're uncommon.
524 if ((clear = kmalloc (sizeof *clear, GFP_ATOMIC)) == NULL) {
525 dev_err (&udev->dev, "can't save CLEAR_TT_BUFFER state\n");
526 /* FIXME recover somehow ... RESET_TT? */
527 return -ENOMEM;
530 /* info that CLEAR_TT_BUFFER needs */
531 clear->tt = tt->multi ? udev->ttport : 1;
532 clear->devinfo = usb_pipeendpoint (pipe);
533 clear->devinfo |= udev->devnum << 4;
534 clear->devinfo |= usb_pipecontrol (pipe)
535 ? (USB_ENDPOINT_XFER_CONTROL << 11)
536 : (USB_ENDPOINT_XFER_BULK << 11);
537 if (usb_pipein (pipe))
538 clear->devinfo |= 1 << 15;
540 /* info for completion callback */
541 clear->hcd = bus_to_hcd(udev->bus);
542 clear->ep = urb->ep;
544 /* tell keventd to clear state for this TT */
545 spin_lock_irqsave (&tt->lock, flags);
546 list_add_tail (&clear->clear_list, &tt->clear_list);
547 schedule_work(&tt->clear_work);
548 spin_unlock_irqrestore (&tt->lock, flags);
549 return 0;
551 EXPORT_SYMBOL_GPL(usb_hub_clear_tt_buffer);
553 /* If do_delay is false, return the number of milliseconds the caller
554 * needs to delay.
556 static unsigned hub_power_on(struct usb_hub *hub, bool do_delay)
558 int port1;
559 unsigned pgood_delay = hub->descriptor->bPwrOn2PwrGood * 2;
560 unsigned delay;
561 u16 wHubCharacteristics =
562 le16_to_cpu(hub->descriptor->wHubCharacteristics);
564 /* Enable power on each port. Some hubs have reserved values
565 * of LPSM (> 2) in their descriptors, even though they are
566 * USB 2.0 hubs. Some hubs do not implement port-power switching
567 * but only emulate it. In all cases, the ports won't work
568 * unless we send these messages to the hub.
570 if ((wHubCharacteristics & HUB_CHAR_LPSM) < 2)
571 dev_dbg(hub->intfdev, "enabling power on all ports\n");
572 else
573 dev_dbg(hub->intfdev, "trying to enable port power on "
574 "non-switchable hub\n");
575 for (port1 = 1; port1 <= hub->descriptor->bNbrPorts; port1++)
576 set_port_feature(hub->hdev, port1, USB_PORT_FEAT_POWER);
578 /* Wait at least 100 msec for power to become stable */
579 delay = max(pgood_delay, (unsigned) 100);
580 if (do_delay)
581 msleep(delay);
582 return delay;
585 static int hub_hub_status(struct usb_hub *hub,
586 u16 *status, u16 *change)
588 int ret;
590 mutex_lock(&hub->status_mutex);
591 ret = get_hub_status(hub->hdev, &hub->status->hub);
592 if (ret < 0)
593 dev_err (hub->intfdev,
594 "%s failed (err = %d)\n", __func__, ret);
595 else {
596 *status = le16_to_cpu(hub->status->hub.wHubStatus);
597 *change = le16_to_cpu(hub->status->hub.wHubChange);
598 ret = 0;
600 mutex_unlock(&hub->status_mutex);
601 return ret;
604 static int hub_port_disable(struct usb_hub *hub, int port1, int set_state)
606 struct usb_device *hdev = hub->hdev;
607 int ret = 0;
609 if (hdev->children[port1-1] && set_state)
610 usb_set_device_state(hdev->children[port1-1],
611 USB_STATE_NOTATTACHED);
612 if (!hub->error)
613 ret = clear_port_feature(hdev, port1, USB_PORT_FEAT_ENABLE);
614 if (ret)
615 dev_err(hub->intfdev, "cannot disable port %d (err = %d)\n",
616 port1, ret);
617 return ret;
621 * Disable a port and mark a logical connnect-change event, so that some
622 * time later khubd will disconnect() any existing usb_device on the port
623 * and will re-enumerate if there actually is a device attached.
625 static void hub_port_logical_disconnect(struct usb_hub *hub, int port1)
627 dev_dbg(hub->intfdev, "logical disconnect on port %d\n", port1);
628 hub_port_disable(hub, port1, 1);
630 /* FIXME let caller ask to power down the port:
631 * - some devices won't enumerate without a VBUS power cycle
632 * - SRP saves power that way
633 * - ... new call, TBD ...
634 * That's easy if this hub can switch power per-port, and
635 * khubd reactivates the port later (timer, SRP, etc).
636 * Powerdown must be optional, because of reset/DFU.
639 set_bit(port1, hub->change_bits);
640 kick_khubd(hub);
644 * usb_remove_device - disable a device's port on its parent hub
645 * @udev: device to be disabled and removed
646 * Context: @udev locked, must be able to sleep.
648 * After @udev's port has been disabled, khubd is notified and it will
649 * see that the device has been disconnected. When the device is
650 * physically unplugged and something is plugged in, the events will
651 * be received and processed normally.
653 int usb_remove_device(struct usb_device *udev)
655 struct usb_hub *hub;
656 struct usb_interface *intf;
658 if (!udev->parent) /* Can't remove a root hub */
659 return -EINVAL;
660 hub = hdev_to_hub(udev->parent);
661 intf = to_usb_interface(hub->intfdev);
663 usb_autopm_get_interface(intf);
664 set_bit(udev->portnum, hub->removed_bits);
665 hub_port_logical_disconnect(hub, udev->portnum);
666 usb_autopm_put_interface(intf);
667 return 0;
670 enum hub_activation_type {
671 HUB_INIT, HUB_INIT2, HUB_INIT3, /* INITs must come first */
672 HUB_POST_RESET, HUB_RESUME, HUB_RESET_RESUME,
675 static void hub_init_func2(struct work_struct *ws);
676 static void hub_init_func3(struct work_struct *ws);
678 static void hub_activate(struct usb_hub *hub, enum hub_activation_type type)
680 struct usb_device *hdev = hub->hdev;
681 int port1;
682 int status;
683 bool need_debounce_delay = false;
684 unsigned delay;
686 /* Continue a partial initialization */
687 if (type == HUB_INIT2)
688 goto init2;
689 if (type == HUB_INIT3)
690 goto init3;
692 /* After a resume, port power should still be on.
693 * For any other type of activation, turn it on.
695 if (type != HUB_RESUME) {
697 /* Speed up system boot by using a delayed_work for the
698 * hub's initial power-up delays. This is pretty awkward
699 * and the implementation looks like a home-brewed sort of
700 * setjmp/longjmp, but it saves at least 100 ms for each
701 * root hub (assuming usbcore is compiled into the kernel
702 * rather than as a module). It adds up.
704 * This can't be done for HUB_RESUME or HUB_RESET_RESUME
705 * because for those activation types the ports have to be
706 * operational when we return. In theory this could be done
707 * for HUB_POST_RESET, but it's easier not to.
709 if (type == HUB_INIT) {
710 delay = hub_power_on(hub, false);
711 PREPARE_DELAYED_WORK(&hub->init_work, hub_init_func2);
712 schedule_delayed_work(&hub->init_work,
713 msecs_to_jiffies(delay));
715 /* Suppress autosuspend until init is done */
716 usb_autopm_get_interface_no_resume(
717 to_usb_interface(hub->intfdev));
718 return; /* Continues at init2: below */
719 } else {
720 hub_power_on(hub, true);
723 init2:
725 /* Check each port and set hub->change_bits to let khubd know
726 * which ports need attention.
728 for (port1 = 1; port1 <= hdev->maxchild; ++port1) {
729 struct usb_device *udev = hdev->children[port1-1];
730 u16 portstatus, portchange;
732 portstatus = portchange = 0;
733 status = hub_port_status(hub, port1, &portstatus, &portchange);
734 if (udev || (portstatus & USB_PORT_STAT_CONNECTION))
735 dev_dbg(hub->intfdev,
736 "port %d: status %04x change %04x\n",
737 port1, portstatus, portchange);
739 /* After anything other than HUB_RESUME (i.e., initialization
740 * or any sort of reset), every port should be disabled.
741 * Unconnected ports should likewise be disabled (paranoia),
742 * and so should ports for which we have no usb_device.
744 if ((portstatus & USB_PORT_STAT_ENABLE) && (
745 type != HUB_RESUME ||
746 !(portstatus & USB_PORT_STAT_CONNECTION) ||
747 !udev ||
748 udev->state == USB_STATE_NOTATTACHED)) {
749 clear_port_feature(hdev, port1, USB_PORT_FEAT_ENABLE);
750 portstatus &= ~USB_PORT_STAT_ENABLE;
753 /* Clear status-change flags; we'll debounce later */
754 if (portchange & USB_PORT_STAT_C_CONNECTION) {
755 need_debounce_delay = true;
756 clear_port_feature(hub->hdev, port1,
757 USB_PORT_FEAT_C_CONNECTION);
759 if (portchange & USB_PORT_STAT_C_ENABLE) {
760 need_debounce_delay = true;
761 clear_port_feature(hub->hdev, port1,
762 USB_PORT_FEAT_C_ENABLE);
765 /* We can forget about a "removed" device when there's a
766 * physical disconnect or the connect status changes.
768 if (!(portstatus & USB_PORT_STAT_CONNECTION) ||
769 (portchange & USB_PORT_STAT_C_CONNECTION))
770 clear_bit(port1, hub->removed_bits);
772 if (!udev || udev->state == USB_STATE_NOTATTACHED) {
773 /* Tell khubd to disconnect the device or
774 * check for a new connection
776 if (udev || (portstatus & USB_PORT_STAT_CONNECTION))
777 set_bit(port1, hub->change_bits);
779 } else if (portstatus & USB_PORT_STAT_ENABLE) {
780 /* The power session apparently survived the resume.
781 * If there was an overcurrent or suspend change
782 * (i.e., remote wakeup request), have khubd
783 * take care of it.
785 if (portchange)
786 set_bit(port1, hub->change_bits);
788 } else if (udev->persist_enabled) {
789 #ifdef CONFIG_PM
790 udev->reset_resume = 1;
791 #endif
792 set_bit(port1, hub->change_bits);
794 } else {
795 /* The power session is gone; tell khubd */
796 usb_set_device_state(udev, USB_STATE_NOTATTACHED);
797 set_bit(port1, hub->change_bits);
801 /* If no port-status-change flags were set, we don't need any
802 * debouncing. If flags were set we can try to debounce the
803 * ports all at once right now, instead of letting khubd do them
804 * one at a time later on.
806 * If any port-status changes do occur during this delay, khubd
807 * will see them later and handle them normally.
809 if (need_debounce_delay) {
810 delay = HUB_DEBOUNCE_STABLE;
812 /* Don't do a long sleep inside a workqueue routine */
813 if (type == HUB_INIT2) {
814 PREPARE_DELAYED_WORK(&hub->init_work, hub_init_func3);
815 schedule_delayed_work(&hub->init_work,
816 msecs_to_jiffies(delay));
817 return; /* Continues at init3: below */
818 } else {
819 msleep(delay);
822 init3:
823 hub->quiescing = 0;
825 status = usb_submit_urb(hub->urb, GFP_NOIO);
826 if (status < 0)
827 dev_err(hub->intfdev, "activate --> %d\n", status);
828 if (hub->has_indicators && blinkenlights)
829 schedule_delayed_work(&hub->leds, LED_CYCLE_PERIOD);
831 /* Scan all ports that need attention */
832 kick_khubd(hub);
834 /* Allow autosuspend if it was suppressed */
835 if (type <= HUB_INIT3)
836 usb_autopm_put_interface_async(to_usb_interface(hub->intfdev));
839 /* Implement the continuations for the delays above */
840 static void hub_init_func2(struct work_struct *ws)
842 struct usb_hub *hub = container_of(ws, struct usb_hub, init_work.work);
844 hub_activate(hub, HUB_INIT2);
847 static void hub_init_func3(struct work_struct *ws)
849 struct usb_hub *hub = container_of(ws, struct usb_hub, init_work.work);
851 hub_activate(hub, HUB_INIT3);
854 enum hub_quiescing_type {
855 HUB_DISCONNECT, HUB_PRE_RESET, HUB_SUSPEND
858 static void hub_quiesce(struct usb_hub *hub, enum hub_quiescing_type type)
860 struct usb_device *hdev = hub->hdev;
861 int i;
863 cancel_delayed_work_sync(&hub->init_work);
865 /* khubd and related activity won't re-trigger */
866 hub->quiescing = 1;
868 if (type != HUB_SUSPEND) {
869 /* Disconnect all the children */
870 for (i = 0; i < hdev->maxchild; ++i) {
871 if (hdev->children[i])
872 usb_disconnect(&hdev->children[i]);
876 /* Stop khubd and related activity */
877 usb_kill_urb(hub->urb);
878 if (hub->has_indicators)
879 cancel_delayed_work_sync(&hub->leds);
880 if (hub->tt.hub)
881 cancel_work_sync(&hub->tt.clear_work);
884 /* caller has locked the hub device */
885 static int hub_pre_reset(struct usb_interface *intf)
887 struct usb_hub *hub = usb_get_intfdata(intf);
889 hub_quiesce(hub, HUB_PRE_RESET);
890 return 0;
893 /* caller has locked the hub device */
894 static int hub_post_reset(struct usb_interface *intf)
896 struct usb_hub *hub = usb_get_intfdata(intf);
898 hub_activate(hub, HUB_POST_RESET);
899 return 0;
902 static int hub_configure(struct usb_hub *hub,
903 struct usb_endpoint_descriptor *endpoint)
905 struct usb_hcd *hcd;
906 struct usb_device *hdev = hub->hdev;
907 struct device *hub_dev = hub->intfdev;
908 u16 hubstatus, hubchange;
909 u16 wHubCharacteristics;
910 unsigned int pipe;
911 int maxp, ret;
912 char *message = "out of memory";
914 hub->buffer = kmalloc(sizeof(*hub->buffer), GFP_KERNEL);
915 if (!hub->buffer) {
916 ret = -ENOMEM;
917 goto fail;
920 hub->status = kmalloc(sizeof(*hub->status), GFP_KERNEL);
921 if (!hub->status) {
922 ret = -ENOMEM;
923 goto fail;
925 mutex_init(&hub->status_mutex);
927 hub->descriptor = kmalloc(sizeof(*hub->descriptor), GFP_KERNEL);
928 if (!hub->descriptor) {
929 ret = -ENOMEM;
930 goto fail;
933 /* Request the entire hub descriptor.
934 * hub->descriptor can handle USB_MAXCHILDREN ports,
935 * but the hub can/will return fewer bytes here.
937 ret = get_hub_descriptor(hdev, hub->descriptor,
938 sizeof(*hub->descriptor));
939 if (ret < 0) {
940 message = "can't read hub descriptor";
941 goto fail;
942 } else if (hub->descriptor->bNbrPorts > USB_MAXCHILDREN) {
943 message = "hub has too many ports!";
944 ret = -ENODEV;
945 goto fail;
948 hdev->maxchild = hub->descriptor->bNbrPorts;
949 dev_info (hub_dev, "%d port%s detected\n", hdev->maxchild,
950 (hdev->maxchild == 1) ? "" : "s");
952 hub->port_owners = kzalloc(hdev->maxchild * sizeof(void *), GFP_KERNEL);
953 if (!hub->port_owners) {
954 ret = -ENOMEM;
955 goto fail;
958 wHubCharacteristics = le16_to_cpu(hub->descriptor->wHubCharacteristics);
960 if (wHubCharacteristics & HUB_CHAR_COMPOUND) {
961 int i;
962 char portstr [USB_MAXCHILDREN + 1];
964 for (i = 0; i < hdev->maxchild; i++)
965 portstr[i] = hub->descriptor->DeviceRemovable
966 [((i + 1) / 8)] & (1 << ((i + 1) % 8))
967 ? 'F' : 'R';
968 portstr[hdev->maxchild] = 0;
969 dev_dbg(hub_dev, "compound device; port removable status: %s\n", portstr);
970 } else
971 dev_dbg(hub_dev, "standalone hub\n");
973 switch (wHubCharacteristics & HUB_CHAR_LPSM) {
974 case 0x00:
975 dev_dbg(hub_dev, "ganged power switching\n");
976 break;
977 case 0x01:
978 dev_dbg(hub_dev, "individual port power switching\n");
979 break;
980 case 0x02:
981 case 0x03:
982 dev_dbg(hub_dev, "no power switching (usb 1.0)\n");
983 break;
986 switch (wHubCharacteristics & HUB_CHAR_OCPM) {
987 case 0x00:
988 dev_dbg(hub_dev, "global over-current protection\n");
989 break;
990 case 0x08:
991 dev_dbg(hub_dev, "individual port over-current protection\n");
992 break;
993 case 0x10:
994 case 0x18:
995 dev_dbg(hub_dev, "no over-current protection\n");
996 break;
999 spin_lock_init (&hub->tt.lock);
1000 INIT_LIST_HEAD (&hub->tt.clear_list);
1001 INIT_WORK(&hub->tt.clear_work, hub_tt_work);
1002 switch (hdev->descriptor.bDeviceProtocol) {
1003 case 0:
1004 break;
1005 case 1:
1006 dev_dbg(hub_dev, "Single TT\n");
1007 hub->tt.hub = hdev;
1008 break;
1009 case 2:
1010 ret = usb_set_interface(hdev, 0, 1);
1011 if (ret == 0) {
1012 dev_dbg(hub_dev, "TT per port\n");
1013 hub->tt.multi = 1;
1014 } else
1015 dev_err(hub_dev, "Using single TT (err %d)\n",
1016 ret);
1017 hub->tt.hub = hdev;
1018 break;
1019 case 3:
1020 /* USB 3.0 hubs don't have a TT */
1021 break;
1022 default:
1023 dev_dbg(hub_dev, "Unrecognized hub protocol %d\n",
1024 hdev->descriptor.bDeviceProtocol);
1025 break;
1028 /* Note 8 FS bit times == (8 bits / 12000000 bps) ~= 666ns */
1029 switch (wHubCharacteristics & HUB_CHAR_TTTT) {
1030 case HUB_TTTT_8_BITS:
1031 if (hdev->descriptor.bDeviceProtocol != 0) {
1032 hub->tt.think_time = 666;
1033 dev_dbg(hub_dev, "TT requires at most %d "
1034 "FS bit times (%d ns)\n",
1035 8, hub->tt.think_time);
1037 break;
1038 case HUB_TTTT_16_BITS:
1039 hub->tt.think_time = 666 * 2;
1040 dev_dbg(hub_dev, "TT requires at most %d "
1041 "FS bit times (%d ns)\n",
1042 16, hub->tt.think_time);
1043 break;
1044 case HUB_TTTT_24_BITS:
1045 hub->tt.think_time = 666 * 3;
1046 dev_dbg(hub_dev, "TT requires at most %d "
1047 "FS bit times (%d ns)\n",
1048 24, hub->tt.think_time);
1049 break;
1050 case HUB_TTTT_32_BITS:
1051 hub->tt.think_time = 666 * 4;
1052 dev_dbg(hub_dev, "TT requires at most %d "
1053 "FS bit times (%d ns)\n",
1054 32, hub->tt.think_time);
1055 break;
1058 /* probe() zeroes hub->indicator[] */
1059 if (wHubCharacteristics & HUB_CHAR_PORTIND) {
1060 hub->has_indicators = 1;
1061 dev_dbg(hub_dev, "Port indicators are supported\n");
1064 dev_dbg(hub_dev, "power on to power good time: %dms\n",
1065 hub->descriptor->bPwrOn2PwrGood * 2);
1067 /* power budgeting mostly matters with bus-powered hubs,
1068 * and battery-powered root hubs (may provide just 8 mA).
1070 ret = usb_get_status(hdev, USB_RECIP_DEVICE, 0, &hubstatus);
1071 if (ret < 2) {
1072 message = "can't get hub status";
1073 goto fail;
1075 le16_to_cpus(&hubstatus);
1076 if (hdev == hdev->bus->root_hub) {
1077 if (hdev->bus_mA == 0 || hdev->bus_mA >= 500)
1078 hub->mA_per_port = 500;
1079 else {
1080 hub->mA_per_port = hdev->bus_mA;
1081 hub->limited_power = 1;
1083 } else if ((hubstatus & (1 << USB_DEVICE_SELF_POWERED)) == 0) {
1084 dev_dbg(hub_dev, "hub controller current requirement: %dmA\n",
1085 hub->descriptor->bHubContrCurrent);
1086 hub->limited_power = 1;
1087 if (hdev->maxchild > 0) {
1088 int remaining = hdev->bus_mA -
1089 hub->descriptor->bHubContrCurrent;
1091 if (remaining < hdev->maxchild * 100)
1092 dev_warn(hub_dev,
1093 "insufficient power available "
1094 "to use all downstream ports\n");
1095 hub->mA_per_port = 100; /* 7.2.1.1 */
1097 } else { /* Self-powered external hub */
1098 /* FIXME: What about battery-powered external hubs that
1099 * provide less current per port? */
1100 hub->mA_per_port = 500;
1102 if (hub->mA_per_port < 500)
1103 dev_dbg(hub_dev, "%umA bus power budget for each child\n",
1104 hub->mA_per_port);
1106 /* Update the HCD's internal representation of this hub before khubd
1107 * starts getting port status changes for devices under the hub.
1109 hcd = bus_to_hcd(hdev->bus);
1110 if (hcd->driver->update_hub_device) {
1111 ret = hcd->driver->update_hub_device(hcd, hdev,
1112 &hub->tt, GFP_KERNEL);
1113 if (ret < 0) {
1114 message = "can't update HCD hub info";
1115 goto fail;
1119 ret = hub_hub_status(hub, &hubstatus, &hubchange);
1120 if (ret < 0) {
1121 message = "can't get hub status";
1122 goto fail;
1125 /* local power status reports aren't always correct */
1126 if (hdev->actconfig->desc.bmAttributes & USB_CONFIG_ATT_SELFPOWER)
1127 dev_dbg(hub_dev, "local power source is %s\n",
1128 (hubstatus & HUB_STATUS_LOCAL_POWER)
1129 ? "lost (inactive)" : "good");
1131 if ((wHubCharacteristics & HUB_CHAR_OCPM) == 0)
1132 dev_dbg(hub_dev, "%sover-current condition exists\n",
1133 (hubstatus & HUB_STATUS_OVERCURRENT) ? "" : "no ");
1135 /* set up the interrupt endpoint
1136 * We use the EP's maxpacket size instead of (PORTS+1+7)/8
1137 * bytes as USB2.0[11.12.3] says because some hubs are known
1138 * to send more data (and thus cause overflow). For root hubs,
1139 * maxpktsize is defined in hcd.c's fake endpoint descriptors
1140 * to be big enough for at least USB_MAXCHILDREN ports. */
1141 pipe = usb_rcvintpipe(hdev, endpoint->bEndpointAddress);
1142 maxp = usb_maxpacket(hdev, pipe, usb_pipeout(pipe));
1144 if (maxp > sizeof(*hub->buffer))
1145 maxp = sizeof(*hub->buffer);
1147 hub->urb = usb_alloc_urb(0, GFP_KERNEL);
1148 if (!hub->urb) {
1149 ret = -ENOMEM;
1150 goto fail;
1153 usb_fill_int_urb(hub->urb, hdev, pipe, *hub->buffer, maxp, hub_irq,
1154 hub, endpoint->bInterval);
1156 /* maybe cycle the hub leds */
1157 if (hub->has_indicators && blinkenlights)
1158 hub->indicator [0] = INDICATOR_CYCLE;
1160 hub_activate(hub, HUB_INIT);
1161 return 0;
1163 fail:
1164 dev_err (hub_dev, "config failed, %s (err %d)\n",
1165 message, ret);
1166 /* hub_disconnect() frees urb and descriptor */
1167 return ret;
1170 static void hub_release(struct kref *kref)
1172 struct usb_hub *hub = container_of(kref, struct usb_hub, kref);
1174 usb_put_intf(to_usb_interface(hub->intfdev));
1175 kfree(hub);
1178 static unsigned highspeed_hubs;
1180 static void hub_disconnect(struct usb_interface *intf)
1182 struct usb_hub *hub = usb_get_intfdata (intf);
1184 /* Take the hub off the event list and don't let it be added again */
1185 spin_lock_irq(&hub_event_lock);
1186 if (!list_empty(&hub->event_list)) {
1187 list_del_init(&hub->event_list);
1188 usb_autopm_put_interface_no_suspend(intf);
1190 hub->disconnected = 1;
1191 spin_unlock_irq(&hub_event_lock);
1193 /* Disconnect all children and quiesce the hub */
1194 hub->error = 0;
1195 hub_quiesce(hub, HUB_DISCONNECT);
1197 usb_set_intfdata (intf, NULL);
1198 hub->hdev->maxchild = 0;
1200 if (hub->hdev->speed == USB_SPEED_HIGH)
1201 highspeed_hubs--;
1203 usb_free_urb(hub->urb);
1204 kfree(hub->port_owners);
1205 kfree(hub->descriptor);
1206 kfree(hub->status);
1207 kfree(hub->buffer);
1209 kref_put(&hub->kref, hub_release);
1212 static int hub_probe(struct usb_interface *intf, const struct usb_device_id *id)
1214 struct usb_host_interface *desc;
1215 struct usb_endpoint_descriptor *endpoint;
1216 struct usb_device *hdev;
1217 struct usb_hub *hub;
1219 desc = intf->cur_altsetting;
1220 hdev = interface_to_usbdev(intf);
1222 /* Hubs have proper suspend/resume support */
1223 usb_enable_autosuspend(hdev);
1225 if (hdev->level == MAX_TOPO_LEVEL) {
1226 dev_err(&intf->dev,
1227 "Unsupported bus topology: hub nested too deep\n");
1228 return -E2BIG;
1231 #ifdef CONFIG_USB_OTG_BLACKLIST_HUB
1232 if (hdev->parent) {
1233 dev_warn(&intf->dev, "ignoring external hub\n");
1234 return -ENODEV;
1236 #endif
1238 /* Some hubs have a subclass of 1, which AFAICT according to the */
1239 /* specs is not defined, but it works */
1240 if ((desc->desc.bInterfaceSubClass != 0) &&
1241 (desc->desc.bInterfaceSubClass != 1)) {
1242 descriptor_error:
1243 dev_err (&intf->dev, "bad descriptor, ignoring hub\n");
1244 return -EIO;
1247 /* Multiple endpoints? What kind of mutant ninja-hub is this? */
1248 if (desc->desc.bNumEndpoints != 1)
1249 goto descriptor_error;
1251 endpoint = &desc->endpoint[0].desc;
1253 /* If it's not an interrupt in endpoint, we'd better punt! */
1254 if (!usb_endpoint_is_int_in(endpoint))
1255 goto descriptor_error;
1257 /* We found a hub */
1258 dev_info (&intf->dev, "USB hub found\n");
1260 hub = kzalloc(sizeof(*hub), GFP_KERNEL);
1261 if (!hub) {
1262 dev_dbg (&intf->dev, "couldn't kmalloc hub struct\n");
1263 return -ENOMEM;
1266 kref_init(&hub->kref);
1267 INIT_LIST_HEAD(&hub->event_list);
1268 hub->intfdev = &intf->dev;
1269 hub->hdev = hdev;
1270 INIT_DELAYED_WORK(&hub->leds, led_work);
1271 INIT_DELAYED_WORK(&hub->init_work, NULL);
1272 usb_get_intf(intf);
1274 usb_set_intfdata (intf, hub);
1275 intf->needs_remote_wakeup = 1;
1277 if (hdev->speed == USB_SPEED_HIGH)
1278 highspeed_hubs++;
1280 if (hub_configure(hub, endpoint) >= 0)
1281 return 0;
1283 hub_disconnect (intf);
1284 return -ENODEV;
1287 static int
1288 hub_ioctl(struct usb_interface *intf, unsigned int code, void *user_data)
1290 struct usb_device *hdev = interface_to_usbdev (intf);
1292 /* assert ifno == 0 (part of hub spec) */
1293 switch (code) {
1294 case USBDEVFS_HUB_PORTINFO: {
1295 struct usbdevfs_hub_portinfo *info = user_data;
1296 int i;
1298 spin_lock_irq(&device_state_lock);
1299 if (hdev->devnum <= 0)
1300 info->nports = 0;
1301 else {
1302 info->nports = hdev->maxchild;
1303 for (i = 0; i < info->nports; i++) {
1304 if (hdev->children[i] == NULL)
1305 info->port[i] = 0;
1306 else
1307 info->port[i] =
1308 hdev->children[i]->devnum;
1311 spin_unlock_irq(&device_state_lock);
1313 return info->nports + 1;
1316 default:
1317 return -ENOSYS;
1322 * Allow user programs to claim ports on a hub. When a device is attached
1323 * to one of these "claimed" ports, the program will "own" the device.
1325 static int find_port_owner(struct usb_device *hdev, unsigned port1,
1326 void ***ppowner)
1328 if (hdev->state == USB_STATE_NOTATTACHED)
1329 return -ENODEV;
1330 if (port1 == 0 || port1 > hdev->maxchild)
1331 return -EINVAL;
1333 /* This assumes that devices not managed by the hub driver
1334 * will always have maxchild equal to 0.
1336 *ppowner = &(hdev_to_hub(hdev)->port_owners[port1 - 1]);
1337 return 0;
1340 /* In the following three functions, the caller must hold hdev's lock */
1341 int usb_hub_claim_port(struct usb_device *hdev, unsigned port1, void *owner)
1343 int rc;
1344 void **powner;
1346 rc = find_port_owner(hdev, port1, &powner);
1347 if (rc)
1348 return rc;
1349 if (*powner)
1350 return -EBUSY;
1351 *powner = owner;
1352 return rc;
1355 int usb_hub_release_port(struct usb_device *hdev, unsigned port1, void *owner)
1357 int rc;
1358 void **powner;
1360 rc = find_port_owner(hdev, port1, &powner);
1361 if (rc)
1362 return rc;
1363 if (*powner != owner)
1364 return -ENOENT;
1365 *powner = NULL;
1366 return rc;
1369 void usb_hub_release_all_ports(struct usb_device *hdev, void *owner)
1371 int n;
1372 void **powner;
1374 n = find_port_owner(hdev, 1, &powner);
1375 if (n == 0) {
1376 for (; n < hdev->maxchild; (++n, ++powner)) {
1377 if (*powner == owner)
1378 *powner = NULL;
1383 /* The caller must hold udev's lock */
1384 bool usb_device_is_owned(struct usb_device *udev)
1386 struct usb_hub *hub;
1388 if (udev->state == USB_STATE_NOTATTACHED || !udev->parent)
1389 return false;
1390 hub = hdev_to_hub(udev->parent);
1391 return !!hub->port_owners[udev->portnum - 1];
1395 static void recursively_mark_NOTATTACHED(struct usb_device *udev)
1397 int i;
1399 for (i = 0; i < udev->maxchild; ++i) {
1400 if (udev->children[i])
1401 recursively_mark_NOTATTACHED(udev->children[i]);
1403 if (udev->state == USB_STATE_SUSPENDED)
1404 udev->active_duration -= jiffies;
1405 udev->state = USB_STATE_NOTATTACHED;
1409 * usb_set_device_state - change a device's current state (usbcore, hcds)
1410 * @udev: pointer to device whose state should be changed
1411 * @new_state: new state value to be stored
1413 * udev->state is _not_ fully protected by the device lock. Although
1414 * most transitions are made only while holding the lock, the state can
1415 * can change to USB_STATE_NOTATTACHED at almost any time. This
1416 * is so that devices can be marked as disconnected as soon as possible,
1417 * without having to wait for any semaphores to be released. As a result,
1418 * all changes to any device's state must be protected by the
1419 * device_state_lock spinlock.
1421 * Once a device has been added to the device tree, all changes to its state
1422 * should be made using this routine. The state should _not_ be set directly.
1424 * If udev->state is already USB_STATE_NOTATTACHED then no change is made.
1425 * Otherwise udev->state is set to new_state, and if new_state is
1426 * USB_STATE_NOTATTACHED then all of udev's descendants' states are also set
1427 * to USB_STATE_NOTATTACHED.
1429 void usb_set_device_state(struct usb_device *udev,
1430 enum usb_device_state new_state)
1432 unsigned long flags;
1434 spin_lock_irqsave(&device_state_lock, flags);
1435 if (udev->state == USB_STATE_NOTATTACHED)
1436 ; /* do nothing */
1437 else if (new_state != USB_STATE_NOTATTACHED) {
1439 /* root hub wakeup capabilities are managed out-of-band
1440 * and may involve silicon errata ... ignore them here.
1442 if (udev->parent) {
1443 if (udev->state == USB_STATE_SUSPENDED
1444 || new_state == USB_STATE_SUSPENDED)
1445 ; /* No change to wakeup settings */
1446 else if (new_state == USB_STATE_CONFIGURED)
1447 device_set_wakeup_capable(&udev->dev,
1448 (udev->actconfig->desc.bmAttributes
1449 & USB_CONFIG_ATT_WAKEUP));
1450 else
1451 device_set_wakeup_capable(&udev->dev, 0);
1453 if (udev->state == USB_STATE_SUSPENDED &&
1454 new_state != USB_STATE_SUSPENDED)
1455 udev->active_duration -= jiffies;
1456 else if (new_state == USB_STATE_SUSPENDED &&
1457 udev->state != USB_STATE_SUSPENDED)
1458 udev->active_duration += jiffies;
1459 udev->state = new_state;
1460 } else
1461 recursively_mark_NOTATTACHED(udev);
1462 spin_unlock_irqrestore(&device_state_lock, flags);
1464 EXPORT_SYMBOL_GPL(usb_set_device_state);
1467 * WUSB devices are simple: they have no hubs behind, so the mapping
1468 * device <-> virtual port number becomes 1:1. Why? to simplify the
1469 * life of the device connection logic in
1470 * drivers/usb/wusbcore/devconnect.c. When we do the initial secret
1471 * handshake we need to assign a temporary address in the unauthorized
1472 * space. For simplicity we use the first virtual port number found to
1473 * be free [drivers/usb/wusbcore/devconnect.c:wusbhc_devconnect_ack()]
1474 * and that becomes it's address [X < 128] or its unauthorized address
1475 * [X | 0x80].
1477 * We add 1 as an offset to the one-based USB-stack port number
1478 * (zero-based wusb virtual port index) for two reasons: (a) dev addr
1479 * 0 is reserved by USB for default address; (b) Linux's USB stack
1480 * uses always #1 for the root hub of the controller. So USB stack's
1481 * port #1, which is wusb virtual-port #0 has address #2.
1483 * Devices connected under xHCI are not as simple. The host controller
1484 * supports virtualization, so the hardware assigns device addresses and
1485 * the HCD must setup data structures before issuing a set address
1486 * command to the hardware.
1488 static void choose_address(struct usb_device *udev)
1490 int devnum;
1491 struct usb_bus *bus = udev->bus;
1493 /* If khubd ever becomes multithreaded, this will need a lock */
1494 if (udev->wusb) {
1495 devnum = udev->portnum + 1;
1496 BUG_ON(test_bit(devnum, bus->devmap.devicemap));
1497 } else {
1498 /* Try to allocate the next devnum beginning at
1499 * bus->devnum_next. */
1500 devnum = find_next_zero_bit(bus->devmap.devicemap, 128,
1501 bus->devnum_next);
1502 if (devnum >= 128)
1503 devnum = find_next_zero_bit(bus->devmap.devicemap,
1504 128, 1);
1505 bus->devnum_next = ( devnum >= 127 ? 1 : devnum + 1);
1507 if (devnum < 128) {
1508 set_bit(devnum, bus->devmap.devicemap);
1509 udev->devnum = devnum;
1513 static void release_address(struct usb_device *udev)
1515 if (udev->devnum > 0) {
1516 clear_bit(udev->devnum, udev->bus->devmap.devicemap);
1517 udev->devnum = -1;
1521 static void update_address(struct usb_device *udev, int devnum)
1523 /* The address for a WUSB device is managed by wusbcore. */
1524 if (!udev->wusb)
1525 udev->devnum = devnum;
1528 static void hub_free_dev(struct usb_device *udev)
1530 struct usb_hcd *hcd = bus_to_hcd(udev->bus);
1532 /* Root hubs aren't real devices, so don't free HCD resources */
1533 if (hcd->driver->free_dev && udev->parent)
1534 hcd->driver->free_dev(hcd, udev);
1538 * usb_disconnect - disconnect a device (usbcore-internal)
1539 * @pdev: pointer to device being disconnected
1540 * Context: !in_interrupt ()
1542 * Something got disconnected. Get rid of it and all of its children.
1544 * If *pdev is a normal device then the parent hub must already be locked.
1545 * If *pdev is a root hub then this routine will acquire the
1546 * usb_bus_list_lock on behalf of the caller.
1548 * Only hub drivers (including virtual root hub drivers for host
1549 * controllers) should ever call this.
1551 * This call is synchronous, and may not be used in an interrupt context.
1553 void usb_disconnect(struct usb_device **pdev)
1555 struct usb_device *udev = *pdev;
1556 int i;
1558 if (!udev) {
1559 pr_debug ("%s nodev\n", __func__);
1560 return;
1563 /* mark the device as inactive, so any further urb submissions for
1564 * this device (and any of its children) will fail immediately.
1565 * this quiesces everyting except pending urbs.
1567 usb_set_device_state(udev, USB_STATE_NOTATTACHED);
1568 dev_info (&udev->dev, "USB disconnect, address %d\n", udev->devnum);
1570 usb_lock_device(udev);
1572 /* Free up all the children before we remove this device */
1573 for (i = 0; i < USB_MAXCHILDREN; i++) {
1574 if (udev->children[i])
1575 usb_disconnect(&udev->children[i]);
1578 /* deallocate hcd/hardware state ... nuking all pending urbs and
1579 * cleaning up all state associated with the current configuration
1580 * so that the hardware is now fully quiesced.
1582 dev_dbg (&udev->dev, "unregistering device\n");
1583 usb_disable_device(udev, 0);
1584 usb_hcd_synchronize_unlinks(udev);
1586 usb_remove_ep_devs(&udev->ep0);
1587 usb_unlock_device(udev);
1589 /* Unregister the device. The device driver is responsible
1590 * for de-configuring the device and invoking the remove-device
1591 * notifier chain (used by usbfs and possibly others).
1593 device_del(&udev->dev);
1595 /* Free the device number and delete the parent's children[]
1596 * (or root_hub) pointer.
1598 release_address(udev);
1600 /* Avoid races with recursively_mark_NOTATTACHED() */
1601 spin_lock_irq(&device_state_lock);
1602 *pdev = NULL;
1603 spin_unlock_irq(&device_state_lock);
1605 hub_free_dev(udev);
1607 put_device(&udev->dev);
1610 #ifdef CONFIG_USB_ANNOUNCE_NEW_DEVICES
1611 static void show_string(struct usb_device *udev, char *id, char *string)
1613 if (!string)
1614 return;
1615 dev_printk(KERN_INFO, &udev->dev, "%s: %s\n", id, string);
1618 static void announce_device(struct usb_device *udev)
1620 dev_info(&udev->dev, "New USB device found, idVendor=%04x, idProduct=%04x\n",
1621 le16_to_cpu(udev->descriptor.idVendor),
1622 le16_to_cpu(udev->descriptor.idProduct));
1623 dev_info(&udev->dev,
1624 "New USB device strings: Mfr=%d, Product=%d, SerialNumber=%d\n",
1625 udev->descriptor.iManufacturer,
1626 udev->descriptor.iProduct,
1627 udev->descriptor.iSerialNumber);
1628 show_string(udev, "Product", udev->product);
1629 show_string(udev, "Manufacturer", udev->manufacturer);
1630 show_string(udev, "SerialNumber", udev->serial);
1632 #else
1633 static inline void announce_device(struct usb_device *udev) { }
1634 #endif
1636 #ifdef CONFIG_USB_OTG
1637 #include "otg_whitelist.h"
1638 #endif
1641 * usb_enumerate_device_otg - FIXME (usbcore-internal)
1642 * @udev: newly addressed device (in ADDRESS state)
1644 * Finish enumeration for On-The-Go devices
1646 static int usb_enumerate_device_otg(struct usb_device *udev)
1648 int err = 0;
1650 #ifdef CONFIG_USB_OTG
1652 * OTG-aware devices on OTG-capable root hubs may be able to use SRP,
1653 * to wake us after we've powered off VBUS; and HNP, switching roles
1654 * "host" to "peripheral". The OTG descriptor helps figure this out.
1656 if (!udev->bus->is_b_host
1657 && udev->config
1658 && udev->parent == udev->bus->root_hub) {
1659 struct usb_otg_descriptor *desc = NULL;
1660 struct usb_bus *bus = udev->bus;
1662 /* descriptor may appear anywhere in config */
1663 if (__usb_get_extra_descriptor (udev->rawdescriptors[0],
1664 le16_to_cpu(udev->config[0].desc.wTotalLength),
1665 USB_DT_OTG, (void **) &desc) == 0) {
1666 if (desc->bmAttributes & USB_OTG_HNP) {
1667 unsigned port1 = udev->portnum;
1669 dev_info(&udev->dev,
1670 "Dual-Role OTG device on %sHNP port\n",
1671 (port1 == bus->otg_port)
1672 ? "" : "non-");
1674 /* enable HNP before suspend, it's simpler */
1675 if (port1 == bus->otg_port)
1676 bus->b_hnp_enable = 1;
1677 err = usb_control_msg(udev,
1678 usb_sndctrlpipe(udev, 0),
1679 USB_REQ_SET_FEATURE, 0,
1680 bus->b_hnp_enable
1681 ? USB_DEVICE_B_HNP_ENABLE
1682 : USB_DEVICE_A_ALT_HNP_SUPPORT,
1683 0, NULL, 0, USB_CTRL_SET_TIMEOUT);
1684 if (err < 0) {
1685 /* OTG MESSAGE: report errors here,
1686 * customize to match your product.
1688 dev_info(&udev->dev,
1689 "can't set HNP mode: %d\n",
1690 err);
1691 bus->b_hnp_enable = 0;
1697 if (!is_targeted(udev)) {
1699 /* Maybe it can talk to us, though we can't talk to it.
1700 * (Includes HNP test device.)
1702 if (udev->bus->b_hnp_enable || udev->bus->is_b_host) {
1703 err = usb_port_suspend(udev, PMSG_SUSPEND);
1704 if (err < 0)
1705 dev_dbg(&udev->dev, "HNP fail, %d\n", err);
1707 err = -ENOTSUPP;
1708 goto fail;
1710 fail:
1711 #endif
1712 return err;
1717 * usb_enumerate_device - Read device configs/intfs/otg (usbcore-internal)
1718 * @udev: newly addressed device (in ADDRESS state)
1720 * This is only called by usb_new_device() and usb_authorize_device()
1721 * and FIXME -- all comments that apply to them apply here wrt to
1722 * environment.
1724 * If the device is WUSB and not authorized, we don't attempt to read
1725 * the string descriptors, as they will be errored out by the device
1726 * until it has been authorized.
1728 static int usb_enumerate_device(struct usb_device *udev)
1730 int err;
1732 if (udev->config == NULL) {
1733 err = usb_get_configuration(udev);
1734 if (err < 0) {
1735 dev_err(&udev->dev, "can't read configurations, error %d\n",
1736 err);
1737 goto fail;
1740 if (udev->wusb == 1 && udev->authorized == 0) {
1741 udev->product = kstrdup("n/a (unauthorized)", GFP_KERNEL);
1742 udev->manufacturer = kstrdup("n/a (unauthorized)", GFP_KERNEL);
1743 udev->serial = kstrdup("n/a (unauthorized)", GFP_KERNEL);
1745 else {
1746 /* read the standard strings and cache them if present */
1747 udev->product = usb_cache_string(udev, udev->descriptor.iProduct);
1748 udev->manufacturer = usb_cache_string(udev,
1749 udev->descriptor.iManufacturer);
1750 udev->serial = usb_cache_string(udev, udev->descriptor.iSerialNumber);
1752 err = usb_enumerate_device_otg(udev);
1753 fail:
1754 return err;
1759 * usb_new_device - perform initial device setup (usbcore-internal)
1760 * @udev: newly addressed device (in ADDRESS state)
1762 * This is called with devices which have been detected but not fully
1763 * enumerated. The device descriptor is available, but not descriptors
1764 * for any device configuration. The caller must have locked either
1765 * the parent hub (if udev is a normal device) or else the
1766 * usb_bus_list_lock (if udev is a root hub). The parent's pointer to
1767 * udev has already been installed, but udev is not yet visible through
1768 * sysfs or other filesystem code.
1770 * It will return if the device is configured properly or not. Zero if
1771 * the interface was registered with the driver core; else a negative
1772 * errno value.
1774 * This call is synchronous, and may not be used in an interrupt context.
1776 * Only the hub driver or root-hub registrar should ever call this.
1778 int usb_new_device(struct usb_device *udev)
1780 int err;
1782 if (udev->parent) {
1783 /* Initialize non-root-hub device wakeup to disabled;
1784 * device (un)configuration controls wakeup capable
1785 * sysfs power/wakeup controls wakeup enabled/disabled
1787 device_init_wakeup(&udev->dev, 0);
1790 /* Tell the runtime-PM framework the device is active */
1791 pm_runtime_set_active(&udev->dev);
1792 pm_runtime_enable(&udev->dev);
1794 err = usb_enumerate_device(udev); /* Read descriptors */
1795 if (err < 0)
1796 goto fail;
1797 dev_dbg(&udev->dev, "udev %d, busnum %d, minor = %d\n",
1798 udev->devnum, udev->bus->busnum,
1799 (((udev->bus->busnum-1) * 128) + (udev->devnum-1)));
1800 /* export the usbdev device-node for libusb */
1801 udev->dev.devt = MKDEV(USB_DEVICE_MAJOR,
1802 (((udev->bus->busnum-1) * 128) + (udev->devnum-1)));
1804 /* Tell the world! */
1805 announce_device(udev);
1807 device_enable_async_suspend(&udev->dev);
1808 /* Register the device. The device driver is responsible
1809 * for configuring the device and invoking the add-device
1810 * notifier chain (used by usbfs and possibly others).
1812 err = device_add(&udev->dev);
1813 if (err) {
1814 dev_err(&udev->dev, "can't device_add, error %d\n", err);
1815 goto fail;
1818 (void) usb_create_ep_devs(&udev->dev, &udev->ep0, udev);
1819 return err;
1821 fail:
1822 usb_set_device_state(udev, USB_STATE_NOTATTACHED);
1823 pm_runtime_disable(&udev->dev);
1824 pm_runtime_set_suspended(&udev->dev);
1825 return err;
1830 * usb_deauthorize_device - deauthorize a device (usbcore-internal)
1831 * @usb_dev: USB device
1833 * Move the USB device to a very basic state where interfaces are disabled
1834 * and the device is in fact unconfigured and unusable.
1836 * We share a lock (that we have) with device_del(), so we need to
1837 * defer its call.
1839 int usb_deauthorize_device(struct usb_device *usb_dev)
1841 usb_lock_device(usb_dev);
1842 if (usb_dev->authorized == 0)
1843 goto out_unauthorized;
1845 usb_dev->authorized = 0;
1846 usb_set_configuration(usb_dev, -1);
1848 kfree(usb_dev->product);
1849 usb_dev->product = kstrdup("n/a (unauthorized)", GFP_KERNEL);
1850 kfree(usb_dev->manufacturer);
1851 usb_dev->manufacturer = kstrdup("n/a (unauthorized)", GFP_KERNEL);
1852 kfree(usb_dev->serial);
1853 usb_dev->serial = kstrdup("n/a (unauthorized)", GFP_KERNEL);
1855 usb_destroy_configuration(usb_dev);
1856 usb_dev->descriptor.bNumConfigurations = 0;
1858 out_unauthorized:
1859 usb_unlock_device(usb_dev);
1860 return 0;
1864 int usb_authorize_device(struct usb_device *usb_dev)
1866 int result = 0, c;
1868 usb_lock_device(usb_dev);
1869 if (usb_dev->authorized == 1)
1870 goto out_authorized;
1872 result = usb_autoresume_device(usb_dev);
1873 if (result < 0) {
1874 dev_err(&usb_dev->dev,
1875 "can't autoresume for authorization: %d\n", result);
1876 goto error_autoresume;
1878 result = usb_get_device_descriptor(usb_dev, sizeof(usb_dev->descriptor));
1879 if (result < 0) {
1880 dev_err(&usb_dev->dev, "can't re-read device descriptor for "
1881 "authorization: %d\n", result);
1882 goto error_device_descriptor;
1885 kfree(usb_dev->product);
1886 usb_dev->product = NULL;
1887 kfree(usb_dev->manufacturer);
1888 usb_dev->manufacturer = NULL;
1889 kfree(usb_dev->serial);
1890 usb_dev->serial = NULL;
1892 usb_dev->authorized = 1;
1893 result = usb_enumerate_device(usb_dev);
1894 if (result < 0)
1895 goto error_enumerate;
1896 /* Choose and set the configuration. This registers the interfaces
1897 * with the driver core and lets interface drivers bind to them.
1899 c = usb_choose_configuration(usb_dev);
1900 if (c >= 0) {
1901 result = usb_set_configuration(usb_dev, c);
1902 if (result) {
1903 dev_err(&usb_dev->dev,
1904 "can't set config #%d, error %d\n", c, result);
1905 /* This need not be fatal. The user can try to
1906 * set other configurations. */
1909 dev_info(&usb_dev->dev, "authorized to connect\n");
1911 error_enumerate:
1912 error_device_descriptor:
1913 usb_autosuspend_device(usb_dev);
1914 error_autoresume:
1915 out_authorized:
1916 usb_unlock_device(usb_dev); // complements locktree
1917 return result;
1921 /* Returns 1 if @hub is a WUSB root hub, 0 otherwise */
1922 static unsigned hub_is_wusb(struct usb_hub *hub)
1924 struct usb_hcd *hcd;
1925 if (hub->hdev->parent != NULL) /* not a root hub? */
1926 return 0;
1927 hcd = container_of(hub->hdev->bus, struct usb_hcd, self);
1928 return hcd->wireless;
1932 #define PORT_RESET_TRIES 5
1933 #define SET_ADDRESS_TRIES 2
1934 #define GET_DESCRIPTOR_TRIES 2
1935 #define SET_CONFIG_TRIES (2 * (use_both_schemes + 1))
1936 #define USE_NEW_SCHEME(i) ((i) / 2 == old_scheme_first)
1938 #define HUB_ROOT_RESET_TIME 50 /* times are in msec */
1939 #define HUB_SHORT_RESET_TIME 10
1940 #define HUB_LONG_RESET_TIME 200
1941 #define HUB_RESET_TIMEOUT 500
1943 static int hub_port_wait_reset(struct usb_hub *hub, int port1,
1944 struct usb_device *udev, unsigned int delay)
1946 int delay_time, ret;
1947 u16 portstatus;
1948 u16 portchange;
1950 for (delay_time = 0;
1951 delay_time < HUB_RESET_TIMEOUT;
1952 delay_time += delay) {
1953 /* wait to give the device a chance to reset */
1954 msleep(delay);
1956 /* read and decode port status */
1957 ret = hub_port_status(hub, port1, &portstatus, &portchange);
1958 if (ret < 0)
1959 return ret;
1961 /* Device went away? */
1962 if (!(portstatus & USB_PORT_STAT_CONNECTION))
1963 return -ENOTCONN;
1965 /* bomb out completely if the connection bounced */
1966 if ((portchange & USB_PORT_STAT_C_CONNECTION))
1967 return -ENOTCONN;
1969 /* if we`ve finished resetting, then break out of the loop */
1970 if (!(portstatus & USB_PORT_STAT_RESET) &&
1971 (portstatus & USB_PORT_STAT_ENABLE)) {
1972 if (hub_is_wusb(hub))
1973 udev->speed = USB_SPEED_WIRELESS;
1974 else if (portstatus & (1 << USB_PORT_FEAT_SUPERSPEED))
1975 udev->speed = USB_SPEED_SUPER;
1976 else if (portstatus & USB_PORT_STAT_HIGH_SPEED)
1977 udev->speed = USB_SPEED_HIGH;
1978 else if (portstatus & USB_PORT_STAT_LOW_SPEED)
1979 udev->speed = USB_SPEED_LOW;
1980 else
1981 udev->speed = USB_SPEED_FULL;
1982 return 0;
1985 /* switch to the long delay after two short delay failures */
1986 if (delay_time >= 2 * HUB_SHORT_RESET_TIME)
1987 delay = HUB_LONG_RESET_TIME;
1989 dev_dbg (hub->intfdev,
1990 "port %d not reset yet, waiting %dms\n",
1991 port1, delay);
1994 return -EBUSY;
1997 static int hub_port_reset(struct usb_hub *hub, int port1,
1998 struct usb_device *udev, unsigned int delay)
2000 int i, status;
2001 struct usb_hcd *hcd;
2003 hcd = bus_to_hcd(udev->bus);
2004 /* Block EHCI CF initialization during the port reset.
2005 * Some companion controllers don't like it when they mix.
2007 down_read(&ehci_cf_port_reset_rwsem);
2009 /* Reset the port */
2010 for (i = 0; i < PORT_RESET_TRIES; i++) {
2011 status = set_port_feature(hub->hdev,
2012 port1, USB_PORT_FEAT_RESET);
2013 if (status)
2014 dev_err(hub->intfdev,
2015 "cannot reset port %d (err = %d)\n",
2016 port1, status);
2017 else {
2018 status = hub_port_wait_reset(hub, port1, udev, delay);
2019 if (status && status != -ENOTCONN)
2020 dev_dbg(hub->intfdev,
2021 "port_wait_reset: err = %d\n",
2022 status);
2025 /* return on disconnect or reset */
2026 switch (status) {
2027 case 0:
2028 /* TRSTRCY = 10 ms; plus some extra */
2029 msleep(10 + 40);
2030 update_address(udev, 0);
2031 if (hcd->driver->reset_device) {
2032 status = hcd->driver->reset_device(hcd, udev);
2033 if (status < 0) {
2034 dev_err(&udev->dev, "Cannot reset "
2035 "HCD device state\n");
2036 break;
2039 /* FALL THROUGH */
2040 case -ENOTCONN:
2041 case -ENODEV:
2042 clear_port_feature(hub->hdev,
2043 port1, USB_PORT_FEAT_C_RESET);
2044 /* FIXME need disconnect() for NOTATTACHED device */
2045 usb_set_device_state(udev, status
2046 ? USB_STATE_NOTATTACHED
2047 : USB_STATE_DEFAULT);
2048 goto done;
2051 dev_dbg (hub->intfdev,
2052 "port %d not enabled, trying reset again...\n",
2053 port1);
2054 delay = HUB_LONG_RESET_TIME;
2057 dev_err (hub->intfdev,
2058 "Cannot enable port %i. Maybe the USB cable is bad?\n",
2059 port1);
2061 done:
2062 up_read(&ehci_cf_port_reset_rwsem);
2063 return status;
2066 #ifdef CONFIG_PM
2068 #define MASK_BITS (USB_PORT_STAT_POWER | USB_PORT_STAT_CONNECTION | \
2069 USB_PORT_STAT_SUSPEND)
2070 #define WANT_BITS (USB_PORT_STAT_POWER | USB_PORT_STAT_CONNECTION)
2072 /* Determine whether the device on a port is ready for a normal resume,
2073 * is ready for a reset-resume, or should be disconnected.
2075 static int check_port_resume_type(struct usb_device *udev,
2076 struct usb_hub *hub, int port1,
2077 int status, unsigned portchange, unsigned portstatus)
2079 /* Is the device still present? */
2080 if (status || (portstatus & MASK_BITS) != WANT_BITS) {
2081 if (status >= 0)
2082 status = -ENODEV;
2085 /* Can't do a normal resume if the port isn't enabled,
2086 * so try a reset-resume instead.
2088 else if (!(portstatus & USB_PORT_STAT_ENABLE) && !udev->reset_resume) {
2089 if (udev->persist_enabled)
2090 udev->reset_resume = 1;
2091 else
2092 status = -ENODEV;
2095 if (status) {
2096 dev_dbg(hub->intfdev,
2097 "port %d status %04x.%04x after resume, %d\n",
2098 port1, portchange, portstatus, status);
2099 } else if (udev->reset_resume) {
2101 /* Late port handoff can set status-change bits */
2102 if (portchange & USB_PORT_STAT_C_CONNECTION)
2103 clear_port_feature(hub->hdev, port1,
2104 USB_PORT_FEAT_C_CONNECTION);
2105 if (portchange & USB_PORT_STAT_C_ENABLE)
2106 clear_port_feature(hub->hdev, port1,
2107 USB_PORT_FEAT_C_ENABLE);
2110 return status;
2113 #ifdef CONFIG_USB_SUSPEND
2116 * usb_port_suspend - suspend a usb device's upstream port
2117 * @udev: device that's no longer in active use, not a root hub
2118 * Context: must be able to sleep; device not locked; pm locks held
2120 * Suspends a USB device that isn't in active use, conserving power.
2121 * Devices may wake out of a suspend, if anything important happens,
2122 * using the remote wakeup mechanism. They may also be taken out of
2123 * suspend by the host, using usb_port_resume(). It's also routine
2124 * to disconnect devices while they are suspended.
2126 * This only affects the USB hardware for a device; its interfaces
2127 * (and, for hubs, child devices) must already have been suspended.
2129 * Selective port suspend reduces power; most suspended devices draw
2130 * less than 500 uA. It's also used in OTG, along with remote wakeup.
2131 * All devices below the suspended port are also suspended.
2133 * Devices leave suspend state when the host wakes them up. Some devices
2134 * also support "remote wakeup", where the device can activate the USB
2135 * tree above them to deliver data, such as a keypress or packet. In
2136 * some cases, this wakes the USB host.
2138 * Suspending OTG devices may trigger HNP, if that's been enabled
2139 * between a pair of dual-role devices. That will change roles, such
2140 * as from A-Host to A-Peripheral or from B-Host back to B-Peripheral.
2142 * Devices on USB hub ports have only one "suspend" state, corresponding
2143 * to ACPI D2, "may cause the device to lose some context".
2144 * State transitions include:
2146 * - suspend, resume ... when the VBUS power link stays live
2147 * - suspend, disconnect ... VBUS lost
2149 * Once VBUS drop breaks the circuit, the port it's using has to go through
2150 * normal re-enumeration procedures, starting with enabling VBUS power.
2151 * Other than re-initializing the hub (plug/unplug, except for root hubs),
2152 * Linux (2.6) currently has NO mechanisms to initiate that: no khubd
2153 * timer, no SRP, no requests through sysfs.
2155 * If CONFIG_USB_SUSPEND isn't enabled, devices only really suspend when
2156 * the root hub for their bus goes into global suspend ... so we don't
2157 * (falsely) update the device power state to say it suspended.
2159 * Returns 0 on success, else negative errno.
2161 int usb_port_suspend(struct usb_device *udev, pm_message_t msg)
2163 struct usb_hub *hub = hdev_to_hub(udev->parent);
2164 int port1 = udev->portnum;
2165 int status;
2167 // dev_dbg(hub->intfdev, "suspend port %d\n", port1);
2169 /* enable remote wakeup when appropriate; this lets the device
2170 * wake up the upstream hub (including maybe the root hub).
2172 * NOTE: OTG devices may issue remote wakeup (or SRP) even when
2173 * we don't explicitly enable it here.
2175 if (udev->do_remote_wakeup) {
2176 status = usb_control_msg(udev, usb_sndctrlpipe(udev, 0),
2177 USB_REQ_SET_FEATURE, USB_RECIP_DEVICE,
2178 USB_DEVICE_REMOTE_WAKEUP, 0,
2179 NULL, 0,
2180 USB_CTRL_SET_TIMEOUT);
2181 if (status) {
2182 dev_dbg(&udev->dev, "won't remote wakeup, status %d\n",
2183 status);
2184 /* bail if autosuspend is requested */
2185 if (msg.event & PM_EVENT_AUTO)
2186 return status;
2190 /* see 7.1.7.6 */
2191 status = set_port_feature(hub->hdev, port1, USB_PORT_FEAT_SUSPEND);
2192 if (status) {
2193 dev_dbg(hub->intfdev, "can't suspend port %d, status %d\n",
2194 port1, status);
2195 /* paranoia: "should not happen" */
2196 if (udev->do_remote_wakeup)
2197 (void) usb_control_msg(udev, usb_sndctrlpipe(udev, 0),
2198 USB_REQ_CLEAR_FEATURE, USB_RECIP_DEVICE,
2199 USB_DEVICE_REMOTE_WAKEUP, 0,
2200 NULL, 0,
2201 USB_CTRL_SET_TIMEOUT);
2202 } else {
2203 /* device has up to 10 msec to fully suspend */
2204 dev_dbg(&udev->dev, "usb %ssuspend\n",
2205 (msg.event & PM_EVENT_AUTO ? "auto-" : ""));
2206 usb_set_device_state(udev, USB_STATE_SUSPENDED);
2207 msleep(10);
2209 return status;
2213 * If the USB "suspend" state is in use (rather than "global suspend"),
2214 * many devices will be individually taken out of suspend state using
2215 * special "resume" signaling. This routine kicks in shortly after
2216 * hardware resume signaling is finished, either because of selective
2217 * resume (by host) or remote wakeup (by device) ... now see what changed
2218 * in the tree that's rooted at this device.
2220 * If @udev->reset_resume is set then the device is reset before the
2221 * status check is done.
2223 static int finish_port_resume(struct usb_device *udev)
2225 int status = 0;
2226 u16 devstatus;
2228 /* caller owns the udev device lock */
2229 dev_dbg(&udev->dev, "%s\n",
2230 udev->reset_resume ? "finish reset-resume" : "finish resume");
2232 /* usb ch9 identifies four variants of SUSPENDED, based on what
2233 * state the device resumes to. Linux currently won't see the
2234 * first two on the host side; they'd be inside hub_port_init()
2235 * during many timeouts, but khubd can't suspend until later.
2237 usb_set_device_state(udev, udev->actconfig
2238 ? USB_STATE_CONFIGURED
2239 : USB_STATE_ADDRESS);
2241 /* 10.5.4.5 says not to reset a suspended port if the attached
2242 * device is enabled for remote wakeup. Hence the reset
2243 * operation is carried out here, after the port has been
2244 * resumed.
2246 if (udev->reset_resume)
2247 retry_reset_resume:
2248 status = usb_reset_and_verify_device(udev);
2250 /* 10.5.4.5 says be sure devices in the tree are still there.
2251 * For now let's assume the device didn't go crazy on resume,
2252 * and device drivers will know about any resume quirks.
2254 if (status == 0) {
2255 devstatus = 0;
2256 status = usb_get_status(udev, USB_RECIP_DEVICE, 0, &devstatus);
2257 if (status >= 0)
2258 status = (status > 0 ? 0 : -ENODEV);
2260 /* If a normal resume failed, try doing a reset-resume */
2261 if (status && !udev->reset_resume && udev->persist_enabled) {
2262 dev_dbg(&udev->dev, "retry with reset-resume\n");
2263 udev->reset_resume = 1;
2264 goto retry_reset_resume;
2268 if (status) {
2269 dev_dbg(&udev->dev, "gone after usb resume? status %d\n",
2270 status);
2271 } else if (udev->actconfig) {
2272 le16_to_cpus(&devstatus);
2273 if (devstatus & (1 << USB_DEVICE_REMOTE_WAKEUP)) {
2274 status = usb_control_msg(udev,
2275 usb_sndctrlpipe(udev, 0),
2276 USB_REQ_CLEAR_FEATURE,
2277 USB_RECIP_DEVICE,
2278 USB_DEVICE_REMOTE_WAKEUP, 0,
2279 NULL, 0,
2280 USB_CTRL_SET_TIMEOUT);
2281 if (status)
2282 dev_dbg(&udev->dev,
2283 "disable remote wakeup, status %d\n",
2284 status);
2286 status = 0;
2288 return status;
2292 * usb_port_resume - re-activate a suspended usb device's upstream port
2293 * @udev: device to re-activate, not a root hub
2294 * Context: must be able to sleep; device not locked; pm locks held
2296 * This will re-activate the suspended device, increasing power usage
2297 * while letting drivers communicate again with its endpoints.
2298 * USB resume explicitly guarantees that the power session between
2299 * the host and the device is the same as it was when the device
2300 * suspended.
2302 * If @udev->reset_resume is set then this routine won't check that the
2303 * port is still enabled. Furthermore, finish_port_resume() above will
2304 * reset @udev. The end result is that a broken power session can be
2305 * recovered and @udev will appear to persist across a loss of VBUS power.
2307 * For example, if a host controller doesn't maintain VBUS suspend current
2308 * during a system sleep or is reset when the system wakes up, all the USB
2309 * power sessions below it will be broken. This is especially troublesome
2310 * for mass-storage devices containing mounted filesystems, since the
2311 * device will appear to have disconnected and all the memory mappings
2312 * to it will be lost. Using the USB_PERSIST facility, the device can be
2313 * made to appear as if it had not disconnected.
2315 * This facility can be dangerous. Although usb_reset_and_verify_device() makes
2316 * every effort to insure that the same device is present after the
2317 * reset as before, it cannot provide a 100% guarantee. Furthermore it's
2318 * quite possible for a device to remain unaltered but its media to be
2319 * changed. If the user replaces a flash memory card while the system is
2320 * asleep, he will have only himself to blame when the filesystem on the
2321 * new card is corrupted and the system crashes.
2323 * Returns 0 on success, else negative errno.
2325 int usb_port_resume(struct usb_device *udev, pm_message_t msg)
2327 struct usb_hub *hub = hdev_to_hub(udev->parent);
2328 int port1 = udev->portnum;
2329 int status;
2330 u16 portchange, portstatus;
2332 /* Skip the initial Clear-Suspend step for a remote wakeup */
2333 status = hub_port_status(hub, port1, &portstatus, &portchange);
2334 if (status == 0 && !(portstatus & USB_PORT_STAT_SUSPEND))
2335 goto SuspendCleared;
2337 // dev_dbg(hub->intfdev, "resume port %d\n", port1);
2339 set_bit(port1, hub->busy_bits);
2341 /* see 7.1.7.7; affects power usage, but not budgeting */
2342 status = clear_port_feature(hub->hdev,
2343 port1, USB_PORT_FEAT_SUSPEND);
2344 if (status) {
2345 dev_dbg(hub->intfdev, "can't resume port %d, status %d\n",
2346 port1, status);
2347 } else {
2348 /* drive resume for at least 20 msec */
2349 dev_dbg(&udev->dev, "usb %sresume\n",
2350 (msg.event & PM_EVENT_AUTO ? "auto-" : ""));
2351 msleep(25);
2353 /* Virtual root hubs can trigger on GET_PORT_STATUS to
2354 * stop resume signaling. Then finish the resume
2355 * sequence.
2357 status = hub_port_status(hub, port1, &portstatus, &portchange);
2359 /* TRSMRCY = 10 msec */
2360 msleep(10);
2363 SuspendCleared:
2364 if (status == 0) {
2365 if (portchange & USB_PORT_STAT_C_SUSPEND)
2366 clear_port_feature(hub->hdev, port1,
2367 USB_PORT_FEAT_C_SUSPEND);
2370 clear_bit(port1, hub->busy_bits);
2372 status = check_port_resume_type(udev,
2373 hub, port1, status, portchange, portstatus);
2374 if (status == 0)
2375 status = finish_port_resume(udev);
2376 if (status < 0) {
2377 dev_dbg(&udev->dev, "can't resume, status %d\n", status);
2378 hub_port_logical_disconnect(hub, port1);
2380 return status;
2383 /* caller has locked udev */
2384 int usb_remote_wakeup(struct usb_device *udev)
2386 int status = 0;
2388 if (udev->state == USB_STATE_SUSPENDED) {
2389 dev_dbg(&udev->dev, "usb %sresume\n", "wakeup-");
2390 status = usb_autoresume_device(udev);
2391 if (status == 0) {
2392 /* Let the drivers do their thing, then... */
2393 usb_autosuspend_device(udev);
2396 return status;
2399 #else /* CONFIG_USB_SUSPEND */
2401 /* When CONFIG_USB_SUSPEND isn't set, we never suspend or resume any ports. */
2403 int usb_port_suspend(struct usb_device *udev, pm_message_t msg)
2405 return 0;
2408 /* However we may need to do a reset-resume */
2410 int usb_port_resume(struct usb_device *udev, pm_message_t msg)
2412 struct usb_hub *hub = hdev_to_hub(udev->parent);
2413 int port1 = udev->portnum;
2414 int status;
2415 u16 portchange, portstatus;
2417 status = hub_port_status(hub, port1, &portstatus, &portchange);
2418 status = check_port_resume_type(udev,
2419 hub, port1, status, portchange, portstatus);
2421 if (status) {
2422 dev_dbg(&udev->dev, "can't resume, status %d\n", status);
2423 hub_port_logical_disconnect(hub, port1);
2424 } else if (udev->reset_resume) {
2425 dev_dbg(&udev->dev, "reset-resume\n");
2426 status = usb_reset_and_verify_device(udev);
2428 return status;
2431 #endif
2433 static int hub_suspend(struct usb_interface *intf, pm_message_t msg)
2435 struct usb_hub *hub = usb_get_intfdata (intf);
2436 struct usb_device *hdev = hub->hdev;
2437 unsigned port1;
2439 /* fail if children aren't already suspended */
2440 for (port1 = 1; port1 <= hdev->maxchild; port1++) {
2441 struct usb_device *udev;
2443 udev = hdev->children [port1-1];
2444 if (udev && udev->can_submit) {
2445 if (!(msg.event & PM_EVENT_AUTO))
2446 dev_dbg(&intf->dev, "port %d nyet suspended\n",
2447 port1);
2448 return -EBUSY;
2452 dev_dbg(&intf->dev, "%s\n", __func__);
2454 /* stop khubd and related activity */
2455 hub_quiesce(hub, HUB_SUSPEND);
2456 return 0;
2459 static int hub_resume(struct usb_interface *intf)
2461 struct usb_hub *hub = usb_get_intfdata(intf);
2463 dev_dbg(&intf->dev, "%s\n", __func__);
2464 hub_activate(hub, HUB_RESUME);
2465 return 0;
2468 static int hub_reset_resume(struct usb_interface *intf)
2470 struct usb_hub *hub = usb_get_intfdata(intf);
2472 dev_dbg(&intf->dev, "%s\n", __func__);
2473 hub_activate(hub, HUB_RESET_RESUME);
2474 return 0;
2478 * usb_root_hub_lost_power - called by HCD if the root hub lost Vbus power
2479 * @rhdev: struct usb_device for the root hub
2481 * The USB host controller driver calls this function when its root hub
2482 * is resumed and Vbus power has been interrupted or the controller
2483 * has been reset. The routine marks @rhdev as having lost power.
2484 * When the hub driver is resumed it will take notice and carry out
2485 * power-session recovery for all the "USB-PERSIST"-enabled child devices;
2486 * the others will be disconnected.
2488 void usb_root_hub_lost_power(struct usb_device *rhdev)
2490 dev_warn(&rhdev->dev, "root hub lost power or was reset\n");
2491 rhdev->reset_resume = 1;
2493 EXPORT_SYMBOL_GPL(usb_root_hub_lost_power);
2495 #else /* CONFIG_PM */
2497 #define hub_suspend NULL
2498 #define hub_resume NULL
2499 #define hub_reset_resume NULL
2500 #endif
2503 /* USB 2.0 spec, 7.1.7.3 / fig 7-29:
2505 * Between connect detection and reset signaling there must be a delay
2506 * of 100ms at least for debounce and power-settling. The corresponding
2507 * timer shall restart whenever the downstream port detects a disconnect.
2509 * Apparently there are some bluetooth and irda-dongles and a number of
2510 * low-speed devices for which this debounce period may last over a second.
2511 * Not covered by the spec - but easy to deal with.
2513 * This implementation uses a 1500ms total debounce timeout; if the
2514 * connection isn't stable by then it returns -ETIMEDOUT. It checks
2515 * every 25ms for transient disconnects. When the port status has been
2516 * unchanged for 100ms it returns the port status.
2518 static int hub_port_debounce(struct usb_hub *hub, int port1)
2520 int ret;
2521 int total_time, stable_time = 0;
2522 u16 portchange, portstatus;
2523 unsigned connection = 0xffff;
2525 for (total_time = 0; ; total_time += HUB_DEBOUNCE_STEP) {
2526 ret = hub_port_status(hub, port1, &portstatus, &portchange);
2527 if (ret < 0)
2528 return ret;
2530 if (!(portchange & USB_PORT_STAT_C_CONNECTION) &&
2531 (portstatus & USB_PORT_STAT_CONNECTION) == connection) {
2532 stable_time += HUB_DEBOUNCE_STEP;
2533 if (stable_time >= HUB_DEBOUNCE_STABLE)
2534 break;
2535 } else {
2536 stable_time = 0;
2537 connection = portstatus & USB_PORT_STAT_CONNECTION;
2540 if (portchange & USB_PORT_STAT_C_CONNECTION) {
2541 clear_port_feature(hub->hdev, port1,
2542 USB_PORT_FEAT_C_CONNECTION);
2545 if (total_time >= HUB_DEBOUNCE_TIMEOUT)
2546 break;
2547 msleep(HUB_DEBOUNCE_STEP);
2550 dev_dbg (hub->intfdev,
2551 "debounce: port %d: total %dms stable %dms status 0x%x\n",
2552 port1, total_time, stable_time, portstatus);
2554 if (stable_time < HUB_DEBOUNCE_STABLE)
2555 return -ETIMEDOUT;
2556 return portstatus;
2559 void usb_ep0_reinit(struct usb_device *udev)
2561 usb_disable_endpoint(udev, 0 + USB_DIR_IN, true);
2562 usb_disable_endpoint(udev, 0 + USB_DIR_OUT, true);
2563 usb_enable_endpoint(udev, &udev->ep0, true);
2565 EXPORT_SYMBOL_GPL(usb_ep0_reinit);
2567 #define usb_sndaddr0pipe() (PIPE_CONTROL << 30)
2568 #define usb_rcvaddr0pipe() ((PIPE_CONTROL << 30) | USB_DIR_IN)
2570 static int hub_set_address(struct usb_device *udev, int devnum)
2572 int retval;
2573 struct usb_hcd *hcd = bus_to_hcd(udev->bus);
2576 * The host controller will choose the device address,
2577 * instead of the core having chosen it earlier
2579 if (!hcd->driver->address_device && devnum <= 1)
2580 return -EINVAL;
2581 if (udev->state == USB_STATE_ADDRESS)
2582 return 0;
2583 if (udev->state != USB_STATE_DEFAULT)
2584 return -EINVAL;
2585 if (hcd->driver->address_device) {
2586 retval = hcd->driver->address_device(hcd, udev);
2587 } else {
2588 retval = usb_control_msg(udev, usb_sndaddr0pipe(),
2589 USB_REQ_SET_ADDRESS, 0, devnum, 0,
2590 NULL, 0, USB_CTRL_SET_TIMEOUT);
2591 if (retval == 0)
2592 update_address(udev, devnum);
2594 if (retval == 0) {
2595 /* Device now using proper address. */
2596 usb_set_device_state(udev, USB_STATE_ADDRESS);
2597 usb_ep0_reinit(udev);
2599 return retval;
2602 /* Reset device, (re)assign address, get device descriptor.
2603 * Device connection must be stable, no more debouncing needed.
2604 * Returns device in USB_STATE_ADDRESS, except on error.
2606 * If this is called for an already-existing device (as part of
2607 * usb_reset_and_verify_device), the caller must own the device lock. For a
2608 * newly detected device that is not accessible through any global
2609 * pointers, it's not necessary to lock the device.
2611 static int
2612 hub_port_init (struct usb_hub *hub, struct usb_device *udev, int port1,
2613 int retry_counter)
2615 static DEFINE_MUTEX(usb_address0_mutex);
2617 struct usb_device *hdev = hub->hdev;
2618 struct usb_hcd *hcd = bus_to_hcd(hdev->bus);
2619 int i, j, retval;
2620 unsigned delay = HUB_SHORT_RESET_TIME;
2621 enum usb_device_speed oldspeed = udev->speed;
2622 char *speed, *type;
2623 int devnum = udev->devnum;
2625 /* root hub ports have a slightly longer reset period
2626 * (from USB 2.0 spec, section 7.1.7.5)
2628 if (!hdev->parent) {
2629 delay = HUB_ROOT_RESET_TIME;
2630 if (port1 == hdev->bus->otg_port)
2631 hdev->bus->b_hnp_enable = 0;
2634 /* Some low speed devices have problems with the quick delay, so */
2635 /* be a bit pessimistic with those devices. RHbug #23670 */
2636 if (oldspeed == USB_SPEED_LOW)
2637 delay = HUB_LONG_RESET_TIME;
2639 mutex_lock(&usb_address0_mutex);
2641 if (!udev->config && oldspeed == USB_SPEED_SUPER) {
2642 /* Don't reset USB 3.0 devices during an initial setup */
2643 usb_set_device_state(udev, USB_STATE_DEFAULT);
2644 } else {
2645 /* Reset the device; full speed may morph to high speed */
2646 /* FIXME a USB 2.0 device may morph into SuperSpeed on reset. */
2647 retval = hub_port_reset(hub, port1, udev, delay);
2648 if (retval < 0) /* error or disconnect */
2649 goto fail;
2650 /* success, speed is known */
2652 retval = -ENODEV;
2654 if (oldspeed != USB_SPEED_UNKNOWN && oldspeed != udev->speed) {
2655 dev_dbg(&udev->dev, "device reset changed speed!\n");
2656 goto fail;
2658 oldspeed = udev->speed;
2660 /* USB 2.0 section 5.5.3 talks about ep0 maxpacket ...
2661 * it's fixed size except for full speed devices.
2662 * For Wireless USB devices, ep0 max packet is always 512 (tho
2663 * reported as 0xff in the device descriptor). WUSB1.0[4.8.1].
2665 switch (udev->speed) {
2666 case USB_SPEED_SUPER:
2667 case USB_SPEED_WIRELESS: /* fixed at 512 */
2668 udev->ep0.desc.wMaxPacketSize = cpu_to_le16(512);
2669 break;
2670 case USB_SPEED_HIGH: /* fixed at 64 */
2671 udev->ep0.desc.wMaxPacketSize = cpu_to_le16(64);
2672 break;
2673 case USB_SPEED_FULL: /* 8, 16, 32, or 64 */
2674 /* to determine the ep0 maxpacket size, try to read
2675 * the device descriptor to get bMaxPacketSize0 and
2676 * then correct our initial guess.
2678 udev->ep0.desc.wMaxPacketSize = cpu_to_le16(64);
2679 break;
2680 case USB_SPEED_LOW: /* fixed at 8 */
2681 udev->ep0.desc.wMaxPacketSize = cpu_to_le16(8);
2682 break;
2683 default:
2684 goto fail;
2687 type = "";
2688 switch (udev->speed) {
2689 case USB_SPEED_LOW: speed = "low"; break;
2690 case USB_SPEED_FULL: speed = "full"; break;
2691 case USB_SPEED_HIGH: speed = "high"; break;
2692 case USB_SPEED_SUPER:
2693 speed = "super";
2694 break;
2695 case USB_SPEED_WIRELESS:
2696 speed = "variable";
2697 type = "Wireless ";
2698 break;
2699 default: speed = "?"; break;
2701 if (udev->speed != USB_SPEED_SUPER)
2702 dev_info(&udev->dev,
2703 "%s %s speed %sUSB device using %s and address %d\n",
2704 (udev->config) ? "reset" : "new", speed, type,
2705 udev->bus->controller->driver->name, devnum);
2707 /* Set up TT records, if needed */
2708 if (hdev->tt) {
2709 udev->tt = hdev->tt;
2710 udev->ttport = hdev->ttport;
2711 } else if (udev->speed != USB_SPEED_HIGH
2712 && hdev->speed == USB_SPEED_HIGH) {
2713 udev->tt = &hub->tt;
2714 udev->ttport = port1;
2717 /* Why interleave GET_DESCRIPTOR and SET_ADDRESS this way?
2718 * Because device hardware and firmware is sometimes buggy in
2719 * this area, and this is how Linux has done it for ages.
2720 * Change it cautiously.
2722 * NOTE: If USE_NEW_SCHEME() is true we will start by issuing
2723 * a 64-byte GET_DESCRIPTOR request. This is what Windows does,
2724 * so it may help with some non-standards-compliant devices.
2725 * Otherwise we start with SET_ADDRESS and then try to read the
2726 * first 8 bytes of the device descriptor to get the ep0 maxpacket
2727 * value.
2729 for (i = 0; i < GET_DESCRIPTOR_TRIES; (++i, msleep(100))) {
2731 * An xHCI controller cannot send any packets to a device until
2732 * a set address command successfully completes.
2734 if (USE_NEW_SCHEME(retry_counter) && !(hcd->driver->flags & HCD_USB3)) {
2735 struct usb_device_descriptor *buf;
2736 int r = 0;
2738 #define GET_DESCRIPTOR_BUFSIZE 64
2739 buf = kmalloc(GET_DESCRIPTOR_BUFSIZE, GFP_NOIO);
2740 if (!buf) {
2741 retval = -ENOMEM;
2742 continue;
2745 /* Retry on all errors; some devices are flakey.
2746 * 255 is for WUSB devices, we actually need to use
2747 * 512 (WUSB1.0[4.8.1]).
2749 for (j = 0; j < 3; ++j) {
2750 buf->bMaxPacketSize0 = 0;
2751 r = usb_control_msg(udev, usb_rcvaddr0pipe(),
2752 USB_REQ_GET_DESCRIPTOR, USB_DIR_IN,
2753 USB_DT_DEVICE << 8, 0,
2754 buf, GET_DESCRIPTOR_BUFSIZE,
2755 initial_descriptor_timeout);
2756 switch (buf->bMaxPacketSize0) {
2757 case 8: case 16: case 32: case 64: case 255:
2758 if (buf->bDescriptorType ==
2759 USB_DT_DEVICE) {
2760 r = 0;
2761 break;
2763 /* FALL THROUGH */
2764 default:
2765 if (r == 0)
2766 r = -EPROTO;
2767 break;
2769 if (r == 0)
2770 break;
2772 udev->descriptor.bMaxPacketSize0 =
2773 buf->bMaxPacketSize0;
2774 kfree(buf);
2776 retval = hub_port_reset(hub, port1, udev, delay);
2777 if (retval < 0) /* error or disconnect */
2778 goto fail;
2779 if (oldspeed != udev->speed) {
2780 dev_dbg(&udev->dev,
2781 "device reset changed speed!\n");
2782 retval = -ENODEV;
2783 goto fail;
2785 if (r) {
2786 dev_err(&udev->dev,
2787 "device descriptor read/64, error %d\n",
2789 retval = -EMSGSIZE;
2790 continue;
2792 #undef GET_DESCRIPTOR_BUFSIZE
2796 * If device is WUSB, we already assigned an
2797 * unauthorized address in the Connect Ack sequence;
2798 * authorization will assign the final address.
2800 if (udev->wusb == 0) {
2801 for (j = 0; j < SET_ADDRESS_TRIES; ++j) {
2802 retval = hub_set_address(udev, devnum);
2803 if (retval >= 0)
2804 break;
2805 msleep(200);
2807 if (retval < 0) {
2808 dev_err(&udev->dev,
2809 "device not accepting address %d, error %d\n",
2810 devnum, retval);
2811 goto fail;
2813 if (udev->speed == USB_SPEED_SUPER) {
2814 devnum = udev->devnum;
2815 dev_info(&udev->dev,
2816 "%s SuperSpeed USB device using %s and address %d\n",
2817 (udev->config) ? "reset" : "new",
2818 udev->bus->controller->driver->name, devnum);
2821 /* cope with hardware quirkiness:
2822 * - let SET_ADDRESS settle, some device hardware wants it
2823 * - read ep0 maxpacket even for high and low speed,
2825 msleep(10);
2826 if (USE_NEW_SCHEME(retry_counter) && !(hcd->driver->flags & HCD_USB3))
2827 break;
2830 retval = usb_get_device_descriptor(udev, 8);
2831 if (retval < 8) {
2832 dev_err(&udev->dev,
2833 "device descriptor read/8, error %d\n",
2834 retval);
2835 if (retval >= 0)
2836 retval = -EMSGSIZE;
2837 } else {
2838 retval = 0;
2839 break;
2842 if (retval)
2843 goto fail;
2845 if (udev->descriptor.bMaxPacketSize0 == 0xff ||
2846 udev->speed == USB_SPEED_SUPER)
2847 i = 512;
2848 else
2849 i = udev->descriptor.bMaxPacketSize0;
2850 if (le16_to_cpu(udev->ep0.desc.wMaxPacketSize) != i) {
2851 if (udev->speed != USB_SPEED_FULL ||
2852 !(i == 8 || i == 16 || i == 32 || i == 64)) {
2853 dev_err(&udev->dev, "ep0 maxpacket = %d\n", i);
2854 retval = -EMSGSIZE;
2855 goto fail;
2857 dev_dbg(&udev->dev, "ep0 maxpacket = %d\n", i);
2858 udev->ep0.desc.wMaxPacketSize = cpu_to_le16(i);
2859 usb_ep0_reinit(udev);
2862 retval = usb_get_device_descriptor(udev, USB_DT_DEVICE_SIZE);
2863 if (retval < (signed)sizeof(udev->descriptor)) {
2864 dev_err(&udev->dev, "device descriptor read/all, error %d\n",
2865 retval);
2866 if (retval >= 0)
2867 retval = -ENOMSG;
2868 goto fail;
2871 retval = 0;
2873 fail:
2874 if (retval) {
2875 hub_port_disable(hub, port1, 0);
2876 update_address(udev, devnum); /* for disconnect processing */
2878 mutex_unlock(&usb_address0_mutex);
2879 return retval;
2882 static void
2883 check_highspeed (struct usb_hub *hub, struct usb_device *udev, int port1)
2885 struct usb_qualifier_descriptor *qual;
2886 int status;
2888 qual = kmalloc (sizeof *qual, GFP_KERNEL);
2889 if (qual == NULL)
2890 return;
2892 status = usb_get_descriptor (udev, USB_DT_DEVICE_QUALIFIER, 0,
2893 qual, sizeof *qual);
2894 if (status == sizeof *qual) {
2895 dev_info(&udev->dev, "not running at top speed; "
2896 "connect to a high speed hub\n");
2897 /* hub LEDs are probably harder to miss than syslog */
2898 if (hub->has_indicators) {
2899 hub->indicator[port1-1] = INDICATOR_GREEN_BLINK;
2900 schedule_delayed_work (&hub->leds, 0);
2903 kfree(qual);
2906 static unsigned
2907 hub_power_remaining (struct usb_hub *hub)
2909 struct usb_device *hdev = hub->hdev;
2910 int remaining;
2911 int port1;
2913 if (!hub->limited_power)
2914 return 0;
2916 remaining = hdev->bus_mA - hub->descriptor->bHubContrCurrent;
2917 for (port1 = 1; port1 <= hdev->maxchild; ++port1) {
2918 struct usb_device *udev = hdev->children[port1 - 1];
2919 int delta;
2921 if (!udev)
2922 continue;
2924 /* Unconfigured devices may not use more than 100mA,
2925 * or 8mA for OTG ports */
2926 if (udev->actconfig)
2927 delta = udev->actconfig->desc.bMaxPower * 2;
2928 else if (port1 != udev->bus->otg_port || hdev->parent)
2929 delta = 100;
2930 else
2931 delta = 8;
2932 if (delta > hub->mA_per_port)
2933 dev_warn(&udev->dev,
2934 "%dmA is over %umA budget for port %d!\n",
2935 delta, hub->mA_per_port, port1);
2936 remaining -= delta;
2938 if (remaining < 0) {
2939 dev_warn(hub->intfdev, "%dmA over power budget!\n",
2940 - remaining);
2941 remaining = 0;
2943 return remaining;
2946 /* Handle physical or logical connection change events.
2947 * This routine is called when:
2948 * a port connection-change occurs;
2949 * a port enable-change occurs (often caused by EMI);
2950 * usb_reset_and_verify_device() encounters changed descriptors (as from
2951 * a firmware download)
2952 * caller already locked the hub
2954 static void hub_port_connect_change(struct usb_hub *hub, int port1,
2955 u16 portstatus, u16 portchange)
2957 struct usb_device *hdev = hub->hdev;
2958 struct device *hub_dev = hub->intfdev;
2959 struct usb_hcd *hcd = bus_to_hcd(hdev->bus);
2960 unsigned wHubCharacteristics =
2961 le16_to_cpu(hub->descriptor->wHubCharacteristics);
2962 struct usb_device *udev;
2963 int status, i;
2965 dev_dbg (hub_dev,
2966 "port %d, status %04x, change %04x, %s\n",
2967 port1, portstatus, portchange, portspeed (portstatus));
2969 if (hub->has_indicators) {
2970 set_port_led(hub, port1, HUB_LED_AUTO);
2971 hub->indicator[port1-1] = INDICATOR_AUTO;
2974 #ifdef CONFIG_USB_OTG
2975 /* during HNP, don't repeat the debounce */
2976 if (hdev->bus->is_b_host)
2977 portchange &= ~(USB_PORT_STAT_C_CONNECTION |
2978 USB_PORT_STAT_C_ENABLE);
2979 #endif
2981 /* Try to resuscitate an existing device */
2982 udev = hdev->children[port1-1];
2983 if ((portstatus & USB_PORT_STAT_CONNECTION) && udev &&
2984 udev->state != USB_STATE_NOTATTACHED) {
2985 usb_lock_device(udev);
2986 if (portstatus & USB_PORT_STAT_ENABLE) {
2987 status = 0; /* Nothing to do */
2989 #ifdef CONFIG_USB_SUSPEND
2990 } else if (udev->state == USB_STATE_SUSPENDED &&
2991 udev->persist_enabled) {
2992 /* For a suspended device, treat this as a
2993 * remote wakeup event.
2995 status = usb_remote_wakeup(udev);
2996 #endif
2998 } else {
2999 status = -ENODEV; /* Don't resuscitate */
3001 usb_unlock_device(udev);
3003 if (status == 0) {
3004 clear_bit(port1, hub->change_bits);
3005 return;
3009 /* Disconnect any existing devices under this port */
3010 if (udev)
3011 usb_disconnect(&hdev->children[port1-1]);
3012 clear_bit(port1, hub->change_bits);
3014 /* We can forget about a "removed" device when there's a physical
3015 * disconnect or the connect status changes.
3017 if (!(portstatus & USB_PORT_STAT_CONNECTION) ||
3018 (portchange & USB_PORT_STAT_C_CONNECTION))
3019 clear_bit(port1, hub->removed_bits);
3021 if (portchange & (USB_PORT_STAT_C_CONNECTION |
3022 USB_PORT_STAT_C_ENABLE)) {
3023 status = hub_port_debounce(hub, port1);
3024 if (status < 0) {
3025 if (printk_ratelimit())
3026 dev_err(hub_dev, "connect-debounce failed, "
3027 "port %d disabled\n", port1);
3028 portstatus &= ~USB_PORT_STAT_CONNECTION;
3029 } else {
3030 portstatus = status;
3034 /* Return now if debouncing failed or nothing is connected or
3035 * the device was "removed".
3037 if (!(portstatus & USB_PORT_STAT_CONNECTION) ||
3038 test_bit(port1, hub->removed_bits)) {
3040 /* maybe switch power back on (e.g. root hub was reset) */
3041 if ((wHubCharacteristics & HUB_CHAR_LPSM) < 2
3042 && !(portstatus & (1 << USB_PORT_FEAT_POWER)))
3043 set_port_feature(hdev, port1, USB_PORT_FEAT_POWER);
3045 if (portstatus & USB_PORT_STAT_ENABLE)
3046 goto done;
3047 return;
3050 for (i = 0; i < SET_CONFIG_TRIES; i++) {
3052 /* reallocate for each attempt, since references
3053 * to the previous one can escape in various ways
3055 udev = usb_alloc_dev(hdev, hdev->bus, port1);
3056 if (!udev) {
3057 dev_err (hub_dev,
3058 "couldn't allocate port %d usb_device\n",
3059 port1);
3060 goto done;
3063 usb_set_device_state(udev, USB_STATE_POWERED);
3064 udev->bus_mA = hub->mA_per_port;
3065 udev->level = hdev->level + 1;
3066 udev->wusb = hub_is_wusb(hub);
3069 * USB 3.0 devices are reset automatically before the connect
3070 * port status change appears, and the root hub port status
3071 * shows the correct speed. We also get port change
3072 * notifications for USB 3.0 devices from the USB 3.0 portion of
3073 * an external USB 3.0 hub, but this isn't handled correctly yet
3074 * FIXME.
3077 if (!(hcd->driver->flags & HCD_USB3))
3078 udev->speed = USB_SPEED_UNKNOWN;
3079 else if ((hdev->parent == NULL) &&
3080 (portstatus & (1 << USB_PORT_FEAT_SUPERSPEED)))
3081 udev->speed = USB_SPEED_SUPER;
3082 else
3083 udev->speed = USB_SPEED_UNKNOWN;
3086 * xHCI needs to issue an address device command later
3087 * in the hub_port_init sequence for SS/HS/FS/LS devices.
3089 if (!(hcd->driver->flags & HCD_USB3)) {
3090 /* set the address */
3091 choose_address(udev);
3092 if (udev->devnum <= 0) {
3093 status = -ENOTCONN; /* Don't retry */
3094 goto loop;
3098 /* reset (non-USB 3.0 devices) and get descriptor */
3099 status = hub_port_init(hub, udev, port1, i);
3100 if (status < 0)
3101 goto loop;
3103 usb_detect_quirks(udev);
3104 if (udev->quirks & USB_QUIRK_DELAY_INIT)
3105 msleep(1000);
3107 /* consecutive bus-powered hubs aren't reliable; they can
3108 * violate the voltage drop budget. if the new child has
3109 * a "powered" LED, users should notice we didn't enable it
3110 * (without reading syslog), even without per-port LEDs
3111 * on the parent.
3113 if (udev->descriptor.bDeviceClass == USB_CLASS_HUB
3114 && udev->bus_mA <= 100) {
3115 u16 devstat;
3117 status = usb_get_status(udev, USB_RECIP_DEVICE, 0,
3118 &devstat);
3119 if (status < 2) {
3120 dev_dbg(&udev->dev, "get status %d ?\n", status);
3121 goto loop_disable;
3123 le16_to_cpus(&devstat);
3124 if ((devstat & (1 << USB_DEVICE_SELF_POWERED)) == 0) {
3125 dev_err(&udev->dev,
3126 "can't connect bus-powered hub "
3127 "to this port\n");
3128 if (hub->has_indicators) {
3129 hub->indicator[port1-1] =
3130 INDICATOR_AMBER_BLINK;
3131 schedule_delayed_work (&hub->leds, 0);
3133 status = -ENOTCONN; /* Don't retry */
3134 goto loop_disable;
3138 /* check for devices running slower than they could */
3139 if (le16_to_cpu(udev->descriptor.bcdUSB) >= 0x0200
3140 && udev->speed == USB_SPEED_FULL
3141 && highspeed_hubs != 0)
3142 check_highspeed (hub, udev, port1);
3144 /* Store the parent's children[] pointer. At this point
3145 * udev becomes globally accessible, although presumably
3146 * no one will look at it until hdev is unlocked.
3148 status = 0;
3150 /* We mustn't add new devices if the parent hub has
3151 * been disconnected; we would race with the
3152 * recursively_mark_NOTATTACHED() routine.
3154 spin_lock_irq(&device_state_lock);
3155 if (hdev->state == USB_STATE_NOTATTACHED)
3156 status = -ENOTCONN;
3157 else
3158 hdev->children[port1-1] = udev;
3159 spin_unlock_irq(&device_state_lock);
3161 /* Run it through the hoops (find a driver, etc) */
3162 if (!status) {
3163 status = usb_new_device(udev);
3164 if (status) {
3165 spin_lock_irq(&device_state_lock);
3166 hdev->children[port1-1] = NULL;
3167 spin_unlock_irq(&device_state_lock);
3171 if (status)
3172 goto loop_disable;
3174 status = hub_power_remaining(hub);
3175 if (status)
3176 dev_dbg(hub_dev, "%dmA power budget left\n", status);
3178 return;
3180 loop_disable:
3181 hub_port_disable(hub, port1, 1);
3182 loop:
3183 usb_ep0_reinit(udev);
3184 release_address(udev);
3185 hub_free_dev(udev);
3186 usb_put_dev(udev);
3187 if ((status == -ENOTCONN) || (status == -ENOTSUPP))
3188 break;
3190 if (hub->hdev->parent ||
3191 !hcd->driver->port_handed_over ||
3192 !(hcd->driver->port_handed_over)(hcd, port1))
3193 dev_err(hub_dev, "unable to enumerate USB device on port %d\n",
3194 port1);
3196 done:
3197 hub_port_disable(hub, port1, 1);
3198 if (hcd->driver->relinquish_port && !hub->hdev->parent)
3199 hcd->driver->relinquish_port(hcd, port1);
3202 static void hub_events(void)
3204 struct list_head *tmp;
3205 struct usb_device *hdev;
3206 struct usb_interface *intf;
3207 struct usb_hub *hub;
3208 struct device *hub_dev;
3209 u16 hubstatus;
3210 u16 hubchange;
3211 u16 portstatus;
3212 u16 portchange;
3213 int i, ret;
3214 int connect_change;
3217 * We restart the list every time to avoid a deadlock with
3218 * deleting hubs downstream from this one. This should be
3219 * safe since we delete the hub from the event list.
3220 * Not the most efficient, but avoids deadlocks.
3222 while (1) {
3224 /* Grab the first entry at the beginning of the list */
3225 spin_lock_irq(&hub_event_lock);
3226 if (list_empty(&hub_event_list)) {
3227 spin_unlock_irq(&hub_event_lock);
3228 break;
3231 tmp = hub_event_list.next;
3232 list_del_init(tmp);
3234 hub = list_entry(tmp, struct usb_hub, event_list);
3235 kref_get(&hub->kref);
3236 spin_unlock_irq(&hub_event_lock);
3238 hdev = hub->hdev;
3239 hub_dev = hub->intfdev;
3240 intf = to_usb_interface(hub_dev);
3241 dev_dbg(hub_dev, "state %d ports %d chg %04x evt %04x\n",
3242 hdev->state, hub->descriptor
3243 ? hub->descriptor->bNbrPorts
3244 : 0,
3245 /* NOTE: expects max 15 ports... */
3246 (u16) hub->change_bits[0],
3247 (u16) hub->event_bits[0]);
3249 /* Lock the device, then check to see if we were
3250 * disconnected while waiting for the lock to succeed. */
3251 usb_lock_device(hdev);
3252 if (unlikely(hub->disconnected))
3253 goto loop_disconnected;
3255 /* If the hub has died, clean up after it */
3256 if (hdev->state == USB_STATE_NOTATTACHED) {
3257 hub->error = -ENODEV;
3258 hub_quiesce(hub, HUB_DISCONNECT);
3259 goto loop;
3262 /* Autoresume */
3263 ret = usb_autopm_get_interface(intf);
3264 if (ret) {
3265 dev_dbg(hub_dev, "Can't autoresume: %d\n", ret);
3266 goto loop;
3269 /* If this is an inactive hub, do nothing */
3270 if (hub->quiescing)
3271 goto loop_autopm;
3273 if (hub->error) {
3274 dev_dbg (hub_dev, "resetting for error %d\n",
3275 hub->error);
3277 ret = usb_reset_device(hdev);
3278 if (ret) {
3279 dev_dbg (hub_dev,
3280 "error resetting hub: %d\n", ret);
3281 goto loop_autopm;
3284 hub->nerrors = 0;
3285 hub->error = 0;
3288 /* deal with port status changes */
3289 for (i = 1; i <= hub->descriptor->bNbrPorts; i++) {
3290 if (test_bit(i, hub->busy_bits))
3291 continue;
3292 connect_change = test_bit(i, hub->change_bits);
3293 if (!test_and_clear_bit(i, hub->event_bits) &&
3294 !connect_change)
3295 continue;
3297 ret = hub_port_status(hub, i,
3298 &portstatus, &portchange);
3299 if (ret < 0)
3300 continue;
3302 if (portchange & USB_PORT_STAT_C_CONNECTION) {
3303 clear_port_feature(hdev, i,
3304 USB_PORT_FEAT_C_CONNECTION);
3305 connect_change = 1;
3308 if (portchange & USB_PORT_STAT_C_ENABLE) {
3309 if (!connect_change)
3310 dev_dbg (hub_dev,
3311 "port %d enable change, "
3312 "status %08x\n",
3313 i, portstatus);
3314 clear_port_feature(hdev, i,
3315 USB_PORT_FEAT_C_ENABLE);
3318 * EM interference sometimes causes badly
3319 * shielded USB devices to be shutdown by
3320 * the hub, this hack enables them again.
3321 * Works at least with mouse driver.
3323 if (!(portstatus & USB_PORT_STAT_ENABLE)
3324 && !connect_change
3325 && hdev->children[i-1]) {
3326 dev_err (hub_dev,
3327 "port %i "
3328 "disabled by hub (EMI?), "
3329 "re-enabling...\n",
3331 connect_change = 1;
3335 if (portchange & USB_PORT_STAT_C_SUSPEND) {
3336 struct usb_device *udev;
3338 clear_port_feature(hdev, i,
3339 USB_PORT_FEAT_C_SUSPEND);
3340 udev = hdev->children[i-1];
3341 if (udev) {
3342 /* TRSMRCY = 10 msec */
3343 msleep(10);
3345 usb_lock_device(udev);
3346 ret = usb_remote_wakeup(hdev->
3347 children[i-1]);
3348 usb_unlock_device(udev);
3349 if (ret < 0)
3350 connect_change = 1;
3351 } else {
3352 ret = -ENODEV;
3353 hub_port_disable(hub, i, 1);
3355 dev_dbg (hub_dev,
3356 "resume on port %d, status %d\n",
3357 i, ret);
3360 if (portchange & USB_PORT_STAT_C_OVERCURRENT) {
3361 dev_err (hub_dev,
3362 "over-current change on port %d\n",
3364 clear_port_feature(hdev, i,
3365 USB_PORT_FEAT_C_OVER_CURRENT);
3366 hub_power_on(hub, true);
3369 if (portchange & USB_PORT_STAT_C_RESET) {
3370 dev_dbg (hub_dev,
3371 "reset change on port %d\n",
3373 clear_port_feature(hdev, i,
3374 USB_PORT_FEAT_C_RESET);
3377 if (connect_change)
3378 hub_port_connect_change(hub, i,
3379 portstatus, portchange);
3380 } /* end for i */
3382 /* deal with hub status changes */
3383 if (test_and_clear_bit(0, hub->event_bits) == 0)
3384 ; /* do nothing */
3385 else if (hub_hub_status(hub, &hubstatus, &hubchange) < 0)
3386 dev_err (hub_dev, "get_hub_status failed\n");
3387 else {
3388 if (hubchange & HUB_CHANGE_LOCAL_POWER) {
3389 dev_dbg (hub_dev, "power change\n");
3390 clear_hub_feature(hdev, C_HUB_LOCAL_POWER);
3391 if (hubstatus & HUB_STATUS_LOCAL_POWER)
3392 /* FIXME: Is this always true? */
3393 hub->limited_power = 1;
3394 else
3395 hub->limited_power = 0;
3397 if (hubchange & HUB_CHANGE_OVERCURRENT) {
3398 dev_dbg (hub_dev, "overcurrent change\n");
3399 msleep(500); /* Cool down */
3400 clear_hub_feature(hdev, C_HUB_OVER_CURRENT);
3401 hub_power_on(hub, true);
3405 loop_autopm:
3406 /* Balance the usb_autopm_get_interface() above */
3407 usb_autopm_put_interface_no_suspend(intf);
3408 loop:
3409 /* Balance the usb_autopm_get_interface_no_resume() in
3410 * kick_khubd() and allow autosuspend.
3412 usb_autopm_put_interface(intf);
3413 loop_disconnected:
3414 usb_unlock_device(hdev);
3415 kref_put(&hub->kref, hub_release);
3417 } /* end while (1) */
3420 static int hub_thread(void *__unused)
3422 /* khubd needs to be freezable to avoid intefering with USB-PERSIST
3423 * port handover. Otherwise it might see that a full-speed device
3424 * was gone before the EHCI controller had handed its port over to
3425 * the companion full-speed controller.
3427 set_freezable();
3429 do {
3430 hub_events();
3431 wait_event_freezable(khubd_wait,
3432 !list_empty(&hub_event_list) ||
3433 kthread_should_stop());
3434 } while (!kthread_should_stop() || !list_empty(&hub_event_list));
3436 pr_debug("%s: khubd exiting\n", usbcore_name);
3437 return 0;
3440 static const struct usb_device_id hub_id_table[] = {
3441 { .match_flags = USB_DEVICE_ID_MATCH_DEV_CLASS,
3442 .bDeviceClass = USB_CLASS_HUB},
3443 { .match_flags = USB_DEVICE_ID_MATCH_INT_CLASS,
3444 .bInterfaceClass = USB_CLASS_HUB},
3445 { } /* Terminating entry */
3448 MODULE_DEVICE_TABLE (usb, hub_id_table);
3450 static struct usb_driver hub_driver = {
3451 .name = "hub",
3452 .probe = hub_probe,
3453 .disconnect = hub_disconnect,
3454 .suspend = hub_suspend,
3455 .resume = hub_resume,
3456 .reset_resume = hub_reset_resume,
3457 .pre_reset = hub_pre_reset,
3458 .post_reset = hub_post_reset,
3459 .ioctl = hub_ioctl,
3460 .id_table = hub_id_table,
3461 .supports_autosuspend = 1,
3464 int usb_hub_init(void)
3466 if (usb_register(&hub_driver) < 0) {
3467 printk(KERN_ERR "%s: can't register hub driver\n",
3468 usbcore_name);
3469 return -1;
3472 khubd_task = kthread_run(hub_thread, NULL, "khubd");
3473 if (!IS_ERR(khubd_task))
3474 return 0;
3476 /* Fall through if kernel_thread failed */
3477 usb_deregister(&hub_driver);
3478 printk(KERN_ERR "%s: can't start khubd\n", usbcore_name);
3480 return -1;
3483 void usb_hub_cleanup(void)
3485 kthread_stop(khubd_task);
3488 * Hub resources are freed for us by usb_deregister. It calls
3489 * usb_driver_purge on every device which in turn calls that
3490 * devices disconnect function if it is using this driver.
3491 * The hub_disconnect function takes care of releasing the
3492 * individual hub resources. -greg
3494 usb_deregister(&hub_driver);
3495 } /* usb_hub_cleanup() */
3497 static int descriptors_changed(struct usb_device *udev,
3498 struct usb_device_descriptor *old_device_descriptor)
3500 int changed = 0;
3501 unsigned index;
3502 unsigned serial_len = 0;
3503 unsigned len;
3504 unsigned old_length;
3505 int length;
3506 char *buf;
3508 if (memcmp(&udev->descriptor, old_device_descriptor,
3509 sizeof(*old_device_descriptor)) != 0)
3510 return 1;
3512 /* Since the idVendor, idProduct, and bcdDevice values in the
3513 * device descriptor haven't changed, we will assume the
3514 * Manufacturer and Product strings haven't changed either.
3515 * But the SerialNumber string could be different (e.g., a
3516 * different flash card of the same brand).
3518 if (udev->serial)
3519 serial_len = strlen(udev->serial) + 1;
3521 len = serial_len;
3522 for (index = 0; index < udev->descriptor.bNumConfigurations; index++) {
3523 old_length = le16_to_cpu(udev->config[index].desc.wTotalLength);
3524 len = max(len, old_length);
3527 buf = kmalloc(len, GFP_NOIO);
3528 if (buf == NULL) {
3529 dev_err(&udev->dev, "no mem to re-read configs after reset\n");
3530 /* assume the worst */
3531 return 1;
3533 for (index = 0; index < udev->descriptor.bNumConfigurations; index++) {
3534 old_length = le16_to_cpu(udev->config[index].desc.wTotalLength);
3535 length = usb_get_descriptor(udev, USB_DT_CONFIG, index, buf,
3536 old_length);
3537 if (length != old_length) {
3538 dev_dbg(&udev->dev, "config index %d, error %d\n",
3539 index, length);
3540 changed = 1;
3541 break;
3543 if (memcmp (buf, udev->rawdescriptors[index], old_length)
3544 != 0) {
3545 dev_dbg(&udev->dev, "config index %d changed (#%d)\n",
3546 index,
3547 ((struct usb_config_descriptor *) buf)->
3548 bConfigurationValue);
3549 changed = 1;
3550 break;
3554 if (!changed && serial_len) {
3555 length = usb_string(udev, udev->descriptor.iSerialNumber,
3556 buf, serial_len);
3557 if (length + 1 != serial_len) {
3558 dev_dbg(&udev->dev, "serial string error %d\n",
3559 length);
3560 changed = 1;
3561 } else if (memcmp(buf, udev->serial, length) != 0) {
3562 dev_dbg(&udev->dev, "serial string changed\n");
3563 changed = 1;
3567 kfree(buf);
3568 return changed;
3572 * usb_reset_and_verify_device - perform a USB port reset to reinitialize a device
3573 * @udev: device to reset (not in SUSPENDED or NOTATTACHED state)
3575 * WARNING - don't use this routine to reset a composite device
3576 * (one with multiple interfaces owned by separate drivers)!
3577 * Use usb_reset_device() instead.
3579 * Do a port reset, reassign the device's address, and establish its
3580 * former operating configuration. If the reset fails, or the device's
3581 * descriptors change from their values before the reset, or the original
3582 * configuration and altsettings cannot be restored, a flag will be set
3583 * telling khubd to pretend the device has been disconnected and then
3584 * re-connected. All drivers will be unbound, and the device will be
3585 * re-enumerated and probed all over again.
3587 * Returns 0 if the reset succeeded, -ENODEV if the device has been
3588 * flagged for logical disconnection, or some other negative error code
3589 * if the reset wasn't even attempted.
3591 * The caller must own the device lock. For example, it's safe to use
3592 * this from a driver probe() routine after downloading new firmware.
3593 * For calls that might not occur during probe(), drivers should lock
3594 * the device using usb_lock_device_for_reset().
3596 * Locking exception: This routine may also be called from within an
3597 * autoresume handler. Such usage won't conflict with other tasks
3598 * holding the device lock because these tasks should always call
3599 * usb_autopm_resume_device(), thereby preventing any unwanted autoresume.
3601 static int usb_reset_and_verify_device(struct usb_device *udev)
3603 struct usb_device *parent_hdev = udev->parent;
3604 struct usb_hub *parent_hub;
3605 struct usb_hcd *hcd = bus_to_hcd(udev->bus);
3606 struct usb_device_descriptor descriptor = udev->descriptor;
3607 int i, ret = 0;
3608 int port1 = udev->portnum;
3610 if (udev->state == USB_STATE_NOTATTACHED ||
3611 udev->state == USB_STATE_SUSPENDED) {
3612 dev_dbg(&udev->dev, "device reset not allowed in state %d\n",
3613 udev->state);
3614 return -EINVAL;
3617 if (!parent_hdev) {
3618 /* this requires hcd-specific logic; see OHCI hc_restart() */
3619 dev_dbg(&udev->dev, "%s for root hub!\n", __func__);
3620 return -EISDIR;
3622 parent_hub = hdev_to_hub(parent_hdev);
3624 set_bit(port1, parent_hub->busy_bits);
3625 for (i = 0; i < SET_CONFIG_TRIES; ++i) {
3627 /* ep0 maxpacket size may change; let the HCD know about it.
3628 * Other endpoints will be handled by re-enumeration. */
3629 usb_ep0_reinit(udev);
3630 ret = hub_port_init(parent_hub, udev, port1, i);
3631 if (ret >= 0 || ret == -ENOTCONN || ret == -ENODEV)
3632 break;
3634 clear_bit(port1, parent_hub->busy_bits);
3636 if (ret < 0)
3637 goto re_enumerate;
3639 /* Device might have changed firmware (DFU or similar) */
3640 if (descriptors_changed(udev, &descriptor)) {
3641 dev_info(&udev->dev, "device firmware changed\n");
3642 udev->descriptor = descriptor; /* for disconnect() calls */
3643 goto re_enumerate;
3646 /* Restore the device's previous configuration */
3647 if (!udev->actconfig)
3648 goto done;
3650 mutex_lock(&hcd->bandwidth_mutex);
3651 ret = usb_hcd_alloc_bandwidth(udev, udev->actconfig, NULL, NULL);
3652 if (ret < 0) {
3653 dev_warn(&udev->dev,
3654 "Busted HC? Not enough HCD resources for "
3655 "old configuration.\n");
3656 mutex_unlock(&hcd->bandwidth_mutex);
3657 goto re_enumerate;
3659 ret = usb_control_msg(udev, usb_sndctrlpipe(udev, 0),
3660 USB_REQ_SET_CONFIGURATION, 0,
3661 udev->actconfig->desc.bConfigurationValue, 0,
3662 NULL, 0, USB_CTRL_SET_TIMEOUT);
3663 if (ret < 0) {
3664 dev_err(&udev->dev,
3665 "can't restore configuration #%d (error=%d)\n",
3666 udev->actconfig->desc.bConfigurationValue, ret);
3667 mutex_unlock(&hcd->bandwidth_mutex);
3668 goto re_enumerate;
3670 mutex_unlock(&hcd->bandwidth_mutex);
3671 usb_set_device_state(udev, USB_STATE_CONFIGURED);
3673 /* Put interfaces back into the same altsettings as before.
3674 * Don't bother to send the Set-Interface request for interfaces
3675 * that were already in altsetting 0; besides being unnecessary,
3676 * many devices can't handle it. Instead just reset the host-side
3677 * endpoint state.
3679 for (i = 0; i < udev->actconfig->desc.bNumInterfaces; i++) {
3680 struct usb_host_config *config = udev->actconfig;
3681 struct usb_interface *intf = config->interface[i];
3682 struct usb_interface_descriptor *desc;
3684 desc = &intf->cur_altsetting->desc;
3685 if (desc->bAlternateSetting == 0) {
3686 usb_disable_interface(udev, intf, true);
3687 usb_enable_interface(udev, intf, true);
3688 ret = 0;
3689 } else {
3690 /* Let the bandwidth allocation function know that this
3691 * device has been reset, and it will have to use
3692 * alternate setting 0 as the current alternate setting.
3694 intf->resetting_device = 1;
3695 ret = usb_set_interface(udev, desc->bInterfaceNumber,
3696 desc->bAlternateSetting);
3697 intf->resetting_device = 0;
3699 if (ret < 0) {
3700 dev_err(&udev->dev, "failed to restore interface %d "
3701 "altsetting %d (error=%d)\n",
3702 desc->bInterfaceNumber,
3703 desc->bAlternateSetting,
3704 ret);
3705 goto re_enumerate;
3709 done:
3710 return 0;
3712 re_enumerate:
3713 hub_port_logical_disconnect(parent_hub, port1);
3714 return -ENODEV;
3718 * usb_reset_device - warn interface drivers and perform a USB port reset
3719 * @udev: device to reset (not in SUSPENDED or NOTATTACHED state)
3721 * Warns all drivers bound to registered interfaces (using their pre_reset
3722 * method), performs the port reset, and then lets the drivers know that
3723 * the reset is over (using their post_reset method).
3725 * Return value is the same as for usb_reset_and_verify_device().
3727 * The caller must own the device lock. For example, it's safe to use
3728 * this from a driver probe() routine after downloading new firmware.
3729 * For calls that might not occur during probe(), drivers should lock
3730 * the device using usb_lock_device_for_reset().
3732 * If an interface is currently being probed or disconnected, we assume
3733 * its driver knows how to handle resets. For all other interfaces,
3734 * if the driver doesn't have pre_reset and post_reset methods then
3735 * we attempt to unbind it and rebind afterward.
3737 int usb_reset_device(struct usb_device *udev)
3739 int ret;
3740 int i;
3741 struct usb_host_config *config = udev->actconfig;
3743 if (udev->state == USB_STATE_NOTATTACHED ||
3744 udev->state == USB_STATE_SUSPENDED) {
3745 dev_dbg(&udev->dev, "device reset not allowed in state %d\n",
3746 udev->state);
3747 return -EINVAL;
3750 /* Prevent autosuspend during the reset */
3751 usb_autoresume_device(udev);
3753 if (config) {
3754 for (i = 0; i < config->desc.bNumInterfaces; ++i) {
3755 struct usb_interface *cintf = config->interface[i];
3756 struct usb_driver *drv;
3757 int unbind = 0;
3759 if (cintf->dev.driver) {
3760 drv = to_usb_driver(cintf->dev.driver);
3761 if (drv->pre_reset && drv->post_reset)
3762 unbind = (drv->pre_reset)(cintf);
3763 else if (cintf->condition ==
3764 USB_INTERFACE_BOUND)
3765 unbind = 1;
3766 if (unbind)
3767 usb_forced_unbind_intf(cintf);
3772 ret = usb_reset_and_verify_device(udev);
3774 if (config) {
3775 for (i = config->desc.bNumInterfaces - 1; i >= 0; --i) {
3776 struct usb_interface *cintf = config->interface[i];
3777 struct usb_driver *drv;
3778 int rebind = cintf->needs_binding;
3780 if (!rebind && cintf->dev.driver) {
3781 drv = to_usb_driver(cintf->dev.driver);
3782 if (drv->post_reset)
3783 rebind = (drv->post_reset)(cintf);
3784 else if (cintf->condition ==
3785 USB_INTERFACE_BOUND)
3786 rebind = 1;
3788 if (ret == 0 && rebind)
3789 usb_rebind_intf(cintf);
3793 usb_autosuspend_device(udev);
3794 return ret;
3796 EXPORT_SYMBOL_GPL(usb_reset_device);
3800 * usb_queue_reset_device - Reset a USB device from an atomic context
3801 * @iface: USB interface belonging to the device to reset
3803 * This function can be used to reset a USB device from an atomic
3804 * context, where usb_reset_device() won't work (as it blocks).
3806 * Doing a reset via this method is functionally equivalent to calling
3807 * usb_reset_device(), except for the fact that it is delayed to a
3808 * workqueue. This means that any drivers bound to other interfaces
3809 * might be unbound, as well as users from usbfs in user space.
3811 * Corner cases:
3813 * - Scheduling two resets at the same time from two different drivers
3814 * attached to two different interfaces of the same device is
3815 * possible; depending on how the driver attached to each interface
3816 * handles ->pre_reset(), the second reset might happen or not.
3818 * - If a driver is unbound and it had a pending reset, the reset will
3819 * be cancelled.
3821 * - This function can be called during .probe() or .disconnect()
3822 * times. On return from .disconnect(), any pending resets will be
3823 * cancelled.
3825 * There is no no need to lock/unlock the @reset_ws as schedule_work()
3826 * does its own.
3828 * NOTE: We don't do any reference count tracking because it is not
3829 * needed. The lifecycle of the work_struct is tied to the
3830 * usb_interface. Before destroying the interface we cancel the
3831 * work_struct, so the fact that work_struct is queued and or
3832 * running means the interface (and thus, the device) exist and
3833 * are referenced.
3835 void usb_queue_reset_device(struct usb_interface *iface)
3837 schedule_work(&iface->reset_ws);
3839 EXPORT_SYMBOL_GPL(usb_queue_reset_device);