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