~ [ source navigation ] ~ [ diff markup ] ~ [ identifier search ] ~ [ freetext search ] ~ [ file search ] ~

Linux Cross Reference
Linux/drivers/usb/usb.c

Version: ~ [ 2.4.0 ] ~
Architecture: ~ [ i386 ] ~ [ alpha ] ~ [ m68k ] ~ [ mips ] ~ [ ppc ] ~ [ sparc ] ~ [ sparc64 ] ~

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

~ [ source navigation ] ~ [ diff markup ] ~ [ identifier search ] ~ [ freetext search ] ~ [ file search ] ~

This page was automatically generated by the LXR engine.
Visit the LXR main site for more information.