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