Merge to Fedora kernel-2.6.18-1.2224_FC5 patched with stable patch-2.6.18.1-vs2.0...
[linux-2.6.git] / drivers / usb / core / hcd.c
1 /*
2  * (C) Copyright Linus Torvalds 1999
3  * (C) Copyright Johannes Erdfelt 1999-2001
4  * (C) Copyright Andreas Gal 1999
5  * (C) Copyright Gregory P. Smith 1999
6  * (C) Copyright Deti Fliegl 1999
7  * (C) Copyright Randy Dunlap 2000
8  * (C) Copyright David Brownell 2000-2002
9  * 
10  * This program is free software; you can redistribute it and/or modify it
11  * under the terms of the GNU General Public License as published by the
12  * Free Software Foundation; either version 2 of the License, or (at your
13  * option) any later version.
14  *
15  * This program is distributed in the hope that it will be useful, but
16  * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
17  * or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
18  * for more details.
19  *
20  * You should have received a copy of the GNU General Public License
21  * along with this program; if not, write to the Free Software Foundation,
22  * Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
23  */
24
25 #include <linux/module.h>
26 #include <linux/version.h>
27 #include <linux/kernel.h>
28 #include <linux/slab.h>
29 #include <linux/completion.h>
30 #include <linux/utsname.h>
31 #include <linux/mm.h>
32 #include <asm/io.h>
33 #include <asm/scatterlist.h>
34 #include <linux/device.h>
35 #include <linux/dma-mapping.h>
36 #include <linux/mutex.h>
37 #include <asm/irq.h>
38 #include <asm/byteorder.h>
39
40 #include <linux/usb.h>
41
42 #include "usb.h"
43 #include "hcd.h"
44 #include "hub.h"
45
46
47 // #define USB_BANDWIDTH_MESSAGES
48
49 /*-------------------------------------------------------------------------*/
50
51 /*
52  * USB Host Controller Driver framework
53  *
54  * Plugs into usbcore (usb_bus) and lets HCDs share code, minimizing
55  * HCD-specific behaviors/bugs.
56  *
57  * This does error checks, tracks devices and urbs, and delegates to a
58  * "hc_driver" only for code (and data) that really needs to know about
59  * hardware differences.  That includes root hub registers, i/o queues,
60  * and so on ... but as little else as possible.
61  *
62  * Shared code includes most of the "root hub" code (these are emulated,
63  * though each HC's hardware works differently) and PCI glue, plus request
64  * tracking overhead.  The HCD code should only block on spinlocks or on
65  * hardware handshaking; blocking on software events (such as other kernel
66  * threads releasing resources, or completing actions) is all generic.
67  *
68  * Happens the USB 2.0 spec says this would be invisible inside the "USBD",
69  * and includes mostly a "HCDI" (HCD Interface) along with some APIs used
70  * only by the hub driver ... and that neither should be seen or used by
71  * usb client device drivers.
72  *
73  * Contributors of ideas or unattributed patches include: David Brownell,
74  * Roman Weissgaerber, Rory Bolt, Greg Kroah-Hartman, ...
75  *
76  * HISTORY:
77  * 2002-02-21   Pull in most of the usb_bus support from usb.c; some
78  *              associated cleanup.  "usb_hcd" still != "usb_bus".
79  * 2001-12-12   Initial patch version for Linux 2.5.1 kernel.
80  */
81
82 /*-------------------------------------------------------------------------*/
83
84 /* host controllers we manage */
85 LIST_HEAD (usb_bus_list);
86 EXPORT_SYMBOL_GPL (usb_bus_list);
87
88 /* used when allocating bus numbers */
89 #define USB_MAXBUS              64
90 struct usb_busmap {
91         unsigned long busmap [USB_MAXBUS / (8*sizeof (unsigned long))];
92 };
93 static struct usb_busmap busmap;
94
95 /* used when updating list of hcds */
96 DEFINE_MUTEX(usb_bus_list_lock);        /* exported only for usbfs */
97 EXPORT_SYMBOL_GPL (usb_bus_list_lock);
98
99 /* used for controlling access to virtual root hubs */
100 static DEFINE_SPINLOCK(hcd_root_hub_lock);
101
102 /* used when updating hcd data */
103 static DEFINE_SPINLOCK(hcd_data_lock);
104
105 /* wait queue for synchronous unlinks */
106 DECLARE_WAIT_QUEUE_HEAD(usb_kill_urb_queue);
107
108 /*-------------------------------------------------------------------------*/
109
110 /*
111  * Sharable chunks of root hub code.
112  */
113
114 /*-------------------------------------------------------------------------*/
115
116 #define KERNEL_REL      ((LINUX_VERSION_CODE >> 16) & 0x0ff)
117 #define KERNEL_VER      ((LINUX_VERSION_CODE >> 8) & 0x0ff)
118
119 /* usb 2.0 root hub device descriptor */
120 static const u8 usb2_rh_dev_descriptor [18] = {
121         0x12,       /*  __u8  bLength; */
122         0x01,       /*  __u8  bDescriptorType; Device */
123         0x00, 0x02, /*  __le16 bcdUSB; v2.0 */
124
125         0x09,       /*  __u8  bDeviceClass; HUB_CLASSCODE */
126         0x00,       /*  __u8  bDeviceSubClass; */
127         0x01,       /*  __u8  bDeviceProtocol; [ usb 2.0 single TT ]*/
128         0x40,       /*  __u8  bMaxPacketSize0; 64 Bytes */
129
130         0x00, 0x00, /*  __le16 idVendor; */
131         0x00, 0x00, /*  __le16 idProduct; */
132         KERNEL_VER, KERNEL_REL, /*  __le16 bcdDevice */
133
134         0x03,       /*  __u8  iManufacturer; */
135         0x02,       /*  __u8  iProduct; */
136         0x01,       /*  __u8  iSerialNumber; */
137         0x01        /*  __u8  bNumConfigurations; */
138 };
139
140 /* no usb 2.0 root hub "device qualifier" descriptor: one speed only */
141
142 /* usb 1.1 root hub device descriptor */
143 static const u8 usb11_rh_dev_descriptor [18] = {
144         0x12,       /*  __u8  bLength; */
145         0x01,       /*  __u8  bDescriptorType; Device */
146         0x10, 0x01, /*  __le16 bcdUSB; v1.1 */
147
148         0x09,       /*  __u8  bDeviceClass; HUB_CLASSCODE */
149         0x00,       /*  __u8  bDeviceSubClass; */
150         0x00,       /*  __u8  bDeviceProtocol; [ low/full speeds only ] */
151         0x40,       /*  __u8  bMaxPacketSize0; 64 Bytes */
152
153         0x00, 0x00, /*  __le16 idVendor; */
154         0x00, 0x00, /*  __le16 idProduct; */
155         KERNEL_VER, KERNEL_REL, /*  __le16 bcdDevice */
156
157         0x03,       /*  __u8  iManufacturer; */
158         0x02,       /*  __u8  iProduct; */
159         0x01,       /*  __u8  iSerialNumber; */
160         0x01        /*  __u8  bNumConfigurations; */
161 };
162
163
164 /*-------------------------------------------------------------------------*/
165
166 /* Configuration descriptors for our root hubs */
167
168 static const u8 fs_rh_config_descriptor [] = {
169
170         /* one configuration */
171         0x09,       /*  __u8  bLength; */
172         0x02,       /*  __u8  bDescriptorType; Configuration */
173         0x19, 0x00, /*  __le16 wTotalLength; */
174         0x01,       /*  __u8  bNumInterfaces; (1) */
175         0x01,       /*  __u8  bConfigurationValue; */
176         0x00,       /*  __u8  iConfiguration; */
177         0xc0,       /*  __u8  bmAttributes; 
178                                  Bit 7: must be set,
179                                      6: Self-powered,
180                                      5: Remote wakeup,
181                                      4..0: resvd */
182         0x00,       /*  __u8  MaxPower; */
183       
184         /* USB 1.1:
185          * USB 2.0, single TT organization (mandatory):
186          *      one interface, protocol 0
187          *
188          * USB 2.0, multiple TT organization (optional):
189          *      two interfaces, protocols 1 (like single TT)
190          *      and 2 (multiple TT mode) ... config is
191          *      sometimes settable
192          *      NOT IMPLEMENTED
193          */
194
195         /* one interface */
196         0x09,       /*  __u8  if_bLength; */
197         0x04,       /*  __u8  if_bDescriptorType; Interface */
198         0x00,       /*  __u8  if_bInterfaceNumber; */
199         0x00,       /*  __u8  if_bAlternateSetting; */
200         0x01,       /*  __u8  if_bNumEndpoints; */
201         0x09,       /*  __u8  if_bInterfaceClass; HUB_CLASSCODE */
202         0x00,       /*  __u8  if_bInterfaceSubClass; */
203         0x00,       /*  __u8  if_bInterfaceProtocol; [usb1.1 or single tt] */
204         0x00,       /*  __u8  if_iInterface; */
205      
206         /* one endpoint (status change endpoint) */
207         0x07,       /*  __u8  ep_bLength; */
208         0x05,       /*  __u8  ep_bDescriptorType; Endpoint */
209         0x81,       /*  __u8  ep_bEndpointAddress; IN Endpoint 1 */
210         0x03,       /*  __u8  ep_bmAttributes; Interrupt */
211         0x02, 0x00, /*  __le16 ep_wMaxPacketSize; 1 + (MAX_ROOT_PORTS / 8) */
212         0xff        /*  __u8  ep_bInterval; (255ms -- usb 2.0 spec) */
213 };
214
215 static const u8 hs_rh_config_descriptor [] = {
216
217         /* one configuration */
218         0x09,       /*  __u8  bLength; */
219         0x02,       /*  __u8  bDescriptorType; Configuration */
220         0x19, 0x00, /*  __le16 wTotalLength; */
221         0x01,       /*  __u8  bNumInterfaces; (1) */
222         0x01,       /*  __u8  bConfigurationValue; */
223         0x00,       /*  __u8  iConfiguration; */
224         0xc0,       /*  __u8  bmAttributes; 
225                                  Bit 7: must be set,
226                                      6: Self-powered,
227                                      5: Remote wakeup,
228                                      4..0: resvd */
229         0x00,       /*  __u8  MaxPower; */
230       
231         /* USB 1.1:
232          * USB 2.0, single TT organization (mandatory):
233          *      one interface, protocol 0
234          *
235          * USB 2.0, multiple TT organization (optional):
236          *      two interfaces, protocols 1 (like single TT)
237          *      and 2 (multiple TT mode) ... config is
238          *      sometimes settable
239          *      NOT IMPLEMENTED
240          */
241
242         /* one interface */
243         0x09,       /*  __u8  if_bLength; */
244         0x04,       /*  __u8  if_bDescriptorType; Interface */
245         0x00,       /*  __u8  if_bInterfaceNumber; */
246         0x00,       /*  __u8  if_bAlternateSetting; */
247         0x01,       /*  __u8  if_bNumEndpoints; */
248         0x09,       /*  __u8  if_bInterfaceClass; HUB_CLASSCODE */
249         0x00,       /*  __u8  if_bInterfaceSubClass; */
250         0x00,       /*  __u8  if_bInterfaceProtocol; [usb1.1 or single tt] */
251         0x00,       /*  __u8  if_iInterface; */
252      
253         /* one endpoint (status change endpoint) */
254         0x07,       /*  __u8  ep_bLength; */
255         0x05,       /*  __u8  ep_bDescriptorType; Endpoint */
256         0x81,       /*  __u8  ep_bEndpointAddress; IN Endpoint 1 */
257         0x03,       /*  __u8  ep_bmAttributes; Interrupt */
258         0x02, 0x00, /*  __le16 ep_wMaxPacketSize; 1 + (MAX_ROOT_PORTS / 8) */
259         0x0c        /*  __u8  ep_bInterval; (256ms -- usb 2.0 spec) */
260 };
261
262 /*-------------------------------------------------------------------------*/
263
264 /*
265  * helper routine for returning string descriptors in UTF-16LE
266  * input can actually be ISO-8859-1; ASCII is its 7-bit subset
267  */
268 static int ascii2utf (char *s, u8 *utf, int utfmax)
269 {
270         int retval;
271
272         for (retval = 0; *s && utfmax > 1; utfmax -= 2, retval += 2) {
273                 *utf++ = *s++;
274                 *utf++ = 0;
275         }
276         if (utfmax > 0) {
277                 *utf = *s;
278                 ++retval;
279         }
280         return retval;
281 }
282
283 /*
284  * rh_string - provides manufacturer, product and serial strings for root hub
285  * @id: the string ID number (1: serial number, 2: product, 3: vendor)
286  * @hcd: the host controller for this root hub
287  * @type: string describing our driver 
288  * @data: return packet in UTF-16 LE
289  * @len: length of the return packet
290  *
291  * Produces either a manufacturer, product or serial number string for the
292  * virtual root hub device.
293  */
294 static int rh_string (
295         int             id,
296         struct usb_hcd  *hcd,
297         u8              *data,
298         int             len
299 ) {
300         char buf [100];
301
302         // language ids
303         if (id == 0) {
304                 buf[0] = 4;    buf[1] = 3;      /* 4 bytes string data */
305                 buf[2] = 0x09; buf[3] = 0x04;   /* MSFT-speak for "en-us" */
306                 len = min (len, 4);
307                 memcpy (data, buf, len);
308                 return len;
309
310         // serial number
311         } else if (id == 1) {
312                 strlcpy (buf, hcd->self.bus_name, sizeof buf);
313
314         // product description
315         } else if (id == 2) {
316                 strlcpy (buf, hcd->product_desc, sizeof buf);
317
318         // id 3 == vendor description
319         } else if (id == 3) {
320                 snprintf (buf, sizeof buf, "%s %s %s", system_utsname.sysname,
321                         system_utsname.release, hcd->driver->description);
322
323         // unsupported IDs --> "protocol stall"
324         } else
325                 return -EPIPE;
326
327         switch (len) {          /* All cases fall through */
328         default:
329                 len = 2 + ascii2utf (buf, data + 2, len - 2);
330         case 2:
331                 data [1] = 3;   /* type == string */
332         case 1:
333                 data [0] = 2 * (strlen (buf) + 1);
334         case 0:
335                 ;               /* Compiler wants a statement here */
336         }
337         return len;
338 }
339
340
341 /* Root hub control transfers execute synchronously */
342 static int rh_call_control (struct usb_hcd *hcd, struct urb *urb)
343 {
344         struct usb_ctrlrequest *cmd;
345         u16             typeReq, wValue, wIndex, wLength;
346         u8              *ubuf = urb->transfer_buffer;
347         u8              tbuf [sizeof (struct usb_hub_descriptor)];
348         const u8        *bufp = tbuf;
349         int             len = 0;
350         int             patch_wakeup = 0;
351         unsigned long   flags;
352         int             status = 0;
353         int             n;
354
355         cmd = (struct usb_ctrlrequest *) urb->setup_packet;
356         typeReq  = (cmd->bRequestType << 8) | cmd->bRequest;
357         wValue   = le16_to_cpu (cmd->wValue);
358         wIndex   = le16_to_cpu (cmd->wIndex);
359         wLength  = le16_to_cpu (cmd->wLength);
360
361         if (wLength > urb->transfer_buffer_length)
362                 goto error;
363
364         urb->actual_length = 0;
365         switch (typeReq) {
366
367         /* DEVICE REQUESTS */
368
369         /* The root hub's remote wakeup enable bit is implemented using
370          * driver model wakeup flags.  If this system supports wakeup
371          * through USB, userspace may change the default "allow wakeup"
372          * policy through sysfs or these calls.
373          *
374          * Most root hubs support wakeup from downstream devices, for
375          * runtime power management (disabling USB clocks and reducing
376          * VBUS power usage).  However, not all of them do so; silicon,
377          * board, and BIOS bugs here are not uncommon, so these can't
378          * be treated quite like external hubs.
379          *
380          * Likewise, not all root hubs will pass wakeup events upstream,
381          * to wake up the whole system.  So don't assume root hub and
382          * controller capabilities are identical.
383          */
384
385         case DeviceRequest | USB_REQ_GET_STATUS:
386                 tbuf [0] = (device_may_wakeup(&hcd->self.root_hub->dev)
387                                         << USB_DEVICE_REMOTE_WAKEUP)
388                                 | (1 << USB_DEVICE_SELF_POWERED);
389                 tbuf [1] = 0;
390                 len = 2;
391                 break;
392         case DeviceOutRequest | USB_REQ_CLEAR_FEATURE:
393                 if (wValue == USB_DEVICE_REMOTE_WAKEUP)
394                         device_set_wakeup_enable(&hcd->self.root_hub->dev, 0);
395                 else
396                         goto error;
397                 break;
398         case DeviceOutRequest | USB_REQ_SET_FEATURE:
399                 if (device_can_wakeup(&hcd->self.root_hub->dev)
400                                 && wValue == USB_DEVICE_REMOTE_WAKEUP)
401                         device_set_wakeup_enable(&hcd->self.root_hub->dev, 1);
402                 else
403                         goto error;
404                 break;
405         case DeviceRequest | USB_REQ_GET_CONFIGURATION:
406                 tbuf [0] = 1;
407                 len = 1;
408                         /* FALLTHROUGH */
409         case DeviceOutRequest | USB_REQ_SET_CONFIGURATION:
410                 break;
411         case DeviceRequest | USB_REQ_GET_DESCRIPTOR:
412                 switch (wValue & 0xff00) {
413                 case USB_DT_DEVICE << 8:
414                         if (hcd->driver->flags & HCD_USB2)
415                                 bufp = usb2_rh_dev_descriptor;
416                         else if (hcd->driver->flags & HCD_USB11)
417                                 bufp = usb11_rh_dev_descriptor;
418                         else
419                                 goto error;
420                         len = 18;
421                         break;
422                 case USB_DT_CONFIG << 8:
423                         if (hcd->driver->flags & HCD_USB2) {
424                                 bufp = hs_rh_config_descriptor;
425                                 len = sizeof hs_rh_config_descriptor;
426                         } else {
427                                 bufp = fs_rh_config_descriptor;
428                                 len = sizeof fs_rh_config_descriptor;
429                         }
430                         if (device_can_wakeup(&hcd->self.root_hub->dev))
431                                 patch_wakeup = 1;
432                         break;
433                 case USB_DT_STRING << 8:
434                         n = rh_string (wValue & 0xff, hcd, ubuf, wLength);
435                         if (n < 0)
436                                 goto error;
437                         urb->actual_length = n;
438                         break;
439                 default:
440                         goto error;
441                 }
442                 break;
443         case DeviceRequest | USB_REQ_GET_INTERFACE:
444                 tbuf [0] = 0;
445                 len = 1;
446                         /* FALLTHROUGH */
447         case DeviceOutRequest | USB_REQ_SET_INTERFACE:
448                 break;
449         case DeviceOutRequest | USB_REQ_SET_ADDRESS:
450                 // wValue == urb->dev->devaddr
451                 dev_dbg (hcd->self.controller, "root hub device address %d\n",
452                         wValue);
453                 break;
454
455         /* INTERFACE REQUESTS (no defined feature/status flags) */
456
457         /* ENDPOINT REQUESTS */
458
459         case EndpointRequest | USB_REQ_GET_STATUS:
460                 // ENDPOINT_HALT flag
461                 tbuf [0] = 0;
462                 tbuf [1] = 0;
463                 len = 2;
464                         /* FALLTHROUGH */
465         case EndpointOutRequest | USB_REQ_CLEAR_FEATURE:
466         case EndpointOutRequest | USB_REQ_SET_FEATURE:
467                 dev_dbg (hcd->self.controller, "no endpoint features yet\n");
468                 break;
469
470         /* CLASS REQUESTS (and errors) */
471
472         default:
473                 /* non-generic request */
474                 switch (typeReq) {
475                 case GetHubStatus:
476                 case GetPortStatus:
477                         len = 4;
478                         break;
479                 case GetHubDescriptor:
480                         len = sizeof (struct usb_hub_descriptor);
481                         break;
482                 }
483                 status = hcd->driver->hub_control (hcd,
484                         typeReq, wValue, wIndex,
485                         tbuf, wLength);
486                 break;
487 error:
488                 /* "protocol stall" on error */
489                 status = -EPIPE;
490         }
491
492         if (status) {
493                 len = 0;
494                 if (status != -EPIPE) {
495                         dev_dbg (hcd->self.controller,
496                                 "CTRL: TypeReq=0x%x val=0x%x "
497                                 "idx=0x%x len=%d ==> %d\n",
498                                 typeReq, wValue, wIndex,
499                                 wLength, status);
500                 }
501         }
502         if (len) {
503                 if (urb->transfer_buffer_length < len)
504                         len = urb->transfer_buffer_length;
505                 urb->actual_length = len;
506                 // always USB_DIR_IN, toward host
507                 memcpy (ubuf, bufp, len);
508
509                 /* report whether RH hardware supports remote wakeup */
510                 if (patch_wakeup &&
511                                 len > offsetof (struct usb_config_descriptor,
512                                                 bmAttributes))
513                         ((struct usb_config_descriptor *)ubuf)->bmAttributes
514                                 |= USB_CONFIG_ATT_WAKEUP;
515         }
516
517         /* any errors get returned through the urb completion */
518         local_irq_save (flags);
519         spin_lock (&urb->lock);
520         if (urb->status == -EINPROGRESS)
521                 urb->status = status;
522         spin_unlock (&urb->lock);
523         usb_hcd_giveback_urb (hcd, urb, NULL);
524         local_irq_restore (flags);
525         return 0;
526 }
527
528 /*-------------------------------------------------------------------------*/
529
530 /*
531  * Root Hub interrupt transfers are polled using a timer if the
532  * driver requests it; otherwise the driver is responsible for
533  * calling usb_hcd_poll_rh_status() when an event occurs.
534  *
535  * Completions are called in_interrupt(), but they may or may not
536  * be in_irq().
537  */
538 void usb_hcd_poll_rh_status(struct usb_hcd *hcd)
539 {
540         struct urb      *urb;
541         int             length;
542         unsigned long   flags;
543         char            buffer[4];      /* Any root hubs with > 31 ports? */
544
545         if (!hcd->uses_new_polling && !hcd->status_urb)
546                 return;
547
548         length = hcd->driver->hub_status_data(hcd, buffer);
549         if (length > 0) {
550
551                 /* try to complete the status urb */
552                 local_irq_save (flags);
553                 spin_lock(&hcd_root_hub_lock);
554                 urb = hcd->status_urb;
555                 if (urb) {
556                         spin_lock(&urb->lock);
557                         if (urb->status == -EINPROGRESS) {
558                                 hcd->poll_pending = 0;
559                                 hcd->status_urb = NULL;
560                                 urb->status = 0;
561                                 urb->hcpriv = NULL;
562                                 urb->actual_length = length;
563                                 memcpy(urb->transfer_buffer, buffer, length);
564                         } else          /* urb has been unlinked */
565                                 length = 0;
566                         spin_unlock(&urb->lock);
567                 } else
568                         length = 0;
569                 spin_unlock(&hcd_root_hub_lock);
570
571                 /* local irqs are always blocked in completions */
572                 if (length > 0)
573                         usb_hcd_giveback_urb (hcd, urb, NULL);
574                 else
575                         hcd->poll_pending = 1;
576                 local_irq_restore (flags);
577         }
578
579         /* The USB 2.0 spec says 256 ms.  This is close enough and won't
580          * exceed that limit if HZ is 100. */
581         if (hcd->uses_new_polling ? hcd->poll_rh :
582                         (length == 0 && hcd->status_urb != NULL))
583                 mod_timer (&hcd->rh_timer, jiffies + msecs_to_jiffies(250));
584 }
585 EXPORT_SYMBOL_GPL(usb_hcd_poll_rh_status);
586
587 /* timer callback */
588 static void rh_timer_func (unsigned long _hcd)
589 {
590         usb_hcd_poll_rh_status((struct usb_hcd *) _hcd);
591 }
592
593 /*-------------------------------------------------------------------------*/
594
595 static int rh_queue_status (struct usb_hcd *hcd, struct urb *urb)
596 {
597         int             retval;
598         unsigned long   flags;
599         int             len = 1 + (urb->dev->maxchild / 8);
600
601         spin_lock_irqsave (&hcd_root_hub_lock, flags);
602         if (urb->status != -EINPROGRESS)        /* already unlinked */
603                 retval = urb->status;
604         else if (hcd->status_urb || urb->transfer_buffer_length < len) {
605                 dev_dbg (hcd->self.controller, "not queuing rh status urb\n");
606                 retval = -EINVAL;
607         } else {
608                 hcd->status_urb = urb;
609                 urb->hcpriv = hcd;      /* indicate it's queued */
610
611                 if (!hcd->uses_new_polling)
612                         mod_timer (&hcd->rh_timer, jiffies +
613                                         msecs_to_jiffies(250));
614
615                 /* If a status change has already occurred, report it ASAP */
616                 else if (hcd->poll_pending)
617                         mod_timer (&hcd->rh_timer, jiffies);
618                 retval = 0;
619         }
620         spin_unlock_irqrestore (&hcd_root_hub_lock, flags);
621         return retval;
622 }
623
624 static int rh_urb_enqueue (struct usb_hcd *hcd, struct urb *urb)
625 {
626         if (usb_pipeint (urb->pipe))
627                 return rh_queue_status (hcd, urb);
628         if (usb_pipecontrol (urb->pipe))
629                 return rh_call_control (hcd, urb);
630         return -EINVAL;
631 }
632
633 /*-------------------------------------------------------------------------*/
634
635 /* Asynchronous unlinks of root-hub control URBs are legal, but they
636  * don't do anything.  Status URB unlinks must be made in process context
637  * with interrupts enabled.
638  */
639 static int usb_rh_urb_dequeue (struct usb_hcd *hcd, struct urb *urb)
640 {
641         if (usb_pipeendpoint(urb->pipe) == 0) { /* Control URB */
642                 if (in_interrupt())
643                         return 0;               /* nothing to do */
644
645                 spin_lock_irq(&urb->lock);      /* from usb_kill_urb */
646                 ++urb->reject;
647                 spin_unlock_irq(&urb->lock);
648
649                 wait_event(usb_kill_urb_queue,
650                                 atomic_read(&urb->use_count) == 0);
651
652                 spin_lock_irq(&urb->lock);
653                 --urb->reject;
654                 spin_unlock_irq(&urb->lock);
655
656         } else {                                /* Status URB */
657                 if (!hcd->uses_new_polling)
658                         del_timer_sync (&hcd->rh_timer);
659                 local_irq_disable ();
660                 spin_lock (&hcd_root_hub_lock);
661                 if (urb == hcd->status_urb) {
662                         hcd->status_urb = NULL;
663                         urb->hcpriv = NULL;
664                 } else
665                         urb = NULL;             /* wasn't fully queued */
666                 spin_unlock (&hcd_root_hub_lock);
667                 if (urb)
668                         usb_hcd_giveback_urb (hcd, urb, NULL);
669                 local_irq_enable ();
670         }
671
672         return 0;
673 }
674
675 /*-------------------------------------------------------------------------*/
676
677 /* exported only within usbcore */
678 struct usb_bus *usb_bus_get(struct usb_bus *bus)
679 {
680         if (bus)
681                 kref_get(&bus->kref);
682         return bus;
683 }
684
685 static void usb_host_release(struct kref *kref)
686 {
687         struct usb_bus *bus = container_of(kref, struct usb_bus, kref);
688
689         if (bus->release)
690                 bus->release(bus);
691 }
692
693 /* exported only within usbcore */
694 void usb_bus_put(struct usb_bus *bus)
695 {
696         if (bus)
697                 kref_put(&bus->kref, usb_host_release);
698 }
699
700 /*-------------------------------------------------------------------------*/
701
702 static struct class *usb_host_class;
703
704 int usb_host_init(void)
705 {
706         int retval = 0;
707
708         usb_host_class = class_create(THIS_MODULE, "usb_host");
709         if (IS_ERR(usb_host_class))
710                 retval = PTR_ERR(usb_host_class);
711         return retval;
712 }
713
714 void usb_host_cleanup(void)
715 {
716         class_destroy(usb_host_class);
717 }
718
719 /**
720  * usb_bus_init - shared initialization code
721  * @bus: the bus structure being initialized
722  *
723  * This code is used to initialize a usb_bus structure, memory for which is
724  * separately managed.
725  */
726 static void usb_bus_init (struct usb_bus *bus)
727 {
728         memset (&bus->devmap, 0, sizeof(struct usb_devmap));
729
730         bus->devnum_next = 1;
731
732         bus->root_hub = NULL;
733         bus->hcpriv = NULL;
734         bus->busnum = -1;
735         bus->bandwidth_allocated = 0;
736         bus->bandwidth_int_reqs  = 0;
737         bus->bandwidth_isoc_reqs = 0;
738
739         INIT_LIST_HEAD (&bus->bus_list);
740
741         kref_init(&bus->kref);
742 }
743
744 /**
745  * usb_alloc_bus - creates a new USB host controller structure
746  * @op: pointer to a struct usb_operations that this bus structure should use
747  * Context: !in_interrupt()
748  *
749  * Creates a USB host controller bus structure with the specified 
750  * usb_operations and initializes all the necessary internal objects.
751  *
752  * If no memory is available, NULL is returned.
753  *
754  * The caller should call usb_put_bus() when it is finished with the structure.
755  */
756 struct usb_bus *usb_alloc_bus (struct usb_operations *op)
757 {
758         struct usb_bus *bus;
759
760         bus = kzalloc (sizeof *bus, GFP_KERNEL);
761         if (!bus)
762                 return NULL;
763         usb_bus_init (bus);
764         bus->op = op;
765         return bus;
766 }
767
768 /*-------------------------------------------------------------------------*/
769
770 /**
771  * usb_register_bus - registers the USB host controller with the usb core
772  * @bus: pointer to the bus to register
773  * Context: !in_interrupt()
774  *
775  * Assigns a bus number, and links the controller into usbcore data
776  * structures so that it can be seen by scanning the bus list.
777  */
778 static int usb_register_bus(struct usb_bus *bus)
779 {
780         int busnum;
781
782         mutex_lock(&usb_bus_list_lock);
783         busnum = find_next_zero_bit (busmap.busmap, USB_MAXBUS, 1);
784         if (busnum < USB_MAXBUS) {
785                 set_bit (busnum, busmap.busmap);
786                 bus->busnum = busnum;
787         } else {
788                 printk (KERN_ERR "%s: too many buses\n", usbcore_name);
789                 mutex_unlock(&usb_bus_list_lock);
790                 return -E2BIG;
791         }
792
793         bus->class_dev = class_device_create(usb_host_class, NULL, MKDEV(0,0),
794                                              bus->controller, "usb_host%d", busnum);
795         if (IS_ERR(bus->class_dev)) {
796                 clear_bit(busnum, busmap.busmap);
797                 mutex_unlock(&usb_bus_list_lock);
798                 return PTR_ERR(bus->class_dev);
799         }
800
801         class_set_devdata(bus->class_dev, bus);
802
803         /* Add it to the local list of buses */
804         list_add (&bus->bus_list, &usb_bus_list);
805         mutex_unlock(&usb_bus_list_lock);
806
807         usb_notify_add_bus(bus);
808
809         dev_info (bus->controller, "new USB bus registered, assigned bus number %d\n", bus->busnum);
810         return 0;
811 }
812
813 /**
814  * usb_deregister_bus - deregisters the USB host controller
815  * @bus: pointer to the bus to deregister
816  * Context: !in_interrupt()
817  *
818  * Recycles the bus number, and unlinks the controller from usbcore data
819  * structures so that it won't be seen by scanning the bus list.
820  */
821 static void usb_deregister_bus (struct usb_bus *bus)
822 {
823         dev_info (bus->controller, "USB bus %d deregistered\n", bus->busnum);
824
825         /*
826          * NOTE: make sure that all the devices are removed by the
827          * controller code, as well as having it call this when cleaning
828          * itself up
829          */
830         mutex_lock(&usb_bus_list_lock);
831         list_del (&bus->bus_list);
832         mutex_unlock(&usb_bus_list_lock);
833
834         usb_notify_remove_bus(bus);
835
836         clear_bit (bus->busnum, busmap.busmap);
837
838         class_device_unregister(bus->class_dev);
839 }
840
841 /**
842  * register_root_hub - called by usb_add_hcd() to register a root hub
843  * @hcd: host controller for this root hub
844  *
845  * This function registers the root hub with the USB subsystem.  It sets up
846  * the device properly in the device tree and then calls usb_new_device()
847  * to register the usb device.  It also assigns the root hub's USB address
848  * (always 1).
849  */
850 static int register_root_hub(struct usb_hcd *hcd)
851 {
852         struct device *parent_dev = hcd->self.controller;
853         struct usb_device *usb_dev = hcd->self.root_hub;
854         const int devnum = 1;
855         int retval;
856
857         usb_dev->devnum = devnum;
858         usb_dev->bus->devnum_next = devnum + 1;
859         memset (&usb_dev->bus->devmap.devicemap, 0,
860                         sizeof usb_dev->bus->devmap.devicemap);
861         set_bit (devnum, usb_dev->bus->devmap.devicemap);
862         usb_set_device_state(usb_dev, USB_STATE_ADDRESS);
863
864         mutex_lock(&usb_bus_list_lock);
865
866         usb_dev->ep0.desc.wMaxPacketSize = __constant_cpu_to_le16(64);
867         retval = usb_get_device_descriptor(usb_dev, USB_DT_DEVICE_SIZE);
868         if (retval != sizeof usb_dev->descriptor) {
869                 mutex_unlock(&usb_bus_list_lock);
870                 dev_dbg (parent_dev, "can't read %s device descriptor %d\n",
871                                 usb_dev->dev.bus_id, retval);
872                 return (retval < 0) ? retval : -EMSGSIZE;
873         }
874
875         retval = usb_new_device (usb_dev);
876         if (retval) {
877                 dev_err (parent_dev, "can't register root hub for %s, %d\n",
878                                 usb_dev->dev.bus_id, retval);
879         }
880         mutex_unlock(&usb_bus_list_lock);
881
882         if (retval == 0) {
883                 spin_lock_irq (&hcd_root_hub_lock);
884                 hcd->rh_registered = 1;
885                 spin_unlock_irq (&hcd_root_hub_lock);
886
887                 /* Did the HC die before the root hub was registered? */
888                 if (hcd->state == HC_STATE_HALT)
889                         usb_hc_died (hcd);      /* This time clean up */
890         }
891
892         return retval;
893 }
894
895 void usb_enable_root_hub_irq (struct usb_bus *bus)
896 {
897         struct usb_hcd *hcd;
898
899         hcd = container_of (bus, struct usb_hcd, self);
900         if (hcd->driver->hub_irq_enable && !hcd->poll_rh &&
901                         hcd->state != HC_STATE_HALT)
902                 hcd->driver->hub_irq_enable (hcd);
903 }
904
905
906 /*-------------------------------------------------------------------------*/
907
908 /**
909  * usb_calc_bus_time - approximate periodic transaction time in nanoseconds
910  * @speed: from dev->speed; USB_SPEED_{LOW,FULL,HIGH}
911  * @is_input: true iff the transaction sends data to the host
912  * @isoc: true for isochronous transactions, false for interrupt ones
913  * @bytecount: how many bytes in the transaction.
914  *
915  * Returns approximate bus time in nanoseconds for a periodic transaction.
916  * See USB 2.0 spec section 5.11.3; only periodic transfers need to be
917  * scheduled in software, this function is only used for such scheduling.
918  */
919 long usb_calc_bus_time (int speed, int is_input, int isoc, int bytecount)
920 {
921         unsigned long   tmp;
922
923         switch (speed) {
924         case USB_SPEED_LOW:     /* INTR only */
925                 if (is_input) {
926                         tmp = (67667L * (31L + 10L * BitTime (bytecount))) / 1000L;
927                         return (64060L + (2 * BW_HUB_LS_SETUP) + BW_HOST_DELAY + tmp);
928                 } else {
929                         tmp = (66700L * (31L + 10L * BitTime (bytecount))) / 1000L;
930                         return (64107L + (2 * BW_HUB_LS_SETUP) + BW_HOST_DELAY + tmp);
931                 }
932         case USB_SPEED_FULL:    /* ISOC or INTR */
933                 if (isoc) {
934                         tmp = (8354L * (31L + 10L * BitTime (bytecount))) / 1000L;
935                         return (((is_input) ? 7268L : 6265L) + BW_HOST_DELAY + tmp);
936                 } else {
937                         tmp = (8354L * (31L + 10L * BitTime (bytecount))) / 1000L;
938                         return (9107L + BW_HOST_DELAY + tmp);
939                 }
940         case USB_SPEED_HIGH:    /* ISOC or INTR */
941                 // FIXME adjust for input vs output
942                 if (isoc)
943                         tmp = HS_NSECS_ISO (bytecount);
944                 else
945                         tmp = HS_NSECS (bytecount);
946                 return tmp;
947         default:
948                 pr_debug ("%s: bogus device speed!\n", usbcore_name);
949                 return -1;
950         }
951 }
952 EXPORT_SYMBOL (usb_calc_bus_time);
953
954 /*
955  * usb_check_bandwidth():
956  *
957  * old_alloc is from host_controller->bandwidth_allocated in microseconds;
958  * bustime is from calc_bus_time(), but converted to microseconds.
959  *
960  * returns <bustime in us> if successful,
961  * or -ENOSPC if bandwidth request fails.
962  *
963  * FIXME:
964  * This initial implementation does not use Endpoint.bInterval
965  * in managing bandwidth allocation.
966  * It probably needs to be expanded to use Endpoint.bInterval.
967  * This can be done as a later enhancement (correction).
968  *
969  * This will also probably require some kind of
970  * frame allocation tracking...meaning, for example,
971  * that if multiple drivers request interrupts every 10 USB frames,
972  * they don't all have to be allocated at
973  * frame numbers N, N+10, N+20, etc.  Some of them could be at
974  * N+11, N+21, N+31, etc., and others at
975  * N+12, N+22, N+32, etc.
976  *
977  * Similarly for isochronous transfers...
978  *
979  * Individual HCDs can schedule more directly ... this logic
980  * is not correct for high speed transfers.
981  */
982 int usb_check_bandwidth (struct usb_device *dev, struct urb *urb)
983 {
984         unsigned int    pipe = urb->pipe;
985         long            bustime;
986         int             is_in = usb_pipein (pipe);
987         int             is_iso = usb_pipeisoc (pipe);
988         int             old_alloc = dev->bus->bandwidth_allocated;
989         int             new_alloc;
990
991
992         bustime = NS_TO_US (usb_calc_bus_time (dev->speed, is_in, is_iso,
993                         usb_maxpacket (dev, pipe, !is_in)));
994         if (is_iso)
995                 bustime /= urb->number_of_packets;
996
997         new_alloc = old_alloc + (int) bustime;
998         if (new_alloc > FRAME_TIME_MAX_USECS_ALLOC) {
999 #ifdef  DEBUG
1000                 char    *mode = 
1001 #ifdef CONFIG_USB_BANDWIDTH
1002                         "";
1003 #else
1004                         "would have ";
1005 #endif
1006                 dev_dbg (&dev->dev, "usb_check_bandwidth %sFAILED: %d + %ld = %d usec\n",
1007                         mode, old_alloc, bustime, new_alloc);
1008 #endif
1009 #ifdef CONFIG_USB_BANDWIDTH
1010                 bustime = -ENOSPC;      /* report error */
1011 #endif
1012         }
1013
1014         return bustime;
1015 }
1016 EXPORT_SYMBOL (usb_check_bandwidth);
1017
1018
1019 /**
1020  * usb_claim_bandwidth - records bandwidth for a periodic transfer
1021  * @dev: source/target of request
1022  * @urb: request (urb->dev == dev)
1023  * @bustime: bandwidth consumed, in (average) microseconds per frame
1024  * @isoc: true iff the request is isochronous
1025  *
1026  * Bus bandwidth reservations are recorded purely for diagnostic purposes.
1027  * HCDs are expected not to overcommit periodic bandwidth, and to record such
1028  * reservations whenever endpoints are added to the periodic schedule.
1029  *
1030  * FIXME averaging per-frame is suboptimal.  Better to sum over the HCD's
1031  * entire periodic schedule ... 32 frames for OHCI, 1024 for UHCI, settable
1032  * for EHCI (256/512/1024 frames, default 1024) and have the bus expose how
1033  * large its periodic schedule is.
1034  */
1035 void usb_claim_bandwidth (struct usb_device *dev, struct urb *urb, int bustime, int isoc)
1036 {
1037         dev->bus->bandwidth_allocated += bustime;
1038         if (isoc)
1039                 dev->bus->bandwidth_isoc_reqs++;
1040         else
1041                 dev->bus->bandwidth_int_reqs++;
1042         urb->bandwidth = bustime;
1043
1044 #ifdef USB_BANDWIDTH_MESSAGES
1045         dev_dbg (&dev->dev, "bandwidth alloc increased by %d (%s) to %d for %d requesters\n",
1046                 bustime,
1047                 isoc ? "ISOC" : "INTR",
1048                 dev->bus->bandwidth_allocated,
1049                 dev->bus->bandwidth_int_reqs + dev->bus->bandwidth_isoc_reqs);
1050 #endif
1051 }
1052 EXPORT_SYMBOL (usb_claim_bandwidth);
1053
1054
1055 /**
1056  * usb_release_bandwidth - reverses effect of usb_claim_bandwidth()
1057  * @dev: source/target of request
1058  * @urb: request (urb->dev == dev)
1059  * @isoc: true iff the request is isochronous
1060  *
1061  * This records that previously allocated bandwidth has been released.
1062  * Bandwidth is released when endpoints are removed from the host controller's
1063  * periodic schedule.
1064  */
1065 void usb_release_bandwidth (struct usb_device *dev, struct urb *urb, int isoc)
1066 {
1067         dev->bus->bandwidth_allocated -= urb->bandwidth;
1068         if (isoc)
1069                 dev->bus->bandwidth_isoc_reqs--;
1070         else
1071                 dev->bus->bandwidth_int_reqs--;
1072
1073 #ifdef USB_BANDWIDTH_MESSAGES
1074         dev_dbg (&dev->dev, "bandwidth alloc reduced by %d (%s) to %d for %d requesters\n",
1075                 urb->bandwidth,
1076                 isoc ? "ISOC" : "INTR",
1077                 dev->bus->bandwidth_allocated,
1078                 dev->bus->bandwidth_int_reqs + dev->bus->bandwidth_isoc_reqs);
1079 #endif
1080         urb->bandwidth = 0;
1081 }
1082 EXPORT_SYMBOL (usb_release_bandwidth);
1083
1084
1085 /*-------------------------------------------------------------------------*/
1086
1087 /*
1088  * Generic HC operations.
1089  */
1090
1091 /*-------------------------------------------------------------------------*/
1092
1093 static void urb_unlink (struct urb *urb)
1094 {
1095         unsigned long           flags;
1096
1097         /* Release any periodic transfer bandwidth */
1098         if (urb->bandwidth)
1099                 usb_release_bandwidth (urb->dev, urb,
1100                         usb_pipeisoc (urb->pipe));
1101
1102         /* clear all state linking urb to this dev (and hcd) */
1103
1104         spin_lock_irqsave (&hcd_data_lock, flags);
1105         list_del_init (&urb->urb_list);
1106         spin_unlock_irqrestore (&hcd_data_lock, flags);
1107 }
1108
1109
1110 /* may be called in any context with a valid urb->dev usecount
1111  * caller surrenders "ownership" of urb
1112  * expects usb_submit_urb() to have sanity checked and conditioned all
1113  * inputs in the urb
1114  */
1115 static int hcd_submit_urb (struct urb *urb, gfp_t mem_flags)
1116 {
1117         int                     status;
1118         struct usb_hcd          *hcd = urb->dev->bus->hcpriv;
1119         struct usb_host_endpoint *ep;
1120         unsigned long           flags;
1121
1122         if (!hcd)
1123                 return -ENODEV;
1124
1125         usbmon_urb_submit(&hcd->self, urb);
1126
1127         /*
1128          * Atomically queue the urb,  first to our records, then to the HCD.
1129          * Access to urb->status is controlled by urb->lock ... changes on
1130          * i/o completion (normal or fault) or unlinking.
1131          */
1132
1133         // FIXME:  verify that quiescing hc works right (RH cleans up)
1134
1135         spin_lock_irqsave (&hcd_data_lock, flags);
1136         ep = (usb_pipein(urb->pipe) ? urb->dev->ep_in : urb->dev->ep_out)
1137                         [usb_pipeendpoint(urb->pipe)];
1138         if (unlikely (!ep))
1139                 status = -ENOENT;
1140         else if (unlikely (urb->reject))
1141                 status = -EPERM;
1142         else switch (hcd->state) {
1143         case HC_STATE_RUNNING:
1144         case HC_STATE_RESUMING:
1145 doit:
1146                 list_add_tail (&urb->urb_list, &ep->urb_list);
1147                 status = 0;
1148                 break;
1149         case HC_STATE_SUSPENDED:
1150                 /* HC upstream links (register access, wakeup signaling) can work
1151                  * even when the downstream links (and DMA etc) are quiesced; let
1152                  * usbcore talk to the root hub.
1153                  */
1154                 if (hcd->self.controller->power.power_state.event == PM_EVENT_ON
1155                                 && urb->dev->parent == NULL)
1156                         goto doit;
1157                 /* FALL THROUGH */
1158         default:
1159                 status = -ESHUTDOWN;
1160                 break;
1161         }
1162         spin_unlock_irqrestore (&hcd_data_lock, flags);
1163         if (status) {
1164                 INIT_LIST_HEAD (&urb->urb_list);
1165                 usbmon_urb_submit_error(&hcd->self, urb, status);
1166                 return status;
1167         }
1168
1169         /* increment urb's reference count as part of giving it to the HCD
1170          * (which now controls it).  HCD guarantees that it either returns
1171          * an error or calls giveback(), but not both.
1172          */
1173         urb = usb_get_urb (urb);
1174         atomic_inc (&urb->use_count);
1175
1176         if (urb->dev == hcd->self.root_hub) {
1177                 /* NOTE:  requirement on hub callers (usbfs and the hub
1178                  * driver, for now) that URBs' urb->transfer_buffer be
1179                  * valid and usb_buffer_{sync,unmap}() not be needed, since
1180                  * they could clobber root hub response data.
1181                  */
1182                 status = rh_urb_enqueue (hcd, urb);
1183                 goto done;
1184         }
1185
1186         /* lower level hcd code should use *_dma exclusively,
1187          * unless it uses pio or talks to another transport.
1188          */
1189         if (hcd->self.controller->dma_mask) {
1190                 if (usb_pipecontrol (urb->pipe)
1191                         && !(urb->transfer_flags & URB_NO_SETUP_DMA_MAP))
1192                         urb->setup_dma = dma_map_single (
1193                                         hcd->self.controller,
1194                                         urb->setup_packet,
1195                                         sizeof (struct usb_ctrlrequest),
1196                                         DMA_TO_DEVICE);
1197                 if (urb->transfer_buffer_length != 0
1198                         && !(urb->transfer_flags & URB_NO_TRANSFER_DMA_MAP))
1199                         urb->transfer_dma = dma_map_single (
1200                                         hcd->self.controller,
1201                                         urb->transfer_buffer,
1202                                         urb->transfer_buffer_length,
1203                                         usb_pipein (urb->pipe)
1204                                             ? DMA_FROM_DEVICE
1205                                             : DMA_TO_DEVICE);
1206         }
1207
1208         status = hcd->driver->urb_enqueue (hcd, ep, urb, mem_flags);
1209 done:
1210         if (unlikely (status)) {
1211                 urb_unlink (urb);
1212                 atomic_dec (&urb->use_count);
1213                 if (urb->reject)
1214                         wake_up (&usb_kill_urb_queue);
1215                 usb_put_urb (urb);
1216                 usbmon_urb_submit_error(&hcd->self, urb, status);
1217         }
1218         return status;
1219 }
1220
1221 /*-------------------------------------------------------------------------*/
1222
1223 /* called in any context */
1224 static int hcd_get_frame_number (struct usb_device *udev)
1225 {
1226         struct usb_hcd  *hcd = (struct usb_hcd *)udev->bus->hcpriv;
1227         if (!HC_IS_RUNNING (hcd->state))
1228                 return -ESHUTDOWN;
1229         return hcd->driver->get_frame_number (hcd);
1230 }
1231
1232 /*-------------------------------------------------------------------------*/
1233
1234 /* this makes the hcd giveback() the urb more quickly, by kicking it
1235  * off hardware queues (which may take a while) and returning it as
1236  * soon as practical.  we've already set up the urb's return status,
1237  * but we can't know if the callback completed already.
1238  */
1239 static int
1240 unlink1 (struct usb_hcd *hcd, struct urb *urb)
1241 {
1242         int             value;
1243
1244         if (urb->dev == hcd->self.root_hub)
1245                 value = usb_rh_urb_dequeue (hcd, urb);
1246         else {
1247
1248                 /* The only reason an HCD might fail this call is if
1249                  * it has not yet fully queued the urb to begin with.
1250                  * Such failures should be harmless. */
1251                 value = hcd->driver->urb_dequeue (hcd, urb);
1252         }
1253
1254         if (value != 0)
1255                 dev_dbg (hcd->self.controller, "dequeue %p --> %d\n",
1256                                 urb, value);
1257         return value;
1258 }
1259
1260 /*
1261  * called in any context
1262  *
1263  * caller guarantees urb won't be recycled till both unlink()
1264  * and the urb's completion function return
1265  */
1266 static int hcd_unlink_urb (struct urb *urb, int status)
1267 {
1268         struct usb_host_endpoint        *ep;
1269         struct usb_hcd                  *hcd = NULL;
1270         struct device                   *sys = NULL;
1271         unsigned long                   flags;
1272         struct list_head                *tmp;
1273         int                             retval;
1274
1275         if (!urb)
1276                 return -EINVAL;
1277         if (!urb->dev || !urb->dev->bus)
1278                 return -ENODEV;
1279         ep = (usb_pipein(urb->pipe) ? urb->dev->ep_in : urb->dev->ep_out)
1280                         [usb_pipeendpoint(urb->pipe)];
1281         if (!ep)
1282                 return -ENODEV;
1283
1284         /*
1285          * we contend for urb->status with the hcd core,
1286          * which changes it while returning the urb.
1287          *
1288          * Caller guaranteed that the urb pointer hasn't been freed, and
1289          * that it was submitted.  But as a rule it can't know whether or
1290          * not it's already been unlinked ... so we respect the reversed
1291          * lock sequence needed for the usb_hcd_giveback_urb() code paths
1292          * (urb lock, then hcd_data_lock) in case some other CPU is now
1293          * unlinking it.
1294          */
1295         spin_lock_irqsave (&urb->lock, flags);
1296         spin_lock (&hcd_data_lock);
1297
1298         sys = &urb->dev->dev;
1299         hcd = urb->dev->bus->hcpriv;
1300         if (hcd == NULL) {
1301                 retval = -ENODEV;
1302                 goto done;
1303         }
1304
1305         /* insist the urb is still queued */
1306         list_for_each(tmp, &ep->urb_list) {
1307                 if (tmp == &urb->urb_list)
1308                         break;
1309         }
1310         if (tmp != &urb->urb_list) {
1311                 retval = -EIDRM;
1312                 goto done;
1313         }
1314
1315         /* Any status except -EINPROGRESS means something already started to
1316          * unlink this URB from the hardware.  So there's no more work to do.
1317          */
1318         if (urb->status != -EINPROGRESS) {
1319                 retval = -EBUSY;
1320                 goto done;
1321         }
1322
1323         /* IRQ setup can easily be broken so that USB controllers
1324          * never get completion IRQs ... maybe even the ones we need to
1325          * finish unlinking the initial failed usb_set_address()
1326          * or device descriptor fetch.
1327          */
1328         if (!test_bit(HCD_FLAG_SAW_IRQ, &hcd->flags)
1329             && hcd->self.root_hub != urb->dev) {
1330                 dev_warn (hcd->self.controller, "Unlink after no-IRQ?  "
1331                         "Controller is probably using the wrong IRQ."
1332                         "\n");
1333                 set_bit(HCD_FLAG_SAW_IRQ, &hcd->flags);
1334         }
1335
1336         urb->status = status;
1337
1338         spin_unlock (&hcd_data_lock);
1339         spin_unlock_irqrestore (&urb->lock, flags);
1340
1341         retval = unlink1 (hcd, urb);
1342         if (retval == 0)
1343                 retval = -EINPROGRESS;
1344         return retval;
1345
1346 done:
1347         spin_unlock (&hcd_data_lock);
1348         spin_unlock_irqrestore (&urb->lock, flags);
1349         if (retval != -EIDRM && sys && sys->driver)
1350                 dev_dbg (sys, "hcd_unlink_urb %p fail %d\n", urb, retval);
1351         return retval;
1352 }
1353
1354 /*-------------------------------------------------------------------------*/
1355
1356 /* disables the endpoint: cancels any pending urbs, then synchronizes with
1357  * the hcd to make sure all endpoint state is gone from hardware. use for
1358  * set_configuration, set_interface, driver removal, physical disconnect.
1359  *
1360  * example:  a qh stored in ep->hcpriv, holding state related to endpoint
1361  * type, maxpacket size, toggle, halt status, and scheduling.
1362  */
1363 static void
1364 hcd_endpoint_disable (struct usb_device *udev, struct usb_host_endpoint *ep)
1365 {
1366         struct usb_hcd          *hcd;
1367         struct urb              *urb;
1368
1369         hcd = udev->bus->hcpriv;
1370
1371         WARN_ON (!HC_IS_RUNNING (hcd->state) && hcd->state != HC_STATE_HALT &&
1372                         udev->state != USB_STATE_NOTATTACHED);
1373
1374         local_irq_disable ();
1375
1376         /* FIXME move most of this into message.c as part of its
1377          * endpoint disable logic
1378          */
1379
1380         /* ep is already gone from udev->ep_{in,out}[]; no more submits */
1381 rescan:
1382         spin_lock (&hcd_data_lock);
1383         list_for_each_entry (urb, &ep->urb_list, urb_list) {
1384                 int     tmp;
1385
1386                 /* another cpu may be in hcd, spinning on hcd_data_lock
1387                  * to giveback() this urb.  the races here should be
1388                  * small, but a full fix needs a new "can't submit"
1389                  * urb state.
1390                  * FIXME urb->reject should allow that...
1391                  */
1392                 if (urb->status != -EINPROGRESS)
1393                         continue;
1394                 usb_get_urb (urb);
1395                 spin_unlock (&hcd_data_lock);
1396
1397                 spin_lock (&urb->lock);
1398                 tmp = urb->status;
1399                 if (tmp == -EINPROGRESS)
1400                         urb->status = -ESHUTDOWN;
1401                 spin_unlock (&urb->lock);
1402
1403                 /* kick hcd unless it's already returning this */
1404                 if (tmp == -EINPROGRESS) {
1405                         tmp = urb->pipe;
1406                         unlink1 (hcd, urb);
1407                         dev_dbg (hcd->self.controller,
1408                                 "shutdown urb %p pipe %08x ep%d%s%s\n",
1409                                 urb, tmp, usb_pipeendpoint (tmp),
1410                                 (tmp & USB_DIR_IN) ? "in" : "out",
1411                                 ({ char *s; \
1412                                  switch (usb_pipetype (tmp)) { \
1413                                  case PIPE_CONTROL:     s = ""; break; \
1414                                  case PIPE_BULK:        s = "-bulk"; break; \
1415                                  case PIPE_INTERRUPT:   s = "-intr"; break; \
1416                                  default:               s = "-iso"; break; \
1417                                 }; s;}));
1418                 }
1419                 usb_put_urb (urb);
1420
1421                 /* list contents may have changed */
1422                 goto rescan;
1423         }
1424         spin_unlock (&hcd_data_lock);
1425         local_irq_enable ();
1426
1427         /* synchronize with the hardware, so old configuration state
1428          * clears out immediately (and will be freed).
1429          */
1430         might_sleep ();
1431         if (hcd->driver->endpoint_disable)
1432                 hcd->driver->endpoint_disable (hcd, ep);
1433 }
1434
1435 /*-------------------------------------------------------------------------*/
1436
1437 #ifdef  CONFIG_PM
1438
1439 int hcd_bus_suspend (struct usb_bus *bus)
1440 {
1441         struct usb_hcd          *hcd;
1442         int                     status;
1443
1444         hcd = container_of (bus, struct usb_hcd, self);
1445         if (!hcd->driver->bus_suspend)
1446                 return -ENOENT;
1447         hcd->state = HC_STATE_QUIESCING;
1448         status = hcd->driver->bus_suspend (hcd);
1449         if (status == 0)
1450                 hcd->state = HC_STATE_SUSPENDED;
1451         else
1452                 dev_dbg(&bus->root_hub->dev, "%s fail, err %d\n",
1453                                 "suspend", status);
1454         return status;
1455 }
1456
1457 int hcd_bus_resume (struct usb_bus *bus)
1458 {
1459         struct usb_hcd          *hcd;
1460         int                     status;
1461
1462         hcd = container_of (bus, struct usb_hcd, self);
1463         if (!hcd->driver->bus_resume)
1464                 return -ENOENT;
1465         if (hcd->state == HC_STATE_RUNNING)
1466                 return 0;
1467         hcd->state = HC_STATE_RESUMING;
1468         status = hcd->driver->bus_resume (hcd);
1469         if (status == 0)
1470                 hcd->state = HC_STATE_RUNNING;
1471         else {
1472                 dev_dbg(&bus->root_hub->dev, "%s fail, err %d\n",
1473                                 "resume", status);
1474                 usb_hc_died(hcd);
1475         }
1476         return status;
1477 }
1478
1479 /*
1480  * usb_hcd_suspend_root_hub - HCD autosuspends downstream ports
1481  * @hcd: host controller for this root hub
1482  *
1483  * This call arranges that usb_hcd_resume_root_hub() is safe to call later;
1484  * that the HCD's root hub polling is deactivated; and that the root's hub
1485  * driver is suspended.  HCDs may call this to autosuspend when their root
1486  * hub's downstream ports are all inactive:  unpowered, disconnected,
1487  * disabled, or suspended.
1488  *
1489  * The HCD will autoresume on device connect change detection (using SRP
1490  * or a D+/D- pullup).  The HCD also autoresumes on remote wakeup signaling
1491  * from any ports that are suspended (if that is enabled).  In most cases,
1492  * overcurrent signaling (on powered ports) will also start autoresume.
1493  *
1494  * Always called with IRQs blocked.
1495  */
1496 void usb_hcd_suspend_root_hub (struct usb_hcd *hcd)
1497 {
1498         struct urb      *urb;
1499
1500         spin_lock (&hcd_root_hub_lock);
1501         usb_suspend_root_hub (hcd->self.root_hub);
1502
1503         /* force status urb to complete/unlink while suspended */
1504         if (hcd->status_urb) {
1505                 urb = hcd->status_urb;
1506                 urb->status = -ECONNRESET;
1507                 urb->hcpriv = NULL;
1508                 urb->actual_length = 0;
1509
1510                 del_timer (&hcd->rh_timer);
1511                 hcd->poll_pending = 0;
1512                 hcd->status_urb = NULL;
1513         } else
1514                 urb = NULL;
1515         spin_unlock (&hcd_root_hub_lock);
1516         hcd->state = HC_STATE_SUSPENDED;
1517
1518         if (urb)
1519                 usb_hcd_giveback_urb (hcd, urb, NULL);
1520 }
1521 EXPORT_SYMBOL_GPL(usb_hcd_suspend_root_hub);
1522
1523 /**
1524  * usb_hcd_resume_root_hub - called by HCD to resume its root hub 
1525  * @hcd: host controller for this root hub
1526  *
1527  * The USB host controller calls this function when its root hub is
1528  * suspended (with the remote wakeup feature enabled) and a remote
1529  * wakeup request is received.  It queues a request for khubd to
1530  * resume the root hub (that is, manage its downstream ports again).
1531  */
1532 void usb_hcd_resume_root_hub (struct usb_hcd *hcd)
1533 {
1534         unsigned long flags;
1535
1536         spin_lock_irqsave (&hcd_root_hub_lock, flags);
1537         if (hcd->rh_registered)
1538                 usb_resume_root_hub (hcd->self.root_hub);
1539         spin_unlock_irqrestore (&hcd_root_hub_lock, flags);
1540 }
1541 EXPORT_SYMBOL_GPL(usb_hcd_resume_root_hub);
1542
1543 #endif
1544
1545 /*-------------------------------------------------------------------------*/
1546
1547 #ifdef  CONFIG_USB_OTG
1548
1549 /**
1550  * usb_bus_start_enum - start immediate enumeration (for OTG)
1551  * @bus: the bus (must use hcd framework)
1552  * @port_num: 1-based number of port; usually bus->otg_port
1553  * Context: in_interrupt()
1554  *
1555  * Starts enumeration, with an immediate reset followed later by
1556  * khubd identifying and possibly configuring the device.
1557  * This is needed by OTG controller drivers, where it helps meet
1558  * HNP protocol timing requirements for starting a port reset.
1559  */
1560 int usb_bus_start_enum(struct usb_bus *bus, unsigned port_num)
1561 {
1562         struct usb_hcd          *hcd;
1563         int                     status = -EOPNOTSUPP;
1564
1565         /* NOTE: since HNP can't start by grabbing the bus's address0_sem,
1566          * boards with root hubs hooked up to internal devices (instead of
1567          * just the OTG port) may need more attention to resetting...
1568          */
1569         hcd = container_of (bus, struct usb_hcd, self);
1570         if (port_num && hcd->driver->start_port_reset)
1571                 status = hcd->driver->start_port_reset(hcd, port_num);
1572
1573         /* run khubd shortly after (first) root port reset finishes;
1574          * it may issue others, until at least 50 msecs have passed.
1575          */
1576         if (status == 0)
1577                 mod_timer(&hcd->rh_timer, jiffies + msecs_to_jiffies(10));
1578         return status;
1579 }
1580 EXPORT_SYMBOL (usb_bus_start_enum);
1581
1582 #endif
1583
1584 /*-------------------------------------------------------------------------*/
1585
1586 /*
1587  * usb_hcd_operations - adapts usb_bus framework to HCD framework (bus glue)
1588  */
1589 static struct usb_operations usb_hcd_operations = {
1590         .get_frame_number =     hcd_get_frame_number,
1591         .submit_urb =           hcd_submit_urb,
1592         .unlink_urb =           hcd_unlink_urb,
1593         .buffer_alloc =         hcd_buffer_alloc,
1594         .buffer_free =          hcd_buffer_free,
1595         .disable =              hcd_endpoint_disable,
1596 };
1597
1598 /*-------------------------------------------------------------------------*/
1599
1600 /**
1601  * usb_hcd_giveback_urb - return URB from HCD to device driver
1602  * @hcd: host controller returning the URB
1603  * @urb: urb being returned to the USB device driver.
1604  * @regs: pt_regs, passed down to the URB completion handler
1605  * Context: in_interrupt()
1606  *
1607  * This hands the URB from HCD to its USB device driver, using its
1608  * completion function.  The HCD has freed all per-urb resources
1609  * (and is done using urb->hcpriv).  It also released all HCD locks;
1610  * the device driver won't cause problems if it frees, modifies,
1611  * or resubmits this URB.
1612  */
1613 void usb_hcd_giveback_urb (struct usb_hcd *hcd, struct urb *urb, struct pt_regs *regs)
1614 {
1615         int at_root_hub;
1616
1617         at_root_hub = (urb->dev == hcd->self.root_hub);
1618         urb_unlink (urb);
1619
1620         /* lower level hcd code should use *_dma exclusively */
1621         if (hcd->self.controller->dma_mask && !at_root_hub) {
1622                 if (usb_pipecontrol (urb->pipe)
1623                         && !(urb->transfer_flags & URB_NO_SETUP_DMA_MAP))
1624                         dma_unmap_single (hcd->self.controller, urb->setup_dma,
1625                                         sizeof (struct usb_ctrlrequest),
1626                                         DMA_TO_DEVICE);
1627                 if (urb->transfer_buffer_length != 0
1628                         && !(urb->transfer_flags & URB_NO_TRANSFER_DMA_MAP))
1629                         dma_unmap_single (hcd->self.controller, 
1630                                         urb->transfer_dma,
1631                                         urb->transfer_buffer_length,
1632                                         usb_pipein (urb->pipe)
1633                                             ? DMA_FROM_DEVICE
1634                                             : DMA_TO_DEVICE);
1635         }
1636
1637         usbmon_urb_complete (&hcd->self, urb);
1638         /* pass ownership to the completion handler */
1639         urb->complete (urb, regs);
1640         atomic_dec (&urb->use_count);
1641         if (unlikely (urb->reject))
1642                 wake_up (&usb_kill_urb_queue);
1643         usb_put_urb (urb);
1644 }
1645 EXPORT_SYMBOL (usb_hcd_giveback_urb);
1646
1647 /*-------------------------------------------------------------------------*/
1648
1649 /**
1650  * usb_hcd_irq - hook IRQs to HCD framework (bus glue)
1651  * @irq: the IRQ being raised
1652  * @__hcd: pointer to the HCD whose IRQ is being signaled
1653  * @r: saved hardware registers
1654  *
1655  * If the controller isn't HALTed, calls the driver's irq handler.
1656  * Checks whether the controller is now dead.
1657  */
1658 irqreturn_t usb_hcd_irq (int irq, void *__hcd, struct pt_regs * r)
1659 {
1660         struct usb_hcd          *hcd = __hcd;
1661         int                     start = hcd->state;
1662
1663         if (unlikely(start == HC_STATE_HALT ||
1664             !test_bit(HCD_FLAG_HW_ACCESSIBLE, &hcd->flags)))
1665                 return IRQ_NONE;
1666         if (hcd->driver->irq (hcd, r) == IRQ_NONE)
1667                 return IRQ_NONE;
1668
1669         set_bit(HCD_FLAG_SAW_IRQ, &hcd->flags);
1670
1671         if (unlikely(hcd->state == HC_STATE_HALT))
1672                 usb_hc_died (hcd);
1673         return IRQ_HANDLED;
1674 }
1675
1676 /*-------------------------------------------------------------------------*/
1677
1678 /**
1679  * usb_hc_died - report abnormal shutdown of a host controller (bus glue)
1680  * @hcd: pointer to the HCD representing the controller
1681  *
1682  * This is called by bus glue to report a USB host controller that died
1683  * while operations may still have been pending.  It's called automatically
1684  * by the PCI glue, so only glue for non-PCI busses should need to call it. 
1685  */
1686 void usb_hc_died (struct usb_hcd *hcd)
1687 {
1688         unsigned long flags;
1689
1690         dev_err (hcd->self.controller, "HC died; cleaning up\n");
1691
1692         spin_lock_irqsave (&hcd_root_hub_lock, flags);
1693         if (hcd->rh_registered) {
1694                 hcd->poll_rh = 0;
1695
1696                 /* make khubd clean up old urbs and devices */
1697                 usb_set_device_state (hcd->self.root_hub,
1698                                 USB_STATE_NOTATTACHED);
1699                 usb_kick_khubd (hcd->self.root_hub);
1700         }
1701         spin_unlock_irqrestore (&hcd_root_hub_lock, flags);
1702 }
1703 EXPORT_SYMBOL_GPL (usb_hc_died);
1704
1705 /*-------------------------------------------------------------------------*/
1706
1707 static void hcd_release (struct usb_bus *bus)
1708 {
1709         struct usb_hcd *hcd;
1710
1711         hcd = container_of(bus, struct usb_hcd, self);
1712         kfree(hcd);
1713 }
1714
1715 /**
1716  * usb_create_hcd - create and initialize an HCD structure
1717  * @driver: HC driver that will use this hcd
1718  * @dev: device for this HC, stored in hcd->self.controller
1719  * @bus_name: value to store in hcd->self.bus_name
1720  * Context: !in_interrupt()
1721  *
1722  * Allocate a struct usb_hcd, with extra space at the end for the
1723  * HC driver's private data.  Initialize the generic members of the
1724  * hcd structure.
1725  *
1726  * If memory is unavailable, returns NULL.
1727  */
1728 struct usb_hcd *usb_create_hcd (const struct hc_driver *driver,
1729                 struct device *dev, char *bus_name)
1730 {
1731         struct usb_hcd *hcd;
1732
1733         hcd = kzalloc(sizeof(*hcd) + driver->hcd_priv_size, GFP_KERNEL);
1734         if (!hcd) {
1735                 dev_dbg (dev, "hcd alloc failed\n");
1736                 return NULL;
1737         }
1738         dev_set_drvdata(dev, hcd);
1739
1740         usb_bus_init(&hcd->self);
1741         hcd->self.op = &usb_hcd_operations;
1742         hcd->self.hcpriv = hcd;
1743         hcd->self.release = &hcd_release;
1744         hcd->self.controller = dev;
1745         hcd->self.bus_name = bus_name;
1746
1747         init_timer(&hcd->rh_timer);
1748         hcd->rh_timer.function = rh_timer_func;
1749         hcd->rh_timer.data = (unsigned long) hcd;
1750
1751         hcd->driver = driver;
1752         hcd->product_desc = (driver->product_desc) ? driver->product_desc :
1753                         "USB Host Controller";
1754
1755         return hcd;
1756 }
1757 EXPORT_SYMBOL (usb_create_hcd);
1758
1759 void usb_put_hcd (struct usb_hcd *hcd)
1760 {
1761         dev_set_drvdata(hcd->self.controller, NULL);
1762         usb_bus_put(&hcd->self);
1763 }
1764 EXPORT_SYMBOL (usb_put_hcd);
1765
1766 /**
1767  * usb_add_hcd - finish generic HCD structure initialization and register
1768  * @hcd: the usb_hcd structure to initialize
1769  * @irqnum: Interrupt line to allocate
1770  * @irqflags: Interrupt type flags
1771  *
1772  * Finish the remaining parts of generic HCD initialization: allocate the
1773  * buffers of consistent memory, register the bus, request the IRQ line,
1774  * and call the driver's reset() and start() routines.
1775  */
1776 int usb_add_hcd(struct usb_hcd *hcd,
1777                 unsigned int irqnum, unsigned long irqflags)
1778 {
1779         int retval;
1780         struct usb_device *rhdev;
1781
1782         dev_info(hcd->self.controller, "%s\n", hcd->product_desc);
1783
1784         set_bit(HCD_FLAG_HW_ACCESSIBLE, &hcd->flags);
1785
1786         /* HC is in reset state, but accessible.  Now do the one-time init,
1787          * bottom up so that hcds can customize the root hubs before khubd
1788          * starts talking to them.  (Note, bus id is assigned early too.)
1789          */
1790         if ((retval = hcd_buffer_create(hcd)) != 0) {
1791                 dev_dbg(hcd->self.controller, "pool alloc failed\n");
1792                 return retval;
1793         }
1794
1795         if ((retval = usb_register_bus(&hcd->self)) < 0)
1796                 goto err_register_bus;
1797
1798         if ((rhdev = usb_alloc_dev(NULL, &hcd->self, 0)) == NULL) {
1799                 dev_err(hcd->self.controller, "unable to allocate root hub\n");
1800                 retval = -ENOMEM;
1801                 goto err_allocate_root_hub;
1802         }
1803         rhdev->speed = (hcd->driver->flags & HCD_USB2) ? USB_SPEED_HIGH :
1804                         USB_SPEED_FULL;
1805         hcd->self.root_hub = rhdev;
1806
1807         /* wakeup flag init defaults to "everything works" for root hubs,
1808          * but drivers can override it in reset() if needed, along with
1809          * recording the overall controller's system wakeup capability.
1810          */
1811         device_init_wakeup(&rhdev->dev, 1);
1812
1813         /* "reset" is misnamed; its role is now one-time init. the controller
1814          * should already have been reset (and boot firmware kicked off etc).
1815          */
1816         if (hcd->driver->reset && (retval = hcd->driver->reset(hcd)) < 0) {
1817                 dev_err(hcd->self.controller, "can't setup\n");
1818                 goto err_hcd_driver_setup;
1819         }
1820
1821         /* NOTE: root hub and controller capabilities may not be the same */
1822         if (device_can_wakeup(hcd->self.controller)
1823                         && device_can_wakeup(&hcd->self.root_hub->dev))
1824                 dev_dbg(hcd->self.controller, "supports USB remote wakeup\n");
1825
1826         /* enable irqs just before we start the controller */
1827         if (hcd->driver->irq) {
1828                 snprintf(hcd->irq_descr, sizeof(hcd->irq_descr), "%s:usb%d",
1829                                 hcd->driver->description, hcd->self.busnum);
1830                 if ((retval = request_irq(irqnum, &usb_hcd_irq, irqflags,
1831                                 hcd->irq_descr, hcd)) != 0) {
1832                         dev_err(hcd->self.controller,
1833                                         "request interrupt %d failed\n", irqnum);
1834                         goto err_request_irq;
1835                 }
1836                 hcd->irq = irqnum;
1837                 dev_info(hcd->self.controller, "irq %d, %s 0x%08llx\n", irqnum,
1838                                 (hcd->driver->flags & HCD_MEMORY) ?
1839                                         "io mem" : "io base",
1840                                         (unsigned long long)hcd->rsrc_start);
1841         } else {
1842                 hcd->irq = -1;
1843                 if (hcd->rsrc_start)
1844                         dev_info(hcd->self.controller, "%s 0x%08llx\n",
1845                                         (hcd->driver->flags & HCD_MEMORY) ?
1846                                         "io mem" : "io base",
1847                                         (unsigned long long)hcd->rsrc_start);
1848         }
1849
1850         if ((retval = hcd->driver->start(hcd)) < 0) {
1851                 dev_err(hcd->self.controller, "startup error %d\n", retval);
1852                 goto err_hcd_driver_start;
1853         }
1854
1855         /* starting here, usbcore will pay attention to this root hub */
1856         rhdev->bus_mA = min(500u, hcd->power_budget);
1857         if ((retval = register_root_hub(hcd)) != 0)
1858                 goto err_register_root_hub;
1859
1860         if (hcd->uses_new_polling && hcd->poll_rh)
1861                 usb_hcd_poll_rh_status(hcd);
1862         return retval;
1863
1864 err_register_root_hub:
1865         hcd->driver->stop(hcd);
1866 err_hcd_driver_start:
1867         if (hcd->irq >= 0)
1868                 free_irq(irqnum, hcd);
1869 err_request_irq:
1870 err_hcd_driver_setup:
1871         hcd->self.root_hub = NULL;
1872         usb_put_dev(rhdev);
1873 err_allocate_root_hub:
1874         usb_deregister_bus(&hcd->self);
1875 err_register_bus:
1876         hcd_buffer_destroy(hcd);
1877         return retval;
1878
1879 EXPORT_SYMBOL (usb_add_hcd);
1880
1881 /**
1882  * usb_remove_hcd - shutdown processing for generic HCDs
1883  * @hcd: the usb_hcd structure to remove
1884  * Context: !in_interrupt()
1885  *
1886  * Disconnects the root hub, then reverses the effects of usb_add_hcd(),
1887  * invoking the HCD's stop() method.
1888  */
1889 void usb_remove_hcd(struct usb_hcd *hcd)
1890 {
1891         dev_info(hcd->self.controller, "remove, state %x\n", hcd->state);
1892
1893         if (HC_IS_RUNNING (hcd->state))
1894                 hcd->state = HC_STATE_QUIESCING;
1895
1896         dev_dbg(hcd->self.controller, "roothub graceful disconnect\n");
1897         spin_lock_irq (&hcd_root_hub_lock);
1898         hcd->rh_registered = 0;
1899         spin_unlock_irq (&hcd_root_hub_lock);
1900
1901         mutex_lock(&usb_bus_list_lock);
1902         usb_disconnect(&hcd->self.root_hub);
1903         mutex_unlock(&usb_bus_list_lock);
1904
1905         hcd->poll_rh = 0;
1906         del_timer_sync(&hcd->rh_timer);
1907
1908         hcd->driver->stop(hcd);
1909         hcd->state = HC_STATE_HALT;
1910
1911         if (hcd->irq >= 0)
1912                 free_irq(hcd->irq, hcd);
1913         usb_deregister_bus(&hcd->self);
1914         hcd_buffer_destroy(hcd);
1915 }
1916 EXPORT_SYMBOL (usb_remove_hcd);
1917
1918 /*-------------------------------------------------------------------------*/
1919
1920 #if defined(CONFIG_USB_MON)
1921
1922 struct usb_mon_operations *mon_ops;
1923
1924 /*
1925  * The registration is unlocked.
1926  * We do it this way because we do not want to lock in hot paths.
1927  *
1928  * Notice that the code is minimally error-proof. Because usbmon needs
1929  * symbols from usbcore, usbcore gets referenced and cannot be unloaded first.
1930  */
1931  
1932 int usb_mon_register (struct usb_mon_operations *ops)
1933 {
1934
1935         if (mon_ops)
1936                 return -EBUSY;
1937
1938         mon_ops = ops;
1939         mb();
1940         return 0;
1941 }
1942 EXPORT_SYMBOL_GPL (usb_mon_register);
1943
1944 void usb_mon_deregister (void)
1945 {
1946
1947         if (mon_ops == NULL) {
1948                 printk(KERN_ERR "USB: monitor was not registered\n");
1949                 return;
1950         }
1951         mon_ops = NULL;
1952         mb();
1953 }
1954 EXPORT_SYMBOL_GPL (usb_mon_deregister);
1955
1956 #endif /* CONFIG_USB_MON */