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