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