usb-redir: allocate buffers before waking up the host adapter
[qemu.git] / hw / usb / redirect.c
blobd4ca026f00a99f49fd1e208c8baa7f3053c3014c
1 /*
2 * USB redirector usb-guest
4 * Copyright (c) 2011-2012 Red Hat, Inc.
6 * Red Hat Authors:
7 * Hans de Goede <hdegoede@redhat.com>
9 * Permission is hereby granted, free of charge, to any person obtaining a copy
10 * of this software and associated documentation files (the "Software"), to deal
11 * in the Software without restriction, including without limitation the rights
12 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
13 * copies of the Software, and to permit persons to whom the Software is
14 * furnished to do so, subject to the following conditions:
16 * The above copyright notice and this permission notice shall be included in
17 * all copies or substantial portions of the Software.
19 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
20 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
21 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
22 * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
23 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
24 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
25 * THE SOFTWARE.
28 #include "qemu/osdep.h"
29 #include "qapi/error.h"
30 #include "qemu-common.h"
31 #include "qemu/timer.h"
32 #include "sysemu/sysemu.h"
33 #include "qapi/qmp/qerror.h"
34 #include "qemu/error-report.h"
35 #include "qemu/iov.h"
36 #include "sysemu/char.h"
38 #include <usbredirparser.h>
39 #include <usbredirfilter.h>
41 #include "hw/usb.h"
43 /* ERROR is defined below. Remove any previous definition. */
44 #undef ERROR
46 #define MAX_ENDPOINTS 32
47 #define NO_INTERFACE_INFO 255 /* Valid interface_count always <= 32 */
48 #define EP2I(ep_address) (((ep_address & 0x80) >> 3) | (ep_address & 0x0f))
49 #define I2EP(i) (((i & 0x10) << 3) | (i & 0x0f))
50 #define USBEP2I(usb_ep) (((usb_ep)->pid == USB_TOKEN_IN) ? \
51 ((usb_ep)->nr | 0x10) : ((usb_ep)->nr))
52 #define I2USBEP(d, i) (usb_ep_get(&(d)->dev, \
53 ((i) & 0x10) ? USB_TOKEN_IN : USB_TOKEN_OUT, \
54 (i) & 0x0f))
56 #ifndef USBREDIR_VERSION /* This is not defined in older usbredir versions */
57 #define USBREDIR_VERSION 0
58 #endif
60 typedef struct USBRedirDevice USBRedirDevice;
62 /* Struct to hold buffered packets */
63 struct buf_packet {
64 uint8_t *data;
65 void *free_on_destroy;
66 uint16_t len;
67 uint16_t offset;
68 uint8_t status;
69 QTAILQ_ENTRY(buf_packet)next;
72 struct endp_data {
73 USBRedirDevice *dev;
74 uint8_t type;
75 uint8_t interval;
76 uint8_t interface; /* bInterfaceNumber this ep belongs to */
77 uint16_t max_packet_size; /* In bytes, not wMaxPacketSize format !! */
78 uint32_t max_streams;
79 uint8_t iso_started;
80 uint8_t iso_error; /* For reporting iso errors to the HC */
81 uint8_t interrupt_started;
82 uint8_t interrupt_error;
83 uint8_t bulk_receiving_enabled;
84 uint8_t bulk_receiving_started;
85 uint8_t bufpq_prefilled;
86 uint8_t bufpq_dropping_packets;
87 QTAILQ_HEAD(, buf_packet) bufpq;
88 int32_t bufpq_size;
89 int32_t bufpq_target_size;
90 USBPacket *pending_async_packet;
93 struct PacketIdQueueEntry {
94 uint64_t id;
95 QTAILQ_ENTRY(PacketIdQueueEntry)next;
98 struct PacketIdQueue {
99 USBRedirDevice *dev;
100 const char *name;
101 QTAILQ_HEAD(, PacketIdQueueEntry) head;
102 int size;
105 struct USBRedirDevice {
106 USBDevice dev;
107 /* Properties */
108 CharDriverState *cs;
109 uint8_t debug;
110 char *filter_str;
111 int32_t bootindex;
112 bool enable_streams;
113 /* Data passed from chardev the fd_read cb to the usbredirparser read cb */
114 const uint8_t *read_buf;
115 int read_buf_size;
116 /* Active chardev-watch-tag */
117 guint watch;
118 /* For async handling of close / reject */
119 QEMUBH *chardev_close_bh;
120 QEMUBH *device_reject_bh;
121 /* To delay the usb attach in case of quick chardev close + open */
122 QEMUTimer *attach_timer;
123 int64_t next_attach_time;
124 struct usbredirparser *parser;
125 struct endp_data endpoint[MAX_ENDPOINTS];
126 struct PacketIdQueue cancelled;
127 struct PacketIdQueue already_in_flight;
128 void (*buffered_bulk_in_complete)(USBRedirDevice *, USBPacket *, uint8_t);
129 /* Data for device filtering */
130 struct usb_redir_device_connect_header device_info;
131 struct usb_redir_interface_info_header interface_info;
132 struct usbredirfilter_rule *filter_rules;
133 int filter_rules_count;
134 int compatible_speedmask;
137 #define TYPE_USB_REDIR "usb-redir"
138 #define USB_REDIRECT(obj) OBJECT_CHECK(USBRedirDevice, (obj), TYPE_USB_REDIR)
140 static void usbredir_hello(void *priv, struct usb_redir_hello_header *h);
141 static void usbredir_device_connect(void *priv,
142 struct usb_redir_device_connect_header *device_connect);
143 static void usbredir_device_disconnect(void *priv);
144 static void usbredir_interface_info(void *priv,
145 struct usb_redir_interface_info_header *interface_info);
146 static void usbredir_ep_info(void *priv,
147 struct usb_redir_ep_info_header *ep_info);
148 static void usbredir_configuration_status(void *priv, uint64_t id,
149 struct usb_redir_configuration_status_header *configuration_status);
150 static void usbredir_alt_setting_status(void *priv, uint64_t id,
151 struct usb_redir_alt_setting_status_header *alt_setting_status);
152 static void usbredir_iso_stream_status(void *priv, uint64_t id,
153 struct usb_redir_iso_stream_status_header *iso_stream_status);
154 static void usbredir_interrupt_receiving_status(void *priv, uint64_t id,
155 struct usb_redir_interrupt_receiving_status_header
156 *interrupt_receiving_status);
157 static void usbredir_bulk_streams_status(void *priv, uint64_t id,
158 struct usb_redir_bulk_streams_status_header *bulk_streams_status);
159 static void usbredir_bulk_receiving_status(void *priv, uint64_t id,
160 struct usb_redir_bulk_receiving_status_header *bulk_receiving_status);
161 static void usbredir_control_packet(void *priv, uint64_t id,
162 struct usb_redir_control_packet_header *control_packet,
163 uint8_t *data, int data_len);
164 static void usbredir_bulk_packet(void *priv, uint64_t id,
165 struct usb_redir_bulk_packet_header *bulk_packet,
166 uint8_t *data, int data_len);
167 static void usbredir_iso_packet(void *priv, uint64_t id,
168 struct usb_redir_iso_packet_header *iso_packet,
169 uint8_t *data, int data_len);
170 static void usbredir_interrupt_packet(void *priv, uint64_t id,
171 struct usb_redir_interrupt_packet_header *interrupt_header,
172 uint8_t *data, int data_len);
173 static void usbredir_buffered_bulk_packet(void *priv, uint64_t id,
174 struct usb_redir_buffered_bulk_packet_header *buffered_bulk_packet,
175 uint8_t *data, int data_len);
177 static void usbredir_handle_status(USBRedirDevice *dev, USBPacket *p,
178 int status);
180 #define VERSION "qemu usb-redir guest " QEMU_VERSION
183 * Logging stuff
186 #define ERROR(...) \
187 do { \
188 if (dev->debug >= usbredirparser_error) { \
189 error_report("usb-redir error: " __VA_ARGS__); \
191 } while (0)
192 #define WARNING(...) \
193 do { \
194 if (dev->debug >= usbredirparser_warning) { \
195 error_report("usb-redir warning: " __VA_ARGS__); \
197 } while (0)
198 #define INFO(...) \
199 do { \
200 if (dev->debug >= usbredirparser_info) { \
201 error_report("usb-redir: " __VA_ARGS__); \
203 } while (0)
204 #define DPRINTF(...) \
205 do { \
206 if (dev->debug >= usbredirparser_debug) { \
207 error_report("usb-redir: " __VA_ARGS__); \
209 } while (0)
210 #define DPRINTF2(...) \
211 do { \
212 if (dev->debug >= usbredirparser_debug_data) { \
213 error_report("usb-redir: " __VA_ARGS__); \
215 } while (0)
217 static void usbredir_log(void *priv, int level, const char *msg)
219 USBRedirDevice *dev = priv;
221 if (dev->debug < level) {
222 return;
225 error_report("%s", msg);
228 static void usbredir_log_data(USBRedirDevice *dev, const char *desc,
229 const uint8_t *data, int len)
231 int i, j, n;
233 if (dev->debug < usbredirparser_debug_data) {
234 return;
237 for (i = 0; i < len; i += j) {
238 char buf[128];
240 n = sprintf(buf, "%s", desc);
241 for (j = 0; j < 8 && i + j < len; j++) {
242 n += sprintf(buf + n, " %02X", data[i + j]);
244 error_report("%s", buf);
249 * usbredirparser io functions
252 static int usbredir_read(void *priv, uint8_t *data, int count)
254 USBRedirDevice *dev = priv;
256 if (dev->read_buf_size < count) {
257 count = dev->read_buf_size;
260 memcpy(data, dev->read_buf, count);
262 dev->read_buf_size -= count;
263 if (dev->read_buf_size) {
264 dev->read_buf += count;
265 } else {
266 dev->read_buf = NULL;
269 return count;
272 static gboolean usbredir_write_unblocked(GIOChannel *chan, GIOCondition cond,
273 void *opaque)
275 USBRedirDevice *dev = opaque;
277 dev->watch = 0;
278 usbredirparser_do_write(dev->parser);
280 return FALSE;
283 static int usbredir_write(void *priv, uint8_t *data, int count)
285 USBRedirDevice *dev = priv;
286 int r;
288 if (!dev->cs->be_open) {
289 return 0;
292 /* Don't send new data to the chardev until our state is fully synced */
293 if (!runstate_check(RUN_STATE_RUNNING)) {
294 return 0;
297 r = qemu_chr_fe_write(dev->cs, data, count);
298 if (r < count) {
299 if (!dev->watch) {
300 dev->watch = qemu_chr_fe_add_watch(dev->cs, G_IO_OUT|G_IO_HUP,
301 usbredir_write_unblocked, dev);
303 if (r < 0) {
304 r = 0;
307 return r;
311 * Cancelled and buffered packets helpers
314 static void packet_id_queue_init(struct PacketIdQueue *q,
315 USBRedirDevice *dev, const char *name)
317 q->dev = dev;
318 q->name = name;
319 QTAILQ_INIT(&q->head);
320 q->size = 0;
323 static void packet_id_queue_add(struct PacketIdQueue *q, uint64_t id)
325 USBRedirDevice *dev = q->dev;
326 struct PacketIdQueueEntry *e;
328 DPRINTF("adding packet id %"PRIu64" to %s queue\n", id, q->name);
330 e = g_new0(struct PacketIdQueueEntry, 1);
331 e->id = id;
332 QTAILQ_INSERT_TAIL(&q->head, e, next);
333 q->size++;
336 static int packet_id_queue_remove(struct PacketIdQueue *q, uint64_t id)
338 USBRedirDevice *dev = q->dev;
339 struct PacketIdQueueEntry *e;
341 QTAILQ_FOREACH(e, &q->head, next) {
342 if (e->id == id) {
343 DPRINTF("removing packet id %"PRIu64" from %s queue\n",
344 id, q->name);
345 QTAILQ_REMOVE(&q->head, e, next);
346 q->size--;
347 g_free(e);
348 return 1;
351 return 0;
354 static void packet_id_queue_empty(struct PacketIdQueue *q)
356 USBRedirDevice *dev = q->dev;
357 struct PacketIdQueueEntry *e, *next_e;
359 DPRINTF("removing %d packet-ids from %s queue\n", q->size, q->name);
361 QTAILQ_FOREACH_SAFE(e, &q->head, next, next_e) {
362 QTAILQ_REMOVE(&q->head, e, next);
363 g_free(e);
365 q->size = 0;
368 static void usbredir_cancel_packet(USBDevice *udev, USBPacket *p)
370 USBRedirDevice *dev = USB_REDIRECT(udev);
371 int i = USBEP2I(p->ep);
373 if (p->combined) {
374 usb_combined_packet_cancel(udev, p);
375 return;
378 if (dev->endpoint[i].pending_async_packet) {
379 assert(dev->endpoint[i].pending_async_packet == p);
380 dev->endpoint[i].pending_async_packet = NULL;
381 return;
384 packet_id_queue_add(&dev->cancelled, p->id);
385 usbredirparser_send_cancel_data_packet(dev->parser, p->id);
386 usbredirparser_do_write(dev->parser);
389 static int usbredir_is_cancelled(USBRedirDevice *dev, uint64_t id)
391 if (!dev->dev.attached) {
392 return 1; /* Treat everything as cancelled after a disconnect */
394 return packet_id_queue_remove(&dev->cancelled, id);
397 static void usbredir_fill_already_in_flight_from_ep(USBRedirDevice *dev,
398 struct USBEndpoint *ep)
400 static USBPacket *p;
402 /* async handled packets for bulk receiving eps do not count as inflight */
403 if (dev->endpoint[USBEP2I(ep)].bulk_receiving_started) {
404 return;
407 QTAILQ_FOREACH(p, &ep->queue, queue) {
408 /* Skip combined packets, except for the first */
409 if (p->combined && p != p->combined->first) {
410 continue;
412 if (p->state == USB_PACKET_ASYNC) {
413 packet_id_queue_add(&dev->already_in_flight, p->id);
418 static void usbredir_fill_already_in_flight(USBRedirDevice *dev)
420 int ep;
421 struct USBDevice *udev = &dev->dev;
423 usbredir_fill_already_in_flight_from_ep(dev, &udev->ep_ctl);
425 for (ep = 0; ep < USB_MAX_ENDPOINTS; ep++) {
426 usbredir_fill_already_in_flight_from_ep(dev, &udev->ep_in[ep]);
427 usbredir_fill_already_in_flight_from_ep(dev, &udev->ep_out[ep]);
431 static int usbredir_already_in_flight(USBRedirDevice *dev, uint64_t id)
433 return packet_id_queue_remove(&dev->already_in_flight, id);
436 static USBPacket *usbredir_find_packet_by_id(USBRedirDevice *dev,
437 uint8_t ep, uint64_t id)
439 USBPacket *p;
441 if (usbredir_is_cancelled(dev, id)) {
442 return NULL;
445 p = usb_ep_find_packet_by_id(&dev->dev,
446 (ep & USB_DIR_IN) ? USB_TOKEN_IN : USB_TOKEN_OUT,
447 ep & 0x0f, id);
448 if (p == NULL) {
449 ERROR("could not find packet with id %"PRIu64"\n", id);
451 return p;
454 static int bufp_alloc(USBRedirDevice *dev, uint8_t *data, uint16_t len,
455 uint8_t status, uint8_t ep, void *free_on_destroy)
457 struct buf_packet *bufp;
459 if (!dev->endpoint[EP2I(ep)].bufpq_dropping_packets &&
460 dev->endpoint[EP2I(ep)].bufpq_size >
461 2 * dev->endpoint[EP2I(ep)].bufpq_target_size) {
462 DPRINTF("bufpq overflow, dropping packets ep %02X\n", ep);
463 dev->endpoint[EP2I(ep)].bufpq_dropping_packets = 1;
465 /* Since we're interupting the stream anyways, drop enough packets to get
466 back to our target buffer size */
467 if (dev->endpoint[EP2I(ep)].bufpq_dropping_packets) {
468 if (dev->endpoint[EP2I(ep)].bufpq_size >
469 dev->endpoint[EP2I(ep)].bufpq_target_size) {
470 free(data);
471 return -1;
473 dev->endpoint[EP2I(ep)].bufpq_dropping_packets = 0;
476 bufp = g_new(struct buf_packet, 1);
477 bufp->data = data;
478 bufp->len = len;
479 bufp->offset = 0;
480 bufp->status = status;
481 bufp->free_on_destroy = free_on_destroy;
482 QTAILQ_INSERT_TAIL(&dev->endpoint[EP2I(ep)].bufpq, bufp, next);
483 dev->endpoint[EP2I(ep)].bufpq_size++;
484 return 0;
487 static void bufp_free(USBRedirDevice *dev, struct buf_packet *bufp,
488 uint8_t ep)
490 QTAILQ_REMOVE(&dev->endpoint[EP2I(ep)].bufpq, bufp, next);
491 dev->endpoint[EP2I(ep)].bufpq_size--;
492 free(bufp->free_on_destroy);
493 g_free(bufp);
496 static void usbredir_free_bufpq(USBRedirDevice *dev, uint8_t ep)
498 struct buf_packet *buf, *buf_next;
500 QTAILQ_FOREACH_SAFE(buf, &dev->endpoint[EP2I(ep)].bufpq, next, buf_next) {
501 bufp_free(dev, buf, ep);
506 * USBDevice callbacks
509 static void usbredir_handle_reset(USBDevice *udev)
511 USBRedirDevice *dev = USB_REDIRECT(udev);
513 DPRINTF("reset device\n");
514 usbredirparser_send_reset(dev->parser);
515 usbredirparser_do_write(dev->parser);
518 static void usbredir_handle_iso_data(USBRedirDevice *dev, USBPacket *p,
519 uint8_t ep)
521 int status, len;
522 if (!dev->endpoint[EP2I(ep)].iso_started &&
523 !dev->endpoint[EP2I(ep)].iso_error) {
524 struct usb_redir_start_iso_stream_header start_iso = {
525 .endpoint = ep,
527 int pkts_per_sec;
529 if (dev->dev.speed == USB_SPEED_HIGH) {
530 pkts_per_sec = 8000 / dev->endpoint[EP2I(ep)].interval;
531 } else {
532 pkts_per_sec = 1000 / dev->endpoint[EP2I(ep)].interval;
534 /* Testing has shown that we need circa 60 ms buffer */
535 dev->endpoint[EP2I(ep)].bufpq_target_size = (pkts_per_sec * 60) / 1000;
537 /* Aim for approx 100 interrupts / second on the client to
538 balance latency and interrupt load */
539 start_iso.pkts_per_urb = pkts_per_sec / 100;
540 if (start_iso.pkts_per_urb < 1) {
541 start_iso.pkts_per_urb = 1;
542 } else if (start_iso.pkts_per_urb > 32) {
543 start_iso.pkts_per_urb = 32;
546 start_iso.no_urbs = DIV_ROUND_UP(
547 dev->endpoint[EP2I(ep)].bufpq_target_size,
548 start_iso.pkts_per_urb);
549 /* Output endpoints pre-fill only 1/2 of the packets, keeping the rest
550 as overflow buffer. Also see the usbredir protocol documentation */
551 if (!(ep & USB_DIR_IN)) {
552 start_iso.no_urbs *= 2;
554 if (start_iso.no_urbs > 16) {
555 start_iso.no_urbs = 16;
558 /* No id, we look at the ep when receiving a status back */
559 usbredirparser_send_start_iso_stream(dev->parser, 0, &start_iso);
560 usbredirparser_do_write(dev->parser);
561 DPRINTF("iso stream started pkts/sec %d pkts/urb %d urbs %d ep %02X\n",
562 pkts_per_sec, start_iso.pkts_per_urb, start_iso.no_urbs, ep);
563 dev->endpoint[EP2I(ep)].iso_started = 1;
564 dev->endpoint[EP2I(ep)].bufpq_prefilled = 0;
565 dev->endpoint[EP2I(ep)].bufpq_dropping_packets = 0;
568 if (ep & USB_DIR_IN) {
569 struct buf_packet *isop;
571 if (dev->endpoint[EP2I(ep)].iso_started &&
572 !dev->endpoint[EP2I(ep)].bufpq_prefilled) {
573 if (dev->endpoint[EP2I(ep)].bufpq_size <
574 dev->endpoint[EP2I(ep)].bufpq_target_size) {
575 return;
577 dev->endpoint[EP2I(ep)].bufpq_prefilled = 1;
580 isop = QTAILQ_FIRST(&dev->endpoint[EP2I(ep)].bufpq);
581 if (isop == NULL) {
582 DPRINTF("iso-token-in ep %02X, no isop, iso_error: %d\n",
583 ep, dev->endpoint[EP2I(ep)].iso_error);
584 /* Re-fill the buffer */
585 dev->endpoint[EP2I(ep)].bufpq_prefilled = 0;
586 /* Check iso_error for stream errors, otherwise its an underrun */
587 status = dev->endpoint[EP2I(ep)].iso_error;
588 dev->endpoint[EP2I(ep)].iso_error = 0;
589 p->status = status ? USB_RET_IOERROR : USB_RET_SUCCESS;
590 return;
592 DPRINTF2("iso-token-in ep %02X status %d len %d queue-size: %d\n", ep,
593 isop->status, isop->len, dev->endpoint[EP2I(ep)].bufpq_size);
595 status = isop->status;
596 len = isop->len;
597 if (len > p->iov.size) {
598 ERROR("received iso data is larger then packet ep %02X (%d > %d)\n",
599 ep, len, (int)p->iov.size);
600 len = p->iov.size;
601 status = usb_redir_babble;
603 usb_packet_copy(p, isop->data, len);
604 bufp_free(dev, isop, ep);
605 usbredir_handle_status(dev, p, status);
606 } else {
607 /* If the stream was not started because of a pending error don't
608 send the packet to the usb-host */
609 if (dev->endpoint[EP2I(ep)].iso_started) {
610 struct usb_redir_iso_packet_header iso_packet = {
611 .endpoint = ep,
612 .length = p->iov.size
614 uint8_t buf[p->iov.size];
615 /* No id, we look at the ep when receiving a status back */
616 usb_packet_copy(p, buf, p->iov.size);
617 usbredirparser_send_iso_packet(dev->parser, 0, &iso_packet,
618 buf, p->iov.size);
619 usbredirparser_do_write(dev->parser);
621 status = dev->endpoint[EP2I(ep)].iso_error;
622 dev->endpoint[EP2I(ep)].iso_error = 0;
623 DPRINTF2("iso-token-out ep %02X status %d len %zd\n", ep, status,
624 p->iov.size);
625 usbredir_handle_status(dev, p, status);
629 static void usbredir_stop_iso_stream(USBRedirDevice *dev, uint8_t ep)
631 struct usb_redir_stop_iso_stream_header stop_iso_stream = {
632 .endpoint = ep
634 if (dev->endpoint[EP2I(ep)].iso_started) {
635 usbredirparser_send_stop_iso_stream(dev->parser, 0, &stop_iso_stream);
636 DPRINTF("iso stream stopped ep %02X\n", ep);
637 dev->endpoint[EP2I(ep)].iso_started = 0;
639 dev->endpoint[EP2I(ep)].iso_error = 0;
640 usbredir_free_bufpq(dev, ep);
644 * The usb-host may poll the endpoint faster then our guest, resulting in lots
645 * of smaller bulkp-s. The below buffered_bulk_in_complete* functions combine
646 * data from multiple bulkp-s into a single packet, avoiding bufpq overflows.
648 static void usbredir_buffered_bulk_add_data_to_packet(USBRedirDevice *dev,
649 struct buf_packet *bulkp, int count, USBPacket *p, uint8_t ep)
651 usb_packet_copy(p, bulkp->data + bulkp->offset, count);
652 bulkp->offset += count;
653 if (bulkp->offset == bulkp->len) {
654 /* Store status in the last packet with data from this bulkp */
655 usbredir_handle_status(dev, p, bulkp->status);
656 bufp_free(dev, bulkp, ep);
660 static void usbredir_buffered_bulk_in_complete_raw(USBRedirDevice *dev,
661 USBPacket *p, uint8_t ep)
663 struct buf_packet *bulkp;
664 int count;
666 while ((bulkp = QTAILQ_FIRST(&dev->endpoint[EP2I(ep)].bufpq)) &&
667 p->actual_length < p->iov.size && p->status == USB_RET_SUCCESS) {
668 count = bulkp->len - bulkp->offset;
669 if (count > (p->iov.size - p->actual_length)) {
670 count = p->iov.size - p->actual_length;
672 usbredir_buffered_bulk_add_data_to_packet(dev, bulkp, count, p, ep);
676 static void usbredir_buffered_bulk_in_complete_ftdi(USBRedirDevice *dev,
677 USBPacket *p, uint8_t ep)
679 const int maxp = dev->endpoint[EP2I(ep)].max_packet_size;
680 uint8_t header[2] = { 0, 0 };
681 struct buf_packet *bulkp;
682 int count;
684 while ((bulkp = QTAILQ_FIRST(&dev->endpoint[EP2I(ep)].bufpq)) &&
685 p->actual_length < p->iov.size && p->status == USB_RET_SUCCESS) {
686 if (bulkp->len < 2) {
687 WARNING("malformed ftdi bulk in packet\n");
688 bufp_free(dev, bulkp, ep);
689 continue;
692 if ((p->actual_length % maxp) == 0) {
693 usb_packet_copy(p, bulkp->data, 2);
694 memcpy(header, bulkp->data, 2);
695 } else {
696 if (bulkp->data[0] != header[0] || bulkp->data[1] != header[1]) {
697 break; /* Different header, add to next packet */
701 if (bulkp->offset == 0) {
702 bulkp->offset = 2; /* Skip header */
704 count = bulkp->len - bulkp->offset;
705 /* Must repeat the header at maxp interval */
706 if (count > (maxp - (p->actual_length % maxp))) {
707 count = maxp - (p->actual_length % maxp);
709 usbredir_buffered_bulk_add_data_to_packet(dev, bulkp, count, p, ep);
713 static void usbredir_buffered_bulk_in_complete(USBRedirDevice *dev,
714 USBPacket *p, uint8_t ep)
716 p->status = USB_RET_SUCCESS; /* Clear previous ASYNC status */
717 dev->buffered_bulk_in_complete(dev, p, ep);
718 DPRINTF("bulk-token-in ep %02X status %d len %d id %"PRIu64"\n",
719 ep, p->status, p->actual_length, p->id);
722 static void usbredir_handle_buffered_bulk_in_data(USBRedirDevice *dev,
723 USBPacket *p, uint8_t ep)
725 /* Input bulk endpoint, buffered packet input */
726 if (!dev->endpoint[EP2I(ep)].bulk_receiving_started) {
727 int bpt;
728 struct usb_redir_start_bulk_receiving_header start = {
729 .endpoint = ep,
730 .stream_id = 0,
731 .no_transfers = 5,
733 /* Round bytes_per_transfer up to a multiple of max_packet_size */
734 bpt = 512 + dev->endpoint[EP2I(ep)].max_packet_size - 1;
735 bpt /= dev->endpoint[EP2I(ep)].max_packet_size;
736 bpt *= dev->endpoint[EP2I(ep)].max_packet_size;
737 start.bytes_per_transfer = bpt;
738 /* No id, we look at the ep when receiving a status back */
739 usbredirparser_send_start_bulk_receiving(dev->parser, 0, &start);
740 usbredirparser_do_write(dev->parser);
741 DPRINTF("bulk receiving started bytes/transfer %u count %d ep %02X\n",
742 start.bytes_per_transfer, start.no_transfers, ep);
743 dev->endpoint[EP2I(ep)].bulk_receiving_started = 1;
744 /* We don't really want to drop bulk packets ever, but
745 having some upper limit to how much we buffer is good. */
746 dev->endpoint[EP2I(ep)].bufpq_target_size = 5000;
747 dev->endpoint[EP2I(ep)].bufpq_dropping_packets = 0;
750 if (QTAILQ_EMPTY(&dev->endpoint[EP2I(ep)].bufpq)) {
751 DPRINTF("bulk-token-in ep %02X, no bulkp\n", ep);
752 assert(dev->endpoint[EP2I(ep)].pending_async_packet == NULL);
753 dev->endpoint[EP2I(ep)].pending_async_packet = p;
754 p->status = USB_RET_ASYNC;
755 return;
757 usbredir_buffered_bulk_in_complete(dev, p, ep);
760 static void usbredir_stop_bulk_receiving(USBRedirDevice *dev, uint8_t ep)
762 struct usb_redir_stop_bulk_receiving_header stop_bulk = {
763 .endpoint = ep,
764 .stream_id = 0,
766 if (dev->endpoint[EP2I(ep)].bulk_receiving_started) {
767 usbredirparser_send_stop_bulk_receiving(dev->parser, 0, &stop_bulk);
768 DPRINTF("bulk receiving stopped ep %02X\n", ep);
769 dev->endpoint[EP2I(ep)].bulk_receiving_started = 0;
771 usbredir_free_bufpq(dev, ep);
774 static void usbredir_handle_bulk_data(USBRedirDevice *dev, USBPacket *p,
775 uint8_t ep)
777 struct usb_redir_bulk_packet_header bulk_packet;
778 size_t size = usb_packet_size(p);
779 const int maxp = dev->endpoint[EP2I(ep)].max_packet_size;
781 if (usbredir_already_in_flight(dev, p->id)) {
782 p->status = USB_RET_ASYNC;
783 return;
786 if (dev->endpoint[EP2I(ep)].bulk_receiving_enabled) {
787 if (size != 0 && (size % maxp) == 0) {
788 usbredir_handle_buffered_bulk_in_data(dev, p, ep);
789 return;
791 WARNING("bulk recv invalid size %zd ep %02x, disabling\n", size, ep);
792 assert(dev->endpoint[EP2I(ep)].pending_async_packet == NULL);
793 usbredir_stop_bulk_receiving(dev, ep);
794 dev->endpoint[EP2I(ep)].bulk_receiving_enabled = 0;
797 DPRINTF("bulk-out ep %02X stream %u len %zd id %"PRIu64"\n",
798 ep, p->stream, size, p->id);
800 bulk_packet.endpoint = ep;
801 bulk_packet.length = size;
802 bulk_packet.stream_id = p->stream;
803 bulk_packet.length_high = size >> 16;
804 assert(bulk_packet.length_high == 0 ||
805 usbredirparser_peer_has_cap(dev->parser,
806 usb_redir_cap_32bits_bulk_length));
808 if (ep & USB_DIR_IN) {
809 usbredirparser_send_bulk_packet(dev->parser, p->id,
810 &bulk_packet, NULL, 0);
811 } else {
812 uint8_t buf[size];
813 usb_packet_copy(p, buf, size);
814 usbredir_log_data(dev, "bulk data out:", buf, size);
815 usbredirparser_send_bulk_packet(dev->parser, p->id,
816 &bulk_packet, buf, size);
818 usbredirparser_do_write(dev->parser);
819 p->status = USB_RET_ASYNC;
822 static void usbredir_handle_interrupt_in_data(USBRedirDevice *dev,
823 USBPacket *p, uint8_t ep)
825 /* Input interrupt endpoint, buffered packet input */
826 struct buf_packet *intp;
827 int status, len;
829 if (!dev->endpoint[EP2I(ep)].interrupt_started &&
830 !dev->endpoint[EP2I(ep)].interrupt_error) {
831 struct usb_redir_start_interrupt_receiving_header start_int = {
832 .endpoint = ep,
834 /* No id, we look at the ep when receiving a status back */
835 usbredirparser_send_start_interrupt_receiving(dev->parser, 0,
836 &start_int);
837 usbredirparser_do_write(dev->parser);
838 DPRINTF("interrupt recv started ep %02X\n", ep);
839 dev->endpoint[EP2I(ep)].interrupt_started = 1;
840 /* We don't really want to drop interrupt packets ever, but
841 having some upper limit to how much we buffer is good. */
842 dev->endpoint[EP2I(ep)].bufpq_target_size = 1000;
843 dev->endpoint[EP2I(ep)].bufpq_dropping_packets = 0;
846 intp = QTAILQ_FIRST(&dev->endpoint[EP2I(ep)].bufpq);
847 if (intp == NULL) {
848 DPRINTF2("interrupt-token-in ep %02X, no intp\n", ep);
849 /* Check interrupt_error for stream errors */
850 status = dev->endpoint[EP2I(ep)].interrupt_error;
851 dev->endpoint[EP2I(ep)].interrupt_error = 0;
852 if (status) {
853 usbredir_handle_status(dev, p, status);
854 } else {
855 p->status = USB_RET_NAK;
857 return;
859 DPRINTF("interrupt-token-in ep %02X status %d len %d\n", ep,
860 intp->status, intp->len);
862 status = intp->status;
863 len = intp->len;
864 if (len > p->iov.size) {
865 ERROR("received int data is larger then packet ep %02X\n", ep);
866 len = p->iov.size;
867 status = usb_redir_babble;
869 usb_packet_copy(p, intp->data, len);
870 bufp_free(dev, intp, ep);
871 usbredir_handle_status(dev, p, status);
875 * Handle interrupt out data, the usbredir protocol expects us to do this
876 * async, so that it can report back a completion status. But guests will
877 * expect immediate completion for an interrupt endpoint, and handling this
878 * async causes migration issues. So we report success directly, counting
879 * on the fact that output interrupt packets normally always succeed.
881 static void usbredir_handle_interrupt_out_data(USBRedirDevice *dev,
882 USBPacket *p, uint8_t ep)
884 struct usb_redir_interrupt_packet_header interrupt_packet;
885 uint8_t buf[p->iov.size];
887 DPRINTF("interrupt-out ep %02X len %zd id %"PRIu64"\n", ep,
888 p->iov.size, p->id);
890 interrupt_packet.endpoint = ep;
891 interrupt_packet.length = p->iov.size;
893 usb_packet_copy(p, buf, p->iov.size);
894 usbredir_log_data(dev, "interrupt data out:", buf, p->iov.size);
895 usbredirparser_send_interrupt_packet(dev->parser, p->id,
896 &interrupt_packet, buf, p->iov.size);
897 usbredirparser_do_write(dev->parser);
900 static void usbredir_stop_interrupt_receiving(USBRedirDevice *dev,
901 uint8_t ep)
903 struct usb_redir_stop_interrupt_receiving_header stop_interrupt_recv = {
904 .endpoint = ep
906 if (dev->endpoint[EP2I(ep)].interrupt_started) {
907 usbredirparser_send_stop_interrupt_receiving(dev->parser, 0,
908 &stop_interrupt_recv);
909 DPRINTF("interrupt recv stopped ep %02X\n", ep);
910 dev->endpoint[EP2I(ep)].interrupt_started = 0;
912 dev->endpoint[EP2I(ep)].interrupt_error = 0;
913 usbredir_free_bufpq(dev, ep);
916 static void usbredir_handle_data(USBDevice *udev, USBPacket *p)
918 USBRedirDevice *dev = USB_REDIRECT(udev);
919 uint8_t ep;
921 ep = p->ep->nr;
922 if (p->pid == USB_TOKEN_IN) {
923 ep |= USB_DIR_IN;
926 switch (dev->endpoint[EP2I(ep)].type) {
927 case USB_ENDPOINT_XFER_CONTROL:
928 ERROR("handle_data called for control transfer on ep %02X\n", ep);
929 p->status = USB_RET_NAK;
930 break;
931 case USB_ENDPOINT_XFER_BULK:
932 if (p->state == USB_PACKET_SETUP && p->pid == USB_TOKEN_IN &&
933 p->ep->pipeline) {
934 p->status = USB_RET_ADD_TO_QUEUE;
935 break;
937 usbredir_handle_bulk_data(dev, p, ep);
938 break;
939 case USB_ENDPOINT_XFER_ISOC:
940 usbredir_handle_iso_data(dev, p, ep);
941 break;
942 case USB_ENDPOINT_XFER_INT:
943 if (ep & USB_DIR_IN) {
944 usbredir_handle_interrupt_in_data(dev, p, ep);
945 } else {
946 usbredir_handle_interrupt_out_data(dev, p, ep);
948 break;
949 default:
950 ERROR("handle_data ep %02X has unknown type %d\n", ep,
951 dev->endpoint[EP2I(ep)].type);
952 p->status = USB_RET_NAK;
956 static void usbredir_flush_ep_queue(USBDevice *dev, USBEndpoint *ep)
958 if (ep->pid == USB_TOKEN_IN && ep->pipeline) {
959 usb_ep_combine_input_packets(ep);
963 static void usbredir_stop_ep(USBRedirDevice *dev, int i)
965 uint8_t ep = I2EP(i);
967 switch (dev->endpoint[i].type) {
968 case USB_ENDPOINT_XFER_BULK:
969 if (ep & USB_DIR_IN) {
970 usbredir_stop_bulk_receiving(dev, ep);
972 break;
973 case USB_ENDPOINT_XFER_ISOC:
974 usbredir_stop_iso_stream(dev, ep);
975 break;
976 case USB_ENDPOINT_XFER_INT:
977 if (ep & USB_DIR_IN) {
978 usbredir_stop_interrupt_receiving(dev, ep);
980 break;
982 usbredir_free_bufpq(dev, ep);
985 static void usbredir_ep_stopped(USBDevice *udev, USBEndpoint *uep)
987 USBRedirDevice *dev = USB_REDIRECT(udev);
989 usbredir_stop_ep(dev, USBEP2I(uep));
990 usbredirparser_do_write(dev->parser);
993 static void usbredir_set_config(USBRedirDevice *dev, USBPacket *p,
994 int config)
996 struct usb_redir_set_configuration_header set_config;
997 int i;
999 DPRINTF("set config %d id %"PRIu64"\n", config, p->id);
1001 for (i = 0; i < MAX_ENDPOINTS; i++) {
1002 usbredir_stop_ep(dev, i);
1005 set_config.configuration = config;
1006 usbredirparser_send_set_configuration(dev->parser, p->id, &set_config);
1007 usbredirparser_do_write(dev->parser);
1008 p->status = USB_RET_ASYNC;
1011 static void usbredir_get_config(USBRedirDevice *dev, USBPacket *p)
1013 DPRINTF("get config id %"PRIu64"\n", p->id);
1015 usbredirparser_send_get_configuration(dev->parser, p->id);
1016 usbredirparser_do_write(dev->parser);
1017 p->status = USB_RET_ASYNC;
1020 static void usbredir_set_interface(USBRedirDevice *dev, USBPacket *p,
1021 int interface, int alt)
1023 struct usb_redir_set_alt_setting_header set_alt;
1024 int i;
1026 DPRINTF("set interface %d alt %d id %"PRIu64"\n", interface, alt, p->id);
1028 for (i = 0; i < MAX_ENDPOINTS; i++) {
1029 if (dev->endpoint[i].interface == interface) {
1030 usbredir_stop_ep(dev, i);
1034 set_alt.interface = interface;
1035 set_alt.alt = alt;
1036 usbredirparser_send_set_alt_setting(dev->parser, p->id, &set_alt);
1037 usbredirparser_do_write(dev->parser);
1038 p->status = USB_RET_ASYNC;
1041 static void usbredir_get_interface(USBRedirDevice *dev, USBPacket *p,
1042 int interface)
1044 struct usb_redir_get_alt_setting_header get_alt;
1046 DPRINTF("get interface %d id %"PRIu64"\n", interface, p->id);
1048 get_alt.interface = interface;
1049 usbredirparser_send_get_alt_setting(dev->parser, p->id, &get_alt);
1050 usbredirparser_do_write(dev->parser);
1051 p->status = USB_RET_ASYNC;
1054 static void usbredir_handle_control(USBDevice *udev, USBPacket *p,
1055 int request, int value, int index, int length, uint8_t *data)
1057 USBRedirDevice *dev = USB_REDIRECT(udev);
1058 struct usb_redir_control_packet_header control_packet;
1060 if (usbredir_already_in_flight(dev, p->id)) {
1061 p->status = USB_RET_ASYNC;
1062 return;
1065 /* Special cases for certain standard device requests */
1066 switch (request) {
1067 case DeviceOutRequest | USB_REQ_SET_ADDRESS:
1068 DPRINTF("set address %d\n", value);
1069 dev->dev.addr = value;
1070 return;
1071 case DeviceOutRequest | USB_REQ_SET_CONFIGURATION:
1072 usbredir_set_config(dev, p, value & 0xff);
1073 return;
1074 case DeviceRequest | USB_REQ_GET_CONFIGURATION:
1075 usbredir_get_config(dev, p);
1076 return;
1077 case InterfaceOutRequest | USB_REQ_SET_INTERFACE:
1078 usbredir_set_interface(dev, p, index, value);
1079 return;
1080 case InterfaceRequest | USB_REQ_GET_INTERFACE:
1081 usbredir_get_interface(dev, p, index);
1082 return;
1085 /* Normal ctrl requests, note request is (bRequestType << 8) | bRequest */
1086 DPRINTF(
1087 "ctrl-out type 0x%x req 0x%x val 0x%x index %d len %d id %"PRIu64"\n",
1088 request >> 8, request & 0xff, value, index, length, p->id);
1090 control_packet.request = request & 0xFF;
1091 control_packet.requesttype = request >> 8;
1092 control_packet.endpoint = control_packet.requesttype & USB_DIR_IN;
1093 control_packet.value = value;
1094 control_packet.index = index;
1095 control_packet.length = length;
1097 if (control_packet.requesttype & USB_DIR_IN) {
1098 usbredirparser_send_control_packet(dev->parser, p->id,
1099 &control_packet, NULL, 0);
1100 } else {
1101 usbredir_log_data(dev, "ctrl data out:", data, length);
1102 usbredirparser_send_control_packet(dev->parser, p->id,
1103 &control_packet, data, length);
1105 usbredirparser_do_write(dev->parser);
1106 p->status = USB_RET_ASYNC;
1109 static int usbredir_alloc_streams(USBDevice *udev, USBEndpoint **eps,
1110 int nr_eps, int streams)
1112 USBRedirDevice *dev = USB_REDIRECT(udev);
1113 #if USBREDIR_VERSION >= 0x000700
1114 struct usb_redir_alloc_bulk_streams_header alloc_streams;
1115 int i;
1117 if (!usbredirparser_peer_has_cap(dev->parser,
1118 usb_redir_cap_bulk_streams)) {
1119 ERROR("peer does not support streams\n");
1120 goto reject;
1123 if (streams == 0) {
1124 ERROR("request to allocate 0 streams\n");
1125 return -1;
1128 alloc_streams.no_streams = streams;
1129 alloc_streams.endpoints = 0;
1130 for (i = 0; i < nr_eps; i++) {
1131 alloc_streams.endpoints |= 1 << USBEP2I(eps[i]);
1133 usbredirparser_send_alloc_bulk_streams(dev->parser, 0, &alloc_streams);
1134 usbredirparser_do_write(dev->parser);
1136 return 0;
1137 #else
1138 ERROR("usbredir_alloc_streams not implemented\n");
1139 goto reject;
1140 #endif
1141 reject:
1142 ERROR("streams are not available, disconnecting\n");
1143 qemu_bh_schedule(dev->device_reject_bh);
1144 return -1;
1147 static void usbredir_free_streams(USBDevice *udev, USBEndpoint **eps,
1148 int nr_eps)
1150 #if USBREDIR_VERSION >= 0x000700
1151 USBRedirDevice *dev = USB_REDIRECT(udev);
1152 struct usb_redir_free_bulk_streams_header free_streams;
1153 int i;
1155 if (!usbredirparser_peer_has_cap(dev->parser,
1156 usb_redir_cap_bulk_streams)) {
1157 return;
1160 free_streams.endpoints = 0;
1161 for (i = 0; i < nr_eps; i++) {
1162 free_streams.endpoints |= 1 << USBEP2I(eps[i]);
1164 usbredirparser_send_free_bulk_streams(dev->parser, 0, &free_streams);
1165 usbredirparser_do_write(dev->parser);
1166 #endif
1170 * Close events can be triggered by usbredirparser_do_write which gets called
1171 * from within the USBDevice data / control packet callbacks and doing a
1172 * usb_detach from within these callbacks is not a good idea.
1174 * So we use a bh handler to take care of close events.
1176 static void usbredir_chardev_close_bh(void *opaque)
1178 USBRedirDevice *dev = opaque;
1180 qemu_bh_cancel(dev->device_reject_bh);
1181 usbredir_device_disconnect(dev);
1183 if (dev->parser) {
1184 DPRINTF("destroying usbredirparser\n");
1185 usbredirparser_destroy(dev->parser);
1186 dev->parser = NULL;
1188 if (dev->watch) {
1189 g_source_remove(dev->watch);
1190 dev->watch = 0;
1194 static void usbredir_create_parser(USBRedirDevice *dev)
1196 uint32_t caps[USB_REDIR_CAPS_SIZE] = { 0, };
1197 int flags = 0;
1199 DPRINTF("creating usbredirparser\n");
1201 dev->parser = qemu_oom_check(usbredirparser_create());
1202 dev->parser->priv = dev;
1203 dev->parser->log_func = usbredir_log;
1204 dev->parser->read_func = usbredir_read;
1205 dev->parser->write_func = usbredir_write;
1206 dev->parser->hello_func = usbredir_hello;
1207 dev->parser->device_connect_func = usbredir_device_connect;
1208 dev->parser->device_disconnect_func = usbredir_device_disconnect;
1209 dev->parser->interface_info_func = usbredir_interface_info;
1210 dev->parser->ep_info_func = usbredir_ep_info;
1211 dev->parser->configuration_status_func = usbredir_configuration_status;
1212 dev->parser->alt_setting_status_func = usbredir_alt_setting_status;
1213 dev->parser->iso_stream_status_func = usbredir_iso_stream_status;
1214 dev->parser->interrupt_receiving_status_func =
1215 usbredir_interrupt_receiving_status;
1216 dev->parser->bulk_streams_status_func = usbredir_bulk_streams_status;
1217 dev->parser->bulk_receiving_status_func = usbredir_bulk_receiving_status;
1218 dev->parser->control_packet_func = usbredir_control_packet;
1219 dev->parser->bulk_packet_func = usbredir_bulk_packet;
1220 dev->parser->iso_packet_func = usbredir_iso_packet;
1221 dev->parser->interrupt_packet_func = usbredir_interrupt_packet;
1222 dev->parser->buffered_bulk_packet_func = usbredir_buffered_bulk_packet;
1223 dev->read_buf = NULL;
1224 dev->read_buf_size = 0;
1226 usbredirparser_caps_set_cap(caps, usb_redir_cap_connect_device_version);
1227 usbredirparser_caps_set_cap(caps, usb_redir_cap_filter);
1228 usbredirparser_caps_set_cap(caps, usb_redir_cap_ep_info_max_packet_size);
1229 usbredirparser_caps_set_cap(caps, usb_redir_cap_64bits_ids);
1230 usbredirparser_caps_set_cap(caps, usb_redir_cap_32bits_bulk_length);
1231 usbredirparser_caps_set_cap(caps, usb_redir_cap_bulk_receiving);
1232 #if USBREDIR_VERSION >= 0x000700
1233 if (dev->enable_streams) {
1234 usbredirparser_caps_set_cap(caps, usb_redir_cap_bulk_streams);
1236 #endif
1238 if (runstate_check(RUN_STATE_INMIGRATE)) {
1239 flags |= usbredirparser_fl_no_hello;
1241 usbredirparser_init(dev->parser, VERSION, caps, USB_REDIR_CAPS_SIZE,
1242 flags);
1243 usbredirparser_do_write(dev->parser);
1246 static void usbredir_reject_device(USBRedirDevice *dev)
1248 usbredir_device_disconnect(dev);
1249 if (usbredirparser_peer_has_cap(dev->parser, usb_redir_cap_filter)) {
1250 usbredirparser_send_filter_reject(dev->parser);
1251 usbredirparser_do_write(dev->parser);
1256 * We may need to reject the device when the hcd calls alloc_streams, doing
1257 * an usb_detach from within a hcd call is not a good idea, hence this bh.
1259 static void usbredir_device_reject_bh(void *opaque)
1261 USBRedirDevice *dev = opaque;
1263 usbredir_reject_device(dev);
1266 static void usbredir_do_attach(void *opaque)
1268 USBRedirDevice *dev = opaque;
1269 Error *local_err = NULL;
1271 /* In order to work properly with XHCI controllers we need these caps */
1272 if ((dev->dev.port->speedmask & USB_SPEED_MASK_SUPER) && !(
1273 usbredirparser_peer_has_cap(dev->parser,
1274 usb_redir_cap_ep_info_max_packet_size) &&
1275 usbredirparser_peer_has_cap(dev->parser,
1276 usb_redir_cap_32bits_bulk_length) &&
1277 usbredirparser_peer_has_cap(dev->parser,
1278 usb_redir_cap_64bits_ids))) {
1279 ERROR("usb-redir-host lacks capabilities needed for use with XHCI\n");
1280 usbredir_reject_device(dev);
1281 return;
1284 usb_device_attach(&dev->dev, &local_err);
1285 if (local_err) {
1286 error_report_err(local_err);
1287 WARNING("rejecting device due to speed mismatch\n");
1288 usbredir_reject_device(dev);
1293 * chardev callbacks
1296 static int usbredir_chardev_can_read(void *opaque)
1298 USBRedirDevice *dev = opaque;
1300 if (!dev->parser) {
1301 WARNING("chardev_can_read called on non open chardev!\n");
1302 return 0;
1305 /* Don't read new data from the chardev until our state is fully synced */
1306 if (!runstate_check(RUN_STATE_RUNNING)) {
1307 return 0;
1310 /* usbredir_parser_do_read will consume *all* data we give it */
1311 return 1024 * 1024;
1314 static void usbredir_chardev_read(void *opaque, const uint8_t *buf, int size)
1316 USBRedirDevice *dev = opaque;
1318 /* No recursion allowed! */
1319 assert(dev->read_buf == NULL);
1321 dev->read_buf = buf;
1322 dev->read_buf_size = size;
1324 usbredirparser_do_read(dev->parser);
1325 /* Send any acks, etc. which may be queued now */
1326 usbredirparser_do_write(dev->parser);
1329 static void usbredir_chardev_event(void *opaque, int event)
1331 USBRedirDevice *dev = opaque;
1333 switch (event) {
1334 case CHR_EVENT_OPENED:
1335 DPRINTF("chardev open\n");
1336 /* Make sure any pending closes are handled (no-op if none pending) */
1337 usbredir_chardev_close_bh(dev);
1338 qemu_bh_cancel(dev->chardev_close_bh);
1339 usbredir_create_parser(dev);
1340 break;
1341 case CHR_EVENT_CLOSED:
1342 DPRINTF("chardev close\n");
1343 qemu_bh_schedule(dev->chardev_close_bh);
1344 break;
1349 * init + destroy
1352 static void usbredir_vm_state_change(void *priv, int running, RunState state)
1354 USBRedirDevice *dev = priv;
1356 if (state == RUN_STATE_RUNNING && dev->parser != NULL) {
1357 usbredirparser_do_write(dev->parser); /* Flush any pending writes */
1361 static void usbredir_init_endpoints(USBRedirDevice *dev)
1363 int i;
1365 usb_ep_init(&dev->dev);
1366 memset(dev->endpoint, 0, sizeof(dev->endpoint));
1367 for (i = 0; i < MAX_ENDPOINTS; i++) {
1368 dev->endpoint[i].dev = dev;
1369 QTAILQ_INIT(&dev->endpoint[i].bufpq);
1373 static void usbredir_realize(USBDevice *udev, Error **errp)
1375 USBRedirDevice *dev = USB_REDIRECT(udev);
1376 int i;
1378 if (dev->cs == NULL) {
1379 error_setg(errp, QERR_MISSING_PARAMETER, "chardev");
1380 return;
1383 if (dev->filter_str) {
1384 i = usbredirfilter_string_to_rules(dev->filter_str, ":", "|",
1385 &dev->filter_rules,
1386 &dev->filter_rules_count);
1387 if (i) {
1388 error_setg(errp, QERR_INVALID_PARAMETER_VALUE, "filter",
1389 "a usb device filter string");
1390 return;
1394 dev->chardev_close_bh = qemu_bh_new(usbredir_chardev_close_bh, dev);
1395 dev->device_reject_bh = qemu_bh_new(usbredir_device_reject_bh, dev);
1396 dev->attach_timer = timer_new_ms(QEMU_CLOCK_VIRTUAL, usbredir_do_attach, dev);
1398 packet_id_queue_init(&dev->cancelled, dev, "cancelled");
1399 packet_id_queue_init(&dev->already_in_flight, dev, "already-in-flight");
1400 usbredir_init_endpoints(dev);
1402 /* We'll do the attach once we receive the speed from the usb-host */
1403 udev->auto_attach = 0;
1405 /* Will be cleared during setup when we find conflicts */
1406 dev->compatible_speedmask = USB_SPEED_MASK_FULL | USB_SPEED_MASK_HIGH;
1408 /* Let the backend know we are ready */
1409 qemu_chr_add_handlers(dev->cs, usbredir_chardev_can_read,
1410 usbredir_chardev_read, usbredir_chardev_event, dev);
1412 qemu_add_vm_change_state_handler(usbredir_vm_state_change, dev);
1415 static void usbredir_cleanup_device_queues(USBRedirDevice *dev)
1417 int i;
1419 packet_id_queue_empty(&dev->cancelled);
1420 packet_id_queue_empty(&dev->already_in_flight);
1421 for (i = 0; i < MAX_ENDPOINTS; i++) {
1422 usbredir_free_bufpq(dev, I2EP(i));
1426 static void usbredir_handle_destroy(USBDevice *udev)
1428 USBRedirDevice *dev = USB_REDIRECT(udev);
1430 qemu_chr_delete(dev->cs);
1431 dev->cs = NULL;
1432 /* Note must be done after qemu_chr_close, as that causes a close event */
1433 qemu_bh_delete(dev->chardev_close_bh);
1434 qemu_bh_delete(dev->device_reject_bh);
1436 timer_del(dev->attach_timer);
1437 timer_free(dev->attach_timer);
1439 usbredir_cleanup_device_queues(dev);
1441 if (dev->parser) {
1442 usbredirparser_destroy(dev->parser);
1444 if (dev->watch) {
1445 g_source_remove(dev->watch);
1448 free(dev->filter_rules);
1451 static int usbredir_check_filter(USBRedirDevice *dev)
1453 if (dev->interface_info.interface_count == NO_INTERFACE_INFO) {
1454 ERROR("No interface info for device\n");
1455 goto error;
1458 if (dev->filter_rules) {
1459 if (!usbredirparser_peer_has_cap(dev->parser,
1460 usb_redir_cap_connect_device_version)) {
1461 ERROR("Device filter specified and peer does not have the "
1462 "connect_device_version capability\n");
1463 goto error;
1466 if (usbredirfilter_check(
1467 dev->filter_rules,
1468 dev->filter_rules_count,
1469 dev->device_info.device_class,
1470 dev->device_info.device_subclass,
1471 dev->device_info.device_protocol,
1472 dev->interface_info.interface_class,
1473 dev->interface_info.interface_subclass,
1474 dev->interface_info.interface_protocol,
1475 dev->interface_info.interface_count,
1476 dev->device_info.vendor_id,
1477 dev->device_info.product_id,
1478 dev->device_info.device_version_bcd,
1479 0) != 0) {
1480 goto error;
1484 return 0;
1486 error:
1487 usbredir_reject_device(dev);
1488 return -1;
1491 static void usbredir_check_bulk_receiving(USBRedirDevice *dev)
1493 int i, j, quirks;
1495 if (!usbredirparser_peer_has_cap(dev->parser,
1496 usb_redir_cap_bulk_receiving)) {
1497 return;
1500 for (i = EP2I(USB_DIR_IN); i < MAX_ENDPOINTS; i++) {
1501 dev->endpoint[i].bulk_receiving_enabled = 0;
1503 for (i = 0; i < dev->interface_info.interface_count; i++) {
1504 quirks = usb_get_quirks(dev->device_info.vendor_id,
1505 dev->device_info.product_id,
1506 dev->interface_info.interface_class[i],
1507 dev->interface_info.interface_subclass[i],
1508 dev->interface_info.interface_protocol[i]);
1509 if (!(quirks & USB_QUIRK_BUFFER_BULK_IN)) {
1510 continue;
1512 if (quirks & USB_QUIRK_IS_FTDI) {
1513 dev->buffered_bulk_in_complete =
1514 usbredir_buffered_bulk_in_complete_ftdi;
1515 } else {
1516 dev->buffered_bulk_in_complete =
1517 usbredir_buffered_bulk_in_complete_raw;
1520 for (j = EP2I(USB_DIR_IN); j < MAX_ENDPOINTS; j++) {
1521 if (dev->endpoint[j].interface ==
1522 dev->interface_info.interface[i] &&
1523 dev->endpoint[j].type == USB_ENDPOINT_XFER_BULK &&
1524 dev->endpoint[j].max_packet_size != 0) {
1525 dev->endpoint[j].bulk_receiving_enabled = 1;
1527 * With buffering pipelining is not necessary. Also packet
1528 * combining and bulk in buffering don't play nice together!
1530 I2USBEP(dev, j)->pipeline = false;
1531 break; /* Only buffer for the first ep of each intf */
1538 * usbredirparser packet complete callbacks
1541 static void usbredir_handle_status(USBRedirDevice *dev, USBPacket *p,
1542 int status)
1544 switch (status) {
1545 case usb_redir_success:
1546 p->status = USB_RET_SUCCESS; /* Clear previous ASYNC status */
1547 break;
1548 case usb_redir_stall:
1549 p->status = USB_RET_STALL;
1550 break;
1551 case usb_redir_cancelled:
1553 * When the usbredir-host unredirects a device, it will report a status
1554 * of cancelled for all pending packets, followed by a disconnect msg.
1556 p->status = USB_RET_IOERROR;
1557 break;
1558 case usb_redir_inval:
1559 WARNING("got invalid param error from usb-host?\n");
1560 p->status = USB_RET_IOERROR;
1561 break;
1562 case usb_redir_babble:
1563 p->status = USB_RET_BABBLE;
1564 break;
1565 case usb_redir_ioerror:
1566 case usb_redir_timeout:
1567 default:
1568 p->status = USB_RET_IOERROR;
1572 static void usbredir_hello(void *priv, struct usb_redir_hello_header *h)
1574 USBRedirDevice *dev = priv;
1576 /* Try to send the filter info now that we've the usb-host's caps */
1577 if (usbredirparser_peer_has_cap(dev->parser, usb_redir_cap_filter) &&
1578 dev->filter_rules) {
1579 usbredirparser_send_filter_filter(dev->parser, dev->filter_rules,
1580 dev->filter_rules_count);
1581 usbredirparser_do_write(dev->parser);
1585 static void usbredir_device_connect(void *priv,
1586 struct usb_redir_device_connect_header *device_connect)
1588 USBRedirDevice *dev = priv;
1589 const char *speed;
1591 if (timer_pending(dev->attach_timer) || dev->dev.attached) {
1592 ERROR("Received device connect while already connected\n");
1593 return;
1596 switch (device_connect->speed) {
1597 case usb_redir_speed_low:
1598 speed = "low speed";
1599 dev->dev.speed = USB_SPEED_LOW;
1600 dev->compatible_speedmask &= ~USB_SPEED_MASK_FULL;
1601 dev->compatible_speedmask &= ~USB_SPEED_MASK_HIGH;
1602 break;
1603 case usb_redir_speed_full:
1604 speed = "full speed";
1605 dev->dev.speed = USB_SPEED_FULL;
1606 dev->compatible_speedmask &= ~USB_SPEED_MASK_HIGH;
1607 break;
1608 case usb_redir_speed_high:
1609 speed = "high speed";
1610 dev->dev.speed = USB_SPEED_HIGH;
1611 break;
1612 case usb_redir_speed_super:
1613 speed = "super speed";
1614 dev->dev.speed = USB_SPEED_SUPER;
1615 break;
1616 default:
1617 speed = "unknown speed";
1618 dev->dev.speed = USB_SPEED_FULL;
1621 if (usbredirparser_peer_has_cap(dev->parser,
1622 usb_redir_cap_connect_device_version)) {
1623 INFO("attaching %s device %04x:%04x version %d.%d class %02x\n",
1624 speed, device_connect->vendor_id, device_connect->product_id,
1625 ((device_connect->device_version_bcd & 0xf000) >> 12) * 10 +
1626 ((device_connect->device_version_bcd & 0x0f00) >> 8),
1627 ((device_connect->device_version_bcd & 0x00f0) >> 4) * 10 +
1628 ((device_connect->device_version_bcd & 0x000f) >> 0),
1629 device_connect->device_class);
1630 } else {
1631 INFO("attaching %s device %04x:%04x class %02x\n", speed,
1632 device_connect->vendor_id, device_connect->product_id,
1633 device_connect->device_class);
1636 dev->dev.speedmask = (1 << dev->dev.speed) | dev->compatible_speedmask;
1637 dev->device_info = *device_connect;
1639 if (usbredir_check_filter(dev)) {
1640 WARNING("Device %04x:%04x rejected by device filter, not attaching\n",
1641 device_connect->vendor_id, device_connect->product_id);
1642 return;
1645 usbredir_check_bulk_receiving(dev);
1646 timer_mod(dev->attach_timer, dev->next_attach_time);
1649 static void usbredir_device_disconnect(void *priv)
1651 USBRedirDevice *dev = priv;
1653 /* Stop any pending attaches */
1654 timer_del(dev->attach_timer);
1656 if (dev->dev.attached) {
1657 DPRINTF("detaching device\n");
1658 usb_device_detach(&dev->dev);
1660 * Delay next usb device attach to give the guest a chance to see
1661 * see the detach / attach in case of quick close / open succession
1663 dev->next_attach_time = qemu_clock_get_ms(QEMU_CLOCK_VIRTUAL) + 200;
1666 /* Reset state so that the next dev connected starts with a clean slate */
1667 usbredir_cleanup_device_queues(dev);
1668 usbredir_init_endpoints(dev);
1669 dev->interface_info.interface_count = NO_INTERFACE_INFO;
1670 dev->dev.addr = 0;
1671 dev->dev.speed = 0;
1672 dev->compatible_speedmask = USB_SPEED_MASK_FULL | USB_SPEED_MASK_HIGH;
1675 static void usbredir_interface_info(void *priv,
1676 struct usb_redir_interface_info_header *interface_info)
1678 USBRedirDevice *dev = priv;
1680 dev->interface_info = *interface_info;
1683 * If we receive interface info after the device has already been
1684 * connected (ie on a set_config), re-check interface dependent things.
1686 if (timer_pending(dev->attach_timer) || dev->dev.attached) {
1687 usbredir_check_bulk_receiving(dev);
1688 if (usbredir_check_filter(dev)) {
1689 ERROR("Device no longer matches filter after interface info "
1690 "change, disconnecting!\n");
1695 static void usbredir_mark_speed_incompatible(USBRedirDevice *dev, int speed)
1697 dev->compatible_speedmask &= ~(1 << speed);
1698 dev->dev.speedmask = (1 << dev->dev.speed) | dev->compatible_speedmask;
1701 static void usbredir_set_pipeline(USBRedirDevice *dev, struct USBEndpoint *uep)
1703 if (uep->type != USB_ENDPOINT_XFER_BULK) {
1704 return;
1706 if (uep->pid == USB_TOKEN_OUT) {
1707 uep->pipeline = true;
1709 if (uep->pid == USB_TOKEN_IN && uep->max_packet_size != 0 &&
1710 usbredirparser_peer_has_cap(dev->parser,
1711 usb_redir_cap_32bits_bulk_length)) {
1712 uep->pipeline = true;
1716 static void usbredir_setup_usb_eps(USBRedirDevice *dev)
1718 struct USBEndpoint *usb_ep;
1719 int i;
1721 for (i = 0; i < MAX_ENDPOINTS; i++) {
1722 usb_ep = I2USBEP(dev, i);
1723 usb_ep->type = dev->endpoint[i].type;
1724 usb_ep->ifnum = dev->endpoint[i].interface;
1725 usb_ep->max_packet_size = dev->endpoint[i].max_packet_size;
1726 usb_ep->max_streams = dev->endpoint[i].max_streams;
1727 usbredir_set_pipeline(dev, usb_ep);
1731 static void usbredir_ep_info(void *priv,
1732 struct usb_redir_ep_info_header *ep_info)
1734 USBRedirDevice *dev = priv;
1735 int i;
1737 for (i = 0; i < MAX_ENDPOINTS; i++) {
1738 dev->endpoint[i].type = ep_info->type[i];
1739 dev->endpoint[i].interval = ep_info->interval[i];
1740 dev->endpoint[i].interface = ep_info->interface[i];
1741 if (usbredirparser_peer_has_cap(dev->parser,
1742 usb_redir_cap_ep_info_max_packet_size)) {
1743 dev->endpoint[i].max_packet_size = ep_info->max_packet_size[i];
1745 #if USBREDIR_VERSION >= 0x000700
1746 if (usbredirparser_peer_has_cap(dev->parser,
1747 usb_redir_cap_bulk_streams)) {
1748 dev->endpoint[i].max_streams = ep_info->max_streams[i];
1750 #endif
1751 switch (dev->endpoint[i].type) {
1752 case usb_redir_type_invalid:
1753 break;
1754 case usb_redir_type_iso:
1755 usbredir_mark_speed_incompatible(dev, USB_SPEED_FULL);
1756 usbredir_mark_speed_incompatible(dev, USB_SPEED_HIGH);
1757 /* Fall through */
1758 case usb_redir_type_interrupt:
1759 if (!usbredirparser_peer_has_cap(dev->parser,
1760 usb_redir_cap_ep_info_max_packet_size) ||
1761 ep_info->max_packet_size[i] > 64) {
1762 usbredir_mark_speed_incompatible(dev, USB_SPEED_FULL);
1764 if (!usbredirparser_peer_has_cap(dev->parser,
1765 usb_redir_cap_ep_info_max_packet_size) ||
1766 ep_info->max_packet_size[i] > 1024) {
1767 usbredir_mark_speed_incompatible(dev, USB_SPEED_HIGH);
1769 if (dev->endpoint[i].interval == 0) {
1770 ERROR("Received 0 interval for isoc or irq endpoint\n");
1771 usbredir_reject_device(dev);
1772 return;
1774 /* Fall through */
1775 case usb_redir_type_control:
1776 case usb_redir_type_bulk:
1777 DPRINTF("ep: %02X type: %d interface: %d\n", I2EP(i),
1778 dev->endpoint[i].type, dev->endpoint[i].interface);
1779 break;
1780 default:
1781 ERROR("Received invalid endpoint type\n");
1782 usbredir_reject_device(dev);
1783 return;
1786 /* The new ep info may have caused a speed incompatibility, recheck */
1787 if (dev->dev.attached &&
1788 !(dev->dev.port->speedmask & dev->dev.speedmask)) {
1789 ERROR("Device no longer matches speed after endpoint info change, "
1790 "disconnecting!\n");
1791 usbredir_reject_device(dev);
1792 return;
1794 usbredir_setup_usb_eps(dev);
1795 usbredir_check_bulk_receiving(dev);
1798 static void usbredir_configuration_status(void *priv, uint64_t id,
1799 struct usb_redir_configuration_status_header *config_status)
1801 USBRedirDevice *dev = priv;
1802 USBPacket *p;
1804 DPRINTF("set config status %d config %d id %"PRIu64"\n",
1805 config_status->status, config_status->configuration, id);
1807 p = usbredir_find_packet_by_id(dev, 0, id);
1808 if (p) {
1809 if (dev->dev.setup_buf[0] & USB_DIR_IN) {
1810 dev->dev.data_buf[0] = config_status->configuration;
1811 p->actual_length = 1;
1813 usbredir_handle_status(dev, p, config_status->status);
1814 usb_generic_async_ctrl_complete(&dev->dev, p);
1818 static void usbredir_alt_setting_status(void *priv, uint64_t id,
1819 struct usb_redir_alt_setting_status_header *alt_setting_status)
1821 USBRedirDevice *dev = priv;
1822 USBPacket *p;
1824 DPRINTF("alt status %d intf %d alt %d id: %"PRIu64"\n",
1825 alt_setting_status->status, alt_setting_status->interface,
1826 alt_setting_status->alt, id);
1828 p = usbredir_find_packet_by_id(dev, 0, id);
1829 if (p) {
1830 if (dev->dev.setup_buf[0] & USB_DIR_IN) {
1831 dev->dev.data_buf[0] = alt_setting_status->alt;
1832 p->actual_length = 1;
1834 usbredir_handle_status(dev, p, alt_setting_status->status);
1835 usb_generic_async_ctrl_complete(&dev->dev, p);
1839 static void usbredir_iso_stream_status(void *priv, uint64_t id,
1840 struct usb_redir_iso_stream_status_header *iso_stream_status)
1842 USBRedirDevice *dev = priv;
1843 uint8_t ep = iso_stream_status->endpoint;
1845 DPRINTF("iso status %d ep %02X id %"PRIu64"\n", iso_stream_status->status,
1846 ep, id);
1848 if (!dev->dev.attached || !dev->endpoint[EP2I(ep)].iso_started) {
1849 return;
1852 dev->endpoint[EP2I(ep)].iso_error = iso_stream_status->status;
1853 if (iso_stream_status->status == usb_redir_stall) {
1854 DPRINTF("iso stream stopped by peer ep %02X\n", ep);
1855 dev->endpoint[EP2I(ep)].iso_started = 0;
1859 static void usbredir_interrupt_receiving_status(void *priv, uint64_t id,
1860 struct usb_redir_interrupt_receiving_status_header
1861 *interrupt_receiving_status)
1863 USBRedirDevice *dev = priv;
1864 uint8_t ep = interrupt_receiving_status->endpoint;
1866 DPRINTF("interrupt recv status %d ep %02X id %"PRIu64"\n",
1867 interrupt_receiving_status->status, ep, id);
1869 if (!dev->dev.attached || !dev->endpoint[EP2I(ep)].interrupt_started) {
1870 return;
1873 dev->endpoint[EP2I(ep)].interrupt_error =
1874 interrupt_receiving_status->status;
1875 if (interrupt_receiving_status->status == usb_redir_stall) {
1876 DPRINTF("interrupt receiving stopped by peer ep %02X\n", ep);
1877 dev->endpoint[EP2I(ep)].interrupt_started = 0;
1881 static void usbredir_bulk_streams_status(void *priv, uint64_t id,
1882 struct usb_redir_bulk_streams_status_header *bulk_streams_status)
1884 #if USBREDIR_VERSION >= 0x000700
1885 USBRedirDevice *dev = priv;
1887 if (bulk_streams_status->status == usb_redir_success) {
1888 DPRINTF("bulk streams status %d eps %08x\n",
1889 bulk_streams_status->status, bulk_streams_status->endpoints);
1890 } else {
1891 ERROR("bulk streams %s failed status %d eps %08x\n",
1892 (bulk_streams_status->no_streams == 0) ? "free" : "alloc",
1893 bulk_streams_status->status, bulk_streams_status->endpoints);
1894 ERROR("usb-redir-host does not provide streams, disconnecting\n");
1895 usbredir_reject_device(dev);
1897 #endif
1900 static void usbredir_bulk_receiving_status(void *priv, uint64_t id,
1901 struct usb_redir_bulk_receiving_status_header *bulk_receiving_status)
1903 USBRedirDevice *dev = priv;
1904 uint8_t ep = bulk_receiving_status->endpoint;
1906 DPRINTF("bulk recv status %d ep %02X id %"PRIu64"\n",
1907 bulk_receiving_status->status, ep, id);
1909 if (!dev->dev.attached || !dev->endpoint[EP2I(ep)].bulk_receiving_started) {
1910 return;
1913 if (bulk_receiving_status->status == usb_redir_stall) {
1914 DPRINTF("bulk receiving stopped by peer ep %02X\n", ep);
1915 dev->endpoint[EP2I(ep)].bulk_receiving_started = 0;
1919 static void usbredir_control_packet(void *priv, uint64_t id,
1920 struct usb_redir_control_packet_header *control_packet,
1921 uint8_t *data, int data_len)
1923 USBRedirDevice *dev = priv;
1924 USBPacket *p;
1925 int len = control_packet->length;
1927 DPRINTF("ctrl-in status %d len %d id %"PRIu64"\n", control_packet->status,
1928 len, id);
1930 /* Fix up USB-3 ep0 maxpacket size to allow superspeed connected devices
1931 * to work redirected to a not superspeed capable hcd */
1932 if (dev->dev.speed == USB_SPEED_SUPER &&
1933 !((dev->dev.port->speedmask & USB_SPEED_MASK_SUPER)) &&
1934 control_packet->requesttype == 0x80 &&
1935 control_packet->request == 6 &&
1936 control_packet->value == 0x100 && control_packet->index == 0 &&
1937 data_len >= 18 && data[7] == 9) {
1938 data[7] = 64;
1941 p = usbredir_find_packet_by_id(dev, 0, id);
1942 if (p) {
1943 usbredir_handle_status(dev, p, control_packet->status);
1944 if (data_len > 0) {
1945 usbredir_log_data(dev, "ctrl data in:", data, data_len);
1946 if (data_len > sizeof(dev->dev.data_buf)) {
1947 ERROR("ctrl buffer too small (%d > %zu)\n",
1948 data_len, sizeof(dev->dev.data_buf));
1949 p->status = USB_RET_STALL;
1950 data_len = len = sizeof(dev->dev.data_buf);
1952 memcpy(dev->dev.data_buf, data, data_len);
1954 p->actual_length = len;
1955 usb_generic_async_ctrl_complete(&dev->dev, p);
1957 free(data);
1960 static void usbredir_bulk_packet(void *priv, uint64_t id,
1961 struct usb_redir_bulk_packet_header *bulk_packet,
1962 uint8_t *data, int data_len)
1964 USBRedirDevice *dev = priv;
1965 uint8_t ep = bulk_packet->endpoint;
1966 int len = (bulk_packet->length_high << 16) | bulk_packet->length;
1967 USBPacket *p;
1969 DPRINTF("bulk-in status %d ep %02X stream %u len %d id %"PRIu64"\n",
1970 bulk_packet->status, ep, bulk_packet->stream_id, len, id);
1972 p = usbredir_find_packet_by_id(dev, ep, id);
1973 if (p) {
1974 size_t size = usb_packet_size(p);
1975 usbredir_handle_status(dev, p, bulk_packet->status);
1976 if (data_len > 0) {
1977 usbredir_log_data(dev, "bulk data in:", data, data_len);
1978 if (data_len > size) {
1979 ERROR("bulk got more data then requested (%d > %zd)\n",
1980 data_len, p->iov.size);
1981 p->status = USB_RET_BABBLE;
1982 data_len = len = size;
1984 usb_packet_copy(p, data, data_len);
1986 p->actual_length = len;
1987 if (p->pid == USB_TOKEN_IN && p->ep->pipeline) {
1988 usb_combined_input_packet_complete(&dev->dev, p);
1989 } else {
1990 usb_packet_complete(&dev->dev, p);
1993 free(data);
1996 static void usbredir_iso_packet(void *priv, uint64_t id,
1997 struct usb_redir_iso_packet_header *iso_packet,
1998 uint8_t *data, int data_len)
2000 USBRedirDevice *dev = priv;
2001 uint8_t ep = iso_packet->endpoint;
2003 DPRINTF2("iso-in status %d ep %02X len %d id %"PRIu64"\n",
2004 iso_packet->status, ep, data_len, id);
2006 if (dev->endpoint[EP2I(ep)].type != USB_ENDPOINT_XFER_ISOC) {
2007 ERROR("received iso packet for non iso endpoint %02X\n", ep);
2008 free(data);
2009 return;
2012 if (dev->endpoint[EP2I(ep)].iso_started == 0) {
2013 DPRINTF("received iso packet for non started stream ep %02X\n", ep);
2014 free(data);
2015 return;
2018 /* bufp_alloc also adds the packet to the ep queue */
2019 bufp_alloc(dev, data, data_len, iso_packet->status, ep, data);
2022 static void usbredir_interrupt_packet(void *priv, uint64_t id,
2023 struct usb_redir_interrupt_packet_header *interrupt_packet,
2024 uint8_t *data, int data_len)
2026 USBRedirDevice *dev = priv;
2027 uint8_t ep = interrupt_packet->endpoint;
2029 DPRINTF("interrupt-in status %d ep %02X len %d id %"PRIu64"\n",
2030 interrupt_packet->status, ep, data_len, id);
2032 if (dev->endpoint[EP2I(ep)].type != USB_ENDPOINT_XFER_INT) {
2033 ERROR("received int packet for non interrupt endpoint %02X\n", ep);
2034 free(data);
2035 return;
2038 if (ep & USB_DIR_IN) {
2039 bool q_was_empty;
2041 if (dev->endpoint[EP2I(ep)].interrupt_started == 0) {
2042 DPRINTF("received int packet while not started ep %02X\n", ep);
2043 free(data);
2044 return;
2047 q_was_empty = QTAILQ_EMPTY(&dev->endpoint[EP2I(ep)].bufpq);
2049 /* bufp_alloc also adds the packet to the ep queue */
2050 bufp_alloc(dev, data, data_len, interrupt_packet->status, ep, data);
2052 if (q_was_empty) {
2053 usb_wakeup(usb_ep_get(&dev->dev, USB_TOKEN_IN, ep & 0x0f), 0);
2055 } else {
2057 * We report output interrupt packets as completed directly upon
2058 * submission, so all we can do here if one failed is warn.
2060 if (interrupt_packet->status) {
2061 WARNING("interrupt output failed status %d ep %02X id %"PRIu64"\n",
2062 interrupt_packet->status, ep, id);
2067 static void usbredir_buffered_bulk_packet(void *priv, uint64_t id,
2068 struct usb_redir_buffered_bulk_packet_header *buffered_bulk_packet,
2069 uint8_t *data, int data_len)
2071 USBRedirDevice *dev = priv;
2072 uint8_t status, ep = buffered_bulk_packet->endpoint;
2073 void *free_on_destroy;
2074 int i, len;
2076 DPRINTF("buffered-bulk-in status %d ep %02X len %d id %"PRIu64"\n",
2077 buffered_bulk_packet->status, ep, data_len, id);
2079 if (dev->endpoint[EP2I(ep)].type != USB_ENDPOINT_XFER_BULK) {
2080 ERROR("received buffered-bulk packet for non bulk ep %02X\n", ep);
2081 free(data);
2082 return;
2085 if (dev->endpoint[EP2I(ep)].bulk_receiving_started == 0) {
2086 DPRINTF("received buffered-bulk packet on not started ep %02X\n", ep);
2087 free(data);
2088 return;
2091 /* Data must be in maxp chunks for buffered_bulk_add_*_data_to_packet */
2092 len = dev->endpoint[EP2I(ep)].max_packet_size;
2093 status = usb_redir_success;
2094 free_on_destroy = NULL;
2095 for (i = 0; i < data_len; i += len) {
2096 int r;
2097 if (len >= (data_len - i)) {
2098 len = data_len - i;
2099 status = buffered_bulk_packet->status;
2100 free_on_destroy = data;
2102 /* bufp_alloc also adds the packet to the ep queue */
2103 r = bufp_alloc(dev, data + i, len, status, ep, free_on_destroy);
2104 if (r) {
2105 break;
2109 if (dev->endpoint[EP2I(ep)].pending_async_packet) {
2110 USBPacket *p = dev->endpoint[EP2I(ep)].pending_async_packet;
2111 dev->endpoint[EP2I(ep)].pending_async_packet = NULL;
2112 usbredir_buffered_bulk_in_complete(dev, p, ep);
2113 usb_packet_complete(&dev->dev, p);
2118 * Migration code
2121 static void usbredir_pre_save(void *priv)
2123 USBRedirDevice *dev = priv;
2125 usbredir_fill_already_in_flight(dev);
2128 static int usbredir_post_load(void *priv, int version_id)
2130 USBRedirDevice *dev = priv;
2132 if (dev->parser == NULL) {
2133 return 0;
2136 switch (dev->device_info.speed) {
2137 case usb_redir_speed_low:
2138 dev->dev.speed = USB_SPEED_LOW;
2139 break;
2140 case usb_redir_speed_full:
2141 dev->dev.speed = USB_SPEED_FULL;
2142 break;
2143 case usb_redir_speed_high:
2144 dev->dev.speed = USB_SPEED_HIGH;
2145 break;
2146 case usb_redir_speed_super:
2147 dev->dev.speed = USB_SPEED_SUPER;
2148 break;
2149 default:
2150 dev->dev.speed = USB_SPEED_FULL;
2152 dev->dev.speedmask = (1 << dev->dev.speed);
2154 usbredir_setup_usb_eps(dev);
2155 usbredir_check_bulk_receiving(dev);
2157 return 0;
2160 /* For usbredirparser migration */
2161 static void usbredir_put_parser(QEMUFile *f, void *priv, size_t unused)
2163 USBRedirDevice *dev = priv;
2164 uint8_t *data;
2165 int len;
2167 if (dev->parser == NULL) {
2168 qemu_put_be32(f, 0);
2169 return;
2172 usbredirparser_serialize(dev->parser, &data, &len);
2173 qemu_oom_check(data);
2175 qemu_put_be32(f, len);
2176 qemu_put_buffer(f, data, len);
2178 free(data);
2181 static int usbredir_get_parser(QEMUFile *f, void *priv, size_t unused)
2183 USBRedirDevice *dev = priv;
2184 uint8_t *data;
2185 int len, ret;
2187 len = qemu_get_be32(f);
2188 if (len == 0) {
2189 return 0;
2193 * If our chardev is not open already at this point the usbredir connection
2194 * has been broken (non seamless migration, or restore from disk).
2196 * In this case create a temporary parser to receive the migration data,
2197 * and schedule the close_bh to report the device as disconnected to the
2198 * guest and to destroy the parser again.
2200 if (dev->parser == NULL) {
2201 WARNING("usb-redir connection broken during migration\n");
2202 usbredir_create_parser(dev);
2203 qemu_bh_schedule(dev->chardev_close_bh);
2206 data = g_malloc(len);
2207 qemu_get_buffer(f, data, len);
2209 ret = usbredirparser_unserialize(dev->parser, data, len);
2211 g_free(data);
2213 return ret;
2216 static const VMStateInfo usbredir_parser_vmstate_info = {
2217 .name = "usb-redir-parser",
2218 .put = usbredir_put_parser,
2219 .get = usbredir_get_parser,
2223 /* For buffered packets (iso/irq) queue migration */
2224 static void usbredir_put_bufpq(QEMUFile *f, void *priv, size_t unused)
2226 struct endp_data *endp = priv;
2227 USBRedirDevice *dev = endp->dev;
2228 struct buf_packet *bufp;
2229 int len, i = 0;
2231 qemu_put_be32(f, endp->bufpq_size);
2232 QTAILQ_FOREACH(bufp, &endp->bufpq, next) {
2233 len = bufp->len - bufp->offset;
2234 DPRINTF("put_bufpq %d/%d len %d status %d\n", i + 1, endp->bufpq_size,
2235 len, bufp->status);
2236 qemu_put_be32(f, len);
2237 qemu_put_be32(f, bufp->status);
2238 qemu_put_buffer(f, bufp->data + bufp->offset, len);
2239 i++;
2241 assert(i == endp->bufpq_size);
2244 static int usbredir_get_bufpq(QEMUFile *f, void *priv, size_t unused)
2246 struct endp_data *endp = priv;
2247 USBRedirDevice *dev = endp->dev;
2248 struct buf_packet *bufp;
2249 int i;
2251 endp->bufpq_size = qemu_get_be32(f);
2252 for (i = 0; i < endp->bufpq_size; i++) {
2253 bufp = g_new(struct buf_packet, 1);
2254 bufp->len = qemu_get_be32(f);
2255 bufp->status = qemu_get_be32(f);
2256 bufp->offset = 0;
2257 bufp->data = qemu_oom_check(malloc(bufp->len)); /* regular malloc! */
2258 bufp->free_on_destroy = bufp->data;
2259 qemu_get_buffer(f, bufp->data, bufp->len);
2260 QTAILQ_INSERT_TAIL(&endp->bufpq, bufp, next);
2261 DPRINTF("get_bufpq %d/%d len %d status %d\n", i + 1, endp->bufpq_size,
2262 bufp->len, bufp->status);
2264 return 0;
2267 static const VMStateInfo usbredir_ep_bufpq_vmstate_info = {
2268 .name = "usb-redir-bufpq",
2269 .put = usbredir_put_bufpq,
2270 .get = usbredir_get_bufpq,
2274 /* For endp_data migration */
2275 static bool usbredir_bulk_receiving_needed(void *priv)
2277 struct endp_data *endp = priv;
2279 return endp->bulk_receiving_started;
2282 static const VMStateDescription usbredir_bulk_receiving_vmstate = {
2283 .name = "usb-redir-ep/bulk-receiving",
2284 .version_id = 1,
2285 .minimum_version_id = 1,
2286 .needed = usbredir_bulk_receiving_needed,
2287 .fields = (VMStateField[]) {
2288 VMSTATE_UINT8(bulk_receiving_started, struct endp_data),
2289 VMSTATE_END_OF_LIST()
2293 static bool usbredir_stream_needed(void *priv)
2295 struct endp_data *endp = priv;
2297 return endp->max_streams;
2300 static const VMStateDescription usbredir_stream_vmstate = {
2301 .name = "usb-redir-ep/stream-state",
2302 .version_id = 1,
2303 .minimum_version_id = 1,
2304 .needed = usbredir_stream_needed,
2305 .fields = (VMStateField[]) {
2306 VMSTATE_UINT32(max_streams, struct endp_data),
2307 VMSTATE_END_OF_LIST()
2311 static const VMStateDescription usbredir_ep_vmstate = {
2312 .name = "usb-redir-ep",
2313 .version_id = 1,
2314 .minimum_version_id = 1,
2315 .fields = (VMStateField[]) {
2316 VMSTATE_UINT8(type, struct endp_data),
2317 VMSTATE_UINT8(interval, struct endp_data),
2318 VMSTATE_UINT8(interface, struct endp_data),
2319 VMSTATE_UINT16(max_packet_size, struct endp_data),
2320 VMSTATE_UINT8(iso_started, struct endp_data),
2321 VMSTATE_UINT8(iso_error, struct endp_data),
2322 VMSTATE_UINT8(interrupt_started, struct endp_data),
2323 VMSTATE_UINT8(interrupt_error, struct endp_data),
2324 VMSTATE_UINT8(bufpq_prefilled, struct endp_data),
2325 VMSTATE_UINT8(bufpq_dropping_packets, struct endp_data),
2327 .name = "bufpq",
2328 .version_id = 0,
2329 .field_exists = NULL,
2330 .size = 0,
2331 .info = &usbredir_ep_bufpq_vmstate_info,
2332 .flags = VMS_SINGLE,
2333 .offset = 0,
2335 VMSTATE_INT32(bufpq_target_size, struct endp_data),
2336 VMSTATE_END_OF_LIST()
2338 .subsections = (const VMStateDescription*[]) {
2339 &usbredir_bulk_receiving_vmstate,
2340 &usbredir_stream_vmstate,
2341 NULL
2346 /* For PacketIdQueue migration */
2347 static void usbredir_put_packet_id_q(QEMUFile *f, void *priv, size_t unused)
2349 struct PacketIdQueue *q = priv;
2350 USBRedirDevice *dev = q->dev;
2351 struct PacketIdQueueEntry *e;
2352 int remain = q->size;
2354 DPRINTF("put_packet_id_q %s size %d\n", q->name, q->size);
2355 qemu_put_be32(f, q->size);
2356 QTAILQ_FOREACH(e, &q->head, next) {
2357 qemu_put_be64(f, e->id);
2358 remain--;
2360 assert(remain == 0);
2363 static int usbredir_get_packet_id_q(QEMUFile *f, void *priv, size_t unused)
2365 struct PacketIdQueue *q = priv;
2366 USBRedirDevice *dev = q->dev;
2367 int i, size;
2368 uint64_t id;
2370 size = qemu_get_be32(f);
2371 DPRINTF("get_packet_id_q %s size %d\n", q->name, size);
2372 for (i = 0; i < size; i++) {
2373 id = qemu_get_be64(f);
2374 packet_id_queue_add(q, id);
2376 assert(q->size == size);
2377 return 0;
2380 static const VMStateInfo usbredir_ep_packet_id_q_vmstate_info = {
2381 .name = "usb-redir-packet-id-q",
2382 .put = usbredir_put_packet_id_q,
2383 .get = usbredir_get_packet_id_q,
2386 static const VMStateDescription usbredir_ep_packet_id_queue_vmstate = {
2387 .name = "usb-redir-packet-id-queue",
2388 .version_id = 1,
2389 .minimum_version_id = 1,
2390 .fields = (VMStateField[]) {
2392 .name = "queue",
2393 .version_id = 0,
2394 .field_exists = NULL,
2395 .size = 0,
2396 .info = &usbredir_ep_packet_id_q_vmstate_info,
2397 .flags = VMS_SINGLE,
2398 .offset = 0,
2400 VMSTATE_END_OF_LIST()
2405 /* For usb_redir_device_connect_header migration */
2406 static const VMStateDescription usbredir_device_info_vmstate = {
2407 .name = "usb-redir-device-info",
2408 .version_id = 1,
2409 .minimum_version_id = 1,
2410 .fields = (VMStateField[]) {
2411 VMSTATE_UINT8(speed, struct usb_redir_device_connect_header),
2412 VMSTATE_UINT8(device_class, struct usb_redir_device_connect_header),
2413 VMSTATE_UINT8(device_subclass, struct usb_redir_device_connect_header),
2414 VMSTATE_UINT8(device_protocol, struct usb_redir_device_connect_header),
2415 VMSTATE_UINT16(vendor_id, struct usb_redir_device_connect_header),
2416 VMSTATE_UINT16(product_id, struct usb_redir_device_connect_header),
2417 VMSTATE_UINT16(device_version_bcd,
2418 struct usb_redir_device_connect_header),
2419 VMSTATE_END_OF_LIST()
2424 /* For usb_redir_interface_info_header migration */
2425 static const VMStateDescription usbredir_interface_info_vmstate = {
2426 .name = "usb-redir-interface-info",
2427 .version_id = 1,
2428 .minimum_version_id = 1,
2429 .fields = (VMStateField[]) {
2430 VMSTATE_UINT32(interface_count,
2431 struct usb_redir_interface_info_header),
2432 VMSTATE_UINT8_ARRAY(interface,
2433 struct usb_redir_interface_info_header, 32),
2434 VMSTATE_UINT8_ARRAY(interface_class,
2435 struct usb_redir_interface_info_header, 32),
2436 VMSTATE_UINT8_ARRAY(interface_subclass,
2437 struct usb_redir_interface_info_header, 32),
2438 VMSTATE_UINT8_ARRAY(interface_protocol,
2439 struct usb_redir_interface_info_header, 32),
2440 VMSTATE_END_OF_LIST()
2445 /* And finally the USBRedirDevice vmstate itself */
2446 static const VMStateDescription usbredir_vmstate = {
2447 .name = "usb-redir",
2448 .version_id = 1,
2449 .minimum_version_id = 1,
2450 .pre_save = usbredir_pre_save,
2451 .post_load = usbredir_post_load,
2452 .fields = (VMStateField[]) {
2453 VMSTATE_USB_DEVICE(dev, USBRedirDevice),
2454 VMSTATE_TIMER_PTR(attach_timer, USBRedirDevice),
2456 .name = "parser",
2457 .version_id = 0,
2458 .field_exists = NULL,
2459 .size = 0,
2460 .info = &usbredir_parser_vmstate_info,
2461 .flags = VMS_SINGLE,
2462 .offset = 0,
2464 VMSTATE_STRUCT_ARRAY(endpoint, USBRedirDevice, MAX_ENDPOINTS, 1,
2465 usbredir_ep_vmstate, struct endp_data),
2466 VMSTATE_STRUCT(cancelled, USBRedirDevice, 1,
2467 usbredir_ep_packet_id_queue_vmstate,
2468 struct PacketIdQueue),
2469 VMSTATE_STRUCT(already_in_flight, USBRedirDevice, 1,
2470 usbredir_ep_packet_id_queue_vmstate,
2471 struct PacketIdQueue),
2472 VMSTATE_STRUCT(device_info, USBRedirDevice, 1,
2473 usbredir_device_info_vmstate,
2474 struct usb_redir_device_connect_header),
2475 VMSTATE_STRUCT(interface_info, USBRedirDevice, 1,
2476 usbredir_interface_info_vmstate,
2477 struct usb_redir_interface_info_header),
2478 VMSTATE_END_OF_LIST()
2482 static Property usbredir_properties[] = {
2483 DEFINE_PROP_CHR("chardev", USBRedirDevice, cs),
2484 DEFINE_PROP_UINT8("debug", USBRedirDevice, debug, usbredirparser_warning),
2485 DEFINE_PROP_STRING("filter", USBRedirDevice, filter_str),
2486 DEFINE_PROP_BOOL("streams", USBRedirDevice, enable_streams, true),
2487 DEFINE_PROP_END_OF_LIST(),
2490 static void usbredir_class_initfn(ObjectClass *klass, void *data)
2492 USBDeviceClass *uc = USB_DEVICE_CLASS(klass);
2493 DeviceClass *dc = DEVICE_CLASS(klass);
2495 uc->realize = usbredir_realize;
2496 uc->product_desc = "USB Redirection Device";
2497 uc->handle_destroy = usbredir_handle_destroy;
2498 uc->cancel_packet = usbredir_cancel_packet;
2499 uc->handle_reset = usbredir_handle_reset;
2500 uc->handle_data = usbredir_handle_data;
2501 uc->handle_control = usbredir_handle_control;
2502 uc->flush_ep_queue = usbredir_flush_ep_queue;
2503 uc->ep_stopped = usbredir_ep_stopped;
2504 uc->alloc_streams = usbredir_alloc_streams;
2505 uc->free_streams = usbredir_free_streams;
2506 dc->vmsd = &usbredir_vmstate;
2507 dc->props = usbredir_properties;
2508 set_bit(DEVICE_CATEGORY_MISC, dc->categories);
2511 static void usbredir_instance_init(Object *obj)
2513 USBDevice *udev = USB_DEVICE(obj);
2514 USBRedirDevice *dev = USB_REDIRECT(udev);
2516 device_add_bootindex_property(obj, &dev->bootindex,
2517 "bootindex", NULL,
2518 &udev->qdev, NULL);
2521 static const TypeInfo usbredir_dev_info = {
2522 .name = TYPE_USB_REDIR,
2523 .parent = TYPE_USB_DEVICE,
2524 .instance_size = sizeof(USBRedirDevice),
2525 .class_init = usbredir_class_initfn,
2526 .instance_init = usbredir_instance_init,
2529 static void usbredir_register_types(void)
2531 type_register_static(&usbredir_dev_info);
2534 type_init(usbredir_register_types)