Statistics
| Branch: | Revision:

root / usb-linux.c @ d4c4e6fd

History | View | Annotate | Download (41.9 kB)

1
/*
2
 * Linux host USB redirector
3
 *
4
 * Copyright (c) 2005 Fabrice Bellard
5
 *
6
 * Copyright (c) 2008 Max Krasnyansky
7
 *      Support for host device auto connect & disconnect
8
 *      Major rewrite to support fully async operation
9
 *
10
 * Copyright 2008 TJ <linux@tjworld.net>
11
 *      Added flexible support for /dev/bus/usb /sys/bus/usb/devices in addition
12
 *      to the legacy /proc/bus/usb USB device discovery and handling
13
 *
14
 * Permission is hereby granted, free of charge, to any person obtaining a copy
15
 * of this software and associated documentation files (the "Software"), to deal
16
 * in the Software without restriction, including without limitation the rights
17
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
18
 * copies of the Software, and to permit persons to whom the Software is
19
 * furnished to do so, subject to the following conditions:
20
 *
21
 * The above copyright notice and this permission notice shall be included in
22
 * all copies or substantial portions of the Software.
23
 *
24
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
25
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
26
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
27
 * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
28
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
29
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
30
 * THE SOFTWARE.
31
 */
32

    
33
#include "qemu-common.h"
34
#include "qemu-timer.h"
35
#include "monitor.h"
36

    
37
#include <dirent.h>
38
#include <sys/ioctl.h>
39
#include <signal.h>
40

    
41
#include <linux/usbdevice_fs.h>
42
#include <linux/version.h>
43
#include "hw/usb.h"
44

    
45
/* We redefine it to avoid version problems */
46
struct usb_ctrltransfer {
47
    uint8_t  bRequestType;
48
    uint8_t  bRequest;
49
    uint16_t wValue;
50
    uint16_t wIndex;
51
    uint16_t wLength;
52
    uint32_t timeout;
53
    void *data;
54
};
55

    
56
struct usb_ctrlrequest {
57
    uint8_t bRequestType;
58
    uint8_t bRequest;
59
    uint16_t wValue;
60
    uint16_t wIndex;
61
    uint16_t wLength;
62
};
63

    
64
typedef int USBScanFunc(void *opaque, int bus_num, int addr, int class_id,
65
                        int vendor_id, int product_id,
66
                        const char *product_name, int speed);
67

    
68
//#define DEBUG
69

    
70
#ifdef DEBUG
71
#define DPRINTF printf
72
#else
73
#define DPRINTF(...)
74
#endif
75

    
76
#define USBDBG_DEVOPENED "husb: opened %s/devices\n"
77

    
78
#define USBPROCBUS_PATH "/proc/bus/usb"
79
#define PRODUCT_NAME_SZ 32
80
#define MAX_ENDPOINTS 16
81
#define USBDEVBUS_PATH "/dev/bus/usb"
82
#define USBSYSBUS_PATH "/sys/bus/usb"
83

    
84
static char *usb_host_device_path;
85

    
86
#define USB_FS_NONE 0
87
#define USB_FS_PROC 1
88
#define USB_FS_DEV 2
89
#define USB_FS_SYS 3
90

    
91
static int usb_fs_type;
92

    
93
/* endpoint association data */
94
struct endp_data {
95
    uint8_t type;
96
    uint8_t halted;
97
};
98

    
99
enum {
100
    CTRL_STATE_IDLE = 0,
101
    CTRL_STATE_SETUP,
102
    CTRL_STATE_DATA,
103
    CTRL_STATE_ACK
104
};
105

    
106
/*
107
 * Control transfer state.
108
 * Note that 'buffer' _must_ follow 'req' field because 
109
 * we need contigious buffer when we submit control URB.
110
 */ 
111
struct ctrl_struct {
112
    uint16_t len;
113
    uint16_t offset;
114
    uint8_t  state;
115
    struct   usb_ctrlrequest req;
116
    uint8_t  buffer[8192];
117
};
118

    
119
struct USBAutoFilter {
120
    uint32_t bus_num;
121
    uint32_t addr;
122
    uint32_t vendor_id;
123
    uint32_t product_id;
124
};
125

    
126
typedef struct USBHostDevice {
127
    USBDevice dev;
128
    int       fd;
129

    
130
    uint8_t   descr[1024];
131
    int       descr_len;
132
    int       configuration;
133
    int       ninterfaces;
134
    int       closing;
135

    
136
    struct ctrl_struct ctrl;
137
    struct endp_data endp_table[MAX_ENDPOINTS];
138

    
139
    /* Host side address */
140
    int bus_num;
141
    int addr;
142
    struct USBAutoFilter match;
143

    
144
    QTAILQ_ENTRY(USBHostDevice) next;
145
} USBHostDevice;
146

    
147
static QTAILQ_HEAD(, USBHostDevice) hostdevs = QTAILQ_HEAD_INITIALIZER(hostdevs);
148

    
149
static int usb_host_close(USBHostDevice *dev);
150
static int parse_filter(const char *spec, struct USBAutoFilter *f);
151
static void usb_host_auto_check(void *unused);
152

    
153
static int is_isoc(USBHostDevice *s, int ep)
154
{
155
    return s->endp_table[ep - 1].type == USBDEVFS_URB_TYPE_ISO;
156
}
157

    
158
static int is_halted(USBHostDevice *s, int ep)
159
{
160
    return s->endp_table[ep - 1].halted;
161
}
162

    
163
static void clear_halt(USBHostDevice *s, int ep)
164
{
165
    s->endp_table[ep - 1].halted = 0;
166
}
167

    
168
static void set_halt(USBHostDevice *s, int ep)
169
{
170
    s->endp_table[ep - 1].halted = 1;
171
}
172

    
173
/* 
174
 * Async URB state.
175
 * We always allocate one isoc descriptor even for bulk transfers
176
 * to simplify allocation and casts. 
177
 */
178
typedef struct AsyncURB
179
{
180
    struct usbdevfs_urb urb;
181
    struct usbdevfs_iso_packet_desc isocpd;
182

    
183
    USBPacket     *packet;
184
    USBHostDevice *hdev;
185
} AsyncURB;
186

    
187
static AsyncURB *async_alloc(void)
188
{
189
    return (AsyncURB *) qemu_mallocz(sizeof(AsyncURB));
190
}
191

    
192
static void async_free(AsyncURB *aurb)
193
{
194
    qemu_free(aurb);
195
}
196

    
197
static void async_complete_ctrl(USBHostDevice *s, USBPacket *p)
198
{
199
    switch(s->ctrl.state) {
200
    case CTRL_STATE_SETUP:
201
        if (p->len < s->ctrl.len)
202
            s->ctrl.len = p->len;
203
        s->ctrl.state = CTRL_STATE_DATA;
204
        p->len = 8;
205
        break;
206

    
207
    case CTRL_STATE_ACK:
208
        s->ctrl.state = CTRL_STATE_IDLE;
209
        p->len = 0;
210
        break;
211

    
212
    default:
213
        break;
214
    }
215
}
216

    
217
static void async_complete(void *opaque)
218
{
219
    USBHostDevice *s = opaque;
220
    AsyncURB *aurb;
221

    
222
    while (1) {
223
            USBPacket *p;
224

    
225
        int r = ioctl(s->fd, USBDEVFS_REAPURBNDELAY, &aurb);
226
        if (r < 0) {
227
            if (errno == EAGAIN)
228
                return;
229

    
230
            if (errno == ENODEV && !s->closing) {
231
                printf("husb: device %d.%d disconnected\n", s->bus_num, s->addr);
232
                usb_host_close(s);
233
                usb_host_auto_check(NULL);
234
                return;
235
            }
236

    
237
            DPRINTF("husb: async. reap urb failed errno %d\n", errno);
238
            return;
239
        }
240

    
241
        p = aurb->packet;
242

    
243
        DPRINTF("husb: async completed. aurb %p status %d alen %d\n", 
244
                aurb, aurb->urb.status, aurb->urb.actual_length);
245

    
246
        if (p) {
247
            switch (aurb->urb.status) {
248
            case 0:
249
                p->len = aurb->urb.actual_length;
250
                if (aurb->urb.type == USBDEVFS_URB_TYPE_CONTROL)
251
                    async_complete_ctrl(s, p);
252
                break;
253

    
254
            case -EPIPE:
255
                set_halt(s, p->devep);
256
                p->len = USB_RET_STALL;
257
                break;
258

    
259
            default:
260
                p->len = USB_RET_NAK;
261
                break;
262
            }
263

    
264
            usb_packet_complete(p);
265
        }
266

    
267
        async_free(aurb);
268
    }
269
}
270

    
271
static void async_cancel(USBPacket *unused, void *opaque)
272
{
273
    AsyncURB *aurb = opaque;
274
    USBHostDevice *s = aurb->hdev;
275

    
276
    DPRINTF("husb: async cancel. aurb %p\n", aurb);
277

    
278
    /* Mark it as dead (see async_complete above) */
279
    aurb->packet = NULL;
280

    
281
    int r = ioctl(s->fd, USBDEVFS_DISCARDURB, aurb);
282
    if (r < 0) {
283
        DPRINTF("husb: async. discard urb failed errno %d\n", errno);
284
    }
285
}
286

    
287
static int usb_host_claim_interfaces(USBHostDevice *dev, int configuration)
288
{
289
    int dev_descr_len, config_descr_len;
290
    int interface, nb_interfaces;
291
    int ret, i;
292

    
293
    if (configuration == 0) /* address state - ignore */
294
        return 1;
295

    
296
    DPRINTF("husb: claiming interfaces. config %d\n", configuration);
297

    
298
    i = 0;
299
    dev_descr_len = dev->descr[0];
300
    if (dev_descr_len > dev->descr_len)
301
        goto fail;
302

    
303
    i += dev_descr_len;
304
    while (i < dev->descr_len) {
305
        DPRINTF("husb: i is %d, descr_len is %d, dl %d, dt %d\n", i, dev->descr_len,
306
               dev->descr[i], dev->descr[i+1]);
307

    
308
        if (dev->descr[i+1] != USB_DT_CONFIG) {
309
            i += dev->descr[i];
310
            continue;
311
        }
312
        config_descr_len = dev->descr[i];
313

    
314
        printf("husb: config #%d need %d\n", dev->descr[i + 5], configuration); 
315

    
316
        if (configuration < 0 || configuration == dev->descr[i + 5]) {
317
            configuration = dev->descr[i + 5];
318
            break;
319
        }
320

    
321
        i += config_descr_len;
322
    }
323

    
324
    if (i >= dev->descr_len) {
325
        fprintf(stderr, "husb: update iface failed. no matching configuration\n");
326
        goto fail;
327
    }
328
    nb_interfaces = dev->descr[i + 4];
329

    
330
#ifdef USBDEVFS_DISCONNECT
331
    /* earlier Linux 2.4 do not support that */
332
    {
333
        struct usbdevfs_ioctl ctrl;
334
        for (interface = 0; interface < nb_interfaces; interface++) {
335
            ctrl.ioctl_code = USBDEVFS_DISCONNECT;
336
            ctrl.ifno = interface;
337
            ret = ioctl(dev->fd, USBDEVFS_IOCTL, &ctrl);
338
            if (ret < 0 && errno != ENODATA) {
339
                perror("USBDEVFS_DISCONNECT");
340
                goto fail;
341
            }
342
        }
343
    }
344
#endif
345

    
346
    /* XXX: only grab if all interfaces are free */
347
    for (interface = 0; interface < nb_interfaces; interface++) {
348
        ret = ioctl(dev->fd, USBDEVFS_CLAIMINTERFACE, &interface);
349
        if (ret < 0) {
350
            if (errno == EBUSY) {
351
                printf("husb: update iface. device already grabbed\n");
352
            } else {
353
                perror("husb: failed to claim interface");
354
            }
355
        fail:
356
            return 0;
357
        }
358
    }
359

    
360
    printf("husb: %d interfaces claimed for configuration %d\n",
361
           nb_interfaces, configuration);
362

    
363
    dev->ninterfaces   = nb_interfaces;
364
    dev->configuration = configuration;
365
    return 1;
366
}
367

    
368
static int usb_host_release_interfaces(USBHostDevice *s)
369
{
370
    int ret, i;
371

    
372
    DPRINTF("husb: releasing interfaces\n");
373

    
374
    for (i = 0; i < s->ninterfaces; i++) {
375
        ret = ioctl(s->fd, USBDEVFS_RELEASEINTERFACE, &i);
376
        if (ret < 0) {
377
            perror("husb: failed to release interface");
378
            return 0;
379
        }
380
    }
381

    
382
    return 1;
383
}
384

    
385
static void usb_host_handle_reset(USBDevice *dev)
386
{
387
    USBHostDevice *s = DO_UPCAST(USBHostDevice, dev, dev);
388

    
389
    DPRINTF("husb: reset device %u.%u\n", s->bus_num, s->addr);
390

    
391
    ioctl(s->fd, USBDEVFS_RESET);
392

    
393
    usb_host_claim_interfaces(s, s->configuration);
394
}
395

    
396
static void usb_host_handle_destroy(USBDevice *dev)
397
{
398
    USBHostDevice *s = (USBHostDevice *)dev;
399

    
400
    usb_host_close(s);
401
    QTAILQ_REMOVE(&hostdevs, s, next);
402
}
403

    
404
static int usb_linux_update_endp_table(USBHostDevice *s);
405

    
406
static int usb_host_handle_data(USBHostDevice *s, USBPacket *p)
407
{
408
    struct usbdevfs_urb *urb;
409
    AsyncURB *aurb;
410
    int ret;
411

    
412
    aurb = async_alloc();
413
    aurb->hdev   = s;
414
    aurb->packet = p;
415

    
416
    urb = &aurb->urb;
417

    
418
    if (p->pid == USB_TOKEN_IN)
419
            urb->endpoint = p->devep | 0x80;
420
    else
421
            urb->endpoint = p->devep;
422

    
423
    if (is_halted(s, p->devep)) {
424
        ret = ioctl(s->fd, USBDEVFS_CLEAR_HALT, &urb->endpoint);
425
        if (ret < 0) {
426
            DPRINTF("husb: failed to clear halt. ep 0x%x errno %d\n", 
427
                   urb->endpoint, errno);
428
            return USB_RET_NAK;
429
        }
430
        clear_halt(s, p->devep);
431
    }
432

    
433
    urb->buffer        = p->data;
434
    urb->buffer_length = p->len;
435

    
436
    if (is_isoc(s, p->devep)) {
437
        /* Setup ISOC transfer */
438
        urb->type     = USBDEVFS_URB_TYPE_ISO;
439
        urb->flags    = USBDEVFS_URB_ISO_ASAP;
440
        urb->number_of_packets = 1;
441
        urb->iso_frame_desc[0].length = p->len;
442
    } else {
443
        /* Setup bulk transfer */
444
        urb->type     = USBDEVFS_URB_TYPE_BULK;
445
    }
446

    
447
    urb->usercontext = s;
448

    
449
    ret = ioctl(s->fd, USBDEVFS_SUBMITURB, urb);
450

    
451
    DPRINTF("husb: data submit. ep 0x%x len %u aurb %p\n", urb->endpoint, p->len, aurb);
452

    
453
    if (ret < 0) {
454
        DPRINTF("husb: submit failed. errno %d\n", errno);
455
        async_free(aurb);
456

    
457
        switch(errno) {
458
        case ETIMEDOUT:
459
            return USB_RET_NAK;
460
        case EPIPE:
461
        default:
462
            return USB_RET_STALL;
463
        }
464
    }
465

    
466
    usb_defer_packet(p, async_cancel, aurb);
467
    return USB_RET_ASYNC;
468
}
469

    
470
static int ctrl_error(void)
471
{
472
    if (errno == ETIMEDOUT)
473
        return USB_RET_NAK;
474
    else 
475
        return USB_RET_STALL;
476
}
477

    
478
static int usb_host_set_address(USBHostDevice *s, int addr)
479
{
480
    DPRINTF("husb: ctrl set addr %u\n", addr);
481
    s->dev.addr = addr;
482
    return 0;
483
}
484

    
485
static int usb_host_set_config(USBHostDevice *s, int config)
486
{
487
    usb_host_release_interfaces(s);
488

    
489
    int ret = ioctl(s->fd, USBDEVFS_SETCONFIGURATION, &config);
490
 
491
    DPRINTF("husb: ctrl set config %d ret %d errno %d\n", config, ret, errno);
492
    
493
    if (ret < 0)
494
        return ctrl_error();
495
 
496
    usb_host_claim_interfaces(s, config);
497
    return 0;
498
}
499

    
500
static int usb_host_set_interface(USBHostDevice *s, int iface, int alt)
501
{
502
    struct usbdevfs_setinterface si;
503
    int ret;
504

    
505
    si.interface  = iface;
506
    si.altsetting = alt;
507
    ret = ioctl(s->fd, USBDEVFS_SETINTERFACE, &si);
508
    
509
    DPRINTF("husb: ctrl set iface %d altset %d ret %d errno %d\n", 
510
            iface, alt, ret, errno);
511
    
512
    if (ret < 0)
513
        return ctrl_error();
514

    
515
    usb_linux_update_endp_table(s);
516
    return 0;
517
}
518

    
519
static int usb_host_handle_control(USBHostDevice *s, USBPacket *p)
520
{
521
    struct usbdevfs_urb *urb;
522
    AsyncURB *aurb;
523
    int ret, value, index;
524
    int buffer_len;
525

    
526
    /* 
527
     * Process certain standard device requests.
528
     * These are infrequent and are processed synchronously.
529
     */
530
    value = le16_to_cpu(s->ctrl.req.wValue);
531
    index = le16_to_cpu(s->ctrl.req.wIndex);
532

    
533
    DPRINTF("husb: ctrl type 0x%x req 0x%x val 0x%x index %u len %u\n",
534
        s->ctrl.req.bRequestType, s->ctrl.req.bRequest, value, index, 
535
        s->ctrl.len);
536

    
537
    if (s->ctrl.req.bRequestType == 0) {
538
        switch (s->ctrl.req.bRequest) {
539
        case USB_REQ_SET_ADDRESS:
540
            return usb_host_set_address(s, value);
541

    
542
        case USB_REQ_SET_CONFIGURATION:
543
            return usb_host_set_config(s, value & 0xff);
544
        }
545
    }
546

    
547
    if (s->ctrl.req.bRequestType == 1 &&
548
                  s->ctrl.req.bRequest == USB_REQ_SET_INTERFACE)
549
        return usb_host_set_interface(s, index, value);
550

    
551
    /* The rest are asynchronous */
552

    
553
    buffer_len = 8 + s->ctrl.len;
554
    if (buffer_len > sizeof(s->ctrl.buffer)) {
555
        fprintf(stderr, "husb: ctrl buffer too small (%u > %zu)\n",
556
                buffer_len, sizeof(s->ctrl.buffer));
557
        return USB_RET_STALL;
558
    }
559

    
560
    aurb = async_alloc();
561
    aurb->hdev   = s;
562
    aurb->packet = p;
563

    
564
    /* 
565
     * Setup ctrl transfer.
566
     *
567
     * s->ctrl is layed out such that data buffer immediately follows
568
     * 'req' struct which is exactly what usbdevfs expects.
569
     */ 
570
    urb = &aurb->urb;
571

    
572
    urb->type     = USBDEVFS_URB_TYPE_CONTROL;
573
    urb->endpoint = p->devep;
574

    
575
    urb->buffer        = &s->ctrl.req;
576
    urb->buffer_length = buffer_len;
577

    
578
    urb->usercontext = s;
579

    
580
    ret = ioctl(s->fd, USBDEVFS_SUBMITURB, urb);
581

    
582
    DPRINTF("husb: submit ctrl. len %u aurb %p\n", urb->buffer_length, aurb);
583

    
584
    if (ret < 0) {
585
        DPRINTF("husb: submit failed. errno %d\n", errno);
586
        async_free(aurb);
587

    
588
        switch(errno) {
589
        case ETIMEDOUT:
590
            return USB_RET_NAK;
591
        case EPIPE:
592
        default:
593
            return USB_RET_STALL;
594
        }
595
    }
596

    
597
    usb_defer_packet(p, async_cancel, aurb);
598
    return USB_RET_ASYNC;
599
}
600

    
601
static int do_token_setup(USBDevice *dev, USBPacket *p)
602
{
603
    USBHostDevice *s = (USBHostDevice *) dev;
604
    int ret = 0;
605

    
606
    if (p->len != 8)
607
        return USB_RET_STALL;
608
 
609
    memcpy(&s->ctrl.req, p->data, 8);
610
    s->ctrl.len    = le16_to_cpu(s->ctrl.req.wLength);
611
    s->ctrl.offset = 0;
612
    s->ctrl.state  = CTRL_STATE_SETUP;
613

    
614
    if (s->ctrl.req.bRequestType & USB_DIR_IN) {
615
        ret = usb_host_handle_control(s, p);
616
        if (ret < 0)
617
            return ret;
618

    
619
        if (ret < s->ctrl.len)
620
            s->ctrl.len = ret;
621
        s->ctrl.state = CTRL_STATE_DATA;
622
    } else {
623
        if (s->ctrl.len == 0)
624
            s->ctrl.state = CTRL_STATE_ACK;
625
        else
626
            s->ctrl.state = CTRL_STATE_DATA;
627
    }
628

    
629
    return ret;
630
}
631

    
632
static int do_token_in(USBDevice *dev, USBPacket *p)
633
{
634
    USBHostDevice *s = (USBHostDevice *) dev;
635
    int ret = 0;
636

    
637
    if (p->devep != 0)
638
        return usb_host_handle_data(s, p);
639

    
640
    switch(s->ctrl.state) {
641
    case CTRL_STATE_ACK:
642
        if (!(s->ctrl.req.bRequestType & USB_DIR_IN)) {
643
            ret = usb_host_handle_control(s, p);
644
            if (ret == USB_RET_ASYNC)
645
                return USB_RET_ASYNC;
646

    
647
            s->ctrl.state = CTRL_STATE_IDLE;
648
            return ret > 0 ? 0 : ret;
649
        }
650

    
651
        return 0;
652

    
653
    case CTRL_STATE_DATA:
654
        if (s->ctrl.req.bRequestType & USB_DIR_IN) {
655
            int len = s->ctrl.len - s->ctrl.offset;
656
            if (len > p->len)
657
                len = p->len;
658
            memcpy(p->data, s->ctrl.buffer + s->ctrl.offset, len);
659
            s->ctrl.offset += len;
660
            if (s->ctrl.offset >= s->ctrl.len)
661
                s->ctrl.state = CTRL_STATE_ACK;
662
            return len;
663
        }
664

    
665
        s->ctrl.state = CTRL_STATE_IDLE;
666
        return USB_RET_STALL;
667

    
668
    default:
669
        return USB_RET_STALL;
670
    }
671
}
672

    
673
static int do_token_out(USBDevice *dev, USBPacket *p)
674
{
675
    USBHostDevice *s = (USBHostDevice *) dev;
676

    
677
    if (p->devep != 0)
678
        return usb_host_handle_data(s, p);
679

    
680
    switch(s->ctrl.state) {
681
    case CTRL_STATE_ACK:
682
        if (s->ctrl.req.bRequestType & USB_DIR_IN) {
683
            s->ctrl.state = CTRL_STATE_IDLE;
684
            /* transfer OK */
685
        } else {
686
            /* ignore additional output */
687
        }
688
        return 0;
689

    
690
    case CTRL_STATE_DATA:
691
        if (!(s->ctrl.req.bRequestType & USB_DIR_IN)) {
692
            int len = s->ctrl.len - s->ctrl.offset;
693
            if (len > p->len)
694
                len = p->len;
695
            memcpy(s->ctrl.buffer + s->ctrl.offset, p->data, len);
696
            s->ctrl.offset += len;
697
            if (s->ctrl.offset >= s->ctrl.len)
698
                s->ctrl.state = CTRL_STATE_ACK;
699
            return len;
700
        }
701

    
702
        s->ctrl.state = CTRL_STATE_IDLE;
703
        return USB_RET_STALL;
704

    
705
    default:
706
        return USB_RET_STALL;
707
    }
708
}
709

    
710
/*
711
 * Packet handler.
712
 * Called by the HC (host controller).
713
 *
714
 * Returns length of the transaction or one of the USB_RET_XXX codes.
715
 */
716
static int usb_host_handle_packet(USBDevice *s, USBPacket *p)
717
{
718
    switch(p->pid) {
719
    case USB_MSG_ATTACH:
720
        s->state = USB_STATE_ATTACHED;
721
        return 0;
722

    
723
    case USB_MSG_DETACH:
724
        s->state = USB_STATE_NOTATTACHED;
725
        return 0;
726

    
727
    case USB_MSG_RESET:
728
        s->remote_wakeup = 0;
729
        s->addr = 0;
730
        s->state = USB_STATE_DEFAULT;
731
        s->info->handle_reset(s);
732
        return 0;
733
    }
734

    
735
    /* Rest of the PIDs must match our address */
736
    if (s->state < USB_STATE_DEFAULT || p->devaddr != s->addr)
737
        return USB_RET_NODEV;
738

    
739
    switch (p->pid) {
740
    case USB_TOKEN_SETUP:
741
        return do_token_setup(s, p);
742

    
743
    case USB_TOKEN_IN:
744
        return do_token_in(s, p);
745

    
746
    case USB_TOKEN_OUT:
747
        return do_token_out(s, p);
748
 
749
    default:
750
        return USB_RET_STALL;
751
    }
752
}
753

    
754
/* returns 1 on problem encountered or 0 for success */
755
static int usb_linux_update_endp_table(USBHostDevice *s)
756
{
757
    uint8_t *descriptors;
758
    uint8_t devep, type, configuration, alt_interface;
759
    struct usb_ctrltransfer ct;
760
    int interface, ret, length, i;
761

    
762
    ct.bRequestType = USB_DIR_IN;
763
    ct.bRequest = USB_REQ_GET_CONFIGURATION;
764
    ct.wValue = 0;
765
    ct.wIndex = 0;
766
    ct.wLength = 1;
767
    ct.data = &configuration;
768
    ct.timeout = 50;
769

    
770
    ret = ioctl(s->fd, USBDEVFS_CONTROL, &ct);
771
    if (ret < 0) {
772
        perror("usb_linux_update_endp_table");
773
        return 1;
774
    }
775

    
776
    /* in address state */
777
    if (configuration == 0)
778
        return 1;
779

    
780
    /* get the desired configuration, interface, and endpoint descriptors
781
     * from device description */
782
    descriptors = &s->descr[18];
783
    length = s->descr_len - 18;
784
    i = 0;
785

    
786
    if (descriptors[i + 1] != USB_DT_CONFIG ||
787
        descriptors[i + 5] != configuration) {
788
        DPRINTF("invalid descriptor data - configuration\n");
789
        return 1;
790
    }
791
    i += descriptors[i];
792

    
793
    while (i < length) {
794
        if (descriptors[i + 1] != USB_DT_INTERFACE ||
795
            (descriptors[i + 1] == USB_DT_INTERFACE &&
796
             descriptors[i + 4] == 0)) {
797
            i += descriptors[i];
798
            continue;
799
        }
800

    
801
        interface = descriptors[i + 2];
802

    
803
        ct.bRequestType = USB_DIR_IN | USB_RECIP_INTERFACE;
804
        ct.bRequest = USB_REQ_GET_INTERFACE;
805
        ct.wValue = 0;
806
        ct.wIndex = interface;
807
        ct.wLength = 1;
808
        ct.data = &alt_interface;
809
        ct.timeout = 50;
810

    
811
        ret = ioctl(s->fd, USBDEVFS_CONTROL, &ct);
812
        if (ret < 0) {
813
            alt_interface = interface;
814
        }
815

    
816
        /* the current interface descriptor is the active interface
817
         * and has endpoints */
818
        if (descriptors[i + 3] != alt_interface) {
819
            i += descriptors[i];
820
            continue;
821
        }
822

    
823
        /* advance to the endpoints */
824
        while (i < length && descriptors[i +1] != USB_DT_ENDPOINT)
825
            i += descriptors[i];
826

    
827
        if (i >= length)
828
            break;
829

    
830
        while (i < length) {
831
            if (descriptors[i + 1] != USB_DT_ENDPOINT)
832
                break;
833

    
834
            devep = descriptors[i + 2];
835
            switch (descriptors[i + 3] & 0x3) {
836
            case 0x00:
837
                type = USBDEVFS_URB_TYPE_CONTROL;
838
                break;
839
            case 0x01:
840
                type = USBDEVFS_URB_TYPE_ISO;
841
                break;
842
            case 0x02:
843
                type = USBDEVFS_URB_TYPE_BULK;
844
                break;
845
            case 0x03:
846
                type = USBDEVFS_URB_TYPE_INTERRUPT;
847
                break;
848
            default:
849
                DPRINTF("usb_host: malformed endpoint type\n");
850
                type = USBDEVFS_URB_TYPE_BULK;
851
            }
852
            s->endp_table[(devep & 0xf) - 1].type = type;
853
            s->endp_table[(devep & 0xf) - 1].halted = 0;
854

    
855
            i += descriptors[i];
856
        }
857
    }
858
    return 0;
859
}
860

    
861
static int usb_host_open(USBHostDevice *dev, int bus_num,
862
                         int addr, const char *prod_name)
863
{
864
    int fd = -1, ret;
865
    struct usbdevfs_connectinfo ci;
866
    char buf[1024];
867

    
868
    if (dev->fd != -1)
869
        goto fail;
870

    
871
    printf("husb: open device %d.%d\n", bus_num, addr);
872

    
873
    if (!usb_host_device_path) {
874
        perror("husb: USB Host Device Path not set");
875
        goto fail;
876
    }
877
    snprintf(buf, sizeof(buf), "%s/%03d/%03d", usb_host_device_path,
878
             bus_num, addr);
879
    fd = open(buf, O_RDWR | O_NONBLOCK);
880
    if (fd < 0) {
881
        perror(buf);
882
        goto fail;
883
    }
884
    DPRINTF("husb: opened %s\n", buf);
885

    
886
    dev->bus_num = bus_num;
887
    dev->addr = addr;
888
    dev->fd = fd;
889

    
890
    /* read the device description */
891
    dev->descr_len = read(fd, dev->descr, sizeof(dev->descr));
892
    if (dev->descr_len <= 0) {
893
        perror("husb: reading device data failed");
894
        goto fail;
895
    }
896

    
897
#ifdef DEBUG
898
    {
899
        int x;
900
        printf("=== begin dumping device descriptor data ===\n");
901
        for (x = 0; x < dev->descr_len; x++)
902
            printf("%02x ", dev->descr[x]);
903
        printf("\n=== end dumping device descriptor data ===\n");
904
    }
905
#endif
906

    
907

    
908
    /* 
909
     * Initial configuration is -1 which makes us claim first 
910
     * available config. We used to start with 1, which does not
911
     * always work. I've seen devices where first config starts 
912
     * with 2.
913
     */
914
    if (!usb_host_claim_interfaces(dev, -1))
915
        goto fail;
916

    
917
    ret = ioctl(fd, USBDEVFS_CONNECTINFO, &ci);
918
    if (ret < 0) {
919
        perror("usb_host_device_open: USBDEVFS_CONNECTINFO");
920
        goto fail;
921
    }
922

    
923
    printf("husb: grabbed usb device %d.%d\n", bus_num, addr);
924

    
925
    ret = usb_linux_update_endp_table(dev);
926
    if (ret)
927
        goto fail;
928

    
929
    if (ci.slow)
930
        dev->dev.speed = USB_SPEED_LOW;
931
    else
932
        dev->dev.speed = USB_SPEED_HIGH;
933

    
934
    if (!prod_name || prod_name[0] == '\0')
935
        snprintf(dev->dev.product_desc, sizeof(dev->dev.product_desc),
936
                 "host:%d.%d", bus_num, addr);
937
    else
938
        pstrcpy(dev->dev.product_desc, sizeof(dev->dev.product_desc),
939
                prod_name);
940

    
941
    /* USB devio uses 'write' flag to check for async completions */
942
    qemu_set_fd_handler(dev->fd, NULL, async_complete, dev);
943

    
944
    usb_device_attach(&dev->dev);
945
    return 0;
946

    
947
fail:
948
    dev->fd = -1;
949
    if (fd != -1)
950
        close(fd);
951
    return -1;
952
}
953

    
954
static int usb_host_close(USBHostDevice *dev)
955
{
956
    if (dev->fd == -1)
957
        return -1;
958

    
959
    qemu_set_fd_handler(dev->fd, NULL, NULL, NULL);
960
    dev->closing = 1;
961
    async_complete(dev);
962
    dev->closing = 0;
963
    usb_device_detach(&dev->dev);
964
    close(dev->fd);
965
    dev->fd = -1;
966
    return 0;
967
}
968

    
969
static int usb_host_initfn(USBDevice *dev)
970
{
971
    USBHostDevice *s = DO_UPCAST(USBHostDevice, dev, dev);
972

    
973
    dev->auto_attach = 0;
974
    s->fd = -1;
975
    QTAILQ_INSERT_TAIL(&hostdevs, s, next);
976
    usb_host_auto_check(NULL);
977
    return 0;
978
}
979

    
980
static struct USBDeviceInfo usb_host_dev_info = {
981
    .product_desc   = "USB Host Device",
982
    .qdev.name      = "usb-host",
983
    .qdev.size      = sizeof(USBHostDevice),
984
    .init           = usb_host_initfn,
985
    .handle_packet  = usb_host_handle_packet,
986
    .handle_reset   = usb_host_handle_reset,
987
    .handle_destroy = usb_host_handle_destroy,
988
    .usbdevice_name = "host",
989
    .usbdevice_init = usb_host_device_open,
990
    .qdev.props     = (Property[]) {
991
        DEFINE_PROP_UINT32("hostbus",  USBHostDevice, match.bus_num,    0),
992
        DEFINE_PROP_UINT32("hostaddr", USBHostDevice, match.addr,       0),
993
        DEFINE_PROP_HEX32("vendorid",  USBHostDevice, match.vendor_id,  0),
994
        DEFINE_PROP_HEX32("productid", USBHostDevice, match.product_id, 0),
995
        DEFINE_PROP_END_OF_LIST(),
996
    },
997
};
998

    
999
static void usb_host_register_devices(void)
1000
{
1001
    usb_qdev_register(&usb_host_dev_info);
1002
}
1003
device_init(usb_host_register_devices)
1004

    
1005
USBDevice *usb_host_device_open(const char *devname)
1006
{
1007
    struct USBAutoFilter filter;
1008
    USBDevice *dev;
1009
    char *p;
1010

    
1011
    dev = usb_create(NULL /* FIXME */, "usb-host");
1012

    
1013
    if (strstr(devname, "auto:")) {
1014
        if (parse_filter(devname, &filter) < 0)
1015
            goto fail;
1016
    } else {
1017
        if ((p = strchr(devname, '.'))) {
1018
            filter.bus_num    = strtoul(devname, NULL, 0);
1019
            filter.addr       = strtoul(p + 1, NULL, 0);
1020
            filter.vendor_id  = 0;
1021
            filter.product_id = 0;
1022
        } else if ((p = strchr(devname, ':'))) {
1023
            filter.bus_num    = 0;
1024
            filter.addr       = 0;
1025
            filter.vendor_id  = strtoul(devname, NULL, 16);
1026
            filter.product_id = strtoul(p + 1, NULL, 16);
1027
        } else {
1028
            goto fail;
1029
        }
1030
    }
1031

    
1032
    qdev_prop_set_uint32(&dev->qdev, "hostbus",   filter.bus_num);
1033
    qdev_prop_set_uint32(&dev->qdev, "hostaddr",  filter.addr);
1034
    qdev_prop_set_uint32(&dev->qdev, "vendorid",  filter.vendor_id);
1035
    qdev_prop_set_uint32(&dev->qdev, "productid", filter.product_id);
1036
    qdev_init_nofail(&dev->qdev);
1037
    return dev;
1038

    
1039
fail:
1040
    qdev_free(&dev->qdev);
1041
    return NULL;
1042
}
1043

    
1044
int usb_host_device_close(const char *devname)
1045
{
1046
#if 0
1047
    char product_name[PRODUCT_NAME_SZ];
1048
    int bus_num, addr;
1049
    USBHostDevice *s;
1050

1051
    if (strstr(devname, "auto:"))
1052
        return usb_host_auto_del(devname);
1053

1054
    if (usb_host_find_device(&bus_num, &addr, product_name, sizeof(product_name),
1055
                             devname) < 0)
1056
        return -1;
1057

1058
    s = hostdev_find(bus_num, addr);
1059
    if (s) {
1060
        usb_device_delete_addr(s->bus_num, s->dev.addr);
1061
        return 0;
1062
    }
1063
#endif
1064

    
1065
    return -1;
1066
}
1067

    
1068
static int get_tag_value(char *buf, int buf_size,
1069
                         const char *str, const char *tag,
1070
                         const char *stopchars)
1071
{
1072
    const char *p;
1073
    char *q;
1074
    p = strstr(str, tag);
1075
    if (!p)
1076
        return -1;
1077
    p += strlen(tag);
1078
    while (qemu_isspace(*p))
1079
        p++;
1080
    q = buf;
1081
    while (*p != '\0' && !strchr(stopchars, *p)) {
1082
        if ((q - buf) < (buf_size - 1))
1083
            *q++ = *p;
1084
        p++;
1085
    }
1086
    *q = '\0';
1087
    return q - buf;
1088
}
1089

    
1090
/*
1091
 * Use /proc/bus/usb/devices or /dev/bus/usb/devices file to determine
1092
 * host's USB devices. This is legacy support since many distributions
1093
 * are moving to /sys/bus/usb
1094
 */
1095
static int usb_host_scan_dev(void *opaque, USBScanFunc *func)
1096
{
1097
    FILE *f = NULL;
1098
    char line[1024];
1099
    char buf[1024];
1100
    int bus_num, addr, speed, device_count, class_id, product_id, vendor_id;
1101
    char product_name[512];
1102
    int ret = 0;
1103

    
1104
    if (!usb_host_device_path) {
1105
        perror("husb: USB Host Device Path not set");
1106
        goto the_end;
1107
    }
1108
    snprintf(line, sizeof(line), "%s/devices", usb_host_device_path);
1109
    f = fopen(line, "r");
1110
    if (!f) {
1111
        perror("husb: cannot open devices file");
1112
        goto the_end;
1113
    }
1114

    
1115
    device_count = 0;
1116
    bus_num = addr = speed = class_id = product_id = vendor_id = 0;
1117
    for(;;) {
1118
        if (fgets(line, sizeof(line), f) == NULL)
1119
            break;
1120
        if (strlen(line) > 0)
1121
            line[strlen(line) - 1] = '\0';
1122
        if (line[0] == 'T' && line[1] == ':') {
1123
            if (device_count && (vendor_id || product_id)) {
1124
                /* New device.  Add the previously discovered device.  */
1125
                ret = func(opaque, bus_num, addr, class_id, vendor_id,
1126
                           product_id, product_name, speed);
1127
                if (ret)
1128
                    goto the_end;
1129
            }
1130
            if (get_tag_value(buf, sizeof(buf), line, "Bus=", " ") < 0)
1131
                goto fail;
1132
            bus_num = atoi(buf);
1133
            if (get_tag_value(buf, sizeof(buf), line, "Dev#=", " ") < 0)
1134
                goto fail;
1135
            addr = atoi(buf);
1136
            if (get_tag_value(buf, sizeof(buf), line, "Spd=", " ") < 0)
1137
                goto fail;
1138
            if (!strcmp(buf, "480"))
1139
                speed = USB_SPEED_HIGH;
1140
            else if (!strcmp(buf, "1.5"))
1141
                speed = USB_SPEED_LOW;
1142
            else
1143
                speed = USB_SPEED_FULL;
1144
            product_name[0] = '\0';
1145
            class_id = 0xff;
1146
            device_count++;
1147
            product_id = 0;
1148
            vendor_id = 0;
1149
        } else if (line[0] == 'P' && line[1] == ':') {
1150
            if (get_tag_value(buf, sizeof(buf), line, "Vendor=", " ") < 0)
1151
                goto fail;
1152
            vendor_id = strtoul(buf, NULL, 16);
1153
            if (get_tag_value(buf, sizeof(buf), line, "ProdID=", " ") < 0)
1154
                goto fail;
1155
            product_id = strtoul(buf, NULL, 16);
1156
        } else if (line[0] == 'S' && line[1] == ':') {
1157
            if (get_tag_value(buf, sizeof(buf), line, "Product=", "") < 0)
1158
                goto fail;
1159
            pstrcpy(product_name, sizeof(product_name), buf);
1160
        } else if (line[0] == 'D' && line[1] == ':') {
1161
            if (get_tag_value(buf, sizeof(buf), line, "Cls=", " (") < 0)
1162
                goto fail;
1163
            class_id = strtoul(buf, NULL, 16);
1164
        }
1165
    fail: ;
1166
    }
1167
    if (device_count && (vendor_id || product_id)) {
1168
        /* Add the last device.  */
1169
        ret = func(opaque, bus_num, addr, class_id, vendor_id,
1170
                   product_id, product_name, speed);
1171
    }
1172
 the_end:
1173
    if (f)
1174
        fclose(f);
1175
    return ret;
1176
}
1177

    
1178
/*
1179
 * Read sys file-system device file
1180
 *
1181
 * @line address of buffer to put file contents in
1182
 * @line_size size of line
1183
 * @device_file path to device file (printf format string)
1184
 * @device_name device being opened (inserted into device_file)
1185
 *
1186
 * @return 0 failed, 1 succeeded ('line' contains data)
1187
 */
1188
static int usb_host_read_file(char *line, size_t line_size, const char *device_file, const char *device_name)
1189
{
1190
    FILE *f;
1191
    int ret = 0;
1192
    char filename[PATH_MAX];
1193

    
1194
    snprintf(filename, PATH_MAX, USBSYSBUS_PATH "/devices/%s/%s", device_name,
1195
             device_file);
1196
    f = fopen(filename, "r");
1197
    if (f) {
1198
        ret = fgets(line, line_size, f) != NULL;
1199
        fclose(f);
1200
    }
1201

    
1202
    return ret;
1203
}
1204

    
1205
/*
1206
 * Use /sys/bus/usb/devices/ directory to determine host's USB
1207
 * devices.
1208
 *
1209
 * This code is based on Robert Schiele's original patches posted to
1210
 * the Novell bug-tracker https://bugzilla.novell.com/show_bug.cgi?id=241950
1211
 */
1212
static int usb_host_scan_sys(void *opaque, USBScanFunc *func)
1213
{
1214
    DIR *dir = NULL;
1215
    char line[1024];
1216
    int bus_num, addr, speed, class_id, product_id, vendor_id;
1217
    int ret = 0;
1218
    char product_name[512];
1219
    struct dirent *de;
1220

    
1221
    dir = opendir(USBSYSBUS_PATH "/devices");
1222
    if (!dir) {
1223
        perror("husb: cannot open devices directory");
1224
        goto the_end;
1225
    }
1226

    
1227
    while ((de = readdir(dir))) {
1228
        if (de->d_name[0] != '.' && !strchr(de->d_name, ':')) {
1229
            char *tmpstr = de->d_name;
1230
            if (!strncmp(de->d_name, "usb", 3))
1231
                tmpstr += 3;
1232
            bus_num = atoi(tmpstr);
1233

    
1234
            if (!usb_host_read_file(line, sizeof(line), "devnum", de->d_name))
1235
                goto the_end;
1236
            if (sscanf(line, "%d", &addr) != 1)
1237
                goto the_end;
1238

    
1239
            if (!usb_host_read_file(line, sizeof(line), "bDeviceClass",
1240
                                    de->d_name))
1241
                goto the_end;
1242
            if (sscanf(line, "%x", &class_id) != 1)
1243
                goto the_end;
1244

    
1245
            if (!usb_host_read_file(line, sizeof(line), "idVendor", de->d_name))
1246
                goto the_end;
1247
            if (sscanf(line, "%x", &vendor_id) != 1)
1248
                goto the_end;
1249

    
1250
            if (!usb_host_read_file(line, sizeof(line), "idProduct",
1251
                                    de->d_name))
1252
                goto the_end;
1253
            if (sscanf(line, "%x", &product_id) != 1)
1254
                goto the_end;
1255

    
1256
            if (!usb_host_read_file(line, sizeof(line), "product",
1257
                                    de->d_name)) {
1258
                *product_name = 0;
1259
            } else {
1260
                if (strlen(line) > 0)
1261
                    line[strlen(line) - 1] = '\0';
1262
                pstrcpy(product_name, sizeof(product_name), line);
1263
            }
1264

    
1265
            if (!usb_host_read_file(line, sizeof(line), "speed", de->d_name))
1266
                goto the_end;
1267
            if (!strcmp(line, "480\n"))
1268
                speed = USB_SPEED_HIGH;
1269
            else if (!strcmp(line, "1.5\n"))
1270
                speed = USB_SPEED_LOW;
1271
            else
1272
                speed = USB_SPEED_FULL;
1273

    
1274
            ret = func(opaque, bus_num, addr, class_id, vendor_id,
1275
                       product_id, product_name, speed);
1276
            if (ret)
1277
                goto the_end;
1278
        }
1279
    }
1280
 the_end:
1281
    if (dir)
1282
        closedir(dir);
1283
    return ret;
1284
}
1285

    
1286
/*
1287
 * Determine how to access the host's USB devices and call the
1288
 * specific support function.
1289
 */
1290
static int usb_host_scan(void *opaque, USBScanFunc *func)
1291
{
1292
    Monitor *mon = cur_mon;
1293
    FILE *f = NULL;
1294
    DIR *dir = NULL;
1295
    int ret = 0;
1296
    const char *fs_type[] = {"unknown", "proc", "dev", "sys"};
1297
    char devpath[PATH_MAX];
1298

    
1299
    /* only check the host once */
1300
    if (!usb_fs_type) {
1301
        dir = opendir(USBSYSBUS_PATH "/devices");
1302
        if (dir) {
1303
            /* devices found in /dev/bus/usb/ (yes - not a mistake!) */
1304
            strcpy(devpath, USBDEVBUS_PATH);
1305
            usb_fs_type = USB_FS_SYS;
1306
            closedir(dir);
1307
            DPRINTF(USBDBG_DEVOPENED, USBSYSBUS_PATH);
1308
            goto found_devices;
1309
        }
1310
        f = fopen(USBPROCBUS_PATH "/devices", "r");
1311
        if (f) {
1312
            /* devices found in /proc/bus/usb/ */
1313
            strcpy(devpath, USBPROCBUS_PATH);
1314
            usb_fs_type = USB_FS_PROC;
1315
            fclose(f);
1316
            DPRINTF(USBDBG_DEVOPENED, USBPROCBUS_PATH);
1317
            goto found_devices;
1318
        }
1319
        /* try additional methods if an access method hasn't been found yet */
1320
        f = fopen(USBDEVBUS_PATH "/devices", "r");
1321
        if (f) {
1322
            /* devices found in /dev/bus/usb/ */
1323
            strcpy(devpath, USBDEVBUS_PATH);
1324
            usb_fs_type = USB_FS_DEV;
1325
            fclose(f);
1326
            DPRINTF(USBDBG_DEVOPENED, USBDEVBUS_PATH);
1327
            goto found_devices;
1328
        }
1329
    found_devices:
1330
        if (!usb_fs_type) {
1331
            if (mon)
1332
                monitor_printf(mon, "husb: unable to access USB devices\n");
1333
            return -ENOENT;
1334
        }
1335

    
1336
        /* the module setting (used later for opening devices) */
1337
        usb_host_device_path = qemu_mallocz(strlen(devpath)+1);
1338
        strcpy(usb_host_device_path, devpath);
1339
        if (mon)
1340
            monitor_printf(mon, "husb: using %s file-system with %s\n",
1341
                           fs_type[usb_fs_type], usb_host_device_path);
1342
    }
1343

    
1344
    switch (usb_fs_type) {
1345
    case USB_FS_PROC:
1346
    case USB_FS_DEV:
1347
        ret = usb_host_scan_dev(opaque, func);
1348
        break;
1349
    case USB_FS_SYS:
1350
        ret = usb_host_scan_sys(opaque, func);
1351
        break;
1352
    default:
1353
        ret = -EINVAL;
1354
        break;
1355
    }
1356
    return ret;
1357
}
1358

    
1359
static QEMUTimer *usb_auto_timer;
1360

    
1361
static int usb_host_auto_scan(void *opaque, int bus_num, int addr,
1362
                              int class_id, int vendor_id, int product_id,
1363
                              const char *product_name, int speed)
1364
{
1365
    struct USBAutoFilter *f;
1366
    struct USBHostDevice *s;
1367

    
1368
    /* Ignore hubs */
1369
    if (class_id == 9)
1370
        return 0;
1371

    
1372
    QTAILQ_FOREACH(s, &hostdevs, next) {
1373
        f = &s->match;
1374

    
1375
        if (f->bus_num > 0 && f->bus_num != bus_num)
1376
            continue;
1377

    
1378
        if (f->addr > 0 && f->addr != addr)
1379
            continue;
1380

    
1381
        if (f->vendor_id > 0 && f->vendor_id != vendor_id)
1382
            continue;
1383

    
1384
        if (f->product_id > 0 && f->product_id != product_id)
1385
            continue;
1386

    
1387
        /* We got a match */
1388

    
1389
        /* Already attached ? */
1390
        if (s->fd != -1)
1391
            return 0;
1392

    
1393
        DPRINTF("husb: auto open: bus_num %d addr %d\n", bus_num, addr);
1394

    
1395
        usb_host_open(s, bus_num, addr, product_name);
1396
    }
1397

    
1398
    return 0;
1399
}
1400

    
1401
static void usb_host_auto_check(void *unused)
1402
{
1403
    struct USBHostDevice *s;
1404
    int unconnected = 0;
1405

    
1406
    usb_host_scan(NULL, usb_host_auto_scan);
1407

    
1408
    QTAILQ_FOREACH(s, &hostdevs, next) {
1409
        if (s->fd == -1)
1410
            unconnected++;
1411
    }
1412

    
1413
    if (unconnected == 0) {
1414
        /* nothing to watch */
1415
        if (usb_auto_timer)
1416
            qemu_del_timer(usb_auto_timer);
1417
        return;
1418
    }
1419

    
1420
    if (!usb_auto_timer) {
1421
        usb_auto_timer = qemu_new_timer(rt_clock, usb_host_auto_check, NULL);
1422
        if (!usb_auto_timer)
1423
            return;
1424
    }
1425
    qemu_mod_timer(usb_auto_timer, qemu_get_clock(rt_clock) + 2000);
1426
}
1427

    
1428
/*
1429
 * Autoconnect filter
1430
 * Format:
1431
 *    auto:bus:dev[:vid:pid]
1432
 *    auto:bus.dev[:vid:pid]
1433
 *
1434
 *    bus  - bus number    (dec, * means any)
1435
 *    dev  - device number (dec, * means any)
1436
 *    vid  - vendor id     (hex, * means any)
1437
 *    pid  - product id    (hex, * means any)
1438
 *
1439
 *    See 'lsusb' output.
1440
 */
1441
static int parse_filter(const char *spec, struct USBAutoFilter *f)
1442
{
1443
    enum { BUS, DEV, VID, PID, DONE };
1444
    const char *p = spec;
1445
    int i;
1446

    
1447
    f->bus_num    = 0;
1448
    f->addr       = 0;
1449
    f->vendor_id  = 0;
1450
    f->product_id = 0;
1451

    
1452
    for (i = BUS; i < DONE; i++) {
1453
            p = strpbrk(p, ":.");
1454
            if (!p) break;
1455
        p++;
1456
 
1457
            if (*p == '*')
1458
            continue;
1459

    
1460
        switch(i) {
1461
        case BUS: f->bus_num = strtol(p, NULL, 10);    break;
1462
        case DEV: f->addr    = strtol(p, NULL, 10);    break;
1463
        case VID: f->vendor_id  = strtol(p, NULL, 16); break;
1464
        case PID: f->product_id = strtol(p, NULL, 16); break;
1465
        }
1466
    }
1467

    
1468
    if (i < DEV) {
1469
        fprintf(stderr, "husb: invalid auto filter spec %s\n", spec);
1470
        return -1;
1471
    }
1472

    
1473
    return 0;
1474
}
1475

    
1476
/**********************/
1477
/* USB host device info */
1478

    
1479
struct usb_class_info {
1480
    int class;
1481
    const char *class_name;
1482
};
1483

    
1484
static const struct usb_class_info usb_class_info[] = {
1485
    { USB_CLASS_AUDIO, "Audio"},
1486
    { USB_CLASS_COMM, "Communication"},
1487
    { USB_CLASS_HID, "HID"},
1488
    { USB_CLASS_HUB, "Hub" },
1489
    { USB_CLASS_PHYSICAL, "Physical" },
1490
    { USB_CLASS_PRINTER, "Printer" },
1491
    { USB_CLASS_MASS_STORAGE, "Storage" },
1492
    { USB_CLASS_CDC_DATA, "Data" },
1493
    { USB_CLASS_APP_SPEC, "Application Specific" },
1494
    { USB_CLASS_VENDOR_SPEC, "Vendor Specific" },
1495
    { USB_CLASS_STILL_IMAGE, "Still Image" },
1496
    { USB_CLASS_CSCID, "Smart Card" },
1497
    { USB_CLASS_CONTENT_SEC, "Content Security" },
1498
    { -1, NULL }
1499
};
1500

    
1501
static const char *usb_class_str(uint8_t class)
1502
{
1503
    const struct usb_class_info *p;
1504
    for(p = usb_class_info; p->class != -1; p++) {
1505
        if (p->class == class)
1506
            break;
1507
    }
1508
    return p->class_name;
1509
}
1510

    
1511
static void usb_info_device(Monitor *mon, int bus_num, int addr, int class_id,
1512
                            int vendor_id, int product_id,
1513
                            const char *product_name,
1514
                            int speed)
1515
{
1516
    const char *class_str, *speed_str;
1517

    
1518
    switch(speed) {
1519
    case USB_SPEED_LOW:
1520
        speed_str = "1.5";
1521
        break;
1522
    case USB_SPEED_FULL:
1523
        speed_str = "12";
1524
        break;
1525
    case USB_SPEED_HIGH:
1526
        speed_str = "480";
1527
        break;
1528
    default:
1529
        speed_str = "?";
1530
        break;
1531
    }
1532

    
1533
    monitor_printf(mon, "  Device %d.%d, speed %s Mb/s\n",
1534
                bus_num, addr, speed_str);
1535
    class_str = usb_class_str(class_id);
1536
    if (class_str)
1537
        monitor_printf(mon, "    %s:", class_str);
1538
    else
1539
        monitor_printf(mon, "    Class %02x:", class_id);
1540
    monitor_printf(mon, " USB device %04x:%04x", vendor_id, product_id);
1541
    if (product_name[0] != '\0')
1542
        monitor_printf(mon, ", %s", product_name);
1543
    monitor_printf(mon, "\n");
1544
}
1545

    
1546
static int usb_host_info_device(void *opaque, int bus_num, int addr,
1547
                                int class_id,
1548
                                int vendor_id, int product_id,
1549
                                const char *product_name,
1550
                                int speed)
1551
{
1552
    Monitor *mon = opaque;
1553

    
1554
    usb_info_device(mon, bus_num, addr, class_id, vendor_id, product_id,
1555
                    product_name, speed);
1556
    return 0;
1557
}
1558

    
1559
static void dec2str(int val, char *str, size_t size)
1560
{
1561
    if (val == 0)
1562
        snprintf(str, size, "*");
1563
    else
1564
        snprintf(str, size, "%d", val); 
1565
}
1566

    
1567
static void hex2str(int val, char *str, size_t size)
1568
{
1569
    if (val == 0)
1570
        snprintf(str, size, "*");
1571
    else
1572
        snprintf(str, size, "%04x", val);
1573
}
1574

    
1575
void usb_host_info(Monitor *mon)
1576
{
1577
    struct USBAutoFilter *f;
1578
    struct USBHostDevice *s;
1579

    
1580
    usb_host_scan(mon, usb_host_info_device);
1581

    
1582
    if (QTAILQ_EMPTY(&hostdevs))
1583
        return;
1584
    monitor_printf(mon, "  Auto filters:\n");
1585
    QTAILQ_FOREACH(s, &hostdevs, next) {
1586
        char bus[10], addr[10], vid[10], pid[10];
1587
        f = &s->match;
1588
        dec2str(f->bus_num, bus, sizeof(bus));
1589
        dec2str(f->addr, addr, sizeof(addr));
1590
        hex2str(f->vendor_id, vid, sizeof(vid));
1591
        hex2str(f->product_id, pid, sizeof(pid));
1592
        monitor_printf(mon, "    Device %s.%s ID %s:%s\n",
1593
                       bus, addr, vid, pid);
1594
    }
1595
}