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