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