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