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

Last change on this file since 31884 was 31884, checked in by brainslayer, 3 months ago

update kernels

File size: 165.2 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                /*
2667                 * The port state is unknown until the reset completes.
2668                 *
2669                 * On top of that, some chips may require additional time
2670                 * to re-establish a connection after the reset is complete,
2671                 * so also wait for the connection to be re-established.
2672                 */
2673                if (!(portstatus & USB_PORT_STAT_RESET) &&
2674                    (portstatus & USB_PORT_STAT_CONNECTION))
2675                        break;
2676
2677                /* switch to the long delay after two short delay failures */
2678                if (delay_time >= 2 * HUB_SHORT_RESET_TIME)
2679                        delay = HUB_LONG_RESET_TIME;
2680
2681                dev_dbg(&hub->ports[port1 - 1]->dev,
2682                                "not %sreset yet, waiting %dms\n",
2683                                warm ? "warm " : "", delay);
2684        }
2685
2686        if ((portstatus & USB_PORT_STAT_RESET))
2687                return -EBUSY;
2688
2689        if (hub_port_warm_reset_required(hub, port1, portstatus))
2690                return -ENOTCONN;
2691
2692        /* Device went away? */
2693        if (!(portstatus & USB_PORT_STAT_CONNECTION))
2694                return -ENOTCONN;
2695
2696        /* bomb out completely if the connection bounced.  A USB 3.0
2697         * connection may bounce if multiple warm resets were issued,
2698         * but the device may have successfully re-connected. Ignore it.
2699         */
2700        if (!hub_is_superspeed(hub->hdev) &&
2701                        (portchange & USB_PORT_STAT_C_CONNECTION))
2702                return -ENOTCONN;
2703
2704        if (!(portstatus & USB_PORT_STAT_ENABLE))
2705                return -EBUSY;
2706
2707        if (!udev)
2708                return 0;
2709
2710        if (hub_is_wusb(hub))
2711                udev->speed = USB_SPEED_WIRELESS;
2712        else if (hub_is_superspeedplus(hub->hdev) &&
2713                 port_speed_is_ssp(hub->hdev, ext_portstatus &
2714                                   USB_EXT_PORT_STAT_RX_SPEED_ID))
2715                udev->speed = USB_SPEED_SUPER_PLUS;
2716        else if (hub_is_superspeed(hub->hdev))
2717                udev->speed = USB_SPEED_SUPER;
2718        else if (portstatus & USB_PORT_STAT_HIGH_SPEED)
2719                udev->speed = USB_SPEED_HIGH;
2720        else if (portstatus & USB_PORT_STAT_LOW_SPEED)
2721                udev->speed = USB_SPEED_LOW;
2722        else
2723                udev->speed = USB_SPEED_FULL;
2724        return 0;
2725}
2726
2727/* Handle port reset and port warm(BH) reset (for USB3 protocol ports) */
2728static int hub_port_reset(struct usb_hub *hub, int port1,
2729                        struct usb_device *udev, unsigned int delay, bool warm)
2730{
2731        int i, status;
2732        u16 portchange, portstatus;
2733        struct usb_port *port_dev = hub->ports[port1 - 1];
2734
2735        if (!hub_is_superspeed(hub->hdev)) {
2736                if (warm) {
2737                        dev_err(hub->intfdev, "only USB3 hub support "
2738                                                "warm reset\n");
2739                        return -EINVAL;
2740                }
2741                /* Block EHCI CF initialization during the port reset.
2742                 * Some companion controllers don't like it when they mix.
2743                 */
2744                down_read(&ehci_cf_port_reset_rwsem);
2745        } else if (!warm) {
2746                /*
2747                 * If the caller hasn't explicitly requested a warm reset,
2748                 * double check and see if one is needed.
2749                 */
2750                if (hub_port_status(hub, port1, &portstatus, &portchange) == 0)
2751                        if (hub_port_warm_reset_required(hub, port1,
2752                                                        portstatus))
2753                                warm = true;
2754        }
2755        clear_bit(port1, hub->warm_reset_bits);
2756
2757        /* Reset the port */
2758        for (i = 0; i < PORT_RESET_TRIES; i++) {
2759                status = set_port_feature(hub->hdev, port1, (warm ?
2760                                        USB_PORT_FEAT_BH_PORT_RESET :
2761                                        USB_PORT_FEAT_RESET));
2762                if (status == -ENODEV) {
2763                        ;       /* The hub is gone */
2764                } else if (status) {
2765                        dev_err(&port_dev->dev,
2766                                        "cannot %sreset (err = %d)\n",
2767                                        warm ? "warm " : "", status);
2768                } else {
2769                        status = hub_port_wait_reset(hub, port1, udev, delay,
2770                                                                warm);
2771                        if (status && status != -ENOTCONN && status != -ENODEV)
2772                                dev_dbg(hub->intfdev,
2773                                                "port_wait_reset: err = %d\n",
2774                                                status);
2775                }
2776
2777                /* Check for disconnect or reset */
2778                if (status == 0 || status == -ENOTCONN || status == -ENODEV) {
2779                        usb_clear_port_feature(hub->hdev, port1,
2780                                        USB_PORT_FEAT_C_RESET);
2781
2782                        if (!hub_is_superspeed(hub->hdev))
2783                                goto done;
2784
2785                        usb_clear_port_feature(hub->hdev, port1,
2786                                        USB_PORT_FEAT_C_BH_PORT_RESET);
2787                        usb_clear_port_feature(hub->hdev, port1,
2788                                        USB_PORT_FEAT_C_PORT_LINK_STATE);
2789                        usb_clear_port_feature(hub->hdev, port1,
2790                                        USB_PORT_FEAT_C_CONNECTION);
2791
2792                        /*
2793                         * If a USB 3.0 device migrates from reset to an error
2794                         * state, re-issue the warm reset.
2795                         */
2796                        if (hub_port_status(hub, port1,
2797                                        &portstatus, &portchange) < 0)
2798                                goto done;
2799
2800                        if (!hub_port_warm_reset_required(hub, port1,
2801                                        portstatus))
2802                                goto done;
2803
2804                        /*
2805                         * If the port is in SS.Inactive or Compliance Mode, the
2806                         * hot or warm reset failed.  Try another warm reset.
2807                         */
2808                        if (!warm) {
2809                                dev_dbg(&port_dev->dev,
2810                                                "hot reset failed, warm reset\n");
2811                                warm = true;
2812                        }
2813                }
2814
2815                dev_dbg(&port_dev->dev,
2816                                "not enabled, trying %sreset again...\n",
2817                                warm ? "warm " : "");
2818                delay = HUB_LONG_RESET_TIME;
2819        }
2820
2821        dev_err(&port_dev->dev, "Cannot enable. Maybe the USB cable is bad?\n");
2822
2823done:
2824        if (status == 0) {
2825                /* TRSTRCY = 10 ms; plus some extra */
2826                msleep(10 + 40);
2827                if (udev) {
2828                        struct usb_hcd *hcd = bus_to_hcd(udev->bus);
2829
2830                        update_devnum(udev, 0);
2831                        /* The xHC may think the device is already reset,
2832                         * so ignore the status.
2833                         */
2834                        if (hcd->driver->reset_device)
2835                                hcd->driver->reset_device(hcd, udev);
2836
2837                        usb_set_device_state(udev, USB_STATE_DEFAULT);
2838                }
2839        } else {
2840                if (udev)
2841                        usb_set_device_state(udev, USB_STATE_NOTATTACHED);
2842        }
2843
2844        if (!hub_is_superspeed(hub->hdev))
2845                up_read(&ehci_cf_port_reset_rwsem);
2846
2847        return status;
2848}
2849
2850/* Check if a port is power on */
2851static int port_is_power_on(struct usb_hub *hub, unsigned portstatus)
2852{
2853        int ret = 0;
2854
2855        if (hub_is_superspeed(hub->hdev)) {
2856                if (portstatus & USB_SS_PORT_STAT_POWER)
2857                        ret = 1;
2858        } else {
2859                if (portstatus & USB_PORT_STAT_POWER)
2860                        ret = 1;
2861        }
2862
2863        return ret;
2864}
2865
2866static void usb_lock_port(struct usb_port *port_dev)
2867                __acquires(&port_dev->status_lock)
2868{
2869        mutex_lock(&port_dev->status_lock);
2870        __acquire(&port_dev->status_lock);
2871}
2872
2873static void usb_unlock_port(struct usb_port *port_dev)
2874                __releases(&port_dev->status_lock)
2875{
2876        mutex_unlock(&port_dev->status_lock);
2877        __release(&port_dev->status_lock);
2878}
2879
2880#ifdef  CONFIG_PM
2881
2882/* Check if a port is suspended(USB2.0 port) or in U3 state(USB3.0 port) */
2883static int port_is_suspended(struct usb_hub *hub, unsigned portstatus)
2884{
2885        int ret = 0;
2886
2887        if (hub_is_superspeed(hub->hdev)) {
2888                if ((portstatus & USB_PORT_STAT_LINK_STATE)
2889                                == USB_SS_PORT_LS_U3)
2890                        ret = 1;
2891        } else {
2892                if (portstatus & USB_PORT_STAT_SUSPEND)
2893                        ret = 1;
2894        }
2895
2896        return ret;
2897}
2898
2899/* Determine whether the device on a port is ready for a normal resume,
2900 * is ready for a reset-resume, or should be disconnected.
2901 */
2902static int check_port_resume_type(struct usb_device *udev,
2903                struct usb_hub *hub, int port1,
2904                int status, u16 portchange, u16 portstatus)
2905{
2906        struct usb_port *port_dev = hub->ports[port1 - 1];
2907        int retries = 3;
2908
2909 retry:
2910        /* Is a warm reset needed to recover the connection? */
2911        if (status == 0 && udev->reset_resume
2912                && hub_port_warm_reset_required(hub, port1, portstatus)) {
2913                /* pass */;
2914        }
2915        /* Is the device still present? */
2916        else if (status || port_is_suspended(hub, portstatus) ||
2917                        !port_is_power_on(hub, portstatus)) {
2918                if (status >= 0)
2919                        status = -ENODEV;
2920        } else if (!(portstatus & USB_PORT_STAT_CONNECTION)) {
2921                if (retries--) {
2922                        usleep_range(200, 300);
2923                        status = hub_port_status(hub, port1, &portstatus,
2924                                                             &portchange);
2925                        goto retry;
2926                }
2927                status = -ENODEV;
2928        }
2929
2930        /* Can't do a normal resume if the port isn't enabled,
2931         * so try a reset-resume instead.
2932         */
2933        else if (!(portstatus & USB_PORT_STAT_ENABLE) && !udev->reset_resume) {
2934                if (udev->persist_enabled)
2935                        udev->reset_resume = 1;
2936                else
2937                        status = -ENODEV;
2938        }
2939
2940        if (status) {
2941                dev_dbg(&port_dev->dev, "status %04x.%04x after resume, %d\n",
2942                                portchange, portstatus, status);
2943        } else if (udev->reset_resume) {
2944
2945                /* Late port handoff can set status-change bits */
2946                if (portchange & USB_PORT_STAT_C_CONNECTION)
2947                        usb_clear_port_feature(hub->hdev, port1,
2948                                        USB_PORT_FEAT_C_CONNECTION);
2949                if (portchange & USB_PORT_STAT_C_ENABLE)
2950                        usb_clear_port_feature(hub->hdev, port1,
2951                                        USB_PORT_FEAT_C_ENABLE);
2952        }
2953
2954        return status;
2955}
2956
2957int usb_disable_ltm(struct usb_device *udev)
2958{
2959        struct usb_hcd *hcd = bus_to_hcd(udev->bus);
2960
2961        /* Check if the roothub and device supports LTM. */
2962        if (!usb_device_supports_ltm(hcd->self.root_hub) ||
2963                        !usb_device_supports_ltm(udev))
2964                return 0;
2965
2966        /* Clear Feature LTM Enable can only be sent if the device is
2967         * configured.
2968         */
2969        if (!udev->actconfig)
2970                return 0;
2971
2972        return usb_control_msg(udev, usb_sndctrlpipe(udev, 0),
2973                        USB_REQ_CLEAR_FEATURE, USB_RECIP_DEVICE,
2974                        USB_DEVICE_LTM_ENABLE, 0, NULL, 0,
2975                        USB_CTRL_SET_TIMEOUT);
2976}
2977EXPORT_SYMBOL_GPL(usb_disable_ltm);
2978
2979void usb_enable_ltm(struct usb_device *udev)
2980{
2981        struct usb_hcd *hcd = bus_to_hcd(udev->bus);
2982
2983        /* Check if the roothub and device supports LTM. */
2984        if (!usb_device_supports_ltm(hcd->self.root_hub) ||
2985                        !usb_device_supports_ltm(udev))
2986                return;
2987
2988        /* Set Feature LTM Enable can only be sent if the device is
2989         * configured.
2990         */
2991        if (!udev->actconfig)
2992                return;
2993
2994        usb_control_msg(udev, usb_sndctrlpipe(udev, 0),
2995                        USB_REQ_SET_FEATURE, USB_RECIP_DEVICE,
2996                        USB_DEVICE_LTM_ENABLE, 0, NULL, 0,
2997                        USB_CTRL_SET_TIMEOUT);
2998}
2999EXPORT_SYMBOL_GPL(usb_enable_ltm);
3000
3001/*
3002 * usb_enable_remote_wakeup - enable remote wakeup for a device
3003 * @udev: target device
3004 *
3005 * For USB-2 devices: Set the device's remote wakeup feature.
3006 *
3007 * For USB-3 devices: Assume there's only one function on the device and
3008 * enable remote wake for the first interface.  FIXME if the interface
3009 * association descriptor shows there's more than one function.
3010 */
3011static int usb_enable_remote_wakeup(struct usb_device *udev)
3012{
3013        if (udev->speed < USB_SPEED_SUPER)
3014                return usb_control_msg(udev, usb_sndctrlpipe(udev, 0),
3015                                USB_REQ_SET_FEATURE, USB_RECIP_DEVICE,
3016                                USB_DEVICE_REMOTE_WAKEUP, 0, NULL, 0,
3017                                USB_CTRL_SET_TIMEOUT);
3018        else
3019                return usb_control_msg(udev, usb_sndctrlpipe(udev, 0),
3020                                USB_REQ_SET_FEATURE, USB_RECIP_INTERFACE,
3021                                USB_INTRF_FUNC_SUSPEND,
3022                                USB_INTRF_FUNC_SUSPEND_RW |
3023                                        USB_INTRF_FUNC_SUSPEND_LP,
3024                                NULL, 0, USB_CTRL_SET_TIMEOUT);
3025}
3026
3027/*
3028 * usb_disable_remote_wakeup - disable remote wakeup for a device
3029 * @udev: target device
3030 *
3031 * For USB-2 devices: Clear the device's remote wakeup feature.
3032 *
3033 * For USB-3 devices: Assume there's only one function on the device and
3034 * disable remote wake for the first interface.  FIXME if the interface
3035 * association descriptor shows there's more than one function.
3036 */
3037static int usb_disable_remote_wakeup(struct usb_device *udev)
3038{
3039        if (udev->speed < USB_SPEED_SUPER)
3040                return usb_control_msg(udev, usb_sndctrlpipe(udev, 0),
3041                                USB_REQ_CLEAR_FEATURE, USB_RECIP_DEVICE,
3042                                USB_DEVICE_REMOTE_WAKEUP, 0, NULL, 0,
3043                                USB_CTRL_SET_TIMEOUT);
3044        else
3045                return usb_control_msg(udev, usb_sndctrlpipe(udev, 0),
3046                                USB_REQ_SET_FEATURE, USB_RECIP_INTERFACE,
3047                                USB_INTRF_FUNC_SUSPEND, 0, NULL, 0,
3048                                USB_CTRL_SET_TIMEOUT);
3049}
3050
3051/* Count of wakeup-enabled devices at or below udev */
3052static unsigned wakeup_enabled_descendants(struct usb_device *udev)
3053{
3054        struct usb_hub *hub = usb_hub_to_struct_hub(udev);
3055
3056        return udev->do_remote_wakeup +
3057                        (hub ? hub->wakeup_enabled_descendants : 0);
3058}
3059
3060/*
3061 * usb_port_suspend - suspend a usb device's upstream port
3062 * @udev: device that's no longer in active use, not a root hub
3063 * Context: must be able to sleep; device not locked; pm locks held
3064 *
3065 * Suspends a USB device that isn't in active use, conserving power.
3066 * Devices may wake out of a suspend, if anything important happens,
3067 * using the remote wakeup mechanism.  They may also be taken out of
3068 * suspend by the host, using usb_port_resume().  It's also routine
3069 * to disconnect devices while they are suspended.
3070 *
3071 * This only affects the USB hardware for a device; its interfaces
3072 * (and, for hubs, child devices) must already have been suspended.
3073 *
3074 * Selective port suspend reduces power; most suspended devices draw
3075 * less than 500 uA.  It's also used in OTG, along with remote wakeup.
3076 * All devices below the suspended port are also suspended.
3077 *
3078 * Devices leave suspend state when the host wakes them up.  Some devices
3079 * also support "remote wakeup", where the device can activate the USB
3080 * tree above them to deliver data, such as a keypress or packet.  In
3081 * some cases, this wakes the USB host.
3082 *
3083 * Suspending OTG devices may trigger HNP, if that's been enabled
3084 * between a pair of dual-role devices.  That will change roles, such
3085 * as from A-Host to A-Peripheral or from B-Host back to B-Peripheral.
3086 *
3087 * Devices on USB hub ports have only one "suspend" state, corresponding
3088 * to ACPI D2, "may cause the device to lose some context".
3089 * State transitions include:
3090 *
3091 *   - suspend, resume ... when the VBUS power link stays live
3092 *   - suspend, disconnect ... VBUS lost
3093 *
3094 * Once VBUS drop breaks the circuit, the port it's using has to go through
3095 * normal re-enumeration procedures, starting with enabling VBUS power.
3096 * Other than re-initializing the hub (plug/unplug, except for root hubs),
3097 * Linux (2.6) currently has NO mechanisms to initiate that:  no hub_wq
3098 * timer, no SRP, no requests through sysfs.
3099 *
3100 * If Runtime PM isn't enabled or used, non-SuperSpeed devices may not get
3101 * suspended until their bus goes into global suspend (i.e., the root
3102 * hub is suspended).  Nevertheless, we change @udev->state to
3103 * USB_STATE_SUSPENDED as this is the device's "logical" state.  The actual
3104 * upstream port setting is stored in @udev->port_is_suspended.
3105 *
3106 * Returns 0 on success, else negative errno.
3107 */
3108int usb_port_suspend(struct usb_device *udev, pm_message_t msg)
3109{
3110        struct usb_hub  *hub = usb_hub_to_struct_hub(udev->parent);
3111        struct usb_port *port_dev = hub->ports[udev->portnum - 1];
3112        int             port1 = udev->portnum;
3113        int             status;
3114        bool            really_suspend = true;
3115
3116        usb_lock_port(port_dev);
3117
3118        /* enable remote wakeup when appropriate; this lets the device
3119         * wake up the upstream hub (including maybe the root hub).
3120         *
3121         * NOTE:  OTG devices may issue remote wakeup (or SRP) even when
3122         * we don't explicitly enable it here.
3123         */
3124        if (udev->do_remote_wakeup) {
3125                status = usb_enable_remote_wakeup(udev);
3126                if (status) {
3127                        dev_dbg(&udev->dev, "won't remote wakeup, status %d\n",
3128                                        status);
3129                        /* bail if autosuspend is requested */
3130                        if (PMSG_IS_AUTO(msg))
3131                                goto err_wakeup;
3132                }
3133        }
3134
3135        /* disable USB2 hardware LPM */
3136        if (udev->usb2_hw_lpm_enabled == 1)
3137                usb_set_usb2_hardware_lpm(udev, 0);
3138
3139        if (usb_disable_ltm(udev)) {
3140                dev_err(&udev->dev, "Failed to disable LTM before suspend\n.");
3141                status = -ENOMEM;
3142                if (PMSG_IS_AUTO(msg))
3143                        goto err_ltm;
3144        }
3145        if (usb_unlocked_disable_lpm(udev)) {
3146                dev_err(&udev->dev, "Failed to disable LPM before suspend\n.");
3147                status = -ENOMEM;
3148                if (PMSG_IS_AUTO(msg))
3149                        goto err_lpm3;
3150        }
3151
3152        /* see 7.1.7.6 */
3153        if (hub_is_superspeed(hub->hdev))
3154                status = hub_set_port_link_state(hub, port1, USB_SS_PORT_LS_U3);
3155
3156        /*
3157         * For system suspend, we do not need to enable the suspend feature
3158         * on individual USB-2 ports.  The devices will automatically go
3159         * into suspend a few ms after the root hub stops sending packets.
3160         * The USB 2.0 spec calls this "global suspend".
3161         *
3162         * However, many USB hubs have a bug: They don't relay wakeup requests
3163         * from a downstream port if the port's suspend feature isn't on.
3164         * Therefore we will turn on the suspend feature if udev or any of its
3165         * descendants is enabled for remote wakeup.
3166         */
3167        else if (PMSG_IS_AUTO(msg) || wakeup_enabled_descendants(udev) > 0)
3168                status = set_port_feature(hub->hdev, port1,
3169                                USB_PORT_FEAT_SUSPEND);
3170        else {
3171                really_suspend = false;
3172                status = 0;
3173        }
3174        if (status) {
3175                dev_dbg(&port_dev->dev, "can't suspend, status %d\n", status);
3176
3177                /* Try to enable USB3 LPM and LTM again */
3178                usb_unlocked_enable_lpm(udev);
3179 err_lpm3:
3180                usb_enable_ltm(udev);
3181 err_ltm:
3182                /* Try to enable USB2 hardware LPM again */
3183                if (udev->usb2_hw_lpm_capable == 1)
3184                        usb_set_usb2_hardware_lpm(udev, 1);
3185
3186                if (udev->do_remote_wakeup)
3187                        (void) usb_disable_remote_wakeup(udev);
3188 err_wakeup:
3189
3190                /* System sleep transitions should never fail */
3191                if (!PMSG_IS_AUTO(msg))
3192                        status = 0;
3193        } else {
3194                dev_dbg(&udev->dev, "usb %ssuspend, wakeup %d\n",
3195                                (PMSG_IS_AUTO(msg) ? "auto-" : ""),
3196                                udev->do_remote_wakeup);
3197                if (really_suspend) {
3198                        udev->port_is_suspended = 1;
3199
3200                        /* device has up to 10 msec to fully suspend */
3201                        msleep(10);
3202                }
3203                usb_set_device_state(udev, USB_STATE_SUSPENDED);
3204        }
3205
3206        if (status == 0 && !udev->do_remote_wakeup && udev->persist_enabled
3207                        && test_and_clear_bit(port1, hub->child_usage_bits))
3208                pm_runtime_put_sync(&port_dev->dev);
3209
3210        usb_mark_last_busy(hub->hdev);
3211
3212        usb_unlock_port(port_dev);
3213        return status;
3214}
3215
3216/*
3217 * If the USB "suspend" state is in use (rather than "global suspend"),
3218 * many devices will be individually taken out of suspend state using
3219 * special "resume" signaling.  This routine kicks in shortly after
3220 * hardware resume signaling is finished, either because of selective
3221 * resume (by host) or remote wakeup (by device) ... now see what changed
3222 * in the tree that's rooted at this device.
3223 *
3224 * If @udev->reset_resume is set then the device is reset before the
3225 * status check is done.
3226 */
3227static int finish_port_resume(struct usb_device *udev)
3228{
3229        int     status = 0;
3230        u16     devstatus = 0;
3231
3232        /* caller owns the udev device lock */
3233        dev_dbg(&udev->dev, "%s\n",
3234                udev->reset_resume ? "finish reset-resume" : "finish resume");
3235
3236        /* usb ch9 identifies four variants of SUSPENDED, based on what
3237         * state the device resumes to.  Linux currently won't see the
3238         * first two on the host side; they'd be inside hub_port_init()
3239         * during many timeouts, but hub_wq can't suspend until later.
3240         */
3241        usb_set_device_state(udev, udev->actconfig
3242                        ? USB_STATE_CONFIGURED
3243                        : USB_STATE_ADDRESS);
3244
3245        /* 10.5.4.5 says not to reset a suspended port if the attached
3246         * device is enabled for remote wakeup.  Hence the reset
3247         * operation is carried out here, after the port has been
3248         * resumed.
3249         */
3250        if (udev->reset_resume) {
3251                /*
3252                 * If the device morphs or switches modes when it is reset,
3253                 * we don't want to perform a reset-resume.  We'll fail the
3254                 * resume, which will cause a logical disconnect, and then
3255                 * the device will be rediscovered.
3256                 */
3257 retry_reset_resume:
3258                if (udev->quirks & USB_QUIRK_RESET)
3259                        status = -ENODEV;
3260                else
3261                        status = usb_reset_and_verify_device(udev);
3262        }
3263
3264        /* 10.5.4.5 says be sure devices in the tree are still there.
3265         * For now let's assume the device didn't go crazy on resume,
3266         * and device drivers will know about any resume quirks.
3267         */
3268        if (status == 0) {
3269                devstatus = 0;
3270                status = usb_get_status(udev, USB_RECIP_DEVICE, 0, &devstatus);
3271
3272                /* If a normal resume failed, try doing a reset-resume */
3273                if (status && !udev->reset_resume && udev->persist_enabled) {
3274                        dev_dbg(&udev->dev, "retry with reset-resume\n");
3275                        udev->reset_resume = 1;
3276                        goto retry_reset_resume;
3277                }
3278        }
3279
3280        if (status) {
3281                dev_dbg(&udev->dev, "gone after usb resume? status %d\n",
3282                                status);
3283        /*
3284         * There are a few quirky devices which violate the standard
3285         * by claiming to have remote wakeup enabled after a reset,
3286         * which crash if the feature is cleared, hence check for
3287         * udev->reset_resume
3288         */
3289        } else if (udev->actconfig && !udev->reset_resume) {
3290                if (udev->speed < USB_SPEED_SUPER) {
3291                        if (devstatus & (1 << USB_DEVICE_REMOTE_WAKEUP))
3292                                status = usb_disable_remote_wakeup(udev);
3293                } else {
3294                        status = usb_get_status(udev, USB_RECIP_INTERFACE, 0,
3295                                        &devstatus);
3296                        if (!status && devstatus & (USB_INTRF_STAT_FUNC_RW_CAP
3297                                        | USB_INTRF_STAT_FUNC_RW))
3298                                status = usb_disable_remote_wakeup(udev);
3299                }
3300
3301                if (status)
3302                        dev_dbg(&udev->dev,
3303                                "disable remote wakeup, status %d\n",
3304                                status);
3305                status = 0;
3306        }
3307        return status;
3308}
3309
3310/*
3311 * There are some SS USB devices which take longer time for link training.
3312 * XHCI specs 4.19.4 says that when Link training is successful, port
3313 * sets CCS bit to 1. So if SW reads port status before successful link
3314 * training, then it will not find device to be present.
3315 * USB Analyzer log with such buggy devices show that in some cases
3316 * device switch on the RX termination after long delay of host enabling
3317 * the VBUS. In few other cases it has been seen that device fails to
3318 * negotiate link training in first attempt. It has been
3319 * reported till now that few devices take as long as 2000 ms to train
3320 * the link after host enabling its VBUS and termination. Following
3321 * routine implements a 2000 ms timeout for link training. If in a case
3322 * link trains before timeout, loop will exit earlier.
3323 *
3324 * There are also some 2.0 hard drive based devices and 3.0 thumb
3325 * drives that, when plugged into a 2.0 only port, take a long
3326 * time to set CCS after VBUS enable.
3327 *
3328 * FIXME: If a device was connected before suspend, but was removed
3329 * while system was asleep, then the loop in the following routine will
3330 * only exit at timeout.
3331 *
3332 * This routine should only be called when persist is enabled.
3333 */
3334static int wait_for_connected(struct usb_device *udev,
3335                struct usb_hub *hub, int *port1,
3336                u16 *portchange, u16 *portstatus)
3337{
3338        int status = 0, delay_ms = 0;
3339
3340        while (delay_ms < 2000) {
3341                if (status || *portstatus & USB_PORT_STAT_CONNECTION)
3342                        break;
3343                msleep(20);
3344                delay_ms += 20;
3345                status = hub_port_status(hub, *port1, portstatus, portchange);
3346        }
3347        dev_dbg(&udev->dev, "Waited %dms for CONNECT\n", delay_ms);
3348        return status;
3349}
3350
3351/*
3352 * usb_port_resume - re-activate a suspended usb device's upstream port
3353 * @udev: device to re-activate, not a root hub
3354 * Context: must be able to sleep; device not locked; pm locks held
3355 *
3356 * This will re-activate the suspended device, increasing power usage
3357 * while letting drivers communicate again with its endpoints.
3358 * USB resume explicitly guarantees that the power session between
3359 * the host and the device is the same as it was when the device
3360 * suspended.
3361 *
3362 * If @udev->reset_resume is set then this routine won't check that the
3363 * port is still enabled.  Furthermore, finish_port_resume() above will
3364 * reset @udev.  The end result is that a broken power session can be
3365 * recovered and @udev will appear to persist across a loss of VBUS power.
3366 *
3367 * For example, if a host controller doesn't maintain VBUS suspend current
3368 * during a system sleep or is reset when the system wakes up, all the USB
3369 * power sessions below it will be broken.  This is especially troublesome
3370 * for mass-storage devices containing mounted filesystems, since the
3371 * device will appear to have disconnected and all the memory mappings
3372 * to it will be lost.  Using the USB_PERSIST facility, the device can be
3373 * made to appear as if it had not disconnected.
3374 *
3375 * This facility can be dangerous.  Although usb_reset_and_verify_device() makes
3376 * every effort to insure that the same device is present after the
3377 * reset as before, it cannot provide a 100% guarantee.  Furthermore it's
3378 * quite possible for a device to remain unaltered but its media to be
3379 * changed.  If the user replaces a flash memory card while the system is
3380 * asleep, he will have only himself to blame when the filesystem on the
3381 * new card is corrupted and the system crashes.
3382 *
3383 * Returns 0 on success, else negative errno.
3384 */
3385int usb_port_resume(struct usb_device *udev, pm_message_t msg)
3386{
3387        struct usb_hub  *hub = usb_hub_to_struct_hub(udev->parent);
3388        struct usb_port *port_dev = hub->ports[udev->portnum  - 1];
3389        int             port1 = udev->portnum;
3390        int             status;
3391        u16             portchange, portstatus;
3392
3393        if (!test_and_set_bit(port1, hub->child_usage_bits)) {
3394                status = pm_runtime_get_sync(&port_dev->dev);
3395                if (status < 0) {
3396                        dev_dbg(&udev->dev, "can't resume usb port, status %d\n",
3397                                        status);
3398                        return status;
3399                }
3400        }
3401
3402        usb_lock_port(port_dev);
3403
3404        /* Skip the initial Clear-Suspend step for a remote wakeup */
3405        status = hub_port_status(hub, port1, &portstatus, &portchange);
3406        if (status == 0 && !port_is_suspended(hub, portstatus))
3407                goto SuspendCleared;
3408
3409        /* see 7.1.7.7; affects power usage, but not budgeting */
3410        if (hub_is_superspeed(hub->hdev))
3411                status = hub_set_port_link_state(hub, port1, USB_SS_PORT_LS_U0);
3412        else
3413                status = usb_clear_port_feature(hub->hdev,
3414                                port1, USB_PORT_FEAT_SUSPEND);
3415        if (status) {
3416                dev_dbg(&port_dev->dev, "can't resume, status %d\n", status);
3417        } else {
3418                /* drive resume for USB_RESUME_TIMEOUT msec */
3419                dev_dbg(&udev->dev, "usb %sresume\n",
3420                                (PMSG_IS_AUTO(msg) ? "auto-" : ""));
3421                msleep(USB_RESUME_TIMEOUT);
3422
3423                /* Virtual root hubs can trigger on GET_PORT_STATUS to
3424                 * stop resume signaling.  Then finish the resume
3425                 * sequence.
3426                 */
3427                status = hub_port_status(hub, port1, &portstatus, &portchange);
3428
3429                /* TRSMRCY = 10 msec */
3430                msleep(10);
3431        }
3432
3433 SuspendCleared:
3434        if (status == 0) {
3435                udev->port_is_suspended = 0;
3436                if (hub_is_superspeed(hub->hdev)) {
3437                        if (portchange & USB_PORT_STAT_C_LINK_STATE)
3438                                usb_clear_port_feature(hub->hdev, port1,
3439                                        USB_PORT_FEAT_C_PORT_LINK_STATE);
3440                } else {
3441                        if (portchange & USB_PORT_STAT_C_SUSPEND)
3442                                usb_clear_port_feature(hub->hdev, port1,
3443                                                USB_PORT_FEAT_C_SUSPEND);
3444                }
3445        }
3446
3447        if (udev->persist_enabled)
3448                status = wait_for_connected(udev, hub, &port1, &portchange,
3449                                &portstatus);
3450
3451        status = check_port_resume_type(udev,
3452                        hub, port1, status, portchange, portstatus);
3453        if (status == 0)
3454                status = finish_port_resume(udev);
3455        if (status < 0) {
3456                dev_dbg(&udev->dev, "can't resume, status %d\n", status);
3457                hub_port_logical_disconnect(hub, port1);
3458        } else  {
3459                /* Try to enable USB2 hardware LPM */
3460                if (udev->usb2_hw_lpm_capable == 1)
3461                        usb_set_usb2_hardware_lpm(udev, 1);
3462
3463                /* Try to enable USB3 LTM and LPM */
3464                usb_enable_ltm(udev);
3465                usb_unlocked_enable_lpm(udev);
3466        }
3467
3468        usb_unlock_port(port_dev);
3469
3470        return status;
3471}
3472
3473int usb_remote_wakeup(struct usb_device *udev)
3474{
3475        int     status = 0;
3476
3477        usb_lock_device(udev);
3478        if (udev->state == USB_STATE_SUSPENDED) {
3479                dev_dbg(&udev->dev, "usb %sresume\n", "wakeup-");
3480                status = usb_autoresume_device(udev);
3481                if (status == 0) {
3482                        /* Let the drivers do their thing, then... */
3483                        usb_autosuspend_device(udev);
3484                }
3485        }
3486        usb_unlock_device(udev);
3487        return status;
3488}
3489
3490/* Returns 1 if there was a remote wakeup and a connect status change. */
3491static int hub_handle_remote_wakeup(struct usb_hub *hub, unsigned int port,
3492                u16 portstatus, u16 portchange)
3493                __must_hold(&port_dev->status_lock)
3494{
3495        struct usb_port *port_dev = hub->ports[port - 1];
3496        struct usb_device *hdev;
3497        struct usb_device *udev;
3498        int connect_change = 0;
3499        int ret;
3500
3501        hdev = hub->hdev;
3502        udev = port_dev->child;
3503        if (!hub_is_superspeed(hdev)) {
3504                if (!(portchange & USB_PORT_STAT_C_SUSPEND))
3505                        return 0;
3506                usb_clear_port_feature(hdev, port, USB_PORT_FEAT_C_SUSPEND);
3507        } else {
3508                if (!udev || udev->state != USB_STATE_SUSPENDED ||
3509                                 (portstatus & USB_PORT_STAT_LINK_STATE) !=
3510                                 USB_SS_PORT_LS_U0)
3511                        return 0;
3512        }
3513
3514        if (udev) {
3515                /* TRSMRCY = 10 msec */
3516                msleep(10);
3517
3518                usb_unlock_port(port_dev);
3519                ret = usb_remote_wakeup(udev);
3520                usb_lock_port(port_dev);
3521                if (ret < 0)
3522                        connect_change = 1;
3523        } else {
3524                ret = -ENODEV;
3525                hub_port_disable(hub, port, 1);
3526        }
3527        dev_dbg(&port_dev->dev, "resume, status %d\n", ret);
3528        return connect_change;
3529}
3530
3531static int check_ports_changed(struct usb_hub *hub)
3532{
3533        int port1;
3534
3535        for (port1 = 1; port1 <= hub->hdev->maxchild; ++port1) {
3536                u16 portstatus, portchange;
3537                int status;
3538
3539                status = hub_port_status(hub, port1, &portstatus, &portchange);
3540                if (!status && portchange)
3541                        return 1;
3542        }
3543        return 0;
3544}
3545
3546static int hub_suspend(struct usb_interface *intf, pm_message_t msg)
3547{
3548        struct usb_hub          *hub = usb_get_intfdata(intf);
3549        struct usb_device       *hdev = hub->hdev;
3550        unsigned                port1;
3551        int                     status;
3552
3553        /*
3554         * Warn if children aren't already suspended.
3555         * Also, add up the number of wakeup-enabled descendants.
3556         */
3557        hub->wakeup_enabled_descendants = 0;
3558        for (port1 = 1; port1 <= hdev->maxchild; port1++) {
3559                struct usb_port *port_dev = hub->ports[port1 - 1];
3560                struct usb_device *udev = port_dev->child;
3561
3562                if (udev && udev->can_submit) {
3563                        dev_warn(&port_dev->dev, "device %s not suspended yet\n",
3564                                        dev_name(&udev->dev));
3565                        if (PMSG_IS_AUTO(msg))
3566                                return -EBUSY;
3567                }
3568                if (udev)
3569                        hub->wakeup_enabled_descendants +=
3570                                        wakeup_enabled_descendants(udev);
3571        }
3572
3573        if (hdev->do_remote_wakeup && hub->quirk_check_port_auto_suspend) {
3574                /* check if there are changes pending on hub ports */
3575                if (check_ports_changed(hub)) {
3576                        if (PMSG_IS_AUTO(msg))
3577                                return -EBUSY;
3578                        pm_wakeup_event(&hdev->dev, 2000);
3579                }
3580        }
3581
3582        if (hub_is_superspeed(hdev) && hdev->do_remote_wakeup) {
3583                /* Enable hub to send remote wakeup for all ports. */
3584                for (port1 = 1; port1 <= hdev->maxchild; port1++) {
3585                        status = set_port_feature(hdev,
3586                                        port1 |
3587                                        USB_PORT_FEAT_REMOTE_WAKE_CONNECT |
3588                                        USB_PORT_FEAT_REMOTE_WAKE_DISCONNECT |
3589                                        USB_PORT_FEAT_REMOTE_WAKE_OVER_CURRENT,
3590                                        USB_PORT_FEAT_REMOTE_WAKE_MASK);
3591                }
3592        }
3593
3594        dev_dbg(&intf->dev, "%s\n", __func__);
3595
3596        /* stop hub_wq and related activity */
3597        hub_quiesce(hub, HUB_SUSPEND);
3598        return 0;
3599}
3600
3601static int hub_resume(struct usb_interface *intf)
3602{
3603        struct usb_hub *hub = usb_get_intfdata(intf);
3604
3605        dev_dbg(&intf->dev, "%s\n", __func__);
3606        hub_activate(hub, HUB_RESUME);
3607        return 0;
3608}
3609
3610static int hub_reset_resume(struct usb_interface *intf)
3611{
3612        struct usb_hub *hub = usb_get_intfdata(intf);
3613
3614        dev_dbg(&intf->dev, "%s\n", __func__);
3615        hub_activate(hub, HUB_RESET_RESUME);
3616        return 0;
3617}
3618
3619/**
3620 * usb_root_hub_lost_power - called by HCD if the root hub lost Vbus power
3621 * @rhdev: struct usb_device for the root hub
3622 *
3623 * The USB host controller driver calls this function when its root hub
3624 * is resumed and Vbus power has been interrupted or the controller
3625 * has been reset.  The routine marks @rhdev as having lost power.
3626 * When the hub driver is resumed it will take notice and carry out
3627 * power-session recovery for all the "USB-PERSIST"-enabled child devices;
3628 * the others will be disconnected.
3629 */
3630void usb_root_hub_lost_power(struct usb_device *rhdev)
3631{
3632        dev_warn(&rhdev->dev, "root hub lost power or was reset\n");
3633        rhdev->reset_resume = 1;
3634}
3635EXPORT_SYMBOL_GPL(usb_root_hub_lost_power);
3636
3637static const char * const usb3_lpm_names[]  = {
3638        "U0",
3639        "U1",
3640        "U2",
3641        "U3",
3642};
3643
3644/*
3645 * Send a Set SEL control transfer to the device, prior to enabling
3646 * device-initiated U1 or U2.  This lets the device know the exit latencies from
3647 * the time the device initiates a U1 or U2 exit, to the time it will receive a
3648 * packet from the host.
3649 *
3650 * This function will fail if the SEL or PEL values for udev are greater than
3651 * the maximum allowed values for the link state to be enabled.
3652 */
3653static int usb_req_set_sel(struct usb_device *udev, enum usb3_link_state state)
3654{
3655        struct usb_set_sel_req *sel_values;
3656        unsigned long long u1_sel;
3657        unsigned long long u1_pel;
3658        unsigned long long u2_sel;
3659        unsigned long long u2_pel;
3660        int ret;
3661
3662        if (udev->state != USB_STATE_CONFIGURED)
3663                return 0;
3664
3665        /* Convert SEL and PEL stored in ns to us */
3666        u1_sel = DIV_ROUND_UP(udev->u1_params.sel, 1000);
3667        u1_pel = DIV_ROUND_UP(udev->u1_params.pel, 1000);
3668        u2_sel = DIV_ROUND_UP(udev->u2_params.sel, 1000);
3669        u2_pel = DIV_ROUND_UP(udev->u2_params.pel, 1000);
3670
3671        /*
3672         * Make sure that the calculated SEL and PEL values for the link
3673         * state we're enabling aren't bigger than the max SEL/PEL
3674         * value that will fit in the SET SEL control transfer.
3675         * Otherwise the device would get an incorrect idea of the exit
3676         * latency for the link state, and could start a device-initiated
3677         * U1/U2 when the exit latencies are too high.
3678         */
3679        if ((state == USB3_LPM_U1 &&
3680                                (u1_sel > USB3_LPM_MAX_U1_SEL_PEL ||
3681                                 u1_pel > USB3_LPM_MAX_U1_SEL_PEL)) ||
3682                        (state == USB3_LPM_U2 &&
3683                         (u2_sel > USB3_LPM_MAX_U2_SEL_PEL ||
3684                          u2_pel > USB3_LPM_MAX_U2_SEL_PEL))) {
3685                dev_dbg(&udev->dev, "Device-initiated %s disabled due to long SEL %llu us or PEL %llu us\n",
3686                                usb3_lpm_names[state], u1_sel, u1_pel);
3687                return -EINVAL;
3688        }
3689
3690        /*
3691         * If we're enabling device-initiated LPM for one link state,
3692         * but the other link state has a too high SEL or PEL value,
3693         * just set those values to the max in the Set SEL request.
3694         */
3695        if (u1_sel > USB3_LPM_MAX_U1_SEL_PEL)
3696                u1_sel = USB3_LPM_MAX_U1_SEL_PEL;
3697
3698        if (u1_pel > USB3_LPM_MAX_U1_SEL_PEL)
3699                u1_pel = USB3_LPM_MAX_U1_SEL_PEL;
3700
3701        if (u2_sel > USB3_LPM_MAX_U2_SEL_PEL)
3702                u2_sel = USB3_LPM_MAX_U2_SEL_PEL;
3703
3704        if (u2_pel > USB3_LPM_MAX_U2_SEL_PEL)
3705                u2_pel = USB3_LPM_MAX_U2_SEL_PEL;
3706
3707        /*
3708         * usb_enable_lpm() can be called as part of a failed device reset,
3709         * which may be initiated by an error path of a mass storage driver.
3710         * Therefore, use GFP_NOIO.
3711         */
3712        sel_values = kmalloc(sizeof *(sel_values), GFP_NOIO);
3713        if (!sel_values)
3714                return -ENOMEM;
3715
3716        sel_values->u1_sel = u1_sel;
3717        sel_values->u1_pel = u1_pel;
3718        sel_values->u2_sel = cpu_to_le16(u2_sel);
3719        sel_values->u2_pel = cpu_to_le16(u2_pel);
3720
3721        ret = usb_control_msg(udev, usb_sndctrlpipe(udev, 0),
3722                        USB_REQ_SET_SEL,
3723                        USB_RECIP_DEVICE,
3724                        0, 0,
3725                        sel_values, sizeof *(sel_values),
3726                        USB_CTRL_SET_TIMEOUT);
3727        kfree(sel_values);
3728        return ret;
3729}
3730
3731/*
3732 * Enable or disable device-initiated U1 or U2 transitions.
3733 */
3734static int usb_set_device_initiated_lpm(struct usb_device *udev,
3735                enum usb3_link_state state, bool enable)
3736{
3737        int ret;
3738        int feature;
3739
3740        switch (state) {
3741        case USB3_LPM_U1:
3742                feature = USB_DEVICE_U1_ENABLE;
3743                break;
3744        case USB3_LPM_U2:
3745                feature = USB_DEVICE_U2_ENABLE;
3746                break;
3747        default:
3748                dev_warn(&udev->dev, "%s: Can't %s non-U1 or U2 state.\n",
3749                                __func__, enable ? "enable" : "disable");
3750                return -EINVAL;
3751        }
3752
3753        if (udev->state != USB_STATE_CONFIGURED) {
3754                dev_dbg(&udev->dev, "%s: Can't %s %s state "
3755                                "for unconfigured device.\n",
3756                                __func__, enable ? "enable" : "disable",
3757                                usb3_lpm_names[state]);
3758                return 0;
3759        }
3760
3761        if (enable) {
3762                /*
3763                 * Now send the control transfer to enable device-initiated LPM
3764                 * for either U1 or U2.
3765                 */
3766                ret = usb_control_msg(udev, usb_sndctrlpipe(udev, 0),
3767                                USB_REQ_SET_FEATURE,
3768                                USB_RECIP_DEVICE,
3769                                feature,
3770                                0, NULL, 0,
3771                                USB_CTRL_SET_TIMEOUT);
3772        } else {
3773                ret = usb_control_msg(udev, usb_sndctrlpipe(udev, 0),
3774                                USB_REQ_CLEAR_FEATURE,
3775                                USB_RECIP_DEVICE,
3776                                feature,
3777                                0, NULL, 0,
3778                                USB_CTRL_SET_TIMEOUT);
3779        }
3780        if (ret < 0) {
3781                dev_warn(&udev->dev, "%s of device-initiated %s failed.\n",
3782                                enable ? "Enable" : "Disable",
3783                                usb3_lpm_names[state]);
3784                return -EBUSY;
3785        }
3786        return 0;
3787}
3788
3789static int usb_set_lpm_timeout(struct usb_device *udev,
3790                enum usb3_link_state state, int timeout)
3791{
3792        int ret;
3793        int feature;
3794
3795        switch (state) {
3796        case USB3_LPM_U1:
3797                feature = USB_PORT_FEAT_U1_TIMEOUT;
3798                break;
3799        case USB3_LPM_U2:
3800                feature = USB_PORT_FEAT_U2_TIMEOUT;
3801                break;
3802        default:
3803                dev_warn(&udev->dev, "%s: Can't set timeout for non-U1 or U2 state.\n",
3804                                __func__);
3805                return -EINVAL;
3806        }
3807
3808        if (state == USB3_LPM_U1 && timeout > USB3_LPM_U1_MAX_TIMEOUT &&
3809                        timeout != USB3_LPM_DEVICE_INITIATED) {
3810                dev_warn(&udev->dev, "Failed to set %s timeout to 0x%x, "
3811                                "which is a reserved value.\n",
3812                                usb3_lpm_names[state], timeout);
3813                return -EINVAL;
3814        }
3815
3816        ret = set_port_feature(udev->parent,
3817                        USB_PORT_LPM_TIMEOUT(timeout) | udev->portnum,
3818                        feature);
3819        if (ret < 0) {
3820                dev_warn(&udev->dev, "Failed to set %s timeout to 0x%x,"
3821                                "error code %i\n", usb3_lpm_names[state],
3822                                timeout, ret);
3823                return -EBUSY;
3824        }
3825        if (state == USB3_LPM_U1)
3826                udev->u1_params.timeout = timeout;
3827        else
3828                udev->u2_params.timeout = timeout;
3829        return 0;
3830}
3831
3832/*
3833 * Enable the hub-initiated U1/U2 idle timeouts, and enable device-initiated
3834 * U1/U2 entry.
3835 *
3836 * We will attempt to enable U1 or U2, but there are no guarantees that the
3837 * control transfers to set the hub timeout or enable device-initiated U1/U2
3838 * will be successful.
3839 *
3840 * If we cannot set the parent hub U1/U2 timeout, we attempt to let the xHCI
3841 * driver know about it.  If that call fails, it should be harmless, and just
3842 * take up more slightly more bus bandwidth for unnecessary U1/U2 exit latency.
3843 */
3844static void usb_enable_link_state(struct usb_hcd *hcd, struct usb_device *udev,
3845                enum usb3_link_state state)
3846{
3847        int timeout, ret;
3848        __u8 u1_mel = udev->bos->ss_cap->bU1devExitLat;
3849        __le16 u2_mel = udev->bos->ss_cap->bU2DevExitLat;
3850
3851        /* If the device says it doesn't have *any* exit latency to come out of
3852         * U1 or U2, it's probably lying.  Assume it doesn't implement that link
3853         * state.
3854         */
3855        if ((state == USB3_LPM_U1 && u1_mel == 0) ||
3856                        (state == USB3_LPM_U2 && u2_mel == 0))
3857                return;
3858
3859        /*
3860         * First, let the device know about the exit latencies
3861         * associated with the link state we're about to enable.
3862         */
3863        ret = usb_req_set_sel(udev, state);
3864        if (ret < 0) {
3865                dev_warn(&udev->dev, "Set SEL for device-initiated %s failed.\n",
3866                                usb3_lpm_names[state]);
3867                return;
3868        }
3869
3870        /* We allow the host controller to set the U1/U2 timeout internally
3871         * first, so that it can change its schedule to account for the
3872         * additional latency to send data to a device in a lower power
3873         * link state.
3874         */
3875        timeout = hcd->driver->enable_usb3_lpm_timeout(hcd, udev, state);
3876
3877        /* xHCI host controller doesn't want to enable this LPM state. */
3878        if (timeout == 0)
3879                return;
3880
3881        if (timeout < 0) {
3882                dev_warn(&udev->dev, "Could not enable %s link state, "
3883                                "xHCI error %i.\n", usb3_lpm_names[state],
3884                                timeout);
3885                return;
3886        }
3887
3888        if (usb_set_lpm_timeout(udev, state, timeout)) {
3889                /* If we can't set the parent hub U1/U2 timeout,
3890                 * device-initiated LPM won't be allowed either, so let the xHCI
3891                 * host know that this link state won't be enabled.
3892                 */
3893                hcd->driver->disable_usb3_lpm_timeout(hcd, udev, state);
3894        } else {
3895                /* Only a configured device will accept the Set Feature
3896                 * U1/U2_ENABLE
3897                 */
3898                if (udev->actconfig)
3899                        usb_set_device_initiated_lpm(udev, state, true);
3900
3901                /* As soon as usb_set_lpm_timeout(timeout) returns 0, the
3902                 * hub-initiated LPM is enabled. Thus, LPM is enabled no
3903                 * matter the result of usb_set_device_initiated_lpm().
3904                 * The only difference is whether device is able to initiate
3905                 * LPM.
3906                 */
3907                if (state == USB3_LPM_U1)
3908                        udev->usb3_lpm_u1_enabled = 1;
3909                else if (state == USB3_LPM_U2)
3910                        udev->usb3_lpm_u2_enabled = 1;
3911        }
3912}
3913
3914/*
3915 * Disable the hub-initiated U1/U2 idle timeouts, and disable device-initiated
3916 * U1/U2 entry.
3917 *
3918 * If this function returns -EBUSY, the parent hub will still allow U1/U2 entry.
3919 * If zero is returned, the parent will not allow the link to go into U1/U2.
3920 *
3921 * If zero is returned, device-initiated U1/U2 entry may still be enabled, but
3922 * it won't have an effect on the bus link state because the parent hub will
3923 * still disallow device-initiated U1/U2 entry.
3924 *
3925 * If zero is returned, the xHCI host controller may still think U1/U2 entry is
3926 * possible.  The result will be slightly more bus bandwidth will be taken up
3927 * (to account for U1/U2 exit latency), but it should be harmless.
3928 */
3929static int usb_disable_link_state(struct usb_hcd *hcd, struct usb_device *udev,
3930                enum usb3_link_state state)
3931{
3932        switch (state) {
3933        case USB3_LPM_U1:
3934        case USB3_LPM_U2:
3935                break;
3936        default:
3937                dev_warn(&udev->dev, "%s: Can't disable non-U1 or U2 state.\n",
3938                                __func__);
3939                return -EINVAL;
3940        }
3941
3942        if (usb_set_lpm_timeout(udev, state, 0))
3943                return -EBUSY;
3944
3945        usb_set_device_initiated_lpm(udev, state, false);
3946
3947        if (hcd->driver->disable_usb3_lpm_timeout(hcd, udev, state))
3948                dev_warn(&udev->dev, "Could not disable xHCI %s timeout, "
3949                                "bus schedule bandwidth may be impacted.\n",
3950                                usb3_lpm_names[state]);
3951
3952        /* As soon as usb_set_lpm_timeout(0) return 0, hub initiated LPM
3953         * is disabled. Hub will disallows link to enter U1/U2 as well,
3954         * even device is initiating LPM. Hence LPM is disabled if hub LPM
3955         * timeout set to 0, no matter device-initiated LPM is disabled or
3956         * not.
3957         */
3958        if (state == USB3_LPM_U1)
3959                udev->usb3_lpm_u1_enabled = 0;
3960        else if (state == USB3_LPM_U2)
3961                udev->usb3_lpm_u2_enabled = 0;
3962
3963        return 0;
3964}
3965
3966/*
3967 * Disable hub-initiated and device-initiated U1 and U2 entry.
3968 * Caller must own the bandwidth_mutex.
3969 *
3970 * This will call usb_enable_lpm() on failure, which will decrement
3971 * lpm_disable_count, and will re-enable LPM if lpm_disable_count reaches zero.
3972 */
3973int usb_disable_lpm(struct usb_device *udev)
3974{
3975        struct usb_hcd *hcd;
3976
3977        if (!udev || !udev->parent ||
3978                        udev->speed < USB_SPEED_SUPER ||
3979                        !udev->lpm_capable ||
3980                        udev->state < USB_STATE_DEFAULT)
3981                return 0;
3982
3983        hcd = bus_to_hcd(udev->bus);
3984        if (!hcd || !hcd->driver->disable_usb3_lpm_timeout)
3985                return 0;
3986
3987        udev->lpm_disable_count++;
3988        if ((udev->u1_params.timeout == 0 && udev->u2_params.timeout == 0))
3989                return 0;
3990
3991        /* If LPM is enabled, attempt to disable it. */
3992        if (usb_disable_link_state(hcd, udev, USB3_LPM_U1))
3993                goto enable_lpm;
3994        if (usb_disable_link_state(hcd, udev, USB3_LPM_U2))
3995                goto enable_lpm;
3996
3997        return 0;
3998
3999enable_lpm:
4000        usb_enable_lpm(udev);
4001        return -EBUSY;
4002}
4003EXPORT_SYMBOL_GPL(usb_disable_lpm);
4004
4005/* Grab the bandwidth_mutex before calling usb_disable_lpm() */
4006int usb_unlocked_disable_lpm(struct usb_device *udev)
4007{
4008        struct usb_hcd *hcd = bus_to_hcd(udev->bus);
4009        int ret;
4010
4011        if (!hcd)
4012                return -EINVAL;
4013
4014        mutex_lock(hcd->bandwidth_mutex);
4015        ret = usb_disable_lpm(udev);
4016        mutex_unlock(hcd->bandwidth_mutex);
4017
4018        return ret;
4019}
4020EXPORT_SYMBOL_GPL(usb_unlocked_disable_lpm);
4021
4022/*
4023 * Attempt to enable device-initiated and hub-initiated U1 and U2 entry.  The
4024 * xHCI host policy may prevent U1 or U2 from being enabled.
4025 *
4026 * Other callers may have disabled link PM, so U1 and U2 entry will be disabled
4027 * until the lpm_disable_count drops to zero.  Caller must own the
4028 * bandwidth_mutex.
4029 */
4030void usb_enable_lpm(struct usb_device *udev)
4031{
4032        struct usb_hcd *hcd;
4033        struct usb_hub *hub;
4034        struct usb_port *port_dev;
4035
4036        if (!udev || !udev->parent ||
4037                        udev->speed < USB_SPEED_SUPER ||
4038                        !udev->lpm_capable ||
4039                        udev->state < USB_STATE_DEFAULT)
4040                return;
4041
4042        udev->lpm_disable_count--;
4043        hcd = bus_to_hcd(udev->bus);
4044        /* Double check that we can both enable and disable LPM.
4045         * Device must be configured to accept set feature U1/U2 timeout.
4046         */
4047        if (!hcd || !hcd->driver->enable_usb3_lpm_timeout ||
4048                        !hcd->driver->disable_usb3_lpm_timeout)
4049                return;
4050
4051        if (udev->lpm_disable_count > 0)
4052                return;
4053
4054        hub = usb_hub_to_struct_hub(udev->parent);
4055        if (!hub)
4056                return;
4057
4058        port_dev = hub->ports[udev->portnum - 1];
4059
4060        if (port_dev->usb3_lpm_u1_permit)
4061                usb_enable_link_state(hcd, udev, USB3_LPM_U1);
4062
4063        if (port_dev->usb3_lpm_u2_permit)
4064                usb_enable_link_state(hcd, udev, USB3_LPM_U2);
4065}
4066EXPORT_SYMBOL_GPL(usb_enable_lpm);
4067
4068/* Grab the bandwidth_mutex before calling usb_enable_lpm() */
4069void usb_unlocked_enable_lpm(struct usb_device *udev)
4070{
4071        struct usb_hcd *hcd = bus_to_hcd(udev->bus);
4072
4073        if (!hcd)
4074                return;
4075
4076        mutex_lock(hcd->bandwidth_mutex);
4077        usb_enable_lpm(udev);
4078        mutex_unlock(hcd->bandwidth_mutex);
4079}
4080EXPORT_SYMBOL_GPL(usb_unlocked_enable_lpm);
4081
4082/* usb3 devices use U3 for disabled, make sure remote wakeup is disabled */
4083static void hub_usb3_port_prepare_disable(struct usb_hub *hub,
4084                                          struct usb_port *port_dev)
4085{
4086        struct usb_device *udev = port_dev->child;
4087        int ret;
4088
4089        if (udev && udev->port_is_suspended && udev->do_remote_wakeup) {
4090                ret = hub_set_port_link_state(hub, port_dev->portnum,
4091                                              USB_SS_PORT_LS_U0);
4092                if (!ret) {
4093                        msleep(USB_RESUME_TIMEOUT);
4094                        ret = usb_disable_remote_wakeup(udev);
4095                }
4096                if (ret)
4097                        dev_warn(&udev->dev,
4098                                 "Port disable: can't disable remote wake\n");
4099                udev->do_remote_wakeup = 0;
4100        }
4101}
4102
4103#else   /* CONFIG_PM */
4104
4105#define hub_suspend             NULL
4106#define hub_resume              NULL
4107#define hub_reset_resume        NULL
4108
4109static inline void hub_usb3_port_prepare_disable(struct usb_hub *hub,
4110                                                 struct usb_port *port_dev) { }
4111
4112int usb_disable_lpm(struct usb_device *udev)
4113{
4114        return 0;
4115}
4116EXPORT_SYMBOL_GPL(usb_disable_lpm);
4117
4118void usb_enable_lpm(struct usb_device *udev) { }
4119EXPORT_SYMBOL_GPL(usb_enable_lpm);
4120
4121int usb_unlocked_disable_lpm(struct usb_device *udev)
4122{
4123        return 0;
4124}
4125EXPORT_SYMBOL_GPL(usb_unlocked_disable_lpm);
4126
4127void usb_unlocked_enable_lpm(struct usb_device *udev) { }
4128EXPORT_SYMBOL_GPL(usb_unlocked_enable_lpm);
4129
4130int usb_disable_ltm(struct usb_device *udev)
4131{
4132        return 0;
4133}
4134EXPORT_SYMBOL_GPL(usb_disable_ltm);
4135
4136void usb_enable_ltm(struct usb_device *udev) { }
4137EXPORT_SYMBOL_GPL(usb_enable_ltm);
4138
4139static int hub_handle_remote_wakeup(struct usb_hub *hub, unsigned int port,
4140                u16 portstatus, u16 portchange)
4141{
4142        return 0;
4143}
4144
4145#endif  /* CONFIG_PM */
4146
4147/*
4148 * USB-3 does not have a similar link state as USB-2 that will avoid negotiating
4149 * a connection with a plugged-in cable but will signal the host when the cable
4150 * is unplugged. Disable remote wake and set link state to U3 for USB-3 devices
4151 */
4152static int hub_port_disable(struct usb_hub *hub, int port1, int set_state)
4153{
4154        struct usb_port *port_dev = hub->ports[port1 - 1];
4155        struct usb_device *hdev = hub->hdev;
4156        int ret = 0;
4157
4158        if (!hub->error) {
4159                if (hub_is_superspeed(hub->hdev)) {
4160                        hub_usb3_port_prepare_disable(hub, port_dev);
4161                        ret = hub_set_port_link_state(hub, port_dev->portnum,
4162                                                      USB_SS_PORT_LS_U3);
4163                } else {
4164                        ret = usb_clear_port_feature(hdev, port1,
4165                                        USB_PORT_FEAT_ENABLE);
4166                }
4167        }
4168        if (port_dev->child && set_state)
4169                usb_set_device_state(port_dev->child, USB_STATE_NOTATTACHED);
4170        if (ret && ret != -ENODEV)
4171                dev_err(&port_dev->dev, "cannot disable (err = %d)\n", ret);
4172        return ret;
4173}
4174
4175
4176/* USB 2.0 spec, 7.1.7.3 / fig 7-29:
4177 *
4178 * Between connect detection and reset signaling there must be a delay
4179 * of 100ms at least for debounce and power-settling.  The corresponding
4180 * timer shall restart whenever the downstream port detects a disconnect.
4181 *
4182 * Apparently there are some bluetooth and irda-dongles and a number of
4183 * low-speed devices for which this debounce period may last over a second.
4184 * Not covered by the spec - but easy to deal with.
4185 *
4186 * This implementation uses a 1500ms total debounce timeout; if the
4187 * connection isn't stable by then it returns -ETIMEDOUT.  It checks
4188 * every 25ms for transient disconnects.  When the port status has been
4189 * unchanged for 100ms it returns the port status.
4190 */
4191int hub_port_debounce(struct usb_hub *hub, int port1, bool must_be_connected)
4192{
4193        int ret;
4194        u16 portchange, portstatus;
4195        unsigned connection = 0xffff;
4196        int total_time, stable_time = 0;
4197        struct usb_port *port_dev = hub->ports[port1 - 1];
4198
4199        for (total_time = 0; ; total_time += HUB_DEBOUNCE_STEP) {
4200                ret = hub_port_status(hub, port1, &portstatus, &portchange);
4201                if (ret < 0)
4202                        return ret;
4203
4204                if (!(portchange & USB_PORT_STAT_C_CONNECTION) &&
4205                     (portstatus & USB_PORT_STAT_CONNECTION) == connection) {
4206                        if (!must_be_connected ||
4207                             (connection == USB_PORT_STAT_CONNECTION))
4208                                stable_time += HUB_DEBOUNCE_STEP;
4209                        if (stable_time >= HUB_DEBOUNCE_STABLE)
4210                                break;
4211                } else {
4212                        stable_time = 0;
4213                        connection = portstatus & USB_PORT_STAT_CONNECTION;
4214                }
4215
4216                if (portchange & USB_PORT_STAT_C_CONNECTION) {
4217                        usb_clear_port_feature(hub->hdev, port1,
4218                                        USB_PORT_FEAT_C_CONNECTION);
4219                }
4220
4221                if (total_time >= HUB_DEBOUNCE_TIMEOUT)
4222                        break;
4223                msleep(HUB_DEBOUNCE_STEP);
4224        }
4225
4226        dev_dbg(&port_dev->dev, "debounce total %dms stable %dms status 0x%x\n",
4227                        total_time, stable_time, portstatus);
4228
4229        if (stable_time < HUB_DEBOUNCE_STABLE)
4230                return -ETIMEDOUT;
4231        return portstatus;
4232}
4233
4234void usb_ep0_reinit(struct usb_device *udev)
4235{
4236        usb_disable_endpoint(udev, 0 + USB_DIR_IN, true);
4237        usb_disable_endpoint(udev, 0 + USB_DIR_OUT, true);
4238        usb_enable_endpoint(udev, &udev->ep0, true);
4239}
4240EXPORT_SYMBOL_GPL(usb_ep0_reinit);
4241
4242#define usb_sndaddr0pipe()      (PIPE_CONTROL << 30)
4243#define usb_rcvaddr0pipe()      ((PIPE_CONTROL << 30) | USB_DIR_IN)
4244
4245static int hub_set_address(struct usb_device *udev, int devnum)
4246{
4247        int retval;
4248        struct usb_hcd *hcd = bus_to_hcd(udev->bus);
4249
4250        /*
4251         * The host controller will choose the device address,
4252         * instead of the core having chosen it earlier
4253         */
4254        if (!hcd->driver->address_device && devnum <= 1)
4255                return -EINVAL;
4256        if (udev->state == USB_STATE_ADDRESS)
4257                return 0;
4258        if (udev->state != USB_STATE_DEFAULT)
4259                return -EINVAL;
4260        if (hcd->driver->address_device)
4261                retval = hcd->driver->address_device(hcd, udev);
4262        else
4263                retval = usb_control_msg(udev, usb_sndaddr0pipe(),
4264                                USB_REQ_SET_ADDRESS, 0, devnum, 0,
4265                                NULL, 0, USB_CTRL_SET_TIMEOUT);
4266        if (retval == 0) {
4267                update_devnum(udev, devnum);
4268                /* Device now using proper address. */
4269                usb_set_device_state(udev, USB_STATE_ADDRESS);
4270                usb_ep0_reinit(udev);
4271        }
4272        return retval;
4273}
4274
4275/*
4276 * There are reports of USB 3.0 devices that say they support USB 2.0 Link PM
4277 * when they're plugged into a USB 2.0 port, but they don't work when LPM is
4278 * enabled.
4279 *
4280 * Only enable USB 2.0 Link PM if the port is internal (hardwired), or the
4281 * device says it supports the new USB 2.0 Link PM errata by setting the BESL
4282 * support bit in the BOS descriptor.
4283 */
4284static void hub_set_initial_usb2_lpm_policy(struct usb_device *udev)
4285{
4286        struct usb_hub *hub = usb_hub_to_struct_hub(udev->parent);
4287        int connect_type = USB_PORT_CONNECT_TYPE_UNKNOWN;
4288
4289        if (!udev->usb2_hw_lpm_capable || !udev->bos)
4290                return;
4291
4292        if (hub)
4293                connect_type = hub->ports[udev->portnum - 1]->connect_type;
4294
4295        if ((udev->bos->ext_cap->bmAttributes & cpu_to_le32(USB_BESL_SUPPORT)) ||
4296                        connect_type == USB_PORT_CONNECT_TYPE_HARD_WIRED) {
4297                udev->usb2_hw_lpm_allowed = 1;
4298                usb_set_usb2_hardware_lpm(udev, 1);
4299        }
4300}
4301
4302static int hub_enable_device(struct usb_device *udev)
4303{
4304        struct usb_hcd *hcd = bus_to_hcd(udev->bus);
4305
4306        if (!hcd->driver->enable_device)
4307                return 0;
4308        if (udev->state == USB_STATE_ADDRESS)
4309                return 0;
4310        if (udev->state != USB_STATE_DEFAULT)
4311                return -EINVAL;
4312
4313        return hcd->driver->enable_device(hcd, udev);
4314}
4315
4316/* Reset device, (re)assign address, get device descriptor.
4317 * Device connection must be stable, no more debouncing needed.
4318 * Returns device in USB_STATE_ADDRESS, except on error.
4319 *
4320 * If this is called for an already-existing device (as part of
4321 * usb_reset_and_verify_device), the caller must own the device lock and
4322 * the port lock.  For a newly detected device that is not accessible
4323 * through any global pointers, it's not necessary to lock the device,
4324 * but it is still necessary to lock the port.
4325 */
4326static int
4327hub_port_init(struct usb_hub *hub, struct usb_device *udev, int port1,
4328                int retry_counter)
4329{
4330        struct usb_device       *hdev = hub->hdev;
4331        struct usb_hcd          *hcd = bus_to_hcd(hdev->bus);
4332        int                     retries, operations, retval, i;
4333        unsigned                delay = HUB_SHORT_RESET_TIME;
4334        enum usb_device_speed   oldspeed = udev->speed;
4335        const char              *speed;
4336        int                     devnum = udev->devnum;
4337
4338        /* root hub ports have a slightly longer reset period
4339         * (from USB 2.0 spec, section 7.1.7.5)
4340         */
4341        if (!hdev->parent) {
4342                delay = HUB_ROOT_RESET_TIME;
4343                if (port1 == hdev->bus->otg_port)
4344                        hdev->bus->b_hnp_enable = 0;
4345        }
4346
4347        /* Some low speed devices have problems with the quick delay, so */
4348        /*  be a bit pessimistic with those devices. RHbug #23670 */
4349        if (oldspeed == USB_SPEED_LOW)
4350                delay = HUB_LONG_RESET_TIME;
4351
4352        mutex_lock(hcd->address0_mutex);
4353
4354        /* Reset the device; full speed may morph to high speed */
4355        /* FIXME a USB 2.0 device may morph into SuperSpeed on reset. */
4356        retval = hub_port_reset(hub, port1, udev, delay, false);
4357        if (retval < 0)         /* error or disconnect */
4358                goto fail;
4359        /* success, speed is known */
4360
4361        retval = -ENODEV;
4362#if defined(CONFIG_MACH_AR7100) || defined(CONFIG_MACH_AR7240) || defined(CONFIG_LANTIQ)
4363        ap_usb_led_on();
4364#endif
4365        /* Don't allow speed changes at reset, except usb 3.0 to faster */
4366        if (oldspeed != USB_SPEED_UNKNOWN && oldspeed != udev->speed &&
4367            !(oldspeed == USB_SPEED_SUPER && udev->speed > oldspeed)) {
4368                dev_dbg(&udev->dev, "device reset changed speed!\n");
4369                goto fail;
4370        }
4371        oldspeed = udev->speed;
4372
4373        /* USB 2.0 section 5.5.3 talks about ep0 maxpacket ...
4374         * it's fixed size except for full speed devices.
4375         * For Wireless USB devices, ep0 max packet is always 512 (tho
4376         * reported as 0xff in the device descriptor). WUSB1.0[4.8.1].
4377         */
4378        switch (udev->speed) {
4379        case USB_SPEED_SUPER_PLUS:
4380        case USB_SPEED_SUPER:
4381        case USB_SPEED_WIRELESS:        /* fixed at 512 */
4382                udev->ep0.desc.wMaxPacketSize = cpu_to_le16(512);
4383                break;
4384        case USB_SPEED_HIGH:            /* fixed at 64 */
4385                udev->ep0.desc.wMaxPacketSize = cpu_to_le16(64);
4386                break;
4387        case USB_SPEED_FULL:            /* 8, 16, 32, or 64 */
4388                /* to determine the ep0 maxpacket size, try to read
4389                 * the device descriptor to get bMaxPacketSize0 and
4390                 * then correct our initial guess.
4391                 */
4392                udev->ep0.desc.wMaxPacketSize = cpu_to_le16(64);
4393                break;
4394        case USB_SPEED_LOW:             /* fixed at 8 */
4395                udev->ep0.desc.wMaxPacketSize = cpu_to_le16(8);
4396                break;
4397        default:
4398                goto fail;
4399        }
4400
4401        if (udev->speed == USB_SPEED_WIRELESS)
4402                speed = "variable speed Wireless";
4403        else
4404                speed = usb_speed_string(udev->speed);
4405
4406        if (udev->speed < USB_SPEED_SUPER)
4407                dev_info(&udev->dev,
4408                                "%s %s USB device number %d using %s\n",
4409                                (udev->config) ? "reset" : "new", speed,
4410                                devnum, udev->bus->controller->driver->name);
4411
4412        /* Set up TT records, if needed  */
4413        if (hdev->tt) {
4414                udev->tt = hdev->tt;
4415                udev->ttport = hdev->ttport;
4416        } else if (udev->speed != USB_SPEED_HIGH
4417                        && hdev->speed == USB_SPEED_HIGH) {
4418/*              if (!hub->tt.hub) {
4419                        dev_err(&udev->dev, "parent hub has no TT\n");
4420                        retval = -EINVAL;
4421                        goto fail;
4422                }*/
4423                udev->tt = &hub->tt;
4424                udev->ttport = port1;
4425        }
4426
4427        /* Why interleave GET_DESCRIPTOR and SET_ADDRESS this way?
4428         * Because device hardware and firmware is sometimes buggy in
4429         * this area, and this is how Linux has done it for ages.
4430         * Change it cautiously.
4431         *
4432         * NOTE:  If use_new_scheme() is true we will start by issuing
4433         * a 64-byte GET_DESCRIPTOR request.  This is what Windows does,
4434         * so it may help with some non-standards-compliant devices.
4435         * Otherwise we start with SET_ADDRESS and then try to read the
4436         * first 8 bytes of the device descriptor to get the ep0 maxpacket
4437         * value.
4438         */
4439        for (retries = 0; retries < GET_DESCRIPTOR_TRIES; (++retries, msleep(100))) {
4440                bool did_new_scheme = false;
4441
4442                if (use_new_scheme(udev, retry_counter)) {
4443                        struct usb_device_descriptor *buf;
4444                        int r = 0;
4445
4446                        did_new_scheme = true;
4447                        retval = hub_enable_device(udev);
4448                        if (retval < 0) {
4449                                dev_err(&udev->dev,
4450                                        "hub failed to enable device, error %d\n",
4451                                        retval);
4452                                goto fail;
4453                        }
4454
4455#define GET_DESCRIPTOR_BUFSIZE  64
4456                        buf = kmalloc(GET_DESCRIPTOR_BUFSIZE, GFP_NOIO);
4457                        if (!buf) {
4458                                retval = -ENOMEM;
4459                                continue;
4460                        }
4461
4462                        /* Retry on all errors; some devices are flakey.
4463                         * 255 is for WUSB devices, we actually need to use
4464                         * 512 (WUSB1.0[4.8.1]).
4465                         */
4466                        for (operations = 0; operations < 10; ++operations) {
4467                                buf->bMaxPacketSize0 = 0;
4468                                r = usb_control_msg(udev, usb_rcvaddr0pipe(),
4469                                        USB_REQ_GET_DESCRIPTOR, USB_DIR_IN,
4470                                        USB_DT_DEVICE << 8, 0,
4471                                        buf, GET_DESCRIPTOR_BUFSIZE,
4472                                        initial_descriptor_timeout);
4473                                switch (buf->bMaxPacketSize0) {
4474                                case 8: case 16: case 32: case 64: case 255:
4475                                        if (buf->bDescriptorType ==
4476                                                        USB_DT_DEVICE) {
4477                                                r = 0;
4478                                                break;
4479                                        }
4480                                        /* FALL THROUGH */
4481                                default:
4482                                        if (r == 0) {
4483                                                r = -EPROTO;
4484                                                continue;
4485                                        }
4486                                        break;
4487                                }
4488                                /*
4489                                 * Some devices time out if they are powered on
4490                                 * when already connected. They need a second
4491                                 * reset. But only on the first attempt,
4492                                 * lest we get into a time out/reset loop
4493                                 */
4494                                if (r == 0  || (r == -ETIMEDOUT && retries == 0))
4495                                        break;
4496                        }
4497                        udev->descriptor.bMaxPacketSize0 =
4498                                        buf->bMaxPacketSize0;
4499                        kfree(buf);
4500
4501                        retval = hub_port_reset(hub, port1, udev, delay, false);
4502                        if (retval < 0)         /* error or disconnect */
4503                                goto fail;
4504                        if (oldspeed != udev->speed) {
4505                                dev_dbg(&udev->dev,
4506                                        "device reset changed speed!\n");
4507                                retval = -ENODEV;
4508                                goto fail;
4509                        }
4510                        if (r) {
4511                                if (r != -ENODEV)
4512                                        dev_err(&udev->dev, "device descriptor read/64, error %d\n",
4513                                                        r);
4514                                retval = -EMSGSIZE;
4515                                continue;
4516                        }
4517#undef GET_DESCRIPTOR_BUFSIZE
4518                }
4519
4520                /*
4521                 * If device is WUSB, we already assigned an
4522                 * unauthorized address in the Connect Ack sequence;
4523                 * authorization will assign the final address.
4524                 */
4525                if (udev->wusb == 0) {
4526                        for (operations = 0; operations < SET_ADDRESS_TRIES; ++operations) {
4527                                retval = hub_set_address(udev, devnum);
4528                                if (retval >= 0)
4529                                        break;
4530                                msleep(200);
4531                        }
4532                        if (retval < 0) {
4533                                if (retval != -ENODEV)
4534                                        dev_err(&udev->dev, "device not accepting address %d, error %d\n",
4535                                                        devnum, retval);
4536                                goto fail;
4537                        }
4538                        if (udev->speed >= USB_SPEED_SUPER) {
4539                                devnum = udev->devnum;
4540                                dev_info(&udev->dev,
4541                                                "%s SuperSpeed%s USB device number %d using %s\n",
4542                                                (udev->config) ? "reset" : "new",
4543                                         (udev->speed == USB_SPEED_SUPER_PLUS) ? "Plus" : "",
4544                                                devnum, udev->bus->controller->driver->name);
4545                        }
4546
4547                        /* cope with hardware quirkiness:
4548                         *  - let SET_ADDRESS settle, some device hardware wants it
4549                         *  - read ep0 maxpacket even for high and low speed,
4550                         */
4551                        msleep(10);
4552                        /* use_new_scheme() checks the speed which may have
4553                         * changed since the initial look so we cache the result
4554                         * in did_new_scheme
4555                         */
4556                        if (did_new_scheme)
4557                                break;
4558                }
4559
4560                retval = usb_get_device_descriptor(udev, 8);
4561                if (retval < 8) {
4562                        if (retval != -ENODEV)
4563                                dev_err(&udev->dev,
4564                                        "device descriptor read/8, error %d\n",
4565                                        retval);
4566                        if (retval >= 0)
4567                                retval = -EMSGSIZE;
4568                } else {
4569                        retval = 0;
4570                        break;
4571                }
4572        }
4573        if (retval)
4574                goto fail;
4575
4576        /*
4577         * Some superspeed devices have finished the link training process
4578         * and attached to a superspeed hub port, but the device descriptor
4579         * got from those devices show they aren't superspeed devices. Warm
4580         * reset the port attached by the devices can fix them.
4581         */
4582        if ((udev->speed >= USB_SPEED_SUPER) &&
4583                        (le16_to_cpu(udev->descriptor.bcdUSB) < 0x0300)) {
4584                dev_err(&udev->dev, "got a wrong device descriptor, "
4585                                "warm reset device\n");
4586                hub_port_reset(hub, port1, udev,
4587                                HUB_BH_RESET_TIME, true);
4588                retval = -EINVAL;
4589                goto fail;
4590        }
4591
4592        if (udev->descriptor.bMaxPacketSize0 == 0xff ||
4593                        udev->speed >= USB_SPEED_SUPER)
4594                i = 512;
4595        else
4596                i = udev->descriptor.bMaxPacketSize0;
4597        if (usb_endpoint_maxp(&udev->ep0.desc) != i) {
4598                if (udev->speed == USB_SPEED_LOW ||
4599                                !(i == 8 || i == 16 || i == 32 || i == 64)) {
4600                        dev_err(&udev->dev, "Invalid ep0 maxpacket: %d\n", i);
4601                        retval = -EMSGSIZE;
4602                        goto fail;
4603                }
4604                if (udev->speed == USB_SPEED_FULL)
4605                        dev_dbg(&udev->dev, "ep0 maxpacket = %d\n", i);
4606                else
4607                        dev_warn(&udev->dev, "Using ep0 maxpacket: %d\n", i);
4608                udev->ep0.desc.wMaxPacketSize = cpu_to_le16(i);
4609                usb_ep0_reinit(udev);
4610        }
4611
4612        retval = usb_get_device_descriptor(udev, USB_DT_DEVICE_SIZE);
4613        if (retval < (signed)sizeof(udev->descriptor)) {
4614                if (retval != -ENODEV)
4615                        dev_err(&udev->dev, "device descriptor read/all, error %d\n",
4616                                        retval);
4617                if (retval >= 0)
4618                        retval = -ENOMSG;
4619                goto fail;
4620        }
4621
4622        usb_detect_quirks(udev);
4623
4624        if (udev->wusb == 0 && le16_to_cpu(udev->descriptor.bcdUSB) >= 0x0201) {
4625                retval = usb_get_bos_descriptor(udev);
4626                if (!retval) {
4627                        udev->lpm_capable = usb_device_supports_lpm(udev);
4628                        usb_set_lpm_parameters(udev);
4629                }
4630        }
4631
4632        retval = 0;
4633        /* notify HCD that we have a device connected and addressed */
4634        if (hcd->driver->update_device)
4635                hcd->driver->update_device(hcd, udev);
4636        hub_set_initial_usb2_lpm_policy(udev);
4637fail:
4638        if (retval) {
4639                hub_port_disable(hub, port1, 0);
4640                update_devnum(udev, devnum);    /* for disconnect processing */
4641        }
4642        mutex_unlock(hcd->address0_mutex);
4643        return retval;
4644}
4645
4646static void
4647check_highspeed(struct usb_hub *hub, struct usb_device *udev, int port1)
4648{
4649        struct usb_qualifier_descriptor *qual;
4650        int                             status;
4651
4652        if (udev->quirks & USB_QUIRK_DEVICE_QUALIFIER)
4653                return;
4654
4655        qual = kmalloc(sizeof *qual, GFP_KERNEL);
4656        if (qual == NULL)
4657                return;
4658
4659        status = usb_get_descriptor(udev, USB_DT_DEVICE_QUALIFIER, 0,
4660                        qual, sizeof *qual);
4661        if (status == sizeof *qual) {
4662                dev_info(&udev->dev, "not running at top speed; "
4663                        "connect to a high speed hub\n");
4664                /* hub LEDs are probably harder to miss than syslog */
4665                if (hub->has_indicators) {
4666                        hub->indicator[port1-1] = INDICATOR_GREEN_BLINK;
4667                        queue_delayed_work(system_power_efficient_wq,
4668                                        &hub->leds, 0);
4669                }
4670        }
4671        kfree(qual);
4672}
4673
4674static unsigned
4675hub_power_remaining(struct usb_hub *hub)
4676{
4677        struct usb_device *hdev = hub->hdev;
4678        int remaining;
4679        int port1;
4680
4681        if (!hub->limited_power)
4682                return 0;
4683
4684        remaining = hdev->bus_mA - hub->descriptor->bHubContrCurrent;
4685        for (port1 = 1; port1 <= hdev->maxchild; ++port1) {
4686                struct usb_port *port_dev = hub->ports[port1 - 1];
4687                struct usb_device *udev = port_dev->child;
4688                unsigned unit_load;
4689                int delta;
4690
4691                if (!udev)
4692                        continue;
4693                if (hub_is_superspeed(udev))
4694                        unit_load = 150;
4695                else
4696                        unit_load = 100;
4697
4698                /*
4699                 * Unconfigured devices may not use more than one unit load,
4700                 * or 8mA for OTG ports
4701                 */
4702                if (udev->actconfig)
4703                        delta = usb_get_max_power(udev, udev->actconfig);
4704                else if (port1 != udev->bus->otg_port || hdev->parent)
4705                        delta = unit_load;
4706                else
4707                        delta = 8;
4708                if (delta > hub->mA_per_port)
4709                        dev_warn(&port_dev->dev, "%dmA is over %umA budget!\n",
4710                                        delta, hub->mA_per_port);
4711                remaining -= delta;
4712        }
4713        if (remaining < 0) {
4714                dev_warn(hub->intfdev, "%dmA over power budget!\n",
4715                        -remaining);
4716                remaining = 0;
4717        }
4718        return remaining;
4719}
4720
4721static void hub_port_connect(struct usb_hub *hub, int port1, u16 portstatus,
4722                u16 portchange)
4723{
4724        int status, i;
4725        unsigned unit_load;
4726        struct usb_device *hdev = hub->hdev;
4727        struct usb_hcd *hcd = bus_to_hcd(hdev->bus);
4728        struct usb_port *port_dev = hub->ports[port1 - 1];
4729        struct usb_device *udev = port_dev->child;
4730        static int unreliable_port = -1;
4731
4732        /* Disconnect any existing devices under this port */
4733        if (udev) {
4734                if (hcd->usb_phy && !hdev->parent)
4735                        usb_phy_notify_disconnect(hcd->usb_phy, udev->speed);
4736                usb_disconnect(&port_dev->child);
4737        }
4738
4739        /* We can forget about a "removed" device when there's a physical
4740         * disconnect or the connect status changes.
4741         */
4742        if (!(portstatus & USB_PORT_STAT_CONNECTION) ||
4743                        (portchange & USB_PORT_STAT_C_CONNECTION))
4744                clear_bit(port1, hub->removed_bits);
4745
4746        if (portchange & (USB_PORT_STAT_C_CONNECTION |
4747                                USB_PORT_STAT_C_ENABLE)) {
4748                status = hub_port_debounce_be_stable(hub, port1);
4749                if (status < 0) {
4750                        if (status != -ENODEV &&
4751                                port1 != unreliable_port &&
4752                                printk_ratelimit())
4753                                dev_err(&port_dev->dev, "connect-debounce failed\n");
4754                        portstatus &= ~USB_PORT_STAT_CONNECTION;
4755                        unreliable_port = port1;
4756                } else {
4757                        portstatus = status;
4758                }
4759        }
4760
4761        /* Return now if debouncing failed or nothing is connected or
4762         * the device was "removed".
4763         */
4764        if (!(portstatus & USB_PORT_STAT_CONNECTION) ||
4765                        test_bit(port1, hub->removed_bits)) {
4766
4767                /*
4768                 * maybe switch power back on (e.g. root hub was reset)
4769                 * but only if the port isn't owned by someone else.
4770                 */
4771                if (hub_is_port_power_switchable(hub)
4772                                && !port_is_power_on(hub, portstatus)
4773                                && !port_dev->port_owner)
4774                        set_port_feature(hdev, port1, USB_PORT_FEAT_POWER);
4775
4776                if (portstatus & USB_PORT_STAT_ENABLE)
4777                        goto done;
4778                return;
4779        }
4780        if (hub_is_superspeed(hub->hdev))
4781                unit_load = 150;
4782        else
4783                unit_load = 100;
4784
4785        status = 0;
4786        for (i = 0; i < SET_CONFIG_TRIES; i++) {
4787
4788                /* reallocate for each attempt, since references
4789                 * to the previous one can escape in various ways
4790                 */
4791                udev = usb_alloc_dev(hdev, hdev->bus, port1);
4792                if (!udev) {
4793                        dev_err(&port_dev->dev,
4794                                        "couldn't allocate usb_device\n");
4795                        goto done;
4796                }
4797
4798                usb_set_device_state(udev, USB_STATE_POWERED);
4799                udev->bus_mA = hub->mA_per_port;
4800                udev->level = hdev->level + 1;
4801                udev->wusb = hub_is_wusb(hub);
4802
4803                /* Devices connected to SuperSpeed hubs are USB 3.0 or later */
4804                if (hub_is_superspeed(hub->hdev))
4805                        udev->speed = USB_SPEED_SUPER;
4806                else
4807                        udev->speed = USB_SPEED_UNKNOWN;
4808
4809                choose_devnum(udev);
4810                if (udev->devnum <= 0) {
4811                        status = -ENOTCONN;     /* Don't retry */
4812                        goto loop;
4813                }
4814
4815                /* reset (non-USB 3.0 devices) and get descriptor */
4816                usb_lock_port(port_dev);
4817                status = hub_port_init(hub, udev, port1, i);
4818                usb_unlock_port(port_dev);
4819                if (status < 0)
4820                        goto loop;
4821
4822                if (udev->quirks & USB_QUIRK_DELAY_INIT)
4823                        msleep(1000);
4824
4825                /* consecutive bus-powered hubs aren't reliable; they can
4826                 * violate the voltage drop budget.  if the new child has
4827                 * a "powered" LED, users should notice we didn't enable it
4828                 * (without reading syslog), even without per-port LEDs
4829                 * on the parent.
4830                 */
4831                if (udev->descriptor.bDeviceClass == USB_CLASS_HUB
4832                                && udev->bus_mA <= unit_load) {
4833                        u16     devstat;
4834
4835                        status = usb_get_status(udev, USB_RECIP_DEVICE, 0,
4836                                        &devstat);
4837                        if (status) {
4838                                dev_dbg(&udev->dev, "get status %d ?\n", status);
4839                                goto loop_disable;
4840                        }
4841                        if ((devstat & (1 << USB_DEVICE_SELF_POWERED)) == 0) {
4842                                dev_err(&udev->dev,
4843                                        "can't connect bus-powered hub "
4844                                        "to this port\n");
4845                                if (hub->has_indicators) {
4846                                        hub->indicator[port1-1] =
4847                                                INDICATOR_AMBER_BLINK;
4848                                        queue_delayed_work(
4849                                                system_power_efficient_wq,
4850                                                &hub->leds, 0);
4851                                }
4852                                status = -ENOTCONN;     /* Don't retry */
4853                                goto loop_disable;
4854                        }
4855                }
4856
4857                /* check for devices running slower than they could */
4858                if (le16_to_cpu(udev->descriptor.bcdUSB) >= 0x0200
4859                                && udev->speed == USB_SPEED_FULL
4860                                && highspeed_hubs != 0)
4861                        check_highspeed(hub, udev, port1);
4862
4863                /* Store the parent's children[] pointer.  At this point
4864                 * udev becomes globally accessible, although presumably
4865                 * no one will look at it until hdev is unlocked.
4866                 */
4867                status = 0;
4868
4869                mutex_lock(&usb_port_peer_mutex);
4870
4871                /* We mustn't add new devices if the parent hub has
4872                 * been disconnected; we would race with the
4873                 * recursively_mark_NOTATTACHED() routine.
4874                 */
4875                spin_lock_irq(&device_state_lock);
4876                if (hdev->state == USB_STATE_NOTATTACHED)
4877                        status = -ENOTCONN;
4878                else
4879                        port_dev->child = udev;
4880                spin_unlock_irq(&device_state_lock);
4881                mutex_unlock(&usb_port_peer_mutex);
4882
4883                /* Run it through the hoops (find a driver, etc) */
4884                if (!status) {
4885                        status = usb_new_device(udev);
4886                        if (status) {
4887                                mutex_lock(&usb_port_peer_mutex);
4888                                spin_lock_irq(&device_state_lock);
4889                                port_dev->child = NULL;
4890                                spin_unlock_irq(&device_state_lock);
4891                                mutex_unlock(&usb_port_peer_mutex);
4892                        } else {
4893                                if (hcd->usb_phy && !hdev->parent)
4894                                        usb_phy_notify_connect(hcd->usb_phy,
4895                                                        udev->speed);
4896                        }
4897                }
4898
4899                if (status)
4900                        goto loop_disable;
4901
4902                status = hub_power_remaining(hub);
4903                if (status)
4904                        dev_dbg(hub->intfdev, "%dmA power budget left\n", status);
4905
4906                return;
4907
4908loop_disable:
4909                hub_port_disable(hub, port1, 1);
4910loop:
4911                usb_ep0_reinit(udev);
4912                release_devnum(udev);
4913                hub_free_dev(udev);
4914                usb_put_dev(udev);
4915                if ((status == -ENOTCONN) || (status == -ENOTSUPP))
4916                        break;
4917        }
4918        if (hub->hdev->parent ||
4919                        !hcd->driver->port_handed_over ||
4920                        !(hcd->driver->port_handed_over)(hcd, port1)) {
4921                if (status != -ENOTCONN && status != -ENODEV)
4922                        dev_err(&port_dev->dev,
4923                                        "unable to enumerate USB device\n");
4924        }
4925
4926done:
4927        hub_port_disable(hub, port1, 1);
4928        if (hcd->driver->relinquish_port && !hub->hdev->parent)
4929                hcd->driver->relinquish_port(hcd, port1);
4930
4931}
4932
4933/* Handle physical or logical connection change events.
4934 * This routine is called when:
4935 *      a port connection-change occurs;
4936 *      a port enable-change occurs (often caused by EMI);
4937 *      usb_reset_and_verify_device() encounters changed descriptors (as from
4938 *              a firmware download)
4939 * caller already locked the hub
4940 */
4941static void hub_port_connect_change(struct usb_hub *hub, int port1,
4942                                        u16 portstatus, u16 portchange)
4943                __must_hold(&port_dev->status_lock)
4944{
4945        struct usb_port *port_dev = hub->ports[port1 - 1];
4946        struct usb_device *udev = port_dev->child;
4947        int status = -ENODEV;
4948
4949        dev_dbg(&port_dev->dev, "status %04x, change %04x, %s\n", portstatus,
4950                        portchange, portspeed(hub, portstatus));
4951
4952        if (hub->has_indicators) {
4953                set_port_led(hub, port1, HUB_LED_AUTO);
4954                hub->indicator[port1-1] = INDICATOR_AUTO;
4955        }
4956
4957#ifdef  CONFIG_USB_OTG
4958        /* during HNP, don't repeat the debounce */
4959        if (hub->hdev->bus->is_b_host)
4960                portchange &= ~(USB_PORT_STAT_C_CONNECTION |
4961                                USB_PORT_STAT_C_ENABLE);
4962#endif
4963
4964        /* Try to resuscitate an existing device */
4965        if ((portstatus & USB_PORT_STAT_CONNECTION) && udev &&
4966                        udev->state != USB_STATE_NOTATTACHED) {
4967                if (portstatus & USB_PORT_STAT_ENABLE) {
4968                        status = 0;             /* Nothing to do */
4969#ifdef CONFIG_PM
4970                } else if (udev->state == USB_STATE_SUSPENDED &&
4971                                udev->persist_enabled) {
4972                        /* For a suspended device, treat this as a
4973                         * remote wakeup event.
4974                         */
4975                        usb_unlock_port(port_dev);
4976                        status = usb_remote_wakeup(udev);
4977                        usb_lock_port(port_dev);
4978#endif
4979                } else {
4980                        /* Don't resuscitate */;
4981                }
4982        }
4983        clear_bit(port1, hub->change_bits);
4984
4985        /* successfully revalidated the connection */
4986        if (status == 0)
4987                return;
4988
4989        usb_unlock_port(port_dev);
4990        hub_port_connect(hub, port1, portstatus, portchange);
4991        usb_lock_port(port_dev);
4992}
4993
4994static void port_event(struct usb_hub *hub, int port1)
4995                __must_hold(&port_dev->status_lock)
4996{
4997        int connect_change;
4998        struct usb_port *port_dev = hub->ports[port1 - 1];
4999        struct usb_device *udev = port_dev->child;
5000        struct usb_device *hdev = hub->hdev;
5001        u16 portstatus, portchange;
5002
5003        connect_change = test_bit(port1, hub->change_bits);
5004        clear_bit(port1, hub->event_bits);
5005        clear_bit(port1, hub->wakeup_bits);
5006
5007        if (hub_port_status(hub, port1, &portstatus, &portchange) < 0)
5008                return;
5009
5010        if (portchange & USB_PORT_STAT_C_CONNECTION) {
5011                usb_clear_port_feature(hdev, port1, USB_PORT_FEAT_C_CONNECTION);
5012                connect_change = 1;
5013        }
5014
5015        if (portchange & USB_PORT_STAT_C_ENABLE) {
5016                if (!connect_change)
5017                        dev_dbg(&port_dev->dev, "enable change, status %08x\n",
5018                                        portstatus);
5019                usb_clear_port_feature(hdev, port1, USB_PORT_FEAT_C_ENABLE);
5020
5021                /*
5022                 * EM interference sometimes causes badly shielded USB devices
5023                 * to be shutdown by the hub, this hack enables them again.
5024                 * Works at least with mouse driver.
5025                 */
5026                if (!(portstatus & USB_PORT_STAT_ENABLE)
5027                    && !connect_change && udev) {
5028                        dev_err(&port_dev->dev, "disabled by hub (EMI?), re-enabling...\n");
5029                        connect_change = 1;
5030                }
5031        }
5032
5033        if (portchange & USB_PORT_STAT_C_OVERCURRENT) {
5034                u16 status = 0, unused;
5035
5036                dev_dbg(&port_dev->dev, "over-current change\n");
5037                usb_clear_port_feature(hdev, port1,
5038                                USB_PORT_FEAT_C_OVER_CURRENT);
5039                msleep(100);    /* Cool down */
5040                hub_power_on(hub, true);
5041                hub_port_status(hub, port1, &status, &unused);
5042                if (status & USB_PORT_STAT_OVERCURRENT)
5043                        dev_err(&port_dev->dev, "over-current condition\n");
5044        }
5045
5046        if (portchange & USB_PORT_STAT_C_RESET) {
5047                dev_dbg(&port_dev->dev, "reset change\n");
5048                usb_clear_port_feature(hdev, port1, USB_PORT_FEAT_C_RESET);
5049        }
5050        if ((portchange & USB_PORT_STAT_C_BH_RESET)
5051            && hub_is_superspeed(hdev)) {
5052                dev_dbg(&port_dev->dev, "warm reset change\n");
5053                usb_clear_port_feature(hdev, port1,
5054                                USB_PORT_FEAT_C_BH_PORT_RESET);
5055        }
5056        if (portchange & USB_PORT_STAT_C_LINK_STATE) {
5057                dev_dbg(&port_dev->dev, "link state change\n");
5058                usb_clear_port_feature(hdev, port1,
5059                                USB_PORT_FEAT_C_PORT_LINK_STATE);
5060        }
5061        if (portchange & USB_PORT_STAT_C_CONFIG_ERROR) {
5062                dev_warn(&port_dev->dev, "config error\n");
5063                usb_clear_port_feature(hdev, port1,
5064                                USB_PORT_FEAT_C_PORT_CONFIG_ERROR);
5065        }
5066
5067        /* skip port actions that require the port to be powered on */
5068        if (!pm_runtime_active(&port_dev->dev))
5069                return;
5070
5071        if (hub_handle_remote_wakeup(hub, port1, portstatus, portchange))
5072                connect_change = 1;
5073
5074        /*
5075         * Warm reset a USB3 protocol port if it's in
5076         * SS.Inactive state.
5077         */
5078        if (hub_port_warm_reset_required(hub, port1, portstatus)) {
5079                dev_dbg(&port_dev->dev, "do warm reset\n");
5080                if (!udev || !(portstatus & USB_PORT_STAT_CONNECTION)
5081                                || udev->state == USB_STATE_NOTATTACHED) {
5082                        if (hub_port_reset(hub, port1, NULL,
5083                                        HUB_BH_RESET_TIME, true) < 0)
5084                                hub_port_disable(hub, port1, 1);
5085                } else {
5086                        usb_unlock_port(port_dev);
5087                        usb_lock_device(udev);
5088                        usb_reset_device(udev);
5089                        usb_unlock_device(udev);
5090                        usb_lock_port(port_dev);
5091                        connect_change = 0;
5092                }
5093        }
5094
5095        if (connect_change)
5096                hub_port_connect_change(hub, port1, portstatus, portchange);
5097}
5098
5099static void hub_event(struct work_struct *work)
5100{
5101        struct usb_device *hdev;
5102        struct usb_interface *intf;
5103        struct usb_hub *hub;
5104        struct device *hub_dev;
5105        u16 hubstatus;
5106        u16 hubchange;
5107        int i, ret;
5108
5109        hub = container_of(work, struct usb_hub, events);
5110        hdev = hub->hdev;
5111        hub_dev = hub->intfdev;
5112        intf = to_usb_interface(hub_dev);
5113
5114        dev_dbg(hub_dev, "state %d ports %d chg %04x evt %04x\n",
5115                        hdev->state, hdev->maxchild,
5116                        /* NOTE: expects max 15 ports... */
5117                        (u16) hub->change_bits[0],
5118                        (u16) hub->event_bits[0]);
5119
5120        /* Lock the device, then check to see if we were
5121         * disconnected while waiting for the lock to succeed. */
5122        usb_lock_device(hdev);
5123        if (unlikely(hub->disconnected))
5124                goto out_hdev_lock;
5125
5126        /* If the hub has died, clean up after it */
5127        if (hdev->state == USB_STATE_NOTATTACHED) {
5128                hub->error = -ENODEV;
5129                hub_quiesce(hub, HUB_DISCONNECT);
5130                goto out_hdev_lock;
5131        }
5132
5133        /* Autoresume */
5134        ret = usb_autopm_get_interface(intf);
5135        if (ret) {
5136                dev_dbg(hub_dev, "Can't autoresume: %d\n", ret);
5137                goto out_hdev_lock;
5138        }
5139
5140        /* If this is an inactive hub, do nothing */
5141        if (hub->quiescing)
5142                goto out_autopm;
5143
5144        if (hub->error) {
5145                dev_dbg(hub_dev, "resetting for error %d\n", hub->error);
5146
5147                ret = usb_reset_device(hdev);
5148                if (ret) {
5149                        dev_dbg(hub_dev, "error resetting hub: %d\n", ret);
5150                        goto out_autopm;
5151                }
5152
5153                hub->nerrors = 0;
5154                hub->error = 0;
5155        }
5156
5157        /* deal with port status changes */
5158        for (i = 1; i <= hdev->maxchild; i++) {
5159                struct usb_port *port_dev = hub->ports[i - 1];
5160
5161                if (test_bit(i, hub->event_bits)
5162                                || test_bit(i, hub->change_bits)
5163                                || test_bit(i, hub->wakeup_bits)) {
5164                        /*
5165                         * The get_noresume and barrier ensure that if
5166                         * the port was in the process of resuming, we
5167                         * flush that work and keep the port active for
5168                         * the duration of the port_event().  However,
5169                         * if the port is runtime pm suspended
5170                         * (powered-off), we leave it in that state, run
5171                         * an abbreviated port_event(), and move on.
5172                         */
5173                        pm_runtime_get_noresume(&port_dev->dev);
5174                        pm_runtime_barrier(&port_dev->dev);
5175                        usb_lock_port(port_dev);
5176                        port_event(hub, i);
5177                        usb_unlock_port(port_dev);
5178                        pm_runtime_put_sync(&port_dev->dev);
5179                }
5180        }
5181
5182        /* deal with hub status changes */
5183        if (test_and_clear_bit(0, hub->event_bits) == 0)
5184                ;       /* do nothing */
5185        else if (hub_hub_status(hub, &hubstatus, &hubchange) < 0)
5186                dev_err(hub_dev, "get_hub_status failed\n");
5187        else {
5188                if (hubchange & HUB_CHANGE_LOCAL_POWER) {
5189                        dev_dbg(hub_dev, "power change\n");
5190                        clear_hub_feature(hdev, C_HUB_LOCAL_POWER);
5191                        if (hubstatus & HUB_STATUS_LOCAL_POWER)
5192                                /* FIXME: Is this always true? */
5193                                hub->limited_power = 1;
5194                        else
5195                                hub->limited_power = 0;
5196                }
5197                if (hubchange & HUB_CHANGE_OVERCURRENT) {
5198                        u16 status = 0;
5199                        u16 unused;
5200
5201                        dev_dbg(hub_dev, "over-current change\n");
5202                        clear_hub_feature(hdev, C_HUB_OVER_CURRENT);
5203                        msleep(500);    /* Cool down */
5204                        hub_power_on(hub, true);
5205                        hub_hub_status(hub, &status, &unused);
5206                        if (status & HUB_STATUS_OVERCURRENT)
5207                                dev_err(hub_dev, "over-current condition\n");
5208                }
5209        }
5210
5211out_autopm:
5212        /* Balance the usb_autopm_get_interface() above */
5213        usb_autopm_put_interface_no_suspend(intf);
5214out_hdev_lock:
5215        usb_unlock_device(hdev);
5216
5217        /* Balance the stuff in kick_hub_wq() and allow autosuspend */
5218        usb_autopm_put_interface(intf);
5219        kref_put(&hub->kref, hub_release);
5220}
5221
5222static const struct usb_device_id hub_id_table[] = {
5223    { .match_flags = USB_DEVICE_ID_MATCH_VENDOR
5224                        | USB_DEVICE_ID_MATCH_INT_CLASS,
5225      .idVendor = USB_VENDOR_GENESYS_LOGIC,
5226      .bInterfaceClass = USB_CLASS_HUB,
5227      .driver_info = HUB_QUIRK_CHECK_PORT_AUTOSUSPEND},
5228    { .match_flags = USB_DEVICE_ID_MATCH_DEV_CLASS,
5229      .bDeviceClass = USB_CLASS_HUB},
5230    { .match_flags = USB_DEVICE_ID_MATCH_INT_CLASS,
5231      .bInterfaceClass = USB_CLASS_HUB},
5232    { }                                         /* Terminating entry */
5233};
5234
5235MODULE_DEVICE_TABLE(usb, hub_id_table);
5236
5237static struct usb_driver hub_driver = {
5238        .name =         "hub",
5239        .probe =        hub_probe,
5240        .disconnect =   hub_disconnect,
5241        .suspend =      hub_suspend,
5242        .resume =       hub_resume,
5243        .reset_resume = hub_reset_resume,
5244        .pre_reset =    hub_pre_reset,
5245        .post_reset =   hub_post_reset,
5246        .unlocked_ioctl = hub_ioctl,
5247        .id_table =     hub_id_table,
5248        .supports_autosuspend = 1,
5249};
5250
5251int usb_hub_init(void)
5252{
5253        if (usb_register(&hub_driver) < 0) {
5254                printk(KERN_ERR "%s: can't register hub driver\n",
5255                        usbcore_name);
5256                return -1;
5257        }
5258
5259        /*
5260         * The workqueue needs to be freezable to avoid interfering with
5261         * USB-PERSIST port handover. Otherwise it might see that a full-speed
5262         * device was gone before the EHCI controller had handed its port
5263         * over to the companion full-speed controller.
5264         */
5265        hub_wq = alloc_workqueue("usb_hub_wq", WQ_FREEZABLE, 0);
5266        if (hub_wq)
5267                return 0;
5268
5269        /* Fall through if kernel_thread failed */
5270        usb_deregister(&hub_driver);
5271        pr_err("%s: can't allocate workqueue for usb hub\n", usbcore_name);
5272
5273        return -1;
5274}
5275
5276void usb_hub_cleanup(void)
5277{
5278        destroy_workqueue(hub_wq);
5279
5280        /*
5281         * Hub resources are freed for us by usb_deregister. It calls
5282         * usb_driver_purge on every device which in turn calls that
5283         * devices disconnect function if it is using this driver.
5284         * The hub_disconnect function takes care of releasing the
5285         * individual hub resources. -greg
5286         */
5287        usb_deregister(&hub_driver);
5288} /* usb_hub_cleanup() */
5289
5290static int descriptors_changed(struct usb_device *udev,
5291                struct usb_device_descriptor *old_device_descriptor,
5292                struct usb_host_bos *old_bos)
5293{
5294        int             changed = 0;
5295        unsigned        index;
5296        unsigned        serial_len = 0;
5297        unsigned        len;
5298        unsigned        old_length;
5299        int             length;
5300        char            *buf;
5301
5302        if (memcmp(&udev->descriptor, old_device_descriptor,
5303                        sizeof(*old_device_descriptor)) != 0)
5304                return 1;
5305
5306        if ((old_bos && !udev->bos) || (!old_bos && udev->bos))
5307                return 1;
5308        if (udev->bos) {
5309                len = le16_to_cpu(udev->bos->desc->wTotalLength);
5310                if (len != le16_to_cpu(old_bos->desc->wTotalLength))
5311                        return 1;
5312                if (memcmp(udev->bos->desc, old_bos->desc, len))
5313                        return 1;
5314        }
5315
5316        /* Since the idVendor, idProduct, and bcdDevice values in the
5317         * device descriptor haven't changed, we will assume the
5318         * Manufacturer and Product strings haven't changed either.
5319         * But the SerialNumber string could be different (e.g., a
5320         * different flash card of the same brand).
5321         */
5322        if (udev->serial)
5323                serial_len = strlen(udev->serial) + 1;
5324
5325        len = serial_len;
5326        for (index = 0; index < udev->descriptor.bNumConfigurations; index++) {
5327                old_length = le16_to_cpu(udev->config[index].desc.wTotalLength);
5328                len = max(len, old_length);
5329        }
5330
5331        buf = kmalloc(len, GFP_NOIO);
5332        if (!buf)
5333                /* assume the worst */
5334                return 1;
5335
5336        for (index = 0; index < udev->descriptor.bNumConfigurations; index++) {
5337                old_length = le16_to_cpu(udev->config[index].desc.wTotalLength);
5338                length = usb_get_descriptor(udev, USB_DT_CONFIG, index, buf,
5339                                old_length);
5340                if (length != old_length) {
5341                        dev_dbg(&udev->dev, "config index %d, error %d\n",
5342                                        index, length);
5343                        changed = 1;
5344                        break;
5345                }
5346                if (memcmp(buf, udev->rawdescriptors[index], old_length)
5347                                != 0) {
5348                        dev_dbg(&udev->dev, "config index %d changed (#%d)\n",
5349                                index,
5350                                ((struct usb_config_descriptor *) buf)->
5351                                        bConfigurationValue);
5352                        changed = 1;
5353                        break;
5354                }
5355        }
5356
5357        if (!changed && serial_len) {
5358                length = usb_string(udev, udev->descriptor.iSerialNumber,
5359                                buf, serial_len);
5360                if (length + 1 != serial_len) {
5361                        dev_dbg(&udev->dev, "serial string error %d\n",
5362                                        length);
5363                        changed = 1;
5364                } else if (memcmp(buf, udev->serial, length) != 0) {
5365                        dev_dbg(&udev->dev, "serial string changed\n");
5366                        changed = 1;
5367                }
5368        }
5369
5370        kfree(buf);
5371        return changed;
5372}
5373
5374/**
5375 * usb_reset_and_verify_device - perform a USB port reset to reinitialize a device
5376 * @udev: device to reset (not in SUSPENDED or NOTATTACHED state)
5377 *
5378 * WARNING - don't use this routine to reset a composite device
5379 * (one with multiple interfaces owned by separate drivers)!
5380 * Use usb_reset_device() instead.
5381 *
5382 * Do a port reset, reassign the device's address, and establish its
5383 * former operating configuration.  If the reset fails, or the device's
5384 * descriptors change from their values before the reset, or the original
5385 * configuration and altsettings cannot be restored, a flag will be set
5386 * telling hub_wq to pretend the device has been disconnected and then
5387 * re-connected.  All drivers will be unbound, and the device will be
5388 * re-enumerated and probed all over again.
5389 *
5390 * Return: 0 if the reset succeeded, -ENODEV if the device has been
5391 * flagged for logical disconnection, or some other negative error code
5392 * if the reset wasn't even attempted.
5393 *
5394 * Note:
5395 * The caller must own the device lock and the port lock, the latter is
5396 * taken by usb_reset_device().  For example, it's safe to use
5397 * usb_reset_device() from a driver probe() routine after downloading
5398 * new firmware.  For calls that might not occur during probe(), drivers
5399 * should lock the device using usb_lock_device_for_reset().
5400 *
5401 * Locking exception: This routine may also be called from within an
5402 * autoresume handler.  Such usage won't conflict with other tasks
5403 * holding the device lock because these tasks should always call
5404 * usb_autopm_resume_device(), thereby preventing any unwanted
5405 * autoresume.  The autoresume handler is expected to have already
5406 * acquired the port lock before calling this routine.
5407 */
5408static int usb_reset_and_verify_device(struct usb_device *udev)
5409{
5410        struct usb_device               *parent_hdev = udev->parent;
5411        struct usb_hub                  *parent_hub;
5412        struct usb_hcd                  *hcd = bus_to_hcd(udev->bus);
5413        struct usb_device_descriptor    descriptor = udev->descriptor;
5414        struct usb_host_bos             *bos;
5415        int                             i, j, ret = 0;
5416        int                             port1 = udev->portnum;
5417
5418        if (udev->state == USB_STATE_NOTATTACHED ||
5419                        udev->state == USB_STATE_SUSPENDED) {
5420                dev_dbg(&udev->dev, "device reset not allowed in state %d\n",
5421                                udev->state);
5422                return -EINVAL;
5423        }
5424
5425        if (!parent_hdev)
5426                return -EISDIR;
5427
5428        parent_hub = usb_hub_to_struct_hub(parent_hdev);
5429
5430        /* Disable USB2 hardware LPM.
5431         * It will be re-enabled by the enumeration process.
5432         */
5433        if (udev->usb2_hw_lpm_enabled == 1)
5434                usb_set_usb2_hardware_lpm(udev, 0);
5435
5436        /* Disable LPM and LTM while we reset the device and reinstall the alt
5437         * settings.  Device-initiated LPM settings, and system exit latency
5438         * settings are cleared when the device is reset, so we have to set
5439         * them up again.
5440         */
5441        ret = usb_unlocked_disable_lpm(udev);
5442        if (ret) {
5443                dev_err(&udev->dev, "%s Failed to disable LPM\n.", __func__);
5444                goto re_enumerate_no_bos;
5445        }
5446        ret = usb_disable_ltm(udev);
5447        if (ret) {
5448                dev_err(&udev->dev, "%s Failed to disable LTM\n.",
5449                                __func__);
5450                goto re_enumerate_no_bos;
5451        }
5452
5453        bos = udev->bos;
5454        udev->bos = NULL;
5455
5456        for (i = 0; i < SET_CONFIG_TRIES; ++i) {
5457
5458                /* ep0 maxpacket size may change; let the HCD know about it.
5459                 * Other endpoints will be handled by re-enumeration. */
5460                usb_ep0_reinit(udev);
5461                ret = hub_port_init(parent_hub, udev, port1, i);
5462                if (ret >= 0 || ret == -ENOTCONN || ret == -ENODEV)
5463                        break;
5464        }
5465
5466        if (ret < 0)
5467                goto re_enumerate;
5468
5469        /* Device might have changed firmware (DFU or similar) */
5470        if (descriptors_changed(udev, &descriptor, bos)) {
5471                dev_info(&udev->dev, "device firmware changed\n");
5472                udev->descriptor = descriptor;  /* for disconnect() calls */
5473                goto re_enumerate;
5474        }
5475
5476        /* Restore the device's previous configuration */
5477        if (!udev->actconfig)
5478                goto done;
5479
5480        mutex_lock(hcd->bandwidth_mutex);
5481        ret = usb_hcd_alloc_bandwidth(udev, udev->actconfig, NULL, NULL);
5482        if (ret < 0) {
5483                dev_warn(&udev->dev,
5484                                "Busted HC?  Not enough HCD resources for "
5485                                "old configuration.\n");
5486                mutex_unlock(hcd->bandwidth_mutex);
5487                goto re_enumerate;
5488        }
5489        ret = usb_control_msg(udev, usb_sndctrlpipe(udev, 0),
5490                        USB_REQ_SET_CONFIGURATION, 0,
5491                        udev->actconfig->desc.bConfigurationValue, 0,
5492                        NULL, 0, USB_CTRL_SET_TIMEOUT);
5493        if (ret < 0) {
5494                dev_err(&udev->dev,
5495                        "can't restore configuration #%d (error=%d)\n",
5496                        udev->actconfig->desc.bConfigurationValue, ret);
5497                mutex_unlock(hcd->bandwidth_mutex);
5498                goto re_enumerate;
5499        }
5500        mutex_unlock(hcd->bandwidth_mutex);
5501        usb_set_device_state(udev, USB_STATE_CONFIGURED);
5502
5503        /* Put interfaces back into the same altsettings as before.
5504         * Don't bother to send the Set-Interface request for interfaces
5505         * that were already in altsetting 0; besides being unnecessary,
5506         * many devices can't handle it.  Instead just reset the host-side
5507         * endpoint state.
5508         */
5509        for (i = 0; i < udev->actconfig->desc.bNumInterfaces; i++) {
5510                struct usb_host_config *config = udev->actconfig;
5511                struct usb_interface *intf = config->interface[i];
5512                struct usb_interface_descriptor *desc;
5513
5514                desc = &intf->cur_altsetting->desc;
5515                if (desc->bAlternateSetting == 0) {
5516                        usb_disable_interface(udev, intf, true);
5517                        usb_enable_interface(udev, intf, true);
5518                        ret = 0;
5519                } else {
5520                        /* Let the bandwidth allocation function know that this
5521                         * device has been reset, and it will have to use
5522                         * alternate setting 0 as the current alternate setting.
5523                         */
5524                        intf->resetting_device = 1;
5525                        ret = usb_set_interface(udev, desc->bInterfaceNumber,
5526                                        desc->bAlternateSetting);
5527                        intf->resetting_device = 0;
5528                }
5529                if (ret < 0) {
5530                        dev_err(&udev->dev, "failed to restore interface %d "
5531                                "altsetting %d (error=%d)\n",
5532                                desc->bInterfaceNumber,
5533                                desc->bAlternateSetting,
5534                                ret);
5535                        goto re_enumerate;
5536                }
5537                /* Resetting also frees any allocated streams */
5538                for (j = 0; j < intf->cur_altsetting->desc.bNumEndpoints; j++)
5539                        intf->cur_altsetting->endpoint[j].streams = 0;
5540        }
5541
5542done:
5543        /* Now that the alt settings are re-installed, enable LTM and LPM. */
5544        usb_set_usb2_hardware_lpm(udev, 1);
5545        usb_unlocked_enable_lpm(udev);
5546        usb_enable_ltm(udev);
5547        usb_release_bos_descriptor(udev);
5548        udev->bos = bos;
5549        return 0;
5550
5551re_enumerate:
5552        usb_release_bos_descriptor(udev);
5553        udev->bos = bos;
5554re_enumerate_no_bos:
5555        /* LPM state doesn't matter when we're about to destroy the device. */
5556        hub_port_logical_disconnect(parent_hub, port1);
5557        return -ENODEV;
5558}
5559
5560/**
5561 * usb_reset_device - warn interface drivers and perform a USB port reset
5562 * @udev: device to reset (not in SUSPENDED or NOTATTACHED state)
5563 *
5564 * Warns all drivers bound to registered interfaces (using their pre_reset
5565 * method), performs the port reset, and then lets the drivers know that
5566 * the reset is over (using their post_reset method).
5567 *
5568 * Return: The same as for usb_reset_and_verify_device().
5569 *
5570 * Note:
5571 * The caller must own the device lock.  For example, it's safe to use
5572 * this from a driver probe() routine after downloading new firmware.
5573 * For calls that might not occur during probe(), drivers should lock
5574 * the device using usb_lock_device_for_reset().
5575 *
5576 * If an interface is currently being probed or disconnected, we assume
5577 * its driver knows how to handle resets.  For all other interfaces,
5578 * if the driver doesn't have pre_reset and post_reset methods then
5579 * we attempt to unbind it and rebind afterward.
5580 */
5581int usb_reset_device(struct usb_device *udev)
5582{
5583        int ret;
5584        int i;
5585        unsigned int noio_flag;
5586        struct usb_port *port_dev;
5587        struct usb_host_config *config = udev->actconfig;
5588        struct usb_hub *hub = usb_hub_to_struct_hub(udev->parent);
5589
5590        if (udev->state == USB_STATE_NOTATTACHED ||
5591                        udev->state == USB_STATE_SUSPENDED) {
5592                dev_dbg(&udev->dev, "device reset not allowed in state %d\n",
5593                                udev->state);
5594                return -EINVAL;
5595        }
5596
5597        if (!udev->parent) {
5598                /* this requires hcd-specific logic; see ohci_restart() */
5599                dev_dbg(&udev->dev, "%s for root hub!\n", __func__);
5600                return -EISDIR;
5601        }
5602
5603        port_dev = hub->ports[udev->portnum - 1];
5604
5605        /*
5606         * Don't allocate memory with GFP_KERNEL in current
5607         * context to avoid possible deadlock if usb mass
5608         * storage interface or usbnet interface(iSCSI case)
5609         * is included in current configuration. The easist
5610         * approach is to do it for every device reset,
5611         * because the device 'memalloc_noio' flag may have
5612         * not been set before reseting the usb device.
5613         */
5614        noio_flag = memalloc_noio_save();
5615
5616        /* Prevent autosuspend during the reset */
5617        usb_autoresume_device(udev);
5618
5619        if (config) {
5620                for (i = 0; i < config->desc.bNumInterfaces; ++i) {
5621                        struct usb_interface *cintf = config->interface[i];
5622                        struct usb_driver *drv;
5623                        int unbind = 0;
5624
5625                        if (cintf->dev.driver) {
5626                                drv = to_usb_driver(cintf->dev.driver);
5627                                if (drv->pre_reset && drv->post_reset)
5628                                        unbind = (drv->pre_reset)(cintf);
5629                                else if (cintf->condition ==
5630                                                USB_INTERFACE_BOUND)
5631                                        unbind = 1;
5632                                if (unbind)
5633                                        usb_forced_unbind_intf(cintf);
5634                        }
5635                }
5636        }
5637
5638        usb_lock_port(port_dev);
5639        ret = usb_reset_and_verify_device(udev);
5640        usb_unlock_port(port_dev);
5641
5642        if (config) {
5643                for (i = config->desc.bNumInterfaces - 1; i >= 0; --i) {
5644                        struct usb_interface *cintf = config->interface[i];
5645                        struct usb_driver *drv;
5646                        int rebind = cintf->needs_binding;
5647
5648                        if (!rebind && cintf->dev.driver) {
5649                                drv = to_usb_driver(cintf->dev.driver);
5650                                if (drv->post_reset)
5651                                        rebind = (drv->post_reset)(cintf);
5652                                else if (cintf->condition ==
5653                                                USB_INTERFACE_BOUND)
5654                                        rebind = 1;
5655                                if (rebind)
5656                                        cintf->needs_binding = 1;
5657                        }
5658                }
5659                usb_unbind_and_rebind_marked_interfaces(udev);
5660        }
5661
5662        usb_autosuspend_device(udev);
5663        memalloc_noio_restore(noio_flag);
5664        return ret;
5665}
5666EXPORT_SYMBOL_GPL(usb_reset_device);
5667
5668
5669/**
5670 * usb_queue_reset_device - Reset a USB device from an atomic context
5671 * @iface: USB interface belonging to the device to reset
5672 *
5673 * This function can be used to reset a USB device from an atomic
5674 * context, where usb_reset_device() won't work (as it blocks).
5675 *
5676 * Doing a reset via this method is functionally equivalent to calling
5677 * usb_reset_device(), except for the fact that it is delayed to a
5678 * workqueue. This means that any drivers bound to other interfaces
5679 * might be unbound, as well as users from usbfs in user space.
5680 *
5681 * Corner cases:
5682 *
5683 * - Scheduling two resets at the same time from two different drivers
5684 *   attached to two different interfaces of the same device is
5685 *   possible; depending on how the driver attached to each interface
5686 *   handles ->pre_reset(), the second reset might happen or not.
5687 *
5688 * - If the reset is delayed so long that the interface is unbound from
5689 *   its driver, the reset will be skipped.
5690 *
5691 * - This function can be called during .probe().  It can also be called
5692 *   during .disconnect(), but doing so is pointless because the reset
5693 *   will not occur.  If you really want to reset the device during
5694 *   .disconnect(), call usb_reset_device() directly -- but watch out
5695 *   for nested unbinding issues!
5696 */
5697void usb_queue_reset_device(struct usb_interface *iface)
5698{
5699        if (schedule_work(&iface->reset_ws))
5700                usb_get_intf(iface);
5701}
5702EXPORT_SYMBOL_GPL(usb_queue_reset_device);
5703
5704/**
5705 * usb_hub_find_child - Get the pointer of child device
5706 * attached to the port which is specified by @port1.
5707 * @hdev: USB device belonging to the usb hub
5708 * @port1: port num to indicate which port the child device
5709 *      is attached to.
5710 *
5711 * USB drivers call this function to get hub's child device
5712 * pointer.
5713 *
5714 * Return: %NULL if input param is invalid and
5715 * child's usb_device pointer if non-NULL.
5716 */
5717struct usb_device *usb_hub_find_child(struct usb_device *hdev,
5718                int port1)
5719{
5720        struct usb_hub *hub = usb_hub_to_struct_hub(hdev);
5721
5722        if (port1 < 1 || port1 > hdev->maxchild)
5723                return NULL;
5724        return hub->ports[port1 - 1]->child;
5725}
5726EXPORT_SYMBOL_GPL(usb_hub_find_child);
5727
5728void usb_hub_adjust_deviceremovable(struct usb_device *hdev,
5729                struct usb_hub_descriptor *desc)
5730{
5731        struct usb_hub *hub = usb_hub_to_struct_hub(hdev);
5732        enum usb_port_connect_type connect_type;
5733        int i;
5734
5735        if (!hub)
5736                return;
5737
5738        if (!hub_is_superspeed(hdev)) {
5739                for (i = 1; i <= hdev->maxchild; i++) {
5740                        struct usb_port *port_dev = hub->ports[i - 1];
5741
5742                        connect_type = port_dev->connect_type;
5743                        if (connect_type == USB_PORT_CONNECT_TYPE_HARD_WIRED) {
5744                                u8 mask = 1 << (i%8);
5745
5746                                if (!(desc->u.hs.DeviceRemovable[i/8] & mask)) {
5747                                        dev_dbg(&port_dev->dev, "DeviceRemovable is changed to 1 according to platform information.\n");
5748                                        desc->u.hs.DeviceRemovable[i/8] |= mask;
5749                                }
5750                        }
5751                }
5752        } else {
5753                u16 port_removable = le16_to_cpu(desc->u.ss.DeviceRemovable);
5754
5755                for (i = 1; i <= hdev->maxchild; i++) {
5756                        struct usb_port *port_dev = hub->ports[i - 1];
5757
5758                        connect_type = port_dev->connect_type;
5759                        if (connect_type == USB_PORT_CONNECT_TYPE_HARD_WIRED) {
5760                                u16 mask = 1 << i;
5761
5762                                if (!(port_removable & mask)) {
5763                                        dev_dbg(&port_dev->dev, "DeviceRemovable is changed to 1 according to platform information.\n");
5764                                        port_removable |= mask;
5765                                }
5766                        }
5767                }
5768
5769                desc->u.ss.DeviceRemovable = cpu_to_le16(port_removable);
5770        }
5771}
5772
5773#ifdef CONFIG_ACPI
5774/**
5775 * usb_get_hub_port_acpi_handle - Get the usb port's acpi handle
5776 * @hdev: USB device belonging to the usb hub
5777 * @port1: port num of the port
5778 *
5779 * Return: Port's acpi handle if successful, %NULL if params are
5780 * invalid.
5781 */
5782acpi_handle usb_get_hub_port_acpi_handle(struct usb_device *hdev,
5783        int port1)
5784{
5785        struct usb_hub *hub = usb_hub_to_struct_hub(hdev);
5786
5787        if (!hub)
5788                return NULL;
5789
5790        return ACPI_HANDLE(&hub->ports[port1 - 1]->dev);
5791}
5792#endif
Note: See TracBrowser for help on using the repository browser.