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