- Linus: more PageDirty / swapcache handling
[davej-history.git] / drivers / usb / usb.c
blob7fc5e5cb32f2636c6723c26bf52d7956a083faff
1 /*
2 * drivers/usb/usb.c
4 * (C) Copyright Linus Torvalds 1999
5 * (C) Copyright Johannes Erdfelt 1999
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 (kernel hotplug, usb_device_id)
11 * (C) Copyright Yggdrasil Computing, Inc. 2000
12 * (usb_device_id matching changes by Adam J. Richter)
14 * NOTE! This is not actually a driver at all, rather this is
15 * just a collection of helper routines that implement the
16 * generic USB things that the real drivers can use..
18 * Think of this as a "USB library" rather than anything else.
19 * It should be considered a slave, with no callbacks. Callbacks
20 * are evil.
22 * $Id: usb.c,v 1.53 2000/01/14 16:19:09 acher Exp $
25 #include <linux/config.h>
26 #include <linux/module.h>
27 #include <linux/string.h>
28 #include <linux/bitops.h>
29 #include <linux/malloc.h>
30 #include <linux/interrupt.h> /* for in_interrupt() */
31 #include <linux/kmod.h>
32 #include <linux/init.h>
33 #include <linux/devfs_fs_kernel.h>
35 #ifdef CONFIG_USB_DEBUG
36 #define DEBUG
37 #else
38 #undef DEBUG
39 #endif
40 #include <linux/usb.h>
42 #define DEVNUM_ROUND_ROBIN /***** OPTION *****/
43 #ifdef DEVNUM_ROUND_ROBIN
44 static int devnum_next = 1;
45 #endif
47 static const int usb_bandwidth_option =
48 #ifdef CONFIG_USB_BANDWIDTH
50 #else
52 #endif
54 extern int usb_hub_init(void);
55 extern void usb_hub_cleanup(void);
58 * Prototypes for the device driver probing/loading functions
60 static void usb_find_drivers(struct usb_device *);
61 static int usb_find_interface_driver(struct usb_device *, unsigned int);
62 static void usb_check_support(struct usb_device *);
65 * We have a per-interface "registered driver" list.
67 LIST_HEAD(usb_driver_list);
68 LIST_HEAD(usb_bus_list);
70 devfs_handle_t usb_devfs_handle; /* /dev/usb dir. */
72 static struct usb_busmap busmap;
74 static struct usb_driver *usb_minors[16];
76 int usb_register(struct usb_driver *new_driver)
78 if (new_driver->fops != NULL) {
79 if (usb_minors[new_driver->minor/16]) {
80 err("error registering %s driver", new_driver->name);
81 return -EINVAL;
83 usb_minors[new_driver->minor/16] = new_driver;
86 info("registered new driver %s", new_driver->name);
88 init_MUTEX(&new_driver->serialize);
90 /* Add it to the list of known drivers */
91 list_add(&new_driver->driver_list, &usb_driver_list);
93 usb_scan_devices();
95 return 0;
99 * We go through all existing devices, and see if any of them would
100 * be acceptable to the new driver.. This is done using a depth-first
101 * search for devices without a registered driver already, then
102 * running 'probe' with each of the drivers registered on every one
103 * of these.
105 void usb_scan_devices(void)
107 struct list_head *tmp;
109 tmp = usb_bus_list.next;
110 while (tmp != &usb_bus_list) {
111 struct usb_bus *bus = list_entry(tmp,struct usb_bus, bus_list);
113 tmp = tmp->next;
114 usb_check_support(bus->root_hub);
119 * This function is part of a depth-first search down the device tree,
120 * removing any instances of a device driver.
122 static void usb_drivers_purge(struct usb_driver *driver,struct usb_device *dev)
124 int i;
126 if (!dev) {
127 err("null device being purged!!!");
128 return;
131 for (i=0; i<USB_MAXCHILDREN; i++)
132 if (dev->children[i])
133 usb_drivers_purge(driver, dev->children[i]);
135 if (!dev->actconfig)
136 return;
138 for (i = 0; i < dev->actconfig->bNumInterfaces; i++) {
139 struct usb_interface *interface = &dev->actconfig->interface[i];
141 if (interface->driver == driver) {
142 down(&driver->serialize);
143 driver->disconnect(dev, interface->private_data);
144 up(&driver->serialize);
145 usb_driver_release_interface(driver, interface);
147 * This will go through the list looking for another
148 * driver that can handle the device
150 usb_find_interface_driver(dev, i);
156 * Unlink a driver from the driver list when it is unloaded
158 void usb_deregister(struct usb_driver *driver)
160 struct list_head *tmp;
162 info("deregistering driver %s", driver->name);
163 if (driver->fops != NULL)
164 usb_minors[driver->minor/16] = NULL;
167 * first we remove the driver, to be sure it doesn't get used by
168 * another thread while we are stepping through removing entries
170 list_del(&driver->driver_list);
172 tmp = usb_bus_list.next;
173 while (tmp != &usb_bus_list) {
174 struct usb_bus *bus = list_entry(tmp,struct usb_bus,bus_list);
176 tmp = tmp->next;
177 usb_drivers_purge(driver, bus->root_hub);
181 struct usb_interface *usb_ifnum_to_if(struct usb_device *dev, unsigned ifnum)
183 int i;
185 for (i = 0; i < dev->actconfig->bNumInterfaces; i++)
186 if (dev->actconfig->interface[i].altsetting[0].bInterfaceNumber == ifnum)
187 return &dev->actconfig->interface[i];
189 return NULL;
192 struct usb_endpoint_descriptor *usb_epnum_to_ep_desc(struct usb_device *dev, unsigned epnum)
194 int i, j, k;
196 for (i = 0; i < dev->actconfig->bNumInterfaces; i++)
197 for (j = 0; j < dev->actconfig->interface[i].num_altsetting; j++)
198 for (k = 0; k < dev->actconfig->interface[i].altsetting[j].bNumEndpoints; k++)
199 if (epnum == dev->actconfig->interface[i].altsetting[j].endpoint[k].bEndpointAddress)
200 return &dev->actconfig->interface[i].altsetting[j].endpoint[k];
202 return NULL;
206 * usb_calc_bus_time:
208 * returns (approximate) USB bus time in nanoseconds for a USB transaction.
210 static long usb_calc_bus_time (int low_speed, int input_dir, int isoc, int bytecount)
212 unsigned long tmp;
214 if (low_speed) /* no isoc. here */
216 if (input_dir)
218 tmp = (67667L * (31L + 10L * BitTime (bytecount))) / 1000L;
219 return (64060L + (2 * BW_HUB_LS_SETUP) + BW_HOST_DELAY + tmp);
221 else
223 tmp = (66700L * (31L + 10L * BitTime (bytecount))) / 1000L;
224 return (64107L + (2 * BW_HUB_LS_SETUP) + BW_HOST_DELAY + tmp);
228 /* for full-speed: */
230 if (!isoc) /* Input or Output */
232 tmp = (8354L * (31L + 10L * BitTime (bytecount))) / 1000L;
233 return (9107L + BW_HOST_DELAY + tmp);
234 } /* end not Isoc */
236 /* for isoc: */
238 tmp = (8354L * (31L + 10L * BitTime (bytecount))) / 1000L;
239 return (((input_dir) ? 7268L : 6265L) + BW_HOST_DELAY + tmp);
243 * usb_check_bandwidth():
245 * old_alloc is from host_controller->bandwidth_allocated in microseconds;
246 * bustime is from calc_bus_time(), but converted to microseconds.
248 * returns <bustime in us> if successful,
249 * or USB_ST_BANDWIDTH_ERROR if bandwidth request fails.
251 * FIXME:
252 * This initial implementation does not use Endpoint.bInterval
253 * in managing bandwidth allocation.
254 * It probably needs to be expanded to use Endpoint.bInterval.
255 * This can be done as a later enhancement (correction).
256 * This will also probably require some kind of
257 * frame allocation tracking...meaning, for example,
258 * that if multiple drivers request interrupts every 10 USB frames,
259 * they don't all have to be allocated at
260 * frame numbers N, N+10, N+20, etc. Some of them could be at
261 * N+11, N+21, N+31, etc., and others at
262 * N+12, N+22, N+32, etc.
263 * However, this first cut at USB bandwidth allocation does not
264 * contain any frame allocation tracking.
266 int usb_check_bandwidth (struct usb_device *dev, struct urb *urb)
268 int new_alloc;
269 int old_alloc = dev->bus->bandwidth_allocated;
270 unsigned int pipe = urb->pipe;
271 long bustime;
273 bustime = usb_calc_bus_time (usb_pipeslow(pipe), usb_pipein(pipe),
274 usb_pipeisoc(pipe), usb_maxpacket(dev, pipe, usb_pipeout(pipe)));
275 if (usb_pipeisoc(pipe))
276 bustime = NS_TO_US(bustime) / urb->number_of_packets;
277 else
278 bustime = NS_TO_US(bustime);
280 new_alloc = old_alloc + (int)bustime;
281 /* what new total allocated bus time would be */
283 if (new_alloc > FRAME_TIME_MAX_USECS_ALLOC)
284 dbg("usb-check-bandwidth %sFAILED: was %u, would be %u, bustime = %ld us",
285 usb_bandwidth_option ? "" : "would have ",
286 old_alloc, new_alloc, bustime);
288 if (!usb_bandwidth_option) /* don't enforce it */
289 return (bustime);
290 return (new_alloc <= FRAME_TIME_MAX_USECS_ALLOC) ? bustime : USB_ST_BANDWIDTH_ERROR;
293 void usb_claim_bandwidth (struct usb_device *dev, struct urb *urb, int bustime, int isoc)
295 dev->bus->bandwidth_allocated += bustime;
296 if (isoc)
297 dev->bus->bandwidth_isoc_reqs++;
298 else
299 dev->bus->bandwidth_int_reqs++;
300 urb->bandwidth = bustime;
302 #ifdef USB_BANDWIDTH_MESSAGES
303 dbg("bandwidth alloc increased by %d to %d for %d requesters",
304 bustime,
305 dev->bus->bandwidth_allocated,
306 dev->bus->bandwidth_int_reqs + dev->bus->bandwidth_isoc_reqs);
307 #endif
311 * usb_release_bandwidth():
313 * called to release a pipe's bandwidth (in microseconds)
315 void usb_release_bandwidth(struct usb_device *dev, struct urb *urb, int isoc)
317 dev->bus->bandwidth_allocated -= urb->bandwidth;
318 if (isoc)
319 dev->bus->bandwidth_isoc_reqs--;
320 else
321 dev->bus->bandwidth_int_reqs--;
323 #ifdef USB_BANDWIDTH_MESSAGES
324 dbg("bandwidth alloc reduced by %d to %d for %d requesters",
325 urb->bandwidth,
326 dev->bus->bandwidth_allocated,
327 dev->bus->bandwidth_int_reqs + dev->bus->bandwidth_isoc_reqs);
328 #endif
329 urb->bandwidth = 0;
333 * New functions for (de)registering a controller
335 struct usb_bus *usb_alloc_bus(struct usb_operations *op)
337 struct usb_bus *bus;
339 bus = kmalloc(sizeof(*bus), GFP_KERNEL);
340 if (!bus)
341 return NULL;
343 memset(&bus->devmap, 0, sizeof(struct usb_devmap));
345 bus->op = op;
346 bus->root_hub = NULL;
347 bus->hcpriv = NULL;
348 bus->busnum = -1;
349 bus->bandwidth_allocated = 0;
350 bus->bandwidth_int_reqs = 0;
351 bus->bandwidth_isoc_reqs = 0;
353 INIT_LIST_HEAD(&bus->bus_list);
354 INIT_LIST_HEAD(&bus->inodes);
356 return bus;
359 void usb_free_bus(struct usb_bus *bus)
361 if (!bus)
362 return;
364 kfree(bus);
367 void usb_register_bus(struct usb_bus *bus)
369 int busnum;
371 busnum = find_next_zero_bit(busmap.busmap, USB_MAXBUS, 1);
372 if (busnum < USB_MAXBUS) {
373 set_bit(busnum, busmap.busmap);
374 bus->busnum = busnum;
375 } else
376 warn("too many buses");
378 /* Add it to the list of buses */
379 list_add(&bus->bus_list, &usb_bus_list);
381 usbdevfs_add_bus(bus);
383 info("new USB bus registered, assigned bus number %d", bus->busnum);
386 void usb_deregister_bus(struct usb_bus *bus)
388 info("USB bus %d deregistered", bus->busnum);
391 * NOTE: make sure that all the devices are removed by the
392 * controller code, as well as having it call this when cleaning
393 * itself up
395 list_del(&bus->bus_list);
397 usbdevfs_remove_bus(bus);
399 clear_bit(bus->busnum, busmap.busmap);
403 * This function is for doing a depth-first search for devices which
404 * have support, for dynamic loading of driver modules.
406 static void usb_check_support(struct usb_device *dev)
408 int i;
410 if (!dev) {
411 err("null device being checked!!!");
412 return;
415 for (i=0; i<USB_MAXCHILDREN; i++)
416 if (dev->children[i])
417 usb_check_support(dev->children[i]);
419 if (!dev->actconfig)
420 return;
422 /* now we check this device */
423 if (dev->devnum > 0)
424 for (i = 0; i < dev->actconfig->bNumInterfaces; i++)
425 usb_find_interface_driver(dev, i);
430 * This is intended to be used by usb device drivers that need to
431 * claim more than one interface on a device at once when probing
432 * (audio and acm are good examples). No device driver should have
433 * to mess with the internal usb_interface or usb_device structure
434 * members.
436 void usb_driver_claim_interface(struct usb_driver *driver, struct usb_interface *iface, void* priv)
438 if (!iface || !driver)
439 return;
441 dbg("%s driver claimed interface %p", driver->name, iface);
443 iface->driver = driver;
444 iface->private_data = priv;
445 } /* usb_driver_claim_interface() */
448 * This should be used by drivers to check other interfaces to see if
449 * they are available or not.
451 int usb_interface_claimed(struct usb_interface *iface)
453 if (!iface)
454 return 0;
456 return (iface->driver != NULL);
457 } /* usb_interface_claimed() */
460 * This should be used by drivers to release their claimed interfaces
462 void usb_driver_release_interface(struct usb_driver *driver, struct usb_interface *iface)
464 /* this should never happen, don't release something that's not ours */
465 if (!iface || iface->driver != driver)
466 return;
468 iface->driver = NULL;
469 iface->private_data = NULL;
473 /* usb_match_id searches an array of usb_device_id's and returns
474 the first one that matches the device and interface.
476 Parameters:
477 "id" is an array of usb_device_id's is terminated by an entry
478 containing all zeroes.
480 "dev" and "interface" are the device and interface for which
481 a match is sought.
483 If no match is found or if the "id" pointer is NULL, then
484 usb_match_id returns NULL.
487 What constitutes a match:
489 A zero in any element of a usb_device_id entry is a wildcard
490 (i.e., that field always matches). For there to be a match,
491 *every* nonzero element of the usb_device_id must match the
492 provided device and interface in. The comparison is for equality,
493 except for one pair of fields: usb_match_id.bcdDevice_{lo,hi} define
494 an inclusive range that dev->descriptor.bcdDevice must be in.
496 If interface->altsettings does not exist (i.e., there are no
497 interfaces defined), then bInterface{Class,SubClass,Protocol}
498 only match if they are all zeroes.
501 What constitutes a good "usb_device_id"?
503 The match algorithm is very simple, so that intelligence in
504 driver selection must come from smart driver id records.
505 Unless you have good reasons to use another selection policy,
506 provide match elements only in related groups:
508 * device specifiers (vendor and product IDs; and maybe
509 a revision range for that product);
510 * generic device specs (class/subclass/protocol);
511 * interface specs (class/subclass/protocol).
513 Within those groups, work from least specific to most specific.
514 For example, don't give a product version range without vendor
515 and product IDs.
517 "driver_info" is not considered by the kernel matching algorithm,
518 but you can create a wildcard "matches anything" usb_device_id
519 as your driver's "modules.usbmap" entry if you provide only an
520 id with a nonzero "driver_info" field.
523 const struct usb_device_id *
524 usb_match_id(struct usb_device *dev, struct usb_interface *interface,
525 const struct usb_device_id *id)
527 struct usb_interface_descriptor *intf = 0;
529 /* proc_connectinfo in devio.c may call us with id == NULL. */
530 if (id == NULL)
531 return NULL;
533 /* It is important to check that id->driver_info is nonzero,
534 since an entry that is all zeroes except for a nonzero
535 id->driver_info is the way to create an entry that
536 indicates that the driver want to examine every
537 device and interface. */
538 for (; id->idVendor || id->bDeviceClass || id->bInterfaceClass ||
539 id->driver_info; id++) {
541 if (id->idVendor &&
542 id->idVendor != dev->descriptor.idVendor)
543 continue;
545 if (id->idProduct &&
546 id->idProduct != dev->descriptor.idProduct)
547 continue;
549 /* No need to test id->bcdDevice_lo != 0, since 0 is never
550 greater than any unsigned number. */
551 if (id->bcdDevice_lo > dev->descriptor.bcdDevice)
552 continue;
554 if (id->bcdDevice_hi &&
555 id->bcdDevice_hi < dev->descriptor.bcdDevice)
556 continue;
558 if (id->bDeviceClass &&
559 id->bDeviceClass != dev->descriptor.bDeviceClass)
560 continue;
562 if (id->bDeviceSubClass &&
563 id->bDeviceSubClass!= dev->descriptor.bDeviceClass)
564 continue;
566 if (id->bDeviceProtocol &&
567 id->bDeviceProtocol != dev->descriptor.bDeviceProtocol)
568 continue;
570 intf = &interface->altsetting [interface->act_altsetting];
572 if (id->bInterfaceClass
573 && id->bInterfaceClass != intf->bInterfaceClass)
574 continue;
576 if (id->bInterfaceSubClass &&
577 id->bInterfaceSubClass != intf->bInterfaceSubClass)
578 continue;
580 if (id->bInterfaceProtocol
581 && id->bInterfaceProtocol != intf->bInterfaceProtocol)
582 continue;
584 return id;
587 return NULL;
591 * This entrypoint gets called for each new device.
593 * We now walk the list of registered USB drivers,
594 * looking for one that will accept this interface.
596 * "New Style" drivers use a table describing the devices and interfaces
597 * they handle. Those tables are available to user mode tools deciding
598 * whether to load driver modules for a new device.
600 * The probe return value is changed to be a private pointer. This way
601 * the drivers don't have to dig around in our structures to set the
602 * private pointer if they only need one interface.
604 * Returns: 0 if a driver accepted the interface, -1 otherwise
606 static int usb_find_interface_driver(struct usb_device *dev, unsigned ifnum)
608 struct list_head *tmp;
609 struct usb_interface *interface;
610 void *private;
611 const struct usb_device_id *id;
612 struct usb_driver *driver;
613 int i;
615 if ((!dev) || (ifnum >= dev->actconfig->bNumInterfaces)) {
616 err("bad find_interface_driver params");
617 return -1;
620 interface = dev->actconfig->interface + ifnum;
622 if (usb_interface_claimed(interface))
623 return -1;
625 private = NULL;
626 for (tmp = usb_driver_list.next; tmp != &usb_driver_list;) {
628 driver = list_entry(tmp, struct usb_driver, driver_list);
629 tmp = tmp->next;
631 down(&driver->serialize);
632 id = driver->id_table;
633 /* new style driver? */
634 if (id) {
635 for (i = 0; i < interface->num_altsetting; i++) {
636 interface->act_altsetting = i;
637 id = usb_match_id(dev, interface, id);
638 if (id) {
639 private = driver->probe(dev,ifnum,id);
640 if (private != NULL)
641 break;
644 /* if driver not bound, leave defaults unchanged */
645 if (private == NULL)
646 interface->act_altsetting = 0;
648 else /* "old style" driver */
649 private = driver->probe(dev, ifnum, NULL);
651 up(&driver->serialize);
652 if (private) {
653 usb_driver_claim_interface(driver, interface, private);
654 return 0;
658 return -1;
662 #ifdef CONFIG_HOTPLUG
665 * USB hotplugging invokes what /proc/sys/kernel/hotplug says
666 * (normally /sbin/hotplug) when USB devices get added or removed.
668 * This invokes a user mode policy agent, typically helping to load driver
669 * or other modules, configure the device, and more. Drivers can provide
670 * a MODULE_DEVICE_TABLE to help with module loading subtasks.
672 * Some synchronization is important: removes can't start processing
673 * before the add-device processing completes, and vice versa. That keeps
674 * a stack of USB-related identifiers stable while they're in use. If we
675 * know that agents won't complete after they return (such as by forking
676 * a process that completes later), it's enough to just waitpid() for the
677 * agent -- as is currently done.
679 * The reason: we know we're called either from khubd (the typical case)
680 * or from root hub initialization (init, kapmd, modprobe, etc). In both
681 * cases, we know no other thread can recycle our address, since we must
682 * already have been serialized enough to prevent that.
684 static void call_policy (char *verb, struct usb_device *dev)
686 char *argv [3], **envp, *buf, *scratch;
687 int i = 0, value;
689 if (!hotplug_path [0])
690 return;
691 if (in_interrupt ()) {
692 dbg ("In_interrupt");
693 return;
695 if (!current->fs->root) {
696 /* statically linked USB is initted rather early */
697 dbg ("call_policy %s, num %d -- no FS yet", verb, dev->devnum);
698 return;
700 if (dev->devnum < 0) {
701 dbg ("device already deleted ??");
702 return;
704 if (!(envp = (char **) kmalloc (20 * sizeof (char *), GFP_KERNEL))) {
705 dbg ("enomem");
706 return;
708 if (!(buf = kmalloc (256, GFP_KERNEL))) {
709 kfree (envp);
710 dbg ("enomem2");
711 return;
714 /* only one standardized param to hotplug command: type */
715 argv [0] = hotplug_path;
716 argv [1] = "usb";
717 argv [2] = 0;
719 /* minimal command environment */
720 envp [i++] = "HOME=/";
721 envp [i++] = "PATH=/sbin:/bin:/usr/sbin:/usr/bin";
723 #ifdef DEBUG
724 /* hint that policy agent should enter no-stdout debug mode */
725 envp [i++] = "DEBUG=kernel";
726 #endif
727 /* extensible set of named bus-specific parameters,
728 * supporting multiple driver selection algorithms.
730 scratch = buf;
732 /* action: add, remove */
733 envp [i++] = scratch;
734 scratch += sprintf (scratch, "ACTION=%s", verb) + 1;
736 #ifdef CONFIG_USB_DEVICEFS
737 /* If this is available, userspace programs can directly read
738 * all the device descriptors we don't tell them about. Or
739 * even act as usermode drivers.
741 * FIXME reduce hardwired intelligence here
743 envp [i++] = "DEVFS=/proc/bus/usb";
744 envp [i++] = scratch;
745 scratch += sprintf (scratch, "DEVICE=/proc/bus/usb/%03d/%03d",
746 dev->bus->busnum, dev->devnum) + 1;
747 #endif
749 /* per-device configuration hacks are common */
750 envp [i++] = scratch;
751 scratch += sprintf (scratch, "PRODUCT=%x/%x/%x",
752 dev->descriptor.idVendor,
753 dev->descriptor.idProduct,
754 dev->descriptor.bcdDevice) + 1;
756 /* class-based driver binding models */
757 envp [i++] = scratch;
758 scratch += sprintf (scratch, "TYPE=%d/%d/%d",
759 dev->descriptor.bDeviceClass,
760 dev->descriptor.bDeviceSubClass,
761 dev->descriptor.bDeviceProtocol) + 1;
762 if (dev->descriptor.bDeviceClass == 0) {
763 int alt = dev->actconfig->interface [0].act_altsetting;
765 /* a simple/common case: one config, one interface, one driver
766 * with current altsetting being a reasonable setting.
767 * everything needs a smart agent and usbdevfs; or can rely on
768 * device-specific binding policies.
770 envp [i++] = scratch;
771 scratch += sprintf (scratch, "INTERFACE=%d/%d/%d",
772 dev->actconfig->interface [0].altsetting [alt].bInterfaceClass,
773 dev->actconfig->interface [0].altsetting [alt].bInterfaceSubClass,
774 dev->actconfig->interface [0].altsetting [alt].bInterfaceProtocol)
775 + 1;
776 /* INTERFACE-0, INTERFACE-1, ... ? */
778 envp [i++] = 0;
779 /* assert: (scratch - buf) < sizeof buf */
781 /* NOTE: user mode daemons can call the agents too */
783 dbg ("kusbd: %s %s %d", argv [0], verb, dev->devnum);
784 value = call_usermodehelper (argv [0], argv, envp);
785 kfree (buf);
786 kfree (envp);
787 if (value != 0)
788 dbg ("kusbd policy returned 0x%x", value);
791 #else
793 static inline void
794 call_policy (char *verb, struct usb_device *dev)
795 { }
797 #endif /* KMOD */
801 * This entrypoint gets called for each new device.
803 * All interfaces are scanned for matching drivers.
805 static void usb_find_drivers(struct usb_device *dev)
807 unsigned ifnum;
808 unsigned rejected = 0;
809 unsigned claimed = 0;
811 for (ifnum = 0; ifnum < dev->actconfig->bNumInterfaces; ifnum++) {
812 /* if this interface hasn't already been claimed */
813 if (!usb_interface_claimed(dev->actconfig->interface + ifnum)) {
814 if (usb_find_interface_driver(dev, ifnum))
815 rejected++;
816 else
817 claimed++;
821 if (rejected)
822 dbg("unhandled interfaces on device");
824 if (!claimed) {
825 warn("USB device %d (vend/prod 0x%x/0x%x) is not claimed by any active driver.",
826 dev->devnum,
827 dev->descriptor.idVendor,
828 dev->descriptor.idProduct);
829 #ifdef DEBUG
830 usb_show_device(dev);
831 #endif
836 * Only HC's should call usb_alloc_dev and usb_free_dev directly
837 * Anybody may use usb_inc_dev_use or usb_dec_dev_use
839 struct usb_device *usb_alloc_dev(struct usb_device *parent, struct usb_bus *bus)
841 struct usb_device *dev;
843 dev = kmalloc(sizeof(*dev), GFP_KERNEL);
844 if (!dev)
845 return NULL;
847 memset(dev, 0, sizeof(*dev));
849 dev->bus = bus;
850 dev->parent = parent;
851 atomic_set(&dev->refcnt, 1);
852 INIT_LIST_HEAD(&dev->inodes);
853 INIT_LIST_HEAD(&dev->filelist);
855 dev->bus->op->allocate(dev);
857 return dev;
860 void usb_free_dev(struct usb_device *dev)
862 if (atomic_dec_and_test(&dev->refcnt)) {
863 dev->bus->op->deallocate(dev);
864 usb_destroy_configuration(dev);
865 kfree(dev);
869 void usb_inc_dev_use(struct usb_device *dev)
871 atomic_inc(&dev->refcnt);
874 /* -------------------------------------------------------------------------------------
875 * New USB Core Functions
876 * -------------------------------------------------------------------------------------*/
878 urb_t *usb_alloc_urb(int iso_packets)
880 urb_t *urb;
882 urb = (urb_t *)kmalloc(sizeof(urb_t) + iso_packets * sizeof(iso_packet_descriptor_t),
883 in_interrupt() ? GFP_ATOMIC : GFP_KERNEL);
884 if (!urb) {
885 err("alloc_urb: kmalloc failed");
886 return NULL;
889 memset(urb, 0, sizeof(*urb));
891 spin_lock_init(&urb->lock);
893 return urb;
896 /*-------------------------------------------------------------------*/
897 void usb_free_urb(urb_t* urb)
899 if (urb)
900 kfree(urb);
902 /*-------------------------------------------------------------------*/
903 int usb_submit_urb(urb_t *urb)
905 if (urb && urb->dev)
906 return urb->dev->bus->op->submit_urb(urb);
907 else
908 return -ENODEV;
911 /*-------------------------------------------------------------------*/
912 int usb_unlink_urb(urb_t *urb)
914 if (urb && urb->dev)
915 return urb->dev->bus->op->unlink_urb(urb);
916 else
917 return -ENODEV;
919 /*-------------------------------------------------------------------*
920 * COMPLETION HANDLERS *
921 *-------------------------------------------------------------------*/
923 /*-------------------------------------------------------------------*
924 * completion handler for compatibility wrappers (sync control/bulk) *
925 *-------------------------------------------------------------------*/
926 static void usb_api_blocking_completion(urb_t *urb)
928 api_wrapper_data *awd = (api_wrapper_data *)urb->context;
930 if (waitqueue_active(awd->wakeup))
931 wake_up(awd->wakeup);
932 #if 0
933 else
934 dbg("(blocking_completion): waitqueue empty!");
935 // even occurs if urb was unlinked by timeout...
936 #endif
939 /*-------------------------------------------------------------------*
940 * COMPATIBILITY STUFF *
941 *-------------------------------------------------------------------*/
943 // Starts urb and waits for completion or timeout
944 static int usb_start_wait_urb(urb_t *urb, int timeout, int* actual_length)
946 DECLARE_WAITQUEUE(wait, current);
947 DECLARE_WAIT_QUEUE_HEAD(wqh);
948 api_wrapper_data awd;
949 int status;
951 awd.wakeup = &wqh;
952 init_waitqueue_head(&wqh);
953 current->state = TASK_INTERRUPTIBLE;
954 add_wait_queue(&wqh, &wait);
955 urb->context = &awd;
956 status = usb_submit_urb(urb);
957 if (status) {
958 // something went wrong
959 usb_free_urb(urb);
960 current->state = TASK_RUNNING;
961 remove_wait_queue(&wqh, &wait);
962 return status;
965 if (urb->status == -EINPROGRESS) {
966 while (timeout && urb->status == -EINPROGRESS)
967 status = timeout = schedule_timeout(timeout);
968 } else
969 status = 1;
971 current->state = TASK_RUNNING;
972 remove_wait_queue(&wqh, &wait);
974 if (!status) {
975 // timeout
976 printk("usb_control/bulk_msg: timeout\n");
977 usb_unlink_urb(urb); // remove urb safely
978 status = -ETIMEDOUT;
979 } else
980 status = urb->status;
982 if (actual_length)
983 *actual_length = urb->actual_length;
985 usb_free_urb(urb);
986 return status;
989 /*-------------------------------------------------------------------*/
990 // returns status (negative) or length (positive)
991 int usb_internal_control_msg(struct usb_device *usb_dev, unsigned int pipe,
992 devrequest *cmd, void *data, int len, int timeout)
994 urb_t *urb;
995 int retv;
996 int length;
998 urb = usb_alloc_urb(0);
999 if (!urb)
1000 return -ENOMEM;
1002 FILL_CONTROL_URB(urb, usb_dev, pipe, (unsigned char*)cmd, data, len, /* build urb */
1003 (usb_complete_t)usb_api_blocking_completion,0);
1005 retv = usb_start_wait_urb(urb, timeout, &length);
1006 if (retv < 0)
1007 return retv;
1008 else
1009 return length;
1013 /*-------------------------------------------------------------------*/
1014 /* usb_control_msg() - builds control urb, and waits for completion */
1015 /* Synchronous behavior - don't use this function from within an */
1016 /* interrupt context, (like a bottom half handler.) In this case, */
1017 /* use usb_submit_urb() directly instead. */
1019 int usb_control_msg(struct usb_device *dev, unsigned int pipe, __u8 request, __u8 requesttype,
1020 __u16 value, __u16 index, void *data, __u16 size, int timeout)
1022 devrequest *dr = kmalloc(sizeof(devrequest), GFP_KERNEL);
1023 int ret;
1025 if (!dr)
1026 return -ENOMEM;
1028 dr->requesttype = requesttype;
1029 dr->request = request;
1030 dr->value = cpu_to_le16p(&value);
1031 dr->index = cpu_to_le16p(&index);
1032 dr->length = cpu_to_le16p(&size);
1034 //dbg("usb_control_msg");
1036 ret = usb_internal_control_msg(dev, pipe, dr, data, size, timeout);
1038 kfree(dr);
1040 return ret;
1043 /*-------------------------------------------------------------------*/
1044 /* usb_bulk_msg() Builds a bulk urb, and waits for completion. */
1045 /* Synchronous behavior - don't use this function from within an */
1046 /* interrupt context, (like a bottom half handler.) In this case, */
1047 /* use usb_submit_urb() directly instead. */
1049 int usb_bulk_msg(struct usb_device *usb_dev, unsigned int pipe,
1050 void *data, int len, int *actual_length, int timeout)
1052 urb_t *urb;
1054 if (len < 0)
1055 return -EINVAL;
1057 urb=usb_alloc_urb(0);
1058 if (!urb)
1059 return -ENOMEM;
1061 FILL_BULK_URB(urb,usb_dev,pipe,(unsigned char*)data,len, /* build urb */
1062 (usb_complete_t)usb_api_blocking_completion,0);
1064 return usb_start_wait_urb(urb,timeout,actual_length);
1068 * usb_get_current_frame_number()
1070 * returns the current frame number for the parent USB bus/controller
1071 * of the given USB device.
1073 int usb_get_current_frame_number(struct usb_device *usb_dev)
1075 return usb_dev->bus->op->get_frame_number (usb_dev);
1077 /*-------------------------------------------------------------------*/
1079 static int usb_parse_endpoint(struct usb_device *dev, struct usb_endpoint_descriptor *endpoint, unsigned char *buffer, int size)
1081 struct usb_descriptor_header *header;
1082 unsigned char *begin;
1083 int parsed = 0, len, numskipped;
1085 header = (struct usb_descriptor_header *)buffer;
1087 /* Everything should be fine being passed into here, but we sanity */
1088 /* check JIC */
1089 if (header->bLength > size) {
1090 err("ran out of descriptors parsing");
1091 return -1;
1094 if (header->bDescriptorType != USB_DT_ENDPOINT) {
1095 warn("unexpected descriptor 0x%X, expecting endpoint descriptor, type 0x%X",
1096 endpoint->bDescriptorType, USB_DT_ENDPOINT);
1097 return parsed;
1100 if (header->bLength == USB_DT_ENDPOINT_AUDIO_SIZE)
1101 memcpy(endpoint, buffer, USB_DT_ENDPOINT_AUDIO_SIZE);
1102 else
1103 memcpy(endpoint, buffer, USB_DT_ENDPOINT_SIZE);
1105 le16_to_cpus(&endpoint->wMaxPacketSize);
1107 buffer += header->bLength;
1108 size -= header->bLength;
1109 parsed += header->bLength;
1111 /* Skip over the rest of the Class Specific or Vendor Specific */
1112 /* descriptors */
1113 begin = buffer;
1114 numskipped = 0;
1115 while (size >= sizeof(struct usb_descriptor_header)) {
1116 header = (struct usb_descriptor_header *)buffer;
1118 if (header->bLength < 2) {
1119 err("invalid descriptor length of %d", header->bLength);
1120 return -1;
1123 /* If we find another descriptor which is at or below us */
1124 /* in the descriptor heirarchy then we're done */
1125 if ((header->bDescriptorType == USB_DT_ENDPOINT) ||
1126 (header->bDescriptorType == USB_DT_INTERFACE) ||
1127 (header->bDescriptorType == USB_DT_CONFIG) ||
1128 (header->bDescriptorType == USB_DT_DEVICE))
1129 break;
1131 dbg("skipping descriptor 0x%X",
1132 header->bDescriptorType);
1133 numskipped++;
1135 buffer += header->bLength;
1136 size -= header->bLength;
1137 parsed += header->bLength;
1139 if (numskipped)
1140 dbg("skipped %d class/vendor specific endpoint descriptors", numskipped);
1142 /* Copy any unknown descriptors into a storage area for drivers */
1143 /* to later parse */
1144 len = (int)(buffer - begin);
1145 if (!len) {
1146 endpoint->extra = NULL;
1147 endpoint->extralen = 0;
1148 return parsed;
1151 endpoint->extra = kmalloc(len, GFP_KERNEL);
1153 if (!endpoint->extra) {
1154 err("couldn't allocate memory for endpoint extra descriptors");
1155 endpoint->extralen = 0;
1156 return parsed;
1159 memcpy(endpoint->extra, begin, len);
1160 endpoint->extralen = len;
1162 return parsed;
1165 static int usb_parse_interface(struct usb_device *dev, struct usb_interface *interface, unsigned char *buffer, int size)
1167 int i, len, numskipped, retval, parsed = 0;
1168 struct usb_descriptor_header *header;
1169 struct usb_interface_descriptor *ifp;
1170 unsigned char *begin;
1172 interface->act_altsetting = 0;
1173 interface->num_altsetting = 0;
1174 interface->max_altsetting = USB_ALTSETTINGALLOC;
1176 interface->altsetting = kmalloc(sizeof(struct usb_interface_descriptor) * interface->max_altsetting, GFP_KERNEL);
1178 if (!interface->altsetting) {
1179 err("couldn't kmalloc interface->altsetting");
1180 return -1;
1183 while (size > 0) {
1184 if (interface->num_altsetting >= interface->max_altsetting) {
1185 void *ptr;
1186 int oldmas;
1188 oldmas = interface->max_altsetting;
1189 interface->max_altsetting += USB_ALTSETTINGALLOC;
1190 if (interface->max_altsetting > USB_MAXALTSETTING) {
1191 warn("too many alternate settings (max %d)",
1192 USB_MAXALTSETTING);
1193 return -1;
1196 ptr = interface->altsetting;
1197 interface->altsetting = kmalloc(sizeof(struct usb_interface_descriptor) * interface->max_altsetting, GFP_KERNEL);
1198 if (!interface->altsetting) {
1199 err("couldn't kmalloc interface->altsetting");
1200 interface->altsetting = ptr;
1201 return -1;
1203 memcpy(interface->altsetting, ptr, sizeof(struct usb_interface_descriptor) * oldmas);
1205 kfree(ptr);
1208 ifp = interface->altsetting + interface->num_altsetting;
1209 interface->num_altsetting++;
1211 memcpy(ifp, buffer, USB_DT_INTERFACE_SIZE);
1213 /* Skip over the interface */
1214 buffer += ifp->bLength;
1215 parsed += ifp->bLength;
1216 size -= ifp->bLength;
1218 begin = buffer;
1219 numskipped = 0;
1221 /* Skip over any interface, class or vendor descriptors */
1222 while (size >= sizeof(struct usb_descriptor_header)) {
1223 header = (struct usb_descriptor_header *)buffer;
1225 if (header->bLength < 2) {
1226 err("invalid descriptor length of %d", header->bLength);
1227 return -1;
1230 /* If we find another descriptor which is at or below */
1231 /* us in the descriptor heirarchy then return */
1232 if ((header->bDescriptorType == USB_DT_INTERFACE) ||
1233 (header->bDescriptorType == USB_DT_ENDPOINT) ||
1234 (header->bDescriptorType == USB_DT_CONFIG) ||
1235 (header->bDescriptorType == USB_DT_DEVICE))
1236 break;
1238 numskipped++;
1240 buffer += header->bLength;
1241 parsed += header->bLength;
1242 size -= header->bLength;
1245 if (numskipped)
1246 dbg("skipped %d class/vendor specific interface descriptors", numskipped);
1248 /* Copy any unknown descriptors into a storage area for */
1249 /* drivers to later parse */
1250 len = (int)(buffer - begin);
1251 if (!len) {
1252 ifp->extra = NULL;
1253 ifp->extralen = 0;
1254 } else {
1255 ifp->extra = kmalloc(len, GFP_KERNEL);
1257 if (!ifp->extra) {
1258 err("couldn't allocate memory for interface extra descriptors");
1259 ifp->extralen = 0;
1260 return -1;
1262 memcpy(ifp->extra, begin, len);
1263 ifp->extralen = len;
1266 /* Did we hit an unexpected descriptor? */
1267 header = (struct usb_descriptor_header *)buffer;
1268 if ((size >= sizeof(struct usb_descriptor_header)) &&
1269 ((header->bDescriptorType == USB_DT_CONFIG) ||
1270 (header->bDescriptorType == USB_DT_DEVICE)))
1271 return parsed;
1273 if (ifp->bNumEndpoints > USB_MAXENDPOINTS) {
1274 warn("too many endpoints");
1275 return -1;
1278 ifp->endpoint = (struct usb_endpoint_descriptor *)
1279 kmalloc(ifp->bNumEndpoints *
1280 sizeof(struct usb_endpoint_descriptor), GFP_KERNEL);
1281 if (!ifp->endpoint) {
1282 err("out of memory");
1283 return -1;
1286 memset(ifp->endpoint, 0, ifp->bNumEndpoints *
1287 sizeof(struct usb_endpoint_descriptor));
1289 for (i = 0; i < ifp->bNumEndpoints; i++) {
1290 header = (struct usb_descriptor_header *)buffer;
1292 if (header->bLength > size) {
1293 err("ran out of descriptors parsing");
1294 return -1;
1297 retval = usb_parse_endpoint(dev, ifp->endpoint + i, buffer, size);
1298 if (retval < 0)
1299 return retval;
1301 buffer += retval;
1302 parsed += retval;
1303 size -= retval;
1306 /* We check to see if it's an alternate to this one */
1307 ifp = (struct usb_interface_descriptor *)buffer;
1308 if (size < USB_DT_INTERFACE_SIZE ||
1309 ifp->bDescriptorType != USB_DT_INTERFACE ||
1310 !ifp->bAlternateSetting)
1311 return parsed;
1314 return parsed;
1317 int usb_parse_configuration(struct usb_device *dev, struct usb_config_descriptor *config, char *buffer)
1319 int i, retval, size;
1320 struct usb_descriptor_header *header;
1322 memcpy(config, buffer, USB_DT_CONFIG_SIZE);
1323 le16_to_cpus(&config->wTotalLength);
1324 size = config->wTotalLength;
1326 if (config->bNumInterfaces > USB_MAXINTERFACES) {
1327 warn("too many interfaces");
1328 return -1;
1331 config->interface = (struct usb_interface *)
1332 kmalloc(config->bNumInterfaces *
1333 sizeof(struct usb_interface), GFP_KERNEL);
1334 dbg("kmalloc IF %p, numif %i", config->interface, config->bNumInterfaces);
1335 if (!config->interface) {
1336 err("out of memory");
1337 return -1;
1340 memset(config->interface, 0,
1341 config->bNumInterfaces * sizeof(struct usb_interface));
1343 buffer += config->bLength;
1344 size -= config->bLength;
1346 for (i = 0; i < config->bNumInterfaces; i++) {
1347 int numskipped, len;
1348 char *begin;
1350 /* Skip over the rest of the Class Specific or Vendor */
1351 /* Specific descriptors */
1352 begin = buffer;
1353 numskipped = 0;
1354 while (size >= sizeof(struct usb_descriptor_header)) {
1355 header = (struct usb_descriptor_header *)buffer;
1357 if ((header->bLength > size) || (header->bLength < 2)) {
1358 err("invalid descriptor length of %d", header->bLength);
1359 return -1;
1362 /* If we find another descriptor which is at or below */
1363 /* us in the descriptor heirarchy then we're done */
1364 if ((header->bDescriptorType == USB_DT_ENDPOINT) ||
1365 (header->bDescriptorType == USB_DT_INTERFACE) ||
1366 (header->bDescriptorType == USB_DT_CONFIG) ||
1367 (header->bDescriptorType == USB_DT_DEVICE))
1368 break;
1370 dbg("skipping descriptor 0x%X", header->bDescriptorType);
1371 numskipped++;
1373 buffer += header->bLength;
1374 size -= header->bLength;
1376 if (numskipped)
1377 dbg("skipped %d class/vendor specific endpoint descriptors", numskipped);
1379 /* Copy any unknown descriptors into a storage area for */
1380 /* drivers to later parse */
1381 len = (int)(buffer - begin);
1382 if (!len) {
1383 config->extra = NULL;
1384 config->extralen = 0;
1385 } else {
1386 config->extra = kmalloc(len, GFP_KERNEL);
1387 if (!config->extra) {
1388 err("couldn't allocate memory for config extra descriptors");
1389 config->extralen = 0;
1390 return -1;
1393 memcpy(config->extra, begin, len);
1394 config->extralen = len;
1397 retval = usb_parse_interface(dev, config->interface + i, buffer, size);
1398 if (retval < 0)
1399 return retval;
1401 buffer += retval;
1402 size -= retval;
1405 return size;
1408 void usb_destroy_configuration(struct usb_device *dev)
1410 int c, i, j, k;
1412 if (!dev->config)
1413 return;
1415 if (dev->rawdescriptors) {
1416 for (i = 0; i < dev->descriptor.bNumConfigurations; i++)
1417 kfree(dev->rawdescriptors[i]);
1419 kfree(dev->rawdescriptors);
1422 for (c = 0; c < dev->descriptor.bNumConfigurations; c++) {
1423 struct usb_config_descriptor *cf = &dev->config[c];
1425 if (!cf->interface)
1426 break;
1428 for (i = 0; i < cf->bNumInterfaces; i++) {
1429 struct usb_interface *ifp =
1430 &cf->interface[i];
1432 if (!ifp->altsetting)
1433 break;
1435 for (j = 0; j < ifp->num_altsetting; j++) {
1436 struct usb_interface_descriptor *as =
1437 &ifp->altsetting[j];
1439 if(as->extra) {
1440 kfree(as->extra);
1443 if (!as->endpoint)
1444 break;
1446 for(k = 0; k < as->bNumEndpoints; k++) {
1447 if(as->endpoint[k].extra) {
1448 kfree(as->endpoint[k].extra);
1451 kfree(as->endpoint);
1454 kfree(ifp->altsetting);
1456 kfree(cf->interface);
1458 kfree(dev->config);
1461 /* for returning string descriptors in UTF-16LE */
1462 static int ascii2utf (char *ascii, __u8 *utf, int utfmax)
1464 int retval;
1466 for (retval = 0; *ascii && utfmax > 1; utfmax -= 2, retval += 2) {
1467 *utf++ = *ascii++ & 0x7f;
1468 *utf++ = 0;
1470 return retval;
1474 * root_hub_string is used by each host controller's root hub code,
1475 * so that they're identified consistently throughout the system.
1477 int usb_root_hub_string (int id, int serial, char *type, __u8 *data, int len)
1479 char buf [30];
1481 // assert (len > (2 * (sizeof (buf) + 1)));
1482 // assert (strlen (type) <= 8);
1484 // language ids
1485 if (id == 0) {
1486 *data++ = 4; *data++ = 3; /* 4 bytes data */
1487 *data++ = 0; *data++ = 0; /* some language id */
1488 return 4;
1490 // serial number
1491 } else if (id == 1) {
1492 sprintf (buf, "%x", serial);
1494 // product description
1495 } else if (id == 2) {
1496 sprintf (buf, "USB %s Root Hub", type);
1498 // id 3 == vendor description
1500 // unsupported IDs --> "stall"
1501 } else
1502 return 0;
1504 data [0] = 2 + ascii2utf (buf, data + 2, len - 2);
1505 data [1] = 3;
1506 return data [0];
1510 * __usb_get_extra_descriptor() finds a descriptor of specific type in the
1511 * extra field of the interface and endpoint descriptor structs.
1514 int __usb_get_extra_descriptor(char *buffer, unsigned size, unsigned char type, void **ptr)
1516 struct usb_descriptor_header *header;
1518 while (size >= sizeof(struct usb_descriptor_header)) {
1519 header = (struct usb_descriptor_header *)buffer;
1521 if (header->bLength < 2) {
1522 err("invalid descriptor length of %d", header->bLength);
1523 return -1;
1526 if (header->bDescriptorType == type) {
1527 *ptr = header;
1528 return 0;
1531 buffer += header->bLength;
1532 size -= header->bLength;
1534 return -1;
1538 * Something got disconnected. Get rid of it, and all of its children.
1540 void usb_disconnect(struct usb_device **pdev)
1542 struct usb_device * dev = *pdev;
1543 int i;
1545 if (!dev)
1546 return;
1548 *pdev = NULL;
1550 info("USB disconnect on device %d", dev->devnum);
1552 if (dev->actconfig) {
1553 for (i = 0; i < dev->actconfig->bNumInterfaces; i++) {
1554 struct usb_interface *interface = &dev->actconfig->interface[i];
1555 struct usb_driver *driver = interface->driver;
1556 if (driver) {
1557 down(&driver->serialize);
1558 driver->disconnect(dev, interface->private_data);
1559 up(&driver->serialize);
1560 usb_driver_release_interface(driver, interface);
1565 /* Free up all the children.. */
1566 for (i = 0; i < USB_MAXCHILDREN; i++) {
1567 struct usb_device **child = dev->children + i;
1568 if (*child)
1569 usb_disconnect(child);
1572 /* Let policy agent unload modules etc */
1573 call_policy ("remove", dev);
1575 /* Free the device number and remove the /proc/bus/usb entry */
1576 if (dev->devnum > 0) {
1577 clear_bit(dev->devnum, &dev->bus->devmap.devicemap);
1578 usbdevfs_remove_device(dev);
1581 /* Free up the device itself */
1582 usb_free_dev(dev);
1586 * Connect a new USB device. This basically just initializes
1587 * the USB device information and sets up the topology - it's
1588 * up to the low-level driver to reset the port and actually
1589 * do the setup (the upper levels don't know how to do that).
1591 void usb_connect(struct usb_device *dev)
1593 int devnum;
1594 // FIXME needs locking for SMP!!
1595 /* why? this is called only from the hub thread,
1596 * which hopefully doesn't run on multiple CPU's simultaneously 8-)
1598 dev->descriptor.bMaxPacketSize0 = 8; /* Start off at 8 bytes */
1599 #ifndef DEVNUM_ROUND_ROBIN
1600 devnum = find_next_zero_bit(dev->bus->devmap.devicemap, 128, 1);
1601 #else /* round_robin alloc of devnums */
1602 /* Try to allocate the next devnum beginning at devnum_next. */
1603 devnum = find_next_zero_bit(dev->bus->devmap.devicemap, 128, devnum_next);
1604 if (devnum >= 128)
1605 devnum = find_next_zero_bit(dev->bus->devmap.devicemap, 128, 1);
1607 devnum_next = devnum + 1;
1608 if (devnum_next >= 128)
1609 devnum_next = 1;
1610 #endif /* round_robin alloc of devnums */
1612 if (devnum < 128) {
1613 set_bit(devnum, dev->bus->devmap.devicemap);
1614 dev->devnum = devnum;
1619 * These are the actual routines to send
1620 * and receive control messages.
1623 #define GET_TIMEOUT 3
1624 #define SET_TIMEOUT 3
1626 int usb_set_address(struct usb_device *dev)
1628 return usb_control_msg(dev, usb_snddefctrl(dev), USB_REQ_SET_ADDRESS,
1629 0, dev->devnum, 0, NULL, 0, HZ * GET_TIMEOUT);
1632 int usb_get_descriptor(struct usb_device *dev, unsigned char type, unsigned char index, void *buf, int size)
1634 int i = 5;
1635 int result;
1637 memset(buf,0,size); // Make sure we parse really received data
1639 while (i--) {
1640 if ((result = usb_control_msg(dev, usb_rcvctrlpipe(dev, 0),
1641 USB_REQ_GET_DESCRIPTOR, USB_DIR_IN,
1642 (type << 8) + index, 0, buf, size, HZ * GET_TIMEOUT)) > 0 ||
1643 result == -EPIPE)
1644 break; /* retry if the returned length was 0; flaky device */
1646 return result;
1649 int usb_get_class_descriptor(struct usb_device *dev, int ifnum,
1650 unsigned char type, unsigned char id, void *buf, int size)
1652 return usb_control_msg(dev, usb_rcvctrlpipe(dev, 0),
1653 USB_REQ_GET_DESCRIPTOR, USB_RECIP_INTERFACE | USB_DIR_IN,
1654 (type << 8) + id, ifnum, buf, size, HZ * GET_TIMEOUT);
1657 int usb_get_string(struct usb_device *dev, unsigned short langid, unsigned char index, void *buf, int size)
1659 return usb_control_msg(dev, usb_rcvctrlpipe(dev, 0),
1660 USB_REQ_GET_DESCRIPTOR, USB_DIR_IN,
1661 (USB_DT_STRING << 8) + index, langid, buf, size, HZ * GET_TIMEOUT);
1664 int usb_get_device_descriptor(struct usb_device *dev)
1666 int ret = usb_get_descriptor(dev, USB_DT_DEVICE, 0, &dev->descriptor,
1667 sizeof(dev->descriptor));
1668 if (ret >= 0) {
1669 le16_to_cpus(&dev->descriptor.bcdUSB);
1670 le16_to_cpus(&dev->descriptor.idVendor);
1671 le16_to_cpus(&dev->descriptor.idProduct);
1672 le16_to_cpus(&dev->descriptor.bcdDevice);
1674 return ret;
1677 int usb_get_status(struct usb_device *dev, int type, int target, void *data)
1679 return usb_control_msg(dev, usb_rcvctrlpipe(dev, 0),
1680 USB_REQ_GET_STATUS, USB_DIR_IN | type, 0, target, data, 2, HZ * GET_TIMEOUT);
1683 int usb_get_protocol(struct usb_device *dev, int ifnum)
1685 unsigned char type;
1686 int ret;
1688 if ((ret = usb_control_msg(dev, usb_rcvctrlpipe(dev, 0),
1689 USB_REQ_GET_PROTOCOL, USB_DIR_IN | USB_TYPE_CLASS | USB_RECIP_INTERFACE,
1690 0, ifnum, &type, 1, HZ * GET_TIMEOUT)) < 0)
1691 return ret;
1693 return type;
1696 int usb_set_protocol(struct usb_device *dev, int ifnum, int protocol)
1698 return usb_control_msg(dev, usb_sndctrlpipe(dev, 0),
1699 USB_REQ_SET_PROTOCOL, USB_TYPE_CLASS | USB_RECIP_INTERFACE,
1700 protocol, ifnum, NULL, 0, HZ * SET_TIMEOUT);
1703 int usb_set_idle(struct usb_device *dev, int ifnum, int duration, int report_id)
1705 return usb_control_msg(dev, usb_sndctrlpipe(dev, 0),
1706 USB_REQ_SET_IDLE, USB_TYPE_CLASS | USB_RECIP_INTERFACE,
1707 (duration << 8) | report_id, ifnum, NULL, 0, HZ * SET_TIMEOUT);
1710 void usb_set_maxpacket(struct usb_device *dev)
1712 int i, b;
1714 for (i=0; i<dev->actconfig->bNumInterfaces; i++) {
1715 struct usb_interface *ifp = dev->actconfig->interface + i;
1716 struct usb_interface_descriptor *as = ifp->altsetting + ifp->act_altsetting;
1717 struct usb_endpoint_descriptor *ep = as->endpoint;
1718 int e;
1720 for (e=0; e<as->bNumEndpoints; e++) {
1721 b = ep[e].bEndpointAddress & USB_ENDPOINT_NUMBER_MASK;
1722 if ((ep[e].bmAttributes & USB_ENDPOINT_XFERTYPE_MASK) ==
1723 USB_ENDPOINT_XFER_CONTROL) { /* Control => bidirectional */
1724 dev->epmaxpacketout[b] = ep[e].wMaxPacketSize;
1725 dev->epmaxpacketin [b] = ep[e].wMaxPacketSize;
1727 else if (usb_endpoint_out(ep[e].bEndpointAddress)) {
1728 if (ep[e].wMaxPacketSize > dev->epmaxpacketout[b])
1729 dev->epmaxpacketout[b] = ep[e].wMaxPacketSize;
1731 else {
1732 if (ep[e].wMaxPacketSize > dev->epmaxpacketin [b])
1733 dev->epmaxpacketin [b] = ep[e].wMaxPacketSize;
1740 * endp: endpoint number in bits 0-3;
1741 * direction flag in bit 7 (1 = IN, 0 = OUT)
1743 int usb_clear_halt(struct usb_device *dev, int pipe)
1745 int result;
1746 __u16 status;
1747 int endp=usb_pipeendpoint(pipe)|(usb_pipein(pipe)<<7);
1750 if (!usb_endpoint_halted(dev, endp & 0x0f, usb_endpoint_out(endp)))
1751 return 0;
1754 result = usb_control_msg(dev, usb_sndctrlpipe(dev, 0),
1755 USB_REQ_CLEAR_FEATURE, USB_RECIP_ENDPOINT, 0, endp, NULL, 0, HZ * SET_TIMEOUT);
1757 /* don't clear if failed */
1758 if (result < 0)
1759 return result;
1761 result = usb_control_msg(dev, usb_rcvctrlpipe(dev, 0),
1762 USB_REQ_GET_STATUS, USB_DIR_IN | USB_RECIP_ENDPOINT, 0, endp,
1763 &status, sizeof(status), HZ * SET_TIMEOUT);
1764 if (result < 0)
1765 return result;
1767 if (le16_to_cpu(status) & 1)
1768 return -EPIPE; /* still halted */
1770 usb_endpoint_running(dev, usb_pipeendpoint(pipe), usb_pipeout(pipe));
1772 /* toggle is reset on clear */
1774 usb_settoggle(dev, usb_pipeendpoint(pipe), usb_pipeout(pipe), 0);
1776 return 0;
1779 int usb_set_interface(struct usb_device *dev, int interface, int alternate)
1781 struct usb_interface *iface;
1782 int ret;
1784 iface = usb_ifnum_to_if(dev, interface);
1785 if (!iface) {
1786 warn("selecting invalid interface %d", interface);
1787 return -EINVAL;
1790 if ((ret = usb_control_msg(dev, usb_sndctrlpipe(dev, 0),
1791 USB_REQ_SET_INTERFACE, USB_RECIP_INTERFACE, alternate,
1792 interface, NULL, 0, HZ * 5)) < 0)
1793 return ret;
1795 iface->act_altsetting = alternate;
1796 dev->toggle[0] = 0; /* 9.1.1.5 says to do this */
1797 dev->toggle[1] = 0;
1798 usb_set_maxpacket(dev);
1799 return 0;
1802 int usb_set_configuration(struct usb_device *dev, int configuration)
1804 int i, ret;
1805 struct usb_config_descriptor *cp = NULL;
1807 for (i=0; i<dev->descriptor.bNumConfigurations; i++) {
1808 if (dev->config[i].bConfigurationValue == configuration) {
1809 cp = &dev->config[i];
1810 break;
1813 if (!cp) {
1814 warn("selecting invalid configuration %d", configuration);
1815 return -EINVAL;
1818 if ((ret = usb_control_msg(dev, usb_sndctrlpipe(dev, 0),
1819 USB_REQ_SET_CONFIGURATION, 0, configuration, 0, NULL, 0, HZ * SET_TIMEOUT)) < 0)
1820 return ret;
1822 dev->actconfig = cp;
1823 dev->toggle[0] = 0;
1824 dev->toggle[1] = 0;
1825 usb_set_maxpacket(dev);
1827 return 0;
1830 int usb_get_report(struct usb_device *dev, int ifnum, unsigned char type, unsigned char id, void *buf, int size)
1832 return usb_control_msg(dev, usb_rcvctrlpipe(dev, 0),
1833 USB_REQ_GET_REPORT, USB_DIR_IN | USB_TYPE_CLASS | USB_RECIP_INTERFACE,
1834 (type << 8) + id, ifnum, buf, size, HZ * GET_TIMEOUT);
1837 int usb_set_report(struct usb_device *dev, int ifnum, unsigned char type, unsigned char id, void *buf, int size)
1839 return usb_control_msg(dev, usb_sndctrlpipe(dev, 0),
1840 USB_REQ_SET_REPORT, USB_TYPE_CLASS | USB_RECIP_INTERFACE,
1841 (type << 8) + id, ifnum, buf, size, HZ);
1844 int usb_get_configuration(struct usb_device *dev)
1846 int result;
1847 unsigned int cfgno, length;
1848 unsigned char buffer[8];
1849 unsigned char *bigbuffer;
1850 struct usb_config_descriptor *desc =
1851 (struct usb_config_descriptor *)buffer;
1853 if (dev->descriptor.bNumConfigurations > USB_MAXCONFIG) {
1854 warn("too many configurations");
1855 return -EINVAL;
1858 if (dev->descriptor.bNumConfigurations < 1) {
1859 warn("not enough configurations");
1860 return -EINVAL;
1863 dev->config = (struct usb_config_descriptor *)
1864 kmalloc(dev->descriptor.bNumConfigurations *
1865 sizeof(struct usb_config_descriptor), GFP_KERNEL);
1866 if (!dev->config) {
1867 err("out of memory");
1868 return -ENOMEM;
1870 memset(dev->config, 0, dev->descriptor.bNumConfigurations *
1871 sizeof(struct usb_config_descriptor));
1873 dev->rawdescriptors = (char **)kmalloc(sizeof(char *) *
1874 dev->descriptor.bNumConfigurations, GFP_KERNEL);
1875 if (!dev->rawdescriptors) {
1876 err("out of memory");
1877 return -ENOMEM;
1880 for (cfgno = 0; cfgno < dev->descriptor.bNumConfigurations; cfgno++) {
1881 /* We grab the first 8 bytes so we know how long the whole */
1882 /* configuration is */
1883 result = usb_get_descriptor(dev, USB_DT_CONFIG, cfgno, buffer, 8);
1884 if (result < 8) {
1885 if (result < 0)
1886 err("unable to get descriptor");
1887 else {
1888 err("config descriptor too short (expected %i, got %i)", 8, result);
1889 result = -EINVAL;
1891 goto err;
1894 /* Get the full buffer */
1895 length = le16_to_cpu(desc->wTotalLength);
1897 bigbuffer = kmalloc(length, GFP_KERNEL);
1898 if (!bigbuffer) {
1899 err("unable to allocate memory for configuration descriptors");
1900 result = -ENOMEM;
1901 goto err;
1904 /* Now that we know the length, get the whole thing */
1905 result = usb_get_descriptor(dev, USB_DT_CONFIG, cfgno, bigbuffer, length);
1906 if (result < 0) {
1907 err("couldn't get all of config descriptors");
1908 kfree(bigbuffer);
1909 goto err;
1912 if (result < length) {
1913 err("config descriptor too short (expected %i, got %i)", length, result);
1914 result = -EINVAL;
1915 kfree(bigbuffer);
1916 goto err;
1919 dev->rawdescriptors[cfgno] = bigbuffer;
1921 result = usb_parse_configuration(dev, &dev->config[cfgno], bigbuffer);
1922 if (result > 0)
1923 dbg("descriptor data left");
1924 else if (result < 0) {
1925 result = -EINVAL;
1926 goto err;
1930 return 0;
1931 err:
1932 dev->descriptor.bNumConfigurations = cfgno;
1933 return result;
1937 * usb_string:
1938 * returns string length (> 0) or error (< 0)
1940 int usb_string(struct usb_device *dev, int index, char *buf, size_t size)
1942 unsigned char *tbuf;
1943 int err;
1944 unsigned int u, idx;
1946 if (size <= 0 || !buf || !index)
1947 return -EINVAL;
1948 buf[0] = 0;
1949 tbuf = kmalloc(256, GFP_KERNEL);
1950 if (!tbuf)
1951 return -ENOMEM;
1953 /* get langid for strings if it's not yet known */
1954 if (!dev->have_langid) {
1955 err = usb_get_string(dev, 0, 0, tbuf, 4);
1956 if (err < 0) {
1957 err("error getting string descriptor 0 (error=%d)", err);
1958 goto errout;
1959 } else if (tbuf[0] < 4) {
1960 err("string descriptor 0 too short");
1961 err = -EINVAL;
1962 goto errout;
1963 } else {
1964 dev->have_langid = -1;
1965 dev->string_langid = tbuf[2] | (tbuf[3]<< 8);
1966 /* always use the first langid listed */
1967 dbg("USB device number %d default language ID 0x%x",
1968 dev->devnum, dev->string_langid);
1973 * Just ask for a maximum length string and then take the length
1974 * that was returned.
1976 err = usb_get_string(dev, dev->string_langid, index, tbuf, 255);
1977 if (err < 0)
1978 goto errout;
1980 size--; /* leave room for trailing NULL char in output buffer */
1981 for (idx = 0, u = 2; u < err; u += 2) {
1982 if (idx >= size)
1983 break;
1984 if (tbuf[u+1]) /* high byte */
1985 buf[idx++] = '?'; /* non-ASCII character */
1986 else
1987 buf[idx++] = tbuf[u];
1989 buf[idx] = 0;
1990 err = idx;
1992 errout:
1993 kfree(tbuf);
1994 return err;
1998 * By the time we get here, the device has gotten a new device ID
1999 * and is in the default state. We need to identify the thing and
2000 * get the ball rolling..
2002 * Returns 0 for success, != 0 for error.
2004 int usb_new_device(struct usb_device *dev)
2006 int err;
2008 /* USB v1.1 5.5.3 */
2009 /* We read the first 8 bytes from the device descriptor to get to */
2010 /* the bMaxPacketSize0 field. Then we set the maximum packet size */
2011 /* for the control pipe, and retrieve the rest */
2012 dev->epmaxpacketin [0] = 8;
2013 dev->epmaxpacketout[0] = 8;
2015 err = usb_set_address(dev);
2016 if (err < 0) {
2017 err("USB device not accepting new address=%d (error=%d)",
2018 dev->devnum, err);
2019 clear_bit(dev->devnum, &dev->bus->devmap.devicemap);
2020 dev->devnum = -1;
2021 return 1;
2024 wait_ms(10); /* Let the SET_ADDRESS settle */
2026 err = usb_get_descriptor(dev, USB_DT_DEVICE, 0, &dev->descriptor, 8);
2027 if (err < 8) {
2028 if (err < 0)
2029 err("USB device not responding, giving up (error=%d)", err);
2030 else
2031 err("USB device descriptor short read (expected %i, got %i)", 8, err);
2032 clear_bit(dev->devnum, &dev->bus->devmap.devicemap);
2033 dev->devnum = -1;
2034 return 1;
2036 dev->epmaxpacketin [0] = dev->descriptor.bMaxPacketSize0;
2037 dev->epmaxpacketout[0] = dev->descriptor.bMaxPacketSize0;
2039 err = usb_get_device_descriptor(dev);
2040 if (err < sizeof(dev->descriptor)) {
2041 if (err < 0)
2042 err("unable to get device descriptor (error=%d)", err);
2043 else
2044 err("USB device descriptor short read (expected %i, got %i)",
2045 sizeof(dev->descriptor), err);
2047 clear_bit(dev->devnum, &dev->bus->devmap.devicemap);
2048 dev->devnum = -1;
2049 return 1;
2052 err = usb_get_configuration(dev);
2053 if (err < 0) {
2054 err("unable to get device %d configuration (error=%d)",
2055 dev->devnum, err);
2056 usb_destroy_configuration(dev);
2057 clear_bit(dev->devnum, &dev->bus->devmap.devicemap);
2058 dev->devnum = -1;
2059 return 1;
2062 /* we set the default configuration here */
2063 err = usb_set_configuration(dev, dev->config[0].bConfigurationValue);
2064 if (err) {
2065 err("failed to set device %d default configuration (error=%d)",
2066 dev->devnum, err);
2067 clear_bit(dev->devnum, &dev->bus->devmap.devicemap);
2068 dev->devnum = -1;
2069 return 1;
2072 dbg("new device strings: Mfr=%d, Product=%d, SerialNumber=%d",
2073 dev->descriptor.iManufacturer, dev->descriptor.iProduct, dev->descriptor.iSerialNumber);
2074 #ifdef DEBUG
2075 if (dev->descriptor.iManufacturer)
2076 usb_show_string(dev, "Manufacturer", dev->descriptor.iManufacturer);
2077 if (dev->descriptor.iProduct)
2078 usb_show_string(dev, "Product", dev->descriptor.iProduct);
2079 if (dev->descriptor.iSerialNumber)
2080 usb_show_string(dev, "SerialNumber", dev->descriptor.iSerialNumber);
2081 #endif
2083 /* now that the basic setup is over, add a /proc/bus/usb entry */
2084 usbdevfs_add_device(dev);
2086 /* find drivers willing to handle this device */
2087 usb_find_drivers(dev);
2089 /* userspace may load modules and/or configure further */
2090 call_policy ("add", dev);
2092 return 0;
2095 static int usb_open(struct inode * inode, struct file * file)
2097 int minor = MINOR(inode->i_rdev);
2098 struct usb_driver *c = usb_minors[minor/16];
2099 int err = -ENODEV;
2100 struct file_operations *old_fops, *new_fops = NULL;
2103 * No load-on-demand? Randy, could you ACK that it's really not
2104 * supposed to be done? -- AV
2106 if (!c || !(new_fops = fops_get(c->fops)))
2107 return err;
2108 old_fops = file->f_op;
2109 file->f_op = new_fops;
2110 /* Curiouser and curiouser... NULL ->open() as "no device" ? */
2111 if (file->f_op->open)
2112 err = file->f_op->open(inode,file);
2113 if (err) {
2114 fops_put(file->f_op);
2115 file->f_op = fops_get(old_fops);
2117 fops_put(old_fops);
2118 return err;
2121 static struct file_operations usb_fops = {
2122 owner: THIS_MODULE,
2123 open: usb_open,
2126 int usb_major_init(void)
2128 if (devfs_register_chrdev(USB_MAJOR, "usb", &usb_fops)) {
2129 err("unable to get major %d for usb devices", USB_MAJOR);
2130 return -EBUSY;
2133 usb_devfs_handle = devfs_mk_dir(NULL, "usb", NULL);
2135 return 0;
2138 void usb_major_cleanup(void)
2140 devfs_unregister(usb_devfs_handle);
2141 devfs_unregister_chrdev(USB_MAJOR, "usb");
2145 #ifdef CONFIG_PROC_FS
2146 struct list_head *usb_driver_get_list(void)
2148 return &usb_driver_list;
2151 struct list_head *usb_bus_get_list(void)
2153 return &usb_bus_list;
2155 #endif
2159 * Init
2161 static int __init usb_init(void)
2163 usb_major_init();
2164 usbdevfs_init();
2165 usb_hub_init();
2167 return 0;
2171 * Cleanup
2173 static void __exit usb_exit(void)
2175 usb_major_cleanup();
2176 usbdevfs_cleanup();
2177 usb_hub_cleanup();
2180 module_init(usb_init);
2181 module_exit(usb_exit);
2184 * USB may be built into the kernel or be built as modules.
2185 * If the USB core [and maybe a host controller driver] is built
2186 * into the kernel, and other device drivers are built as modules,
2187 * then these symbols need to be exported for the modules to use.
2189 EXPORT_SYMBOL(usb_ifnum_to_if);
2190 EXPORT_SYMBOL(usb_epnum_to_ep_desc);
2192 EXPORT_SYMBOL(usb_register);
2193 EXPORT_SYMBOL(usb_deregister);
2194 EXPORT_SYMBOL(usb_scan_devices);
2195 EXPORT_SYMBOL(usb_alloc_bus);
2196 EXPORT_SYMBOL(usb_free_bus);
2197 EXPORT_SYMBOL(usb_register_bus);
2198 EXPORT_SYMBOL(usb_deregister_bus);
2199 EXPORT_SYMBOL(usb_alloc_dev);
2200 EXPORT_SYMBOL(usb_free_dev);
2201 EXPORT_SYMBOL(usb_inc_dev_use);
2203 EXPORT_SYMBOL(usb_driver_claim_interface);
2204 EXPORT_SYMBOL(usb_interface_claimed);
2205 EXPORT_SYMBOL(usb_driver_release_interface);
2206 EXPORT_SYMBOL(usb_match_id);
2208 EXPORT_SYMBOL(usb_root_hub_string);
2209 EXPORT_SYMBOL(usb_new_device);
2210 EXPORT_SYMBOL(usb_reset_device);
2211 EXPORT_SYMBOL(usb_connect);
2212 EXPORT_SYMBOL(usb_disconnect);
2214 EXPORT_SYMBOL(usb_check_bandwidth);
2215 EXPORT_SYMBOL(usb_claim_bandwidth);
2216 EXPORT_SYMBOL(usb_release_bandwidth);
2218 EXPORT_SYMBOL(usb_set_address);
2219 EXPORT_SYMBOL(usb_get_descriptor);
2220 EXPORT_SYMBOL(usb_get_class_descriptor);
2221 EXPORT_SYMBOL(__usb_get_extra_descriptor);
2222 EXPORT_SYMBOL(usb_get_device_descriptor);
2223 EXPORT_SYMBOL(usb_get_string);
2224 EXPORT_SYMBOL(usb_string);
2225 EXPORT_SYMBOL(usb_get_protocol);
2226 EXPORT_SYMBOL(usb_set_protocol);
2227 EXPORT_SYMBOL(usb_get_report);
2228 EXPORT_SYMBOL(usb_set_report);
2229 EXPORT_SYMBOL(usb_set_idle);
2230 EXPORT_SYMBOL(usb_clear_halt);
2231 EXPORT_SYMBOL(usb_set_interface);
2232 EXPORT_SYMBOL(usb_get_configuration);
2233 EXPORT_SYMBOL(usb_set_configuration);
2235 EXPORT_SYMBOL(usb_get_current_frame_number);
2237 EXPORT_SYMBOL(usb_alloc_urb);
2238 EXPORT_SYMBOL(usb_free_urb);
2239 EXPORT_SYMBOL(usb_submit_urb);
2240 EXPORT_SYMBOL(usb_unlink_urb);
2242 EXPORT_SYMBOL(usb_control_msg);
2243 EXPORT_SYMBOL(usb_bulk_msg);
2245 EXPORT_SYMBOL(usb_devfs_handle);