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