scripts/kvm/kvm_stat: Improve debugfs access checking
[qemu.git] / hw / usb / host-libusb.c
blob3f8e540bd2959185de396b580f476e382b90817a
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 <poll.h>
37 #include <libusb.h>
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"
45 #include "hw/usb.h"
47 /* ------------------------------------------------------------------------ */
49 #define TYPE_USB_HOST_DEVICE "usb-host"
50 #define USB_HOST_DEVICE(obj) \
51 OBJECT_CHECK(USBHostDevice, (obj), TYPE_USB_HOST_DEVICE)
53 typedef struct USBHostDevice USBHostDevice;
54 typedef struct USBHostRequest USBHostRequest;
55 typedef struct USBHostIsoXfer USBHostIsoXfer;
56 typedef struct USBHostIsoRing USBHostIsoRing;
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;
66 enum USBHostDeviceOptions {
67 USB_HOST_OPT_PIPELINE,
70 struct USBHostDevice {
71 USBDevice parent_obj;
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;
81 /* state */
82 QTAILQ_ENTRY(USBHostDevice) next;
83 int seen, errcount;
84 int bus_num;
85 int addr;
86 char port[16];
88 libusb_device *dev;
89 libusb_device_handle *dh;
90 struct libusb_device_descriptor ddesc;
92 struct {
93 bool detached;
94 bool claimed;
95 } ifs[USB_MAX_INTERFACES];
97 /* callbacks & friends */
98 QEMUBH *bh_nodev;
99 QEMUBH *bh_postld;
100 Notifier exit;
102 /* request queues */
103 QTAILQ_HEAD(, USBHostRequest) requests;
104 QTAILQ_HEAD(, USBHostIsoRing) isorings;
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;
119 struct USBHostIsoXfer {
120 USBHostIsoRing *ring;
121 struct libusb_transfer *xfer;
122 bool copy_complete;
123 unsigned int packet;
124 QTAILQ_ENTRY(USBHostIsoXfer) next;
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;
136 static QTAILQ_HEAD(, USBHostDevice) hostdevs =
137 QTAILQ_HEAD_INITIALIZER(hostdevs);
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);
145 /* ------------------------------------------------------------------------ */
147 #ifndef LIBUSB_LOG_LEVEL_WARNING /* older libusb didn't define these */
148 #define LIBUSB_LOG_LEVEL_WARNING 2
149 #endif
151 /* ------------------------------------------------------------------------ */
153 #define CONTROL_TIMEOUT 10000 /* 10 sec */
154 #define BULK_TIMEOUT 0 /* unlimited */
155 #define INTR_TIMEOUT 0 /* unlimited */
157 #if LIBUSBX_API_VERSION >= 0x01000103
158 # define HAVE_STREAMS 1
159 #endif
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",
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,
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,
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",
202 static libusb_context *ctx;
203 static uint32_t loglevel;
205 static void usb_host_handle_fd(void *opaque)
207 struct timeval tv = { 0, 0 };
208 libusb_handle_events_timeout(ctx, &tv);
211 static void usb_host_add_fd(int fd, short events, void *user_data)
213 qemu_set_fd_handler(fd,
214 (events & POLLIN) ? usb_host_handle_fd : NULL,
215 (events & POLLOUT) ? usb_host_handle_fd : NULL,
216 ctx);
219 static void usb_host_del_fd(int fd, void *user_data)
221 qemu_set_fd_handler(fd, NULL, NULL, NULL);
224 static int usb_host_init(void)
226 const struct libusb_pollfd **poll;
227 int i, rc;
229 if (ctx) {
230 return 0;
232 rc = libusb_init(&ctx);
233 if (rc != 0) {
234 return -1;
236 libusb_set_debug(ctx, loglevel);
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);
247 free(poll);
248 return 0;
251 static int usb_host_get_port(libusb_device *dev, char *port, size_t len)
253 uint8_t path[7];
254 size_t off;
255 int rc, i;
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;
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]);
269 return off;
272 static void usb_host_libusb_error(const char *func, int rc)
274 const char *errname;
276 if (rc >= 0) {
277 return;
280 if (-rc < ARRAY_SIZE(err_names) && err_names[-rc]) {
281 errname = err_names[-rc];
282 } else {
283 errname = "?";
285 error_report("%s: %d [%s]", func, rc, errname);
288 /* ------------------------------------------------------------------------ */
290 static bool usb_host_use_combining(USBEndpoint *ep)
292 int type;
294 if (!ep->pipeline) {
295 return false;
297 if (ep->pid != USB_TOKEN_IN) {
298 return false;
300 type = usb_ep_get_type(ep->dev, ep->pid, ep->nr);
301 if (type != USB_ENDPOINT_XFER_BULK) {
302 return false;
304 return true;
307 /* ------------------------------------------------------------------------ */
309 static USBHostRequest *usb_host_req_alloc(USBHostDevice *s, USBPacket *p,
310 bool in, size_t bufsize)
312 USBHostRequest *r = g_new0(USBHostRequest, 1);
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);
321 QTAILQ_INSERT_TAIL(&s->requests, r, next);
322 return r;
325 static void usb_host_req_free(USBHostRequest *r)
327 if (r->host) {
328 QTAILQ_REMOVE(&r->host->requests, r, next);
330 libusb_free_transfer(r->xfer);
331 g_free(r->buffer);
332 g_free(r);
335 static USBHostRequest *usb_host_req_find(USBHostDevice *s, USBPacket *p)
337 USBHostRequest *r;
339 QTAILQ_FOREACH(r, &s->requests, next) {
340 if (r->p == p) {
341 return r;
344 return NULL;
347 static void usb_host_req_complete_ctrl(struct libusb_transfer *xfer)
349 USBHostRequest *r = xfer->user_data;
350 USBHostDevice *s = r->host;
351 bool disconnect = (xfer->status == LIBUSB_TRANSFER_NO_DEVICE);
353 if (r->p == NULL) {
354 goto out; /* request was canceled */
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);
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;
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);
373 out:
374 usb_host_req_free(r);
375 if (disconnect) {
376 usb_host_nodev(s);
380 static void usb_host_req_complete_data(struct libusb_transfer *xfer)
382 USBHostRequest *r = xfer->user_data;
383 USBHostDevice *s = r->host;
384 bool disconnect = (xfer->status == LIBUSB_TRANSFER_NO_DEVICE);
386 if (r->p == NULL) {
387 goto out; /* request was canceled */
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);
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);
402 out:
403 usb_host_req_free(r);
404 if (disconnect) {
405 usb_host_nodev(s);
409 static void usb_host_req_abort(USBHostRequest *r)
411 USBHostDevice *s = r->host;
412 bool inflight = (r->p && r->p->state == USB_PACKET_ASYNC);
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);
423 r->p = NULL;
426 QTAILQ_REMOVE(&r->host->requests, r, next);
427 r->host = NULL;
429 if (inflight) {
430 libusb_cancel_transfer(r->xfer);
434 /* ------------------------------------------------------------------------ */
436 static void usb_host_req_complete_iso(struct libusb_transfer *transfer)
438 USBHostIsoXfer *xfer = transfer->user_data;
440 if (!xfer) {
441 /* USBHostIsoXfer released while inflight */
442 g_free(transfer->buffer);
443 libusb_free_transfer(transfer);
444 return;
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);
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);
460 static USBHostIsoRing *usb_host_iso_alloc(USBHostDevice *s, USBEndpoint *ep)
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;
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);
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;
482 xfer->xfer->endpoint = ring->ep->nr;
483 if (ring->ep->pid == USB_TOKEN_IN) {
484 xfer->xfer->endpoint |= USB_DIR_IN;
486 xfer->xfer->callback = usb_host_req_complete_iso;
487 xfer->xfer->user_data = xfer;
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);
493 QTAILQ_INSERT_TAIL(&ring->unused, xfer, next);
496 return ring;
499 static USBHostIsoRing *usb_host_iso_find(USBHostDevice *s, USBEndpoint *ep)
501 USBHostIsoRing *ring;
503 QTAILQ_FOREACH(ring, &s->isorings, next) {
504 if (ring->ep == ep) {
505 return ring;
508 return NULL;
511 static void usb_host_iso_reset_xfer(USBHostIsoXfer *xfer)
513 libusb_set_iso_packet_lengths(xfer->xfer,
514 xfer->ring->ep->max_packet_size);
515 xfer->packet = 0;
516 xfer->copy_complete = false;
519 static void usb_host_iso_free_xfer(USBHostIsoXfer *xfer, bool inflight)
521 if (inflight) {
522 xfer->xfer->user_data = NULL;
523 } else {
524 g_free(xfer->xfer->buffer);
525 libusb_free_transfer(xfer->xfer);
527 g_free(xfer);
530 static void usb_host_iso_free(USBHostIsoRing *ring)
532 USBHostIsoXfer *xfer;
534 while ((xfer = QTAILQ_FIRST(&ring->inflight)) != NULL) {
535 QTAILQ_REMOVE(&ring->inflight, xfer, next);
536 usb_host_iso_free_xfer(xfer, true);
538 while ((xfer = QTAILQ_FIRST(&ring->unused)) != NULL) {
539 QTAILQ_REMOVE(&ring->unused, xfer, next);
540 usb_host_iso_free_xfer(xfer, false);
542 while ((xfer = QTAILQ_FIRST(&ring->copy)) != NULL) {
543 QTAILQ_REMOVE(&ring->copy, xfer, next);
544 usb_host_iso_free_xfer(xfer, false);
547 QTAILQ_REMOVE(&ring->host->isorings, ring, next);
548 g_free(ring);
551 static void usb_host_iso_free_all(USBHostDevice *s)
553 USBHostIsoRing *ring;
555 while ((ring = QTAILQ_FIRST(&s->isorings)) != NULL) {
556 usb_host_iso_free(ring);
560 static bool usb_host_iso_data_copy(USBHostIsoXfer *xfer, USBPacket *p)
562 unsigned int psize;
563 unsigned char *buf;
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;
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;
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;
586 static void usb_host_iso_data_in(USBHostDevice *s, USBPacket *p)
588 USBHostIsoRing *ring;
589 USBHostIsoXfer *xfer;
590 bool disconnect = false;
591 int rc;
593 ring = usb_host_iso_find(s, p->ep);
594 if (ring == NULL) {
595 ring = usb_host_iso_alloc(s, p->ep);
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);
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;
618 break;
620 if (QTAILQ_EMPTY(&ring->inflight)) {
621 trace_usb_host_iso_start(s->bus_num, s->addr, p->ep->nr);
623 QTAILQ_INSERT_TAIL(&ring->inflight, xfer, next);
626 if (disconnect) {
627 usb_host_nodev(s);
631 static void usb_host_iso_data_out(USBHostDevice *s, USBPacket *p)
633 USBHostIsoRing *ring;
634 USBHostIsoXfer *xfer;
635 bool disconnect = false;
636 int rc, filled = 0;
638 ring = usb_host_iso_find(s, p->ep);
639 if (ring == NULL) {
640 ring = usb_host_iso_alloc(s, p->ep);
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);
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;
655 QTAILQ_REMOVE(&ring->unused, xfer, next);
656 usb_host_iso_reset_xfer(xfer);
657 QTAILQ_INSERT_TAIL(&ring->copy, xfer, next);
659 usb_host_iso_data_copy(xfer, p);
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;
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;
680 break;
682 if (QTAILQ_EMPTY(&ring->inflight)) {
683 trace_usb_host_iso_start(s->bus_num, s->addr, p->ep->nr);
685 QTAILQ_INSERT_TAIL(&ring->inflight, xfer, next);
688 if (disconnect) {
689 usb_host_nodev(s);
693 /* ------------------------------------------------------------------------ */
695 static void usb_host_speed_compat(USBHostDevice *s)
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;
709 for (c = 0;; c++) {
710 rc = libusb_get_config_descriptor(s->dev, c, &conf);
711 if (rc != 0) {
712 break;
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;
735 #endif
736 break;
737 case 0x03: /* INTERRUPT */
738 if (endp->wMaxPacketSize > 64) {
739 compat_full = false;
741 if (endp->wMaxPacketSize > 1024) {
742 compat_high = false;
744 break;
749 libusb_free_config_descriptor(conf);
752 udev->speedmask = (1 << udev->speed);
753 if (udev->speed == USB_SPEED_SUPER && compat_high) {
754 udev->speedmask |= USB_SPEED_MASK_HIGH;
756 if (udev->speed == USB_SPEED_SUPER && compat_full) {
757 udev->speedmask |= USB_SPEED_MASK_FULL;
759 if (udev->speed == USB_SPEED_HIGH && compat_full) {
760 udev->speedmask |= USB_SPEED_MASK_FULL;
764 static void usb_host_ep_update(USBHostDevice *s)
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",
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;
783 usb_ep_reset(udev);
784 rc = libusb_get_active_config_descriptor(s->dev, &conf);
785 if (rc != 0) {
786 return;
788 trace_usb_host_parse_config(s->bus_num, s->addr,
789 conf->bConfigurationValue, true);
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];
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;
805 if (ep == 0) {
806 trace_usb_host_parse_error(s->bus_num, s->addr,
807 "invalid endpoint address");
808 return;
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;
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);
832 #endif
836 libusb_free_config_descriptor(conf);
839 static int usb_host_open(USBHostDevice *s, libusb_device *dev)
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;
847 trace_usb_host_open_started(bus_num, addr);
849 if (s->dh != NULL) {
850 goto fail;
852 rc = libusb_open(dev, &s->dh);
853 if (rc != 0) {
854 goto fail;
857 s->dev = dev;
858 s->bus_num = bus_num;
859 s->addr = addr;
861 usb_host_detach_kernel(s);
863 libusb_get_device_descriptor(dev, &s->ddesc);
864 usb_host_get_port(s->dev, s->port, sizeof(s->port));
866 usb_ep_init(udev);
867 usb_host_ep_update(s);
869 udev->speed = speed_map[libusb_get_device_speed(dev)];
870 usb_host_speed_compat(s);
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);
881 usb_device_attach(udev, &local_err);
882 if (local_err) {
883 error_report_err(local_err);
884 goto fail;
887 trace_usb_host_open_success(bus_num, addr);
888 return 0;
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;
900 return -1;
903 static void usb_host_abort_xfers(USBHostDevice *s)
905 USBHostRequest *r, *rtmp;
907 QTAILQ_FOREACH_SAFE(r, &s->requests, next, rtmp) {
908 usb_host_req_abort(r);
912 static int usb_host_close(USBHostDevice *s)
914 USBDevice *udev = USB_DEVICE(s);
916 if (s->dh == NULL) {
917 return -1;
920 trace_usb_host_close(s->bus_num, s->addr);
922 usb_host_abort_xfers(s);
923 usb_host_iso_free_all(s);
925 if (udev->attached) {
926 usb_device_detach(udev);
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;
936 usb_host_auto_check(NULL);
937 return 0;
940 static void usb_host_nodev_bh(void *opaque)
942 USBHostDevice *s = opaque;
943 usb_host_close(s);
946 static void usb_host_nodev(USBHostDevice *s)
948 if (!s->bh_nodev) {
949 s->bh_nodev = qemu_bh_new(usb_host_nodev_bh, s);
951 qemu_bh_schedule(s->bh_nodev);
954 static void usb_host_exit_notifier(struct Notifier *n, void *data)
956 USBHostDevice *s = container_of(n, USBHostDevice, exit);
958 if (s->dh) {
959 usb_host_release_interfaces(s);
960 usb_host_attach_kernel(s);
964 static void usb_host_realize(USBDevice *udev, Error **errp)
966 USBHostDevice *s = USB_HOST_DEVICE(udev);
968 if (s->match.vendor_id > 0xffff) {
969 error_setg(errp, "vendorid out of range");
970 return;
972 if (s->match.product_id > 0xffff) {
973 error_setg(errp, "productid out of range");
974 return;
976 if (s->match.addr > 127) {
977 error_setg(errp, "hostaddr out of range");
978 return;
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);
987 s->exit.notify = usb_host_exit_notifier;
988 qemu_add_exit_notifier(&s->exit);
990 QTAILQ_INSERT_TAIL(&hostdevs, s, next);
991 usb_host_auto_check(NULL);
994 static void usb_host_instance_init(Object *obj)
996 USBDevice *udev = USB_DEVICE(obj);
997 USBHostDevice *s = USB_HOST_DEVICE(udev);
999 device_add_bootindex_property(obj, &s->bootindex,
1000 "bootindex", NULL,
1001 &udev->qdev, NULL);
1004 static void usb_host_handle_destroy(USBDevice *udev)
1006 USBHostDevice *s = USB_HOST_DEVICE(udev);
1008 qemu_remove_exit_notifier(&s->exit);
1009 QTAILQ_REMOVE(&hostdevs, s, next);
1010 usb_host_close(s);
1013 static void usb_host_cancel_packet(USBDevice *udev, USBPacket *p)
1015 USBHostDevice *s = USB_HOST_DEVICE(udev);
1016 USBHostRequest *r;
1018 if (p->combined) {
1019 usb_combined_packet_cancel(udev, p);
1020 return;
1023 trace_usb_host_req_canceled(s->bus_num, s->addr, p);
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);
1032 static void usb_host_detach_kernel(USBHostDevice *s)
1034 struct libusb_config_descriptor *conf;
1035 int rc, i;
1037 rc = libusb_get_active_config_descriptor(s->dev, &conf);
1038 if (rc != 0) {
1039 return;
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;
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;
1052 libusb_free_config_descriptor(conf);
1055 static void usb_host_attach_kernel(USBHostDevice *s)
1057 struct libusb_config_descriptor *conf;
1058 int rc, i;
1060 rc = libusb_get_active_config_descriptor(s->dev, &conf);
1061 if (rc != 0) {
1062 return;
1064 for (i = 0; i < conf->bNumInterfaces; i++) {
1065 if (!s->ifs[i].detached) {
1066 continue;
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;
1072 libusb_free_config_descriptor(conf);
1075 static int usb_host_claim_interfaces(USBHostDevice *s, int configuration)
1077 USBDevice *udev = USB_DEVICE(s);
1078 struct libusb_config_descriptor *conf;
1079 int rc, i;
1081 for (i = 0; i < USB_MAX_INTERFACES; i++) {
1082 udev->altsetting[i] = 0;
1084 udev->ninterfaces = 0;
1085 udev->configuration = 0;
1087 usb_host_detach_kernel(s);
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;
1095 return USB_RET_STALL;
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;
1105 s->ifs[i].claimed = true;
1108 udev->ninterfaces = conf->bNumInterfaces;
1109 udev->configuration = configuration;
1111 libusb_free_config_descriptor(conf);
1112 return USB_RET_SUCCESS;
1115 static void usb_host_release_interfaces(USBHostDevice *s)
1117 USBDevice *udev = USB_DEVICE(s);
1118 int i, rc;
1120 for (i = 0; i < udev->ninterfaces; i++) {
1121 if (!s->ifs[i].claimed) {
1122 continue;
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;
1131 static void usb_host_set_address(USBHostDevice *s, int addr)
1133 USBDevice *udev = USB_DEVICE(s);
1135 trace_usb_host_set_address(s->bus_num, s->addr, addr);
1136 udev->addr = addr;
1139 static void usb_host_set_config(USBHostDevice *s, int config, USBPacket *p)
1141 int rc;
1143 trace_usb_host_set_config(s->bus_num, s->addr, config);
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);
1153 return;
1155 p->status = usb_host_claim_interfaces(s, config);
1156 if (p->status != USB_RET_SUCCESS) {
1157 return;
1159 usb_host_ep_update(s);
1162 static void usb_host_set_interface(USBHostDevice *s, int iface, int alt,
1163 USBPacket *p)
1165 USBDevice *udev = USB_DEVICE(s);
1166 int rc;
1168 trace_usb_host_set_interface(s->bus_num, s->addr, iface, alt);
1170 usb_host_iso_free_all(s);
1172 if (iface >= USB_MAX_INTERFACES) {
1173 p->status = USB_RET_STALL;
1174 return;
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);
1184 return;
1187 udev->altsetting[iface] = alt;
1188 usb_host_ep_update(s);
1191 static void usb_host_handle_control(USBDevice *udev, USBPacket *p,
1192 int request, int value, int index,
1193 int length, uint8_t *data)
1195 USBHostDevice *s = USB_HOST_DEVICE(udev);
1196 USBHostRequest *r;
1197 int rc;
1199 trace_usb_host_req_control(s->bus_num, s->addr, p, request, value, index);
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;
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;
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;
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;
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;
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);
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;
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);
1260 return;
1263 p->status = USB_RET_ASYNC;
1266 static void usb_host_handle_data(USBDevice *udev, USBPacket *p)
1268 USBHostDevice *s = USB_HOST_DEVICE(udev);
1269 USBHostRequest *r;
1270 size_t size;
1271 int ep, rc;
1273 if (usb_host_use_combining(p->ep) && p->state == USB_PACKET_SETUP) {
1274 p->status = USB_RET_ADD_TO_QUEUE;
1275 return;
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);
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;
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;
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);
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);
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);
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);
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;
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);
1354 return;
1357 p->status = USB_RET_ASYNC;
1360 static void usb_host_flush_ep_queue(USBDevice *dev, USBEndpoint *ep)
1362 if (usb_host_use_combining(ep)) {
1363 usb_ep_combine_input_packets(ep);
1367 static void usb_host_handle_reset(USBDevice *udev)
1369 USBHostDevice *s = USB_HOST_DEVICE(udev);
1370 int rc;
1372 trace_usb_host_reset(s->bus_num, s->addr);
1374 rc = libusb_reset_device(s->dh);
1375 if (rc != 0) {
1376 usb_host_nodev(s);
1380 static int usb_host_alloc_streams(USBDevice *udev, USBEndpoint **eps,
1381 int nr_eps, int streams)
1383 #ifdef HAVE_STREAMS
1384 USBHostDevice *s = USB_HOST_DEVICE(udev);
1385 unsigned char endpoints[30];
1386 int i, rc;
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;
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);
1402 return (rc == streams) ? 0 : -1;
1403 #else
1404 error_report("libusb_alloc_streams: error not implemented");
1405 return -1;
1406 #endif
1409 static void usb_host_free_streams(USBDevice *udev, USBEndpoint **eps,
1410 int nr_eps)
1412 #ifdef HAVE_STREAMS
1413 USBHostDevice *s = USB_HOST_DEVICE(udev);
1414 unsigned char endpoints[30];
1415 int i;
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;
1423 libusb_free_streams(s->dh, endpoints, nr_eps);
1424 #endif
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.
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.
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.
1443 static void usb_host_post_load_bh(void *opaque)
1445 USBHostDevice *dev = opaque;
1446 USBDevice *udev = USB_DEVICE(dev);
1448 if (dev->dh != NULL) {
1449 usb_host_close(dev);
1451 if (udev->attached) {
1452 usb_device_detach(udev);
1454 usb_host_auto_check(NULL);
1457 static int usb_host_post_load(void *opaque, int version_id)
1459 USBHostDevice *dev = opaque;
1461 if (!dev->bh_postld) {
1462 dev->bh_postld = qemu_bh_new(usb_host_post_load_bh, dev);
1464 qemu_bh_schedule(dev->bh_postld);
1465 return 0;
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()
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(),
1494 static void usb_host_class_initfn(ObjectClass *klass, void *data)
1496 DeviceClass *dc = DEVICE_CLASS(klass);
1497 USBDeviceClass *uc = USB_DEVICE_CLASS(klass);
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);
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,
1522 static void usb_host_register_types(void)
1524 type_register_static(&usb_host_dev_info);
1527 type_init(usb_host_register_types)
1529 /* ------------------------------------------------------------------------ */
1531 static QEMUTimer *usb_auto_timer;
1532 static VMChangeStateEntry *usb_vmstate;
1534 static void usb_host_vm_state(void *unused, int running, RunState state)
1536 if (running) {
1537 usb_host_auto_check(unused);
1541 static void usb_host_auto_check(void *unused)
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;
1550 if (usb_host_init() != 0) {
1551 return;
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;
1560 if (ddesc.bDeviceClass == LIBUSB_CLASS_HUB) {
1561 continue;
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;
1569 if (f->addr > 0 &&
1570 f->addr != libusb_get_device_address(devs[i])) {
1571 continue;
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;
1580 if (f->vendor_id > 0 &&
1581 f->vendor_id != ddesc.idVendor) {
1582 continue;
1584 if (f->product_id > 0 &&
1585 f->product_id != ddesc.idProduct) {
1586 continue;
1589 /* We got a match */
1590 s->seen++;
1591 if (s->errcount >= 3) {
1592 continue;
1594 if (s->dh != NULL) {
1595 continue;
1597 if (usb_host_open(s, devs[i]) < 0) {
1598 s->errcount++;
1599 continue;
1601 break;
1604 libusb_free_device_list(devs, 1);
1606 QTAILQ_FOREACH(s, &hostdevs, next) {
1607 if (s->dh == NULL) {
1608 unconnected++;
1610 if (s->seen == 0) {
1611 if (s->dh) {
1612 usb_host_close(s);
1614 s->errcount = 0;
1616 s->seen = 0;
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();
1626 return;
1628 #endif
1631 if (!usb_vmstate) {
1632 usb_vmstate = qemu_add_vm_change_state_handler(usb_host_vm_state, NULL);
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;
1639 trace_usb_host_auto_scan_enabled();
1641 timer_mod(usb_auto_timer, qemu_clock_get_ms(QEMU_CLOCK_REALTIME) + 2000);
1644 void hmp_info_usbhost(Monitor *mon, const QDict *qdict)
1646 libusb_device **devs = NULL;
1647 struct libusb_device_descriptor ddesc;
1648 char port[16];
1649 int i, n;
1651 if (usb_host_init() != 0) {
1652 return;
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;
1660 if (ddesc.bDeviceClass == LIBUSB_CLASS_HUB) {
1661 continue;
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);
1683 monitor_printf(mon, "\n");
1685 libusb_free_device_list(devs, 1);