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 {
72 struct endp_data endp_table[MAX_ENDPOINTS];
79 typedef struct PendingURB {
80 struct usbdevfs_urb *urb;
84 struct PendingURB *next;
87 PendingURB *pending_urbs = NULL;
89 int add_pending_urb(struct usbdevfs_urb *urb)
91 PendingURB *purb = qemu_mallocz(sizeof(PendingURB));
97 purb->next = pending_urbs;
104 int del_pending_urb(struct usbdevfs_urb *urb)
106 PendingURB *purb = pending_urbs;
107 PendingURB *prev = NULL;
109 while (purb && purb->urb != urb) {
114 if (purb && purb->urb == urb) {
116 prev->next = purb->next;
118 pending_urbs = purb->next;
126 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) {
140 static int usb_host_update_interfaces(USBHostDevice *dev, int configuration)
142 int dev_descr_len, config_descr_len;
143 int interface, nb_interfaces, nb_configurations;
146 if (configuration == 0) /* address state - ignore */
150 dev_descr_len = dev->descr[0];
151 if (dev_descr_len > dev->descr_len)
153 nb_configurations = dev->descr[17];
156 while (i < dev->descr_len) {
158 printf("i is %d, descr_len is %d, dl %d, dt %d\n", i, dev->descr_len,
159 dev->descr[i], dev->descr[i+1]);
161 if (dev->descr[i+1] != USB_DT_CONFIG) {
165 config_descr_len = dev->descr[i];
167 if (configuration == dev->descr[i + 5])
170 i += config_descr_len;
173 if (i >= dev->descr_len) {
174 printf("usb_host: error - device has no matching configuration\n");
177 nb_interfaces = dev->descr[i + 4];
179 #ifdef USBDEVFS_DISCONNECT
180 /* earlier Linux 2.4 do not support that */
182 struct usbdevfs_ioctl ctrl;
183 for (interface = 0; interface < nb_interfaces; interface++) {
184 ctrl.ioctl_code = USBDEVFS_DISCONNECT;
185 ctrl.ifno = interface;
186 ret = ioctl(dev->fd, USBDEVFS_IOCTL, &ctrl);
187 if (ret < 0 && errno != ENODATA) {
188 perror("USBDEVFS_DISCONNECT");
195 /* XXX: only grab if all interfaces are free */
196 for (interface = 0; interface < nb_interfaces; interface++) {
197 ret = ioctl(dev->fd, USBDEVFS_CLAIMINTERFACE, &interface);
199 if (errno == EBUSY) {
201 "usb_host: warning - device already grabbed\n");
203 perror("USBDEVFS_CLAIMINTERFACE");
211 printf("usb_host: %d interfaces claimed for configuration %d\n",
212 nb_interfaces, configuration);
218 static void usb_host_handle_reset(USBDevice *dev)
221 USBHostDevice *s = (USBHostDevice *)dev;
222 /* USBDEVFS_RESET, but not the first time as it has already be
223 done by the host OS */
224 ioctl(s->fd, USBDEVFS_RESET);
228 static void usb_host_handle_destroy(USBDevice *dev)
230 USBHostDevice *s = (USBHostDevice *)dev;
237 static int usb_linux_update_endp_table(USBHostDevice *s);
239 static int usb_host_handle_control(USBDevice *dev,
246 USBHostDevice *s = (USBHostDevice *)dev;
247 struct usb_ctrltransfer ct;
248 struct usbdevfs_setinterface si;
249 int intf_update_required = 0;
252 if (request == (DeviceOutRequest | USB_REQ_SET_ADDRESS)) {
253 /* specific SET_ADDRESS support */
256 } else if (request == ((USB_RECIP_INTERFACE << 8) |
257 USB_REQ_SET_INTERFACE)) {
258 /* set alternate setting for the interface */
259 si.interface = index;
260 si.altsetting = value;
261 ret = ioctl(s->fd, USBDEVFS_SETINTERFACE, &si);
262 usb_linux_update_endp_table(s);
263 } else if (request == (DeviceOutRequest | USB_REQ_SET_CONFIGURATION)) {
265 printf("usb_host_handle_control: SET_CONFIGURATION request - "
266 "config %d\n", value & 0xff);
268 if (s->configuration != (value & 0xff)) {
269 s->configuration = (value & 0xff);
270 intf_update_required = 1;
275 ct.bRequestType = request >> 8;
276 ct.bRequest = request;
282 ret = ioctl(s->fd, USBDEVFS_CONTROL, &ct);
290 return USB_RET_STALL;
293 if (intf_update_required) {
295 printf("usb_host_handle_control: updating interfaces\n");
297 usb_host_update_interfaces(s, value & 0xff);
303 static int usb_host_handle_isoch(USBDevice *dev, USBPacket *p);
305 static int usb_host_handle_data(USBDevice *dev, USBPacket *p)
307 USBHostDevice *s = (USBHostDevice *)dev;
308 struct usbdevfs_bulktransfer bt;
310 uint8_t devep = p->devep;
312 if (s->endp_table[p->devep - 1].type == USBDEVFS_URB_TYPE_ISO) {
313 return usb_host_handle_isoch(dev, p);
316 /* XXX: optimize and handle all data types by looking at the
318 if (p->pid == USB_TOKEN_IN)
324 ret = ioctl(s->fd, USBDEVFS_BULK, &bt);
332 printf("handle_data: errno=%d\n", errno);
334 return USB_RET_STALL;
341 static void usb_linux_bh_cb(void *opaque);
343 void isoch_done(int signum, siginfo_t *info, void *context) {
344 struct usbdevfs_urb *urb = (struct usbdevfs_urb *)info->si_addr;
345 USBHostDevice *s = (USBHostDevice *)urb->usercontext;
348 if (info->si_code != SI_ASYNCIO ||
349 info->si_signo != SIG_ISOCOMPLETE) {
353 purb = get_pending_urb(urb);
355 purb->bh = qemu_bh_new(usb_linux_bh_cb, purb);
358 purb->status = info->si_errno;
359 qemu_bh_schedule(purb->bh);
364 static int usb_host_handle_isoch(USBDevice *dev, USBPacket *p)
366 USBHostDevice *s = (USBHostDevice *)dev;
367 struct usbdevfs_urb *urb, *purb = NULL;
369 uint8_t devep = p->devep;
371 if (p->pid == USB_TOKEN_IN)
374 urb = qemu_mallocz(sizeof(struct usbdevfs_urb) +
375 sizeof(struct usbdevfs_iso_packet_desc));
377 printf("usb_host_handle_isoch: malloc failed\n");
381 urb->type = USBDEVFS_URB_TYPE_ISO;
382 urb->endpoint = devep;
384 urb->flags = USBDEVFS_URB_ISO_ASAP;
385 urb->buffer = p->data;
386 urb->buffer_length = p->len;
387 urb->actual_length = 0;
388 urb->start_frame = 0;
389 urb->error_count = 0;
391 urb->signr = SIG_ISOCOMPLETE;
395 urb->usercontext = s;
396 urb->number_of_packets = 1;
397 urb->iso_frame_desc[0].length = p->len;
398 urb->iso_frame_desc[0].actual_length = 0;
399 urb->iso_frame_desc[0].status = 0;
400 ret = ioctl(s->fd, USBDEVFS_SUBMITURB, urb);
402 if (!add_pending_urb(urb)) {
403 printf("usb_host_handle_isoch: add_pending_urb failed %p\n", urb);
406 printf("usb_host_handle_isoch: SUBMITURB ioctl=%d errno=%d\n",
414 return USB_RET_STALL;
418 /* FIXME: handle urbs_ready together with sync io
419 * workaround for injecting the signaled urbs into current frame */
420 if (s->urbs_ready > 0) {
421 ret = ioctl(s->fd, USBDEVFS_REAPURBNDELAY, &purb);
423 ret = purb->actual_length;
430 return USB_RET_ASYNC;
432 ret = ioctl(s->fd, USBDEVFS_REAPURBNDELAY, &purb);
434 if (del_pending_urb(purb)) {
435 ret = purb->actual_length;
438 printf("usb_host_handle_isoch: del_pending_urb failed %p\n", purb);
442 printf("usb_host_handle_isoch: REAPURBNDELAY ioctl=%d errno=%d\n",
450 static void usb_linux_bh_cb(void *opaque)
452 PendingURB *pending_urb = (PendingURB *)opaque;
453 USBHostDevice *s = pending_urb->dev;
454 struct usbdevfs_urb *purb = NULL;
455 USBPacket *p = s->packet;
458 /* FIXME: handle purb->status */
459 qemu_free(pending_urb->bh);
460 del_pending_urb(pending_urb->urb);
467 ret = ioctl(s->fd, USBDEVFS_REAPURBNDELAY, &purb);
469 printf("usb_linux_bh_cb: REAPURBNDELAY ioctl=%d errno=%d\n",
475 if (purb == pending_urb->urb) {
476 printf("usb_linux_bh_cb: urb mismatch reaped=%p pending=%p\n",
481 p->len = purb->actual_length;
482 usb_packet_complete(p);
487 /* returns 1 on problem encountered or 0 for success */
488 static int usb_linux_update_endp_table(USBHostDevice *s)
490 uint8_t *descriptors;
491 uint8_t devep, type, configuration, alt_interface;
492 struct usb_ctrltransfer ct;
493 int interface, ret, length, i;
495 ct.bRequestType = USB_DIR_IN;
496 ct.bRequest = USB_REQ_GET_CONFIGURATION;
500 ct.data = &configuration;
503 ret = ioctl(s->fd, USBDEVFS_CONTROL, &ct);
505 perror("usb_linux_update_endp_table");
509 /* in address state */
510 if (configuration == 0)
513 /* get the desired configuration, interface, and endpoint descriptors
514 * from device description */
515 descriptors = &s->descr[18];
516 length = s->descr_len - 18;
519 if (descriptors[i + 1] != USB_DT_CONFIG ||
520 descriptors[i + 5] != configuration) {
521 printf("invalid descriptor data - configuration\n");
527 if (descriptors[i + 1] != USB_DT_INTERFACE ||
528 (descriptors[i + 1] == USB_DT_INTERFACE &&
529 descriptors[i + 4] == 0)) {
534 interface = descriptors[i + 2];
536 ct.bRequestType = USB_DIR_IN | USB_RECIP_INTERFACE;
537 ct.bRequest = USB_REQ_GET_INTERFACE;
539 ct.wIndex = interface;
541 ct.data = &alt_interface;
544 ret = ioctl(s->fd, USBDEVFS_CONTROL, &ct);
546 perror("usb_linux_update_endp_table");
550 /* the current interface descriptor is the active interface
551 * and has endpoints */
552 if (descriptors[i + 3] != alt_interface) {
557 /* advance to the endpoints */
558 while (i < length && descriptors[i +1] != USB_DT_ENDPOINT)
565 if (descriptors[i + 1] != USB_DT_ENDPOINT)
568 devep = descriptors[i + 2];
569 switch (descriptors[i + 3] & 0x3) {
571 type = USBDEVFS_URB_TYPE_CONTROL;
574 type = USBDEVFS_URB_TYPE_ISO;
577 type = USBDEVFS_URB_TYPE_BULK;
580 type = USBDEVFS_URB_TYPE_INTERRUPT;
583 printf("usb_host: malformed endpoint type\n");
584 type = USBDEVFS_URB_TYPE_BULK;
586 s->endp_table[(devep & 0xf) - 1].type = type;
594 /* XXX: exclude high speed devices or implement EHCI */
595 USBDevice *usb_host_device_open(const char *devname)
598 USBHostDevice *dev = NULL;
599 struct usbdevfs_connectinfo ci;
602 char product_name[PRODUCT_NAME_SZ];
604 dev = qemu_mallocz(sizeof(USBHostDevice));
609 printf("usb_host_device_open %s\n", devname);
611 if (usb_host_find_device(&bus_num, &addr,
612 product_name, sizeof(product_name),
616 snprintf(buf, sizeof(buf), USBDEVFS_PATH "/%03d/%03d",
618 fd = open(buf, O_RDWR | O_NONBLOCK);
624 /* read the device description */
625 dev->descr_len = read(fd, dev->descr, sizeof(dev->descr));
626 if (dev->descr_len <= 0) {
627 perror("usb_host_update_interfaces: reading device data failed");
634 printf("=== begin dumping device descriptor data ===\n");
635 for (x = 0; x < dev->descr_len; x++)
636 printf("%02x ", dev->descr[x]);
637 printf("\n=== end dumping device descriptor data ===\n");
642 dev->configuration = 1;
644 /* XXX - do something about initial configuration */
645 if (!usb_host_update_interfaces(dev, 1))
648 ret = ioctl(fd, USBDEVFS_CONNECTINFO, &ci);
650 perror("USBDEVFS_CONNECTINFO");
655 printf("host USB device %d.%d grabbed\n", bus_num, addr);
658 ret = usb_linux_update_endp_table(dev);
663 dev->dev.speed = USB_SPEED_LOW;
665 dev->dev.speed = USB_SPEED_HIGH;
666 dev->dev.handle_packet = usb_generic_handle_packet;
668 dev->dev.handle_reset = usb_host_handle_reset;
669 dev->dev.handle_control = usb_host_handle_control;
670 dev->dev.handle_data = usb_host_handle_data;
671 dev->dev.handle_destroy = usb_host_handle_destroy;
673 if (product_name[0] == '\0')
674 snprintf(dev->dev.devname, sizeof(dev->dev.devname),
677 pstrcpy(dev->dev.devname, sizeof(dev->dev.devname),
681 /* set up the signal handlers */
682 sigemptyset(&sigact.sa_mask);
683 sigact.sa_sigaction = isoch_done;
684 sigact.sa_flags = SA_SIGINFO;
685 sigact.sa_restorer = 0;
686 ret = sigaction(SIG_ISOCOMPLETE, &sigact, NULL);
688 printf("sigaction SIG_ISOCOMPLETE=%d errno=%d\n", ret, errno);
692 return (USBDevice *)dev;
700 static int get_tag_value(char *buf, int buf_size,
701 const char *str, const char *tag,
702 const char *stopchars)
706 p = strstr(str, tag);
713 while (*p != '\0' && !strchr(stopchars, *p)) {
714 if ((q - buf) < (buf_size - 1))
722 static int usb_host_scan(void *opaque, USBScanFunc *func)
727 int bus_num, addr, speed, device_count, class_id, product_id, vendor_id;
729 char product_name[512];
731 f = fopen(USBDEVFS_PATH "/devices", "r");
733 term_printf("Could not open %s\n", USBDEVFS_PATH "/devices");
737 bus_num = addr = speed = class_id = product_id = vendor_id = 0;
740 if (fgets(line, sizeof(line), f) == NULL)
742 if (strlen(line) > 0)
743 line[strlen(line) - 1] = '\0';
744 if (line[0] == 'T' && line[1] == ':') {
745 if (device_count && (vendor_id || product_id)) {
746 /* New device. Add the previously discovered device. */
747 ret = func(opaque, bus_num, addr, class_id, vendor_id,
748 product_id, product_name, speed);
752 if (get_tag_value(buf, sizeof(buf), line, "Bus=", " ") < 0)
755 if (get_tag_value(buf, sizeof(buf), line, "Dev#=", " ") < 0)
758 if (get_tag_value(buf, sizeof(buf), line, "Spd=", " ") < 0)
760 if (!strcmp(buf, "480"))
761 speed = USB_SPEED_HIGH;
762 else if (!strcmp(buf, "1.5"))
763 speed = USB_SPEED_LOW;
765 speed = USB_SPEED_FULL;
766 product_name[0] = '\0';
771 } else if (line[0] == 'P' && line[1] == ':') {
772 if (get_tag_value(buf, sizeof(buf), line, "Vendor=", " ") < 0)
774 vendor_id = strtoul(buf, NULL, 16);
775 if (get_tag_value(buf, sizeof(buf), line, "ProdID=", " ") < 0)
777 product_id = strtoul(buf, NULL, 16);
778 } else if (line[0] == 'S' && line[1] == ':') {
779 if (get_tag_value(buf, sizeof(buf), line, "Product=", "") < 0)
781 pstrcpy(product_name, sizeof(product_name), buf);
782 } else if (line[0] == 'D' && line[1] == ':') {
783 if (get_tag_value(buf, sizeof(buf), line, "Cls=", " (") < 0)
785 class_id = strtoul(buf, NULL, 16);
789 if (device_count && (vendor_id || product_id)) {
790 /* Add the last device. */
791 ret = func(opaque, bus_num, addr, class_id, vendor_id,
792 product_id, product_name, speed);
799 typedef struct FindDeviceState {
804 char product_name[PRODUCT_NAME_SZ];
807 static int usb_host_find_device_scan(void *opaque, int bus_num, int addr,
809 int vendor_id, int product_id,
810 const char *product_name, int speed)
812 FindDeviceState *s = opaque;
813 if ((vendor_id == s->vendor_id &&
814 product_id == s->product_id) ||
815 (bus_num == s->bus_num &&
817 pstrcpy(s->product_name, PRODUCT_NAME_SZ, product_name);
818 s->bus_num = bus_num;
827 'bus.addr' (decimal numbers) or
828 'vendor_id:product_id' (hexa numbers) */
829 static int usb_host_find_device(int *pbus_num, int *paddr,
830 char *product_name, int product_name_size,
837 p = strchr(devname, '.');
839 *pbus_num = strtoul(devname, NULL, 0);
840 *paddr = strtoul(p + 1, NULL, 0);
841 fs.bus_num = *pbus_num;
843 ret = usb_host_scan(&fs, usb_host_find_device_scan);
845 pstrcpy(product_name, product_name_size, fs.product_name);
848 p = strchr(devname, ':');
850 fs.vendor_id = strtoul(devname, NULL, 16);
851 fs.product_id = strtoul(p + 1, NULL, 16);
852 ret = usb_host_scan(&fs, usb_host_find_device_scan);
854 *pbus_num = fs.bus_num;
856 pstrcpy(product_name, product_name_size, fs.product_name);
863 /**********************/
864 /* USB host device info */
866 struct usb_class_info {
868 const char *class_name;
871 static const struct usb_class_info usb_class_info[] = {
872 { USB_CLASS_AUDIO, "Audio"},
873 { USB_CLASS_COMM, "Communication"},
874 { USB_CLASS_HID, "HID"},
875 { USB_CLASS_HUB, "Hub" },
876 { USB_CLASS_PHYSICAL, "Physical" },
877 { USB_CLASS_PRINTER, "Printer" },
878 { USB_CLASS_MASS_STORAGE, "Storage" },
879 { USB_CLASS_CDC_DATA, "Data" },
880 { USB_CLASS_APP_SPEC, "Application Specific" },
881 { USB_CLASS_VENDOR_SPEC, "Vendor Specific" },
882 { USB_CLASS_STILL_IMAGE, "Still Image" },
883 { USB_CLASS_CSCID, "Smart Card" },
884 { USB_CLASS_CONTENT_SEC, "Content Security" },
888 static const char *usb_class_str(uint8_t class)
890 const struct usb_class_info *p;
891 for(p = usb_class_info; p->class != -1; p++) {
892 if (p->class == class)
895 return p->class_name;
898 void usb_info_device(int bus_num, int addr, int class_id,
899 int vendor_id, int product_id,
900 const char *product_name,
903 const char *class_str, *speed_str;
920 term_printf(" Device %d.%d, speed %s Mb/s\n",
921 bus_num, addr, speed_str);
922 class_str = usb_class_str(class_id);
924 term_printf(" %s:", class_str);
926 term_printf(" Class %02x:", class_id);
927 term_printf(" USB device %04x:%04x", vendor_id, product_id);
928 if (product_name[0] != '\0')
929 term_printf(", %s", product_name);
933 static int usb_host_info_device(void *opaque, int bus_num, int addr,
935 int vendor_id, int product_id,
936 const char *product_name,
939 usb_info_device(bus_num, addr, class_id, vendor_id, product_id,
940 product_name, speed);
944 void usb_host_info(void)
946 usb_host_scan(NULL, usb_host_info_device);
951 void usb_host_info(void)
953 term_printf("USB host devices not supported\n");
956 /* XXX: modify configure to compile the right host driver */
957 USBDevice *usb_host_device_open(const char *devname)