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"
38 #include <sys/ioctl.h>
41 #include <linux/usbdevice_fs.h>
42 #include <linux/version.h>
45 /* We redefine it to avoid version problems */
46 struct usb_ctrltransfer {
56 struct usb_ctrlrequest {
64 typedef int USBScanFunc(void *opaque, int bus_num, int addr, int class_id,
65 int vendor_id, int product_id,
66 const char *product_name, int speed);
67 static int usb_host_find_device(int *pbus_num, int *paddr,
68 char *product_name, int product_name_size,
73 #define dprintf printf
78 #define USBDBG_DEVOPENED "husb: opened %s/devices\n"
80 #define USBPROCBUS_PATH "/proc/bus/usb"
81 #define PRODUCT_NAME_SZ 32
82 #define MAX_ENDPOINTS 16
83 #define USBDEVBUS_PATH "/dev/bus/usb"
84 #define USBSYSBUS_PATH "/sys/bus/usb"
86 static char *usb_host_device_path;
93 static int usb_fs_type;
95 /* endpoint association data */
109 * Control transfer state.
110 * Note that 'buffer' _must_ follow 'req' field because
111 * we need contigious buffer when we submit control URB.
117 struct usb_ctrlrequest req;
118 uint8_t buffer[1024];
121 typedef struct USBHostDevice {
131 struct ctrl_struct ctrl;
132 struct endp_data endp_table[MAX_ENDPOINTS];
134 /* Host side address */
138 struct USBHostDevice *next;
141 static int is_isoc(USBHostDevice *s, int ep)
143 return s->endp_table[ep - 1].type == USBDEVFS_URB_TYPE_ISO;
146 static int is_halted(USBHostDevice *s, int ep)
148 return s->endp_table[ep - 1].halted;
151 static void clear_halt(USBHostDevice *s, int ep)
153 s->endp_table[ep - 1].halted = 0;
156 static void set_halt(USBHostDevice *s, int ep)
158 s->endp_table[ep - 1].halted = 1;
161 static USBHostDevice *hostdev_list;
163 static void hostdev_link(USBHostDevice *dev)
165 dev->next = hostdev_list;
169 static void hostdev_unlink(USBHostDevice *dev)
171 USBHostDevice *pdev = hostdev_list;
172 USBHostDevice **prev = &hostdev_list;
185 static USBHostDevice *hostdev_find(int bus_num, int addr)
187 USBHostDevice *s = hostdev_list;
189 if (s->bus_num == bus_num && s->addr == addr)
198 * We always allocate one isoc descriptor even for bulk transfers
199 * to simplify allocation and casts.
201 typedef struct AsyncURB
203 struct usbdevfs_urb urb;
204 struct usbdevfs_iso_packet_desc isocpd;
210 static AsyncURB *async_alloc(void)
212 return (AsyncURB *) qemu_mallocz(sizeof(AsyncURB));
215 static void async_free(AsyncURB *aurb)
220 static void async_complete_ctrl(USBHostDevice *s, USBPacket *p)
222 switch(s->ctrl.state) {
223 case CTRL_STATE_SETUP:
224 if (p->len < s->ctrl.len)
225 s->ctrl.len = p->len;
226 s->ctrl.state = CTRL_STATE_DATA;
231 s->ctrl.state = CTRL_STATE_IDLE;
240 static void async_complete(void *opaque)
242 USBHostDevice *s = opaque;
248 int r = ioctl(s->fd, USBDEVFS_REAPURBNDELAY, &aurb);
253 if (errno == ENODEV && !s->closing) {
254 printf("husb: device %d.%d disconnected\n", s->bus_num, s->addr);
255 usb_device_del_addr(0, s->dev.addr);
259 dprintf("husb: async. reap urb failed errno %d\n", errno);
265 dprintf("husb: async completed. aurb %p status %d alen %d\n",
266 aurb, aurb->urb.status, aurb->urb.actual_length);
269 switch (aurb->urb.status) {
271 p->len = aurb->urb.actual_length;
272 if (aurb->urb.type == USBDEVFS_URB_TYPE_CONTROL)
273 async_complete_ctrl(s, p);
277 set_halt(s, p->devep);
280 p->len = USB_RET_NAK;
284 usb_packet_complete(p);
291 static void async_cancel(USBPacket *unused, void *opaque)
293 AsyncURB *aurb = opaque;
294 USBHostDevice *s = aurb->hdev;
296 dprintf("husb: async cancel. aurb %p\n", aurb);
298 /* Mark it as dead (see async_complete above) */
301 int r = ioctl(s->fd, USBDEVFS_DISCARDURB, aurb);
303 dprintf("husb: async. discard urb failed errno %d\n", errno);
307 static int usb_host_claim_interfaces(USBHostDevice *dev, int configuration)
309 int dev_descr_len, config_descr_len;
310 int interface, nb_interfaces, nb_configurations;
313 if (configuration == 0) /* address state - ignore */
316 dprintf("husb: claiming interfaces. config %d\n", configuration);
319 dev_descr_len = dev->descr[0];
320 if (dev_descr_len > dev->descr_len)
322 nb_configurations = dev->descr[17];
325 while (i < dev->descr_len) {
326 dprintf("husb: i is %d, descr_len is %d, dl %d, dt %d\n", i, dev->descr_len,
327 dev->descr[i], dev->descr[i+1]);
329 if (dev->descr[i+1] != USB_DT_CONFIG) {
333 config_descr_len = dev->descr[i];
335 printf("husb: config #%d need %d\n", dev->descr[i + 5], configuration);
337 if (configuration < 0 || configuration == dev->descr[i + 5]) {
338 configuration = dev->descr[i + 5];
342 i += config_descr_len;
345 if (i >= dev->descr_len) {
346 fprintf(stderr, "husb: update iface failed. no matching configuration\n");
349 nb_interfaces = dev->descr[i + 4];
351 #ifdef USBDEVFS_DISCONNECT
352 /* earlier Linux 2.4 do not support that */
354 struct usbdevfs_ioctl ctrl;
355 for (interface = 0; interface < nb_interfaces; interface++) {
356 ctrl.ioctl_code = USBDEVFS_DISCONNECT;
357 ctrl.ifno = interface;
358 ret = ioctl(dev->fd, USBDEVFS_IOCTL, &ctrl);
359 if (ret < 0 && errno != ENODATA) {
360 perror("USBDEVFS_DISCONNECT");
367 /* XXX: only grab if all interfaces are free */
368 for (interface = 0; interface < nb_interfaces; interface++) {
369 ret = ioctl(dev->fd, USBDEVFS_CLAIMINTERFACE, &interface);
371 if (errno == EBUSY) {
372 printf("husb: update iface. device already grabbed\n");
374 perror("husb: failed to claim interface");
381 printf("husb: %d interfaces claimed for configuration %d\n",
382 nb_interfaces, configuration);
384 dev->ninterfaces = nb_interfaces;
385 dev->configuration = configuration;
389 static int usb_host_release_interfaces(USBHostDevice *s)
393 dprintf("husb: releasing interfaces\n");
395 for (i = 0; i < s->ninterfaces; i++) {
396 ret = ioctl(s->fd, USBDEVFS_RELEASEINTERFACE, &i);
398 perror("husb: failed to release interface");
406 static void usb_host_handle_reset(USBDevice *dev)
408 USBHostDevice *s = (USBHostDevice *) dev;
410 dprintf("husb: reset device %u.%u\n", s->bus_num, s->addr);
412 ioctl(s->fd, USBDEVFS_RESET);
414 usb_host_claim_interfaces(s, s->configuration);
417 static void usb_host_handle_destroy(USBDevice *dev)
419 USBHostDevice *s = (USBHostDevice *)dev;
423 qemu_set_fd_handler(s->fd, NULL, NULL, NULL);
435 static int usb_linux_update_endp_table(USBHostDevice *s);
437 static int usb_host_handle_data(USBHostDevice *s, USBPacket *p)
439 struct usbdevfs_urb *urb;
443 aurb = async_alloc();
449 if (p->pid == USB_TOKEN_IN)
450 urb->endpoint = p->devep | 0x80;
452 urb->endpoint = p->devep;
454 if (is_halted(s, p->devep)) {
455 ret = ioctl(s->fd, USBDEVFS_CLEAR_HALT, &urb->endpoint);
457 dprintf("husb: failed to clear halt. ep 0x%x errno %d\n",
458 urb->endpoint, errno);
461 clear_halt(s, p->devep);
464 urb->buffer = p->data;
465 urb->buffer_length = p->len;
467 if (is_isoc(s, p->devep)) {
468 /* Setup ISOC transfer */
469 urb->type = USBDEVFS_URB_TYPE_ISO;
470 urb->flags = USBDEVFS_URB_ISO_ASAP;
471 urb->number_of_packets = 1;
472 urb->iso_frame_desc[0].length = p->len;
474 /* Setup bulk transfer */
475 urb->type = USBDEVFS_URB_TYPE_BULK;
478 urb->usercontext = s;
480 ret = ioctl(s->fd, USBDEVFS_SUBMITURB, urb);
482 dprintf("husb: data submit. ep 0x%x len %u aurb %p\n", urb->endpoint, p->len, aurb);
485 dprintf("husb: submit failed. errno %d\n", errno);
493 return USB_RET_STALL;
497 usb_defer_packet(p, async_cancel, aurb);
498 return USB_RET_ASYNC;
501 static int ctrl_error(void)
503 if (errno == ETIMEDOUT)
506 return USB_RET_STALL;
509 static int usb_host_set_address(USBHostDevice *s, int addr)
511 dprintf("husb: ctrl set addr %u\n", addr);
516 static int usb_host_set_config(USBHostDevice *s, int config)
518 usb_host_release_interfaces(s);
520 int ret = ioctl(s->fd, USBDEVFS_SETCONFIGURATION, &config);
522 dprintf("husb: ctrl set config %d ret %d errno %d\n", config, ret, errno);
527 usb_host_claim_interfaces(s, config);
531 static int usb_host_set_interface(USBHostDevice *s, int iface, int alt)
533 struct usbdevfs_setinterface si;
536 si.interface = iface;
538 ret = ioctl(s->fd, USBDEVFS_SETINTERFACE, &si);
540 dprintf("husb: ctrl set iface %d altset %d ret %d errno %d\n",
541 iface, alt, ret, errno);
546 usb_linux_update_endp_table(s);
550 static int usb_host_handle_control(USBHostDevice *s, USBPacket *p)
552 struct usbdevfs_urb *urb;
554 int ret, value, index;
557 * Process certain standard device requests.
558 * These are infrequent and are processed synchronously.
560 value = le16_to_cpu(s->ctrl.req.wValue);
561 index = le16_to_cpu(s->ctrl.req.wIndex);
563 dprintf("husb: ctrl type 0x%x req 0x%x val 0x%x index %u len %u\n",
564 s->ctrl.req.bRequestType, s->ctrl.req.bRequest, value, index,
567 if (s->ctrl.req.bRequestType == 0) {
568 switch (s->ctrl.req.bRequest) {
569 case USB_REQ_SET_ADDRESS:
570 return usb_host_set_address(s, value);
572 case USB_REQ_SET_CONFIGURATION:
573 return usb_host_set_config(s, value & 0xff);
577 if (s->ctrl.req.bRequestType == 1 &&
578 s->ctrl.req.bRequest == USB_REQ_SET_INTERFACE)
579 return usb_host_set_interface(s, index, value);
581 /* The rest are asynchronous */
583 aurb = async_alloc();
588 * Setup ctrl transfer.
590 * s->ctrl is layed out such that data buffer immediately follows
591 * 'req' struct which is exactly what usbdevfs expects.
595 urb->type = USBDEVFS_URB_TYPE_CONTROL;
596 urb->endpoint = p->devep;
598 urb->buffer = &s->ctrl.req;
599 urb->buffer_length = 8 + s->ctrl.len;
601 urb->usercontext = s;
603 ret = ioctl(s->fd, USBDEVFS_SUBMITURB, urb);
605 dprintf("husb: submit ctrl. len %u aurb %p\n", urb->buffer_length, aurb);
608 dprintf("husb: submit failed. errno %d\n", errno);
616 return USB_RET_STALL;
620 usb_defer_packet(p, async_cancel, aurb);
621 return USB_RET_ASYNC;
624 static int do_token_setup(USBDevice *dev, USBPacket *p)
626 USBHostDevice *s = (USBHostDevice *) dev;
630 return USB_RET_STALL;
632 memcpy(&s->ctrl.req, p->data, 8);
633 s->ctrl.len = le16_to_cpu(s->ctrl.req.wLength);
635 s->ctrl.state = CTRL_STATE_SETUP;
637 if (s->ctrl.req.bRequestType & USB_DIR_IN) {
638 ret = usb_host_handle_control(s, p);
642 if (ret < s->ctrl.len)
644 s->ctrl.state = CTRL_STATE_DATA;
646 if (s->ctrl.len == 0)
647 s->ctrl.state = CTRL_STATE_ACK;
649 s->ctrl.state = CTRL_STATE_DATA;
655 static int do_token_in(USBDevice *dev, USBPacket *p)
657 USBHostDevice *s = (USBHostDevice *) dev;
661 return usb_host_handle_data(s, p);
663 switch(s->ctrl.state) {
665 if (!(s->ctrl.req.bRequestType & USB_DIR_IN)) {
666 ret = usb_host_handle_control(s, p);
667 if (ret == USB_RET_ASYNC)
668 return USB_RET_ASYNC;
670 s->ctrl.state = CTRL_STATE_IDLE;
671 return ret > 0 ? 0 : ret;
676 case CTRL_STATE_DATA:
677 if (s->ctrl.req.bRequestType & USB_DIR_IN) {
678 int len = s->ctrl.len - s->ctrl.offset;
681 memcpy(p->data, s->ctrl.buffer + s->ctrl.offset, len);
682 s->ctrl.offset += len;
683 if (s->ctrl.offset >= s->ctrl.len)
684 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);
703 switch(s->ctrl.state) {
705 if (s->ctrl.req.bRequestType & USB_DIR_IN) {
706 s->ctrl.state = CTRL_STATE_IDLE;
709 /* ignore additional output */
713 case CTRL_STATE_DATA:
714 if (!(s->ctrl.req.bRequestType & USB_DIR_IN)) {
715 int len = s->ctrl.len - s->ctrl.offset;
718 memcpy(s->ctrl.buffer + s->ctrl.offset, p->data, len);
719 s->ctrl.offset += len;
720 if (s->ctrl.offset >= s->ctrl.len)
721 s->ctrl.state = CTRL_STATE_ACK;
725 s->ctrl.state = CTRL_STATE_IDLE;
726 return USB_RET_STALL;
729 return USB_RET_STALL;
735 * Called by the HC (host controller).
737 * Returns length of the transaction or one of the USB_RET_XXX codes.
739 static int usb_host_handle_packet(USBDevice *s, USBPacket *p)
743 s->state = USB_STATE_ATTACHED;
747 s->state = USB_STATE_NOTATTACHED;
751 s->remote_wakeup = 0;
753 s->state = USB_STATE_DEFAULT;
758 /* Rest of the PIDs must match our address */
759 if (s->state < USB_STATE_DEFAULT || p->devaddr != s->addr)
760 return USB_RET_NODEV;
763 case USB_TOKEN_SETUP:
764 return do_token_setup(s, p);
767 return do_token_in(s, p);
770 return do_token_out(s, p);
773 return USB_RET_STALL;
777 /* returns 1 on problem encountered or 0 for success */
778 static int usb_linux_update_endp_table(USBHostDevice *s)
780 uint8_t *descriptors;
781 uint8_t devep, type, configuration, alt_interface;
782 struct usb_ctrltransfer ct;
783 int interface, ret, length, i;
785 ct.bRequestType = USB_DIR_IN;
786 ct.bRequest = USB_REQ_GET_CONFIGURATION;
790 ct.data = &configuration;
793 ret = ioctl(s->fd, USBDEVFS_CONTROL, &ct);
795 perror("usb_linux_update_endp_table");
799 /* in address state */
800 if (configuration == 0)
803 /* get the desired configuration, interface, and endpoint descriptors
804 * from device description */
805 descriptors = &s->descr[18];
806 length = s->descr_len - 18;
809 if (descriptors[i + 1] != USB_DT_CONFIG ||
810 descriptors[i + 5] != configuration) {
811 dprintf("invalid descriptor data - configuration\n");
817 if (descriptors[i + 1] != USB_DT_INTERFACE ||
818 (descriptors[i + 1] == USB_DT_INTERFACE &&
819 descriptors[i + 4] == 0)) {
824 interface = descriptors[i + 2];
826 ct.bRequestType = USB_DIR_IN | USB_RECIP_INTERFACE;
827 ct.bRequest = USB_REQ_GET_INTERFACE;
829 ct.wIndex = interface;
831 ct.data = &alt_interface;
834 ret = ioctl(s->fd, USBDEVFS_CONTROL, &ct);
836 perror("usb_linux_update_endp_table");
840 /* the current interface descriptor is the active interface
841 * and has endpoints */
842 if (descriptors[i + 3] != alt_interface) {
847 /* advance to the endpoints */
848 while (i < length && descriptors[i +1] != USB_DT_ENDPOINT)
855 if (descriptors[i + 1] != USB_DT_ENDPOINT)
858 devep = descriptors[i + 2];
859 switch (descriptors[i + 3] & 0x3) {
861 type = USBDEVFS_URB_TYPE_CONTROL;
864 type = USBDEVFS_URB_TYPE_ISO;
867 type = USBDEVFS_URB_TYPE_BULK;
870 type = USBDEVFS_URB_TYPE_INTERRUPT;
873 dprintf("usb_host: malformed endpoint type\n");
874 type = USBDEVFS_URB_TYPE_BULK;
876 s->endp_table[(devep & 0xf) - 1].type = type;
877 s->endp_table[(devep & 0xf) - 1].halted = 0;
885 static USBDevice *usb_host_device_open_addr(int bus_num, int addr, const char *prod_name)
888 USBHostDevice *dev = NULL;
889 struct usbdevfs_connectinfo ci;
892 dev = qemu_mallocz(sizeof(USBHostDevice));
894 dev->bus_num = bus_num;
897 printf("husb: open device %d.%d\n", bus_num, addr);
899 if (!usb_host_device_path) {
900 perror("husb: USB Host Device Path not set");
903 snprintf(buf, sizeof(buf), "%s/%03d/%03d", usb_host_device_path,
905 fd = open(buf, O_RDWR | O_NONBLOCK);
910 dprintf("husb: opened %s\n", buf);
912 /* read the device description */
913 dev->descr_len = read(fd, dev->descr, sizeof(dev->descr));
914 if (dev->descr_len <= 0) {
915 perror("husb: reading device data failed");
922 printf("=== begin dumping device descriptor data ===\n");
923 for (x = 0; x < dev->descr_len; x++)
924 printf("%02x ", dev->descr[x]);
925 printf("\n=== end dumping device descriptor data ===\n");
932 * Initial configuration is -1 which makes us claim first
933 * available config. We used to start with 1, which does not
934 * always work. I've seen devices where first config starts
937 if (!usb_host_claim_interfaces(dev, -1))
940 ret = ioctl(fd, USBDEVFS_CONNECTINFO, &ci);
942 perror("usb_host_device_open: USBDEVFS_CONNECTINFO");
946 printf("husb: grabbed usb device %d.%d\n", bus_num, addr);
948 ret = usb_linux_update_endp_table(dev);
953 dev->dev.speed = USB_SPEED_LOW;
955 dev->dev.speed = USB_SPEED_HIGH;
957 dev->dev.handle_packet = usb_host_handle_packet;
958 dev->dev.handle_reset = usb_host_handle_reset;
959 dev->dev.handle_destroy = usb_host_handle_destroy;
961 if (!prod_name || prod_name[0] == '\0')
962 snprintf(dev->dev.devname, sizeof(dev->dev.devname),
963 "host:%d.%d", bus_num, addr);
965 pstrcpy(dev->dev.devname, sizeof(dev->dev.devname),
968 /* USB devio uses 'write' flag to check for async completions */
969 qemu_set_fd_handler(dev->fd, NULL, async_complete, dev);
973 return (USBDevice *) dev;
983 static int usb_host_auto_add(const char *spec);
984 static int usb_host_auto_del(const char *spec);
986 USBDevice *usb_host_device_open(const char *devname)
988 Monitor *mon = cur_mon;
990 char product_name[PRODUCT_NAME_SZ];
992 if (strstr(devname, "auto:")) {
993 usb_host_auto_add(devname);
997 if (usb_host_find_device(&bus_num, &addr, product_name, sizeof(product_name),
1001 if (hostdev_find(bus_num, addr)) {
1002 monitor_printf(mon, "husb: host usb device %d.%d is already open\n",
1007 return usb_host_device_open_addr(bus_num, addr, product_name);
1010 int usb_host_device_close(const char *devname)
1012 char product_name[PRODUCT_NAME_SZ];
1016 if (strstr(devname, "auto:"))
1017 return usb_host_auto_del(devname);
1019 if (usb_host_find_device(&bus_num, &addr, product_name, sizeof(product_name),
1023 s = hostdev_find(bus_num, addr);
1025 usb_device_del_addr(0, s->dev.addr);
1032 static int get_tag_value(char *buf, int buf_size,
1033 const char *str, const char *tag,
1034 const char *stopchars)
1038 p = strstr(str, tag);
1042 while (qemu_isspace(*p))
1045 while (*p != '\0' && !strchr(stopchars, *p)) {
1046 if ((q - buf) < (buf_size - 1))
1055 * Use /proc/bus/usb/devices or /dev/bus/usb/devices file to determine
1056 * host's USB devices. This is legacy support since many distributions
1057 * are moving to /sys/bus/usb
1059 static int usb_host_scan_dev(void *opaque, USBScanFunc *func)
1064 int bus_num, addr, speed, device_count, class_id, product_id, vendor_id;
1065 char product_name[512];
1068 if (!usb_host_device_path) {
1069 perror("husb: USB Host Device Path not set");
1072 snprintf(line, sizeof(line), "%s/devices", usb_host_device_path);
1073 f = fopen(line, "r");
1075 perror("husb: cannot open devices file");
1080 bus_num = addr = speed = class_id = product_id = vendor_id = 0;
1082 if (fgets(line, sizeof(line), f) == NULL)
1084 if (strlen(line) > 0)
1085 line[strlen(line) - 1] = '\0';
1086 if (line[0] == 'T' && line[1] == ':') {
1087 if (device_count && (vendor_id || product_id)) {
1088 /* New device. Add the previously discovered device. */
1089 ret = func(opaque, bus_num, addr, class_id, vendor_id,
1090 product_id, product_name, speed);
1094 if (get_tag_value(buf, sizeof(buf), line, "Bus=", " ") < 0)
1096 bus_num = atoi(buf);
1097 if (get_tag_value(buf, sizeof(buf), line, "Dev#=", " ") < 0)
1100 if (get_tag_value(buf, sizeof(buf), line, "Spd=", " ") < 0)
1102 if (!strcmp(buf, "480"))
1103 speed = USB_SPEED_HIGH;
1104 else if (!strcmp(buf, "1.5"))
1105 speed = USB_SPEED_LOW;
1107 speed = USB_SPEED_FULL;
1108 product_name[0] = '\0';
1113 } else if (line[0] == 'P' && line[1] == ':') {
1114 if (get_tag_value(buf, sizeof(buf), line, "Vendor=", " ") < 0)
1116 vendor_id = strtoul(buf, NULL, 16);
1117 if (get_tag_value(buf, sizeof(buf), line, "ProdID=", " ") < 0)
1119 product_id = strtoul(buf, NULL, 16);
1120 } else if (line[0] == 'S' && line[1] == ':') {
1121 if (get_tag_value(buf, sizeof(buf), line, "Product=", "") < 0)
1123 pstrcpy(product_name, sizeof(product_name), buf);
1124 } else if (line[0] == 'D' && line[1] == ':') {
1125 if (get_tag_value(buf, sizeof(buf), line, "Cls=", " (") < 0)
1127 class_id = strtoul(buf, NULL, 16);
1131 if (device_count && (vendor_id || product_id)) {
1132 /* Add the last device. */
1133 ret = func(opaque, bus_num, addr, class_id, vendor_id,
1134 product_id, product_name, speed);
1143 * Read sys file-system device file
1145 * @line address of buffer to put file contents in
1146 * @line_size size of line
1147 * @device_file path to device file (printf format string)
1148 * @device_name device being opened (inserted into device_file)
1150 * @return 0 failed, 1 succeeded ('line' contains data)
1152 static int usb_host_read_file(char *line, size_t line_size, const char *device_file, const char *device_name)
1154 Monitor *mon = cur_mon;
1157 char filename[PATH_MAX];
1159 snprintf(filename, PATH_MAX, USBSYSBUS_PATH "/devices/%s/%s", device_name,
1161 f = fopen(filename, "r");
1163 fgets(line, line_size, f);
1167 monitor_printf(mon, "husb: could not open %s\n", filename);
1174 * Use /sys/bus/usb/devices/ directory to determine host's USB
1177 * This code is based on Robert Schiele's original patches posted to
1178 * the Novell bug-tracker https://bugzilla.novell.com/show_bug.cgi?id=241950
1180 static int usb_host_scan_sys(void *opaque, USBScanFunc *func)
1184 int bus_num, addr, speed, class_id, product_id, vendor_id;
1186 char product_name[512];
1189 dir = opendir(USBSYSBUS_PATH "/devices");
1191 perror("husb: cannot open devices directory");
1195 while ((de = readdir(dir))) {
1196 if (de->d_name[0] != '.' && !strchr(de->d_name, ':')) {
1197 char *tmpstr = de->d_name;
1198 if (!strncmp(de->d_name, "usb", 3))
1200 bus_num = atoi(tmpstr);
1202 if (!usb_host_read_file(line, sizeof(line), "devnum", de->d_name))
1204 if (sscanf(line, "%d", &addr) != 1)
1207 if (!usb_host_read_file(line, sizeof(line), "bDeviceClass",
1210 if (sscanf(line, "%x", &class_id) != 1)
1213 if (!usb_host_read_file(line, sizeof(line), "idVendor", de->d_name))
1215 if (sscanf(line, "%x", &vendor_id) != 1)
1218 if (!usb_host_read_file(line, sizeof(line), "idProduct",
1221 if (sscanf(line, "%x", &product_id) != 1)
1224 if (!usb_host_read_file(line, sizeof(line), "product",
1228 if (strlen(line) > 0)
1229 line[strlen(line) - 1] = '\0';
1230 pstrcpy(product_name, sizeof(product_name), line);
1233 if (!usb_host_read_file(line, sizeof(line), "speed", de->d_name))
1235 if (!strcmp(line, "480\n"))
1236 speed = USB_SPEED_HIGH;
1237 else if (!strcmp(line, "1.5\n"))
1238 speed = USB_SPEED_LOW;
1240 speed = USB_SPEED_FULL;
1242 ret = func(opaque, bus_num, addr, class_id, vendor_id,
1243 product_id, product_name, speed);
1255 * Determine how to access the host's USB devices and call the
1256 * specific support function.
1258 static int usb_host_scan(void *opaque, USBScanFunc *func)
1260 Monitor *mon = cur_mon;
1264 const char *fs_type[] = {"unknown", "proc", "dev", "sys"};
1265 char devpath[PATH_MAX];
1267 /* only check the host once */
1269 f = fopen(USBPROCBUS_PATH "/devices", "r");
1271 /* devices found in /proc/bus/usb/ */
1272 strcpy(devpath, USBPROCBUS_PATH);
1273 usb_fs_type = USB_FS_PROC;
1275 dprintf(USBDBG_DEVOPENED, USBPROCBUS_PATH);
1278 /* try additional methods if an access method hasn't been found yet */
1279 f = fopen(USBDEVBUS_PATH "/devices", "r");
1281 /* devices found in /dev/bus/usb/ */
1282 strcpy(devpath, USBDEVBUS_PATH);
1283 usb_fs_type = USB_FS_DEV;
1285 dprintf(USBDBG_DEVOPENED, USBDEVBUS_PATH);
1288 dir = opendir(USBSYSBUS_PATH "/devices");
1290 /* devices found in /dev/bus/usb/ (yes - not a mistake!) */
1291 strcpy(devpath, USBDEVBUS_PATH);
1292 usb_fs_type = USB_FS_SYS;
1294 dprintf(USBDBG_DEVOPENED, USBSYSBUS_PATH);
1299 monitor_printf(mon, "husb: unable to access USB devices\n");
1303 /* the module setting (used later for opening devices) */
1304 usb_host_device_path = qemu_mallocz(strlen(devpath)+1);
1305 strcpy(usb_host_device_path, devpath);
1306 monitor_printf(mon, "husb: using %s file-system with %s\n",
1307 fs_type[usb_fs_type], usb_host_device_path);
1310 switch (usb_fs_type) {
1313 ret = usb_host_scan_dev(opaque, func);
1316 ret = usb_host_scan_sys(opaque, func);
1325 struct USBAutoFilter {
1326 struct USBAutoFilter *next;
1333 static QEMUTimer *usb_auto_timer;
1334 static struct USBAutoFilter *usb_auto_filter;
1336 static int usb_host_auto_scan(void *opaque, int bus_num, int addr,
1337 int class_id, int vendor_id, int product_id,
1338 const char *product_name, int speed)
1340 struct USBAutoFilter *f;
1341 struct USBDevice *dev;
1347 for (f = usb_auto_filter; f; f = f->next) {
1348 if (f->bus_num >= 0 && f->bus_num != bus_num)
1351 if (f->addr >= 0 && f->addr != addr)
1354 if (f->vendor_id >= 0 && f->vendor_id != vendor_id)
1357 if (f->product_id >= 0 && f->product_id != product_id)
1360 /* We got a match */
1362 /* Allredy attached ? */
1363 if (hostdev_find(bus_num, addr))
1366 dprintf("husb: auto open: bus_num %d addr %d\n", bus_num, addr);
1368 dev = usb_host_device_open_addr(bus_num, addr, product_name);
1370 usb_device_add_dev(dev);
1376 static void usb_host_auto_timer(void *unused)
1378 usb_host_scan(NULL, usb_host_auto_scan);
1379 qemu_mod_timer(usb_auto_timer, qemu_get_clock(rt_clock) + 2000);
1383 * Autoconnect filter
1385 * auto:bus:dev[:vid:pid]
1386 * auto:bus.dev[:vid:pid]
1388 * bus - bus number (dec, * means any)
1389 * dev - device number (dec, * means any)
1390 * vid - vendor id (hex, * means any)
1391 * pid - product id (hex, * means any)
1393 * See 'lsusb' output.
1395 static int parse_filter(const char *spec, struct USBAutoFilter *f)
1397 enum { BUS, DEV, VID, PID, DONE };
1398 const char *p = spec;
1406 for (i = BUS; i < DONE; i++) {
1407 p = strpbrk(p, ":.");
1415 case BUS: f->bus_num = strtol(p, NULL, 10); break;
1416 case DEV: f->addr = strtol(p, NULL, 10); break;
1417 case VID: f->vendor_id = strtol(p, NULL, 16); break;
1418 case PID: f->product_id = strtol(p, NULL, 16); break;
1423 fprintf(stderr, "husb: invalid auto filter spec %s\n", spec);
1430 static int match_filter(const struct USBAutoFilter *f1,
1431 const struct USBAutoFilter *f2)
1433 return f1->bus_num == f2->bus_num &&
1434 f1->addr == f2->addr &&
1435 f1->vendor_id == f2->vendor_id &&
1436 f1->product_id == f2->product_id;
1439 static int usb_host_auto_add(const char *spec)
1441 struct USBAutoFilter filter, *f;
1443 if (parse_filter(spec, &filter) < 0)
1446 f = qemu_mallocz(sizeof(*f));
1450 if (!usb_auto_filter) {
1452 * First entry. Init and start the monitor.
1453 * Right now we're using timer to check for new devices.
1454 * If this turns out to be too expensive we can move that into a
1457 usb_auto_timer = qemu_new_timer(rt_clock, usb_host_auto_timer, NULL);
1458 if (!usb_auto_timer) {
1459 fprintf(stderr, "husb: failed to allocate auto scan timer\n");
1464 /* Check for new devices every two seconds */
1465 qemu_mod_timer(usb_auto_timer, qemu_get_clock(rt_clock) + 2000);
1468 dprintf("husb: added auto filter: bus_num %d addr %d vid %d pid %d\n",
1469 f->bus_num, f->addr, f->vendor_id, f->product_id);
1471 f->next = usb_auto_filter;
1472 usb_auto_filter = f;
1477 static int usb_host_auto_del(const char *spec)
1479 struct USBAutoFilter *pf = usb_auto_filter;
1480 struct USBAutoFilter **prev = &usb_auto_filter;
1481 struct USBAutoFilter filter;
1483 if (parse_filter(spec, &filter) < 0)
1487 if (match_filter(pf, &filter)) {
1488 dprintf("husb: removed auto filter: bus_num %d addr %d vid %d pid %d\n",
1489 pf->bus_num, pf->addr, pf->vendor_id, pf->product_id);
1493 if (!usb_auto_filter) {
1494 /* No more filters. Stop scanning. */
1495 qemu_del_timer(usb_auto_timer);
1496 qemu_free_timer(usb_auto_timer);
1509 typedef struct FindDeviceState {
1514 char product_name[PRODUCT_NAME_SZ];
1517 static int usb_host_find_device_scan(void *opaque, int bus_num, int addr,
1519 int vendor_id, int product_id,
1520 const char *product_name, int speed)
1522 FindDeviceState *s = opaque;
1523 if ((vendor_id == s->vendor_id &&
1524 product_id == s->product_id) ||
1525 (bus_num == s->bus_num &&
1527 pstrcpy(s->product_name, PRODUCT_NAME_SZ, product_name);
1528 s->bus_num = bus_num;
1537 'bus.addr' (decimal numbers) or
1538 'vendor_id:product_id' (hexa numbers) */
1539 static int usb_host_find_device(int *pbus_num, int *paddr,
1540 char *product_name, int product_name_size,
1541 const char *devname)
1547 p = strchr(devname, '.');
1549 *pbus_num = strtoul(devname, NULL, 0);
1550 *paddr = strtoul(p + 1, NULL, 0);
1551 fs.bus_num = *pbus_num;
1553 ret = usb_host_scan(&fs, usb_host_find_device_scan);
1555 pstrcpy(product_name, product_name_size, fs.product_name);
1559 p = strchr(devname, ':');
1561 fs.vendor_id = strtoul(devname, NULL, 16);
1562 fs.product_id = strtoul(p + 1, NULL, 16);
1563 ret = usb_host_scan(&fs, usb_host_find_device_scan);
1565 *pbus_num = fs.bus_num;
1567 pstrcpy(product_name, product_name_size, fs.product_name);
1574 /**********************/
1575 /* USB host device info */
1577 struct usb_class_info {
1579 const char *class_name;
1582 static const struct usb_class_info usb_class_info[] = {
1583 { USB_CLASS_AUDIO, "Audio"},
1584 { USB_CLASS_COMM, "Communication"},
1585 { USB_CLASS_HID, "HID"},
1586 { USB_CLASS_HUB, "Hub" },
1587 { USB_CLASS_PHYSICAL, "Physical" },
1588 { USB_CLASS_PRINTER, "Printer" },
1589 { USB_CLASS_MASS_STORAGE, "Storage" },
1590 { USB_CLASS_CDC_DATA, "Data" },
1591 { USB_CLASS_APP_SPEC, "Application Specific" },
1592 { USB_CLASS_VENDOR_SPEC, "Vendor Specific" },
1593 { USB_CLASS_STILL_IMAGE, "Still Image" },
1594 { USB_CLASS_CSCID, "Smart Card" },
1595 { USB_CLASS_CONTENT_SEC, "Content Security" },
1599 static const char *usb_class_str(uint8_t class)
1601 const struct usb_class_info *p;
1602 for(p = usb_class_info; p->class != -1; p++) {
1603 if (p->class == class)
1606 return p->class_name;
1609 static void usb_info_device(int bus_num, int addr, int class_id,
1610 int vendor_id, int product_id,
1611 const char *product_name,
1614 Monitor *mon = cur_mon;
1615 const char *class_str, *speed_str;
1621 case USB_SPEED_FULL:
1624 case USB_SPEED_HIGH:
1632 monitor_printf(mon, " Device %d.%d, speed %s Mb/s\n",
1633 bus_num, addr, speed_str);
1634 class_str = usb_class_str(class_id);
1636 monitor_printf(mon, " %s:", class_str);
1638 monitor_printf(mon, " Class %02x:", class_id);
1639 monitor_printf(mon, " USB device %04x:%04x", vendor_id, product_id);
1640 if (product_name[0] != '\0')
1641 monitor_printf(mon, ", %s", product_name);
1642 monitor_printf(mon, "\n");
1645 static int usb_host_info_device(void *opaque, int bus_num, int addr,
1647 int vendor_id, int product_id,
1648 const char *product_name,
1651 usb_info_device(bus_num, addr, class_id, vendor_id, product_id,
1652 product_name, speed);
1656 static void dec2str(int val, char *str, size_t size)
1659 snprintf(str, size, "*");
1661 snprintf(str, size, "%d", val);
1664 static void hex2str(int val, char *str, size_t size)
1667 snprintf(str, size, "*");
1669 snprintf(str, size, "%x", val);
1672 void usb_host_info(Monitor *mon)
1674 struct USBAutoFilter *f;
1676 usb_host_scan(NULL, usb_host_info_device);
1678 if (usb_auto_filter)
1679 monitor_printf(mon, " Auto filters:\n");
1680 for (f = usb_auto_filter; f; f = f->next) {
1681 char bus[10], addr[10], vid[10], pid[10];
1682 dec2str(f->bus_num, bus, sizeof(bus));
1683 dec2str(f->addr, addr, sizeof(addr));
1684 hex2str(f->vendor_id, vid, sizeof(vid));
1685 hex2str(f->product_id, pid, sizeof(pid));
1686 monitor_printf(mon, " Device %s.%s ID %s:%s\n",
1687 bus, addr, vid, pid);