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