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