Merge branch 'qemu-cvs'
[kvm-userspace.git] / qemu / usb-linux.c
blob3968f9a01357f82910f2a39291a33b104610573a
1 /*
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
10 * Permission is hereby granted, free of charge, to any person obtaining a copy
11 * of this software and associated documentation files (the "Software"), to deal
12 * in the Software without restriction, including without limitation the rights
13 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
14 * copies of the Software, and to permit persons to whom the Software is
15 * furnished to do so, subject to the following conditions:
17 * The above copyright notice and this permission notice shall be included in
18 * all copies or substantial portions of the Software.
20 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
21 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
22 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
23 * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
24 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
25 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
26 * THE SOFTWARE.
29 #include "qemu-common.h"
30 #include "qemu-timer.h"
31 #include "console.h"
33 #if defined(__linux__)
34 #define __user
36 #include <dirent.h>
37 #include <sys/ioctl.h>
38 #include <signal.h>
40 #include <linux/usbdevice_fs.h>
41 #include <linux/version.h>
42 #include "hw/usb.h"
44 /* We redefine it to avoid version problems */
45 struct usb_ctrltransfer {
46 uint8_t bRequestType;
47 uint8_t bRequest;
48 uint16_t wValue;
49 uint16_t wIndex;
50 uint16_t wLength;
51 uint32_t timeout;
52 void *data;
55 struct usb_ctrlrequest {
56 uint8_t bRequestType;
57 uint8_t bRequest;
58 uint16_t wValue;
59 uint16_t wIndex;
60 uint16_t wLength;
63 typedef int USBScanFunc(void *opaque, int bus_num, int addr, int class_id,
64 int vendor_id, int product_id,
65 const char *product_name, int speed);
66 static int usb_host_find_device(int *pbus_num, int *paddr,
67 char *product_name, int product_name_size,
68 const char *devname);
69 //#define DEBUG
71 #ifdef DEBUG
72 #define dprintf printf
73 #else
74 #define dprintf(...)
75 #endif
77 #define USBDEVFS_PATH "/proc/bus/usb"
78 #define PRODUCT_NAME_SZ 32
79 #define MAX_ENDPOINTS 16
81 /* endpoint association data */
82 struct endp_data {
83 uint8_t type;
84 uint8_t halted;
87 enum {
88 CTRL_STATE_IDLE = 0,
89 CTRL_STATE_SETUP,
90 CTRL_STATE_DATA,
91 CTRL_STATE_ACK
95 * Control transfer state.
96 * Note that 'buffer' _must_ follow 'req' field because
97 * we need contigious buffer when we submit control URB.
98 */
99 struct ctrl_struct {
100 uint16_t len;
101 uint16_t offset;
102 uint8_t state;
103 struct usb_ctrlrequest req;
104 uint8_t buffer[1024];
107 typedef struct USBHostDevice {
108 USBDevice dev;
109 int fd;
111 uint8_t descr[1024];
112 int descr_len;
113 int configuration;
114 int ninterfaces;
115 int closing;
117 struct ctrl_struct ctrl;
118 struct endp_data endp_table[MAX_ENDPOINTS];
120 /* Host side address */
121 int bus_num;
122 int addr;
124 struct USBHostDevice *next;
125 } USBHostDevice;
127 static int is_isoc(USBHostDevice *s, int ep)
129 return s->endp_table[ep - 1].type == USBDEVFS_URB_TYPE_ISO;
132 static int is_halted(USBHostDevice *s, int ep)
134 return s->endp_table[ep - 1].halted;
137 static void clear_halt(USBHostDevice *s, int ep)
139 s->endp_table[ep - 1].halted = 0;
142 static void set_halt(USBHostDevice *s, int ep)
144 s->endp_table[ep - 1].halted = 1;
147 static USBHostDevice *hostdev_list;
149 static void hostdev_link(USBHostDevice *dev)
151 dev->next = hostdev_list;
152 hostdev_list = dev;
155 static void hostdev_unlink(USBHostDevice *dev)
157 USBHostDevice *pdev = hostdev_list;
158 USBHostDevice **prev = &hostdev_list;
160 while (pdev) {
161 if (pdev == dev) {
162 *prev = dev->next;
163 return;
166 prev = &pdev->next;
167 pdev = pdev->next;
171 static USBHostDevice *hostdev_find(int bus_num, int addr)
173 USBHostDevice *s = hostdev_list;
174 while (s) {
175 if (s->bus_num == bus_num && s->addr == addr)
176 return s;
177 s = s->next;
179 return NULL;
183 * Async URB state.
184 * We always allocate one isoc descriptor even for bulk transfers
185 * to simplify allocation and casts.
187 typedef struct AsyncURB
189 struct usbdevfs_urb urb;
190 struct usbdevfs_iso_packet_desc isocpd;
192 USBPacket *packet;
193 USBHostDevice *hdev;
194 } AsyncURB;
196 static AsyncURB *async_alloc(void)
198 return (AsyncURB *) qemu_mallocz(sizeof(AsyncURB));
201 static void async_free(AsyncURB *aurb)
203 qemu_free(aurb);
206 static void async_complete_ctrl(USBHostDevice *s, USBPacket *p)
208 switch(s->ctrl.state) {
209 case CTRL_STATE_SETUP:
210 if (p->len < s->ctrl.len)
211 s->ctrl.len = p->len;
212 s->ctrl.state = CTRL_STATE_DATA;
213 p->len = 8;
214 break;
216 case CTRL_STATE_ACK:
217 s->ctrl.state = CTRL_STATE_IDLE;
218 p->len = 0;
219 break;
221 default:
222 break;
226 static void async_complete(void *opaque)
228 USBHostDevice *s = opaque;
229 AsyncURB *aurb;
231 while (1) {
232 USBPacket *p;
234 int r = ioctl(s->fd, USBDEVFS_REAPURBNDELAY, &aurb);
235 if (r < 0) {
236 if (errno == EAGAIN)
237 return;
239 if (errno == ENODEV && !s->closing) {
240 printf("husb: device %d.%d disconnected\n", s->bus_num, s->addr);
241 usb_device_del_addr(0, s->dev.addr);
242 return;
245 dprintf("husb: async. reap urb failed errno %d\n", errno);
246 return;
249 p = aurb->packet;
251 dprintf("husb: async completed. aurb %p status %d alen %d\n",
252 aurb, aurb->urb.status, aurb->urb.actual_length);
254 if (p) {
255 switch (aurb->urb.status) {
256 case 0:
257 p->len = aurb->urb.actual_length;
258 if (aurb->urb.type == USBDEVFS_URB_TYPE_CONTROL)
259 async_complete_ctrl(s, p);
260 break;
262 case -EPIPE:
263 set_halt(s, p->devep);
264 /* fall through */
265 default:
266 p->len = USB_RET_NAK;
267 break;
270 usb_packet_complete(p);
273 async_free(aurb);
277 static void async_cancel(USBPacket *unused, void *opaque)
279 AsyncURB *aurb = opaque;
280 USBHostDevice *s = aurb->hdev;
282 dprintf("husb: async cancel. aurb %p\n", aurb);
284 /* Mark it as dead (see async_complete above) */
285 aurb->packet = NULL;
287 int r = ioctl(s->fd, USBDEVFS_DISCARDURB, aurb);
288 if (r < 0) {
289 dprintf("husb: async. discard urb failed errno %d\n", errno);
293 static int usb_host_claim_interfaces(USBHostDevice *dev, int configuration)
295 int dev_descr_len, config_descr_len;
296 int interface, nb_interfaces, nb_configurations;
297 int ret, i;
299 if (configuration == 0) /* address state - ignore */
300 return 1;
302 dprintf("husb: claiming interfaces. config %d\n", configuration);
304 i = 0;
305 dev_descr_len = dev->descr[0];
306 if (dev_descr_len > dev->descr_len)
307 goto fail;
308 nb_configurations = dev->descr[17];
310 i += dev_descr_len;
311 while (i < dev->descr_len) {
312 dprintf("husb: i is %d, descr_len is %d, dl %d, dt %d\n", i, dev->descr_len,
313 dev->descr[i], dev->descr[i+1]);
315 if (dev->descr[i+1] != USB_DT_CONFIG) {
316 i += dev->descr[i];
317 continue;
319 config_descr_len = dev->descr[i];
321 printf("husb: config #%d need %d\n", dev->descr[i + 5], configuration);
323 if (configuration < 0 || configuration == dev->descr[i + 5]) {
324 configuration = dev->descr[i + 5];
325 break;
328 i += config_descr_len;
331 if (i >= dev->descr_len) {
332 fprintf(stderr, "husb: update iface failed. no matching configuration\n");
333 goto fail;
335 nb_interfaces = dev->descr[i + 4];
337 #ifdef USBDEVFS_DISCONNECT
338 /* earlier Linux 2.4 do not support that */
340 struct usbdevfs_ioctl ctrl;
341 for (interface = 0; interface < nb_interfaces; interface++) {
342 ctrl.ioctl_code = USBDEVFS_DISCONNECT;
343 ctrl.ifno = interface;
344 ret = ioctl(dev->fd, USBDEVFS_IOCTL, &ctrl);
345 if (ret < 0 && errno != ENODATA) {
346 perror("USBDEVFS_DISCONNECT");
347 goto fail;
351 #endif
353 /* XXX: only grab if all interfaces are free */
354 for (interface = 0; interface < nb_interfaces; interface++) {
355 ret = ioctl(dev->fd, USBDEVFS_CLAIMINTERFACE, &interface);
356 if (ret < 0) {
357 if (errno == EBUSY) {
358 printf("husb: update iface. device already grabbed\n");
359 } else {
360 perror("husb: failed to claim interface");
362 fail:
363 return 0;
367 printf("husb: %d interfaces claimed for configuration %d\n",
368 nb_interfaces, configuration);
370 dev->ninterfaces = nb_interfaces;
371 dev->configuration = configuration;
372 return 1;
375 static int usb_host_release_interfaces(USBHostDevice *s)
377 int ret, i;
379 dprintf("husb: releasing interfaces\n");
381 for (i = 0; i < s->ninterfaces; i++) {
382 ret = ioctl(s->fd, USBDEVFS_RELEASEINTERFACE, &i);
383 if (ret < 0) {
384 perror("husb: failed to release interface");
385 return 0;
389 return 1;
392 static void usb_host_handle_reset(USBDevice *dev)
394 USBHostDevice *s = (USBHostDevice *) dev;
396 dprintf("husb: reset device %u.%u\n", s->bus_num, s->addr);
398 ioctl(s->fd, USBDEVFS_RESET);
400 usb_host_claim_interfaces(s, s->configuration);
403 static void usb_host_handle_destroy(USBDevice *dev)
405 USBHostDevice *s = (USBHostDevice *)dev;
407 s->closing = 1;
409 qemu_set_fd_handler(s->fd, NULL, NULL, NULL);
411 hostdev_unlink(s);
413 async_complete(s);
415 if (s->fd >= 0)
416 close(s->fd);
418 qemu_free(s);
421 static int usb_linux_update_endp_table(USBHostDevice *s);
423 static int usb_host_handle_data(USBHostDevice *s, USBPacket *p)
425 struct usbdevfs_urb *urb;
426 AsyncURB *aurb;
427 int ret;
429 aurb = async_alloc();
430 if (!aurb) {
431 dprintf("husb: async malloc failed\n");
432 return USB_RET_NAK;
434 aurb->hdev = s;
435 aurb->packet = p;
437 urb = &aurb->urb;
439 if (p->pid == USB_TOKEN_IN)
440 urb->endpoint = p->devep | 0x80;
441 else
442 urb->endpoint = p->devep;
444 if (is_halted(s, p->devep)) {
445 ret = ioctl(s->fd, USBDEVFS_CLEAR_HALT, &urb->endpoint);
446 if (ret < 0) {
447 dprintf("husb: failed to clear halt. ep 0x%x errno %d\n",
448 urb->endpoint, errno);
449 return USB_RET_NAK;
451 clear_halt(s, p->devep);
454 urb->buffer = p->data;
455 urb->buffer_length = p->len;
457 if (is_isoc(s, p->devep)) {
458 /* Setup ISOC transfer */
459 urb->type = USBDEVFS_URB_TYPE_ISO;
460 urb->flags = USBDEVFS_URB_ISO_ASAP;
461 urb->number_of_packets = 1;
462 urb->iso_frame_desc[0].length = p->len;
463 } else {
464 /* Setup bulk transfer */
465 urb->type = USBDEVFS_URB_TYPE_BULK;
468 urb->usercontext = s;
470 ret = ioctl(s->fd, USBDEVFS_SUBMITURB, urb);
472 dprintf("husb: data submit. ep 0x%x len %u aurb %p\n", urb->endpoint, p->len, aurb);
474 if (ret < 0) {
475 dprintf("husb: submit failed. errno %d\n", errno);
476 async_free(aurb);
478 switch(errno) {
479 case ETIMEDOUT:
480 return USB_RET_NAK;
481 case EPIPE:
482 default:
483 return USB_RET_STALL;
487 usb_defer_packet(p, async_cancel, aurb);
488 return USB_RET_ASYNC;
491 static int ctrl_error(void)
493 if (errno == ETIMEDOUT)
494 return USB_RET_NAK;
495 else
496 return USB_RET_STALL;
499 static int usb_host_set_address(USBHostDevice *s, int addr)
501 dprintf("husb: ctrl set addr %u\n", addr);
502 s->dev.addr = addr;
503 return 0;
506 static int usb_host_set_config(USBHostDevice *s, int config)
508 usb_host_release_interfaces(s);
510 int ret = ioctl(s->fd, USBDEVFS_SETCONFIGURATION, &config);
512 dprintf("husb: ctrl set config %d ret %d errno %d\n", config, ret, errno);
514 if (ret < 0)
515 return ctrl_error();
517 usb_host_claim_interfaces(s, config);
518 return 0;
521 static int usb_host_set_interface(USBHostDevice *s, int iface, int alt)
523 struct usbdevfs_setinterface si;
524 int ret;
526 si.interface = iface;
527 si.altsetting = alt;
528 ret = ioctl(s->fd, USBDEVFS_SETINTERFACE, &si);
530 dprintf("husb: ctrl set iface %d altset %d ret %d errno %d\n",
531 iface, alt, ret, errno);
533 if (ret < 0)
534 return ctrl_error();
536 usb_linux_update_endp_table(s);
537 return 0;
540 static int usb_host_handle_control(USBHostDevice *s, USBPacket *p)
542 struct usbdevfs_urb *urb;
543 AsyncURB *aurb;
544 int ret, value, index;
547 * Process certain standard device requests.
548 * These are infrequent and are processed synchronously.
550 value = le16_to_cpu(s->ctrl.req.wValue);
551 index = le16_to_cpu(s->ctrl.req.wIndex);
553 dprintf("husb: ctrl type 0x%x req 0x%x val 0x%x index %u len %u\n",
554 s->ctrl.req.bRequestType, s->ctrl.req.bRequest, value, index,
555 s->ctrl.len);
557 if (s->ctrl.req.bRequestType == 0) {
558 switch (s->ctrl.req.bRequest) {
559 case USB_REQ_SET_ADDRESS:
560 return usb_host_set_address(s, value);
562 case USB_REQ_SET_CONFIGURATION:
563 return usb_host_set_config(s, value & 0xff);
567 if (s->ctrl.req.bRequestType == 1 &&
568 s->ctrl.req.bRequest == USB_REQ_SET_INTERFACE)
569 return usb_host_set_interface(s, index, value);
571 /* The rest are asynchronous */
573 aurb = async_alloc();
574 if (!aurb) {
575 dprintf("husb: async malloc failed\n");
576 return USB_RET_NAK;
578 aurb->hdev = s;
579 aurb->packet = p;
582 * Setup ctrl transfer.
584 * s->ctrl is layed out such that data buffer immediately follows
585 * 'req' struct which is exactly what usbdevfs expects.
587 urb = &aurb->urb;
589 urb->type = USBDEVFS_URB_TYPE_CONTROL;
590 urb->endpoint = p->devep;
592 urb->buffer = &s->ctrl.req;
593 urb->buffer_length = 8 + s->ctrl.len;
595 urb->usercontext = s;
597 ret = ioctl(s->fd, USBDEVFS_SUBMITURB, urb);
599 dprintf("husb: submit ctrl. len %u aurb %p\n", urb->buffer_length, aurb);
601 if (ret < 0) {
602 dprintf("husb: submit failed. errno %d\n", errno);
603 async_free(aurb);
605 switch(errno) {
606 case ETIMEDOUT:
607 return USB_RET_NAK;
608 case EPIPE:
609 default:
610 return USB_RET_STALL;
614 usb_defer_packet(p, async_cancel, aurb);
615 return USB_RET_ASYNC;
618 static int do_token_setup(USBDevice *dev, USBPacket *p)
620 USBHostDevice *s = (USBHostDevice *) dev;
621 int ret = 0;
623 if (p->len != 8)
624 return USB_RET_STALL;
626 memcpy(&s->ctrl.req, p->data, 8);
627 s->ctrl.len = le16_to_cpu(s->ctrl.req.wLength);
628 s->ctrl.offset = 0;
629 s->ctrl.state = CTRL_STATE_SETUP;
631 if (s->ctrl.req.bRequestType & USB_DIR_IN) {
632 ret = usb_host_handle_control(s, p);
633 if (ret < 0)
634 return ret;
636 if (ret < s->ctrl.len)
637 s->ctrl.len = ret;
638 s->ctrl.state = CTRL_STATE_DATA;
639 } else {
640 if (s->ctrl.len == 0)
641 s->ctrl.state = CTRL_STATE_ACK;
642 else
643 s->ctrl.state = CTRL_STATE_DATA;
646 return ret;
649 static int do_token_in(USBDevice *dev, USBPacket *p)
651 USBHostDevice *s = (USBHostDevice *) dev;
652 int ret = 0;
654 if (p->devep != 0)
655 return usb_host_handle_data(s, p);
657 switch(s->ctrl.state) {
658 case CTRL_STATE_ACK:
659 if (!(s->ctrl.req.bRequestType & USB_DIR_IN)) {
660 ret = usb_host_handle_control(s, p);
661 if (ret == USB_RET_ASYNC)
662 return USB_RET_ASYNC;
664 s->ctrl.state = CTRL_STATE_IDLE;
665 return ret > 0 ? 0 : ret;
668 return 0;
670 case CTRL_STATE_DATA:
671 if (s->ctrl.req.bRequestType & USB_DIR_IN) {
672 int len = s->ctrl.len - s->ctrl.offset;
673 if (len > p->len)
674 len = p->len;
675 memcpy(p->data, s->ctrl.buffer + s->ctrl.offset, len);
676 s->ctrl.offset += len;
677 if (s->ctrl.offset >= s->ctrl.len)
678 s->ctrl.state = CTRL_STATE_ACK;
679 return len;
682 s->ctrl.state = CTRL_STATE_IDLE;
683 return USB_RET_STALL;
685 default:
686 return USB_RET_STALL;
690 static int do_token_out(USBDevice *dev, USBPacket *p)
692 USBHostDevice *s = (USBHostDevice *) dev;
694 if (p->devep != 0)
695 return usb_host_handle_data(s, p);
697 switch(s->ctrl.state) {
698 case CTRL_STATE_ACK:
699 if (s->ctrl.req.bRequestType & USB_DIR_IN) {
700 s->ctrl.state = CTRL_STATE_IDLE;
701 /* transfer OK */
702 } else {
703 /* ignore additional output */
705 return 0;
707 case CTRL_STATE_DATA:
708 if (!(s->ctrl.req.bRequestType & USB_DIR_IN)) {
709 int len = s->ctrl.len - s->ctrl.offset;
710 if (len > p->len)
711 len = p->len;
712 memcpy(s->ctrl.buffer + s->ctrl.offset, p->data, len);
713 s->ctrl.offset += len;
714 if (s->ctrl.offset >= s->ctrl.len)
715 s->ctrl.state = CTRL_STATE_ACK;
716 return len;
719 s->ctrl.state = CTRL_STATE_IDLE;
720 return USB_RET_STALL;
722 default:
723 return USB_RET_STALL;
728 * Packet handler.
729 * Called by the HC (host controller).
731 * Returns length of the transaction or one of the USB_RET_XXX codes.
733 static int usb_host_handle_packet(USBDevice *s, USBPacket *p)
735 switch(p->pid) {
736 case USB_MSG_ATTACH:
737 s->state = USB_STATE_ATTACHED;
738 return 0;
740 case USB_MSG_DETACH:
741 s->state = USB_STATE_NOTATTACHED;
742 return 0;
744 case USB_MSG_RESET:
745 s->remote_wakeup = 0;
746 s->addr = 0;
747 s->state = USB_STATE_DEFAULT;
748 s->handle_reset(s);
749 return 0;
752 /* Rest of the PIDs must match our address */
753 if (s->state < USB_STATE_DEFAULT || p->devaddr != s->addr)
754 return USB_RET_NODEV;
756 switch (p->pid) {
757 case USB_TOKEN_SETUP:
758 return do_token_setup(s, p);
760 case USB_TOKEN_IN:
761 return do_token_in(s, p);
763 case USB_TOKEN_OUT:
764 return do_token_out(s, p);
766 default:
767 return USB_RET_STALL;
771 /* returns 1 on problem encountered or 0 for success */
772 static int usb_linux_update_endp_table(USBHostDevice *s)
774 uint8_t *descriptors;
775 uint8_t devep, type, configuration, alt_interface;
776 struct usbdevfs_ctrltransfer ct;
777 int interface, ret, length, i;
779 ct.bRequestType = USB_DIR_IN;
780 ct.bRequest = USB_REQ_GET_CONFIGURATION;
781 ct.wValue = 0;
782 ct.wIndex = 0;
783 ct.wLength = 1;
784 ct.data = &configuration;
785 ct.timeout = 50;
787 ret = ioctl(s->fd, USBDEVFS_CONTROL, &ct);
788 if (ret < 0) {
789 perror("usb_linux_update_endp_table");
790 return 1;
793 /* in address state */
794 if (configuration == 0)
795 return 1;
797 /* get the desired configuration, interface, and endpoint descriptors
798 * from device description */
799 descriptors = &s->descr[18];
800 length = s->descr_len - 18;
801 i = 0;
803 if (descriptors[i + 1] != USB_DT_CONFIG ||
804 descriptors[i + 5] != configuration) {
805 dprintf("invalid descriptor data - configuration\n");
806 return 1;
808 i += descriptors[i];
810 while (i < length) {
811 if (descriptors[i + 1] != USB_DT_INTERFACE ||
812 (descriptors[i + 1] == USB_DT_INTERFACE &&
813 descriptors[i + 4] == 0)) {
814 i += descriptors[i];
815 continue;
818 interface = descriptors[i + 2];
820 ct.bRequestType = USB_DIR_IN | USB_RECIP_INTERFACE;
821 ct.bRequest = USB_REQ_GET_INTERFACE;
822 ct.wValue = 0;
823 ct.wIndex = interface;
824 ct.wLength = 1;
825 ct.data = &alt_interface;
826 ct.timeout = 50;
828 ret = ioctl(s->fd, USBDEVFS_CONTROL, &ct);
829 if (ret < 0) {
830 perror("usb_linux_update_endp_table");
831 return 1;
834 /* the current interface descriptor is the active interface
835 * and has endpoints */
836 if (descriptors[i + 3] != alt_interface) {
837 i += descriptors[i];
838 continue;
841 /* advance to the endpoints */
842 while (i < length && descriptors[i +1] != USB_DT_ENDPOINT)
843 i += descriptors[i];
845 if (i >= length)
846 break;
848 while (i < length) {
849 if (descriptors[i + 1] != USB_DT_ENDPOINT)
850 break;
852 devep = descriptors[i + 2];
853 switch (descriptors[i + 3] & 0x3) {
854 case 0x00:
855 type = USBDEVFS_URB_TYPE_CONTROL;
856 break;
857 case 0x01:
858 type = USBDEVFS_URB_TYPE_ISO;
859 break;
860 case 0x02:
861 type = USBDEVFS_URB_TYPE_BULK;
862 break;
863 case 0x03:
864 type = USBDEVFS_URB_TYPE_INTERRUPT;
865 break;
866 default:
867 dprintf("usb_host: malformed endpoint type\n");
868 type = USBDEVFS_URB_TYPE_BULK;
870 s->endp_table[(devep & 0xf) - 1].type = type;
871 s->endp_table[(devep & 0xf) - 1].halted = 0;
873 i += descriptors[i];
876 return 0;
879 static USBDevice *usb_host_device_open_addr(int bus_num, int addr, const char *prod_name)
881 int fd = -1, ret;
882 USBHostDevice *dev = NULL;
883 struct usbdevfs_connectinfo ci;
884 char buf[1024];
886 dev = qemu_mallocz(sizeof(USBHostDevice));
887 if (!dev)
888 goto fail;
890 dev->bus_num = bus_num;
891 dev->addr = addr;
893 printf("husb: open device %d.%d\n", bus_num, addr);
895 snprintf(buf, sizeof(buf), USBDEVFS_PATH "/%03d/%03d",
896 bus_num, addr);
897 fd = open(buf, O_RDWR | O_NONBLOCK);
898 if (fd < 0) {
899 perror(buf);
900 goto fail;
903 /* read the device description */
904 dev->descr_len = read(fd, dev->descr, sizeof(dev->descr));
905 if (dev->descr_len <= 0) {
906 perror("husb: reading device data failed");
907 goto fail;
910 #ifdef DEBUG
912 int x;
913 printf("=== begin dumping device descriptor data ===\n");
914 for (x = 0; x < dev->descr_len; x++)
915 printf("%02x ", dev->descr[x]);
916 printf("\n=== end dumping device descriptor data ===\n");
918 #endif
920 dev->fd = fd;
923 * Initial configuration is -1 which makes us claim first
924 * available config. We used to start with 1, which does not
925 * always work. I've seen devices where first config starts
926 * with 2.
928 if (!usb_host_claim_interfaces(dev, -1))
929 goto fail;
931 ret = ioctl(fd, USBDEVFS_CONNECTINFO, &ci);
932 if (ret < 0) {
933 perror("usb_host_device_open: USBDEVFS_CONNECTINFO");
934 goto fail;
937 printf("husb: grabbed usb device %d.%d\n", bus_num, addr);
939 ret = usb_linux_update_endp_table(dev);
940 if (ret)
941 goto fail;
943 if (ci.slow)
944 dev->dev.speed = USB_SPEED_LOW;
945 else
946 dev->dev.speed = USB_SPEED_HIGH;
948 dev->dev.handle_packet = usb_host_handle_packet;
949 dev->dev.handle_reset = usb_host_handle_reset;
950 dev->dev.handle_destroy = usb_host_handle_destroy;
952 if (!prod_name || prod_name[0] == '\0')
953 snprintf(dev->dev.devname, sizeof(dev->dev.devname),
954 "host:%d.%d", bus_num, addr);
955 else
956 pstrcpy(dev->dev.devname, sizeof(dev->dev.devname),
957 prod_name);
959 /* USB devio uses 'write' flag to check for async completions */
960 qemu_set_fd_handler(dev->fd, NULL, async_complete, dev);
962 hostdev_link(dev);
964 return (USBDevice *) dev;
966 fail:
967 if (dev)
968 qemu_free(dev);
970 close(fd);
971 return NULL;
974 static int usb_host_auto_add(const char *spec);
975 static int usb_host_auto_del(const char *spec);
977 USBDevice *usb_host_device_open(const char *devname)
979 int bus_num, addr;
980 char product_name[PRODUCT_NAME_SZ];
982 if (strstr(devname, "auto:")) {
983 usb_host_auto_add(devname);
984 return NULL;
987 if (usb_host_find_device(&bus_num, &addr, product_name, sizeof(product_name),
988 devname) < 0)
989 return NULL;
991 if (hostdev_find(bus_num, addr)) {
992 term_printf("husb: host usb device %d.%d is already open\n", bus_num, addr);
993 return NULL;
996 return usb_host_device_open_addr(bus_num, addr, product_name);
999 int usb_host_device_close(const char *devname)
1001 char product_name[PRODUCT_NAME_SZ];
1002 int bus_num, addr;
1003 USBHostDevice *s;
1005 if (strstr(devname, "auto:"))
1006 return usb_host_auto_del(devname);
1008 if (usb_host_find_device(&bus_num, &addr, product_name, sizeof(product_name),
1009 devname) < 0)
1010 return -1;
1012 s = hostdev_find(bus_num, addr);
1013 if (s) {
1014 usb_device_del_addr(0, s->dev.addr);
1015 return 0;
1018 return -1;
1021 static int get_tag_value(char *buf, int buf_size,
1022 const char *str, const char *tag,
1023 const char *stopchars)
1025 const char *p;
1026 char *q;
1027 p = strstr(str, tag);
1028 if (!p)
1029 return -1;
1030 p += strlen(tag);
1031 while (isspace(*p))
1032 p++;
1033 q = buf;
1034 while (*p != '\0' && !strchr(stopchars, *p)) {
1035 if ((q - buf) < (buf_size - 1))
1036 *q++ = *p;
1037 p++;
1039 *q = '\0';
1040 return q - buf;
1043 static int usb_host_scan(void *opaque, USBScanFunc *func)
1045 FILE *f;
1046 char line[1024];
1047 char buf[1024];
1048 int bus_num, addr, speed, device_count, class_id, product_id, vendor_id;
1049 int ret;
1050 char product_name[512];
1052 f = fopen(USBDEVFS_PATH "/devices", "r");
1053 if (!f) {
1054 term_printf("husb: could not open %s\n", USBDEVFS_PATH "/devices");
1055 return 0;
1057 device_count = 0;
1058 bus_num = addr = speed = class_id = product_id = vendor_id = 0;
1059 ret = 0;
1060 for(;;) {
1061 if (fgets(line, sizeof(line), f) == NULL)
1062 break;
1063 if (strlen(line) > 0)
1064 line[strlen(line) - 1] = '\0';
1065 if (line[0] == 'T' && line[1] == ':') {
1066 if (device_count && (vendor_id || product_id)) {
1067 /* New device. Add the previously discovered device. */
1068 ret = func(opaque, bus_num, addr, class_id, vendor_id,
1069 product_id, product_name, speed);
1070 if (ret)
1071 goto the_end;
1073 if (get_tag_value(buf, sizeof(buf), line, "Bus=", " ") < 0)
1074 goto fail;
1075 bus_num = atoi(buf);
1076 if (get_tag_value(buf, sizeof(buf), line, "Dev#=", " ") < 0)
1077 goto fail;
1078 addr = atoi(buf);
1079 if (get_tag_value(buf, sizeof(buf), line, "Spd=", " ") < 0)
1080 goto fail;
1081 if (!strcmp(buf, "480"))
1082 speed = USB_SPEED_HIGH;
1083 else if (!strcmp(buf, "1.5"))
1084 speed = USB_SPEED_LOW;
1085 else
1086 speed = USB_SPEED_FULL;
1087 product_name[0] = '\0';
1088 class_id = 0xff;
1089 device_count++;
1090 product_id = 0;
1091 vendor_id = 0;
1092 } else if (line[0] == 'P' && line[1] == ':') {
1093 if (get_tag_value(buf, sizeof(buf), line, "Vendor=", " ") < 0)
1094 goto fail;
1095 vendor_id = strtoul(buf, NULL, 16);
1096 if (get_tag_value(buf, sizeof(buf), line, "ProdID=", " ") < 0)
1097 goto fail;
1098 product_id = strtoul(buf, NULL, 16);
1099 } else if (line[0] == 'S' && line[1] == ':') {
1100 if (get_tag_value(buf, sizeof(buf), line, "Product=", "") < 0)
1101 goto fail;
1102 pstrcpy(product_name, sizeof(product_name), buf);
1103 } else if (line[0] == 'D' && line[1] == ':') {
1104 if (get_tag_value(buf, sizeof(buf), line, "Cls=", " (") < 0)
1105 goto fail;
1106 class_id = strtoul(buf, NULL, 16);
1108 fail: ;
1110 if (device_count && (vendor_id || product_id)) {
1111 /* Add the last device. */
1112 ret = func(opaque, bus_num, addr, class_id, vendor_id,
1113 product_id, product_name, speed);
1115 the_end:
1116 fclose(f);
1117 return ret;
1120 struct USBAutoFilter {
1121 struct USBAutoFilter *next;
1122 int bus_num;
1123 int addr;
1124 int vendor_id;
1125 int product_id;
1128 static QEMUTimer *usb_auto_timer;
1129 static struct USBAutoFilter *usb_auto_filter;
1131 static int usb_host_auto_scan(void *opaque, int bus_num, int addr,
1132 int class_id, int vendor_id, int product_id,
1133 const char *product_name, int speed)
1135 struct USBAutoFilter *f;
1136 struct USBDevice *dev;
1138 /* Ignore hubs */
1139 if (class_id == 9)
1140 return 0;
1142 for (f = usb_auto_filter; f; f = f->next) {
1143 if (f->bus_num >= 0 && f->bus_num != bus_num)
1144 continue;
1146 if (f->addr >= 0 && f->addr != addr)
1147 continue;
1149 if (f->vendor_id >= 0 && f->vendor_id != vendor_id)
1150 continue;
1152 if (f->product_id >= 0 && f->product_id != product_id)
1153 continue;
1155 /* We got a match */
1157 /* Allredy attached ? */
1158 if (hostdev_find(bus_num, addr))
1159 return 0;
1161 dprintf("husb: auto open: bus_num %d addr %d\n", bus_num, addr);
1163 dev = usb_host_device_open_addr(bus_num, addr, product_name);
1164 if (dev)
1165 usb_device_add_dev(dev);
1168 return 0;
1171 static void usb_host_auto_timer(void *unused)
1173 usb_host_scan(NULL, usb_host_auto_scan);
1174 qemu_mod_timer(usb_auto_timer, qemu_get_clock(rt_clock) + 2000);
1178 * Autoconnect filter
1179 * Format:
1180 * auto:bus:dev[:vid:pid]
1181 * auto:bus.dev[:vid:pid]
1183 * bus - bus number (dec, * means any)
1184 * dev - device number (dec, * means any)
1185 * vid - vendor id (hex, * means any)
1186 * pid - product id (hex, * means any)
1188 * See 'lsusb' output.
1190 static int parse_filter(const char *spec, struct USBAutoFilter *f)
1192 enum { BUS, DEV, VID, PID, DONE };
1193 const char *p = spec;
1194 int i;
1196 f->bus_num = -1;
1197 f->addr = -1;
1198 f->vendor_id = -1;
1199 f->product_id = -1;
1201 for (i = BUS; i < DONE; i++) {
1202 p = strpbrk(p, ":.");
1203 if (!p) break;
1204 p++;
1206 if (*p == '*')
1207 continue;
1209 switch(i) {
1210 case BUS: f->bus_num = strtol(p, NULL, 10); break;
1211 case DEV: f->addr = strtol(p, NULL, 10); break;
1212 case VID: f->vendor_id = strtol(p, NULL, 16); break;
1213 case PID: f->product_id = strtol(p, NULL, 16); break;
1217 if (i < DEV) {
1218 fprintf(stderr, "husb: invalid auto filter spec %s\n", spec);
1219 return -1;
1222 return 0;
1225 static int match_filter(const struct USBAutoFilter *f1,
1226 const struct USBAutoFilter *f2)
1228 return f1->bus_num == f2->bus_num &&
1229 f1->addr == f2->addr &&
1230 f1->vendor_id == f2->vendor_id &&
1231 f1->product_id == f2->product_id;
1234 static int usb_host_auto_add(const char *spec)
1236 struct USBAutoFilter filter, *f;
1238 if (parse_filter(spec, &filter) < 0)
1239 return -1;
1241 f = qemu_mallocz(sizeof(*f));
1242 if (!f) {
1243 fprintf(stderr, "husb: failed to allocate auto filter\n");
1244 return -1;
1247 *f = filter;
1249 if (!usb_auto_filter) {
1251 * First entry. Init and start the monitor.
1252 * Right now we're using timer to check for new devices.
1253 * If this turns out to be too expensive we can move that into a
1254 * separate thread.
1256 usb_auto_timer = qemu_new_timer(rt_clock, usb_host_auto_timer, NULL);
1257 if (!usb_auto_timer) {
1258 fprintf(stderr, "husb: failed to allocate auto scan timer\n");
1259 qemu_free(f);
1260 return -1;
1263 /* Check for new devices every two seconds */
1264 qemu_mod_timer(usb_auto_timer, qemu_get_clock(rt_clock) + 2000);
1267 dprintf("husb: added auto filter: bus_num %d addr %d vid %d pid %d\n",
1268 f->bus_num, f->addr, f->vendor_id, f->product_id);
1270 f->next = usb_auto_filter;
1271 usb_auto_filter = f;
1273 return 0;
1276 static int usb_host_auto_del(const char *spec)
1278 struct USBAutoFilter *pf = usb_auto_filter;
1279 struct USBAutoFilter **prev = &usb_auto_filter;
1280 struct USBAutoFilter filter;
1282 if (parse_filter(spec, &filter) < 0)
1283 return -1;
1285 while (pf) {
1286 if (match_filter(pf, &filter)) {
1287 dprintf("husb: removed auto filter: bus_num %d addr %d vid %d pid %d\n",
1288 pf->bus_num, pf->addr, pf->vendor_id, pf->product_id);
1290 *prev = pf->next;
1292 if (!usb_auto_filter) {
1293 /* No more filters. Stop scanning. */
1294 qemu_del_timer(usb_auto_timer);
1295 qemu_free_timer(usb_auto_timer);
1298 return 0;
1301 prev = &pf->next;
1302 pf = pf->next;
1305 return -1;
1308 typedef struct FindDeviceState {
1309 int vendor_id;
1310 int product_id;
1311 int bus_num;
1312 int addr;
1313 char product_name[PRODUCT_NAME_SZ];
1314 } FindDeviceState;
1316 static int usb_host_find_device_scan(void *opaque, int bus_num, int addr,
1317 int class_id,
1318 int vendor_id, int product_id,
1319 const char *product_name, int speed)
1321 FindDeviceState *s = opaque;
1322 if ((vendor_id == s->vendor_id &&
1323 product_id == s->product_id) ||
1324 (bus_num == s->bus_num &&
1325 addr == s->addr)) {
1326 pstrcpy(s->product_name, PRODUCT_NAME_SZ, product_name);
1327 s->bus_num = bus_num;
1328 s->addr = addr;
1329 return 1;
1330 } else {
1331 return 0;
1335 /* the syntax is :
1336 'bus.addr' (decimal numbers) or
1337 'vendor_id:product_id' (hexa numbers) */
1338 static int usb_host_find_device(int *pbus_num, int *paddr,
1339 char *product_name, int product_name_size,
1340 const char *devname)
1342 const char *p;
1343 int ret;
1344 FindDeviceState fs;
1346 p = strchr(devname, '.');
1347 if (p) {
1348 *pbus_num = strtoul(devname, NULL, 0);
1349 *paddr = strtoul(p + 1, NULL, 0);
1350 fs.bus_num = *pbus_num;
1351 fs.addr = *paddr;
1352 ret = usb_host_scan(&fs, usb_host_find_device_scan);
1353 if (ret)
1354 pstrcpy(product_name, product_name_size, fs.product_name);
1355 return 0;
1358 p = strchr(devname, ':');
1359 if (p) {
1360 fs.vendor_id = strtoul(devname, NULL, 16);
1361 fs.product_id = strtoul(p + 1, NULL, 16);
1362 ret = usb_host_scan(&fs, usb_host_find_device_scan);
1363 if (ret) {
1364 *pbus_num = fs.bus_num;
1365 *paddr = fs.addr;
1366 pstrcpy(product_name, product_name_size, fs.product_name);
1367 return 0;
1370 return -1;
1373 /**********************/
1374 /* USB host device info */
1376 struct usb_class_info {
1377 int class;
1378 const char *class_name;
1381 static const struct usb_class_info usb_class_info[] = {
1382 { USB_CLASS_AUDIO, "Audio"},
1383 { USB_CLASS_COMM, "Communication"},
1384 { USB_CLASS_HID, "HID"},
1385 { USB_CLASS_HUB, "Hub" },
1386 { USB_CLASS_PHYSICAL, "Physical" },
1387 { USB_CLASS_PRINTER, "Printer" },
1388 { USB_CLASS_MASS_STORAGE, "Storage" },
1389 { USB_CLASS_CDC_DATA, "Data" },
1390 { USB_CLASS_APP_SPEC, "Application Specific" },
1391 { USB_CLASS_VENDOR_SPEC, "Vendor Specific" },
1392 { USB_CLASS_STILL_IMAGE, "Still Image" },
1393 { USB_CLASS_CSCID, "Smart Card" },
1394 { USB_CLASS_CONTENT_SEC, "Content Security" },
1395 { -1, NULL }
1398 static const char *usb_class_str(uint8_t class)
1400 const struct usb_class_info *p;
1401 for(p = usb_class_info; p->class != -1; p++) {
1402 if (p->class == class)
1403 break;
1405 return p->class_name;
1408 static void usb_info_device(int bus_num, int addr, int class_id,
1409 int vendor_id, int product_id,
1410 const char *product_name,
1411 int speed)
1413 const char *class_str, *speed_str;
1415 switch(speed) {
1416 case USB_SPEED_LOW:
1417 speed_str = "1.5";
1418 break;
1419 case USB_SPEED_FULL:
1420 speed_str = "12";
1421 break;
1422 case USB_SPEED_HIGH:
1423 speed_str = "480";
1424 break;
1425 default:
1426 speed_str = "?";
1427 break;
1430 term_printf(" Device %d.%d, speed %s Mb/s\n",
1431 bus_num, addr, speed_str);
1432 class_str = usb_class_str(class_id);
1433 if (class_str)
1434 term_printf(" %s:", class_str);
1435 else
1436 term_printf(" Class %02x:", class_id);
1437 term_printf(" USB device %04x:%04x", vendor_id, product_id);
1438 if (product_name[0] != '\0')
1439 term_printf(", %s", product_name);
1440 term_printf("\n");
1443 static int usb_host_info_device(void *opaque, int bus_num, int addr,
1444 int class_id,
1445 int vendor_id, int product_id,
1446 const char *product_name,
1447 int speed)
1449 usb_info_device(bus_num, addr, class_id, vendor_id, product_id,
1450 product_name, speed);
1451 return 0;
1454 static void dec2str(int val, char *str)
1456 if (val == -1)
1457 strcpy(str, "*");
1458 else
1459 sprintf(str, "%d", val);
1462 static void hex2str(int val, char *str)
1464 if (val == -1)
1465 strcpy(str, "*");
1466 else
1467 sprintf(str, "%x", val);
1470 void usb_host_info(void)
1472 struct USBAutoFilter *f;
1474 usb_host_scan(NULL, usb_host_info_device);
1476 if (usb_auto_filter)
1477 term_printf(" Auto filters:\n");
1478 for (f = usb_auto_filter; f; f = f->next) {
1479 char bus[10], addr[10], vid[10], pid[10];
1480 dec2str(f->bus_num, bus);
1481 dec2str(f->addr, addr);
1482 hex2str(f->vendor_id, vid);
1483 hex2str(f->product_id, pid);
1484 term_printf(" Device %s.%s ID %s:%s\n", bus, addr, vid, pid);
1488 #else
1490 #include "hw/usb.h"
1492 void usb_host_info(void)
1494 term_printf("USB host devices not supported\n");
1497 /* XXX: modify configure to compile the right host driver */
1498 USBDevice *usb_host_device_open(const char *devname)
1500 return NULL;
1503 int usb_host_device_close(const char *devname)
1505 return 0;
1508 #endif