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