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