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
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
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
39 #include "qemu-common.h"
40 #include "monitor/monitor.h"
41 #include "sysemu/sysemu.h"
46 /* ------------------------------------------------------------------------ */
48 #define TYPE_USB_HOST_DEVICE "usb-host"
49 #define USB_HOST_DEVICE(obj) \
50 OBJECT_CHECK(USBHostDevice, (obj), TYPE_USB_HOST_DEVICE)
52 typedef struct USBHostDevice USBHostDevice;
53 typedef struct USBHostRequest USBHostRequest;
54 typedef struct USBHostIsoXfer USBHostIsoXfer;
55 typedef struct USBHostIsoRing USBHostIsoRing;
57 struct USBAutoFilter {
65 enum USBHostDeviceOptions {
66 USB_HOST_OPT_PIPELINE,
69 struct USBHostDevice {
73 struct USBAutoFilter match;
75 uint32_t iso_urb_count;
76 uint32_t iso_urb_frames;
81 QTAILQ_ENTRY(USBHostDevice) next;
88 libusb_device_handle *dh;
89 struct libusb_device_descriptor ddesc;
94 } ifs[USB_MAX_INTERFACES];
96 /* callbacks & friends */
102 QTAILQ_HEAD(, USBHostRequest) requests;
103 QTAILQ_HEAD(, USBHostIsoRing) isorings;
106 struct USBHostRequest {
110 struct libusb_transfer *xfer;
111 unsigned char *buffer;
114 QTAILQ_ENTRY(USBHostRequest) next;
117 struct USBHostIsoXfer {
118 USBHostIsoRing *ring;
119 struct libusb_transfer *xfer;
122 QTAILQ_ENTRY(USBHostIsoXfer) next;
125 struct USBHostIsoRing {
128 QTAILQ_HEAD(, USBHostIsoXfer) unused;
129 QTAILQ_HEAD(, USBHostIsoXfer) inflight;
130 QTAILQ_HEAD(, USBHostIsoXfer) copy;
131 QTAILQ_ENTRY(USBHostIsoRing) next;
134 static QTAILQ_HEAD(, USBHostDevice) hostdevs =
135 QTAILQ_HEAD_INITIALIZER(hostdevs);
137 static void usb_host_auto_check(void *unused);
138 static void usb_host_release_interfaces(USBHostDevice *s);
139 static void usb_host_nodev(USBHostDevice *s);
140 static void usb_host_detach_kernel(USBHostDevice *s);
141 static void usb_host_attach_kernel(USBHostDevice *s);
143 /* ------------------------------------------------------------------------ */
145 #define CONTROL_TIMEOUT 10000 /* 10 sec */
146 #define BULK_TIMEOUT 0 /* unlimited */
147 #define INTR_TIMEOUT 0 /* unlimited */
149 static const char *speed_name[] = {
150 [LIBUSB_SPEED_UNKNOWN] = "?",
151 [LIBUSB_SPEED_LOW] = "1.5",
152 [LIBUSB_SPEED_FULL] = "12",
153 [LIBUSB_SPEED_HIGH] = "480",
154 [LIBUSB_SPEED_SUPER] = "5000",
157 static const unsigned int speed_map[] = {
158 [LIBUSB_SPEED_LOW] = USB_SPEED_LOW,
159 [LIBUSB_SPEED_FULL] = USB_SPEED_FULL,
160 [LIBUSB_SPEED_HIGH] = USB_SPEED_HIGH,
161 [LIBUSB_SPEED_SUPER] = USB_SPEED_SUPER,
164 static const unsigned int status_map[] = {
165 [LIBUSB_TRANSFER_COMPLETED] = USB_RET_SUCCESS,
166 [LIBUSB_TRANSFER_ERROR] = USB_RET_IOERROR,
167 [LIBUSB_TRANSFER_TIMED_OUT] = USB_RET_IOERROR,
168 [LIBUSB_TRANSFER_CANCELLED] = USB_RET_IOERROR,
169 [LIBUSB_TRANSFER_STALL] = USB_RET_STALL,
170 [LIBUSB_TRANSFER_NO_DEVICE] = USB_RET_NODEV,
171 [LIBUSB_TRANSFER_OVERFLOW] = USB_RET_BABBLE,
174 static const char *err_names[] = {
175 [-LIBUSB_ERROR_IO] = "IO",
176 [-LIBUSB_ERROR_INVALID_PARAM] = "INVALID_PARAM",
177 [-LIBUSB_ERROR_ACCESS] = "ACCESS",
178 [-LIBUSB_ERROR_NO_DEVICE] = "NO_DEVICE",
179 [-LIBUSB_ERROR_NOT_FOUND] = "NOT_FOUND",
180 [-LIBUSB_ERROR_BUSY] = "BUSY",
181 [-LIBUSB_ERROR_TIMEOUT] = "TIMEOUT",
182 [-LIBUSB_ERROR_OVERFLOW] = "OVERFLOW",
183 [-LIBUSB_ERROR_PIPE] = "PIPE",
184 [-LIBUSB_ERROR_INTERRUPTED] = "INTERRUPTED",
185 [-LIBUSB_ERROR_NO_MEM] = "NO_MEM",
186 [-LIBUSB_ERROR_NOT_SUPPORTED] = "NOT_SUPPORTED",
187 [-LIBUSB_ERROR_OTHER] = "OTHER",
190 static libusb_context *ctx;
191 static uint32_t loglevel;
193 static void usb_host_handle_fd(void *opaque)
195 struct timeval tv = { 0, 0 };
196 libusb_handle_events_timeout(ctx, &tv);
199 static void usb_host_add_fd(int fd, short events, void *user_data)
201 qemu_set_fd_handler(fd,
202 (events & POLLIN) ? usb_host_handle_fd : NULL,
203 (events & POLLOUT) ? usb_host_handle_fd : NULL,
207 static void usb_host_del_fd(int fd, void *user_data)
209 qemu_set_fd_handler(fd, NULL, NULL, NULL);
212 static int usb_host_init(void)
214 const struct libusb_pollfd **poll;
220 rc = libusb_init(&ctx);
224 libusb_set_debug(ctx, loglevel);
226 libusb_set_pollfd_notifiers(ctx, usb_host_add_fd,
229 poll = libusb_get_pollfds(ctx);
231 for (i = 0; poll[i] != NULL; i++) {
232 usb_host_add_fd(poll[i]->fd, poll[i]->events, ctx);
239 static int usb_host_get_port(libusb_device *dev, char *port, size_t len)
245 #if LIBUSBX_API_VERSION >= 0x01000102
246 rc = libusb_get_port_numbers(dev, path, 7);
248 rc = libusb_get_port_path(ctx, dev, path, 7);
253 off = snprintf(port, len, "%d", path[0]);
254 for (i = 1; i < rc; i++) {
255 off += snprintf(port+off, len-off, ".%d", path[i]);
260 static void usb_host_libusb_error(const char *func, int rc)
268 if (-rc < ARRAY_SIZE(err_names) && err_names[-rc]) {
269 errname = err_names[-rc];
273 fprintf(stderr, "%s: %d [%s]\n", func, rc, errname);
276 /* ------------------------------------------------------------------------ */
278 static bool usb_host_use_combining(USBEndpoint *ep)
285 if (ep->pid != USB_TOKEN_IN) {
288 type = usb_ep_get_type(ep->dev, ep->pid, ep->nr);
289 if (type != USB_ENDPOINT_XFER_BULK) {
295 /* ------------------------------------------------------------------------ */
297 static USBHostRequest *usb_host_req_alloc(USBHostDevice *s, USBPacket *p,
298 bool in, size_t bufsize)
300 USBHostRequest *r = g_new0(USBHostRequest, 1);
305 r->xfer = libusb_alloc_transfer(0);
307 r->buffer = g_malloc(bufsize);
309 QTAILQ_INSERT_TAIL(&s->requests, r, next);
313 static void usb_host_req_free(USBHostRequest *r)
316 QTAILQ_REMOVE(&r->host->requests, r, next);
318 libusb_free_transfer(r->xfer);
323 static USBHostRequest *usb_host_req_find(USBHostDevice *s, USBPacket *p)
327 QTAILQ_FOREACH(r, &s->requests, next) {
335 static void usb_host_req_complete_ctrl(struct libusb_transfer *xfer)
337 USBHostRequest *r = xfer->user_data;
338 USBHostDevice *s = r->host;
339 bool disconnect = (xfer->status == LIBUSB_TRANSFER_NO_DEVICE);
342 goto out; /* request was canceled */
345 r->p->status = status_map[xfer->status];
346 r->p->actual_length = xfer->actual_length;
347 if (r->in && xfer->actual_length) {
348 memcpy(r->cbuf, r->buffer + 8, xfer->actual_length);
350 trace_usb_host_req_complete(s->bus_num, s->addr, r->p,
351 r->p->status, r->p->actual_length);
352 usb_generic_async_ctrl_complete(USB_DEVICE(s), r->p);
355 usb_host_req_free(r);
361 static void usb_host_req_complete_data(struct libusb_transfer *xfer)
363 USBHostRequest *r = xfer->user_data;
364 USBHostDevice *s = r->host;
365 bool disconnect = (xfer->status == LIBUSB_TRANSFER_NO_DEVICE);
368 goto out; /* request was canceled */
371 r->p->status = status_map[xfer->status];
372 if (r->in && xfer->actual_length) {
373 usb_packet_copy(r->p, r->buffer, xfer->actual_length);
375 trace_usb_host_req_complete(s->bus_num, s->addr, r->p,
376 r->p->status, r->p->actual_length);
377 if (usb_host_use_combining(r->p->ep)) {
378 usb_combined_input_packet_complete(USB_DEVICE(s), r->p);
380 usb_packet_complete(USB_DEVICE(s), r->p);
384 usb_host_req_free(r);
390 static void usb_host_req_abort(USBHostRequest *r)
392 USBHostDevice *s = r->host;
393 bool inflight = (r->p && r->p->state == USB_PACKET_ASYNC);
396 r->p->status = USB_RET_NODEV;
397 trace_usb_host_req_complete(s->bus_num, s->addr, r->p,
398 r->p->status, r->p->actual_length);
399 if (r->p->ep->nr == 0) {
400 usb_generic_async_ctrl_complete(USB_DEVICE(s), r->p);
402 usb_packet_complete(USB_DEVICE(s), r->p);
407 QTAILQ_REMOVE(&r->host->requests, r, next);
411 libusb_cancel_transfer(r->xfer);
415 /* ------------------------------------------------------------------------ */
417 static void usb_host_req_complete_iso(struct libusb_transfer *transfer)
419 USBHostIsoXfer *xfer = transfer->user_data;
422 /* USBHostIsoXfer released while inflight */
423 g_free(transfer->buffer);
424 libusb_free_transfer(transfer);
428 QTAILQ_REMOVE(&xfer->ring->inflight, xfer, next);
429 if (QTAILQ_EMPTY(&xfer->ring->inflight)) {
430 USBHostDevice *s = xfer->ring->host;
431 trace_usb_host_iso_stop(s->bus_num, s->addr, xfer->ring->ep->nr);
433 if (xfer->ring->ep->pid == USB_TOKEN_IN) {
434 QTAILQ_INSERT_TAIL(&xfer->ring->copy, xfer, next);
436 QTAILQ_INSERT_TAIL(&xfer->ring->unused, xfer, next);
440 static USBHostIsoRing *usb_host_iso_alloc(USBHostDevice *s, USBEndpoint *ep)
442 USBHostIsoRing *ring = g_new0(USBHostIsoRing, 1);
443 USBHostIsoXfer *xfer;
444 /* FIXME: check interval (for now assume one xfer per frame) */
445 int packets = s->iso_urb_frames;
450 QTAILQ_INIT(&ring->unused);
451 QTAILQ_INIT(&ring->inflight);
452 QTAILQ_INIT(&ring->copy);
453 QTAILQ_INSERT_TAIL(&s->isorings, ring, next);
455 for (i = 0; i < s->iso_urb_count; i++) {
456 xfer = g_new0(USBHostIsoXfer, 1);
458 xfer->xfer = libusb_alloc_transfer(packets);
459 xfer->xfer->dev_handle = s->dh;
460 xfer->xfer->type = LIBUSB_TRANSFER_TYPE_ISOCHRONOUS;
462 xfer->xfer->endpoint = ring->ep->nr;
463 if (ring->ep->pid == USB_TOKEN_IN) {
464 xfer->xfer->endpoint |= USB_DIR_IN;
466 xfer->xfer->callback = usb_host_req_complete_iso;
467 xfer->xfer->user_data = xfer;
469 xfer->xfer->num_iso_packets = packets;
470 xfer->xfer->length = ring->ep->max_packet_size * packets;
471 xfer->xfer->buffer = g_malloc0(xfer->xfer->length);
473 QTAILQ_INSERT_TAIL(&ring->unused, xfer, next);
479 static USBHostIsoRing *usb_host_iso_find(USBHostDevice *s, USBEndpoint *ep)
481 USBHostIsoRing *ring;
483 QTAILQ_FOREACH(ring, &s->isorings, next) {
484 if (ring->ep == ep) {
491 static void usb_host_iso_reset_xfer(USBHostIsoXfer *xfer)
493 libusb_set_iso_packet_lengths(xfer->xfer,
494 xfer->ring->ep->max_packet_size);
496 xfer->copy_complete = false;
499 static void usb_host_iso_free_xfer(USBHostIsoXfer *xfer, bool inflight)
502 xfer->xfer->user_data = NULL;
504 g_free(xfer->xfer->buffer);
505 libusb_free_transfer(xfer->xfer);
510 static void usb_host_iso_free(USBHostIsoRing *ring)
512 USBHostIsoXfer *xfer;
514 while ((xfer = QTAILQ_FIRST(&ring->inflight)) != NULL) {
515 QTAILQ_REMOVE(&ring->inflight, xfer, next);
516 usb_host_iso_free_xfer(xfer, true);
518 while ((xfer = QTAILQ_FIRST(&ring->unused)) != NULL) {
519 QTAILQ_REMOVE(&ring->unused, xfer, next);
520 usb_host_iso_free_xfer(xfer, false);
522 while ((xfer = QTAILQ_FIRST(&ring->copy)) != NULL) {
523 QTAILQ_REMOVE(&ring->copy, xfer, next);
524 usb_host_iso_free_xfer(xfer, false);
527 QTAILQ_REMOVE(&ring->host->isorings, ring, next);
531 static void usb_host_iso_free_all(USBHostDevice *s)
533 USBHostIsoRing *ring;
535 while ((ring = QTAILQ_FIRST(&s->isorings)) != NULL) {
536 usb_host_iso_free(ring);
540 static bool usb_host_iso_data_copy(USBHostIsoXfer *xfer, USBPacket *p)
545 buf = libusb_get_iso_packet_buffer_simple(xfer->xfer, xfer->packet);
546 if (p->pid == USB_TOKEN_OUT) {
548 if (psize > xfer->ring->ep->max_packet_size) {
549 /* should not happen (guest bug) */
550 psize = xfer->ring->ep->max_packet_size;
552 xfer->xfer->iso_packet_desc[xfer->packet].length = psize;
554 psize = xfer->xfer->iso_packet_desc[xfer->packet].actual_length;
555 if (psize > p->iov.size) {
556 /* should not happen (guest bug) */
560 usb_packet_copy(p, buf, psize);
562 xfer->copy_complete = (xfer->packet == xfer->xfer->num_iso_packets);
563 return xfer->copy_complete;
566 static void usb_host_iso_data_in(USBHostDevice *s, USBPacket *p)
568 USBHostIsoRing *ring;
569 USBHostIsoXfer *xfer;
570 bool disconnect = false;
573 ring = usb_host_iso_find(s, p->ep);
575 ring = usb_host_iso_alloc(s, p->ep);
578 /* copy data to guest */
579 xfer = QTAILQ_FIRST(&ring->copy);
581 if (usb_host_iso_data_copy(xfer, p)) {
582 QTAILQ_REMOVE(&ring->copy, xfer, next);
583 QTAILQ_INSERT_TAIL(&ring->unused, xfer, next);
587 /* submit empty bufs to host */
588 while ((xfer = QTAILQ_FIRST(&ring->unused)) != NULL) {
589 QTAILQ_REMOVE(&ring->unused, xfer, next);
590 usb_host_iso_reset_xfer(xfer);
591 rc = libusb_submit_transfer(xfer->xfer);
593 usb_host_libusb_error("libusb_submit_transfer [iso]", rc);
594 QTAILQ_INSERT_TAIL(&ring->unused, xfer, next);
595 if (rc == LIBUSB_ERROR_NO_DEVICE) {
600 if (QTAILQ_EMPTY(&ring->inflight)) {
601 trace_usb_host_iso_start(s->bus_num, s->addr, p->ep->nr);
603 QTAILQ_INSERT_TAIL(&ring->inflight, xfer, next);
611 static void usb_host_iso_data_out(USBHostDevice *s, USBPacket *p)
613 USBHostIsoRing *ring;
614 USBHostIsoXfer *xfer;
615 bool disconnect = false;
618 ring = usb_host_iso_find(s, p->ep);
620 ring = usb_host_iso_alloc(s, p->ep);
623 /* copy data from guest */
624 xfer = QTAILQ_FIRST(&ring->copy);
625 while (xfer != NULL && xfer->copy_complete) {
627 xfer = QTAILQ_NEXT(xfer, next);
630 xfer = QTAILQ_FIRST(&ring->unused);
632 trace_usb_host_iso_out_of_bufs(s->bus_num, s->addr, p->ep->nr);
635 QTAILQ_REMOVE(&ring->unused, xfer, next);
636 usb_host_iso_reset_xfer(xfer);
637 QTAILQ_INSERT_TAIL(&ring->copy, xfer, next);
639 usb_host_iso_data_copy(xfer, p);
641 if (QTAILQ_EMPTY(&ring->inflight)) {
642 /* wait until half of our buffers are filled
643 before kicking the iso out stream */
644 if (filled*2 < s->iso_urb_count) {
649 /* submit filled bufs to host */
650 while ((xfer = QTAILQ_FIRST(&ring->copy)) != NULL &&
651 xfer->copy_complete) {
652 QTAILQ_REMOVE(&ring->copy, xfer, next);
653 rc = libusb_submit_transfer(xfer->xfer);
655 usb_host_libusb_error("libusb_submit_transfer [iso]", rc);
656 QTAILQ_INSERT_TAIL(&ring->unused, xfer, next);
657 if (rc == LIBUSB_ERROR_NO_DEVICE) {
662 if (QTAILQ_EMPTY(&ring->inflight)) {
663 trace_usb_host_iso_start(s->bus_num, s->addr, p->ep->nr);
665 QTAILQ_INSERT_TAIL(&ring->inflight, xfer, next);
673 /* ------------------------------------------------------------------------ */
675 static bool usb_host_full_speed_compat(USBHostDevice *s)
677 struct libusb_config_descriptor *conf;
678 const struct libusb_interface_descriptor *intf;
679 const struct libusb_endpoint_descriptor *endp;
684 rc = libusb_get_config_descriptor(s->dev, c, &conf);
688 for (i = 0; i < conf->bNumInterfaces; i++) {
689 for (a = 0; a < conf->interface[i].num_altsetting; a++) {
690 intf = &conf->interface[i].altsetting[a];
691 for (e = 0; e < intf->bNumEndpoints; e++) {
692 endp = &intf->endpoint[e];
693 type = endp->bmAttributes & 0x3;
697 case 0x03: /* INTERRUPT */
698 if (endp->wMaxPacketSize > 64) {
706 libusb_free_config_descriptor(conf);
711 static void usb_host_ep_update(USBHostDevice *s)
713 static const char *tname[] = {
714 [USB_ENDPOINT_XFER_CONTROL] = "control",
715 [USB_ENDPOINT_XFER_ISOC] = "isoc",
716 [USB_ENDPOINT_XFER_BULK] = "bulk",
717 [USB_ENDPOINT_XFER_INT] = "int",
719 USBDevice *udev = USB_DEVICE(s);
720 struct libusb_config_descriptor *conf;
721 const struct libusb_interface_descriptor *intf;
722 const struct libusb_endpoint_descriptor *endp;
723 #if LIBUSBX_API_VERSION >= 0x01000103
724 struct libusb_ss_endpoint_companion_descriptor *endp_ss_comp;
731 rc = libusb_get_active_config_descriptor(s->dev, &conf);
735 trace_usb_host_parse_config(s->bus_num, s->addr,
736 conf->bConfigurationValue, true);
738 for (i = 0; i < conf->bNumInterfaces; i++) {
739 assert(udev->altsetting[i] < conf->interface[i].num_altsetting);
740 intf = &conf->interface[i].altsetting[udev->altsetting[i]];
741 trace_usb_host_parse_interface(s->bus_num, s->addr,
742 intf->bInterfaceNumber,
743 intf->bAlternateSetting, true);
744 for (e = 0; e < intf->bNumEndpoints; e++) {
745 endp = &intf->endpoint[e];
747 devep = endp->bEndpointAddress;
748 pid = (devep & USB_DIR_IN) ? USB_TOKEN_IN : USB_TOKEN_OUT;
750 type = endp->bmAttributes & 0x3;
753 trace_usb_host_parse_error(s->bus_num, s->addr,
754 "invalid endpoint address");
757 if (usb_ep_get_type(udev, pid, ep) != USB_ENDPOINT_XFER_INVALID) {
758 trace_usb_host_parse_error(s->bus_num, s->addr,
759 "duplicate endpoint address");
763 trace_usb_host_parse_endpoint(s->bus_num, s->addr, ep,
764 (devep & USB_DIR_IN) ? "in" : "out",
766 usb_ep_set_max_packet_size(udev, pid, ep,
767 endp->wMaxPacketSize);
768 usb_ep_set_type(udev, pid, ep, type);
769 usb_ep_set_ifnum(udev, pid, ep, i);
770 usb_ep_set_halted(udev, pid, ep, 0);
771 #if LIBUSBX_API_VERSION >= 0x01000103
772 if (type == LIBUSB_TRANSFER_TYPE_BULK &&
773 libusb_get_ss_endpoint_companion_descriptor(ctx, endp,
774 &endp_ss_comp) == LIBUSB_SUCCESS) {
775 usb_ep_set_max_streams(udev, pid, ep,
776 endp_ss_comp->bmAttributes);
777 libusb_free_ss_endpoint_companion_descriptor(endp_ss_comp);
783 libusb_free_config_descriptor(conf);
786 static int usb_host_open(USBHostDevice *s, libusb_device *dev)
788 USBDevice *udev = USB_DEVICE(s);
789 int bus_num = libusb_get_bus_number(dev);
790 int addr = libusb_get_device_address(dev);
793 trace_usb_host_open_started(bus_num, addr);
798 rc = libusb_open(dev, &s->dh);
804 s->bus_num = bus_num;
807 usb_host_detach_kernel(s);
809 libusb_get_device_descriptor(dev, &s->ddesc);
810 usb_host_get_port(s->dev, s->port, sizeof(s->port));
813 usb_host_ep_update(s);
815 udev->speed = speed_map[libusb_get_device_speed(dev)];
816 udev->speedmask = (1 << udev->speed);
817 if (udev->speed == USB_SPEED_HIGH && usb_host_full_speed_compat(s)) {
818 udev->speedmask |= USB_SPEED_MASK_FULL;
821 if (s->ddesc.iProduct) {
822 libusb_get_string_descriptor_ascii(s->dh, s->ddesc.iProduct,
823 (unsigned char *)udev->product_desc,
824 sizeof(udev->product_desc));
826 snprintf(udev->product_desc, sizeof(udev->product_desc),
827 "host:%d.%d", bus_num, addr);
830 rc = usb_device_attach(udev);
835 trace_usb_host_open_success(bus_num, addr);
839 trace_usb_host_open_failure(bus_num, addr);
848 static void usb_host_abort_xfers(USBHostDevice *s)
850 USBHostRequest *r, *rtmp;
852 QTAILQ_FOREACH_SAFE(r, &s->requests, next, rtmp) {
853 usb_host_req_abort(r);
857 static int usb_host_close(USBHostDevice *s)
859 USBDevice *udev = USB_DEVICE(s);
865 trace_usb_host_close(s->bus_num, s->addr);
867 usb_host_abort_xfers(s);
868 usb_host_iso_free_all(s);
870 if (udev->attached) {
871 usb_device_detach(udev);
874 usb_host_release_interfaces(s);
875 libusb_reset_device(s->dh);
876 usb_host_attach_kernel(s);
881 usb_host_auto_check(NULL);
885 static void usb_host_nodev_bh(void *opaque)
887 USBHostDevice *s = opaque;
891 static void usb_host_nodev(USBHostDevice *s)
894 s->bh_nodev = qemu_bh_new(usb_host_nodev_bh, s);
896 qemu_bh_schedule(s->bh_nodev);
899 static void usb_host_exit_notifier(struct Notifier *n, void *data)
901 USBHostDevice *s = container_of(n, USBHostDevice, exit);
904 usb_host_release_interfaces(s);
905 usb_host_attach_kernel(s);
909 static int usb_host_initfn(USBDevice *udev)
911 USBHostDevice *s = USB_HOST_DEVICE(udev);
913 loglevel = s->loglevel;
914 udev->flags |= (1 << USB_DEV_FLAG_IS_HOST);
915 udev->auto_attach = 0;
916 QTAILQ_INIT(&s->requests);
917 QTAILQ_INIT(&s->isorings);
919 s->exit.notify = usb_host_exit_notifier;
920 qemu_add_exit_notifier(&s->exit);
922 QTAILQ_INSERT_TAIL(&hostdevs, s, next);
923 add_boot_device_path(s->bootindex, &udev->qdev, NULL);
924 usb_host_auto_check(NULL);
928 static void usb_host_handle_destroy(USBDevice *udev)
930 USBHostDevice *s = USB_HOST_DEVICE(udev);
932 qemu_remove_exit_notifier(&s->exit);
933 QTAILQ_REMOVE(&hostdevs, s, next);
937 static void usb_host_cancel_packet(USBDevice *udev, USBPacket *p)
939 USBHostDevice *s = USB_HOST_DEVICE(udev);
943 usb_combined_packet_cancel(udev, p);
947 trace_usb_host_req_canceled(s->bus_num, s->addr, p);
949 r = usb_host_req_find(s, p);
951 r->p = NULL; /* mark as dead */
952 libusb_cancel_transfer(r->xfer);
956 static void usb_host_detach_kernel(USBHostDevice *s)
958 struct libusb_config_descriptor *conf;
961 rc = libusb_get_active_config_descriptor(s->dev, &conf);
965 for (i = 0; i < conf->bNumInterfaces; i++) {
966 rc = libusb_kernel_driver_active(s->dh, i);
967 usb_host_libusb_error("libusb_kernel_driver_active", rc);
971 trace_usb_host_detach_kernel(s->bus_num, s->addr, i);
972 rc = libusb_detach_kernel_driver(s->dh, i);
973 usb_host_libusb_error("libusb_detach_kernel_driver", rc);
974 s->ifs[i].detached = true;
976 libusb_free_config_descriptor(conf);
979 static void usb_host_attach_kernel(USBHostDevice *s)
981 struct libusb_config_descriptor *conf;
984 rc = libusb_get_active_config_descriptor(s->dev, &conf);
988 for (i = 0; i < conf->bNumInterfaces; i++) {
989 if (!s->ifs[i].detached) {
992 trace_usb_host_attach_kernel(s->bus_num, s->addr, i);
993 libusb_attach_kernel_driver(s->dh, i);
994 s->ifs[i].detached = false;
996 libusb_free_config_descriptor(conf);
999 static int usb_host_claim_interfaces(USBHostDevice *s, int configuration)
1001 USBDevice *udev = USB_DEVICE(s);
1002 struct libusb_config_descriptor *conf;
1005 for (i = 0; i < USB_MAX_INTERFACES; i++) {
1006 udev->altsetting[i] = 0;
1008 udev->ninterfaces = 0;
1009 udev->configuration = 0;
1011 usb_host_detach_kernel(s);
1013 rc = libusb_get_active_config_descriptor(s->dev, &conf);
1015 if (rc == LIBUSB_ERROR_NOT_FOUND) {
1016 /* address state - ignore */
1017 return USB_RET_SUCCESS;
1019 return USB_RET_STALL;
1022 for (i = 0; i < conf->bNumInterfaces; i++) {
1023 trace_usb_host_claim_interface(s->bus_num, s->addr, configuration, i);
1024 rc = libusb_claim_interface(s->dh, i);
1025 usb_host_libusb_error("libusb_claim_interface", rc);
1027 return USB_RET_STALL;
1029 s->ifs[i].claimed = true;
1032 udev->ninterfaces = conf->bNumInterfaces;
1033 udev->configuration = configuration;
1035 libusb_free_config_descriptor(conf);
1036 return USB_RET_SUCCESS;
1039 static void usb_host_release_interfaces(USBHostDevice *s)
1041 USBDevice *udev = USB_DEVICE(s);
1044 for (i = 0; i < udev->ninterfaces; i++) {
1045 if (!s->ifs[i].claimed) {
1048 trace_usb_host_release_interface(s->bus_num, s->addr, i);
1049 rc = libusb_release_interface(s->dh, i);
1050 usb_host_libusb_error("libusb_release_interface", rc);
1051 s->ifs[i].claimed = false;
1055 static void usb_host_set_address(USBHostDevice *s, int addr)
1057 USBDevice *udev = USB_DEVICE(s);
1059 trace_usb_host_set_address(s->bus_num, s->addr, addr);
1063 static void usb_host_set_config(USBHostDevice *s, int config, USBPacket *p)
1067 trace_usb_host_set_config(s->bus_num, s->addr, config);
1069 usb_host_release_interfaces(s);
1070 rc = libusb_set_configuration(s->dh, config);
1072 usb_host_libusb_error("libusb_set_configuration", rc);
1073 p->status = USB_RET_STALL;
1074 if (rc == LIBUSB_ERROR_NO_DEVICE) {
1079 p->status = usb_host_claim_interfaces(s, config);
1080 if (p->status != USB_RET_SUCCESS) {
1083 usb_host_ep_update(s);
1086 static void usb_host_set_interface(USBHostDevice *s, int iface, int alt,
1089 USBDevice *udev = USB_DEVICE(s);
1092 trace_usb_host_set_interface(s->bus_num, s->addr, iface, alt);
1094 usb_host_iso_free_all(s);
1096 if (iface >= USB_MAX_INTERFACES) {
1097 p->status = USB_RET_STALL;
1101 rc = libusb_set_interface_alt_setting(s->dh, iface, alt);
1103 usb_host_libusb_error("libusb_set_interface_alt_setting", rc);
1104 p->status = USB_RET_STALL;
1105 if (rc == LIBUSB_ERROR_NO_DEVICE) {
1111 udev->altsetting[iface] = alt;
1112 usb_host_ep_update(s);
1115 static void usb_host_handle_control(USBDevice *udev, USBPacket *p,
1116 int request, int value, int index,
1117 int length, uint8_t *data)
1119 USBHostDevice *s = USB_HOST_DEVICE(udev);
1123 trace_usb_host_req_control(s->bus_num, s->addr, p, request, value, index);
1125 if (s->dh == NULL) {
1126 p->status = USB_RET_NODEV;
1127 trace_usb_host_req_emulated(s->bus_num, s->addr, p, p->status);
1132 case DeviceOutRequest | USB_REQ_SET_ADDRESS:
1133 usb_host_set_address(s, value);
1134 trace_usb_host_req_emulated(s->bus_num, s->addr, p, p->status);
1137 case DeviceOutRequest | USB_REQ_SET_CONFIGURATION:
1138 usb_host_set_config(s, value & 0xff, p);
1139 trace_usb_host_req_emulated(s->bus_num, s->addr, p, p->status);
1142 case InterfaceOutRequest | USB_REQ_SET_INTERFACE:
1143 usb_host_set_interface(s, index, value, p);
1144 trace_usb_host_req_emulated(s->bus_num, s->addr, p, p->status);
1147 case EndpointOutRequest | USB_REQ_CLEAR_FEATURE:
1148 if (value == 0) { /* clear halt */
1149 int pid = (index & USB_DIR_IN) ? USB_TOKEN_IN : USB_TOKEN_OUT;
1150 libusb_clear_halt(s->dh, index);
1151 usb_ep_set_halted(udev, pid, index & 0x0f, 0);
1152 trace_usb_host_req_emulated(s->bus_num, s->addr, p, p->status);
1157 r = usb_host_req_alloc(s, p, (request >> 8) & USB_DIR_IN, length + 8);
1160 memcpy(r->buffer, udev->setup_buf, 8);
1162 memcpy(r->buffer + 8, r->cbuf, r->clen);
1165 libusb_fill_control_transfer(r->xfer, s->dh, r->buffer,
1166 usb_host_req_complete_ctrl, r,
1168 rc = libusb_submit_transfer(r->xfer);
1170 p->status = USB_RET_NODEV;
1171 trace_usb_host_req_complete(s->bus_num, s->addr, p,
1172 p->status, p->actual_length);
1173 if (rc == LIBUSB_ERROR_NO_DEVICE) {
1179 p->status = USB_RET_ASYNC;
1182 static void usb_host_handle_data(USBDevice *udev, USBPacket *p)
1184 USBHostDevice *s = USB_HOST_DEVICE(udev);
1189 if (usb_host_use_combining(p->ep) && p->state == USB_PACKET_SETUP) {
1190 p->status = USB_RET_ADD_TO_QUEUE;
1194 trace_usb_host_req_data(s->bus_num, s->addr, p,
1195 p->pid == USB_TOKEN_IN,
1196 p->ep->nr, p->iov.size);
1198 if (s->dh == NULL) {
1199 p->status = USB_RET_NODEV;
1200 trace_usb_host_req_emulated(s->bus_num, s->addr, p, p->status);
1203 if (p->ep->halted) {
1204 p->status = USB_RET_STALL;
1205 trace_usb_host_req_emulated(s->bus_num, s->addr, p, p->status);
1209 switch (usb_ep_get_type(udev, p->pid, p->ep->nr)) {
1210 case USB_ENDPOINT_XFER_BULK:
1211 size = usb_packet_size(p);
1212 r = usb_host_req_alloc(s, p, p->pid == USB_TOKEN_IN, size);
1214 usb_packet_copy(p, r->buffer, size);
1216 ep = p->ep->nr | (r->in ? USB_DIR_IN : 0);
1218 #if LIBUSBX_API_VERSION >= 0x01000103
1219 libusb_fill_bulk_stream_transfer(r->xfer, s->dh, ep, p->stream,
1221 usb_host_req_complete_data, r,
1224 usb_host_req_free(r);
1225 p->status = USB_RET_STALL;
1229 libusb_fill_bulk_transfer(r->xfer, s->dh, ep,
1231 usb_host_req_complete_data, r,
1235 case USB_ENDPOINT_XFER_INT:
1236 r = usb_host_req_alloc(s, p, p->pid == USB_TOKEN_IN, p->iov.size);
1238 usb_packet_copy(p, r->buffer, p->iov.size);
1240 ep = p->ep->nr | (r->in ? USB_DIR_IN : 0);
1241 libusb_fill_interrupt_transfer(r->xfer, s->dh, ep,
1242 r->buffer, p->iov.size,
1243 usb_host_req_complete_data, r,
1246 case USB_ENDPOINT_XFER_ISOC:
1247 if (p->pid == USB_TOKEN_IN) {
1248 usb_host_iso_data_in(s, p);
1250 usb_host_iso_data_out(s, p);
1252 trace_usb_host_req_complete(s->bus_num, s->addr, p,
1253 p->status, p->actual_length);
1256 p->status = USB_RET_STALL;
1257 trace_usb_host_req_complete(s->bus_num, s->addr, p,
1258 p->status, p->actual_length);
1262 rc = libusb_submit_transfer(r->xfer);
1264 p->status = USB_RET_NODEV;
1265 trace_usb_host_req_complete(s->bus_num, s->addr, p,
1266 p->status, p->actual_length);
1267 if (rc == LIBUSB_ERROR_NO_DEVICE) {
1273 p->status = USB_RET_ASYNC;
1276 static void usb_host_flush_ep_queue(USBDevice *dev, USBEndpoint *ep)
1278 if (usb_host_use_combining(ep)) {
1279 usb_ep_combine_input_packets(ep);
1283 static void usb_host_handle_reset(USBDevice *udev)
1285 USBHostDevice *s = USB_HOST_DEVICE(udev);
1288 trace_usb_host_reset(s->bus_num, s->addr);
1290 rc = libusb_reset_device(s->dh);
1296 static int usb_host_alloc_streams(USBDevice *udev, USBEndpoint **eps,
1297 int nr_eps, int streams)
1299 #if LIBUSBX_API_VERSION >= 0x01000103
1300 USBHostDevice *s = USB_HOST_DEVICE(udev);
1301 unsigned char endpoints[30];
1304 for (i = 0; i < nr_eps; i++) {
1305 endpoints[i] = eps[i]->nr;
1306 if (eps[i]->pid == USB_TOKEN_IN) {
1307 endpoints[i] |= 0x80;
1310 rc = libusb_alloc_streams(s->dh, streams, endpoints, nr_eps);
1312 usb_host_libusb_error("libusb_alloc_streams", rc);
1313 } else if (rc != streams) {
1315 "libusb_alloc_streams: got less streams then requested %d < %d\n",
1319 return (rc == streams) ? 0 : -1;
1321 fprintf(stderr, "libusb_alloc_streams: error not implemented\n");
1326 static void usb_host_free_streams(USBDevice *udev, USBEndpoint **eps,
1329 #if LIBUSBX_API_VERSION >= 0x01000103
1330 USBHostDevice *s = USB_HOST_DEVICE(udev);
1331 unsigned char endpoints[30];
1334 for (i = 0; i < nr_eps; i++) {
1335 endpoints[i] = eps[i]->nr;
1336 if (eps[i]->pid == USB_TOKEN_IN) {
1337 endpoints[i] |= 0x80;
1340 libusb_free_streams(s->dh, endpoints, nr_eps);
1345 * This is *NOT* about restoring state. We have absolutely no idea
1346 * what state the host device is in at the moment and whenever it is
1347 * still present in the first place. Attemping to contine where we
1348 * left off is impossible.
1350 * What we are going to to to here is emulate a surprise removal of
1351 * the usb device passed through, then kick host scan so the device
1352 * will get re-attached (and re-initialized by the guest) in case it
1355 * As the device removal will change the state of other devices (usb
1356 * host controller, most likely interrupt controller too) we have to
1357 * wait with it until *all* vmstate is loaded. Thus post_load just
1358 * kicks a bottom half which then does the actual work.
1360 static void usb_host_post_load_bh(void *opaque)
1362 USBHostDevice *dev = opaque;
1363 USBDevice *udev = USB_DEVICE(dev);
1365 if (dev->dh != NULL) {
1366 usb_host_close(dev);
1368 if (udev->attached) {
1369 usb_device_detach(udev);
1371 usb_host_auto_check(NULL);
1374 static int usb_host_post_load(void *opaque, int version_id)
1376 USBHostDevice *dev = opaque;
1378 if (!dev->bh_postld) {
1379 dev->bh_postld = qemu_bh_new(usb_host_post_load_bh, dev);
1381 qemu_bh_schedule(dev->bh_postld);
1385 static const VMStateDescription vmstate_usb_host = {
1388 .minimum_version_id = 1,
1389 .post_load = usb_host_post_load,
1390 .fields = (VMStateField[]) {
1391 VMSTATE_USB_DEVICE(parent_obj, USBHostDevice),
1392 VMSTATE_END_OF_LIST()
1396 static Property usb_host_dev_properties[] = {
1397 DEFINE_PROP_UINT32("hostbus", USBHostDevice, match.bus_num, 0),
1398 DEFINE_PROP_UINT32("hostaddr", USBHostDevice, match.addr, 0),
1399 DEFINE_PROP_STRING("hostport", USBHostDevice, match.port),
1400 DEFINE_PROP_UINT32("vendorid", USBHostDevice, match.vendor_id, 0),
1401 DEFINE_PROP_UINT32("productid", USBHostDevice, match.product_id, 0),
1402 DEFINE_PROP_UINT32("isobufs", USBHostDevice, iso_urb_count, 4),
1403 DEFINE_PROP_UINT32("isobsize", USBHostDevice, iso_urb_frames, 32),
1404 DEFINE_PROP_INT32("bootindex", USBHostDevice, bootindex, -1),
1405 DEFINE_PROP_UINT32("loglevel", USBHostDevice, loglevel,
1406 LIBUSB_LOG_LEVEL_WARNING),
1407 DEFINE_PROP_BIT("pipeline", USBHostDevice, options,
1408 USB_HOST_OPT_PIPELINE, true),
1409 DEFINE_PROP_END_OF_LIST(),
1412 static void usb_host_class_initfn(ObjectClass *klass, void *data)
1414 DeviceClass *dc = DEVICE_CLASS(klass);
1415 USBDeviceClass *uc = USB_DEVICE_CLASS(klass);
1417 uc->init = usb_host_initfn;
1418 uc->product_desc = "USB Host Device";
1419 uc->cancel_packet = usb_host_cancel_packet;
1420 uc->handle_data = usb_host_handle_data;
1421 uc->handle_control = usb_host_handle_control;
1422 uc->handle_reset = usb_host_handle_reset;
1423 uc->handle_destroy = usb_host_handle_destroy;
1424 uc->flush_ep_queue = usb_host_flush_ep_queue;
1425 uc->alloc_streams = usb_host_alloc_streams;
1426 uc->free_streams = usb_host_free_streams;
1427 dc->vmsd = &vmstate_usb_host;
1428 dc->props = usb_host_dev_properties;
1429 set_bit(DEVICE_CATEGORY_BRIDGE, dc->categories);
1432 static TypeInfo usb_host_dev_info = {
1433 .name = TYPE_USB_HOST_DEVICE,
1434 .parent = TYPE_USB_DEVICE,
1435 .instance_size = sizeof(USBHostDevice),
1436 .class_init = usb_host_class_initfn,
1439 static void usb_host_register_types(void)
1441 type_register_static(&usb_host_dev_info);
1444 type_init(usb_host_register_types)
1446 /* ------------------------------------------------------------------------ */
1448 static QEMUTimer *usb_auto_timer;
1449 static VMChangeStateEntry *usb_vmstate;
1451 static void usb_host_vm_state(void *unused, int running, RunState state)
1454 usb_host_auto_check(unused);
1458 static void usb_host_auto_check(void *unused)
1460 struct USBHostDevice *s;
1461 struct USBAutoFilter *f;
1462 libusb_device **devs;
1463 struct libusb_device_descriptor ddesc;
1464 int unconnected = 0;
1467 if (usb_host_init() != 0) {
1471 if (runstate_is_running()) {
1472 n = libusb_get_device_list(ctx, &devs);
1473 for (i = 0; i < n; i++) {
1474 if (libusb_get_device_descriptor(devs[i], &ddesc) != 0) {
1477 if (ddesc.bDeviceClass == LIBUSB_CLASS_HUB) {
1480 QTAILQ_FOREACH(s, &hostdevs, next) {
1482 if (f->bus_num > 0 &&
1483 f->bus_num != libusb_get_bus_number(devs[i])) {
1487 f->addr != libusb_get_device_address(devs[i])) {
1490 if (f->port != NULL) {
1491 char port[16] = "-";
1492 usb_host_get_port(devs[i], port, sizeof(port));
1493 if (strcmp(f->port, port) != 0) {
1497 if (f->vendor_id > 0 &&
1498 f->vendor_id != ddesc.idVendor) {
1501 if (f->product_id > 0 &&
1502 f->product_id != ddesc.idProduct) {
1506 /* We got a match */
1508 if (s->errcount >= 3) {
1511 if (s->dh != NULL) {
1514 if (usb_host_open(s, devs[i]) < 0) {
1521 libusb_free_device_list(devs, 1);
1523 QTAILQ_FOREACH(s, &hostdevs, next) {
1524 if (s->dh == NULL) {
1537 if (unconnected == 0) {
1538 /* nothing to watch */
1539 if (usb_auto_timer) {
1540 timer_del(usb_auto_timer);
1541 trace_usb_host_auto_scan_disabled();
1549 usb_vmstate = qemu_add_vm_change_state_handler(usb_host_vm_state, NULL);
1551 if (!usb_auto_timer) {
1552 usb_auto_timer = timer_new_ms(QEMU_CLOCK_REALTIME, usb_host_auto_check, NULL);
1553 if (!usb_auto_timer) {
1556 trace_usb_host_auto_scan_enabled();
1558 timer_mod(usb_auto_timer, qemu_clock_get_ms(QEMU_CLOCK_REALTIME) + 2000);
1561 void usb_host_info(Monitor *mon, const QDict *qdict)
1563 libusb_device **devs;
1564 struct libusb_device_descriptor ddesc;
1568 if (usb_host_init() != 0) {
1572 n = libusb_get_device_list(ctx, &devs);
1573 for (i = 0; i < n; i++) {
1574 if (libusb_get_device_descriptor(devs[i], &ddesc) != 0) {
1577 if (ddesc.bDeviceClass == LIBUSB_CLASS_HUB) {
1580 usb_host_get_port(devs[i], port, sizeof(port));
1581 monitor_printf(mon, " Bus %d, Addr %d, Port %s, Speed %s Mb/s\n",
1582 libusb_get_bus_number(devs[i]),
1583 libusb_get_device_address(devs[i]),
1585 speed_name[libusb_get_device_speed(devs[i])]);
1586 monitor_printf(mon, " Class %02x:", ddesc.bDeviceClass);
1587 monitor_printf(mon, " USB device %04x:%04x",
1588 ddesc.idVendor, ddesc.idProduct);
1589 if (ddesc.iProduct) {
1590 libusb_device_handle *handle;
1591 if (libusb_open(devs[i], &handle) == 0) {
1592 unsigned char name[64] = "";
1593 libusb_get_string_descriptor_ascii(handle,
1595 name, sizeof(name));
1596 libusb_close(handle);
1597 monitor_printf(mon, ", %s", name);
1600 monitor_printf(mon, "\n");
1602 libusb_free_device_list(devs, 1);