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