Import 2.4.0-test5pre6
[davej-history.git] / drivers / usb / usb.c
blob0154d7f4885573776cbc775081e151ee02ff581e
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
11 * NOTE! This is not actually a driver at all, rather this is
12 * just a collection of helper routines that implement the
13 * generic USB things that the real drivers can use..
15 * Think of this as a "USB library" rather than anything else.
16 * It should be considered a slave, with no callbacks. Callbacks
17 * are evil.
19 * $Id: usb.c,v 1.53 2000/01/14 16:19:09 acher Exp $
22 #include <linux/config.h>
23 #include <linux/module.h>
24 #include <linux/string.h>
25 #include <linux/bitops.h>
26 #include <linux/malloc.h>
27 #include <linux/interrupt.h> /* for in_interrupt() */
30 #if defined(CONFIG_KMOD) && defined(CONFIG_HOTPLUG)
31 #include <linux/kmod.h>
32 #include <linux/sched.h>
33 #include <asm/uaccess.h>
35 #define __KERNEL_SYSCALLS__
36 #include <linux/unistd.h>
38 /* waitpid() call glue uses this */
39 static int errno;
40 #endif
43 #ifdef CONFIG_USB_DEBUG
44 #define DEBUG
45 #else
46 #undef DEBUG
47 #endif
48 #include <linux/usb.h>
50 static const int usb_bandwidth_option =
51 #ifdef CONFIG_USB_BANDWIDTH
53 #else
55 #endif
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 static struct usb_busmap busmap;
72 static struct usb_driver *usb_minors[16];
74 int usb_register(struct usb_driver *new_driver)
76 if (new_driver->fops != NULL) {
77 if (usb_minors[new_driver->minor/16]) {
78 err("error registering %s driver", new_driver->name);
79 return -EINVAL;
81 usb_minors[new_driver->minor/16] = new_driver;
84 info("registered new driver %s", new_driver->name);
86 init_MUTEX(&new_driver->serialize);
88 /* Add it to the list of known drivers */
89 list_add(&new_driver->driver_list, &usb_driver_list);
91 usb_scan_devices();
93 return 0;
97 * We go through all existing devices, and see if any of them would
98 * be acceptable to the new driver.. This is done using a depth-first
99 * search for devices without a registered driver already, then
100 * running 'probe' with each of the drivers registered on every one
101 * of these.
103 void usb_scan_devices(void)
105 struct list_head *tmp;
107 tmp = usb_bus_list.next;
108 while (tmp != &usb_bus_list) {
109 struct usb_bus *bus = list_entry(tmp,struct usb_bus, bus_list);
111 tmp = tmp->next;
112 usb_check_support(bus->root_hub);
117 * This function is part of a depth-first search down the device tree,
118 * removing any instances of a device driver.
120 static void usb_drivers_purge(struct usb_driver *driver,struct usb_device *dev)
122 int i;
124 if (!dev) {
125 err("null device being purged!!!");
126 return;
129 for (i=0; i<USB_MAXCHILDREN; i++)
130 if (dev->children[i])
131 usb_drivers_purge(driver, dev->children[i]);
133 if (!dev->actconfig)
134 return;
136 for (i = 0; i < dev->actconfig->bNumInterfaces; i++) {
137 struct usb_interface *interface = &dev->actconfig->interface[i];
139 if (interface->driver == driver) {
140 down(&driver->serialize);
141 driver->disconnect(dev, interface->private_data);
142 up(&driver->serialize);
143 usb_driver_release_interface(driver, interface);
145 * This will go through the list looking for another
146 * driver that can handle the device
148 usb_find_interface_driver(dev, i);
154 * Unlink a driver from the driver list when it is unloaded
156 void usb_deregister(struct usb_driver *driver)
158 struct list_head *tmp;
160 info("deregistering driver %s", driver->name);
161 if (driver->fops != NULL)
162 usb_minors[driver->minor/16] = NULL;
165 * first we remove the driver, to be sure it doesn't get used by
166 * another thread while we are stepping through removing entries
168 list_del(&driver->driver_list);
170 tmp = usb_bus_list.next;
171 while (tmp != &usb_bus_list) {
172 struct usb_bus *bus = list_entry(tmp,struct usb_bus,bus_list);
174 tmp = tmp->next;
175 usb_drivers_purge(driver, bus->root_hub);
179 struct usb_interface *usb_ifnum_to_if(struct usb_device *dev, unsigned ifnum)
181 int i;
183 for (i = 0; i < dev->actconfig->bNumInterfaces; i++)
184 if (dev->actconfig->interface[i].altsetting[0].bInterfaceNumber == ifnum)
185 return &dev->actconfig->interface[i];
187 return NULL;
191 * usb_calc_bus_time:
193 * returns (approximate) USB bus time in nanoseconds for a USB transaction.
195 static long usb_calc_bus_time (int low_speed, int input_dir, int isoc, int bytecount)
197 unsigned long tmp;
199 if (low_speed) /* no isoc. here */
201 if (input_dir)
203 tmp = (67667L * (31L + 10L * BitTime (bytecount))) / 1000L;
204 return (64060L + (2 * BW_HUB_LS_SETUP) + BW_HOST_DELAY + tmp);
206 else
208 tmp = (66700L * (31L + 10L * BitTime (bytecount))) / 1000L;
209 return (64107L + (2 * BW_HUB_LS_SETUP) + BW_HOST_DELAY + tmp);
213 /* for full-speed: */
215 if (!isoc) /* Input or Output */
217 tmp = (8354L * (31L + 10L * BitTime (bytecount))) / 1000L;
218 return (9107L + BW_HOST_DELAY + tmp);
219 } /* end not Isoc */
221 /* for isoc: */
223 tmp = (8354L * (31L + 10L * BitTime (bytecount))) / 1000L;
224 return (((input_dir) ? 7268L : 6265L) + BW_HOST_DELAY + tmp);
228 * usb_check_bandwidth():
230 * old_alloc is from host_controller->bandwidth_allocated in microseconds;
231 * bustime is from calc_bus_time(), but converted to microseconds.
233 * returns <bustime in us> if successful,
234 * or USB_ST_BANDWIDTH_ERROR if bandwidth request fails.
236 * FIXME:
237 * This initial implementation does not use Endpoint.bInterval
238 * in managing bandwidth allocation.
239 * It probably needs to be expanded to use Endpoint.bInterval.
240 * This can be done as a later enhancement (correction).
241 * This will also probably require some kind of
242 * frame allocation tracking...meaning, for example,
243 * that if multiple drivers request interrupts every 10 USB frames,
244 * they don't all have to be allocated at
245 * frame numbers N, N+10, N+20, etc. Some of them could be at
246 * N+11, N+21, N+31, etc., and others at
247 * N+12, N+22, N+32, etc.
248 * However, this first cut at USB bandwidth allocation does not
249 * contain any frame allocation tracking.
251 int usb_check_bandwidth (struct usb_device *dev, struct urb *urb)
253 int new_alloc;
254 int old_alloc = dev->bus->bandwidth_allocated;
255 unsigned int pipe = urb->pipe;
256 long bustime;
258 bustime = usb_calc_bus_time (usb_pipeslow(pipe), usb_pipein(pipe),
259 usb_pipeisoc(pipe), usb_maxpacket(dev, pipe, usb_pipeout(pipe)));
260 if (usb_pipeisoc(pipe))
261 bustime = NS_TO_US(bustime) / urb->number_of_packets;
262 else
263 bustime = NS_TO_US(bustime);
265 new_alloc = old_alloc + (int)bustime;
266 /* what new total allocated bus time would be */
268 if (new_alloc > FRAME_TIME_MAX_USECS_ALLOC)
269 dbg("usb-check-bandwidth %sFAILED: was %u, would be %u, bustime = %ld us",
270 usb_bandwidth_option ? "" : "would have ",
271 old_alloc, new_alloc, bustime);
273 if (!usb_bandwidth_option) /* don't enforce it */
274 return (bustime);
275 return (new_alloc <= FRAME_TIME_MAX_USECS_ALLOC) ? bustime : USB_ST_BANDWIDTH_ERROR;
278 void usb_claim_bandwidth (struct usb_device *dev, struct urb *urb, int bustime, int isoc)
280 dev->bus->bandwidth_allocated += bustime;
281 if (isoc)
282 dev->bus->bandwidth_isoc_reqs++;
283 else
284 dev->bus->bandwidth_int_reqs++;
285 urb->bandwidth = bustime;
287 dbg("bw_alloc increased by %d to %d for %d requesters",
288 bustime,
289 dev->bus->bandwidth_allocated,
290 dev->bus->bandwidth_int_reqs + dev->bus->bandwidth_isoc_reqs);
294 * usb_release_bandwidth():
296 * called to release a pipe's bandwidth (in microseconds)
298 void usb_release_bandwidth(struct usb_device *dev, struct urb *urb, int isoc)
300 dev->bus->bandwidth_allocated -= urb->bandwidth;
301 if (isoc)
302 dev->bus->bandwidth_isoc_reqs--;
303 else
304 dev->bus->bandwidth_int_reqs--;
306 dbg("bw_alloc reduced by %d to %d for %d requesters",
307 urb->bandwidth,
308 dev->bus->bandwidth_allocated,
309 dev->bus->bandwidth_int_reqs + dev->bus->bandwidth_isoc_reqs);
310 urb->bandwidth = 0;
314 * New functions for (de)registering a controller
316 struct usb_bus *usb_alloc_bus(struct usb_operations *op)
318 struct usb_bus *bus;
320 bus = kmalloc(sizeof(*bus), GFP_KERNEL);
321 if (!bus)
322 return NULL;
324 memset(&bus->devmap, 0, sizeof(struct usb_devmap));
326 bus->op = op;
327 bus->root_hub = NULL;
328 bus->hcpriv = NULL;
329 bus->busnum = -1;
330 bus->bandwidth_allocated = 0;
331 bus->bandwidth_int_reqs = 0;
332 bus->bandwidth_isoc_reqs = 0;
334 INIT_LIST_HEAD(&bus->bus_list);
335 INIT_LIST_HEAD(&bus->inodes);
337 return bus;
340 void usb_free_bus(struct usb_bus *bus)
342 if (!bus)
343 return;
345 kfree(bus);
348 void usb_register_bus(struct usb_bus *bus)
350 int busnum;
352 busnum = find_next_zero_bit(busmap.busmap, USB_MAXBUS, 1);
353 if (busnum < USB_MAXBUS) {
354 set_bit(busnum, busmap.busmap);
355 bus->busnum = busnum;
356 } else
357 warn("too many buses");
359 /* Add it to the list of buses */
360 list_add(&bus->bus_list, &usb_bus_list);
362 usbdevfs_add_bus(bus);
364 info("new USB bus registered, assigned bus number %d", bus->busnum);
367 void usb_deregister_bus(struct usb_bus *bus)
369 info("USB bus %d deregistered", bus->busnum);
372 * NOTE: make sure that all the devices are removed by the
373 * controller code, as well as having it call this when cleaning
374 * itself up
376 list_del(&bus->bus_list);
378 usbdevfs_remove_bus(bus);
380 clear_bit(bus->busnum, busmap.busmap);
384 * This function is for doing a depth-first search for devices which
385 * have support, for dynamic loading of driver modules.
387 static void usb_check_support(struct usb_device *dev)
389 int i;
391 if (!dev) {
392 err("null device being checked!!!");
393 return;
396 for (i=0; i<USB_MAXCHILDREN; i++)
397 if (dev->children[i])
398 usb_check_support(dev->children[i]);
400 if (!dev->actconfig)
401 return;
403 /* now we check this device */
404 if (dev->devnum > 0)
405 for (i = 0; i < dev->actconfig->bNumInterfaces; i++)
406 usb_find_interface_driver(dev, i);
411 * This is intended to be used by usb device drivers that need to
412 * claim more than one interface on a device at once when probing
413 * (audio and acm are good examples). No device driver should have
414 * to mess with the internal usb_interface or usb_device structure
415 * members.
417 void usb_driver_claim_interface(struct usb_driver *driver, struct usb_interface *iface, void* priv)
419 if (!iface || !driver)
420 return;
422 dbg("%s driver claimed interface %p", driver->name, iface);
424 iface->driver = driver;
425 iface->private_data = priv;
426 } /* usb_driver_claim_interface() */
429 * This should be used by drivers to check other interfaces to see if
430 * they are available or not.
432 int usb_interface_claimed(struct usb_interface *iface)
434 if (!iface)
435 return 0;
437 return (iface->driver != NULL);
438 } /* usb_interface_claimed() */
441 * This should be used by drivers to release their claimed interfaces
443 void usb_driver_release_interface(struct usb_driver *driver, struct usb_interface *iface)
445 /* this should never happen, don't release something that's not ours */
446 if (!iface || iface->driver != driver)
447 return;
449 iface->driver = NULL;
450 iface->private_data = NULL;
454 * This entrypoint gets called for each new device.
456 * We now walk the list of registered USB drivers,
457 * looking for one that will accept this interface.
459 * The probe return value is changed to be a private pointer. This way
460 * the drivers don't have to dig around in our structures to set the
461 * private pointer if they only need one interface.
463 * Returns: 0 if a driver accepted the interface, -1 otherwise
465 static int usb_find_interface_driver(struct usb_device *dev, unsigned ifnum)
467 struct list_head *tmp = usb_driver_list.next;
468 struct usb_interface *interface;
470 if ((!dev) || (ifnum >= dev->actconfig->bNumInterfaces)) {
471 err("bad find_interface_driver params");
472 return -1;
475 interface = dev->actconfig->interface + ifnum;
477 if (usb_interface_claimed(interface))
478 return -1;
480 while (tmp != &usb_driver_list) {
481 void *private;
482 struct usb_driver *driver = list_entry(tmp, struct usb_driver,
483 driver_list);
485 tmp = tmp->next;
486 down(&driver->serialize);
487 private = driver->probe(dev, ifnum);
488 up(&driver->serialize);
489 if (!private)
490 continue;
491 usb_driver_claim_interface(driver, interface, private);
493 return 0;
496 return -1;
500 #if defined(CONFIG_KMOD) && defined(CONFIG_HOTPLUG)
503 * USB hotplugging invokes what /proc/sys/kernel/hotplug says
504 * (normally /sbin/hotplug) when USB devices get added or removed.
507 static int exec_helper (void *arg)
509 void **params = (void **) arg;
510 char *path = (char *) params [0];
511 char **argv = (char **) params [1];
512 char **envp = (char **) params [2];
513 return exec_usermodehelper (path, argv, envp);
516 int call_usermodehelper (char *path, char **argv, char **envp)
518 void *params [3] = { path, argv, envp };
519 int pid, pid2, retval;
520 mm_segment_t fs;
522 if ((pid = kernel_thread (exec_helper, (void *) params, 0)) < 0) {
523 err ("failed fork of %s, errno = %d", argv [0], -pid);
524 return -1;
527 /* set signal mask? */
528 fs = get_fs ();
529 set_fs (KERNEL_DS); /* retval is in kernel space. */
530 pid2 = waitpid (pid, &retval, __WCLONE); /* "errno" gets assigned */
531 set_fs (fs);
532 /* restore signal mask? */
534 if (pid2 != pid) {
535 err ("waitpid(%d) failed, returned %d\n", pid, pid2);
536 return -1;
538 return retval;
541 static int to_bcd (char *buf, __u16 *bcdValue)
543 int retval = 0;
544 char *value = (char *) bcdValue;
545 int temp;
547 /* digits are 0-9 then ":;<=>?" for devices using
548 * non-bcd (non-standard!) values here ... */
550 /* No leading (or later, trailing) zeroes since scripts do
551 * literal matches, and that's how they're doing them. */
552 if ((temp = value [1] & 0xf0) != 0) {
553 temp >>= 4;
554 temp += '0';
555 *buf++ = (char) temp;
556 retval++;
559 temp = value [1] & 0x0f;
560 temp += '0';
561 *buf++ = (char) temp;
562 retval++;
564 *buf++ = '.';
565 retval++;
567 temp = value [0] & 0xf0;
568 temp >>= 4;
569 temp += '0';
570 *buf++ = (char) temp;
571 retval++;
573 if ((temp = value [0] & 0x0f) != 0) {
574 temp += '0';
575 *buf++ = (char) temp;
576 retval++;
578 *buf++ = 0;
580 return retval;
584 * This invokes a user mode policy agent, typically helping to load driver
585 * or other modules, configure the device, or both.
587 * Some synchronization is important: removes can't start processing
588 * before the add-device processing completes, and vice versa. That keeps
589 * a stack of USB-related identifiers stable while they're in use. If we
590 * know that agents won't complete after they return (such as by forking
591 * a process that completes later), it's enough to just waitpid() for the
592 * agent -- as is currently done.
594 * The reason: we know we're called either from khubd (the typical case)
595 * or from root hub initialization (init, kapmd, modprobe, etc). In both
596 * cases, we know no other thread can recycle our address, since we must
597 * already have been serialized enough to prevent that.
599 static void call_policy (char *verb, struct usb_device *dev)
601 char *argv [3], **envp, *buf, *scratch;
602 int i = 0, value;
604 if (!hotplug_path [0])
605 return;
606 if (in_interrupt ()) {
607 dbg ("In_interrupt");
608 return;
610 if (!current->fs->root) {
611 /* statically linked USB is initted rather early */
612 dbg ("call_policy %s, num %d -- no FS yet", verb, dev->devnum);
613 return;
615 if (dev->devnum < 0) {
616 dbg ("device already deleted ??");
617 return;
619 if (!(envp = (char **) kmalloc (20 * sizeof (char *), GFP_KERNEL))) {
620 dbg ("enomem");
621 return;
623 if (!(buf = kmalloc (256, GFP_KERNEL))) {
624 kfree (envp);
625 dbg ("enomem2");
626 return;
629 /* only one standardized param to hotplug command: type */
630 argv [0] = hotplug_path;
631 argv [1] = "usb";
632 argv [2] = 0;
634 /* minimal command environment */
635 envp [i++] = "HOME=/";
636 envp [i++] = "PATH=/sbin:/bin:/usr/sbin:/usr/bin";
638 #ifdef DEBUG
639 /* hint that policy agent should enter no-stdout debug mode */
640 envp [i++] = "DEBUG=kernel";
641 #endif
642 /* extensible set of named bus-specific parameters,
643 * supporting multiple driver selection algorithms.
645 scratch = buf;
647 /* action: add, remove */
648 envp [i++] = scratch;
649 scratch += sprintf (scratch, "ACTION=%s", verb) + 1;
651 #ifdef CONFIG_USB_DEVICEFS
652 /* If this is available, userspace programs can directly read
653 * all the device descriptors we don't tell them about. Or
654 * even act as usermode drivers.
656 * XXX how little intelligence can we hardwire?
657 * (a) mount point: /devfs, /dev, /proc/bus/usb etc.
658 * (b) naming convention: bus1/device3, 001/003 etc.
660 envp [i++] = "DEVFS=/proc/bus/usb";
661 envp [i++] = scratch;
662 scratch += sprintf (scratch, "DEVICE=/proc/bus/usb/%03d/%03d",
663 dev->bus->busnum, dev->devnum) + 1;
664 #endif
666 /* per-device configuration hacks are often necessary */
667 envp [i++] = scratch;
668 scratch += sprintf (scratch, "PRODUCT=%x/%x/",
669 dev->descriptor.idVendor,
670 dev->descriptor.idProduct);
671 scratch += to_bcd (scratch, &dev->descriptor.bcdDevice) + 1;
673 /* otherwise, use a simple (so far) generic driver binding model */
674 envp [i++] = scratch;
675 if (dev->descriptor.bDeviceClass == 0) {
676 int alt = dev->actconfig->interface [0].act_altsetting;
678 /* simple/common case: one config, one interface, one driver
679 * unsimple cases: everything else
681 scratch += sprintf (scratch, "INTERFACE=%d/%d/%d",
682 dev->actconfig->interface [0].altsetting [alt].bInterfaceClass,
683 dev->actconfig->interface [0].altsetting [alt].bInterfaceSubClass,
684 dev->actconfig->interface [0].altsetting [alt].bInterfaceProtocol)
685 + 1;
686 /* INTERFACE-0, INTERFACE-1, ... ? */
687 } else {
688 /* simple/common case: generic device, handled generically */
689 scratch += sprintf (scratch, "TYPE=%d/%d/%d",
690 dev->descriptor.bDeviceClass,
691 dev->descriptor.bDeviceSubClass,
692 dev->descriptor.bDeviceProtocol) + 1;
694 envp [i++] = 0;
695 /* assert: (scratch - buf) < sizeof buf */
697 /* NOTE: user mode daemons can call the agents too */
699 dbg ("kusbd: %s %s %d", argv [0], verb, dev->devnum);
700 value = call_usermodehelper (argv [0], argv, envp);
701 kfree (buf);
702 kfree (envp);
703 dbg ("kusbd policy returned 0x%x", value);
706 #else
708 static inline void
709 call_policy (char *verb, struct usb_device *dev)
710 { }
712 #endif /* KMOD && HOTPLUG */
716 * This entrypoint gets called for each new device.
718 * All interfaces are scanned for matching drivers.
720 static void usb_find_drivers(struct usb_device *dev)
722 unsigned ifnum;
723 unsigned rejected = 0;
724 unsigned claimed = 0;
726 for (ifnum = 0; ifnum < dev->actconfig->bNumInterfaces; ifnum++) {
727 /* if this interface hasn't already been claimed */
728 if (!usb_interface_claimed(dev->actconfig->interface + ifnum)) {
729 if (usb_find_interface_driver(dev, ifnum))
730 rejected++;
731 else
732 claimed++;
736 if (rejected)
737 dbg("unhandled interfaces on device");
739 if (!claimed) {
740 warn("USB device %d (prod/vend 0x%x/0x%x) is not claimed by any active driver.",
741 dev->devnum,
742 dev->descriptor.idVendor,
743 dev->descriptor.idProduct);
744 #ifdef DEBUG
745 usb_show_device(dev);
746 #endif
751 * Only HC's should call usb_alloc_dev and usb_free_dev directly
752 * Anybody may use usb_inc_dev_use or usb_dec_dev_use
754 struct usb_device *usb_alloc_dev(struct usb_device *parent, struct usb_bus *bus)
756 struct usb_device *dev;
758 dev = kmalloc(sizeof(*dev), GFP_KERNEL);
759 if (!dev)
760 return NULL;
762 memset(dev, 0, sizeof(*dev));
764 dev->bus = bus;
765 dev->parent = parent;
766 atomic_set(&dev->refcnt, 1);
767 INIT_LIST_HEAD(&dev->inodes);
768 INIT_LIST_HEAD(&dev->filelist);
770 dev->bus->op->allocate(dev);
772 return dev;
775 void usb_free_dev(struct usb_device *dev)
777 if (atomic_dec_and_test(&dev->refcnt)) {
778 usb_destroy_configuration(dev);
779 dev->bus->op->deallocate(dev);
780 kfree(dev);
784 void usb_inc_dev_use(struct usb_device *dev)
786 atomic_inc(&dev->refcnt);
788 /* -------------------------------------------------------------------------------------
789 * New USB Core Functions
790 * -------------------------------------------------------------------------------------*/
792 urb_t *usb_alloc_urb(int iso_packets)
794 urb_t *urb;
796 urb = (urb_t *)kmalloc(sizeof(urb_t) + iso_packets * sizeof(iso_packet_descriptor_t),
797 in_interrupt() ? GFP_ATOMIC : GFP_KERNEL);
798 if (!urb) {
799 err("alloc_urb: kmalloc failed");
800 return NULL;
803 memset(urb, 0, sizeof(*urb));
805 spin_lock_init(&urb->lock);
807 return urb;
810 /*-------------------------------------------------------------------*/
811 void usb_free_urb(urb_t* urb)
813 if (urb)
814 kfree(urb);
816 /*-------------------------------------------------------------------*/
817 int usb_submit_urb(urb_t *urb)
819 if (urb && urb->dev)
820 return urb->dev->bus->op->submit_urb(urb);
821 else
822 return -1;
825 /*-------------------------------------------------------------------*/
826 int usb_unlink_urb(urb_t *urb)
828 if (urb && urb->dev)
829 return urb->dev->bus->op->unlink_urb(urb);
830 else
831 return -1;
833 /*-------------------------------------------------------------------*
834 * COMPLETION HANDLERS *
835 *-------------------------------------------------------------------*/
837 /*-------------------------------------------------------------------*
838 * completion handler for compatibility wrappers (sync control/bulk) *
839 *-------------------------------------------------------------------*/
840 static void usb_api_blocking_completion(urb_t *urb)
842 api_wrapper_data *awd = (api_wrapper_data *)urb->context;
844 if (waitqueue_active(awd->wakeup))
845 wake_up(awd->wakeup);
846 #if 0
847 else
848 dbg("(blocking_completion): waitqueue empty!");
849 // even occurs if urb was unlinked by timeout...
850 #endif
853 /*-------------------------------------------------------------------*
854 * COMPATIBILITY STUFF *
855 *-------------------------------------------------------------------*/
857 // Starts urb and waits for completion or timeout
858 static int usb_start_wait_urb(urb_t *urb, int timeout, int* actual_length)
860 DECLARE_WAITQUEUE(wait, current);
861 DECLARE_WAIT_QUEUE_HEAD(wqh);
862 api_wrapper_data awd;
863 int status;
865 awd.wakeup = &wqh;
866 awd.handler = 0;
867 init_waitqueue_head(&wqh);
868 current->state = TASK_INTERRUPTIBLE;
869 add_wait_queue(&wqh, &wait);
870 urb->context = &awd;
871 status = usb_submit_urb(urb);
872 if (status) {
873 // something went wrong
874 usb_free_urb(urb);
875 remove_wait_queue(&wqh, &wait);
876 return status;
879 if (urb->status == -EINPROGRESS) {
880 while (timeout && urb->status == -EINPROGRESS)
881 status = timeout = schedule_timeout(timeout);
882 } else
883 status = 1;
885 remove_wait_queue(&wqh, &wait);
887 if (!status) {
888 // timeout
889 printk("usb_control/bulk_msg: timeout\n");
890 usb_unlink_urb(urb); // remove urb safely
891 status = -ETIMEDOUT;
892 } else
893 status = urb->status;
895 if (actual_length)
896 *actual_length = urb->actual_length;
898 usb_free_urb(urb);
899 return status;
902 /*-------------------------------------------------------------------*/
903 // returns status (negative) or length (positive)
904 int usb_internal_control_msg(struct usb_device *usb_dev, unsigned int pipe,
905 devrequest *cmd, void *data, int len, int timeout)
907 urb_t *urb;
908 int retv;
909 int length;
911 urb = usb_alloc_urb(0);
912 if (!urb)
913 return -ENOMEM;
915 FILL_CONTROL_URB(urb, usb_dev, pipe, (unsigned char*)cmd, data, len, /* build urb */
916 (usb_complete_t)usb_api_blocking_completion,0);
918 retv = usb_start_wait_urb(urb, timeout, &length);
919 if (retv < 0)
920 return retv;
921 else
922 return length;
926 /*-------------------------------------------------------------------*/
927 int usb_control_msg(struct usb_device *dev, unsigned int pipe, __u8 request, __u8 requesttype,
928 __u16 value, __u16 index, void *data, __u16 size, int timeout)
930 devrequest *dr = kmalloc(sizeof(devrequest), GFP_KERNEL);
931 int ret;
933 if (!dr)
934 return -ENOMEM;
936 dr->requesttype = requesttype;
937 dr->request = request;
938 dr->value = cpu_to_le16p(&value);
939 dr->index = cpu_to_le16p(&index);
940 dr->length = cpu_to_le16p(&size);
942 //dbg("usb_control_msg");
944 ret = usb_internal_control_msg(dev, pipe, dr, data, size, timeout);
946 kfree(dr);
948 return ret;
951 /*-------------------------------------------------------------------*/
952 /* compatibility wrapper, builds bulk urb, and waits for completion */
953 /* synchronous behavior */
955 int usb_bulk_msg(struct usb_device *usb_dev, unsigned int pipe,
956 void *data, int len, int *actual_length, int timeout)
958 urb_t *urb;
960 if (len < 0)
961 return -EINVAL;
963 urb=usb_alloc_urb(0);
964 if (!urb)
965 return -ENOMEM;
967 FILL_BULK_URB(urb,usb_dev,pipe,(unsigned char*)data,len, /* build urb */
968 (usb_complete_t)usb_api_blocking_completion,0);
970 return usb_start_wait_urb(urb,timeout,actual_length);
974 * usb_get_current_frame_number()
976 * returns the current frame number for the parent USB bus/controller
977 * of the given USB device.
979 int usb_get_current_frame_number(struct usb_device *usb_dev)
981 return usb_dev->bus->op->get_frame_number (usb_dev);
983 /*-------------------------------------------------------------------*/
985 static int usb_parse_endpoint(struct usb_device *dev, struct usb_endpoint_descriptor *endpoint, unsigned char *buffer, int size)
987 struct usb_descriptor_header *header;
988 unsigned char *begin;
989 int parsed = 0, len, numskipped;
991 header = (struct usb_descriptor_header *)buffer;
993 /* Everything should be fine being passed into here, but we sanity */
994 /* check JIC */
995 if (header->bLength > size) {
996 err("ran out of descriptors parsing");
997 return -1;
1000 if (header->bDescriptorType != USB_DT_ENDPOINT) {
1001 warn("unexpected descriptor 0x%X, expecting endpoint descriptor, type 0x%X",
1002 endpoint->bDescriptorType, USB_DT_ENDPOINT);
1003 return parsed;
1006 if (header->bLength == USB_DT_ENDPOINT_AUDIO_SIZE)
1007 memcpy(endpoint, buffer, USB_DT_ENDPOINT_AUDIO_SIZE);
1008 else
1009 memcpy(endpoint, buffer, USB_DT_ENDPOINT_SIZE);
1011 le16_to_cpus(&endpoint->wMaxPacketSize);
1013 buffer += header->bLength;
1014 size -= header->bLength;
1015 parsed += header->bLength;
1017 /* Skip over the rest of the Class Specific or Vendor Specific */
1018 /* descriptors */
1019 begin = buffer;
1020 numskipped = 0;
1021 while (size >= sizeof(struct usb_descriptor_header)) {
1022 header = (struct usb_descriptor_header *)buffer;
1024 if (header->bLength < 2) {
1025 err("invalid descriptor length of %d", header->bLength);
1026 return -1;
1029 /* If we find another descriptor which is at or below us */
1030 /* in the descriptor heirarchy then we're done */
1031 if ((header->bDescriptorType == USB_DT_ENDPOINT) ||
1032 (header->bDescriptorType == USB_DT_INTERFACE) ||
1033 (header->bDescriptorType == USB_DT_CONFIG) ||
1034 (header->bDescriptorType == USB_DT_DEVICE))
1035 break;
1037 dbg("skipping descriptor 0x%X",
1038 header->bDescriptorType);
1039 numskipped++;
1041 buffer += header->bLength;
1042 size -= header->bLength;
1043 parsed += header->bLength;
1045 if (numskipped)
1046 dbg("skipped %d class/vendor specific endpoint descriptors", numskipped);
1048 /* Copy any unknown descriptors into a storage area for drivers */
1049 /* to later parse */
1050 len = (int)(buffer - begin);
1051 if (!len) {
1052 endpoint->extra = NULL;
1053 endpoint->extralen = 0;
1054 return parsed;
1057 endpoint->extra = kmalloc(len, GFP_KERNEL);
1059 if (!endpoint->extra) {
1060 err("couldn't allocate memory for endpoint extra descriptors");
1061 endpoint->extralen = 0;
1062 return parsed;
1065 memcpy(endpoint->extra, begin, len);
1066 endpoint->extralen = len;
1068 return parsed;
1071 static int usb_parse_interface(struct usb_device *dev, struct usb_interface *interface, unsigned char *buffer, int size)
1073 int i, len, numskipped, retval, parsed = 0;
1074 struct usb_descriptor_header *header;
1075 struct usb_interface_descriptor *ifp;
1076 unsigned char *begin;
1078 interface->act_altsetting = 0;
1079 interface->num_altsetting = 0;
1080 interface->max_altsetting = USB_ALTSETTINGALLOC;
1082 interface->altsetting = kmalloc(sizeof(struct usb_interface_descriptor) * interface->max_altsetting, GFP_KERNEL);
1084 if (!interface->altsetting) {
1085 err("couldn't kmalloc interface->altsetting");
1086 return -1;
1089 while (size > 0) {
1090 if (interface->num_altsetting >= interface->max_altsetting) {
1091 void *ptr;
1092 int oldmas;
1094 oldmas = interface->max_altsetting;
1095 interface->max_altsetting += USB_ALTSETTINGALLOC;
1096 if (interface->max_altsetting > USB_MAXALTSETTING) {
1097 warn("too many alternate settings (max %d)",
1098 USB_MAXALTSETTING);
1099 return -1;
1102 ptr = interface->altsetting;
1103 interface->altsetting = kmalloc(sizeof(struct usb_interface_descriptor) * interface->max_altsetting, GFP_KERNEL);
1104 if (!interface->altsetting) {
1105 err("couldn't kmalloc interface->altsetting");
1106 interface->altsetting = ptr;
1107 return -1;
1109 memcpy(interface->altsetting, ptr, sizeof(struct usb_interface_descriptor) * oldmas);
1111 kfree(ptr);
1114 ifp = interface->altsetting + interface->num_altsetting;
1115 interface->num_altsetting++;
1117 memcpy(ifp, buffer, USB_DT_INTERFACE_SIZE);
1119 /* Skip over the interface */
1120 buffer += ifp->bLength;
1121 parsed += ifp->bLength;
1122 size -= ifp->bLength;
1124 begin = buffer;
1125 numskipped = 0;
1127 /* Skip over any interface, class or vendor descriptors */
1128 while (size >= sizeof(struct usb_descriptor_header)) {
1129 header = (struct usb_descriptor_header *)buffer;
1131 if (header->bLength < 2) {
1132 err("invalid descriptor length of %d", header->bLength);
1133 return -1;
1136 /* If we find another descriptor which is at or below */
1137 /* us in the descriptor heirarchy then return */
1138 if ((header->bDescriptorType == USB_DT_INTERFACE) ||
1139 (header->bDescriptorType == USB_DT_ENDPOINT) ||
1140 (header->bDescriptorType == USB_DT_CONFIG) ||
1141 (header->bDescriptorType == USB_DT_DEVICE))
1142 break;
1144 numskipped++;
1146 buffer += header->bLength;
1147 parsed += header->bLength;
1148 size -= header->bLength;
1151 if (numskipped)
1152 dbg("skipped %d class/vendor specific interface descriptors", numskipped);
1154 /* Copy any unknown descriptors into a storage area for */
1155 /* drivers to later parse */
1156 len = (int)(buffer - begin);
1157 if (!len) {
1158 ifp->extra = NULL;
1159 ifp->extralen = 0;
1160 } else {
1161 ifp->extra = kmalloc(len, GFP_KERNEL);
1163 if (!ifp->extra) {
1164 err("couldn't allocate memory for interface extra descriptors");
1165 ifp->extralen = 0;
1166 return -1;
1168 memcpy(ifp->extra, begin, len);
1169 ifp->extralen = len;
1172 /* Did we hit an unexpected descriptor? */
1173 header = (struct usb_descriptor_header *)buffer;
1174 if ((size >= sizeof(struct usb_descriptor_header)) &&
1175 ((header->bDescriptorType == USB_DT_CONFIG) ||
1176 (header->bDescriptorType == USB_DT_DEVICE)))
1177 return parsed;
1179 if (ifp->bNumEndpoints > USB_MAXENDPOINTS) {
1180 warn("too many endpoints");
1181 return -1;
1184 ifp->endpoint = (struct usb_endpoint_descriptor *)
1185 kmalloc(ifp->bNumEndpoints *
1186 sizeof(struct usb_endpoint_descriptor), GFP_KERNEL);
1187 if (!ifp->endpoint) {
1188 err("out of memory");
1189 return -1;
1192 memset(ifp->endpoint, 0, ifp->bNumEndpoints *
1193 sizeof(struct usb_endpoint_descriptor));
1195 for (i = 0; i < ifp->bNumEndpoints; i++) {
1196 header = (struct usb_descriptor_header *)buffer;
1198 if (header->bLength > size) {
1199 err("ran out of descriptors parsing");
1200 return -1;
1203 retval = usb_parse_endpoint(dev, ifp->endpoint + i, buffer, size);
1204 if (retval < 0)
1205 return retval;
1207 buffer += retval;
1208 parsed += retval;
1209 size -= retval;
1212 /* We check to see if it's an alternate to this one */
1213 ifp = (struct usb_interface_descriptor *)buffer;
1214 if (size < USB_DT_INTERFACE_SIZE ||
1215 ifp->bDescriptorType != USB_DT_INTERFACE ||
1216 !ifp->bAlternateSetting)
1217 return parsed;
1220 return parsed;
1223 int usb_parse_configuration(struct usb_device *dev, struct usb_config_descriptor *config, char *buffer)
1225 int i;
1226 int retval;
1227 int size;
1228 struct usb_descriptor_header *header;
1230 memcpy(config, buffer, USB_DT_CONFIG_SIZE);
1231 le16_to_cpus(&config->wTotalLength);
1232 size = config->wTotalLength;
1234 if (config->bNumInterfaces > USB_MAXINTERFACES) {
1235 warn("too many interfaces");
1236 return -1;
1239 config->interface = (struct usb_interface *)
1240 kmalloc(config->bNumInterfaces *
1241 sizeof(struct usb_interface), GFP_KERNEL);
1242 dbg("kmalloc IF %p, numif %i",config->interface,config->bNumInterfaces);
1243 if (!config->interface) {
1244 err("out of memory");
1245 return -1;
1248 memset(config->interface, 0,
1249 config->bNumInterfaces * sizeof(struct usb_interface));
1251 buffer += config->bLength;
1252 size -= config->bLength;
1254 for (i = 0; i < config->bNumInterfaces; i++) {
1255 header = (struct usb_descriptor_header *)buffer;
1256 if ((header->bLength > size) || (header->bLength <= 2)) {
1257 err("ran out of descriptors parsing");
1258 return -1;
1261 if (header->bDescriptorType != USB_DT_INTERFACE) {
1262 warn("unexpected descriptor 0x%X",
1263 header->bDescriptorType);
1265 buffer += header->bLength;
1266 size -= header->bLength;
1267 continue;
1270 retval = usb_parse_interface(dev, config->interface + i, buffer, size);
1271 if (retval < 0)
1272 return retval;
1274 buffer += retval;
1275 size -= retval;
1278 return size;
1281 void usb_destroy_configuration(struct usb_device *dev)
1283 int c, i, j, k;
1285 if (!dev->config)
1286 return;
1288 if (dev->rawdescriptors) {
1289 for (i = 0; i < dev->descriptor.bNumConfigurations; i++)
1290 kfree(dev->rawdescriptors[i]);
1292 kfree(dev->rawdescriptors);
1295 for (c = 0; c < dev->descriptor.bNumConfigurations; c++) {
1296 struct usb_config_descriptor *cf = &dev->config[c];
1298 if (!cf->interface)
1299 break;
1301 for (i = 0; i < cf->bNumInterfaces; i++) {
1302 struct usb_interface *ifp =
1303 &cf->interface[i];
1305 if (!ifp->altsetting)
1306 break;
1308 for (j = 0; j < ifp->num_altsetting; j++) {
1309 struct usb_interface_descriptor *as =
1310 &ifp->altsetting[j];
1312 if(as->extra) {
1313 kfree(as->extra);
1316 if (!as->endpoint)
1317 break;
1319 for(k = 0; k < as->bNumEndpoints; k++) {
1320 if(as->endpoint[k].extra) {
1321 kfree(as->endpoint[k].extra);
1324 kfree(as->endpoint);
1327 kfree(ifp->altsetting);
1329 kfree(cf->interface);
1331 kfree(dev->config);
1334 void usb_init_root_hub(struct usb_device *dev)
1336 dev->devnum = -1;
1337 dev->slow = 0;
1338 dev->actconfig = NULL;
1341 /* for returning string descriptors in UTF-16LE */
1342 static int ascii2utf (char *ascii, __u8 *utf, int utfmax)
1344 int retval;
1346 for (retval = 0; *ascii && utfmax > 1; utfmax -= 2, retval += 2) {
1347 *utf++ = *ascii++ & 0x7f;
1348 *utf++ = 0;
1350 return retval;
1354 * root_hub_string is used by each host controller's root hub code,
1355 * so that they're identified consistently throughout the system.
1357 int usb_root_hub_string (int id, int serial, char *type, __u8 *data, int len)
1359 char buf [30];
1361 // assert (len > (2 * (sizeof (buf) + 1)));
1362 // assert (strlen (type) <= 8);
1364 // language ids
1365 if (id == 0) {
1366 *data++ = 4; *data++ = 3; /* 4 bytes data */
1367 *data++ = 0; *data++ = 0; /* some language id */
1368 return 4;
1370 // serial number
1371 } else if (id == 1) {
1372 sprintf (buf, "%x", serial);
1374 // product description
1375 } else if (id == 2) {
1376 sprintf (buf, "USB %s Root Hub", type);
1378 // id 3 == vendor description
1380 // unsupported IDs --> "stall"
1381 } else
1382 return 0;
1384 data [0] = 2 + ascii2utf (buf, data + 2, len - 2);
1385 data [1] = 3;
1386 return data [0];
1390 * __usb_get_extra_descriptor() finds a descriptor of specific type in the
1391 * extra field of the interface and endpoint descriptor structs.
1394 int __usb_get_extra_descriptor(char *buffer, unsigned size, unsigned char type, void **ptr)
1396 struct usb_descriptor_header *header;
1398 while (size >= sizeof(struct usb_descriptor_header)) {
1399 header = (struct usb_descriptor_header *)buffer;
1401 if (header->bLength < 2) {
1402 err("invalid descriptor length of %d", header->bLength);
1403 return -1;
1406 if (header->bDescriptorType == type) {
1407 *ptr = header;
1408 return 0;
1411 buffer += header->bLength;
1412 size -= header->bLength;
1414 return -1;
1418 * Something got disconnected. Get rid of it, and all of its children.
1420 void usb_disconnect(struct usb_device **pdev)
1422 struct usb_device * dev = *pdev;
1423 int i;
1425 if (!dev)
1426 return;
1428 *pdev = NULL;
1430 info("USB disconnect on device %d", dev->devnum);
1432 call_policy ("remove", dev);
1434 if (dev->actconfig) {
1435 for (i = 0; i < dev->actconfig->bNumInterfaces; i++) {
1436 struct usb_interface *interface = &dev->actconfig->interface[i];
1437 struct usb_driver *driver = interface->driver;
1438 if (driver) {
1439 down(&driver->serialize);
1440 driver->disconnect(dev, interface->private_data);
1441 up(&driver->serialize);
1442 usb_driver_release_interface(driver, interface);
1447 /* Free up all the children.. */
1448 for (i = 0; i < USB_MAXCHILDREN; i++) {
1449 struct usb_device **child = dev->children + i;
1450 if (*child)
1451 usb_disconnect(child);
1454 /* remove /proc/bus/usb entry */
1455 usbdevfs_remove_device(dev);
1457 /* Free up the device itself, including its device number */
1458 if (dev->devnum > 0)
1459 clear_bit(dev->devnum, &dev->bus->devmap.devicemap);
1461 usb_free_dev(dev);
1465 * Connect a new USB device. This basically just initializes
1466 * the USB device information and sets up the topology - it's
1467 * up to the low-level driver to reset the port and actually
1468 * do the setup (the upper levels don't know how to do that).
1470 void usb_connect(struct usb_device *dev)
1472 int devnum;
1473 // FIXME needs locking for SMP!!
1474 /* why? this is called only from the hub thread,
1475 * which hopefully doesn't run on multiple CPU's simulatenously 8-)
1477 dev->descriptor.bMaxPacketSize0 = 8; /* Start off at 8 bytes */
1478 devnum = find_next_zero_bit(dev->bus->devmap.devicemap, 128, 1);
1479 if (devnum < 128) {
1480 set_bit(devnum, dev->bus->devmap.devicemap);
1481 dev->devnum = devnum;
1486 * These are the actual routines to send
1487 * and receive control messages.
1490 #define GET_TIMEOUT 3
1491 #define SET_TIMEOUT 3
1493 int usb_set_address(struct usb_device *dev)
1495 return usb_control_msg(dev, usb_snddefctrl(dev), USB_REQ_SET_ADDRESS,
1496 0, dev->devnum, 0, NULL, 0, HZ * GET_TIMEOUT);
1499 int usb_get_descriptor(struct usb_device *dev, unsigned char type, unsigned char index, void *buf, int size)
1501 int i = 5;
1502 int result;
1504 memset(buf,0,size); // Make sure we parse really received data
1506 while (i--) {
1507 if ((result = usb_control_msg(dev, usb_rcvctrlpipe(dev, 0),
1508 USB_REQ_GET_DESCRIPTOR, USB_DIR_IN,
1509 (type << 8) + index, 0, buf, size, HZ * GET_TIMEOUT)) >= 0 ||
1510 result == -EPIPE)
1511 break;
1513 return result;
1516 int usb_get_class_descriptor(struct usb_device *dev, int ifnum,
1517 unsigned char type, unsigned char id, void *buf, int size)
1519 return usb_control_msg(dev, usb_rcvctrlpipe(dev, 0),
1520 USB_REQ_GET_DESCRIPTOR, USB_RECIP_INTERFACE | USB_DIR_IN,
1521 (type << 8) + id, ifnum, buf, size, HZ * GET_TIMEOUT);
1524 int usb_get_string(struct usb_device *dev, unsigned short langid, unsigned char index, void *buf, int size)
1526 return usb_control_msg(dev, usb_rcvctrlpipe(dev, 0),
1527 USB_REQ_GET_DESCRIPTOR, USB_DIR_IN,
1528 (USB_DT_STRING << 8) + index, langid, buf, size, HZ * GET_TIMEOUT);
1531 int usb_get_device_descriptor(struct usb_device *dev)
1533 int ret = usb_get_descriptor(dev, USB_DT_DEVICE, 0, &dev->descriptor,
1534 sizeof(dev->descriptor));
1535 if (ret >= 0) {
1536 le16_to_cpus(&dev->descriptor.bcdUSB);
1537 le16_to_cpus(&dev->descriptor.idVendor);
1538 le16_to_cpus(&dev->descriptor.idProduct);
1539 le16_to_cpus(&dev->descriptor.bcdDevice);
1541 return ret;
1544 int usb_get_status(struct usb_device *dev, int type, int target, void *data)
1546 return usb_control_msg(dev, usb_rcvctrlpipe(dev, 0),
1547 USB_REQ_GET_STATUS, USB_DIR_IN | type, 0, target, data, 2, HZ * GET_TIMEOUT);
1550 int usb_get_protocol(struct usb_device *dev, int ifnum)
1552 unsigned char type;
1553 int ret;
1555 if ((ret = usb_control_msg(dev, usb_rcvctrlpipe(dev, 0),
1556 USB_REQ_GET_PROTOCOL, USB_DIR_IN | USB_TYPE_CLASS | USB_RECIP_INTERFACE,
1557 0, ifnum, &type, 1, HZ * GET_TIMEOUT)) < 0)
1558 return ret;
1560 return type;
1563 int usb_set_protocol(struct usb_device *dev, int ifnum, int protocol)
1565 return usb_control_msg(dev, usb_sndctrlpipe(dev, 0),
1566 USB_REQ_SET_PROTOCOL, USB_TYPE_CLASS | USB_RECIP_INTERFACE,
1567 protocol, ifnum, NULL, 0, HZ * SET_TIMEOUT);
1570 int usb_set_idle(struct usb_device *dev, int ifnum, int duration, int report_id)
1572 return usb_control_msg(dev, usb_sndctrlpipe(dev, 0),
1573 USB_REQ_SET_IDLE, USB_TYPE_CLASS | USB_RECIP_INTERFACE,
1574 (duration << 8) | report_id, ifnum, NULL, 0, HZ * SET_TIMEOUT);
1577 void usb_set_maxpacket(struct usb_device *dev)
1579 int i, b;
1581 for (i=0; i<dev->actconfig->bNumInterfaces; i++) {
1582 struct usb_interface *ifp = dev->actconfig->interface + i;
1583 struct usb_interface_descriptor *as = ifp->altsetting + ifp->act_altsetting;
1584 struct usb_endpoint_descriptor *ep = as->endpoint;
1585 int e;
1587 for (e=0; e<as->bNumEndpoints; e++) {
1588 b = ep[e].bEndpointAddress & USB_ENDPOINT_NUMBER_MASK;
1589 if ((ep[e].bmAttributes & USB_ENDPOINT_XFERTYPE_MASK) ==
1590 USB_ENDPOINT_XFER_CONTROL) { /* Control => bidirectional */
1591 dev->epmaxpacketout[b] = ep[e].wMaxPacketSize;
1592 dev->epmaxpacketin [b] = ep[e].wMaxPacketSize;
1594 else if (usb_endpoint_out(ep[e].bEndpointAddress)) {
1595 if (ep[e].wMaxPacketSize > dev->epmaxpacketout[b])
1596 dev->epmaxpacketout[b] = ep[e].wMaxPacketSize;
1598 else {
1599 if (ep[e].wMaxPacketSize > dev->epmaxpacketin [b])
1600 dev->epmaxpacketin [b] = ep[e].wMaxPacketSize;
1607 * endp: endpoint number in bits 0-3;
1608 * direction flag in bit 7 (1 = IN, 0 = OUT)
1610 int usb_clear_halt(struct usb_device *dev, int pipe)
1612 int result;
1613 __u16 status;
1614 int endp=usb_pipeendpoint(pipe)|(usb_pipein(pipe)<<7);
1617 if (!usb_endpoint_halted(dev, endp & 0x0f, usb_endpoint_out(endp)))
1618 return 0;
1621 result = usb_control_msg(dev, usb_sndctrlpipe(dev, 0),
1622 USB_REQ_CLEAR_FEATURE, USB_RECIP_ENDPOINT, 0, endp, NULL, 0, HZ * SET_TIMEOUT);
1624 /* don't clear if failed */
1625 if (result < 0)
1626 return result;
1628 result = usb_control_msg(dev, usb_rcvctrlpipe(dev, 0),
1629 USB_REQ_GET_STATUS, USB_DIR_IN | USB_RECIP_ENDPOINT, 0, endp,
1630 &status, sizeof(status), HZ * SET_TIMEOUT);
1631 if (result < 0)
1632 return result;
1634 if (status & 1)
1635 return -EPIPE; /* still halted */
1637 usb_endpoint_running(dev, usb_pipeendpoint(pipe), usb_pipeout(pipe));
1639 /* toggle is reset on clear */
1641 usb_settoggle(dev, usb_pipeendpoint(pipe), usb_pipeout(pipe), 0);
1643 return 0;
1646 int usb_set_interface(struct usb_device *dev, int interface, int alternate)
1648 struct usb_interface *iface;
1649 int ret;
1651 iface = usb_ifnum_to_if(dev, interface);
1652 if (!iface) {
1653 warn("selecting invalid interface %d", interface);
1654 return -EINVAL;
1657 if ((ret = usb_control_msg(dev, usb_sndctrlpipe(dev, 0),
1658 USB_REQ_SET_INTERFACE, USB_RECIP_INTERFACE, alternate,
1659 interface, NULL, 0, HZ * 5)) < 0)
1660 return ret;
1662 iface->act_altsetting = alternate;
1663 dev->toggle[0] = 0; /* 9.1.1.5 says to do this */
1664 dev->toggle[1] = 0;
1665 usb_set_maxpacket(dev);
1666 return 0;
1669 int usb_set_configuration(struct usb_device *dev, int configuration)
1671 int i, ret;
1672 struct usb_config_descriptor *cp = NULL;
1674 for (i=0; i<dev->descriptor.bNumConfigurations; i++) {
1675 if (dev->config[i].bConfigurationValue == configuration) {
1676 cp = &dev->config[i];
1677 break;
1680 if (!cp) {
1681 warn("selecting invalid configuration %d", configuration);
1682 return -1;
1685 if ((ret = usb_control_msg(dev, usb_sndctrlpipe(dev, 0),
1686 USB_REQ_SET_CONFIGURATION, 0, configuration, 0, NULL, 0, HZ * SET_TIMEOUT)) < 0)
1687 return ret;
1689 dev->actconfig = cp;
1690 dev->toggle[0] = 0;
1691 dev->toggle[1] = 0;
1692 usb_set_maxpacket(dev);
1694 return 0;
1697 int usb_get_report(struct usb_device *dev, int ifnum, unsigned char type, unsigned char id, void *buf, int size)
1699 return usb_control_msg(dev, usb_rcvctrlpipe(dev, 0),
1700 USB_REQ_GET_REPORT, USB_DIR_IN | USB_TYPE_CLASS | USB_RECIP_INTERFACE,
1701 (type << 8) + id, ifnum, buf, size, HZ * GET_TIMEOUT);
1704 int usb_set_report(struct usb_device *dev, int ifnum, unsigned char type, unsigned char id, void *buf, int size)
1706 return usb_control_msg(dev, usb_sndctrlpipe(dev, 0),
1707 USB_REQ_SET_REPORT, USB_TYPE_CLASS | USB_RECIP_INTERFACE,
1708 (type << 8) + id, ifnum, buf, size, HZ);
1711 int usb_get_configuration(struct usb_device *dev)
1713 int result;
1714 unsigned int cfgno, length;
1715 unsigned char buffer[8];
1716 unsigned char *bigbuffer;
1717 struct usb_config_descriptor *desc =
1718 (struct usb_config_descriptor *)buffer;
1720 if (dev->descriptor.bNumConfigurations > USB_MAXCONFIG) {
1721 warn("too many configurations");
1722 return -1;
1725 if (dev->descriptor.bNumConfigurations < 1) {
1726 warn("not enough configurations");
1727 return -1;
1730 dev->config = (struct usb_config_descriptor *)
1731 kmalloc(dev->descriptor.bNumConfigurations *
1732 sizeof(struct usb_config_descriptor), GFP_KERNEL);
1733 if (!dev->config) {
1734 err("out of memory");
1735 return -1;
1737 memset(dev->config, 0, dev->descriptor.bNumConfigurations *
1738 sizeof(struct usb_config_descriptor));
1740 dev->rawdescriptors = (char **)kmalloc(sizeof(char *) *
1741 dev->descriptor.bNumConfigurations, GFP_KERNEL);
1742 if (!dev->rawdescriptors) {
1743 err("out of memory");
1744 return -1;
1747 for (cfgno = 0; cfgno < dev->descriptor.bNumConfigurations; cfgno++) {
1748 /* We grab the first 8 bytes so we know how long the whole */
1749 /* configuration is */
1750 result = usb_get_descriptor(dev, USB_DT_CONFIG, cfgno, buffer, 8);
1751 if (result < 8) {
1752 if (result < 0)
1753 err("unable to get descriptor");
1754 else
1755 err("config descriptor too short (expected %i, got %i)", 8, result);
1756 goto err;
1759 /* Get the full buffer */
1760 length = le16_to_cpu(desc->wTotalLength);
1762 bigbuffer = kmalloc(length, GFP_KERNEL);
1763 if (!bigbuffer) {
1764 err("unable to allocate memory for configuration descriptors");
1765 result = -ENOMEM;
1766 goto err;
1769 /* Now that we know the length, get the whole thing */
1770 result = usb_get_descriptor(dev, USB_DT_CONFIG, cfgno, bigbuffer, length);
1771 if (result < 0) {
1772 err("couldn't get all of config descriptors");
1773 kfree(bigbuffer);
1774 goto err;
1777 if (result < length) {
1778 err("config descriptor too short (expected %i, got %i)", length, result);
1779 kfree(bigbuffer);
1780 goto err;
1783 dev->rawdescriptors[cfgno] = bigbuffer;
1785 result = usb_parse_configuration(dev, &dev->config[cfgno], bigbuffer);
1786 if (result > 0)
1787 dbg("descriptor data left");
1788 else if (result < 0) {
1789 result = -1;
1790 goto err;
1794 return 0;
1795 err:
1796 dev->descriptor.bNumConfigurations = cfgno;
1797 return result;
1801 * usb_string:
1802 * returns string length (> 0) or error (< 0)
1804 int usb_string(struct usb_device *dev, int index, char *buf, size_t size)
1806 unsigned char *tbuf;
1807 int err;
1808 unsigned int u, idx;
1810 if (size <= 0 || !buf || !index)
1811 return -EINVAL;
1812 buf[0] = 0;
1813 tbuf = kmalloc(256, GFP_KERNEL);
1814 if (!tbuf)
1815 return -ENOMEM;
1817 /* get langid for strings if it's not yet known */
1818 if (!dev->have_langid) {
1819 err = usb_get_string(dev, 0, 0, tbuf, 4);
1820 if (err < 0) {
1821 err("error getting string descriptor 0 (error=%d)", err);
1822 goto errout;
1823 } else if (tbuf[0] < 4) {
1824 err("string descriptor 0 too short");
1825 err = -EINVAL;
1826 goto errout;
1827 } else {
1828 dev->have_langid = -1;
1829 dev->string_langid = tbuf[2] | (tbuf[3]<< 8);
1830 /* always use the first langid listed */
1831 dbg("USB device number %d default language ID 0x%x",
1832 dev->devnum, dev->string_langid);
1837 * Just ask for a maximum length string and then take the length
1838 * that was returned.
1840 err = usb_get_string(dev, dev->string_langid, index, tbuf, 255);
1841 if (err < 0)
1842 goto errout;
1844 size--; /* leave room for trailing NULL char in output buffer */
1845 for (idx = 0, u = 2; u < err; u += 2) {
1846 if (idx >= size)
1847 break;
1848 if (tbuf[u+1]) /* high byte */
1849 buf[idx++] = '?'; /* non-ASCII character */
1850 else
1851 buf[idx++] = tbuf[u];
1853 buf[idx] = 0;
1854 err = idx;
1856 errout:
1857 kfree(tbuf);
1858 return err;
1862 * By the time we get here, the device has gotten a new device ID
1863 * and is in the default state. We need to identify the thing and
1864 * get the ball rolling..
1866 * Returns 0 for success, != 0 for error.
1868 int usb_new_device(struct usb_device *dev)
1870 int err;
1872 info("USB new device connect, assigned device number %d", dev->devnum);
1874 /* USB v1.1 5.5.3 */
1875 /* We read the first 8 bytes from the device descriptor to get to */
1876 /* the bMaxPacketSize0 field. Then we set the maximum packet size */
1877 /* for the control pipe, and retrieve the rest */
1878 dev->epmaxpacketin [0] = 8;
1879 dev->epmaxpacketout[0] = 8;
1881 err = usb_set_address(dev);
1882 if (err < 0) {
1883 err("USB device not accepting new address (error=%d)", err);
1884 clear_bit(dev->devnum, &dev->bus->devmap.devicemap);
1885 dev->devnum = -1;
1886 return 1;
1889 wait_ms(10); /* Let the SET_ADDRESS settle */
1891 err = usb_get_descriptor(dev, USB_DT_DEVICE, 0, &dev->descriptor, 8);
1892 if (err < 8) {
1893 if (err < 0)
1894 err("USB device not responding, giving up (error=%d)", err);
1895 else
1896 err("USB device descriptor short read (expected %i, got %i)",8,err);
1897 clear_bit(dev->devnum, &dev->bus->devmap.devicemap);
1898 dev->devnum = -1;
1899 return 1;
1901 dev->epmaxpacketin [0] = dev->descriptor.bMaxPacketSize0;
1902 dev->epmaxpacketout[0] = dev->descriptor.bMaxPacketSize0;
1904 err = usb_get_device_descriptor(dev);
1905 if (err < sizeof(dev->descriptor)) {
1906 if (err < 0)
1907 err("unable to get device descriptor (error=%d)", err);
1908 else
1909 err("USB device descriptor short read (expected %i, got %i)", sizeof(dev->descriptor), err);
1911 clear_bit(dev->devnum, &dev->bus->devmap.devicemap);
1912 dev->devnum = -1;
1913 return 1;
1916 err = usb_get_configuration(dev);
1917 if (err < 0) {
1918 err("unable to get configuration (error=%d)", err);
1919 clear_bit(dev->devnum, &dev->bus->devmap.devicemap);
1920 dev->devnum = -1;
1921 return 1;
1924 dev->actconfig = dev->config;
1925 usb_set_maxpacket(dev);
1927 /* we set the default configuration here */
1928 err = usb_set_configuration(dev, dev->config[0].bConfigurationValue);
1929 if (err) {
1930 err("failed to set default configuration (error=%d)", err);
1931 return -1;
1934 dbg("new device strings: Mfr=%d, Product=%d, SerialNumber=%d",
1935 dev->descriptor.iManufacturer, dev->descriptor.iProduct, dev->descriptor.iSerialNumber);
1936 #ifdef DEBUG
1937 if (dev->descriptor.iManufacturer)
1938 usb_show_string(dev, "Manufacturer", dev->descriptor.iManufacturer);
1939 if (dev->descriptor.iProduct)
1940 usb_show_string(dev, "Product", dev->descriptor.iProduct);
1941 if (dev->descriptor.iSerialNumber)
1942 usb_show_string(dev, "SerialNumber", dev->descriptor.iSerialNumber);
1943 #endif
1945 /* now that the basic setup is over, add a /proc/bus/usb entry */
1946 usbdevfs_add_device(dev);
1948 /* find drivers willing to handle this device */
1949 usb_find_drivers(dev);
1951 /* userspace may load modules and/or configure further */
1952 call_policy ("add", dev);
1954 return 0;
1957 static int usb_open(struct inode * inode, struct file * file)
1959 int minor = MINOR(inode->i_rdev);
1960 struct usb_driver *c = usb_minors[minor/16];
1961 int err = -ENODEV;
1962 struct file_operations *old_fops, *new_fops = NULL;
1965 * No load-on-demand? Randy, could you ACK that it's really not
1966 * supposed to be done? -- AV
1968 if (!c || !(new_fops = fops_get(c->fops)))
1969 return err;
1970 old_fops = file->f_op;
1971 file->f_op = new_fops;
1972 /* Curiouser and curiouser... NULL ->open() as "no device" ? */
1973 if (file->f_op->open)
1974 err = file->f_op->open(inode,file);
1975 if (err) {
1976 fops_put(file->f_op);
1977 file->f_op = fops_get(old_fops);
1979 fops_put(old_fops);
1980 return err;
1983 static struct file_operations usb_fops = {
1984 owner: THIS_MODULE,
1985 open: usb_open,
1988 int usb_major_init(void)
1990 if (register_chrdev(USB_MAJOR,"usb",&usb_fops)) {
1991 err("unable to get major %d for usb devices", USB_MAJOR);
1992 return -EBUSY;
1994 return 0;
1997 void usb_major_cleanup(void)
1999 unregister_chrdev(USB_MAJOR, "usb");
2003 #ifdef CONFIG_PROC_FS
2004 struct list_head *usb_driver_get_list(void)
2006 return &usb_driver_list;
2009 struct list_head *usb_bus_get_list(void)
2011 return &usb_bus_list;
2013 #endif
2016 * USB may be built into the kernel or be built as modules.
2017 * If the USB core [and maybe a host controller driver] is built
2018 * into the kernel, and other device drivers are built as modules,
2019 * then these symbols need to be exported for the modules to use.
2021 EXPORT_SYMBOL(usb_ifnum_to_if);
2023 EXPORT_SYMBOL(usb_register);
2024 EXPORT_SYMBOL(usb_deregister);
2025 EXPORT_SYMBOL(usb_scan_devices);
2026 EXPORT_SYMBOL(usb_alloc_bus);
2027 EXPORT_SYMBOL(usb_free_bus);
2028 EXPORT_SYMBOL(usb_register_bus);
2029 EXPORT_SYMBOL(usb_deregister_bus);
2030 EXPORT_SYMBOL(usb_alloc_dev);
2031 EXPORT_SYMBOL(usb_free_dev);
2032 EXPORT_SYMBOL(usb_inc_dev_use);
2034 EXPORT_SYMBOL(usb_driver_claim_interface);
2035 EXPORT_SYMBOL(usb_interface_claimed);
2036 EXPORT_SYMBOL(usb_driver_release_interface);
2038 EXPORT_SYMBOL(usb_init_root_hub);
2039 EXPORT_SYMBOL(usb_root_hub_string);
2040 EXPORT_SYMBOL(usb_new_device);
2041 EXPORT_SYMBOL(usb_reset_device);
2042 EXPORT_SYMBOL(usb_connect);
2043 EXPORT_SYMBOL(usb_disconnect);
2045 EXPORT_SYMBOL(usb_check_bandwidth);
2046 EXPORT_SYMBOL(usb_claim_bandwidth);
2047 EXPORT_SYMBOL(usb_release_bandwidth);
2049 EXPORT_SYMBOL(usb_set_address);
2050 EXPORT_SYMBOL(usb_get_descriptor);
2051 EXPORT_SYMBOL(usb_get_class_descriptor);
2052 EXPORT_SYMBOL(__usb_get_extra_descriptor);
2053 EXPORT_SYMBOL(usb_get_device_descriptor);
2054 EXPORT_SYMBOL(usb_get_string);
2055 EXPORT_SYMBOL(usb_string);
2056 EXPORT_SYMBOL(usb_get_protocol);
2057 EXPORT_SYMBOL(usb_set_protocol);
2058 EXPORT_SYMBOL(usb_get_report);
2059 EXPORT_SYMBOL(usb_set_report);
2060 EXPORT_SYMBOL(usb_set_idle);
2061 EXPORT_SYMBOL(usb_clear_halt);
2062 EXPORT_SYMBOL(usb_set_interface);
2063 EXPORT_SYMBOL(usb_get_configuration);
2064 EXPORT_SYMBOL(usb_set_configuration);
2066 EXPORT_SYMBOL(usb_get_current_frame_number);
2068 EXPORT_SYMBOL(usb_alloc_urb);
2069 EXPORT_SYMBOL(usb_free_urb);
2070 EXPORT_SYMBOL(usb_submit_urb);
2071 EXPORT_SYMBOL(usb_unlink_urb);
2073 EXPORT_SYMBOL(usb_control_msg);
2074 EXPORT_SYMBOL(usb_bulk_msg);