Statistics
| Branch: | Revision:

root / usb-linux.c @ 0f5160d1

History | View | Annotate | Download (43.7 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
#include "sysemu.h"
37

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

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

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

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

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

    
69
//#define DEBUG
70

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

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

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

    
85
static char *usb_host_device_path;
86

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

    
92
static int usb_fs_type;
93

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

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

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

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

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

    
131
    uint8_t   descr[1024];
132
    int       descr_len;
133
    int       configuration;
134
    int       ninterfaces;
135
    int       closing;
136
    Notifier  exit;
137

    
138
    struct ctrl_struct ctrl;
139
    struct endp_data endp_table[MAX_ENDPOINTS];
140

    
141
    /* Host side address */
142
    int bus_num;
143
    int addr;
144
    int devpath;
145
    struct USBAutoFilter match;
146

    
147
    QTAILQ_ENTRY(USBHostDevice) next;
148
} USBHostDevice;
149

    
150
static QTAILQ_HEAD(, USBHostDevice) hostdevs = QTAILQ_HEAD_INITIALIZER(hostdevs);
151

    
152
static int usb_host_close(USBHostDevice *dev);
153
static int parse_filter(const char *spec, struct USBAutoFilter *f);
154
static void usb_host_auto_check(void *unused);
155

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

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

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

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

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

    
186
    USBPacket     *packet;
187
    USBHostDevice *hdev;
188
} AsyncURB;
189

    
190
static AsyncURB *async_alloc(void)
191
{
192
    return (AsyncURB *) qemu_mallocz(sizeof(AsyncURB));
193
}
194

    
195
static void async_free(AsyncURB *aurb)
196
{
197
    qemu_free(aurb);
198
}
199

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

    
210
    case CTRL_STATE_ACK:
211
        s->ctrl.state = CTRL_STATE_IDLE;
212
        p->len = 0;
213
        break;
214

    
215
    default:
216
        break;
217
    }
218
}
219

    
220
static void async_complete(void *opaque)
221
{
222
    USBHostDevice *s = opaque;
223
    AsyncURB *aurb;
224

    
225
    while (1) {
226
        USBPacket *p;
227

    
228
        int r = ioctl(s->fd, USBDEVFS_REAPURBNDELAY, &aurb);
229
        if (r < 0) {
230
            if (errno == EAGAIN) {
231
                return;
232
            }
233
            if (errno == ENODEV && !s->closing) {
234
                printf("husb: device %d.%d disconnected\n",
235
                       s->bus_num, s->addr);
236
                usb_host_close(s);
237
                usb_host_auto_check(NULL);
238
                return;
239
            }
240

    
241
            DPRINTF("husb: async. reap urb failed errno %d\n", errno);
242
            return;
243
        }
244

    
245
        p = aurb->packet;
246

    
247
        DPRINTF("husb: async completed. aurb %p status %d alen %d\n",
248
                aurb, aurb->urb.status, aurb->urb.actual_length);
249

    
250
        if (p) {
251
            switch (aurb->urb.status) {
252
            case 0:
253
                p->len = aurb->urb.actual_length;
254
                if (aurb->urb.type == USBDEVFS_URB_TYPE_CONTROL) {
255
                    async_complete_ctrl(s, p);
256
                }
257
                break;
258

    
259
            case -EPIPE:
260
                set_halt(s, p->devep);
261
                p->len = USB_RET_STALL;
262
                break;
263

    
264
            default:
265
                p->len = USB_RET_NAK;
266
                break;
267
            }
268

    
269
            usb_packet_complete(p);
270
        }
271

    
272
        async_free(aurb);
273
    }
274
}
275

    
276
static void async_cancel(USBPacket *unused, void *opaque)
277
{
278
    AsyncURB *aurb = opaque;
279
    USBHostDevice *s = aurb->hdev;
280

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

    
283
    /* Mark it as dead (see async_complete above) */
284
    aurb->packet = NULL;
285

    
286
    int r = ioctl(s->fd, USBDEVFS_DISCARDURB, aurb);
287
    if (r < 0) {
288
        DPRINTF("husb: async. discard urb failed errno %d\n", errno);
289
    }
290
}
291

    
292
static int usb_host_claim_interfaces(USBHostDevice *dev, int configuration)
293
{
294
    int dev_descr_len, config_descr_len;
295
    int interface, nb_interfaces;
296
    int ret, i;
297

    
298
    if (configuration == 0) /* address state - ignore */
299
        return 1;
300

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

    
303
    i = 0;
304
    dev_descr_len = dev->descr[0];
305
    if (dev_descr_len > dev->descr_len) {
306
        goto fail;
307
    }
308

    
309
    i += dev_descr_len;
310
    while (i < dev->descr_len) {
311
        DPRINTF("husb: i is %d, descr_len is %d, dl %d, dt %d\n",
312
                i, dev->descr_len,
313
               dev->descr[i], dev->descr[i+1]);
314

    
315
        if (dev->descr[i+1] != USB_DT_CONFIG) {
316
            i += dev->descr[i];
317
            continue;
318
        }
319
        config_descr_len = dev->descr[i];
320

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

    
323
        if (configuration < 0 || configuration == dev->descr[i + 5]) {
324
            configuration = dev->descr[i + 5];
325
            break;
326
        }
327

    
328
        i += config_descr_len;
329
    }
330

    
331
    if (i >= dev->descr_len) {
332
        fprintf(stderr,
333
                "husb: update iface failed. no matching configuration\n");
334
        goto fail;
335
    }
336
    nb_interfaces = dev->descr[i + 4];
337

    
338
#ifdef USBDEVFS_DISCONNECT
339
    /* earlier Linux 2.4 do not support that */
340
    {
341
        struct usbdevfs_ioctl ctrl;
342
        for (interface = 0; interface < nb_interfaces; interface++) {
343
            ctrl.ioctl_code = USBDEVFS_DISCONNECT;
344
            ctrl.ifno = interface;
345
            ret = ioctl(dev->fd, USBDEVFS_IOCTL, &ctrl);
346
            if (ret < 0 && errno != ENODATA) {
347
                perror("USBDEVFS_DISCONNECT");
348
                goto fail;
349
            }
350
        }
351
    }
352
#endif
353

    
354
    /* XXX: only grab if all interfaces are free */
355
    for (interface = 0; interface < nb_interfaces; interface++) {
356
        ret = ioctl(dev->fd, USBDEVFS_CLAIMINTERFACE, &interface);
357
        if (ret < 0) {
358
            if (errno == EBUSY) {
359
                printf("husb: update iface. device already grabbed\n");
360
            } else {
361
                perror("husb: failed to claim interface");
362
            }
363
        fail:
364
            return 0;
365
        }
366
    }
367

    
368
    printf("husb: %d interfaces claimed for configuration %d\n",
369
           nb_interfaces, configuration);
370

    
371
    dev->ninterfaces   = nb_interfaces;
372
    dev->configuration = configuration;
373
    return 1;
374
}
375

    
376
static int usb_host_release_interfaces(USBHostDevice *s)
377
{
378
    int ret, i;
379

    
380
    DPRINTF("husb: releasing interfaces\n");
381

    
382
    for (i = 0; i < s->ninterfaces; i++) {
383
        ret = ioctl(s->fd, USBDEVFS_RELEASEINTERFACE, &i);
384
        if (ret < 0) {
385
            perror("husb: failed to release interface");
386
            return 0;
387
        }
388
    }
389

    
390
    return 1;
391
}
392

    
393
static void usb_host_handle_reset(USBDevice *dev)
394
{
395
    USBHostDevice *s = DO_UPCAST(USBHostDevice, dev, dev);
396

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

    
399
    ioctl(s->fd, USBDEVFS_RESET);
400

    
401
    usb_host_claim_interfaces(s, s->configuration);
402
}
403

    
404
static void usb_host_handle_destroy(USBDevice *dev)
405
{
406
    USBHostDevice *s = (USBHostDevice *)dev;
407

    
408
    usb_host_close(s);
409
    QTAILQ_REMOVE(&hostdevs, s, next);
410
    qemu_remove_exit_notifier(&s->exit);
411
}
412

    
413
static int usb_linux_update_endp_table(USBHostDevice *s);
414

    
415
static int usb_host_handle_data(USBHostDevice *s, USBPacket *p)
416
{
417
    struct usbdevfs_urb *urb;
418
    AsyncURB *aurb;
419
    int ret;
420

    
421
    aurb = async_alloc();
422
    aurb->hdev   = s;
423
    aurb->packet = p;
424

    
425
    urb = &aurb->urb;
426

    
427
    if (p->pid == USB_TOKEN_IN) {
428
        urb->endpoint = p->devep | 0x80;
429
    } else {
430
        urb->endpoint = p->devep;
431
    }
432

    
433
    if (is_halted(s, p->devep)) {
434
        ret = ioctl(s->fd, USBDEVFS_CLEAR_HALT, &urb->endpoint);
435
        if (ret < 0) {
436
            DPRINTF("husb: failed to clear halt. ep 0x%x errno %d\n",
437
                   urb->endpoint, errno);
438
            return USB_RET_NAK;
439
        }
440
        clear_halt(s, p->devep);
441
    }
442

    
443
    urb->buffer        = p->data;
444
    urb->buffer_length = p->len;
445

    
446
    if (is_isoc(s, p->devep)) {
447
        /* Setup ISOC transfer */
448
        urb->type     = USBDEVFS_URB_TYPE_ISO;
449
        urb->flags    = USBDEVFS_URB_ISO_ASAP;
450
        urb->number_of_packets = 1;
451
        urb->iso_frame_desc[0].length = p->len;
452
    } else {
453
        /* Setup bulk transfer */
454
        urb->type     = USBDEVFS_URB_TYPE_BULK;
455
    }
456

    
457
    urb->usercontext = s;
458

    
459
    ret = ioctl(s->fd, USBDEVFS_SUBMITURB, urb);
460

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

    
464
    if (ret < 0) {
465
        DPRINTF("husb: submit failed. errno %d\n", errno);
466
        async_free(aurb);
467

    
468
        switch(errno) {
469
        case ETIMEDOUT:
470
            return USB_RET_NAK;
471
        case EPIPE:
472
        default:
473
            return USB_RET_STALL;
474
        }
475
    }
476

    
477
    usb_defer_packet(p, async_cancel, aurb);
478
    return USB_RET_ASYNC;
479
}
480

    
481
static int ctrl_error(void)
482
{
483
    if (errno == ETIMEDOUT) {
484
        return USB_RET_NAK;
485
    } else {
486
        return USB_RET_STALL;
487
    }
488
}
489

    
490
static int usb_host_set_address(USBHostDevice *s, int addr)
491
{
492
    DPRINTF("husb: ctrl set addr %u\n", addr);
493
    s->dev.addr = addr;
494
    return 0;
495
}
496

    
497
static int usb_host_set_config(USBHostDevice *s, int config)
498
{
499
    usb_host_release_interfaces(s);
500

    
501
    int ret = ioctl(s->fd, USBDEVFS_SETCONFIGURATION, &config);
502

    
503
    DPRINTF("husb: ctrl set config %d ret %d errno %d\n", config, ret, errno);
504

    
505
    if (ret < 0) {
506
        return ctrl_error();
507
    }
508
    usb_host_claim_interfaces(s, config);
509
    return 0;
510
}
511

    
512
static int usb_host_set_interface(USBHostDevice *s, int iface, int alt)
513
{
514
    struct usbdevfs_setinterface si;
515
    int ret;
516

    
517
    si.interface  = iface;
518
    si.altsetting = alt;
519
    ret = ioctl(s->fd, USBDEVFS_SETINTERFACE, &si);
520

    
521
    DPRINTF("husb: ctrl set iface %d altset %d ret %d errno %d\n",
522
            iface, alt, ret, errno);
523

    
524
    if (ret < 0) {
525
        return ctrl_error();
526
    }
527
    usb_linux_update_endp_table(s);
528
    return 0;
529
}
530

    
531
static int usb_host_handle_control(USBHostDevice *s, USBPacket *p)
532
{
533
    struct usbdevfs_urb *urb;
534
    AsyncURB *aurb;
535
    int ret, value, index;
536
    int buffer_len;
537

    
538
    /*
539
     * Process certain standard device requests.
540
     * These are infrequent and are processed synchronously.
541
     */
542
    value = le16_to_cpu(s->ctrl.req.wValue);
543
    index = le16_to_cpu(s->ctrl.req.wIndex);
544

    
545
    DPRINTF("husb: ctrl type 0x%x req 0x%x val 0x%x index %u len %u\n",
546
            s->ctrl.req.bRequestType, s->ctrl.req.bRequest, value, index,
547
            s->ctrl.len);
548

    
549
    if (s->ctrl.req.bRequestType == 0) {
550
        switch (s->ctrl.req.bRequest) {
551
        case USB_REQ_SET_ADDRESS:
552
            return usb_host_set_address(s, value);
553

    
554
        case USB_REQ_SET_CONFIGURATION:
555
            return usb_host_set_config(s, value & 0xff);
556
        }
557
    }
558

    
559
    if (s->ctrl.req.bRequestType == 1 &&
560
                  s->ctrl.req.bRequest == USB_REQ_SET_INTERFACE) {
561
        return usb_host_set_interface(s, index, value);
562
    }
563

    
564
    /* The rest are asynchronous */
565

    
566
    buffer_len = 8 + s->ctrl.len;
567
    if (buffer_len > sizeof(s->ctrl.buffer)) {
568
        fprintf(stderr, "husb: ctrl buffer too small (%u > %zu)\n",
569
                buffer_len, sizeof(s->ctrl.buffer));
570
        return USB_RET_STALL;
571
    }
572

    
573
    aurb = async_alloc();
574
    aurb->hdev   = s;
575
    aurb->packet = p;
576

    
577
    /*
578
     * Setup ctrl transfer.
579
     *
580
     * s->ctrl is layed out such that data buffer immediately follows
581
     * 'req' struct which is exactly what usbdevfs expects.
582
     */
583
    urb = &aurb->urb;
584

    
585
    urb->type     = USBDEVFS_URB_TYPE_CONTROL;
586
    urb->endpoint = p->devep;
587

    
588
    urb->buffer        = &s->ctrl.req;
589
    urb->buffer_length = buffer_len;
590

    
591
    urb->usercontext = s;
592

    
593
    ret = ioctl(s->fd, USBDEVFS_SUBMITURB, urb);
594

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

    
597
    if (ret < 0) {
598
        DPRINTF("husb: submit failed. errno %d\n", errno);
599
        async_free(aurb);
600

    
601
        switch(errno) {
602
        case ETIMEDOUT:
603
            return USB_RET_NAK;
604
        case EPIPE:
605
        default:
606
            return USB_RET_STALL;
607
        }
608
    }
609

    
610
    usb_defer_packet(p, async_cancel, aurb);
611
    return USB_RET_ASYNC;
612
}
613

    
614
static int do_token_setup(USBDevice *dev, USBPacket *p)
615
{
616
    USBHostDevice *s = (USBHostDevice *) dev;
617
    int ret = 0;
618

    
619
    if (p->len != 8) {
620
        return USB_RET_STALL;
621
    }
622

    
623
    memcpy(&s->ctrl.req, p->data, 8);
624
    s->ctrl.len    = le16_to_cpu(s->ctrl.req.wLength);
625
    s->ctrl.offset = 0;
626
    s->ctrl.state  = CTRL_STATE_SETUP;
627

    
628
    if (s->ctrl.req.bRequestType & USB_DIR_IN) {
629
        ret = usb_host_handle_control(s, p);
630
        if (ret < 0) {
631
            return ret;
632
        }
633

    
634
        if (ret < s->ctrl.len) {
635
            s->ctrl.len = ret;
636
        }
637
        s->ctrl.state = CTRL_STATE_DATA;
638
    } else {
639
        if (s->ctrl.len == 0) {
640
            s->ctrl.state = CTRL_STATE_ACK;
641
        } else {
642
            s->ctrl.state = CTRL_STATE_DATA;
643
        }
644
    }
645

    
646
    return ret;
647
}
648

    
649
static int do_token_in(USBDevice *dev, USBPacket *p)
650
{
651
    USBHostDevice *s = (USBHostDevice *) dev;
652
    int ret = 0;
653

    
654
    if (p->devep != 0) {
655
        return usb_host_handle_data(s, p);
656
    }
657

    
658
    switch(s->ctrl.state) {
659
    case CTRL_STATE_ACK:
660
        if (!(s->ctrl.req.bRequestType & USB_DIR_IN)) {
661
            ret = usb_host_handle_control(s, p);
662
            if (ret == USB_RET_ASYNC) {
663
                return USB_RET_ASYNC;
664
            }
665
            s->ctrl.state = CTRL_STATE_IDLE;
666
            return ret > 0 ? 0 : ret;
667
        }
668

    
669
        return 0;
670

    
671
    case CTRL_STATE_DATA:
672
        if (s->ctrl.req.bRequestType & USB_DIR_IN) {
673
            int len = s->ctrl.len - s->ctrl.offset;
674
            if (len > p->len) {
675
                len = p->len;
676
            }
677
            memcpy(p->data, s->ctrl.buffer + s->ctrl.offset, len);
678
            s->ctrl.offset += len;
679
            if (s->ctrl.offset >= s->ctrl.len) {
680
                s->ctrl.state = CTRL_STATE_ACK;
681
            }
682
            return len;
683
        }
684

    
685
        s->ctrl.state = CTRL_STATE_IDLE;
686
        return USB_RET_STALL;
687

    
688
    default:
689
        return USB_RET_STALL;
690
    }
691
}
692

    
693
static int do_token_out(USBDevice *dev, USBPacket *p)
694
{
695
    USBHostDevice *s = (USBHostDevice *) dev;
696

    
697
    if (p->devep != 0) {
698
        return usb_host_handle_data(s, p);
699
    }
700

    
701
    switch(s->ctrl.state) {
702
    case CTRL_STATE_ACK:
703
        if (s->ctrl.req.bRequestType & USB_DIR_IN) {
704
            s->ctrl.state = CTRL_STATE_IDLE;
705
            /* transfer OK */
706
        } else {
707
            /* ignore additional output */
708
        }
709
        return 0;
710

    
711
    case CTRL_STATE_DATA:
712
        if (!(s->ctrl.req.bRequestType & USB_DIR_IN)) {
713
            int len = s->ctrl.len - s->ctrl.offset;
714
            if (len > p->len) {
715
                len = p->len;
716
            }
717
            memcpy(s->ctrl.buffer + s->ctrl.offset, p->data, len);
718
            s->ctrl.offset += len;
719
            if (s->ctrl.offset >= s->ctrl.len) {
720
                s->ctrl.state = CTRL_STATE_ACK;
721
            }
722
            return len;
723
        }
724

    
725
        s->ctrl.state = CTRL_STATE_IDLE;
726
        return USB_RET_STALL;
727

    
728
    default:
729
        return USB_RET_STALL;
730
    }
731
}
732

    
733
/*
734
 * Packet handler.
735
 * Called by the HC (host controller).
736
 *
737
 * Returns length of the transaction or one of the USB_RET_XXX codes.
738
 */
739
static int usb_host_handle_packet(USBDevice *s, USBPacket *p)
740
{
741
    switch(p->pid) {
742
    case USB_MSG_ATTACH:
743
        s->state = USB_STATE_ATTACHED;
744
        return 0;
745

    
746
    case USB_MSG_DETACH:
747
        s->state = USB_STATE_NOTATTACHED;
748
        return 0;
749

    
750
    case USB_MSG_RESET:
751
        s->remote_wakeup = 0;
752
        s->addr = 0;
753
        s->state = USB_STATE_DEFAULT;
754
        s->info->handle_reset(s);
755
        return 0;
756
    }
757

    
758
    /* Rest of the PIDs must match our address */
759
    if (s->state < USB_STATE_DEFAULT || p->devaddr != s->addr) {
760
        return USB_RET_NODEV;
761
    }
762

    
763
    switch (p->pid) {
764
    case USB_TOKEN_SETUP:
765
        return do_token_setup(s, p);
766

    
767
    case USB_TOKEN_IN:
768
        return do_token_in(s, p);
769

    
770
    case USB_TOKEN_OUT:
771
        return do_token_out(s, p);
772

    
773
    default:
774
        return USB_RET_STALL;
775
    }
776
}
777

    
778
/* returns 1 on problem encountered or 0 for success */
779
static int usb_linux_update_endp_table(USBHostDevice *s)
780
{
781
    uint8_t *descriptors;
782
    uint8_t devep, type, configuration, alt_interface;
783
    struct usb_ctrltransfer ct;
784
    int interface, ret, length, i;
785

    
786
    ct.bRequestType = USB_DIR_IN;
787
    ct.bRequest = USB_REQ_GET_CONFIGURATION;
788
    ct.wValue = 0;
789
    ct.wIndex = 0;
790
    ct.wLength = 1;
791
    ct.data = &configuration;
792
    ct.timeout = 50;
793

    
794
    ret = ioctl(s->fd, USBDEVFS_CONTROL, &ct);
795
    if (ret < 0) {
796
        perror("usb_linux_update_endp_table");
797
        return 1;
798
    }
799

    
800
    /* in address state */
801
    if (configuration == 0) {
802
        return 1;
803
    }
804

    
805
    /* get the desired configuration, interface, and endpoint descriptors
806
     * from device description */
807
    descriptors = &s->descr[18];
808
    length = s->descr_len - 18;
809
    i = 0;
810

    
811
    if (descriptors[i + 1] != USB_DT_CONFIG ||
812
        descriptors[i + 5] != configuration) {
813
        DPRINTF("invalid descriptor data - configuration\n");
814
        return 1;
815
    }
816
    i += descriptors[i];
817

    
818
    while (i < length) {
819
        if (descriptors[i + 1] != USB_DT_INTERFACE ||
820
            (descriptors[i + 1] == USB_DT_INTERFACE &&
821
             descriptors[i + 4] == 0)) {
822
            i += descriptors[i];
823
            continue;
824
        }
825

    
826
        interface = descriptors[i + 2];
827

    
828
        ct.bRequestType = USB_DIR_IN | USB_RECIP_INTERFACE;
829
        ct.bRequest = USB_REQ_GET_INTERFACE;
830
        ct.wValue = 0;
831
        ct.wIndex = interface;
832
        ct.wLength = 1;
833
        ct.data = &alt_interface;
834
        ct.timeout = 50;
835

    
836
        ret = ioctl(s->fd, USBDEVFS_CONTROL, &ct);
837
        if (ret < 0) {
838
            alt_interface = interface;
839
        }
840

    
841
        /* the current interface descriptor is the active interface
842
         * and has endpoints */
843
        if (descriptors[i + 3] != alt_interface) {
844
            i += descriptors[i];
845
            continue;
846
        }
847

    
848
        /* advance to the endpoints */
849
        while (i < length && descriptors[i +1] != USB_DT_ENDPOINT) {
850
            i += descriptors[i];
851
        }
852

    
853
        if (i >= length)
854
            break;
855

    
856
        while (i < length) {
857
            if (descriptors[i + 1] != USB_DT_ENDPOINT) {
858
                break;
859
            }
860

    
861
            devep = descriptors[i + 2];
862
            switch (descriptors[i + 3] & 0x3) {
863
            case 0x00:
864
                type = USBDEVFS_URB_TYPE_CONTROL;
865
                break;
866
            case 0x01:
867
                type = USBDEVFS_URB_TYPE_ISO;
868
                break;
869
            case 0x02:
870
                type = USBDEVFS_URB_TYPE_BULK;
871
                break;
872
            case 0x03:
873
                type = USBDEVFS_URB_TYPE_INTERRUPT;
874
                break;
875
            default:
876
                DPRINTF("usb_host: malformed endpoint type\n");
877
                type = USBDEVFS_URB_TYPE_BULK;
878
            }
879
            s->endp_table[(devep & 0xf) - 1].type = type;
880
            s->endp_table[(devep & 0xf) - 1].halted = 0;
881

    
882
            i += descriptors[i];
883
        }
884
    }
885
    return 0;
886
}
887

    
888
static int usb_host_open(USBHostDevice *dev, int bus_num,
889
                         int addr, int devpath, const char *prod_name)
890
{
891
    int fd = -1, ret;
892
    struct usbdevfs_connectinfo ci;
893
    char buf[1024];
894

    
895
    if (dev->fd != -1) {
896
        goto fail;
897
    }
898
    printf("husb: open device %d.%d\n", bus_num, addr);
899

    
900
    if (!usb_host_device_path) {
901
        perror("husb: USB Host Device Path not set");
902
        goto fail;
903
    }
904
    snprintf(buf, sizeof(buf), "%s/%03d/%03d", usb_host_device_path,
905
             bus_num, addr);
906
    fd = open(buf, O_RDWR | O_NONBLOCK);
907
    if (fd < 0) {
908
        perror(buf);
909
        goto fail;
910
    }
911
    DPRINTF("husb: opened %s\n", buf);
912

    
913
    dev->bus_num = bus_num;
914
    dev->addr = addr;
915
    dev->devpath = devpath;
916
    dev->fd = fd;
917

    
918
    /* read the device description */
919
    dev->descr_len = read(fd, dev->descr, sizeof(dev->descr));
920
    if (dev->descr_len <= 0) {
921
        perror("husb: reading device data failed");
922
        goto fail;
923
    }
924

    
925
#ifdef DEBUG
926
    {
927
        int x;
928
        printf("=== begin dumping device descriptor data ===\n");
929
        for (x = 0; x < dev->descr_len; x++) {
930
            printf("%02x ", dev->descr[x]);
931
        }
932
        printf("\n=== end dumping device descriptor data ===\n");
933
    }
934
#endif
935

    
936

    
937
    /*
938
     * Initial configuration is -1 which makes us claim first
939
     * available config. We used to start with 1, which does not
940
     * always work. I've seen devices where first config starts
941
     * with 2.
942
     */
943
    if (!usb_host_claim_interfaces(dev, -1)) {
944
        goto fail;
945
    }
946

    
947
    ret = ioctl(fd, USBDEVFS_CONNECTINFO, &ci);
948
    if (ret < 0) {
949
        perror("usb_host_device_open: USBDEVFS_CONNECTINFO");
950
        goto fail;
951
    }
952

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

    
955
    ret = usb_linux_update_endp_table(dev);
956
    if (ret) {
957
        goto fail;
958
    }
959

    
960
    if (ci.slow) {
961
        dev->dev.speed = USB_SPEED_LOW;
962
    } else {
963
        dev->dev.speed = USB_SPEED_HIGH;
964
    }
965

    
966
    if (!prod_name || prod_name[0] == '\0') {
967
        snprintf(dev->dev.product_desc, sizeof(dev->dev.product_desc),
968
                 "host:%d.%d", bus_num, addr);
969
    } else {
970
        pstrcpy(dev->dev.product_desc, sizeof(dev->dev.product_desc),
971
                prod_name);
972
    }
973

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

    
977
    usb_device_attach(&dev->dev);
978
    return 0;
979

    
980
fail:
981
    dev->fd = -1;
982
    if (fd != -1) {
983
        close(fd);
984
    }
985
    return -1;
986
}
987

    
988
static int usb_host_close(USBHostDevice *dev)
989
{
990
    if (dev->fd == -1) {
991
        return -1;
992
    }
993

    
994
    qemu_set_fd_handler(dev->fd, NULL, NULL, NULL);
995
    dev->closing = 1;
996
    async_complete(dev);
997
    dev->closing = 0;
998
    usb_device_detach(&dev->dev);
999
    ioctl(dev->fd, USBDEVFS_RESET);
1000
    close(dev->fd);
1001
    dev->fd = -1;
1002
    return 0;
1003
}
1004

    
1005
static void usb_host_exit_notifier(struct Notifier* n)
1006
{
1007
    USBHostDevice *s = container_of(n, USBHostDevice, exit);
1008

    
1009
    if (s->fd != -1) {
1010
        ioctl(s->fd, USBDEVFS_RESET);
1011
    }
1012
}
1013

    
1014
static int usb_host_initfn(USBDevice *dev)
1015
{
1016
    USBHostDevice *s = DO_UPCAST(USBHostDevice, dev, dev);
1017

    
1018
    dev->auto_attach = 0;
1019
    s->fd = -1;
1020
    QTAILQ_INSERT_TAIL(&hostdevs, s, next);
1021
    s->exit.notify = usb_host_exit_notifier;
1022
    qemu_add_exit_notifier(&s->exit);
1023
    usb_host_auto_check(NULL);
1024
    return 0;
1025
}
1026

    
1027
static struct USBDeviceInfo usb_host_dev_info = {
1028
    .product_desc   = "USB Host Device",
1029
    .qdev.name      = "usb-host",
1030
    .qdev.size      = sizeof(USBHostDevice),
1031
    .init           = usb_host_initfn,
1032
    .handle_packet  = usb_host_handle_packet,
1033
    .handle_reset   = usb_host_handle_reset,
1034
    .handle_destroy = usb_host_handle_destroy,
1035
    .usbdevice_name = "host",
1036
    .usbdevice_init = usb_host_device_open,
1037
    .qdev.props     = (Property[]) {
1038
        DEFINE_PROP_UINT32("hostbus",  USBHostDevice, match.bus_num,    0),
1039
        DEFINE_PROP_UINT32("hostaddr", USBHostDevice, match.addr,       0),
1040
        DEFINE_PROP_HEX32("vendorid",  USBHostDevice, match.vendor_id,  0),
1041
        DEFINE_PROP_HEX32("productid", USBHostDevice, match.product_id, 0),
1042
        DEFINE_PROP_END_OF_LIST(),
1043
    },
1044
};
1045

    
1046
static void usb_host_register_devices(void)
1047
{
1048
    usb_qdev_register(&usb_host_dev_info);
1049
}
1050
device_init(usb_host_register_devices)
1051

    
1052
USBDevice *usb_host_device_open(const char *devname)
1053
{
1054
    struct USBAutoFilter filter;
1055
    USBDevice *dev;
1056
    char *p;
1057

    
1058
    dev = usb_create(NULL /* FIXME */, "usb-host");
1059

    
1060
    if (strstr(devname, "auto:")) {
1061
        if (parse_filter(devname, &filter) < 0) {
1062
            goto fail;
1063
        }
1064
    } else {
1065
        if ((p = strchr(devname, '.'))) {
1066
            filter.bus_num    = strtoul(devname, NULL, 0);
1067
            filter.addr       = strtoul(p + 1, NULL, 0);
1068
            filter.vendor_id  = 0;
1069
            filter.product_id = 0;
1070
        } else if ((p = strchr(devname, ':'))) {
1071
            filter.bus_num    = 0;
1072
            filter.addr       = 0;
1073
            filter.vendor_id  = strtoul(devname, NULL, 16);
1074
            filter.product_id = strtoul(p + 1, NULL, 16);
1075
        } else {
1076
            goto fail;
1077
        }
1078
    }
1079

    
1080
    qdev_prop_set_uint32(&dev->qdev, "hostbus",   filter.bus_num);
1081
    qdev_prop_set_uint32(&dev->qdev, "hostaddr",  filter.addr);
1082
    qdev_prop_set_uint32(&dev->qdev, "vendorid",  filter.vendor_id);
1083
    qdev_prop_set_uint32(&dev->qdev, "productid", filter.product_id);
1084
    qdev_init_nofail(&dev->qdev);
1085
    return dev;
1086

    
1087
fail:
1088
    qdev_free(&dev->qdev);
1089
    return NULL;
1090
}
1091

    
1092
int usb_host_device_close(const char *devname)
1093
{
1094
#if 0
1095
    char product_name[PRODUCT_NAME_SZ];
1096
    int bus_num, addr;
1097
    USBHostDevice *s;
1098

1099
    if (strstr(devname, "auto:")) {
1100
        return usb_host_auto_del(devname);
1101
    }
1102
    if (usb_host_find_device(&bus_num, &addr, product_name,
1103
                                    sizeof(product_name), devname) < 0) {
1104
        return -1;
1105
    }
1106
    s = hostdev_find(bus_num, addr);
1107
    if (s) {
1108
        usb_device_delete_addr(s->bus_num, s->dev.addr);
1109
        return 0;
1110
    }
1111
#endif
1112

    
1113
    return -1;
1114
}
1115

    
1116
static int get_tag_value(char *buf, int buf_size,
1117
                         const char *str, const char *tag,
1118
                         const char *stopchars)
1119
{
1120
    const char *p;
1121
    char *q;
1122
    p = strstr(str, tag);
1123
    if (!p) {
1124
        return -1;
1125
    }
1126
    p += strlen(tag);
1127
    while (qemu_isspace(*p)) {
1128
        p++;
1129
    }
1130
    q = buf;
1131
    while (*p != '\0' && !strchr(stopchars, *p)) {
1132
        if ((q - buf) < (buf_size - 1)) {
1133
            *q++ = *p;
1134
        }
1135
        p++;
1136
    }
1137
    *q = '\0';
1138
    return q - buf;
1139
}
1140

    
1141
/*
1142
 * Use /proc/bus/usb/devices or /dev/bus/usb/devices file to determine
1143
 * host's USB devices. This is legacy support since many distributions
1144
 * are moving to /sys/bus/usb
1145
 */
1146
static int usb_host_scan_dev(void *opaque, USBScanFunc *func)
1147
{
1148
    FILE *f = NULL;
1149
    char line[1024];
1150
    char buf[1024];
1151
    int bus_num, addr, speed, device_count, class_id, product_id, vendor_id;
1152
    char product_name[512];
1153
    int ret = 0;
1154

    
1155
    if (!usb_host_device_path) {
1156
        perror("husb: USB Host Device Path not set");
1157
        goto the_end;
1158
    }
1159
    snprintf(line, sizeof(line), "%s/devices", usb_host_device_path);
1160
    f = fopen(line, "r");
1161
    if (!f) {
1162
        perror("husb: cannot open devices file");
1163
        goto the_end;
1164
    }
1165

    
1166
    device_count = 0;
1167
    bus_num = addr = speed = class_id = product_id = vendor_id = 0;
1168
    for(;;) {
1169
        if (fgets(line, sizeof(line), f) == NULL) {
1170
            break;
1171
        }
1172
        if (strlen(line) > 0) {
1173
            line[strlen(line) - 1] = '\0';
1174
        }
1175
        if (line[0] == 'T' && line[1] == ':') {
1176
            if (device_count && (vendor_id || product_id)) {
1177
                /* New device.  Add the previously discovered device.  */
1178
                ret = func(opaque, bus_num, addr, 0, class_id, vendor_id,
1179
                           product_id, product_name, speed);
1180
                if (ret) {
1181
                    goto the_end;
1182
                }
1183
            }
1184
            if (get_tag_value(buf, sizeof(buf), line, "Bus=", " ") < 0) {
1185
                goto fail;
1186
            }
1187
            bus_num = atoi(buf);
1188
            if (get_tag_value(buf, sizeof(buf), line, "Dev#=", " ") < 0) {
1189
                goto fail;
1190
            }
1191
            addr = atoi(buf);
1192
            if (get_tag_value(buf, sizeof(buf), line, "Spd=", " ") < 0) {
1193
                goto fail;
1194
            }
1195
            if (!strcmp(buf, "480")) {
1196
                speed = USB_SPEED_HIGH;
1197
            } else if (!strcmp(buf, "1.5")) {
1198
                speed = USB_SPEED_LOW;
1199
            } else {
1200
                speed = USB_SPEED_FULL;
1201
            }
1202
            product_name[0] = '\0';
1203
            class_id = 0xff;
1204
            device_count++;
1205
            product_id = 0;
1206
            vendor_id = 0;
1207
        } else if (line[0] == 'P' && line[1] == ':') {
1208
            if (get_tag_value(buf, sizeof(buf), line, "Vendor=", " ") < 0) {
1209
                goto fail;
1210
            }
1211
            vendor_id = strtoul(buf, NULL, 16);
1212
            if (get_tag_value(buf, sizeof(buf), line, "ProdID=", " ") < 0) {
1213
                goto fail;
1214
            }
1215
            product_id = strtoul(buf, NULL, 16);
1216
        } else if (line[0] == 'S' && line[1] == ':') {
1217
            if (get_tag_value(buf, sizeof(buf), line, "Product=", "") < 0) {
1218
                goto fail;
1219
            }
1220
            pstrcpy(product_name, sizeof(product_name), buf);
1221
        } else if (line[0] == 'D' && line[1] == ':') {
1222
            if (get_tag_value(buf, sizeof(buf), line, "Cls=", " (") < 0) {
1223
                goto fail;
1224
            }
1225
            class_id = strtoul(buf, NULL, 16);
1226
        }
1227
    fail: ;
1228
    }
1229
    if (device_count && (vendor_id || product_id)) {
1230
        /* Add the last device.  */
1231
        ret = func(opaque, bus_num, addr, 0, class_id, vendor_id,
1232
                   product_id, product_name, speed);
1233
    }
1234
 the_end:
1235
    if (f) {
1236
        fclose(f);
1237
    }
1238
    return ret;
1239
}
1240

    
1241
/*
1242
 * Read sys file-system device file
1243
 *
1244
 * @line address of buffer to put file contents in
1245
 * @line_size size of line
1246
 * @device_file path to device file (printf format string)
1247
 * @device_name device being opened (inserted into device_file)
1248
 *
1249
 * @return 0 failed, 1 succeeded ('line' contains data)
1250
 */
1251
static int usb_host_read_file(char *line, size_t line_size,
1252
                              const char *device_file, const char *device_name)
1253
{
1254
    FILE *f;
1255
    int ret = 0;
1256
    char filename[PATH_MAX];
1257

    
1258
    snprintf(filename, PATH_MAX, USBSYSBUS_PATH "/devices/%s/%s", device_name,
1259
             device_file);
1260
    f = fopen(filename, "r");
1261
    if (f) {
1262
        ret = fgets(line, line_size, f) != NULL;
1263
        fclose(f);
1264
    }
1265

    
1266
    return ret;
1267
}
1268

    
1269
/*
1270
 * Use /sys/bus/usb/devices/ directory to determine host's USB
1271
 * devices.
1272
 *
1273
 * This code is based on Robert Schiele's original patches posted to
1274
 * the Novell bug-tracker https://bugzilla.novell.com/show_bug.cgi?id=241950
1275
 */
1276
static int usb_host_scan_sys(void *opaque, USBScanFunc *func)
1277
{
1278
    DIR *dir = NULL;
1279
    char line[1024];
1280
    int bus_num, addr, devpath, speed, class_id, product_id, vendor_id;
1281
    int ret = 0;
1282
    char product_name[512];
1283
    struct dirent *de;
1284

    
1285
    dir = opendir(USBSYSBUS_PATH "/devices");
1286
    if (!dir) {
1287
        perror("husb: cannot open devices directory");
1288
        goto the_end;
1289
    }
1290

    
1291
    while ((de = readdir(dir))) {
1292
        if (de->d_name[0] != '.' && !strchr(de->d_name, ':')) {
1293
            char *tmpstr = de->d_name;
1294
            if (!strncmp(de->d_name, "usb", 3)) {
1295
                tmpstr += 3;
1296
            }
1297
            if (sscanf(tmpstr, "%d-%d", &bus_num, &devpath) < 1) {
1298
                goto the_end;
1299
            }
1300

    
1301
            if (!usb_host_read_file(line, sizeof(line), "devnum", de->d_name)) {
1302
                goto the_end;
1303
            }
1304
            if (sscanf(line, "%d", &addr) != 1) {
1305
                goto the_end;
1306
            }
1307
            if (!usb_host_read_file(line, sizeof(line), "bDeviceClass",
1308
                                    de->d_name)) {
1309
                goto the_end;
1310
            }
1311
            if (sscanf(line, "%x", &class_id) != 1) {
1312
                goto the_end;
1313
            }
1314

    
1315
            if (!usb_host_read_file(line, sizeof(line), "idVendor",
1316
                                    de->d_name)) {
1317
                goto the_end;
1318
            }
1319
            if (sscanf(line, "%x", &vendor_id) != 1) {
1320
                goto the_end;
1321
            }
1322
            if (!usb_host_read_file(line, sizeof(line), "idProduct",
1323
                                    de->d_name)) {
1324
                goto the_end;
1325
            }
1326
            if (sscanf(line, "%x", &product_id) != 1) {
1327
                goto the_end;
1328
            }
1329
            if (!usb_host_read_file(line, sizeof(line), "product",
1330
                                    de->d_name)) {
1331
                *product_name = 0;
1332
            } else {
1333
                if (strlen(line) > 0) {
1334
                    line[strlen(line) - 1] = '\0';
1335
                }
1336
                pstrcpy(product_name, sizeof(product_name), line);
1337
            }
1338

    
1339
            if (!usb_host_read_file(line, sizeof(line), "speed", de->d_name)) {
1340
                goto the_end;
1341
            }
1342
            if (!strcmp(line, "480\n")) {
1343
                speed = USB_SPEED_HIGH;
1344
            } else if (!strcmp(line, "1.5\n")) {
1345
                speed = USB_SPEED_LOW;
1346
            } else {
1347
                speed = USB_SPEED_FULL;
1348
            }
1349

    
1350
            ret = func(opaque, bus_num, addr, devpath, class_id, vendor_id,
1351
                       product_id, product_name, speed);
1352
            if (ret) {
1353
                goto the_end;
1354
            }
1355
        }
1356
    }
1357
 the_end:
1358
    if (dir) {
1359
        closedir(dir);
1360
    }
1361
    return ret;
1362
}
1363

    
1364
/*
1365
 * Determine how to access the host's USB devices and call the
1366
 * specific support function.
1367
 */
1368
static int usb_host_scan(void *opaque, USBScanFunc *func)
1369
{
1370
    Monitor *mon = cur_mon;
1371
    FILE *f = NULL;
1372
    DIR *dir = NULL;
1373
    int ret = 0;
1374
    const char *fs_type[] = {"unknown", "proc", "dev", "sys"};
1375
    char devpath[PATH_MAX];
1376

    
1377
    /* only check the host once */
1378
    if (!usb_fs_type) {
1379
        dir = opendir(USBSYSBUS_PATH "/devices");
1380
        if (dir) {
1381
            /* devices found in /dev/bus/usb/ (yes - not a mistake!) */
1382
            strcpy(devpath, USBDEVBUS_PATH);
1383
            usb_fs_type = USB_FS_SYS;
1384
            closedir(dir);
1385
            DPRINTF(USBDBG_DEVOPENED, USBSYSBUS_PATH);
1386
            goto found_devices;
1387
        }
1388
        f = fopen(USBPROCBUS_PATH "/devices", "r");
1389
        if (f) {
1390
            /* devices found in /proc/bus/usb/ */
1391
            strcpy(devpath, USBPROCBUS_PATH);
1392
            usb_fs_type = USB_FS_PROC;
1393
            fclose(f);
1394
            DPRINTF(USBDBG_DEVOPENED, USBPROCBUS_PATH);
1395
            goto found_devices;
1396
        }
1397
        /* try additional methods if an access method hasn't been found yet */
1398
        f = fopen(USBDEVBUS_PATH "/devices", "r");
1399
        if (f) {
1400
            /* devices found in /dev/bus/usb/ */
1401
            strcpy(devpath, USBDEVBUS_PATH);
1402
            usb_fs_type = USB_FS_DEV;
1403
            fclose(f);
1404
            DPRINTF(USBDBG_DEVOPENED, USBDEVBUS_PATH);
1405
            goto found_devices;
1406
        }
1407
    found_devices:
1408
        if (!usb_fs_type) {
1409
            if (mon) {
1410
                monitor_printf(mon, "husb: unable to access USB devices\n");
1411
            }
1412
            return -ENOENT;
1413
        }
1414

    
1415
        /* the module setting (used later for opening devices) */
1416
        usb_host_device_path = qemu_mallocz(strlen(devpath)+1);
1417
        strcpy(usb_host_device_path, devpath);
1418
        if (mon) {
1419
            monitor_printf(mon, "husb: using %s file-system with %s\n",
1420
                           fs_type[usb_fs_type], usb_host_device_path);
1421
        }
1422
    }
1423

    
1424
    switch (usb_fs_type) {
1425
    case USB_FS_PROC:
1426
    case USB_FS_DEV:
1427
        ret = usb_host_scan_dev(opaque, func);
1428
        break;
1429
    case USB_FS_SYS:
1430
        ret = usb_host_scan_sys(opaque, func);
1431
        break;
1432
    default:
1433
        ret = -EINVAL;
1434
        break;
1435
    }
1436
    return ret;
1437
}
1438

    
1439
static QEMUTimer *usb_auto_timer;
1440

    
1441
static int usb_host_auto_scan(void *opaque, int bus_num, int addr, int devpath,
1442
                              int class_id, int vendor_id, int product_id,
1443
                              const char *product_name, int speed)
1444
{
1445
    struct USBAutoFilter *f;
1446
    struct USBHostDevice *s;
1447

    
1448
    /* Ignore hubs */
1449
    if (class_id == 9)
1450
        return 0;
1451

    
1452
    QTAILQ_FOREACH(s, &hostdevs, next) {
1453
        f = &s->match;
1454

    
1455
        if (f->bus_num > 0 && f->bus_num != bus_num) {
1456
            continue;
1457
        }
1458
        if (f->addr > 0 && f->addr != addr) {
1459
            continue;
1460
        }
1461

    
1462
        if (f->vendor_id > 0 && f->vendor_id != vendor_id) {
1463
            continue;
1464
        }
1465

    
1466
        if (f->product_id > 0 && f->product_id != product_id) {
1467
            continue;
1468
        }
1469
        /* We got a match */
1470

    
1471
        /* Already attached ? */
1472
        if (s->fd != -1) {
1473
            return 0;
1474
        }
1475
        DPRINTF("husb: auto open: bus_num %d addr %d\n", bus_num, addr);
1476

    
1477
        usb_host_open(s, bus_num, addr, devpath, product_name);
1478
    }
1479

    
1480
    return 0;
1481
}
1482

    
1483
static void usb_host_auto_check(void *unused)
1484
{
1485
    struct USBHostDevice *s;
1486
    int unconnected = 0;
1487

    
1488
    usb_host_scan(NULL, usb_host_auto_scan);
1489

    
1490
    QTAILQ_FOREACH(s, &hostdevs, next) {
1491
        if (s->fd == -1) {
1492
            unconnected++;
1493
        }
1494
    }
1495

    
1496
    if (unconnected == 0) {
1497
        /* nothing to watch */
1498
        if (usb_auto_timer) {
1499
            qemu_del_timer(usb_auto_timer);
1500
        }
1501
        return;
1502
    }
1503

    
1504
    if (!usb_auto_timer) {
1505
        usb_auto_timer = qemu_new_timer(rt_clock, usb_host_auto_check, NULL);
1506
        if (!usb_auto_timer) {
1507
            return;
1508
        }
1509
    }
1510
    qemu_mod_timer(usb_auto_timer, qemu_get_clock(rt_clock) + 2000);
1511
}
1512

    
1513
/*
1514
 * Autoconnect filter
1515
 * Format:
1516
 *    auto:bus:dev[:vid:pid]
1517
 *    auto:bus.dev[:vid:pid]
1518
 *
1519
 *    bus  - bus number    (dec, * means any)
1520
 *    dev  - device number (dec, * means any)
1521
 *    vid  - vendor id     (hex, * means any)
1522
 *    pid  - product id    (hex, * means any)
1523
 *
1524
 *    See 'lsusb' output.
1525
 */
1526
static int parse_filter(const char *spec, struct USBAutoFilter *f)
1527
{
1528
    enum { BUS, DEV, VID, PID, DONE };
1529
    const char *p = spec;
1530
    int i;
1531

    
1532
    f->bus_num    = 0;
1533
    f->addr       = 0;
1534
    f->vendor_id  = 0;
1535
    f->product_id = 0;
1536

    
1537
    for (i = BUS; i < DONE; i++) {
1538
        p = strpbrk(p, ":.");
1539
        if (!p) {
1540
            break;
1541
        }
1542
        p++;
1543

    
1544
        if (*p == '*') {
1545
            continue;
1546
        }
1547
        switch(i) {
1548
        case BUS: f->bus_num = strtol(p, NULL, 10);    break;
1549
        case DEV: f->addr    = strtol(p, NULL, 10);    break;
1550
        case VID: f->vendor_id  = strtol(p, NULL, 16); break;
1551
        case PID: f->product_id = strtol(p, NULL, 16); break;
1552
        }
1553
    }
1554

    
1555
    if (i < DEV) {
1556
        fprintf(stderr, "husb: invalid auto filter spec %s\n", spec);
1557
        return -1;
1558
    }
1559

    
1560
    return 0;
1561
}
1562

    
1563
/**********************/
1564
/* USB host device info */
1565

    
1566
struct usb_class_info {
1567
    int class;
1568
    const char *class_name;
1569
};
1570

    
1571
static const struct usb_class_info usb_class_info[] = {
1572
    { USB_CLASS_AUDIO, "Audio"},
1573
    { USB_CLASS_COMM, "Communication"},
1574
    { USB_CLASS_HID, "HID"},
1575
    { USB_CLASS_HUB, "Hub" },
1576
    { USB_CLASS_PHYSICAL, "Physical" },
1577
    { USB_CLASS_PRINTER, "Printer" },
1578
    { USB_CLASS_MASS_STORAGE, "Storage" },
1579
    { USB_CLASS_CDC_DATA, "Data" },
1580
    { USB_CLASS_APP_SPEC, "Application Specific" },
1581
    { USB_CLASS_VENDOR_SPEC, "Vendor Specific" },
1582
    { USB_CLASS_STILL_IMAGE, "Still Image" },
1583
    { USB_CLASS_CSCID, "Smart Card" },
1584
    { USB_CLASS_CONTENT_SEC, "Content Security" },
1585
    { -1, NULL }
1586
};
1587

    
1588
static const char *usb_class_str(uint8_t class)
1589
{
1590
    const struct usb_class_info *p;
1591
    for(p = usb_class_info; p->class != -1; p++) {
1592
        if (p->class == class) {
1593
            break;
1594
        }
1595
    }
1596
    return p->class_name;
1597
}
1598

    
1599
static void usb_info_device(Monitor *mon, int bus_num, int addr, int class_id,
1600
                            int vendor_id, int product_id,
1601
                            const char *product_name,
1602
                            int speed)
1603
{
1604
    const char *class_str, *speed_str;
1605

    
1606
    switch(speed) {
1607
    case USB_SPEED_LOW:
1608
        speed_str = "1.5";
1609
        break;
1610
    case USB_SPEED_FULL:
1611
        speed_str = "12";
1612
        break;
1613
    case USB_SPEED_HIGH:
1614
        speed_str = "480";
1615
        break;
1616
    default:
1617
        speed_str = "?";
1618
        break;
1619
    }
1620

    
1621
    monitor_printf(mon, "  Device %d.%d, speed %s Mb/s\n",
1622
                bus_num, addr, speed_str);
1623
    class_str = usb_class_str(class_id);
1624
    if (class_str) {
1625
        monitor_printf(mon, "    %s:", class_str);
1626
    } else {
1627
        monitor_printf(mon, "    Class %02x:", class_id);
1628
    }
1629
    monitor_printf(mon, " USB device %04x:%04x", vendor_id, product_id);
1630
    if (product_name[0] != '\0') {
1631
        monitor_printf(mon, ", %s", product_name);
1632
    }
1633
    monitor_printf(mon, "\n");
1634
}
1635

    
1636
static int usb_host_info_device(void *opaque, int bus_num, int addr,
1637
                                int devpath, int class_id,
1638
                                int vendor_id, int product_id,
1639
                                const char *product_name,
1640
                                int speed)
1641
{
1642
    Monitor *mon = opaque;
1643

    
1644
    usb_info_device(mon, bus_num, addr, class_id, vendor_id, product_id,
1645
                    product_name, speed);
1646
    return 0;
1647
}
1648

    
1649
static void dec2str(int val, char *str, size_t size)
1650
{
1651
    if (val == 0) {
1652
        snprintf(str, size, "*");
1653
    } else {
1654
        snprintf(str, size, "%d", val);
1655
    }
1656
}
1657

    
1658
static void hex2str(int val, char *str, size_t size)
1659
{
1660
    if (val == 0) {
1661
        snprintf(str, size, "*");
1662
    } else {
1663
        snprintf(str, size, "%04x", val);
1664
    }
1665
}
1666

    
1667
void usb_host_info(Monitor *mon)
1668
{
1669
    struct USBAutoFilter *f;
1670
    struct USBHostDevice *s;
1671

    
1672
    usb_host_scan(mon, usb_host_info_device);
1673

    
1674
    if (QTAILQ_EMPTY(&hostdevs)) {
1675
        return;
1676
    }
1677

    
1678
    monitor_printf(mon, "  Auto filters:\n");
1679
    QTAILQ_FOREACH(s, &hostdevs, next) {
1680
        char bus[10], addr[10], vid[10], pid[10];
1681
        f = &s->match;
1682
        dec2str(f->bus_num, bus, sizeof(bus));
1683
        dec2str(f->addr, addr, sizeof(addr));
1684
        hex2str(f->vendor_id, vid, sizeof(vid));
1685
        hex2str(f->product_id, pid, sizeof(pid));
1686
        monitor_printf(mon, "    Device %s.%s ID %s:%s\n",
1687
                       bus, addr, vid, pid);
1688
    }
1689
}