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