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