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