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