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