char: add a /chardevs container
[qemu/ar7.git] / hw / usb / redirect.c
blobb001a27f052b837cc18cf95fb3beff8abc7574e1
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 CharBackend 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;
135 VMChangeStateEntry *vmstate;
138 #define TYPE_USB_REDIR "usb-redir"
139 #define USB_REDIRECT(obj) OBJECT_CHECK(USBRedirDevice, (obj), TYPE_USB_REDIR)
141 static void usbredir_hello(void *priv, struct usb_redir_hello_header *h);
142 static void usbredir_device_connect(void *priv,
143 struct usb_redir_device_connect_header *device_connect);
144 static void usbredir_device_disconnect(void *priv);
145 static void usbredir_interface_info(void *priv,
146 struct usb_redir_interface_info_header *interface_info);
147 static void usbredir_ep_info(void *priv,
148 struct usb_redir_ep_info_header *ep_info);
149 static void usbredir_configuration_status(void *priv, uint64_t id,
150 struct usb_redir_configuration_status_header *configuration_status);
151 static void usbredir_alt_setting_status(void *priv, uint64_t id,
152 struct usb_redir_alt_setting_status_header *alt_setting_status);
153 static void usbredir_iso_stream_status(void *priv, uint64_t id,
154 struct usb_redir_iso_stream_status_header *iso_stream_status);
155 static void usbredir_interrupt_receiving_status(void *priv, uint64_t id,
156 struct usb_redir_interrupt_receiving_status_header
157 *interrupt_receiving_status);
158 static void usbredir_bulk_streams_status(void *priv, uint64_t id,
159 struct usb_redir_bulk_streams_status_header *bulk_streams_status);
160 static void usbredir_bulk_receiving_status(void *priv, uint64_t id,
161 struct usb_redir_bulk_receiving_status_header *bulk_receiving_status);
162 static void usbredir_control_packet(void *priv, uint64_t id,
163 struct usb_redir_control_packet_header *control_packet,
164 uint8_t *data, int data_len);
165 static void usbredir_bulk_packet(void *priv, uint64_t id,
166 struct usb_redir_bulk_packet_header *bulk_packet,
167 uint8_t *data, int data_len);
168 static void usbredir_iso_packet(void *priv, uint64_t id,
169 struct usb_redir_iso_packet_header *iso_packet,
170 uint8_t *data, int data_len);
171 static void usbredir_interrupt_packet(void *priv, uint64_t id,
172 struct usb_redir_interrupt_packet_header *interrupt_header,
173 uint8_t *data, int data_len);
174 static void usbredir_buffered_bulk_packet(void *priv, uint64_t id,
175 struct usb_redir_buffered_bulk_packet_header *buffered_bulk_packet,
176 uint8_t *data, int data_len);
178 static void usbredir_handle_status(USBRedirDevice *dev, USBPacket *p,
179 int status);
181 #define VERSION "qemu usb-redir guest " QEMU_VERSION
184 * Logging stuff
187 #define ERROR(...) \
188 do { \
189 if (dev->debug >= usbredirparser_error) { \
190 error_report("usb-redir error: " __VA_ARGS__); \
192 } while (0)
193 #define WARNING(...) \
194 do { \
195 if (dev->debug >= usbredirparser_warning) { \
196 error_report("usb-redir warning: " __VA_ARGS__); \
198 } while (0)
199 #define INFO(...) \
200 do { \
201 if (dev->debug >= usbredirparser_info) { \
202 error_report("usb-redir: " __VA_ARGS__); \
204 } while (0)
205 #define DPRINTF(...) \
206 do { \
207 if (dev->debug >= usbredirparser_debug) { \
208 error_report("usb-redir: " __VA_ARGS__); \
210 } while (0)
211 #define DPRINTF2(...) \
212 do { \
213 if (dev->debug >= usbredirparser_debug_data) { \
214 error_report("usb-redir: " __VA_ARGS__); \
216 } while (0)
218 static void usbredir_log(void *priv, int level, const char *msg)
220 USBRedirDevice *dev = priv;
222 if (dev->debug < level) {
223 return;
226 error_report("%s", msg);
229 static void usbredir_log_data(USBRedirDevice *dev, const char *desc,
230 const uint8_t *data, int len)
232 int i, j, n;
234 if (dev->debug < usbredirparser_debug_data) {
235 return;
238 for (i = 0; i < len; i += j) {
239 char buf[128];
241 n = sprintf(buf, "%s", desc);
242 for (j = 0; j < 8 && i + j < len; j++) {
243 n += sprintf(buf + n, " %02X", data[i + j]);
245 error_report("%s", buf);
250 * usbredirparser io functions
253 static int usbredir_read(void *priv, uint8_t *data, int count)
255 USBRedirDevice *dev = priv;
257 if (dev->read_buf_size < count) {
258 count = dev->read_buf_size;
261 memcpy(data, dev->read_buf, count);
263 dev->read_buf_size -= count;
264 if (dev->read_buf_size) {
265 dev->read_buf += count;
266 } else {
267 dev->read_buf = NULL;
270 return count;
273 static gboolean usbredir_write_unblocked(GIOChannel *chan, GIOCondition cond,
274 void *opaque)
276 USBRedirDevice *dev = opaque;
278 dev->watch = 0;
279 usbredirparser_do_write(dev->parser);
281 return FALSE;
284 static int usbredir_write(void *priv, uint8_t *data, int count)
286 USBRedirDevice *dev = priv;
287 Chardev *chr = qemu_chr_fe_get_driver(&dev->cs);
288 int r;
290 if (!chr->be_open) {
291 return 0;
294 /* Don't send new data to the chardev until our state is fully synced */
295 if (!runstate_check(RUN_STATE_RUNNING)) {
296 return 0;
299 r = qemu_chr_fe_write(&dev->cs, data, count);
300 if (r < count) {
301 if (!dev->watch) {
302 dev->watch = qemu_chr_fe_add_watch(&dev->cs, G_IO_OUT | G_IO_HUP,
303 usbredir_write_unblocked, dev);
305 if (r < 0) {
306 r = 0;
309 return r;
313 * Cancelled and buffered packets helpers
316 static void packet_id_queue_init(struct PacketIdQueue *q,
317 USBRedirDevice *dev, const char *name)
319 q->dev = dev;
320 q->name = name;
321 QTAILQ_INIT(&q->head);
322 q->size = 0;
325 static void packet_id_queue_add(struct PacketIdQueue *q, uint64_t id)
327 USBRedirDevice *dev = q->dev;
328 struct PacketIdQueueEntry *e;
330 DPRINTF("adding packet id %"PRIu64" to %s queue\n", id, q->name);
332 e = g_new0(struct PacketIdQueueEntry, 1);
333 e->id = id;
334 QTAILQ_INSERT_TAIL(&q->head, e, next);
335 q->size++;
338 static int packet_id_queue_remove(struct PacketIdQueue *q, uint64_t id)
340 USBRedirDevice *dev = q->dev;
341 struct PacketIdQueueEntry *e;
343 QTAILQ_FOREACH(e, &q->head, next) {
344 if (e->id == id) {
345 DPRINTF("removing packet id %"PRIu64" from %s queue\n",
346 id, q->name);
347 QTAILQ_REMOVE(&q->head, e, next);
348 q->size--;
349 g_free(e);
350 return 1;
353 return 0;
356 static void packet_id_queue_empty(struct PacketIdQueue *q)
358 USBRedirDevice *dev = q->dev;
359 struct PacketIdQueueEntry *e, *next_e;
361 DPRINTF("removing %d packet-ids from %s queue\n", q->size, q->name);
363 QTAILQ_FOREACH_SAFE(e, &q->head, next, next_e) {
364 QTAILQ_REMOVE(&q->head, e, next);
365 g_free(e);
367 q->size = 0;
370 static void usbredir_cancel_packet(USBDevice *udev, USBPacket *p)
372 USBRedirDevice *dev = USB_REDIRECT(udev);
373 int i = USBEP2I(p->ep);
375 if (p->combined) {
376 usb_combined_packet_cancel(udev, p);
377 return;
380 if (dev->endpoint[i].pending_async_packet) {
381 assert(dev->endpoint[i].pending_async_packet == p);
382 dev->endpoint[i].pending_async_packet = NULL;
383 return;
386 packet_id_queue_add(&dev->cancelled, p->id);
387 usbredirparser_send_cancel_data_packet(dev->parser, p->id);
388 usbredirparser_do_write(dev->parser);
391 static int usbredir_is_cancelled(USBRedirDevice *dev, uint64_t id)
393 if (!dev->dev.attached) {
394 return 1; /* Treat everything as cancelled after a disconnect */
396 return packet_id_queue_remove(&dev->cancelled, id);
399 static void usbredir_fill_already_in_flight_from_ep(USBRedirDevice *dev,
400 struct USBEndpoint *ep)
402 static USBPacket *p;
404 /* async handled packets for bulk receiving eps do not count as inflight */
405 if (dev->endpoint[USBEP2I(ep)].bulk_receiving_started) {
406 return;
409 QTAILQ_FOREACH(p, &ep->queue, queue) {
410 /* Skip combined packets, except for the first */
411 if (p->combined && p != p->combined->first) {
412 continue;
414 if (p->state == USB_PACKET_ASYNC) {
415 packet_id_queue_add(&dev->already_in_flight, p->id);
420 static void usbredir_fill_already_in_flight(USBRedirDevice *dev)
422 int ep;
423 struct USBDevice *udev = &dev->dev;
425 usbredir_fill_already_in_flight_from_ep(dev, &udev->ep_ctl);
427 for (ep = 0; ep < USB_MAX_ENDPOINTS; ep++) {
428 usbredir_fill_already_in_flight_from_ep(dev, &udev->ep_in[ep]);
429 usbredir_fill_already_in_flight_from_ep(dev, &udev->ep_out[ep]);
433 static int usbredir_already_in_flight(USBRedirDevice *dev, uint64_t id)
435 return packet_id_queue_remove(&dev->already_in_flight, id);
438 static USBPacket *usbredir_find_packet_by_id(USBRedirDevice *dev,
439 uint8_t ep, uint64_t id)
441 USBPacket *p;
443 if (usbredir_is_cancelled(dev, id)) {
444 return NULL;
447 p = usb_ep_find_packet_by_id(&dev->dev,
448 (ep & USB_DIR_IN) ? USB_TOKEN_IN : USB_TOKEN_OUT,
449 ep & 0x0f, id);
450 if (p == NULL) {
451 ERROR("could not find packet with id %"PRIu64"\n", id);
453 return p;
456 static int bufp_alloc(USBRedirDevice *dev, uint8_t *data, uint16_t len,
457 uint8_t status, uint8_t ep, void *free_on_destroy)
459 struct buf_packet *bufp;
461 if (!dev->endpoint[EP2I(ep)].bufpq_dropping_packets &&
462 dev->endpoint[EP2I(ep)].bufpq_size >
463 2 * dev->endpoint[EP2I(ep)].bufpq_target_size) {
464 DPRINTF("bufpq overflow, dropping packets ep %02X\n", ep);
465 dev->endpoint[EP2I(ep)].bufpq_dropping_packets = 1;
467 /* Since we're interupting the stream anyways, drop enough packets to get
468 back to our target buffer size */
469 if (dev->endpoint[EP2I(ep)].bufpq_dropping_packets) {
470 if (dev->endpoint[EP2I(ep)].bufpq_size >
471 dev->endpoint[EP2I(ep)].bufpq_target_size) {
472 free(data);
473 return -1;
475 dev->endpoint[EP2I(ep)].bufpq_dropping_packets = 0;
478 bufp = g_new(struct buf_packet, 1);
479 bufp->data = data;
480 bufp->len = len;
481 bufp->offset = 0;
482 bufp->status = status;
483 bufp->free_on_destroy = free_on_destroy;
484 QTAILQ_INSERT_TAIL(&dev->endpoint[EP2I(ep)].bufpq, bufp, next);
485 dev->endpoint[EP2I(ep)].bufpq_size++;
486 return 0;
489 static void bufp_free(USBRedirDevice *dev, struct buf_packet *bufp,
490 uint8_t ep)
492 QTAILQ_REMOVE(&dev->endpoint[EP2I(ep)].bufpq, bufp, next);
493 dev->endpoint[EP2I(ep)].bufpq_size--;
494 free(bufp->free_on_destroy);
495 g_free(bufp);
498 static void usbredir_free_bufpq(USBRedirDevice *dev, uint8_t ep)
500 struct buf_packet *buf, *buf_next;
502 QTAILQ_FOREACH_SAFE(buf, &dev->endpoint[EP2I(ep)].bufpq, next, buf_next) {
503 bufp_free(dev, buf, ep);
508 * USBDevice callbacks
511 static void usbredir_handle_reset(USBDevice *udev)
513 USBRedirDevice *dev = USB_REDIRECT(udev);
515 DPRINTF("reset device\n");
516 usbredirparser_send_reset(dev->parser);
517 usbredirparser_do_write(dev->parser);
520 static void usbredir_handle_iso_data(USBRedirDevice *dev, USBPacket *p,
521 uint8_t ep)
523 int status, len;
524 if (!dev->endpoint[EP2I(ep)].iso_started &&
525 !dev->endpoint[EP2I(ep)].iso_error) {
526 struct usb_redir_start_iso_stream_header start_iso = {
527 .endpoint = ep,
529 int pkts_per_sec;
531 if (dev->dev.speed == USB_SPEED_HIGH) {
532 pkts_per_sec = 8000 / dev->endpoint[EP2I(ep)].interval;
533 } else {
534 pkts_per_sec = 1000 / dev->endpoint[EP2I(ep)].interval;
536 /* Testing has shown that we need circa 60 ms buffer */
537 dev->endpoint[EP2I(ep)].bufpq_target_size = (pkts_per_sec * 60) / 1000;
539 /* Aim for approx 100 interrupts / second on the client to
540 balance latency and interrupt load */
541 start_iso.pkts_per_urb = pkts_per_sec / 100;
542 if (start_iso.pkts_per_urb < 1) {
543 start_iso.pkts_per_urb = 1;
544 } else if (start_iso.pkts_per_urb > 32) {
545 start_iso.pkts_per_urb = 32;
548 start_iso.no_urbs = DIV_ROUND_UP(
549 dev->endpoint[EP2I(ep)].bufpq_target_size,
550 start_iso.pkts_per_urb);
551 /* Output endpoints pre-fill only 1/2 of the packets, keeping the rest
552 as overflow buffer. Also see the usbredir protocol documentation */
553 if (!(ep & USB_DIR_IN)) {
554 start_iso.no_urbs *= 2;
556 if (start_iso.no_urbs > 16) {
557 start_iso.no_urbs = 16;
560 /* No id, we look at the ep when receiving a status back */
561 usbredirparser_send_start_iso_stream(dev->parser, 0, &start_iso);
562 usbredirparser_do_write(dev->parser);
563 DPRINTF("iso stream started pkts/sec %d pkts/urb %d urbs %d ep %02X\n",
564 pkts_per_sec, start_iso.pkts_per_urb, start_iso.no_urbs, ep);
565 dev->endpoint[EP2I(ep)].iso_started = 1;
566 dev->endpoint[EP2I(ep)].bufpq_prefilled = 0;
567 dev->endpoint[EP2I(ep)].bufpq_dropping_packets = 0;
570 if (ep & USB_DIR_IN) {
571 struct buf_packet *isop;
573 if (dev->endpoint[EP2I(ep)].iso_started &&
574 !dev->endpoint[EP2I(ep)].bufpq_prefilled) {
575 if (dev->endpoint[EP2I(ep)].bufpq_size <
576 dev->endpoint[EP2I(ep)].bufpq_target_size) {
577 return;
579 dev->endpoint[EP2I(ep)].bufpq_prefilled = 1;
582 isop = QTAILQ_FIRST(&dev->endpoint[EP2I(ep)].bufpq);
583 if (isop == NULL) {
584 DPRINTF("iso-token-in ep %02X, no isop, iso_error: %d\n",
585 ep, dev->endpoint[EP2I(ep)].iso_error);
586 /* Re-fill the buffer */
587 dev->endpoint[EP2I(ep)].bufpq_prefilled = 0;
588 /* Check iso_error for stream errors, otherwise its an underrun */
589 status = dev->endpoint[EP2I(ep)].iso_error;
590 dev->endpoint[EP2I(ep)].iso_error = 0;
591 p->status = status ? USB_RET_IOERROR : USB_RET_SUCCESS;
592 return;
594 DPRINTF2("iso-token-in ep %02X status %d len %d queue-size: %d\n", ep,
595 isop->status, isop->len, dev->endpoint[EP2I(ep)].bufpq_size);
597 status = isop->status;
598 len = isop->len;
599 if (len > p->iov.size) {
600 ERROR("received iso data is larger then packet ep %02X (%d > %d)\n",
601 ep, len, (int)p->iov.size);
602 len = p->iov.size;
603 status = usb_redir_babble;
605 usb_packet_copy(p, isop->data, len);
606 bufp_free(dev, isop, ep);
607 usbredir_handle_status(dev, p, status);
608 } else {
609 /* If the stream was not started because of a pending error don't
610 send the packet to the usb-host */
611 if (dev->endpoint[EP2I(ep)].iso_started) {
612 struct usb_redir_iso_packet_header iso_packet = {
613 .endpoint = ep,
614 .length = p->iov.size
616 uint8_t buf[p->iov.size];
617 /* No id, we look at the ep when receiving a status back */
618 usb_packet_copy(p, buf, p->iov.size);
619 usbredirparser_send_iso_packet(dev->parser, 0, &iso_packet,
620 buf, p->iov.size);
621 usbredirparser_do_write(dev->parser);
623 status = dev->endpoint[EP2I(ep)].iso_error;
624 dev->endpoint[EP2I(ep)].iso_error = 0;
625 DPRINTF2("iso-token-out ep %02X status %d len %zd\n", ep, status,
626 p->iov.size);
627 usbredir_handle_status(dev, p, status);
631 static void usbredir_stop_iso_stream(USBRedirDevice *dev, uint8_t ep)
633 struct usb_redir_stop_iso_stream_header stop_iso_stream = {
634 .endpoint = ep
636 if (dev->endpoint[EP2I(ep)].iso_started) {
637 usbredirparser_send_stop_iso_stream(dev->parser, 0, &stop_iso_stream);
638 DPRINTF("iso stream stopped ep %02X\n", ep);
639 dev->endpoint[EP2I(ep)].iso_started = 0;
641 dev->endpoint[EP2I(ep)].iso_error = 0;
642 usbredir_free_bufpq(dev, ep);
646 * The usb-host may poll the endpoint faster then our guest, resulting in lots
647 * of smaller bulkp-s. The below buffered_bulk_in_complete* functions combine
648 * data from multiple bulkp-s into a single packet, avoiding bufpq overflows.
650 static void usbredir_buffered_bulk_add_data_to_packet(USBRedirDevice *dev,
651 struct buf_packet *bulkp, int count, USBPacket *p, uint8_t ep)
653 usb_packet_copy(p, bulkp->data + bulkp->offset, count);
654 bulkp->offset += count;
655 if (bulkp->offset == bulkp->len) {
656 /* Store status in the last packet with data from this bulkp */
657 usbredir_handle_status(dev, p, bulkp->status);
658 bufp_free(dev, bulkp, ep);
662 static void usbredir_buffered_bulk_in_complete_raw(USBRedirDevice *dev,
663 USBPacket *p, uint8_t ep)
665 struct buf_packet *bulkp;
666 int count;
668 while ((bulkp = QTAILQ_FIRST(&dev->endpoint[EP2I(ep)].bufpq)) &&
669 p->actual_length < p->iov.size && p->status == USB_RET_SUCCESS) {
670 count = bulkp->len - bulkp->offset;
671 if (count > (p->iov.size - p->actual_length)) {
672 count = p->iov.size - p->actual_length;
674 usbredir_buffered_bulk_add_data_to_packet(dev, bulkp, count, p, ep);
678 static void usbredir_buffered_bulk_in_complete_ftdi(USBRedirDevice *dev,
679 USBPacket *p, uint8_t ep)
681 const int maxp = dev->endpoint[EP2I(ep)].max_packet_size;
682 uint8_t header[2] = { 0, 0 };
683 struct buf_packet *bulkp;
684 int count;
686 while ((bulkp = QTAILQ_FIRST(&dev->endpoint[EP2I(ep)].bufpq)) &&
687 p->actual_length < p->iov.size && p->status == USB_RET_SUCCESS) {
688 if (bulkp->len < 2) {
689 WARNING("malformed ftdi bulk in packet\n");
690 bufp_free(dev, bulkp, ep);
691 continue;
694 if ((p->actual_length % maxp) == 0) {
695 usb_packet_copy(p, bulkp->data, 2);
696 memcpy(header, bulkp->data, 2);
697 } else {
698 if (bulkp->data[0] != header[0] || bulkp->data[1] != header[1]) {
699 break; /* Different header, add to next packet */
703 if (bulkp->offset == 0) {
704 bulkp->offset = 2; /* Skip header */
706 count = bulkp->len - bulkp->offset;
707 /* Must repeat the header at maxp interval */
708 if (count > (maxp - (p->actual_length % maxp))) {
709 count = maxp - (p->actual_length % maxp);
711 usbredir_buffered_bulk_add_data_to_packet(dev, bulkp, count, p, ep);
715 static void usbredir_buffered_bulk_in_complete(USBRedirDevice *dev,
716 USBPacket *p, uint8_t ep)
718 p->status = USB_RET_SUCCESS; /* Clear previous ASYNC status */
719 dev->buffered_bulk_in_complete(dev, p, ep);
720 DPRINTF("bulk-token-in ep %02X status %d len %d id %"PRIu64"\n",
721 ep, p->status, p->actual_length, p->id);
724 static void usbredir_handle_buffered_bulk_in_data(USBRedirDevice *dev,
725 USBPacket *p, uint8_t ep)
727 /* Input bulk endpoint, buffered packet input */
728 if (!dev->endpoint[EP2I(ep)].bulk_receiving_started) {
729 int bpt;
730 struct usb_redir_start_bulk_receiving_header start = {
731 .endpoint = ep,
732 .stream_id = 0,
733 .no_transfers = 5,
735 /* Round bytes_per_transfer up to a multiple of max_packet_size */
736 bpt = 512 + dev->endpoint[EP2I(ep)].max_packet_size - 1;
737 bpt /= dev->endpoint[EP2I(ep)].max_packet_size;
738 bpt *= dev->endpoint[EP2I(ep)].max_packet_size;
739 start.bytes_per_transfer = bpt;
740 /* No id, we look at the ep when receiving a status back */
741 usbredirparser_send_start_bulk_receiving(dev->parser, 0, &start);
742 usbredirparser_do_write(dev->parser);
743 DPRINTF("bulk receiving started bytes/transfer %u count %d ep %02X\n",
744 start.bytes_per_transfer, start.no_transfers, ep);
745 dev->endpoint[EP2I(ep)].bulk_receiving_started = 1;
746 /* We don't really want to drop bulk packets ever, but
747 having some upper limit to how much we buffer is good. */
748 dev->endpoint[EP2I(ep)].bufpq_target_size = 5000;
749 dev->endpoint[EP2I(ep)].bufpq_dropping_packets = 0;
752 if (QTAILQ_EMPTY(&dev->endpoint[EP2I(ep)].bufpq)) {
753 DPRINTF("bulk-token-in ep %02X, no bulkp\n", ep);
754 assert(dev->endpoint[EP2I(ep)].pending_async_packet == NULL);
755 dev->endpoint[EP2I(ep)].pending_async_packet = p;
756 p->status = USB_RET_ASYNC;
757 return;
759 usbredir_buffered_bulk_in_complete(dev, p, ep);
762 static void usbredir_stop_bulk_receiving(USBRedirDevice *dev, uint8_t ep)
764 struct usb_redir_stop_bulk_receiving_header stop_bulk = {
765 .endpoint = ep,
766 .stream_id = 0,
768 if (dev->endpoint[EP2I(ep)].bulk_receiving_started) {
769 usbredirparser_send_stop_bulk_receiving(dev->parser, 0, &stop_bulk);
770 DPRINTF("bulk receiving stopped ep %02X\n", ep);
771 dev->endpoint[EP2I(ep)].bulk_receiving_started = 0;
773 usbredir_free_bufpq(dev, ep);
776 static void usbredir_handle_bulk_data(USBRedirDevice *dev, USBPacket *p,
777 uint8_t ep)
779 struct usb_redir_bulk_packet_header bulk_packet;
780 size_t size = usb_packet_size(p);
781 const int maxp = dev->endpoint[EP2I(ep)].max_packet_size;
783 if (usbredir_already_in_flight(dev, p->id)) {
784 p->status = USB_RET_ASYNC;
785 return;
788 if (dev->endpoint[EP2I(ep)].bulk_receiving_enabled) {
789 if (size != 0 && (size % maxp) == 0) {
790 usbredir_handle_buffered_bulk_in_data(dev, p, ep);
791 return;
793 WARNING("bulk recv invalid size %zd ep %02x, disabling\n", size, ep);
794 assert(dev->endpoint[EP2I(ep)].pending_async_packet == NULL);
795 usbredir_stop_bulk_receiving(dev, ep);
796 dev->endpoint[EP2I(ep)].bulk_receiving_enabled = 0;
799 DPRINTF("bulk-out ep %02X stream %u len %zd id %"PRIu64"\n",
800 ep, p->stream, size, p->id);
802 bulk_packet.endpoint = ep;
803 bulk_packet.length = size;
804 bulk_packet.stream_id = p->stream;
805 bulk_packet.length_high = size >> 16;
806 assert(bulk_packet.length_high == 0 ||
807 usbredirparser_peer_has_cap(dev->parser,
808 usb_redir_cap_32bits_bulk_length));
810 if (ep & USB_DIR_IN) {
811 usbredirparser_send_bulk_packet(dev->parser, p->id,
812 &bulk_packet, NULL, 0);
813 } else {
814 uint8_t buf[size];
815 usb_packet_copy(p, buf, size);
816 usbredir_log_data(dev, "bulk data out:", buf, size);
817 usbredirparser_send_bulk_packet(dev->parser, p->id,
818 &bulk_packet, buf, size);
820 usbredirparser_do_write(dev->parser);
821 p->status = USB_RET_ASYNC;
824 static void usbredir_handle_interrupt_in_data(USBRedirDevice *dev,
825 USBPacket *p, uint8_t ep)
827 /* Input interrupt endpoint, buffered packet input */
828 struct buf_packet *intp;
829 int status, len;
831 if (!dev->endpoint[EP2I(ep)].interrupt_started &&
832 !dev->endpoint[EP2I(ep)].interrupt_error) {
833 struct usb_redir_start_interrupt_receiving_header start_int = {
834 .endpoint = ep,
836 /* No id, we look at the ep when receiving a status back */
837 usbredirparser_send_start_interrupt_receiving(dev->parser, 0,
838 &start_int);
839 usbredirparser_do_write(dev->parser);
840 DPRINTF("interrupt recv started ep %02X\n", ep);
841 dev->endpoint[EP2I(ep)].interrupt_started = 1;
842 /* We don't really want to drop interrupt packets ever, but
843 having some upper limit to how much we buffer is good. */
844 dev->endpoint[EP2I(ep)].bufpq_target_size = 1000;
845 dev->endpoint[EP2I(ep)].bufpq_dropping_packets = 0;
848 intp = QTAILQ_FIRST(&dev->endpoint[EP2I(ep)].bufpq);
849 if (intp == NULL) {
850 DPRINTF2("interrupt-token-in ep %02X, no intp\n", ep);
851 /* Check interrupt_error for stream errors */
852 status = dev->endpoint[EP2I(ep)].interrupt_error;
853 dev->endpoint[EP2I(ep)].interrupt_error = 0;
854 if (status) {
855 usbredir_handle_status(dev, p, status);
856 } else {
857 p->status = USB_RET_NAK;
859 return;
861 DPRINTF("interrupt-token-in ep %02X status %d len %d\n", ep,
862 intp->status, intp->len);
864 status = intp->status;
865 len = intp->len;
866 if (len > p->iov.size) {
867 ERROR("received int data is larger then packet ep %02X\n", ep);
868 len = p->iov.size;
869 status = usb_redir_babble;
871 usb_packet_copy(p, intp->data, len);
872 bufp_free(dev, intp, ep);
873 usbredir_handle_status(dev, p, status);
877 * Handle interrupt out data, the usbredir protocol expects us to do this
878 * async, so that it can report back a completion status. But guests will
879 * expect immediate completion for an interrupt endpoint, and handling this
880 * async causes migration issues. So we report success directly, counting
881 * on the fact that output interrupt packets normally always succeed.
883 static void usbredir_handle_interrupt_out_data(USBRedirDevice *dev,
884 USBPacket *p, uint8_t ep)
886 struct usb_redir_interrupt_packet_header interrupt_packet;
887 uint8_t buf[p->iov.size];
889 DPRINTF("interrupt-out ep %02X len %zd id %"PRIu64"\n", ep,
890 p->iov.size, p->id);
892 interrupt_packet.endpoint = ep;
893 interrupt_packet.length = p->iov.size;
895 usb_packet_copy(p, buf, p->iov.size);
896 usbredir_log_data(dev, "interrupt data out:", buf, p->iov.size);
897 usbredirparser_send_interrupt_packet(dev->parser, p->id,
898 &interrupt_packet, buf, p->iov.size);
899 usbredirparser_do_write(dev->parser);
902 static void usbredir_stop_interrupt_receiving(USBRedirDevice *dev,
903 uint8_t ep)
905 struct usb_redir_stop_interrupt_receiving_header stop_interrupt_recv = {
906 .endpoint = ep
908 if (dev->endpoint[EP2I(ep)].interrupt_started) {
909 usbredirparser_send_stop_interrupt_receiving(dev->parser, 0,
910 &stop_interrupt_recv);
911 DPRINTF("interrupt recv stopped ep %02X\n", ep);
912 dev->endpoint[EP2I(ep)].interrupt_started = 0;
914 dev->endpoint[EP2I(ep)].interrupt_error = 0;
915 usbredir_free_bufpq(dev, ep);
918 static void usbredir_handle_data(USBDevice *udev, USBPacket *p)
920 USBRedirDevice *dev = USB_REDIRECT(udev);
921 uint8_t ep;
923 ep = p->ep->nr;
924 if (p->pid == USB_TOKEN_IN) {
925 ep |= USB_DIR_IN;
928 switch (dev->endpoint[EP2I(ep)].type) {
929 case USB_ENDPOINT_XFER_CONTROL:
930 ERROR("handle_data called for control transfer on ep %02X\n", ep);
931 p->status = USB_RET_NAK;
932 break;
933 case USB_ENDPOINT_XFER_BULK:
934 if (p->state == USB_PACKET_SETUP && p->pid == USB_TOKEN_IN &&
935 p->ep->pipeline) {
936 p->status = USB_RET_ADD_TO_QUEUE;
937 break;
939 usbredir_handle_bulk_data(dev, p, ep);
940 break;
941 case USB_ENDPOINT_XFER_ISOC:
942 usbredir_handle_iso_data(dev, p, ep);
943 break;
944 case USB_ENDPOINT_XFER_INT:
945 if (ep & USB_DIR_IN) {
946 usbredir_handle_interrupt_in_data(dev, p, ep);
947 } else {
948 usbredir_handle_interrupt_out_data(dev, p, ep);
950 break;
951 default:
952 ERROR("handle_data ep %02X has unknown type %d\n", ep,
953 dev->endpoint[EP2I(ep)].type);
954 p->status = USB_RET_NAK;
958 static void usbredir_flush_ep_queue(USBDevice *dev, USBEndpoint *ep)
960 if (ep->pid == USB_TOKEN_IN && ep->pipeline) {
961 usb_ep_combine_input_packets(ep);
965 static void usbredir_stop_ep(USBRedirDevice *dev, int i)
967 uint8_t ep = I2EP(i);
969 switch (dev->endpoint[i].type) {
970 case USB_ENDPOINT_XFER_BULK:
971 if (ep & USB_DIR_IN) {
972 usbredir_stop_bulk_receiving(dev, ep);
974 break;
975 case USB_ENDPOINT_XFER_ISOC:
976 usbredir_stop_iso_stream(dev, ep);
977 break;
978 case USB_ENDPOINT_XFER_INT:
979 if (ep & USB_DIR_IN) {
980 usbredir_stop_interrupt_receiving(dev, ep);
982 break;
984 usbredir_free_bufpq(dev, ep);
987 static void usbredir_ep_stopped(USBDevice *udev, USBEndpoint *uep)
989 USBRedirDevice *dev = USB_REDIRECT(udev);
991 usbredir_stop_ep(dev, USBEP2I(uep));
992 usbredirparser_do_write(dev->parser);
995 static void usbredir_set_config(USBRedirDevice *dev, USBPacket *p,
996 int config)
998 struct usb_redir_set_configuration_header set_config;
999 int i;
1001 DPRINTF("set config %d id %"PRIu64"\n", config, p->id);
1003 for (i = 0; i < MAX_ENDPOINTS; i++) {
1004 usbredir_stop_ep(dev, i);
1007 set_config.configuration = config;
1008 usbredirparser_send_set_configuration(dev->parser, p->id, &set_config);
1009 usbredirparser_do_write(dev->parser);
1010 p->status = USB_RET_ASYNC;
1013 static void usbredir_get_config(USBRedirDevice *dev, USBPacket *p)
1015 DPRINTF("get config id %"PRIu64"\n", p->id);
1017 usbredirparser_send_get_configuration(dev->parser, p->id);
1018 usbredirparser_do_write(dev->parser);
1019 p->status = USB_RET_ASYNC;
1022 static void usbredir_set_interface(USBRedirDevice *dev, USBPacket *p,
1023 int interface, int alt)
1025 struct usb_redir_set_alt_setting_header set_alt;
1026 int i;
1028 DPRINTF("set interface %d alt %d id %"PRIu64"\n", interface, alt, p->id);
1030 for (i = 0; i < MAX_ENDPOINTS; i++) {
1031 if (dev->endpoint[i].interface == interface) {
1032 usbredir_stop_ep(dev, i);
1036 set_alt.interface = interface;
1037 set_alt.alt = alt;
1038 usbredirparser_send_set_alt_setting(dev->parser, p->id, &set_alt);
1039 usbredirparser_do_write(dev->parser);
1040 p->status = USB_RET_ASYNC;
1043 static void usbredir_get_interface(USBRedirDevice *dev, USBPacket *p,
1044 int interface)
1046 struct usb_redir_get_alt_setting_header get_alt;
1048 DPRINTF("get interface %d id %"PRIu64"\n", interface, p->id);
1050 get_alt.interface = interface;
1051 usbredirparser_send_get_alt_setting(dev->parser, p->id, &get_alt);
1052 usbredirparser_do_write(dev->parser);
1053 p->status = USB_RET_ASYNC;
1056 static void usbredir_handle_control(USBDevice *udev, USBPacket *p,
1057 int request, int value, int index, int length, uint8_t *data)
1059 USBRedirDevice *dev = USB_REDIRECT(udev);
1060 struct usb_redir_control_packet_header control_packet;
1062 if (usbredir_already_in_flight(dev, p->id)) {
1063 p->status = USB_RET_ASYNC;
1064 return;
1067 /* Special cases for certain standard device requests */
1068 switch (request) {
1069 case DeviceOutRequest | USB_REQ_SET_ADDRESS:
1070 DPRINTF("set address %d\n", value);
1071 dev->dev.addr = value;
1072 return;
1073 case DeviceOutRequest | USB_REQ_SET_CONFIGURATION:
1074 usbredir_set_config(dev, p, value & 0xff);
1075 return;
1076 case DeviceRequest | USB_REQ_GET_CONFIGURATION:
1077 usbredir_get_config(dev, p);
1078 return;
1079 case InterfaceOutRequest | USB_REQ_SET_INTERFACE:
1080 usbredir_set_interface(dev, p, index, value);
1081 return;
1082 case InterfaceRequest | USB_REQ_GET_INTERFACE:
1083 usbredir_get_interface(dev, p, index);
1084 return;
1087 /* Normal ctrl requests, note request is (bRequestType << 8) | bRequest */
1088 DPRINTF(
1089 "ctrl-out type 0x%x req 0x%x val 0x%x index %d len %d id %"PRIu64"\n",
1090 request >> 8, request & 0xff, value, index, length, p->id);
1092 control_packet.request = request & 0xFF;
1093 control_packet.requesttype = request >> 8;
1094 control_packet.endpoint = control_packet.requesttype & USB_DIR_IN;
1095 control_packet.value = value;
1096 control_packet.index = index;
1097 control_packet.length = length;
1099 if (control_packet.requesttype & USB_DIR_IN) {
1100 usbredirparser_send_control_packet(dev->parser, p->id,
1101 &control_packet, NULL, 0);
1102 } else {
1103 usbredir_log_data(dev, "ctrl data out:", data, length);
1104 usbredirparser_send_control_packet(dev->parser, p->id,
1105 &control_packet, data, length);
1107 usbredirparser_do_write(dev->parser);
1108 p->status = USB_RET_ASYNC;
1111 static int usbredir_alloc_streams(USBDevice *udev, USBEndpoint **eps,
1112 int nr_eps, int streams)
1114 USBRedirDevice *dev = USB_REDIRECT(udev);
1115 #if USBREDIR_VERSION >= 0x000700
1116 struct usb_redir_alloc_bulk_streams_header alloc_streams;
1117 int i;
1119 if (!usbredirparser_peer_has_cap(dev->parser,
1120 usb_redir_cap_bulk_streams)) {
1121 ERROR("peer does not support streams\n");
1122 goto reject;
1125 if (streams == 0) {
1126 ERROR("request to allocate 0 streams\n");
1127 return -1;
1130 alloc_streams.no_streams = streams;
1131 alloc_streams.endpoints = 0;
1132 for (i = 0; i < nr_eps; i++) {
1133 alloc_streams.endpoints |= 1 << USBEP2I(eps[i]);
1135 usbredirparser_send_alloc_bulk_streams(dev->parser, 0, &alloc_streams);
1136 usbredirparser_do_write(dev->parser);
1138 return 0;
1139 #else
1140 ERROR("usbredir_alloc_streams not implemented\n");
1141 goto reject;
1142 #endif
1143 reject:
1144 ERROR("streams are not available, disconnecting\n");
1145 qemu_bh_schedule(dev->device_reject_bh);
1146 return -1;
1149 static void usbredir_free_streams(USBDevice *udev, USBEndpoint **eps,
1150 int nr_eps)
1152 #if USBREDIR_VERSION >= 0x000700
1153 USBRedirDevice *dev = USB_REDIRECT(udev);
1154 struct usb_redir_free_bulk_streams_header free_streams;
1155 int i;
1157 if (!usbredirparser_peer_has_cap(dev->parser,
1158 usb_redir_cap_bulk_streams)) {
1159 return;
1162 free_streams.endpoints = 0;
1163 for (i = 0; i < nr_eps; i++) {
1164 free_streams.endpoints |= 1 << USBEP2I(eps[i]);
1166 usbredirparser_send_free_bulk_streams(dev->parser, 0, &free_streams);
1167 usbredirparser_do_write(dev->parser);
1168 #endif
1172 * Close events can be triggered by usbredirparser_do_write which gets called
1173 * from within the USBDevice data / control packet callbacks and doing a
1174 * usb_detach from within these callbacks is not a good idea.
1176 * So we use a bh handler to take care of close events.
1178 static void usbredir_chardev_close_bh(void *opaque)
1180 USBRedirDevice *dev = opaque;
1182 qemu_bh_cancel(dev->device_reject_bh);
1183 usbredir_device_disconnect(dev);
1185 if (dev->parser) {
1186 DPRINTF("destroying usbredirparser\n");
1187 usbredirparser_destroy(dev->parser);
1188 dev->parser = NULL;
1190 if (dev->watch) {
1191 g_source_remove(dev->watch);
1192 dev->watch = 0;
1196 static void usbredir_create_parser(USBRedirDevice *dev)
1198 uint32_t caps[USB_REDIR_CAPS_SIZE] = { 0, };
1199 int flags = 0;
1201 DPRINTF("creating usbredirparser\n");
1203 dev->parser = qemu_oom_check(usbredirparser_create());
1204 dev->parser->priv = dev;
1205 dev->parser->log_func = usbredir_log;
1206 dev->parser->read_func = usbredir_read;
1207 dev->parser->write_func = usbredir_write;
1208 dev->parser->hello_func = usbredir_hello;
1209 dev->parser->device_connect_func = usbredir_device_connect;
1210 dev->parser->device_disconnect_func = usbredir_device_disconnect;
1211 dev->parser->interface_info_func = usbredir_interface_info;
1212 dev->parser->ep_info_func = usbredir_ep_info;
1213 dev->parser->configuration_status_func = usbredir_configuration_status;
1214 dev->parser->alt_setting_status_func = usbredir_alt_setting_status;
1215 dev->parser->iso_stream_status_func = usbredir_iso_stream_status;
1216 dev->parser->interrupt_receiving_status_func =
1217 usbredir_interrupt_receiving_status;
1218 dev->parser->bulk_streams_status_func = usbredir_bulk_streams_status;
1219 dev->parser->bulk_receiving_status_func = usbredir_bulk_receiving_status;
1220 dev->parser->control_packet_func = usbredir_control_packet;
1221 dev->parser->bulk_packet_func = usbredir_bulk_packet;
1222 dev->parser->iso_packet_func = usbredir_iso_packet;
1223 dev->parser->interrupt_packet_func = usbredir_interrupt_packet;
1224 dev->parser->buffered_bulk_packet_func = usbredir_buffered_bulk_packet;
1225 dev->read_buf = NULL;
1226 dev->read_buf_size = 0;
1228 usbredirparser_caps_set_cap(caps, usb_redir_cap_connect_device_version);
1229 usbredirparser_caps_set_cap(caps, usb_redir_cap_filter);
1230 usbredirparser_caps_set_cap(caps, usb_redir_cap_ep_info_max_packet_size);
1231 usbredirparser_caps_set_cap(caps, usb_redir_cap_64bits_ids);
1232 usbredirparser_caps_set_cap(caps, usb_redir_cap_32bits_bulk_length);
1233 usbredirparser_caps_set_cap(caps, usb_redir_cap_bulk_receiving);
1234 #if USBREDIR_VERSION >= 0x000700
1235 if (dev->enable_streams) {
1236 usbredirparser_caps_set_cap(caps, usb_redir_cap_bulk_streams);
1238 #endif
1240 if (runstate_check(RUN_STATE_INMIGRATE)) {
1241 flags |= usbredirparser_fl_no_hello;
1243 usbredirparser_init(dev->parser, VERSION, caps, USB_REDIR_CAPS_SIZE,
1244 flags);
1245 usbredirparser_do_write(dev->parser);
1248 static void usbredir_reject_device(USBRedirDevice *dev)
1250 usbredir_device_disconnect(dev);
1251 if (usbredirparser_peer_has_cap(dev->parser, usb_redir_cap_filter)) {
1252 usbredirparser_send_filter_reject(dev->parser);
1253 usbredirparser_do_write(dev->parser);
1258 * We may need to reject the device when the hcd calls alloc_streams, doing
1259 * an usb_detach from within a hcd call is not a good idea, hence this bh.
1261 static void usbredir_device_reject_bh(void *opaque)
1263 USBRedirDevice *dev = opaque;
1265 usbredir_reject_device(dev);
1268 static void usbredir_do_attach(void *opaque)
1270 USBRedirDevice *dev = opaque;
1271 Error *local_err = NULL;
1273 /* In order to work properly with XHCI controllers we need these caps */
1274 if ((dev->dev.port->speedmask & USB_SPEED_MASK_SUPER) && !(
1275 usbredirparser_peer_has_cap(dev->parser,
1276 usb_redir_cap_ep_info_max_packet_size) &&
1277 usbredirparser_peer_has_cap(dev->parser,
1278 usb_redir_cap_32bits_bulk_length) &&
1279 usbredirparser_peer_has_cap(dev->parser,
1280 usb_redir_cap_64bits_ids))) {
1281 ERROR("usb-redir-host lacks capabilities needed for use with XHCI\n");
1282 usbredir_reject_device(dev);
1283 return;
1286 usb_device_attach(&dev->dev, &local_err);
1287 if (local_err) {
1288 error_report_err(local_err);
1289 WARNING("rejecting device due to speed mismatch\n");
1290 usbredir_reject_device(dev);
1295 * chardev callbacks
1298 static int usbredir_chardev_can_read(void *opaque)
1300 USBRedirDevice *dev = opaque;
1302 if (!dev->parser) {
1303 WARNING("chardev_can_read called on non open chardev!\n");
1304 return 0;
1307 /* Don't read new data from the chardev until our state is fully synced */
1308 if (!runstate_check(RUN_STATE_RUNNING)) {
1309 return 0;
1312 /* usbredir_parser_do_read will consume *all* data we give it */
1313 return 1024 * 1024;
1316 static void usbredir_chardev_read(void *opaque, const uint8_t *buf, int size)
1318 USBRedirDevice *dev = opaque;
1320 /* No recursion allowed! */
1321 assert(dev->read_buf == NULL);
1323 dev->read_buf = buf;
1324 dev->read_buf_size = size;
1326 usbredirparser_do_read(dev->parser);
1327 /* Send any acks, etc. which may be queued now */
1328 usbredirparser_do_write(dev->parser);
1331 static void usbredir_chardev_event(void *opaque, int event)
1333 USBRedirDevice *dev = opaque;
1335 switch (event) {
1336 case CHR_EVENT_OPENED:
1337 DPRINTF("chardev open\n");
1338 /* Make sure any pending closes are handled (no-op if none pending) */
1339 usbredir_chardev_close_bh(dev);
1340 qemu_bh_cancel(dev->chardev_close_bh);
1341 usbredir_create_parser(dev);
1342 break;
1343 case CHR_EVENT_CLOSED:
1344 DPRINTF("chardev close\n");
1345 qemu_bh_schedule(dev->chardev_close_bh);
1346 break;
1351 * init + destroy
1354 static void usbredir_vm_state_change(void *priv, int running, RunState state)
1356 USBRedirDevice *dev = priv;
1358 if (state == RUN_STATE_RUNNING && dev->parser != NULL) {
1359 usbredirparser_do_write(dev->parser); /* Flush any pending writes */
1363 static void usbredir_init_endpoints(USBRedirDevice *dev)
1365 int i;
1367 usb_ep_init(&dev->dev);
1368 memset(dev->endpoint, 0, sizeof(dev->endpoint));
1369 for (i = 0; i < MAX_ENDPOINTS; i++) {
1370 dev->endpoint[i].dev = dev;
1371 QTAILQ_INIT(&dev->endpoint[i].bufpq);
1375 static void usbredir_realize(USBDevice *udev, Error **errp)
1377 USBRedirDevice *dev = USB_REDIRECT(udev);
1378 int i;
1380 if (!qemu_chr_fe_get_driver(&dev->cs)) {
1381 error_setg(errp, QERR_MISSING_PARAMETER, "chardev");
1382 return;
1385 if (dev->filter_str) {
1386 i = usbredirfilter_string_to_rules(dev->filter_str, ":", "|",
1387 &dev->filter_rules,
1388 &dev->filter_rules_count);
1389 if (i) {
1390 error_setg(errp, QERR_INVALID_PARAMETER_VALUE, "filter",
1391 "a usb device filter string");
1392 return;
1396 dev->chardev_close_bh = qemu_bh_new(usbredir_chardev_close_bh, dev);
1397 dev->device_reject_bh = qemu_bh_new(usbredir_device_reject_bh, dev);
1398 dev->attach_timer = timer_new_ms(QEMU_CLOCK_VIRTUAL, usbredir_do_attach, dev);
1400 packet_id_queue_init(&dev->cancelled, dev, "cancelled");
1401 packet_id_queue_init(&dev->already_in_flight, dev, "already-in-flight");
1402 usbredir_init_endpoints(dev);
1404 /* We'll do the attach once we receive the speed from the usb-host */
1405 udev->auto_attach = 0;
1407 /* Will be cleared during setup when we find conflicts */
1408 dev->compatible_speedmask = USB_SPEED_MASK_FULL | USB_SPEED_MASK_HIGH;
1410 /* Let the backend know we are ready */
1411 qemu_chr_fe_set_handlers(&dev->cs, usbredir_chardev_can_read,
1412 usbredir_chardev_read, usbredir_chardev_event,
1413 dev, NULL, true);
1415 dev->vmstate =
1416 qemu_add_vm_change_state_handler(usbredir_vm_state_change, dev);
1419 static void usbredir_cleanup_device_queues(USBRedirDevice *dev)
1421 int i;
1423 packet_id_queue_empty(&dev->cancelled);
1424 packet_id_queue_empty(&dev->already_in_flight);
1425 for (i = 0; i < MAX_ENDPOINTS; i++) {
1426 usbredir_free_bufpq(dev, I2EP(i));
1430 static void usbredir_unrealize(USBDevice *udev, Error **errp)
1432 USBRedirDevice *dev = USB_REDIRECT(udev);
1433 Chardev *chr = qemu_chr_fe_get_driver(&dev->cs);
1435 qemu_chr_fe_deinit(&dev->cs);
1436 object_unparent(OBJECT(chr));
1438 /* Note must be done after qemu_chr_close, as that causes a close event */
1439 qemu_bh_delete(dev->chardev_close_bh);
1440 qemu_bh_delete(dev->device_reject_bh);
1442 timer_del(dev->attach_timer);
1443 timer_free(dev->attach_timer);
1445 usbredir_cleanup_device_queues(dev);
1447 if (dev->parser) {
1448 usbredirparser_destroy(dev->parser);
1450 if (dev->watch) {
1451 g_source_remove(dev->watch);
1454 free(dev->filter_rules);
1455 qemu_del_vm_change_state_handler(dev->vmstate);
1458 static int usbredir_check_filter(USBRedirDevice *dev)
1460 if (dev->interface_info.interface_count == NO_INTERFACE_INFO) {
1461 ERROR("No interface info for device\n");
1462 goto error;
1465 if (dev->filter_rules) {
1466 if (!usbredirparser_peer_has_cap(dev->parser,
1467 usb_redir_cap_connect_device_version)) {
1468 ERROR("Device filter specified and peer does not have the "
1469 "connect_device_version capability\n");
1470 goto error;
1473 if (usbredirfilter_check(
1474 dev->filter_rules,
1475 dev->filter_rules_count,
1476 dev->device_info.device_class,
1477 dev->device_info.device_subclass,
1478 dev->device_info.device_protocol,
1479 dev->interface_info.interface_class,
1480 dev->interface_info.interface_subclass,
1481 dev->interface_info.interface_protocol,
1482 dev->interface_info.interface_count,
1483 dev->device_info.vendor_id,
1484 dev->device_info.product_id,
1485 dev->device_info.device_version_bcd,
1486 0) != 0) {
1487 goto error;
1491 return 0;
1493 error:
1494 usbredir_reject_device(dev);
1495 return -1;
1498 static void usbredir_check_bulk_receiving(USBRedirDevice *dev)
1500 int i, j, quirks;
1502 if (!usbredirparser_peer_has_cap(dev->parser,
1503 usb_redir_cap_bulk_receiving)) {
1504 return;
1507 for (i = EP2I(USB_DIR_IN); i < MAX_ENDPOINTS; i++) {
1508 dev->endpoint[i].bulk_receiving_enabled = 0;
1510 for (i = 0; i < dev->interface_info.interface_count; i++) {
1511 quirks = usb_get_quirks(dev->device_info.vendor_id,
1512 dev->device_info.product_id,
1513 dev->interface_info.interface_class[i],
1514 dev->interface_info.interface_subclass[i],
1515 dev->interface_info.interface_protocol[i]);
1516 if (!(quirks & USB_QUIRK_BUFFER_BULK_IN)) {
1517 continue;
1519 if (quirks & USB_QUIRK_IS_FTDI) {
1520 dev->buffered_bulk_in_complete =
1521 usbredir_buffered_bulk_in_complete_ftdi;
1522 } else {
1523 dev->buffered_bulk_in_complete =
1524 usbredir_buffered_bulk_in_complete_raw;
1527 for (j = EP2I(USB_DIR_IN); j < MAX_ENDPOINTS; j++) {
1528 if (dev->endpoint[j].interface ==
1529 dev->interface_info.interface[i] &&
1530 dev->endpoint[j].type == USB_ENDPOINT_XFER_BULK &&
1531 dev->endpoint[j].max_packet_size != 0) {
1532 dev->endpoint[j].bulk_receiving_enabled = 1;
1534 * With buffering pipelining is not necessary. Also packet
1535 * combining and bulk in buffering don't play nice together!
1537 I2USBEP(dev, j)->pipeline = false;
1538 break; /* Only buffer for the first ep of each intf */
1545 * usbredirparser packet complete callbacks
1548 static void usbredir_handle_status(USBRedirDevice *dev, USBPacket *p,
1549 int status)
1551 switch (status) {
1552 case usb_redir_success:
1553 p->status = USB_RET_SUCCESS; /* Clear previous ASYNC status */
1554 break;
1555 case usb_redir_stall:
1556 p->status = USB_RET_STALL;
1557 break;
1558 case usb_redir_cancelled:
1560 * When the usbredir-host unredirects a device, it will report a status
1561 * of cancelled for all pending packets, followed by a disconnect msg.
1563 p->status = USB_RET_IOERROR;
1564 break;
1565 case usb_redir_inval:
1566 WARNING("got invalid param error from usb-host?\n");
1567 p->status = USB_RET_IOERROR;
1568 break;
1569 case usb_redir_babble:
1570 p->status = USB_RET_BABBLE;
1571 break;
1572 case usb_redir_ioerror:
1573 case usb_redir_timeout:
1574 default:
1575 p->status = USB_RET_IOERROR;
1579 static void usbredir_hello(void *priv, struct usb_redir_hello_header *h)
1581 USBRedirDevice *dev = priv;
1583 /* Try to send the filter info now that we've the usb-host's caps */
1584 if (usbredirparser_peer_has_cap(dev->parser, usb_redir_cap_filter) &&
1585 dev->filter_rules) {
1586 usbredirparser_send_filter_filter(dev->parser, dev->filter_rules,
1587 dev->filter_rules_count);
1588 usbredirparser_do_write(dev->parser);
1592 static void usbredir_device_connect(void *priv,
1593 struct usb_redir_device_connect_header *device_connect)
1595 USBRedirDevice *dev = priv;
1596 const char *speed;
1598 if (timer_pending(dev->attach_timer) || dev->dev.attached) {
1599 ERROR("Received device connect while already connected\n");
1600 return;
1603 switch (device_connect->speed) {
1604 case usb_redir_speed_low:
1605 speed = "low speed";
1606 dev->dev.speed = USB_SPEED_LOW;
1607 dev->compatible_speedmask &= ~USB_SPEED_MASK_FULL;
1608 dev->compatible_speedmask &= ~USB_SPEED_MASK_HIGH;
1609 break;
1610 case usb_redir_speed_full:
1611 speed = "full speed";
1612 dev->dev.speed = USB_SPEED_FULL;
1613 dev->compatible_speedmask &= ~USB_SPEED_MASK_HIGH;
1614 break;
1615 case usb_redir_speed_high:
1616 speed = "high speed";
1617 dev->dev.speed = USB_SPEED_HIGH;
1618 break;
1619 case usb_redir_speed_super:
1620 speed = "super speed";
1621 dev->dev.speed = USB_SPEED_SUPER;
1622 break;
1623 default:
1624 speed = "unknown speed";
1625 dev->dev.speed = USB_SPEED_FULL;
1628 if (usbredirparser_peer_has_cap(dev->parser,
1629 usb_redir_cap_connect_device_version)) {
1630 INFO("attaching %s device %04x:%04x version %d.%d class %02x\n",
1631 speed, device_connect->vendor_id, device_connect->product_id,
1632 ((device_connect->device_version_bcd & 0xf000) >> 12) * 10 +
1633 ((device_connect->device_version_bcd & 0x0f00) >> 8),
1634 ((device_connect->device_version_bcd & 0x00f0) >> 4) * 10 +
1635 ((device_connect->device_version_bcd & 0x000f) >> 0),
1636 device_connect->device_class);
1637 } else {
1638 INFO("attaching %s device %04x:%04x class %02x\n", speed,
1639 device_connect->vendor_id, device_connect->product_id,
1640 device_connect->device_class);
1643 dev->dev.speedmask = (1 << dev->dev.speed) | dev->compatible_speedmask;
1644 dev->device_info = *device_connect;
1646 if (usbredir_check_filter(dev)) {
1647 WARNING("Device %04x:%04x rejected by device filter, not attaching\n",
1648 device_connect->vendor_id, device_connect->product_id);
1649 return;
1652 usbredir_check_bulk_receiving(dev);
1653 timer_mod(dev->attach_timer, dev->next_attach_time);
1656 static void usbredir_device_disconnect(void *priv)
1658 USBRedirDevice *dev = priv;
1660 /* Stop any pending attaches */
1661 timer_del(dev->attach_timer);
1663 if (dev->dev.attached) {
1664 DPRINTF("detaching device\n");
1665 usb_device_detach(&dev->dev);
1667 * Delay next usb device attach to give the guest a chance to see
1668 * see the detach / attach in case of quick close / open succession
1670 dev->next_attach_time = qemu_clock_get_ms(QEMU_CLOCK_VIRTUAL) + 200;
1673 /* Reset state so that the next dev connected starts with a clean slate */
1674 usbredir_cleanup_device_queues(dev);
1675 usbredir_init_endpoints(dev);
1676 dev->interface_info.interface_count = NO_INTERFACE_INFO;
1677 dev->dev.addr = 0;
1678 dev->dev.speed = 0;
1679 dev->compatible_speedmask = USB_SPEED_MASK_FULL | USB_SPEED_MASK_HIGH;
1682 static void usbredir_interface_info(void *priv,
1683 struct usb_redir_interface_info_header *interface_info)
1685 USBRedirDevice *dev = priv;
1687 dev->interface_info = *interface_info;
1690 * If we receive interface info after the device has already been
1691 * connected (ie on a set_config), re-check interface dependent things.
1693 if (timer_pending(dev->attach_timer) || dev->dev.attached) {
1694 usbredir_check_bulk_receiving(dev);
1695 if (usbredir_check_filter(dev)) {
1696 ERROR("Device no longer matches filter after interface info "
1697 "change, disconnecting!\n");
1702 static void usbredir_mark_speed_incompatible(USBRedirDevice *dev, int speed)
1704 dev->compatible_speedmask &= ~(1 << speed);
1705 dev->dev.speedmask = (1 << dev->dev.speed) | dev->compatible_speedmask;
1708 static void usbredir_set_pipeline(USBRedirDevice *dev, struct USBEndpoint *uep)
1710 if (uep->type != USB_ENDPOINT_XFER_BULK) {
1711 return;
1713 if (uep->pid == USB_TOKEN_OUT) {
1714 uep->pipeline = true;
1716 if (uep->pid == USB_TOKEN_IN && uep->max_packet_size != 0 &&
1717 usbredirparser_peer_has_cap(dev->parser,
1718 usb_redir_cap_32bits_bulk_length)) {
1719 uep->pipeline = true;
1723 static void usbredir_setup_usb_eps(USBRedirDevice *dev)
1725 struct USBEndpoint *usb_ep;
1726 int i;
1728 for (i = 0; i < MAX_ENDPOINTS; i++) {
1729 usb_ep = I2USBEP(dev, i);
1730 usb_ep->type = dev->endpoint[i].type;
1731 usb_ep->ifnum = dev->endpoint[i].interface;
1732 usb_ep->max_packet_size = dev->endpoint[i].max_packet_size;
1733 usb_ep->max_streams = dev->endpoint[i].max_streams;
1734 usbredir_set_pipeline(dev, usb_ep);
1738 static void usbredir_ep_info(void *priv,
1739 struct usb_redir_ep_info_header *ep_info)
1741 USBRedirDevice *dev = priv;
1742 int i;
1744 for (i = 0; i < MAX_ENDPOINTS; i++) {
1745 dev->endpoint[i].type = ep_info->type[i];
1746 dev->endpoint[i].interval = ep_info->interval[i];
1747 dev->endpoint[i].interface = ep_info->interface[i];
1748 if (usbredirparser_peer_has_cap(dev->parser,
1749 usb_redir_cap_ep_info_max_packet_size)) {
1750 dev->endpoint[i].max_packet_size = ep_info->max_packet_size[i];
1752 #if USBREDIR_VERSION >= 0x000700
1753 if (usbredirparser_peer_has_cap(dev->parser,
1754 usb_redir_cap_bulk_streams)) {
1755 dev->endpoint[i].max_streams = ep_info->max_streams[i];
1757 #endif
1758 switch (dev->endpoint[i].type) {
1759 case usb_redir_type_invalid:
1760 break;
1761 case usb_redir_type_iso:
1762 usbredir_mark_speed_incompatible(dev, USB_SPEED_FULL);
1763 usbredir_mark_speed_incompatible(dev, USB_SPEED_HIGH);
1764 /* Fall through */
1765 case usb_redir_type_interrupt:
1766 if (!usbredirparser_peer_has_cap(dev->parser,
1767 usb_redir_cap_ep_info_max_packet_size) ||
1768 ep_info->max_packet_size[i] > 64) {
1769 usbredir_mark_speed_incompatible(dev, USB_SPEED_FULL);
1771 if (!usbredirparser_peer_has_cap(dev->parser,
1772 usb_redir_cap_ep_info_max_packet_size) ||
1773 ep_info->max_packet_size[i] > 1024) {
1774 usbredir_mark_speed_incompatible(dev, USB_SPEED_HIGH);
1776 if (dev->endpoint[i].interval == 0) {
1777 ERROR("Received 0 interval for isoc or irq endpoint\n");
1778 usbredir_reject_device(dev);
1779 return;
1781 /* Fall through */
1782 case usb_redir_type_control:
1783 case usb_redir_type_bulk:
1784 DPRINTF("ep: %02X type: %d interface: %d\n", I2EP(i),
1785 dev->endpoint[i].type, dev->endpoint[i].interface);
1786 break;
1787 default:
1788 ERROR("Received invalid endpoint type\n");
1789 usbredir_reject_device(dev);
1790 return;
1793 /* The new ep info may have caused a speed incompatibility, recheck */
1794 if (dev->dev.attached &&
1795 !(dev->dev.port->speedmask & dev->dev.speedmask)) {
1796 ERROR("Device no longer matches speed after endpoint info change, "
1797 "disconnecting!\n");
1798 usbredir_reject_device(dev);
1799 return;
1801 usbredir_setup_usb_eps(dev);
1802 usbredir_check_bulk_receiving(dev);
1805 static void usbredir_configuration_status(void *priv, uint64_t id,
1806 struct usb_redir_configuration_status_header *config_status)
1808 USBRedirDevice *dev = priv;
1809 USBPacket *p;
1811 DPRINTF("set config status %d config %d id %"PRIu64"\n",
1812 config_status->status, config_status->configuration, id);
1814 p = usbredir_find_packet_by_id(dev, 0, id);
1815 if (p) {
1816 if (dev->dev.setup_buf[0] & USB_DIR_IN) {
1817 dev->dev.data_buf[0] = config_status->configuration;
1818 p->actual_length = 1;
1820 usbredir_handle_status(dev, p, config_status->status);
1821 usb_generic_async_ctrl_complete(&dev->dev, p);
1825 static void usbredir_alt_setting_status(void *priv, uint64_t id,
1826 struct usb_redir_alt_setting_status_header *alt_setting_status)
1828 USBRedirDevice *dev = priv;
1829 USBPacket *p;
1831 DPRINTF("alt status %d intf %d alt %d id: %"PRIu64"\n",
1832 alt_setting_status->status, alt_setting_status->interface,
1833 alt_setting_status->alt, id);
1835 p = usbredir_find_packet_by_id(dev, 0, id);
1836 if (p) {
1837 if (dev->dev.setup_buf[0] & USB_DIR_IN) {
1838 dev->dev.data_buf[0] = alt_setting_status->alt;
1839 p->actual_length = 1;
1841 usbredir_handle_status(dev, p, alt_setting_status->status);
1842 usb_generic_async_ctrl_complete(&dev->dev, p);
1846 static void usbredir_iso_stream_status(void *priv, uint64_t id,
1847 struct usb_redir_iso_stream_status_header *iso_stream_status)
1849 USBRedirDevice *dev = priv;
1850 uint8_t ep = iso_stream_status->endpoint;
1852 DPRINTF("iso status %d ep %02X id %"PRIu64"\n", iso_stream_status->status,
1853 ep, id);
1855 if (!dev->dev.attached || !dev->endpoint[EP2I(ep)].iso_started) {
1856 return;
1859 dev->endpoint[EP2I(ep)].iso_error = iso_stream_status->status;
1860 if (iso_stream_status->status == usb_redir_stall) {
1861 DPRINTF("iso stream stopped by peer ep %02X\n", ep);
1862 dev->endpoint[EP2I(ep)].iso_started = 0;
1866 static void usbredir_interrupt_receiving_status(void *priv, uint64_t id,
1867 struct usb_redir_interrupt_receiving_status_header
1868 *interrupt_receiving_status)
1870 USBRedirDevice *dev = priv;
1871 uint8_t ep = interrupt_receiving_status->endpoint;
1873 DPRINTF("interrupt recv status %d ep %02X id %"PRIu64"\n",
1874 interrupt_receiving_status->status, ep, id);
1876 if (!dev->dev.attached || !dev->endpoint[EP2I(ep)].interrupt_started) {
1877 return;
1880 dev->endpoint[EP2I(ep)].interrupt_error =
1881 interrupt_receiving_status->status;
1882 if (interrupt_receiving_status->status == usb_redir_stall) {
1883 DPRINTF("interrupt receiving stopped by peer ep %02X\n", ep);
1884 dev->endpoint[EP2I(ep)].interrupt_started = 0;
1888 static void usbredir_bulk_streams_status(void *priv, uint64_t id,
1889 struct usb_redir_bulk_streams_status_header *bulk_streams_status)
1891 #if USBREDIR_VERSION >= 0x000700
1892 USBRedirDevice *dev = priv;
1894 if (bulk_streams_status->status == usb_redir_success) {
1895 DPRINTF("bulk streams status %d eps %08x\n",
1896 bulk_streams_status->status, bulk_streams_status->endpoints);
1897 } else {
1898 ERROR("bulk streams %s failed status %d eps %08x\n",
1899 (bulk_streams_status->no_streams == 0) ? "free" : "alloc",
1900 bulk_streams_status->status, bulk_streams_status->endpoints);
1901 ERROR("usb-redir-host does not provide streams, disconnecting\n");
1902 usbredir_reject_device(dev);
1904 #endif
1907 static void usbredir_bulk_receiving_status(void *priv, uint64_t id,
1908 struct usb_redir_bulk_receiving_status_header *bulk_receiving_status)
1910 USBRedirDevice *dev = priv;
1911 uint8_t ep = bulk_receiving_status->endpoint;
1913 DPRINTF("bulk recv status %d ep %02X id %"PRIu64"\n",
1914 bulk_receiving_status->status, ep, id);
1916 if (!dev->dev.attached || !dev->endpoint[EP2I(ep)].bulk_receiving_started) {
1917 return;
1920 if (bulk_receiving_status->status == usb_redir_stall) {
1921 DPRINTF("bulk receiving stopped by peer ep %02X\n", ep);
1922 dev->endpoint[EP2I(ep)].bulk_receiving_started = 0;
1926 static void usbredir_control_packet(void *priv, uint64_t id,
1927 struct usb_redir_control_packet_header *control_packet,
1928 uint8_t *data, int data_len)
1930 USBRedirDevice *dev = priv;
1931 USBPacket *p;
1932 int len = control_packet->length;
1934 DPRINTF("ctrl-in status %d len %d id %"PRIu64"\n", control_packet->status,
1935 len, id);
1937 /* Fix up USB-3 ep0 maxpacket size to allow superspeed connected devices
1938 * to work redirected to a not superspeed capable hcd */
1939 if (dev->dev.speed == USB_SPEED_SUPER &&
1940 !((dev->dev.port->speedmask & USB_SPEED_MASK_SUPER)) &&
1941 control_packet->requesttype == 0x80 &&
1942 control_packet->request == 6 &&
1943 control_packet->value == 0x100 && control_packet->index == 0 &&
1944 data_len >= 18 && data[7] == 9) {
1945 data[7] = 64;
1948 p = usbredir_find_packet_by_id(dev, 0, id);
1949 if (p) {
1950 usbredir_handle_status(dev, p, control_packet->status);
1951 if (data_len > 0) {
1952 usbredir_log_data(dev, "ctrl data in:", data, data_len);
1953 if (data_len > sizeof(dev->dev.data_buf)) {
1954 ERROR("ctrl buffer too small (%d > %zu)\n",
1955 data_len, sizeof(dev->dev.data_buf));
1956 p->status = USB_RET_STALL;
1957 data_len = len = sizeof(dev->dev.data_buf);
1959 memcpy(dev->dev.data_buf, data, data_len);
1961 p->actual_length = len;
1962 usb_generic_async_ctrl_complete(&dev->dev, p);
1964 free(data);
1967 static void usbredir_bulk_packet(void *priv, uint64_t id,
1968 struct usb_redir_bulk_packet_header *bulk_packet,
1969 uint8_t *data, int data_len)
1971 USBRedirDevice *dev = priv;
1972 uint8_t ep = bulk_packet->endpoint;
1973 int len = (bulk_packet->length_high << 16) | bulk_packet->length;
1974 USBPacket *p;
1976 DPRINTF("bulk-in status %d ep %02X stream %u len %d id %"PRIu64"\n",
1977 bulk_packet->status, ep, bulk_packet->stream_id, len, id);
1979 p = usbredir_find_packet_by_id(dev, ep, id);
1980 if (p) {
1981 size_t size = usb_packet_size(p);
1982 usbredir_handle_status(dev, p, bulk_packet->status);
1983 if (data_len > 0) {
1984 usbredir_log_data(dev, "bulk data in:", data, data_len);
1985 if (data_len > size) {
1986 ERROR("bulk got more data then requested (%d > %zd)\n",
1987 data_len, p->iov.size);
1988 p->status = USB_RET_BABBLE;
1989 data_len = len = size;
1991 usb_packet_copy(p, data, data_len);
1993 p->actual_length = len;
1994 if (p->pid == USB_TOKEN_IN && p->ep->pipeline) {
1995 usb_combined_input_packet_complete(&dev->dev, p);
1996 } else {
1997 usb_packet_complete(&dev->dev, p);
2000 free(data);
2003 static void usbredir_iso_packet(void *priv, uint64_t id,
2004 struct usb_redir_iso_packet_header *iso_packet,
2005 uint8_t *data, int data_len)
2007 USBRedirDevice *dev = priv;
2008 uint8_t ep = iso_packet->endpoint;
2010 DPRINTF2("iso-in status %d ep %02X len %d id %"PRIu64"\n",
2011 iso_packet->status, ep, data_len, id);
2013 if (dev->endpoint[EP2I(ep)].type != USB_ENDPOINT_XFER_ISOC) {
2014 ERROR("received iso packet for non iso endpoint %02X\n", ep);
2015 free(data);
2016 return;
2019 if (dev->endpoint[EP2I(ep)].iso_started == 0) {
2020 DPRINTF("received iso packet for non started stream ep %02X\n", ep);
2021 free(data);
2022 return;
2025 /* bufp_alloc also adds the packet to the ep queue */
2026 bufp_alloc(dev, data, data_len, iso_packet->status, ep, data);
2029 static void usbredir_interrupt_packet(void *priv, uint64_t id,
2030 struct usb_redir_interrupt_packet_header *interrupt_packet,
2031 uint8_t *data, int data_len)
2033 USBRedirDevice *dev = priv;
2034 uint8_t ep = interrupt_packet->endpoint;
2036 DPRINTF("interrupt-in status %d ep %02X len %d id %"PRIu64"\n",
2037 interrupt_packet->status, ep, data_len, id);
2039 if (dev->endpoint[EP2I(ep)].type != USB_ENDPOINT_XFER_INT) {
2040 ERROR("received int packet for non interrupt endpoint %02X\n", ep);
2041 free(data);
2042 return;
2045 if (ep & USB_DIR_IN) {
2046 bool q_was_empty;
2048 if (dev->endpoint[EP2I(ep)].interrupt_started == 0) {
2049 DPRINTF("received int packet while not started ep %02X\n", ep);
2050 free(data);
2051 return;
2054 q_was_empty = QTAILQ_EMPTY(&dev->endpoint[EP2I(ep)].bufpq);
2056 /* bufp_alloc also adds the packet to the ep queue */
2057 bufp_alloc(dev, data, data_len, interrupt_packet->status, ep, data);
2059 if (q_was_empty) {
2060 usb_wakeup(usb_ep_get(&dev->dev, USB_TOKEN_IN, ep & 0x0f), 0);
2062 } else {
2064 * We report output interrupt packets as completed directly upon
2065 * submission, so all we can do here if one failed is warn.
2067 if (interrupt_packet->status) {
2068 WARNING("interrupt output failed status %d ep %02X id %"PRIu64"\n",
2069 interrupt_packet->status, ep, id);
2074 static void usbredir_buffered_bulk_packet(void *priv, uint64_t id,
2075 struct usb_redir_buffered_bulk_packet_header *buffered_bulk_packet,
2076 uint8_t *data, int data_len)
2078 USBRedirDevice *dev = priv;
2079 uint8_t status, ep = buffered_bulk_packet->endpoint;
2080 void *free_on_destroy;
2081 int i, len;
2083 DPRINTF("buffered-bulk-in status %d ep %02X len %d id %"PRIu64"\n",
2084 buffered_bulk_packet->status, ep, data_len, id);
2086 if (dev->endpoint[EP2I(ep)].type != USB_ENDPOINT_XFER_BULK) {
2087 ERROR("received buffered-bulk packet for non bulk ep %02X\n", ep);
2088 free(data);
2089 return;
2092 if (dev->endpoint[EP2I(ep)].bulk_receiving_started == 0) {
2093 DPRINTF("received buffered-bulk packet on not started ep %02X\n", ep);
2094 free(data);
2095 return;
2098 /* Data must be in maxp chunks for buffered_bulk_add_*_data_to_packet */
2099 len = dev->endpoint[EP2I(ep)].max_packet_size;
2100 status = usb_redir_success;
2101 free_on_destroy = NULL;
2102 for (i = 0; i < data_len; i += len) {
2103 int r;
2104 if (len >= (data_len - i)) {
2105 len = data_len - i;
2106 status = buffered_bulk_packet->status;
2107 free_on_destroy = data;
2109 /* bufp_alloc also adds the packet to the ep queue */
2110 r = bufp_alloc(dev, data + i, len, status, ep, free_on_destroy);
2111 if (r) {
2112 break;
2116 if (dev->endpoint[EP2I(ep)].pending_async_packet) {
2117 USBPacket *p = dev->endpoint[EP2I(ep)].pending_async_packet;
2118 dev->endpoint[EP2I(ep)].pending_async_packet = NULL;
2119 usbredir_buffered_bulk_in_complete(dev, p, ep);
2120 usb_packet_complete(&dev->dev, p);
2125 * Migration code
2128 static void usbredir_pre_save(void *priv)
2130 USBRedirDevice *dev = priv;
2132 usbredir_fill_already_in_flight(dev);
2135 static int usbredir_post_load(void *priv, int version_id)
2137 USBRedirDevice *dev = priv;
2139 if (dev->parser == NULL) {
2140 return 0;
2143 switch (dev->device_info.speed) {
2144 case usb_redir_speed_low:
2145 dev->dev.speed = USB_SPEED_LOW;
2146 break;
2147 case usb_redir_speed_full:
2148 dev->dev.speed = USB_SPEED_FULL;
2149 break;
2150 case usb_redir_speed_high:
2151 dev->dev.speed = USB_SPEED_HIGH;
2152 break;
2153 case usb_redir_speed_super:
2154 dev->dev.speed = USB_SPEED_SUPER;
2155 break;
2156 default:
2157 dev->dev.speed = USB_SPEED_FULL;
2159 dev->dev.speedmask = (1 << dev->dev.speed);
2161 usbredir_setup_usb_eps(dev);
2162 usbredir_check_bulk_receiving(dev);
2164 return 0;
2167 /* For usbredirparser migration */
2168 static int usbredir_put_parser(QEMUFile *f, void *priv, size_t unused,
2169 VMStateField *field, QJSON *vmdesc)
2171 USBRedirDevice *dev = priv;
2172 uint8_t *data;
2173 int len;
2175 if (dev->parser == NULL) {
2176 qemu_put_be32(f, 0);
2177 return 0;
2180 usbredirparser_serialize(dev->parser, &data, &len);
2181 qemu_oom_check(data);
2183 qemu_put_be32(f, len);
2184 qemu_put_buffer(f, data, len);
2186 free(data);
2188 return 0;
2191 static int usbredir_get_parser(QEMUFile *f, void *priv, size_t unused,
2192 VMStateField *field)
2194 USBRedirDevice *dev = priv;
2195 uint8_t *data;
2196 int len, ret;
2198 len = qemu_get_be32(f);
2199 if (len == 0) {
2200 return 0;
2204 * If our chardev is not open already at this point the usbredir connection
2205 * has been broken (non seamless migration, or restore from disk).
2207 * In this case create a temporary parser to receive the migration data,
2208 * and schedule the close_bh to report the device as disconnected to the
2209 * guest and to destroy the parser again.
2211 if (dev->parser == NULL) {
2212 WARNING("usb-redir connection broken during migration\n");
2213 usbredir_create_parser(dev);
2214 qemu_bh_schedule(dev->chardev_close_bh);
2217 data = g_malloc(len);
2218 qemu_get_buffer(f, data, len);
2220 ret = usbredirparser_unserialize(dev->parser, data, len);
2222 g_free(data);
2224 return ret;
2227 static const VMStateInfo usbredir_parser_vmstate_info = {
2228 .name = "usb-redir-parser",
2229 .put = usbredir_put_parser,
2230 .get = usbredir_get_parser,
2234 /* For buffered packets (iso/irq) queue migration */
2235 static int usbredir_put_bufpq(QEMUFile *f, void *priv, size_t unused,
2236 VMStateField *field, QJSON *vmdesc)
2238 struct endp_data *endp = priv;
2239 USBRedirDevice *dev = endp->dev;
2240 struct buf_packet *bufp;
2241 int len, i = 0;
2243 qemu_put_be32(f, endp->bufpq_size);
2244 QTAILQ_FOREACH(bufp, &endp->bufpq, next) {
2245 len = bufp->len - bufp->offset;
2246 DPRINTF("put_bufpq %d/%d len %d status %d\n", i + 1, endp->bufpq_size,
2247 len, bufp->status);
2248 qemu_put_be32(f, len);
2249 qemu_put_be32(f, bufp->status);
2250 qemu_put_buffer(f, bufp->data + bufp->offset, len);
2251 i++;
2253 assert(i == endp->bufpq_size);
2255 return 0;
2258 static int usbredir_get_bufpq(QEMUFile *f, void *priv, size_t unused,
2259 VMStateField *field)
2261 struct endp_data *endp = priv;
2262 USBRedirDevice *dev = endp->dev;
2263 struct buf_packet *bufp;
2264 int i;
2266 endp->bufpq_size = qemu_get_be32(f);
2267 for (i = 0; i < endp->bufpq_size; i++) {
2268 bufp = g_new(struct buf_packet, 1);
2269 bufp->len = qemu_get_be32(f);
2270 bufp->status = qemu_get_be32(f);
2271 bufp->offset = 0;
2272 bufp->data = qemu_oom_check(malloc(bufp->len)); /* regular malloc! */
2273 bufp->free_on_destroy = bufp->data;
2274 qemu_get_buffer(f, bufp->data, bufp->len);
2275 QTAILQ_INSERT_TAIL(&endp->bufpq, bufp, next);
2276 DPRINTF("get_bufpq %d/%d len %d status %d\n", i + 1, endp->bufpq_size,
2277 bufp->len, bufp->status);
2279 return 0;
2282 static const VMStateInfo usbredir_ep_bufpq_vmstate_info = {
2283 .name = "usb-redir-bufpq",
2284 .put = usbredir_put_bufpq,
2285 .get = usbredir_get_bufpq,
2289 /* For endp_data migration */
2290 static bool usbredir_bulk_receiving_needed(void *priv)
2292 struct endp_data *endp = priv;
2294 return endp->bulk_receiving_started;
2297 static const VMStateDescription usbredir_bulk_receiving_vmstate = {
2298 .name = "usb-redir-ep/bulk-receiving",
2299 .version_id = 1,
2300 .minimum_version_id = 1,
2301 .needed = usbredir_bulk_receiving_needed,
2302 .fields = (VMStateField[]) {
2303 VMSTATE_UINT8(bulk_receiving_started, struct endp_data),
2304 VMSTATE_END_OF_LIST()
2308 static bool usbredir_stream_needed(void *priv)
2310 struct endp_data *endp = priv;
2312 return endp->max_streams;
2315 static const VMStateDescription usbredir_stream_vmstate = {
2316 .name = "usb-redir-ep/stream-state",
2317 .version_id = 1,
2318 .minimum_version_id = 1,
2319 .needed = usbredir_stream_needed,
2320 .fields = (VMStateField[]) {
2321 VMSTATE_UINT32(max_streams, struct endp_data),
2322 VMSTATE_END_OF_LIST()
2326 static const VMStateDescription usbredir_ep_vmstate = {
2327 .name = "usb-redir-ep",
2328 .version_id = 1,
2329 .minimum_version_id = 1,
2330 .fields = (VMStateField[]) {
2331 VMSTATE_UINT8(type, struct endp_data),
2332 VMSTATE_UINT8(interval, struct endp_data),
2333 VMSTATE_UINT8(interface, struct endp_data),
2334 VMSTATE_UINT16(max_packet_size, struct endp_data),
2335 VMSTATE_UINT8(iso_started, struct endp_data),
2336 VMSTATE_UINT8(iso_error, struct endp_data),
2337 VMSTATE_UINT8(interrupt_started, struct endp_data),
2338 VMSTATE_UINT8(interrupt_error, struct endp_data),
2339 VMSTATE_UINT8(bufpq_prefilled, struct endp_data),
2340 VMSTATE_UINT8(bufpq_dropping_packets, struct endp_data),
2342 .name = "bufpq",
2343 .version_id = 0,
2344 .field_exists = NULL,
2345 .size = 0,
2346 .info = &usbredir_ep_bufpq_vmstate_info,
2347 .flags = VMS_SINGLE,
2348 .offset = 0,
2350 VMSTATE_INT32(bufpq_target_size, struct endp_data),
2351 VMSTATE_END_OF_LIST()
2353 .subsections = (const VMStateDescription*[]) {
2354 &usbredir_bulk_receiving_vmstate,
2355 &usbredir_stream_vmstate,
2356 NULL
2361 /* For PacketIdQueue migration */
2362 static int usbredir_put_packet_id_q(QEMUFile *f, void *priv, size_t unused,
2363 VMStateField *field, QJSON *vmdesc)
2365 struct PacketIdQueue *q = priv;
2366 USBRedirDevice *dev = q->dev;
2367 struct PacketIdQueueEntry *e;
2368 int remain = q->size;
2370 DPRINTF("put_packet_id_q %s size %d\n", q->name, q->size);
2371 qemu_put_be32(f, q->size);
2372 QTAILQ_FOREACH(e, &q->head, next) {
2373 qemu_put_be64(f, e->id);
2374 remain--;
2376 assert(remain == 0);
2378 return 0;
2381 static int usbredir_get_packet_id_q(QEMUFile *f, void *priv, size_t unused,
2382 VMStateField *field)
2384 struct PacketIdQueue *q = priv;
2385 USBRedirDevice *dev = q->dev;
2386 int i, size;
2387 uint64_t id;
2389 size = qemu_get_be32(f);
2390 DPRINTF("get_packet_id_q %s size %d\n", q->name, size);
2391 for (i = 0; i < size; i++) {
2392 id = qemu_get_be64(f);
2393 packet_id_queue_add(q, id);
2395 assert(q->size == size);
2396 return 0;
2399 static const VMStateInfo usbredir_ep_packet_id_q_vmstate_info = {
2400 .name = "usb-redir-packet-id-q",
2401 .put = usbredir_put_packet_id_q,
2402 .get = usbredir_get_packet_id_q,
2405 static const VMStateDescription usbredir_ep_packet_id_queue_vmstate = {
2406 .name = "usb-redir-packet-id-queue",
2407 .version_id = 1,
2408 .minimum_version_id = 1,
2409 .fields = (VMStateField[]) {
2411 .name = "queue",
2412 .version_id = 0,
2413 .field_exists = NULL,
2414 .size = 0,
2415 .info = &usbredir_ep_packet_id_q_vmstate_info,
2416 .flags = VMS_SINGLE,
2417 .offset = 0,
2419 VMSTATE_END_OF_LIST()
2424 /* For usb_redir_device_connect_header migration */
2425 static const VMStateDescription usbredir_device_info_vmstate = {
2426 .name = "usb-redir-device-info",
2427 .version_id = 1,
2428 .minimum_version_id = 1,
2429 .fields = (VMStateField[]) {
2430 VMSTATE_UINT8(speed, struct usb_redir_device_connect_header),
2431 VMSTATE_UINT8(device_class, struct usb_redir_device_connect_header),
2432 VMSTATE_UINT8(device_subclass, struct usb_redir_device_connect_header),
2433 VMSTATE_UINT8(device_protocol, struct usb_redir_device_connect_header),
2434 VMSTATE_UINT16(vendor_id, struct usb_redir_device_connect_header),
2435 VMSTATE_UINT16(product_id, struct usb_redir_device_connect_header),
2436 VMSTATE_UINT16(device_version_bcd,
2437 struct usb_redir_device_connect_header),
2438 VMSTATE_END_OF_LIST()
2443 /* For usb_redir_interface_info_header migration */
2444 static const VMStateDescription usbredir_interface_info_vmstate = {
2445 .name = "usb-redir-interface-info",
2446 .version_id = 1,
2447 .minimum_version_id = 1,
2448 .fields = (VMStateField[]) {
2449 VMSTATE_UINT32(interface_count,
2450 struct usb_redir_interface_info_header),
2451 VMSTATE_UINT8_ARRAY(interface,
2452 struct usb_redir_interface_info_header, 32),
2453 VMSTATE_UINT8_ARRAY(interface_class,
2454 struct usb_redir_interface_info_header, 32),
2455 VMSTATE_UINT8_ARRAY(interface_subclass,
2456 struct usb_redir_interface_info_header, 32),
2457 VMSTATE_UINT8_ARRAY(interface_protocol,
2458 struct usb_redir_interface_info_header, 32),
2459 VMSTATE_END_OF_LIST()
2464 /* And finally the USBRedirDevice vmstate itself */
2465 static const VMStateDescription usbredir_vmstate = {
2466 .name = "usb-redir",
2467 .version_id = 1,
2468 .minimum_version_id = 1,
2469 .pre_save = usbredir_pre_save,
2470 .post_load = usbredir_post_load,
2471 .fields = (VMStateField[]) {
2472 VMSTATE_USB_DEVICE(dev, USBRedirDevice),
2473 VMSTATE_TIMER_PTR(attach_timer, USBRedirDevice),
2475 .name = "parser",
2476 .version_id = 0,
2477 .field_exists = NULL,
2478 .size = 0,
2479 .info = &usbredir_parser_vmstate_info,
2480 .flags = VMS_SINGLE,
2481 .offset = 0,
2483 VMSTATE_STRUCT_ARRAY(endpoint, USBRedirDevice, MAX_ENDPOINTS, 1,
2484 usbredir_ep_vmstate, struct endp_data),
2485 VMSTATE_STRUCT(cancelled, USBRedirDevice, 1,
2486 usbredir_ep_packet_id_queue_vmstate,
2487 struct PacketIdQueue),
2488 VMSTATE_STRUCT(already_in_flight, USBRedirDevice, 1,
2489 usbredir_ep_packet_id_queue_vmstate,
2490 struct PacketIdQueue),
2491 VMSTATE_STRUCT(device_info, USBRedirDevice, 1,
2492 usbredir_device_info_vmstate,
2493 struct usb_redir_device_connect_header),
2494 VMSTATE_STRUCT(interface_info, USBRedirDevice, 1,
2495 usbredir_interface_info_vmstate,
2496 struct usb_redir_interface_info_header),
2497 VMSTATE_END_OF_LIST()
2501 static Property usbredir_properties[] = {
2502 DEFINE_PROP_CHR("chardev", USBRedirDevice, cs),
2503 DEFINE_PROP_UINT8("debug", USBRedirDevice, debug, usbredirparser_warning),
2504 DEFINE_PROP_STRING("filter", USBRedirDevice, filter_str),
2505 DEFINE_PROP_BOOL("streams", USBRedirDevice, enable_streams, true),
2506 DEFINE_PROP_END_OF_LIST(),
2509 static void usbredir_class_initfn(ObjectClass *klass, void *data)
2511 USBDeviceClass *uc = USB_DEVICE_CLASS(klass);
2512 DeviceClass *dc = DEVICE_CLASS(klass);
2514 uc->realize = usbredir_realize;
2515 uc->product_desc = "USB Redirection Device";
2516 uc->unrealize = usbredir_unrealize;
2517 uc->cancel_packet = usbredir_cancel_packet;
2518 uc->handle_reset = usbredir_handle_reset;
2519 uc->handle_data = usbredir_handle_data;
2520 uc->handle_control = usbredir_handle_control;
2521 uc->flush_ep_queue = usbredir_flush_ep_queue;
2522 uc->ep_stopped = usbredir_ep_stopped;
2523 uc->alloc_streams = usbredir_alloc_streams;
2524 uc->free_streams = usbredir_free_streams;
2525 dc->vmsd = &usbredir_vmstate;
2526 dc->props = usbredir_properties;
2527 set_bit(DEVICE_CATEGORY_MISC, dc->categories);
2530 static void usbredir_instance_init(Object *obj)
2532 USBDevice *udev = USB_DEVICE(obj);
2533 USBRedirDevice *dev = USB_REDIRECT(udev);
2535 device_add_bootindex_property(obj, &dev->bootindex,
2536 "bootindex", NULL,
2537 &udev->qdev, NULL);
2540 static const TypeInfo usbredir_dev_info = {
2541 .name = TYPE_USB_REDIR,
2542 .parent = TYPE_USB_DEVICE,
2543 .instance_size = sizeof(USBRedirDevice),
2544 .class_init = usbredir_class_initfn,
2545 .instance_init = usbredir_instance_init,
2548 static void usbredir_register_types(void)
2550 type_register_static(&usbredir_dev_info);
2553 type_init(usbredir_register_types)