OpenCores
URL https://opencores.org/ocsvn/or1k/or1k/trunk

Subversion Repositories or1k

[/] [or1k/] [trunk/] [linux/] [linux-2.4/] [drivers/] [usb/] [usb.c] - Blame information for rev 1765

Details | Compare with Previous | View Log

Line No. Rev Author Line
1 1275 phoenix
/*
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
 */
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
 */
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
 */
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
 */
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
 
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
 
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
 
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
 */
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
 */
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
 
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
 */
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
 
369
static void usb_bus_get(struct usb_bus *bus)
370
{
371
        atomic_inc(&bus->refcnt);
372
}
373
 
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
 */
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
 */
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
 */
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
 */
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
 */
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
 */
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
 */
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
 */
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 *
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
 */
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
 */
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
 */
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
 
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
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
 */
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
 */
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
 
993
        dev->bus->op->allocate(dev);
994
 
995
        return dev;
996
}
997
 
998
void usb_free_dev(struct usb_device *dev)
999
{
1000
        if (atomic_dec_and_test(&dev->refcnt)) {
1001
                dev->bus->op->deallocate(dev);
1002
                usb_destroy_configuration(dev);
1003
 
1004
                usb_bus_put(dev->bus);
1005
 
1006
                kfree(dev);
1007
        }
1008
}
1009
 
1010
void usb_inc_dev_use(struct usb_device *dev)
1011
{
1012
        atomic_inc(&dev->refcnt);
1013
}
1014
 
1015
/* -------------------------------------------------------------------------------------
1016
 * New USB Core Functions
1017
 * -------------------------------------------------------------------------------------*/
1018
 
1019
/**
1020
 *      usb_alloc_urb - creates a new urb for a USB driver to use
1021
 *      @iso_packets: number of iso packets for this urb
1022
 *
1023
 *      Creates an urb for the USB driver to use and returns a pointer to it.
1024
 *      If no memory is available, NULL is returned.
1025
 *
1026
 *      If the driver want to use this urb for interrupt, control, or bulk
1027
 *      endpoints, pass '0' as the number of iso packets.
1028
 *
1029
 *      The driver should call usb_free_urb() when it is finished with the urb.
1030
 */
1031
struct urb *usb_alloc_urb(int iso_packets)
1032
{
1033
        struct urb *urb;
1034
 
1035
        urb = (struct urb *)kmalloc(sizeof(struct urb) + iso_packets * sizeof(struct iso_packet_descriptor),
1036
                        /* pessimize to prevent deadlocks */ GFP_ATOMIC);
1037
        if (!urb) {
1038
                err("alloc_urb: kmalloc failed");
1039
                return NULL;
1040
        }
1041
 
1042
        memset(urb, 0, sizeof(*urb));
1043
 
1044
        spin_lock_init(&urb->lock);
1045
 
1046
        return urb;
1047
}
1048
 
1049
/**
1050
 *      usb_free_urb - frees the memory used by a urb
1051
 *      @urb: pointer to the urb to free
1052
 *
1053
 *      If an urb is created with a call to usb_create_urb() it should be
1054
 *      cleaned up with a call to usb_free_urb() when the driver is finished
1055
 *      with it.
1056
 */
1057
void usb_free_urb(struct urb* urb)
1058
{
1059
        if (urb)
1060
                kfree(urb);
1061
}
1062
/*-------------------------------------------------------------------*/
1063
int usb_submit_urb(struct urb *urb)
1064
{
1065
        if (urb && urb->dev && urb->dev->bus && urb->dev->bus->op)
1066
                return urb->dev->bus->op->submit_urb(urb);
1067
        else
1068
                return -ENODEV;
1069
}
1070
 
1071
/*-------------------------------------------------------------------*/
1072
int usb_unlink_urb(struct urb *urb)
1073
{
1074
        if (urb && urb->dev && urb->dev->bus && urb->dev->bus->op)
1075
                return urb->dev->bus->op->unlink_urb(urb);
1076
        else
1077
                return -ENODEV;
1078
}
1079
/*-------------------------------------------------------------------*
1080
 *                     COMPLETION HANDLERS                           *
1081
 *-------------------------------------------------------------------*/
1082
 
1083
/*-------------------------------------------------------------------*
1084
 * completion handler for compatibility wrappers (sync control/bulk) *
1085
 *-------------------------------------------------------------------*/
1086
static void usb_api_blocking_completion(struct urb *urb)
1087
{
1088
        struct usb_api_data *awd = (struct usb_api_data *)urb->context;
1089
 
1090
        awd->done = 1;
1091
        wmb();
1092
        wake_up(&awd->wqh);
1093
}
1094
 
1095
/*-------------------------------------------------------------------*
1096
 *                         COMPATIBILITY STUFF                       *
1097
 *-------------------------------------------------------------------*/
1098
 
1099
// Starts urb and waits for completion or timeout
1100
static int usb_start_wait_urb(struct urb *urb, int timeout, int* actual_length)
1101
{
1102
        DECLARE_WAITQUEUE(wait, current);
1103
        struct usb_api_data awd;
1104
        int status;
1105
 
1106
        init_waitqueue_head(&awd.wqh);
1107
        awd.done = 0;
1108
 
1109
        set_current_state(TASK_UNINTERRUPTIBLE);
1110
        add_wait_queue(&awd.wqh, &wait);
1111
 
1112
        urb->context = &awd;
1113
        status = usb_submit_urb(urb);
1114
        if (status) {
1115
                // something went wrong
1116
                usb_free_urb(urb);
1117
                set_current_state(TASK_RUNNING);
1118
                remove_wait_queue(&awd.wqh, &wait);
1119
                return status;
1120
        }
1121
 
1122
        while (timeout && !awd.done)
1123
        {
1124
                timeout = schedule_timeout(timeout);
1125
                set_current_state(TASK_UNINTERRUPTIBLE);
1126
                rmb();
1127
        }
1128
 
1129
        set_current_state(TASK_RUNNING);
1130
        remove_wait_queue(&awd.wqh, &wait);
1131
 
1132
        if (!timeout && !awd.done) {
1133
                if (urb->status != -EINPROGRESS) {      /* No callback?!! */
1134
                        printk(KERN_ERR "usb: raced timeout, "
1135
                            "pipe 0x%x status %d time left %d\n",
1136
                            urb->pipe, urb->status, timeout);
1137
                        status = urb->status;
1138
                } else {
1139
                        printk("usb_control/bulk_msg: timeout\n");
1140
                        usb_unlink_urb(urb);  // remove urb safely
1141
                        status = -ETIMEDOUT;
1142
                }
1143
        } else
1144
                status = urb->status;
1145
 
1146
        if (actual_length)
1147
                *actual_length = urb->actual_length;
1148
 
1149
        usb_free_urb(urb);
1150
        return status;
1151
}
1152
 
1153
/*-------------------------------------------------------------------*/
1154
// returns status (negative) or length (positive)
1155
int usb_internal_control_msg(struct usb_device *usb_dev, unsigned int pipe,
1156
                            struct usb_ctrlrequest *cmd,  void *data, int len, int timeout)
1157
{
1158
        struct urb *urb;
1159
        int retv;
1160
        int length;
1161
 
1162
        urb = usb_alloc_urb(0);
1163
        if (!urb)
1164
                return -ENOMEM;
1165
 
1166
        FILL_CONTROL_URB(urb, usb_dev, pipe, (unsigned char*)cmd, data, len,
1167
                   usb_api_blocking_completion, 0);
1168
 
1169
        retv = usb_start_wait_urb(urb, timeout, &length);
1170
        if (retv < 0)
1171
                return retv;
1172
        else
1173
                return length;
1174
}
1175
 
1176
/**
1177
 *      usb_control_msg - Builds a control urb, sends it off and waits for completion
1178
 *      @dev: pointer to the usb device to send the message to
1179
 *      @pipe: endpoint "pipe" to send the message to
1180
 *      @request: USB message request value
1181
 *      @requesttype: USB message request type value
1182
 *      @value: USB message value
1183
 *      @index: USB message index value
1184
 *      @data: pointer to the data to send
1185
 *      @size: length in bytes of the data to send
1186
 *      @timeout: time to wait for the message to complete before timing out (if 0 the wait is forever)
1187
 *
1188
 *      This function sends a simple control message to a specified endpoint
1189
 *      and waits for the message to complete, or timeout.
1190
 *
1191
 *      If successful, it returns the number of bytes transferred;
1192
 *      otherwise, it returns a negative error number.
1193
 *
1194
 *      Don't use this function from within an interrupt context, like a
1195
 *      bottom half handler.  If you need a asyncronous message, or need to send
1196
 *      a message from within interrupt context, use usb_submit_urb()
1197
 */
1198
int usb_control_msg(struct usb_device *dev, unsigned int pipe, __u8 request, __u8 requesttype,
1199
                         __u16 value, __u16 index, void *data, __u16 size, int timeout)
1200
{
1201
        struct usb_ctrlrequest *dr = kmalloc(sizeof(struct usb_ctrlrequest), GFP_NOIO);
1202
        int ret;
1203
 
1204
        if (!dr)
1205
                return -ENOMEM;
1206
 
1207
        dr->bRequestType = requesttype;
1208
        dr->bRequest = request;
1209
        dr->wValue = cpu_to_le16p(&value);
1210
        dr->wIndex = cpu_to_le16p(&index);
1211
        dr->wLength = cpu_to_le16p(&size);
1212
 
1213
        //dbg("usb_control_msg");       
1214
 
1215
        ret = usb_internal_control_msg(dev, pipe, dr, data, size, timeout);
1216
 
1217
        kfree(dr);
1218
 
1219
        return ret;
1220
}
1221
 
1222
 
1223
/**
1224
 *      usb_bulk_msg - Builds a bulk urb, sends it off and waits for completion
1225
 *      @usb_dev: pointer to the usb device to send the message to
1226
 *      @pipe: endpoint "pipe" to send the message to
1227
 *      @data: pointer to the data to send
1228
 *      @len: length in bytes of the data to send
1229
 *      @actual_length: pointer to a location to put the actual length transferred in bytes
1230
 *      @timeout: time to wait for the message to complete before timing out (if 0 the wait is forever)
1231
 *
1232
 *      This function sends a simple bulk message to a specified endpoint
1233
 *      and waits for the message to complete, or timeout.
1234
 *
1235
 *      If successful, it returns 0, otherwise a negative error number.
1236
 *      The number of actual bytes transferred will be stored in the
1237
 *      actual_length paramater.
1238
 *
1239
 *      Don't use this function from within an interrupt context, like a
1240
 *      bottom half handler.  If you need a asyncronous message, or need to
1241
 *      send a message from within interrupt context, use usb_submit_urb()
1242
 */
1243
int usb_bulk_msg(struct usb_device *usb_dev, unsigned int pipe,
1244
                        void *data, int len, int *actual_length, int timeout)
1245
{
1246
        struct urb *urb;
1247
 
1248
        if (len < 0)
1249
                return -EINVAL;
1250
 
1251
        urb=usb_alloc_urb(0);
1252
        if (!urb)
1253
                return -ENOMEM;
1254
 
1255
        FILL_BULK_URB(urb, usb_dev, pipe, data, len,
1256
                    usb_api_blocking_completion, 0);
1257
 
1258
        return usb_start_wait_urb(urb,timeout,actual_length);
1259
}
1260
 
1261
/*
1262
 * usb_get_current_frame_number()
1263
 *
1264
 * returns the current frame number for the parent USB bus/controller
1265
 * of the given USB device.
1266
 */
1267
int usb_get_current_frame_number(struct usb_device *usb_dev)
1268
{
1269
        return usb_dev->bus->op->get_frame_number (usb_dev);
1270
}
1271
/*-------------------------------------------------------------------*/
1272
 
1273
static int usb_parse_endpoint(struct usb_endpoint_descriptor *endpoint, unsigned char *buffer, int size)
1274
{
1275
        struct usb_descriptor_header *header;
1276
        unsigned char *begin;
1277
        int parsed = 0, len, numskipped;
1278
 
1279
        header = (struct usb_descriptor_header *)buffer;
1280
 
1281
        /* Everything should be fine being passed into here, but we sanity */
1282
        /*  check JIC */
1283
        if (header->bLength > size) {
1284
                err("ran out of descriptors parsing");
1285
                return -1;
1286
        }
1287
 
1288
        if (header->bDescriptorType != USB_DT_ENDPOINT) {
1289
                warn("unexpected descriptor 0x%X, expecting endpoint descriptor, type 0x%X",
1290
                        endpoint->bDescriptorType, USB_DT_ENDPOINT);
1291
                return parsed;
1292
        }
1293
 
1294
        if (header->bLength == USB_DT_ENDPOINT_AUDIO_SIZE)
1295
                memcpy(endpoint, buffer, USB_DT_ENDPOINT_AUDIO_SIZE);
1296
        else
1297
                memcpy(endpoint, buffer, USB_DT_ENDPOINT_SIZE);
1298
 
1299
        le16_to_cpus(&endpoint->wMaxPacketSize);
1300
 
1301
        buffer += header->bLength;
1302
        size -= header->bLength;
1303
        parsed += header->bLength;
1304
 
1305
        /* Skip over the rest of the Class Specific or Vendor Specific */
1306
        /*  descriptors */
1307
        begin = buffer;
1308
        numskipped = 0;
1309
        while (size >= sizeof(struct usb_descriptor_header)) {
1310
                header = (struct usb_descriptor_header *)buffer;
1311
 
1312
                if (header->bLength < 2) {
1313
                        err("invalid descriptor length of %d", header->bLength);
1314
                        return -1;
1315
                }
1316
 
1317
                /* If we find another "proper" descriptor then we're done  */
1318
                if ((header->bDescriptorType == USB_DT_ENDPOINT) ||
1319
                    (header->bDescriptorType == USB_DT_INTERFACE) ||
1320
                    (header->bDescriptorType == USB_DT_CONFIG) ||
1321
                    (header->bDescriptorType == USB_DT_DEVICE))
1322
                        break;
1323
 
1324
                dbg("skipping descriptor 0x%X",
1325
                        header->bDescriptorType);
1326
                numskipped++;
1327
 
1328
                buffer += header->bLength;
1329
                size -= header->bLength;
1330
                parsed += header->bLength;
1331
        }
1332
        if (numskipped)
1333
                dbg("skipped %d class/vendor specific endpoint descriptors", numskipped);
1334
 
1335
        /* Copy any unknown descriptors into a storage area for drivers */
1336
        /*  to later parse */
1337
        len = (int)(buffer - begin);
1338
        if (!len) {
1339
                endpoint->extra = NULL;
1340
                endpoint->extralen = 0;
1341
                return parsed;
1342
        }
1343
 
1344
        endpoint->extra = kmalloc(len, GFP_KERNEL);
1345
 
1346
        if (!endpoint->extra) {
1347
                err("couldn't allocate memory for endpoint extra descriptors");
1348
                endpoint->extralen = 0;
1349
                return parsed;
1350
        }
1351
 
1352
        memcpy(endpoint->extra, begin, len);
1353
        endpoint->extralen = len;
1354
 
1355
        return parsed;
1356
}
1357
 
1358
static int usb_parse_interface(struct usb_interface *interface, unsigned char *buffer, int size)
1359
{
1360
        int i, len, numskipped, retval, parsed = 0;
1361
        struct usb_descriptor_header *header;
1362
        struct usb_interface_descriptor *ifp;
1363
        unsigned char *begin;
1364
 
1365
        interface->act_altsetting = 0;
1366
        interface->num_altsetting = 0;
1367
        interface->max_altsetting = USB_ALTSETTINGALLOC;
1368
 
1369
        interface->altsetting = kmalloc(sizeof(struct usb_interface_descriptor) * interface->max_altsetting, GFP_KERNEL);
1370
 
1371
        if (!interface->altsetting) {
1372
                err("couldn't kmalloc interface->altsetting");
1373
                return -1;
1374
        }
1375
 
1376
        while (size > 0) {
1377
                if (interface->num_altsetting >= interface->max_altsetting) {
1378
                        void *ptr;
1379
                        int oldmas;
1380
 
1381
                        oldmas = interface->max_altsetting;
1382
                        interface->max_altsetting += USB_ALTSETTINGALLOC;
1383
                        if (interface->max_altsetting > USB_MAXALTSETTING) {
1384
                                warn("too many alternate settings (max %d)",
1385
                                        USB_MAXALTSETTING);
1386
                                return -1;
1387
                        }
1388
 
1389
                        ptr = interface->altsetting;
1390
                        interface->altsetting = kmalloc(sizeof(struct usb_interface_descriptor) * interface->max_altsetting, GFP_KERNEL);
1391
                        if (!interface->altsetting) {
1392
                                err("couldn't kmalloc interface->altsetting");
1393
                                interface->altsetting = ptr;
1394
                                return -1;
1395
                        }
1396
                        memcpy(interface->altsetting, ptr, sizeof(struct usb_interface_descriptor) * oldmas);
1397
 
1398
                        kfree(ptr);
1399
                }
1400
 
1401
                ifp = interface->altsetting + interface->num_altsetting;
1402
                interface->num_altsetting++;
1403
 
1404
                memcpy(ifp, buffer, USB_DT_INTERFACE_SIZE);
1405
 
1406
                /* Skip over the interface */
1407
                buffer += ifp->bLength;
1408
                parsed += ifp->bLength;
1409
                size -= ifp->bLength;
1410
 
1411
                begin = buffer;
1412
                numskipped = 0;
1413
 
1414
                /* Skip over any interface, class or vendor descriptors */
1415
                while (size >= sizeof(struct usb_descriptor_header)) {
1416
                        header = (struct usb_descriptor_header *)buffer;
1417
 
1418
                        if (header->bLength < 2) {
1419
                                err("invalid descriptor length of %d", header->bLength);
1420
                                return -1;
1421
                        }
1422
 
1423
                        /* If we find another "proper" descriptor then we're done  */
1424
                        if ((header->bDescriptorType == USB_DT_INTERFACE) ||
1425
                            (header->bDescriptorType == USB_DT_ENDPOINT) ||
1426
                            (header->bDescriptorType == USB_DT_CONFIG) ||
1427
                            (header->bDescriptorType == USB_DT_DEVICE))
1428
                                break;
1429
 
1430
                        numskipped++;
1431
 
1432
                        buffer += header->bLength;
1433
                        parsed += header->bLength;
1434
                        size -= header->bLength;
1435
                }
1436
 
1437
                if (numskipped)
1438
                        dbg("skipped %d class/vendor specific interface descriptors", numskipped);
1439
 
1440
                /* Copy any unknown descriptors into a storage area for */
1441
                /*  drivers to later parse */
1442
                len = (int)(buffer - begin);
1443
                if (!len) {
1444
                        ifp->extra = NULL;
1445
                        ifp->extralen = 0;
1446
                } else {
1447
                        ifp->extra = kmalloc(len, GFP_KERNEL);
1448
 
1449
                        if (!ifp->extra) {
1450
                                err("couldn't allocate memory for interface extra descriptors");
1451
                                ifp->extralen = 0;
1452
                                return -1;
1453
                        }
1454
                        memcpy(ifp->extra, begin, len);
1455
                        ifp->extralen = len;
1456
                }
1457
 
1458
                /* Did we hit an unexpected descriptor? */
1459
                header = (struct usb_descriptor_header *)buffer;
1460
                if ((size >= sizeof(struct usb_descriptor_header)) &&
1461
                    ((header->bDescriptorType == USB_DT_CONFIG) ||
1462
                     (header->bDescriptorType == USB_DT_DEVICE)))
1463
                        return parsed;
1464
 
1465
                if (ifp->bNumEndpoints > USB_MAXENDPOINTS) {
1466
                        warn("too many endpoints");
1467
                        return -1;
1468
                }
1469
 
1470
                ifp->endpoint = (struct usb_endpoint_descriptor *)
1471
                        kmalloc(ifp->bNumEndpoints *
1472
                        sizeof(struct usb_endpoint_descriptor), GFP_KERNEL);
1473
                if (!ifp->endpoint) {
1474
                        err("out of memory");
1475
                        return -1;
1476
                }
1477
 
1478
                memset(ifp->endpoint, 0, ifp->bNumEndpoints *
1479
                        sizeof(struct usb_endpoint_descriptor));
1480
 
1481
                for (i = 0; i < ifp->bNumEndpoints; i++) {
1482
                        header = (struct usb_descriptor_header *)buffer;
1483
 
1484
                        if (header->bLength > size) {
1485
                                err("ran out of descriptors parsing");
1486
                                return -1;
1487
                        }
1488
 
1489
                        retval = usb_parse_endpoint(ifp->endpoint + i, buffer, size);
1490
                        if (retval < 0)
1491
                                return retval;
1492
 
1493
                        buffer += retval;
1494
                        parsed += retval;
1495
                        size -= retval;
1496
                }
1497
 
1498
                /* We check to see if it's an alternate to this one */
1499
                ifp = (struct usb_interface_descriptor *)buffer;
1500
                if (size < USB_DT_INTERFACE_SIZE ||
1501
                    ifp->bDescriptorType != USB_DT_INTERFACE ||
1502
                    !ifp->bAlternateSetting)
1503
                        return parsed;
1504
        }
1505
 
1506
        return parsed;
1507
}
1508
 
1509
int usb_parse_configuration(struct usb_config_descriptor *config, char *buffer)
1510
{
1511
        int i, retval, size;
1512
        struct usb_descriptor_header *header;
1513
 
1514
        memcpy(config, buffer, USB_DT_CONFIG_SIZE);
1515
        le16_to_cpus(&config->wTotalLength);
1516
        size = config->wTotalLength;
1517
 
1518
        if (config->bNumInterfaces > USB_MAXINTERFACES) {
1519
                warn("too many interfaces");
1520
                return -1;
1521
        }
1522
 
1523
        config->interface = (struct usb_interface *)
1524
                kmalloc(config->bNumInterfaces *
1525
                sizeof(struct usb_interface), GFP_KERNEL);
1526
        dbg("kmalloc IF %p, numif %i", config->interface, config->bNumInterfaces);
1527
        if (!config->interface) {
1528
                err("out of memory");
1529
                return -1;
1530
        }
1531
 
1532
        memset(config->interface, 0,
1533
               config->bNumInterfaces * sizeof(struct usb_interface));
1534
 
1535
        buffer += config->bLength;
1536
        size -= config->bLength;
1537
 
1538
        config->extra = NULL;
1539
        config->extralen = 0;
1540
 
1541
        for (i = 0; i < config->bNumInterfaces; i++) {
1542
                int numskipped, len;
1543
                char *begin;
1544
 
1545
                /* Skip over the rest of the Class Specific or Vendor */
1546
                /*  Specific descriptors */
1547
                begin = buffer;
1548
                numskipped = 0;
1549
                while (size >= sizeof(struct usb_descriptor_header)) {
1550
                        header = (struct usb_descriptor_header *)buffer;
1551
 
1552
                        if ((header->bLength > size) || (header->bLength < 2)) {
1553
                                err("invalid descriptor length of %d", header->bLength);
1554
                                return -1;
1555
                        }
1556
 
1557
                        /* If we find another "proper" descriptor then we're done  */
1558
                        if ((header->bDescriptorType == USB_DT_ENDPOINT) ||
1559
                            (header->bDescriptorType == USB_DT_INTERFACE) ||
1560
                            (header->bDescriptorType == USB_DT_CONFIG) ||
1561
                            (header->bDescriptorType == USB_DT_DEVICE))
1562
                                break;
1563
 
1564
                        dbg("skipping descriptor 0x%X", header->bDescriptorType);
1565
                        numskipped++;
1566
 
1567
                        buffer += header->bLength;
1568
                        size -= header->bLength;
1569
                }
1570
                if (numskipped)
1571
                        dbg("skipped %d class/vendor specific endpoint descriptors", numskipped);
1572
 
1573
                /* Copy any unknown descriptors into a storage area for */
1574
                /*  drivers to later parse */
1575
                len = (int)(buffer - begin);
1576
                if (len) {
1577
                        if (config->extralen) {
1578
                                warn("extra config descriptor");
1579
                        } else {
1580
                                config->extra = kmalloc(len, GFP_KERNEL);
1581
                                if (!config->extra) {
1582
                                        err("couldn't allocate memory for config extra descriptors");
1583
                                        config->extralen = 0;
1584
                                        return -1;
1585
                                }
1586
 
1587
                                memcpy(config->extra, begin, len);
1588
                                config->extralen = len;
1589
                        }
1590
                }
1591
 
1592
                retval = usb_parse_interface(config->interface + i, buffer, size);
1593
                if (retval < 0)
1594
                        return retval;
1595
 
1596
                buffer += retval;
1597
                size -= retval;
1598
        }
1599
 
1600
        return size;
1601
}
1602
 
1603
void usb_destroy_configuration(struct usb_device *dev)
1604
{
1605
        int c, i, j, k;
1606
 
1607
        if (!dev->config)
1608
                return;
1609
 
1610
        if (dev->rawdescriptors) {
1611
                for (i = 0; i < dev->descriptor.bNumConfigurations; i++)
1612
                        kfree(dev->rawdescriptors[i]);
1613
 
1614
                kfree(dev->rawdescriptors);
1615
        }
1616
 
1617
        for (c = 0; c < dev->descriptor.bNumConfigurations; c++) {
1618
                struct usb_config_descriptor *cf = &dev->config[c];
1619
 
1620
                if (!cf->interface)
1621
                        break;
1622
 
1623
                for (i = 0; i < cf->bNumInterfaces; i++) {
1624
                        struct usb_interface *ifp =
1625
                                &cf->interface[i];
1626
 
1627
                        if (!ifp->altsetting)
1628
                                break;
1629
 
1630
                        for (j = 0; j < ifp->num_altsetting; j++) {
1631
                                struct usb_interface_descriptor *as =
1632
                                        &ifp->altsetting[j];
1633
 
1634
                                if(as->extra) {
1635
                                        kfree(as->extra);
1636
                                }
1637
 
1638
                                if (!as->endpoint)
1639
                                        break;
1640
 
1641
                                for(k = 0; k < as->bNumEndpoints; k++) {
1642
                                        if(as->endpoint[k].extra) {
1643
                                                kfree(as->endpoint[k].extra);
1644
                                        }
1645
                                }
1646
                                kfree(as->endpoint);
1647
                        }
1648
 
1649
                        kfree(ifp->altsetting);
1650
                }
1651
                kfree(cf->interface);
1652
        }
1653
        kfree(dev->config);
1654
}
1655
 
1656
/* for returning string descriptors in UTF-16LE */
1657
static int ascii2utf (char *ascii, __u8 *utf, int utfmax)
1658
{
1659
        int retval;
1660
 
1661
        for (retval = 0; *ascii && utfmax > 1; utfmax -= 2, retval += 2) {
1662
                *utf++ = *ascii++ & 0x7f;
1663
                *utf++ = 0;
1664
        }
1665
        return retval;
1666
}
1667
 
1668
/*
1669
 * root_hub_string is used by each host controller's root hub code,
1670
 * so that they're identified consistently throughout the system.
1671
 */
1672
int usb_root_hub_string (int id, int serial, char *type, __u8 *data, int len)
1673
{
1674
        char buf [30];
1675
 
1676
        // assert (len > (2 * (sizeof (buf) + 1)));
1677
        // assert (strlen (type) <= 8);
1678
 
1679
        // language ids
1680
        if (id == 0) {
1681
                *data++ = 4; *data++ = 3;       /* 4 bytes data */
1682
                *data++ = 0; *data++ = 0; /* some language id */
1683
                return 4;
1684
 
1685
        // serial number
1686
        } else if (id == 1) {
1687
                sprintf (buf, "%x", serial);
1688
 
1689
        // product description
1690
        } else if (id == 2) {
1691
                sprintf (buf, "USB %s Root Hub", type);
1692
 
1693
        // id 3 == vendor description
1694
 
1695
        // unsupported IDs --> "stall"
1696
        } else
1697
            return 0;
1698
 
1699
        data [0] = 2 + ascii2utf (buf, data + 2, len - 2);
1700
        data [1] = 3;
1701
        return data [0];
1702
}
1703
 
1704
/*
1705
 * __usb_get_extra_descriptor() finds a descriptor of specific type in the
1706
 * extra field of the interface and endpoint descriptor structs.
1707
 */
1708
 
1709
int __usb_get_extra_descriptor(char *buffer, unsigned size, unsigned char type, void **ptr)
1710
{
1711
        struct usb_descriptor_header *header;
1712
 
1713
        while (size >= sizeof(struct usb_descriptor_header)) {
1714
                header = (struct usb_descriptor_header *)buffer;
1715
 
1716
                if (header->bLength < 2) {
1717
                        err("invalid descriptor length of %d", header->bLength);
1718
                        return -1;
1719
                }
1720
 
1721
                if (header->bDescriptorType == type) {
1722
                        *ptr = header;
1723
                        return 0;
1724
                }
1725
 
1726
                buffer += header->bLength;
1727
                size -= header->bLength;
1728
        }
1729
        return -1;
1730
}
1731
 
1732
/*
1733
 * Something got disconnected. Get rid of it, and all of its children.
1734
 */
1735
void usb_disconnect(struct usb_device **pdev)
1736
{
1737
        struct usb_device * dev = *pdev;
1738
        int i;
1739
 
1740
        if (!dev)
1741
                return;
1742
 
1743
        *pdev = NULL;
1744
 
1745
        info("USB disconnect on device %s-%s address %d",
1746
                        dev->bus->bus_name, dev->devpath, dev->devnum);
1747
 
1748
        if (dev->actconfig) {
1749
                for (i = 0; i < dev->actconfig->bNumInterfaces; i++) {
1750
                        struct usb_interface *interface = &dev->actconfig->interface[i];
1751
                        struct usb_driver *driver = interface->driver;
1752
                        if (driver) {
1753
                                down(&driver->serialize);
1754
                                driver->disconnect(dev, interface->private_data);
1755
                                up(&driver->serialize);
1756
                                /* if driver->disconnect didn't release the interface */
1757
                                if (interface->driver)
1758
                                        usb_driver_release_interface(driver, interface);
1759
                        }
1760
                }
1761
        }
1762
 
1763
        /* Free up all the children.. */
1764
        for (i = 0; i < USB_MAXCHILDREN; i++) {
1765
                struct usb_device **child = dev->children + i;
1766
                if (*child)
1767
                        usb_disconnect(child);
1768
        }
1769
 
1770
        /* Let policy agent unload modules etc */
1771
        call_policy ("remove", dev);
1772
 
1773
        /* Free the device number and remove the /proc/bus/usb entry */
1774
        if (dev->devnum > 0) {
1775
                clear_bit(dev->devnum, &dev->bus->devmap.devicemap);
1776
                usbdevfs_remove_device(dev);
1777
        }
1778
 
1779
        /* Free up the device itself */
1780
        usb_free_dev(dev);
1781
}
1782
 
1783
/*
1784
 * Connect a new USB device. This basically just initializes
1785
 * the USB device information and sets up the topology - it's
1786
 * up to the low-level driver to reset the port and actually
1787
 * do the setup (the upper levels don't know how to do that).
1788
 */
1789
void usb_connect(struct usb_device *dev)
1790
{
1791
        int devnum;
1792
        // FIXME needs locking for SMP!!
1793
        /* why? this is called only from the hub thread,
1794
         * which hopefully doesn't run on multiple CPU's simultaneously 8-)
1795
         */
1796
        dev->descriptor.bMaxPacketSize0 = 8;  /* Start off at 8 bytes  */
1797
#ifndef DEVNUM_ROUND_ROBIN
1798
        devnum = find_next_zero_bit(dev->bus->devmap.devicemap, 128, 1);
1799
#else   /* round_robin alloc of devnums */
1800
        /* Try to allocate the next devnum beginning at bus->devnum_next. */
1801
        devnum = find_next_zero_bit(dev->bus->devmap.devicemap, 128, dev->bus->devnum_next);
1802
        if (devnum >= 128)
1803
                devnum = find_next_zero_bit(dev->bus->devmap.devicemap, 128, 1);
1804
 
1805
        dev->bus->devnum_next = ( devnum >= 127 ? 1 : devnum + 1);
1806
#endif  /* round_robin alloc of devnums */
1807
 
1808
        if (devnum < 128) {
1809
                set_bit(devnum, dev->bus->devmap.devicemap);
1810
                dev->devnum = devnum;
1811
        }
1812
}
1813
 
1814
/*
1815
 * These are the actual routines to send
1816
 * and receive control messages.
1817
 */
1818
 
1819
/* USB spec identifies 5 second timeouts.
1820
 * Some devices (MGE Ellipse UPSes, etc) need it, too.
1821
 */
1822
#define GET_TIMEOUT 5
1823
#define SET_TIMEOUT 5
1824
 
1825
int usb_set_address(struct usb_device *dev)
1826
{
1827
        return usb_control_msg(dev, usb_snddefctrl(dev), USB_REQ_SET_ADDRESS,
1828
                0, dev->devnum, 0, NULL, 0, HZ * SET_TIMEOUT);
1829
}
1830
 
1831
int usb_get_descriptor(struct usb_device *dev, unsigned char type, unsigned char index, void *buf, int size)
1832
{
1833
        int i = 5;
1834
        int result;
1835
 
1836
        memset(buf,0,size);      // Make sure we parse really received data
1837
 
1838
        while (i--) {
1839
                if ((result = usb_control_msg(dev, usb_rcvctrlpipe(dev, 0),
1840
                        USB_REQ_GET_DESCRIPTOR, USB_DIR_IN,
1841
                        (type << 8) + index, 0, buf, size, HZ * GET_TIMEOUT)) > 0 ||
1842
                     result == -EPIPE)
1843
                        break;  /* retry if the returned length was 0; flaky device */
1844
        }
1845
        return result;
1846
}
1847
 
1848
int usb_get_class_descriptor(struct usb_device *dev, int ifnum,
1849
                unsigned char type, unsigned char id, void *buf, int size)
1850
{
1851
        return usb_control_msg(dev, usb_rcvctrlpipe(dev, 0),
1852
                USB_REQ_GET_DESCRIPTOR, USB_RECIP_INTERFACE | USB_DIR_IN,
1853
                (type << 8) + id, ifnum, buf, size, HZ * GET_TIMEOUT);
1854
}
1855
 
1856
int usb_get_string(struct usb_device *dev, unsigned short langid, unsigned char index, void *buf, int size)
1857
{
1858
        return usb_control_msg(dev, usb_rcvctrlpipe(dev, 0),
1859
                USB_REQ_GET_DESCRIPTOR, USB_DIR_IN,
1860
                (USB_DT_STRING << 8) + index, langid, buf, size, HZ * GET_TIMEOUT);
1861
}
1862
 
1863
int usb_get_device_descriptor(struct usb_device *dev)
1864
{
1865
        int ret = usb_get_descriptor(dev, USB_DT_DEVICE, 0, &dev->descriptor,
1866
                                     sizeof(dev->descriptor));
1867
        if (ret >= 0) {
1868
                le16_to_cpus(&dev->descriptor.bcdUSB);
1869
                le16_to_cpus(&dev->descriptor.idVendor);
1870
                le16_to_cpus(&dev->descriptor.idProduct);
1871
                le16_to_cpus(&dev->descriptor.bcdDevice);
1872
        }
1873
        return ret;
1874
}
1875
 
1876
int usb_get_status(struct usb_device *dev, int type, int target, void *data)
1877
{
1878
        return usb_control_msg(dev, usb_rcvctrlpipe(dev, 0),
1879
                USB_REQ_GET_STATUS, USB_DIR_IN | type, 0, target, data, 2, HZ * GET_TIMEOUT);
1880
}
1881
 
1882
int usb_get_protocol(struct usb_device *dev, int ifnum)
1883
{
1884
        unsigned char type;
1885
        int ret;
1886
 
1887
        if ((ret = usb_control_msg(dev, usb_rcvctrlpipe(dev, 0),
1888
            USB_REQ_GET_PROTOCOL, USB_DIR_IN | USB_TYPE_CLASS | USB_RECIP_INTERFACE,
1889
            0, ifnum, &type, 1, HZ * GET_TIMEOUT)) < 0)
1890
                return ret;
1891
 
1892
        return type;
1893
}
1894
 
1895
int usb_set_protocol(struct usb_device *dev, int ifnum, int protocol)
1896
{
1897
        return usb_control_msg(dev, usb_sndctrlpipe(dev, 0),
1898
                USB_REQ_SET_PROTOCOL, USB_TYPE_CLASS | USB_RECIP_INTERFACE,
1899
                protocol, ifnum, NULL, 0, HZ * SET_TIMEOUT);
1900
}
1901
 
1902
int usb_set_idle(struct usb_device *dev, int ifnum, int duration, int report_id)
1903
{
1904
        return usb_control_msg(dev, usb_sndctrlpipe(dev, 0),
1905
                USB_REQ_SET_IDLE, USB_TYPE_CLASS | USB_RECIP_INTERFACE,
1906
                (duration << 8) | report_id, ifnum, NULL, 0, HZ * SET_TIMEOUT);
1907
}
1908
 
1909
void usb_set_maxpacket(struct usb_device *dev)
1910
{
1911
        int i, b;
1912
 
1913
        for (i=0; i<dev->actconfig->bNumInterfaces; i++) {
1914
                struct usb_interface *ifp = dev->actconfig->interface + i;
1915
                struct usb_interface_descriptor *as = ifp->altsetting + ifp->act_altsetting;
1916
                struct usb_endpoint_descriptor *ep = as->endpoint;
1917
                int e;
1918
 
1919
                for (e=0; e<as->bNumEndpoints; e++) {
1920
                        b = ep[e].bEndpointAddress & USB_ENDPOINT_NUMBER_MASK;
1921
                        if ((ep[e].bmAttributes & USB_ENDPOINT_XFERTYPE_MASK) ==
1922
                                USB_ENDPOINT_XFER_CONTROL) {    /* Control => bidirectional */
1923
                                dev->epmaxpacketout[b] = ep[e].wMaxPacketSize;
1924
                                dev->epmaxpacketin [b] = ep[e].wMaxPacketSize;
1925
                                }
1926
                        else if (usb_endpoint_out(ep[e].bEndpointAddress)) {
1927
                                if (ep[e].wMaxPacketSize > dev->epmaxpacketout[b])
1928
                                        dev->epmaxpacketout[b] = ep[e].wMaxPacketSize;
1929
                        }
1930
                        else {
1931
                                if (ep[e].wMaxPacketSize > dev->epmaxpacketin [b])
1932
                                        dev->epmaxpacketin [b] = ep[e].wMaxPacketSize;
1933
                        }
1934
                }
1935
        }
1936
}
1937
 
1938
/*
1939
 * endp: endpoint number in bits 0-3;
1940
 *      direction flag in bit 7 (1 = IN, 0 = OUT)
1941
 */
1942
int usb_clear_halt(struct usb_device *dev, int pipe)
1943
{
1944
        int result;
1945
        __u16 status;
1946
        unsigned char *buffer;
1947
        int endp=usb_pipeendpoint(pipe)|(usb_pipein(pipe)<<7);
1948
 
1949
/*
1950
        if (!usb_endpoint_halted(dev, endp & 0x0f, usb_endpoint_out(endp)))
1951
                return 0;
1952
*/
1953
 
1954
        result = usb_control_msg(dev, usb_sndctrlpipe(dev, 0),
1955
                USB_REQ_CLEAR_FEATURE, USB_RECIP_ENDPOINT, 0, endp, NULL, 0, HZ * SET_TIMEOUT);
1956
 
1957
        /* don't clear if failed */
1958
        if (result < 0)
1959
                return result;
1960
 
1961
        buffer = kmalloc(sizeof(status), GFP_KERNEL);
1962
        if (!buffer) {
1963
                err("unable to allocate memory for configuration descriptors");
1964
                return -ENOMEM;
1965
        }
1966
 
1967
        result = usb_control_msg(dev, usb_rcvctrlpipe(dev, 0),
1968
                USB_REQ_GET_STATUS, USB_DIR_IN | USB_RECIP_ENDPOINT, 0, endp,
1969
                buffer, sizeof(status), HZ * SET_TIMEOUT);
1970
 
1971
        memcpy(&status, buffer, sizeof(status));
1972
        kfree(buffer);
1973
 
1974
        if (result < 0)
1975
                return result;
1976
 
1977
        if (le16_to_cpu(status) & 1)
1978
                return -EPIPE;          /* still halted */
1979
 
1980
        usb_endpoint_running(dev, usb_pipeendpoint(pipe), usb_pipeout(pipe));
1981
 
1982
        /* toggle is reset on clear */
1983
 
1984
        usb_settoggle(dev, usb_pipeendpoint(pipe), usb_pipeout(pipe), 0);
1985
 
1986
        return 0;
1987
}
1988
 
1989
int usb_set_interface(struct usb_device *dev, int interface, int alternate)
1990
{
1991
        struct usb_interface *iface;
1992
        int ret;
1993
 
1994
        iface = usb_ifnum_to_if(dev, interface);
1995
        if (!iface) {
1996
                warn("selecting invalid interface %d", interface);
1997
                return -EINVAL;
1998
        }
1999
 
2000
        /* 9.4.10 says devices don't need this, if the interface
2001
           only has one alternate setting */
2002
        if (iface->num_altsetting == 1) {
2003
                dbg("ignoring set_interface for dev %d, iface %d, alt %d",
2004
                        dev->devnum, interface, alternate);
2005
                return 0;
2006
        }
2007
 
2008
        if ((ret = usb_control_msg(dev, usb_sndctrlpipe(dev, 0),
2009
            USB_REQ_SET_INTERFACE, USB_RECIP_INTERFACE, alternate,
2010
            interface, NULL, 0, HZ * 5)) < 0)
2011
                return ret;
2012
 
2013
        iface->act_altsetting = alternate;
2014
        dev->toggle[0] = 0;       /* 9.1.1.5 says to do this */
2015
        dev->toggle[1] = 0;
2016
        usb_set_maxpacket(dev);
2017
        return 0;
2018
}
2019
 
2020
int usb_set_configuration(struct usb_device *dev, int configuration)
2021
{
2022
        int i, ret;
2023
        struct usb_config_descriptor *cp = NULL;
2024
 
2025
        for (i=0; i<dev->descriptor.bNumConfigurations; i++) {
2026
                if (dev->config[i].bConfigurationValue == configuration) {
2027
                        cp = &dev->config[i];
2028
                        break;
2029
                }
2030
        }
2031
        if (!cp) {
2032
                warn("selecting invalid configuration %d", configuration);
2033
                return -EINVAL;
2034
        }
2035
 
2036
        if ((ret = usb_control_msg(dev, usb_sndctrlpipe(dev, 0),
2037
            USB_REQ_SET_CONFIGURATION, 0, configuration, 0, NULL, 0, HZ * SET_TIMEOUT)) < 0)
2038
                return ret;
2039
 
2040
        dev->actconfig = cp;
2041
        dev->toggle[0] = 0;
2042
        dev->toggle[1] = 0;
2043
        usb_set_maxpacket(dev);
2044
 
2045
        return 0;
2046
}
2047
 
2048
int usb_get_report(struct usb_device *dev, int ifnum, unsigned char type, unsigned char id, void *buf, int size)
2049
{
2050
        return usb_control_msg(dev, usb_rcvctrlpipe(dev, 0),
2051
                USB_REQ_GET_REPORT, USB_DIR_IN | USB_TYPE_CLASS | USB_RECIP_INTERFACE,
2052
                (type << 8) + id, ifnum, buf, size, HZ * GET_TIMEOUT);
2053
}
2054
 
2055
int usb_set_report(struct usb_device *dev, int ifnum, unsigned char type, unsigned char id, void *buf, int size)
2056
{
2057
        return usb_control_msg(dev, usb_sndctrlpipe(dev, 0),
2058
                USB_REQ_SET_REPORT, USB_TYPE_CLASS | USB_RECIP_INTERFACE,
2059
                (type << 8) + id, ifnum, buf, size, HZ);
2060
}
2061
 
2062
int usb_get_configuration(struct usb_device *dev)
2063
{
2064
        int result;
2065
        unsigned int cfgno, length;
2066
        unsigned char *buffer;
2067
        unsigned char *bigbuffer;
2068
        struct usb_config_descriptor *desc;
2069
 
2070
        if (dev->descriptor.bNumConfigurations > USB_MAXCONFIG) {
2071
                warn("too many configurations");
2072
                return -EINVAL;
2073
        }
2074
 
2075
        if (dev->descriptor.bNumConfigurations < 1) {
2076
                warn("not enough configurations");
2077
                return -EINVAL;
2078
        }
2079
 
2080
        dev->config = (struct usb_config_descriptor *)
2081
                kmalloc(dev->descriptor.bNumConfigurations *
2082
                sizeof(struct usb_config_descriptor), GFP_KERNEL);
2083
        if (!dev->config) {
2084
                err("out of memory");
2085
                return -ENOMEM;
2086
        }
2087
        memset(dev->config, 0, dev->descriptor.bNumConfigurations *
2088
                sizeof(struct usb_config_descriptor));
2089
 
2090
        dev->rawdescriptors = (char **)kmalloc(sizeof(char *) *
2091
                dev->descriptor.bNumConfigurations, GFP_KERNEL);
2092
        if (!dev->rawdescriptors) {
2093
                err("out of memory");
2094
                return -ENOMEM;
2095
        }
2096
 
2097
        buffer = kmalloc(8, GFP_KERNEL);
2098
        if (!buffer) {
2099
                err("unable to allocate memory for configuration descriptors");
2100
                return -ENOMEM;
2101
        }
2102
        desc = (struct usb_config_descriptor *)buffer;
2103
 
2104
        for (cfgno = 0; cfgno < dev->descriptor.bNumConfigurations; cfgno++) {
2105
                /* We grab the first 8 bytes so we know how long the whole */
2106
                /*  configuration is */
2107
                result = usb_get_descriptor(dev, USB_DT_CONFIG, cfgno, buffer, 8);
2108
                if (result < 8) {
2109
                        if (result < 0)
2110
                                err("unable to get descriptor");
2111
                        else {
2112
                                err("config descriptor too short (expected %i, got %i)", 8, result);
2113
                                result = -EINVAL;
2114
                        }
2115
                        goto err;
2116
                }
2117
 
2118
                /* Get the full buffer */
2119
                length = le16_to_cpu(desc->wTotalLength);
2120
 
2121
                bigbuffer = kmalloc(length, GFP_KERNEL);
2122
                if (!bigbuffer) {
2123
                        err("unable to allocate memory for configuration descriptors");
2124
                        result = -ENOMEM;
2125
                        goto err;
2126
                }
2127
 
2128
                /* Now that we know the length, get the whole thing */
2129
                result = usb_get_descriptor(dev, USB_DT_CONFIG, cfgno, bigbuffer, length);
2130
                if (result < 0) {
2131
                        err("couldn't get all of config descriptors");
2132
                        kfree(bigbuffer);
2133
                        goto err;
2134
                }
2135
 
2136
                if (result < length) {
2137
                        err("config descriptor too short (expected %i, got %i)", length, result);
2138
                        result = -EINVAL;
2139
                        kfree(bigbuffer);
2140
                        goto err;
2141
                }
2142
 
2143
                dev->rawdescriptors[cfgno] = bigbuffer;
2144
 
2145
                result = usb_parse_configuration(&dev->config[cfgno], bigbuffer);
2146
                if (result > 0)
2147
                        dbg("descriptor data left");
2148
                else if (result < 0) {
2149
                        result = -EINVAL;
2150
                        goto err;
2151
                }
2152
        }
2153
 
2154
        kfree(buffer);
2155
        return 0;
2156
err:
2157
        kfree(buffer);
2158
        dev->descriptor.bNumConfigurations = cfgno;
2159
        return result;
2160
}
2161
 
2162
/*
2163
 * usb_string:
2164
 *      returns string length (> 0) or error (< 0)
2165
 */
2166
int usb_string(struct usb_device *dev, int index, char *buf, size_t size)
2167
{
2168
        unsigned char *tbuf;
2169
        int err;
2170
        unsigned int u, idx;
2171
 
2172
        if (size <= 0 || !buf || !index)
2173
                return -EINVAL;
2174
        buf[0] = 0;
2175
        tbuf = kmalloc(256, GFP_KERNEL);
2176
        if (!tbuf)
2177
                return -ENOMEM;
2178
 
2179
        /* get langid for strings if it's not yet known */
2180
        if (!dev->have_langid) {
2181
                err = usb_get_string(dev, 0, 0, tbuf, 4);
2182
                if (err < 0) {
2183
                        err("error getting string descriptor 0 (error=%d)", err);
2184
                        goto errout;
2185
                } else if (err < 4 || tbuf[0] < 4) {
2186
                        err("string descriptor 0 too short");
2187
                        err = -EINVAL;
2188
                        goto errout;
2189
                } else {
2190
                        dev->have_langid = -1;
2191
                        dev->string_langid = tbuf[2] | (tbuf[3]<< 8);
2192
                                /* always use the first langid listed */
2193
                        dbg("USB device number %d default language ID 0x%x",
2194
                                dev->devnum, dev->string_langid);
2195
                }
2196
        }
2197
 
2198
        /*
2199
         * Just ask for a maximum length string and then take the length
2200
         * that was returned.
2201
         */
2202
        err = usb_get_string(dev, dev->string_langid, index, tbuf, 255);
2203
        if (err < 0)
2204
                goto errout;
2205
 
2206
        size--;         /* leave room for trailing NULL char in output buffer */
2207
        for (idx = 0, u = 2; u < err; u += 2) {
2208
                if (idx >= size)
2209
                        break;
2210
                if (tbuf[u+1])                  /* high byte */
2211
                        buf[idx++] = '?';  /* non-ASCII character */
2212
                else
2213
                        buf[idx++] = tbuf[u];
2214
        }
2215
        buf[idx] = 0;
2216
        err = idx;
2217
 
2218
 errout:
2219
        kfree(tbuf);
2220
        return err;
2221
}
2222
 
2223
/*
2224
 * By the time we get here, the device has gotten a new device ID
2225
 * and is in the default state. We need to identify the thing and
2226
 * get the ball rolling..
2227
 *
2228
 * Returns 0 for success, != 0 for error.
2229
 */
2230
int usb_new_device(struct usb_device *dev)
2231
{
2232
        int err;
2233
 
2234
        /* USB v1.1 5.5.3 */
2235
        /* We read the first 8 bytes from the device descriptor to get to */
2236
        /*  the bMaxPacketSize0 field. Then we set the maximum packet size */
2237
        /*  for the control pipe, and retrieve the rest */
2238
        dev->epmaxpacketin [0] = 8;
2239
        dev->epmaxpacketout[0] = 8;
2240
 
2241
        err = usb_set_address(dev);
2242
        if (err < 0) {
2243
                err("USB device not accepting new address=%d (error=%d)",
2244
                        dev->devnum, err);
2245
                clear_bit(dev->devnum, &dev->bus->devmap.devicemap);
2246
                dev->devnum = -1;
2247
                return 1;
2248
        }
2249
 
2250
        wait_ms(10);    /* Let the SET_ADDRESS settle */
2251
 
2252
        err = usb_get_descriptor(dev, USB_DT_DEVICE, 0, &dev->descriptor, 8);
2253
        if (err < 8) {
2254
                if (err < 0)
2255
                        err("USB device not responding, giving up (error=%d)", err);
2256
                else
2257
                        err("USB device descriptor short read (expected %i, got %i)", 8, err);
2258
                clear_bit(dev->devnum, &dev->bus->devmap.devicemap);
2259
                dev->devnum = -1;
2260
                return 1;
2261
        }
2262
        dev->epmaxpacketin [0] = dev->descriptor.bMaxPacketSize0;
2263
        dev->epmaxpacketout[0] = dev->descriptor.bMaxPacketSize0;
2264
 
2265
        err = usb_get_device_descriptor(dev);
2266
        if (err < (signed)sizeof(dev->descriptor)) {
2267
                if (err < 0)
2268
                        err("unable to get device descriptor (error=%d)", err);
2269
                else
2270
                        err("USB device descriptor short read (expected %Zi, got %i)",
2271
                                sizeof(dev->descriptor), err);
2272
 
2273
                clear_bit(dev->devnum, &dev->bus->devmap.devicemap);
2274
                dev->devnum = -1;
2275
                return 1;
2276
        }
2277
 
2278
        err = usb_get_configuration(dev);
2279
        if (err < 0) {
2280
                err("unable to get device %d configuration (error=%d)",
2281
                        dev->devnum, err);
2282
                clear_bit(dev->devnum, &dev->bus->devmap.devicemap);
2283
                dev->devnum = -1;
2284
                return 1;
2285
        }
2286
 
2287
        /* we set the default configuration here */
2288
        err = usb_set_configuration(dev, dev->config[0].bConfigurationValue);
2289
        if (err) {
2290
                err("failed to set device %d default configuration (error=%d)",
2291
                        dev->devnum, err);
2292
                clear_bit(dev->devnum, &dev->bus->devmap.devicemap);
2293
                dev->devnum = -1;
2294
                return 1;
2295
        }
2296
 
2297
        dbg("new device strings: Mfr=%d, Product=%d, SerialNumber=%d",
2298
                dev->descriptor.iManufacturer, dev->descriptor.iProduct, dev->descriptor.iSerialNumber);
2299
#ifdef DEBUG
2300
        if (dev->descriptor.iManufacturer)
2301
                usb_show_string(dev, "Manufacturer", dev->descriptor.iManufacturer);
2302
        if (dev->descriptor.iProduct)
2303
                usb_show_string(dev, "Product", dev->descriptor.iProduct);
2304
        if (dev->descriptor.iSerialNumber)
2305
                usb_show_string(dev, "SerialNumber", dev->descriptor.iSerialNumber);
2306
#endif
2307
 
2308
        /* now that the basic setup is over, add a /proc/bus/usb entry */
2309
        usbdevfs_add_device(dev);
2310
 
2311
        /* find drivers willing to handle this device */
2312
        usb_find_drivers(dev);
2313
 
2314
        /* userspace may load modules and/or configure further */
2315
        call_policy ("add", dev);
2316
 
2317
        return 0;
2318
}
2319
 
2320
static int usb_open(struct inode * inode, struct file * file)
2321
{
2322
        int minor = MINOR(inode->i_rdev);
2323
        struct usb_driver *c = usb_minors[minor/16];
2324
        int err = -ENODEV;
2325
        struct file_operations *old_fops, *new_fops = NULL;
2326
 
2327
        /*
2328
         * No load-on-demand? Randy, could you ACK that it's really not
2329
         * supposed to be done?                                 -- AV
2330
         */
2331
        if (!c || !(new_fops = fops_get(c->fops)))
2332
                return err;
2333
        old_fops = file->f_op;
2334
        file->f_op = new_fops;
2335
        /* Curiouser and curiouser... NULL ->open() as "no device" ? */
2336
        if (file->f_op->open)
2337
                err = file->f_op->open(inode,file);
2338
        if (err) {
2339
                fops_put(file->f_op);
2340
                file->f_op = fops_get(old_fops);
2341
        }
2342
        fops_put(old_fops);
2343
        return err;
2344
}
2345
 
2346
static struct file_operations usb_fops = {
2347
        owner:          THIS_MODULE,
2348
        open:           usb_open,
2349
};
2350
 
2351
int usb_major_init(void)
2352
{
2353
        if (devfs_register_chrdev(USB_MAJOR, "usb", &usb_fops)) {
2354
                err("unable to get major %d for usb devices", USB_MAJOR);
2355
                return -EBUSY;
2356
        }
2357
 
2358
        usb_devfs_handle = devfs_mk_dir(NULL, "usb", NULL);
2359
 
2360
        return 0;
2361
}
2362
 
2363
void usb_major_cleanup(void)
2364
{
2365
        devfs_unregister(usb_devfs_handle);
2366
        devfs_unregister_chrdev(USB_MAJOR, "usb");
2367
}
2368
 
2369
 
2370
#ifdef CONFIG_PROC_FS
2371
struct list_head *usb_driver_get_list(void)
2372
{
2373
        return &usb_driver_list;
2374
}
2375
 
2376
struct list_head *usb_bus_get_list(void)
2377
{
2378
        return &usb_bus_list;
2379
}
2380
#endif
2381
 
2382
 
2383
/*
2384
 * Init
2385
 */
2386
static int __init usb_init(void)
2387
{
2388
        init_MUTEX(&usb_bus_list_lock);
2389
        usb_major_init();
2390
        usbdevfs_init();
2391
        usb_hub_init();
2392
 
2393
        return 0;
2394
}
2395
 
2396
/*
2397
 * Cleanup
2398
 */
2399
static void __exit usb_exit(void)
2400
{
2401
        usb_major_cleanup();
2402
        usbdevfs_cleanup();
2403
        usb_hub_cleanup();
2404
}
2405
 
2406
module_init(usb_init);
2407
module_exit(usb_exit);
2408
 
2409
/*
2410
 * USB may be built into the kernel or be built as modules.
2411
 * If the USB core [and maybe a host controller driver] is built
2412
 * into the kernel, and other device drivers are built as modules,
2413
 * then these symbols need to be exported for the modules to use.
2414
 */
2415
EXPORT_SYMBOL(usb_ifnum_to_ifpos);
2416
EXPORT_SYMBOL(usb_ifnum_to_if);
2417
EXPORT_SYMBOL(usb_epnum_to_ep_desc);
2418
 
2419
EXPORT_SYMBOL(usb_register);
2420
EXPORT_SYMBOL(usb_deregister);
2421
EXPORT_SYMBOL(usb_scan_devices);
2422
EXPORT_SYMBOL(usb_alloc_bus);
2423
EXPORT_SYMBOL(usb_free_bus);
2424
EXPORT_SYMBOL(usb_register_bus);
2425
EXPORT_SYMBOL(usb_deregister_bus);
2426
EXPORT_SYMBOL(usb_alloc_dev);
2427
EXPORT_SYMBOL(usb_free_dev);
2428
EXPORT_SYMBOL(usb_inc_dev_use);
2429
 
2430
EXPORT_SYMBOL(usb_find_interface_driver_for_ifnum);
2431
EXPORT_SYMBOL(usb_driver_claim_interface);
2432
EXPORT_SYMBOL(usb_interface_claimed);
2433
EXPORT_SYMBOL(usb_driver_release_interface);
2434
EXPORT_SYMBOL(usb_match_id);
2435
 
2436
EXPORT_SYMBOL(usb_root_hub_string);
2437
EXPORT_SYMBOL(usb_new_device);
2438
EXPORT_SYMBOL(usb_reset_device);
2439
EXPORT_SYMBOL(usb_connect);
2440
EXPORT_SYMBOL(usb_disconnect);
2441
 
2442
EXPORT_SYMBOL(usb_calc_bus_time);
2443
EXPORT_SYMBOL(usb_check_bandwidth);
2444
EXPORT_SYMBOL(usb_claim_bandwidth);
2445
EXPORT_SYMBOL(usb_release_bandwidth);
2446
 
2447
EXPORT_SYMBOL(usb_set_address);
2448
EXPORT_SYMBOL(usb_get_descriptor);
2449
EXPORT_SYMBOL(usb_get_class_descriptor);
2450
EXPORT_SYMBOL(__usb_get_extra_descriptor);
2451
EXPORT_SYMBOL(usb_get_device_descriptor);
2452
EXPORT_SYMBOL(usb_get_string);
2453
EXPORT_SYMBOL(usb_string);
2454
EXPORT_SYMBOL(usb_get_protocol);
2455
EXPORT_SYMBOL(usb_set_protocol);
2456
EXPORT_SYMBOL(usb_get_report);
2457
EXPORT_SYMBOL(usb_set_report);
2458
EXPORT_SYMBOL(usb_set_idle);
2459
EXPORT_SYMBOL(usb_clear_halt);
2460
EXPORT_SYMBOL(usb_set_interface);
2461
EXPORT_SYMBOL(usb_get_configuration);
2462
EXPORT_SYMBOL(usb_set_configuration);
2463
EXPORT_SYMBOL(usb_get_status);
2464
 
2465
EXPORT_SYMBOL(usb_get_current_frame_number);
2466
 
2467
EXPORT_SYMBOL(usb_alloc_urb);
2468
EXPORT_SYMBOL(usb_free_urb);
2469
EXPORT_SYMBOL(usb_submit_urb);
2470
EXPORT_SYMBOL(usb_unlink_urb);
2471
 
2472
EXPORT_SYMBOL(usb_control_msg);
2473
EXPORT_SYMBOL(usb_bulk_msg);
2474
 
2475
EXPORT_SYMBOL(usb_devfs_handle);
2476
MODULE_LICENSE("GPL");

powered by: WebSVN 2.1.0

© copyright 1999-2024 OpenCores.org, equivalent to Oliscience, all rights reserved. OpenCores®, registered trademark.