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

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

update kernel

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