source: src/linux/universal/linux-4.9/drivers/usb/core/hub.c @ 31794

Last change on this file since 31794 was 31794, checked in by brainslayer, 5 months ago

update kernel

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