source: src/linux/universal/linux-3.2/drivers/usb/core/hub.c @ 18278

Last change on this file since 18278 was 18278, checked in by BrainSlayer, 16 months ago

gpio stp interface for lantiq and usb led func

File size: 116.4 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/quirks.h>
24#include <linux/kthread.h>
25#include <linux/mutex.h>
26#include <linux/freezer.h>
27
28#include <asm/uaccess.h>
29#include <asm/byteorder.h>
30
31#include "usb.h"
32
33void ap_usb_led_on(void);
34void ap_usb_led_off(void);
35
36/* if we are in debug mode, always announce new devices */
37#ifdef DEBUG
38#ifndef CONFIG_USB_ANNOUNCE_NEW_DEVICES
39#define CONFIG_USB_ANNOUNCE_NEW_DEVICES
40#endif
41#endif
42
43struct usb_hub {
44        struct device           *intfdev;       /* the "interface" device */
45        struct usb_device       *hdev;
46        struct kref             kref;
47        struct urb              *urb;           /* for interrupt polling pipe */
48
49        /* buffer for urb ... with extra space in case of babble */
50        char                    (*buffer)[8];
51        union {
52                struct usb_hub_status   hub;
53                struct usb_port_status  port;
54        }                       *status;        /* buffer for status reports */
55        struct mutex            status_mutex;   /* for the status buffer */
56
57        int                     error;          /* last reported error */
58        int                     nerrors;        /* track consecutive errors */
59
60        struct list_head        event_list;     /* hubs w/data or errs ready */
61        unsigned long           event_bits[1];  /* status change bitmask */
62        unsigned long           change_bits[1]; /* ports with logical connect
63                                                        status change */
64        unsigned long           busy_bits[1];   /* ports being reset or
65                                                        resumed */
66        unsigned long           removed_bits[1]; /* ports with a "removed"
67                                                        device present */
68#if USB_MAXCHILDREN > 31 /* 8*sizeof(unsigned long) - 1 */
69#error event_bits[] is too short!
70#endif
71
72        struct usb_hub_descriptor *descriptor;  /* class descriptor */
73        struct usb_tt           tt;             /* Transaction Translator */
74
75        unsigned                mA_per_port;    /* current for each child */
76
77        unsigned                limited_power:1;
78        unsigned                quiescing:1;
79        unsigned                disconnected:1;
80
81        unsigned                has_indicators:1;
82        u8                      indicator[USB_MAXCHILDREN];
83        struct delayed_work     leds;
84        struct delayed_work     init_work;
85        void                    **port_owners;
86};
87
88static inline int hub_is_superspeed(struct usb_device *hdev)
89{
90        return (hdev->descriptor.bDeviceProtocol == 3);
91}
92
93/* Protect struct usb_device->state and ->children members
94 * Note: Both are also protected by ->dev.sem, except that ->state can
95 * change to USB_STATE_NOTATTACHED even when the semaphore isn't held. */
96static DEFINE_SPINLOCK(device_state_lock);
97
98/* khubd's worklist and its lock */
99static DEFINE_SPINLOCK(hub_event_lock);
100static LIST_HEAD(hub_event_list);       /* List of hubs needing servicing */
101
102/* Wakes up khubd */
103static DECLARE_WAIT_QUEUE_HEAD(khubd_wait);
104
105static struct task_struct *khubd_task;
106
107/* cycle leds on hubs that aren't blinking for attention */
108static int blinkenlights = 0;
109module_param (blinkenlights, bool, S_IRUGO);
110MODULE_PARM_DESC (blinkenlights, "true to cycle leds on hubs");
111
112/*
113 * Device SATA8000 FW1.0 from DATAST0R Technology Corp requires about
114 * 10 seconds to send reply for the initial 64-byte descriptor request.
115 */
116/* define initial 64-byte descriptor request timeout in milliseconds */
117static int initial_descriptor_timeout = USB_CTRL_GET_TIMEOUT;
118module_param(initial_descriptor_timeout, int, S_IRUGO|S_IWUSR);
119MODULE_PARM_DESC(initial_descriptor_timeout,
120                "initial 64-byte descriptor request timeout in milliseconds "
121                "(default 5000 - 5.0 seconds)");
122
123/*
124 * As of 2.6.10 we introduce a new USB device initialization scheme which
125 * closely resembles the way Windows works.  Hopefully it will be compatible
126 * with a wider range of devices than the old scheme.  However some previously
127 * working devices may start giving rise to "device not accepting address"
128 * errors; if that happens the user can try the old scheme by adjusting the
129 * following module parameters.
130 *
131 * For maximum flexibility there are two boolean parameters to control the
132 * hub driver's behavior.  On the first initialization attempt, if the
133 * "old_scheme_first" parameter is set then the old scheme will be used,
134 * otherwise the new scheme is used.  If that fails and "use_both_schemes"
135 * is set, then the driver will make another attempt, using the other scheme.
136 */
137static int old_scheme_first = 0;
138module_param(old_scheme_first, bool, S_IRUGO | S_IWUSR);
139MODULE_PARM_DESC(old_scheme_first,
140                 "start with the old device initialization scheme");
141
142static int use_both_schemes = 1;
143module_param(use_both_schemes, bool, S_IRUGO | S_IWUSR);
144MODULE_PARM_DESC(use_both_schemes,
145                "try the other device initialization scheme if the "
146                "first one fails");
147
148/* Mutual exclusion for EHCI CF initialization.  This interferes with
149 * port reset on some companion controllers.
150 */
151DECLARE_RWSEM(ehci_cf_port_reset_rwsem);
152EXPORT_SYMBOL_GPL(ehci_cf_port_reset_rwsem);
153
154#define HUB_DEBOUNCE_TIMEOUT    1500
155#define HUB_DEBOUNCE_STEP         25
156#define HUB_DEBOUNCE_STABLE      100
157
158
159static int usb_reset_and_verify_device(struct usb_device *udev);
160
161static inline char *portspeed(struct usb_hub *hub, int portstatus)
162{
163        if (hub_is_superspeed(hub->hdev))
164                return "5.0 Gb/s";
165        if (portstatus & USB_PORT_STAT_HIGH_SPEED)
166                return "480 Mb/s";
167        else if (portstatus & USB_PORT_STAT_LOW_SPEED)
168                return "1.5 Mb/s";
169        else
170                return "12 Mb/s";
171}
172
173/* Note that hdev or one of its children must be locked! */
174static struct usb_hub *hdev_to_hub(struct usb_device *hdev)
175{
176        if (!hdev || !hdev->actconfig)
177                return NULL;
178        return usb_get_intfdata(hdev->actconfig->interface[0]);
179}
180
181/* USB 2.0 spec Section 11.24.4.5 */
182static int get_hub_descriptor(struct usb_device *hdev, void *data)
183{
184        int i, ret, size;
185        unsigned dtype;
186
187        if (hub_is_superspeed(hdev)) {
188                dtype = USB_DT_SS_HUB;
189                size = USB_DT_SS_HUB_SIZE;
190        } else {
191                dtype = USB_DT_HUB;
192                size = sizeof(struct usb_hub_descriptor);
193        }
194
195        for (i = 0; i < 3; i++) {
196                ret = usb_control_msg(hdev, usb_rcvctrlpipe(hdev, 0),
197                        USB_REQ_GET_DESCRIPTOR, USB_DIR_IN | USB_RT_HUB,
198                        dtype << 8, 0, data, size,
199                        USB_CTRL_GET_TIMEOUT);
200                if (ret >= (USB_DT_HUB_NONVAR_SIZE + 2))
201                        return ret;
202        }
203        return -EINVAL;
204}
205
206/*
207 * USB 2.0 spec Section 11.24.2.1
208 */
209static int clear_hub_feature(struct usb_device *hdev, int feature)
210{
211        return usb_control_msg(hdev, usb_sndctrlpipe(hdev, 0),
212                USB_REQ_CLEAR_FEATURE, USB_RT_HUB, feature, 0, NULL, 0, 1000);
213}
214
215/*
216 * USB 2.0 spec Section 11.24.2.2
217 */
218static int clear_port_feature(struct usb_device *hdev, int port1, int feature)
219{
220        return usb_control_msg(hdev, usb_sndctrlpipe(hdev, 0),
221                USB_REQ_CLEAR_FEATURE, USB_RT_PORT, feature, port1,
222                NULL, 0, 1000);
223}
224
225/*
226 * USB 2.0 spec Section 11.24.2.13
227 */
228static int set_port_feature(struct usb_device *hdev, int port1, int feature)
229{
230        return usb_control_msg(hdev, usb_sndctrlpipe(hdev, 0),
231                USB_REQ_SET_FEATURE, USB_RT_PORT, feature, port1,
232                NULL, 0, 1000);
233}
234
235/*
236 * USB 2.0 spec Section 11.24.2.7.1.10 and table 11-7
237 * for info about using port indicators
238 */
239static void set_port_led(
240        struct usb_hub *hub,
241        int port1,
242        int selector
243)
244{
245        int status = set_port_feature(hub->hdev, (selector << 8) | port1,
246                        USB_PORT_FEAT_INDICATOR);
247        if (status < 0)
248                dev_dbg (hub->intfdev,
249                        "port %d indicator %s status %d\n",
250                        port1,
251                        ({ char *s; switch (selector) {
252                        case HUB_LED_AMBER: s = "amber"; break;
253                        case HUB_LED_GREEN: s = "green"; break;
254                        case HUB_LED_OFF: s = "off"; break;
255                        case HUB_LED_AUTO: s = "auto"; break;
256                        default: s = "??"; break;
257                        }; s; }),
258                        status);
259}
260
261#define LED_CYCLE_PERIOD        ((2*HZ)/3)
262
263static void led_work (struct work_struct *work)
264{
265        struct usb_hub          *hub =
266                container_of(work, struct usb_hub, leds.work);
267        struct usb_device       *hdev = hub->hdev;
268        unsigned                i;
269        unsigned                changed = 0;
270        int                     cursor = -1;
271
272        if (hdev->state != USB_STATE_CONFIGURED || hub->quiescing)
273                return;
274
275        for (i = 0; i < hub->descriptor->bNbrPorts; i++) {
276                unsigned        selector, mode;
277
278                /* 30%-50% duty cycle */
279
280                switch (hub->indicator[i]) {
281                /* cycle marker */
282                case INDICATOR_CYCLE:
283                        cursor = i;
284                        selector = HUB_LED_AUTO;
285                        mode = INDICATOR_AUTO;
286                        break;
287                /* blinking green = sw attention */
288                case INDICATOR_GREEN_BLINK:
289                        selector = HUB_LED_GREEN;
290                        mode = INDICATOR_GREEN_BLINK_OFF;
291                        break;
292                case INDICATOR_GREEN_BLINK_OFF:
293                        selector = HUB_LED_OFF;
294                        mode = INDICATOR_GREEN_BLINK;
295                        break;
296                /* blinking amber = hw attention */
297                case INDICATOR_AMBER_BLINK:
298                        selector = HUB_LED_AMBER;
299                        mode = INDICATOR_AMBER_BLINK_OFF;
300                        break;
301                case INDICATOR_AMBER_BLINK_OFF:
302                        selector = HUB_LED_OFF;
303                        mode = INDICATOR_AMBER_BLINK;
304                        break;
305                /* blink green/amber = reserved */
306                case INDICATOR_ALT_BLINK:
307                        selector = HUB_LED_GREEN;
308                        mode = INDICATOR_ALT_BLINK_OFF;
309                        break;
310                case INDICATOR_ALT_BLINK_OFF:
311                        selector = HUB_LED_AMBER;
312                        mode = INDICATOR_ALT_BLINK;
313                        break;
314                default:
315                        continue;
316                }
317                if (selector != HUB_LED_AUTO)
318                        changed = 1;
319                set_port_led(hub, i + 1, selector);
320                hub->indicator[i] = mode;
321        }
322        if (!changed && blinkenlights) {
323                cursor++;
324                cursor %= hub->descriptor->bNbrPorts;
325                set_port_led(hub, cursor + 1, HUB_LED_GREEN);
326                hub->indicator[cursor] = INDICATOR_CYCLE;
327                changed++;
328        }
329        if (changed)
330                schedule_delayed_work(&hub->leds, LED_CYCLE_PERIOD);
331}
332
333/* use a short timeout for hub/port status fetches */
334#define USB_STS_TIMEOUT         1000
335#define USB_STS_RETRIES         5
336
337/*
338 * USB 2.0 spec Section 11.24.2.6
339 */
340static int get_hub_status(struct usb_device *hdev,
341                struct usb_hub_status *data)
342{
343        int i, status = -ETIMEDOUT;
344
345        for (i = 0; i < USB_STS_RETRIES &&
346                        (status == -ETIMEDOUT || status == -EPIPE); i++) {
347                status = usb_control_msg(hdev, usb_rcvctrlpipe(hdev, 0),
348                        USB_REQ_GET_STATUS, USB_DIR_IN | USB_RT_HUB, 0, 0,
349                        data, sizeof(*data), USB_STS_TIMEOUT);
350        }
351        return status;
352}
353
354/*
355 * USB 2.0 spec Section 11.24.2.7
356 */
357static int get_port_status(struct usb_device *hdev, int port1,
358                struct usb_port_status *data)
359{
360        int i, status = -ETIMEDOUT;
361
362        for (i = 0; i < USB_STS_RETRIES &&
363                        (status == -ETIMEDOUT || status == -EPIPE); i++) {
364                status = usb_control_msg(hdev, usb_rcvctrlpipe(hdev, 0),
365                        USB_REQ_GET_STATUS, USB_DIR_IN | USB_RT_PORT, 0, port1,
366                        data, sizeof(*data), USB_STS_TIMEOUT);
367        }
368        return status;
369}
370
371static int hub_port_status(struct usb_hub *hub, int port1,
372                u16 *status, u16 *change)
373{
374        int ret;
375
376        mutex_lock(&hub->status_mutex);
377        ret = get_port_status(hub->hdev, port1, &hub->status->port);
378        if (ret < 4) {
379                dev_err(hub->intfdev,
380                        "%s failed (err = %d)\n", __func__, ret);
381                if (ret >= 0)
382                        ret = -EIO;
383        } else {
384                *status = le16_to_cpu(hub->status->port.wPortStatus);
385                *change = le16_to_cpu(hub->status->port.wPortChange);
386
387                ret = 0;
388        }
389        mutex_unlock(&hub->status_mutex);
390        return ret;
391}
392
393static void kick_khubd(struct usb_hub *hub)
394{
395        unsigned long   flags;
396
397        spin_lock_irqsave(&hub_event_lock, flags);
398        if (!hub->disconnected && list_empty(&hub->event_list)) {
399                list_add_tail(&hub->event_list, &hub_event_list);
400
401                /* Suppress autosuspend until khubd runs */
402                usb_autopm_get_interface_no_resume(
403                                to_usb_interface(hub->intfdev));
404                wake_up(&khubd_wait);
405        }
406        spin_unlock_irqrestore(&hub_event_lock, flags);
407}
408
409void usb_kick_khubd(struct usb_device *hdev)
410{
411        struct usb_hub *hub = hdev_to_hub(hdev);
412
413        if (hub)
414                kick_khubd(hub);
415}
416
417
418/* completion function, fires on port status changes and various faults */
419static void hub_irq(struct urb *urb)
420{
421        struct usb_hub *hub = urb->context;
422        int status = urb->status;
423        unsigned i;
424        unsigned long bits;
425
426        switch (status) {
427        case -ENOENT:           /* synchronous unlink */
428        case -ECONNRESET:       /* async unlink */
429        case -ESHUTDOWN:        /* hardware going away */
430                return;
431
432        default:                /* presumably an error */
433                /* Cause a hub reset after 10 consecutive errors */
434                dev_dbg (hub->intfdev, "transfer --> %d\n", status);
435                if ((++hub->nerrors < 10) || hub->error)
436                        goto resubmit;
437                hub->error = status;
438                /* FALL THROUGH */
439
440        /* let khubd handle things */
441        case 0:                 /* we got data:  port status changed */
442                bits = 0;
443                for (i = 0; i < urb->actual_length; ++i)
444                        bits |= ((unsigned long) ((*hub->buffer)[i]))
445                                        << (i*8);
446                hub->event_bits[0] = bits;
447                break;
448        }
449
450        hub->nerrors = 0;
451
452        /* Something happened, let khubd figure it out */
453        kick_khubd(hub);
454
455resubmit:
456        if (hub->quiescing)
457                return;
458
459        if ((status = usb_submit_urb (hub->urb, GFP_ATOMIC)) != 0
460                        && status != -ENODEV && status != -EPERM)
461                dev_err (hub->intfdev, "resubmit --> %d\n", status);
462}
463
464/* USB 2.0 spec Section 11.24.2.3 */
465static inline int
466hub_clear_tt_buffer (struct usb_device *hdev, u16 devinfo, u16 tt)
467{
468        return usb_control_msg(hdev, usb_sndctrlpipe(hdev, 0),
469                               HUB_CLEAR_TT_BUFFER, USB_RT_PORT, devinfo,
470                               tt, NULL, 0, 1000);
471}
472
473/*
474 * enumeration blocks khubd for a long time. we use keventd instead, since
475 * long blocking there is the exception, not the rule.  accordingly, HCDs
476 * talking to TTs must queue control transfers (not just bulk and iso), so
477 * both can talk to the same hub concurrently.
478 */
479static void hub_tt_work(struct work_struct *work)
480{
481        struct usb_hub          *hub =
482                container_of(work, struct usb_hub, tt.clear_work);
483        unsigned long           flags;
484        int                     limit = 100;
485
486        spin_lock_irqsave (&hub->tt.lock, flags);
487        while (--limit && !list_empty (&hub->tt.clear_list)) {
488                struct list_head        *next;
489                struct usb_tt_clear     *clear;
490                struct usb_device       *hdev = hub->hdev;
491                const struct hc_driver  *drv;
492                int                     status;
493
494                next = hub->tt.clear_list.next;
495                clear = list_entry (next, struct usb_tt_clear, clear_list);
496                list_del (&clear->clear_list);
497
498                /* drop lock so HCD can concurrently report other TT errors */
499                spin_unlock_irqrestore (&hub->tt.lock, flags);
500                status = hub_clear_tt_buffer (hdev, clear->devinfo, clear->tt);
501                if (status)
502                        dev_err (&hdev->dev,
503                                "clear tt %d (%04x) error %d\n",
504                                clear->tt, clear->devinfo, status);
505
506                /* Tell the HCD, even if the operation failed */
507                drv = clear->hcd->driver;
508                if (drv->clear_tt_buffer_complete)
509                        (drv->clear_tt_buffer_complete)(clear->hcd, clear->ep);
510
511                kfree(clear);
512                spin_lock_irqsave(&hub->tt.lock, flags);
513        }
514        spin_unlock_irqrestore (&hub->tt.lock, flags);
515}
516
517/**
518 * usb_hub_clear_tt_buffer - clear control/bulk TT state in high speed hub
519 * @urb: an URB associated with the failed or incomplete split transaction
520 *
521 * High speed HCDs use this to tell the hub driver that some split control or
522 * bulk transaction failed in a way that requires clearing internal state of
523 * a transaction translator.  This is normally detected (and reported) from
524 * interrupt context.
525 *
526 * It may not be possible for that hub to handle additional full (or low)
527 * speed transactions until that state is fully cleared out.
528 */
529int usb_hub_clear_tt_buffer(struct urb *urb)
530{
531        struct usb_device       *udev = urb->dev;
532        int                     pipe = urb->pipe;
533        struct usb_tt           *tt = udev->tt;
534        unsigned long           flags;
535        struct usb_tt_clear     *clear;
536
537        /* we've got to cope with an arbitrary number of pending TT clears,
538         * since each TT has "at least two" buffers that can need it (and
539         * there can be many TTs per hub).  even if they're uncommon.
540         */
541        if ((clear = kmalloc (sizeof *clear, GFP_ATOMIC)) == NULL) {
542                dev_err (&udev->dev, "can't save CLEAR_TT_BUFFER state\n");
543                /* FIXME recover somehow ... RESET_TT? */
544                return -ENOMEM;
545        }
546
547        /* info that CLEAR_TT_BUFFER needs */
548        clear->tt = tt->multi ? udev->ttport : 1;
549        clear->devinfo = usb_pipeendpoint (pipe);
550        clear->devinfo |= udev->devnum << 4;
551        clear->devinfo |= usb_pipecontrol (pipe)
552                        ? (USB_ENDPOINT_XFER_CONTROL << 11)
553                        : (USB_ENDPOINT_XFER_BULK << 11);
554        if (usb_pipein (pipe))
555                clear->devinfo |= 1 << 15;
556
557        /* info for completion callback */
558        clear->hcd = bus_to_hcd(udev->bus);
559        clear->ep = urb->ep;
560
561        /* tell keventd to clear state for this TT */
562        spin_lock_irqsave (&tt->lock, flags);
563        list_add_tail (&clear->clear_list, &tt->clear_list);
564        schedule_work(&tt->clear_work);
565        spin_unlock_irqrestore (&tt->lock, flags);
566        return 0;
567}
568EXPORT_SYMBOL_GPL(usb_hub_clear_tt_buffer);
569
570/* If do_delay is false, return the number of milliseconds the caller
571 * needs to delay.
572 */
573static unsigned hub_power_on(struct usb_hub *hub, bool do_delay)
574{
575        int port1;
576        unsigned pgood_delay = hub->descriptor->bPwrOn2PwrGood * 2;
577        unsigned delay;
578        u16 wHubCharacteristics =
579                        le16_to_cpu(hub->descriptor->wHubCharacteristics);
580
581        /* Enable power on each port.  Some hubs have reserved values
582         * of LPSM (> 2) in their descriptors, even though they are
583         * USB 2.0 hubs.  Some hubs do not implement port-power switching
584         * but only emulate it.  In all cases, the ports won't work
585         * unless we send these messages to the hub.
586         */
587        if ((wHubCharacteristics & HUB_CHAR_LPSM) < 2)
588                dev_dbg(hub->intfdev, "enabling power on all ports\n");
589        else
590                dev_dbg(hub->intfdev, "trying to enable port power on "
591                                "non-switchable hub\n");
592        for (port1 = 1; port1 <= hub->descriptor->bNbrPorts; port1++)
593                set_port_feature(hub->hdev, port1, USB_PORT_FEAT_POWER);
594
595        /* Wait at least 100 msec for power to become stable */
596        delay = max(pgood_delay, (unsigned) 100);
597        if (do_delay)
598                msleep(delay);
599        return delay;
600}
601
602static int hub_hub_status(struct usb_hub *hub,
603                u16 *status, u16 *change)
604{
605        int ret;
606
607        mutex_lock(&hub->status_mutex);
608        ret = get_hub_status(hub->hdev, &hub->status->hub);
609        if (ret < 0)
610                dev_err (hub->intfdev,
611                        "%s failed (err = %d)\n", __func__, ret);
612        else {
613                *status = le16_to_cpu(hub->status->hub.wHubStatus);
614                *change = le16_to_cpu(hub->status->hub.wHubChange);
615                ret = 0;
616        }
617        mutex_unlock(&hub->status_mutex);
618        return ret;
619}
620
621static int hub_port_disable(struct usb_hub *hub, int port1, int set_state)
622{
623        struct usb_device *hdev = hub->hdev;
624        int ret = 0;
625
626        if (hdev->children[port1-1] && set_state)
627                usb_set_device_state(hdev->children[port1-1],
628                                USB_STATE_NOTATTACHED);
629        if (!hub->error && !hub_is_superspeed(hub->hdev))
630                ret = clear_port_feature(hdev, port1, USB_PORT_FEAT_ENABLE);
631        if (ret)
632                dev_err(hub->intfdev, "cannot disable port %d (err = %d)\n",
633                                port1, ret);
634        return ret;
635}
636
637/*
638 * Disable a port and mark a logical connect-change event, so that some
639 * time later khubd will disconnect() any existing usb_device on the port
640 * and will re-enumerate if there actually is a device attached.
641 */
642static void hub_port_logical_disconnect(struct usb_hub *hub, int port1)
643{
644        dev_dbg(hub->intfdev, "logical disconnect on port %d\n", port1);
645        hub_port_disable(hub, port1, 1);
646
647        /* FIXME let caller ask to power down the port:
648         *  - some devices won't enumerate without a VBUS power cycle
649         *  - SRP saves power that way
650         *  - ... new call, TBD ...
651         * That's easy if this hub can switch power per-port, and
652         * khubd reactivates the port later (timer, SRP, etc).
653         * Powerdown must be optional, because of reset/DFU.
654         */
655
656        set_bit(port1, hub->change_bits);
657        kick_khubd(hub);
658}
659
660/**
661 * usb_remove_device - disable a device's port on its parent hub
662 * @udev: device to be disabled and removed
663 * Context: @udev locked, must be able to sleep.
664 *
665 * After @udev's port has been disabled, khubd is notified and it will
666 * see that the device has been disconnected.  When the device is
667 * physically unplugged and something is plugged in, the events will
668 * be received and processed normally.
669 */
670int usb_remove_device(struct usb_device *udev)
671{
672        struct usb_hub *hub;
673        struct usb_interface *intf;
674
675        if (!udev->parent)      /* Can't remove a root hub */
676                return -EINVAL;
677        hub = hdev_to_hub(udev->parent);
678        intf = to_usb_interface(hub->intfdev);
679
680        usb_autopm_get_interface(intf);
681        set_bit(udev->portnum, hub->removed_bits);
682        hub_port_logical_disconnect(hub, udev->portnum);
683        usb_autopm_put_interface(intf);
684        return 0;
685}
686
687enum hub_activation_type {
688        HUB_INIT, HUB_INIT2, HUB_INIT3,         /* INITs must come first */
689        HUB_POST_RESET, HUB_RESUME, HUB_RESET_RESUME,
690};
691
692static void hub_init_func2(struct work_struct *ws);
693static void hub_init_func3(struct work_struct *ws);
694
695static void hub_activate(struct usb_hub *hub, enum hub_activation_type type)
696{
697        struct usb_device *hdev = hub->hdev;
698        struct usb_hcd *hcd;
699        int ret;
700        int port1;
701        int status;
702        bool need_debounce_delay = false;
703        unsigned delay;
704
705        /* Continue a partial initialization */
706        if (type == HUB_INIT2)
707                goto init2;
708        if (type == HUB_INIT3)
709                goto init3;
710
711        /* After a resume, port power should still be on.
712         * For any other type of activation, turn it on.
713         */
714        if (type != HUB_RESUME) {
715
716                /* Speed up system boot by using a delayed_work for the
717                 * hub's initial power-up delays.  This is pretty awkward
718                 * and the implementation looks like a home-brewed sort of
719                 * setjmp/longjmp, but it saves at least 100 ms for each
720                 * root hub (assuming usbcore is compiled into the kernel
721                 * rather than as a module).  It adds up.
722                 *
723                 * This can't be done for HUB_RESUME or HUB_RESET_RESUME
724                 * because for those activation types the ports have to be
725                 * operational when we return.  In theory this could be done
726                 * for HUB_POST_RESET, but it's easier not to.
727                 */
728                if (type == HUB_INIT) {
729                        delay = hub_power_on(hub, false);
730                        PREPARE_DELAYED_WORK(&hub->init_work, hub_init_func2);
731                        schedule_delayed_work(&hub->init_work,
732                                        msecs_to_jiffies(delay));
733
734                        /* Suppress autosuspend until init is done */
735                        usb_autopm_get_interface_no_resume(
736                                        to_usb_interface(hub->intfdev));
737                        return;         /* Continues at init2: below */
738                } else if (type == HUB_RESET_RESUME) {
739                        /* The internal host controller state for the hub device
740                         * may be gone after a host power loss on system resume.
741                         * Update the device's info so the HW knows it's a hub.
742                         */
743                        hcd = bus_to_hcd(hdev->bus);
744                        if (hcd->driver->update_hub_device) {
745                                ret = hcd->driver->update_hub_device(hcd, hdev,
746                                                &hub->tt, GFP_NOIO);
747                                if (ret < 0) {
748                                        dev_err(hub->intfdev, "Host not "
749                                                        "accepting hub info "
750                                                        "update.\n");
751                                        dev_err(hub->intfdev, "LS/FS devices "
752                                                        "and hubs may not work "
753                                                        "under this hub\n.");
754                                }
755                        }
756                        hub_power_on(hub, true);
757                } else {
758                        hub_power_on(hub, true);
759                }
760        }
761 init2:
762
763        /* Check each port and set hub->change_bits to let khubd know
764         * which ports need attention.
765         */
766        for (port1 = 1; port1 <= hdev->maxchild; ++port1) {
767                struct usb_device *udev = hdev->children[port1-1];
768                u16 portstatus, portchange;
769
770                portstatus = portchange = 0;
771                status = hub_port_status(hub, port1, &portstatus, &portchange);
772                if (udev || (portstatus & USB_PORT_STAT_CONNECTION))
773                        dev_dbg(hub->intfdev,
774                                        "port %d: status %04x change %04x\n",
775                                        port1, portstatus, portchange);
776
777                /* After anything other than HUB_RESUME (i.e., initialization
778                 * or any sort of reset), every port should be disabled.
779                 * Unconnected ports should likewise be disabled (paranoia),
780                 * and so should ports for which we have no usb_device.
781                 */
782                if ((portstatus & USB_PORT_STAT_ENABLE) && (
783                                type != HUB_RESUME ||
784                                !(portstatus & USB_PORT_STAT_CONNECTION) ||
785                                !udev ||
786                                udev->state == USB_STATE_NOTATTACHED)) {
787                        /*
788                         * USB3 protocol ports will automatically transition
789                         * to Enabled state when detect an USB3.0 device attach.
790                         * Do not disable USB3 protocol ports.
791                         */
792                        if (!hub_is_superspeed(hdev)) {
793                                clear_port_feature(hdev, port1,
794                                                   USB_PORT_FEAT_ENABLE);
795                                portstatus &= ~USB_PORT_STAT_ENABLE;
796                        } else {
797                                /* Pretend that power was lost for USB3 devs */
798                                portstatus &= ~USB_PORT_STAT_ENABLE;
799                        }
800                }
801
802                /* Clear status-change flags; we'll debounce later */
803                if (portchange & USB_PORT_STAT_C_CONNECTION) {
804                        need_debounce_delay = true;
805                        clear_port_feature(hub->hdev, port1,
806                                        USB_PORT_FEAT_C_CONNECTION);
807                }
808                if (portchange & USB_PORT_STAT_C_ENABLE) {
809                        need_debounce_delay = true;
810                        clear_port_feature(hub->hdev, port1,
811                                        USB_PORT_FEAT_C_ENABLE);
812                }
813                if (portchange & USB_PORT_STAT_C_LINK_STATE) {
814                        need_debounce_delay = true;
815                        clear_port_feature(hub->hdev, port1,
816                                        USB_PORT_FEAT_C_PORT_LINK_STATE);
817                }
818
819                if ((portchange & USB_PORT_STAT_C_BH_RESET) &&
820                                hub_is_superspeed(hub->hdev)) {
821                        need_debounce_delay = true;
822                        clear_port_feature(hub->hdev, port1,
823                                        USB_PORT_FEAT_C_BH_PORT_RESET);
824                }
825                /* We can forget about a "removed" device when there's a
826                 * physical disconnect or the connect status changes.
827                 */
828                if (!(portstatus & USB_PORT_STAT_CONNECTION) ||
829                                (portchange & USB_PORT_STAT_C_CONNECTION))
830                        clear_bit(port1, hub->removed_bits);
831
832                if (!udev || udev->state == USB_STATE_NOTATTACHED) {
833                        /* Tell khubd to disconnect the device or
834                         * check for a new connection
835                         */
836                        if (udev || (portstatus & USB_PORT_STAT_CONNECTION))
837                                set_bit(port1, hub->change_bits);
838
839                } else if (portstatus & USB_PORT_STAT_ENABLE) {
840                        /* The power session apparently survived the resume.
841                         * If there was an overcurrent or suspend change
842                         * (i.e., remote wakeup request), have khubd
843                         * take care of it.
844                         */
845                        if (portchange)
846                                set_bit(port1, hub->change_bits);
847
848                } else if (udev->persist_enabled) {
849#ifdef CONFIG_PM
850                        udev->reset_resume = 1;
851#endif
852                        set_bit(port1, hub->change_bits);
853
854                } else {
855                        /* The power session is gone; tell khubd */
856                        usb_set_device_state(udev, USB_STATE_NOTATTACHED);
857                        set_bit(port1, hub->change_bits);
858                }
859        }
860
861        /* If no port-status-change flags were set, we don't need any
862         * debouncing.  If flags were set we can try to debounce the
863         * ports all at once right now, instead of letting khubd do them
864         * one at a time later on.
865         *
866         * If any port-status changes do occur during this delay, khubd
867         * will see them later and handle them normally.
868         */
869        if (need_debounce_delay) {
870                delay = HUB_DEBOUNCE_STABLE;
871
872                /* Don't do a long sleep inside a workqueue routine */
873                if (type == HUB_INIT2) {
874                        PREPARE_DELAYED_WORK(&hub->init_work, hub_init_func3);
875                        schedule_delayed_work(&hub->init_work,
876                                        msecs_to_jiffies(delay));
877                        return;         /* Continues at init3: below */
878                } else {
879                        msleep(delay);
880                }
881        }
882 init3:
883        hub->quiescing = 0;
884
885        status = usb_submit_urb(hub->urb, GFP_NOIO);
886        if (status < 0)
887                dev_err(hub->intfdev, "activate --> %d\n", status);
888        if (hub->has_indicators && blinkenlights)
889                schedule_delayed_work(&hub->leds, LED_CYCLE_PERIOD);
890
891        /* Scan all ports that need attention */
892        kick_khubd(hub);
893
894        /* Allow autosuspend if it was suppressed */
895        if (type <= HUB_INIT3)
896                usb_autopm_put_interface_async(to_usb_interface(hub->intfdev));
897}
898
899/* Implement the continuations for the delays above */
900static void hub_init_func2(struct work_struct *ws)
901{
902        struct usb_hub *hub = container_of(ws, struct usb_hub, init_work.work);
903
904        hub_activate(hub, HUB_INIT2);
905}
906
907static void hub_init_func3(struct work_struct *ws)
908{
909        struct usb_hub *hub = container_of(ws, struct usb_hub, init_work.work);
910
911        hub_activate(hub, HUB_INIT3);
912}
913
914enum hub_quiescing_type {
915        HUB_DISCONNECT, HUB_PRE_RESET, HUB_SUSPEND
916};
917
918static void hub_quiesce(struct usb_hub *hub, enum hub_quiescing_type type)
919{
920        struct usb_device *hdev = hub->hdev;
921        int i;
922
923        cancel_delayed_work_sync(&hub->init_work);
924
925        /* khubd and related activity won't re-trigger */
926        hub->quiescing = 1;
927
928        if (type != HUB_SUSPEND) {
929                /* Disconnect all the children */
930                for (i = 0; i < hdev->maxchild; ++i) {
931                        if (hdev->children[i])
932                                usb_disconnect(&hdev->children[i]);
933                }
934        }
935
936        /* Stop khubd and related activity */
937        usb_kill_urb(hub->urb);
938        if (hub->has_indicators)
939                cancel_delayed_work_sync(&hub->leds);
940        if (hub->tt.hub)
941                cancel_work_sync(&hub->tt.clear_work);
942}
943
944/* caller has locked the hub device */
945static int hub_pre_reset(struct usb_interface *intf)
946{
947        struct usb_hub *hub = usb_get_intfdata(intf);
948
949        hub_quiesce(hub, HUB_PRE_RESET);
950        return 0;
951}
952
953/* caller has locked the hub device */
954static int hub_post_reset(struct usb_interface *intf)
955{
956        struct usb_hub *hub = usb_get_intfdata(intf);
957
958        hub_activate(hub, HUB_POST_RESET);
959        return 0;
960}
961
962static int hub_configure(struct usb_hub *hub,
963        struct usb_endpoint_descriptor *endpoint)
964{
965        struct usb_hcd *hcd;
966        struct usb_device *hdev = hub->hdev;
967        struct device *hub_dev = hub->intfdev;
968        u16 hubstatus, hubchange;
969        u16 wHubCharacteristics;
970        unsigned int pipe;
971        int maxp, ret;
972        char *message = "out of memory";
973
974        hub->buffer = kmalloc(sizeof(*hub->buffer), GFP_KERNEL);
975        if (!hub->buffer) {
976                ret = -ENOMEM;
977                goto fail;
978        }
979
980        hub->status = kmalloc(sizeof(*hub->status), GFP_KERNEL);
981        if (!hub->status) {
982                ret = -ENOMEM;
983                goto fail;
984        }
985        mutex_init(&hub->status_mutex);
986
987        hub->descriptor = kmalloc(sizeof(*hub->descriptor), GFP_KERNEL);
988        if (!hub->descriptor) {
989                ret = -ENOMEM;
990                goto fail;
991        }
992
993        if (hub_is_superspeed(hdev) && (hdev->parent != NULL)) {
994                ret = usb_control_msg(hdev, usb_sndctrlpipe(hdev, 0),
995                                HUB_SET_DEPTH, USB_RT_HUB,
996                                hdev->level - 1, 0, NULL, 0,
997                                USB_CTRL_SET_TIMEOUT);
998
999                if (ret < 0) {
1000                        message = "can't set hub depth";
1001                        goto fail;
1002                }
1003        }
1004
1005        /* Request the entire hub descriptor.
1006         * hub->descriptor can handle USB_MAXCHILDREN ports,
1007         * but the hub can/will return fewer bytes here.
1008         */
1009        ret = get_hub_descriptor(hdev, hub->descriptor);
1010        if (ret < 0) {
1011                message = "can't read hub descriptor";
1012                goto fail;
1013        } else if (hub->descriptor->bNbrPorts > USB_MAXCHILDREN) {
1014                message = "hub has too many ports!";
1015                ret = -ENODEV;
1016                goto fail;
1017        }
1018
1019        hdev->maxchild = hub->descriptor->bNbrPorts;
1020        dev_info (hub_dev, "%d port%s detected\n", hdev->maxchild,
1021                (hdev->maxchild == 1) ? "" : "s");
1022
1023        hub->port_owners = kzalloc(hdev->maxchild * sizeof(void *), GFP_KERNEL);
1024        if (!hub->port_owners) {
1025                ret = -ENOMEM;
1026                goto fail;
1027        }
1028
1029        wHubCharacteristics = le16_to_cpu(hub->descriptor->wHubCharacteristics);
1030
1031        /* FIXME for USB 3.0, skip for now */
1032        if ((wHubCharacteristics & HUB_CHAR_COMPOUND) &&
1033                        !(hub_is_superspeed(hdev))) {
1034                int     i;
1035                char    portstr [USB_MAXCHILDREN + 1];
1036
1037                for (i = 0; i < hdev->maxchild; i++)
1038                        portstr[i] = hub->descriptor->u.hs.DeviceRemovable
1039                                    [((i + 1) / 8)] & (1 << ((i + 1) % 8))
1040                                ? 'F' : 'R';
1041                portstr[hdev->maxchild] = 0;
1042                dev_dbg(hub_dev, "compound device; port removable status: %s\n", portstr);
1043        } else
1044                dev_dbg(hub_dev, "standalone hub\n");
1045
1046        switch (wHubCharacteristics & HUB_CHAR_LPSM) {
1047                case 0x00:
1048                        dev_dbg(hub_dev, "ganged power switching\n");
1049                        break;
1050                case 0x01:
1051                        dev_dbg(hub_dev, "individual port power switching\n");
1052                        break;
1053                case 0x02:
1054                case 0x03:
1055                        dev_dbg(hub_dev, "no power switching (usb 1.0)\n");
1056                        break;
1057        }
1058
1059        switch (wHubCharacteristics & HUB_CHAR_OCPM) {
1060                case 0x00:
1061                        dev_dbg(hub_dev, "global over-current protection\n");
1062                        break;
1063                case 0x08:
1064                        dev_dbg(hub_dev, "individual port over-current protection\n");
1065                        break;
1066                case 0x10:
1067                case 0x18:
1068                        dev_dbg(hub_dev, "no over-current protection\n");
1069                        break;
1070        }
1071
1072        spin_lock_init (&hub->tt.lock);
1073        INIT_LIST_HEAD (&hub->tt.clear_list);
1074        INIT_WORK(&hub->tt.clear_work, hub_tt_work);
1075        switch (hdev->descriptor.bDeviceProtocol) {
1076                case 0:
1077                        break;
1078                case 1:
1079                        dev_dbg(hub_dev, "Single TT\n");
1080                        hub->tt.hub = hdev;
1081                        break;
1082                case 2:
1083                        ret = usb_set_interface(hdev, 0, 1);
1084                        if (ret == 0) {
1085                                dev_dbg(hub_dev, "TT per port\n");
1086                                hub->tt.multi = 1;
1087                        } else
1088                                dev_err(hub_dev, "Using single TT (err %d)\n",
1089                                        ret);
1090                        hub->tt.hub = hdev;
1091                        break;
1092                case 3:
1093                        /* USB 3.0 hubs don't have a TT */
1094                        break;
1095                default:
1096                        dev_dbg(hub_dev, "Unrecognized hub protocol %d\n",
1097                                hdev->descriptor.bDeviceProtocol);
1098                        break;
1099        }
1100
1101        /* Note 8 FS bit times == (8 bits / 12000000 bps) ~= 666ns */
1102        switch (wHubCharacteristics & HUB_CHAR_TTTT) {
1103                case HUB_TTTT_8_BITS:
1104                        if (hdev->descriptor.bDeviceProtocol != 0) {
1105                                hub->tt.think_time = 666;
1106                                dev_dbg(hub_dev, "TT requires at most %d "
1107                                                "FS bit times (%d ns)\n",
1108                                        8, hub->tt.think_time);
1109                        }
1110                        break;
1111                case HUB_TTTT_16_BITS:
1112                        hub->tt.think_time = 666 * 2;
1113                        dev_dbg(hub_dev, "TT requires at most %d "
1114                                        "FS bit times (%d ns)\n",
1115                                16, hub->tt.think_time);
1116                        break;
1117                case HUB_TTTT_24_BITS:
1118                        hub->tt.think_time = 666 * 3;
1119                        dev_dbg(hub_dev, "TT requires at most %d "
1120                                        "FS bit times (%d ns)\n",
1121                                24, hub->tt.think_time);
1122                        break;
1123                case HUB_TTTT_32_BITS:
1124                        hub->tt.think_time = 666 * 4;
1125                        dev_dbg(hub_dev, "TT requires at most %d "
1126                                        "FS bit times (%d ns)\n",
1127                                32, hub->tt.think_time);
1128                        break;
1129        }
1130
1131        /* probe() zeroes hub->indicator[] */
1132        if (wHubCharacteristics & HUB_CHAR_PORTIND) {
1133                hub->has_indicators = 1;
1134                dev_dbg(hub_dev, "Port indicators are supported\n");
1135        }
1136
1137        dev_dbg(hub_dev, "power on to power good time: %dms\n",
1138                hub->descriptor->bPwrOn2PwrGood * 2);
1139
1140        /* power budgeting mostly matters with bus-powered hubs,
1141         * and battery-powered root hubs (may provide just 8 mA).
1142         */
1143        ret = usb_get_status(hdev, USB_RECIP_DEVICE, 0, &hubstatus);
1144        if (ret < 2) {
1145                message = "can't get hub status";
1146                goto fail;
1147        }
1148        le16_to_cpus(&hubstatus);
1149        if (hdev == hdev->bus->root_hub) {
1150                if (hdev->bus_mA == 0 || hdev->bus_mA >= 500)
1151                        hub->mA_per_port = 500;
1152                else {
1153                        hub->mA_per_port = hdev->bus_mA;
1154                        hub->limited_power = 1;
1155                }
1156        } else if ((hubstatus & (1 << USB_DEVICE_SELF_POWERED)) == 0) {
1157                dev_dbg(hub_dev, "hub controller current requirement: %dmA\n",
1158                        hub->descriptor->bHubContrCurrent);
1159                hub->limited_power = 1;
1160                if (hdev->maxchild > 0) {
1161                        int remaining = hdev->bus_mA -
1162                                        hub->descriptor->bHubContrCurrent;
1163
1164                        if (remaining < hdev->maxchild * 100)
1165                                dev_warn(hub_dev,
1166                                        "insufficient power available "
1167                                        "to use all downstream ports\n");
1168                        hub->mA_per_port = 100;         /* 7.2.1.1 */
1169                }
1170        } else {        /* Self-powered external hub */
1171                /* FIXME: What about battery-powered external hubs that
1172                 * provide less current per port? */
1173                hub->mA_per_port = 500;
1174        }
1175        if (hub->mA_per_port < 500)
1176                dev_dbg(hub_dev, "%umA bus power budget for each child\n",
1177                                hub->mA_per_port);
1178
1179        /* Update the HCD's internal representation of this hub before khubd
1180         * starts getting port status changes for devices under the hub.
1181         */
1182        hcd = bus_to_hcd(hdev->bus);
1183        if (hcd->driver->update_hub_device) {
1184                ret = hcd->driver->update_hub_device(hcd, hdev,
1185                                &hub->tt, GFP_KERNEL);
1186                if (ret < 0) {
1187                        message = "can't update HCD hub info";
1188                        goto fail;
1189                }
1190        }
1191
1192        ret = hub_hub_status(hub, &hubstatus, &hubchange);
1193        if (ret < 0) {
1194                message = "can't get hub status";
1195                goto fail;
1196        }
1197
1198        /* local power status reports aren't always correct */
1199        if (hdev->actconfig->desc.bmAttributes & USB_CONFIG_ATT_SELFPOWER)
1200                dev_dbg(hub_dev, "local power source is %s\n",
1201                        (hubstatus & HUB_STATUS_LOCAL_POWER)
1202                        ? "lost (inactive)" : "good");
1203
1204        if ((wHubCharacteristics & HUB_CHAR_OCPM) == 0)
1205                dev_dbg(hub_dev, "%sover-current condition exists\n",
1206                        (hubstatus & HUB_STATUS_OVERCURRENT) ? "" : "no ");
1207
1208        /* set up the interrupt endpoint
1209         * We use the EP's maxpacket size instead of (PORTS+1+7)/8
1210         * bytes as USB2.0[11.12.3] says because some hubs are known
1211         * to send more data (and thus cause overflow). For root hubs,
1212         * maxpktsize is defined in hcd.c's fake endpoint descriptors
1213         * to be big enough for at least USB_MAXCHILDREN ports. */
1214        pipe = usb_rcvintpipe(hdev, endpoint->bEndpointAddress);
1215        maxp = usb_maxpacket(hdev, pipe, usb_pipeout(pipe));
1216
1217        if (maxp > sizeof(*hub->buffer))
1218                maxp = sizeof(*hub->buffer);
1219
1220        hub->urb = usb_alloc_urb(0, GFP_KERNEL);
1221        if (!hub->urb) {
1222                ret = -ENOMEM;
1223                goto fail;
1224        }
1225
1226        usb_fill_int_urb(hub->urb, hdev, pipe, *hub->buffer, maxp, hub_irq,
1227                hub, endpoint->bInterval);
1228
1229        /* maybe cycle the hub leds */
1230        if (hub->has_indicators && blinkenlights)
1231                hub->indicator [0] = INDICATOR_CYCLE;
1232
1233        hub_activate(hub, HUB_INIT);
1234        return 0;
1235
1236fail:
1237        dev_err (hub_dev, "config failed, %s (err %d)\n",
1238                        message, ret);
1239        /* hub_disconnect() frees urb and descriptor */
1240        return ret;
1241}
1242
1243static void hub_release(struct kref *kref)
1244{
1245        struct usb_hub *hub = container_of(kref, struct usb_hub, kref);
1246
1247        usb_put_intf(to_usb_interface(hub->intfdev));
1248        kfree(hub);
1249}
1250
1251static unsigned highspeed_hubs;
1252
1253static void hub_disconnect(struct usb_interface *intf)
1254{
1255        struct usb_hub *hub = usb_get_intfdata (intf);
1256
1257        /* Take the hub off the event list and don't let it be added again */
1258        spin_lock_irq(&hub_event_lock);
1259        if (!list_empty(&hub->event_list)) {
1260                list_del_init(&hub->event_list);
1261                usb_autopm_put_interface_no_suspend(intf);
1262        }
1263        hub->disconnected = 1;
1264        spin_unlock_irq(&hub_event_lock);
1265
1266        /* Disconnect all children and quiesce the hub */
1267        hub->error = 0;
1268        hub_quiesce(hub, HUB_DISCONNECT);
1269
1270        usb_set_intfdata (intf, NULL);
1271        hub->hdev->maxchild = 0;
1272
1273        if (hub->hdev->speed == USB_SPEED_HIGH)
1274                highspeed_hubs--;
1275
1276        usb_free_urb(hub->urb);
1277        kfree(hub->port_owners);
1278        kfree(hub->descriptor);
1279        kfree(hub->status);
1280        kfree(hub->buffer);
1281
1282        kref_put(&hub->kref, hub_release);
1283}
1284
1285static int hub_probe(struct usb_interface *intf, const struct usb_device_id *id)
1286{
1287        struct usb_host_interface *desc;
1288        struct usb_endpoint_descriptor *endpoint;
1289        struct usb_device *hdev;
1290        struct usb_hub *hub;
1291
1292        desc = intf->cur_altsetting;
1293        hdev = interface_to_usbdev(intf);
1294
1295#if defined(CONFIG_MACH_AR7100) || defined(CONFIG_MACH_AR7240) || defined(CONFIG_LANTIQ)
1296        ap_usb_led_off();
1297#endif
1298
1299        /* Hubs have proper suspend/resume support.  USB 3.0 device suspend is
1300         * different from USB 2.0/1.1 device suspend, and unfortunately we
1301         * don't support it yet.  So leave autosuspend disabled for USB 3.0
1302         * external hubs for now.  Enable autosuspend for USB 3.0 roothubs,
1303         * since that isn't a "real" hub.
1304         */
1305        if (!hub_is_superspeed(hdev) || !hdev->parent)
1306                usb_enable_autosuspend(hdev);
1307
1308        if (hdev->level == MAX_TOPO_LEVEL) {
1309                dev_err(&intf->dev,
1310                        "Unsupported bus topology: hub nested too deep\n");
1311                return -E2BIG;
1312        }
1313
1314#ifdef  CONFIG_USB_OTG_BLACKLIST_HUB
1315        if (hdev->parent) {
1316                dev_warn(&intf->dev, "ignoring external hub\n");
1317                return -ENODEV;
1318        }
1319#endif
1320
1321        /* Some hubs have a subclass of 1, which AFAICT according to the */
1322        /*  specs is not defined, but it works */
1323        if ((desc->desc.bInterfaceSubClass != 0) &&
1324            (desc->desc.bInterfaceSubClass != 1)) {
1325descriptor_error:
1326                dev_err (&intf->dev, "bad descriptor, ignoring hub\n");
1327                return -EIO;
1328        }
1329
1330        /* Multiple endpoints? What kind of mutant ninja-hub is this? */
1331        if (desc->desc.bNumEndpoints != 1)
1332                goto descriptor_error;
1333
1334        endpoint = &desc->endpoint[0].desc;
1335
1336        /* If it's not an interrupt in endpoint, we'd better punt! */
1337        if (!usb_endpoint_is_int_in(endpoint))
1338                goto descriptor_error;
1339
1340        /* We found a hub */
1341        dev_info (&intf->dev, "USB hub found\n");
1342
1343        hub = kzalloc(sizeof(*hub), GFP_KERNEL);
1344        if (!hub) {
1345                dev_dbg (&intf->dev, "couldn't kmalloc hub struct\n");
1346                return -ENOMEM;
1347        }
1348
1349        kref_init(&hub->kref);
1350        INIT_LIST_HEAD(&hub->event_list);
1351        hub->intfdev = &intf->dev;
1352        hub->hdev = hdev;
1353        INIT_DELAYED_WORK(&hub->leds, led_work);
1354        INIT_DELAYED_WORK(&hub->init_work, NULL);
1355        usb_get_intf(intf);
1356
1357        usb_set_intfdata (intf, hub);
1358        intf->needs_remote_wakeup = 1;
1359
1360        if (hdev->speed == USB_SPEED_HIGH)
1361                highspeed_hubs++;
1362
1363        if (hub_configure(hub, endpoint) >= 0)
1364                return 0;
1365
1366        hub_disconnect (intf);
1367        return -ENODEV;
1368}
1369
1370/* No BKL needed */
1371static int
1372hub_ioctl(struct usb_interface *intf, unsigned int code, void *user_data)
1373{
1374        struct usb_device *hdev = interface_to_usbdev (intf);
1375
1376        /* assert ifno == 0 (part of hub spec) */
1377        switch (code) {
1378        case USBDEVFS_HUB_PORTINFO: {
1379                struct usbdevfs_hub_portinfo *info = user_data;
1380                int i;
1381
1382                spin_lock_irq(&device_state_lock);
1383                if (hdev->devnum <= 0)
1384                        info->nports = 0;
1385                else {
1386                        info->nports = hdev->maxchild;
1387                        for (i = 0; i < info->nports; i++) {
1388                                if (hdev->children[i] == NULL)
1389                                        info->port[i] = 0;
1390                                else
1391                                        info->port[i] =
1392                                                hdev->children[i]->devnum;
1393                        }
1394                }
1395                spin_unlock_irq(&device_state_lock);
1396
1397                return info->nports + 1;
1398                }
1399
1400        default:
1401                return -ENOSYS;
1402        }
1403}
1404
1405/*
1406 * Allow user programs to claim ports on a hub.  When a device is attached
1407 * to one of these "claimed" ports, the program will "own" the device.
1408 */
1409static int find_port_owner(struct usb_device *hdev, unsigned port1,
1410                void ***ppowner)
1411{
1412        if (hdev->state == USB_STATE_NOTATTACHED)
1413                return -ENODEV;
1414        if (port1 == 0 || port1 > hdev->maxchild)
1415                return -EINVAL;
1416
1417        /* This assumes that devices not managed by the hub driver
1418         * will always have maxchild equal to 0.
1419         */
1420        *ppowner = &(hdev_to_hub(hdev)->port_owners[port1 - 1]);
1421        return 0;
1422}
1423
1424/* In the following three functions, the caller must hold hdev's lock */
1425int usb_hub_claim_port(struct usb_device *hdev, unsigned port1, void *owner)
1426{
1427        int rc;
1428        void **powner;
1429
1430        rc = find_port_owner(hdev, port1, &powner);
1431        if (rc)
1432                return rc;
1433        if (*powner)
1434                return -EBUSY;
1435        *powner = owner;
1436        return rc;
1437}
1438
1439int usb_hub_release_port(struct usb_device *hdev, unsigned port1, void *owner)
1440{
1441        int rc;
1442        void **powner;
1443
1444        rc = find_port_owner(hdev, port1, &powner);
1445        if (rc)
1446                return rc;
1447        if (*powner != owner)
1448                return -ENOENT;
1449        *powner = NULL;
1450        return rc;
1451}
1452
1453void usb_hub_release_all_ports(struct usb_device *hdev, void *owner)
1454{
1455        int n;
1456        void **powner;
1457
1458        n = find_port_owner(hdev, 1, &powner);
1459        if (n == 0) {
1460                for (; n < hdev->maxchild; (++n, ++powner)) {
1461                        if (*powner == owner)
1462                                *powner = NULL;
1463                }
1464        }
1465}
1466
1467/* The caller must hold udev's lock */
1468bool usb_device_is_owned(struct usb_device *udev)
1469{
1470        struct usb_hub *hub;
1471
1472        if (udev->state == USB_STATE_NOTATTACHED || !udev->parent)
1473                return false;
1474        hub = hdev_to_hub(udev->parent);
1475        return !!hub->port_owners[udev->portnum - 1];
1476}
1477
1478
1479static void recursively_mark_NOTATTACHED(struct usb_device *udev)
1480{
1481        int i;
1482
1483        for (i = 0; i < udev->maxchild; ++i) {
1484                if (udev->children[i])
1485                        recursively_mark_NOTATTACHED(udev->children[i]);
1486        }
1487        if (udev->state == USB_STATE_SUSPENDED)
1488                udev->active_duration -= jiffies;
1489        udev->state = USB_STATE_NOTATTACHED;
1490}
1491
1492/**
1493 * usb_set_device_state - change a device's current state (usbcore, hcds)
1494 * @udev: pointer to device whose state should be changed
1495 * @new_state: new state value to be stored
1496 *
1497 * udev->state is _not_ fully protected by the device lock.  Although
1498 * most transitions are made only while holding the lock, the state can
1499 * can change to USB_STATE_NOTATTACHED at almost any time.  This
1500 * is so that devices can be marked as disconnected as soon as possible,
1501 * without having to wait for any semaphores to be released.  As a result,
1502 * all changes to any device's state must be protected by the
1503 * device_state_lock spinlock.
1504 *
1505 * Once a device has been added to the device tree, all changes to its state
1506 * should be made using this routine.  The state should _not_ be set directly.
1507 *
1508 * If udev->state is already USB_STATE_NOTATTACHED then no change is made.
1509 * Otherwise udev->state is set to new_state, and if new_state is
1510 * USB_STATE_NOTATTACHED then all of udev's descendants' states are also set
1511 * to USB_STATE_NOTATTACHED.
1512 */
1513void usb_set_device_state(struct usb_device *udev,
1514                enum usb_device_state new_state)
1515{
1516        unsigned long flags;
1517        int wakeup = -1;
1518
1519        spin_lock_irqsave(&device_state_lock, flags);
1520        if (udev->state == USB_STATE_NOTATTACHED)
1521                ;       /* do nothing */
1522        else if (new_state != USB_STATE_NOTATTACHED) {
1523
1524                /* root hub wakeup capabilities are managed out-of-band
1525                 * and may involve silicon errata ... ignore them here.
1526                 */
1527                if (udev->parent) {
1528                        if (udev->state == USB_STATE_SUSPENDED
1529                                        || new_state == USB_STATE_SUSPENDED)
1530                                ;       /* No change to wakeup settings */
1531                        else if (new_state == USB_STATE_CONFIGURED)
1532                                wakeup = udev->actconfig->desc.bmAttributes
1533                                         & USB_CONFIG_ATT_WAKEUP;
1534                        else
1535                                wakeup = 0;
1536                }
1537                if (udev->state == USB_STATE_SUSPENDED &&
1538                        new_state != USB_STATE_SUSPENDED)
1539                        udev->active_duration -= jiffies;
1540                else if (new_state == USB_STATE_SUSPENDED &&
1541                                udev->state != USB_STATE_SUSPENDED)
1542                        udev->active_duration += jiffies;
1543                udev->state = new_state;
1544        } else
1545                recursively_mark_NOTATTACHED(udev);
1546        spin_unlock_irqrestore(&device_state_lock, flags);
1547        if (wakeup >= 0)
1548                device_set_wakeup_capable(&udev->dev, wakeup);
1549}
1550EXPORT_SYMBOL_GPL(usb_set_device_state);
1551
1552/*
1553 * Choose a device number.
1554 *
1555 * Device numbers are used as filenames in usbfs.  On USB-1.1 and
1556 * USB-2.0 buses they are also used as device addresses, however on
1557 * USB-3.0 buses the address is assigned by the controller hardware
1558 * and it usually is not the same as the device number.
1559 *
1560 * WUSB devices are simple: they have no hubs behind, so the mapping
1561 * device <-> virtual port number becomes 1:1. Why? to simplify the
1562 * life of the device connection logic in
1563 * drivers/usb/wusbcore/devconnect.c. When we do the initial secret
1564 * handshake we need to assign a temporary address in the unauthorized
1565 * space. For simplicity we use the first virtual port number found to
1566 * be free [drivers/usb/wusbcore/devconnect.c:wusbhc_devconnect_ack()]
1567 * and that becomes it's address [X < 128] or its unauthorized address
1568 * [X | 0x80].
1569 *
1570 * We add 1 as an offset to the one-based USB-stack port number
1571 * (zero-based wusb virtual port index) for two reasons: (a) dev addr
1572 * 0 is reserved by USB for default address; (b) Linux's USB stack
1573 * uses always #1 for the root hub of the controller. So USB stack's
1574 * port #1, which is wusb virtual-port #0 has address #2.
1575 *
1576 * Devices connected under xHCI are not as simple.  The host controller
1577 * supports virtualization, so the hardware assigns device addresses and
1578 * the HCD must setup data structures before issuing a set address
1579 * command to the hardware.
1580 */
1581static void choose_devnum(struct usb_device *udev)
1582{
1583        int             devnum;
1584        struct usb_bus  *bus = udev->bus;
1585
1586        /* If khubd ever becomes multithreaded, this will need a lock */
1587        if (udev->wusb) {
1588                devnum = udev->portnum + 1;
1589                BUG_ON(test_bit(devnum, bus->devmap.devicemap));
1590        } else {
1591                /* Try to allocate the next devnum beginning at
1592                 * bus->devnum_next. */
1593                devnum = find_next_zero_bit(bus->devmap.devicemap, 128,
1594                                            bus->devnum_next);
1595                if (devnum >= 128)
1596                        devnum = find_next_zero_bit(bus->devmap.devicemap,
1597                                                    128, 1);
1598                bus->devnum_next = ( devnum >= 127 ? 1 : devnum + 1);
1599        }
1600        if (devnum < 128) {
1601                set_bit(devnum, bus->devmap.devicemap);
1602                udev->devnum = devnum;
1603        }
1604}
1605
1606static void release_devnum(struct usb_device *udev)
1607{
1608        if (udev->devnum > 0) {
1609                clear_bit(udev->devnum, udev->bus->devmap.devicemap);
1610                udev->devnum = -1;
1611        }
1612}
1613
1614static void update_devnum(struct usb_device *udev, int devnum)
1615{
1616        /* The address for a WUSB device is managed by wusbcore. */
1617        if (!udev->wusb)
1618                udev->devnum = devnum;
1619}
1620
1621static void hub_free_dev(struct usb_device *udev)
1622{
1623        struct usb_hcd *hcd = bus_to_hcd(udev->bus);
1624
1625        /* Root hubs aren't real devices, so don't free HCD resources */
1626        if (hcd->driver->free_dev && udev->parent)
1627                hcd->driver->free_dev(hcd, udev);
1628}
1629
1630/**
1631 * usb_disconnect - disconnect a device (usbcore-internal)
1632 * @pdev: pointer to device being disconnected
1633 * Context: !in_interrupt ()
1634 *
1635 * Something got disconnected. Get rid of it and all of its children.
1636 *
1637 * If *pdev is a normal device then the parent hub must already be locked.
1638 * If *pdev is a root hub then this routine will acquire the
1639 * usb_bus_list_lock on behalf of the caller.
1640 *
1641 * Only hub drivers (including virtual root hub drivers for host
1642 * controllers) should ever call this.
1643 *
1644 * This call is synchronous, and may not be used in an interrupt context.
1645 */
1646void usb_disconnect(struct usb_device **pdev)
1647{
1648        struct usb_device       *udev = *pdev;
1649        int                     i;
1650        struct usb_hcd          *hcd = bus_to_hcd(udev->bus);
1651
1652        /* mark the device as inactive, so any further urb submissions for
1653         * this device (and any of its children) will fail immediately.
1654         * this quiesces everything except pending urbs.
1655         */
1656        usb_set_device_state(udev, USB_STATE_NOTATTACHED);
1657        dev_info(&udev->dev, "USB disconnect, device number %d\n",
1658                        udev->devnum);
1659
1660#if defined(CONFIG_MACH_AR7100) || defined(CONFIG_MACH_AR7240) || defined(CONFIG_LANTIQ)
1661        /* Turn USB LED off only if its a last device attached to root hub */
1662        if(udev->parent == udev->bus->root_hub)
1663                ap_usb_led_off();
1664#endif
1665
1666        usb_lock_device(udev);
1667
1668        /* Free up all the children before we remove this device */
1669        for (i = 0; i < USB_MAXCHILDREN; i++) {
1670                if (udev->children[i])
1671                        usb_disconnect(&udev->children[i]);
1672        }
1673
1674        /* deallocate hcd/hardware state ... nuking all pending urbs and
1675         * cleaning up all state associated with the current configuration
1676         * so that the hardware is now fully quiesced.
1677         */
1678        dev_dbg (&udev->dev, "unregistering device\n");
1679        mutex_lock(hcd->bandwidth_mutex);
1680        usb_disable_device(udev, 0);
1681        mutex_unlock(hcd->bandwidth_mutex);
1682        usb_hcd_synchronize_unlinks(udev);
1683
1684        usb_remove_ep_devs(&udev->ep0);
1685        usb_unlock_device(udev);
1686
1687        /* Unregister the device.  The device driver is responsible
1688         * for de-configuring the device and invoking the remove-device
1689         * notifier chain (used by usbfs and possibly others).
1690         */
1691        device_del(&udev->dev);
1692
1693        /* Free the device number and delete the parent's children[]
1694         * (or root_hub) pointer.
1695         */
1696        release_devnum(udev);
1697
1698        /* Avoid races with recursively_mark_NOTATTACHED() */
1699        spin_lock_irq(&device_state_lock);
1700        *pdev = NULL;
1701        spin_unlock_irq(&device_state_lock);
1702
1703        hub_free_dev(udev);
1704
1705        put_device(&udev->dev);
1706}
1707
1708#ifdef CONFIG_USB_ANNOUNCE_NEW_DEVICES
1709static void show_string(struct usb_device *udev, char *id, char *string)
1710{
1711        if (!string)
1712                return;
1713        dev_printk(KERN_INFO, &udev->dev, "%s: %s\n", id, string);
1714}
1715
1716static void announce_device(struct usb_device *udev)
1717{
1718        dev_info(&udev->dev, "New USB device found, idVendor=%04x, idProduct=%04x\n",
1719                le16_to_cpu(udev->descriptor.idVendor),
1720                le16_to_cpu(udev->descriptor.idProduct));
1721        dev_info(&udev->dev,
1722                "New USB device strings: Mfr=%d, Product=%d, SerialNumber=%d\n",
1723                udev->descriptor.iManufacturer,
1724                udev->descriptor.iProduct,
1725                udev->descriptor.iSerialNumber);
1726        show_string(udev, "Product", udev->product);
1727        show_string(udev, "Manufacturer", udev->manufacturer);
1728        show_string(udev, "SerialNumber", udev->serial);
1729}
1730#else
1731static inline void announce_device(struct usb_device *udev) { }
1732#endif
1733
1734#ifdef  CONFIG_USB_OTG
1735#include "otg_whitelist.h"
1736#endif
1737
1738/**
1739 * usb_enumerate_device_otg - FIXME (usbcore-internal)
1740 * @udev: newly addressed device (in ADDRESS state)
1741 *
1742 * Finish enumeration for On-The-Go devices
1743 */
1744static int usb_enumerate_device_otg(struct usb_device *udev)
1745{
1746        int err = 0;
1747
1748#ifdef  CONFIG_USB_OTG
1749        /*
1750         * OTG-aware devices on OTG-capable root hubs may be able to use SRP,
1751         * to wake us after we've powered off VBUS; and HNP, switching roles
1752         * "host" to "peripheral".  The OTG descriptor helps figure this out.
1753         */
1754        if (!udev->bus->is_b_host
1755                        && udev->config
1756                        && udev->parent == udev->bus->root_hub) {
1757                struct usb_otg_descriptor       *desc = NULL;
1758                struct usb_bus                  *bus = udev->bus;
1759
1760                /* descriptor may appear anywhere in config */
1761                if (__usb_get_extra_descriptor (udev->rawdescriptors[0],
1762                                        le16_to_cpu(udev->config[0].desc.wTotalLength),
1763                                        USB_DT_OTG, (void **) &desc) == 0) {
1764                        if (desc->bmAttributes & USB_OTG_HNP) {
1765                                unsigned                port1 = udev->portnum;
1766
1767                                dev_info(&udev->dev,
1768                                        "Dual-Role OTG device on %sHNP port\n",
1769                                        (port1 == bus->otg_port)
1770                                                ? "" : "non-");
1771
1772                                /* enable HNP before suspend, it's simpler */
1773                                if (port1 == bus->otg_port)
1774                                        bus->b_hnp_enable = 1;
1775                                err = usb_control_msg(udev,
1776                                        usb_sndctrlpipe(udev, 0),
1777                                        USB_REQ_SET_FEATURE, 0,
1778                                        bus->b_hnp_enable
1779                                                ? USB_DEVICE_B_HNP_ENABLE
1780                                                : USB_DEVICE_A_ALT_HNP_SUPPORT,
1781                                        0, NULL, 0, USB_CTRL_SET_TIMEOUT);
1782                                if (err < 0) {
1783                                        /* OTG MESSAGE: report errors here,
1784                                         * customize to match your product.
1785                                         */
1786                                        dev_info(&udev->dev,
1787                                                "can't set HNP mode: %d\n",
1788                                                err);
1789                                        bus->b_hnp_enable = 0;
1790                                }
1791                        }
1792                }
1793        }
1794
1795        if (!is_targeted(udev)) {
1796
1797                /* Maybe it can talk to us, though we can't talk to it.
1798                 * (Includes HNP test device.)
1799                 */
1800                if (udev->bus->b_hnp_enable || udev->bus->is_b_host) {
1801                        err = usb_port_suspend(udev, PMSG_SUSPEND);
1802                        if (err < 0)
1803                                dev_dbg(&udev->dev, "HNP fail, %d\n", err);
1804                }
1805                err = -ENOTSUPP;
1806                goto fail;
1807        }
1808fail:
1809#endif
1810        return err;
1811}
1812
1813
1814/**
1815 * usb_enumerate_device - Read device configs/intfs/otg (usbcore-internal)
1816 * @udev: newly addressed device (in ADDRESS state)
1817 *
1818 * This is only called by usb_new_device() and usb_authorize_device()
1819 * and FIXME -- all comments that apply to them apply here wrt to
1820 * environment.
1821 *
1822 * If the device is WUSB and not authorized, we don't attempt to read
1823 * the string descriptors, as they will be errored out by the device
1824 * until it has been authorized.
1825 */
1826static int usb_enumerate_device(struct usb_device *udev)
1827{
1828        int err;
1829
1830        if (udev->config == NULL) {
1831                err = usb_get_configuration(udev);
1832                if (err < 0) {
1833                        dev_err(&udev->dev, "can't read configurations, error %d\n",
1834                                err);
1835                        goto fail;
1836                }
1837        }
1838        if (udev->wusb == 1 && udev->authorized == 0) {
1839                udev->product = kstrdup("n/a (unauthorized)", GFP_KERNEL);
1840                udev->manufacturer = kstrdup("n/a (unauthorized)", GFP_KERNEL);
1841                udev->serial = kstrdup("n/a (unauthorized)", GFP_KERNEL);
1842        }
1843        else {
1844                /* read the standard strings and cache them if present */
1845                udev->product = usb_cache_string(udev, udev->descriptor.iProduct);
1846                udev->manufacturer = usb_cache_string(udev,
1847                                                      udev->descriptor.iManufacturer);
1848                udev->serial = usb_cache_string(udev, udev->descriptor.iSerialNumber);
1849        }
1850        err = usb_enumerate_device_otg(udev);
1851fail:
1852        return err;
1853}
1854
1855
1856/**
1857 * usb_new_device - perform initial device setup (usbcore-internal)
1858 * @udev: newly addressed device (in ADDRESS state)
1859 *
1860 * This is called with devices which have been detected but not fully
1861 * enumerated.  The device descriptor is available, but not descriptors
1862 * for any device configuration.  The caller must have locked either
1863 * the parent hub (if udev is a normal device) or else the
1864 * usb_bus_list_lock (if udev is a root hub).  The parent's pointer to
1865 * udev has already been installed, but udev is not yet visible through
1866 * sysfs or other filesystem code.
1867 *
1868 * It will return if the device is configured properly or not.  Zero if
1869 * the interface was registered with the driver core; else a negative
1870 * errno value.
1871 *
1872 * This call is synchronous, and may not be used in an interrupt context.
1873 *
1874 * Only the hub driver or root-hub registrar should ever call this.
1875 */
1876int usb_new_device(struct usb_device *udev)
1877{
1878        int err;
1879
1880        if (udev->parent) {
1881                /* Initialize non-root-hub device wakeup to disabled;
1882                 * device (un)configuration controls wakeup capable
1883                 * sysfs power/wakeup controls wakeup enabled/disabled
1884                 */
1885                device_init_wakeup(&udev->dev, 0);
1886        }
1887
1888        /* Tell the runtime-PM framework the device is active */
1889        pm_runtime_set_active(&udev->dev);
1890        pm_runtime_get_noresume(&udev->dev);
1891        pm_runtime_use_autosuspend(&udev->dev);
1892        pm_runtime_enable(&udev->dev);
1893
1894        /* By default, forbid autosuspend for all devices.  It will be
1895         * allowed for hubs during binding.
1896         */
1897        usb_disable_autosuspend(udev);
1898
1899        err = usb_enumerate_device(udev);       /* Read descriptors */
1900        if (err < 0)
1901                goto fail;
1902        dev_dbg(&udev->dev, "udev %d, busnum %d, minor = %d\n",
1903                        udev->devnum, udev->bus->busnum,
1904                        (((udev->bus->busnum-1) * 128) + (udev->devnum-1)));
1905        /* export the usbdev device-node for libusb */
1906        udev->dev.devt = MKDEV(USB_DEVICE_MAJOR,
1907                        (((udev->bus->busnum-1) * 128) + (udev->devnum-1)));
1908
1909        /* Tell the world! */
1910        announce_device(udev);
1911
1912        device_enable_async_suspend(&udev->dev);
1913        /* Register the device.  The device driver is responsible
1914         * for configuring the device and invoking the add-device
1915         * notifier chain (used by usbfs and possibly others).
1916         */
1917        err = device_add(&udev->dev);
1918        if (err) {
1919                dev_err(&udev->dev, "can't device_add, error %d\n", err);
1920                goto fail;
1921        }
1922
1923        (void) usb_create_ep_devs(&udev->dev, &udev->ep0, udev);
1924        usb_mark_last_busy(udev);
1925        pm_runtime_put_sync_autosuspend(&udev->dev);
1926        return err;
1927
1928fail:
1929        usb_set_device_state(udev, USB_STATE_NOTATTACHED);
1930        pm_runtime_disable(&udev->dev);
1931        pm_runtime_set_suspended(&udev->dev);
1932        return err;
1933}
1934
1935
1936/**
1937 * usb_deauthorize_device - deauthorize a device (usbcore-internal)
1938 * @usb_dev: USB device
1939 *
1940 * Move the USB device to a very basic state where interfaces are disabled
1941 * and the device is in fact unconfigured and unusable.
1942 *
1943 * We share a lock (that we have) with device_del(), so we need to
1944 * defer its call.
1945 */
1946int usb_deauthorize_device(struct usb_device *usb_dev)
1947{
1948        usb_lock_device(usb_dev);
1949        if (usb_dev->authorized == 0)
1950                goto out_unauthorized;
1951
1952        usb_dev->authorized = 0;
1953        usb_set_configuration(usb_dev, -1);
1954
1955        kfree(usb_dev->product);
1956        usb_dev->product = kstrdup("n/a (unauthorized)", GFP_KERNEL);
1957        kfree(usb_dev->manufacturer);
1958        usb_dev->manufacturer = kstrdup("n/a (unauthorized)", GFP_KERNEL);
1959        kfree(usb_dev->serial);
1960        usb_dev->serial = kstrdup("n/a (unauthorized)", GFP_KERNEL);
1961
1962        usb_destroy_configuration(usb_dev);
1963        usb_dev->descriptor.bNumConfigurations = 0;
1964
1965out_unauthorized:
1966        usb_unlock_device(usb_dev);
1967        return 0;
1968}
1969
1970
1971int usb_authorize_device(struct usb_device *usb_dev)
1972{
1973        int result = 0, c;
1974
1975        usb_lock_device(usb_dev);
1976        if (usb_dev->authorized == 1)
1977                goto out_authorized;
1978
1979        result = usb_autoresume_device(usb_dev);
1980        if (result < 0) {
1981                dev_err(&usb_dev->dev,
1982                        "can't autoresume for authorization: %d\n", result);
1983                goto error_autoresume;
1984        }
1985        result = usb_get_device_descriptor(usb_dev, sizeof(usb_dev->descriptor));
1986        if (result < 0) {
1987                dev_err(&usb_dev->dev, "can't re-read device descriptor for "
1988                        "authorization: %d\n", result);
1989                goto error_device_descriptor;
1990        }
1991
1992        kfree(usb_dev->product);
1993        usb_dev->product = NULL;
1994        kfree(usb_dev->manufacturer);
1995        usb_dev->manufacturer = NULL;
1996        kfree(usb_dev->serial);
1997        usb_dev->serial = NULL;
1998
1999        usb_dev->authorized = 1;
2000        result = usb_enumerate_device(usb_dev);
2001        if (result < 0)
2002                goto error_enumerate;
2003        /* Choose and set the configuration.  This registers the interfaces
2004         * with the driver core and lets interface drivers bind to them.
2005         */
2006        c = usb_choose_configuration(usb_dev);
2007        if (c >= 0) {
2008                result = usb_set_configuration(usb_dev, c);
2009                if (result) {
2010                        dev_err(&usb_dev->dev,
2011                                "can't set config #%d, error %d\n", c, result);
2012                        /* This need not be fatal.  The user can try to
2013                         * set other configurations. */
2014                }
2015        }
2016        dev_info(&usb_dev->dev, "authorized to connect\n");
2017
2018error_enumerate:
2019error_device_descriptor:
2020        usb_autosuspend_device(usb_dev);
2021error_autoresume:
2022out_authorized:
2023        usb_unlock_device(usb_dev);     // complements locktree
2024        return result;
2025}
2026
2027
2028/* Returns 1 if @hub is a WUSB root hub, 0 otherwise */
2029static unsigned hub_is_wusb(struct usb_hub *hub)
2030{
2031        struct usb_hcd *hcd;
2032        if (hub->hdev->parent != NULL)  /* not a root hub? */
2033                return 0;
2034        hcd = container_of(hub->hdev->bus, struct usb_hcd, self);
2035        return hcd->wireless;
2036}
2037
2038
2039#define PORT_RESET_TRIES        5
2040#define SET_ADDRESS_TRIES       2
2041#define GET_DESCRIPTOR_TRIES    2
2042#define SET_CONFIG_TRIES        (2 * (use_both_schemes + 1))
2043#define USE_NEW_SCHEME(i)       ((i) / 2 == old_scheme_first)
2044
2045#define HUB_ROOT_RESET_TIME     50      /* times are in msec */
2046#define HUB_SHORT_RESET_TIME    10
2047#define HUB_BH_RESET_TIME       50
2048#define HUB_LONG_RESET_TIME     200
2049#define HUB_RESET_TIMEOUT       500
2050
2051static int hub_port_reset(struct usb_hub *hub, int port1,
2052                        struct usb_device *udev, unsigned int delay, bool warm);
2053
2054/* Is a USB 3.0 port in the Inactive state? */
2055static bool hub_port_inactive(struct usb_hub *hub, u16 portstatus)
2056{
2057        return hub_is_superspeed(hub->hdev) &&
2058                (portstatus & USB_PORT_STAT_LINK_STATE) ==
2059                USB_SS_PORT_LS_SS_INACTIVE;
2060}
2061
2062static int hub_port_wait_reset(struct usb_hub *hub, int port1,
2063                        struct usb_device *udev, unsigned int delay, bool warm)
2064{
2065        int delay_time, ret;
2066        u16 portstatus;
2067        u16 portchange;
2068
2069        for (delay_time = 0;
2070                        delay_time < HUB_RESET_TIMEOUT;
2071                        delay_time += delay) {
2072                /* wait to give the device a chance to reset */
2073                msleep(delay);
2074
2075                /* read and decode port status */
2076                ret = hub_port_status(hub, port1, &portstatus, &portchange);
2077                if (ret < 0)
2078                        return ret;
2079
2080                /*
2081                 * Some buggy devices require a warm reset to be issued even
2082                 * when the port appears not to be connected.
2083                 */
2084                if (!warm) {
2085                        /*
2086                         * Some buggy devices can cause an NEC host controller
2087                         * to transition to the "Error" state after a hot port
2088                         * reset.  This will show up as the port state in
2089                         * "Inactive", and the port may also report a
2090                         * disconnect.  Forcing a warm port reset seems to make
2091                         * the device work.
2092                         *
2093                         * See https://bugzilla.kernel.org/show_bug.cgi?id=41752
2094                         */
2095                        if (hub_port_inactive(hub, portstatus)) {
2096                                int ret;
2097
2098                                if ((portchange & USB_PORT_STAT_C_CONNECTION))
2099                                        clear_port_feature(hub->hdev, port1,
2100                                                        USB_PORT_FEAT_C_CONNECTION);
2101                                if (portchange & USB_PORT_STAT_C_LINK_STATE)
2102                                        clear_port_feature(hub->hdev, port1,
2103                                                        USB_PORT_FEAT_C_PORT_LINK_STATE);
2104                                if (portchange & USB_PORT_STAT_C_RESET)
2105                                        clear_port_feature(hub->hdev, port1,
2106                                                        USB_PORT_FEAT_C_RESET);
2107                                dev_dbg(hub->intfdev, "hot reset failed, warm reset port %d\n",
2108                                                port1);
2109                                ret = hub_port_reset(hub, port1,
2110                                                udev, HUB_BH_RESET_TIME,
2111                                                true);
2112                                if ((portchange & USB_PORT_STAT_C_CONNECTION))
2113                                        clear_port_feature(hub->hdev, port1,
2114                                                        USB_PORT_FEAT_C_CONNECTION);
2115                                return ret;
2116                        }
2117                        /* Device went away? */
2118                        if (!(portstatus & USB_PORT_STAT_CONNECTION))
2119                                return -ENOTCONN;
2120
2121                        /* bomb out completely if the connection bounced */
2122                        if ((portchange & USB_PORT_STAT_C_CONNECTION))
2123                                return -ENOTCONN;
2124
2125                        /* if we`ve finished resetting, then break out of
2126                         * the loop
2127                         */
2128                        if (!(portstatus & USB_PORT_STAT_RESET) &&
2129                            (portstatus & USB_PORT_STAT_ENABLE)) {
2130                                if (hub_is_wusb(hub))
2131                                        udev->speed = USB_SPEED_WIRELESS;
2132                                else if (hub_is_superspeed(hub->hdev))
2133                                        udev->speed = USB_SPEED_SUPER;
2134                                else if (portstatus & USB_PORT_STAT_HIGH_SPEED)
2135                                        udev->speed = USB_SPEED_HIGH;
2136                                else if (portstatus & USB_PORT_STAT_LOW_SPEED)
2137                                        udev->speed = USB_SPEED_LOW;
2138                                else
2139                                        udev->speed = USB_SPEED_FULL;
2140                                return 0;
2141                        }
2142                } else {
2143                        if (portchange & USB_PORT_STAT_C_BH_RESET)
2144                                return 0;
2145                }
2146
2147                /* switch to the long delay after two short delay failures */
2148                if (delay_time >= 2 * HUB_SHORT_RESET_TIME)
2149                        delay = HUB_LONG_RESET_TIME;
2150
2151                dev_dbg (hub->intfdev,
2152                        "port %d not %sreset yet, waiting %dms\n",
2153                        port1, warm ? "warm " : "", delay);
2154        }
2155
2156        return -EBUSY;
2157}
2158
2159static void hub_port_finish_reset(struct usb_hub *hub, int port1,
2160                        struct usb_device *udev, int *status, bool warm)
2161{
2162        switch (*status) {
2163        case 0:
2164                if (!warm) {
2165                        struct usb_hcd *hcd;
2166                        /* TRSTRCY = 10 ms; plus some extra */
2167                        msleep(10 + 40);
2168                        update_devnum(udev, 0);
2169                        hcd = bus_to_hcd(udev->bus);
2170                        if (hcd->driver->reset_device) {
2171                                *status = hcd->driver->reset_device(hcd, udev);
2172                                if (*status < 0) {
2173                                        dev_err(&udev->dev, "Cannot reset "
2174                                                        "HCD device state\n");
2175                                        break;
2176                                }
2177                        }
2178                }
2179                /* FALL THROUGH */
2180        case -ENOTCONN:
2181        case -ENODEV:
2182                clear_port_feature(hub->hdev,
2183                                port1, USB_PORT_FEAT_C_RESET);
2184                /* FIXME need disconnect() for NOTATTACHED device */
2185                if (warm) {
2186                        clear_port_feature(hub->hdev, port1,
2187                                        USB_PORT_FEAT_C_BH_PORT_RESET);
2188                        clear_port_feature(hub->hdev, port1,
2189                                        USB_PORT_FEAT_C_PORT_LINK_STATE);
2190                } else {
2191                        usb_set_device_state(udev, *status
2192                                        ? USB_STATE_NOTATTACHED
2193                                        : USB_STATE_DEFAULT);
2194                }
2195                break;
2196        }
2197}
2198
2199/* Handle port reset and port warm(BH) reset (for USB3 protocol ports) */
2200static int hub_port_reset(struct usb_hub *hub, int port1,
2201                        struct usb_device *udev, unsigned int delay, bool warm)
2202{
2203        int i, status;
2204
2205        if (!warm) {
2206                /* Block EHCI CF initialization during the port reset.
2207                 * Some companion controllers don't like it when they mix.
2208                 */
2209                down_read(&ehci_cf_port_reset_rwsem);
2210        } else {
2211                if (!hub_is_superspeed(hub->hdev)) {
2212                        dev_err(hub->intfdev, "only USB3 hub support "
2213                                                "warm reset\n");
2214                        return -EINVAL;
2215                }
2216        }
2217
2218        /* Reset the port */
2219        for (i = 0; i < PORT_RESET_TRIES; i++) {
2220                status = set_port_feature(hub->hdev, port1, (warm ?
2221                                        USB_PORT_FEAT_BH_PORT_RESET :
2222                                        USB_PORT_FEAT_RESET));
2223                if (status) {
2224                        dev_err(hub->intfdev,
2225                                        "cannot %sreset port %d (err = %d)\n",
2226                                        warm ? "warm " : "", port1, status);
2227                } else {
2228                        status = hub_port_wait_reset(hub, port1, udev, delay,
2229                                                                warm);
2230                        if (status && status != -ENOTCONN)
2231                                dev_dbg(hub->intfdev,
2232                                                "port_wait_reset: err = %d\n",
2233                                                status);
2234                }
2235
2236                /* return on disconnect or reset */
2237                if (status == 0 || status == -ENOTCONN || status == -ENODEV) {
2238                        hub_port_finish_reset(hub, port1, udev, &status, warm);
2239                        goto done;
2240                }
2241
2242                dev_dbg (hub->intfdev,
2243                        "port %d not enabled, trying %sreset again...\n",
2244                        port1, warm ? "warm " : "");
2245                delay = HUB_LONG_RESET_TIME;
2246        }
2247
2248        dev_err (hub->intfdev,
2249                "Cannot enable port %i.  Maybe the USB cable is bad?\n",
2250                port1);
2251
2252done:
2253        if (!warm)
2254                up_read(&ehci_cf_port_reset_rwsem);
2255
2256        return status;
2257}
2258
2259/* Check if a port is power on */
2260static int port_is_power_on(struct usb_hub *hub, unsigned portstatus)
2261{
2262        int ret = 0;
2263
2264        if (hub_is_superspeed(hub->hdev)) {
2265                if (portstatus & USB_SS_PORT_STAT_POWER)
2266                        ret = 1;
2267        } else {
2268                if (portstatus & USB_PORT_STAT_POWER)
2269                        ret = 1;
2270        }
2271
2272        return ret;
2273}
2274
2275#ifdef  CONFIG_PM
2276
2277/* Check if a port is suspended(USB2.0 port) or in U3 state(USB3.0 port) */
2278static int port_is_suspended(struct usb_hub *hub, unsigned portstatus)
2279{
2280        int ret = 0;
2281
2282        if (hub_is_superspeed(hub->hdev)) {
2283                if ((portstatus & USB_PORT_STAT_LINK_STATE)
2284                                == USB_SS_PORT_LS_U3)
2285                        ret = 1;
2286        } else {
2287                if (portstatus & USB_PORT_STAT_SUSPEND)
2288                        ret = 1;
2289        }
2290
2291        return ret;
2292}
2293
2294/* Determine whether the device on a port is ready for a normal resume,
2295 * is ready for a reset-resume, or should be disconnected.
2296 */
2297static int check_port_resume_type(struct usb_device *udev,
2298                struct usb_hub *hub, int port1,
2299                int status, unsigned portchange, unsigned portstatus)
2300{
2301        /* Is the device still present? */
2302        if (status || port_is_suspended(hub, portstatus) ||
2303                        !port_is_power_on(hub, portstatus) ||
2304                        !(portstatus & USB_PORT_STAT_CONNECTION)) {
2305                if (status >= 0)
2306                        status = -ENODEV;
2307        }
2308
2309        /* Can't do a normal resume if the port isn't enabled,
2310         * so try a reset-resume instead.
2311         */
2312        else if (!(portstatus & USB_PORT_STAT_ENABLE) && !udev->reset_resume) {
2313                if (udev->persist_enabled)
2314                        udev->reset_resume = 1;
2315                else
2316                        status = -ENODEV;
2317        }
2318
2319        if (status) {
2320                dev_dbg(hub->intfdev,
2321                                "port %d status %04x.%04x after resume, %d\n",
2322                                port1, portchange, portstatus, status);
2323        } else if (udev->reset_resume) {
2324
2325                /* Late port handoff can set status-change bits */
2326                if (portchange & USB_PORT_STAT_C_CONNECTION)
2327                        clear_port_feature(hub->hdev, port1,
2328                                        USB_PORT_FEAT_C_CONNECTION);
2329                if (portchange & USB_PORT_STAT_C_ENABLE)
2330                        clear_port_feature(hub->hdev, port1,
2331                                        USB_PORT_FEAT_C_ENABLE);
2332        }
2333
2334        return status;
2335}
2336
2337#ifdef  CONFIG_USB_SUSPEND
2338
2339/*
2340 * usb_port_suspend - suspend a usb device's upstream port
2341 * @udev: device that's no longer in active use, not a root hub
2342 * Context: must be able to sleep; device not locked; pm locks held
2343 *
2344 * Suspends a USB device that isn't in active use, conserving power.
2345 * Devices may wake out of a suspend, if anything important happens,
2346 * using the remote wakeup mechanism.  They may also be taken out of
2347 * suspend by the host, using usb_port_resume().  It's also routine
2348 * to disconnect devices while they are suspended.
2349 *
2350 * This only affects the USB hardware for a device; its interfaces
2351 * (and, for hubs, child devices) must already have been suspended.
2352 *
2353 * Selective port suspend reduces power; most suspended devices draw
2354 * less than 500 uA.  It's also used in OTG, along with remote wakeup.
2355 * All devices below the suspended port are also suspended.
2356 *
2357 * Devices leave suspend state when the host wakes them up.  Some devices
2358 * also support "remote wakeup", where the device can activate the USB
2359 * tree above them to deliver data, such as a keypress or packet.  In
2360 * some cases, this wakes the USB host.
2361 *
2362 * Suspending OTG devices may trigger HNP, if that's been enabled
2363 * between a pair of dual-role devices.  That will change roles, such
2364 * as from A-Host to A-Peripheral or from B-Host back to B-Peripheral.
2365 *
2366 * Devices on USB hub ports have only one "suspend" state, corresponding
2367 * to ACPI D2, "may cause the device to lose some context".
2368 * State transitions include:
2369 *
2370 *   - suspend, resume ... when the VBUS power link stays live
2371 *   - suspend, disconnect ... VBUS lost
2372 *
2373 * Once VBUS drop breaks the circuit, the port it's using has to go through
2374 * normal re-enumeration procedures, starting with enabling VBUS power.
2375 * Other than re-initializing the hub (plug/unplug, except for root hubs),
2376 * Linux (2.6) currently has NO mechanisms to initiate that:  no khubd
2377 * timer, no SRP, no requests through sysfs.
2378 *
2379 * If CONFIG_USB_SUSPEND isn't enabled, devices only really suspend when
2380 * the root hub for their bus goes into global suspend ... so we don't
2381 * (falsely) update the device power state to say it suspended.
2382 *
2383 * Returns 0 on success, else negative errno.
2384 */
2385int usb_port_suspend(struct usb_device *udev, pm_message_t msg)
2386{
2387        struct usb_hub  *hub = hdev_to_hub(udev->parent);
2388        int             port1 = udev->portnum;
2389        int             status;
2390
2391        /* enable remote wakeup when appropriate; this lets the device
2392         * wake up the upstream hub (including maybe the root hub).
2393         *
2394         * NOTE:  OTG devices may issue remote wakeup (or SRP) even when
2395         * we don't explicitly enable it here.
2396         */
2397        if (udev->do_remote_wakeup) {
2398                status = usb_control_msg(udev, usb_sndctrlpipe(udev, 0),
2399                                USB_REQ_SET_FEATURE, USB_RECIP_DEVICE,
2400                                USB_DEVICE_REMOTE_WAKEUP, 0,
2401                                NULL, 0,
2402                                USB_CTRL_SET_TIMEOUT);
2403                if (status) {
2404                        dev_dbg(&udev->dev, "won't remote wakeup, status %d\n",
2405                                        status);
2406                        /* bail if autosuspend is requested */
2407                        if (PMSG_IS_AUTO(msg))
2408                                return status;
2409                }
2410        }
2411
2412        /* disable USB2 hardware LPM */
2413        if (udev->usb2_hw_lpm_enabled == 1)
2414                usb_set_usb2_hardware_lpm(udev, 0);
2415
2416        /* see 7.1.7.6 */
2417        if (hub_is_superspeed(hub->hdev))
2418                status = set_port_feature(hub->hdev,
2419                                port1 | (USB_SS_PORT_LS_U3 << 3),
2420                                USB_PORT_FEAT_LINK_STATE);
2421        else
2422                status = set_port_feature(hub->hdev, port1,
2423                                                USB_PORT_FEAT_SUSPEND);
2424        if (status) {
2425                dev_dbg(hub->intfdev, "can't suspend port %d, status %d\n",
2426                                port1, status);
2427                /* paranoia:  "should not happen" */
2428                if (udev->do_remote_wakeup)
2429                        (void) usb_control_msg(udev, usb_sndctrlpipe(udev, 0),
2430                                USB_REQ_CLEAR_FEATURE, USB_RECIP_DEVICE,
2431                                USB_DEVICE_REMOTE_WAKEUP, 0,
2432                                NULL, 0,
2433                                USB_CTRL_SET_TIMEOUT);
2434
2435                /* System sleep transitions should never fail */
2436                if (!PMSG_IS_AUTO(msg))
2437                        status = 0;
2438        } else {
2439                /* device has up to 10 msec to fully suspend */
2440                dev_dbg(&udev->dev, "usb %ssuspend, wakeup %d\n",
2441                                (PMSG_IS_AUTO(msg) ? "auto-" : ""),
2442                                udev->do_remote_wakeup);
2443                usb_set_device_state(udev, USB_STATE_SUSPENDED);
2444                msleep(10);
2445        }
2446        usb_mark_last_busy(hub->hdev);
2447        return status;
2448}
2449
2450/*
2451 * If the USB "suspend" state is in use (rather than "global suspend"),
2452 * many devices will be individually taken out of suspend state using
2453 * special "resume" signaling.  This routine kicks in shortly after
2454 * hardware resume signaling is finished, either because of selective
2455 * resume (by host) or remote wakeup (by device) ... now see what changed
2456 * in the tree that's rooted at this device.
2457 *
2458 * If @udev->reset_resume is set then the device is reset before the
2459 * status check is done.
2460 */
2461static int finish_port_resume(struct usb_device *udev)
2462{
2463        int     status = 0;
2464        u16     devstatus;
2465
2466        /* caller owns the udev device lock */
2467        dev_dbg(&udev->dev, "%s\n",
2468                udev->reset_resume ? "finish reset-resume" : "finish resume");
2469
2470        /* usb ch9 identifies four variants of SUSPENDED, based on what
2471         * state the device resumes to.  Linux currently won't see the
2472         * first two on the host side; they'd be inside hub_port_init()
2473         * during many timeouts, but khubd can't suspend until later.
2474         */
2475        usb_set_device_state(udev, udev->actconfig
2476                        ? USB_STATE_CONFIGURED
2477                        : USB_STATE_ADDRESS);
2478
2479        /* 10.5.4.5 says not to reset a suspended port if the attached
2480         * device is enabled for remote wakeup.  Hence the reset
2481         * operation is carried out here, after the port has been
2482         * resumed.
2483         */
2484        if (udev->reset_resume)
2485 retry_reset_resume:
2486                status = usb_reset_and_verify_device(udev);
2487
2488        /* 10.5.4.5 says be sure devices in the tree are still there.
2489         * For now let's assume the device didn't go crazy on resume,
2490         * and device drivers will know about any resume quirks.
2491         */
2492        if (status == 0) {
2493                devstatus = 0;
2494                status = usb_get_status(udev, USB_RECIP_DEVICE, 0, &devstatus);
2495                if (status >= 0)
2496                        status = (status > 0 ? 0 : -ENODEV);
2497
2498                /* If a normal resume failed, try doing a reset-resume */
2499                if (status && !udev->reset_resume && udev->persist_enabled) {
2500                        dev_dbg(&udev->dev, "retry with reset-resume\n");
2501                        udev->reset_resume = 1;
2502                        goto retry_reset_resume;
2503                }
2504        }
2505
2506        if (status) {
2507                dev_dbg(&udev->dev, "gone after usb resume? status %d\n",
2508                                status);
2509        } else if (udev->actconfig) {
2510                le16_to_cpus(&devstatus);
2511                if (devstatus & (1 << USB_DEVICE_REMOTE_WAKEUP)) {
2512                        status = usb_control_msg(udev,
2513                                        usb_sndctrlpipe(udev, 0),
2514                                        USB_REQ_CLEAR_FEATURE,
2515                                                USB_RECIP_DEVICE,
2516                                        USB_DEVICE_REMOTE_WAKEUP, 0,
2517                                        NULL, 0,
2518                                        USB_CTRL_SET_TIMEOUT);
2519                        if (status)
2520                                dev_dbg(&udev->dev,
2521                                        "disable remote wakeup, status %d\n",
2522                                        status);
2523                }
2524                status = 0;
2525        }
2526        return status;
2527}
2528
2529/*
2530 * usb_port_resume - re-activate a suspended usb device's upstream port
2531 * @udev: device to re-activate, not a root hub
2532 * Context: must be able to sleep; device not locked; pm locks held
2533 *
2534 * This will re-activate the suspended device, increasing power usage
2535 * while letting drivers communicate again with its endpoints.
2536 * USB resume explicitly guarantees that the power session between
2537 * the host and the device is the same as it was when the device
2538 * suspended.
2539 *
2540 * If @udev->reset_resume is set then this routine won't check that the
2541 * port is still enabled.  Furthermore, finish_port_resume() above will
2542 * reset @udev.  The end result is that a broken power session can be
2543 * recovered and @udev will appear to persist across a loss of VBUS power.
2544 *
2545 * For example, if a host controller doesn't maintain VBUS suspend current
2546 * during a system sleep or is reset when the system wakes up, all the USB
2547 * power sessions below it will be broken.  This is especially troublesome
2548 * for mass-storage devices containing mounted filesystems, since the
2549 * device will appear to have disconnected and all the memory mappings
2550 * to it will be lost.  Using the USB_PERSIST facility, the device can be
2551 * made to appear as if it had not disconnected.
2552 *
2553 * This facility can be dangerous.  Although usb_reset_and_verify_device() makes
2554 * every effort to insure that the same device is present after the
2555 * reset as before, it cannot provide a 100% guarantee.  Furthermore it's
2556 * quite possible for a device to remain unaltered but its media to be
2557 * changed.  If the user replaces a flash memory card while the system is
2558 * asleep, he will have only himself to blame when the filesystem on the
2559 * new card is corrupted and the system crashes.
2560 *
2561 * Returns 0 on success, else negative errno.
2562 */
2563int usb_port_resume(struct usb_device *udev, pm_message_t msg)
2564{
2565        struct usb_hub  *hub = hdev_to_hub(udev->parent);
2566        int             port1 = udev->portnum;
2567        int             status;
2568        u16             portchange, portstatus;
2569
2570        /* Skip the initial Clear-Suspend step for a remote wakeup */
2571        status = hub_port_status(hub, port1, &portstatus, &portchange);
2572        if (status == 0 && !port_is_suspended(hub, portstatus))
2573                goto SuspendCleared;
2574
2575        // dev_dbg(hub->intfdev, "resume port %d\n", port1);
2576
2577        set_bit(port1, hub->busy_bits);
2578
2579        /* see 7.1.7.7; affects power usage, but not budgeting */
2580        if (hub_is_superspeed(hub->hdev))
2581                status = set_port_feature(hub->hdev,
2582                                port1 | (USB_SS_PORT_LS_U0 << 3),
2583                                USB_PORT_FEAT_LINK_STATE);
2584        else
2585                status = clear_port_feature(hub->hdev,
2586                                port1, USB_PORT_FEAT_SUSPEND);
2587        if (status) {
2588                dev_dbg(hub->intfdev, "can't resume port %d, status %d\n",
2589                                port1, status);
2590        } else {
2591                /* drive resume for at least 20 msec */
2592                dev_dbg(&udev->dev, "usb %sresume\n",
2593                                (PMSG_IS_AUTO(msg) ? "auto-" : ""));
2594                msleep(25);
2595
2596                /* Virtual root hubs can trigger on GET_PORT_STATUS to
2597                 * stop resume signaling.  Then finish the resume
2598                 * sequence.
2599                 */
2600                status = hub_port_status(hub, port1, &portstatus, &portchange);
2601
2602                /* TRSMRCY = 10 msec */
2603                msleep(10);
2604        }
2605
2606 SuspendCleared:
2607        if (status == 0) {
2608                if (hub_is_superspeed(hub->hdev)) {
2609                        if (portchange & USB_PORT_STAT_C_LINK_STATE)
2610                                clear_port_feature(hub->hdev, port1,
2611                                        USB_PORT_FEAT_C_PORT_LINK_STATE);
2612                } else {
2613                        if (portchange & USB_PORT_STAT_C_SUSPEND)
2614                                clear_port_feature(hub->hdev, port1,
2615                                                USB_PORT_FEAT_C_SUSPEND);
2616                }
2617        }
2618
2619        clear_bit(port1, hub->busy_bits);
2620
2621        status = check_port_resume_type(udev,
2622                        hub, port1, status, portchange, portstatus);
2623        if (status == 0)
2624                status = finish_port_resume(udev);
2625        if (status < 0) {
2626                dev_dbg(&udev->dev, "can't resume, status %d\n", status);
2627                hub_port_logical_disconnect(hub, port1);
2628        } else  {
2629                /* Try to enable USB2 hardware LPM */
2630                if (udev->usb2_hw_lpm_capable == 1)
2631                        usb_set_usb2_hardware_lpm(udev, 1);
2632        }
2633
2634        return status;
2635}
2636
2637/* caller has locked udev */
2638int usb_remote_wakeup(struct usb_device *udev)
2639{
2640        int     status = 0;
2641
2642        if (udev->state == USB_STATE_SUSPENDED) {
2643                dev_dbg(&udev->dev, "usb %sresume\n", "wakeup-");
2644                status = usb_autoresume_device(udev);
2645                if (status == 0) {
2646                        /* Let the drivers do their thing, then... */
2647                        usb_autosuspend_device(udev);
2648                }
2649        }
2650        return status;
2651}
2652
2653#else   /* CONFIG_USB_SUSPEND */
2654
2655/* When CONFIG_USB_SUSPEND isn't set, we never suspend or resume any ports. */
2656
2657int usb_port_suspend(struct usb_device *udev, pm_message_t msg)
2658{
2659        return 0;
2660}
2661
2662/* However we may need to do a reset-resume */
2663
2664int usb_port_resume(struct usb_device *udev, pm_message_t msg)
2665{
2666        struct usb_hub  *hub = hdev_to_hub(udev->parent);
2667        int             port1 = udev->portnum;
2668        int             status;
2669        u16             portchange, portstatus;
2670
2671        status = hub_port_status(hub, port1, &portstatus, &portchange);
2672        status = check_port_resume_type(udev,
2673                        hub, port1, status, portchange, portstatus);
2674
2675        if (status) {
2676                dev_dbg(&udev->dev, "can't resume, status %d\n", status);
2677                hub_port_logical_disconnect(hub, port1);
2678        } else if (udev->reset_resume) {
2679                dev_dbg(&udev->dev, "reset-resume\n");
2680                status = usb_reset_and_verify_device(udev);
2681        }
2682        return status;
2683}
2684
2685#endif
2686
2687static int hub_suspend(struct usb_interface *intf, pm_message_t msg)
2688{
2689        struct usb_hub          *hub = usb_get_intfdata (intf);
2690        struct usb_device       *hdev = hub->hdev;
2691        unsigned                port1;
2692
2693        /* Warn if children aren't already suspended */
2694        for (port1 = 1; port1 <= hdev->maxchild; port1++) {
2695                struct usb_device       *udev;
2696
2697                udev = hdev->children [port1-1];
2698                if (udev && udev->can_submit) {
2699                        dev_warn(&intf->dev, "port %d nyet suspended\n", port1);
2700                        if (PMSG_IS_AUTO(msg))
2701                                return -EBUSY;
2702                }
2703        }
2704
2705        dev_dbg(&intf->dev, "%s\n", __func__);
2706
2707        /* stop khubd and related activity */
2708        hub_quiesce(hub, HUB_SUSPEND);
2709        return 0;
2710}
2711
2712static int hub_resume(struct usb_interface *intf)
2713{
2714        struct usb_hub *hub = usb_get_intfdata(intf);
2715
2716        dev_dbg(&intf->dev, "%s\n", __func__);
2717        hub_activate(hub, HUB_RESUME);
2718        return 0;
2719}
2720
2721static int hub_reset_resume(struct usb_interface *intf)
2722{
2723        struct usb_hub *hub = usb_get_intfdata(intf);
2724
2725        dev_dbg(&intf->dev, "%s\n", __func__);
2726        hub_activate(hub, HUB_RESET_RESUME);
2727        return 0;
2728}
2729
2730/**
2731 * usb_root_hub_lost_power - called by HCD if the root hub lost Vbus power
2732 * @rhdev: struct usb_device for the root hub
2733 *
2734 * The USB host controller driver calls this function when its root hub
2735 * is resumed and Vbus power has been interrupted or the controller
2736 * has been reset.  The routine marks @rhdev as having lost power.
2737 * When the hub driver is resumed it will take notice and carry out
2738 * power-session recovery for all the "USB-PERSIST"-enabled child devices;
2739 * the others will be disconnected.
2740 */
2741void usb_root_hub_lost_power(struct usb_device *rhdev)
2742{
2743        dev_warn(&rhdev->dev, "root hub lost power or was reset\n");
2744        rhdev->reset_resume = 1;
2745}
2746EXPORT_SYMBOL_GPL(usb_root_hub_lost_power);
2747
2748#else   /* CONFIG_PM */
2749
2750#define hub_suspend             NULL
2751#define hub_resume              NULL
2752#define hub_reset_resume        NULL
2753#endif
2754
2755
2756/* USB 2.0 spec, 7.1.7.3 / fig 7-29:
2757 *
2758 * Between connect detection and reset signaling there must be a delay
2759 * of 100ms at least for debounce and power-settling.  The corresponding
2760 * timer shall restart whenever the downstream port detects a disconnect.
2761 *
2762 * Apparently there are some bluetooth and irda-dongles and a number of
2763 * low-speed devices for which this debounce period may last over a second.
2764 * Not covered by the spec - but easy to deal with.
2765 *
2766 * This implementation uses a 1500ms total debounce timeout; if the
2767 * connection isn't stable by then it returns -ETIMEDOUT.  It checks
2768 * every 25ms for transient disconnects.  When the port status has been
2769 * unchanged for 100ms it returns the port status.
2770 */
2771static int hub_port_debounce(struct usb_hub *hub, int port1)
2772{
2773        int ret;
2774        int total_time, stable_time = 0;
2775        u16 portchange, portstatus;
2776        unsigned connection = 0xffff;
2777
2778        for (total_time = 0; ; total_time += HUB_DEBOUNCE_STEP) {
2779                ret = hub_port_status(hub, port1, &portstatus, &portchange);
2780                if (ret < 0)
2781                        return ret;
2782
2783                if (!(portchange & USB_PORT_STAT_C_CONNECTION) &&
2784                     (portstatus & USB_PORT_STAT_CONNECTION) == connection) {
2785                        stable_time += HUB_DEBOUNCE_STEP;
2786                        if (stable_time >= HUB_DEBOUNCE_STABLE)
2787                                break;
2788                } else {
2789                        stable_time = 0;
2790                        connection = portstatus & USB_PORT_STAT_CONNECTION;
2791                }
2792
2793                if (portchange & USB_PORT_STAT_C_CONNECTION) {
2794                        clear_port_feature(hub->hdev, port1,
2795                                        USB_PORT_FEAT_C_CONNECTION);
2796                }
2797
2798                if (total_time >= HUB_DEBOUNCE_TIMEOUT)
2799                        break;
2800                msleep(HUB_DEBOUNCE_STEP);
2801        }
2802
2803        dev_dbg (hub->intfdev,
2804                "debounce: port %d: total %dms stable %dms status 0x%x\n",
2805                port1, total_time, stable_time, portstatus);
2806
2807        if (stable_time < HUB_DEBOUNCE_STABLE)
2808                return -ETIMEDOUT;
2809        return portstatus;
2810}
2811
2812void usb_ep0_reinit(struct usb_device *udev)
2813{
2814        usb_disable_endpoint(udev, 0 + USB_DIR_IN, true);
2815        usb_disable_endpoint(udev, 0 + USB_DIR_OUT, true);
2816        usb_enable_endpoint(udev, &udev->ep0, true);
2817}
2818EXPORT_SYMBOL_GPL(usb_ep0_reinit);
2819
2820#define usb_sndaddr0pipe()      (PIPE_CONTROL << 30)
2821#define usb_rcvaddr0pipe()      ((PIPE_CONTROL << 30) | USB_DIR_IN)
2822
2823static int hub_set_address(struct usb_device *udev, int devnum)
2824{
2825        int retval;
2826        struct usb_hcd *hcd = bus_to_hcd(udev->bus);
2827
2828        /*
2829         * The host controller will choose the device address,
2830         * instead of the core having chosen it earlier
2831         */
2832        if (!hcd->driver->address_device && devnum <= 1)
2833                return -EINVAL;
2834        if (udev->state == USB_STATE_ADDRESS)
2835                return 0;
2836        if (udev->state != USB_STATE_DEFAULT)
2837                return -EINVAL;
2838        if (hcd->driver->address_device)
2839                retval = hcd->driver->address_device(hcd, udev);
2840        else
2841                retval = usb_control_msg(udev, usb_sndaddr0pipe(),
2842                                USB_REQ_SET_ADDRESS, 0, devnum, 0,
2843                                NULL, 0, USB_CTRL_SET_TIMEOUT);
2844        if (retval == 0) {
2845                update_devnum(udev, devnum);
2846                /* Device now using proper address. */
2847                usb_set_device_state(udev, USB_STATE_ADDRESS);
2848                usb_ep0_reinit(udev);
2849        }
2850        return retval;
2851}
2852
2853/* Reset device, (re)assign address, get device descriptor.
2854 * Device connection must be stable, no more debouncing needed.
2855 * Returns device in USB_STATE_ADDRESS, except on error.
2856 *
2857 * If this is called for an already-existing device (as part of
2858 * usb_reset_and_verify_device), the caller must own the device lock.  For a
2859 * newly detected device that is not accessible through any global
2860 * pointers, it's not necessary to lock the device.
2861 */
2862static int
2863hub_port_init (struct usb_hub *hub, struct usb_device *udev, int port1,
2864                int retry_counter)
2865{
2866        static DEFINE_MUTEX(usb_address0_mutex);
2867
2868        struct usb_device       *hdev = hub->hdev;
2869        struct usb_hcd          *hcd = bus_to_hcd(hdev->bus);
2870        int                     i, j, retval;
2871        unsigned                delay = HUB_SHORT_RESET_TIME;
2872        enum usb_device_speed   oldspeed = udev->speed;
2873        const char              *speed;
2874        int                     devnum = udev->devnum;
2875
2876        /* root hub ports have a slightly longer reset period
2877         * (from USB 2.0 spec, section 7.1.7.5)
2878         */
2879        if (!hdev->parent) {
2880                delay = HUB_ROOT_RESET_TIME;
2881                if (port1 == hdev->bus->otg_port)
2882                        hdev->bus->b_hnp_enable = 0;
2883        }
2884
2885        /* Some low speed devices have problems with the quick delay, so */
2886        /*  be a bit pessimistic with those devices. RHbug #23670 */
2887        if (oldspeed == USB_SPEED_LOW)
2888                delay = HUB_LONG_RESET_TIME;
2889
2890        mutex_lock(&usb_address0_mutex);
2891
2892        /* Reset the device; full speed may morph to high speed */
2893        /* FIXME a USB 2.0 device may morph into SuperSpeed on reset. */
2894        retval = hub_port_reset(hub, port1, udev, delay, false);
2895        if (retval < 0)         /* error or disconnect */
2896                goto fail;
2897        /* success, speed is known */
2898
2899        retval = -ENODEV;
2900#if defined(CONFIG_MACH_AR7100) || defined(CONFIG_MACH_AR7240) || defined(CONFIG_LANTIQ)
2901        ap_usb_led_on();
2902#endif
2903        if (oldspeed != USB_SPEED_UNKNOWN && oldspeed != udev->speed) {
2904                dev_dbg(&udev->dev, "device reset changed speed!\n");
2905                goto fail;
2906        }
2907        oldspeed = udev->speed;
2908
2909        /* USB 2.0 section 5.5.3 talks about ep0 maxpacket ...
2910         * it's fixed size except for full speed devices.
2911         * For Wireless USB devices, ep0 max packet is always 512 (tho
2912         * reported as 0xff in the device descriptor). WUSB1.0[4.8.1].
2913         */
2914        switch (udev->speed) {
2915        case USB_SPEED_SUPER:
2916        case USB_SPEED_WIRELESS:        /* fixed at 512 */
2917                udev->ep0.desc.wMaxPacketSize = cpu_to_le16(512);
2918                break;
2919        case USB_SPEED_HIGH:            /* fixed at 64 */
2920                udev->ep0.desc.wMaxPacketSize = cpu_to_le16(64);
2921                break;
2922        case USB_SPEED_FULL:            /* 8, 16, 32, or 64 */
2923                /* to determine the ep0 maxpacket size, try to read
2924                 * the device descriptor to get bMaxPacketSize0 and
2925                 * then correct our initial guess.
2926                 */
2927                udev->ep0.desc.wMaxPacketSize = cpu_to_le16(64);
2928                break;
2929        case USB_SPEED_LOW:             /* fixed at 8 */
2930                udev->ep0.desc.wMaxPacketSize = cpu_to_le16(8);
2931                break;
2932        default:
2933                goto fail;
2934        }
2935
2936        if (udev->speed == USB_SPEED_WIRELESS)
2937                speed = "variable speed Wireless";
2938        else
2939                speed = usb_speed_string(udev->speed);
2940
2941        if (udev->speed != USB_SPEED_SUPER)
2942                dev_info(&udev->dev,
2943                                "%s %s USB device number %d using %s\n",
2944                                (udev->config) ? "reset" : "new", speed,
2945                                devnum, udev->bus->controller->driver->name);
2946
2947        /* Set up TT records, if needed  */
2948        if (hdev->tt) {
2949                udev->tt = hdev->tt;
2950                udev->ttport = hdev->ttport;
2951        } else if (udev->speed != USB_SPEED_HIGH
2952                        && hdev->speed == USB_SPEED_HIGH) {
2953/*              if (!hub->tt.hub) {
2954                        dev_err(&udev->dev, "parent hub has no TT\n");
2955                        retval = -EINVAL;
2956                        goto fail;
2957                }*/
2958                udev->tt = &hub->tt;
2959                udev->ttport = port1;
2960        }
2961 
2962        /* Why interleave GET_DESCRIPTOR and SET_ADDRESS this way?
2963         * Because device hardware and firmware is sometimes buggy in
2964         * this area, and this is how Linux has done it for ages.
2965         * Change it cautiously.
2966         *
2967         * NOTE:  If USE_NEW_SCHEME() is true we will start by issuing
2968         * a 64-byte GET_DESCRIPTOR request.  This is what Windows does,
2969         * so it may help with some non-standards-compliant devices.
2970         * Otherwise we start with SET_ADDRESS and then try to read the
2971         * first 8 bytes of the device descriptor to get the ep0 maxpacket
2972         * value.
2973         */
2974        for (i = 0; i < GET_DESCRIPTOR_TRIES; (++i, msleep(100))) {
2975                if (USE_NEW_SCHEME(retry_counter) && !(hcd->driver->flags & HCD_USB3)) {
2976                        struct usb_device_descriptor *buf;
2977                        int r = 0;
2978
2979#define GET_DESCRIPTOR_BUFSIZE  64
2980                        buf = kmalloc(GET_DESCRIPTOR_BUFSIZE, GFP_NOIO);
2981                        if (!buf) {
2982                                retval = -ENOMEM;
2983                                continue;
2984                        }
2985
2986                        /* Retry on all errors; some devices are flakey.
2987                         * 255 is for WUSB devices, we actually need to use
2988                         * 512 (WUSB1.0[4.8.1]).
2989                         */
2990                        for (j = 0; j < 3; ++j) {
2991                                buf->bMaxPacketSize0 = 0;
2992                                r = usb_control_msg(udev, usb_rcvaddr0pipe(),
2993                                        USB_REQ_GET_DESCRIPTOR, USB_DIR_IN,
2994                                        USB_DT_DEVICE << 8, 0,
2995                                        buf, GET_DESCRIPTOR_BUFSIZE,
2996                                        initial_descriptor_timeout);
2997                                switch (buf->bMaxPacketSize0) {
2998                                case 8: case 16: case 32: case 64: case 255:
2999                                        if (buf->bDescriptorType ==
3000                                                        USB_DT_DEVICE) {
3001                                                r = 0;
3002                                                break;
3003                                        }
3004                                        /* FALL THROUGH */
3005                                default:
3006                                        if (r == 0)
3007                                                r = -EPROTO;
3008                                        break;
3009                                }
3010                                if (r == 0)
3011                                        break;
3012                        }
3013                        udev->descriptor.bMaxPacketSize0 =
3014                                        buf->bMaxPacketSize0;
3015                        kfree(buf);
3016
3017                        retval = hub_port_reset(hub, port1, udev, delay, false);
3018                        if (retval < 0)         /* error or disconnect */
3019                                goto fail;
3020                        if (oldspeed != udev->speed) {
3021                                dev_dbg(&udev->dev,
3022                                        "device reset changed speed!\n");
3023                                retval = -ENODEV;
3024                                goto fail;
3025                        }
3026                        if (r) {
3027                                dev_err(&udev->dev,
3028                                        "device descriptor read/64, error %d\n",
3029                                        r);
3030                                retval = -EMSGSIZE;
3031                                continue;
3032                        }
3033#undef GET_DESCRIPTOR_BUFSIZE
3034                }
3035
3036                /*
3037                 * If device is WUSB, we already assigned an
3038                 * unauthorized address in the Connect Ack sequence;
3039                 * authorization will assign the final address.
3040                 */
3041                if (udev->wusb == 0) {
3042                        for (j = 0; j < SET_ADDRESS_TRIES; ++j) {
3043                                retval = hub_set_address(udev, devnum);
3044                                if (retval >= 0)
3045                                        break;
3046                                msleep(200);
3047                        }
3048                        if (retval < 0) {
3049                                dev_err(&udev->dev,
3050                                        "device not accepting address %d, error %d\n",
3051                                        devnum, retval);
3052                                goto fail;
3053                        }
3054                        if (udev->speed == USB_SPEED_SUPER) {
3055                                devnum = udev->devnum;
3056                                dev_info(&udev->dev,
3057                                                "%s SuperSpeed USB device number %d using %s\n",
3058                                                (udev->config) ? "reset" : "new",
3059                                                devnum, udev->bus->controller->driver->name);
3060                        }
3061
3062                        /* cope with hardware quirkiness:
3063                         *  - let SET_ADDRESS settle, some device hardware wants it
3064                         *  - read ep0 maxpacket even for high and low speed,
3065                         */
3066                        msleep(10);
3067                        if (USE_NEW_SCHEME(retry_counter) && !(hcd->driver->flags & HCD_USB3))
3068                                break;
3069                }
3070
3071                retval = usb_get_device_descriptor(udev, 8);
3072                if (retval < 8) {
3073                        dev_err(&udev->dev,
3074                                        "device descriptor read/8, error %d\n",
3075                                        retval);
3076                        if (retval >= 0)
3077                                retval = -EMSGSIZE;
3078                } else {
3079                        retval = 0;
3080                        break;
3081                }
3082        }
3083        if (retval)
3084                goto fail;
3085
3086        if (udev->descriptor.bMaxPacketSize0 == 0xff ||
3087                        udev->speed == USB_SPEED_SUPER)
3088                i = 512;
3089        else
3090                i = udev->descriptor.bMaxPacketSize0;
3091        if (usb_endpoint_maxp(&udev->ep0.desc) != i) {
3092                if (udev->speed == USB_SPEED_LOW ||
3093                                !(i == 8 || i == 16 || i == 32 || i == 64)) {
3094                        dev_err(&udev->dev, "Invalid ep0 maxpacket: %d\n", i);
3095                        retval = -EMSGSIZE;
3096                        goto fail;
3097                }
3098                if (udev->speed == USB_SPEED_FULL)
3099                        dev_dbg(&udev->dev, "ep0 maxpacket = %d\n", i);
3100                else
3101                        dev_warn(&udev->dev, "Using ep0 maxpacket: %d\n", i);
3102                udev->ep0.desc.wMaxPacketSize = cpu_to_le16(i);
3103                usb_ep0_reinit(udev);
3104        }
3105 
3106        retval = usb_get_device_descriptor(udev, USB_DT_DEVICE_SIZE);
3107        if (retval < (signed)sizeof(udev->descriptor)) {
3108                dev_err(&udev->dev, "device descriptor read/all, error %d\n",
3109                        retval);
3110                if (retval >= 0)
3111                        retval = -ENOMSG;
3112                goto fail;
3113        }
3114
3115        if (udev->wusb == 0 && le16_to_cpu(udev->descriptor.bcdUSB) >= 0x0201) {
3116                retval = usb_get_bos_descriptor(udev);
3117                if (!retval) {
3118                        if (udev->bos->ext_cap && (USB_LPM_SUPPORT &
3119                                le32_to_cpu(udev->bos->ext_cap->bmAttributes)))
3120                                        udev->lpm_capable = 1;
3121                }
3122        }
3123
3124        retval = 0;
3125        /* notify HCD that we have a device connected and addressed */
3126        if (hcd->driver->update_device)
3127                hcd->driver->update_device(hcd, udev);
3128fail:
3129        if (retval) {
3130                hub_port_disable(hub, port1, 0);
3131                update_devnum(udev, devnum);    /* for disconnect processing */
3132        }
3133        mutex_unlock(&usb_address0_mutex);
3134        return retval;
3135}
3136
3137static void
3138check_highspeed (struct usb_hub *hub, struct usb_device *udev, int port1)
3139{
3140        struct usb_qualifier_descriptor *qual;
3141        int                             status;
3142
3143        qual = kmalloc (sizeof *qual, GFP_KERNEL);
3144        if (qual == NULL)
3145                return;
3146
3147        status = usb_get_descriptor (udev, USB_DT_DEVICE_QUALIFIER, 0,
3148                        qual, sizeof *qual);
3149        if (status == sizeof *qual) {
3150                dev_info(&udev->dev, "not running at top speed; "
3151                        "connect to a high speed hub\n");
3152                /* hub LEDs are probably harder to miss than syslog */
3153                if (hub->has_indicators) {
3154                        hub->indicator[port1-1] = INDICATOR_GREEN_BLINK;
3155                        schedule_delayed_work (&hub->leds, 0);
3156                }
3157        }
3158        kfree(qual);
3159}
3160
3161static unsigned
3162hub_power_remaining (struct usb_hub *hub)
3163{
3164        struct usb_device *hdev = hub->hdev;
3165        int remaining;
3166        int port1;
3167
3168        if (!hub->limited_power)
3169                return 0;
3170
3171        remaining = hdev->bus_mA - hub->descriptor->bHubContrCurrent;
3172        for (port1 = 1; port1 <= hdev->maxchild; ++port1) {
3173                struct usb_device       *udev = hdev->children[port1 - 1];
3174                int                     delta;
3175
3176                if (!udev)
3177                        continue;
3178
3179                /* Unconfigured devices may not use more than 100mA,
3180                 * or 8mA for OTG ports */
3181                if (udev->actconfig)
3182                        delta = udev->actconfig->desc.bMaxPower * 2;
3183                else if (port1 != udev->bus->otg_port || hdev->parent)
3184                        delta = 100;
3185                else
3186                        delta = 8;
3187                if (delta > hub->mA_per_port)
3188                        dev_warn(&udev->dev,
3189                                 "%dmA is over %umA budget for port %d!\n",
3190                                 delta, hub->mA_per_port, port1);
3191                remaining -= delta;
3192        }
3193        if (remaining < 0) {
3194                dev_warn(hub->intfdev, "%dmA over power budget!\n",
3195                        - remaining);
3196                remaining = 0;
3197        }
3198        return remaining;
3199}
3200
3201/* Handle physical or logical connection change events.
3202 * This routine is called when:
3203 *      a port connection-change occurs;
3204 *      a port enable-change occurs (often caused by EMI);
3205 *      usb_reset_and_verify_device() encounters changed descriptors (as from
3206 *              a firmware download)
3207 * caller already locked the hub
3208 */
3209static void hub_port_connect_change(struct usb_hub *hub, int port1,
3210                                        u16 portstatus, u16 portchange)
3211{
3212        struct usb_device *hdev = hub->hdev;
3213        struct device *hub_dev = hub->intfdev;
3214        struct usb_hcd *hcd = bus_to_hcd(hdev->bus);
3215        unsigned wHubCharacteristics =
3216                        le16_to_cpu(hub->descriptor->wHubCharacteristics);
3217        struct usb_device *udev;
3218        int status, i;
3219
3220        dev_dbg (hub_dev,
3221                "port %d, status %04x, change %04x, %s\n",
3222                port1, portstatus, portchange, portspeed(hub, portstatus));
3223
3224        if (hub->has_indicators) {
3225                set_port_led(hub, port1, HUB_LED_AUTO);
3226                hub->indicator[port1-1] = INDICATOR_AUTO;
3227        }
3228
3229#ifdef  CONFIG_USB_OTG
3230        /* during HNP, don't repeat the debounce */
3231        if (hdev->bus->is_b_host)
3232                portchange &= ~(USB_PORT_STAT_C_CONNECTION |
3233                                USB_PORT_STAT_C_ENABLE);
3234#endif
3235
3236        /* Try to resuscitate an existing device */
3237        udev = hdev->children[port1-1];
3238        if ((portstatus & USB_PORT_STAT_CONNECTION) && udev &&
3239                        udev->state != USB_STATE_NOTATTACHED) {
3240                usb_lock_device(udev);
3241                if (portstatus & USB_PORT_STAT_ENABLE) {
3242                        status = 0;             /* Nothing to do */
3243
3244#ifdef CONFIG_USB_SUSPEND
3245                } else if (udev->state == USB_STATE_SUSPENDED &&
3246                                udev->persist_enabled) {
3247                        /* For a suspended device, treat this as a
3248                         * remote wakeup event.
3249                         */
3250                        status = usb_remote_wakeup(udev);
3251#endif
3252
3253                } else {
3254                        status = -ENODEV;       /* Don't resuscitate */
3255                }
3256                usb_unlock_device(udev);
3257
3258                if (status == 0) {
3259                        clear_bit(port1, hub->change_bits);
3260                        return;
3261                }
3262        }
3263
3264        /* Disconnect any existing devices under this port */
3265        if (udev)
3266                usb_disconnect(&hdev->children[port1-1]);
3267        clear_bit(port1, hub->change_bits);
3268
3269        /* We can forget about a "removed" device when there's a physical
3270         * disconnect or the connect status changes.
3271         */
3272        if (!(portstatus & USB_PORT_STAT_CONNECTION) ||
3273                        (portchange & USB_PORT_STAT_C_CONNECTION))
3274                clear_bit(port1, hub->removed_bits);
3275
3276        if (portchange & (USB_PORT_STAT_C_CONNECTION |
3277                                USB_PORT_STAT_C_ENABLE)) {
3278                status = hub_port_debounce(hub, port1);
3279                if (status < 0) {
3280                        if (printk_ratelimit())
3281                                dev_err(hub_dev, "connect-debounce failed, "
3282                                                "port %d disabled\n", port1);
3283                        portstatus &= ~USB_PORT_STAT_CONNECTION;
3284                } else {
3285                        portstatus = status;
3286                }
3287        }
3288
3289        /* Return now if debouncing failed or nothing is connected or
3290         * the device was "removed".
3291         */
3292        if (!(portstatus & USB_PORT_STAT_CONNECTION) ||
3293                        test_bit(port1, hub->removed_bits)) {
3294
3295                /* maybe switch power back on (e.g. root hub was reset) */
3296                if ((wHubCharacteristics & HUB_CHAR_LPSM) < 2
3297                                && !port_is_power_on(hub, portstatus))
3298                        set_port_feature(hdev, port1, USB_PORT_FEAT_POWER);
3299
3300                if (portstatus & USB_PORT_STAT_ENABLE)
3301                        goto done;
3302                return;
3303        }
3304
3305        for (i = 0; i < SET_CONFIG_TRIES; i++) {
3306
3307                /* reallocate for each attempt, since references
3308                 * to the previous one can escape in various ways
3309                 */
3310                udev = usb_alloc_dev(hdev, hdev->bus, port1);
3311                if (!udev) {
3312                        dev_err (hub_dev,
3313                                "couldn't allocate port %d usb_device\n",
3314                                port1);
3315                        goto done;
3316                }
3317
3318                usb_set_device_state(udev, USB_STATE_POWERED);
3319                udev->bus_mA = hub->mA_per_port;
3320                udev->level = hdev->level + 1;
3321                udev->wusb = hub_is_wusb(hub);
3322
3323                /* Only USB 3.0 devices are connected to SuperSpeed hubs. */
3324                if (hub_is_superspeed(hub->hdev))
3325                        udev->speed = USB_SPEED_SUPER;
3326                else
3327                        udev->speed = USB_SPEED_UNKNOWN;
3328
3329                choose_devnum(udev);
3330                if (udev->devnum <= 0) {
3331                        status = -ENOTCONN;     /* Don't retry */
3332                        goto loop;
3333                }
3334
3335                /* reset (non-USB 3.0 devices) and get descriptor */
3336                status = hub_port_init(hub, udev, port1, i);
3337                if (status < 0)
3338                        goto loop;
3339
3340                usb_detect_quirks(udev);
3341                if (udev->quirks & USB_QUIRK_DELAY_INIT)
3342                        msleep(1000);
3343
3344                /* consecutive bus-powered hubs aren't reliable; they can
3345                 * violate the voltage drop budget.  if the new child has
3346                 * a "powered" LED, users should notice we didn't enable it
3347                 * (without reading syslog), even without per-port LEDs
3348                 * on the parent.
3349                 */
3350                if (udev->descriptor.bDeviceClass == USB_CLASS_HUB
3351                                && udev->bus_mA <= 100) {
3352                        u16     devstat;
3353
3354                        status = usb_get_status(udev, USB_RECIP_DEVICE, 0,
3355                                        &devstat);
3356                        if (status < 2) {
3357                                dev_dbg(&udev->dev, "get status %d ?\n", status);
3358                                goto loop_disable;
3359                        }
3360                        le16_to_cpus(&devstat);
3361                        if ((devstat & (1 << USB_DEVICE_SELF_POWERED)) == 0) {
3362                                dev_err(&udev->dev,
3363                                        "can't connect bus-powered hub "
3364                                        "to this port\n");
3365                                if (hub->has_indicators) {
3366                                        hub->indicator[port1-1] =
3367                                                INDICATOR_AMBER_BLINK;
3368                                        schedule_delayed_work (&hub->leds, 0);
3369                                }
3370                                status = -ENOTCONN;     /* Don't retry */
3371                                goto loop_disable;
3372                        }
3373                }
3374 
3375                /* check for devices running slower than they could */
3376                if (le16_to_cpu(udev->descriptor.bcdUSB) >= 0x0200
3377                                && udev->speed == USB_SPEED_FULL
3378                                && highspeed_hubs != 0)
3379                        check_highspeed (hub, udev, port1);
3380
3381                /* Store the parent's children[] pointer.  At this point
3382                 * udev becomes globally accessible, although presumably
3383                 * no one will look at it until hdev is unlocked.
3384                 */
3385                status = 0;
3386
3387                /* We mustn't add new devices if the parent hub has
3388                 * been disconnected; we would race with the
3389                 * recursively_mark_NOTATTACHED() routine.
3390                 */
3391                spin_lock_irq(&device_state_lock);
3392                if (hdev->state == USB_STATE_NOTATTACHED)
3393                        status = -ENOTCONN;
3394                else
3395                        hdev->children[port1-1] = udev;
3396                spin_unlock_irq(&device_state_lock);
3397
3398                /* Run it through the hoops (find a driver, etc) */
3399                if (!status) {
3400                        status = usb_new_device(udev);
3401                        if (status) {
3402                                spin_lock_irq(&device_state_lock);
3403                                hdev->children[port1-1] = NULL;
3404                                spin_unlock_irq(&device_state_lock);
3405                        }
3406                }
3407
3408                if (status)
3409                        goto loop_disable;
3410
3411                status = hub_power_remaining(hub);
3412                if (status)
3413                        dev_dbg(hub_dev, "%dmA power budget left\n", status);
3414
3415                return;
3416
3417loop_disable:
3418                hub_port_disable(hub, port1, 1);
3419loop:
3420                usb_ep0_reinit(udev);
3421                release_devnum(udev);
3422                hub_free_dev(udev);
3423                usb_put_dev(udev);
3424                if ((status == -ENOTCONN) || (status == -ENOTSUPP))
3425                        break;
3426        }
3427        if (hub->hdev->parent ||
3428                        !hcd->driver->port_handed_over ||
3429                        !(hcd->driver->port_handed_over)(hcd, port1))
3430                dev_err(hub_dev, "unable to enumerate USB device on port %d\n",
3431                                port1);
3432 
3433done:
3434        hub_port_disable(hub, port1, 1);
3435        if (hcd->driver->relinquish_port && !hub->hdev->parent)
3436                hcd->driver->relinquish_port(hcd, port1);
3437}
3438
3439static void hub_events(void)
3440{
3441        struct list_head *tmp;
3442        struct usb_device *hdev;
3443        struct usb_interface *intf;
3444        struct usb_hub *hub;
3445        struct device *hub_dev;
3446        u16 hubstatus;
3447        u16 hubchange;
3448        u16 portstatus;
3449        u16 portchange;
3450        int i, ret;
3451        int connect_change;
3452
3453        /*
3454         *  We restart the list every time to avoid a deadlock with
3455         * deleting hubs downstream from this one. This should be
3456         * safe since we delete the hub from the event list.
3457         * Not the most efficient, but avoids deadlocks.
3458         */
3459        while (1) {
3460
3461                /* Grab the first entry at the beginning of the list */
3462                spin_lock_irq(&hub_event_lock);
3463                if (list_empty(&hub_event_list)) {
3464                        spin_unlock_irq(&hub_event_lock);
3465                        break;
3466                }
3467
3468                tmp = hub_event_list.next;
3469                list_del_init(tmp);
3470
3471                hub = list_entry(tmp, struct usb_hub, event_list);
3472                kref_get(&hub->kref);
3473                spin_unlock_irq(&hub_event_lock);
3474
3475                hdev = hub->hdev;
3476                hub_dev = hub->intfdev;
3477                intf = to_usb_interface(hub_dev);
3478                dev_dbg(hub_dev, "state %d ports %d chg %04x evt %04x\n",
3479                                hdev->state, hub->descriptor
3480                                        ? hub->descriptor->bNbrPorts
3481                                        : 0,
3482                                /* NOTE: expects max 15 ports... */
3483                                (u16) hub->change_bits[0],
3484                                (u16) hub->event_bits[0]);
3485
3486                /* Lock the device, then check to see if we were
3487                 * disconnected while waiting for the lock to succeed. */
3488                usb_lock_device(hdev);
3489                if (unlikely(hub->disconnected))
3490                        goto loop_disconnected;
3491
3492                /* If the hub has died, clean up after it */
3493                if (hdev->state == USB_STATE_NOTATTACHED) {
3494                        hub->error = -ENODEV;
3495                        hub_quiesce(hub, HUB_DISCONNECT);
3496                        goto loop;
3497                }
3498
3499                /* Autoresume */
3500                ret = usb_autopm_get_interface(intf);
3501                if (ret) {
3502                        dev_dbg(hub_dev, "Can't autoresume: %d\n", ret);
3503                        goto loop;
3504                }
3505
3506                /* If this is an inactive hub, do nothing */
3507                if (hub->quiescing)
3508                        goto loop_autopm;
3509
3510                if (hub->error) {
3511                        dev_dbg (hub_dev, "resetting for error %d\n",
3512                                hub->error);
3513
3514                        ret = usb_reset_device(hdev);
3515                        if (ret) {
3516                                dev_dbg (hub_dev,
3517                                        "error resetting hub: %d\n", ret);
3518                                goto loop_autopm;
3519                        }
3520
3521                        hub->nerrors = 0;
3522                        hub->error = 0;
3523                }
3524
3525                /* deal with port status changes */
3526                for (i = 1; i <= hub->descriptor->bNbrPorts; i++) {
3527                        if (test_bit(i, hub->busy_bits))
3528                                continue;
3529                        connect_change = test_bit(i, hub->change_bits);
3530                        if (!test_and_clear_bit(i, hub->event_bits) &&
3531                                        !connect_change)
3532                                continue;
3533
3534                        ret = hub_port_status(hub, i,
3535                                        &portstatus, &portchange);
3536                        if (ret < 0)
3537                                continue;
3538
3539                        if (portchange & USB_PORT_STAT_C_CONNECTION) {
3540                                clear_port_feature(hdev, i,
3541                                        USB_PORT_FEAT_C_CONNECTION);
3542                                connect_change = 1;
3543                        }
3544
3545                        if (portchange & USB_PORT_STAT_C_ENABLE) {
3546                                if (!connect_change)
3547                                        dev_dbg (hub_dev,
3548                                                "port %d enable change, "
3549                                                "status %08x\n",
3550                                                i, portstatus);
3551                                clear_port_feature(hdev, i,
3552                                        USB_PORT_FEAT_C_ENABLE);
3553
3554                                /*
3555                                 * EM interference sometimes causes badly
3556                                 * shielded USB devices to be shutdown by
3557                                 * the hub, this hack enables them again.
3558                                 * Works at least with mouse driver.
3559                                 */
3560                                if (!(portstatus & USB_PORT_STAT_ENABLE)
3561                                    && !connect_change
3562                                    && hdev->children[i-1]) {
3563                                        dev_err (hub_dev,
3564                                            "port %i "
3565                                            "disabled by hub (EMI?), "
3566                                            "re-enabling...\n",
3567                                                i);
3568                                        connect_change = 1;
3569                                }
3570                        }
3571
3572                        if (portchange & USB_PORT_STAT_C_SUSPEND) {
3573                                struct usb_device *udev;
3574
3575                                clear_port_feature(hdev, i,
3576                                        USB_PORT_FEAT_C_SUSPEND);
3577                                udev = hdev->children[i-1];
3578                                if (udev) {
3579                                        /* TRSMRCY = 10 msec */
3580                                        msleep(10);
3581
3582                                        usb_lock_device(udev);
3583                                        ret = usb_remote_wakeup(hdev->
3584                                                        children[i-1]);
3585                                        usb_unlock_device(udev);
3586                                        if (ret < 0)
3587                                                connect_change = 1;
3588                                } else {
3589                                        ret = -ENODEV;
3590                                        hub_port_disable(hub, i, 1);
3591                                }
3592                                dev_dbg (hub_dev,
3593                                        "resume on port %d, status %d\n",
3594                                        i, ret);
3595                        }
3596                       
3597                        if (portchange & USB_PORT_STAT_C_OVERCURRENT) {
3598                                u16 status = 0;
3599                                u16 unused;
3600
3601                                dev_dbg(hub_dev, "over-current change on port "
3602                                        "%d\n", i);
3603                                clear_port_feature(hdev, i,
3604                                        USB_PORT_FEAT_C_OVER_CURRENT);
3605                                msleep(100);    /* Cool down */
3606                                hub_power_on(hub, true);
3607                                hub_port_status(hub, i, &status, &unused);
3608                                if (status & USB_PORT_STAT_OVERCURRENT)
3609                                        dev_err(hub_dev, "over-current "
3610                                                "condition on port %d\n", i);
3611                        }
3612
3613                        if (portchange & USB_PORT_STAT_C_RESET) {
3614                                dev_dbg (hub_dev,
3615                                        "reset change on port %d\n",
3616                                        i);
3617                                clear_port_feature(hdev, i,
3618                                        USB_PORT_FEAT_C_RESET);
3619                        }
3620                        if ((portchange & USB_PORT_STAT_C_BH_RESET) &&
3621                                        hub_is_superspeed(hub->hdev)) {
3622                                dev_dbg(hub_dev,
3623                                        "warm reset change on port %d\n",
3624                                        i);
3625                                clear_port_feature(hdev, i,
3626                                        USB_PORT_FEAT_C_BH_PORT_RESET);
3627                        }
3628                        if (portchange & USB_PORT_STAT_C_LINK_STATE) {
3629                                clear_port_feature(hub->hdev, i,
3630                                                USB_PORT_FEAT_C_PORT_LINK_STATE);
3631                        }
3632                        if (portchange & USB_PORT_STAT_C_CONFIG_ERROR) {
3633                                dev_warn(hub_dev,
3634                                        "config error on port %d\n",
3635                                        i);
3636                                clear_port_feature(hub->hdev, i,
3637                                                USB_PORT_FEAT_C_PORT_CONFIG_ERROR);
3638                        }
3639
3640                        /* Warm reset a USB3 protocol port if it's in
3641                         * SS.Inactive state.
3642                         */
3643                        if (hub_is_superspeed(hub->hdev) &&
3644                                (portstatus & USB_PORT_STAT_LINK_STATE)
3645                                        == USB_SS_PORT_LS_SS_INACTIVE) {
3646                                dev_dbg(hub_dev, "warm reset port %d\n", i);
3647                                hub_port_reset(hub, i, NULL,
3648                                                HUB_BH_RESET_TIME, true);
3649                        }
3650
3651                        if (connect_change)
3652                                hub_port_connect_change(hub, i,
3653                                                portstatus, portchange);
3654                } /* end for i */
3655
3656                /* deal with hub status changes */
3657                if (test_and_clear_bit(0, hub->event_bits) == 0)
3658                        ;       /* do nothing */
3659                else if (hub_hub_status(hub, &hubstatus, &hubchange) < 0)
3660                        dev_err (hub_dev, "get_hub_status failed\n");
3661                else {
3662                        if (hubchange & HUB_CHANGE_LOCAL_POWER) {
3663                                dev_dbg (hub_dev, "power change\n");
3664                                clear_hub_feature(hdev, C_HUB_LOCAL_POWER);
3665                                if (hubstatus & HUB_STATUS_LOCAL_POWER)
3666                                        /* FIXME: Is this always true? */
3667                                        hub->limited_power = 1;
3668                                else
3669                                        hub->limited_power = 0;
3670                        }
3671                        if (hubchange & HUB_CHANGE_OVERCURRENT) {
3672                                u16 status = 0;
3673                                u16 unused;
3674
3675                                dev_dbg(hub_dev, "over-current change\n");
3676                                clear_hub_feature(hdev, C_HUB_OVER_CURRENT);
3677                                msleep(500);    /* Cool down */
3678                                hub_power_on(hub, true);
3679                                hub_hub_status(hub, &status, &unused);
3680                                if (status & HUB_STATUS_OVERCURRENT)
3681                                        dev_err(hub_dev, "over-current "
3682                                                "condition\n");
3683                        }
3684                }
3685
3686 loop_autopm:
3687                /* Balance the usb_autopm_get_interface() above */
3688                usb_autopm_put_interface_no_suspend(intf);
3689 loop:
3690                /* Balance the usb_autopm_get_interface_no_resume() in
3691                 * kick_khubd() and allow autosuspend.
3692                 */
3693                usb_autopm_put_interface(intf);
3694 loop_disconnected:
3695                usb_unlock_device(hdev);
3696                kref_put(&hub->kref, hub_release);
3697
3698        } /* end while (1) */
3699}
3700
3701static int hub_thread(void *__unused)
3702{
3703        /* khubd needs to be freezable to avoid intefering with USB-PERSIST
3704         * port handover.  Otherwise it might see that a full-speed device
3705         * was gone before the EHCI controller had handed its port over to
3706         * the companion full-speed controller.
3707         */
3708        set_freezable();
3709
3710        do {
3711                hub_events();
3712                wait_event_freezable(khubd_wait,
3713                                !list_empty(&hub_event_list) ||
3714                                kthread_should_stop());
3715        } while (!kthread_should_stop() || !list_empty(&hub_event_list));
3716
3717        pr_debug("%s: khubd exiting\n", usbcore_name);
3718        return 0;
3719}
3720
3721static const struct usb_device_id hub_id_table[] = {
3722    { .match_flags = USB_DEVICE_ID_MATCH_DEV_CLASS,
3723      .bDeviceClass = USB_CLASS_HUB},
3724    { .match_flags = USB_DEVICE_ID_MATCH_INT_CLASS,
3725      .bInterfaceClass = USB_CLASS_HUB},
3726    { }                                         /* Terminating entry */
3727};
3728
3729MODULE_DEVICE_TABLE (usb, hub_id_table);
3730
3731static struct usb_driver hub_driver = {
3732        .name =         "hub",
3733        .probe =        hub_probe,
3734        .disconnect =   hub_disconnect,
3735        .suspend =      hub_suspend,
3736        .resume =       hub_resume,
3737        .reset_resume = hub_reset_resume,
3738        .pre_reset =    hub_pre_reset,
3739        .post_reset =   hub_post_reset,
3740        .unlocked_ioctl = hub_ioctl,
3741        .id_table =     hub_id_table,
3742        .supports_autosuspend = 1,
3743};
3744
3745int usb_hub_init(void)
3746{
3747        if (usb_register(&hub_driver) < 0) {
3748                printk(KERN_ERR "%s: can't register hub driver\n",
3749                        usbcore_name);
3750                return -1;
3751        }
3752
3753        khubd_task = kthread_run(hub_thread, NULL, "khubd");
3754        if (!IS_ERR(khubd_task))
3755                return 0;
3756
3757        /* Fall through if kernel_thread failed */
3758        usb_deregister(&hub_driver);
3759        printk(KERN_ERR "%s: can't start khubd\n", usbcore_name);
3760
3761        return -1;
3762}
3763
3764void usb_hub_cleanup(void)
3765{
3766        kthread_stop(khubd_task);
3767
3768        /*
3769         * Hub resources are freed for us by usb_deregister. It calls
3770         * usb_driver_purge on every device which in turn calls that
3771         * devices disconnect function if it is using this driver.
3772         * The hub_disconnect function takes care of releasing the
3773         * individual hub resources. -greg
3774         */
3775        usb_deregister(&hub_driver);
3776} /* usb_hub_cleanup() */
3777
3778static int descriptors_changed(struct usb_device *udev,
3779                struct usb_device_descriptor *old_device_descriptor)
3780{
3781        int             changed = 0;
3782        unsigned        index;
3783        unsigned        serial_len = 0;
3784        unsigned        len;
3785        unsigned        old_length;
3786        int             length;
3787        char            *buf;
3788
3789        if (memcmp(&udev->descriptor, old_device_descriptor,
3790                        sizeof(*old_device_descriptor)) != 0)
3791                return 1;
3792
3793        /* Since the idVendor, idProduct, and bcdDevice values in the
3794         * device descriptor haven't changed, we will assume the
3795         * Manufacturer and Product strings haven't changed either.
3796         * But the SerialNumber string could be different (e.g., a
3797         * different flash card of the same brand).
3798         */
3799        if (udev->serial)
3800                serial_len = strlen(udev->serial) + 1;
3801
3802        len = serial_len;
3803        for (index = 0; index < udev->descriptor.bNumConfigurations; index++) {
3804                old_length = le16_to_cpu(udev->config[index].desc.wTotalLength);
3805                len = max(len, old_length);
3806        }
3807
3808        buf = kmalloc(len, GFP_NOIO);
3809        if (buf == NULL) {
3810                dev_err(&udev->dev, "no mem to re-read configs after reset\n");
3811                /* assume the worst */
3812                return 1;
3813        }
3814        for (index = 0; index < udev->descriptor.bNumConfigurations; index++) {
3815                old_length = le16_to_cpu(udev->config[index].desc.wTotalLength);
3816                length = usb_get_descriptor(udev, USB_DT_CONFIG, index, buf,
3817                                old_length);
3818                if (length != old_length) {
3819                        dev_dbg(&udev->dev, "config index %d, error %d\n",
3820                                        index, length);
3821                        changed = 1;
3822                        break;
3823                }
3824                if (memcmp (buf, udev->rawdescriptors[index], old_length)
3825                                != 0) {
3826                        dev_dbg(&udev->dev, "config index %d changed (#%d)\n",
3827                                index,
3828                                ((struct usb_config_descriptor *) buf)->
3829                                        bConfigurationValue);
3830                        changed = 1;
3831                        break;
3832                }
3833        }
3834
3835        if (!changed && serial_len) {
3836                length = usb_string(udev, udev->descriptor.iSerialNumber,
3837                                buf, serial_len);
3838                if (length + 1 != serial_len) {
3839                        dev_dbg(&udev->dev, "serial string error %d\n",
3840                                        length);
3841                        changed = 1;
3842                } else if (memcmp(buf, udev->serial, length) != 0) {
3843                        dev_dbg(&udev->dev, "serial string changed\n");
3844                        changed = 1;
3845                }
3846        }
3847
3848        kfree(buf);
3849        return changed;
3850}
3851
3852/**
3853 * usb_reset_and_verify_device - perform a USB port reset to reinitialize a device
3854 * @udev: device to reset (not in SUSPENDED or NOTATTACHED state)
3855 *
3856 * WARNING - don't use this routine to reset a composite device
3857 * (one with multiple interfaces owned by separate drivers)!
3858 * Use usb_reset_device() instead.
3859 *
3860 * Do a port reset, reassign the device's address, and establish its
3861 * former operating configuration.  If the reset fails, or the device's
3862 * descriptors change from their values before the reset, or the original
3863 * configuration and altsettings cannot be restored, a flag will be set
3864 * telling khubd to pretend the device has been disconnected and then
3865 * re-connected.  All drivers will be unbound, and the device will be
3866 * re-enumerated and probed all over again.
3867 *
3868 * Returns 0 if the reset succeeded, -ENODEV if the device has been
3869 * flagged for logical disconnection, or some other negative error code
3870 * if the reset wasn't even attempted.
3871 *
3872 * The caller must own the device lock.  For example, it's safe to use
3873 * this from a driver probe() routine after downloading new firmware.
3874 * For calls that might not occur during probe(), drivers should lock
3875 * the device using usb_lock_device_for_reset().
3876 *
3877 * Locking exception: This routine may also be called from within an
3878 * autoresume handler.  Such usage won't conflict with other tasks
3879 * holding the device lock because these tasks should always call
3880 * usb_autopm_resume_device(), thereby preventing any unwanted autoresume.
3881 */
3882static int usb_reset_and_verify_device(struct usb_device *udev)
3883{
3884        struct usb_device               *parent_hdev = udev->parent;
3885        struct usb_hub                  *parent_hub;
3886        struct usb_hcd                  *hcd = bus_to_hcd(udev->bus);
3887        struct usb_device_descriptor    descriptor = udev->descriptor;
3888        int                             i, ret = 0;
3889        int                             port1 = udev->portnum;
3890
3891        if (udev->state == USB_STATE_NOTATTACHED ||
3892                        udev->state == USB_STATE_SUSPENDED) {
3893                dev_dbg(&udev->dev, "device reset not allowed in state %d\n",
3894                                udev->state);
3895                return -EINVAL;
3896        }
3897
3898        if (!parent_hdev) {
3899                /* this requires hcd-specific logic; see ohci_restart() */
3900                dev_dbg(&udev->dev, "%s for root hub!\n", __func__);
3901                return -EISDIR;
3902        }
3903        parent_hub = hdev_to_hub(parent_hdev);
3904
3905        set_bit(port1, parent_hub->busy_bits);
3906        for (i = 0; i < SET_CONFIG_TRIES; ++i) {
3907
3908                /* ep0 maxpacket size may change; let the HCD know about it.
3909                 * Other endpoints will be handled by re-enumeration. */
3910                usb_ep0_reinit(udev);
3911                ret = hub_port_init(parent_hub, udev, port1, i);
3912                if (ret >= 0 || ret == -ENOTCONN || ret == -ENODEV)
3913                        break;
3914        }
3915        clear_bit(port1, parent_hub->busy_bits);
3916
3917        if (ret < 0)
3918                goto re_enumerate;
3919 
3920        /* Device might have changed firmware (DFU or similar) */
3921        if (descriptors_changed(udev, &descriptor)) {
3922                dev_info(&udev->dev, "device firmware changed\n");
3923                udev->descriptor = descriptor;  /* for disconnect() calls */
3924                goto re_enumerate;
3925        }
3926
3927        /* Restore the device's previous configuration */
3928        if (!udev->actconfig)
3929                goto done;
3930
3931        mutex_lock(hcd->bandwidth_mutex);
3932        ret = usb_hcd_alloc_bandwidth(udev, udev->actconfig, NULL, NULL);
3933        if (ret < 0) {
3934                dev_warn(&udev->dev,
3935                                "Busted HC?  Not enough HCD resources for "
3936                                "old configuration.\n");
3937                mutex_unlock(hcd->bandwidth_mutex);
3938                goto re_enumerate;
3939        }
3940        ret = usb_control_msg(udev, usb_sndctrlpipe(udev, 0),
3941                        USB_REQ_SET_CONFIGURATION, 0,
3942                        udev->actconfig->desc.bConfigurationValue, 0,
3943                        NULL, 0, USB_CTRL_SET_TIMEOUT);
3944        if (ret < 0) {
3945                dev_err(&udev->dev,
3946                        "can't restore configuration #%d (error=%d)\n",
3947                        udev->actconfig->desc.bConfigurationValue, ret);
3948                mutex_unlock(hcd->bandwidth_mutex);
3949                goto re_enumerate;
3950        }
3951        mutex_unlock(hcd->bandwidth_mutex);
3952        usb_set_device_state(udev, USB_STATE_CONFIGURED);
3953
3954        /* Put interfaces back into the same altsettings as before.
3955         * Don't bother to send the Set-Interface request for interfaces
3956         * that were already in altsetting 0; besides being unnecessary,
3957         * many devices can't handle it.  Instead just reset the host-side
3958         * endpoint state.
3959         */
3960        for (i = 0; i < udev->actconfig->desc.bNumInterfaces; i++) {
3961                struct usb_host_config *config = udev->actconfig;
3962                struct usb_interface *intf = config->interface[i];
3963                struct usb_interface_descriptor *desc;
3964
3965                desc = &intf->cur_altsetting->desc;
3966                if (desc->bAlternateSetting == 0) {
3967                        usb_disable_interface(udev, intf, true);
3968                        usb_enable_interface(udev, intf, true);
3969                        ret = 0;
3970                } else {
3971                        /* Let the bandwidth allocation function know that this
3972                         * device has been reset, and it will have to use
3973                         * alternate setting 0 as the current alternate setting.
3974                         */
3975                        intf->resetting_device = 1;
3976                        ret = usb_set_interface(udev, desc->bInterfaceNumber,
3977                                        desc->bAlternateSetting);
3978                        intf->resetting_device = 0;
3979                }
3980                if (ret < 0) {
3981                        dev_err(&udev->dev, "failed to restore interface %d "
3982                                "altsetting %d (error=%d)\n",
3983                                desc->bInterfaceNumber,
3984                                desc->bAlternateSetting,
3985                                ret);
3986                        goto re_enumerate;
3987                }
3988        }
3989
3990done:
3991        return 0;
3992 
3993re_enumerate:
3994        hub_port_logical_disconnect(parent_hub, port1);
3995        return -ENODEV;
3996}
3997
3998/**
3999 * usb_reset_device - warn interface drivers and perform a USB port reset
4000 * @udev: device to reset (not in SUSPENDED or NOTATTACHED state)
4001 *
4002 * Warns all drivers bound to registered interfaces (using their pre_reset
4003 * method), performs the port reset, and then lets the drivers know that
4004 * the reset is over (using their post_reset method).
4005 *
4006 * Return value is the same as for usb_reset_and_verify_device().
4007 *
4008 * The caller must own the device lock.  For example, it's safe to use
4009 * this from a driver probe() routine after downloading new firmware.
4010 * For calls that might not occur during probe(), drivers should lock
4011 * the device using usb_lock_device_for_reset().
4012 *
4013 * If an interface is currently being probed or disconnected, we assume
4014 * its driver knows how to handle resets.  For all other interfaces,
4015 * if the driver doesn't have pre_reset and post_reset methods then
4016 * we attempt to unbind it and rebind afterward.
4017 */
4018int usb_reset_device(struct usb_device *udev)
4019{
4020        int ret;
4021        int i;
4022        struct usb_host_config *config = udev->actconfig;
4023
4024        if (udev->state == USB_STATE_NOTATTACHED ||
4025                        udev->state == USB_STATE_SUSPENDED) {
4026                dev_dbg(&udev->dev, "device reset not allowed in state %d\n",
4027                                udev->state);
4028                return -EINVAL;
4029        }
4030
4031        /* Prevent autosuspend during the reset */
4032        usb_autoresume_device(udev);
4033
4034        if (config) {
4035                for (i = 0; i < config->desc.bNumInterfaces; ++i) {
4036                        struct usb_interface *cintf = config->interface[i];
4037                        struct usb_driver *drv;
4038                        int unbind = 0;
4039
4040                        if (cintf->dev.driver) {
4041                                drv = to_usb_driver(cintf->dev.driver);
4042                                if (drv->pre_reset && drv->post_reset)
4043                                        unbind = (drv->pre_reset)(cintf);
4044                                else if (cintf->condition ==
4045                                                USB_INTERFACE_BOUND)
4046                                        unbind = 1;
4047                                if (unbind)
4048                                        usb_forced_unbind_intf(cintf);
4049                        }
4050                }
4051        }
4052
4053        ret = usb_reset_and_verify_device(udev);
4054
4055        if (config) {
4056                for (i = config->desc.bNumInterfaces - 1; i >= 0; --i) {
4057                        struct usb_interface *cintf = config->interface[i];
4058                        struct usb_driver *drv;
4059                        int rebind = cintf->needs_binding;
4060
4061                        if (!rebind && cintf->dev.driver) {
4062                                drv = to_usb_driver(cintf->dev.driver);
4063                                if (drv->post_reset)
4064                                        rebind = (drv->post_reset)(cintf);
4065                                else if (cintf->condition ==
4066                                                USB_INTERFACE_BOUND)
4067                                        rebind = 1;
4068                        }
4069                        if (ret == 0 && rebind)
4070                                usb_rebind_intf(cintf);
4071                }
4072        }
4073
4074        usb_autosuspend_device(udev);
4075        return ret;
4076}
4077EXPORT_SYMBOL_GPL(usb_reset_device);
4078
4079
4080/**
4081 * usb_queue_reset_device - Reset a USB device from an atomic context
4082 * @iface: USB interface belonging to the device to reset
4083 *
4084 * This function can be used to reset a USB device from an atomic
4085 * context, where usb_reset_device() won't work (as it blocks).
4086 *
4087 * Doing a reset via this method is functionally equivalent to calling
4088 * usb_reset_device(), except for the fact that it is delayed to a
4089 * workqueue. This means that any drivers bound to other interfaces
4090 * might be unbound, as well as users from usbfs in user space.
4091 *
4092 * Corner cases:
4093 *
4094 * - Scheduling two resets at the same time from two different drivers
4095 *   attached to two different interfaces of the same device is
4096 *   possible; depending on how the driver attached to each interface
4097 *   handles ->pre_reset(), the second reset might happen or not.
4098 *
4099 * - If a driver is unbound and it had a pending reset, the reset will
4100 *   be cancelled.
4101 *
4102 * - This function can be called during .probe() or .disconnect()
4103 *   times. On return from .disconnect(), any pending resets will be
4104 *   cancelled.
4105 *
4106 * There is no no need to lock/unlock the @reset_ws as schedule_work()
4107 * does its own.
4108 *
4109 * NOTE: We don't do any reference count tracking because it is not
4110 *     needed. The lifecycle of the work_struct is tied to the
4111 *     usb_interface. Before destroying the interface we cancel the
4112 *     work_struct, so the fact that work_struct is queued and or
4113 *     running means the interface (and thus, the device) exist and
4114 *     are referenced.
4115 */
4116void usb_queue_reset_device(struct usb_interface *iface)
4117{
4118        schedule_work(&iface->reset_ws);
4119}
4120EXPORT_SYMBOL_GPL(usb_queue_reset_device);
Note: See TracBrowser for help on using the repository browser.