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