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