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