xref: /openbmc/qemu/hw/usb/host-libusb.c (revision 500eb6db)
1 /*
2  * Linux host USB redirector
3  *
4  * Copyright (c) 2005 Fabrice Bellard
5  *
6  * Copyright (c) 2008 Max Krasnyansky
7  *      Support for host device auto connect & disconnect
8  *      Major rewrite to support fully async operation
9  *
10  * Copyright 2008 TJ <linux@tjworld.net>
11  *      Added flexible support for /dev/bus/usb /sys/bus/usb/devices in addition
12  *      to the legacy /proc/bus/usb USB device discovery and handling
13  *
14  * (c) 2012 Gerd Hoffmann <kraxel@redhat.com>
15  *      Completely rewritten to use libusb instead of usbfs ioctls.
16  *
17  * Permission is hereby granted, free of charge, to any person obtaining a copy
18  * of this software and associated documentation files (the "Software"), to deal
19  * in the Software without restriction, including without limitation the rights
20  * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
21  * copies of the Software, and to permit persons to whom the Software is
22  * furnished to do so, subject to the following conditions:
23  *
24  * The above copyright notice and this permission notice shall be included in
25  * all copies or substantial portions of the Software.
26  *
27  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
28  * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
29  * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
30  * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
31  * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
32  * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
33  * THE SOFTWARE.
34  */
35 
36 #include "qemu/osdep.h"
37 #ifndef CONFIG_WIN32
38 #include <poll.h>
39 #endif
40 #include <libusb.h>
41 
42 #include "qapi/error.h"
43 #include "monitor/monitor.h"
44 #include "qemu/error-report.h"
45 #include "qemu/module.h"
46 #include "sysemu/sysemu.h"
47 #include "trace.h"
48 
49 #include "hw/usb.h"
50 
51 /* ------------------------------------------------------------------------ */
52 
53 #define TYPE_USB_HOST_DEVICE "usb-host"
54 #define USB_HOST_DEVICE(obj) \
55      OBJECT_CHECK(USBHostDevice, (obj), TYPE_USB_HOST_DEVICE)
56 
57 typedef struct USBHostDevice USBHostDevice;
58 typedef struct USBHostRequest USBHostRequest;
59 typedef struct USBHostIsoXfer USBHostIsoXfer;
60 typedef struct USBHostIsoRing USBHostIsoRing;
61 
62 struct USBAutoFilter {
63     uint32_t bus_num;
64     uint32_t addr;
65     char     *port;
66     uint32_t vendor_id;
67     uint32_t product_id;
68 };
69 
70 enum USBHostDeviceOptions {
71     USB_HOST_OPT_PIPELINE,
72 };
73 
74 struct USBHostDevice {
75     USBDevice parent_obj;
76 
77     /* properties */
78     struct USBAutoFilter             match;
79     int32_t                          bootindex;
80     uint32_t                         iso_urb_count;
81     uint32_t                         iso_urb_frames;
82     uint32_t                         options;
83     uint32_t                         loglevel;
84     bool                             needs_autoscan;
85     bool                             allow_guest_reset;
86     /* state */
87     QTAILQ_ENTRY(USBHostDevice)      next;
88     int                              seen, errcount;
89     int                              bus_num;
90     int                              addr;
91     char                             port[16];
92 
93     libusb_device                    *dev;
94     libusb_device_handle             *dh;
95     struct libusb_device_descriptor  ddesc;
96 
97     struct {
98         bool                         detached;
99         bool                         claimed;
100     } ifs[USB_MAX_INTERFACES];
101 
102     /* callbacks & friends */
103     QEMUBH                           *bh_nodev;
104     QEMUBH                           *bh_postld;
105     bool                             bh_postld_pending;
106     Notifier                         exit;
107 
108     /* request queues */
109     QTAILQ_HEAD(, USBHostRequest)    requests;
110     QTAILQ_HEAD(, USBHostIsoRing)    isorings;
111 };
112 
113 struct USBHostRequest {
114     USBHostDevice                    *host;
115     USBPacket                        *p;
116     bool                             in;
117     struct libusb_transfer           *xfer;
118     unsigned char                    *buffer;
119     unsigned char                    *cbuf;
120     unsigned int                     clen;
121     bool                             usb3ep0quirk;
122     QTAILQ_ENTRY(USBHostRequest)     next;
123 };
124 
125 struct USBHostIsoXfer {
126     USBHostIsoRing                   *ring;
127     struct libusb_transfer           *xfer;
128     bool                             copy_complete;
129     unsigned int                     packet;
130     QTAILQ_ENTRY(USBHostIsoXfer)     next;
131 };
132 
133 struct USBHostIsoRing {
134     USBHostDevice                    *host;
135     USBEndpoint                      *ep;
136     QTAILQ_HEAD(, USBHostIsoXfer)    unused;
137     QTAILQ_HEAD(, USBHostIsoXfer)    inflight;
138     QTAILQ_HEAD(, USBHostIsoXfer)    copy;
139     QTAILQ_ENTRY(USBHostIsoRing)     next;
140 };
141 
142 static QTAILQ_HEAD(, USBHostDevice) hostdevs =
143     QTAILQ_HEAD_INITIALIZER(hostdevs);
144 
145 static void usb_host_auto_check(void *unused);
146 static void usb_host_release_interfaces(USBHostDevice *s);
147 static void usb_host_nodev(USBHostDevice *s);
148 static void usb_host_detach_kernel(USBHostDevice *s);
149 static void usb_host_attach_kernel(USBHostDevice *s);
150 
151 /* ------------------------------------------------------------------------ */
152 
153 #ifndef LIBUSB_LOG_LEVEL_WARNING /* older libusb didn't define these */
154 #define LIBUSB_LOG_LEVEL_WARNING 2
155 #endif
156 
157 /* ------------------------------------------------------------------------ */
158 
159 #define CONTROL_TIMEOUT  10000        /* 10 sec    */
160 #define BULK_TIMEOUT         0        /* unlimited */
161 #define INTR_TIMEOUT         0        /* unlimited */
162 
163 #ifndef LIBUSB_API_VERSION
164 # define LIBUSB_API_VERSION LIBUSBX_API_VERSION
165 #endif
166 #if LIBUSB_API_VERSION >= 0x01000103
167 # define HAVE_STREAMS 1
168 #endif
169 
170 static const char *speed_name[] = {
171     [LIBUSB_SPEED_UNKNOWN] = "?",
172     [LIBUSB_SPEED_LOW]     = "1.5",
173     [LIBUSB_SPEED_FULL]    = "12",
174     [LIBUSB_SPEED_HIGH]    = "480",
175     [LIBUSB_SPEED_SUPER]   = "5000",
176 };
177 
178 static const unsigned int speed_map[] = {
179     [LIBUSB_SPEED_LOW]     = USB_SPEED_LOW,
180     [LIBUSB_SPEED_FULL]    = USB_SPEED_FULL,
181     [LIBUSB_SPEED_HIGH]    = USB_SPEED_HIGH,
182     [LIBUSB_SPEED_SUPER]   = USB_SPEED_SUPER,
183 };
184 
185 static const unsigned int status_map[] = {
186     [LIBUSB_TRANSFER_COMPLETED] = USB_RET_SUCCESS,
187     [LIBUSB_TRANSFER_ERROR]     = USB_RET_IOERROR,
188     [LIBUSB_TRANSFER_TIMED_OUT] = USB_RET_IOERROR,
189     [LIBUSB_TRANSFER_CANCELLED] = USB_RET_IOERROR,
190     [LIBUSB_TRANSFER_STALL]     = USB_RET_STALL,
191     [LIBUSB_TRANSFER_NO_DEVICE] = USB_RET_NODEV,
192     [LIBUSB_TRANSFER_OVERFLOW]  = USB_RET_BABBLE,
193 };
194 
195 static const char *err_names[] = {
196     [-LIBUSB_ERROR_IO]               = "IO",
197     [-LIBUSB_ERROR_INVALID_PARAM]    = "INVALID_PARAM",
198     [-LIBUSB_ERROR_ACCESS]           = "ACCESS",
199     [-LIBUSB_ERROR_NO_DEVICE]        = "NO_DEVICE",
200     [-LIBUSB_ERROR_NOT_FOUND]        = "NOT_FOUND",
201     [-LIBUSB_ERROR_BUSY]             = "BUSY",
202     [-LIBUSB_ERROR_TIMEOUT]          = "TIMEOUT",
203     [-LIBUSB_ERROR_OVERFLOW]         = "OVERFLOW",
204     [-LIBUSB_ERROR_PIPE]             = "PIPE",
205     [-LIBUSB_ERROR_INTERRUPTED]      = "INTERRUPTED",
206     [-LIBUSB_ERROR_NO_MEM]           = "NO_MEM",
207     [-LIBUSB_ERROR_NOT_SUPPORTED]    = "NOT_SUPPORTED",
208     [-LIBUSB_ERROR_OTHER]            = "OTHER",
209 };
210 
211 static libusb_context *ctx;
212 static uint32_t loglevel;
213 
214 #ifndef CONFIG_WIN32
215 
216 static void usb_host_handle_fd(void *opaque)
217 {
218     struct timeval tv = { 0, 0 };
219     libusb_handle_events_timeout(ctx, &tv);
220 }
221 
222 static void usb_host_add_fd(int fd, short events, void *user_data)
223 {
224     qemu_set_fd_handler(fd,
225                         (events & POLLIN)  ? usb_host_handle_fd : NULL,
226                         (events & POLLOUT) ? usb_host_handle_fd : NULL,
227                         ctx);
228 }
229 
230 static void usb_host_del_fd(int fd, void *user_data)
231 {
232     qemu_set_fd_handler(fd, NULL, NULL, NULL);
233 }
234 
235 #endif /* !CONFIG_WIN32 */
236 
237 static int usb_host_init(void)
238 {
239 #ifndef CONFIG_WIN32
240     const struct libusb_pollfd **poll;
241 #endif
242     int rc;
243 
244     if (ctx) {
245         return 0;
246     }
247     rc = libusb_init(&ctx);
248     if (rc != 0) {
249         return -1;
250     }
251 #if LIBUSB_API_VERSION >= 0x01000106
252     libusb_set_option(ctx, LIBUSB_OPTION_LOG_LEVEL, loglevel);
253 #else
254     libusb_set_debug(ctx, loglevel);
255 #endif
256 #ifdef CONFIG_WIN32
257     /* FIXME: add support for Windows. */
258 #else
259     libusb_set_pollfd_notifiers(ctx, usb_host_add_fd,
260                                 usb_host_del_fd,
261                                 ctx);
262     poll = libusb_get_pollfds(ctx);
263     if (poll) {
264         int i;
265         for (i = 0; poll[i] != NULL; i++) {
266             usb_host_add_fd(poll[i]->fd, poll[i]->events, ctx);
267         }
268     }
269     free(poll);
270 #endif
271     return 0;
272 }
273 
274 static int usb_host_get_port(libusb_device *dev, char *port, size_t len)
275 {
276     uint8_t path[7];
277     size_t off;
278     int rc, i;
279 
280 #if LIBUSB_API_VERSION >= 0x01000102
281     rc = libusb_get_port_numbers(dev, path, 7);
282 #else
283     rc = libusb_get_port_path(ctx, dev, path, 7);
284 #endif
285     if (rc < 0) {
286         return 0;
287     }
288     off = snprintf(port, len, "%d", path[0]);
289     for (i = 1; i < rc; i++) {
290         off += snprintf(port+off, len-off, ".%d", path[i]);
291     }
292     return off;
293 }
294 
295 static void usb_host_libusb_error(const char *func, int rc)
296 {
297     const char *errname;
298 
299     if (rc >= 0) {
300         return;
301     }
302 
303     if (-rc < ARRAY_SIZE(err_names) && err_names[-rc]) {
304         errname = err_names[-rc];
305     } else {
306         errname = "?";
307     }
308     error_report("%s: %d [%s]", func, rc, errname);
309 }
310 
311 /* ------------------------------------------------------------------------ */
312 
313 static bool usb_host_use_combining(USBEndpoint *ep)
314 {
315     int type;
316 
317     if (!ep->pipeline) {
318         return false;
319     }
320     if (ep->pid != USB_TOKEN_IN) {
321         return false;
322     }
323     type = usb_ep_get_type(ep->dev, ep->pid, ep->nr);
324     if (type != USB_ENDPOINT_XFER_BULK) {
325         return false;
326     }
327     return true;
328 }
329 
330 /* ------------------------------------------------------------------------ */
331 
332 static USBHostRequest *usb_host_req_alloc(USBHostDevice *s, USBPacket *p,
333                                           bool in, size_t bufsize)
334 {
335     USBHostRequest *r = g_new0(USBHostRequest, 1);
336 
337     r->host = s;
338     r->p = p;
339     r->in = in;
340     r->xfer = libusb_alloc_transfer(0);
341     if (bufsize) {
342         r->buffer = g_malloc(bufsize);
343     }
344     QTAILQ_INSERT_TAIL(&s->requests, r, next);
345     return r;
346 }
347 
348 static void usb_host_req_free(USBHostRequest *r)
349 {
350     if (r->host) {
351         QTAILQ_REMOVE(&r->host->requests, r, next);
352     }
353     libusb_free_transfer(r->xfer);
354     g_free(r->buffer);
355     g_free(r);
356 }
357 
358 static USBHostRequest *usb_host_req_find(USBHostDevice *s, USBPacket *p)
359 {
360     USBHostRequest *r;
361 
362     QTAILQ_FOREACH(r, &s->requests, next) {
363         if (r->p == p) {
364             return r;
365         }
366     }
367     return NULL;
368 }
369 
370 static void LIBUSB_CALL usb_host_req_complete_ctrl(struct libusb_transfer *xfer)
371 {
372     USBHostRequest *r = xfer->user_data;
373     USBHostDevice  *s = r->host;
374     bool disconnect = (xfer->status == LIBUSB_TRANSFER_NO_DEVICE);
375 
376     if (r->p == NULL) {
377         goto out; /* request was canceled */
378     }
379 
380     r->p->status = status_map[xfer->status];
381     r->p->actual_length = xfer->actual_length;
382     if (r->in && xfer->actual_length) {
383         memcpy(r->cbuf, r->buffer + 8, xfer->actual_length);
384 
385         /* Fix up USB-3 ep0 maxpacket size to allow superspeed connected devices
386          * to work redirected to a not superspeed capable hcd */
387         if (r->usb3ep0quirk && xfer->actual_length >= 18 &&
388             r->cbuf[7] == 9) {
389             r->cbuf[7] = 64;
390         }
391     }
392     trace_usb_host_req_complete(s->bus_num, s->addr, r->p,
393                                 r->p->status, r->p->actual_length);
394     usb_generic_async_ctrl_complete(USB_DEVICE(s), r->p);
395 
396 out:
397     usb_host_req_free(r);
398     if (disconnect) {
399         usb_host_nodev(s);
400     }
401 }
402 
403 static void LIBUSB_CALL usb_host_req_complete_data(struct libusb_transfer *xfer)
404 {
405     USBHostRequest *r = xfer->user_data;
406     USBHostDevice  *s = r->host;
407     bool disconnect = (xfer->status == LIBUSB_TRANSFER_NO_DEVICE);
408 
409     if (r->p == NULL) {
410         goto out; /* request was canceled */
411     }
412 
413     r->p->status = status_map[xfer->status];
414     if (r->in && xfer->actual_length) {
415         usb_packet_copy(r->p, r->buffer, xfer->actual_length);
416     }
417     trace_usb_host_req_complete(s->bus_num, s->addr, r->p,
418                                 r->p->status, r->p->actual_length);
419     if (usb_host_use_combining(r->p->ep)) {
420         usb_combined_input_packet_complete(USB_DEVICE(s), r->p);
421     } else {
422         usb_packet_complete(USB_DEVICE(s), r->p);
423     }
424 
425 out:
426     usb_host_req_free(r);
427     if (disconnect) {
428         usb_host_nodev(s);
429     }
430 }
431 
432 static void usb_host_req_abort(USBHostRequest *r)
433 {
434     USBHostDevice  *s = r->host;
435     bool inflight = (r->p && r->p->state == USB_PACKET_ASYNC);
436 
437     if (inflight) {
438         r->p->status = USB_RET_NODEV;
439         trace_usb_host_req_complete(s->bus_num, s->addr, r->p,
440                                     r->p->status, r->p->actual_length);
441         if (r->p->ep->nr == 0) {
442             usb_generic_async_ctrl_complete(USB_DEVICE(s), r->p);
443         } else {
444             usb_packet_complete(USB_DEVICE(s), r->p);
445         }
446         r->p = NULL;
447     }
448 
449     QTAILQ_REMOVE(&r->host->requests, r, next);
450     r->host = NULL;
451 
452     if (inflight) {
453         libusb_cancel_transfer(r->xfer);
454     }
455 }
456 
457 /* ------------------------------------------------------------------------ */
458 
459 static void LIBUSB_CALL
460 usb_host_req_complete_iso(struct libusb_transfer *transfer)
461 {
462     USBHostIsoXfer *xfer = transfer->user_data;
463 
464     if (!xfer) {
465         /* USBHostIsoXfer released while inflight */
466         g_free(transfer->buffer);
467         libusb_free_transfer(transfer);
468         return;
469     }
470 
471     QTAILQ_REMOVE(&xfer->ring->inflight, xfer, next);
472     if (QTAILQ_EMPTY(&xfer->ring->inflight)) {
473         USBHostDevice *s = xfer->ring->host;
474         trace_usb_host_iso_stop(s->bus_num, s->addr, xfer->ring->ep->nr);
475     }
476     if (xfer->ring->ep->pid == USB_TOKEN_IN) {
477         QTAILQ_INSERT_TAIL(&xfer->ring->copy, xfer, next);
478         usb_wakeup(xfer->ring->ep, 0);
479     } else {
480         QTAILQ_INSERT_TAIL(&xfer->ring->unused, xfer, next);
481     }
482 }
483 
484 static USBHostIsoRing *usb_host_iso_alloc(USBHostDevice *s, USBEndpoint *ep)
485 {
486     USBHostIsoRing *ring = g_new0(USBHostIsoRing, 1);
487     USBHostIsoXfer *xfer;
488     /* FIXME: check interval (for now assume one xfer per frame) */
489     int packets = s->iso_urb_frames;
490     int i;
491 
492     ring->host = s;
493     ring->ep = ep;
494     QTAILQ_INIT(&ring->unused);
495     QTAILQ_INIT(&ring->inflight);
496     QTAILQ_INIT(&ring->copy);
497     QTAILQ_INSERT_TAIL(&s->isorings, ring, next);
498 
499     for (i = 0; i < s->iso_urb_count; i++) {
500         xfer = g_new0(USBHostIsoXfer, 1);
501         xfer->ring = ring;
502         xfer->xfer = libusb_alloc_transfer(packets);
503         xfer->xfer->dev_handle = s->dh;
504         xfer->xfer->type = LIBUSB_TRANSFER_TYPE_ISOCHRONOUS;
505 
506         xfer->xfer->endpoint = ring->ep->nr;
507         if (ring->ep->pid == USB_TOKEN_IN) {
508             xfer->xfer->endpoint |= USB_DIR_IN;
509         }
510         xfer->xfer->callback = usb_host_req_complete_iso;
511         xfer->xfer->user_data = xfer;
512 
513         xfer->xfer->num_iso_packets = packets;
514         xfer->xfer->length = ring->ep->max_packet_size * packets;
515         xfer->xfer->buffer = g_malloc0(xfer->xfer->length);
516 
517         QTAILQ_INSERT_TAIL(&ring->unused, xfer, next);
518     }
519 
520     return ring;
521 }
522 
523 static USBHostIsoRing *usb_host_iso_find(USBHostDevice *s, USBEndpoint *ep)
524 {
525     USBHostIsoRing *ring;
526 
527     QTAILQ_FOREACH(ring, &s->isorings, next) {
528         if (ring->ep == ep) {
529             return ring;
530         }
531     }
532     return NULL;
533 }
534 
535 static void usb_host_iso_reset_xfer(USBHostIsoXfer *xfer)
536 {
537     libusb_set_iso_packet_lengths(xfer->xfer,
538                                   xfer->ring->ep->max_packet_size);
539     xfer->packet = 0;
540     xfer->copy_complete = false;
541 }
542 
543 static void usb_host_iso_free_xfer(USBHostIsoXfer *xfer, bool inflight)
544 {
545     if (inflight) {
546         xfer->xfer->user_data = NULL;
547     } else {
548         g_free(xfer->xfer->buffer);
549         libusb_free_transfer(xfer->xfer);
550     }
551     g_free(xfer);
552 }
553 
554 static void usb_host_iso_free(USBHostIsoRing *ring)
555 {
556     USBHostIsoXfer *xfer;
557 
558     while ((xfer = QTAILQ_FIRST(&ring->inflight)) != NULL) {
559         QTAILQ_REMOVE(&ring->inflight, xfer, next);
560         usb_host_iso_free_xfer(xfer, true);
561     }
562     while ((xfer = QTAILQ_FIRST(&ring->unused)) != NULL) {
563         QTAILQ_REMOVE(&ring->unused, xfer, next);
564         usb_host_iso_free_xfer(xfer, false);
565     }
566     while ((xfer = QTAILQ_FIRST(&ring->copy)) != NULL) {
567         QTAILQ_REMOVE(&ring->copy, xfer, next);
568         usb_host_iso_free_xfer(xfer, false);
569     }
570 
571     QTAILQ_REMOVE(&ring->host->isorings, ring, next);
572     g_free(ring);
573 }
574 
575 static void usb_host_iso_free_all(USBHostDevice *s)
576 {
577     USBHostIsoRing *ring;
578 
579     while ((ring = QTAILQ_FIRST(&s->isorings)) != NULL) {
580         usb_host_iso_free(ring);
581     }
582 }
583 
584 static bool usb_host_iso_data_copy(USBHostIsoXfer *xfer, USBPacket *p)
585 {
586     unsigned int psize;
587     unsigned char *buf;
588 
589     buf = libusb_get_iso_packet_buffer_simple(xfer->xfer, xfer->packet);
590     if (p->pid == USB_TOKEN_OUT) {
591         psize = p->iov.size;
592         if (psize > xfer->ring->ep->max_packet_size) {
593             /* should not happen (guest bug) */
594             psize = xfer->ring->ep->max_packet_size;
595         }
596         xfer->xfer->iso_packet_desc[xfer->packet].length = psize;
597     } else {
598         psize = xfer->xfer->iso_packet_desc[xfer->packet].actual_length;
599         if (psize > p->iov.size) {
600             /* should not happen (guest bug) */
601             psize = p->iov.size;
602         }
603     }
604     usb_packet_copy(p, buf, psize);
605     xfer->packet++;
606     xfer->copy_complete = (xfer->packet == xfer->xfer->num_iso_packets);
607     return xfer->copy_complete;
608 }
609 
610 static void usb_host_iso_data_in(USBHostDevice *s, USBPacket *p)
611 {
612     USBHostIsoRing *ring;
613     USBHostIsoXfer *xfer;
614     bool disconnect = false;
615     int rc;
616 
617     ring = usb_host_iso_find(s, p->ep);
618     if (ring == NULL) {
619         ring = usb_host_iso_alloc(s, p->ep);
620     }
621 
622     /* copy data to guest */
623     xfer = QTAILQ_FIRST(&ring->copy);
624     if (xfer != NULL) {
625         if (usb_host_iso_data_copy(xfer, p)) {
626             QTAILQ_REMOVE(&ring->copy, xfer, next);
627             QTAILQ_INSERT_TAIL(&ring->unused, xfer, next);
628         }
629     }
630 
631     /* submit empty bufs to host */
632     while ((xfer = QTAILQ_FIRST(&ring->unused)) != NULL) {
633         QTAILQ_REMOVE(&ring->unused, xfer, next);
634         usb_host_iso_reset_xfer(xfer);
635         rc = libusb_submit_transfer(xfer->xfer);
636         if (rc != 0) {
637             usb_host_libusb_error("libusb_submit_transfer [iso]", rc);
638             QTAILQ_INSERT_TAIL(&ring->unused, xfer, next);
639             if (rc == LIBUSB_ERROR_NO_DEVICE) {
640                 disconnect = true;
641             }
642             break;
643         }
644         if (QTAILQ_EMPTY(&ring->inflight)) {
645             trace_usb_host_iso_start(s->bus_num, s->addr, p->ep->nr);
646         }
647         QTAILQ_INSERT_TAIL(&ring->inflight, xfer, next);
648     }
649 
650     if (disconnect) {
651         usb_host_nodev(s);
652     }
653 }
654 
655 static void usb_host_iso_data_out(USBHostDevice *s, USBPacket *p)
656 {
657     USBHostIsoRing *ring;
658     USBHostIsoXfer *xfer;
659     bool disconnect = false;
660     int rc, filled = 0;
661 
662     ring = usb_host_iso_find(s, p->ep);
663     if (ring == NULL) {
664         ring = usb_host_iso_alloc(s, p->ep);
665     }
666 
667     /* copy data from guest */
668     xfer = QTAILQ_FIRST(&ring->copy);
669     while (xfer != NULL && xfer->copy_complete) {
670         filled++;
671         xfer = QTAILQ_NEXT(xfer, next);
672     }
673     if (xfer == NULL) {
674         xfer = QTAILQ_FIRST(&ring->unused);
675         if (xfer == NULL) {
676             trace_usb_host_iso_out_of_bufs(s->bus_num, s->addr, p->ep->nr);
677             return;
678         }
679         QTAILQ_REMOVE(&ring->unused, xfer, next);
680         usb_host_iso_reset_xfer(xfer);
681         QTAILQ_INSERT_TAIL(&ring->copy, xfer, next);
682     }
683     usb_host_iso_data_copy(xfer, p);
684 
685     if (QTAILQ_EMPTY(&ring->inflight)) {
686         /* wait until half of our buffers are filled
687            before kicking the iso out stream */
688         if (filled*2 < s->iso_urb_count) {
689             return;
690         }
691     }
692 
693     /* submit filled bufs to host */
694     while ((xfer = QTAILQ_FIRST(&ring->copy)) != NULL &&
695            xfer->copy_complete) {
696         QTAILQ_REMOVE(&ring->copy, xfer, next);
697         rc = libusb_submit_transfer(xfer->xfer);
698         if (rc != 0) {
699             usb_host_libusb_error("libusb_submit_transfer [iso]", rc);
700             QTAILQ_INSERT_TAIL(&ring->unused, xfer, next);
701             if (rc == LIBUSB_ERROR_NO_DEVICE) {
702                 disconnect = true;
703             }
704             break;
705         }
706         if (QTAILQ_EMPTY(&ring->inflight)) {
707             trace_usb_host_iso_start(s->bus_num, s->addr, p->ep->nr);
708         }
709         QTAILQ_INSERT_TAIL(&ring->inflight, xfer, next);
710     }
711 
712     if (disconnect) {
713         usb_host_nodev(s);
714     }
715 }
716 
717 /* ------------------------------------------------------------------------ */
718 
719 static void usb_host_speed_compat(USBHostDevice *s)
720 {
721     USBDevice *udev = USB_DEVICE(s);
722     struct libusb_config_descriptor *conf;
723     const struct libusb_interface_descriptor *intf;
724     const struct libusb_endpoint_descriptor *endp;
725 #ifdef HAVE_STREAMS
726     struct libusb_ss_endpoint_companion_descriptor *endp_ss_comp;
727 #endif
728     bool compat_high = true;
729     bool compat_full = true;
730     uint8_t type;
731     int rc, c, i, a, e;
732 
733     for (c = 0;; c++) {
734         rc = libusb_get_config_descriptor(s->dev, c, &conf);
735         if (rc != 0) {
736             break;
737         }
738         for (i = 0; i < conf->bNumInterfaces; i++) {
739             for (a = 0; a < conf->interface[i].num_altsetting; a++) {
740                 intf = &conf->interface[i].altsetting[a];
741                 for (e = 0; e < intf->bNumEndpoints; e++) {
742                     endp = &intf->endpoint[e];
743                     type = endp->bmAttributes & 0x3;
744                     switch (type) {
745                     case 0x01: /* ISO */
746                         compat_full = false;
747                         compat_high = false;
748                         break;
749                     case 0x02: /* BULK */
750 #ifdef HAVE_STREAMS
751                         rc = libusb_get_ss_endpoint_companion_descriptor
752                             (ctx, endp, &endp_ss_comp);
753                         if (rc == LIBUSB_SUCCESS) {
754                             int streams = endp_ss_comp->bmAttributes & 0x1f;
755                             if (streams) {
756                                 compat_full = false;
757                                 compat_high = false;
758                             }
759                             libusb_free_ss_endpoint_companion_descriptor
760                                 (endp_ss_comp);
761                         }
762 #endif
763                         break;
764                     case 0x03: /* INTERRUPT */
765                         if (endp->wMaxPacketSize > 64) {
766                             compat_full = false;
767                         }
768                         if (endp->wMaxPacketSize > 1024) {
769                             compat_high = false;
770                         }
771                         break;
772                     }
773                 }
774             }
775         }
776         libusb_free_config_descriptor(conf);
777     }
778 
779     udev->speedmask = (1 << udev->speed);
780     if (udev->speed == USB_SPEED_SUPER && compat_high) {
781         udev->speedmask |= USB_SPEED_MASK_HIGH;
782     }
783     if (udev->speed == USB_SPEED_SUPER && compat_full) {
784         udev->speedmask |= USB_SPEED_MASK_FULL;
785     }
786     if (udev->speed == USB_SPEED_HIGH && compat_full) {
787         udev->speedmask |= USB_SPEED_MASK_FULL;
788     }
789 }
790 
791 static void usb_host_ep_update(USBHostDevice *s)
792 {
793     static const char *tname[] = {
794         [USB_ENDPOINT_XFER_CONTROL] = "control",
795         [USB_ENDPOINT_XFER_ISOC]    = "isoc",
796         [USB_ENDPOINT_XFER_BULK]    = "bulk",
797         [USB_ENDPOINT_XFER_INT]     = "int",
798     };
799     USBDevice *udev = USB_DEVICE(s);
800     struct libusb_config_descriptor *conf;
801     const struct libusb_interface_descriptor *intf;
802     const struct libusb_endpoint_descriptor *endp;
803 #ifdef HAVE_STREAMS
804     struct libusb_ss_endpoint_companion_descriptor *endp_ss_comp;
805 #endif
806     uint8_t devep, type;
807     int pid, ep;
808     int rc, i, e;
809 
810     usb_ep_reset(udev);
811     rc = libusb_get_active_config_descriptor(s->dev, &conf);
812     if (rc != 0) {
813         return;
814     }
815     trace_usb_host_parse_config(s->bus_num, s->addr,
816                                 conf->bConfigurationValue, true);
817 
818     for (i = 0; i < conf->bNumInterfaces; i++) {
819         assert(udev->altsetting[i] < conf->interface[i].num_altsetting);
820         intf = &conf->interface[i].altsetting[udev->altsetting[i]];
821         trace_usb_host_parse_interface(s->bus_num, s->addr,
822                                        intf->bInterfaceNumber,
823                                        intf->bAlternateSetting, true);
824         for (e = 0; e < intf->bNumEndpoints; e++) {
825             endp = &intf->endpoint[e];
826 
827             devep = endp->bEndpointAddress;
828             pid = (devep & USB_DIR_IN) ? USB_TOKEN_IN : USB_TOKEN_OUT;
829             ep = devep & 0xf;
830             type = endp->bmAttributes & 0x3;
831 
832             if (ep == 0) {
833                 trace_usb_host_parse_error(s->bus_num, s->addr,
834                                            "invalid endpoint address");
835                 return;
836             }
837             if (usb_ep_get_type(udev, pid, ep) != USB_ENDPOINT_XFER_INVALID) {
838                 trace_usb_host_parse_error(s->bus_num, s->addr,
839                                            "duplicate endpoint address");
840                 return;
841             }
842 
843             trace_usb_host_parse_endpoint(s->bus_num, s->addr, ep,
844                                           (devep & USB_DIR_IN) ? "in" : "out",
845                                           tname[type], true);
846             usb_ep_set_max_packet_size(udev, pid, ep,
847                                        endp->wMaxPacketSize);
848             usb_ep_set_type(udev, pid, ep, type);
849             usb_ep_set_ifnum(udev, pid, ep, i);
850             usb_ep_set_halted(udev, pid, ep, 0);
851 #ifdef HAVE_STREAMS
852             if (type == LIBUSB_TRANSFER_TYPE_BULK &&
853                     libusb_get_ss_endpoint_companion_descriptor(ctx, endp,
854                         &endp_ss_comp) == LIBUSB_SUCCESS) {
855                 usb_ep_set_max_streams(udev, pid, ep,
856                                        endp_ss_comp->bmAttributes);
857                 libusb_free_ss_endpoint_companion_descriptor(endp_ss_comp);
858             }
859 #endif
860         }
861     }
862 
863     libusb_free_config_descriptor(conf);
864 }
865 
866 static int usb_host_open(USBHostDevice *s, libusb_device *dev)
867 {
868     USBDevice *udev = USB_DEVICE(s);
869     int bus_num = libusb_get_bus_number(dev);
870     int addr    = libusb_get_device_address(dev);
871     int rc;
872     Error *local_err = NULL;
873 
874     if (s->bh_postld_pending) {
875         return -1;
876     }
877 
878     trace_usb_host_open_started(bus_num, addr);
879 
880     if (s->dh != NULL) {
881         goto fail;
882     }
883     rc = libusb_open(dev, &s->dh);
884     if (rc != 0) {
885         goto fail;
886     }
887 
888     s->dev     = dev;
889     s->bus_num = bus_num;
890     s->addr    = addr;
891 
892     usb_host_detach_kernel(s);
893 
894     libusb_get_device_descriptor(dev, &s->ddesc);
895     usb_host_get_port(s->dev, s->port, sizeof(s->port));
896 
897     usb_ep_init(udev);
898     usb_host_ep_update(s);
899 
900     udev->speed     = speed_map[libusb_get_device_speed(dev)];
901     usb_host_speed_compat(s);
902 
903     if (s->ddesc.iProduct) {
904         libusb_get_string_descriptor_ascii(s->dh, s->ddesc.iProduct,
905                                            (unsigned char *)udev->product_desc,
906                                            sizeof(udev->product_desc));
907     } else {
908         snprintf(udev->product_desc, sizeof(udev->product_desc),
909                  "host:%d.%d", bus_num, addr);
910     }
911 
912     usb_device_attach(udev, &local_err);
913     if (local_err) {
914         error_report_err(local_err);
915         goto fail;
916     }
917 
918     trace_usb_host_open_success(bus_num, addr);
919     return 0;
920 
921 fail:
922     trace_usb_host_open_failure(bus_num, addr);
923     if (s->dh != NULL) {
924         usb_host_release_interfaces(s);
925         libusb_reset_device(s->dh);
926         usb_host_attach_kernel(s);
927         libusb_close(s->dh);
928         s->dh = NULL;
929         s->dev = NULL;
930     }
931     return -1;
932 }
933 
934 static void usb_host_abort_xfers(USBHostDevice *s)
935 {
936     USBHostRequest *r, *rtmp;
937 
938     QTAILQ_FOREACH_SAFE(r, &s->requests, next, rtmp) {
939         usb_host_req_abort(r);
940     }
941 }
942 
943 static int usb_host_close(USBHostDevice *s)
944 {
945     USBDevice *udev = USB_DEVICE(s);
946 
947     if (s->dh == NULL) {
948         return -1;
949     }
950 
951     trace_usb_host_close(s->bus_num, s->addr);
952 
953     usb_host_abort_xfers(s);
954     usb_host_iso_free_all(s);
955 
956     if (udev->attached) {
957         usb_device_detach(udev);
958     }
959 
960     usb_host_release_interfaces(s);
961     libusb_reset_device(s->dh);
962     usb_host_attach_kernel(s);
963     libusb_close(s->dh);
964     s->dh = NULL;
965     s->dev = NULL;
966 
967     usb_host_auto_check(NULL);
968     return 0;
969 }
970 
971 static void usb_host_nodev_bh(void *opaque)
972 {
973     USBHostDevice *s = opaque;
974     usb_host_close(s);
975 }
976 
977 static void usb_host_nodev(USBHostDevice *s)
978 {
979     if (!s->bh_nodev) {
980         s->bh_nodev = qemu_bh_new(usb_host_nodev_bh, s);
981     }
982     qemu_bh_schedule(s->bh_nodev);
983 }
984 
985 static void usb_host_exit_notifier(struct Notifier *n, void *data)
986 {
987     USBHostDevice *s = container_of(n, USBHostDevice, exit);
988 
989     if (s->dh) {
990         usb_host_release_interfaces(s);
991         libusb_reset_device(s->dh);
992         usb_host_attach_kernel(s);
993         libusb_close(s->dh);
994     }
995 }
996 
997 static libusb_device *usb_host_find_ref(int bus, int addr)
998 {
999     libusb_device **devs = NULL;
1000     libusb_device *ret = NULL;
1001     int i, n;
1002 
1003     if (usb_host_init() != 0) {
1004         return NULL;
1005     }
1006     n = libusb_get_device_list(ctx, &devs);
1007     for (i = 0; i < n; i++) {
1008         if (libusb_get_bus_number(devs[i]) == bus &&
1009             libusb_get_device_address(devs[i]) == addr) {
1010             ret = libusb_ref_device(devs[i]);
1011             break;
1012         }
1013     }
1014     libusb_free_device_list(devs, 1);
1015     return ret;
1016 }
1017 
1018 static void usb_host_realize(USBDevice *udev, Error **errp)
1019 {
1020     USBHostDevice *s = USB_HOST_DEVICE(udev);
1021     libusb_device *ldev;
1022     int rc;
1023 
1024     if (s->match.vendor_id > 0xffff) {
1025         error_setg(errp, "vendorid out of range");
1026         return;
1027     }
1028     if (s->match.product_id > 0xffff) {
1029         error_setg(errp, "productid out of range");
1030         return;
1031     }
1032     if (s->match.addr > 127) {
1033         error_setg(errp, "hostaddr out of range");
1034         return;
1035     }
1036 
1037     loglevel = s->loglevel;
1038     udev->flags |= (1 << USB_DEV_FLAG_IS_HOST);
1039     udev->auto_attach = 0;
1040     QTAILQ_INIT(&s->requests);
1041     QTAILQ_INIT(&s->isorings);
1042 
1043     if (s->match.addr && s->match.bus_num &&
1044         !s->match.vendor_id &&
1045         !s->match.product_id &&
1046         !s->match.port) {
1047         s->needs_autoscan = false;
1048         ldev = usb_host_find_ref(s->match.bus_num,
1049                                  s->match.addr);
1050         if (!ldev) {
1051             error_setg(errp, "failed to find host usb device %d:%d",
1052                        s->match.bus_num, s->match.addr);
1053             return;
1054         }
1055         rc = usb_host_open(s, ldev);
1056         libusb_unref_device(ldev);
1057         if (rc < 0) {
1058             error_setg(errp, "failed to open host usb device %d:%d",
1059                        s->match.bus_num, s->match.addr);
1060             return;
1061         }
1062     } else {
1063         s->needs_autoscan = true;
1064         QTAILQ_INSERT_TAIL(&hostdevs, s, next);
1065         usb_host_auto_check(NULL);
1066     }
1067 
1068     s->exit.notify = usb_host_exit_notifier;
1069     qemu_add_exit_notifier(&s->exit);
1070 }
1071 
1072 static void usb_host_instance_init(Object *obj)
1073 {
1074     USBDevice *udev = USB_DEVICE(obj);
1075     USBHostDevice *s = USB_HOST_DEVICE(udev);
1076 
1077     device_add_bootindex_property(obj, &s->bootindex,
1078                                   "bootindex", NULL,
1079                                   &udev->qdev, NULL);
1080 }
1081 
1082 static void usb_host_unrealize(USBDevice *udev, Error **errp)
1083 {
1084     USBHostDevice *s = USB_HOST_DEVICE(udev);
1085 
1086     qemu_remove_exit_notifier(&s->exit);
1087     if (s->needs_autoscan) {
1088         QTAILQ_REMOVE(&hostdevs, s, next);
1089     }
1090     usb_host_close(s);
1091 }
1092 
1093 static void usb_host_cancel_packet(USBDevice *udev, USBPacket *p)
1094 {
1095     USBHostDevice *s = USB_HOST_DEVICE(udev);
1096     USBHostRequest *r;
1097 
1098     if (p->combined) {
1099         usb_combined_packet_cancel(udev, p);
1100         return;
1101     }
1102 
1103     trace_usb_host_req_canceled(s->bus_num, s->addr, p);
1104 
1105     r = usb_host_req_find(s, p);
1106     if (r && r->p) {
1107         r->p = NULL; /* mark as dead */
1108         libusb_cancel_transfer(r->xfer);
1109     }
1110 }
1111 
1112 static void usb_host_detach_kernel(USBHostDevice *s)
1113 {
1114     struct libusb_config_descriptor *conf;
1115     int rc, i;
1116 
1117     rc = libusb_get_active_config_descriptor(s->dev, &conf);
1118     if (rc != 0) {
1119         return;
1120     }
1121     for (i = 0; i < USB_MAX_INTERFACES; i++) {
1122         rc = libusb_kernel_driver_active(s->dh, i);
1123         usb_host_libusb_error("libusb_kernel_driver_active", rc);
1124         if (rc != 1) {
1125             if (rc == 0) {
1126                 s->ifs[i].detached = true;
1127             }
1128             continue;
1129         }
1130         trace_usb_host_detach_kernel(s->bus_num, s->addr, i);
1131         rc = libusb_detach_kernel_driver(s->dh, i);
1132         usb_host_libusb_error("libusb_detach_kernel_driver", rc);
1133         s->ifs[i].detached = true;
1134     }
1135     libusb_free_config_descriptor(conf);
1136 }
1137 
1138 static void usb_host_attach_kernel(USBHostDevice *s)
1139 {
1140     struct libusb_config_descriptor *conf;
1141     int rc, i;
1142 
1143     rc = libusb_get_active_config_descriptor(s->dev, &conf);
1144     if (rc != 0) {
1145         return;
1146     }
1147     for (i = 0; i < USB_MAX_INTERFACES; i++) {
1148         if (!s->ifs[i].detached) {
1149             continue;
1150         }
1151         trace_usb_host_attach_kernel(s->bus_num, s->addr, i);
1152         libusb_attach_kernel_driver(s->dh, i);
1153         s->ifs[i].detached = false;
1154     }
1155     libusb_free_config_descriptor(conf);
1156 }
1157 
1158 static int usb_host_claim_interfaces(USBHostDevice *s, int configuration)
1159 {
1160     USBDevice *udev = USB_DEVICE(s);
1161     struct libusb_config_descriptor *conf;
1162     int rc, i, claimed;
1163 
1164     for (i = 0; i < USB_MAX_INTERFACES; i++) {
1165         udev->altsetting[i] = 0;
1166     }
1167     udev->ninterfaces   = 0;
1168     udev->configuration = 0;
1169 
1170     usb_host_detach_kernel(s);
1171 
1172     rc = libusb_get_active_config_descriptor(s->dev, &conf);
1173     if (rc != 0) {
1174         if (rc == LIBUSB_ERROR_NOT_FOUND) {
1175             /* address state - ignore */
1176             return USB_RET_SUCCESS;
1177         }
1178         return USB_RET_STALL;
1179     }
1180 
1181     claimed = 0;
1182     for (i = 0; i < USB_MAX_INTERFACES; i++) {
1183         trace_usb_host_claim_interface(s->bus_num, s->addr, configuration, i);
1184         rc = libusb_claim_interface(s->dh, i);
1185         if (rc == 0) {
1186             s->ifs[i].claimed = true;
1187             if (++claimed == conf->bNumInterfaces) {
1188                 break;
1189             }
1190         }
1191     }
1192     if (claimed != conf->bNumInterfaces) {
1193         return USB_RET_STALL;
1194     }
1195 
1196     udev->ninterfaces   = conf->bNumInterfaces;
1197     udev->configuration = configuration;
1198 
1199     libusb_free_config_descriptor(conf);
1200     return USB_RET_SUCCESS;
1201 }
1202 
1203 static void usb_host_release_interfaces(USBHostDevice *s)
1204 {
1205     int i, rc;
1206 
1207     for (i = 0; i < USB_MAX_INTERFACES; i++) {
1208         if (!s->ifs[i].claimed) {
1209             continue;
1210         }
1211         trace_usb_host_release_interface(s->bus_num, s->addr, i);
1212         rc = libusb_release_interface(s->dh, i);
1213         usb_host_libusb_error("libusb_release_interface", rc);
1214         s->ifs[i].claimed = false;
1215     }
1216 }
1217 
1218 static void usb_host_set_address(USBHostDevice *s, int addr)
1219 {
1220     USBDevice *udev = USB_DEVICE(s);
1221 
1222     trace_usb_host_set_address(s->bus_num, s->addr, addr);
1223     udev->addr = addr;
1224 }
1225 
1226 static void usb_host_set_config(USBHostDevice *s, int config, USBPacket *p)
1227 {
1228     int rc = 0;
1229 
1230     trace_usb_host_set_config(s->bus_num, s->addr, config);
1231 
1232     usb_host_release_interfaces(s);
1233     if (s->ddesc.bNumConfigurations != 1) {
1234         rc = libusb_set_configuration(s->dh, config);
1235         if (rc != 0) {
1236             usb_host_libusb_error("libusb_set_configuration", rc);
1237             p->status = USB_RET_STALL;
1238             if (rc == LIBUSB_ERROR_NO_DEVICE) {
1239                 usb_host_nodev(s);
1240             }
1241             return;
1242         }
1243     }
1244     p->status = usb_host_claim_interfaces(s, config);
1245     if (p->status != USB_RET_SUCCESS) {
1246         return;
1247     }
1248     usb_host_ep_update(s);
1249 }
1250 
1251 static void usb_host_set_interface(USBHostDevice *s, int iface, int alt,
1252                                    USBPacket *p)
1253 {
1254     USBDevice *udev = USB_DEVICE(s);
1255     int rc;
1256 
1257     trace_usb_host_set_interface(s->bus_num, s->addr, iface, alt);
1258 
1259     usb_host_iso_free_all(s);
1260 
1261     if (iface >= USB_MAX_INTERFACES) {
1262         p->status = USB_RET_STALL;
1263         return;
1264     }
1265 
1266     rc = libusb_set_interface_alt_setting(s->dh, iface, alt);
1267     if (rc != 0) {
1268         usb_host_libusb_error("libusb_set_interface_alt_setting", rc);
1269         p->status = USB_RET_STALL;
1270         if (rc == LIBUSB_ERROR_NO_DEVICE) {
1271             usb_host_nodev(s);
1272         }
1273         return;
1274     }
1275 
1276     udev->altsetting[iface] = alt;
1277     usb_host_ep_update(s);
1278 }
1279 
1280 static void usb_host_handle_control(USBDevice *udev, USBPacket *p,
1281                                     int request, int value, int index,
1282                                     int length, uint8_t *data)
1283 {
1284     USBHostDevice *s = USB_HOST_DEVICE(udev);
1285     USBHostRequest *r;
1286     int rc;
1287 
1288     trace_usb_host_req_control(s->bus_num, s->addr, p, request, value, index);
1289 
1290     if (s->dh == NULL) {
1291         p->status = USB_RET_NODEV;
1292         trace_usb_host_req_emulated(s->bus_num, s->addr, p, p->status);
1293         return;
1294     }
1295 
1296     switch (request) {
1297     case DeviceOutRequest | USB_REQ_SET_ADDRESS:
1298         usb_host_set_address(s, value);
1299         trace_usb_host_req_emulated(s->bus_num, s->addr, p, p->status);
1300         return;
1301 
1302     case DeviceOutRequest | USB_REQ_SET_CONFIGURATION:
1303         usb_host_set_config(s, value & 0xff, p);
1304         trace_usb_host_req_emulated(s->bus_num, s->addr, p, p->status);
1305         return;
1306 
1307     case InterfaceOutRequest | USB_REQ_SET_INTERFACE:
1308         usb_host_set_interface(s, index, value, p);
1309         trace_usb_host_req_emulated(s->bus_num, s->addr, p, p->status);
1310         return;
1311 
1312     case EndpointOutRequest | USB_REQ_CLEAR_FEATURE:
1313         if (value == 0) { /* clear halt */
1314             int pid = (index & USB_DIR_IN) ? USB_TOKEN_IN : USB_TOKEN_OUT;
1315             libusb_clear_halt(s->dh, index);
1316             usb_ep_set_halted(udev, pid, index & 0x0f, 0);
1317             trace_usb_host_req_emulated(s->bus_num, s->addr, p, p->status);
1318             return;
1319         }
1320     }
1321 
1322     r = usb_host_req_alloc(s, p, (request >> 8) & USB_DIR_IN, length + 8);
1323     r->cbuf = data;
1324     r->clen = length;
1325     memcpy(r->buffer, udev->setup_buf, 8);
1326     if (!r->in) {
1327         memcpy(r->buffer + 8, r->cbuf, r->clen);
1328     }
1329 
1330     /* Fix up USB-3 ep0 maxpacket size to allow superspeed connected devices
1331      * to work redirected to a not superspeed capable hcd */
1332     if ((udev->speedmask & USB_SPEED_MASK_SUPER) &&
1333         !(udev->port->speedmask & USB_SPEED_MASK_SUPER) &&
1334         request == 0x8006 && value == 0x100 && index == 0) {
1335         r->usb3ep0quirk = true;
1336     }
1337 
1338     libusb_fill_control_transfer(r->xfer, s->dh, r->buffer,
1339                                  usb_host_req_complete_ctrl, r,
1340                                  CONTROL_TIMEOUT);
1341     rc = libusb_submit_transfer(r->xfer);
1342     if (rc != 0) {
1343         p->status = USB_RET_NODEV;
1344         trace_usb_host_req_complete(s->bus_num, s->addr, p,
1345                                     p->status, p->actual_length);
1346         if (rc == LIBUSB_ERROR_NO_DEVICE) {
1347             usb_host_nodev(s);
1348         }
1349         return;
1350     }
1351 
1352     p->status = USB_RET_ASYNC;
1353 }
1354 
1355 static void usb_host_handle_data(USBDevice *udev, USBPacket *p)
1356 {
1357     USBHostDevice *s = USB_HOST_DEVICE(udev);
1358     USBHostRequest *r;
1359     size_t size;
1360     int ep, rc;
1361 
1362     if (usb_host_use_combining(p->ep) && p->state == USB_PACKET_SETUP) {
1363         p->status = USB_RET_ADD_TO_QUEUE;
1364         return;
1365     }
1366 
1367     trace_usb_host_req_data(s->bus_num, s->addr, p,
1368                             p->pid == USB_TOKEN_IN,
1369                             p->ep->nr, p->iov.size);
1370 
1371     if (s->dh == NULL) {
1372         p->status = USB_RET_NODEV;
1373         trace_usb_host_req_emulated(s->bus_num, s->addr, p, p->status);
1374         return;
1375     }
1376     if (p->ep->halted) {
1377         p->status = USB_RET_STALL;
1378         trace_usb_host_req_emulated(s->bus_num, s->addr, p, p->status);
1379         return;
1380     }
1381 
1382     switch (usb_ep_get_type(udev, p->pid, p->ep->nr)) {
1383     case USB_ENDPOINT_XFER_BULK:
1384         size = usb_packet_size(p);
1385         r = usb_host_req_alloc(s, p, p->pid == USB_TOKEN_IN, size);
1386         if (!r->in) {
1387             usb_packet_copy(p, r->buffer, size);
1388         }
1389         ep = p->ep->nr | (r->in ? USB_DIR_IN : 0);
1390         if (p->stream) {
1391 #ifdef HAVE_STREAMS
1392             libusb_fill_bulk_stream_transfer(r->xfer, s->dh, ep, p->stream,
1393                                              r->buffer, size,
1394                                              usb_host_req_complete_data, r,
1395                                              BULK_TIMEOUT);
1396 #else
1397             usb_host_req_free(r);
1398             p->status = USB_RET_STALL;
1399             return;
1400 #endif
1401         } else {
1402             libusb_fill_bulk_transfer(r->xfer, s->dh, ep,
1403                                       r->buffer, size,
1404                                       usb_host_req_complete_data, r,
1405                                       BULK_TIMEOUT);
1406         }
1407         break;
1408     case USB_ENDPOINT_XFER_INT:
1409         r = usb_host_req_alloc(s, p, p->pid == USB_TOKEN_IN, p->iov.size);
1410         if (!r->in) {
1411             usb_packet_copy(p, r->buffer, p->iov.size);
1412         }
1413         ep = p->ep->nr | (r->in ? USB_DIR_IN : 0);
1414         libusb_fill_interrupt_transfer(r->xfer, s->dh, ep,
1415                                        r->buffer, p->iov.size,
1416                                        usb_host_req_complete_data, r,
1417                                        INTR_TIMEOUT);
1418         break;
1419     case USB_ENDPOINT_XFER_ISOC:
1420         if (p->pid == USB_TOKEN_IN) {
1421             usb_host_iso_data_in(s, p);
1422         } else {
1423             usb_host_iso_data_out(s, p);
1424         }
1425         trace_usb_host_req_complete(s->bus_num, s->addr, p,
1426                                     p->status, p->actual_length);
1427         return;
1428     default:
1429         p->status = USB_RET_STALL;
1430         trace_usb_host_req_complete(s->bus_num, s->addr, p,
1431                                     p->status, p->actual_length);
1432         return;
1433     }
1434 
1435     rc = libusb_submit_transfer(r->xfer);
1436     if (rc != 0) {
1437         p->status = USB_RET_NODEV;
1438         trace_usb_host_req_complete(s->bus_num, s->addr, p,
1439                                     p->status, p->actual_length);
1440         if (rc == LIBUSB_ERROR_NO_DEVICE) {
1441             usb_host_nodev(s);
1442         }
1443         return;
1444     }
1445 
1446     p->status = USB_RET_ASYNC;
1447 }
1448 
1449 static void usb_host_flush_ep_queue(USBDevice *dev, USBEndpoint *ep)
1450 {
1451     if (usb_host_use_combining(ep)) {
1452         usb_ep_combine_input_packets(ep);
1453     }
1454 }
1455 
1456 static void usb_host_handle_reset(USBDevice *udev)
1457 {
1458     USBHostDevice *s = USB_HOST_DEVICE(udev);
1459     int rc;
1460 
1461     if (!s->allow_guest_reset) {
1462         return;
1463     }
1464     if (udev->addr == 0) {
1465         return;
1466     }
1467 
1468     trace_usb_host_reset(s->bus_num, s->addr);
1469 
1470     rc = libusb_reset_device(s->dh);
1471     if (rc != 0) {
1472         usb_host_nodev(s);
1473     }
1474 }
1475 
1476 static int usb_host_alloc_streams(USBDevice *udev, USBEndpoint **eps,
1477                                   int nr_eps, int streams)
1478 {
1479 #ifdef HAVE_STREAMS
1480     USBHostDevice *s = USB_HOST_DEVICE(udev);
1481     unsigned char endpoints[30];
1482     int i, rc;
1483 
1484     for (i = 0; i < nr_eps; i++) {
1485         endpoints[i] = eps[i]->nr;
1486         if (eps[i]->pid == USB_TOKEN_IN) {
1487             endpoints[i] |= 0x80;
1488         }
1489     }
1490     rc = libusb_alloc_streams(s->dh, streams, endpoints, nr_eps);
1491     if (rc < 0) {
1492         usb_host_libusb_error("libusb_alloc_streams", rc);
1493     } else if (rc != streams) {
1494         error_report("libusb_alloc_streams: got less streams "
1495                      "then requested %d < %d", rc, streams);
1496     }
1497 
1498     return (rc == streams) ? 0 : -1;
1499 #else
1500     error_report("libusb_alloc_streams: error not implemented");
1501     return -1;
1502 #endif
1503 }
1504 
1505 static void usb_host_free_streams(USBDevice *udev, USBEndpoint **eps,
1506                                   int nr_eps)
1507 {
1508 #ifdef HAVE_STREAMS
1509     USBHostDevice *s = USB_HOST_DEVICE(udev);
1510     unsigned char endpoints[30];
1511     int i;
1512 
1513     for (i = 0; i < nr_eps; i++) {
1514         endpoints[i] = eps[i]->nr;
1515         if (eps[i]->pid == USB_TOKEN_IN) {
1516             endpoints[i] |= 0x80;
1517         }
1518     }
1519     libusb_free_streams(s->dh, endpoints, nr_eps);
1520 #endif
1521 }
1522 
1523 /*
1524  * This is *NOT* about restoring state.  We have absolutely no idea
1525  * what state the host device is in at the moment and whenever it is
1526  * still present in the first place.  Attemping to contine where we
1527  * left off is impossible.
1528  *
1529  * What we are going to do here is emulate a surprise removal of
1530  * the usb device passed through, then kick host scan so the device
1531  * will get re-attached (and re-initialized by the guest) in case it
1532  * is still present.
1533  *
1534  * As the device removal will change the state of other devices (usb
1535  * host controller, most likely interrupt controller too) we have to
1536  * wait with it until *all* vmstate is loaded.  Thus post_load just
1537  * kicks a bottom half which then does the actual work.
1538  */
1539 static void usb_host_post_load_bh(void *opaque)
1540 {
1541     USBHostDevice *dev = opaque;
1542     USBDevice *udev = USB_DEVICE(dev);
1543 
1544     if (dev->dh != NULL) {
1545         usb_host_close(dev);
1546     }
1547     if (udev->attached) {
1548         usb_device_detach(udev);
1549     }
1550     dev->bh_postld_pending = false;
1551     usb_host_auto_check(NULL);
1552 }
1553 
1554 static int usb_host_post_load(void *opaque, int version_id)
1555 {
1556     USBHostDevice *dev = opaque;
1557 
1558     if (!dev->bh_postld) {
1559         dev->bh_postld = qemu_bh_new(usb_host_post_load_bh, dev);
1560     }
1561     qemu_bh_schedule(dev->bh_postld);
1562     dev->bh_postld_pending = true;
1563     return 0;
1564 }
1565 
1566 static const VMStateDescription vmstate_usb_host = {
1567     .name = "usb-host",
1568     .version_id = 1,
1569     .minimum_version_id = 1,
1570     .post_load = usb_host_post_load,
1571     .fields = (VMStateField[]) {
1572         VMSTATE_USB_DEVICE(parent_obj, USBHostDevice),
1573         VMSTATE_END_OF_LIST()
1574     }
1575 };
1576 
1577 static Property usb_host_dev_properties[] = {
1578     DEFINE_PROP_UINT32("hostbus",  USBHostDevice, match.bus_num,    0),
1579     DEFINE_PROP_UINT32("hostaddr", USBHostDevice, match.addr,       0),
1580     DEFINE_PROP_STRING("hostport", USBHostDevice, match.port),
1581     DEFINE_PROP_UINT32("vendorid",  USBHostDevice, match.vendor_id,  0),
1582     DEFINE_PROP_UINT32("productid", USBHostDevice, match.product_id, 0),
1583     DEFINE_PROP_UINT32("isobufs",  USBHostDevice, iso_urb_count,    4),
1584     DEFINE_PROP_UINT32("isobsize", USBHostDevice, iso_urb_frames,   32),
1585     DEFINE_PROP_BOOL("guest-reset", USBHostDevice, allow_guest_reset, true),
1586     DEFINE_PROP_UINT32("loglevel",  USBHostDevice, loglevel,
1587                        LIBUSB_LOG_LEVEL_WARNING),
1588     DEFINE_PROP_BIT("pipeline",    USBHostDevice, options,
1589                     USB_HOST_OPT_PIPELINE, true),
1590     DEFINE_PROP_END_OF_LIST(),
1591 };
1592 
1593 static void usb_host_class_initfn(ObjectClass *klass, void *data)
1594 {
1595     DeviceClass *dc = DEVICE_CLASS(klass);
1596     USBDeviceClass *uc = USB_DEVICE_CLASS(klass);
1597 
1598     uc->realize        = usb_host_realize;
1599     uc->product_desc   = "USB Host Device";
1600     uc->cancel_packet  = usb_host_cancel_packet;
1601     uc->handle_data    = usb_host_handle_data;
1602     uc->handle_control = usb_host_handle_control;
1603     uc->handle_reset   = usb_host_handle_reset;
1604     uc->unrealize      = usb_host_unrealize;
1605     uc->flush_ep_queue = usb_host_flush_ep_queue;
1606     uc->alloc_streams  = usb_host_alloc_streams;
1607     uc->free_streams   = usb_host_free_streams;
1608     dc->vmsd = &vmstate_usb_host;
1609     dc->props = usb_host_dev_properties;
1610     set_bit(DEVICE_CATEGORY_BRIDGE, dc->categories);
1611 }
1612 
1613 static TypeInfo usb_host_dev_info = {
1614     .name          = TYPE_USB_HOST_DEVICE,
1615     .parent        = TYPE_USB_DEVICE,
1616     .instance_size = sizeof(USBHostDevice),
1617     .class_init    = usb_host_class_initfn,
1618     .instance_init = usb_host_instance_init,
1619 };
1620 
1621 static void usb_host_register_types(void)
1622 {
1623     type_register_static(&usb_host_dev_info);
1624 }
1625 
1626 type_init(usb_host_register_types)
1627 
1628 /* ------------------------------------------------------------------------ */
1629 
1630 static QEMUTimer *usb_auto_timer;
1631 static VMChangeStateEntry *usb_vmstate;
1632 
1633 static void usb_host_vm_state(void *unused, int running, RunState state)
1634 {
1635     if (running) {
1636         usb_host_auto_check(unused);
1637     }
1638 }
1639 
1640 static void usb_host_auto_check(void *unused)
1641 {
1642     struct USBHostDevice *s;
1643     struct USBAutoFilter *f;
1644     libusb_device **devs = NULL;
1645     struct libusb_device_descriptor ddesc;
1646     int unconnected = 0;
1647     int i, n;
1648 
1649     if (usb_host_init() != 0) {
1650         return;
1651     }
1652 
1653     if (runstate_is_running()) {
1654         n = libusb_get_device_list(ctx, &devs);
1655         for (i = 0; i < n; i++) {
1656             if (libusb_get_device_descriptor(devs[i], &ddesc) != 0) {
1657                 continue;
1658             }
1659             if (ddesc.bDeviceClass == LIBUSB_CLASS_HUB) {
1660                 continue;
1661             }
1662             QTAILQ_FOREACH(s, &hostdevs, next) {
1663                 f = &s->match;
1664                 if (f->bus_num > 0 &&
1665                     f->bus_num != libusb_get_bus_number(devs[i])) {
1666                     continue;
1667                 }
1668                 if (f->addr > 0 &&
1669                     f->addr != libusb_get_device_address(devs[i])) {
1670                     continue;
1671                 }
1672                 if (f->port != NULL) {
1673                     char port[16] = "-";
1674                     usb_host_get_port(devs[i], port, sizeof(port));
1675                     if (strcmp(f->port, port) != 0) {
1676                         continue;
1677                     }
1678                 }
1679                 if (f->vendor_id > 0 &&
1680                     f->vendor_id != ddesc.idVendor) {
1681                     continue;
1682                 }
1683                 if (f->product_id > 0 &&
1684                     f->product_id != ddesc.idProduct) {
1685                     continue;
1686                 }
1687 
1688                 /* We got a match */
1689                 s->seen++;
1690                 if (s->errcount >= 3) {
1691                     continue;
1692                 }
1693                 if (s->dh != NULL) {
1694                     continue;
1695                 }
1696                 if (usb_host_open(s, devs[i]) < 0) {
1697                     s->errcount++;
1698                     continue;
1699                 }
1700                 break;
1701             }
1702         }
1703         libusb_free_device_list(devs, 1);
1704 
1705         QTAILQ_FOREACH(s, &hostdevs, next) {
1706             if (s->dh == NULL) {
1707                 unconnected++;
1708             }
1709             if (s->seen == 0) {
1710                 if (s->dh) {
1711                     usb_host_close(s);
1712                 }
1713                 s->errcount = 0;
1714             }
1715             s->seen = 0;
1716         }
1717 
1718 #if 0
1719         if (unconnected == 0) {
1720             /* nothing to watch */
1721             if (usb_auto_timer) {
1722                 timer_del(usb_auto_timer);
1723                 trace_usb_host_auto_scan_disabled();
1724             }
1725             return;
1726         }
1727 #endif
1728     }
1729 
1730     if (!usb_vmstate) {
1731         usb_vmstate = qemu_add_vm_change_state_handler(usb_host_vm_state, NULL);
1732     }
1733     if (!usb_auto_timer) {
1734         usb_auto_timer = timer_new_ms(QEMU_CLOCK_REALTIME, usb_host_auto_check, NULL);
1735         if (!usb_auto_timer) {
1736             return;
1737         }
1738         trace_usb_host_auto_scan_enabled();
1739     }
1740     timer_mod(usb_auto_timer, qemu_clock_get_ms(QEMU_CLOCK_REALTIME) + 2000);
1741 }
1742 
1743 /**
1744  * Check whether USB host device has a USB mass storage SCSI interface
1745  */
1746 bool usb_host_dev_is_scsi_storage(USBDevice *ud)
1747 {
1748     USBHostDevice *uhd = USB_HOST_DEVICE(ud);
1749     struct libusb_config_descriptor *conf;
1750     const struct libusb_interface_descriptor *intf;
1751     bool is_scsi_storage = false;
1752     int i;
1753 
1754     if (!uhd || libusb_get_active_config_descriptor(uhd->dev, &conf) != 0) {
1755         return false;
1756     }
1757 
1758     for (i = 0; i < conf->bNumInterfaces; i++) {
1759         intf = &conf->interface[i].altsetting[ud->altsetting[i]];
1760         if (intf->bInterfaceClass == LIBUSB_CLASS_MASS_STORAGE &&
1761             intf->bInterfaceSubClass == 6) {                 /* 6 means SCSI */
1762             is_scsi_storage = true;
1763             break;
1764         }
1765     }
1766 
1767     libusb_free_config_descriptor(conf);
1768 
1769     return is_scsi_storage;
1770 }
1771 
1772 void hmp_info_usbhost(Monitor *mon, const QDict *qdict)
1773 {
1774     libusb_device **devs = NULL;
1775     struct libusb_device_descriptor ddesc;
1776     char port[16];
1777     int i, n;
1778 
1779     if (usb_host_init() != 0) {
1780         return;
1781     }
1782 
1783     n = libusb_get_device_list(ctx, &devs);
1784     for (i = 0; i < n; i++) {
1785         if (libusb_get_device_descriptor(devs[i], &ddesc) != 0) {
1786             continue;
1787         }
1788         if (ddesc.bDeviceClass == LIBUSB_CLASS_HUB) {
1789             continue;
1790         }
1791         usb_host_get_port(devs[i], port, sizeof(port));
1792         monitor_printf(mon, "  Bus %d, Addr %d, Port %s, Speed %s Mb/s\n",
1793                        libusb_get_bus_number(devs[i]),
1794                        libusb_get_device_address(devs[i]),
1795                        port,
1796                        speed_name[libusb_get_device_speed(devs[i])]);
1797         monitor_printf(mon, "    Class %02x:", ddesc.bDeviceClass);
1798         monitor_printf(mon, " USB device %04x:%04x",
1799                        ddesc.idVendor, ddesc.idProduct);
1800         if (ddesc.iProduct) {
1801             libusb_device_handle *handle;
1802             if (libusb_open(devs[i], &handle) == 0) {
1803                 unsigned char name[64] = "";
1804                 libusb_get_string_descriptor_ascii(handle,
1805                                                    ddesc.iProduct,
1806                                                    name, sizeof(name));
1807                 libusb_close(handle);
1808                 monitor_printf(mon, ", %s", name);
1809             }
1810         }
1811         monitor_printf(mon, "\n");
1812     }
1813     libusb_free_device_list(devs, 1);
1814 }
1815