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