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