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