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