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