redirect.c 49.4 KB
Newer Older
1 2 3
/*
 * USB redirector usb-guest
 *
4
 * Copyright (c) 2011-2012 Red Hat, Inc.
5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36
 *
 * Red Hat Authors:
 * Hans de Goede <hdegoede@redhat.com>
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
 * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 * THE SOFTWARE.
 */

#include "qemu-common.h"
#include "qemu-timer.h"
#include "monitor.h"
#include "sysemu.h"

#include <dirent.h>
#include <sys/ioctl.h>
#include <signal.h>
#include <usbredirparser.h>
37
#include <usbredirfilter.h>
38 39 40 41

#include "hw/usb.h"

#define MAX_ENDPOINTS 32
42
#define NO_INTERFACE_INFO 255 /* Valid interface_count always <= 32 */
43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59
#define EP2I(ep_address) (((ep_address & 0x80) >> 3) | (ep_address & 0x0f))
#define I2EP(i) (((i & 0x10) << 3) | (i & 0x0f))

typedef struct USBRedirDevice USBRedirDevice;

/* Struct to hold buffered packets (iso or int input packets) */
struct buf_packet {
    uint8_t *data;
    int len;
    int status;
    QTAILQ_ENTRY(buf_packet)next;
};

struct endp_data {
    uint8_t type;
    uint8_t interval;
    uint8_t interface; /* bInterfaceNumber this ep belongs to */
60
    uint16_t max_packet_size; /* In bytes, not wMaxPacketSize format !! */
61 62 63 64
    uint8_t iso_started;
    uint8_t iso_error; /* For reporting iso errors to the HC */
    uint8_t interrupt_started;
    uint8_t interrupt_error;
65
    uint8_t bufpq_prefilled;
66
    uint8_t bufpq_dropping_packets;
67
    QTAILQ_HEAD(, buf_packet) bufpq;
68
    int bufpq_size;
69
    int bufpq_target_size;
70 71
};

72 73 74 75 76 77 78 79 80 81 82 83
struct PacketIdQueueEntry {
    uint64_t id;
    QTAILQ_ENTRY(PacketIdQueueEntry)next;
};

struct PacketIdQueue {
    USBRedirDevice *dev;
    const char *name;
    QTAILQ_HEAD(, PacketIdQueueEntry) head;
    int size;
};

84 85 86 87 88
struct USBRedirDevice {
    USBDevice dev;
    /* Properties */
    CharDriverState *cs;
    uint8_t debug;
89
    char *filter_str;
90
    int32_t bootindex;
91 92 93
    /* Data passed from chardev the fd_read cb to the usbredirparser read cb */
    const uint8_t *read_buf;
    int read_buf_size;
94 95
    /* For async handling of close */
    QEMUBH *chardev_close_bh;
96 97 98 99 100
    /* To delay the usb attach in case of quick chardev close + open */
    QEMUTimer *attach_timer;
    int64_t next_attach_time;
    struct usbredirparser *parser;
    struct endp_data endpoint[MAX_ENDPOINTS];
101
    struct PacketIdQueue cancelled;
102
    struct PacketIdQueue already_in_flight;
103 104 105 106 107
    /* Data for device filtering */
    struct usb_redir_device_connect_header device_info;
    struct usb_redir_interface_info_header interface_info;
    struct usbredirfilter_rule *filter_rules;
    int filter_rules_count;
108 109
};

110
static void usbredir_hello(void *priv, struct usb_redir_hello_header *h);
111 112 113 114 115 116 117
static void usbredir_device_connect(void *priv,
    struct usb_redir_device_connect_header *device_connect);
static void usbredir_device_disconnect(void *priv);
static void usbredir_interface_info(void *priv,
    struct usb_redir_interface_info_header *interface_info);
static void usbredir_ep_info(void *priv,
    struct usb_redir_ep_info_header *ep_info);
118
static void usbredir_configuration_status(void *priv, uint64_t id,
119
    struct usb_redir_configuration_status_header *configuration_status);
120
static void usbredir_alt_setting_status(void *priv, uint64_t id,
121
    struct usb_redir_alt_setting_status_header *alt_setting_status);
122
static void usbredir_iso_stream_status(void *priv, uint64_t id,
123
    struct usb_redir_iso_stream_status_header *iso_stream_status);
124
static void usbredir_interrupt_receiving_status(void *priv, uint64_t id,
125 126
    struct usb_redir_interrupt_receiving_status_header
    *interrupt_receiving_status);
127
static void usbredir_bulk_streams_status(void *priv, uint64_t id,
128
    struct usb_redir_bulk_streams_status_header *bulk_streams_status);
129
static void usbredir_control_packet(void *priv, uint64_t id,
130 131
    struct usb_redir_control_packet_header *control_packet,
    uint8_t *data, int data_len);
132
static void usbredir_bulk_packet(void *priv, uint64_t id,
133 134
    struct usb_redir_bulk_packet_header *bulk_packet,
    uint8_t *data, int data_len);
135
static void usbredir_iso_packet(void *priv, uint64_t id,
136 137
    struct usb_redir_iso_packet_header *iso_packet,
    uint8_t *data, int data_len);
138
static void usbredir_interrupt_packet(void *priv, uint64_t id,
139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187
    struct usb_redir_interrupt_packet_header *interrupt_header,
    uint8_t *data, int data_len);

static int usbredir_handle_status(USBRedirDevice *dev,
                                       int status, int actual_len);

/*
 * Logging stuff
 */

#define ERROR(...) \
    do { \
        if (dev->debug >= usbredirparser_error) { \
            error_report("usb-redir error: " __VA_ARGS__); \
        } \
    } while (0)
#define WARNING(...) \
    do { \
        if (dev->debug >= usbredirparser_warning) { \
            error_report("usb-redir warning: " __VA_ARGS__); \
        } \
    } while (0)
#define INFO(...) \
    do { \
        if (dev->debug >= usbredirparser_info) { \
            error_report("usb-redir: " __VA_ARGS__); \
        } \
    } while (0)
#define DPRINTF(...) \
    do { \
        if (dev->debug >= usbredirparser_debug) { \
            error_report("usb-redir: " __VA_ARGS__); \
        } \
    } while (0)
#define DPRINTF2(...) \
    do { \
        if (dev->debug >= usbredirparser_debug_data) { \
            error_report("usb-redir: " __VA_ARGS__); \
        } \
    } while (0)

static void usbredir_log(void *priv, int level, const char *msg)
{
    USBRedirDevice *dev = priv;

    if (dev->debug < level) {
        return;
    }

188
    error_report("%s", msg);
189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206
}

static void usbredir_log_data(USBRedirDevice *dev, const char *desc,
    const uint8_t *data, int len)
{
    int i, j, n;

    if (dev->debug < usbredirparser_debug_data) {
        return;
    }

    for (i = 0; i < len; i += j) {
        char buf[128];

        n = sprintf(buf, "%s", desc);
        for (j = 0; j < 8 && i + j < len; j++) {
            n += sprintf(buf + n, " %02X", data[i + j]);
        }
207
        error_report("%s", buf);
208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238
    }
}

/*
 * usbredirparser io functions
 */

static int usbredir_read(void *priv, uint8_t *data, int count)
{
    USBRedirDevice *dev = priv;

    if (dev->read_buf_size < count) {
        count = dev->read_buf_size;
    }

    memcpy(data, dev->read_buf, count);

    dev->read_buf_size -= count;
    if (dev->read_buf_size) {
        dev->read_buf += count;
    } else {
        dev->read_buf = NULL;
    }

    return count;
}

static int usbredir_write(void *priv, uint8_t *data, int count)
{
    USBRedirDevice *dev = priv;

239 240 241 242
    if (!dev->cs->opened) {
        return 0;
    }

243
    return qemu_chr_fe_write(dev->cs, data, count);
244 245 246
}

/*
247
 * Cancelled and buffered packets helpers
248 249
 */

250 251
static void packet_id_queue_init(struct PacketIdQueue *q,
    USBRedirDevice *dev, const char *name)
252
{
253 254 255 256 257 258 259 260 261 262
    q->dev = dev;
    q->name = name;
    QTAILQ_INIT(&q->head);
    q->size = 0;
}

static void packet_id_queue_add(struct PacketIdQueue *q, uint64_t id)
{
    USBRedirDevice *dev = q->dev;
    struct PacketIdQueueEntry *e;
263

264 265 266 267 268 269 270
    DPRINTF("adding packet id %"PRIu64" to %s queue\n", id, q->name);

    e = g_malloc0(sizeof(struct PacketIdQueueEntry));
    e->id = id;
    QTAILQ_INSERT_TAIL(&q->head, e, next);
    q->size++;
}
271

272 273 274 275
static int packet_id_queue_remove(struct PacketIdQueue *q, uint64_t id)
{
    USBRedirDevice *dev = q->dev;
    struct PacketIdQueueEntry *e;
276

277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308
    QTAILQ_FOREACH(e, &q->head, next) {
        if (e->id == id) {
            DPRINTF("removing packet id %"PRIu64" from %s queue\n",
                    id, q->name);
            QTAILQ_REMOVE(&q->head, e, next);
            q->size--;
            g_free(e);
            return 1;
        }
    }
    return 0;
}

static void packet_id_queue_empty(struct PacketIdQueue *q)
{
    USBRedirDevice *dev = q->dev;
    struct PacketIdQueueEntry *e, *next_e;

    DPRINTF("removing %d packet-ids from %s queue\n", q->size, q->name);

    QTAILQ_FOREACH_SAFE(e, &q->head, next, next_e) {
        QTAILQ_REMOVE(&q->head, e, next);
        g_free(e);
    }
    q->size = 0;
}

static void usbredir_cancel_packet(USBDevice *udev, USBPacket *p)
{
    USBRedirDevice *dev = DO_UPCAST(USBRedirDevice, dev, udev);

    packet_id_queue_add(&dev->cancelled, p->id);
309 310
    usbredirparser_send_cancel_data_packet(dev->parser, p->id);
    usbredirparser_do_write(dev->parser);
311 312
}

313
static int usbredir_is_cancelled(USBRedirDevice *dev, uint64_t id)
314
{
315 316 317
    if (!dev->dev.attached) {
        return 1; /* Treat everything as cancelled after a disconnect */
    }
318
    return packet_id_queue_remove(&dev->cancelled, id);
319 320
}

321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348
static void usbredir_fill_already_in_flight_from_ep(USBRedirDevice *dev,
    struct USBEndpoint *ep)
{
    static USBPacket *p;

    QTAILQ_FOREACH(p, &ep->queue, queue) {
        packet_id_queue_add(&dev->already_in_flight, p->id);
    }
}

static void usbredir_fill_already_in_flight(USBRedirDevice *dev)
{
    int ep;
    struct USBDevice *udev = &dev->dev;

    usbredir_fill_already_in_flight_from_ep(dev, &udev->ep_ctl);

    for (ep = 0; ep < USB_MAX_ENDPOINTS; ep++) {
        usbredir_fill_already_in_flight_from_ep(dev, &udev->ep_in[ep]);
        usbredir_fill_already_in_flight_from_ep(dev, &udev->ep_out[ep]);
    }
}

static int usbredir_already_in_flight(USBRedirDevice *dev, uint64_t id)
{
    return packet_id_queue_remove(&dev->already_in_flight, id);
}

349 350
static USBPacket *usbredir_find_packet_by_id(USBRedirDevice *dev,
    uint8_t ep, uint64_t id)
351
{
352
    USBPacket *p;
353

354 355 356
    if (usbredir_is_cancelled(dev, id)) {
        return NULL;
    }
357

358 359 360 361 362
    p = usb_ep_find_packet_by_id(&dev->dev,
                            (ep & USB_DIR_IN) ? USB_TOKEN_IN : USB_TOKEN_OUT,
                            ep & 0x0f, id);
    if (p == NULL) {
        ERROR("could not find packet with id %"PRIu64"\n", id);
363
    }
364
    return p;
365 366
}

367
static void bufp_alloc(USBRedirDevice *dev,
368 369
    uint8_t *data, int len, int status, uint8_t ep)
{
370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389
    struct buf_packet *bufp;

    if (!dev->endpoint[EP2I(ep)].bufpq_dropping_packets &&
        dev->endpoint[EP2I(ep)].bufpq_size >
            2 * dev->endpoint[EP2I(ep)].bufpq_target_size) {
        DPRINTF("bufpq overflow, dropping packets ep %02X\n", ep);
        dev->endpoint[EP2I(ep)].bufpq_dropping_packets = 1;
    }
    /* Since we're interupting the stream anyways, drop enough packets to get
       back to our target buffer size */
    if (dev->endpoint[EP2I(ep)].bufpq_dropping_packets) {
        if (dev->endpoint[EP2I(ep)].bufpq_size >
                dev->endpoint[EP2I(ep)].bufpq_target_size) {
            free(data);
            return;
        }
        dev->endpoint[EP2I(ep)].bufpq_dropping_packets = 0;
    }

    bufp = g_malloc(sizeof(struct buf_packet));
390 391 392 393
    bufp->data   = data;
    bufp->len    = len;
    bufp->status = status;
    QTAILQ_INSERT_TAIL(&dev->endpoint[EP2I(ep)].bufpq, bufp, next);
394
    dev->endpoint[EP2I(ep)].bufpq_size++;
395 396 397 398 399 400
}

static void bufp_free(USBRedirDevice *dev, struct buf_packet *bufp,
    uint8_t ep)
{
    QTAILQ_REMOVE(&dev->endpoint[EP2I(ep)].bufpq, bufp, next);
401
    dev->endpoint[EP2I(ep)].bufpq_size--;
402
    free(bufp->data);
403
    g_free(bufp);
404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436
}

static void usbredir_free_bufpq(USBRedirDevice *dev, uint8_t ep)
{
    struct buf_packet *buf, *buf_next;

    QTAILQ_FOREACH_SAFE(buf, &dev->endpoint[EP2I(ep)].bufpq, next, buf_next) {
        bufp_free(dev, buf, ep);
    }
}

/*
 * USBDevice callbacks
 */

static void usbredir_handle_reset(USBDevice *udev)
{
    USBRedirDevice *dev = DO_UPCAST(USBRedirDevice, dev, udev);

    DPRINTF("reset device\n");
    usbredirparser_send_reset(dev->parser);
    usbredirparser_do_write(dev->parser);
}

static int usbredir_handle_iso_data(USBRedirDevice *dev, USBPacket *p,
                                     uint8_t ep)
{
    int status, len;
    if (!dev->endpoint[EP2I(ep)].iso_started &&
            !dev->endpoint[EP2I(ep)].iso_error) {
        struct usb_redir_start_iso_stream_header start_iso = {
            .endpoint = ep,
        };
437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467
        int pkts_per_sec;

        if (dev->dev.speed == USB_SPEED_HIGH) {
            pkts_per_sec = 8000 / dev->endpoint[EP2I(ep)].interval;
        } else {
            pkts_per_sec = 1000 / dev->endpoint[EP2I(ep)].interval;
        }
        /* Testing has shown that we need circa 60 ms buffer */
        dev->endpoint[EP2I(ep)].bufpq_target_size = (pkts_per_sec * 60) / 1000;

        /* Aim for approx 100 interrupts / second on the client to
           balance latency and interrupt load */
        start_iso.pkts_per_urb = pkts_per_sec / 100;
        if (start_iso.pkts_per_urb < 1) {
            start_iso.pkts_per_urb = 1;
        } else if (start_iso.pkts_per_urb > 32) {
            start_iso.pkts_per_urb = 32;
        }

        start_iso.no_urbs = (dev->endpoint[EP2I(ep)].bufpq_target_size +
                             start_iso.pkts_per_urb - 1) /
                            start_iso.pkts_per_urb;
        /* Output endpoints pre-fill only 1/2 of the packets, keeping the rest
           as overflow buffer. Also see the usbredir protocol documentation */
        if (!(ep & USB_DIR_IN)) {
            start_iso.no_urbs *= 2;
        }
        if (start_iso.no_urbs > 16) {
            start_iso.no_urbs = 16;
        }

468 469 470
        /* No id, we look at the ep when receiving a status back */
        usbredirparser_send_start_iso_stream(dev->parser, 0, &start_iso);
        usbredirparser_do_write(dev->parser);
471 472
        DPRINTF("iso stream started pkts/sec %d pkts/urb %d urbs %d ep %02X\n",
                pkts_per_sec, start_iso.pkts_per_urb, start_iso.no_urbs, ep);
473
        dev->endpoint[EP2I(ep)].iso_started = 1;
474
        dev->endpoint[EP2I(ep)].bufpq_prefilled = 0;
475
        dev->endpoint[EP2I(ep)].bufpq_dropping_packets = 0;
476 477 478 479 480
    }

    if (ep & USB_DIR_IN) {
        struct buf_packet *isop;

481 482 483 484 485 486 487 488 489
        if (dev->endpoint[EP2I(ep)].iso_started &&
                !dev->endpoint[EP2I(ep)].bufpq_prefilled) {
            if (dev->endpoint[EP2I(ep)].bufpq_size <
                    dev->endpoint[EP2I(ep)].bufpq_target_size) {
                return usbredir_handle_status(dev, 0, 0);
            }
            dev->endpoint[EP2I(ep)].bufpq_prefilled = 1;
        }

490 491
        isop = QTAILQ_FIRST(&dev->endpoint[EP2I(ep)].bufpq);
        if (isop == NULL) {
492 493
            DPRINTF("iso-token-in ep %02X, no isop, iso_error: %d\n",
                    ep, dev->endpoint[EP2I(ep)].iso_error);
494 495
            /* Re-fill the buffer */
            dev->endpoint[EP2I(ep)].bufpq_prefilled = 0;
496 497 498
            /* Check iso_error for stream errors, otherwise its an underrun */
            status = dev->endpoint[EP2I(ep)].iso_error;
            dev->endpoint[EP2I(ep)].iso_error = 0;
H
Hans de Goede 已提交
499
            return status ? USB_RET_IOERROR : 0;
500
        }
501 502
        DPRINTF2("iso-token-in ep %02X status %d len %d queue-size: %d\n", ep,
                 isop->status, isop->len, dev->endpoint[EP2I(ep)].bufpq_size);
503 504 505 506

        status = isop->status;
        if (status != usb_redir_success) {
            bufp_free(dev, isop, ep);
H
Hans de Goede 已提交
507
            return USB_RET_IOERROR;
508 509 510
        }

        len = isop->len;
G
Gerd Hoffmann 已提交
511
        if (len > p->iov.size) {
512 513
            ERROR("received iso data is larger then packet ep %02X (%d > %d)\n",
                  ep, len, (int)p->iov.size);
514
            bufp_free(dev, isop, ep);
515
            return USB_RET_BABBLE;
516
        }
G
Gerd Hoffmann 已提交
517
        usb_packet_copy(p, isop->data, len);
518 519 520 521 522 523 524 525
        bufp_free(dev, isop, ep);
        return len;
    } else {
        /* If the stream was not started because of a pending error don't
           send the packet to the usb-host */
        if (dev->endpoint[EP2I(ep)].iso_started) {
            struct usb_redir_iso_packet_header iso_packet = {
                .endpoint = ep,
G
Gerd Hoffmann 已提交
526
                .length = p->iov.size
527
            };
G
Gerd Hoffmann 已提交
528
            uint8_t buf[p->iov.size];
529
            /* No id, we look at the ep when receiving a status back */
G
Gerd Hoffmann 已提交
530
            usb_packet_copy(p, buf, p->iov.size);
531
            usbredirparser_send_iso_packet(dev->parser, 0, &iso_packet,
G
Gerd Hoffmann 已提交
532
                                           buf, p->iov.size);
533 534 535 536
            usbredirparser_do_write(dev->parser);
        }
        status = dev->endpoint[EP2I(ep)].iso_error;
        dev->endpoint[EP2I(ep)].iso_error = 0;
G
Gerd Hoffmann 已提交
537 538 539
        DPRINTF2("iso-token-out ep %02X status %d len %zd\n", ep, status,
                 p->iov.size);
        return usbredir_handle_status(dev, status, p->iov.size);
540 541 542 543 544 545 546 547 548 549 550 551 552
    }
}

static void usbredir_stop_iso_stream(USBRedirDevice *dev, uint8_t ep)
{
    struct usb_redir_stop_iso_stream_header stop_iso_stream = {
        .endpoint = ep
    };
    if (dev->endpoint[EP2I(ep)].iso_started) {
        usbredirparser_send_stop_iso_stream(dev->parser, 0, &stop_iso_stream);
        DPRINTF("iso stream stopped ep %02X\n", ep);
        dev->endpoint[EP2I(ep)].iso_started = 0;
    }
553
    dev->endpoint[EP2I(ep)].iso_error = 0;
554 555 556 557 558 559 560 561
    usbredir_free_bufpq(dev, ep);
}

static int usbredir_handle_bulk_data(USBRedirDevice *dev, USBPacket *p,
                                      uint8_t ep)
{
    struct usb_redir_bulk_packet_header bulk_packet;

562
    DPRINTF("bulk-out ep %02X len %zd id %"PRIu64"\n", ep, p->iov.size, p->id);
563

564 565 566 567
    if (usbredir_already_in_flight(dev, p->id)) {
        return USB_RET_ASYNC;
    }

568
    bulk_packet.endpoint  = ep;
G
Gerd Hoffmann 已提交
569
    bulk_packet.length    = p->iov.size;
570 571 572
    bulk_packet.stream_id = 0;

    if (ep & USB_DIR_IN) {
573
        usbredirparser_send_bulk_packet(dev->parser, p->id,
574 575
                                        &bulk_packet, NULL, 0);
    } else {
G
Gerd Hoffmann 已提交
576 577 578
        uint8_t buf[p->iov.size];
        usb_packet_copy(p, buf, p->iov.size);
        usbredir_log_data(dev, "bulk data out:", buf, p->iov.size);
579
        usbredirparser_send_bulk_packet(dev->parser, p->id,
G
Gerd Hoffmann 已提交
580
                                        &bulk_packet, buf, p->iov.size);
581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604
    }
    usbredirparser_do_write(dev->parser);
    return USB_RET_ASYNC;
}

static int usbredir_handle_interrupt_data(USBRedirDevice *dev,
                                           USBPacket *p, uint8_t ep)
{
    if (ep & USB_DIR_IN) {
        /* Input interrupt endpoint, buffered packet input */
        struct buf_packet *intp;
        int status, len;

        if (!dev->endpoint[EP2I(ep)].interrupt_started &&
                !dev->endpoint[EP2I(ep)].interrupt_error) {
            struct usb_redir_start_interrupt_receiving_header start_int = {
                .endpoint = ep,
            };
            /* No id, we look at the ep when receiving a status back */
            usbredirparser_send_start_interrupt_receiving(dev->parser, 0,
                                                          &start_int);
            usbredirparser_do_write(dev->parser);
            DPRINTF("interrupt recv started ep %02X\n", ep);
            dev->endpoint[EP2I(ep)].interrupt_started = 1;
605 606 607 608
            /* We don't really want to drop interrupt packets ever, but
               having some upper limit to how much we buffer is good. */
            dev->endpoint[EP2I(ep)].bufpq_target_size = 1000;
            dev->endpoint[EP2I(ep)].bufpq_dropping_packets = 0;
609 610 611 612 613 614 615 616
        }

        intp = QTAILQ_FIRST(&dev->endpoint[EP2I(ep)].bufpq);
        if (intp == NULL) {
            DPRINTF2("interrupt-token-in ep %02X, no intp\n", ep);
            /* Check interrupt_error for stream errors */
            status = dev->endpoint[EP2I(ep)].interrupt_error;
            dev->endpoint[EP2I(ep)].interrupt_error = 0;
617 618 619 620
            if (status) {
                return usbredir_handle_status(dev, status, 0);
            }
            return USB_RET_NAK;
621 622 623 624 625 626 627 628 629 630 631
        }
        DPRINTF("interrupt-token-in ep %02X status %d len %d\n", ep,
                intp->status, intp->len);

        status = intp->status;
        if (status != usb_redir_success) {
            bufp_free(dev, intp, ep);
            return usbredir_handle_status(dev, status, 0);
        }

        len = intp->len;
G
Gerd Hoffmann 已提交
632
        if (len > p->iov.size) {
633 634
            ERROR("received int data is larger then packet ep %02X\n", ep);
            bufp_free(dev, intp, ep);
635
            return USB_RET_BABBLE;
636
        }
G
Gerd Hoffmann 已提交
637
        usb_packet_copy(p, intp->data, len);
638 639 640 641 642
        bufp_free(dev, intp, ep);
        return len;
    } else {
        /* Output interrupt endpoint, normal async operation */
        struct usb_redir_interrupt_packet_header interrupt_packet;
G
Gerd Hoffmann 已提交
643
        uint8_t buf[p->iov.size];
644

645 646
        DPRINTF("interrupt-out ep %02X len %zd id %"PRIu64"\n", ep,
                p->iov.size, p->id);
647

648 649 650 651
        if (usbredir_already_in_flight(dev, p->id)) {
            return USB_RET_ASYNC;
        }

652
        interrupt_packet.endpoint  = ep;
G
Gerd Hoffmann 已提交
653
        interrupt_packet.length    = p->iov.size;
654

G
Gerd Hoffmann 已提交
655 656
        usb_packet_copy(p, buf, p->iov.size);
        usbredir_log_data(dev, "interrupt data out:", buf, p->iov.size);
657
        usbredirparser_send_interrupt_packet(dev->parser, p->id,
G
Gerd Hoffmann 已提交
658
                                        &interrupt_packet, buf, p->iov.size);
659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675
        usbredirparser_do_write(dev->parser);
        return USB_RET_ASYNC;
    }
}

static void usbredir_stop_interrupt_receiving(USBRedirDevice *dev,
    uint8_t ep)
{
    struct usb_redir_stop_interrupt_receiving_header stop_interrupt_recv = {
        .endpoint = ep
    };
    if (dev->endpoint[EP2I(ep)].interrupt_started) {
        usbredirparser_send_stop_interrupt_receiving(dev->parser, 0,
                                                     &stop_interrupt_recv);
        DPRINTF("interrupt recv stopped ep %02X\n", ep);
        dev->endpoint[EP2I(ep)].interrupt_started = 0;
    }
676
    dev->endpoint[EP2I(ep)].interrupt_error = 0;
677 678 679 680 681 682 683 684
    usbredir_free_bufpq(dev, ep);
}

static int usbredir_handle_data(USBDevice *udev, USBPacket *p)
{
    USBRedirDevice *dev = DO_UPCAST(USBRedirDevice, dev, udev);
    uint8_t ep;

685
    ep = p->ep->nr;
686 687 688 689 690 691 692 693 694 695 696
    if (p->pid == USB_TOKEN_IN) {
        ep |= USB_DIR_IN;
    }

    switch (dev->endpoint[EP2I(ep)].type) {
    case USB_ENDPOINT_XFER_CONTROL:
        ERROR("handle_data called for control transfer on ep %02X\n", ep);
        return USB_RET_NAK;
    case USB_ENDPOINT_XFER_ISOC:
        return usbredir_handle_iso_data(dev, p, ep);
    case USB_ENDPOINT_XFER_BULK:
697
        return usbredir_handle_bulk_data(dev, p, ep);
698
    case USB_ENDPOINT_XFER_INT:
699
        return usbredir_handle_interrupt_data(dev, p, ep);
700 701 702 703 704 705 706 707 708 709 710 711 712
    default:
        ERROR("handle_data ep %02X has unknown type %d\n", ep,
              dev->endpoint[EP2I(ep)].type);
        return USB_RET_NAK;
    }
}

static int usbredir_set_config(USBRedirDevice *dev, USBPacket *p,
                                int config)
{
    struct usb_redir_set_configuration_header set_config;
    int i;

713
    DPRINTF("set config %d id %"PRIu64"\n", config, p->id);
714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729

    for (i = 0; i < MAX_ENDPOINTS; i++) {
        switch (dev->endpoint[i].type) {
        case USB_ENDPOINT_XFER_ISOC:
            usbredir_stop_iso_stream(dev, I2EP(i));
            break;
        case USB_ENDPOINT_XFER_INT:
            if (i & 0x10) {
                usbredir_stop_interrupt_receiving(dev, I2EP(i));
            }
            break;
        }
        usbredir_free_bufpq(dev, I2EP(i));
    }

    set_config.configuration = config;
730
    usbredirparser_send_set_configuration(dev->parser, p->id, &set_config);
731 732 733 734 735 736
    usbredirparser_do_write(dev->parser);
    return USB_RET_ASYNC;
}

static int usbredir_get_config(USBRedirDevice *dev, USBPacket *p)
{
737
    DPRINTF("get config id %"PRIu64"\n", p->id);
738

739
    usbredirparser_send_get_configuration(dev->parser, p->id);
740 741 742 743 744 745 746 747 748 749
    usbredirparser_do_write(dev->parser);
    return USB_RET_ASYNC;
}

static int usbredir_set_interface(USBRedirDevice *dev, USBPacket *p,
                                   int interface, int alt)
{
    struct usb_redir_set_alt_setting_header set_alt;
    int i;

750
    DPRINTF("set interface %d alt %d id %"PRIu64"\n", interface, alt, p->id);
751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769

    for (i = 0; i < MAX_ENDPOINTS; i++) {
        if (dev->endpoint[i].interface == interface) {
            switch (dev->endpoint[i].type) {
            case USB_ENDPOINT_XFER_ISOC:
                usbredir_stop_iso_stream(dev, I2EP(i));
                break;
            case USB_ENDPOINT_XFER_INT:
                if (i & 0x10) {
                    usbredir_stop_interrupt_receiving(dev, I2EP(i));
                }
                break;
            }
            usbredir_free_bufpq(dev, I2EP(i));
        }
    }

    set_alt.interface = interface;
    set_alt.alt = alt;
770
    usbredirparser_send_set_alt_setting(dev->parser, p->id, &set_alt);
771 772 773 774 775 776 777 778 779
    usbredirparser_do_write(dev->parser);
    return USB_RET_ASYNC;
}

static int usbredir_get_interface(USBRedirDevice *dev, USBPacket *p,
                                   int interface)
{
    struct usb_redir_get_alt_setting_header get_alt;

780
    DPRINTF("get interface %d id %"PRIu64"\n", interface, p->id);
781 782

    get_alt.interface = interface;
783
    usbredirparser_send_get_alt_setting(dev->parser, p->id, &get_alt);
784 785 786 787 788 789 790 791 792 793
    usbredirparser_do_write(dev->parser);
    return USB_RET_ASYNC;
}

static int usbredir_handle_control(USBDevice *udev, USBPacket *p,
        int request, int value, int index, int length, uint8_t *data)
{
    USBRedirDevice *dev = DO_UPCAST(USBRedirDevice, dev, udev);
    struct usb_redir_control_packet_header control_packet;

794 795 796 797
    if (usbredir_already_in_flight(dev, p->id)) {
        return USB_RET_ASYNC;
    }

798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813
    /* Special cases for certain standard device requests */
    switch (request) {
    case DeviceOutRequest | USB_REQ_SET_ADDRESS:
        DPRINTF("set address %d\n", value);
        dev->dev.addr = value;
        return 0;
    case DeviceOutRequest | USB_REQ_SET_CONFIGURATION:
        return usbredir_set_config(dev, p, value & 0xff);
    case DeviceRequest | USB_REQ_GET_CONFIGURATION:
        return usbredir_get_config(dev, p);
    case InterfaceOutRequest | USB_REQ_SET_INTERFACE:
        return usbredir_set_interface(dev, p, index, value);
    case InterfaceRequest | USB_REQ_GET_INTERFACE:
        return usbredir_get_interface(dev, p, index);
    }

814 815 816 817
    /* Normal ctrl requests, note request is (bRequestType << 8) | bRequest */
    DPRINTF(
        "ctrl-out type 0x%x req 0x%x val 0x%x index %d len %d id %"PRIu64"\n",
        request >> 8, request & 0xff, value, index, length, p->id);
818 819 820 821 822 823 824 825 826

    control_packet.request     = request & 0xFF;
    control_packet.requesttype = request >> 8;
    control_packet.endpoint    = control_packet.requesttype & USB_DIR_IN;
    control_packet.value       = value;
    control_packet.index       = index;
    control_packet.length      = length;

    if (control_packet.requesttype & USB_DIR_IN) {
827
        usbredirparser_send_control_packet(dev->parser, p->id,
828 829 830
                                           &control_packet, NULL, 0);
    } else {
        usbredir_log_data(dev, "ctrl data out:", data, length);
831
        usbredirparser_send_control_packet(dev->parser, p->id,
832 833 834 835 836 837 838 839 840 841 842
                                           &control_packet, data, length);
    }
    usbredirparser_do_write(dev->parser);
    return USB_RET_ASYNC;
}

/*
 * Close events can be triggered by usbredirparser_do_write which gets called
 * from within the USBDevice data / control packet callbacks and doing a
 * usb_detach from within these callbacks is not a good idea.
 *
843
 * So we use a bh handler to take care of close events.
844
 */
845
static void usbredir_chardev_close_bh(void *opaque)
846 847 848 849 850 851 852 853 854
{
    USBRedirDevice *dev = opaque;

    usbredir_device_disconnect(dev);

    if (dev->parser) {
        usbredirparser_destroy(dev->parser);
        dev->parser = NULL;
    }
855
}
856

857 858 859 860
static void usbredir_chardev_open(USBRedirDevice *dev)
{
    uint32_t caps[USB_REDIR_CAPS_SIZE] = { 0, };
    char version[32];
861

862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893
    /* Make sure any pending closes are handled (no-op if none pending) */
    usbredir_chardev_close_bh(dev);
    qemu_bh_cancel(dev->chardev_close_bh);

    strcpy(version, "qemu usb-redir guest ");
    pstrcat(version, sizeof(version), qemu_get_version());

    dev->parser = qemu_oom_check(usbredirparser_create());
    dev->parser->priv = dev;
    dev->parser->log_func = usbredir_log;
    dev->parser->read_func = usbredir_read;
    dev->parser->write_func = usbredir_write;
    dev->parser->hello_func = usbredir_hello;
    dev->parser->device_connect_func = usbredir_device_connect;
    dev->parser->device_disconnect_func = usbredir_device_disconnect;
    dev->parser->interface_info_func = usbredir_interface_info;
    dev->parser->ep_info_func = usbredir_ep_info;
    dev->parser->configuration_status_func = usbredir_configuration_status;
    dev->parser->alt_setting_status_func = usbredir_alt_setting_status;
    dev->parser->iso_stream_status_func = usbredir_iso_stream_status;
    dev->parser->interrupt_receiving_status_func =
        usbredir_interrupt_receiving_status;
    dev->parser->bulk_streams_status_func = usbredir_bulk_streams_status;
    dev->parser->control_packet_func = usbredir_control_packet;
    dev->parser->bulk_packet_func = usbredir_bulk_packet;
    dev->parser->iso_packet_func = usbredir_iso_packet;
    dev->parser->interrupt_packet_func = usbredir_interrupt_packet;
    dev->read_buf = NULL;
    dev->read_buf_size = 0;

    usbredirparser_caps_set_cap(caps, usb_redir_cap_connect_device_version);
    usbredirparser_caps_set_cap(caps, usb_redir_cap_filter);
894
    usbredirparser_caps_set_cap(caps, usb_redir_cap_ep_info_max_packet_size);
895
    usbredirparser_caps_set_cap(caps, usb_redir_cap_64bits_ids);
896 897
    usbredirparser_init(dev->parser, version, caps, USB_REDIR_CAPS_SIZE, 0);
    usbredirparser_do_write(dev->parser);
898 899
}

900 901 902 903 904 905 906 907 908
static void usbredir_reject_device(USBRedirDevice *dev)
{
    usbredir_device_disconnect(dev);
    if (usbredirparser_peer_has_cap(dev->parser, usb_redir_cap_filter)) {
        usbredirparser_send_filter_reject(dev->parser);
        usbredirparser_do_write(dev->parser);
    }
}

909 910 911 912
static void usbredir_do_attach(void *opaque)
{
    USBRedirDevice *dev = opaque;

913 914 915 916 917 918 919 920 921 922 923
    /* In order to work properly with XHCI controllers we need these caps */
    if ((dev->dev.port->speedmask & USB_SPEED_MASK_SUPER) && !(
        usbredirparser_peer_has_cap(dev->parser,
                                    usb_redir_cap_ep_info_max_packet_size) &&
        usbredirparser_peer_has_cap(dev->parser,
                                    usb_redir_cap_64bits_ids))) {
        ERROR("usb-redir-host lacks capabilities needed for use with XHCI\n");
        usbredir_reject_device(dev);
        return;
    }

924
    if (usb_device_attach(&dev->dev) != 0) {
925
        usbredir_reject_device(dev);
926
    }
927 928 929 930 931 932 933 934 935 936
}

/*
 * chardev callbacks
 */

static int usbredir_chardev_can_read(void *opaque)
{
    USBRedirDevice *dev = opaque;

937 938
    if (!dev->parser) {
        WARNING("chardev_can_read called on non open chardev!\n");
939 940
        return 0;
    }
941 942 943

    /* usbredir_parser_do_read will consume *all* data we give it */
    return 1024 * 1024;
944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966
}

static void usbredir_chardev_read(void *opaque, const uint8_t *buf, int size)
{
    USBRedirDevice *dev = opaque;

    /* No recursion allowed! */
    assert(dev->read_buf == NULL);

    dev->read_buf = buf;
    dev->read_buf_size = size;

    usbredirparser_do_read(dev->parser);
    /* Send any acks, etc. which may be queued now */
    usbredirparser_do_write(dev->parser);
}

static void usbredir_chardev_event(void *opaque, int event)
{
    USBRedirDevice *dev = opaque;

    switch (event) {
    case CHR_EVENT_OPENED:
967 968
        usbredir_chardev_open(dev);
        break;
969
    case CHR_EVENT_CLOSED:
970
        qemu_bh_schedule(dev->chardev_close_bh);
971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988
        break;
    }
}

/*
 * init + destroy
 */

static int usbredir_initfn(USBDevice *udev)
{
    USBRedirDevice *dev = DO_UPCAST(USBRedirDevice, dev, udev);
    int i;

    if (dev->cs == NULL) {
        qerror_report(QERR_MISSING_PARAMETER, "chardev");
        return -1;
    }

989 990 991 992 993 994 995 996 997 998 999
    if (dev->filter_str) {
        i = usbredirfilter_string_to_rules(dev->filter_str, ":", "|",
                                           &dev->filter_rules,
                                           &dev->filter_rules_count);
        if (i) {
            qerror_report(QERR_INVALID_PARAMETER_VALUE, "filter",
                          "a usb device filter string");
            return -1;
        }
    }

1000
    dev->chardev_close_bh = qemu_bh_new(usbredir_chardev_close_bh, dev);
1001 1002
    dev->attach_timer = qemu_new_timer_ms(vm_clock, usbredir_do_attach, dev);

1003
    packet_id_queue_init(&dev->cancelled, dev, "cancelled");
1004
    packet_id_queue_init(&dev->already_in_flight, dev, "already-in-flight");
1005 1006 1007 1008 1009 1010 1011
    for (i = 0; i < MAX_ENDPOINTS; i++) {
        QTAILQ_INIT(&dev->endpoint[i].bufpq);
    }

    /* We'll do the attach once we receive the speed from the usb-host */
    udev->auto_attach = 0;

1012 1013
    /* Let the backend know we are ready */
    qemu_chr_fe_open(dev->cs);
1014 1015 1016
    qemu_chr_add_handlers(dev->cs, usbredir_chardev_can_read,
                          usbredir_chardev_read, usbredir_chardev_event, dev);

1017
    add_boot_device_path(dev->bootindex, &udev->qdev, NULL);
1018 1019 1020 1021 1022 1023 1024
    return 0;
}

static void usbredir_cleanup_device_queues(USBRedirDevice *dev)
{
    int i;

1025
    packet_id_queue_empty(&dev->cancelled);
1026
    packet_id_queue_empty(&dev->already_in_flight);
1027 1028 1029 1030 1031 1032 1033 1034 1035
    for (i = 0; i < MAX_ENDPOINTS; i++) {
        usbredir_free_bufpq(dev, I2EP(i));
    }
}

static void usbredir_handle_destroy(USBDevice *udev)
{
    USBRedirDevice *dev = DO_UPCAST(USBRedirDevice, dev, udev);

1036
    qemu_chr_fe_close(dev->cs);
1037
    qemu_chr_delete(dev->cs);
1038
    /* Note must be done after qemu_chr_close, as that causes a close event */
1039
    qemu_bh_delete(dev->chardev_close_bh);
1040 1041 1042 1043 1044 1045 1046 1047 1048

    qemu_del_timer(dev->attach_timer);
    qemu_free_timer(dev->attach_timer);

    usbredir_cleanup_device_queues(dev);

    if (dev->parser) {
        usbredirparser_destroy(dev->parser);
    }
1049 1050 1051 1052 1053 1054

    free(dev->filter_rules);
}

static int usbredir_check_filter(USBRedirDevice *dev)
{
1055
    if (dev->interface_info.interface_count == NO_INTERFACE_INFO) {
1056
        ERROR("No interface info for device\n");
1057
        goto error;
1058 1059 1060 1061 1062 1063 1064
    }

    if (dev->filter_rules) {
        if (!usbredirparser_peer_has_cap(dev->parser,
                                    usb_redir_cap_connect_device_version)) {
            ERROR("Device filter specified and peer does not have the "
                  "connect_device_version capability\n");
1065
            goto error;
1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081
        }

        if (usbredirfilter_check(
                dev->filter_rules,
                dev->filter_rules_count,
                dev->device_info.device_class,
                dev->device_info.device_subclass,
                dev->device_info.device_protocol,
                dev->interface_info.interface_class,
                dev->interface_info.interface_subclass,
                dev->interface_info.interface_protocol,
                dev->interface_info.interface_count,
                dev->device_info.vendor_id,
                dev->device_info.product_id,
                dev->device_info.device_version_bcd,
                0) != 0) {
1082
            goto error;
1083 1084 1085 1086
        }
    }

    return 0;
1087 1088

error:
1089
    usbredir_reject_device(dev);
1090
    return -1;
1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105
}

/*
 * usbredirparser packet complete callbacks
 */

static int usbredir_handle_status(USBRedirDevice *dev,
                                       int status, int actual_len)
{
    switch (status) {
    case usb_redir_success:
        return actual_len;
    case usb_redir_stall:
        return USB_RET_STALL;
    case usb_redir_cancelled:
1106 1107 1108 1109 1110
        /*
         * When the usbredir-host unredirects a device, it will report a status
         * of cancelled for all pending packets, followed by a disconnect msg.
         */
        return USB_RET_IOERROR;
1111
    case usb_redir_inval:
H
Hans de Goede 已提交
1112
        WARNING("got invalid param error from usb-host?\n");
1113
        return USB_RET_IOERROR;
1114 1115
    case usb_redir_babble:
        return USB_RET_BABBLE;
1116 1117 1118
    case usb_redir_ioerror:
    case usb_redir_timeout:
    default:
H
Hans de Goede 已提交
1119
        return USB_RET_IOERROR;
1120 1121 1122
    }
}

1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135
static void usbredir_hello(void *priv, struct usb_redir_hello_header *h)
{
    USBRedirDevice *dev = priv;

    /* Try to send the filter info now that we've the usb-host's caps */
    if (usbredirparser_peer_has_cap(dev->parser, usb_redir_cap_filter) &&
            dev->filter_rules) {
        usbredirparser_send_filter_filter(dev->parser, dev->filter_rules,
                                          dev->filter_rules_count);
        usbredirparser_do_write(dev->parser);
    }
}

1136 1137 1138 1139
static void usbredir_device_connect(void *priv,
    struct usb_redir_device_connect_header *device_connect)
{
    USBRedirDevice *dev = priv;
1140
    const char *speed;
1141

1142 1143 1144 1145 1146
    if (qemu_timer_pending(dev->attach_timer) || dev->dev.attached) {
        ERROR("Received device connect while already connected\n");
        return;
    }

1147 1148
    switch (device_connect->speed) {
    case usb_redir_speed_low:
1149
        speed = "low speed";
1150 1151 1152
        dev->dev.speed = USB_SPEED_LOW;
        break;
    case usb_redir_speed_full:
1153
        speed = "full speed";
1154 1155 1156
        dev->dev.speed = USB_SPEED_FULL;
        break;
    case usb_redir_speed_high:
1157
        speed = "high speed";
1158 1159 1160
        dev->dev.speed = USB_SPEED_HIGH;
        break;
    case usb_redir_speed_super:
1161
        speed = "super speed";
1162 1163 1164
        dev->dev.speed = USB_SPEED_SUPER;
        break;
    default:
1165
        speed = "unknown speed";
1166 1167
        dev->dev.speed = USB_SPEED_FULL;
    }
1168 1169 1170 1171 1172

    if (usbredirparser_peer_has_cap(dev->parser,
                                    usb_redir_cap_connect_device_version)) {
        INFO("attaching %s device %04x:%04x version %d.%d class %02x\n",
             speed, device_connect->vendor_id, device_connect->product_id,
1173 1174 1175 1176
             ((device_connect->device_version_bcd & 0xf000) >> 12) * 10 +
             ((device_connect->device_version_bcd & 0x0f00) >>  8),
             ((device_connect->device_version_bcd & 0x00f0) >>  4) * 10 +
             ((device_connect->device_version_bcd & 0x000f) >>  0),
1177 1178 1179 1180 1181 1182 1183
             device_connect->device_class);
    } else {
        INFO("attaching %s device %04x:%04x class %02x\n", speed,
             device_connect->vendor_id, device_connect->product_id,
             device_connect->device_class);
    }

1184
    dev->dev.speedmask = (1 << dev->dev.speed);
1185 1186 1187 1188 1189 1190 1191 1192
    dev->device_info = *device_connect;

    if (usbredir_check_filter(dev)) {
        WARNING("Device %04x:%04x rejected by device filter, not attaching\n",
                device_connect->vendor_id, device_connect->product_id);
        return;
    }

1193 1194 1195 1196 1197 1198
    qemu_mod_timer(dev->attach_timer, dev->next_attach_time);
}

static void usbredir_device_disconnect(void *priv)
{
    USBRedirDevice *dev = priv;
1199
    int i;
1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211

    /* Stop any pending attaches */
    qemu_del_timer(dev->attach_timer);

    if (dev->dev.attached) {
        usb_device_detach(&dev->dev);
        /*
         * Delay next usb device attach to give the guest a chance to see
         * see the detach / attach in case of quick close / open succession
         */
        dev->next_attach_time = qemu_get_clock_ms(vm_clock) + 200;
    }
1212 1213 1214 1215 1216 1217 1218

    /* Reset state so that the next dev connected starts with a clean slate */
    usbredir_cleanup_device_queues(dev);
    memset(dev->endpoint, 0, sizeof(dev->endpoint));
    for (i = 0; i < MAX_ENDPOINTS; i++) {
        QTAILQ_INIT(&dev->endpoint[i].bufpq);
    }
1219
    usb_ep_init(&dev->dev);
1220
    dev->interface_info.interface_count = NO_INTERFACE_INFO;
1221 1222
    dev->dev.addr = 0;
    dev->dev.speed = 0;
1223 1224 1225 1226 1227
}

static void usbredir_interface_info(void *priv,
    struct usb_redir_interface_info_header *interface_info)
{
1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241
    USBRedirDevice *dev = priv;

    dev->interface_info = *interface_info;

    /*
     * If we receive interface info after the device has already been
     * connected (ie on a set_config), re-check the filter.
     */
    if (qemu_timer_pending(dev->attach_timer) || dev->dev.attached) {
        if (usbredir_check_filter(dev)) {
            ERROR("Device no longer matches filter after interface info "
                  "change, disconnecting!\n");
        }
    }
1242 1243 1244 1245 1246 1247
}

static void usbredir_ep_info(void *priv,
    struct usb_redir_ep_info_header *ep_info)
{
    USBRedirDevice *dev = priv;
1248
    struct USBEndpoint *usb_ep;
1249 1250 1251 1252 1253 1254
    int i;

    for (i = 0; i < MAX_ENDPOINTS; i++) {
        dev->endpoint[i].type = ep_info->type[i];
        dev->endpoint[i].interval = ep_info->interval[i];
        dev->endpoint[i].interface = ep_info->interface[i];
1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266
        switch (dev->endpoint[i].type) {
        case usb_redir_type_invalid:
            break;
        case usb_redir_type_iso:
        case usb_redir_type_interrupt:
            if (dev->endpoint[i].interval == 0) {
                ERROR("Received 0 interval for isoc or irq endpoint\n");
                usbredir_device_disconnect(dev);
            }
            /* Fall through */
        case usb_redir_type_control:
        case usb_redir_type_bulk:
1267 1268
            DPRINTF("ep: %02X type: %d interface: %d\n", I2EP(i),
                    dev->endpoint[i].type, dev->endpoint[i].interface);
1269 1270 1271 1272
            break;
        default:
            ERROR("Received invalid endpoint type\n");
            usbredir_device_disconnect(dev);
1273
            return;
1274
        }
1275 1276 1277 1278 1279
        usb_ep = usb_ep_get(&dev->dev,
                            (i & 0x10) ? USB_TOKEN_IN : USB_TOKEN_OUT,
                            i & 0x0f);
        usb_ep->type = dev->endpoint[i].type;
        usb_ep->ifnum = dev->endpoint[i].interface;
1280 1281
        if (usbredirparser_peer_has_cap(dev->parser,
                                     usb_redir_cap_ep_info_max_packet_size)) {
1282 1283
            dev->endpoint[i].max_packet_size =
                usb_ep->max_packet_size = ep_info->max_packet_size[i];
1284
        }
1285 1286 1287
        if (ep_info->type[i] == usb_redir_type_bulk) {
            usb_ep->pipeline = true;
        }
1288 1289 1290
    }
}

1291
static void usbredir_configuration_status(void *priv, uint64_t id,
1292 1293 1294
    struct usb_redir_configuration_status_header *config_status)
{
    USBRedirDevice *dev = priv;
1295
    USBPacket *p;
1296 1297
    int len = 0;

1298 1299
    DPRINTF("set config status %d config %d id %"PRIu64"\n",
            config_status->status, config_status->configuration, id);
1300

1301 1302
    p = usbredir_find_packet_by_id(dev, 0, id);
    if (p) {
1303
        if (dev->dev.setup_buf[0] & USB_DIR_IN) {
1304 1305 1306
            dev->dev.data_buf[0] = config_status->configuration;
            len = 1;
        }
1307 1308
        p->result = usbredir_handle_status(dev, config_status->status, len);
        usb_generic_async_ctrl_complete(&dev->dev, p);
1309 1310 1311
    }
}

1312
static void usbredir_alt_setting_status(void *priv, uint64_t id,
1313 1314 1315
    struct usb_redir_alt_setting_status_header *alt_setting_status)
{
    USBRedirDevice *dev = priv;
1316
    USBPacket *p;
1317 1318
    int len = 0;

1319 1320
    DPRINTF("alt status %d intf %d alt %d id: %"PRIu64"\n",
            alt_setting_status->status, alt_setting_status->interface,
1321 1322
            alt_setting_status->alt, id);

1323 1324
    p = usbredir_find_packet_by_id(dev, 0, id);
    if (p) {
1325
        if (dev->dev.setup_buf[0] & USB_DIR_IN) {
1326 1327 1328
            dev->dev.data_buf[0] = alt_setting_status->alt;
            len = 1;
        }
1329
        p->result =
1330
            usbredir_handle_status(dev, alt_setting_status->status, len);
1331
        usb_generic_async_ctrl_complete(&dev->dev, p);
1332 1333 1334
    }
}

1335
static void usbredir_iso_stream_status(void *priv, uint64_t id,
1336 1337 1338 1339 1340
    struct usb_redir_iso_stream_status_header *iso_stream_status)
{
    USBRedirDevice *dev = priv;
    uint8_t ep = iso_stream_status->endpoint;

1341
    DPRINTF("iso status %d ep %02X id %"PRIu64"\n", iso_stream_status->status,
1342 1343
            ep, id);

1344
    if (!dev->dev.attached || !dev->endpoint[EP2I(ep)].iso_started) {
1345 1346 1347
        return;
    }

1348 1349 1350 1351 1352 1353 1354
    dev->endpoint[EP2I(ep)].iso_error = iso_stream_status->status;
    if (iso_stream_status->status == usb_redir_stall) {
        DPRINTF("iso stream stopped by peer ep %02X\n", ep);
        dev->endpoint[EP2I(ep)].iso_started = 0;
    }
}

1355
static void usbredir_interrupt_receiving_status(void *priv, uint64_t id,
1356 1357 1358 1359 1360 1361
    struct usb_redir_interrupt_receiving_status_header
    *interrupt_receiving_status)
{
    USBRedirDevice *dev = priv;
    uint8_t ep = interrupt_receiving_status->endpoint;

1362
    DPRINTF("interrupt recv status %d ep %02X id %"PRIu64"\n",
1363 1364
            interrupt_receiving_status->status, ep, id);

1365
    if (!dev->dev.attached || !dev->endpoint[EP2I(ep)].interrupt_started) {
1366 1367 1368
        return;
    }

1369 1370 1371 1372 1373 1374 1375 1376
    dev->endpoint[EP2I(ep)].interrupt_error =
        interrupt_receiving_status->status;
    if (interrupt_receiving_status->status == usb_redir_stall) {
        DPRINTF("interrupt receiving stopped by peer ep %02X\n", ep);
        dev->endpoint[EP2I(ep)].interrupt_started = 0;
    }
}

1377
static void usbredir_bulk_streams_status(void *priv, uint64_t id,
1378 1379 1380 1381
    struct usb_redir_bulk_streams_status_header *bulk_streams_status)
{
}

1382
static void usbredir_control_packet(void *priv, uint64_t id,
1383 1384 1385 1386
    struct usb_redir_control_packet_header *control_packet,
    uint8_t *data, int data_len)
{
    USBRedirDevice *dev = priv;
1387
    USBPacket *p;
1388 1389
    int len = control_packet->length;

1390
    DPRINTF("ctrl-in status %d len %d id %"PRIu64"\n", control_packet->status,
1391 1392
            len, id);

1393 1394
    p = usbredir_find_packet_by_id(dev, 0, id);
    if (p) {
1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405
        len = usbredir_handle_status(dev, control_packet->status, len);
        if (len > 0) {
            usbredir_log_data(dev, "ctrl data in:", data, data_len);
            if (data_len <= sizeof(dev->dev.data_buf)) {
                memcpy(dev->dev.data_buf, data, data_len);
            } else {
                ERROR("ctrl buffer too small (%d > %zu)\n",
                      data_len, sizeof(dev->dev.data_buf));
                len = USB_RET_STALL;
            }
        }
1406 1407
        p->result = len;
        usb_generic_async_ctrl_complete(&dev->dev, p);
1408 1409 1410 1411
    }
    free(data);
}

1412
static void usbredir_bulk_packet(void *priv, uint64_t id,
1413 1414 1415 1416 1417 1418
    struct usb_redir_bulk_packet_header *bulk_packet,
    uint8_t *data, int data_len)
{
    USBRedirDevice *dev = priv;
    uint8_t ep = bulk_packet->endpoint;
    int len = bulk_packet->length;
1419
    USBPacket *p;
1420

1421 1422
    DPRINTF("bulk-in status %d ep %02X len %d id %"PRIu64"\n",
            bulk_packet->status, ep, len, id);
1423

1424 1425
    p = usbredir_find_packet_by_id(dev, ep, id);
    if (p) {
1426 1427 1428
        len = usbredir_handle_status(dev, bulk_packet->status, len);
        if (len > 0) {
            usbredir_log_data(dev, "bulk data in:", data, data_len);
1429 1430
            if (data_len <= p->iov.size) {
                usb_packet_copy(p, data, data_len);
1431
            } else {
1432 1433 1434
                ERROR("bulk got more data then requested (%d > %zd)\n",
                      data_len, p->iov.size);
                len = USB_RET_BABBLE;
1435 1436
            }
        }
1437 1438
        p->result = len;
        usb_packet_complete(&dev->dev, p);
1439 1440 1441 1442
    }
    free(data);
}

1443
static void usbredir_iso_packet(void *priv, uint64_t id,
1444 1445 1446 1447 1448 1449
    struct usb_redir_iso_packet_header *iso_packet,
    uint8_t *data, int data_len)
{
    USBRedirDevice *dev = priv;
    uint8_t ep = iso_packet->endpoint;

1450 1451
    DPRINTF2("iso-in status %d ep %02X len %d id %"PRIu64"\n",
             iso_packet->status, ep, data_len, id);
1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468

    if (dev->endpoint[EP2I(ep)].type != USB_ENDPOINT_XFER_ISOC) {
        ERROR("received iso packet for non iso endpoint %02X\n", ep);
        free(data);
        return;
    }

    if (dev->endpoint[EP2I(ep)].iso_started == 0) {
        DPRINTF("received iso packet for non started stream ep %02X\n", ep);
        free(data);
        return;
    }

    /* bufp_alloc also adds the packet to the ep queue */
    bufp_alloc(dev, data, data_len, iso_packet->status, ep);
}

1469
static void usbredir_interrupt_packet(void *priv, uint64_t id,
1470 1471 1472 1473 1474 1475
    struct usb_redir_interrupt_packet_header *interrupt_packet,
    uint8_t *data, int data_len)
{
    USBRedirDevice *dev = priv;
    uint8_t ep = interrupt_packet->endpoint;

1476
    DPRINTF("interrupt-in status %d ep %02X len %d id %"PRIu64"\n",
1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496
            interrupt_packet->status, ep, data_len, id);

    if (dev->endpoint[EP2I(ep)].type != USB_ENDPOINT_XFER_INT) {
        ERROR("received int packet for non interrupt endpoint %02X\n", ep);
        free(data);
        return;
    }

    if (ep & USB_DIR_IN) {
        if (dev->endpoint[EP2I(ep)].interrupt_started == 0) {
            DPRINTF("received int packet while not started ep %02X\n", ep);
            free(data);
            return;
        }

        /* bufp_alloc also adds the packet to the ep queue */
        bufp_alloc(dev, data, data_len, interrupt_packet->status, ep);
    } else {
        int len = interrupt_packet->length;

1497 1498 1499
        USBPacket *p = usbredir_find_packet_by_id(dev, ep, id);
        if (p) {
            p->result = usbredir_handle_status(dev,
1500
                                               interrupt_packet->status, len);
1501
            usb_packet_complete(&dev->dev, p);
1502 1503 1504 1505
        }
    }
}

A
Anthony Liguori 已提交
1506 1507 1508
static Property usbredir_properties[] = {
    DEFINE_PROP_CHR("chardev", USBRedirDevice, cs),
    DEFINE_PROP_UINT8("debug", USBRedirDevice, debug, 0),
1509
    DEFINE_PROP_STRING("filter", USBRedirDevice, filter_str),
1510
    DEFINE_PROP_INT32("bootindex", USBRedirDevice, bootindex, -1),
A
Anthony Liguori 已提交
1511 1512 1513
    DEFINE_PROP_END_OF_LIST(),
};

1514 1515 1516
static void usbredir_class_initfn(ObjectClass *klass, void *data)
{
    USBDeviceClass *uc = USB_DEVICE_CLASS(klass);
A
Anthony Liguori 已提交
1517
    DeviceClass *dc = DEVICE_CLASS(klass);
1518 1519 1520 1521 1522 1523 1524 1525

    uc->init           = usbredir_initfn;
    uc->product_desc   = "USB Redirection Device";
    uc->handle_destroy = usbredir_handle_destroy;
    uc->cancel_packet  = usbredir_cancel_packet;
    uc->handle_reset   = usbredir_handle_reset;
    uc->handle_data    = usbredir_handle_data;
    uc->handle_control = usbredir_handle_control;
A
Anthony Liguori 已提交
1526
    dc->props          = usbredir_properties;
1527 1528
}

A
Anthony Liguori 已提交
1529 1530 1531 1532 1533
static TypeInfo usbredir_dev_info = {
    .name          = "usb-redir",
    .parent        = TYPE_USB_DEVICE,
    .instance_size = sizeof(USBRedirDevice),
    .class_init    = usbredir_class_initfn,
1534 1535
};

A
Andreas Färber 已提交
1536
static void usbredir_register_types(void)
1537
{
A
Anthony Liguori 已提交
1538
    type_register_static(&usbredir_dev_info);
1539
}
A
Andreas Färber 已提交
1540 1541

type_init(usbredir_register_types)