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