2 * Linux host USB redirector
4 * Copyright (c) 2005 Fabrice Bellard
6 * Permission is hereby granted, free of charge, to any person obtaining a copy
7 * of this software and associated documentation files (the "Software"), to deal
8 * in the Software without restriction, including without limitation the rights
9 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
10 * copies of the Software, and to permit persons to whom the Software is
11 * furnished to do so, subject to the following conditions:
13 * The above copyright notice and this permission notice shall be included in
14 * all copies or substantial portions of the Software.
16 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
19 * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
21 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
24 #include "qemu-common.h"
25 #include "qemu-timer.h"
29 #if defined(__linux__)
31 #include <sys/ioctl.h>
32 #include <linux/usbdevice_fs.h>
33 #include <linux/version.h>
36 /* We redefine it to avoid version problems */
37 struct usb_ctrltransfer {
47 typedef int USBScanFunc(void *opaque, int bus_num, int addr, int class_id,
48 int vendor_id, int product_id,
49 const char *product_name, int speed);
50 static int usb_host_find_device(int *pbus_num, int *paddr,
51 char *product_name, int product_name_size,
58 #define USBDEVFS_PATH "/proc/bus/usb"
59 #define PRODUCT_NAME_SZ 32
60 #define SIG_ISOCOMPLETE (SIGRTMIN+7)
61 #define MAX_ENDPOINTS 16
63 struct sigaction sigact;
65 /* endpoint association data */
70 /* FIXME: move USBPacket to PendingURB */
71 typedef struct USBHostDevice {
76 struct endp_data endp_table[MAX_ENDPOINTS];
84 typedef struct PendingURB {
85 struct usbdevfs_urb *urb;
87 struct PendingURB *next;
90 static PendingURB *pending_urbs = NULL;
92 static int add_pending_urb(struct usbdevfs_urb *urb)
94 PendingURB *purb = qemu_mallocz(sizeof(PendingURB));
98 purb->next = pending_urbs;
105 static int del_pending_urb(struct usbdevfs_urb *urb)
107 PendingURB *purb = pending_urbs;
108 PendingURB *prev = NULL;
110 while (purb && purb->urb != urb) {
115 if (purb && purb->urb == urb) {
117 prev->next = purb->next;
119 pending_urbs = purb->next;
128 static PendingURB *get_pending_urb(struct usbdevfs_urb *urb)
130 PendingURB *purb = pending_urbs;
132 while (purb && purb->urb != urb) {
136 if (purb && purb->urb == urb) {
143 static int usb_host_update_interfaces(USBHostDevice *dev, int configuration)
145 int dev_descr_len, config_descr_len;
146 int interface, nb_interfaces, nb_configurations;
149 if (configuration == 0) /* address state - ignore */
153 dev_descr_len = dev->descr[0];
154 if (dev_descr_len > dev->descr_len)
156 nb_configurations = dev->descr[17];
159 while (i < dev->descr_len) {
161 printf("i is %d, descr_len is %d, dl %d, dt %d\n", i, dev->descr_len,
162 dev->descr[i], dev->descr[i+1]);
164 if (dev->descr[i+1] != USB_DT_CONFIG) {
168 config_descr_len = dev->descr[i];
171 printf("config #%d need %d\n", dev->descr[i + 5], configuration);
174 if (configuration < 0 || configuration == dev->descr[i + 5])
177 i += config_descr_len;
180 if (i >= dev->descr_len) {
181 printf("usb_host: error - device has no matching configuration\n");
184 nb_interfaces = dev->descr[i + 4];
186 #ifdef USBDEVFS_DISCONNECT
187 /* earlier Linux 2.4 do not support that */
189 struct usbdevfs_ioctl ctrl;
190 for (interface = 0; interface < nb_interfaces; interface++) {
191 ctrl.ioctl_code = USBDEVFS_DISCONNECT;
192 ctrl.ifno = interface;
193 ret = ioctl(dev->fd, USBDEVFS_IOCTL, &ctrl);
194 if (ret < 0 && errno != ENODATA) {
195 perror("USBDEVFS_DISCONNECT");
202 /* XXX: only grab if all interfaces are free */
203 for (interface = 0; interface < nb_interfaces; interface++) {
204 ret = ioctl(dev->fd, USBDEVFS_CLAIMINTERFACE, &interface);
206 if (errno == EBUSY) {
208 "usb_host: warning - device already grabbed\n");
210 perror("USBDEVFS_CLAIMINTERFACE");
218 printf("usb_host: %d interfaces claimed for configuration %d\n",
219 nb_interfaces, configuration);
225 static void usb_host_handle_reset(USBDevice *dev)
228 USBHostDevice *s = (USBHostDevice *)dev;
229 /* USBDEVFS_RESET, but not the first time as it has already be
230 done by the host OS */
231 ioctl(s->fd, USBDEVFS_RESET);
235 static void usb_host_handle_destroy(USBDevice *dev)
237 USBHostDevice *s = (USBHostDevice *)dev;
239 qemu_del_timer(s->timer);
247 static int usb_linux_update_endp_table(USBHostDevice *s);
249 static int usb_host_handle_control(USBDevice *dev,
256 USBHostDevice *s = (USBHostDevice *)dev;
257 struct usb_ctrltransfer ct;
258 struct usbdevfs_setinterface si;
259 int intf_update_required = 0;
262 if (request == (DeviceOutRequest | USB_REQ_SET_ADDRESS)) {
263 /* specific SET_ADDRESS support */
266 } else if (request == ((USB_RECIP_INTERFACE << 8) |
267 USB_REQ_SET_INTERFACE)) {
268 /* set alternate setting for the interface */
269 si.interface = index;
270 si.altsetting = value;
271 ret = ioctl(s->fd, USBDEVFS_SETINTERFACE, &si);
272 usb_linux_update_endp_table(s);
273 } else if (request == (DeviceOutRequest | USB_REQ_SET_CONFIGURATION)) {
275 printf("usb_host_handle_control: SET_CONFIGURATION request - "
276 "config %d\n", value & 0xff);
278 if (s->configuration != (value & 0xff)) {
279 s->configuration = (value & 0xff);
280 intf_update_required = 1;
285 ct.bRequestType = request >> 8;
286 ct.bRequest = request;
292 ret = ioctl(s->fd, USBDEVFS_CONTROL, &ct);
300 return USB_RET_STALL;
303 if (intf_update_required) {
305 printf("usb_host_handle_control: updating interfaces\n");
307 usb_host_update_interfaces(s, value & 0xff);
313 static int usb_host_handle_isoch(USBDevice *dev, USBPacket *p);
315 static int usb_host_handle_data(USBDevice *dev, USBPacket *p)
317 USBHostDevice *s = (USBHostDevice *)dev;
318 struct usbdevfs_bulktransfer bt;
320 uint8_t devep = p->devep;
322 if (s->endp_table[p->devep - 1].type == USBDEVFS_URB_TYPE_ISO) {
323 return usb_host_handle_isoch(dev, p);
326 /* XXX: optimize and handle all data types by looking at the
328 if (p->pid == USB_TOKEN_IN)
334 ret = ioctl(s->fd, USBDEVFS_BULK, &bt);
342 printf("handle_data: errno=%d\n", errno);
344 return USB_RET_STALL;
352 static void urb_completion_pipe_read(void *opaque)
354 USBHostDevice *s = opaque;
355 USBPacket *p = s->packet;
356 PendingURB *pending_urb = NULL;
357 struct usbdevfs_urb *purb = NULL;
360 len = read(s->pipe_fds[0], &pending_urb, sizeof(pending_urb));
361 if (len != sizeof(pending_urb)) {
362 printf("urb_completion: error reading pending_urb, len=%d\n", len);
366 /* FIXME: handle pending_urb->status */
367 del_pending_urb(pending_urb->urb);
374 ret = ioctl(s->fd, USBDEVFS_REAPURBNDELAY, &purb);
376 printf("urb_completion: REAPURBNDELAY ioctl=%d errno=%d\n",
382 if (purb == pending_urb->urb) {
383 printf("urb_completion: urb mismatch reaped=%p pending=%p\n",
388 p->len = purb->actual_length;
389 usb_packet_complete(p);
394 static void isoch_done(int signum, siginfo_t *info, void *context)
396 struct usbdevfs_urb *urb = (struct usbdevfs_urb *)info->si_addr;
397 USBHostDevice *s = (USBHostDevice *)urb->usercontext;
400 if (info->si_code != SI_ASYNCIO ||
401 info->si_signo != SIG_ISOCOMPLETE) {
405 purb = get_pending_urb(urb);
407 purb->status = info->si_errno;
408 write(s->pipe_fds[1], &purb, sizeof(purb));
413 static int usb_host_handle_isoch(USBDevice *dev, USBPacket *p)
415 USBHostDevice *s = (USBHostDevice *)dev;
416 struct usbdevfs_urb *urb, *purb = NULL;
418 uint8_t devep = p->devep;
420 if (p->pid == USB_TOKEN_IN)
423 urb = qemu_mallocz(sizeof(struct usbdevfs_urb) +
424 sizeof(struct usbdevfs_iso_packet_desc));
426 printf("usb_host_handle_isoch: malloc failed\n");
430 urb->type = USBDEVFS_URB_TYPE_ISO;
431 urb->endpoint = devep;
433 urb->flags = USBDEVFS_URB_ISO_ASAP;
434 urb->buffer = p->data;
435 urb->buffer_length = p->len;
436 urb->actual_length = 0;
437 urb->start_frame = 0;
438 urb->error_count = 0;
440 urb->signr = SIG_ISOCOMPLETE;
444 urb->usercontext = s;
445 urb->number_of_packets = 1;
446 urb->iso_frame_desc[0].length = p->len;
447 urb->iso_frame_desc[0].actual_length = 0;
448 urb->iso_frame_desc[0].status = 0;
449 ret = ioctl(s->fd, USBDEVFS_SUBMITURB, urb);
451 if (!add_pending_urb(urb)) {
452 printf("usb_host_handle_isoch: add_pending_urb failed %p\n", urb);
455 printf("usb_host_handle_isoch: SUBMITURB ioctl=%d errno=%d\n",
463 return USB_RET_STALL;
467 /* FIXME: handle urbs_ready together with sync io
468 * workaround for injecting the signaled urbs into current frame */
469 if (s->urbs_ready > 0) {
470 ret = ioctl(s->fd, USBDEVFS_REAPURBNDELAY, &purb);
472 ret = purb->actual_length;
479 return USB_RET_ASYNC;
481 ret = ioctl(s->fd, USBDEVFS_REAPURBNDELAY, &purb);
483 if (del_pending_urb(purb)) {
484 ret = purb->actual_length;
487 printf("usb_host_handle_isoch: del_pending_urb failed %p\n", purb);
491 printf("usb_host_handle_isoch: REAPURBNDELAY ioctl=%d errno=%d\n",
499 /* returns 1 on problem encountered or 0 for success */
500 static int usb_linux_update_endp_table(USBHostDevice *s)
502 uint8_t *descriptors;
503 uint8_t devep, type, configuration, alt_interface;
504 struct usb_ctrltransfer ct;
505 int interface, ret, length, i;
507 ct.bRequestType = USB_DIR_IN;
508 ct.bRequest = USB_REQ_GET_CONFIGURATION;
512 ct.data = &configuration;
515 ret = ioctl(s->fd, USBDEVFS_CONTROL, &ct);
517 perror("usb_linux_update_endp_table");
521 /* in address state */
522 if (configuration == 0)
525 /* get the desired configuration, interface, and endpoint descriptors
526 * from device description */
527 descriptors = &s->descr[18];
528 length = s->descr_len - 18;
531 if (descriptors[i + 1] != USB_DT_CONFIG ||
532 descriptors[i + 5] != configuration) {
533 printf("invalid descriptor data - configuration\n");
539 if (descriptors[i + 1] != USB_DT_INTERFACE ||
540 (descriptors[i + 1] == USB_DT_INTERFACE &&
541 descriptors[i + 4] == 0)) {
546 interface = descriptors[i + 2];
548 ct.bRequestType = USB_DIR_IN | USB_RECIP_INTERFACE;
549 ct.bRequest = USB_REQ_GET_INTERFACE;
551 ct.wIndex = interface;
553 ct.data = &alt_interface;
556 ret = ioctl(s->fd, USBDEVFS_CONTROL, &ct);
558 perror("usb_linux_update_endp_table");
562 /* the current interface descriptor is the active interface
563 * and has endpoints */
564 if (descriptors[i + 3] != alt_interface) {
569 /* advance to the endpoints */
570 while (i < length && descriptors[i +1] != USB_DT_ENDPOINT)
577 if (descriptors[i + 1] != USB_DT_ENDPOINT)
580 devep = descriptors[i + 2];
581 switch (descriptors[i + 3] & 0x3) {
583 type = USBDEVFS_URB_TYPE_CONTROL;
586 type = USBDEVFS_URB_TYPE_ISO;
589 type = USBDEVFS_URB_TYPE_BULK;
592 type = USBDEVFS_URB_TYPE_INTERRUPT;
595 printf("usb_host: malformed endpoint type\n");
596 type = USBDEVFS_URB_TYPE_BULK;
598 s->endp_table[(devep & 0xf) - 1].type = type;
606 static void usb_host_device_check(void *priv)
608 USBHostDevice *s = priv;
609 struct usbdevfs_connectinfo ci;
612 err = ioctl(s->fd, USBDEVFS_CONNECTINFO, &ci);
614 printf("usb device %d.%d disconnected\n", 0, s->dev.addr);
615 usb_device_del_addr(0, s->dev.addr);
619 qemu_mod_timer(s->timer, qemu_get_clock(rt_clock) + 1000);
622 /* XXX: exclude high speed devices or implement EHCI */
623 USBDevice *usb_host_device_open(const char *devname)
626 USBHostDevice *dev = NULL;
627 struct usbdevfs_connectinfo ci;
630 char product_name[PRODUCT_NAME_SZ];
632 if (usb_host_find_device(&bus_num, &addr,
633 product_name, sizeof(product_name),
638 dev = qemu_mallocz(sizeof(USBHostDevice));
642 dev->timer = qemu_new_timer(rt_clock, usb_host_device_check, (void *) dev);
647 printf("usb_host_device_open %s\n", devname);
650 snprintf(buf, sizeof(buf), USBDEVFS_PATH "/%03d/%03d",
652 fd = open(buf, O_RDWR | O_NONBLOCK);
658 /* read the device description */
659 dev->descr_len = read(fd, dev->descr, sizeof(dev->descr));
660 if (dev->descr_len <= 0) {
661 perror("usb_host_device_open: reading device data failed");
668 printf("=== begin dumping device descriptor data ===\n");
669 for (x = 0; x < dev->descr_len; x++)
670 printf("%02x ", dev->descr[x]);
671 printf("\n=== end dumping device descriptor data ===\n");
676 dev->configuration = 1;
678 /* XXX - do something about initial configuration */
679 if (!usb_host_update_interfaces(dev, -1))
682 ret = ioctl(fd, USBDEVFS_CONNECTINFO, &ci);
684 perror("usb_host_device_open: USBDEVFS_CONNECTINFO");
689 printf("host USB device %d.%d grabbed\n", bus_num, addr);
692 ret = usb_linux_update_endp_table(dev);
697 dev->dev.speed = USB_SPEED_LOW;
699 dev->dev.speed = USB_SPEED_HIGH;
700 dev->dev.handle_packet = usb_generic_handle_packet;
702 dev->dev.handle_reset = usb_host_handle_reset;
703 dev->dev.handle_control = usb_host_handle_control;
704 dev->dev.handle_data = usb_host_handle_data;
705 dev->dev.handle_destroy = usb_host_handle_destroy;
707 if (product_name[0] == '\0')
708 snprintf(dev->dev.devname, sizeof(dev->dev.devname),
711 pstrcpy(dev->dev.devname, sizeof(dev->dev.devname),
715 /* set up the signal handlers */
716 sigemptyset(&sigact.sa_mask);
717 sigact.sa_sigaction = isoch_done;
718 sigact.sa_flags = SA_SIGINFO;
719 sigact.sa_restorer = 0;
720 ret = sigaction(SIG_ISOCOMPLETE, &sigact, NULL);
722 perror("usb_host_device_open: sigaction failed");
726 if (pipe(dev->pipe_fds) < 0) {
727 perror("usb_host_device_open: pipe creation failed");
730 fcntl(dev->pipe_fds[0], F_SETFL, O_NONBLOCK | O_ASYNC);
731 fcntl(dev->pipe_fds[1], F_SETFL, O_NONBLOCK);
732 qemu_set_fd_handler(dev->pipe_fds[0], urb_completion_pipe_read, NULL, dev);
735 /* Start the timer to detect disconnect */
736 qemu_mod_timer(dev->timer, qemu_get_clock(rt_clock) + 1000);
739 return (USBDevice *)dev;
743 qemu_del_timer(dev->timer);
750 static int get_tag_value(char *buf, int buf_size,
751 const char *str, const char *tag,
752 const char *stopchars)
756 p = strstr(str, tag);
763 while (*p != '\0' && !strchr(stopchars, *p)) {
764 if ((q - buf) < (buf_size - 1))
772 static int usb_host_scan(void *opaque, USBScanFunc *func)
777 int bus_num, addr, speed, device_count, class_id, product_id, vendor_id;
779 char product_name[512];
781 f = fopen(USBDEVFS_PATH "/devices", "r");
783 term_printf("Could not open %s\n", USBDEVFS_PATH "/devices");
787 bus_num = addr = speed = class_id = product_id = vendor_id = 0;
790 if (fgets(line, sizeof(line), f) == NULL)
792 if (strlen(line) > 0)
793 line[strlen(line) - 1] = '\0';
794 if (line[0] == 'T' && line[1] == ':') {
795 if (device_count && (vendor_id || product_id)) {
796 /* New device. Add the previously discovered device. */
797 ret = func(opaque, bus_num, addr, class_id, vendor_id,
798 product_id, product_name, speed);
802 if (get_tag_value(buf, sizeof(buf), line, "Bus=", " ") < 0)
805 if (get_tag_value(buf, sizeof(buf), line, "Dev#=", " ") < 0)
808 if (get_tag_value(buf, sizeof(buf), line, "Spd=", " ") < 0)
810 if (!strcmp(buf, "480"))
811 speed = USB_SPEED_HIGH;
812 else if (!strcmp(buf, "1.5"))
813 speed = USB_SPEED_LOW;
815 speed = USB_SPEED_FULL;
816 product_name[0] = '\0';
821 } else if (line[0] == 'P' && line[1] == ':') {
822 if (get_tag_value(buf, sizeof(buf), line, "Vendor=", " ") < 0)
824 vendor_id = strtoul(buf, NULL, 16);
825 if (get_tag_value(buf, sizeof(buf), line, "ProdID=", " ") < 0)
827 product_id = strtoul(buf, NULL, 16);
828 } else if (line[0] == 'S' && line[1] == ':') {
829 if (get_tag_value(buf, sizeof(buf), line, "Product=", "") < 0)
831 pstrcpy(product_name, sizeof(product_name), buf);
832 } else if (line[0] == 'D' && line[1] == ':') {
833 if (get_tag_value(buf, sizeof(buf), line, "Cls=", " (") < 0)
835 class_id = strtoul(buf, NULL, 16);
839 if (device_count && (vendor_id || product_id)) {
840 /* Add the last device. */
841 ret = func(opaque, bus_num, addr, class_id, vendor_id,
842 product_id, product_name, speed);
849 typedef struct FindDeviceState {
854 char product_name[PRODUCT_NAME_SZ];
857 static int usb_host_find_device_scan(void *opaque, int bus_num, int addr,
859 int vendor_id, int product_id,
860 const char *product_name, int speed)
862 FindDeviceState *s = opaque;
863 if ((vendor_id == s->vendor_id &&
864 product_id == s->product_id) ||
865 (bus_num == s->bus_num &&
867 pstrcpy(s->product_name, PRODUCT_NAME_SZ, product_name);
868 s->bus_num = bus_num;
877 'bus.addr' (decimal numbers) or
878 'vendor_id:product_id' (hexa numbers) */
879 static int usb_host_find_device(int *pbus_num, int *paddr,
880 char *product_name, int product_name_size,
887 p = strchr(devname, '.');
889 *pbus_num = strtoul(devname, NULL, 0);
890 *paddr = strtoul(p + 1, NULL, 0);
891 fs.bus_num = *pbus_num;
893 ret = usb_host_scan(&fs, usb_host_find_device_scan);
895 pstrcpy(product_name, product_name_size, fs.product_name);
898 p = strchr(devname, ':');
900 fs.vendor_id = strtoul(devname, NULL, 16);
901 fs.product_id = strtoul(p + 1, NULL, 16);
902 ret = usb_host_scan(&fs, usb_host_find_device_scan);
904 *pbus_num = fs.bus_num;
906 pstrcpy(product_name, product_name_size, fs.product_name);
913 /**********************/
914 /* USB host device info */
916 struct usb_class_info {
918 const char *class_name;
921 static const struct usb_class_info usb_class_info[] = {
922 { USB_CLASS_AUDIO, "Audio"},
923 { USB_CLASS_COMM, "Communication"},
924 { USB_CLASS_HID, "HID"},
925 { USB_CLASS_HUB, "Hub" },
926 { USB_CLASS_PHYSICAL, "Physical" },
927 { USB_CLASS_PRINTER, "Printer" },
928 { USB_CLASS_MASS_STORAGE, "Storage" },
929 { USB_CLASS_CDC_DATA, "Data" },
930 { USB_CLASS_APP_SPEC, "Application Specific" },
931 { USB_CLASS_VENDOR_SPEC, "Vendor Specific" },
932 { USB_CLASS_STILL_IMAGE, "Still Image" },
933 { USB_CLASS_CSCID, "Smart Card" },
934 { USB_CLASS_CONTENT_SEC, "Content Security" },
938 static const char *usb_class_str(uint8_t class)
940 const struct usb_class_info *p;
941 for(p = usb_class_info; p->class != -1; p++) {
942 if (p->class == class)
945 return p->class_name;
948 static void usb_info_device(int bus_num, int addr, int class_id,
949 int vendor_id, int product_id,
950 const char *product_name,
953 const char *class_str, *speed_str;
970 term_printf(" Device %d.%d, speed %s Mb/s\n",
971 bus_num, addr, speed_str);
972 class_str = usb_class_str(class_id);
974 term_printf(" %s:", class_str);
976 term_printf(" Class %02x:", class_id);
977 term_printf(" USB device %04x:%04x", vendor_id, product_id);
978 if (product_name[0] != '\0')
979 term_printf(", %s", product_name);
983 static int usb_host_info_device(void *opaque, int bus_num, int addr,
985 int vendor_id, int product_id,
986 const char *product_name,
989 usb_info_device(bus_num, addr, class_id, vendor_id, product_id,
990 product_name, speed);
994 void usb_host_info(void)
996 usb_host_scan(NULL, usb_host_info_device);
1001 void usb_host_info(void)
1003 term_printf("USB host devices not supported\n");
1006 /* XXX: modify configure to compile the right host driver */
1007 USBDevice *usb_host_device_open(const char *devname)