usb-redir: Add an usbredir_setup_usb_eps() helper function
[qemu.git] / hw / usb / host-linux.c
blob3a258b4bd45ab5b5d117db7e050cf756dd886940
1 /*
2 * Linux host USB redirector
4 * Copyright (c) 2005 Fabrice Bellard
6 * Copyright (c) 2008 Max Krasnyansky
7 * Support for host device auto connect & disconnect
8 * Major rewrite to support fully async operation
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
14 * Permission is hereby granted, free of charge, to any person obtaining a copy
15 * of this software and associated documentation files (the "Software"), to deal
16 * in the Software without restriction, including without limitation the rights
17 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
18 * copies of the Software, and to permit persons to whom the Software is
19 * furnished to do so, subject to the following conditions:
21 * The above copyright notice and this permission notice shall be included in
22 * all copies or substantial portions of the Software.
24 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
25 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
26 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
27 * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
28 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
29 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
30 * THE SOFTWARE.
33 #include "qemu-common.h"
34 #include "qemu-timer.h"
35 #include "monitor.h"
36 #include "sysemu.h"
37 #include "trace.h"
39 #include <dirent.h>
40 #include <sys/ioctl.h>
42 #include <linux/usbdevice_fs.h>
43 #include <linux/version.h>
44 #include "hw/usb.h"
45 #include "hw/usb/desc.h"
47 /* We redefine it to avoid version problems */
48 struct usb_ctrltransfer {
49 uint8_t bRequestType;
50 uint8_t bRequest;
51 uint16_t wValue;
52 uint16_t wIndex;
53 uint16_t wLength;
54 uint32_t timeout;
55 void *data;
58 typedef int USBScanFunc(void *opaque, int bus_num, int addr, const char *port,
59 int class_id, int vendor_id, int product_id,
60 const char *product_name, int speed);
62 //#define DEBUG
64 #ifdef DEBUG
65 #define DPRINTF printf
66 #else
67 #define DPRINTF(...)
68 #endif
70 #define PRODUCT_NAME_SZ 32
71 #define MAX_PORTLEN 16
73 /* endpoint association data */
74 #define ISO_FRAME_DESC_PER_URB 32
76 /* devio.c limits single requests to 16k */
77 #define MAX_USBFS_BUFFER_SIZE 16384
79 typedef struct AsyncURB AsyncURB;
81 struct endp_data {
82 uint8_t halted;
83 uint8_t iso_started;
84 AsyncURB *iso_urb;
85 int iso_urb_idx;
86 int iso_buffer_used;
87 int inflight;
90 struct USBAutoFilter {
91 uint32_t bus_num;
92 uint32_t addr;
93 char *port;
94 uint32_t vendor_id;
95 uint32_t product_id;
98 enum USBHostDeviceOptions {
99 USB_HOST_OPT_PIPELINE,
102 typedef struct USBHostDevice {
103 USBDevice dev;
104 int fd;
105 int hub_fd;
106 int hub_port;
108 uint8_t descr[8192];
109 int descr_len;
110 int closing;
111 uint32_t iso_urb_count;
112 uint32_t options;
113 Notifier exit;
114 QEMUBH *bh;
116 struct endp_data ep_in[USB_MAX_ENDPOINTS];
117 struct endp_data ep_out[USB_MAX_ENDPOINTS];
118 QLIST_HEAD(, AsyncURB) aurbs;
120 /* Host side address */
121 int bus_num;
122 int addr;
123 char port[MAX_PORTLEN];
124 struct USBAutoFilter match;
125 int32_t bootindex;
126 int seen, errcount;
128 QTAILQ_ENTRY(USBHostDevice) next;
129 } USBHostDevice;
131 static QTAILQ_HEAD(, USBHostDevice) hostdevs = QTAILQ_HEAD_INITIALIZER(hostdevs);
133 static int usb_host_close(USBHostDevice *dev);
134 static int parse_filter(const char *spec, struct USBAutoFilter *f);
135 static void usb_host_auto_check(void *unused);
136 static int usb_host_read_file(char *line, size_t line_size,
137 const char *device_file, const char *device_name);
138 static int usb_linux_update_endp_table(USBHostDevice *s);
140 static int usb_host_usbfs_type(USBHostDevice *s, USBPacket *p)
142 static const int usbfs[] = {
143 [USB_ENDPOINT_XFER_CONTROL] = USBDEVFS_URB_TYPE_CONTROL,
144 [USB_ENDPOINT_XFER_ISOC] = USBDEVFS_URB_TYPE_ISO,
145 [USB_ENDPOINT_XFER_BULK] = USBDEVFS_URB_TYPE_BULK,
146 [USB_ENDPOINT_XFER_INT] = USBDEVFS_URB_TYPE_INTERRUPT,
148 uint8_t type = p->ep->type;
149 assert(type < ARRAY_SIZE(usbfs));
150 return usbfs[type];
153 static int usb_host_do_reset(USBHostDevice *dev)
155 struct timeval s, e;
156 uint32_t usecs;
157 int ret;
159 gettimeofday(&s, NULL);
160 ret = ioctl(dev->fd, USBDEVFS_RESET);
161 gettimeofday(&e, NULL);
162 usecs = (e.tv_sec - s.tv_sec) * 1000000;
163 usecs += e.tv_usec - s.tv_usec;
164 if (usecs > 1000000) {
165 /* more than a second, something is fishy, broken usb device? */
166 fprintf(stderr, "husb: device %d:%d reset took %d.%06d seconds\n",
167 dev->bus_num, dev->addr, usecs / 1000000, usecs % 1000000);
169 return ret;
172 static struct endp_data *get_endp(USBHostDevice *s, int pid, int ep)
174 struct endp_data *eps = pid == USB_TOKEN_IN ? s->ep_in : s->ep_out;
175 assert(pid == USB_TOKEN_IN || pid == USB_TOKEN_OUT);
176 assert(ep > 0 && ep <= USB_MAX_ENDPOINTS);
177 return eps + ep - 1;
180 static int is_isoc(USBHostDevice *s, int pid, int ep)
182 return usb_ep_get_type(&s->dev, pid, ep) == USB_ENDPOINT_XFER_ISOC;
185 static int is_valid(USBHostDevice *s, int pid, int ep)
187 return usb_ep_get_type(&s->dev, pid, ep) != USB_ENDPOINT_XFER_INVALID;
190 static int is_halted(USBHostDevice *s, int pid, int ep)
192 return get_endp(s, pid, ep)->halted;
195 static void clear_halt(USBHostDevice *s, int pid, int ep)
197 trace_usb_host_ep_clear_halt(s->bus_num, s->addr, ep);
198 get_endp(s, pid, ep)->halted = 0;
201 static void set_halt(USBHostDevice *s, int pid, int ep)
203 if (ep != 0) {
204 trace_usb_host_ep_set_halt(s->bus_num, s->addr, ep);
205 get_endp(s, pid, ep)->halted = 1;
209 static int is_iso_started(USBHostDevice *s, int pid, int ep)
211 return get_endp(s, pid, ep)->iso_started;
214 static void clear_iso_started(USBHostDevice *s, int pid, int ep)
216 trace_usb_host_iso_stop(s->bus_num, s->addr, ep);
217 get_endp(s, pid, ep)->iso_started = 0;
220 static void set_iso_started(USBHostDevice *s, int pid, int ep)
222 struct endp_data *e = get_endp(s, pid, ep);
224 trace_usb_host_iso_start(s->bus_num, s->addr, ep);
225 if (!e->iso_started) {
226 e->iso_started = 1;
227 e->inflight = 0;
231 static int change_iso_inflight(USBHostDevice *s, int pid, int ep, int value)
233 struct endp_data *e = get_endp(s, pid, ep);
235 e->inflight += value;
236 return e->inflight;
239 static void set_iso_urb(USBHostDevice *s, int pid, int ep, AsyncURB *iso_urb)
241 get_endp(s, pid, ep)->iso_urb = iso_urb;
244 static AsyncURB *get_iso_urb(USBHostDevice *s, int pid, int ep)
246 return get_endp(s, pid, ep)->iso_urb;
249 static void set_iso_urb_idx(USBHostDevice *s, int pid, int ep, int i)
251 get_endp(s, pid, ep)->iso_urb_idx = i;
254 static int get_iso_urb_idx(USBHostDevice *s, int pid, int ep)
256 return get_endp(s, pid, ep)->iso_urb_idx;
259 static void set_iso_buffer_used(USBHostDevice *s, int pid, int ep, int i)
261 get_endp(s, pid, ep)->iso_buffer_used = i;
264 static int get_iso_buffer_used(USBHostDevice *s, int pid, int ep)
266 return get_endp(s, pid, ep)->iso_buffer_used;
270 * Async URB state.
271 * We always allocate iso packet descriptors even for bulk transfers
272 * to simplify allocation and casts.
274 struct AsyncURB
276 struct usbdevfs_urb urb;
277 struct usbdevfs_iso_packet_desc isocpd[ISO_FRAME_DESC_PER_URB];
278 USBHostDevice *hdev;
279 QLIST_ENTRY(AsyncURB) next;
281 /* For regular async urbs */
282 USBPacket *packet;
283 int more; /* large transfer, more urbs follow */
285 /* For buffered iso handling */
286 int iso_frame_idx; /* -1 means in flight */
289 static AsyncURB *async_alloc(USBHostDevice *s)
291 AsyncURB *aurb = g_malloc0(sizeof(AsyncURB));
292 aurb->hdev = s;
293 QLIST_INSERT_HEAD(&s->aurbs, aurb, next);
294 return aurb;
297 static void async_free(AsyncURB *aurb)
299 QLIST_REMOVE(aurb, next);
300 g_free(aurb);
303 static void do_disconnect(USBHostDevice *s)
305 usb_host_close(s);
306 usb_host_auto_check(NULL);
309 static void async_complete(void *opaque)
311 USBHostDevice *s = opaque;
312 AsyncURB *aurb;
313 int urbs = 0;
315 while (1) {
316 USBPacket *p;
318 int r = ioctl(s->fd, USBDEVFS_REAPURBNDELAY, &aurb);
319 if (r < 0) {
320 if (errno == EAGAIN) {
321 if (urbs > 2) {
322 /* indicates possible latency issues */
323 trace_usb_host_iso_many_urbs(s->bus_num, s->addr, urbs);
325 return;
327 if (errno == ENODEV) {
328 if (!s->closing) {
329 trace_usb_host_disconnect(s->bus_num, s->addr);
330 do_disconnect(s);
332 return;
335 perror("USBDEVFS_REAPURBNDELAY");
336 return;
339 DPRINTF("husb: async completed. aurb %p status %d alen %d\n",
340 aurb, aurb->urb.status, aurb->urb.actual_length);
342 /* If this is a buffered iso urb mark it as complete and don't do
343 anything else (it is handled further in usb_host_handle_iso_data) */
344 if (aurb->iso_frame_idx == -1) {
345 int inflight;
346 int pid = (aurb->urb.endpoint & USB_DIR_IN) ?
347 USB_TOKEN_IN : USB_TOKEN_OUT;
348 int ep = aurb->urb.endpoint & 0xf;
349 if (aurb->urb.status == -EPIPE) {
350 set_halt(s, pid, ep);
352 aurb->iso_frame_idx = 0;
353 urbs++;
354 inflight = change_iso_inflight(s, pid, ep, -1);
355 if (inflight == 0 && is_iso_started(s, pid, ep)) {
356 /* can be latency issues, or simply end of stream */
357 trace_usb_host_iso_out_of_bufs(s->bus_num, s->addr, ep);
359 continue;
362 p = aurb->packet;
363 trace_usb_host_urb_complete(s->bus_num, s->addr, aurb, aurb->urb.status,
364 aurb->urb.actual_length, aurb->more);
366 if (p) {
367 switch (aurb->urb.status) {
368 case 0:
369 p->result += aurb->urb.actual_length;
370 break;
372 case -EPIPE:
373 set_halt(s, p->pid, p->ep->nr);
374 p->result = USB_RET_STALL;
375 break;
377 case -EOVERFLOW:
378 p->result = USB_RET_BABBLE;
379 break;
381 default:
382 p->result = USB_RET_IOERROR;
383 break;
386 if (aurb->urb.type == USBDEVFS_URB_TYPE_CONTROL) {
387 trace_usb_host_req_complete(s->bus_num, s->addr, p, p->result);
388 usb_generic_async_ctrl_complete(&s->dev, p);
389 } else if (!aurb->more) {
390 trace_usb_host_req_complete(s->bus_num, s->addr, p, p->result);
391 usb_packet_complete(&s->dev, p);
395 async_free(aurb);
399 static void usb_host_async_cancel(USBDevice *dev, USBPacket *p)
401 USBHostDevice *s = DO_UPCAST(USBHostDevice, dev, dev);
402 AsyncURB *aurb;
404 trace_usb_host_req_canceled(s->bus_num, s->addr, p);
406 QLIST_FOREACH(aurb, &s->aurbs, next) {
407 if (p != aurb->packet) {
408 continue;
411 trace_usb_host_urb_canceled(s->bus_num, s->addr, aurb);
413 /* Mark it as dead (see async_complete above) */
414 aurb->packet = NULL;
416 int r = ioctl(s->fd, USBDEVFS_DISCARDURB, aurb);
417 if (r < 0) {
418 DPRINTF("husb: async. discard urb failed errno %d\n", errno);
423 static int usb_host_open_device(int bus, int addr)
425 const char *usbfs = NULL;
426 char filename[32];
427 struct stat st;
428 int fd, rc;
430 rc = stat("/dev/bus/usb", &st);
431 if (rc == 0 && S_ISDIR(st.st_mode)) {
432 /* udev-created device nodes available */
433 usbfs = "/dev/bus/usb";
434 } else {
435 /* fallback: usbfs mounted below /proc */
436 usbfs = "/proc/bus/usb";
439 snprintf(filename, sizeof(filename), "%s/%03d/%03d",
440 usbfs, bus, addr);
441 fd = open(filename, O_RDWR | O_NONBLOCK);
442 if (fd < 0) {
443 fprintf(stderr, "husb: open %s: %s\n", filename, strerror(errno));
445 return fd;
448 static int usb_host_claim_port(USBHostDevice *s)
450 #ifdef USBDEVFS_CLAIM_PORT
451 char *h, hub_name[64], line[1024];
452 int hub_addr, ret;
454 snprintf(hub_name, sizeof(hub_name), "%d-%s",
455 s->match.bus_num, s->match.port);
457 /* try strip off last ".$portnr" to get hub */
458 h = strrchr(hub_name, '.');
459 if (h != NULL) {
460 s->hub_port = atoi(h+1);
461 *h = '\0';
462 } else {
463 /* no dot in there -> it is the root hub */
464 snprintf(hub_name, sizeof(hub_name), "usb%d",
465 s->match.bus_num);
466 s->hub_port = atoi(s->match.port);
469 if (!usb_host_read_file(line, sizeof(line), "devnum",
470 hub_name)) {
471 return -1;
473 if (sscanf(line, "%d", &hub_addr) != 1) {
474 return -1;
477 s->hub_fd = usb_host_open_device(s->match.bus_num, hub_addr);
478 if (s->hub_fd < 0) {
479 return -1;
482 ret = ioctl(s->hub_fd, USBDEVFS_CLAIM_PORT, &s->hub_port);
483 if (ret < 0) {
484 close(s->hub_fd);
485 s->hub_fd = -1;
486 return -1;
489 trace_usb_host_claim_port(s->match.bus_num, hub_addr, s->hub_port);
490 return 0;
491 #else
492 return -1;
493 #endif
496 static void usb_host_release_port(USBHostDevice *s)
498 if (s->hub_fd == -1) {
499 return;
501 #ifdef USBDEVFS_RELEASE_PORT
502 ioctl(s->hub_fd, USBDEVFS_RELEASE_PORT, &s->hub_port);
503 #endif
504 close(s->hub_fd);
505 s->hub_fd = -1;
508 static int usb_host_disconnect_ifaces(USBHostDevice *dev, int nb_interfaces)
510 /* earlier Linux 2.4 do not support that */
511 #ifdef USBDEVFS_DISCONNECT
512 struct usbdevfs_ioctl ctrl;
513 int ret, interface;
515 for (interface = 0; interface < nb_interfaces; interface++) {
516 ctrl.ioctl_code = USBDEVFS_DISCONNECT;
517 ctrl.ifno = interface;
518 ctrl.data = 0;
519 ret = ioctl(dev->fd, USBDEVFS_IOCTL, &ctrl);
520 if (ret < 0 && errno != ENODATA) {
521 perror("USBDEVFS_DISCONNECT");
522 return -1;
525 #endif
526 return 0;
529 static int usb_linux_get_num_interfaces(USBHostDevice *s)
531 char device_name[64], line[1024];
532 int num_interfaces = 0;
534 sprintf(device_name, "%d-%s", s->bus_num, s->port);
535 if (!usb_host_read_file(line, sizeof(line), "bNumInterfaces",
536 device_name)) {
537 return -1;
539 if (sscanf(line, "%d", &num_interfaces) != 1) {
540 return -1;
542 return num_interfaces;
545 static int usb_host_claim_interfaces(USBHostDevice *dev, int configuration)
547 const char *op = NULL;
548 int dev_descr_len, config_descr_len;
549 int interface, nb_interfaces;
550 int ret, i;
552 for (i = 0; i < USB_MAX_INTERFACES; i++) {
553 dev->dev.altsetting[i] = 0;
556 if (configuration == 0) { /* address state - ignore */
557 dev->dev.ninterfaces = 0;
558 dev->dev.configuration = 0;
559 return 1;
562 DPRINTF("husb: claiming interfaces. config %d\n", configuration);
564 i = 0;
565 dev_descr_len = dev->descr[0];
566 if (dev_descr_len > dev->descr_len) {
567 fprintf(stderr, "husb: update iface failed. descr too short\n");
568 return 0;
571 i += dev_descr_len;
572 while (i < dev->descr_len) {
573 DPRINTF("husb: i is %d, descr_len is %d, dl %d, dt %d\n",
574 i, dev->descr_len,
575 dev->descr[i], dev->descr[i+1]);
577 if (dev->descr[i+1] != USB_DT_CONFIG) {
578 i += dev->descr[i];
579 continue;
581 config_descr_len = dev->descr[i];
583 DPRINTF("husb: config #%d need %d\n", dev->descr[i + 5], configuration);
585 if (configuration == dev->descr[i + 5]) {
586 configuration = dev->descr[i + 5];
587 break;
590 i += config_descr_len;
593 if (i >= dev->descr_len) {
594 fprintf(stderr,
595 "husb: update iface failed. no matching configuration\n");
596 return 0;
598 nb_interfaces = dev->descr[i + 4];
600 if (usb_host_disconnect_ifaces(dev, nb_interfaces) < 0) {
601 goto fail;
604 /* XXX: only grab if all interfaces are free */
605 for (interface = 0; interface < nb_interfaces; interface++) {
606 op = "USBDEVFS_CLAIMINTERFACE";
607 ret = ioctl(dev->fd, USBDEVFS_CLAIMINTERFACE, &interface);
608 if (ret < 0) {
609 goto fail;
613 trace_usb_host_claim_interfaces(dev->bus_num, dev->addr,
614 nb_interfaces, configuration);
616 dev->dev.ninterfaces = nb_interfaces;
617 dev->dev.configuration = configuration;
618 return 1;
620 fail:
621 if (errno == ENODEV) {
622 do_disconnect(dev);
624 perror(op);
625 return 0;
628 static int usb_host_release_interfaces(USBHostDevice *s)
630 int ret, i;
632 trace_usb_host_release_interfaces(s->bus_num, s->addr);
634 for (i = 0; i < s->dev.ninterfaces; i++) {
635 ret = ioctl(s->fd, USBDEVFS_RELEASEINTERFACE, &i);
636 if (ret < 0) {
637 perror("USBDEVFS_RELEASEINTERFACE");
638 return 0;
641 return 1;
644 static void usb_host_handle_reset(USBDevice *dev)
646 USBHostDevice *s = DO_UPCAST(USBHostDevice, dev, dev);
648 trace_usb_host_reset(s->bus_num, s->addr);
650 usb_host_do_reset(s);;
652 usb_host_claim_interfaces(s, 0);
653 usb_linux_update_endp_table(s);
656 static void usb_host_handle_destroy(USBDevice *dev)
658 USBHostDevice *s = (USBHostDevice *)dev;
660 usb_host_release_port(s);
661 usb_host_close(s);
662 QTAILQ_REMOVE(&hostdevs, s, next);
663 qemu_remove_exit_notifier(&s->exit);
666 /* iso data is special, we need to keep enough urbs in flight to make sure
667 that the controller never runs out of them, otherwise the device will
668 likely suffer a buffer underrun / overrun. */
669 static AsyncURB *usb_host_alloc_iso(USBHostDevice *s, int pid, uint8_t ep)
671 AsyncURB *aurb;
672 int i, j, len = usb_ep_get_max_packet_size(&s->dev, pid, ep);
674 aurb = g_malloc0(s->iso_urb_count * sizeof(*aurb));
675 for (i = 0; i < s->iso_urb_count; i++) {
676 aurb[i].urb.endpoint = ep;
677 aurb[i].urb.buffer_length = ISO_FRAME_DESC_PER_URB * len;
678 aurb[i].urb.buffer = g_malloc(aurb[i].urb.buffer_length);
679 aurb[i].urb.type = USBDEVFS_URB_TYPE_ISO;
680 aurb[i].urb.flags = USBDEVFS_URB_ISO_ASAP;
681 aurb[i].urb.number_of_packets = ISO_FRAME_DESC_PER_URB;
682 for (j = 0 ; j < ISO_FRAME_DESC_PER_URB; j++)
683 aurb[i].urb.iso_frame_desc[j].length = len;
684 if (pid == USB_TOKEN_IN) {
685 aurb[i].urb.endpoint |= 0x80;
686 /* Mark as fully consumed (idle) */
687 aurb[i].iso_frame_idx = ISO_FRAME_DESC_PER_URB;
690 set_iso_urb(s, pid, ep, aurb);
692 return aurb;
695 static void usb_host_stop_n_free_iso(USBHostDevice *s, int pid, uint8_t ep)
697 AsyncURB *aurb;
698 int i, ret, killed = 0, free = 1;
700 aurb = get_iso_urb(s, pid, ep);
701 if (!aurb) {
702 return;
705 for (i = 0; i < s->iso_urb_count; i++) {
706 /* in flight? */
707 if (aurb[i].iso_frame_idx == -1) {
708 ret = ioctl(s->fd, USBDEVFS_DISCARDURB, &aurb[i]);
709 if (ret < 0) {
710 perror("USBDEVFS_DISCARDURB");
711 free = 0;
712 continue;
714 killed++;
718 /* Make sure any urbs we've killed are reaped before we free them */
719 if (killed) {
720 async_complete(s);
723 for (i = 0; i < s->iso_urb_count; i++) {
724 g_free(aurb[i].urb.buffer);
727 if (free)
728 g_free(aurb);
729 else
730 printf("husb: leaking iso urbs because of discard failure\n");
731 set_iso_urb(s, pid, ep, NULL);
732 set_iso_urb_idx(s, pid, ep, 0);
733 clear_iso_started(s, pid, ep);
736 static int urb_status_to_usb_ret(int status)
738 switch (status) {
739 case -EPIPE:
740 return USB_RET_STALL;
741 case -EOVERFLOW:
742 return USB_RET_BABBLE;
743 default:
744 return USB_RET_IOERROR;
748 static int usb_host_handle_iso_data(USBHostDevice *s, USBPacket *p, int in)
750 AsyncURB *aurb;
751 int i, j, ret, max_packet_size, offset, len = 0;
752 uint8_t *buf;
754 max_packet_size = p->ep->max_packet_size;
755 if (max_packet_size == 0)
756 return USB_RET_NAK;
758 aurb = get_iso_urb(s, p->pid, p->ep->nr);
759 if (!aurb) {
760 aurb = usb_host_alloc_iso(s, p->pid, p->ep->nr);
763 i = get_iso_urb_idx(s, p->pid, p->ep->nr);
764 j = aurb[i].iso_frame_idx;
765 if (j >= 0 && j < ISO_FRAME_DESC_PER_URB) {
766 if (in) {
767 /* Check urb status */
768 if (aurb[i].urb.status) {
769 len = urb_status_to_usb_ret(aurb[i].urb.status);
770 /* Move to the next urb */
771 aurb[i].iso_frame_idx = ISO_FRAME_DESC_PER_URB - 1;
772 /* Check frame status */
773 } else if (aurb[i].urb.iso_frame_desc[j].status) {
774 len = urb_status_to_usb_ret(
775 aurb[i].urb.iso_frame_desc[j].status);
776 /* Check the frame fits */
777 } else if (aurb[i].urb.iso_frame_desc[j].actual_length
778 > p->iov.size) {
779 printf("husb: received iso data is larger then packet\n");
780 len = USB_RET_BABBLE;
781 /* All good copy data over */
782 } else {
783 len = aurb[i].urb.iso_frame_desc[j].actual_length;
784 buf = aurb[i].urb.buffer +
785 j * aurb[i].urb.iso_frame_desc[0].length;
786 usb_packet_copy(p, buf, len);
788 } else {
789 len = p->iov.size;
790 offset = (j == 0) ? 0 : get_iso_buffer_used(s, p->pid, p->ep->nr);
792 /* Check the frame fits */
793 if (len > max_packet_size) {
794 printf("husb: send iso data is larger then max packet size\n");
795 return USB_RET_NAK;
798 /* All good copy data over */
799 usb_packet_copy(p, aurb[i].urb.buffer + offset, len);
800 aurb[i].urb.iso_frame_desc[j].length = len;
801 offset += len;
802 set_iso_buffer_used(s, p->pid, p->ep->nr, offset);
804 /* Start the stream once we have buffered enough data */
805 if (!is_iso_started(s, p->pid, p->ep->nr) && i == 1 && j == 8) {
806 set_iso_started(s, p->pid, p->ep->nr);
809 aurb[i].iso_frame_idx++;
810 if (aurb[i].iso_frame_idx == ISO_FRAME_DESC_PER_URB) {
811 i = (i + 1) % s->iso_urb_count;
812 set_iso_urb_idx(s, p->pid, p->ep->nr, i);
814 } else {
815 if (in) {
816 set_iso_started(s, p->pid, p->ep->nr);
817 } else {
818 DPRINTF("hubs: iso out error no free buffer, dropping packet\n");
822 if (is_iso_started(s, p->pid, p->ep->nr)) {
823 /* (Re)-submit all fully consumed / filled urbs */
824 for (i = 0; i < s->iso_urb_count; i++) {
825 if (aurb[i].iso_frame_idx == ISO_FRAME_DESC_PER_URB) {
826 ret = ioctl(s->fd, USBDEVFS_SUBMITURB, &aurb[i]);
827 if (ret < 0) {
828 perror("USBDEVFS_SUBMITURB");
829 if (!in || len == 0) {
830 switch(errno) {
831 case ETIMEDOUT:
832 len = USB_RET_NAK;
833 break;
834 case EPIPE:
835 default:
836 len = USB_RET_STALL;
839 break;
841 aurb[i].iso_frame_idx = -1;
842 change_iso_inflight(s, p->pid, p->ep->nr, 1);
847 return len;
850 static int usb_host_handle_data(USBDevice *dev, USBPacket *p)
852 USBHostDevice *s = DO_UPCAST(USBHostDevice, dev, dev);
853 struct usbdevfs_urb *urb;
854 AsyncURB *aurb;
855 int ret, rem, prem, v;
856 uint8_t *pbuf;
857 uint8_t ep;
859 trace_usb_host_req_data(s->bus_num, s->addr, p,
860 p->pid == USB_TOKEN_IN,
861 p->ep->nr, p->iov.size);
863 if (!is_valid(s, p->pid, p->ep->nr)) {
864 trace_usb_host_req_complete(s->bus_num, s->addr, p, USB_RET_NAK);
865 return USB_RET_NAK;
868 if (p->pid == USB_TOKEN_IN) {
869 ep = p->ep->nr | 0x80;
870 } else {
871 ep = p->ep->nr;
874 if (is_halted(s, p->pid, p->ep->nr)) {
875 unsigned int arg = ep;
876 ret = ioctl(s->fd, USBDEVFS_CLEAR_HALT, &arg);
877 if (ret < 0) {
878 perror("USBDEVFS_CLEAR_HALT");
879 trace_usb_host_req_complete(s->bus_num, s->addr, p, USB_RET_NAK);
880 return USB_RET_NAK;
882 clear_halt(s, p->pid, p->ep->nr);
885 if (is_isoc(s, p->pid, p->ep->nr)) {
886 return usb_host_handle_iso_data(s, p, p->pid == USB_TOKEN_IN);
889 v = 0;
890 prem = 0;
891 pbuf = NULL;
892 rem = p->iov.size;
893 do {
894 if (prem == 0 && rem > 0) {
895 assert(v < p->iov.niov);
896 prem = p->iov.iov[v].iov_len;
897 pbuf = p->iov.iov[v].iov_base;
898 assert(prem <= rem);
899 v++;
901 aurb = async_alloc(s);
902 aurb->packet = p;
904 urb = &aurb->urb;
905 urb->endpoint = ep;
906 urb->type = usb_host_usbfs_type(s, p);
907 urb->usercontext = s;
908 urb->buffer = pbuf;
909 urb->buffer_length = prem;
911 if (urb->buffer_length > MAX_USBFS_BUFFER_SIZE) {
912 urb->buffer_length = MAX_USBFS_BUFFER_SIZE;
914 pbuf += urb->buffer_length;
915 prem -= urb->buffer_length;
916 rem -= urb->buffer_length;
917 if (rem) {
918 aurb->more = 1;
921 trace_usb_host_urb_submit(s->bus_num, s->addr, aurb,
922 urb->buffer_length, aurb->more);
923 ret = ioctl(s->fd, USBDEVFS_SUBMITURB, urb);
925 DPRINTF("husb: data submit: ep 0x%x, len %u, more %d, packet %p, aurb %p\n",
926 urb->endpoint, urb->buffer_length, aurb->more, p, aurb);
928 if (ret < 0) {
929 perror("USBDEVFS_SUBMITURB");
930 async_free(aurb);
932 switch(errno) {
933 case ETIMEDOUT:
934 trace_usb_host_req_complete(s->bus_num, s->addr, p,
935 USB_RET_NAK);
936 return USB_RET_NAK;
937 case EPIPE:
938 default:
939 trace_usb_host_req_complete(s->bus_num, s->addr, p,
940 USB_RET_STALL);
941 return USB_RET_STALL;
944 } while (rem > 0);
946 return USB_RET_ASYNC;
949 static int ctrl_error(void)
951 if (errno == ETIMEDOUT) {
952 return USB_RET_NAK;
953 } else {
954 return USB_RET_STALL;
958 static int usb_host_set_address(USBHostDevice *s, int addr)
960 trace_usb_host_set_address(s->bus_num, s->addr, addr);
961 s->dev.addr = addr;
962 return 0;
965 static int usb_host_set_config(USBHostDevice *s, int config)
967 int ret, first = 1;
969 trace_usb_host_set_config(s->bus_num, s->addr, config);
971 usb_host_release_interfaces(s);
973 again:
974 ret = ioctl(s->fd, USBDEVFS_SETCONFIGURATION, &config);
976 DPRINTF("husb: ctrl set config %d ret %d errno %d\n", config, ret, errno);
978 if (ret < 0 && errno == EBUSY && first) {
979 /* happens if usb device is in use by host drivers */
980 int count = usb_linux_get_num_interfaces(s);
981 if (count > 0) {
982 DPRINTF("husb: busy -> disconnecting %d interfaces\n", count);
983 usb_host_disconnect_ifaces(s, count);
984 first = 0;
985 goto again;
989 if (ret < 0) {
990 return ctrl_error();
992 usb_host_claim_interfaces(s, config);
993 usb_linux_update_endp_table(s);
994 return 0;
997 static int usb_host_set_interface(USBHostDevice *s, int iface, int alt)
999 struct usbdevfs_setinterface si;
1000 int i, ret;
1002 trace_usb_host_set_interface(s->bus_num, s->addr, iface, alt);
1004 for (i = 1; i <= USB_MAX_ENDPOINTS; i++) {
1005 if (is_isoc(s, USB_TOKEN_IN, i)) {
1006 usb_host_stop_n_free_iso(s, USB_TOKEN_IN, i);
1008 if (is_isoc(s, USB_TOKEN_OUT, i)) {
1009 usb_host_stop_n_free_iso(s, USB_TOKEN_OUT, i);
1013 if (iface >= USB_MAX_INTERFACES) {
1014 return USB_RET_STALL;
1017 si.interface = iface;
1018 si.altsetting = alt;
1019 ret = ioctl(s->fd, USBDEVFS_SETINTERFACE, &si);
1021 DPRINTF("husb: ctrl set iface %d altset %d ret %d errno %d\n",
1022 iface, alt, ret, errno);
1024 if (ret < 0) {
1025 return ctrl_error();
1028 s->dev.altsetting[iface] = alt;
1029 usb_linux_update_endp_table(s);
1030 return 0;
1033 static int usb_host_handle_control(USBDevice *dev, USBPacket *p,
1034 int request, int value, int index, int length, uint8_t *data)
1036 USBHostDevice *s = DO_UPCAST(USBHostDevice, dev, dev);
1037 struct usbdevfs_urb *urb;
1038 AsyncURB *aurb;
1039 int ret;
1042 * Process certain standard device requests.
1043 * These are infrequent and are processed synchronously.
1046 /* Note request is (bRequestType << 8) | bRequest */
1047 trace_usb_host_req_control(s->bus_num, s->addr, p, request, value, index);
1049 switch (request) {
1050 case DeviceOutRequest | USB_REQ_SET_ADDRESS:
1051 ret = usb_host_set_address(s, value);
1052 trace_usb_host_req_emulated(s->bus_num, s->addr, p, ret);
1053 return ret;
1055 case DeviceOutRequest | USB_REQ_SET_CONFIGURATION:
1056 ret = usb_host_set_config(s, value & 0xff);
1057 trace_usb_host_req_emulated(s->bus_num, s->addr, p, ret);
1058 return ret;
1060 case InterfaceOutRequest | USB_REQ_SET_INTERFACE:
1061 ret = usb_host_set_interface(s, index, value);
1062 trace_usb_host_req_emulated(s->bus_num, s->addr, p, ret);
1063 return ret;
1065 case EndpointOutRequest | USB_REQ_CLEAR_FEATURE:
1066 if (value == 0) { /* clear halt */
1067 int pid = (index & USB_DIR_IN) ? USB_TOKEN_IN : USB_TOKEN_OUT;
1068 ioctl(s->fd, USBDEVFS_CLEAR_HALT, &index);
1069 clear_halt(s, pid, index & 0x0f);
1070 trace_usb_host_req_emulated(s->bus_num, s->addr, p, 0);
1071 return 0;
1075 /* The rest are asynchronous */
1076 assert(p && p->result == 0);
1078 if (length > sizeof(dev->data_buf)) {
1079 fprintf(stderr, "husb: ctrl buffer too small (%d > %zu)\n",
1080 length, sizeof(dev->data_buf));
1081 return USB_RET_STALL;
1084 aurb = async_alloc(s);
1085 aurb->packet = p;
1088 * Setup ctrl transfer.
1090 * s->ctrl is laid out such that data buffer immediately follows
1091 * 'req' struct which is exactly what usbdevfs expects.
1093 urb = &aurb->urb;
1095 urb->type = USBDEVFS_URB_TYPE_CONTROL;
1096 urb->endpoint = p->ep->nr;
1098 urb->buffer = &dev->setup_buf;
1099 urb->buffer_length = length + 8;
1101 urb->usercontext = s;
1103 trace_usb_host_urb_submit(s->bus_num, s->addr, aurb,
1104 urb->buffer_length, aurb->more);
1105 ret = ioctl(s->fd, USBDEVFS_SUBMITURB, urb);
1107 DPRINTF("husb: submit ctrl. len %u aurb %p\n", urb->buffer_length, aurb);
1109 if (ret < 0) {
1110 DPRINTF("husb: submit failed. errno %d\n", errno);
1111 async_free(aurb);
1113 switch(errno) {
1114 case ETIMEDOUT:
1115 return USB_RET_NAK;
1116 case EPIPE:
1117 default:
1118 return USB_RET_STALL;
1122 return USB_RET_ASYNC;
1125 /* returns 1 on problem encountered or 0 for success */
1126 static int usb_linux_update_endp_table(USBHostDevice *s)
1128 static const char *tname[] = {
1129 [USB_ENDPOINT_XFER_CONTROL] = "control",
1130 [USB_ENDPOINT_XFER_ISOC] = "isoc",
1131 [USB_ENDPOINT_XFER_BULK] = "bulk",
1132 [USB_ENDPOINT_XFER_INT] = "int",
1134 uint8_t devep, type;
1135 uint16_t mps, v, p;
1136 int ep, pid;
1137 unsigned int i, configuration = -1, interface = -1, altsetting = -1;
1138 struct endp_data *epd;
1139 USBDescriptor *d;
1140 bool active = false;
1142 usb_ep_reset(&s->dev);
1144 for (i = 0;; i += d->bLength) {
1145 if (i+2 >= s->descr_len) {
1146 break;
1148 d = (void *)(s->descr + i);
1149 if (d->bLength < 2) {
1150 trace_usb_host_parse_error(s->bus_num, s->addr,
1151 "descriptor too short");
1152 goto error;
1154 if (i + d->bLength > s->descr_len) {
1155 trace_usb_host_parse_error(s->bus_num, s->addr,
1156 "descriptor too long");
1157 goto error;
1159 switch (d->bDescriptorType) {
1160 case 0:
1161 trace_usb_host_parse_error(s->bus_num, s->addr,
1162 "invalid descriptor type");
1163 goto error;
1164 case USB_DT_DEVICE:
1165 if (d->bLength < 0x12) {
1166 trace_usb_host_parse_error(s->bus_num, s->addr,
1167 "device descriptor too short");
1168 goto error;
1170 v = (d->u.device.idVendor_hi << 8) | d->u.device.idVendor_lo;
1171 p = (d->u.device.idProduct_hi << 8) | d->u.device.idProduct_lo;
1172 trace_usb_host_parse_device(s->bus_num, s->addr, v, p);
1173 break;
1174 case USB_DT_CONFIG:
1175 if (d->bLength < 0x09) {
1176 trace_usb_host_parse_error(s->bus_num, s->addr,
1177 "config descriptor too short");
1178 goto error;
1180 configuration = d->u.config.bConfigurationValue;
1181 active = (configuration == s->dev.configuration);
1182 trace_usb_host_parse_config(s->bus_num, s->addr,
1183 configuration, active);
1184 break;
1185 case USB_DT_INTERFACE:
1186 if (d->bLength < 0x09) {
1187 trace_usb_host_parse_error(s->bus_num, s->addr,
1188 "interface descriptor too short");
1189 goto error;
1191 interface = d->u.interface.bInterfaceNumber;
1192 altsetting = d->u.interface.bAlternateSetting;
1193 active = (configuration == s->dev.configuration) &&
1194 (altsetting == s->dev.altsetting[interface]);
1195 trace_usb_host_parse_interface(s->bus_num, s->addr,
1196 interface, altsetting, active);
1197 break;
1198 case USB_DT_ENDPOINT:
1199 if (d->bLength < 0x07) {
1200 trace_usb_host_parse_error(s->bus_num, s->addr,
1201 "endpoint descriptor too short");
1202 goto error;
1204 devep = d->u.endpoint.bEndpointAddress;
1205 pid = (devep & USB_DIR_IN) ? USB_TOKEN_IN : USB_TOKEN_OUT;
1206 ep = devep & 0xf;
1207 if (ep == 0) {
1208 trace_usb_host_parse_error(s->bus_num, s->addr,
1209 "invalid endpoint address");
1210 goto error;
1213 type = d->u.endpoint.bmAttributes & 0x3;
1214 mps = d->u.endpoint.wMaxPacketSize_lo |
1215 (d->u.endpoint.wMaxPacketSize_hi << 8);
1216 trace_usb_host_parse_endpoint(s->bus_num, s->addr, ep,
1217 (devep & USB_DIR_IN) ? "in" : "out",
1218 tname[type], active);
1220 if (active) {
1221 usb_ep_set_max_packet_size(&s->dev, pid, ep, mps);
1222 assert(usb_ep_get_type(&s->dev, pid, ep) ==
1223 USB_ENDPOINT_XFER_INVALID);
1224 usb_ep_set_type(&s->dev, pid, ep, type);
1225 usb_ep_set_ifnum(&s->dev, pid, ep, interface);
1226 if ((s->options & (1 << USB_HOST_OPT_PIPELINE)) &&
1227 (type == USB_ENDPOINT_XFER_BULK) &&
1228 (pid == USB_TOKEN_OUT)) {
1229 usb_ep_set_pipeline(&s->dev, pid, ep, true);
1232 epd = get_endp(s, pid, ep);
1233 epd->halted = 0;
1236 break;
1237 default:
1238 trace_usb_host_parse_unknown(s->bus_num, s->addr,
1239 d->bLength, d->bDescriptorType);
1240 break;
1243 return 0;
1245 error:
1246 usb_ep_reset(&s->dev);
1247 return 1;
1251 * Check if we can safely redirect a usb2 device to a usb1 virtual controller,
1252 * this function assumes this is safe, if:
1253 * 1) There are no isoc endpoints
1254 * 2) There are no interrupt endpoints with a max_packet_size > 64
1255 * Note bulk endpoints with a max_packet_size > 64 in theory also are not
1256 * usb1 compatible, but in practice this seems to work fine.
1258 static int usb_linux_full_speed_compat(USBHostDevice *dev)
1260 int i, packet_size;
1263 * usb_linux_update_endp_table only registers info about ep in the current
1264 * interface altsettings, so we need to parse the descriptors again.
1266 for (i = 0; (i + 5) < dev->descr_len; i += dev->descr[i]) {
1267 if (dev->descr[i + 1] == USB_DT_ENDPOINT) {
1268 switch (dev->descr[i + 3] & 0x3) {
1269 case 0x00: /* CONTROL */
1270 break;
1271 case 0x01: /* ISO */
1272 return 0;
1273 case 0x02: /* BULK */
1274 break;
1275 case 0x03: /* INTERRUPT */
1276 packet_size = dev->descr[i + 4] + (dev->descr[i + 5] << 8);
1277 if (packet_size > 64)
1278 return 0;
1279 break;
1283 return 1;
1286 static int usb_host_open(USBHostDevice *dev, int bus_num,
1287 int addr, const char *port,
1288 const char *prod_name, int speed)
1290 int fd = -1, ret;
1292 trace_usb_host_open_started(bus_num, addr);
1294 if (dev->fd != -1) {
1295 goto fail;
1298 fd = usb_host_open_device(bus_num, addr);
1299 if (fd < 0) {
1300 goto fail;
1302 DPRINTF("husb: opened %s\n", buf);
1304 dev->bus_num = bus_num;
1305 dev->addr = addr;
1306 strcpy(dev->port, port);
1307 dev->fd = fd;
1309 /* read the device description */
1310 dev->descr_len = read(fd, dev->descr, sizeof(dev->descr));
1311 if (dev->descr_len <= 0) {
1312 perror("husb: reading device data failed");
1313 goto fail;
1316 #ifdef DEBUG
1318 int x;
1319 printf("=== begin dumping device descriptor data ===\n");
1320 for (x = 0; x < dev->descr_len; x++) {
1321 printf("%02x ", dev->descr[x]);
1323 printf("\n=== end dumping device descriptor data ===\n");
1325 #endif
1328 /* start unconfigured -- we'll wait for the guest to set a configuration */
1329 if (!usb_host_claim_interfaces(dev, 0)) {
1330 goto fail;
1333 usb_ep_init(&dev->dev);
1334 ret = usb_linux_update_endp_table(dev);
1335 if (ret) {
1336 goto fail;
1339 if (speed == -1) {
1340 struct usbdevfs_connectinfo ci;
1342 ret = ioctl(fd, USBDEVFS_CONNECTINFO, &ci);
1343 if (ret < 0) {
1344 perror("usb_host_device_open: USBDEVFS_CONNECTINFO");
1345 goto fail;
1348 if (ci.slow) {
1349 speed = USB_SPEED_LOW;
1350 } else {
1351 speed = USB_SPEED_HIGH;
1354 dev->dev.speed = speed;
1355 dev->dev.speedmask = (1 << speed);
1356 if (dev->dev.speed == USB_SPEED_HIGH && usb_linux_full_speed_compat(dev)) {
1357 dev->dev.speedmask |= USB_SPEED_MASK_FULL;
1360 trace_usb_host_open_success(bus_num, addr);
1362 if (!prod_name || prod_name[0] == '\0') {
1363 snprintf(dev->dev.product_desc, sizeof(dev->dev.product_desc),
1364 "host:%d.%d", bus_num, addr);
1365 } else {
1366 pstrcpy(dev->dev.product_desc, sizeof(dev->dev.product_desc),
1367 prod_name);
1370 ret = usb_device_attach(&dev->dev);
1371 if (ret) {
1372 goto fail;
1375 /* USB devio uses 'write' flag to check for async completions */
1376 qemu_set_fd_handler(dev->fd, NULL, async_complete, dev);
1378 return 0;
1380 fail:
1381 trace_usb_host_open_failure(bus_num, addr);
1382 if (dev->fd != -1) {
1383 close(dev->fd);
1384 dev->fd = -1;
1386 return -1;
1389 static int usb_host_close(USBHostDevice *dev)
1391 int i;
1393 if (dev->fd == -1) {
1394 return -1;
1397 trace_usb_host_close(dev->bus_num, dev->addr);
1399 qemu_set_fd_handler(dev->fd, NULL, NULL, NULL);
1400 dev->closing = 1;
1401 for (i = 1; i <= USB_MAX_ENDPOINTS; i++) {
1402 if (is_isoc(dev, USB_TOKEN_IN, i)) {
1403 usb_host_stop_n_free_iso(dev, USB_TOKEN_IN, i);
1405 if (is_isoc(dev, USB_TOKEN_OUT, i)) {
1406 usb_host_stop_n_free_iso(dev, USB_TOKEN_OUT, i);
1409 async_complete(dev);
1410 dev->closing = 0;
1411 if (dev->dev.attached) {
1412 usb_device_detach(&dev->dev);
1414 usb_host_do_reset(dev);
1415 close(dev->fd);
1416 dev->fd = -1;
1417 return 0;
1420 static void usb_host_exit_notifier(struct Notifier *n, void *data)
1422 USBHostDevice *s = container_of(n, USBHostDevice, exit);
1424 usb_host_release_port(s);
1425 if (s->fd != -1) {
1426 usb_host_do_reset(s);;
1431 * This is *NOT* about restoring state. We have absolutely no idea
1432 * what state the host device is in at the moment and whenever it is
1433 * still present in the first place. Attemping to contine where we
1434 * left off is impossible.
1436 * What we are going to to to here is emulate a surprise removal of
1437 * the usb device passed through, then kick host scan so the device
1438 * will get re-attached (and re-initialized by the guest) in case it
1439 * is still present.
1441 * As the device removal will change the state of other devices (usb
1442 * host controller, most likely interrupt controller too) we have to
1443 * wait with it until *all* vmstate is loaded. Thus post_load just
1444 * kicks a bottom half which then does the actual work.
1446 static void usb_host_post_load_bh(void *opaque)
1448 USBHostDevice *dev = opaque;
1450 if (dev->fd != -1) {
1451 usb_host_close(dev);
1453 if (dev->dev.attached) {
1454 usb_device_detach(&dev->dev);
1456 usb_host_auto_check(NULL);
1459 static int usb_host_post_load(void *opaque, int version_id)
1461 USBHostDevice *dev = opaque;
1463 qemu_bh_schedule(dev->bh);
1464 return 0;
1467 static int usb_host_initfn(USBDevice *dev)
1469 USBHostDevice *s = DO_UPCAST(USBHostDevice, dev, dev);
1471 dev->auto_attach = 0;
1472 s->fd = -1;
1473 s->hub_fd = -1;
1475 QTAILQ_INSERT_TAIL(&hostdevs, s, next);
1476 s->exit.notify = usb_host_exit_notifier;
1477 qemu_add_exit_notifier(&s->exit);
1478 s->bh = qemu_bh_new(usb_host_post_load_bh, s);
1479 usb_host_auto_check(NULL);
1481 if (s->match.bus_num != 0 && s->match.port != NULL) {
1482 usb_host_claim_port(s);
1484 add_boot_device_path(s->bootindex, &dev->qdev, NULL);
1485 return 0;
1488 static const VMStateDescription vmstate_usb_host = {
1489 .name = "usb-host",
1490 .version_id = 1,
1491 .minimum_version_id = 1,
1492 .post_load = usb_host_post_load,
1493 .fields = (VMStateField[]) {
1494 VMSTATE_USB_DEVICE(dev, USBHostDevice),
1495 VMSTATE_END_OF_LIST()
1499 static Property usb_host_dev_properties[] = {
1500 DEFINE_PROP_UINT32("hostbus", USBHostDevice, match.bus_num, 0),
1501 DEFINE_PROP_UINT32("hostaddr", USBHostDevice, match.addr, 0),
1502 DEFINE_PROP_STRING("hostport", USBHostDevice, match.port),
1503 DEFINE_PROP_HEX32("vendorid", USBHostDevice, match.vendor_id, 0),
1504 DEFINE_PROP_HEX32("productid", USBHostDevice, match.product_id, 0),
1505 DEFINE_PROP_UINT32("isobufs", USBHostDevice, iso_urb_count, 4),
1506 DEFINE_PROP_INT32("bootindex", USBHostDevice, bootindex, -1),
1507 DEFINE_PROP_BIT("pipeline", USBHostDevice, options,
1508 USB_HOST_OPT_PIPELINE, true),
1509 DEFINE_PROP_END_OF_LIST(),
1512 static void usb_host_class_initfn(ObjectClass *klass, void *data)
1514 DeviceClass *dc = DEVICE_CLASS(klass);
1515 USBDeviceClass *uc = USB_DEVICE_CLASS(klass);
1517 uc->init = usb_host_initfn;
1518 uc->product_desc = "USB Host Device";
1519 uc->cancel_packet = usb_host_async_cancel;
1520 uc->handle_data = usb_host_handle_data;
1521 uc->handle_control = usb_host_handle_control;
1522 uc->handle_reset = usb_host_handle_reset;
1523 uc->handle_destroy = usb_host_handle_destroy;
1524 dc->vmsd = &vmstate_usb_host;
1525 dc->props = usb_host_dev_properties;
1528 static TypeInfo usb_host_dev_info = {
1529 .name = "usb-host",
1530 .parent = TYPE_USB_DEVICE,
1531 .instance_size = sizeof(USBHostDevice),
1532 .class_init = usb_host_class_initfn,
1535 static void usb_host_register_types(void)
1537 type_register_static(&usb_host_dev_info);
1538 usb_legacy_register("usb-host", "host", usb_host_device_open);
1541 type_init(usb_host_register_types)
1543 USBDevice *usb_host_device_open(USBBus *bus, const char *devname)
1545 struct USBAutoFilter filter;
1546 USBDevice *dev;
1547 char *p;
1549 dev = usb_create(bus, "usb-host");
1551 if (strstr(devname, "auto:")) {
1552 if (parse_filter(devname, &filter) < 0) {
1553 goto fail;
1555 } else {
1556 if ((p = strchr(devname, '.'))) {
1557 filter.bus_num = strtoul(devname, NULL, 0);
1558 filter.addr = strtoul(p + 1, NULL, 0);
1559 filter.vendor_id = 0;
1560 filter.product_id = 0;
1561 } else if ((p = strchr(devname, ':'))) {
1562 filter.bus_num = 0;
1563 filter.addr = 0;
1564 filter.vendor_id = strtoul(devname, NULL, 16);
1565 filter.product_id = strtoul(p + 1, NULL, 16);
1566 } else {
1567 goto fail;
1571 qdev_prop_set_uint32(&dev->qdev, "hostbus", filter.bus_num);
1572 qdev_prop_set_uint32(&dev->qdev, "hostaddr", filter.addr);
1573 qdev_prop_set_uint32(&dev->qdev, "vendorid", filter.vendor_id);
1574 qdev_prop_set_uint32(&dev->qdev, "productid", filter.product_id);
1575 qdev_init_nofail(&dev->qdev);
1576 return dev;
1578 fail:
1579 qdev_free(&dev->qdev);
1580 return NULL;
1583 int usb_host_device_close(const char *devname)
1585 #if 0
1586 char product_name[PRODUCT_NAME_SZ];
1587 int bus_num, addr;
1588 USBHostDevice *s;
1590 if (strstr(devname, "auto:")) {
1591 return usb_host_auto_del(devname);
1593 if (usb_host_find_device(&bus_num, &addr, product_name,
1594 sizeof(product_name), devname) < 0) {
1595 return -1;
1597 s = hostdev_find(bus_num, addr);
1598 if (s) {
1599 usb_device_delete_addr(s->bus_num, s->dev.addr);
1600 return 0;
1602 #endif
1604 return -1;
1608 * Read sys file-system device file
1610 * @line address of buffer to put file contents in
1611 * @line_size size of line
1612 * @device_file path to device file (printf format string)
1613 * @device_name device being opened (inserted into device_file)
1615 * @return 0 failed, 1 succeeded ('line' contains data)
1617 static int usb_host_read_file(char *line, size_t line_size,
1618 const char *device_file, const char *device_name)
1620 FILE *f;
1621 int ret = 0;
1622 char filename[PATH_MAX];
1624 snprintf(filename, PATH_MAX, "/sys/bus/usb/devices/%s/%s", device_name,
1625 device_file);
1626 f = fopen(filename, "r");
1627 if (f) {
1628 ret = fgets(line, line_size, f) != NULL;
1629 fclose(f);
1632 return ret;
1636 * Use /sys/bus/usb/devices/ directory to determine host's USB
1637 * devices.
1639 * This code is based on Robert Schiele's original patches posted to
1640 * the Novell bug-tracker https://bugzilla.novell.com/show_bug.cgi?id=241950
1642 static int usb_host_scan(void *opaque, USBScanFunc *func)
1644 DIR *dir = NULL;
1645 char line[1024];
1646 int bus_num, addr, speed, class_id, product_id, vendor_id;
1647 int ret = 0;
1648 char port[MAX_PORTLEN];
1649 char product_name[512];
1650 struct dirent *de;
1652 dir = opendir("/sys/bus/usb/devices");
1653 if (!dir) {
1654 perror("husb: opendir /sys/bus/usb/devices");
1655 fprintf(stderr, "husb: please make sure sysfs is mounted at /sys\n");
1656 goto the_end;
1659 while ((de = readdir(dir))) {
1660 if (de->d_name[0] != '.' && !strchr(de->d_name, ':')) {
1661 if (sscanf(de->d_name, "%d-%7[0-9.]", &bus_num, port) < 2) {
1662 continue;
1665 if (!usb_host_read_file(line, sizeof(line), "devnum", de->d_name)) {
1666 goto the_end;
1668 if (sscanf(line, "%d", &addr) != 1) {
1669 goto the_end;
1671 if (!usb_host_read_file(line, sizeof(line), "bDeviceClass",
1672 de->d_name)) {
1673 goto the_end;
1675 if (sscanf(line, "%x", &class_id) != 1) {
1676 goto the_end;
1679 if (!usb_host_read_file(line, sizeof(line), "idVendor",
1680 de->d_name)) {
1681 goto the_end;
1683 if (sscanf(line, "%x", &vendor_id) != 1) {
1684 goto the_end;
1686 if (!usb_host_read_file(line, sizeof(line), "idProduct",
1687 de->d_name)) {
1688 goto the_end;
1690 if (sscanf(line, "%x", &product_id) != 1) {
1691 goto the_end;
1693 if (!usb_host_read_file(line, sizeof(line), "product",
1694 de->d_name)) {
1695 *product_name = 0;
1696 } else {
1697 if (strlen(line) > 0) {
1698 line[strlen(line) - 1] = '\0';
1700 pstrcpy(product_name, sizeof(product_name), line);
1703 if (!usb_host_read_file(line, sizeof(line), "speed", de->d_name)) {
1704 goto the_end;
1706 if (!strcmp(line, "5000\n")) {
1707 speed = USB_SPEED_SUPER;
1708 } else if (!strcmp(line, "480\n")) {
1709 speed = USB_SPEED_HIGH;
1710 } else if (!strcmp(line, "1.5\n")) {
1711 speed = USB_SPEED_LOW;
1712 } else {
1713 speed = USB_SPEED_FULL;
1716 ret = func(opaque, bus_num, addr, port, class_id, vendor_id,
1717 product_id, product_name, speed);
1718 if (ret) {
1719 goto the_end;
1723 the_end:
1724 if (dir) {
1725 closedir(dir);
1727 return ret;
1730 static QEMUTimer *usb_auto_timer;
1732 static int usb_host_auto_scan(void *opaque, int bus_num,
1733 int addr, const char *port,
1734 int class_id, int vendor_id, int product_id,
1735 const char *product_name, int speed)
1737 struct USBAutoFilter *f;
1738 struct USBHostDevice *s;
1740 /* Ignore hubs */
1741 if (class_id == 9)
1742 return 0;
1744 QTAILQ_FOREACH(s, &hostdevs, next) {
1745 f = &s->match;
1747 if (f->bus_num > 0 && f->bus_num != bus_num) {
1748 continue;
1750 if (f->addr > 0 && f->addr != addr) {
1751 continue;
1753 if (f->port != NULL && (port == NULL || strcmp(f->port, port) != 0)) {
1754 continue;
1757 if (f->vendor_id > 0 && f->vendor_id != vendor_id) {
1758 continue;
1761 if (f->product_id > 0 && f->product_id != product_id) {
1762 continue;
1764 /* We got a match */
1765 s->seen++;
1766 if (s->errcount >= 3) {
1767 return 0;
1770 /* Already attached ? */
1771 if (s->fd != -1) {
1772 return 0;
1774 DPRINTF("husb: auto open: bus_num %d addr %d\n", bus_num, addr);
1776 if (usb_host_open(s, bus_num, addr, port, product_name, speed) < 0) {
1777 s->errcount++;
1779 break;
1782 return 0;
1785 static void usb_host_auto_check(void *unused)
1787 struct USBHostDevice *s;
1788 int unconnected = 0;
1790 if (runstate_is_running()) {
1791 usb_host_scan(NULL, usb_host_auto_scan);
1793 QTAILQ_FOREACH(s, &hostdevs, next) {
1794 if (s->fd == -1) {
1795 unconnected++;
1797 if (s->seen == 0) {
1798 s->errcount = 0;
1800 s->seen = 0;
1803 if (unconnected == 0) {
1804 /* nothing to watch */
1805 if (usb_auto_timer) {
1806 qemu_del_timer(usb_auto_timer);
1807 trace_usb_host_auto_scan_disabled();
1809 return;
1813 if (!usb_auto_timer) {
1814 usb_auto_timer = qemu_new_timer_ms(rt_clock, usb_host_auto_check, NULL);
1815 if (!usb_auto_timer) {
1816 return;
1818 trace_usb_host_auto_scan_enabled();
1820 qemu_mod_timer(usb_auto_timer, qemu_get_clock_ms(rt_clock) + 2000);
1824 * Autoconnect filter
1825 * Format:
1826 * auto:bus:dev[:vid:pid]
1827 * auto:bus.dev[:vid:pid]
1829 * bus - bus number (dec, * means any)
1830 * dev - device number (dec, * means any)
1831 * vid - vendor id (hex, * means any)
1832 * pid - product id (hex, * means any)
1834 * See 'lsusb' output.
1836 static int parse_filter(const char *spec, struct USBAutoFilter *f)
1838 enum { BUS, DEV, VID, PID, DONE };
1839 const char *p = spec;
1840 int i;
1842 f->bus_num = 0;
1843 f->addr = 0;
1844 f->vendor_id = 0;
1845 f->product_id = 0;
1847 for (i = BUS; i < DONE; i++) {
1848 p = strpbrk(p, ":.");
1849 if (!p) {
1850 break;
1852 p++;
1854 if (*p == '*') {
1855 continue;
1857 switch(i) {
1858 case BUS: f->bus_num = strtol(p, NULL, 10); break;
1859 case DEV: f->addr = strtol(p, NULL, 10); break;
1860 case VID: f->vendor_id = strtol(p, NULL, 16); break;
1861 case PID: f->product_id = strtol(p, NULL, 16); break;
1865 if (i < DEV) {
1866 fprintf(stderr, "husb: invalid auto filter spec %s\n", spec);
1867 return -1;
1870 return 0;
1873 /**********************/
1874 /* USB host device info */
1876 struct usb_class_info {
1877 int class;
1878 const char *class_name;
1881 static const struct usb_class_info usb_class_info[] = {
1882 { USB_CLASS_AUDIO, "Audio"},
1883 { USB_CLASS_COMM, "Communication"},
1884 { USB_CLASS_HID, "HID"},
1885 { USB_CLASS_HUB, "Hub" },
1886 { USB_CLASS_PHYSICAL, "Physical" },
1887 { USB_CLASS_PRINTER, "Printer" },
1888 { USB_CLASS_MASS_STORAGE, "Storage" },
1889 { USB_CLASS_CDC_DATA, "Data" },
1890 { USB_CLASS_APP_SPEC, "Application Specific" },
1891 { USB_CLASS_VENDOR_SPEC, "Vendor Specific" },
1892 { USB_CLASS_STILL_IMAGE, "Still Image" },
1893 { USB_CLASS_CSCID, "Smart Card" },
1894 { USB_CLASS_CONTENT_SEC, "Content Security" },
1895 { -1, NULL }
1898 static const char *usb_class_str(uint8_t class)
1900 const struct usb_class_info *p;
1901 for(p = usb_class_info; p->class != -1; p++) {
1902 if (p->class == class) {
1903 break;
1906 return p->class_name;
1909 static void usb_info_device(Monitor *mon, int bus_num,
1910 int addr, const char *port,
1911 int class_id, int vendor_id, int product_id,
1912 const char *product_name,
1913 int speed)
1915 const char *class_str, *speed_str;
1917 switch(speed) {
1918 case USB_SPEED_LOW:
1919 speed_str = "1.5";
1920 break;
1921 case USB_SPEED_FULL:
1922 speed_str = "12";
1923 break;
1924 case USB_SPEED_HIGH:
1925 speed_str = "480";
1926 break;
1927 case USB_SPEED_SUPER:
1928 speed_str = "5000";
1929 break;
1930 default:
1931 speed_str = "?";
1932 break;
1935 monitor_printf(mon, " Bus %d, Addr %d, Port %s, Speed %s Mb/s\n",
1936 bus_num, addr, port, speed_str);
1937 class_str = usb_class_str(class_id);
1938 if (class_str) {
1939 monitor_printf(mon, " %s:", class_str);
1940 } else {
1941 monitor_printf(mon, " Class %02x:", class_id);
1943 monitor_printf(mon, " USB device %04x:%04x", vendor_id, product_id);
1944 if (product_name[0] != '\0') {
1945 monitor_printf(mon, ", %s", product_name);
1947 monitor_printf(mon, "\n");
1950 static int usb_host_info_device(void *opaque, int bus_num, int addr,
1951 const char *path, int class_id,
1952 int vendor_id, int product_id,
1953 const char *product_name,
1954 int speed)
1956 Monitor *mon = opaque;
1958 usb_info_device(mon, bus_num, addr, path, class_id, vendor_id, product_id,
1959 product_name, speed);
1960 return 0;
1963 static void dec2str(int val, char *str, size_t size)
1965 if (val == 0) {
1966 snprintf(str, size, "*");
1967 } else {
1968 snprintf(str, size, "%d", val);
1972 static void hex2str(int val, char *str, size_t size)
1974 if (val == 0) {
1975 snprintf(str, size, "*");
1976 } else {
1977 snprintf(str, size, "%04x", val);
1981 void usb_host_info(Monitor *mon)
1983 struct USBAutoFilter *f;
1984 struct USBHostDevice *s;
1986 usb_host_scan(mon, usb_host_info_device);
1988 if (QTAILQ_EMPTY(&hostdevs)) {
1989 return;
1992 monitor_printf(mon, " Auto filters:\n");
1993 QTAILQ_FOREACH(s, &hostdevs, next) {
1994 char bus[10], addr[10], vid[10], pid[10];
1995 f = &s->match;
1996 dec2str(f->bus_num, bus, sizeof(bus));
1997 dec2str(f->addr, addr, sizeof(addr));
1998 hex2str(f->vendor_id, vid, sizeof(vid));
1999 hex2str(f->product_id, pid, sizeof(pid));
2000 monitor_printf(mon, " Bus %s, Addr %s, Port %s, ID %s:%s\n",
2001 bus, addr, f->port ? f->port : "*", vid, pid);