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