usb-redir: Allow to attach USB 2.0 devices to 1.1 host controller
[qemu-kvm.git] / hw / usb / redirect.c
blob8d4d3f41bef552ebff18b1111e210ddb1520133e
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-common.h"
29 #include "qemu-timer.h"
30 #include "monitor.h"
31 #include "sysemu.h"
32 #include "iov.h"
34 #include <dirent.h>
35 #include <sys/ioctl.h>
36 #include <signal.h>
37 #include <usbredirparser.h>
38 #include <usbredirfilter.h>
40 #include "hw/usb.h"
42 #define MAX_ENDPOINTS 32
43 #define NO_INTERFACE_INFO 255 /* Valid interface_count always <= 32 */
44 #define EP2I(ep_address) (((ep_address & 0x80) >> 3) | (ep_address & 0x0f))
45 #define I2EP(i) (((i & 0x10) << 3) | (i & 0x0f))
47 typedef struct USBRedirDevice USBRedirDevice;
49 /* Struct to hold buffered packets (iso or int input packets) */
50 struct buf_packet {
51 uint8_t *data;
52 int len;
53 int status;
54 QTAILQ_ENTRY(buf_packet)next;
57 struct endp_data {
58 uint8_t type;
59 uint8_t interval;
60 uint8_t interface; /* bInterfaceNumber this ep belongs to */
61 uint16_t max_packet_size; /* In bytes, not wMaxPacketSize format !! */
62 uint8_t iso_started;
63 uint8_t iso_error; /* For reporting iso errors to the HC */
64 uint8_t interrupt_started;
65 uint8_t interrupt_error;
66 uint8_t bufpq_prefilled;
67 uint8_t bufpq_dropping_packets;
68 QTAILQ_HEAD(, buf_packet) bufpq;
69 int32_t bufpq_size;
70 int32_t bufpq_target_size;
73 struct PacketIdQueueEntry {
74 uint64_t id;
75 QTAILQ_ENTRY(PacketIdQueueEntry)next;
78 struct PacketIdQueue {
79 USBRedirDevice *dev;
80 const char *name;
81 QTAILQ_HEAD(, PacketIdQueueEntry) head;
82 int size;
85 struct USBRedirDevice {
86 USBDevice dev;
87 /* Properties */
88 CharDriverState *cs;
89 uint8_t debug;
90 char *filter_str;
91 int32_t bootindex;
92 /* Data passed from chardev the fd_read cb to the usbredirparser read cb */
93 const uint8_t *read_buf;
94 int read_buf_size;
95 /* For async handling of close */
96 QEMUBH *chardev_close_bh;
97 /* To delay the usb attach in case of quick chardev close + open */
98 QEMUTimer *attach_timer;
99 int64_t next_attach_time;
100 struct usbredirparser *parser;
101 struct endp_data endpoint[MAX_ENDPOINTS];
102 struct PacketIdQueue cancelled;
103 struct PacketIdQueue already_in_flight;
104 /* Data for device filtering */
105 struct usb_redir_device_connect_header device_info;
106 struct usb_redir_interface_info_header interface_info;
107 struct usbredirfilter_rule *filter_rules;
108 int filter_rules_count;
109 int compatible_speedmask;
112 static void usbredir_hello(void *priv, struct usb_redir_hello_header *h);
113 static void usbredir_device_connect(void *priv,
114 struct usb_redir_device_connect_header *device_connect);
115 static void usbredir_device_disconnect(void *priv);
116 static void usbredir_interface_info(void *priv,
117 struct usb_redir_interface_info_header *interface_info);
118 static void usbredir_ep_info(void *priv,
119 struct usb_redir_ep_info_header *ep_info);
120 static void usbredir_configuration_status(void *priv, uint64_t id,
121 struct usb_redir_configuration_status_header *configuration_status);
122 static void usbredir_alt_setting_status(void *priv, uint64_t id,
123 struct usb_redir_alt_setting_status_header *alt_setting_status);
124 static void usbredir_iso_stream_status(void *priv, uint64_t id,
125 struct usb_redir_iso_stream_status_header *iso_stream_status);
126 static void usbredir_interrupt_receiving_status(void *priv, uint64_t id,
127 struct usb_redir_interrupt_receiving_status_header
128 *interrupt_receiving_status);
129 static void usbredir_bulk_streams_status(void *priv, uint64_t id,
130 struct usb_redir_bulk_streams_status_header *bulk_streams_status);
131 static void usbredir_control_packet(void *priv, uint64_t id,
132 struct usb_redir_control_packet_header *control_packet,
133 uint8_t *data, int data_len);
134 static void usbredir_bulk_packet(void *priv, uint64_t id,
135 struct usb_redir_bulk_packet_header *bulk_packet,
136 uint8_t *data, int data_len);
137 static void usbredir_iso_packet(void *priv, uint64_t id,
138 struct usb_redir_iso_packet_header *iso_packet,
139 uint8_t *data, int data_len);
140 static void usbredir_interrupt_packet(void *priv, uint64_t id,
141 struct usb_redir_interrupt_packet_header *interrupt_header,
142 uint8_t *data, int data_len);
144 static int usbredir_handle_status(USBRedirDevice *dev,
145 int status, int actual_len);
147 #define VERSION "qemu usb-redir guest " QEMU_VERSION
150 * Logging stuff
153 #define ERROR(...) \
154 do { \
155 if (dev->debug >= usbredirparser_error) { \
156 error_report("usb-redir error: " __VA_ARGS__); \
158 } while (0)
159 #define WARNING(...) \
160 do { \
161 if (dev->debug >= usbredirparser_warning) { \
162 error_report("usb-redir warning: " __VA_ARGS__); \
164 } while (0)
165 #define INFO(...) \
166 do { \
167 if (dev->debug >= usbredirparser_info) { \
168 error_report("usb-redir: " __VA_ARGS__); \
170 } while (0)
171 #define DPRINTF(...) \
172 do { \
173 if (dev->debug >= usbredirparser_debug) { \
174 error_report("usb-redir: " __VA_ARGS__); \
176 } while (0)
177 #define DPRINTF2(...) \
178 do { \
179 if (dev->debug >= usbredirparser_debug_data) { \
180 error_report("usb-redir: " __VA_ARGS__); \
182 } while (0)
184 static void usbredir_log(void *priv, int level, const char *msg)
186 USBRedirDevice *dev = priv;
188 if (dev->debug < level) {
189 return;
192 error_report("%s", msg);
195 static void usbredir_log_data(USBRedirDevice *dev, const char *desc,
196 const uint8_t *data, int len)
198 int i, j, n;
200 if (dev->debug < usbredirparser_debug_data) {
201 return;
204 for (i = 0; i < len; i += j) {
205 char buf[128];
207 n = sprintf(buf, "%s", desc);
208 for (j = 0; j < 8 && i + j < len; j++) {
209 n += sprintf(buf + n, " %02X", data[i + j]);
211 error_report("%s", buf);
216 * usbredirparser io functions
219 static int usbredir_read(void *priv, uint8_t *data, int count)
221 USBRedirDevice *dev = priv;
223 if (dev->read_buf_size < count) {
224 count = dev->read_buf_size;
227 memcpy(data, dev->read_buf, count);
229 dev->read_buf_size -= count;
230 if (dev->read_buf_size) {
231 dev->read_buf += count;
232 } else {
233 dev->read_buf = NULL;
236 return count;
239 static int usbredir_write(void *priv, uint8_t *data, int count)
241 USBRedirDevice *dev = priv;
243 if (!dev->cs->opened) {
244 return 0;
247 /* Don't send new data to the chardev until our state is fully synced */
248 if (!runstate_check(RUN_STATE_RUNNING)) {
249 return 0;
252 return qemu_chr_fe_write(dev->cs, data, count);
256 * Cancelled and buffered packets helpers
259 static void packet_id_queue_init(struct PacketIdQueue *q,
260 USBRedirDevice *dev, const char *name)
262 q->dev = dev;
263 q->name = name;
264 QTAILQ_INIT(&q->head);
265 q->size = 0;
268 static void packet_id_queue_add(struct PacketIdQueue *q, uint64_t id)
270 USBRedirDevice *dev = q->dev;
271 struct PacketIdQueueEntry *e;
273 DPRINTF("adding packet id %"PRIu64" to %s queue\n", id, q->name);
275 e = g_malloc0(sizeof(struct PacketIdQueueEntry));
276 e->id = id;
277 QTAILQ_INSERT_TAIL(&q->head, e, next);
278 q->size++;
281 static int packet_id_queue_remove(struct PacketIdQueue *q, uint64_t id)
283 USBRedirDevice *dev = q->dev;
284 struct PacketIdQueueEntry *e;
286 QTAILQ_FOREACH(e, &q->head, next) {
287 if (e->id == id) {
288 DPRINTF("removing packet id %"PRIu64" from %s queue\n",
289 id, q->name);
290 QTAILQ_REMOVE(&q->head, e, next);
291 q->size--;
292 g_free(e);
293 return 1;
296 return 0;
299 static void packet_id_queue_empty(struct PacketIdQueue *q)
301 USBRedirDevice *dev = q->dev;
302 struct PacketIdQueueEntry *e, *next_e;
304 DPRINTF("removing %d packet-ids from %s queue\n", q->size, q->name);
306 QTAILQ_FOREACH_SAFE(e, &q->head, next, next_e) {
307 QTAILQ_REMOVE(&q->head, e, next);
308 g_free(e);
310 q->size = 0;
313 static void usbredir_cancel_packet(USBDevice *udev, USBPacket *p)
315 USBRedirDevice *dev = DO_UPCAST(USBRedirDevice, dev, udev);
317 if (p->combined) {
318 usb_combined_packet_cancel(udev, p);
319 return;
322 packet_id_queue_add(&dev->cancelled, p->id);
323 usbredirparser_send_cancel_data_packet(dev->parser, p->id);
324 usbredirparser_do_write(dev->parser);
327 static int usbredir_is_cancelled(USBRedirDevice *dev, uint64_t id)
329 if (!dev->dev.attached) {
330 return 1; /* Treat everything as cancelled after a disconnect */
332 return packet_id_queue_remove(&dev->cancelled, id);
335 static void usbredir_fill_already_in_flight_from_ep(USBRedirDevice *dev,
336 struct USBEndpoint *ep)
338 static USBPacket *p;
340 QTAILQ_FOREACH(p, &ep->queue, queue) {
341 /* Skip combined packets, except for the first */
342 if (p->combined && p != p->combined->first) {
343 continue;
345 packet_id_queue_add(&dev->already_in_flight, p->id);
349 static void usbredir_fill_already_in_flight(USBRedirDevice *dev)
351 int ep;
352 struct USBDevice *udev = &dev->dev;
354 usbredir_fill_already_in_flight_from_ep(dev, &udev->ep_ctl);
356 for (ep = 0; ep < USB_MAX_ENDPOINTS; ep++) {
357 usbredir_fill_already_in_flight_from_ep(dev, &udev->ep_in[ep]);
358 usbredir_fill_already_in_flight_from_ep(dev, &udev->ep_out[ep]);
362 static int usbredir_already_in_flight(USBRedirDevice *dev, uint64_t id)
364 return packet_id_queue_remove(&dev->already_in_flight, id);
367 static USBPacket *usbredir_find_packet_by_id(USBRedirDevice *dev,
368 uint8_t ep, uint64_t id)
370 USBPacket *p;
372 if (usbredir_is_cancelled(dev, id)) {
373 return NULL;
376 p = usb_ep_find_packet_by_id(&dev->dev,
377 (ep & USB_DIR_IN) ? USB_TOKEN_IN : USB_TOKEN_OUT,
378 ep & 0x0f, id);
379 if (p == NULL) {
380 ERROR("could not find packet with id %"PRIu64"\n", id);
382 return p;
385 static void bufp_alloc(USBRedirDevice *dev,
386 uint8_t *data, int len, int status, uint8_t ep)
388 struct buf_packet *bufp;
390 if (!dev->endpoint[EP2I(ep)].bufpq_dropping_packets &&
391 dev->endpoint[EP2I(ep)].bufpq_size >
392 2 * dev->endpoint[EP2I(ep)].bufpq_target_size) {
393 DPRINTF("bufpq overflow, dropping packets ep %02X\n", ep);
394 dev->endpoint[EP2I(ep)].bufpq_dropping_packets = 1;
396 /* Since we're interupting the stream anyways, drop enough packets to get
397 back to our target buffer size */
398 if (dev->endpoint[EP2I(ep)].bufpq_dropping_packets) {
399 if (dev->endpoint[EP2I(ep)].bufpq_size >
400 dev->endpoint[EP2I(ep)].bufpq_target_size) {
401 free(data);
402 return;
404 dev->endpoint[EP2I(ep)].bufpq_dropping_packets = 0;
407 bufp = g_malloc(sizeof(struct buf_packet));
408 bufp->data = data;
409 bufp->len = len;
410 bufp->status = status;
411 QTAILQ_INSERT_TAIL(&dev->endpoint[EP2I(ep)].bufpq, bufp, next);
412 dev->endpoint[EP2I(ep)].bufpq_size++;
415 static void bufp_free(USBRedirDevice *dev, struct buf_packet *bufp,
416 uint8_t ep)
418 QTAILQ_REMOVE(&dev->endpoint[EP2I(ep)].bufpq, bufp, next);
419 dev->endpoint[EP2I(ep)].bufpq_size--;
420 free(bufp->data);
421 g_free(bufp);
424 static void usbredir_free_bufpq(USBRedirDevice *dev, uint8_t ep)
426 struct buf_packet *buf, *buf_next;
428 QTAILQ_FOREACH_SAFE(buf, &dev->endpoint[EP2I(ep)].bufpq, next, buf_next) {
429 bufp_free(dev, buf, ep);
434 * USBDevice callbacks
437 static void usbredir_handle_reset(USBDevice *udev)
439 USBRedirDevice *dev = DO_UPCAST(USBRedirDevice, dev, udev);
441 DPRINTF("reset device\n");
442 usbredirparser_send_reset(dev->parser);
443 usbredirparser_do_write(dev->parser);
446 static int usbredir_handle_iso_data(USBRedirDevice *dev, USBPacket *p,
447 uint8_t ep)
449 int status, len;
450 if (!dev->endpoint[EP2I(ep)].iso_started &&
451 !dev->endpoint[EP2I(ep)].iso_error) {
452 struct usb_redir_start_iso_stream_header start_iso = {
453 .endpoint = ep,
455 int pkts_per_sec;
457 if (dev->dev.speed == USB_SPEED_HIGH) {
458 pkts_per_sec = 8000 / dev->endpoint[EP2I(ep)].interval;
459 } else {
460 pkts_per_sec = 1000 / dev->endpoint[EP2I(ep)].interval;
462 /* Testing has shown that we need circa 60 ms buffer */
463 dev->endpoint[EP2I(ep)].bufpq_target_size = (pkts_per_sec * 60) / 1000;
465 /* Aim for approx 100 interrupts / second on the client to
466 balance latency and interrupt load */
467 start_iso.pkts_per_urb = pkts_per_sec / 100;
468 if (start_iso.pkts_per_urb < 1) {
469 start_iso.pkts_per_urb = 1;
470 } else if (start_iso.pkts_per_urb > 32) {
471 start_iso.pkts_per_urb = 32;
474 start_iso.no_urbs = (dev->endpoint[EP2I(ep)].bufpq_target_size +
475 start_iso.pkts_per_urb - 1) /
476 start_iso.pkts_per_urb;
477 /* Output endpoints pre-fill only 1/2 of the packets, keeping the rest
478 as overflow buffer. Also see the usbredir protocol documentation */
479 if (!(ep & USB_DIR_IN)) {
480 start_iso.no_urbs *= 2;
482 if (start_iso.no_urbs > 16) {
483 start_iso.no_urbs = 16;
486 /* No id, we look at the ep when receiving a status back */
487 usbredirparser_send_start_iso_stream(dev->parser, 0, &start_iso);
488 usbredirparser_do_write(dev->parser);
489 DPRINTF("iso stream started pkts/sec %d pkts/urb %d urbs %d ep %02X\n",
490 pkts_per_sec, start_iso.pkts_per_urb, start_iso.no_urbs, ep);
491 dev->endpoint[EP2I(ep)].iso_started = 1;
492 dev->endpoint[EP2I(ep)].bufpq_prefilled = 0;
493 dev->endpoint[EP2I(ep)].bufpq_dropping_packets = 0;
496 if (ep & USB_DIR_IN) {
497 struct buf_packet *isop;
499 if (dev->endpoint[EP2I(ep)].iso_started &&
500 !dev->endpoint[EP2I(ep)].bufpq_prefilled) {
501 if (dev->endpoint[EP2I(ep)].bufpq_size <
502 dev->endpoint[EP2I(ep)].bufpq_target_size) {
503 return usbredir_handle_status(dev, 0, 0);
505 dev->endpoint[EP2I(ep)].bufpq_prefilled = 1;
508 isop = QTAILQ_FIRST(&dev->endpoint[EP2I(ep)].bufpq);
509 if (isop == NULL) {
510 DPRINTF("iso-token-in ep %02X, no isop, iso_error: %d\n",
511 ep, dev->endpoint[EP2I(ep)].iso_error);
512 /* Re-fill the buffer */
513 dev->endpoint[EP2I(ep)].bufpq_prefilled = 0;
514 /* Check iso_error for stream errors, otherwise its an underrun */
515 status = dev->endpoint[EP2I(ep)].iso_error;
516 dev->endpoint[EP2I(ep)].iso_error = 0;
517 return status ? USB_RET_IOERROR : 0;
519 DPRINTF2("iso-token-in ep %02X status %d len %d queue-size: %d\n", ep,
520 isop->status, isop->len, dev->endpoint[EP2I(ep)].bufpq_size);
522 status = isop->status;
523 if (status != usb_redir_success) {
524 bufp_free(dev, isop, ep);
525 return USB_RET_IOERROR;
528 len = isop->len;
529 if (len > p->iov.size) {
530 ERROR("received iso data is larger then packet ep %02X (%d > %d)\n",
531 ep, len, (int)p->iov.size);
532 bufp_free(dev, isop, ep);
533 return USB_RET_BABBLE;
535 usb_packet_copy(p, isop->data, len);
536 bufp_free(dev, isop, ep);
537 return len;
538 } else {
539 /* If the stream was not started because of a pending error don't
540 send the packet to the usb-host */
541 if (dev->endpoint[EP2I(ep)].iso_started) {
542 struct usb_redir_iso_packet_header iso_packet = {
543 .endpoint = ep,
544 .length = p->iov.size
546 uint8_t buf[p->iov.size];
547 /* No id, we look at the ep when receiving a status back */
548 usb_packet_copy(p, buf, p->iov.size);
549 usbredirparser_send_iso_packet(dev->parser, 0, &iso_packet,
550 buf, p->iov.size);
551 usbredirparser_do_write(dev->parser);
553 status = dev->endpoint[EP2I(ep)].iso_error;
554 dev->endpoint[EP2I(ep)].iso_error = 0;
555 DPRINTF2("iso-token-out ep %02X status %d len %zd\n", ep, status,
556 p->iov.size);
557 return usbredir_handle_status(dev, status, p->iov.size);
561 static void usbredir_stop_iso_stream(USBRedirDevice *dev, uint8_t ep)
563 struct usb_redir_stop_iso_stream_header stop_iso_stream = {
564 .endpoint = ep
566 if (dev->endpoint[EP2I(ep)].iso_started) {
567 usbredirparser_send_stop_iso_stream(dev->parser, 0, &stop_iso_stream);
568 DPRINTF("iso stream stopped ep %02X\n", ep);
569 dev->endpoint[EP2I(ep)].iso_started = 0;
571 dev->endpoint[EP2I(ep)].iso_error = 0;
572 usbredir_free_bufpq(dev, ep);
575 static int usbredir_handle_bulk_data(USBRedirDevice *dev, USBPacket *p,
576 uint8_t ep)
578 struct usb_redir_bulk_packet_header bulk_packet;
579 size_t size = (p->combined) ? p->combined->iov.size : p->iov.size;
581 DPRINTF("bulk-out ep %02X len %zd id %"PRIu64"\n", ep, size, p->id);
583 if (usbredir_already_in_flight(dev, p->id)) {
584 return USB_RET_ASYNC;
587 bulk_packet.endpoint = ep;
588 bulk_packet.length = size;
589 bulk_packet.stream_id = 0;
590 bulk_packet.length_high = size >> 16;
591 assert(bulk_packet.length_high == 0 ||
592 usbredirparser_peer_has_cap(dev->parser,
593 usb_redir_cap_32bits_bulk_length));
595 if (ep & USB_DIR_IN) {
596 usbredirparser_send_bulk_packet(dev->parser, p->id,
597 &bulk_packet, NULL, 0);
598 } else {
599 uint8_t buf[size];
600 if (p->combined) {
601 iov_to_buf(p->combined->iov.iov, p->combined->iov.niov,
602 0, buf, size);
603 } else {
604 usb_packet_copy(p, buf, size);
606 usbredir_log_data(dev, "bulk data out:", buf, size);
607 usbredirparser_send_bulk_packet(dev->parser, p->id,
608 &bulk_packet, buf, size);
610 usbredirparser_do_write(dev->parser);
611 return USB_RET_ASYNC;
614 static int usbredir_handle_interrupt_data(USBRedirDevice *dev,
615 USBPacket *p, uint8_t ep)
617 if (ep & USB_DIR_IN) {
618 /* Input interrupt endpoint, buffered packet input */
619 struct buf_packet *intp;
620 int status, len;
622 if (!dev->endpoint[EP2I(ep)].interrupt_started &&
623 !dev->endpoint[EP2I(ep)].interrupt_error) {
624 struct usb_redir_start_interrupt_receiving_header start_int = {
625 .endpoint = ep,
627 /* No id, we look at the ep when receiving a status back */
628 usbredirparser_send_start_interrupt_receiving(dev->parser, 0,
629 &start_int);
630 usbredirparser_do_write(dev->parser);
631 DPRINTF("interrupt recv started ep %02X\n", ep);
632 dev->endpoint[EP2I(ep)].interrupt_started = 1;
633 /* We don't really want to drop interrupt packets ever, but
634 having some upper limit to how much we buffer is good. */
635 dev->endpoint[EP2I(ep)].bufpq_target_size = 1000;
636 dev->endpoint[EP2I(ep)].bufpq_dropping_packets = 0;
639 intp = QTAILQ_FIRST(&dev->endpoint[EP2I(ep)].bufpq);
640 if (intp == NULL) {
641 DPRINTF2("interrupt-token-in ep %02X, no intp\n", ep);
642 /* Check interrupt_error for stream errors */
643 status = dev->endpoint[EP2I(ep)].interrupt_error;
644 dev->endpoint[EP2I(ep)].interrupt_error = 0;
645 if (status) {
646 return usbredir_handle_status(dev, status, 0);
648 return USB_RET_NAK;
650 DPRINTF("interrupt-token-in ep %02X status %d len %d\n", ep,
651 intp->status, intp->len);
653 status = intp->status;
654 if (status != usb_redir_success) {
655 bufp_free(dev, intp, ep);
656 return usbredir_handle_status(dev, status, 0);
659 len = intp->len;
660 if (len > p->iov.size) {
661 ERROR("received int data is larger then packet ep %02X\n", ep);
662 bufp_free(dev, intp, ep);
663 return USB_RET_BABBLE;
665 usb_packet_copy(p, intp->data, len);
666 bufp_free(dev, intp, ep);
667 return len;
668 } else {
669 /* Output interrupt endpoint, normal async operation */
670 struct usb_redir_interrupt_packet_header interrupt_packet;
671 uint8_t buf[p->iov.size];
673 DPRINTF("interrupt-out ep %02X len %zd id %"PRIu64"\n", ep,
674 p->iov.size, p->id);
676 if (usbredir_already_in_flight(dev, p->id)) {
677 return USB_RET_ASYNC;
680 interrupt_packet.endpoint = ep;
681 interrupt_packet.length = p->iov.size;
683 usb_packet_copy(p, buf, p->iov.size);
684 usbredir_log_data(dev, "interrupt data out:", buf, p->iov.size);
685 usbredirparser_send_interrupt_packet(dev->parser, p->id,
686 &interrupt_packet, buf, p->iov.size);
687 usbredirparser_do_write(dev->parser);
688 return USB_RET_ASYNC;
692 static void usbredir_stop_interrupt_receiving(USBRedirDevice *dev,
693 uint8_t ep)
695 struct usb_redir_stop_interrupt_receiving_header stop_interrupt_recv = {
696 .endpoint = ep
698 if (dev->endpoint[EP2I(ep)].interrupt_started) {
699 usbredirparser_send_stop_interrupt_receiving(dev->parser, 0,
700 &stop_interrupt_recv);
701 DPRINTF("interrupt recv stopped ep %02X\n", ep);
702 dev->endpoint[EP2I(ep)].interrupt_started = 0;
704 dev->endpoint[EP2I(ep)].interrupt_error = 0;
705 usbredir_free_bufpq(dev, ep);
708 static int usbredir_handle_data(USBDevice *udev, USBPacket *p)
710 USBRedirDevice *dev = DO_UPCAST(USBRedirDevice, dev, udev);
711 uint8_t ep;
713 ep = p->ep->nr;
714 if (p->pid == USB_TOKEN_IN) {
715 ep |= USB_DIR_IN;
718 switch (dev->endpoint[EP2I(ep)].type) {
719 case USB_ENDPOINT_XFER_CONTROL:
720 ERROR("handle_data called for control transfer on ep %02X\n", ep);
721 return USB_RET_NAK;
722 case USB_ENDPOINT_XFER_ISOC:
723 return usbredir_handle_iso_data(dev, p, ep);
724 case USB_ENDPOINT_XFER_BULK:
725 if (p->state == USB_PACKET_SETUP && p->pid == USB_TOKEN_IN &&
726 p->ep->pipeline) {
727 return USB_RET_ADD_TO_QUEUE;
729 return usbredir_handle_bulk_data(dev, p, ep);
730 case USB_ENDPOINT_XFER_INT:
731 return usbredir_handle_interrupt_data(dev, p, ep);
732 default:
733 ERROR("handle_data ep %02X has unknown type %d\n", ep,
734 dev->endpoint[EP2I(ep)].type);
735 return USB_RET_NAK;
739 static void usbredir_flush_ep_queue(USBDevice *dev, USBEndpoint *ep)
741 if (ep->pid == USB_TOKEN_IN && ep->pipeline) {
742 usb_ep_combine_input_packets(ep);
746 static int usbredir_set_config(USBRedirDevice *dev, USBPacket *p,
747 int config)
749 struct usb_redir_set_configuration_header set_config;
750 int i;
752 DPRINTF("set config %d id %"PRIu64"\n", config, p->id);
754 for (i = 0; i < MAX_ENDPOINTS; i++) {
755 switch (dev->endpoint[i].type) {
756 case USB_ENDPOINT_XFER_ISOC:
757 usbredir_stop_iso_stream(dev, I2EP(i));
758 break;
759 case USB_ENDPOINT_XFER_INT:
760 if (i & 0x10) {
761 usbredir_stop_interrupt_receiving(dev, I2EP(i));
763 break;
765 usbredir_free_bufpq(dev, I2EP(i));
768 set_config.configuration = config;
769 usbredirparser_send_set_configuration(dev->parser, p->id, &set_config);
770 usbredirparser_do_write(dev->parser);
771 return USB_RET_ASYNC;
774 static int usbredir_get_config(USBRedirDevice *dev, USBPacket *p)
776 DPRINTF("get config id %"PRIu64"\n", p->id);
778 usbredirparser_send_get_configuration(dev->parser, p->id);
779 usbredirparser_do_write(dev->parser);
780 return USB_RET_ASYNC;
783 static int usbredir_set_interface(USBRedirDevice *dev, USBPacket *p,
784 int interface, int alt)
786 struct usb_redir_set_alt_setting_header set_alt;
787 int i;
789 DPRINTF("set interface %d alt %d id %"PRIu64"\n", interface, alt, p->id);
791 for (i = 0; i < MAX_ENDPOINTS; i++) {
792 if (dev->endpoint[i].interface == interface) {
793 switch (dev->endpoint[i].type) {
794 case USB_ENDPOINT_XFER_ISOC:
795 usbredir_stop_iso_stream(dev, I2EP(i));
796 break;
797 case USB_ENDPOINT_XFER_INT:
798 if (i & 0x10) {
799 usbredir_stop_interrupt_receiving(dev, I2EP(i));
801 break;
803 usbredir_free_bufpq(dev, I2EP(i));
807 set_alt.interface = interface;
808 set_alt.alt = alt;
809 usbredirparser_send_set_alt_setting(dev->parser, p->id, &set_alt);
810 usbredirparser_do_write(dev->parser);
811 return USB_RET_ASYNC;
814 static int usbredir_get_interface(USBRedirDevice *dev, USBPacket *p,
815 int interface)
817 struct usb_redir_get_alt_setting_header get_alt;
819 DPRINTF("get interface %d id %"PRIu64"\n", interface, p->id);
821 get_alt.interface = interface;
822 usbredirparser_send_get_alt_setting(dev->parser, p->id, &get_alt);
823 usbredirparser_do_write(dev->parser);
824 return USB_RET_ASYNC;
827 static int usbredir_handle_control(USBDevice *udev, USBPacket *p,
828 int request, int value, int index, int length, uint8_t *data)
830 USBRedirDevice *dev = DO_UPCAST(USBRedirDevice, dev, udev);
831 struct usb_redir_control_packet_header control_packet;
833 if (usbredir_already_in_flight(dev, p->id)) {
834 return USB_RET_ASYNC;
837 /* Special cases for certain standard device requests */
838 switch (request) {
839 case DeviceOutRequest | USB_REQ_SET_ADDRESS:
840 DPRINTF("set address %d\n", value);
841 dev->dev.addr = value;
842 return 0;
843 case DeviceOutRequest | USB_REQ_SET_CONFIGURATION:
844 return usbredir_set_config(dev, p, value & 0xff);
845 case DeviceRequest | USB_REQ_GET_CONFIGURATION:
846 return usbredir_get_config(dev, p);
847 case InterfaceOutRequest | USB_REQ_SET_INTERFACE:
848 return usbredir_set_interface(dev, p, index, value);
849 case InterfaceRequest | USB_REQ_GET_INTERFACE:
850 return usbredir_get_interface(dev, p, index);
853 /* Normal ctrl requests, note request is (bRequestType << 8) | bRequest */
854 DPRINTF(
855 "ctrl-out type 0x%x req 0x%x val 0x%x index %d len %d id %"PRIu64"\n",
856 request >> 8, request & 0xff, value, index, length, p->id);
858 control_packet.request = request & 0xFF;
859 control_packet.requesttype = request >> 8;
860 control_packet.endpoint = control_packet.requesttype & USB_DIR_IN;
861 control_packet.value = value;
862 control_packet.index = index;
863 control_packet.length = length;
865 if (control_packet.requesttype & USB_DIR_IN) {
866 usbredirparser_send_control_packet(dev->parser, p->id,
867 &control_packet, NULL, 0);
868 } else {
869 usbredir_log_data(dev, "ctrl data out:", data, length);
870 usbredirparser_send_control_packet(dev->parser, p->id,
871 &control_packet, data, length);
873 usbredirparser_do_write(dev->parser);
874 return USB_RET_ASYNC;
878 * Close events can be triggered by usbredirparser_do_write which gets called
879 * from within the USBDevice data / control packet callbacks and doing a
880 * usb_detach from within these callbacks is not a good idea.
882 * So we use a bh handler to take care of close events.
884 static void usbredir_chardev_close_bh(void *opaque)
886 USBRedirDevice *dev = opaque;
888 usbredir_device_disconnect(dev);
890 if (dev->parser) {
891 DPRINTF("destroying usbredirparser\n");
892 usbredirparser_destroy(dev->parser);
893 dev->parser = NULL;
897 static void usbredir_create_parser(USBRedirDevice *dev)
899 uint32_t caps[USB_REDIR_CAPS_SIZE] = { 0, };
900 int flags = 0;
902 DPRINTF("creating usbredirparser\n");
904 dev->parser = qemu_oom_check(usbredirparser_create());
905 dev->parser->priv = dev;
906 dev->parser->log_func = usbredir_log;
907 dev->parser->read_func = usbredir_read;
908 dev->parser->write_func = usbredir_write;
909 dev->parser->hello_func = usbredir_hello;
910 dev->parser->device_connect_func = usbredir_device_connect;
911 dev->parser->device_disconnect_func = usbredir_device_disconnect;
912 dev->parser->interface_info_func = usbredir_interface_info;
913 dev->parser->ep_info_func = usbredir_ep_info;
914 dev->parser->configuration_status_func = usbredir_configuration_status;
915 dev->parser->alt_setting_status_func = usbredir_alt_setting_status;
916 dev->parser->iso_stream_status_func = usbredir_iso_stream_status;
917 dev->parser->interrupt_receiving_status_func =
918 usbredir_interrupt_receiving_status;
919 dev->parser->bulk_streams_status_func = usbredir_bulk_streams_status;
920 dev->parser->control_packet_func = usbredir_control_packet;
921 dev->parser->bulk_packet_func = usbredir_bulk_packet;
922 dev->parser->iso_packet_func = usbredir_iso_packet;
923 dev->parser->interrupt_packet_func = usbredir_interrupt_packet;
924 dev->read_buf = NULL;
925 dev->read_buf_size = 0;
927 usbredirparser_caps_set_cap(caps, usb_redir_cap_connect_device_version);
928 usbredirparser_caps_set_cap(caps, usb_redir_cap_filter);
929 usbredirparser_caps_set_cap(caps, usb_redir_cap_ep_info_max_packet_size);
930 usbredirparser_caps_set_cap(caps, usb_redir_cap_64bits_ids);
931 usbredirparser_caps_set_cap(caps, usb_redir_cap_32bits_bulk_length);
933 if (runstate_check(RUN_STATE_INMIGRATE)) {
934 flags |= usbredirparser_fl_no_hello;
936 usbredirparser_init(dev->parser, VERSION, caps, USB_REDIR_CAPS_SIZE,
937 flags);
938 usbredirparser_do_write(dev->parser);
941 static void usbredir_reject_device(USBRedirDevice *dev)
943 usbredir_device_disconnect(dev);
944 if (usbredirparser_peer_has_cap(dev->parser, usb_redir_cap_filter)) {
945 usbredirparser_send_filter_reject(dev->parser);
946 usbredirparser_do_write(dev->parser);
950 static void usbredir_do_attach(void *opaque)
952 USBRedirDevice *dev = opaque;
954 /* In order to work properly with XHCI controllers we need these caps */
955 if ((dev->dev.port->speedmask & USB_SPEED_MASK_SUPER) && !(
956 usbredirparser_peer_has_cap(dev->parser,
957 usb_redir_cap_ep_info_max_packet_size) &&
958 usbredirparser_peer_has_cap(dev->parser,
959 usb_redir_cap_64bits_ids))) {
960 ERROR("usb-redir-host lacks capabilities needed for use with XHCI\n");
961 usbredir_reject_device(dev);
962 return;
965 if (usb_device_attach(&dev->dev) != 0) {
966 WARNING("rejecting device due to speed mismatch\n");
967 usbredir_reject_device(dev);
972 * chardev callbacks
975 static int usbredir_chardev_can_read(void *opaque)
977 USBRedirDevice *dev = opaque;
979 if (!dev->parser) {
980 WARNING("chardev_can_read called on non open chardev!\n");
981 return 0;
984 /* Don't read new data from the chardev until our state is fully synced */
985 if (!runstate_check(RUN_STATE_RUNNING)) {
986 return 0;
989 /* usbredir_parser_do_read will consume *all* data we give it */
990 return 1024 * 1024;
993 static void usbredir_chardev_read(void *opaque, const uint8_t *buf, int size)
995 USBRedirDevice *dev = opaque;
997 /* No recursion allowed! */
998 assert(dev->read_buf == NULL);
1000 dev->read_buf = buf;
1001 dev->read_buf_size = size;
1003 usbredirparser_do_read(dev->parser);
1004 /* Send any acks, etc. which may be queued now */
1005 usbredirparser_do_write(dev->parser);
1008 static void usbredir_chardev_event(void *opaque, int event)
1010 USBRedirDevice *dev = opaque;
1012 switch (event) {
1013 case CHR_EVENT_OPENED:
1014 DPRINTF("chardev open\n");
1015 /* Make sure any pending closes are handled (no-op if none pending) */
1016 usbredir_chardev_close_bh(dev);
1017 qemu_bh_cancel(dev->chardev_close_bh);
1018 usbredir_create_parser(dev);
1019 break;
1020 case CHR_EVENT_CLOSED:
1021 DPRINTF("chardev close\n");
1022 qemu_bh_schedule(dev->chardev_close_bh);
1023 break;
1028 * init + destroy
1031 static void usbredir_vm_state_change(void *priv, int running, RunState state)
1033 USBRedirDevice *dev = priv;
1035 if (state == RUN_STATE_RUNNING && dev->parser != NULL) {
1036 usbredirparser_do_write(dev->parser); /* Flush any pending writes */
1040 static int usbredir_initfn(USBDevice *udev)
1042 USBRedirDevice *dev = DO_UPCAST(USBRedirDevice, dev, udev);
1043 int i;
1045 if (dev->cs == NULL) {
1046 qerror_report(QERR_MISSING_PARAMETER, "chardev");
1047 return -1;
1050 if (dev->filter_str) {
1051 i = usbredirfilter_string_to_rules(dev->filter_str, ":", "|",
1052 &dev->filter_rules,
1053 &dev->filter_rules_count);
1054 if (i) {
1055 qerror_report(QERR_INVALID_PARAMETER_VALUE, "filter",
1056 "a usb device filter string");
1057 return -1;
1061 dev->chardev_close_bh = qemu_bh_new(usbredir_chardev_close_bh, dev);
1062 dev->attach_timer = qemu_new_timer_ms(vm_clock, usbredir_do_attach, dev);
1064 packet_id_queue_init(&dev->cancelled, dev, "cancelled");
1065 packet_id_queue_init(&dev->already_in_flight, dev, "already-in-flight");
1066 for (i = 0; i < MAX_ENDPOINTS; i++) {
1067 QTAILQ_INIT(&dev->endpoint[i].bufpq);
1070 /* We'll do the attach once we receive the speed from the usb-host */
1071 udev->auto_attach = 0;
1073 /* Will be cleared during setup when we find conflicts */
1074 dev->compatible_speedmask = USB_SPEED_MASK_FULL;
1076 /* Let the backend know we are ready */
1077 qemu_chr_fe_open(dev->cs);
1078 qemu_chr_add_handlers(dev->cs, usbredir_chardev_can_read,
1079 usbredir_chardev_read, usbredir_chardev_event, dev);
1081 qemu_add_vm_change_state_handler(usbredir_vm_state_change, dev);
1082 add_boot_device_path(dev->bootindex, &udev->qdev, NULL);
1083 return 0;
1086 static void usbredir_cleanup_device_queues(USBRedirDevice *dev)
1088 int i;
1090 packet_id_queue_empty(&dev->cancelled);
1091 packet_id_queue_empty(&dev->already_in_flight);
1092 for (i = 0; i < MAX_ENDPOINTS; i++) {
1093 usbredir_free_bufpq(dev, I2EP(i));
1097 static void usbredir_handle_destroy(USBDevice *udev)
1099 USBRedirDevice *dev = DO_UPCAST(USBRedirDevice, dev, udev);
1101 qemu_chr_fe_close(dev->cs);
1102 qemu_chr_delete(dev->cs);
1103 /* Note must be done after qemu_chr_close, as that causes a close event */
1104 qemu_bh_delete(dev->chardev_close_bh);
1106 qemu_del_timer(dev->attach_timer);
1107 qemu_free_timer(dev->attach_timer);
1109 usbredir_cleanup_device_queues(dev);
1111 if (dev->parser) {
1112 usbredirparser_destroy(dev->parser);
1115 free(dev->filter_rules);
1118 static int usbredir_check_filter(USBRedirDevice *dev)
1120 if (dev->interface_info.interface_count == NO_INTERFACE_INFO) {
1121 ERROR("No interface info for device\n");
1122 goto error;
1125 if (dev->filter_rules) {
1126 if (!usbredirparser_peer_has_cap(dev->parser,
1127 usb_redir_cap_connect_device_version)) {
1128 ERROR("Device filter specified and peer does not have the "
1129 "connect_device_version capability\n");
1130 goto error;
1133 if (usbredirfilter_check(
1134 dev->filter_rules,
1135 dev->filter_rules_count,
1136 dev->device_info.device_class,
1137 dev->device_info.device_subclass,
1138 dev->device_info.device_protocol,
1139 dev->interface_info.interface_class,
1140 dev->interface_info.interface_subclass,
1141 dev->interface_info.interface_protocol,
1142 dev->interface_info.interface_count,
1143 dev->device_info.vendor_id,
1144 dev->device_info.product_id,
1145 dev->device_info.device_version_bcd,
1146 0) != 0) {
1147 goto error;
1151 return 0;
1153 error:
1154 usbredir_reject_device(dev);
1155 return -1;
1159 * usbredirparser packet complete callbacks
1162 static int usbredir_handle_status(USBRedirDevice *dev,
1163 int status, int actual_len)
1165 switch (status) {
1166 case usb_redir_success:
1167 return actual_len;
1168 case usb_redir_stall:
1169 return USB_RET_STALL;
1170 case usb_redir_cancelled:
1172 * When the usbredir-host unredirects a device, it will report a status
1173 * of cancelled for all pending packets, followed by a disconnect msg.
1175 return USB_RET_IOERROR;
1176 case usb_redir_inval:
1177 WARNING("got invalid param error from usb-host?\n");
1178 return USB_RET_IOERROR;
1179 case usb_redir_babble:
1180 return USB_RET_BABBLE;
1181 case usb_redir_ioerror:
1182 case usb_redir_timeout:
1183 default:
1184 return USB_RET_IOERROR;
1188 static void usbredir_hello(void *priv, struct usb_redir_hello_header *h)
1190 USBRedirDevice *dev = priv;
1192 /* Try to send the filter info now that we've the usb-host's caps */
1193 if (usbredirparser_peer_has_cap(dev->parser, usb_redir_cap_filter) &&
1194 dev->filter_rules) {
1195 usbredirparser_send_filter_filter(dev->parser, dev->filter_rules,
1196 dev->filter_rules_count);
1197 usbredirparser_do_write(dev->parser);
1201 static void usbredir_device_connect(void *priv,
1202 struct usb_redir_device_connect_header *device_connect)
1204 USBRedirDevice *dev = priv;
1205 const char *speed;
1207 if (qemu_timer_pending(dev->attach_timer) || dev->dev.attached) {
1208 ERROR("Received device connect while already connected\n");
1209 return;
1212 switch (device_connect->speed) {
1213 case usb_redir_speed_low:
1214 speed = "low speed";
1215 dev->dev.speed = USB_SPEED_LOW;
1216 dev->compatible_speedmask &= ~USB_SPEED_MASK_FULL;
1217 break;
1218 case usb_redir_speed_full:
1219 speed = "full speed";
1220 dev->dev.speed = USB_SPEED_FULL;
1221 break;
1222 case usb_redir_speed_high:
1223 speed = "high speed";
1224 dev->dev.speed = USB_SPEED_HIGH;
1225 break;
1226 case usb_redir_speed_super:
1227 speed = "super speed";
1228 dev->dev.speed = USB_SPEED_SUPER;
1229 break;
1230 default:
1231 speed = "unknown speed";
1232 dev->dev.speed = USB_SPEED_FULL;
1235 if (usbredirparser_peer_has_cap(dev->parser,
1236 usb_redir_cap_connect_device_version)) {
1237 INFO("attaching %s device %04x:%04x version %d.%d class %02x\n",
1238 speed, device_connect->vendor_id, device_connect->product_id,
1239 ((device_connect->device_version_bcd & 0xf000) >> 12) * 10 +
1240 ((device_connect->device_version_bcd & 0x0f00) >> 8),
1241 ((device_connect->device_version_bcd & 0x00f0) >> 4) * 10 +
1242 ((device_connect->device_version_bcd & 0x000f) >> 0),
1243 device_connect->device_class);
1244 } else {
1245 INFO("attaching %s device %04x:%04x class %02x\n", speed,
1246 device_connect->vendor_id, device_connect->product_id,
1247 device_connect->device_class);
1250 dev->dev.speedmask = (1 << dev->dev.speed) | dev->compatible_speedmask;
1251 dev->device_info = *device_connect;
1253 if (usbredir_check_filter(dev)) {
1254 WARNING("Device %04x:%04x rejected by device filter, not attaching\n",
1255 device_connect->vendor_id, device_connect->product_id);
1256 return;
1259 qemu_mod_timer(dev->attach_timer, dev->next_attach_time);
1262 static void usbredir_device_disconnect(void *priv)
1264 USBRedirDevice *dev = priv;
1265 int i;
1267 /* Stop any pending attaches */
1268 qemu_del_timer(dev->attach_timer);
1270 if (dev->dev.attached) {
1271 DPRINTF("detaching device\n");
1272 usb_device_detach(&dev->dev);
1274 * Delay next usb device attach to give the guest a chance to see
1275 * see the detach / attach in case of quick close / open succession
1277 dev->next_attach_time = qemu_get_clock_ms(vm_clock) + 200;
1280 /* Reset state so that the next dev connected starts with a clean slate */
1281 usbredir_cleanup_device_queues(dev);
1282 memset(dev->endpoint, 0, sizeof(dev->endpoint));
1283 for (i = 0; i < MAX_ENDPOINTS; i++) {
1284 QTAILQ_INIT(&dev->endpoint[i].bufpq);
1286 usb_ep_init(&dev->dev);
1287 dev->interface_info.interface_count = NO_INTERFACE_INFO;
1288 dev->dev.addr = 0;
1289 dev->dev.speed = 0;
1290 dev->compatible_speedmask = USB_SPEED_MASK_FULL;
1293 static void usbredir_interface_info(void *priv,
1294 struct usb_redir_interface_info_header *interface_info)
1296 USBRedirDevice *dev = priv;
1298 dev->interface_info = *interface_info;
1301 * If we receive interface info after the device has already been
1302 * connected (ie on a set_config), re-check the filter.
1304 if (qemu_timer_pending(dev->attach_timer) || dev->dev.attached) {
1305 if (usbredir_check_filter(dev)) {
1306 ERROR("Device no longer matches filter after interface info "
1307 "change, disconnecting!\n");
1312 static void usbredir_mark_speed_incompatible(USBRedirDevice *dev, int speed)
1314 dev->compatible_speedmask &= ~(1 << speed);
1315 dev->dev.speedmask = (1 << dev->dev.speed) | dev->compatible_speedmask;
1318 static void usbredir_set_pipeline(USBRedirDevice *dev, struct USBEndpoint *uep)
1320 if (uep->type != USB_ENDPOINT_XFER_BULK) {
1321 return;
1323 if (uep->pid == USB_TOKEN_OUT) {
1324 uep->pipeline = true;
1326 if (uep->pid == USB_TOKEN_IN && uep->max_packet_size != 0 &&
1327 usbredirparser_peer_has_cap(dev->parser,
1328 usb_redir_cap_32bits_bulk_length)) {
1329 uep->pipeline = true;
1333 static void usbredir_setup_usb_eps(USBRedirDevice *dev)
1335 struct USBEndpoint *usb_ep;
1336 int i, pid;
1338 for (i = 0; i < MAX_ENDPOINTS; i++) {
1339 pid = (i & 0x10) ? USB_TOKEN_IN : USB_TOKEN_OUT;
1340 usb_ep = usb_ep_get(&dev->dev, pid, i & 0x0f);
1341 usb_ep->type = dev->endpoint[i].type;
1342 usb_ep->ifnum = dev->endpoint[i].interface;
1343 usb_ep->max_packet_size = dev->endpoint[i].max_packet_size;
1344 usbredir_set_pipeline(dev, usb_ep);
1348 static void usbredir_ep_info(void *priv,
1349 struct usb_redir_ep_info_header *ep_info)
1351 USBRedirDevice *dev = priv;
1352 int i;
1354 for (i = 0; i < MAX_ENDPOINTS; i++) {
1355 dev->endpoint[i].type = ep_info->type[i];
1356 dev->endpoint[i].interval = ep_info->interval[i];
1357 dev->endpoint[i].interface = ep_info->interface[i];
1358 if (usbredirparser_peer_has_cap(dev->parser,
1359 usb_redir_cap_ep_info_max_packet_size)) {
1360 dev->endpoint[i].max_packet_size = ep_info->max_packet_size[i];
1362 switch (dev->endpoint[i].type) {
1363 case usb_redir_type_invalid:
1364 break;
1365 case usb_redir_type_iso:
1366 usbredir_mark_speed_incompatible(dev, USB_SPEED_FULL);
1367 /* Fall through */
1368 case usb_redir_type_interrupt:
1369 if (!usbredirparser_peer_has_cap(dev->parser,
1370 usb_redir_cap_ep_info_max_packet_size) ||
1371 ep_info->max_packet_size[i] > 64) {
1372 usbredir_mark_speed_incompatible(dev, USB_SPEED_FULL);
1374 if (dev->endpoint[i].interval == 0) {
1375 ERROR("Received 0 interval for isoc or irq endpoint\n");
1376 usbredir_reject_device(dev);
1377 return;
1379 /* Fall through */
1380 case usb_redir_type_control:
1381 case usb_redir_type_bulk:
1382 DPRINTF("ep: %02X type: %d interface: %d\n", I2EP(i),
1383 dev->endpoint[i].type, dev->endpoint[i].interface);
1384 break;
1385 default:
1386 ERROR("Received invalid endpoint type\n");
1387 usbredir_reject_device(dev);
1388 return;
1391 /* The new ep info may have caused a speed incompatibility, recheck */
1392 if (dev->dev.attached &&
1393 !(dev->dev.port->speedmask & dev->dev.speedmask)) {
1394 ERROR("Device no longer matches speed after endpoint info change, "
1395 "disconnecting!\n");
1396 usbredir_reject_device(dev);
1397 return;
1399 usbredir_setup_usb_eps(dev);
1402 static void usbredir_configuration_status(void *priv, uint64_t id,
1403 struct usb_redir_configuration_status_header *config_status)
1405 USBRedirDevice *dev = priv;
1406 USBPacket *p;
1407 int len = 0;
1409 DPRINTF("set config status %d config %d id %"PRIu64"\n",
1410 config_status->status, config_status->configuration, id);
1412 p = usbredir_find_packet_by_id(dev, 0, id);
1413 if (p) {
1414 if (dev->dev.setup_buf[0] & USB_DIR_IN) {
1415 dev->dev.data_buf[0] = config_status->configuration;
1416 len = 1;
1418 p->result = usbredir_handle_status(dev, config_status->status, len);
1419 usb_generic_async_ctrl_complete(&dev->dev, p);
1423 static void usbredir_alt_setting_status(void *priv, uint64_t id,
1424 struct usb_redir_alt_setting_status_header *alt_setting_status)
1426 USBRedirDevice *dev = priv;
1427 USBPacket *p;
1428 int len = 0;
1430 DPRINTF("alt status %d intf %d alt %d id: %"PRIu64"\n",
1431 alt_setting_status->status, alt_setting_status->interface,
1432 alt_setting_status->alt, id);
1434 p = usbredir_find_packet_by_id(dev, 0, id);
1435 if (p) {
1436 if (dev->dev.setup_buf[0] & USB_DIR_IN) {
1437 dev->dev.data_buf[0] = alt_setting_status->alt;
1438 len = 1;
1440 p->result =
1441 usbredir_handle_status(dev, alt_setting_status->status, len);
1442 usb_generic_async_ctrl_complete(&dev->dev, p);
1446 static void usbredir_iso_stream_status(void *priv, uint64_t id,
1447 struct usb_redir_iso_stream_status_header *iso_stream_status)
1449 USBRedirDevice *dev = priv;
1450 uint8_t ep = iso_stream_status->endpoint;
1452 DPRINTF("iso status %d ep %02X id %"PRIu64"\n", iso_stream_status->status,
1453 ep, id);
1455 if (!dev->dev.attached || !dev->endpoint[EP2I(ep)].iso_started) {
1456 return;
1459 dev->endpoint[EP2I(ep)].iso_error = iso_stream_status->status;
1460 if (iso_stream_status->status == usb_redir_stall) {
1461 DPRINTF("iso stream stopped by peer ep %02X\n", ep);
1462 dev->endpoint[EP2I(ep)].iso_started = 0;
1466 static void usbredir_interrupt_receiving_status(void *priv, uint64_t id,
1467 struct usb_redir_interrupt_receiving_status_header
1468 *interrupt_receiving_status)
1470 USBRedirDevice *dev = priv;
1471 uint8_t ep = interrupt_receiving_status->endpoint;
1473 DPRINTF("interrupt recv status %d ep %02X id %"PRIu64"\n",
1474 interrupt_receiving_status->status, ep, id);
1476 if (!dev->dev.attached || !dev->endpoint[EP2I(ep)].interrupt_started) {
1477 return;
1480 dev->endpoint[EP2I(ep)].interrupt_error =
1481 interrupt_receiving_status->status;
1482 if (interrupt_receiving_status->status == usb_redir_stall) {
1483 DPRINTF("interrupt receiving stopped by peer ep %02X\n", ep);
1484 dev->endpoint[EP2I(ep)].interrupt_started = 0;
1488 static void usbredir_bulk_streams_status(void *priv, uint64_t id,
1489 struct usb_redir_bulk_streams_status_header *bulk_streams_status)
1493 static void usbredir_control_packet(void *priv, uint64_t id,
1494 struct usb_redir_control_packet_header *control_packet,
1495 uint8_t *data, int data_len)
1497 USBRedirDevice *dev = priv;
1498 USBPacket *p;
1499 int len = control_packet->length;
1501 DPRINTF("ctrl-in status %d len %d id %"PRIu64"\n", control_packet->status,
1502 len, id);
1504 p = usbredir_find_packet_by_id(dev, 0, id);
1505 if (p) {
1506 len = usbredir_handle_status(dev, control_packet->status, len);
1507 if (len > 0) {
1508 usbredir_log_data(dev, "ctrl data in:", data, data_len);
1509 if (data_len <= sizeof(dev->dev.data_buf)) {
1510 memcpy(dev->dev.data_buf, data, data_len);
1511 } else {
1512 ERROR("ctrl buffer too small (%d > %zu)\n",
1513 data_len, sizeof(dev->dev.data_buf));
1514 len = USB_RET_STALL;
1517 p->result = len;
1518 usb_generic_async_ctrl_complete(&dev->dev, p);
1520 free(data);
1523 static void usbredir_bulk_packet(void *priv, uint64_t id,
1524 struct usb_redir_bulk_packet_header *bulk_packet,
1525 uint8_t *data, int data_len)
1527 USBRedirDevice *dev = priv;
1528 uint8_t ep = bulk_packet->endpoint;
1529 int len = (bulk_packet->length_high << 16) | bulk_packet->length;
1530 USBPacket *p;
1532 DPRINTF("bulk-in status %d ep %02X len %d id %"PRIu64"\n",
1533 bulk_packet->status, ep, len, id);
1535 p = usbredir_find_packet_by_id(dev, ep, id);
1536 if (p) {
1537 size_t size = (p->combined) ? p->combined->iov.size : p->iov.size;
1538 len = usbredir_handle_status(dev, bulk_packet->status, len);
1539 if (len > 0) {
1540 usbredir_log_data(dev, "bulk data in:", data, data_len);
1541 if (data_len <= size) {
1542 if (p->combined) {
1543 iov_from_buf(p->combined->iov.iov, p->combined->iov.niov,
1544 0, data, data_len);
1545 } else {
1546 usb_packet_copy(p, data, data_len);
1548 } else {
1549 ERROR("bulk got more data then requested (%d > %zd)\n",
1550 data_len, p->iov.size);
1551 len = USB_RET_BABBLE;
1554 p->result = len;
1555 if (p->pid == USB_TOKEN_IN && p->ep->pipeline) {
1556 usb_combined_input_packet_complete(&dev->dev, p);
1557 } else {
1558 usb_packet_complete(&dev->dev, p);
1561 free(data);
1564 static void usbredir_iso_packet(void *priv, uint64_t id,
1565 struct usb_redir_iso_packet_header *iso_packet,
1566 uint8_t *data, int data_len)
1568 USBRedirDevice *dev = priv;
1569 uint8_t ep = iso_packet->endpoint;
1571 DPRINTF2("iso-in status %d ep %02X len %d id %"PRIu64"\n",
1572 iso_packet->status, ep, data_len, id);
1574 if (dev->endpoint[EP2I(ep)].type != USB_ENDPOINT_XFER_ISOC) {
1575 ERROR("received iso packet for non iso endpoint %02X\n", ep);
1576 free(data);
1577 return;
1580 if (dev->endpoint[EP2I(ep)].iso_started == 0) {
1581 DPRINTF("received iso packet for non started stream ep %02X\n", ep);
1582 free(data);
1583 return;
1586 /* bufp_alloc also adds the packet to the ep queue */
1587 bufp_alloc(dev, data, data_len, iso_packet->status, ep);
1590 static void usbredir_interrupt_packet(void *priv, uint64_t id,
1591 struct usb_redir_interrupt_packet_header *interrupt_packet,
1592 uint8_t *data, int data_len)
1594 USBRedirDevice *dev = priv;
1595 uint8_t ep = interrupt_packet->endpoint;
1597 DPRINTF("interrupt-in status %d ep %02X len %d id %"PRIu64"\n",
1598 interrupt_packet->status, ep, data_len, id);
1600 if (dev->endpoint[EP2I(ep)].type != USB_ENDPOINT_XFER_INT) {
1601 ERROR("received int packet for non interrupt endpoint %02X\n", ep);
1602 free(data);
1603 return;
1606 if (ep & USB_DIR_IN) {
1607 if (dev->endpoint[EP2I(ep)].interrupt_started == 0) {
1608 DPRINTF("received int packet while not started ep %02X\n", ep);
1609 free(data);
1610 return;
1613 /* bufp_alloc also adds the packet to the ep queue */
1614 bufp_alloc(dev, data, data_len, interrupt_packet->status, ep);
1615 } else {
1616 int len = interrupt_packet->length;
1618 USBPacket *p = usbredir_find_packet_by_id(dev, ep, id);
1619 if (p) {
1620 p->result = usbredir_handle_status(dev,
1621 interrupt_packet->status, len);
1622 usb_packet_complete(&dev->dev, p);
1628 * Migration code
1631 static void usbredir_pre_save(void *priv)
1633 USBRedirDevice *dev = priv;
1635 usbredir_fill_already_in_flight(dev);
1638 static int usbredir_post_load(void *priv, int version_id)
1640 USBRedirDevice *dev = priv;
1642 switch (dev->device_info.speed) {
1643 case usb_redir_speed_low:
1644 dev->dev.speed = USB_SPEED_LOW;
1645 break;
1646 case usb_redir_speed_full:
1647 dev->dev.speed = USB_SPEED_FULL;
1648 break;
1649 case usb_redir_speed_high:
1650 dev->dev.speed = USB_SPEED_HIGH;
1651 break;
1652 case usb_redir_speed_super:
1653 dev->dev.speed = USB_SPEED_SUPER;
1654 break;
1655 default:
1656 dev->dev.speed = USB_SPEED_FULL;
1658 dev->dev.speedmask = (1 << dev->dev.speed);
1660 usbredir_setup_usb_eps(dev);
1662 return 0;
1665 /* For usbredirparser migration */
1666 static void usbredir_put_parser(QEMUFile *f, void *priv, size_t unused)
1668 USBRedirDevice *dev = priv;
1669 uint8_t *data;
1670 int len;
1672 if (dev->parser == NULL) {
1673 qemu_put_be32(f, 0);
1674 return;
1677 usbredirparser_serialize(dev->parser, &data, &len);
1678 qemu_oom_check(data);
1680 qemu_put_be32(f, len);
1681 qemu_put_buffer(f, data, len);
1683 free(data);
1686 static int usbredir_get_parser(QEMUFile *f, void *priv, size_t unused)
1688 USBRedirDevice *dev = priv;
1689 uint8_t *data;
1690 int len, ret;
1692 len = qemu_get_be32(f);
1693 if (len == 0) {
1694 return 0;
1698 * If our chardev is not open already at this point the usbredir connection
1699 * has been broken (non seamless migration, or restore from disk).
1701 * In this case create a temporary parser to receive the migration data,
1702 * and schedule the close_bh to report the device as disconnected to the
1703 * guest and to destroy the parser again.
1705 if (dev->parser == NULL) {
1706 WARNING("usb-redir connection broken during migration\n");
1707 usbredir_create_parser(dev);
1708 qemu_bh_schedule(dev->chardev_close_bh);
1711 data = g_malloc(len);
1712 qemu_get_buffer(f, data, len);
1714 ret = usbredirparser_unserialize(dev->parser, data, len);
1716 g_free(data);
1718 return ret;
1721 static const VMStateInfo usbredir_parser_vmstate_info = {
1722 .name = "usb-redir-parser",
1723 .put = usbredir_put_parser,
1724 .get = usbredir_get_parser,
1728 /* For buffered packets (iso/irq) queue migration */
1729 static void usbredir_put_bufpq(QEMUFile *f, void *priv, size_t unused)
1731 struct endp_data *endp = priv;
1732 struct buf_packet *bufp;
1733 int remain = endp->bufpq_size;
1735 qemu_put_be32(f, endp->bufpq_size);
1736 QTAILQ_FOREACH(bufp, &endp->bufpq, next) {
1737 qemu_put_be32(f, bufp->len);
1738 qemu_put_be32(f, bufp->status);
1739 qemu_put_buffer(f, bufp->data, bufp->len);
1740 remain--;
1742 assert(remain == 0);
1745 static int usbredir_get_bufpq(QEMUFile *f, void *priv, size_t unused)
1747 struct endp_data *endp = priv;
1748 struct buf_packet *bufp;
1749 int i;
1751 endp->bufpq_size = qemu_get_be32(f);
1752 for (i = 0; i < endp->bufpq_size; i++) {
1753 bufp = g_malloc(sizeof(struct buf_packet));
1754 bufp->len = qemu_get_be32(f);
1755 bufp->status = qemu_get_be32(f);
1756 bufp->data = qemu_oom_check(malloc(bufp->len)); /* regular malloc! */
1757 qemu_get_buffer(f, bufp->data, bufp->len);
1758 QTAILQ_INSERT_TAIL(&endp->bufpq, bufp, next);
1760 return 0;
1763 static const VMStateInfo usbredir_ep_bufpq_vmstate_info = {
1764 .name = "usb-redir-bufpq",
1765 .put = usbredir_put_bufpq,
1766 .get = usbredir_get_bufpq,
1770 /* For endp_data migration */
1771 static const VMStateDescription usbredir_ep_vmstate = {
1772 .name = "usb-redir-ep",
1773 .version_id = 1,
1774 .minimum_version_id = 1,
1775 .fields = (VMStateField[]) {
1776 VMSTATE_UINT8(type, struct endp_data),
1777 VMSTATE_UINT8(interval, struct endp_data),
1778 VMSTATE_UINT8(interface, struct endp_data),
1779 VMSTATE_UINT16(max_packet_size, struct endp_data),
1780 VMSTATE_UINT8(iso_started, struct endp_data),
1781 VMSTATE_UINT8(iso_error, struct endp_data),
1782 VMSTATE_UINT8(interrupt_started, struct endp_data),
1783 VMSTATE_UINT8(interrupt_error, struct endp_data),
1784 VMSTATE_UINT8(bufpq_prefilled, struct endp_data),
1785 VMSTATE_UINT8(bufpq_dropping_packets, struct endp_data),
1787 .name = "bufpq",
1788 .version_id = 0,
1789 .field_exists = NULL,
1790 .size = 0,
1791 .info = &usbredir_ep_bufpq_vmstate_info,
1792 .flags = VMS_SINGLE,
1793 .offset = 0,
1795 VMSTATE_INT32(bufpq_target_size, struct endp_data),
1796 VMSTATE_END_OF_LIST()
1801 /* For PacketIdQueue migration */
1802 static void usbredir_put_packet_id_q(QEMUFile *f, void *priv, size_t unused)
1804 struct PacketIdQueue *q = priv;
1805 USBRedirDevice *dev = q->dev;
1806 struct PacketIdQueueEntry *e;
1807 int remain = q->size;
1809 DPRINTF("put_packet_id_q %s size %d\n", q->name, q->size);
1810 qemu_put_be32(f, q->size);
1811 QTAILQ_FOREACH(e, &q->head, next) {
1812 qemu_put_be64(f, e->id);
1813 remain--;
1815 assert(remain == 0);
1818 static int usbredir_get_packet_id_q(QEMUFile *f, void *priv, size_t unused)
1820 struct PacketIdQueue *q = priv;
1821 USBRedirDevice *dev = q->dev;
1822 int i, size;
1823 uint64_t id;
1825 size = qemu_get_be32(f);
1826 DPRINTF("get_packet_id_q %s size %d\n", q->name, size);
1827 for (i = 0; i < size; i++) {
1828 id = qemu_get_be64(f);
1829 packet_id_queue_add(q, id);
1831 assert(q->size == size);
1832 return 0;
1835 static const VMStateInfo usbredir_ep_packet_id_q_vmstate_info = {
1836 .name = "usb-redir-packet-id-q",
1837 .put = usbredir_put_packet_id_q,
1838 .get = usbredir_get_packet_id_q,
1841 static const VMStateDescription usbredir_ep_packet_id_queue_vmstate = {
1842 .name = "usb-redir-packet-id-queue",
1843 .version_id = 1,
1844 .minimum_version_id = 1,
1845 .fields = (VMStateField[]) {
1847 .name = "queue",
1848 .version_id = 0,
1849 .field_exists = NULL,
1850 .size = 0,
1851 .info = &usbredir_ep_packet_id_q_vmstate_info,
1852 .flags = VMS_SINGLE,
1853 .offset = 0,
1855 VMSTATE_END_OF_LIST()
1860 /* For usb_redir_device_connect_header migration */
1861 static const VMStateDescription usbredir_device_info_vmstate = {
1862 .name = "usb-redir-device-info",
1863 .version_id = 1,
1864 .minimum_version_id = 1,
1865 .fields = (VMStateField[]) {
1866 VMSTATE_UINT8(speed, struct usb_redir_device_connect_header),
1867 VMSTATE_UINT8(device_class, struct usb_redir_device_connect_header),
1868 VMSTATE_UINT8(device_subclass, struct usb_redir_device_connect_header),
1869 VMSTATE_UINT8(device_protocol, struct usb_redir_device_connect_header),
1870 VMSTATE_UINT16(vendor_id, struct usb_redir_device_connect_header),
1871 VMSTATE_UINT16(product_id, struct usb_redir_device_connect_header),
1872 VMSTATE_UINT16(device_version_bcd,
1873 struct usb_redir_device_connect_header),
1874 VMSTATE_END_OF_LIST()
1879 /* For usb_redir_interface_info_header migration */
1880 static const VMStateDescription usbredir_interface_info_vmstate = {
1881 .name = "usb-redir-interface-info",
1882 .version_id = 1,
1883 .minimum_version_id = 1,
1884 .fields = (VMStateField[]) {
1885 VMSTATE_UINT32(interface_count,
1886 struct usb_redir_interface_info_header),
1887 VMSTATE_UINT8_ARRAY(interface,
1888 struct usb_redir_interface_info_header, 32),
1889 VMSTATE_UINT8_ARRAY(interface_class,
1890 struct usb_redir_interface_info_header, 32),
1891 VMSTATE_UINT8_ARRAY(interface_subclass,
1892 struct usb_redir_interface_info_header, 32),
1893 VMSTATE_UINT8_ARRAY(interface_protocol,
1894 struct usb_redir_interface_info_header, 32),
1895 VMSTATE_END_OF_LIST()
1900 /* And finally the USBRedirDevice vmstate itself */
1901 static const VMStateDescription usbredir_vmstate = {
1902 .name = "usb-redir",
1903 .version_id = 1,
1904 .minimum_version_id = 1,
1905 .pre_save = usbredir_pre_save,
1906 .post_load = usbredir_post_load,
1907 .fields = (VMStateField[]) {
1908 VMSTATE_USB_DEVICE(dev, USBRedirDevice),
1909 VMSTATE_TIMER(attach_timer, USBRedirDevice),
1911 .name = "parser",
1912 .version_id = 0,
1913 .field_exists = NULL,
1914 .size = 0,
1915 .info = &usbredir_parser_vmstate_info,
1916 .flags = VMS_SINGLE,
1917 .offset = 0,
1919 VMSTATE_STRUCT_ARRAY(endpoint, USBRedirDevice, MAX_ENDPOINTS, 1,
1920 usbredir_ep_vmstate, struct endp_data),
1921 VMSTATE_STRUCT(cancelled, USBRedirDevice, 1,
1922 usbredir_ep_packet_id_queue_vmstate,
1923 struct PacketIdQueue),
1924 VMSTATE_STRUCT(already_in_flight, USBRedirDevice, 1,
1925 usbredir_ep_packet_id_queue_vmstate,
1926 struct PacketIdQueue),
1927 VMSTATE_STRUCT(device_info, USBRedirDevice, 1,
1928 usbredir_device_info_vmstate,
1929 struct usb_redir_device_connect_header),
1930 VMSTATE_STRUCT(interface_info, USBRedirDevice, 1,
1931 usbredir_interface_info_vmstate,
1932 struct usb_redir_interface_info_header),
1933 VMSTATE_END_OF_LIST()
1937 static Property usbredir_properties[] = {
1938 DEFINE_PROP_CHR("chardev", USBRedirDevice, cs),
1939 DEFINE_PROP_UINT8("debug", USBRedirDevice, debug, 0),
1940 DEFINE_PROP_STRING("filter", USBRedirDevice, filter_str),
1941 DEFINE_PROP_INT32("bootindex", USBRedirDevice, bootindex, -1),
1942 DEFINE_PROP_END_OF_LIST(),
1945 static void usbredir_class_initfn(ObjectClass *klass, void *data)
1947 USBDeviceClass *uc = USB_DEVICE_CLASS(klass);
1948 DeviceClass *dc = DEVICE_CLASS(klass);
1950 uc->init = usbredir_initfn;
1951 uc->product_desc = "USB Redirection Device";
1952 uc->handle_destroy = usbredir_handle_destroy;
1953 uc->cancel_packet = usbredir_cancel_packet;
1954 uc->handle_reset = usbredir_handle_reset;
1955 uc->handle_data = usbredir_handle_data;
1956 uc->handle_control = usbredir_handle_control;
1957 uc->flush_ep_queue = usbredir_flush_ep_queue;
1958 dc->vmsd = &usbredir_vmstate;
1959 dc->props = usbredir_properties;
1962 static TypeInfo usbredir_dev_info = {
1963 .name = "usb-redir",
1964 .parent = TYPE_USB_DEVICE,
1965 .instance_size = sizeof(USBRedirDevice),
1966 .class_init = usbredir_class_initfn,
1969 static void usbredir_register_types(void)
1971 type_register_static(&usbredir_dev_info);
1974 type_init(usbredir_register_types)