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