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