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