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
26 #if defined(__linux__)
28 #include <sys/ioctl.h>
29 #include <linux/usbdevice_fs.h>
30 #include <linux/version.h>
33 /* We redefine it to avoid version problems */
34 struct usb_ctrltransfer {
44 typedef int USBScanFunc(void *opaque, int bus_num, int addr, int class_id,
45 int vendor_id, int product_id,
46 const char *product_name, int speed);
47 static int usb_host_find_device(int *pbus_num, int *paddr,
48 char *product_name, int product_name_size,
55 #define USBDEVFS_PATH "/proc/bus/usb"
56 #define PRODUCT_NAME_SZ 32
57 #define SIG_ISOCOMPLETE (SIGRTMIN+7)
58 #define MAX_ENDPOINTS 16
60 struct sigaction sigact;
62 /* endpoint association data */
67 /* FIXME: move USBPacket to PendingURB */
68 typedef struct USBHostDevice {
73 struct endp_data endp_table[MAX_ENDPOINTS];
80 typedef struct PendingURB {
81 struct usbdevfs_urb *urb;
83 struct PendingURB *next;
86 static PendingURB *pending_urbs = NULL;
88 static int add_pending_urb(struct usbdevfs_urb *urb)
90 PendingURB *purb = qemu_mallocz(sizeof(PendingURB));
94 purb->next = pending_urbs;
101 static int del_pending_urb(struct usbdevfs_urb *urb)
103 PendingURB *purb = pending_urbs;
104 PendingURB *prev = NULL;
106 while (purb && purb->urb != urb) {
111 if (purb && purb->urb == urb) {
113 prev->next = purb->next;
115 pending_urbs = purb->next;
124 static PendingURB *get_pending_urb(struct usbdevfs_urb *urb)
126 PendingURB *purb = pending_urbs;
128 while (purb && purb->urb != urb) {
132 if (purb && purb->urb == urb) {
139 static int usb_host_update_interfaces(USBHostDevice *dev, int configuration)
141 int dev_descr_len, config_descr_len;
142 int interface, nb_interfaces, nb_configurations;
145 if (configuration == 0) /* address state - ignore */
149 dev_descr_len = dev->descr[0];
150 if (dev_descr_len > dev->descr_len)
152 nb_configurations = dev->descr[17];
155 while (i < dev->descr_len) {
157 printf("i is %d, descr_len is %d, dl %d, dt %d\n", i, dev->descr_len,
158 dev->descr[i], dev->descr[i+1]);
160 if (dev->descr[i+1] != USB_DT_CONFIG) {
164 config_descr_len = dev->descr[i];
166 if (configuration == dev->descr[i + 5])
169 i += config_descr_len;
172 if (i >= dev->descr_len) {
173 printf("usb_host: error - device has no matching configuration\n");
176 nb_interfaces = dev->descr[i + 4];
178 #ifdef USBDEVFS_DISCONNECT
179 /* earlier Linux 2.4 do not support that */
181 struct usbdevfs_ioctl ctrl;
182 for (interface = 0; interface < nb_interfaces; interface++) {
183 ctrl.ioctl_code = USBDEVFS_DISCONNECT;
184 ctrl.ifno = interface;
185 ret = ioctl(dev->fd, USBDEVFS_IOCTL, &ctrl);
186 if (ret < 0 && errno != ENODATA) {
187 perror("USBDEVFS_DISCONNECT");
194 /* XXX: only grab if all interfaces are free */
195 for (interface = 0; interface < nb_interfaces; interface++) {
196 ret = ioctl(dev->fd, USBDEVFS_CLAIMINTERFACE, &interface);
198 if (errno == EBUSY) {
200 "usb_host: warning - device already grabbed\n");
202 perror("USBDEVFS_CLAIMINTERFACE");
210 printf("usb_host: %d interfaces claimed for configuration %d\n",
211 nb_interfaces, configuration);
217 static void usb_host_handle_reset(USBDevice *dev)
220 USBHostDevice *s = (USBHostDevice *)dev;
221 /* USBDEVFS_RESET, but not the first time as it has already be
222 done by the host OS */
223 ioctl(s->fd, USBDEVFS_RESET);
227 static void usb_host_handle_destroy(USBDevice *dev)
229 USBHostDevice *s = (USBHostDevice *)dev;
236 static int usb_linux_update_endp_table(USBHostDevice *s);
238 static int usb_host_handle_control(USBDevice *dev,
245 USBHostDevice *s = (USBHostDevice *)dev;
246 struct usb_ctrltransfer ct;
247 struct usbdevfs_setinterface si;
248 int intf_update_required = 0;
251 if (request == (DeviceOutRequest | USB_REQ_SET_ADDRESS)) {
252 /* specific SET_ADDRESS support */
255 } else if (request == ((USB_RECIP_INTERFACE << 8) |
256 USB_REQ_SET_INTERFACE)) {
257 /* set alternate setting for the interface */
258 si.interface = index;
259 si.altsetting = value;
260 ret = ioctl(s->fd, USBDEVFS_SETINTERFACE, &si);
261 usb_linux_update_endp_table(s);
262 } else if (request == (DeviceOutRequest | USB_REQ_SET_CONFIGURATION)) {
264 printf("usb_host_handle_control: SET_CONFIGURATION request - "
265 "config %d\n", value & 0xff);
267 if (s->configuration != (value & 0xff)) {
268 s->configuration = (value & 0xff);
269 intf_update_required = 1;
274 ct.bRequestType = request >> 8;
275 ct.bRequest = request;
281 ret = ioctl(s->fd, USBDEVFS_CONTROL, &ct);
289 return USB_RET_STALL;
292 if (intf_update_required) {
294 printf("usb_host_handle_control: updating interfaces\n");
296 usb_host_update_interfaces(s, value & 0xff);
302 static int usb_host_handle_isoch(USBDevice *dev, USBPacket *p);
304 static int usb_host_handle_data(USBDevice *dev, USBPacket *p)
306 USBHostDevice *s = (USBHostDevice *)dev;
307 struct usbdevfs_bulktransfer bt;
309 uint8_t devep = p->devep;
311 if (s->endp_table[p->devep - 1].type == USBDEVFS_URB_TYPE_ISO) {
312 return usb_host_handle_isoch(dev, p);
315 /* XXX: optimize and handle all data types by looking at the
317 if (p->pid == USB_TOKEN_IN)
323 ret = ioctl(s->fd, USBDEVFS_BULK, &bt);
331 printf("handle_data: errno=%d\n", errno);
333 return USB_RET_STALL;
341 static void urb_completion_pipe_read(void *opaque)
343 USBHostDevice *s = opaque;
344 USBPacket *p = s->packet;
345 PendingURB *pending_urb = NULL;
346 struct usbdevfs_urb *purb = NULL;
349 len = read(s->pipe_fds[0], &pending_urb, sizeof(pending_urb));
350 if (len != sizeof(pending_urb)) {
351 printf("urb_completion: error reading pending_urb, len=%d\n", len);
355 /* FIXME: handle pending_urb->status */
356 del_pending_urb(pending_urb->urb);
363 ret = ioctl(s->fd, USBDEVFS_REAPURBNDELAY, &purb);
365 printf("urb_completion: REAPURBNDELAY ioctl=%d errno=%d\n",
371 if (purb == pending_urb->urb) {
372 printf("urb_completion: urb mismatch reaped=%p pending=%p\n",
377 p->len = purb->actual_length;
378 usb_packet_complete(p);
383 static void isoch_done(int signum, siginfo_t *info, void *context)
385 struct usbdevfs_urb *urb = (struct usbdevfs_urb *)info->si_addr;
386 USBHostDevice *s = (USBHostDevice *)urb->usercontext;
389 if (info->si_code != SI_ASYNCIO ||
390 info->si_signo != SIG_ISOCOMPLETE) {
394 purb = get_pending_urb(urb);
396 purb->status = info->si_errno;
397 write(s->pipe_fds[1], &purb, sizeof(purb));
402 static int usb_host_handle_isoch(USBDevice *dev, USBPacket *p)
404 USBHostDevice *s = (USBHostDevice *)dev;
405 struct usbdevfs_urb *urb, *purb = NULL;
407 uint8_t devep = p->devep;
409 if (p->pid == USB_TOKEN_IN)
412 urb = qemu_mallocz(sizeof(struct usbdevfs_urb) +
413 sizeof(struct usbdevfs_iso_packet_desc));
415 printf("usb_host_handle_isoch: malloc failed\n");
419 urb->type = USBDEVFS_URB_TYPE_ISO;
420 urb->endpoint = devep;
422 urb->flags = USBDEVFS_URB_ISO_ASAP;
423 urb->buffer = p->data;
424 urb->buffer_length = p->len;
425 urb->actual_length = 0;
426 urb->start_frame = 0;
427 urb->error_count = 0;
429 urb->signr = SIG_ISOCOMPLETE;
433 urb->usercontext = s;
434 urb->number_of_packets = 1;
435 urb->iso_frame_desc[0].length = p->len;
436 urb->iso_frame_desc[0].actual_length = 0;
437 urb->iso_frame_desc[0].status = 0;
438 ret = ioctl(s->fd, USBDEVFS_SUBMITURB, urb);
440 if (!add_pending_urb(urb)) {
441 printf("usb_host_handle_isoch: add_pending_urb failed %p\n", urb);
444 printf("usb_host_handle_isoch: SUBMITURB ioctl=%d errno=%d\n",
452 return USB_RET_STALL;
456 /* FIXME: handle urbs_ready together with sync io
457 * workaround for injecting the signaled urbs into current frame */
458 if (s->urbs_ready > 0) {
459 ret = ioctl(s->fd, USBDEVFS_REAPURBNDELAY, &purb);
461 ret = purb->actual_length;
468 return USB_RET_ASYNC;
470 ret = ioctl(s->fd, USBDEVFS_REAPURBNDELAY, &purb);
472 if (del_pending_urb(purb)) {
473 ret = purb->actual_length;
476 printf("usb_host_handle_isoch: del_pending_urb failed %p\n", purb);
480 printf("usb_host_handle_isoch: REAPURBNDELAY ioctl=%d errno=%d\n",
488 /* returns 1 on problem encountered or 0 for success */
489 static int usb_linux_update_endp_table(USBHostDevice *s)
491 uint8_t *descriptors;
492 uint8_t devep, type, configuration, alt_interface;
493 struct usb_ctrltransfer ct;
494 int interface, ret, length, i;
496 ct.bRequestType = USB_DIR_IN;
497 ct.bRequest = USB_REQ_GET_CONFIGURATION;
501 ct.data = &configuration;
504 ret = ioctl(s->fd, USBDEVFS_CONTROL, &ct);
506 perror("usb_linux_update_endp_table");
510 /* in address state */
511 if (configuration == 0)
514 /* get the desired configuration, interface, and endpoint descriptors
515 * from device description */
516 descriptors = &s->descr[18];
517 length = s->descr_len - 18;
520 if (descriptors[i + 1] != USB_DT_CONFIG ||
521 descriptors[i + 5] != configuration) {
522 printf("invalid descriptor data - configuration\n");
528 if (descriptors[i + 1] != USB_DT_INTERFACE ||
529 (descriptors[i + 1] == USB_DT_INTERFACE &&
530 descriptors[i + 4] == 0)) {
535 interface = descriptors[i + 2];
537 ct.bRequestType = USB_DIR_IN | USB_RECIP_INTERFACE;
538 ct.bRequest = USB_REQ_GET_INTERFACE;
540 ct.wIndex = interface;
542 ct.data = &alt_interface;
545 ret = ioctl(s->fd, USBDEVFS_CONTROL, &ct);
547 perror("usb_linux_update_endp_table");
551 /* the current interface descriptor is the active interface
552 * and has endpoints */
553 if (descriptors[i + 3] != alt_interface) {
558 /* advance to the endpoints */
559 while (i < length && descriptors[i +1] != USB_DT_ENDPOINT)
566 if (descriptors[i + 1] != USB_DT_ENDPOINT)
569 devep = descriptors[i + 2];
570 switch (descriptors[i + 3] & 0x3) {
572 type = USBDEVFS_URB_TYPE_CONTROL;
575 type = USBDEVFS_URB_TYPE_ISO;
578 type = USBDEVFS_URB_TYPE_BULK;
581 type = USBDEVFS_URB_TYPE_INTERRUPT;
584 printf("usb_host: malformed endpoint type\n");
585 type = USBDEVFS_URB_TYPE_BULK;
587 s->endp_table[(devep & 0xf) - 1].type = type;
595 /* XXX: exclude high speed devices or implement EHCI */
596 USBDevice *usb_host_device_open(const char *devname)
599 USBHostDevice *dev = NULL;
600 struct usbdevfs_connectinfo ci;
603 char product_name[PRODUCT_NAME_SZ];
605 dev = qemu_mallocz(sizeof(USBHostDevice));
610 printf("usb_host_device_open %s\n", devname);
612 if (usb_host_find_device(&bus_num, &addr,
613 product_name, sizeof(product_name),
617 snprintf(buf, sizeof(buf), USBDEVFS_PATH "/%03d/%03d",
619 fd = open(buf, O_RDWR | O_NONBLOCK);
625 /* read the device description */
626 dev->descr_len = read(fd, dev->descr, sizeof(dev->descr));
627 if (dev->descr_len <= 0) {
628 perror("usb_host_device_open: reading device data failed");
635 printf("=== begin dumping device descriptor data ===\n");
636 for (x = 0; x < dev->descr_len; x++)
637 printf("%02x ", dev->descr[x]);
638 printf("\n=== end dumping device descriptor data ===\n");
643 dev->configuration = 1;
645 /* XXX - do something about initial configuration */
646 if (!usb_host_update_interfaces(dev, 1))
649 ret = ioctl(fd, USBDEVFS_CONNECTINFO, &ci);
651 perror("usb_host_device_open: USBDEVFS_CONNECTINFO");
656 printf("host USB device %d.%d grabbed\n", bus_num, addr);
659 ret = usb_linux_update_endp_table(dev);
664 dev->dev.speed = USB_SPEED_LOW;
666 dev->dev.speed = USB_SPEED_HIGH;
667 dev->dev.handle_packet = usb_generic_handle_packet;
669 dev->dev.handle_reset = usb_host_handle_reset;
670 dev->dev.handle_control = usb_host_handle_control;
671 dev->dev.handle_data = usb_host_handle_data;
672 dev->dev.handle_destroy = usb_host_handle_destroy;
674 if (product_name[0] == '\0')
675 snprintf(dev->dev.devname, sizeof(dev->dev.devname),
678 pstrcpy(dev->dev.devname, sizeof(dev->dev.devname),
682 /* set up the signal handlers */
683 sigemptyset(&sigact.sa_mask);
684 sigact.sa_sigaction = isoch_done;
685 sigact.sa_flags = SA_SIGINFO;
686 sigact.sa_restorer = 0;
687 ret = sigaction(SIG_ISOCOMPLETE, &sigact, NULL);
689 perror("usb_host_device_open: sigaction failed");
693 if (pipe(dev->pipe_fds) < 0) {
694 perror("usb_host_device_open: pipe creation failed");
697 fcntl(dev->pipe_fds[0], F_SETFL, O_NONBLOCK | O_ASYNC);
698 fcntl(dev->pipe_fds[1], F_SETFL, O_NONBLOCK);
699 qemu_set_fd_handler(dev->pipe_fds[0], urb_completion_pipe_read, NULL, dev);
702 return (USBDevice *)dev;
710 static int get_tag_value(char *buf, int buf_size,
711 const char *str, const char *tag,
712 const char *stopchars)
716 p = strstr(str, tag);
723 while (*p != '\0' && !strchr(stopchars, *p)) {
724 if ((q - buf) < (buf_size - 1))
732 static int usb_host_scan(void *opaque, USBScanFunc *func)
737 int bus_num, addr, speed, device_count, class_id, product_id, vendor_id;
739 char product_name[512];
741 f = fopen(USBDEVFS_PATH "/devices", "r");
743 term_printf("Could not open %s\n", USBDEVFS_PATH "/devices");
747 bus_num = addr = speed = class_id = product_id = vendor_id = 0;
750 if (fgets(line, sizeof(line), f) == NULL)
752 if (strlen(line) > 0)
753 line[strlen(line) - 1] = '\0';
754 if (line[0] == 'T' && line[1] == ':') {
755 if (device_count && (vendor_id || product_id)) {
756 /* New device. Add the previously discovered device. */
757 ret = func(opaque, bus_num, addr, class_id, vendor_id,
758 product_id, product_name, speed);
762 if (get_tag_value(buf, sizeof(buf), line, "Bus=", " ") < 0)
765 if (get_tag_value(buf, sizeof(buf), line, "Dev#=", " ") < 0)
768 if (get_tag_value(buf, sizeof(buf), line, "Spd=", " ") < 0)
770 if (!strcmp(buf, "480"))
771 speed = USB_SPEED_HIGH;
772 else if (!strcmp(buf, "1.5"))
773 speed = USB_SPEED_LOW;
775 speed = USB_SPEED_FULL;
776 product_name[0] = '\0';
781 } else if (line[0] == 'P' && line[1] == ':') {
782 if (get_tag_value(buf, sizeof(buf), line, "Vendor=", " ") < 0)
784 vendor_id = strtoul(buf, NULL, 16);
785 if (get_tag_value(buf, sizeof(buf), line, "ProdID=", " ") < 0)
787 product_id = strtoul(buf, NULL, 16);
788 } else if (line[0] == 'S' && line[1] == ':') {
789 if (get_tag_value(buf, sizeof(buf), line, "Product=", "") < 0)
791 pstrcpy(product_name, sizeof(product_name), buf);
792 } else if (line[0] == 'D' && line[1] == ':') {
793 if (get_tag_value(buf, sizeof(buf), line, "Cls=", " (") < 0)
795 class_id = strtoul(buf, NULL, 16);
799 if (device_count && (vendor_id || product_id)) {
800 /* Add the last device. */
801 ret = func(opaque, bus_num, addr, class_id, vendor_id,
802 product_id, product_name, speed);
809 typedef struct FindDeviceState {
814 char product_name[PRODUCT_NAME_SZ];
817 static int usb_host_find_device_scan(void *opaque, int bus_num, int addr,
819 int vendor_id, int product_id,
820 const char *product_name, int speed)
822 FindDeviceState *s = opaque;
823 if ((vendor_id == s->vendor_id &&
824 product_id == s->product_id) ||
825 (bus_num == s->bus_num &&
827 pstrcpy(s->product_name, PRODUCT_NAME_SZ, product_name);
828 s->bus_num = bus_num;
837 'bus.addr' (decimal numbers) or
838 'vendor_id:product_id' (hexa numbers) */
839 static int usb_host_find_device(int *pbus_num, int *paddr,
840 char *product_name, int product_name_size,
847 p = strchr(devname, '.');
849 *pbus_num = strtoul(devname, NULL, 0);
850 *paddr = strtoul(p + 1, NULL, 0);
851 fs.bus_num = *pbus_num;
853 ret = usb_host_scan(&fs, usb_host_find_device_scan);
855 pstrcpy(product_name, product_name_size, fs.product_name);
858 p = strchr(devname, ':');
860 fs.vendor_id = strtoul(devname, NULL, 16);
861 fs.product_id = strtoul(p + 1, NULL, 16);
862 ret = usb_host_scan(&fs, usb_host_find_device_scan);
864 *pbus_num = fs.bus_num;
866 pstrcpy(product_name, product_name_size, fs.product_name);
873 /**********************/
874 /* USB host device info */
876 struct usb_class_info {
878 const char *class_name;
881 static const struct usb_class_info usb_class_info[] = {
882 { USB_CLASS_AUDIO, "Audio"},
883 { USB_CLASS_COMM, "Communication"},
884 { USB_CLASS_HID, "HID"},
885 { USB_CLASS_HUB, "Hub" },
886 { USB_CLASS_PHYSICAL, "Physical" },
887 { USB_CLASS_PRINTER, "Printer" },
888 { USB_CLASS_MASS_STORAGE, "Storage" },
889 { USB_CLASS_CDC_DATA, "Data" },
890 { USB_CLASS_APP_SPEC, "Application Specific" },
891 { USB_CLASS_VENDOR_SPEC, "Vendor Specific" },
892 { USB_CLASS_STILL_IMAGE, "Still Image" },
893 { USB_CLASS_CSCID, "Smart Card" },
894 { USB_CLASS_CONTENT_SEC, "Content Security" },
898 static const char *usb_class_str(uint8_t class)
900 const struct usb_class_info *p;
901 for(p = usb_class_info; p->class != -1; p++) {
902 if (p->class == class)
905 return p->class_name;
908 void usb_info_device(int bus_num, int addr, int class_id,
909 int vendor_id, int product_id,
910 const char *product_name,
913 const char *class_str, *speed_str;
930 term_printf(" Device %d.%d, speed %s Mb/s\n",
931 bus_num, addr, speed_str);
932 class_str = usb_class_str(class_id);
934 term_printf(" %s:", class_str);
936 term_printf(" Class %02x:", class_id);
937 term_printf(" USB device %04x:%04x", vendor_id, product_id);
938 if (product_name[0] != '\0')
939 term_printf(", %s", product_name);
943 static int usb_host_info_device(void *opaque, int bus_num, int addr,
945 int vendor_id, int product_id,
946 const char *product_name,
949 usb_info_device(bus_num, addr, class_id, vendor_id, product_id,
950 product_name, speed);
954 void usb_host_info(void)
956 usb_host_scan(NULL, usb_host_info_device);
961 void usb_host_info(void)
963 term_printf("USB host devices not supported\n");
966 /* XXX: modify configure to compile the right host driver */
967 USBDevice *usb_host_device_open(const char *devname)