root/src/linux/rt2880/linux-2.6.23/drivers/usb/core/hub.c

Revision 12433, 84.7 kB (checked in by BrainSlayer, 5 months ago)

fixes usb issues with some devices

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