xref: /openbmc/qemu/hw/usb/host-libusb.c (revision 86c7dba0)
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 <poll.h>
37 #include <libusb.h>
38 
39 #include "qemu-common.h"
40 #include "monitor/monitor.h"
41 #include "sysemu/sysemu.h"
42 #include "trace.h"
43 
44 #include "hw/usb.h"
45 
46 /* ------------------------------------------------------------------------ */
47 
48 #define TYPE_USB_HOST_DEVICE "usb-host"
49 #define USB_HOST_DEVICE(obj) \
50      OBJECT_CHECK(USBHostDevice, (obj), TYPE_USB_HOST_DEVICE)
51 
52 typedef struct USBHostDevice USBHostDevice;
53 typedef struct USBHostRequest USBHostRequest;
54 typedef struct USBHostIsoXfer USBHostIsoXfer;
55 typedef struct USBHostIsoRing USBHostIsoRing;
56 
57 struct USBAutoFilter {
58     uint32_t bus_num;
59     uint32_t addr;
60     char     *port;
61     uint32_t vendor_id;
62     uint32_t product_id;
63 };
64 
65 enum USBHostDeviceOptions {
66     USB_HOST_OPT_PIPELINE,
67 };
68 
69 struct USBHostDevice {
70     USBDevice parent_obj;
71 
72     /* properties */
73     struct USBAutoFilter             match;
74     int32_t                          bootindex;
75     uint32_t                         iso_urb_count;
76     uint32_t                         iso_urb_frames;
77     uint32_t                         options;
78     uint32_t                         loglevel;
79 
80     /* state */
81     QTAILQ_ENTRY(USBHostDevice)      next;
82     int                              seen, errcount;
83     int                              bus_num;
84     int                              addr;
85     char                             port[16];
86 
87     libusb_device                    *dev;
88     libusb_device_handle             *dh;
89     struct libusb_device_descriptor  ddesc;
90 
91     struct {
92         bool                         detached;
93         bool                         claimed;
94     } ifs[USB_MAX_INTERFACES];
95 
96     /* callbacks & friends */
97     QEMUBH                           *bh;
98     Notifier                         exit;
99 
100     /* request queues */
101     QTAILQ_HEAD(, USBHostRequest)    requests;
102     QTAILQ_HEAD(, USBHostIsoRing)    isorings;
103 };
104 
105 struct USBHostRequest {
106     USBHostDevice                    *host;
107     USBPacket                        *p;
108     bool                             in;
109     struct libusb_transfer           *xfer;
110     unsigned char                    *buffer;
111     unsigned char                    *cbuf;
112     unsigned int                     clen;
113     QTAILQ_ENTRY(USBHostRequest)     next;
114 };
115 
116 struct USBHostIsoXfer {
117     USBHostIsoRing                   *ring;
118     struct libusb_transfer           *xfer;
119     bool                             copy_complete;
120     unsigned int                     packet;
121     QTAILQ_ENTRY(USBHostIsoXfer)     next;
122 };
123 
124 struct USBHostIsoRing {
125     USBHostDevice                    *host;
126     USBEndpoint                      *ep;
127     QTAILQ_HEAD(, USBHostIsoXfer)    unused;
128     QTAILQ_HEAD(, USBHostIsoXfer)    inflight;
129     QTAILQ_HEAD(, USBHostIsoXfer)    copy;
130     QTAILQ_ENTRY(USBHostIsoRing)     next;
131 };
132 
133 static QTAILQ_HEAD(, USBHostDevice) hostdevs =
134     QTAILQ_HEAD_INITIALIZER(hostdevs);
135 
136 static void usb_host_auto_check(void *unused);
137 static void usb_host_release_interfaces(USBHostDevice *s);
138 static void usb_host_nodev(USBHostDevice *s);
139 static void usb_host_attach_kernel(USBHostDevice *s);
140 
141 /* ------------------------------------------------------------------------ */
142 
143 #define CONTROL_TIMEOUT  10000        /* 10 sec    */
144 #define BULK_TIMEOUT         0        /* unlimited */
145 #define INTR_TIMEOUT         0        /* unlimited */
146 
147 static const char *speed_name[] = {
148     [LIBUSB_SPEED_UNKNOWN] = "?",
149     [LIBUSB_SPEED_LOW]     = "1.5",
150     [LIBUSB_SPEED_FULL]    = "12",
151     [LIBUSB_SPEED_HIGH]    = "480",
152     [LIBUSB_SPEED_SUPER]   = "5000",
153 };
154 
155 static const unsigned int speed_map[] = {
156     [LIBUSB_SPEED_LOW]     = USB_SPEED_LOW,
157     [LIBUSB_SPEED_FULL]    = USB_SPEED_FULL,
158     [LIBUSB_SPEED_HIGH]    = USB_SPEED_HIGH,
159     [LIBUSB_SPEED_SUPER]   = USB_SPEED_SUPER,
160 };
161 
162 static const unsigned int status_map[] = {
163     [LIBUSB_TRANSFER_COMPLETED] = USB_RET_SUCCESS,
164     [LIBUSB_TRANSFER_ERROR]     = USB_RET_IOERROR,
165     [LIBUSB_TRANSFER_TIMED_OUT] = USB_RET_IOERROR,
166     [LIBUSB_TRANSFER_CANCELLED] = USB_RET_IOERROR,
167     [LIBUSB_TRANSFER_STALL]     = USB_RET_STALL,
168     [LIBUSB_TRANSFER_NO_DEVICE] = USB_RET_NODEV,
169     [LIBUSB_TRANSFER_OVERFLOW]  = USB_RET_BABBLE,
170 };
171 
172 static const char *err_names[] = {
173     [-LIBUSB_ERROR_IO]               = "IO",
174     [-LIBUSB_ERROR_INVALID_PARAM]    = "INVALID_PARAM",
175     [-LIBUSB_ERROR_ACCESS]           = "ACCESS",
176     [-LIBUSB_ERROR_NO_DEVICE]        = "NO_DEVICE",
177     [-LIBUSB_ERROR_NOT_FOUND]        = "NOT_FOUND",
178     [-LIBUSB_ERROR_BUSY]             = "BUSY",
179     [-LIBUSB_ERROR_TIMEOUT]          = "TIMEOUT",
180     [-LIBUSB_ERROR_OVERFLOW]         = "OVERFLOW",
181     [-LIBUSB_ERROR_PIPE]             = "PIPE",
182     [-LIBUSB_ERROR_INTERRUPTED]      = "INTERRUPTED",
183     [-LIBUSB_ERROR_NO_MEM]           = "NO_MEM",
184     [-LIBUSB_ERROR_NOT_SUPPORTED]    = "NOT_SUPPORTED",
185     [-LIBUSB_ERROR_OTHER]            = "OTHER",
186 };
187 
188 static libusb_context *ctx;
189 static uint32_t loglevel;
190 
191 static void usb_host_handle_fd(void *opaque)
192 {
193     struct timeval tv = { 0, 0 };
194     libusb_handle_events_timeout(ctx, &tv);
195 }
196 
197 static void usb_host_add_fd(int fd, short events, void *user_data)
198 {
199     qemu_set_fd_handler(fd,
200                         (events & POLLIN)  ? usb_host_handle_fd : NULL,
201                         (events & POLLOUT) ? usb_host_handle_fd : NULL,
202                         ctx);
203 }
204 
205 static void usb_host_del_fd(int fd, void *user_data)
206 {
207     qemu_set_fd_handler(fd, NULL, NULL, NULL);
208 }
209 
210 static int usb_host_init(void)
211 {
212     const struct libusb_pollfd **poll;
213     int i, rc;
214 
215     if (ctx) {
216         return 0;
217     }
218     rc = libusb_init(&ctx);
219     if (rc != 0) {
220         return -1;
221     }
222     libusb_set_debug(ctx, loglevel);
223 
224     libusb_set_pollfd_notifiers(ctx, usb_host_add_fd,
225                                 usb_host_del_fd,
226                                 ctx);
227     poll = libusb_get_pollfds(ctx);
228     if (poll) {
229         for (i = 0; poll[i] != NULL; i++) {
230             usb_host_add_fd(poll[i]->fd, poll[i]->events, ctx);
231         }
232     }
233     free(poll);
234     return 0;
235 }
236 
237 static int usb_host_get_port(libusb_device *dev, char *port, size_t len)
238 {
239 #if defined(LIBUSBX_API_VERSION) && (LIBUSBX_API_VERSION >= 0x010000ff)
240     /* have libusb_get_port_path() */
241     uint8_t path[7];
242     size_t off;
243     int rc, i;
244 
245     rc = libusb_get_port_path(ctx, dev, path, 7);
246     if (rc < 0) {
247         return 0;
248     }
249     off = snprintf(port, len, "%d", path[0]);
250     for (i = 1; i < rc; i++) {
251         off += snprintf(port+off, len-off, ".%d", path[i]);
252     }
253     return off;
254 #else
255     return snprintf(port, len, "FIXME");
256 #endif
257 }
258 
259 static void usb_host_libusb_error(const char *func, int rc)
260 {
261     const char *errname;
262 
263     if (rc >= 0) {
264         return;
265     }
266 
267     if (-rc < ARRAY_SIZE(err_names) && err_names[-rc]) {
268         errname = err_names[-rc];
269     } else {
270         errname = "?";
271     }
272     fprintf(stderr, "%s: %d [%s]\n", func, rc, errname);
273 }
274 
275 /* ------------------------------------------------------------------------ */
276 
277 static bool usb_host_use_combining(USBEndpoint *ep)
278 {
279     int type;
280 
281     if (!ep->pipeline) {
282         return false;
283     }
284     if (ep->pid != USB_TOKEN_IN) {
285         return false;
286     }
287     type = usb_ep_get_type(ep->dev, ep->pid, ep->nr);
288     if (type != USB_ENDPOINT_XFER_BULK) {
289         return false;
290     }
291     return true;
292 }
293 
294 /* ------------------------------------------------------------------------ */
295 
296 static USBHostRequest *usb_host_req_alloc(USBHostDevice *s, USBPacket *p,
297                                           bool in, size_t bufsize)
298 {
299     USBHostRequest *r = g_new0(USBHostRequest, 1);
300 
301     r->host = s;
302     r->p = p;
303     r->in = in;
304     r->xfer = libusb_alloc_transfer(0);
305     if (bufsize) {
306         r->buffer = g_malloc(bufsize);
307     }
308     QTAILQ_INSERT_TAIL(&s->requests, r, next);
309     return r;
310 }
311 
312 static void usb_host_req_free(USBHostRequest *r)
313 {
314     if (r->host) {
315         QTAILQ_REMOVE(&r->host->requests, r, next);
316     }
317     libusb_free_transfer(r->xfer);
318     g_free(r->buffer);
319     g_free(r);
320 }
321 
322 static USBHostRequest *usb_host_req_find(USBHostDevice *s, USBPacket *p)
323 {
324     USBHostRequest *r;
325 
326     QTAILQ_FOREACH(r, &s->requests, next) {
327         if (r->p == p) {
328             return r;
329         }
330     }
331     return NULL;
332 }
333 
334 static void usb_host_req_complete_ctrl(struct libusb_transfer *xfer)
335 {
336     USBHostRequest *r = xfer->user_data;
337     USBHostDevice  *s = r->host;
338     bool disconnect = (xfer->status == LIBUSB_TRANSFER_NO_DEVICE);
339 
340     if (r->p == NULL) {
341         goto out; /* request was canceled */
342     }
343 
344     r->p->status = status_map[xfer->status];
345     r->p->actual_length = xfer->actual_length;
346     if (r->in && xfer->actual_length) {
347         memcpy(r->cbuf, r->buffer + 8, xfer->actual_length);
348     }
349     trace_usb_host_req_complete(s->bus_num, s->addr, r->p,
350                                 r->p->status, r->p->actual_length);
351     usb_generic_async_ctrl_complete(USB_DEVICE(s), r->p);
352 
353 out:
354     usb_host_req_free(r);
355     if (disconnect) {
356         usb_host_nodev(s);
357     }
358 }
359 
360 static void usb_host_req_complete_data(struct libusb_transfer *xfer)
361 {
362     USBHostRequest *r = xfer->user_data;
363     USBHostDevice  *s = r->host;
364     bool disconnect = (xfer->status == LIBUSB_TRANSFER_NO_DEVICE);
365 
366     if (r->p == NULL) {
367         goto out; /* request was canceled */
368     }
369 
370     r->p->status = status_map[xfer->status];
371     if (r->in && xfer->actual_length) {
372         usb_packet_copy(r->p, r->buffer, xfer->actual_length);
373     }
374     trace_usb_host_req_complete(s->bus_num, s->addr, r->p,
375                                 r->p->status, r->p->actual_length);
376     if (usb_host_use_combining(r->p->ep)) {
377         usb_combined_input_packet_complete(USB_DEVICE(s), r->p);
378     } else {
379         usb_packet_complete(USB_DEVICE(s), r->p);
380     }
381 
382 out:
383     usb_host_req_free(r);
384     if (disconnect) {
385         usb_host_nodev(s);
386     }
387 }
388 
389 static void usb_host_req_abort(USBHostRequest *r)
390 {
391     USBHostDevice  *s = r->host;
392     bool inflight = (r->p && r->p->state == USB_RET_ASYNC);
393 
394     if (inflight) {
395         r->p->status = USB_RET_NODEV;
396         trace_usb_host_req_complete(s->bus_num, s->addr, r->p,
397                                     r->p->status, r->p->actual_length);
398         if (r->p->ep->nr == 0) {
399             usb_generic_async_ctrl_complete(USB_DEVICE(s), r->p);
400         } else {
401             usb_packet_complete(USB_DEVICE(s), r->p);
402         }
403         r->p = NULL;
404     }
405 
406     QTAILQ_REMOVE(&r->host->requests, r, next);
407     r->host = NULL;
408 
409     if (inflight) {
410         libusb_cancel_transfer(r->xfer);
411     }
412 }
413 
414 /* ------------------------------------------------------------------------ */
415 
416 static void usb_host_req_complete_iso(struct libusb_transfer *transfer)
417 {
418     USBHostIsoXfer *xfer = transfer->user_data;
419 
420     if (!xfer) {
421         /* USBHostIsoXfer released while inflight */
422         g_free(transfer->buffer);
423         libusb_free_transfer(transfer);
424         return;
425     }
426 
427     QTAILQ_REMOVE(&xfer->ring->inflight, xfer, next);
428     if (QTAILQ_EMPTY(&xfer->ring->inflight)) {
429         USBHostDevice *s = xfer->ring->host;
430         trace_usb_host_iso_stop(s->bus_num, s->addr, xfer->ring->ep->nr);
431     }
432     if (xfer->ring->ep->pid == USB_TOKEN_IN) {
433         QTAILQ_INSERT_TAIL(&xfer->ring->copy, xfer, next);
434     } else {
435         QTAILQ_INSERT_TAIL(&xfer->ring->unused, xfer, next);
436     }
437 }
438 
439 static USBHostIsoRing *usb_host_iso_alloc(USBHostDevice *s, USBEndpoint *ep)
440 {
441     USBHostIsoRing *ring = g_new0(USBHostIsoRing, 1);
442     USBHostIsoXfer *xfer;
443     /* FIXME: check interval (for now assume one xfer per frame) */
444     int packets = s->iso_urb_frames;
445     int i;
446 
447     ring->host = s;
448     ring->ep = ep;
449     QTAILQ_INIT(&ring->unused);
450     QTAILQ_INIT(&ring->inflight);
451     QTAILQ_INIT(&ring->copy);
452     QTAILQ_INSERT_TAIL(&s->isorings, ring, next);
453 
454     for (i = 0; i < s->iso_urb_count; i++) {
455         xfer = g_new0(USBHostIsoXfer, 1);
456         xfer->ring = ring;
457         xfer->xfer = libusb_alloc_transfer(packets);
458         xfer->xfer->dev_handle = s->dh;
459         xfer->xfer->type = LIBUSB_TRANSFER_TYPE_ISOCHRONOUS;
460 
461         xfer->xfer->endpoint = ring->ep->nr;
462         if (ring->ep->pid == USB_TOKEN_IN) {
463             xfer->xfer->endpoint |= USB_DIR_IN;
464         }
465         xfer->xfer->callback = usb_host_req_complete_iso;
466         xfer->xfer->user_data = xfer;
467 
468         xfer->xfer->num_iso_packets = packets;
469         xfer->xfer->length = ring->ep->max_packet_size * packets;
470         xfer->xfer->buffer = g_malloc0(xfer->xfer->length);
471 
472         QTAILQ_INSERT_TAIL(&ring->unused, xfer, next);
473     }
474 
475     return ring;
476 }
477 
478 static USBHostIsoRing *usb_host_iso_find(USBHostDevice *s, USBEndpoint *ep)
479 {
480     USBHostIsoRing *ring;
481 
482     QTAILQ_FOREACH(ring, &s->isorings, next) {
483         if (ring->ep == ep) {
484             return ring;
485         }
486     }
487     return NULL;
488 }
489 
490 static void usb_host_iso_reset_xfer(USBHostIsoXfer *xfer)
491 {
492     libusb_set_iso_packet_lengths(xfer->xfer,
493                                   xfer->ring->ep->max_packet_size);
494     xfer->packet = 0;
495     xfer->copy_complete = false;
496 }
497 
498 static void usb_host_iso_free_xfer(USBHostIsoXfer *xfer, bool inflight)
499 {
500     if (inflight) {
501         xfer->xfer->user_data = NULL;
502     } else {
503         g_free(xfer->xfer->buffer);
504         libusb_free_transfer(xfer->xfer);
505     }
506     g_free(xfer);
507 }
508 
509 static void usb_host_iso_free(USBHostIsoRing *ring)
510 {
511     USBHostIsoXfer *xfer;
512 
513     while ((xfer = QTAILQ_FIRST(&ring->inflight)) != NULL) {
514         QTAILQ_REMOVE(&ring->inflight, xfer, next);
515         usb_host_iso_free_xfer(xfer, true);
516     }
517     while ((xfer = QTAILQ_FIRST(&ring->unused)) != NULL) {
518         QTAILQ_REMOVE(&ring->unused, xfer, next);
519         usb_host_iso_free_xfer(xfer, false);
520     }
521     while ((xfer = QTAILQ_FIRST(&ring->copy)) != NULL) {
522         QTAILQ_REMOVE(&ring->copy, xfer, next);
523         usb_host_iso_free_xfer(xfer, false);
524     }
525 
526     QTAILQ_REMOVE(&ring->host->isorings, ring, next);
527     g_free(ring);
528 }
529 
530 static void usb_host_iso_free_all(USBHostDevice *s)
531 {
532     USBHostIsoRing *ring;
533 
534     while ((ring = QTAILQ_FIRST(&s->isorings)) != NULL) {
535         usb_host_iso_free(ring);
536     }
537 }
538 
539 static bool usb_host_iso_data_copy(USBHostIsoXfer *xfer, USBPacket *p)
540 {
541     unsigned int psize;
542     unsigned char *buf;
543 
544     buf = libusb_get_iso_packet_buffer_simple(xfer->xfer, xfer->packet);
545     if (p->pid == USB_TOKEN_OUT) {
546         psize = p->iov.size;
547         if (psize > xfer->ring->ep->max_packet_size) {
548             /* should not happen (guest bug) */
549             psize = xfer->ring->ep->max_packet_size;
550         }
551         xfer->xfer->iso_packet_desc[xfer->packet].length = psize;
552     } else {
553         psize = xfer->xfer->iso_packet_desc[xfer->packet].actual_length;
554         if (psize > p->iov.size) {
555             /* should not happen (guest bug) */
556             psize = p->iov.size;
557         }
558     }
559     usb_packet_copy(p, buf, psize);
560     xfer->packet++;
561     xfer->copy_complete = (xfer->packet == xfer->xfer->num_iso_packets);
562     return xfer->copy_complete;
563 }
564 
565 static void usb_host_iso_data_in(USBHostDevice *s, USBPacket *p)
566 {
567     USBHostIsoRing *ring;
568     USBHostIsoXfer *xfer;
569     bool disconnect = false;
570     int rc;
571 
572     ring = usb_host_iso_find(s, p->ep);
573     if (ring == NULL) {
574         ring = usb_host_iso_alloc(s, p->ep);
575     }
576 
577     /* copy data to guest */
578     xfer = QTAILQ_FIRST(&ring->copy);
579     if (xfer != NULL) {
580         if (usb_host_iso_data_copy(xfer, p)) {
581             QTAILQ_REMOVE(&ring->copy, xfer, next);
582             QTAILQ_INSERT_TAIL(&ring->unused, xfer, next);
583         }
584     }
585 
586     /* submit empty bufs to host */
587     while ((xfer = QTAILQ_FIRST(&ring->unused)) != NULL) {
588         QTAILQ_REMOVE(&ring->unused, xfer, next);
589         usb_host_iso_reset_xfer(xfer);
590         rc = libusb_submit_transfer(xfer->xfer);
591         if (rc != 0) {
592             usb_host_libusb_error("libusb_submit_transfer [iso]", rc);
593             QTAILQ_INSERT_TAIL(&ring->unused, xfer, next);
594             if (rc == LIBUSB_ERROR_NO_DEVICE) {
595                 disconnect = true;
596             }
597             break;
598         }
599         if (QTAILQ_EMPTY(&ring->inflight)) {
600             trace_usb_host_iso_start(s->bus_num, s->addr, p->ep->nr);
601         }
602         QTAILQ_INSERT_TAIL(&ring->inflight, xfer, next);
603     }
604 
605     if (disconnect) {
606         usb_host_nodev(s);
607     }
608 }
609 
610 static void usb_host_iso_data_out(USBHostDevice *s, USBPacket *p)
611 {
612     USBHostIsoRing *ring;
613     USBHostIsoXfer *xfer;
614     bool disconnect = false;
615     int rc, filled = 0;
616 
617     ring = usb_host_iso_find(s, p->ep);
618     if (ring == NULL) {
619         ring = usb_host_iso_alloc(s, p->ep);
620     }
621 
622     /* copy data from guest */
623     xfer = QTAILQ_FIRST(&ring->copy);
624     while (xfer != NULL && xfer->copy_complete) {
625         filled++;
626         xfer = QTAILQ_NEXT(xfer, next);
627     }
628     if (xfer == NULL) {
629         xfer = QTAILQ_FIRST(&ring->unused);
630         if (xfer == NULL) {
631             trace_usb_host_iso_out_of_bufs(s->bus_num, s->addr, p->ep->nr);
632             return;
633         }
634         QTAILQ_REMOVE(&ring->unused, xfer, next);
635         usb_host_iso_reset_xfer(xfer);
636         QTAILQ_INSERT_TAIL(&ring->copy, xfer, next);
637     }
638     usb_host_iso_data_copy(xfer, p);
639 
640     if (QTAILQ_EMPTY(&ring->inflight)) {
641         /* wait until half of our buffers are filled
642            before kicking the iso out stream */
643         if (filled*2 < s->iso_urb_count) {
644             return;
645         }
646     }
647 
648     /* submit filled bufs to host */
649     while ((xfer = QTAILQ_FIRST(&ring->copy)) != NULL &&
650            xfer->copy_complete) {
651         QTAILQ_REMOVE(&ring->copy, xfer, next);
652         rc = libusb_submit_transfer(xfer->xfer);
653         if (rc != 0) {
654             usb_host_libusb_error("libusb_submit_transfer [iso]", rc);
655             QTAILQ_INSERT_TAIL(&ring->unused, xfer, next);
656             if (rc == LIBUSB_ERROR_NO_DEVICE) {
657                 disconnect = true;
658             }
659             break;
660         }
661         if (QTAILQ_EMPTY(&ring->inflight)) {
662             trace_usb_host_iso_start(s->bus_num, s->addr, p->ep->nr);
663         }
664         QTAILQ_INSERT_TAIL(&ring->inflight, xfer, next);
665     }
666 
667     if (disconnect) {
668         usb_host_nodev(s);
669     }
670 }
671 
672 /* ------------------------------------------------------------------------ */
673 
674 static void usb_host_ep_update(USBHostDevice *s)
675 {
676     static const char *tname[] = {
677         [USB_ENDPOINT_XFER_CONTROL] = "control",
678         [USB_ENDPOINT_XFER_ISOC]    = "isoc",
679         [USB_ENDPOINT_XFER_BULK]    = "bulk",
680         [USB_ENDPOINT_XFER_INT]     = "int",
681     };
682     USBDevice *udev = USB_DEVICE(s);
683     struct libusb_config_descriptor *conf;
684     const struct libusb_interface_descriptor *intf;
685     const struct libusb_endpoint_descriptor *endp;
686     uint8_t devep, type;
687     int pid, ep;
688     int rc, i, e;
689 
690     usb_ep_reset(udev);
691     rc = libusb_get_active_config_descriptor(s->dev, &conf);
692     if (rc != 0) {
693         return;
694     }
695     trace_usb_host_parse_config(s->bus_num, s->addr,
696                                 conf->bConfigurationValue, true);
697 
698     for (i = 0; i < conf->bNumInterfaces; i++) {
699         assert(udev->altsetting[i] < conf->interface[i].num_altsetting);
700         intf = &conf->interface[i].altsetting[udev->altsetting[i]];
701         trace_usb_host_parse_interface(s->bus_num, s->addr,
702                                        intf->bInterfaceNumber,
703                                        intf->bAlternateSetting, true);
704         for (e = 0; e < intf->bNumEndpoints; e++) {
705             endp = &intf->endpoint[e];
706 
707             devep = endp->bEndpointAddress;
708             pid = (devep & USB_DIR_IN) ? USB_TOKEN_IN : USB_TOKEN_OUT;
709             ep = devep & 0xf;
710             type = endp->bmAttributes & 0x3;
711 
712             if (ep == 0) {
713                 trace_usb_host_parse_error(s->bus_num, s->addr,
714                                            "invalid endpoint address");
715                 return;
716             }
717             if (usb_ep_get_type(udev, pid, ep) != USB_ENDPOINT_XFER_INVALID) {
718                 trace_usb_host_parse_error(s->bus_num, s->addr,
719                                            "duplicate endpoint address");
720                 return;
721             }
722 
723             trace_usb_host_parse_endpoint(s->bus_num, s->addr, ep,
724                                           (devep & USB_DIR_IN) ? "in" : "out",
725                                           tname[type], true);
726             usb_ep_set_max_packet_size(udev, pid, ep,
727                                        endp->wMaxPacketSize);
728             usb_ep_set_type(udev, pid, ep, type);
729             usb_ep_set_ifnum(udev, pid, ep, i);
730             usb_ep_set_halted(udev, pid, ep, 0);
731         }
732     }
733 
734     libusb_free_config_descriptor(conf);
735 }
736 
737 static int usb_host_open(USBHostDevice *s, libusb_device *dev)
738 {
739     USBDevice *udev = USB_DEVICE(s);
740     int bus_num = libusb_get_bus_number(dev);
741     int addr    = libusb_get_device_address(dev);
742     int rc;
743 
744     trace_usb_host_open_started(bus_num, addr);
745 
746     if (s->dh != NULL) {
747         goto fail;
748     }
749     rc = libusb_open(dev, &s->dh);
750     if (rc != 0) {
751         goto fail;
752     }
753 
754     libusb_get_device_descriptor(dev, &s->ddesc);
755     s->dev     = dev;
756     s->bus_num = bus_num;
757     s->addr    = addr;
758     usb_host_get_port(s->dev, s->port, sizeof(s->port));
759 
760     usb_ep_init(udev);
761     usb_host_ep_update(s);
762 
763     udev->speed     = speed_map[libusb_get_device_speed(dev)];
764     udev->speedmask = (1 << udev->speed);
765 #if 0
766     if (udev->speed == USB_SPEED_HIGH && usb_linux_full_speed_compat(dev)) {
767         udev->speedmask |= USB_SPEED_MASK_FULL;
768     }
769 #endif
770 
771     if (s->ddesc.iProduct) {
772         libusb_get_string_descriptor_ascii(s->dh, s->ddesc.iProduct,
773                                            (unsigned char *)udev->product_desc,
774                                            sizeof(udev->product_desc));
775     } else {
776         snprintf(udev->product_desc, sizeof(udev->product_desc),
777                  "host:%d.%d", bus_num, addr);
778     }
779 
780     rc = usb_device_attach(udev);
781     if (rc) {
782         goto fail;
783     }
784 
785     trace_usb_host_open_success(bus_num, addr);
786     return 0;
787 
788 fail:
789     trace_usb_host_open_failure(bus_num, addr);
790     if (s->dh != NULL) {
791         libusb_close(s->dh);
792         s->dh = NULL;
793         s->dev = NULL;
794     }
795     return -1;
796 }
797 
798 static void usb_host_abort_xfers(USBHostDevice *s)
799 {
800     USBHostRequest *r, *rtmp;
801 
802     QTAILQ_FOREACH_SAFE(r, &s->requests, next, rtmp) {
803         usb_host_req_abort(r);
804     }
805 }
806 
807 static int usb_host_close(USBHostDevice *s)
808 {
809     USBDevice *udev = USB_DEVICE(s);
810 
811     if (s->dh == NULL) {
812         return -1;
813     }
814 
815     trace_usb_host_close(s->bus_num, s->addr);
816 
817     usb_host_abort_xfers(s);
818     usb_host_iso_free_all(s);
819 
820     if (udev->attached) {
821         usb_device_detach(udev);
822     }
823 
824     usb_host_release_interfaces(s);
825     libusb_reset_device(s->dh);
826     usb_host_attach_kernel(s);
827     libusb_close(s->dh);
828     s->dh = NULL;
829     s->dev = NULL;
830 
831     usb_host_auto_check(NULL);
832     return 0;
833 }
834 
835 static void usb_host_nodev_bh(void *opaque)
836 {
837     USBHostDevice *s = opaque;
838     usb_host_close(s);
839 }
840 
841 static void usb_host_nodev(USBHostDevice *s)
842 {
843     if (!s->bh) {
844         s->bh = qemu_bh_new(usb_host_nodev_bh, s);
845     }
846     qemu_bh_schedule(s->bh);
847 }
848 
849 static void usb_host_exit_notifier(struct Notifier *n, void *data)
850 {
851     USBHostDevice *s = container_of(n, USBHostDevice, exit);
852 
853     if (s->dh) {
854         usb_host_release_interfaces(s);
855         usb_host_attach_kernel(s);
856     }
857 }
858 
859 static int usb_host_initfn(USBDevice *udev)
860 {
861     USBHostDevice *s = USB_HOST_DEVICE(udev);
862 
863     loglevel = s->loglevel;
864     udev->auto_attach = 0;
865     QTAILQ_INIT(&s->requests);
866     QTAILQ_INIT(&s->isorings);
867 
868     s->exit.notify = usb_host_exit_notifier;
869     qemu_add_exit_notifier(&s->exit);
870 
871     QTAILQ_INSERT_TAIL(&hostdevs, s, next);
872     add_boot_device_path(s->bootindex, &udev->qdev, NULL);
873     usb_host_auto_check(NULL);
874     return 0;
875 }
876 
877 static void usb_host_handle_destroy(USBDevice *udev)
878 {
879     USBHostDevice *s = USB_HOST_DEVICE(udev);
880 
881     qemu_remove_exit_notifier(&s->exit);
882     QTAILQ_REMOVE(&hostdevs, s, next);
883     usb_host_close(s);
884 }
885 
886 static void usb_host_cancel_packet(USBDevice *udev, USBPacket *p)
887 {
888     USBHostDevice *s = USB_HOST_DEVICE(udev);
889     USBHostRequest *r;
890 
891     if (p->combined) {
892         usb_combined_packet_cancel(udev, p);
893         return;
894     }
895 
896     trace_usb_host_req_canceled(s->bus_num, s->addr, p);
897 
898     r = usb_host_req_find(s, p);
899     if (r && r->p) {
900         r->p = NULL; /* mark as dead */
901         libusb_cancel_transfer(r->xfer);
902     }
903 }
904 
905 static void usb_host_detach_kernel(USBHostDevice *s)
906 {
907     struct libusb_config_descriptor *conf;
908     int rc, i;
909 
910     rc = libusb_get_active_config_descriptor(s->dev, &conf);
911     if (rc != 0) {
912         return;
913     }
914     for (i = 0; i < conf->bNumInterfaces; i++) {
915         rc = libusb_kernel_driver_active(s->dh, i);
916         usb_host_libusb_error("libusb_kernel_driver_active", rc);
917         if (rc != 1) {
918             continue;
919         }
920         trace_usb_host_detach_kernel(s->bus_num, s->addr, i);
921         rc = libusb_detach_kernel_driver(s->dh, i);
922         usb_host_libusb_error("libusb_detach_kernel_driver", rc);
923         s->ifs[i].detached = true;
924     }
925     libusb_free_config_descriptor(conf);
926 }
927 
928 static void usb_host_attach_kernel(USBHostDevice *s)
929 {
930     struct libusb_config_descriptor *conf;
931     int rc, i;
932 
933     rc = libusb_get_active_config_descriptor(s->dev, &conf);
934     if (rc != 0) {
935         return;
936     }
937     for (i = 0; i < conf->bNumInterfaces; i++) {
938         if (!s->ifs[i].detached) {
939             continue;
940         }
941         trace_usb_host_attach_kernel(s->bus_num, s->addr, i);
942         libusb_attach_kernel_driver(s->dh, i);
943         s->ifs[i].detached = false;
944     }
945     libusb_free_config_descriptor(conf);
946 }
947 
948 static int usb_host_claim_interfaces(USBHostDevice *s, int configuration)
949 {
950     USBDevice *udev = USB_DEVICE(s);
951     struct libusb_config_descriptor *conf;
952     int rc, i;
953 
954     for (i = 0; i < USB_MAX_INTERFACES; i++) {
955         udev->altsetting[i] = 0;
956     }
957     udev->ninterfaces   = 0;
958     udev->configuration = 0;
959 
960     if (configuration == 0) {
961         /* address state - ignore */
962         return USB_RET_SUCCESS;
963     }
964 
965     usb_host_detach_kernel(s);
966 
967     rc = libusb_get_active_config_descriptor(s->dev, &conf);
968     if (rc != 0) {
969         return USB_RET_STALL;
970     }
971 
972     for (i = 0; i < conf->bNumInterfaces; i++) {
973         trace_usb_host_claim_interface(s->bus_num, s->addr, configuration, i);
974         rc = libusb_claim_interface(s->dh, i);
975         usb_host_libusb_error("libusb_claim_interface", rc);
976         if (rc != 0) {
977             return USB_RET_STALL;
978         }
979         s->ifs[i].claimed = true;
980     }
981 
982     udev->ninterfaces   = conf->bNumInterfaces;
983     udev->configuration = configuration;
984 
985     libusb_free_config_descriptor(conf);
986     return USB_RET_SUCCESS;
987 }
988 
989 static void usb_host_release_interfaces(USBHostDevice *s)
990 {
991     USBDevice *udev = USB_DEVICE(s);
992     int i, rc;
993 
994     for (i = 0; i < udev->ninterfaces; i++) {
995         if (!s->ifs[i].claimed) {
996             continue;
997         }
998         trace_usb_host_release_interface(s->bus_num, s->addr, i);
999         rc = libusb_release_interface(s->dh, i);
1000         usb_host_libusb_error("libusb_release_interface", rc);
1001         s->ifs[i].claimed = false;
1002     }
1003 }
1004 
1005 static void usb_host_set_address(USBHostDevice *s, int addr)
1006 {
1007     USBDevice *udev = USB_DEVICE(s);
1008 
1009     trace_usb_host_set_address(s->bus_num, s->addr, addr);
1010     udev->addr = addr;
1011 }
1012 
1013 static void usb_host_set_config(USBHostDevice *s, int config, USBPacket *p)
1014 {
1015     int rc;
1016 
1017     trace_usb_host_set_config(s->bus_num, s->addr, config);
1018 
1019     usb_host_release_interfaces(s);
1020     usb_host_detach_kernel(s);
1021     rc = libusb_set_configuration(s->dh, config);
1022     if (rc != 0) {
1023         usb_host_libusb_error("libusb_set_configuration", rc);
1024         p->status = USB_RET_STALL;
1025         if (rc == LIBUSB_ERROR_NO_DEVICE) {
1026             usb_host_nodev(s);
1027         }
1028         return;
1029     }
1030     p->status = usb_host_claim_interfaces(s, config);
1031     if (p->status != USB_RET_SUCCESS) {
1032         return;
1033     }
1034     usb_host_ep_update(s);
1035 }
1036 
1037 static void usb_host_set_interface(USBHostDevice *s, int iface, int alt,
1038                                    USBPacket *p)
1039 {
1040     USBDevice *udev = USB_DEVICE(s);
1041     int rc;
1042 
1043     trace_usb_host_set_interface(s->bus_num, s->addr, iface, alt);
1044 
1045     usb_host_iso_free_all(s);
1046 
1047     if (iface >= USB_MAX_INTERFACES) {
1048         p->status = USB_RET_STALL;
1049         return;
1050     }
1051 
1052     rc = libusb_set_interface_alt_setting(s->dh, iface, alt);
1053     if (rc != 0) {
1054         usb_host_libusb_error("libusb_set_interface_alt_setting", rc);
1055         p->status = USB_RET_STALL;
1056         if (rc == LIBUSB_ERROR_NO_DEVICE) {
1057             usb_host_nodev(s);
1058         }
1059         return;
1060     }
1061 
1062     udev->altsetting[iface] = alt;
1063     usb_host_ep_update(s);
1064 }
1065 
1066 static void usb_host_handle_control(USBDevice *udev, USBPacket *p,
1067                                     int request, int value, int index,
1068                                     int length, uint8_t *data)
1069 {
1070     USBHostDevice *s = USB_HOST_DEVICE(udev);
1071     USBHostRequest *r;
1072     int rc;
1073 
1074     trace_usb_host_req_control(s->bus_num, s->addr, p, request, value, index);
1075 
1076     if (s->dh == NULL) {
1077         p->status = USB_RET_NODEV;
1078         trace_usb_host_req_emulated(s->bus_num, s->addr, p, p->status);
1079         return;
1080     }
1081 
1082     switch (request) {
1083     case DeviceOutRequest | USB_REQ_SET_ADDRESS:
1084         usb_host_set_address(s, value);
1085         trace_usb_host_req_emulated(s->bus_num, s->addr, p, p->status);
1086         return;
1087 
1088     case DeviceOutRequest | USB_REQ_SET_CONFIGURATION:
1089         usb_host_set_config(s, value & 0xff, p);
1090         trace_usb_host_req_emulated(s->bus_num, s->addr, p, p->status);
1091         return;
1092 
1093     case InterfaceOutRequest | USB_REQ_SET_INTERFACE:
1094         usb_host_set_interface(s, index, value, p);
1095         trace_usb_host_req_emulated(s->bus_num, s->addr, p, p->status);
1096         return;
1097 
1098     case EndpointOutRequest | USB_REQ_CLEAR_FEATURE:
1099         if (value == 0) { /* clear halt */
1100             int pid = (index & USB_DIR_IN) ? USB_TOKEN_IN : USB_TOKEN_OUT;
1101             libusb_clear_halt(s->dh, index);
1102             usb_ep_set_halted(udev, pid, index & 0x0f, 0);
1103             trace_usb_host_req_emulated(s->bus_num, s->addr, p, p->status);
1104             return;
1105         }
1106     }
1107 
1108     r = usb_host_req_alloc(s, p, (request >> 8) & USB_DIR_IN, length + 8);
1109     r->cbuf = data;
1110     r->clen = length;
1111     memcpy(r->buffer, udev->setup_buf, 8);
1112     if (!r->in) {
1113         memcpy(r->buffer + 8, r->cbuf, r->clen);
1114     }
1115 
1116     libusb_fill_control_transfer(r->xfer, s->dh, r->buffer,
1117                                  usb_host_req_complete_ctrl, r,
1118                                  CONTROL_TIMEOUT);
1119     rc = libusb_submit_transfer(r->xfer);
1120     if (rc != 0) {
1121         p->status = USB_RET_NODEV;
1122         trace_usb_host_req_complete(s->bus_num, s->addr, p,
1123                                     p->status, p->actual_length);
1124         if (rc == LIBUSB_ERROR_NO_DEVICE) {
1125             usb_host_nodev(s);
1126         }
1127         return;
1128     }
1129 
1130     p->status = USB_RET_ASYNC;
1131 }
1132 
1133 static void usb_host_handle_data(USBDevice *udev, USBPacket *p)
1134 {
1135     USBHostDevice *s = USB_HOST_DEVICE(udev);
1136     USBHostRequest *r;
1137     size_t size;
1138     int ep, rc;
1139 
1140     if (usb_host_use_combining(p->ep) && p->state == USB_PACKET_SETUP) {
1141         p->status = USB_RET_ADD_TO_QUEUE;
1142         return;
1143     }
1144 
1145     trace_usb_host_req_data(s->bus_num, s->addr, p,
1146                             p->pid == USB_TOKEN_IN,
1147                             p->ep->nr, p->iov.size);
1148 
1149     if (s->dh == NULL) {
1150         p->status = USB_RET_NODEV;
1151         trace_usb_host_req_emulated(s->bus_num, s->addr, p, p->status);
1152         return;
1153     }
1154     if (p->ep->halted) {
1155         p->status = USB_RET_STALL;
1156         trace_usb_host_req_emulated(s->bus_num, s->addr, p, p->status);
1157         return;
1158     }
1159 
1160     switch (usb_ep_get_type(udev, p->pid, p->ep->nr)) {
1161     case USB_ENDPOINT_XFER_BULK:
1162         size = usb_packet_size(p);
1163         r = usb_host_req_alloc(s, p, p->pid == USB_TOKEN_IN, size);
1164         if (!r->in) {
1165             usb_packet_copy(p, r->buffer, size);
1166         }
1167         ep = p->ep->nr | (r->in ? USB_DIR_IN : 0);
1168         libusb_fill_bulk_transfer(r->xfer, s->dh, ep,
1169                                   r->buffer, size,
1170                                   usb_host_req_complete_data, r,
1171                                   BULK_TIMEOUT);
1172         break;
1173     case USB_ENDPOINT_XFER_INT:
1174         r = usb_host_req_alloc(s, p, p->pid == USB_TOKEN_IN, p->iov.size);
1175         if (!r->in) {
1176             usb_packet_copy(p, r->buffer, p->iov.size);
1177         }
1178         ep = p->ep->nr | (r->in ? USB_DIR_IN : 0);
1179         libusb_fill_interrupt_transfer(r->xfer, s->dh, ep,
1180                                        r->buffer, p->iov.size,
1181                                        usb_host_req_complete_data, r,
1182                                        INTR_TIMEOUT);
1183         break;
1184     case USB_ENDPOINT_XFER_ISOC:
1185         if (p->pid == USB_TOKEN_IN) {
1186             usb_host_iso_data_in(s, p);
1187         } else {
1188             usb_host_iso_data_out(s, p);
1189         }
1190         trace_usb_host_req_complete(s->bus_num, s->addr, p,
1191                                     p->status, p->actual_length);
1192         return;
1193     default:
1194         p->status = USB_RET_STALL;
1195         trace_usb_host_req_complete(s->bus_num, s->addr, p,
1196                                     p->status, p->actual_length);
1197         return;
1198     }
1199 
1200     rc = libusb_submit_transfer(r->xfer);
1201     if (rc != 0) {
1202         p->status = USB_RET_NODEV;
1203         trace_usb_host_req_complete(s->bus_num, s->addr, p,
1204                                     p->status, p->actual_length);
1205         if (rc == LIBUSB_ERROR_NO_DEVICE) {
1206             usb_host_nodev(s);
1207         }
1208         return;
1209     }
1210 
1211     p->status = USB_RET_ASYNC;
1212 }
1213 
1214 static void usb_host_flush_ep_queue(USBDevice *dev, USBEndpoint *ep)
1215 {
1216     if (usb_host_use_combining(ep)) {
1217         usb_ep_combine_input_packets(ep);
1218     }
1219 }
1220 
1221 static void usb_host_handle_reset(USBDevice *udev)
1222 {
1223     USBHostDevice *s = USB_HOST_DEVICE(udev);
1224 
1225     trace_usb_host_reset(s->bus_num, s->addr);
1226 
1227     if (udev->configuration == 0) {
1228         return;
1229     }
1230     usb_host_release_interfaces(s);
1231     libusb_reset_device(s->dh);
1232     usb_host_claim_interfaces(s, 0);
1233     usb_host_ep_update(s);
1234 }
1235 
1236 static const VMStateDescription vmstate_usb_host = {
1237     .name = "usb-host",
1238     .unmigratable = 1,
1239     .fields = (VMStateField[]) {
1240         VMSTATE_USB_DEVICE(parent_obj, USBHostDevice),
1241         VMSTATE_END_OF_LIST()
1242     }
1243 };
1244 
1245 static Property usb_host_dev_properties[] = {
1246     DEFINE_PROP_UINT32("hostbus",  USBHostDevice, match.bus_num,    0),
1247     DEFINE_PROP_UINT32("hostaddr", USBHostDevice, match.addr,       0),
1248     DEFINE_PROP_STRING("hostport", USBHostDevice, match.port),
1249     DEFINE_PROP_HEX32("vendorid",  USBHostDevice, match.vendor_id,  0),
1250     DEFINE_PROP_HEX32("productid", USBHostDevice, match.product_id, 0),
1251     DEFINE_PROP_UINT32("isobufs",  USBHostDevice, iso_urb_count,    4),
1252     DEFINE_PROP_UINT32("isobsize", USBHostDevice, iso_urb_frames,   32),
1253     DEFINE_PROP_INT32("bootindex", USBHostDevice, bootindex,        -1),
1254     DEFINE_PROP_UINT32("loglevel",  USBHostDevice, loglevel,
1255                        LIBUSB_LOG_LEVEL_WARNING),
1256     DEFINE_PROP_BIT("pipeline",    USBHostDevice, options,
1257                     USB_HOST_OPT_PIPELINE, true),
1258     DEFINE_PROP_END_OF_LIST(),
1259 };
1260 
1261 static void usb_host_class_initfn(ObjectClass *klass, void *data)
1262 {
1263     DeviceClass *dc = DEVICE_CLASS(klass);
1264     USBDeviceClass *uc = USB_DEVICE_CLASS(klass);
1265 
1266     uc->init           = usb_host_initfn;
1267     uc->product_desc   = "USB Host Device";
1268     uc->cancel_packet  = usb_host_cancel_packet;
1269     uc->handle_data    = usb_host_handle_data;
1270     uc->handle_control = usb_host_handle_control;
1271     uc->handle_reset   = usb_host_handle_reset;
1272     uc->handle_destroy = usb_host_handle_destroy;
1273     uc->flush_ep_queue = usb_host_flush_ep_queue;
1274     dc->vmsd = &vmstate_usb_host;
1275     dc->props = usb_host_dev_properties;
1276 }
1277 
1278 static TypeInfo usb_host_dev_info = {
1279     .name          = TYPE_USB_HOST_DEVICE,
1280     .parent        = TYPE_USB_DEVICE,
1281     .instance_size = sizeof(USBHostDevice),
1282     .class_init    = usb_host_class_initfn,
1283 };
1284 
1285 static void usb_host_register_types(void)
1286 {
1287     type_register_static(&usb_host_dev_info);
1288 }
1289 
1290 type_init(usb_host_register_types)
1291 
1292 /* ------------------------------------------------------------------------ */
1293 
1294 static QEMUTimer *usb_auto_timer;
1295 static VMChangeStateEntry *usb_vmstate;
1296 
1297 static void usb_host_vm_state(void *unused, int running, RunState state)
1298 {
1299     if (running) {
1300         usb_host_auto_check(unused);
1301     }
1302 }
1303 
1304 static void usb_host_auto_check(void *unused)
1305 {
1306     struct USBHostDevice *s;
1307     struct USBAutoFilter *f;
1308     libusb_device **devs;
1309     struct libusb_device_descriptor ddesc;
1310     int unconnected = 0;
1311     int i, n;
1312 
1313     if (usb_host_init() != 0) {
1314         return;
1315     }
1316 
1317     if (runstate_is_running()) {
1318         n = libusb_get_device_list(ctx, &devs);
1319         for (i = 0; i < n; i++) {
1320             if (libusb_get_device_descriptor(devs[i], &ddesc) != 0) {
1321                 continue;
1322             }
1323             if (ddesc.bDeviceClass == LIBUSB_CLASS_HUB) {
1324                 continue;
1325             }
1326             QTAILQ_FOREACH(s, &hostdevs, next) {
1327                 f = &s->match;
1328                 if (f->bus_num > 0 &&
1329                     f->bus_num != libusb_get_bus_number(devs[i])) {
1330                     continue;
1331                 }
1332                 if (f->addr > 0 &&
1333                     f->addr != libusb_get_device_address(devs[i])) {
1334                     continue;
1335                 }
1336                 if (f->port != NULL) {
1337                     char port[16] = "-";
1338                     usb_host_get_port(devs[i], port, sizeof(port));
1339                     if (strcmp(f->port, port) != 0) {
1340                         continue;
1341                     }
1342                 }
1343                 if (f->vendor_id > 0 &&
1344                     f->vendor_id != ddesc.idVendor) {
1345                     continue;
1346                 }
1347                 if (f->product_id > 0 &&
1348                     f->product_id != ddesc.idProduct) {
1349                     continue;
1350                 }
1351 
1352                 /* We got a match */
1353                 s->seen++;
1354                 if (s->errcount >= 3) {
1355                     continue;
1356                 }
1357                 if (s->dh != NULL) {
1358                     continue;
1359                 }
1360                 if (usb_host_open(s, devs[i]) < 0) {
1361                     s->errcount++;
1362                     continue;
1363                 }
1364                 break;
1365             }
1366         }
1367         libusb_free_device_list(devs, 1);
1368 
1369         QTAILQ_FOREACH(s, &hostdevs, next) {
1370             if (s->dh == NULL) {
1371                 unconnected++;
1372             }
1373             if (s->seen == 0) {
1374                 if (s->dh) {
1375                     usb_host_close(s);
1376                 }
1377                 s->errcount = 0;
1378             }
1379             s->seen = 0;
1380         }
1381 
1382 #if 0
1383         if (unconnected == 0) {
1384             /* nothing to watch */
1385             if (usb_auto_timer) {
1386                 qemu_del_timer(usb_auto_timer);
1387                 trace_usb_host_auto_scan_disabled();
1388             }
1389             return;
1390         }
1391 #endif
1392     }
1393 
1394     if (!usb_vmstate) {
1395         usb_vmstate = qemu_add_vm_change_state_handler(usb_host_vm_state, NULL);
1396     }
1397     if (!usb_auto_timer) {
1398         usb_auto_timer = qemu_new_timer_ms(rt_clock, usb_host_auto_check, NULL);
1399         if (!usb_auto_timer) {
1400             return;
1401         }
1402         trace_usb_host_auto_scan_enabled();
1403     }
1404     qemu_mod_timer(usb_auto_timer, qemu_get_clock_ms(rt_clock) + 2000);
1405 }
1406 
1407 void usb_host_info(Monitor *mon, const QDict *qdict)
1408 {
1409     libusb_device **devs;
1410     struct libusb_device_descriptor ddesc;
1411     char port[16];
1412     int i, n;
1413 
1414     if (usb_host_init() != 0) {
1415         return;
1416     }
1417 
1418     n = libusb_get_device_list(ctx, &devs);
1419     for (i = 0; i < n; i++) {
1420         if (libusb_get_device_descriptor(devs[i], &ddesc) != 0) {
1421             continue;
1422         }
1423         if (ddesc.bDeviceClass == LIBUSB_CLASS_HUB) {
1424             continue;
1425         }
1426         usb_host_get_port(devs[i], port, sizeof(port));
1427         monitor_printf(mon, "  Bus %d, Addr %d, Port %s, Speed %s Mb/s\n",
1428                        libusb_get_bus_number(devs[i]),
1429                        libusb_get_device_address(devs[i]),
1430                        port,
1431                        speed_name[libusb_get_device_speed(devs[i])]);
1432         monitor_printf(mon, "    Class %02x:", ddesc.bDeviceClass);
1433         monitor_printf(mon, " USB device %04x:%04x",
1434                        ddesc.idVendor, ddesc.idProduct);
1435         if (ddesc.iProduct) {
1436             libusb_device_handle *handle;
1437             if (libusb_open(devs[i], &handle) == 0) {
1438                 unsigned char name[64] = "";
1439                 libusb_get_string_descriptor_ascii(handle,
1440                                                    ddesc.iProduct,
1441                                                    name, sizeof(name));
1442                 libusb_close(handle);
1443                 monitor_printf(mon, ", %s", name);
1444             }
1445         }
1446         monitor_printf(mon, "\n");
1447     }
1448     libusb_free_device_list(devs, 1);
1449 }
1450