Add qemu 2.4.0
[kvmfornfv.git] / qemu / 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 <poll.h>
37 #include <libusb.h>
38
39 #include "qemu-common.h"
40 #include "monitor/monitor.h"
41 #include "qemu/error-report.h"
42 #include "sysemu/sysemu.h"
43 #include "trace.h"
44
45 #include "hw/usb.h"
46
47 /* ------------------------------------------------------------------------ */
48
49 #define TYPE_USB_HOST_DEVICE "usb-host"
50 #define USB_HOST_DEVICE(obj) \
51      OBJECT_CHECK(USBHostDevice, (obj), TYPE_USB_HOST_DEVICE)
52
53 typedef struct USBHostDevice USBHostDevice;
54 typedef struct USBHostRequest USBHostRequest;
55 typedef struct USBHostIsoXfer USBHostIsoXfer;
56 typedef struct USBHostIsoRing USBHostIsoRing;
57
58 struct USBAutoFilter {
59     uint32_t bus_num;
60     uint32_t addr;
61     char     *port;
62     uint32_t vendor_id;
63     uint32_t product_id;
64 };
65
66 enum USBHostDeviceOptions {
67     USB_HOST_OPT_PIPELINE,
68 };
69
70 struct USBHostDevice {
71     USBDevice parent_obj;
72
73     /* properties */
74     struct USBAutoFilter             match;
75     int32_t                          bootindex;
76     uint32_t                         iso_urb_count;
77     uint32_t                         iso_urb_frames;
78     uint32_t                         options;
79     uint32_t                         loglevel;
80
81     /* state */
82     QTAILQ_ENTRY(USBHostDevice)      next;
83     int                              seen, errcount;
84     int                              bus_num;
85     int                              addr;
86     char                             port[16];
87
88     libusb_device                    *dev;
89     libusb_device_handle             *dh;
90     struct libusb_device_descriptor  ddesc;
91
92     struct {
93         bool                         detached;
94         bool                         claimed;
95     } ifs[USB_MAX_INTERFACES];
96
97     /* callbacks & friends */
98     QEMUBH                           *bh_nodev;
99     QEMUBH                           *bh_postld;
100     Notifier                         exit;
101
102     /* request queues */
103     QTAILQ_HEAD(, USBHostRequest)    requests;
104     QTAILQ_HEAD(, USBHostIsoRing)    isorings;
105 };
106
107 struct USBHostRequest {
108     USBHostDevice                    *host;
109     USBPacket                        *p;
110     bool                             in;
111     struct libusb_transfer           *xfer;
112     unsigned char                    *buffer;
113     unsigned char                    *cbuf;
114     unsigned int                     clen;
115     bool                             usb3ep0quirk;
116     QTAILQ_ENTRY(USBHostRequest)     next;
117 };
118
119 struct USBHostIsoXfer {
120     USBHostIsoRing                   *ring;
121     struct libusb_transfer           *xfer;
122     bool                             copy_complete;
123     unsigned int                     packet;
124     QTAILQ_ENTRY(USBHostIsoXfer)     next;
125 };
126
127 struct USBHostIsoRing {
128     USBHostDevice                    *host;
129     USBEndpoint                      *ep;
130     QTAILQ_HEAD(, USBHostIsoXfer)    unused;
131     QTAILQ_HEAD(, USBHostIsoXfer)    inflight;
132     QTAILQ_HEAD(, USBHostIsoXfer)    copy;
133     QTAILQ_ENTRY(USBHostIsoRing)     next;
134 };
135
136 static QTAILQ_HEAD(, USBHostDevice) hostdevs =
137     QTAILQ_HEAD_INITIALIZER(hostdevs);
138
139 static void usb_host_auto_check(void *unused);
140 static void usb_host_release_interfaces(USBHostDevice *s);
141 static void usb_host_nodev(USBHostDevice *s);
142 static void usb_host_detach_kernel(USBHostDevice *s);
143 static void usb_host_attach_kernel(USBHostDevice *s);
144
145 /* ------------------------------------------------------------------------ */
146
147 #ifndef LIBUSB_LOG_LEVEL_WARNING /* older libusb didn't define these */
148 #define LIBUSB_LOG_LEVEL_WARNING 2
149 #endif
150
151 /* ------------------------------------------------------------------------ */
152
153 #define CONTROL_TIMEOUT  10000        /* 10 sec    */
154 #define BULK_TIMEOUT         0        /* unlimited */
155 #define INTR_TIMEOUT         0        /* unlimited */
156
157 #if LIBUSBX_API_VERSION >= 0x01000103
158 # define HAVE_STREAMS 1
159 #endif
160
161 static const char *speed_name[] = {
162     [LIBUSB_SPEED_UNKNOWN] = "?",
163     [LIBUSB_SPEED_LOW]     = "1.5",
164     [LIBUSB_SPEED_FULL]    = "12",
165     [LIBUSB_SPEED_HIGH]    = "480",
166     [LIBUSB_SPEED_SUPER]   = "5000",
167 };
168
169 static const unsigned int speed_map[] = {
170     [LIBUSB_SPEED_LOW]     = USB_SPEED_LOW,
171     [LIBUSB_SPEED_FULL]    = USB_SPEED_FULL,
172     [LIBUSB_SPEED_HIGH]    = USB_SPEED_HIGH,
173     [LIBUSB_SPEED_SUPER]   = USB_SPEED_SUPER,
174 };
175
176 static const unsigned int status_map[] = {
177     [LIBUSB_TRANSFER_COMPLETED] = USB_RET_SUCCESS,
178     [LIBUSB_TRANSFER_ERROR]     = USB_RET_IOERROR,
179     [LIBUSB_TRANSFER_TIMED_OUT] = USB_RET_IOERROR,
180     [LIBUSB_TRANSFER_CANCELLED] = USB_RET_IOERROR,
181     [LIBUSB_TRANSFER_STALL]     = USB_RET_STALL,
182     [LIBUSB_TRANSFER_NO_DEVICE] = USB_RET_NODEV,
183     [LIBUSB_TRANSFER_OVERFLOW]  = USB_RET_BABBLE,
184 };
185
186 static const char *err_names[] = {
187     [-LIBUSB_ERROR_IO]               = "IO",
188     [-LIBUSB_ERROR_INVALID_PARAM]    = "INVALID_PARAM",
189     [-LIBUSB_ERROR_ACCESS]           = "ACCESS",
190     [-LIBUSB_ERROR_NO_DEVICE]        = "NO_DEVICE",
191     [-LIBUSB_ERROR_NOT_FOUND]        = "NOT_FOUND",
192     [-LIBUSB_ERROR_BUSY]             = "BUSY",
193     [-LIBUSB_ERROR_TIMEOUT]          = "TIMEOUT",
194     [-LIBUSB_ERROR_OVERFLOW]         = "OVERFLOW",
195     [-LIBUSB_ERROR_PIPE]             = "PIPE",
196     [-LIBUSB_ERROR_INTERRUPTED]      = "INTERRUPTED",
197     [-LIBUSB_ERROR_NO_MEM]           = "NO_MEM",
198     [-LIBUSB_ERROR_NOT_SUPPORTED]    = "NOT_SUPPORTED",
199     [-LIBUSB_ERROR_OTHER]            = "OTHER",
200 };
201
202 static libusb_context *ctx;
203 static uint32_t loglevel;
204
205 static void usb_host_handle_fd(void *opaque)
206 {
207     struct timeval tv = { 0, 0 };
208     libusb_handle_events_timeout(ctx, &tv);
209 }
210
211 static void usb_host_add_fd(int fd, short events, void *user_data)
212 {
213     qemu_set_fd_handler(fd,
214                         (events & POLLIN)  ? usb_host_handle_fd : NULL,
215                         (events & POLLOUT) ? usb_host_handle_fd : NULL,
216                         ctx);
217 }
218
219 static void usb_host_del_fd(int fd, void *user_data)
220 {
221     qemu_set_fd_handler(fd, NULL, NULL, NULL);
222 }
223
224 static int usb_host_init(void)
225 {
226     const struct libusb_pollfd **poll;
227     int i, rc;
228
229     if (ctx) {
230         return 0;
231     }
232     rc = libusb_init(&ctx);
233     if (rc != 0) {
234         return -1;
235     }
236     libusb_set_debug(ctx, loglevel);
237
238     libusb_set_pollfd_notifiers(ctx, usb_host_add_fd,
239                                 usb_host_del_fd,
240                                 ctx);
241     poll = libusb_get_pollfds(ctx);
242     if (poll) {
243         for (i = 0; poll[i] != NULL; i++) {
244             usb_host_add_fd(poll[i]->fd, poll[i]->events, ctx);
245         }
246     }
247     free(poll);
248     return 0;
249 }
250
251 static int usb_host_get_port(libusb_device *dev, char *port, size_t len)
252 {
253     uint8_t path[7];
254     size_t off;
255     int rc, i;
256
257 #if LIBUSBX_API_VERSION >= 0x01000102
258     rc = libusb_get_port_numbers(dev, path, 7);
259 #else
260     rc = libusb_get_port_path(ctx, dev, path, 7);
261 #endif
262     if (rc < 0) {
263         return 0;
264     }
265     off = snprintf(port, len, "%d", path[0]);
266     for (i = 1; i < rc; i++) {
267         off += snprintf(port+off, len-off, ".%d", path[i]);
268     }
269     return off;
270 }
271
272 static void usb_host_libusb_error(const char *func, int rc)
273 {
274     const char *errname;
275
276     if (rc >= 0) {
277         return;
278     }
279
280     if (-rc < ARRAY_SIZE(err_names) && err_names[-rc]) {
281         errname = err_names[-rc];
282     } else {
283         errname = "?";
284     }
285     error_report("%s: %d [%s]", func, rc, errname);
286 }
287
288 /* ------------------------------------------------------------------------ */
289
290 static bool usb_host_use_combining(USBEndpoint *ep)
291 {
292     int type;
293
294     if (!ep->pipeline) {
295         return false;
296     }
297     if (ep->pid != USB_TOKEN_IN) {
298         return false;
299     }
300     type = usb_ep_get_type(ep->dev, ep->pid, ep->nr);
301     if (type != USB_ENDPOINT_XFER_BULK) {
302         return false;
303     }
304     return true;
305 }
306
307 /* ------------------------------------------------------------------------ */
308
309 static USBHostRequest *usb_host_req_alloc(USBHostDevice *s, USBPacket *p,
310                                           bool in, size_t bufsize)
311 {
312     USBHostRequest *r = g_new0(USBHostRequest, 1);
313
314     r->host = s;
315     r->p = p;
316     r->in = in;
317     r->xfer = libusb_alloc_transfer(0);
318     if (bufsize) {
319         r->buffer = g_malloc(bufsize);
320     }
321     QTAILQ_INSERT_TAIL(&s->requests, r, next);
322     return r;
323 }
324
325 static void usb_host_req_free(USBHostRequest *r)
326 {
327     if (r->host) {
328         QTAILQ_REMOVE(&r->host->requests, r, next);
329     }
330     libusb_free_transfer(r->xfer);
331     g_free(r->buffer);
332     g_free(r);
333 }
334
335 static USBHostRequest *usb_host_req_find(USBHostDevice *s, USBPacket *p)
336 {
337     USBHostRequest *r;
338
339     QTAILQ_FOREACH(r, &s->requests, next) {
340         if (r->p == p) {
341             return r;
342         }
343     }
344     return NULL;
345 }
346
347 static void usb_host_req_complete_ctrl(struct libusb_transfer *xfer)
348 {
349     USBHostRequest *r = xfer->user_data;
350     USBHostDevice  *s = r->host;
351     bool disconnect = (xfer->status == LIBUSB_TRANSFER_NO_DEVICE);
352
353     if (r->p == NULL) {
354         goto out; /* request was canceled */
355     }
356
357     r->p->status = status_map[xfer->status];
358     r->p->actual_length = xfer->actual_length;
359     if (r->in && xfer->actual_length) {
360         memcpy(r->cbuf, r->buffer + 8, xfer->actual_length);
361
362         /* Fix up USB-3 ep0 maxpacket size to allow superspeed connected devices
363          * to work redirected to a not superspeed capable hcd */
364         if (r->usb3ep0quirk && xfer->actual_length >= 18 &&
365             r->cbuf[7] == 9) {
366             r->cbuf[7] = 64;
367         }
368     }
369     trace_usb_host_req_complete(s->bus_num, s->addr, r->p,
370                                 r->p->status, r->p->actual_length);
371     usb_generic_async_ctrl_complete(USB_DEVICE(s), r->p);
372
373 out:
374     usb_host_req_free(r);
375     if (disconnect) {
376         usb_host_nodev(s);
377     }
378 }
379
380 static void usb_host_req_complete_data(struct libusb_transfer *xfer)
381 {
382     USBHostRequest *r = xfer->user_data;
383     USBHostDevice  *s = r->host;
384     bool disconnect = (xfer->status == LIBUSB_TRANSFER_NO_DEVICE);
385
386     if (r->p == NULL) {
387         goto out; /* request was canceled */
388     }
389
390     r->p->status = status_map[xfer->status];
391     if (r->in && xfer->actual_length) {
392         usb_packet_copy(r->p, r->buffer, xfer->actual_length);
393     }
394     trace_usb_host_req_complete(s->bus_num, s->addr, r->p,
395                                 r->p->status, r->p->actual_length);
396     if (usb_host_use_combining(r->p->ep)) {
397         usb_combined_input_packet_complete(USB_DEVICE(s), r->p);
398     } else {
399         usb_packet_complete(USB_DEVICE(s), r->p);
400     }
401
402 out:
403     usb_host_req_free(r);
404     if (disconnect) {
405         usb_host_nodev(s);
406     }
407 }
408
409 static void usb_host_req_abort(USBHostRequest *r)
410 {
411     USBHostDevice  *s = r->host;
412     bool inflight = (r->p && r->p->state == USB_PACKET_ASYNC);
413
414     if (inflight) {
415         r->p->status = USB_RET_NODEV;
416         trace_usb_host_req_complete(s->bus_num, s->addr, r->p,
417                                     r->p->status, r->p->actual_length);
418         if (r->p->ep->nr == 0) {
419             usb_generic_async_ctrl_complete(USB_DEVICE(s), r->p);
420         } else {
421             usb_packet_complete(USB_DEVICE(s), r->p);
422         }
423         r->p = NULL;
424     }
425
426     QTAILQ_REMOVE(&r->host->requests, r, next);
427     r->host = NULL;
428
429     if (inflight) {
430         libusb_cancel_transfer(r->xfer);
431     }
432 }
433
434 /* ------------------------------------------------------------------------ */
435
436 static void usb_host_req_complete_iso(struct libusb_transfer *transfer)
437 {
438     USBHostIsoXfer *xfer = transfer->user_data;
439
440     if (!xfer) {
441         /* USBHostIsoXfer released while inflight */
442         g_free(transfer->buffer);
443         libusb_free_transfer(transfer);
444         return;
445     }
446
447     QTAILQ_REMOVE(&xfer->ring->inflight, xfer, next);
448     if (QTAILQ_EMPTY(&xfer->ring->inflight)) {
449         USBHostDevice *s = xfer->ring->host;
450         trace_usb_host_iso_stop(s->bus_num, s->addr, xfer->ring->ep->nr);
451     }
452     if (xfer->ring->ep->pid == USB_TOKEN_IN) {
453         QTAILQ_INSERT_TAIL(&xfer->ring->copy, xfer, next);
454     } else {
455         QTAILQ_INSERT_TAIL(&xfer->ring->unused, xfer, next);
456     }
457 }
458
459 static USBHostIsoRing *usb_host_iso_alloc(USBHostDevice *s, USBEndpoint *ep)
460 {
461     USBHostIsoRing *ring = g_new0(USBHostIsoRing, 1);
462     USBHostIsoXfer *xfer;
463     /* FIXME: check interval (for now assume one xfer per frame) */
464     int packets = s->iso_urb_frames;
465     int i;
466
467     ring->host = s;
468     ring->ep = ep;
469     QTAILQ_INIT(&ring->unused);
470     QTAILQ_INIT(&ring->inflight);
471     QTAILQ_INIT(&ring->copy);
472     QTAILQ_INSERT_TAIL(&s->isorings, ring, next);
473
474     for (i = 0; i < s->iso_urb_count; i++) {
475         xfer = g_new0(USBHostIsoXfer, 1);
476         xfer->ring = ring;
477         xfer->xfer = libusb_alloc_transfer(packets);
478         xfer->xfer->dev_handle = s->dh;
479         xfer->xfer->type = LIBUSB_TRANSFER_TYPE_ISOCHRONOUS;
480
481         xfer->xfer->endpoint = ring->ep->nr;
482         if (ring->ep->pid == USB_TOKEN_IN) {
483             xfer->xfer->endpoint |= USB_DIR_IN;
484         }
485         xfer->xfer->callback = usb_host_req_complete_iso;
486         xfer->xfer->user_data = xfer;
487
488         xfer->xfer->num_iso_packets = packets;
489         xfer->xfer->length = ring->ep->max_packet_size * packets;
490         xfer->xfer->buffer = g_malloc0(xfer->xfer->length);
491
492         QTAILQ_INSERT_TAIL(&ring->unused, xfer, next);
493     }
494
495     return ring;
496 }
497
498 static USBHostIsoRing *usb_host_iso_find(USBHostDevice *s, USBEndpoint *ep)
499 {
500     USBHostIsoRing *ring;
501
502     QTAILQ_FOREACH(ring, &s->isorings, next) {
503         if (ring->ep == ep) {
504             return ring;
505         }
506     }
507     return NULL;
508 }
509
510 static void usb_host_iso_reset_xfer(USBHostIsoXfer *xfer)
511 {
512     libusb_set_iso_packet_lengths(xfer->xfer,
513                                   xfer->ring->ep->max_packet_size);
514     xfer->packet = 0;
515     xfer->copy_complete = false;
516 }
517
518 static void usb_host_iso_free_xfer(USBHostIsoXfer *xfer, bool inflight)
519 {
520     if (inflight) {
521         xfer->xfer->user_data = NULL;
522     } else {
523         g_free(xfer->xfer->buffer);
524         libusb_free_transfer(xfer->xfer);
525     }
526     g_free(xfer);
527 }
528
529 static void usb_host_iso_free(USBHostIsoRing *ring)
530 {
531     USBHostIsoXfer *xfer;
532
533     while ((xfer = QTAILQ_FIRST(&ring->inflight)) != NULL) {
534         QTAILQ_REMOVE(&ring->inflight, xfer, next);
535         usb_host_iso_free_xfer(xfer, true);
536     }
537     while ((xfer = QTAILQ_FIRST(&ring->unused)) != NULL) {
538         QTAILQ_REMOVE(&ring->unused, xfer, next);
539         usb_host_iso_free_xfer(xfer, false);
540     }
541     while ((xfer = QTAILQ_FIRST(&ring->copy)) != NULL) {
542         QTAILQ_REMOVE(&ring->copy, xfer, next);
543         usb_host_iso_free_xfer(xfer, false);
544     }
545
546     QTAILQ_REMOVE(&ring->host->isorings, ring, next);
547     g_free(ring);
548 }
549
550 static void usb_host_iso_free_all(USBHostDevice *s)
551 {
552     USBHostIsoRing *ring;
553
554     while ((ring = QTAILQ_FIRST(&s->isorings)) != NULL) {
555         usb_host_iso_free(ring);
556     }
557 }
558
559 static bool usb_host_iso_data_copy(USBHostIsoXfer *xfer, USBPacket *p)
560 {
561     unsigned int psize;
562     unsigned char *buf;
563
564     buf = libusb_get_iso_packet_buffer_simple(xfer->xfer, xfer->packet);
565     if (p->pid == USB_TOKEN_OUT) {
566         psize = p->iov.size;
567         if (psize > xfer->ring->ep->max_packet_size) {
568             /* should not happen (guest bug) */
569             psize = xfer->ring->ep->max_packet_size;
570         }
571         xfer->xfer->iso_packet_desc[xfer->packet].length = psize;
572     } else {
573         psize = xfer->xfer->iso_packet_desc[xfer->packet].actual_length;
574         if (psize > p->iov.size) {
575             /* should not happen (guest bug) */
576             psize = p->iov.size;
577         }
578     }
579     usb_packet_copy(p, buf, psize);
580     xfer->packet++;
581     xfer->copy_complete = (xfer->packet == xfer->xfer->num_iso_packets);
582     return xfer->copy_complete;
583 }
584
585 static void usb_host_iso_data_in(USBHostDevice *s, USBPacket *p)
586 {
587     USBHostIsoRing *ring;
588     USBHostIsoXfer *xfer;
589     bool disconnect = false;
590     int rc;
591
592     ring = usb_host_iso_find(s, p->ep);
593     if (ring == NULL) {
594         ring = usb_host_iso_alloc(s, p->ep);
595     }
596
597     /* copy data to guest */
598     xfer = QTAILQ_FIRST(&ring->copy);
599     if (xfer != NULL) {
600         if (usb_host_iso_data_copy(xfer, p)) {
601             QTAILQ_REMOVE(&ring->copy, xfer, next);
602             QTAILQ_INSERT_TAIL(&ring->unused, xfer, next);
603         }
604     }
605
606     /* submit empty bufs to host */
607     while ((xfer = QTAILQ_FIRST(&ring->unused)) != NULL) {
608         QTAILQ_REMOVE(&ring->unused, xfer, next);
609         usb_host_iso_reset_xfer(xfer);
610         rc = libusb_submit_transfer(xfer->xfer);
611         if (rc != 0) {
612             usb_host_libusb_error("libusb_submit_transfer [iso]", rc);
613             QTAILQ_INSERT_TAIL(&ring->unused, xfer, next);
614             if (rc == LIBUSB_ERROR_NO_DEVICE) {
615                 disconnect = true;
616             }
617             break;
618         }
619         if (QTAILQ_EMPTY(&ring->inflight)) {
620             trace_usb_host_iso_start(s->bus_num, s->addr, p->ep->nr);
621         }
622         QTAILQ_INSERT_TAIL(&ring->inflight, xfer, next);
623     }
624
625     if (disconnect) {
626         usb_host_nodev(s);
627     }
628 }
629
630 static void usb_host_iso_data_out(USBHostDevice *s, USBPacket *p)
631 {
632     USBHostIsoRing *ring;
633     USBHostIsoXfer *xfer;
634     bool disconnect = false;
635     int rc, filled = 0;
636
637     ring = usb_host_iso_find(s, p->ep);
638     if (ring == NULL) {
639         ring = usb_host_iso_alloc(s, p->ep);
640     }
641
642     /* copy data from guest */
643     xfer = QTAILQ_FIRST(&ring->copy);
644     while (xfer != NULL && xfer->copy_complete) {
645         filled++;
646         xfer = QTAILQ_NEXT(xfer, next);
647     }
648     if (xfer == NULL) {
649         xfer = QTAILQ_FIRST(&ring->unused);
650         if (xfer == NULL) {
651             trace_usb_host_iso_out_of_bufs(s->bus_num, s->addr, p->ep->nr);
652             return;
653         }
654         QTAILQ_REMOVE(&ring->unused, xfer, next);
655         usb_host_iso_reset_xfer(xfer);
656         QTAILQ_INSERT_TAIL(&ring->copy, xfer, next);
657     }
658     usb_host_iso_data_copy(xfer, p);
659
660     if (QTAILQ_EMPTY(&ring->inflight)) {
661         /* wait until half of our buffers are filled
662            before kicking the iso out stream */
663         if (filled*2 < s->iso_urb_count) {
664             return;
665         }
666     }
667
668     /* submit filled bufs to host */
669     while ((xfer = QTAILQ_FIRST(&ring->copy)) != NULL &&
670            xfer->copy_complete) {
671         QTAILQ_REMOVE(&ring->copy, xfer, next);
672         rc = libusb_submit_transfer(xfer->xfer);
673         if (rc != 0) {
674             usb_host_libusb_error("libusb_submit_transfer [iso]", rc);
675             QTAILQ_INSERT_TAIL(&ring->unused, xfer, next);
676             if (rc == LIBUSB_ERROR_NO_DEVICE) {
677                 disconnect = true;
678             }
679             break;
680         }
681         if (QTAILQ_EMPTY(&ring->inflight)) {
682             trace_usb_host_iso_start(s->bus_num, s->addr, p->ep->nr);
683         }
684         QTAILQ_INSERT_TAIL(&ring->inflight, xfer, next);
685     }
686
687     if (disconnect) {
688         usb_host_nodev(s);
689     }
690 }
691
692 /* ------------------------------------------------------------------------ */
693
694 static void usb_host_speed_compat(USBHostDevice *s)
695 {
696     USBDevice *udev = USB_DEVICE(s);
697     struct libusb_config_descriptor *conf;
698     const struct libusb_interface_descriptor *intf;
699     const struct libusb_endpoint_descriptor *endp;
700 #ifdef HAVE_STREAMS
701     struct libusb_ss_endpoint_companion_descriptor *endp_ss_comp;
702 #endif
703     bool compat_high = true;
704     bool compat_full = true;
705     uint8_t type;
706     int rc, c, i, a, e;
707
708     for (c = 0;; c++) {
709         rc = libusb_get_config_descriptor(s->dev, c, &conf);
710         if (rc != 0) {
711             break;
712         }
713         for (i = 0; i < conf->bNumInterfaces; i++) {
714             for (a = 0; a < conf->interface[i].num_altsetting; a++) {
715                 intf = &conf->interface[i].altsetting[a];
716                 for (e = 0; e < intf->bNumEndpoints; e++) {
717                     endp = &intf->endpoint[e];
718                     type = endp->bmAttributes & 0x3;
719                     switch (type) {
720                     case 0x01: /* ISO */
721                         compat_full = false;
722                         compat_high = false;
723                         break;
724                     case 0x02: /* BULK */
725 #ifdef HAVE_STREAMS
726                         rc = libusb_get_ss_endpoint_companion_descriptor
727                             (ctx, endp, &endp_ss_comp);
728                         if (rc == LIBUSB_SUCCESS) {
729                             libusb_free_ss_endpoint_companion_descriptor
730                                 (endp_ss_comp);
731                             compat_full = false;
732                             compat_high = false;
733                         }
734 #endif
735                         break;
736                     case 0x03: /* INTERRUPT */
737                         if (endp->wMaxPacketSize > 64) {
738                             compat_full = false;
739                         }
740                         if (endp->wMaxPacketSize > 1024) {
741                             compat_high = false;
742                         }
743                         break;
744                     }
745                 }
746             }
747         }
748         libusb_free_config_descriptor(conf);
749     }
750
751     udev->speedmask = (1 << udev->speed);
752     if (udev->speed == USB_SPEED_SUPER && compat_high) {
753         udev->speedmask |= USB_SPEED_MASK_HIGH;
754     }
755     if (udev->speed == USB_SPEED_SUPER && compat_full) {
756         udev->speedmask |= USB_SPEED_MASK_FULL;
757     }
758     if (udev->speed == USB_SPEED_HIGH && compat_full) {
759         udev->speedmask |= USB_SPEED_MASK_FULL;
760     }
761 }
762
763 static void usb_host_ep_update(USBHostDevice *s)
764 {
765     static const char *tname[] = {
766         [USB_ENDPOINT_XFER_CONTROL] = "control",
767         [USB_ENDPOINT_XFER_ISOC]    = "isoc",
768         [USB_ENDPOINT_XFER_BULK]    = "bulk",
769         [USB_ENDPOINT_XFER_INT]     = "int",
770     };
771     USBDevice *udev = USB_DEVICE(s);
772     struct libusb_config_descriptor *conf;
773     const struct libusb_interface_descriptor *intf;
774     const struct libusb_endpoint_descriptor *endp;
775 #ifdef HAVE_STREAMS
776     struct libusb_ss_endpoint_companion_descriptor *endp_ss_comp;
777 #endif
778     uint8_t devep, type;
779     int pid, ep;
780     int rc, i, e;
781
782     usb_ep_reset(udev);
783     rc = libusb_get_active_config_descriptor(s->dev, &conf);
784     if (rc != 0) {
785         return;
786     }
787     trace_usb_host_parse_config(s->bus_num, s->addr,
788                                 conf->bConfigurationValue, true);
789
790     for (i = 0; i < conf->bNumInterfaces; i++) {
791         assert(udev->altsetting[i] < conf->interface[i].num_altsetting);
792         intf = &conf->interface[i].altsetting[udev->altsetting[i]];
793         trace_usb_host_parse_interface(s->bus_num, s->addr,
794                                        intf->bInterfaceNumber,
795                                        intf->bAlternateSetting, true);
796         for (e = 0; e < intf->bNumEndpoints; e++) {
797             endp = &intf->endpoint[e];
798
799             devep = endp->bEndpointAddress;
800             pid = (devep & USB_DIR_IN) ? USB_TOKEN_IN : USB_TOKEN_OUT;
801             ep = devep & 0xf;
802             type = endp->bmAttributes & 0x3;
803
804             if (ep == 0) {
805                 trace_usb_host_parse_error(s->bus_num, s->addr,
806                                            "invalid endpoint address");
807                 return;
808             }
809             if (usb_ep_get_type(udev, pid, ep) != USB_ENDPOINT_XFER_INVALID) {
810                 trace_usb_host_parse_error(s->bus_num, s->addr,
811                                            "duplicate endpoint address");
812                 return;
813             }
814
815             trace_usb_host_parse_endpoint(s->bus_num, s->addr, ep,
816                                           (devep & USB_DIR_IN) ? "in" : "out",
817                                           tname[type], true);
818             usb_ep_set_max_packet_size(udev, pid, ep,
819                                        endp->wMaxPacketSize);
820             usb_ep_set_type(udev, pid, ep, type);
821             usb_ep_set_ifnum(udev, pid, ep, i);
822             usb_ep_set_halted(udev, pid, ep, 0);
823 #ifdef HAVE_STREAMS
824             if (type == LIBUSB_TRANSFER_TYPE_BULK &&
825                     libusb_get_ss_endpoint_companion_descriptor(ctx, endp,
826                         &endp_ss_comp) == LIBUSB_SUCCESS) {
827                 usb_ep_set_max_streams(udev, pid, ep,
828                                        endp_ss_comp->bmAttributes);
829                 libusb_free_ss_endpoint_companion_descriptor(endp_ss_comp);
830             }
831 #endif
832         }
833     }
834
835     libusb_free_config_descriptor(conf);
836 }
837
838 static int usb_host_open(USBHostDevice *s, libusb_device *dev)
839 {
840     USBDevice *udev = USB_DEVICE(s);
841     int bus_num = libusb_get_bus_number(dev);
842     int addr    = libusb_get_device_address(dev);
843     int rc;
844     Error *local_err = NULL;
845
846     trace_usb_host_open_started(bus_num, addr);
847
848     if (s->dh != NULL) {
849         goto fail;
850     }
851     rc = libusb_open(dev, &s->dh);
852     if (rc != 0) {
853         goto fail;
854     }
855
856     s->dev     = dev;
857     s->bus_num = bus_num;
858     s->addr    = addr;
859
860     usb_host_detach_kernel(s);
861
862     libusb_get_device_descriptor(dev, &s->ddesc);
863     usb_host_get_port(s->dev, s->port, sizeof(s->port));
864
865     usb_ep_init(udev);
866     usb_host_ep_update(s);
867
868     udev->speed     = speed_map[libusb_get_device_speed(dev)];
869     usb_host_speed_compat(s);
870
871     if (s->ddesc.iProduct) {
872         libusb_get_string_descriptor_ascii(s->dh, s->ddesc.iProduct,
873                                            (unsigned char *)udev->product_desc,
874                                            sizeof(udev->product_desc));
875     } else {
876         snprintf(udev->product_desc, sizeof(udev->product_desc),
877                  "host:%d.%d", bus_num, addr);
878     }
879
880     usb_device_attach(udev, &local_err);
881     if (local_err) {
882         error_report_err(local_err);
883         goto fail;
884     }
885
886     trace_usb_host_open_success(bus_num, addr);
887     return 0;
888
889 fail:
890     trace_usb_host_open_failure(bus_num, addr);
891     if (s->dh != NULL) {
892         usb_host_release_interfaces(s);
893         libusb_reset_device(s->dh);
894         usb_host_attach_kernel(s);
895         libusb_close(s->dh);
896         s->dh = NULL;
897         s->dev = NULL;
898     }
899     return -1;
900 }
901
902 static void usb_host_abort_xfers(USBHostDevice *s)
903 {
904     USBHostRequest *r, *rtmp;
905
906     QTAILQ_FOREACH_SAFE(r, &s->requests, next, rtmp) {
907         usb_host_req_abort(r);
908     }
909 }
910
911 static int usb_host_close(USBHostDevice *s)
912 {
913     USBDevice *udev = USB_DEVICE(s);
914
915     if (s->dh == NULL) {
916         return -1;
917     }
918
919     trace_usb_host_close(s->bus_num, s->addr);
920
921     usb_host_abort_xfers(s);
922     usb_host_iso_free_all(s);
923
924     if (udev->attached) {
925         usb_device_detach(udev);
926     }
927
928     usb_host_release_interfaces(s);
929     libusb_reset_device(s->dh);
930     usb_host_attach_kernel(s);
931     libusb_close(s->dh);
932     s->dh = NULL;
933     s->dev = NULL;
934
935     usb_host_auto_check(NULL);
936     return 0;
937 }
938
939 static void usb_host_nodev_bh(void *opaque)
940 {
941     USBHostDevice *s = opaque;
942     usb_host_close(s);
943 }
944
945 static void usb_host_nodev(USBHostDevice *s)
946 {
947     if (!s->bh_nodev) {
948         s->bh_nodev = qemu_bh_new(usb_host_nodev_bh, s);
949     }
950     qemu_bh_schedule(s->bh_nodev);
951 }
952
953 static void usb_host_exit_notifier(struct Notifier *n, void *data)
954 {
955     USBHostDevice *s = container_of(n, USBHostDevice, exit);
956
957     if (s->dh) {
958         usb_host_release_interfaces(s);
959         usb_host_attach_kernel(s);
960     }
961 }
962
963 static void usb_host_realize(USBDevice *udev, Error **errp)
964 {
965     USBHostDevice *s = USB_HOST_DEVICE(udev);
966
967     if (s->match.vendor_id > 0xffff) {
968         error_setg(errp, "vendorid out of range");
969         return;
970     }
971     if (s->match.product_id > 0xffff) {
972         error_setg(errp, "productid out of range");
973         return;
974     }
975     if (s->match.addr > 127) {
976         error_setg(errp, "hostaddr out of range");
977         return;
978     }
979
980     loglevel = s->loglevel;
981     udev->flags |= (1 << USB_DEV_FLAG_IS_HOST);
982     udev->auto_attach = 0;
983     QTAILQ_INIT(&s->requests);
984     QTAILQ_INIT(&s->isorings);
985
986     s->exit.notify = usb_host_exit_notifier;
987     qemu_add_exit_notifier(&s->exit);
988
989     QTAILQ_INSERT_TAIL(&hostdevs, s, next);
990     usb_host_auto_check(NULL);
991 }
992
993 static void usb_host_instance_init(Object *obj)
994 {
995     USBDevice *udev = USB_DEVICE(obj);
996     USBHostDevice *s = USB_HOST_DEVICE(udev);
997
998     device_add_bootindex_property(obj, &s->bootindex,
999                                   "bootindex", NULL,
1000                                   &udev->qdev, NULL);
1001 }
1002
1003 static void usb_host_handle_destroy(USBDevice *udev)
1004 {
1005     USBHostDevice *s = USB_HOST_DEVICE(udev);
1006
1007     qemu_remove_exit_notifier(&s->exit);
1008     QTAILQ_REMOVE(&hostdevs, s, next);
1009     usb_host_close(s);
1010 }
1011
1012 static void usb_host_cancel_packet(USBDevice *udev, USBPacket *p)
1013 {
1014     USBHostDevice *s = USB_HOST_DEVICE(udev);
1015     USBHostRequest *r;
1016
1017     if (p->combined) {
1018         usb_combined_packet_cancel(udev, p);
1019         return;
1020     }
1021
1022     trace_usb_host_req_canceled(s->bus_num, s->addr, p);
1023
1024     r = usb_host_req_find(s, p);
1025     if (r && r->p) {
1026         r->p = NULL; /* mark as dead */
1027         libusb_cancel_transfer(r->xfer);
1028     }
1029 }
1030
1031 static void usb_host_detach_kernel(USBHostDevice *s)
1032 {
1033     struct libusb_config_descriptor *conf;
1034     int rc, i;
1035
1036     rc = libusb_get_active_config_descriptor(s->dev, &conf);
1037     if (rc != 0) {
1038         return;
1039     }
1040     for (i = 0; i < conf->bNumInterfaces; i++) {
1041         rc = libusb_kernel_driver_active(s->dh, i);
1042         usb_host_libusb_error("libusb_kernel_driver_active", rc);
1043         if (rc != 1) {
1044             continue;
1045         }
1046         trace_usb_host_detach_kernel(s->bus_num, s->addr, i);
1047         rc = libusb_detach_kernel_driver(s->dh, i);
1048         usb_host_libusb_error("libusb_detach_kernel_driver", rc);
1049         s->ifs[i].detached = true;
1050     }
1051     libusb_free_config_descriptor(conf);
1052 }
1053
1054 static void usb_host_attach_kernel(USBHostDevice *s)
1055 {
1056     struct libusb_config_descriptor *conf;
1057     int rc, i;
1058
1059     rc = libusb_get_active_config_descriptor(s->dev, &conf);
1060     if (rc != 0) {
1061         return;
1062     }
1063     for (i = 0; i < conf->bNumInterfaces; i++) {
1064         if (!s->ifs[i].detached) {
1065             continue;
1066         }
1067         trace_usb_host_attach_kernel(s->bus_num, s->addr, i);
1068         libusb_attach_kernel_driver(s->dh, i);
1069         s->ifs[i].detached = false;
1070     }
1071     libusb_free_config_descriptor(conf);
1072 }
1073
1074 static int usb_host_claim_interfaces(USBHostDevice *s, int configuration)
1075 {
1076     USBDevice *udev = USB_DEVICE(s);
1077     struct libusb_config_descriptor *conf;
1078     int rc, i;
1079
1080     for (i = 0; i < USB_MAX_INTERFACES; i++) {
1081         udev->altsetting[i] = 0;
1082     }
1083     udev->ninterfaces   = 0;
1084     udev->configuration = 0;
1085
1086     usb_host_detach_kernel(s);
1087
1088     rc = libusb_get_active_config_descriptor(s->dev, &conf);
1089     if (rc != 0) {
1090         if (rc == LIBUSB_ERROR_NOT_FOUND) {
1091             /* address state - ignore */
1092             return USB_RET_SUCCESS;
1093         }
1094         return USB_RET_STALL;
1095     }
1096
1097     for (i = 0; i < conf->bNumInterfaces; i++) {
1098         trace_usb_host_claim_interface(s->bus_num, s->addr, configuration, i);
1099         rc = libusb_claim_interface(s->dh, i);
1100         usb_host_libusb_error("libusb_claim_interface", rc);
1101         if (rc != 0) {
1102             return USB_RET_STALL;
1103         }
1104         s->ifs[i].claimed = true;
1105     }
1106
1107     udev->ninterfaces   = conf->bNumInterfaces;
1108     udev->configuration = configuration;
1109
1110     libusb_free_config_descriptor(conf);
1111     return USB_RET_SUCCESS;
1112 }
1113
1114 static void usb_host_release_interfaces(USBHostDevice *s)
1115 {
1116     USBDevice *udev = USB_DEVICE(s);
1117     int i, rc;
1118
1119     for (i = 0; i < udev->ninterfaces; i++) {
1120         if (!s->ifs[i].claimed) {
1121             continue;
1122         }
1123         trace_usb_host_release_interface(s->bus_num, s->addr, i);
1124         rc = libusb_release_interface(s->dh, i);
1125         usb_host_libusb_error("libusb_release_interface", rc);
1126         s->ifs[i].claimed = false;
1127     }
1128 }
1129
1130 static void usb_host_set_address(USBHostDevice *s, int addr)
1131 {
1132     USBDevice *udev = USB_DEVICE(s);
1133
1134     trace_usb_host_set_address(s->bus_num, s->addr, addr);
1135     udev->addr = addr;
1136 }
1137
1138 static void usb_host_set_config(USBHostDevice *s, int config, USBPacket *p)
1139 {
1140     int rc;
1141
1142     trace_usb_host_set_config(s->bus_num, s->addr, config);
1143
1144     usb_host_release_interfaces(s);
1145     rc = libusb_set_configuration(s->dh, config);
1146     if (rc != 0) {
1147         usb_host_libusb_error("libusb_set_configuration", rc);
1148         p->status = USB_RET_STALL;
1149         if (rc == LIBUSB_ERROR_NO_DEVICE) {
1150             usb_host_nodev(s);
1151         }
1152         return;
1153     }
1154     p->status = usb_host_claim_interfaces(s, config);
1155     if (p->status != USB_RET_SUCCESS) {
1156         return;
1157     }
1158     usb_host_ep_update(s);
1159 }
1160
1161 static void usb_host_set_interface(USBHostDevice *s, int iface, int alt,
1162                                    USBPacket *p)
1163 {
1164     USBDevice *udev = USB_DEVICE(s);
1165     int rc;
1166
1167     trace_usb_host_set_interface(s->bus_num, s->addr, iface, alt);
1168
1169     usb_host_iso_free_all(s);
1170
1171     if (iface >= USB_MAX_INTERFACES) {
1172         p->status = USB_RET_STALL;
1173         return;
1174     }
1175
1176     rc = libusb_set_interface_alt_setting(s->dh, iface, alt);
1177     if (rc != 0) {
1178         usb_host_libusb_error("libusb_set_interface_alt_setting", rc);
1179         p->status = USB_RET_STALL;
1180         if (rc == LIBUSB_ERROR_NO_DEVICE) {
1181             usb_host_nodev(s);
1182         }
1183         return;
1184     }
1185
1186     udev->altsetting[iface] = alt;
1187     usb_host_ep_update(s);
1188 }
1189
1190 static void usb_host_handle_control(USBDevice *udev, USBPacket *p,
1191                                     int request, int value, int index,
1192                                     int length, uint8_t *data)
1193 {
1194     USBHostDevice *s = USB_HOST_DEVICE(udev);
1195     USBHostRequest *r;
1196     int rc;
1197
1198     trace_usb_host_req_control(s->bus_num, s->addr, p, request, value, index);
1199
1200     if (s->dh == NULL) {
1201         p->status = USB_RET_NODEV;
1202         trace_usb_host_req_emulated(s->bus_num, s->addr, p, p->status);
1203         return;
1204     }
1205
1206     switch (request) {
1207     case DeviceOutRequest | USB_REQ_SET_ADDRESS:
1208         usb_host_set_address(s, value);
1209         trace_usb_host_req_emulated(s->bus_num, s->addr, p, p->status);
1210         return;
1211
1212     case DeviceOutRequest | USB_REQ_SET_CONFIGURATION:
1213         usb_host_set_config(s, value & 0xff, p);
1214         trace_usb_host_req_emulated(s->bus_num, s->addr, p, p->status);
1215         return;
1216
1217     case InterfaceOutRequest | USB_REQ_SET_INTERFACE:
1218         usb_host_set_interface(s, index, value, p);
1219         trace_usb_host_req_emulated(s->bus_num, s->addr, p, p->status);
1220         return;
1221
1222     case EndpointOutRequest | USB_REQ_CLEAR_FEATURE:
1223         if (value == 0) { /* clear halt */
1224             int pid = (index & USB_DIR_IN) ? USB_TOKEN_IN : USB_TOKEN_OUT;
1225             libusb_clear_halt(s->dh, index);
1226             usb_ep_set_halted(udev, pid, index & 0x0f, 0);
1227             trace_usb_host_req_emulated(s->bus_num, s->addr, p, p->status);
1228             return;
1229         }
1230     }
1231
1232     r = usb_host_req_alloc(s, p, (request >> 8) & USB_DIR_IN, length + 8);
1233     r->cbuf = data;
1234     r->clen = length;
1235     memcpy(r->buffer, udev->setup_buf, 8);
1236     if (!r->in) {
1237         memcpy(r->buffer + 8, r->cbuf, r->clen);
1238     }
1239
1240     /* Fix up USB-3 ep0 maxpacket size to allow superspeed connected devices
1241      * to work redirected to a not superspeed capable hcd */
1242     if (udev->speed == USB_SPEED_SUPER &&
1243         !(udev->port->speedmask & USB_SPEED_MASK_SUPER) &&
1244         request == 0x8006 && value == 0x100 && index == 0) {
1245         r->usb3ep0quirk = true;
1246     }
1247
1248     libusb_fill_control_transfer(r->xfer, s->dh, r->buffer,
1249                                  usb_host_req_complete_ctrl, r,
1250                                  CONTROL_TIMEOUT);
1251     rc = libusb_submit_transfer(r->xfer);
1252     if (rc != 0) {
1253         p->status = USB_RET_NODEV;
1254         trace_usb_host_req_complete(s->bus_num, s->addr, p,
1255                                     p->status, p->actual_length);
1256         if (rc == LIBUSB_ERROR_NO_DEVICE) {
1257             usb_host_nodev(s);
1258         }
1259         return;
1260     }
1261
1262     p->status = USB_RET_ASYNC;
1263 }
1264
1265 static void usb_host_handle_data(USBDevice *udev, USBPacket *p)
1266 {
1267     USBHostDevice *s = USB_HOST_DEVICE(udev);
1268     USBHostRequest *r;
1269     size_t size;
1270     int ep, rc;
1271
1272     if (usb_host_use_combining(p->ep) && p->state == USB_PACKET_SETUP) {
1273         p->status = USB_RET_ADD_TO_QUEUE;
1274         return;
1275     }
1276
1277     trace_usb_host_req_data(s->bus_num, s->addr, p,
1278                             p->pid == USB_TOKEN_IN,
1279                             p->ep->nr, p->iov.size);
1280
1281     if (s->dh == NULL) {
1282         p->status = USB_RET_NODEV;
1283         trace_usb_host_req_emulated(s->bus_num, s->addr, p, p->status);
1284         return;
1285     }
1286     if (p->ep->halted) {
1287         p->status = USB_RET_STALL;
1288         trace_usb_host_req_emulated(s->bus_num, s->addr, p, p->status);
1289         return;
1290     }
1291
1292     switch (usb_ep_get_type(udev, p->pid, p->ep->nr)) {
1293     case USB_ENDPOINT_XFER_BULK:
1294         size = usb_packet_size(p);
1295         r = usb_host_req_alloc(s, p, p->pid == USB_TOKEN_IN, size);
1296         if (!r->in) {
1297             usb_packet_copy(p, r->buffer, size);
1298         }
1299         ep = p->ep->nr | (r->in ? USB_DIR_IN : 0);
1300         if (p->stream) {
1301 #ifdef HAVE_STREAMS
1302             libusb_fill_bulk_stream_transfer(r->xfer, s->dh, ep, p->stream,
1303                                              r->buffer, size,
1304                                              usb_host_req_complete_data, r,
1305                                              BULK_TIMEOUT);
1306 #else
1307             usb_host_req_free(r);
1308             p->status = USB_RET_STALL;
1309             return;
1310 #endif
1311         } else {
1312             libusb_fill_bulk_transfer(r->xfer, s->dh, ep,
1313                                       r->buffer, size,
1314                                       usb_host_req_complete_data, r,
1315                                       BULK_TIMEOUT);
1316         }
1317         break;
1318     case USB_ENDPOINT_XFER_INT:
1319         r = usb_host_req_alloc(s, p, p->pid == USB_TOKEN_IN, p->iov.size);
1320         if (!r->in) {
1321             usb_packet_copy(p, r->buffer, p->iov.size);
1322         }
1323         ep = p->ep->nr | (r->in ? USB_DIR_IN : 0);
1324         libusb_fill_interrupt_transfer(r->xfer, s->dh, ep,
1325                                        r->buffer, p->iov.size,
1326                                        usb_host_req_complete_data, r,
1327                                        INTR_TIMEOUT);
1328         break;
1329     case USB_ENDPOINT_XFER_ISOC:
1330         if (p->pid == USB_TOKEN_IN) {
1331             usb_host_iso_data_in(s, p);
1332         } else {
1333             usb_host_iso_data_out(s, p);
1334         }
1335         trace_usb_host_req_complete(s->bus_num, s->addr, p,
1336                                     p->status, p->actual_length);
1337         return;
1338     default:
1339         p->status = USB_RET_STALL;
1340         trace_usb_host_req_complete(s->bus_num, s->addr, p,
1341                                     p->status, p->actual_length);
1342         return;
1343     }
1344
1345     rc = libusb_submit_transfer(r->xfer);
1346     if (rc != 0) {
1347         p->status = USB_RET_NODEV;
1348         trace_usb_host_req_complete(s->bus_num, s->addr, p,
1349                                     p->status, p->actual_length);
1350         if (rc == LIBUSB_ERROR_NO_DEVICE) {
1351             usb_host_nodev(s);
1352         }
1353         return;
1354     }
1355
1356     p->status = USB_RET_ASYNC;
1357 }
1358
1359 static void usb_host_flush_ep_queue(USBDevice *dev, USBEndpoint *ep)
1360 {
1361     if (usb_host_use_combining(ep)) {
1362         usb_ep_combine_input_packets(ep);
1363     }
1364 }
1365
1366 static void usb_host_handle_reset(USBDevice *udev)
1367 {
1368     USBHostDevice *s = USB_HOST_DEVICE(udev);
1369     int rc;
1370
1371     trace_usb_host_reset(s->bus_num, s->addr);
1372
1373     rc = libusb_reset_device(s->dh);
1374     if (rc != 0) {
1375         usb_host_nodev(s);
1376     }
1377 }
1378
1379 static int usb_host_alloc_streams(USBDevice *udev, USBEndpoint **eps,
1380                                   int nr_eps, int streams)
1381 {
1382 #ifdef HAVE_STREAMS
1383     USBHostDevice *s = USB_HOST_DEVICE(udev);
1384     unsigned char endpoints[30];
1385     int i, rc;
1386
1387     for (i = 0; i < nr_eps; i++) {
1388         endpoints[i] = eps[i]->nr;
1389         if (eps[i]->pid == USB_TOKEN_IN) {
1390             endpoints[i] |= 0x80;
1391         }
1392     }
1393     rc = libusb_alloc_streams(s->dh, streams, endpoints, nr_eps);
1394     if (rc < 0) {
1395         usb_host_libusb_error("libusb_alloc_streams", rc);
1396     } else if (rc != streams) {
1397         error_report("libusb_alloc_streams: got less streams "
1398                      "then requested %d < %d", rc, streams);
1399     }
1400
1401     return (rc == streams) ? 0 : -1;
1402 #else
1403     error_report("libusb_alloc_streams: error not implemented");
1404     return -1;
1405 #endif
1406 }
1407
1408 static void usb_host_free_streams(USBDevice *udev, USBEndpoint **eps,
1409                                   int nr_eps)
1410 {
1411 #ifdef HAVE_STREAMS
1412     USBHostDevice *s = USB_HOST_DEVICE(udev);
1413     unsigned char endpoints[30];
1414     int i;
1415
1416     for (i = 0; i < nr_eps; i++) {
1417         endpoints[i] = eps[i]->nr;
1418         if (eps[i]->pid == USB_TOKEN_IN) {
1419             endpoints[i] |= 0x80;
1420         }
1421     }
1422     libusb_free_streams(s->dh, endpoints, nr_eps);
1423 #endif
1424 }
1425
1426 /*
1427  * This is *NOT* about restoring state.  We have absolutely no idea
1428  * what state the host device is in at the moment and whenever it is
1429  * still present in the first place.  Attemping to contine where we
1430  * left off is impossible.
1431  *
1432  * What we are going to to to here is emulate a surprise removal of
1433  * the usb device passed through, then kick host scan so the device
1434  * will get re-attached (and re-initialized by the guest) in case it
1435  * is still present.
1436  *
1437  * As the device removal will change the state of other devices (usb
1438  * host controller, most likely interrupt controller too) we have to
1439  * wait with it until *all* vmstate is loaded.  Thus post_load just
1440  * kicks a bottom half which then does the actual work.
1441  */
1442 static void usb_host_post_load_bh(void *opaque)
1443 {
1444     USBHostDevice *dev = opaque;
1445     USBDevice *udev = USB_DEVICE(dev);
1446
1447     if (dev->dh != NULL) {
1448         usb_host_close(dev);
1449     }
1450     if (udev->attached) {
1451         usb_device_detach(udev);
1452     }
1453     usb_host_auto_check(NULL);
1454 }
1455
1456 static int usb_host_post_load(void *opaque, int version_id)
1457 {
1458     USBHostDevice *dev = opaque;
1459
1460     if (!dev->bh_postld) {
1461         dev->bh_postld = qemu_bh_new(usb_host_post_load_bh, dev);
1462     }
1463     qemu_bh_schedule(dev->bh_postld);
1464     return 0;
1465 }
1466
1467 static const VMStateDescription vmstate_usb_host = {
1468     .name = "usb-host",
1469     .version_id = 1,
1470     .minimum_version_id = 1,
1471     .post_load = usb_host_post_load,
1472     .fields = (VMStateField[]) {
1473         VMSTATE_USB_DEVICE(parent_obj, USBHostDevice),
1474         VMSTATE_END_OF_LIST()
1475     }
1476 };
1477
1478 static Property usb_host_dev_properties[] = {
1479     DEFINE_PROP_UINT32("hostbus",  USBHostDevice, match.bus_num,    0),
1480     DEFINE_PROP_UINT32("hostaddr", USBHostDevice, match.addr,       0),
1481     DEFINE_PROP_STRING("hostport", USBHostDevice, match.port),
1482     DEFINE_PROP_UINT32("vendorid",  USBHostDevice, match.vendor_id,  0),
1483     DEFINE_PROP_UINT32("productid", USBHostDevice, match.product_id, 0),
1484     DEFINE_PROP_UINT32("isobufs",  USBHostDevice, iso_urb_count,    4),
1485     DEFINE_PROP_UINT32("isobsize", USBHostDevice, iso_urb_frames,   32),
1486     DEFINE_PROP_UINT32("loglevel",  USBHostDevice, loglevel,
1487                        LIBUSB_LOG_LEVEL_WARNING),
1488     DEFINE_PROP_BIT("pipeline",    USBHostDevice, options,
1489                     USB_HOST_OPT_PIPELINE, true),
1490     DEFINE_PROP_END_OF_LIST(),
1491 };
1492
1493 static void usb_host_class_initfn(ObjectClass *klass, void *data)
1494 {
1495     DeviceClass *dc = DEVICE_CLASS(klass);
1496     USBDeviceClass *uc = USB_DEVICE_CLASS(klass);
1497
1498     uc->realize        = usb_host_realize;
1499     uc->product_desc   = "USB Host Device";
1500     uc->cancel_packet  = usb_host_cancel_packet;
1501     uc->handle_data    = usb_host_handle_data;
1502     uc->handle_control = usb_host_handle_control;
1503     uc->handle_reset   = usb_host_handle_reset;
1504     uc->handle_destroy = usb_host_handle_destroy;
1505     uc->flush_ep_queue = usb_host_flush_ep_queue;
1506     uc->alloc_streams  = usb_host_alloc_streams;
1507     uc->free_streams   = usb_host_free_streams;
1508     dc->vmsd = &vmstate_usb_host;
1509     dc->props = usb_host_dev_properties;
1510     set_bit(DEVICE_CATEGORY_BRIDGE, dc->categories);
1511 }
1512
1513 static TypeInfo usb_host_dev_info = {
1514     .name          = TYPE_USB_HOST_DEVICE,
1515     .parent        = TYPE_USB_DEVICE,
1516     .instance_size = sizeof(USBHostDevice),
1517     .class_init    = usb_host_class_initfn,
1518     .instance_init = usb_host_instance_init,
1519 };
1520
1521 static void usb_host_register_types(void)
1522 {
1523     type_register_static(&usb_host_dev_info);
1524 }
1525
1526 type_init(usb_host_register_types)
1527
1528 /* ------------------------------------------------------------------------ */
1529
1530 static QEMUTimer *usb_auto_timer;
1531 static VMChangeStateEntry *usb_vmstate;
1532
1533 static void usb_host_vm_state(void *unused, int running, RunState state)
1534 {
1535     if (running) {
1536         usb_host_auto_check(unused);
1537     }
1538 }
1539
1540 static void usb_host_auto_check(void *unused)
1541 {
1542     struct USBHostDevice *s;
1543     struct USBAutoFilter *f;
1544     libusb_device **devs = NULL;
1545     struct libusb_device_descriptor ddesc;
1546     int unconnected = 0;
1547     int i, n;
1548
1549     if (usb_host_init() != 0) {
1550         return;
1551     }
1552
1553     if (runstate_is_running()) {
1554         n = libusb_get_device_list(ctx, &devs);
1555         for (i = 0; i < n; i++) {
1556             if (libusb_get_device_descriptor(devs[i], &ddesc) != 0) {
1557                 continue;
1558             }
1559             if (ddesc.bDeviceClass == LIBUSB_CLASS_HUB) {
1560                 continue;
1561             }
1562             QTAILQ_FOREACH(s, &hostdevs, next) {
1563                 f = &s->match;
1564                 if (f->bus_num > 0 &&
1565                     f->bus_num != libusb_get_bus_number(devs[i])) {
1566                     continue;
1567                 }
1568                 if (f->addr > 0 &&
1569                     f->addr != libusb_get_device_address(devs[i])) {
1570                     continue;
1571                 }
1572                 if (f->port != NULL) {
1573                     char port[16] = "-";
1574                     usb_host_get_port(devs[i], port, sizeof(port));
1575                     if (strcmp(f->port, port) != 0) {
1576                         continue;
1577                     }
1578                 }
1579                 if (f->vendor_id > 0 &&
1580                     f->vendor_id != ddesc.idVendor) {
1581                     continue;
1582                 }
1583                 if (f->product_id > 0 &&
1584                     f->product_id != ddesc.idProduct) {
1585                     continue;
1586                 }
1587
1588                 /* We got a match */
1589                 s->seen++;
1590                 if (s->errcount >= 3) {
1591                     continue;
1592                 }
1593                 if (s->dh != NULL) {
1594                     continue;
1595                 }
1596                 if (usb_host_open(s, devs[i]) < 0) {
1597                     s->errcount++;
1598                     continue;
1599                 }
1600                 break;
1601             }
1602         }
1603         libusb_free_device_list(devs, 1);
1604
1605         QTAILQ_FOREACH(s, &hostdevs, next) {
1606             if (s->dh == NULL) {
1607                 unconnected++;
1608             }
1609             if (s->seen == 0) {
1610                 if (s->dh) {
1611                     usb_host_close(s);
1612                 }
1613                 s->errcount = 0;
1614             }
1615             s->seen = 0;
1616         }
1617
1618 #if 0
1619         if (unconnected == 0) {
1620             /* nothing to watch */
1621             if (usb_auto_timer) {
1622                 timer_del(usb_auto_timer);
1623                 trace_usb_host_auto_scan_disabled();
1624             }
1625             return;
1626         }
1627 #endif
1628     }
1629
1630     if (!usb_vmstate) {
1631         usb_vmstate = qemu_add_vm_change_state_handler(usb_host_vm_state, NULL);
1632     }
1633     if (!usb_auto_timer) {
1634         usb_auto_timer = timer_new_ms(QEMU_CLOCK_REALTIME, usb_host_auto_check, NULL);
1635         if (!usb_auto_timer) {
1636             return;
1637         }
1638         trace_usb_host_auto_scan_enabled();
1639     }
1640     timer_mod(usb_auto_timer, qemu_clock_get_ms(QEMU_CLOCK_REALTIME) + 2000);
1641 }
1642
1643 void hmp_info_usbhost(Monitor *mon, const QDict *qdict)
1644 {
1645     libusb_device **devs = NULL;
1646     struct libusb_device_descriptor ddesc;
1647     char port[16];
1648     int i, n;
1649
1650     if (usb_host_init() != 0) {
1651         return;
1652     }
1653
1654     n = libusb_get_device_list(ctx, &devs);
1655     for (i = 0; i < n; i++) {
1656         if (libusb_get_device_descriptor(devs[i], &ddesc) != 0) {
1657             continue;
1658         }
1659         if (ddesc.bDeviceClass == LIBUSB_CLASS_HUB) {
1660             continue;
1661         }
1662         usb_host_get_port(devs[i], port, sizeof(port));
1663         monitor_printf(mon, "  Bus %d, Addr %d, Port %s, Speed %s Mb/s\n",
1664                        libusb_get_bus_number(devs[i]),
1665                        libusb_get_device_address(devs[i]),
1666                        port,
1667                        speed_name[libusb_get_device_speed(devs[i])]);
1668         monitor_printf(mon, "    Class %02x:", ddesc.bDeviceClass);
1669         monitor_printf(mon, " USB device %04x:%04x",
1670                        ddesc.idVendor, ddesc.idProduct);
1671         if (ddesc.iProduct) {
1672             libusb_device_handle *handle;
1673             if (libusb_open(devs[i], &handle) == 0) {
1674                 unsigned char name[64] = "";
1675                 libusb_get_string_descriptor_ascii(handle,
1676                                                    ddesc.iProduct,
1677                                                    name, sizeof(name));
1678                 libusb_close(handle);
1679                 monitor_printf(mon, ", %s", name);
1680             }
1681         }
1682         monitor_printf(mon, "\n");
1683     }
1684     libusb_free_device_list(devs, 1);
1685 }