Merge master.kernel.org:/pub/scm/linux/kernel/git/gregkh/usb-2.6
[pandora-kernel.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 #include <linux/platform_device.h>
40 #include <linux/workqueue.h>
41
42 #include <linux/usb.h>
43
44 #include "usb.h"
45 #include "hcd.h"
46 #include "hub.h"
47
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                     /* __le16 ep_wMaxPacketSize; 1 + (MAX_ROOT_PORTS / 8)
259                      * see hub.c:hub_configure() for details. */
260         (USB_MAXCHILDREN + 1 + 7) / 8, 0x00,
261         0x0c        /*  __u8  ep_bInterval; (256ms -- usb 2.0 spec) */
262 };
263
264 /*-------------------------------------------------------------------------*/
265
266 /*
267  * helper routine for returning string descriptors in UTF-16LE
268  * input can actually be ISO-8859-1; ASCII is its 7-bit subset
269  */
270 static int ascii2utf (char *s, u8 *utf, int utfmax)
271 {
272         int retval;
273
274         for (retval = 0; *s && utfmax > 1; utfmax -= 2, retval += 2) {
275                 *utf++ = *s++;
276                 *utf++ = 0;
277         }
278         if (utfmax > 0) {
279                 *utf = *s;
280                 ++retval;
281         }
282         return retval;
283 }
284
285 /*
286  * rh_string - provides manufacturer, product and serial strings for root hub
287  * @id: the string ID number (1: serial number, 2: product, 3: vendor)
288  * @hcd: the host controller for this root hub
289  * @type: string describing our driver 
290  * @data: return packet in UTF-16 LE
291  * @len: length of the return packet
292  *
293  * Produces either a manufacturer, product or serial number string for the
294  * virtual root hub device.
295  */
296 static int rh_string (
297         int             id,
298         struct usb_hcd  *hcd,
299         u8              *data,
300         int             len
301 ) {
302         char buf [100];
303
304         // language ids
305         if (id == 0) {
306                 buf[0] = 4;    buf[1] = 3;      /* 4 bytes string data */
307                 buf[2] = 0x09; buf[3] = 0x04;   /* MSFT-speak for "en-us" */
308                 len = min (len, 4);
309                 memcpy (data, buf, len);
310                 return len;
311
312         // serial number
313         } else if (id == 1) {
314                 strlcpy (buf, hcd->self.bus_name, sizeof buf);
315
316         // product description
317         } else if (id == 2) {
318                 strlcpy (buf, hcd->product_desc, sizeof buf);
319
320         // id 3 == vendor description
321         } else if (id == 3) {
322                 snprintf (buf, sizeof buf, "%s %s %s", init_utsname()->sysname,
323                         init_utsname()->release, hcd->driver->description);
324
325         // unsupported IDs --> "protocol stall"
326         } else
327                 return -EPIPE;
328
329         switch (len) {          /* All cases fall through */
330         default:
331                 len = 2 + ascii2utf (buf, data + 2, len - 2);
332         case 2:
333                 data [1] = 3;   /* type == string */
334         case 1:
335                 data [0] = 2 * (strlen (buf) + 1);
336         case 0:
337                 ;               /* Compiler wants a statement here */
338         }
339         return len;
340 }
341
342
343 /* Root hub control transfers execute synchronously */
344 static int rh_call_control (struct usb_hcd *hcd, struct urb *urb)
345 {
346         struct usb_ctrlrequest *cmd;
347         u16             typeReq, wValue, wIndex, wLength;
348         u8              *ubuf = urb->transfer_buffer;
349         u8              tbuf [sizeof (struct usb_hub_descriptor)]
350                 __attribute__((aligned(4)));
351         const u8        *bufp = tbuf;
352         int             len = 0;
353         int             patch_wakeup = 0;
354         unsigned long   flags;
355         int             status = 0;
356         int             n;
357
358         cmd = (struct usb_ctrlrequest *) urb->setup_packet;
359         typeReq  = (cmd->bRequestType << 8) | cmd->bRequest;
360         wValue   = le16_to_cpu (cmd->wValue);
361         wIndex   = le16_to_cpu (cmd->wIndex);
362         wLength  = le16_to_cpu (cmd->wLength);
363
364         if (wLength > urb->transfer_buffer_length)
365                 goto error;
366
367         urb->actual_length = 0;
368         switch (typeReq) {
369
370         /* DEVICE REQUESTS */
371
372         /* The root hub's remote wakeup enable bit is implemented using
373          * driver model wakeup flags.  If this system supports wakeup
374          * through USB, userspace may change the default "allow wakeup"
375          * policy through sysfs or these calls.
376          *
377          * Most root hubs support wakeup from downstream devices, for
378          * runtime power management (disabling USB clocks and reducing
379          * VBUS power usage).  However, not all of them do so; silicon,
380          * board, and BIOS bugs here are not uncommon, so these can't
381          * be treated quite like external hubs.
382          *
383          * Likewise, not all root hubs will pass wakeup events upstream,
384          * to wake up the whole system.  So don't assume root hub and
385          * controller capabilities are identical.
386          */
387
388         case DeviceRequest | USB_REQ_GET_STATUS:
389                 tbuf [0] = (device_may_wakeup(&hcd->self.root_hub->dev)
390                                         << USB_DEVICE_REMOTE_WAKEUP)
391                                 | (1 << USB_DEVICE_SELF_POWERED);
392                 tbuf [1] = 0;
393                 len = 2;
394                 break;
395         case DeviceOutRequest | USB_REQ_CLEAR_FEATURE:
396                 if (wValue == USB_DEVICE_REMOTE_WAKEUP)
397                         device_set_wakeup_enable(&hcd->self.root_hub->dev, 0);
398                 else
399                         goto error;
400                 break;
401         case DeviceOutRequest | USB_REQ_SET_FEATURE:
402                 if (device_can_wakeup(&hcd->self.root_hub->dev)
403                                 && wValue == USB_DEVICE_REMOTE_WAKEUP)
404                         device_set_wakeup_enable(&hcd->self.root_hub->dev, 1);
405                 else
406                         goto error;
407                 break;
408         case DeviceRequest | USB_REQ_GET_CONFIGURATION:
409                 tbuf [0] = 1;
410                 len = 1;
411                         /* FALLTHROUGH */
412         case DeviceOutRequest | USB_REQ_SET_CONFIGURATION:
413                 break;
414         case DeviceRequest | USB_REQ_GET_DESCRIPTOR:
415                 switch (wValue & 0xff00) {
416                 case USB_DT_DEVICE << 8:
417                         if (hcd->driver->flags & HCD_USB2)
418                                 bufp = usb2_rh_dev_descriptor;
419                         else if (hcd->driver->flags & HCD_USB11)
420                                 bufp = usb11_rh_dev_descriptor;
421                         else
422                                 goto error;
423                         len = 18;
424                         break;
425                 case USB_DT_CONFIG << 8:
426                         if (hcd->driver->flags & HCD_USB2) {
427                                 bufp = hs_rh_config_descriptor;
428                                 len = sizeof hs_rh_config_descriptor;
429                         } else {
430                                 bufp = fs_rh_config_descriptor;
431                                 len = sizeof fs_rh_config_descriptor;
432                         }
433                         if (device_can_wakeup(&hcd->self.root_hub->dev))
434                                 patch_wakeup = 1;
435                         break;
436                 case USB_DT_STRING << 8:
437                         n = rh_string (wValue & 0xff, hcd, ubuf, wLength);
438                         if (n < 0)
439                                 goto error;
440                         urb->actual_length = n;
441                         break;
442                 default:
443                         goto error;
444                 }
445                 break;
446         case DeviceRequest | USB_REQ_GET_INTERFACE:
447                 tbuf [0] = 0;
448                 len = 1;
449                         /* FALLTHROUGH */
450         case DeviceOutRequest | USB_REQ_SET_INTERFACE:
451                 break;
452         case DeviceOutRequest | USB_REQ_SET_ADDRESS:
453                 // wValue == urb->dev->devaddr
454                 dev_dbg (hcd->self.controller, "root hub device address %d\n",
455                         wValue);
456                 break;
457
458         /* INTERFACE REQUESTS (no defined feature/status flags) */
459
460         /* ENDPOINT REQUESTS */
461
462         case EndpointRequest | USB_REQ_GET_STATUS:
463                 // ENDPOINT_HALT flag
464                 tbuf [0] = 0;
465                 tbuf [1] = 0;
466                 len = 2;
467                         /* FALLTHROUGH */
468         case EndpointOutRequest | USB_REQ_CLEAR_FEATURE:
469         case EndpointOutRequest | USB_REQ_SET_FEATURE:
470                 dev_dbg (hcd->self.controller, "no endpoint features yet\n");
471                 break;
472
473         /* CLASS REQUESTS (and errors) */
474
475         default:
476                 /* non-generic request */
477                 switch (typeReq) {
478                 case GetHubStatus:
479                 case GetPortStatus:
480                         len = 4;
481                         break;
482                 case GetHubDescriptor:
483                         len = sizeof (struct usb_hub_descriptor);
484                         break;
485                 }
486                 status = hcd->driver->hub_control (hcd,
487                         typeReq, wValue, wIndex,
488                         tbuf, wLength);
489                 break;
490 error:
491                 /* "protocol stall" on error */
492                 status = -EPIPE;
493         }
494
495         if (status) {
496                 len = 0;
497                 if (status != -EPIPE) {
498                         dev_dbg (hcd->self.controller,
499                                 "CTRL: TypeReq=0x%x val=0x%x "
500                                 "idx=0x%x len=%d ==> %d\n",
501                                 typeReq, wValue, wIndex,
502                                 wLength, status);
503                 }
504         }
505         if (len) {
506                 if (urb->transfer_buffer_length < len)
507                         len = urb->transfer_buffer_length;
508                 urb->actual_length = len;
509                 // always USB_DIR_IN, toward host
510                 memcpy (ubuf, bufp, len);
511
512                 /* report whether RH hardware supports remote wakeup */
513                 if (patch_wakeup &&
514                                 len > offsetof (struct usb_config_descriptor,
515                                                 bmAttributes))
516                         ((struct usb_config_descriptor *)ubuf)->bmAttributes
517                                 |= USB_CONFIG_ATT_WAKEUP;
518         }
519
520         /* any errors get returned through the urb completion */
521         local_irq_save (flags);
522         spin_lock (&urb->lock);
523         if (urb->status == -EINPROGRESS)
524                 urb->status = status;
525         spin_unlock (&urb->lock);
526         usb_hcd_giveback_urb (hcd, urb);
527         local_irq_restore (flags);
528         return 0;
529 }
530
531 /*-------------------------------------------------------------------------*/
532
533 /*
534  * Root Hub interrupt transfers are polled using a timer if the
535  * driver requests it; otherwise the driver is responsible for
536  * calling usb_hcd_poll_rh_status() when an event occurs.
537  *
538  * Completions are called in_interrupt(), but they may or may not
539  * be in_irq().
540  */
541 void usb_hcd_poll_rh_status(struct usb_hcd *hcd)
542 {
543         struct urb      *urb;
544         int             length;
545         unsigned long   flags;
546         char            buffer[4];      /* Any root hubs with > 31 ports? */
547
548         if (unlikely(!hcd->rh_registered))
549                 return;
550         if (!hcd->uses_new_polling && !hcd->status_urb)
551                 return;
552
553         length = hcd->driver->hub_status_data(hcd, buffer);
554         if (length > 0) {
555
556                 /* try to complete the status urb */
557                 local_irq_save (flags);
558                 spin_lock(&hcd_root_hub_lock);
559                 urb = hcd->status_urb;
560                 if (urb) {
561                         spin_lock(&urb->lock);
562                         if (urb->status == -EINPROGRESS) {
563                                 hcd->poll_pending = 0;
564                                 hcd->status_urb = NULL;
565                                 urb->status = 0;
566                                 urb->hcpriv = NULL;
567                                 urb->actual_length = length;
568                                 memcpy(urb->transfer_buffer, buffer, length);
569                         } else          /* urb has been unlinked */
570                                 length = 0;
571                         spin_unlock(&urb->lock);
572                 } else
573                         length = 0;
574                 spin_unlock(&hcd_root_hub_lock);
575
576                 /* local irqs are always blocked in completions */
577                 if (length > 0)
578                         usb_hcd_giveback_urb (hcd, urb);
579                 else
580                         hcd->poll_pending = 1;
581                 local_irq_restore (flags);
582         }
583
584         /* The USB 2.0 spec says 256 ms.  This is close enough and won't
585          * exceed that limit if HZ is 100. */
586         if (hcd->uses_new_polling ? hcd->poll_rh :
587                         (length == 0 && hcd->status_urb != NULL))
588                 mod_timer (&hcd->rh_timer, jiffies + msecs_to_jiffies(250));
589 }
590 EXPORT_SYMBOL_GPL(usb_hcd_poll_rh_status);
591
592 /* timer callback */
593 static void rh_timer_func (unsigned long _hcd)
594 {
595         usb_hcd_poll_rh_status((struct usb_hcd *) _hcd);
596 }
597
598 /*-------------------------------------------------------------------------*/
599
600 static int rh_queue_status (struct usb_hcd *hcd, struct urb *urb)
601 {
602         int             retval;
603         unsigned long   flags;
604         int             len = 1 + (urb->dev->maxchild / 8);
605
606         spin_lock_irqsave (&hcd_root_hub_lock, flags);
607         if (urb->status != -EINPROGRESS)        /* already unlinked */
608                 retval = urb->status;
609         else if (hcd->status_urb || urb->transfer_buffer_length < len) {
610                 dev_dbg (hcd->self.controller, "not queuing rh status urb\n");
611                 retval = -EINVAL;
612         } else {
613                 hcd->status_urb = urb;
614                 urb->hcpriv = hcd;      /* indicate it's queued */
615
616                 if (!hcd->uses_new_polling)
617                         mod_timer (&hcd->rh_timer, jiffies +
618                                         msecs_to_jiffies(250));
619
620                 /* If a status change has already occurred, report it ASAP */
621                 else if (hcd->poll_pending)
622                         mod_timer (&hcd->rh_timer, jiffies);
623                 retval = 0;
624         }
625         spin_unlock_irqrestore (&hcd_root_hub_lock, flags);
626         return retval;
627 }
628
629 static int rh_urb_enqueue (struct usb_hcd *hcd, struct urb *urb)
630 {
631         if (usb_pipeint (urb->pipe))
632                 return rh_queue_status (hcd, urb);
633         if (usb_pipecontrol (urb->pipe))
634                 return rh_call_control (hcd, urb);
635         return -EINVAL;
636 }
637
638 /*-------------------------------------------------------------------------*/
639
640 /* Unlinks of root-hub control URBs are legal, but they don't do anything
641  * since these URBs always execute synchronously.
642  */
643 static int usb_rh_urb_dequeue (struct usb_hcd *hcd, struct urb *urb)
644 {
645         unsigned long   flags;
646
647         if (usb_pipeendpoint(urb->pipe) == 0) { /* Control URB */
648                 ;       /* Do nothing */
649
650         } else {                                /* Status URB */
651                 if (!hcd->uses_new_polling)
652                         del_timer (&hcd->rh_timer);
653                 local_irq_save (flags);
654                 spin_lock (&hcd_root_hub_lock);
655                 if (urb == hcd->status_urb) {
656                         hcd->status_urb = NULL;
657                         urb->hcpriv = NULL;
658                 } else
659                         urb = NULL;             /* wasn't fully queued */
660                 spin_unlock (&hcd_root_hub_lock);
661                 if (urb)
662                         usb_hcd_giveback_urb (hcd, urb);
663                 local_irq_restore (flags);
664         }
665
666         return 0;
667 }
668
669 /*-------------------------------------------------------------------------*/
670
671 static struct class *usb_host_class;
672
673 int usb_host_init(void)
674 {
675         int retval = 0;
676
677         usb_host_class = class_create(THIS_MODULE, "usb_host");
678         if (IS_ERR(usb_host_class))
679                 retval = PTR_ERR(usb_host_class);
680         return retval;
681 }
682
683 void usb_host_cleanup(void)
684 {
685         class_destroy(usb_host_class);
686 }
687
688 /**
689  * usb_bus_init - shared initialization code
690  * @bus: the bus structure being initialized
691  *
692  * This code is used to initialize a usb_bus structure, memory for which is
693  * separately managed.
694  */
695 static void usb_bus_init (struct usb_bus *bus)
696 {
697         memset (&bus->devmap, 0, sizeof(struct usb_devmap));
698
699         bus->devnum_next = 1;
700
701         bus->root_hub = NULL;
702         bus->busnum = -1;
703         bus->bandwidth_allocated = 0;
704         bus->bandwidth_int_reqs  = 0;
705         bus->bandwidth_isoc_reqs = 0;
706
707         INIT_LIST_HEAD (&bus->bus_list);
708 }
709
710 /*-------------------------------------------------------------------------*/
711
712 /**
713  * usb_register_bus - registers the USB host controller with the usb core
714  * @bus: pointer to the bus to register
715  * Context: !in_interrupt()
716  *
717  * Assigns a bus number, and links the controller into usbcore data
718  * structures so that it can be seen by scanning the bus list.
719  */
720 static int usb_register_bus(struct usb_bus *bus)
721 {
722         int busnum;
723
724         mutex_lock(&usb_bus_list_lock);
725         busnum = find_next_zero_bit (busmap.busmap, USB_MAXBUS, 1);
726         if (busnum < USB_MAXBUS) {
727                 set_bit (busnum, busmap.busmap);
728                 bus->busnum = busnum;
729         } else {
730                 printk (KERN_ERR "%s: too many buses\n", usbcore_name);
731                 mutex_unlock(&usb_bus_list_lock);
732                 return -E2BIG;
733         }
734
735         bus->class_dev = class_device_create(usb_host_class, NULL, MKDEV(0,0),
736                                              bus->controller, "usb_host%d", busnum);
737         if (IS_ERR(bus->class_dev)) {
738                 clear_bit(busnum, busmap.busmap);
739                 mutex_unlock(&usb_bus_list_lock);
740                 return PTR_ERR(bus->class_dev);
741         }
742
743         class_set_devdata(bus->class_dev, bus);
744
745         /* Add it to the local list of buses */
746         list_add (&bus->bus_list, &usb_bus_list);
747         mutex_unlock(&usb_bus_list_lock);
748
749         usb_notify_add_bus(bus);
750
751         dev_info (bus->controller, "new USB bus registered, assigned bus number %d\n", bus->busnum);
752         return 0;
753 }
754
755 /**
756  * usb_deregister_bus - deregisters the USB host controller
757  * @bus: pointer to the bus to deregister
758  * Context: !in_interrupt()
759  *
760  * Recycles the bus number, and unlinks the controller from usbcore data
761  * structures so that it won't be seen by scanning the bus list.
762  */
763 static void usb_deregister_bus (struct usb_bus *bus)
764 {
765         dev_info (bus->controller, "USB bus %d deregistered\n", bus->busnum);
766
767         /*
768          * NOTE: make sure that all the devices are removed by the
769          * controller code, as well as having it call this when cleaning
770          * itself up
771          */
772         mutex_lock(&usb_bus_list_lock);
773         list_del (&bus->bus_list);
774         mutex_unlock(&usb_bus_list_lock);
775
776         usb_notify_remove_bus(bus);
777
778         clear_bit (bus->busnum, busmap.busmap);
779
780         class_device_unregister(bus->class_dev);
781 }
782
783 /**
784  * register_root_hub - called by usb_add_hcd() to register a root hub
785  * @hcd: host controller for this root hub
786  *
787  * This function registers the root hub with the USB subsystem.  It sets up
788  * the device properly in the device tree and then calls usb_new_device()
789  * to register the usb device.  It also assigns the root hub's USB address
790  * (always 1).
791  */
792 static int register_root_hub(struct usb_hcd *hcd)
793 {
794         struct device *parent_dev = hcd->self.controller;
795         struct usb_device *usb_dev = hcd->self.root_hub;
796         const int devnum = 1;
797         int retval;
798
799         usb_dev->devnum = devnum;
800         usb_dev->bus->devnum_next = devnum + 1;
801         memset (&usb_dev->bus->devmap.devicemap, 0,
802                         sizeof usb_dev->bus->devmap.devicemap);
803         set_bit (devnum, usb_dev->bus->devmap.devicemap);
804         usb_set_device_state(usb_dev, USB_STATE_ADDRESS);
805
806         mutex_lock(&usb_bus_list_lock);
807
808         usb_dev->ep0.desc.wMaxPacketSize = __constant_cpu_to_le16(64);
809         retval = usb_get_device_descriptor(usb_dev, USB_DT_DEVICE_SIZE);
810         if (retval != sizeof usb_dev->descriptor) {
811                 mutex_unlock(&usb_bus_list_lock);
812                 dev_dbg (parent_dev, "can't read %s device descriptor %d\n",
813                                 usb_dev->dev.bus_id, retval);
814                 return (retval < 0) ? retval : -EMSGSIZE;
815         }
816
817         retval = usb_new_device (usb_dev);
818         if (retval) {
819                 dev_err (parent_dev, "can't register root hub for %s, %d\n",
820                                 usb_dev->dev.bus_id, retval);
821         }
822         mutex_unlock(&usb_bus_list_lock);
823
824         if (retval == 0) {
825                 spin_lock_irq (&hcd_root_hub_lock);
826                 hcd->rh_registered = 1;
827                 spin_unlock_irq (&hcd_root_hub_lock);
828
829                 /* Did the HC die before the root hub was registered? */
830                 if (hcd->state == HC_STATE_HALT)
831                         usb_hc_died (hcd);      /* This time clean up */
832         }
833
834         return retval;
835 }
836
837 void usb_enable_root_hub_irq (struct usb_bus *bus)
838 {
839         struct usb_hcd *hcd;
840
841         hcd = container_of (bus, struct usb_hcd, self);
842         if (hcd->driver->hub_irq_enable && hcd->state != HC_STATE_HALT)
843                 hcd->driver->hub_irq_enable (hcd);
844 }
845
846
847 /*-------------------------------------------------------------------------*/
848
849 /**
850  * usb_calc_bus_time - approximate periodic transaction time in nanoseconds
851  * @speed: from dev->speed; USB_SPEED_{LOW,FULL,HIGH}
852  * @is_input: true iff the transaction sends data to the host
853  * @isoc: true for isochronous transactions, false for interrupt ones
854  * @bytecount: how many bytes in the transaction.
855  *
856  * Returns approximate bus time in nanoseconds for a periodic transaction.
857  * See USB 2.0 spec section 5.11.3; only periodic transfers need to be
858  * scheduled in software, this function is only used for such scheduling.
859  */
860 long usb_calc_bus_time (int speed, int is_input, int isoc, int bytecount)
861 {
862         unsigned long   tmp;
863
864         switch (speed) {
865         case USB_SPEED_LOW:     /* INTR only */
866                 if (is_input) {
867                         tmp = (67667L * (31L + 10L * BitTime (bytecount))) / 1000L;
868                         return (64060L + (2 * BW_HUB_LS_SETUP) + BW_HOST_DELAY + tmp);
869                 } else {
870                         tmp = (66700L * (31L + 10L * BitTime (bytecount))) / 1000L;
871                         return (64107L + (2 * BW_HUB_LS_SETUP) + BW_HOST_DELAY + tmp);
872                 }
873         case USB_SPEED_FULL:    /* ISOC or INTR */
874                 if (isoc) {
875                         tmp = (8354L * (31L + 10L * BitTime (bytecount))) / 1000L;
876                         return (((is_input) ? 7268L : 6265L) + BW_HOST_DELAY + tmp);
877                 } else {
878                         tmp = (8354L * (31L + 10L * BitTime (bytecount))) / 1000L;
879                         return (9107L + BW_HOST_DELAY + tmp);
880                 }
881         case USB_SPEED_HIGH:    /* ISOC or INTR */
882                 // FIXME adjust for input vs output
883                 if (isoc)
884                         tmp = HS_NSECS_ISO (bytecount);
885                 else
886                         tmp = HS_NSECS (bytecount);
887                 return tmp;
888         default:
889                 pr_debug ("%s: bogus device speed!\n", usbcore_name);
890                 return -1;
891         }
892 }
893 EXPORT_SYMBOL (usb_calc_bus_time);
894
895
896 /*-------------------------------------------------------------------------*/
897
898 /*
899  * Generic HC operations.
900  */
901
902 /*-------------------------------------------------------------------------*/
903
904 static void urb_unlink (struct urb *urb)
905 {
906         unsigned long           flags;
907
908         /* clear all state linking urb to this dev (and hcd) */
909
910         spin_lock_irqsave (&hcd_data_lock, flags);
911         list_del_init (&urb->urb_list);
912         spin_unlock_irqrestore (&hcd_data_lock, flags);
913 }
914
915
916 /* may be called in any context with a valid urb->dev usecount
917  * caller surrenders "ownership" of urb
918  * expects usb_submit_urb() to have sanity checked and conditioned all
919  * inputs in the urb
920  */
921 int usb_hcd_submit_urb (struct urb *urb, gfp_t mem_flags)
922 {
923         int                     status;
924         struct usb_hcd          *hcd = bus_to_hcd(urb->dev->bus);
925         struct usb_host_endpoint *ep;
926         unsigned long           flags;
927
928         if (!hcd)
929                 return -ENODEV;
930
931         usbmon_urb_submit(&hcd->self, urb);
932
933         /*
934          * Atomically queue the urb,  first to our records, then to the HCD.
935          * Access to urb->status is controlled by urb->lock ... changes on
936          * i/o completion (normal or fault) or unlinking.
937          */
938
939         // FIXME:  verify that quiescing hc works right (RH cleans up)
940
941         spin_lock_irqsave (&hcd_data_lock, flags);
942         ep = (usb_pipein(urb->pipe) ? urb->dev->ep_in : urb->dev->ep_out)
943                         [usb_pipeendpoint(urb->pipe)];
944         if (unlikely (!ep))
945                 status = -ENOENT;
946         else if (unlikely (urb->reject))
947                 status = -EPERM;
948         else switch (hcd->state) {
949         case HC_STATE_RUNNING:
950         case HC_STATE_RESUMING:
951 doit:
952                 list_add_tail (&urb->urb_list, &ep->urb_list);
953                 status = 0;
954                 break;
955         case HC_STATE_SUSPENDED:
956                 /* HC upstream links (register access, wakeup signaling) can work
957                  * even when the downstream links (and DMA etc) are quiesced; let
958                  * usbcore talk to the root hub.
959                  */
960                 if (hcd->self.controller->power.power_state.event == PM_EVENT_ON
961                                 && urb->dev->parent == NULL)
962                         goto doit;
963                 /* FALL THROUGH */
964         default:
965                 status = -ESHUTDOWN;
966                 break;
967         }
968         spin_unlock_irqrestore (&hcd_data_lock, flags);
969         if (status) {
970                 INIT_LIST_HEAD (&urb->urb_list);
971                 usbmon_urb_submit_error(&hcd->self, urb, status);
972                 return status;
973         }
974
975         /* increment urb's reference count as part of giving it to the HCD
976          * (which now controls it).  HCD guarantees that it either returns
977          * an error or calls giveback(), but not both.
978          */
979         urb = usb_get_urb (urb);
980         atomic_inc (&urb->use_count);
981
982         if (urb->dev == hcd->self.root_hub) {
983                 /* NOTE:  requirement on hub callers (usbfs and the hub
984                  * driver, for now) that URBs' urb->transfer_buffer be
985                  * valid and usb_buffer_{sync,unmap}() not be needed, since
986                  * they could clobber root hub response data.
987                  */
988                 status = rh_urb_enqueue (hcd, urb);
989                 goto done;
990         }
991
992         /* lower level hcd code should use *_dma exclusively,
993          * unless it uses pio or talks to another transport.
994          */
995         if (hcd->self.uses_dma) {
996                 if (usb_pipecontrol (urb->pipe)
997                         && !(urb->transfer_flags & URB_NO_SETUP_DMA_MAP))
998                         urb->setup_dma = dma_map_single (
999                                         hcd->self.controller,
1000                                         urb->setup_packet,
1001                                         sizeof (struct usb_ctrlrequest),
1002                                         DMA_TO_DEVICE);
1003                 if (urb->transfer_buffer_length != 0
1004                         && !(urb->transfer_flags & URB_NO_TRANSFER_DMA_MAP))
1005                         urb->transfer_dma = dma_map_single (
1006                                         hcd->self.controller,
1007                                         urb->transfer_buffer,
1008                                         urb->transfer_buffer_length,
1009                                         usb_pipein (urb->pipe)
1010                                             ? DMA_FROM_DEVICE
1011                                             : DMA_TO_DEVICE);
1012         }
1013
1014         status = hcd->driver->urb_enqueue (hcd, ep, urb, mem_flags);
1015 done:
1016         if (unlikely (status)) {
1017                 urb_unlink (urb);
1018                 atomic_dec (&urb->use_count);
1019                 if (urb->reject)
1020                         wake_up (&usb_kill_urb_queue);
1021                 usbmon_urb_submit_error(&hcd->self, urb, status);
1022                 usb_put_urb (urb);
1023         }
1024         return status;
1025 }
1026
1027 /*-------------------------------------------------------------------------*/
1028
1029 /* called in any context */
1030 int usb_hcd_get_frame_number (struct usb_device *udev)
1031 {
1032         struct usb_hcd  *hcd = bus_to_hcd(udev->bus);
1033
1034         if (!HC_IS_RUNNING (hcd->state))
1035                 return -ESHUTDOWN;
1036         return hcd->driver->get_frame_number (hcd);
1037 }
1038
1039 /*-------------------------------------------------------------------------*/
1040
1041 /* this makes the hcd giveback() the urb more quickly, by kicking it
1042  * off hardware queues (which may take a while) and returning it as
1043  * soon as practical.  we've already set up the urb's return status,
1044  * but we can't know if the callback completed already.
1045  */
1046 static int
1047 unlink1 (struct usb_hcd *hcd, struct urb *urb)
1048 {
1049         int             value;
1050
1051         if (urb->dev == hcd->self.root_hub)
1052                 value = usb_rh_urb_dequeue (hcd, urb);
1053         else {
1054
1055                 /* The only reason an HCD might fail this call is if
1056                  * it has not yet fully queued the urb to begin with.
1057                  * Such failures should be harmless. */
1058                 value = hcd->driver->urb_dequeue (hcd, urb);
1059         }
1060
1061         if (value != 0)
1062                 dev_dbg (hcd->self.controller, "dequeue %p --> %d\n",
1063                                 urb, value);
1064         return value;
1065 }
1066
1067 /*
1068  * called in any context
1069  *
1070  * caller guarantees urb won't be recycled till both unlink()
1071  * and the urb's completion function return
1072  */
1073 int usb_hcd_unlink_urb (struct urb *urb, int status)
1074 {
1075         struct usb_host_endpoint        *ep;
1076         struct usb_hcd                  *hcd = NULL;
1077         struct device                   *sys = NULL;
1078         unsigned long                   flags;
1079         struct list_head                *tmp;
1080         int                             retval;
1081
1082         if (!urb)
1083                 return -EINVAL;
1084         if (!urb->dev || !urb->dev->bus)
1085                 return -ENODEV;
1086         ep = (usb_pipein(urb->pipe) ? urb->dev->ep_in : urb->dev->ep_out)
1087                         [usb_pipeendpoint(urb->pipe)];
1088         if (!ep)
1089                 return -ENODEV;
1090
1091         /*
1092          * we contend for urb->status with the hcd core,
1093          * which changes it while returning the urb.
1094          *
1095          * Caller guaranteed that the urb pointer hasn't been freed, and
1096          * that it was submitted.  But as a rule it can't know whether or
1097          * not it's already been unlinked ... so we respect the reversed
1098          * lock sequence needed for the usb_hcd_giveback_urb() code paths
1099          * (urb lock, then hcd_data_lock) in case some other CPU is now
1100          * unlinking it.
1101          */
1102         spin_lock_irqsave (&urb->lock, flags);
1103         spin_lock (&hcd_data_lock);
1104
1105         sys = &urb->dev->dev;
1106         hcd = bus_to_hcd(urb->dev->bus);
1107         if (hcd == NULL) {
1108                 retval = -ENODEV;
1109                 goto done;
1110         }
1111
1112         /* insist the urb is still queued */
1113         list_for_each(tmp, &ep->urb_list) {
1114                 if (tmp == &urb->urb_list)
1115                         break;
1116         }
1117         if (tmp != &urb->urb_list) {
1118                 retval = -EIDRM;
1119                 goto done;
1120         }
1121
1122         /* Any status except -EINPROGRESS means something already started to
1123          * unlink this URB from the hardware.  So there's no more work to do.
1124          */
1125         if (urb->status != -EINPROGRESS) {
1126                 retval = -EBUSY;
1127                 goto done;
1128         }
1129
1130         /* IRQ setup can easily be broken so that USB controllers
1131          * never get completion IRQs ... maybe even the ones we need to
1132          * finish unlinking the initial failed usb_set_address()
1133          * or device descriptor fetch.
1134          */
1135         if (!test_bit(HCD_FLAG_SAW_IRQ, &hcd->flags)
1136             && hcd->self.root_hub != urb->dev) {
1137                 dev_warn (hcd->self.controller, "Unlink after no-IRQ?  "
1138                         "Controller is probably using the wrong IRQ."
1139                         "\n");
1140                 set_bit(HCD_FLAG_SAW_IRQ, &hcd->flags);
1141         }
1142
1143         urb->status = status;
1144
1145         spin_unlock (&hcd_data_lock);
1146         spin_unlock_irqrestore (&urb->lock, flags);
1147
1148         retval = unlink1 (hcd, urb);
1149         if (retval == 0)
1150                 retval = -EINPROGRESS;
1151         return retval;
1152
1153 done:
1154         spin_unlock (&hcd_data_lock);
1155         spin_unlock_irqrestore (&urb->lock, flags);
1156         if (retval != -EIDRM && sys && sys->driver)
1157                 dev_dbg (sys, "hcd_unlink_urb %p fail %d\n", urb, retval);
1158         return retval;
1159 }
1160
1161 /*-------------------------------------------------------------------------*/
1162
1163 /* disables the endpoint: cancels any pending urbs, then synchronizes with
1164  * the hcd to make sure all endpoint state is gone from hardware, and then
1165  * waits until the endpoint's queue is completely drained. use for
1166  * set_configuration, set_interface, driver removal, physical disconnect.
1167  *
1168  * example:  a qh stored in ep->hcpriv, holding state related to endpoint
1169  * type, maxpacket size, toggle, halt status, and scheduling.
1170  */
1171 void usb_hcd_endpoint_disable (struct usb_device *udev,
1172                 struct usb_host_endpoint *ep)
1173 {
1174         struct usb_hcd          *hcd;
1175         struct urb              *urb;
1176
1177         hcd = bus_to_hcd(udev->bus);
1178         local_irq_disable ();
1179
1180         /* ep is already gone from udev->ep_{in,out}[]; no more submits */
1181 rescan:
1182         spin_lock (&hcd_data_lock);
1183         list_for_each_entry (urb, &ep->urb_list, urb_list) {
1184                 int     tmp;
1185
1186                 /* the urb may already have been unlinked */
1187                 if (urb->status != -EINPROGRESS)
1188                         continue;
1189                 usb_get_urb (urb);
1190                 spin_unlock (&hcd_data_lock);
1191
1192                 spin_lock (&urb->lock);
1193                 tmp = urb->status;
1194                 if (tmp == -EINPROGRESS)
1195                         urb->status = -ESHUTDOWN;
1196                 spin_unlock (&urb->lock);
1197
1198                 /* kick hcd unless it's already returning this */
1199                 if (tmp == -EINPROGRESS) {
1200                         tmp = urb->pipe;
1201                         unlink1 (hcd, urb);
1202                         dev_dbg (hcd->self.controller,
1203                                 "shutdown urb %p pipe %08x ep%d%s%s\n",
1204                                 urb, tmp, usb_pipeendpoint (tmp),
1205                                 (tmp & USB_DIR_IN) ? "in" : "out",
1206                                 ({ char *s; \
1207                                  switch (usb_pipetype (tmp)) { \
1208                                  case PIPE_CONTROL:     s = ""; break; \
1209                                  case PIPE_BULK:        s = "-bulk"; break; \
1210                                  case PIPE_INTERRUPT:   s = "-intr"; break; \
1211                                  default:               s = "-iso"; break; \
1212                                 }; s;}));
1213                 }
1214                 usb_put_urb (urb);
1215
1216                 /* list contents may have changed */
1217                 goto rescan;
1218         }
1219         spin_unlock (&hcd_data_lock);
1220         local_irq_enable ();
1221
1222         /* synchronize with the hardware, so old configuration state
1223          * clears out immediately (and will be freed).
1224          */
1225         might_sleep ();
1226         if (hcd->driver->endpoint_disable)
1227                 hcd->driver->endpoint_disable (hcd, ep);
1228
1229         /* Wait until the endpoint queue is completely empty.  Most HCDs
1230          * will have done this already in their endpoint_disable method,
1231          * but some might not.  And there could be root-hub control URBs
1232          * still pending since they aren't affected by the HCDs'
1233          * endpoint_disable methods.
1234          */
1235         while (!list_empty (&ep->urb_list)) {
1236                 spin_lock_irq (&hcd_data_lock);
1237
1238                 /* The list may have changed while we acquired the spinlock */
1239                 urb = NULL;
1240                 if (!list_empty (&ep->urb_list)) {
1241                         urb = list_entry (ep->urb_list.prev, struct urb,
1242                                         urb_list);
1243                         usb_get_urb (urb);
1244                 }
1245                 spin_unlock_irq (&hcd_data_lock);
1246
1247                 if (urb) {
1248                         usb_kill_urb (urb);
1249                         usb_put_urb (urb);
1250                 }
1251         }
1252 }
1253
1254 /*-------------------------------------------------------------------------*/
1255
1256 #ifdef  CONFIG_PM
1257
1258 int hcd_bus_suspend (struct usb_bus *bus)
1259 {
1260         struct usb_hcd          *hcd;
1261         int                     status;
1262
1263         hcd = container_of (bus, struct usb_hcd, self);
1264         if (!hcd->driver->bus_suspend)
1265                 return -ENOENT;
1266         hcd->state = HC_STATE_QUIESCING;
1267         status = hcd->driver->bus_suspend (hcd);
1268         if (status == 0)
1269                 hcd->state = HC_STATE_SUSPENDED;
1270         else
1271                 dev_dbg(&bus->root_hub->dev, "%s fail, err %d\n",
1272                                 "suspend", status);
1273         return status;
1274 }
1275
1276 int hcd_bus_resume (struct usb_bus *bus)
1277 {
1278         struct usb_hcd          *hcd;
1279         int                     status;
1280
1281         hcd = container_of (bus, struct usb_hcd, self);
1282         if (!hcd->driver->bus_resume)
1283                 return -ENOENT;
1284         if (hcd->state == HC_STATE_RUNNING)
1285                 return 0;
1286         hcd->state = HC_STATE_RESUMING;
1287         status = hcd->driver->bus_resume (hcd);
1288         if (status == 0)
1289                 hcd->state = HC_STATE_RUNNING;
1290         else {
1291                 dev_dbg(&bus->root_hub->dev, "%s fail, err %d\n",
1292                                 "resume", status);
1293                 usb_hc_died(hcd);
1294         }
1295         return status;
1296 }
1297
1298 /* Workqueue routine for root-hub remote wakeup */
1299 static void hcd_resume_work(struct work_struct *work)
1300 {
1301         struct usb_hcd *hcd = container_of(work, struct usb_hcd, wakeup_work);
1302         struct usb_device *udev = hcd->self.root_hub;
1303
1304         usb_lock_device(udev);
1305         usb_mark_last_busy(udev);
1306         usb_external_resume_device(udev);
1307         usb_unlock_device(udev);
1308 }
1309
1310 /**
1311  * usb_hcd_resume_root_hub - called by HCD to resume its root hub 
1312  * @hcd: host controller for this root hub
1313  *
1314  * The USB host controller calls this function when its root hub is
1315  * suspended (with the remote wakeup feature enabled) and a remote
1316  * wakeup request is received.  The routine submits a workqueue request
1317  * to resume the root hub (that is, manage its downstream ports again).
1318  */
1319 void usb_hcd_resume_root_hub (struct usb_hcd *hcd)
1320 {
1321         unsigned long flags;
1322
1323         spin_lock_irqsave (&hcd_root_hub_lock, flags);
1324         if (hcd->rh_registered)
1325                 queue_work(ksuspend_usb_wq, &hcd->wakeup_work);
1326         spin_unlock_irqrestore (&hcd_root_hub_lock, flags);
1327 }
1328 EXPORT_SYMBOL_GPL(usb_hcd_resume_root_hub);
1329
1330 #endif
1331
1332 /*-------------------------------------------------------------------------*/
1333
1334 #ifdef  CONFIG_USB_OTG
1335
1336 /**
1337  * usb_bus_start_enum - start immediate enumeration (for OTG)
1338  * @bus: the bus (must use hcd framework)
1339  * @port_num: 1-based number of port; usually bus->otg_port
1340  * Context: in_interrupt()
1341  *
1342  * Starts enumeration, with an immediate reset followed later by
1343  * khubd identifying and possibly configuring the device.
1344  * This is needed by OTG controller drivers, where it helps meet
1345  * HNP protocol timing requirements for starting a port reset.
1346  */
1347 int usb_bus_start_enum(struct usb_bus *bus, unsigned port_num)
1348 {
1349         struct usb_hcd          *hcd;
1350         int                     status = -EOPNOTSUPP;
1351
1352         /* NOTE: since HNP can't start by grabbing the bus's address0_sem,
1353          * boards with root hubs hooked up to internal devices (instead of
1354          * just the OTG port) may need more attention to resetting...
1355          */
1356         hcd = container_of (bus, struct usb_hcd, self);
1357         if (port_num && hcd->driver->start_port_reset)
1358                 status = hcd->driver->start_port_reset(hcd, port_num);
1359
1360         /* run khubd shortly after (first) root port reset finishes;
1361          * it may issue others, until at least 50 msecs have passed.
1362          */
1363         if (status == 0)
1364                 mod_timer(&hcd->rh_timer, jiffies + msecs_to_jiffies(10));
1365         return status;
1366 }
1367 EXPORT_SYMBOL (usb_bus_start_enum);
1368
1369 #endif
1370
1371 /*-------------------------------------------------------------------------*/
1372
1373 /**
1374  * usb_hcd_giveback_urb - return URB from HCD to device driver
1375  * @hcd: host controller returning the URB
1376  * @urb: urb being returned to the USB device driver.
1377  * Context: in_interrupt()
1378  *
1379  * This hands the URB from HCD to its USB device driver, using its
1380  * completion function.  The HCD has freed all per-urb resources
1381  * (and is done using urb->hcpriv).  It also released all HCD locks;
1382  * the device driver won't cause problems if it frees, modifies,
1383  * or resubmits this URB.
1384  */
1385 void usb_hcd_giveback_urb (struct usb_hcd *hcd, struct urb *urb)
1386 {
1387         int at_root_hub;
1388
1389         at_root_hub = (urb->dev == hcd->self.root_hub);
1390         urb_unlink (urb);
1391
1392         /* lower level hcd code should use *_dma exclusively if the
1393          * host controller does DMA */
1394         if (hcd->self.uses_dma && !at_root_hub) {
1395                 if (usb_pipecontrol (urb->pipe)
1396                         && !(urb->transfer_flags & URB_NO_SETUP_DMA_MAP))
1397                         dma_unmap_single (hcd->self.controller, urb->setup_dma,
1398                                         sizeof (struct usb_ctrlrequest),
1399                                         DMA_TO_DEVICE);
1400                 if (urb->transfer_buffer_length != 0
1401                         && !(urb->transfer_flags & URB_NO_TRANSFER_DMA_MAP))
1402                         dma_unmap_single (hcd->self.controller, 
1403                                         urb->transfer_dma,
1404                                         urb->transfer_buffer_length,
1405                                         usb_pipein (urb->pipe)
1406                                             ? DMA_FROM_DEVICE
1407                                             : DMA_TO_DEVICE);
1408         }
1409
1410         usbmon_urb_complete (&hcd->self, urb);
1411         /* pass ownership to the completion handler */
1412         urb->complete (urb);
1413         atomic_dec (&urb->use_count);
1414         if (unlikely (urb->reject))
1415                 wake_up (&usb_kill_urb_queue);
1416         usb_put_urb (urb);
1417 }
1418 EXPORT_SYMBOL (usb_hcd_giveback_urb);
1419
1420 /*-------------------------------------------------------------------------*/
1421
1422 /**
1423  * usb_hcd_irq - hook IRQs to HCD framework (bus glue)
1424  * @irq: the IRQ being raised
1425  * @__hcd: pointer to the HCD whose IRQ is being signaled
1426  * @r: saved hardware registers
1427  *
1428  * If the controller isn't HALTed, calls the driver's irq handler.
1429  * Checks whether the controller is now dead.
1430  */
1431 irqreturn_t usb_hcd_irq (int irq, void *__hcd)
1432 {
1433         struct usb_hcd          *hcd = __hcd;
1434         int                     start = hcd->state;
1435
1436         if (unlikely(start == HC_STATE_HALT ||
1437             !test_bit(HCD_FLAG_HW_ACCESSIBLE, &hcd->flags)))
1438                 return IRQ_NONE;
1439         if (hcd->driver->irq (hcd) == IRQ_NONE)
1440                 return IRQ_NONE;
1441
1442         set_bit(HCD_FLAG_SAW_IRQ, &hcd->flags);
1443
1444         if (unlikely(hcd->state == HC_STATE_HALT))
1445                 usb_hc_died (hcd);
1446         return IRQ_HANDLED;
1447 }
1448
1449 /*-------------------------------------------------------------------------*/
1450
1451 /**
1452  * usb_hc_died - report abnormal shutdown of a host controller (bus glue)
1453  * @hcd: pointer to the HCD representing the controller
1454  *
1455  * This is called by bus glue to report a USB host controller that died
1456  * while operations may still have been pending.  It's called automatically
1457  * by the PCI glue, so only glue for non-PCI busses should need to call it. 
1458  */
1459 void usb_hc_died (struct usb_hcd *hcd)
1460 {
1461         unsigned long flags;
1462
1463         dev_err (hcd->self.controller, "HC died; cleaning up\n");
1464
1465         spin_lock_irqsave (&hcd_root_hub_lock, flags);
1466         if (hcd->rh_registered) {
1467                 hcd->poll_rh = 0;
1468
1469                 /* make khubd clean up old urbs and devices */
1470                 usb_set_device_state (hcd->self.root_hub,
1471                                 USB_STATE_NOTATTACHED);
1472                 usb_kick_khubd (hcd->self.root_hub);
1473         }
1474         spin_unlock_irqrestore (&hcd_root_hub_lock, flags);
1475 }
1476 EXPORT_SYMBOL_GPL (usb_hc_died);
1477
1478 /*-------------------------------------------------------------------------*/
1479
1480 /**
1481  * usb_create_hcd - create and initialize an HCD structure
1482  * @driver: HC driver that will use this hcd
1483  * @dev: device for this HC, stored in hcd->self.controller
1484  * @bus_name: value to store in hcd->self.bus_name
1485  * Context: !in_interrupt()
1486  *
1487  * Allocate a struct usb_hcd, with extra space at the end for the
1488  * HC driver's private data.  Initialize the generic members of the
1489  * hcd structure.
1490  *
1491  * If memory is unavailable, returns NULL.
1492  */
1493 struct usb_hcd *usb_create_hcd (const struct hc_driver *driver,
1494                 struct device *dev, char *bus_name)
1495 {
1496         struct usb_hcd *hcd;
1497
1498         hcd = kzalloc(sizeof(*hcd) + driver->hcd_priv_size, GFP_KERNEL);
1499         if (!hcd) {
1500                 dev_dbg (dev, "hcd alloc failed\n");
1501                 return NULL;
1502         }
1503         dev_set_drvdata(dev, hcd);
1504         kref_init(&hcd->kref);
1505
1506         usb_bus_init(&hcd->self);
1507         hcd->self.controller = dev;
1508         hcd->self.bus_name = bus_name;
1509         hcd->self.uses_dma = (dev->dma_mask != NULL);
1510
1511         init_timer(&hcd->rh_timer);
1512         hcd->rh_timer.function = rh_timer_func;
1513         hcd->rh_timer.data = (unsigned long) hcd;
1514 #ifdef CONFIG_PM
1515         INIT_WORK(&hcd->wakeup_work, hcd_resume_work);
1516 #endif
1517
1518         hcd->driver = driver;
1519         hcd->product_desc = (driver->product_desc) ? driver->product_desc :
1520                         "USB Host Controller";
1521
1522         return hcd;
1523 }
1524 EXPORT_SYMBOL (usb_create_hcd);
1525
1526 static void hcd_release (struct kref *kref)
1527 {
1528         struct usb_hcd *hcd = container_of (kref, struct usb_hcd, kref);
1529
1530         kfree(hcd);
1531 }
1532
1533 struct usb_hcd *usb_get_hcd (struct usb_hcd *hcd)
1534 {
1535         if (hcd)
1536                 kref_get (&hcd->kref);
1537         return hcd;
1538 }
1539 EXPORT_SYMBOL (usb_get_hcd);
1540
1541 void usb_put_hcd (struct usb_hcd *hcd)
1542 {
1543         if (hcd)
1544                 kref_put (&hcd->kref, hcd_release);
1545 }
1546 EXPORT_SYMBOL (usb_put_hcd);
1547
1548 /**
1549  * usb_add_hcd - finish generic HCD structure initialization and register
1550  * @hcd: the usb_hcd structure to initialize
1551  * @irqnum: Interrupt line to allocate
1552  * @irqflags: Interrupt type flags
1553  *
1554  * Finish the remaining parts of generic HCD initialization: allocate the
1555  * buffers of consistent memory, register the bus, request the IRQ line,
1556  * and call the driver's reset() and start() routines.
1557  */
1558 int usb_add_hcd(struct usb_hcd *hcd,
1559                 unsigned int irqnum, unsigned long irqflags)
1560 {
1561         int retval;
1562         struct usb_device *rhdev;
1563
1564         dev_info(hcd->self.controller, "%s\n", hcd->product_desc);
1565
1566         set_bit(HCD_FLAG_HW_ACCESSIBLE, &hcd->flags);
1567
1568         /* HC is in reset state, but accessible.  Now do the one-time init,
1569          * bottom up so that hcds can customize the root hubs before khubd
1570          * starts talking to them.  (Note, bus id is assigned early too.)
1571          */
1572         if ((retval = hcd_buffer_create(hcd)) != 0) {
1573                 dev_dbg(hcd->self.controller, "pool alloc failed\n");
1574                 return retval;
1575         }
1576
1577         if ((retval = usb_register_bus(&hcd->self)) < 0)
1578                 goto err_register_bus;
1579
1580         if ((rhdev = usb_alloc_dev(NULL, &hcd->self, 0)) == NULL) {
1581                 dev_err(hcd->self.controller, "unable to allocate root hub\n");
1582                 retval = -ENOMEM;
1583                 goto err_allocate_root_hub;
1584         }
1585         rhdev->speed = (hcd->driver->flags & HCD_USB2) ? USB_SPEED_HIGH :
1586                         USB_SPEED_FULL;
1587         hcd->self.root_hub = rhdev;
1588
1589         /* wakeup flag init defaults to "everything works" for root hubs,
1590          * but drivers can override it in reset() if needed, along with
1591          * recording the overall controller's system wakeup capability.
1592          */
1593         device_init_wakeup(&rhdev->dev, 1);
1594
1595         /* "reset" is misnamed; its role is now one-time init. the controller
1596          * should already have been reset (and boot firmware kicked off etc).
1597          */
1598         if (hcd->driver->reset && (retval = hcd->driver->reset(hcd)) < 0) {
1599                 dev_err(hcd->self.controller, "can't setup\n");
1600                 goto err_hcd_driver_setup;
1601         }
1602
1603         /* NOTE: root hub and controller capabilities may not be the same */
1604         if (device_can_wakeup(hcd->self.controller)
1605                         && device_can_wakeup(&hcd->self.root_hub->dev))
1606                 dev_dbg(hcd->self.controller, "supports USB remote wakeup\n");
1607
1608         /* enable irqs just before we start the controller */
1609         if (hcd->driver->irq) {
1610                 snprintf(hcd->irq_descr, sizeof(hcd->irq_descr), "%s:usb%d",
1611                                 hcd->driver->description, hcd->self.busnum);
1612                 if ((retval = request_irq(irqnum, &usb_hcd_irq, irqflags,
1613                                 hcd->irq_descr, hcd)) != 0) {
1614                         dev_err(hcd->self.controller,
1615                                         "request interrupt %d failed\n", irqnum);
1616                         goto err_request_irq;
1617                 }
1618                 hcd->irq = irqnum;
1619                 dev_info(hcd->self.controller, "irq %d, %s 0x%08llx\n", irqnum,
1620                                 (hcd->driver->flags & HCD_MEMORY) ?
1621                                         "io mem" : "io base",
1622                                         (unsigned long long)hcd->rsrc_start);
1623         } else {
1624                 hcd->irq = -1;
1625                 if (hcd->rsrc_start)
1626                         dev_info(hcd->self.controller, "%s 0x%08llx\n",
1627                                         (hcd->driver->flags & HCD_MEMORY) ?
1628                                         "io mem" : "io base",
1629                                         (unsigned long long)hcd->rsrc_start);
1630         }
1631
1632         if ((retval = hcd->driver->start(hcd)) < 0) {
1633                 dev_err(hcd->self.controller, "startup error %d\n", retval);
1634                 goto err_hcd_driver_start;
1635         }
1636
1637         /* starting here, usbcore will pay attention to this root hub */
1638         rhdev->bus_mA = min(500u, hcd->power_budget);
1639         if ((retval = register_root_hub(hcd)) != 0)
1640                 goto err_register_root_hub;
1641
1642         if (hcd->uses_new_polling && hcd->poll_rh)
1643                 usb_hcd_poll_rh_status(hcd);
1644         return retval;
1645
1646 err_register_root_hub:
1647         hcd->driver->stop(hcd);
1648 err_hcd_driver_start:
1649         if (hcd->irq >= 0)
1650                 free_irq(irqnum, hcd);
1651 err_request_irq:
1652 err_hcd_driver_setup:
1653         hcd->self.root_hub = NULL;
1654         usb_put_dev(rhdev);
1655 err_allocate_root_hub:
1656         usb_deregister_bus(&hcd->self);
1657 err_register_bus:
1658         hcd_buffer_destroy(hcd);
1659         return retval;
1660
1661 EXPORT_SYMBOL (usb_add_hcd);
1662
1663 /**
1664  * usb_remove_hcd - shutdown processing for generic HCDs
1665  * @hcd: the usb_hcd structure to remove
1666  * Context: !in_interrupt()
1667  *
1668  * Disconnects the root hub, then reverses the effects of usb_add_hcd(),
1669  * invoking the HCD's stop() method.
1670  */
1671 void usb_remove_hcd(struct usb_hcd *hcd)
1672 {
1673         dev_info(hcd->self.controller, "remove, state %x\n", hcd->state);
1674
1675         if (HC_IS_RUNNING (hcd->state))
1676                 hcd->state = HC_STATE_QUIESCING;
1677
1678         dev_dbg(hcd->self.controller, "roothub graceful disconnect\n");
1679         spin_lock_irq (&hcd_root_hub_lock);
1680         hcd->rh_registered = 0;
1681         spin_unlock_irq (&hcd_root_hub_lock);
1682
1683 #ifdef CONFIG_PM
1684         flush_workqueue(ksuspend_usb_wq);
1685 #endif
1686
1687         mutex_lock(&usb_bus_list_lock);
1688         usb_disconnect(&hcd->self.root_hub);
1689         mutex_unlock(&usb_bus_list_lock);
1690
1691         hcd->driver->stop(hcd);
1692         hcd->state = HC_STATE_HALT;
1693
1694         hcd->poll_rh = 0;
1695         del_timer_sync(&hcd->rh_timer);
1696
1697         if (hcd->irq >= 0)
1698                 free_irq(hcd->irq, hcd);
1699         usb_deregister_bus(&hcd->self);
1700         hcd_buffer_destroy(hcd);
1701 }
1702 EXPORT_SYMBOL (usb_remove_hcd);
1703
1704 void
1705 usb_hcd_platform_shutdown(struct platform_device* dev)
1706 {
1707         struct usb_hcd *hcd = platform_get_drvdata(dev);
1708
1709         if (hcd->driver->shutdown)
1710                 hcd->driver->shutdown(hcd);
1711 }
1712 EXPORT_SYMBOL (usb_hcd_platform_shutdown);
1713
1714 /*-------------------------------------------------------------------------*/
1715
1716 #if defined(CONFIG_USB_MON)
1717
1718 struct usb_mon_operations *mon_ops;
1719
1720 /*
1721  * The registration is unlocked.
1722  * We do it this way because we do not want to lock in hot paths.
1723  *
1724  * Notice that the code is minimally error-proof. Because usbmon needs
1725  * symbols from usbcore, usbcore gets referenced and cannot be unloaded first.
1726  */
1727  
1728 int usb_mon_register (struct usb_mon_operations *ops)
1729 {
1730
1731         if (mon_ops)
1732                 return -EBUSY;
1733
1734         mon_ops = ops;
1735         mb();
1736         return 0;
1737 }
1738 EXPORT_SYMBOL_GPL (usb_mon_register);
1739
1740 void usb_mon_deregister (void)
1741 {
1742
1743         if (mon_ops == NULL) {
1744                 printk(KERN_ERR "USB: monitor was not registered\n");
1745                 return;
1746         }
1747         mon_ops = NULL;
1748         mb();
1749 }
1750 EXPORT_SYMBOL_GPL (usb_mon_deregister);
1751
1752 #endif /* CONFIG_USB_MON */