qemu/hw/usb/host-libusb.c
<<
>>
Prefs
   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 * (c) 2012 Gerd Hoffmann <kraxel@redhat.com>
  15 *      Completely rewritten to use libusb instead of usbfs ioctls.
  16 *
  17 * Permission is hereby granted, free of charge, to any person obtaining a copy
  18 * of this software and associated documentation files (the "Software"), to deal
  19 * in the Software without restriction, including without limitation the rights
  20 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  21 * copies of the Software, and to permit persons to whom the Software is
  22 * furnished to do so, subject to the following conditions:
  23 *
  24 * The above copyright notice and this permission notice shall be included in
  25 * all copies or substantial portions of the Software.
  26 *
  27 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  28 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  29 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
  30 * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  31 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  32 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  33 * THE SOFTWARE.
  34 */
  35
  36#include "qemu/osdep.h"
  37#ifndef CONFIG_WIN32
  38#include <poll.h>
  39#endif
  40#include <libusb.h>
  41
  42#include "qapi/error.h"
  43#include "migration/vmstate.h"
  44#include "monitor/monitor.h"
  45#include "qemu/error-report.h"
  46#include "qemu/main-loop.h"
  47#include "qemu/module.h"
  48#include "sysemu/runstate.h"
  49#include "sysemu/sysemu.h"
  50#include "trace.h"
  51
  52#include "hw/qdev-properties.h"
  53#include "hw/usb.h"
  54
  55/* ------------------------------------------------------------------------ */
  56
  57#define TYPE_USB_HOST_DEVICE "usb-host"
  58#define USB_HOST_DEVICE(obj) \
  59     OBJECT_CHECK(USBHostDevice, (obj), TYPE_USB_HOST_DEVICE)
  60
  61typedef struct USBHostDevice USBHostDevice;
  62typedef struct USBHostRequest USBHostRequest;
  63typedef struct USBHostIsoXfer USBHostIsoXfer;
  64typedef struct USBHostIsoRing USBHostIsoRing;
  65
  66struct USBAutoFilter {
  67    uint32_t bus_num;
  68    uint32_t addr;
  69    char     *port;
  70    uint32_t vendor_id;
  71    uint32_t product_id;
  72};
  73
  74enum USBHostDeviceOptions {
  75    USB_HOST_OPT_PIPELINE,
  76};
  77
  78struct USBHostDevice {
  79    USBDevice parent_obj;
  80
  81    /* properties */
  82    struct USBAutoFilter             match;
  83    int32_t                          bootindex;
  84    uint32_t                         iso_urb_count;
  85    uint32_t                         iso_urb_frames;
  86    uint32_t                         options;
  87    uint32_t                         loglevel;
  88    bool                             needs_autoscan;
  89    bool                             allow_one_guest_reset;
  90    bool                             allow_all_guest_resets;
  91
  92    /* state */
  93    QTAILQ_ENTRY(USBHostDevice)      next;
  94    int                              seen, errcount;
  95    int                              bus_num;
  96    int                              addr;
  97    char                             port[16];
  98
  99    libusb_device                    *dev;
 100    libusb_device_handle             *dh;
 101    struct libusb_device_descriptor  ddesc;
 102
 103    struct {
 104        bool                         detached;
 105        bool                         claimed;
 106    } ifs[USB_MAX_INTERFACES];
 107
 108    /* callbacks & friends */
 109    QEMUBH                           *bh_nodev;
 110    QEMUBH                           *bh_postld;
 111    bool                             bh_postld_pending;
 112    Notifier                         exit;
 113
 114    /* request queues */
 115    QTAILQ_HEAD(, USBHostRequest)    requests;
 116    QTAILQ_HEAD(, USBHostIsoRing)    isorings;
 117};
 118
 119struct USBHostRequest {
 120    USBHostDevice                    *host;
 121    USBPacket                        *p;
 122    bool                             in;
 123    struct libusb_transfer           *xfer;
 124    unsigned char                    *buffer;
 125    unsigned char                    *cbuf;
 126    unsigned int                     clen;
 127    bool                             usb3ep0quirk;
 128    QTAILQ_ENTRY(USBHostRequest)     next;
 129};
 130
 131struct USBHostIsoXfer {
 132    USBHostIsoRing                   *ring;
 133    struct libusb_transfer           *xfer;
 134    bool                             copy_complete;
 135    unsigned int                     packet;
 136    QTAILQ_ENTRY(USBHostIsoXfer)     next;
 137};
 138
 139struct USBHostIsoRing {
 140    USBHostDevice                    *host;
 141    USBEndpoint                      *ep;
 142    QTAILQ_HEAD(, USBHostIsoXfer)    unused;
 143    QTAILQ_HEAD(, USBHostIsoXfer)    inflight;
 144    QTAILQ_HEAD(, USBHostIsoXfer)    copy;
 145    QTAILQ_ENTRY(USBHostIsoRing)     next;
 146};
 147
 148static QTAILQ_HEAD(, USBHostDevice) hostdevs =
 149    QTAILQ_HEAD_INITIALIZER(hostdevs);
 150
 151static void usb_host_auto_check(void *unused);
 152static void usb_host_release_interfaces(USBHostDevice *s);
 153static void usb_host_nodev(USBHostDevice *s);
 154static void usb_host_detach_kernel(USBHostDevice *s);
 155static void usb_host_attach_kernel(USBHostDevice *s);
 156
 157/* ------------------------------------------------------------------------ */
 158
 159#ifndef LIBUSB_LOG_LEVEL_WARNING /* older libusb didn't define these */
 160#define LIBUSB_LOG_LEVEL_WARNING 2
 161#endif
 162
 163/* ------------------------------------------------------------------------ */
 164
 165#define CONTROL_TIMEOUT  10000        /* 10 sec    */
 166#define BULK_TIMEOUT         0        /* unlimited */
 167#define INTR_TIMEOUT         0        /* unlimited */
 168
 169#ifndef LIBUSB_API_VERSION
 170# define LIBUSB_API_VERSION LIBUSBX_API_VERSION
 171#endif
 172#if LIBUSB_API_VERSION >= 0x01000103
 173# define HAVE_STREAMS 1
 174#endif
 175
 176static const char *speed_name[] = {
 177    [LIBUSB_SPEED_UNKNOWN] = "?",
 178    [LIBUSB_SPEED_LOW]     = "1.5",
 179    [LIBUSB_SPEED_FULL]    = "12",
 180    [LIBUSB_SPEED_HIGH]    = "480",
 181    [LIBUSB_SPEED_SUPER]   = "5000",
 182};
 183
 184static const unsigned int speed_map[] = {
 185    [LIBUSB_SPEED_LOW]     = USB_SPEED_LOW,
 186    [LIBUSB_SPEED_FULL]    = USB_SPEED_FULL,
 187    [LIBUSB_SPEED_HIGH]    = USB_SPEED_HIGH,
 188    [LIBUSB_SPEED_SUPER]   = USB_SPEED_SUPER,
 189};
 190
 191static const unsigned int status_map[] = {
 192    [LIBUSB_TRANSFER_COMPLETED] = USB_RET_SUCCESS,
 193    [LIBUSB_TRANSFER_ERROR]     = USB_RET_IOERROR,
 194    [LIBUSB_TRANSFER_TIMED_OUT] = USB_RET_IOERROR,
 195    [LIBUSB_TRANSFER_CANCELLED] = USB_RET_IOERROR,
 196    [LIBUSB_TRANSFER_STALL]     = USB_RET_STALL,
 197    [LIBUSB_TRANSFER_NO_DEVICE] = USB_RET_NODEV,
 198    [LIBUSB_TRANSFER_OVERFLOW]  = USB_RET_BABBLE,
 199};
 200
 201static const char *err_names[] = {
 202    [-LIBUSB_ERROR_IO]               = "IO",
 203    [-LIBUSB_ERROR_INVALID_PARAM]    = "INVALID_PARAM",
 204    [-LIBUSB_ERROR_ACCESS]           = "ACCESS",
 205    [-LIBUSB_ERROR_NO_DEVICE]        = "NO_DEVICE",
 206    [-LIBUSB_ERROR_NOT_FOUND]        = "NOT_FOUND",
 207    [-LIBUSB_ERROR_BUSY]             = "BUSY",
 208    [-LIBUSB_ERROR_TIMEOUT]          = "TIMEOUT",
 209    [-LIBUSB_ERROR_OVERFLOW]         = "OVERFLOW",
 210    [-LIBUSB_ERROR_PIPE]             = "PIPE",
 211    [-LIBUSB_ERROR_INTERRUPTED]      = "INTERRUPTED",
 212    [-LIBUSB_ERROR_NO_MEM]           = "NO_MEM",
 213    [-LIBUSB_ERROR_NOT_SUPPORTED]    = "NOT_SUPPORTED",
 214    [-LIBUSB_ERROR_OTHER]            = "OTHER",
 215};
 216
 217static libusb_context *ctx;
 218static uint32_t loglevel;
 219
 220#ifndef CONFIG_WIN32
 221
 222static void usb_host_handle_fd(void *opaque)
 223{
 224    struct timeval tv = { 0, 0 };
 225    libusb_handle_events_timeout(ctx, &tv);
 226}
 227
 228static void usb_host_add_fd(int fd, short events, void *user_data)
 229{
 230    qemu_set_fd_handler(fd,
 231                        (events & POLLIN)  ? usb_host_handle_fd : NULL,
 232                        (events & POLLOUT) ? usb_host_handle_fd : NULL,
 233                        ctx);
 234}
 235
 236static void usb_host_del_fd(int fd, void *user_data)
 237{
 238    qemu_set_fd_handler(fd, NULL, NULL, NULL);
 239}
 240
 241#endif /* !CONFIG_WIN32 */
 242
 243static int usb_host_init(void)
 244{
 245#ifndef CONFIG_WIN32
 246    const struct libusb_pollfd **poll;
 247#endif
 248    int rc;
 249
 250    if (ctx) {
 251        return 0;
 252    }
 253    rc = libusb_init(&ctx);
 254    if (rc != 0) {
 255        return -1;
 256    }
 257#if LIBUSB_API_VERSION >= 0x01000106
 258    libusb_set_option(ctx, LIBUSB_OPTION_LOG_LEVEL, loglevel);
 259#else
 260    libusb_set_debug(ctx, loglevel);
 261#endif
 262#ifdef CONFIG_WIN32
 263    /* FIXME: add support for Windows. */
 264#else
 265    libusb_set_pollfd_notifiers(ctx, usb_host_add_fd,
 266                                usb_host_del_fd,
 267                                ctx);
 268    poll = libusb_get_pollfds(ctx);
 269    if (poll) {
 270        int i;
 271        for (i = 0; poll[i] != NULL; i++) {
 272            usb_host_add_fd(poll[i]->fd, poll[i]->events, ctx);
 273        }
 274    }
 275    free(poll);
 276#endif
 277    return 0;
 278}
 279
 280static int usb_host_get_port(libusb_device *dev, char *port, size_t len)
 281{
 282    uint8_t path[7];
 283    size_t off;
 284    int rc, i;
 285
 286#if LIBUSB_API_VERSION >= 0x01000102
 287    rc = libusb_get_port_numbers(dev, path, 7);
 288#else
 289    rc = libusb_get_port_path(ctx, dev, path, 7);
 290#endif
 291    if (rc < 0) {
 292        return 0;
 293    }
 294    off = snprintf(port, len, "%d", path[0]);
 295    for (i = 1; i < rc; i++) {
 296        off += snprintf(port+off, len-off, ".%d", path[i]);
 297    }
 298    return off;
 299}
 300
 301static void usb_host_libusb_error(const char *func, int rc)
 302{
 303    const char *errname;
 304
 305    if (rc >= 0) {
 306        return;
 307    }
 308
 309    if (-rc < ARRAY_SIZE(err_names) && err_names[-rc]) {
 310        errname = err_names[-rc];
 311    } else {
 312        errname = "?";
 313    }
 314    error_report("%s: %d [%s]", func, rc, errname);
 315}
 316
 317/* ------------------------------------------------------------------------ */
 318
 319static bool usb_host_use_combining(USBEndpoint *ep)
 320{
 321    int type;
 322
 323    if (!ep->pipeline) {
 324        return false;
 325    }
 326    if (ep->pid != USB_TOKEN_IN) {
 327        return false;
 328    }
 329    type = usb_ep_get_type(ep->dev, ep->pid, ep->nr);
 330    if (type != USB_ENDPOINT_XFER_BULK) {
 331        return false;
 332    }
 333    return true;
 334}
 335
 336/* ------------------------------------------------------------------------ */
 337
 338static USBHostRequest *usb_host_req_alloc(USBHostDevice *s, USBPacket *p,
 339                                          bool in, size_t bufsize)
 340{
 341    USBHostRequest *r = g_new0(USBHostRequest, 1);
 342
 343    r->host = s;
 344    r->p = p;
 345    r->in = in;
 346    r->xfer = libusb_alloc_transfer(0);
 347    if (bufsize) {
 348        r->buffer = g_malloc(bufsize);
 349    }
 350    QTAILQ_INSERT_TAIL(&s->requests, r, next);
 351    return r;
 352}
 353
 354static void usb_host_req_free(USBHostRequest *r)
 355{
 356    if (r->host) {
 357        QTAILQ_REMOVE(&r->host->requests, r, next);
 358    }
 359    libusb_free_transfer(r->xfer);
 360    g_free(r->buffer);
 361    g_free(r);
 362}
 363
 364static USBHostRequest *usb_host_req_find(USBHostDevice *s, USBPacket *p)
 365{
 366    USBHostRequest *r;
 367
 368    QTAILQ_FOREACH(r, &s->requests, next) {
 369        if (r->p == p) {
 370            return r;
 371        }
 372    }
 373    return NULL;
 374}
 375
 376static void LIBUSB_CALL usb_host_req_complete_ctrl(struct libusb_transfer *xfer)
 377{
 378    USBHostRequest *r = xfer->user_data;
 379    USBHostDevice  *s = r->host;
 380    bool disconnect = (xfer->status == LIBUSB_TRANSFER_NO_DEVICE);
 381
 382    if (r->p == NULL) {
 383        goto out; /* request was canceled */
 384    }
 385
 386    r->p->status = status_map[xfer->status];
 387    r->p->actual_length = xfer->actual_length;
 388    if (r->in && xfer->actual_length) {
 389        memcpy(r->cbuf, r->buffer + 8, xfer->actual_length);
 390
 391        /* Fix up USB-3 ep0 maxpacket size to allow superspeed connected devices
 392         * to work redirected to a not superspeed capable hcd */
 393        if (r->usb3ep0quirk && xfer->actual_length >= 18 &&
 394            r->cbuf[7] == 9) {
 395            r->cbuf[7] = 64;
 396        }
 397    }
 398    trace_usb_host_req_complete(s->bus_num, s->addr, r->p,
 399                                r->p->status, r->p->actual_length);
 400    usb_generic_async_ctrl_complete(USB_DEVICE(s), r->p);
 401
 402out:
 403    usb_host_req_free(r);
 404    if (disconnect) {
 405        usb_host_nodev(s);
 406    }
 407}
 408
 409static void LIBUSB_CALL usb_host_req_complete_data(struct libusb_transfer *xfer)
 410{
 411    USBHostRequest *r = xfer->user_data;
 412    USBHostDevice  *s = r->host;
 413    bool disconnect = (xfer->status == LIBUSB_TRANSFER_NO_DEVICE);
 414
 415    if (r->p == NULL) {
 416        goto out; /* request was canceled */
 417    }
 418
 419    r->p->status = status_map[xfer->status];
 420    if (r->in && xfer->actual_length) {
 421        usb_packet_copy(r->p, r->buffer, xfer->actual_length);
 422    }
 423    trace_usb_host_req_complete(s->bus_num, s->addr, r->p,
 424                                r->p->status, r->p->actual_length);
 425    if (usb_host_use_combining(r->p->ep)) {
 426        usb_combined_input_packet_complete(USB_DEVICE(s), r->p);
 427    } else {
 428        usb_packet_complete(USB_DEVICE(s), r->p);
 429    }
 430
 431out:
 432    usb_host_req_free(r);
 433    if (disconnect) {
 434        usb_host_nodev(s);
 435    }
 436}
 437
 438static void usb_host_req_abort(USBHostRequest *r)
 439{
 440    USBHostDevice  *s = r->host;
 441    bool inflight = (r->p && r->p->state == USB_PACKET_ASYNC);
 442
 443    if (inflight) {
 444        r->p->status = USB_RET_NODEV;
 445        trace_usb_host_req_complete(s->bus_num, s->addr, r->p,
 446                                    r->p->status, r->p->actual_length);
 447        if (r->p->ep->nr == 0) {
 448            usb_generic_async_ctrl_complete(USB_DEVICE(s), r->p);
 449        } else {
 450            usb_packet_complete(USB_DEVICE(s), r->p);
 451        }
 452        r->p = NULL;
 453    }
 454
 455    QTAILQ_REMOVE(&r->host->requests, r, next);
 456    r->host = NULL;
 457
 458    if (inflight) {
 459        libusb_cancel_transfer(r->xfer);
 460    }
 461}
 462
 463/* ------------------------------------------------------------------------ */
 464
 465static void LIBUSB_CALL
 466usb_host_req_complete_iso(struct libusb_transfer *transfer)
 467{
 468    USBHostIsoXfer *xfer = transfer->user_data;
 469
 470    if (!xfer) {
 471        /* USBHostIsoXfer released while inflight */
 472        g_free(transfer->buffer);
 473        libusb_free_transfer(transfer);
 474        return;
 475    }
 476
 477    QTAILQ_REMOVE(&xfer->ring->inflight, xfer, next);
 478    if (QTAILQ_EMPTY(&xfer->ring->inflight)) {
 479        USBHostDevice *s = xfer->ring->host;
 480        trace_usb_host_iso_stop(s->bus_num, s->addr, xfer->ring->ep->nr);
 481    }
 482    if (xfer->ring->ep->pid == USB_TOKEN_IN) {
 483        QTAILQ_INSERT_TAIL(&xfer->ring->copy, xfer, next);
 484        usb_wakeup(xfer->ring->ep, 0);
 485    } else {
 486        QTAILQ_INSERT_TAIL(&xfer->ring->unused, xfer, next);
 487    }
 488}
 489
 490static USBHostIsoRing *usb_host_iso_alloc(USBHostDevice *s, USBEndpoint *ep)
 491{
 492    USBHostIsoRing *ring = g_new0(USBHostIsoRing, 1);
 493    USBHostIsoXfer *xfer;
 494    /* FIXME: check interval (for now assume one xfer per frame) */
 495    int packets = s->iso_urb_frames;
 496    int i;
 497
 498    ring->host = s;
 499    ring->ep = ep;
 500    QTAILQ_INIT(&ring->unused);
 501    QTAILQ_INIT(&ring->inflight);
 502    QTAILQ_INIT(&ring->copy);
 503    QTAILQ_INSERT_TAIL(&s->isorings, ring, next);
 504
 505    for (i = 0; i < s->iso_urb_count; i++) {
 506        xfer = g_new0(USBHostIsoXfer, 1);
 507        xfer->ring = ring;
 508        xfer->xfer = libusb_alloc_transfer(packets);
 509        xfer->xfer->dev_handle = s->dh;
 510        xfer->xfer->type = LIBUSB_TRANSFER_TYPE_ISOCHRONOUS;
 511
 512        xfer->xfer->endpoint = ring->ep->nr;
 513        if (ring->ep->pid == USB_TOKEN_IN) {
 514            xfer->xfer->endpoint |= USB_DIR_IN;
 515        }
 516        xfer->xfer->callback = usb_host_req_complete_iso;
 517        xfer->xfer->user_data = xfer;
 518
 519        xfer->xfer->num_iso_packets = packets;
 520        xfer->xfer->length = ring->ep->max_packet_size * packets;
 521        xfer->xfer->buffer = g_malloc0(xfer->xfer->length);
 522
 523        QTAILQ_INSERT_TAIL(&ring->unused, xfer, next);
 524    }
 525
 526    return ring;
 527}
 528
 529static USBHostIsoRing *usb_host_iso_find(USBHostDevice *s, USBEndpoint *ep)
 530{
 531    USBHostIsoRing *ring;
 532
 533    QTAILQ_FOREACH(ring, &s->isorings, next) {
 534        if (ring->ep == ep) {
 535            return ring;
 536        }
 537    }
 538    return NULL;
 539}
 540
 541static void usb_host_iso_reset_xfer(USBHostIsoXfer *xfer)
 542{
 543    libusb_set_iso_packet_lengths(xfer->xfer,
 544                                  xfer->ring->ep->max_packet_size);
 545    xfer->packet = 0;
 546    xfer->copy_complete = false;
 547}
 548
 549static void usb_host_iso_free_xfer(USBHostIsoXfer *xfer, bool inflight)
 550{
 551    if (inflight) {
 552        xfer->xfer->user_data = NULL;
 553    } else {
 554        g_free(xfer->xfer->buffer);
 555        libusb_free_transfer(xfer->xfer);
 556    }
 557    g_free(xfer);
 558}
 559
 560static void usb_host_iso_free(USBHostIsoRing *ring)
 561{
 562    USBHostIsoXfer *xfer;
 563
 564    while ((xfer = QTAILQ_FIRST(&ring->inflight)) != NULL) {
 565        QTAILQ_REMOVE(&ring->inflight, xfer, next);
 566        usb_host_iso_free_xfer(xfer, true);
 567    }
 568    while ((xfer = QTAILQ_FIRST(&ring->unused)) != NULL) {
 569        QTAILQ_REMOVE(&ring->unused, xfer, next);
 570        usb_host_iso_free_xfer(xfer, false);
 571    }
 572    while ((xfer = QTAILQ_FIRST(&ring->copy)) != NULL) {
 573        QTAILQ_REMOVE(&ring->copy, xfer, next);
 574        usb_host_iso_free_xfer(xfer, false);
 575    }
 576
 577    QTAILQ_REMOVE(&ring->host->isorings, ring, next);
 578    g_free(ring);
 579}
 580
 581static void usb_host_iso_free_all(USBHostDevice *s)
 582{
 583    USBHostIsoRing *ring;
 584
 585    while ((ring = QTAILQ_FIRST(&s->isorings)) != NULL) {
 586        usb_host_iso_free(ring);
 587    }
 588}
 589
 590static bool usb_host_iso_data_copy(USBHostIsoXfer *xfer, USBPacket *p)
 591{
 592    unsigned int psize;
 593    unsigned char *buf;
 594
 595    buf = libusb_get_iso_packet_buffer_simple(xfer->xfer, xfer->packet);
 596    if (p->pid == USB_TOKEN_OUT) {
 597        psize = p->iov.size;
 598        if (psize > xfer->ring->ep->max_packet_size) {
 599            /* should not happen (guest bug) */
 600            psize = xfer->ring->ep->max_packet_size;
 601        }
 602        xfer->xfer->iso_packet_desc[xfer->packet].length = psize;
 603    } else {
 604        psize = xfer->xfer->iso_packet_desc[xfer->packet].actual_length;
 605        if (psize > p->iov.size) {
 606            /* should not happen (guest bug) */
 607            psize = p->iov.size;
 608        }
 609    }
 610    usb_packet_copy(p, buf, psize);
 611    xfer->packet++;
 612    xfer->copy_complete = (xfer->packet == xfer->xfer->num_iso_packets);
 613    return xfer->copy_complete;
 614}
 615
 616static void usb_host_iso_data_in(USBHostDevice *s, USBPacket *p)
 617{
 618    USBHostIsoRing *ring;
 619    USBHostIsoXfer *xfer;
 620    bool disconnect = false;
 621    int rc;
 622
 623    ring = usb_host_iso_find(s, p->ep);
 624    if (ring == NULL) {
 625        ring = usb_host_iso_alloc(s, p->ep);
 626    }
 627
 628    /* copy data to guest */
 629    xfer = QTAILQ_FIRST(&ring->copy);
 630    if (xfer != NULL) {
 631        if (usb_host_iso_data_copy(xfer, p)) {
 632            QTAILQ_REMOVE(&ring->copy, xfer, next);
 633            QTAILQ_INSERT_TAIL(&ring->unused, xfer, next);
 634        }
 635    }
 636
 637    /* submit empty bufs to host */
 638    while ((xfer = QTAILQ_FIRST(&ring->unused)) != NULL) {
 639        QTAILQ_REMOVE(&ring->unused, xfer, next);
 640        usb_host_iso_reset_xfer(xfer);
 641        rc = libusb_submit_transfer(xfer->xfer);
 642        if (rc != 0) {
 643            usb_host_libusb_error("libusb_submit_transfer [iso]", rc);
 644            QTAILQ_INSERT_TAIL(&ring->unused, xfer, next);
 645            if (rc == LIBUSB_ERROR_NO_DEVICE) {
 646                disconnect = true;
 647            }
 648            break;
 649        }
 650        if (QTAILQ_EMPTY(&ring->inflight)) {
 651            trace_usb_host_iso_start(s->bus_num, s->addr, p->ep->nr);
 652        }
 653        QTAILQ_INSERT_TAIL(&ring->inflight, xfer, next);
 654    }
 655
 656    if (disconnect) {
 657        usb_host_nodev(s);
 658    }
 659}
 660
 661static void usb_host_iso_data_out(USBHostDevice *s, USBPacket *p)
 662{
 663    USBHostIsoRing *ring;
 664    USBHostIsoXfer *xfer;
 665    bool disconnect = false;
 666    int rc, filled = 0;
 667
 668    ring = usb_host_iso_find(s, p->ep);
 669    if (ring == NULL) {
 670        ring = usb_host_iso_alloc(s, p->ep);
 671    }
 672
 673    /* copy data from guest */
 674    xfer = QTAILQ_FIRST(&ring->copy);
 675    while (xfer != NULL && xfer->copy_complete) {
 676        filled++;
 677        xfer = QTAILQ_NEXT(xfer, next);
 678    }
 679    if (xfer == NULL) {
 680        xfer = QTAILQ_FIRST(&ring->unused);
 681        if (xfer == NULL) {
 682            trace_usb_host_iso_out_of_bufs(s->bus_num, s->addr, p->ep->nr);
 683            return;
 684        }
 685        QTAILQ_REMOVE(&ring->unused, xfer, next);
 686        usb_host_iso_reset_xfer(xfer);
 687        QTAILQ_INSERT_TAIL(&ring->copy, xfer, next);
 688    }
 689    usb_host_iso_data_copy(xfer, p);
 690
 691    if (QTAILQ_EMPTY(&ring->inflight)) {
 692        /* wait until half of our buffers are filled
 693           before kicking the iso out stream */
 694        if (filled*2 < s->iso_urb_count) {
 695            return;
 696        }
 697    }
 698
 699    /* submit filled bufs to host */
 700    while ((xfer = QTAILQ_FIRST(&ring->copy)) != NULL &&
 701           xfer->copy_complete) {
 702        QTAILQ_REMOVE(&ring->copy, xfer, next);
 703        rc = libusb_submit_transfer(xfer->xfer);
 704        if (rc != 0) {
 705            usb_host_libusb_error("libusb_submit_transfer [iso]", rc);
 706            QTAILQ_INSERT_TAIL(&ring->unused, xfer, next);
 707            if (rc == LIBUSB_ERROR_NO_DEVICE) {
 708                disconnect = true;
 709            }
 710            break;
 711        }
 712        if (QTAILQ_EMPTY(&ring->inflight)) {
 713            trace_usb_host_iso_start(s->bus_num, s->addr, p->ep->nr);
 714        }
 715        QTAILQ_INSERT_TAIL(&ring->inflight, xfer, next);
 716    }
 717
 718    if (disconnect) {
 719        usb_host_nodev(s);
 720    }
 721}
 722
 723/* ------------------------------------------------------------------------ */
 724
 725static void usb_host_speed_compat(USBHostDevice *s)
 726{
 727    USBDevice *udev = USB_DEVICE(s);
 728    struct libusb_config_descriptor *conf;
 729    const struct libusb_interface_descriptor *intf;
 730    const struct libusb_endpoint_descriptor *endp;
 731#ifdef HAVE_STREAMS
 732    struct libusb_ss_endpoint_companion_descriptor *endp_ss_comp;
 733#endif
 734    bool compat_high = true;
 735    bool compat_full = true;
 736    uint8_t type;
 737    int rc, c, i, a, e;
 738
 739    for (c = 0;; c++) {
 740        rc = libusb_get_config_descriptor(s->dev, c, &conf);
 741        if (rc != 0) {
 742            break;
 743        }
 744        for (i = 0; i < conf->bNumInterfaces; i++) {
 745            for (a = 0; a < conf->interface[i].num_altsetting; a++) {
 746                intf = &conf->interface[i].altsetting[a];
 747                for (e = 0; e < intf->bNumEndpoints; e++) {
 748                    endp = &intf->endpoint[e];
 749                    type = endp->bmAttributes & 0x3;
 750                    switch (type) {
 751                    case 0x01: /* ISO */
 752                        compat_full = false;
 753                        compat_high = false;
 754                        break;
 755                    case 0x02: /* BULK */
 756#ifdef HAVE_STREAMS
 757                        rc = libusb_get_ss_endpoint_companion_descriptor
 758                            (ctx, endp, &endp_ss_comp);
 759                        if (rc == LIBUSB_SUCCESS) {
 760                            int streams = endp_ss_comp->bmAttributes & 0x1f;
 761                            if (streams) {
 762                                compat_full = false;
 763                                compat_high = false;
 764                            }
 765                            libusb_free_ss_endpoint_companion_descriptor
 766                                (endp_ss_comp);
 767                        }
 768#endif
 769                        break;
 770                    case 0x03: /* INTERRUPT */
 771                        if (endp->wMaxPacketSize > 64) {
 772                            compat_full = false;
 773                        }
 774                        if (endp->wMaxPacketSize > 1024) {
 775                            compat_high = false;
 776                        }
 777                        break;
 778                    }
 779                }
 780            }
 781        }
 782        libusb_free_config_descriptor(conf);
 783    }
 784
 785    udev->speedmask = (1 << udev->speed);
 786    if (udev->speed == USB_SPEED_SUPER && compat_high) {
 787        udev->speedmask |= USB_SPEED_MASK_HIGH;
 788    }
 789    if (udev->speed == USB_SPEED_SUPER && compat_full) {
 790        udev->speedmask |= USB_SPEED_MASK_FULL;
 791    }
 792    if (udev->speed == USB_SPEED_HIGH && compat_full) {
 793        udev->speedmask |= USB_SPEED_MASK_FULL;
 794    }
 795}
 796
 797static void usb_host_ep_update(USBHostDevice *s)
 798{
 799    static const char *tname[] = {
 800        [USB_ENDPOINT_XFER_CONTROL] = "control",
 801        [USB_ENDPOINT_XFER_ISOC]    = "isoc",
 802        [USB_ENDPOINT_XFER_BULK]    = "bulk",
 803        [USB_ENDPOINT_XFER_INT]     = "int",
 804    };
 805    USBDevice *udev = USB_DEVICE(s);
 806    struct libusb_config_descriptor *conf;
 807    const struct libusb_interface_descriptor *intf;
 808    const struct libusb_endpoint_descriptor *endp;
 809#ifdef HAVE_STREAMS
 810    struct libusb_ss_endpoint_companion_descriptor *endp_ss_comp;
 811#endif
 812    uint8_t devep, type;
 813    int pid, ep;
 814    int rc, i, e;
 815
 816    usb_ep_reset(udev);
 817    rc = libusb_get_active_config_descriptor(s->dev, &conf);
 818    if (rc != 0) {
 819        return;
 820    }
 821    trace_usb_host_parse_config(s->bus_num, s->addr,
 822                                conf->bConfigurationValue, true);
 823
 824    for (i = 0; i < conf->bNumInterfaces; i++) {
 825        assert(udev->altsetting[i] < conf->interface[i].num_altsetting);
 826        intf = &conf->interface[i].altsetting[udev->altsetting[i]];
 827        trace_usb_host_parse_interface(s->bus_num, s->addr,
 828                                       intf->bInterfaceNumber,
 829                                       intf->bAlternateSetting, true);
 830        for (e = 0; e < intf->bNumEndpoints; e++) {
 831            endp = &intf->endpoint[e];
 832
 833            devep = endp->bEndpointAddress;
 834            pid = (devep & USB_DIR_IN) ? USB_TOKEN_IN : USB_TOKEN_OUT;
 835            ep = devep & 0xf;
 836            type = endp->bmAttributes & 0x3;
 837
 838            if (ep == 0) {
 839                trace_usb_host_parse_error(s->bus_num, s->addr,
 840                                           "invalid endpoint address");
 841                return;
 842            }
 843            if (usb_ep_get_type(udev, pid, ep) != USB_ENDPOINT_XFER_INVALID) {
 844                trace_usb_host_parse_error(s->bus_num, s->addr,
 845                                           "duplicate endpoint address");
 846                return;
 847            }
 848
 849            trace_usb_host_parse_endpoint(s->bus_num, s->addr, ep,
 850                                          (devep & USB_DIR_IN) ? "in" : "out",
 851                                          tname[type], true);
 852            usb_ep_set_max_packet_size(udev, pid, ep,
 853                                       endp->wMaxPacketSize);
 854            usb_ep_set_type(udev, pid, ep, type);
 855            usb_ep_set_ifnum(udev, pid, ep, i);
 856            usb_ep_set_halted(udev, pid, ep, 0);
 857#ifdef HAVE_STREAMS
 858            if (type == LIBUSB_TRANSFER_TYPE_BULK &&
 859                    libusb_get_ss_endpoint_companion_descriptor(ctx, endp,
 860                        &endp_ss_comp) == LIBUSB_SUCCESS) {
 861                usb_ep_set_max_streams(udev, pid, ep,
 862                                       endp_ss_comp->bmAttributes);
 863                libusb_free_ss_endpoint_companion_descriptor(endp_ss_comp);
 864            }
 865#endif
 866        }
 867    }
 868
 869    libusb_free_config_descriptor(conf);
 870}
 871
 872static int usb_host_open(USBHostDevice *s, libusb_device *dev)
 873{
 874    USBDevice *udev = USB_DEVICE(s);
 875    int bus_num = libusb_get_bus_number(dev);
 876    int addr    = libusb_get_device_address(dev);
 877    int rc;
 878    Error *local_err = NULL;
 879
 880    if (s->bh_postld_pending) {
 881        return -1;
 882    }
 883
 884    trace_usb_host_open_started(bus_num, addr);
 885
 886    if (s->dh != NULL) {
 887        goto fail;
 888    }
 889    rc = libusb_open(dev, &s->dh);
 890    if (rc != 0) {
 891        goto fail;
 892    }
 893
 894    s->dev     = dev;
 895    s->bus_num = bus_num;
 896    s->addr    = addr;
 897
 898    usb_host_detach_kernel(s);
 899
 900    libusb_get_device_descriptor(dev, &s->ddesc);
 901    usb_host_get_port(s->dev, s->port, sizeof(s->port));
 902
 903    usb_ep_init(udev);
 904    usb_host_ep_update(s);
 905
 906    udev->speed     = speed_map[libusb_get_device_speed(dev)];
 907    usb_host_speed_compat(s);
 908
 909    if (s->ddesc.iProduct) {
 910        libusb_get_string_descriptor_ascii(s->dh, s->ddesc.iProduct,
 911                                           (unsigned char *)udev->product_desc,
 912                                           sizeof(udev->product_desc));
 913    } else {
 914        snprintf(udev->product_desc, sizeof(udev->product_desc),
 915                 "host:%d.%d", bus_num, addr);
 916    }
 917
 918    usb_device_attach(udev, &local_err);
 919    if (local_err) {
 920        error_report_err(local_err);
 921        goto fail;
 922    }
 923
 924    trace_usb_host_open_success(bus_num, addr);
 925    return 0;
 926
 927fail:
 928    trace_usb_host_open_failure(bus_num, addr);
 929    if (s->dh != NULL) {
 930        usb_host_release_interfaces(s);
 931        libusb_reset_device(s->dh);
 932        usb_host_attach_kernel(s);
 933        libusb_close(s->dh);
 934        s->dh = NULL;
 935        s->dev = NULL;
 936    }
 937    return -1;
 938}
 939
 940static void usb_host_abort_xfers(USBHostDevice *s)
 941{
 942    USBHostRequest *r, *rtmp;
 943
 944    QTAILQ_FOREACH_SAFE(r, &s->requests, next, rtmp) {
 945        usb_host_req_abort(r);
 946    }
 947}
 948
 949static int usb_host_close(USBHostDevice *s)
 950{
 951    USBDevice *udev = USB_DEVICE(s);
 952
 953    if (s->dh == NULL) {
 954        return -1;
 955    }
 956
 957    trace_usb_host_close(s->bus_num, s->addr);
 958
 959    usb_host_abort_xfers(s);
 960    usb_host_iso_free_all(s);
 961
 962    if (udev->attached) {
 963        usb_device_detach(udev);
 964    }
 965
 966    usb_host_release_interfaces(s);
 967    libusb_reset_device(s->dh);
 968    usb_host_attach_kernel(s);
 969    libusb_close(s->dh);
 970    s->dh = NULL;
 971    s->dev = NULL;
 972
 973    usb_host_auto_check(NULL);
 974    return 0;
 975}
 976
 977static void usb_host_nodev_bh(void *opaque)
 978{
 979    USBHostDevice *s = opaque;
 980    usb_host_close(s);
 981}
 982
 983static void usb_host_nodev(USBHostDevice *s)
 984{
 985    if (!s->bh_nodev) {
 986        s->bh_nodev = qemu_bh_new(usb_host_nodev_bh, s);
 987    }
 988    qemu_bh_schedule(s->bh_nodev);
 989}
 990
 991static void usb_host_exit_notifier(struct Notifier *n, void *data)
 992{
 993    USBHostDevice *s = container_of(n, USBHostDevice, exit);
 994
 995    if (s->dh) {
 996        usb_host_release_interfaces(s);
 997        libusb_reset_device(s->dh);
 998        usb_host_attach_kernel(s);
 999        libusb_close(s->dh);
1000    }
1001}
1002
1003static libusb_device *usb_host_find_ref(int bus, int addr)
1004{
1005    libusb_device **devs = NULL;
1006    libusb_device *ret = NULL;
1007    int i, n;
1008
1009    if (usb_host_init() != 0) {
1010        return NULL;
1011    }
1012    n = libusb_get_device_list(ctx, &devs);
1013    for (i = 0; i < n; i++) {
1014        if (libusb_get_bus_number(devs[i]) == bus &&
1015            libusb_get_device_address(devs[i]) == addr) {
1016            ret = libusb_ref_device(devs[i]);
1017            break;
1018        }
1019    }
1020    libusb_free_device_list(devs, 1);
1021    return ret;
1022}
1023
1024static void usb_host_realize(USBDevice *udev, Error **errp)
1025{
1026    USBHostDevice *s = USB_HOST_DEVICE(udev);
1027    libusb_device *ldev;
1028    int rc;
1029
1030    if (s->match.vendor_id > 0xffff) {
1031        error_setg(errp, "vendorid out of range");
1032        return;
1033    }
1034    if (s->match.product_id > 0xffff) {
1035        error_setg(errp, "productid out of range");
1036        return;
1037    }
1038    if (s->match.addr > 127) {
1039        error_setg(errp, "hostaddr out of range");
1040        return;
1041    }
1042
1043    loglevel = s->loglevel;
1044    udev->flags |= (1 << USB_DEV_FLAG_IS_HOST);
1045    udev->auto_attach = 0;
1046    QTAILQ_INIT(&s->requests);
1047    QTAILQ_INIT(&s->isorings);
1048
1049    if (s->match.addr && s->match.bus_num &&
1050        !s->match.vendor_id &&
1051        !s->match.product_id &&
1052        !s->match.port) {
1053        s->needs_autoscan = false;
1054        ldev = usb_host_find_ref(s->match.bus_num,
1055                                 s->match.addr);
1056        if (!ldev) {
1057            error_setg(errp, "failed to find host usb device %d:%d",
1058                       s->match.bus_num, s->match.addr);
1059            return;
1060        }
1061        rc = usb_host_open(s, ldev);
1062        libusb_unref_device(ldev);
1063        if (rc < 0) {
1064            error_setg(errp, "failed to open host usb device %d:%d",
1065                       s->match.bus_num, s->match.addr);
1066            return;
1067        }
1068    } else {
1069        s->needs_autoscan = true;
1070        QTAILQ_INSERT_TAIL(&hostdevs, s, next);
1071        usb_host_auto_check(NULL);
1072    }
1073
1074    s->exit.notify = usb_host_exit_notifier;
1075    qemu_add_exit_notifier(&s->exit);
1076}
1077
1078static void usb_host_instance_init(Object *obj)
1079{
1080    USBDevice *udev = USB_DEVICE(obj);
1081    USBHostDevice *s = USB_HOST_DEVICE(udev);
1082
1083    device_add_bootindex_property(obj, &s->bootindex,
1084                                  "bootindex", NULL,
1085                                  &udev->qdev, NULL);
1086}
1087
1088static void usb_host_unrealize(USBDevice *udev, Error **errp)
1089{
1090    USBHostDevice *s = USB_HOST_DEVICE(udev);
1091
1092    qemu_remove_exit_notifier(&s->exit);
1093    if (s->needs_autoscan) {
1094        QTAILQ_REMOVE(&hostdevs, s, next);
1095    }
1096    usb_host_close(s);
1097}
1098
1099static void usb_host_cancel_packet(USBDevice *udev, USBPacket *p)
1100{
1101    USBHostDevice *s = USB_HOST_DEVICE(udev);
1102    USBHostRequest *r;
1103
1104    if (p->combined) {
1105        usb_combined_packet_cancel(udev, p);
1106        return;
1107    }
1108
1109    trace_usb_host_req_canceled(s->bus_num, s->addr, p);
1110
1111    r = usb_host_req_find(s, p);
1112    if (r && r->p) {
1113        r->p = NULL; /* mark as dead */
1114        libusb_cancel_transfer(r->xfer);
1115    }
1116}
1117
1118static void usb_host_detach_kernel(USBHostDevice *s)
1119{
1120    struct libusb_config_descriptor *conf;
1121    int rc, i;
1122
1123    rc = libusb_get_active_config_descriptor(s->dev, &conf);
1124    if (rc != 0) {
1125        return;
1126    }
1127    for (i = 0; i < USB_MAX_INTERFACES; i++) {
1128        rc = libusb_kernel_driver_active(s->dh, i);
1129        usb_host_libusb_error("libusb_kernel_driver_active", rc);
1130        if (rc != 1) {
1131            if (rc == 0) {
1132                s->ifs[i].detached = true;
1133            }
1134            continue;
1135        }
1136        trace_usb_host_detach_kernel(s->bus_num, s->addr, i);
1137        rc = libusb_detach_kernel_driver(s->dh, i);
1138        usb_host_libusb_error("libusb_detach_kernel_driver", rc);
1139        s->ifs[i].detached = true;
1140    }
1141    libusb_free_config_descriptor(conf);
1142}
1143
1144static void usb_host_attach_kernel(USBHostDevice *s)
1145{
1146    struct libusb_config_descriptor *conf;
1147    int rc, i;
1148
1149    rc = libusb_get_active_config_descriptor(s->dev, &conf);
1150    if (rc != 0) {
1151        return;
1152    }
1153    for (i = 0; i < USB_MAX_INTERFACES; i++) {
1154        if (!s->ifs[i].detached) {
1155            continue;
1156        }
1157        trace_usb_host_attach_kernel(s->bus_num, s->addr, i);
1158        libusb_attach_kernel_driver(s->dh, i);
1159        s->ifs[i].detached = false;
1160    }
1161    libusb_free_config_descriptor(conf);
1162}
1163
1164static int usb_host_claim_interfaces(USBHostDevice *s, int configuration)
1165{
1166    USBDevice *udev = USB_DEVICE(s);
1167    struct libusb_config_descriptor *conf;
1168    int rc, i, claimed;
1169
1170    for (i = 0; i < USB_MAX_INTERFACES; i++) {
1171        udev->altsetting[i] = 0;
1172    }
1173    udev->ninterfaces   = 0;
1174    udev->configuration = 0;
1175
1176    usb_host_detach_kernel(s);
1177
1178    rc = libusb_get_active_config_descriptor(s->dev, &conf);
1179    if (rc != 0) {
1180        if (rc == LIBUSB_ERROR_NOT_FOUND) {
1181            /* address state - ignore */
1182            return USB_RET_SUCCESS;
1183        }
1184        return USB_RET_STALL;
1185    }
1186
1187    claimed = 0;
1188    for (i = 0; i < USB_MAX_INTERFACES; i++) {
1189        trace_usb_host_claim_interface(s->bus_num, s->addr, configuration, i);
1190        rc = libusb_claim_interface(s->dh, i);
1191        if (rc == 0) {
1192            s->ifs[i].claimed = true;
1193            if (++claimed == conf->bNumInterfaces) {
1194                break;
1195            }
1196        }
1197    }
1198    if (claimed != conf->bNumInterfaces) {
1199        return USB_RET_STALL;
1200    }
1201
1202    udev->ninterfaces   = conf->bNumInterfaces;
1203    udev->configuration = configuration;
1204
1205    libusb_free_config_descriptor(conf);
1206    return USB_RET_SUCCESS;
1207}
1208
1209static void usb_host_release_interfaces(USBHostDevice *s)
1210{
1211    int i, rc;
1212
1213    for (i = 0; i < USB_MAX_INTERFACES; i++) {
1214        if (!s->ifs[i].claimed) {
1215            continue;
1216        }
1217        trace_usb_host_release_interface(s->bus_num, s->addr, i);
1218        rc = libusb_release_interface(s->dh, i);
1219        usb_host_libusb_error("libusb_release_interface", rc);
1220        s->ifs[i].claimed = false;
1221    }
1222}
1223
1224static void usb_host_set_address(USBHostDevice *s, int addr)
1225{
1226    USBDevice *udev = USB_DEVICE(s);
1227
1228    trace_usb_host_set_address(s->bus_num, s->addr, addr);
1229    udev->addr = addr;
1230}
1231
1232static void usb_host_set_config(USBHostDevice *s, int config, USBPacket *p)
1233{
1234    int rc = 0;
1235
1236    trace_usb_host_set_config(s->bus_num, s->addr, config);
1237
1238    usb_host_release_interfaces(s);
1239    if (s->ddesc.bNumConfigurations != 1) {
1240        rc = libusb_set_configuration(s->dh, config);
1241        if (rc != 0) {
1242            usb_host_libusb_error("libusb_set_configuration", rc);
1243            p->status = USB_RET_STALL;
1244            if (rc == LIBUSB_ERROR_NO_DEVICE) {
1245                usb_host_nodev(s);
1246            }
1247            return;
1248        }
1249    }
1250    p->status = usb_host_claim_interfaces(s, config);
1251    if (p->status != USB_RET_SUCCESS) {
1252        return;
1253    }
1254    usb_host_ep_update(s);
1255}
1256
1257static void usb_host_set_interface(USBHostDevice *s, int iface, int alt,
1258                                   USBPacket *p)
1259{
1260    USBDevice *udev = USB_DEVICE(s);
1261    int rc;
1262
1263    trace_usb_host_set_interface(s->bus_num, s->addr, iface, alt);
1264
1265    usb_host_iso_free_all(s);
1266
1267    if (iface >= USB_MAX_INTERFACES) {
1268        p->status = USB_RET_STALL;
1269        return;
1270    }
1271
1272    rc = libusb_set_interface_alt_setting(s->dh, iface, alt);
1273    if (rc != 0) {
1274        usb_host_libusb_error("libusb_set_interface_alt_setting", rc);
1275        p->status = USB_RET_STALL;
1276        if (rc == LIBUSB_ERROR_NO_DEVICE) {
1277            usb_host_nodev(s);
1278        }
1279        return;
1280    }
1281
1282    udev->altsetting[iface] = alt;
1283    usb_host_ep_update(s);
1284}
1285
1286static void usb_host_handle_control(USBDevice *udev, USBPacket *p,
1287                                    int request, int value, int index,
1288                                    int length, uint8_t *data)
1289{
1290    USBHostDevice *s = USB_HOST_DEVICE(udev);
1291    USBHostRequest *r;
1292    int rc;
1293
1294    trace_usb_host_req_control(s->bus_num, s->addr, p, request, value, index);
1295
1296    if (s->dh == NULL) {
1297        p->status = USB_RET_NODEV;
1298        trace_usb_host_req_emulated(s->bus_num, s->addr, p, p->status);
1299        return;
1300    }
1301
1302    switch (request) {
1303    case DeviceOutRequest | USB_REQ_SET_ADDRESS:
1304        usb_host_set_address(s, value);
1305        trace_usb_host_req_emulated(s->bus_num, s->addr, p, p->status);
1306        return;
1307
1308    case DeviceOutRequest | USB_REQ_SET_CONFIGURATION:
1309        usb_host_set_config(s, value & 0xff, p);
1310        trace_usb_host_req_emulated(s->bus_num, s->addr, p, p->status);
1311        return;
1312
1313    case InterfaceOutRequest | USB_REQ_SET_INTERFACE:
1314        usb_host_set_interface(s, index, value, p);
1315        trace_usb_host_req_emulated(s->bus_num, s->addr, p, p->status);
1316        return;
1317
1318    case EndpointOutRequest | USB_REQ_CLEAR_FEATURE:
1319        if (value == 0) { /* clear halt */
1320            int pid = (index & USB_DIR_IN) ? USB_TOKEN_IN : USB_TOKEN_OUT;
1321            libusb_clear_halt(s->dh, index);
1322            usb_ep_set_halted(udev, pid, index & 0x0f, 0);
1323            trace_usb_host_req_emulated(s->bus_num, s->addr, p, p->status);
1324            return;
1325        }
1326    }
1327
1328    r = usb_host_req_alloc(s, p, (request >> 8) & USB_DIR_IN, length + 8);
1329    r->cbuf = data;
1330    r->clen = length;
1331    memcpy(r->buffer, udev->setup_buf, 8);
1332    if (!r->in) {
1333        memcpy(r->buffer + 8, r->cbuf, r->clen);
1334    }
1335
1336    /* Fix up USB-3 ep0 maxpacket size to allow superspeed connected devices
1337     * to work redirected to a not superspeed capable hcd */
1338    if ((udev->speedmask & USB_SPEED_MASK_SUPER) &&
1339        !(udev->port->speedmask & USB_SPEED_MASK_SUPER) &&
1340        request == 0x8006 && value == 0x100 && index == 0) {
1341        r->usb3ep0quirk = true;
1342    }
1343
1344    libusb_fill_control_transfer(r->xfer, s->dh, r->buffer,
1345                                 usb_host_req_complete_ctrl, r,
1346                                 CONTROL_TIMEOUT);
1347    rc = libusb_submit_transfer(r->xfer);
1348    if (rc != 0) {
1349        p->status = USB_RET_NODEV;
1350        trace_usb_host_req_complete(s->bus_num, s->addr, p,
1351                                    p->status, p->actual_length);
1352        if (rc == LIBUSB_ERROR_NO_DEVICE) {
1353            usb_host_nodev(s);
1354        }
1355        return;
1356    }
1357
1358    p->status = USB_RET_ASYNC;
1359}
1360
1361static void usb_host_handle_data(USBDevice *udev, USBPacket *p)
1362{
1363    USBHostDevice *s = USB_HOST_DEVICE(udev);
1364    USBHostRequest *r;
1365    size_t size;
1366    int ep, rc;
1367
1368    if (usb_host_use_combining(p->ep) && p->state == USB_PACKET_SETUP) {
1369        p->status = USB_RET_ADD_TO_QUEUE;
1370        return;
1371    }
1372
1373    trace_usb_host_req_data(s->bus_num, s->addr, p,
1374                            p->pid == USB_TOKEN_IN,
1375                            p->ep->nr, p->iov.size);
1376
1377    if (s->dh == NULL) {
1378        p->status = USB_RET_NODEV;
1379        trace_usb_host_req_emulated(s->bus_num, s->addr, p, p->status);
1380        return;
1381    }
1382    if (p->ep->halted) {
1383        p->status = USB_RET_STALL;
1384        trace_usb_host_req_emulated(s->bus_num, s->addr, p, p->status);
1385        return;
1386    }
1387
1388    switch (usb_ep_get_type(udev, p->pid, p->ep->nr)) {
1389    case USB_ENDPOINT_XFER_BULK:
1390        size = usb_packet_size(p);
1391        r = usb_host_req_alloc(s, p, p->pid == USB_TOKEN_IN, size);
1392        if (!r->in) {
1393            usb_packet_copy(p, r->buffer, size);
1394        }
1395        ep = p->ep->nr | (r->in ? USB_DIR_IN : 0);
1396        if (p->stream) {
1397#ifdef HAVE_STREAMS
1398            libusb_fill_bulk_stream_transfer(r->xfer, s->dh, ep, p->stream,
1399                                             r->buffer, size,
1400                                             usb_host_req_complete_data, r,
1401                                             BULK_TIMEOUT);
1402#else
1403            usb_host_req_free(r);
1404            p->status = USB_RET_STALL;
1405            return;
1406#endif
1407        } else {
1408            libusb_fill_bulk_transfer(r->xfer, s->dh, ep,
1409                                      r->buffer, size,
1410                                      usb_host_req_complete_data, r,
1411                                      BULK_TIMEOUT);
1412        }
1413        break;
1414    case USB_ENDPOINT_XFER_INT:
1415        r = usb_host_req_alloc(s, p, p->pid == USB_TOKEN_IN, p->iov.size);
1416        if (!r->in) {
1417            usb_packet_copy(p, r->buffer, p->iov.size);
1418        }
1419        ep = p->ep->nr | (r->in ? USB_DIR_IN : 0);
1420        libusb_fill_interrupt_transfer(r->xfer, s->dh, ep,
1421                                       r->buffer, p->iov.size,
1422                                       usb_host_req_complete_data, r,
1423                                       INTR_TIMEOUT);
1424        break;
1425    case USB_ENDPOINT_XFER_ISOC:
1426        if (p->pid == USB_TOKEN_IN) {
1427            usb_host_iso_data_in(s, p);
1428        } else {
1429            usb_host_iso_data_out(s, p);
1430        }
1431        trace_usb_host_req_complete(s->bus_num, s->addr, p,
1432                                    p->status, p->actual_length);
1433        return;
1434    default:
1435        p->status = USB_RET_STALL;
1436        trace_usb_host_req_complete(s->bus_num, s->addr, p,
1437                                    p->status, p->actual_length);
1438        return;
1439    }
1440
1441    rc = libusb_submit_transfer(r->xfer);
1442    if (rc != 0) {
1443        p->status = USB_RET_NODEV;
1444        trace_usb_host_req_complete(s->bus_num, s->addr, p,
1445                                    p->status, p->actual_length);
1446        if (rc == LIBUSB_ERROR_NO_DEVICE) {
1447            usb_host_nodev(s);
1448        }
1449        return;
1450    }
1451
1452    p->status = USB_RET_ASYNC;
1453}
1454
1455static void usb_host_flush_ep_queue(USBDevice *dev, USBEndpoint *ep)
1456{
1457    if (usb_host_use_combining(ep)) {
1458        usb_ep_combine_input_packets(ep);
1459    }
1460}
1461
1462static void usb_host_handle_reset(USBDevice *udev)
1463{
1464    USBHostDevice *s = USB_HOST_DEVICE(udev);
1465    int rc;
1466
1467    if (!s->allow_one_guest_reset && !s->allow_all_guest_resets) {
1468        return;
1469    }
1470    if (!s->allow_all_guest_resets && udev->addr == 0) {
1471        return;
1472    }
1473
1474    trace_usb_host_reset(s->bus_num, s->addr);
1475
1476    rc = libusb_reset_device(s->dh);
1477    if (rc != 0) {
1478        usb_host_nodev(s);
1479    }
1480}
1481
1482static int usb_host_alloc_streams(USBDevice *udev, USBEndpoint **eps,
1483                                  int nr_eps, int streams)
1484{
1485#ifdef HAVE_STREAMS
1486    USBHostDevice *s = USB_HOST_DEVICE(udev);
1487    unsigned char endpoints[30];
1488    int i, rc;
1489
1490    for (i = 0; i < nr_eps; i++) {
1491        endpoints[i] = eps[i]->nr;
1492        if (eps[i]->pid == USB_TOKEN_IN) {
1493            endpoints[i] |= 0x80;
1494        }
1495    }
1496    rc = libusb_alloc_streams(s->dh, streams, endpoints, nr_eps);
1497    if (rc < 0) {
1498        usb_host_libusb_error("libusb_alloc_streams", rc);
1499    } else if (rc != streams) {
1500        error_report("libusb_alloc_streams: got less streams "
1501                     "then requested %d < %d", rc, streams);
1502    }
1503
1504    return (rc == streams) ? 0 : -1;
1505#else
1506    error_report("libusb_alloc_streams: error not implemented");
1507    return -1;
1508#endif
1509}
1510
1511static void usb_host_free_streams(USBDevice *udev, USBEndpoint **eps,
1512                                  int nr_eps)
1513{
1514#ifdef HAVE_STREAMS
1515    USBHostDevice *s = USB_HOST_DEVICE(udev);
1516    unsigned char endpoints[30];
1517    int i;
1518
1519    for (i = 0; i < nr_eps; i++) {
1520        endpoints[i] = eps[i]->nr;
1521        if (eps[i]->pid == USB_TOKEN_IN) {
1522            endpoints[i] |= 0x80;
1523        }
1524    }
1525    libusb_free_streams(s->dh, endpoints, nr_eps);
1526#endif
1527}
1528
1529/*
1530 * This is *NOT* about restoring state.  We have absolutely no idea
1531 * what state the host device is in at the moment and whenever it is
1532 * still present in the first place.  Attemping to contine where we
1533 * left off is impossible.
1534 *
1535 * What we are going to do here is emulate a surprise removal of
1536 * the usb device passed through, then kick host scan so the device
1537 * will get re-attached (and re-initialized by the guest) in case it
1538 * is still present.
1539 *
1540 * As the device removal will change the state of other devices (usb
1541 * host controller, most likely interrupt controller too) we have to
1542 * wait with it until *all* vmstate is loaded.  Thus post_load just
1543 * kicks a bottom half which then does the actual work.
1544 */
1545static void usb_host_post_load_bh(void *opaque)
1546{
1547    USBHostDevice *dev = opaque;
1548    USBDevice *udev = USB_DEVICE(dev);
1549
1550    if (dev->dh != NULL) {
1551        usb_host_close(dev);
1552    }
1553    if (udev->attached) {
1554        usb_device_detach(udev);
1555    }
1556    dev->bh_postld_pending = false;
1557    usb_host_auto_check(NULL);
1558}
1559
1560static int usb_host_post_load(void *opaque, int version_id)
1561{
1562    USBHostDevice *dev = opaque;
1563
1564    if (!dev->bh_postld) {
1565        dev->bh_postld = qemu_bh_new(usb_host_post_load_bh, dev);
1566    }
1567    qemu_bh_schedule(dev->bh_postld);
1568    dev->bh_postld_pending = true;
1569    return 0;
1570}
1571
1572static const VMStateDescription vmstate_usb_host = {
1573    .name = "usb-host",
1574    .version_id = 1,
1575    .minimum_version_id = 1,
1576    .post_load = usb_host_post_load,
1577    .fields = (VMStateField[]) {
1578        VMSTATE_USB_DEVICE(parent_obj, USBHostDevice),
1579        VMSTATE_END_OF_LIST()
1580    }
1581};
1582
1583static Property usb_host_dev_properties[] = {
1584    DEFINE_PROP_UINT32("hostbus",  USBHostDevice, match.bus_num,    0),
1585    DEFINE_PROP_UINT32("hostaddr", USBHostDevice, match.addr,       0),
1586    DEFINE_PROP_STRING("hostport", USBHostDevice, match.port),
1587    DEFINE_PROP_UINT32("vendorid",  USBHostDevice, match.vendor_id,  0),
1588    DEFINE_PROP_UINT32("productid", USBHostDevice, match.product_id, 0),
1589    DEFINE_PROP_UINT32("isobufs",  USBHostDevice, iso_urb_count,    4),
1590    DEFINE_PROP_UINT32("isobsize", USBHostDevice, iso_urb_frames,   32),
1591    DEFINE_PROP_BOOL("guest-reset", USBHostDevice,
1592                     allow_one_guest_reset, true),
1593    DEFINE_PROP_BOOL("guest-resets-all", USBHostDevice,
1594                     allow_all_guest_resets, false),
1595    DEFINE_PROP_UINT32("loglevel",  USBHostDevice, loglevel,
1596                       LIBUSB_LOG_LEVEL_WARNING),
1597    DEFINE_PROP_BIT("pipeline",    USBHostDevice, options,
1598                    USB_HOST_OPT_PIPELINE, true),
1599    DEFINE_PROP_END_OF_LIST(),
1600};
1601
1602static void usb_host_class_initfn(ObjectClass *klass, void *data)
1603{
1604    DeviceClass *dc = DEVICE_CLASS(klass);
1605    USBDeviceClass *uc = USB_DEVICE_CLASS(klass);
1606
1607    uc->realize        = usb_host_realize;
1608    uc->product_desc   = "USB Host Device";
1609    uc->cancel_packet  = usb_host_cancel_packet;
1610    uc->handle_data    = usb_host_handle_data;
1611    uc->handle_control = usb_host_handle_control;
1612    uc->handle_reset   = usb_host_handle_reset;
1613    uc->unrealize      = usb_host_unrealize;
1614    uc->flush_ep_queue = usb_host_flush_ep_queue;
1615    uc->alloc_streams  = usb_host_alloc_streams;
1616    uc->free_streams   = usb_host_free_streams;
1617    dc->vmsd = &vmstate_usb_host;
1618    dc->props = usb_host_dev_properties;
1619    set_bit(DEVICE_CATEGORY_BRIDGE, dc->categories);
1620}
1621
1622static TypeInfo usb_host_dev_info = {
1623    .name          = TYPE_USB_HOST_DEVICE,
1624    .parent        = TYPE_USB_DEVICE,
1625    .instance_size = sizeof(USBHostDevice),
1626    .class_init    = usb_host_class_initfn,
1627    .instance_init = usb_host_instance_init,
1628};
1629
1630static void usb_host_register_types(void)
1631{
1632    type_register_static(&usb_host_dev_info);
1633}
1634
1635type_init(usb_host_register_types)
1636
1637/* ------------------------------------------------------------------------ */
1638
1639static QEMUTimer *usb_auto_timer;
1640static VMChangeStateEntry *usb_vmstate;
1641
1642static void usb_host_vm_state(void *unused, int running, RunState state)
1643{
1644    if (running) {
1645        usb_host_auto_check(unused);
1646    }
1647}
1648
1649static void usb_host_auto_check(void *unused)
1650{
1651    struct USBHostDevice *s;
1652    struct USBAutoFilter *f;
1653    libusb_device **devs = NULL;
1654    struct libusb_device_descriptor ddesc;
1655    int unconnected = 0;
1656    int i, n;
1657
1658    if (usb_host_init() != 0) {
1659        return;
1660    }
1661
1662    if (runstate_is_running()) {
1663        n = libusb_get_device_list(ctx, &devs);
1664        for (i = 0; i < n; i++) {
1665            if (libusb_get_device_descriptor(devs[i], &ddesc) != 0) {
1666                continue;
1667            }
1668            if (ddesc.bDeviceClass == LIBUSB_CLASS_HUB) {
1669                continue;
1670            }
1671            QTAILQ_FOREACH(s, &hostdevs, next) {
1672                f = &s->match;
1673                if (f->bus_num > 0 &&
1674                    f->bus_num != libusb_get_bus_number(devs[i])) {
1675                    continue;
1676                }
1677                if (f->addr > 0 &&
1678                    f->addr != libusb_get_device_address(devs[i])) {
1679                    continue;
1680                }
1681                if (f->port != NULL) {
1682                    char port[16] = "-";
1683                    usb_host_get_port(devs[i], port, sizeof(port));
1684                    if (strcmp(f->port, port) != 0) {
1685                        continue;
1686                    }
1687                }
1688                if (f->vendor_id > 0 &&
1689                    f->vendor_id != ddesc.idVendor) {
1690                    continue;
1691                }
1692                if (f->product_id > 0 &&
1693                    f->product_id != ddesc.idProduct) {
1694                    continue;
1695                }
1696
1697                /* We got a match */
1698                s->seen++;
1699                if (s->errcount >= 3) {
1700                    continue;
1701                }
1702                if (s->dh != NULL) {
1703                    continue;
1704                }
1705                if (usb_host_open(s, devs[i]) < 0) {
1706                    s->errcount++;
1707                    continue;
1708                }
1709                break;
1710            }
1711        }
1712        libusb_free_device_list(devs, 1);
1713
1714        QTAILQ_FOREACH(s, &hostdevs, next) {
1715            if (s->dh == NULL) {
1716                unconnected++;
1717            }
1718            if (s->seen == 0) {
1719                if (s->dh) {
1720                    usb_host_close(s);
1721                }
1722                s->errcount = 0;
1723            }
1724            s->seen = 0;
1725        }
1726
1727#if 0
1728        if (unconnected == 0) {
1729            /* nothing to watch */
1730            if (usb_auto_timer) {
1731                timer_del(usb_auto_timer);
1732                trace_usb_host_auto_scan_disabled();
1733            }
1734            return;
1735        }
1736#endif
1737    }
1738
1739    if (!usb_vmstate) {
1740        usb_vmstate = qemu_add_vm_change_state_handler(usb_host_vm_state, NULL);
1741    }
1742    if (!usb_auto_timer) {
1743        usb_auto_timer = timer_new_ms(QEMU_CLOCK_REALTIME, usb_host_auto_check, NULL);
1744        if (!usb_auto_timer) {
1745            return;
1746        }
1747        trace_usb_host_auto_scan_enabled();
1748    }
1749    timer_mod(usb_auto_timer, qemu_clock_get_ms(QEMU_CLOCK_REALTIME) + 2000);
1750}
1751
1752/**
1753 * Check whether USB host device has a USB mass storage SCSI interface
1754 */
1755bool usb_host_dev_is_scsi_storage(USBDevice *ud)
1756{
1757    USBHostDevice *uhd = USB_HOST_DEVICE(ud);
1758    struct libusb_config_descriptor *conf;
1759    const struct libusb_interface_descriptor *intf;
1760    bool is_scsi_storage = false;
1761    int i;
1762
1763    if (!uhd || libusb_get_active_config_descriptor(uhd->dev, &conf) != 0) {
1764        return false;
1765    }
1766
1767    for (i = 0; i < conf->bNumInterfaces; i++) {
1768        intf = &conf->interface[i].altsetting[ud->altsetting[i]];
1769        if (intf->bInterfaceClass == LIBUSB_CLASS_MASS_STORAGE &&
1770            intf->bInterfaceSubClass == 6) {                 /* 6 means SCSI */
1771            is_scsi_storage = true;
1772            break;
1773        }
1774    }
1775
1776    libusb_free_config_descriptor(conf);
1777
1778    return is_scsi_storage;
1779}
1780
1781void hmp_info_usbhost(Monitor *mon, const QDict *qdict)
1782{
1783    libusb_device **devs = NULL;
1784    struct libusb_device_descriptor ddesc;
1785    char port[16];
1786    int i, n;
1787
1788    if (usb_host_init() != 0) {
1789        return;
1790    }
1791
1792    n = libusb_get_device_list(ctx, &devs);
1793    for (i = 0; i < n; i++) {
1794        if (libusb_get_device_descriptor(devs[i], &ddesc) != 0) {
1795            continue;
1796        }
1797        if (ddesc.bDeviceClass == LIBUSB_CLASS_HUB) {
1798            continue;
1799        }
1800        usb_host_get_port(devs[i], port, sizeof(port));
1801        monitor_printf(mon, "  Bus %d, Addr %d, Port %s, Speed %s Mb/s\n",
1802                       libusb_get_bus_number(devs[i]),
1803                       libusb_get_device_address(devs[i]),
1804                       port,
1805                       speed_name[libusb_get_device_speed(devs[i])]);
1806        monitor_printf(mon, "    Class %02x:", ddesc.bDeviceClass);
1807        monitor_printf(mon, " USB device %04x:%04x",
1808                       ddesc.idVendor, ddesc.idProduct);
1809        if (ddesc.iProduct) {
1810            libusb_device_handle *handle;
1811            if (libusb_open(devs[i], &handle) == 0) {
1812                unsigned char name[64] = "";
1813                libusb_get_string_descriptor_ascii(handle,
1814                                                   ddesc.iProduct,
1815                                                   name, sizeof(name));
1816                libusb_close(handle);
1817                monitor_printf(mon, ", %s", name);
1818            }
1819        }
1820        monitor_printf(mon, "\n");
1821    }
1822    libusb_free_device_list(devs, 1);
1823}
1824