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