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