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