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

P
pbrook 已提交
33
#include "qemu-common.h"
34
#include "qemu-timer.h"
A
aliguori 已提交
35
#include "monitor.h"
36
#include "sysemu.h"
B
bellard 已提交
37 38 39

#include <dirent.h>
#include <sys/ioctl.h>
40
#include <signal.h>
B
bellard 已提交
41

42 43 44
#include <linux/usbdevice_fs.h>
#include <linux/version.h>
#include "hw/usb.h"
B
bellard 已提交
45

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

struct usb_ctrlrequest {
    uint8_t bRequestType;
    uint8_t bRequest;
    uint16_t wValue;
    uint16_t wIndex;
    uint16_t wLength;
};

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

69
//#define DEBUG
70 71

#ifdef DEBUG
M
malc 已提交
72
#define DPRINTF printf
73
#else
M
malc 已提交
74
#define DPRINTF(...)
75
#endif
B
bellard 已提交
76

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

79
#define USBPROCBUS_PATH "/proc/bus/usb"
80
#define PRODUCT_NAME_SZ 32
81
#define MAX_ENDPOINTS 16
82 83 84 85 86 87 88 89 90 91 92
#define USBDEVBUS_PATH "/dev/bus/usb"
#define USBSYSBUS_PATH "/sys/bus/usb"

static char *usb_host_device_path;

#define USB_FS_NONE 0
#define USB_FS_PROC 1
#define USB_FS_DEV 2
#define USB_FS_SYS 3

static int usb_fs_type;
B
bellard 已提交
93

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

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

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

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

B
bellard 已提交
127 128
typedef struct USBHostDevice {
    USBDevice dev;
129 130 131 132 133
    int       fd;

    uint8_t   descr[1024];
    int       descr_len;
    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 142 143

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

147
    QTAILQ_ENTRY(USBHostDevice) next;
B
bellard 已提交
148 149
} USBHostDevice;

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

static int usb_host_close(USBHostDevice *dev);
static int parse_filter(const char *spec, struct USBAutoFilter *f);
static void usb_host_auto_check(void *unused);
155 156
static int usb_host_read_file(char *line, size_t line_size,
                            const char *device_file, const char *device_name);
157

158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177
static int is_isoc(USBHostDevice *s, int ep)
{
    return s->endp_table[ep - 1].type == USBDEVFS_URB_TYPE_ISO;
}

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

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

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

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

188 189 190
    USBPacket     *packet;
    USBHostDevice *hdev;
} AsyncURB;
191

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

197
static void async_free(AsyncURB *aurb)
198
{
199 200
    qemu_free(aurb);
}
201

202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221
static void async_complete_ctrl(USBHostDevice *s, USBPacket *p)
{
    switch(s->ctrl.state) {
    case CTRL_STATE_SETUP:
        if (p->len < s->ctrl.len)
            s->ctrl.len = p->len;
        s->ctrl.state = CTRL_STATE_DATA;
        p->len = 8;
        break;

    case CTRL_STATE_ACK:
        s->ctrl.state = CTRL_STATE_IDLE;
        p->len = 0;
        break;

    default:
        break;
    }
}

222 223 224 225 226 227
static void async_complete(void *opaque)
{
    USBHostDevice *s = opaque;
    AsyncURB *aurb;

    while (1) {
228
        USBPacket *p;
229

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

M
malc 已提交
243
            DPRINTF("husb: async. reap urb failed errno %d\n", errno);
244
            return;
245
        }
246 247 248

        p = aurb->packet;

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

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

            case -EPIPE:
                set_halt(s, p->devep);
263 264
                p->len = USB_RET_STALL;
                break;
265

266 267 268 269 270 271
            default:
                p->len = USB_RET_NAK;
                break;
            }

            usb_packet_complete(p);
272
        }
273 274

        async_free(aurb);
275 276 277
    }
}

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

M
malc 已提交
283
    DPRINTF("husb: async cancel. aurb %p\n", aurb);
284 285 286

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

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

294
static int usb_host_claim_interfaces(USBHostDevice *dev, int configuration)
295 296
{
    int dev_descr_len, config_descr_len;
297
    int interface, nb_interfaces;
298 299 300 301 302
    int ret, i;

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

M
malc 已提交
303
    DPRINTF("husb: claiming interfaces. config %d\n", configuration);
304

305 306
    i = 0;
    dev_descr_len = dev->descr[0];
307
    if (dev_descr_len > dev->descr_len) {
308
        goto fail;
309
    }
310 311 312

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

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

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

325 326
        if (configuration < 0 || configuration == dev->descr[i + 5]) {
            configuration = dev->descr[i + 5];
327
            break;
328
        }
329 330 331 332 333

        i += config_descr_len;
    }

    if (i >= dev->descr_len) {
334 335
        fprintf(stderr,
                "husb: update iface failed. no matching configuration\n");
336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360
        goto fail;
    }
    nb_interfaces = dev->descr[i + 4];

#ifdef USBDEVFS_DISCONNECT
    /* earlier Linux 2.4 do not support that */
    {
        struct usbdevfs_ioctl ctrl;
        for (interface = 0; interface < nb_interfaces; interface++) {
            ctrl.ioctl_code = USBDEVFS_DISCONNECT;
            ctrl.ifno = interface;
            ret = ioctl(dev->fd, USBDEVFS_IOCTL, &ctrl);
            if (ret < 0 && errno != ENODATA) {
                perror("USBDEVFS_DISCONNECT");
                goto fail;
            }
        }
    }
#endif

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

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

373 374 375 376 377 378 379 380 381
    dev->ninterfaces   = nb_interfaces;
    dev->configuration = configuration;
    return 1;
}

static int usb_host_release_interfaces(USBHostDevice *s)
{
    int ret, i;

M
malc 已提交
382
    DPRINTF("husb: releasing interfaces\n");
383 384 385 386 387 388 389 390 391

    for (i = 0; i < s->ninterfaces; i++) {
        ret = ioctl(s->fd, USBDEVFS_RELEASEINTERFACE, &i);
        if (ret < 0) {
            perror("husb: failed to release interface");
            return 0;
        }
    }

392 393 394
    return 1;
}

B
bellard 已提交
395
static void usb_host_handle_reset(USBDevice *dev)
B
bellard 已提交
396
{
397
    USBHostDevice *s = DO_UPCAST(USBHostDevice, dev, dev);
398

M
malc 已提交
399
    DPRINTF("husb: reset device %u.%u\n", s->bus_num, s->addr);
400

B
bellard 已提交
401
    ioctl(s->fd, USBDEVFS_RESET);
402 403

    usb_host_claim_interfaces(s, s->configuration);
404
}
B
bellard 已提交
405

B
bellard 已提交
406 407 408 409
static void usb_host_handle_destroy(USBDevice *dev)
{
    USBHostDevice *s = (USBHostDevice *)dev;

410 411
    usb_host_close(s);
    QTAILQ_REMOVE(&hostdevs, s, next);
412
    qemu_remove_exit_notifier(&s->exit);
B
bellard 已提交
413 414
}

415 416
static int usb_linux_update_endp_table(USBHostDevice *s);

417
static int usb_host_handle_data(USBHostDevice *s, USBPacket *p)
B
bellard 已提交
418
{
419
    struct usbdevfs_urb *urb;
420
    AsyncURB *aurb;
B
bellard 已提交
421 422
    int ret;

423 424 425 426 427
    aurb = async_alloc();
    aurb->hdev   = s;
    aurb->packet = p;

    urb = &aurb->urb;
428

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

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

445 446
    urb->buffer        = p->data;
    urb->buffer_length = p->len;
447

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

459
    urb->usercontext = s;
460

461
    ret = ioctl(s->fd, USBDEVFS_SUBMITURB, urb);
462

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

466
    if (ret < 0) {
M
malc 已提交
467
        DPRINTF("husb: submit failed. errno %d\n", errno);
468
        async_free(aurb);
469 470 471 472 473 474 475 476 477

        switch(errno) {
        case ETIMEDOUT:
            return USB_RET_NAK;
        case EPIPE:
        default:
            return USB_RET_STALL;
        }
    }
478 479

    usb_defer_packet(p, async_cancel, aurb);
480 481 482
    return USB_RET_ASYNC;
}

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

static int usb_host_set_address(USBHostDevice *s, int addr)
{
M
malc 已提交
494
    DPRINTF("husb: ctrl set addr %u\n", addr);
495 496 497 498 499 500 501 502 503
    s->dev.addr = addr;
    return 0;
}

static int usb_host_set_config(USBHostDevice *s, int config)
{
    usb_host_release_interfaces(s);

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

M
malc 已提交
505
    DPRINTF("husb: ctrl set config %d ret %d errno %d\n", config, ret, errno);
506 507

    if (ret < 0) {
508
        return ctrl_error();
509
    }
510 511 512 513 514 515 516 517 518 519 520 521 522
    usb_host_claim_interfaces(s, config);
    return 0;
}

static int usb_host_set_interface(USBHostDevice *s, int iface, int alt)
{
    struct usbdevfs_setinterface si;
    int ret;

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

523 524 525 526 527 528
    DPRINTF("husb: ctrl set iface %d altset %d ret %d errno %d\n",
            iface, alt, ret, errno);

    if (ret < 0) {
        return ctrl_error();
    }
529 530 531 532 533 534 535 536 537
    usb_linux_update_endp_table(s);
    return 0;
}

static int usb_host_handle_control(USBHostDevice *s, USBPacket *p)
{
    struct usbdevfs_urb *urb;
    AsyncURB *aurb;
    int ret, value, index;
J
Jim Paris 已提交
538
    int buffer_len;
539

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

M
malc 已提交
547
    DPRINTF("husb: ctrl type 0x%x req 0x%x val 0x%x index %u len %u\n",
548 549
            s->ctrl.req.bRequestType, s->ctrl.req.bRequest, value, index,
            s->ctrl.len);
550 551 552 553 554 555 556 557 558 559 560 561

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

        case USB_REQ_SET_CONFIGURATION:
            return usb_host_set_config(s, value & 0xff);
        }
    }

    if (s->ctrl.req.bRequestType == 1 &&
562
                  s->ctrl.req.bRequest == USB_REQ_SET_INTERFACE) {
563
        return usb_host_set_interface(s, index, value);
564
    }
565 566 567

    /* The rest are asynchronous */

J
Jim Paris 已提交
568 569
    buffer_len = 8 + s->ctrl.len;
    if (buffer_len > sizeof(s->ctrl.buffer)) {
570 571 572
        fprintf(stderr, "husb: ctrl buffer too small (%u > %zu)\n",
                buffer_len, sizeof(s->ctrl.buffer));
        return USB_RET_STALL;
J
Jim Paris 已提交
573 574
    }

575 576 577 578
    aurb = async_alloc();
    aurb->hdev   = s;
    aurb->packet = p;

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

    urb->type     = USBDEVFS_URB_TYPE_CONTROL;
    urb->endpoint = p->devep;

    urb->buffer        = &s->ctrl.req;
J
Jim Paris 已提交
591
    urb->buffer_length = buffer_len;
592 593 594 595 596

    urb->usercontext = s;

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

M
malc 已提交
597
    DPRINTF("husb: submit ctrl. len %u aurb %p\n", urb->buffer_length, aurb);
598 599

    if (ret < 0) {
M
malc 已提交
600
        DPRINTF("husb: submit failed. errno %d\n", errno);
601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620
        async_free(aurb);

        switch(errno) {
        case ETIMEDOUT:
            return USB_RET_NAK;
        case EPIPE:
        default:
            return USB_RET_STALL;
        }
    }

    usb_defer_packet(p, async_cancel, aurb);
    return USB_RET_ASYNC;
}

static int do_token_setup(USBDevice *dev, USBPacket *p)
{
    USBHostDevice *s = (USBHostDevice *) dev;
    int ret = 0;

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

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

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

636
        if (ret < s->ctrl.len) {
637
            s->ctrl.len = ret;
638
        }
639 640
        s->ctrl.state = CTRL_STATE_DATA;
    } else {
641
        if (s->ctrl.len == 0) {
642
            s->ctrl.state = CTRL_STATE_ACK;
643
        } else {
644
            s->ctrl.state = CTRL_STATE_DATA;
645
        }
646 647 648 649 650 651 652 653 654 655
    }

    return ret;
}

static int do_token_in(USBDevice *dev, USBPacket *p)
{
    USBHostDevice *s = (USBHostDevice *) dev;
    int ret = 0;

656
    if (p->devep != 0) {
657
        return usb_host_handle_data(s, p);
658
    }
659 660 661 662 663

    switch(s->ctrl.state) {
    case CTRL_STATE_ACK:
        if (!(s->ctrl.req.bRequestType & USB_DIR_IN)) {
            ret = usb_host_handle_control(s, p);
664
            if (ret == USB_RET_ASYNC) {
665
                return USB_RET_ASYNC;
666
            }
667 668 669 670 671 672 673 674 675
            s->ctrl.state = CTRL_STATE_IDLE;
            return ret > 0 ? 0 : ret;
        }

        return 0;

    case CTRL_STATE_DATA:
        if (s->ctrl.req.bRequestType & USB_DIR_IN) {
            int len = s->ctrl.len - s->ctrl.offset;
676
            if (len > p->len) {
677
                len = p->len;
678
            }
679 680
            memcpy(p->data, s->ctrl.buffer + s->ctrl.offset, len);
            s->ctrl.offset += len;
681
            if (s->ctrl.offset >= s->ctrl.len) {
682
                s->ctrl.state = CTRL_STATE_ACK;
683
            }
684 685 686 687 688 689 690 691 692 693 694 695 696 697 698
            return len;
        }

        s->ctrl.state = CTRL_STATE_IDLE;
        return USB_RET_STALL;

    default:
        return USB_RET_STALL;
    }
}

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

699
    if (p->devep != 0) {
700
        return usb_host_handle_data(s, p);
701
    }
702 703 704 705 706 707 708 709 710 711 712 713 714 715

    switch(s->ctrl.state) {
    case CTRL_STATE_ACK:
        if (s->ctrl.req.bRequestType & USB_DIR_IN) {
            s->ctrl.state = CTRL_STATE_IDLE;
            /* transfer OK */
        } else {
            /* ignore additional output */
        }
        return 0;

    case CTRL_STATE_DATA:
        if (!(s->ctrl.req.bRequestType & USB_DIR_IN)) {
            int len = s->ctrl.len - s->ctrl.offset;
716
            if (len > p->len) {
717
                len = p->len;
718
            }
719 720
            memcpy(s->ctrl.buffer + s->ctrl.offset, p->data, len);
            s->ctrl.offset += len;
721
            if (s->ctrl.offset >= s->ctrl.len) {
722
                s->ctrl.state = CTRL_STATE_ACK;
723
            }
724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740
            return len;
        }

        s->ctrl.state = CTRL_STATE_IDLE;
        return USB_RET_STALL;

    default:
        return USB_RET_STALL;
    }
}

/*
 * Packet handler.
 * Called by the HC (host controller).
 *
 * Returns length of the transaction or one of the USB_RET_XXX codes.
 */
741
static int usb_host_handle_packet(USBDevice *s, USBPacket *p)
742 743 744 745 746 747 748 749 750 751 752 753 754 755
{
    switch(p->pid) {
    case USB_MSG_ATTACH:
        s->state = USB_STATE_ATTACHED;
        return 0;

    case USB_MSG_DETACH:
        s->state = USB_STATE_NOTATTACHED;
        return 0;

    case USB_MSG_RESET:
        s->remote_wakeup = 0;
        s->addr = 0;
        s->state = USB_STATE_DEFAULT;
756
        s->info->handle_reset(s);
757 758 759 760
        return 0;
    }

    /* Rest of the PIDs must match our address */
761
    if (s->state < USB_STATE_DEFAULT || p->devaddr != s->addr) {
762
        return USB_RET_NODEV;
763
    }
764 765 766 767 768 769 770 771 772 773

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

    case USB_TOKEN_IN:
        return do_token_in(s, p);

    case USB_TOKEN_OUT:
        return do_token_out(s, p);
774

775 776 777 778 779
    default:
        return USB_RET_STALL;
    }
}

780
static int usb_linux_get_configuration(USBHostDevice *s)
781
{
782
    uint8_t configuration;
P
pbrook 已提交
783
    struct usb_ctrltransfer ct;
784
    int ret;
785

786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802
    if (usb_fs_type == USB_FS_SYS) {
        char device_name[32], line[1024];
        int configuration;

        sprintf(device_name, "%d-%d", s->bus_num, s->devpath);

        if (!usb_host_read_file(line, sizeof(line), "bConfigurationValue",
                                device_name)) {
            goto usbdevfs;
        }
        if (sscanf(line, "%d", &configuration) != 1) {
            goto usbdevfs;
        }
        return configuration;
    }

usbdevfs:
803 804 805 806 807 808 809 810 811 812
    ct.bRequestType = USB_DIR_IN;
    ct.bRequest = USB_REQ_GET_CONFIGURATION;
    ct.wValue = 0;
    ct.wIndex = 0;
    ct.wLength = 1;
    ct.data = &configuration;
    ct.timeout = 50;

    ret = ioctl(s->fd, USBDEVFS_CONTROL, &ct);
    if (ret < 0) {
813 814
        perror("usb_linux_get_configuration");
        return -1;
815 816 817
    }

    /* in address state */
818
    if (configuration == 0) {
819
        return -1;
820
    }
821

822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837
    return configuration;
}

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

    i = usb_linux_get_configuration(s);
    if (i < 0)
        return 1;
    configuration = i;

838 839 840 841 842 843 844 845
    /* get the desired configuration, interface, and endpoint descriptors
     * from device description */
    descriptors = &s->descr[18];
    length = s->descr_len - 18;
    i = 0;

    if (descriptors[i + 1] != USB_DT_CONFIG ||
        descriptors[i + 5] != configuration) {
M
malc 已提交
846
        DPRINTF("invalid descriptor data - configuration\n");
847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870
        return 1;
    }
    i += descriptors[i];

    while (i < length) {
        if (descriptors[i + 1] != USB_DT_INTERFACE ||
            (descriptors[i + 1] == USB_DT_INTERFACE &&
             descriptors[i + 4] == 0)) {
            i += descriptors[i];
            continue;
        }

        interface = descriptors[i + 2];

        ct.bRequestType = USB_DIR_IN | USB_RECIP_INTERFACE;
        ct.bRequest = USB_REQ_GET_INTERFACE;
        ct.wValue = 0;
        ct.wIndex = interface;
        ct.wLength = 1;
        ct.data = &alt_interface;
        ct.timeout = 50;

        ret = ioctl(s->fd, USBDEVFS_CONTROL, &ct);
        if (ret < 0) {
J
Jason Wessel 已提交
871
            alt_interface = interface;
872 873 874 875 876 877 878 879 880 881
        }

        /* the current interface descriptor is the active interface
         * and has endpoints */
        if (descriptors[i + 3] != alt_interface) {
            i += descriptors[i];
            continue;
        }

        /* advance to the endpoints */
882
        while (i < length && descriptors[i +1] != USB_DT_ENDPOINT) {
883
            i += descriptors[i];
884
        }
885 886 887 888 889

        if (i >= length)
            break;

        while (i < length) {
890
            if (descriptors[i + 1] != USB_DT_ENDPOINT) {
891
                break;
892
            }
893 894 895 896 897 898 899 900 901 902 903 904 905 906 907

            devep = descriptors[i + 2];
            switch (descriptors[i + 3] & 0x3) {
            case 0x00:
                type = USBDEVFS_URB_TYPE_CONTROL;
                break;
            case 0x01:
                type = USBDEVFS_URB_TYPE_ISO;
                break;
            case 0x02:
                type = USBDEVFS_URB_TYPE_BULK;
                break;
            case 0x03:
                type = USBDEVFS_URB_TYPE_INTERRUPT;
                break;
908 909 910
            default:
                DPRINTF("usb_host: malformed endpoint type\n");
                type = USBDEVFS_URB_TYPE_BULK;
911 912
            }
            s->endp_table[(devep & 0xf) - 1].type = type;
913
            s->endp_table[(devep & 0xf) - 1].halted = 0;
914 915 916 917 918 919 920

            i += descriptors[i];
        }
    }
    return 0;
}

921
static int usb_host_open(USBHostDevice *dev, int bus_num,
922
                         int addr, int devpath, const char *prod_name)
B
bellard 已提交
923
{
924
    int fd = -1, ret;
B
bellard 已提交
925
    struct usbdevfs_connectinfo ci;
B
bellard 已提交
926
    char buf[1024];
927

928
    if (dev->fd != -1) {
929
        goto fail;
930
    }
931
    printf("husb: open device %d.%d\n", bus_num, addr);
932

933 934 935 936 937
    if (!usb_host_device_path) {
        perror("husb: USB Host Device Path not set");
        goto fail;
    }
    snprintf(buf, sizeof(buf), "%s/%03d/%03d", usb_host_device_path,
B
bellard 已提交
938
             bus_num, addr);
939
    fd = open(buf, O_RDWR | O_NONBLOCK);
B
bellard 已提交
940
    if (fd < 0) {
B
bellard 已提交
941
        perror(buf);
942
        goto fail;
B
bellard 已提交
943
    }
M
malc 已提交
944
    DPRINTF("husb: opened %s\n", buf);
B
bellard 已提交
945

946 947
    dev->bus_num = bus_num;
    dev->addr = addr;
948
    dev->devpath = devpath;
949
    dev->fd = fd;
950

951 952 953
    /* read the device description */
    dev->descr_len = read(fd, dev->descr, sizeof(dev->descr));
    if (dev->descr_len <= 0) {
954
        perror("husb: reading device data failed");
B
bellard 已提交
955 956
        goto fail;
    }
957

958
#ifdef DEBUG
B
bellard 已提交
959
    {
960 961
        int x;
        printf("=== begin dumping device descriptor data ===\n");
962
        for (x = 0; x < dev->descr_len; x++) {
963
            printf("%02x ", dev->descr[x]);
964
        }
965
        printf("\n=== end dumping device descriptor data ===\n");
B
bellard 已提交
966
    }
B
bellard 已提交
967 968
#endif

969

970 971
    /*
     * Initial configuration is -1 which makes us claim first
972
     * available config. We used to start with 1, which does not
973
     * always work. I've seen devices where first config starts
974 975
     * with 2.
     */
976
    if (!usb_host_claim_interfaces(dev, -1)) {
977
        goto fail;
978
    }
B
bellard 已提交
979 980 981

    ret = ioctl(fd, USBDEVFS_CONNECTINFO, &ci);
    if (ret < 0) {
982
        perror("usb_host_device_open: USBDEVFS_CONNECTINFO");
B
bellard 已提交
983 984 985
        goto fail;
    }

986
    printf("husb: grabbed usb device %d.%d\n", bus_num, addr);
B
bellard 已提交
987

988
    ret = usb_linux_update_endp_table(dev);
989
    if (ret) {
B
bellard 已提交
990
        goto fail;
991
    }
992

993
    if (ci.slow) {
B
bellard 已提交
994
        dev->dev.speed = USB_SPEED_LOW;
995
    } else {
B
bellard 已提交
996
        dev->dev.speed = USB_SPEED_HIGH;
997
    }
B
bellard 已提交
998

999
    if (!prod_name || prod_name[0] == '\0') {
1000
        snprintf(dev->dev.product_desc, sizeof(dev->dev.product_desc),
1001
                 "host:%d.%d", bus_num, addr);
1002
    } else {
1003
        pstrcpy(dev->dev.product_desc, sizeof(dev->dev.product_desc),
1004
                prod_name);
1005
    }
1006

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

1010 1011
    usb_device_attach(&dev->dev);
    return 0;
1012

1013
fail:
1014
    dev->fd = -1;
1015
    if (fd != -1) {
1016
        close(fd);
1017
    }
1018 1019 1020 1021 1022
    return -1;
}

static int usb_host_close(USBHostDevice *dev)
{
1023
    if (dev->fd == -1) {
1024
        return -1;
1025
    }
1026 1027 1028 1029 1030 1031

    qemu_set_fd_handler(dev->fd, NULL, NULL, NULL);
    dev->closing = 1;
    async_complete(dev);
    dev->closing = 0;
    usb_device_detach(&dev->dev);
1032
    ioctl(dev->fd, USBDEVFS_RESET);
1033 1034 1035 1036 1037
    close(dev->fd);
    dev->fd = -1;
    return 0;
}

1038 1039 1040 1041 1042 1043 1044 1045 1046
static void usb_host_exit_notifier(struct Notifier* n)
{
    USBHostDevice *s = container_of(n, USBHostDevice, exit);

    if (s->fd != -1) {
        ioctl(s->fd, USBDEVFS_RESET);
    }
}

1047 1048 1049 1050 1051 1052 1053
static int usb_host_initfn(USBDevice *dev)
{
    USBHostDevice *s = DO_UPCAST(USBHostDevice, dev, dev);

    dev->auto_attach = 0;
    s->fd = -1;
    QTAILQ_INSERT_TAIL(&hostdevs, s, next);
1054 1055
    s->exit.notify = usb_host_exit_notifier;
    qemu_add_exit_notifier(&s->exit);
1056 1057
    usb_host_auto_check(NULL);
    return 0;
B
bellard 已提交
1058
}
B
bellard 已提交
1059

1060
static struct USBDeviceInfo usb_host_dev_info = {
1061
    .product_desc   = "USB Host Device",
1062
    .qdev.name      = "usb-host",
1063 1064 1065 1066 1067
    .qdev.size      = sizeof(USBHostDevice),
    .init           = usb_host_initfn,
    .handle_packet  = usb_host_handle_packet,
    .handle_reset   = usb_host_handle_reset,
    .handle_destroy = usb_host_handle_destroy,
1068 1069 1070 1071 1072 1073 1074 1075 1076
    .usbdevice_name = "host",
    .usbdevice_init = usb_host_device_open,
    .qdev.props     = (Property[]) {
        DEFINE_PROP_UINT32("hostbus",  USBHostDevice, match.bus_num,    0),
        DEFINE_PROP_UINT32("hostaddr", USBHostDevice, match.addr,       0),
        DEFINE_PROP_HEX32("vendorid",  USBHostDevice, match.vendor_id,  0),
        DEFINE_PROP_HEX32("productid", USBHostDevice, match.product_id, 0),
        DEFINE_PROP_END_OF_LIST(),
    },
1077 1078 1079 1080 1081 1082 1083 1084
};

static void usb_host_register_devices(void)
{
    usb_qdev_register(&usb_host_dev_info);
}
device_init(usb_host_register_devices)

1085 1086
USBDevice *usb_host_device_open(const char *devname)
{
1087
    struct USBAutoFilter filter;
1088 1089 1090
    USBDevice *dev;
    char *p;

1091
    dev = usb_create(NULL /* FIXME */, "usb-host");
1092

1093
    if (strstr(devname, "auto:")) {
1094
        if (parse_filter(devname, &filter) < 0) {
1095
            goto fail;
1096
        }
1097 1098
    } else {
        if ((p = strchr(devname, '.'))) {
1099 1100 1101 1102
            filter.bus_num    = strtoul(devname, NULL, 0);
            filter.addr       = strtoul(p + 1, NULL, 0);
            filter.vendor_id  = 0;
            filter.product_id = 0;
1103
        } else if ((p = strchr(devname, ':'))) {
1104 1105
            filter.bus_num    = 0;
            filter.addr       = 0;
1106
            filter.vendor_id  = strtoul(devname, NULL, 16);
1107
            filter.product_id = strtoul(p + 1, NULL, 16);
1108 1109 1110
        } else {
            goto fail;
        }
1111
    }
1112

1113 1114
    qdev_prop_set_uint32(&dev->qdev, "hostbus",   filter.bus_num);
    qdev_prop_set_uint32(&dev->qdev, "hostaddr",  filter.addr);
1115 1116
    qdev_prop_set_uint32(&dev->qdev, "vendorid",  filter.vendor_id);
    qdev_prop_set_uint32(&dev->qdev, "productid", filter.product_id);
K
Kevin Wolf 已提交
1117
    qdev_init_nofail(&dev->qdev);
1118
    return dev;
1119

1120 1121 1122
fail:
    qdev_free(&dev->qdev);
    return NULL;
1123
}
1124 1125 1126

int usb_host_device_close(const char *devname)
{
1127
#if 0
1128 1129 1130 1131
    char product_name[PRODUCT_NAME_SZ];
    int bus_num, addr;
    USBHostDevice *s;

1132
    if (strstr(devname, "auto:")) {
1133
        return usb_host_auto_del(devname);
1134 1135 1136
    }
    if (usb_host_find_device(&bus_num, &addr, product_name,
                                    sizeof(product_name), devname) < 0) {
1137
        return -1;
1138
    }
1139 1140
    s = hostdev_find(bus_num, addr);
    if (s) {
1141
        usb_device_delete_addr(s->bus_num, s->dev.addr);
1142 1143
        return 0;
    }
1144
#endif
1145 1146 1147

    return -1;
}
1148

B
bellard 已提交
1149
static int get_tag_value(char *buf, int buf_size,
1150
                         const char *str, const char *tag,
B
bellard 已提交
1151 1152 1153 1154 1155
                         const char *stopchars)
{
    const char *p;
    char *q;
    p = strstr(str, tag);
1156
    if (!p) {
B
bellard 已提交
1157
        return -1;
1158
    }
B
bellard 已提交
1159
    p += strlen(tag);
1160
    while (qemu_isspace(*p)) {
B
bellard 已提交
1161
        p++;
1162
    }
B
bellard 已提交
1163 1164
    q = buf;
    while (*p != '\0' && !strchr(stopchars, *p)) {
1165
        if ((q - buf) < (buf_size - 1)) {
B
bellard 已提交
1166
            *q++ = *p;
1167
        }
B
bellard 已提交
1168 1169 1170 1171
        p++;
    }
    *q = '\0';
    return q - buf;
B
bellard 已提交
1172 1173
}

1174 1175 1176 1177 1178 1179
/*
 * Use /proc/bus/usb/devices or /dev/bus/usb/devices file to determine
 * host's USB devices. This is legacy support since many distributions
 * are moving to /sys/bus/usb
 */
static int usb_host_scan_dev(void *opaque, USBScanFunc *func)
B
bellard 已提交
1180
{
1181
    FILE *f = NULL;
B
bellard 已提交
1182
    char line[1024];
B
bellard 已提交
1183
    char buf[1024];
B
bellard 已提交
1184 1185
    int bus_num, addr, speed, device_count, class_id, product_id, vendor_id;
    char product_name[512];
1186
    int ret = 0;
1187

1188 1189 1190 1191 1192 1193
    if (!usb_host_device_path) {
        perror("husb: USB Host Device Path not set");
        goto the_end;
    }
    snprintf(line, sizeof(line), "%s/devices", usb_host_device_path);
    f = fopen(line, "r");
B
bellard 已提交
1194
    if (!f) {
1195 1196
        perror("husb: cannot open devices file");
        goto the_end;
B
bellard 已提交
1197
    }
1198

B
bellard 已提交
1199 1200
    device_count = 0;
    bus_num = addr = speed = class_id = product_id = vendor_id = 0;
B
bellard 已提交
1201
    for(;;) {
1202
        if (fgets(line, sizeof(line), f) == NULL) {
B
bellard 已提交
1203
            break;
1204 1205
        }
        if (strlen(line) > 0) {
B
bellard 已提交
1206
            line[strlen(line) - 1] = '\0';
1207
        }
B
bellard 已提交
1208
        if (line[0] == 'T' && line[1] == ':') {
1209 1210
            if (device_count && (vendor_id || product_id)) {
                /* New device.  Add the previously discovered device.  */
1211
                ret = func(opaque, bus_num, addr, 0, class_id, vendor_id,
B
bellard 已提交
1212
                           product_id, product_name, speed);
1213
                if (ret) {
B
bellard 已提交
1214
                    goto the_end;
1215
                }
B
bellard 已提交
1216
            }
1217
            if (get_tag_value(buf, sizeof(buf), line, "Bus=", " ") < 0) {
B
bellard 已提交
1218
                goto fail;
1219
            }
B
bellard 已提交
1220
            bus_num = atoi(buf);
1221
            if (get_tag_value(buf, sizeof(buf), line, "Dev#=", " ") < 0) {
B
bellard 已提交
1222
                goto fail;
1223
            }
B
bellard 已提交
1224
            addr = atoi(buf);
1225
            if (get_tag_value(buf, sizeof(buf), line, "Spd=", " ") < 0) {
B
bellard 已提交
1226
                goto fail;
1227 1228
            }
            if (!strcmp(buf, "480")) {
B
bellard 已提交
1229
                speed = USB_SPEED_HIGH;
1230
            } else if (!strcmp(buf, "1.5")) {
B
bellard 已提交
1231
                speed = USB_SPEED_LOW;
1232
            } else {
B
bellard 已提交
1233
                speed = USB_SPEED_FULL;
1234
            }
B
bellard 已提交
1235 1236 1237 1238 1239 1240
            product_name[0] = '\0';
            class_id = 0xff;
            device_count++;
            product_id = 0;
            vendor_id = 0;
        } else if (line[0] == 'P' && line[1] == ':') {
1241
            if (get_tag_value(buf, sizeof(buf), line, "Vendor=", " ") < 0) {
B
bellard 已提交
1242
                goto fail;
1243
            }
B
bellard 已提交
1244
            vendor_id = strtoul(buf, NULL, 16);
1245
            if (get_tag_value(buf, sizeof(buf), line, "ProdID=", " ") < 0) {
B
bellard 已提交
1246
                goto fail;
1247
            }
B
bellard 已提交
1248 1249
            product_id = strtoul(buf, NULL, 16);
        } else if (line[0] == 'S' && line[1] == ':') {
1250
            if (get_tag_value(buf, sizeof(buf), line, "Product=", "") < 0) {
B
bellard 已提交
1251
                goto fail;
1252
            }
B
bellard 已提交
1253 1254
            pstrcpy(product_name, sizeof(product_name), buf);
        } else if (line[0] == 'D' && line[1] == ':') {
1255
            if (get_tag_value(buf, sizeof(buf), line, "Cls=", " (") < 0) {
B
bellard 已提交
1256
                goto fail;
1257
            }
B
bellard 已提交
1258
            class_id = strtoul(buf, NULL, 16);
B
bellard 已提交
1259
        }
B
bellard 已提交
1260 1261
    fail: ;
    }
1262 1263
    if (device_count && (vendor_id || product_id)) {
        /* Add the last device.  */
1264
        ret = func(opaque, bus_num, addr, 0, class_id, vendor_id,
B
bellard 已提交
1265
                   product_id, product_name, speed);
B
bellard 已提交
1266
    }
B
bellard 已提交
1267
 the_end:
1268
    if (f) {
1269
        fclose(f);
1270
    }
1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283
    return ret;
}

/*
 * Read sys file-system device file
 *
 * @line address of buffer to put file contents in
 * @line_size size of line
 * @device_file path to device file (printf format string)
 * @device_name device being opened (inserted into device_file)
 *
 * @return 0 failed, 1 succeeded ('line' contains data)
 */
1284 1285
static int usb_host_read_file(char *line, size_t line_size,
                              const char *device_file, const char *device_name)
1286 1287 1288 1289 1290
{
    FILE *f;
    int ret = 0;
    char filename[PATH_MAX];

1291 1292
    snprintf(filename, PATH_MAX, USBSYSBUS_PATH "/devices/%s/%s", device_name,
             device_file);
1293 1294
    f = fopen(filename, "r");
    if (f) {
1295
        ret = fgets(line, line_size, f) != NULL;
1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310
        fclose(f);
    }

    return ret;
}

/*
 * Use /sys/bus/usb/devices/ directory to determine host's USB
 * devices.
 *
 * This code is based on Robert Schiele's original patches posted to
 * the Novell bug-tracker https://bugzilla.novell.com/show_bug.cgi?id=241950
 */
static int usb_host_scan_sys(void *opaque, USBScanFunc *func)
{
1311
    DIR *dir = NULL;
1312
    char line[1024];
1313
    int bus_num, addr, devpath, speed, class_id, product_id, vendor_id;
1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326
    int ret = 0;
    char product_name[512];
    struct dirent *de;

    dir = opendir(USBSYSBUS_PATH "/devices");
    if (!dir) {
        perror("husb: cannot open devices directory");
        goto the_end;
    }

    while ((de = readdir(dir))) {
        if (de->d_name[0] != '.' && !strchr(de->d_name, ':')) {
            char *tmpstr = de->d_name;
1327
            if (!strncmp(de->d_name, "usb", 3)) {
1328
                tmpstr += 3;
1329
            }
1330 1331 1332
            if (sscanf(tmpstr, "%d-%d", &bus_num, &devpath) < 1) {
                goto the_end;
            }
1333

1334
            if (!usb_host_read_file(line, sizeof(line), "devnum", de->d_name)) {
1335
                goto the_end;
1336 1337
            }
            if (sscanf(line, "%d", &addr) != 1) {
1338
                goto the_end;
1339
            }
1340
            if (!usb_host_read_file(line, sizeof(line), "bDeviceClass",
1341
                                    de->d_name)) {
1342
                goto the_end;
1343 1344
            }
            if (sscanf(line, "%x", &class_id) != 1) {
1345
                goto the_end;
1346
            }
1347

1348 1349
            if (!usb_host_read_file(line, sizeof(line), "idVendor",
                                    de->d_name)) {
1350
                goto the_end;
1351 1352
            }
            if (sscanf(line, "%x", &vendor_id) != 1) {
1353
                goto the_end;
1354
            }
1355
            if (!usb_host_read_file(line, sizeof(line), "idProduct",
1356
                                    de->d_name)) {
1357
                goto the_end;
1358 1359
            }
            if (sscanf(line, "%x", &product_id) != 1) {
1360
                goto the_end;
1361
            }
1362 1363
            if (!usb_host_read_file(line, sizeof(line), "product",
                                    de->d_name)) {
1364 1365
                *product_name = 0;
            } else {
1366
                if (strlen(line) > 0) {
1367
                    line[strlen(line) - 1] = '\0';
1368
                }
1369 1370 1371
                pstrcpy(product_name, sizeof(product_name), line);
            }

1372
            if (!usb_host_read_file(line, sizeof(line), "speed", de->d_name)) {
1373
                goto the_end;
1374 1375
            }
            if (!strcmp(line, "480\n")) {
1376
                speed = USB_SPEED_HIGH;
1377
            } else if (!strcmp(line, "1.5\n")) {
1378
                speed = USB_SPEED_LOW;
1379
            } else {
1380
                speed = USB_SPEED_FULL;
1381
            }
1382

1383
            ret = func(opaque, bus_num, addr, devpath, class_id, vendor_id,
1384
                       product_id, product_name, speed);
1385
            if (ret) {
1386
                goto the_end;
1387
            }
1388 1389 1390
        }
    }
 the_end:
1391
    if (dir) {
1392
        closedir(dir);
1393
    }
1394 1395 1396 1397 1398 1399 1400 1401 1402
    return ret;
}

/*
 * Determine how to access the host's USB devices and call the
 * specific support function.
 */
static int usb_host_scan(void *opaque, USBScanFunc *func)
{
A
aliguori 已提交
1403
    Monitor *mon = cur_mon;
1404 1405
    FILE *f = NULL;
    DIR *dir = NULL;
1406 1407 1408 1409 1410 1411
    int ret = 0;
    const char *fs_type[] = {"unknown", "proc", "dev", "sys"};
    char devpath[PATH_MAX];

    /* only check the host once */
    if (!usb_fs_type) {
1412 1413 1414 1415 1416 1417
        dir = opendir(USBSYSBUS_PATH "/devices");
        if (dir) {
            /* devices found in /dev/bus/usb/ (yes - not a mistake!) */
            strcpy(devpath, USBDEVBUS_PATH);
            usb_fs_type = USB_FS_SYS;
            closedir(dir);
M
malc 已提交
1418
            DPRINTF(USBDBG_DEVOPENED, USBSYSBUS_PATH);
1419 1420
            goto found_devices;
        }
1421 1422 1423 1424 1425 1426
        f = fopen(USBPROCBUS_PATH "/devices", "r");
        if (f) {
            /* devices found in /proc/bus/usb/ */
            strcpy(devpath, USBPROCBUS_PATH);
            usb_fs_type = USB_FS_PROC;
            fclose(f);
M
malc 已提交
1427
            DPRINTF(USBDBG_DEVOPENED, USBPROCBUS_PATH);
1428
            goto found_devices;
1429 1430 1431
        }
        /* try additional methods if an access method hasn't been found yet */
        f = fopen(USBDEVBUS_PATH "/devices", "r");
1432
        if (f) {
1433 1434 1435 1436
            /* devices found in /dev/bus/usb/ */
            strcpy(devpath, USBDEVBUS_PATH);
            usb_fs_type = USB_FS_DEV;
            fclose(f);
M
malc 已提交
1437
            DPRINTF(USBDBG_DEVOPENED, USBDEVBUS_PATH);
1438
            goto found_devices;
1439
        }
1440
    found_devices:
1441
        if (!usb_fs_type) {
1442
            if (mon) {
1443
                monitor_printf(mon, "husb: unable to access USB devices\n");
1444
            }
1445
            return -ENOENT;
1446 1447 1448 1449
        }

        /* the module setting (used later for opening devices) */
        usb_host_device_path = qemu_mallocz(strlen(devpath)+1);
1450
        strcpy(usb_host_device_path, devpath);
1451
        if (mon) {
1452 1453
            monitor_printf(mon, "husb: using %s file-system with %s\n",
                           fs_type[usb_fs_type], usb_host_device_path);
1454
        }
1455 1456 1457 1458 1459 1460 1461 1462 1463 1464
    }

    switch (usb_fs_type) {
    case USB_FS_PROC:
    case USB_FS_DEV:
        ret = usb_host_scan_dev(opaque, func);
        break;
    case USB_FS_SYS:
        ret = usb_host_scan_sys(opaque, func);
        break;
1465 1466 1467
    default:
        ret = -EINVAL;
        break;
1468
    }
B
bellard 已提交
1469
    return ret;
B
bellard 已提交
1470 1471
}

1472 1473
static QEMUTimer *usb_auto_timer;

1474
static int usb_host_auto_scan(void *opaque, int bus_num, int addr, int devpath,
1475 1476
                              int class_id, int vendor_id, int product_id,
                              const char *product_name, int speed)
1477 1478
{
    struct USBAutoFilter *f;
1479
    struct USBHostDevice *s;
1480 1481 1482 1483 1484

    /* Ignore hubs */
    if (class_id == 9)
        return 0;

1485 1486 1487
    QTAILQ_FOREACH(s, &hostdevs, next) {
        f = &s->match;

1488
        if (f->bus_num > 0 && f->bus_num != bus_num) {
1489
            continue;
1490 1491
        }
        if (f->addr > 0 && f->addr != addr) {
1492
            continue;
1493
        }
1494

1495
        if (f->vendor_id > 0 && f->vendor_id != vendor_id) {
1496
            continue;
1497
        }
1498

1499
        if (f->product_id > 0 && f->product_id != product_id) {
1500
            continue;
1501
        }
1502 1503
        /* We got a match */

1504
        /* Already attached ? */
1505
        if (s->fd != -1) {
1506
            return 0;
1507
        }
M
malc 已提交
1508
        DPRINTF("husb: auto open: bus_num %d addr %d\n", bus_num, addr);
1509

1510
        usb_host_open(s, bus_num, addr, devpath, product_name);
1511 1512 1513 1514 1515
    }

    return 0;
}

1516
static void usb_host_auto_check(void *unused)
1517
{
1518 1519 1520
    struct USBHostDevice *s;
    int unconnected = 0;

1521
    usb_host_scan(NULL, usb_host_auto_scan);
1522 1523

    QTAILQ_FOREACH(s, &hostdevs, next) {
1524
        if (s->fd == -1) {
1525
            unconnected++;
1526
        }
1527 1528 1529 1530
    }

    if (unconnected == 0) {
        /* nothing to watch */
1531
        if (usb_auto_timer) {
1532
            qemu_del_timer(usb_auto_timer);
1533
        }
1534 1535 1536 1537
        return;
    }

    if (!usb_auto_timer) {
1538
        usb_auto_timer = qemu_new_timer_ms(rt_clock, usb_host_auto_check, NULL);
1539
        if (!usb_auto_timer) {
1540
            return;
1541
        }
1542
    }
1543
    qemu_mod_timer(usb_auto_timer, qemu_get_clock_ms(rt_clock) + 2000);
1544 1545 1546
}

/*
1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557
 * Autoconnect filter
 * Format:
 *    auto:bus:dev[:vid:pid]
 *    auto:bus.dev[:vid:pid]
 *
 *    bus  - bus number    (dec, * means any)
 *    dev  - device number (dec, * means any)
 *    vid  - vendor id     (hex, * means any)
 *    pid  - product id    (hex, * means any)
 *
 *    See 'lsusb' output.
1558
 */
1559
static int parse_filter(const char *spec, struct USBAutoFilter *f)
1560
{
1561 1562 1563 1564
    enum { BUS, DEV, VID, PID, DONE };
    const char *p = spec;
    int i;

1565 1566 1567 1568
    f->bus_num    = 0;
    f->addr       = 0;
    f->vendor_id  = 0;
    f->product_id = 0;
1569 1570

    for (i = BUS; i < DONE; i++) {
1571 1572 1573 1574
        p = strpbrk(p, ":.");
        if (!p) {
            break;
        }
1575 1576
        p++;

1577 1578 1579
        if (*p == '*') {
            continue;
        }
1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595
        switch(i) {
        case BUS: f->bus_num = strtol(p, NULL, 10);    break;
        case DEV: f->addr    = strtol(p, NULL, 10);    break;
        case VID: f->vendor_id  = strtol(p, NULL, 16); break;
        case PID: f->product_id = strtol(p, NULL, 16); break;
        }
    }

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

    return 0;
}

B
bellard 已提交
1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615
/**********************/
/* USB host device info */

struct usb_class_info {
    int class;
    const char *class_name;
};

static const struct usb_class_info usb_class_info[] = {
    { USB_CLASS_AUDIO, "Audio"},
    { USB_CLASS_COMM, "Communication"},
    { USB_CLASS_HID, "HID"},
    { USB_CLASS_HUB, "Hub" },
    { USB_CLASS_PHYSICAL, "Physical" },
    { USB_CLASS_PRINTER, "Printer" },
    { USB_CLASS_MASS_STORAGE, "Storage" },
    { USB_CLASS_CDC_DATA, "Data" },
    { USB_CLASS_APP_SPEC, "Application Specific" },
    { USB_CLASS_VENDOR_SPEC, "Vendor Specific" },
    { USB_CLASS_STILL_IMAGE, "Still Image" },
1616
    { USB_CLASS_CSCID, "Smart Card" },
B
bellard 已提交
1617 1618 1619 1620 1621
    { USB_CLASS_CONTENT_SEC, "Content Security" },
    { -1, NULL }
};

static const char *usb_class_str(uint8_t class)
B
bellard 已提交
1622
{
B
bellard 已提交
1623 1624
    const struct usb_class_info *p;
    for(p = usb_class_info; p->class != -1; p++) {
1625
        if (p->class == class) {
B
bellard 已提交
1626
            break;
1627
        }
B
bellard 已提交
1628
    }
B
bellard 已提交
1629 1630 1631
    return p->class_name;
}

1632
static void usb_info_device(Monitor *mon, int bus_num, int addr, int class_id,
1633 1634 1635
                            int vendor_id, int product_id,
                            const char *product_name,
                            int speed)
B
bellard 已提交
1636 1637 1638 1639
{
    const char *class_str, *speed_str;

    switch(speed) {
1640 1641
    case USB_SPEED_LOW:
        speed_str = "1.5";
B
bellard 已提交
1642
        break;
1643 1644
    case USB_SPEED_FULL:
        speed_str = "12";
B
bellard 已提交
1645
        break;
1646 1647
    case USB_SPEED_HIGH:
        speed_str = "480";
B
bellard 已提交
1648 1649
        break;
    default:
1650
        speed_str = "?";
B
bellard 已提交
1651 1652 1653
        break;
    }

A
aliguori 已提交
1654
    monitor_printf(mon, "  Device %d.%d, speed %s Mb/s\n",
B
bellard 已提交
1655 1656
                bus_num, addr, speed_str);
    class_str = usb_class_str(class_id);
1657
    if (class_str) {
A
aliguori 已提交
1658
        monitor_printf(mon, "    %s:", class_str);
1659
    } else {
A
aliguori 已提交
1660
        monitor_printf(mon, "    Class %02x:", class_id);
1661
    }
A
aliguori 已提交
1662
    monitor_printf(mon, " USB device %04x:%04x", vendor_id, product_id);
1663
    if (product_name[0] != '\0') {
A
aliguori 已提交
1664
        monitor_printf(mon, ", %s", product_name);
1665
    }
A
aliguori 已提交
1666
    monitor_printf(mon, "\n");
B
bellard 已提交
1667 1668
}

1669
static int usb_host_info_device(void *opaque, int bus_num, int addr,
1670
                                int devpath, int class_id,
1671
                                int vendor_id, int product_id,
B
bellard 已提交
1672 1673 1674
                                const char *product_name,
                                int speed)
{
1675 1676 1677
    Monitor *mon = opaque;

    usb_info_device(mon, bus_num, addr, class_id, vendor_id, product_id,
B
bellard 已提交
1678 1679 1680 1681
                    product_name, speed);
    return 0;
}

A
aliguori 已提交
1682
static void dec2str(int val, char *str, size_t size)
1683
{
1684
    if (val == 0) {
A
aliguori 已提交
1685
        snprintf(str, size, "*");
1686 1687 1688
    } else {
        snprintf(str, size, "%d", val);
    }
1689 1690
}

A
aliguori 已提交
1691
static void hex2str(int val, char *str, size_t size)
1692
{
1693
    if (val == 0) {
A
aliguori 已提交
1694
        snprintf(str, size, "*");
1695
    } else {
1696
        snprintf(str, size, "%04x", val);
1697
    }
1698 1699
}

A
aliguori 已提交
1700
void usb_host_info(Monitor *mon)
B
bellard 已提交
1701
{
1702
    struct USBAutoFilter *f;
1703
    struct USBHostDevice *s;
1704

1705
    usb_host_scan(mon, usb_host_info_device);
1706

1707
    if (QTAILQ_EMPTY(&hostdevs)) {
1708
        return;
1709 1710
    }

1711 1712
    monitor_printf(mon, "  Auto filters:\n");
    QTAILQ_FOREACH(s, &hostdevs, next) {
1713
        char bus[10], addr[10], vid[10], pid[10];
1714
        f = &s->match;
A
aliguori 已提交
1715 1716 1717 1718
        dec2str(f->bus_num, bus, sizeof(bus));
        dec2str(f->addr, addr, sizeof(addr));
        hex2str(f->vendor_id, vid, sizeof(vid));
        hex2str(f->product_id, pid, sizeof(pid));
A
aliguori 已提交
1719 1720
        monitor_printf(mon, "    Device %s.%s ID %s:%s\n",
                       bus, addr, vid, pid);
1721
    }
B
bellard 已提交
1722
}