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