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