source: src/linux/universal/linux-3.18/drivers/usb/core/hub.c @ 31869

Last change on this file since 31869 was 31869, checked in by brainslayer, 2 months ago

update

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