[PATCH] USB: reorg some functions out of the main usb.c file
[firefly-linux-kernel-4.4.55.git] / drivers / usb / core / usb.c
1 /*
2  * drivers/usb/usb.c
3  *
4  * (C) Copyright Linus Torvalds 1999
5  * (C) Copyright Johannes Erdfelt 1999-2001
6  * (C) Copyright Andreas Gal 1999
7  * (C) Copyright Gregory P. Smith 1999
8  * (C) Copyright Deti Fliegl 1999 (new USB architecture)
9  * (C) Copyright Randy Dunlap 2000
10  * (C) Copyright David Brownell 2000-2004
11  * (C) Copyright Yggdrasil Computing, Inc. 2000
12  *     (usb_device_id matching changes by Adam J. Richter)
13  * (C) Copyright Greg Kroah-Hartman 2002-2003
14  *
15  * NOTE! This is not actually a driver at all, rather this is
16  * just a collection of helper routines that implement the
17  * generic USB things that the real drivers can use..
18  *
19  * Think of this as a "USB library" rather than anything else.
20  * It should be considered a slave, with no callbacks. Callbacks
21  * are evil.
22  */
23
24 #include <linux/config.h>
25 #include <linux/module.h>
26 #include <linux/string.h>
27 #include <linux/bitops.h>
28 #include <linux/slab.h>
29 #include <linux/interrupt.h>  /* for in_interrupt() */
30 #include <linux/kmod.h>
31 #include <linux/init.h>
32 #include <linux/spinlock.h>
33 #include <linux/errno.h>
34 #include <linux/smp_lock.h>
35 #include <linux/rwsem.h>
36 #include <linux/usb.h>
37
38 #include <asm/io.h>
39 #include <asm/scatterlist.h>
40 #include <linux/mm.h>
41 #include <linux/dma-mapping.h>
42
43 #include "hcd.h"
44 #include "usb.h"
45
46
47 const char *usbcore_name = "usbcore";
48
49 static int nousb;       /* Disable USB when built into kernel image */
50                         /* Not honored on modular build */
51
52 static DECLARE_RWSEM(usb_all_devices_rwsem);
53
54
55 /**
56  * usb_ifnum_to_if - get the interface object with a given interface number
57  * @dev: the device whose current configuration is considered
58  * @ifnum: the desired interface
59  *
60  * This walks the device descriptor for the currently active configuration
61  * and returns a pointer to the interface with that particular interface
62  * number, or null.
63  *
64  * Note that configuration descriptors are not required to assign interface
65  * numbers sequentially, so that it would be incorrect to assume that
66  * the first interface in that descriptor corresponds to interface zero.
67  * This routine helps device drivers avoid such mistakes.
68  * However, you should make sure that you do the right thing with any
69  * alternate settings available for this interfaces.
70  *
71  * Don't call this function unless you are bound to one of the interfaces
72  * on this device or you have locked the device!
73  */
74 struct usb_interface *usb_ifnum_to_if(struct usb_device *dev, unsigned ifnum)
75 {
76         struct usb_host_config *config = dev->actconfig;
77         int i;
78
79         if (!config)
80                 return NULL;
81         for (i = 0; i < config->desc.bNumInterfaces; i++)
82                 if (config->interface[i]->altsetting[0]
83                                 .desc.bInterfaceNumber == ifnum)
84                         return config->interface[i];
85
86         return NULL;
87 }
88
89 /**
90  * usb_altnum_to_altsetting - get the altsetting structure with a given
91  *      alternate setting number.
92  * @intf: the interface containing the altsetting in question
93  * @altnum: the desired alternate setting number
94  *
95  * This searches the altsetting array of the specified interface for
96  * an entry with the correct bAlternateSetting value and returns a pointer
97  * to that entry, or null.
98  *
99  * Note that altsettings need not be stored sequentially by number, so
100  * it would be incorrect to assume that the first altsetting entry in
101  * the array corresponds to altsetting zero.  This routine helps device
102  * drivers avoid such mistakes.
103  *
104  * Don't call this function unless you are bound to the intf interface
105  * or you have locked the device!
106  */
107 struct usb_host_interface *usb_altnum_to_altsetting(struct usb_interface *intf,
108                 unsigned int altnum)
109 {
110         int i;
111
112         for (i = 0; i < intf->num_altsetting; i++) {
113                 if (intf->altsetting[i].desc.bAlternateSetting == altnum)
114                         return &intf->altsetting[i];
115         }
116         return NULL;
117 }
118
119 /**
120  * usb_driver_claim_interface - bind a driver to an interface
121  * @driver: the driver to be bound
122  * @iface: the interface to which it will be bound; must be in the
123  *      usb device's active configuration
124  * @priv: driver data associated with that interface
125  *
126  * This is used by usb device drivers that need to claim more than one
127  * interface on a device when probing (audio and acm are current examples).
128  * No device driver should directly modify internal usb_interface or
129  * usb_device structure members.
130  *
131  * Few drivers should need to use this routine, since the most natural
132  * way to bind to an interface is to return the private data from
133  * the driver's probe() method.
134  *
135  * Callers must own the device lock and the driver model's usb_bus_type.subsys
136  * writelock.  So driver probe() entries don't need extra locking,
137  * but other call contexts may need to explicitly claim those locks.
138  */
139 int usb_driver_claim_interface(struct usb_driver *driver,
140                                 struct usb_interface *iface, void* priv)
141 {
142         struct device *dev = &iface->dev;
143
144         if (dev->driver)
145                 return -EBUSY;
146
147         dev->driver = &driver->driver;
148         usb_set_intfdata(iface, priv);
149         iface->condition = USB_INTERFACE_BOUND;
150         mark_active(iface);
151
152         /* if interface was already added, bind now; else let
153          * the future device_add() bind it, bypassing probe()
154          */
155         if (device_is_registered(dev))
156                 device_bind_driver(dev);
157
158         return 0;
159 }
160
161 /**
162  * usb_driver_release_interface - unbind a driver from an interface
163  * @driver: the driver to be unbound
164  * @iface: the interface from which it will be unbound
165  *
166  * This can be used by drivers to release an interface without waiting
167  * for their disconnect() methods to be called.  In typical cases this
168  * also causes the driver disconnect() method to be called.
169  *
170  * This call is synchronous, and may not be used in an interrupt context.
171  * Callers must own the device lock and the driver model's usb_bus_type.subsys
172  * writelock.  So driver disconnect() entries don't need extra locking,
173  * but other call contexts may need to explicitly claim those locks.
174  */
175 void usb_driver_release_interface(struct usb_driver *driver,
176                                         struct usb_interface *iface)
177 {
178         struct device *dev = &iface->dev;
179
180         /* this should never happen, don't release something that's not ours */
181         if (!dev->driver || dev->driver != &driver->driver)
182                 return;
183
184         /* don't release from within disconnect() */
185         if (iface->condition != USB_INTERFACE_BOUND)
186                 return;
187
188         /* don't release if the interface hasn't been added yet */
189         if (device_is_registered(dev)) {
190                 iface->condition = USB_INTERFACE_UNBINDING;
191                 device_release_driver(dev);
192         }
193
194         dev->driver = NULL;
195         usb_set_intfdata(iface, NULL);
196         iface->condition = USB_INTERFACE_UNBOUND;
197         mark_quiesced(iface);
198 }
199
200 static int __find_interface(struct device * dev, void * data)
201 {
202         struct usb_interface ** ret = (struct usb_interface **)data;
203         struct usb_interface * intf = *ret;
204         int *minor = (int *)data;
205
206         /* can't look at usb devices, only interfaces */
207         if (dev->driver == &usb_generic_driver)
208                 return 0;
209
210         intf = to_usb_interface(dev);
211         if (intf->minor != -1 && intf->minor == *minor) {
212                 *ret = intf;
213                 return 1;
214         }
215         return 0;
216 }
217
218 /**
219  * usb_find_interface - find usb_interface pointer for driver and device
220  * @drv: the driver whose current configuration is considered
221  * @minor: the minor number of the desired device
222  *
223  * This walks the driver device list and returns a pointer to the interface 
224  * with the matching minor.  Note, this only works for devices that share the
225  * USB major number.
226  */
227 struct usb_interface *usb_find_interface(struct usb_driver *drv, int minor)
228 {
229         struct usb_interface *intf = (struct usb_interface *)(long)minor;
230         int ret;
231
232         ret = driver_for_each_device(&drv->driver, NULL, &intf, __find_interface);
233
234         return ret ? intf : NULL;
235 }
236
237 #ifdef  CONFIG_HOTPLUG
238
239 /*
240  * USB hotplugging invokes what /proc/sys/kernel/hotplug says
241  * (normally /sbin/hotplug) when USB devices get added or removed.
242  *
243  * This invokes a user mode policy agent, typically helping to load driver
244  * or other modules, configure the device, and more.  Drivers can provide
245  * a MODULE_DEVICE_TABLE to help with module loading subtasks.
246  *
247  * We're called either from khubd (the typical case) or from root hub
248  * (init, kapmd, modprobe, rmmod, etc), but the agents need to handle
249  * delays in event delivery.  Use sysfs (and DEVPATH) to make sure the
250  * device (and this configuration!) are still present.
251  */
252 static int usb_hotplug (struct device *dev, char **envp, int num_envp,
253                         char *buffer, int buffer_size)
254 {
255         struct usb_interface *intf;
256         struct usb_device *usb_dev;
257         struct usb_host_interface *alt;
258         int i = 0;
259         int length = 0;
260
261         if (!dev)
262                 return -ENODEV;
263
264         /* driver is often null here; dev_dbg() would oops */
265         pr_debug ("usb %s: hotplug\n", dev->bus_id);
266
267         /* Must check driver_data here, as on remove driver is always NULL */
268         if ((dev->driver == &usb_generic_driver) || 
269             (dev->driver_data == &usb_generic_driver_data))
270                 return 0;
271
272         intf = to_usb_interface(dev);
273         usb_dev = interface_to_usbdev (intf);
274         alt = intf->cur_altsetting;
275
276         if (usb_dev->devnum < 0) {
277                 pr_debug ("usb %s: already deleted?\n", dev->bus_id);
278                 return -ENODEV;
279         }
280         if (!usb_dev->bus) {
281                 pr_debug ("usb %s: bus removed?\n", dev->bus_id);
282                 return -ENODEV;
283         }
284
285 #ifdef  CONFIG_USB_DEVICEFS
286         /* If this is available, userspace programs can directly read
287          * all the device descriptors we don't tell them about.  Or
288          * even act as usermode drivers.
289          *
290          * FIXME reduce hardwired intelligence here
291          */
292         if (add_hotplug_env_var(envp, num_envp, &i,
293                                 buffer, buffer_size, &length,
294                                 "DEVICE=/proc/bus/usb/%03d/%03d",
295                                 usb_dev->bus->busnum, usb_dev->devnum))
296                 return -ENOMEM;
297 #endif
298
299         /* per-device configurations are common */
300         if (add_hotplug_env_var(envp, num_envp, &i,
301                                 buffer, buffer_size, &length,
302                                 "PRODUCT=%x/%x/%x",
303                                 le16_to_cpu(usb_dev->descriptor.idVendor),
304                                 le16_to_cpu(usb_dev->descriptor.idProduct),
305                                 le16_to_cpu(usb_dev->descriptor.bcdDevice)))
306                 return -ENOMEM;
307
308         /* class-based driver binding models */
309         if (add_hotplug_env_var(envp, num_envp, &i,
310                                 buffer, buffer_size, &length,
311                                 "TYPE=%d/%d/%d",
312                                 usb_dev->descriptor.bDeviceClass,
313                                 usb_dev->descriptor.bDeviceSubClass,
314                                 usb_dev->descriptor.bDeviceProtocol))
315                 return -ENOMEM;
316
317         if (add_hotplug_env_var(envp, num_envp, &i,
318                                 buffer, buffer_size, &length,
319                                 "INTERFACE=%d/%d/%d",
320                                 alt->desc.bInterfaceClass,
321                                 alt->desc.bInterfaceSubClass,
322                                 alt->desc.bInterfaceProtocol))
323                 return -ENOMEM;
324
325         if (add_hotplug_env_var(envp, num_envp, &i,
326                                 buffer, buffer_size, &length,
327                                 "MODALIAS=usb:v%04Xp%04Xd%04Xdc%02Xdsc%02Xdp%02Xic%02Xisc%02Xip%02X",
328                                 le16_to_cpu(usb_dev->descriptor.idVendor),
329                                 le16_to_cpu(usb_dev->descriptor.idProduct),
330                                 le16_to_cpu(usb_dev->descriptor.bcdDevice),
331                                 usb_dev->descriptor.bDeviceClass,
332                                 usb_dev->descriptor.bDeviceSubClass,
333                                 usb_dev->descriptor.bDeviceProtocol,
334                                 alt->desc.bInterfaceClass,
335                                 alt->desc.bInterfaceSubClass,
336                                 alt->desc.bInterfaceProtocol))
337                 return -ENOMEM;
338
339         envp[i] = NULL;
340
341         return 0;
342 }
343
344 #else
345
346 static int usb_hotplug (struct device *dev, char **envp,
347                         int num_envp, char *buffer, int buffer_size)
348 {
349         return -ENODEV;
350 }
351
352 #endif  /* CONFIG_HOTPLUG */
353
354 /**
355  * usb_release_dev - free a usb device structure when all users of it are finished.
356  * @dev: device that's been disconnected
357  *
358  * Will be called only by the device core when all users of this usb device are
359  * done.
360  */
361 static void usb_release_dev(struct device *dev)
362 {
363         struct usb_device *udev;
364
365         udev = to_usb_device(dev);
366
367         usb_destroy_configuration(udev);
368         usb_bus_put(udev->bus);
369         kfree(udev->product);
370         kfree(udev->manufacturer);
371         kfree(udev->serial);
372         kfree(udev);
373 }
374
375 /**
376  * usb_alloc_dev - usb device constructor (usbcore-internal)
377  * @parent: hub to which device is connected; null to allocate a root hub
378  * @bus: bus used to access the device
379  * @port1: one-based index of port; ignored for root hubs
380  * Context: !in_interrupt ()
381  *
382  * Only hub drivers (including virtual root hub drivers for host
383  * controllers) should ever call this.
384  *
385  * This call may not be used in a non-sleeping context.
386  */
387 struct usb_device *
388 usb_alloc_dev(struct usb_device *parent, struct usb_bus *bus, unsigned port1)
389 {
390         struct usb_device *dev;
391
392         dev = kzalloc(sizeof(*dev), GFP_KERNEL);
393         if (!dev)
394                 return NULL;
395
396         bus = usb_bus_get(bus);
397         if (!bus) {
398                 kfree(dev);
399                 return NULL;
400         }
401
402         device_initialize(&dev->dev);
403         dev->dev.bus = &usb_bus_type;
404         dev->dev.dma_mask = bus->controller->dma_mask;
405         dev->dev.driver_data = &usb_generic_driver_data;
406         dev->dev.driver = &usb_generic_driver;
407         dev->dev.release = usb_release_dev;
408         dev->state = USB_STATE_ATTACHED;
409
410         INIT_LIST_HEAD(&dev->ep0.urb_list);
411         dev->ep0.desc.bLength = USB_DT_ENDPOINT_SIZE;
412         dev->ep0.desc.bDescriptorType = USB_DT_ENDPOINT;
413         /* ep0 maxpacket comes later, from device descriptor */
414         dev->ep_in[0] = dev->ep_out[0] = &dev->ep0;
415
416         /* Save readable and stable topology id, distinguishing devices
417          * by location for diagnostics, tools, driver model, etc.  The
418          * string is a path along hub ports, from the root.  Each device's
419          * dev->devpath will be stable until USB is re-cabled, and hubs
420          * are often labeled with these port numbers.  The bus_id isn't
421          * as stable:  bus->busnum changes easily from modprobe order,
422          * cardbus or pci hotplugging, and so on.
423          */
424         if (unlikely (!parent)) {
425                 dev->devpath [0] = '0';
426
427                 dev->dev.parent = bus->controller;
428                 sprintf (&dev->dev.bus_id[0], "usb%d", bus->busnum);
429         } else {
430                 /* match any labeling on the hubs; it's one-based */
431                 if (parent->devpath [0] == '0')
432                         snprintf (dev->devpath, sizeof dev->devpath,
433                                 "%d", port1);
434                 else
435                         snprintf (dev->devpath, sizeof dev->devpath,
436                                 "%s.%d", parent->devpath, port1);
437
438                 dev->dev.parent = &parent->dev;
439                 sprintf (&dev->dev.bus_id[0], "%d-%s",
440                         bus->busnum, dev->devpath);
441
442                 /* hub driver sets up TT records */
443         }
444
445         dev->bus = bus;
446         dev->parent = parent;
447         INIT_LIST_HEAD(&dev->filelist);
448
449         init_MUTEX(&dev->serialize);
450
451         return dev;
452 }
453
454 /**
455  * usb_get_dev - increments the reference count of the usb device structure
456  * @dev: the device being referenced
457  *
458  * Each live reference to a device should be refcounted.
459  *
460  * Drivers for USB interfaces should normally record such references in
461  * their probe() methods, when they bind to an interface, and release
462  * them by calling usb_put_dev(), in their disconnect() methods.
463  *
464  * A pointer to the device with the incremented reference counter is returned.
465  */
466 struct usb_device *usb_get_dev(struct usb_device *dev)
467 {
468         if (dev)
469                 get_device(&dev->dev);
470         return dev;
471 }
472
473 /**
474  * usb_put_dev - release a use of the usb device structure
475  * @dev: device that's been disconnected
476  *
477  * Must be called when a user of a device is finished with it.  When the last
478  * user of the device calls this function, the memory of the device is freed.
479  */
480 void usb_put_dev(struct usb_device *dev)
481 {
482         if (dev)
483                 put_device(&dev->dev);
484 }
485
486 /**
487  * usb_get_intf - increments the reference count of the usb interface structure
488  * @intf: the interface being referenced
489  *
490  * Each live reference to a interface must be refcounted.
491  *
492  * Drivers for USB interfaces should normally record such references in
493  * their probe() methods, when they bind to an interface, and release
494  * them by calling usb_put_intf(), in their disconnect() methods.
495  *
496  * A pointer to the interface with the incremented reference counter is
497  * returned.
498  */
499 struct usb_interface *usb_get_intf(struct usb_interface *intf)
500 {
501         if (intf)
502                 get_device(&intf->dev);
503         return intf;
504 }
505
506 /**
507  * usb_put_intf - release a use of the usb interface structure
508  * @intf: interface that's been decremented
509  *
510  * Must be called when a user of an interface is finished with it.  When the
511  * last user of the interface calls this function, the memory of the interface
512  * is freed.
513  */
514 void usb_put_intf(struct usb_interface *intf)
515 {
516         if (intf)
517                 put_device(&intf->dev);
518 }
519
520
521 /*                      USB device locking
522  *
523  * Although locking USB devices should be straightforward, it is
524  * complicated by the way the driver-model core works.  When a new USB
525  * driver is registered or unregistered, the core will automatically
526  * probe or disconnect all matching interfaces on all USB devices while
527  * holding the USB subsystem writelock.  There's no good way for us to
528  * tell which devices will be used or to lock them beforehand; our only
529  * option is to effectively lock all the USB devices.
530  *
531  * We do that by using a private rw-semaphore, usb_all_devices_rwsem.
532  * When locking an individual device you must first acquire the rwsem's
533  * readlock.  When a driver is registered or unregistered the writelock
534  * must be held.  These actions are encapsulated in the subroutines
535  * below, so all a driver needs to do is call usb_lock_device() and
536  * usb_unlock_device().
537  *
538  * Complications arise when several devices are to be locked at the same
539  * time.  Only hub-aware drivers that are part of usbcore ever have to
540  * do this; nobody else needs to worry about it.  The problem is that
541  * usb_lock_device() must not be called to lock a second device since it
542  * would acquire the rwsem's readlock reentrantly, leading to deadlock if
543  * another thread was waiting for the writelock.  The solution is simple:
544  *
545  *      When locking more than one device, call usb_lock_device()
546  *      to lock the first one.  Lock the others by calling
547  *      down(&udev->serialize) directly.
548  *
549  *      When unlocking multiple devices, use up(&udev->serialize)
550  *      to unlock all but the last one.  Unlock the last one by
551  *      calling usb_unlock_device().
552  *
553  *      When locking both a device and its parent, always lock the
554  *      the parent first.
555  */
556
557 /**
558  * usb_lock_device - acquire the lock for a usb device structure
559  * @udev: device that's being locked
560  *
561  * Use this routine when you don't hold any other device locks;
562  * to acquire nested inner locks call down(&udev->serialize) directly.
563  * This is necessary for proper interaction with usb_lock_all_devices().
564  */
565 void usb_lock_device(struct usb_device *udev)
566 {
567         down_read(&usb_all_devices_rwsem);
568         down(&udev->serialize);
569 }
570
571 /**
572  * usb_trylock_device - attempt to acquire the lock for a usb device structure
573  * @udev: device that's being locked
574  *
575  * Don't use this routine if you already hold a device lock;
576  * use down_trylock(&udev->serialize) instead.
577  * This is necessary for proper interaction with usb_lock_all_devices().
578  *
579  * Returns 1 if successful, 0 if contention.
580  */
581 int usb_trylock_device(struct usb_device *udev)
582 {
583         if (!down_read_trylock(&usb_all_devices_rwsem))
584                 return 0;
585         if (down_trylock(&udev->serialize)) {
586                 up_read(&usb_all_devices_rwsem);
587                 return 0;
588         }
589         return 1;
590 }
591
592 /**
593  * usb_lock_device_for_reset - cautiously acquire the lock for a
594  *      usb device structure
595  * @udev: device that's being locked
596  * @iface: interface bound to the driver making the request (optional)
597  *
598  * Attempts to acquire the device lock, but fails if the device is
599  * NOTATTACHED or SUSPENDED, or if iface is specified and the interface
600  * is neither BINDING nor BOUND.  Rather than sleeping to wait for the
601  * lock, the routine polls repeatedly.  This is to prevent deadlock with
602  * disconnect; in some drivers (such as usb-storage) the disconnect()
603  * or suspend() method will block waiting for a device reset to complete.
604  *
605  * Returns a negative error code for failure, otherwise 1 or 0 to indicate
606  * that the device will or will not have to be unlocked.  (0 can be
607  * returned when an interface is given and is BINDING, because in that
608  * case the driver already owns the device lock.)
609  */
610 int usb_lock_device_for_reset(struct usb_device *udev,
611                 struct usb_interface *iface)
612 {
613         unsigned long jiffies_expire = jiffies + HZ;
614
615         if (udev->state == USB_STATE_NOTATTACHED)
616                 return -ENODEV;
617         if (udev->state == USB_STATE_SUSPENDED)
618                 return -EHOSTUNREACH;
619         if (iface) {
620                 switch (iface->condition) {
621                   case USB_INTERFACE_BINDING:
622                         return 0;
623                   case USB_INTERFACE_BOUND:
624                         break;
625                   default:
626                         return -EINTR;
627                 }
628         }
629
630         while (!usb_trylock_device(udev)) {
631
632                 /* If we can't acquire the lock after waiting one second,
633                  * we're probably deadlocked */
634                 if (time_after(jiffies, jiffies_expire))
635                         return -EBUSY;
636
637                 msleep(15);
638                 if (udev->state == USB_STATE_NOTATTACHED)
639                         return -ENODEV;
640                 if (udev->state == USB_STATE_SUSPENDED)
641                         return -EHOSTUNREACH;
642                 if (iface && iface->condition != USB_INTERFACE_BOUND)
643                         return -EINTR;
644         }
645         return 1;
646 }
647
648 /**
649  * usb_unlock_device - release the lock for a usb device structure
650  * @udev: device that's being unlocked
651  *
652  * Use this routine when releasing the only device lock you hold;
653  * to release inner nested locks call up(&udev->serialize) directly.
654  * This is necessary for proper interaction with usb_lock_all_devices().
655  */
656 void usb_unlock_device(struct usb_device *udev)
657 {
658         up(&udev->serialize);
659         up_read(&usb_all_devices_rwsem);
660 }
661
662 /**
663  * usb_lock_all_devices - acquire the lock for all usb device structures
664  *
665  * This is necessary when registering a new driver or probing a bus,
666  * since the driver-model core may try to use any usb_device.
667  */
668 void usb_lock_all_devices(void)
669 {
670         down_write(&usb_all_devices_rwsem);
671 }
672
673 /**
674  * usb_unlock_all_devices - release the lock for all usb device structures
675  */
676 void usb_unlock_all_devices(void)
677 {
678         up_write(&usb_all_devices_rwsem);
679 }
680
681
682 static struct usb_device *match_device(struct usb_device *dev,
683                                        u16 vendor_id, u16 product_id)
684 {
685         struct usb_device *ret_dev = NULL;
686         int child;
687
688         dev_dbg(&dev->dev, "check for vendor %04x, product %04x ...\n",
689             le16_to_cpu(dev->descriptor.idVendor),
690             le16_to_cpu(dev->descriptor.idProduct));
691
692         /* see if this device matches */
693         if ((vendor_id == le16_to_cpu(dev->descriptor.idVendor)) &&
694             (product_id == le16_to_cpu(dev->descriptor.idProduct))) {
695                 dev_dbg (&dev->dev, "matched this device!\n");
696                 ret_dev = usb_get_dev(dev);
697                 goto exit;
698         }
699
700         /* look through all of the children of this device */
701         for (child = 0; child < dev->maxchild; ++child) {
702                 if (dev->children[child]) {
703                         down(&dev->children[child]->serialize);
704                         ret_dev = match_device(dev->children[child],
705                                                vendor_id, product_id);
706                         up(&dev->children[child]->serialize);
707                         if (ret_dev)
708                                 goto exit;
709                 }
710         }
711 exit:
712         return ret_dev;
713 }
714
715 /**
716  * usb_find_device - find a specific usb device in the system
717  * @vendor_id: the vendor id of the device to find
718  * @product_id: the product id of the device to find
719  *
720  * Returns a pointer to a struct usb_device if such a specified usb
721  * device is present in the system currently.  The usage count of the
722  * device will be incremented if a device is found.  Make sure to call
723  * usb_put_dev() when the caller is finished with the device.
724  *
725  * If a device with the specified vendor and product id is not found,
726  * NULL is returned.
727  */
728 struct usb_device *usb_find_device(u16 vendor_id, u16 product_id)
729 {
730         struct list_head *buslist;
731         struct usb_bus *bus;
732         struct usb_device *dev = NULL;
733         
734         down(&usb_bus_list_lock);
735         for (buslist = usb_bus_list.next;
736              buslist != &usb_bus_list; 
737              buslist = buslist->next) {
738                 bus = container_of(buslist, struct usb_bus, bus_list);
739                 if (!bus->root_hub)
740                         continue;
741                 usb_lock_device(bus->root_hub);
742                 dev = match_device(bus->root_hub, vendor_id, product_id);
743                 usb_unlock_device(bus->root_hub);
744                 if (dev)
745                         goto exit;
746         }
747 exit:
748         up(&usb_bus_list_lock);
749         return dev;
750 }
751
752 /**
753  * usb_get_current_frame_number - return current bus frame number
754  * @dev: the device whose bus is being queried
755  *
756  * Returns the current frame number for the USB host controller
757  * used with the given USB device.  This can be used when scheduling
758  * isochronous requests.
759  *
760  * Note that different kinds of host controller have different
761  * "scheduling horizons".  While one type might support scheduling only
762  * 32 frames into the future, others could support scheduling up to
763  * 1024 frames into the future.
764  */
765 int usb_get_current_frame_number(struct usb_device *dev)
766 {
767         return dev->bus->op->get_frame_number (dev);
768 }
769
770 /*-------------------------------------------------------------------*/
771 /*
772  * __usb_get_extra_descriptor() finds a descriptor of specific type in the
773  * extra field of the interface and endpoint descriptor structs.
774  */
775
776 int __usb_get_extra_descriptor(char *buffer, unsigned size,
777         unsigned char type, void **ptr)
778 {
779         struct usb_descriptor_header *header;
780
781         while (size >= sizeof(struct usb_descriptor_header)) {
782                 header = (struct usb_descriptor_header *)buffer;
783
784                 if (header->bLength < 2) {
785                         printk(KERN_ERR
786                                 "%s: bogus descriptor, type %d length %d\n",
787                                 usbcore_name,
788                                 header->bDescriptorType, 
789                                 header->bLength);
790                         return -1;
791                 }
792
793                 if (header->bDescriptorType == type) {
794                         *ptr = header;
795                         return 0;
796                 }
797
798                 buffer += header->bLength;
799                 size -= header->bLength;
800         }
801         return -1;
802 }
803
804 /**
805  * usb_buffer_alloc - allocate dma-consistent buffer for URB_NO_xxx_DMA_MAP
806  * @dev: device the buffer will be used with
807  * @size: requested buffer size
808  * @mem_flags: affect whether allocation may block
809  * @dma: used to return DMA address of buffer
810  *
811  * Return value is either null (indicating no buffer could be allocated), or
812  * the cpu-space pointer to a buffer that may be used to perform DMA to the
813  * specified device.  Such cpu-space buffers are returned along with the DMA
814  * address (through the pointer provided).
815  *
816  * These buffers are used with URB_NO_xxx_DMA_MAP set in urb->transfer_flags
817  * to avoid behaviors like using "DMA bounce buffers", or tying down I/O
818  * mapping hardware for long idle periods.  The implementation varies between
819  * platforms, depending on details of how DMA will work to this device.
820  * Using these buffers also helps prevent cacheline sharing problems on
821  * architectures where CPU caches are not DMA-coherent.
822  *
823  * When the buffer is no longer used, free it with usb_buffer_free().
824  */
825 void *usb_buffer_alloc (
826         struct usb_device *dev,
827         size_t size,
828         gfp_t mem_flags,
829         dma_addr_t *dma
830 )
831 {
832         if (!dev || !dev->bus || !dev->bus->op || !dev->bus->op->buffer_alloc)
833                 return NULL;
834         return dev->bus->op->buffer_alloc (dev->bus, size, mem_flags, dma);
835 }
836
837 /**
838  * usb_buffer_free - free memory allocated with usb_buffer_alloc()
839  * @dev: device the buffer was used with
840  * @size: requested buffer size
841  * @addr: CPU address of buffer
842  * @dma: DMA address of buffer
843  *
844  * This reclaims an I/O buffer, letting it be reused.  The memory must have
845  * been allocated using usb_buffer_alloc(), and the parameters must match
846  * those provided in that allocation request. 
847  */
848 void usb_buffer_free (
849         struct usb_device *dev,
850         size_t size,
851         void *addr,
852         dma_addr_t dma
853 )
854 {
855         if (!dev || !dev->bus || !dev->bus->op || !dev->bus->op->buffer_free)
856                 return;
857         dev->bus->op->buffer_free (dev->bus, size, addr, dma);
858 }
859
860 /**
861  * usb_buffer_map - create DMA mapping(s) for an urb
862  * @urb: urb whose transfer_buffer/setup_packet will be mapped
863  *
864  * Return value is either null (indicating no buffer could be mapped), or
865  * the parameter.  URB_NO_TRANSFER_DMA_MAP and URB_NO_SETUP_DMA_MAP are
866  * added to urb->transfer_flags if the operation succeeds.  If the device
867  * is connected to this system through a non-DMA controller, this operation
868  * always succeeds.
869  *
870  * This call would normally be used for an urb which is reused, perhaps
871  * as the target of a large periodic transfer, with usb_buffer_dmasync()
872  * calls to synchronize memory and dma state.
873  *
874  * Reverse the effect of this call with usb_buffer_unmap().
875  */
876 #if 0
877 struct urb *usb_buffer_map (struct urb *urb)
878 {
879         struct usb_bus          *bus;
880         struct device           *controller;
881
882         if (!urb
883                         || !urb->dev
884                         || !(bus = urb->dev->bus)
885                         || !(controller = bus->controller))
886                 return NULL;
887
888         if (controller->dma_mask) {
889                 urb->transfer_dma = dma_map_single (controller,
890                         urb->transfer_buffer, urb->transfer_buffer_length,
891                         usb_pipein (urb->pipe)
892                                 ? DMA_FROM_DEVICE : DMA_TO_DEVICE);
893                 if (usb_pipecontrol (urb->pipe))
894                         urb->setup_dma = dma_map_single (controller,
895                                         urb->setup_packet,
896                                         sizeof (struct usb_ctrlrequest),
897                                         DMA_TO_DEVICE);
898         // FIXME generic api broken like pci, can't report errors
899         // if (urb->transfer_dma == DMA_ADDR_INVALID) return 0;
900         } else
901                 urb->transfer_dma = ~0;
902         urb->transfer_flags |= (URB_NO_TRANSFER_DMA_MAP
903                                 | URB_NO_SETUP_DMA_MAP);
904         return urb;
905 }
906 #endif  /*  0  */
907
908 /* XXX DISABLED, no users currently.  If you wish to re-enable this
909  * XXX please determine whether the sync is to transfer ownership of
910  * XXX the buffer from device to cpu or vice verse, and thusly use the
911  * XXX appropriate _for_{cpu,device}() method.  -DaveM
912  */
913 #if 0
914
915 /**
916  * usb_buffer_dmasync - synchronize DMA and CPU view of buffer(s)
917  * @urb: urb whose transfer_buffer/setup_packet will be synchronized
918  */
919 void usb_buffer_dmasync (struct urb *urb)
920 {
921         struct usb_bus          *bus;
922         struct device           *controller;
923
924         if (!urb
925                         || !(urb->transfer_flags & URB_NO_TRANSFER_DMA_MAP)
926                         || !urb->dev
927                         || !(bus = urb->dev->bus)
928                         || !(controller = bus->controller))
929                 return;
930
931         if (controller->dma_mask) {
932                 dma_sync_single (controller,
933                         urb->transfer_dma, urb->transfer_buffer_length,
934                         usb_pipein (urb->pipe)
935                                 ? DMA_FROM_DEVICE : DMA_TO_DEVICE);
936                 if (usb_pipecontrol (urb->pipe))
937                         dma_sync_single (controller,
938                                         urb->setup_dma,
939                                         sizeof (struct usb_ctrlrequest),
940                                         DMA_TO_DEVICE);
941         }
942 }
943 #endif
944
945 /**
946  * usb_buffer_unmap - free DMA mapping(s) for an urb
947  * @urb: urb whose transfer_buffer will be unmapped
948  *
949  * Reverses the effect of usb_buffer_map().
950  */
951 #if 0
952 void usb_buffer_unmap (struct urb *urb)
953 {
954         struct usb_bus          *bus;
955         struct device           *controller;
956
957         if (!urb
958                         || !(urb->transfer_flags & URB_NO_TRANSFER_DMA_MAP)
959                         || !urb->dev
960                         || !(bus = urb->dev->bus)
961                         || !(controller = bus->controller))
962                 return;
963
964         if (controller->dma_mask) {
965                 dma_unmap_single (controller,
966                         urb->transfer_dma, urb->transfer_buffer_length,
967                         usb_pipein (urb->pipe)
968                                 ? DMA_FROM_DEVICE : DMA_TO_DEVICE);
969                 if (usb_pipecontrol (urb->pipe))
970                         dma_unmap_single (controller,
971                                         urb->setup_dma,
972                                         sizeof (struct usb_ctrlrequest),
973                                         DMA_TO_DEVICE);
974         }
975         urb->transfer_flags &= ~(URB_NO_TRANSFER_DMA_MAP
976                                 | URB_NO_SETUP_DMA_MAP);
977 }
978 #endif  /*  0  */
979
980 /**
981  * usb_buffer_map_sg - create scatterlist DMA mapping(s) for an endpoint
982  * @dev: device to which the scatterlist will be mapped
983  * @pipe: endpoint defining the mapping direction
984  * @sg: the scatterlist to map
985  * @nents: the number of entries in the scatterlist
986  *
987  * Return value is either < 0 (indicating no buffers could be mapped), or
988  * the number of DMA mapping array entries in the scatterlist.
989  *
990  * The caller is responsible for placing the resulting DMA addresses from
991  * the scatterlist into URB transfer buffer pointers, and for setting the
992  * URB_NO_TRANSFER_DMA_MAP transfer flag in each of those URBs.
993  *
994  * Top I/O rates come from queuing URBs, instead of waiting for each one
995  * to complete before starting the next I/O.   This is particularly easy
996  * to do with scatterlists.  Just allocate and submit one URB for each DMA
997  * mapping entry returned, stopping on the first error or when all succeed.
998  * Better yet, use the usb_sg_*() calls, which do that (and more) for you.
999  *
1000  * This call would normally be used when translating scatterlist requests,
1001  * rather than usb_buffer_map(), since on some hardware (with IOMMUs) it
1002  * may be able to coalesce mappings for improved I/O efficiency.
1003  *
1004  * Reverse the effect of this call with usb_buffer_unmap_sg().
1005  */
1006 int usb_buffer_map_sg (struct usb_device *dev, unsigned pipe,
1007                 struct scatterlist *sg, int nents)
1008 {
1009         struct usb_bus          *bus;
1010         struct device           *controller;
1011
1012         if (!dev
1013                         || usb_pipecontrol (pipe)
1014                         || !(bus = dev->bus)
1015                         || !(controller = bus->controller)
1016                         || !controller->dma_mask)
1017                 return -1;
1018
1019         // FIXME generic api broken like pci, can't report errors
1020         return dma_map_sg (controller, sg, nents,
1021                         usb_pipein (pipe) ? DMA_FROM_DEVICE : DMA_TO_DEVICE);
1022 }
1023
1024 /* XXX DISABLED, no users currently.  If you wish to re-enable this
1025  * XXX please determine whether the sync is to transfer ownership of
1026  * XXX the buffer from device to cpu or vice verse, and thusly use the
1027  * XXX appropriate _for_{cpu,device}() method.  -DaveM
1028  */
1029 #if 0
1030
1031 /**
1032  * usb_buffer_dmasync_sg - synchronize DMA and CPU view of scatterlist buffer(s)
1033  * @dev: device to which the scatterlist will be mapped
1034  * @pipe: endpoint defining the mapping direction
1035  * @sg: the scatterlist to synchronize
1036  * @n_hw_ents: the positive return value from usb_buffer_map_sg
1037  *
1038  * Use this when you are re-using a scatterlist's data buffers for
1039  * another USB request.
1040  */
1041 void usb_buffer_dmasync_sg (struct usb_device *dev, unsigned pipe,
1042                 struct scatterlist *sg, int n_hw_ents)
1043 {
1044         struct usb_bus          *bus;
1045         struct device           *controller;
1046
1047         if (!dev
1048                         || !(bus = dev->bus)
1049                         || !(controller = bus->controller)
1050                         || !controller->dma_mask)
1051                 return;
1052
1053         dma_sync_sg (controller, sg, n_hw_ents,
1054                         usb_pipein (pipe) ? DMA_FROM_DEVICE : DMA_TO_DEVICE);
1055 }
1056 #endif
1057
1058 /**
1059  * usb_buffer_unmap_sg - free DMA mapping(s) for a scatterlist
1060  * @dev: device to which the scatterlist will be mapped
1061  * @pipe: endpoint defining the mapping direction
1062  * @sg: the scatterlist to unmap
1063  * @n_hw_ents: the positive return value from usb_buffer_map_sg
1064  *
1065  * Reverses the effect of usb_buffer_map_sg().
1066  */
1067 void usb_buffer_unmap_sg (struct usb_device *dev, unsigned pipe,
1068                 struct scatterlist *sg, int n_hw_ents)
1069 {
1070         struct usb_bus          *bus;
1071         struct device           *controller;
1072
1073         if (!dev
1074                         || !(bus = dev->bus)
1075                         || !(controller = bus->controller)
1076                         || !controller->dma_mask)
1077                 return;
1078
1079         dma_unmap_sg (controller, sg, n_hw_ents,
1080                         usb_pipein (pipe) ? DMA_FROM_DEVICE : DMA_TO_DEVICE);
1081 }
1082
1083 static int verify_suspended(struct device *dev, void *unused)
1084 {
1085         return (dev->power.power_state.event == PM_EVENT_ON) ? -EBUSY : 0;
1086 }
1087
1088 static int usb_generic_suspend(struct device *dev, pm_message_t message)
1089 {
1090         struct usb_interface    *intf;
1091         struct usb_driver       *driver;
1092         int                     status;
1093
1094         /* USB devices enter SUSPEND state through their hubs, but can be
1095          * marked for FREEZE as soon as their children are already idled.
1096          * But those semantics are useless, so we equate the two (sigh).
1097          */
1098         if (dev->driver == &usb_generic_driver) {
1099                 if (dev->power.power_state.event == message.event)
1100                         return 0;
1101                 /* we need to rule out bogus requests through sysfs */
1102                 status = device_for_each_child(dev, NULL, verify_suspended);
1103                 if (status)
1104                         return status;
1105                 return usb_suspend_device (to_usb_device(dev));
1106         }
1107
1108         if ((dev->driver == NULL) ||
1109             (dev->driver_data == &usb_generic_driver_data))
1110                 return 0;
1111
1112         intf = to_usb_interface(dev);
1113         driver = to_usb_driver(dev->driver);
1114
1115         /* with no hardware, USB interfaces only use FREEZE and ON states */
1116         if (!is_active(intf))
1117                 return 0;
1118
1119         if (driver->suspend && driver->resume) {
1120                 status = driver->suspend(intf, message);
1121                 if (status)
1122                         dev_err(dev, "%s error %d\n", "suspend", status);
1123                 else
1124                         mark_quiesced(intf);
1125         } else {
1126                 // FIXME else if there's no suspend method, disconnect...
1127                 dev_warn(dev, "no suspend for driver %s?\n", driver->name);
1128                 mark_quiesced(intf);
1129                 status = 0;
1130         }
1131         return status;
1132 }
1133
1134 static int usb_generic_resume(struct device *dev)
1135 {
1136         struct usb_interface    *intf;
1137         struct usb_driver       *driver;
1138         struct usb_device       *udev;
1139         int                     status;
1140
1141         if (dev->power.power_state.event == PM_EVENT_ON)
1142                 return 0;
1143
1144         /* mark things as "on" immediately, no matter what errors crop up */
1145         dev->power.power_state.event = PM_EVENT_ON;
1146
1147         /* devices resume through their hubs */
1148         if (dev->driver == &usb_generic_driver) {
1149                 udev = to_usb_device(dev);
1150                 if (udev->state == USB_STATE_NOTATTACHED)
1151                         return 0;
1152                 return usb_resume_device (to_usb_device(dev));
1153         }
1154
1155         if ((dev->driver == NULL) ||
1156             (dev->driver_data == &usb_generic_driver_data)) {
1157                 dev->power.power_state.event = PM_EVENT_FREEZE;
1158                 return 0;
1159         }
1160
1161         intf = to_usb_interface(dev);
1162         driver = to_usb_driver(dev->driver);
1163
1164         udev = interface_to_usbdev(intf);
1165         if (udev->state == USB_STATE_NOTATTACHED)
1166                 return 0;
1167
1168         /* if driver was suspended, it has a resume method;
1169          * however, sysfs can wrongly mark things as suspended
1170          * (on the "no suspend method" FIXME path above)
1171          */
1172         if (driver->resume) {
1173                 status = driver->resume(intf);
1174                 if (status) {
1175                         dev_err(dev, "%s error %d\n", "resume", status);
1176                         mark_quiesced(intf);
1177                 }
1178         } else
1179                 dev_warn(dev, "no resume for driver %s?\n", driver->name);
1180         return 0;
1181 }
1182
1183 struct bus_type usb_bus_type = {
1184         .name =         "usb",
1185         .match =        usb_device_match,
1186         .hotplug =      usb_hotplug,
1187         .suspend =      usb_generic_suspend,
1188         .resume =       usb_generic_resume,
1189 };
1190
1191 #ifndef MODULE
1192
1193 static int __init usb_setup_disable(char *str)
1194 {
1195         nousb = 1;
1196         return 1;
1197 }
1198
1199 /* format to disable USB on kernel command line is: nousb */
1200 __setup("nousb", usb_setup_disable);
1201
1202 #endif
1203
1204 /*
1205  * for external read access to <nousb>
1206  */
1207 int usb_disabled(void)
1208 {
1209         return nousb;
1210 }
1211
1212 /*
1213  * Init
1214  */
1215 static int __init usb_init(void)
1216 {
1217         int retval;
1218         if (nousb) {
1219                 pr_info ("%s: USB support disabled\n", usbcore_name);
1220                 return 0;
1221         }
1222
1223         retval = bus_register(&usb_bus_type);
1224         if (retval) 
1225                 goto out;
1226         retval = usb_host_init();
1227         if (retval)
1228                 goto host_init_failed;
1229         retval = usb_major_init();
1230         if (retval)
1231                 goto major_init_failed;
1232         retval = usb_register(&usbfs_driver);
1233         if (retval)
1234                 goto driver_register_failed;
1235         retval = usbdev_init();
1236         if (retval)
1237                 goto usbdevice_init_failed;
1238         retval = usbfs_init();
1239         if (retval)
1240                 goto fs_init_failed;
1241         retval = usb_hub_init();
1242         if (retval)
1243                 goto hub_init_failed;
1244         retval = driver_register(&usb_generic_driver);
1245         if (!retval)
1246                 goto out;
1247
1248         usb_hub_cleanup();
1249 hub_init_failed:
1250         usbfs_cleanup();
1251 fs_init_failed:
1252         usbdev_cleanup();
1253 usbdevice_init_failed:
1254         usb_deregister(&usbfs_driver);
1255 driver_register_failed:
1256         usb_major_cleanup();
1257 major_init_failed:
1258         usb_host_cleanup();
1259 host_init_failed:
1260         bus_unregister(&usb_bus_type);
1261 out:
1262         return retval;
1263 }
1264
1265 /*
1266  * Cleanup
1267  */
1268 static void __exit usb_exit(void)
1269 {
1270         /* This will matter if shutdown/reboot does exitcalls. */
1271         if (nousb)
1272                 return;
1273
1274         driver_unregister(&usb_generic_driver);
1275         usb_major_cleanup();
1276         usbfs_cleanup();
1277         usb_deregister(&usbfs_driver);
1278         usbdev_cleanup();
1279         usb_hub_cleanup();
1280         usb_host_cleanup();
1281         bus_unregister(&usb_bus_type);
1282 }
1283
1284 subsys_initcall(usb_init);
1285 module_exit(usb_exit);
1286
1287 /*
1288  * USB may be built into the kernel or be built as modules.
1289  * These symbols are exported for device (or host controller)
1290  * driver modules to use.
1291  */
1292
1293 EXPORT_SYMBOL(usb_disabled);
1294
1295 EXPORT_SYMBOL_GPL(usb_get_intf);
1296 EXPORT_SYMBOL_GPL(usb_put_intf);
1297
1298 EXPORT_SYMBOL(usb_alloc_dev);
1299 EXPORT_SYMBOL(usb_put_dev);
1300 EXPORT_SYMBOL(usb_get_dev);
1301 EXPORT_SYMBOL(usb_hub_tt_clear_buffer);
1302
1303 EXPORT_SYMBOL(usb_lock_device);
1304 EXPORT_SYMBOL(usb_trylock_device);
1305 EXPORT_SYMBOL(usb_lock_device_for_reset);
1306 EXPORT_SYMBOL(usb_unlock_device);
1307
1308 EXPORT_SYMBOL(usb_driver_claim_interface);
1309 EXPORT_SYMBOL(usb_driver_release_interface);
1310 EXPORT_SYMBOL(usb_find_interface);
1311 EXPORT_SYMBOL(usb_ifnum_to_if);
1312 EXPORT_SYMBOL(usb_altnum_to_altsetting);
1313
1314 EXPORT_SYMBOL(usb_reset_device);
1315 EXPORT_SYMBOL(usb_disconnect);
1316
1317 EXPORT_SYMBOL(__usb_get_extra_descriptor);
1318
1319 EXPORT_SYMBOL(usb_find_device);
1320 EXPORT_SYMBOL(usb_get_current_frame_number);
1321
1322 EXPORT_SYMBOL (usb_buffer_alloc);
1323 EXPORT_SYMBOL (usb_buffer_free);
1324
1325 #if 0
1326 EXPORT_SYMBOL (usb_buffer_map);
1327 EXPORT_SYMBOL (usb_buffer_dmasync);
1328 EXPORT_SYMBOL (usb_buffer_unmap);
1329 #endif
1330
1331 EXPORT_SYMBOL (usb_buffer_map_sg);
1332 #if 0
1333 EXPORT_SYMBOL (usb_buffer_dmasync_sg);
1334 #endif
1335 EXPORT_SYMBOL (usb_buffer_unmap_sg);
1336
1337 MODULE_LICENSE("GPL");