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