patch-2_6_7-vs1_9_1_12
[linux-2.6.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 #include <linux/kernel.h>
13 #include <linux/errno.h>
14 #include <linux/module.h>
15 #include <linux/moduleparam.h>
16 #include <linux/completion.h>
17 #include <linux/sched.h>
18 #include <linux/list.h>
19 #include <linux/slab.h>
20 #include <linux/smp_lock.h>
21 #include <linux/ioctl.h>
22 #ifdef CONFIG_USB_DEBUG
23         #define DEBUG
24 #else
25         #undef DEBUG
26 #endif
27 #include <linux/usb.h>
28 #include <linux/usbdevice_fs.h>
29 #include <linux/suspend.h>
30
31 #include <asm/semaphore.h>
32 #include <asm/uaccess.h>
33 #include <asm/byteorder.h>
34
35 #include "usb.h"
36 #include "hcd.h"
37 #include "hub.h"
38
39 /* Wakes up khubd */
40 static spinlock_t hub_event_lock = SPIN_LOCK_UNLOCKED;
41
42 static LIST_HEAD(hub_event_list);       /* List of hubs needing servicing */
43 static LIST_HEAD(hub_list);             /* List of all hubs (for cleanup) */
44
45 static DECLARE_WAIT_QUEUE_HEAD(khubd_wait);
46 static pid_t khubd_pid = 0;                     /* PID of khubd */
47 static DECLARE_COMPLETION(khubd_exited);
48
49 /* cycle leds on hubs that aren't blinking for attention */
50 static int blinkenlights = 0;
51 module_param (blinkenlights, bool, S_IRUGO);
52 MODULE_PARM_DESC (blinkenlights, "true to cycle leds on hubs");
53
54
55 #ifdef  DEBUG
56 static inline char *portspeed (int portstatus)
57 {
58         if (portstatus & (1 << USB_PORT_FEAT_HIGHSPEED))
59                 return "480 Mb/s";
60         else if (portstatus & (1 << USB_PORT_FEAT_LOWSPEED))
61                 return "1.5 Mb/s";
62         else
63                 return "12 Mb/s";
64 }
65 #endif
66
67 /* for dev_info, dev_dbg, etc */
68 static inline struct device *hubdev (struct usb_device *hdev)
69 {
70         return &hdev->actconfig->interface[0]->dev;
71 }
72
73 /* USB 2.0 spec Section 11.24.4.5 */
74 static int get_hub_descriptor(struct usb_device *hdev, void *data, int size)
75 {
76         return usb_control_msg(hdev, usb_rcvctrlpipe(hdev, 0),
77                 USB_REQ_GET_DESCRIPTOR, USB_DIR_IN | USB_RT_HUB,
78                 USB_DT_HUB << 8, 0, data, size, HZ * USB_CTRL_GET_TIMEOUT);
79 }
80
81 /*
82  * USB 2.0 spec Section 11.24.2.1
83  */
84 static int clear_hub_feature(struct usb_device *hdev, int feature)
85 {
86         return usb_control_msg(hdev, usb_sndctrlpipe(hdev, 0),
87                 USB_REQ_CLEAR_FEATURE, USB_RT_HUB, feature, 0, NULL, 0, HZ);
88 }
89
90 /*
91  * USB 2.0 spec Section 11.24.2.2
92  */
93 static int clear_port_feature(struct usb_device *hdev, int port, int feature)
94 {
95         return usb_control_msg(hdev, usb_sndctrlpipe(hdev, 0),
96                 USB_REQ_CLEAR_FEATURE, USB_RT_PORT, feature, port, NULL, 0, HZ);
97 }
98
99 /*
100  * USB 2.0 spec Section 11.24.2.13
101  */
102 static int set_port_feature(struct usb_device *hdev, int port, int feature)
103 {
104         return usb_control_msg(hdev, usb_sndctrlpipe(hdev, 0),
105                 USB_REQ_SET_FEATURE, USB_RT_PORT, feature, port, NULL, 0, HZ);
106 }
107
108 /*
109  * USB 2.0 spec Section 11.24.2.7.1.10 and table 11-7
110  * for info about using port indicators
111  */
112 static void set_port_led(
113         struct usb_device *hdev,
114         int port,
115         int selector
116 )
117 {
118         int status = set_port_feature(hdev, (selector << 8) | port,
119                         USB_PORT_FEAT_INDICATOR);
120         if (status < 0)
121                 dev_dbg (hubdev (hdev),
122                         "port %d indicator %s status %d\n",
123                         port,
124                         ({ char *s; switch (selector) {
125                         case HUB_LED_AMBER: s = "amber"; break;
126                         case HUB_LED_GREEN: s = "green"; break;
127                         case HUB_LED_OFF: s = "off"; break;
128                         case HUB_LED_AUTO: s = "auto"; break;
129                         default: s = "??"; break;
130                         }; s; }),
131                         status);
132 }
133
134 #define LED_CYCLE_PERIOD        ((2*HZ)/3)
135
136 static void led_work (void *__hub)
137 {
138         struct usb_hub          *hub = __hub;
139         struct usb_device       *hdev = interface_to_usbdev (hub->intf);
140         unsigned                i;
141         unsigned                changed = 0;
142         int                     cursor = -1;
143
144         if (hdev->state != USB_STATE_CONFIGURED)
145                 return;
146
147         for (i = 0; i < hub->descriptor->bNbrPorts; i++) {
148                 unsigned        selector, mode;
149
150                 /* 30%-50% duty cycle */
151
152                 switch (hub->indicator[i]) {
153                 /* cycle marker */
154                 case INDICATOR_CYCLE:
155                         cursor = i;
156                         selector = HUB_LED_AUTO;
157                         mode = INDICATOR_AUTO;
158                         break;
159                 /* blinking green = sw attention */
160                 case INDICATOR_GREEN_BLINK:
161                         selector = HUB_LED_GREEN;
162                         mode = INDICATOR_GREEN_BLINK_OFF;
163                         break;
164                 case INDICATOR_GREEN_BLINK_OFF:
165                         selector = HUB_LED_OFF;
166                         mode = INDICATOR_GREEN_BLINK;
167                         break;
168                 /* blinking amber = hw attention */
169                 case INDICATOR_AMBER_BLINK:
170                         selector = HUB_LED_AMBER;
171                         mode = INDICATOR_AMBER_BLINK_OFF;
172                         break;
173                 case INDICATOR_AMBER_BLINK_OFF:
174                         selector = HUB_LED_OFF;
175                         mode = INDICATOR_AMBER_BLINK;
176                         break;
177                 /* blink green/amber = reserved */
178                 case INDICATOR_ALT_BLINK:
179                         selector = HUB_LED_GREEN;
180                         mode = INDICATOR_ALT_BLINK_OFF;
181                         break;
182                 case INDICATOR_ALT_BLINK_OFF:
183                         selector = HUB_LED_AMBER;
184                         mode = INDICATOR_ALT_BLINK;
185                         break;
186                 default:
187                         continue;
188                 }
189                 if (selector != HUB_LED_AUTO)
190                         changed = 1;
191                 set_port_led(hdev, i + 1, selector);
192                 hub->indicator[i] = mode;
193         }
194         if (!changed && blinkenlights) {
195                 cursor++;
196                 cursor %= hub->descriptor->bNbrPorts;
197                 set_port_led(hdev, cursor + 1, HUB_LED_GREEN);
198                 hub->indicator[cursor] = INDICATOR_CYCLE;
199                 changed++;
200         }
201         if (changed)
202                 schedule_delayed_work(&hub->leds, LED_CYCLE_PERIOD);
203 }
204
205 /*
206  * USB 2.0 spec Section 11.24.2.6
207  */
208 static int get_hub_status(struct usb_device *hdev,
209                 struct usb_hub_status *data)
210 {
211         return usb_control_msg(hdev, usb_rcvctrlpipe(hdev, 0),
212                 USB_REQ_GET_STATUS, USB_DIR_IN | USB_RT_HUB, 0, 0,
213                 data, sizeof(*data), HZ * USB_CTRL_GET_TIMEOUT);
214 }
215
216 /*
217  * USB 2.0 spec Section 11.24.2.7
218  */
219 static int get_port_status(struct usb_device *hdev, int port,
220                 struct usb_port_status *data)
221 {
222         return usb_control_msg(hdev, usb_rcvctrlpipe(hdev, 0),
223                 USB_REQ_GET_STATUS, USB_DIR_IN | USB_RT_PORT, 0, port,
224                 data, sizeof(*data), HZ * USB_CTRL_GET_TIMEOUT);
225 }
226
227 /* completion function, fires on port status changes and various faults */
228 static void hub_irq(struct urb *urb, struct pt_regs *regs)
229 {
230         struct usb_hub *hub = (struct usb_hub *)urb->context;
231         int status;
232
233         spin_lock(&hub_event_lock);
234         hub->urb_active = 0;
235         if (hub->urb_complete) {        /* disconnect or rmmod */
236                 complete(hub->urb_complete);
237                 goto done;
238         }
239
240         switch (urb->status) {
241         case -ENOENT:           /* synchronous unlink */
242         case -ECONNRESET:       /* async unlink */
243         case -ESHUTDOWN:        /* hardware going away */
244                 goto done;
245
246         default:                /* presumably an error */
247                 /* Cause a hub reset after 10 consecutive errors */
248                 dev_dbg (&hub->intf->dev, "transfer --> %d\n", urb->status);
249                 if ((++hub->nerrors < 10) || hub->error)
250                         goto resubmit;
251                 hub->error = urb->status;
252                 /* FALL THROUGH */
253         
254         /* let khubd handle things */
255         case 0:                 /* we got data:  port status changed */
256                 break;
257         }
258
259         hub->nerrors = 0;
260
261         /* Something happened, let khubd figure it out */
262         if (list_empty(&hub->event_list)) {
263                 list_add(&hub->event_list, &hub_event_list);
264                 wake_up(&khubd_wait);
265         }
266
267 resubmit:
268         if ((status = usb_submit_urb (hub->urb, GFP_ATOMIC)) != 0
269                         /* ENODEV means we raced disconnect() */
270                         && status != -ENODEV)
271                 dev_err (&hub->intf->dev, "resubmit --> %d\n", urb->status);
272         if (status == 0)
273                 hub->urb_active = 1;
274 done:
275         spin_unlock(&hub_event_lock);
276 }
277
278 /* USB 2.0 spec Section 11.24.2.3 */
279 static inline int
280 hub_clear_tt_buffer (struct usb_device *hdev, u16 devinfo, u16 tt)
281 {
282         return usb_control_msg (hdev, usb_rcvctrlpipe (hdev, 0),
283                 HUB_CLEAR_TT_BUFFER, USB_RT_PORT,
284                 devinfo, tt, 0, 0, HZ);
285 }
286
287 /*
288  * enumeration blocks khubd for a long time. we use keventd instead, since
289  * long blocking there is the exception, not the rule.  accordingly, HCDs
290  * talking to TTs must queue control transfers (not just bulk and iso), so
291  * both can talk to the same hub concurrently.
292  */
293 static void hub_tt_kevent (void *arg)
294 {
295         struct usb_hub          *hub = arg;
296         unsigned long           flags;
297
298         spin_lock_irqsave (&hub->tt.lock, flags);
299         while (!list_empty (&hub->tt.clear_list)) {
300                 struct list_head        *temp;
301                 struct usb_tt_clear     *clear;
302                 struct usb_device       *hdev;
303                 int                     status;
304
305                 temp = hub->tt.clear_list.next;
306                 clear = list_entry (temp, struct usb_tt_clear, clear_list);
307                 list_del (&clear->clear_list);
308
309                 /* drop lock so HCD can concurrently report other TT errors */
310                 spin_unlock_irqrestore (&hub->tt.lock, flags);
311                 hdev = interface_to_usbdev (hub->intf);
312                 status = hub_clear_tt_buffer (hdev, clear->devinfo, clear->tt);
313                 spin_lock_irqsave (&hub->tt.lock, flags);
314
315                 if (status)
316                         dev_err (&hdev->dev,
317                                 "clear tt %d (%04x) error %d\n",
318                                 clear->tt, clear->devinfo, status);
319                 kfree (clear);
320         }
321         spin_unlock_irqrestore (&hub->tt.lock, flags);
322 }
323
324 /**
325  * usb_hub_tt_clear_buffer - clear control/bulk TT state in high speed hub
326  * @dev: the device whose split transaction failed
327  * @pipe: identifies the endpoint of the failed transaction
328  *
329  * High speed HCDs use this to tell the hub driver that some split control or
330  * bulk transaction failed in a way that requires clearing internal state of
331  * a transaction translator.  This is normally detected (and reported) from
332  * interrupt context.
333  *
334  * It may not be possible for that hub to handle additional full (or low)
335  * speed transactions until that state is fully cleared out.
336  */
337 void usb_hub_tt_clear_buffer (struct usb_device *udev, int pipe)
338 {
339         struct usb_tt           *tt = udev->tt;
340         unsigned long           flags;
341         struct usb_tt_clear     *clear;
342
343         /* we've got to cope with an arbitrary number of pending TT clears,
344          * since each TT has "at least two" buffers that can need it (and
345          * there can be many TTs per hub).  even if they're uncommon.
346          */
347         if ((clear = kmalloc (sizeof *clear, SLAB_ATOMIC)) == 0) {
348                 dev_err (&udev->dev, "can't save CLEAR_TT_BUFFER state\n");
349                 /* FIXME recover somehow ... RESET_TT? */
350                 return;
351         }
352
353         /* info that CLEAR_TT_BUFFER needs */
354         clear->tt = tt->multi ? udev->ttport : 1;
355         clear->devinfo = usb_pipeendpoint (pipe);
356         clear->devinfo |= udev->devnum << 4;
357         clear->devinfo |= usb_pipecontrol (pipe)
358                         ? (USB_ENDPOINT_XFER_CONTROL << 11)
359                         : (USB_ENDPOINT_XFER_BULK << 11);
360         if (usb_pipein (pipe))
361                 clear->devinfo |= 1 << 15;
362         
363         /* tell keventd to clear state for this TT */
364         spin_lock_irqsave (&tt->lock, flags);
365         list_add_tail (&clear->clear_list, &tt->clear_list);
366         schedule_work (&tt->kevent);
367         spin_unlock_irqrestore (&tt->lock, flags);
368 }
369
370 static void hub_power_on(struct usb_hub *hub)
371 {
372         struct usb_device *hdev;
373         int i;
374
375         /* if hub supports power switching, enable power on each port */
376         if ((hub->descriptor->wHubCharacteristics & HUB_CHAR_LPSM) < 2) {
377                 dev_dbg(&hub->intf->dev, "enabling power on all ports\n");
378                 hdev = interface_to_usbdev(hub->intf);
379                 for (i = 0; i < hub->descriptor->bNbrPorts; i++)
380                         set_port_feature(hdev, i + 1, USB_PORT_FEAT_POWER);
381         }
382
383         /* Wait for power to be enabled */
384         msleep(hub->descriptor->bPwrOn2PwrGood * 2);
385 }
386
387 static int hub_hub_status(struct usb_hub *hub,
388                 u16 *status, u16 *change)
389 {
390         struct usb_device *hdev = interface_to_usbdev (hub->intf);
391         int ret;
392
393         ret = get_hub_status(hdev, &hub->status->hub);
394         if (ret < 0)
395                 dev_err (&hub->intf->dev,
396                         "%s failed (err = %d)\n", __FUNCTION__, ret);
397         else {
398                 *status = le16_to_cpu(hub->status->hub.wHubStatus);
399                 *change = le16_to_cpu(hub->status->hub.wHubChange); 
400                 ret = 0;
401         }
402         return ret;
403 }
404
405 static int hub_configure(struct usb_hub *hub,
406         struct usb_endpoint_descriptor *endpoint)
407 {
408         struct usb_device *hdev = interface_to_usbdev (hub->intf);
409         struct device *hub_dev = &hub->intf->dev;
410         u16 hubstatus, hubchange;
411         unsigned int pipe;
412         int maxp, ret;
413         char *message;
414
415         hub->buffer = usb_buffer_alloc(hdev, sizeof(*hub->buffer), GFP_KERNEL,
416                         &hub->buffer_dma);
417         if (!hub->buffer) {
418                 message = "can't allocate hub irq buffer";
419                 ret = -ENOMEM;
420                 goto fail;
421         }
422
423         hub->status = kmalloc(sizeof(*hub->status), GFP_KERNEL);
424         if (!hub->status) {
425                 message = "can't kmalloc hub status buffer";
426                 ret = -ENOMEM;
427                 goto fail;
428         }
429
430         hub->descriptor = kmalloc(sizeof(*hub->descriptor), GFP_KERNEL);
431         if (!hub->descriptor) {
432                 message = "can't kmalloc hub descriptor";
433                 ret = -ENOMEM;
434                 goto fail;
435         }
436
437         /* Request the entire hub descriptor.
438          * hub->descriptor can handle USB_MAXCHILDREN ports,
439          * but the hub can/will return fewer bytes here.
440          */
441         ret = get_hub_descriptor(hdev, hub->descriptor,
442                         sizeof(*hub->descriptor));
443         if (ret < 0) {
444                 message = "can't read hub descriptor";
445                 goto fail;
446         } else if (hub->descriptor->bNbrPorts > USB_MAXCHILDREN) {
447                 message = "hub has too many ports!";
448                 ret = -ENODEV;
449                 goto fail;
450         }
451
452         hdev->maxchild = hub->descriptor->bNbrPorts;
453         dev_info (hub_dev, "%d port%s detected\n", hdev->maxchild,
454                 (hdev->maxchild == 1) ? "" : "s");
455
456         le16_to_cpus(&hub->descriptor->wHubCharacteristics);
457
458         if (hub->descriptor->wHubCharacteristics & HUB_CHAR_COMPOUND) {
459                 int     i;
460                 char    portstr [USB_MAXCHILDREN + 1];
461
462                 for (i = 0; i < hdev->maxchild; i++)
463                         portstr[i] = hub->descriptor->DeviceRemovable
464                                     [((i + 1) / 8)] & (1 << ((i + 1) % 8))
465                                 ? 'F' : 'R';
466                 portstr[hdev->maxchild] = 0;
467                 dev_dbg(hub_dev, "compound device; port removable status: %s\n", portstr);
468         } else
469                 dev_dbg(hub_dev, "standalone hub\n");
470
471         switch (hub->descriptor->wHubCharacteristics & HUB_CHAR_LPSM) {
472                 case 0x00:
473                         dev_dbg(hub_dev, "ganged power switching\n");
474                         break;
475                 case 0x01:
476                         dev_dbg(hub_dev, "individual port power switching\n");
477                         break;
478                 case 0x02:
479                 case 0x03:
480                         dev_dbg(hub_dev, "no power switching (usb 1.0)\n");
481                         break;
482         }
483
484         switch (hub->descriptor->wHubCharacteristics & HUB_CHAR_OCPM) {
485                 case 0x00:
486                         dev_dbg(hub_dev, "global over-current protection\n");
487                         break;
488                 case 0x08:
489                         dev_dbg(hub_dev, "individual port over-current protection\n");
490                         break;
491                 case 0x10:
492                 case 0x18:
493                         dev_dbg(hub_dev, "no over-current protection\n");
494                         break;
495         }
496
497         spin_lock_init (&hub->tt.lock);
498         INIT_LIST_HEAD (&hub->tt.clear_list);
499         INIT_WORK (&hub->tt.kevent, hub_tt_kevent, hub);
500         switch (hdev->descriptor.bDeviceProtocol) {
501                 case 0:
502                         break;
503                 case 1:
504                         dev_dbg(hub_dev, "Single TT\n");
505                         hub->tt.hub = hdev;
506                         break;
507                 case 2:
508                         ret = usb_set_interface(hdev, 0, 1);
509                         if (ret == 0) {
510                                 dev_dbg(hub_dev, "TT per port\n");
511                                 hub->tt.multi = 1;
512                         } else
513                                 dev_err(hub_dev, "Using single TT (err %d)\n",
514                                         ret);
515                         hub->tt.hub = hdev;
516                         break;
517                 default:
518                         dev_dbg(hub_dev, "Unrecognized hub protocol %d\n",
519                                 hdev->descriptor.bDeviceProtocol);
520                         break;
521         }
522
523         switch (hub->descriptor->wHubCharacteristics & HUB_CHAR_TTTT) {
524                 case 0x00:
525                         if (hdev->descriptor.bDeviceProtocol != 0)
526                                 dev_dbg(hub_dev, "TT requires at most 8 FS bit times\n");
527                         break;
528                 case 0x20:
529                         dev_dbg(hub_dev, "TT requires at most 16 FS bit times\n");
530                         break;
531                 case 0x40:
532                         dev_dbg(hub_dev, "TT requires at most 24 FS bit times\n");
533                         break;
534                 case 0x60:
535                         dev_dbg(hub_dev, "TT requires at most 32 FS bit times\n");
536                         break;
537         }
538
539         /* probe() zeroes hub->indicator[] */
540         if (hub->descriptor->wHubCharacteristics & HUB_CHAR_PORTIND) {
541                 hub->has_indicators = 1;
542                 dev_dbg(hub_dev, "Port indicators are supported\n");
543         }
544
545         dev_dbg(hub_dev, "power on to power good time: %dms\n",
546                 hub->descriptor->bPwrOn2PwrGood * 2);
547
548         /* power budgeting mostly matters with bus-powered hubs,
549          * and battery-powered root hubs (may provide just 8 mA).
550          */
551         ret = usb_get_status(hdev, USB_RECIP_DEVICE, 0, &hubstatus);
552         if (ret < 0) {
553                 message = "can't get hub status";
554                 goto fail;
555         }
556         cpu_to_le16s(&hubstatus);
557         if ((hubstatus & (1 << USB_DEVICE_SELF_POWERED)) == 0) {
558                 dev_dbg(hub_dev, "hub controller current requirement: %dmA\n",
559                         hub->descriptor->bHubContrCurrent);
560                 hub->power_budget = (501 - hub->descriptor->bHubContrCurrent)
561                                         / 2;
562                 dev_dbg(hub_dev, "%dmA bus power budget for children\n",
563                         hub->power_budget * 2);
564         }
565
566
567         ret = hub_hub_status(hub, &hubstatus, &hubchange);
568         if (ret < 0) {
569                 message = "can't get hub status";
570                 goto fail;
571         }
572
573         /* local power status reports aren't always correct */
574         if (hdev->actconfig->desc.bmAttributes & USB_CONFIG_ATT_SELFPOWER)
575                 dev_dbg(hub_dev, "local power source is %s\n",
576                         (hubstatus & HUB_STATUS_LOCAL_POWER)
577                         ? "lost (inactive)" : "good");
578
579         if ((hub->descriptor->wHubCharacteristics & HUB_CHAR_OCPM) == 0)
580                 dev_dbg(hub_dev, "%sover-current condition exists\n",
581                         (hubstatus & HUB_STATUS_OVERCURRENT) ? "" : "no ");
582
583         /* Start the interrupt endpoint */
584         pipe = usb_rcvintpipe(hdev, endpoint->bEndpointAddress);
585         maxp = usb_maxpacket(hdev, pipe, usb_pipeout(pipe));
586
587         if (maxp > sizeof(*hub->buffer))
588                 maxp = sizeof(*hub->buffer);
589
590         hub->urb = usb_alloc_urb(0, GFP_KERNEL);
591         if (!hub->urb) {
592                 message = "couldn't allocate interrupt urb";
593                 ret = -ENOMEM;
594                 goto fail;
595         }
596
597         usb_fill_int_urb(hub->urb, hdev, pipe, *hub->buffer, maxp, hub_irq,
598                 hub, endpoint->bInterval);
599         hub->urb->transfer_dma = hub->buffer_dma;
600         hub->urb->transfer_flags |= URB_NO_TRANSFER_DMA_MAP;
601         ret = usb_submit_urb(hub->urb, GFP_KERNEL);
602         if (ret) {
603                 message = "couldn't submit status urb";
604                 goto fail;
605         }
606         hub->urb_active = 1;
607
608         /* Wake up khubd */
609         wake_up(&khubd_wait);
610
611         /* maybe start cycling the hub leds */
612         if (hub->has_indicators && blinkenlights) {
613                 set_port_led(hdev, 1, HUB_LED_GREEN);
614                 hub->indicator [0] = INDICATOR_CYCLE;
615                 schedule_delayed_work(&hub->leds, LED_CYCLE_PERIOD);
616         }
617
618         hub_power_on(hub);
619
620         return 0;
621
622 fail:
623         dev_err (hub_dev, "config failed, %s (err %d)\n",
624                         message, ret);
625         /* hub_disconnect() frees urb and descriptor */
626         return ret;
627 }
628
629 static unsigned highspeed_hubs;
630
631 static void hub_disconnect(struct usb_interface *intf)
632 {
633         struct usb_hub *hub = usb_get_intfdata (intf);
634         DECLARE_COMPLETION(urb_complete);
635         unsigned long flags;
636
637         if (!hub)
638                 return;
639
640         if (interface_to_usbdev(intf)->speed == USB_SPEED_HIGH)
641                 highspeed_hubs--;
642
643         usb_set_intfdata (intf, NULL);
644         spin_lock_irqsave(&hub_event_lock, flags);
645         hub->urb_complete = &urb_complete;
646
647         /* Delete it and then reset it */
648         list_del_init(&hub->event_list);
649         list_del_init(&hub->hub_list);
650
651         spin_unlock_irqrestore(&hub_event_lock, flags);
652
653         down(&hub->khubd_sem); /* Wait for khubd to leave this hub alone. */
654         up(&hub->khubd_sem);
655
656         /* assuming we used keventd, it must quiesce too */
657         if (hub->has_indicators)
658                 cancel_delayed_work (&hub->leds);
659         if (hub->has_indicators || hub->tt.hub)
660                 flush_scheduled_work ();
661
662         if (hub->urb) {
663                 usb_unlink_urb(hub->urb);
664                 if (hub->urb_active)
665                         wait_for_completion(&urb_complete);
666                 usb_free_urb(hub->urb);
667                 hub->urb = NULL;
668         }
669
670         if (hub->descriptor) {
671                 kfree(hub->descriptor);
672                 hub->descriptor = NULL;
673         }
674
675         if (hub->status) {
676                 kfree(hub->status);
677                 hub->status = NULL;
678         }
679
680         if (hub->buffer) {
681                 usb_buffer_free(interface_to_usbdev(intf),
682                                 sizeof(*hub->buffer), hub->buffer,
683                                 hub->buffer_dma);
684                 hub->buffer = NULL;
685         }
686
687         /* Free the memory */
688         kfree(hub);
689 }
690
691 static int hub_probe(struct usb_interface *intf, const struct usb_device_id *id)
692 {
693         struct usb_host_interface *desc;
694         struct usb_endpoint_descriptor *endpoint;
695         struct usb_device *hdev;
696         struct usb_hub *hub;
697         struct device *hub_dev;
698         unsigned long flags;
699
700         desc = intf->cur_altsetting;
701         hdev = interface_to_usbdev(intf);
702         hub_dev = &intf->dev;
703
704         /* Some hubs have a subclass of 1, which AFAICT according to the */
705         /*  specs is not defined, but it works */
706         if ((desc->desc.bInterfaceSubClass != 0) &&
707             (desc->desc.bInterfaceSubClass != 1)) {
708 descriptor_error:
709                 dev_err (hub_dev, "bad descriptor, ignoring hub\n");
710                 return -EIO;
711         }
712
713         /* Multiple endpoints? What kind of mutant ninja-hub is this? */
714         if (desc->desc.bNumEndpoints != 1) {
715                 goto descriptor_error;
716         }
717
718         endpoint = &desc->endpoint[0].desc;
719
720         /* Output endpoint? Curiouser and curiouser.. */
721         if (!(endpoint->bEndpointAddress & USB_DIR_IN)) {
722                 goto descriptor_error;
723         }
724
725         /* If it's not an interrupt endpoint, we'd better punt! */
726         if ((endpoint->bmAttributes & USB_ENDPOINT_XFERTYPE_MASK)
727                         != USB_ENDPOINT_XFER_INT) {
728                 goto descriptor_error;
729                 return -EIO;
730         }
731
732         /* We found a hub */
733         dev_info (hub_dev, "USB hub found\n");
734
735         hub = kmalloc(sizeof(*hub), GFP_KERNEL);
736         if (!hub) {
737                 dev_dbg (hub_dev, "couldn't kmalloc hub struct\n");
738                 return -ENOMEM;
739         }
740
741         memset(hub, 0, sizeof(*hub));
742
743         INIT_LIST_HEAD(&hub->event_list);
744         hub->intf = intf;
745         init_MUTEX(&hub->khubd_sem);
746         INIT_WORK(&hub->leds, led_work, hub);
747
748         /* Record the new hub's existence */
749         spin_lock_irqsave(&hub_event_lock, flags);
750         INIT_LIST_HEAD(&hub->hub_list);
751         list_add(&hub->hub_list, &hub_list);
752         spin_unlock_irqrestore(&hub_event_lock, flags);
753
754         usb_set_intfdata (intf, hub);
755
756         if (hdev->speed == USB_SPEED_HIGH)
757                 highspeed_hubs++;
758
759         if (hub_configure(hub, endpoint) >= 0)
760                 return 0;
761
762         hub_disconnect (intf);
763         return -ENODEV;
764 }
765
766 static int
767 hub_ioctl(struct usb_interface *intf, unsigned int code, void *user_data)
768 {
769         struct usb_device *hdev = interface_to_usbdev (intf);
770
771         /* assert ifno == 0 (part of hub spec) */
772         switch (code) {
773         case USBDEVFS_HUB_PORTINFO: {
774                 struct usbdevfs_hub_portinfo *info = user_data;
775                 unsigned long flags;
776                 int i;
777
778                 spin_lock_irqsave(&hub_event_lock, flags);
779                 if (hdev->devnum <= 0)
780                         info->nports = 0;
781                 else {
782                         info->nports = hdev->maxchild;
783                         for (i = 0; i < info->nports; i++) {
784                                 if (hdev->children[i] == NULL)
785                                         info->port[i] = 0;
786                                 else
787                                         info->port[i] =
788                                                 hdev->children[i]->devnum;
789                         }
790                 }
791                 spin_unlock_irqrestore(&hub_event_lock, flags);
792
793                 return info->nports + 1;
794                 }
795
796         default:
797                 return -ENOSYS;
798         }
799 }
800
801 static int hub_reset(struct usb_hub *hub)
802 {
803         struct usb_device *hdev = interface_to_usbdev(hub->intf);
804         int i;
805
806         /* Disconnect any attached devices */
807         for (i = 0; i < hub->descriptor->bNbrPorts; i++) {
808                 if (hdev->children[i])
809                         usb_disconnect(&hdev->children[i]);
810         }
811
812         /* Attempt to reset the hub */
813         if (hub->urb)
814                 usb_unlink_urb(hub->urb);
815         else
816                 return -1;
817
818         if (usb_reset_device(hdev))
819                 return -1;
820
821         hub->urb->dev = hdev;                                                    
822         if (usb_submit_urb(hub->urb, GFP_KERNEL))
823                 return -1;
824
825         hub_power_on(hub);
826
827         return 0;
828 }
829
830 static void hub_start_disconnect(struct usb_device *hdev)
831 {
832         struct usb_device *parent = hdev->parent;
833         int i;
834
835         /* Find the device pointer to disconnect */
836         if (parent) {
837                 for (i = 0; i < parent->maxchild; i++) {
838                         if (parent->children[i] == hdev) {
839                                 usb_disconnect(&parent->children[i]);
840                                 return;
841                         }
842                 }
843         }
844
845         dev_err(&hdev->dev, "cannot disconnect hub!\n");
846 }
847
848 static int hub_port_status(struct usb_device *hdev, int port,
849                                u16 *status, u16 *change)
850 {
851         struct usb_hub *hub = usb_get_intfdata(hdev->actconfig->interface[0]);
852         int ret;
853
854         if (!hub)
855                 return -ENODEV;
856
857         ret = get_port_status(hdev, port + 1, &hub->status->port);
858         if (ret < 0)
859                 dev_err (&hub->intf->dev,
860                         "%s failed (err = %d)\n", __FUNCTION__, ret);
861         else {
862                 *status = le16_to_cpu(hub->status->port.wPortStatus);
863                 *change = le16_to_cpu(hub->status->port.wPortChange); 
864                 ret = 0;
865         }
866         return ret;
867 }
868
869 #define PORT_RESET_TRIES        5
870 #define SET_ADDRESS_TRIES       2
871 #define GET_DESCRIPTOR_TRIES    2
872 #define SET_CONFIG_TRIES        2
873
874 #define HUB_ROOT_RESET_TIME     50      /* times are in msec */
875 #define HUB_SHORT_RESET_TIME    10
876 #define HUB_LONG_RESET_TIME     200
877 #define HUB_RESET_TIMEOUT       500
878
879 static int hub_port_wait_reset(struct usb_device *hdev, int port,
880                                 struct usb_device *udev, unsigned int delay)
881 {
882         int delay_time, ret;
883         u16 portstatus;
884         u16 portchange;
885
886         for (delay_time = 0;
887                         delay_time < HUB_RESET_TIMEOUT;
888                         delay_time += delay) {
889                 /* wait to give the device a chance to reset */
890                 msleep(delay);
891
892                 /* read and decode port status */
893                 ret = hub_port_status(hdev, port, &portstatus, &portchange);
894                 if (ret < 0)
895                         return ret;
896
897                 /* Device went away? */
898                 if (!(portstatus & USB_PORT_STAT_CONNECTION))
899                         return -ENOTCONN;
900
901                 /* bomb out completely if something weird happened */
902                 if ((portchange & USB_PORT_STAT_C_CONNECTION))
903                         return -EINVAL;
904
905                 /* if we`ve finished resetting, then break out of the loop */
906                 if (!(portstatus & USB_PORT_STAT_RESET) &&
907                     (portstatus & USB_PORT_STAT_ENABLE)) {
908                         if (portstatus & USB_PORT_STAT_HIGH_SPEED)
909                                 udev->speed = USB_SPEED_HIGH;
910                         else if (portstatus & USB_PORT_STAT_LOW_SPEED)
911                                 udev->speed = USB_SPEED_LOW;
912                         else
913                                 udev->speed = USB_SPEED_FULL;
914                         return 0;
915                 }
916
917                 /* switch to the long delay after two short delay failures */
918                 if (delay_time >= 2 * HUB_SHORT_RESET_TIME)
919                         delay = HUB_LONG_RESET_TIME;
920
921                 dev_dbg (hubdev (hdev),
922                         "port %d not reset yet, waiting %dms\n",
923                         port + 1, delay);
924         }
925
926         return -EBUSY;
927 }
928
929 static int hub_port_reset(struct usb_device *hdev, int port,
930                                 struct usb_device *udev, unsigned int delay)
931 {
932         int i, status;
933         struct device *hub_dev = hubdev (hdev);
934
935         /* Reset the port */
936         for (i = 0; i < PORT_RESET_TRIES; i++) {
937                 set_port_feature(hdev, port + 1, USB_PORT_FEAT_RESET);
938
939                 /* return on disconnect or reset */
940                 status = hub_port_wait_reset(hdev, port, udev, delay);
941                 if (status == -ENOTCONN || status == 0) {
942                         clear_port_feature(hdev,
943                                 port + 1, USB_PORT_FEAT_C_RESET);
944                         udev->state = status
945                                         ? USB_STATE_NOTATTACHED
946                                         : USB_STATE_DEFAULT;
947                         return status;
948                 }
949
950                 dev_dbg (hub_dev,
951                         "port %d not enabled, trying reset again...\n",
952                         port + 1);
953                 delay = HUB_LONG_RESET_TIME;
954         }
955
956         dev_err (hub_dev,
957                 "Cannot enable port %i.  Maybe the USB cable is bad?\n",
958                 port + 1);
959
960         return status;
961 }
962
963 static int hub_port_disable(struct usb_device *hdev, int port)
964 {
965         int ret;
966
967         ret = clear_port_feature(hdev, port + 1, USB_PORT_FEAT_ENABLE);
968         if (ret)
969                 dev_err(hubdev(hdev), "cannot disable port %d (err = %d)\n",
970                         port + 1, ret);
971
972         return ret;
973 }
974
975 /* USB 2.0 spec, 7.1.7.3 / fig 7-29:
976  *
977  * Between connect detection and reset signaling there must be a delay
978  * of 100ms at least for debounce and power-settling. The corresponding
979  * timer shall restart whenever the downstream port detects a disconnect.
980  * 
981  * Apparently there are some bluetooth and irda-dongles and a number
982  * of low-speed devices which require longer delays of about 200-400ms.
983  * Not covered by the spec - but easy to deal with.
984  *
985  * This implementation uses 400ms minimum debounce timeout and checks
986  * every 25ms for transient disconnects to restart the delay.
987  */
988
989 #define HUB_DEBOUNCE_TIMEOUT    400
990 #define HUB_DEBOUNCE_STEP        25
991 #define HUB_DEBOUNCE_STABLE       4
992
993 static int hub_port_debounce(struct usb_device *hdev, int port)
994 {
995         int ret;
996         int delay_time, stable_count;
997         u16 portchange, portstatus;
998         unsigned connection;
999
1000         connection = 0;
1001         stable_count = 0;
1002         for (delay_time = 0; delay_time < HUB_DEBOUNCE_TIMEOUT; delay_time += HUB_DEBOUNCE_STEP) {
1003                 msleep(HUB_DEBOUNCE_STEP);
1004
1005                 ret = hub_port_status(hdev, port, &portstatus, &portchange);
1006                 if (ret < 0)
1007                         return ret;
1008
1009                 if ((portstatus & USB_PORT_STAT_CONNECTION) == connection) {
1010                         if (connection) {
1011                                 if (++stable_count == HUB_DEBOUNCE_STABLE)
1012                                         break;
1013                         }
1014                 } else {
1015                         stable_count = 0;
1016                 }
1017                 connection = portstatus & USB_PORT_STAT_CONNECTION;
1018
1019                 if ((portchange & USB_PORT_STAT_C_CONNECTION)) {
1020                         clear_port_feature(hdev, port+1, USB_PORT_FEAT_C_CONNECTION);
1021                 }
1022         }
1023
1024         dev_dbg (hubdev (hdev),
1025                 "debounce: port %d: delay %dms stable %d status 0x%x\n",
1026                 port + 1, delay_time, stable_count, portstatus);
1027
1028         return (portstatus & USB_PORT_STAT_CONNECTION) ? 0 : -ENOTCONN;
1029 }
1030
1031 static int hub_set_address(struct usb_device *udev)
1032 {
1033         int retval;
1034
1035         if (udev->devnum == 0)
1036                 return -EINVAL;
1037         if (udev->state != USB_STATE_DEFAULT &&
1038                         udev->state != USB_STATE_ADDRESS)
1039                 return -EINVAL;
1040         retval = usb_control_msg(udev, usb_snddefctrl(udev),
1041                 USB_REQ_SET_ADDRESS, 0, udev->devnum, 0,
1042                 NULL, 0, HZ * USB_CTRL_SET_TIMEOUT);
1043         if (retval == 0)
1044                 udev->state = USB_STATE_ADDRESS;
1045         return retval;
1046 }
1047
1048 /* reset device, (re)assign address, get device descriptor.
1049  * device connection is stable, no more debouncing needed.
1050  * returns device in USB_STATE_ADDRESS, except on error.
1051  * on error return, device is no longer usable (ref dropped).
1052  *
1053  * caller owns dev->serialize for the device, guarding against
1054  * config changes and disconnect processing.
1055  */
1056 static int
1057 hub_port_init (struct usb_device *hdev, struct usb_device *udev, int port)
1058 {
1059         static DECLARE_MUTEX(usb_address0_sem);
1060
1061         int                     i, j, retval;
1062         unsigned                delay = HUB_SHORT_RESET_TIME;
1063         enum usb_device_speed   oldspeed = udev->speed;
1064
1065         /* root hub ports have a slightly longer reset period
1066          * (from USB 2.0 spec, section 7.1.7.5)
1067          */
1068         if (!hdev->parent)
1069                 delay = HUB_ROOT_RESET_TIME;
1070
1071         /* Some low speed devices have problems with the quick delay, so */
1072         /*  be a bit pessimistic with those devices. RHbug #23670 */
1073         if (oldspeed == USB_SPEED_LOW)
1074                 delay = HUB_LONG_RESET_TIME;
1075
1076         down(&usb_address0_sem);
1077
1078         /* Reset the device; full speed may morph to high speed */
1079         retval = hub_port_reset(hdev, port, udev, delay);
1080         if (retval < 0)         /* error or disconnect */
1081                 goto fail;
1082                                 /* success, speed is known */
1083         retval = -ENODEV;
1084
1085         if (oldspeed != USB_SPEED_UNKNOWN && oldspeed != udev->speed) {
1086                 dev_dbg(&udev->dev, "device reset changed speed!\n");
1087                 goto fail;
1088         }
1089   
1090         /* USB 2.0 section 5.5.3 talks about ep0 maxpacket ...
1091          * it's fixed size except for full speed devices.
1092          */
1093         switch (udev->speed) {
1094         case USB_SPEED_HIGH:            /* fixed at 64 */
1095                 i = 64;
1096                 break;
1097         case USB_SPEED_FULL:            /* 8, 16, 32, or 64 */
1098                 /* to determine the ep0 maxpacket size, read the first 8
1099                  * bytes from the device descriptor to get bMaxPacketSize0;
1100                  * then correct our initial (small) guess.
1101                  */
1102                 // FALLTHROUGH
1103         case USB_SPEED_LOW:             /* fixed at 8 */
1104                 i = 8;
1105                 break;
1106         default:
1107                 goto fail;
1108         }
1109         udev->epmaxpacketin [0] = i;
1110         udev->epmaxpacketout[0] = i;
1111  
1112         /* set the address */
1113         if (udev->devnum <= 0) {
1114                 usb_choose_address(udev);
1115                 if (udev->devnum <= 0)
1116                         goto fail;
1117
1118                 /* Set up TT records, if needed  */
1119                 if (hdev->tt) {
1120                         udev->tt = hdev->tt;
1121                         udev->ttport = hdev->ttport;
1122                 } else if (udev->speed != USB_SPEED_HIGH
1123                                 && hdev->speed == USB_SPEED_HIGH) {
1124                         struct usb_hub  *hub;
1125  
1126                         hub = usb_get_intfdata (hdev->actconfig
1127                                                         ->interface[0]);
1128                         udev->tt = &hub->tt;
1129                         udev->ttport = port + 1;
1130                 }
1131
1132                 /* force the right log message (below) at low speed */
1133                 oldspeed = USB_SPEED_UNKNOWN;
1134         }
1135  
1136         dev_info (&udev->dev,
1137                         "%s %s speed USB device using address %d\n",
1138                         (oldspeed == USB_SPEED_UNKNOWN) ? "new" : "reset",
1139                         ({ char *speed; switch (udev->speed) {
1140                         case USB_SPEED_LOW:     speed = "low";  break;
1141                         case USB_SPEED_FULL:    speed = "full"; break;
1142                         case USB_SPEED_HIGH:    speed = "high"; break;
1143                         default:                speed = "?";    break;
1144                         }; speed;}),
1145                         udev->devnum);
1146  
1147         /* Why interleave GET_DESCRIPTOR and SET_ADDRESS this way?
1148          * Because device hardware and firmware is sometimes buggy in
1149          * this area, and this is how Linux has done it for ages.
1150          * Change it cautiously.
1151          *
1152          * NOTE:  Windows gets the descriptor first, seemingly to help
1153          * work around device bugs like "can't use addresses with bit 3
1154          * set in certain configurations".  Yes, really.
1155          */
1156         for (i = 0; i < GET_DESCRIPTOR_TRIES; ++i) {
1157                 for (j = 0; j < SET_ADDRESS_TRIES; ++j) {
1158                         retval = hub_set_address(udev);
1159                         if (retval >= 0)
1160                                 break;
1161                         msleep(200);
1162                 }
1163                 if (retval < 0) {
1164                         dev_err(&udev->dev,
1165                                 "device not accepting address %d, error %d\n",
1166                                 udev->devnum, retval);
1167  fail:
1168                         hub_port_disable(hdev, port);
1169                         usb_release_address(udev);
1170                         usb_put_dev(udev);
1171                         up(&usb_address0_sem);
1172                         return retval;
1173                 }
1174  
1175                 /* cope with hardware quirkiness:
1176                  *  - let SET_ADDRESS settle, some device hardware wants it
1177                  *  - read ep0 maxpacket even for high and low speed,
1178                  */
1179                 msleep(10);
1180                 retval = usb_get_device_descriptor(udev, 8);
1181                 if (retval >= 8)
1182                         break;
1183                 msleep(100);
1184         }
1185         if (retval != 8) {
1186                 dev_err(&udev->dev, "device descriptor read/%s, error %d\n",
1187                                 "8", retval);
1188                 if (retval >= 0)
1189                         retval = -EMSGSIZE;
1190                 goto fail;
1191         }
1192         if (udev->speed == USB_SPEED_FULL
1193                         && (udev->epmaxpacketin [0]
1194                                 != udev->descriptor.bMaxPacketSize0)) {
1195                 usb_disable_endpoint(udev, 0);
1196                 usb_endpoint_running(udev, 0, 1);
1197                 usb_endpoint_running(udev, 0, 0);
1198                 udev->epmaxpacketin [0] = udev->descriptor.bMaxPacketSize0;
1199                 udev->epmaxpacketout[0] = udev->descriptor.bMaxPacketSize0;
1200         }
1201   
1202         retval = usb_get_device_descriptor(udev, USB_DT_DEVICE_SIZE);
1203         if (retval < (signed)sizeof(udev->descriptor)) {
1204                 dev_err(&udev->dev, "device descriptor read/%s, error %d\n",
1205                         "all", retval);
1206                 if (retval >= 0)
1207                         retval = -ENOMSG;
1208                 goto fail;
1209         }
1210
1211         /* now dev is visible to other tasks */
1212         hdev->children[port] = udev;
1213
1214         up(&usb_address0_sem);
1215         return 0;
1216 }
1217
1218 static void
1219 check_highspeed (struct usb_hub *hub, struct usb_device *udev, int port)
1220 {
1221         struct usb_qualifier_descriptor *qual;
1222         int                             status;
1223
1224         qual = kmalloc (sizeof *qual, SLAB_KERNEL);
1225         if (qual == 0)
1226                 return;
1227
1228         status = usb_get_descriptor (udev, USB_DT_DEVICE_QUALIFIER, 0,
1229                         qual, sizeof *qual);
1230         if (status == sizeof *qual) {
1231                 dev_info(&udev->dev, "not running at top speed; "
1232                         "connect to a high speed hub\n");
1233                 /* hub LEDs are probably harder to miss than syslog */
1234                 if (hub->has_indicators) {
1235                         hub->indicator[port] = INDICATOR_GREEN_BLINK;
1236                         schedule_work (&hub->leds);
1237                 }
1238         }
1239         kfree (qual);
1240 }
1241
1242 static unsigned
1243 hub_power_remaining (struct usb_hub *hub, struct usb_device *hdev)
1244 {
1245         int remaining;
1246         unsigned i;
1247
1248         remaining = hub->power_budget;
1249         if (!remaining)         /* self-powered */
1250                 return 0;
1251
1252         for (i = 0; i < hdev->maxchild; i++) {
1253                 struct usb_device       *udev = hdev->children[i];
1254                 int                     delta;
1255
1256                 if (!udev)
1257                         continue;
1258
1259                 if (udev->actconfig)
1260                         delta = udev->actconfig->desc.bMaxPower;
1261                 else
1262                         delta = 50;
1263                 // dev_dbg(&udev->dev, "budgeted %dmA\n", 2 * delta);
1264                 remaining -= delta;
1265         }
1266         if (remaining < 0) {
1267                 dev_warn(&hub->intf->dev,
1268                         "%dmA over power budget!\n",
1269                         -2 * remaining);
1270                 remaining = 0;
1271         }
1272         return remaining;
1273 }
1274  
1275 static void hub_port_connect_change(struct usb_hub *hub, int port,
1276                                         u16 portstatus, u16 portchange)
1277 {
1278         struct usb_device *hdev = interface_to_usbdev(hub->intf);
1279         struct device *hub_dev = &hub->intf->dev;
1280         int status, i;
1281  
1282         dev_dbg (hub_dev,
1283                 "port %d, status %04x, change %04x, %s\n",
1284                 port + 1, portstatus, portchange, portspeed (portstatus));
1285  
1286         /* Clear the connection change status */
1287         clear_port_feature(hdev, port + 1, USB_PORT_FEAT_C_CONNECTION);
1288
1289         if (hub->has_indicators) {
1290                 set_port_led(hdev, port + 1, HUB_LED_AUTO);
1291                 hub->indicator[port] = INDICATOR_AUTO;
1292         }
1293  
1294         /* Disconnect any existing devices under this port */
1295         if (hdev->children[port])
1296                 usb_disconnect(&hdev->children[port]);
1297
1298         /* Return now if nothing is connected */
1299         if (!(portstatus & USB_PORT_STAT_CONNECTION)) {
1300
1301                 /* maybe switch power back on (e.g. root hub was reset) */
1302                 if ((hub->descriptor->wHubCharacteristics
1303                                         & HUB_CHAR_LPSM) < 2
1304                                 && !(portstatus & (1 << USB_PORT_FEAT_POWER)))
1305                         set_port_feature(hdev, port + 1, USB_PORT_FEAT_POWER);
1306  
1307                 if (portstatus & USB_PORT_STAT_ENABLE)
1308                         goto done;
1309                 return;
1310         }
1311   
1312         if (hub_port_debounce(hdev, port)) {
1313                 dev_err (hub_dev,
1314                         "connect-debounce failed, port %d disabled\n",
1315                         port+1);
1316                 goto done;
1317         }
1318
1319         for (i = 0; i < SET_CONFIG_TRIES; i++) {
1320                 struct usb_device *udev;
1321
1322                 /* reallocate for each attempt, since references
1323                  * to the previous one can escape in various ways
1324                  */
1325                 udev = usb_alloc_dev(hdev, hdev->bus, port);
1326                 if (!udev) {
1327                         dev_err (hub_dev,
1328                                 "couldn't allocate port %d usb_device\n", port+1);
1329                         goto done;
1330                 }
1331                 udev->state = USB_STATE_POWERED;
1332           
1333                 /* hub can tell if it's lowspeed already:  D- pullup (not D+) */
1334                 if (portstatus & USB_PORT_STAT_LOW_SPEED)
1335                         udev->speed = USB_SPEED_LOW;
1336                 else
1337                         udev->speed = USB_SPEED_UNKNOWN;
1338
1339                 /* reset, set address, get descriptor, add to hub's children */
1340                 down (&udev->serialize);
1341                 status = hub_port_init(hdev, udev, port);
1342                 if (status == -ENOTCONN)
1343                         break;
1344                 if (status < 0)
1345                         continue;
1346
1347                 /* consecutive bus-powered hubs aren't reliable; they can
1348                  * violate the voltage drop budget.  if the new child has
1349                  * a "powered" LED, users should notice we didn't enable it
1350                  * (without reading syslog), even without per-port LEDs
1351                  * on the parent.
1352                  */
1353                 if (udev->descriptor.bDeviceClass == USB_CLASS_HUB
1354                                 && hub->power_budget) {
1355                         u16     devstat;
1356
1357                         status = usb_get_status(udev, USB_RECIP_DEVICE, 0,
1358                                         &devstat);
1359                         if (status < 0) {
1360                                 dev_dbg(&udev->dev, "get status %d ?\n", status);
1361                                 continue;
1362                         }
1363                         cpu_to_le16s(&devstat);
1364                         if ((devstat & (1 << USB_DEVICE_SELF_POWERED)) == 0) {
1365                                 dev_err(&udev->dev,
1366                                         "can't connect bus-powered hub "
1367                                         "to this port\n");
1368                                 if (hub->has_indicators) {
1369                                         hub->indicator[port] =
1370                                                 INDICATOR_AMBER_BLINK;
1371                                         schedule_work (&hub->leds);
1372                                 }
1373                                 hdev->children[port] = NULL;
1374                                 usb_put_dev(udev);
1375                                 hub_port_disable(hdev, port);
1376                                 return;
1377                         }
1378                 }
1379  
1380                 /* check for devices running slower than they could */
1381                 if (udev->descriptor.bcdUSB >= 0x0200
1382                                 && udev->speed == USB_SPEED_FULL
1383                                 && highspeed_hubs != 0)
1384                         check_highspeed (hub, udev, port);
1385
1386                 /* Run it through the hoops (find a driver, etc) */
1387                 status = usb_new_device(udev);
1388                 if (status != 0) {
1389                         hdev->children[port] = NULL;
1390                         continue;
1391                 }
1392                 up (&udev->serialize);
1393
1394                 status = hub_power_remaining(hub, hdev);
1395                 if (status)
1396                         dev_dbg(hub_dev,
1397                                 "%dmA power budget left\n",
1398                                 2 * status);
1399
1400                 return;
1401         }
1402  
1403 done:
1404         hub_port_disable(hdev, port);
1405 }
1406
1407 static void hub_events(void)
1408 {
1409         unsigned long flags;
1410         struct list_head *tmp;
1411         struct usb_device *hdev;
1412         struct usb_hub *hub;
1413         struct device *hub_dev;
1414         u16 hubstatus;
1415         u16 hubchange;
1416         u16 portstatus;
1417         u16 portchange;
1418         int i, ret;
1419
1420         /*
1421          *  We restart the list every time to avoid a deadlock with
1422          * deleting hubs downstream from this one. This should be
1423          * safe since we delete the hub from the event list.
1424          * Not the most efficient, but avoids deadlocks.
1425          */
1426         while (1) {
1427                 spin_lock_irqsave(&hub_event_lock, flags);
1428
1429                 if (list_empty(&hub_event_list))
1430                         break;
1431
1432                 /* Grab the next entry from the beginning of the list */
1433                 tmp = hub_event_list.next;
1434
1435                 hub = list_entry(tmp, struct usb_hub, event_list);
1436                 hdev = interface_to_usbdev(hub->intf);
1437                 hub_dev = &hub->intf->dev;
1438
1439                 list_del_init(tmp);
1440
1441                 if (unlikely(down_trylock(&hub->khubd_sem)))
1442                         BUG();  /* never blocks, we were on list */
1443
1444                 spin_unlock_irqrestore(&hub_event_lock, flags);
1445
1446                 if (hub->error) {
1447                         dev_dbg (hub_dev, "resetting for error %d\n",
1448                                 hub->error);
1449
1450                         if (hub_reset(hub)) {
1451                                 dev_dbg (hub_dev,
1452                                         "can't reset; disconnecting\n");
1453                                 up(&hub->khubd_sem);
1454                                 hub_start_disconnect(hdev);
1455                                 continue;
1456                         }
1457
1458                         hub->nerrors = 0;
1459                         hub->error = 0;
1460                 }
1461
1462                 for (i = 0; i < hub->descriptor->bNbrPorts; i++) {
1463                         ret = hub_port_status(hdev, i, &portstatus, &portchange);
1464                         if (ret < 0) {
1465                                 continue;
1466                         }
1467
1468                         if (portchange & USB_PORT_STAT_C_CONNECTION) {
1469                                 hub_port_connect_change(hub, i, portstatus, portchange);
1470                         } else if (portchange & USB_PORT_STAT_C_ENABLE) {
1471                                 dev_dbg (hub_dev,
1472                                         "port %d enable change, status %08x\n",
1473                                         i + 1, portstatus);
1474                                 clear_port_feature(hdev,
1475                                         i + 1, USB_PORT_FEAT_C_ENABLE);
1476
1477                                 /*
1478                                  * EM interference sometimes causes badly
1479                                  * shielded USB devices to be shutdown by
1480                                  * the hub, this hack enables them again.
1481                                  * Works at least with mouse driver. 
1482                                  */
1483                                 if (!(portstatus & USB_PORT_STAT_ENABLE)
1484                                     && (portstatus & USB_PORT_STAT_CONNECTION)
1485                                     && (hdev->children[i])) {
1486                                         dev_err (hub_dev,
1487                                             "port %i "
1488                                             "disabled by hub (EMI?), "
1489                                             "re-enabling...",
1490                                                 i + 1);
1491                                         hub_port_connect_change(hub,
1492                                                 i, portstatus, portchange);
1493                                 }
1494                         }
1495
1496                         if (portchange & USB_PORT_STAT_C_SUSPEND) {
1497                                 dev_dbg (hub_dev,
1498                                         "suspend change on port %d\n",
1499                                         i + 1);
1500                                 clear_port_feature(hdev,
1501                                         i + 1,  USB_PORT_FEAT_C_SUSPEND);
1502                         }
1503                         
1504                         if (portchange & USB_PORT_STAT_C_OVERCURRENT) {
1505                                 dev_err (hub_dev,
1506                                         "over-current change on port %d\n",
1507                                         i + 1);
1508                                 clear_port_feature(hdev,
1509                                         i + 1, USB_PORT_FEAT_C_OVER_CURRENT);
1510                                 hub_power_on(hub);
1511                         }
1512
1513                         if (portchange & USB_PORT_STAT_C_RESET) {
1514                                 dev_dbg (hub_dev,
1515                                         "reset change on port %d\n",
1516                                         i + 1);
1517                                 clear_port_feature(hdev,
1518                                         i + 1, USB_PORT_FEAT_C_RESET);
1519                         }
1520                 } /* end for i */
1521
1522                 /* deal with hub status changes */
1523                 if (hub_hub_status(hub, &hubstatus, &hubchange) < 0)
1524                         dev_err (hub_dev, "get_hub_status failed\n");
1525                 else {
1526                         if (hubchange & HUB_CHANGE_LOCAL_POWER) {
1527                                 dev_dbg (hub_dev, "power change\n");
1528                                 clear_hub_feature(hdev, C_HUB_LOCAL_POWER);
1529                         }
1530                         if (hubchange & HUB_CHANGE_OVERCURRENT) {
1531                                 dev_dbg (hub_dev, "overcurrent change\n");
1532                                 msleep(500);    /* Cool down */
1533                                 clear_hub_feature(hdev, C_HUB_OVER_CURRENT);
1534                                 hub_power_on(hub);
1535                         }
1536                 }
1537                 up(&hub->khubd_sem);
1538         } /* end while (1) */
1539
1540         spin_unlock_irqrestore(&hub_event_lock, flags);
1541 }
1542
1543 static int hub_thread(void *__unused)
1544 {
1545         /*
1546          * This thread doesn't need any user-level access,
1547          * so get rid of all our resources
1548          */
1549
1550         daemonize("khubd");
1551         allow_signal(SIGKILL);
1552
1553         /* Send me a signal to get me die (for debugging) */
1554         do {
1555                 hub_events();
1556                 wait_event_interruptible(khubd_wait, !list_empty(&hub_event_list)); 
1557                 if (current->flags & PF_FREEZE)
1558                         refrigerator(PF_FREEZE);
1559         } while (!signal_pending(current));
1560
1561         pr_debug ("%s: khubd exiting\n", usbcore_name);
1562         complete_and_exit(&khubd_exited, 0);
1563 }
1564
1565 static struct usb_device_id hub_id_table [] = {
1566     { .match_flags = USB_DEVICE_ID_MATCH_DEV_CLASS,
1567       .bDeviceClass = USB_CLASS_HUB},
1568     { .match_flags = USB_DEVICE_ID_MATCH_INT_CLASS,
1569       .bInterfaceClass = USB_CLASS_HUB},
1570     { }                                         /* Terminating entry */
1571 };
1572
1573 MODULE_DEVICE_TABLE (usb, hub_id_table);
1574
1575 static struct usb_driver hub_driver = {
1576         .owner =        THIS_MODULE,
1577         .name =         "hub",
1578         .probe =        hub_probe,
1579         .disconnect =   hub_disconnect,
1580         .ioctl =        hub_ioctl,
1581         .id_table =     hub_id_table,
1582 };
1583
1584 /*
1585  * This should be a separate module.
1586  */
1587 int usb_hub_init(void)
1588 {
1589         pid_t pid;
1590
1591         if (usb_register(&hub_driver) < 0) {
1592                 printk(KERN_ERR "%s: can't register hub driver\n",
1593                         usbcore_name);
1594                 return -1;
1595         }
1596
1597         pid = kernel_thread(hub_thread, NULL, CLONE_KERNEL);
1598         if (pid >= 0) {
1599                 khubd_pid = pid;
1600
1601                 return 0;
1602         }
1603
1604         /* Fall through if kernel_thread failed */
1605         usb_deregister(&hub_driver);
1606         printk(KERN_ERR "%s: can't start khubd\n", usbcore_name);
1607
1608         return -1;
1609 }
1610
1611 void usb_hub_cleanup(void)
1612 {
1613         int ret;
1614
1615         /* Kill the thread */
1616         ret = kill_proc(khubd_pid, SIGKILL, 1);
1617
1618         wait_for_completion(&khubd_exited);
1619
1620         /*
1621          * Hub resources are freed for us by usb_deregister. It calls
1622          * usb_driver_purge on every device which in turn calls that
1623          * devices disconnect function if it is using this driver.
1624          * The hub_disconnect function takes care of releasing the
1625          * individual hub resources. -greg
1626          */
1627         usb_deregister(&hub_driver);
1628 } /* usb_hub_cleanup() */
1629
1630
1631 static int config_descriptors_changed(struct usb_device *udev)
1632 {
1633         unsigned                        index;
1634         unsigned                        len = 0;
1635         struct usb_config_descriptor    *buf;
1636
1637         for (index = 0; index < udev->descriptor.bNumConfigurations; index++) {
1638                 if (len < udev->config[index].desc.wTotalLength)
1639                         len = udev->config[index].desc.wTotalLength;
1640         }
1641         buf = kmalloc (len, SLAB_KERNEL);
1642         if (buf == 0) {
1643                 dev_err(&udev->dev, "no mem to re-read configs after reset\n");
1644                 /* assume the worst */
1645                 return 1;
1646         }
1647         for (index = 0; index < udev->descriptor.bNumConfigurations; index++) {
1648                 int length;
1649                 int old_length = udev->config[index].desc.wTotalLength;
1650
1651                 length = usb_get_descriptor(udev, USB_DT_CONFIG, index, buf,
1652                                 old_length);
1653                 if (length < old_length) {
1654                         dev_dbg(&udev->dev, "config index %d, error %d\n",
1655                                         index, length);
1656                         break;
1657                 }
1658                 if (memcmp (buf, udev->rawdescriptors[index], old_length)
1659                                 != 0) {
1660                         dev_dbg(&udev->dev, "config index %d changed (#%d)\n",
1661                                 index, buf->bConfigurationValue);
1662 /* FIXME enable this when we can re-enumerate after reset;
1663  * until then DFU-ish drivers need this and other workarounds
1664  */
1665 //                      break;
1666                 }
1667         }
1668         kfree(buf);
1669         return index != udev->descriptor.bNumConfigurations;
1670 }
1671
1672 /*
1673  * WARNING - don't reset any device unless drivers for all of its
1674  * interfaces are expecting that reset!  Maybe some driver->reset()
1675  * method should eventually help ensure sufficient cooperation.
1676  *
1677  * This is the same as usb_reset_device() except that the caller
1678  * already holds dev->serialize.  For example, it's safe to use
1679  * this from a driver probe() routine after downloading new firmware.
1680  */
1681 int __usb_reset_device(struct usb_device *udev)
1682 {
1683         struct usb_device *parent = udev->parent;
1684         struct usb_device_descriptor descriptor = udev->descriptor;
1685         int i, ret, port = -1;
1686
1687         if (udev->maxchild) {
1688                 /* this requires hub- or hcd-specific logic;
1689                  * see hub_reset() and OHCI hc_restart()
1690                  */
1691                 dev_dbg(&udev->dev, "%s for hub!\n", __FUNCTION__);
1692                 return -EINVAL;
1693         }
1694
1695         for (i = 0; i < parent->maxchild; i++)
1696                 if (parent->children[i] == udev) {
1697                         port = i;
1698                         break;
1699                 }
1700
1701         if (port < 0)
1702                 return -ENOENT;
1703
1704         ret = hub_port_init(parent, udev, port);
1705         if (ret < 0)
1706                 goto re_enumerate;
1707  
1708         /* Device might have changed firmware (DFU or similar) */
1709         if (memcmp(&udev->descriptor, &descriptor, sizeof descriptor)
1710                         || config_descriptors_changed (udev)) {
1711                 dev_info(&udev->dev, "device firmware changed\n");
1712                 udev->descriptor = descriptor;  /* for disconnect() calls */
1713                 goto re_enumerate;
1714         }
1715   
1716         if (!udev->actconfig)
1717                 return 0;
1718
1719         ret = usb_control_msg(udev, usb_sndctrlpipe(udev, 0),
1720                         USB_REQ_SET_CONFIGURATION, 0,
1721                         udev->actconfig->desc.bConfigurationValue, 0,
1722                         NULL, 0, HZ * USB_CTRL_SET_TIMEOUT);
1723         if (ret < 0) {
1724                 dev_err(&udev->dev,
1725                         "can't restore configuration #%d (error=%d)\n",
1726                         udev->actconfig->desc.bConfigurationValue, ret);
1727                 goto re_enumerate;
1728         }
1729         udev->state = USB_STATE_CONFIGURED;
1730
1731         for (i = 0; i < udev->actconfig->desc.bNumInterfaces; i++) {
1732                 struct usb_interface *intf = udev->actconfig->interface[i];
1733                 struct usb_interface_descriptor *desc;
1734
1735                 /* set_interface resets host side toggle and halt status even
1736                  * for altsetting zero.  the interface may have no driver.
1737                  */
1738                 desc = &intf->cur_altsetting->desc;
1739                 ret = usb_set_interface(udev, desc->bInterfaceNumber,
1740                         desc->bAlternateSetting);
1741                 if (ret < 0) {
1742                         dev_err(&udev->dev, "failed to restore interface %d "
1743                                 "altsetting %d (error=%d)\n",
1744                                 desc->bInterfaceNumber,
1745                                 desc->bAlternateSetting,
1746                                 ret);
1747                         goto re_enumerate;
1748                 }
1749         }
1750
1751         return 0;
1752  
1753 re_enumerate:
1754         /* FIXME make some task re-enumerate; don't just mark unusable */
1755         udev->state = USB_STATE_NOTATTACHED;
1756         return -ENODEV;
1757 }
1758 EXPORT_SYMBOL(__usb_reset_device);
1759
1760 int usb_reset_device(struct usb_device *udev)
1761 {
1762         int r;
1763         
1764         down(&udev->serialize);
1765         r = __usb_reset_device(udev);
1766         up(&udev->serialize);
1767
1768         return r;
1769 }