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