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