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