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