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