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