linux-old/drivers/usb/usb.c
<<
>>
Prefs
   1/*
   2 * drivers/usb/usb.c
   3 *
   4 * (C) Copyright Linus Torvalds 1999
   5 * (C) Copyright Johannes Erdfelt 1999-2001
   6 * (C) Copyright Andreas Gal 1999
   7 * (C) Copyright Gregory P. Smith 1999
   8 * (C) Copyright Deti Fliegl 1999 (new USB architecture)
   9 * (C) Copyright Randy Dunlap 2000
  10 * (C) Copyright David Brownell 2000 (kernel hotplug, usb_device_id)
  11 * (C) Copyright Yggdrasil Computing, Inc. 2000
  12 *     (usb_device_id matching changes by Adam J. Richter)
  13 *
  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..
  17 *
  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.
  21 */
  22
  23#include <linux/config.h>
  24#include <linux/module.h>
  25#include <linux/string.h>
  26#include <linux/bitops.h>
  27#include <linux/slab.h>
  28#include <linux/interrupt.h>  /* for in_interrupt() */
  29#include <linux/kmod.h>
  30#include <linux/init.h>
  31#include <linux/devfs_fs_kernel.h>
  32#include <linux/spinlock.h>
  33
  34#ifdef CONFIG_USB_DEBUG
  35        #define DEBUG
  36#else
  37        #undef DEBUG
  38#endif
  39#include <linux/usb.h>
  40
  41#include "hcd.h"
  42
  43static const int usb_bandwidth_option =
  44#ifdef CONFIG_USB_BANDWIDTH
  45                                1;
  46#else
  47                                0;
  48#endif
  49
  50extern int  usb_hub_init(void);
  51extern void usb_hub_cleanup(void);
  52
  53/*
  54 * Prototypes for the device driver probing/loading functions
  55 */
  56static void usb_find_drivers(struct usb_device *);
  57static int  usb_find_interface_driver(struct usb_device *, unsigned int);
  58static void usb_check_support(struct usb_device *);
  59
  60/*
  61 * We have a per-interface "registered driver" list.
  62 */
  63LIST_HEAD(usb_driver_list);
  64LIST_HEAD(usb_bus_list);
  65struct semaphore usb_bus_list_lock;
  66
  67devfs_handle_t usb_devfs_handle;        /* /dev/usb dir. */
  68
  69static struct usb_busmap busmap;
  70
  71static struct usb_driver *usb_minors[16];
  72
  73/**
  74 *      usb_register - register a USB driver
  75 *      @new_driver: USB operations for the driver
  76 *
  77 *      Registers a USB driver with the USB core.  The list of unattached
  78 *      interfaces will be rescanned whenever a new driver is added, allowing
  79 *      the new driver to attach to any recognized devices.
  80 *      Returns a negative error code on failure and 0 on success.
  81 */
  82int usb_register(struct usb_driver *new_driver)
  83{
  84        if (new_driver->fops != NULL) {
  85                if (usb_minors[new_driver->minor/16]) {
  86                         err("error registering %s driver", new_driver->name);
  87                        return -EINVAL;
  88                }
  89                usb_minors[new_driver->minor/16] = new_driver;
  90        }
  91
  92        info("registered new driver %s", new_driver->name);
  93
  94        init_MUTEX(&new_driver->serialize);
  95
  96        /* Add it to the list of known drivers */
  97        list_add_tail(&new_driver->driver_list, &usb_driver_list);
  98
  99        usb_scan_devices();
 100
 101        return 0;
 102}
 103
 104/**
 105 *      usb_scan_devices - scans all unclaimed USB interfaces
 106 *
 107 *      Goes through all unclaimed USB interfaces, and offers them to all
 108 *      registered USB drivers through the 'probe' function.
 109 *      This will automatically be called after usb_register is called.
 110 *      It is called by some of the USB subsystems after one of their subdrivers
 111 *      are registered.
 112 */
 113void usb_scan_devices(void)
 114{
 115        struct list_head *tmp;
 116
 117        down (&usb_bus_list_lock);
 118        tmp = usb_bus_list.next;
 119        while (tmp != &usb_bus_list) {
 120                struct usb_bus *bus = list_entry(tmp,struct usb_bus, bus_list);
 121
 122                tmp = tmp->next;
 123                usb_check_support(bus->root_hub);
 124        }
 125        up (&usb_bus_list_lock);
 126}
 127
 128/*
 129 * This function is part of a depth-first search down the device tree,
 130 * removing any instances of a device driver.
 131 */
 132static void usb_drivers_purge(struct usb_driver *driver,struct usb_device *dev)
 133{
 134        int i;
 135
 136        if (!dev) {
 137                err("null device being purged!!!");
 138                return;
 139        }
 140
 141        for (i=0; i<USB_MAXCHILDREN; i++)
 142                if (dev->children[i])
 143                        usb_drivers_purge(driver, dev->children[i]);
 144
 145        if (!dev->actconfig)
 146                return;
 147                        
 148        for (i = 0; i < dev->actconfig->bNumInterfaces; i++) {
 149                struct usb_interface *interface = &dev->actconfig->interface[i];
 150                
 151                if (interface->driver == driver) {
 152                        down(&driver->serialize);
 153                        driver->disconnect(dev, interface->private_data);
 154                        up(&driver->serialize);
 155                        /* if driver->disconnect didn't release the interface */
 156                        if (interface->driver)
 157                                usb_driver_release_interface(driver, interface);
 158                        /*
 159                         * This will go through the list looking for another
 160                         * driver that can handle the device
 161                         */
 162                        usb_find_interface_driver(dev, i);
 163                }
 164        }
 165}
 166
 167/**
 168 *      usb_deregister - unregister a USB driver
 169 *      @driver: USB operations of the driver to unregister
 170 *
 171 *      Unlinks the specified driver from the internal USB driver list.
 172 */
 173void usb_deregister(struct usb_driver *driver)
 174{
 175        struct list_head *tmp;
 176
 177        info("deregistering driver %s", driver->name);
 178        if (driver->fops != NULL)
 179                usb_minors[driver->minor/16] = NULL;
 180
 181        /*
 182         * first we remove the driver, to be sure it doesn't get used by
 183         * another thread while we are stepping through removing entries
 184         */
 185        list_del(&driver->driver_list);
 186
 187        down (&usb_bus_list_lock);
 188        tmp = usb_bus_list.next;
 189        while (tmp != &usb_bus_list) {
 190                struct usb_bus *bus = list_entry(tmp,struct usb_bus,bus_list);
 191
 192                tmp = tmp->next;
 193                usb_drivers_purge(driver, bus->root_hub);
 194        }
 195        up (&usb_bus_list_lock);
 196}
 197
 198int usb_ifnum_to_ifpos(struct usb_device *dev, unsigned ifnum)
 199{
 200        int i;
 201
 202        for (i = 0; i < dev->actconfig->bNumInterfaces; i++)
 203                if (dev->actconfig->interface[i].altsetting[0].bInterfaceNumber == ifnum)
 204                        return i;
 205
 206        return -EINVAL;
 207}
 208
 209struct usb_interface *usb_ifnum_to_if(struct usb_device *dev, unsigned ifnum)
 210{
 211        int i;
 212
 213        for (i = 0; i < dev->actconfig->bNumInterfaces; i++)
 214                if (dev->actconfig->interface[i].altsetting[0].bInterfaceNumber == ifnum)
 215                        return &dev->actconfig->interface[i];
 216
 217        return NULL;
 218}
 219
 220struct usb_endpoint_descriptor *usb_epnum_to_ep_desc(struct usb_device *dev, unsigned epnum)
 221{
 222        int i, j, k;
 223
 224        for (i = 0; i < dev->actconfig->bNumInterfaces; i++)
 225                for (j = 0; j < dev->actconfig->interface[i].num_altsetting; j++)
 226                        for (k = 0; k < dev->actconfig->interface[i].altsetting[j].bNumEndpoints; k++)
 227                                if (epnum == dev->actconfig->interface[i].altsetting[j].endpoint[k].bEndpointAddress)
 228                                        return &dev->actconfig->interface[i].altsetting[j].endpoint[k];
 229
 230        return NULL;
 231}
 232
 233/*
 234 * usb_calc_bus_time - approximate periodic transaction time in nanoseconds
 235 * @speed: from dev->speed; USB_SPEED_{LOW,FULL,HIGH}
 236 * @is_input: true iff the transaction sends data to the host
 237 * @isoc: true for isochronous transactions, false for interrupt ones
 238 * @bytecount: how many bytes in the transaction.
 239 *
 240 * Returns approximate bus time in nanoseconds for a periodic transaction.
 241 * See USB 2.0 spec section 5.11.3; only periodic transfers need to be
 242 * scheduled in software, this function is only used for such scheduling.
 243 */
 244long usb_calc_bus_time (int speed, int is_input, int isoc, int bytecount)
 245{
 246        unsigned long   tmp;
 247
 248        switch (speed) {
 249        case USB_SPEED_LOW:     /* INTR only */
 250                if (is_input) {
 251                        tmp = (67667L * (31L + 10L * BitTime (bytecount))) / 1000L;
 252                        return (64060L + (2 * BW_HUB_LS_SETUP) + BW_HOST_DELAY + tmp);
 253                } else {
 254                        tmp = (66700L * (31L + 10L * BitTime (bytecount))) / 1000L;
 255                        return (64107L + (2 * BW_HUB_LS_SETUP) + BW_HOST_DELAY + tmp);
 256                }
 257        case USB_SPEED_FULL:    /* ISOC or INTR */
 258                if (isoc) {
 259                        tmp = (8354L * (31L + 10L * BitTime (bytecount))) / 1000L;
 260                        return (((is_input) ? 7268L : 6265L) + BW_HOST_DELAY + tmp);
 261                } else {
 262                        tmp = (8354L * (31L + 10L * BitTime (bytecount))) / 1000L;
 263                        return (9107L + BW_HOST_DELAY + tmp);
 264                }
 265        case USB_SPEED_HIGH:    /* ISOC or INTR */
 266                // FIXME adjust for input vs output
 267                if (isoc)
 268                        tmp = HS_USECS (bytecount);
 269                else
 270                        tmp = HS_USECS_ISO (bytecount);
 271                return tmp;
 272        default:
 273                dbg ("bogus device speed!");
 274                return -1;
 275        }
 276}
 277
 278
 279/*
 280 * usb_check_bandwidth():
 281 *
 282 * old_alloc is from host_controller->bandwidth_allocated in microseconds;
 283 * bustime is from calc_bus_time(), but converted to microseconds.
 284 *
 285 * returns <bustime in us> if successful,
 286 * or USB_ST_BANDWIDTH_ERROR if bandwidth request fails.
 287 *
 288 * FIXME:
 289 * This initial implementation does not use Endpoint.bInterval
 290 * in managing bandwidth allocation.
 291 * It probably needs to be expanded to use Endpoint.bInterval.
 292 * This can be done as a later enhancement (correction).
 293 * This will also probably require some kind of
 294 * frame allocation tracking...meaning, for example,
 295 * that if multiple drivers request interrupts every 10 USB frames,
 296 * they don't all have to be allocated at
 297 * frame numbers N, N+10, N+20, etc.  Some of them could be at
 298 * N+11, N+21, N+31, etc., and others at
 299 * N+12, N+22, N+32, etc.
 300 * However, this first cut at USB bandwidth allocation does not
 301 * contain any frame allocation tracking.
 302 */
 303int usb_check_bandwidth (struct usb_device *dev, struct urb *urb)
 304{
 305        int             new_alloc;
 306        int             old_alloc = dev->bus->bandwidth_allocated;
 307        unsigned int    pipe = urb->pipe;
 308        long            bustime;
 309
 310        bustime = usb_calc_bus_time (dev->speed, usb_pipein(pipe),
 311                        usb_pipeisoc(pipe), usb_maxpacket(dev, pipe, usb_pipeout(pipe)));
 312        if (usb_pipeisoc(pipe))
 313                bustime = NS_TO_US(bustime) / urb->number_of_packets;
 314        else
 315                bustime = NS_TO_US(bustime);
 316
 317        new_alloc = old_alloc + (int)bustime;
 318                /* what new total allocated bus time would be */
 319
 320        if (new_alloc > FRAME_TIME_MAX_USECS_ALLOC)
 321                dbg("usb-check-bandwidth %sFAILED: was %u, would be %u, bustime = %ld us",
 322                        usb_bandwidth_option ? "" : "would have ",
 323                        old_alloc, new_alloc, bustime);
 324
 325        if (!usb_bandwidth_option)      /* don't enforce it */
 326                return (bustime);
 327        return (new_alloc <= FRAME_TIME_MAX_USECS_ALLOC) ? bustime : USB_ST_BANDWIDTH_ERROR;
 328}
 329
 330void usb_claim_bandwidth (struct usb_device *dev, struct urb *urb, int bustime, int isoc)
 331{
 332        dev->bus->bandwidth_allocated += bustime;
 333        if (isoc)
 334                dev->bus->bandwidth_isoc_reqs++;
 335        else
 336                dev->bus->bandwidth_int_reqs++;
 337        urb->bandwidth = bustime;
 338
 339#ifdef USB_BANDWIDTH_MESSAGES
 340        dbg("bandwidth alloc increased by %d to %d for %d requesters",
 341                bustime,
 342                dev->bus->bandwidth_allocated,
 343                dev->bus->bandwidth_int_reqs + dev->bus->bandwidth_isoc_reqs);
 344#endif
 345}
 346
 347/*
 348 * usb_release_bandwidth():
 349 *
 350 * called to release a pipe's bandwidth (in microseconds)
 351 */
 352void usb_release_bandwidth(struct usb_device *dev, struct urb *urb, int isoc)
 353{
 354        dev->bus->bandwidth_allocated -= urb->bandwidth;
 355        if (isoc)
 356                dev->bus->bandwidth_isoc_reqs--;
 357        else
 358                dev->bus->bandwidth_int_reqs--;
 359
 360#ifdef USB_BANDWIDTH_MESSAGES
 361        dbg("bandwidth alloc reduced by %d to %d for %d requesters",
 362                urb->bandwidth,
 363                dev->bus->bandwidth_allocated,
 364                dev->bus->bandwidth_int_reqs + dev->bus->bandwidth_isoc_reqs);
 365#endif
 366        urb->bandwidth = 0;
 367}
 368
 369static void usb_bus_get(struct usb_bus *bus)
 370{
 371        atomic_inc(&bus->refcnt);
 372}
 373
 374static void usb_bus_put(struct usb_bus *bus)
 375{
 376        if (atomic_dec_and_test(&bus->refcnt))
 377                kfree(bus);
 378}
 379
 380/**
 381 *      usb_alloc_bus - creates a new USB host controller structure
 382 *      @op: pointer to a struct usb_operations that this bus structure should use
 383 *
 384 *      Creates a USB host controller bus structure with the specified 
 385 *      usb_operations and initializes all the necessary internal objects.
 386 *      (For use only by USB Host Controller Drivers.)
 387 *
 388 *      If no memory is available, NULL is returned.
 389 *
 390 *      The caller should call usb_free_bus() when it is finished with the structure.
 391 */
 392struct usb_bus *usb_alloc_bus(struct usb_operations *op)
 393{
 394        struct usb_bus *bus;
 395
 396        bus = kmalloc(sizeof(*bus), GFP_KERNEL);
 397        if (!bus)
 398                return NULL;
 399
 400        memset(&bus->devmap, 0, sizeof(struct usb_devmap));
 401
 402#ifdef DEVNUM_ROUND_ROBIN
 403        bus->devnum_next = 1;
 404#endif /* DEVNUM_ROUND_ROBIN */
 405
 406        bus->op = op;
 407        bus->root_hub = NULL;
 408        bus->hcpriv = NULL;
 409        bus->busnum = -1;
 410        bus->bandwidth_allocated = 0;
 411        bus->bandwidth_int_reqs  = 0;
 412        bus->bandwidth_isoc_reqs = 0;
 413
 414        INIT_LIST_HEAD(&bus->bus_list);
 415        INIT_LIST_HEAD(&bus->inodes);
 416
 417        atomic_set(&bus->refcnt, 1);
 418
 419        return bus;
 420}
 421
 422/**
 423 *      usb_free_bus - frees the memory used by a bus structure
 424 *      @bus: pointer to the bus to free
 425 *
 426 *      (For use only by USB Host Controller Drivers.)
 427 */
 428void usb_free_bus(struct usb_bus *bus)
 429{
 430        if (!bus)
 431                return;
 432
 433        usb_bus_put(bus);
 434}
 435
 436/**
 437 *      usb_register_bus - registers the USB host controller with the usb core
 438 *      @bus: pointer to the bus to register
 439 *
 440 *      (For use only by USB Host Controller Drivers.)
 441 */
 442void usb_register_bus(struct usb_bus *bus)
 443{
 444        int busnum;
 445
 446        down (&usb_bus_list_lock);
 447        busnum = find_next_zero_bit(busmap.busmap, USB_MAXBUS, 1);
 448        if (busnum < USB_MAXBUS) {
 449                set_bit(busnum, busmap.busmap);
 450                bus->busnum = busnum;
 451        } else
 452                warn("too many buses");
 453
 454        usb_bus_get(bus);
 455
 456        /* Add it to the list of buses */
 457        list_add(&bus->bus_list, &usb_bus_list);
 458        up (&usb_bus_list_lock);
 459
 460        usbdevfs_add_bus(bus);
 461
 462        info("new USB bus registered, assigned bus number %d", bus->busnum);
 463}
 464
 465/**
 466 *      usb_deregister_bus - deregisters the USB host controller
 467 *      @bus: pointer to the bus to deregister
 468 *
 469 *      (For use only by USB Host Controller Drivers.)
 470 */
 471void usb_deregister_bus(struct usb_bus *bus)
 472{
 473        info("USB bus %d deregistered", bus->busnum);
 474
 475        /*
 476         * NOTE: make sure that all the devices are removed by the
 477         * controller code, as well as having it call this when cleaning
 478         * itself up
 479         */
 480        down (&usb_bus_list_lock);
 481        list_del(&bus->bus_list);
 482        clear_bit(bus->busnum, busmap.busmap);
 483        up (&usb_bus_list_lock);
 484
 485        usbdevfs_remove_bus(bus);
 486
 487        usb_bus_put(bus);
 488}
 489
 490/*
 491 * This function is for doing a depth-first search for devices which
 492 * have support, for dynamic loading of driver modules.
 493 */
 494static void usb_check_support(struct usb_device *dev)
 495{
 496        int i;
 497
 498        if (!dev) {
 499                err("null device being checked!!!");
 500                return;
 501        }
 502
 503        for (i=0; i<USB_MAXCHILDREN; i++)
 504                if (dev->children[i])
 505                        usb_check_support(dev->children[i]);
 506
 507        if (!dev->actconfig)
 508                return;
 509
 510        /* now we check this device */
 511        if (dev->devnum > 0)
 512                for (i = 0; i < dev->actconfig->bNumInterfaces; i++)
 513                        usb_find_interface_driver(dev, i);
 514}
 515
 516
 517/*
 518 * This is intended to be used by usb device drivers that need to
 519 * claim more than one interface on a device at once when probing
 520 * (audio and acm are good examples).  No device driver should have
 521 * to mess with the internal usb_interface or usb_device structure
 522 * members.
 523 */
 524void usb_driver_claim_interface(struct usb_driver *driver, struct usb_interface *iface, void* priv)
 525{
 526        if (!iface || !driver)
 527                return;
 528
 529        dbg("%s driver claimed interface %p", driver->name, iface);
 530
 531        iface->driver = driver;
 532        iface->private_data = priv;
 533} /* usb_driver_claim_interface() */
 534
 535/*
 536 * This should be used by drivers to check other interfaces to see if
 537 * they are available or not.
 538 */
 539int usb_interface_claimed(struct usb_interface *iface)
 540{
 541        if (!iface)
 542                return 0;
 543
 544        return (iface->driver != NULL);
 545} /* usb_interface_claimed() */
 546
 547/*
 548 * This should be used by drivers to release their claimed interfaces
 549 */
 550void usb_driver_release_interface(struct usb_driver *driver, struct usb_interface *iface)
 551{
 552        /* this should never happen, don't release something that's not ours */
 553        if (!iface || iface->driver != driver)
 554                return;
 555
 556        iface->driver = NULL;
 557        iface->private_data = NULL;
 558}
 559
 560
 561/**
 562 * usb_match_id - find first usb_device_id matching device or interface
 563 * @dev: the device whose descriptors are considered when matching
 564 * @interface: the interface of interest
 565 * @id: array of usb_device_id structures, terminated by zero entry
 566 *
 567 * usb_match_id searches an array of usb_device_id's and returns
 568 * the first one matching the device or interface, or null.
 569 * This is used when binding (or rebinding) a driver to an interface.
 570 * Most USB device drivers will use this indirectly, through the usb core,
 571 * but some layered driver frameworks use it directly.
 572 * These device tables are exported with MODULE_DEVICE_TABLE, through
 573 * modutils and "modules.usbmap", to support the driver loading
 574 * functionality of USB hotplugging.
 575 *
 576 * What Matches:
 577 *
 578 * The "match_flags" element in a usb_device_id controls which
 579 * members are used.  If the corresponding bit is set, the
 580 * value in the device_id must match its corresponding member
 581 * in the device or interface descriptor, or else the device_id
 582 * does not match.
 583 *
 584 * "driver_info" is normally used only by device drivers,
 585 * but you can create a wildcard "matches anything" usb_device_id
 586 * as a driver's "modules.usbmap" entry if you provide an id with
 587 * only a nonzero "driver_info" field.  If you do this, the USB device
 588 * driver's probe() routine should use additional intelligence to
 589 * decide whether to bind to the specified interface.
 590 * 
 591 * What Makes Good usb_device_id Tables:
 592 *
 593 * The match algorithm is very simple, so that intelligence in
 594 * driver selection must come from smart driver id records.
 595 * Unless you have good reasons to use another selection policy,
 596 * provide match elements only in related groups, and order match
 597 * specifiers from specific to general.  Use the macros provided
 598 * for that purpose if you can.
 599 *
 600 * The most specific match specifiers use device descriptor
 601 * data.  These are commonly used with product-specific matches;
 602 * the USB_DEVICE macro lets you provide vendor and product IDs,
 603 * and you can also match against ranges of product revisions.
 604 * These are widely used for devices with application or vendor
 605 * specific bDeviceClass values.
 606 *
 607 * Matches based on device class/subclass/protocol specifications
 608 * are slightly more general; use the USB_DEVICE_INFO macro, or
 609 * its siblings.  These are used with single-function devices
 610 * where bDeviceClass doesn't specify that each interface has
 611 * its own class. 
 612 *
 613 * Matches based on interface class/subclass/protocol are the
 614 * most general; they let drivers bind to any interface on a
 615 * multiple-function device.  Use the USB_INTERFACE_INFO
 616 * macro, or its siblings, to match class-per-interface style 
 617 * devices (as recorded in bDeviceClass).
 618 *  
 619 * Within those groups, remember that not all combinations are
 620 * meaningful.  For example, don't give a product version range
 621 * without vendor and product IDs; or specify a protocol without
 622 * its associated class and subclass.
 623 */   
 624const struct usb_device_id *
 625usb_match_id(struct usb_device *dev, struct usb_interface *interface,
 626             const struct usb_device_id *id)
 627{
 628        struct usb_interface_descriptor *intf = 0;
 629
 630        /* proc_connectinfo in devio.c may call us with id == NULL. */
 631        if (id == NULL)
 632                return NULL;
 633
 634        /* It is important to check that id->driver_info is nonzero,
 635           since an entry that is all zeroes except for a nonzero
 636           id->driver_info is the way to create an entry that
 637           indicates that the driver want to examine every
 638           device and interface. */
 639        for (; id->idVendor || id->bDeviceClass || id->bInterfaceClass ||
 640               id->driver_info; id++) {
 641
 642                if ((id->match_flags & USB_DEVICE_ID_MATCH_VENDOR) &&
 643                    id->idVendor != dev->descriptor.idVendor)
 644                        continue;
 645
 646                if ((id->match_flags & USB_DEVICE_ID_MATCH_PRODUCT) &&
 647                    id->idProduct != dev->descriptor.idProduct)
 648                        continue;
 649
 650                /* No need to test id->bcdDevice_lo != 0, since 0 is never
 651                   greater than any unsigned number. */
 652                if ((id->match_flags & USB_DEVICE_ID_MATCH_DEV_LO) &&
 653                    (id->bcdDevice_lo > dev->descriptor.bcdDevice))
 654                        continue;
 655
 656                if ((id->match_flags & USB_DEVICE_ID_MATCH_DEV_HI) &&
 657                    (id->bcdDevice_hi < dev->descriptor.bcdDevice))
 658                        continue;
 659
 660                if ((id->match_flags & USB_DEVICE_ID_MATCH_DEV_CLASS) &&
 661                    (id->bDeviceClass != dev->descriptor.bDeviceClass))
 662                        continue;
 663
 664                if ((id->match_flags & USB_DEVICE_ID_MATCH_DEV_SUBCLASS) &&
 665                    (id->bDeviceSubClass!= dev->descriptor.bDeviceSubClass))
 666                        continue;
 667
 668                if ((id->match_flags & USB_DEVICE_ID_MATCH_DEV_PROTOCOL) &&
 669                    (id->bDeviceProtocol != dev->descriptor.bDeviceProtocol))
 670                        continue;
 671
 672                intf = &interface->altsetting [interface->act_altsetting];
 673
 674                if ((id->match_flags & USB_DEVICE_ID_MATCH_INT_CLASS) &&
 675                    (id->bInterfaceClass != intf->bInterfaceClass))
 676                        continue;
 677
 678                if ((id->match_flags & USB_DEVICE_ID_MATCH_INT_SUBCLASS) &&
 679                    (id->bInterfaceSubClass != intf->bInterfaceSubClass))
 680                    continue;
 681
 682                if ((id->match_flags & USB_DEVICE_ID_MATCH_INT_PROTOCOL) &&
 683                    (id->bInterfaceProtocol != intf->bInterfaceProtocol))
 684                    continue;
 685
 686                return id;
 687        }
 688
 689        return NULL;
 690}
 691
 692/*
 693 * This entrypoint gets called for each new device.
 694 *
 695 * We now walk the list of registered USB drivers,
 696 * looking for one that will accept this interface.
 697 *
 698 * "New Style" drivers use a table describing the devices and interfaces
 699 * they handle.  Those tables are available to user mode tools deciding
 700 * whether to load driver modules for a new device.
 701 *
 702 * The probe return value is changed to be a private pointer.  This way
 703 * the drivers don't have to dig around in our structures to set the
 704 * private pointer if they only need one interface. 
 705 *
 706 * Returns: 0 if a driver accepted the interface, -1 otherwise
 707 */
 708static int usb_find_interface_driver(struct usb_device *dev, unsigned ifnum)
 709{
 710        struct list_head *tmp;
 711        struct usb_interface *interface;
 712        void *private;
 713        const struct usb_device_id *id;
 714        struct usb_driver *driver;
 715        int i;
 716        
 717        if ((!dev) || (ifnum >= dev->actconfig->bNumInterfaces)) {
 718                err("bad find_interface_driver params");
 719                return -1;
 720        }
 721
 722        down(&dev->serialize);
 723
 724        interface = dev->actconfig->interface + ifnum;
 725
 726        if (usb_interface_claimed(interface))
 727                goto out_err;
 728
 729        private = NULL;
 730        for (tmp = usb_driver_list.next; tmp != &usb_driver_list;) {
 731                driver = list_entry(tmp, struct usb_driver, driver_list);
 732                tmp = tmp->next;
 733
 734                id = driver->id_table;
 735                /* new style driver? */
 736                if (id) {
 737                        for (i = 0; i < interface->num_altsetting; i++) {
 738                                interface->act_altsetting = i;
 739                                id = usb_match_id(dev, interface, id);
 740                                if (id) {
 741                                        down(&driver->serialize);
 742                                        private = driver->probe(dev,ifnum,id);
 743                                        up(&driver->serialize);
 744                                        if (private != NULL)
 745                                                break;
 746                                }
 747                        }
 748
 749                        /* if driver not bound, leave defaults unchanged */
 750                        if (private == NULL)
 751                                interface->act_altsetting = 0;
 752                } else { /* "old style" driver */
 753                        down(&driver->serialize);
 754                        private = driver->probe(dev, ifnum, NULL);
 755                        up(&driver->serialize);
 756                }
 757
 758                /* probe() may have changed the config on us */
 759                interface = dev->actconfig->interface + ifnum;
 760
 761                if (private) {
 762                        usb_driver_claim_interface(driver, interface, private);
 763                        up(&dev->serialize);
 764                        return 0;
 765                }
 766        }
 767
 768out_err:
 769        up(&dev->serialize);
 770        return -1;
 771}
 772
 773/*
 774 * This simply converts the interface _number_ (as in interface.bInterfaceNumber) and
 775 * converts it to the interface _position_ (as in dev->actconfig->interface + position)
 776 * and calls usb_find_interface_driver().
 777 *
 778 * Note that the number is the same as the position for all interfaces _except_
 779 * devices with interfaces not sequentially numbered (e.g., 0, 2, 3, etc).
 780 */
 781int usb_find_interface_driver_for_ifnum(struct usb_device *dev, unsigned ifnum)
 782{
 783        int ifpos = usb_ifnum_to_ifpos(dev, ifnum);
 784
 785        if (0 > ifpos)
 786                return -EINVAL;
 787
 788        return usb_find_interface_driver(dev, ifpos);
 789}
 790
 791#ifdef  CONFIG_HOTPLUG
 792
 793/*
 794 * USB hotplugging invokes what /proc/sys/kernel/hotplug says
 795 * (normally /sbin/hotplug) when USB devices get added or removed.
 796 *
 797 * This invokes a user mode policy agent, typically helping to load driver
 798 * or other modules, configure the device, and more.  Drivers can provide
 799 * a MODULE_DEVICE_TABLE to help with module loading subtasks.
 800 *
 801 * Some synchronization is important: removes can't start processing
 802 * before the add-device processing completes, and vice versa.  That keeps
 803 * a stack of USB-related identifiers stable while they're in use.  If we
 804 * know that agents won't complete after they return (such as by forking
 805 * a process that completes later), it's enough to just waitpid() for the
 806 * agent -- as is currently done.
 807 *
 808 * The reason: we know we're called either from khubd (the typical case)
 809 * or from root hub initialization (init, kapmd, modprobe, etc).  In both
 810 * cases, we know no other thread can recycle our address, since we must
 811 * already have been serialized enough to prevent that.
 812 */
 813static void call_policy_interface (char *verb, struct usb_device *dev, int interface)
 814{
 815        char *argv [3], **envp, *buf, *scratch;
 816        int i = 0, value;
 817
 818        if (!hotplug_path [0])
 819                return;
 820        if (in_interrupt ()) {
 821                dbg ("In_interrupt");
 822                return;
 823        }
 824        if (!current->fs->root) {
 825                /* statically linked USB is initted rather early */
 826                dbg ("call_policy %s, num %d -- no FS yet", verb, dev->devnum);
 827                return;
 828        }
 829        if (dev->devnum < 0) {
 830                dbg ("device already deleted ??");
 831                return;
 832        }
 833        if (!(envp = (char **) kmalloc (20 * sizeof (char *), GFP_KERNEL))) {
 834                dbg ("enomem");
 835                return;
 836        }
 837        if (!(buf = kmalloc (256, GFP_KERNEL))) {
 838                kfree (envp);
 839                dbg ("enomem2");
 840                return;
 841        }
 842
 843        /* only one standardized param to hotplug command: type */
 844        argv [0] = hotplug_path;
 845        argv [1] = "usb";
 846        argv [2] = 0;
 847
 848        /* minimal command environment */
 849        envp [i++] = "HOME=/";
 850        envp [i++] = "PATH=/sbin:/bin:/usr/sbin:/usr/bin";
 851
 852#ifdef  DEBUG
 853        /* hint that policy agent should enter no-stdout debug mode */
 854        envp [i++] = "DEBUG=kernel";
 855#endif
 856        /* extensible set of named bus-specific parameters,
 857         * supporting multiple driver selection algorithms.
 858         */
 859        scratch = buf;
 860
 861        /* action:  add, remove */
 862        envp [i++] = scratch;
 863        scratch += sprintf (scratch, "ACTION=%s", verb) + 1;
 864
 865#ifdef  CONFIG_USB_DEVICEFS
 866        /* If this is available, userspace programs can directly read
 867         * all the device descriptors we don't tell them about.  Or
 868         * even act as usermode drivers.
 869         *
 870         * FIXME reduce hardwired intelligence here
 871         */
 872        envp [i++] = "DEVFS=/proc/bus/usb";
 873        envp [i++] = scratch;
 874        scratch += sprintf (scratch, "DEVICE=/proc/bus/usb/%03d/%03d",
 875                dev->bus->busnum, dev->devnum) + 1;
 876#endif
 877
 878        /* per-device configuration hacks are common */
 879        envp [i++] = scratch;
 880        scratch += sprintf (scratch, "PRODUCT=%x/%x/%x",
 881                dev->descriptor.idVendor,
 882                dev->descriptor.idProduct,
 883                dev->descriptor.bcdDevice) + 1;
 884
 885        /* class-based driver binding models */
 886        envp [i++] = scratch;
 887        scratch += sprintf (scratch, "TYPE=%d/%d/%d",
 888                            dev->descriptor.bDeviceClass,
 889                            dev->descriptor.bDeviceSubClass,
 890                            dev->descriptor.bDeviceProtocol) + 1;
 891        if (dev->descriptor.bDeviceClass == 0) {
 892                int alt = dev->actconfig->interface [interface].act_altsetting;
 893
 894                envp [i++] = scratch;
 895                scratch += sprintf (scratch, "INTERFACE=%d/%d/%d",
 896                        dev->actconfig->interface [interface].altsetting [alt].bInterfaceClass,
 897                        dev->actconfig->interface [interface].altsetting [alt].bInterfaceSubClass,
 898                        dev->actconfig->interface [interface].altsetting [alt].bInterfaceProtocol)
 899                        + 1;
 900        }
 901        envp [i++] = 0;
 902        /* assert: (scratch - buf) < sizeof buf */
 903
 904        /* NOTE: user mode daemons can call the agents too */
 905
 906        dbg ("kusbd: %s %s %d", argv [0], verb, dev->devnum);
 907        value = call_usermodehelper (argv [0], argv, envp);
 908        kfree (buf);
 909        kfree (envp);
 910        if (value != 0)
 911                dbg ("kusbd policy returned 0x%x", value);
 912}
 913
 914static void call_policy (char *verb, struct usb_device *dev)
 915{
 916        int i;
 917        for (i = 0; i < dev->actconfig->bNumInterfaces; i++) {
 918                call_policy_interface (verb, dev, i);
 919        }
 920}
 921
 922#else
 923
 924static inline void
 925call_policy (char *verb, struct usb_device *dev)
 926{ } 
 927
 928#endif  /* CONFIG_HOTPLUG */
 929
 930
 931/*
 932 * This entrypoint gets called for each new device.
 933 *
 934 * All interfaces are scanned for matching drivers.
 935 */
 936static void usb_find_drivers(struct usb_device *dev)
 937{
 938        unsigned ifnum;
 939        unsigned rejected = 0;
 940        unsigned claimed = 0;
 941
 942        for (ifnum = 0; ifnum < dev->actconfig->bNumInterfaces; ifnum++) {
 943                /* if this interface hasn't already been claimed */
 944                if (!usb_interface_claimed(dev->actconfig->interface + ifnum)) {
 945                        if (usb_find_interface_driver(dev, ifnum))
 946                                rejected++;
 947                        else
 948                                claimed++;
 949                }
 950        }
 951 
 952        if (rejected)
 953                dbg("unhandled interfaces on device");
 954
 955        if (!claimed) {
 956                warn("USB device %d (vend/prod 0x%x/0x%x) is not claimed by any active driver.",
 957                        dev->devnum,
 958                        dev->descriptor.idVendor,
 959                        dev->descriptor.idProduct);
 960#ifdef DEBUG
 961                usb_show_device(dev);
 962#endif
 963        }
 964}
 965
 966/*
 967 * Only HC's should call usb_alloc_dev and usb_free_dev directly
 968 * Anybody may use usb_inc_dev_use or usb_dec_dev_use
 969 */
 970struct usb_device *usb_alloc_dev(struct usb_device *parent, struct usb_bus *bus)
 971{
 972        struct usb_device *dev;
 973
 974        dev = kmalloc(sizeof(*dev), GFP_KERNEL);
 975        if (!dev)
 976                return NULL;
 977
 978        memset(dev, 0, sizeof(*dev));
 979
 980        usb_bus_get(bus);
 981
 982        if (!parent)
 983                dev->devpath [0] = '0';
 984
 985        dev->bus = bus;
 986        dev->parent = parent;
 987        atomic_set(&dev->refcnt, 1);
 988        INIT_LIST_HEAD(&dev->inodes);
 989        INIT_LIST_HEAD(&dev->filelist);
 990
 991        init_MUTEX(&dev->serialize);
 992        init_MUTEX(&dev->exclusive_access);
 993
 994        dev->bus->op->allocate(dev);
 995
 996        return dev;
 997}
 998
 999void usb_free_dev(struct usb_device *dev)
1000{
1001        if (atomic_dec_and_test(&dev->refcnt)) {
1002                dev->bus->op->deallocate(dev);
1003                usb_destroy_configuration(dev);
1004
1005                usb_bus_put(dev->bus);
1006
1007                kfree(dev);
1008        }
1009}
1010
1011void usb_inc_dev_use(struct usb_device *dev)
1012{
1013        atomic_inc(&dev->refcnt);
1014}
1015
1016/* ------------------------------------------------------------------------------------- 
1017 * New USB Core Functions
1018 * -------------------------------------------------------------------------------------*/
1019
1020/**
1021 *      usb_alloc_urb - creates a new urb for a USB driver to use
1022 *      @iso_packets: number of iso packets for this urb
1023 *
1024 *      Creates an urb for the USB driver to use and returns a pointer to it.
1025 *      If no memory is available, NULL is returned.
1026 *
1027 *      If the driver want to use this urb for interrupt, control, or bulk
1028 *      endpoints, pass '0' as the number of iso packets.
1029 *
1030 *      The driver should call usb_free_urb() when it is finished with the urb.
1031 */
1032struct urb *usb_alloc_urb(int iso_packets)
1033{
1034        struct urb *urb;
1035
1036        urb = (struct urb *)kmalloc(sizeof(struct urb) + iso_packets * sizeof(struct iso_packet_descriptor),
1037                        /* pessimize to prevent deadlocks */ GFP_ATOMIC);
1038        if (!urb) {
1039                err("alloc_urb: kmalloc failed");
1040                return NULL;
1041        }
1042
1043        memset(urb, 0, sizeof(*urb));
1044
1045        spin_lock_init(&urb->lock);
1046
1047        return urb;
1048}
1049
1050/**
1051 *      usb_free_urb - frees the memory used by a urb
1052 *      @urb: pointer to the urb to free
1053 *
1054 *      If an urb is created with a call to usb_create_urb() it should be
1055 *      cleaned up with a call to usb_free_urb() when the driver is finished
1056 *      with it.
1057 */
1058void usb_free_urb(struct urb* urb)
1059{
1060        if (urb)
1061                kfree(urb);
1062}
1063/*-------------------------------------------------------------------*/
1064int usb_submit_urb(struct urb *urb)
1065{
1066        if (urb && urb->dev && urb->dev->bus && urb->dev->bus->op)
1067                return urb->dev->bus->op->submit_urb(urb);
1068        else
1069                return -ENODEV;
1070}
1071
1072/*-------------------------------------------------------------------*/
1073int usb_unlink_urb(struct urb *urb)
1074{
1075        if (urb && urb->dev && urb->dev->bus && urb->dev->bus->op)
1076                return urb->dev->bus->op->unlink_urb(urb);
1077        else
1078                return -ENODEV;
1079}
1080/*-------------------------------------------------------------------*
1081 *                     COMPLETION HANDLERS                           *
1082 *-------------------------------------------------------------------*/
1083
1084/*-------------------------------------------------------------------*
1085 * completion handler for compatibility wrappers (sync control/bulk) *
1086 *-------------------------------------------------------------------*/
1087static void usb_api_blocking_completion(struct urb *urb)
1088{
1089        struct usb_api_data *awd = (struct usb_api_data *)urb->context;
1090
1091        awd->done = 1;
1092        wmb();
1093        wake_up(&awd->wqh);
1094}
1095
1096/*-------------------------------------------------------------------*
1097 *                         COMPATIBILITY STUFF                       *
1098 *-------------------------------------------------------------------*/
1099
1100// Starts urb and waits for completion or timeout
1101static int usb_start_wait_urb(struct urb *urb, int timeout, int* actual_length)
1102{ 
1103        DECLARE_WAITQUEUE(wait, current);
1104        struct usb_api_data awd;
1105        int status;
1106
1107        init_waitqueue_head(&awd.wqh);  
1108        awd.done = 0;
1109
1110        set_current_state(TASK_UNINTERRUPTIBLE);
1111        add_wait_queue(&awd.wqh, &wait);
1112
1113        urb->context = &awd;
1114        status = usb_submit_urb(urb);
1115        if (status) {
1116                // something went wrong
1117                usb_free_urb(urb);
1118                set_current_state(TASK_RUNNING);
1119                remove_wait_queue(&awd.wqh, &wait);
1120                return status;
1121        }
1122
1123        while (timeout && !awd.done)
1124        {
1125                timeout = schedule_timeout(timeout);
1126                set_current_state(TASK_UNINTERRUPTIBLE);
1127                rmb();
1128        }
1129
1130        set_current_state(TASK_RUNNING);
1131        remove_wait_queue(&awd.wqh, &wait);
1132
1133        if (!timeout && !awd.done) {
1134                if (urb->status != -EINPROGRESS) {      /* No callback?!! */
1135                        printk(KERN_ERR "usb: raced timeout, "
1136                            "pipe 0x%x status %d time left %d\n",
1137                            urb->pipe, urb->status, timeout);
1138                        status = urb->status;
1139                } else {
1140                        printk("usb_control/bulk_msg: timeout\n");
1141                        usb_unlink_urb(urb);  // remove urb safely
1142                        status = -ETIMEDOUT;
1143                }
1144        } else
1145                status = urb->status;
1146
1147        if (actual_length)
1148                *actual_length = urb->actual_length;
1149
1150        usb_free_urb(urb);
1151        return status;
1152}
1153
1154/*-------------------------------------------------------------------*/
1155// returns status (negative) or length (positive)
1156int usb_internal_control_msg(struct usb_device *usb_dev, unsigned int pipe, 
1157                            struct usb_ctrlrequest *cmd,  void *data, int len, int timeout)
1158{
1159        struct urb *urb;
1160        int retv;
1161        int length;
1162
1163        urb = usb_alloc_urb(0);
1164        if (!urb)
1165                return -ENOMEM;
1166  
1167        FILL_CONTROL_URB(urb, usb_dev, pipe, (unsigned char*)cmd, data, len,
1168                   usb_api_blocking_completion, 0);
1169
1170        retv = usb_start_wait_urb(urb, timeout, &length);
1171        if (retv < 0)
1172                return retv;
1173        else
1174                return length;
1175}
1176
1177/**
1178 *      usb_control_msg - Builds a control urb, sends it off and waits for completion
1179 *      @dev: pointer to the usb device to send the message to
1180 *      @pipe: endpoint "pipe" to send the message to
1181 *      @request: USB message request value
1182 *      @requesttype: USB message request type value
1183 *      @value: USB message value
1184 *      @index: USB message index value
1185 *      @data: pointer to the data to send
1186 *      @size: length in bytes of the data to send
1187 *      @timeout: time to wait for the message to complete before timing out (if 0 the wait is forever)
1188 *
1189 *      This function sends a simple control message to a specified endpoint
1190 *      and waits for the message to complete, or timeout.
1191 *      
1192 *      If successful, it returns the number of bytes transferred; 
1193 *      otherwise, it returns a negative error number.
1194 *
1195 *      Don't use this function from within an interrupt context, like a
1196 *      bottom half handler.  If you need a asyncronous message, or need to send
1197 *      a message from within interrupt context, use usb_submit_urb()
1198 */
1199int usb_control_msg(struct usb_device *dev, unsigned int pipe, __u8 request, __u8 requesttype,
1200                         __u16 value, __u16 index, void *data, __u16 size, int timeout)
1201{
1202        struct usb_ctrlrequest *dr = kmalloc(sizeof(struct usb_ctrlrequest), GFP_NOIO);
1203        int ret;
1204        
1205        if (!dr)
1206                return -ENOMEM;
1207
1208        dr->bRequestType = requesttype;
1209        dr->bRequest = request;
1210        dr->wValue = cpu_to_le16p(&value);
1211        dr->wIndex = cpu_to_le16p(&index);
1212        dr->wLength = cpu_to_le16p(&size);
1213
1214        //dbg("usb_control_msg");       
1215
1216        ret = usb_internal_control_msg(dev, pipe, dr, data, size, timeout);
1217
1218        kfree(dr);
1219
1220        return ret;
1221}
1222
1223
1224/**
1225 *      usb_bulk_msg - Builds a bulk urb, sends it off and waits for completion
1226 *      @usb_dev: pointer to the usb device to send the message to
1227 *      @pipe: endpoint "pipe" to send the message to
1228 *      @data: pointer to the data to send
1229 *      @len: length in bytes of the data to send
1230 *      @actual_length: pointer to a location to put the actual length transferred in bytes
1231 *      @timeout: time to wait for the message to complete before timing out (if 0 the wait is forever)
1232 *
1233 *      This function sends a simple bulk message to a specified endpoint
1234 *      and waits for the message to complete, or timeout.
1235 *      
1236 *      If successful, it returns 0, otherwise a negative error number.
1237 *      The number of actual bytes transferred will be stored in the 
1238 *      actual_length paramater.
1239 *
1240 *      Don't use this function from within an interrupt context, like a
1241 *      bottom half handler.  If you need a asyncronous message, or need to
1242 *      send a message from within interrupt context, use usb_submit_urb()
1243 */
1244int usb_bulk_msg(struct usb_device *usb_dev, unsigned int pipe, 
1245                        void *data, int len, int *actual_length, int timeout)
1246{
1247        struct urb *urb;
1248
1249        if (len < 0)
1250                return -EINVAL;
1251
1252        urb=usb_alloc_urb(0);
1253        if (!urb)
1254                return -ENOMEM;
1255
1256        FILL_BULK_URB(urb, usb_dev, pipe, data, len,
1257                    usb_api_blocking_completion, 0);
1258
1259        return usb_start_wait_urb(urb,timeout,actual_length);
1260}
1261
1262/*
1263 * usb_get_current_frame_number()
1264 *
1265 * returns the current frame number for the parent USB bus/controller
1266 * of the given USB device.
1267 */
1268int usb_get_current_frame_number(struct usb_device *usb_dev)
1269{
1270        return usb_dev->bus->op->get_frame_number (usb_dev);
1271}
1272/*-------------------------------------------------------------------*/
1273
1274static int usb_parse_endpoint(struct usb_endpoint_descriptor *endpoint, unsigned char *buffer, int size)
1275{
1276        struct usb_descriptor_header *header;
1277        unsigned char *begin;
1278        int parsed = 0, len, numskipped;
1279
1280        header = (struct usb_descriptor_header *)buffer;
1281
1282        /* Everything should be fine being passed into here, but we sanity */
1283        /*  check JIC */
1284        if (header->bLength > size) {
1285                err("ran out of descriptors parsing");
1286                return -1;
1287        }
1288                
1289        if (header->bDescriptorType != USB_DT_ENDPOINT) {
1290                warn("unexpected descriptor 0x%X, expecting endpoint descriptor, type 0x%X",
1291                        endpoint->bDescriptorType, USB_DT_ENDPOINT);
1292                return parsed;
1293        }
1294
1295        if (header->bLength == USB_DT_ENDPOINT_AUDIO_SIZE)
1296                memcpy(endpoint, buffer, USB_DT_ENDPOINT_AUDIO_SIZE);
1297        else
1298                memcpy(endpoint, buffer, USB_DT_ENDPOINT_SIZE);
1299        
1300        le16_to_cpus(&endpoint->wMaxPacketSize);
1301
1302        buffer += header->bLength;
1303        size -= header->bLength;
1304        parsed += header->bLength;
1305
1306        /* Skip over the rest of the Class Specific or Vendor Specific */
1307        /*  descriptors */
1308        begin = buffer;
1309        numskipped = 0;
1310        while (size >= sizeof(struct usb_descriptor_header)) {
1311                header = (struct usb_descriptor_header *)buffer;
1312
1313                if (header->bLength < 2) {
1314                        err("invalid descriptor length of %d", header->bLength);
1315                        return -1;
1316                }
1317
1318                /* If we find another "proper" descriptor then we're done  */
1319                if ((header->bDescriptorType == USB_DT_ENDPOINT) ||
1320                    (header->bDescriptorType == USB_DT_INTERFACE) ||
1321                    (header->bDescriptorType == USB_DT_CONFIG) ||
1322                    (header->bDescriptorType == USB_DT_DEVICE))
1323                        break;
1324
1325                dbg("skipping descriptor 0x%X",
1326                        header->bDescriptorType);
1327                numskipped++;
1328
1329                buffer += header->bLength;
1330                size -= header->bLength;
1331                parsed += header->bLength;
1332        }
1333        if (numskipped)
1334                dbg("skipped %d class/vendor specific endpoint descriptors", numskipped);
1335
1336        /* Copy any unknown descriptors into a storage area for drivers */
1337        /*  to later parse */
1338        len = (int)(buffer - begin);
1339        if (!len) {
1340                endpoint->extra = NULL;
1341                endpoint->extralen = 0;
1342                return parsed;
1343        }
1344
1345        endpoint->extra = kmalloc(len, GFP_KERNEL);
1346
1347        if (!endpoint->extra) {
1348                err("couldn't allocate memory for endpoint extra descriptors");
1349                endpoint->extralen = 0;
1350                return parsed;
1351        }
1352
1353        memcpy(endpoint->extra, begin, len);
1354        endpoint->extralen = len;
1355
1356        return parsed;
1357}
1358
1359static int usb_parse_interface(struct usb_interface *interface, unsigned char *buffer, int size)
1360{
1361        int i, len, numskipped, retval, parsed = 0;
1362        struct usb_descriptor_header *header;
1363        struct usb_interface_descriptor *ifp;
1364        unsigned char *begin;
1365
1366        interface->act_altsetting = 0;
1367        interface->num_altsetting = 0;
1368        interface->max_altsetting = USB_ALTSETTINGALLOC;
1369
1370        interface->altsetting = kmalloc(sizeof(struct usb_interface_descriptor) * interface->max_altsetting, GFP_KERNEL);
1371        
1372        if (!interface->altsetting) {
1373                err("couldn't kmalloc interface->altsetting");
1374                return -1;
1375        }
1376
1377        while (size > 0) {
1378                if (interface->num_altsetting >= interface->max_altsetting) {
1379                        void *ptr;
1380                        int oldmas;
1381
1382                        oldmas = interface->max_altsetting;
1383                        interface->max_altsetting += USB_ALTSETTINGALLOC;
1384                        if (interface->max_altsetting > USB_MAXALTSETTING) {
1385                                warn("too many alternate settings (max %d)",
1386                                        USB_MAXALTSETTING);
1387                                return -1;
1388                        }
1389
1390                        ptr = interface->altsetting;
1391                        interface->altsetting = kmalloc(sizeof(struct usb_interface_descriptor) * interface->max_altsetting, GFP_KERNEL);
1392                        if (!interface->altsetting) {
1393                                err("couldn't kmalloc interface->altsetting");
1394                                interface->altsetting = ptr;
1395                                return -1;
1396                        }
1397                        memcpy(interface->altsetting, ptr, sizeof(struct usb_interface_descriptor) * oldmas);
1398
1399                        kfree(ptr);
1400                }
1401
1402                ifp = interface->altsetting + interface->num_altsetting;
1403                interface->num_altsetting++;
1404
1405                memcpy(ifp, buffer, USB_DT_INTERFACE_SIZE);
1406
1407                /* Skip over the interface */
1408                buffer += ifp->bLength;
1409                parsed += ifp->bLength;
1410                size -= ifp->bLength;
1411
1412                begin = buffer;
1413                numskipped = 0;
1414
1415                /* Skip over any interface, class or vendor descriptors */
1416                while (size >= sizeof(struct usb_descriptor_header)) {
1417                        header = (struct usb_descriptor_header *)buffer;
1418
1419                        if (header->bLength < 2) {
1420                                err("invalid descriptor length of %d", header->bLength);
1421                                return -1;
1422                        }
1423
1424                        /* If we find another "proper" descriptor then we're done  */
1425                        if ((header->bDescriptorType == USB_DT_INTERFACE) ||
1426                            (header->bDescriptorType == USB_DT_ENDPOINT) ||
1427                            (header->bDescriptorType == USB_DT_CONFIG) ||
1428                            (header->bDescriptorType == USB_DT_DEVICE))
1429                                break;
1430
1431                        numskipped++;
1432
1433                        buffer += header->bLength;
1434                        parsed += header->bLength;
1435                        size -= header->bLength;
1436                }
1437
1438                if (numskipped)
1439                        dbg("skipped %d class/vendor specific interface descriptors", numskipped);
1440
1441                /* Copy any unknown descriptors into a storage area for */
1442                /*  drivers to later parse */
1443                len = (int)(buffer - begin);
1444                if (!len) {
1445                        ifp->extra = NULL;
1446                        ifp->extralen = 0;
1447                } else {
1448                        ifp->extra = kmalloc(len, GFP_KERNEL);
1449
1450                        if (!ifp->extra) {
1451                                err("couldn't allocate memory for interface extra descriptors");
1452                                ifp->extralen = 0;
1453                                return -1;
1454                        }
1455                        memcpy(ifp->extra, begin, len);
1456                        ifp->extralen = len;
1457                }
1458
1459                /* Did we hit an unexpected descriptor? */
1460                header = (struct usb_descriptor_header *)buffer;
1461                if ((size >= sizeof(struct usb_descriptor_header)) &&
1462                    ((header->bDescriptorType == USB_DT_CONFIG) ||
1463                     (header->bDescriptorType == USB_DT_DEVICE)))
1464                        return parsed;
1465
1466                if (ifp->bNumEndpoints > USB_MAXENDPOINTS) {
1467                        warn("too many endpoints");
1468                        return -1;
1469                }
1470
1471                ifp->endpoint = (struct usb_endpoint_descriptor *)
1472                        kmalloc(ifp->bNumEndpoints *
1473                        sizeof(struct usb_endpoint_descriptor), GFP_KERNEL);
1474                if (!ifp->endpoint) {
1475                        err("out of memory");
1476                        return -1;      
1477                }
1478
1479                memset(ifp->endpoint, 0, ifp->bNumEndpoints *
1480                        sizeof(struct usb_endpoint_descriptor));
1481        
1482                for (i = 0; i < ifp->bNumEndpoints; i++) {
1483                        header = (struct usb_descriptor_header *)buffer;
1484
1485                        if (header->bLength > size) {
1486                                err("ran out of descriptors parsing");
1487                                return -1;
1488                        }
1489                
1490                        retval = usb_parse_endpoint(ifp->endpoint + i, buffer, size);
1491                        if (retval < 0)
1492                                return retval;
1493
1494                        buffer += retval;
1495                        parsed += retval;
1496                        size -= retval;
1497                }
1498
1499                /* We check to see if it's an alternate to this one */
1500                ifp = (struct usb_interface_descriptor *)buffer;
1501                if (size < USB_DT_INTERFACE_SIZE ||
1502                    ifp->bDescriptorType != USB_DT_INTERFACE ||
1503                    !ifp->bAlternateSetting)
1504                        return parsed;
1505        }
1506
1507        return parsed;
1508}
1509
1510int usb_parse_configuration(struct usb_config_descriptor *config, char *buffer)
1511{
1512        int i, retval, size;
1513        struct usb_descriptor_header *header;
1514
1515        memcpy(config, buffer, USB_DT_CONFIG_SIZE);
1516        le16_to_cpus(&config->wTotalLength);
1517        size = config->wTotalLength;
1518
1519        if (config->bNumInterfaces > USB_MAXINTERFACES) {
1520                warn("too many interfaces");
1521                return -1;
1522        }
1523
1524        config->interface = (struct usb_interface *)
1525                kmalloc(config->bNumInterfaces *
1526                sizeof(struct usb_interface), GFP_KERNEL);
1527        dbg("kmalloc IF %p, numif %i", config->interface, config->bNumInterfaces);
1528        if (!config->interface) {
1529                err("out of memory");
1530                return -1;      
1531        }
1532
1533        memset(config->interface, 0,
1534               config->bNumInterfaces * sizeof(struct usb_interface));
1535
1536        buffer += config->bLength;
1537        size -= config->bLength;
1538        
1539        config->extra = NULL;
1540        config->extralen = 0;
1541
1542        for (i = 0; i < config->bNumInterfaces; i++) {
1543                int numskipped, len;
1544                char *begin;
1545
1546                /* Skip over the rest of the Class Specific or Vendor */
1547                /*  Specific descriptors */
1548                begin = buffer;
1549                numskipped = 0;
1550                while (size >= sizeof(struct usb_descriptor_header)) {
1551                        header = (struct usb_descriptor_header *)buffer;
1552
1553                        if ((header->bLength > size) || (header->bLength < 2)) {
1554                                err("invalid descriptor length of %d", header->bLength);
1555                                return -1;
1556                        }
1557
1558                        /* If we find another "proper" descriptor then we're done  */
1559                        if ((header->bDescriptorType == USB_DT_ENDPOINT) ||
1560                            (header->bDescriptorType == USB_DT_INTERFACE) ||
1561                            (header->bDescriptorType == USB_DT_CONFIG) ||
1562                            (header->bDescriptorType == USB_DT_DEVICE))
1563                                break;
1564
1565                        dbg("skipping descriptor 0x%X", header->bDescriptorType);
1566                        numskipped++;
1567
1568                        buffer += header->bLength;
1569                        size -= header->bLength;
1570                }
1571                if (numskipped)
1572                        dbg("skipped %d class/vendor specific endpoint descriptors", numskipped);
1573
1574                /* Copy any unknown descriptors into a storage area for */
1575                /*  drivers to later parse */
1576                len = (int)(buffer - begin);
1577                if (len) {
1578                        if (config->extralen) {
1579                                warn("extra config descriptor");
1580                        } else {
1581                                config->extra = kmalloc(len, GFP_KERNEL);
1582                                if (!config->extra) {
1583                                        err("couldn't allocate memory for config extra descriptors");
1584                                        config->extralen = 0;
1585                                        return -1;
1586                                }
1587
1588                                memcpy(config->extra, begin, len);
1589                                config->extralen = len;
1590                        }
1591                }
1592
1593                retval = usb_parse_interface(config->interface + i, buffer, size);
1594                if (retval < 0)
1595                        return retval;
1596
1597                buffer += retval;
1598                size -= retval;
1599        }
1600
1601        return size;
1602}
1603
1604void usb_destroy_configuration(struct usb_device *dev)
1605{
1606        int c, i, j, k;
1607        
1608        if (!dev->config)
1609                return;
1610
1611        if (dev->rawdescriptors) {
1612                for (i = 0; i < dev->descriptor.bNumConfigurations; i++)
1613                        kfree(dev->rawdescriptors[i]);
1614
1615                kfree(dev->rawdescriptors);
1616        }
1617
1618        for (c = 0; c < dev->descriptor.bNumConfigurations; c++) {
1619                struct usb_config_descriptor *cf = &dev->config[c];
1620
1621                if (!cf->interface)
1622                        break;
1623
1624                for (i = 0; i < cf->bNumInterfaces; i++) {
1625                        struct usb_interface *ifp =
1626                                &cf->interface[i];
1627                                
1628                        if (!ifp->altsetting)
1629                                break;
1630
1631                        for (j = 0; j < ifp->num_altsetting; j++) {
1632                                struct usb_interface_descriptor *as =
1633                                        &ifp->altsetting[j];
1634                                        
1635                                if(as->extra) {
1636                                        kfree(as->extra);
1637                                }
1638
1639                                if (!as->endpoint)
1640                                        break;
1641                                        
1642                                for(k = 0; k < as->bNumEndpoints; k++) {
1643                                        if(as->endpoint[k].extra) {
1644                                                kfree(as->endpoint[k].extra);
1645                                        }
1646                                }       
1647                                kfree(as->endpoint);
1648                        }
1649
1650                        kfree(ifp->altsetting);
1651                }
1652                kfree(cf->interface);
1653        }
1654        kfree(dev->config);
1655}
1656
1657/* for returning string descriptors in UTF-16LE */
1658static int ascii2utf (char *ascii, __u8 *utf, int utfmax)
1659{
1660        int retval;
1661
1662        for (retval = 0; *ascii && utfmax > 1; utfmax -= 2, retval += 2) {
1663                *utf++ = *ascii++ & 0x7f;
1664                *utf++ = 0;
1665        }
1666        return retval;
1667}
1668
1669/*
1670 * root_hub_string is used by each host controller's root hub code,
1671 * so that they're identified consistently throughout the system.
1672 */
1673int usb_root_hub_string (int id, int serial, char *type, __u8 *data, int len)
1674{
1675        char buf [30];
1676
1677        // assert (len > (2 * (sizeof (buf) + 1)));
1678        // assert (strlen (type) <= 8);
1679
1680        // language ids
1681        if (id == 0) {
1682                *data++ = 4; *data++ = 3;       /* 4 bytes data */
1683                *data++ = 0; *data++ = 0;       /* some language id */
1684                return 4;
1685
1686        // serial number
1687        } else if (id == 1) {
1688                sprintf (buf, "%x", serial);
1689
1690        // product description
1691        } else if (id == 2) {
1692                sprintf (buf, "USB %s Root Hub", type);
1693
1694        // id 3 == vendor description
1695
1696        // unsupported IDs --> "stall"
1697        } else
1698            return 0;
1699
1700        data [0] = 2 + ascii2utf (buf, data + 2, len - 2);
1701        data [1] = 3;
1702        return data [0];
1703}
1704
1705/*
1706 * __usb_get_extra_descriptor() finds a descriptor of specific type in the
1707 * extra field of the interface and endpoint descriptor structs.
1708 */
1709
1710int __usb_get_extra_descriptor(char *buffer, unsigned size, unsigned char type, void **ptr)
1711{
1712        struct usb_descriptor_header *header;
1713
1714        while (size >= sizeof(struct usb_descriptor_header)) {
1715                header = (struct usb_descriptor_header *)buffer;
1716
1717                if (header->bLength < 2) {
1718                        err("invalid descriptor length of %d", header->bLength);
1719                        return -1;
1720                }
1721
1722                if (header->bDescriptorType == type) {
1723                        *ptr = header;
1724                        return 0;
1725                }
1726
1727                buffer += header->bLength;
1728                size -= header->bLength;
1729        }
1730        return -1;
1731}
1732
1733/*
1734 * Something got disconnected. Get rid of it, and all of its children.
1735 */
1736void usb_disconnect(struct usb_device **pdev)
1737{
1738        struct usb_device * dev = *pdev;
1739        int i;
1740
1741        if (!dev)
1742                return;
1743
1744        *pdev = NULL;
1745
1746        info("USB disconnect on device %s-%s address %d",
1747                        dev->bus->bus_name, dev->devpath, dev->devnum);
1748
1749        if (dev->actconfig) {
1750                for (i = 0; i < dev->actconfig->bNumInterfaces; i++) {
1751                        struct usb_interface *interface = &dev->actconfig->interface[i];
1752                        struct usb_driver *driver = interface->driver;
1753                        if (driver) {
1754                                down(&driver->serialize);
1755                                driver->disconnect(dev, interface->private_data);
1756                                up(&driver->serialize);
1757                                /* if driver->disconnect didn't release the interface */
1758                                if (interface->driver)
1759                                        usb_driver_release_interface(driver, interface);
1760                        }
1761                }
1762        }
1763
1764        /* Free up all the children.. */
1765        for (i = 0; i < USB_MAXCHILDREN; i++) {
1766                struct usb_device **child = dev->children + i;
1767                if (*child)
1768                        usb_disconnect(child);
1769        }
1770
1771        /* Let policy agent unload modules etc */
1772        call_policy ("remove", dev);
1773
1774        /* Free the device number and remove the /proc/bus/usb entry */
1775        if (dev->devnum > 0) {
1776                clear_bit(dev->devnum, &dev->bus->devmap.devicemap);
1777                usbdevfs_remove_device(dev);
1778        }
1779
1780        /* Free up the device itself */
1781        usb_free_dev(dev);
1782}
1783
1784/*
1785 * Connect a new USB device. This basically just initializes
1786 * the USB device information and sets up the topology - it's
1787 * up to the low-level driver to reset the port and actually
1788 * do the setup (the upper levels don't know how to do that).
1789 */
1790void usb_connect(struct usb_device *dev)
1791{
1792        int devnum;
1793        // FIXME needs locking for SMP!!
1794        /* why? this is called only from the hub thread, 
1795         * which hopefully doesn't run on multiple CPU's simultaneously 8-)
1796         */
1797        dev->descriptor.bMaxPacketSize0 = 8;  /* Start off at 8 bytes  */
1798#ifndef DEVNUM_ROUND_ROBIN
1799        devnum = find_next_zero_bit(dev->bus->devmap.devicemap, 128, 1);
1800#else   /* round_robin alloc of devnums */
1801        /* Try to allocate the next devnum beginning at bus->devnum_next. */
1802        devnum = find_next_zero_bit(dev->bus->devmap.devicemap, 128, dev->bus->devnum_next);
1803        if (devnum >= 128)
1804                devnum = find_next_zero_bit(dev->bus->devmap.devicemap, 128, 1);
1805
1806        dev->bus->devnum_next = ( devnum >= 127 ? 1 : devnum + 1);
1807#endif  /* round_robin alloc of devnums */
1808
1809        if (devnum < 128) {
1810                set_bit(devnum, dev->bus->devmap.devicemap);
1811                dev->devnum = devnum;
1812        }
1813}
1814
1815/*
1816 * These are the actual routines to send
1817 * and receive control messages.
1818 */
1819
1820/* USB spec identifies 5 second timeouts.
1821 * Some devices (MGE Ellipse UPSes, etc) need it, too.
1822 */
1823#define GET_TIMEOUT 5
1824#define SET_TIMEOUT 5
1825
1826int usb_set_address(struct usb_device *dev)
1827{
1828        return usb_control_msg(dev, usb_snddefctrl(dev), USB_REQ_SET_ADDRESS,
1829                0, dev->devnum, 0, NULL, 0, HZ * SET_TIMEOUT);
1830}
1831
1832int usb_get_descriptor(struct usb_device *dev, unsigned char type, unsigned char index, void *buf, int size)
1833{
1834        int i = 5;
1835        int result;
1836        
1837        memset(buf,0,size);     // Make sure we parse really received data
1838
1839        while (i--) {
1840                if ((result = usb_control_msg(dev, usb_rcvctrlpipe(dev, 0),
1841                        USB_REQ_GET_DESCRIPTOR, USB_DIR_IN,
1842                        (type << 8) + index, 0, buf, size, HZ * GET_TIMEOUT)) > 0 ||
1843                     result == -EPIPE)
1844                        break;  /* retry if the returned length was 0; flaky device */
1845        }
1846        return result;
1847}
1848
1849int usb_get_class_descriptor(struct usb_device *dev, int ifnum,
1850                unsigned char type, unsigned char id, void *buf, int size)
1851{
1852        return usb_control_msg(dev, usb_rcvctrlpipe(dev, 0),
1853                USB_REQ_GET_DESCRIPTOR, USB_RECIP_INTERFACE | USB_DIR_IN,
1854                (type << 8) + id, ifnum, buf, size, HZ * GET_TIMEOUT);
1855}
1856
1857int usb_get_string(struct usb_device *dev, unsigned short langid, unsigned char index, void *buf, int size)
1858{
1859        return usb_control_msg(dev, usb_rcvctrlpipe(dev, 0),
1860                USB_REQ_GET_DESCRIPTOR, USB_DIR_IN,
1861                (USB_DT_STRING << 8) + index, langid, buf, size, HZ * GET_TIMEOUT);
1862}
1863
1864int usb_get_device_descriptor(struct usb_device *dev)
1865{
1866        int ret = usb_get_descriptor(dev, USB_DT_DEVICE, 0, &dev->descriptor,
1867                                     sizeof(dev->descriptor));
1868        if (ret >= 0) {
1869                le16_to_cpus(&dev->descriptor.bcdUSB);
1870                le16_to_cpus(&dev->descriptor.idVendor);
1871                le16_to_cpus(&dev->descriptor.idProduct);
1872                le16_to_cpus(&dev->descriptor.bcdDevice);
1873        }
1874        return ret;
1875}
1876
1877int usb_get_status(struct usb_device *dev, int type, int target, void *data)
1878{
1879        return usb_control_msg(dev, usb_rcvctrlpipe(dev, 0),
1880                USB_REQ_GET_STATUS, USB_DIR_IN | type, 0, target, data, 2, HZ * GET_TIMEOUT);
1881}
1882
1883int usb_get_protocol(struct usb_device *dev, int ifnum)
1884{
1885        unsigned char type;
1886        int ret;
1887
1888        if ((ret = usb_control_msg(dev, usb_rcvctrlpipe(dev, 0),
1889            USB_REQ_GET_PROTOCOL, USB_DIR_IN | USB_TYPE_CLASS | USB_RECIP_INTERFACE,
1890            0, ifnum, &type, 1, HZ * GET_TIMEOUT)) < 0)
1891                return ret;
1892
1893        return type;
1894}
1895
1896int usb_set_protocol(struct usb_device *dev, int ifnum, int protocol)
1897{
1898        return usb_control_msg(dev, usb_sndctrlpipe(dev, 0),
1899                USB_REQ_SET_PROTOCOL, USB_TYPE_CLASS | USB_RECIP_INTERFACE,
1900                protocol, ifnum, NULL, 0, HZ * SET_TIMEOUT);
1901}
1902
1903int usb_set_idle(struct usb_device *dev, int ifnum, int duration, int report_id)
1904{
1905        return usb_control_msg(dev, usb_sndctrlpipe(dev, 0),
1906                USB_REQ_SET_IDLE, USB_TYPE_CLASS | USB_RECIP_INTERFACE,
1907                (duration << 8) | report_id, ifnum, NULL, 0, HZ * SET_TIMEOUT);
1908}
1909
1910void usb_set_maxpacket(struct usb_device *dev)
1911{
1912        int i, b;
1913
1914        for (i=0; i<dev->actconfig->bNumInterfaces; i++) {
1915                struct usb_interface *ifp = dev->actconfig->interface + i;
1916                struct usb_interface_descriptor *as = ifp->altsetting + ifp->act_altsetting;
1917                struct usb_endpoint_descriptor *ep = as->endpoint;
1918                int e;
1919
1920                for (e=0; e<as->bNumEndpoints; e++) {
1921                        b = ep[e].bEndpointAddress & USB_ENDPOINT_NUMBER_MASK;
1922                        if ((ep[e].bmAttributes & USB_ENDPOINT_XFERTYPE_MASK) ==
1923                                USB_ENDPOINT_XFER_CONTROL) {    /* Control => bidirectional */
1924                                dev->epmaxpacketout[b] = ep[e].wMaxPacketSize;
1925                                dev->epmaxpacketin [b] = ep[e].wMaxPacketSize;
1926                                }
1927                        else if (usb_endpoint_out(ep[e].bEndpointAddress)) {
1928                                if (ep[e].wMaxPacketSize > dev->epmaxpacketout[b])
1929                                        dev->epmaxpacketout[b] = ep[e].wMaxPacketSize;
1930                        }
1931                        else {
1932                                if (ep[e].wMaxPacketSize > dev->epmaxpacketin [b])
1933                                        dev->epmaxpacketin [b] = ep[e].wMaxPacketSize;
1934                        }
1935                }
1936        }
1937}
1938
1939/*
1940 * endp: endpoint number in bits 0-3;
1941 *      direction flag in bit 7 (1 = IN, 0 = OUT)
1942 */
1943int usb_clear_halt(struct usb_device *dev, int pipe)
1944{
1945        int result;
1946        __u16 status;
1947        unsigned char *buffer;
1948        int endp=usb_pipeendpoint(pipe)|(usb_pipein(pipe)<<7);
1949
1950/*
1951        if (!usb_endpoint_halted(dev, endp & 0x0f, usb_endpoint_out(endp)))
1952                return 0;
1953*/
1954
1955        result = usb_control_msg(dev, usb_sndctrlpipe(dev, 0),
1956                USB_REQ_CLEAR_FEATURE, USB_RECIP_ENDPOINT, 0, endp, NULL, 0, HZ * SET_TIMEOUT);
1957
1958        /* don't clear if failed */
1959        if (result < 0)
1960                return result;
1961
1962        buffer = kmalloc(sizeof(status), GFP_KERNEL);
1963        if (!buffer) {
1964                err("unable to allocate memory for configuration descriptors");
1965                return -ENOMEM;
1966        }
1967
1968        result = usb_control_msg(dev, usb_rcvctrlpipe(dev, 0),
1969                USB_REQ_GET_STATUS, USB_DIR_IN | USB_RECIP_ENDPOINT, 0, endp,
1970                buffer, sizeof(status), HZ * SET_TIMEOUT);
1971
1972        memcpy(&status, buffer, sizeof(status));
1973        kfree(buffer);
1974
1975        if (result < 0)
1976                return result;
1977
1978        if (le16_to_cpu(status) & 1)
1979                return -EPIPE;          /* still halted */
1980
1981        usb_endpoint_running(dev, usb_pipeendpoint(pipe), usb_pipeout(pipe));
1982
1983        /* toggle is reset on clear */
1984
1985        usb_settoggle(dev, usb_pipeendpoint(pipe), usb_pipeout(pipe), 0);
1986
1987        return 0;
1988}
1989
1990int usb_set_interface(struct usb_device *dev, int interface, int alternate)
1991{
1992        struct usb_interface *iface;
1993        int ret;
1994
1995        iface = usb_ifnum_to_if(dev, interface);
1996        if (!iface) {
1997                warn("selecting invalid interface %d", interface);
1998                return -EINVAL;
1999        }
2000
2001        /* 9.4.10 says devices don't need this, if the interface
2002           only has one alternate setting */
2003        if (iface->num_altsetting == 1) {
2004                dbg("ignoring set_interface for dev %d, iface %d, alt %d",
2005                        dev->devnum, interface, alternate);
2006                return 0;
2007        }
2008
2009        if ((ret = usb_control_msg(dev, usb_sndctrlpipe(dev, 0),
2010            USB_REQ_SET_INTERFACE, USB_RECIP_INTERFACE, alternate,
2011            interface, NULL, 0, HZ * 5)) < 0)
2012                return ret;
2013
2014        iface->act_altsetting = alternate;
2015        dev->toggle[0] = 0;     /* 9.1.1.5 says to do this */
2016        dev->toggle[1] = 0;
2017        usb_set_maxpacket(dev);
2018        return 0;
2019}
2020
2021int usb_set_configuration(struct usb_device *dev, int configuration)
2022{
2023        int i, ret;
2024        struct usb_config_descriptor *cp = NULL;
2025        
2026        for (i=0; i<dev->descriptor.bNumConfigurations; i++) {
2027                if (dev->config[i].bConfigurationValue == configuration) {
2028                        cp = &dev->config[i];
2029                        break;
2030                }
2031        }
2032        if (!cp) {
2033                warn("selecting invalid configuration %d", configuration);
2034                return -EINVAL;
2035        }
2036
2037        if ((ret = usb_control_msg(dev, usb_sndctrlpipe(dev, 0),
2038            USB_REQ_SET_CONFIGURATION, 0, configuration, 0, NULL, 0, HZ * SET_TIMEOUT)) < 0)
2039                return ret;
2040
2041        dev->actconfig = cp;
2042        dev->toggle[0] = 0;
2043        dev->toggle[1] = 0;
2044        usb_set_maxpacket(dev);
2045
2046        return 0;
2047}
2048
2049int usb_get_report(struct usb_device *dev, int ifnum, unsigned char type, unsigned char id, void *buf, int size)
2050{
2051        return usb_control_msg(dev, usb_rcvctrlpipe(dev, 0),
2052                USB_REQ_GET_REPORT, USB_DIR_IN | USB_TYPE_CLASS | USB_RECIP_INTERFACE,
2053                (type << 8) + id, ifnum, buf, size, HZ * GET_TIMEOUT);
2054}
2055
2056int usb_set_report(struct usb_device *dev, int ifnum, unsigned char type, unsigned char id, void *buf, int size)
2057{
2058        return usb_control_msg(dev, usb_sndctrlpipe(dev, 0),
2059                USB_REQ_SET_REPORT, USB_TYPE_CLASS | USB_RECIP_INTERFACE,
2060                (type << 8) + id, ifnum, buf, size, HZ);
2061}
2062
2063int usb_get_configuration(struct usb_device *dev)
2064{
2065        int result;
2066        unsigned int cfgno, length;
2067        unsigned char *buffer;
2068        unsigned char *bigbuffer;
2069        struct usb_config_descriptor *desc;
2070
2071        if (dev->descriptor.bNumConfigurations > USB_MAXCONFIG) {
2072                warn("too many configurations");
2073                return -EINVAL;
2074        }
2075
2076        if (dev->descriptor.bNumConfigurations < 1) {
2077                warn("not enough configurations");
2078                return -EINVAL;
2079        }
2080
2081        dev->config = (struct usb_config_descriptor *)
2082                kmalloc(dev->descriptor.bNumConfigurations *
2083                sizeof(struct usb_config_descriptor), GFP_KERNEL);
2084        if (!dev->config) {
2085                err("out of memory");
2086                return -ENOMEM; 
2087        }
2088        memset(dev->config, 0, dev->descriptor.bNumConfigurations *
2089                sizeof(struct usb_config_descriptor));
2090
2091        dev->rawdescriptors = (char **)kmalloc(sizeof(char *) *
2092                dev->descriptor.bNumConfigurations, GFP_KERNEL);
2093        if (!dev->rawdescriptors) {
2094                err("out of memory");
2095                return -ENOMEM;
2096        }
2097
2098        buffer = kmalloc(8, GFP_KERNEL);
2099        if (!buffer) {
2100                err("unable to allocate memory for configuration descriptors");
2101                return -ENOMEM;
2102        }
2103        desc = (struct usb_config_descriptor *)buffer;
2104
2105        for (cfgno = 0; cfgno < dev->descriptor.bNumConfigurations; cfgno++) {
2106                /* We grab the first 8 bytes so we know how long the whole */
2107                /*  configuration is */
2108                result = usb_get_descriptor(dev, USB_DT_CONFIG, cfgno, buffer, 8);
2109                if (result < 8) {
2110                        if (result < 0)
2111                                err("unable to get descriptor");
2112                        else {
2113                                err("config descriptor too short (expected %i, got %i)", 8, result);
2114                                result = -EINVAL;
2115                        }
2116                        goto err;
2117                }
2118
2119                /* Get the full buffer */
2120                length = le16_to_cpu(desc->wTotalLength);
2121
2122                bigbuffer = kmalloc(length, GFP_KERNEL);
2123                if (!bigbuffer) {
2124                        err("unable to allocate memory for configuration descriptors");
2125                        result = -ENOMEM;
2126                        goto err;
2127                }
2128
2129                /* Now that we know the length, get the whole thing */
2130                result = usb_get_descriptor(dev, USB_DT_CONFIG, cfgno, bigbuffer, length);
2131                if (result < 0) {
2132                        err("couldn't get all of config descriptors");
2133                        kfree(bigbuffer);
2134                        goto err;
2135                }       
2136        
2137                if (result < length) {
2138                        err("config descriptor too short (expected %i, got %i)", length, result);
2139                        result = -EINVAL;
2140                        kfree(bigbuffer);
2141                        goto err;
2142                }
2143
2144                dev->rawdescriptors[cfgno] = bigbuffer;
2145
2146                result = usb_parse_configuration(&dev->config[cfgno], bigbuffer);
2147                if (result > 0)
2148                        dbg("descriptor data left");
2149                else if (result < 0) {
2150                        result = -EINVAL;
2151                        goto err;
2152                }
2153        }
2154
2155        kfree(buffer);
2156        return 0;
2157err:
2158        kfree(buffer);
2159        dev->descriptor.bNumConfigurations = cfgno;
2160        return result;
2161}
2162
2163/*
2164 * usb_string:
2165 *      returns string length (> 0) or error (< 0)
2166 */
2167int usb_string(struct usb_device *dev, int index, char *buf, size_t size)
2168{
2169        unsigned char *tbuf;
2170        int err;
2171        unsigned int u, idx;
2172
2173        if (size <= 0 || !buf || !index)
2174                return -EINVAL;
2175        buf[0] = 0;
2176        tbuf = kmalloc(256, GFP_KERNEL);
2177        if (!tbuf)
2178                return -ENOMEM;
2179
2180        /* get langid for strings if it's not yet known */
2181        if (!dev->have_langid) {
2182                err = usb_get_string(dev, 0, 0, tbuf, 4);
2183                if (err < 0) {
2184                        err("error getting string descriptor 0 (error=%d)", err);
2185                        goto errout;
2186                } else if (err < 4 || tbuf[0] < 4) {
2187                        err("string descriptor 0 too short");
2188                        err = -EINVAL;
2189                        goto errout;
2190                } else {
2191                        dev->have_langid = -1;
2192                        dev->string_langid = tbuf[2] | (tbuf[3]<< 8);
2193                                /* always use the first langid listed */
2194                        dbg("USB device number %d default language ID 0x%x",
2195                                dev->devnum, dev->string_langid);
2196                }
2197        }
2198
2199        /*
2200         * Just ask for a maximum length string and then take the length
2201         * that was returned.
2202         */
2203        err = usb_get_string(dev, dev->string_langid, index, tbuf, 255);
2204        if (err < 0)
2205                goto errout;
2206
2207        size--;         /* leave room for trailing NULL char in output buffer */
2208        for (idx = 0, u = 2; u < err; u += 2) {
2209                if (idx >= size)
2210                        break;
2211                if (tbuf[u+1])                  /* high byte */
2212                        buf[idx++] = '?';  /* non-ASCII character */
2213                else
2214                        buf[idx++] = tbuf[u];
2215        }
2216        buf[idx] = 0;
2217        err = idx;
2218
2219 errout:
2220        kfree(tbuf);
2221        return err;
2222}
2223
2224/*
2225 * By the time we get here, the device has gotten a new device ID
2226 * and is in the default state. We need to identify the thing and
2227 * get the ball rolling..
2228 *
2229 * Returns 0 for success, != 0 for error.
2230 */
2231int usb_new_device(struct usb_device *dev)
2232{
2233        int err;
2234
2235        /* USB v1.1 5.5.3 */
2236        /* We read the first 8 bytes from the device descriptor to get to */
2237        /*  the bMaxPacketSize0 field. Then we set the maximum packet size */
2238        /*  for the control pipe, and retrieve the rest */
2239        dev->epmaxpacketin [0] = 8;
2240        dev->epmaxpacketout[0] = 8;
2241
2242        err = usb_set_address(dev);
2243        if (err < 0) {
2244                err("USB device not accepting new address=%d (error=%d)",
2245                        dev->devnum, err);
2246                clear_bit(dev->devnum, &dev->bus->devmap.devicemap);
2247                dev->devnum = -1;
2248                return 1;
2249        }
2250
2251        wait_ms(10);    /* Let the SET_ADDRESS settle */
2252
2253        err = usb_get_descriptor(dev, USB_DT_DEVICE, 0, &dev->descriptor, 8);
2254        if (err < 8) {
2255                if (err < 0)
2256                        err("USB device not responding, giving up (error=%d)", err);
2257                else
2258                        err("USB device descriptor short read (expected %i, got %i)", 8, err);
2259                clear_bit(dev->devnum, &dev->bus->devmap.devicemap);
2260                dev->devnum = -1;
2261                return 1;
2262        }
2263        dev->epmaxpacketin [0] = dev->descriptor.bMaxPacketSize0;
2264        dev->epmaxpacketout[0] = dev->descriptor.bMaxPacketSize0;
2265
2266        err = usb_get_device_descriptor(dev);
2267        if (err < (signed)sizeof(dev->descriptor)) {
2268                if (err < 0)
2269                        err("unable to get device descriptor (error=%d)", err);
2270                else
2271                        err("USB device descriptor short read (expected %Zi, got %i)",
2272                                sizeof(dev->descriptor), err);
2273        
2274                clear_bit(dev->devnum, &dev->bus->devmap.devicemap);
2275                dev->devnum = -1;
2276                return 1;
2277        }
2278
2279        err = usb_get_configuration(dev);
2280        if (err < 0) {
2281                err("unable to get device %d configuration (error=%d)",
2282                        dev->devnum, err);
2283                clear_bit(dev->devnum, &dev->bus->devmap.devicemap);
2284                dev->devnum = -1;
2285                return 1;
2286        }
2287
2288        /* we set the default configuration here */
2289        err = usb_set_configuration(dev, dev->config[0].bConfigurationValue);
2290        if (err) {
2291                err("failed to set device %d default configuration (error=%d)",
2292                        dev->devnum, err);
2293                clear_bit(dev->devnum, &dev->bus->devmap.devicemap);
2294                dev->devnum = -1;
2295                return 1;
2296        }
2297
2298        dbg("new device strings: Mfr=%d, Product=%d, SerialNumber=%d",
2299                dev->descriptor.iManufacturer, dev->descriptor.iProduct, dev->descriptor.iSerialNumber);
2300#ifdef DEBUG
2301        if (dev->descriptor.iManufacturer)
2302                usb_show_string(dev, "Manufacturer", dev->descriptor.iManufacturer);
2303        if (dev->descriptor.iProduct)
2304                usb_show_string(dev, "Product", dev->descriptor.iProduct);
2305        if (dev->descriptor.iSerialNumber)
2306                usb_show_string(dev, "SerialNumber", dev->descriptor.iSerialNumber);
2307#endif
2308
2309        /* now that the basic setup is over, add a /proc/bus/usb entry */
2310        usbdevfs_add_device(dev);
2311
2312        /* find drivers willing to handle this device */
2313        usb_find_drivers(dev);
2314
2315        /* userspace may load modules and/or configure further */
2316        call_policy ("add", dev);
2317
2318        return 0;
2319}
2320
2321static int usb_open(struct inode * inode, struct file * file)
2322{
2323        int minor = MINOR(inode->i_rdev);
2324        struct usb_driver *c = usb_minors[minor/16];
2325        int err = -ENODEV;
2326        struct file_operations *old_fops, *new_fops = NULL;
2327
2328        /*
2329         * No load-on-demand? Randy, could you ACK that it's really not
2330         * supposed to be done?                                 -- AV
2331         */
2332        if (!c || !(new_fops = fops_get(c->fops)))
2333                return err;
2334        old_fops = file->f_op;
2335        file->f_op = new_fops;
2336        /* Curiouser and curiouser... NULL ->open() as "no device" ? */
2337        if (file->f_op->open)
2338                err = file->f_op->open(inode,file);
2339        if (err) {
2340                fops_put(file->f_op);
2341                file->f_op = fops_get(old_fops);
2342        }
2343        fops_put(old_fops);
2344        return err;
2345}
2346
2347static struct file_operations usb_fops = {
2348        owner:          THIS_MODULE,
2349        open:           usb_open,
2350};
2351
2352int usb_major_init(void)
2353{
2354        if (devfs_register_chrdev(USB_MAJOR, "usb", &usb_fops)) {
2355                err("unable to get major %d for usb devices", USB_MAJOR);
2356                return -EBUSY;
2357        }
2358
2359        usb_devfs_handle = devfs_mk_dir(NULL, "usb", NULL);
2360
2361        return 0;
2362}
2363
2364void usb_major_cleanup(void)
2365{
2366        devfs_unregister(usb_devfs_handle);
2367        devfs_unregister_chrdev(USB_MAJOR, "usb");
2368}
2369
2370
2371#ifdef CONFIG_PROC_FS
2372struct list_head *usb_driver_get_list(void)
2373{
2374        return &usb_driver_list;
2375}
2376
2377struct list_head *usb_bus_get_list(void)
2378{
2379        return &usb_bus_list;
2380}
2381#endif
2382
2383
2384/*
2385 * Init
2386 */
2387static int __init usb_init(void)
2388{
2389        init_MUTEX(&usb_bus_list_lock);
2390        usb_major_init();
2391        usbdevfs_init();
2392        usb_hub_init();
2393
2394        return 0;
2395}
2396
2397/*
2398 * Cleanup
2399 */
2400static void __exit usb_exit(void)
2401{
2402        usb_major_cleanup();
2403        usbdevfs_cleanup();
2404        usb_hub_cleanup();
2405}
2406
2407module_init(usb_init);
2408module_exit(usb_exit);
2409
2410/*
2411 * USB may be built into the kernel or be built as modules.
2412 * If the USB core [and maybe a host controller driver] is built
2413 * into the kernel, and other device drivers are built as modules,
2414 * then these symbols need to be exported for the modules to use.
2415 */
2416EXPORT_SYMBOL(usb_ifnum_to_ifpos);
2417EXPORT_SYMBOL(usb_ifnum_to_if);
2418EXPORT_SYMBOL(usb_epnum_to_ep_desc);
2419
2420EXPORT_SYMBOL(usb_register);
2421EXPORT_SYMBOL(usb_deregister);
2422EXPORT_SYMBOL(usb_scan_devices);
2423EXPORT_SYMBOL(usb_alloc_bus);
2424EXPORT_SYMBOL(usb_free_bus);
2425EXPORT_SYMBOL(usb_register_bus);
2426EXPORT_SYMBOL(usb_deregister_bus);
2427EXPORT_SYMBOL(usb_alloc_dev);
2428EXPORT_SYMBOL(usb_free_dev);
2429EXPORT_SYMBOL(usb_inc_dev_use);
2430
2431EXPORT_SYMBOL(usb_find_interface_driver_for_ifnum);
2432EXPORT_SYMBOL(usb_driver_claim_interface);
2433EXPORT_SYMBOL(usb_interface_claimed);
2434EXPORT_SYMBOL(usb_driver_release_interface);
2435EXPORT_SYMBOL(usb_match_id);
2436
2437EXPORT_SYMBOL(usb_root_hub_string);
2438EXPORT_SYMBOL(usb_new_device);
2439EXPORT_SYMBOL(usb_reset_device);
2440EXPORT_SYMBOL(usb_connect);
2441EXPORT_SYMBOL(usb_disconnect);
2442
2443EXPORT_SYMBOL(usb_calc_bus_time);
2444EXPORT_SYMBOL(usb_check_bandwidth);
2445EXPORT_SYMBOL(usb_claim_bandwidth);
2446EXPORT_SYMBOL(usb_release_bandwidth);
2447
2448EXPORT_SYMBOL(usb_set_address);
2449EXPORT_SYMBOL(usb_get_descriptor);
2450EXPORT_SYMBOL(usb_get_class_descriptor);
2451EXPORT_SYMBOL(__usb_get_extra_descriptor);
2452EXPORT_SYMBOL(usb_get_device_descriptor);
2453EXPORT_SYMBOL(usb_get_string);
2454EXPORT_SYMBOL(usb_string);
2455EXPORT_SYMBOL(usb_get_protocol);
2456EXPORT_SYMBOL(usb_set_protocol);
2457EXPORT_SYMBOL(usb_get_report);
2458EXPORT_SYMBOL(usb_set_report);
2459EXPORT_SYMBOL(usb_set_idle);
2460EXPORT_SYMBOL(usb_clear_halt);
2461EXPORT_SYMBOL(usb_set_interface);
2462EXPORT_SYMBOL(usb_get_configuration);
2463EXPORT_SYMBOL(usb_set_configuration);
2464EXPORT_SYMBOL(usb_get_status);
2465
2466EXPORT_SYMBOL(usb_get_current_frame_number);
2467
2468EXPORT_SYMBOL(usb_alloc_urb);
2469EXPORT_SYMBOL(usb_free_urb);
2470EXPORT_SYMBOL(usb_submit_urb);
2471EXPORT_SYMBOL(usb_unlink_urb);
2472
2473EXPORT_SYMBOL(usb_control_msg);
2474EXPORT_SYMBOL(usb_bulk_msg);
2475
2476EXPORT_SYMBOL(usb_devfs_handle);
2477MODULE_LICENSE("GPL");
2478
lxr.linux.no kindly hosted by Redpill Linpro AS, provider of Linux consulting and operations services since 1995.