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