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