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