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