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
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
33 #include "qemu-common.h"
34 #include "qemu-timer.h"
39 #include <sys/ioctl.h>
42 #include <linux/usbdevice_fs.h>
43 #include <linux/version.h>
46 /* We redefine it to avoid version problems */
47 struct usb_ctrltransfer {
57 struct usb_ctrlrequest {
65 typedef int USBScanFunc(void *opaque, int bus_num, int addr, int devpath,
66 int class_id, int vendor_id, int product_id,
67 const char *product_name, int speed);
72 #define DPRINTF printf
77 #define USBDBG_DEVOPENED "husb: opened %s/devices\n"
79 #define USBPROCBUS_PATH "/proc/bus/usb"
80 #define PRODUCT_NAME_SZ 32
81 #define MAX_ENDPOINTS 16
82 #define USBDEVBUS_PATH "/dev/bus/usb"
83 #define USBSYSBUS_PATH "/sys/bus/usb"
85 static char *usb_host_device_path;
92 static int usb_fs_type;
94 /* endpoint association data */
108 * Control transfer state.
109 * Note that 'buffer' _must_ follow 'req' field because
110 * we need contiguous buffer when we submit control URB.
116 struct usb_ctrlrequest req;
117 uint8_t buffer[8192];
120 struct USBAutoFilter {
127 typedef struct USBHostDevice {
138 struct ctrl_struct ctrl;
139 struct endp_data endp_table[MAX_ENDPOINTS];
141 /* Host side address */
145 struct USBAutoFilter match;
147 QTAILQ_ENTRY(USBHostDevice) next;
150 static QTAILQ_HEAD(, USBHostDevice) hostdevs = QTAILQ_HEAD_INITIALIZER(hostdevs);
152 static int usb_host_close(USBHostDevice *dev);
153 static int parse_filter(const char *spec, struct USBAutoFilter *f);
154 static void usb_host_auto_check(void *unused);
155 static int usb_host_read_file(char *line, size_t line_size,
156 const char *device_file, const char *device_name);
158 static int is_isoc(USBHostDevice *s, int ep)
160 return s->endp_table[ep - 1].type == USBDEVFS_URB_TYPE_ISO;
163 static int is_halted(USBHostDevice *s, int ep)
165 return s->endp_table[ep - 1].halted;
168 static void clear_halt(USBHostDevice *s, int ep)
170 s->endp_table[ep - 1].halted = 0;
173 static void set_halt(USBHostDevice *s, int ep)
175 s->endp_table[ep - 1].halted = 1;
180 * We always allocate one isoc descriptor even for bulk transfers
181 * to simplify allocation and casts.
183 typedef struct AsyncURB
185 struct usbdevfs_urb urb;
186 struct usbdevfs_iso_packet_desc isocpd;
192 static AsyncURB *async_alloc(void)
194 return (AsyncURB *) qemu_mallocz(sizeof(AsyncURB));
197 static void async_free(AsyncURB *aurb)
202 static void async_complete_ctrl(USBHostDevice *s, USBPacket *p)
204 switch(s->ctrl.state) {
205 case CTRL_STATE_SETUP:
206 if (p->len < s->ctrl.len)
207 s->ctrl.len = p->len;
208 s->ctrl.state = CTRL_STATE_DATA;
213 s->ctrl.state = CTRL_STATE_IDLE;
222 static void async_complete(void *opaque)
224 USBHostDevice *s = opaque;
230 int r = ioctl(s->fd, USBDEVFS_REAPURBNDELAY, &aurb);
232 if (errno == EAGAIN) {
235 if (errno == ENODEV && !s->closing) {
236 printf("husb: device %d.%d disconnected\n",
237 s->bus_num, s->addr);
239 usb_host_auto_check(NULL);
243 DPRINTF("husb: async. reap urb failed errno %d\n", errno);
249 DPRINTF("husb: async completed. aurb %p status %d alen %d\n",
250 aurb, aurb->urb.status, aurb->urb.actual_length);
253 switch (aurb->urb.status) {
255 p->len = aurb->urb.actual_length;
256 if (aurb->urb.type == USBDEVFS_URB_TYPE_CONTROL) {
257 async_complete_ctrl(s, p);
262 set_halt(s, p->devep);
263 p->len = USB_RET_STALL;
267 p->len = USB_RET_NAK;
271 usb_packet_complete(p);
278 static void async_cancel(USBPacket *unused, void *opaque)
280 AsyncURB *aurb = opaque;
281 USBHostDevice *s = aurb->hdev;
283 DPRINTF("husb: async cancel. aurb %p\n", aurb);
285 /* Mark it as dead (see async_complete above) */
288 int r = ioctl(s->fd, USBDEVFS_DISCARDURB, aurb);
290 DPRINTF("husb: async. discard urb failed errno %d\n", errno);
294 static int usb_host_claim_interfaces(USBHostDevice *dev, int configuration)
296 int dev_descr_len, config_descr_len;
297 int interface, nb_interfaces;
300 if (configuration == 0) /* address state - ignore */
303 DPRINTF("husb: claiming interfaces. config %d\n", configuration);
306 dev_descr_len = dev->descr[0];
307 if (dev_descr_len > dev->descr_len) {
312 while (i < dev->descr_len) {
313 DPRINTF("husb: i is %d, descr_len is %d, dl %d, dt %d\n",
315 dev->descr[i], dev->descr[i+1]);
317 if (dev->descr[i+1] != USB_DT_CONFIG) {
321 config_descr_len = dev->descr[i];
323 printf("husb: config #%d need %d\n", dev->descr[i + 5], configuration);
325 if (configuration < 0 || configuration == dev->descr[i + 5]) {
326 configuration = dev->descr[i + 5];
330 i += config_descr_len;
333 if (i >= dev->descr_len) {
335 "husb: update iface failed. no matching configuration\n");
338 nb_interfaces = dev->descr[i + 4];
340 #ifdef USBDEVFS_DISCONNECT
341 /* earlier Linux 2.4 do not support that */
343 struct usbdevfs_ioctl ctrl;
344 for (interface = 0; interface < nb_interfaces; interface++) {
345 ctrl.ioctl_code = USBDEVFS_DISCONNECT;
346 ctrl.ifno = interface;
348 ret = ioctl(dev->fd, USBDEVFS_IOCTL, &ctrl);
349 if (ret < 0 && errno != ENODATA) {
350 perror("USBDEVFS_DISCONNECT");
357 /* XXX: only grab if all interfaces are free */
358 for (interface = 0; interface < nb_interfaces; interface++) {
359 ret = ioctl(dev->fd, USBDEVFS_CLAIMINTERFACE, &interface);
361 if (errno == EBUSY) {
362 printf("husb: update iface. device already grabbed\n");
364 perror("husb: failed to claim interface");
371 printf("husb: %d interfaces claimed for configuration %d\n",
372 nb_interfaces, configuration);
374 dev->ninterfaces = nb_interfaces;
375 dev->configuration = configuration;
379 static int usb_host_release_interfaces(USBHostDevice *s)
383 DPRINTF("husb: releasing interfaces\n");
385 for (i = 0; i < s->ninterfaces; i++) {
386 ret = ioctl(s->fd, USBDEVFS_RELEASEINTERFACE, &i);
388 perror("husb: failed to release interface");
396 static void usb_host_handle_reset(USBDevice *dev)
398 USBHostDevice *s = DO_UPCAST(USBHostDevice, dev, dev);
400 DPRINTF("husb: reset device %u.%u\n", s->bus_num, s->addr);
402 ioctl(s->fd, USBDEVFS_RESET);
404 usb_host_claim_interfaces(s, s->configuration);
407 static void usb_host_handle_destroy(USBDevice *dev)
409 USBHostDevice *s = (USBHostDevice *)dev;
412 QTAILQ_REMOVE(&hostdevs, s, next);
413 qemu_remove_exit_notifier(&s->exit);
416 static int usb_linux_update_endp_table(USBHostDevice *s);
418 static int usb_host_handle_data(USBHostDevice *s, USBPacket *p)
420 struct usbdevfs_urb *urb;
424 aurb = async_alloc();
430 if (p->pid == USB_TOKEN_IN) {
431 urb->endpoint = p->devep | 0x80;
433 urb->endpoint = p->devep;
436 if (is_halted(s, p->devep)) {
437 ret = ioctl(s->fd, USBDEVFS_CLEAR_HALT, &urb->endpoint);
439 DPRINTF("husb: failed to clear halt. ep 0x%x errno %d\n",
440 urb->endpoint, errno);
443 clear_halt(s, p->devep);
446 urb->buffer = p->data;
447 urb->buffer_length = p->len;
449 if (is_isoc(s, p->devep)) {
450 /* Setup ISOC transfer */
451 urb->type = USBDEVFS_URB_TYPE_ISO;
452 urb->flags = USBDEVFS_URB_ISO_ASAP;
453 urb->number_of_packets = 1;
454 urb->iso_frame_desc[0].length = p->len;
456 /* Setup bulk transfer */
457 urb->type = USBDEVFS_URB_TYPE_BULK;
460 urb->usercontext = s;
462 ret = ioctl(s->fd, USBDEVFS_SUBMITURB, urb);
464 DPRINTF("husb: data submit. ep 0x%x len %u aurb %p\n",
465 urb->endpoint, p->len, aurb);
468 DPRINTF("husb: submit failed. errno %d\n", errno);
476 return USB_RET_STALL;
480 usb_defer_packet(p, async_cancel, aurb);
481 return USB_RET_ASYNC;
484 static int ctrl_error(void)
486 if (errno == ETIMEDOUT) {
489 return USB_RET_STALL;
493 static int usb_host_set_address(USBHostDevice *s, int addr)
495 DPRINTF("husb: ctrl set addr %u\n", addr);
500 static int usb_host_set_config(USBHostDevice *s, int config)
502 usb_host_release_interfaces(s);
504 int ret = ioctl(s->fd, USBDEVFS_SETCONFIGURATION, &config);
506 DPRINTF("husb: ctrl set config %d ret %d errno %d\n", config, ret, errno);
511 usb_host_claim_interfaces(s, config);
515 static int usb_host_set_interface(USBHostDevice *s, int iface, int alt)
517 struct usbdevfs_setinterface si;
520 si.interface = iface;
522 ret = ioctl(s->fd, USBDEVFS_SETINTERFACE, &si);
524 DPRINTF("husb: ctrl set iface %d altset %d ret %d errno %d\n",
525 iface, alt, ret, errno);
530 usb_linux_update_endp_table(s);
534 static int usb_host_handle_control(USBHostDevice *s, USBPacket *p)
536 struct usbdevfs_urb *urb;
538 int ret, value, index;
542 * Process certain standard device requests.
543 * These are infrequent and are processed synchronously.
545 value = le16_to_cpu(s->ctrl.req.wValue);
546 index = le16_to_cpu(s->ctrl.req.wIndex);
548 DPRINTF("husb: ctrl type 0x%x req 0x%x val 0x%x index %u len %u\n",
549 s->ctrl.req.bRequestType, s->ctrl.req.bRequest, value, index,
552 if (s->ctrl.req.bRequestType == 0) {
553 switch (s->ctrl.req.bRequest) {
554 case USB_REQ_SET_ADDRESS:
555 return usb_host_set_address(s, value);
557 case USB_REQ_SET_CONFIGURATION:
558 return usb_host_set_config(s, value & 0xff);
562 if (s->ctrl.req.bRequestType == 1 &&
563 s->ctrl.req.bRequest == USB_REQ_SET_INTERFACE) {
564 return usb_host_set_interface(s, index, value);
567 /* The rest are asynchronous */
569 buffer_len = 8 + s->ctrl.len;
570 if (buffer_len > sizeof(s->ctrl.buffer)) {
571 fprintf(stderr, "husb: ctrl buffer too small (%u > %zu)\n",
572 buffer_len, sizeof(s->ctrl.buffer));
573 return USB_RET_STALL;
576 aurb = async_alloc();
581 * Setup ctrl transfer.
583 * s->ctrl is laid out such that data buffer immediately follows
584 * 'req' struct which is exactly what usbdevfs expects.
588 urb->type = USBDEVFS_URB_TYPE_CONTROL;
589 urb->endpoint = p->devep;
591 urb->buffer = &s->ctrl.req;
592 urb->buffer_length = buffer_len;
594 urb->usercontext = s;
596 ret = ioctl(s->fd, USBDEVFS_SUBMITURB, urb);
598 DPRINTF("husb: submit ctrl. len %u aurb %p\n", urb->buffer_length, aurb);
601 DPRINTF("husb: submit failed. errno %d\n", errno);
609 return USB_RET_STALL;
613 usb_defer_packet(p, async_cancel, aurb);
614 return USB_RET_ASYNC;
617 static int do_token_setup(USBDevice *dev, USBPacket *p)
619 USBHostDevice *s = (USBHostDevice *) dev;
623 return USB_RET_STALL;
626 memcpy(&s->ctrl.req, p->data, 8);
627 s->ctrl.len = le16_to_cpu(s->ctrl.req.wLength);
629 s->ctrl.state = CTRL_STATE_SETUP;
631 if (s->ctrl.req.bRequestType & USB_DIR_IN) {
632 ret = usb_host_handle_control(s, p);
637 if (ret < s->ctrl.len) {
640 s->ctrl.state = CTRL_STATE_DATA;
642 if (s->ctrl.len == 0) {
643 s->ctrl.state = CTRL_STATE_ACK;
645 s->ctrl.state = CTRL_STATE_DATA;
652 static int do_token_in(USBDevice *dev, USBPacket *p)
654 USBHostDevice *s = (USBHostDevice *) dev;
658 return usb_host_handle_data(s, p);
661 switch(s->ctrl.state) {
663 if (!(s->ctrl.req.bRequestType & USB_DIR_IN)) {
664 ret = usb_host_handle_control(s, p);
665 if (ret == USB_RET_ASYNC) {
666 return USB_RET_ASYNC;
668 s->ctrl.state = CTRL_STATE_IDLE;
669 return ret > 0 ? 0 : ret;
674 case CTRL_STATE_DATA:
675 if (s->ctrl.req.bRequestType & USB_DIR_IN) {
676 int len = s->ctrl.len - s->ctrl.offset;
680 memcpy(p->data, s->ctrl.buffer + s->ctrl.offset, len);
681 s->ctrl.offset += len;
682 if (s->ctrl.offset >= s->ctrl.len) {
683 s->ctrl.state = CTRL_STATE_ACK;
688 s->ctrl.state = CTRL_STATE_IDLE;
689 return USB_RET_STALL;
692 return USB_RET_STALL;
696 static int do_token_out(USBDevice *dev, USBPacket *p)
698 USBHostDevice *s = (USBHostDevice *) dev;
701 return usb_host_handle_data(s, p);
704 switch(s->ctrl.state) {
706 if (s->ctrl.req.bRequestType & USB_DIR_IN) {
707 s->ctrl.state = CTRL_STATE_IDLE;
710 /* ignore additional output */
714 case CTRL_STATE_DATA:
715 if (!(s->ctrl.req.bRequestType & USB_DIR_IN)) {
716 int len = s->ctrl.len - s->ctrl.offset;
720 memcpy(s->ctrl.buffer + s->ctrl.offset, p->data, len);
721 s->ctrl.offset += len;
722 if (s->ctrl.offset >= s->ctrl.len) {
723 s->ctrl.state = CTRL_STATE_ACK;
728 s->ctrl.state = CTRL_STATE_IDLE;
729 return USB_RET_STALL;
732 return USB_RET_STALL;
738 * Called by the HC (host controller).
740 * Returns length of the transaction or one of the USB_RET_XXX codes.
742 static int usb_host_handle_packet(USBDevice *s, USBPacket *p)
746 s->state = USB_STATE_ATTACHED;
750 s->state = USB_STATE_NOTATTACHED;
754 s->remote_wakeup = 0;
756 s->state = USB_STATE_DEFAULT;
757 s->info->handle_reset(s);
761 /* Rest of the PIDs must match our address */
762 if (s->state < USB_STATE_DEFAULT || p->devaddr != s->addr) {
763 return USB_RET_NODEV;
767 case USB_TOKEN_SETUP:
768 return do_token_setup(s, p);
771 return do_token_in(s, p);
774 return do_token_out(s, p);
777 return USB_RET_STALL;
781 static int usb_linux_get_configuration(USBHostDevice *s)
783 uint8_t configuration;
784 struct usb_ctrltransfer ct;
787 if (usb_fs_type == USB_FS_SYS) {
788 char device_name[32], line[1024];
791 sprintf(device_name, "%d-%d", s->bus_num, s->devpath);
793 if (!usb_host_read_file(line, sizeof(line), "bConfigurationValue",
797 if (sscanf(line, "%d", &configuration) != 1) {
800 return configuration;
804 ct.bRequestType = USB_DIR_IN;
805 ct.bRequest = USB_REQ_GET_CONFIGURATION;
809 ct.data = &configuration;
812 ret = ioctl(s->fd, USBDEVFS_CONTROL, &ct);
814 perror("usb_linux_get_configuration");
818 /* in address state */
819 if (configuration == 0) {
823 return configuration;
826 /* returns 1 on problem encountered or 0 for success */
827 static int usb_linux_update_endp_table(USBHostDevice *s)
829 uint8_t *descriptors;
830 uint8_t devep, type, configuration, alt_interface;
831 struct usb_ctrltransfer ct;
832 int interface, ret, length, i;
834 i = usb_linux_get_configuration(s);
839 /* get the desired configuration, interface, and endpoint descriptors
840 * from device description */
841 descriptors = &s->descr[18];
842 length = s->descr_len - 18;
845 if (descriptors[i + 1] != USB_DT_CONFIG ||
846 descriptors[i + 5] != configuration) {
847 DPRINTF("invalid descriptor data - configuration\n");
853 if (descriptors[i + 1] != USB_DT_INTERFACE ||
854 (descriptors[i + 1] == USB_DT_INTERFACE &&
855 descriptors[i + 4] == 0)) {
860 interface = descriptors[i + 2];
862 ct.bRequestType = USB_DIR_IN | USB_RECIP_INTERFACE;
863 ct.bRequest = USB_REQ_GET_INTERFACE;
865 ct.wIndex = interface;
867 ct.data = &alt_interface;
870 ret = ioctl(s->fd, USBDEVFS_CONTROL, &ct);
872 alt_interface = interface;
875 /* the current interface descriptor is the active interface
876 * and has endpoints */
877 if (descriptors[i + 3] != alt_interface) {
882 /* advance to the endpoints */
883 while (i < length && descriptors[i +1] != USB_DT_ENDPOINT) {
891 if (descriptors[i + 1] != USB_DT_ENDPOINT) {
895 devep = descriptors[i + 2];
896 switch (descriptors[i + 3] & 0x3) {
898 type = USBDEVFS_URB_TYPE_CONTROL;
901 type = USBDEVFS_URB_TYPE_ISO;
904 type = USBDEVFS_URB_TYPE_BULK;
907 type = USBDEVFS_URB_TYPE_INTERRUPT;
910 DPRINTF("usb_host: malformed endpoint type\n");
911 type = USBDEVFS_URB_TYPE_BULK;
913 s->endp_table[(devep & 0xf) - 1].type = type;
914 s->endp_table[(devep & 0xf) - 1].halted = 0;
922 static int usb_host_open(USBHostDevice *dev, int bus_num,
923 int addr, int devpath, const char *prod_name)
926 struct usbdevfs_connectinfo ci;
932 printf("husb: open device %d.%d\n", bus_num, addr);
934 if (!usb_host_device_path) {
935 perror("husb: USB Host Device Path not set");
938 snprintf(buf, sizeof(buf), "%s/%03d/%03d", usb_host_device_path,
940 fd = open(buf, O_RDWR | O_NONBLOCK);
945 DPRINTF("husb: opened %s\n", buf);
947 dev->bus_num = bus_num;
949 dev->devpath = devpath;
952 /* read the device description */
953 dev->descr_len = read(fd, dev->descr, sizeof(dev->descr));
954 if (dev->descr_len <= 0) {
955 perror("husb: reading device data failed");
962 printf("=== begin dumping device descriptor data ===\n");
963 for (x = 0; x < dev->descr_len; x++) {
964 printf("%02x ", dev->descr[x]);
966 printf("\n=== end dumping device descriptor data ===\n");
972 * Initial configuration is -1 which makes us claim first
973 * available config. We used to start with 1, which does not
974 * always work. I've seen devices where first config starts
977 if (!usb_host_claim_interfaces(dev, -1)) {
981 ret = ioctl(fd, USBDEVFS_CONNECTINFO, &ci);
983 perror("usb_host_device_open: USBDEVFS_CONNECTINFO");
987 printf("husb: grabbed usb device %d.%d\n", bus_num, addr);
989 ret = usb_linux_update_endp_table(dev);
995 dev->dev.speed = USB_SPEED_LOW;
997 dev->dev.speed = USB_SPEED_HIGH;
1000 if (!prod_name || prod_name[0] == '\0') {
1001 snprintf(dev->dev.product_desc, sizeof(dev->dev.product_desc),
1002 "host:%d.%d", bus_num, addr);
1004 pstrcpy(dev->dev.product_desc, sizeof(dev->dev.product_desc),
1008 /* USB devio uses 'write' flag to check for async completions */
1009 qemu_set_fd_handler(dev->fd, NULL, async_complete, dev);
1011 usb_device_attach(&dev->dev);
1022 static int usb_host_close(USBHostDevice *dev)
1024 if (dev->fd == -1) {
1028 qemu_set_fd_handler(dev->fd, NULL, NULL, NULL);
1030 async_complete(dev);
1032 usb_device_detach(&dev->dev);
1033 ioctl(dev->fd, USBDEVFS_RESET);
1039 static void usb_host_exit_notifier(struct Notifier* n)
1041 USBHostDevice *s = container_of(n, USBHostDevice, exit);
1044 ioctl(s->fd, USBDEVFS_RESET);
1048 static int usb_host_initfn(USBDevice *dev)
1050 USBHostDevice *s = DO_UPCAST(USBHostDevice, dev, dev);
1052 dev->auto_attach = 0;
1054 QTAILQ_INSERT_TAIL(&hostdevs, s, next);
1055 s->exit.notify = usb_host_exit_notifier;
1056 qemu_add_exit_notifier(&s->exit);
1057 usb_host_auto_check(NULL);
1061 static struct USBDeviceInfo usb_host_dev_info = {
1062 .product_desc = "USB Host Device",
1063 .qdev.name = "usb-host",
1064 .qdev.size = sizeof(USBHostDevice),
1065 .init = usb_host_initfn,
1066 .handle_packet = usb_host_handle_packet,
1067 .handle_reset = usb_host_handle_reset,
1068 .handle_destroy = usb_host_handle_destroy,
1069 .usbdevice_name = "host",
1070 .usbdevice_init = usb_host_device_open,
1071 .qdev.props = (Property[]) {
1072 DEFINE_PROP_UINT32("hostbus", USBHostDevice, match.bus_num, 0),
1073 DEFINE_PROP_UINT32("hostaddr", USBHostDevice, match.addr, 0),
1074 DEFINE_PROP_HEX32("vendorid", USBHostDevice, match.vendor_id, 0),
1075 DEFINE_PROP_HEX32("productid", USBHostDevice, match.product_id, 0),
1076 DEFINE_PROP_END_OF_LIST(),
1080 static void usb_host_register_devices(void)
1082 usb_qdev_register(&usb_host_dev_info);
1084 device_init(usb_host_register_devices)
1086 USBDevice *usb_host_device_open(const char *devname)
1088 struct USBAutoFilter filter;
1092 dev = usb_create(NULL /* FIXME */, "usb-host");
1094 if (strstr(devname, "auto:")) {
1095 if (parse_filter(devname, &filter) < 0) {
1099 if ((p = strchr(devname, '.'))) {
1100 filter.bus_num = strtoul(devname, NULL, 0);
1101 filter.addr = strtoul(p + 1, NULL, 0);
1102 filter.vendor_id = 0;
1103 filter.product_id = 0;
1104 } else if ((p = strchr(devname, ':'))) {
1107 filter.vendor_id = strtoul(devname, NULL, 16);
1108 filter.product_id = strtoul(p + 1, NULL, 16);
1114 qdev_prop_set_uint32(&dev->qdev, "hostbus", filter.bus_num);
1115 qdev_prop_set_uint32(&dev->qdev, "hostaddr", filter.addr);
1116 qdev_prop_set_uint32(&dev->qdev, "vendorid", filter.vendor_id);
1117 qdev_prop_set_uint32(&dev->qdev, "productid", filter.product_id);
1118 qdev_init_nofail(&dev->qdev);
1122 qdev_free(&dev->qdev);
1126 int usb_host_device_close(const char *devname)
1129 char product_name[PRODUCT_NAME_SZ];
1133 if (strstr(devname, "auto:")) {
1134 return usb_host_auto_del(devname);
1136 if (usb_host_find_device(&bus_num, &addr, product_name,
1137 sizeof(product_name), devname) < 0) {
1140 s = hostdev_find(bus_num, addr);
1142 usb_device_delete_addr(s->bus_num, s->dev.addr);
1150 static int get_tag_value(char *buf, int buf_size,
1151 const char *str, const char *tag,
1152 const char *stopchars)
1156 p = strstr(str, tag);
1161 while (qemu_isspace(*p)) {
1165 while (*p != '\0' && !strchr(stopchars, *p)) {
1166 if ((q - buf) < (buf_size - 1)) {
1176 * Use /proc/bus/usb/devices or /dev/bus/usb/devices file to determine
1177 * host's USB devices. This is legacy support since many distributions
1178 * are moving to /sys/bus/usb
1180 static int usb_host_scan_dev(void *opaque, USBScanFunc *func)
1185 int bus_num, addr, speed, device_count, class_id, product_id, vendor_id;
1186 char product_name[512];
1189 if (!usb_host_device_path) {
1190 perror("husb: USB Host Device Path not set");
1193 snprintf(line, sizeof(line), "%s/devices", usb_host_device_path);
1194 f = fopen(line, "r");
1196 perror("husb: cannot open devices file");
1201 bus_num = addr = speed = class_id = product_id = vendor_id = 0;
1203 if (fgets(line, sizeof(line), f) == NULL) {
1206 if (strlen(line) > 0) {
1207 line[strlen(line) - 1] = '\0';
1209 if (line[0] == 'T' && line[1] == ':') {
1210 if (device_count && (vendor_id || product_id)) {
1211 /* New device. Add the previously discovered device. */
1212 ret = func(opaque, bus_num, addr, 0, class_id, vendor_id,
1213 product_id, product_name, speed);
1218 if (get_tag_value(buf, sizeof(buf), line, "Bus=", " ") < 0) {
1221 bus_num = atoi(buf);
1222 if (get_tag_value(buf, sizeof(buf), line, "Dev#=", " ") < 0) {
1226 if (get_tag_value(buf, sizeof(buf), line, "Spd=", " ") < 0) {
1229 if (!strcmp(buf, "480")) {
1230 speed = USB_SPEED_HIGH;
1231 } else if (!strcmp(buf, "1.5")) {
1232 speed = USB_SPEED_LOW;
1234 speed = USB_SPEED_FULL;
1236 product_name[0] = '\0';
1241 } else if (line[0] == 'P' && line[1] == ':') {
1242 if (get_tag_value(buf, sizeof(buf), line, "Vendor=", " ") < 0) {
1245 vendor_id = strtoul(buf, NULL, 16);
1246 if (get_tag_value(buf, sizeof(buf), line, "ProdID=", " ") < 0) {
1249 product_id = strtoul(buf, NULL, 16);
1250 } else if (line[0] == 'S' && line[1] == ':') {
1251 if (get_tag_value(buf, sizeof(buf), line, "Product=", "") < 0) {
1254 pstrcpy(product_name, sizeof(product_name), buf);
1255 } else if (line[0] == 'D' && line[1] == ':') {
1256 if (get_tag_value(buf, sizeof(buf), line, "Cls=", " (") < 0) {
1259 class_id = strtoul(buf, NULL, 16);
1263 if (device_count && (vendor_id || product_id)) {
1264 /* Add the last device. */
1265 ret = func(opaque, bus_num, addr, 0, class_id, vendor_id,
1266 product_id, product_name, speed);
1276 * Read sys file-system device file
1278 * @line address of buffer to put file contents in
1279 * @line_size size of line
1280 * @device_file path to device file (printf format string)
1281 * @device_name device being opened (inserted into device_file)
1283 * @return 0 failed, 1 succeeded ('line' contains data)
1285 static int usb_host_read_file(char *line, size_t line_size,
1286 const char *device_file, const char *device_name)
1290 char filename[PATH_MAX];
1292 snprintf(filename, PATH_MAX, USBSYSBUS_PATH "/devices/%s/%s", device_name,
1294 f = fopen(filename, "r");
1296 ret = fgets(line, line_size, f) != NULL;
1304 * Use /sys/bus/usb/devices/ directory to determine host's USB
1307 * This code is based on Robert Schiele's original patches posted to
1308 * the Novell bug-tracker https://bugzilla.novell.com/show_bug.cgi?id=241950
1310 static int usb_host_scan_sys(void *opaque, USBScanFunc *func)
1314 int bus_num, addr, devpath, speed, class_id, product_id, vendor_id;
1316 char product_name[512];
1319 dir = opendir(USBSYSBUS_PATH "/devices");
1321 perror("husb: cannot open devices directory");
1325 while ((de = readdir(dir))) {
1326 if (de->d_name[0] != '.' && !strchr(de->d_name, ':')) {
1327 char *tmpstr = de->d_name;
1328 if (!strncmp(de->d_name, "usb", 3)) {
1331 if (sscanf(tmpstr, "%d-%d", &bus_num, &devpath) < 1) {
1335 if (!usb_host_read_file(line, sizeof(line), "devnum", de->d_name)) {
1338 if (sscanf(line, "%d", &addr) != 1) {
1341 if (!usb_host_read_file(line, sizeof(line), "bDeviceClass",
1345 if (sscanf(line, "%x", &class_id) != 1) {
1349 if (!usb_host_read_file(line, sizeof(line), "idVendor",
1353 if (sscanf(line, "%x", &vendor_id) != 1) {
1356 if (!usb_host_read_file(line, sizeof(line), "idProduct",
1360 if (sscanf(line, "%x", &product_id) != 1) {
1363 if (!usb_host_read_file(line, sizeof(line), "product",
1367 if (strlen(line) > 0) {
1368 line[strlen(line) - 1] = '\0';
1370 pstrcpy(product_name, sizeof(product_name), line);
1373 if (!usb_host_read_file(line, sizeof(line), "speed", de->d_name)) {
1376 if (!strcmp(line, "480\n")) {
1377 speed = USB_SPEED_HIGH;
1378 } else if (!strcmp(line, "1.5\n")) {
1379 speed = USB_SPEED_LOW;
1381 speed = USB_SPEED_FULL;
1384 ret = func(opaque, bus_num, addr, devpath, class_id, vendor_id,
1385 product_id, product_name, speed);
1399 * Determine how to access the host's USB devices and call the
1400 * specific support function.
1402 static int usb_host_scan(void *opaque, USBScanFunc *func)
1404 Monitor *mon = cur_mon;
1408 const char *fs_type[] = {"unknown", "proc", "dev", "sys"};
1409 char devpath[PATH_MAX];
1411 /* only check the host once */
1413 dir = opendir(USBSYSBUS_PATH "/devices");
1415 /* devices found in /dev/bus/usb/ (yes - not a mistake!) */
1416 strcpy(devpath, USBDEVBUS_PATH);
1417 usb_fs_type = USB_FS_SYS;
1419 DPRINTF(USBDBG_DEVOPENED, USBSYSBUS_PATH);
1422 f = fopen(USBPROCBUS_PATH "/devices", "r");
1424 /* devices found in /proc/bus/usb/ */
1425 strcpy(devpath, USBPROCBUS_PATH);
1426 usb_fs_type = USB_FS_PROC;
1428 DPRINTF(USBDBG_DEVOPENED, USBPROCBUS_PATH);
1431 /* try additional methods if an access method hasn't been found yet */
1432 f = fopen(USBDEVBUS_PATH "/devices", "r");
1434 /* devices found in /dev/bus/usb/ */
1435 strcpy(devpath, USBDEVBUS_PATH);
1436 usb_fs_type = USB_FS_DEV;
1438 DPRINTF(USBDBG_DEVOPENED, USBDEVBUS_PATH);
1444 monitor_printf(mon, "husb: unable to access USB devices\n");
1449 /* the module setting (used later for opening devices) */
1450 usb_host_device_path = qemu_mallocz(strlen(devpath)+1);
1451 strcpy(usb_host_device_path, devpath);
1453 monitor_printf(mon, "husb: using %s file-system with %s\n",
1454 fs_type[usb_fs_type], usb_host_device_path);
1458 switch (usb_fs_type) {
1461 ret = usb_host_scan_dev(opaque, func);
1464 ret = usb_host_scan_sys(opaque, func);
1473 static QEMUTimer *usb_auto_timer;
1475 static int usb_host_auto_scan(void *opaque, int bus_num, int addr, int devpath,
1476 int class_id, int vendor_id, int product_id,
1477 const char *product_name, int speed)
1479 struct USBAutoFilter *f;
1480 struct USBHostDevice *s;
1486 QTAILQ_FOREACH(s, &hostdevs, next) {
1489 if (f->bus_num > 0 && f->bus_num != bus_num) {
1492 if (f->addr > 0 && f->addr != addr) {
1496 if (f->vendor_id > 0 && f->vendor_id != vendor_id) {
1500 if (f->product_id > 0 && f->product_id != product_id) {
1503 /* We got a match */
1505 /* Already attached ? */
1509 DPRINTF("husb: auto open: bus_num %d addr %d\n", bus_num, addr);
1511 usb_host_open(s, bus_num, addr, devpath, product_name);
1517 static void usb_host_auto_check(void *unused)
1519 struct USBHostDevice *s;
1520 int unconnected = 0;
1522 usb_host_scan(NULL, usb_host_auto_scan);
1524 QTAILQ_FOREACH(s, &hostdevs, next) {
1530 if (unconnected == 0) {
1531 /* nothing to watch */
1532 if (usb_auto_timer) {
1533 qemu_del_timer(usb_auto_timer);
1538 if (!usb_auto_timer) {
1539 usb_auto_timer = qemu_new_timer_ms(rt_clock, usb_host_auto_check, NULL);
1540 if (!usb_auto_timer) {
1544 qemu_mod_timer(usb_auto_timer, qemu_get_clock_ms(rt_clock) + 2000);
1548 * Autoconnect filter
1550 * auto:bus:dev[:vid:pid]
1551 * auto:bus.dev[:vid:pid]
1553 * bus - bus number (dec, * means any)
1554 * dev - device number (dec, * means any)
1555 * vid - vendor id (hex, * means any)
1556 * pid - product id (hex, * means any)
1558 * See 'lsusb' output.
1560 static int parse_filter(const char *spec, struct USBAutoFilter *f)
1562 enum { BUS, DEV, VID, PID, DONE };
1563 const char *p = spec;
1571 for (i = BUS; i < DONE; i++) {
1572 p = strpbrk(p, ":.");
1582 case BUS: f->bus_num = strtol(p, NULL, 10); break;
1583 case DEV: f->addr = strtol(p, NULL, 10); break;
1584 case VID: f->vendor_id = strtol(p, NULL, 16); break;
1585 case PID: f->product_id = strtol(p, NULL, 16); break;
1590 fprintf(stderr, "husb: invalid auto filter spec %s\n", spec);
1597 /**********************/
1598 /* USB host device info */
1600 struct usb_class_info {
1602 const char *class_name;
1605 static const struct usb_class_info usb_class_info[] = {
1606 { USB_CLASS_AUDIO, "Audio"},
1607 { USB_CLASS_COMM, "Communication"},
1608 { USB_CLASS_HID, "HID"},
1609 { USB_CLASS_HUB, "Hub" },
1610 { USB_CLASS_PHYSICAL, "Physical" },
1611 { USB_CLASS_PRINTER, "Printer" },
1612 { USB_CLASS_MASS_STORAGE, "Storage" },
1613 { USB_CLASS_CDC_DATA, "Data" },
1614 { USB_CLASS_APP_SPEC, "Application Specific" },
1615 { USB_CLASS_VENDOR_SPEC, "Vendor Specific" },
1616 { USB_CLASS_STILL_IMAGE, "Still Image" },
1617 { USB_CLASS_CSCID, "Smart Card" },
1618 { USB_CLASS_CONTENT_SEC, "Content Security" },
1622 static const char *usb_class_str(uint8_t class)
1624 const struct usb_class_info *p;
1625 for(p = usb_class_info; p->class != -1; p++) {
1626 if (p->class == class) {
1630 return p->class_name;
1633 static void usb_info_device(Monitor *mon, int bus_num, int addr, int class_id,
1634 int vendor_id, int product_id,
1635 const char *product_name,
1638 const char *class_str, *speed_str;
1644 case USB_SPEED_FULL:
1647 case USB_SPEED_HIGH:
1655 monitor_printf(mon, " Device %d.%d, speed %s Mb/s\n",
1656 bus_num, addr, speed_str);
1657 class_str = usb_class_str(class_id);
1659 monitor_printf(mon, " %s:", class_str);
1661 monitor_printf(mon, " Class %02x:", class_id);
1663 monitor_printf(mon, " USB device %04x:%04x", vendor_id, product_id);
1664 if (product_name[0] != '\0') {
1665 monitor_printf(mon, ", %s", product_name);
1667 monitor_printf(mon, "\n");
1670 static int usb_host_info_device(void *opaque, int bus_num, int addr,
1671 int devpath, int class_id,
1672 int vendor_id, int product_id,
1673 const char *product_name,
1676 Monitor *mon = opaque;
1678 usb_info_device(mon, bus_num, addr, class_id, vendor_id, product_id,
1679 product_name, speed);
1683 static void dec2str(int val, char *str, size_t size)
1686 snprintf(str, size, "*");
1688 snprintf(str, size, "%d", val);
1692 static void hex2str(int val, char *str, size_t size)
1695 snprintf(str, size, "*");
1697 snprintf(str, size, "%04x", val);
1701 void usb_host_info(Monitor *mon)
1703 struct USBAutoFilter *f;
1704 struct USBHostDevice *s;
1706 usb_host_scan(mon, usb_host_info_device);
1708 if (QTAILQ_EMPTY(&hostdevs)) {
1712 monitor_printf(mon, " Auto filters:\n");
1713 QTAILQ_FOREACH(s, &hostdevs, next) {
1714 char bus[10], addr[10], vid[10], pid[10];
1716 dec2str(f->bus_num, bus, sizeof(bus));
1717 dec2str(f->addr, addr, sizeof(addr));
1718 hex2str(f->vendor_id, vid, sizeof(vid));
1719 hex2str(f->product_id, pid, sizeof(pid));
1720 monitor_printf(mon, " Device %s.%s ID %s:%s\n",
1721 bus, addr, vid, pid);