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