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