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