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