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