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