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