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 DECLARE_RWSEM(usb_all_devices_rwsem);
67 EXPORT_SYMBOL(usb_all_devices_rwsem);
70 static int generic_probe (struct device *dev)
74 static int generic_remove (struct device *dev)
79 static struct device_driver usb_generic_driver = {
83 .probe = generic_probe,
84 .remove = generic_remove,
87 static int usb_generic_driver_data;
89 /* called from driver core with usb_bus_type.subsys writelock */
90 int usb_probe_interface(struct device *dev)
92 struct usb_interface * intf = to_usb_interface(dev);
93 struct usb_driver * driver = to_usb_driver(dev->driver);
94 const struct usb_device_id *id;
97 dev_dbg(dev, "%s\n", __FUNCTION__);
101 /* FIXME we'd much prefer to just resume it ... */
102 if (interface_to_usbdev(intf)->state == USB_STATE_SUSPENDED)
103 return -EHOSTUNREACH;
105 id = usb_match_id (intf, driver->id_table);
107 dev_dbg (dev, "%s - got id\n", __FUNCTION__);
108 intf->condition = USB_INTERFACE_BINDING;
109 error = driver->probe (intf, id);
110 intf->condition = error ? USB_INTERFACE_UNBOUND :
117 /* called from driver core with usb_bus_type.subsys writelock */
118 int usb_unbind_interface(struct device *dev)
120 struct usb_interface *intf = to_usb_interface(dev);
121 struct usb_driver *driver = to_usb_driver(intf->dev.driver);
123 intf->condition = USB_INTERFACE_UNBINDING;
125 /* release all urbs for this interface */
126 usb_disable_interface(interface_to_usbdev(intf), intf);
128 if (driver && driver->disconnect)
129 driver->disconnect(intf);
131 /* reset other interface state */
132 usb_set_interface(interface_to_usbdev(intf),
133 intf->altsetting[0].desc.bInterfaceNumber,
135 usb_set_intfdata(intf, NULL);
136 intf->condition = USB_INTERFACE_UNBOUND;
142 * usb_register - register a USB driver
143 * @new_driver: USB operations for the driver
145 * Registers a USB driver with the USB core. The list of unattached
146 * interfaces will be rescanned whenever a new driver is added, allowing
147 * the new driver to attach to any recognized devices.
148 * Returns a negative error code on failure and 0 on success.
150 * NOTE: if you want your driver to use the USB major number, you must call
151 * usb_register_dev() to enable that functionality. This function no longer
152 * takes care of that.
154 int usb_register(struct usb_driver *new_driver)
161 new_driver->driver.name = (char *)new_driver->name;
162 new_driver->driver.bus = &usb_bus_type;
163 new_driver->driver.probe = usb_probe_interface;
164 new_driver->driver.remove = usb_unbind_interface;
165 new_driver->driver.owner = new_driver->owner;
167 usb_lock_all_devices();
168 retval = driver_register(&new_driver->driver);
169 usb_unlock_all_devices();
172 pr_info("%s: registered new driver %s\n",
173 usbcore_name, new_driver->name);
174 usbfs_update_special();
176 printk(KERN_ERR "%s: error %d registering driver %s\n",
177 usbcore_name, retval, new_driver->name);
184 * usb_deregister - unregister a USB driver
185 * @driver: USB operations of the driver to unregister
186 * Context: must be able to sleep
188 * Unlinks the specified driver from the internal USB driver list.
190 * NOTE: If you called usb_register_dev(), you still need to call
191 * usb_deregister_dev() to clean up your driver's allocated minor numbers,
192 * this * call will no longer do it for you.
194 void usb_deregister(struct usb_driver *driver)
196 pr_info("%s: deregistering driver %s\n", usbcore_name, driver->name);
198 usb_lock_all_devices();
199 driver_unregister (&driver->driver);
200 usb_unlock_all_devices();
202 usbfs_update_special();
206 * usb_ifnum_to_if - get the interface object with a given interface number
207 * @dev: the device whose current configuration is considered
208 * @ifnum: the desired interface
210 * This walks the device descriptor for the currently active configuration
211 * and returns a pointer to the interface with that particular interface
214 * Note that configuration descriptors are not required to assign interface
215 * numbers sequentially, so that it would be incorrect to assume that
216 * the first interface in that descriptor corresponds to interface zero.
217 * This routine helps device drivers avoid such mistakes.
218 * However, you should make sure that you do the right thing with any
219 * alternate settings available for this interfaces.
221 * Don't call this function unless you are bound to one of the interfaces
222 * on this device or you have locked the device!
224 struct usb_interface *usb_ifnum_to_if(struct usb_device *dev, unsigned ifnum)
226 struct usb_host_config *config = dev->actconfig;
231 for (i = 0; i < config->desc.bNumInterfaces; i++)
232 if (config->interface[i]->altsetting[0]
233 .desc.bInterfaceNumber == ifnum)
234 return config->interface[i];
240 * usb_altnum_to_altsetting - get the altsetting structure with a given
241 * alternate setting number.
242 * @intf: the interface containing the altsetting in question
243 * @altnum: the desired alternate setting number
245 * This searches the altsetting array of the specified interface for
246 * an entry with the correct bAlternateSetting value and returns a pointer
247 * to that entry, or null.
249 * Note that altsettings need not be stored sequentially by number, so
250 * it would be incorrect to assume that the first altsetting entry in
251 * the array corresponds to altsetting zero. This routine helps device
252 * drivers avoid such mistakes.
254 * Don't call this function unless you are bound to the intf interface
255 * or you have locked the device!
257 struct usb_host_interface *usb_altnum_to_altsetting(struct usb_interface *intf,
262 for (i = 0; i < intf->num_altsetting; i++) {
263 if (intf->altsetting[i].desc.bAlternateSetting == altnum)
264 return &intf->altsetting[i];
270 * usb_epnum_to_ep_desc - get the endpoint object with a given endpoint number
271 * @dev: the device whose current configuration+altsettings is considered
272 * @epnum: the desired endpoint, masked with USB_DIR_IN as appropriate.
274 * This walks the device descriptor for the currently active configuration,
275 * and returns a pointer to the endpoint with that particular endpoint
278 * Note that interface descriptors are not required to list endpoint
279 * numbers in any standardized order, so that it would be wrong to
280 * assume that ep2in precedes either ep5in, ep2out, or even ep1out.
281 * This routine helps device drivers avoid such mistakes.
283 struct usb_endpoint_descriptor *
284 usb_epnum_to_ep_desc(struct usb_device *dev, unsigned epnum)
286 struct usb_host_config *config = dev->actconfig;
291 for (i = 0; i < config->desc.bNumInterfaces; i++) {
292 struct usb_interface *intf;
293 struct usb_host_interface *alt;
295 /* only endpoints in current altsetting are active */
296 intf = config->interface[i];
297 alt = intf->cur_altsetting;
299 for (k = 0; k < alt->desc.bNumEndpoints; k++)
300 if (epnum == alt->endpoint[k].desc.bEndpointAddress)
301 return &alt->endpoint[k].desc;
308 * usb_driver_claim_interface - bind a driver to an interface
309 * @driver: the driver to be bound
310 * @iface: the interface to which it will be bound; must be in the
311 * usb device's active configuration
312 * @priv: driver data associated with that interface
314 * This is used by usb device drivers that need to claim more than one
315 * interface on a device when probing (audio and acm are current examples).
316 * No device driver should directly modify internal usb_interface or
317 * usb_device structure members.
319 * Few drivers should need to use this routine, since the most natural
320 * way to bind to an interface is to return the private data from
321 * the driver's probe() method.
323 * Callers must own the device lock and the driver model's usb_bus_type.subsys
324 * writelock. So driver probe() entries don't need extra locking,
325 * but other call contexts may need to explicitly claim those locks.
327 int usb_driver_claim_interface(struct usb_driver *driver,
328 struct usb_interface *iface, void* priv)
330 struct device *dev = &iface->dev;
335 dev->driver = &driver->driver;
336 usb_set_intfdata(iface, priv);
337 iface->condition = USB_INTERFACE_BOUND;
339 /* if interface was already added, bind now; else let
340 * the future device_add() bind it, bypassing probe()
342 if (!list_empty (&dev->bus_list))
343 device_bind_driver(dev);
349 * usb_driver_release_interface - unbind a driver from an interface
350 * @driver: the driver to be unbound
351 * @iface: the interface from which it will be unbound
353 * This can be used by drivers to release an interface without waiting
354 * for their disconnect() methods to be called. In typical cases this
355 * also causes the driver disconnect() method to be called.
357 * This call is synchronous, and may not be used in an interrupt context.
358 * Callers must own the device lock and the driver model's usb_bus_type.subsys
359 * writelock. So driver disconnect() entries don't need extra locking,
360 * but other call contexts may need to explicitly claim those locks.
362 void usb_driver_release_interface(struct usb_driver *driver,
363 struct usb_interface *iface)
365 struct device *dev = &iface->dev;
367 /* this should never happen, don't release something that's not ours */
368 if (!dev->driver || dev->driver != &driver->driver)
371 /* don't disconnect from disconnect(), or before dev_add() */
372 if (!list_empty (&dev->driver_list) && !list_empty (&dev->bus_list))
373 device_release_driver(dev);
376 usb_set_intfdata(iface, NULL);
377 iface->condition = USB_INTERFACE_UNBOUND;
381 * usb_match_id - find first usb_device_id matching device or interface
382 * @interface: the interface of interest
383 * @id: array of usb_device_id structures, terminated by zero entry
385 * usb_match_id searches an array of usb_device_id's and returns
386 * the first one matching the device or interface, or null.
387 * This is used when binding (or rebinding) a driver to an interface.
388 * Most USB device drivers will use this indirectly, through the usb core,
389 * but some layered driver frameworks use it directly.
390 * These device tables are exported with MODULE_DEVICE_TABLE, through
391 * modutils and "modules.usbmap", to support the driver loading
392 * functionality of USB hotplugging.
396 * The "match_flags" element in a usb_device_id controls which
397 * members are used. If the corresponding bit is set, the
398 * value in the device_id must match its corresponding member
399 * in the device or interface descriptor, or else the device_id
402 * "driver_info" is normally used only by device drivers,
403 * but you can create a wildcard "matches anything" usb_device_id
404 * as a driver's "modules.usbmap" entry if you provide an id with
405 * only a nonzero "driver_info" field. If you do this, the USB device
406 * driver's probe() routine should use additional intelligence to
407 * decide whether to bind to the specified interface.
409 * What Makes Good usb_device_id Tables:
411 * The match algorithm is very simple, so that intelligence in
412 * driver selection must come from smart driver id records.
413 * Unless you have good reasons to use another selection policy,
414 * provide match elements only in related groups, and order match
415 * specifiers from specific to general. Use the macros provided
416 * for that purpose if you can.
418 * The most specific match specifiers use device descriptor
419 * data. These are commonly used with product-specific matches;
420 * the USB_DEVICE macro lets you provide vendor and product IDs,
421 * and you can also match against ranges of product revisions.
422 * These are widely used for devices with application or vendor
423 * specific bDeviceClass values.
425 * Matches based on device class/subclass/protocol specifications
426 * are slightly more general; use the USB_DEVICE_INFO macro, or
427 * its siblings. These are used with single-function devices
428 * where bDeviceClass doesn't specify that each interface has
431 * Matches based on interface class/subclass/protocol are the
432 * most general; they let drivers bind to any interface on a
433 * multiple-function device. Use the USB_INTERFACE_INFO
434 * macro, or its siblings, to match class-per-interface style
435 * devices (as recorded in bDeviceClass).
437 * Within those groups, remember that not all combinations are
438 * meaningful. For example, don't give a product version range
439 * without vendor and product IDs; or specify a protocol without
440 * its associated class and subclass.
442 const struct usb_device_id *
443 usb_match_id(struct usb_interface *interface, const struct usb_device_id *id)
445 struct usb_host_interface *intf;
446 struct usb_device *dev;
448 /* proc_connectinfo in devio.c may call us with id == NULL. */
452 intf = interface->cur_altsetting;
453 dev = interface_to_usbdev(interface);
455 /* It is important to check that id->driver_info is nonzero,
456 since an entry that is all zeroes except for a nonzero
457 id->driver_info is the way to create an entry that
458 indicates that the driver want to examine every
459 device and interface. */
460 for (; id->idVendor || id->bDeviceClass || id->bInterfaceClass ||
461 id->driver_info; id++) {
463 if ((id->match_flags & USB_DEVICE_ID_MATCH_VENDOR) &&
464 id->idVendor != dev->descriptor.idVendor)
467 if ((id->match_flags & USB_DEVICE_ID_MATCH_PRODUCT) &&
468 id->idProduct != dev->descriptor.idProduct)
471 /* No need to test id->bcdDevice_lo != 0, since 0 is never
472 greater than any unsigned number. */
473 if ((id->match_flags & USB_DEVICE_ID_MATCH_DEV_LO) &&
474 (id->bcdDevice_lo > dev->descriptor.bcdDevice))
477 if ((id->match_flags & USB_DEVICE_ID_MATCH_DEV_HI) &&
478 (id->bcdDevice_hi < dev->descriptor.bcdDevice))
481 if ((id->match_flags & USB_DEVICE_ID_MATCH_DEV_CLASS) &&
482 (id->bDeviceClass != dev->descriptor.bDeviceClass))
485 if ((id->match_flags & USB_DEVICE_ID_MATCH_DEV_SUBCLASS) &&
486 (id->bDeviceSubClass!= dev->descriptor.bDeviceSubClass))
489 if ((id->match_flags & USB_DEVICE_ID_MATCH_DEV_PROTOCOL) &&
490 (id->bDeviceProtocol != dev->descriptor.bDeviceProtocol))
493 if ((id->match_flags & USB_DEVICE_ID_MATCH_INT_CLASS) &&
494 (id->bInterfaceClass != intf->desc.bInterfaceClass))
497 if ((id->match_flags & USB_DEVICE_ID_MATCH_INT_SUBCLASS) &&
498 (id->bInterfaceSubClass != intf->desc.bInterfaceSubClass))
501 if ((id->match_flags & USB_DEVICE_ID_MATCH_INT_PROTOCOL) &&
502 (id->bInterfaceProtocol != intf->desc.bInterfaceProtocol))
512 * usb_find_interface - find usb_interface pointer for driver and device
513 * @drv: the driver whose current configuration is considered
514 * @minor: the minor number of the desired device
516 * This walks the driver device list and returns a pointer to the interface
517 * with the matching minor. Note, this only works for devices that share the
520 struct usb_interface *usb_find_interface(struct usb_driver *drv, int minor)
522 struct list_head *entry;
524 struct usb_interface *intf;
526 list_for_each(entry, &drv->driver.devices) {
527 dev = container_of(entry, struct device, driver_list);
529 /* can't look at usb devices, only interfaces */
530 if (dev->driver == &usb_generic_driver)
533 intf = to_usb_interface(dev);
534 if (intf->minor == -1)
536 if (intf->minor == minor)
540 /* no device found that matches */
544 static int usb_device_match (struct device *dev, struct device_driver *drv)
546 struct usb_interface *intf;
547 struct usb_driver *usb_drv;
548 const struct usb_device_id *id;
550 /* check for generic driver, which we don't match any device with */
551 if (drv == &usb_generic_driver)
554 intf = to_usb_interface(dev);
555 usb_drv = to_usb_driver(drv);
557 id = usb_match_id (intf, usb_drv->id_table);
565 #ifdef CONFIG_HOTPLUG
568 * USB hotplugging invokes what /proc/sys/kernel/hotplug says
569 * (normally /sbin/hotplug) when USB devices get added or removed.
571 * This invokes a user mode policy agent, typically helping to load driver
572 * or other modules, configure the device, and more. Drivers can provide
573 * a MODULE_DEVICE_TABLE to help with module loading subtasks.
575 * We're called either from khubd (the typical case) or from root hub
576 * (init, kapmd, modprobe, rmmod, etc), but the agents need to handle
577 * delays in event delivery. Use sysfs (and DEVPATH) to make sure the
578 * device (and this configuration!) are still present.
580 static int usb_hotplug (struct device *dev, char **envp, int num_envp,
581 char *buffer, int buffer_size)
583 struct usb_interface *intf;
584 struct usb_device *usb_dev;
591 /* driver is often null here; dev_dbg() would oops */
592 pr_debug ("usb %s: hotplug\n", dev->bus_id);
594 /* Must check driver_data here, as on remove driver is always NULL */
595 if ((dev->driver == &usb_generic_driver) ||
596 (dev->driver_data == &usb_generic_driver_data))
599 intf = to_usb_interface(dev);
600 usb_dev = interface_to_usbdev (intf);
602 if (usb_dev->devnum < 0) {
603 pr_debug ("usb %s: already deleted?\n", dev->bus_id);
607 pr_debug ("usb %s: bus removed?\n", dev->bus_id);
611 #ifdef CONFIG_USB_DEVICEFS
612 /* If this is available, userspace programs can directly read
613 * all the device descriptors we don't tell them about. Or
614 * even act as usermode drivers.
616 * FIXME reduce hardwired intelligence here
618 if (add_hotplug_env_var(envp, num_envp, &i,
619 buffer, buffer_size, &length,
620 "DEVICE=/proc/bus/usb/%03d/%03d",
621 usb_dev->bus->busnum, usb_dev->devnum))
625 /* per-device configurations are common */
626 if (add_hotplug_env_var(envp, num_envp, &i,
627 buffer, buffer_size, &length,
629 usb_dev->descriptor.idVendor,
630 usb_dev->descriptor.idProduct,
631 usb_dev->descriptor.bcdDevice))
634 /* class-based driver binding models */
635 if (add_hotplug_env_var(envp, num_envp, &i,
636 buffer, buffer_size, &length,
638 usb_dev->descriptor.bDeviceClass,
639 usb_dev->descriptor.bDeviceSubClass,
640 usb_dev->descriptor.bDeviceProtocol))
643 if (usb_dev->descriptor.bDeviceClass == 0) {
644 struct usb_host_interface *alt = intf->cur_altsetting;
646 /* 2.4 only exposed interface zero. in 2.5, hotplug
647 * agents are called for all interfaces, and can use
648 * $DEVPATH/bInterfaceNumber if necessary.
650 if (add_hotplug_env_var(envp, num_envp, &i,
651 buffer, buffer_size, &length,
652 "INTERFACE=%d/%d/%d",
653 alt->desc.bInterfaceClass,
654 alt->desc.bInterfaceSubClass,
655 alt->desc.bInterfaceProtocol))
666 static int usb_hotplug (struct device *dev, char **envp,
667 int num_envp, char *buffer, int buffer_size)
672 #endif /* CONFIG_HOTPLUG */
675 * usb_release_dev - free a usb device structure when all users of it are finished.
676 * @dev: device that's been disconnected
678 * Will be called only by the device core when all users of this usb device are
681 static void usb_release_dev(struct device *dev)
683 struct usb_device *udev;
685 udev = to_usb_device(dev);
687 if (udev->bus && udev->bus->op && udev->bus->op->deallocate)
688 udev->bus->op->deallocate(udev);
689 usb_destroy_configuration(udev);
690 usb_bus_put(udev->bus);
695 * usb_alloc_dev - usb device constructor (usbcore-internal)
696 * @parent: hub to which device is connected; null to allocate a root hub
697 * @bus: bus used to access the device
698 * @port: zero based index of port; ignored for root hubs
699 * Context: !in_interrupt ()
701 * Only hub drivers (including virtual root hub drivers for host
702 * controllers) should ever call this.
704 * This call may not be used in a non-sleeping context.
707 usb_alloc_dev(struct usb_device *parent, struct usb_bus *bus, unsigned port)
709 struct usb_device *dev;
711 dev = kmalloc(sizeof(*dev), GFP_KERNEL);
715 memset(dev, 0, sizeof(*dev));
717 bus = usb_bus_get(bus);
723 device_initialize(&dev->dev);
724 dev->dev.bus = &usb_bus_type;
725 dev->dev.dma_mask = bus->controller->dma_mask;
726 dev->dev.driver_data = &usb_generic_driver_data;
727 dev->dev.driver = &usb_generic_driver;
728 dev->dev.release = usb_release_dev;
729 dev->state = USB_STATE_ATTACHED;
731 /* Save readable and stable topology id, distinguishing devices
732 * by location for diagnostics, tools, driver model, etc. The
733 * string is a path along hub ports, from the root. Each device's
734 * dev->devpath will be stable until USB is re-cabled, and hubs
735 * are often labeled with these port numbers. The bus_id isn't
736 * as stable: bus->busnum changes easily from modprobe order,
737 * cardbus or pci hotplugging, and so on.
739 if (unlikely (!parent)) {
740 dev->devpath [0] = '0';
742 dev->dev.parent = bus->controller;
743 sprintf (&dev->dev.bus_id[0], "usb%d", bus->busnum);
745 /* match any labeling on the hubs; it's one-based */
746 if (parent->devpath [0] == '0')
747 snprintf (dev->devpath, sizeof dev->devpath,
750 snprintf (dev->devpath, sizeof dev->devpath,
751 "%s.%d", parent->devpath, port + 1);
753 dev->dev.parent = &parent->dev;
754 sprintf (&dev->dev.bus_id[0], "%d-%s",
755 bus->busnum, dev->devpath);
757 /* hub driver sets up TT records */
761 dev->parent = parent;
762 INIT_LIST_HEAD(&dev->filelist);
764 init_MUTEX(&dev->serialize);
766 if (dev->bus->op->allocate)
767 if (dev->bus->op->allocate(dev)) {
777 * usb_get_dev - increments the reference count of the usb device structure
778 * @dev: the device being referenced
780 * Each live reference to a device should be refcounted.
782 * Drivers for USB interfaces should normally record such references in
783 * their probe() methods, when they bind to an interface, and release
784 * them by calling usb_put_dev(), in their disconnect() methods.
786 * A pointer to the device with the incremented reference counter is returned.
788 struct usb_device *usb_get_dev(struct usb_device *dev)
791 get_device(&dev->dev);
796 * usb_put_dev - release a use of the usb device structure
797 * @dev: device that's been disconnected
799 * Must be called when a user of a device is finished with it. When the last
800 * user of the device calls this function, the memory of the device is freed.
802 void usb_put_dev(struct usb_device *dev)
805 put_device(&dev->dev);
809 * usb_get_intf - increments the reference count of the usb interface structure
810 * @intf: the interface being referenced
812 * Each live reference to a interface must be refcounted.
814 * Drivers for USB interfaces should normally record such references in
815 * their probe() methods, when they bind to an interface, and release
816 * them by calling usb_put_intf(), in their disconnect() methods.
818 * A pointer to the interface with the incremented reference counter is
821 struct usb_interface *usb_get_intf(struct usb_interface *intf)
824 get_device(&intf->dev);
829 * usb_put_intf - release a use of the usb interface structure
830 * @intf: interface that's been decremented
832 * Must be called when a user of an interface is finished with it. When the
833 * last user of the interface calls this function, the memory of the interface
836 void usb_put_intf(struct usb_interface *intf)
839 put_device(&intf->dev);
843 /* USB device locking
845 * Although locking USB devices should be straightforward, it is
846 * complicated by the way the driver-model core works. When a new USB
847 * driver is registered or unregistered, the core will automatically
848 * probe or disconnect all matching interfaces on all USB devices while
849 * holding the USB subsystem writelock. There's no good way for us to
850 * tell which devices will be used or to lock them beforehand; our only
851 * option is to effectively lock all the USB devices.
853 * We do that by using a private rw-semaphore, usb_all_devices_rwsem.
854 * When locking an individual device you must first acquire the rwsem's
855 * readlock. When a driver is registered or unregistered the writelock
856 * must be held. These actions are encapsulated in the subroutines
857 * below, so all a driver needs to do is call usb_lock_device() and
858 * usb_unlock_device().
860 * Complications arise when several devices are to be locked at the same
861 * time. Only hub-aware drivers that are part of usbcore ever have to
862 * do this; nobody else needs to worry about it. The problem is that
863 * usb_lock_device() must not be called to lock a second device since it
864 * would acquire the rwsem's readlock reentrantly, leading to deadlock if
865 * another thread was waiting for the writelock. The solution is simple:
867 * When locking more than one device, call usb_lock_device()
868 * to lock the first one. Lock the others by calling
869 * down(&udev->serialize) directly.
871 * When unlocking multiple devices, use up(&udev->serialize)
872 * to unlock all but the last one. Unlock the last one by
873 * calling usb_unlock_device().
875 * When locking both a device and its parent, always lock the
880 * usb_lock_device - acquire the lock for a usb device structure
881 * @udev: device that's being locked
883 * Use this routine when you don't hold any other device locks;
884 * to acquire nested inner locks call down(&udev->serialize) directly.
885 * This is necessary for proper interaction with usb_lock_all_devices().
887 void usb_lock_device(struct usb_device *udev)
889 down_read(&usb_all_devices_rwsem);
890 down(&udev->serialize);
894 * usb_trylock_device - attempt to acquire the lock for a usb device structure
895 * @udev: device that's being locked
897 * Don't use this routine if you already hold a device lock;
898 * use down_trylock(&udev->serialize) instead.
899 * This is necessary for proper interaction with usb_lock_all_devices().
901 * Returns 1 if successful, 0 if contention.
903 int usb_trylock_device(struct usb_device *udev)
905 if (!down_read_trylock(&usb_all_devices_rwsem))
907 if (down_trylock(&udev->serialize)) {
908 up_read(&usb_all_devices_rwsem);
915 * usb_lock_device_for_reset - cautiously acquire the lock for a
916 * usb device structure
917 * @udev: device that's being locked
918 * @iface: interface bound to the driver making the request (optional)
920 * Attempts to acquire the device lock, but fails if the device is
921 * NOTATTACHED or SUSPENDED, or if iface is specified and the interface
922 * is neither BINDING nor BOUND. Rather than sleeping to wait for the
923 * lock, the routine polls repeatedly. This is to prevent deadlock with
924 * disconnect; in some drivers (such as usb-storage) the disconnect()
925 * callback will block waiting for a device reset to complete.
927 * Returns a negative error code for failure, otherwise 1 or 0 to indicate
928 * that the device will or will not have to be unlocked. (0 can be
929 * returned when an interface is given and is BINDING, because in that
930 * case the driver already owns the device lock.)
932 int usb_lock_device_for_reset(struct usb_device *udev,
933 struct usb_interface *iface)
935 if (udev->state == USB_STATE_NOTATTACHED)
937 if (udev->state == USB_STATE_SUSPENDED)
938 return -EHOSTUNREACH;
940 switch (iface->condition) {
941 case USB_INTERFACE_BINDING:
943 case USB_INTERFACE_BOUND:
950 while (!usb_trylock_device(udev)) {
952 if (udev->state == USB_STATE_NOTATTACHED)
954 if (udev->state == USB_STATE_SUSPENDED)
955 return -EHOSTUNREACH;
956 if (iface && iface->condition != USB_INTERFACE_BOUND)
963 * usb_unlock_device - release the lock for a usb device structure
964 * @udev: device that's being unlocked
966 * Use this routine when releasing the only device lock you hold;
967 * to release inner nested locks call up(&udev->serialize) directly.
968 * This is necessary for proper interaction with usb_lock_all_devices().
970 void usb_unlock_device(struct usb_device *udev)
972 up(&udev->serialize);
973 up_read(&usb_all_devices_rwsem);
977 * usb_lock_all_devices - acquire the lock for all usb device structures
979 * This is necessary when registering a new driver or probing a bus,
980 * since the driver-model core may try to use any usb_device.
982 void usb_lock_all_devices(void)
984 down_write(&usb_all_devices_rwsem);
988 * usb_unlock_all_devices - release the lock for all usb device structures
990 void usb_unlock_all_devices(void)
992 up_write(&usb_all_devices_rwsem);
996 static struct usb_device *match_device(struct usb_device *dev,
997 u16 vendor_id, u16 product_id)
999 struct usb_device *ret_dev = NULL;
1002 dev_dbg(&dev->dev, "check for vendor %04x, product %04x ...\n",
1003 dev->descriptor.idVendor,
1004 dev->descriptor.idProduct);
1006 /* see if this device matches */
1007 if ((dev->descriptor.idVendor == vendor_id) &&
1008 (dev->descriptor.idProduct == product_id)) {
1009 dev_dbg (&dev->dev, "matched this device!\n");
1010 ret_dev = usb_get_dev(dev);
1014 /* look through all of the children of this device */
1015 for (child = 0; child < dev->maxchild; ++child) {
1016 if (dev->children[child]) {
1017 down(&dev->children[child]->serialize);
1018 ret_dev = match_device(dev->children[child],
1019 vendor_id, product_id);
1020 up(&dev->children[child]->serialize);
1030 * usb_find_device - find a specific usb device in the system
1031 * @vendor_id: the vendor id of the device to find
1032 * @product_id: the product id of the device to find
1034 * Returns a pointer to a struct usb_device if such a specified usb
1035 * device is present in the system currently. The usage count of the
1036 * device will be incremented if a device is found. Make sure to call
1037 * usb_put_dev() when the caller is finished with the device.
1039 * If a device with the specified vendor and product id is not found,
1042 struct usb_device *usb_find_device(u16 vendor_id, u16 product_id)
1044 struct list_head *buslist;
1045 struct usb_bus *bus;
1046 struct usb_device *dev = NULL;
1048 down(&usb_bus_list_lock);
1049 for (buslist = usb_bus_list.next;
1050 buslist != &usb_bus_list;
1051 buslist = buslist->next) {
1052 bus = container_of(buslist, struct usb_bus, bus_list);
1055 usb_lock_device(bus->root_hub);
1056 dev = match_device(bus->root_hub, vendor_id, product_id);
1057 usb_unlock_device(bus->root_hub);
1062 up(&usb_bus_list_lock);
1067 * usb_get_current_frame_number - return current bus frame number
1068 * @dev: the device whose bus is being queried
1070 * Returns the current frame number for the USB host controller
1071 * used with the given USB device. This can be used when scheduling
1072 * isochronous requests.
1074 * Note that different kinds of host controller have different
1075 * "scheduling horizons". While one type might support scheduling only
1076 * 32 frames into the future, others could support scheduling up to
1077 * 1024 frames into the future.
1079 int usb_get_current_frame_number(struct usb_device *dev)
1081 return dev->bus->op->get_frame_number (dev);
1084 /*-------------------------------------------------------------------*/
1086 * __usb_get_extra_descriptor() finds a descriptor of specific type in the
1087 * extra field of the interface and endpoint descriptor structs.
1090 int __usb_get_extra_descriptor(char *buffer, unsigned size,
1091 unsigned char type, void **ptr)
1093 struct usb_descriptor_header *header;
1095 while (size >= sizeof(struct usb_descriptor_header)) {
1096 header = (struct usb_descriptor_header *)buffer;
1098 if (header->bLength < 2) {
1100 "%s: bogus descriptor, type %d length %d\n",
1102 header->bDescriptorType,
1107 if (header->bDescriptorType == type) {
1112 buffer += header->bLength;
1113 size -= header->bLength;
1119 * usb_buffer_alloc - allocate dma-consistent buffer for URB_NO_xxx_DMA_MAP
1120 * @dev: device the buffer will be used with
1121 * @size: requested buffer size
1122 * @mem_flags: affect whether allocation may block
1123 * @dma: used to return DMA address of buffer
1125 * Return value is either null (indicating no buffer could be allocated), or
1126 * the cpu-space pointer to a buffer that may be used to perform DMA to the
1127 * specified device. Such cpu-space buffers are returned along with the DMA
1128 * address (through the pointer provided).
1130 * These buffers are used with URB_NO_xxx_DMA_MAP set in urb->transfer_flags
1131 * to avoid behaviors like using "DMA bounce buffers", or tying down I/O
1132 * mapping hardware for long idle periods. The implementation varies between
1133 * platforms, depending on details of how DMA will work to this device.
1134 * Using these buffers also helps prevent cacheline sharing problems on
1135 * architectures where CPU caches are not DMA-coherent.
1137 * When the buffer is no longer used, free it with usb_buffer_free().
1139 void *usb_buffer_alloc (
1140 struct usb_device *dev,
1146 if (!dev || !dev->bus || !dev->bus->op || !dev->bus->op->buffer_alloc)
1148 return dev->bus->op->buffer_alloc (dev->bus, size, mem_flags, dma);
1152 * usb_buffer_free - free memory allocated with usb_buffer_alloc()
1153 * @dev: device the buffer was used with
1154 * @size: requested buffer size
1155 * @addr: CPU address of buffer
1156 * @dma: DMA address of buffer
1158 * This reclaims an I/O buffer, letting it be reused. The memory must have
1159 * been allocated using usb_buffer_alloc(), and the parameters must match
1160 * those provided in that allocation request.
1162 void usb_buffer_free (
1163 struct usb_device *dev,
1169 if (!dev || !dev->bus || !dev->bus->op || !dev->bus->op->buffer_free)
1171 dev->bus->op->buffer_free (dev->bus, size, addr, dma);
1175 * usb_buffer_map - create DMA mapping(s) for an urb
1176 * @urb: urb whose transfer_buffer/setup_packet will be mapped
1178 * Return value is either null (indicating no buffer could be mapped), or
1179 * the parameter. URB_NO_TRANSFER_DMA_MAP and URB_NO_SETUP_DMA_MAP are
1180 * added to urb->transfer_flags if the operation succeeds. If the device
1181 * is connected to this system through a non-DMA controller, this operation
1184 * This call would normally be used for an urb which is reused, perhaps
1185 * as the target of a large periodic transfer, with usb_buffer_dmasync()
1186 * calls to synchronize memory and dma state.
1188 * Reverse the effect of this call with usb_buffer_unmap().
1190 struct urb *usb_buffer_map (struct urb *urb)
1192 struct usb_bus *bus;
1193 struct device *controller;
1197 || !(bus = urb->dev->bus)
1198 || !(controller = bus->controller))
1201 if (controller->dma_mask) {
1202 urb->transfer_dma = dma_map_single (controller,
1203 urb->transfer_buffer, urb->transfer_buffer_length,
1204 usb_pipein (urb->pipe)
1205 ? DMA_FROM_DEVICE : DMA_TO_DEVICE);
1206 if (usb_pipecontrol (urb->pipe))
1207 urb->setup_dma = dma_map_single (controller,
1209 sizeof (struct usb_ctrlrequest),
1211 // FIXME generic api broken like pci, can't report errors
1212 // if (urb->transfer_dma == DMA_ADDR_INVALID) return 0;
1214 urb->transfer_dma = ~0;
1215 urb->transfer_flags |= (URB_NO_TRANSFER_DMA_MAP
1216 | URB_NO_SETUP_DMA_MAP);
1220 /* XXX DISABLED, no users currently. If you wish to re-enable this
1221 * XXX please determine whether the sync is to transfer ownership of
1222 * XXX the buffer from device to cpu or vice verse, and thusly use the
1223 * XXX appropriate _for_{cpu,device}() method. -DaveM
1228 * usb_buffer_dmasync - synchronize DMA and CPU view of buffer(s)
1229 * @urb: urb whose transfer_buffer/setup_packet will be synchronized
1231 void usb_buffer_dmasync (struct urb *urb)
1233 struct usb_bus *bus;
1234 struct device *controller;
1237 || !(urb->transfer_flags & URB_NO_TRANSFER_DMA_MAP)
1239 || !(bus = urb->dev->bus)
1240 || !(controller = bus->controller))
1243 if (controller->dma_mask) {
1244 dma_sync_single (controller,
1245 urb->transfer_dma, urb->transfer_buffer_length,
1246 usb_pipein (urb->pipe)
1247 ? DMA_FROM_DEVICE : DMA_TO_DEVICE);
1248 if (usb_pipecontrol (urb->pipe))
1249 dma_sync_single (controller,
1251 sizeof (struct usb_ctrlrequest),
1258 * usb_buffer_unmap - free DMA mapping(s) for an urb
1259 * @urb: urb whose transfer_buffer will be unmapped
1261 * Reverses the effect of usb_buffer_map().
1263 void usb_buffer_unmap (struct urb *urb)
1265 struct usb_bus *bus;
1266 struct device *controller;
1269 || !(urb->transfer_flags & URB_NO_TRANSFER_DMA_MAP)
1271 || !(bus = urb->dev->bus)
1272 || !(controller = bus->controller))
1275 if (controller->dma_mask) {
1276 dma_unmap_single (controller,
1277 urb->transfer_dma, urb->transfer_buffer_length,
1278 usb_pipein (urb->pipe)
1279 ? DMA_FROM_DEVICE : DMA_TO_DEVICE);
1280 if (usb_pipecontrol (urb->pipe))
1281 dma_unmap_single (controller,
1283 sizeof (struct usb_ctrlrequest),
1286 urb->transfer_flags &= ~(URB_NO_TRANSFER_DMA_MAP
1287 | URB_NO_SETUP_DMA_MAP);
1291 * usb_buffer_map_sg - create scatterlist DMA mapping(s) for an endpoint
1292 * @dev: device to which the scatterlist will be mapped
1293 * @pipe: endpoint defining the mapping direction
1294 * @sg: the scatterlist to map
1295 * @nents: the number of entries in the scatterlist
1297 * Return value is either < 0 (indicating no buffers could be mapped), or
1298 * the number of DMA mapping array entries in the scatterlist.
1300 * The caller is responsible for placing the resulting DMA addresses from
1301 * the scatterlist into URB transfer buffer pointers, and for setting the
1302 * URB_NO_TRANSFER_DMA_MAP transfer flag in each of those URBs.
1304 * Top I/O rates come from queuing URBs, instead of waiting for each one
1305 * to complete before starting the next I/O. This is particularly easy
1306 * to do with scatterlists. Just allocate and submit one URB for each DMA
1307 * mapping entry returned, stopping on the first error or when all succeed.
1308 * Better yet, use the usb_sg_*() calls, which do that (and more) for you.
1310 * This call would normally be used when translating scatterlist requests,
1311 * rather than usb_buffer_map(), since on some hardware (with IOMMUs) it
1312 * may be able to coalesce mappings for improved I/O efficiency.
1314 * Reverse the effect of this call with usb_buffer_unmap_sg().
1316 int usb_buffer_map_sg (struct usb_device *dev, unsigned pipe,
1317 struct scatterlist *sg, int nents)
1319 struct usb_bus *bus;
1320 struct device *controller;
1323 || usb_pipecontrol (pipe)
1324 || !(bus = dev->bus)
1325 || !(controller = bus->controller)
1326 || !controller->dma_mask)
1329 // FIXME generic api broken like pci, can't report errors
1330 return dma_map_sg (controller, sg, nents,
1331 usb_pipein (pipe) ? DMA_FROM_DEVICE : DMA_TO_DEVICE);
1334 /* XXX DISABLED, no users currently. If you wish to re-enable this
1335 * XXX please determine whether the sync is to transfer ownership of
1336 * XXX the buffer from device to cpu or vice verse, and thusly use the
1337 * XXX appropriate _for_{cpu,device}() method. -DaveM
1342 * usb_buffer_dmasync_sg - synchronize DMA and CPU view of scatterlist buffer(s)
1343 * @dev: device to which the scatterlist will be mapped
1344 * @pipe: endpoint defining the mapping direction
1345 * @sg: the scatterlist to synchronize
1346 * @n_hw_ents: the positive return value from usb_buffer_map_sg
1348 * Use this when you are re-using a scatterlist's data buffers for
1349 * another USB request.
1351 void usb_buffer_dmasync_sg (struct usb_device *dev, unsigned pipe,
1352 struct scatterlist *sg, int n_hw_ents)
1354 struct usb_bus *bus;
1355 struct device *controller;
1358 || !(bus = dev->bus)
1359 || !(controller = bus->controller)
1360 || !controller->dma_mask)
1363 dma_sync_sg (controller, sg, n_hw_ents,
1364 usb_pipein (pipe) ? DMA_FROM_DEVICE : DMA_TO_DEVICE);
1369 * usb_buffer_unmap_sg - free DMA mapping(s) for a scatterlist
1370 * @dev: device to which the scatterlist will be mapped
1371 * @pipe: endpoint defining the mapping direction
1372 * @sg: the scatterlist to unmap
1373 * @n_hw_ents: the positive return value from usb_buffer_map_sg
1375 * Reverses the effect of usb_buffer_map_sg().
1377 void usb_buffer_unmap_sg (struct usb_device *dev, unsigned pipe,
1378 struct scatterlist *sg, int n_hw_ents)
1380 struct usb_bus *bus;
1381 struct device *controller;
1384 || !(bus = dev->bus)
1385 || !(controller = bus->controller)
1386 || !controller->dma_mask)
1389 dma_unmap_sg (controller, sg, n_hw_ents,
1390 usb_pipein (pipe) ? DMA_FROM_DEVICE : DMA_TO_DEVICE);
1393 static int usb_generic_suspend(struct device *dev, u32 state)
1395 struct usb_interface *intf;
1396 struct usb_driver *driver;
1398 if (dev->driver == &usb_generic_driver)
1399 return usb_suspend_device (to_usb_device(dev), state);
1401 if ((dev->driver == NULL) ||
1402 (dev->driver_data == &usb_generic_driver_data))
1405 intf = to_usb_interface(dev);
1406 driver = to_usb_driver(dev->driver);
1408 /* there's only one USB suspend state */
1409 if (intf->dev.power.power_state)
1412 if (driver->suspend)
1413 return driver->suspend(intf, state);
1417 static int usb_generic_resume(struct device *dev)
1419 struct usb_interface *intf;
1420 struct usb_driver *driver;
1422 /* devices resume through their hub */
1423 if (dev->driver == &usb_generic_driver)
1424 return usb_resume_device (to_usb_device(dev));
1426 if ((dev->driver == NULL) ||
1427 (dev->driver_data == &usb_generic_driver_data))
1430 intf = to_usb_interface(dev);
1431 driver = to_usb_driver(dev->driver);
1434 return driver->resume(intf);
1438 struct bus_type usb_bus_type = {
1440 .match = usb_device_match,
1441 .hotplug = usb_hotplug,
1442 .suspend = usb_generic_suspend,
1443 .resume = usb_generic_resume,
1448 static int __init usb_setup_disable(char *str)
1454 /* format to disable USB on kernel command line is: nousb */
1455 __setup("nousb", usb_setup_disable);
1460 * for external read access to <nousb>
1462 int usb_disabled(void)
1470 static int __init usb_init(void)
1474 pr_info ("%s: USB support disabled\n", usbcore_name);
1478 retval = bus_register(&usb_bus_type);
1481 retval = usb_host_init();
1483 goto host_init_failed;
1484 retval = usb_major_init();
1486 goto major_init_failed;
1487 retval = usbfs_init();
1489 goto fs_init_failed;
1490 retval = usb_hub_init();
1492 goto hub_init_failed;
1494 retval = driver_register(&usb_generic_driver);
1502 usb_major_cleanup();
1506 bus_unregister(&usb_bus_type);
1514 static void __exit usb_exit(void)
1516 /* This will matter if shutdown/reboot does exitcalls. */
1520 driver_unregister(&usb_generic_driver);
1521 usb_major_cleanup();
1525 bus_unregister(&usb_bus_type);
1528 subsys_initcall(usb_init);
1529 module_exit(usb_exit);
1532 * USB may be built into the kernel or be built as modules.
1533 * These symbols are exported for device (or host controller)
1534 * driver modules to use.
1536 EXPORT_SYMBOL(usb_epnum_to_ep_desc);
1538 EXPORT_SYMBOL(usb_register);
1539 EXPORT_SYMBOL(usb_deregister);
1540 EXPORT_SYMBOL(usb_disabled);
1542 EXPORT_SYMBOL(usb_alloc_dev);
1543 EXPORT_SYMBOL(usb_put_dev);
1544 EXPORT_SYMBOL(usb_get_dev);
1545 EXPORT_SYMBOL(usb_hub_tt_clear_buffer);
1547 EXPORT_SYMBOL(usb_lock_device);
1548 EXPORT_SYMBOL(usb_trylock_device);
1549 EXPORT_SYMBOL(usb_lock_device_for_reset);
1550 EXPORT_SYMBOL(usb_unlock_device);
1552 EXPORT_SYMBOL(usb_driver_claim_interface);
1553 EXPORT_SYMBOL(usb_driver_release_interface);
1554 EXPORT_SYMBOL(usb_match_id);
1555 EXPORT_SYMBOL(usb_find_interface);
1556 EXPORT_SYMBOL(usb_ifnum_to_if);
1557 EXPORT_SYMBOL(usb_altnum_to_altsetting);
1559 EXPORT_SYMBOL(usb_reset_device);
1560 EXPORT_SYMBOL(usb_disconnect);
1562 EXPORT_SYMBOL(__usb_get_extra_descriptor);
1564 EXPORT_SYMBOL(usb_find_device);
1565 EXPORT_SYMBOL(usb_get_current_frame_number);
1567 EXPORT_SYMBOL (usb_buffer_alloc);
1568 EXPORT_SYMBOL (usb_buffer_free);
1570 EXPORT_SYMBOL (usb_buffer_map);
1572 EXPORT_SYMBOL (usb_buffer_dmasync);
1574 EXPORT_SYMBOL (usb_buffer_unmap);
1576 EXPORT_SYMBOL (usb_buffer_map_sg);
1578 EXPORT_SYMBOL (usb_buffer_dmasync_sg);
1580 EXPORT_SYMBOL (usb_buffer_unmap_sg);
1582 MODULE_LICENSE("GPL");