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