xref: /linux/drivers/usb/core/usb.c (revision f3d9478b2ce468c3115b02ecae7e975990697f15)
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/usb.h>
36 #include <linux/mutex.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 
51 
52 /**
53  * usb_ifnum_to_if - get the interface object with a given interface number
54  * @dev: the device whose current configuration is considered
55  * @ifnum: the desired interface
56  *
57  * This walks the device descriptor for the currently active configuration
58  * and returns a pointer to the interface with that particular interface
59  * number, or null.
60  *
61  * Note that configuration descriptors are not required to assign interface
62  * numbers sequentially, so that it would be incorrect to assume that
63  * the first interface in that descriptor corresponds to interface zero.
64  * This routine helps device drivers avoid such mistakes.
65  * However, you should make sure that you do the right thing with any
66  * alternate settings available for this interfaces.
67  *
68  * Don't call this function unless you are bound to one of the interfaces
69  * on this device or you have locked the device!
70  */
71 struct usb_interface *usb_ifnum_to_if(struct usb_device *dev, unsigned ifnum)
72 {
73 	struct usb_host_config *config = dev->actconfig;
74 	int i;
75 
76 	if (!config)
77 		return NULL;
78 	for (i = 0; i < config->desc.bNumInterfaces; i++)
79 		if (config->interface[i]->altsetting[0]
80 				.desc.bInterfaceNumber == ifnum)
81 			return config->interface[i];
82 
83 	return NULL;
84 }
85 
86 /**
87  * usb_altnum_to_altsetting - get the altsetting structure with a given
88  *	alternate setting number.
89  * @intf: the interface containing the altsetting in question
90  * @altnum: the desired alternate setting number
91  *
92  * This searches the altsetting array of the specified interface for
93  * an entry with the correct bAlternateSetting value and returns a pointer
94  * to that entry, or null.
95  *
96  * Note that altsettings need not be stored sequentially by number, so
97  * it would be incorrect to assume that the first altsetting entry in
98  * the array corresponds to altsetting zero.  This routine helps device
99  * drivers avoid such mistakes.
100  *
101  * Don't call this function unless you are bound to the intf interface
102  * or you have locked the device!
103  */
104 struct usb_host_interface *usb_altnum_to_altsetting(struct usb_interface *intf,
105 		unsigned int altnum)
106 {
107 	int i;
108 
109 	for (i = 0; i < intf->num_altsetting; i++) {
110 		if (intf->altsetting[i].desc.bAlternateSetting == altnum)
111 			return &intf->altsetting[i];
112 	}
113 	return NULL;
114 }
115 
116 /**
117  * usb_driver_claim_interface - bind a driver to an interface
118  * @driver: the driver to be bound
119  * @iface: the interface to which it will be bound; must be in the
120  *	usb device's active configuration
121  * @priv: driver data associated with that interface
122  *
123  * This is used by usb device drivers that need to claim more than one
124  * interface on a device when probing (audio and acm are current examples).
125  * No device driver should directly modify internal usb_interface or
126  * usb_device structure members.
127  *
128  * Few drivers should need to use this routine, since the most natural
129  * way to bind to an interface is to return the private data from
130  * the driver's probe() method.
131  *
132  * Callers must own the device lock and the driver model's usb_bus_type.subsys
133  * writelock.  So driver probe() entries don't need extra locking,
134  * but other call contexts may need to explicitly claim those locks.
135  */
136 int usb_driver_claim_interface(struct usb_driver *driver,
137 				struct usb_interface *iface, void* priv)
138 {
139 	struct device *dev = &iface->dev;
140 
141 	if (dev->driver)
142 		return -EBUSY;
143 
144 	dev->driver = &driver->driver;
145 	usb_set_intfdata(iface, priv);
146 	iface->condition = USB_INTERFACE_BOUND;
147 	mark_active(iface);
148 
149 	/* if interface was already added, bind now; else let
150 	 * the future device_add() bind it, bypassing probe()
151 	 */
152 	if (device_is_registered(dev))
153 		device_bind_driver(dev);
154 
155 	return 0;
156 }
157 
158 /**
159  * usb_driver_release_interface - unbind a driver from an interface
160  * @driver: the driver to be unbound
161  * @iface: the interface from which it will be unbound
162  *
163  * This can be used by drivers to release an interface without waiting
164  * for their disconnect() methods to be called.  In typical cases this
165  * also causes the driver disconnect() method to be called.
166  *
167  * This call is synchronous, and may not be used in an interrupt context.
168  * Callers must own the device lock and the driver model's usb_bus_type.subsys
169  * writelock.  So driver disconnect() entries don't need extra locking,
170  * but other call contexts may need to explicitly claim those locks.
171  */
172 void usb_driver_release_interface(struct usb_driver *driver,
173 					struct usb_interface *iface)
174 {
175 	struct device *dev = &iface->dev;
176 
177 	/* this should never happen, don't release something that's not ours */
178 	if (!dev->driver || dev->driver != &driver->driver)
179 		return;
180 
181 	/* don't release from within disconnect() */
182 	if (iface->condition != USB_INTERFACE_BOUND)
183 		return;
184 
185 	/* don't release if the interface hasn't been added yet */
186 	if (device_is_registered(dev)) {
187 		iface->condition = USB_INTERFACE_UNBINDING;
188 		device_release_driver(dev);
189 	}
190 
191 	dev->driver = NULL;
192 	usb_set_intfdata(iface, NULL);
193 	iface->condition = USB_INTERFACE_UNBOUND;
194 	mark_quiesced(iface);
195 }
196 
197 struct find_interface_arg {
198 	int minor;
199 	struct usb_interface *interface;
200 };
201 
202 static int __find_interface(struct device * dev, void * data)
203 {
204 	struct find_interface_arg *arg = data;
205 	struct usb_interface *intf;
206 
207 	/* can't look at usb devices, only interfaces */
208 	if (dev->driver == &usb_generic_driver)
209 		return 0;
210 
211 	intf = to_usb_interface(dev);
212 	if (intf->minor != -1 && intf->minor == arg->minor) {
213 		arg->interface = intf;
214 		return 1;
215 	}
216 	return 0;
217 }
218 
219 /**
220  * usb_find_interface - find usb_interface pointer for driver and device
221  * @drv: the driver whose current configuration is considered
222  * @minor: the minor number of the desired device
223  *
224  * This walks the driver device list and returns a pointer to the interface
225  * with the matching minor.  Note, this only works for devices that share the
226  * USB major number.
227  */
228 struct usb_interface *usb_find_interface(struct usb_driver *drv, int minor)
229 {
230 	struct find_interface_arg argb;
231 
232 	argb.minor = minor;
233 	argb.interface = NULL;
234 	driver_for_each_device(&drv->driver, NULL, &argb, __find_interface);
235 	return argb.interface;
236 }
237 
238 #ifdef	CONFIG_HOTPLUG
239 
240 /*
241  * This sends an uevent to userspace, typically helping to load driver
242  * or other modules, configure the device, and more.  Drivers can provide
243  * a MODULE_DEVICE_TABLE to help with module loading subtasks.
244  *
245  * We're called either from khubd (the typical case) or from root hub
246  * (init, kapmd, modprobe, rmmod, etc), but the agents need to handle
247  * delays in event delivery.  Use sysfs (and DEVPATH) to make sure the
248  * device (and this configuration!) are still present.
249  */
250 static int usb_uevent(struct device *dev, char **envp, int num_envp,
251 		      char *buffer, int buffer_size)
252 {
253 	struct usb_interface *intf;
254 	struct usb_device *usb_dev;
255 	struct usb_host_interface *alt;
256 	int i = 0;
257 	int length = 0;
258 
259 	if (!dev)
260 		return -ENODEV;
261 
262 	/* driver is often null here; dev_dbg() would oops */
263 	pr_debug ("usb %s: uevent\n", dev->bus_id);
264 
265 	/* Must check driver_data here, as on remove driver is always NULL */
266 	if ((dev->driver == &usb_generic_driver) ||
267 	    (dev->driver_data == &usb_generic_driver_data))
268 		return 0;
269 
270 	intf = to_usb_interface(dev);
271 	usb_dev = interface_to_usbdev (intf);
272 	alt = intf->cur_altsetting;
273 
274 	if (usb_dev->devnum < 0) {
275 		pr_debug ("usb %s: already deleted?\n", dev->bus_id);
276 		return -ENODEV;
277 	}
278 	if (!usb_dev->bus) {
279 		pr_debug ("usb %s: bus removed?\n", dev->bus_id);
280 		return -ENODEV;
281 	}
282 
283 #ifdef	CONFIG_USB_DEVICEFS
284 	/* If this is available, userspace programs can directly read
285 	 * all the device descriptors we don't tell them about.  Or
286 	 * even act as usermode drivers.
287 	 *
288 	 * FIXME reduce hardwired intelligence here
289 	 */
290 	if (add_uevent_var(envp, num_envp, &i,
291 			   buffer, buffer_size, &length,
292 			   "DEVICE=/proc/bus/usb/%03d/%03d",
293 			   usb_dev->bus->busnum, usb_dev->devnum))
294 		return -ENOMEM;
295 #endif
296 
297 	/* per-device configurations are common */
298 	if (add_uevent_var(envp, num_envp, &i,
299 			   buffer, buffer_size, &length,
300 			   "PRODUCT=%x/%x/%x",
301 			   le16_to_cpu(usb_dev->descriptor.idVendor),
302 			   le16_to_cpu(usb_dev->descriptor.idProduct),
303 			   le16_to_cpu(usb_dev->descriptor.bcdDevice)))
304 		return -ENOMEM;
305 
306 	/* class-based driver binding models */
307 	if (add_uevent_var(envp, num_envp, &i,
308 			   buffer, buffer_size, &length,
309 			   "TYPE=%d/%d/%d",
310 			   usb_dev->descriptor.bDeviceClass,
311 			   usb_dev->descriptor.bDeviceSubClass,
312 			   usb_dev->descriptor.bDeviceProtocol))
313 		return -ENOMEM;
314 
315 	if (add_uevent_var(envp, num_envp, &i,
316 			   buffer, buffer_size, &length,
317 			   "INTERFACE=%d/%d/%d",
318 			   alt->desc.bInterfaceClass,
319 			   alt->desc.bInterfaceSubClass,
320 			   alt->desc.bInterfaceProtocol))
321 		return -ENOMEM;
322 
323 	if (add_uevent_var(envp, num_envp, &i,
324 			   buffer, buffer_size, &length,
325 			   "MODALIAS=usb:v%04Xp%04Xd%04Xdc%02Xdsc%02Xdp%02Xic%02Xisc%02Xip%02X",
326 			   le16_to_cpu(usb_dev->descriptor.idVendor),
327 			   le16_to_cpu(usb_dev->descriptor.idProduct),
328 			   le16_to_cpu(usb_dev->descriptor.bcdDevice),
329 			   usb_dev->descriptor.bDeviceClass,
330 			   usb_dev->descriptor.bDeviceSubClass,
331 			   usb_dev->descriptor.bDeviceProtocol,
332 			   alt->desc.bInterfaceClass,
333 			   alt->desc.bInterfaceSubClass,
334 			   alt->desc.bInterfaceProtocol))
335 		return -ENOMEM;
336 
337 	envp[i] = NULL;
338 
339 	return 0;
340 }
341 
342 #else
343 
344 static int usb_uevent(struct device *dev, char **envp,
345 			int num_envp, char *buffer, int buffer_size)
346 {
347 	return -ENODEV;
348 }
349 
350 #endif	/* CONFIG_HOTPLUG */
351 
352 /**
353  * usb_release_dev - free a usb device structure when all users of it are finished.
354  * @dev: device that's been disconnected
355  *
356  * Will be called only by the device core when all users of this usb device are
357  * done.
358  */
359 static void usb_release_dev(struct device *dev)
360 {
361 	struct usb_device *udev;
362 
363 	udev = to_usb_device(dev);
364 
365 	usb_destroy_configuration(udev);
366 	usb_bus_put(udev->bus);
367 	kfree(udev->product);
368 	kfree(udev->manufacturer);
369 	kfree(udev->serial);
370 	kfree(udev);
371 }
372 
373 /**
374  * usb_alloc_dev - usb device constructor (usbcore-internal)
375  * @parent: hub to which device is connected; null to allocate a root hub
376  * @bus: bus used to access the device
377  * @port1: one-based index of port; ignored for root hubs
378  * Context: !in_interrupt ()
379  *
380  * Only hub drivers (including virtual root hub drivers for host
381  * controllers) should ever call this.
382  *
383  * This call may not be used in a non-sleeping context.
384  */
385 struct usb_device *
386 usb_alloc_dev(struct usb_device *parent, struct usb_bus *bus, unsigned port1)
387 {
388 	struct usb_device *dev;
389 
390 	dev = kzalloc(sizeof(*dev), GFP_KERNEL);
391 	if (!dev)
392 		return NULL;
393 
394 	bus = usb_bus_get(bus);
395 	if (!bus) {
396 		kfree(dev);
397 		return NULL;
398 	}
399 
400 	device_initialize(&dev->dev);
401 	dev->dev.bus = &usb_bus_type;
402 	dev->dev.dma_mask = bus->controller->dma_mask;
403 	dev->dev.driver_data = &usb_generic_driver_data;
404 	dev->dev.driver = &usb_generic_driver;
405 	dev->dev.release = usb_release_dev;
406 	dev->state = USB_STATE_ATTACHED;
407 
408 	INIT_LIST_HEAD(&dev->ep0.urb_list);
409 	dev->ep0.desc.bLength = USB_DT_ENDPOINT_SIZE;
410 	dev->ep0.desc.bDescriptorType = USB_DT_ENDPOINT;
411 	/* ep0 maxpacket comes later, from device descriptor */
412 	dev->ep_in[0] = dev->ep_out[0] = &dev->ep0;
413 
414 	/* Save readable and stable topology id, distinguishing devices
415 	 * by location for diagnostics, tools, driver model, etc.  The
416 	 * string is a path along hub ports, from the root.  Each device's
417 	 * dev->devpath will be stable until USB is re-cabled, and hubs
418 	 * are often labeled with these port numbers.  The bus_id isn't
419 	 * as stable:  bus->busnum changes easily from modprobe order,
420 	 * cardbus or pci hotplugging, and so on.
421 	 */
422 	if (unlikely (!parent)) {
423 		dev->devpath [0] = '0';
424 
425 		dev->dev.parent = bus->controller;
426 		sprintf (&dev->dev.bus_id[0], "usb%d", bus->busnum);
427 	} else {
428 		/* match any labeling on the hubs; it's one-based */
429 		if (parent->devpath [0] == '0')
430 			snprintf (dev->devpath, sizeof dev->devpath,
431 				"%d", port1);
432 		else
433 			snprintf (dev->devpath, sizeof dev->devpath,
434 				"%s.%d", parent->devpath, port1);
435 
436 		dev->dev.parent = &parent->dev;
437 		sprintf (&dev->dev.bus_id[0], "%d-%s",
438 			bus->busnum, dev->devpath);
439 
440 		/* hub driver sets up TT records */
441 	}
442 
443 	dev->portnum = port1;
444 	dev->bus = bus;
445 	dev->parent = parent;
446 	INIT_LIST_HEAD(&dev->filelist);
447 
448 	return dev;
449 }
450 
451 /**
452  * usb_get_dev - increments the reference count of the usb device structure
453  * @dev: the device being referenced
454  *
455  * Each live reference to a device should be refcounted.
456  *
457  * Drivers for USB interfaces should normally record such references in
458  * their probe() methods, when they bind to an interface, and release
459  * them by calling usb_put_dev(), in their disconnect() methods.
460  *
461  * A pointer to the device with the incremented reference counter is returned.
462  */
463 struct usb_device *usb_get_dev(struct usb_device *dev)
464 {
465 	if (dev)
466 		get_device(&dev->dev);
467 	return dev;
468 }
469 
470 /**
471  * usb_put_dev - release a use of the usb device structure
472  * @dev: device that's been disconnected
473  *
474  * Must be called when a user of a device is finished with it.  When the last
475  * user of the device calls this function, the memory of the device is freed.
476  */
477 void usb_put_dev(struct usb_device *dev)
478 {
479 	if (dev)
480 		put_device(&dev->dev);
481 }
482 
483 /**
484  * usb_get_intf - increments the reference count of the usb interface structure
485  * @intf: the interface being referenced
486  *
487  * Each live reference to a interface must be refcounted.
488  *
489  * Drivers for USB interfaces should normally record such references in
490  * their probe() methods, when they bind to an interface, and release
491  * them by calling usb_put_intf(), in their disconnect() methods.
492  *
493  * A pointer to the interface with the incremented reference counter is
494  * returned.
495  */
496 struct usb_interface *usb_get_intf(struct usb_interface *intf)
497 {
498 	if (intf)
499 		get_device(&intf->dev);
500 	return intf;
501 }
502 
503 /**
504  * usb_put_intf - release a use of the usb interface structure
505  * @intf: interface that's been decremented
506  *
507  * Must be called when a user of an interface is finished with it.  When the
508  * last user of the interface calls this function, the memory of the interface
509  * is freed.
510  */
511 void usb_put_intf(struct usb_interface *intf)
512 {
513 	if (intf)
514 		put_device(&intf->dev);
515 }
516 
517 
518 /*			USB device locking
519  *
520  * USB devices and interfaces are locked using the semaphore in their
521  * embedded struct device.  The hub driver guarantees that whenever a
522  * device is connected or disconnected, drivers are called with the
523  * USB device locked as well as their particular interface.
524  *
525  * Complications arise when several devices are to be locked at the same
526  * time.  Only hub-aware drivers that are part of usbcore ever have to
527  * do this; nobody else needs to worry about it.  The rule for locking
528  * is simple:
529  *
530  *	When locking both a device and its parent, always lock the
531  *	the parent first.
532  */
533 
534 /**
535  * usb_lock_device_for_reset - cautiously acquire the lock for a
536  *	usb device structure
537  * @udev: device that's being locked
538  * @iface: interface bound to the driver making the request (optional)
539  *
540  * Attempts to acquire the device lock, but fails if the device is
541  * NOTATTACHED or SUSPENDED, or if iface is specified and the interface
542  * is neither BINDING nor BOUND.  Rather than sleeping to wait for the
543  * lock, the routine polls repeatedly.  This is to prevent deadlock with
544  * disconnect; in some drivers (such as usb-storage) the disconnect()
545  * or suspend() method will block waiting for a device reset to complete.
546  *
547  * Returns a negative error code for failure, otherwise 1 or 0 to indicate
548  * that the device will or will not have to be unlocked.  (0 can be
549  * returned when an interface is given and is BINDING, because in that
550  * case the driver already owns the device lock.)
551  */
552 int usb_lock_device_for_reset(struct usb_device *udev,
553 		struct usb_interface *iface)
554 {
555 	unsigned long jiffies_expire = jiffies + HZ;
556 
557 	if (udev->state == USB_STATE_NOTATTACHED)
558 		return -ENODEV;
559 	if (udev->state == USB_STATE_SUSPENDED)
560 		return -EHOSTUNREACH;
561 	if (iface) {
562 		switch (iface->condition) {
563 		  case USB_INTERFACE_BINDING:
564 			return 0;
565 		  case USB_INTERFACE_BOUND:
566 			break;
567 		  default:
568 			return -EINTR;
569 		}
570 	}
571 
572 	while (usb_trylock_device(udev) != 0) {
573 
574 		/* If we can't acquire the lock after waiting one second,
575 		 * we're probably deadlocked */
576 		if (time_after(jiffies, jiffies_expire))
577 			return -EBUSY;
578 
579 		msleep(15);
580 		if (udev->state == USB_STATE_NOTATTACHED)
581 			return -ENODEV;
582 		if (udev->state == USB_STATE_SUSPENDED)
583 			return -EHOSTUNREACH;
584 		if (iface && iface->condition != USB_INTERFACE_BOUND)
585 			return -EINTR;
586 	}
587 	return 1;
588 }
589 
590 
591 static struct usb_device *match_device(struct usb_device *dev,
592 				       u16 vendor_id, u16 product_id)
593 {
594 	struct usb_device *ret_dev = NULL;
595 	int child;
596 
597 	dev_dbg(&dev->dev, "check for vendor %04x, product %04x ...\n",
598 	    le16_to_cpu(dev->descriptor.idVendor),
599 	    le16_to_cpu(dev->descriptor.idProduct));
600 
601 	/* see if this device matches */
602 	if ((vendor_id == le16_to_cpu(dev->descriptor.idVendor)) &&
603 	    (product_id == le16_to_cpu(dev->descriptor.idProduct))) {
604 		dev_dbg (&dev->dev, "matched this device!\n");
605 		ret_dev = usb_get_dev(dev);
606 		goto exit;
607 	}
608 
609 	/* look through all of the children of this device */
610 	for (child = 0; child < dev->maxchild; ++child) {
611 		if (dev->children[child]) {
612 			usb_lock_device(dev->children[child]);
613 			ret_dev = match_device(dev->children[child],
614 					       vendor_id, product_id);
615 			usb_unlock_device(dev->children[child]);
616 			if (ret_dev)
617 				goto exit;
618 		}
619 	}
620 exit:
621 	return ret_dev;
622 }
623 
624 /**
625  * usb_find_device - find a specific usb device in the system
626  * @vendor_id: the vendor id of the device to find
627  * @product_id: the product id of the device to find
628  *
629  * Returns a pointer to a struct usb_device if such a specified usb
630  * device is present in the system currently.  The usage count of the
631  * device will be incremented if a device is found.  Make sure to call
632  * usb_put_dev() when the caller is finished with the device.
633  *
634  * If a device with the specified vendor and product id is not found,
635  * NULL is returned.
636  */
637 struct usb_device *usb_find_device(u16 vendor_id, u16 product_id)
638 {
639 	struct list_head *buslist;
640 	struct usb_bus *bus;
641 	struct usb_device *dev = NULL;
642 
643 	mutex_lock(&usb_bus_list_lock);
644 	for (buslist = usb_bus_list.next;
645 	     buslist != &usb_bus_list;
646 	     buslist = buslist->next) {
647 		bus = container_of(buslist, struct usb_bus, bus_list);
648 		if (!bus->root_hub)
649 			continue;
650 		usb_lock_device(bus->root_hub);
651 		dev = match_device(bus->root_hub, vendor_id, product_id);
652 		usb_unlock_device(bus->root_hub);
653 		if (dev)
654 			goto exit;
655 	}
656 exit:
657 	mutex_unlock(&usb_bus_list_lock);
658 	return dev;
659 }
660 
661 /**
662  * usb_get_current_frame_number - return current bus frame number
663  * @dev: the device whose bus is being queried
664  *
665  * Returns the current frame number for the USB host controller
666  * used with the given USB device.  This can be used when scheduling
667  * isochronous requests.
668  *
669  * Note that different kinds of host controller have different
670  * "scheduling horizons".  While one type might support scheduling only
671  * 32 frames into the future, others could support scheduling up to
672  * 1024 frames into the future.
673  */
674 int usb_get_current_frame_number(struct usb_device *dev)
675 {
676 	return dev->bus->op->get_frame_number (dev);
677 }
678 
679 /*-------------------------------------------------------------------*/
680 /*
681  * __usb_get_extra_descriptor() finds a descriptor of specific type in the
682  * extra field of the interface and endpoint descriptor structs.
683  */
684 
685 int __usb_get_extra_descriptor(char *buffer, unsigned size,
686 	unsigned char type, void **ptr)
687 {
688 	struct usb_descriptor_header *header;
689 
690 	while (size >= sizeof(struct usb_descriptor_header)) {
691 		header = (struct usb_descriptor_header *)buffer;
692 
693 		if (header->bLength < 2) {
694 			printk(KERN_ERR
695 				"%s: bogus descriptor, type %d length %d\n",
696 				usbcore_name,
697 				header->bDescriptorType,
698 				header->bLength);
699 			return -1;
700 		}
701 
702 		if (header->bDescriptorType == type) {
703 			*ptr = header;
704 			return 0;
705 		}
706 
707 		buffer += header->bLength;
708 		size -= header->bLength;
709 	}
710 	return -1;
711 }
712 
713 /**
714  * usb_buffer_alloc - allocate dma-consistent buffer for URB_NO_xxx_DMA_MAP
715  * @dev: device the buffer will be used with
716  * @size: requested buffer size
717  * @mem_flags: affect whether allocation may block
718  * @dma: used to return DMA address of buffer
719  *
720  * Return value is either null (indicating no buffer could be allocated), or
721  * the cpu-space pointer to a buffer that may be used to perform DMA to the
722  * specified device.  Such cpu-space buffers are returned along with the DMA
723  * address (through the pointer provided).
724  *
725  * These buffers are used with URB_NO_xxx_DMA_MAP set in urb->transfer_flags
726  * to avoid behaviors like using "DMA bounce buffers", or tying down I/O
727  * mapping hardware for long idle periods.  The implementation varies between
728  * platforms, depending on details of how DMA will work to this device.
729  * Using these buffers also helps prevent cacheline sharing problems on
730  * architectures where CPU caches are not DMA-coherent.
731  *
732  * When the buffer is no longer used, free it with usb_buffer_free().
733  */
734 void *usb_buffer_alloc (
735 	struct usb_device *dev,
736 	size_t size,
737 	gfp_t mem_flags,
738 	dma_addr_t *dma
739 )
740 {
741 	if (!dev || !dev->bus || !dev->bus->op || !dev->bus->op->buffer_alloc)
742 		return NULL;
743 	return dev->bus->op->buffer_alloc (dev->bus, size, mem_flags, dma);
744 }
745 
746 /**
747  * usb_buffer_free - free memory allocated with usb_buffer_alloc()
748  * @dev: device the buffer was used with
749  * @size: requested buffer size
750  * @addr: CPU address of buffer
751  * @dma: DMA address of buffer
752  *
753  * This reclaims an I/O buffer, letting it be reused.  The memory must have
754  * been allocated using usb_buffer_alloc(), and the parameters must match
755  * those provided in that allocation request.
756  */
757 void usb_buffer_free (
758 	struct usb_device *dev,
759 	size_t size,
760 	void *addr,
761 	dma_addr_t dma
762 )
763 {
764 	if (!dev || !dev->bus || !dev->bus->op || !dev->bus->op->buffer_free)
765 	    	return;
766 	dev->bus->op->buffer_free (dev->bus, size, addr, dma);
767 }
768 
769 /**
770  * usb_buffer_map - create DMA mapping(s) for an urb
771  * @urb: urb whose transfer_buffer/setup_packet will be mapped
772  *
773  * Return value is either null (indicating no buffer could be mapped), or
774  * the parameter.  URB_NO_TRANSFER_DMA_MAP and URB_NO_SETUP_DMA_MAP are
775  * added to urb->transfer_flags if the operation succeeds.  If the device
776  * is connected to this system through a non-DMA controller, this operation
777  * always succeeds.
778  *
779  * This call would normally be used for an urb which is reused, perhaps
780  * as the target of a large periodic transfer, with usb_buffer_dmasync()
781  * calls to synchronize memory and dma state.
782  *
783  * Reverse the effect of this call with usb_buffer_unmap().
784  */
785 #if 0
786 struct urb *usb_buffer_map (struct urb *urb)
787 {
788 	struct usb_bus		*bus;
789 	struct device		*controller;
790 
791 	if (!urb
792 			|| !urb->dev
793 			|| !(bus = urb->dev->bus)
794 			|| !(controller = bus->controller))
795 		return NULL;
796 
797 	if (controller->dma_mask) {
798 		urb->transfer_dma = dma_map_single (controller,
799 			urb->transfer_buffer, urb->transfer_buffer_length,
800 			usb_pipein (urb->pipe)
801 				? DMA_FROM_DEVICE : DMA_TO_DEVICE);
802 		if (usb_pipecontrol (urb->pipe))
803 			urb->setup_dma = dma_map_single (controller,
804 					urb->setup_packet,
805 					sizeof (struct usb_ctrlrequest),
806 					DMA_TO_DEVICE);
807 	// FIXME generic api broken like pci, can't report errors
808 	// if (urb->transfer_dma == DMA_ADDR_INVALID) return 0;
809 	} else
810 		urb->transfer_dma = ~0;
811 	urb->transfer_flags |= (URB_NO_TRANSFER_DMA_MAP
812 				| URB_NO_SETUP_DMA_MAP);
813 	return urb;
814 }
815 #endif  /*  0  */
816 
817 /* XXX DISABLED, no users currently.  If you wish to re-enable this
818  * XXX please determine whether the sync is to transfer ownership of
819  * XXX the buffer from device to cpu or vice verse, and thusly use the
820  * XXX appropriate _for_{cpu,device}() method.  -DaveM
821  */
822 #if 0
823 
824 /**
825  * usb_buffer_dmasync - synchronize DMA and CPU view of buffer(s)
826  * @urb: urb whose transfer_buffer/setup_packet will be synchronized
827  */
828 void usb_buffer_dmasync (struct urb *urb)
829 {
830 	struct usb_bus		*bus;
831 	struct device		*controller;
832 
833 	if (!urb
834 			|| !(urb->transfer_flags & URB_NO_TRANSFER_DMA_MAP)
835 			|| !urb->dev
836 			|| !(bus = urb->dev->bus)
837 			|| !(controller = bus->controller))
838 		return;
839 
840 	if (controller->dma_mask) {
841 		dma_sync_single (controller,
842 			urb->transfer_dma, urb->transfer_buffer_length,
843 			usb_pipein (urb->pipe)
844 				? DMA_FROM_DEVICE : DMA_TO_DEVICE);
845 		if (usb_pipecontrol (urb->pipe))
846 			dma_sync_single (controller,
847 					urb->setup_dma,
848 					sizeof (struct usb_ctrlrequest),
849 					DMA_TO_DEVICE);
850 	}
851 }
852 #endif
853 
854 /**
855  * usb_buffer_unmap - free DMA mapping(s) for an urb
856  * @urb: urb whose transfer_buffer will be unmapped
857  *
858  * Reverses the effect of usb_buffer_map().
859  */
860 #if 0
861 void usb_buffer_unmap (struct urb *urb)
862 {
863 	struct usb_bus		*bus;
864 	struct device		*controller;
865 
866 	if (!urb
867 			|| !(urb->transfer_flags & URB_NO_TRANSFER_DMA_MAP)
868 			|| !urb->dev
869 			|| !(bus = urb->dev->bus)
870 			|| !(controller = bus->controller))
871 		return;
872 
873 	if (controller->dma_mask) {
874 		dma_unmap_single (controller,
875 			urb->transfer_dma, urb->transfer_buffer_length,
876 			usb_pipein (urb->pipe)
877 				? DMA_FROM_DEVICE : DMA_TO_DEVICE);
878 		if (usb_pipecontrol (urb->pipe))
879 			dma_unmap_single (controller,
880 					urb->setup_dma,
881 					sizeof (struct usb_ctrlrequest),
882 					DMA_TO_DEVICE);
883 	}
884 	urb->transfer_flags &= ~(URB_NO_TRANSFER_DMA_MAP
885 				| URB_NO_SETUP_DMA_MAP);
886 }
887 #endif  /*  0  */
888 
889 /**
890  * usb_buffer_map_sg - create scatterlist DMA mapping(s) for an endpoint
891  * @dev: device to which the scatterlist will be mapped
892  * @pipe: endpoint defining the mapping direction
893  * @sg: the scatterlist to map
894  * @nents: the number of entries in the scatterlist
895  *
896  * Return value is either < 0 (indicating no buffers could be mapped), or
897  * the number of DMA mapping array entries in the scatterlist.
898  *
899  * The caller is responsible for placing the resulting DMA addresses from
900  * the scatterlist into URB transfer buffer pointers, and for setting the
901  * URB_NO_TRANSFER_DMA_MAP transfer flag in each of those URBs.
902  *
903  * Top I/O rates come from queuing URBs, instead of waiting for each one
904  * to complete before starting the next I/O.   This is particularly easy
905  * to do with scatterlists.  Just allocate and submit one URB for each DMA
906  * mapping entry returned, stopping on the first error or when all succeed.
907  * Better yet, use the usb_sg_*() calls, which do that (and more) for you.
908  *
909  * This call would normally be used when translating scatterlist requests,
910  * rather than usb_buffer_map(), since on some hardware (with IOMMUs) it
911  * may be able to coalesce mappings for improved I/O efficiency.
912  *
913  * Reverse the effect of this call with usb_buffer_unmap_sg().
914  */
915 int usb_buffer_map_sg (struct usb_device *dev, unsigned pipe,
916 		struct scatterlist *sg, int nents)
917 {
918 	struct usb_bus		*bus;
919 	struct device		*controller;
920 
921 	if (!dev
922 			|| usb_pipecontrol (pipe)
923 			|| !(bus = dev->bus)
924 			|| !(controller = bus->controller)
925 			|| !controller->dma_mask)
926 		return -1;
927 
928 	// FIXME generic api broken like pci, can't report errors
929 	return dma_map_sg (controller, sg, nents,
930 			usb_pipein (pipe) ? DMA_FROM_DEVICE : DMA_TO_DEVICE);
931 }
932 
933 /* XXX DISABLED, no users currently.  If you wish to re-enable this
934  * XXX please determine whether the sync is to transfer ownership of
935  * XXX the buffer from device to cpu or vice verse, and thusly use the
936  * XXX appropriate _for_{cpu,device}() method.  -DaveM
937  */
938 #if 0
939 
940 /**
941  * usb_buffer_dmasync_sg - synchronize DMA and CPU view of scatterlist buffer(s)
942  * @dev: device to which the scatterlist will be mapped
943  * @pipe: endpoint defining the mapping direction
944  * @sg: the scatterlist to synchronize
945  * @n_hw_ents: the positive return value from usb_buffer_map_sg
946  *
947  * Use this when you are re-using a scatterlist's data buffers for
948  * another USB request.
949  */
950 void usb_buffer_dmasync_sg (struct usb_device *dev, unsigned pipe,
951 		struct scatterlist *sg, int n_hw_ents)
952 {
953 	struct usb_bus		*bus;
954 	struct device		*controller;
955 
956 	if (!dev
957 			|| !(bus = dev->bus)
958 			|| !(controller = bus->controller)
959 			|| !controller->dma_mask)
960 		return;
961 
962 	dma_sync_sg (controller, sg, n_hw_ents,
963 			usb_pipein (pipe) ? DMA_FROM_DEVICE : DMA_TO_DEVICE);
964 }
965 #endif
966 
967 /**
968  * usb_buffer_unmap_sg - free DMA mapping(s) for a scatterlist
969  * @dev: device to which the scatterlist will be mapped
970  * @pipe: endpoint defining the mapping direction
971  * @sg: the scatterlist to unmap
972  * @n_hw_ents: the positive return value from usb_buffer_map_sg
973  *
974  * Reverses the effect of usb_buffer_map_sg().
975  */
976 void usb_buffer_unmap_sg (struct usb_device *dev, unsigned pipe,
977 		struct scatterlist *sg, int n_hw_ents)
978 {
979 	struct usb_bus		*bus;
980 	struct device		*controller;
981 
982 	if (!dev
983 			|| !(bus = dev->bus)
984 			|| !(controller = bus->controller)
985 			|| !controller->dma_mask)
986 		return;
987 
988 	dma_unmap_sg (controller, sg, n_hw_ents,
989 			usb_pipein (pipe) ? DMA_FROM_DEVICE : DMA_TO_DEVICE);
990 }
991 
992 static int verify_suspended(struct device *dev, void *unused)
993 {
994 	return (dev->power.power_state.event == PM_EVENT_ON) ? -EBUSY : 0;
995 }
996 
997 static int usb_generic_suspend(struct device *dev, pm_message_t message)
998 {
999 	struct usb_interface	*intf;
1000 	struct usb_driver	*driver;
1001 	int			status;
1002 
1003 	/* USB devices enter SUSPEND state through their hubs, but can be
1004 	 * marked for FREEZE as soon as their children are already idled.
1005 	 * But those semantics are useless, so we equate the two (sigh).
1006 	 */
1007 	if (dev->driver == &usb_generic_driver) {
1008 		if (dev->power.power_state.event == message.event)
1009 			return 0;
1010 		/* we need to rule out bogus requests through sysfs */
1011 		status = device_for_each_child(dev, NULL, verify_suspended);
1012 		if (status)
1013 			return status;
1014  		return usb_suspend_device (to_usb_device(dev));
1015 	}
1016 
1017 	if ((dev->driver == NULL) ||
1018 	    (dev->driver_data == &usb_generic_driver_data))
1019 		return 0;
1020 
1021 	intf = to_usb_interface(dev);
1022 	driver = to_usb_driver(dev->driver);
1023 
1024 	/* with no hardware, USB interfaces only use FREEZE and ON states */
1025 	if (!is_active(intf))
1026 		return 0;
1027 
1028 	if (driver->suspend && driver->resume) {
1029 		status = driver->suspend(intf, message);
1030 		if (status)
1031 			dev_err(dev, "%s error %d\n", "suspend", status);
1032 		else
1033 			mark_quiesced(intf);
1034 	} else {
1035 		// FIXME else if there's no suspend method, disconnect...
1036 		dev_warn(dev, "no suspend for driver %s?\n", driver->name);
1037 		mark_quiesced(intf);
1038 		status = 0;
1039 	}
1040 	return status;
1041 }
1042 
1043 static int usb_generic_resume(struct device *dev)
1044 {
1045 	struct usb_interface	*intf;
1046 	struct usb_driver	*driver;
1047 	struct usb_device	*udev;
1048 	int			status;
1049 
1050 	if (dev->power.power_state.event == PM_EVENT_ON)
1051 		return 0;
1052 
1053 	/* mark things as "on" immediately, no matter what errors crop up */
1054 	dev->power.power_state.event = PM_EVENT_ON;
1055 
1056 	/* devices resume through their hubs */
1057 	if (dev->driver == &usb_generic_driver) {
1058 		udev = to_usb_device(dev);
1059 		if (udev->state == USB_STATE_NOTATTACHED)
1060 			return 0;
1061 		return usb_resume_device (to_usb_device(dev));
1062 	}
1063 
1064 	if ((dev->driver == NULL) ||
1065 	    (dev->driver_data == &usb_generic_driver_data)) {
1066 		dev->power.power_state.event = PM_EVENT_FREEZE;
1067 		return 0;
1068 	}
1069 
1070 	intf = to_usb_interface(dev);
1071 	driver = to_usb_driver(dev->driver);
1072 
1073 	udev = interface_to_usbdev(intf);
1074 	if (udev->state == USB_STATE_NOTATTACHED)
1075 		return 0;
1076 
1077 	/* if driver was suspended, it has a resume method;
1078 	 * however, sysfs can wrongly mark things as suspended
1079 	 * (on the "no suspend method" FIXME path above)
1080 	 */
1081 	if (driver->resume) {
1082 		status = driver->resume(intf);
1083 		if (status) {
1084 			dev_err(dev, "%s error %d\n", "resume", status);
1085 			mark_quiesced(intf);
1086 		}
1087 	} else
1088 		dev_warn(dev, "no resume for driver %s?\n", driver->name);
1089 	return 0;
1090 }
1091 
1092 struct bus_type usb_bus_type = {
1093 	.name =		"usb",
1094 	.match =	usb_device_match,
1095 	.uevent =	usb_uevent,
1096 	.suspend =	usb_generic_suspend,
1097 	.resume =	usb_generic_resume,
1098 };
1099 
1100 /* format to disable USB on kernel command line is: nousb */
1101 __module_param_call("", nousb, param_set_bool, param_get_bool, &nousb, 0444);
1102 
1103 /*
1104  * for external read access to <nousb>
1105  */
1106 int usb_disabled(void)
1107 {
1108 	return nousb;
1109 }
1110 
1111 /*
1112  * Init
1113  */
1114 static int __init usb_init(void)
1115 {
1116 	int retval;
1117 	if (nousb) {
1118 		pr_info ("%s: USB support disabled\n", usbcore_name);
1119 		return 0;
1120 	}
1121 
1122 	retval = bus_register(&usb_bus_type);
1123 	if (retval)
1124 		goto out;
1125 	retval = usb_host_init();
1126 	if (retval)
1127 		goto host_init_failed;
1128 	retval = usb_major_init();
1129 	if (retval)
1130 		goto major_init_failed;
1131 	retval = usb_register(&usbfs_driver);
1132 	if (retval)
1133 		goto driver_register_failed;
1134 	retval = usbdev_init();
1135 	if (retval)
1136 		goto usbdevice_init_failed;
1137 	retval = usbfs_init();
1138 	if (retval)
1139 		goto fs_init_failed;
1140 	retval = usb_hub_init();
1141 	if (retval)
1142 		goto hub_init_failed;
1143 	retval = driver_register(&usb_generic_driver);
1144 	if (!retval)
1145 		goto out;
1146 
1147 	usb_hub_cleanup();
1148 hub_init_failed:
1149 	usbfs_cleanup();
1150 fs_init_failed:
1151 	usbdev_cleanup();
1152 usbdevice_init_failed:
1153 	usb_deregister(&usbfs_driver);
1154 driver_register_failed:
1155 	usb_major_cleanup();
1156 major_init_failed:
1157 	usb_host_cleanup();
1158 host_init_failed:
1159 	bus_unregister(&usb_bus_type);
1160 out:
1161 	return retval;
1162 }
1163 
1164 /*
1165  * Cleanup
1166  */
1167 static void __exit usb_exit(void)
1168 {
1169 	/* This will matter if shutdown/reboot does exitcalls. */
1170 	if (nousb)
1171 		return;
1172 
1173 	driver_unregister(&usb_generic_driver);
1174 	usb_major_cleanup();
1175 	usbfs_cleanup();
1176 	usb_deregister(&usbfs_driver);
1177 	usbdev_cleanup();
1178 	usb_hub_cleanup();
1179 	usb_host_cleanup();
1180 	bus_unregister(&usb_bus_type);
1181 }
1182 
1183 subsys_initcall(usb_init);
1184 module_exit(usb_exit);
1185 
1186 /*
1187  * USB may be built into the kernel or be built as modules.
1188  * These symbols are exported for device (or host controller)
1189  * driver modules to use.
1190  */
1191 
1192 EXPORT_SYMBOL(usb_disabled);
1193 
1194 EXPORT_SYMBOL_GPL(usb_get_intf);
1195 EXPORT_SYMBOL_GPL(usb_put_intf);
1196 
1197 EXPORT_SYMBOL(usb_put_dev);
1198 EXPORT_SYMBOL(usb_get_dev);
1199 EXPORT_SYMBOL(usb_hub_tt_clear_buffer);
1200 
1201 EXPORT_SYMBOL(usb_lock_device_for_reset);
1202 
1203 EXPORT_SYMBOL(usb_driver_claim_interface);
1204 EXPORT_SYMBOL(usb_driver_release_interface);
1205 EXPORT_SYMBOL(usb_find_interface);
1206 EXPORT_SYMBOL(usb_ifnum_to_if);
1207 EXPORT_SYMBOL(usb_altnum_to_altsetting);
1208 
1209 EXPORT_SYMBOL(usb_reset_device);
1210 EXPORT_SYMBOL(usb_reset_composite_device);
1211 
1212 EXPORT_SYMBOL(__usb_get_extra_descriptor);
1213 
1214 EXPORT_SYMBOL(usb_find_device);
1215 EXPORT_SYMBOL(usb_get_current_frame_number);
1216 
1217 EXPORT_SYMBOL (usb_buffer_alloc);
1218 EXPORT_SYMBOL (usb_buffer_free);
1219 
1220 #if 0
1221 EXPORT_SYMBOL (usb_buffer_map);
1222 EXPORT_SYMBOL (usb_buffer_dmasync);
1223 EXPORT_SYMBOL (usb_buffer_unmap);
1224 #endif
1225 
1226 EXPORT_SYMBOL (usb_buffer_map_sg);
1227 #if 0
1228 EXPORT_SYMBOL (usb_buffer_dmasync_sg);
1229 #endif
1230 EXPORT_SYMBOL (usb_buffer_unmap_sg);
1231 
1232 MODULE_LICENSE("GPL");
1233