1 /*
2  * drivers/usb/driver.c - most of the driver model stuff for usb
3  *
4  * (C) Copyright 2005 Greg Kroah-Hartman <gregkh@suse.de>
5  *
6  * based on drivers/usb/usb.c which had the following copyrights:
7  *	(C) Copyright Linus Torvalds 1999
8  *	(C) Copyright Johannes Erdfelt 1999-2001
9  *	(C) Copyright Andreas Gal 1999
10  *	(C) Copyright Gregory P. Smith 1999
11  *	(C) Copyright Deti Fliegl 1999 (new USB architecture)
12  *	(C) Copyright Randy Dunlap 2000
13  *	(C) Copyright David Brownell 2000-2004
14  *	(C) Copyright Yggdrasil Computing, Inc. 2000
15  *		(usb_device_id matching changes by Adam J. Richter)
16  *	(C) Copyright Greg Kroah-Hartman 2002-2003
17  *
18  * NOTE! This is not actually a driver at all, rather this is
19  * just a collection of helper routines that implement the
20  * matching, probing, releasing, suspending and resuming for
21  * real drivers.
22  *
23  */
24 
25 #include <linux/device.h>
26 #include <linux/slab.h>
27 #include <linux/export.h>
28 #include <linux/usb.h>
29 #include <linux/usb/quirks.h>
30 #include <linux/usb/hcd.h>
31 
32 #include "usb.h"
33 
34 
35 #ifdef CONFIG_HOTPLUG
36 
37 /*
38  * Adds a new dynamic USBdevice ID to this driver,
39  * and cause the driver to probe for all devices again.
40  */
usb_store_new_id(struct usb_dynids * dynids,struct device_driver * driver,const char * buf,size_t count)41 ssize_t usb_store_new_id(struct usb_dynids *dynids,
42 			 struct device_driver *driver,
43 			 const char *buf, size_t count)
44 {
45 	struct usb_dynid *dynid;
46 	u32 idVendor = 0;
47 	u32 idProduct = 0;
48 	unsigned int bInterfaceClass = 0;
49 	int fields = 0;
50 	int retval = 0;
51 
52 	fields = sscanf(buf, "%x %x %x", &idVendor, &idProduct,
53 					&bInterfaceClass);
54 	if (fields < 2)
55 		return -EINVAL;
56 
57 	dynid = kzalloc(sizeof(*dynid), GFP_KERNEL);
58 	if (!dynid)
59 		return -ENOMEM;
60 
61 	INIT_LIST_HEAD(&dynid->node);
62 	dynid->id.idVendor = idVendor;
63 	dynid->id.idProduct = idProduct;
64 	dynid->id.match_flags = USB_DEVICE_ID_MATCH_DEVICE;
65 	if (fields == 3) {
66 		dynid->id.bInterfaceClass = (u8)bInterfaceClass;
67 		dynid->id.match_flags |= USB_DEVICE_ID_MATCH_INT_CLASS;
68 	}
69 
70 	spin_lock(&dynids->lock);
71 	list_add_tail(&dynid->node, &dynids->list);
72 	spin_unlock(&dynids->lock);
73 
74 	retval = driver_attach(driver);
75 
76 	if (retval)
77 		return retval;
78 	return count;
79 }
80 EXPORT_SYMBOL_GPL(usb_store_new_id);
81 
store_new_id(struct device_driver * driver,const char * buf,size_t count)82 static ssize_t store_new_id(struct device_driver *driver,
83 			    const char *buf, size_t count)
84 {
85 	struct usb_driver *usb_drv = to_usb_driver(driver);
86 
87 	return usb_store_new_id(&usb_drv->dynids, driver, buf, count);
88 }
89 static DRIVER_ATTR(new_id, S_IWUSR, NULL, store_new_id);
90 
91 /**
92  * store_remove_id - remove a USB device ID from this driver
93  * @driver: target device driver
94  * @buf: buffer for scanning device ID data
95  * @count: input size
96  *
97  * Removes a dynamic usb device ID from this driver.
98  */
99 static ssize_t
store_remove_id(struct device_driver * driver,const char * buf,size_t count)100 store_remove_id(struct device_driver *driver, const char *buf, size_t count)
101 {
102 	struct usb_dynid *dynid, *n;
103 	struct usb_driver *usb_driver = to_usb_driver(driver);
104 	u32 idVendor = 0;
105 	u32 idProduct = 0;
106 	int fields = 0;
107 	int retval = 0;
108 
109 	fields = sscanf(buf, "%x %x", &idVendor, &idProduct);
110 	if (fields < 2)
111 		return -EINVAL;
112 
113 	spin_lock(&usb_driver->dynids.lock);
114 	list_for_each_entry_safe(dynid, n, &usb_driver->dynids.list, node) {
115 		struct usb_device_id *id = &dynid->id;
116 		if ((id->idVendor == idVendor) &&
117 		    (id->idProduct == idProduct)) {
118 			list_del(&dynid->node);
119 			kfree(dynid);
120 			retval = 0;
121 			break;
122 		}
123 	}
124 	spin_unlock(&usb_driver->dynids.lock);
125 
126 	if (retval)
127 		return retval;
128 	return count;
129 }
130 static DRIVER_ATTR(remove_id, S_IWUSR, NULL, store_remove_id);
131 
usb_create_newid_files(struct usb_driver * usb_drv)132 static int usb_create_newid_files(struct usb_driver *usb_drv)
133 {
134 	int error = 0;
135 
136 	if (usb_drv->no_dynamic_id)
137 		goto exit;
138 
139 	if (usb_drv->probe != NULL) {
140 		error = driver_create_file(&usb_drv->drvwrap.driver,
141 					   &driver_attr_new_id);
142 		if (error == 0) {
143 			error = driver_create_file(&usb_drv->drvwrap.driver,
144 					&driver_attr_remove_id);
145 			if (error)
146 				driver_remove_file(&usb_drv->drvwrap.driver,
147 						&driver_attr_new_id);
148 		}
149 	}
150 exit:
151 	return error;
152 }
153 
usb_remove_newid_files(struct usb_driver * usb_drv)154 static void usb_remove_newid_files(struct usb_driver *usb_drv)
155 {
156 	if (usb_drv->no_dynamic_id)
157 		return;
158 
159 	if (usb_drv->probe != NULL) {
160 		driver_remove_file(&usb_drv->drvwrap.driver,
161 				&driver_attr_remove_id);
162 		driver_remove_file(&usb_drv->drvwrap.driver,
163 				   &driver_attr_new_id);
164 	}
165 }
166 
usb_free_dynids(struct usb_driver * usb_drv)167 static void usb_free_dynids(struct usb_driver *usb_drv)
168 {
169 	struct usb_dynid *dynid, *n;
170 
171 	spin_lock(&usb_drv->dynids.lock);
172 	list_for_each_entry_safe(dynid, n, &usb_drv->dynids.list, node) {
173 		list_del(&dynid->node);
174 		kfree(dynid);
175 	}
176 	spin_unlock(&usb_drv->dynids.lock);
177 }
178 #else
usb_create_newid_files(struct usb_driver * usb_drv)179 static inline int usb_create_newid_files(struct usb_driver *usb_drv)
180 {
181 	return 0;
182 }
183 
usb_remove_newid_files(struct usb_driver * usb_drv)184 static void usb_remove_newid_files(struct usb_driver *usb_drv)
185 {
186 }
187 
usb_free_dynids(struct usb_driver * usb_drv)188 static inline void usb_free_dynids(struct usb_driver *usb_drv)
189 {
190 }
191 #endif
192 
usb_match_dynamic_id(struct usb_interface * intf,struct usb_driver * drv)193 static const struct usb_device_id *usb_match_dynamic_id(struct usb_interface *intf,
194 							struct usb_driver *drv)
195 {
196 	struct usb_dynid *dynid;
197 
198 	spin_lock(&drv->dynids.lock);
199 	list_for_each_entry(dynid, &drv->dynids.list, node) {
200 		if (usb_match_one_id(intf, &dynid->id)) {
201 			spin_unlock(&drv->dynids.lock);
202 			return &dynid->id;
203 		}
204 	}
205 	spin_unlock(&drv->dynids.lock);
206 	return NULL;
207 }
208 
209 
210 /* called from driver core with dev locked */
usb_probe_device(struct device * dev)211 static int usb_probe_device(struct device *dev)
212 {
213 	struct usb_device_driver *udriver = to_usb_device_driver(dev->driver);
214 	struct usb_device *udev = to_usb_device(dev);
215 	int error = 0;
216 
217 	dev_dbg(dev, "%s\n", __func__);
218 
219 	/* TODO: Add real matching code */
220 
221 	/* The device should always appear to be in use
222 	 * unless the driver suports autosuspend.
223 	 */
224 	if (!udriver->supports_autosuspend)
225 		error = usb_autoresume_device(udev);
226 
227 	if (!error)
228 		error = udriver->probe(udev);
229 	return error;
230 }
231 
232 /* called from driver core with dev locked */
usb_unbind_device(struct device * dev)233 static int usb_unbind_device(struct device *dev)
234 {
235 	struct usb_device *udev = to_usb_device(dev);
236 	struct usb_device_driver *udriver = to_usb_device_driver(dev->driver);
237 
238 	udriver->disconnect(udev);
239 	if (!udriver->supports_autosuspend)
240 		usb_autosuspend_device(udev);
241 	return 0;
242 }
243 
244 /*
245  * Cancel any pending scheduled resets
246  *
247  * [see usb_queue_reset_device()]
248  *
249  * Called after unconfiguring / when releasing interfaces. See
250  * comments in __usb_queue_reset_device() regarding
251  * udev->reset_running.
252  */
usb_cancel_queued_reset(struct usb_interface * iface)253 static void usb_cancel_queued_reset(struct usb_interface *iface)
254 {
255 	if (iface->reset_running == 0)
256 		cancel_work_sync(&iface->reset_ws);
257 }
258 
259 /* called from driver core with dev locked */
usb_probe_interface(struct device * dev)260 static int usb_probe_interface(struct device *dev)
261 {
262 	struct usb_driver *driver = to_usb_driver(dev->driver);
263 	struct usb_interface *intf = to_usb_interface(dev);
264 	struct usb_device *udev = interface_to_usbdev(intf);
265 	const struct usb_device_id *id;
266 	int error = -ENODEV;
267 
268 	dev_dbg(dev, "%s\n", __func__);
269 
270 	intf->needs_binding = 0;
271 
272 	if (usb_device_is_owned(udev))
273 		return error;
274 
275 	if (udev->authorized == 0) {
276 		dev_err(&intf->dev, "Device is not authorized for usage\n");
277 		return error;
278 	}
279 
280 	id = usb_match_id(intf, driver->id_table);
281 	if (!id)
282 		id = usb_match_dynamic_id(intf, driver);
283 	if (!id)
284 		return error;
285 
286 	dev_dbg(dev, "%s - got id\n", __func__);
287 
288 	error = usb_autoresume_device(udev);
289 	if (error)
290 		return error;
291 
292 	intf->condition = USB_INTERFACE_BINDING;
293 
294 	/* Probed interfaces are initially active.  They are
295 	 * runtime-PM-enabled only if the driver has autosuspend support.
296 	 * They are sensitive to their children's power states.
297 	 */
298 	pm_runtime_set_active(dev);
299 	pm_suspend_ignore_children(dev, false);
300 	if (driver->supports_autosuspend)
301 		pm_runtime_enable(dev);
302 
303 	/* Carry out a deferred switch to altsetting 0 */
304 	if (intf->needs_altsetting0) {
305 		error = usb_set_interface(udev, intf->altsetting[0].
306 				desc.bInterfaceNumber, 0);
307 		if (error < 0)
308 			goto err;
309 		intf->needs_altsetting0 = 0;
310 	}
311 
312 	error = driver->probe(intf, id);
313 	if (error)
314 		goto err;
315 
316 	intf->condition = USB_INTERFACE_BOUND;
317 	usb_autosuspend_device(udev);
318 	return error;
319 
320  err:
321 	intf->needs_remote_wakeup = 0;
322 	intf->condition = USB_INTERFACE_UNBOUND;
323 	usb_cancel_queued_reset(intf);
324 
325 	/* Unbound interfaces are always runtime-PM-disabled and -suspended */
326 	if (driver->supports_autosuspend)
327 		pm_runtime_disable(dev);
328 	pm_runtime_set_suspended(dev);
329 
330 	usb_autosuspend_device(udev);
331 	return error;
332 }
333 
334 /* called from driver core with dev locked */
usb_unbind_interface(struct device * dev)335 static int usb_unbind_interface(struct device *dev)
336 {
337 	struct usb_driver *driver = to_usb_driver(dev->driver);
338 	struct usb_interface *intf = to_usb_interface(dev);
339 	struct usb_device *udev;
340 	int error, r;
341 
342 	intf->condition = USB_INTERFACE_UNBINDING;
343 
344 	/* Autoresume for set_interface call below */
345 	udev = interface_to_usbdev(intf);
346 	error = usb_autoresume_device(udev);
347 
348 	/* Terminate all URBs for this interface unless the driver
349 	 * supports "soft" unbinding.
350 	 */
351 	if (!driver->soft_unbind)
352 		usb_disable_interface(udev, intf, false);
353 
354 	driver->disconnect(intf);
355 	usb_cancel_queued_reset(intf);
356 
357 	/* Reset other interface state.
358 	 * We cannot do a Set-Interface if the device is suspended or
359 	 * if it is prepared for a system sleep (since installing a new
360 	 * altsetting means creating new endpoint device entries).
361 	 * When either of these happens, defer the Set-Interface.
362 	 */
363 	if (intf->cur_altsetting->desc.bAlternateSetting == 0) {
364 		/* Already in altsetting 0 so skip Set-Interface.
365 		 * Just re-enable it without affecting the endpoint toggles.
366 		 */
367 		usb_enable_interface(udev, intf, false);
368 	} else if (!error && !intf->dev.power.is_prepared) {
369 		r = usb_set_interface(udev, intf->altsetting[0].
370 				desc.bInterfaceNumber, 0);
371 		if (r < 0)
372 			intf->needs_altsetting0 = 1;
373 	} else {
374 		intf->needs_altsetting0 = 1;
375 	}
376 	usb_set_intfdata(intf, NULL);
377 
378 	intf->condition = USB_INTERFACE_UNBOUND;
379 	intf->needs_remote_wakeup = 0;
380 
381 	/* Unbound interfaces are always runtime-PM-disabled and -suspended */
382 	if (driver->supports_autosuspend)
383 		pm_runtime_disable(dev);
384 	pm_runtime_set_suspended(dev);
385 
386 	/* Undo any residual pm_autopm_get_interface_* calls */
387 	for (r = atomic_read(&intf->pm_usage_cnt); r > 0; --r)
388 		usb_autopm_put_interface_no_suspend(intf);
389 	atomic_set(&intf->pm_usage_cnt, 0);
390 
391 	if (!error)
392 		usb_autosuspend_device(udev);
393 
394 	return 0;
395 }
396 
397 /**
398  * usb_driver_claim_interface - bind a driver to an interface
399  * @driver: the driver to be bound
400  * @iface: the interface to which it will be bound; must be in the
401  *	usb device's active configuration
402  * @priv: driver data associated with that interface
403  *
404  * This is used by usb device drivers that need to claim more than one
405  * interface on a device when probing (audio and acm are current examples).
406  * No device driver should directly modify internal usb_interface or
407  * usb_device structure members.
408  *
409  * Few drivers should need to use this routine, since the most natural
410  * way to bind to an interface is to return the private data from
411  * the driver's probe() method.
412  *
413  * Callers must own the device lock, so driver probe() entries don't need
414  * extra locking, but other call contexts may need to explicitly claim that
415  * lock.
416  */
usb_driver_claim_interface(struct usb_driver * driver,struct usb_interface * iface,void * priv)417 int usb_driver_claim_interface(struct usb_driver *driver,
418 				struct usb_interface *iface, void *priv)
419 {
420 	struct device *dev = &iface->dev;
421 	int retval = 0;
422 
423 	if (dev->driver)
424 		return -EBUSY;
425 
426 	dev->driver = &driver->drvwrap.driver;
427 	usb_set_intfdata(iface, priv);
428 	iface->needs_binding = 0;
429 
430 	iface->condition = USB_INTERFACE_BOUND;
431 
432 	/* Claimed interfaces are initially inactive (suspended) and
433 	 * runtime-PM-enabled, but only if the driver has autosuspend
434 	 * support.  Otherwise they are marked active, to prevent the
435 	 * device from being autosuspended, but left disabled.  In either
436 	 * case they are sensitive to their children's power states.
437 	 */
438 	pm_suspend_ignore_children(dev, false);
439 	if (driver->supports_autosuspend)
440 		pm_runtime_enable(dev);
441 	else
442 		pm_runtime_set_active(dev);
443 
444 	/* if interface was already added, bind now; else let
445 	 * the future device_add() bind it, bypassing probe()
446 	 */
447 	if (device_is_registered(dev))
448 		retval = device_bind_driver(dev);
449 
450 	return retval;
451 }
452 EXPORT_SYMBOL_GPL(usb_driver_claim_interface);
453 
454 /**
455  * usb_driver_release_interface - unbind a driver from an interface
456  * @driver: the driver to be unbound
457  * @iface: the interface from which it will be unbound
458  *
459  * This can be used by drivers to release an interface without waiting
460  * for their disconnect() methods to be called.  In typical cases this
461  * also causes the driver disconnect() method to be called.
462  *
463  * This call is synchronous, and may not be used in an interrupt context.
464  * Callers must own the device lock, so driver disconnect() entries don't
465  * need extra locking, but other call contexts may need to explicitly claim
466  * that lock.
467  */
usb_driver_release_interface(struct usb_driver * driver,struct usb_interface * iface)468 void usb_driver_release_interface(struct usb_driver *driver,
469 					struct usb_interface *iface)
470 {
471 	struct device *dev = &iface->dev;
472 
473 	/* this should never happen, don't release something that's not ours */
474 	if (!dev->driver || dev->driver != &driver->drvwrap.driver)
475 		return;
476 
477 	/* don't release from within disconnect() */
478 	if (iface->condition != USB_INTERFACE_BOUND)
479 		return;
480 	iface->condition = USB_INTERFACE_UNBINDING;
481 
482 	/* Release via the driver core only if the interface
483 	 * has already been registered
484 	 */
485 	if (device_is_registered(dev)) {
486 		device_release_driver(dev);
487 	} else {
488 		device_lock(dev);
489 		usb_unbind_interface(dev);
490 		dev->driver = NULL;
491 		device_unlock(dev);
492 	}
493 }
494 EXPORT_SYMBOL_GPL(usb_driver_release_interface);
495 
496 /* returns 0 if no match, 1 if match */
usb_match_device(struct usb_device * dev,const struct usb_device_id * id)497 int usb_match_device(struct usb_device *dev, const struct usb_device_id *id)
498 {
499 	if ((id->match_flags & USB_DEVICE_ID_MATCH_VENDOR) &&
500 	    id->idVendor != le16_to_cpu(dev->descriptor.idVendor))
501 		return 0;
502 
503 	if ((id->match_flags & USB_DEVICE_ID_MATCH_PRODUCT) &&
504 	    id->idProduct != le16_to_cpu(dev->descriptor.idProduct))
505 		return 0;
506 
507 	/* No need to test id->bcdDevice_lo != 0, since 0 is never
508 	   greater than any unsigned number. */
509 	if ((id->match_flags & USB_DEVICE_ID_MATCH_DEV_LO) &&
510 	    (id->bcdDevice_lo > le16_to_cpu(dev->descriptor.bcdDevice)))
511 		return 0;
512 
513 	if ((id->match_flags & USB_DEVICE_ID_MATCH_DEV_HI) &&
514 	    (id->bcdDevice_hi < le16_to_cpu(dev->descriptor.bcdDevice)))
515 		return 0;
516 
517 	if ((id->match_flags & USB_DEVICE_ID_MATCH_DEV_CLASS) &&
518 	    (id->bDeviceClass != dev->descriptor.bDeviceClass))
519 		return 0;
520 
521 	if ((id->match_flags & USB_DEVICE_ID_MATCH_DEV_SUBCLASS) &&
522 	    (id->bDeviceSubClass != dev->descriptor.bDeviceSubClass))
523 		return 0;
524 
525 	if ((id->match_flags & USB_DEVICE_ID_MATCH_DEV_PROTOCOL) &&
526 	    (id->bDeviceProtocol != dev->descriptor.bDeviceProtocol))
527 		return 0;
528 
529 	return 1;
530 }
531 
532 /* returns 0 if no match, 1 if match */
usb_match_one_id_intf(struct usb_device * dev,struct usb_host_interface * intf,const struct usb_device_id * id)533 int usb_match_one_id_intf(struct usb_device *dev,
534 			  struct usb_host_interface *intf,
535 			  const struct usb_device_id *id)
536 {
537 	/* The interface class, subclass, and protocol should never be
538 	 * checked for a match if the device class is Vendor Specific,
539 	 * unless the match record specifies the Vendor ID. */
540 	if (dev->descriptor.bDeviceClass == USB_CLASS_VENDOR_SPEC &&
541 			!(id->match_flags & USB_DEVICE_ID_MATCH_VENDOR) &&
542 			(id->match_flags & (USB_DEVICE_ID_MATCH_INT_CLASS |
543 				USB_DEVICE_ID_MATCH_INT_SUBCLASS |
544 				USB_DEVICE_ID_MATCH_INT_PROTOCOL)))
545 		return 0;
546 
547 	if ((id->match_flags & USB_DEVICE_ID_MATCH_INT_CLASS) &&
548 	    (id->bInterfaceClass != intf->desc.bInterfaceClass))
549 		return 0;
550 
551 	if ((id->match_flags & USB_DEVICE_ID_MATCH_INT_SUBCLASS) &&
552 	    (id->bInterfaceSubClass != intf->desc.bInterfaceSubClass))
553 		return 0;
554 
555 	if ((id->match_flags & USB_DEVICE_ID_MATCH_INT_PROTOCOL) &&
556 	    (id->bInterfaceProtocol != intf->desc.bInterfaceProtocol))
557 		return 0;
558 
559 	return 1;
560 }
561 
562 /* returns 0 if no match, 1 if match */
usb_match_one_id(struct usb_interface * interface,const struct usb_device_id * id)563 int usb_match_one_id(struct usb_interface *interface,
564 		     const struct usb_device_id *id)
565 {
566 	struct usb_host_interface *intf;
567 	struct usb_device *dev;
568 
569 	/* proc_connectinfo in devio.c may call us with id == NULL. */
570 	if (id == NULL)
571 		return 0;
572 
573 	intf = interface->cur_altsetting;
574 	dev = interface_to_usbdev(interface);
575 
576 	if (!usb_match_device(dev, id))
577 		return 0;
578 
579 	return usb_match_one_id_intf(dev, intf, id);
580 }
581 EXPORT_SYMBOL_GPL(usb_match_one_id);
582 
583 /**
584  * usb_match_id - find first usb_device_id matching device or interface
585  * @interface: the interface of interest
586  * @id: array of usb_device_id structures, terminated by zero entry
587  *
588  * usb_match_id searches an array of usb_device_id's and returns
589  * the first one matching the device or interface, or null.
590  * This is used when binding (or rebinding) a driver to an interface.
591  * Most USB device drivers will use this indirectly, through the usb core,
592  * but some layered driver frameworks use it directly.
593  * These device tables are exported with MODULE_DEVICE_TABLE, through
594  * modutils, to support the driver loading functionality of USB hotplugging.
595  *
596  * What Matches:
597  *
598  * The "match_flags" element in a usb_device_id controls which
599  * members are used.  If the corresponding bit is set, the
600  * value in the device_id must match its corresponding member
601  * in the device or interface descriptor, or else the device_id
602  * does not match.
603  *
604  * "driver_info" is normally used only by device drivers,
605  * but you can create a wildcard "matches anything" usb_device_id
606  * as a driver's "modules.usbmap" entry if you provide an id with
607  * only a nonzero "driver_info" field.  If you do this, the USB device
608  * driver's probe() routine should use additional intelligence to
609  * decide whether to bind to the specified interface.
610  *
611  * What Makes Good usb_device_id Tables:
612  *
613  * The match algorithm is very simple, so that intelligence in
614  * driver selection must come from smart driver id records.
615  * Unless you have good reasons to use another selection policy,
616  * provide match elements only in related groups, and order match
617  * specifiers from specific to general.  Use the macros provided
618  * for that purpose if you can.
619  *
620  * The most specific match specifiers use device descriptor
621  * data.  These are commonly used with product-specific matches;
622  * the USB_DEVICE macro lets you provide vendor and product IDs,
623  * and you can also match against ranges of product revisions.
624  * These are widely used for devices with application or vendor
625  * specific bDeviceClass values.
626  *
627  * Matches based on device class/subclass/protocol specifications
628  * are slightly more general; use the USB_DEVICE_INFO macro, or
629  * its siblings.  These are used with single-function devices
630  * where bDeviceClass doesn't specify that each interface has
631  * its own class.
632  *
633  * Matches based on interface class/subclass/protocol are the
634  * most general; they let drivers bind to any interface on a
635  * multiple-function device.  Use the USB_INTERFACE_INFO
636  * macro, or its siblings, to match class-per-interface style
637  * devices (as recorded in bInterfaceClass).
638  *
639  * Note that an entry created by USB_INTERFACE_INFO won't match
640  * any interface if the device class is set to Vendor-Specific.
641  * This is deliberate; according to the USB spec the meanings of
642  * the interface class/subclass/protocol for these devices are also
643  * vendor-specific, and hence matching against a standard product
644  * class wouldn't work anyway.  If you really want to use an
645  * interface-based match for such a device, create a match record
646  * that also specifies the vendor ID.  (Unforunately there isn't a
647  * standard macro for creating records like this.)
648  *
649  * Within those groups, remember that not all combinations are
650  * meaningful.  For example, don't give a product version range
651  * without vendor and product IDs; or specify a protocol without
652  * its associated class and subclass.
653  */
usb_match_id(struct usb_interface * interface,const struct usb_device_id * id)654 const struct usb_device_id *usb_match_id(struct usb_interface *interface,
655 					 const struct usb_device_id *id)
656 {
657 	/* proc_connectinfo in devio.c may call us with id == NULL. */
658 	if (id == NULL)
659 		return NULL;
660 
661 	/* It is important to check that id->driver_info is nonzero,
662 	   since an entry that is all zeroes except for a nonzero
663 	   id->driver_info is the way to create an entry that
664 	   indicates that the driver want to examine every
665 	   device and interface. */
666 	for (; id->idVendor || id->idProduct || id->bDeviceClass ||
667 	       id->bInterfaceClass || id->driver_info; id++) {
668 		if (usb_match_one_id(interface, id))
669 			return id;
670 	}
671 
672 	return NULL;
673 }
674 EXPORT_SYMBOL_GPL(usb_match_id);
675 
usb_device_match(struct device * dev,struct device_driver * drv)676 static int usb_device_match(struct device *dev, struct device_driver *drv)
677 {
678 	/* devices and interfaces are handled separately */
679 	if (is_usb_device(dev)) {
680 
681 		/* interface drivers never match devices */
682 		if (!is_usb_device_driver(drv))
683 			return 0;
684 
685 		/* TODO: Add real matching code */
686 		return 1;
687 
688 	} else if (is_usb_interface(dev)) {
689 		struct usb_interface *intf;
690 		struct usb_driver *usb_drv;
691 		const struct usb_device_id *id;
692 
693 		/* device drivers never match interfaces */
694 		if (is_usb_device_driver(drv))
695 			return 0;
696 
697 		intf = to_usb_interface(dev);
698 		usb_drv = to_usb_driver(drv);
699 
700 		id = usb_match_id(intf, usb_drv->id_table);
701 		if (id)
702 			return 1;
703 
704 		id = usb_match_dynamic_id(intf, usb_drv);
705 		if (id)
706 			return 1;
707 	}
708 
709 	return 0;
710 }
711 
712 #ifdef	CONFIG_HOTPLUG
usb_uevent(struct device * dev,struct kobj_uevent_env * env)713 static int usb_uevent(struct device *dev, struct kobj_uevent_env *env)
714 {
715 	struct usb_device *usb_dev;
716 
717 	if (is_usb_device(dev)) {
718 		usb_dev = to_usb_device(dev);
719 	} else if (is_usb_interface(dev)) {
720 		struct usb_interface *intf = to_usb_interface(dev);
721 
722 		usb_dev = interface_to_usbdev(intf);
723 	} else {
724 		return 0;
725 	}
726 
727 	if (usb_dev->devnum < 0) {
728 		/* driver is often null here; dev_dbg() would oops */
729 		pr_debug("usb %s: already deleted?\n", dev_name(dev));
730 		return -ENODEV;
731 	}
732 	if (!usb_dev->bus) {
733 		pr_debug("usb %s: bus removed?\n", dev_name(dev));
734 		return -ENODEV;
735 	}
736 
737 #ifdef	CONFIG_USB_DEVICEFS
738 	/* If this is available, userspace programs can directly read
739 	 * all the device descriptors we don't tell them about.  Or
740 	 * act as usermode drivers.
741 	 */
742 	if (add_uevent_var(env, "DEVICE=/proc/bus/usb/%03d/%03d",
743 			   usb_dev->bus->busnum, usb_dev->devnum))
744 		return -ENOMEM;
745 #endif
746 
747 	/* per-device configurations are common */
748 	if (add_uevent_var(env, "PRODUCT=%x/%x/%x",
749 			   le16_to_cpu(usb_dev->descriptor.idVendor),
750 			   le16_to_cpu(usb_dev->descriptor.idProduct),
751 			   le16_to_cpu(usb_dev->descriptor.bcdDevice)))
752 		return -ENOMEM;
753 
754 	/* class-based driver binding models */
755 	if (add_uevent_var(env, "TYPE=%d/%d/%d",
756 			   usb_dev->descriptor.bDeviceClass,
757 			   usb_dev->descriptor.bDeviceSubClass,
758 			   usb_dev->descriptor.bDeviceProtocol))
759 		return -ENOMEM;
760 
761 	return 0;
762 }
763 
764 #else
765 
usb_uevent(struct device * dev,struct kobj_uevent_env * env)766 static int usb_uevent(struct device *dev, struct kobj_uevent_env *env)
767 {
768 	return -ENODEV;
769 }
770 #endif	/* CONFIG_HOTPLUG */
771 
772 /**
773  * usb_register_device_driver - register a USB device (not interface) driver
774  * @new_udriver: USB operations for the device driver
775  * @owner: module owner of this driver.
776  *
777  * Registers a USB device driver with the USB core.  The list of
778  * unattached devices will be rescanned whenever a new driver is
779  * added, allowing the new driver to attach to any recognized devices.
780  * Returns a negative error code on failure and 0 on success.
781  */
usb_register_device_driver(struct usb_device_driver * new_udriver,struct module * owner)782 int usb_register_device_driver(struct usb_device_driver *new_udriver,
783 		struct module *owner)
784 {
785 	int retval = 0;
786 
787 	if (usb_disabled())
788 		return -ENODEV;
789 
790 	new_udriver->drvwrap.for_devices = 1;
791 	new_udriver->drvwrap.driver.name = (char *) new_udriver->name;
792 	new_udriver->drvwrap.driver.bus = &usb_bus_type;
793 	new_udriver->drvwrap.driver.probe = usb_probe_device;
794 	new_udriver->drvwrap.driver.remove = usb_unbind_device;
795 	new_udriver->drvwrap.driver.owner = owner;
796 
797 	retval = driver_register(&new_udriver->drvwrap.driver);
798 
799 	if (!retval) {
800 		pr_info("%s: registered new device driver %s\n",
801 			usbcore_name, new_udriver->name);
802 		usbfs_update_special();
803 	} else {
804 		printk(KERN_ERR "%s: error %d registering device "
805 			"	driver %s\n",
806 			usbcore_name, retval, new_udriver->name);
807 	}
808 
809 	return retval;
810 }
811 EXPORT_SYMBOL_GPL(usb_register_device_driver);
812 
813 /**
814  * usb_deregister_device_driver - unregister a USB device (not interface) driver
815  * @udriver: USB operations of the device driver to unregister
816  * Context: must be able to sleep
817  *
818  * Unlinks the specified driver from the internal USB driver list.
819  */
usb_deregister_device_driver(struct usb_device_driver * udriver)820 void usb_deregister_device_driver(struct usb_device_driver *udriver)
821 {
822 	pr_info("%s: deregistering device driver %s\n",
823 			usbcore_name, udriver->name);
824 
825 	driver_unregister(&udriver->drvwrap.driver);
826 	usbfs_update_special();
827 }
828 EXPORT_SYMBOL_GPL(usb_deregister_device_driver);
829 
830 /**
831  * usb_register_driver - register a USB interface driver
832  * @new_driver: USB operations for the interface driver
833  * @owner: module owner of this driver.
834  * @mod_name: module name string
835  *
836  * Registers a USB interface driver with the USB core.  The list of
837  * unattached interfaces will be rescanned whenever a new driver is
838  * added, allowing the new driver to attach to any recognized interfaces.
839  * Returns a negative error code on failure and 0 on success.
840  *
841  * NOTE: if you want your driver to use the USB major number, you must call
842  * usb_register_dev() to enable that functionality.  This function no longer
843  * takes care of that.
844  */
usb_register_driver(struct usb_driver * new_driver,struct module * owner,const char * mod_name)845 int usb_register_driver(struct usb_driver *new_driver, struct module *owner,
846 			const char *mod_name)
847 {
848 	int retval = 0;
849 
850 	if (usb_disabled())
851 		return -ENODEV;
852 
853 	new_driver->drvwrap.for_devices = 0;
854 	new_driver->drvwrap.driver.name = (char *) new_driver->name;
855 	new_driver->drvwrap.driver.bus = &usb_bus_type;
856 	new_driver->drvwrap.driver.probe = usb_probe_interface;
857 	new_driver->drvwrap.driver.remove = usb_unbind_interface;
858 	new_driver->drvwrap.driver.owner = owner;
859 	new_driver->drvwrap.driver.mod_name = mod_name;
860 	spin_lock_init(&new_driver->dynids.lock);
861 	INIT_LIST_HEAD(&new_driver->dynids.list);
862 
863 	retval = driver_register(&new_driver->drvwrap.driver);
864 	if (retval)
865 		goto out;
866 
867 	usbfs_update_special();
868 
869 	retval = usb_create_newid_files(new_driver);
870 	if (retval)
871 		goto out_newid;
872 
873 	pr_info("%s: registered new interface driver %s\n",
874 			usbcore_name, new_driver->name);
875 
876 out:
877 	return retval;
878 
879 out_newid:
880 	driver_unregister(&new_driver->drvwrap.driver);
881 
882 	printk(KERN_ERR "%s: error %d registering interface "
883 			"	driver %s\n",
884 			usbcore_name, retval, new_driver->name);
885 	goto out;
886 }
887 EXPORT_SYMBOL_GPL(usb_register_driver);
888 
889 /**
890  * usb_deregister - unregister a USB interface driver
891  * @driver: USB operations of the interface driver to unregister
892  * Context: must be able to sleep
893  *
894  * Unlinks the specified driver from the internal USB driver list.
895  *
896  * NOTE: If you called usb_register_dev(), you still need to call
897  * usb_deregister_dev() to clean up your driver's allocated minor numbers,
898  * this * call will no longer do it for you.
899  */
usb_deregister(struct usb_driver * driver)900 void usb_deregister(struct usb_driver *driver)
901 {
902 	pr_info("%s: deregistering interface driver %s\n",
903 			usbcore_name, driver->name);
904 
905 	usb_remove_newid_files(driver);
906 	driver_unregister(&driver->drvwrap.driver);
907 	usb_free_dynids(driver);
908 
909 	usbfs_update_special();
910 }
911 EXPORT_SYMBOL_GPL(usb_deregister);
912 
913 /* Forced unbinding of a USB interface driver, either because
914  * it doesn't support pre_reset/post_reset/reset_resume or
915  * because it doesn't support suspend/resume.
916  *
917  * The caller must hold @intf's device's lock, but not @intf's lock.
918  */
usb_forced_unbind_intf(struct usb_interface * intf)919 void usb_forced_unbind_intf(struct usb_interface *intf)
920 {
921 	struct usb_driver *driver = to_usb_driver(intf->dev.driver);
922 
923 	dev_dbg(&intf->dev, "forced unbind\n");
924 	usb_driver_release_interface(driver, intf);
925 
926 	/* Mark the interface for later rebinding */
927 	intf->needs_binding = 1;
928 }
929 
930 /*
931  * Unbind drivers for @udev's marked interfaces.  These interfaces have
932  * the needs_binding flag set, for example by usb_resume_interface().
933  *
934  * The caller must hold @udev's device lock.
935  */
unbind_marked_interfaces(struct usb_device * udev)936 static void unbind_marked_interfaces(struct usb_device *udev)
937 {
938 	struct usb_host_config	*config;
939 	int			i;
940 	struct usb_interface	*intf;
941 
942 	config = udev->actconfig;
943 	if (config) {
944 		for (i = 0; i < config->desc.bNumInterfaces; ++i) {
945 			intf = config->interface[i];
946 			if (intf->dev.driver && intf->needs_binding)
947 				usb_forced_unbind_intf(intf);
948 		}
949 	}
950 }
951 
952 /* Delayed forced unbinding of a USB interface driver and scan
953  * for rebinding.
954  *
955  * The caller must hold @intf's device's lock, but not @intf's lock.
956  *
957  * Note: Rebinds will be skipped if a system sleep transition is in
958  * progress and the PM "complete" callback hasn't occurred yet.
959  */
usb_rebind_intf(struct usb_interface * intf)960 static void usb_rebind_intf(struct usb_interface *intf)
961 {
962 	int rc;
963 
964 	/* Delayed unbind of an existing driver */
965 	if (intf->dev.driver)
966 		usb_forced_unbind_intf(intf);
967 
968 	/* Try to rebind the interface */
969 	if (!intf->dev.power.is_prepared) {
970 		intf->needs_binding = 0;
971 		rc = device_attach(&intf->dev);
972 		if (rc < 0)
973 			dev_warn(&intf->dev, "rebind failed: %d\n", rc);
974 	}
975 }
976 
977 /*
978  * Rebind drivers to @udev's marked interfaces.  These interfaces have
979  * the needs_binding flag set.
980  *
981  * The caller must hold @udev's device lock.
982  */
rebind_marked_interfaces(struct usb_device * udev)983 static void rebind_marked_interfaces(struct usb_device *udev)
984 {
985 	struct usb_host_config	*config;
986 	int			i;
987 	struct usb_interface	*intf;
988 
989 	config = udev->actconfig;
990 	if (config) {
991 		for (i = 0; i < config->desc.bNumInterfaces; ++i) {
992 			intf = config->interface[i];
993 			if (intf->needs_binding)
994 				usb_rebind_intf(intf);
995 		}
996 	}
997 }
998 
999 /*
1000  * Unbind all of @udev's marked interfaces and then rebind all of them.
1001  * This ordering is necessary because some drivers claim several interfaces
1002  * when they are first probed.
1003  *
1004  * The caller must hold @udev's device lock.
1005  */
usb_unbind_and_rebind_marked_interfaces(struct usb_device * udev)1006 void usb_unbind_and_rebind_marked_interfaces(struct usb_device *udev)
1007 {
1008 	unbind_marked_interfaces(udev);
1009 	rebind_marked_interfaces(udev);
1010 }
1011 
1012 #ifdef CONFIG_PM
1013 
1014 /* Unbind drivers for @udev's interfaces that don't support suspend/resume
1015  * There is no check for reset_resume here because it can be determined
1016  * only during resume whether reset_resume is needed.
1017  *
1018  * The caller must hold @udev's device lock.
1019  */
unbind_no_pm_drivers_interfaces(struct usb_device * udev)1020 static void unbind_no_pm_drivers_interfaces(struct usb_device *udev)
1021 {
1022 	struct usb_host_config	*config;
1023 	int			i;
1024 	struct usb_interface	*intf;
1025 	struct usb_driver	*drv;
1026 
1027 	config = udev->actconfig;
1028 	if (config) {
1029 		for (i = 0; i < config->desc.bNumInterfaces; ++i) {
1030 			intf = config->interface[i];
1031 
1032 			if (intf->dev.driver) {
1033 				drv = to_usb_driver(intf->dev.driver);
1034 				if (!drv->suspend || !drv->resume)
1035 					usb_forced_unbind_intf(intf);
1036 			}
1037 		}
1038 	}
1039 }
1040 
usb_suspend_device(struct usb_device * udev,pm_message_t msg)1041 static int usb_suspend_device(struct usb_device *udev, pm_message_t msg)
1042 {
1043 	struct usb_device_driver	*udriver;
1044 	int				status = 0;
1045 
1046 	if (udev->state == USB_STATE_NOTATTACHED ||
1047 			udev->state == USB_STATE_SUSPENDED)
1048 		goto done;
1049 
1050 	/* For devices that don't have a driver, we do a generic suspend. */
1051 	if (udev->dev.driver)
1052 		udriver = to_usb_device_driver(udev->dev.driver);
1053 	else {
1054 		udev->do_remote_wakeup = 0;
1055 		udriver = &usb_generic_driver;
1056 	}
1057 	status = udriver->suspend(udev, msg);
1058 
1059  done:
1060 	dev_vdbg(&udev->dev, "%s: status %d\n", __func__, status);
1061 	return status;
1062 }
1063 
usb_resume_device(struct usb_device * udev,pm_message_t msg)1064 static int usb_resume_device(struct usb_device *udev, pm_message_t msg)
1065 {
1066 	struct usb_device_driver	*udriver;
1067 	int				status = 0;
1068 
1069 	if (udev->state == USB_STATE_NOTATTACHED)
1070 		goto done;
1071 
1072 	/* Can't resume it if it doesn't have a driver. */
1073 	if (udev->dev.driver == NULL) {
1074 		status = -ENOTCONN;
1075 		goto done;
1076 	}
1077 
1078 	/* Non-root devices on a full/low-speed bus must wait for their
1079 	 * companion high-speed root hub, in case a handoff is needed.
1080 	 */
1081 	if (!PMSG_IS_AUTO(msg) && udev->parent && udev->bus->hs_companion)
1082 		device_pm_wait_for_dev(&udev->dev,
1083 				&udev->bus->hs_companion->root_hub->dev);
1084 
1085 	if (udev->quirks & USB_QUIRK_RESET_RESUME)
1086 		udev->reset_resume = 1;
1087 
1088 	udriver = to_usb_device_driver(udev->dev.driver);
1089 	status = udriver->resume(udev, msg);
1090 
1091  done:
1092 	dev_vdbg(&udev->dev, "%s: status %d\n", __func__, status);
1093 	return status;
1094 }
1095 
usb_suspend_interface(struct usb_device * udev,struct usb_interface * intf,pm_message_t msg)1096 static int usb_suspend_interface(struct usb_device *udev,
1097 		struct usb_interface *intf, pm_message_t msg)
1098 {
1099 	struct usb_driver	*driver;
1100 	int			status = 0;
1101 
1102 	if (udev->state == USB_STATE_NOTATTACHED ||
1103 			intf->condition == USB_INTERFACE_UNBOUND)
1104 		goto done;
1105 	driver = to_usb_driver(intf->dev.driver);
1106 
1107 	/* at this time we know the driver supports suspend */
1108 	status = driver->suspend(intf, msg);
1109 	if (status && !PMSG_IS_AUTO(msg))
1110 		dev_err(&intf->dev, "suspend error %d\n", status);
1111 
1112  done:
1113 	dev_vdbg(&intf->dev, "%s: status %d\n", __func__, status);
1114 	return status;
1115 }
1116 
usb_resume_interface(struct usb_device * udev,struct usb_interface * intf,pm_message_t msg,int reset_resume)1117 static int usb_resume_interface(struct usb_device *udev,
1118 		struct usb_interface *intf, pm_message_t msg, int reset_resume)
1119 {
1120 	struct usb_driver	*driver;
1121 	int			status = 0;
1122 
1123 	if (udev->state == USB_STATE_NOTATTACHED)
1124 		goto done;
1125 
1126 	/* Don't let autoresume interfere with unbinding */
1127 	if (intf->condition == USB_INTERFACE_UNBINDING)
1128 		goto done;
1129 
1130 	/* Can't resume it if it doesn't have a driver. */
1131 	if (intf->condition == USB_INTERFACE_UNBOUND) {
1132 
1133 		/* Carry out a deferred switch to altsetting 0 */
1134 		if (intf->needs_altsetting0 && !intf->dev.power.is_prepared) {
1135 			usb_set_interface(udev, intf->altsetting[0].
1136 					desc.bInterfaceNumber, 0);
1137 			intf->needs_altsetting0 = 0;
1138 		}
1139 		goto done;
1140 	}
1141 
1142 	/* Don't resume if the interface is marked for rebinding */
1143 	if (intf->needs_binding)
1144 		goto done;
1145 	driver = to_usb_driver(intf->dev.driver);
1146 
1147 	if (reset_resume) {
1148 		if (driver->reset_resume) {
1149 			status = driver->reset_resume(intf);
1150 			if (status)
1151 				dev_err(&intf->dev, "%s error %d\n",
1152 						"reset_resume", status);
1153 		} else {
1154 			intf->needs_binding = 1;
1155 			dev_warn(&intf->dev, "no %s for driver %s?\n",
1156 					"reset_resume", driver->name);
1157 		}
1158 	} else {
1159 		status = driver->resume(intf);
1160 		if (status)
1161 			dev_err(&intf->dev, "resume error %d\n", status);
1162 	}
1163 
1164 done:
1165 	dev_vdbg(&intf->dev, "%s: status %d\n", __func__, status);
1166 
1167 	/* Later we will unbind the driver and/or reprobe, if necessary */
1168 	return status;
1169 }
1170 
1171 /**
1172  * usb_suspend_both - suspend a USB device and its interfaces
1173  * @udev: the usb_device to suspend
1174  * @msg: Power Management message describing this state transition
1175  *
1176  * This is the central routine for suspending USB devices.  It calls the
1177  * suspend methods for all the interface drivers in @udev and then calls
1178  * the suspend method for @udev itself.  If an error occurs at any stage,
1179  * all the interfaces which were suspended are resumed so that they remain
1180  * in the same state as the device.
1181  *
1182  * Autosuspend requests originating from a child device or an interface
1183  * driver may be made without the protection of @udev's device lock, but
1184  * all other suspend calls will hold the lock.  Usbcore will insure that
1185  * method calls do not arrive during bind, unbind, or reset operations.
1186  * However drivers must be prepared to handle suspend calls arriving at
1187  * unpredictable times.
1188  *
1189  * This routine can run only in process context.
1190  */
usb_suspend_both(struct usb_device * udev,pm_message_t msg)1191 static int usb_suspend_both(struct usb_device *udev, pm_message_t msg)
1192 {
1193 	int			status = 0;
1194 	int			i = 0, n = 0;
1195 	struct usb_interface	*intf;
1196 
1197 	if (udev->state == USB_STATE_NOTATTACHED ||
1198 			udev->state == USB_STATE_SUSPENDED)
1199 		goto done;
1200 
1201 	/* Suspend all the interfaces and then udev itself */
1202 	if (udev->actconfig) {
1203 		n = udev->actconfig->desc.bNumInterfaces;
1204 		for (i = n - 1; i >= 0; --i) {
1205 			intf = udev->actconfig->interface[i];
1206 			status = usb_suspend_interface(udev, intf, msg);
1207 
1208 			/* Ignore errors during system sleep transitions */
1209 			if (!PMSG_IS_AUTO(msg))
1210 				status = 0;
1211 			if (status != 0)
1212 				break;
1213 		}
1214 	}
1215 	if (status == 0) {
1216 		status = usb_suspend_device(udev, msg);
1217 
1218 		/*
1219 		 * Ignore errors from non-root-hub devices during
1220 		 * system sleep transitions.  For the most part,
1221 		 * these devices should go to low power anyway when
1222 		 * the entire bus is suspended.
1223 		 */
1224 		if (udev->parent && !PMSG_IS_AUTO(msg))
1225 			status = 0;
1226 	}
1227 
1228 	/* If the suspend failed, resume interfaces that did get suspended */
1229 	if (status != 0) {
1230 		msg.event ^= (PM_EVENT_SUSPEND | PM_EVENT_RESUME);
1231 		while (++i < n) {
1232 			intf = udev->actconfig->interface[i];
1233 			usb_resume_interface(udev, intf, msg, 0);
1234 		}
1235 
1236 	/* If the suspend succeeded then prevent any more URB submissions
1237 	 * and flush any outstanding URBs.
1238 	 */
1239 	} else {
1240 		udev->can_submit = 0;
1241 		for (i = 0; i < 16; ++i) {
1242 			usb_hcd_flush_endpoint(udev, udev->ep_out[i]);
1243 			usb_hcd_flush_endpoint(udev, udev->ep_in[i]);
1244 		}
1245 	}
1246 
1247  done:
1248 	dev_vdbg(&udev->dev, "%s: status %d\n", __func__, status);
1249 	return status;
1250 }
1251 
1252 /**
1253  * usb_resume_both - resume a USB device and its interfaces
1254  * @udev: the usb_device to resume
1255  * @msg: Power Management message describing this state transition
1256  *
1257  * This is the central routine for resuming USB devices.  It calls the
1258  * the resume method for @udev and then calls the resume methods for all
1259  * the interface drivers in @udev.
1260  *
1261  * Autoresume requests originating from a child device or an interface
1262  * driver may be made without the protection of @udev's device lock, but
1263  * all other resume calls will hold the lock.  Usbcore will insure that
1264  * method calls do not arrive during bind, unbind, or reset operations.
1265  * However drivers must be prepared to handle resume calls arriving at
1266  * unpredictable times.
1267  *
1268  * This routine can run only in process context.
1269  */
usb_resume_both(struct usb_device * udev,pm_message_t msg)1270 static int usb_resume_both(struct usb_device *udev, pm_message_t msg)
1271 {
1272 	int			status = 0;
1273 	int			i;
1274 	struct usb_interface	*intf;
1275 
1276 	if (udev->state == USB_STATE_NOTATTACHED) {
1277 		status = -ENODEV;
1278 		goto done;
1279 	}
1280 	udev->can_submit = 1;
1281 
1282 	/* Resume the device */
1283 	if (udev->state == USB_STATE_SUSPENDED || udev->reset_resume)
1284 		status = usb_resume_device(udev, msg);
1285 
1286 	/* Resume the interfaces */
1287 	if (status == 0 && udev->actconfig) {
1288 		for (i = 0; i < udev->actconfig->desc.bNumInterfaces; i++) {
1289 			intf = udev->actconfig->interface[i];
1290 			usb_resume_interface(udev, intf, msg,
1291 					udev->reset_resume);
1292 		}
1293 	}
1294 	usb_mark_last_busy(udev);
1295 
1296  done:
1297 	dev_vdbg(&udev->dev, "%s: status %d\n", __func__, status);
1298 	if (!status)
1299 		udev->reset_resume = 0;
1300 	return status;
1301 }
1302 
choose_wakeup(struct usb_device * udev,pm_message_t msg)1303 static void choose_wakeup(struct usb_device *udev, pm_message_t msg)
1304 {
1305 	int	w;
1306 
1307 	/* Remote wakeup is needed only when we actually go to sleep.
1308 	 * For things like FREEZE and QUIESCE, if the device is already
1309 	 * autosuspended then its current wakeup setting is okay.
1310 	 */
1311 	if (msg.event == PM_EVENT_FREEZE || msg.event == PM_EVENT_QUIESCE) {
1312 		if (udev->state != USB_STATE_SUSPENDED)
1313 			udev->do_remote_wakeup = 0;
1314 		return;
1315 	}
1316 
1317 	/* Enable remote wakeup if it is allowed, even if no interface drivers
1318 	 * actually want it.
1319 	 */
1320 	w = device_may_wakeup(&udev->dev);
1321 
1322 	/* If the device is autosuspended with the wrong wakeup setting,
1323 	 * autoresume now so the setting can be changed.
1324 	 */
1325 	if (udev->state == USB_STATE_SUSPENDED && w != udev->do_remote_wakeup)
1326 		pm_runtime_resume(&udev->dev);
1327 	udev->do_remote_wakeup = w;
1328 }
1329 
1330 /* The device lock is held by the PM core */
usb_suspend(struct device * dev,pm_message_t msg)1331 int usb_suspend(struct device *dev, pm_message_t msg)
1332 {
1333 	struct usb_device	*udev = to_usb_device(dev);
1334 
1335 	unbind_no_pm_drivers_interfaces(udev);
1336 
1337 	/* From now on we are sure all drivers support suspend/resume
1338 	 * but not necessarily reset_resume()
1339 	 * so we may still need to unbind and rebind upon resume
1340 	 */
1341 	choose_wakeup(udev, msg);
1342 	return usb_suspend_both(udev, msg);
1343 }
1344 
1345 /* The device lock is held by the PM core */
usb_resume_complete(struct device * dev)1346 int usb_resume_complete(struct device *dev)
1347 {
1348 	struct usb_device *udev = to_usb_device(dev);
1349 
1350 	/* For PM complete calls, all we do is rebind interfaces
1351 	 * whose needs_binding flag is set
1352 	 */
1353 	if (udev->state != USB_STATE_NOTATTACHED)
1354 		rebind_marked_interfaces(udev);
1355 	return 0;
1356 }
1357 
1358 /* The device lock is held by the PM core */
usb_resume(struct device * dev,pm_message_t msg)1359 int usb_resume(struct device *dev, pm_message_t msg)
1360 {
1361 	struct usb_device	*udev = to_usb_device(dev);
1362 	int			status;
1363 
1364 	/* For all calls, take the device back to full power and
1365 	 * tell the PM core in case it was autosuspended previously.
1366 	 * Unbind the interfaces that will need rebinding later,
1367 	 * because they fail to support reset_resume.
1368 	 * (This can't be done in usb_resume_interface()
1369 	 * above because it doesn't own the right set of locks.)
1370 	 */
1371 	status = usb_resume_both(udev, msg);
1372 	if (status == 0) {
1373 		pm_runtime_disable(dev);
1374 		pm_runtime_set_active(dev);
1375 		pm_runtime_enable(dev);
1376 		unbind_marked_interfaces(udev);
1377 	}
1378 
1379 	/* Avoid PM error messages for devices disconnected while suspended
1380 	 * as we'll display regular disconnect messages just a bit later.
1381 	 */
1382 	if (status == -ENODEV || status == -ESHUTDOWN)
1383 		status = 0;
1384 	return status;
1385 }
1386 
1387 #endif /* CONFIG_PM */
1388 
1389 #ifdef CONFIG_USB_SUSPEND
1390 
1391 /**
1392  * usb_enable_autosuspend - allow a USB device to be autosuspended
1393  * @udev: the USB device which may be autosuspended
1394  *
1395  * This routine allows @udev to be autosuspended.  An autosuspend won't
1396  * take place until the autosuspend_delay has elapsed and all the other
1397  * necessary conditions are satisfied.
1398  *
1399  * The caller must hold @udev's device lock.
1400  */
usb_enable_autosuspend(struct usb_device * udev)1401 void usb_enable_autosuspend(struct usb_device *udev)
1402 {
1403 	pm_runtime_allow(&udev->dev);
1404 }
1405 EXPORT_SYMBOL_GPL(usb_enable_autosuspend);
1406 
1407 /**
1408  * usb_disable_autosuspend - prevent a USB device from being autosuspended
1409  * @udev: the USB device which may not be autosuspended
1410  *
1411  * This routine prevents @udev from being autosuspended and wakes it up
1412  * if it is already autosuspended.
1413  *
1414  * The caller must hold @udev's device lock.
1415  */
usb_disable_autosuspend(struct usb_device * udev)1416 void usb_disable_autosuspend(struct usb_device *udev)
1417 {
1418 	pm_runtime_forbid(&udev->dev);
1419 }
1420 EXPORT_SYMBOL_GPL(usb_disable_autosuspend);
1421 
1422 /**
1423  * usb_autosuspend_device - delayed autosuspend of a USB device and its interfaces
1424  * @udev: the usb_device to autosuspend
1425  *
1426  * This routine should be called when a core subsystem is finished using
1427  * @udev and wants to allow it to autosuspend.  Examples would be when
1428  * @udev's device file in usbfs is closed or after a configuration change.
1429  *
1430  * @udev's usage counter is decremented; if it drops to 0 and all the
1431  * interfaces are inactive then a delayed autosuspend will be attempted.
1432  * The attempt may fail (see autosuspend_check()).
1433  *
1434  * The caller must hold @udev's device lock.
1435  *
1436  * This routine can run only in process context.
1437  */
usb_autosuspend_device(struct usb_device * udev)1438 void usb_autosuspend_device(struct usb_device *udev)
1439 {
1440 	int	status;
1441 
1442 	usb_mark_last_busy(udev);
1443 	status = pm_runtime_put_sync_autosuspend(&udev->dev);
1444 	dev_vdbg(&udev->dev, "%s: cnt %d -> %d\n",
1445 			__func__, atomic_read(&udev->dev.power.usage_count),
1446 			status);
1447 }
1448 
1449 /**
1450  * usb_autoresume_device - immediately autoresume a USB device and its interfaces
1451  * @udev: the usb_device to autoresume
1452  *
1453  * This routine should be called when a core subsystem wants to use @udev
1454  * and needs to guarantee that it is not suspended.  No autosuspend will
1455  * occur until usb_autosuspend_device() is called.  (Note that this will
1456  * not prevent suspend events originating in the PM core.)  Examples would
1457  * be when @udev's device file in usbfs is opened or when a remote-wakeup
1458  * request is received.
1459  *
1460  * @udev's usage counter is incremented to prevent subsequent autosuspends.
1461  * However if the autoresume fails then the usage counter is re-decremented.
1462  *
1463  * The caller must hold @udev's device lock.
1464  *
1465  * This routine can run only in process context.
1466  */
usb_autoresume_device(struct usb_device * udev)1467 int usb_autoresume_device(struct usb_device *udev)
1468 {
1469 	int	status;
1470 
1471 	status = pm_runtime_get_sync(&udev->dev);
1472 	if (status < 0)
1473 		pm_runtime_put_sync(&udev->dev);
1474 	dev_vdbg(&udev->dev, "%s: cnt %d -> %d\n",
1475 			__func__, atomic_read(&udev->dev.power.usage_count),
1476 			status);
1477 	if (status > 0)
1478 		status = 0;
1479 	return status;
1480 }
1481 
1482 /**
1483  * usb_autopm_put_interface - decrement a USB interface's PM-usage counter
1484  * @intf: the usb_interface whose counter should be decremented
1485  *
1486  * This routine should be called by an interface driver when it is
1487  * finished using @intf and wants to allow it to autosuspend.  A typical
1488  * example would be a character-device driver when its device file is
1489  * closed.
1490  *
1491  * The routine decrements @intf's usage counter.  When the counter reaches
1492  * 0, a delayed autosuspend request for @intf's device is attempted.  The
1493  * attempt may fail (see autosuspend_check()).
1494  *
1495  * This routine can run only in process context.
1496  */
usb_autopm_put_interface(struct usb_interface * intf)1497 void usb_autopm_put_interface(struct usb_interface *intf)
1498 {
1499 	struct usb_device	*udev = interface_to_usbdev(intf);
1500 	int			status;
1501 
1502 	usb_mark_last_busy(udev);
1503 	atomic_dec(&intf->pm_usage_cnt);
1504 	status = pm_runtime_put_sync(&intf->dev);
1505 	dev_vdbg(&intf->dev, "%s: cnt %d -> %d\n",
1506 			__func__, atomic_read(&intf->dev.power.usage_count),
1507 			status);
1508 }
1509 EXPORT_SYMBOL_GPL(usb_autopm_put_interface);
1510 
1511 /**
1512  * usb_autopm_put_interface_async - decrement a USB interface's PM-usage counter
1513  * @intf: the usb_interface whose counter should be decremented
1514  *
1515  * This routine does much the same thing as usb_autopm_put_interface():
1516  * It decrements @intf's usage counter and schedules a delayed
1517  * autosuspend request if the counter is <= 0.  The difference is that it
1518  * does not perform any synchronization; callers should hold a private
1519  * lock and handle all synchronization issues themselves.
1520  *
1521  * Typically a driver would call this routine during an URB's completion
1522  * handler, if no more URBs were pending.
1523  *
1524  * This routine can run in atomic context.
1525  */
usb_autopm_put_interface_async(struct usb_interface * intf)1526 void usb_autopm_put_interface_async(struct usb_interface *intf)
1527 {
1528 	struct usb_device	*udev = interface_to_usbdev(intf);
1529 	int			status;
1530 
1531 	usb_mark_last_busy(udev);
1532 	atomic_dec(&intf->pm_usage_cnt);
1533 	status = pm_runtime_put(&intf->dev);
1534 	dev_vdbg(&intf->dev, "%s: cnt %d -> %d\n",
1535 			__func__, atomic_read(&intf->dev.power.usage_count),
1536 			status);
1537 }
1538 EXPORT_SYMBOL_GPL(usb_autopm_put_interface_async);
1539 
1540 /**
1541  * usb_autopm_put_interface_no_suspend - decrement a USB interface's PM-usage counter
1542  * @intf: the usb_interface whose counter should be decremented
1543  *
1544  * This routine decrements @intf's usage counter but does not carry out an
1545  * autosuspend.
1546  *
1547  * This routine can run in atomic context.
1548  */
usb_autopm_put_interface_no_suspend(struct usb_interface * intf)1549 void usb_autopm_put_interface_no_suspend(struct usb_interface *intf)
1550 {
1551 	struct usb_device	*udev = interface_to_usbdev(intf);
1552 
1553 	usb_mark_last_busy(udev);
1554 	atomic_dec(&intf->pm_usage_cnt);
1555 	pm_runtime_put_noidle(&intf->dev);
1556 }
1557 EXPORT_SYMBOL_GPL(usb_autopm_put_interface_no_suspend);
1558 
1559 /**
1560  * usb_autopm_get_interface - increment a USB interface's PM-usage counter
1561  * @intf: the usb_interface whose counter should be incremented
1562  *
1563  * This routine should be called by an interface driver when it wants to
1564  * use @intf and needs to guarantee that it is not suspended.  In addition,
1565  * the routine prevents @intf from being autosuspended subsequently.  (Note
1566  * that this will not prevent suspend events originating in the PM core.)
1567  * This prevention will persist until usb_autopm_put_interface() is called
1568  * or @intf is unbound.  A typical example would be a character-device
1569  * driver when its device file is opened.
1570  *
1571  * @intf's usage counter is incremented to prevent subsequent autosuspends.
1572  * However if the autoresume fails then the counter is re-decremented.
1573  *
1574  * This routine can run only in process context.
1575  */
usb_autopm_get_interface(struct usb_interface * intf)1576 int usb_autopm_get_interface(struct usb_interface *intf)
1577 {
1578 	int	status;
1579 
1580 	status = pm_runtime_get_sync(&intf->dev);
1581 	if (status < 0)
1582 		pm_runtime_put_sync(&intf->dev);
1583 	else
1584 		atomic_inc(&intf->pm_usage_cnt);
1585 	dev_vdbg(&intf->dev, "%s: cnt %d -> %d\n",
1586 			__func__, atomic_read(&intf->dev.power.usage_count),
1587 			status);
1588 	if (status > 0)
1589 		status = 0;
1590 	return status;
1591 }
1592 EXPORT_SYMBOL_GPL(usb_autopm_get_interface);
1593 
1594 /**
1595  * usb_autopm_get_interface_async - increment a USB interface's PM-usage counter
1596  * @intf: the usb_interface whose counter should be incremented
1597  *
1598  * This routine does much the same thing as
1599  * usb_autopm_get_interface(): It increments @intf's usage counter and
1600  * queues an autoresume request if the device is suspended.  The
1601  * differences are that it does not perform any synchronization (callers
1602  * should hold a private lock and handle all synchronization issues
1603  * themselves), and it does not autoresume the device directly (it only
1604  * queues a request).  After a successful call, the device may not yet be
1605  * resumed.
1606  *
1607  * This routine can run in atomic context.
1608  */
usb_autopm_get_interface_async(struct usb_interface * intf)1609 int usb_autopm_get_interface_async(struct usb_interface *intf)
1610 {
1611 	int	status;
1612 
1613 	status = pm_runtime_get(&intf->dev);
1614 	if (status < 0 && status != -EINPROGRESS)
1615 		pm_runtime_put_noidle(&intf->dev);
1616 	else
1617 		atomic_inc(&intf->pm_usage_cnt);
1618 	dev_vdbg(&intf->dev, "%s: cnt %d -> %d\n",
1619 			__func__, atomic_read(&intf->dev.power.usage_count),
1620 			status);
1621 	if (status > 0 || status == -EINPROGRESS)
1622 		status = 0;
1623 	return status;
1624 }
1625 EXPORT_SYMBOL_GPL(usb_autopm_get_interface_async);
1626 
1627 /**
1628  * usb_autopm_get_interface_no_resume - increment a USB interface's PM-usage counter
1629  * @intf: the usb_interface whose counter should be incremented
1630  *
1631  * This routine increments @intf's usage counter but does not carry out an
1632  * autoresume.
1633  *
1634  * This routine can run in atomic context.
1635  */
usb_autopm_get_interface_no_resume(struct usb_interface * intf)1636 void usb_autopm_get_interface_no_resume(struct usb_interface *intf)
1637 {
1638 	struct usb_device	*udev = interface_to_usbdev(intf);
1639 
1640 	usb_mark_last_busy(udev);
1641 	atomic_inc(&intf->pm_usage_cnt);
1642 	pm_runtime_get_noresume(&intf->dev);
1643 }
1644 EXPORT_SYMBOL_GPL(usb_autopm_get_interface_no_resume);
1645 
1646 /* Internal routine to check whether we may autosuspend a device. */
autosuspend_check(struct usb_device * udev)1647 static int autosuspend_check(struct usb_device *udev)
1648 {
1649 	int			w, i;
1650 	struct usb_interface	*intf;
1651 
1652 	/* Fail if autosuspend is disabled, or any interfaces are in use, or
1653 	 * any interface drivers require remote wakeup but it isn't available.
1654 	 */
1655 	w = 0;
1656 	if (udev->actconfig) {
1657 		for (i = 0; i < udev->actconfig->desc.bNumInterfaces; i++) {
1658 			intf = udev->actconfig->interface[i];
1659 
1660 			/* We don't need to check interfaces that are
1661 			 * disabled for runtime PM.  Either they are unbound
1662 			 * or else their drivers don't support autosuspend
1663 			 * and so they are permanently active.
1664 			 */
1665 			if (intf->dev.power.disable_depth)
1666 				continue;
1667 			if (atomic_read(&intf->dev.power.usage_count) > 0)
1668 				return -EBUSY;
1669 			w |= intf->needs_remote_wakeup;
1670 
1671 			/* Don't allow autosuspend if the device will need
1672 			 * a reset-resume and any of its interface drivers
1673 			 * doesn't include support or needs remote wakeup.
1674 			 */
1675 			if (udev->quirks & USB_QUIRK_RESET_RESUME) {
1676 				struct usb_driver *driver;
1677 
1678 				driver = to_usb_driver(intf->dev.driver);
1679 				if (!driver->reset_resume ||
1680 						intf->needs_remote_wakeup)
1681 					return -EOPNOTSUPP;
1682 			}
1683 		}
1684 	}
1685 	if (w && !device_can_wakeup(&udev->dev)) {
1686 		dev_dbg(&udev->dev, "remote wakeup needed for autosuspend\n");
1687 		return -EOPNOTSUPP;
1688 	}
1689 	udev->do_remote_wakeup = w;
1690 	return 0;
1691 }
1692 
usb_runtime_suspend(struct device * dev)1693 int usb_runtime_suspend(struct device *dev)
1694 {
1695 	struct usb_device	*udev = to_usb_device(dev);
1696 	int			status;
1697 
1698 	/* A USB device can be suspended if it passes the various autosuspend
1699 	 * checks.  Runtime suspend for a USB device means suspending all the
1700 	 * interfaces and then the device itself.
1701 	 */
1702 	if (autosuspend_check(udev) != 0)
1703 		return -EAGAIN;
1704 
1705 	status = usb_suspend_both(udev, PMSG_AUTO_SUSPEND);
1706 
1707 	/* Allow a retry if autosuspend failed temporarily */
1708 	if (status == -EAGAIN || status == -EBUSY)
1709 		usb_mark_last_busy(udev);
1710 
1711 	/*
1712 	 * The PM core reacts badly unless the return code is 0,
1713 	 * -EAGAIN, or -EBUSY, so always return -EBUSY on an error
1714 	 * (except for root hubs, because they don't suspend through
1715 	 * an upstream port like other USB devices).
1716 	 */
1717 	if (status != 0 && udev->parent)
1718 		return -EBUSY;
1719 	return status;
1720 }
1721 
usb_runtime_resume(struct device * dev)1722 int usb_runtime_resume(struct device *dev)
1723 {
1724 	struct usb_device	*udev = to_usb_device(dev);
1725 	int			status;
1726 
1727 	/* Runtime resume for a USB device means resuming both the device
1728 	 * and all its interfaces.
1729 	 */
1730 	status = usb_resume_both(udev, PMSG_AUTO_RESUME);
1731 	return status;
1732 }
1733 
usb_runtime_idle(struct device * dev)1734 int usb_runtime_idle(struct device *dev)
1735 {
1736 	struct usb_device	*udev = to_usb_device(dev);
1737 
1738 	/* An idle USB device can be suspended if it passes the various
1739 	 * autosuspend checks.
1740 	 */
1741 	if (autosuspend_check(udev) == 0)
1742 		pm_runtime_autosuspend(dev);
1743 	return 0;
1744 }
1745 
usb_set_usb2_hardware_lpm(struct usb_device * udev,int enable)1746 int usb_set_usb2_hardware_lpm(struct usb_device *udev, int enable)
1747 {
1748 	struct usb_hcd *hcd = bus_to_hcd(udev->bus);
1749 	int ret = -EPERM;
1750 
1751 	if (hcd->driver->set_usb2_hw_lpm) {
1752 		ret = hcd->driver->set_usb2_hw_lpm(hcd, udev, enable);
1753 		if (!ret)
1754 			udev->usb2_hw_lpm_enabled = enable;
1755 	}
1756 
1757 	return ret;
1758 }
1759 
1760 #endif /* CONFIG_USB_SUSPEND */
1761 
1762 struct bus_type usb_bus_type = {
1763 	.name =		"usb",
1764 	.match =	usb_device_match,
1765 	.uevent =	usb_uevent,
1766 };
1767