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