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