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
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..
19 * Think of this as a "USB library" rather than anything else.
20 * It should be considered a slave, with no callbacks. Callbacks
24 #include <linux/config.h>
26 #ifdef CONFIG_USB_DEBUG
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>
46 #include <asm/scatterlist.h>
48 #include <linux/dma-mapping.h>
53 extern int usb_hub_init(void);
54 extern void usb_hub_cleanup(void);
55 extern int usb_major_init(void);
56 extern void usb_major_cleanup(void);
57 extern int usb_host_init(void);
58 extern void usb_host_cleanup(void);
61 const char *usbcore_name = "usbcore";
63 int nousb; /* Disable USB when built into kernel image */
64 /* Not honored on modular build */
66 static DECLARE_RWSEM(usb_all_devices_rwsem);
69 static int generic_probe (struct device *dev)
73 static int generic_remove (struct device *dev)
78 static struct device_driver usb_generic_driver = {
82 .probe = generic_probe,
83 .remove = generic_remove,
86 static int usb_generic_driver_data;
88 /* called from driver core with usb_bus_type.subsys writelock */
89 int usb_probe_interface(struct device *dev)
91 struct usb_interface * intf = to_usb_interface(dev);
92 struct usb_driver * driver = to_usb_driver(dev->driver);
93 const struct usb_device_id *id;
96 dev_dbg(dev, "%s\n", __FUNCTION__);
100 /* FIXME we'd much prefer to just resume it ... */
101 if (interface_to_usbdev(intf)->state == USB_STATE_SUSPENDED)
102 return -EHOSTUNREACH;
104 id = usb_match_id (intf, driver->id_table);
106 dev_dbg (dev, "%s - got id\n", __FUNCTION__);
107 intf->condition = USB_INTERFACE_BINDING;
108 error = driver->probe (intf, id);
109 intf->condition = error ? USB_INTERFACE_UNBOUND :
116 /* called from driver core with usb_bus_type.subsys writelock */
117 int usb_unbind_interface(struct device *dev)
119 struct usb_interface *intf = to_usb_interface(dev);
120 struct usb_driver *driver = to_usb_driver(intf->dev.driver);
122 intf->condition = USB_INTERFACE_UNBINDING;
124 /* release all urbs for this interface */
125 usb_disable_interface(interface_to_usbdev(intf), intf);
127 if (driver && driver->disconnect)
128 driver->disconnect(intf);
130 /* reset other interface state */
131 usb_set_interface(interface_to_usbdev(intf),
132 intf->altsetting[0].desc.bInterfaceNumber,
134 usb_set_intfdata(intf, NULL);
135 intf->condition = USB_INTERFACE_UNBOUND;
141 * usb_register - register a USB driver
142 * @new_driver: USB operations for the driver
144 * Registers a USB driver with the USB core. The list of unattached
145 * interfaces will be rescanned whenever a new driver is added, allowing
146 * the new driver to attach to any recognized devices.
147 * Returns a negative error code on failure and 0 on success.
149 * NOTE: if you want your driver to use the USB major number, you must call
150 * usb_register_dev() to enable that functionality. This function no longer
151 * takes care of that.
153 int usb_register(struct usb_driver *new_driver)
160 new_driver->driver.name = (char *)new_driver->name;
161 new_driver->driver.bus = &usb_bus_type;
162 new_driver->driver.probe = usb_probe_interface;
163 new_driver->driver.remove = usb_unbind_interface;
164 new_driver->driver.owner = new_driver->owner;
166 usb_lock_all_devices();
167 retval = driver_register(&new_driver->driver);
168 usb_unlock_all_devices();
171 pr_info("%s: registered new driver %s\n",
172 usbcore_name, new_driver->name);
173 usbfs_update_special();
175 printk(KERN_ERR "%s: error %d registering driver %s\n",
176 usbcore_name, retval, new_driver->name);
183 * usb_deregister - unregister a USB driver
184 * @driver: USB operations of the driver to unregister
185 * Context: must be able to sleep
187 * Unlinks the specified driver from the internal USB driver list.
189 * NOTE: If you called usb_register_dev(), you still need to call
190 * usb_deregister_dev() to clean up your driver's allocated minor numbers,
191 * this * call will no longer do it for you.
193 void usb_deregister(struct usb_driver *driver)
195 pr_info("%s: deregistering driver %s\n", usbcore_name, driver->name);
197 usb_lock_all_devices();
198 driver_unregister (&driver->driver);
199 usb_unlock_all_devices();
201 usbfs_update_special();
205 * usb_ifnum_to_if - get the interface object with a given interface number
206 * @dev: the device whose current configuration is considered
207 * @ifnum: the desired interface
209 * This walks the device descriptor for the currently active configuration
210 * and returns a pointer to the interface with that particular interface
213 * Note that configuration descriptors are not required to assign interface
214 * numbers sequentially, so that it would be incorrect to assume that
215 * the first interface in that descriptor corresponds to interface zero.
216 * This routine helps device drivers avoid such mistakes.
217 * However, you should make sure that you do the right thing with any
218 * alternate settings available for this interfaces.
220 * Don't call this function unless you are bound to one of the interfaces
221 * on this device or you have locked the device!
223 struct usb_interface *usb_ifnum_to_if(struct usb_device *dev, unsigned ifnum)
225 struct usb_host_config *config = dev->actconfig;
230 for (i = 0; i < config->desc.bNumInterfaces; i++)
231 if (config->interface[i]->altsetting[0]
232 .desc.bInterfaceNumber == ifnum)
233 return config->interface[i];
239 * usb_altnum_to_altsetting - get the altsetting structure with a given
240 * alternate setting number.
241 * @intf: the interface containing the altsetting in question
242 * @altnum: the desired alternate setting number
244 * This searches the altsetting array of the specified interface for
245 * an entry with the correct bAlternateSetting value and returns a pointer
246 * to that entry, or null.
248 * Note that altsettings need not be stored sequentially by number, so
249 * it would be incorrect to assume that the first altsetting entry in
250 * the array corresponds to altsetting zero. This routine helps device
251 * drivers avoid such mistakes.
253 * Don't call this function unless you are bound to the intf interface
254 * or you have locked the device!
256 struct usb_host_interface *usb_altnum_to_altsetting(struct usb_interface *intf,
261 for (i = 0; i < intf->num_altsetting; i++) {
262 if (intf->altsetting[i].desc.bAlternateSetting == altnum)
263 return &intf->altsetting[i];
269 * usb_driver_claim_interface - bind a driver to an interface
270 * @driver: the driver to be bound
271 * @iface: the interface to which it will be bound; must be in the
272 * usb device's active configuration
273 * @priv: driver data associated with that interface
275 * This is used by usb device drivers that need to claim more than one
276 * interface on a device when probing (audio and acm are current examples).
277 * No device driver should directly modify internal usb_interface or
278 * usb_device structure members.
280 * Few drivers should need to use this routine, since the most natural
281 * way to bind to an interface is to return the private data from
282 * the driver's probe() method.
284 * Callers must own the device lock and the driver model's usb_bus_type.subsys
285 * writelock. So driver probe() entries don't need extra locking,
286 * but other call contexts may need to explicitly claim those locks.
288 int usb_driver_claim_interface(struct usb_driver *driver,
289 struct usb_interface *iface, void* priv)
291 struct device *dev = &iface->dev;
296 dev->driver = &driver->driver;
297 usb_set_intfdata(iface, priv);
298 iface->condition = USB_INTERFACE_BOUND;
300 /* if interface was already added, bind now; else let
301 * the future device_add() bind it, bypassing probe()
303 if (!list_empty (&dev->bus_list))
304 device_bind_driver(dev);
310 * usb_driver_release_interface - unbind a driver from an interface
311 * @driver: the driver to be unbound
312 * @iface: the interface from which it will be unbound
314 * This can be used by drivers to release an interface without waiting
315 * for their disconnect() methods to be called. In typical cases this
316 * also causes the driver disconnect() method to be called.
318 * This call is synchronous, and may not be used in an interrupt context.
319 * Callers must own the device lock and the driver model's usb_bus_type.subsys
320 * writelock. So driver disconnect() entries don't need extra locking,
321 * but other call contexts may need to explicitly claim those locks.
323 void usb_driver_release_interface(struct usb_driver *driver,
324 struct usb_interface *iface)
326 struct device *dev = &iface->dev;
328 /* this should never happen, don't release something that's not ours */
329 if (!dev->driver || dev->driver != &driver->driver)
332 /* don't disconnect from disconnect(), or before dev_add() */
333 if (!list_empty (&dev->driver_list) && !list_empty (&dev->bus_list))
334 device_release_driver(dev);
337 usb_set_intfdata(iface, NULL);
338 iface->condition = USB_INTERFACE_UNBOUND;
342 * usb_match_id - find first usb_device_id matching device or interface
343 * @interface: the interface of interest
344 * @id: array of usb_device_id structures, terminated by zero entry
346 * usb_match_id searches an array of usb_device_id's and returns
347 * the first one matching the device or interface, or null.
348 * This is used when binding (or rebinding) a driver to an interface.
349 * Most USB device drivers will use this indirectly, through the usb core,
350 * but some layered driver frameworks use it directly.
351 * These device tables are exported with MODULE_DEVICE_TABLE, through
352 * modutils and "modules.usbmap", to support the driver loading
353 * functionality of USB hotplugging.
357 * The "match_flags" element in a usb_device_id controls which
358 * members are used. If the corresponding bit is set, the
359 * value in the device_id must match its corresponding member
360 * in the device or interface descriptor, or else the device_id
363 * "driver_info" is normally used only by device drivers,
364 * but you can create a wildcard "matches anything" usb_device_id
365 * as a driver's "modules.usbmap" entry if you provide an id with
366 * only a nonzero "driver_info" field. If you do this, the USB device
367 * driver's probe() routine should use additional intelligence to
368 * decide whether to bind to the specified interface.
370 * What Makes Good usb_device_id Tables:
372 * The match algorithm is very simple, so that intelligence in
373 * driver selection must come from smart driver id records.
374 * Unless you have good reasons to use another selection policy,
375 * provide match elements only in related groups, and order match
376 * specifiers from specific to general. Use the macros provided
377 * for that purpose if you can.
379 * The most specific match specifiers use device descriptor
380 * data. These are commonly used with product-specific matches;
381 * the USB_DEVICE macro lets you provide vendor and product IDs,
382 * and you can also match against ranges of product revisions.
383 * These are widely used for devices with application or vendor
384 * specific bDeviceClass values.
386 * Matches based on device class/subclass/protocol specifications
387 * are slightly more general; use the USB_DEVICE_INFO macro, or
388 * its siblings. These are used with single-function devices
389 * where bDeviceClass doesn't specify that each interface has
392 * Matches based on interface class/subclass/protocol are the
393 * most general; they let drivers bind to any interface on a
394 * multiple-function device. Use the USB_INTERFACE_INFO
395 * macro, or its siblings, to match class-per-interface style
396 * devices (as recorded in bDeviceClass).
398 * Within those groups, remember that not all combinations are
399 * meaningful. For example, don't give a product version range
400 * without vendor and product IDs; or specify a protocol without
401 * its associated class and subclass.
403 const struct usb_device_id *
404 usb_match_id(struct usb_interface *interface, const struct usb_device_id *id)
406 struct usb_host_interface *intf;
407 struct usb_device *dev;
409 /* proc_connectinfo in devio.c may call us with id == NULL. */
413 intf = interface->cur_altsetting;
414 dev = interface_to_usbdev(interface);
416 /* It is important to check that id->driver_info is nonzero,
417 since an entry that is all zeroes except for a nonzero
418 id->driver_info is the way to create an entry that
419 indicates that the driver want to examine every
420 device and interface. */
421 for (; id->idVendor || id->bDeviceClass || id->bInterfaceClass ||
422 id->driver_info; id++) {
424 if ((id->match_flags & USB_DEVICE_ID_MATCH_VENDOR) &&
425 id->idVendor != le16_to_cpu(dev->descriptor.idVendor))
428 if ((id->match_flags & USB_DEVICE_ID_MATCH_PRODUCT) &&
429 id->idProduct != le16_to_cpu(dev->descriptor.idProduct))
432 /* No need to test id->bcdDevice_lo != 0, since 0 is never
433 greater than any unsigned number. */
434 if ((id->match_flags & USB_DEVICE_ID_MATCH_DEV_LO) &&
435 (id->bcdDevice_lo > le16_to_cpu(dev->descriptor.bcdDevice)))
438 if ((id->match_flags & USB_DEVICE_ID_MATCH_DEV_HI) &&
439 (id->bcdDevice_hi < le16_to_cpu(dev->descriptor.bcdDevice)))
442 if ((id->match_flags & USB_DEVICE_ID_MATCH_DEV_CLASS) &&
443 (id->bDeviceClass != dev->descriptor.bDeviceClass))
446 if ((id->match_flags & USB_DEVICE_ID_MATCH_DEV_SUBCLASS) &&
447 (id->bDeviceSubClass!= dev->descriptor.bDeviceSubClass))
450 if ((id->match_flags & USB_DEVICE_ID_MATCH_DEV_PROTOCOL) &&
451 (id->bDeviceProtocol != dev->descriptor.bDeviceProtocol))
454 if ((id->match_flags & USB_DEVICE_ID_MATCH_INT_CLASS) &&
455 (id->bInterfaceClass != intf->desc.bInterfaceClass))
458 if ((id->match_flags & USB_DEVICE_ID_MATCH_INT_SUBCLASS) &&
459 (id->bInterfaceSubClass != intf->desc.bInterfaceSubClass))
462 if ((id->match_flags & USB_DEVICE_ID_MATCH_INT_PROTOCOL) &&
463 (id->bInterfaceProtocol != intf->desc.bInterfaceProtocol))
473 * usb_find_interface - find usb_interface pointer for driver and device
474 * @drv: the driver whose current configuration is considered
475 * @minor: the minor number of the desired device
477 * This walks the driver device list and returns a pointer to the interface
478 * with the matching minor. Note, this only works for devices that share the
481 struct usb_interface *usb_find_interface(struct usb_driver *drv, int minor)
483 struct list_head *entry;
485 struct usb_interface *intf;
487 list_for_each(entry, &drv->driver.devices) {
488 dev = container_of(entry, struct device, driver_list);
490 /* can't look at usb devices, only interfaces */
491 if (dev->driver == &usb_generic_driver)
494 intf = to_usb_interface(dev);
495 if (intf->minor == -1)
497 if (intf->minor == minor)
501 /* no device found that matches */
505 static int usb_device_match (struct device *dev, struct device_driver *drv)
507 struct usb_interface *intf;
508 struct usb_driver *usb_drv;
509 const struct usb_device_id *id;
511 /* check for generic driver, which we don't match any device with */
512 if (drv == &usb_generic_driver)
515 intf = to_usb_interface(dev);
516 usb_drv = to_usb_driver(drv);
518 id = usb_match_id (intf, usb_drv->id_table);
526 #ifdef CONFIG_HOTPLUG
529 * USB hotplugging invokes what /proc/sys/kernel/hotplug says
530 * (normally /sbin/hotplug) when USB devices get added or removed.
532 * This invokes a user mode policy agent, typically helping to load driver
533 * or other modules, configure the device, and more. Drivers can provide
534 * a MODULE_DEVICE_TABLE to help with module loading subtasks.
536 * We're called either from khubd (the typical case) or from root hub
537 * (init, kapmd, modprobe, rmmod, etc), but the agents need to handle
538 * delays in event delivery. Use sysfs (and DEVPATH) to make sure the
539 * device (and this configuration!) are still present.
541 static int usb_hotplug (struct device *dev, char **envp, int num_envp,
542 char *buffer, int buffer_size)
544 struct usb_interface *intf;
545 struct usb_device *usb_dev;
552 /* driver is often null here; dev_dbg() would oops */
553 pr_debug ("usb %s: hotplug\n", dev->bus_id);
555 /* Must check driver_data here, as on remove driver is always NULL */
556 if ((dev->driver == &usb_generic_driver) ||
557 (dev->driver_data == &usb_generic_driver_data))
560 intf = to_usb_interface(dev);
561 usb_dev = interface_to_usbdev (intf);
563 if (usb_dev->devnum < 0) {
564 pr_debug ("usb %s: already deleted?\n", dev->bus_id);
568 pr_debug ("usb %s: bus removed?\n", dev->bus_id);
572 #ifdef CONFIG_USB_DEVICEFS
573 /* If this is available, userspace programs can directly read
574 * all the device descriptors we don't tell them about. Or
575 * even act as usermode drivers.
577 * FIXME reduce hardwired intelligence here
579 if (add_hotplug_env_var(envp, num_envp, &i,
580 buffer, buffer_size, &length,
581 "DEVICE=/proc/bus/usb/%03d/%03d",
582 usb_dev->bus->busnum, usb_dev->devnum))
586 /* per-device configurations are common */
587 if (add_hotplug_env_var(envp, num_envp, &i,
588 buffer, buffer_size, &length,
590 le16_to_cpu(usb_dev->descriptor.idVendor),
591 le16_to_cpu(usb_dev->descriptor.idProduct),
592 le16_to_cpu(usb_dev->descriptor.bcdDevice)))
595 /* class-based driver binding models */
596 if (add_hotplug_env_var(envp, num_envp, &i,
597 buffer, buffer_size, &length,
599 usb_dev->descriptor.bDeviceClass,
600 usb_dev->descriptor.bDeviceSubClass,
601 usb_dev->descriptor.bDeviceProtocol))
604 if (usb_dev->descriptor.bDeviceClass == 0) {
605 struct usb_host_interface *alt = intf->cur_altsetting;
607 /* 2.4 only exposed interface zero. in 2.5, hotplug
608 * agents are called for all interfaces, and can use
609 * $DEVPATH/bInterfaceNumber if necessary.
611 if (add_hotplug_env_var(envp, num_envp, &i,
612 buffer, buffer_size, &length,
613 "INTERFACE=%d/%d/%d",
614 alt->desc.bInterfaceClass,
615 alt->desc.bInterfaceSubClass,
616 alt->desc.bInterfaceProtocol))
627 static int usb_hotplug (struct device *dev, char **envp,
628 int num_envp, char *buffer, int buffer_size)
633 #endif /* CONFIG_HOTPLUG */
636 * usb_release_dev - free a usb device structure when all users of it are finished.
637 * @dev: device that's been disconnected
639 * Will be called only by the device core when all users of this usb device are
642 static void usb_release_dev(struct device *dev)
644 struct usb_device *udev;
646 udev = to_usb_device(dev);
648 usb_destroy_configuration(udev);
649 usb_bus_put(udev->bus);
654 * usb_alloc_dev - usb device constructor (usbcore-internal)
655 * @parent: hub to which device is connected; null to allocate a root hub
656 * @bus: bus used to access the device
657 * @port1: one-based index of port; ignored for root hubs
658 * Context: !in_interrupt ()
660 * Only hub drivers (including virtual root hub drivers for host
661 * controllers) should ever call this.
663 * This call may not be used in a non-sleeping context.
666 usb_alloc_dev(struct usb_device *parent, struct usb_bus *bus, unsigned port1)
668 struct usb_device *dev;
670 dev = kmalloc(sizeof(*dev), GFP_KERNEL);
674 memset(dev, 0, sizeof(*dev));
676 bus = usb_bus_get(bus);
682 device_initialize(&dev->dev);
683 dev->dev.bus = &usb_bus_type;
684 dev->dev.dma_mask = bus->controller->dma_mask;
685 dev->dev.driver_data = &usb_generic_driver_data;
686 dev->dev.driver = &usb_generic_driver;
687 dev->dev.release = usb_release_dev;
688 dev->state = USB_STATE_ATTACHED;
690 INIT_LIST_HEAD(&dev->ep0.urb_list);
691 dev->ep0.desc.bLength = USB_DT_ENDPOINT_SIZE;
692 dev->ep0.desc.bDescriptorType = USB_DT_ENDPOINT;
693 /* ep0 maxpacket comes later, from device descriptor */
694 dev->ep_in[0] = dev->ep_out[0] = &dev->ep0;
696 /* Save readable and stable topology id, distinguishing devices
697 * by location for diagnostics, tools, driver model, etc. The
698 * string is a path along hub ports, from the root. Each device's
699 * dev->devpath will be stable until USB is re-cabled, and hubs
700 * are often labeled with these port numbers. The bus_id isn't
701 * as stable: bus->busnum changes easily from modprobe order,
702 * cardbus or pci hotplugging, and so on.
704 if (unlikely (!parent)) {
705 dev->devpath [0] = '0';
707 dev->dev.parent = bus->controller;
708 sprintf (&dev->dev.bus_id[0], "usb%d", bus->busnum);
710 /* match any labeling on the hubs; it's one-based */
711 if (parent->devpath [0] == '0')
712 snprintf (dev->devpath, sizeof dev->devpath,
715 snprintf (dev->devpath, sizeof dev->devpath,
716 "%s.%d", parent->devpath, port1);
718 dev->dev.parent = &parent->dev;
719 sprintf (&dev->dev.bus_id[0], "%d-%s",
720 bus->busnum, dev->devpath);
722 /* hub driver sets up TT records */
726 dev->parent = parent;
727 INIT_LIST_HEAD(&dev->filelist);
729 init_MUTEX(&dev->serialize);
735 * usb_get_dev - increments the reference count of the usb device structure
736 * @dev: the device being referenced
738 * Each live reference to a device should be refcounted.
740 * Drivers for USB interfaces should normally record such references in
741 * their probe() methods, when they bind to an interface, and release
742 * them by calling usb_put_dev(), in their disconnect() methods.
744 * A pointer to the device with the incremented reference counter is returned.
746 struct usb_device *usb_get_dev(struct usb_device *dev)
749 get_device(&dev->dev);
754 * usb_put_dev - release a use of the usb device structure
755 * @dev: device that's been disconnected
757 * Must be called when a user of a device is finished with it. When the last
758 * user of the device calls this function, the memory of the device is freed.
760 void usb_put_dev(struct usb_device *dev)
763 put_device(&dev->dev);
767 * usb_get_intf - increments the reference count of the usb interface structure
768 * @intf: the interface being referenced
770 * Each live reference to a interface must be refcounted.
772 * Drivers for USB interfaces should normally record such references in
773 * their probe() methods, when they bind to an interface, and release
774 * them by calling usb_put_intf(), in their disconnect() methods.
776 * A pointer to the interface with the incremented reference counter is
779 struct usb_interface *usb_get_intf(struct usb_interface *intf)
782 get_device(&intf->dev);
787 * usb_put_intf - release a use of the usb interface structure
788 * @intf: interface that's been decremented
790 * Must be called when a user of an interface is finished with it. When the
791 * last user of the interface calls this function, the memory of the interface
794 void usb_put_intf(struct usb_interface *intf)
797 put_device(&intf->dev);
801 /* USB device locking
803 * Although locking USB devices should be straightforward, it is
804 * complicated by the way the driver-model core works. When a new USB
805 * driver is registered or unregistered, the core will automatically
806 * probe or disconnect all matching interfaces on all USB devices while
807 * holding the USB subsystem writelock. There's no good way for us to
808 * tell which devices will be used or to lock them beforehand; our only
809 * option is to effectively lock all the USB devices.
811 * We do that by using a private rw-semaphore, usb_all_devices_rwsem.
812 * When locking an individual device you must first acquire the rwsem's
813 * readlock. When a driver is registered or unregistered the writelock
814 * must be held. These actions are encapsulated in the subroutines
815 * below, so all a driver needs to do is call usb_lock_device() and
816 * usb_unlock_device().
818 * Complications arise when several devices are to be locked at the same
819 * time. Only hub-aware drivers that are part of usbcore ever have to
820 * do this; nobody else needs to worry about it. The problem is that
821 * usb_lock_device() must not be called to lock a second device since it
822 * would acquire the rwsem's readlock reentrantly, leading to deadlock if
823 * another thread was waiting for the writelock. The solution is simple:
825 * When locking more than one device, call usb_lock_device()
826 * to lock the first one. Lock the others by calling
827 * down(&udev->serialize) directly.
829 * When unlocking multiple devices, use up(&udev->serialize)
830 * to unlock all but the last one. Unlock the last one by
831 * calling usb_unlock_device().
833 * When locking both a device and its parent, always lock the
838 * usb_lock_device - acquire the lock for a usb device structure
839 * @udev: device that's being locked
841 * Use this routine when you don't hold any other device locks;
842 * to acquire nested inner locks call down(&udev->serialize) directly.
843 * This is necessary for proper interaction with usb_lock_all_devices().
845 void usb_lock_device(struct usb_device *udev)
847 down_read(&usb_all_devices_rwsem);
848 down(&udev->serialize);
852 * usb_trylock_device - attempt to acquire the lock for a usb device structure
853 * @udev: device that's being locked
855 * Don't use this routine if you already hold a device lock;
856 * use down_trylock(&udev->serialize) instead.
857 * This is necessary for proper interaction with usb_lock_all_devices().
859 * Returns 1 if successful, 0 if contention.
861 int usb_trylock_device(struct usb_device *udev)
863 if (!down_read_trylock(&usb_all_devices_rwsem))
865 if (down_trylock(&udev->serialize)) {
866 up_read(&usb_all_devices_rwsem);
873 * usb_lock_device_for_reset - cautiously acquire the lock for a
874 * usb device structure
875 * @udev: device that's being locked
876 * @iface: interface bound to the driver making the request (optional)
878 * Attempts to acquire the device lock, but fails if the device is
879 * NOTATTACHED or SUSPENDED, or if iface is specified and the interface
880 * is neither BINDING nor BOUND. Rather than sleeping to wait for the
881 * lock, the routine polls repeatedly. This is to prevent deadlock with
882 * disconnect; in some drivers (such as usb-storage) the disconnect()
883 * callback will block waiting for a device reset to complete.
885 * Returns a negative error code for failure, otherwise 1 or 0 to indicate
886 * that the device will or will not have to be unlocked. (0 can be
887 * returned when an interface is given and is BINDING, because in that
888 * case the driver already owns the device lock.)
890 int usb_lock_device_for_reset(struct usb_device *udev,
891 struct usb_interface *iface)
893 if (udev->state == USB_STATE_NOTATTACHED)
895 if (udev->state == USB_STATE_SUSPENDED)
896 return -EHOSTUNREACH;
898 switch (iface->condition) {
899 case USB_INTERFACE_BINDING:
901 case USB_INTERFACE_BOUND:
908 while (!usb_trylock_device(udev)) {
910 if (udev->state == USB_STATE_NOTATTACHED)
912 if (udev->state == USB_STATE_SUSPENDED)
913 return -EHOSTUNREACH;
914 if (iface && iface->condition != USB_INTERFACE_BOUND)
921 * usb_unlock_device - release the lock for a usb device structure
922 * @udev: device that's being unlocked
924 * Use this routine when releasing the only device lock you hold;
925 * to release inner nested locks call up(&udev->serialize) directly.
926 * This is necessary for proper interaction with usb_lock_all_devices().
928 void usb_unlock_device(struct usb_device *udev)
930 up(&udev->serialize);
931 up_read(&usb_all_devices_rwsem);
935 * usb_lock_all_devices - acquire the lock for all usb device structures
937 * This is necessary when registering a new driver or probing a bus,
938 * since the driver-model core may try to use any usb_device.
940 void usb_lock_all_devices(void)
942 down_write(&usb_all_devices_rwsem);
946 * usb_unlock_all_devices - release the lock for all usb device structures
948 void usb_unlock_all_devices(void)
950 up_write(&usb_all_devices_rwsem);
954 static struct usb_device *match_device(struct usb_device *dev,
955 u16 vendor_id, u16 product_id)
957 struct usb_device *ret_dev = NULL;
960 dev_dbg(&dev->dev, "check for vendor %04x, product %04x ...\n",
961 le16_to_cpu(dev->descriptor.idVendor),
962 le16_to_cpu(dev->descriptor.idProduct));
964 /* see if this device matches */
965 if ((vendor_id == le16_to_cpu(dev->descriptor.idVendor)) &&
966 (product_id == le16_to_cpu(dev->descriptor.idProduct))) {
967 dev_dbg (&dev->dev, "matched this device!\n");
968 ret_dev = usb_get_dev(dev);
972 /* look through all of the children of this device */
973 for (child = 0; child < dev->maxchild; ++child) {
974 if (dev->children[child]) {
975 down(&dev->children[child]->serialize);
976 ret_dev = match_device(dev->children[child],
977 vendor_id, product_id);
978 up(&dev->children[child]->serialize);
988 * usb_find_device - find a specific usb device in the system
989 * @vendor_id: the vendor id of the device to find
990 * @product_id: the product id of the device to find
992 * Returns a pointer to a struct usb_device if such a specified usb
993 * device is present in the system currently. The usage count of the
994 * device will be incremented if a device is found. Make sure to call
995 * usb_put_dev() when the caller is finished with the device.
997 * If a device with the specified vendor and product id is not found,
1000 struct usb_device *usb_find_device(u16 vendor_id, u16 product_id)
1002 struct list_head *buslist;
1003 struct usb_bus *bus;
1004 struct usb_device *dev = NULL;
1006 down(&usb_bus_list_lock);
1007 for (buslist = usb_bus_list.next;
1008 buslist != &usb_bus_list;
1009 buslist = buslist->next) {
1010 bus = container_of(buslist, struct usb_bus, bus_list);
1013 usb_lock_device(bus->root_hub);
1014 dev = match_device(bus->root_hub, vendor_id, product_id);
1015 usb_unlock_device(bus->root_hub);
1020 up(&usb_bus_list_lock);
1025 * usb_get_current_frame_number - return current bus frame number
1026 * @dev: the device whose bus is being queried
1028 * Returns the current frame number for the USB host controller
1029 * used with the given USB device. This can be used when scheduling
1030 * isochronous requests.
1032 * Note that different kinds of host controller have different
1033 * "scheduling horizons". While one type might support scheduling only
1034 * 32 frames into the future, others could support scheduling up to
1035 * 1024 frames into the future.
1037 int usb_get_current_frame_number(struct usb_device *dev)
1039 return dev->bus->op->get_frame_number (dev);
1042 /*-------------------------------------------------------------------*/
1044 * __usb_get_extra_descriptor() finds a descriptor of specific type in the
1045 * extra field of the interface and endpoint descriptor structs.
1048 int __usb_get_extra_descriptor(char *buffer, unsigned size,
1049 unsigned char type, void **ptr)
1051 struct usb_descriptor_header *header;
1053 while (size >= sizeof(struct usb_descriptor_header)) {
1054 header = (struct usb_descriptor_header *)buffer;
1056 if (header->bLength < 2) {
1058 "%s: bogus descriptor, type %d length %d\n",
1060 header->bDescriptorType,
1065 if (header->bDescriptorType == type) {
1070 buffer += header->bLength;
1071 size -= header->bLength;
1077 * usb_buffer_alloc - allocate dma-consistent buffer for URB_NO_xxx_DMA_MAP
1078 * @dev: device the buffer will be used with
1079 * @size: requested buffer size
1080 * @mem_flags: affect whether allocation may block
1081 * @dma: used to return DMA address of buffer
1083 * Return value is either null (indicating no buffer could be allocated), or
1084 * the cpu-space pointer to a buffer that may be used to perform DMA to the
1085 * specified device. Such cpu-space buffers are returned along with the DMA
1086 * address (through the pointer provided).
1088 * These buffers are used with URB_NO_xxx_DMA_MAP set in urb->transfer_flags
1089 * to avoid behaviors like using "DMA bounce buffers", or tying down I/O
1090 * mapping hardware for long idle periods. The implementation varies between
1091 * platforms, depending on details of how DMA will work to this device.
1092 * Using these buffers also helps prevent cacheline sharing problems on
1093 * architectures where CPU caches are not DMA-coherent.
1095 * When the buffer is no longer used, free it with usb_buffer_free().
1097 void *usb_buffer_alloc (
1098 struct usb_device *dev,
1104 if (!dev || !dev->bus || !dev->bus->op || !dev->bus->op->buffer_alloc)
1106 return dev->bus->op->buffer_alloc (dev->bus, size, mem_flags, dma);
1110 * usb_buffer_free - free memory allocated with usb_buffer_alloc()
1111 * @dev: device the buffer was used with
1112 * @size: requested buffer size
1113 * @addr: CPU address of buffer
1114 * @dma: DMA address of buffer
1116 * This reclaims an I/O buffer, letting it be reused. The memory must have
1117 * been allocated using usb_buffer_alloc(), and the parameters must match
1118 * those provided in that allocation request.
1120 void usb_buffer_free (
1121 struct usb_device *dev,
1127 if (!dev || !dev->bus || !dev->bus->op || !dev->bus->op->buffer_free)
1129 dev->bus->op->buffer_free (dev->bus, size, addr, dma);
1133 * usb_buffer_map - create DMA mapping(s) for an urb
1134 * @urb: urb whose transfer_buffer/setup_packet will be mapped
1136 * Return value is either null (indicating no buffer could be mapped), or
1137 * the parameter. URB_NO_TRANSFER_DMA_MAP and URB_NO_SETUP_DMA_MAP are
1138 * added to urb->transfer_flags if the operation succeeds. If the device
1139 * is connected to this system through a non-DMA controller, this operation
1142 * This call would normally be used for an urb which is reused, perhaps
1143 * as the target of a large periodic transfer, with usb_buffer_dmasync()
1144 * calls to synchronize memory and dma state.
1146 * Reverse the effect of this call with usb_buffer_unmap().
1148 struct urb *usb_buffer_map (struct urb *urb)
1150 struct usb_bus *bus;
1151 struct device *controller;
1155 || !(bus = urb->dev->bus)
1156 || !(controller = bus->controller))
1159 if (controller->dma_mask) {
1160 urb->transfer_dma = dma_map_single (controller,
1161 urb->transfer_buffer, urb->transfer_buffer_length,
1162 usb_pipein (urb->pipe)
1163 ? DMA_FROM_DEVICE : DMA_TO_DEVICE);
1164 if (usb_pipecontrol (urb->pipe))
1165 urb->setup_dma = dma_map_single (controller,
1167 sizeof (struct usb_ctrlrequest),
1169 // FIXME generic api broken like pci, can't report errors
1170 // if (urb->transfer_dma == DMA_ADDR_INVALID) return 0;
1172 urb->transfer_dma = ~0;
1173 urb->transfer_flags |= (URB_NO_TRANSFER_DMA_MAP
1174 | URB_NO_SETUP_DMA_MAP);
1178 /* XXX DISABLED, no users currently. If you wish to re-enable this
1179 * XXX please determine whether the sync is to transfer ownership of
1180 * XXX the buffer from device to cpu or vice verse, and thusly use the
1181 * XXX appropriate _for_{cpu,device}() method. -DaveM
1186 * usb_buffer_dmasync - synchronize DMA and CPU view of buffer(s)
1187 * @urb: urb whose transfer_buffer/setup_packet will be synchronized
1189 void usb_buffer_dmasync (struct urb *urb)
1191 struct usb_bus *bus;
1192 struct device *controller;
1195 || !(urb->transfer_flags & URB_NO_TRANSFER_DMA_MAP)
1197 || !(bus = urb->dev->bus)
1198 || !(controller = bus->controller))
1201 if (controller->dma_mask) {
1202 dma_sync_single (controller,
1203 urb->transfer_dma, urb->transfer_buffer_length,
1204 usb_pipein (urb->pipe)
1205 ? DMA_FROM_DEVICE : DMA_TO_DEVICE);
1206 if (usb_pipecontrol (urb->pipe))
1207 dma_sync_single (controller,
1209 sizeof (struct usb_ctrlrequest),
1216 * usb_buffer_unmap - free DMA mapping(s) for an urb
1217 * @urb: urb whose transfer_buffer will be unmapped
1219 * Reverses the effect of usb_buffer_map().
1221 void usb_buffer_unmap (struct urb *urb)
1223 struct usb_bus *bus;
1224 struct device *controller;
1227 || !(urb->transfer_flags & URB_NO_TRANSFER_DMA_MAP)
1229 || !(bus = urb->dev->bus)
1230 || !(controller = bus->controller))
1233 if (controller->dma_mask) {
1234 dma_unmap_single (controller,
1235 urb->transfer_dma, urb->transfer_buffer_length,
1236 usb_pipein (urb->pipe)
1237 ? DMA_FROM_DEVICE : DMA_TO_DEVICE);
1238 if (usb_pipecontrol (urb->pipe))
1239 dma_unmap_single (controller,
1241 sizeof (struct usb_ctrlrequest),
1244 urb->transfer_flags &= ~(URB_NO_TRANSFER_DMA_MAP
1245 | URB_NO_SETUP_DMA_MAP);
1249 * usb_buffer_map_sg - create scatterlist DMA mapping(s) for an endpoint
1250 * @dev: device to which the scatterlist will be mapped
1251 * @pipe: endpoint defining the mapping direction
1252 * @sg: the scatterlist to map
1253 * @nents: the number of entries in the scatterlist
1255 * Return value is either < 0 (indicating no buffers could be mapped), or
1256 * the number of DMA mapping array entries in the scatterlist.
1258 * The caller is responsible for placing the resulting DMA addresses from
1259 * the scatterlist into URB transfer buffer pointers, and for setting the
1260 * URB_NO_TRANSFER_DMA_MAP transfer flag in each of those URBs.
1262 * Top I/O rates come from queuing URBs, instead of waiting for each one
1263 * to complete before starting the next I/O. This is particularly easy
1264 * to do with scatterlists. Just allocate and submit one URB for each DMA
1265 * mapping entry returned, stopping on the first error or when all succeed.
1266 * Better yet, use the usb_sg_*() calls, which do that (and more) for you.
1268 * This call would normally be used when translating scatterlist requests,
1269 * rather than usb_buffer_map(), since on some hardware (with IOMMUs) it
1270 * may be able to coalesce mappings for improved I/O efficiency.
1272 * Reverse the effect of this call with usb_buffer_unmap_sg().
1274 int usb_buffer_map_sg (struct usb_device *dev, unsigned pipe,
1275 struct scatterlist *sg, int nents)
1277 struct usb_bus *bus;
1278 struct device *controller;
1281 || usb_pipecontrol (pipe)
1282 || !(bus = dev->bus)
1283 || !(controller = bus->controller)
1284 || !controller->dma_mask)
1287 // FIXME generic api broken like pci, can't report errors
1288 return dma_map_sg (controller, sg, nents,
1289 usb_pipein (pipe) ? DMA_FROM_DEVICE : DMA_TO_DEVICE);
1292 /* XXX DISABLED, no users currently. If you wish to re-enable this
1293 * XXX please determine whether the sync is to transfer ownership of
1294 * XXX the buffer from device to cpu or vice verse, and thusly use the
1295 * XXX appropriate _for_{cpu,device}() method. -DaveM
1300 * usb_buffer_dmasync_sg - synchronize DMA and CPU view of scatterlist buffer(s)
1301 * @dev: device to which the scatterlist will be mapped
1302 * @pipe: endpoint defining the mapping direction
1303 * @sg: the scatterlist to synchronize
1304 * @n_hw_ents: the positive return value from usb_buffer_map_sg
1306 * Use this when you are re-using a scatterlist's data buffers for
1307 * another USB request.
1309 void usb_buffer_dmasync_sg (struct usb_device *dev, unsigned pipe,
1310 struct scatterlist *sg, int n_hw_ents)
1312 struct usb_bus *bus;
1313 struct device *controller;
1316 || !(bus = dev->bus)
1317 || !(controller = bus->controller)
1318 || !controller->dma_mask)
1321 dma_sync_sg (controller, sg, n_hw_ents,
1322 usb_pipein (pipe) ? DMA_FROM_DEVICE : DMA_TO_DEVICE);
1327 * usb_buffer_unmap_sg - free DMA mapping(s) for a scatterlist
1328 * @dev: device to which the scatterlist will be mapped
1329 * @pipe: endpoint defining the mapping direction
1330 * @sg: the scatterlist to unmap
1331 * @n_hw_ents: the positive return value from usb_buffer_map_sg
1333 * Reverses the effect of usb_buffer_map_sg().
1335 void usb_buffer_unmap_sg (struct usb_device *dev, unsigned pipe,
1336 struct scatterlist *sg, int n_hw_ents)
1338 struct usb_bus *bus;
1339 struct device *controller;
1342 || !(bus = dev->bus)
1343 || !(controller = bus->controller)
1344 || !controller->dma_mask)
1347 dma_unmap_sg (controller, sg, n_hw_ents,
1348 usb_pipein (pipe) ? DMA_FROM_DEVICE : DMA_TO_DEVICE);
1351 static int usb_generic_suspend(struct device *dev, u32 state)
1353 struct usb_interface *intf;
1354 struct usb_driver *driver;
1356 if (dev->driver == &usb_generic_driver)
1357 return usb_suspend_device (to_usb_device(dev), state);
1359 if ((dev->driver == NULL) ||
1360 (dev->driver_data == &usb_generic_driver_data))
1363 intf = to_usb_interface(dev);
1364 driver = to_usb_driver(dev->driver);
1366 /* there's only one USB suspend state */
1367 if (intf->dev.power.power_state)
1370 if (driver->suspend)
1371 return driver->suspend(intf, state);
1375 static int usb_generic_resume(struct device *dev)
1377 struct usb_interface *intf;
1378 struct usb_driver *driver;
1380 /* devices resume through their hub */
1381 if (dev->driver == &usb_generic_driver)
1382 return usb_resume_device (to_usb_device(dev));
1384 if ((dev->driver == NULL) ||
1385 (dev->driver_data == &usb_generic_driver_data))
1388 intf = to_usb_interface(dev);
1389 driver = to_usb_driver(dev->driver);
1392 return driver->resume(intf);
1396 struct bus_type usb_bus_type = {
1398 .match = usb_device_match,
1399 .hotplug = usb_hotplug,
1400 .suspend = usb_generic_suspend,
1401 .resume = usb_generic_resume,
1406 static int __init usb_setup_disable(char *str)
1412 /* format to disable USB on kernel command line is: nousb */
1413 __setup("nousb", usb_setup_disable);
1418 * for external read access to <nousb>
1420 int usb_disabled(void)
1428 static int __init usb_init(void)
1432 pr_info ("%s: USB support disabled\n", usbcore_name);
1436 retval = bus_register(&usb_bus_type);
1439 retval = usb_host_init();
1441 goto host_init_failed;
1442 retval = usb_major_init();
1444 goto major_init_failed;
1445 retval = usbfs_init();
1447 goto fs_init_failed;
1448 retval = usb_hub_init();
1450 goto hub_init_failed;
1452 retval = driver_register(&usb_generic_driver);
1460 usb_major_cleanup();
1464 bus_unregister(&usb_bus_type);
1472 static void __exit usb_exit(void)
1474 /* This will matter if shutdown/reboot does exitcalls. */
1478 driver_unregister(&usb_generic_driver);
1479 usb_major_cleanup();
1483 bus_unregister(&usb_bus_type);
1486 subsys_initcall(usb_init);
1487 module_exit(usb_exit);
1490 * USB may be built into the kernel or be built as modules.
1491 * These symbols are exported for device (or host controller)
1492 * driver modules to use.
1495 EXPORT_SYMBOL(usb_register);
1496 EXPORT_SYMBOL(usb_deregister);
1497 EXPORT_SYMBOL(usb_disabled);
1499 EXPORT_SYMBOL(usb_alloc_dev);
1500 EXPORT_SYMBOL(usb_put_dev);
1501 EXPORT_SYMBOL(usb_get_dev);
1502 EXPORT_SYMBOL(usb_hub_tt_clear_buffer);
1504 EXPORT_SYMBOL(usb_lock_device);
1505 EXPORT_SYMBOL(usb_trylock_device);
1506 EXPORT_SYMBOL(usb_lock_device_for_reset);
1507 EXPORT_SYMBOL(usb_unlock_device);
1509 EXPORT_SYMBOL(usb_driver_claim_interface);
1510 EXPORT_SYMBOL(usb_driver_release_interface);
1511 EXPORT_SYMBOL(usb_match_id);
1512 EXPORT_SYMBOL(usb_find_interface);
1513 EXPORT_SYMBOL(usb_ifnum_to_if);
1514 EXPORT_SYMBOL(usb_altnum_to_altsetting);
1516 EXPORT_SYMBOL(usb_reset_device);
1517 EXPORT_SYMBOL(usb_disconnect);
1519 EXPORT_SYMBOL(__usb_get_extra_descriptor);
1521 EXPORT_SYMBOL(usb_find_device);
1522 EXPORT_SYMBOL(usb_get_current_frame_number);
1524 EXPORT_SYMBOL (usb_buffer_alloc);
1525 EXPORT_SYMBOL (usb_buffer_free);
1527 EXPORT_SYMBOL (usb_buffer_map);
1529 EXPORT_SYMBOL (usb_buffer_dmasync);
1531 EXPORT_SYMBOL (usb_buffer_unmap);
1533 EXPORT_SYMBOL (usb_buffer_map_sg);
1535 EXPORT_SYMBOL (usb_buffer_dmasync_sg);
1537 EXPORT_SYMBOL (usb_buffer_unmap_sg);
1539 MODULE_LICENSE("GPL");