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[2048];
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_delete_addr(s->bus_num, 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;
558 * Process certain standard device requests.
559 * These are infrequent and are processed synchronously.
561 value = le16_to_cpu(s->ctrl.req.wValue);
562 index = le16_to_cpu(s->ctrl.req.wIndex);
564 dprintf("husb: ctrl type 0x%x req 0x%x val 0x%x index %u len %u\n",
565 s->ctrl.req.bRequestType, s->ctrl.req.bRequest, value, index,
568 if (s->ctrl.req.bRequestType == 0) {
569 switch (s->ctrl.req.bRequest) {
570 case USB_REQ_SET_ADDRESS:
571 return usb_host_set_address(s, value);
573 case USB_REQ_SET_CONFIGURATION:
574 return usb_host_set_config(s, value & 0xff);
578 if (s->ctrl.req.bRequestType == 1 &&
579 s->ctrl.req.bRequest == USB_REQ_SET_INTERFACE)
580 return usb_host_set_interface(s, index, value);
582 /* The rest are asynchronous */
584 buffer_len = 8 + s->ctrl.len;
585 if (buffer_len > sizeof(s->ctrl.buffer)) {
586 fprintf(stderr, "husb: ctrl buffer too small (%u > %zu)\n",
587 buffer_len, sizeof(s->ctrl.buffer));
588 return USB_RET_STALL;
591 aurb = async_alloc();
596 * Setup ctrl transfer.
598 * s->ctrl is layed out such that data buffer immediately follows
599 * 'req' struct which is exactly what usbdevfs expects.
603 urb->type = USBDEVFS_URB_TYPE_CONTROL;
604 urb->endpoint = p->devep;
606 urb->buffer = &s->ctrl.req;
607 urb->buffer_length = buffer_len;
609 urb->usercontext = s;
611 ret = ioctl(s->fd, USBDEVFS_SUBMITURB, urb);
613 dprintf("husb: submit ctrl. len %u aurb %p\n", urb->buffer_length, aurb);
616 dprintf("husb: submit failed. errno %d\n", errno);
624 return USB_RET_STALL;
628 usb_defer_packet(p, async_cancel, aurb);
629 return USB_RET_ASYNC;
632 static int do_token_setup(USBDevice *dev, USBPacket *p)
634 USBHostDevice *s = (USBHostDevice *) dev;
638 return USB_RET_STALL;
640 memcpy(&s->ctrl.req, p->data, 8);
641 s->ctrl.len = le16_to_cpu(s->ctrl.req.wLength);
643 s->ctrl.state = CTRL_STATE_SETUP;
645 if (s->ctrl.req.bRequestType & USB_DIR_IN) {
646 ret = usb_host_handle_control(s, p);
650 if (ret < s->ctrl.len)
652 s->ctrl.state = CTRL_STATE_DATA;
654 if (s->ctrl.len == 0)
655 s->ctrl.state = CTRL_STATE_ACK;
657 s->ctrl.state = CTRL_STATE_DATA;
663 static int do_token_in(USBDevice *dev, USBPacket *p)
665 USBHostDevice *s = (USBHostDevice *) dev;
669 return usb_host_handle_data(s, p);
671 switch(s->ctrl.state) {
673 if (!(s->ctrl.req.bRequestType & USB_DIR_IN)) {
674 ret = usb_host_handle_control(s, p);
675 if (ret == USB_RET_ASYNC)
676 return USB_RET_ASYNC;
678 s->ctrl.state = CTRL_STATE_IDLE;
679 return ret > 0 ? 0 : ret;
684 case CTRL_STATE_DATA:
685 if (s->ctrl.req.bRequestType & USB_DIR_IN) {
686 int len = s->ctrl.len - s->ctrl.offset;
689 memcpy(p->data, s->ctrl.buffer + s->ctrl.offset, len);
690 s->ctrl.offset += len;
691 if (s->ctrl.offset >= s->ctrl.len)
692 s->ctrl.state = CTRL_STATE_ACK;
696 s->ctrl.state = CTRL_STATE_IDLE;
697 return USB_RET_STALL;
700 return USB_RET_STALL;
704 static int do_token_out(USBDevice *dev, USBPacket *p)
706 USBHostDevice *s = (USBHostDevice *) dev;
709 return usb_host_handle_data(s, p);
711 switch(s->ctrl.state) {
713 if (s->ctrl.req.bRequestType & USB_DIR_IN) {
714 s->ctrl.state = CTRL_STATE_IDLE;
717 /* ignore additional output */
721 case CTRL_STATE_DATA:
722 if (!(s->ctrl.req.bRequestType & USB_DIR_IN)) {
723 int len = s->ctrl.len - s->ctrl.offset;
726 memcpy(s->ctrl.buffer + s->ctrl.offset, p->data, len);
727 s->ctrl.offset += len;
728 if (s->ctrl.offset >= s->ctrl.len)
729 s->ctrl.state = CTRL_STATE_ACK;
733 s->ctrl.state = CTRL_STATE_IDLE;
734 return USB_RET_STALL;
737 return USB_RET_STALL;
743 * Called by the HC (host controller).
745 * Returns length of the transaction or one of the USB_RET_XXX codes.
747 static int usb_host_handle_packet(USBDevice *s, USBPacket *p)
751 s->state = USB_STATE_ATTACHED;
755 s->state = USB_STATE_NOTATTACHED;
759 s->remote_wakeup = 0;
761 s->state = USB_STATE_DEFAULT;
762 s->info->handle_reset(s);
766 /* Rest of the PIDs must match our address */
767 if (s->state < USB_STATE_DEFAULT || p->devaddr != s->addr)
768 return USB_RET_NODEV;
771 case USB_TOKEN_SETUP:
772 return do_token_setup(s, p);
775 return do_token_in(s, p);
778 return do_token_out(s, p);
781 return USB_RET_STALL;
785 /* returns 1 on problem encountered or 0 for success */
786 static int usb_linux_update_endp_table(USBHostDevice *s)
788 uint8_t *descriptors;
789 uint8_t devep, type, configuration, alt_interface;
790 struct usb_ctrltransfer ct;
791 int interface, ret, length, i;
793 ct.bRequestType = USB_DIR_IN;
794 ct.bRequest = USB_REQ_GET_CONFIGURATION;
798 ct.data = &configuration;
801 ret = ioctl(s->fd, USBDEVFS_CONTROL, &ct);
803 perror("usb_linux_update_endp_table");
807 /* in address state */
808 if (configuration == 0)
811 /* get the desired configuration, interface, and endpoint descriptors
812 * from device description */
813 descriptors = &s->descr[18];
814 length = s->descr_len - 18;
817 if (descriptors[i + 1] != USB_DT_CONFIG ||
818 descriptors[i + 5] != configuration) {
819 dprintf("invalid descriptor data - configuration\n");
825 if (descriptors[i + 1] != USB_DT_INTERFACE ||
826 (descriptors[i + 1] == USB_DT_INTERFACE &&
827 descriptors[i + 4] == 0)) {
832 interface = descriptors[i + 2];
834 ct.bRequestType = USB_DIR_IN | USB_RECIP_INTERFACE;
835 ct.bRequest = USB_REQ_GET_INTERFACE;
837 ct.wIndex = interface;
839 ct.data = &alt_interface;
842 ret = ioctl(s->fd, USBDEVFS_CONTROL, &ct);
844 alt_interface = interface;
847 /* the current interface descriptor is the active interface
848 * and has endpoints */
849 if (descriptors[i + 3] != alt_interface) {
854 /* advance to the endpoints */
855 while (i < length && descriptors[i +1] != USB_DT_ENDPOINT)
862 if (descriptors[i + 1] != USB_DT_ENDPOINT)
865 devep = descriptors[i + 2];
866 switch (descriptors[i + 3] & 0x3) {
868 type = USBDEVFS_URB_TYPE_CONTROL;
871 type = USBDEVFS_URB_TYPE_ISO;
874 type = USBDEVFS_URB_TYPE_BULK;
877 type = USBDEVFS_URB_TYPE_INTERRUPT;
880 dprintf("usb_host: malformed endpoint type\n");
881 type = USBDEVFS_URB_TYPE_BULK;
883 s->endp_table[(devep & 0xf) - 1].type = type;
884 s->endp_table[(devep & 0xf) - 1].halted = 0;
892 static int usb_host_initfn(USBDevice *dev)
897 static USBDevice *usb_host_device_open_addr(int bus_num, int addr, const char *prod_name)
902 struct usbdevfs_connectinfo ci;
905 printf("husb: open device %d.%d\n", bus_num, addr);
907 if (!usb_host_device_path) {
908 perror("husb: USB Host Device Path not set");
911 snprintf(buf, sizeof(buf), "%s/%03d/%03d", usb_host_device_path,
913 fd = open(buf, O_RDWR | O_NONBLOCK);
918 dprintf("husb: opened %s\n", buf);
920 d = usb_create(NULL /* FIXME */, "USB Host Device");
921 dev = DO_UPCAST(USBHostDevice, dev, d);
923 dev->bus_num = bus_num;
927 /* read the device description */
928 dev->descr_len = read(fd, dev->descr, sizeof(dev->descr));
929 if (dev->descr_len <= 0) {
930 perror("husb: reading device data failed");
937 printf("=== begin dumping device descriptor data ===\n");
938 for (x = 0; x < dev->descr_len; x++)
939 printf("%02x ", dev->descr[x]);
940 printf("\n=== end dumping device descriptor data ===\n");
946 * Initial configuration is -1 which makes us claim first
947 * available config. We used to start with 1, which does not
948 * always work. I've seen devices where first config starts
951 if (!usb_host_claim_interfaces(dev, -1))
954 ret = ioctl(fd, USBDEVFS_CONNECTINFO, &ci);
956 perror("usb_host_device_open: USBDEVFS_CONNECTINFO");
960 printf("husb: grabbed usb device %d.%d\n", bus_num, addr);
962 ret = usb_linux_update_endp_table(dev);
967 dev->dev.speed = USB_SPEED_LOW;
969 dev->dev.speed = USB_SPEED_HIGH;
971 if (!prod_name || prod_name[0] == '\0')
972 snprintf(dev->dev.devname, sizeof(dev->dev.devname),
973 "host:%d.%d", bus_num, addr);
975 pstrcpy(dev->dev.devname, sizeof(dev->dev.devname),
978 /* USB devio uses 'write' flag to check for async completions */
979 qemu_set_fd_handler(dev->fd, NULL, async_complete, dev);
983 if (qdev_init(&d->qdev) < 0)
985 return (USBDevice *) dev;
996 static struct USBDeviceInfo usb_host_dev_info = {
997 .qdev.name = "USB Host Device",
998 .qdev.size = sizeof(USBHostDevice),
999 .init = usb_host_initfn,
1000 .handle_packet = usb_host_handle_packet,
1001 .handle_reset = usb_host_handle_reset,
1003 .handle_control = usb_host_handle_control,
1004 .handle_data = usb_host_handle_data,
1006 .handle_destroy = usb_host_handle_destroy,
1009 static void usb_host_register_devices(void)
1011 usb_qdev_register(&usb_host_dev_info);
1013 device_init(usb_host_register_devices)
1015 static int usb_host_auto_add(const char *spec);
1016 static int usb_host_auto_del(const char *spec);
1018 USBDevice *usb_host_device_open(const char *devname)
1020 Monitor *mon = cur_mon;
1022 char product_name[PRODUCT_NAME_SZ];
1024 if (strstr(devname, "auto:")) {
1025 usb_host_auto_add(devname);
1029 if (usb_host_find_device(&bus_num, &addr, product_name, sizeof(product_name),
1033 if (hostdev_find(bus_num, addr)) {
1034 monitor_printf(mon, "husb: host usb device %d.%d is already open\n",
1039 return usb_host_device_open_addr(bus_num, addr, product_name);
1042 int usb_host_device_close(const char *devname)
1044 char product_name[PRODUCT_NAME_SZ];
1048 if (strstr(devname, "auto:"))
1049 return usb_host_auto_del(devname);
1051 if (usb_host_find_device(&bus_num, &addr, product_name, sizeof(product_name),
1055 s = hostdev_find(bus_num, addr);
1057 usb_device_delete_addr(s->bus_num, s->dev.addr);
1064 static int get_tag_value(char *buf, int buf_size,
1065 const char *str, const char *tag,
1066 const char *stopchars)
1070 p = strstr(str, tag);
1074 while (qemu_isspace(*p))
1077 while (*p != '\0' && !strchr(stopchars, *p)) {
1078 if ((q - buf) < (buf_size - 1))
1087 * Use /proc/bus/usb/devices or /dev/bus/usb/devices file to determine
1088 * host's USB devices. This is legacy support since many distributions
1089 * are moving to /sys/bus/usb
1091 static int usb_host_scan_dev(void *opaque, USBScanFunc *func)
1096 int bus_num, addr, speed, device_count, class_id, product_id, vendor_id;
1097 char product_name[512];
1100 if (!usb_host_device_path) {
1101 perror("husb: USB Host Device Path not set");
1104 snprintf(line, sizeof(line), "%s/devices", usb_host_device_path);
1105 f = fopen(line, "r");
1107 perror("husb: cannot open devices file");
1112 bus_num = addr = speed = class_id = product_id = vendor_id = 0;
1114 if (fgets(line, sizeof(line), f) == NULL)
1116 if (strlen(line) > 0)
1117 line[strlen(line) - 1] = '\0';
1118 if (line[0] == 'T' && line[1] == ':') {
1119 if (device_count && (vendor_id || product_id)) {
1120 /* New device. Add the previously discovered device. */
1121 ret = func(opaque, bus_num, addr, class_id, vendor_id,
1122 product_id, product_name, speed);
1126 if (get_tag_value(buf, sizeof(buf), line, "Bus=", " ") < 0)
1128 bus_num = atoi(buf);
1129 if (get_tag_value(buf, sizeof(buf), line, "Dev#=", " ") < 0)
1132 if (get_tag_value(buf, sizeof(buf), line, "Spd=", " ") < 0)
1134 if (!strcmp(buf, "480"))
1135 speed = USB_SPEED_HIGH;
1136 else if (!strcmp(buf, "1.5"))
1137 speed = USB_SPEED_LOW;
1139 speed = USB_SPEED_FULL;
1140 product_name[0] = '\0';
1145 } else if (line[0] == 'P' && line[1] == ':') {
1146 if (get_tag_value(buf, sizeof(buf), line, "Vendor=", " ") < 0)
1148 vendor_id = strtoul(buf, NULL, 16);
1149 if (get_tag_value(buf, sizeof(buf), line, "ProdID=", " ") < 0)
1151 product_id = strtoul(buf, NULL, 16);
1152 } else if (line[0] == 'S' && line[1] == ':') {
1153 if (get_tag_value(buf, sizeof(buf), line, "Product=", "") < 0)
1155 pstrcpy(product_name, sizeof(product_name), buf);
1156 } else if (line[0] == 'D' && line[1] == ':') {
1157 if (get_tag_value(buf, sizeof(buf), line, "Cls=", " (") < 0)
1159 class_id = strtoul(buf, NULL, 16);
1163 if (device_count && (vendor_id || product_id)) {
1164 /* Add the last device. */
1165 ret = func(opaque, bus_num, addr, class_id, vendor_id,
1166 product_id, product_name, speed);
1175 * Read sys file-system device file
1177 * @line address of buffer to put file contents in
1178 * @line_size size of line
1179 * @device_file path to device file (printf format string)
1180 * @device_name device being opened (inserted into device_file)
1182 * @return 0 failed, 1 succeeded ('line' contains data)
1184 static int usb_host_read_file(char *line, size_t line_size, const char *device_file, const char *device_name)
1186 Monitor *mon = cur_mon;
1189 char filename[PATH_MAX];
1191 snprintf(filename, PATH_MAX, USBSYSBUS_PATH "/devices/%s/%s", device_name,
1193 f = fopen(filename, "r");
1195 fgets(line, line_size, f);
1199 monitor_printf(mon, "husb: could not open %s\n", filename);
1206 * Use /sys/bus/usb/devices/ directory to determine host's USB
1209 * This code is based on Robert Schiele's original patches posted to
1210 * the Novell bug-tracker https://bugzilla.novell.com/show_bug.cgi?id=241950
1212 static int usb_host_scan_sys(void *opaque, USBScanFunc *func)
1216 int bus_num, addr, speed, class_id, product_id, vendor_id;
1218 char product_name[512];
1221 dir = opendir(USBSYSBUS_PATH "/devices");
1223 perror("husb: cannot open devices directory");
1227 while ((de = readdir(dir))) {
1228 if (de->d_name[0] != '.' && !strchr(de->d_name, ':')) {
1229 char *tmpstr = de->d_name;
1230 if (!strncmp(de->d_name, "usb", 3))
1232 bus_num = atoi(tmpstr);
1234 if (!usb_host_read_file(line, sizeof(line), "devnum", de->d_name))
1236 if (sscanf(line, "%d", &addr) != 1)
1239 if (!usb_host_read_file(line, sizeof(line), "bDeviceClass",
1242 if (sscanf(line, "%x", &class_id) != 1)
1245 if (!usb_host_read_file(line, sizeof(line), "idVendor", de->d_name))
1247 if (sscanf(line, "%x", &vendor_id) != 1)
1250 if (!usb_host_read_file(line, sizeof(line), "idProduct",
1253 if (sscanf(line, "%x", &product_id) != 1)
1256 if (!usb_host_read_file(line, sizeof(line), "product",
1260 if (strlen(line) > 0)
1261 line[strlen(line) - 1] = '\0';
1262 pstrcpy(product_name, sizeof(product_name), line);
1265 if (!usb_host_read_file(line, sizeof(line), "speed", de->d_name))
1267 if (!strcmp(line, "480\n"))
1268 speed = USB_SPEED_HIGH;
1269 else if (!strcmp(line, "1.5\n"))
1270 speed = USB_SPEED_LOW;
1272 speed = USB_SPEED_FULL;
1274 ret = func(opaque, bus_num, addr, class_id, vendor_id,
1275 product_id, product_name, speed);
1287 * Determine how to access the host's USB devices and call the
1288 * specific support function.
1290 static int usb_host_scan(void *opaque, USBScanFunc *func)
1292 Monitor *mon = cur_mon;
1296 const char *fs_type[] = {"unknown", "proc", "dev", "sys"};
1297 char devpath[PATH_MAX];
1299 /* only check the host once */
1301 dir = opendir(USBSYSBUS_PATH "/devices");
1303 /* devices found in /dev/bus/usb/ (yes - not a mistake!) */
1304 strcpy(devpath, USBDEVBUS_PATH);
1305 usb_fs_type = USB_FS_SYS;
1307 dprintf(USBDBG_DEVOPENED, USBSYSBUS_PATH);
1310 f = fopen(USBPROCBUS_PATH "/devices", "r");
1312 /* devices found in /proc/bus/usb/ */
1313 strcpy(devpath, USBPROCBUS_PATH);
1314 usb_fs_type = USB_FS_PROC;
1316 dprintf(USBDBG_DEVOPENED, USBPROCBUS_PATH);
1319 /* try additional methods if an access method hasn't been found yet */
1320 f = fopen(USBDEVBUS_PATH "/devices", "r");
1322 /* devices found in /dev/bus/usb/ */
1323 strcpy(devpath, USBDEVBUS_PATH);
1324 usb_fs_type = USB_FS_DEV;
1326 dprintf(USBDBG_DEVOPENED, USBDEVBUS_PATH);
1331 monitor_printf(mon, "husb: unable to access USB devices\n");
1335 /* the module setting (used later for opening devices) */
1336 usb_host_device_path = qemu_mallocz(strlen(devpath)+1);
1337 strcpy(usb_host_device_path, devpath);
1338 monitor_printf(mon, "husb: using %s file-system with %s\n",
1339 fs_type[usb_fs_type], usb_host_device_path);
1342 switch (usb_fs_type) {
1345 ret = usb_host_scan_dev(opaque, func);
1348 ret = usb_host_scan_sys(opaque, func);
1357 struct USBAutoFilter {
1358 struct USBAutoFilter *next;
1365 static QEMUTimer *usb_auto_timer;
1366 static struct USBAutoFilter *usb_auto_filter;
1368 static int usb_host_auto_scan(void *opaque, int bus_num, int addr,
1369 int class_id, int vendor_id, int product_id,
1370 const char *product_name, int speed)
1372 struct USBAutoFilter *f;
1373 struct USBDevice *dev;
1379 for (f = usb_auto_filter; f; f = f->next) {
1380 if (f->bus_num >= 0 && f->bus_num != bus_num)
1383 if (f->addr >= 0 && f->addr != addr)
1386 if (f->vendor_id >= 0 && f->vendor_id != vendor_id)
1389 if (f->product_id >= 0 && f->product_id != product_id)
1392 /* We got a match */
1394 /* Already attached ? */
1395 if (hostdev_find(bus_num, addr))
1398 dprintf("husb: auto open: bus_num %d addr %d\n", bus_num, addr);
1400 dev = usb_host_device_open_addr(bus_num, addr, product_name);
1406 static void usb_host_auto_timer(void *unused)
1408 usb_host_scan(NULL, usb_host_auto_scan);
1409 qemu_mod_timer(usb_auto_timer, qemu_get_clock(rt_clock) + 2000);
1413 * Autoconnect filter
1415 * auto:bus:dev[:vid:pid]
1416 * auto:bus.dev[:vid:pid]
1418 * bus - bus number (dec, * means any)
1419 * dev - device number (dec, * means any)
1420 * vid - vendor id (hex, * means any)
1421 * pid - product id (hex, * means any)
1423 * See 'lsusb' output.
1425 static int parse_filter(const char *spec, struct USBAutoFilter *f)
1427 enum { BUS, DEV, VID, PID, DONE };
1428 const char *p = spec;
1436 for (i = BUS; i < DONE; i++) {
1437 p = strpbrk(p, ":.");
1445 case BUS: f->bus_num = strtol(p, NULL, 10); break;
1446 case DEV: f->addr = strtol(p, NULL, 10); break;
1447 case VID: f->vendor_id = strtol(p, NULL, 16); break;
1448 case PID: f->product_id = strtol(p, NULL, 16); break;
1453 fprintf(stderr, "husb: invalid auto filter spec %s\n", spec);
1460 static int match_filter(const struct USBAutoFilter *f1,
1461 const struct USBAutoFilter *f2)
1463 return f1->bus_num == f2->bus_num &&
1464 f1->addr == f2->addr &&
1465 f1->vendor_id == f2->vendor_id &&
1466 f1->product_id == f2->product_id;
1469 static int usb_host_auto_add(const char *spec)
1471 struct USBAutoFilter filter, *f;
1473 if (parse_filter(spec, &filter) < 0)
1476 f = qemu_mallocz(sizeof(*f));
1480 if (!usb_auto_filter) {
1482 * First entry. Init and start the monitor.
1483 * Right now we're using timer to check for new devices.
1484 * If this turns out to be too expensive we can move that into a
1487 usb_auto_timer = qemu_new_timer(rt_clock, usb_host_auto_timer, NULL);
1488 if (!usb_auto_timer) {
1489 fprintf(stderr, "husb: failed to allocate auto scan timer\n");
1494 /* Check for new devices every two seconds */
1495 qemu_mod_timer(usb_auto_timer, qemu_get_clock(rt_clock) + 2000);
1498 dprintf("husb: added auto filter: bus_num %d addr %d vid %d pid %d\n",
1499 f->bus_num, f->addr, f->vendor_id, f->product_id);
1501 f->next = usb_auto_filter;
1502 usb_auto_filter = f;
1507 static int usb_host_auto_del(const char *spec)
1509 struct USBAutoFilter *pf = usb_auto_filter;
1510 struct USBAutoFilter **prev = &usb_auto_filter;
1511 struct USBAutoFilter filter;
1513 if (parse_filter(spec, &filter) < 0)
1517 if (match_filter(pf, &filter)) {
1518 dprintf("husb: removed auto filter: bus_num %d addr %d vid %d pid %d\n",
1519 pf->bus_num, pf->addr, pf->vendor_id, pf->product_id);
1523 if (!usb_auto_filter) {
1524 /* No more filters. Stop scanning. */
1525 qemu_del_timer(usb_auto_timer);
1526 qemu_free_timer(usb_auto_timer);
1539 typedef struct FindDeviceState {
1544 char product_name[PRODUCT_NAME_SZ];
1547 static int usb_host_find_device_scan(void *opaque, int bus_num, int addr,
1549 int vendor_id, int product_id,
1550 const char *product_name, int speed)
1552 FindDeviceState *s = opaque;
1553 if ((vendor_id == s->vendor_id &&
1554 product_id == s->product_id) ||
1555 (bus_num == s->bus_num &&
1557 pstrcpy(s->product_name, PRODUCT_NAME_SZ, product_name);
1558 s->bus_num = bus_num;
1567 'bus.addr' (decimal numbers) or
1568 'vendor_id:product_id' (hexa numbers) */
1569 static int usb_host_find_device(int *pbus_num, int *paddr,
1570 char *product_name, int product_name_size,
1571 const char *devname)
1577 p = strchr(devname, '.');
1579 *pbus_num = strtoul(devname, NULL, 0);
1580 *paddr = strtoul(p + 1, NULL, 0);
1581 fs.bus_num = *pbus_num;
1583 ret = usb_host_scan(&fs, usb_host_find_device_scan);
1585 pstrcpy(product_name, product_name_size, fs.product_name);
1589 p = strchr(devname, ':');
1591 fs.vendor_id = strtoul(devname, NULL, 16);
1592 fs.product_id = strtoul(p + 1, NULL, 16);
1593 ret = usb_host_scan(&fs, usb_host_find_device_scan);
1595 *pbus_num = fs.bus_num;
1597 pstrcpy(product_name, product_name_size, fs.product_name);
1604 /**********************/
1605 /* USB host device info */
1607 struct usb_class_info {
1609 const char *class_name;
1612 static const struct usb_class_info usb_class_info[] = {
1613 { USB_CLASS_AUDIO, "Audio"},
1614 { USB_CLASS_COMM, "Communication"},
1615 { USB_CLASS_HID, "HID"},
1616 { USB_CLASS_HUB, "Hub" },
1617 { USB_CLASS_PHYSICAL, "Physical" },
1618 { USB_CLASS_PRINTER, "Printer" },
1619 { USB_CLASS_MASS_STORAGE, "Storage" },
1620 { USB_CLASS_CDC_DATA, "Data" },
1621 { USB_CLASS_APP_SPEC, "Application Specific" },
1622 { USB_CLASS_VENDOR_SPEC, "Vendor Specific" },
1623 { USB_CLASS_STILL_IMAGE, "Still Image" },
1624 { USB_CLASS_CSCID, "Smart Card" },
1625 { USB_CLASS_CONTENT_SEC, "Content Security" },
1629 static const char *usb_class_str(uint8_t class)
1631 const struct usb_class_info *p;
1632 for(p = usb_class_info; p->class != -1; p++) {
1633 if (p->class == class)
1636 return p->class_name;
1639 static void usb_info_device(Monitor *mon, int bus_num, int addr, int class_id,
1640 int vendor_id, int product_id,
1641 const char *product_name,
1644 const char *class_str, *speed_str;
1650 case USB_SPEED_FULL:
1653 case USB_SPEED_HIGH:
1661 monitor_printf(mon, " Device %d.%d, speed %s Mb/s\n",
1662 bus_num, addr, speed_str);
1663 class_str = usb_class_str(class_id);
1665 monitor_printf(mon, " %s:", class_str);
1667 monitor_printf(mon, " Class %02x:", class_id);
1668 monitor_printf(mon, " USB device %04x:%04x", vendor_id, product_id);
1669 if (product_name[0] != '\0')
1670 monitor_printf(mon, ", %s", product_name);
1671 monitor_printf(mon, "\n");
1674 static int usb_host_info_device(void *opaque, int bus_num, int addr,
1676 int vendor_id, int product_id,
1677 const char *product_name,
1680 Monitor *mon = opaque;
1682 usb_info_device(mon, bus_num, addr, class_id, vendor_id, product_id,
1683 product_name, speed);
1687 static void dec2str(int val, char *str, size_t size)
1690 snprintf(str, size, "*");
1692 snprintf(str, size, "%d", val);
1695 static void hex2str(int val, char *str, size_t size)
1698 snprintf(str, size, "*");
1700 snprintf(str, size, "%x", val);
1703 void usb_host_info(Monitor *mon)
1705 struct USBAutoFilter *f;
1707 usb_host_scan(mon, usb_host_info_device);
1709 if (usb_auto_filter)
1710 monitor_printf(mon, " Auto filters:\n");
1711 for (f = usb_auto_filter; f; f = f->next) {
1712 char bus[10], addr[10], vid[10], pid[10];
1713 dec2str(f->bus_num, bus, sizeof(bus));
1714 dec2str(f->addr, addr, sizeof(addr));
1715 hex2str(f->vendor_id, vid, sizeof(vid));
1716 hex2str(f->product_id, pid, sizeof(pid));
1717 monitor_printf(mon, " Device %s.%s ID %s:%s\n",
1718 bus, addr, vid, pid);