ftp://ftp.kernel.org/pub/linux/kernel/v2.6/linux-2.6.6.tar.bz2
[linux-2.6.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
26 #ifdef CONFIG_USB_DEBUG
27         #define DEBUG
28 #else
29         #undef DEBUG
30 #endif
31
32 #include <linux/module.h>
33 #include <linux/string.h>
34 #include <linux/bitops.h>
35 #include <linux/slab.h>
36 #include <linux/interrupt.h>  /* for in_interrupt() */
37 #include <linux/kmod.h>
38 #include <linux/init.h>
39 #include <linux/spinlock.h>
40 #include <linux/errno.h>
41 #include <linux/smp_lock.h>
42 #include <linux/usb.h>
43
44 #include <asm/io.h>
45 #include <asm/scatterlist.h>
46 #include <linux/mm.h>
47 #include <linux/dma-mapping.h>
48
49 #include "hcd.h"
50 #include "usb.h"
51
52 extern int  usb_hub_init(void);
53 extern void usb_hub_cleanup(void);
54 extern int usb_major_init(void);
55 extern void usb_major_cleanup(void);
56 extern int usb_host_init(void);
57 extern void usb_host_cleanup(void);
58
59
60 const char *usbcore_name = "usbcore";
61
62 int nousb;              /* Disable USB when built into kernel image */
63                         /* Not honored on modular build */
64
65
66 static int generic_probe (struct device *dev)
67 {
68         return 0;
69 }
70 static int generic_remove (struct device *dev)
71 {
72         return 0;
73 }
74
75 static struct device_driver usb_generic_driver = {
76         .name = "usb",
77         .bus = &usb_bus_type,
78         .probe = generic_probe,
79         .remove = generic_remove,
80 };
81
82 static int usb_generic_driver_data;
83
84 /* called from driver core with usb_bus_type.subsys writelock */
85 int usb_probe_interface(struct device *dev)
86 {
87         struct usb_interface * intf = to_usb_interface(dev);
88         struct usb_driver * driver = to_usb_driver(dev->driver);
89         const struct usb_device_id *id;
90         int error = -ENODEV;
91
92         dev_dbg(dev, "%s\n", __FUNCTION__);
93
94         if (!driver->probe)
95                 return error;
96
97         id = usb_match_id (intf, driver->id_table);
98         if (id) {
99                 dev_dbg (dev, "%s - got id\n", __FUNCTION__);
100                 error = driver->probe (intf, id);
101         }
102
103         return error;
104 }
105
106 /* called from driver core with usb_bus_type.subsys writelock */
107 int usb_unbind_interface(struct device *dev)
108 {
109         struct usb_interface *intf = to_usb_interface(dev);
110         struct usb_driver *driver = to_usb_driver(intf->dev.driver);
111
112         /* release all urbs for this interface */
113         usb_disable_interface(interface_to_usbdev(intf), intf);
114
115         if (driver && driver->disconnect)
116                 driver->disconnect(intf);
117
118         /* reset other interface state */
119         usb_set_interface(interface_to_usbdev(intf),
120                         intf->altsetting[0].desc.bInterfaceNumber,
121                         0);
122         usb_set_intfdata(intf, NULL);
123
124         return 0;
125 }
126
127 /**
128  * usb_register - register a USB driver
129  * @new_driver: USB operations for the driver
130  *
131  * Registers a USB driver with the USB core.  The list of unattached
132  * interfaces will be rescanned whenever a new driver is added, allowing
133  * the new driver to attach to any recognized devices.
134  * Returns a negative error code on failure and 0 on success.
135  * 
136  * NOTE: if you want your driver to use the USB major number, you must call
137  * usb_register_dev() to enable that functionality.  This function no longer
138  * takes care of that.
139  */
140 int usb_register(struct usb_driver *new_driver)
141 {
142         int retval = 0;
143
144         if (nousb)
145                 return -ENODEV;
146
147         new_driver->driver.name = (char *)new_driver->name;
148         new_driver->driver.bus = &usb_bus_type;
149         new_driver->driver.probe = usb_probe_interface;
150         new_driver->driver.remove = usb_unbind_interface;
151
152         retval = driver_register(&new_driver->driver);
153
154         if (!retval) {
155                 pr_info("%s: registered new driver %s\n",
156                         usbcore_name, new_driver->name);
157                 usbfs_update_special();
158         } else {
159                 printk(KERN_ERR "%s: error %d registering driver %s\n",
160                         usbcore_name, retval, new_driver->name);
161         }
162
163         return retval;
164 }
165
166 /**
167  * usb_deregister - unregister a USB driver
168  * @driver: USB operations of the driver to unregister
169  * Context: must be able to sleep
170  *
171  * Unlinks the specified driver from the internal USB driver list.
172  * 
173  * NOTE: If you called usb_register_dev(), you still need to call
174  * usb_deregister_dev() to clean up your driver's allocated minor numbers,
175  * this * call will no longer do it for you.
176  */
177 void usb_deregister(struct usb_driver *driver)
178 {
179         pr_info("%s: deregistering driver %s\n", usbcore_name, driver->name);
180
181         driver_unregister (&driver->driver);
182
183         usbfs_update_special();
184 }
185
186 /**
187  * usb_ifnum_to_if - get the interface object with a given interface number
188  * @dev: the device whose current configuration is considered
189  * @ifnum: the desired interface
190  *
191  * This walks the device descriptor for the currently active configuration
192  * and returns a pointer to the interface with that particular interface
193  * number, or null.
194  *
195  * Note that configuration descriptors are not required to assign interface
196  * numbers sequentially, so that it would be incorrect to assume that
197  * the first interface in that descriptor corresponds to interface zero.
198  * This routine helps device drivers avoid such mistakes.
199  * However, you should make sure that you do the right thing with any
200  * alternate settings available for this interfaces.
201  */
202 struct usb_interface *usb_ifnum_to_if(struct usb_device *dev, unsigned ifnum)
203 {
204         struct usb_host_config *config = dev->actconfig;
205         int i;
206
207         if (!config)
208                 return NULL;
209         for (i = 0; i < config->desc.bNumInterfaces; i++)
210                 if (config->interface[i]->altsetting[0]
211                                 .desc.bInterfaceNumber == ifnum)
212                         return config->interface[i];
213
214         return NULL;
215 }
216
217 /**
218  * usb_altnum_to_altsetting - get the altsetting structure with a given
219  *      alternate setting number.
220  * @intf: the interface containing the altsetting in question
221  * @altnum: the desired alternate setting number
222  *
223  * This searches the altsetting array of the specified interface for
224  * an entry with the correct bAlternateSetting value and returns a pointer
225  * to that entry, or null.
226  *
227  * Note that altsettings need not be stored sequentially by number, so
228  * it would be incorrect to assume that the first altsetting entry in
229  * the array corresponds to altsetting zero.  This routine helps device
230  * drivers avoid such mistakes.
231  */
232 struct usb_host_interface *usb_altnum_to_altsetting(struct usb_interface *intf,
233                 unsigned int altnum)
234 {
235         int i;
236
237         for (i = 0; i < intf->num_altsetting; i++) {
238                 if (intf->altsetting[i].desc.bAlternateSetting == altnum)
239                         return &intf->altsetting[i];
240         }
241         return NULL;
242 }
243
244 /**
245  * usb_epnum_to_ep_desc - get the endpoint object with a given endpoint number
246  * @dev: the device whose current configuration+altsettings is considered
247  * @epnum: the desired endpoint, masked with USB_DIR_IN as appropriate.
248  *
249  * This walks the device descriptor for the currently active configuration,
250  * and returns a pointer to the endpoint with that particular endpoint
251  * number, or null.
252  *
253  * Note that interface descriptors are not required to list endpoint
254  * numbers in any standardized order, so that it would be wrong to
255  * assume that ep2in precedes either ep5in, ep2out, or even ep1out.
256  * This routine helps device drivers avoid such mistakes.
257  */
258 struct usb_endpoint_descriptor *
259 usb_epnum_to_ep_desc(struct usb_device *dev, unsigned epnum)
260 {
261         struct usb_host_config *config = dev->actconfig;
262         int i, k;
263
264         if (!config)
265                 return NULL;
266         for (i = 0; i < config->desc.bNumInterfaces; i++) {
267                 struct usb_interface            *intf;
268                 struct usb_host_interface       *alt;
269
270                 /* only endpoints in current altsetting are active */
271                 intf = config->interface[i];
272                 alt = intf->cur_altsetting;
273
274                 for (k = 0; k < alt->desc.bNumEndpoints; k++)
275                         if (epnum == alt->endpoint[k].desc.bEndpointAddress)
276                                 return &alt->endpoint[k].desc;
277         }
278
279         return NULL;
280 }
281
282 /**
283  * usb_driver_claim_interface - bind a driver to an interface
284  * @driver: the driver to be bound
285  * @iface: the interface to which it will be bound; must be in the
286  *      usb device's active configuration
287  * @priv: driver data associated with that interface
288  *
289  * This is used by usb device drivers that need to claim more than one
290  * interface on a device when probing (audio and acm are current examples).
291  * No device driver should directly modify internal usb_interface or
292  * usb_device structure members.
293  *
294  * Few drivers should need to use this routine, since the most natural
295  * way to bind to an interface is to return the private data from
296  * the driver's probe() method.
297  *
298  * Callers must own the driver model's usb bus writelock.  So driver
299  * probe() entries don't need extra locking, but other call contexts
300  * may need to explicitly claim that lock.
301  */
302 int usb_driver_claim_interface(struct usb_driver *driver, struct usb_interface *iface, void* priv)
303 {
304         struct device *dev = &iface->dev;
305
306         if (dev->driver)
307                 return -EBUSY;
308
309         dev->driver = &driver->driver;
310         usb_set_intfdata(iface, priv);
311
312         /* if interface was already added, bind now; else let
313          * the future device_add() bind it, bypassing probe()
314          */
315         if (!list_empty (&dev->bus_list))
316                 device_bind_driver(dev);
317
318         return 0;
319 }
320
321 /**
322  * usb_driver_release_interface - unbind a driver from an interface
323  * @driver: the driver to be unbound
324  * @iface: the interface from which it will be unbound
325  *
326  * This can be used by drivers to release an interface without waiting
327  * for their disconnect() methods to be called.  In typical cases this
328  * also causes the driver disconnect() method to be called.
329  *
330  * This call is synchronous, and may not be used in an interrupt context.
331  * Callers must own the usb_device serialize semaphore and the driver model's
332  * usb bus writelock.  So driver disconnect() entries don't need extra locking,
333  * but other call contexts may need to explicitly claim those locks.
334  */
335 void usb_driver_release_interface(struct usb_driver *driver,
336                                         struct usb_interface *iface)
337 {
338         struct device *dev = &iface->dev;
339
340         /* this should never happen, don't release something that's not ours */
341         if (!dev->driver || dev->driver != &driver->driver)
342                 return;
343
344         /* don't disconnect from disconnect(), or before dev_add() */
345         if (!list_empty (&dev->driver_list) && !list_empty (&dev->bus_list))
346                 device_release_driver(dev);
347
348         dev->driver = NULL;
349         usb_set_intfdata(iface, NULL);
350 }
351
352 /**
353  * usb_match_id - find first usb_device_id matching device or interface
354  * @interface: the interface of interest
355  * @id: array of usb_device_id structures, terminated by zero entry
356  *
357  * usb_match_id searches an array of usb_device_id's and returns
358  * the first one matching the device or interface, or null.
359  * This is used when binding (or rebinding) a driver to an interface.
360  * Most USB device drivers will use this indirectly, through the usb core,
361  * but some layered driver frameworks use it directly.
362  * These device tables are exported with MODULE_DEVICE_TABLE, through
363  * modutils and "modules.usbmap", to support the driver loading
364  * functionality of USB hotplugging.
365  *
366  * What Matches:
367  *
368  * The "match_flags" element in a usb_device_id controls which
369  * members are used.  If the corresponding bit is set, the
370  * value in the device_id must match its corresponding member
371  * in the device or interface descriptor, or else the device_id
372  * does not match.
373  *
374  * "driver_info" is normally used only by device drivers,
375  * but you can create a wildcard "matches anything" usb_device_id
376  * as a driver's "modules.usbmap" entry if you provide an id with
377  * only a nonzero "driver_info" field.  If you do this, the USB device
378  * driver's probe() routine should use additional intelligence to
379  * decide whether to bind to the specified interface.
380  * 
381  * What Makes Good usb_device_id Tables:
382  *
383  * The match algorithm is very simple, so that intelligence in
384  * driver selection must come from smart driver id records.
385  * Unless you have good reasons to use another selection policy,
386  * provide match elements only in related groups, and order match
387  * specifiers from specific to general.  Use the macros provided
388  * for that purpose if you can.
389  *
390  * The most specific match specifiers use device descriptor
391  * data.  These are commonly used with product-specific matches;
392  * the USB_DEVICE macro lets you provide vendor and product IDs,
393  * and you can also match against ranges of product revisions.
394  * These are widely used for devices with application or vendor
395  * specific bDeviceClass values.
396  *
397  * Matches based on device class/subclass/protocol specifications
398  * are slightly more general; use the USB_DEVICE_INFO macro, or
399  * its siblings.  These are used with single-function devices
400  * where bDeviceClass doesn't specify that each interface has
401  * its own class. 
402  *
403  * Matches based on interface class/subclass/protocol are the
404  * most general; they let drivers bind to any interface on a
405  * multiple-function device.  Use the USB_INTERFACE_INFO
406  * macro, or its siblings, to match class-per-interface style 
407  * devices (as recorded in bDeviceClass).
408  *  
409  * Within those groups, remember that not all combinations are
410  * meaningful.  For example, don't give a product version range
411  * without vendor and product IDs; or specify a protocol without
412  * its associated class and subclass.
413  */   
414 const struct usb_device_id *
415 usb_match_id(struct usb_interface *interface, const struct usb_device_id *id)
416 {
417         struct usb_host_interface *intf;
418         struct usb_device *dev;
419
420         /* proc_connectinfo in devio.c may call us with id == NULL. */
421         if (id == NULL)
422                 return NULL;
423
424         intf = interface->cur_altsetting;
425         dev = interface_to_usbdev(interface);
426
427         /* It is important to check that id->driver_info is nonzero,
428            since an entry that is all zeroes except for a nonzero
429            id->driver_info is the way to create an entry that
430            indicates that the driver want to examine every
431            device and interface. */
432         for (; id->idVendor || id->bDeviceClass || id->bInterfaceClass ||
433                id->driver_info; id++) {
434
435                 if ((id->match_flags & USB_DEVICE_ID_MATCH_VENDOR) &&
436                     id->idVendor != dev->descriptor.idVendor)
437                         continue;
438
439                 if ((id->match_flags & USB_DEVICE_ID_MATCH_PRODUCT) &&
440                     id->idProduct != dev->descriptor.idProduct)
441                         continue;
442
443                 /* No need to test id->bcdDevice_lo != 0, since 0 is never
444                    greater than any unsigned number. */
445                 if ((id->match_flags & USB_DEVICE_ID_MATCH_DEV_LO) &&
446                     (id->bcdDevice_lo > dev->descriptor.bcdDevice))
447                         continue;
448
449                 if ((id->match_flags & USB_DEVICE_ID_MATCH_DEV_HI) &&
450                     (id->bcdDevice_hi < dev->descriptor.bcdDevice))
451                         continue;
452
453                 if ((id->match_flags & USB_DEVICE_ID_MATCH_DEV_CLASS) &&
454                     (id->bDeviceClass != dev->descriptor.bDeviceClass))
455                         continue;
456
457                 if ((id->match_flags & USB_DEVICE_ID_MATCH_DEV_SUBCLASS) &&
458                     (id->bDeviceSubClass!= dev->descriptor.bDeviceSubClass))
459                         continue;
460
461                 if ((id->match_flags & USB_DEVICE_ID_MATCH_DEV_PROTOCOL) &&
462                     (id->bDeviceProtocol != dev->descriptor.bDeviceProtocol))
463                         continue;
464
465                 if ((id->match_flags & USB_DEVICE_ID_MATCH_INT_CLASS) &&
466                     (id->bInterfaceClass != intf->desc.bInterfaceClass))
467                         continue;
468
469                 if ((id->match_flags & USB_DEVICE_ID_MATCH_INT_SUBCLASS) &&
470                     (id->bInterfaceSubClass != intf->desc.bInterfaceSubClass))
471                         continue;
472
473                 if ((id->match_flags & USB_DEVICE_ID_MATCH_INT_PROTOCOL) &&
474                     (id->bInterfaceProtocol != intf->desc.bInterfaceProtocol))
475                         continue;
476
477                 return id;
478         }
479
480         return NULL;
481 }
482
483 /**
484  * usb_find_interface - find usb_interface pointer for driver and device
485  * @drv: the driver whose current configuration is considered
486  * @minor: the minor number of the desired device
487  *
488  * This walks the driver device list and returns a pointer to the interface 
489  * with the matching minor.  Note, this only works for devices that share the
490  * USB major number.
491  */
492 struct usb_interface *usb_find_interface(struct usb_driver *drv, int minor)
493 {
494         struct list_head *entry;
495         struct device *dev;
496         struct usb_interface *intf;
497
498         list_for_each(entry, &drv->driver.devices) {
499                 dev = container_of(entry, struct device, driver_list);
500
501                 /* can't look at usb devices, only interfaces */
502                 if (dev->driver == &usb_generic_driver)
503                         continue;
504
505                 intf = to_usb_interface(dev);
506                 if (intf->minor == -1)
507                         continue;
508                 if (intf->minor == minor)
509                         return intf;
510         }
511
512         /* no device found that matches */
513         return NULL;    
514 }
515
516 static int usb_device_match (struct device *dev, struct device_driver *drv)
517 {
518         struct usb_interface *intf;
519         struct usb_driver *usb_drv;
520         const struct usb_device_id *id;
521
522         /* check for generic driver, which we don't match any device with */
523         if (drv == &usb_generic_driver)
524                 return 0;
525
526         intf = to_usb_interface(dev);
527
528         usb_drv = to_usb_driver(drv);
529         id = usb_drv->id_table;
530         
531         id = usb_match_id (intf, usb_drv->id_table);
532         if (id)
533                 return 1;
534
535         return 0;
536 }
537
538
539 #ifdef  CONFIG_HOTPLUG
540
541 /*
542  * USB hotplugging invokes what /proc/sys/kernel/hotplug says
543  * (normally /sbin/hotplug) when USB devices get added or removed.
544  *
545  * This invokes a user mode policy agent, typically helping to load driver
546  * or other modules, configure the device, and more.  Drivers can provide
547  * a MODULE_DEVICE_TABLE to help with module loading subtasks.
548  *
549  * We're called either from khubd (the typical case) or from root hub
550  * (init, kapmd, modprobe, rmmod, etc), but the agents need to handle
551  * delays in event delivery.  Use sysfs (and DEVPATH) to make sure the
552  * device (and this configuration!) are still present.
553  */
554 static int usb_hotplug (struct device *dev, char **envp, int num_envp,
555                         char *buffer, int buffer_size)
556 {
557         struct usb_interface *intf;
558         struct usb_device *usb_dev;
559         char *scratch;
560         int i = 0;
561         int length = 0;
562
563         if (!dev)
564                 return -ENODEV;
565
566         /* driver is often null here; dev_dbg() would oops */
567         pr_debug ("usb %s: hotplug\n", dev->bus_id);
568
569         /* Must check driver_data here, as on remove driver is always NULL */
570         if ((dev->driver == &usb_generic_driver) || 
571             (dev->driver_data == &usb_generic_driver_data))
572                 return 0;
573
574         intf = to_usb_interface(dev);
575         usb_dev = interface_to_usbdev (intf);
576         
577         if (usb_dev->devnum < 0) {
578                 pr_debug ("usb %s: already deleted?\n", dev->bus_id);
579                 return -ENODEV;
580         }
581         if (!usb_dev->bus) {
582                 pr_debug ("usb %s: bus removed?\n", dev->bus_id);
583                 return -ENODEV;
584         }
585
586         scratch = buffer;
587
588 #ifdef  CONFIG_USB_DEVICEFS
589         /* If this is available, userspace programs can directly read
590          * all the device descriptors we don't tell them about.  Or
591          * even act as usermode drivers.
592          *
593          * FIXME reduce hardwired intelligence here
594          */
595         envp [i++] = scratch;
596         length += snprintf (scratch, buffer_size - length,
597                             "DEVICE=/proc/bus/usb/%03d/%03d",
598                             usb_dev->bus->busnum, usb_dev->devnum);
599         if ((buffer_size - length <= 0) || (i >= num_envp))
600                 return -ENOMEM;
601         ++length;
602         scratch += length;
603 #endif
604
605         /* per-device configurations are common */
606         envp [i++] = scratch;
607         length += snprintf (scratch, buffer_size - length, "PRODUCT=%x/%x/%x",
608                             usb_dev->descriptor.idVendor,
609                             usb_dev->descriptor.idProduct,
610                             usb_dev->descriptor.bcdDevice);
611         if ((buffer_size - length <= 0) || (i >= num_envp))
612                 return -ENOMEM;
613         ++length;
614         scratch += length;
615
616         /* class-based driver binding models */
617         envp [i++] = scratch;
618         length += snprintf (scratch, buffer_size - length, "TYPE=%d/%d/%d",
619                             usb_dev->descriptor.bDeviceClass,
620                             usb_dev->descriptor.bDeviceSubClass,
621                             usb_dev->descriptor.bDeviceProtocol);
622         if ((buffer_size - length <= 0) || (i >= num_envp))
623                 return -ENOMEM;
624         ++length;
625         scratch += length;
626
627         if (usb_dev->descriptor.bDeviceClass == 0) {
628                 struct usb_host_interface *alt = intf->cur_altsetting;
629
630                 /* 2.4 only exposed interface zero.  in 2.5, hotplug
631                  * agents are called for all interfaces, and can use
632                  * $DEVPATH/bInterfaceNumber if necessary.
633                  */
634                 envp [i++] = scratch;
635                 length += snprintf (scratch, buffer_size - length,
636                             "INTERFACE=%d/%d/%d",
637                             alt->desc.bInterfaceClass,
638                             alt->desc.bInterfaceSubClass,
639                             alt->desc.bInterfaceProtocol);
640                 if ((buffer_size - length <= 0) || (i >= num_envp))
641                         return -ENOMEM;
642                 ++length;
643                 scratch += length;
644
645         }
646         envp [i++] = 0;
647
648         return 0;
649 }
650
651 #else
652
653 static int usb_hotplug (struct device *dev, char **envp,
654                         int num_envp, char *buffer, int buffer_size)
655 {
656         return -ENODEV;
657 }
658
659 #endif  /* CONFIG_HOTPLUG */
660
661 /**
662  * usb_release_dev - free a usb device structure when all users of it are finished.
663  * @dev: device that's been disconnected
664  *
665  * Will be called only by the device core when all users of this usb device are
666  * done.
667  */
668 static void usb_release_dev(struct device *dev)
669 {
670         struct usb_device *udev;
671
672         udev = to_usb_device(dev);
673
674         if (udev->bus && udev->bus->op && udev->bus->op->deallocate)
675                 udev->bus->op->deallocate(udev);
676         usb_destroy_configuration(udev);
677         usb_bus_put(udev->bus);
678         kfree (udev);
679 }
680
681 /**
682  * usb_alloc_dev - usb device constructor (usbcore-internal)
683  * @parent: hub to which device is connected; null to allocate a root hub
684  * @bus: bus used to access the device
685  * @port: zero based index of port; ignored for root hubs
686  * Context: !in_interrupt ()
687  *
688  * Only hub drivers (including virtual root hub drivers for host
689  * controllers) should ever call this.
690  *
691  * This call may not be used in a non-sleeping context.
692  */
693 struct usb_device *
694 usb_alloc_dev(struct usb_device *parent, struct usb_bus *bus, unsigned port)
695 {
696         struct usb_device *dev;
697
698         dev = kmalloc(sizeof(*dev), GFP_KERNEL);
699         if (!dev)
700                 return NULL;
701
702         memset(dev, 0, sizeof(*dev));
703
704         bus = usb_bus_get(bus);
705         if (!bus) {
706                 kfree(dev);
707                 return NULL;
708         }
709
710         device_initialize(&dev->dev);
711         dev->dev.bus = &usb_bus_type;
712         dev->dev.dma_mask = bus->controller->dma_mask;
713         dev->dev.driver_data = &usb_generic_driver_data;
714         dev->dev.driver = &usb_generic_driver;
715         dev->dev.release = usb_release_dev;
716         dev->state = USB_STATE_ATTACHED;
717
718         /* Save readable and stable topology id, distinguishing devices
719          * by location for diagnostics, tools, driver model, etc.  The
720          * string is a path along hub ports, from the root.  Each device's
721          * dev->devpath will be stable until USB is re-cabled, and hubs
722          * are often labeled with these port numbers.  The bus_id isn't
723          * as stable:  bus->busnum changes easily from modprobe order,
724          * cardbus or pci hotplugging, and so on.
725          */
726         if (unlikely (!parent)) {
727                 dev->devpath [0] = '0';
728
729                 dev->dev.parent = bus->controller;
730                 sprintf (&dev->dev.bus_id[0], "usb%d", bus->busnum);
731         } else {
732                 /* match any labeling on the hubs; it's one-based */
733                 if (parent->devpath [0] == '0')
734                         snprintf (dev->devpath, sizeof dev->devpath,
735                                 "%d", port + 1);
736                 else
737                         snprintf (dev->devpath, sizeof dev->devpath,
738                                 "%s.%d", parent->devpath, port + 1);
739
740                 dev->dev.parent = &parent->dev;
741                 sprintf (&dev->dev.bus_id[0], "%d-%s",
742                         bus->busnum, dev->devpath);
743
744                 /* hub driver sets up TT records */
745         }
746
747         dev->bus = bus;
748         dev->parent = parent;
749         INIT_LIST_HEAD(&dev->filelist);
750
751         init_MUTEX(&dev->serialize);
752
753         if (dev->bus->op->allocate)
754                 dev->bus->op->allocate(dev);
755
756         return dev;
757 }
758
759 /**
760  * usb_get_dev - increments the reference count of the usb device structure
761  * @dev: the device being referenced
762  *
763  * Each live reference to a device should be refcounted.
764  *
765  * Drivers for USB interfaces should normally record such references in
766  * their probe() methods, when they bind to an interface, and release
767  * them by calling usb_put_dev(), in their disconnect() methods.
768  *
769  * A pointer to the device with the incremented reference counter is returned.
770  */
771 struct usb_device *usb_get_dev(struct usb_device *dev)
772 {
773         if (dev)
774                 get_device(&dev->dev);
775         return dev;
776 }
777
778 /**
779  * usb_put_dev - release a use of the usb device structure
780  * @dev: device that's been disconnected
781  *
782  * Must be called when a user of a device is finished with it.  When the last
783  * user of the device calls this function, the memory of the device is freed.
784  */
785 void usb_put_dev(struct usb_device *dev)
786 {
787         if (dev)
788                 put_device(&dev->dev);
789 }
790
791 /**
792  * usb_get_intf - increments the reference count of the usb interface structure
793  * @intf: the interface being referenced
794  *
795  * Each live reference to a interface must be refcounted.
796  *
797  * Drivers for USB interfaces should normally record such references in
798  * their probe() methods, when they bind to an interface, and release
799  * them by calling usb_put_intf(), in their disconnect() methods.
800  *
801  * A pointer to the interface with the incremented reference counter is
802  * returned.
803  */
804 struct usb_interface *usb_get_intf(struct usb_interface *intf)
805 {
806         if (intf)
807                 get_device(&intf->dev);
808         return intf;
809 }
810
811 /**
812  * usb_put_intf - release a use of the usb interface structure
813  * @intf: interface that's been decremented
814  *
815  * Must be called when a user of an interface is finished with it.  When the
816  * last user of the interface calls this function, the memory of the interface
817  * is freed.
818  */
819 void usb_put_intf(struct usb_interface *intf)
820 {
821         if (intf)
822                 put_device(&intf->dev);
823 }
824
825 static struct usb_device *match_device(struct usb_device *dev,
826                                        u16 vendor_id, u16 product_id)
827 {
828         struct usb_device *ret_dev = NULL;
829         int child;
830
831         dev_dbg(&dev->dev, "check for vendor %04x, product %04x ...\n",
832             dev->descriptor.idVendor,
833             dev->descriptor.idProduct);
834
835         /* see if this device matches */
836         if ((dev->descriptor.idVendor == vendor_id) &&
837             (dev->descriptor.idProduct == product_id)) {
838                 dev_dbg (&dev->dev, "matched this device!\n");
839                 ret_dev = usb_get_dev(dev);
840                 goto exit;
841         }
842
843         /* look through all of the children of this device */
844         for (child = 0; child < dev->maxchild; ++child) {
845                 if (dev->children[child]) {
846                         ret_dev = match_device(dev->children[child],
847                                                vendor_id, product_id);
848                         if (ret_dev)
849                                 goto exit;
850                 }
851         }
852 exit:
853         return ret_dev;
854 }
855
856 /**
857  * usb_find_device - find a specific usb device in the system
858  * @vendor_id: the vendor id of the device to find
859  * @product_id: the product id of the device to find
860  *
861  * Returns a pointer to a struct usb_device if such a specified usb
862  * device is present in the system currently.  The usage count of the
863  * device will be incremented if a device is found.  Make sure to call
864  * usb_put_dev() when the caller is finished with the device.
865  *
866  * If a device with the specified vendor and product id is not found,
867  * NULL is returned.
868  */
869 struct usb_device *usb_find_device(u16 vendor_id, u16 product_id)
870 {
871         struct list_head *buslist;
872         struct usb_bus *bus;
873         struct usb_device *dev = NULL;
874         
875         down(&usb_bus_list_lock);
876         for (buslist = usb_bus_list.next;
877              buslist != &usb_bus_list; 
878              buslist = buslist->next) {
879                 bus = container_of(buslist, struct usb_bus, bus_list);
880                 dev = match_device(bus->root_hub, vendor_id, product_id);
881                 if (dev)
882                         goto exit;
883         }
884 exit:
885         up(&usb_bus_list_lock);
886         return dev;
887 }
888
889 /**
890  * usb_get_current_frame_number - return current bus frame number
891  * @dev: the device whose bus is being queried
892  *
893  * Returns the current frame number for the USB host controller
894  * used with the given USB device.  This can be used when scheduling
895  * isochronous requests.
896  *
897  * Note that different kinds of host controller have different
898  * "scheduling horizons".  While one type might support scheduling only
899  * 32 frames into the future, others could support scheduling up to
900  * 1024 frames into the future.
901  */
902 int usb_get_current_frame_number(struct usb_device *dev)
903 {
904         return dev->bus->op->get_frame_number (dev);
905 }
906
907 /*-------------------------------------------------------------------*/
908 /*
909  * __usb_get_extra_descriptor() finds a descriptor of specific type in the
910  * extra field of the interface and endpoint descriptor structs.
911  */
912
913 int __usb_get_extra_descriptor(char *buffer, unsigned size,
914         unsigned char type, void **ptr)
915 {
916         struct usb_descriptor_header *header;
917
918         while (size >= sizeof(struct usb_descriptor_header)) {
919                 header = (struct usb_descriptor_header *)buffer;
920
921                 if (header->bLength < 2) {
922                         printk(KERN_ERR
923                                 "%s: bogus descriptor, type %d length %d\n",
924                                 usbcore_name,
925                                 header->bDescriptorType, 
926                                 header->bLength);
927                         return -1;
928                 }
929
930                 if (header->bDescriptorType == type) {
931                         *ptr = header;
932                         return 0;
933                 }
934
935                 buffer += header->bLength;
936                 size -= header->bLength;
937         }
938         return -1;
939 }
940
941 /**
942  * usb_disconnect - disconnect a device (usbcore-internal)
943  * @pdev: pointer to device being disconnected
944  * Context: !in_interrupt ()
945  *
946  * Something got disconnected. Get rid of it, and all of its children.
947  *
948  * Only hub drivers (including virtual root hub drivers for host
949  * controllers) should ever call this.
950  *
951  * This call is synchronous, and may not be used in an interrupt context.
952  */
953 void usb_disconnect(struct usb_device **pdev)
954 {
955         struct usb_device       *dev = *pdev;
956         struct usb_bus          *bus;
957         struct usb_operations   *ops;
958         int                     i;
959
960         might_sleep ();
961
962         if (!dev) {
963                 pr_debug ("%s nodev\n", __FUNCTION__);
964                 return;
965         }
966         bus = dev->bus;
967         if (!bus) {
968                 pr_debug ("%s nobus\n", __FUNCTION__);
969                 return;
970         }
971         ops = bus->op;
972
973         *pdev = NULL;
974
975         /* mark the device as inactive, so any further urb submissions for
976          * this device will fail.
977          */
978         dev->state = USB_STATE_NOTATTACHED;
979         down(&dev->serialize);
980
981         dev_info (&dev->dev, "USB disconnect, address %d\n", dev->devnum);
982
983         /* Free up all the children before we remove this device */
984         for (i = 0; i < USB_MAXCHILDREN; i++) {
985                 struct usb_device **child = dev->children + i;
986                 if (*child)
987                         usb_disconnect(child);
988         }
989
990         /* deallocate hcd/hardware state ... nuking all pending urbs and
991          * cleaning up all state associated with the current configuration
992          */
993         usb_disable_device(dev, 0);
994
995         dev_dbg (&dev->dev, "unregistering device\n");
996         /* Free the device number and remove the /proc/bus/usb entry */
997         if (dev->devnum > 0) {
998                 clear_bit(dev->devnum, dev->bus->devmap.devicemap);
999                 usbfs_remove_device(dev);
1000         }
1001         up(&dev->serialize);
1002         device_unregister(&dev->dev);
1003 }
1004
1005 /**
1006  * usb_choose_address - pick device address (usbcore-internal)
1007  * @dev: newly detected device (in DEFAULT state)
1008  *
1009  * Picks a device address.  It's up to the hub (or root hub) driver
1010  * to handle and manage enumeration, starting from the DEFAULT state.
1011  * Only hub drivers (but not virtual root hub drivers for host
1012  * controllers) should ever call this.
1013  */
1014 void usb_choose_address(struct usb_device *dev)
1015 {
1016         int devnum;
1017         // FIXME needs locking for SMP!!
1018         /* why? this is called only from the hub thread, 
1019          * which hopefully doesn't run on multiple CPU's simultaneously 8-)
1020          */
1021
1022         /* Try to allocate the next devnum beginning at bus->devnum_next. */
1023         devnum = find_next_zero_bit(dev->bus->devmap.devicemap, 128, dev->bus->devnum_next);
1024         if (devnum >= 128)
1025                 devnum = find_next_zero_bit(dev->bus->devmap.devicemap, 128, 1);
1026
1027         dev->bus->devnum_next = ( devnum >= 127 ? 1 : devnum + 1);
1028
1029         if (devnum < 128) {
1030                 set_bit(devnum, dev->bus->devmap.devicemap);
1031                 dev->devnum = devnum;
1032         }
1033 }
1034
1035
1036 // hub-only!! ... and only exported for reset/reinit path.
1037 // otherwise used internally, for usb_new_device()
1038 int usb_set_address(struct usb_device *dev)
1039 {
1040         int retval;
1041
1042         if (dev->devnum == 0)
1043                 return -EINVAL;
1044         if (dev->state != USB_STATE_DEFAULT && dev->state != USB_STATE_ADDRESS)
1045                 return -EINVAL;
1046         retval = usb_control_msg(dev, usb_snddefctrl(dev), USB_REQ_SET_ADDRESS,
1047                 0, dev->devnum, 0, NULL, 0, HZ * USB_CTRL_SET_TIMEOUT);
1048         if (retval == 0)
1049                 dev->state = USB_STATE_ADDRESS;
1050         return retval;
1051 }
1052
1053 static inline void usb_show_string(struct usb_device *dev, char *id, int index)
1054 {
1055         char *buf;
1056
1057         if (!index)
1058                 return;
1059         if (!(buf = kmalloc(256, GFP_KERNEL)))
1060                 return;
1061         if (usb_string(dev, index, buf, 256) > 0)
1062                 dev_printk(KERN_INFO, &dev->dev, "%s: %s\n", id, buf);
1063         kfree(buf);
1064 }
1065
1066 /*
1067  * By the time we get here, we chose a new device address
1068  * and is in the default state. We need to identify the thing and
1069  * get the ball rolling..
1070  *
1071  * Returns 0 for success, != 0 for error.
1072  *
1073  * This call is synchronous, and may not be used in an interrupt context.
1074  *
1075  * Only the hub driver should ever call this; root hub registration
1076  * uses it only indirectly.
1077  */
1078 #define NEW_DEVICE_RETRYS       2
1079 #define SET_ADDRESS_RETRYS      2
1080 int usb_new_device(struct usb_device *dev)
1081 {
1082         int err = -EINVAL;
1083         int i;
1084         int j;
1085         int config;
1086
1087         /* USB 2.0 section 5.5.3 talks about ep0 maxpacket ...
1088          * it's fixed size except for full speed devices.
1089          */
1090         switch (dev->speed) {
1091         case USB_SPEED_HIGH:            /* fixed at 64 */
1092                 i = 64;
1093                 break;
1094         case USB_SPEED_FULL:            /* 8, 16, 32, or 64 */
1095                 /* to determine the ep0 maxpacket size, read the first 8
1096                  * bytes from the device descriptor to get bMaxPacketSize0;
1097                  * then correct our initial (small) guess.
1098                  */
1099                 // FALLTHROUGH
1100         case USB_SPEED_LOW:             /* fixed at 8 */
1101                 i = 8;
1102                 break;
1103         default:
1104                 goto fail;
1105         }
1106         dev->epmaxpacketin [0] = i;
1107         dev->epmaxpacketout[0] = i;
1108
1109         for (i = 0; i < NEW_DEVICE_RETRYS; ++i) {
1110
1111                 for (j = 0; j < SET_ADDRESS_RETRYS; ++j) {
1112                         err = usb_set_address(dev);
1113                         if (err >= 0)
1114                                 break;
1115                         wait_ms(200);
1116                 }
1117                 if (err < 0) {
1118                         dev_err(&dev->dev,
1119                                 "device not accepting address %d, error %d\n",
1120                                 dev->devnum, err);
1121                         goto fail;
1122                 }
1123
1124                 wait_ms(10);    /* Let the SET_ADDRESS settle */
1125
1126                 /* high and low speed devices don't need this... */
1127                 err = usb_get_device_descriptor(dev, 8);
1128                 if (err >= 8)
1129                         break;
1130                 wait_ms(100);
1131         }
1132
1133         if (err < 8) {
1134                 dev_err(&dev->dev, "device descriptor read/8, error %d\n", err);
1135                 goto fail;
1136         }
1137         if (dev->speed == USB_SPEED_FULL) {
1138                 usb_disable_endpoint(dev, 0);
1139                 usb_endpoint_running(dev, 0, 1);
1140                 usb_endpoint_running(dev, 0, 0);
1141                 dev->epmaxpacketin [0] = dev->descriptor.bMaxPacketSize0;
1142                 dev->epmaxpacketout[0] = dev->descriptor.bMaxPacketSize0;
1143         }
1144
1145         /* USB device state == addressed ... still not usable */
1146
1147         err = usb_get_device_descriptor(dev, sizeof(dev->descriptor));
1148         if (err != (signed)sizeof(dev->descriptor)) {
1149                 dev_err(&dev->dev, "device descriptor read/all, error %d\n", err);
1150                 goto fail;
1151         }
1152
1153         err = usb_get_configuration(dev);
1154         if (err < 0) {
1155                 dev_err(&dev->dev, "can't read configurations, error %d\n",
1156                         err);
1157                 goto fail;
1158         }
1159
1160         /* Tell the world! */
1161         dev_dbg(&dev->dev, "new device strings: Mfr=%d, Product=%d, SerialNumber=%d\n",
1162                 dev->descriptor.iManufacturer, dev->descriptor.iProduct, dev->descriptor.iSerialNumber);
1163
1164 #ifdef DEBUG
1165         if (dev->descriptor.iProduct)
1166                 usb_show_string(dev, "Product", dev->descriptor.iProduct);
1167         if (dev->descriptor.iManufacturer)
1168                 usb_show_string(dev, "Manufacturer", dev->descriptor.iManufacturer);
1169         if (dev->descriptor.iSerialNumber)
1170                 usb_show_string(dev, "SerialNumber", dev->descriptor.iSerialNumber);
1171 #endif
1172
1173         down(&dev->serialize);
1174
1175         /* put device-specific files into sysfs */
1176         err = device_add (&dev->dev);
1177         if (err) {
1178                 dev_err(&dev->dev, "can't device_add, error %d\n", err);
1179                 up(&dev->serialize);
1180                 goto fail;
1181         }
1182         usb_create_driverfs_dev_files (dev);
1183
1184         /* choose and set the configuration. that registers the interfaces
1185          * with the driver core, and lets usb device drivers bind to them.
1186          * NOTE:  should interact with hub power budgeting.
1187          */
1188         config = dev->config[0].desc.bConfigurationValue;
1189         if (dev->descriptor.bNumConfigurations != 1) {
1190                 for (i = 0; i < dev->descriptor.bNumConfigurations; i++) {
1191                         struct usb_interface_descriptor *desc;
1192
1193                         /* heuristic:  Linux is more likely to have class
1194                          * drivers, so avoid vendor-specific interfaces.
1195                          */
1196                         desc = &dev->config[i].interface[0]
1197                                         ->altsetting->desc;
1198                         if (desc->bInterfaceClass == USB_CLASS_VENDOR_SPEC)
1199                                 continue;
1200                         /* COMM/2/all is CDC ACM, except 0xff is MSFT RNDIS */
1201                         if (desc->bInterfaceClass == USB_CLASS_COMM
1202                                         && desc->bInterfaceSubClass == 2
1203                                         && desc->bInterfaceProtocol == 0xff)
1204                                 continue;
1205                         config = dev->config[i].desc.bConfigurationValue;
1206                         break;
1207                 }
1208                 dev_info(&dev->dev,
1209                         "configuration #%d chosen from %d choices\n",
1210                         config,
1211                         dev->descriptor.bNumConfigurations);
1212         }
1213         err = usb_set_configuration(dev, config);
1214         up(&dev->serialize);
1215         if (err) {
1216                 dev_err(&dev->dev, "can't set config #%d, error %d\n",
1217                         config, err);
1218                 device_del(&dev->dev);
1219                 goto fail;
1220         }
1221
1222         /* USB device state == configured ... usable */
1223
1224         /* add a /proc/bus/usb entry */
1225         usbfs_add_device(dev);
1226
1227         return 0;
1228 fail:
1229         dev->state = USB_STATE_DEFAULT;
1230         clear_bit(dev->devnum, dev->bus->devmap.devicemap);
1231         dev->devnum = -1;
1232         return err;
1233 }
1234
1235 /**
1236  * usb_buffer_alloc - allocate dma-consistent buffer for URB_NO_xxx_DMA_MAP
1237  * @dev: device the buffer will be used with
1238  * @size: requested buffer size
1239  * @mem_flags: affect whether allocation may block
1240  * @dma: used to return DMA address of buffer
1241  *
1242  * Return value is either null (indicating no buffer could be allocated), or
1243  * the cpu-space pointer to a buffer that may be used to perform DMA to the
1244  * specified device.  Such cpu-space buffers are returned along with the DMA
1245  * address (through the pointer provided).
1246  *
1247  * These buffers are used with URB_NO_xxx_DMA_MAP set in urb->transfer_flags
1248  * to avoid behaviors like using "DMA bounce buffers", or tying down I/O
1249  * mapping hardware for long idle periods.  The implementation varies between
1250  * platforms, depending on details of how DMA will work to this device.
1251  * Using these buffers also helps prevent cacheline sharing problems on
1252  * architectures where CPU caches are not DMA-coherent.
1253  *
1254  * When the buffer is no longer used, free it with usb_buffer_free().
1255  */
1256 void *usb_buffer_alloc (
1257         struct usb_device *dev,
1258         size_t size,
1259         int mem_flags,
1260         dma_addr_t *dma
1261 )
1262 {
1263         if (!dev || !dev->bus || !dev->bus->op || !dev->bus->op->buffer_alloc)
1264                 return 0;
1265         return dev->bus->op->buffer_alloc (dev->bus, size, mem_flags, dma);
1266 }
1267
1268 /**
1269  * usb_buffer_free - free memory allocated with usb_buffer_alloc()
1270  * @dev: device the buffer was used with
1271  * @size: requested buffer size
1272  * @addr: CPU address of buffer
1273  * @dma: DMA address of buffer
1274  *
1275  * This reclaims an I/O buffer, letting it be reused.  The memory must have
1276  * been allocated using usb_buffer_alloc(), and the parameters must match
1277  * those provided in that allocation request. 
1278  */
1279 void usb_buffer_free (
1280         struct usb_device *dev,
1281         size_t size,
1282         void *addr,
1283         dma_addr_t dma
1284 )
1285 {
1286         if (!dev || !dev->bus || !dev->bus->op || !dev->bus->op->buffer_free)
1287                 return;
1288         dev->bus->op->buffer_free (dev->bus, size, addr, dma);
1289 }
1290
1291 /**
1292  * usb_buffer_map - create DMA mapping(s) for an urb
1293  * @urb: urb whose transfer_buffer/setup_packet will be mapped
1294  *
1295  * Return value is either null (indicating no buffer could be mapped), or
1296  * the parameter.  URB_NO_TRANSFER_DMA_MAP and URB_NO_SETUP_DMA_MAP are
1297  * added to urb->transfer_flags if the operation succeeds.  If the device
1298  * is connected to this system through a non-DMA controller, this operation
1299  * always succeeds.
1300  *
1301  * This call would normally be used for an urb which is reused, perhaps
1302  * as the target of a large periodic transfer, with usb_buffer_dmasync()
1303  * calls to synchronize memory and dma state.
1304  *
1305  * Reverse the effect of this call with usb_buffer_unmap().
1306  */
1307 struct urb *usb_buffer_map (struct urb *urb)
1308 {
1309         struct usb_bus          *bus;
1310         struct device           *controller;
1311
1312         if (!urb
1313                         || !urb->dev
1314                         || !(bus = urb->dev->bus)
1315                         || !(controller = bus->controller))
1316                 return 0;
1317
1318         if (controller->dma_mask) {
1319                 urb->transfer_dma = dma_map_single (controller,
1320                         urb->transfer_buffer, urb->transfer_buffer_length,
1321                         usb_pipein (urb->pipe)
1322                                 ? DMA_FROM_DEVICE : DMA_TO_DEVICE);
1323                 if (usb_pipecontrol (urb->pipe))
1324                         urb->setup_dma = dma_map_single (controller,
1325                                         urb->setup_packet,
1326                                         sizeof (struct usb_ctrlrequest),
1327                                         DMA_TO_DEVICE);
1328         // FIXME generic api broken like pci, can't report errors
1329         // if (urb->transfer_dma == DMA_ADDR_INVALID) return 0;
1330         } else
1331                 urb->transfer_dma = ~0;
1332         urb->transfer_flags |= (URB_NO_TRANSFER_DMA_MAP
1333                                 | URB_NO_SETUP_DMA_MAP);
1334         return urb;
1335 }
1336
1337 /* XXX DISABLED, no users currently.  If you wish to re-enable this
1338  * XXX please determine whether the sync is to transfer ownership of
1339  * XXX the buffer from device to cpu or vice verse, and thusly use the
1340  * XXX appropriate _for_{cpu,device}() method.  -DaveM
1341  */
1342 #if 0
1343
1344 /**
1345  * usb_buffer_dmasync - synchronize DMA and CPU view of buffer(s)
1346  * @urb: urb whose transfer_buffer/setup_packet will be synchronized
1347  */
1348 void usb_buffer_dmasync (struct urb *urb)
1349 {
1350         struct usb_bus          *bus;
1351         struct device           *controller;
1352
1353         if (!urb
1354                         || !(urb->transfer_flags & URB_NO_TRANSFER_DMA_MAP)
1355                         || !urb->dev
1356                         || !(bus = urb->dev->bus)
1357                         || !(controller = bus->controller))
1358                 return;
1359
1360         if (controller->dma_mask) {
1361                 dma_sync_single (controller,
1362                         urb->transfer_dma, urb->transfer_buffer_length,
1363                         usb_pipein (urb->pipe)
1364                                 ? DMA_FROM_DEVICE : DMA_TO_DEVICE);
1365                 if (usb_pipecontrol (urb->pipe))
1366                         dma_sync_single (controller,
1367                                         urb->setup_dma,
1368                                         sizeof (struct usb_ctrlrequest),
1369                                         DMA_TO_DEVICE);
1370         }
1371 }
1372 #endif
1373
1374 /**
1375  * usb_buffer_unmap - free DMA mapping(s) for an urb
1376  * @urb: urb whose transfer_buffer will be unmapped
1377  *
1378  * Reverses the effect of usb_buffer_map().
1379  */
1380 void usb_buffer_unmap (struct urb *urb)
1381 {
1382         struct usb_bus          *bus;
1383         struct device           *controller;
1384
1385         if (!urb
1386                         || !(urb->transfer_flags & URB_NO_TRANSFER_DMA_MAP)
1387                         || !urb->dev
1388                         || !(bus = urb->dev->bus)
1389                         || !(controller = bus->controller))
1390                 return;
1391
1392         if (controller->dma_mask) {
1393                 dma_unmap_single (controller,
1394                         urb->transfer_dma, urb->transfer_buffer_length,
1395                         usb_pipein (urb->pipe)
1396                                 ? DMA_FROM_DEVICE : DMA_TO_DEVICE);
1397                 if (usb_pipecontrol (urb->pipe))
1398                         dma_unmap_single (controller,
1399                                         urb->setup_dma,
1400                                         sizeof (struct usb_ctrlrequest),
1401                                         DMA_TO_DEVICE);
1402         }
1403         urb->transfer_flags &= ~(URB_NO_TRANSFER_DMA_MAP
1404                                 | URB_NO_SETUP_DMA_MAP);
1405 }
1406
1407 /**
1408  * usb_buffer_map_sg - create scatterlist DMA mapping(s) for an endpoint
1409  * @dev: device to which the scatterlist will be mapped
1410  * @pipe: endpoint defining the mapping direction
1411  * @sg: the scatterlist to map
1412  * @nents: the number of entries in the scatterlist
1413  *
1414  * Return value is either < 0 (indicating no buffers could be mapped), or
1415  * the number of DMA mapping array entries in the scatterlist.
1416  *
1417  * The caller is responsible for placing the resulting DMA addresses from
1418  * the scatterlist into URB transfer buffer pointers, and for setting the
1419  * URB_NO_TRANSFER_DMA_MAP transfer flag in each of those URBs.
1420  *
1421  * Top I/O rates come from queuing URBs, instead of waiting for each one
1422  * to complete before starting the next I/O.   This is particularly easy
1423  * to do with scatterlists.  Just allocate and submit one URB for each DMA
1424  * mapping entry returned, stopping on the first error or when all succeed.
1425  * Better yet, use the usb_sg_*() calls, which do that (and more) for you.
1426  *
1427  * This call would normally be used when translating scatterlist requests,
1428  * rather than usb_buffer_map(), since on some hardware (with IOMMUs) it
1429  * may be able to coalesce mappings for improved I/O efficiency.
1430  *
1431  * Reverse the effect of this call with usb_buffer_unmap_sg().
1432  */
1433 int usb_buffer_map_sg (struct usb_device *dev, unsigned pipe,
1434                 struct scatterlist *sg, int nents)
1435 {
1436         struct usb_bus          *bus;
1437         struct device           *controller;
1438
1439         if (!dev
1440                         || usb_pipecontrol (pipe)
1441                         || !(bus = dev->bus)
1442                         || !(controller = bus->controller)
1443                         || !controller->dma_mask)
1444                 return -1;
1445
1446         // FIXME generic api broken like pci, can't report errors
1447         return dma_map_sg (controller, sg, nents,
1448                         usb_pipein (pipe) ? DMA_FROM_DEVICE : DMA_TO_DEVICE);
1449 }
1450
1451 /* XXX DISABLED, no users currently.  If you wish to re-enable this
1452  * XXX please determine whether the sync is to transfer ownership of
1453  * XXX the buffer from device to cpu or vice verse, and thusly use the
1454  * XXX appropriate _for_{cpu,device}() method.  -DaveM
1455  */
1456 #if 0
1457
1458 /**
1459  * usb_buffer_dmasync_sg - synchronize DMA and CPU view of scatterlist buffer(s)
1460  * @dev: device to which the scatterlist will be mapped
1461  * @pipe: endpoint defining the mapping direction
1462  * @sg: the scatterlist to synchronize
1463  * @n_hw_ents: the positive return value from usb_buffer_map_sg
1464  *
1465  * Use this when you are re-using a scatterlist's data buffers for
1466  * another USB request.
1467  */
1468 void usb_buffer_dmasync_sg (struct usb_device *dev, unsigned pipe,
1469                 struct scatterlist *sg, int n_hw_ents)
1470 {
1471         struct usb_bus          *bus;
1472         struct device           *controller;
1473
1474         if (!dev
1475                         || !(bus = dev->bus)
1476                         || !(controller = bus->controller)
1477                         || !controller->dma_mask)
1478                 return;
1479
1480         dma_sync_sg (controller, sg, n_hw_ents,
1481                         usb_pipein (pipe) ? DMA_FROM_DEVICE : DMA_TO_DEVICE);
1482 }
1483 #endif
1484
1485 /**
1486  * usb_buffer_unmap_sg - free DMA mapping(s) for a scatterlist
1487  * @dev: device to which the scatterlist will be mapped
1488  * @pipe: endpoint defining the mapping direction
1489  * @sg: the scatterlist to unmap
1490  * @n_hw_ents: the positive return value from usb_buffer_map_sg
1491  *
1492  * Reverses the effect of usb_buffer_map_sg().
1493  */
1494 void usb_buffer_unmap_sg (struct usb_device *dev, unsigned pipe,
1495                 struct scatterlist *sg, int n_hw_ents)
1496 {
1497         struct usb_bus          *bus;
1498         struct device           *controller;
1499
1500         if (!dev
1501                         || !(bus = dev->bus)
1502                         || !(controller = bus->controller)
1503                         || !controller->dma_mask)
1504                 return;
1505
1506         dma_unmap_sg (controller, sg, n_hw_ents,
1507                         usb_pipein (pipe) ? DMA_FROM_DEVICE : DMA_TO_DEVICE);
1508 }
1509
1510 static int usb_device_suspend(struct device *dev, u32 state)
1511 {
1512         struct usb_interface *intf;
1513         struct usb_driver *driver;
1514
1515         if ((dev->driver == NULL) ||
1516             (dev->driver == &usb_generic_driver) ||
1517             (dev->driver_data == &usb_generic_driver_data))
1518                 return 0;
1519
1520         intf = to_usb_interface(dev);
1521         driver = to_usb_driver(dev->driver);
1522
1523         if (driver->suspend)
1524                 return driver->suspend(intf, state);
1525         return 0;
1526 }
1527
1528 static int usb_device_resume(struct device *dev)
1529 {
1530         struct usb_interface *intf;
1531         struct usb_driver *driver;
1532
1533         if ((dev->driver == NULL) ||
1534             (dev->driver == &usb_generic_driver) ||
1535             (dev->driver_data == &usb_generic_driver_data))
1536                 return 0;
1537
1538         intf = to_usb_interface(dev);
1539         driver = to_usb_driver(dev->driver);
1540
1541         if (driver->resume)
1542                 return driver->resume(intf);
1543         return 0;
1544 }
1545
1546 struct bus_type usb_bus_type = {
1547         .name =         "usb",
1548         .match =        usb_device_match,
1549         .hotplug =      usb_hotplug,
1550         .suspend =      usb_device_suspend,
1551         .resume =       usb_device_resume,
1552 };
1553
1554 #ifndef MODULE
1555
1556 static int __init usb_setup_disable(char *str)
1557 {
1558         nousb = 1;
1559         return 1;
1560 }
1561
1562 /* format to disable USB on kernel command line is: nousb */
1563 __setup("nousb", usb_setup_disable);
1564
1565 #endif
1566
1567 /*
1568  * for external read access to <nousb>
1569  */
1570 int usb_disabled(void)
1571 {
1572         return nousb;
1573 }
1574
1575 /*
1576  * Init
1577  */
1578 static int __init usb_init(void)
1579 {
1580         if (nousb) {
1581                 pr_info ("%s: USB support disabled\n", usbcore_name);
1582                 return 0;
1583         }
1584
1585         bus_register(&usb_bus_type);
1586         usb_host_init();
1587         usb_major_init();
1588         usbfs_init();
1589         usb_hub_init();
1590
1591         driver_register(&usb_generic_driver);
1592
1593         return 0;
1594 }
1595
1596 /*
1597  * Cleanup
1598  */
1599 static void __exit usb_exit(void)
1600 {
1601         /* This will matter if shutdown/reboot does exitcalls. */
1602         if (nousb)
1603                 return;
1604
1605         driver_unregister(&usb_generic_driver);
1606         usb_major_cleanup();
1607         usbfs_cleanup();
1608         usb_hub_cleanup();
1609         usb_host_cleanup();
1610         bus_unregister(&usb_bus_type);
1611 }
1612
1613 subsys_initcall(usb_init);
1614 module_exit(usb_exit);
1615
1616 /*
1617  * USB may be built into the kernel or be built as modules.
1618  * These symbols are exported for device (or host controller)
1619  * driver modules to use.
1620  */
1621 EXPORT_SYMBOL(usb_epnum_to_ep_desc);
1622
1623 EXPORT_SYMBOL(usb_register);
1624 EXPORT_SYMBOL(usb_deregister);
1625 EXPORT_SYMBOL(usb_disabled);
1626
1627 EXPORT_SYMBOL(usb_alloc_dev);
1628 EXPORT_SYMBOL(usb_put_dev);
1629 EXPORT_SYMBOL(usb_get_dev);
1630 EXPORT_SYMBOL(usb_hub_tt_clear_buffer);
1631
1632 EXPORT_SYMBOL(usb_driver_claim_interface);
1633 EXPORT_SYMBOL(usb_driver_release_interface);
1634 EXPORT_SYMBOL(usb_match_id);
1635 EXPORT_SYMBOL(usb_find_interface);
1636 EXPORT_SYMBOL(usb_ifnum_to_if);
1637 EXPORT_SYMBOL(usb_altnum_to_altsetting);
1638
1639 EXPORT_SYMBOL(usb_reset_device);
1640 EXPORT_SYMBOL(usb_disconnect);
1641
1642 EXPORT_SYMBOL(__usb_get_extra_descriptor);
1643
1644 EXPORT_SYMBOL(usb_find_device);
1645 EXPORT_SYMBOL(usb_get_current_frame_number);
1646
1647 EXPORT_SYMBOL (usb_buffer_alloc);
1648 EXPORT_SYMBOL (usb_buffer_free);
1649
1650 EXPORT_SYMBOL (usb_buffer_map);
1651 #if 0
1652 EXPORT_SYMBOL (usb_buffer_dmasync);
1653 #endif
1654 EXPORT_SYMBOL (usb_buffer_unmap);
1655
1656 EXPORT_SYMBOL (usb_buffer_map_sg);
1657 #if 0
1658 EXPORT_SYMBOL (usb_buffer_dmasync_sg);
1659 #endif
1660 EXPORT_SYMBOL (usb_buffer_unmap_sg);
1661
1662 MODULE_LICENSE("GPL");