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