master
c 2,666 lines 86.9 KB
Raw
1 /*
2 * USB redirector usb-guest
3 *
4 * Copyright (c) 2011-2012 Red Hat, Inc.
5 *
6 * Red Hat Authors:
7 * Hans de Goede <hdegoede@redhat.com>
8 *
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:
15 *
16 * The above copyright notice and this permission notice shall be included in
17 * all copies or substantial portions of the Software.
18 *
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.
26 */
27
28 #include "qemu/osdep.h"
29 #include "qemu/cutils.h"
30 #include "qemu/units.h"
31 #include "qapi/error.h"
32 #include "qemu/timer.h"
33 #include "system/runstate.h"
34 #include "system/system.h"
35 #include "qapi/qmp/qerror.h"
36 #include "qemu/error-report.h"
37 #include "qemu/iov.h"
38 #include "qemu/module.h"
39 #include "chardev/char-fe.h"
40
41 #include <usbredirparser.h>
42 #include <usbredirfilter.h>
43
44 #include "hw/core/qdev-properties.h"
45 #include "hw/core/qdev-properties-system.h"
46 #include "hw/usb/usb.h"
47 #include "migration/qemu-file-types.h"
48 #include "migration/vmstate.h"
49 #include "qom/object.h"
50
51 /* ERROR is defined below. Remove any previous definition. */
52 #undef ERROR
53
54 #define MAX_ENDPOINTS 32
55 #define NO_INTERFACE_INFO 255 /* Valid interface_count always <= 32 */
56 #define EP2I(ep_address) (((ep_address & 0x80) >> 3) | (ep_address & 0x0f))
57 #define I2EP(i) (((i & 0x10) << 3) | (i & 0x0f))
58 #define USBEP2I(usb_ep) (((usb_ep)->pid == USB_TOKEN_IN) ? \
59 ((usb_ep)->nr | 0x10) : ((usb_ep)->nr))
60 #define I2USBEP(d, i) (usb_ep_get(&(d)->dev, \
61 ((i) & 0x10) ? USB_TOKEN_IN : USB_TOKEN_OUT, \
62 (i) & 0x0f))
63
64 #ifndef USBREDIR_VERSION /* This is not defined in older usbredir versions */
65 #define USBREDIR_VERSION 0
66 #endif
67
68 typedef struct USBRedirDevice USBRedirDevice;
69
70 /* Struct to hold buffered packets */
71 struct buf_packet {
72 uint8_t *data;
73 void *free_on_destroy;
74 uint16_t len;
75 uint16_t offset;
76 uint8_t status;
77 QTAILQ_ENTRY(buf_packet)next;
78 };
79
80 struct endp_data {
81 USBRedirDevice *dev;
82 uint8_t type;
83 uint8_t interval;
84 uint8_t interface; /* bInterfaceNumber this ep belongs to */
85 uint16_t max_packet_size; /* In bytes, not wMaxPacketSize format !! */
86 uint32_t max_streams;
87 uint8_t iso_started;
88 uint8_t iso_error; /* For reporting iso errors to the HC */
89 uint8_t interrupt_started;
90 uint8_t interrupt_error;
91 uint8_t bulk_receiving_enabled;
92 uint8_t bulk_receiving_started;
93 uint8_t bufpq_prefilled;
94 uint8_t bufpq_dropping_packets;
95 QTAILQ_HEAD(, buf_packet) bufpq;
96 int32_t bufpq_size;
97 int32_t bufpq_target_size;
98 USBPacket *pending_async_packet;
99 };
100
101 struct PacketIdQueueEntry {
102 uint64_t id;
103 QTAILQ_ENTRY(PacketIdQueueEntry)next;
104 };
105
106 struct PacketIdQueue {
107 USBRedirDevice *dev;
108 const char *name;
109 QTAILQ_HEAD(, PacketIdQueueEntry) head;
110 int size;
111 };
112
113 struct USBRedirDevice {
114 USBDevice dev;
115 /* Properties */
116 CharFrontend cs;
117 bool enable_streams;
118 bool suppress_remote_wake;
119 bool in_write;
120 uint8_t debug;
121 int32_t bootindex;
122 char *filter_str;
123 /* Data passed from chardev the fd_read cb to the usbredirparser read cb */
124 const uint8_t *read_buf;
125 int read_buf_size;
126 /* Active chardev-watch-tag */
127 guint watch;
128 /* For async handling of close / reject */
129 QEMUBH *chardev_close_bh;
130 QEMUBH *device_reject_bh;
131 /* To delay the usb attach in case of quick chardev close + open */
132 QEMUTimer *attach_timer;
133 int64_t next_attach_time;
134 struct usbredirparser *parser;
135 struct endp_data endpoint[MAX_ENDPOINTS];
136 struct PacketIdQueue cancelled;
137 struct PacketIdQueue already_in_flight;
138 void (*buffered_bulk_in_complete)(USBRedirDevice *, USBPacket *, uint8_t);
139 /* Data for device filtering */
140 struct usb_redir_device_connect_header device_info;
141 struct usb_redir_interface_info_header interface_info;
142 struct usbredirfilter_rule *filter_rules;
143 int filter_rules_count;
144 int compatible_speedmask;
145 VMChangeStateEntry *vmstate;
146 };
147
148 #define TYPE_USB_REDIR "usb-redir"
149 DECLARE_INSTANCE_CHECKER(USBRedirDevice, USB_REDIRECT,
150 TYPE_USB_REDIR)
151
152 static void usbredir_hello(void *priv, struct usb_redir_hello_header *h);
153 static void usbredir_device_connect(void *priv,
154 struct usb_redir_device_connect_header *device_connect);
155 static void usbredir_device_disconnect(void *priv);
156 static void usbredir_interface_info(void *priv,
157 struct usb_redir_interface_info_header *interface_info);
158 static void usbredir_ep_info(void *priv,
159 struct usb_redir_ep_info_header *ep_info);
160 static void usbredir_configuration_status(void *priv, uint64_t id,
161 struct usb_redir_configuration_status_header *configuration_status);
162 static void usbredir_alt_setting_status(void *priv, uint64_t id,
163 struct usb_redir_alt_setting_status_header *alt_setting_status);
164 static void usbredir_iso_stream_status(void *priv, uint64_t id,
165 struct usb_redir_iso_stream_status_header *iso_stream_status);
166 static void usbredir_interrupt_receiving_status(void *priv, uint64_t id,
167 struct usb_redir_interrupt_receiving_status_header
168 *interrupt_receiving_status);
169 static void usbredir_bulk_streams_status(void *priv, uint64_t id,
170 struct usb_redir_bulk_streams_status_header *bulk_streams_status);
171 static void usbredir_bulk_receiving_status(void *priv, uint64_t id,
172 struct usb_redir_bulk_receiving_status_header *bulk_receiving_status);
173 static void usbredir_control_packet(void *priv, uint64_t id,
174 struct usb_redir_control_packet_header *control_packet,
175 uint8_t *data, int data_len);
176 static void usbredir_bulk_packet(void *priv, uint64_t id,
177 struct usb_redir_bulk_packet_header *bulk_packet,
178 uint8_t *data, int data_len);
179 static void usbredir_iso_packet(void *priv, uint64_t id,
180 struct usb_redir_iso_packet_header *iso_packet,
181 uint8_t *data, int data_len);
182 static void usbredir_interrupt_packet(void *priv, uint64_t id,
183 struct usb_redir_interrupt_packet_header *interrupt_header,
184 uint8_t *data, int data_len);
185 static void usbredir_buffered_bulk_packet(void *priv, uint64_t id,
186 struct usb_redir_buffered_bulk_packet_header *buffered_bulk_packet,
187 uint8_t *data, int data_len);
188
189 static void usbredir_handle_status(USBRedirDevice *dev, USBPacket *p,
190 int status);
191
192 #define VERSION "qemu usb-redir guest " QEMU_VERSION
193
194 /*
195 * Logging stuff
196 */
197
198 #define ERROR(...) \
199 do { \
200 if (dev->debug >= usbredirparser_error) { \
201 error_report("usb-redir error: " __VA_ARGS__); \
202 } \
203 } while (0)
204 #define WARNING(...) \
205 do { \
206 if (dev->debug >= usbredirparser_warning) { \
207 warn_report("" __VA_ARGS__); \
208 } \
209 } while (0)
210 #define INFO(...) \
211 do { \
212 if (dev->debug >= usbredirparser_info) { \
213 error_report("usb-redir: " __VA_ARGS__); \
214 } \
215 } while (0)
216 #define DPRINTF(...) \
217 do { \
218 if (dev->debug >= usbredirparser_debug) { \
219 error_report("usb-redir: " __VA_ARGS__); \
220 } \
221 } while (0)
222 #define DPRINTF2(...) \
223 do { \
224 if (dev->debug >= usbredirparser_debug_data) { \
225 error_report("usb-redir: " __VA_ARGS__); \
226 } \
227 } while (0)
228
229 static void usbredir_log(void *priv, int level, const char *msg)
230 {
231 USBRedirDevice *dev = priv;
232
233 if (dev->debug < level) {
234 return;
235 }
236
237 error_report("%s", msg);
238 }
239
240 static void usbredir_log_data(USBRedirDevice *dev, const char *desc,
241 const uint8_t *data, int len)
242 {
243 if (dev->debug < usbredirparser_debug_data) {
244 return;
245 }
246 qemu_hexdump(stderr, desc, data, len);
247 }
248
249 /*
250 * usbredirparser io functions
251 */
252
253 static int usbredir_read(void *priv, uint8_t *data, int count)
254 {
255 USBRedirDevice *dev = priv;
256
257 if (dev->read_buf_size < count) {
258 count = dev->read_buf_size;
259 }
260
261 memcpy(data, dev->read_buf, count);
262
263 dev->read_buf_size -= count;
264 if (dev->read_buf_size) {
265 dev->read_buf += count;
266 } else {
267 dev->read_buf = NULL;
268 }
269
270 return count;
271 }
272
273 static gboolean usbredir_write_unblocked(void *do_not_use, GIOCondition cond,
274 void *opaque)
275 {
276 USBRedirDevice *dev = opaque;
277
278 dev->watch = 0;
279 usbredirparser_do_write(dev->parser);
280
281 return G_SOURCE_REMOVE;
282 }
283
284 static int usbredir_write(void *priv, uint8_t *data, int count)
285 {
286 USBRedirDevice *dev = priv;
287 int r;
288
289 if (!qemu_chr_fe_backend_open(&dev->cs)) {
290 return 0;
291 }
292
293 /* Don't send new data to the chardev until our state is fully synced */
294 if (!runstate_check(RUN_STATE_RUNNING)) {
295 return 0;
296 }
297
298 /* Recursion check */
299 if (dev->in_write) {
300 DPRINTF("usbredir_write recursion\n");
301 return 0;
302 }
303 dev->in_write = true;
304
305 r = qemu_chr_fe_write(&dev->cs, data, count);
306 if (r < count) {
307 if (!dev->watch) {
308 dev->watch = qemu_chr_fe_add_watch(&dev->cs, G_IO_OUT | G_IO_HUP,
309 usbredir_write_unblocked, dev);
310 }
311 if (r < 0) {
312 r = 0;
313 }
314 }
315 dev->in_write = false;
316 return r;
317 }
318
319 /*
320 * Cancelled and buffered packets helpers
321 */
322
323 static void packet_id_queue_init(struct PacketIdQueue *q,
324 USBRedirDevice *dev, const char *name)
325 {
326 q->dev = dev;
327 q->name = name;
328 QTAILQ_INIT(&q->head);
329 q->size = 0;
330 }
331
332 static void packet_id_queue_add(struct PacketIdQueue *q, uint64_t id)
333 {
334 USBRedirDevice *dev = q->dev;
335 struct PacketIdQueueEntry *e;
336
337 DPRINTF("adding packet id %"PRIu64" to %s queue\n", id, q->name);
338
339 e = g_new0(struct PacketIdQueueEntry, 1);
340 e->id = id;
341 QTAILQ_INSERT_TAIL(&q->head, e, next);
342 q->size++;
343 }
344
345 static int packet_id_queue_remove(struct PacketIdQueue *q, uint64_t id)
346 {
347 USBRedirDevice *dev = q->dev;
348 struct PacketIdQueueEntry *e;
349
350 QTAILQ_FOREACH(e, &q->head, next) {
351 if (e->id == id) {
352 DPRINTF("removing packet id %"PRIu64" from %s queue\n",
353 id, q->name);
354 QTAILQ_REMOVE(&q->head, e, next);
355 q->size--;
356 g_free(e);
357 return 1;
358 }
359 }
360 return 0;
361 }
362
363 static void packet_id_queue_empty(struct PacketIdQueue *q)
364 {
365 USBRedirDevice *dev = q->dev;
366 struct PacketIdQueueEntry *e, *next_e;
367
368 DPRINTF("removing %d packet-ids from %s queue\n", q->size, q->name);
369
370 QTAILQ_FOREACH_SAFE(e, &q->head, next, next_e) {
371 QTAILQ_REMOVE(&q->head, e, next);
372 g_free(e);
373 }
374 q->size = 0;
375 }
376
377 static void usbredir_cancel_packet(USBDevice *udev, USBPacket *p)
378 {
379 USBRedirDevice *dev = USB_REDIRECT(udev);
380 int i = USBEP2I(p->ep);
381
382 if (p->combined) {
383 usb_combined_packet_cancel(udev, p);
384 return;
385 }
386
387 if (dev->endpoint[i].pending_async_packet) {
388 assert(dev->endpoint[i].pending_async_packet == p);
389 dev->endpoint[i].pending_async_packet = NULL;
390 return;
391 }
392
393 packet_id_queue_add(&dev->cancelled, p->id);
394 usbredirparser_send_cancel_data_packet(dev->parser, p->id);
395 usbredirparser_do_write(dev->parser);
396 }
397
398 static int usbredir_is_cancelled(USBRedirDevice *dev, uint64_t id)
399 {
400 if (!dev->dev.attached) {
401 return 1; /* Treat everything as cancelled after a disconnect */
402 }
403 return packet_id_queue_remove(&dev->cancelled, id);
404 }
405
406 static void usbredir_fill_already_in_flight_from_ep(USBRedirDevice *dev,
407 struct USBEndpoint *ep)
408 {
409 static USBPacket *p;
410
411 /* async handled packets for bulk receiving eps do not count as inflight */
412 if (dev->endpoint[USBEP2I(ep)].bulk_receiving_started) {
413 return;
414 }
415
416 QTAILQ_FOREACH(p, &ep->queue, queue) {
417 /* Skip combined packets, except for the first */
418 if (p->combined && p != p->combined->first) {
419 continue;
420 }
421 if (p->state == USB_PACKET_ASYNC) {
422 packet_id_queue_add(&dev->already_in_flight, p->id);
423 }
424 }
425 }
426
427 static void usbredir_fill_already_in_flight(USBRedirDevice *dev)
428 {
429 int ep;
430 struct USBDevice *udev = &dev->dev;
431
432 usbredir_fill_already_in_flight_from_ep(dev, &udev->ep_ctl);
433
434 for (ep = 0; ep < USB_MAX_ENDPOINTS; ep++) {
435 usbredir_fill_already_in_flight_from_ep(dev, &udev->ep_in[ep]);
436 usbredir_fill_already_in_flight_from_ep(dev, &udev->ep_out[ep]);
437 }
438 }
439
440 static int usbredir_already_in_flight(USBRedirDevice *dev, uint64_t id)
441 {
442 return packet_id_queue_remove(&dev->already_in_flight, id);
443 }
444
445 static USBPacket *usbredir_find_packet_by_id(USBRedirDevice *dev,
446 uint8_t ep, uint64_t id)
447 {
448 USBPacket *p;
449
450 if (usbredir_is_cancelled(dev, id)) {
451 return NULL;
452 }
453
454 p = usb_ep_find_packet_by_id(&dev->dev,
455 (ep & USB_DIR_IN) ? USB_TOKEN_IN : USB_TOKEN_OUT,
456 ep & 0x0f, id);
457 if (p == NULL) {
458 ERROR("could not find packet with id %"PRIu64"\n", id);
459 }
460 return p;
461 }
462
463 static int bufp_alloc(USBRedirDevice *dev, uint8_t *data, uint16_t len,
464 uint8_t status, uint8_t ep, void *free_on_destroy)
465 {
466 struct buf_packet *bufp;
467
468 if (!dev->endpoint[EP2I(ep)].bufpq_dropping_packets &&
469 dev->endpoint[EP2I(ep)].bufpq_size >
470 2 * dev->endpoint[EP2I(ep)].bufpq_target_size) {
471 DPRINTF("bufpq overflow, dropping packets ep %02X\n", ep);
472 dev->endpoint[EP2I(ep)].bufpq_dropping_packets = 1;
473 }
474 /* Since we're interrupting the stream anyways, drop enough packets to get
475 back to our target buffer size */
476 if (dev->endpoint[EP2I(ep)].bufpq_dropping_packets) {
477 if (dev->endpoint[EP2I(ep)].bufpq_size >
478 dev->endpoint[EP2I(ep)].bufpq_target_size) {
479 free(free_on_destroy);
480 return -1;
481 }
482 dev->endpoint[EP2I(ep)].bufpq_dropping_packets = 0;
483 }
484
485 bufp = g_new(struct buf_packet, 1);
486 bufp->data = data;
487 bufp->len = len;
488 bufp->offset = 0;
489 bufp->status = status;
490 bufp->free_on_destroy = free_on_destroy;
491 QTAILQ_INSERT_TAIL(&dev->endpoint[EP2I(ep)].bufpq, bufp, next);
492 dev->endpoint[EP2I(ep)].bufpq_size++;
493 return 0;
494 }
495
496 static void bufp_free(USBRedirDevice *dev, struct buf_packet *bufp,
497 uint8_t ep)
498 {
499 QTAILQ_REMOVE(&dev->endpoint[EP2I(ep)].bufpq, bufp, next);
500 dev->endpoint[EP2I(ep)].bufpq_size--;
501 free(bufp->free_on_destroy);
502 g_free(bufp);
503 }
504
505 static void usbredir_free_bufpq(USBRedirDevice *dev, uint8_t ep)
506 {
507 struct buf_packet *buf, *buf_next;
508
509 QTAILQ_FOREACH_SAFE(buf, &dev->endpoint[EP2I(ep)].bufpq, next, buf_next) {
510 bufp_free(dev, buf, ep);
511 }
512 }
513
514 /*
515 * USBDevice callbacks
516 */
517
518 static void usbredir_handle_reset(USBDevice *udev)
519 {
520 USBRedirDevice *dev = USB_REDIRECT(udev);
521
522 DPRINTF("reset device\n");
523 usbredirparser_send_reset(dev->parser);
524 usbredirparser_do_write(dev->parser);
525 }
526
527 static void usbredir_handle_iso_data(USBRedirDevice *dev, USBPacket *p,
528 uint8_t ep)
529 {
530 int status, len;
531 if (!dev->endpoint[EP2I(ep)].iso_started &&
532 !dev->endpoint[EP2I(ep)].iso_error) {
533 struct usb_redir_start_iso_stream_header start_iso = {
534 .endpoint = ep,
535 };
536 int pkts_per_sec;
537
538 if (dev->dev.speed == USB_SPEED_HIGH) {
539 pkts_per_sec = 8000 / dev->endpoint[EP2I(ep)].interval;
540 } else {
541 pkts_per_sec = 1000 / dev->endpoint[EP2I(ep)].interval;
542 }
543 /* Testing has shown that we need circa 60 ms buffer */
544 dev->endpoint[EP2I(ep)].bufpq_target_size = (pkts_per_sec * 60) / 1000;
545
546 /* Aim for approx 100 interrupts / second on the client to
547 balance latency and interrupt load */
548 start_iso.pkts_per_urb = pkts_per_sec / 100;
549 if (start_iso.pkts_per_urb < 1) {
550 start_iso.pkts_per_urb = 1;
551 } else if (start_iso.pkts_per_urb > 32) {
552 start_iso.pkts_per_urb = 32;
553 }
554
555 start_iso.no_urbs = DIV_ROUND_UP(
556 dev->endpoint[EP2I(ep)].bufpq_target_size,
557 start_iso.pkts_per_urb);
558 /* Output endpoints pre-fill only 1/2 of the packets, keeping the rest
559 as overflow buffer. Also see the usbredir protocol documentation */
560 if (!(ep & USB_DIR_IN)) {
561 start_iso.no_urbs *= 2;
562 }
563 if (start_iso.no_urbs > 16) {
564 start_iso.no_urbs = 16;
565 }
566
567 /* No id, we look at the ep when receiving a status back */
568 usbredirparser_send_start_iso_stream(dev->parser, 0, &start_iso);
569 usbredirparser_do_write(dev->parser);
570 DPRINTF("iso stream started pkts/sec %d pkts/urb %d urbs %d ep %02X\n",
571 pkts_per_sec, start_iso.pkts_per_urb, start_iso.no_urbs, ep);
572 dev->endpoint[EP2I(ep)].iso_started = 1;
573 dev->endpoint[EP2I(ep)].bufpq_prefilled = 0;
574 dev->endpoint[EP2I(ep)].bufpq_dropping_packets = 0;
575 }
576
577 if (ep & USB_DIR_IN) {
578 struct buf_packet *isop;
579
580 if (dev->endpoint[EP2I(ep)].iso_started &&
581 !dev->endpoint[EP2I(ep)].bufpq_prefilled) {
582 if (dev->endpoint[EP2I(ep)].bufpq_size <
583 dev->endpoint[EP2I(ep)].bufpq_target_size) {
584 return;
585 }
586 dev->endpoint[EP2I(ep)].bufpq_prefilled = 1;
587 }
588
589 isop = QTAILQ_FIRST(&dev->endpoint[EP2I(ep)].bufpq);
590 if (isop == NULL) {
591 DPRINTF("iso-token-in ep %02X, no isop, iso_error: %d\n",
592 ep, dev->endpoint[EP2I(ep)].iso_error);
593 /* Re-fill the buffer */
594 dev->endpoint[EP2I(ep)].bufpq_prefilled = 0;
595 /* Check iso_error for stream errors, otherwise its an underrun */
596 status = dev->endpoint[EP2I(ep)].iso_error;
597 dev->endpoint[EP2I(ep)].iso_error = 0;
598 p->status = status ? USB_RET_IOERROR : USB_RET_SUCCESS;
599 return;
600 }
601 DPRINTF2("iso-token-in ep %02X status %d len %d queue-size: %d\n", ep,
602 isop->status, isop->len, dev->endpoint[EP2I(ep)].bufpq_size);
603
604 status = isop->status;
605 len = isop->len;
606 if (len > p->iov.size) {
607 ERROR("received iso data is larger then packet ep %02X (%d > %d)\n",
608 ep, len, (int)p->iov.size);
609 len = p->iov.size;
610 status = usb_redir_babble;
611 }
612 usb_packet_copy(p, isop->data, len);
613 bufp_free(dev, isop, ep);
614 usbredir_handle_status(dev, p, status);
615 } else {
616 /* If the stream was not started because of a pending error don't
617 send the packet to the usb-host */
618 if (dev->endpoint[EP2I(ep)].iso_started) {
619 struct usb_redir_iso_packet_header iso_packet = {
620 .endpoint = ep,
621 .length = p->iov.size
622 };
623 g_autofree uint8_t *buf = g_malloc(p->iov.size);
624 /* No id, we look at the ep when receiving a status back */
625 usb_packet_copy(p, buf, p->iov.size);
626 usbredirparser_send_iso_packet(dev->parser, 0, &iso_packet,
627 buf, p->iov.size);
628 usbredirparser_do_write(dev->parser);
629 }
630 status = dev->endpoint[EP2I(ep)].iso_error;
631 dev->endpoint[EP2I(ep)].iso_error = 0;
632 DPRINTF2("iso-token-out ep %02X status %d len %zd\n", ep, status,
633 p->iov.size);
634 usbredir_handle_status(dev, p, status);
635 }
636 }
637
638 static void usbredir_stop_iso_stream(USBRedirDevice *dev, uint8_t ep)
639 {
640 struct usb_redir_stop_iso_stream_header stop_iso_stream = {
641 .endpoint = ep
642 };
643 if (dev->endpoint[EP2I(ep)].iso_started) {
644 usbredirparser_send_stop_iso_stream(dev->parser, 0, &stop_iso_stream);
645 DPRINTF("iso stream stopped ep %02X\n", ep);
646 dev->endpoint[EP2I(ep)].iso_started = 0;
647 }
648 dev->endpoint[EP2I(ep)].iso_error = 0;
649 usbredir_free_bufpq(dev, ep);
650 }
651
652 /*
653 * The usb-host may poll the endpoint faster then our guest, resulting in lots
654 * of smaller bulkp-s. The below buffered_bulk_in_complete* functions combine
655 * data from multiple bulkp-s into a single packet, avoiding bufpq overflows.
656 */
657 static void usbredir_buffered_bulk_add_data_to_packet(USBRedirDevice *dev,
658 struct buf_packet *bulkp, int count, USBPacket *p, uint8_t ep)
659 {
660 usb_packet_copy(p, bulkp->data + bulkp->offset, count);
661 bulkp->offset += count;
662 if (bulkp->offset == bulkp->len) {
663 /* Store status in the last packet with data from this bulkp */
664 usbredir_handle_status(dev, p, bulkp->status);
665 bufp_free(dev, bulkp, ep);
666 }
667 }
668
669 static void usbredir_buffered_bulk_in_complete_raw(USBRedirDevice *dev,
670 USBPacket *p, uint8_t ep)
671 {
672 struct buf_packet *bulkp;
673 int count;
674
675 while ((bulkp = QTAILQ_FIRST(&dev->endpoint[EP2I(ep)].bufpq)) &&
676 p->actual_length < p->iov.size && p->status == USB_RET_SUCCESS) {
677 count = bulkp->len - bulkp->offset;
678 if (count > (p->iov.size - p->actual_length)) {
679 count = p->iov.size - p->actual_length;
680 }
681 usbredir_buffered_bulk_add_data_to_packet(dev, bulkp, count, p, ep);
682 }
683 }
684
685 static void usbredir_buffered_bulk_in_complete_ftdi(USBRedirDevice *dev,
686 USBPacket *p, uint8_t ep)
687 {
688 const int maxp = dev->endpoint[EP2I(ep)].max_packet_size;
689 uint8_t header[2] = { 0, 0 };
690 struct buf_packet *bulkp;
691 int count;
692
693 assert(maxp != 0);
694 while ((bulkp = QTAILQ_FIRST(&dev->endpoint[EP2I(ep)].bufpq)) &&
695 p->actual_length < p->iov.size && p->status == USB_RET_SUCCESS) {
696 if (bulkp->len < 2) {
697 WARNING("malformed ftdi bulk in packet\n");
698 bufp_free(dev, bulkp, ep);
699 continue;
700 }
701
702 if ((p->actual_length % maxp) == 0) {
703 usb_packet_copy(p, bulkp->data, 2);
704 memcpy(header, bulkp->data, 2);
705 } else {
706 if (bulkp->data[0] != header[0] || bulkp->data[1] != header[1]) {
707 break; /* Different header, add to next packet */
708 }
709 }
710
711 if (bulkp->offset == 0) {
712 bulkp->offset = 2; /* Skip header */
713 }
714 count = bulkp->len - bulkp->offset;
715 /* Must repeat the header at maxp interval */
716 if (count > (maxp - (p->actual_length % maxp))) {
717 count = maxp - (p->actual_length % maxp);
718 }
719 usbredir_buffered_bulk_add_data_to_packet(dev, bulkp, count, p, ep);
720 }
721 }
722
723 static void usbredir_buffered_bulk_in_complete(USBRedirDevice *dev,
724 USBPacket *p, uint8_t ep)
725 {
726 p->status = USB_RET_SUCCESS; /* Clear previous ASYNC status */
727 dev->buffered_bulk_in_complete(dev, p, ep);
728 DPRINTF("bulk-token-in ep %02X status %d len %d id %"PRIu64"\n",
729 ep, p->status, p->actual_length, p->id);
730 }
731
732 static void usbredir_handle_buffered_bulk_in_data(USBRedirDevice *dev,
733 USBPacket *p, uint8_t ep)
734 {
735 /* Input bulk endpoint, buffered packet input */
736 if (!dev->endpoint[EP2I(ep)].bulk_receiving_started) {
737 int bpt;
738 struct usb_redir_start_bulk_receiving_header start = {
739 .endpoint = ep,
740 .stream_id = 0,
741 .no_transfers = 5,
742 };
743 assert(dev->endpoint[EP2I(ep)].max_packet_size != 0);
744 /* Round bytes_per_transfer up to a multiple of max_packet_size */
745 bpt = 512 + dev->endpoint[EP2I(ep)].max_packet_size - 1;
746 bpt /= dev->endpoint[EP2I(ep)].max_packet_size;
747 bpt *= dev->endpoint[EP2I(ep)].max_packet_size;
748 start.bytes_per_transfer = bpt;
749 /* No id, we look at the ep when receiving a status back */
750 usbredirparser_send_start_bulk_receiving(dev->parser, 0, &start);
751 usbredirparser_do_write(dev->parser);
752 DPRINTF("bulk receiving started bytes/transfer %u count %d ep %02X\n",
753 start.bytes_per_transfer, start.no_transfers, ep);
754 dev->endpoint[EP2I(ep)].bulk_receiving_started = 1;
755 /* We don't really want to drop bulk packets ever, but
756 having some upper limit to how much we buffer is good. */
757 dev->endpoint[EP2I(ep)].bufpq_target_size = 5000;
758 dev->endpoint[EP2I(ep)].bufpq_dropping_packets = 0;
759 }
760
761 if (QTAILQ_EMPTY(&dev->endpoint[EP2I(ep)].bufpq)) {
762 DPRINTF("bulk-token-in ep %02X, no bulkp\n", ep);
763 assert(dev->endpoint[EP2I(ep)].pending_async_packet == NULL);
764 dev->endpoint[EP2I(ep)].pending_async_packet = p;
765 p->status = USB_RET_ASYNC;
766 return;
767 }
768 usbredir_buffered_bulk_in_complete(dev, p, ep);
769 }
770
771 static void usbredir_stop_bulk_receiving(USBRedirDevice *dev, uint8_t ep)
772 {
773 struct usb_redir_stop_bulk_receiving_header stop_bulk = {
774 .endpoint = ep,
775 .stream_id = 0,
776 };
777 if (dev->endpoint[EP2I(ep)].bulk_receiving_started) {
778 usbredirparser_send_stop_bulk_receiving(dev->parser, 0, &stop_bulk);
779 DPRINTF("bulk receiving stopped ep %02X\n", ep);
780 dev->endpoint[EP2I(ep)].bulk_receiving_started = 0;
781 }
782 usbredir_free_bufpq(dev, ep);
783 }
784
785 static void usbredir_handle_bulk_data(USBRedirDevice *dev, USBPacket *p,
786 uint8_t ep)
787 {
788 struct usb_redir_bulk_packet_header bulk_packet;
789 size_t size = usb_packet_size(p);
790 const int maxp = dev->endpoint[EP2I(ep)].max_packet_size;
791
792 if (usbredir_already_in_flight(dev, p->id)) {
793 p->status = USB_RET_ASYNC;
794 return;
795 }
796
797 if (dev->endpoint[EP2I(ep)].bulk_receiving_enabled) {
798 assert(maxp != 0);
799 if (size != 0 && (size % maxp) == 0) {
800 usbredir_handle_buffered_bulk_in_data(dev, p, ep);
801 return;
802 }
803 WARNING("bulk recv invalid size %zd ep %02x, disabling\n", size, ep);
804 assert(dev->endpoint[EP2I(ep)].pending_async_packet == NULL);
805 usbredir_stop_bulk_receiving(dev, ep);
806 dev->endpoint[EP2I(ep)].bulk_receiving_enabled = 0;
807 }
808
809 DPRINTF("bulk-out ep %02X stream %u len %zd id %"PRIu64"\n",
810 ep, p->stream, size, p->id);
811
812 bulk_packet.endpoint = ep;
813 bulk_packet.length = size;
814 bulk_packet.stream_id = p->stream;
815 bulk_packet.length_high = size >> 16;
816 assert(bulk_packet.length_high == 0 ||
817 usbredirparser_peer_has_cap(dev->parser,
818 usb_redir_cap_32bits_bulk_length));
819
820 if (ep & USB_DIR_IN || size == 0) {
821 usbredirparser_send_bulk_packet(dev->parser, p->id,
822 &bulk_packet, NULL, 0);
823 } else {
824 g_autofree uint8_t *buf = g_malloc(size);
825 usb_packet_copy(p, buf, size);
826 usbredir_log_data(dev, "bulk data out:", buf, size);
827 usbredirparser_send_bulk_packet(dev->parser, p->id,
828 &bulk_packet, buf, size);
829 }
830 usbredirparser_do_write(dev->parser);
831 p->status = USB_RET_ASYNC;
832 }
833
834 static void usbredir_handle_interrupt_in_data(USBRedirDevice *dev,
835 USBPacket *p, uint8_t ep)
836 {
837 /* Input interrupt endpoint, buffered packet input */
838 struct buf_packet *intp, *intp_to_free;
839 int status, len, sum;
840
841 if (!dev->endpoint[EP2I(ep)].interrupt_started &&
842 !dev->endpoint[EP2I(ep)].interrupt_error) {
843 struct usb_redir_start_interrupt_receiving_header start_int = {
844 .endpoint = ep,
845 };
846 /* No id, we look at the ep when receiving a status back */
847 usbredirparser_send_start_interrupt_receiving(dev->parser, 0,
848 &start_int);
849 usbredirparser_do_write(dev->parser);
850 DPRINTF("interrupt recv started ep %02X\n", ep);
851 dev->endpoint[EP2I(ep)].interrupt_started = 1;
852 /* We don't really want to drop interrupt packets ever, but
853 having some upper limit to how much we buffer is good. */
854 dev->endpoint[EP2I(ep)].bufpq_target_size = 1000;
855 dev->endpoint[EP2I(ep)].bufpq_dropping_packets = 0;
856 }
857
858 /* check for completed interrupt message (with all fragments) */
859 sum = 0;
860 QTAILQ_FOREACH(intp, &dev->endpoint[EP2I(ep)].bufpq, next) {
861 sum += intp->len;
862 if (intp->len < dev->endpoint[EP2I(ep)].max_packet_size ||
863 sum >= p->iov.size)
864 break;
865 }
866
867 if (intp == NULL) {
868 DPRINTF2("interrupt-token-in ep %02X, no intp, buffered %d\n", ep, sum);
869 /* Check interrupt_error for stream errors */
870 status = dev->endpoint[EP2I(ep)].interrupt_error;
871 dev->endpoint[EP2I(ep)].interrupt_error = 0;
872 if (status) {
873 usbredir_handle_status(dev, p, status);
874 } else {
875 p->status = USB_RET_NAK;
876 }
877 return;
878 }
879
880 /* copy of completed interrupt message */
881 sum = 0;
882 status = usb_redir_success;
883 intp_to_free = NULL;
884 QTAILQ_FOREACH(intp, &dev->endpoint[EP2I(ep)].bufpq, next) {
885 if (intp_to_free) {
886 bufp_free(dev, intp_to_free, ep);
887 }
888 DPRINTF("interrupt-token-in ep %02X fragment status %d len %d\n", ep,
889 intp->status, intp->len);
890
891 sum += intp->len;
892 len = intp->len;
893 if (status == usb_redir_success) {
894 status = intp->status;
895 }
896 if (sum > p->iov.size) {
897 ERROR("received int data is larger then packet ep %02X\n", ep);
898 len -= (sum - p->iov.size);
899 sum = p->iov.size;
900 status = usb_redir_babble;
901 }
902
903 usb_packet_copy(p, intp->data, len);
904
905 intp_to_free = intp;
906 if (intp->len < dev->endpoint[EP2I(ep)].max_packet_size ||
907 sum >= p->iov.size)
908 break;
909 }
910 if (intp_to_free) {
911 bufp_free(dev, intp_to_free, ep);
912 }
913 DPRINTF("interrupt-token-in ep %02X summary status %d len %d\n", ep,
914 status, sum);
915 usbredir_handle_status(dev, p, status);
916 }
917
918 /*
919 * Handle interrupt out data, the usbredir protocol expects us to do this
920 * async, so that it can report back a completion status. But guests will
921 * expect immediate completion for an interrupt endpoint, and handling this
922 * async causes migration issues. So we report success directly, counting
923 * on the fact that output interrupt packets normally always succeed.
924 */
925 static void usbredir_handle_interrupt_out_data(USBRedirDevice *dev,
926 USBPacket *p, uint8_t ep)
927 {
928 struct usb_redir_interrupt_packet_header interrupt_packet;
929 g_autofree uint8_t *buf = g_malloc(p->iov.size);
930
931 DPRINTF("interrupt-out ep %02X len %zd id %"PRIu64"\n", ep,
932 p->iov.size, p->id);
933
934 interrupt_packet.endpoint = ep;
935 interrupt_packet.length = p->iov.size;
936
937 usb_packet_copy(p, buf, p->iov.size);
938 usbredir_log_data(dev, "interrupt data out:", buf, p->iov.size);
939 usbredirparser_send_interrupt_packet(dev->parser, p->id,
940 &interrupt_packet, buf, p->iov.size);
941 usbredirparser_do_write(dev->parser);
942 }
943
944 static void usbredir_stop_interrupt_receiving(USBRedirDevice *dev,
945 uint8_t ep)
946 {
947 struct usb_redir_stop_interrupt_receiving_header stop_interrupt_recv = {
948 .endpoint = ep
949 };
950 if (dev->endpoint[EP2I(ep)].interrupt_started) {
951 usbredirparser_send_stop_interrupt_receiving(dev->parser, 0,
952 &stop_interrupt_recv);
953 DPRINTF("interrupt recv stopped ep %02X\n", ep);
954 dev->endpoint[EP2I(ep)].interrupt_started = 0;
955 }
956 dev->endpoint[EP2I(ep)].interrupt_error = 0;
957 usbredir_free_bufpq(dev, ep);
958 }
959
960 static void usbredir_handle_data(USBDevice *udev, USBPacket *p)
961 {
962 USBRedirDevice *dev = USB_REDIRECT(udev);
963 uint8_t ep;
964
965 ep = p->ep->nr;
966 if (p->pid == USB_TOKEN_IN) {
967 ep |= USB_DIR_IN;
968 }
969
970 switch (dev->endpoint[EP2I(ep)].type) {
971 case USB_ENDPOINT_XFER_CONTROL:
972 ERROR("handle_data called for control transfer on ep %02X\n", ep);
973 p->status = USB_RET_NAK;
974 break;
975 case USB_ENDPOINT_XFER_BULK:
976 if (p->state == USB_PACKET_SETUP && p->pid == USB_TOKEN_IN &&
977 p->ep->pipeline) {
978 p->status = USB_RET_ADD_TO_QUEUE;
979 break;
980 }
981 usbredir_handle_bulk_data(dev, p, ep);
982 break;
983 case USB_ENDPOINT_XFER_ISOC:
984 usbredir_handle_iso_data(dev, p, ep);
985 break;
986 case USB_ENDPOINT_XFER_INT:
987 if (ep & USB_DIR_IN) {
988 usbredir_handle_interrupt_in_data(dev, p, ep);
989 } else {
990 usbredir_handle_interrupt_out_data(dev, p, ep);
991 }
992 break;
993 default:
994 ERROR("handle_data ep %02X has unknown type %d\n", ep,
995 dev->endpoint[EP2I(ep)].type);
996 p->status = USB_RET_NAK;
997 }
998 }
999
1000 static void usbredir_flush_ep_queue(USBDevice *dev, USBEndpoint *ep)
1001 {
1002 if (ep->pid == USB_TOKEN_IN && ep->pipeline) {
1003 usb_ep_combine_input_packets(ep);
1004 }
1005 }
1006
1007 static void usbredir_stop_ep(USBRedirDevice *dev, int i)
1008 {
1009 uint8_t ep = I2EP(i);
1010
1011 switch (dev->endpoint[i].type) {
1012 case USB_ENDPOINT_XFER_BULK:
1013 if (ep & USB_DIR_IN) {
1014 usbredir_stop_bulk_receiving(dev, ep);
1015 }
1016 break;
1017 case USB_ENDPOINT_XFER_ISOC:
1018 usbredir_stop_iso_stream(dev, ep);
1019 break;
1020 case USB_ENDPOINT_XFER_INT:
1021 if (ep & USB_DIR_IN) {
1022 usbredir_stop_interrupt_receiving(dev, ep);
1023 }
1024 break;
1025 }
1026 usbredir_free_bufpq(dev, ep);
1027 }
1028
1029 static void usbredir_ep_stopped(USBDevice *udev, USBEndpoint *uep)
1030 {
1031 USBRedirDevice *dev = USB_REDIRECT(udev);
1032
1033 usbredir_stop_ep(dev, USBEP2I(uep));
1034 usbredirparser_do_write(dev->parser);
1035 }
1036
1037 static void usbredir_set_config(USBRedirDevice *dev, USBPacket *p,
1038 int config)
1039 {
1040 struct usb_redir_set_configuration_header set_config;
1041 int i;
1042
1043 DPRINTF("set config %d id %"PRIu64"\n", config, p->id);
1044
1045 for (i = 0; i < MAX_ENDPOINTS; i++) {
1046 usbredir_stop_ep(dev, i);
1047 }
1048
1049 set_config.configuration = config;
1050 usbredirparser_send_set_configuration(dev->parser, p->id, &set_config);
1051 usbredirparser_do_write(dev->parser);
1052 p->status = USB_RET_ASYNC;
1053 }
1054
1055 static void usbredir_get_config(USBRedirDevice *dev, USBPacket *p)
1056 {
1057 DPRINTF("get config id %"PRIu64"\n", p->id);
1058
1059 usbredirparser_send_get_configuration(dev->parser, p->id);
1060 usbredirparser_do_write(dev->parser);
1061 p->status = USB_RET_ASYNC;
1062 }
1063
1064 static void usbredir_set_interface(USBRedirDevice *dev, USBPacket *p,
1065 int interface, int alt)
1066 {
1067 struct usb_redir_set_alt_setting_header set_alt;
1068 int i;
1069
1070 DPRINTF("set interface %d alt %d id %"PRIu64"\n", interface, alt, p->id);
1071
1072 for (i = 0; i < MAX_ENDPOINTS; i++) {
1073 if (dev->endpoint[i].interface == interface) {
1074 usbredir_stop_ep(dev, i);
1075 }
1076 }
1077
1078 set_alt.interface = interface;
1079 set_alt.alt = alt;
1080 usbredirparser_send_set_alt_setting(dev->parser, p->id, &set_alt);
1081 usbredirparser_do_write(dev->parser);
1082 p->status = USB_RET_ASYNC;
1083 }
1084
1085 static void usbredir_get_interface(USBRedirDevice *dev, USBPacket *p,
1086 int interface)
1087 {
1088 struct usb_redir_get_alt_setting_header get_alt;
1089
1090 DPRINTF("get interface %d id %"PRIu64"\n", interface, p->id);
1091
1092 get_alt.interface = interface;
1093 usbredirparser_send_get_alt_setting(dev->parser, p->id, &get_alt);
1094 usbredirparser_do_write(dev->parser);
1095 p->status = USB_RET_ASYNC;
1096 }
1097
1098 static void usbredir_handle_control(USBDevice *udev, USBPacket *p,
1099 int request, int value, int index, int length, uint8_t *data)
1100 {
1101 USBRedirDevice *dev = USB_REDIRECT(udev);
1102 struct usb_redir_control_packet_header control_packet;
1103
1104 if (usbredir_already_in_flight(dev, p->id)) {
1105 p->status = USB_RET_ASYNC;
1106 return;
1107 }
1108
1109 /* Special cases for certain standard device requests */
1110 switch (request) {
1111 case DeviceOutRequest | USB_REQ_SET_ADDRESS:
1112 DPRINTF("set address %d\n", value);
1113 dev->dev.addr = value;
1114 return;
1115 case DeviceOutRequest | USB_REQ_SET_CONFIGURATION:
1116 usbredir_set_config(dev, p, value & 0xff);
1117 return;
1118 case DeviceRequest | USB_REQ_GET_CONFIGURATION:
1119 usbredir_get_config(dev, p);
1120 return;
1121 case InterfaceOutRequest | USB_REQ_SET_INTERFACE:
1122 usbredir_set_interface(dev, p, index, value);
1123 return;
1124 case InterfaceRequest | USB_REQ_GET_INTERFACE:
1125 usbredir_get_interface(dev, p, index);
1126 return;
1127 }
1128
1129 /* Normal ctrl requests, note request is (bRequestType << 8) | bRequest */
1130 DPRINTF(
1131 "ctrl-out type 0x%x req 0x%x val 0x%x index %d len %d id %"PRIu64"\n",
1132 request >> 8, request & 0xff, value, index, length, p->id);
1133
1134 control_packet.request = request & 0xFF;
1135 control_packet.requesttype = request >> 8;
1136 control_packet.endpoint = control_packet.requesttype & USB_DIR_IN;
1137 control_packet.value = value;
1138 control_packet.index = index;
1139 control_packet.length = length;
1140
1141 if (control_packet.requesttype & USB_DIR_IN) {
1142 usbredirparser_send_control_packet(dev->parser, p->id,
1143 &control_packet, NULL, 0);
1144 } else {
1145 usbredir_log_data(dev, "ctrl data out:", data, length);
1146 usbredirparser_send_control_packet(dev->parser, p->id,
1147 &control_packet, data, length);
1148 }
1149 usbredirparser_do_write(dev->parser);
1150 p->status = USB_RET_ASYNC;
1151 }
1152
1153 static int usbredir_alloc_streams(USBDevice *udev, USBEndpoint **eps,
1154 int nr_eps, int streams)
1155 {
1156 USBRedirDevice *dev = USB_REDIRECT(udev);
1157 #if USBREDIR_VERSION >= 0x000700
1158 struct usb_redir_alloc_bulk_streams_header alloc_streams;
1159 int i;
1160
1161 if (!usbredirparser_peer_has_cap(dev->parser,
1162 usb_redir_cap_bulk_streams)) {
1163 ERROR("peer does not support streams\n");
1164 goto reject;
1165 }
1166
1167 if (streams == 0) {
1168 ERROR("request to allocate 0 streams\n");
1169 return -1;
1170 }
1171
1172 alloc_streams.no_streams = streams;
1173 alloc_streams.endpoints = 0;
1174 for (i = 0; i < nr_eps; i++) {
1175 alloc_streams.endpoints |= 1 << USBEP2I(eps[i]);
1176 }
1177 usbredirparser_send_alloc_bulk_streams(dev->parser, 0, &alloc_streams);
1178 usbredirparser_do_write(dev->parser);
1179
1180 return 0;
1181 #else
1182 ERROR("usbredir_alloc_streams not implemented\n");
1183 goto reject;
1184 #endif
1185 reject:
1186 ERROR("streams are not available, disconnecting\n");
1187 qemu_bh_schedule(dev->device_reject_bh);
1188 return -1;
1189 }
1190
1191 static void usbredir_free_streams(USBDevice *udev, USBEndpoint **eps,
1192 int nr_eps)
1193 {
1194 #if USBREDIR_VERSION >= 0x000700
1195 USBRedirDevice *dev = USB_REDIRECT(udev);
1196 struct usb_redir_free_bulk_streams_header free_streams;
1197 int i;
1198
1199 if (!usbredirparser_peer_has_cap(dev->parser,
1200 usb_redir_cap_bulk_streams)) {
1201 return;
1202 }
1203
1204 free_streams.endpoints = 0;
1205 for (i = 0; i < nr_eps; i++) {
1206 free_streams.endpoints |= 1 << USBEP2I(eps[i]);
1207 }
1208 usbredirparser_send_free_bulk_streams(dev->parser, 0, &free_streams);
1209 usbredirparser_do_write(dev->parser);
1210 #endif
1211 }
1212
1213 /*
1214 * Close events can be triggered by usbredirparser_do_write which gets called
1215 * from within the USBDevice data / control packet callbacks and doing a
1216 * usb_detach from within these callbacks is not a good idea.
1217 *
1218 * So we use a bh handler to take care of close events.
1219 */
1220 static void usbredir_chardev_close_bh(void *opaque)
1221 {
1222 USBRedirDevice *dev = opaque;
1223
1224 qemu_bh_cancel(dev->device_reject_bh);
1225 usbredir_device_disconnect(dev);
1226
1227 if (dev->parser) {
1228 DPRINTF("destroying usbredirparser\n");
1229 usbredirparser_destroy(dev->parser);
1230 dev->parser = NULL;
1231 }
1232 g_clear_handle_id(&dev->watch, g_source_remove);
1233 }
1234
1235 static void usbredir_create_parser(USBRedirDevice *dev)
1236 {
1237 uint32_t caps[USB_REDIR_CAPS_SIZE] = { 0, };
1238 int flags = 0;
1239
1240 DPRINTF("creating usbredirparser\n");
1241
1242 dev->parser = usbredirparser_create();
1243 if (!dev->parser) {
1244 error_report("usbredirparser_create() failed");
1245 exit(1);
1246 }
1247 dev->parser->priv = dev;
1248 dev->parser->log_func = usbredir_log;
1249 dev->parser->read_func = usbredir_read;
1250 dev->parser->write_func = usbredir_write;
1251 dev->parser->hello_func = usbredir_hello;
1252 dev->parser->device_connect_func = usbredir_device_connect;
1253 dev->parser->device_disconnect_func = usbredir_device_disconnect;
1254 dev->parser->interface_info_func = usbredir_interface_info;
1255 dev->parser->ep_info_func = usbredir_ep_info;
1256 dev->parser->configuration_status_func = usbredir_configuration_status;
1257 dev->parser->alt_setting_status_func = usbredir_alt_setting_status;
1258 dev->parser->iso_stream_status_func = usbredir_iso_stream_status;
1259 dev->parser->interrupt_receiving_status_func =
1260 usbredir_interrupt_receiving_status;
1261 dev->parser->bulk_streams_status_func = usbredir_bulk_streams_status;
1262 dev->parser->bulk_receiving_status_func = usbredir_bulk_receiving_status;
1263 dev->parser->control_packet_func = usbredir_control_packet;
1264 dev->parser->bulk_packet_func = usbredir_bulk_packet;
1265 dev->parser->iso_packet_func = usbredir_iso_packet;
1266 dev->parser->interrupt_packet_func = usbredir_interrupt_packet;
1267 dev->parser->buffered_bulk_packet_func = usbredir_buffered_bulk_packet;
1268 dev->read_buf = NULL;
1269 dev->read_buf_size = 0;
1270
1271 usbredirparser_caps_set_cap(caps, usb_redir_cap_connect_device_version);
1272 usbredirparser_caps_set_cap(caps, usb_redir_cap_filter);
1273 usbredirparser_caps_set_cap(caps, usb_redir_cap_ep_info_max_packet_size);
1274 usbredirparser_caps_set_cap(caps, usb_redir_cap_64bits_ids);
1275 usbredirparser_caps_set_cap(caps, usb_redir_cap_32bits_bulk_length);
1276 usbredirparser_caps_set_cap(caps, usb_redir_cap_bulk_receiving);
1277 #if USBREDIR_VERSION >= 0x000700
1278 if (dev->enable_streams) {
1279 usbredirparser_caps_set_cap(caps, usb_redir_cap_bulk_streams);
1280 }
1281 #endif
1282
1283 if (runstate_check(RUN_STATE_INMIGRATE)) {
1284 flags |= usbredirparser_fl_no_hello;
1285 }
1286 usbredirparser_init(dev->parser, VERSION, caps, USB_REDIR_CAPS_SIZE,
1287 flags);
1288 usbredirparser_do_write(dev->parser);
1289 }
1290
1291 static void usbredir_reject_device(USBRedirDevice *dev)
1292 {
1293 usbredir_device_disconnect(dev);
1294 if (usbredirparser_peer_has_cap(dev->parser, usb_redir_cap_filter)) {
1295 usbredirparser_send_filter_reject(dev->parser);
1296 usbredirparser_do_write(dev->parser);
1297 }
1298 }
1299
1300 /*
1301 * We may need to reject the device when the hcd calls alloc_streams, doing
1302 * an usb_detach from within a hcd call is not a good idea, hence this bh.
1303 */
1304 static void usbredir_device_reject_bh(void *opaque)
1305 {
1306 USBRedirDevice *dev = opaque;
1307
1308 usbredir_reject_device(dev);
1309 }
1310
1311 static void usbredir_do_attach(void *opaque)
1312 {
1313 USBRedirDevice *dev = opaque;
1314 Error *local_err = NULL;
1315
1316 /* In order to work properly with XHCI controllers we need these caps */
1317 if ((dev->dev.port->speedmask & USB_SPEED_MASK_SUPER) && !(
1318 usbredirparser_peer_has_cap(dev->parser,
1319 usb_redir_cap_ep_info_max_packet_size) &&
1320 usbredirparser_peer_has_cap(dev->parser,
1321 usb_redir_cap_32bits_bulk_length) &&
1322 usbredirparser_peer_has_cap(dev->parser,
1323 usb_redir_cap_64bits_ids))) {
1324 ERROR("usb-redir-host lacks capabilities needed for use with XHCI\n");
1325 usbredir_reject_device(dev);
1326 return;
1327 }
1328
1329 usb_device_attach(&dev->dev, &local_err);
1330 if (local_err) {
1331 error_report_err(local_err);
1332 WARNING("rejecting device due to speed mismatch\n");
1333 usbredir_reject_device(dev);
1334 }
1335 }
1336
1337 /*
1338 * chardev callbacks
1339 */
1340
1341 static int usbredir_chardev_can_read(void *opaque)
1342 {
1343 USBRedirDevice *dev = opaque;
1344
1345 if (!dev->parser) {
1346 WARNING("chardev_can_read called on non open chardev!\n");
1347 return 0;
1348 }
1349
1350 /* Don't read new data from the chardev until our state is fully synced */
1351 if (!runstate_check(RUN_STATE_RUNNING)) {
1352 return 0;
1353 }
1354
1355 /* usbredir_parser_do_read will consume *all* data we give it */
1356 return 1 * MiB;
1357 }
1358
1359 static void usbredir_chardev_read(void *opaque, const uint8_t *buf, int size)
1360 {
1361 USBRedirDevice *dev = opaque;
1362
1363 /* No recursion allowed! */
1364 assert(dev->read_buf == NULL);
1365
1366 dev->read_buf = buf;
1367 dev->read_buf_size = size;
1368
1369 usbredirparser_do_read(dev->parser);
1370 /* Send any acks, etc. which may be queued now */
1371 usbredirparser_do_write(dev->parser);
1372 }
1373
1374 static void usbredir_chardev_event(void *opaque, QEMUChrEvent event)
1375 {
1376 USBRedirDevice *dev = opaque;
1377
1378 switch (event) {
1379 case CHR_EVENT_OPENED:
1380 DPRINTF("chardev open\n");
1381 /* Make sure any pending closes are handled (no-op if none pending) */
1382 usbredir_chardev_close_bh(dev);
1383 qemu_bh_cancel(dev->chardev_close_bh);
1384 usbredir_create_parser(dev);
1385 break;
1386 case CHR_EVENT_CLOSED:
1387 DPRINTF("chardev close\n");
1388 qemu_bh_schedule(dev->chardev_close_bh);
1389 break;
1390 case CHR_EVENT_BREAK:
1391 case CHR_EVENT_MUX_IN:
1392 case CHR_EVENT_MUX_OUT:
1393 /* Ignore */
1394 break;
1395 }
1396 }
1397
1398 /*
1399 * init + destroy
1400 */
1401
1402 static void usbredir_vm_state_change(void *priv, bool running, RunState state)
1403 {
1404 USBRedirDevice *dev = priv;
1405
1406 if (running && dev->parser != NULL) {
1407 usbredirparser_do_write(dev->parser); /* Flush any pending writes */
1408 }
1409 }
1410
1411 static void usbredir_init_endpoints(USBRedirDevice *dev)
1412 {
1413 int i;
1414
1415 usb_ep_init(&dev->dev);
1416 memset(dev->endpoint, 0, sizeof(dev->endpoint));
1417 for (i = 0; i < MAX_ENDPOINTS; i++) {
1418 dev->endpoint[i].dev = dev;
1419 QTAILQ_INIT(&dev->endpoint[i].bufpq);
1420 }
1421 }
1422
1423 static void usbredir_realize(USBDevice *udev, Error **errp)
1424 {
1425 USBRedirDevice *dev = USB_REDIRECT(udev);
1426 int i;
1427
1428 if (!qemu_chr_fe_backend_connected(&dev->cs)) {
1429 error_setg(errp, QERR_MISSING_PARAMETER, "chardev");
1430 return;
1431 }
1432
1433 if (dev->filter_str) {
1434 i = usbredirfilter_string_to_rules(dev->filter_str, ":", "|",
1435 &dev->filter_rules,
1436 &dev->filter_rules_count);
1437 if (i) {
1438 error_setg(errp, QERR_INVALID_PARAMETER_VALUE, "filter",
1439 "a usb device filter string");
1440 return;
1441 }
1442 }
1443
1444 dev->chardev_close_bh = qemu_bh_new_guarded(usbredir_chardev_close_bh, dev,
1445 &DEVICE(dev)->mem_reentrancy_guard);
1446 dev->device_reject_bh = qemu_bh_new_guarded(usbredir_device_reject_bh, dev,
1447 &DEVICE(dev)->mem_reentrancy_guard);
1448 dev->attach_timer = timer_new_ms(QEMU_CLOCK_VIRTUAL, usbredir_do_attach, dev);
1449
1450 packet_id_queue_init(&dev->cancelled, dev, "cancelled");
1451 packet_id_queue_init(&dev->already_in_flight, dev, "already-in-flight");
1452 usbredir_init_endpoints(dev);
1453
1454 /* We'll do the attach once we receive the speed from the usb-host */
1455 udev->auto_attach = 0;
1456
1457 /* Will be cleared during setup when we find conflicts */
1458 dev->compatible_speedmask = USB_SPEED_MASK_FULL | USB_SPEED_MASK_HIGH;
1459
1460 /* Let the backend know we are ready */
1461 qemu_chr_fe_set_handlers(&dev->cs, usbredir_chardev_can_read,
1462 usbredir_chardev_read, usbredir_chardev_event,
1463 NULL, dev, NULL, true);
1464
1465 dev->vmstate =
1466 qemu_add_vm_change_state_handler(usbredir_vm_state_change, dev);
1467 }
1468
1469 static void usbredir_cleanup_device_queues(USBRedirDevice *dev)
1470 {
1471 int i;
1472
1473 packet_id_queue_empty(&dev->cancelled);
1474 packet_id_queue_empty(&dev->already_in_flight);
1475 for (i = 0; i < MAX_ENDPOINTS; i++) {
1476 usbredir_free_bufpq(dev, I2EP(i));
1477 }
1478 }
1479
1480 static void usbredir_unrealize(USBDevice *udev)
1481 {
1482 USBRedirDevice *dev = USB_REDIRECT(udev);
1483
1484 qemu_chr_fe_deinit(&dev->cs, true);
1485
1486 /* Note must be done after qemu_chr_close, as that causes a close event */
1487 qemu_bh_delete(dev->chardev_close_bh);
1488 qemu_bh_delete(dev->device_reject_bh);
1489
1490 timer_free(dev->attach_timer);
1491
1492 usbredir_cleanup_device_queues(dev);
1493
1494 if (dev->parser) {
1495 usbredirparser_destroy(dev->parser);
1496 }
1497 g_clear_handle_id(&dev->watch, g_source_remove);
1498
1499 free(dev->filter_rules);
1500 qemu_del_vm_change_state_handler(dev->vmstate);
1501 }
1502
1503 static int usbredir_check_filter(USBRedirDevice *dev)
1504 {
1505 if (dev->interface_info.interface_count == NO_INTERFACE_INFO) {
1506 ERROR("No interface info for device\n");
1507 goto error;
1508 }
1509
1510 if (dev->filter_rules) {
1511 if (!usbredirparser_peer_has_cap(dev->parser,
1512 usb_redir_cap_connect_device_version)) {
1513 ERROR("Device filter specified and peer does not have the "
1514 "connect_device_version capability\n");
1515 goto error;
1516 }
1517
1518 if (usbredirfilter_check(
1519 dev->filter_rules,
1520 dev->filter_rules_count,
1521 dev->device_info.device_class,
1522 dev->device_info.device_subclass,
1523 dev->device_info.device_protocol,
1524 dev->interface_info.interface_class,
1525 dev->interface_info.interface_subclass,
1526 dev->interface_info.interface_protocol,
1527 dev->interface_info.interface_count,
1528 dev->device_info.vendor_id,
1529 dev->device_info.product_id,
1530 dev->device_info.device_version_bcd,
1531 0) != 0) {
1532 goto error;
1533 }
1534 }
1535
1536 return 0;
1537
1538 error:
1539 usbredir_reject_device(dev);
1540 return -1;
1541 }
1542
1543 static void usbredir_check_bulk_receiving(USBRedirDevice *dev)
1544 {
1545 int i, j, quirks;
1546
1547 if (!usbredirparser_peer_has_cap(dev->parser,
1548 usb_redir_cap_bulk_receiving)) {
1549 return;
1550 }
1551
1552 for (i = EP2I(USB_DIR_IN); i < MAX_ENDPOINTS; i++) {
1553 dev->endpoint[i].bulk_receiving_enabled = 0;
1554 }
1555
1556 if (dev->interface_info.interface_count == NO_INTERFACE_INFO) {
1557 return;
1558 }
1559
1560 for (i = 0; i < dev->interface_info.interface_count; i++) {
1561 quirks = usb_get_quirks(dev->device_info.vendor_id,
1562 dev->device_info.product_id,
1563 dev->interface_info.interface_class[i],
1564 dev->interface_info.interface_subclass[i],
1565 dev->interface_info.interface_protocol[i]);
1566 if (!(quirks & USB_QUIRK_BUFFER_BULK_IN)) {
1567 continue;
1568 }
1569 if (quirks & USB_QUIRK_IS_FTDI) {
1570 dev->buffered_bulk_in_complete =
1571 usbredir_buffered_bulk_in_complete_ftdi;
1572 } else {
1573 dev->buffered_bulk_in_complete =
1574 usbredir_buffered_bulk_in_complete_raw;
1575 }
1576
1577 for (j = EP2I(USB_DIR_IN); j < MAX_ENDPOINTS; j++) {
1578 if (dev->endpoint[j].interface ==
1579 dev->interface_info.interface[i] &&
1580 dev->endpoint[j].type == USB_ENDPOINT_XFER_BULK &&
1581 dev->endpoint[j].max_packet_size != 0) {
1582 dev->endpoint[j].bulk_receiving_enabled = 1;
1583 /*
1584 * With buffering pipelining is not necessary. Also packet
1585 * combining and bulk in buffering don't play nice together!
1586 */
1587 I2USBEP(dev, j)->pipeline = false;
1588 break; /* Only buffer for the first ep of each intf */
1589 }
1590 }
1591 }
1592 }
1593
1594 /*
1595 * usbredirparser packet complete callbacks
1596 */
1597
1598 static void usbredir_handle_status(USBRedirDevice *dev, USBPacket *p,
1599 int status)
1600 {
1601 switch (status) {
1602 case usb_redir_success:
1603 p->status = USB_RET_SUCCESS; /* Clear previous ASYNC status */
1604 break;
1605 case usb_redir_stall:
1606 p->status = USB_RET_STALL;
1607 break;
1608 case usb_redir_cancelled:
1609 /*
1610 * When the usbredir-host unredirects a device, it will report a status
1611 * of cancelled for all pending packets, followed by a disconnect msg.
1612 */
1613 p->status = USB_RET_IOERROR;
1614 break;
1615 case usb_redir_inval:
1616 WARNING("got invalid param error from usb-host?\n");
1617 p->status = USB_RET_IOERROR;
1618 break;
1619 case usb_redir_babble:
1620 p->status = USB_RET_BABBLE;
1621 break;
1622 case usb_redir_ioerror:
1623 case usb_redir_timeout:
1624 default:
1625 p->status = USB_RET_IOERROR;
1626 }
1627 }
1628
1629 static void usbredir_hello(void *priv, struct usb_redir_hello_header *h)
1630 {
1631 USBRedirDevice *dev = priv;
1632
1633 /* Try to send the filter info now that we've the usb-host's caps */
1634 if (usbredirparser_peer_has_cap(dev->parser, usb_redir_cap_filter) &&
1635 dev->filter_rules) {
1636 usbredirparser_send_filter_filter(dev->parser, dev->filter_rules,
1637 dev->filter_rules_count);
1638 usbredirparser_do_write(dev->parser);
1639 }
1640 }
1641
1642 static void usbredir_device_connect(void *priv,
1643 struct usb_redir_device_connect_header *device_connect)
1644 {
1645 USBRedirDevice *dev = priv;
1646 const char *speed;
1647
1648 if (timer_pending(dev->attach_timer) || dev->dev.attached) {
1649 ERROR("Received device connect while already connected\n");
1650 return;
1651 }
1652
1653 switch (device_connect->speed) {
1654 case usb_redir_speed_low:
1655 speed = "low speed";
1656 dev->dev.speed = USB_SPEED_LOW;
1657 dev->compatible_speedmask &= ~USB_SPEED_MASK_FULL;
1658 dev->compatible_speedmask &= ~USB_SPEED_MASK_HIGH;
1659 break;
1660 case usb_redir_speed_full:
1661 speed = "full speed";
1662 dev->dev.speed = USB_SPEED_FULL;
1663 dev->compatible_speedmask &= ~USB_SPEED_MASK_HIGH;
1664 break;
1665 case usb_redir_speed_high:
1666 speed = "high speed";
1667 dev->dev.speed = USB_SPEED_HIGH;
1668 break;
1669 case usb_redir_speed_super:
1670 speed = "super speed";
1671 dev->dev.speed = USB_SPEED_SUPER;
1672 break;
1673 default:
1674 speed = "unknown speed";
1675 dev->dev.speed = USB_SPEED_FULL;
1676 }
1677
1678 if (usbredirparser_peer_has_cap(dev->parser,
1679 usb_redir_cap_connect_device_version)) {
1680 INFO("attaching %s device %04x:%04x version %d.%d class %02x\n",
1681 speed, device_connect->vendor_id, device_connect->product_id,
1682 ((device_connect->device_version_bcd & 0xf000) >> 12) * 10 +
1683 ((device_connect->device_version_bcd & 0x0f00) >> 8),
1684 ((device_connect->device_version_bcd & 0x00f0) >> 4) * 10 +
1685 ((device_connect->device_version_bcd & 0x000f) >> 0),
1686 device_connect->device_class);
1687 } else {
1688 INFO("attaching %s device %04x:%04x class %02x\n", speed,
1689 device_connect->vendor_id, device_connect->product_id,
1690 device_connect->device_class);
1691 }
1692
1693 dev->dev.speedmask = (1 << dev->dev.speed) | dev->compatible_speedmask;
1694 dev->device_info = *device_connect;
1695
1696 if (usbredir_check_filter(dev)) {
1697 WARNING("Device %04x:%04x rejected by device filter, not attaching\n",
1698 device_connect->vendor_id, device_connect->product_id);
1699 return;
1700 }
1701
1702 usbredir_check_bulk_receiving(dev);
1703 timer_mod(dev->attach_timer, dev->next_attach_time);
1704 }
1705
1706 static void usbredir_device_disconnect(void *priv)
1707 {
1708 USBRedirDevice *dev = priv;
1709
1710 /* Stop any pending attaches */
1711 timer_del(dev->attach_timer);
1712
1713 if (dev->dev.attached) {
1714 DPRINTF("detaching device\n");
1715 usb_device_detach(&dev->dev);
1716 /*
1717 * Delay next usb device attach to give the guest a chance to see
1718 * see the detach / attach in case of quick close / open succession
1719 */
1720 dev->next_attach_time = qemu_clock_get_ms(QEMU_CLOCK_VIRTUAL) + 200;
1721 }
1722
1723 /* Reset state so that the next dev connected starts with a clean slate */
1724 usbredir_cleanup_device_queues(dev);
1725 usbredir_init_endpoints(dev);
1726 dev->interface_info.interface_count = NO_INTERFACE_INFO;
1727 dev->dev.addr = 0;
1728 dev->dev.speed = 0;
1729 dev->compatible_speedmask = USB_SPEED_MASK_FULL | USB_SPEED_MASK_HIGH;
1730 }
1731
1732 static void usbredir_interface_info(void *priv,
1733 struct usb_redir_interface_info_header *interface_info)
1734 {
1735 USBRedirDevice *dev = priv;
1736
1737 dev->interface_info = *interface_info;
1738
1739 /*
1740 * If we receive interface info after the device has already been
1741 * connected (ie on a set_config), re-check interface dependent things.
1742 */
1743 if (timer_pending(dev->attach_timer) || dev->dev.attached) {
1744 usbredir_check_bulk_receiving(dev);
1745 if (usbredir_check_filter(dev)) {
1746 ERROR("Device no longer matches filter after interface info "
1747 "change, disconnecting!\n");
1748 }
1749 }
1750 }
1751
1752 static void usbredir_mark_speed_incompatible(USBRedirDevice *dev, int speed)
1753 {
1754 dev->compatible_speedmask &= ~(1 << speed);
1755 dev->dev.speedmask = (1 << dev->dev.speed) | dev->compatible_speedmask;
1756 }
1757
1758 static void usbredir_set_pipeline(USBRedirDevice *dev, struct USBEndpoint *uep)
1759 {
1760 if (uep->type != USB_ENDPOINT_XFER_BULK) {
1761 return;
1762 }
1763 if (uep->pid == USB_TOKEN_OUT) {
1764 uep->pipeline = true;
1765 }
1766 if (uep->pid == USB_TOKEN_IN && uep->max_packet_size != 0 &&
1767 usbredirparser_peer_has_cap(dev->parser,
1768 usb_redir_cap_32bits_bulk_length)) {
1769 uep->pipeline = true;
1770 }
1771 }
1772
1773 static void usbredir_setup_usb_eps(USBRedirDevice *dev)
1774 {
1775 struct USBEndpoint *usb_ep;
1776 int i;
1777
1778 for (i = 0; i < MAX_ENDPOINTS; i++) {
1779 usb_ep = I2USBEP(dev, i);
1780 usb_ep->type = dev->endpoint[i].type;
1781 usb_ep->ifnum = dev->endpoint[i].interface;
1782 usb_ep->max_packet_size = dev->endpoint[i].max_packet_size;
1783 usb_ep->max_streams = dev->endpoint[i].max_streams;
1784 usbredir_set_pipeline(dev, usb_ep);
1785 }
1786 }
1787
1788 static void usbredir_ep_info(void *priv,
1789 struct usb_redir_ep_info_header *ep_info)
1790 {
1791 USBRedirDevice *dev = priv;
1792 int i;
1793
1794 assert(dev != NULL);
1795 for (i = 0; i < MAX_ENDPOINTS; i++) {
1796 dev->endpoint[i].type = ep_info->type[i];
1797 dev->endpoint[i].interval = ep_info->interval[i];
1798 dev->endpoint[i].interface = ep_info->interface[i];
1799 if (usbredirparser_peer_has_cap(dev->parser,
1800 usb_redir_cap_ep_info_max_packet_size)) {
1801 dev->endpoint[i].max_packet_size = ep_info->max_packet_size[i];
1802 if (ep_info->max_packet_size[i] == 0 &&
1803 dev->endpoint[i].bulk_receiving_enabled) {
1804 USBPacket *p = dev->endpoint[i].pending_async_packet;
1805 usbredir_stop_bulk_receiving(dev, I2EP(i));
1806 dev->endpoint[i].bulk_receiving_enabled = 0;
1807 if (p != NULL) {
1808 dev->endpoint[i].pending_async_packet = NULL;
1809 p->status = USB_RET_IOERROR;
1810 usb_packet_complete(&dev->dev, p);
1811 }
1812 }
1813 }
1814 #if USBREDIR_VERSION >= 0x000700
1815 if (usbredirparser_peer_has_cap(dev->parser,
1816 usb_redir_cap_bulk_streams)) {
1817 dev->endpoint[i].max_streams = ep_info->max_streams[i];
1818 }
1819 #endif
1820 switch (dev->endpoint[i].type) {
1821 case usb_redir_type_invalid:
1822 break;
1823 case usb_redir_type_iso:
1824 usbredir_mark_speed_incompatible(dev, USB_SPEED_FULL);
1825 usbredir_mark_speed_incompatible(dev, USB_SPEED_HIGH);
1826 /* Fall through */
1827 case usb_redir_type_interrupt:
1828 if (!usbredirparser_peer_has_cap(dev->parser,
1829 usb_redir_cap_ep_info_max_packet_size) ||
1830 ep_info->max_packet_size[i] > 64) {
1831 usbredir_mark_speed_incompatible(dev, USB_SPEED_FULL);
1832 }
1833 if (!usbredirparser_peer_has_cap(dev->parser,
1834 usb_redir_cap_ep_info_max_packet_size) ||
1835 ep_info->max_packet_size[i] > 1024) {
1836 usbredir_mark_speed_incompatible(dev, USB_SPEED_HIGH);
1837 }
1838 if (dev->endpoint[i].interval == 0) {
1839 ERROR("Received 0 interval for isoc or irq endpoint\n");
1840 usbredir_reject_device(dev);
1841 return;
1842 }
1843 /* Fall through */
1844 case usb_redir_type_control:
1845 case usb_redir_type_bulk:
1846 DPRINTF("ep: %02X type: %d interface: %d\n", I2EP(i),
1847 dev->endpoint[i].type, dev->endpoint[i].interface);
1848 break;
1849 default:
1850 ERROR("Received invalid endpoint type\n");
1851 usbredir_reject_device(dev);
1852 return;
1853 }
1854 }
1855 /* The new ep info may have caused a speed incompatibility, recheck */
1856 if (dev->dev.attached &&
1857 !(dev->dev.port->speedmask & dev->dev.speedmask)) {
1858 ERROR("Device no longer matches speed after endpoint info change, "
1859 "disconnecting!\n");
1860 usbredir_reject_device(dev);
1861 return;
1862 }
1863 usbredir_setup_usb_eps(dev);
1864 usbredir_check_bulk_receiving(dev);
1865 }
1866
1867 static void usbredir_configuration_status(void *priv, uint64_t id,
1868 struct usb_redir_configuration_status_header *config_status)
1869 {
1870 USBRedirDevice *dev = priv;
1871 USBPacket *p;
1872
1873 DPRINTF("set config status %d config %d id %"PRIu64"\n",
1874 config_status->status, config_status->configuration, id);
1875
1876 p = usbredir_find_packet_by_id(dev, 0, id);
1877 if (p) {
1878 if (dev->dev.setup_buf[0] & USB_DIR_IN) {
1879 dev->dev.data_buf[0] = config_status->configuration;
1880 p->actual_length = 1;
1881 }
1882 usbredir_handle_status(dev, p, config_status->status);
1883 usb_generic_async_ctrl_complete(&dev->dev, p);
1884 }
1885 }
1886
1887 static void usbredir_alt_setting_status(void *priv, uint64_t id,
1888 struct usb_redir_alt_setting_status_header *alt_setting_status)
1889 {
1890 USBRedirDevice *dev = priv;
1891 USBPacket *p;
1892
1893 DPRINTF("alt status %d intf %d alt %d id: %"PRIu64"\n",
1894 alt_setting_status->status, alt_setting_status->interface,
1895 alt_setting_status->alt, id);
1896
1897 p = usbredir_find_packet_by_id(dev, 0, id);
1898 if (p) {
1899 if (dev->dev.setup_buf[0] & USB_DIR_IN) {
1900 dev->dev.data_buf[0] = alt_setting_status->alt;
1901 p->actual_length = 1;
1902 }
1903 usbredir_handle_status(dev, p, alt_setting_status->status);
1904 usb_generic_async_ctrl_complete(&dev->dev, p);
1905 }
1906 }
1907
1908 static void usbredir_iso_stream_status(void *priv, uint64_t id,
1909 struct usb_redir_iso_stream_status_header *iso_stream_status)
1910 {
1911 USBRedirDevice *dev = priv;
1912 uint8_t ep = iso_stream_status->endpoint;
1913
1914 DPRINTF("iso status %d ep %02X id %"PRIu64"\n", iso_stream_status->status,
1915 ep, id);
1916
1917 if (!dev->dev.attached || !dev->endpoint[EP2I(ep)].iso_started) {
1918 return;
1919 }
1920
1921 dev->endpoint[EP2I(ep)].iso_error = iso_stream_status->status;
1922 if (iso_stream_status->status == usb_redir_stall) {
1923 DPRINTF("iso stream stopped by peer ep %02X\n", ep);
1924 dev->endpoint[EP2I(ep)].iso_started = 0;
1925 }
1926 }
1927
1928 static void usbredir_interrupt_receiving_status(void *priv, uint64_t id,
1929 struct usb_redir_interrupt_receiving_status_header
1930 *interrupt_receiving_status)
1931 {
1932 USBRedirDevice *dev = priv;
1933 uint8_t ep = interrupt_receiving_status->endpoint;
1934
1935 DPRINTF("interrupt recv status %d ep %02X id %"PRIu64"\n",
1936 interrupt_receiving_status->status, ep, id);
1937
1938 if (!dev->dev.attached || !dev->endpoint[EP2I(ep)].interrupt_started) {
1939 return;
1940 }
1941
1942 dev->endpoint[EP2I(ep)].interrupt_error =
1943 interrupt_receiving_status->status;
1944 if (interrupt_receiving_status->status == usb_redir_stall) {
1945 DPRINTF("interrupt receiving stopped by peer ep %02X\n", ep);
1946 dev->endpoint[EP2I(ep)].interrupt_started = 0;
1947 }
1948 }
1949
1950 static void usbredir_bulk_streams_status(void *priv, uint64_t id,
1951 struct usb_redir_bulk_streams_status_header *bulk_streams_status)
1952 {
1953 #if USBREDIR_VERSION >= 0x000700
1954 USBRedirDevice *dev = priv;
1955
1956 if (bulk_streams_status->status == usb_redir_success) {
1957 DPRINTF("bulk streams status %d eps %08x\n",
1958 bulk_streams_status->status, bulk_streams_status->endpoints);
1959 } else {
1960 ERROR("bulk streams %s failed status %d eps %08x\n",
1961 (bulk_streams_status->no_streams == 0) ? "free" : "alloc",
1962 bulk_streams_status->status, bulk_streams_status->endpoints);
1963 ERROR("usb-redir-host does not provide streams, disconnecting\n");
1964 usbredir_reject_device(dev);
1965 }
1966 #endif
1967 }
1968
1969 static void usbredir_bulk_receiving_status(void *priv, uint64_t id,
1970 struct usb_redir_bulk_receiving_status_header *bulk_receiving_status)
1971 {
1972 USBRedirDevice *dev = priv;
1973 uint8_t ep = bulk_receiving_status->endpoint;
1974
1975 DPRINTF("bulk recv status %d ep %02X id %"PRIu64"\n",
1976 bulk_receiving_status->status, ep, id);
1977
1978 if (!dev->dev.attached || !dev->endpoint[EP2I(ep)].bulk_receiving_started) {
1979 return;
1980 }
1981
1982 if (bulk_receiving_status->status == usb_redir_stall) {
1983 DPRINTF("bulk receiving stopped by peer ep %02X\n", ep);
1984 dev->endpoint[EP2I(ep)].bulk_receiving_started = 0;
1985 }
1986 }
1987
1988 static void usbredir_control_packet(void *priv, uint64_t id,
1989 struct usb_redir_control_packet_header *control_packet,
1990 uint8_t *data, int data_len)
1991 {
1992 USBRedirDevice *dev = priv;
1993 USBPacket *p;
1994 int len = control_packet->length;
1995
1996 DPRINTF("ctrl-in status %d len %d id %"PRIu64"\n", control_packet->status,
1997 len, id);
1998
1999 /* Fix up USB-3 ep0 maxpacket size to allow superspeed connected devices
2000 * to work redirected to a not superspeed capable hcd */
2001 if (dev->dev.speed == USB_SPEED_SUPER &&
2002 !((dev->dev.port->speedmask & USB_SPEED_MASK_SUPER)) &&
2003 control_packet->requesttype == 0x80 &&
2004 control_packet->request == 6 &&
2005 control_packet->value == 0x100 && control_packet->index == 0 &&
2006 data_len >= 18 && data[7] == 9) {
2007 data[7] = 64;
2008 }
2009
2010 p = usbredir_find_packet_by_id(dev, 0, id);
2011 if (p) {
2012 usbredir_handle_status(dev, p, control_packet->status);
2013 if (data_len > 0) {
2014 usbredir_log_data(dev, "ctrl data in:", data, data_len);
2015 if (data_len > sizeof(dev->dev.data_buf)) {
2016 ERROR("ctrl buffer too small (%d > %zu)\n",
2017 data_len, sizeof(dev->dev.data_buf));
2018 p->status = USB_RET_STALL;
2019 data_len = len = sizeof(dev->dev.data_buf);
2020 }
2021 memcpy(dev->dev.data_buf, data, data_len);
2022 }
2023 p->actual_length = len;
2024 /*
2025 * If this is GET_DESCRIPTOR request for configuration descriptor,
2026 * remove 'remote wakeup' flag from it to prevent idle power down
2027 * in Windows guest
2028 */
2029 if (dev->suppress_remote_wake &&
2030 control_packet->requesttype == USB_DIR_IN &&
2031 control_packet->request == USB_REQ_GET_DESCRIPTOR &&
2032 control_packet->value == (USB_DT_CONFIG << 8) &&
2033 control_packet->index == 0 &&
2034 /* bmAttributes field of config descriptor */
2035 len > 7 && (dev->dev.data_buf[7] & USB_CFG_ATT_WAKEUP)) {
2036 DPRINTF("Removed remote wake %04X:%04X\n",
2037 dev->device_info.vendor_id,
2038 dev->device_info.product_id);
2039 dev->dev.data_buf[7] &= ~USB_CFG_ATT_WAKEUP;
2040 }
2041 usb_generic_async_ctrl_complete(&dev->dev, p);
2042 }
2043 free(data);
2044 }
2045
2046 static void usbredir_bulk_packet(void *priv, uint64_t id,
2047 struct usb_redir_bulk_packet_header *bulk_packet,
2048 uint8_t *data, int data_len)
2049 {
2050 USBRedirDevice *dev = priv;
2051 uint8_t ep = bulk_packet->endpoint;
2052 int len = (bulk_packet->length_high << 16) | bulk_packet->length;
2053 USBPacket *p;
2054
2055 DPRINTF("bulk-in status %d ep %02X stream %u len %d id %"PRIu64"\n",
2056 bulk_packet->status, ep, bulk_packet->stream_id, len, id);
2057
2058 p = usbredir_find_packet_by_id(dev, ep, id);
2059 if (p) {
2060 size_t size = usb_packet_size(p);
2061 usbredir_handle_status(dev, p, bulk_packet->status);
2062 if (data_len > 0) {
2063 usbredir_log_data(dev, "bulk data in:", data, data_len);
2064 if (data_len > size) {
2065 ERROR("bulk got more data then requested (%d > %zd)\n",
2066 data_len, p->iov.size);
2067 p->status = USB_RET_BABBLE;
2068 data_len = len = size;
2069 }
2070 usb_packet_copy(p, data, data_len);
2071 }
2072 p->actual_length = len;
2073 if (p->pid == USB_TOKEN_IN && p->ep->pipeline) {
2074 usb_combined_input_packet_complete(&dev->dev, p);
2075 } else {
2076 usb_packet_complete(&dev->dev, p);
2077 }
2078 }
2079 free(data);
2080 }
2081
2082 static void usbredir_iso_packet(void *priv, uint64_t id,
2083 struct usb_redir_iso_packet_header *iso_packet,
2084 uint8_t *data, int data_len)
2085 {
2086 USBRedirDevice *dev = priv;
2087 uint8_t ep = iso_packet->endpoint;
2088
2089 DPRINTF2("iso-in status %d ep %02X len %d id %"PRIu64"\n",
2090 iso_packet->status, ep, data_len, id);
2091
2092 if (dev->endpoint[EP2I(ep)].type != USB_ENDPOINT_XFER_ISOC) {
2093 ERROR("received iso packet for non iso endpoint %02X\n", ep);
2094 free(data);
2095 return;
2096 }
2097
2098 if (dev->endpoint[EP2I(ep)].iso_started == 0) {
2099 DPRINTF("received iso packet for non started stream ep %02X\n", ep);
2100 free(data);
2101 return;
2102 }
2103
2104 /* bufp_alloc also adds the packet to the ep queue */
2105 bufp_alloc(dev, data, data_len, iso_packet->status, ep, data);
2106 }
2107
2108 static void usbredir_interrupt_packet(void *priv, uint64_t id,
2109 struct usb_redir_interrupt_packet_header *interrupt_packet,
2110 uint8_t *data, int data_len)
2111 {
2112 USBRedirDevice *dev = priv;
2113 uint8_t ep = interrupt_packet->endpoint;
2114
2115 DPRINTF("interrupt-in status %d ep %02X len %d id %"PRIu64"\n",
2116 interrupt_packet->status, ep, data_len, id);
2117
2118 if (dev->endpoint[EP2I(ep)].type != USB_ENDPOINT_XFER_INT) {
2119 ERROR("received int packet for non interrupt endpoint %02X\n", ep);
2120 free(data);
2121 return;
2122 }
2123
2124 if (ep & USB_DIR_IN) {
2125 if (dev->endpoint[EP2I(ep)].interrupt_started == 0) {
2126 DPRINTF("received int packet while not started ep %02X\n", ep);
2127 free(data);
2128 return;
2129 }
2130
2131 /* bufp_alloc also adds the packet to the ep queue */
2132 bufp_alloc(dev, data, data_len, interrupt_packet->status, ep, data);
2133
2134 /* insufficient data solved with USB_RET_NAK */
2135 usb_wakeup(usb_ep_get(&dev->dev, USB_TOKEN_IN, ep & 0x0f), 0);
2136 } else {
2137 /*
2138 * We report output interrupt packets as completed directly upon
2139 * submission, so all we can do here if one failed is warn.
2140 */
2141 if (interrupt_packet->status) {
2142 WARNING("interrupt output failed status %d ep %02X id %"PRIu64"\n",
2143 interrupt_packet->status, ep, id);
2144 }
2145 }
2146 }
2147
2148 static void usbredir_buffered_bulk_packet(void *priv, uint64_t id,
2149 struct usb_redir_buffered_bulk_packet_header *buffered_bulk_packet,
2150 uint8_t *data, int data_len)
2151 {
2152 USBRedirDevice *dev = priv;
2153 uint8_t status, ep = buffered_bulk_packet->endpoint;
2154 void *free_on_destroy;
2155 int i, len, queued = 0;
2156
2157 DPRINTF("buffered-bulk-in status %d ep %02X len %d id %"PRIu64"\n",
2158 buffered_bulk_packet->status, ep, data_len, id);
2159
2160 if (dev->endpoint[EP2I(ep)].type != USB_ENDPOINT_XFER_BULK) {
2161 ERROR("received buffered-bulk packet for non bulk ep %02X\n", ep);
2162 free(data);
2163 return;
2164 }
2165
2166 if (dev->endpoint[EP2I(ep)].bulk_receiving_started == 0) {
2167 DPRINTF("received buffered-bulk packet on not started ep %02X\n", ep);
2168 free(data);
2169 return;
2170 }
2171
2172 /* Data must be in maxp chunks for buffered_bulk_add_*_data_to_packet */
2173 assert(dev->endpoint[EP2I(ep)].max_packet_size != 0);
2174 len = dev->endpoint[EP2I(ep)].max_packet_size;
2175 status = usb_redir_success;
2176 free_on_destroy = NULL;
2177 for (i = 0; i < data_len; i += len) {
2178 int r;
2179 if (len >= (data_len - i)) {
2180 len = data_len - i;
2181 status = buffered_bulk_packet->status;
2182 free_on_destroy = data;
2183 }
2184 /* bufp_alloc also adds the packet to the ep queue */
2185 r = bufp_alloc(dev, data + i, len, status, ep, free_on_destroy);
2186 if (r) {
2187 /*
2188 * Earlier fragments from this packet are in the queue
2189 * with interior pointers into data. If the dropped
2190 * fragment was the final one, bufp_alloc already freed
2191 * data so those pointers are dangling. Remove them.
2192 */
2193 while (queued > 0) {
2194 struct buf_packet *bufp;
2195 bufp = QTAILQ_LAST(&dev->endpoint[EP2I(ep)].bufpq);
2196 bufp_free(dev, bufp, ep);
2197 queued--;
2198 }
2199 if (!free_on_destroy) {
2200 free(data);
2201 }
2202 break;
2203 }
2204 queued++;
2205 }
2206
2207 if (dev->endpoint[EP2I(ep)].pending_async_packet) {
2208 USBPacket *p = dev->endpoint[EP2I(ep)].pending_async_packet;
2209 dev->endpoint[EP2I(ep)].pending_async_packet = NULL;
2210 usbredir_buffered_bulk_in_complete(dev, p, ep);
2211 usb_packet_complete(&dev->dev, p);
2212 }
2213 }
2214
2215 /*
2216 * Migration code
2217 */
2218
2219 static int usbredir_pre_save(void *priv)
2220 {
2221 USBRedirDevice *dev = priv;
2222
2223 usbredir_fill_already_in_flight(dev);
2224
2225 return 0;
2226 }
2227
2228 static int usbredir_post_load(void *priv, int version_id)
2229 {
2230 USBRedirDevice *dev = priv;
2231
2232 if (dev == NULL || dev->parser == NULL) {
2233 return 0;
2234 }
2235
2236 switch (dev->device_info.speed) {
2237 case usb_redir_speed_low:
2238 dev->dev.speed = USB_SPEED_LOW;
2239 break;
2240 case usb_redir_speed_full:
2241 dev->dev.speed = USB_SPEED_FULL;
2242 break;
2243 case usb_redir_speed_high:
2244 dev->dev.speed = USB_SPEED_HIGH;
2245 break;
2246 case usb_redir_speed_super:
2247 dev->dev.speed = USB_SPEED_SUPER;
2248 break;
2249 default:
2250 dev->dev.speed = USB_SPEED_FULL;
2251 }
2252 dev->dev.speedmask = (1 << dev->dev.speed);
2253
2254 usbredir_setup_usb_eps(dev);
2255 usbredir_check_bulk_receiving(dev);
2256
2257 for (int i = 0; i < MAX_ENDPOINTS; i++) {
2258 if (dev->endpoint[i].bulk_receiving_started &&
2259 dev->endpoint[i].max_packet_size == 0) {
2260 error_report("usbredir: endpoint %d has bulk receiving started "
2261 "with zero max_packet_size", i);
2262 return -EINVAL;
2263 }
2264 }
2265
2266 return 0;
2267 }
2268
2269 /* For usbredirparser migration */
2270 static int usbredir_put_parser(QEMUFile *f, void *priv, size_t unused,
2271 const VMStateField *field, JSONWriter *vmdesc)
2272 {
2273 USBRedirDevice *dev = priv;
2274 uint8_t *data;
2275 int len;
2276
2277 if (dev->parser == NULL) {
2278 qemu_put_be32(f, 0);
2279 return 0;
2280 }
2281
2282 usbredirparser_serialize(dev->parser, &data, &len);
2283 if (!data) {
2284 error_report("usbredirparser_serialize failed");
2285 exit(1);
2286 }
2287
2288 qemu_put_be32(f, len);
2289 qemu_put_buffer(f, data, len);
2290
2291 free(data);
2292
2293 return 0;
2294 }
2295
2296 static int usbredir_get_parser(QEMUFile *f, void *priv, size_t unused,
2297 const VMStateField *field)
2298 {
2299 USBRedirDevice *dev = priv;
2300 uint8_t *data;
2301 int len, ret;
2302
2303 len = qemu_get_be32(f);
2304 if (len == 0) {
2305 return 0;
2306 }
2307
2308 /*
2309 * If our chardev is not open already at this point the usbredir connection
2310 * has been broken (non seamless migration, or restore from disk).
2311 *
2312 * In this case create a temporary parser to receive the migration data,
2313 * and schedule the close_bh to report the device as disconnected to the
2314 * guest and to destroy the parser again.
2315 */
2316 if (dev->parser == NULL) {
2317 WARNING("usb-redir connection broken during migration\n");
2318 usbredir_create_parser(dev);
2319 qemu_bh_schedule(dev->chardev_close_bh);
2320 }
2321
2322 data = g_malloc(len);
2323 qemu_get_buffer(f, data, len);
2324
2325 ret = usbredirparser_unserialize(dev->parser, data, len);
2326
2327 g_free(data);
2328
2329 return ret;
2330 }
2331
2332 static const VMStateInfo usbredir_parser_vmstate_info = {
2333 .name = "usb-redir-parser",
2334 .put = usbredir_put_parser,
2335 .get = usbredir_get_parser,
2336 };
2337
2338
2339 /* For buffered packets (iso/irq) queue migration */
2340 static int usbredir_put_bufpq(QEMUFile *f, void *priv, size_t unused,
2341 const VMStateField *field, JSONWriter *vmdesc)
2342 {
2343 struct endp_data *endp = priv;
2344 USBRedirDevice *dev = endp->dev;
2345 struct buf_packet *bufp;
2346 int len, i = 0;
2347
2348 qemu_put_be32(f, endp->bufpq_size);
2349 QTAILQ_FOREACH(bufp, &endp->bufpq, next) {
2350 len = bufp->len - bufp->offset;
2351 DPRINTF("put_bufpq %d/%d len %d status %d\n", i + 1, endp->bufpq_size,
2352 len, bufp->status);
2353 qemu_put_be32(f, len);
2354 qemu_put_be32(f, bufp->status);
2355 qemu_put_buffer(f, bufp->data + bufp->offset, len);
2356 i++;
2357 }
2358 assert(i == endp->bufpq_size);
2359
2360 return 0;
2361 }
2362
2363 static int usbredir_get_bufpq(QEMUFile *f, void *priv, size_t unused,
2364 const VMStateField *field)
2365 {
2366 struct endp_data *endp = priv;
2367 USBRedirDevice *dev = endp->dev;
2368 struct buf_packet *bufp;
2369 int i;
2370
2371 endp->bufpq_size = qemu_get_be32(f);
2372 for (i = 0; i < endp->bufpq_size; i++) {
2373 bufp = g_new(struct buf_packet, 1);
2374 bufp->len = qemu_get_be32(f);
2375 bufp->status = qemu_get_be32(f);
2376 bufp->offset = 0;
2377 bufp->data = malloc(bufp->len); /* regular malloc! */
2378 if (!bufp->data) {
2379 error_report("usbredir_get_bufpq: out of memory");
2380 exit(1);
2381 }
2382 bufp->free_on_destroy = bufp->data;
2383 qemu_get_buffer(f, bufp->data, bufp->len);
2384 QTAILQ_INSERT_TAIL(&endp->bufpq, bufp, next);
2385 DPRINTF("get_bufpq %d/%d len %d status %d\n", i + 1, endp->bufpq_size,
2386 bufp->len, bufp->status);
2387 }
2388 return 0;
2389 }
2390
2391 static const VMStateInfo usbredir_ep_bufpq_vmstate_info = {
2392 .name = "usb-redir-bufpq",
2393 .put = usbredir_put_bufpq,
2394 .get = usbredir_get_bufpq,
2395 };
2396
2397
2398 /* For endp_data migration */
2399 static bool usbredir_bulk_receiving_needed(void *priv)
2400 {
2401 struct endp_data *endp = priv;
2402
2403 return endp->bulk_receiving_started;
2404 }
2405
2406 static const VMStateDescription usbredir_bulk_receiving_vmstate = {
2407 .name = "usb-redir-ep/bulk-receiving",
2408 .version_id = 1,
2409 .minimum_version_id = 1,
2410 .needed = usbredir_bulk_receiving_needed,
2411 .fields = (const VMStateField[]) {
2412 VMSTATE_UINT8(bulk_receiving_started, struct endp_data),
2413 VMSTATE_END_OF_LIST()
2414 }
2415 };
2416
2417 static bool usbredir_stream_needed(void *priv)
2418 {
2419 struct endp_data *endp = priv;
2420
2421 return endp->max_streams;
2422 }
2423
2424 static const VMStateDescription usbredir_stream_vmstate = {
2425 .name = "usb-redir-ep/stream-state",
2426 .version_id = 1,
2427 .minimum_version_id = 1,
2428 .needed = usbredir_stream_needed,
2429 .fields = (const VMStateField[]) {
2430 VMSTATE_UINT32(max_streams, struct endp_data),
2431 VMSTATE_END_OF_LIST()
2432 }
2433 };
2434
2435 static const VMStateDescription usbredir_ep_vmstate = {
2436 .name = "usb-redir-ep",
2437 .version_id = 1,
2438 .minimum_version_id = 1,
2439 .fields = (const VMStateField[]) {
2440 VMSTATE_UINT8(type, struct endp_data),
2441 VMSTATE_UINT8(interval, struct endp_data),
2442 VMSTATE_UINT8(interface, struct endp_data),
2443 VMSTATE_UINT16(max_packet_size, struct endp_data),
2444 VMSTATE_UINT8(iso_started, struct endp_data),
2445 VMSTATE_UINT8(iso_error, struct endp_data),
2446 VMSTATE_UINT8(interrupt_started, struct endp_data),
2447 VMSTATE_UINT8(interrupt_error, struct endp_data),
2448 VMSTATE_UINT8(bufpq_prefilled, struct endp_data),
2449 VMSTATE_UINT8(bufpq_dropping_packets, struct endp_data),
2450 {
2451 .name = "bufpq",
2452 .version_id = 0,
2453 .field_exists = NULL,
2454 .size = 0,
2455 .info = &usbredir_ep_bufpq_vmstate_info,
2456 .flags = VMS_SINGLE,
2457 .offset = 0,
2458 },
2459 VMSTATE_INT32(bufpq_target_size, struct endp_data),
2460 VMSTATE_END_OF_LIST()
2461 },
2462 .subsections = (const VMStateDescription * const []) {
2463 &usbredir_bulk_receiving_vmstate,
2464 &usbredir_stream_vmstate,
2465 NULL
2466 }
2467 };
2468
2469
2470 /* For PacketIdQueue migration */
2471 static int usbredir_put_packet_id_q(QEMUFile *f, void *priv, size_t unused,
2472 const VMStateField *field,
2473 JSONWriter *vmdesc)
2474 {
2475 struct PacketIdQueue *q = priv;
2476 USBRedirDevice *dev = q->dev;
2477 struct PacketIdQueueEntry *e;
2478 int remain = q->size;
2479
2480 DPRINTF("put_packet_id_q %s size %d\n", q->name, q->size);
2481 qemu_put_be32(f, q->size);
2482 QTAILQ_FOREACH(e, &q->head, next) {
2483 qemu_put_be64(f, e->id);
2484 remain--;
2485 }
2486 assert(remain == 0);
2487
2488 return 0;
2489 }
2490
2491 static int usbredir_get_packet_id_q(QEMUFile *f, void *priv, size_t unused,
2492 const VMStateField *field)
2493 {
2494 struct PacketIdQueue *q = priv;
2495 USBRedirDevice *dev = q->dev;
2496 int i, size;
2497 uint64_t id;
2498
2499 size = qemu_get_be32(f);
2500 DPRINTF("get_packet_id_q %s size %d\n", q->name, size);
2501 for (i = 0; i < size; i++) {
2502 id = qemu_get_be64(f);
2503 packet_id_queue_add(q, id);
2504 }
2505 assert(q->size == size);
2506 return 0;
2507 }
2508
2509 static const VMStateInfo usbredir_ep_packet_id_q_vmstate_info = {
2510 .name = "usb-redir-packet-id-q",
2511 .put = usbredir_put_packet_id_q,
2512 .get = usbredir_get_packet_id_q,
2513 };
2514
2515 static const VMStateDescription usbredir_ep_packet_id_queue_vmstate = {
2516 .name = "usb-redir-packet-id-queue",
2517 .version_id = 1,
2518 .minimum_version_id = 1,
2519 .fields = (const VMStateField[]) {
2520 {
2521 .name = "queue",
2522 .version_id = 0,
2523 .field_exists = NULL,
2524 .size = 0,
2525 .info = &usbredir_ep_packet_id_q_vmstate_info,
2526 .flags = VMS_SINGLE,
2527 .offset = 0,
2528 },
2529 VMSTATE_END_OF_LIST()
2530 }
2531 };
2532
2533
2534 /* For usb_redir_device_connect_header migration */
2535 static const VMStateDescription usbredir_device_info_vmstate = {
2536 .name = "usb-redir-device-info",
2537 .version_id = 1,
2538 .minimum_version_id = 1,
2539 .fields = (const VMStateField[]) {
2540 VMSTATE_UINT8(speed, struct usb_redir_device_connect_header),
2541 VMSTATE_UINT8(device_class, struct usb_redir_device_connect_header),
2542 VMSTATE_UINT8(device_subclass, struct usb_redir_device_connect_header),
2543 VMSTATE_UINT8(device_protocol, struct usb_redir_device_connect_header),
2544 VMSTATE_UINT16(vendor_id, struct usb_redir_device_connect_header),
2545 VMSTATE_UINT16(product_id, struct usb_redir_device_connect_header),
2546 VMSTATE_UINT16(device_version_bcd,
2547 struct usb_redir_device_connect_header),
2548 VMSTATE_END_OF_LIST()
2549 }
2550 };
2551
2552
2553 /* For usb_redir_interface_info_header migration */
2554 static const VMStateDescription usbredir_interface_info_vmstate = {
2555 .name = "usb-redir-interface-info",
2556 .version_id = 1,
2557 .minimum_version_id = 1,
2558 .fields = (const VMStateField[]) {
2559 VMSTATE_UINT32(interface_count,
2560 struct usb_redir_interface_info_header),
2561 VMSTATE_UINT8_ARRAY(interface,
2562 struct usb_redir_interface_info_header, 32),
2563 VMSTATE_UINT8_ARRAY(interface_class,
2564 struct usb_redir_interface_info_header, 32),
2565 VMSTATE_UINT8_ARRAY(interface_subclass,
2566 struct usb_redir_interface_info_header, 32),
2567 VMSTATE_UINT8_ARRAY(interface_protocol,
2568 struct usb_redir_interface_info_header, 32),
2569 VMSTATE_END_OF_LIST()
2570 }
2571 };
2572
2573
2574 /* And finally the USBRedirDevice vmstate itself */
2575 static const VMStateDescription usbredir_vmstate = {
2576 .name = "usb-redir",
2577 .version_id = 1,
2578 .minimum_version_id = 1,
2579 .pre_save = usbredir_pre_save,
2580 .post_load = usbredir_post_load,
2581 .fields = (const VMStateField[]) {
2582 VMSTATE_USB_DEVICE(dev, USBRedirDevice),
2583 VMSTATE_TIMER_PTR(attach_timer, USBRedirDevice),
2584 {
2585 .name = "parser",
2586 .version_id = 0,
2587 .field_exists = NULL,
2588 .size = 0,
2589 .info = &usbredir_parser_vmstate_info,
2590 .flags = VMS_SINGLE,
2591 .offset = 0,
2592 },
2593 VMSTATE_STRUCT_ARRAY(endpoint, USBRedirDevice, MAX_ENDPOINTS, 1,
2594 usbredir_ep_vmstate, struct endp_data),
2595 VMSTATE_STRUCT(cancelled, USBRedirDevice, 1,
2596 usbredir_ep_packet_id_queue_vmstate,
2597 struct PacketIdQueue),
2598 VMSTATE_STRUCT(already_in_flight, USBRedirDevice, 1,
2599 usbredir_ep_packet_id_queue_vmstate,
2600 struct PacketIdQueue),
2601 VMSTATE_STRUCT(device_info, USBRedirDevice, 1,
2602 usbredir_device_info_vmstate,
2603 struct usb_redir_device_connect_header),
2604 VMSTATE_STRUCT(interface_info, USBRedirDevice, 1,
2605 usbredir_interface_info_vmstate,
2606 struct usb_redir_interface_info_header),
2607 VMSTATE_END_OF_LIST()
2608 }
2609 };
2610
2611 static const Property usbredir_properties[] = {
2612 DEFINE_PROP_CHR("chardev", USBRedirDevice, cs),
2613 DEFINE_PROP_UINT8("debug", USBRedirDevice, debug, usbredirparser_warning),
2614 DEFINE_PROP_STRING("filter", USBRedirDevice, filter_str),
2615 DEFINE_PROP_BOOL("streams", USBRedirDevice, enable_streams, true),
2616 DEFINE_PROP_BOOL("suppress-remote-wake", USBRedirDevice,
2617 suppress_remote_wake, true),
2618 };
2619
2620 static void usbredir_class_initfn(ObjectClass *klass, const void *data)
2621 {
2622 USBDeviceClass *uc = USB_DEVICE_CLASS(klass);
2623 DeviceClass *dc = DEVICE_CLASS(klass);
2624
2625 uc->realize = usbredir_realize;
2626 uc->product_desc = "USB Redirection Device";
2627 uc->unrealize = usbredir_unrealize;
2628 uc->cancel_packet = usbredir_cancel_packet;
2629 uc->handle_reset = usbredir_handle_reset;
2630 uc->handle_data = usbredir_handle_data;
2631 uc->handle_control = usbredir_handle_control;
2632 uc->flush_ep_queue = usbredir_flush_ep_queue;
2633 uc->ep_stopped = usbredir_ep_stopped;
2634 uc->alloc_streams = usbredir_alloc_streams;
2635 uc->free_streams = usbredir_free_streams;
2636 dc->vmsd = &usbredir_vmstate;
2637 device_class_set_props(dc, usbredir_properties);
2638 set_bit(DEVICE_CATEGORY_MISC, dc->categories);
2639 }
2640
2641 static void usbredir_instance_init(Object *obj)
2642 {
2643 USBDevice *udev = USB_DEVICE(obj);
2644 USBRedirDevice *dev = USB_REDIRECT(udev);
2645
2646 device_add_bootindex_property(obj, &dev->bootindex,
2647 "bootindex", NULL,
2648 &udev->qdev);
2649 }
2650
2651 static const TypeInfo usbredir_dev_info = {
2652 .name = TYPE_USB_REDIR,
2653 .parent = TYPE_USB_DEVICE,
2654 .instance_size = sizeof(USBRedirDevice),
2655 .class_init = usbredir_class_initfn,
2656 .instance_init = usbredir_instance_init,
2657 };
2658 module_obj(TYPE_USB_REDIR);
2659 module_kconfig(USB);
2660
2661 static void usbredir_register_types(void)
2662 {
2663 type_register_static(&usbredir_dev_info);
2664 }
2665
2666 type_init(usbredir_register_types)