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