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

Last change on this file since 31884 was 31884, checked in by brainslayer, 6 weeks ago

update kernels

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