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