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"
28 #if defined(__linux__)
30 #include <sys/ioctl.h>
31 #include <linux/usbdevice_fs.h>
32 #include <linux/version.h>
35 /* We redefine it to avoid version problems */
36 struct usb_ctrltransfer {
46 typedef int USBScanFunc(void *opaque, int bus_num, int addr, int class_id,
47 int vendor_id, int product_id,
48 const char *product_name, int speed);
49 static int usb_host_find_device(int *pbus_num, int *paddr,
50 char *product_name, int product_name_size,
57 #define USBDEVFS_PATH "/proc/bus/usb"
58 #define PRODUCT_NAME_SZ 32
59 #define SIG_ISOCOMPLETE (SIGRTMIN+7)
60 #define MAX_ENDPOINTS 16
62 struct sigaction sigact;
64 /* endpoint association data */
69 /* FIXME: move USBPacket to PendingURB */
70 typedef struct USBHostDevice {
75 struct endp_data endp_table[MAX_ENDPOINTS];
82 typedef struct PendingURB {
83 struct usbdevfs_urb *urb;
85 struct PendingURB *next;
88 static PendingURB *pending_urbs = NULL;
90 static int add_pending_urb(struct usbdevfs_urb *urb)
92 PendingURB *purb = qemu_mallocz(sizeof(PendingURB));
96 purb->next = pending_urbs;
103 static int del_pending_urb(struct usbdevfs_urb *urb)
105 PendingURB *purb = pending_urbs;
106 PendingURB *prev = NULL;
108 while (purb && purb->urb != urb) {
113 if (purb && purb->urb == urb) {
115 prev->next = purb->next;
117 pending_urbs = purb->next;
126 static PendingURB *get_pending_urb(struct usbdevfs_urb *urb)
128 PendingURB *purb = pending_urbs;
130 while (purb && purb->urb != urb) {
134 if (purb && purb->urb == urb) {
141 static int usb_host_update_interfaces(USBHostDevice *dev, int configuration)
143 int dev_descr_len, config_descr_len;
144 int interface, nb_interfaces, nb_configurations;
147 if (configuration == 0) /* address state - ignore */
151 dev_descr_len = dev->descr[0];
152 if (dev_descr_len > dev->descr_len)
154 nb_configurations = dev->descr[17];
157 while (i < dev->descr_len) {
159 printf("i is %d, descr_len is %d, dl %d, dt %d\n", i, dev->descr_len,
160 dev->descr[i], dev->descr[i+1]);
162 if (dev->descr[i+1] != USB_DT_CONFIG) {
166 config_descr_len = dev->descr[i];
168 if (configuration == dev->descr[i + 5])
171 i += config_descr_len;
174 if (i >= dev->descr_len) {
175 printf("usb_host: error - device has no matching configuration\n");
178 nb_interfaces = dev->descr[i + 4];
180 #ifdef USBDEVFS_DISCONNECT
181 /* earlier Linux 2.4 do not support that */
183 struct usbdevfs_ioctl ctrl;
184 for (interface = 0; interface < nb_interfaces; interface++) {
185 ctrl.ioctl_code = USBDEVFS_DISCONNECT;
186 ctrl.ifno = interface;
187 ret = ioctl(dev->fd, USBDEVFS_IOCTL, &ctrl);
188 if (ret < 0 && errno != ENODATA) {
189 perror("USBDEVFS_DISCONNECT");
196 /* XXX: only grab if all interfaces are free */
197 for (interface = 0; interface < nb_interfaces; interface++) {
198 ret = ioctl(dev->fd, USBDEVFS_CLAIMINTERFACE, &interface);
200 if (errno == EBUSY) {
202 "usb_host: warning - device already grabbed\n");
204 perror("USBDEVFS_CLAIMINTERFACE");
212 printf("usb_host: %d interfaces claimed for configuration %d\n",
213 nb_interfaces, configuration);
219 static void usb_host_handle_reset(USBDevice *dev)
222 USBHostDevice *s = (USBHostDevice *)dev;
223 /* USBDEVFS_RESET, but not the first time as it has already be
224 done by the host OS */
225 ioctl(s->fd, USBDEVFS_RESET);
229 static void usb_host_handle_destroy(USBDevice *dev)
231 USBHostDevice *s = (USBHostDevice *)dev;
238 static int usb_linux_update_endp_table(USBHostDevice *s);
240 static int usb_host_handle_control(USBDevice *dev,
247 USBHostDevice *s = (USBHostDevice *)dev;
248 struct usb_ctrltransfer ct;
249 struct usbdevfs_setinterface si;
250 int intf_update_required = 0;
253 if (request == (DeviceOutRequest | USB_REQ_SET_ADDRESS)) {
254 /* specific SET_ADDRESS support */
257 } else if (request == ((USB_RECIP_INTERFACE << 8) |
258 USB_REQ_SET_INTERFACE)) {
259 /* set alternate setting for the interface */
260 si.interface = index;
261 si.altsetting = value;
262 ret = ioctl(s->fd, USBDEVFS_SETINTERFACE, &si);
263 usb_linux_update_endp_table(s);
264 } else if (request == (DeviceOutRequest | USB_REQ_SET_CONFIGURATION)) {
266 printf("usb_host_handle_control: SET_CONFIGURATION request - "
267 "config %d\n", value & 0xff);
269 if (s->configuration != (value & 0xff)) {
270 s->configuration = (value & 0xff);
271 intf_update_required = 1;
276 ct.bRequestType = request >> 8;
277 ct.bRequest = request;
283 ret = ioctl(s->fd, USBDEVFS_CONTROL, &ct);
291 return USB_RET_STALL;
294 if (intf_update_required) {
296 printf("usb_host_handle_control: updating interfaces\n");
298 usb_host_update_interfaces(s, value & 0xff);
304 static int usb_host_handle_isoch(USBDevice *dev, USBPacket *p);
306 static int usb_host_handle_data(USBDevice *dev, USBPacket *p)
308 USBHostDevice *s = (USBHostDevice *)dev;
309 struct usbdevfs_bulktransfer bt;
311 uint8_t devep = p->devep;
313 if (s->endp_table[p->devep - 1].type == USBDEVFS_URB_TYPE_ISO) {
314 return usb_host_handle_isoch(dev, p);
317 /* XXX: optimize and handle all data types by looking at the
319 if (p->pid == USB_TOKEN_IN)
325 ret = ioctl(s->fd, USBDEVFS_BULK, &bt);
333 printf("handle_data: errno=%d\n", errno);
335 return USB_RET_STALL;
343 static void urb_completion_pipe_read(void *opaque)
345 USBHostDevice *s = opaque;
346 USBPacket *p = s->packet;
347 PendingURB *pending_urb = NULL;
348 struct usbdevfs_urb *purb = NULL;
351 len = read(s->pipe_fds[0], &pending_urb, sizeof(pending_urb));
352 if (len != sizeof(pending_urb)) {
353 printf("urb_completion: error reading pending_urb, len=%d\n", len);
357 /* FIXME: handle pending_urb->status */
358 del_pending_urb(pending_urb->urb);
365 ret = ioctl(s->fd, USBDEVFS_REAPURBNDELAY, &purb);
367 printf("urb_completion: REAPURBNDELAY ioctl=%d errno=%d\n",
373 if (purb == pending_urb->urb) {
374 printf("urb_completion: urb mismatch reaped=%p pending=%p\n",
379 p->len = purb->actual_length;
380 usb_packet_complete(p);
385 static void isoch_done(int signum, siginfo_t *info, void *context)
387 struct usbdevfs_urb *urb = (struct usbdevfs_urb *)info->si_addr;
388 USBHostDevice *s = (USBHostDevice *)urb->usercontext;
391 if (info->si_code != SI_ASYNCIO ||
392 info->si_signo != SIG_ISOCOMPLETE) {
396 purb = get_pending_urb(urb);
398 purb->status = info->si_errno;
399 write(s->pipe_fds[1], &purb, sizeof(purb));
404 static int usb_host_handle_isoch(USBDevice *dev, USBPacket *p)
406 USBHostDevice *s = (USBHostDevice *)dev;
407 struct usbdevfs_urb *urb, *purb = NULL;
409 uint8_t devep = p->devep;
411 if (p->pid == USB_TOKEN_IN)
414 urb = qemu_mallocz(sizeof(struct usbdevfs_urb) +
415 sizeof(struct usbdevfs_iso_packet_desc));
417 printf("usb_host_handle_isoch: malloc failed\n");
421 urb->type = USBDEVFS_URB_TYPE_ISO;
422 urb->endpoint = devep;
424 urb->flags = USBDEVFS_URB_ISO_ASAP;
425 urb->buffer = p->data;
426 urb->buffer_length = p->len;
427 urb->actual_length = 0;
428 urb->start_frame = 0;
429 urb->error_count = 0;
431 urb->signr = SIG_ISOCOMPLETE;
435 urb->usercontext = s;
436 urb->number_of_packets = 1;
437 urb->iso_frame_desc[0].length = p->len;
438 urb->iso_frame_desc[0].actual_length = 0;
439 urb->iso_frame_desc[0].status = 0;
440 ret = ioctl(s->fd, USBDEVFS_SUBMITURB, urb);
442 if (!add_pending_urb(urb)) {
443 printf("usb_host_handle_isoch: add_pending_urb failed %p\n", urb);
446 printf("usb_host_handle_isoch: SUBMITURB ioctl=%d errno=%d\n",
454 return USB_RET_STALL;
458 /* FIXME: handle urbs_ready together with sync io
459 * workaround for injecting the signaled urbs into current frame */
460 if (s->urbs_ready > 0) {
461 ret = ioctl(s->fd, USBDEVFS_REAPURBNDELAY, &purb);
463 ret = purb->actual_length;
470 return USB_RET_ASYNC;
472 ret = ioctl(s->fd, USBDEVFS_REAPURBNDELAY, &purb);
474 if (del_pending_urb(purb)) {
475 ret = purb->actual_length;
478 printf("usb_host_handle_isoch: del_pending_urb failed %p\n", purb);
482 printf("usb_host_handle_isoch: REAPURBNDELAY ioctl=%d errno=%d\n",
490 /* returns 1 on problem encountered or 0 for success */
491 static int usb_linux_update_endp_table(USBHostDevice *s)
493 uint8_t *descriptors;
494 uint8_t devep, type, configuration, alt_interface;
495 struct usb_ctrltransfer ct;
496 int interface, ret, length, i;
498 ct.bRequestType = USB_DIR_IN;
499 ct.bRequest = USB_REQ_GET_CONFIGURATION;
503 ct.data = &configuration;
506 ret = ioctl(s->fd, USBDEVFS_CONTROL, &ct);
508 perror("usb_linux_update_endp_table");
512 /* in address state */
513 if (configuration == 0)
516 /* get the desired configuration, interface, and endpoint descriptors
517 * from device description */
518 descriptors = &s->descr[18];
519 length = s->descr_len - 18;
522 if (descriptors[i + 1] != USB_DT_CONFIG ||
523 descriptors[i + 5] != configuration) {
524 printf("invalid descriptor data - configuration\n");
530 if (descriptors[i + 1] != USB_DT_INTERFACE ||
531 (descriptors[i + 1] == USB_DT_INTERFACE &&
532 descriptors[i + 4] == 0)) {
537 interface = descriptors[i + 2];
539 ct.bRequestType = USB_DIR_IN | USB_RECIP_INTERFACE;
540 ct.bRequest = USB_REQ_GET_INTERFACE;
542 ct.wIndex = interface;
544 ct.data = &alt_interface;
547 ret = ioctl(s->fd, USBDEVFS_CONTROL, &ct);
549 perror("usb_linux_update_endp_table");
553 /* the current interface descriptor is the active interface
554 * and has endpoints */
555 if (descriptors[i + 3] != alt_interface) {
560 /* advance to the endpoints */
561 while (i < length && descriptors[i +1] != USB_DT_ENDPOINT)
568 if (descriptors[i + 1] != USB_DT_ENDPOINT)
571 devep = descriptors[i + 2];
572 switch (descriptors[i + 3] & 0x3) {
574 type = USBDEVFS_URB_TYPE_CONTROL;
577 type = USBDEVFS_URB_TYPE_ISO;
580 type = USBDEVFS_URB_TYPE_BULK;
583 type = USBDEVFS_URB_TYPE_INTERRUPT;
586 printf("usb_host: malformed endpoint type\n");
587 type = USBDEVFS_URB_TYPE_BULK;
589 s->endp_table[(devep & 0xf) - 1].type = type;
597 /* XXX: exclude high speed devices or implement EHCI */
598 USBDevice *usb_host_device_open(const char *devname)
601 USBHostDevice *dev = NULL;
602 struct usbdevfs_connectinfo ci;
605 char product_name[PRODUCT_NAME_SZ];
607 dev = qemu_mallocz(sizeof(USBHostDevice));
612 printf("usb_host_device_open %s\n", devname);
614 if (usb_host_find_device(&bus_num, &addr,
615 product_name, sizeof(product_name),
619 snprintf(buf, sizeof(buf), USBDEVFS_PATH "/%03d/%03d",
621 fd = open(buf, O_RDWR | O_NONBLOCK);
627 /* read the device description */
628 dev->descr_len = read(fd, dev->descr, sizeof(dev->descr));
629 if (dev->descr_len <= 0) {
630 perror("usb_host_device_open: reading device data failed");
637 printf("=== begin dumping device descriptor data ===\n");
638 for (x = 0; x < dev->descr_len; x++)
639 printf("%02x ", dev->descr[x]);
640 printf("\n=== end dumping device descriptor data ===\n");
645 dev->configuration = 1;
647 /* XXX - do something about initial configuration */
648 if (!usb_host_update_interfaces(dev, 1))
651 ret = ioctl(fd, USBDEVFS_CONNECTINFO, &ci);
653 perror("usb_host_device_open: USBDEVFS_CONNECTINFO");
658 printf("host USB device %d.%d grabbed\n", bus_num, addr);
661 ret = usb_linux_update_endp_table(dev);
666 dev->dev.speed = USB_SPEED_LOW;
668 dev->dev.speed = USB_SPEED_HIGH;
669 dev->dev.handle_packet = usb_generic_handle_packet;
671 dev->dev.handle_reset = usb_host_handle_reset;
672 dev->dev.handle_control = usb_host_handle_control;
673 dev->dev.handle_data = usb_host_handle_data;
674 dev->dev.handle_destroy = usb_host_handle_destroy;
676 if (product_name[0] == '\0')
677 snprintf(dev->dev.devname, sizeof(dev->dev.devname),
680 pstrcpy(dev->dev.devname, sizeof(dev->dev.devname),
684 /* set up the signal handlers */
685 sigemptyset(&sigact.sa_mask);
686 sigact.sa_sigaction = isoch_done;
687 sigact.sa_flags = SA_SIGINFO;
688 sigact.sa_restorer = 0;
689 ret = sigaction(SIG_ISOCOMPLETE, &sigact, NULL);
691 perror("usb_host_device_open: sigaction failed");
695 if (pipe(dev->pipe_fds) < 0) {
696 perror("usb_host_device_open: pipe creation failed");
699 fcntl(dev->pipe_fds[0], F_SETFL, O_NONBLOCK | O_ASYNC);
700 fcntl(dev->pipe_fds[1], F_SETFL, O_NONBLOCK);
701 qemu_set_fd_handler(dev->pipe_fds[0], urb_completion_pipe_read, NULL, dev);
704 return (USBDevice *)dev;
712 static int get_tag_value(char *buf, int buf_size,
713 const char *str, const char *tag,
714 const char *stopchars)
718 p = strstr(str, tag);
725 while (*p != '\0' && !strchr(stopchars, *p)) {
726 if ((q - buf) < (buf_size - 1))
734 static int usb_host_scan(void *opaque, USBScanFunc *func)
739 int bus_num, addr, speed, device_count, class_id, product_id, vendor_id;
741 char product_name[512];
743 f = fopen(USBDEVFS_PATH "/devices", "r");
745 term_printf("Could not open %s\n", USBDEVFS_PATH "/devices");
749 bus_num = addr = speed = class_id = product_id = vendor_id = 0;
752 if (fgets(line, sizeof(line), f) == NULL)
754 if (strlen(line) > 0)
755 line[strlen(line) - 1] = '\0';
756 if (line[0] == 'T' && line[1] == ':') {
757 if (device_count && (vendor_id || product_id)) {
758 /* New device. Add the previously discovered device. */
759 ret = func(opaque, bus_num, addr, class_id, vendor_id,
760 product_id, product_name, speed);
764 if (get_tag_value(buf, sizeof(buf), line, "Bus=", " ") < 0)
767 if (get_tag_value(buf, sizeof(buf), line, "Dev#=", " ") < 0)
770 if (get_tag_value(buf, sizeof(buf), line, "Spd=", " ") < 0)
772 if (!strcmp(buf, "480"))
773 speed = USB_SPEED_HIGH;
774 else if (!strcmp(buf, "1.5"))
775 speed = USB_SPEED_LOW;
777 speed = USB_SPEED_FULL;
778 product_name[0] = '\0';
783 } else if (line[0] == 'P' && line[1] == ':') {
784 if (get_tag_value(buf, sizeof(buf), line, "Vendor=", " ") < 0)
786 vendor_id = strtoul(buf, NULL, 16);
787 if (get_tag_value(buf, sizeof(buf), line, "ProdID=", " ") < 0)
789 product_id = strtoul(buf, NULL, 16);
790 } else if (line[0] == 'S' && line[1] == ':') {
791 if (get_tag_value(buf, sizeof(buf), line, "Product=", "") < 0)
793 pstrcpy(product_name, sizeof(product_name), buf);
794 } else if (line[0] == 'D' && line[1] == ':') {
795 if (get_tag_value(buf, sizeof(buf), line, "Cls=", " (") < 0)
797 class_id = strtoul(buf, NULL, 16);
801 if (device_count && (vendor_id || product_id)) {
802 /* Add the last device. */
803 ret = func(opaque, bus_num, addr, class_id, vendor_id,
804 product_id, product_name, speed);
811 typedef struct FindDeviceState {
816 char product_name[PRODUCT_NAME_SZ];
819 static int usb_host_find_device_scan(void *opaque, int bus_num, int addr,
821 int vendor_id, int product_id,
822 const char *product_name, int speed)
824 FindDeviceState *s = opaque;
825 if ((vendor_id == s->vendor_id &&
826 product_id == s->product_id) ||
827 (bus_num == s->bus_num &&
829 pstrcpy(s->product_name, PRODUCT_NAME_SZ, product_name);
830 s->bus_num = bus_num;
839 'bus.addr' (decimal numbers) or
840 'vendor_id:product_id' (hexa numbers) */
841 static int usb_host_find_device(int *pbus_num, int *paddr,
842 char *product_name, int product_name_size,
849 p = strchr(devname, '.');
851 *pbus_num = strtoul(devname, NULL, 0);
852 *paddr = strtoul(p + 1, NULL, 0);
853 fs.bus_num = *pbus_num;
855 ret = usb_host_scan(&fs, usb_host_find_device_scan);
857 pstrcpy(product_name, product_name_size, fs.product_name);
860 p = strchr(devname, ':');
862 fs.vendor_id = strtoul(devname, NULL, 16);
863 fs.product_id = strtoul(p + 1, NULL, 16);
864 ret = usb_host_scan(&fs, usb_host_find_device_scan);
866 *pbus_num = fs.bus_num;
868 pstrcpy(product_name, product_name_size, fs.product_name);
875 /**********************/
876 /* USB host device info */
878 struct usb_class_info {
880 const char *class_name;
883 static const struct usb_class_info usb_class_info[] = {
884 { USB_CLASS_AUDIO, "Audio"},
885 { USB_CLASS_COMM, "Communication"},
886 { USB_CLASS_HID, "HID"},
887 { USB_CLASS_HUB, "Hub" },
888 { USB_CLASS_PHYSICAL, "Physical" },
889 { USB_CLASS_PRINTER, "Printer" },
890 { USB_CLASS_MASS_STORAGE, "Storage" },
891 { USB_CLASS_CDC_DATA, "Data" },
892 { USB_CLASS_APP_SPEC, "Application Specific" },
893 { USB_CLASS_VENDOR_SPEC, "Vendor Specific" },
894 { USB_CLASS_STILL_IMAGE, "Still Image" },
895 { USB_CLASS_CSCID, "Smart Card" },
896 { USB_CLASS_CONTENT_SEC, "Content Security" },
900 static const char *usb_class_str(uint8_t class)
902 const struct usb_class_info *p;
903 for(p = usb_class_info; p->class != -1; p++) {
904 if (p->class == class)
907 return p->class_name;
910 static void usb_info_device(int bus_num, int addr, int class_id,
911 int vendor_id, int product_id,
912 const char *product_name,
915 const char *class_str, *speed_str;
932 term_printf(" Device %d.%d, speed %s Mb/s\n",
933 bus_num, addr, speed_str);
934 class_str = usb_class_str(class_id);
936 term_printf(" %s:", class_str);
938 term_printf(" Class %02x:", class_id);
939 term_printf(" USB device %04x:%04x", vendor_id, product_id);
940 if (product_name[0] != '\0')
941 term_printf(", %s", product_name);
945 static int usb_host_info_device(void *opaque, int bus_num, int addr,
947 int vendor_id, int product_id,
948 const char *product_name,
951 usb_info_device(bus_num, addr, class_id, vendor_id, product_id,
952 product_name, speed);
956 void usb_host_info(void)
958 usb_host_scan(NULL, usb_host_info_device);
963 void usb_host_info(void)
965 term_printf("USB host devices not supported\n");
968 /* XXX: modify configure to compile the right host driver */
969 USBDevice *usb_host_device_open(const char *devname)