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