kernel.org linux-2.6.10
[linux-2.6.git] / drivers / usb / core / usb.c
1 /*
2  * drivers/usb/usb.c
3  *
4  * (C) Copyright Linus Torvalds 1999
5  * (C) Copyright Johannes Erdfelt 1999-2001
6  * (C) Copyright Andreas Gal 1999
7  * (C) Copyright Gregory P. Smith 1999
8  * (C) Copyright Deti Fliegl 1999 (new USB architecture)
9  * (C) Copyright Randy Dunlap 2000
10  * (C) Copyright David Brownell 2000-2004
11  * (C) Copyright Yggdrasil Computing, Inc. 2000
12  *     (usb_device_id matching changes by Adam J. Richter)
13  * (C) Copyright Greg Kroah-Hartman 2002-2003
14  *
15  * NOTE! This is not actually a driver at all, rather this is
16  * just a collection of helper routines that implement the
17  * generic USB things that the real drivers can use..
18  *
19  * Think of this as a "USB library" rather than anything else.
20  * It should be considered a slave, with no callbacks. Callbacks
21  * are evil.
22  */
23
24 #include <linux/config.h>
25
26 #ifdef CONFIG_USB_DEBUG
27         #define DEBUG
28 #else
29         #undef DEBUG
30 #endif
31
32 #include <linux/module.h>
33 #include <linux/string.h>
34 #include <linux/bitops.h>
35 #include <linux/slab.h>
36 #include <linux/interrupt.h>  /* for in_interrupt() */
37 #include <linux/kmod.h>
38 #include <linux/init.h>
39 #include <linux/spinlock.h>
40 #include <linux/errno.h>
41 #include <linux/smp_lock.h>
42 #include <linux/rwsem.h>
43 #include <linux/usb.h>
44
45 #include <asm/io.h>
46 #include <asm/scatterlist.h>
47 #include <linux/mm.h>
48 #include <linux/dma-mapping.h>
49
50 #include "hcd.h"
51 #include "usb.h"
52
53 extern int  usb_hub_init(void);
54 extern void usb_hub_cleanup(void);
55 extern int usb_major_init(void);
56 extern void usb_major_cleanup(void);
57 extern int usb_host_init(void);
58 extern void usb_host_cleanup(void);
59
60
61 const char *usbcore_name = "usbcore";
62
63 int nousb;              /* Disable USB when built into kernel image */
64                         /* Not honored on modular build */
65
66 DECLARE_RWSEM(usb_all_devices_rwsem);
67 EXPORT_SYMBOL(usb_all_devices_rwsem);
68
69
70 static int generic_probe (struct device *dev)
71 {
72         return 0;
73 }
74 static int generic_remove (struct device *dev)
75 {
76         return 0;
77 }
78
79 static struct device_driver usb_generic_driver = {
80         .owner = THIS_MODULE,
81         .name = "usb",
82         .bus = &usb_bus_type,
83         .probe = generic_probe,
84         .remove = generic_remove,
85 };
86
87 static int usb_generic_driver_data;
88
89 /* called from driver core with usb_bus_type.subsys writelock */
90 int usb_probe_interface(struct device *dev)
91 {
92         struct usb_interface * intf = to_usb_interface(dev);
93         struct usb_driver * driver = to_usb_driver(dev->driver);
94         const struct usb_device_id *id;
95         int error = -ENODEV;
96
97         dev_dbg(dev, "%s\n", __FUNCTION__);
98
99         if (!driver->probe)
100                 return error;
101         /* FIXME we'd much prefer to just resume it ... */
102         if (interface_to_usbdev(intf)->state == USB_STATE_SUSPENDED)
103                 return -EHOSTUNREACH;
104
105         id = usb_match_id (intf, driver->id_table);
106         if (id) {
107                 dev_dbg (dev, "%s - got id\n", __FUNCTION__);
108                 intf->condition = USB_INTERFACE_BINDING;
109                 error = driver->probe (intf, id);
110                 intf->condition = error ? USB_INTERFACE_UNBOUND :
111                                 USB_INTERFACE_BOUND;
112         }
113
114         return error;
115 }
116
117 /* called from driver core with usb_bus_type.subsys writelock */
118 int usb_unbind_interface(struct device *dev)
119 {
120         struct usb_interface *intf = to_usb_interface(dev);
121         struct usb_driver *driver = to_usb_driver(intf->dev.driver);
122
123         intf->condition = USB_INTERFACE_UNBINDING;
124
125         /* release all urbs for this interface */
126         usb_disable_interface(interface_to_usbdev(intf), intf);
127
128         if (driver && driver->disconnect)
129                 driver->disconnect(intf);
130
131         /* reset other interface state */
132         usb_set_interface(interface_to_usbdev(intf),
133                         intf->altsetting[0].desc.bInterfaceNumber,
134                         0);
135         usb_set_intfdata(intf, NULL);
136         intf->condition = USB_INTERFACE_UNBOUND;
137
138         return 0;
139 }
140
141 /**
142  * usb_register - register a USB driver
143  * @new_driver: USB operations for the driver
144  *
145  * Registers a USB driver with the USB core.  The list of unattached
146  * interfaces will be rescanned whenever a new driver is added, allowing
147  * the new driver to attach to any recognized devices.
148  * Returns a negative error code on failure and 0 on success.
149  * 
150  * NOTE: if you want your driver to use the USB major number, you must call
151  * usb_register_dev() to enable that functionality.  This function no longer
152  * takes care of that.
153  */
154 int usb_register(struct usb_driver *new_driver)
155 {
156         int retval = 0;
157
158         if (nousb)
159                 return -ENODEV;
160
161         new_driver->driver.name = (char *)new_driver->name;
162         new_driver->driver.bus = &usb_bus_type;
163         new_driver->driver.probe = usb_probe_interface;
164         new_driver->driver.remove = usb_unbind_interface;
165         new_driver->driver.owner = new_driver->owner;
166
167         usb_lock_all_devices();
168         retval = driver_register(&new_driver->driver);
169         usb_unlock_all_devices();
170
171         if (!retval) {
172                 pr_info("%s: registered new driver %s\n",
173                         usbcore_name, new_driver->name);
174                 usbfs_update_special();
175         } else {
176                 printk(KERN_ERR "%s: error %d registering driver %s\n",
177                         usbcore_name, retval, new_driver->name);
178         }
179
180         return retval;
181 }
182
183 /**
184  * usb_deregister - unregister a USB driver
185  * @driver: USB operations of the driver to unregister
186  * Context: must be able to sleep
187  *
188  * Unlinks the specified driver from the internal USB driver list.
189  * 
190  * NOTE: If you called usb_register_dev(), you still need to call
191  * usb_deregister_dev() to clean up your driver's allocated minor numbers,
192  * this * call will no longer do it for you.
193  */
194 void usb_deregister(struct usb_driver *driver)
195 {
196         pr_info("%s: deregistering driver %s\n", usbcore_name, driver->name);
197
198         usb_lock_all_devices();
199         driver_unregister (&driver->driver);
200         usb_unlock_all_devices();
201
202         usbfs_update_special();
203 }
204
205 /**
206  * usb_ifnum_to_if - get the interface object with a given interface number
207  * @dev: the device whose current configuration is considered
208  * @ifnum: the desired interface
209  *
210  * This walks the device descriptor for the currently active configuration
211  * and returns a pointer to the interface with that particular interface
212  * number, or null.
213  *
214  * Note that configuration descriptors are not required to assign interface
215  * numbers sequentially, so that it would be incorrect to assume that
216  * the first interface in that descriptor corresponds to interface zero.
217  * This routine helps device drivers avoid such mistakes.
218  * However, you should make sure that you do the right thing with any
219  * alternate settings available for this interfaces.
220  *
221  * Don't call this function unless you are bound to one of the interfaces
222  * on this device or you have locked the device!
223  */
224 struct usb_interface *usb_ifnum_to_if(struct usb_device *dev, unsigned ifnum)
225 {
226         struct usb_host_config *config = dev->actconfig;
227         int i;
228
229         if (!config)
230                 return NULL;
231         for (i = 0; i < config->desc.bNumInterfaces; i++)
232                 if (config->interface[i]->altsetting[0]
233                                 .desc.bInterfaceNumber == ifnum)
234                         return config->interface[i];
235
236         return NULL;
237 }
238
239 /**
240  * usb_altnum_to_altsetting - get the altsetting structure with a given
241  *      alternate setting number.
242  * @intf: the interface containing the altsetting in question
243  * @altnum: the desired alternate setting number
244  *
245  * This searches the altsetting array of the specified interface for
246  * an entry with the correct bAlternateSetting value and returns a pointer
247  * to that entry, or null.
248  *
249  * Note that altsettings need not be stored sequentially by number, so
250  * it would be incorrect to assume that the first altsetting entry in
251  * the array corresponds to altsetting zero.  This routine helps device
252  * drivers avoid such mistakes.
253  *
254  * Don't call this function unless you are bound to the intf interface
255  * or you have locked the device!
256  */
257 struct usb_host_interface *usb_altnum_to_altsetting(struct usb_interface *intf,
258                 unsigned int altnum)
259 {
260         int i;
261
262         for (i = 0; i < intf->num_altsetting; i++) {
263                 if (intf->altsetting[i].desc.bAlternateSetting == altnum)
264                         return &intf->altsetting[i];
265         }
266         return NULL;
267 }
268
269 /**
270  * usb_epnum_to_ep_desc - get the endpoint object with a given endpoint number
271  * @dev: the device whose current configuration+altsettings is considered
272  * @epnum: the desired endpoint, masked with USB_DIR_IN as appropriate.
273  *
274  * This walks the device descriptor for the currently active configuration,
275  * and returns a pointer to the endpoint with that particular endpoint
276  * number, or null.
277  *
278  * Note that interface descriptors are not required to list endpoint
279  * numbers in any standardized order, so that it would be wrong to
280  * assume that ep2in precedes either ep5in, ep2out, or even ep1out.
281  * This routine helps device drivers avoid such mistakes.
282  */
283 struct usb_endpoint_descriptor *
284 usb_epnum_to_ep_desc(struct usb_device *dev, unsigned epnum)
285 {
286         struct usb_host_config *config = dev->actconfig;
287         int i, k;
288
289         if (!config)
290                 return NULL;
291         for (i = 0; i < config->desc.bNumInterfaces; i++) {
292                 struct usb_interface            *intf;
293                 struct usb_host_interface       *alt;
294
295                 /* only endpoints in current altsetting are active */
296                 intf = config->interface[i];
297                 alt = intf->cur_altsetting;
298
299                 for (k = 0; k < alt->desc.bNumEndpoints; k++)
300                         if (epnum == alt->endpoint[k].desc.bEndpointAddress)
301                                 return &alt->endpoint[k].desc;
302         }
303
304         return NULL;
305 }
306
307 /**
308  * usb_driver_claim_interface - bind a driver to an interface
309  * @driver: the driver to be bound
310  * @iface: the interface to which it will be bound; must be in the
311  *      usb device's active configuration
312  * @priv: driver data associated with that interface
313  *
314  * This is used by usb device drivers that need to claim more than one
315  * interface on a device when probing (audio and acm are current examples).
316  * No device driver should directly modify internal usb_interface or
317  * usb_device structure members.
318  *
319  * Few drivers should need to use this routine, since the most natural
320  * way to bind to an interface is to return the private data from
321  * the driver's probe() method.
322  *
323  * Callers must own the device lock and the driver model's usb_bus_type.subsys
324  * writelock.  So driver probe() entries don't need extra locking,
325  * but other call contexts may need to explicitly claim those locks.
326  */
327 int usb_driver_claim_interface(struct usb_driver *driver,
328                                 struct usb_interface *iface, void* priv)
329 {
330         struct device *dev = &iface->dev;
331
332         if (dev->driver)
333                 return -EBUSY;
334
335         dev->driver = &driver->driver;
336         usb_set_intfdata(iface, priv);
337         iface->condition = USB_INTERFACE_BOUND;
338
339         /* if interface was already added, bind now; else let
340          * the future device_add() bind it, bypassing probe()
341          */
342         if (!list_empty (&dev->bus_list))
343                 device_bind_driver(dev);
344
345         return 0;
346 }
347
348 /**
349  * usb_driver_release_interface - unbind a driver from an interface
350  * @driver: the driver to be unbound
351  * @iface: the interface from which it will be unbound
352  *
353  * This can be used by drivers to release an interface without waiting
354  * for their disconnect() methods to be called.  In typical cases this
355  * also causes the driver disconnect() method to be called.
356  *
357  * This call is synchronous, and may not be used in an interrupt context.
358  * Callers must own the device lock and the driver model's usb_bus_type.subsys
359  * writelock.  So driver disconnect() entries don't need extra locking,
360  * but other call contexts may need to explicitly claim those locks.
361  */
362 void usb_driver_release_interface(struct usb_driver *driver,
363                                         struct usb_interface *iface)
364 {
365         struct device *dev = &iface->dev;
366
367         /* this should never happen, don't release something that's not ours */
368         if (!dev->driver || dev->driver != &driver->driver)
369                 return;
370
371         /* don't disconnect from disconnect(), or before dev_add() */
372         if (!list_empty (&dev->driver_list) && !list_empty (&dev->bus_list))
373                 device_release_driver(dev);
374
375         dev->driver = NULL;
376         usb_set_intfdata(iface, NULL);
377         iface->condition = USB_INTERFACE_UNBOUND;
378 }
379
380 /**
381  * usb_match_id - find first usb_device_id matching device or interface
382  * @interface: the interface of interest
383  * @id: array of usb_device_id structures, terminated by zero entry
384  *
385  * usb_match_id searches an array of usb_device_id's and returns
386  * the first one matching the device or interface, or null.
387  * This is used when binding (or rebinding) a driver to an interface.
388  * Most USB device drivers will use this indirectly, through the usb core,
389  * but some layered driver frameworks use it directly.
390  * These device tables are exported with MODULE_DEVICE_TABLE, through
391  * modutils and "modules.usbmap", to support the driver loading
392  * functionality of USB hotplugging.
393  *
394  * What Matches:
395  *
396  * The "match_flags" element in a usb_device_id controls which
397  * members are used.  If the corresponding bit is set, the
398  * value in the device_id must match its corresponding member
399  * in the device or interface descriptor, or else the device_id
400  * does not match.
401  *
402  * "driver_info" is normally used only by device drivers,
403  * but you can create a wildcard "matches anything" usb_device_id
404  * as a driver's "modules.usbmap" entry if you provide an id with
405  * only a nonzero "driver_info" field.  If you do this, the USB device
406  * driver's probe() routine should use additional intelligence to
407  * decide whether to bind to the specified interface.
408  * 
409  * What Makes Good usb_device_id Tables:
410  *
411  * The match algorithm is very simple, so that intelligence in
412  * driver selection must come from smart driver id records.
413  * Unless you have good reasons to use another selection policy,
414  * provide match elements only in related groups, and order match
415  * specifiers from specific to general.  Use the macros provided
416  * for that purpose if you can.
417  *
418  * The most specific match specifiers use device descriptor
419  * data.  These are commonly used with product-specific matches;
420  * the USB_DEVICE macro lets you provide vendor and product IDs,
421  * and you can also match against ranges of product revisions.
422  * These are widely used for devices with application or vendor
423  * specific bDeviceClass values.
424  *
425  * Matches based on device class/subclass/protocol specifications
426  * are slightly more general; use the USB_DEVICE_INFO macro, or
427  * its siblings.  These are used with single-function devices
428  * where bDeviceClass doesn't specify that each interface has
429  * its own class. 
430  *
431  * Matches based on interface class/subclass/protocol are the
432  * most general; they let drivers bind to any interface on a
433  * multiple-function device.  Use the USB_INTERFACE_INFO
434  * macro, or its siblings, to match class-per-interface style 
435  * devices (as recorded in bDeviceClass).
436  *  
437  * Within those groups, remember that not all combinations are
438  * meaningful.  For example, don't give a product version range
439  * without vendor and product IDs; or specify a protocol without
440  * its associated class and subclass.
441  */   
442 const struct usb_device_id *
443 usb_match_id(struct usb_interface *interface, const struct usb_device_id *id)
444 {
445         struct usb_host_interface *intf;
446         struct usb_device *dev;
447
448         /* proc_connectinfo in devio.c may call us with id == NULL. */
449         if (id == NULL)
450                 return NULL;
451
452         intf = interface->cur_altsetting;
453         dev = interface_to_usbdev(interface);
454
455         /* It is important to check that id->driver_info is nonzero,
456            since an entry that is all zeroes except for a nonzero
457            id->driver_info is the way to create an entry that
458            indicates that the driver want to examine every
459            device and interface. */
460         for (; id->idVendor || id->bDeviceClass || id->bInterfaceClass ||
461                id->driver_info; id++) {
462
463                 if ((id->match_flags & USB_DEVICE_ID_MATCH_VENDOR) &&
464                     id->idVendor != dev->descriptor.idVendor)
465                         continue;
466
467                 if ((id->match_flags & USB_DEVICE_ID_MATCH_PRODUCT) &&
468                     id->idProduct != dev->descriptor.idProduct)
469                         continue;
470
471                 /* No need to test id->bcdDevice_lo != 0, since 0 is never
472                    greater than any unsigned number. */
473                 if ((id->match_flags & USB_DEVICE_ID_MATCH_DEV_LO) &&
474                     (id->bcdDevice_lo > dev->descriptor.bcdDevice))
475                         continue;
476
477                 if ((id->match_flags & USB_DEVICE_ID_MATCH_DEV_HI) &&
478                     (id->bcdDevice_hi < dev->descriptor.bcdDevice))
479                         continue;
480
481                 if ((id->match_flags & USB_DEVICE_ID_MATCH_DEV_CLASS) &&
482                     (id->bDeviceClass != dev->descriptor.bDeviceClass))
483                         continue;
484
485                 if ((id->match_flags & USB_DEVICE_ID_MATCH_DEV_SUBCLASS) &&
486                     (id->bDeviceSubClass!= dev->descriptor.bDeviceSubClass))
487                         continue;
488
489                 if ((id->match_flags & USB_DEVICE_ID_MATCH_DEV_PROTOCOL) &&
490                     (id->bDeviceProtocol != dev->descriptor.bDeviceProtocol))
491                         continue;
492
493                 if ((id->match_flags & USB_DEVICE_ID_MATCH_INT_CLASS) &&
494                     (id->bInterfaceClass != intf->desc.bInterfaceClass))
495                         continue;
496
497                 if ((id->match_flags & USB_DEVICE_ID_MATCH_INT_SUBCLASS) &&
498                     (id->bInterfaceSubClass != intf->desc.bInterfaceSubClass))
499                         continue;
500
501                 if ((id->match_flags & USB_DEVICE_ID_MATCH_INT_PROTOCOL) &&
502                     (id->bInterfaceProtocol != intf->desc.bInterfaceProtocol))
503                         continue;
504
505                 return id;
506         }
507
508         return NULL;
509 }
510
511 /**
512  * usb_find_interface - find usb_interface pointer for driver and device
513  * @drv: the driver whose current configuration is considered
514  * @minor: the minor number of the desired device
515  *
516  * This walks the driver device list and returns a pointer to the interface 
517  * with the matching minor.  Note, this only works for devices that share the
518  * USB major number.
519  */
520 struct usb_interface *usb_find_interface(struct usb_driver *drv, int minor)
521 {
522         struct list_head *entry;
523         struct device *dev;
524         struct usb_interface *intf;
525
526         list_for_each(entry, &drv->driver.devices) {
527                 dev = container_of(entry, struct device, driver_list);
528
529                 /* can't look at usb devices, only interfaces */
530                 if (dev->driver == &usb_generic_driver)
531                         continue;
532
533                 intf = to_usb_interface(dev);
534                 if (intf->minor == -1)
535                         continue;
536                 if (intf->minor == minor)
537                         return intf;
538         }
539
540         /* no device found that matches */
541         return NULL;    
542 }
543
544 static int usb_device_match (struct device *dev, struct device_driver *drv)
545 {
546         struct usb_interface *intf;
547         struct usb_driver *usb_drv;
548         const struct usb_device_id *id;
549
550         /* check for generic driver, which we don't match any device with */
551         if (drv == &usb_generic_driver)
552                 return 0;
553
554         intf = to_usb_interface(dev);
555         usb_drv = to_usb_driver(drv);
556         
557         id = usb_match_id (intf, usb_drv->id_table);
558         if (id)
559                 return 1;
560
561         return 0;
562 }
563
564
565 #ifdef  CONFIG_HOTPLUG
566
567 /*
568  * USB hotplugging invokes what /proc/sys/kernel/hotplug says
569  * (normally /sbin/hotplug) when USB devices get added or removed.
570  *
571  * This invokes a user mode policy agent, typically helping to load driver
572  * or other modules, configure the device, and more.  Drivers can provide
573  * a MODULE_DEVICE_TABLE to help with module loading subtasks.
574  *
575  * We're called either from khubd (the typical case) or from root hub
576  * (init, kapmd, modprobe, rmmod, etc), but the agents need to handle
577  * delays in event delivery.  Use sysfs (and DEVPATH) to make sure the
578  * device (and this configuration!) are still present.
579  */
580 static int usb_hotplug (struct device *dev, char **envp, int num_envp,
581                         char *buffer, int buffer_size)
582 {
583         struct usb_interface *intf;
584         struct usb_device *usb_dev;
585         int i = 0;
586         int length = 0;
587
588         if (!dev)
589                 return -ENODEV;
590
591         /* driver is often null here; dev_dbg() would oops */
592         pr_debug ("usb %s: hotplug\n", dev->bus_id);
593
594         /* Must check driver_data here, as on remove driver is always NULL */
595         if ((dev->driver == &usb_generic_driver) || 
596             (dev->driver_data == &usb_generic_driver_data))
597                 return 0;
598
599         intf = to_usb_interface(dev);
600         usb_dev = interface_to_usbdev (intf);
601         
602         if (usb_dev->devnum < 0) {
603                 pr_debug ("usb %s: already deleted?\n", dev->bus_id);
604                 return -ENODEV;
605         }
606         if (!usb_dev->bus) {
607                 pr_debug ("usb %s: bus removed?\n", dev->bus_id);
608                 return -ENODEV;
609         }
610
611 #ifdef  CONFIG_USB_DEVICEFS
612         /* If this is available, userspace programs can directly read
613          * all the device descriptors we don't tell them about.  Or
614          * even act as usermode drivers.
615          *
616          * FIXME reduce hardwired intelligence here
617          */
618         if (add_hotplug_env_var(envp, num_envp, &i,
619                                 buffer, buffer_size, &length,
620                                 "DEVICE=/proc/bus/usb/%03d/%03d",
621                                 usb_dev->bus->busnum, usb_dev->devnum))
622                 return -ENOMEM;
623 #endif
624
625         /* per-device configurations are common */
626         if (add_hotplug_env_var(envp, num_envp, &i,
627                                 buffer, buffer_size, &length,
628                                 "PRODUCT=%x/%x/%x",
629                                 usb_dev->descriptor.idVendor,
630                                 usb_dev->descriptor.idProduct,
631                                 usb_dev->descriptor.bcdDevice))
632                 return -ENOMEM;
633
634         /* class-based driver binding models */
635         if (add_hotplug_env_var(envp, num_envp, &i,
636                                 buffer, buffer_size, &length,
637                                 "TYPE=%d/%d/%d",
638                                 usb_dev->descriptor.bDeviceClass,
639                                 usb_dev->descriptor.bDeviceSubClass,
640                                 usb_dev->descriptor.bDeviceProtocol))
641                 return -ENOMEM;
642
643         if (usb_dev->descriptor.bDeviceClass == 0) {
644                 struct usb_host_interface *alt = intf->cur_altsetting;
645
646                 /* 2.4 only exposed interface zero.  in 2.5, hotplug
647                  * agents are called for all interfaces, and can use
648                  * $DEVPATH/bInterfaceNumber if necessary.
649                  */
650                 if (add_hotplug_env_var(envp, num_envp, &i,
651                                         buffer, buffer_size, &length,
652                                         "INTERFACE=%d/%d/%d",
653                                         alt->desc.bInterfaceClass,
654                                         alt->desc.bInterfaceSubClass,
655                                         alt->desc.bInterfaceProtocol))
656                         return -ENOMEM;
657         }
658
659         envp[i] = NULL;
660
661         return 0;
662 }
663
664 #else
665
666 static int usb_hotplug (struct device *dev, char **envp,
667                         int num_envp, char *buffer, int buffer_size)
668 {
669         return -ENODEV;
670 }
671
672 #endif  /* CONFIG_HOTPLUG */
673
674 /**
675  * usb_release_dev - free a usb device structure when all users of it are finished.
676  * @dev: device that's been disconnected
677  *
678  * Will be called only by the device core when all users of this usb device are
679  * done.
680  */
681 static void usb_release_dev(struct device *dev)
682 {
683         struct usb_device *udev;
684
685         udev = to_usb_device(dev);
686
687         if (udev->bus && udev->bus->op && udev->bus->op->deallocate)
688                 udev->bus->op->deallocate(udev);
689         usb_destroy_configuration(udev);
690         usb_bus_put(udev->bus);
691         kfree (udev);
692 }
693
694 /**
695  * usb_alloc_dev - usb device constructor (usbcore-internal)
696  * @parent: hub to which device is connected; null to allocate a root hub
697  * @bus: bus used to access the device
698  * @port: zero based index of port; ignored for root hubs
699  * Context: !in_interrupt ()
700  *
701  * Only hub drivers (including virtual root hub drivers for host
702  * controllers) should ever call this.
703  *
704  * This call may not be used in a non-sleeping context.
705  */
706 struct usb_device *
707 usb_alloc_dev(struct usb_device *parent, struct usb_bus *bus, unsigned port)
708 {
709         struct usb_device *dev;
710
711         dev = kmalloc(sizeof(*dev), GFP_KERNEL);
712         if (!dev)
713                 return NULL;
714
715         memset(dev, 0, sizeof(*dev));
716
717         bus = usb_bus_get(bus);
718         if (!bus) {
719                 kfree(dev);
720                 return NULL;
721         }
722
723         device_initialize(&dev->dev);
724         dev->dev.bus = &usb_bus_type;
725         dev->dev.dma_mask = bus->controller->dma_mask;
726         dev->dev.driver_data = &usb_generic_driver_data;
727         dev->dev.driver = &usb_generic_driver;
728         dev->dev.release = usb_release_dev;
729         dev->state = USB_STATE_ATTACHED;
730
731         /* Save readable and stable topology id, distinguishing devices
732          * by location for diagnostics, tools, driver model, etc.  The
733          * string is a path along hub ports, from the root.  Each device's
734          * dev->devpath will be stable until USB is re-cabled, and hubs
735          * are often labeled with these port numbers.  The bus_id isn't
736          * as stable:  bus->busnum changes easily from modprobe order,
737          * cardbus or pci hotplugging, and so on.
738          */
739         if (unlikely (!parent)) {
740                 dev->devpath [0] = '0';
741
742                 dev->dev.parent = bus->controller;
743                 sprintf (&dev->dev.bus_id[0], "usb%d", bus->busnum);
744         } else {
745                 /* match any labeling on the hubs; it's one-based */
746                 if (parent->devpath [0] == '0')
747                         snprintf (dev->devpath, sizeof dev->devpath,
748                                 "%d", port + 1);
749                 else
750                         snprintf (dev->devpath, sizeof dev->devpath,
751                                 "%s.%d", parent->devpath, port + 1);
752
753                 dev->dev.parent = &parent->dev;
754                 sprintf (&dev->dev.bus_id[0], "%d-%s",
755                         bus->busnum, dev->devpath);
756
757                 /* hub driver sets up TT records */
758         }
759
760         dev->bus = bus;
761         dev->parent = parent;
762         INIT_LIST_HEAD(&dev->filelist);
763
764         init_MUTEX(&dev->serialize);
765
766         if (dev->bus->op->allocate)
767                 if (dev->bus->op->allocate(dev)) {
768                         usb_bus_put(bus);
769                         kfree(dev);
770                         return NULL;
771                 }
772
773         return dev;
774 }
775
776 /**
777  * usb_get_dev - increments the reference count of the usb device structure
778  * @dev: the device being referenced
779  *
780  * Each live reference to a device should be refcounted.
781  *
782  * Drivers for USB interfaces should normally record such references in
783  * their probe() methods, when they bind to an interface, and release
784  * them by calling usb_put_dev(), in their disconnect() methods.
785  *
786  * A pointer to the device with the incremented reference counter is returned.
787  */
788 struct usb_device *usb_get_dev(struct usb_device *dev)
789 {
790         if (dev)
791                 get_device(&dev->dev);
792         return dev;
793 }
794
795 /**
796  * usb_put_dev - release a use of the usb device structure
797  * @dev: device that's been disconnected
798  *
799  * Must be called when a user of a device is finished with it.  When the last
800  * user of the device calls this function, the memory of the device is freed.
801  */
802 void usb_put_dev(struct usb_device *dev)
803 {
804         if (dev)
805                 put_device(&dev->dev);
806 }
807
808 /**
809  * usb_get_intf - increments the reference count of the usb interface structure
810  * @intf: the interface being referenced
811  *
812  * Each live reference to a interface must be refcounted.
813  *
814  * Drivers for USB interfaces should normally record such references in
815  * their probe() methods, when they bind to an interface, and release
816  * them by calling usb_put_intf(), in their disconnect() methods.
817  *
818  * A pointer to the interface with the incremented reference counter is
819  * returned.
820  */
821 struct usb_interface *usb_get_intf(struct usb_interface *intf)
822 {
823         if (intf)
824                 get_device(&intf->dev);
825         return intf;
826 }
827
828 /**
829  * usb_put_intf - release a use of the usb interface structure
830  * @intf: interface that's been decremented
831  *
832  * Must be called when a user of an interface is finished with it.  When the
833  * last user of the interface calls this function, the memory of the interface
834  * is freed.
835  */
836 void usb_put_intf(struct usb_interface *intf)
837 {
838         if (intf)
839                 put_device(&intf->dev);
840 }
841
842
843 /*                      USB device locking
844  *
845  * Although locking USB devices should be straightforward, it is
846  * complicated by the way the driver-model core works.  When a new USB
847  * driver is registered or unregistered, the core will automatically
848  * probe or disconnect all matching interfaces on all USB devices while
849  * holding the USB subsystem writelock.  There's no good way for us to
850  * tell which devices will be used or to lock them beforehand; our only
851  * option is to effectively lock all the USB devices.
852  *
853  * We do that by using a private rw-semaphore, usb_all_devices_rwsem.
854  * When locking an individual device you must first acquire the rwsem's
855  * readlock.  When a driver is registered or unregistered the writelock
856  * must be held.  These actions are encapsulated in the subroutines
857  * below, so all a driver needs to do is call usb_lock_device() and
858  * usb_unlock_device().
859  *
860  * Complications arise when several devices are to be locked at the same
861  * time.  Only hub-aware drivers that are part of usbcore ever have to
862  * do this; nobody else needs to worry about it.  The problem is that
863  * usb_lock_device() must not be called to lock a second device since it
864  * would acquire the rwsem's readlock reentrantly, leading to deadlock if
865  * another thread was waiting for the writelock.  The solution is simple:
866  *
867  *      When locking more than one device, call usb_lock_device()
868  *      to lock the first one.  Lock the others by calling
869  *      down(&udev->serialize) directly.
870  *
871  *      When unlocking multiple devices, use up(&udev->serialize)
872  *      to unlock all but the last one.  Unlock the last one by
873  *      calling usb_unlock_device().
874  *
875  *      When locking both a device and its parent, always lock the
876  *      the parent first.
877  */
878
879 /**
880  * usb_lock_device - acquire the lock for a usb device structure
881  * @udev: device that's being locked
882  *
883  * Use this routine when you don't hold any other device locks;
884  * to acquire nested inner locks call down(&udev->serialize) directly.
885  * This is necessary for proper interaction with usb_lock_all_devices().
886  */
887 void usb_lock_device(struct usb_device *udev)
888 {
889         down_read(&usb_all_devices_rwsem);
890         down(&udev->serialize);
891 }
892
893 /**
894  * usb_trylock_device - attempt to acquire the lock for a usb device structure
895  * @udev: device that's being locked
896  *
897  * Don't use this routine if you already hold a device lock;
898  * use down_trylock(&udev->serialize) instead.
899  * This is necessary for proper interaction with usb_lock_all_devices().
900  *
901  * Returns 1 if successful, 0 if contention.
902  */
903 int usb_trylock_device(struct usb_device *udev)
904 {
905         if (!down_read_trylock(&usb_all_devices_rwsem))
906                 return 0;
907         if (down_trylock(&udev->serialize)) {
908                 up_read(&usb_all_devices_rwsem);
909                 return 0;
910         }
911         return 1;
912 }
913
914 /**
915  * usb_lock_device_for_reset - cautiously acquire the lock for a
916  *      usb device structure
917  * @udev: device that's being locked
918  * @iface: interface bound to the driver making the request (optional)
919  *
920  * Attempts to acquire the device lock, but fails if the device is
921  * NOTATTACHED or SUSPENDED, or if iface is specified and the interface
922  * is neither BINDING nor BOUND.  Rather than sleeping to wait for the
923  * lock, the routine polls repeatedly.  This is to prevent deadlock with
924  * disconnect; in some drivers (such as usb-storage) the disconnect()
925  * callback will block waiting for a device reset to complete.
926  *
927  * Returns a negative error code for failure, otherwise 1 or 0 to indicate
928  * that the device will or will not have to be unlocked.  (0 can be
929  * returned when an interface is given and is BINDING, because in that
930  * case the driver already owns the device lock.)
931  */
932 int usb_lock_device_for_reset(struct usb_device *udev,
933                 struct usb_interface *iface)
934 {
935         if (udev->state == USB_STATE_NOTATTACHED)
936                 return -ENODEV;
937         if (udev->state == USB_STATE_SUSPENDED)
938                 return -EHOSTUNREACH;
939         if (iface) {
940                 switch (iface->condition) {
941                   case USB_INTERFACE_BINDING:
942                         return 0;
943                   case USB_INTERFACE_BOUND:
944                         break;
945                   default:
946                         return -EINTR;
947                 }
948         }
949
950         while (!usb_trylock_device(udev)) {
951                 msleep(15);
952                 if (udev->state == USB_STATE_NOTATTACHED)
953                         return -ENODEV;
954                 if (udev->state == USB_STATE_SUSPENDED)
955                         return -EHOSTUNREACH;
956                 if (iface && iface->condition != USB_INTERFACE_BOUND)
957                         return -EINTR;
958         }
959         return 1;
960 }
961
962 /**
963  * usb_unlock_device - release the lock for a usb device structure
964  * @udev: device that's being unlocked
965  *
966  * Use this routine when releasing the only device lock you hold;
967  * to release inner nested locks call up(&udev->serialize) directly.
968  * This is necessary for proper interaction with usb_lock_all_devices().
969  */
970 void usb_unlock_device(struct usb_device *udev)
971 {
972         up(&udev->serialize);
973         up_read(&usb_all_devices_rwsem);
974 }
975
976 /**
977  * usb_lock_all_devices - acquire the lock for all usb device structures
978  *
979  * This is necessary when registering a new driver or probing a bus,
980  * since the driver-model core may try to use any usb_device.
981  */
982 void usb_lock_all_devices(void)
983 {
984         down_write(&usb_all_devices_rwsem);
985 }
986
987 /**
988  * usb_unlock_all_devices - release the lock for all usb device structures
989  */
990 void usb_unlock_all_devices(void)
991 {
992         up_write(&usb_all_devices_rwsem);
993 }
994
995
996 static struct usb_device *match_device(struct usb_device *dev,
997                                        u16 vendor_id, u16 product_id)
998 {
999         struct usb_device *ret_dev = NULL;
1000         int child;
1001
1002         dev_dbg(&dev->dev, "check for vendor %04x, product %04x ...\n",
1003             dev->descriptor.idVendor,
1004             dev->descriptor.idProduct);
1005
1006         /* see if this device matches */
1007         if ((dev->descriptor.idVendor == vendor_id) &&
1008             (dev->descriptor.idProduct == product_id)) {
1009                 dev_dbg (&dev->dev, "matched this device!\n");
1010                 ret_dev = usb_get_dev(dev);
1011                 goto exit;
1012         }
1013
1014         /* look through all of the children of this device */
1015         for (child = 0; child < dev->maxchild; ++child) {
1016                 if (dev->children[child]) {
1017                         down(&dev->children[child]->serialize);
1018                         ret_dev = match_device(dev->children[child],
1019                                                vendor_id, product_id);
1020                         up(&dev->children[child]->serialize);
1021                         if (ret_dev)
1022                                 goto exit;
1023                 }
1024         }
1025 exit:
1026         return ret_dev;
1027 }
1028
1029 /**
1030  * usb_find_device - find a specific usb device in the system
1031  * @vendor_id: the vendor id of the device to find
1032  * @product_id: the product id of the device to find
1033  *
1034  * Returns a pointer to a struct usb_device if such a specified usb
1035  * device is present in the system currently.  The usage count of the
1036  * device will be incremented if a device is found.  Make sure to call
1037  * usb_put_dev() when the caller is finished with the device.
1038  *
1039  * If a device with the specified vendor and product id is not found,
1040  * NULL is returned.
1041  */
1042 struct usb_device *usb_find_device(u16 vendor_id, u16 product_id)
1043 {
1044         struct list_head *buslist;
1045         struct usb_bus *bus;
1046         struct usb_device *dev = NULL;
1047         
1048         down(&usb_bus_list_lock);
1049         for (buslist = usb_bus_list.next;
1050              buslist != &usb_bus_list; 
1051              buslist = buslist->next) {
1052                 bus = container_of(buslist, struct usb_bus, bus_list);
1053                 if (!bus->root_hub)
1054                         continue;
1055                 usb_lock_device(bus->root_hub);
1056                 dev = match_device(bus->root_hub, vendor_id, product_id);
1057                 usb_unlock_device(bus->root_hub);
1058                 if (dev)
1059                         goto exit;
1060         }
1061 exit:
1062         up(&usb_bus_list_lock);
1063         return dev;
1064 }
1065
1066 /**
1067  * usb_get_current_frame_number - return current bus frame number
1068  * @dev: the device whose bus is being queried
1069  *
1070  * Returns the current frame number for the USB host controller
1071  * used with the given USB device.  This can be used when scheduling
1072  * isochronous requests.
1073  *
1074  * Note that different kinds of host controller have different
1075  * "scheduling horizons".  While one type might support scheduling only
1076  * 32 frames into the future, others could support scheduling up to
1077  * 1024 frames into the future.
1078  */
1079 int usb_get_current_frame_number(struct usb_device *dev)
1080 {
1081         return dev->bus->op->get_frame_number (dev);
1082 }
1083
1084 /*-------------------------------------------------------------------*/
1085 /*
1086  * __usb_get_extra_descriptor() finds a descriptor of specific type in the
1087  * extra field of the interface and endpoint descriptor structs.
1088  */
1089
1090 int __usb_get_extra_descriptor(char *buffer, unsigned size,
1091         unsigned char type, void **ptr)
1092 {
1093         struct usb_descriptor_header *header;
1094
1095         while (size >= sizeof(struct usb_descriptor_header)) {
1096                 header = (struct usb_descriptor_header *)buffer;
1097
1098                 if (header->bLength < 2) {
1099                         printk(KERN_ERR
1100                                 "%s: bogus descriptor, type %d length %d\n",
1101                                 usbcore_name,
1102                                 header->bDescriptorType, 
1103                                 header->bLength);
1104                         return -1;
1105                 }
1106
1107                 if (header->bDescriptorType == type) {
1108                         *ptr = header;
1109                         return 0;
1110                 }
1111
1112                 buffer += header->bLength;
1113                 size -= header->bLength;
1114         }
1115         return -1;
1116 }
1117
1118 /**
1119  * usb_buffer_alloc - allocate dma-consistent buffer for URB_NO_xxx_DMA_MAP
1120  * @dev: device the buffer will be used with
1121  * @size: requested buffer size
1122  * @mem_flags: affect whether allocation may block
1123  * @dma: used to return DMA address of buffer
1124  *
1125  * Return value is either null (indicating no buffer could be allocated), or
1126  * the cpu-space pointer to a buffer that may be used to perform DMA to the
1127  * specified device.  Such cpu-space buffers are returned along with the DMA
1128  * address (through the pointer provided).
1129  *
1130  * These buffers are used with URB_NO_xxx_DMA_MAP set in urb->transfer_flags
1131  * to avoid behaviors like using "DMA bounce buffers", or tying down I/O
1132  * mapping hardware for long idle periods.  The implementation varies between
1133  * platforms, depending on details of how DMA will work to this device.
1134  * Using these buffers also helps prevent cacheline sharing problems on
1135  * architectures where CPU caches are not DMA-coherent.
1136  *
1137  * When the buffer is no longer used, free it with usb_buffer_free().
1138  */
1139 void *usb_buffer_alloc (
1140         struct usb_device *dev,
1141         size_t size,
1142         int mem_flags,
1143         dma_addr_t *dma
1144 )
1145 {
1146         if (!dev || !dev->bus || !dev->bus->op || !dev->bus->op->buffer_alloc)
1147                 return NULL;
1148         return dev->bus->op->buffer_alloc (dev->bus, size, mem_flags, dma);
1149 }
1150
1151 /**
1152  * usb_buffer_free - free memory allocated with usb_buffer_alloc()
1153  * @dev: device the buffer was used with
1154  * @size: requested buffer size
1155  * @addr: CPU address of buffer
1156  * @dma: DMA address of buffer
1157  *
1158  * This reclaims an I/O buffer, letting it be reused.  The memory must have
1159  * been allocated using usb_buffer_alloc(), and the parameters must match
1160  * those provided in that allocation request. 
1161  */
1162 void usb_buffer_free (
1163         struct usb_device *dev,
1164         size_t size,
1165         void *addr,
1166         dma_addr_t dma
1167 )
1168 {
1169         if (!dev || !dev->bus || !dev->bus->op || !dev->bus->op->buffer_free)
1170                 return;
1171         dev->bus->op->buffer_free (dev->bus, size, addr, dma);
1172 }
1173
1174 /**
1175  * usb_buffer_map - create DMA mapping(s) for an urb
1176  * @urb: urb whose transfer_buffer/setup_packet will be mapped
1177  *
1178  * Return value is either null (indicating no buffer could be mapped), or
1179  * the parameter.  URB_NO_TRANSFER_DMA_MAP and URB_NO_SETUP_DMA_MAP are
1180  * added to urb->transfer_flags if the operation succeeds.  If the device
1181  * is connected to this system through a non-DMA controller, this operation
1182  * always succeeds.
1183  *
1184  * This call would normally be used for an urb which is reused, perhaps
1185  * as the target of a large periodic transfer, with usb_buffer_dmasync()
1186  * calls to synchronize memory and dma state.
1187  *
1188  * Reverse the effect of this call with usb_buffer_unmap().
1189  */
1190 struct urb *usb_buffer_map (struct urb *urb)
1191 {
1192         struct usb_bus          *bus;
1193         struct device           *controller;
1194
1195         if (!urb
1196                         || !urb->dev
1197                         || !(bus = urb->dev->bus)
1198                         || !(controller = bus->controller))
1199                 return NULL;
1200
1201         if (controller->dma_mask) {
1202                 urb->transfer_dma = dma_map_single (controller,
1203                         urb->transfer_buffer, urb->transfer_buffer_length,
1204                         usb_pipein (urb->pipe)
1205                                 ? DMA_FROM_DEVICE : DMA_TO_DEVICE);
1206                 if (usb_pipecontrol (urb->pipe))
1207                         urb->setup_dma = dma_map_single (controller,
1208                                         urb->setup_packet,
1209                                         sizeof (struct usb_ctrlrequest),
1210                                         DMA_TO_DEVICE);
1211         // FIXME generic api broken like pci, can't report errors
1212         // if (urb->transfer_dma == DMA_ADDR_INVALID) return 0;
1213         } else
1214                 urb->transfer_dma = ~0;
1215         urb->transfer_flags |= (URB_NO_TRANSFER_DMA_MAP
1216                                 | URB_NO_SETUP_DMA_MAP);
1217         return urb;
1218 }
1219
1220 /* XXX DISABLED, no users currently.  If you wish to re-enable this
1221  * XXX please determine whether the sync is to transfer ownership of
1222  * XXX the buffer from device to cpu or vice verse, and thusly use the
1223  * XXX appropriate _for_{cpu,device}() method.  -DaveM
1224  */
1225 #if 0
1226
1227 /**
1228  * usb_buffer_dmasync - synchronize DMA and CPU view of buffer(s)
1229  * @urb: urb whose transfer_buffer/setup_packet will be synchronized
1230  */
1231 void usb_buffer_dmasync (struct urb *urb)
1232 {
1233         struct usb_bus          *bus;
1234         struct device           *controller;
1235
1236         if (!urb
1237                         || !(urb->transfer_flags & URB_NO_TRANSFER_DMA_MAP)
1238                         || !urb->dev
1239                         || !(bus = urb->dev->bus)
1240                         || !(controller = bus->controller))
1241                 return;
1242
1243         if (controller->dma_mask) {
1244                 dma_sync_single (controller,
1245                         urb->transfer_dma, urb->transfer_buffer_length,
1246                         usb_pipein (urb->pipe)
1247                                 ? DMA_FROM_DEVICE : DMA_TO_DEVICE);
1248                 if (usb_pipecontrol (urb->pipe))
1249                         dma_sync_single (controller,
1250                                         urb->setup_dma,
1251                                         sizeof (struct usb_ctrlrequest),
1252                                         DMA_TO_DEVICE);
1253         }
1254 }
1255 #endif
1256
1257 /**
1258  * usb_buffer_unmap - free DMA mapping(s) for an urb
1259  * @urb: urb whose transfer_buffer will be unmapped
1260  *
1261  * Reverses the effect of usb_buffer_map().
1262  */
1263 void usb_buffer_unmap (struct urb *urb)
1264 {
1265         struct usb_bus          *bus;
1266         struct device           *controller;
1267
1268         if (!urb
1269                         || !(urb->transfer_flags & URB_NO_TRANSFER_DMA_MAP)
1270                         || !urb->dev
1271                         || !(bus = urb->dev->bus)
1272                         || !(controller = bus->controller))
1273                 return;
1274
1275         if (controller->dma_mask) {
1276                 dma_unmap_single (controller,
1277                         urb->transfer_dma, urb->transfer_buffer_length,
1278                         usb_pipein (urb->pipe)
1279                                 ? DMA_FROM_DEVICE : DMA_TO_DEVICE);
1280                 if (usb_pipecontrol (urb->pipe))
1281                         dma_unmap_single (controller,
1282                                         urb->setup_dma,
1283                                         sizeof (struct usb_ctrlrequest),
1284                                         DMA_TO_DEVICE);
1285         }
1286         urb->transfer_flags &= ~(URB_NO_TRANSFER_DMA_MAP
1287                                 | URB_NO_SETUP_DMA_MAP);
1288 }
1289
1290 /**
1291  * usb_buffer_map_sg - create scatterlist DMA mapping(s) for an endpoint
1292  * @dev: device to which the scatterlist will be mapped
1293  * @pipe: endpoint defining the mapping direction
1294  * @sg: the scatterlist to map
1295  * @nents: the number of entries in the scatterlist
1296  *
1297  * Return value is either < 0 (indicating no buffers could be mapped), or
1298  * the number of DMA mapping array entries in the scatterlist.
1299  *
1300  * The caller is responsible for placing the resulting DMA addresses from
1301  * the scatterlist into URB transfer buffer pointers, and for setting the
1302  * URB_NO_TRANSFER_DMA_MAP transfer flag in each of those URBs.
1303  *
1304  * Top I/O rates come from queuing URBs, instead of waiting for each one
1305  * to complete before starting the next I/O.   This is particularly easy
1306  * to do with scatterlists.  Just allocate and submit one URB for each DMA
1307  * mapping entry returned, stopping on the first error or when all succeed.
1308  * Better yet, use the usb_sg_*() calls, which do that (and more) for you.
1309  *
1310  * This call would normally be used when translating scatterlist requests,
1311  * rather than usb_buffer_map(), since on some hardware (with IOMMUs) it
1312  * may be able to coalesce mappings for improved I/O efficiency.
1313  *
1314  * Reverse the effect of this call with usb_buffer_unmap_sg().
1315  */
1316 int usb_buffer_map_sg (struct usb_device *dev, unsigned pipe,
1317                 struct scatterlist *sg, int nents)
1318 {
1319         struct usb_bus          *bus;
1320         struct device           *controller;
1321
1322         if (!dev
1323                         || usb_pipecontrol (pipe)
1324                         || !(bus = dev->bus)
1325                         || !(controller = bus->controller)
1326                         || !controller->dma_mask)
1327                 return -1;
1328
1329         // FIXME generic api broken like pci, can't report errors
1330         return dma_map_sg (controller, sg, nents,
1331                         usb_pipein (pipe) ? DMA_FROM_DEVICE : DMA_TO_DEVICE);
1332 }
1333
1334 /* XXX DISABLED, no users currently.  If you wish to re-enable this
1335  * XXX please determine whether the sync is to transfer ownership of
1336  * XXX the buffer from device to cpu or vice verse, and thusly use the
1337  * XXX appropriate _for_{cpu,device}() method.  -DaveM
1338  */
1339 #if 0
1340
1341 /**
1342  * usb_buffer_dmasync_sg - synchronize DMA and CPU view of scatterlist buffer(s)
1343  * @dev: device to which the scatterlist will be mapped
1344  * @pipe: endpoint defining the mapping direction
1345  * @sg: the scatterlist to synchronize
1346  * @n_hw_ents: the positive return value from usb_buffer_map_sg
1347  *
1348  * Use this when you are re-using a scatterlist's data buffers for
1349  * another USB request.
1350  */
1351 void usb_buffer_dmasync_sg (struct usb_device *dev, unsigned pipe,
1352                 struct scatterlist *sg, int n_hw_ents)
1353 {
1354         struct usb_bus          *bus;
1355         struct device           *controller;
1356
1357         if (!dev
1358                         || !(bus = dev->bus)
1359                         || !(controller = bus->controller)
1360                         || !controller->dma_mask)
1361                 return;
1362
1363         dma_sync_sg (controller, sg, n_hw_ents,
1364                         usb_pipein (pipe) ? DMA_FROM_DEVICE : DMA_TO_DEVICE);
1365 }
1366 #endif
1367
1368 /**
1369  * usb_buffer_unmap_sg - free DMA mapping(s) for a scatterlist
1370  * @dev: device to which the scatterlist will be mapped
1371  * @pipe: endpoint defining the mapping direction
1372  * @sg: the scatterlist to unmap
1373  * @n_hw_ents: the positive return value from usb_buffer_map_sg
1374  *
1375  * Reverses the effect of usb_buffer_map_sg().
1376  */
1377 void usb_buffer_unmap_sg (struct usb_device *dev, unsigned pipe,
1378                 struct scatterlist *sg, int n_hw_ents)
1379 {
1380         struct usb_bus          *bus;
1381         struct device           *controller;
1382
1383         if (!dev
1384                         || !(bus = dev->bus)
1385                         || !(controller = bus->controller)
1386                         || !controller->dma_mask)
1387                 return;
1388
1389         dma_unmap_sg (controller, sg, n_hw_ents,
1390                         usb_pipein (pipe) ? DMA_FROM_DEVICE : DMA_TO_DEVICE);
1391 }
1392
1393 static int usb_generic_suspend(struct device *dev, u32 state)
1394 {
1395         struct usb_interface *intf;
1396         struct usb_driver *driver;
1397
1398         if (dev->driver == &usb_generic_driver)
1399                 return usb_suspend_device (to_usb_device(dev), state);
1400
1401         if ((dev->driver == NULL) ||
1402             (dev->driver_data == &usb_generic_driver_data))
1403                 return 0;
1404
1405         intf = to_usb_interface(dev);
1406         driver = to_usb_driver(dev->driver);
1407
1408         /* there's only one USB suspend state */
1409         if (intf->dev.power.power_state)
1410                 return 0;
1411
1412         if (driver->suspend)
1413                 return driver->suspend(intf, state);
1414         return 0;
1415 }
1416
1417 static int usb_generic_resume(struct device *dev)
1418 {
1419         struct usb_interface *intf;
1420         struct usb_driver *driver;
1421
1422         /* devices resume through their hub */
1423         if (dev->driver == &usb_generic_driver)
1424                 return usb_resume_device (to_usb_device(dev));
1425
1426         if ((dev->driver == NULL) ||
1427             (dev->driver_data == &usb_generic_driver_data))
1428                 return 0;
1429
1430         intf = to_usb_interface(dev);
1431         driver = to_usb_driver(dev->driver);
1432
1433         if (driver->resume)
1434                 return driver->resume(intf);
1435         return 0;
1436 }
1437
1438 struct bus_type usb_bus_type = {
1439         .name =         "usb",
1440         .match =        usb_device_match,
1441         .hotplug =      usb_hotplug,
1442         .suspend =      usb_generic_suspend,
1443         .resume =       usb_generic_resume,
1444 };
1445
1446 #ifndef MODULE
1447
1448 static int __init usb_setup_disable(char *str)
1449 {
1450         nousb = 1;
1451         return 1;
1452 }
1453
1454 /* format to disable USB on kernel command line is: nousb */
1455 __setup("nousb", usb_setup_disable);
1456
1457 #endif
1458
1459 /*
1460  * for external read access to <nousb>
1461  */
1462 int usb_disabled(void)
1463 {
1464         return nousb;
1465 }
1466
1467 /*
1468  * Init
1469  */
1470 static int __init usb_init(void)
1471 {
1472         int retval;
1473         if (nousb) {
1474                 pr_info ("%s: USB support disabled\n", usbcore_name);
1475                 return 0;
1476         }
1477
1478         retval = bus_register(&usb_bus_type);
1479         if (retval) 
1480                 goto out;
1481         retval = usb_host_init();
1482         if (retval)
1483                 goto host_init_failed;
1484         retval = usb_major_init();
1485         if (retval)
1486                 goto major_init_failed;
1487         retval = usbfs_init();
1488         if (retval)
1489                 goto fs_init_failed;
1490         retval = usb_hub_init();
1491         if (retval)
1492                 goto hub_init_failed;
1493
1494         retval = driver_register(&usb_generic_driver);
1495         if (!retval)
1496                 goto out;
1497
1498         usb_hub_cleanup();
1499 hub_init_failed:
1500         usbfs_cleanup();
1501 fs_init_failed:
1502         usb_major_cleanup();    
1503 major_init_failed:
1504         usb_host_cleanup();
1505 host_init_failed:
1506         bus_unregister(&usb_bus_type);
1507 out:
1508         return retval;
1509 }
1510
1511 /*
1512  * Cleanup
1513  */
1514 static void __exit usb_exit(void)
1515 {
1516         /* This will matter if shutdown/reboot does exitcalls. */
1517         if (nousb)
1518                 return;
1519
1520         driver_unregister(&usb_generic_driver);
1521         usb_major_cleanup();
1522         usbfs_cleanup();
1523         usb_hub_cleanup();
1524         usb_host_cleanup();
1525         bus_unregister(&usb_bus_type);
1526 }
1527
1528 subsys_initcall(usb_init);
1529 module_exit(usb_exit);
1530
1531 /*
1532  * USB may be built into the kernel or be built as modules.
1533  * These symbols are exported for device (or host controller)
1534  * driver modules to use.
1535  */
1536 EXPORT_SYMBOL(usb_epnum_to_ep_desc);
1537
1538 EXPORT_SYMBOL(usb_register);
1539 EXPORT_SYMBOL(usb_deregister);
1540 EXPORT_SYMBOL(usb_disabled);
1541
1542 EXPORT_SYMBOL(usb_alloc_dev);
1543 EXPORT_SYMBOL(usb_put_dev);
1544 EXPORT_SYMBOL(usb_get_dev);
1545 EXPORT_SYMBOL(usb_hub_tt_clear_buffer);
1546
1547 EXPORT_SYMBOL(usb_lock_device);
1548 EXPORT_SYMBOL(usb_trylock_device);
1549 EXPORT_SYMBOL(usb_lock_device_for_reset);
1550 EXPORT_SYMBOL(usb_unlock_device);
1551
1552 EXPORT_SYMBOL(usb_driver_claim_interface);
1553 EXPORT_SYMBOL(usb_driver_release_interface);
1554 EXPORT_SYMBOL(usb_match_id);
1555 EXPORT_SYMBOL(usb_find_interface);
1556 EXPORT_SYMBOL(usb_ifnum_to_if);
1557 EXPORT_SYMBOL(usb_altnum_to_altsetting);
1558
1559 EXPORT_SYMBOL(usb_reset_device);
1560 EXPORT_SYMBOL(usb_disconnect);
1561
1562 EXPORT_SYMBOL(__usb_get_extra_descriptor);
1563
1564 EXPORT_SYMBOL(usb_find_device);
1565 EXPORT_SYMBOL(usb_get_current_frame_number);
1566
1567 EXPORT_SYMBOL (usb_buffer_alloc);
1568 EXPORT_SYMBOL (usb_buffer_free);
1569
1570 EXPORT_SYMBOL (usb_buffer_map);
1571 #if 0
1572 EXPORT_SYMBOL (usb_buffer_dmasync);
1573 #endif
1574 EXPORT_SYMBOL (usb_buffer_unmap);
1575
1576 EXPORT_SYMBOL (usb_buffer_map_sg);
1577 #if 0
1578 EXPORT_SYMBOL (usb_buffer_dmasync_sg);
1579 #endif
1580 EXPORT_SYMBOL (usb_buffer_unmap_sg);
1581
1582 MODULE_LICENSE("GPL");