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