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