include/qemu/osdep.h: Don't include qapi/error.h
[qemu/ar7.git] / hw / usb / host-libusb.c
blob6458a94485accee53bc87428cf1786b68321712c
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 #include <poll.h>
38 #include <libusb.h>
40 #include "qapi/error.h"
41 #include "qemu-common.h"
42 #include "monitor/monitor.h"
43 #include "qemu/error-report.h"
44 #include "sysemu/sysemu.h"
45 #include "trace.h"
47 #include "hw/usb.h"
49 /* ------------------------------------------------------------------------ */
51 #define TYPE_USB_HOST_DEVICE "usb-host"
52 #define USB_HOST_DEVICE(obj) \
53 OBJECT_CHECK(USBHostDevice, (obj), TYPE_USB_HOST_DEVICE)
55 typedef struct USBHostDevice USBHostDevice;
56 typedef struct USBHostRequest USBHostRequest;
57 typedef struct USBHostIsoXfer USBHostIsoXfer;
58 typedef struct USBHostIsoRing USBHostIsoRing;
60 struct USBAutoFilter {
61 uint32_t bus_num;
62 uint32_t addr;
63 char *port;
64 uint32_t vendor_id;
65 uint32_t product_id;
68 enum USBHostDeviceOptions {
69 USB_HOST_OPT_PIPELINE,
72 struct USBHostDevice {
73 USBDevice parent_obj;
75 /* properties */
76 struct USBAutoFilter match;
77 int32_t bootindex;
78 uint32_t iso_urb_count;
79 uint32_t iso_urb_frames;
80 uint32_t options;
81 uint32_t loglevel;
83 /* state */
84 QTAILQ_ENTRY(USBHostDevice) next;
85 int seen, errcount;
86 int bus_num;
87 int addr;
88 char port[16];
90 libusb_device *dev;
91 libusb_device_handle *dh;
92 struct libusb_device_descriptor ddesc;
94 struct {
95 bool detached;
96 bool claimed;
97 } ifs[USB_MAX_INTERFACES];
99 /* callbacks & friends */
100 QEMUBH *bh_nodev;
101 QEMUBH *bh_postld;
102 Notifier exit;
104 /* request queues */
105 QTAILQ_HEAD(, USBHostRequest) requests;
106 QTAILQ_HEAD(, USBHostIsoRing) isorings;
109 struct USBHostRequest {
110 USBHostDevice *host;
111 USBPacket *p;
112 bool in;
113 struct libusb_transfer *xfer;
114 unsigned char *buffer;
115 unsigned char *cbuf;
116 unsigned int clen;
117 bool usb3ep0quirk;
118 QTAILQ_ENTRY(USBHostRequest) next;
121 struct USBHostIsoXfer {
122 USBHostIsoRing *ring;
123 struct libusb_transfer *xfer;
124 bool copy_complete;
125 unsigned int packet;
126 QTAILQ_ENTRY(USBHostIsoXfer) next;
129 struct USBHostIsoRing {
130 USBHostDevice *host;
131 USBEndpoint *ep;
132 QTAILQ_HEAD(, USBHostIsoXfer) unused;
133 QTAILQ_HEAD(, USBHostIsoXfer) inflight;
134 QTAILQ_HEAD(, USBHostIsoXfer) copy;
135 QTAILQ_ENTRY(USBHostIsoRing) next;
138 static QTAILQ_HEAD(, USBHostDevice) hostdevs =
139 QTAILQ_HEAD_INITIALIZER(hostdevs);
141 static void usb_host_auto_check(void *unused);
142 static void usb_host_release_interfaces(USBHostDevice *s);
143 static void usb_host_nodev(USBHostDevice *s);
144 static void usb_host_detach_kernel(USBHostDevice *s);
145 static void usb_host_attach_kernel(USBHostDevice *s);
147 /* ------------------------------------------------------------------------ */
149 #ifndef LIBUSB_LOG_LEVEL_WARNING /* older libusb didn't define these */
150 #define LIBUSB_LOG_LEVEL_WARNING 2
151 #endif
153 /* ------------------------------------------------------------------------ */
155 #define CONTROL_TIMEOUT 10000 /* 10 sec */
156 #define BULK_TIMEOUT 0 /* unlimited */
157 #define INTR_TIMEOUT 0 /* unlimited */
159 #if LIBUSBX_API_VERSION >= 0x01000103
160 # define HAVE_STREAMS 1
161 #endif
163 static const char *speed_name[] = {
164 [LIBUSB_SPEED_UNKNOWN] = "?",
165 [LIBUSB_SPEED_LOW] = "1.5",
166 [LIBUSB_SPEED_FULL] = "12",
167 [LIBUSB_SPEED_HIGH] = "480",
168 [LIBUSB_SPEED_SUPER] = "5000",
171 static const unsigned int speed_map[] = {
172 [LIBUSB_SPEED_LOW] = USB_SPEED_LOW,
173 [LIBUSB_SPEED_FULL] = USB_SPEED_FULL,
174 [LIBUSB_SPEED_HIGH] = USB_SPEED_HIGH,
175 [LIBUSB_SPEED_SUPER] = USB_SPEED_SUPER,
178 static const unsigned int status_map[] = {
179 [LIBUSB_TRANSFER_COMPLETED] = USB_RET_SUCCESS,
180 [LIBUSB_TRANSFER_ERROR] = USB_RET_IOERROR,
181 [LIBUSB_TRANSFER_TIMED_OUT] = USB_RET_IOERROR,
182 [LIBUSB_TRANSFER_CANCELLED] = USB_RET_IOERROR,
183 [LIBUSB_TRANSFER_STALL] = USB_RET_STALL,
184 [LIBUSB_TRANSFER_NO_DEVICE] = USB_RET_NODEV,
185 [LIBUSB_TRANSFER_OVERFLOW] = USB_RET_BABBLE,
188 static const char *err_names[] = {
189 [-LIBUSB_ERROR_IO] = "IO",
190 [-LIBUSB_ERROR_INVALID_PARAM] = "INVALID_PARAM",
191 [-LIBUSB_ERROR_ACCESS] = "ACCESS",
192 [-LIBUSB_ERROR_NO_DEVICE] = "NO_DEVICE",
193 [-LIBUSB_ERROR_NOT_FOUND] = "NOT_FOUND",
194 [-LIBUSB_ERROR_BUSY] = "BUSY",
195 [-LIBUSB_ERROR_TIMEOUT] = "TIMEOUT",
196 [-LIBUSB_ERROR_OVERFLOW] = "OVERFLOW",
197 [-LIBUSB_ERROR_PIPE] = "PIPE",
198 [-LIBUSB_ERROR_INTERRUPTED] = "INTERRUPTED",
199 [-LIBUSB_ERROR_NO_MEM] = "NO_MEM",
200 [-LIBUSB_ERROR_NOT_SUPPORTED] = "NOT_SUPPORTED",
201 [-LIBUSB_ERROR_OTHER] = "OTHER",
204 static libusb_context *ctx;
205 static uint32_t loglevel;
207 static void usb_host_handle_fd(void *opaque)
209 struct timeval tv = { 0, 0 };
210 libusb_handle_events_timeout(ctx, &tv);
213 static void usb_host_add_fd(int fd, short events, void *user_data)
215 qemu_set_fd_handler(fd,
216 (events & POLLIN) ? usb_host_handle_fd : NULL,
217 (events & POLLOUT) ? usb_host_handle_fd : NULL,
218 ctx);
221 static void usb_host_del_fd(int fd, void *user_data)
223 qemu_set_fd_handler(fd, NULL, NULL, NULL);
226 static int usb_host_init(void)
228 const struct libusb_pollfd **poll;
229 int i, rc;
231 if (ctx) {
232 return 0;
234 rc = libusb_init(&ctx);
235 if (rc != 0) {
236 return -1;
238 libusb_set_debug(ctx, loglevel);
240 libusb_set_pollfd_notifiers(ctx, usb_host_add_fd,
241 usb_host_del_fd,
242 ctx);
243 poll = libusb_get_pollfds(ctx);
244 if (poll) {
245 for (i = 0; poll[i] != NULL; i++) {
246 usb_host_add_fd(poll[i]->fd, poll[i]->events, ctx);
249 free(poll);
250 return 0;
253 static int usb_host_get_port(libusb_device *dev, char *port, size_t len)
255 uint8_t path[7];
256 size_t off;
257 int rc, i;
259 #if LIBUSBX_API_VERSION >= 0x01000102
260 rc = libusb_get_port_numbers(dev, path, 7);
261 #else
262 rc = libusb_get_port_path(ctx, dev, path, 7);
263 #endif
264 if (rc < 0) {
265 return 0;
267 off = snprintf(port, len, "%d", path[0]);
268 for (i = 1; i < rc; i++) {
269 off += snprintf(port+off, len-off, ".%d", path[i]);
271 return off;
274 static void usb_host_libusb_error(const char *func, int rc)
276 const char *errname;
278 if (rc >= 0) {
279 return;
282 if (-rc < ARRAY_SIZE(err_names) && err_names[-rc]) {
283 errname = err_names[-rc];
284 } else {
285 errname = "?";
287 error_report("%s: %d [%s]", func, rc, errname);
290 /* ------------------------------------------------------------------------ */
292 static bool usb_host_use_combining(USBEndpoint *ep)
294 int type;
296 if (!ep->pipeline) {
297 return false;
299 if (ep->pid != USB_TOKEN_IN) {
300 return false;
302 type = usb_ep_get_type(ep->dev, ep->pid, ep->nr);
303 if (type != USB_ENDPOINT_XFER_BULK) {
304 return false;
306 return true;
309 /* ------------------------------------------------------------------------ */
311 static USBHostRequest *usb_host_req_alloc(USBHostDevice *s, USBPacket *p,
312 bool in, size_t bufsize)
314 USBHostRequest *r = g_new0(USBHostRequest, 1);
316 r->host = s;
317 r->p = p;
318 r->in = in;
319 r->xfer = libusb_alloc_transfer(0);
320 if (bufsize) {
321 r->buffer = g_malloc(bufsize);
323 QTAILQ_INSERT_TAIL(&s->requests, r, next);
324 return r;
327 static void usb_host_req_free(USBHostRequest *r)
329 if (r->host) {
330 QTAILQ_REMOVE(&r->host->requests, r, next);
332 libusb_free_transfer(r->xfer);
333 g_free(r->buffer);
334 g_free(r);
337 static USBHostRequest *usb_host_req_find(USBHostDevice *s, USBPacket *p)
339 USBHostRequest *r;
341 QTAILQ_FOREACH(r, &s->requests, next) {
342 if (r->p == p) {
343 return r;
346 return NULL;
349 static void usb_host_req_complete_ctrl(struct libusb_transfer *xfer)
351 USBHostRequest *r = xfer->user_data;
352 USBHostDevice *s = r->host;
353 bool disconnect = (xfer->status == LIBUSB_TRANSFER_NO_DEVICE);
355 if (r->p == NULL) {
356 goto out; /* request was canceled */
359 r->p->status = status_map[xfer->status];
360 r->p->actual_length = xfer->actual_length;
361 if (r->in && xfer->actual_length) {
362 memcpy(r->cbuf, r->buffer + 8, xfer->actual_length);
364 /* Fix up USB-3 ep0 maxpacket size to allow superspeed connected devices
365 * to work redirected to a not superspeed capable hcd */
366 if (r->usb3ep0quirk && xfer->actual_length >= 18 &&
367 r->cbuf[7] == 9) {
368 r->cbuf[7] = 64;
371 trace_usb_host_req_complete(s->bus_num, s->addr, r->p,
372 r->p->status, r->p->actual_length);
373 usb_generic_async_ctrl_complete(USB_DEVICE(s), r->p);
375 out:
376 usb_host_req_free(r);
377 if (disconnect) {
378 usb_host_nodev(s);
382 static void usb_host_req_complete_data(struct libusb_transfer *xfer)
384 USBHostRequest *r = xfer->user_data;
385 USBHostDevice *s = r->host;
386 bool disconnect = (xfer->status == LIBUSB_TRANSFER_NO_DEVICE);
388 if (r->p == NULL) {
389 goto out; /* request was canceled */
392 r->p->status = status_map[xfer->status];
393 if (r->in && xfer->actual_length) {
394 usb_packet_copy(r->p, r->buffer, xfer->actual_length);
396 trace_usb_host_req_complete(s->bus_num, s->addr, r->p,
397 r->p->status, r->p->actual_length);
398 if (usb_host_use_combining(r->p->ep)) {
399 usb_combined_input_packet_complete(USB_DEVICE(s), r->p);
400 } else {
401 usb_packet_complete(USB_DEVICE(s), r->p);
404 out:
405 usb_host_req_free(r);
406 if (disconnect) {
407 usb_host_nodev(s);
411 static void usb_host_req_abort(USBHostRequest *r)
413 USBHostDevice *s = r->host;
414 bool inflight = (r->p && r->p->state == USB_PACKET_ASYNC);
416 if (inflight) {
417 r->p->status = USB_RET_NODEV;
418 trace_usb_host_req_complete(s->bus_num, s->addr, r->p,
419 r->p->status, r->p->actual_length);
420 if (r->p->ep->nr == 0) {
421 usb_generic_async_ctrl_complete(USB_DEVICE(s), r->p);
422 } else {
423 usb_packet_complete(USB_DEVICE(s), r->p);
425 r->p = NULL;
428 QTAILQ_REMOVE(&r->host->requests, r, next);
429 r->host = NULL;
431 if (inflight) {
432 libusb_cancel_transfer(r->xfer);
436 /* ------------------------------------------------------------------------ */
438 static void usb_host_req_complete_iso(struct libusb_transfer *transfer)
440 USBHostIsoXfer *xfer = transfer->user_data;
442 if (!xfer) {
443 /* USBHostIsoXfer released while inflight */
444 g_free(transfer->buffer);
445 libusb_free_transfer(transfer);
446 return;
449 QTAILQ_REMOVE(&xfer->ring->inflight, xfer, next);
450 if (QTAILQ_EMPTY(&xfer->ring->inflight)) {
451 USBHostDevice *s = xfer->ring->host;
452 trace_usb_host_iso_stop(s->bus_num, s->addr, xfer->ring->ep->nr);
454 if (xfer->ring->ep->pid == USB_TOKEN_IN) {
455 QTAILQ_INSERT_TAIL(&xfer->ring->copy, xfer, next);
456 usb_wakeup(xfer->ring->ep, 0);
457 } else {
458 QTAILQ_INSERT_TAIL(&xfer->ring->unused, xfer, next);
462 static USBHostIsoRing *usb_host_iso_alloc(USBHostDevice *s, USBEndpoint *ep)
464 USBHostIsoRing *ring = g_new0(USBHostIsoRing, 1);
465 USBHostIsoXfer *xfer;
466 /* FIXME: check interval (for now assume one xfer per frame) */
467 int packets = s->iso_urb_frames;
468 int i;
470 ring->host = s;
471 ring->ep = ep;
472 QTAILQ_INIT(&ring->unused);
473 QTAILQ_INIT(&ring->inflight);
474 QTAILQ_INIT(&ring->copy);
475 QTAILQ_INSERT_TAIL(&s->isorings, ring, next);
477 for (i = 0; i < s->iso_urb_count; i++) {
478 xfer = g_new0(USBHostIsoXfer, 1);
479 xfer->ring = ring;
480 xfer->xfer = libusb_alloc_transfer(packets);
481 xfer->xfer->dev_handle = s->dh;
482 xfer->xfer->type = LIBUSB_TRANSFER_TYPE_ISOCHRONOUS;
484 xfer->xfer->endpoint = ring->ep->nr;
485 if (ring->ep->pid == USB_TOKEN_IN) {
486 xfer->xfer->endpoint |= USB_DIR_IN;
488 xfer->xfer->callback = usb_host_req_complete_iso;
489 xfer->xfer->user_data = xfer;
491 xfer->xfer->num_iso_packets = packets;
492 xfer->xfer->length = ring->ep->max_packet_size * packets;
493 xfer->xfer->buffer = g_malloc0(xfer->xfer->length);
495 QTAILQ_INSERT_TAIL(&ring->unused, xfer, next);
498 return ring;
501 static USBHostIsoRing *usb_host_iso_find(USBHostDevice *s, USBEndpoint *ep)
503 USBHostIsoRing *ring;
505 QTAILQ_FOREACH(ring, &s->isorings, next) {
506 if (ring->ep == ep) {
507 return ring;
510 return NULL;
513 static void usb_host_iso_reset_xfer(USBHostIsoXfer *xfer)
515 libusb_set_iso_packet_lengths(xfer->xfer,
516 xfer->ring->ep->max_packet_size);
517 xfer->packet = 0;
518 xfer->copy_complete = false;
521 static void usb_host_iso_free_xfer(USBHostIsoXfer *xfer, bool inflight)
523 if (inflight) {
524 xfer->xfer->user_data = NULL;
525 } else {
526 g_free(xfer->xfer->buffer);
527 libusb_free_transfer(xfer->xfer);
529 g_free(xfer);
532 static void usb_host_iso_free(USBHostIsoRing *ring)
534 USBHostIsoXfer *xfer;
536 while ((xfer = QTAILQ_FIRST(&ring->inflight)) != NULL) {
537 QTAILQ_REMOVE(&ring->inflight, xfer, next);
538 usb_host_iso_free_xfer(xfer, true);
540 while ((xfer = QTAILQ_FIRST(&ring->unused)) != NULL) {
541 QTAILQ_REMOVE(&ring->unused, xfer, next);
542 usb_host_iso_free_xfer(xfer, false);
544 while ((xfer = QTAILQ_FIRST(&ring->copy)) != NULL) {
545 QTAILQ_REMOVE(&ring->copy, xfer, next);
546 usb_host_iso_free_xfer(xfer, false);
549 QTAILQ_REMOVE(&ring->host->isorings, ring, next);
550 g_free(ring);
553 static void usb_host_iso_free_all(USBHostDevice *s)
555 USBHostIsoRing *ring;
557 while ((ring = QTAILQ_FIRST(&s->isorings)) != NULL) {
558 usb_host_iso_free(ring);
562 static bool usb_host_iso_data_copy(USBHostIsoXfer *xfer, USBPacket *p)
564 unsigned int psize;
565 unsigned char *buf;
567 buf = libusb_get_iso_packet_buffer_simple(xfer->xfer, xfer->packet);
568 if (p->pid == USB_TOKEN_OUT) {
569 psize = p->iov.size;
570 if (psize > xfer->ring->ep->max_packet_size) {
571 /* should not happen (guest bug) */
572 psize = xfer->ring->ep->max_packet_size;
574 xfer->xfer->iso_packet_desc[xfer->packet].length = psize;
575 } else {
576 psize = xfer->xfer->iso_packet_desc[xfer->packet].actual_length;
577 if (psize > p->iov.size) {
578 /* should not happen (guest bug) */
579 psize = p->iov.size;
582 usb_packet_copy(p, buf, psize);
583 xfer->packet++;
584 xfer->copy_complete = (xfer->packet == xfer->xfer->num_iso_packets);
585 return xfer->copy_complete;
588 static void usb_host_iso_data_in(USBHostDevice *s, USBPacket *p)
590 USBHostIsoRing *ring;
591 USBHostIsoXfer *xfer;
592 bool disconnect = false;
593 int rc;
595 ring = usb_host_iso_find(s, p->ep);
596 if (ring == NULL) {
597 ring = usb_host_iso_alloc(s, p->ep);
600 /* copy data to guest */
601 xfer = QTAILQ_FIRST(&ring->copy);
602 if (xfer != NULL) {
603 if (usb_host_iso_data_copy(xfer, p)) {
604 QTAILQ_REMOVE(&ring->copy, xfer, next);
605 QTAILQ_INSERT_TAIL(&ring->unused, xfer, next);
609 /* submit empty bufs to host */
610 while ((xfer = QTAILQ_FIRST(&ring->unused)) != NULL) {
611 QTAILQ_REMOVE(&ring->unused, xfer, next);
612 usb_host_iso_reset_xfer(xfer);
613 rc = libusb_submit_transfer(xfer->xfer);
614 if (rc != 0) {
615 usb_host_libusb_error("libusb_submit_transfer [iso]", rc);
616 QTAILQ_INSERT_TAIL(&ring->unused, xfer, next);
617 if (rc == LIBUSB_ERROR_NO_DEVICE) {
618 disconnect = true;
620 break;
622 if (QTAILQ_EMPTY(&ring->inflight)) {
623 trace_usb_host_iso_start(s->bus_num, s->addr, p->ep->nr);
625 QTAILQ_INSERT_TAIL(&ring->inflight, xfer, next);
628 if (disconnect) {
629 usb_host_nodev(s);
633 static void usb_host_iso_data_out(USBHostDevice *s, USBPacket *p)
635 USBHostIsoRing *ring;
636 USBHostIsoXfer *xfer;
637 bool disconnect = false;
638 int rc, filled = 0;
640 ring = usb_host_iso_find(s, p->ep);
641 if (ring == NULL) {
642 ring = usb_host_iso_alloc(s, p->ep);
645 /* copy data from guest */
646 xfer = QTAILQ_FIRST(&ring->copy);
647 while (xfer != NULL && xfer->copy_complete) {
648 filled++;
649 xfer = QTAILQ_NEXT(xfer, next);
651 if (xfer == NULL) {
652 xfer = QTAILQ_FIRST(&ring->unused);
653 if (xfer == NULL) {
654 trace_usb_host_iso_out_of_bufs(s->bus_num, s->addr, p->ep->nr);
655 return;
657 QTAILQ_REMOVE(&ring->unused, xfer, next);
658 usb_host_iso_reset_xfer(xfer);
659 QTAILQ_INSERT_TAIL(&ring->copy, xfer, next);
661 usb_host_iso_data_copy(xfer, p);
663 if (QTAILQ_EMPTY(&ring->inflight)) {
664 /* wait until half of our buffers are filled
665 before kicking the iso out stream */
666 if (filled*2 < s->iso_urb_count) {
667 return;
671 /* submit filled bufs to host */
672 while ((xfer = QTAILQ_FIRST(&ring->copy)) != NULL &&
673 xfer->copy_complete) {
674 QTAILQ_REMOVE(&ring->copy, xfer, next);
675 rc = libusb_submit_transfer(xfer->xfer);
676 if (rc != 0) {
677 usb_host_libusb_error("libusb_submit_transfer [iso]", rc);
678 QTAILQ_INSERT_TAIL(&ring->unused, xfer, next);
679 if (rc == LIBUSB_ERROR_NO_DEVICE) {
680 disconnect = true;
682 break;
684 if (QTAILQ_EMPTY(&ring->inflight)) {
685 trace_usb_host_iso_start(s->bus_num, s->addr, p->ep->nr);
687 QTAILQ_INSERT_TAIL(&ring->inflight, xfer, next);
690 if (disconnect) {
691 usb_host_nodev(s);
695 /* ------------------------------------------------------------------------ */
697 static void usb_host_speed_compat(USBHostDevice *s)
699 USBDevice *udev = USB_DEVICE(s);
700 struct libusb_config_descriptor *conf;
701 const struct libusb_interface_descriptor *intf;
702 const struct libusb_endpoint_descriptor *endp;
703 #ifdef HAVE_STREAMS
704 struct libusb_ss_endpoint_companion_descriptor *endp_ss_comp;
705 #endif
706 bool compat_high = true;
707 bool compat_full = true;
708 uint8_t type;
709 int rc, c, i, a, e;
711 for (c = 0;; c++) {
712 rc = libusb_get_config_descriptor(s->dev, c, &conf);
713 if (rc != 0) {
714 break;
716 for (i = 0; i < conf->bNumInterfaces; i++) {
717 for (a = 0; a < conf->interface[i].num_altsetting; a++) {
718 intf = &conf->interface[i].altsetting[a];
719 for (e = 0; e < intf->bNumEndpoints; e++) {
720 endp = &intf->endpoint[e];
721 type = endp->bmAttributes & 0x3;
722 switch (type) {
723 case 0x01: /* ISO */
724 compat_full = false;
725 compat_high = false;
726 break;
727 case 0x02: /* BULK */
728 #ifdef HAVE_STREAMS
729 rc = libusb_get_ss_endpoint_companion_descriptor
730 (ctx, endp, &endp_ss_comp);
731 if (rc == LIBUSB_SUCCESS) {
732 libusb_free_ss_endpoint_companion_descriptor
733 (endp_ss_comp);
734 compat_full = false;
735 compat_high = false;
737 #endif
738 break;
739 case 0x03: /* INTERRUPT */
740 if (endp->wMaxPacketSize > 64) {
741 compat_full = false;
743 if (endp->wMaxPacketSize > 1024) {
744 compat_high = false;
746 break;
751 libusb_free_config_descriptor(conf);
754 udev->speedmask = (1 << udev->speed);
755 if (udev->speed == USB_SPEED_SUPER && compat_high) {
756 udev->speedmask |= USB_SPEED_MASK_HIGH;
758 if (udev->speed == USB_SPEED_SUPER && compat_full) {
759 udev->speedmask |= USB_SPEED_MASK_FULL;
761 if (udev->speed == USB_SPEED_HIGH && compat_full) {
762 udev->speedmask |= USB_SPEED_MASK_FULL;
766 static void usb_host_ep_update(USBHostDevice *s)
768 static const char *tname[] = {
769 [USB_ENDPOINT_XFER_CONTROL] = "control",
770 [USB_ENDPOINT_XFER_ISOC] = "isoc",
771 [USB_ENDPOINT_XFER_BULK] = "bulk",
772 [USB_ENDPOINT_XFER_INT] = "int",
774 USBDevice *udev = USB_DEVICE(s);
775 struct libusb_config_descriptor *conf;
776 const struct libusb_interface_descriptor *intf;
777 const struct libusb_endpoint_descriptor *endp;
778 #ifdef HAVE_STREAMS
779 struct libusb_ss_endpoint_companion_descriptor *endp_ss_comp;
780 #endif
781 uint8_t devep, type;
782 int pid, ep;
783 int rc, i, e;
785 usb_ep_reset(udev);
786 rc = libusb_get_active_config_descriptor(s->dev, &conf);
787 if (rc != 0) {
788 return;
790 trace_usb_host_parse_config(s->bus_num, s->addr,
791 conf->bConfigurationValue, true);
793 for (i = 0; i < conf->bNumInterfaces; i++) {
794 assert(udev->altsetting[i] < conf->interface[i].num_altsetting);
795 intf = &conf->interface[i].altsetting[udev->altsetting[i]];
796 trace_usb_host_parse_interface(s->bus_num, s->addr,
797 intf->bInterfaceNumber,
798 intf->bAlternateSetting, true);
799 for (e = 0; e < intf->bNumEndpoints; e++) {
800 endp = &intf->endpoint[e];
802 devep = endp->bEndpointAddress;
803 pid = (devep & USB_DIR_IN) ? USB_TOKEN_IN : USB_TOKEN_OUT;
804 ep = devep & 0xf;
805 type = endp->bmAttributes & 0x3;
807 if (ep == 0) {
808 trace_usb_host_parse_error(s->bus_num, s->addr,
809 "invalid endpoint address");
810 return;
812 if (usb_ep_get_type(udev, pid, ep) != USB_ENDPOINT_XFER_INVALID) {
813 trace_usb_host_parse_error(s->bus_num, s->addr,
814 "duplicate endpoint address");
815 return;
818 trace_usb_host_parse_endpoint(s->bus_num, s->addr, ep,
819 (devep & USB_DIR_IN) ? "in" : "out",
820 tname[type], true);
821 usb_ep_set_max_packet_size(udev, pid, ep,
822 endp->wMaxPacketSize);
823 usb_ep_set_type(udev, pid, ep, type);
824 usb_ep_set_ifnum(udev, pid, ep, i);
825 usb_ep_set_halted(udev, pid, ep, 0);
826 #ifdef HAVE_STREAMS
827 if (type == LIBUSB_TRANSFER_TYPE_BULK &&
828 libusb_get_ss_endpoint_companion_descriptor(ctx, endp,
829 &endp_ss_comp) == LIBUSB_SUCCESS) {
830 usb_ep_set_max_streams(udev, pid, ep,
831 endp_ss_comp->bmAttributes);
832 libusb_free_ss_endpoint_companion_descriptor(endp_ss_comp);
834 #endif
838 libusb_free_config_descriptor(conf);
841 static int usb_host_open(USBHostDevice *s, libusb_device *dev)
843 USBDevice *udev = USB_DEVICE(s);
844 int bus_num = libusb_get_bus_number(dev);
845 int addr = libusb_get_device_address(dev);
846 int rc;
847 Error *local_err = NULL;
849 trace_usb_host_open_started(bus_num, addr);
851 if (s->dh != NULL) {
852 goto fail;
854 rc = libusb_open(dev, &s->dh);
855 if (rc != 0) {
856 goto fail;
859 s->dev = dev;
860 s->bus_num = bus_num;
861 s->addr = addr;
863 usb_host_detach_kernel(s);
865 libusb_get_device_descriptor(dev, &s->ddesc);
866 usb_host_get_port(s->dev, s->port, sizeof(s->port));
868 usb_ep_init(udev);
869 usb_host_ep_update(s);
871 udev->speed = speed_map[libusb_get_device_speed(dev)];
872 usb_host_speed_compat(s);
874 if (s->ddesc.iProduct) {
875 libusb_get_string_descriptor_ascii(s->dh, s->ddesc.iProduct,
876 (unsigned char *)udev->product_desc,
877 sizeof(udev->product_desc));
878 } else {
879 snprintf(udev->product_desc, sizeof(udev->product_desc),
880 "host:%d.%d", bus_num, addr);
883 usb_device_attach(udev, &local_err);
884 if (local_err) {
885 error_report_err(local_err);
886 goto fail;
889 trace_usb_host_open_success(bus_num, addr);
890 return 0;
892 fail:
893 trace_usb_host_open_failure(bus_num, addr);
894 if (s->dh != NULL) {
895 usb_host_release_interfaces(s);
896 libusb_reset_device(s->dh);
897 usb_host_attach_kernel(s);
898 libusb_close(s->dh);
899 s->dh = NULL;
900 s->dev = NULL;
902 return -1;
905 static void usb_host_abort_xfers(USBHostDevice *s)
907 USBHostRequest *r, *rtmp;
909 QTAILQ_FOREACH_SAFE(r, &s->requests, next, rtmp) {
910 usb_host_req_abort(r);
914 static int usb_host_close(USBHostDevice *s)
916 USBDevice *udev = USB_DEVICE(s);
918 if (s->dh == NULL) {
919 return -1;
922 trace_usb_host_close(s->bus_num, s->addr);
924 usb_host_abort_xfers(s);
925 usb_host_iso_free_all(s);
927 if (udev->attached) {
928 usb_device_detach(udev);
931 usb_host_release_interfaces(s);
932 libusb_reset_device(s->dh);
933 usb_host_attach_kernel(s);
934 libusb_close(s->dh);
935 s->dh = NULL;
936 s->dev = NULL;
938 usb_host_auto_check(NULL);
939 return 0;
942 static void usb_host_nodev_bh(void *opaque)
944 USBHostDevice *s = opaque;
945 usb_host_close(s);
948 static void usb_host_nodev(USBHostDevice *s)
950 if (!s->bh_nodev) {
951 s->bh_nodev = qemu_bh_new(usb_host_nodev_bh, s);
953 qemu_bh_schedule(s->bh_nodev);
956 static void usb_host_exit_notifier(struct Notifier *n, void *data)
958 USBHostDevice *s = container_of(n, USBHostDevice, exit);
960 if (s->dh) {
961 usb_host_release_interfaces(s);
962 usb_host_attach_kernel(s);
966 static void usb_host_realize(USBDevice *udev, Error **errp)
968 USBHostDevice *s = USB_HOST_DEVICE(udev);
970 if (s->match.vendor_id > 0xffff) {
971 error_setg(errp, "vendorid out of range");
972 return;
974 if (s->match.product_id > 0xffff) {
975 error_setg(errp, "productid out of range");
976 return;
978 if (s->match.addr > 127) {
979 error_setg(errp, "hostaddr out of range");
980 return;
983 loglevel = s->loglevel;
984 udev->flags |= (1 << USB_DEV_FLAG_IS_HOST);
985 udev->auto_attach = 0;
986 QTAILQ_INIT(&s->requests);
987 QTAILQ_INIT(&s->isorings);
989 s->exit.notify = usb_host_exit_notifier;
990 qemu_add_exit_notifier(&s->exit);
992 QTAILQ_INSERT_TAIL(&hostdevs, s, next);
993 usb_host_auto_check(NULL);
996 static void usb_host_instance_init(Object *obj)
998 USBDevice *udev = USB_DEVICE(obj);
999 USBHostDevice *s = USB_HOST_DEVICE(udev);
1001 device_add_bootindex_property(obj, &s->bootindex,
1002 "bootindex", NULL,
1003 &udev->qdev, NULL);
1006 static void usb_host_handle_destroy(USBDevice *udev)
1008 USBHostDevice *s = USB_HOST_DEVICE(udev);
1010 qemu_remove_exit_notifier(&s->exit);
1011 QTAILQ_REMOVE(&hostdevs, s, next);
1012 usb_host_close(s);
1015 static void usb_host_cancel_packet(USBDevice *udev, USBPacket *p)
1017 USBHostDevice *s = USB_HOST_DEVICE(udev);
1018 USBHostRequest *r;
1020 if (p->combined) {
1021 usb_combined_packet_cancel(udev, p);
1022 return;
1025 trace_usb_host_req_canceled(s->bus_num, s->addr, p);
1027 r = usb_host_req_find(s, p);
1028 if (r && r->p) {
1029 r->p = NULL; /* mark as dead */
1030 libusb_cancel_transfer(r->xfer);
1034 static void usb_host_detach_kernel(USBHostDevice *s)
1036 struct libusb_config_descriptor *conf;
1037 int rc, i;
1039 rc = libusb_get_active_config_descriptor(s->dev, &conf);
1040 if (rc != 0) {
1041 return;
1043 for (i = 0; i < conf->bNumInterfaces; i++) {
1044 rc = libusb_kernel_driver_active(s->dh, i);
1045 usb_host_libusb_error("libusb_kernel_driver_active", rc);
1046 if (rc != 1) {
1047 continue;
1049 trace_usb_host_detach_kernel(s->bus_num, s->addr, i);
1050 rc = libusb_detach_kernel_driver(s->dh, i);
1051 usb_host_libusb_error("libusb_detach_kernel_driver", rc);
1052 s->ifs[i].detached = true;
1054 libusb_free_config_descriptor(conf);
1057 static void usb_host_attach_kernel(USBHostDevice *s)
1059 struct libusb_config_descriptor *conf;
1060 int rc, i;
1062 rc = libusb_get_active_config_descriptor(s->dev, &conf);
1063 if (rc != 0) {
1064 return;
1066 for (i = 0; i < conf->bNumInterfaces; i++) {
1067 if (!s->ifs[i].detached) {
1068 continue;
1070 trace_usb_host_attach_kernel(s->bus_num, s->addr, i);
1071 libusb_attach_kernel_driver(s->dh, i);
1072 s->ifs[i].detached = false;
1074 libusb_free_config_descriptor(conf);
1077 static int usb_host_claim_interfaces(USBHostDevice *s, int configuration)
1079 USBDevice *udev = USB_DEVICE(s);
1080 struct libusb_config_descriptor *conf;
1081 int rc, i;
1083 for (i = 0; i < USB_MAX_INTERFACES; i++) {
1084 udev->altsetting[i] = 0;
1086 udev->ninterfaces = 0;
1087 udev->configuration = 0;
1089 usb_host_detach_kernel(s);
1091 rc = libusb_get_active_config_descriptor(s->dev, &conf);
1092 if (rc != 0) {
1093 if (rc == LIBUSB_ERROR_NOT_FOUND) {
1094 /* address state - ignore */
1095 return USB_RET_SUCCESS;
1097 return USB_RET_STALL;
1100 for (i = 0; i < conf->bNumInterfaces; i++) {
1101 trace_usb_host_claim_interface(s->bus_num, s->addr, configuration, i);
1102 rc = libusb_claim_interface(s->dh, i);
1103 usb_host_libusb_error("libusb_claim_interface", rc);
1104 if (rc != 0) {
1105 return USB_RET_STALL;
1107 s->ifs[i].claimed = true;
1110 udev->ninterfaces = conf->bNumInterfaces;
1111 udev->configuration = configuration;
1113 libusb_free_config_descriptor(conf);
1114 return USB_RET_SUCCESS;
1117 static void usb_host_release_interfaces(USBHostDevice *s)
1119 USBDevice *udev = USB_DEVICE(s);
1120 int i, rc;
1122 for (i = 0; i < udev->ninterfaces; i++) {
1123 if (!s->ifs[i].claimed) {
1124 continue;
1126 trace_usb_host_release_interface(s->bus_num, s->addr, i);
1127 rc = libusb_release_interface(s->dh, i);
1128 usb_host_libusb_error("libusb_release_interface", rc);
1129 s->ifs[i].claimed = false;
1133 static void usb_host_set_address(USBHostDevice *s, int addr)
1135 USBDevice *udev = USB_DEVICE(s);
1137 trace_usb_host_set_address(s->bus_num, s->addr, addr);
1138 udev->addr = addr;
1141 static void usb_host_set_config(USBHostDevice *s, int config, USBPacket *p)
1143 int rc;
1145 trace_usb_host_set_config(s->bus_num, s->addr, config);
1147 usb_host_release_interfaces(s);
1148 rc = libusb_set_configuration(s->dh, config);
1149 if (rc != 0) {
1150 usb_host_libusb_error("libusb_set_configuration", rc);
1151 p->status = USB_RET_STALL;
1152 if (rc == LIBUSB_ERROR_NO_DEVICE) {
1153 usb_host_nodev(s);
1155 return;
1157 p->status = usb_host_claim_interfaces(s, config);
1158 if (p->status != USB_RET_SUCCESS) {
1159 return;
1161 usb_host_ep_update(s);
1164 static void usb_host_set_interface(USBHostDevice *s, int iface, int alt,
1165 USBPacket *p)
1167 USBDevice *udev = USB_DEVICE(s);
1168 int rc;
1170 trace_usb_host_set_interface(s->bus_num, s->addr, iface, alt);
1172 usb_host_iso_free_all(s);
1174 if (iface >= USB_MAX_INTERFACES) {
1175 p->status = USB_RET_STALL;
1176 return;
1179 rc = libusb_set_interface_alt_setting(s->dh, iface, alt);
1180 if (rc != 0) {
1181 usb_host_libusb_error("libusb_set_interface_alt_setting", rc);
1182 p->status = USB_RET_STALL;
1183 if (rc == LIBUSB_ERROR_NO_DEVICE) {
1184 usb_host_nodev(s);
1186 return;
1189 udev->altsetting[iface] = alt;
1190 usb_host_ep_update(s);
1193 static void usb_host_handle_control(USBDevice *udev, USBPacket *p,
1194 int request, int value, int index,
1195 int length, uint8_t *data)
1197 USBHostDevice *s = USB_HOST_DEVICE(udev);
1198 USBHostRequest *r;
1199 int rc;
1201 trace_usb_host_req_control(s->bus_num, s->addr, p, request, value, index);
1203 if (s->dh == NULL) {
1204 p->status = USB_RET_NODEV;
1205 trace_usb_host_req_emulated(s->bus_num, s->addr, p, p->status);
1206 return;
1209 switch (request) {
1210 case DeviceOutRequest | USB_REQ_SET_ADDRESS:
1211 usb_host_set_address(s, value);
1212 trace_usb_host_req_emulated(s->bus_num, s->addr, p, p->status);
1213 return;
1215 case DeviceOutRequest | USB_REQ_SET_CONFIGURATION:
1216 usb_host_set_config(s, value & 0xff, p);
1217 trace_usb_host_req_emulated(s->bus_num, s->addr, p, p->status);
1218 return;
1220 case InterfaceOutRequest | USB_REQ_SET_INTERFACE:
1221 usb_host_set_interface(s, index, value, p);
1222 trace_usb_host_req_emulated(s->bus_num, s->addr, p, p->status);
1223 return;
1225 case EndpointOutRequest | USB_REQ_CLEAR_FEATURE:
1226 if (value == 0) { /* clear halt */
1227 int pid = (index & USB_DIR_IN) ? USB_TOKEN_IN : USB_TOKEN_OUT;
1228 libusb_clear_halt(s->dh, index);
1229 usb_ep_set_halted(udev, pid, index & 0x0f, 0);
1230 trace_usb_host_req_emulated(s->bus_num, s->addr, p, p->status);
1231 return;
1235 r = usb_host_req_alloc(s, p, (request >> 8) & USB_DIR_IN, length + 8);
1236 r->cbuf = data;
1237 r->clen = length;
1238 memcpy(r->buffer, udev->setup_buf, 8);
1239 if (!r->in) {
1240 memcpy(r->buffer + 8, r->cbuf, r->clen);
1243 /* Fix up USB-3 ep0 maxpacket size to allow superspeed connected devices
1244 * to work redirected to a not superspeed capable hcd */
1245 if ((udev->speedmask & USB_SPEED_MASK_SUPER) &&
1246 !(udev->port->speedmask & USB_SPEED_MASK_SUPER) &&
1247 request == 0x8006 && value == 0x100 && index == 0) {
1248 r->usb3ep0quirk = true;
1251 libusb_fill_control_transfer(r->xfer, s->dh, r->buffer,
1252 usb_host_req_complete_ctrl, r,
1253 CONTROL_TIMEOUT);
1254 rc = libusb_submit_transfer(r->xfer);
1255 if (rc != 0) {
1256 p->status = USB_RET_NODEV;
1257 trace_usb_host_req_complete(s->bus_num, s->addr, p,
1258 p->status, p->actual_length);
1259 if (rc == LIBUSB_ERROR_NO_DEVICE) {
1260 usb_host_nodev(s);
1262 return;
1265 p->status = USB_RET_ASYNC;
1268 static void usb_host_handle_data(USBDevice *udev, USBPacket *p)
1270 USBHostDevice *s = USB_HOST_DEVICE(udev);
1271 USBHostRequest *r;
1272 size_t size;
1273 int ep, rc;
1275 if (usb_host_use_combining(p->ep) && p->state == USB_PACKET_SETUP) {
1276 p->status = USB_RET_ADD_TO_QUEUE;
1277 return;
1280 trace_usb_host_req_data(s->bus_num, s->addr, p,
1281 p->pid == USB_TOKEN_IN,
1282 p->ep->nr, p->iov.size);
1284 if (s->dh == NULL) {
1285 p->status = USB_RET_NODEV;
1286 trace_usb_host_req_emulated(s->bus_num, s->addr, p, p->status);
1287 return;
1289 if (p->ep->halted) {
1290 p->status = USB_RET_STALL;
1291 trace_usb_host_req_emulated(s->bus_num, s->addr, p, p->status);
1292 return;
1295 switch (usb_ep_get_type(udev, p->pid, p->ep->nr)) {
1296 case USB_ENDPOINT_XFER_BULK:
1297 size = usb_packet_size(p);
1298 r = usb_host_req_alloc(s, p, p->pid == USB_TOKEN_IN, size);
1299 if (!r->in) {
1300 usb_packet_copy(p, r->buffer, size);
1302 ep = p->ep->nr | (r->in ? USB_DIR_IN : 0);
1303 if (p->stream) {
1304 #ifdef HAVE_STREAMS
1305 libusb_fill_bulk_stream_transfer(r->xfer, s->dh, ep, p->stream,
1306 r->buffer, size,
1307 usb_host_req_complete_data, r,
1308 BULK_TIMEOUT);
1309 #else
1310 usb_host_req_free(r);
1311 p->status = USB_RET_STALL;
1312 return;
1313 #endif
1314 } else {
1315 libusb_fill_bulk_transfer(r->xfer, s->dh, ep,
1316 r->buffer, size,
1317 usb_host_req_complete_data, r,
1318 BULK_TIMEOUT);
1320 break;
1321 case USB_ENDPOINT_XFER_INT:
1322 r = usb_host_req_alloc(s, p, p->pid == USB_TOKEN_IN, p->iov.size);
1323 if (!r->in) {
1324 usb_packet_copy(p, r->buffer, p->iov.size);
1326 ep = p->ep->nr | (r->in ? USB_DIR_IN : 0);
1327 libusb_fill_interrupt_transfer(r->xfer, s->dh, ep,
1328 r->buffer, p->iov.size,
1329 usb_host_req_complete_data, r,
1330 INTR_TIMEOUT);
1331 break;
1332 case USB_ENDPOINT_XFER_ISOC:
1333 if (p->pid == USB_TOKEN_IN) {
1334 usb_host_iso_data_in(s, p);
1335 } else {
1336 usb_host_iso_data_out(s, p);
1338 trace_usb_host_req_complete(s->bus_num, s->addr, p,
1339 p->status, p->actual_length);
1340 return;
1341 default:
1342 p->status = USB_RET_STALL;
1343 trace_usb_host_req_complete(s->bus_num, s->addr, p,
1344 p->status, p->actual_length);
1345 return;
1348 rc = libusb_submit_transfer(r->xfer);
1349 if (rc != 0) {
1350 p->status = USB_RET_NODEV;
1351 trace_usb_host_req_complete(s->bus_num, s->addr, p,
1352 p->status, p->actual_length);
1353 if (rc == LIBUSB_ERROR_NO_DEVICE) {
1354 usb_host_nodev(s);
1356 return;
1359 p->status = USB_RET_ASYNC;
1362 static void usb_host_flush_ep_queue(USBDevice *dev, USBEndpoint *ep)
1364 if (usb_host_use_combining(ep)) {
1365 usb_ep_combine_input_packets(ep);
1369 static void usb_host_handle_reset(USBDevice *udev)
1371 USBHostDevice *s = USB_HOST_DEVICE(udev);
1372 int rc;
1374 trace_usb_host_reset(s->bus_num, s->addr);
1376 rc = libusb_reset_device(s->dh);
1377 if (rc != 0) {
1378 usb_host_nodev(s);
1382 static int usb_host_alloc_streams(USBDevice *udev, USBEndpoint **eps,
1383 int nr_eps, int streams)
1385 #ifdef HAVE_STREAMS
1386 USBHostDevice *s = USB_HOST_DEVICE(udev);
1387 unsigned char endpoints[30];
1388 int i, rc;
1390 for (i = 0; i < nr_eps; i++) {
1391 endpoints[i] = eps[i]->nr;
1392 if (eps[i]->pid == USB_TOKEN_IN) {
1393 endpoints[i] |= 0x80;
1396 rc = libusb_alloc_streams(s->dh, streams, endpoints, nr_eps);
1397 if (rc < 0) {
1398 usb_host_libusb_error("libusb_alloc_streams", rc);
1399 } else if (rc != streams) {
1400 error_report("libusb_alloc_streams: got less streams "
1401 "then requested %d < %d", rc, streams);
1404 return (rc == streams) ? 0 : -1;
1405 #else
1406 error_report("libusb_alloc_streams: error not implemented");
1407 return -1;
1408 #endif
1411 static void usb_host_free_streams(USBDevice *udev, USBEndpoint **eps,
1412 int nr_eps)
1414 #ifdef HAVE_STREAMS
1415 USBHostDevice *s = USB_HOST_DEVICE(udev);
1416 unsigned char endpoints[30];
1417 int i;
1419 for (i = 0; i < nr_eps; i++) {
1420 endpoints[i] = eps[i]->nr;
1421 if (eps[i]->pid == USB_TOKEN_IN) {
1422 endpoints[i] |= 0x80;
1425 libusb_free_streams(s->dh, endpoints, nr_eps);
1426 #endif
1430 * This is *NOT* about restoring state. We have absolutely no idea
1431 * what state the host device is in at the moment and whenever it is
1432 * still present in the first place. Attemping to contine where we
1433 * left off is impossible.
1435 * What we are going to do here is emulate a surprise removal of
1436 * the usb device passed through, then kick host scan so the device
1437 * will get re-attached (and re-initialized by the guest) in case it
1438 * is still present.
1440 * As the device removal will change the state of other devices (usb
1441 * host controller, most likely interrupt controller too) we have to
1442 * wait with it until *all* vmstate is loaded. Thus post_load just
1443 * kicks a bottom half which then does the actual work.
1445 static void usb_host_post_load_bh(void *opaque)
1447 USBHostDevice *dev = opaque;
1448 USBDevice *udev = USB_DEVICE(dev);
1450 if (dev->dh != NULL) {
1451 usb_host_close(dev);
1453 if (udev->attached) {
1454 usb_device_detach(udev);
1456 usb_host_auto_check(NULL);
1459 static int usb_host_post_load(void *opaque, int version_id)
1461 USBHostDevice *dev = opaque;
1463 if (!dev->bh_postld) {
1464 dev->bh_postld = qemu_bh_new(usb_host_post_load_bh, dev);
1466 qemu_bh_schedule(dev->bh_postld);
1467 return 0;
1470 static const VMStateDescription vmstate_usb_host = {
1471 .name = "usb-host",
1472 .version_id = 1,
1473 .minimum_version_id = 1,
1474 .post_load = usb_host_post_load,
1475 .fields = (VMStateField[]) {
1476 VMSTATE_USB_DEVICE(parent_obj, USBHostDevice),
1477 VMSTATE_END_OF_LIST()
1481 static Property usb_host_dev_properties[] = {
1482 DEFINE_PROP_UINT32("hostbus", USBHostDevice, match.bus_num, 0),
1483 DEFINE_PROP_UINT32("hostaddr", USBHostDevice, match.addr, 0),
1484 DEFINE_PROP_STRING("hostport", USBHostDevice, match.port),
1485 DEFINE_PROP_UINT32("vendorid", USBHostDevice, match.vendor_id, 0),
1486 DEFINE_PROP_UINT32("productid", USBHostDevice, match.product_id, 0),
1487 DEFINE_PROP_UINT32("isobufs", USBHostDevice, iso_urb_count, 4),
1488 DEFINE_PROP_UINT32("isobsize", USBHostDevice, iso_urb_frames, 32),
1489 DEFINE_PROP_UINT32("loglevel", USBHostDevice, loglevel,
1490 LIBUSB_LOG_LEVEL_WARNING),
1491 DEFINE_PROP_BIT("pipeline", USBHostDevice, options,
1492 USB_HOST_OPT_PIPELINE, true),
1493 DEFINE_PROP_END_OF_LIST(),
1496 static void usb_host_class_initfn(ObjectClass *klass, void *data)
1498 DeviceClass *dc = DEVICE_CLASS(klass);
1499 USBDeviceClass *uc = USB_DEVICE_CLASS(klass);
1501 uc->realize = usb_host_realize;
1502 uc->product_desc = "USB Host Device";
1503 uc->cancel_packet = usb_host_cancel_packet;
1504 uc->handle_data = usb_host_handle_data;
1505 uc->handle_control = usb_host_handle_control;
1506 uc->handle_reset = usb_host_handle_reset;
1507 uc->handle_destroy = usb_host_handle_destroy;
1508 uc->flush_ep_queue = usb_host_flush_ep_queue;
1509 uc->alloc_streams = usb_host_alloc_streams;
1510 uc->free_streams = usb_host_free_streams;
1511 dc->vmsd = &vmstate_usb_host;
1512 dc->props = usb_host_dev_properties;
1513 set_bit(DEVICE_CATEGORY_BRIDGE, dc->categories);
1516 static TypeInfo usb_host_dev_info = {
1517 .name = TYPE_USB_HOST_DEVICE,
1518 .parent = TYPE_USB_DEVICE,
1519 .instance_size = sizeof(USBHostDevice),
1520 .class_init = usb_host_class_initfn,
1521 .instance_init = usb_host_instance_init,
1524 static void usb_host_register_types(void)
1526 type_register_static(&usb_host_dev_info);
1529 type_init(usb_host_register_types)
1531 /* ------------------------------------------------------------------------ */
1533 static QEMUTimer *usb_auto_timer;
1534 static VMChangeStateEntry *usb_vmstate;
1536 static void usb_host_vm_state(void *unused, int running, RunState state)
1538 if (running) {
1539 usb_host_auto_check(unused);
1543 static void usb_host_auto_check(void *unused)
1545 struct USBHostDevice *s;
1546 struct USBAutoFilter *f;
1547 libusb_device **devs = NULL;
1548 struct libusb_device_descriptor ddesc;
1549 int unconnected = 0;
1550 int i, n;
1552 if (usb_host_init() != 0) {
1553 return;
1556 if (runstate_is_running()) {
1557 n = libusb_get_device_list(ctx, &devs);
1558 for (i = 0; i < n; i++) {
1559 if (libusb_get_device_descriptor(devs[i], &ddesc) != 0) {
1560 continue;
1562 if (ddesc.bDeviceClass == LIBUSB_CLASS_HUB) {
1563 continue;
1565 QTAILQ_FOREACH(s, &hostdevs, next) {
1566 f = &s->match;
1567 if (f->bus_num > 0 &&
1568 f->bus_num != libusb_get_bus_number(devs[i])) {
1569 continue;
1571 if (f->addr > 0 &&
1572 f->addr != libusb_get_device_address(devs[i])) {
1573 continue;
1575 if (f->port != NULL) {
1576 char port[16] = "-";
1577 usb_host_get_port(devs[i], port, sizeof(port));
1578 if (strcmp(f->port, port) != 0) {
1579 continue;
1582 if (f->vendor_id > 0 &&
1583 f->vendor_id != ddesc.idVendor) {
1584 continue;
1586 if (f->product_id > 0 &&
1587 f->product_id != ddesc.idProduct) {
1588 continue;
1591 /* We got a match */
1592 s->seen++;
1593 if (s->errcount >= 3) {
1594 continue;
1596 if (s->dh != NULL) {
1597 continue;
1599 if (usb_host_open(s, devs[i]) < 0) {
1600 s->errcount++;
1601 continue;
1603 break;
1606 libusb_free_device_list(devs, 1);
1608 QTAILQ_FOREACH(s, &hostdevs, next) {
1609 if (s->dh == NULL) {
1610 unconnected++;
1612 if (s->seen == 0) {
1613 if (s->dh) {
1614 usb_host_close(s);
1616 s->errcount = 0;
1618 s->seen = 0;
1621 #if 0
1622 if (unconnected == 0) {
1623 /* nothing to watch */
1624 if (usb_auto_timer) {
1625 timer_del(usb_auto_timer);
1626 trace_usb_host_auto_scan_disabled();
1628 return;
1630 #endif
1633 if (!usb_vmstate) {
1634 usb_vmstate = qemu_add_vm_change_state_handler(usb_host_vm_state, NULL);
1636 if (!usb_auto_timer) {
1637 usb_auto_timer = timer_new_ms(QEMU_CLOCK_REALTIME, usb_host_auto_check, NULL);
1638 if (!usb_auto_timer) {
1639 return;
1641 trace_usb_host_auto_scan_enabled();
1643 timer_mod(usb_auto_timer, qemu_clock_get_ms(QEMU_CLOCK_REALTIME) + 2000);
1646 void hmp_info_usbhost(Monitor *mon, const QDict *qdict)
1648 libusb_device **devs = NULL;
1649 struct libusb_device_descriptor ddesc;
1650 char port[16];
1651 int i, n;
1653 if (usb_host_init() != 0) {
1654 return;
1657 n = libusb_get_device_list(ctx, &devs);
1658 for (i = 0; i < n; i++) {
1659 if (libusb_get_device_descriptor(devs[i], &ddesc) != 0) {
1660 continue;
1662 if (ddesc.bDeviceClass == LIBUSB_CLASS_HUB) {
1663 continue;
1665 usb_host_get_port(devs[i], port, sizeof(port));
1666 monitor_printf(mon, " Bus %d, Addr %d, Port %s, Speed %s Mb/s\n",
1667 libusb_get_bus_number(devs[i]),
1668 libusb_get_device_address(devs[i]),
1669 port,
1670 speed_name[libusb_get_device_speed(devs[i])]);
1671 monitor_printf(mon, " Class %02x:", ddesc.bDeviceClass);
1672 monitor_printf(mon, " USB device %04x:%04x",
1673 ddesc.idVendor, ddesc.idProduct);
1674 if (ddesc.iProduct) {
1675 libusb_device_handle *handle;
1676 if (libusb_open(devs[i], &handle) == 0) {
1677 unsigned char name[64] = "";
1678 libusb_get_string_descriptor_ascii(handle,
1679 ddesc.iProduct,
1680 name, sizeof(name));
1681 libusb_close(handle);
1682 monitor_printf(mon, ", %s", name);
1685 monitor_printf(mon, "\n");
1687 libusb_free_device_list(devs, 1);