wxx: Fix compiler warning for host-libusb.c
[qemu.git] / hw / usb / host-libusb.c
blob9af0580ab0b4f8dcd55e5b588d46a657236ec2a9
1 /*
2 * Linux host USB redirector
4 * Copyright (c) 2005 Fabrice Bellard
6 * Copyright (c) 2008 Max Krasnyansky
7 * Support for host device auto connect & disconnect
8 * Major rewrite to support fully async operation
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
14 * (c) 2012 Gerd Hoffmann <kraxel@redhat.com>
15 * Completely rewritten to use libusb instead of usbfs ioctls.
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:
24 * The above copyright notice and this permission notice shall be included in
25 * all copies or substantial portions of the Software.
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.
36 #include "qemu/osdep.h"
37 #ifndef CONFIG_WIN32
38 #include <poll.h>
39 #endif
40 #include <libusb.h>
42 #include "qapi/error.h"
43 #include "qemu-common.h"
44 #include "monitor/monitor.h"
45 #include "qemu/error-report.h"
46 #include "sysemu/sysemu.h"
47 #include "trace.h"
49 #include "hw/usb.h"
51 /* ------------------------------------------------------------------------ */
53 #define TYPE_USB_HOST_DEVICE "usb-host"
54 #define USB_HOST_DEVICE(obj) \
55 OBJECT_CHECK(USBHostDevice, (obj), TYPE_USB_HOST_DEVICE)
57 typedef struct USBHostDevice USBHostDevice;
58 typedef struct USBHostRequest USBHostRequest;
59 typedef struct USBHostIsoXfer USBHostIsoXfer;
60 typedef struct USBHostIsoRing USBHostIsoRing;
62 struct USBAutoFilter {
63 uint32_t bus_num;
64 uint32_t addr;
65 char *port;
66 uint32_t vendor_id;
67 uint32_t product_id;
70 enum USBHostDeviceOptions {
71 USB_HOST_OPT_PIPELINE,
74 struct USBHostDevice {
75 USBDevice parent_obj;
77 /* properties */
78 struct USBAutoFilter match;
79 int32_t bootindex;
80 uint32_t iso_urb_count;
81 uint32_t iso_urb_frames;
82 uint32_t options;
83 uint32_t loglevel;
84 bool needs_autoscan;
86 /* state */
87 QTAILQ_ENTRY(USBHostDevice) next;
88 int seen, errcount;
89 int bus_num;
90 int addr;
91 char port[16];
93 libusb_device *dev;
94 libusb_device_handle *dh;
95 struct libusb_device_descriptor ddesc;
97 struct {
98 bool detached;
99 bool claimed;
100 } ifs[USB_MAX_INTERFACES];
102 /* callbacks & friends */
103 QEMUBH *bh_nodev;
104 QEMUBH *bh_postld;
105 Notifier exit;
107 /* request queues */
108 QTAILQ_HEAD(, USBHostRequest) requests;
109 QTAILQ_HEAD(, USBHostIsoRing) isorings;
112 struct USBHostRequest {
113 USBHostDevice *host;
114 USBPacket *p;
115 bool in;
116 struct libusb_transfer *xfer;
117 unsigned char *buffer;
118 unsigned char *cbuf;
119 unsigned int clen;
120 bool usb3ep0quirk;
121 QTAILQ_ENTRY(USBHostRequest) next;
124 struct USBHostIsoXfer {
125 USBHostIsoRing *ring;
126 struct libusb_transfer *xfer;
127 bool copy_complete;
128 unsigned int packet;
129 QTAILQ_ENTRY(USBHostIsoXfer) next;
132 struct USBHostIsoRing {
133 USBHostDevice *host;
134 USBEndpoint *ep;
135 QTAILQ_HEAD(, USBHostIsoXfer) unused;
136 QTAILQ_HEAD(, USBHostIsoXfer) inflight;
137 QTAILQ_HEAD(, USBHostIsoXfer) copy;
138 QTAILQ_ENTRY(USBHostIsoRing) next;
141 static QTAILQ_HEAD(, USBHostDevice) hostdevs =
142 QTAILQ_HEAD_INITIALIZER(hostdevs);
144 static void usb_host_auto_check(void *unused);
145 static void usb_host_release_interfaces(USBHostDevice *s);
146 static void usb_host_nodev(USBHostDevice *s);
147 static void usb_host_detach_kernel(USBHostDevice *s);
148 static void usb_host_attach_kernel(USBHostDevice *s);
150 /* ------------------------------------------------------------------------ */
152 #ifndef LIBUSB_LOG_LEVEL_WARNING /* older libusb didn't define these */
153 #define LIBUSB_LOG_LEVEL_WARNING 2
154 #endif
156 /* ------------------------------------------------------------------------ */
158 #define CONTROL_TIMEOUT 10000 /* 10 sec */
159 #define BULK_TIMEOUT 0 /* unlimited */
160 #define INTR_TIMEOUT 0 /* unlimited */
162 #if LIBUSBX_API_VERSION >= 0x01000103
163 # define HAVE_STREAMS 1
164 #endif
166 static const char *speed_name[] = {
167 [LIBUSB_SPEED_UNKNOWN] = "?",
168 [LIBUSB_SPEED_LOW] = "1.5",
169 [LIBUSB_SPEED_FULL] = "12",
170 [LIBUSB_SPEED_HIGH] = "480",
171 [LIBUSB_SPEED_SUPER] = "5000",
174 static const unsigned int speed_map[] = {
175 [LIBUSB_SPEED_LOW] = USB_SPEED_LOW,
176 [LIBUSB_SPEED_FULL] = USB_SPEED_FULL,
177 [LIBUSB_SPEED_HIGH] = USB_SPEED_HIGH,
178 [LIBUSB_SPEED_SUPER] = USB_SPEED_SUPER,
181 static const unsigned int status_map[] = {
182 [LIBUSB_TRANSFER_COMPLETED] = USB_RET_SUCCESS,
183 [LIBUSB_TRANSFER_ERROR] = USB_RET_IOERROR,
184 [LIBUSB_TRANSFER_TIMED_OUT] = USB_RET_IOERROR,
185 [LIBUSB_TRANSFER_CANCELLED] = USB_RET_IOERROR,
186 [LIBUSB_TRANSFER_STALL] = USB_RET_STALL,
187 [LIBUSB_TRANSFER_NO_DEVICE] = USB_RET_NODEV,
188 [LIBUSB_TRANSFER_OVERFLOW] = USB_RET_BABBLE,
191 static const char *err_names[] = {
192 [-LIBUSB_ERROR_IO] = "IO",
193 [-LIBUSB_ERROR_INVALID_PARAM] = "INVALID_PARAM",
194 [-LIBUSB_ERROR_ACCESS] = "ACCESS",
195 [-LIBUSB_ERROR_NO_DEVICE] = "NO_DEVICE",
196 [-LIBUSB_ERROR_NOT_FOUND] = "NOT_FOUND",
197 [-LIBUSB_ERROR_BUSY] = "BUSY",
198 [-LIBUSB_ERROR_TIMEOUT] = "TIMEOUT",
199 [-LIBUSB_ERROR_OVERFLOW] = "OVERFLOW",
200 [-LIBUSB_ERROR_PIPE] = "PIPE",
201 [-LIBUSB_ERROR_INTERRUPTED] = "INTERRUPTED",
202 [-LIBUSB_ERROR_NO_MEM] = "NO_MEM",
203 [-LIBUSB_ERROR_NOT_SUPPORTED] = "NOT_SUPPORTED",
204 [-LIBUSB_ERROR_OTHER] = "OTHER",
207 static libusb_context *ctx;
208 static uint32_t loglevel;
210 #ifndef CONFIG_WIN32
212 static void usb_host_handle_fd(void *opaque)
214 struct timeval tv = { 0, 0 };
215 libusb_handle_events_timeout(ctx, &tv);
218 static void usb_host_add_fd(int fd, short events, void *user_data)
220 qemu_set_fd_handler(fd,
221 (events & POLLIN) ? usb_host_handle_fd : NULL,
222 (events & POLLOUT) ? usb_host_handle_fd : NULL,
223 ctx);
226 static void usb_host_del_fd(int fd, void *user_data)
228 qemu_set_fd_handler(fd, NULL, NULL, NULL);
231 #endif /* !CONFIG_WIN32 */
233 static int usb_host_init(void)
235 #ifndef CONFIG_WIN32
236 const struct libusb_pollfd **poll;
237 #endif
238 int rc;
240 if (ctx) {
241 return 0;
243 rc = libusb_init(&ctx);
244 if (rc != 0) {
245 return -1;
247 libusb_set_debug(ctx, loglevel);
248 #ifdef CONFIG_WIN32
249 /* FIXME: add support for Windows. */
250 #else
251 libusb_set_pollfd_notifiers(ctx, usb_host_add_fd,
252 usb_host_del_fd,
253 ctx);
254 poll = libusb_get_pollfds(ctx);
255 if (poll) {
256 int i;
257 for (i = 0; poll[i] != NULL; i++) {
258 usb_host_add_fd(poll[i]->fd, poll[i]->events, ctx);
261 free(poll);
262 #endif
263 return 0;
266 static int usb_host_get_port(libusb_device *dev, char *port, size_t len)
268 uint8_t path[7];
269 size_t off;
270 int rc, i;
272 #if LIBUSBX_API_VERSION >= 0x01000102
273 rc = libusb_get_port_numbers(dev, path, 7);
274 #else
275 rc = libusb_get_port_path(ctx, dev, path, 7);
276 #endif
277 if (rc < 0) {
278 return 0;
280 off = snprintf(port, len, "%d", path[0]);
281 for (i = 1; i < rc; i++) {
282 off += snprintf(port+off, len-off, ".%d", path[i]);
284 return off;
287 static void usb_host_libusb_error(const char *func, int rc)
289 const char *errname;
291 if (rc >= 0) {
292 return;
295 if (-rc < ARRAY_SIZE(err_names) && err_names[-rc]) {
296 errname = err_names[-rc];
297 } else {
298 errname = "?";
300 error_report("%s: %d [%s]", func, rc, errname);
303 /* ------------------------------------------------------------------------ */
305 static bool usb_host_use_combining(USBEndpoint *ep)
307 int type;
309 if (!ep->pipeline) {
310 return false;
312 if (ep->pid != USB_TOKEN_IN) {
313 return false;
315 type = usb_ep_get_type(ep->dev, ep->pid, ep->nr);
316 if (type != USB_ENDPOINT_XFER_BULK) {
317 return false;
319 return true;
322 /* ------------------------------------------------------------------------ */
324 static USBHostRequest *usb_host_req_alloc(USBHostDevice *s, USBPacket *p,
325 bool in, size_t bufsize)
327 USBHostRequest *r = g_new0(USBHostRequest, 1);
329 r->host = s;
330 r->p = p;
331 r->in = in;
332 r->xfer = libusb_alloc_transfer(0);
333 if (bufsize) {
334 r->buffer = g_malloc(bufsize);
336 QTAILQ_INSERT_TAIL(&s->requests, r, next);
337 return r;
340 static void usb_host_req_free(USBHostRequest *r)
342 if (r->host) {
343 QTAILQ_REMOVE(&r->host->requests, r, next);
345 libusb_free_transfer(r->xfer);
346 g_free(r->buffer);
347 g_free(r);
350 static USBHostRequest *usb_host_req_find(USBHostDevice *s, USBPacket *p)
352 USBHostRequest *r;
354 QTAILQ_FOREACH(r, &s->requests, next) {
355 if (r->p == p) {
356 return r;
359 return NULL;
362 static void usb_host_req_complete_ctrl(struct libusb_transfer *xfer)
364 USBHostRequest *r = xfer->user_data;
365 USBHostDevice *s = r->host;
366 bool disconnect = (xfer->status == LIBUSB_TRANSFER_NO_DEVICE);
368 if (r->p == NULL) {
369 goto out; /* request was canceled */
372 r->p->status = status_map[xfer->status];
373 r->p->actual_length = xfer->actual_length;
374 if (r->in && xfer->actual_length) {
375 memcpy(r->cbuf, r->buffer + 8, xfer->actual_length);
377 /* Fix up USB-3 ep0 maxpacket size to allow superspeed connected devices
378 * to work redirected to a not superspeed capable hcd */
379 if (r->usb3ep0quirk && xfer->actual_length >= 18 &&
380 r->cbuf[7] == 9) {
381 r->cbuf[7] = 64;
384 trace_usb_host_req_complete(s->bus_num, s->addr, r->p,
385 r->p->status, r->p->actual_length);
386 usb_generic_async_ctrl_complete(USB_DEVICE(s), r->p);
388 out:
389 usb_host_req_free(r);
390 if (disconnect) {
391 usb_host_nodev(s);
395 static void usb_host_req_complete_data(struct libusb_transfer *xfer)
397 USBHostRequest *r = xfer->user_data;
398 USBHostDevice *s = r->host;
399 bool disconnect = (xfer->status == LIBUSB_TRANSFER_NO_DEVICE);
401 if (r->p == NULL) {
402 goto out; /* request was canceled */
405 r->p->status = status_map[xfer->status];
406 if (r->in && xfer->actual_length) {
407 usb_packet_copy(r->p, r->buffer, xfer->actual_length);
409 trace_usb_host_req_complete(s->bus_num, s->addr, r->p,
410 r->p->status, r->p->actual_length);
411 if (usb_host_use_combining(r->p->ep)) {
412 usb_combined_input_packet_complete(USB_DEVICE(s), r->p);
413 } else {
414 usb_packet_complete(USB_DEVICE(s), r->p);
417 out:
418 usb_host_req_free(r);
419 if (disconnect) {
420 usb_host_nodev(s);
424 static void usb_host_req_abort(USBHostRequest *r)
426 USBHostDevice *s = r->host;
427 bool inflight = (r->p && r->p->state == USB_PACKET_ASYNC);
429 if (inflight) {
430 r->p->status = USB_RET_NODEV;
431 trace_usb_host_req_complete(s->bus_num, s->addr, r->p,
432 r->p->status, r->p->actual_length);
433 if (r->p->ep->nr == 0) {
434 usb_generic_async_ctrl_complete(USB_DEVICE(s), r->p);
435 } else {
436 usb_packet_complete(USB_DEVICE(s), r->p);
438 r->p = NULL;
441 QTAILQ_REMOVE(&r->host->requests, r, next);
442 r->host = NULL;
444 if (inflight) {
445 libusb_cancel_transfer(r->xfer);
449 /* ------------------------------------------------------------------------ */
451 static void usb_host_req_complete_iso(struct libusb_transfer *transfer)
453 USBHostIsoXfer *xfer = transfer->user_data;
455 if (!xfer) {
456 /* USBHostIsoXfer released while inflight */
457 g_free(transfer->buffer);
458 libusb_free_transfer(transfer);
459 return;
462 QTAILQ_REMOVE(&xfer->ring->inflight, xfer, next);
463 if (QTAILQ_EMPTY(&xfer->ring->inflight)) {
464 USBHostDevice *s = xfer->ring->host;
465 trace_usb_host_iso_stop(s->bus_num, s->addr, xfer->ring->ep->nr);
467 if (xfer->ring->ep->pid == USB_TOKEN_IN) {
468 QTAILQ_INSERT_TAIL(&xfer->ring->copy, xfer, next);
469 usb_wakeup(xfer->ring->ep, 0);
470 } else {
471 QTAILQ_INSERT_TAIL(&xfer->ring->unused, xfer, next);
475 static USBHostIsoRing *usb_host_iso_alloc(USBHostDevice *s, USBEndpoint *ep)
477 USBHostIsoRing *ring = g_new0(USBHostIsoRing, 1);
478 USBHostIsoXfer *xfer;
479 /* FIXME: check interval (for now assume one xfer per frame) */
480 int packets = s->iso_urb_frames;
481 int i;
483 ring->host = s;
484 ring->ep = ep;
485 QTAILQ_INIT(&ring->unused);
486 QTAILQ_INIT(&ring->inflight);
487 QTAILQ_INIT(&ring->copy);
488 QTAILQ_INSERT_TAIL(&s->isorings, ring, next);
490 for (i = 0; i < s->iso_urb_count; i++) {
491 xfer = g_new0(USBHostIsoXfer, 1);
492 xfer->ring = ring;
493 xfer->xfer = libusb_alloc_transfer(packets);
494 xfer->xfer->dev_handle = s->dh;
495 xfer->xfer->type = LIBUSB_TRANSFER_TYPE_ISOCHRONOUS;
497 xfer->xfer->endpoint = ring->ep->nr;
498 if (ring->ep->pid == USB_TOKEN_IN) {
499 xfer->xfer->endpoint |= USB_DIR_IN;
501 xfer->xfer->callback = usb_host_req_complete_iso;
502 xfer->xfer->user_data = xfer;
504 xfer->xfer->num_iso_packets = packets;
505 xfer->xfer->length = ring->ep->max_packet_size * packets;
506 xfer->xfer->buffer = g_malloc0(xfer->xfer->length);
508 QTAILQ_INSERT_TAIL(&ring->unused, xfer, next);
511 return ring;
514 static USBHostIsoRing *usb_host_iso_find(USBHostDevice *s, USBEndpoint *ep)
516 USBHostIsoRing *ring;
518 QTAILQ_FOREACH(ring, &s->isorings, next) {
519 if (ring->ep == ep) {
520 return ring;
523 return NULL;
526 static void usb_host_iso_reset_xfer(USBHostIsoXfer *xfer)
528 libusb_set_iso_packet_lengths(xfer->xfer,
529 xfer->ring->ep->max_packet_size);
530 xfer->packet = 0;
531 xfer->copy_complete = false;
534 static void usb_host_iso_free_xfer(USBHostIsoXfer *xfer, bool inflight)
536 if (inflight) {
537 xfer->xfer->user_data = NULL;
538 } else {
539 g_free(xfer->xfer->buffer);
540 libusb_free_transfer(xfer->xfer);
542 g_free(xfer);
545 static void usb_host_iso_free(USBHostIsoRing *ring)
547 USBHostIsoXfer *xfer;
549 while ((xfer = QTAILQ_FIRST(&ring->inflight)) != NULL) {
550 QTAILQ_REMOVE(&ring->inflight, xfer, next);
551 usb_host_iso_free_xfer(xfer, true);
553 while ((xfer = QTAILQ_FIRST(&ring->unused)) != NULL) {
554 QTAILQ_REMOVE(&ring->unused, xfer, next);
555 usb_host_iso_free_xfer(xfer, false);
557 while ((xfer = QTAILQ_FIRST(&ring->copy)) != NULL) {
558 QTAILQ_REMOVE(&ring->copy, xfer, next);
559 usb_host_iso_free_xfer(xfer, false);
562 QTAILQ_REMOVE(&ring->host->isorings, ring, next);
563 g_free(ring);
566 static void usb_host_iso_free_all(USBHostDevice *s)
568 USBHostIsoRing *ring;
570 while ((ring = QTAILQ_FIRST(&s->isorings)) != NULL) {
571 usb_host_iso_free(ring);
575 static bool usb_host_iso_data_copy(USBHostIsoXfer *xfer, USBPacket *p)
577 unsigned int psize;
578 unsigned char *buf;
580 buf = libusb_get_iso_packet_buffer_simple(xfer->xfer, xfer->packet);
581 if (p->pid == USB_TOKEN_OUT) {
582 psize = p->iov.size;
583 if (psize > xfer->ring->ep->max_packet_size) {
584 /* should not happen (guest bug) */
585 psize = xfer->ring->ep->max_packet_size;
587 xfer->xfer->iso_packet_desc[xfer->packet].length = psize;
588 } else {
589 psize = xfer->xfer->iso_packet_desc[xfer->packet].actual_length;
590 if (psize > p->iov.size) {
591 /* should not happen (guest bug) */
592 psize = p->iov.size;
595 usb_packet_copy(p, buf, psize);
596 xfer->packet++;
597 xfer->copy_complete = (xfer->packet == xfer->xfer->num_iso_packets);
598 return xfer->copy_complete;
601 static void usb_host_iso_data_in(USBHostDevice *s, USBPacket *p)
603 USBHostIsoRing *ring;
604 USBHostIsoXfer *xfer;
605 bool disconnect = false;
606 int rc;
608 ring = usb_host_iso_find(s, p->ep);
609 if (ring == NULL) {
610 ring = usb_host_iso_alloc(s, p->ep);
613 /* copy data to guest */
614 xfer = QTAILQ_FIRST(&ring->copy);
615 if (xfer != NULL) {
616 if (usb_host_iso_data_copy(xfer, p)) {
617 QTAILQ_REMOVE(&ring->copy, xfer, next);
618 QTAILQ_INSERT_TAIL(&ring->unused, xfer, next);
622 /* submit empty bufs to host */
623 while ((xfer = QTAILQ_FIRST(&ring->unused)) != NULL) {
624 QTAILQ_REMOVE(&ring->unused, xfer, next);
625 usb_host_iso_reset_xfer(xfer);
626 rc = libusb_submit_transfer(xfer->xfer);
627 if (rc != 0) {
628 usb_host_libusb_error("libusb_submit_transfer [iso]", rc);
629 QTAILQ_INSERT_TAIL(&ring->unused, xfer, next);
630 if (rc == LIBUSB_ERROR_NO_DEVICE) {
631 disconnect = true;
633 break;
635 if (QTAILQ_EMPTY(&ring->inflight)) {
636 trace_usb_host_iso_start(s->bus_num, s->addr, p->ep->nr);
638 QTAILQ_INSERT_TAIL(&ring->inflight, xfer, next);
641 if (disconnect) {
642 usb_host_nodev(s);
646 static void usb_host_iso_data_out(USBHostDevice *s, USBPacket *p)
648 USBHostIsoRing *ring;
649 USBHostIsoXfer *xfer;
650 bool disconnect = false;
651 int rc, filled = 0;
653 ring = usb_host_iso_find(s, p->ep);
654 if (ring == NULL) {
655 ring = usb_host_iso_alloc(s, p->ep);
658 /* copy data from guest */
659 xfer = QTAILQ_FIRST(&ring->copy);
660 while (xfer != NULL && xfer->copy_complete) {
661 filled++;
662 xfer = QTAILQ_NEXT(xfer, next);
664 if (xfer == NULL) {
665 xfer = QTAILQ_FIRST(&ring->unused);
666 if (xfer == NULL) {
667 trace_usb_host_iso_out_of_bufs(s->bus_num, s->addr, p->ep->nr);
668 return;
670 QTAILQ_REMOVE(&ring->unused, xfer, next);
671 usb_host_iso_reset_xfer(xfer);
672 QTAILQ_INSERT_TAIL(&ring->copy, xfer, next);
674 usb_host_iso_data_copy(xfer, p);
676 if (QTAILQ_EMPTY(&ring->inflight)) {
677 /* wait until half of our buffers are filled
678 before kicking the iso out stream */
679 if (filled*2 < s->iso_urb_count) {
680 return;
684 /* submit filled bufs to host */
685 while ((xfer = QTAILQ_FIRST(&ring->copy)) != NULL &&
686 xfer->copy_complete) {
687 QTAILQ_REMOVE(&ring->copy, xfer, next);
688 rc = libusb_submit_transfer(xfer->xfer);
689 if (rc != 0) {
690 usb_host_libusb_error("libusb_submit_transfer [iso]", rc);
691 QTAILQ_INSERT_TAIL(&ring->unused, xfer, next);
692 if (rc == LIBUSB_ERROR_NO_DEVICE) {
693 disconnect = true;
695 break;
697 if (QTAILQ_EMPTY(&ring->inflight)) {
698 trace_usb_host_iso_start(s->bus_num, s->addr, p->ep->nr);
700 QTAILQ_INSERT_TAIL(&ring->inflight, xfer, next);
703 if (disconnect) {
704 usb_host_nodev(s);
708 /* ------------------------------------------------------------------------ */
710 static void usb_host_speed_compat(USBHostDevice *s)
712 USBDevice *udev = USB_DEVICE(s);
713 struct libusb_config_descriptor *conf;
714 const struct libusb_interface_descriptor *intf;
715 const struct libusb_endpoint_descriptor *endp;
716 #ifdef HAVE_STREAMS
717 struct libusb_ss_endpoint_companion_descriptor *endp_ss_comp;
718 #endif
719 bool compat_high = true;
720 bool compat_full = true;
721 uint8_t type;
722 int rc, c, i, a, e;
724 for (c = 0;; c++) {
725 rc = libusb_get_config_descriptor(s->dev, c, &conf);
726 if (rc != 0) {
727 break;
729 for (i = 0; i < conf->bNumInterfaces; i++) {
730 for (a = 0; a < conf->interface[i].num_altsetting; a++) {
731 intf = &conf->interface[i].altsetting[a];
732 for (e = 0; e < intf->bNumEndpoints; e++) {
733 endp = &intf->endpoint[e];
734 type = endp->bmAttributes & 0x3;
735 switch (type) {
736 case 0x01: /* ISO */
737 compat_full = false;
738 compat_high = false;
739 break;
740 case 0x02: /* BULK */
741 #ifdef HAVE_STREAMS
742 rc = libusb_get_ss_endpoint_companion_descriptor
743 (ctx, endp, &endp_ss_comp);
744 if (rc == LIBUSB_SUCCESS) {
745 libusb_free_ss_endpoint_companion_descriptor
746 (endp_ss_comp);
747 compat_full = false;
748 compat_high = false;
750 #endif
751 break;
752 case 0x03: /* INTERRUPT */
753 if (endp->wMaxPacketSize > 64) {
754 compat_full = false;
756 if (endp->wMaxPacketSize > 1024) {
757 compat_high = false;
759 break;
764 libusb_free_config_descriptor(conf);
767 udev->speedmask = (1 << udev->speed);
768 if (udev->speed == USB_SPEED_SUPER && compat_high) {
769 udev->speedmask |= USB_SPEED_MASK_HIGH;
771 if (udev->speed == USB_SPEED_SUPER && compat_full) {
772 udev->speedmask |= USB_SPEED_MASK_FULL;
774 if (udev->speed == USB_SPEED_HIGH && compat_full) {
775 udev->speedmask |= USB_SPEED_MASK_FULL;
779 static void usb_host_ep_update(USBHostDevice *s)
781 static const char *tname[] = {
782 [USB_ENDPOINT_XFER_CONTROL] = "control",
783 [USB_ENDPOINT_XFER_ISOC] = "isoc",
784 [USB_ENDPOINT_XFER_BULK] = "bulk",
785 [USB_ENDPOINT_XFER_INT] = "int",
787 USBDevice *udev = USB_DEVICE(s);
788 struct libusb_config_descriptor *conf;
789 const struct libusb_interface_descriptor *intf;
790 const struct libusb_endpoint_descriptor *endp;
791 #ifdef HAVE_STREAMS
792 struct libusb_ss_endpoint_companion_descriptor *endp_ss_comp;
793 #endif
794 uint8_t devep, type;
795 int pid, ep;
796 int rc, i, e;
798 usb_ep_reset(udev);
799 rc = libusb_get_active_config_descriptor(s->dev, &conf);
800 if (rc != 0) {
801 return;
803 trace_usb_host_parse_config(s->bus_num, s->addr,
804 conf->bConfigurationValue, true);
806 for (i = 0; i < conf->bNumInterfaces; i++) {
807 assert(udev->altsetting[i] < conf->interface[i].num_altsetting);
808 intf = &conf->interface[i].altsetting[udev->altsetting[i]];
809 trace_usb_host_parse_interface(s->bus_num, s->addr,
810 intf->bInterfaceNumber,
811 intf->bAlternateSetting, true);
812 for (e = 0; e < intf->bNumEndpoints; e++) {
813 endp = &intf->endpoint[e];
815 devep = endp->bEndpointAddress;
816 pid = (devep & USB_DIR_IN) ? USB_TOKEN_IN : USB_TOKEN_OUT;
817 ep = devep & 0xf;
818 type = endp->bmAttributes & 0x3;
820 if (ep == 0) {
821 trace_usb_host_parse_error(s->bus_num, s->addr,
822 "invalid endpoint address");
823 return;
825 if (usb_ep_get_type(udev, pid, ep) != USB_ENDPOINT_XFER_INVALID) {
826 trace_usb_host_parse_error(s->bus_num, s->addr,
827 "duplicate endpoint address");
828 return;
831 trace_usb_host_parse_endpoint(s->bus_num, s->addr, ep,
832 (devep & USB_DIR_IN) ? "in" : "out",
833 tname[type], true);
834 usb_ep_set_max_packet_size(udev, pid, ep,
835 endp->wMaxPacketSize);
836 usb_ep_set_type(udev, pid, ep, type);
837 usb_ep_set_ifnum(udev, pid, ep, i);
838 usb_ep_set_halted(udev, pid, ep, 0);
839 #ifdef HAVE_STREAMS
840 if (type == LIBUSB_TRANSFER_TYPE_BULK &&
841 libusb_get_ss_endpoint_companion_descriptor(ctx, endp,
842 &endp_ss_comp) == LIBUSB_SUCCESS) {
843 usb_ep_set_max_streams(udev, pid, ep,
844 endp_ss_comp->bmAttributes);
845 libusb_free_ss_endpoint_companion_descriptor(endp_ss_comp);
847 #endif
851 libusb_free_config_descriptor(conf);
854 static int usb_host_open(USBHostDevice *s, libusb_device *dev)
856 USBDevice *udev = USB_DEVICE(s);
857 int bus_num = libusb_get_bus_number(dev);
858 int addr = libusb_get_device_address(dev);
859 int rc;
860 Error *local_err = NULL;
862 trace_usb_host_open_started(bus_num, addr);
864 if (s->dh != NULL) {
865 goto fail;
867 rc = libusb_open(dev, &s->dh);
868 if (rc != 0) {
869 goto fail;
872 s->dev = dev;
873 s->bus_num = bus_num;
874 s->addr = addr;
876 usb_host_detach_kernel(s);
878 libusb_get_device_descriptor(dev, &s->ddesc);
879 usb_host_get_port(s->dev, s->port, sizeof(s->port));
881 usb_ep_init(udev);
882 usb_host_ep_update(s);
884 udev->speed = speed_map[libusb_get_device_speed(dev)];
885 usb_host_speed_compat(s);
887 if (s->ddesc.iProduct) {
888 libusb_get_string_descriptor_ascii(s->dh, s->ddesc.iProduct,
889 (unsigned char *)udev->product_desc,
890 sizeof(udev->product_desc));
891 } else {
892 snprintf(udev->product_desc, sizeof(udev->product_desc),
893 "host:%d.%d", bus_num, addr);
896 usb_device_attach(udev, &local_err);
897 if (local_err) {
898 error_report_err(local_err);
899 goto fail;
902 trace_usb_host_open_success(bus_num, addr);
903 return 0;
905 fail:
906 trace_usb_host_open_failure(bus_num, addr);
907 if (s->dh != NULL) {
908 usb_host_release_interfaces(s);
909 libusb_reset_device(s->dh);
910 usb_host_attach_kernel(s);
911 libusb_close(s->dh);
912 s->dh = NULL;
913 s->dev = NULL;
915 return -1;
918 static void usb_host_abort_xfers(USBHostDevice *s)
920 USBHostRequest *r, *rtmp;
922 QTAILQ_FOREACH_SAFE(r, &s->requests, next, rtmp) {
923 usb_host_req_abort(r);
927 static int usb_host_close(USBHostDevice *s)
929 USBDevice *udev = USB_DEVICE(s);
931 if (s->dh == NULL) {
932 return -1;
935 trace_usb_host_close(s->bus_num, s->addr);
937 usb_host_abort_xfers(s);
938 usb_host_iso_free_all(s);
940 if (udev->attached) {
941 usb_device_detach(udev);
944 usb_host_release_interfaces(s);
945 libusb_reset_device(s->dh);
946 usb_host_attach_kernel(s);
947 libusb_close(s->dh);
948 s->dh = NULL;
949 s->dev = NULL;
951 usb_host_auto_check(NULL);
952 return 0;
955 static void usb_host_nodev_bh(void *opaque)
957 USBHostDevice *s = opaque;
958 usb_host_close(s);
961 static void usb_host_nodev(USBHostDevice *s)
963 if (!s->bh_nodev) {
964 s->bh_nodev = qemu_bh_new(usb_host_nodev_bh, s);
966 qemu_bh_schedule(s->bh_nodev);
969 static void usb_host_exit_notifier(struct Notifier *n, void *data)
971 USBHostDevice *s = container_of(n, USBHostDevice, exit);
973 if (s->dh) {
974 usb_host_release_interfaces(s);
975 usb_host_attach_kernel(s);
979 static libusb_device *usb_host_find_ref(int bus, int addr)
981 libusb_device **devs = NULL;
982 libusb_device *ret = NULL;
983 int i, n;
985 if (usb_host_init() != 0) {
986 return NULL;
988 n = libusb_get_device_list(ctx, &devs);
989 for (i = 0; i < n; i++) {
990 if (libusb_get_bus_number(devs[i]) == bus &&
991 libusb_get_device_address(devs[i]) == addr) {
992 ret = libusb_ref_device(devs[i]);
993 break;
996 libusb_free_device_list(devs, 1);
997 return ret;
1000 static void usb_host_realize(USBDevice *udev, Error **errp)
1002 USBHostDevice *s = USB_HOST_DEVICE(udev);
1003 libusb_device *ldev;
1004 int rc;
1006 if (s->match.vendor_id > 0xffff) {
1007 error_setg(errp, "vendorid out of range");
1008 return;
1010 if (s->match.product_id > 0xffff) {
1011 error_setg(errp, "productid out of range");
1012 return;
1014 if (s->match.addr > 127) {
1015 error_setg(errp, "hostaddr out of range");
1016 return;
1019 loglevel = s->loglevel;
1020 udev->flags |= (1 << USB_DEV_FLAG_IS_HOST);
1021 udev->auto_attach = 0;
1022 QTAILQ_INIT(&s->requests);
1023 QTAILQ_INIT(&s->isorings);
1025 if (s->match.addr && s->match.bus_num &&
1026 !s->match.vendor_id &&
1027 !s->match.product_id &&
1028 !s->match.port) {
1029 s->needs_autoscan = false;
1030 ldev = usb_host_find_ref(s->match.bus_num,
1031 s->match.addr);
1032 if (!ldev) {
1033 error_setg(errp, "failed to find host usb device %d:%d",
1034 s->match.bus_num, s->match.addr);
1035 return;
1037 rc = usb_host_open(s, ldev);
1038 libusb_unref_device(ldev);
1039 if (rc < 0) {
1040 error_setg(errp, "failed to open host usb device %d:%d",
1041 s->match.bus_num, s->match.addr);
1042 return;
1044 } else {
1045 s->needs_autoscan = true;
1046 QTAILQ_INSERT_TAIL(&hostdevs, s, next);
1047 usb_host_auto_check(NULL);
1050 s->exit.notify = usb_host_exit_notifier;
1051 qemu_add_exit_notifier(&s->exit);
1054 static void usb_host_instance_init(Object *obj)
1056 USBDevice *udev = USB_DEVICE(obj);
1057 USBHostDevice *s = USB_HOST_DEVICE(udev);
1059 device_add_bootindex_property(obj, &s->bootindex,
1060 "bootindex", NULL,
1061 &udev->qdev, NULL);
1064 static void usb_host_handle_destroy(USBDevice *udev)
1066 USBHostDevice *s = USB_HOST_DEVICE(udev);
1068 qemu_remove_exit_notifier(&s->exit);
1069 if (s->needs_autoscan) {
1070 QTAILQ_REMOVE(&hostdevs, s, next);
1072 usb_host_close(s);
1075 static void usb_host_cancel_packet(USBDevice *udev, USBPacket *p)
1077 USBHostDevice *s = USB_HOST_DEVICE(udev);
1078 USBHostRequest *r;
1080 if (p->combined) {
1081 usb_combined_packet_cancel(udev, p);
1082 return;
1085 trace_usb_host_req_canceled(s->bus_num, s->addr, p);
1087 r = usb_host_req_find(s, p);
1088 if (r && r->p) {
1089 r->p = NULL; /* mark as dead */
1090 libusb_cancel_transfer(r->xfer);
1094 static void usb_host_detach_kernel(USBHostDevice *s)
1096 struct libusb_config_descriptor *conf;
1097 int rc, i;
1099 rc = libusb_get_active_config_descriptor(s->dev, &conf);
1100 if (rc != 0) {
1101 return;
1103 for (i = 0; i < conf->bNumInterfaces; i++) {
1104 rc = libusb_kernel_driver_active(s->dh, i);
1105 usb_host_libusb_error("libusb_kernel_driver_active", rc);
1106 if (rc != 1) {
1107 continue;
1109 trace_usb_host_detach_kernel(s->bus_num, s->addr, i);
1110 rc = libusb_detach_kernel_driver(s->dh, i);
1111 usb_host_libusb_error("libusb_detach_kernel_driver", rc);
1112 s->ifs[i].detached = true;
1114 libusb_free_config_descriptor(conf);
1117 static void usb_host_attach_kernel(USBHostDevice *s)
1119 struct libusb_config_descriptor *conf;
1120 int rc, i;
1122 rc = libusb_get_active_config_descriptor(s->dev, &conf);
1123 if (rc != 0) {
1124 return;
1126 for (i = 0; i < conf->bNumInterfaces; i++) {
1127 if (!s->ifs[i].detached) {
1128 continue;
1130 trace_usb_host_attach_kernel(s->bus_num, s->addr, i);
1131 libusb_attach_kernel_driver(s->dh, i);
1132 s->ifs[i].detached = false;
1134 libusb_free_config_descriptor(conf);
1137 static int usb_host_claim_interfaces(USBHostDevice *s, int configuration)
1139 USBDevice *udev = USB_DEVICE(s);
1140 struct libusb_config_descriptor *conf;
1141 int rc, i;
1143 for (i = 0; i < USB_MAX_INTERFACES; i++) {
1144 udev->altsetting[i] = 0;
1146 udev->ninterfaces = 0;
1147 udev->configuration = 0;
1149 usb_host_detach_kernel(s);
1151 rc = libusb_get_active_config_descriptor(s->dev, &conf);
1152 if (rc != 0) {
1153 if (rc == LIBUSB_ERROR_NOT_FOUND) {
1154 /* address state - ignore */
1155 return USB_RET_SUCCESS;
1157 return USB_RET_STALL;
1160 for (i = 0; i < conf->bNumInterfaces; i++) {
1161 trace_usb_host_claim_interface(s->bus_num, s->addr, configuration, i);
1162 rc = libusb_claim_interface(s->dh, i);
1163 usb_host_libusb_error("libusb_claim_interface", rc);
1164 if (rc != 0) {
1165 return USB_RET_STALL;
1167 s->ifs[i].claimed = true;
1170 udev->ninterfaces = conf->bNumInterfaces;
1171 udev->configuration = configuration;
1173 libusb_free_config_descriptor(conf);
1174 return USB_RET_SUCCESS;
1177 static void usb_host_release_interfaces(USBHostDevice *s)
1179 USBDevice *udev = USB_DEVICE(s);
1180 int i, rc;
1182 for (i = 0; i < udev->ninterfaces; i++) {
1183 if (!s->ifs[i].claimed) {
1184 continue;
1186 trace_usb_host_release_interface(s->bus_num, s->addr, i);
1187 rc = libusb_release_interface(s->dh, i);
1188 usb_host_libusb_error("libusb_release_interface", rc);
1189 s->ifs[i].claimed = false;
1193 static void usb_host_set_address(USBHostDevice *s, int addr)
1195 USBDevice *udev = USB_DEVICE(s);
1197 trace_usb_host_set_address(s->bus_num, s->addr, addr);
1198 udev->addr = addr;
1201 static void usb_host_set_config(USBHostDevice *s, int config, USBPacket *p)
1203 int rc;
1205 trace_usb_host_set_config(s->bus_num, s->addr, config);
1207 usb_host_release_interfaces(s);
1208 rc = libusb_set_configuration(s->dh, config);
1209 if (rc != 0) {
1210 usb_host_libusb_error("libusb_set_configuration", rc);
1211 p->status = USB_RET_STALL;
1212 if (rc == LIBUSB_ERROR_NO_DEVICE) {
1213 usb_host_nodev(s);
1215 return;
1217 p->status = usb_host_claim_interfaces(s, config);
1218 if (p->status != USB_RET_SUCCESS) {
1219 return;
1221 usb_host_ep_update(s);
1224 static void usb_host_set_interface(USBHostDevice *s, int iface, int alt,
1225 USBPacket *p)
1227 USBDevice *udev = USB_DEVICE(s);
1228 int rc;
1230 trace_usb_host_set_interface(s->bus_num, s->addr, iface, alt);
1232 usb_host_iso_free_all(s);
1234 if (iface >= USB_MAX_INTERFACES) {
1235 p->status = USB_RET_STALL;
1236 return;
1239 rc = libusb_set_interface_alt_setting(s->dh, iface, alt);
1240 if (rc != 0) {
1241 usb_host_libusb_error("libusb_set_interface_alt_setting", rc);
1242 p->status = USB_RET_STALL;
1243 if (rc == LIBUSB_ERROR_NO_DEVICE) {
1244 usb_host_nodev(s);
1246 return;
1249 udev->altsetting[iface] = alt;
1250 usb_host_ep_update(s);
1253 static void usb_host_handle_control(USBDevice *udev, USBPacket *p,
1254 int request, int value, int index,
1255 int length, uint8_t *data)
1257 USBHostDevice *s = USB_HOST_DEVICE(udev);
1258 USBHostRequest *r;
1259 int rc;
1261 trace_usb_host_req_control(s->bus_num, s->addr, p, request, value, index);
1263 if (s->dh == NULL) {
1264 p->status = USB_RET_NODEV;
1265 trace_usb_host_req_emulated(s->bus_num, s->addr, p, p->status);
1266 return;
1269 switch (request) {
1270 case DeviceOutRequest | USB_REQ_SET_ADDRESS:
1271 usb_host_set_address(s, value);
1272 trace_usb_host_req_emulated(s->bus_num, s->addr, p, p->status);
1273 return;
1275 case DeviceOutRequest | USB_REQ_SET_CONFIGURATION:
1276 usb_host_set_config(s, value & 0xff, p);
1277 trace_usb_host_req_emulated(s->bus_num, s->addr, p, p->status);
1278 return;
1280 case InterfaceOutRequest | USB_REQ_SET_INTERFACE:
1281 usb_host_set_interface(s, index, value, p);
1282 trace_usb_host_req_emulated(s->bus_num, s->addr, p, p->status);
1283 return;
1285 case EndpointOutRequest | USB_REQ_CLEAR_FEATURE:
1286 if (value == 0) { /* clear halt */
1287 int pid = (index & USB_DIR_IN) ? USB_TOKEN_IN : USB_TOKEN_OUT;
1288 libusb_clear_halt(s->dh, index);
1289 usb_ep_set_halted(udev, pid, index & 0x0f, 0);
1290 trace_usb_host_req_emulated(s->bus_num, s->addr, p, p->status);
1291 return;
1295 r = usb_host_req_alloc(s, p, (request >> 8) & USB_DIR_IN, length + 8);
1296 r->cbuf = data;
1297 r->clen = length;
1298 memcpy(r->buffer, udev->setup_buf, 8);
1299 if (!r->in) {
1300 memcpy(r->buffer + 8, r->cbuf, r->clen);
1303 /* Fix up USB-3 ep0 maxpacket size to allow superspeed connected devices
1304 * to work redirected to a not superspeed capable hcd */
1305 if ((udev->speedmask & USB_SPEED_MASK_SUPER) &&
1306 !(udev->port->speedmask & USB_SPEED_MASK_SUPER) &&
1307 request == 0x8006 && value == 0x100 && index == 0) {
1308 r->usb3ep0quirk = true;
1311 libusb_fill_control_transfer(r->xfer, s->dh, r->buffer,
1312 usb_host_req_complete_ctrl, r,
1313 CONTROL_TIMEOUT);
1314 rc = libusb_submit_transfer(r->xfer);
1315 if (rc != 0) {
1316 p->status = USB_RET_NODEV;
1317 trace_usb_host_req_complete(s->bus_num, s->addr, p,
1318 p->status, p->actual_length);
1319 if (rc == LIBUSB_ERROR_NO_DEVICE) {
1320 usb_host_nodev(s);
1322 return;
1325 p->status = USB_RET_ASYNC;
1328 static void usb_host_handle_data(USBDevice *udev, USBPacket *p)
1330 USBHostDevice *s = USB_HOST_DEVICE(udev);
1331 USBHostRequest *r;
1332 size_t size;
1333 int ep, rc;
1335 if (usb_host_use_combining(p->ep) && p->state == USB_PACKET_SETUP) {
1336 p->status = USB_RET_ADD_TO_QUEUE;
1337 return;
1340 trace_usb_host_req_data(s->bus_num, s->addr, p,
1341 p->pid == USB_TOKEN_IN,
1342 p->ep->nr, p->iov.size);
1344 if (s->dh == NULL) {
1345 p->status = USB_RET_NODEV;
1346 trace_usb_host_req_emulated(s->bus_num, s->addr, p, p->status);
1347 return;
1349 if (p->ep->halted) {
1350 p->status = USB_RET_STALL;
1351 trace_usb_host_req_emulated(s->bus_num, s->addr, p, p->status);
1352 return;
1355 switch (usb_ep_get_type(udev, p->pid, p->ep->nr)) {
1356 case USB_ENDPOINT_XFER_BULK:
1357 size = usb_packet_size(p);
1358 r = usb_host_req_alloc(s, p, p->pid == USB_TOKEN_IN, size);
1359 if (!r->in) {
1360 usb_packet_copy(p, r->buffer, size);
1362 ep = p->ep->nr | (r->in ? USB_DIR_IN : 0);
1363 if (p->stream) {
1364 #ifdef HAVE_STREAMS
1365 libusb_fill_bulk_stream_transfer(r->xfer, s->dh, ep, p->stream,
1366 r->buffer, size,
1367 usb_host_req_complete_data, r,
1368 BULK_TIMEOUT);
1369 #else
1370 usb_host_req_free(r);
1371 p->status = USB_RET_STALL;
1372 return;
1373 #endif
1374 } else {
1375 libusb_fill_bulk_transfer(r->xfer, s->dh, ep,
1376 r->buffer, size,
1377 usb_host_req_complete_data, r,
1378 BULK_TIMEOUT);
1380 break;
1381 case USB_ENDPOINT_XFER_INT:
1382 r = usb_host_req_alloc(s, p, p->pid == USB_TOKEN_IN, p->iov.size);
1383 if (!r->in) {
1384 usb_packet_copy(p, r->buffer, p->iov.size);
1386 ep = p->ep->nr | (r->in ? USB_DIR_IN : 0);
1387 libusb_fill_interrupt_transfer(r->xfer, s->dh, ep,
1388 r->buffer, p->iov.size,
1389 usb_host_req_complete_data, r,
1390 INTR_TIMEOUT);
1391 break;
1392 case USB_ENDPOINT_XFER_ISOC:
1393 if (p->pid == USB_TOKEN_IN) {
1394 usb_host_iso_data_in(s, p);
1395 } else {
1396 usb_host_iso_data_out(s, p);
1398 trace_usb_host_req_complete(s->bus_num, s->addr, p,
1399 p->status, p->actual_length);
1400 return;
1401 default:
1402 p->status = USB_RET_STALL;
1403 trace_usb_host_req_complete(s->bus_num, s->addr, p,
1404 p->status, p->actual_length);
1405 return;
1408 rc = libusb_submit_transfer(r->xfer);
1409 if (rc != 0) {
1410 p->status = USB_RET_NODEV;
1411 trace_usb_host_req_complete(s->bus_num, s->addr, p,
1412 p->status, p->actual_length);
1413 if (rc == LIBUSB_ERROR_NO_DEVICE) {
1414 usb_host_nodev(s);
1416 return;
1419 p->status = USB_RET_ASYNC;
1422 static void usb_host_flush_ep_queue(USBDevice *dev, USBEndpoint *ep)
1424 if (usb_host_use_combining(ep)) {
1425 usb_ep_combine_input_packets(ep);
1429 static void usb_host_handle_reset(USBDevice *udev)
1431 USBHostDevice *s = USB_HOST_DEVICE(udev);
1432 int rc;
1434 trace_usb_host_reset(s->bus_num, s->addr);
1436 rc = libusb_reset_device(s->dh);
1437 if (rc != 0) {
1438 usb_host_nodev(s);
1442 static int usb_host_alloc_streams(USBDevice *udev, USBEndpoint **eps,
1443 int nr_eps, int streams)
1445 #ifdef HAVE_STREAMS
1446 USBHostDevice *s = USB_HOST_DEVICE(udev);
1447 unsigned char endpoints[30];
1448 int i, rc;
1450 for (i = 0; i < nr_eps; i++) {
1451 endpoints[i] = eps[i]->nr;
1452 if (eps[i]->pid == USB_TOKEN_IN) {
1453 endpoints[i] |= 0x80;
1456 rc = libusb_alloc_streams(s->dh, streams, endpoints, nr_eps);
1457 if (rc < 0) {
1458 usb_host_libusb_error("libusb_alloc_streams", rc);
1459 } else if (rc != streams) {
1460 error_report("libusb_alloc_streams: got less streams "
1461 "then requested %d < %d", rc, streams);
1464 return (rc == streams) ? 0 : -1;
1465 #else
1466 error_report("libusb_alloc_streams: error not implemented");
1467 return -1;
1468 #endif
1471 static void usb_host_free_streams(USBDevice *udev, USBEndpoint **eps,
1472 int nr_eps)
1474 #ifdef HAVE_STREAMS
1475 USBHostDevice *s = USB_HOST_DEVICE(udev);
1476 unsigned char endpoints[30];
1477 int i;
1479 for (i = 0; i < nr_eps; i++) {
1480 endpoints[i] = eps[i]->nr;
1481 if (eps[i]->pid == USB_TOKEN_IN) {
1482 endpoints[i] |= 0x80;
1485 libusb_free_streams(s->dh, endpoints, nr_eps);
1486 #endif
1490 * This is *NOT* about restoring state. We have absolutely no idea
1491 * what state the host device is in at the moment and whenever it is
1492 * still present in the first place. Attemping to contine where we
1493 * left off is impossible.
1495 * What we are going to do here is emulate a surprise removal of
1496 * the usb device passed through, then kick host scan so the device
1497 * will get re-attached (and re-initialized by the guest) in case it
1498 * is still present.
1500 * As the device removal will change the state of other devices (usb
1501 * host controller, most likely interrupt controller too) we have to
1502 * wait with it until *all* vmstate is loaded. Thus post_load just
1503 * kicks a bottom half which then does the actual work.
1505 static void usb_host_post_load_bh(void *opaque)
1507 USBHostDevice *dev = opaque;
1508 USBDevice *udev = USB_DEVICE(dev);
1510 if (dev->dh != NULL) {
1511 usb_host_close(dev);
1513 if (udev->attached) {
1514 usb_device_detach(udev);
1516 usb_host_auto_check(NULL);
1519 static int usb_host_post_load(void *opaque, int version_id)
1521 USBHostDevice *dev = opaque;
1523 if (!dev->bh_postld) {
1524 dev->bh_postld = qemu_bh_new(usb_host_post_load_bh, dev);
1526 qemu_bh_schedule(dev->bh_postld);
1527 return 0;
1530 static const VMStateDescription vmstate_usb_host = {
1531 .name = "usb-host",
1532 .version_id = 1,
1533 .minimum_version_id = 1,
1534 .post_load = usb_host_post_load,
1535 .fields = (VMStateField[]) {
1536 VMSTATE_USB_DEVICE(parent_obj, USBHostDevice),
1537 VMSTATE_END_OF_LIST()
1541 static Property usb_host_dev_properties[] = {
1542 DEFINE_PROP_UINT32("hostbus", USBHostDevice, match.bus_num, 0),
1543 DEFINE_PROP_UINT32("hostaddr", USBHostDevice, match.addr, 0),
1544 DEFINE_PROP_STRING("hostport", USBHostDevice, match.port),
1545 DEFINE_PROP_UINT32("vendorid", USBHostDevice, match.vendor_id, 0),
1546 DEFINE_PROP_UINT32("productid", USBHostDevice, match.product_id, 0),
1547 DEFINE_PROP_UINT32("isobufs", USBHostDevice, iso_urb_count, 4),
1548 DEFINE_PROP_UINT32("isobsize", USBHostDevice, iso_urb_frames, 32),
1549 DEFINE_PROP_UINT32("loglevel", USBHostDevice, loglevel,
1550 LIBUSB_LOG_LEVEL_WARNING),
1551 DEFINE_PROP_BIT("pipeline", USBHostDevice, options,
1552 USB_HOST_OPT_PIPELINE, true),
1553 DEFINE_PROP_END_OF_LIST(),
1556 static void usb_host_class_initfn(ObjectClass *klass, void *data)
1558 DeviceClass *dc = DEVICE_CLASS(klass);
1559 USBDeviceClass *uc = USB_DEVICE_CLASS(klass);
1561 uc->realize = usb_host_realize;
1562 uc->product_desc = "USB Host Device";
1563 uc->cancel_packet = usb_host_cancel_packet;
1564 uc->handle_data = usb_host_handle_data;
1565 uc->handle_control = usb_host_handle_control;
1566 uc->handle_reset = usb_host_handle_reset;
1567 uc->handle_destroy = usb_host_handle_destroy;
1568 uc->flush_ep_queue = usb_host_flush_ep_queue;
1569 uc->alloc_streams = usb_host_alloc_streams;
1570 uc->free_streams = usb_host_free_streams;
1571 dc->vmsd = &vmstate_usb_host;
1572 dc->props = usb_host_dev_properties;
1573 set_bit(DEVICE_CATEGORY_BRIDGE, dc->categories);
1576 static TypeInfo usb_host_dev_info = {
1577 .name = TYPE_USB_HOST_DEVICE,
1578 .parent = TYPE_USB_DEVICE,
1579 .instance_size = sizeof(USBHostDevice),
1580 .class_init = usb_host_class_initfn,
1581 .instance_init = usb_host_instance_init,
1584 static void usb_host_register_types(void)
1586 type_register_static(&usb_host_dev_info);
1589 type_init(usb_host_register_types)
1591 /* ------------------------------------------------------------------------ */
1593 static QEMUTimer *usb_auto_timer;
1594 static VMChangeStateEntry *usb_vmstate;
1596 static void usb_host_vm_state(void *unused, int running, RunState state)
1598 if (running) {
1599 usb_host_auto_check(unused);
1603 static void usb_host_auto_check(void *unused)
1605 struct USBHostDevice *s;
1606 struct USBAutoFilter *f;
1607 libusb_device **devs = NULL;
1608 struct libusb_device_descriptor ddesc;
1609 int unconnected = 0;
1610 int i, n;
1612 if (usb_host_init() != 0) {
1613 return;
1616 if (runstate_is_running()) {
1617 n = libusb_get_device_list(ctx, &devs);
1618 for (i = 0; i < n; i++) {
1619 if (libusb_get_device_descriptor(devs[i], &ddesc) != 0) {
1620 continue;
1622 if (ddesc.bDeviceClass == LIBUSB_CLASS_HUB) {
1623 continue;
1625 QTAILQ_FOREACH(s, &hostdevs, next) {
1626 f = &s->match;
1627 if (f->bus_num > 0 &&
1628 f->bus_num != libusb_get_bus_number(devs[i])) {
1629 continue;
1631 if (f->addr > 0 &&
1632 f->addr != libusb_get_device_address(devs[i])) {
1633 continue;
1635 if (f->port != NULL) {
1636 char port[16] = "-";
1637 usb_host_get_port(devs[i], port, sizeof(port));
1638 if (strcmp(f->port, port) != 0) {
1639 continue;
1642 if (f->vendor_id > 0 &&
1643 f->vendor_id != ddesc.idVendor) {
1644 continue;
1646 if (f->product_id > 0 &&
1647 f->product_id != ddesc.idProduct) {
1648 continue;
1651 /* We got a match */
1652 s->seen++;
1653 if (s->errcount >= 3) {
1654 continue;
1656 if (s->dh != NULL) {
1657 continue;
1659 if (usb_host_open(s, devs[i]) < 0) {
1660 s->errcount++;
1661 continue;
1663 break;
1666 libusb_free_device_list(devs, 1);
1668 QTAILQ_FOREACH(s, &hostdevs, next) {
1669 if (s->dh == NULL) {
1670 unconnected++;
1672 if (s->seen == 0) {
1673 if (s->dh) {
1674 usb_host_close(s);
1676 s->errcount = 0;
1678 s->seen = 0;
1681 #if 0
1682 if (unconnected == 0) {
1683 /* nothing to watch */
1684 if (usb_auto_timer) {
1685 timer_del(usb_auto_timer);
1686 trace_usb_host_auto_scan_disabled();
1688 return;
1690 #endif
1693 if (!usb_vmstate) {
1694 usb_vmstate = qemu_add_vm_change_state_handler(usb_host_vm_state, NULL);
1696 if (!usb_auto_timer) {
1697 usb_auto_timer = timer_new_ms(QEMU_CLOCK_REALTIME, usb_host_auto_check, NULL);
1698 if (!usb_auto_timer) {
1699 return;
1701 trace_usb_host_auto_scan_enabled();
1703 timer_mod(usb_auto_timer, qemu_clock_get_ms(QEMU_CLOCK_REALTIME) + 2000);
1706 void hmp_info_usbhost(Monitor *mon, const QDict *qdict)
1708 libusb_device **devs = NULL;
1709 struct libusb_device_descriptor ddesc;
1710 char port[16];
1711 int i, n;
1713 if (usb_host_init() != 0) {
1714 return;
1717 n = libusb_get_device_list(ctx, &devs);
1718 for (i = 0; i < n; i++) {
1719 if (libusb_get_device_descriptor(devs[i], &ddesc) != 0) {
1720 continue;
1722 if (ddesc.bDeviceClass == LIBUSB_CLASS_HUB) {
1723 continue;
1725 usb_host_get_port(devs[i], port, sizeof(port));
1726 monitor_printf(mon, " Bus %d, Addr %d, Port %s, Speed %s Mb/s\n",
1727 libusb_get_bus_number(devs[i]),
1728 libusb_get_device_address(devs[i]),
1729 port,
1730 speed_name[libusb_get_device_speed(devs[i])]);
1731 monitor_printf(mon, " Class %02x:", ddesc.bDeviceClass);
1732 monitor_printf(mon, " USB device %04x:%04x",
1733 ddesc.idVendor, ddesc.idProduct);
1734 if (ddesc.iProduct) {
1735 libusb_device_handle *handle;
1736 if (libusb_open(devs[i], &handle) == 0) {
1737 unsigned char name[64] = "";
1738 libusb_get_string_descriptor_ascii(handle,
1739 ddesc.iProduct,
1740 name, sizeof(name));
1741 libusb_close(handle);
1742 monitor_printf(mon, ", %s", name);
1745 monitor_printf(mon, "\n");
1747 libusb_free_device_list(devs, 1);