USB: xhci: Bandwidth allocation support
[linux-2.6] / drivers / usb / core / usb.c
1 /*
2  * drivers/usb/core/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/module.h>
25 #include <linux/moduleparam.h>
26 #include <linux/string.h>
27 #include <linux/bitops.h>
28 #include <linux/slab.h>
29 #include <linux/interrupt.h>  /* for in_interrupt() */
30 #include <linux/kmod.h>
31 #include <linux/init.h>
32 #include <linux/spinlock.h>
33 #include <linux/errno.h>
34 #include <linux/usb.h>
35 #include <linux/mutex.h>
36 #include <linux/workqueue.h>
37 #include <linux/debugfs.h>
38
39 #include <asm/io.h>
40 #include <linux/scatterlist.h>
41 #include <linux/mm.h>
42 #include <linux/dma-mapping.h>
43
44 #include "hcd.h"
45 #include "usb.h"
46
47
48 const char *usbcore_name = "usbcore";
49
50 static int nousb;       /* Disable USB when built into kernel image */
51
52 /* Workqueue for autosuspend and for remote wakeup of root hubs */
53 struct workqueue_struct *ksuspend_usb_wq;
54
55 #ifdef  CONFIG_USB_SUSPEND
56 static int usb_autosuspend_delay = 2;           /* Default delay value,
57                                                  * in seconds */
58 module_param_named(autosuspend, usb_autosuspend_delay, int, 0644);
59 MODULE_PARM_DESC(autosuspend, "default autosuspend delay");
60
61 #else
62 #define usb_autosuspend_delay           0
63 #endif
64
65
66 /**
67  * usb_ifnum_to_if - get the interface object with a given interface number
68  * @dev: the device whose current configuration is considered
69  * @ifnum: the desired interface
70  *
71  * This walks the device descriptor for the currently active configuration
72  * and returns a pointer to the interface with that particular interface
73  * number, or null.
74  *
75  * Note that configuration descriptors are not required to assign interface
76  * numbers sequentially, so that it would be incorrect to assume that
77  * the first interface in that descriptor corresponds to interface zero.
78  * This routine helps device drivers avoid such mistakes.
79  * However, you should make sure that you do the right thing with any
80  * alternate settings available for this interfaces.
81  *
82  * Don't call this function unless you are bound to one of the interfaces
83  * on this device or you have locked the device!
84  */
85 struct usb_interface *usb_ifnum_to_if(const struct usb_device *dev,
86                                       unsigned ifnum)
87 {
88         struct usb_host_config *config = dev->actconfig;
89         int i;
90
91         if (!config)
92                 return NULL;
93         for (i = 0; i < config->desc.bNumInterfaces; i++)
94                 if (config->interface[i]->altsetting[0]
95                                 .desc.bInterfaceNumber == ifnum)
96                         return config->interface[i];
97
98         return NULL;
99 }
100 EXPORT_SYMBOL_GPL(usb_ifnum_to_if);
101
102 /**
103  * usb_altnum_to_altsetting - get the altsetting structure with a given alternate setting number.
104  * @intf: the interface containing the altsetting in question
105  * @altnum: the desired alternate setting number
106  *
107  * This searches the altsetting array of the specified interface for
108  * an entry with the correct bAlternateSetting value and returns a pointer
109  * to that entry, or null.
110  *
111  * Note that altsettings need not be stored sequentially by number, so
112  * it would be incorrect to assume that the first altsetting entry in
113  * the array corresponds to altsetting zero.  This routine helps device
114  * drivers avoid such mistakes.
115  *
116  * Don't call this function unless you are bound to the intf interface
117  * or you have locked the device!
118  */
119 struct usb_host_interface *usb_altnum_to_altsetting(
120                                         const struct usb_interface *intf,
121                                         unsigned int altnum)
122 {
123         int i;
124
125         for (i = 0; i < intf->num_altsetting; i++) {
126                 if (intf->altsetting[i].desc.bAlternateSetting == altnum)
127                         return &intf->altsetting[i];
128         }
129         return NULL;
130 }
131 EXPORT_SYMBOL_GPL(usb_altnum_to_altsetting);
132
133 struct find_interface_arg {
134         int minor;
135         struct usb_interface *interface;
136 };
137
138 static int __find_interface(struct device *dev, void *data)
139 {
140         struct find_interface_arg *arg = data;
141         struct usb_interface *intf;
142
143         if (!is_usb_interface(dev))
144                 return 0;
145
146         intf = to_usb_interface(dev);
147         if (intf->minor != -1 && intf->minor == arg->minor) {
148                 arg->interface = intf;
149                 return 1;
150         }
151         return 0;
152 }
153
154 /**
155  * usb_find_interface - find usb_interface pointer for driver and device
156  * @drv: the driver whose current configuration is considered
157  * @minor: the minor number of the desired device
158  *
159  * This walks the driver device list and returns a pointer to the interface
160  * with the matching minor.  Note, this only works for devices that share the
161  * USB major number.
162  */
163 struct usb_interface *usb_find_interface(struct usb_driver *drv, int minor)
164 {
165         struct find_interface_arg argb;
166         int retval;
167
168         argb.minor = minor;
169         argb.interface = NULL;
170         /* eat the error, it will be in argb.interface */
171         retval = driver_for_each_device(&drv->drvwrap.driver, NULL, &argb,
172                                         __find_interface);
173         return argb.interface;
174 }
175 EXPORT_SYMBOL_GPL(usb_find_interface);
176
177 /**
178  * usb_release_dev - free a usb device structure when all users of it are finished.
179  * @dev: device that's been disconnected
180  *
181  * Will be called only by the device core when all users of this usb device are
182  * done.
183  */
184 static void usb_release_dev(struct device *dev)
185 {
186         struct usb_device *udev;
187         struct usb_hcd *hcd;
188
189         udev = to_usb_device(dev);
190         hcd = bus_to_hcd(udev->bus);
191
192         usb_destroy_configuration(udev);
193         /* Root hubs aren't real devices, so don't free HCD resources */
194         if (hcd->driver->free_dev && udev->parent)
195                 hcd->driver->free_dev(hcd, udev);
196         usb_put_hcd(hcd);
197         kfree(udev->product);
198         kfree(udev->manufacturer);
199         kfree(udev->serial);
200         kfree(udev);
201 }
202
203 #ifdef  CONFIG_HOTPLUG
204 static int usb_dev_uevent(struct device *dev, struct kobj_uevent_env *env)
205 {
206         struct usb_device *usb_dev;
207
208         usb_dev = to_usb_device(dev);
209
210         if (add_uevent_var(env, "BUSNUM=%03d", usb_dev->bus->busnum))
211                 return -ENOMEM;
212
213         if (add_uevent_var(env, "DEVNUM=%03d", usb_dev->devnum))
214                 return -ENOMEM;
215
216         return 0;
217 }
218
219 #else
220
221 static int usb_dev_uevent(struct device *dev, struct kobj_uevent_env *env)
222 {
223         return -ENODEV;
224 }
225 #endif  /* CONFIG_HOTPLUG */
226
227 #ifdef  CONFIG_PM
228
229 static int ksuspend_usb_init(void)
230 {
231         /* This workqueue is supposed to be both freezable and
232          * singlethreaded.  Its job doesn't justify running on more
233          * than one CPU.
234          */
235         ksuspend_usb_wq = create_freezeable_workqueue("ksuspend_usbd");
236         if (!ksuspend_usb_wq)
237                 return -ENOMEM;
238         return 0;
239 }
240
241 static void ksuspend_usb_cleanup(void)
242 {
243         destroy_workqueue(ksuspend_usb_wq);
244 }
245
246 /* USB device Power-Management thunks.
247  * There's no need to distinguish here between quiescing a USB device
248  * and powering it down; the generic_suspend() routine takes care of
249  * it by skipping the usb_port_suspend() call for a quiesce.  And for
250  * USB interfaces there's no difference at all.
251  */
252
253 static int usb_dev_prepare(struct device *dev)
254 {
255         return 0;               /* Implement eventually? */
256 }
257
258 static void usb_dev_complete(struct device *dev)
259 {
260         /* Currently used only for rebinding interfaces */
261         usb_resume(dev, PMSG_RESUME);   /* Message event is meaningless */
262 }
263
264 static int usb_dev_suspend(struct device *dev)
265 {
266         return usb_suspend(dev, PMSG_SUSPEND);
267 }
268
269 static int usb_dev_resume(struct device *dev)
270 {
271         return usb_resume(dev, PMSG_RESUME);
272 }
273
274 static int usb_dev_freeze(struct device *dev)
275 {
276         return usb_suspend(dev, PMSG_FREEZE);
277 }
278
279 static int usb_dev_thaw(struct device *dev)
280 {
281         return usb_resume(dev, PMSG_THAW);
282 }
283
284 static int usb_dev_poweroff(struct device *dev)
285 {
286         return usb_suspend(dev, PMSG_HIBERNATE);
287 }
288
289 static int usb_dev_restore(struct device *dev)
290 {
291         return usb_resume(dev, PMSG_RESTORE);
292 }
293
294 static struct dev_pm_ops usb_device_pm_ops = {
295         .prepare =      usb_dev_prepare,
296         .complete =     usb_dev_complete,
297         .suspend =      usb_dev_suspend,
298         .resume =       usb_dev_resume,
299         .freeze =       usb_dev_freeze,
300         .thaw =         usb_dev_thaw,
301         .poweroff =     usb_dev_poweroff,
302         .restore =      usb_dev_restore,
303 };
304
305 #else
306
307 #define ksuspend_usb_init()     0
308 #define ksuspend_usb_cleanup()  do {} while (0)
309 #define usb_device_pm_ops       (*(struct dev_pm_ops *)0)
310
311 #endif  /* CONFIG_PM */
312
313 struct device_type usb_device_type = {
314         .name =         "usb_device",
315         .release =      usb_release_dev,
316         .uevent =       usb_dev_uevent,
317         .pm =           &usb_device_pm_ops,
318 };
319
320
321 /* Returns 1 if @usb_bus is WUSB, 0 otherwise */
322 static unsigned usb_bus_is_wusb(struct usb_bus *bus)
323 {
324         struct usb_hcd *hcd = container_of(bus, struct usb_hcd, self);
325         return hcd->wireless;
326 }
327
328
329 /**
330  * usb_alloc_dev - usb device constructor (usbcore-internal)
331  * @parent: hub to which device is connected; null to allocate a root hub
332  * @bus: bus used to access the device
333  * @port1: one-based index of port; ignored for root hubs
334  * Context: !in_interrupt()
335  *
336  * Only hub drivers (including virtual root hub drivers for host
337  * controllers) should ever call this.
338  *
339  * This call may not be used in a non-sleeping context.
340  */
341 struct usb_device *usb_alloc_dev(struct usb_device *parent,
342                                  struct usb_bus *bus, unsigned port1)
343 {
344         struct usb_device *dev;
345         struct usb_hcd *usb_hcd = container_of(bus, struct usb_hcd, self);
346         unsigned root_hub = 0;
347
348         dev = kzalloc(sizeof(*dev), GFP_KERNEL);
349         if (!dev)
350                 return NULL;
351
352         if (!usb_get_hcd(bus_to_hcd(bus))) {
353                 kfree(dev);
354                 return NULL;
355         }
356         /* Root hubs aren't true devices, so don't allocate HCD resources */
357         if (usb_hcd->driver->alloc_dev && parent &&
358                 !usb_hcd->driver->alloc_dev(usb_hcd, dev)) {
359                 usb_put_hcd(bus_to_hcd(bus));
360                 kfree(dev);
361                 return NULL;
362         }
363
364         device_initialize(&dev->dev);
365         dev->dev.bus = &usb_bus_type;
366         dev->dev.type = &usb_device_type;
367         dev->dev.groups = usb_device_groups;
368         dev->dev.dma_mask = bus->controller->dma_mask;
369         set_dev_node(&dev->dev, dev_to_node(bus->controller));
370         dev->state = USB_STATE_ATTACHED;
371         atomic_set(&dev->urbnum, 0);
372
373         INIT_LIST_HEAD(&dev->ep0.urb_list);
374         dev->ep0.desc.bLength = USB_DT_ENDPOINT_SIZE;
375         dev->ep0.desc.bDescriptorType = USB_DT_ENDPOINT;
376         /* ep0 maxpacket comes later, from device descriptor */
377         usb_enable_endpoint(dev, &dev->ep0, false);
378         dev->can_submit = 1;
379
380         /* Save readable and stable topology id, distinguishing devices
381          * by location for diagnostics, tools, driver model, etc.  The
382          * string is a path along hub ports, from the root.  Each device's
383          * dev->devpath will be stable until USB is re-cabled, and hubs
384          * are often labeled with these port numbers.  The name isn't
385          * as stable:  bus->busnum changes easily from modprobe order,
386          * cardbus or pci hotplugging, and so on.
387          */
388         if (unlikely(!parent)) {
389                 dev->devpath[0] = '0';
390                 dev->route = 0;
391
392                 dev->dev.parent = bus->controller;
393                 dev_set_name(&dev->dev, "usb%d", bus->busnum);
394                 root_hub = 1;
395         } else {
396                 /* match any labeling on the hubs; it's one-based */
397                 if (parent->devpath[0] == '0') {
398                         snprintf(dev->devpath, sizeof dev->devpath,
399                                 "%d", port1);
400                         /* Root ports are not counted in route string */
401                         dev->route = 0;
402                 } else {
403                         snprintf(dev->devpath, sizeof dev->devpath,
404                                 "%s.%d", parent->devpath, port1);
405                         dev->route = parent->route +
406                                 (port1 << ((parent->level - 1)*4));
407                 }
408
409                 dev->dev.parent = &parent->dev;
410                 dev_set_name(&dev->dev, "%d-%s", bus->busnum, dev->devpath);
411
412                 /* hub driver sets up TT records */
413         }
414
415         dev->portnum = port1;
416         dev->bus = bus;
417         dev->parent = parent;
418         INIT_LIST_HEAD(&dev->filelist);
419
420 #ifdef  CONFIG_PM
421         mutex_init(&dev->pm_mutex);
422         INIT_DELAYED_WORK(&dev->autosuspend, usb_autosuspend_work);
423         INIT_WORK(&dev->autoresume, usb_autoresume_work);
424         dev->autosuspend_delay = usb_autosuspend_delay * HZ;
425         dev->connect_time = jiffies;
426         dev->active_duration = -jiffies;
427 #endif
428         if (root_hub)   /* Root hub always ok [and always wired] */
429                 dev->authorized = 1;
430         else {
431                 dev->authorized = usb_hcd->authorized_default;
432                 dev->wusb = usb_bus_is_wusb(bus)? 1 : 0;
433         }
434         return dev;
435 }
436
437 /**
438  * usb_get_dev - increments the reference count of the usb device structure
439  * @dev: the device being referenced
440  *
441  * Each live reference to a device should be refcounted.
442  *
443  * Drivers for USB interfaces should normally record such references in
444  * their probe() methods, when they bind to an interface, and release
445  * them by calling usb_put_dev(), in their disconnect() methods.
446  *
447  * A pointer to the device with the incremented reference counter is returned.
448  */
449 struct usb_device *usb_get_dev(struct usb_device *dev)
450 {
451         if (dev)
452                 get_device(&dev->dev);
453         return dev;
454 }
455 EXPORT_SYMBOL_GPL(usb_get_dev);
456
457 /**
458  * usb_put_dev - release a use of the usb device structure
459  * @dev: device that's been disconnected
460  *
461  * Must be called when a user of a device is finished with it.  When the last
462  * user of the device calls this function, the memory of the device is freed.
463  */
464 void usb_put_dev(struct usb_device *dev)
465 {
466         if (dev)
467                 put_device(&dev->dev);
468 }
469 EXPORT_SYMBOL_GPL(usb_put_dev);
470
471 /**
472  * usb_get_intf - increments the reference count of the usb interface structure
473  * @intf: the interface being referenced
474  *
475  * Each live reference to a interface must be refcounted.
476  *
477  * Drivers for USB interfaces should normally record such references in
478  * their probe() methods, when they bind to an interface, and release
479  * them by calling usb_put_intf(), in their disconnect() methods.
480  *
481  * A pointer to the interface with the incremented reference counter is
482  * returned.
483  */
484 struct usb_interface *usb_get_intf(struct usb_interface *intf)
485 {
486         if (intf)
487                 get_device(&intf->dev);
488         return intf;
489 }
490 EXPORT_SYMBOL_GPL(usb_get_intf);
491
492 /**
493  * usb_put_intf - release a use of the usb interface structure
494  * @intf: interface that's been decremented
495  *
496  * Must be called when a user of an interface is finished with it.  When the
497  * last user of the interface calls this function, the memory of the interface
498  * is freed.
499  */
500 void usb_put_intf(struct usb_interface *intf)
501 {
502         if (intf)
503                 put_device(&intf->dev);
504 }
505 EXPORT_SYMBOL_GPL(usb_put_intf);
506
507 /*                      USB device locking
508  *
509  * USB devices and interfaces are locked using the semaphore in their
510  * embedded struct device.  The hub driver guarantees that whenever a
511  * device is connected or disconnected, drivers are called with the
512  * USB device locked as well as their particular interface.
513  *
514  * Complications arise when several devices are to be locked at the same
515  * time.  Only hub-aware drivers that are part of usbcore ever have to
516  * do this; nobody else needs to worry about it.  The rule for locking
517  * is simple:
518  *
519  *      When locking both a device and its parent, always lock the
520  *      the parent first.
521  */
522
523 /**
524  * usb_lock_device_for_reset - cautiously acquire the lock for a usb device structure
525  * @udev: device that's being locked
526  * @iface: interface bound to the driver making the request (optional)
527  *
528  * Attempts to acquire the device lock, but fails if the device is
529  * NOTATTACHED or SUSPENDED, or if iface is specified and the interface
530  * is neither BINDING nor BOUND.  Rather than sleeping to wait for the
531  * lock, the routine polls repeatedly.  This is to prevent deadlock with
532  * disconnect; in some drivers (such as usb-storage) the disconnect()
533  * or suspend() method will block waiting for a device reset to complete.
534  *
535  * Returns a negative error code for failure, otherwise 0.
536  */
537 int usb_lock_device_for_reset(struct usb_device *udev,
538                               const struct usb_interface *iface)
539 {
540         unsigned long jiffies_expire = jiffies + HZ;
541
542         if (udev->state == USB_STATE_NOTATTACHED)
543                 return -ENODEV;
544         if (udev->state == USB_STATE_SUSPENDED)
545                 return -EHOSTUNREACH;
546         if (iface && (iface->condition == USB_INTERFACE_UNBINDING ||
547                         iface->condition == USB_INTERFACE_UNBOUND))
548                 return -EINTR;
549
550         while (usb_trylock_device(udev) != 0) {
551
552                 /* If we can't acquire the lock after waiting one second,
553                  * we're probably deadlocked */
554                 if (time_after(jiffies, jiffies_expire))
555                         return -EBUSY;
556
557                 msleep(15);
558                 if (udev->state == USB_STATE_NOTATTACHED)
559                         return -ENODEV;
560                 if (udev->state == USB_STATE_SUSPENDED)
561                         return -EHOSTUNREACH;
562                 if (iface && (iface->condition == USB_INTERFACE_UNBINDING ||
563                                 iface->condition == USB_INTERFACE_UNBOUND))
564                         return -EINTR;
565         }
566         return 0;
567 }
568 EXPORT_SYMBOL_GPL(usb_lock_device_for_reset);
569
570 static struct usb_device *match_device(struct usb_device *dev,
571                                        u16 vendor_id, u16 product_id)
572 {
573         struct usb_device *ret_dev = NULL;
574         int child;
575
576         dev_dbg(&dev->dev, "check for vendor %04x, product %04x ...\n",
577             le16_to_cpu(dev->descriptor.idVendor),
578             le16_to_cpu(dev->descriptor.idProduct));
579
580         /* see if this device matches */
581         if ((vendor_id == le16_to_cpu(dev->descriptor.idVendor)) &&
582             (product_id == le16_to_cpu(dev->descriptor.idProduct))) {
583                 dev_dbg(&dev->dev, "matched this device!\n");
584                 ret_dev = usb_get_dev(dev);
585                 goto exit;
586         }
587
588         /* look through all of the children of this device */
589         for (child = 0; child < dev->maxchild; ++child) {
590                 if (dev->children[child]) {
591                         usb_lock_device(dev->children[child]);
592                         ret_dev = match_device(dev->children[child],
593                                                vendor_id, product_id);
594                         usb_unlock_device(dev->children[child]);
595                         if (ret_dev)
596                                 goto exit;
597                 }
598         }
599 exit:
600         return ret_dev;
601 }
602
603 /**
604  * usb_find_device - find a specific usb device in the system
605  * @vendor_id: the vendor id of the device to find
606  * @product_id: the product id of the device to find
607  *
608  * Returns a pointer to a struct usb_device if such a specified usb
609  * device is present in the system currently.  The usage count of the
610  * device will be incremented if a device is found.  Make sure to call
611  * usb_put_dev() when the caller is finished with the device.
612  *
613  * If a device with the specified vendor and product id is not found,
614  * NULL is returned.
615  */
616 struct usb_device *usb_find_device(u16 vendor_id, u16 product_id)
617 {
618         struct list_head *buslist;
619         struct usb_bus *bus;
620         struct usb_device *dev = NULL;
621
622         mutex_lock(&usb_bus_list_lock);
623         for (buslist = usb_bus_list.next;
624              buslist != &usb_bus_list;
625              buslist = buslist->next) {
626                 bus = container_of(buslist, struct usb_bus, bus_list);
627                 if (!bus->root_hub)
628                         continue;
629                 usb_lock_device(bus->root_hub);
630                 dev = match_device(bus->root_hub, vendor_id, product_id);
631                 usb_unlock_device(bus->root_hub);
632                 if (dev)
633                         goto exit;
634         }
635 exit:
636         mutex_unlock(&usb_bus_list_lock);
637         return dev;
638 }
639
640 /**
641  * usb_get_current_frame_number - return current bus frame number
642  * @dev: the device whose bus is being queried
643  *
644  * Returns the current frame number for the USB host controller
645  * used with the given USB device.  This can be used when scheduling
646  * isochronous requests.
647  *
648  * Note that different kinds of host controller have different
649  * "scheduling horizons".  While one type might support scheduling only
650  * 32 frames into the future, others could support scheduling up to
651  * 1024 frames into the future.
652  */
653 int usb_get_current_frame_number(struct usb_device *dev)
654 {
655         return usb_hcd_get_frame_number(dev);
656 }
657 EXPORT_SYMBOL_GPL(usb_get_current_frame_number);
658
659 /*-------------------------------------------------------------------*/
660 /*
661  * __usb_get_extra_descriptor() finds a descriptor of specific type in the
662  * extra field of the interface and endpoint descriptor structs.
663  */
664
665 int __usb_get_extra_descriptor(char *buffer, unsigned size,
666                                unsigned char type, void **ptr)
667 {
668         struct usb_descriptor_header *header;
669
670         while (size >= sizeof(struct usb_descriptor_header)) {
671                 header = (struct usb_descriptor_header *)buffer;
672
673                 if (header->bLength < 2) {
674                         printk(KERN_ERR
675                                 "%s: bogus descriptor, type %d length %d\n",
676                                 usbcore_name,
677                                 header->bDescriptorType,
678                                 header->bLength);
679                         return -1;
680                 }
681
682                 if (header->bDescriptorType == type) {
683                         *ptr = header;
684                         return 0;
685                 }
686
687                 buffer += header->bLength;
688                 size -= header->bLength;
689         }
690         return -1;
691 }
692 EXPORT_SYMBOL_GPL(__usb_get_extra_descriptor);
693
694 /**
695  * usb_buffer_alloc - allocate dma-consistent buffer for URB_NO_xxx_DMA_MAP
696  * @dev: device the buffer will be used with
697  * @size: requested buffer size
698  * @mem_flags: affect whether allocation may block
699  * @dma: used to return DMA address of buffer
700  *
701  * Return value is either null (indicating no buffer could be allocated), or
702  * the cpu-space pointer to a buffer that may be used to perform DMA to the
703  * specified device.  Such cpu-space buffers are returned along with the DMA
704  * address (through the pointer provided).
705  *
706  * These buffers are used with URB_NO_xxx_DMA_MAP set in urb->transfer_flags
707  * to avoid behaviors like using "DMA bounce buffers", or thrashing IOMMU
708  * hardware during URB completion/resubmit.  The implementation varies between
709  * platforms, depending on details of how DMA will work to this device.
710  * Using these buffers also eliminates cacheline sharing problems on
711  * architectures where CPU caches are not DMA-coherent.  On systems without
712  * bus-snooping caches, these buffers are uncached.
713  *
714  * When the buffer is no longer used, free it with usb_buffer_free().
715  */
716 void *usb_buffer_alloc(struct usb_device *dev, size_t size, gfp_t mem_flags,
717                        dma_addr_t *dma)
718 {
719         if (!dev || !dev->bus)
720                 return NULL;
721         return hcd_buffer_alloc(dev->bus, size, mem_flags, dma);
722 }
723 EXPORT_SYMBOL_GPL(usb_buffer_alloc);
724
725 /**
726  * usb_buffer_free - free memory allocated with usb_buffer_alloc()
727  * @dev: device the buffer was used with
728  * @size: requested buffer size
729  * @addr: CPU address of buffer
730  * @dma: DMA address of buffer
731  *
732  * This reclaims an I/O buffer, letting it be reused.  The memory must have
733  * been allocated using usb_buffer_alloc(), and the parameters must match
734  * those provided in that allocation request.
735  */
736 void usb_buffer_free(struct usb_device *dev, size_t size, void *addr,
737                      dma_addr_t dma)
738 {
739         if (!dev || !dev->bus)
740                 return;
741         if (!addr)
742                 return;
743         hcd_buffer_free(dev->bus, size, addr, dma);
744 }
745 EXPORT_SYMBOL_GPL(usb_buffer_free);
746
747 /**
748  * usb_buffer_map - create DMA mapping(s) for an urb
749  * @urb: urb whose transfer_buffer/setup_packet will be mapped
750  *
751  * Return value is either null (indicating no buffer could be mapped), or
752  * the parameter.  URB_NO_TRANSFER_DMA_MAP and URB_NO_SETUP_DMA_MAP are
753  * added to urb->transfer_flags if the operation succeeds.  If the device
754  * is connected to this system through a non-DMA controller, this operation
755  * always succeeds.
756  *
757  * This call would normally be used for an urb which is reused, perhaps
758  * as the target of a large periodic transfer, with usb_buffer_dmasync()
759  * calls to synchronize memory and dma state.
760  *
761  * Reverse the effect of this call with usb_buffer_unmap().
762  */
763 #if 0
764 struct urb *usb_buffer_map(struct urb *urb)
765 {
766         struct usb_bus          *bus;
767         struct device           *controller;
768
769         if (!urb
770                         || !urb->dev
771                         || !(bus = urb->dev->bus)
772                         || !(controller = bus->controller))
773                 return NULL;
774
775         if (controller->dma_mask) {
776                 urb->transfer_dma = dma_map_single(controller,
777                         urb->transfer_buffer, urb->transfer_buffer_length,
778                         usb_pipein(urb->pipe)
779                                 ? DMA_FROM_DEVICE : DMA_TO_DEVICE);
780                 if (usb_pipecontrol(urb->pipe))
781                         urb->setup_dma = dma_map_single(controller,
782                                         urb->setup_packet,
783                                         sizeof(struct usb_ctrlrequest),
784                                         DMA_TO_DEVICE);
785         /* FIXME generic api broken like pci, can't report errors */
786         /* if (urb->transfer_dma == DMA_ADDR_INVALID) return 0; */
787         } else
788                 urb->transfer_dma = ~0;
789         urb->transfer_flags |= (URB_NO_TRANSFER_DMA_MAP
790                                 | URB_NO_SETUP_DMA_MAP);
791         return urb;
792 }
793 EXPORT_SYMBOL_GPL(usb_buffer_map);
794 #endif  /*  0  */
795
796 /* XXX DISABLED, no users currently.  If you wish to re-enable this
797  * XXX please determine whether the sync is to transfer ownership of
798  * XXX the buffer from device to cpu or vice verse, and thusly use the
799  * XXX appropriate _for_{cpu,device}() method.  -DaveM
800  */
801 #if 0
802
803 /**
804  * usb_buffer_dmasync - synchronize DMA and CPU view of buffer(s)
805  * @urb: urb whose transfer_buffer/setup_packet will be synchronized
806  */
807 void usb_buffer_dmasync(struct urb *urb)
808 {
809         struct usb_bus          *bus;
810         struct device           *controller;
811
812         if (!urb
813                         || !(urb->transfer_flags & URB_NO_TRANSFER_DMA_MAP)
814                         || !urb->dev
815                         || !(bus = urb->dev->bus)
816                         || !(controller = bus->controller))
817                 return;
818
819         if (controller->dma_mask) {
820                 dma_sync_single_for_cpu(controller,
821                         urb->transfer_dma, urb->transfer_buffer_length,
822                         usb_pipein(urb->pipe)
823                                 ? DMA_FROM_DEVICE : DMA_TO_DEVICE);
824                 if (usb_pipecontrol(urb->pipe))
825                         dma_sync_single_for_cpu(controller,
826                                         urb->setup_dma,
827                                         sizeof(struct usb_ctrlrequest),
828                                         DMA_TO_DEVICE);
829         }
830 }
831 EXPORT_SYMBOL_GPL(usb_buffer_dmasync);
832 #endif
833
834 /**
835  * usb_buffer_unmap - free DMA mapping(s) for an urb
836  * @urb: urb whose transfer_buffer will be unmapped
837  *
838  * Reverses the effect of usb_buffer_map().
839  */
840 #if 0
841 void usb_buffer_unmap(struct urb *urb)
842 {
843         struct usb_bus          *bus;
844         struct device           *controller;
845
846         if (!urb
847                         || !(urb->transfer_flags & URB_NO_TRANSFER_DMA_MAP)
848                         || !urb->dev
849                         || !(bus = urb->dev->bus)
850                         || !(controller = bus->controller))
851                 return;
852
853         if (controller->dma_mask) {
854                 dma_unmap_single(controller,
855                         urb->transfer_dma, urb->transfer_buffer_length,
856                         usb_pipein(urb->pipe)
857                                 ? DMA_FROM_DEVICE : DMA_TO_DEVICE);
858                 if (usb_pipecontrol(urb->pipe))
859                         dma_unmap_single(controller,
860                                         urb->setup_dma,
861                                         sizeof(struct usb_ctrlrequest),
862                                         DMA_TO_DEVICE);
863         }
864         urb->transfer_flags &= ~(URB_NO_TRANSFER_DMA_MAP
865                                 | URB_NO_SETUP_DMA_MAP);
866 }
867 EXPORT_SYMBOL_GPL(usb_buffer_unmap);
868 #endif  /*  0  */
869
870 /**
871  * usb_buffer_map_sg - create scatterlist DMA mapping(s) for an endpoint
872  * @dev: device to which the scatterlist will be mapped
873  * @is_in: mapping transfer direction
874  * @sg: the scatterlist to map
875  * @nents: the number of entries in the scatterlist
876  *
877  * Return value is either < 0 (indicating no buffers could be mapped), or
878  * the number of DMA mapping array entries in the scatterlist.
879  *
880  * The caller is responsible for placing the resulting DMA addresses from
881  * the scatterlist into URB transfer buffer pointers, and for setting the
882  * URB_NO_TRANSFER_DMA_MAP transfer flag in each of those URBs.
883  *
884  * Top I/O rates come from queuing URBs, instead of waiting for each one
885  * to complete before starting the next I/O.   This is particularly easy
886  * to do with scatterlists.  Just allocate and submit one URB for each DMA
887  * mapping entry returned, stopping on the first error or when all succeed.
888  * Better yet, use the usb_sg_*() calls, which do that (and more) for you.
889  *
890  * This call would normally be used when translating scatterlist requests,
891  * rather than usb_buffer_map(), since on some hardware (with IOMMUs) it
892  * may be able to coalesce mappings for improved I/O efficiency.
893  *
894  * Reverse the effect of this call with usb_buffer_unmap_sg().
895  */
896 int usb_buffer_map_sg(const struct usb_device *dev, int is_in,
897                       struct scatterlist *sg, int nents)
898 {
899         struct usb_bus          *bus;
900         struct device           *controller;
901
902         if (!dev
903                         || !(bus = dev->bus)
904                         || !(controller = bus->controller)
905                         || !controller->dma_mask)
906                 return -1;
907
908         /* FIXME generic api broken like pci, can't report errors */
909         return dma_map_sg(controller, sg, nents,
910                         is_in ? DMA_FROM_DEVICE : DMA_TO_DEVICE);
911 }
912 EXPORT_SYMBOL_GPL(usb_buffer_map_sg);
913
914 /* XXX DISABLED, no users currently.  If you wish to re-enable this
915  * XXX please determine whether the sync is to transfer ownership of
916  * XXX the buffer from device to cpu or vice verse, and thusly use the
917  * XXX appropriate _for_{cpu,device}() method.  -DaveM
918  */
919 #if 0
920
921 /**
922  * usb_buffer_dmasync_sg - synchronize DMA and CPU view of scatterlist buffer(s)
923  * @dev: device to which the scatterlist will be mapped
924  * @is_in: mapping transfer direction
925  * @sg: the scatterlist to synchronize
926  * @n_hw_ents: the positive return value from usb_buffer_map_sg
927  *
928  * Use this when you are re-using a scatterlist's data buffers for
929  * another USB request.
930  */
931 void usb_buffer_dmasync_sg(const struct usb_device *dev, int is_in,
932                            struct scatterlist *sg, int n_hw_ents)
933 {
934         struct usb_bus          *bus;
935         struct device           *controller;
936
937         if (!dev
938                         || !(bus = dev->bus)
939                         || !(controller = bus->controller)
940                         || !controller->dma_mask)
941                 return;
942
943         dma_sync_sg_for_cpu(controller, sg, n_hw_ents,
944                             is_in ? DMA_FROM_DEVICE : DMA_TO_DEVICE);
945 }
946 EXPORT_SYMBOL_GPL(usb_buffer_dmasync_sg);
947 #endif
948
949 /**
950  * usb_buffer_unmap_sg - free DMA mapping(s) for a scatterlist
951  * @dev: device to which the scatterlist will be mapped
952  * @is_in: mapping transfer direction
953  * @sg: the scatterlist to unmap
954  * @n_hw_ents: the positive return value from usb_buffer_map_sg
955  *
956  * Reverses the effect of usb_buffer_map_sg().
957  */
958 void usb_buffer_unmap_sg(const struct usb_device *dev, int is_in,
959                          struct scatterlist *sg, int n_hw_ents)
960 {
961         struct usb_bus          *bus;
962         struct device           *controller;
963
964         if (!dev
965                         || !(bus = dev->bus)
966                         || !(controller = bus->controller)
967                         || !controller->dma_mask)
968                 return;
969
970         dma_unmap_sg(controller, sg, n_hw_ents,
971                         is_in ? DMA_FROM_DEVICE : DMA_TO_DEVICE);
972 }
973 EXPORT_SYMBOL_GPL(usb_buffer_unmap_sg);
974
975 /* To disable USB, kernel command line is 'nousb' not 'usbcore.nousb' */
976 #ifdef MODULE
977 module_param(nousb, bool, 0444);
978 #else
979 core_param(nousb, nousb, bool, 0444);
980 #endif
981
982 /*
983  * for external read access to <nousb>
984  */
985 int usb_disabled(void)
986 {
987         return nousb;
988 }
989 EXPORT_SYMBOL_GPL(usb_disabled);
990
991 /*
992  * Notifications of device and interface registration
993  */
994 static int usb_bus_notify(struct notifier_block *nb, unsigned long action,
995                 void *data)
996 {
997         struct device *dev = data;
998
999         switch (action) {
1000         case BUS_NOTIFY_ADD_DEVICE:
1001                 if (dev->type == &usb_device_type)
1002                         (void) usb_create_sysfs_dev_files(to_usb_device(dev));
1003                 else if (dev->type == &usb_if_device_type)
1004                         (void) usb_create_sysfs_intf_files(
1005                                         to_usb_interface(dev));
1006                 break;
1007
1008         case BUS_NOTIFY_DEL_DEVICE:
1009                 if (dev->type == &usb_device_type)
1010                         usb_remove_sysfs_dev_files(to_usb_device(dev));
1011                 else if (dev->type == &usb_if_device_type)
1012                         usb_remove_sysfs_intf_files(to_usb_interface(dev));
1013                 break;
1014         }
1015         return 0;
1016 }
1017
1018 static struct notifier_block usb_bus_nb = {
1019         .notifier_call = usb_bus_notify,
1020 };
1021
1022 struct dentry *usb_debug_root;
1023 EXPORT_SYMBOL_GPL(usb_debug_root);
1024
1025 struct dentry *usb_debug_devices;
1026
1027 static int usb_debugfs_init(void)
1028 {
1029         usb_debug_root = debugfs_create_dir("usb", NULL);
1030         if (!usb_debug_root)
1031                 return -ENOENT;
1032
1033         usb_debug_devices = debugfs_create_file("devices", 0444,
1034                                                 usb_debug_root, NULL,
1035                                                 &usbfs_devices_fops);
1036         if (!usb_debug_devices) {
1037                 debugfs_remove(usb_debug_root);
1038                 usb_debug_root = NULL;
1039                 return -ENOENT;
1040         }
1041
1042         return 0;
1043 }
1044
1045 static void usb_debugfs_cleanup(void)
1046 {
1047         debugfs_remove(usb_debug_devices);
1048         debugfs_remove(usb_debug_root);
1049 }
1050
1051 /*
1052  * Init
1053  */
1054 static int __init usb_init(void)
1055 {
1056         int retval;
1057         if (nousb) {
1058                 pr_info("%s: USB support disabled\n", usbcore_name);
1059                 return 0;
1060         }
1061
1062         retval = usb_debugfs_init();
1063         if (retval)
1064                 goto out;
1065
1066         retval = ksuspend_usb_init();
1067         if (retval)
1068                 goto out;
1069         retval = bus_register(&usb_bus_type);
1070         if (retval)
1071                 goto bus_register_failed;
1072         retval = bus_register_notifier(&usb_bus_type, &usb_bus_nb);
1073         if (retval)
1074                 goto bus_notifier_failed;
1075         retval = usb_major_init();
1076         if (retval)
1077                 goto major_init_failed;
1078         retval = usb_register(&usbfs_driver);
1079         if (retval)
1080                 goto driver_register_failed;
1081         retval = usb_devio_init();
1082         if (retval)
1083                 goto usb_devio_init_failed;
1084         retval = usbfs_init();
1085         if (retval)
1086                 goto fs_init_failed;
1087         retval = usb_hub_init();
1088         if (retval)
1089                 goto hub_init_failed;
1090         retval = usb_register_device_driver(&usb_generic_driver, THIS_MODULE);
1091         if (!retval)
1092                 goto out;
1093
1094         usb_hub_cleanup();
1095 hub_init_failed:
1096         usbfs_cleanup();
1097 fs_init_failed:
1098         usb_devio_cleanup();
1099 usb_devio_init_failed:
1100         usb_deregister(&usbfs_driver);
1101 driver_register_failed:
1102         usb_major_cleanup();
1103 major_init_failed:
1104         bus_unregister_notifier(&usb_bus_type, &usb_bus_nb);
1105 bus_notifier_failed:
1106         bus_unregister(&usb_bus_type);
1107 bus_register_failed:
1108         ksuspend_usb_cleanup();
1109 out:
1110         return retval;
1111 }
1112
1113 /*
1114  * Cleanup
1115  */
1116 static void __exit usb_exit(void)
1117 {
1118         /* This will matter if shutdown/reboot does exitcalls. */
1119         if (nousb)
1120                 return;
1121
1122         usb_deregister_device_driver(&usb_generic_driver);
1123         usb_major_cleanup();
1124         usbfs_cleanup();
1125         usb_deregister(&usbfs_driver);
1126         usb_devio_cleanup();
1127         usb_hub_cleanup();
1128         bus_unregister_notifier(&usb_bus_type, &usb_bus_nb);
1129         bus_unregister(&usb_bus_type);
1130         ksuspend_usb_cleanup();
1131         usb_debugfs_cleanup();
1132 }
1133
1134 subsys_initcall(usb_init);
1135 module_exit(usb_exit);
1136 MODULE_LICENSE("GPL");