source: src/linux/pb42/linux-2.6.23/drivers/usb/core/hub.c @ 14511

Last change on this file since 14511 was 14511, checked in by BrainSlayer, 3 years ago

wndr3700 usb led

File size: 84.7 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/kthread.h>
23#include <linux/mutex.h>
24#include <linux/freezer.h>
25
26#include <asm/semaphore.h>
27#include <asm/uaccess.h>
28#include <asm/byteorder.h>
29
30#include "usb.h"
31#include "hcd.h"
32#include "hub.h"
33
34void ap_usb_led_on(void);
35void ap_usb_led_off(void);
36
37#ifdef  CONFIG_USB_PERSIST
38#define USB_PERSIST     1
39#else
40#define USB_PERSIST     0
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        dma_addr_t              buffer_dma;     /* DMA address for buffer */
52        union {
53                struct usb_hub_status   hub;
54                struct usb_port_status  port;
55        }                       *status;        /* buffer for status reports */
56        struct mutex            status_mutex;   /* for the status buffer */
57
58        int                     error;          /* last reported error */
59        int                     nerrors;        /* track consecutive errors */
60
61        struct list_head        event_list;     /* hubs w/data or errs ready */
62        unsigned long           event_bits[1];  /* status change bitmask */
63        unsigned long           change_bits[1]; /* ports with logical connect
64                                                        status change */
65        unsigned long           busy_bits[1];   /* ports being reset or
66                                                        resumed */
67#if USB_MAXCHILDREN > 31 /* 8*sizeof(unsigned long) - 1 */
68#error event_bits[] is too short!
69#endif
70
71        struct usb_hub_descriptor *descriptor;  /* class descriptor */
72        struct usb_tt           tt;             /* Transaction Translator */
73
74        unsigned                mA_per_port;    /* current for each child */
75
76        unsigned                limited_power:1;
77        unsigned                quiescing:1;
78        unsigned                activating:1;
79        unsigned                disconnected:1;
80
81        unsigned                has_indicators:1;
82        u8                      indicator[USB_MAXCHILDREN];
83        struct delayed_work     leds;
84};
85
86
87/* Protect struct usb_device->state and ->children members
88 * Note: Both are also protected by ->dev.sem, except that ->state can
89 * change to USB_STATE_NOTATTACHED even when the semaphore isn't held. */
90static DEFINE_SPINLOCK(device_state_lock);
91
92/* khubd's worklist and its lock */
93static DEFINE_SPINLOCK(hub_event_lock);
94static LIST_HEAD(hub_event_list);       /* List of hubs needing servicing */
95
96/* Wakes up khubd */
97static DECLARE_WAIT_QUEUE_HEAD(khubd_wait);
98
99static struct task_struct *khubd_task;
100
101/* cycle leds on hubs that aren't blinking for attention */
102static int blinkenlights = 0;
103module_param (blinkenlights, bool, S_IRUGO);
104MODULE_PARM_DESC (blinkenlights, "true to cycle leds on hubs");
105
106/*
107 * As of 2.6.10 we introduce a new USB device initialization scheme which
108 * closely resembles the way Windows works.  Hopefully it will be compatible
109 * with a wider range of devices than the old scheme.  However some previously
110 * working devices may start giving rise to "device not accepting address"
111 * errors; if that happens the user can try the old scheme by adjusting the
112 * following module parameters.
113 *
114 * For maximum flexibility there are two boolean parameters to control the
115 * hub driver's behavior.  On the first initialization attempt, if the
116 * "old_scheme_first" parameter is set then the old scheme will be used,
117 * otherwise the new scheme is used.  If that fails and "use_both_schemes"
118 * is set, then the driver will make another attempt, using the other scheme.
119 */
120static int old_scheme_first = 0;
121module_param(old_scheme_first, bool, S_IRUGO | S_IWUSR);
122MODULE_PARM_DESC(old_scheme_first,
123                 "start with the old device initialization scheme");
124
125static int use_both_schemes = 1;
126module_param(use_both_schemes, bool, S_IRUGO | S_IWUSR);
127MODULE_PARM_DESC(use_both_schemes,
128                "try the other device initialization scheme if the "
129                "first one fails");
130
131/* Mutual exclusion for EHCI CF initialization.  This interferes with
132 * port reset on some companion controllers.
133 */
134DECLARE_RWSEM(ehci_cf_port_reset_rwsem);
135EXPORT_SYMBOL_GPL(ehci_cf_port_reset_rwsem);
136
137
138static inline char *portspeed(int portstatus)
139{
140        if (portstatus & (1 << USB_PORT_FEAT_HIGHSPEED))
141                return "480 Mb/s";
142        else if (portstatus & (1 << USB_PORT_FEAT_LOWSPEED))
143                return "1.5 Mb/s";
144        else
145                return "12 Mb/s";
146}
147
148/* Note that hdev or one of its children must be locked! */
149static inline struct usb_hub *hdev_to_hub(struct usb_device *hdev)
150{
151        return usb_get_intfdata(hdev->actconfig->interface[0]);
152}
153
154/* USB 2.0 spec Section 11.24.4.5 */
155static int get_hub_descriptor(struct usb_device *hdev, void *data, int size)
156{
157        int i, ret;
158
159        for (i = 0; i < 3; i++) {
160                ret = usb_control_msg(hdev, usb_rcvctrlpipe(hdev, 0),
161                        USB_REQ_GET_DESCRIPTOR, USB_DIR_IN | USB_RT_HUB,
162                        USB_DT_HUB << 8, 0, data, size,
163                        USB_CTRL_GET_TIMEOUT);
164                if (ret >= (USB_DT_HUB_NONVAR_SIZE + 2))
165                        return ret;
166        }
167        return -EINVAL;
168}
169
170/*
171 * USB 2.0 spec Section 11.24.2.1
172 */
173static int clear_hub_feature(struct usb_device *hdev, int feature)
174{
175        return usb_control_msg(hdev, usb_sndctrlpipe(hdev, 0),
176                USB_REQ_CLEAR_FEATURE, USB_RT_HUB, feature, 0, NULL, 0, 1000);
177}
178
179/*
180 * USB 2.0 spec Section 11.24.2.2
181 */
182static int clear_port_feature(struct usb_device *hdev, int port1, int feature)
183{
184        return usb_control_msg(hdev, usb_sndctrlpipe(hdev, 0),
185                USB_REQ_CLEAR_FEATURE, USB_RT_PORT, feature, port1,
186                NULL, 0, 1000);
187}
188
189/*
190 * USB 2.0 spec Section 11.24.2.13
191 */
192static int set_port_feature(struct usb_device *hdev, int port1, int feature)
193{
194        return usb_control_msg(hdev, usb_sndctrlpipe(hdev, 0),
195                USB_REQ_SET_FEATURE, USB_RT_PORT, feature, port1,
196                NULL, 0, 1000);
197}
198
199/*
200 * USB 2.0 spec Section 11.24.2.7.1.10 and table 11-7
201 * for info about using port indicators
202 */
203static void set_port_led(
204        struct usb_hub *hub,
205        int port1,
206        int selector
207)
208{
209        int status = set_port_feature(hub->hdev, (selector << 8) | port1,
210                        USB_PORT_FEAT_INDICATOR);
211        if (status < 0)
212                dev_dbg (hub->intfdev,
213                        "port %d indicator %s status %d\n",
214                        port1,
215                        ({ char *s; switch (selector) {
216                        case HUB_LED_AMBER: s = "amber"; break;
217                        case HUB_LED_GREEN: s = "green"; break;
218                        case HUB_LED_OFF: s = "off"; break;
219                        case HUB_LED_AUTO: s = "auto"; break;
220                        default: s = "??"; break;
221                        }; s; }),
222                        status);
223}
224
225#define LED_CYCLE_PERIOD        ((2*HZ)/3)
226
227static void led_work (struct work_struct *work)
228{
229        struct usb_hub          *hub =
230                container_of(work, struct usb_hub, leds.work);
231        struct usb_device       *hdev = hub->hdev;
232        unsigned                i;
233        unsigned                changed = 0;
234        int                     cursor = -1;
235
236        if (hdev->state != USB_STATE_CONFIGURED || hub->quiescing)
237                return;
238
239        for (i = 0; i < hub->descriptor->bNbrPorts; i++) {
240                unsigned        selector, mode;
241
242                /* 30%-50% duty cycle */
243
244                switch (hub->indicator[i]) {
245                /* cycle marker */
246                case INDICATOR_CYCLE:
247                        cursor = i;
248                        selector = HUB_LED_AUTO;
249                        mode = INDICATOR_AUTO;
250                        break;
251                /* blinking green = sw attention */
252                case INDICATOR_GREEN_BLINK:
253                        selector = HUB_LED_GREEN;
254                        mode = INDICATOR_GREEN_BLINK_OFF;
255                        break;
256                case INDICATOR_GREEN_BLINK_OFF:
257                        selector = HUB_LED_OFF;
258                        mode = INDICATOR_GREEN_BLINK;
259                        break;
260                /* blinking amber = hw attention */
261                case INDICATOR_AMBER_BLINK:
262                        selector = HUB_LED_AMBER;
263                        mode = INDICATOR_AMBER_BLINK_OFF;
264                        break;
265                case INDICATOR_AMBER_BLINK_OFF:
266                        selector = HUB_LED_OFF;
267                        mode = INDICATOR_AMBER_BLINK;
268                        break;
269                /* blink green/amber = reserved */
270                case INDICATOR_ALT_BLINK:
271                        selector = HUB_LED_GREEN;
272                        mode = INDICATOR_ALT_BLINK_OFF;
273                        break;
274                case INDICATOR_ALT_BLINK_OFF:
275                        selector = HUB_LED_AMBER;
276                        mode = INDICATOR_ALT_BLINK;
277                        break;
278                default:
279                        continue;
280                }
281                if (selector != HUB_LED_AUTO)
282                        changed = 1;
283                set_port_led(hub, i + 1, selector);
284                hub->indicator[i] = mode;
285        }
286        if (!changed && blinkenlights) {
287                cursor++;
288                cursor %= hub->descriptor->bNbrPorts;
289                set_port_led(hub, cursor + 1, HUB_LED_GREEN);
290                hub->indicator[cursor] = INDICATOR_CYCLE;
291                changed++;
292        }
293        if (changed)
294                schedule_delayed_work(&hub->leds, LED_CYCLE_PERIOD);
295}
296
297/* use a short timeout for hub/port status fetches */
298#define USB_STS_TIMEOUT         1000
299#define USB_STS_RETRIES         5
300
301/*
302 * USB 2.0 spec Section 11.24.2.6
303 */
304static int get_hub_status(struct usb_device *hdev,
305                struct usb_hub_status *data)
306{
307        int i, status = -ETIMEDOUT;
308
309        for (i = 0; i < USB_STS_RETRIES && status == -ETIMEDOUT; i++) {
310                status = usb_control_msg(hdev, usb_rcvctrlpipe(hdev, 0),
311                        USB_REQ_GET_STATUS, USB_DIR_IN | USB_RT_HUB, 0, 0,
312                        data, sizeof(*data), USB_STS_TIMEOUT);
313        }
314        return status;
315}
316
317/*
318 * USB 2.0 spec Section 11.24.2.7
319 */
320static int get_port_status(struct usb_device *hdev, int port1,
321                struct usb_port_status *data)
322{
323        int i, status = -ETIMEDOUT;
324
325        for (i = 0; i < USB_STS_RETRIES && status == -ETIMEDOUT; i++) {
326                status = usb_control_msg(hdev, usb_rcvctrlpipe(hdev, 0),
327                        USB_REQ_GET_STATUS, USB_DIR_IN | USB_RT_PORT, 0, port1,
328                        data, sizeof(*data), USB_STS_TIMEOUT);
329        }
330        return status;
331}
332
333static void kick_khubd(struct usb_hub *hub)
334{
335        unsigned long   flags;
336
337        /* Suppress autosuspend until khubd runs */
338        to_usb_interface(hub->intfdev)->pm_usage_cnt = 1;
339
340        spin_lock_irqsave(&hub_event_lock, flags);
341        if (!hub->disconnected & list_empty(&hub->event_list)) {
342                list_add_tail(&hub->event_list, &hub_event_list);
343                wake_up(&khubd_wait);
344        }
345        spin_unlock_irqrestore(&hub_event_lock, flags);
346}
347
348void usb_kick_khubd(struct usb_device *hdev)
349{
350        /* FIXME: What if hdev isn't bound to the hub driver? */
351        kick_khubd(hdev_to_hub(hdev));
352}
353
354
355/* completion function, fires on port status changes and various faults */
356static void hub_irq(struct urb *urb)
357{
358        struct usb_hub *hub = urb->context;
359        int status;
360        int i;
361        unsigned long bits;
362
363        switch (urb->status) {
364        case -ENOENT:           /* synchronous unlink */
365        case -ECONNRESET:       /* async unlink */
366        case -ESHUTDOWN:        /* hardware going away */
367                return;
368
369        default:                /* presumably an error */
370                /* Cause a hub reset after 10 consecutive errors */
371                dev_dbg (hub->intfdev, "transfer --> %d\n", urb->status);
372                if ((++hub->nerrors < 10) || hub->error)
373                        goto resubmit;
374                hub->error = urb->status;
375                /* FALL THROUGH */
376
377        /* let khubd handle things */
378        case 0:                 /* we got data:  port status changed */
379                bits = 0;
380                for (i = 0; i < urb->actual_length; ++i)
381                        bits |= ((unsigned long) ((*hub->buffer)[i]))
382                                        << (i*8);
383                hub->event_bits[0] = bits;
384                break;
385        }
386
387        hub->nerrors = 0;
388
389        /* Something happened, let khubd figure it out */
390        kick_khubd(hub);
391
392resubmit:
393        if (hub->quiescing)
394                return;
395
396        if ((status = usb_submit_urb (hub->urb, GFP_ATOMIC)) != 0
397                        && status != -ENODEV && status != -EPERM)
398                dev_err (hub->intfdev, "resubmit --> %d\n", status);
399}
400
401/* USB 2.0 spec Section 11.24.2.3 */
402static inline int
403hub_clear_tt_buffer (struct usb_device *hdev, u16 devinfo, u16 tt)
404{
405        return usb_control_msg(hdev, usb_rcvctrlpipe(hdev, 0),
406                               HUB_CLEAR_TT_BUFFER, USB_RT_PORT, devinfo,
407                               tt, NULL, 0, 1000);
408}
409
410/*
411 * enumeration blocks khubd for a long time. we use keventd instead, since
412 * long blocking there is the exception, not the rule.  accordingly, HCDs
413 * talking to TTs must queue control transfers (not just bulk and iso), so
414 * both can talk to the same hub concurrently.
415 */
416static void hub_tt_kevent (struct work_struct *work)
417{
418        struct usb_hub          *hub =
419                container_of(work, struct usb_hub, tt.kevent);
420        unsigned long           flags;
421        int                     limit = 100;
422
423        spin_lock_irqsave (&hub->tt.lock, flags);
424        while (--limit && !list_empty (&hub->tt.clear_list)) {
425                struct list_head        *temp;
426                struct usb_tt_clear     *clear;
427                struct usb_device       *hdev = hub->hdev;
428                int                     status;
429
430                temp = hub->tt.clear_list.next;
431                clear = list_entry (temp, struct usb_tt_clear, clear_list);
432                list_del (&clear->clear_list);
433
434                /* drop lock so HCD can concurrently report other TT errors */
435                spin_unlock_irqrestore (&hub->tt.lock, flags);
436                status = hub_clear_tt_buffer (hdev, clear->devinfo, clear->tt);
437                spin_lock_irqsave (&hub->tt.lock, flags);
438
439                if (status)
440                        dev_err (&hdev->dev,
441                                "clear tt %d (%04x) error %d\n",
442                                clear->tt, clear->devinfo, status);
443                kfree(clear);
444        }
445        spin_unlock_irqrestore (&hub->tt.lock, flags);
446}
447
448/**
449 * usb_hub_tt_clear_buffer - clear control/bulk TT state in high speed hub
450 * @udev: the device whose split transaction failed
451 * @pipe: identifies the endpoint of the failed transaction
452 *
453 * High speed HCDs use this to tell the hub driver that some split control or
454 * bulk transaction failed in a way that requires clearing internal state of
455 * a transaction translator.  This is normally detected (and reported) from
456 * interrupt context.
457 *
458 * It may not be possible for that hub to handle additional full (or low)
459 * speed transactions until that state is fully cleared out.
460 */
461void usb_hub_tt_clear_buffer (struct usb_device *udev, int pipe)
462{
463        struct usb_tt           *tt = udev->tt;
464        unsigned long           flags;
465        struct usb_tt_clear     *clear;
466
467        /* we've got to cope with an arbitrary number of pending TT clears,
468         * since each TT has "at least two" buffers that can need it (and
469         * there can be many TTs per hub).  even if they're uncommon.
470         */
471        if ((clear = kmalloc (sizeof *clear, GFP_ATOMIC)) == NULL) {
472                dev_err (&udev->dev, "can't save CLEAR_TT_BUFFER state\n");
473                /* FIXME recover somehow ... RESET_TT? */
474                return;
475        }
476
477        /* info that CLEAR_TT_BUFFER needs */
478        clear->tt = tt->multi ? udev->ttport : 1;
479        clear->devinfo = usb_pipeendpoint (pipe);
480        clear->devinfo |= udev->devnum << 4;
481        clear->devinfo |= usb_pipecontrol (pipe)
482                        ? (USB_ENDPOINT_XFER_CONTROL << 11)
483                        : (USB_ENDPOINT_XFER_BULK << 11);
484        if (usb_pipein (pipe))
485                clear->devinfo |= 1 << 15;
486       
487        /* tell keventd to clear state for this TT */
488        spin_lock_irqsave (&tt->lock, flags);
489        list_add_tail (&clear->clear_list, &tt->clear_list);
490        schedule_work (&tt->kevent);
491        spin_unlock_irqrestore (&tt->lock, flags);
492}
493
494static void hub_power_on(struct usb_hub *hub)
495{
496        int port1;
497        unsigned pgood_delay = hub->descriptor->bPwrOn2PwrGood * 2;
498        u16 wHubCharacteristics =
499                        le16_to_cpu(hub->descriptor->wHubCharacteristics);
500
501        /* Enable power on each port.  Some hubs have reserved values
502         * of LPSM (> 2) in their descriptors, even though they are
503         * USB 2.0 hubs.  Some hubs do not implement port-power switching
504         * but only emulate it.  In all cases, the ports won't work
505         * unless we send these messages to the hub.
506         */
507        if ((wHubCharacteristics & HUB_CHAR_LPSM) < 2)
508                dev_dbg(hub->intfdev, "enabling power on all ports\n");
509        else
510                dev_dbg(hub->intfdev, "trying to enable port power on "
511                                "non-switchable hub\n");
512        for (port1 = 1; port1 <= hub->descriptor->bNbrPorts; port1++)
513                set_port_feature(hub->hdev, port1, USB_PORT_FEAT_POWER);
514
515        /* Wait at least 100 msec for power to become stable */
516        msleep(max(pgood_delay, (unsigned) 100));
517}
518
519static void hub_quiesce(struct usb_hub *hub)
520{
521        /* (nonblocking) khubd and related activity won't re-trigger */
522        hub->quiescing = 1;
523        hub->activating = 0;
524
525        /* (blocking) stop khubd and related activity */
526        usb_kill_urb(hub->urb);
527        if (hub->has_indicators)
528                cancel_delayed_work(&hub->leds);
529        if (hub->has_indicators || hub->tt.hub)
530                flush_scheduled_work();
531}
532
533static void hub_activate(struct usb_hub *hub)
534{
535        int     status;
536
537        hub->quiescing = 0;
538        hub->activating = 1;
539
540        status = usb_submit_urb(hub->urb, GFP_NOIO);
541        if (status < 0)
542                dev_err(hub->intfdev, "activate --> %d\n", status);
543        if (hub->has_indicators && blinkenlights)
544                schedule_delayed_work(&hub->leds, LED_CYCLE_PERIOD);
545
546        /* scan all ports ASAP */
547        kick_khubd(hub);
548}
549
550static int hub_hub_status(struct usb_hub *hub,
551                u16 *status, u16 *change)
552{
553        int ret;
554
555        mutex_lock(&hub->status_mutex);
556        ret = get_hub_status(hub->hdev, &hub->status->hub);
557        if (ret < 0)
558                dev_err (hub->intfdev,
559                        "%s failed (err = %d)\n", __FUNCTION__, ret);
560        else {
561                *status = le16_to_cpu(hub->status->hub.wHubStatus);
562                *change = le16_to_cpu(hub->status->hub.wHubChange);
563                ret = 0;
564        }
565        mutex_unlock(&hub->status_mutex);
566        return ret;
567}
568
569static int hub_port_disable(struct usb_hub *hub, int port1, int set_state)
570{
571        struct usb_device *hdev = hub->hdev;
572        int ret = 0;
573
574        if (hdev->children[port1-1] && set_state)
575                usb_set_device_state(hdev->children[port1-1],
576                                USB_STATE_NOTATTACHED);
577        if (!hub->error)
578                ret = clear_port_feature(hdev, port1, USB_PORT_FEAT_ENABLE);
579        if (ret)
580                dev_err(hub->intfdev, "cannot disable port %d (err = %d)\n",
581                                port1, ret);
582        return ret;
583}
584
585/*
586 * Disable a port and mark a logical connnect-change event, so that some
587 * time later khubd will disconnect() any existing usb_device on the port
588 * and will re-enumerate if there actually is a device attached.
589 */
590static void hub_port_logical_disconnect(struct usb_hub *hub, int port1)
591{
592        dev_dbg(hub->intfdev, "logical disconnect on port %d\n", port1);
593        hub_port_disable(hub, port1, 1);
594
595        /* FIXME let caller ask to power down the port:
596         *  - some devices won't enumerate without a VBUS power cycle
597         *  - SRP saves power that way
598         *  - ... new call, TBD ...
599         * That's easy if this hub can switch power per-port, and
600         * khubd reactivates the port later (timer, SRP, etc).
601         * Powerdown must be optional, because of reset/DFU.
602         */
603
604        set_bit(port1, hub->change_bits);
605        kick_khubd(hub);
606}
607
608/* caller has locked the hub device */
609static int hub_pre_reset(struct usb_interface *intf)
610{
611        struct usb_hub *hub = usb_get_intfdata(intf);
612        struct usb_device *hdev = hub->hdev;
613        int i;
614
615        /* Disconnect all the children */
616        for (i = 0; i < hdev->maxchild; ++i) {
617                if (hdev->children[i])
618                        usb_disconnect(&hdev->children[i]);
619        }
620        hub_quiesce(hub);
621        return 0;
622}
623
624/* caller has locked the hub device */
625static int hub_post_reset(struct usb_interface *intf)
626{
627        struct usb_hub *hub = usb_get_intfdata(intf);
628
629        hub_power_on(hub);
630        hub_activate(hub);
631        return 0;
632}
633
634static int hub_configure(struct usb_hub *hub,
635        struct usb_endpoint_descriptor *endpoint)
636{
637        struct usb_device *hdev = hub->hdev;
638        struct device *hub_dev = hub->intfdev;
639        u16 hubstatus, hubchange;
640        u16 wHubCharacteristics;
641        unsigned int pipe;
642        int maxp, ret;
643        char *message;
644
645        hub->buffer = usb_buffer_alloc(hdev, sizeof(*hub->buffer), GFP_KERNEL,
646                        &hub->buffer_dma);
647        if (!hub->buffer) {
648                message = "can't allocate hub irq buffer";
649                ret = -ENOMEM;
650                goto fail;
651        }
652
653        hub->status = kmalloc(sizeof(*hub->status), GFP_KERNEL);
654        if (!hub->status) {
655                message = "can't kmalloc hub status buffer";
656                ret = -ENOMEM;
657                goto fail;
658        }
659        mutex_init(&hub->status_mutex);
660
661        hub->descriptor = kmalloc(sizeof(*hub->descriptor), GFP_KERNEL);
662        if (!hub->descriptor) {
663                message = "can't kmalloc hub descriptor";
664                ret = -ENOMEM;
665                goto fail;
666        }
667
668        /* Request the entire hub descriptor.
669         * hub->descriptor can handle USB_MAXCHILDREN ports,
670         * but the hub can/will return fewer bytes here.
671         */
672        ret = get_hub_descriptor(hdev, hub->descriptor,
673                        sizeof(*hub->descriptor));
674        if (ret < 0) {
675                message = "can't read hub descriptor";
676                goto fail;
677        } else if (hub->descriptor->bNbrPorts > USB_MAXCHILDREN) {
678                message = "hub has too many ports!";
679                ret = -ENODEV;
680                goto fail;
681        }
682
683        hdev->maxchild = hub->descriptor->bNbrPorts;
684        dev_info (hub_dev, "%d port%s detected\n", hdev->maxchild,
685                (hdev->maxchild == 1) ? "" : "s");
686
687        wHubCharacteristics = le16_to_cpu(hub->descriptor->wHubCharacteristics);
688
689        if (wHubCharacteristics & HUB_CHAR_COMPOUND) {
690                int     i;
691                char    portstr [USB_MAXCHILDREN + 1];
692
693                for (i = 0; i < hdev->maxchild; i++)
694                        portstr[i] = hub->descriptor->DeviceRemovable
695                                    [((i + 1) / 8)] & (1 << ((i + 1) % 8))
696                                ? 'F' : 'R';
697                portstr[hdev->maxchild] = 0;
698                dev_dbg(hub_dev, "compound device; port removable status: %s\n", portstr);
699        } else
700                dev_dbg(hub_dev, "standalone hub\n");
701
702        switch (wHubCharacteristics & HUB_CHAR_LPSM) {
703                case 0x00:
704                        dev_dbg(hub_dev, "ganged power switching\n");
705                        break;
706                case 0x01:
707                        dev_dbg(hub_dev, "individual port power switching\n");
708                        break;
709                case 0x02:
710                case 0x03:
711                        dev_dbg(hub_dev, "no power switching (usb 1.0)\n");
712                        break;
713        }
714
715        switch (wHubCharacteristics & HUB_CHAR_OCPM) {
716                case 0x00:
717                        dev_dbg(hub_dev, "global over-current protection\n");
718                        break;
719                case 0x08:
720                        dev_dbg(hub_dev, "individual port over-current protection\n");
721                        break;
722                case 0x10:
723                case 0x18:
724                        dev_dbg(hub_dev, "no over-current protection\n");
725                        break;
726        }
727
728        spin_lock_init (&hub->tt.lock);
729        INIT_LIST_HEAD (&hub->tt.clear_list);
730        INIT_WORK (&hub->tt.kevent, hub_tt_kevent);
731        switch (hdev->descriptor.bDeviceProtocol) {
732                case 0:
733                        break;
734                case 1:
735                        dev_dbg(hub_dev, "Single TT\n");
736                        hub->tt.hub = hdev;
737                        break;
738                case 2:
739                        ret = usb_set_interface(hdev, 0, 1);
740                        if (ret == 0) {
741                                dev_dbg(hub_dev, "TT per port\n");
742                                hub->tt.multi = 1;
743                        } else
744                                dev_err(hub_dev, "Using single TT (err %d)\n",
745                                        ret);
746                        hub->tt.hub = hdev;
747                        break;
748                default:
749                        dev_dbg(hub_dev, "Unrecognized hub protocol %d\n",
750                                hdev->descriptor.bDeviceProtocol);
751                        break;
752        }
753
754        /* Note 8 FS bit times == (8 bits / 12000000 bps) ~= 666ns */
755        switch (wHubCharacteristics & HUB_CHAR_TTTT) {
756                case HUB_TTTT_8_BITS:
757                        if (hdev->descriptor.bDeviceProtocol != 0) {
758                                hub->tt.think_time = 666;
759                                dev_dbg(hub_dev, "TT requires at most %d "
760                                                "FS bit times (%d ns)\n",
761                                        8, hub->tt.think_time);
762                        }
763                        break;
764                case HUB_TTTT_16_BITS:
765                        hub->tt.think_time = 666 * 2;
766                        dev_dbg(hub_dev, "TT requires at most %d "
767                                        "FS bit times (%d ns)\n",
768                                16, hub->tt.think_time);
769                        break;
770                case HUB_TTTT_24_BITS:
771                        hub->tt.think_time = 666 * 3;
772                        dev_dbg(hub_dev, "TT requires at most %d "
773                                        "FS bit times (%d ns)\n",
774                                24, hub->tt.think_time);
775                        break;
776                case HUB_TTTT_32_BITS:
777                        hub->tt.think_time = 666 * 4;
778                        dev_dbg(hub_dev, "TT requires at most %d "
779                                        "FS bit times (%d ns)\n",
780                                32, hub->tt.think_time);
781                        break;
782        }
783
784        /* probe() zeroes hub->indicator[] */
785        if (wHubCharacteristics & HUB_CHAR_PORTIND) {
786                hub->has_indicators = 1;
787                dev_dbg(hub_dev, "Port indicators are supported\n");
788        }
789
790        dev_dbg(hub_dev, "power on to power good time: %dms\n",
791                hub->descriptor->bPwrOn2PwrGood * 2);
792
793        /* power budgeting mostly matters with bus-powered hubs,
794         * and battery-powered root hubs (may provide just 8 mA).
795         */
796        ret = usb_get_status(hdev, USB_RECIP_DEVICE, 0, &hubstatus);
797        if (ret < 2) {
798                message = "can't get hub status";
799                goto fail;
800        }
801        le16_to_cpus(&hubstatus);
802        if (hdev == hdev->bus->root_hub) {
803                if (hdev->bus_mA == 0 || hdev->bus_mA >= 500)
804                        hub->mA_per_port = 500;
805                else {
806                        hub->mA_per_port = hdev->bus_mA;
807                        hub->limited_power = 1;
808                }
809        } else if ((hubstatus & (1 << USB_DEVICE_SELF_POWERED)) == 0) {
810                dev_dbg(hub_dev, "hub controller current requirement: %dmA\n",
811                        hub->descriptor->bHubContrCurrent);
812                hub->limited_power = 1;
813                if (hdev->maxchild > 0) {
814                        int remaining = hdev->bus_mA -
815                                        hub->descriptor->bHubContrCurrent;
816
817                        if (remaining < hdev->maxchild * 100)
818                                dev_warn(hub_dev,
819                                        "insufficient power available "
820                                        "to use all downstream ports\n");
821                        hub->mA_per_port = 100;         /* 7.2.1.1 */
822                }
823        } else {        /* Self-powered external hub */
824                /* FIXME: What about battery-powered external hubs that
825                 * provide less current per port? */
826                hub->mA_per_port = 500;
827        }
828        if (hub->mA_per_port < 500)
829                dev_dbg(hub_dev, "%umA bus power budget for each child\n",
830                                hub->mA_per_port);
831
832        ret = hub_hub_status(hub, &hubstatus, &hubchange);
833        if (ret < 0) {
834                message = "can't get hub status";
835                goto fail;
836        }
837
838        /* local power status reports aren't always correct */
839        if (hdev->actconfig->desc.bmAttributes & USB_CONFIG_ATT_SELFPOWER)
840                dev_dbg(hub_dev, "local power source is %s\n",
841                        (hubstatus & HUB_STATUS_LOCAL_POWER)
842                        ? "lost (inactive)" : "good");
843
844        if ((wHubCharacteristics & HUB_CHAR_OCPM) == 0)
845                dev_dbg(hub_dev, "%sover-current condition exists\n",
846                        (hubstatus & HUB_STATUS_OVERCURRENT) ? "" : "no ");
847
848        /* set up the interrupt endpoint
849         * We use the EP's maxpacket size instead of (PORTS+1+7)/8
850         * bytes as USB2.0[11.12.3] says because some hubs are known
851         * to send more data (and thus cause overflow). For root hubs,
852         * maxpktsize is defined in hcd.c's fake endpoint descriptors
853         * to be big enough for at least USB_MAXCHILDREN ports. */
854        pipe = usb_rcvintpipe(hdev, endpoint->bEndpointAddress);
855        maxp = usb_maxpacket(hdev, pipe, usb_pipeout(pipe));
856
857        if (maxp > sizeof(*hub->buffer))
858                maxp = sizeof(*hub->buffer);
859
860        hub->urb = usb_alloc_urb(0, GFP_KERNEL);
861        if (!hub->urb) {
862                message = "couldn't allocate interrupt urb";
863                ret = -ENOMEM;
864                goto fail;
865        }
866
867        usb_fill_int_urb(hub->urb, hdev, pipe, *hub->buffer, maxp, hub_irq,
868                hub, endpoint->bInterval);
869        hub->urb->transfer_dma = hub->buffer_dma;
870        hub->urb->transfer_flags |= URB_NO_TRANSFER_DMA_MAP;
871
872        /* maybe cycle the hub leds */
873        if (hub->has_indicators && blinkenlights)
874                hub->indicator [0] = INDICATOR_CYCLE;
875
876        hub_power_on(hub);
877        hub_activate(hub);
878        return 0;
879
880fail:
881        dev_err (hub_dev, "config failed, %s (err %d)\n",
882                        message, ret);
883        /* hub_disconnect() frees urb and descriptor */
884        return ret;
885}
886
887static void hub_release(struct kref *kref)
888{
889        struct usb_hub *hub = container_of(kref, struct usb_hub, kref);
890
891        usb_put_intf(to_usb_interface(hub->intfdev));
892        kfree(hub);
893}
894
895static unsigned highspeed_hubs;
896
897static void hub_disconnect(struct usb_interface *intf)
898{
899        struct usb_hub *hub = usb_get_intfdata (intf);
900
901        /* Take the hub off the event list and don't let it be added again */
902        spin_lock_irq(&hub_event_lock);
903        list_del_init(&hub->event_list);
904        hub->disconnected = 1;
905        spin_unlock_irq(&hub_event_lock);
906
907        /* Disconnect all children and quiesce the hub */
908        hub->error = 0;
909        hub_pre_reset(intf);
910
911        usb_set_intfdata (intf, NULL);
912
913        if (hub->hdev->speed == USB_SPEED_HIGH)
914                highspeed_hubs--;
915
916        usb_free_urb(hub->urb);
917        kfree(hub->descriptor);
918        kfree(hub->status);
919        usb_buffer_free(hub->hdev, sizeof(*hub->buffer), hub->buffer,
920                        hub->buffer_dma);
921
922        kref_put(&hub->kref, hub_release);
923}
924
925static int hub_probe(struct usb_interface *intf, const struct usb_device_id *id)
926{
927        struct usb_host_interface *desc;
928        struct usb_endpoint_descriptor *endpoint;
929        struct usb_device *hdev;
930        struct usb_hub *hub;
931
932        desc = intf->cur_altsetting;
933        hdev = interface_to_usbdev(intf);
934
935#ifdef  CONFIG_USB_OTG_BLACKLIST_HUB
936        if (hdev->parent) {
937                dev_warn(&intf->dev, "ignoring external hub\n");
938                return -ENODEV;
939        }
940#endif
941
942        /* Some hubs have a subclass of 1, which AFAICT according to the */
943        /*  specs is not defined, but it works */
944        if ((desc->desc.bInterfaceSubClass != 0) &&
945            (desc->desc.bInterfaceSubClass != 1)) {
946descriptor_error:
947                dev_err (&intf->dev, "bad descriptor, ignoring hub\n");
948                return -EIO;
949        }
950
951        /* Multiple endpoints? What kind of mutant ninja-hub is this? */
952        if (desc->desc.bNumEndpoints != 1)
953                goto descriptor_error;
954
955        endpoint = &desc->endpoint[0].desc;
956
957        /* If it's not an interrupt in endpoint, we'd better punt! */
958        if (!usb_endpoint_is_int_in(endpoint))
959                goto descriptor_error;
960
961        /* We found a hub */
962        dev_info (&intf->dev, "USB hub found\n");
963
964        hub = kzalloc(sizeof(*hub), GFP_KERNEL);
965        if (!hub) {
966                dev_dbg (&intf->dev, "couldn't kmalloc hub struct\n");
967                return -ENOMEM;
968        }
969
970        kref_init(&hub->kref);
971        INIT_LIST_HEAD(&hub->event_list);
972        hub->intfdev = &intf->dev;
973        hub->hdev = hdev;
974        INIT_DELAYED_WORK(&hub->leds, led_work);
975        usb_get_intf(intf);
976
977        usb_set_intfdata (intf, hub);
978        intf->needs_remote_wakeup = 1;
979
980        if (hdev->speed == USB_SPEED_HIGH)
981                highspeed_hubs++;
982
983        if (hub_configure(hub, endpoint) >= 0)
984                return 0;
985
986        hub_disconnect (intf);
987        return -ENODEV;
988}
989
990static int
991hub_ioctl(struct usb_interface *intf, unsigned int code, void *user_data)
992{
993        struct usb_device *hdev = interface_to_usbdev (intf);
994
995        /* assert ifno == 0 (part of hub spec) */
996        switch (code) {
997        case USBDEVFS_HUB_PORTINFO: {
998                struct usbdevfs_hub_portinfo *info = user_data;
999                int i;
1000
1001                spin_lock_irq(&device_state_lock);
1002                if (hdev->devnum <= 0)
1003                        info->nports = 0;
1004                else {
1005                        info->nports = hdev->maxchild;
1006                        for (i = 0; i < info->nports; i++) {
1007                                if (hdev->children[i] == NULL)
1008                                        info->port[i] = 0;
1009                                else
1010                                        info->port[i] =
1011                                                hdev->children[i]->devnum;
1012                        }
1013                }
1014                spin_unlock_irq(&device_state_lock);
1015
1016                return info->nports + 1;
1017                }
1018
1019        default:
1020                return -ENOSYS;
1021        }
1022}
1023
1024
1025static void recursively_mark_NOTATTACHED(struct usb_device *udev)
1026{
1027        int i;
1028
1029        for (i = 0; i < udev->maxchild; ++i) {
1030                if (udev->children[i])
1031                        recursively_mark_NOTATTACHED(udev->children[i]);
1032        }
1033        if (udev->state == USB_STATE_SUSPENDED)
1034                udev->discon_suspended = 1;
1035        udev->state = USB_STATE_NOTATTACHED;
1036}
1037
1038/**
1039 * usb_set_device_state - change a device's current state (usbcore, hcds)
1040 * @udev: pointer to device whose state should be changed
1041 * @new_state: new state value to be stored
1042 *
1043 * udev->state is _not_ fully protected by the device lock.  Although
1044 * most transitions are made only while holding the lock, the state can
1045 * can change to USB_STATE_NOTATTACHED at almost any time.  This
1046 * is so that devices can be marked as disconnected as soon as possible,
1047 * without having to wait for any semaphores to be released.  As a result,
1048 * all changes to any device's state must be protected by the
1049 * device_state_lock spinlock.
1050 *
1051 * Once a device has been added to the device tree, all changes to its state
1052 * should be made using this routine.  The state should _not_ be set directly.
1053 *
1054 * If udev->state is already USB_STATE_NOTATTACHED then no change is made.
1055 * Otherwise udev->state is set to new_state, and if new_state is
1056 * USB_STATE_NOTATTACHED then all of udev's descendants' states are also set
1057 * to USB_STATE_NOTATTACHED.
1058 */
1059void usb_set_device_state(struct usb_device *udev,
1060                enum usb_device_state new_state)
1061{
1062        unsigned long flags;
1063
1064        spin_lock_irqsave(&device_state_lock, flags);
1065        if (udev->state == USB_STATE_NOTATTACHED)
1066                ;       /* do nothing */
1067        else if (new_state != USB_STATE_NOTATTACHED) {
1068
1069                /* root hub wakeup capabilities are managed out-of-band
1070                 * and may involve silicon errata ... ignore them here.
1071                 */
1072                if (udev->parent) {
1073                        if (udev->state == USB_STATE_SUSPENDED
1074                                        || new_state == USB_STATE_SUSPENDED)
1075                                ;       /* No change to wakeup settings */
1076                        else if (new_state == USB_STATE_CONFIGURED)
1077                                device_init_wakeup(&udev->dev,
1078                                        (udev->actconfig->desc.bmAttributes
1079                                         & USB_CONFIG_ATT_WAKEUP));
1080                        else
1081                                device_init_wakeup(&udev->dev, 0);
1082                }
1083                udev->state = new_state;
1084        } else
1085                recursively_mark_NOTATTACHED(udev);
1086        spin_unlock_irqrestore(&device_state_lock, flags);
1087}
1088
1089static void choose_address(struct usb_device *udev)
1090{
1091        int             devnum;
1092        struct usb_bus  *bus = udev->bus;
1093
1094        /* If khubd ever becomes multithreaded, this will need a lock */
1095
1096        /* Try to allocate the next devnum beginning at bus->devnum_next. */
1097        devnum = find_next_zero_bit(bus->devmap.devicemap, 128,
1098                        bus->devnum_next);
1099        if (devnum >= 128)
1100                devnum = find_next_zero_bit(bus->devmap.devicemap, 128, 1);
1101
1102        bus->devnum_next = ( devnum >= 127 ? 1 : devnum + 1);
1103
1104        if (devnum < 128) {
1105                set_bit(devnum, bus->devmap.devicemap);
1106                udev->devnum = devnum;
1107        }
1108}
1109
1110static void release_address(struct usb_device *udev)
1111{
1112        if (udev->devnum > 0) {
1113                clear_bit(udev->devnum, udev->bus->devmap.devicemap);
1114                udev->devnum = -1;
1115        }
1116}
1117
1118#ifdef  CONFIG_USB_SUSPEND
1119
1120static void usb_stop_pm(struct usb_device *udev)
1121{
1122        /* Synchronize with the ksuspend thread to prevent any more
1123         * autosuspend requests from being submitted, and decrement
1124         * the parent's count of unsuspended children.
1125         */
1126        usb_pm_lock(udev);
1127        if (udev->parent && !udev->discon_suspended)
1128                usb_autosuspend_device(udev->parent);
1129        usb_pm_unlock(udev);
1130
1131        /* Stop any autosuspend requests already submitted */
1132        cancel_rearming_delayed_work(&udev->autosuspend);
1133}
1134
1135#else
1136
1137static inline void usb_stop_pm(struct usb_device *udev)
1138{ }
1139
1140#endif
1141
1142/**
1143 * usb_disconnect - disconnect a device (usbcore-internal)
1144 * @pdev: pointer to device being disconnected
1145 * Context: !in_interrupt ()
1146 *
1147 * Something got disconnected. Get rid of it and all of its children.
1148 *
1149 * If *pdev is a normal device then the parent hub must already be locked.
1150 * If *pdev is a root hub then this routine will acquire the
1151 * usb_bus_list_lock on behalf of the caller.
1152 *
1153 * Only hub drivers (including virtual root hub drivers for host
1154 * controllers) should ever call this.
1155 *
1156 * This call is synchronous, and may not be used in an interrupt context.
1157 */
1158void usb_disconnect(struct usb_device **pdev)
1159{
1160        struct usb_device       *udev = *pdev;
1161        int                     i;
1162
1163        if (!udev) {
1164                pr_debug ("%s nodev\n", __FUNCTION__);
1165                return;
1166        }
1167
1168        /* mark the device as inactive, so any further urb submissions for
1169         * this device (and any of its children) will fail immediately.
1170         * this quiesces everyting except pending urbs.
1171         */
1172        usb_set_device_state(udev, USB_STATE_NOTATTACHED);
1173        dev_info (&udev->dev, "USB disconnect, address %d\n", udev->devnum);
1174
1175        /* Turn USB LED off only if its a last device attached to root hub */
1176        if(udev->parent == udev->bus->root_hub)
1177                ap_usb_led_off();       
1178
1179        usb_lock_device(udev);
1180
1181        /* Free up all the children before we remove this device */
1182        for (i = 0; i < USB_MAXCHILDREN; i++) {
1183                if (udev->children[i])
1184                        usb_disconnect(&udev->children[i]);
1185        }
1186
1187        /* deallocate hcd/hardware state ... nuking all pending urbs and
1188         * cleaning up all state associated with the current configuration
1189         * so that the hardware is now fully quiesced.
1190         */
1191        dev_dbg (&udev->dev, "unregistering device\n");
1192        usb_disable_device(udev, 0);
1193
1194        usb_unlock_device(udev);
1195
1196        /* Unregister the device.  The device driver is responsible
1197         * for removing the device files from usbfs and sysfs and for
1198         * de-configuring the device.
1199         */
1200        device_del(&udev->dev);
1201
1202        /* Free the device number and delete the parent's children[]
1203         * (or root_hub) pointer.
1204         */
1205        release_address(udev);
1206
1207        /* Avoid races with recursively_mark_NOTATTACHED() */
1208        spin_lock_irq(&device_state_lock);
1209        *pdev = NULL;
1210        spin_unlock_irq(&device_state_lock);
1211
1212        usb_stop_pm(udev);
1213
1214        put_device(&udev->dev);
1215}
1216
1217#ifdef DEBUG
1218static void show_string(struct usb_device *udev, char *id, char *string)
1219{
1220        if (!string)
1221                return;
1222        dev_printk(KERN_INFO, &udev->dev, "%s: %s\n", id, string);
1223}
1224
1225#else
1226static inline void show_string(struct usb_device *udev, char *id, char *string)
1227{}
1228#endif
1229
1230
1231#ifdef  CONFIG_USB_OTG
1232#include "otg_whitelist.h"
1233#endif
1234
1235/**
1236 * usb_new_device - perform initial device setup (usbcore-internal)
1237 * @udev: newly addressed device (in ADDRESS state)
1238 *
1239 * This is called with devices which have been enumerated, but not yet
1240 * configured.  The device descriptor is available, but not descriptors
1241 * for any device configuration.  The caller must have locked either
1242 * the parent hub (if udev is a normal device) or else the
1243 * usb_bus_list_lock (if udev is a root hub).  The parent's pointer to
1244 * udev has already been installed, but udev is not yet visible through
1245 * sysfs or other filesystem code.
1246 *
1247 * It will return if the device is configured properly or not.  Zero if
1248 * the interface was registered with the driver core; else a negative
1249 * errno value.
1250 *
1251 * This call is synchronous, and may not be used in an interrupt context.
1252 *
1253 * Only the hub driver or root-hub registrar should ever call this.
1254 */
1255int usb_new_device(struct usb_device *udev)
1256{
1257        int err;
1258
1259        /* Determine quirks */
1260        usb_detect_quirks(udev);
1261
1262        err = usb_get_configuration(udev);
1263        if (err < 0) {
1264                dev_err(&udev->dev, "can't read configurations, error %d\n",
1265                        err);
1266                goto fail;
1267        }
1268
1269        /* read the standard strings and cache them if present */
1270        udev->product = usb_cache_string(udev, udev->descriptor.iProduct);
1271        udev->manufacturer = usb_cache_string(udev,
1272                        udev->descriptor.iManufacturer);
1273        udev->serial = usb_cache_string(udev, udev->descriptor.iSerialNumber);
1274
1275        /* Tell the world! */
1276        dev_dbg(&udev->dev, "new device strings: Mfr=%d, Product=%d, "
1277                        "SerialNumber=%d\n",
1278                        udev->descriptor.iManufacturer,
1279                        udev->descriptor.iProduct,
1280                        udev->descriptor.iSerialNumber);
1281        show_string(udev, "Product", udev->product);
1282        show_string(udev, "Manufacturer", udev->manufacturer);
1283        show_string(udev, "SerialNumber", udev->serial);
1284
1285#ifdef  CONFIG_USB_OTG
1286        /*
1287         * OTG-aware devices on OTG-capable root hubs may be able to use SRP,
1288         * to wake us after we've powered off VBUS; and HNP, switching roles
1289         * "host" to "peripheral".  The OTG descriptor helps figure this out.
1290         */
1291        if (!udev->bus->is_b_host
1292                        && udev->config
1293                        && udev->parent == udev->bus->root_hub) {
1294                struct usb_otg_descriptor       *desc = 0;
1295                struct usb_bus                  *bus = udev->bus;
1296
1297                /* descriptor may appear anywhere in config */
1298                if (__usb_get_extra_descriptor (udev->rawdescriptors[0],
1299                                        le16_to_cpu(udev->config[0].desc.wTotalLength),
1300                                        USB_DT_OTG, (void **) &desc) == 0) {
1301                        if (desc->bmAttributes & USB_OTG_HNP) {
1302                                unsigned                port1 = udev->portnum;
1303
1304                                dev_info(&udev->dev,
1305                                        "Dual-Role OTG device on %sHNP port\n",
1306                                        (port1 == bus->otg_port)
1307                                                ? "" : "non-");
1308
1309                                /* enable HNP before suspend, it's simpler */
1310                                if (port1 == bus->otg_port)
1311                                        bus->b_hnp_enable = 1;
1312                                err = usb_control_msg(udev,
1313                                        usb_sndctrlpipe(udev, 0),
1314                                        USB_REQ_SET_FEATURE, 0,
1315                                        bus->b_hnp_enable
1316                                                ? USB_DEVICE_B_HNP_ENABLE
1317                                                : USB_DEVICE_A_ALT_HNP_SUPPORT,
1318                                        0, NULL, 0, USB_CTRL_SET_TIMEOUT);
1319                                if (err < 0) {
1320                                        /* OTG MESSAGE: report errors here,
1321                                         * customize to match your product.
1322                                         */
1323                                        dev_info(&udev->dev,
1324                                                "can't set HNP mode; %d\n",
1325                                                err);
1326                                        bus->b_hnp_enable = 0;
1327                                }
1328                        }
1329                }
1330        }
1331
1332        if (!is_targeted(udev)) {
1333
1334                /* Maybe it can talk to us, though we can't talk to it.
1335                 * (Includes HNP test device.)
1336                 */
1337                if (udev->bus->b_hnp_enable || udev->bus->is_b_host) {
1338                        err = usb_port_suspend(udev);
1339                        if (err < 0)
1340                                dev_dbg(&udev->dev, "HNP fail, %d\n", err);
1341                }
1342                err = -ENOTSUPP;
1343                goto fail;
1344        }
1345#endif
1346
1347        /* export the usbdev device-node for libusb */
1348        udev->dev.devt = MKDEV(USB_DEVICE_MAJOR,
1349                        (((udev->bus->busnum-1) * 128) + (udev->devnum-1)));
1350
1351        /* Increment the parent's count of unsuspended children */
1352        if (udev->parent)
1353                usb_autoresume_device(udev->parent);
1354
1355        /* Register the device.  The device driver is responsible
1356         * for adding the device files to sysfs and for configuring
1357         * the device.
1358         */
1359        err = device_add(&udev->dev);
1360        if (err) {
1361                dev_err(&udev->dev, "can't device_add, error %d\n", err);
1362                if (udev->parent)
1363                        usb_autosuspend_device(udev->parent);
1364                goto fail;
1365        }
1366
1367exit:
1368        return err;
1369
1370fail:
1371        usb_set_device_state(udev, USB_STATE_NOTATTACHED);
1372        goto exit;
1373}
1374
1375static int hub_port_status(struct usb_hub *hub, int port1,
1376                               u16 *status, u16 *change)
1377{
1378        int ret;
1379
1380        mutex_lock(&hub->status_mutex);
1381        ret = get_port_status(hub->hdev, port1, &hub->status->port);
1382        if (ret < 4) {
1383                dev_err (hub->intfdev,
1384                        "%s failed (err = %d)\n", __FUNCTION__, ret);
1385                if (ret >= 0)
1386                        ret = -EIO;
1387        } else {
1388                *status = le16_to_cpu(hub->status->port.wPortStatus);
1389                *change = le16_to_cpu(hub->status->port.wPortChange);
1390                ret = 0;
1391        }
1392        mutex_unlock(&hub->status_mutex);
1393        return ret;
1394}
1395
1396
1397/* Returns 1 if @hub is a WUSB root hub, 0 otherwise */
1398static unsigned hub_is_wusb(struct usb_hub *hub)
1399{
1400        struct usb_hcd *hcd;
1401        if (hub->hdev->parent != NULL)  /* not a root hub? */
1402                return 0;
1403        hcd = container_of(hub->hdev->bus, struct usb_hcd, self);
1404        return hcd->wireless;
1405}
1406
1407
1408#define PORT_RESET_TRIES        5
1409#define SET_ADDRESS_TRIES       2
1410#define GET_DESCRIPTOR_TRIES    2
1411#define SET_CONFIG_TRIES        (2 * (use_both_schemes + 1))
1412#define USE_NEW_SCHEME(i)       ((i) / 2 == old_scheme_first)
1413
1414#define HUB_ROOT_RESET_TIME     50      /* times are in msec */
1415#define HUB_SHORT_RESET_TIME    10
1416#define HUB_LONG_RESET_TIME     200
1417#define HUB_RESET_TIMEOUT       500
1418
1419static int hub_port_wait_reset(struct usb_hub *hub, int port1,
1420                                struct usb_device *udev, unsigned int delay)
1421{
1422        int delay_time, ret;
1423        u16 portstatus;
1424        u16 portchange;
1425
1426        for (delay_time = 0;
1427                        delay_time < HUB_RESET_TIMEOUT;
1428                        delay_time += delay) {
1429                /* wait to give the device a chance to reset */
1430                msleep(delay);
1431
1432                /* read and decode port status */
1433                ret = hub_port_status(hub, port1, &portstatus, &portchange);
1434                if (ret < 0)
1435                        return ret;
1436
1437                /* Device went away? */
1438                if (!(portstatus & USB_PORT_STAT_CONNECTION))
1439                        return -ENOTCONN;
1440
1441                /* bomb out completely if the connection bounced */
1442                if ((portchange & USB_PORT_STAT_C_CONNECTION))
1443                        return -ENOTCONN;
1444
1445                /* if we`ve finished resetting, then break out of the loop */
1446                if (!(portstatus & USB_PORT_STAT_RESET) &&
1447                    (portstatus & USB_PORT_STAT_ENABLE)) {
1448                        if (hub_is_wusb(hub))
1449                                udev->speed = USB_SPEED_VARIABLE;
1450                        else if (portstatus & USB_PORT_STAT_HIGH_SPEED)
1451                                udev->speed = USB_SPEED_HIGH;
1452                        else if (portstatus & USB_PORT_STAT_LOW_SPEED)
1453                                udev->speed = USB_SPEED_LOW;
1454                        else
1455                                udev->speed = USB_SPEED_FULL;
1456                        return 0;
1457                }
1458
1459                /* switch to the long delay after two short delay failures */
1460                if (delay_time >= 2 * HUB_SHORT_RESET_TIME)
1461                        delay = HUB_LONG_RESET_TIME;
1462
1463                dev_dbg (hub->intfdev,
1464                        "port %d not reset yet, waiting %dms\n",
1465                        port1, delay);
1466        }
1467
1468        return -EBUSY;
1469}
1470
1471static int hub_port_reset(struct usb_hub *hub, int port1,
1472                                struct usb_device *udev, unsigned int delay)
1473{
1474        int i, status;
1475
1476        /* Block EHCI CF initialization during the port reset.
1477         * Some companion controllers don't like it when they mix.
1478         */
1479        down_read(&ehci_cf_port_reset_rwsem);
1480
1481        /* Reset the port */
1482        for (i = 0; i < PORT_RESET_TRIES; i++) {
1483                status = set_port_feature(hub->hdev,
1484                                port1, USB_PORT_FEAT_RESET);
1485                if (status)
1486                        dev_err(hub->intfdev,
1487                                        "cannot reset port %d (err = %d)\n",
1488                                        port1, status);
1489                else {
1490                        status = hub_port_wait_reset(hub, port1, udev, delay);
1491                        if (status && status != -ENOTCONN)
1492                                dev_dbg(hub->intfdev,
1493                                                "port_wait_reset: err = %d\n",
1494                                                status);
1495                }
1496
1497                /* return on disconnect or reset */
1498                switch (status) {
1499                case 0:
1500                        /* TRSTRCY = 10 ms; plus some extra */
1501                        msleep(10 + 40);
1502                        /* FALL THROUGH */
1503                case -ENOTCONN:
1504                case -ENODEV:
1505                        clear_port_feature(hub->hdev,
1506                                port1, USB_PORT_FEAT_C_RESET);
1507                        /* FIXME need disconnect() for NOTATTACHED device */
1508                        usb_set_device_state(udev, status
1509                                        ? USB_STATE_NOTATTACHED
1510                                        : USB_STATE_DEFAULT);
1511                        goto done;
1512                }
1513
1514                dev_dbg (hub->intfdev,
1515                        "port %d not enabled, trying reset again...\n",
1516                        port1);
1517                delay = HUB_LONG_RESET_TIME;
1518        }
1519
1520        dev_err (hub->intfdev,
1521                "Cannot enable port %i.  Maybe the USB cable is bad?\n",
1522                port1);
1523
1524 done:
1525        up_read(&ehci_cf_port_reset_rwsem);
1526        return status;
1527}
1528
1529#ifdef  CONFIG_PM
1530
1531#ifdef  CONFIG_USB_SUSPEND
1532
1533/*
1534 * usb_port_suspend - suspend a usb device's upstream port
1535 * @udev: device that's no longer in active use, not a root hub
1536 * Context: must be able to sleep; device not locked; pm locks held
1537 *
1538 * Suspends a USB device that isn't in active use, conserving power.
1539 * Devices may wake out of a suspend, if anything important happens,
1540 * using the remote wakeup mechanism.  They may also be taken out of
1541 * suspend by the host, using usb_port_resume().  It's also routine
1542 * to disconnect devices while they are suspended.
1543 *
1544 * This only affects the USB hardware for a device; its interfaces
1545 * (and, for hubs, child devices) must already have been suspended.
1546 *
1547 * Selective port suspend reduces power; most suspended devices draw
1548 * less than 500 uA.  It's also used in OTG, along with remote wakeup.
1549 * All devices below the suspended port are also suspended.
1550 *
1551 * Devices leave suspend state when the host wakes them up.  Some devices
1552 * also support "remote wakeup", where the device can activate the USB
1553 * tree above them to deliver data, such as a keypress or packet.  In
1554 * some cases, this wakes the USB host.
1555 *
1556 * Suspending OTG devices may trigger HNP, if that's been enabled
1557 * between a pair of dual-role devices.  That will change roles, such
1558 * as from A-Host to A-Peripheral or from B-Host back to B-Peripheral.
1559 *
1560 * Devices on USB hub ports have only one "suspend" state, corresponding
1561 * to ACPI D2, "may cause the device to lose some context".
1562 * State transitions include:
1563 *
1564 *   - suspend, resume ... when the VBUS power link stays live
1565 *   - suspend, disconnect ... VBUS lost
1566 *
1567 * Once VBUS drop breaks the circuit, the port it's using has to go through
1568 * normal re-enumeration procedures, starting with enabling VBUS power.
1569 * Other than re-initializing the hub (plug/unplug, except for root hubs),
1570 * Linux (2.6) currently has NO mechanisms to initiate that:  no khubd
1571 * timer, no SRP, no requests through sysfs.
1572 *
1573 * If CONFIG_USB_SUSPEND isn't enabled, devices only really suspend when
1574 * the root hub for their bus goes into global suspend ... so we don't
1575 * (falsely) update the device power state to say it suspended.
1576 *
1577 * Returns 0 on success, else negative errno.
1578 */
1579int usb_port_suspend(struct usb_device *udev)
1580{
1581        struct usb_hub  *hub = hdev_to_hub(udev->parent);
1582        int             port1 = udev->portnum;
1583        int             status;
1584
1585        // dev_dbg(hub->intfdev, "suspend port %d\n", port1);
1586
1587        /* enable remote wakeup when appropriate; this lets the device
1588         * wake up the upstream hub (including maybe the root hub).
1589         *
1590         * NOTE:  OTG devices may issue remote wakeup (or SRP) even when
1591         * we don't explicitly enable it here.
1592         */
1593        if (udev->do_remote_wakeup) {
1594                status = usb_control_msg(udev, usb_sndctrlpipe(udev, 0),
1595                                USB_REQ_SET_FEATURE, USB_RECIP_DEVICE,
1596                                USB_DEVICE_REMOTE_WAKEUP, 0,
1597                                NULL, 0,
1598                                USB_CTRL_SET_TIMEOUT);
1599                if (status)
1600                        dev_dbg(&udev->dev, "won't remote wakeup, status %d\n",
1601                                        status);
1602        }
1603
1604        /* see 7.1.7.6 */
1605        status = set_port_feature(hub->hdev, port1, USB_PORT_FEAT_SUSPEND);
1606        if (status) {
1607                dev_dbg(hub->intfdev, "can't suspend port %d, status %d\n",
1608                                port1, status);
1609                /* paranoia:  "should not happen" */
1610                (void) usb_control_msg(udev, usb_sndctrlpipe(udev, 0),
1611                                USB_REQ_CLEAR_FEATURE, USB_RECIP_DEVICE,
1612                                USB_DEVICE_REMOTE_WAKEUP, 0,
1613                                NULL, 0,
1614                                USB_CTRL_SET_TIMEOUT);
1615        } else {
1616                /* device has up to 10 msec to fully suspend */
1617                dev_dbg(&udev->dev, "usb %ssuspend\n",
1618                                udev->auto_pm ? "auto-" : "");
1619                usb_set_device_state(udev, USB_STATE_SUSPENDED);
1620                msleep(10);
1621        }
1622        return status;
1623}
1624
1625/*
1626 * If the USB "suspend" state is in use (rather than "global suspend"),
1627 * many devices will be individually taken out of suspend state using
1628 * special "resume" signaling.  This routine kicks in shortly after
1629 * hardware resume signaling is finished, either because of selective
1630 * resume (by host) or remote wakeup (by device) ... now see what changed
1631 * in the tree that's rooted at this device.
1632 *
1633 * If @udev->reset_resume is set then the device is reset before the
1634 * status check is done.
1635 */
1636static int finish_port_resume(struct usb_device *udev)
1637{
1638        int     status = 0;
1639        u16     devstatus;
1640
1641        /* caller owns the udev device lock */
1642        dev_dbg(&udev->dev, "finish %sresume\n",
1643                        udev->reset_resume ? "reset-" : "");
1644
1645        /* usb ch9 identifies four variants of SUSPENDED, based on what
1646         * state the device resumes to.  Linux currently won't see the
1647         * first two on the host side; they'd be inside hub_port_init()
1648         * during many timeouts, but khubd can't suspend until later.
1649         */
1650        usb_set_device_state(udev, udev->actconfig
1651                        ? USB_STATE_CONFIGURED
1652                        : USB_STATE_ADDRESS);
1653
1654        /* 10.5.4.5 says not to reset a suspended port if the attached
1655         * device is enabled for remote wakeup.  Hence the reset
1656         * operation is carried out here, after the port has been
1657         * resumed.
1658         */
1659        if (udev->reset_resume)
1660                status = usb_reset_device(udev);
1661
1662        /* 10.5.4.5 says be sure devices in the tree are still there.
1663         * For now let's assume the device didn't go crazy on resume,
1664         * and device drivers will know about any resume quirks.
1665         */
1666        if (status == 0) {
1667                devstatus = 0;
1668                status = usb_get_status(udev, USB_RECIP_DEVICE, 0, &devstatus);
1669                if (status >= 0)
1670                        status = (status > 0 ? 0 : -ENODEV);
1671        }
1672
1673        if (status) {
1674                dev_dbg(&udev->dev, "gone after usb resume? status %d\n",
1675                                status);
1676        } else if (udev->actconfig) {
1677                le16_to_cpus(&devstatus);
1678                if (devstatus & (1 << USB_DEVICE_REMOTE_WAKEUP)) {
1679                        status = usb_control_msg(udev,
1680                                        usb_sndctrlpipe(udev, 0),
1681                                        USB_REQ_CLEAR_FEATURE,
1682                                                USB_RECIP_DEVICE,
1683                                        USB_DEVICE_REMOTE_WAKEUP, 0,
1684                                        NULL, 0,
1685                                        USB_CTRL_SET_TIMEOUT);
1686                        if (status)
1687                                dev_dbg(&udev->dev, "disable remote "
1688                                        "wakeup, status %d\n", status);
1689                }
1690                status = 0;
1691        }
1692        return status;
1693}
1694
1695/*
1696 * usb_port_resume - re-activate a suspended usb device's upstream port
1697 * @udev: device to re-activate, not a root hub
1698 * Context: must be able to sleep; device not locked; pm locks held
1699 *
1700 * This will re-activate the suspended device, increasing power usage
1701 * while letting drivers communicate again with its endpoints.
1702 * USB resume explicitly guarantees that the power session between
1703 * the host and the device is the same as it was when the device
1704 * suspended.
1705 *
1706 * If CONFIG_USB_PERSIST and @udev->reset_resume are both set then this
1707 * routine won't check that the port is still enabled.  Furthermore,
1708 * if @udev->reset_resume is set then finish_port_resume() above will
1709 * reset @udev.  The end result is that a broken power session can be
1710 * recovered and @udev will appear to persist across a loss of VBUS power.
1711 *
1712 * For example, if a host controller doesn't maintain VBUS suspend current
1713 * during a system sleep or is reset when the system wakes up, all the USB
1714 * power sessions below it will be broken.  This is especially troublesome
1715 * for mass-storage devices containing mounted filesystems, since the
1716 * device will appear to have disconnected and all the memory mappings
1717 * to it will be lost.  Using the USB_PERSIST facility, the device can be
1718 * made to appear as if it had not disconnected.
1719 *
1720 * This facility is inherently dangerous.  Although usb_reset_device()
1721 * makes every effort to insure that the same device is present after the
1722 * reset as before, it cannot provide a 100% guarantee.  Furthermore it's
1723 * quite possible for a device to remain unaltered but its media to be
1724 * changed.  If the user replaces a flash memory card while the system is
1725 * asleep, he will have only himself to blame when the filesystem on the
1726 * new card is corrupted and the system crashes.
1727 *
1728 * Returns 0 on success, else negative errno.
1729 */
1730int usb_port_resume(struct usb_device *udev)
1731{
1732        struct usb_hub  *hub = hdev_to_hub(udev->parent);
1733        int             port1 = udev->portnum;
1734        int             status;
1735        u16             portchange, portstatus;
1736        unsigned        mask_flags, want_flags;
1737
1738        /* Skip the initial Clear-Suspend step for a remote wakeup */
1739        status = hub_port_status(hub, port1, &portstatus, &portchange);
1740        if (status == 0 && !(portstatus & USB_PORT_STAT_SUSPEND))
1741                goto SuspendCleared;
1742
1743        // dev_dbg(hub->intfdev, "resume port %d\n", port1);
1744
1745        set_bit(port1, hub->busy_bits);
1746
1747        /* see 7.1.7.7; affects power usage, but not budgeting */
1748        status = clear_port_feature(hub->hdev,
1749                        port1, USB_PORT_FEAT_SUSPEND);
1750        if (status) {
1751                dev_dbg(hub->intfdev, "can't resume port %d, status %d\n",
1752                                port1, status);
1753        } else {
1754                /* drive resume for at least 20 msec */
1755                dev_dbg(&udev->dev, "usb %sresume\n",
1756                                udev->auto_pm ? "auto-" : "");
1757                msleep(25);
1758
1759                /* Virtual root hubs can trigger on GET_PORT_STATUS to
1760                 * stop resume signaling.  Then finish the resume
1761                 * sequence.
1762                 */
1763                status = hub_port_status(hub, port1, &portstatus, &portchange);
1764
1765 SuspendCleared:
1766                if (USB_PERSIST && udev->reset_resume)
1767                        want_flags = USB_PORT_STAT_POWER
1768                                        | USB_PORT_STAT_CONNECTION;
1769                else
1770                        want_flags = USB_PORT_STAT_POWER
1771                                        | USB_PORT_STAT_CONNECTION
1772                                        | USB_PORT_STAT_ENABLE;
1773                mask_flags = want_flags | USB_PORT_STAT_SUSPEND;
1774
1775                if (status < 0 || (portstatus & mask_flags) != want_flags) {
1776                        dev_dbg(hub->intfdev,
1777                                "port %d status %04x.%04x after resume, %d\n",
1778                                port1, portchange, portstatus, status);
1779                        if (status >= 0)
1780                                status = -ENODEV;
1781                } else {
1782                        if (portchange & USB_PORT_STAT_C_SUSPEND)
1783                                clear_port_feature(hub->hdev, port1,
1784                                                USB_PORT_FEAT_C_SUSPEND);
1785                        /* TRSMRCY = 10 msec */
1786                        msleep(10);
1787                }
1788        }
1789
1790        clear_bit(port1, hub->busy_bits);
1791        if (!hub->hdev->parent && !hub->busy_bits[0])
1792                usb_enable_root_hub_irq(hub->hdev->bus);
1793
1794        if (status == 0)
1795                status = finish_port_resume(udev);
1796        if (status < 0) {
1797                dev_dbg(&udev->dev, "can't resume, status %d\n", status);
1798                hub_port_logical_disconnect(hub, port1);
1799        }
1800        return status;
1801}
1802
1803static int remote_wakeup(struct usb_device *udev)
1804{
1805        int     status = 0;
1806
1807        usb_lock_device(udev);
1808        if (udev->state == USB_STATE_SUSPENDED) {
1809                dev_dbg(&udev->dev, "usb %sresume\n", "wakeup-");
1810                usb_mark_last_busy(udev);
1811                status = usb_external_resume_device(udev);
1812        }
1813        usb_unlock_device(udev);
1814        return status;
1815}
1816
1817#else   /* CONFIG_USB_SUSPEND */
1818
1819/* When CONFIG_USB_SUSPEND isn't set, we never suspend or resume any ports. */
1820
1821int usb_port_suspend(struct usb_device *udev)
1822{
1823        return 0;
1824}
1825
1826int usb_port_resume(struct usb_device *udev)
1827{
1828        int status = 0;
1829
1830        /* However we may need to do a reset-resume */
1831        if (udev->reset_resume) {
1832                dev_dbg(&udev->dev, "reset-resume\n");
1833                status = usb_reset_device(udev);
1834        }
1835        return status;
1836}
1837
1838static inline int remote_wakeup(struct usb_device *udev)
1839{
1840        return 0;
1841}
1842
1843#endif
1844
1845static int hub_suspend(struct usb_interface *intf, pm_message_t msg)
1846{
1847        struct usb_hub          *hub = usb_get_intfdata (intf);
1848        struct usb_device       *hdev = hub->hdev;
1849        unsigned                port1;
1850
1851        /* fail if children aren't already suspended */
1852        for (port1 = 1; port1 <= hdev->maxchild; port1++) {
1853                struct usb_device       *udev;
1854
1855                udev = hdev->children [port1-1];
1856                if (udev && msg.event == PM_EVENT_SUSPEND &&
1857#ifdef  CONFIG_USB_SUSPEND
1858                                udev->state != USB_STATE_SUSPENDED
1859#else
1860                                udev->dev.power.power_state.event
1861                                        == PM_EVENT_ON
1862#endif
1863                                ) {
1864                        if (!hdev->auto_pm)
1865                                dev_dbg(&intf->dev, "port %d nyet suspended\n",
1866                                                port1);
1867                        return -EBUSY;
1868                }
1869        }
1870
1871        dev_dbg(&intf->dev, "%s\n", __FUNCTION__);
1872
1873        /* stop khubd and related activity */
1874        hub_quiesce(hub);
1875        return 0;
1876}
1877
1878static int hub_resume(struct usb_interface *intf)
1879{
1880        struct usb_hub          *hub = usb_get_intfdata (intf);
1881
1882        dev_dbg(&intf->dev, "%s\n", __FUNCTION__);
1883
1884        /* tell khubd to look for changes on this hub */
1885        hub_activate(hub);
1886        return 0;
1887}
1888
1889static int hub_reset_resume(struct usb_interface *intf)
1890{
1891        struct usb_hub *hub = usb_get_intfdata(intf);
1892        struct usb_device *hdev = hub->hdev;
1893        int port1;
1894
1895        hub_power_on(hub);
1896
1897        for (port1 = 1; port1 <= hdev->maxchild; ++port1) {
1898                struct usb_device *child = hdev->children[port1-1];
1899
1900                if (child) {
1901
1902                        /* For "USB_PERSIST"-enabled children we must
1903                         * mark the child device for reset-resume and
1904                         * turn off the connect-change status to prevent
1905                         * khubd from disconnecting it later.
1906                         */
1907                        if (USB_PERSIST && child->persist_enabled) {
1908                                child->reset_resume = 1;
1909                                clear_port_feature(hdev, port1,
1910                                                USB_PORT_FEAT_C_CONNECTION);
1911
1912                        /* Otherwise we must disconnect the child,
1913                         * but as we may not lock the child device here
1914                         * we have to do a "logical" disconnect.
1915                         */
1916                        } else {
1917                                hub_port_logical_disconnect(hub, port1);
1918                        }
1919                }
1920        }
1921
1922        hub_activate(hub);
1923        return 0;
1924}
1925
1926/**
1927 * usb_root_hub_lost_power - called by HCD if the root hub lost Vbus power
1928 * @rhdev: struct usb_device for the root hub
1929 *
1930 * The USB host controller driver calls this function when its root hub
1931 * is resumed and Vbus power has been interrupted or the controller
1932 * has been reset.  The routine marks @rhdev as having lost power.  When
1933 * the hub driver is resumed it will take notice; if CONFIG_USB_PERSIST
1934 * is enabled then it will carry out power-session recovery, otherwise
1935 * it will disconnect all the child devices.
1936 */
1937void usb_root_hub_lost_power(struct usb_device *rhdev)
1938{
1939        dev_warn(&rhdev->dev, "root hub lost power or was reset\n");
1940        rhdev->reset_resume = 1;
1941}
1942EXPORT_SYMBOL_GPL(usb_root_hub_lost_power);
1943
1944#else   /* CONFIG_PM */
1945
1946static inline int remote_wakeup(struct usb_device *udev)
1947{
1948        return 0;
1949}
1950
1951#define hub_suspend             NULL
1952#define hub_resume              NULL
1953#define hub_reset_resume        NULL
1954#endif
1955
1956
1957/* USB 2.0 spec, 7.1.7.3 / fig 7-29:
1958 *
1959 * Between connect detection and reset signaling there must be a delay
1960 * of 100ms at least for debounce and power-settling.  The corresponding
1961 * timer shall restart whenever the downstream port detects a disconnect.
1962 *
1963 * Apparently there are some bluetooth and irda-dongles and a number of
1964 * low-speed devices for which this debounce period may last over a second.
1965 * Not covered by the spec - but easy to deal with.
1966 *
1967 * This implementation uses a 1500ms total debounce timeout; if the
1968 * connection isn't stable by then it returns -ETIMEDOUT.  It checks
1969 * every 25ms for transient disconnects.  When the port status has been
1970 * unchanged for 100ms it returns the port status.
1971 */
1972
1973#define HUB_DEBOUNCE_TIMEOUT    1500
1974#define HUB_DEBOUNCE_STEP         25
1975#define HUB_DEBOUNCE_STABLE      100
1976
1977static int hub_port_debounce(struct usb_hub *hub, int port1)
1978{
1979        int ret;
1980        int total_time, stable_time = 0;
1981        u16 portchange, portstatus;
1982        unsigned connection = 0xffff;
1983
1984        for (total_time = 0; ; total_time += HUB_DEBOUNCE_STEP) {
1985                ret = hub_port_status(hub, port1, &portstatus, &portchange);
1986                if (ret < 0)
1987                        return ret;
1988
1989                if (!(portchange & USB_PORT_STAT_C_CONNECTION) &&
1990                     (portstatus & USB_PORT_STAT_CONNECTION) == connection) {
1991                        stable_time += HUB_DEBOUNCE_STEP;
1992                        if (stable_time >= HUB_DEBOUNCE_STABLE)
1993                                break;
1994                } else {
1995                        stable_time = 0;
1996                        connection = portstatus & USB_PORT_STAT_CONNECTION;
1997                }
1998
1999                if (portchange & USB_PORT_STAT_C_CONNECTION) {
2000                        clear_port_feature(hub->hdev, port1,
2001                                        USB_PORT_FEAT_C_CONNECTION);
2002                }
2003
2004                if (total_time >= HUB_DEBOUNCE_TIMEOUT)
2005                        break;
2006                msleep(HUB_DEBOUNCE_STEP);
2007        }
2008
2009        dev_dbg (hub->intfdev,
2010                "debounce: port %d: total %dms stable %dms status 0x%x\n",
2011                port1, total_time, stable_time, portstatus);
2012
2013        if (stable_time < HUB_DEBOUNCE_STABLE)
2014                return -ETIMEDOUT;
2015        return portstatus;
2016}
2017
2018static void ep0_reinit(struct usb_device *udev)
2019{
2020        usb_disable_endpoint(udev, 0 + USB_DIR_IN);
2021        usb_disable_endpoint(udev, 0 + USB_DIR_OUT);
2022        udev->ep_in[0] = udev->ep_out[0] = &udev->ep0;
2023}
2024
2025#define usb_sndaddr0pipe()      (PIPE_CONTROL << 30)
2026#define usb_rcvaddr0pipe()      ((PIPE_CONTROL << 30) | USB_DIR_IN)
2027
2028static int hub_set_address(struct usb_device *udev)
2029{
2030        int retval;
2031
2032        if (udev->devnum == 0)
2033                return -EINVAL;
2034        if (udev->state == USB_STATE_ADDRESS)
2035                return 0;
2036        if (udev->state != USB_STATE_DEFAULT)
2037                return -EINVAL;
2038        retval = usb_control_msg(udev, usb_sndaddr0pipe(),
2039                USB_REQ_SET_ADDRESS, 0, udev->devnum, 0,
2040                NULL, 0, USB_CTRL_SET_TIMEOUT);
2041        if (retval == 0) {
2042                usb_set_device_state(udev, USB_STATE_ADDRESS);
2043                ep0_reinit(udev);
2044        }
2045        return retval;
2046}
2047
2048/* Reset device, (re)assign address, get device descriptor.
2049 * Device connection must be stable, no more debouncing needed.
2050 * Returns device in USB_STATE_ADDRESS, except on error.
2051 *
2052 * If this is called for an already-existing device (as part of
2053 * usb_reset_device), the caller must own the device lock.  For a
2054 * newly detected device that is not accessible through any global
2055 * pointers, it's not necessary to lock the device.
2056 */
2057static int
2058hub_port_init (struct usb_hub *hub, struct usb_device *udev, int port1,
2059                int retry_counter)
2060{
2061        static DEFINE_MUTEX(usb_address0_mutex);
2062
2063        struct usb_device       *hdev = hub->hdev;
2064        int                     i, j, retval;
2065        unsigned                delay = HUB_SHORT_RESET_TIME;
2066        enum usb_device_speed   oldspeed = udev->speed;
2067        char                    *speed, *type;
2068
2069        /* root hub ports have a slightly longer reset period
2070         * (from USB 2.0 spec, section 7.1.7.5)
2071         */
2072        if (!hdev->parent) {
2073                delay = HUB_ROOT_RESET_TIME;
2074                if (port1 == hdev->bus->otg_port)
2075                        hdev->bus->b_hnp_enable = 0;
2076        }
2077
2078        /* Some low speed devices have problems with the quick delay, so */
2079        /*  be a bit pessimistic with those devices. RHbug #23670 */
2080        if (oldspeed == USB_SPEED_LOW)
2081                delay = HUB_LONG_RESET_TIME;
2082
2083        mutex_lock(&usb_address0_mutex);
2084
2085        /* Reset the device; full speed may morph to high speed */
2086        retval = hub_port_reset(hub, port1, udev, delay);
2087        if (retval < 0)         /* error or disconnect */
2088                goto fail;
2089                                /* success, speed is known */
2090        retval = -ENODEV;
2091        ap_usb_led_on();
2092
2093        if (oldspeed != USB_SPEED_UNKNOWN && oldspeed != udev->speed) {
2094                dev_dbg(&udev->dev, "device reset changed speed!\n");
2095                goto fail;
2096        }
2097        oldspeed = udev->speed;
2098 
2099        /* USB 2.0 section 5.5.3 talks about ep0 maxpacket ...
2100         * it's fixed size except for full speed devices.
2101         * For Wireless USB devices, ep0 max packet is always 512 (tho
2102         * reported as 0xff in the device descriptor). WUSB1.0[4.8.1].
2103         */
2104        switch (udev->speed) {
2105        case USB_SPEED_VARIABLE:        /* fixed at 512 */
2106                udev->ep0.desc.wMaxPacketSize = __constant_cpu_to_le16(512);
2107                break;
2108        case USB_SPEED_HIGH:            /* fixed at 64 */
2109                udev->ep0.desc.wMaxPacketSize = __constant_cpu_to_le16(64);
2110                break;
2111        case USB_SPEED_FULL:            /* 8, 16, 32, or 64 */
2112                /* to determine the ep0 maxpacket size, try to read
2113                 * the device descriptor to get bMaxPacketSize0 and
2114                 * then correct our initial guess.
2115                 */
2116                udev->ep0.desc.wMaxPacketSize = __constant_cpu_to_le16(64);
2117                break;
2118        case USB_SPEED_LOW:             /* fixed at 8 */
2119                udev->ep0.desc.wMaxPacketSize = __constant_cpu_to_le16(8);
2120                break;
2121        default:
2122                goto fail;
2123        }
2124 
2125        type = "";
2126        switch (udev->speed) {
2127        case USB_SPEED_LOW:     speed = "low";  break;
2128        case USB_SPEED_FULL:    speed = "full"; break;
2129        case USB_SPEED_HIGH:    speed = "high"; break;
2130        case USB_SPEED_VARIABLE:
2131                                speed = "variable";
2132                                type = "Wireless ";
2133                                break;
2134        default:                speed = "?";    break;
2135        }
2136        dev_info (&udev->dev,
2137                  "%s %s speed %sUSB device using %s and address %d\n",
2138                  (udev->config) ? "reset" : "new", speed, type,
2139                  udev->bus->controller->driver->name, udev->devnum);
2140
2141        /* Set up TT records, if needed  */
2142        if (hdev->tt) {
2143                udev->tt = hdev->tt;
2144                udev->ttport = hdev->ttport;
2145        } else if (udev->speed != USB_SPEED_HIGH
2146                        && hdev->speed == USB_SPEED_HIGH) {
2147                udev->tt = &hub->tt;
2148                udev->ttport = port1;
2149        }
2150 
2151        /* Why interleave GET_DESCRIPTOR and SET_ADDRESS this way?
2152         * Because device hardware and firmware is sometimes buggy in
2153         * this area, and this is how Linux has done it for ages.
2154         * Change it cautiously.
2155         *
2156         * NOTE:  If USE_NEW_SCHEME() is true we will start by issuing
2157         * a 64-byte GET_DESCRIPTOR request.  This is what Windows does,
2158         * so it may help with some non-standards-compliant devices.
2159         * Otherwise we start with SET_ADDRESS and then try to read the
2160         * first 8 bytes of the device descriptor to get the ep0 maxpacket
2161         * value.
2162         */
2163        for (i = 0; i < GET_DESCRIPTOR_TRIES; (++i, msleep(100))) {
2164                if (USE_NEW_SCHEME(retry_counter)) {
2165                        struct usb_device_descriptor *buf;
2166                        int r = 0;
2167
2168#define GET_DESCRIPTOR_BUFSIZE  64
2169                        buf = kmalloc(GET_DESCRIPTOR_BUFSIZE, GFP_NOIO);
2170                        if (!buf) {
2171                                retval = -ENOMEM;
2172                                continue;
2173                        }
2174
2175                        /* Retry on all errors; some devices are flakey.
2176                         * 255 is for WUSB devices, we actually need to use
2177                         * 512 (WUSB1.0[4.8.1]).
2178                         */
2179                        for (j = 0; j < 3; ++j) {
2180                                buf->bMaxPacketSize0 = 0;
2181                                r = usb_control_msg(udev, usb_rcvaddr0pipe(),
2182                                        USB_REQ_GET_DESCRIPTOR, USB_DIR_IN,
2183                                        USB_DT_DEVICE << 8, 0,
2184                                        buf, GET_DESCRIPTOR_BUFSIZE,
2185                                        USB_CTRL_GET_TIMEOUT);
2186                                switch (buf->bMaxPacketSize0) {
2187                                case 8: case 16: case 32: case 64: case 255:
2188                                        if (buf->bDescriptorType ==
2189                                                        USB_DT_DEVICE) {
2190                                                r = 0;
2191                                                break;
2192                                        }
2193                                        /* FALL THROUGH */
2194                                default:
2195                                        if (r == 0)
2196                                                r = -EPROTO;
2197                                        break;
2198                                }
2199                                if (r == 0)
2200                                        break;
2201                        }
2202                        udev->descriptor.bMaxPacketSize0 =
2203                                        buf->bMaxPacketSize0;
2204                        kfree(buf);
2205
2206                        retval = hub_port_reset(hub, port1, udev, delay);
2207                        if (retval < 0)         /* error or disconnect */
2208                                goto fail;
2209                        if (oldspeed != udev->speed) {
2210                                dev_dbg(&udev->dev,
2211                                        "device reset changed speed!\n");
2212                                retval = -ENODEV;
2213                                goto fail;
2214                        }
2215                        if (r) {
2216                                dev_err(&udev->dev, "device descriptor "
2217                                                "read/%s, error %d\n",
2218                                                "64", r);
2219                                retval = -EMSGSIZE;
2220                                continue;
2221                        }
2222#undef GET_DESCRIPTOR_BUFSIZE
2223                }
2224
2225                for (j = 0; j < SET_ADDRESS_TRIES; ++j) {
2226                        retval = hub_set_address(udev);
2227                        if (retval >= 0)
2228                                break;
2229                        msleep(200);
2230                }
2231                if (retval < 0) {
2232                        dev_err(&udev->dev,
2233                                "device not accepting address %d, error %d\n",
2234                                udev->devnum, retval);
2235                        goto fail;
2236                }
2237 
2238                /* cope with hardware quirkiness:
2239                 *  - let SET_ADDRESS settle, some device hardware wants it
2240                 *  - read ep0 maxpacket even for high and low speed,
2241                 */
2242                msleep(10);
2243                if (USE_NEW_SCHEME(retry_counter))
2244                        break;
2245
2246                retval = usb_get_device_descriptor(udev, 8);
2247                if (retval < 8) {
2248                        dev_err(&udev->dev, "device descriptor "
2249                                        "read/%s, error %d\n",
2250                                        "8", retval);
2251                        if (retval >= 0)
2252                                retval = -EMSGSIZE;
2253                } else {
2254                        retval = 0;
2255                        break;
2256                }
2257        }
2258        if (retval)
2259                goto fail;
2260
2261        i = udev->descriptor.bMaxPacketSize0 == 0xff?
2262            512 : udev->descriptor.bMaxPacketSize0;
2263        if (le16_to_cpu(udev->ep0.desc.wMaxPacketSize) != i) {
2264                if (udev->speed != USB_SPEED_FULL ||
2265                                !(i == 8 || i == 16 || i == 32 || i == 64)) {
2266                        dev_err(&udev->dev, "ep0 maxpacket = %d\n", i);
2267                        retval = -EMSGSIZE;
2268                        goto fail;
2269                }
2270                dev_dbg(&udev->dev, "ep0 maxpacket = %d\n", i);
2271                udev->ep0.desc.wMaxPacketSize = cpu_to_le16(i);
2272                ep0_reinit(udev);
2273        }
2274 
2275        retval = usb_get_device_descriptor(udev, USB_DT_DEVICE_SIZE);
2276        if (retval < (signed)sizeof(udev->descriptor)) {
2277                dev_err(&udev->dev, "device descriptor read/%s, error %d\n",
2278                        "all", retval);
2279                if (retval >= 0)
2280                        retval = -ENOMSG;
2281                goto fail;
2282        }
2283
2284        retval = 0;
2285
2286fail:
2287        if (retval)
2288                hub_port_disable(hub, port1, 0);
2289        mutex_unlock(&usb_address0_mutex);
2290        return retval;
2291}
2292
2293static void
2294check_highspeed (struct usb_hub *hub, struct usb_device *udev, int port1)
2295{
2296        struct usb_qualifier_descriptor *qual;
2297        int                             status;
2298
2299        qual = kmalloc (sizeof *qual, GFP_KERNEL);
2300        if (qual == NULL)
2301                return;
2302
2303        status = usb_get_descriptor (udev, USB_DT_DEVICE_QUALIFIER, 0,
2304                        qual, sizeof *qual);
2305        if (status == sizeof *qual) {
2306                dev_info(&udev->dev, "not running at top speed; "
2307                        "connect to a high speed hub\n");
2308                /* hub LEDs are probably harder to miss than syslog */
2309                if (hub->has_indicators) {
2310                        hub->indicator[port1-1] = INDICATOR_GREEN_BLINK;
2311                        schedule_delayed_work (&hub->leds, 0);
2312                }
2313        }
2314        kfree(qual);
2315}
2316
2317static unsigned
2318hub_power_remaining (struct usb_hub *hub)
2319{
2320        struct usb_device *hdev = hub->hdev;
2321        int remaining;
2322        int port1;
2323
2324        if (!hub->limited_power)
2325                return 0;
2326
2327        remaining = hdev->bus_mA - hub->descriptor->bHubContrCurrent;
2328        for (port1 = 1; port1 <= hdev->maxchild; ++port1) {
2329                struct usb_device       *udev = hdev->children[port1 - 1];
2330                int                     delta;
2331
2332                if (!udev)
2333                        continue;
2334
2335                /* Unconfigured devices may not use more than 100mA,
2336                 * or 8mA for OTG ports */
2337                if (udev->actconfig)
2338                        delta = udev->actconfig->desc.bMaxPower * 2;
2339                else if (port1 != udev->bus->otg_port || hdev->parent)
2340                        delta = 100;
2341                else
2342                        delta = 8;
2343                if (delta > hub->mA_per_port)
2344                        dev_warn(&udev->dev, "%dmA is over %umA budget "
2345                                        "for port %d!\n",
2346                                        delta, hub->mA_per_port, port1);
2347                remaining -= delta;
2348        }
2349        if (remaining < 0) {
2350                dev_warn(hub->intfdev, "%dmA over power budget!\n",
2351                        - remaining);
2352                remaining = 0;
2353        }
2354        return remaining;
2355}
2356
2357/* Handle physical or logical connection change events.
2358 * This routine is called when:
2359 *      a port connection-change occurs;
2360 *      a port enable-change occurs (often caused by EMI);
2361 *      usb_reset_device() encounters changed descriptors (as from
2362 *              a firmware download)
2363 * caller already locked the hub
2364 */
2365static void hub_port_connect_change(struct usb_hub *hub, int port1,
2366                                        u16 portstatus, u16 portchange)
2367{
2368        struct usb_device *hdev = hub->hdev;
2369        struct device *hub_dev = hub->intfdev;
2370        u16 wHubCharacteristics = le16_to_cpu(hub->descriptor->wHubCharacteristics);
2371        int status, i;
2372 
2373        dev_dbg (hub_dev,
2374                "port %d, status %04x, change %04x, %s\n",
2375                port1, portstatus, portchange, portspeed (portstatus));
2376
2377        if (hub->has_indicators) {
2378                set_port_led(hub, port1, HUB_LED_AUTO);
2379                hub->indicator[port1-1] = INDICATOR_AUTO;
2380        }
2381 
2382        /* Disconnect any existing devices under this port */
2383        if (hdev->children[port1-1])
2384                usb_disconnect(&hdev->children[port1-1]);
2385        clear_bit(port1, hub->change_bits);
2386
2387#ifdef  CONFIG_USB_OTG
2388        /* during HNP, don't repeat the debounce */
2389        if (hdev->bus->is_b_host)
2390                portchange &= ~USB_PORT_STAT_C_CONNECTION;
2391#endif
2392
2393        if (portchange & USB_PORT_STAT_C_CONNECTION) {
2394                status = hub_port_debounce(hub, port1);
2395                if (status < 0) {
2396                        if (printk_ratelimit())
2397                                dev_err (hub_dev, "connect-debounce failed, "
2398                                                "port %d disabled\n", port1);
2399                        goto done;
2400                }
2401                portstatus = status;
2402        }
2403
2404        /* Return now if nothing is connected */
2405        if (!(portstatus & USB_PORT_STAT_CONNECTION)) {
2406
2407                /* maybe switch power back on (e.g. root hub was reset) */
2408                if ((wHubCharacteristics & HUB_CHAR_LPSM) < 2
2409                                && !(portstatus & (1 << USB_PORT_FEAT_POWER)))
2410                        set_port_feature(hdev, port1, USB_PORT_FEAT_POWER);
2411 
2412                if (portstatus & USB_PORT_STAT_ENABLE)
2413                        goto done;
2414                return;
2415        }
2416
2417        for (i = 0; i < SET_CONFIG_TRIES; i++) {
2418                struct usb_device *udev;
2419
2420                /* reallocate for each attempt, since references
2421                 * to the previous one can escape in various ways
2422                 */
2423                udev = usb_alloc_dev(hdev, hdev->bus, port1);
2424                if (!udev) {
2425                        dev_err (hub_dev,
2426                                "couldn't allocate port %d usb_device\n",
2427                                port1);
2428                        goto done;
2429                }
2430
2431                usb_set_device_state(udev, USB_STATE_POWERED);
2432                udev->speed = USB_SPEED_UNKNOWN;
2433                udev->bus_mA = hub->mA_per_port;
2434                udev->level = hdev->level + 1;
2435
2436                /* set the address */
2437                choose_address(udev);
2438                if (udev->devnum <= 0) {
2439                        status = -ENOTCONN;     /* Don't retry */
2440                        goto loop;
2441                }
2442
2443                /* reset and get descriptor */
2444                status = hub_port_init(hub, udev, port1, i);
2445                if (status < 0)
2446                        goto loop;
2447
2448                /* consecutive bus-powered hubs aren't reliable; they can
2449                 * violate the voltage drop budget.  if the new child has
2450                 * a "powered" LED, users should notice we didn't enable it
2451                 * (without reading syslog), even without per-port LEDs
2452                 * on the parent.
2453                 */
2454                if (udev->descriptor.bDeviceClass == USB_CLASS_HUB
2455                                && udev->bus_mA <= 100) {
2456                        u16     devstat;
2457
2458                        status = usb_get_status(udev, USB_RECIP_DEVICE, 0,
2459                                        &devstat);
2460                        if (status < 2) {
2461                                dev_dbg(&udev->dev, "get status %d ?\n", status);
2462                                goto loop_disable;
2463                        }
2464                        le16_to_cpus(&devstat);
2465                        if ((devstat & (1 << USB_DEVICE_SELF_POWERED)) == 0) {
2466                                dev_err(&udev->dev,
2467                                        "can't connect bus-powered hub "
2468                                        "to this port\n");
2469                                if (hub->has_indicators) {
2470                                        hub->indicator[port1-1] =
2471                                                INDICATOR_AMBER_BLINK;
2472                                        schedule_delayed_work (&hub->leds, 0);
2473                                }
2474                                status = -ENOTCONN;     /* Don't retry */
2475                                goto loop_disable;
2476                        }
2477                }
2478 
2479                /* check for devices running slower than they could */
2480                if (le16_to_cpu(udev->descriptor.bcdUSB) >= 0x0200
2481                                && udev->speed == USB_SPEED_FULL
2482                                && highspeed_hubs != 0)
2483                        check_highspeed (hub, udev, port1);
2484
2485                /* Store the parent's children[] pointer.  At this point
2486                 * udev becomes globally accessible, although presumably
2487                 * no one will look at it until hdev is unlocked.
2488                 */
2489                status = 0;
2490
2491                /* We mustn't add new devices if the parent hub has
2492                 * been disconnected; we would race with the
2493                 * recursively_mark_NOTATTACHED() routine.
2494                 */
2495                spin_lock_irq(&device_state_lock);
2496                if (hdev->state == USB_STATE_NOTATTACHED)
2497                        status = -ENOTCONN;
2498                else
2499                        hdev->children[port1-1] = udev;
2500                spin_unlock_irq(&device_state_lock);
2501
2502                /* Run it through the hoops (find a driver, etc) */
2503                if (!status) {
2504                        status = usb_new_device(udev);
2505                        if (status) {
2506                                spin_lock_irq(&device_state_lock);
2507                                hdev->children[port1-1] = NULL;
2508                                spin_unlock_irq(&device_state_lock);
2509                        }
2510                }
2511
2512                if (status)
2513                        goto loop_disable;
2514
2515                status = hub_power_remaining(hub);
2516                if (status)
2517                        dev_dbg(hub_dev, "%dmA power budget left\n", status);
2518
2519                return;
2520
2521loop_disable:
2522                hub_port_disable(hub, port1, 1);
2523loop:
2524                ep0_reinit(udev);
2525                release_address(udev);
2526                usb_put_dev(udev);
2527                if ((status == -ENOTCONN) || (status == -ENOTSUPP))
2528                        break;
2529        }
2530 
2531done:
2532        hub_port_disable(hub, port1, 1);
2533}
2534
2535static void hub_events(void)
2536{
2537        struct list_head *tmp;
2538        struct usb_device *hdev;
2539        struct usb_interface *intf;
2540        struct usb_hub *hub;
2541        struct device *hub_dev;
2542        u16 hubstatus;
2543        u16 hubchange;
2544        u16 portstatus;
2545        u16 portchange;
2546        int i, ret;
2547        int connect_change;
2548
2549        /*
2550         *  We restart the list every time to avoid a deadlock with
2551         * deleting hubs downstream from this one. This should be
2552         * safe since we delete the hub from the event list.
2553         * Not the most efficient, but avoids deadlocks.
2554         */
2555        while (1) {
2556
2557                /* Grab the first entry at the beginning of the list */
2558                spin_lock_irq(&hub_event_lock);
2559                if (list_empty(&hub_event_list)) {
2560                        spin_unlock_irq(&hub_event_lock);
2561                        break;
2562                }
2563
2564                tmp = hub_event_list.next;
2565                list_del_init(tmp);
2566
2567                hub = list_entry(tmp, struct usb_hub, event_list);
2568                kref_get(&hub->kref);
2569                spin_unlock_irq(&hub_event_lock);
2570
2571                hdev = hub->hdev;
2572                hub_dev = hub->intfdev;
2573                intf = to_usb_interface(hub_dev);
2574                dev_dbg(hub_dev, "state %d ports %d chg %04x evt %04x\n",
2575                                hdev->state, hub->descriptor
2576                                        ? hub->descriptor->bNbrPorts
2577                                        : 0,
2578                                /* NOTE: expects max 15 ports... */
2579                                (u16) hub->change_bits[0],
2580                                (u16) hub->event_bits[0]);
2581
2582                /* Lock the device, then check to see if we were
2583                 * disconnected while waiting for the lock to succeed. */
2584                usb_lock_device(hdev);
2585                if (unlikely(hub->disconnected))
2586                        goto loop;
2587
2588                /* If the hub has died, clean up after it */
2589                if (hdev->state == USB_STATE_NOTATTACHED) {
2590                        hub->error = -ENODEV;
2591                        hub_pre_reset(intf);
2592                        goto loop;
2593                }
2594
2595                /* Autoresume */
2596                ret = usb_autopm_get_interface(intf);
2597                if (ret) {
2598                        dev_dbg(hub_dev, "Can't autoresume: %d\n", ret);
2599                        goto loop;
2600                }
2601
2602                /* If this is an inactive hub, do nothing */
2603                if (hub->quiescing)
2604                        goto loop_autopm;
2605
2606                if (hub->error) {
2607                        dev_dbg (hub_dev, "resetting for error %d\n",
2608                                hub->error);
2609
2610                        ret = usb_reset_composite_device(hdev, intf);
2611                        if (ret) {
2612                                dev_dbg (hub_dev,
2613                                        "error resetting hub: %d\n", ret);
2614                                goto loop_autopm;
2615                        }
2616
2617                        hub->nerrors = 0;
2618                        hub->error = 0;
2619                }
2620
2621                /* deal with port status changes */
2622                for (i = 1; i <= hub->descriptor->bNbrPorts; i++) {
2623                        if (test_bit(i, hub->busy_bits))
2624                                continue;
2625                        connect_change = test_bit(i, hub->change_bits);
2626                        if (!test_and_clear_bit(i, hub->event_bits) &&
2627                                        !connect_change && !hub->activating)
2628                                continue;
2629
2630                        ret = hub_port_status(hub, i,
2631                                        &portstatus, &portchange);
2632                        if (ret < 0)
2633                                continue;
2634
2635                        if (hub->activating && !hdev->children[i-1] &&
2636                                        (portstatus &
2637                                                USB_PORT_STAT_CONNECTION))
2638                                connect_change = 1;
2639
2640                        if (portchange & USB_PORT_STAT_C_CONNECTION) {
2641                                clear_port_feature(hdev, i,
2642                                        USB_PORT_FEAT_C_CONNECTION);
2643                                connect_change = 1;
2644                        }
2645
2646                        if (portchange & USB_PORT_STAT_C_ENABLE) {
2647                                if (!connect_change)
2648                                        dev_dbg (hub_dev,
2649                                                "port %d enable change, "
2650                                                "status %08x\n",
2651                                                i, portstatus);
2652                                clear_port_feature(hdev, i,
2653                                        USB_PORT_FEAT_C_ENABLE);
2654
2655                                /*
2656                                 * EM interference sometimes causes badly
2657                                 * shielded USB devices to be shutdown by
2658                                 * the hub, this hack enables them again.
2659                                 * Works at least with mouse driver.
2660                                 */
2661                                if (!(portstatus & USB_PORT_STAT_ENABLE)
2662                                    && !connect_change
2663                                    && hdev->children[i-1]) {
2664                                        dev_err (hub_dev,
2665                                            "port %i "
2666                                            "disabled by hub (EMI?), "
2667                                            "re-enabling...\n",
2668                                                i);
2669                                        connect_change = 1;
2670                                }
2671                        }
2672
2673                        if (portchange & USB_PORT_STAT_C_SUSPEND) {
2674                                clear_port_feature(hdev, i,
2675                                        USB_PORT_FEAT_C_SUSPEND);
2676                                if (hdev->children[i-1]) {
2677                                        ret = remote_wakeup(hdev->
2678                                                        children[i-1]);
2679                                        if (ret < 0)
2680                                                connect_change = 1;
2681                                } else {
2682                                        ret = -ENODEV;
2683                                        hub_port_disable(hub, i, 1);
2684                                }
2685                                dev_dbg (hub_dev,
2686                                        "resume on port %d, status %d\n",
2687                                        i, ret);
2688                        }
2689                       
2690                        if (portchange & USB_PORT_STAT_C_OVERCURRENT) {
2691                                dev_err (hub_dev,
2692                                        "over-current change on port %d\n",
2693                                        i);
2694                                clear_port_feature(hdev, i,
2695                                        USB_PORT_FEAT_C_OVER_CURRENT);
2696                                hub_power_on(hub);
2697                        }
2698
2699                        if (portchange & USB_PORT_STAT_C_RESET) {
2700                                dev_dbg (hub_dev,
2701                                        "reset change on port %d\n",
2702                                        i);
2703                                clear_port_feature(hdev, i,
2704                                        USB_PORT_FEAT_C_RESET);
2705                        }
2706
2707                        if (connect_change)
2708                                hub_port_connect_change(hub, i,
2709                                                portstatus, portchange);
2710                } /* end for i */
2711
2712                /* deal with hub status changes */
2713                if (test_and_clear_bit(0, hub->event_bits) == 0)
2714                        ;       /* do nothing */
2715                else if (hub_hub_status(hub, &hubstatus, &hubchange) < 0)
2716                        dev_err (hub_dev, "get_hub_status failed\n");
2717                else {
2718                        if (hubchange & HUB_CHANGE_LOCAL_POWER) {
2719                                dev_dbg (hub_dev, "power change\n");
2720                                clear_hub_feature(hdev, C_HUB_LOCAL_POWER);
2721                                if (hubstatus & HUB_STATUS_LOCAL_POWER)
2722                                        /* FIXME: Is this always true? */
2723                                        hub->limited_power = 0;
2724                                else
2725                                        hub->limited_power = 1;
2726                        }
2727                        if (hubchange & HUB_CHANGE_OVERCURRENT) {
2728                                dev_dbg (hub_dev, "overcurrent change\n");
2729                                msleep(500);    /* Cool down */
2730                                clear_hub_feature(hdev, C_HUB_OVER_CURRENT);
2731                                hub_power_on(hub);
2732                        }
2733                }
2734
2735                hub->activating = 0;
2736
2737                /* If this is a root hub, tell the HCD it's okay to
2738                 * re-enable port-change interrupts now. */
2739                if (!hdev->parent && !hub->busy_bits[0])
2740                        usb_enable_root_hub_irq(hdev->bus);
2741
2742loop_autopm:
2743                /* Allow autosuspend if we're not going to run again */
2744                if (list_empty(&hub->event_list))
2745                        usb_autopm_enable(intf);
2746loop:
2747                usb_unlock_device(hdev);
2748                kref_put(&hub->kref, hub_release);
2749
2750        } /* end while (1) */
2751}
2752
2753static int hub_thread(void *__unused)
2754{
2755        set_freezable();
2756        do {
2757                hub_events();
2758                wait_event_interruptible(khubd_wait,
2759                                !list_empty(&hub_event_list) ||
2760                                kthread_should_stop());
2761                try_to_freeze();
2762        } while (!kthread_should_stop() || !list_empty(&hub_event_list));
2763
2764        pr_debug("%s: khubd exiting\n", usbcore_name);
2765        return 0;
2766}
2767
2768static struct usb_device_id hub_id_table [] = {
2769    { .match_flags = USB_DEVICE_ID_MATCH_DEV_CLASS,
2770      .bDeviceClass = USB_CLASS_HUB},
2771    { .match_flags = USB_DEVICE_ID_MATCH_INT_CLASS,
2772      .bInterfaceClass = USB_CLASS_HUB},
2773    { }                                         /* Terminating entry */
2774};
2775
2776MODULE_DEVICE_TABLE (usb, hub_id_table);
2777
2778static struct usb_driver hub_driver = {
2779        .name =         "hub",
2780        .probe =        hub_probe,
2781        .disconnect =   hub_disconnect,
2782        .suspend =      hub_suspend,
2783        .resume =       hub_resume,
2784        .reset_resume = hub_reset_resume,
2785        .pre_reset =    hub_pre_reset,
2786        .post_reset =   hub_post_reset,
2787        .ioctl =        hub_ioctl,
2788        .id_table =     hub_id_table,
2789        .supports_autosuspend = 1,
2790};
2791
2792int usb_hub_init(void)
2793{
2794        if (usb_register(&hub_driver) < 0) {
2795                printk(KERN_ERR "%s: can't register hub driver\n",
2796                        usbcore_name);
2797                return -1;
2798        }
2799
2800        khubd_task = kthread_run(hub_thread, NULL, "khubd");
2801        if (!IS_ERR(khubd_task))
2802                return 0;
2803
2804        /* Fall through if kernel_thread failed */
2805        usb_deregister(&hub_driver);
2806        printk(KERN_ERR "%s: can't start khubd\n", usbcore_name);
2807
2808        return -1;
2809}
2810
2811void usb_hub_cleanup(void)
2812{
2813        kthread_stop(khubd_task);
2814
2815        /*
2816         * Hub resources are freed for us by usb_deregister. It calls
2817         * usb_driver_purge on every device which in turn calls that
2818         * devices disconnect function if it is using this driver.
2819         * The hub_disconnect function takes care of releasing the
2820         * individual hub resources. -greg
2821         */
2822        usb_deregister(&hub_driver);
2823} /* usb_hub_cleanup() */
2824
2825static int config_descriptors_changed(struct usb_device *udev)
2826{
2827        unsigned                        index;
2828        unsigned                        len = 0;
2829        struct usb_config_descriptor    *buf;
2830
2831        for (index = 0; index < udev->descriptor.bNumConfigurations; index++) {
2832                if (len < le16_to_cpu(udev->config[index].desc.wTotalLength))
2833                        len = le16_to_cpu(udev->config[index].desc.wTotalLength);
2834        }
2835        buf = kmalloc (len, GFP_KERNEL);
2836        if (buf == NULL) {
2837                dev_err(&udev->dev, "no mem to re-read configs after reset\n");
2838                /* assume the worst */
2839                return 1;
2840        }
2841        for (index = 0; index < udev->descriptor.bNumConfigurations; index++) {
2842                int length;
2843                int old_length = le16_to_cpu(udev->config[index].desc.wTotalLength);
2844
2845                length = usb_get_descriptor(udev, USB_DT_CONFIG, index, buf,
2846                                old_length);
2847                if (length < old_length) {
2848                        dev_dbg(&udev->dev, "config index %d, error %d\n",
2849                                        index, length);
2850                        break;
2851                }
2852                if (memcmp (buf, udev->rawdescriptors[index], old_length)
2853                                != 0) {
2854                        dev_dbg(&udev->dev, "config index %d changed (#%d)\n",
2855                                index, buf->bConfigurationValue);
2856                        break;
2857                }
2858        }
2859        kfree(buf);
2860        return index != udev->descriptor.bNumConfigurations;
2861}
2862
2863/**
2864 * usb_reset_device - perform a USB port reset to reinitialize a device
2865 * @udev: device to reset (not in SUSPENDED or NOTATTACHED state)
2866 *
2867 * WARNING - don't use this routine to reset a composite device
2868 * (one with multiple interfaces owned by separate drivers)!
2869 * Use usb_reset_composite_device() instead.
2870 *
2871 * Do a port reset, reassign the device's address, and establish its
2872 * former operating configuration.  If the reset fails, or the device's
2873 * descriptors change from their values before the reset, or the original
2874 * configuration and altsettings cannot be restored, a flag will be set
2875 * telling khubd to pretend the device has been disconnected and then
2876 * re-connected.  All drivers will be unbound, and the device will be
2877 * re-enumerated and probed all over again.
2878 *
2879 * Returns 0 if the reset succeeded, -ENODEV if the device has been
2880 * flagged for logical disconnection, or some other negative error code
2881 * if the reset wasn't even attempted.
2882 *
2883 * The caller must own the device lock.  For example, it's safe to use
2884 * this from a driver probe() routine after downloading new firmware.
2885 * For calls that might not occur during probe(), drivers should lock
2886 * the device using usb_lock_device_for_reset().
2887 *
2888 * Locking exception: This routine may also be called from within an
2889 * autoresume handler.  Such usage won't conflict with other tasks
2890 * holding the device lock because these tasks should always call
2891 * usb_autopm_resume_device(), thereby preventing any unwanted autoresume.
2892 */
2893int usb_reset_device(struct usb_device *udev)
2894{
2895        struct usb_device               *parent_hdev = udev->parent;
2896        struct usb_hub                  *parent_hub;
2897        struct usb_device_descriptor    descriptor = udev->descriptor;
2898        int                             i, ret = 0;
2899        int                             port1 = udev->portnum;
2900
2901        if (udev->state == USB_STATE_NOTATTACHED ||
2902                        udev->state == USB_STATE_SUSPENDED) {
2903                dev_dbg(&udev->dev, "device reset not allowed in state %d\n",
2904                                udev->state);
2905                return -EINVAL;
2906        }
2907
2908        if (!parent_hdev) {
2909                /* this requires hcd-specific logic; see OHCI hc_restart() */
2910                dev_dbg(&udev->dev, "%s for root hub!\n", __FUNCTION__);
2911                return -EISDIR;
2912        }
2913        parent_hub = hdev_to_hub(parent_hdev);
2914
2915        set_bit(port1, parent_hub->busy_bits);
2916        for (i = 0; i < SET_CONFIG_TRIES; ++i) {
2917
2918                /* ep0 maxpacket size may change; let the HCD know about it.
2919                 * Other endpoints will be handled by re-enumeration. */
2920                ep0_reinit(udev);
2921                ret = hub_port_init(parent_hub, udev, port1, i);
2922                if (ret >= 0 || ret == -ENOTCONN || ret == -ENODEV)
2923                        break;
2924        }
2925        clear_bit(port1, parent_hub->busy_bits);
2926        if (!parent_hdev->parent && !parent_hub->busy_bits[0])
2927                usb_enable_root_hub_irq(parent_hdev->bus);
2928
2929        if (ret < 0)
2930                goto re_enumerate;
2931 
2932        /* Device might have changed firmware (DFU or similar) */
2933        if (memcmp(&udev->descriptor, &descriptor, sizeof descriptor)
2934                        || config_descriptors_changed (udev)) {
2935                dev_info(&udev->dev, "device firmware changed\n");
2936                udev->descriptor = descriptor;  /* for disconnect() calls */
2937                goto re_enumerate;
2938        }
2939 
2940        if (!udev->actconfig)
2941                goto done;
2942
2943        ret = usb_control_msg(udev, usb_sndctrlpipe(udev, 0),
2944                        USB_REQ_SET_CONFIGURATION, 0,
2945                        udev->actconfig->desc.bConfigurationValue, 0,
2946                        NULL, 0, USB_CTRL_SET_TIMEOUT);
2947        if (ret < 0) {
2948                dev_err(&udev->dev,
2949                        "can't restore configuration #%d (error=%d)\n",
2950                        udev->actconfig->desc.bConfigurationValue, ret);
2951                goto re_enumerate;
2952        }
2953        usb_set_device_state(udev, USB_STATE_CONFIGURED);
2954
2955        for (i = 0; i < udev->actconfig->desc.bNumInterfaces; i++) {
2956                struct usb_interface *intf = udev->actconfig->interface[i];
2957                struct usb_interface_descriptor *desc;
2958
2959                /* set_interface resets host side toggle even
2960                 * for altsetting zero.  the interface may have no driver.
2961                 */
2962                desc = &intf->cur_altsetting->desc;
2963                ret = usb_set_interface(udev, desc->bInterfaceNumber,
2964                        desc->bAlternateSetting);
2965                if (ret < 0) {
2966                        dev_err(&udev->dev, "failed to restore interface %d "
2967                                "altsetting %d (error=%d)\n",
2968                                desc->bInterfaceNumber,
2969                                desc->bAlternateSetting,
2970                                ret);
2971                        goto re_enumerate;
2972                }
2973        }
2974
2975done:
2976        return 0;
2977 
2978re_enumerate:
2979        hub_port_logical_disconnect(parent_hub, port1);
2980        return -ENODEV;
2981}
2982EXPORT_SYMBOL(usb_reset_device);
2983
2984/**
2985 * usb_reset_composite_device - warn interface drivers and perform a USB port reset
2986 * @udev: device to reset (not in SUSPENDED or NOTATTACHED state)
2987 * @iface: interface bound to the driver making the request (optional)
2988 *
2989 * Warns all drivers bound to registered interfaces (using their pre_reset
2990 * method), performs the port reset, and then lets the drivers know that
2991 * the reset is over (using their post_reset method).
2992 *
2993 * Return value is the same as for usb_reset_device().
2994 *
2995 * The caller must own the device lock.  For example, it's safe to use
2996 * this from a driver probe() routine after downloading new firmware.
2997 * For calls that might not occur during probe(), drivers should lock
2998 * the device using usb_lock_device_for_reset().
2999 *
3000 * The interface locks are acquired during the pre_reset stage and released
3001 * during the post_reset stage.  However if iface is not NULL and is
3002 * currently being probed, we assume that the caller already owns its
3003 * lock.
3004 */
3005int usb_reset_composite_device(struct usb_device *udev,
3006                struct usb_interface *iface)
3007{
3008        int ret;
3009        struct usb_host_config *config = udev->actconfig;
3010
3011        if (udev->state == USB_STATE_NOTATTACHED ||
3012                        udev->state == USB_STATE_SUSPENDED) {
3013                dev_dbg(&udev->dev, "device reset not allowed in state %d\n",
3014                                udev->state);
3015                return -EINVAL;
3016        }
3017
3018        /* Prevent autosuspend during the reset */
3019        usb_autoresume_device(udev);
3020
3021        if (iface && iface->condition != USB_INTERFACE_BINDING)
3022                iface = NULL;
3023
3024        if (config) {
3025                int i;
3026                struct usb_interface *cintf;
3027                struct usb_driver *drv;
3028
3029                for (i = 0; i < config->desc.bNumInterfaces; ++i) {
3030                        cintf = config->interface[i];
3031                        if (cintf != iface)
3032                                down(&cintf->dev.sem);
3033                        if (device_is_registered(&cintf->dev) &&
3034                                        cintf->dev.driver) {
3035                                drv = to_usb_driver(cintf->dev.driver);
3036                                if (drv->pre_reset)
3037                                        (drv->pre_reset)(cintf);
3038        /* FIXME: Unbind if pre_reset returns an error or isn't defined */
3039                        }
3040                }
3041        }
3042
3043        ret = usb_reset_device(udev);
3044
3045        if (config) {
3046                int i;
3047                struct usb_interface *cintf;
3048                struct usb_driver *drv;
3049
3050                for (i = config->desc.bNumInterfaces - 1; i >= 0; --i) {
3051                        cintf = config->interface[i];
3052                        if (device_is_registered(&cintf->dev) &&
3053                                        cintf->dev.driver) {
3054                                drv = to_usb_driver(cintf->dev.driver);
3055                                if (drv->post_reset)
3056                                        (drv->post_reset)(cintf);
3057        /* FIXME: Unbind if post_reset returns an error or isn't defined */
3058                        }
3059                        if (cintf != iface)
3060                                up(&cintf->dev.sem);
3061                }
3062        }
3063
3064        usb_autosuspend_device(udev);
3065        return ret;
3066}
3067EXPORT_SYMBOL(usb_reset_composite_device);
Note: See TracBrowser for help on using the repository browser.