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