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