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