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