Merge remote-tracking branch 'stable/linux-4.1.y' into rpi-4.1.y
[projects/modsched/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/workqueue.h>
26 #include <linux/mutex.h>
27 #include <linux/random.h>
28 #include <linux/pm_qos.h>
29
30 #include <asm/uaccess.h>
31 #include <asm/byteorder.h>
32
33 #include "hub.h"
34 #include "otg_whitelist.h"
35
36 #define USB_VENDOR_GENESYS_LOGIC                0x05e3
37 #define HUB_QUIRK_CHECK_PORT_AUTOSUSPEND        0x01
38
39 /* Protect struct usb_device->state and ->children members
40  * Note: Both are also protected by ->dev.sem, except that ->state can
41  * change to USB_STATE_NOTATTACHED even when the semaphore isn't held. */
42 static DEFINE_SPINLOCK(device_state_lock);
43
44 /* workqueue to process hub events */
45 static struct workqueue_struct *hub_wq;
46 static void hub_event(struct work_struct *work);
47
48 /* synchronize hub-port add/remove and peering operations */
49 DEFINE_MUTEX(usb_port_peer_mutex);
50
51 /* cycle leds on hubs that aren't blinking for attention */
52 static bool blinkenlights = 0;
53 module_param (blinkenlights, bool, S_IRUGO);
54 MODULE_PARM_DESC (blinkenlights, "true to cycle leds on hubs");
55
56 /*
57  * Device SATA8000 FW1.0 from DATAST0R Technology Corp requires about
58  * 10 seconds to send reply for the initial 64-byte descriptor request.
59  */
60 /* define initial 64-byte descriptor request timeout in milliseconds */
61 static int initial_descriptor_timeout = USB_CTRL_GET_TIMEOUT;
62 module_param(initial_descriptor_timeout, int, S_IRUGO|S_IWUSR);
63 MODULE_PARM_DESC(initial_descriptor_timeout,
64                 "initial 64-byte descriptor request timeout in milliseconds "
65                 "(default 5000 - 5.0 seconds)");
66
67 /*
68  * As of 2.6.10 we introduce a new USB device initialization scheme which
69  * closely resembles the way Windows works.  Hopefully it will be compatible
70  * with a wider range of devices than the old scheme.  However some previously
71  * working devices may start giving rise to "device not accepting address"
72  * errors; if that happens the user can try the old scheme by adjusting the
73  * following module parameters.
74  *
75  * For maximum flexibility there are two boolean parameters to control the
76  * hub driver's behavior.  On the first initialization attempt, if the
77  * "old_scheme_first" parameter is set then the old scheme will be used,
78  * otherwise the new scheme is used.  If that fails and "use_both_schemes"
79  * is set, then the driver will make another attempt, using the other scheme.
80  */
81 static bool old_scheme_first = 0;
82 module_param(old_scheme_first, bool, S_IRUGO | S_IWUSR);
83 MODULE_PARM_DESC(old_scheme_first,
84                  "start with the old device initialization scheme");
85
86 static bool use_both_schemes = 1;
87 module_param(use_both_schemes, bool, S_IRUGO | S_IWUSR);
88 MODULE_PARM_DESC(use_both_schemes,
89                 "try the other device initialization scheme if the "
90                 "first one fails");
91
92 /* Mutual exclusion for EHCI CF initialization.  This interferes with
93  * port reset on some companion controllers.
94  */
95 DECLARE_RWSEM(ehci_cf_port_reset_rwsem);
96 EXPORT_SYMBOL_GPL(ehci_cf_port_reset_rwsem);
97
98 #define HUB_DEBOUNCE_TIMEOUT    2000
99 #define HUB_DEBOUNCE_STEP         25
100 #define HUB_DEBOUNCE_STABLE      100
101
102 static void hub_release(struct kref *kref);
103 static int usb_reset_and_verify_device(struct usb_device *udev);
104
105 static inline char *portspeed(struct usb_hub *hub, int portstatus)
106 {
107         if (hub_is_superspeed(hub->hdev))
108                 return "5.0 Gb/s";
109         if (portstatus & USB_PORT_STAT_HIGH_SPEED)
110                 return "480 Mb/s";
111         else if (portstatus & USB_PORT_STAT_LOW_SPEED)
112                 return "1.5 Mb/s";
113         else
114                 return "12 Mb/s";
115 }
116
117 /* Note that hdev or one of its children must be locked! */
118 struct usb_hub *usb_hub_to_struct_hub(struct usb_device *hdev)
119 {
120         if (!hdev || !hdev->actconfig || !hdev->maxchild)
121                 return NULL;
122         return usb_get_intfdata(hdev->actconfig->interface[0]);
123 }
124
125 int usb_device_supports_lpm(struct usb_device *udev)
126 {
127         /* Some devices have trouble with LPM */
128         if (udev->quirks & USB_QUIRK_NO_LPM)
129                 return 0;
130
131         /* USB 2.1 (and greater) devices indicate LPM support through
132          * their USB 2.0 Extended Capabilities BOS descriptor.
133          */
134         if (udev->speed == USB_SPEED_HIGH) {
135                 if (udev->bos->ext_cap &&
136                         (USB_LPM_SUPPORT &
137                          le32_to_cpu(udev->bos->ext_cap->bmAttributes)))
138                         return 1;
139                 return 0;
140         }
141
142         /*
143          * According to the USB 3.0 spec, all USB 3.0 devices must support LPM.
144          * However, there are some that don't, and they set the U1/U2 exit
145          * latencies to zero.
146          */
147         if (!udev->bos->ss_cap) {
148                 dev_info(&udev->dev, "No LPM exit latency info found, disabling LPM.\n");
149                 return 0;
150         }
151
152         if (udev->bos->ss_cap->bU1devExitLat == 0 &&
153                         udev->bos->ss_cap->bU2DevExitLat == 0) {
154                 if (udev->parent)
155                         dev_info(&udev->dev, "LPM exit latency is zeroed, disabling LPM.\n");
156                 else
157                         dev_info(&udev->dev, "We don't know the algorithms for LPM for this host, disabling LPM.\n");
158                 return 0;
159         }
160
161         if (!udev->parent || udev->parent->lpm_capable)
162                 return 1;
163         return 0;
164 }
165
166 /*
167  * Set the Maximum Exit Latency (MEL) for the host to initiate a transition from
168  * either U1 or U2.
169  */
170 static void usb_set_lpm_mel(struct usb_device *udev,
171                 struct usb3_lpm_parameters *udev_lpm_params,
172                 unsigned int udev_exit_latency,
173                 struct usb_hub *hub,
174                 struct usb3_lpm_parameters *hub_lpm_params,
175                 unsigned int hub_exit_latency)
176 {
177         unsigned int total_mel;
178         unsigned int device_mel;
179         unsigned int hub_mel;
180
181         /*
182          * Calculate the time it takes to transition all links from the roothub
183          * to the parent hub into U0.  The parent hub must then decode the
184          * packet (hub header decode latency) to figure out which port it was
185          * bound for.
186          *
187          * The Hub Header decode latency is expressed in 0.1us intervals (0x1
188          * means 0.1us).  Multiply that by 100 to get nanoseconds.
189          */
190         total_mel = hub_lpm_params->mel +
191                 (hub->descriptor->u.ss.bHubHdrDecLat * 100);
192
193         /*
194          * How long will it take to transition the downstream hub's port into
195          * U0?  The greater of either the hub exit latency or the device exit
196          * latency.
197          *
198          * The BOS U1/U2 exit latencies are expressed in 1us intervals.
199          * Multiply that by 1000 to get nanoseconds.
200          */
201         device_mel = udev_exit_latency * 1000;
202         hub_mel = hub_exit_latency * 1000;
203         if (device_mel > hub_mel)
204                 total_mel += device_mel;
205         else
206                 total_mel += hub_mel;
207
208         udev_lpm_params->mel = total_mel;
209 }
210
211 /*
212  * Set the maximum Device to Host Exit Latency (PEL) for the device to initiate
213  * a transition from either U1 or U2.
214  */
215 static void usb_set_lpm_pel(struct usb_device *udev,
216                 struct usb3_lpm_parameters *udev_lpm_params,
217                 unsigned int udev_exit_latency,
218                 struct usb_hub *hub,
219                 struct usb3_lpm_parameters *hub_lpm_params,
220                 unsigned int hub_exit_latency,
221                 unsigned int port_to_port_exit_latency)
222 {
223         unsigned int first_link_pel;
224         unsigned int hub_pel;
225
226         /*
227          * First, the device sends an LFPS to transition the link between the
228          * device and the parent hub into U0.  The exit latency is the bigger of
229          * the device exit latency or the hub exit latency.
230          */
231         if (udev_exit_latency > hub_exit_latency)
232                 first_link_pel = udev_exit_latency * 1000;
233         else
234                 first_link_pel = hub_exit_latency * 1000;
235
236         /*
237          * When the hub starts to receive the LFPS, there is a slight delay for
238          * it to figure out that one of the ports is sending an LFPS.  Then it
239          * will forward the LFPS to its upstream link.  The exit latency is the
240          * delay, plus the PEL that we calculated for this hub.
241          */
242         hub_pel = port_to_port_exit_latency * 1000 + hub_lpm_params->pel;
243
244         /*
245          * According to figure C-7 in the USB 3.0 spec, the PEL for this device
246          * is the greater of the two exit latencies.
247          */
248         if (first_link_pel > hub_pel)
249                 udev_lpm_params->pel = first_link_pel;
250         else
251                 udev_lpm_params->pel = hub_pel;
252 }
253
254 /*
255  * Set the System Exit Latency (SEL) to indicate the total worst-case time from
256  * when a device initiates a transition to U0, until when it will receive the
257  * first packet from the host controller.
258  *
259  * Section C.1.5.1 describes the four components to this:
260  *  - t1: device PEL
261  *  - t2: time for the ERDY to make it from the device to the host.
262  *  - t3: a host-specific delay to process the ERDY.
263  *  - t4: time for the packet to make it from the host to the device.
264  *
265  * t3 is specific to both the xHCI host and the platform the host is integrated
266  * into.  The Intel HW folks have said it's negligible, FIXME if a different
267  * vendor says otherwise.
268  */
269 static void usb_set_lpm_sel(struct usb_device *udev,
270                 struct usb3_lpm_parameters *udev_lpm_params)
271 {
272         struct usb_device *parent;
273         unsigned int num_hubs;
274         unsigned int total_sel;
275
276         /* t1 = device PEL */
277         total_sel = udev_lpm_params->pel;
278         /* How many external hubs are in between the device & the root port. */
279         for (parent = udev->parent, num_hubs = 0; parent->parent;
280                         parent = parent->parent)
281                 num_hubs++;
282         /* t2 = 2.1us + 250ns * (num_hubs - 1) */
283         if (num_hubs > 0)
284                 total_sel += 2100 + 250 * (num_hubs - 1);
285
286         /* t4 = 250ns * num_hubs */
287         total_sel += 250 * num_hubs;
288
289         udev_lpm_params->sel = total_sel;
290 }
291
292 static void usb_set_lpm_parameters(struct usb_device *udev)
293 {
294         struct usb_hub *hub;
295         unsigned int port_to_port_delay;
296         unsigned int udev_u1_del;
297         unsigned int udev_u2_del;
298         unsigned int hub_u1_del;
299         unsigned int hub_u2_del;
300
301         if (!udev->lpm_capable || udev->speed != USB_SPEED_SUPER)
302                 return;
303
304         hub = usb_hub_to_struct_hub(udev->parent);
305         /* It doesn't take time to transition the roothub into U0, since it
306          * doesn't have an upstream link.
307          */
308         if (!hub)
309                 return;
310
311         udev_u1_del = udev->bos->ss_cap->bU1devExitLat;
312         udev_u2_del = le16_to_cpu(udev->bos->ss_cap->bU2DevExitLat);
313         hub_u1_del = udev->parent->bos->ss_cap->bU1devExitLat;
314         hub_u2_del = le16_to_cpu(udev->parent->bos->ss_cap->bU2DevExitLat);
315
316         usb_set_lpm_mel(udev, &udev->u1_params, udev_u1_del,
317                         hub, &udev->parent->u1_params, hub_u1_del);
318
319         usb_set_lpm_mel(udev, &udev->u2_params, udev_u2_del,
320                         hub, &udev->parent->u2_params, hub_u2_del);
321
322         /*
323          * Appendix C, section C.2.2.2, says that there is a slight delay from
324          * when the parent hub notices the downstream port is trying to
325          * transition to U0 to when the hub initiates a U0 transition on its
326          * upstream port.  The section says the delays are tPort2PortU1EL and
327          * tPort2PortU2EL, but it doesn't define what they are.
328          *
329          * The hub chapter, sections 10.4.2.4 and 10.4.2.5 seem to be talking
330          * about the same delays.  Use the maximum delay calculations from those
331          * sections.  For U1, it's tHubPort2PortExitLat, which is 1us max.  For
332          * U2, it's tHubPort2PortExitLat + U2DevExitLat - U1DevExitLat.  I
333          * assume the device exit latencies they are talking about are the hub
334          * exit latencies.
335          *
336          * What do we do if the U2 exit latency is less than the U1 exit
337          * latency?  It's possible, although not likely...
338          */
339         port_to_port_delay = 1;
340
341         usb_set_lpm_pel(udev, &udev->u1_params, udev_u1_del,
342                         hub, &udev->parent->u1_params, hub_u1_del,
343                         port_to_port_delay);
344
345         if (hub_u2_del > hub_u1_del)
346                 port_to_port_delay = 1 + hub_u2_del - hub_u1_del;
347         else
348                 port_to_port_delay = 1 + hub_u1_del;
349
350         usb_set_lpm_pel(udev, &udev->u2_params, udev_u2_del,
351                         hub, &udev->parent->u2_params, hub_u2_del,
352                         port_to_port_delay);
353
354         /* Now that we've got PEL, calculate SEL. */
355         usb_set_lpm_sel(udev, &udev->u1_params);
356         usb_set_lpm_sel(udev, &udev->u2_params);
357 }
358
359 /* USB 2.0 spec Section 11.24.4.5 */
360 static int get_hub_descriptor(struct usb_device *hdev, void *data)
361 {
362         int i, ret, size;
363         unsigned dtype;
364
365         if (hub_is_superspeed(hdev)) {
366                 dtype = USB_DT_SS_HUB;
367                 size = USB_DT_SS_HUB_SIZE;
368         } else {
369                 dtype = USB_DT_HUB;
370                 size = sizeof(struct usb_hub_descriptor);
371         }
372
373         for (i = 0; i < 3; i++) {
374                 ret = usb_control_msg(hdev, usb_rcvctrlpipe(hdev, 0),
375                         USB_REQ_GET_DESCRIPTOR, USB_DIR_IN | USB_RT_HUB,
376                         dtype << 8, 0, data, size,
377                         USB_CTRL_GET_TIMEOUT);
378                 if (ret >= (USB_DT_HUB_NONVAR_SIZE + 2))
379                         return ret;
380         }
381         return -EINVAL;
382 }
383
384 /*
385  * USB 2.0 spec Section 11.24.2.1
386  */
387 static int clear_hub_feature(struct usb_device *hdev, int feature)
388 {
389         return usb_control_msg(hdev, usb_sndctrlpipe(hdev, 0),
390                 USB_REQ_CLEAR_FEATURE, USB_RT_HUB, feature, 0, NULL, 0, 1000);
391 }
392
393 /*
394  * USB 2.0 spec Section 11.24.2.2
395  */
396 int usb_clear_port_feature(struct usb_device *hdev, int port1, int feature)
397 {
398         return usb_control_msg(hdev, usb_sndctrlpipe(hdev, 0),
399                 USB_REQ_CLEAR_FEATURE, USB_RT_PORT, feature, port1,
400                 NULL, 0, 1000);
401 }
402
403 /*
404  * USB 2.0 spec Section 11.24.2.13
405  */
406 static int set_port_feature(struct usb_device *hdev, int port1, int feature)
407 {
408         return usb_control_msg(hdev, usb_sndctrlpipe(hdev, 0),
409                 USB_REQ_SET_FEATURE, USB_RT_PORT, feature, port1,
410                 NULL, 0, 1000);
411 }
412
413 static char *to_led_name(int selector)
414 {
415         switch (selector) {
416         case HUB_LED_AMBER:
417                 return "amber";
418         case HUB_LED_GREEN:
419                 return "green";
420         case HUB_LED_OFF:
421                 return "off";
422         case HUB_LED_AUTO:
423                 return "auto";
424         default:
425                 return "??";
426         }
427 }
428
429 /*
430  * USB 2.0 spec Section 11.24.2.7.1.10 and table 11-7
431  * for info about using port indicators
432  */
433 static void set_port_led(struct usb_hub *hub, int port1, int selector)
434 {
435         struct usb_port *port_dev = hub->ports[port1 - 1];
436         int status;
437
438         status = set_port_feature(hub->hdev, (selector << 8) | port1,
439                         USB_PORT_FEAT_INDICATOR);
440         dev_dbg(&port_dev->dev, "indicator %s status %d\n",
441                 to_led_name(selector), status);
442 }
443
444 #define LED_CYCLE_PERIOD        ((2*HZ)/3)
445
446 static void led_work (struct work_struct *work)
447 {
448         struct usb_hub          *hub =
449                 container_of(work, struct usb_hub, leds.work);
450         struct usb_device       *hdev = hub->hdev;
451         unsigned                i;
452         unsigned                changed = 0;
453         int                     cursor = -1;
454
455         if (hdev->state != USB_STATE_CONFIGURED || hub->quiescing)
456                 return;
457
458         for (i = 0; i < hdev->maxchild; i++) {
459                 unsigned        selector, mode;
460
461                 /* 30%-50% duty cycle */
462
463                 switch (hub->indicator[i]) {
464                 /* cycle marker */
465                 case INDICATOR_CYCLE:
466                         cursor = i;
467                         selector = HUB_LED_AUTO;
468                         mode = INDICATOR_AUTO;
469                         break;
470                 /* blinking green = sw attention */
471                 case INDICATOR_GREEN_BLINK:
472                         selector = HUB_LED_GREEN;
473                         mode = INDICATOR_GREEN_BLINK_OFF;
474                         break;
475                 case INDICATOR_GREEN_BLINK_OFF:
476                         selector = HUB_LED_OFF;
477                         mode = INDICATOR_GREEN_BLINK;
478                         break;
479                 /* blinking amber = hw attention */
480                 case INDICATOR_AMBER_BLINK:
481                         selector = HUB_LED_AMBER;
482                         mode = INDICATOR_AMBER_BLINK_OFF;
483                         break;
484                 case INDICATOR_AMBER_BLINK_OFF:
485                         selector = HUB_LED_OFF;
486                         mode = INDICATOR_AMBER_BLINK;
487                         break;
488                 /* blink green/amber = reserved */
489                 case INDICATOR_ALT_BLINK:
490                         selector = HUB_LED_GREEN;
491                         mode = INDICATOR_ALT_BLINK_OFF;
492                         break;
493                 case INDICATOR_ALT_BLINK_OFF:
494                         selector = HUB_LED_AMBER;
495                         mode = INDICATOR_ALT_BLINK;
496                         break;
497                 default:
498                         continue;
499                 }
500                 if (selector != HUB_LED_AUTO)
501                         changed = 1;
502                 set_port_led(hub, i + 1, selector);
503                 hub->indicator[i] = mode;
504         }
505         if (!changed && blinkenlights) {
506                 cursor++;
507                 cursor %= hdev->maxchild;
508                 set_port_led(hub, cursor + 1, HUB_LED_GREEN);
509                 hub->indicator[cursor] = INDICATOR_CYCLE;
510                 changed++;
511         }
512         if (changed)
513                 queue_delayed_work(system_power_efficient_wq,
514                                 &hub->leds, LED_CYCLE_PERIOD);
515 }
516
517 /* use a short timeout for hub/port status fetches */
518 #define USB_STS_TIMEOUT         1000
519 #define USB_STS_RETRIES         5
520
521 /*
522  * USB 2.0 spec Section 11.24.2.6
523  */
524 static int get_hub_status(struct usb_device *hdev,
525                 struct usb_hub_status *data)
526 {
527         int i, status = -ETIMEDOUT;
528
529         for (i = 0; i < USB_STS_RETRIES &&
530                         (status == -ETIMEDOUT || status == -EPIPE); i++) {
531                 status = usb_control_msg(hdev, usb_rcvctrlpipe(hdev, 0),
532                         USB_REQ_GET_STATUS, USB_DIR_IN | USB_RT_HUB, 0, 0,
533                         data, sizeof(*data), USB_STS_TIMEOUT);
534         }
535         return status;
536 }
537
538 /*
539  * USB 2.0 spec Section 11.24.2.7
540  */
541 static int get_port_status(struct usb_device *hdev, int port1,
542                 struct usb_port_status *data)
543 {
544         int i, status = -ETIMEDOUT;
545
546         for (i = 0; i < USB_STS_RETRIES &&
547                         (status == -ETIMEDOUT || status == -EPIPE); i++) {
548                 status = usb_control_msg(hdev, usb_rcvctrlpipe(hdev, 0),
549                         USB_REQ_GET_STATUS, USB_DIR_IN | USB_RT_PORT, 0, port1,
550                         data, sizeof(*data), USB_STS_TIMEOUT);
551         }
552         return status;
553 }
554
555 static int hub_port_status(struct usb_hub *hub, int port1,
556                 u16 *status, u16 *change)
557 {
558         int ret;
559
560         mutex_lock(&hub->status_mutex);
561         ret = get_port_status(hub->hdev, port1, &hub->status->port);
562         if (ret < 4) {
563                 if (ret != -ENODEV)
564                         dev_err(hub->intfdev,
565                                 "%s failed (err = %d)\n", __func__, ret);
566                 if (ret >= 0)
567                         ret = -EIO;
568         } else {
569                 *status = le16_to_cpu(hub->status->port.wPortStatus);
570                 *change = le16_to_cpu(hub->status->port.wPortChange);
571
572                 ret = 0;
573         }
574         mutex_unlock(&hub->status_mutex);
575         return ret;
576 }
577
578 static void kick_hub_wq(struct usb_hub *hub)
579 {
580         struct usb_interface *intf;
581
582         if (hub->disconnected || work_pending(&hub->events))
583                 return;
584
585         /*
586          * Suppress autosuspend until the event is proceed.
587          *
588          * Be careful and make sure that the symmetric operation is
589          * always called. We are here only when there is no pending
590          * work for this hub. Therefore put the interface either when
591          * the new work is called or when it is canceled.
592          */
593         intf = to_usb_interface(hub->intfdev);
594         usb_autopm_get_interface_no_resume(intf);
595         kref_get(&hub->kref);
596
597         if (queue_work(hub_wq, &hub->events))
598                 return;
599
600         /* the work has already been scheduled */
601         usb_autopm_put_interface_async(intf);
602         kref_put(&hub->kref, hub_release);
603 }
604
605 void usb_kick_hub_wq(struct usb_device *hdev)
606 {
607         struct usb_hub *hub = usb_hub_to_struct_hub(hdev);
608
609         if (hub)
610                 kick_hub_wq(hub);
611 }
612
613 /*
614  * Let the USB core know that a USB 3.0 device has sent a Function Wake Device
615  * Notification, which indicates it had initiated remote wakeup.
616  *
617  * USB 3.0 hubs do not report the port link state change from U3 to U0 when the
618  * device initiates resume, so the USB core will not receive notice of the
619  * resume through the normal hub interrupt URB.
620  */
621 void usb_wakeup_notification(struct usb_device *hdev,
622                 unsigned int portnum)
623 {
624         struct usb_hub *hub;
625
626         if (!hdev)
627                 return;
628
629         hub = usb_hub_to_struct_hub(hdev);
630         if (hub) {
631                 set_bit(portnum, hub->wakeup_bits);
632                 kick_hub_wq(hub);
633         }
634 }
635 EXPORT_SYMBOL_GPL(usb_wakeup_notification);
636
637 /* completion function, fires on port status changes and various faults */
638 static void hub_irq(struct urb *urb)
639 {
640         struct usb_hub *hub = urb->context;
641         int status = urb->status;
642         unsigned i;
643         unsigned long bits;
644
645         switch (status) {
646         case -ENOENT:           /* synchronous unlink */
647         case -ECONNRESET:       /* async unlink */
648         case -ESHUTDOWN:        /* hardware going away */
649                 return;
650
651         default:                /* presumably an error */
652                 /* Cause a hub reset after 10 consecutive errors */
653                 dev_dbg (hub->intfdev, "transfer --> %d\n", status);
654                 if ((++hub->nerrors < 10) || hub->error)
655                         goto resubmit;
656                 hub->error = status;
657                 /* FALL THROUGH */
658
659         /* let hub_wq handle things */
660         case 0:                 /* we got data:  port status changed */
661                 bits = 0;
662                 for (i = 0; i < urb->actual_length; ++i)
663                         bits |= ((unsigned long) ((*hub->buffer)[i]))
664                                         << (i*8);
665                 hub->event_bits[0] = bits;
666                 break;
667         }
668
669         hub->nerrors = 0;
670
671         /* Something happened, let hub_wq figure it out */
672         kick_hub_wq(hub);
673
674 resubmit:
675         if (hub->quiescing)
676                 return;
677
678         if ((status = usb_submit_urb (hub->urb, GFP_ATOMIC)) != 0
679                         && status != -ENODEV && status != -EPERM)
680                 dev_err (hub->intfdev, "resubmit --> %d\n", status);
681 }
682
683 /* USB 2.0 spec Section 11.24.2.3 */
684 static inline int
685 hub_clear_tt_buffer (struct usb_device *hdev, u16 devinfo, u16 tt)
686 {
687         /* Need to clear both directions for control ep */
688         if (((devinfo >> 11) & USB_ENDPOINT_XFERTYPE_MASK) ==
689                         USB_ENDPOINT_XFER_CONTROL) {
690                 int status = usb_control_msg(hdev, usb_sndctrlpipe(hdev, 0),
691                                 HUB_CLEAR_TT_BUFFER, USB_RT_PORT,
692                                 devinfo ^ 0x8000, tt, NULL, 0, 1000);
693                 if (status)
694                         return status;
695         }
696         return usb_control_msg(hdev, usb_sndctrlpipe(hdev, 0),
697                                HUB_CLEAR_TT_BUFFER, USB_RT_PORT, devinfo,
698                                tt, NULL, 0, 1000);
699 }
700
701 /*
702  * enumeration blocks hub_wq for a long time. we use keventd instead, since
703  * long blocking there is the exception, not the rule.  accordingly, HCDs
704  * talking to TTs must queue control transfers (not just bulk and iso), so
705  * both can talk to the same hub concurrently.
706  */
707 static void hub_tt_work(struct work_struct *work)
708 {
709         struct usb_hub          *hub =
710                 container_of(work, struct usb_hub, tt.clear_work);
711         unsigned long           flags;
712
713         spin_lock_irqsave (&hub->tt.lock, flags);
714         while (!list_empty(&hub->tt.clear_list)) {
715                 struct list_head        *next;
716                 struct usb_tt_clear     *clear;
717                 struct usb_device       *hdev = hub->hdev;
718                 const struct hc_driver  *drv;
719                 int                     status;
720
721                 next = hub->tt.clear_list.next;
722                 clear = list_entry (next, struct usb_tt_clear, clear_list);
723                 list_del (&clear->clear_list);
724
725                 /* drop lock so HCD can concurrently report other TT errors */
726                 spin_unlock_irqrestore (&hub->tt.lock, flags);
727                 status = hub_clear_tt_buffer (hdev, clear->devinfo, clear->tt);
728                 if (status && status != -ENODEV)
729                         dev_err (&hdev->dev,
730                                 "clear tt %d (%04x) error %d\n",
731                                 clear->tt, clear->devinfo, status);
732
733                 /* Tell the HCD, even if the operation failed */
734                 drv = clear->hcd->driver;
735                 if (drv->clear_tt_buffer_complete)
736                         (drv->clear_tt_buffer_complete)(clear->hcd, clear->ep);
737
738                 kfree(clear);
739                 spin_lock_irqsave(&hub->tt.lock, flags);
740         }
741         spin_unlock_irqrestore (&hub->tt.lock, flags);
742 }
743
744 /**
745  * usb_hub_set_port_power - control hub port's power state
746  * @hdev: USB device belonging to the usb hub
747  * @hub: target hub
748  * @port1: port index
749  * @set: expected status
750  *
751  * call this function to control port's power via setting or
752  * clearing the port's PORT_POWER feature.
753  *
754  * Return: 0 if successful. A negative error code otherwise.
755  */
756 int usb_hub_set_port_power(struct usb_device *hdev, struct usb_hub *hub,
757                            int port1, bool set)
758 {
759         int ret;
760
761         if (set)
762                 ret = set_port_feature(hdev, port1, USB_PORT_FEAT_POWER);
763         else
764                 ret = usb_clear_port_feature(hdev, port1, USB_PORT_FEAT_POWER);
765
766         if (ret)
767                 return ret;
768
769         if (set)
770                 set_bit(port1, hub->power_bits);
771         else
772                 clear_bit(port1, hub->power_bits);
773         return 0;
774 }
775
776 /**
777  * usb_hub_clear_tt_buffer - clear control/bulk TT state in high speed hub
778  * @urb: an URB associated with the failed or incomplete split transaction
779  *
780  * High speed HCDs use this to tell the hub driver that some split control or
781  * bulk transaction failed in a way that requires clearing internal state of
782  * a transaction translator.  This is normally detected (and reported) from
783  * interrupt context.
784  *
785  * It may not be possible for that hub to handle additional full (or low)
786  * speed transactions until that state is fully cleared out.
787  *
788  * Return: 0 if successful. A negative error code otherwise.
789  */
790 int usb_hub_clear_tt_buffer(struct urb *urb)
791 {
792         struct usb_device       *udev = urb->dev;
793         int                     pipe = urb->pipe;
794         struct usb_tt           *tt = udev->tt;
795         unsigned long           flags;
796         struct usb_tt_clear     *clear;
797
798         /* we've got to cope with an arbitrary number of pending TT clears,
799          * since each TT has "at least two" buffers that can need it (and
800          * there can be many TTs per hub).  even if they're uncommon.
801          */
802         if ((clear = kmalloc (sizeof *clear, GFP_ATOMIC)) == NULL) {
803                 dev_err (&udev->dev, "can't save CLEAR_TT_BUFFER state\n");
804                 /* FIXME recover somehow ... RESET_TT? */
805                 return -ENOMEM;
806         }
807
808         /* info that CLEAR_TT_BUFFER needs */
809         clear->tt = tt->multi ? udev->ttport : 1;
810         clear->devinfo = usb_pipeendpoint (pipe);
811         clear->devinfo |= udev->devnum << 4;
812         clear->devinfo |= usb_pipecontrol (pipe)
813                         ? (USB_ENDPOINT_XFER_CONTROL << 11)
814                         : (USB_ENDPOINT_XFER_BULK << 11);
815         if (usb_pipein (pipe))
816                 clear->devinfo |= 1 << 15;
817
818         /* info for completion callback */
819         clear->hcd = bus_to_hcd(udev->bus);
820         clear->ep = urb->ep;
821
822         /* tell keventd to clear state for this TT */
823         spin_lock_irqsave (&tt->lock, flags);
824         list_add_tail (&clear->clear_list, &tt->clear_list);
825         schedule_work(&tt->clear_work);
826         spin_unlock_irqrestore (&tt->lock, flags);
827         return 0;
828 }
829 EXPORT_SYMBOL_GPL(usb_hub_clear_tt_buffer);
830
831 static void hub_power_on(struct usb_hub *hub, bool do_delay)
832 {
833         int port1;
834
835         /* Enable power on each port.  Some hubs have reserved values
836          * of LPSM (> 2) in their descriptors, even though they are
837          * USB 2.0 hubs.  Some hubs do not implement port-power switching
838          * but only emulate it.  In all cases, the ports won't work
839          * unless we send these messages to the hub.
840          */
841         if (hub_is_port_power_switchable(hub))
842                 dev_dbg(hub->intfdev, "enabling power on all ports\n");
843         else
844                 dev_dbg(hub->intfdev, "trying to enable port power on "
845                                 "non-switchable hub\n");
846         for (port1 = 1; port1 <= hub->hdev->maxchild; port1++)
847                 if (test_bit(port1, hub->power_bits))
848                         set_port_feature(hub->hdev, port1, USB_PORT_FEAT_POWER);
849                 else
850                         usb_clear_port_feature(hub->hdev, port1,
851                                                 USB_PORT_FEAT_POWER);
852         if (do_delay)
853                 msleep(hub_power_on_good_delay(hub));
854 }
855
856 static int hub_hub_status(struct usb_hub *hub,
857                 u16 *status, u16 *change)
858 {
859         int ret;
860
861         mutex_lock(&hub->status_mutex);
862         ret = get_hub_status(hub->hdev, &hub->status->hub);
863         if (ret < 0) {
864                 if (ret != -ENODEV)
865                         dev_err(hub->intfdev,
866                                 "%s failed (err = %d)\n", __func__, ret);
867         } else {
868                 *status = le16_to_cpu(hub->status->hub.wHubStatus);
869                 *change = le16_to_cpu(hub->status->hub.wHubChange);
870                 ret = 0;
871         }
872         mutex_unlock(&hub->status_mutex);
873         return ret;
874 }
875
876 static int hub_set_port_link_state(struct usb_hub *hub, int port1,
877                         unsigned int link_status)
878 {
879         return set_port_feature(hub->hdev,
880                         port1 | (link_status << 3),
881                         USB_PORT_FEAT_LINK_STATE);
882 }
883
884 /*
885  * If USB 3.0 ports are placed into the Disabled state, they will no longer
886  * detect any device connects or disconnects.  This is generally not what the
887  * USB core wants, since it expects a disabled port to produce a port status
888  * change event when a new device connects.
889  *
890  * Instead, set the link state to Disabled, wait for the link to settle into
891  * that state, clear any change bits, and then put the port into the RxDetect
892  * state.
893  */
894 static int hub_usb3_port_disable(struct usb_hub *hub, int port1)
895 {
896         int ret;
897         int total_time;
898         u16 portchange, portstatus;
899
900         if (!hub_is_superspeed(hub->hdev))
901                 return -EINVAL;
902
903         ret = hub_port_status(hub, port1, &portstatus, &portchange);
904         if (ret < 0)
905                 return ret;
906
907         /*
908          * USB controller Advanced Micro Devices, Inc. [AMD] FCH USB XHCI
909          * Controller [1022:7814] will have spurious result making the following
910          * usb 3.0 device hotplugging route to the 2.0 root hub and recognized
911          * as high-speed device if we set the usb 3.0 port link state to
912          * Disabled. Since it's already in USB_SS_PORT_LS_RX_DETECT state, we
913          * check the state here to avoid the bug.
914          */
915         if ((portstatus & USB_PORT_STAT_LINK_STATE) ==
916                                 USB_SS_PORT_LS_RX_DETECT) {
917                 dev_dbg(&hub->ports[port1 - 1]->dev,
918                          "Not disabling port; link state is RxDetect\n");
919                 return ret;
920         }
921
922         ret = hub_set_port_link_state(hub, port1, USB_SS_PORT_LS_SS_DISABLED);
923         if (ret)
924                 return ret;
925
926         /* Wait for the link to enter the disabled state. */
927         for (total_time = 0; ; total_time += HUB_DEBOUNCE_STEP) {
928                 ret = hub_port_status(hub, port1, &portstatus, &portchange);
929                 if (ret < 0)
930                         return ret;
931
932                 if ((portstatus & USB_PORT_STAT_LINK_STATE) ==
933                                 USB_SS_PORT_LS_SS_DISABLED)
934                         break;
935                 if (total_time >= HUB_DEBOUNCE_TIMEOUT)
936                         break;
937                 msleep(HUB_DEBOUNCE_STEP);
938         }
939         if (total_time >= HUB_DEBOUNCE_TIMEOUT)
940                 dev_warn(&hub->ports[port1 - 1]->dev,
941                                 "Could not disable after %d ms\n", total_time);
942
943         return hub_set_port_link_state(hub, port1, USB_SS_PORT_LS_RX_DETECT);
944 }
945
946 static int hub_port_disable(struct usb_hub *hub, int port1, int set_state)
947 {
948         struct usb_port *port_dev = hub->ports[port1 - 1];
949         struct usb_device *hdev = hub->hdev;
950         int ret = 0;
951
952         if (port_dev->child && set_state)
953                 usb_set_device_state(port_dev->child, USB_STATE_NOTATTACHED);
954         if (!hub->error) {
955                 if (hub_is_superspeed(hub->hdev))
956                         ret = hub_usb3_port_disable(hub, port1);
957                 else
958                         ret = usb_clear_port_feature(hdev, port1,
959                                         USB_PORT_FEAT_ENABLE);
960         }
961         if (ret && ret != -ENODEV)
962                 dev_err(&port_dev->dev, "cannot disable (err = %d)\n", ret);
963         return ret;
964 }
965
966 /*
967  * Disable a port and mark a logical connect-change event, so that some
968  * time later hub_wq will disconnect() any existing usb_device on the port
969  * and will re-enumerate if there actually is a device attached.
970  */
971 static void hub_port_logical_disconnect(struct usb_hub *hub, int port1)
972 {
973         dev_dbg(&hub->ports[port1 - 1]->dev, "logical disconnect\n");
974         hub_port_disable(hub, port1, 1);
975
976         /* FIXME let caller ask to power down the port:
977          *  - some devices won't enumerate without a VBUS power cycle
978          *  - SRP saves power that way
979          *  - ... new call, TBD ...
980          * That's easy if this hub can switch power per-port, and
981          * hub_wq reactivates the port later (timer, SRP, etc).
982          * Powerdown must be optional, because of reset/DFU.
983          */
984
985         set_bit(port1, hub->change_bits);
986         kick_hub_wq(hub);
987 }
988
989 /**
990  * usb_remove_device - disable a device's port on its parent hub
991  * @udev: device to be disabled and removed
992  * Context: @udev locked, must be able to sleep.
993  *
994  * After @udev's port has been disabled, hub_wq is notified and it will
995  * see that the device has been disconnected.  When the device is
996  * physically unplugged and something is plugged in, the events will
997  * be received and processed normally.
998  *
999  * Return: 0 if successful. A negative error code otherwise.
1000  */
1001 int usb_remove_device(struct usb_device *udev)
1002 {
1003         struct usb_hub *hub;
1004         struct usb_interface *intf;
1005
1006         if (!udev->parent)      /* Can't remove a root hub */
1007                 return -EINVAL;
1008         hub = usb_hub_to_struct_hub(udev->parent);
1009         intf = to_usb_interface(hub->intfdev);
1010
1011         usb_autopm_get_interface(intf);
1012         set_bit(udev->portnum, hub->removed_bits);
1013         hub_port_logical_disconnect(hub, udev->portnum);
1014         usb_autopm_put_interface(intf);
1015         return 0;
1016 }
1017
1018 enum hub_activation_type {
1019         HUB_INIT, HUB_INIT2, HUB_INIT3,         /* INITs must come first */
1020         HUB_POST_RESET, HUB_RESUME, HUB_RESET_RESUME,
1021 };
1022
1023 static void hub_init_func2(struct work_struct *ws);
1024 static void hub_init_func3(struct work_struct *ws);
1025
1026 static void hub_activate(struct usb_hub *hub, enum hub_activation_type type)
1027 {
1028         struct usb_device *hdev = hub->hdev;
1029         struct usb_hcd *hcd;
1030         int ret;
1031         int port1;
1032         int status;
1033         bool need_debounce_delay = false;
1034         unsigned delay;
1035
1036         /* Continue a partial initialization */
1037         if (type == HUB_INIT2 || type == HUB_INIT3) {
1038                 device_lock(hub->intfdev);
1039
1040                 /* Was the hub disconnected while we were waiting? */
1041                 if (hub->disconnected) {
1042                         device_unlock(hub->intfdev);
1043                         kref_put(&hub->kref, hub_release);
1044                         return;
1045                 }
1046                 if (type == HUB_INIT2)
1047                         goto init2;
1048                 goto init3;
1049         }
1050         kref_get(&hub->kref);
1051
1052         /* The superspeed hub except for root hub has to use Hub Depth
1053          * value as an offset into the route string to locate the bits
1054          * it uses to determine the downstream port number. So hub driver
1055          * should send a set hub depth request to superspeed hub after
1056          * the superspeed hub is set configuration in initialization or
1057          * reset procedure.
1058          *
1059          * After a resume, port power should still be on.
1060          * For any other type of activation, turn it on.
1061          */
1062         if (type != HUB_RESUME) {
1063                 if (hdev->parent && hub_is_superspeed(hdev)) {
1064                         ret = usb_control_msg(hdev, usb_sndctrlpipe(hdev, 0),
1065                                         HUB_SET_DEPTH, USB_RT_HUB,
1066                                         hdev->level - 1, 0, NULL, 0,
1067                                         USB_CTRL_SET_TIMEOUT);
1068                         if (ret < 0)
1069                                 dev_err(hub->intfdev,
1070                                                 "set hub depth failed\n");
1071                 }
1072
1073                 /* Speed up system boot by using a delayed_work for the
1074                  * hub's initial power-up delays.  This is pretty awkward
1075                  * and the implementation looks like a home-brewed sort of
1076                  * setjmp/longjmp, but it saves at least 100 ms for each
1077                  * root hub (assuming usbcore is compiled into the kernel
1078                  * rather than as a module).  It adds up.
1079                  *
1080                  * This can't be done for HUB_RESUME or HUB_RESET_RESUME
1081                  * because for those activation types the ports have to be
1082                  * operational when we return.  In theory this could be done
1083                  * for HUB_POST_RESET, but it's easier not to.
1084                  */
1085                 if (type == HUB_INIT) {
1086                         unsigned delay = hub_power_on_good_delay(hub);
1087
1088                         hub_power_on(hub, false);
1089                         INIT_DELAYED_WORK(&hub->init_work, hub_init_func2);
1090                         queue_delayed_work(system_power_efficient_wq,
1091                                         &hub->init_work,
1092                                         msecs_to_jiffies(delay));
1093
1094                         /* Suppress autosuspend until init is done */
1095                         usb_autopm_get_interface_no_resume(
1096                                         to_usb_interface(hub->intfdev));
1097                         return;         /* Continues at init2: below */
1098                 } else if (type == HUB_RESET_RESUME) {
1099                         /* The internal host controller state for the hub device
1100                          * may be gone after a host power loss on system resume.
1101                          * Update the device's info so the HW knows it's a hub.
1102                          */
1103                         hcd = bus_to_hcd(hdev->bus);
1104                         if (hcd->driver->update_hub_device) {
1105                                 ret = hcd->driver->update_hub_device(hcd, hdev,
1106                                                 &hub->tt, GFP_NOIO);
1107                                 if (ret < 0) {
1108                                         dev_err(hub->intfdev, "Host not "
1109                                                         "accepting hub info "
1110                                                         "update.\n");
1111                                         dev_err(hub->intfdev, "LS/FS devices "
1112                                                         "and hubs may not work "
1113                                                         "under this hub\n.");
1114                                 }
1115                         }
1116                         hub_power_on(hub, true);
1117                 } else {
1118                         hub_power_on(hub, true);
1119                 }
1120         }
1121  init2:
1122
1123         /*
1124          * Check each port and set hub->change_bits to let hub_wq know
1125          * which ports need attention.
1126          */
1127         for (port1 = 1; port1 <= hdev->maxchild; ++port1) {
1128                 struct usb_port *port_dev = hub->ports[port1 - 1];
1129                 struct usb_device *udev = port_dev->child;
1130                 u16 portstatus, portchange;
1131
1132                 portstatus = portchange = 0;
1133                 status = hub_port_status(hub, port1, &portstatus, &portchange);
1134                 if (udev || (portstatus & USB_PORT_STAT_CONNECTION))
1135                         dev_dbg(&port_dev->dev, "status %04x change %04x\n",
1136                                         portstatus, portchange);
1137
1138                 /*
1139                  * After anything other than HUB_RESUME (i.e., initialization
1140                  * or any sort of reset), every port should be disabled.
1141                  * Unconnected ports should likewise be disabled (paranoia),
1142                  * and so should ports for which we have no usb_device.
1143                  */
1144                 if ((portstatus & USB_PORT_STAT_ENABLE) && (
1145                                 type != HUB_RESUME ||
1146                                 !(portstatus & USB_PORT_STAT_CONNECTION) ||
1147                                 !udev ||
1148                                 udev->state == USB_STATE_NOTATTACHED)) {
1149                         /*
1150                          * USB3 protocol ports will automatically transition
1151                          * to Enabled state when detect an USB3.0 device attach.
1152                          * Do not disable USB3 protocol ports, just pretend
1153                          * power was lost
1154                          */
1155                         portstatus &= ~USB_PORT_STAT_ENABLE;
1156                         if (!hub_is_superspeed(hdev))
1157                                 usb_clear_port_feature(hdev, port1,
1158                                                    USB_PORT_FEAT_ENABLE);
1159                 }
1160
1161                 /* Clear status-change flags; we'll debounce later */
1162                 if (portchange & USB_PORT_STAT_C_CONNECTION) {
1163                         need_debounce_delay = true;
1164                         usb_clear_port_feature(hub->hdev, port1,
1165                                         USB_PORT_FEAT_C_CONNECTION);
1166                 }
1167                 if (portchange & USB_PORT_STAT_C_ENABLE) {
1168                         need_debounce_delay = true;
1169                         usb_clear_port_feature(hub->hdev, port1,
1170                                         USB_PORT_FEAT_C_ENABLE);
1171                 }
1172                 if (portchange & USB_PORT_STAT_C_RESET) {
1173                         need_debounce_delay = true;
1174                         usb_clear_port_feature(hub->hdev, port1,
1175                                         USB_PORT_FEAT_C_RESET);
1176                 }
1177                 if ((portchange & USB_PORT_STAT_C_BH_RESET) &&
1178                                 hub_is_superspeed(hub->hdev)) {
1179                         need_debounce_delay = true;
1180                         usb_clear_port_feature(hub->hdev, port1,
1181                                         USB_PORT_FEAT_C_BH_PORT_RESET);
1182                 }
1183                 /* We can forget about a "removed" device when there's a
1184                  * physical disconnect or the connect status changes.
1185                  */
1186                 if (!(portstatus & USB_PORT_STAT_CONNECTION) ||
1187                                 (portchange & USB_PORT_STAT_C_CONNECTION))
1188                         clear_bit(port1, hub->removed_bits);
1189
1190                 if (!udev || udev->state == USB_STATE_NOTATTACHED) {
1191                         /* Tell hub_wq to disconnect the device or
1192                          * check for a new connection
1193                          */
1194                         if (udev || (portstatus & USB_PORT_STAT_CONNECTION) ||
1195                             (portstatus & USB_PORT_STAT_OVERCURRENT))
1196                                 set_bit(port1, hub->change_bits);
1197
1198                 } else if (portstatus & USB_PORT_STAT_ENABLE) {
1199                         bool port_resumed = (portstatus &
1200                                         USB_PORT_STAT_LINK_STATE) ==
1201                                 USB_SS_PORT_LS_U0;
1202                         /* The power session apparently survived the resume.
1203                          * If there was an overcurrent or suspend change
1204                          * (i.e., remote wakeup request), have hub_wq
1205                          * take care of it.  Look at the port link state
1206                          * for USB 3.0 hubs, since they don't have a suspend
1207                          * change bit, and they don't set the port link change
1208                          * bit on device-initiated resume.
1209                          */
1210                         if (portchange || (hub_is_superspeed(hub->hdev) &&
1211                                                 port_resumed))
1212                                 set_bit(port1, hub->change_bits);
1213
1214                 } else if (udev->persist_enabled) {
1215 #ifdef CONFIG_PM
1216                         udev->reset_resume = 1;
1217 #endif
1218                         /* Don't set the change_bits when the device
1219                          * was powered off.
1220                          */
1221                         if (test_bit(port1, hub->power_bits))
1222                                 set_bit(port1, hub->change_bits);
1223
1224                 } else {
1225                         /* The power session is gone; tell hub_wq */
1226                         usb_set_device_state(udev, USB_STATE_NOTATTACHED);
1227                         set_bit(port1, hub->change_bits);
1228                 }
1229         }
1230
1231         /* If no port-status-change flags were set, we don't need any
1232          * debouncing.  If flags were set we can try to debounce the
1233          * ports all at once right now, instead of letting hub_wq do them
1234          * one at a time later on.
1235          *
1236          * If any port-status changes do occur during this delay, hub_wq
1237          * will see them later and handle them normally.
1238          */
1239         if (need_debounce_delay) {
1240                 delay = HUB_DEBOUNCE_STABLE;
1241
1242                 /* Don't do a long sleep inside a workqueue routine */
1243                 if (type == HUB_INIT2) {
1244                         INIT_DELAYED_WORK(&hub->init_work, hub_init_func3);
1245                         queue_delayed_work(system_power_efficient_wq,
1246                                         &hub->init_work,
1247                                         msecs_to_jiffies(delay));
1248                         device_unlock(hub->intfdev);
1249                         return;         /* Continues at init3: below */
1250                 } else {
1251                         msleep(delay);
1252                 }
1253         }
1254  init3:
1255         hub->quiescing = 0;
1256
1257         status = usb_submit_urb(hub->urb, GFP_NOIO);
1258         if (status < 0)
1259                 dev_err(hub->intfdev, "activate --> %d\n", status);
1260         if (hub->has_indicators && blinkenlights)
1261                 queue_delayed_work(system_power_efficient_wq,
1262                                 &hub->leds, LED_CYCLE_PERIOD);
1263
1264         /* Scan all ports that need attention */
1265         kick_hub_wq(hub);
1266
1267         /* Allow autosuspend if it was suppressed */
1268         if (type <= HUB_INIT3)
1269                 usb_autopm_put_interface_async(to_usb_interface(hub->intfdev));
1270
1271         if (type == HUB_INIT2 || type == HUB_INIT3)
1272                 device_unlock(hub->intfdev);
1273
1274         kref_put(&hub->kref, hub_release);
1275 }
1276
1277 /* Implement the continuations for the delays above */
1278 static void hub_init_func2(struct work_struct *ws)
1279 {
1280         struct usb_hub *hub = container_of(ws, struct usb_hub, init_work.work);
1281
1282         hub_activate(hub, HUB_INIT2);
1283 }
1284
1285 static void hub_init_func3(struct work_struct *ws)
1286 {
1287         struct usb_hub *hub = container_of(ws, struct usb_hub, init_work.work);
1288
1289         hub_activate(hub, HUB_INIT3);
1290 }
1291
1292 enum hub_quiescing_type {
1293         HUB_DISCONNECT, HUB_PRE_RESET, HUB_SUSPEND
1294 };
1295
1296 static void hub_quiesce(struct usb_hub *hub, enum hub_quiescing_type type)
1297 {
1298         struct usb_device *hdev = hub->hdev;
1299         int i;
1300
1301         cancel_delayed_work_sync(&hub->init_work);
1302
1303         /* hub_wq and related activity won't re-trigger */
1304         hub->quiescing = 1;
1305
1306         if (type != HUB_SUSPEND) {
1307                 /* Disconnect all the children */
1308                 for (i = 0; i < hdev->maxchild; ++i) {
1309                         if (hub->ports[i]->child)
1310                                 usb_disconnect(&hub->ports[i]->child);
1311                 }
1312         }
1313
1314         /* Stop hub_wq and related activity */
1315         usb_kill_urb(hub->urb);
1316         if (hub->has_indicators)
1317                 cancel_delayed_work_sync(&hub->leds);
1318         if (hub->tt.hub)
1319                 flush_work(&hub->tt.clear_work);
1320 }
1321
1322 static void hub_pm_barrier_for_all_ports(struct usb_hub *hub)
1323 {
1324         int i;
1325
1326         for (i = 0; i < hub->hdev->maxchild; ++i)
1327                 pm_runtime_barrier(&hub->ports[i]->dev);
1328 }
1329
1330 /* caller has locked the hub device */
1331 static int hub_pre_reset(struct usb_interface *intf)
1332 {
1333         struct usb_hub *hub = usb_get_intfdata(intf);
1334
1335         hub_quiesce(hub, HUB_PRE_RESET);
1336         hub->in_reset = 1;
1337         hub_pm_barrier_for_all_ports(hub);
1338         return 0;
1339 }
1340
1341 /* caller has locked the hub device */
1342 static int hub_post_reset(struct usb_interface *intf)
1343 {
1344         struct usb_hub *hub = usb_get_intfdata(intf);
1345
1346         hub->in_reset = 0;
1347         hub_pm_barrier_for_all_ports(hub);
1348         hub_activate(hub, HUB_POST_RESET);
1349         return 0;
1350 }
1351
1352 static int hub_configure(struct usb_hub *hub,
1353         struct usb_endpoint_descriptor *endpoint)
1354 {
1355         struct usb_hcd *hcd;
1356         struct usb_device *hdev = hub->hdev;
1357         struct device *hub_dev = hub->intfdev;
1358         u16 hubstatus, hubchange;
1359         u16 wHubCharacteristics;
1360         unsigned int pipe;
1361         int maxp, ret, i;
1362         char *message = "out of memory";
1363         unsigned unit_load;
1364         unsigned full_load;
1365         unsigned maxchild;
1366
1367         hub->buffer = kmalloc(sizeof(*hub->buffer), GFP_KERNEL);
1368         if (!hub->buffer) {
1369                 ret = -ENOMEM;
1370                 goto fail;
1371         }
1372
1373         hub->status = kmalloc(sizeof(*hub->status), GFP_KERNEL);
1374         if (!hub->status) {
1375                 ret = -ENOMEM;
1376                 goto fail;
1377         }
1378         mutex_init(&hub->status_mutex);
1379
1380         hub->descriptor = kmalloc(sizeof(*hub->descriptor), GFP_KERNEL);
1381         if (!hub->descriptor) {
1382                 ret = -ENOMEM;
1383                 goto fail;
1384         }
1385
1386         /* Request the entire hub descriptor.
1387          * hub->descriptor can handle USB_MAXCHILDREN ports,
1388          * but the hub can/will return fewer bytes here.
1389          */
1390         ret = get_hub_descriptor(hdev, hub->descriptor);
1391         if (ret < 0) {
1392                 message = "can't read hub descriptor";
1393                 goto fail;
1394         } else if (hub->descriptor->bNbrPorts > USB_MAXCHILDREN) {
1395                 message = "hub has too many ports!";
1396                 ret = -ENODEV;
1397                 goto fail;
1398         } else if (hub->descriptor->bNbrPorts == 0) {
1399                 message = "hub doesn't have any ports!";
1400                 ret = -ENODEV;
1401                 goto fail;
1402         }
1403
1404         maxchild = hub->descriptor->bNbrPorts;
1405         dev_info(hub_dev, "%d port%s detected\n", maxchild,
1406                         (maxchild == 1) ? "" : "s");
1407
1408         hub->ports = kzalloc(maxchild * sizeof(struct usb_port *), GFP_KERNEL);
1409         if (!hub->ports) {
1410                 ret = -ENOMEM;
1411                 goto fail;
1412         }
1413
1414         wHubCharacteristics = le16_to_cpu(hub->descriptor->wHubCharacteristics);
1415         if (hub_is_superspeed(hdev)) {
1416                 unit_load = 150;
1417                 full_load = 900;
1418         } else {
1419                 unit_load = 100;
1420                 full_load = 500;
1421         }
1422
1423         /* FIXME for USB 3.0, skip for now */
1424         if ((wHubCharacteristics & HUB_CHAR_COMPOUND) &&
1425                         !(hub_is_superspeed(hdev))) {
1426                 int     i;
1427                 char    portstr[USB_MAXCHILDREN + 1];
1428
1429                 for (i = 0; i < maxchild; i++)
1430                         portstr[i] = hub->descriptor->u.hs.DeviceRemovable
1431                                     [((i + 1) / 8)] & (1 << ((i + 1) % 8))
1432                                 ? 'F' : 'R';
1433                 portstr[maxchild] = 0;
1434                 dev_dbg(hub_dev, "compound device; port removable status: %s\n", portstr);
1435         } else
1436                 dev_dbg(hub_dev, "standalone hub\n");
1437
1438         switch (wHubCharacteristics & HUB_CHAR_LPSM) {
1439         case HUB_CHAR_COMMON_LPSM:
1440                 dev_dbg(hub_dev, "ganged power switching\n");
1441                 break;
1442         case HUB_CHAR_INDV_PORT_LPSM:
1443                 dev_dbg(hub_dev, "individual port power switching\n");
1444                 break;
1445         case HUB_CHAR_NO_LPSM:
1446         case HUB_CHAR_LPSM:
1447                 dev_dbg(hub_dev, "no power switching (usb 1.0)\n");
1448                 break;
1449         }
1450
1451         switch (wHubCharacteristics & HUB_CHAR_OCPM) {
1452         case HUB_CHAR_COMMON_OCPM:
1453                 dev_dbg(hub_dev, "global over-current protection\n");
1454                 break;
1455         case HUB_CHAR_INDV_PORT_OCPM:
1456                 dev_dbg(hub_dev, "individual port over-current protection\n");
1457                 break;
1458         case HUB_CHAR_NO_OCPM:
1459         case HUB_CHAR_OCPM:
1460                 dev_dbg(hub_dev, "no over-current protection\n");
1461                 break;
1462         }
1463
1464         spin_lock_init (&hub->tt.lock);
1465         INIT_LIST_HEAD (&hub->tt.clear_list);
1466         INIT_WORK(&hub->tt.clear_work, hub_tt_work);
1467         switch (hdev->descriptor.bDeviceProtocol) {
1468         case USB_HUB_PR_FS:
1469                 break;
1470         case USB_HUB_PR_HS_SINGLE_TT:
1471                 dev_dbg(hub_dev, "Single TT\n");
1472                 hub->tt.hub = hdev;
1473                 break;
1474         case USB_HUB_PR_HS_MULTI_TT:
1475                 ret = usb_set_interface(hdev, 0, 1);
1476                 if (ret == 0) {
1477                         dev_dbg(hub_dev, "TT per port\n");
1478                         hub->tt.multi = 1;
1479                 } else
1480                         dev_err(hub_dev, "Using single TT (err %d)\n",
1481                                 ret);
1482                 hub->tt.hub = hdev;
1483                 break;
1484         case USB_HUB_PR_SS:
1485                 /* USB 3.0 hubs don't have a TT */
1486                 break;
1487         default:
1488                 dev_dbg(hub_dev, "Unrecognized hub protocol %d\n",
1489                         hdev->descriptor.bDeviceProtocol);
1490                 break;
1491         }
1492
1493         /* Note 8 FS bit times == (8 bits / 12000000 bps) ~= 666ns */
1494         switch (wHubCharacteristics & HUB_CHAR_TTTT) {
1495         case HUB_TTTT_8_BITS:
1496                 if (hdev->descriptor.bDeviceProtocol != 0) {
1497                         hub->tt.think_time = 666;
1498                         dev_dbg(hub_dev, "TT requires at most %d "
1499                                         "FS bit times (%d ns)\n",
1500                                 8, hub->tt.think_time);
1501                 }
1502                 break;
1503         case HUB_TTTT_16_BITS:
1504                 hub->tt.think_time = 666 * 2;
1505                 dev_dbg(hub_dev, "TT requires at most %d "
1506                                 "FS bit times (%d ns)\n",
1507                         16, hub->tt.think_time);
1508                 break;
1509         case HUB_TTTT_24_BITS:
1510                 hub->tt.think_time = 666 * 3;
1511                 dev_dbg(hub_dev, "TT requires at most %d "
1512                                 "FS bit times (%d ns)\n",
1513                         24, hub->tt.think_time);
1514                 break;
1515         case HUB_TTTT_32_BITS:
1516                 hub->tt.think_time = 666 * 4;
1517                 dev_dbg(hub_dev, "TT requires at most %d "
1518                                 "FS bit times (%d ns)\n",
1519                         32, hub->tt.think_time);
1520                 break;
1521         }
1522
1523         /* probe() zeroes hub->indicator[] */
1524         if (wHubCharacteristics & HUB_CHAR_PORTIND) {
1525                 hub->has_indicators = 1;
1526                 dev_dbg(hub_dev, "Port indicators are supported\n");
1527         }
1528
1529         dev_dbg(hub_dev, "power on to power good time: %dms\n",
1530                 hub->descriptor->bPwrOn2PwrGood * 2);
1531
1532         /* power budgeting mostly matters with bus-powered hubs,
1533          * and battery-powered root hubs (may provide just 8 mA).
1534          */
1535         ret = usb_get_status(hdev, USB_RECIP_DEVICE, 0, &hubstatus);
1536         if (ret) {
1537                 message = "can't get hub status";
1538                 goto fail;
1539         }
1540         hcd = bus_to_hcd(hdev->bus);
1541         if (hdev == hdev->bus->root_hub) {
1542                 if (hcd->power_budget > 0)
1543                         hdev->bus_mA = hcd->power_budget;
1544                 else
1545                         hdev->bus_mA = full_load * maxchild;
1546                 if (hdev->bus_mA >= full_load)
1547                         hub->mA_per_port = full_load;
1548                 else {
1549                         hub->mA_per_port = hdev->bus_mA;
1550                         hub->limited_power = 1;
1551                 }
1552         } else if ((hubstatus & (1 << USB_DEVICE_SELF_POWERED)) == 0) {
1553                 int remaining = hdev->bus_mA -
1554                         hub->descriptor->bHubContrCurrent;
1555
1556                 dev_dbg(hub_dev, "hub controller current requirement: %dmA\n",
1557                         hub->descriptor->bHubContrCurrent);
1558                 hub->limited_power = 1;
1559
1560                 if (remaining < maxchild * unit_load)
1561                         dev_warn(hub_dev,
1562                                         "insufficient power available "
1563                                         "to use all downstream ports\n");
1564                 hub->mA_per_port = unit_load;   /* 7.2.1 */
1565
1566         } else {        /* Self-powered external hub */
1567                 /* FIXME: What about battery-powered external hubs that
1568                  * provide less current per port? */
1569                 hub->mA_per_port = full_load;
1570         }
1571         if (hub->mA_per_port < full_load)
1572                 dev_dbg(hub_dev, "%umA bus power budget for each child\n",
1573                                 hub->mA_per_port);
1574
1575         ret = hub_hub_status(hub, &hubstatus, &hubchange);
1576         if (ret < 0) {
1577                 message = "can't get hub status";
1578                 goto fail;
1579         }
1580
1581         /* local power status reports aren't always correct */
1582         if (hdev->actconfig->desc.bmAttributes & USB_CONFIG_ATT_SELFPOWER)
1583                 dev_dbg(hub_dev, "local power source is %s\n",
1584                         (hubstatus & HUB_STATUS_LOCAL_POWER)
1585                         ? "lost (inactive)" : "good");
1586
1587         if ((wHubCharacteristics & HUB_CHAR_OCPM) == 0)
1588                 dev_dbg(hub_dev, "%sover-current condition exists\n",
1589                         (hubstatus & HUB_STATUS_OVERCURRENT) ? "" : "no ");
1590
1591         /* set up the interrupt endpoint
1592          * We use the EP's maxpacket size instead of (PORTS+1+7)/8
1593          * bytes as USB2.0[11.12.3] says because some hubs are known
1594          * to send more data (and thus cause overflow). For root hubs,
1595          * maxpktsize is defined in hcd.c's fake endpoint descriptors
1596          * to be big enough for at least USB_MAXCHILDREN ports. */
1597         pipe = usb_rcvintpipe(hdev, endpoint->bEndpointAddress);
1598         maxp = usb_maxpacket(hdev, pipe, usb_pipeout(pipe));
1599
1600         if (maxp > sizeof(*hub->buffer))
1601                 maxp = sizeof(*hub->buffer);
1602
1603         hub->urb = usb_alloc_urb(0, GFP_KERNEL);
1604         if (!hub->urb) {
1605                 ret = -ENOMEM;
1606                 goto fail;
1607         }
1608
1609         usb_fill_int_urb(hub->urb, hdev, pipe, *hub->buffer, maxp, hub_irq,
1610                 hub, endpoint->bInterval);
1611
1612         /* maybe cycle the hub leds */
1613         if (hub->has_indicators && blinkenlights)
1614                 hub->indicator[0] = INDICATOR_CYCLE;
1615
1616         mutex_lock(&usb_port_peer_mutex);
1617         for (i = 0; i < maxchild; i++) {
1618                 ret = usb_hub_create_port_device(hub, i + 1);
1619                 if (ret < 0) {
1620                         dev_err(hub->intfdev,
1621                                 "couldn't create port%d device.\n", i + 1);
1622                         break;
1623                 }
1624         }
1625         hdev->maxchild = i;
1626         for (i = 0; i < hdev->maxchild; i++) {
1627                 struct usb_port *port_dev = hub->ports[i];
1628
1629                 pm_runtime_put(&port_dev->dev);
1630         }
1631
1632         mutex_unlock(&usb_port_peer_mutex);
1633         if (ret < 0)
1634                 goto fail;
1635
1636         /* Update the HCD's internal representation of this hub before hub_wq
1637          * starts getting port status changes for devices under the hub.
1638          */
1639         if (hcd->driver->update_hub_device) {
1640                 ret = hcd->driver->update_hub_device(hcd, hdev,
1641                                 &hub->tt, GFP_KERNEL);
1642                 if (ret < 0) {
1643                         message = "can't update HCD hub info";
1644                         goto fail;
1645                 }
1646         }
1647
1648         usb_hub_adjust_deviceremovable(hdev, hub->descriptor);
1649
1650         hub_activate(hub, HUB_INIT);
1651         return 0;
1652
1653 fail:
1654         dev_err (hub_dev, "config failed, %s (err %d)\n",
1655                         message, ret);
1656         /* hub_disconnect() frees urb and descriptor */
1657         return ret;
1658 }
1659
1660 static void hub_release(struct kref *kref)
1661 {
1662         struct usb_hub *hub = container_of(kref, struct usb_hub, kref);
1663
1664         usb_put_dev(hub->hdev);
1665         usb_put_intf(to_usb_interface(hub->intfdev));
1666         kfree(hub);
1667 }
1668
1669 static unsigned highspeed_hubs;
1670
1671 static void hub_disconnect(struct usb_interface *intf)
1672 {
1673         struct usb_hub *hub = usb_get_intfdata(intf);
1674         struct usb_device *hdev = interface_to_usbdev(intf);
1675         int port1;
1676
1677         /*
1678          * Stop adding new hub events. We do not want to block here and thus
1679          * will not try to remove any pending work item.
1680          */
1681         hub->disconnected = 1;
1682
1683         /* Disconnect all children and quiesce the hub */
1684         hub->error = 0;
1685         hub_quiesce(hub, HUB_DISCONNECT);
1686
1687         mutex_lock(&usb_port_peer_mutex);
1688
1689         /* Avoid races with recursively_mark_NOTATTACHED() */
1690         spin_lock_irq(&device_state_lock);
1691         port1 = hdev->maxchild;
1692         hdev->maxchild = 0;
1693         usb_set_intfdata(intf, NULL);
1694         spin_unlock_irq(&device_state_lock);
1695
1696         for (; port1 > 0; --port1)
1697                 usb_hub_remove_port_device(hub, port1);
1698
1699         mutex_unlock(&usb_port_peer_mutex);
1700
1701         if (hub->hdev->speed == USB_SPEED_HIGH)
1702                 highspeed_hubs--;
1703
1704         usb_free_urb(hub->urb);
1705         kfree(hub->ports);
1706         kfree(hub->descriptor);
1707         kfree(hub->status);
1708         kfree(hub->buffer);
1709
1710         pm_suspend_ignore_children(&intf->dev, false);
1711         kref_put(&hub->kref, hub_release);
1712 }
1713
1714 static int hub_probe(struct usb_interface *intf, const struct usb_device_id *id)
1715 {
1716         struct usb_host_interface *desc;
1717         struct usb_endpoint_descriptor *endpoint;
1718         struct usb_device *hdev;
1719         struct usb_hub *hub;
1720
1721         desc = intf->cur_altsetting;
1722         hdev = interface_to_usbdev(intf);
1723
1724         /*
1725          * Set default autosuspend delay as 0 to speedup bus suspend,
1726          * based on the below considerations:
1727          *
1728          * - Unlike other drivers, the hub driver does not rely on the
1729          *   autosuspend delay to provide enough time to handle a wakeup
1730          *   event, and the submitted status URB is just to check future
1731          *   change on hub downstream ports, so it is safe to do it.
1732          *
1733          * - The patch might cause one or more auto supend/resume for
1734          *   below very rare devices when they are plugged into hub
1735          *   first time:
1736          *
1737          *      devices having trouble initializing, and disconnect
1738          *      themselves from the bus and then reconnect a second
1739          *      or so later
1740          *
1741          *      devices just for downloading firmware, and disconnects
1742          *      themselves after completing it
1743          *
1744          *   For these quite rare devices, their drivers may change the
1745          *   autosuspend delay of their parent hub in the probe() to one
1746          *   appropriate value to avoid the subtle problem if someone
1747          *   does care it.
1748          *
1749          * - The patch may cause one or more auto suspend/resume on
1750          *   hub during running 'lsusb', but it is probably too
1751          *   infrequent to worry about.
1752          *
1753          * - Change autosuspend delay of hub can avoid unnecessary auto
1754          *   suspend timer for hub, also may decrease power consumption
1755          *   of USB bus.
1756          *
1757          * - If user has indicated to prevent autosuspend by passing
1758          *   usbcore.autosuspend = -1 then keep autosuspend disabled.
1759          */
1760 #ifdef CONFIG_PM
1761         if (hdev->dev.power.autosuspend_delay >= 0)
1762                 pm_runtime_set_autosuspend_delay(&hdev->dev, 0);
1763 #endif
1764
1765         /*
1766          * Hubs have proper suspend/resume support, except for root hubs
1767          * where the controller driver doesn't have bus_suspend and
1768          * bus_resume methods.
1769          */
1770         if (hdev->parent) {             /* normal device */
1771                 usb_enable_autosuspend(hdev);
1772         } else {                        /* root hub */
1773                 const struct hc_driver *drv = bus_to_hcd(hdev->bus)->driver;
1774
1775                 if (drv->bus_suspend && drv->bus_resume)
1776                         usb_enable_autosuspend(hdev);
1777         }
1778
1779         if (hdev->level == MAX_TOPO_LEVEL) {
1780                 dev_err(&intf->dev,
1781                         "Unsupported bus topology: hub nested too deep\n");
1782                 return -E2BIG;
1783         }
1784
1785 #ifdef  CONFIG_USB_OTG_BLACKLIST_HUB
1786         if (hdev->parent) {
1787                 dev_warn(&intf->dev, "ignoring external hub\n");
1788                 return -ENODEV;
1789         }
1790 #endif
1791
1792         /* Some hubs have a subclass of 1, which AFAICT according to the */
1793         /*  specs is not defined, but it works */
1794         if ((desc->desc.bInterfaceSubClass != 0) &&
1795             (desc->desc.bInterfaceSubClass != 1)) {
1796 descriptor_error:
1797                 dev_err (&intf->dev, "bad descriptor, ignoring hub\n");
1798                 return -EIO;
1799         }
1800
1801         /* Multiple endpoints? What kind of mutant ninja-hub is this? */
1802         if (desc->desc.bNumEndpoints != 1)
1803                 goto descriptor_error;
1804
1805         endpoint = &desc->endpoint[0].desc;
1806
1807         /* If it's not an interrupt in endpoint, we'd better punt! */
1808         if (!usb_endpoint_is_int_in(endpoint))
1809                 goto descriptor_error;
1810
1811         /* We found a hub */
1812         dev_info (&intf->dev, "USB hub found\n");
1813
1814         hub = kzalloc(sizeof(*hub), GFP_KERNEL);
1815         if (!hub) {
1816                 dev_dbg (&intf->dev, "couldn't kmalloc hub struct\n");
1817                 return -ENOMEM;
1818         }
1819
1820         kref_init(&hub->kref);
1821         hub->intfdev = &intf->dev;
1822         hub->hdev = hdev;
1823         INIT_DELAYED_WORK(&hub->leds, led_work);
1824         INIT_DELAYED_WORK(&hub->init_work, NULL);
1825         INIT_WORK(&hub->events, hub_event);
1826         usb_get_intf(intf);
1827         usb_get_dev(hdev);
1828
1829         usb_set_intfdata (intf, hub);
1830         intf->needs_remote_wakeup = 1;
1831         pm_suspend_ignore_children(&intf->dev, true);
1832
1833         if (hdev->speed == USB_SPEED_HIGH)
1834                 highspeed_hubs++;
1835
1836         if (id->driver_info & HUB_QUIRK_CHECK_PORT_AUTOSUSPEND)
1837                 hub->quirk_check_port_auto_suspend = 1;
1838
1839         if (hub_configure(hub, endpoint) >= 0)
1840                 return 0;
1841
1842         hub_disconnect (intf);
1843         return -ENODEV;
1844 }
1845
1846 static int
1847 hub_ioctl(struct usb_interface *intf, unsigned int code, void *user_data)
1848 {
1849         struct usb_device *hdev = interface_to_usbdev (intf);
1850         struct usb_hub *hub = usb_hub_to_struct_hub(hdev);
1851
1852         /* assert ifno == 0 (part of hub spec) */
1853         switch (code) {
1854         case USBDEVFS_HUB_PORTINFO: {
1855                 struct usbdevfs_hub_portinfo *info = user_data;
1856                 int i;
1857
1858                 spin_lock_irq(&device_state_lock);
1859                 if (hdev->devnum <= 0)
1860                         info->nports = 0;
1861                 else {
1862                         info->nports = hdev->maxchild;
1863                         for (i = 0; i < info->nports; i++) {
1864                                 if (hub->ports[i]->child == NULL)
1865                                         info->port[i] = 0;
1866                                 else
1867                                         info->port[i] =
1868                                                 hub->ports[i]->child->devnum;
1869                         }
1870                 }
1871                 spin_unlock_irq(&device_state_lock);
1872
1873                 return info->nports + 1;
1874                 }
1875
1876         default:
1877                 return -ENOSYS;
1878         }
1879 }
1880
1881 /*
1882  * Allow user programs to claim ports on a hub.  When a device is attached
1883  * to one of these "claimed" ports, the program will "own" the device.
1884  */
1885 static int find_port_owner(struct usb_device *hdev, unsigned port1,
1886                 struct usb_dev_state ***ppowner)
1887 {
1888         struct usb_hub *hub = usb_hub_to_struct_hub(hdev);
1889
1890         if (hdev->state == USB_STATE_NOTATTACHED)
1891                 return -ENODEV;
1892         if (port1 == 0 || port1 > hdev->maxchild)
1893                 return -EINVAL;
1894
1895         /* Devices not managed by the hub driver
1896          * will always have maxchild equal to 0.
1897          */
1898         *ppowner = &(hub->ports[port1 - 1]->port_owner);
1899         return 0;
1900 }
1901
1902 /* In the following three functions, the caller must hold hdev's lock */
1903 int usb_hub_claim_port(struct usb_device *hdev, unsigned port1,
1904                        struct usb_dev_state *owner)
1905 {
1906         int rc;
1907         struct usb_dev_state **powner;
1908
1909         rc = find_port_owner(hdev, port1, &powner);
1910         if (rc)
1911                 return rc;
1912         if (*powner)
1913                 return -EBUSY;
1914         *powner = owner;
1915         return rc;
1916 }
1917 EXPORT_SYMBOL_GPL(usb_hub_claim_port);
1918
1919 int usb_hub_release_port(struct usb_device *hdev, unsigned port1,
1920                          struct usb_dev_state *owner)
1921 {
1922         int rc;
1923         struct usb_dev_state **powner;
1924
1925         rc = find_port_owner(hdev, port1, &powner);
1926         if (rc)
1927                 return rc;
1928         if (*powner != owner)
1929                 return -ENOENT;
1930         *powner = NULL;
1931         return rc;
1932 }
1933 EXPORT_SYMBOL_GPL(usb_hub_release_port);
1934
1935 void usb_hub_release_all_ports(struct usb_device *hdev, struct usb_dev_state *owner)
1936 {
1937         struct usb_hub *hub = usb_hub_to_struct_hub(hdev);
1938         int n;
1939
1940         for (n = 0; n < hdev->maxchild; n++) {
1941                 if (hub->ports[n]->port_owner == owner)
1942                         hub->ports[n]->port_owner = NULL;
1943         }
1944
1945 }
1946
1947 /* The caller must hold udev's lock */
1948 bool usb_device_is_owned(struct usb_device *udev)
1949 {
1950         struct usb_hub *hub;
1951
1952         if (udev->state == USB_STATE_NOTATTACHED || !udev->parent)
1953                 return false;
1954         hub = usb_hub_to_struct_hub(udev->parent);
1955         return !!hub->ports[udev->portnum - 1]->port_owner;
1956 }
1957
1958 static void recursively_mark_NOTATTACHED(struct usb_device *udev)
1959 {
1960         struct usb_hub *hub = usb_hub_to_struct_hub(udev);
1961         int i;
1962
1963         for (i = 0; i < udev->maxchild; ++i) {
1964                 if (hub->ports[i]->child)
1965                         recursively_mark_NOTATTACHED(hub->ports[i]->child);
1966         }
1967         if (udev->state == USB_STATE_SUSPENDED)
1968                 udev->active_duration -= jiffies;
1969         udev->state = USB_STATE_NOTATTACHED;
1970 }
1971
1972 /**
1973  * usb_set_device_state - change a device's current state (usbcore, hcds)
1974  * @udev: pointer to device whose state should be changed
1975  * @new_state: new state value to be stored
1976  *
1977  * udev->state is _not_ fully protected by the device lock.  Although
1978  * most transitions are made only while holding the lock, the state can
1979  * can change to USB_STATE_NOTATTACHED at almost any time.  This
1980  * is so that devices can be marked as disconnected as soon as possible,
1981  * without having to wait for any semaphores to be released.  As a result,
1982  * all changes to any device's state must be protected by the
1983  * device_state_lock spinlock.
1984  *
1985  * Once a device has been added to the device tree, all changes to its state
1986  * should be made using this routine.  The state should _not_ be set directly.
1987  *
1988  * If udev->state is already USB_STATE_NOTATTACHED then no change is made.
1989  * Otherwise udev->state is set to new_state, and if new_state is
1990  * USB_STATE_NOTATTACHED then all of udev's descendants' states are also set
1991  * to USB_STATE_NOTATTACHED.
1992  */
1993 void usb_set_device_state(struct usb_device *udev,
1994                 enum usb_device_state new_state)
1995 {
1996         unsigned long flags;
1997         int wakeup = -1;
1998
1999         spin_lock_irqsave(&device_state_lock, flags);
2000         if (udev->state == USB_STATE_NOTATTACHED)
2001                 ;       /* do nothing */
2002         else if (new_state != USB_STATE_NOTATTACHED) {
2003
2004                 /* root hub wakeup capabilities are managed out-of-band
2005                  * and may involve silicon errata ... ignore them here.
2006                  */
2007                 if (udev->parent) {
2008                         if (udev->state == USB_STATE_SUSPENDED
2009                                         || new_state == USB_STATE_SUSPENDED)
2010                                 ;       /* No change to wakeup settings */
2011                         else if (new_state == USB_STATE_CONFIGURED)
2012                                 wakeup = (udev->quirks &
2013                                         USB_QUIRK_IGNORE_REMOTE_WAKEUP) ? 0 :
2014                                         udev->actconfig->desc.bmAttributes &
2015                                         USB_CONFIG_ATT_WAKEUP;
2016                         else
2017                                 wakeup = 0;
2018                 }
2019                 if (udev->state == USB_STATE_SUSPENDED &&
2020                         new_state != USB_STATE_SUSPENDED)
2021                         udev->active_duration -= jiffies;
2022                 else if (new_state == USB_STATE_SUSPENDED &&
2023                                 udev->state != USB_STATE_SUSPENDED)
2024                         udev->active_duration += jiffies;
2025                 udev->state = new_state;
2026         } else
2027                 recursively_mark_NOTATTACHED(udev);
2028         spin_unlock_irqrestore(&device_state_lock, flags);
2029         if (wakeup >= 0)
2030                 device_set_wakeup_capable(&udev->dev, wakeup);
2031 }
2032 EXPORT_SYMBOL_GPL(usb_set_device_state);
2033
2034 /*
2035  * Choose a device number.
2036  *
2037  * Device numbers are used as filenames in usbfs.  On USB-1.1 and
2038  * USB-2.0 buses they are also used as device addresses, however on
2039  * USB-3.0 buses the address is assigned by the controller hardware
2040  * and it usually is not the same as the device number.
2041  *
2042  * WUSB devices are simple: they have no hubs behind, so the mapping
2043  * device <-> virtual port number becomes 1:1. Why? to simplify the
2044  * life of the device connection logic in
2045  * drivers/usb/wusbcore/devconnect.c. When we do the initial secret
2046  * handshake we need to assign a temporary address in the unauthorized
2047  * space. For simplicity we use the first virtual port number found to
2048  * be free [drivers/usb/wusbcore/devconnect.c:wusbhc_devconnect_ack()]
2049  * and that becomes it's address [X < 128] or its unauthorized address
2050  * [X | 0x80].
2051  *
2052  * We add 1 as an offset to the one-based USB-stack port number
2053  * (zero-based wusb virtual port index) for two reasons: (a) dev addr
2054  * 0 is reserved by USB for default address; (b) Linux's USB stack
2055  * uses always #1 for the root hub of the controller. So USB stack's
2056  * port #1, which is wusb virtual-port #0 has address #2.
2057  *
2058  * Devices connected under xHCI are not as simple.  The host controller
2059  * supports virtualization, so the hardware assigns device addresses and
2060  * the HCD must setup data structures before issuing a set address
2061  * command to the hardware.
2062  */
2063 static void choose_devnum(struct usb_device *udev)
2064 {
2065         int             devnum;
2066         struct usb_bus  *bus = udev->bus;
2067
2068         /* be safe when more hub events are proceed in parallel */
2069         mutex_lock(&bus->usb_address0_mutex);
2070         if (udev->wusb) {
2071                 devnum = udev->portnum + 1;
2072                 BUG_ON(test_bit(devnum, bus->devmap.devicemap));
2073         } else {
2074                 /* Try to allocate the next devnum beginning at
2075                  * bus->devnum_next. */
2076                 devnum = find_next_zero_bit(bus->devmap.devicemap, 128,
2077                                             bus->devnum_next);
2078                 if (devnum >= 128)
2079                         devnum = find_next_zero_bit(bus->devmap.devicemap,
2080                                                     128, 1);
2081                 bus->devnum_next = (devnum >= 127 ? 1 : devnum + 1);
2082         }
2083         if (devnum < 128) {
2084                 set_bit(devnum, bus->devmap.devicemap);
2085                 udev->devnum = devnum;
2086         }
2087         mutex_unlock(&bus->usb_address0_mutex);
2088 }
2089
2090 static void release_devnum(struct usb_device *udev)
2091 {
2092         if (udev->devnum > 0) {
2093                 clear_bit(udev->devnum, udev->bus->devmap.devicemap);
2094                 udev->devnum = -1;
2095         }
2096 }
2097
2098 static void update_devnum(struct usb_device *udev, int devnum)
2099 {
2100         /* The address for a WUSB device is managed by wusbcore. */
2101         if (!udev->wusb)
2102                 udev->devnum = devnum;
2103 }
2104
2105 static void hub_free_dev(struct usb_device *udev)
2106 {
2107         struct usb_hcd *hcd = bus_to_hcd(udev->bus);
2108
2109         /* Root hubs aren't real devices, so don't free HCD resources */
2110         if (hcd->driver->free_dev && udev->parent)
2111                 hcd->driver->free_dev(hcd, udev);
2112 }
2113
2114 static void hub_disconnect_children(struct usb_device *udev)
2115 {
2116         struct usb_hub *hub = usb_hub_to_struct_hub(udev);
2117         int i;
2118
2119         /* Free up all the children before we remove this device */
2120         for (i = 0; i < udev->maxchild; i++) {
2121                 if (hub->ports[i]->child)
2122                         usb_disconnect(&hub->ports[i]->child);
2123         }
2124 }
2125
2126 /**
2127  * usb_disconnect - disconnect a device (usbcore-internal)
2128  * @pdev: pointer to device being disconnected
2129  * Context: !in_interrupt ()
2130  *
2131  * Something got disconnected. Get rid of it and all of its children.
2132  *
2133  * If *pdev is a normal device then the parent hub must already be locked.
2134  * If *pdev is a root hub then the caller must hold the usb_bus_list_lock,
2135  * which protects the set of root hubs as well as the list of buses.
2136  *
2137  * Only hub drivers (including virtual root hub drivers for host
2138  * controllers) should ever call this.
2139  *
2140  * This call is synchronous, and may not be used in an interrupt context.
2141  */
2142 void usb_disconnect(struct usb_device **pdev)
2143 {
2144         struct usb_port *port_dev = NULL;
2145         struct usb_device *udev = *pdev;
2146         struct usb_hub *hub = NULL;
2147         int port1 = 1;
2148
2149         /* mark the device as inactive, so any further urb submissions for
2150          * this device (and any of its children) will fail immediately.
2151          * this quiesces everything except pending urbs.
2152          */
2153         usb_set_device_state(udev, USB_STATE_NOTATTACHED);
2154         dev_info(&udev->dev, "USB disconnect, device number %d\n",
2155                         udev->devnum);
2156
2157         usb_lock_device(udev);
2158
2159         hub_disconnect_children(udev);
2160
2161         /* deallocate hcd/hardware state ... nuking all pending urbs and
2162          * cleaning up all state associated with the current configuration
2163          * so that the hardware is now fully quiesced.
2164          */
2165         dev_dbg (&udev->dev, "unregistering device\n");
2166         usb_disable_device(udev, 0);
2167         usb_hcd_synchronize_unlinks(udev);
2168
2169         if (udev->parent) {
2170                 port1 = udev->portnum;
2171                 hub = usb_hub_to_struct_hub(udev->parent);
2172                 port_dev = hub->ports[port1 - 1];
2173
2174                 sysfs_remove_link(&udev->dev.kobj, "port");
2175                 sysfs_remove_link(&port_dev->dev.kobj, "device");
2176
2177                 /*
2178                  * As usb_port_runtime_resume() de-references udev, make
2179                  * sure no resumes occur during removal
2180                  */
2181                 if (!test_and_set_bit(port1, hub->child_usage_bits))
2182                         pm_runtime_get_sync(&port_dev->dev);
2183         }
2184
2185         usb_remove_ep_devs(&udev->ep0);
2186         usb_unlock_device(udev);
2187
2188         /* Unregister the device.  The device driver is responsible
2189          * for de-configuring the device and invoking the remove-device
2190          * notifier chain (used by usbfs and possibly others).
2191          */
2192         device_del(&udev->dev);
2193
2194         /* Free the device number and delete the parent's children[]
2195          * (or root_hub) pointer.
2196          */
2197         release_devnum(udev);
2198
2199         /* Avoid races with recursively_mark_NOTATTACHED() */
2200         spin_lock_irq(&device_state_lock);
2201         *pdev = NULL;
2202         spin_unlock_irq(&device_state_lock);
2203
2204         if (port_dev && test_and_clear_bit(port1, hub->child_usage_bits))
2205                 pm_runtime_put(&port_dev->dev);
2206
2207         hub_free_dev(udev);
2208
2209         put_device(&udev->dev);
2210 }
2211
2212 #ifdef CONFIG_USB_ANNOUNCE_NEW_DEVICES
2213 static void show_string(struct usb_device *udev, char *id, char *string)
2214 {
2215         if (!string)
2216                 return;
2217         dev_info(&udev->dev, "%s: %s\n", id, string);
2218 }
2219
2220 static void announce_device(struct usb_device *udev)
2221 {
2222         dev_info(&udev->dev, "New USB device found, idVendor=%04x, idProduct=%04x\n",
2223                 le16_to_cpu(udev->descriptor.idVendor),
2224                 le16_to_cpu(udev->descriptor.idProduct));
2225         dev_info(&udev->dev,
2226                 "New USB device strings: Mfr=%d, Product=%d, SerialNumber=%d\n",
2227                 udev->descriptor.iManufacturer,
2228                 udev->descriptor.iProduct,
2229                 udev->descriptor.iSerialNumber);
2230         show_string(udev, "Product", udev->product);
2231         show_string(udev, "Manufacturer", udev->manufacturer);
2232         show_string(udev, "SerialNumber", udev->serial);
2233 }
2234 #else
2235 static inline void announce_device(struct usb_device *udev) { }
2236 #endif
2237
2238
2239 /**
2240  * usb_enumerate_device_otg - FIXME (usbcore-internal)
2241  * @udev: newly addressed device (in ADDRESS state)
2242  *
2243  * Finish enumeration for On-The-Go devices
2244  *
2245  * Return: 0 if successful. A negative error code otherwise.
2246  */
2247 static int usb_enumerate_device_otg(struct usb_device *udev)
2248 {
2249         int err = 0;
2250
2251 #ifdef  CONFIG_USB_OTG
2252         /*
2253          * OTG-aware devices on OTG-capable root hubs may be able to use SRP,
2254          * to wake us after we've powered off VBUS; and HNP, switching roles
2255          * "host" to "peripheral".  The OTG descriptor helps figure this out.
2256          */
2257         if (!udev->bus->is_b_host
2258                         && udev->config
2259                         && udev->parent == udev->bus->root_hub) {
2260                 struct usb_otg_descriptor       *desc = NULL;
2261                 struct usb_bus                  *bus = udev->bus;
2262
2263                 /* descriptor may appear anywhere in config */
2264                 if (__usb_get_extra_descriptor (udev->rawdescriptors[0],
2265                                         le16_to_cpu(udev->config[0].desc.wTotalLength),
2266                                         USB_DT_OTG, (void **) &desc) == 0) {
2267                         if (desc->bmAttributes & USB_OTG_HNP) {
2268                                 unsigned                port1 = udev->portnum;
2269
2270                                 dev_info(&udev->dev,
2271                                         "Dual-Role OTG device on %sHNP port\n",
2272                                         (port1 == bus->otg_port)
2273                                                 ? "" : "non-");
2274
2275                                 /* enable HNP before suspend, it's simpler */
2276                                 if (port1 == bus->otg_port)
2277                                         bus->b_hnp_enable = 1;
2278                                 err = usb_control_msg(udev,
2279                                         usb_sndctrlpipe(udev, 0),
2280                                         USB_REQ_SET_FEATURE, 0,
2281                                         bus->b_hnp_enable
2282                                                 ? USB_DEVICE_B_HNP_ENABLE
2283                                                 : USB_DEVICE_A_ALT_HNP_SUPPORT,
2284                                         0, NULL, 0, USB_CTRL_SET_TIMEOUT);
2285                                 if (err < 0) {
2286                                         /* OTG MESSAGE: report errors here,
2287                                          * customize to match your product.
2288                                          */
2289                                         dev_info(&udev->dev,
2290                                                 "can't set HNP mode: %d\n",
2291                                                 err);
2292                                         bus->b_hnp_enable = 0;
2293                                 }
2294                         }
2295                 }
2296         }
2297 #endif
2298         return err;
2299 }
2300
2301
2302 /**
2303  * usb_enumerate_device - Read device configs/intfs/otg (usbcore-internal)
2304  * @udev: newly addressed device (in ADDRESS state)
2305  *
2306  * This is only called by usb_new_device() and usb_authorize_device()
2307  * and FIXME -- all comments that apply to them apply here wrt to
2308  * environment.
2309  *
2310  * If the device is WUSB and not authorized, we don't attempt to read
2311  * the string descriptors, as they will be errored out by the device
2312  * until it has been authorized.
2313  *
2314  * Return: 0 if successful. A negative error code otherwise.
2315  */
2316 static int usb_enumerate_device(struct usb_device *udev)
2317 {
2318         int err;
2319         struct usb_hcd *hcd = bus_to_hcd(udev->bus);
2320
2321         if (udev->config == NULL) {
2322                 err = usb_get_configuration(udev);
2323                 if (err < 0) {
2324                         if (err != -ENODEV)
2325                                 dev_err(&udev->dev, "can't read configurations, error %d\n",
2326                                                 err);
2327                         return err;
2328                 }
2329         }
2330
2331         /* read the standard strings and cache them if present */
2332         udev->product = usb_cache_string(udev, udev->descriptor.iProduct);
2333         udev->manufacturer = usb_cache_string(udev,
2334                                               udev->descriptor.iManufacturer);
2335         udev->serial = usb_cache_string(udev, udev->descriptor.iSerialNumber);
2336
2337         err = usb_enumerate_device_otg(udev);
2338         if (err < 0)
2339                 return err;
2340
2341         if (IS_ENABLED(CONFIG_USB_OTG_WHITELIST) && hcd->tpl_support &&
2342                 !is_targeted(udev)) {
2343                 /* Maybe it can talk to us, though we can't talk to it.
2344                  * (Includes HNP test device.)
2345                  */
2346                 if (IS_ENABLED(CONFIG_USB_OTG) && (udev->bus->b_hnp_enable
2347                         || udev->bus->is_b_host)) {
2348                         err = usb_port_suspend(udev, PMSG_AUTO_SUSPEND);
2349                         if (err < 0)
2350                                 dev_dbg(&udev->dev, "HNP fail, %d\n", err);
2351                 }
2352                 return -ENOTSUPP;
2353         }
2354
2355         usb_detect_interface_quirks(udev);
2356
2357         return 0;
2358 }
2359
2360 static void set_usb_port_removable(struct usb_device *udev)
2361 {
2362         struct usb_device *hdev = udev->parent;
2363         struct usb_hub *hub;
2364         u8 port = udev->portnum;
2365         u16 wHubCharacteristics;
2366         bool removable = true;
2367
2368         if (!hdev)
2369                 return;
2370
2371         hub = usb_hub_to_struct_hub(udev->parent);
2372
2373         wHubCharacteristics = le16_to_cpu(hub->descriptor->wHubCharacteristics);
2374
2375         if (!(wHubCharacteristics & HUB_CHAR_COMPOUND))
2376                 return;
2377
2378         if (hub_is_superspeed(hdev)) {
2379                 if (le16_to_cpu(hub->descriptor->u.ss.DeviceRemovable)
2380                                 & (1 << port))
2381                         removable = false;
2382         } else {
2383                 if (hub->descriptor->u.hs.DeviceRemovable[port / 8] & (1 << (port % 8)))
2384                         removable = false;
2385         }
2386
2387         if (removable)
2388                 udev->removable = USB_DEVICE_REMOVABLE;
2389         else
2390                 udev->removable = USB_DEVICE_FIXED;
2391
2392         /*
2393          * Platform firmware may have populated an alternative value for
2394          * removable.  If the parent port has a known connect_type use
2395          * that instead.
2396          */
2397         switch (hub->ports[udev->portnum - 1]->connect_type) {
2398         case USB_PORT_CONNECT_TYPE_HOT_PLUG:
2399                 udev->removable = USB_DEVICE_REMOVABLE;
2400                 break;
2401         case USB_PORT_CONNECT_TYPE_HARD_WIRED:
2402                 udev->removable = USB_DEVICE_FIXED;
2403                 break;
2404         default: /* use what was set above */
2405                 break;
2406         }
2407 }
2408
2409 /**
2410  * usb_new_device - perform initial device setup (usbcore-internal)
2411  * @udev: newly addressed device (in ADDRESS state)
2412  *
2413  * This is called with devices which have been detected but not fully
2414  * enumerated.  The device descriptor is available, but not descriptors
2415  * for any device configuration.  The caller must have locked either
2416  * the parent hub (if udev is a normal device) or else the
2417  * usb_bus_list_lock (if udev is a root hub).  The parent's pointer to
2418  * udev has already been installed, but udev is not yet visible through
2419  * sysfs or other filesystem code.
2420  *
2421  * This call is synchronous, and may not be used in an interrupt context.
2422  *
2423  * Only the hub driver or root-hub registrar should ever call this.
2424  *
2425  * Return: Whether the device is configured properly or not. Zero if the
2426  * interface was registered with the driver core; else a negative errno
2427  * value.
2428  *
2429  */
2430 int usb_new_device(struct usb_device *udev)
2431 {
2432         int err;
2433
2434         if (udev->parent) {
2435                 /* Initialize non-root-hub device wakeup to disabled;
2436                  * device (un)configuration controls wakeup capable
2437                  * sysfs power/wakeup controls wakeup enabled/disabled
2438                  */
2439                 device_init_wakeup(&udev->dev, 0);
2440         }
2441
2442         /* Tell the runtime-PM framework the device is active */
2443         pm_runtime_set_active(&udev->dev);
2444         pm_runtime_get_noresume(&udev->dev);
2445         pm_runtime_use_autosuspend(&udev->dev);
2446         pm_runtime_enable(&udev->dev);
2447
2448         /* By default, forbid autosuspend for all devices.  It will be
2449          * allowed for hubs during binding.
2450          */
2451         usb_disable_autosuspend(udev);
2452
2453         err = usb_enumerate_device(udev);       /* Read descriptors */
2454         if (err < 0)
2455                 goto fail;
2456         dev_dbg(&udev->dev, "udev %d, busnum %d, minor = %d\n",
2457                         udev->devnum, udev->bus->busnum,
2458                         (((udev->bus->busnum-1) * 128) + (udev->devnum-1)));
2459         /* export the usbdev device-node for libusb */
2460         udev->dev.devt = MKDEV(USB_DEVICE_MAJOR,
2461                         (((udev->bus->busnum-1) * 128) + (udev->devnum-1)));
2462
2463         /* Tell the world! */
2464         announce_device(udev);
2465
2466         if (udev->serial)
2467                 add_device_randomness(udev->serial, strlen(udev->serial));
2468         if (udev->product)
2469                 add_device_randomness(udev->product, strlen(udev->product));
2470         if (udev->manufacturer)
2471                 add_device_randomness(udev->manufacturer,
2472                                       strlen(udev->manufacturer));
2473
2474         device_enable_async_suspend(&udev->dev);
2475
2476         /* check whether the hub or firmware marks this port as non-removable */
2477         if (udev->parent)
2478                 set_usb_port_removable(udev);
2479
2480         /* Register the device.  The device driver is responsible
2481          * for configuring the device and invoking the add-device
2482          * notifier chain (used by usbfs and possibly others).
2483          */
2484         err = device_add(&udev->dev);
2485         if (err) {
2486                 dev_err(&udev->dev, "can't device_add, error %d\n", err);
2487                 goto fail;
2488         }
2489
2490         /* Create link files between child device and usb port device. */
2491         if (udev->parent) {
2492                 struct usb_hub *hub = usb_hub_to_struct_hub(udev->parent);
2493                 int port1 = udev->portnum;
2494                 struct usb_port *port_dev = hub->ports[port1 - 1];
2495
2496                 err = sysfs_create_link(&udev->dev.kobj,
2497                                 &port_dev->dev.kobj, "port");
2498                 if (err)
2499                         goto fail;
2500
2501                 err = sysfs_create_link(&port_dev->dev.kobj,
2502                                 &udev->dev.kobj, "device");
2503                 if (err) {
2504                         sysfs_remove_link(&udev->dev.kobj, "port");
2505                         goto fail;
2506                 }
2507
2508                 if (!test_and_set_bit(port1, hub->child_usage_bits))
2509                         pm_runtime_get_sync(&port_dev->dev);
2510         }
2511
2512         (void) usb_create_ep_devs(&udev->dev, &udev->ep0, udev);
2513         usb_mark_last_busy(udev);
2514         pm_runtime_put_sync_autosuspend(&udev->dev);
2515         return err;
2516
2517 fail:
2518         usb_set_device_state(udev, USB_STATE_NOTATTACHED);
2519         pm_runtime_disable(&udev->dev);
2520         pm_runtime_set_suspended(&udev->dev);
2521         return err;
2522 }
2523
2524
2525 /**
2526  * usb_deauthorize_device - deauthorize a device (usbcore-internal)
2527  * @usb_dev: USB device
2528  *
2529  * Move the USB device to a very basic state where interfaces are disabled
2530  * and the device is in fact unconfigured and unusable.
2531  *
2532  * We share a lock (that we have) with device_del(), so we need to
2533  * defer its call.
2534  *
2535  * Return: 0.
2536  */
2537 int usb_deauthorize_device(struct usb_device *usb_dev)
2538 {
2539         usb_lock_device(usb_dev);
2540         if (usb_dev->authorized == 0)
2541                 goto out_unauthorized;
2542
2543         usb_dev->authorized = 0;
2544         usb_set_configuration(usb_dev, -1);
2545
2546 out_unauthorized:
2547         usb_unlock_device(usb_dev);
2548         return 0;
2549 }
2550
2551
2552 int usb_authorize_device(struct usb_device *usb_dev)
2553 {
2554         int result = 0, c;
2555
2556         usb_lock_device(usb_dev);
2557         if (usb_dev->authorized == 1)
2558                 goto out_authorized;
2559
2560         result = usb_autoresume_device(usb_dev);
2561         if (result < 0) {
2562                 dev_err(&usb_dev->dev,
2563                         "can't autoresume for authorization: %d\n", result);
2564                 goto error_autoresume;
2565         }
2566
2567         if (usb_dev->wusb) {
2568                 result = usb_get_device_descriptor(usb_dev, sizeof(usb_dev->descriptor));
2569                 if (result < 0) {
2570                         dev_err(&usb_dev->dev, "can't re-read device descriptor for "
2571                                 "authorization: %d\n", result);
2572                         goto error_device_descriptor;
2573                 }
2574         }
2575
2576         usb_dev->authorized = 1;
2577         /* Choose and set the configuration.  This registers the interfaces
2578          * with the driver core and lets interface drivers bind to them.
2579          */
2580         c = usb_choose_configuration(usb_dev);
2581         if (c >= 0) {
2582                 result = usb_set_configuration(usb_dev, c);
2583                 if (result) {
2584                         dev_err(&usb_dev->dev,
2585                                 "can't set config #%d, error %d\n", c, result);
2586                         /* This need not be fatal.  The user can try to
2587                          * set other configurations. */
2588                 }
2589         }
2590         dev_info(&usb_dev->dev, "authorized to connect\n");
2591
2592 error_device_descriptor:
2593         usb_autosuspend_device(usb_dev);
2594 error_autoresume:
2595 out_authorized:
2596         usb_unlock_device(usb_dev);     /* complements locktree */
2597         return result;
2598 }
2599
2600
2601 /* Returns 1 if @hub is a WUSB root hub, 0 otherwise */
2602 static unsigned hub_is_wusb(struct usb_hub *hub)
2603 {
2604         struct usb_hcd *hcd;
2605         if (hub->hdev->parent != NULL)  /* not a root hub? */
2606                 return 0;
2607         hcd = container_of(hub->hdev->bus, struct usb_hcd, self);
2608         return hcd->wireless;
2609 }
2610
2611
2612 #define PORT_RESET_TRIES        5
2613 #define SET_ADDRESS_TRIES       2
2614 #define GET_DESCRIPTOR_TRIES    2
2615 #define SET_CONFIG_TRIES        (2 * (use_both_schemes + 1))
2616 #define USE_NEW_SCHEME(i)       ((i) / 2 == (int)old_scheme_first)
2617
2618 #define HUB_ROOT_RESET_TIME     50      /* times are in msec */
2619 #define HUB_SHORT_RESET_TIME    10
2620 #define HUB_BH_RESET_TIME       50
2621 #define HUB_LONG_RESET_TIME     200
2622 #define HUB_RESET_TIMEOUT       800
2623
2624 /*
2625  * "New scheme" enumeration causes an extra state transition to be
2626  * exposed to an xhci host and causes USB3 devices to receive control
2627  * commands in the default state.  This has been seen to cause
2628  * enumeration failures, so disable this enumeration scheme for USB3
2629  * devices.
2630  */
2631 static bool use_new_scheme(struct usb_device *udev, int retry)
2632 {
2633         if (udev->speed == USB_SPEED_SUPER)
2634                 return false;
2635
2636         return USE_NEW_SCHEME(retry);
2637 }
2638
2639 /* Is a USB 3.0 port in the Inactive or Compliance Mode state?
2640  * Port worm reset is required to recover
2641  */
2642 static bool hub_port_warm_reset_required(struct usb_hub *hub, int port1,
2643                 u16 portstatus)
2644 {
2645         u16 link_state;
2646
2647         if (!hub_is_superspeed(hub->hdev))
2648                 return false;
2649
2650         if (test_bit(port1, hub->warm_reset_bits))
2651                 return true;
2652
2653         link_state = portstatus & USB_PORT_STAT_LINK_STATE;
2654         return link_state == USB_SS_PORT_LS_SS_INACTIVE
2655                 || link_state == USB_SS_PORT_LS_COMP_MOD;
2656 }
2657
2658 static int hub_port_wait_reset(struct usb_hub *hub, int port1,
2659                         struct usb_device *udev, unsigned int delay, bool warm)
2660 {
2661         int delay_time, ret;
2662         u16 portstatus;
2663         u16 portchange;
2664
2665         for (delay_time = 0;
2666                         delay_time < HUB_RESET_TIMEOUT;
2667                         delay_time += delay) {
2668                 /* wait to give the device a chance to reset */
2669                 msleep(delay);
2670
2671                 /* read and decode port status */
2672                 ret = hub_port_status(hub, port1, &portstatus, &portchange);
2673                 if (ret < 0)
2674                         return ret;
2675
2676                 /* The port state is unknown until the reset completes. */
2677                 if (!(portstatus & USB_PORT_STAT_RESET))
2678                         break;
2679
2680                 /* switch to the long delay after two short delay failures */
2681                 if (delay_time >= 2 * HUB_SHORT_RESET_TIME)
2682                         delay = HUB_LONG_RESET_TIME;
2683
2684                 dev_dbg(&hub->ports[port1 - 1]->dev,
2685                                 "not %sreset yet, waiting %dms\n",
2686                                 warm ? "warm " : "", delay);
2687         }
2688
2689         if ((portstatus & USB_PORT_STAT_RESET))
2690                 return -EBUSY;
2691
2692         if (hub_port_warm_reset_required(hub, port1, portstatus))
2693                 return -ENOTCONN;
2694
2695         /* Device went away? */
2696         if (!(portstatus & USB_PORT_STAT_CONNECTION))
2697                 return -ENOTCONN;
2698
2699         /* bomb out completely if the connection bounced.  A USB 3.0
2700          * connection may bounce if multiple warm resets were issued,
2701          * but the device may have successfully re-connected. Ignore it.
2702          */
2703         if (!hub_is_superspeed(hub->hdev) &&
2704                         (portchange & USB_PORT_STAT_C_CONNECTION))
2705                 return -ENOTCONN;
2706
2707         if (!(portstatus & USB_PORT_STAT_ENABLE))
2708                 return -EBUSY;
2709
2710         if (!udev)
2711                 return 0;
2712
2713         if (hub_is_wusb(hub))
2714                 udev->speed = USB_SPEED_WIRELESS;
2715         else if (hub_is_superspeed(hub->hdev))
2716                 udev->speed = USB_SPEED_SUPER;
2717         else if (portstatus & USB_PORT_STAT_HIGH_SPEED)
2718                 udev->speed = USB_SPEED_HIGH;
2719         else if (portstatus & USB_PORT_STAT_LOW_SPEED)
2720                 udev->speed = USB_SPEED_LOW;
2721         else
2722                 udev->speed = USB_SPEED_FULL;
2723         return 0;
2724 }
2725
2726 /* Handle port reset and port warm(BH) reset (for USB3 protocol ports) */
2727 static int hub_port_reset(struct usb_hub *hub, int port1,
2728                         struct usb_device *udev, unsigned int delay, bool warm)
2729 {
2730         int i, status;
2731         u16 portchange, portstatus;
2732         struct usb_port *port_dev = hub->ports[port1 - 1];
2733
2734         if (!hub_is_superspeed(hub->hdev)) {
2735                 if (warm) {
2736                         dev_err(hub->intfdev, "only USB3 hub support "
2737                                                 "warm reset\n");
2738                         return -EINVAL;
2739                 }
2740                 /* Block EHCI CF initialization during the port reset.
2741                  * Some companion controllers don't like it when they mix.
2742                  */
2743                 down_read(&ehci_cf_port_reset_rwsem);
2744         } else if (!warm) {
2745                 /*
2746                  * If the caller hasn't explicitly requested a warm reset,
2747                  * double check and see if one is needed.
2748                  */
2749                 if (hub_port_status(hub, port1, &portstatus, &portchange) == 0)
2750                         if (hub_port_warm_reset_required(hub, port1,
2751                                                         portstatus))
2752                                 warm = true;
2753         }
2754         clear_bit(port1, hub->warm_reset_bits);
2755
2756         /* Reset the port */
2757         for (i = 0; i < PORT_RESET_TRIES; i++) {
2758                 status = set_port_feature(hub->hdev, port1, (warm ?
2759                                         USB_PORT_FEAT_BH_PORT_RESET :
2760                                         USB_PORT_FEAT_RESET));
2761                 if (status == -ENODEV) {
2762                         ;       /* The hub is gone */
2763                 } else if (status) {
2764                         dev_err(&port_dev->dev,
2765                                         "cannot %sreset (err = %d)\n",
2766                                         warm ? "warm " : "", status);
2767                 } else {
2768                         status = hub_port_wait_reset(hub, port1, udev, delay,
2769                                                                 warm);
2770                         if (status && status != -ENOTCONN && status != -ENODEV)
2771                                 dev_dbg(hub->intfdev,
2772                                                 "port_wait_reset: err = %d\n",
2773                                                 status);
2774                 }
2775
2776                 /* Check for disconnect or reset */
2777                 if (status == 0 || status == -ENOTCONN || status == -ENODEV) {
2778                         usb_clear_port_feature(hub->hdev, port1,
2779                                         USB_PORT_FEAT_C_RESET);
2780
2781                         if (!hub_is_superspeed(hub->hdev))
2782                                 goto done;
2783
2784                         usb_clear_port_feature(hub->hdev, port1,
2785                                         USB_PORT_FEAT_C_BH_PORT_RESET);
2786                         usb_clear_port_feature(hub->hdev, port1,
2787                                         USB_PORT_FEAT_C_PORT_LINK_STATE);
2788                         usb_clear_port_feature(hub->hdev, port1,
2789                                         USB_PORT_FEAT_C_CONNECTION);
2790
2791                         /*
2792                          * If a USB 3.0 device migrates from reset to an error
2793                          * state, re-issue the warm reset.
2794                          */
2795                         if (hub_port_status(hub, port1,
2796                                         &portstatus, &portchange) < 0)
2797                                 goto done;
2798
2799                         if (!hub_port_warm_reset_required(hub, port1,
2800                                         portstatus))
2801                                 goto done;
2802
2803                         /*
2804                          * If the port is in SS.Inactive or Compliance Mode, the
2805                          * hot or warm reset failed.  Try another warm reset.
2806                          */
2807                         if (!warm) {
2808                                 dev_dbg(&port_dev->dev,
2809                                                 "hot reset failed, warm reset\n");
2810                                 warm = true;
2811                         }
2812                 }
2813
2814                 dev_dbg(&port_dev->dev,
2815                                 "not enabled, trying %sreset again...\n",
2816                                 warm ? "warm " : "");
2817                 delay = HUB_LONG_RESET_TIME;
2818         }
2819
2820         dev_err(&port_dev->dev, "Cannot enable. Maybe the USB cable is bad?\n");
2821
2822 done:
2823         if (status == 0) {
2824                 /* TRSTRCY = 10 ms; plus some extra */
2825                 msleep(10 + 40);
2826                 if (udev) {
2827                         struct usb_hcd *hcd = bus_to_hcd(udev->bus);
2828
2829                         update_devnum(udev, 0);
2830                         /* The xHC may think the device is already reset,
2831                          * so ignore the status.
2832                          */
2833                         if (hcd->driver->reset_device)
2834                                 hcd->driver->reset_device(hcd, udev);
2835
2836                         usb_set_device_state(udev, USB_STATE_DEFAULT);
2837                 }
2838         } else {
2839                 if (udev)
2840                         usb_set_device_state(udev, USB_STATE_NOTATTACHED);
2841         }
2842
2843         if (!hub_is_superspeed(hub->hdev))
2844                 up_read(&ehci_cf_port_reset_rwsem);
2845
2846         return status;
2847 }
2848
2849 /* Check if a port is power on */
2850 static int port_is_power_on(struct usb_hub *hub, unsigned portstatus)
2851 {
2852         int ret = 0;
2853
2854         if (hub_is_superspeed(hub->hdev)) {
2855                 if (portstatus & USB_SS_PORT_STAT_POWER)
2856                         ret = 1;
2857         } else {
2858                 if (portstatus & USB_PORT_STAT_POWER)
2859                         ret = 1;
2860         }
2861
2862         return ret;
2863 }
2864
2865 static void usb_lock_port(struct usb_port *port_dev)
2866                 __acquires(&port_dev->status_lock)
2867 {
2868         mutex_lock(&port_dev->status_lock);
2869         __acquire(&port_dev->status_lock);
2870 }
2871
2872 static void usb_unlock_port(struct usb_port *port_dev)
2873                 __releases(&port_dev->status_lock)
2874 {
2875         mutex_unlock(&port_dev->status_lock);
2876         __release(&port_dev->status_lock);
2877 }
2878
2879 #ifdef  CONFIG_PM
2880
2881 /* Check if a port is suspended(USB2.0 port) or in U3 state(USB3.0 port) */
2882 static int port_is_suspended(struct usb_hub *hub, unsigned portstatus)
2883 {
2884         int ret = 0;
2885
2886         if (hub_is_superspeed(hub->hdev)) {
2887                 if ((portstatus & USB_PORT_STAT_LINK_STATE)
2888                                 == USB_SS_PORT_LS_U3)
2889                         ret = 1;
2890         } else {
2891                 if (portstatus & USB_PORT_STAT_SUSPEND)
2892                         ret = 1;
2893         }
2894
2895         return ret;
2896 }
2897
2898 /* Determine whether the device on a port is ready for a normal resume,
2899  * is ready for a reset-resume, or should be disconnected.
2900  */
2901 static int check_port_resume_type(struct usb_device *udev,
2902                 struct usb_hub *hub, int port1,
2903                 int status, u16 portchange, u16 portstatus)
2904 {
2905         struct usb_port *port_dev = hub->ports[port1 - 1];
2906         int retries = 3;
2907
2908  retry:
2909         /* Is a warm reset needed to recover the connection? */
2910         if (status == 0 && udev->reset_resume
2911                 && hub_port_warm_reset_required(hub, port1, portstatus)) {
2912                 /* pass */;
2913         }
2914         /* Is the device still present? */
2915         else if (status || port_is_suspended(hub, portstatus) ||
2916                         !port_is_power_on(hub, portstatus)) {
2917                 if (status >= 0)
2918                         status = -ENODEV;
2919         } else if (!(portstatus & USB_PORT_STAT_CONNECTION)) {
2920                 if (retries--) {
2921                         usleep_range(200, 300);
2922                         status = hub_port_status(hub, port1, &portstatus,
2923                                                              &portchange);
2924                         goto retry;
2925                 }
2926                 status = -ENODEV;
2927         }
2928
2929         /* Can't do a normal resume if the port isn't enabled,
2930          * so try a reset-resume instead.
2931          */
2932         else if (!(portstatus & USB_PORT_STAT_ENABLE) && !udev->reset_resume) {
2933                 if (udev->persist_enabled)
2934                         udev->reset_resume = 1;
2935                 else
2936                         status = -ENODEV;
2937         }
2938
2939         if (status) {
2940                 dev_dbg(&port_dev->dev, "status %04x.%04x after resume, %d\n",
2941                                 portchange, portstatus, status);
2942         } else if (udev->reset_resume) {
2943
2944                 /* Late port handoff can set status-change bits */
2945                 if (portchange & USB_PORT_STAT_C_CONNECTION)
2946                         usb_clear_port_feature(hub->hdev, port1,
2947                                         USB_PORT_FEAT_C_CONNECTION);
2948                 if (portchange & USB_PORT_STAT_C_ENABLE)
2949                         usb_clear_port_feature(hub->hdev, port1,
2950                                         USB_PORT_FEAT_C_ENABLE);
2951         }
2952
2953         return status;
2954 }
2955
2956 int usb_disable_ltm(struct usb_device *udev)
2957 {
2958         struct usb_hcd *hcd = bus_to_hcd(udev->bus);
2959
2960         /* Check if the roothub and device supports LTM. */
2961         if (!usb_device_supports_ltm(hcd->self.root_hub) ||
2962                         !usb_device_supports_ltm(udev))
2963                 return 0;
2964
2965         /* Clear Feature LTM Enable can only be sent if the device is
2966          * configured.
2967          */
2968         if (!udev->actconfig)
2969                 return 0;
2970
2971         return usb_control_msg(udev, usb_sndctrlpipe(udev, 0),
2972                         USB_REQ_CLEAR_FEATURE, USB_RECIP_DEVICE,
2973                         USB_DEVICE_LTM_ENABLE, 0, NULL, 0,
2974                         USB_CTRL_SET_TIMEOUT);
2975 }
2976 EXPORT_SYMBOL_GPL(usb_disable_ltm);
2977
2978 void usb_enable_ltm(struct usb_device *udev)
2979 {
2980         struct usb_hcd *hcd = bus_to_hcd(udev->bus);
2981
2982         /* Check if the roothub and device supports LTM. */
2983         if (!usb_device_supports_ltm(hcd->self.root_hub) ||
2984                         !usb_device_supports_ltm(udev))
2985                 return;
2986
2987         /* Set Feature LTM Enable can only be sent if the device is
2988          * configured.
2989          */
2990         if (!udev->actconfig)
2991                 return;
2992
2993         usb_control_msg(udev, usb_sndctrlpipe(udev, 0),
2994                         USB_REQ_SET_FEATURE, USB_RECIP_DEVICE,
2995                         USB_DEVICE_LTM_ENABLE, 0, NULL, 0,
2996                         USB_CTRL_SET_TIMEOUT);
2997 }
2998 EXPORT_SYMBOL_GPL(usb_enable_ltm);
2999
3000 /*
3001  * usb_enable_remote_wakeup - enable remote wakeup for a device
3002  * @udev: target device
3003  *
3004  * For USB-2 devices: Set the device's remote wakeup feature.
3005  *
3006  * For USB-3 devices: Assume there's only one function on the device and
3007  * enable remote wake for the first interface.  FIXME if the interface
3008  * association descriptor shows there's more than one function.
3009  */
3010 static int usb_enable_remote_wakeup(struct usb_device *udev)
3011 {
3012         if (udev->speed < USB_SPEED_SUPER)
3013                 return usb_control_msg(udev, usb_sndctrlpipe(udev, 0),
3014                                 USB_REQ_SET_FEATURE, USB_RECIP_DEVICE,
3015                                 USB_DEVICE_REMOTE_WAKEUP, 0, NULL, 0,
3016                                 USB_CTRL_SET_TIMEOUT);
3017         else
3018                 return usb_control_msg(udev, usb_sndctrlpipe(udev, 0),
3019                                 USB_REQ_SET_FEATURE, USB_RECIP_INTERFACE,
3020                                 USB_INTRF_FUNC_SUSPEND,
3021                                 USB_INTRF_FUNC_SUSPEND_RW |
3022                                         USB_INTRF_FUNC_SUSPEND_LP,
3023                                 NULL, 0, USB_CTRL_SET_TIMEOUT);
3024 }
3025
3026 /*
3027  * usb_disable_remote_wakeup - disable remote wakeup for a device
3028  * @udev: target device
3029  *
3030  * For USB-2 devices: Clear the device's remote wakeup feature.
3031  *
3032  * For USB-3 devices: Assume there's only one function on the device and
3033  * disable remote wake for the first interface.  FIXME if the interface
3034  * association descriptor shows there's more than one function.
3035  */
3036 static int usb_disable_remote_wakeup(struct usb_device *udev)
3037 {
3038         if (udev->speed < USB_SPEED_SUPER)
3039                 return usb_control_msg(udev, usb_sndctrlpipe(udev, 0),
3040                                 USB_REQ_CLEAR_FEATURE, USB_RECIP_DEVICE,
3041                                 USB_DEVICE_REMOTE_WAKEUP, 0, NULL, 0,
3042                                 USB_CTRL_SET_TIMEOUT);
3043         else
3044                 return usb_control_msg(udev, usb_sndctrlpipe(udev, 0),
3045                                 USB_REQ_CLEAR_FEATURE, USB_RECIP_INTERFACE,
3046                                 USB_INTRF_FUNC_SUSPEND, 0, NULL, 0,
3047                                 USB_CTRL_SET_TIMEOUT);
3048 }
3049
3050 /* Count of wakeup-enabled devices at or below udev */
3051 static unsigned wakeup_enabled_descendants(struct usb_device *udev)
3052 {
3053         struct usb_hub *hub = usb_hub_to_struct_hub(udev);
3054
3055         return udev->do_remote_wakeup +
3056                         (hub ? hub->wakeup_enabled_descendants : 0);
3057 }
3058
3059 /*
3060  * usb_port_suspend - suspend a usb device's upstream port
3061  * @udev: device that's no longer in active use, not a root hub
3062  * Context: must be able to sleep; device not locked; pm locks held
3063  *
3064  * Suspends a USB device that isn't in active use, conserving power.
3065  * Devices may wake out of a suspend, if anything important happens,
3066  * using the remote wakeup mechanism.  They may also be taken out of
3067  * suspend by the host, using usb_port_resume().  It's also routine
3068  * to disconnect devices while they are suspended.
3069  *
3070  * This only affects the USB hardware for a device; its interfaces
3071  * (and, for hubs, child devices) must already have been suspended.
3072  *
3073  * Selective port suspend reduces power; most suspended devices draw
3074  * less than 500 uA.  It's also used in OTG, along with remote wakeup.
3075  * All devices below the suspended port are also suspended.
3076  *
3077  * Devices leave suspend state when the host wakes them up.  Some devices
3078  * also support "remote wakeup", where the device can activate the USB
3079  * tree above them to deliver data, such as a keypress or packet.  In
3080  * some cases, this wakes the USB host.
3081  *
3082  * Suspending OTG devices may trigger HNP, if that's been enabled
3083  * between a pair of dual-role devices.  That will change roles, such
3084  * as from A-Host to A-Peripheral or from B-Host back to B-Peripheral.
3085  *
3086  * Devices on USB hub ports have only one "suspend" state, corresponding
3087  * to ACPI D2, "may cause the device to lose some context".
3088  * State transitions include:
3089  *
3090  *   - suspend, resume ... when the VBUS power link stays live
3091  *   - suspend, disconnect ... VBUS lost
3092  *
3093  * Once VBUS drop breaks the circuit, the port it's using has to go through
3094  * normal re-enumeration procedures, starting with enabling VBUS power.
3095  * Other than re-initializing the hub (plug/unplug, except for root hubs),
3096  * Linux (2.6) currently has NO mechanisms to initiate that:  no hub_wq
3097  * timer, no SRP, no requests through sysfs.
3098  *
3099  * If Runtime PM isn't enabled or used, non-SuperSpeed devices may not get
3100  * suspended until their bus goes into global suspend (i.e., the root
3101  * hub is suspended).  Nevertheless, we change @udev->state to
3102  * USB_STATE_SUSPENDED as this is the device's "logical" state.  The actual
3103  * upstream port setting is stored in @udev->port_is_suspended.
3104  *
3105  * Returns 0 on success, else negative errno.
3106  */
3107 int usb_port_suspend(struct usb_device *udev, pm_message_t msg)
3108 {
3109         struct usb_hub  *hub = usb_hub_to_struct_hub(udev->parent);
3110         struct usb_port *port_dev = hub->ports[udev->portnum - 1];
3111         int             port1 = udev->portnum;
3112         int             status;
3113         bool            really_suspend = true;
3114
3115         usb_lock_port(port_dev);
3116
3117         /* enable remote wakeup when appropriate; this lets the device
3118          * wake up the upstream hub (including maybe the root hub).
3119          *
3120          * NOTE:  OTG devices may issue remote wakeup (or SRP) even when
3121          * we don't explicitly enable it here.
3122          */
3123         if (udev->do_remote_wakeup) {
3124                 status = usb_enable_remote_wakeup(udev);
3125                 if (status) {
3126                         dev_dbg(&udev->dev, "won't remote wakeup, status %d\n",
3127                                         status);
3128                         /* bail if autosuspend is requested */
3129                         if (PMSG_IS_AUTO(msg))
3130                                 goto err_wakeup;
3131                 }
3132         }
3133
3134         /* disable USB2 hardware LPM */
3135         if (udev->usb2_hw_lpm_enabled == 1)
3136                 usb_set_usb2_hardware_lpm(udev, 0);
3137
3138         if (usb_disable_ltm(udev)) {
3139                 dev_err(&udev->dev, "Failed to disable LTM before suspend\n.");
3140                 status = -ENOMEM;
3141                 if (PMSG_IS_AUTO(msg))
3142                         goto err_ltm;
3143         }
3144         if (usb_unlocked_disable_lpm(udev)) {
3145                 dev_err(&udev->dev, "Failed to disable LPM before suspend\n.");
3146                 status = -ENOMEM;
3147                 if (PMSG_IS_AUTO(msg))
3148                         goto err_lpm3;
3149         }
3150
3151         /* see 7.1.7.6 */
3152         if (hub_is_superspeed(hub->hdev))
3153                 status = hub_set_port_link_state(hub, port1, USB_SS_PORT_LS_U3);
3154
3155         /*
3156          * For system suspend, we do not need to enable the suspend feature
3157          * on individual USB-2 ports.  The devices will automatically go
3158          * into suspend a few ms after the root hub stops sending packets.
3159          * The USB 2.0 spec calls this "global suspend".
3160          *
3161          * However, many USB hubs have a bug: They don't relay wakeup requests
3162          * from a downstream port if the port's suspend feature isn't on.
3163          * Therefore we will turn on the suspend feature if udev or any of its
3164          * descendants is enabled for remote wakeup.
3165          */
3166         else if (PMSG_IS_AUTO(msg) || wakeup_enabled_descendants(udev) > 0)
3167                 status = set_port_feature(hub->hdev, port1,
3168                                 USB_PORT_FEAT_SUSPEND);
3169         else {
3170                 really_suspend = false;
3171                 status = 0;
3172         }
3173         if (status) {
3174                 dev_dbg(&port_dev->dev, "can't suspend, status %d\n", status);
3175
3176                 /* Try to enable USB3 LPM and LTM again */
3177                 usb_unlocked_enable_lpm(udev);
3178  err_lpm3:
3179                 usb_enable_ltm(udev);
3180  err_ltm