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