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