usb-linux: walk async urb list in cancel
[qemu.git] / usb-linux.c
blob5e9c5e413521f755a75ce3090bff4c94b41b5a99
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 * Copyright 2008 TJ <linux@tjworld.net>
11 * Added flexible support for /dev/bus/usb /sys/bus/usb/devices in addition
12 * to the legacy /proc/bus/usb USB device discovery and handling
14 * Permission is hereby granted, free of charge, to any person obtaining a copy
15 * of this software and associated documentation files (the "Software"), to deal
16 * in the Software without restriction, including without limitation the rights
17 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
18 * copies of the Software, and to permit persons to whom the Software is
19 * furnished to do so, subject to the following conditions:
21 * The above copyright notice and this permission notice shall be included in
22 * all copies or substantial portions of the Software.
24 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
25 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
26 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
27 * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
28 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
29 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
30 * THE SOFTWARE.
33 #include "qemu-common.h"
34 #include "qemu-timer.h"
35 #include "monitor.h"
36 #include "sysemu.h"
38 #include <dirent.h>
39 #include <sys/ioctl.h>
40 #include <signal.h>
42 #include <linux/usbdevice_fs.h>
43 #include <linux/version.h>
44 #include "hw/usb.h"
46 /* We redefine it to avoid version problems */
47 struct usb_ctrltransfer {
48 uint8_t bRequestType;
49 uint8_t bRequest;
50 uint16_t wValue;
51 uint16_t wIndex;
52 uint16_t wLength;
53 uint32_t timeout;
54 void *data;
57 typedef int USBScanFunc(void *opaque, int bus_num, int addr, char *port,
58 int class_id, int vendor_id, int product_id,
59 const char *product_name, int speed);
61 //#define DEBUG
63 #ifdef DEBUG
64 #define DPRINTF printf
65 #else
66 #define DPRINTF(...)
67 #endif
69 #define USBDBG_DEVOPENED "husb: opened %s/devices\n"
71 #define USBPROCBUS_PATH "/proc/bus/usb"
72 #define PRODUCT_NAME_SZ 32
73 #define MAX_ENDPOINTS 15
74 #define MAX_PORTLEN 16
75 #define USBDEVBUS_PATH "/dev/bus/usb"
76 #define USBSYSBUS_PATH "/sys/bus/usb"
78 static char *usb_host_device_path;
80 #define USB_FS_NONE 0
81 #define USB_FS_PROC 1
82 #define USB_FS_DEV 2
83 #define USB_FS_SYS 3
85 static int usb_fs_type;
87 /* endpoint association data */
88 #define ISO_FRAME_DESC_PER_URB 32
89 #define ISO_URB_COUNT 3
90 #define INVALID_EP_TYPE 255
92 typedef struct AsyncURB AsyncURB;
94 struct endp_data {
95 uint8_t type;
96 uint8_t halted;
97 uint8_t iso_started;
98 AsyncURB *iso_urb;
99 int iso_urb_idx;
100 int iso_buffer_used;
101 int max_packet_size;
104 struct USBAutoFilter {
105 uint32_t bus_num;
106 uint32_t addr;
107 char *port;
108 uint32_t vendor_id;
109 uint32_t product_id;
112 typedef struct USBHostDevice {
113 USBDevice dev;
114 int fd;
116 uint8_t descr[1024];
117 int descr_len;
118 int configuration;
119 int ninterfaces;
120 int closing;
121 Notifier exit;
123 struct endp_data endp_table[MAX_ENDPOINTS];
124 QLIST_HEAD(, AsyncURB) aurbs;
126 /* Host side address */
127 int bus_num;
128 int addr;
129 char port[MAX_PORTLEN];
130 struct USBAutoFilter match;
132 QTAILQ_ENTRY(USBHostDevice) next;
133 } USBHostDevice;
135 static QTAILQ_HEAD(, USBHostDevice) hostdevs = QTAILQ_HEAD_INITIALIZER(hostdevs);
137 static int usb_host_close(USBHostDevice *dev);
138 static int parse_filter(const char *spec, struct USBAutoFilter *f);
139 static void usb_host_auto_check(void *unused);
140 static int usb_host_read_file(char *line, size_t line_size,
141 const char *device_file, const char *device_name);
143 static int is_isoc(USBHostDevice *s, int ep)
145 return s->endp_table[ep - 1].type == USBDEVFS_URB_TYPE_ISO;
148 static int is_valid(USBHostDevice *s, int ep)
150 return s->endp_table[ep - 1].type != INVALID_EP_TYPE;
153 static int is_halted(USBHostDevice *s, int ep)
155 return s->endp_table[ep - 1].halted;
158 static void clear_halt(USBHostDevice *s, int ep)
160 s->endp_table[ep - 1].halted = 0;
163 static void set_halt(USBHostDevice *s, int ep)
165 s->endp_table[ep - 1].halted = 1;
168 static int is_iso_started(USBHostDevice *s, int ep)
170 return s->endp_table[ep - 1].iso_started;
173 static void clear_iso_started(USBHostDevice *s, int ep)
175 s->endp_table[ep - 1].iso_started = 0;
178 static void set_iso_started(USBHostDevice *s, int ep)
180 s->endp_table[ep - 1].iso_started = 1;
183 static void set_iso_urb(USBHostDevice *s, int ep, AsyncURB *iso_urb)
185 s->endp_table[ep - 1].iso_urb = iso_urb;
188 static AsyncURB *get_iso_urb(USBHostDevice *s, int ep)
190 return s->endp_table[ep - 1].iso_urb;
193 static void set_iso_urb_idx(USBHostDevice *s, int ep, int i)
195 s->endp_table[ep - 1].iso_urb_idx = i;
198 static int get_iso_urb_idx(USBHostDevice *s, int ep)
200 return s->endp_table[ep - 1].iso_urb_idx;
203 static void set_iso_buffer_used(USBHostDevice *s, int ep, int i)
205 s->endp_table[ep - 1].iso_buffer_used = i;
208 static int get_iso_buffer_used(USBHostDevice *s, int ep)
210 return s->endp_table[ep - 1].iso_buffer_used;
213 static int get_max_packet_size(USBHostDevice *s, int ep)
215 return s->endp_table[ep - 1].max_packet_size;
219 * Async URB state.
220 * We always allocate iso packet descriptors even for bulk transfers
221 * to simplify allocation and casts.
223 struct AsyncURB
225 struct usbdevfs_urb urb;
226 struct usbdevfs_iso_packet_desc isocpd[ISO_FRAME_DESC_PER_URB];
227 USBHostDevice *hdev;
228 QLIST_ENTRY(AsyncURB) next;
230 /* For regular async urbs */
231 USBPacket *packet;
233 /* For buffered iso handling */
234 int iso_frame_idx; /* -1 means in flight */
237 static AsyncURB *async_alloc(USBHostDevice *s)
239 AsyncURB *aurb = qemu_mallocz(sizeof(AsyncURB));
240 aurb->hdev = s;
241 QLIST_INSERT_HEAD(&s->aurbs, aurb, next);
242 return aurb;
245 static void async_free(AsyncURB *aurb)
247 QLIST_REMOVE(aurb, next);
248 qemu_free(aurb);
251 static void async_complete(void *opaque)
253 USBHostDevice *s = opaque;
254 AsyncURB *aurb;
256 while (1) {
257 USBPacket *p;
259 int r = ioctl(s->fd, USBDEVFS_REAPURBNDELAY, &aurb);
260 if (r < 0) {
261 if (errno == EAGAIN) {
262 return;
264 if (errno == ENODEV && !s->closing) {
265 printf("husb: device %d.%d disconnected\n",
266 s->bus_num, s->addr);
267 usb_host_close(s);
268 usb_host_auto_check(NULL);
269 return;
272 DPRINTF("husb: async. reap urb failed errno %d\n", errno);
273 return;
276 DPRINTF("husb: async completed. aurb %p status %d alen %d\n",
277 aurb, aurb->urb.status, aurb->urb.actual_length);
279 /* If this is a buffered iso urb mark it as complete and don't do
280 anything else (it is handled further in usb_host_handle_iso_data) */
281 if (aurb->iso_frame_idx == -1) {
282 if (aurb->urb.status == -EPIPE) {
283 set_halt(s, aurb->urb.endpoint & 0xf);
285 aurb->iso_frame_idx = 0;
286 continue;
289 p = aurb->packet;
291 if (p) {
292 switch (aurb->urb.status) {
293 case 0:
294 p->len = aurb->urb.actual_length;
295 break;
297 case -EPIPE:
298 set_halt(s, p->devep);
299 p->len = USB_RET_STALL;
300 break;
302 default:
303 p->len = USB_RET_NAK;
304 break;
307 if (aurb->urb.type == USBDEVFS_URB_TYPE_CONTROL) {
308 usb_generic_async_ctrl_complete(&s->dev, p);
309 } else {
310 usb_packet_complete(&s->dev, p);
314 async_free(aurb);
318 static void async_cancel(USBPacket *p, void *opaque)
320 USBHostDevice *s = opaque;
321 AsyncURB *aurb;
323 QLIST_FOREACH(aurb, &s->aurbs, next) {
324 if (p != aurb->packet) {
325 continue;
328 DPRINTF("husb: async cancel: packet %p, aurb %p\n", p, aurb);
330 /* Mark it as dead (see async_complete above) */
331 aurb->packet = NULL;
333 int r = ioctl(s->fd, USBDEVFS_DISCARDURB, aurb);
334 if (r < 0) {
335 DPRINTF("husb: async. discard urb failed errno %d\n", errno);
340 static int usb_host_claim_interfaces(USBHostDevice *dev, int configuration)
342 int dev_descr_len, config_descr_len;
343 int interface, nb_interfaces;
344 int ret, i;
346 if (configuration == 0) /* address state - ignore */
347 return 1;
349 DPRINTF("husb: claiming interfaces. config %d\n", configuration);
351 i = 0;
352 dev_descr_len = dev->descr[0];
353 if (dev_descr_len > dev->descr_len) {
354 goto fail;
357 i += dev_descr_len;
358 while (i < dev->descr_len) {
359 DPRINTF("husb: i is %d, descr_len is %d, dl %d, dt %d\n",
360 i, dev->descr_len,
361 dev->descr[i], dev->descr[i+1]);
363 if (dev->descr[i+1] != USB_DT_CONFIG) {
364 i += dev->descr[i];
365 continue;
367 config_descr_len = dev->descr[i];
369 printf("husb: config #%d need %d\n", dev->descr[i + 5], configuration);
371 if (configuration < 0 || configuration == dev->descr[i + 5]) {
372 configuration = dev->descr[i + 5];
373 break;
376 i += config_descr_len;
379 if (i >= dev->descr_len) {
380 fprintf(stderr,
381 "husb: update iface failed. no matching configuration\n");
382 goto fail;
384 nb_interfaces = dev->descr[i + 4];
386 #ifdef USBDEVFS_DISCONNECT
387 /* earlier Linux 2.4 do not support that */
389 struct usbdevfs_ioctl ctrl;
390 for (interface = 0; interface < nb_interfaces; interface++) {
391 ctrl.ioctl_code = USBDEVFS_DISCONNECT;
392 ctrl.ifno = interface;
393 ctrl.data = 0;
394 ret = ioctl(dev->fd, USBDEVFS_IOCTL, &ctrl);
395 if (ret < 0 && errno != ENODATA) {
396 perror("USBDEVFS_DISCONNECT");
397 goto fail;
401 #endif
403 /* XXX: only grab if all interfaces are free */
404 for (interface = 0; interface < nb_interfaces; interface++) {
405 ret = ioctl(dev->fd, USBDEVFS_CLAIMINTERFACE, &interface);
406 if (ret < 0) {
407 if (errno == EBUSY) {
408 printf("husb: update iface. device already grabbed\n");
409 } else {
410 perror("husb: failed to claim interface");
412 fail:
413 return 0;
417 printf("husb: %d interfaces claimed for configuration %d\n",
418 nb_interfaces, configuration);
420 dev->ninterfaces = nb_interfaces;
421 dev->configuration = configuration;
422 return 1;
425 static int usb_host_release_interfaces(USBHostDevice *s)
427 int ret, i;
429 DPRINTF("husb: releasing interfaces\n");
431 for (i = 0; i < s->ninterfaces; i++) {
432 ret = ioctl(s->fd, USBDEVFS_RELEASEINTERFACE, &i);
433 if (ret < 0) {
434 perror("husb: failed to release interface");
435 return 0;
439 return 1;
442 static void usb_host_handle_reset(USBDevice *dev)
444 USBHostDevice *s = DO_UPCAST(USBHostDevice, dev, dev);
446 DPRINTF("husb: reset device %u.%u\n", s->bus_num, s->addr);
448 ioctl(s->fd, USBDEVFS_RESET);
450 usb_host_claim_interfaces(s, s->configuration);
453 static void usb_host_handle_destroy(USBDevice *dev)
455 USBHostDevice *s = (USBHostDevice *)dev;
457 usb_host_close(s);
458 QTAILQ_REMOVE(&hostdevs, s, next);
459 qemu_remove_exit_notifier(&s->exit);
462 static int usb_linux_update_endp_table(USBHostDevice *s);
464 /* iso data is special, we need to keep enough urbs in flight to make sure
465 that the controller never runs out of them, otherwise the device will
466 likely suffer a buffer underrun / overrun. */
467 static AsyncURB *usb_host_alloc_iso(USBHostDevice *s, uint8_t ep, int in)
469 AsyncURB *aurb;
470 int i, j, len = get_max_packet_size(s, ep);
472 aurb = qemu_mallocz(ISO_URB_COUNT * sizeof(*aurb));
473 for (i = 0; i < ISO_URB_COUNT; i++) {
474 aurb[i].urb.endpoint = ep;
475 aurb[i].urb.buffer_length = ISO_FRAME_DESC_PER_URB * len;
476 aurb[i].urb.buffer = qemu_malloc(aurb[i].urb.buffer_length);
477 aurb[i].urb.type = USBDEVFS_URB_TYPE_ISO;
478 aurb[i].urb.flags = USBDEVFS_URB_ISO_ASAP;
479 aurb[i].urb.number_of_packets = ISO_FRAME_DESC_PER_URB;
480 for (j = 0 ; j < ISO_FRAME_DESC_PER_URB; j++)
481 aurb[i].urb.iso_frame_desc[j].length = len;
482 if (in) {
483 aurb[i].urb.endpoint |= 0x80;
484 /* Mark as fully consumed (idle) */
485 aurb[i].iso_frame_idx = ISO_FRAME_DESC_PER_URB;
488 set_iso_urb(s, ep, aurb);
490 return aurb;
493 static void usb_host_stop_n_free_iso(USBHostDevice *s, uint8_t ep)
495 AsyncURB *aurb;
496 int i, ret, killed = 0, free = 1;
498 aurb = get_iso_urb(s, ep);
499 if (!aurb) {
500 return;
503 for (i = 0; i < ISO_URB_COUNT; i++) {
504 /* in flight? */
505 if (aurb[i].iso_frame_idx == -1) {
506 ret = ioctl(s->fd, USBDEVFS_DISCARDURB, &aurb[i]);
507 if (ret < 0) {
508 printf("husb: discard isoc in urb failed errno %d\n", errno);
509 free = 0;
510 continue;
512 killed++;
516 /* Make sure any urbs we've killed are reaped before we free them */
517 if (killed) {
518 async_complete(s);
521 for (i = 0; i < ISO_URB_COUNT; i++) {
522 qemu_free(aurb[i].urb.buffer);
525 if (free)
526 qemu_free(aurb);
527 else
528 printf("husb: leaking iso urbs because of discard failure\n");
529 set_iso_urb(s, ep, NULL);
530 set_iso_urb_idx(s, ep, 0);
531 clear_iso_started(s, ep);
534 static int urb_status_to_usb_ret(int status)
536 switch (status) {
537 case -EPIPE:
538 return USB_RET_STALL;
539 default:
540 return USB_RET_NAK;
544 static int usb_host_handle_iso_data(USBHostDevice *s, USBPacket *p, int in)
546 AsyncURB *aurb;
547 int i, j, ret, max_packet_size, offset, len = 0;
549 max_packet_size = get_max_packet_size(s, p->devep);
550 if (max_packet_size == 0)
551 return USB_RET_NAK;
553 aurb = get_iso_urb(s, p->devep);
554 if (!aurb) {
555 aurb = usb_host_alloc_iso(s, p->devep, in);
558 i = get_iso_urb_idx(s, p->devep);
559 j = aurb[i].iso_frame_idx;
560 if (j >= 0 && j < ISO_FRAME_DESC_PER_URB) {
561 if (in) {
562 /* Check urb status */
563 if (aurb[i].urb.status) {
564 len = urb_status_to_usb_ret(aurb[i].urb.status);
565 /* Move to the next urb */
566 aurb[i].iso_frame_idx = ISO_FRAME_DESC_PER_URB - 1;
567 /* Check frame status */
568 } else if (aurb[i].urb.iso_frame_desc[j].status) {
569 len = urb_status_to_usb_ret(
570 aurb[i].urb.iso_frame_desc[j].status);
571 /* Check the frame fits */
572 } else if (aurb[i].urb.iso_frame_desc[j].actual_length > p->len) {
573 printf("husb: received iso data is larger then packet\n");
574 len = USB_RET_NAK;
575 /* All good copy data over */
576 } else {
577 len = aurb[i].urb.iso_frame_desc[j].actual_length;
578 memcpy(p->data,
579 aurb[i].urb.buffer +
580 j * aurb[i].urb.iso_frame_desc[0].length,
581 len);
583 } else {
584 len = p->len;
585 offset = (j == 0) ? 0 : get_iso_buffer_used(s, p->devep);
587 /* Check the frame fits */
588 if (len > max_packet_size) {
589 printf("husb: send iso data is larger then max packet size\n");
590 return USB_RET_NAK;
593 /* All good copy data over */
594 memcpy(aurb[i].urb.buffer + offset, p->data, len);
595 aurb[i].urb.iso_frame_desc[j].length = len;
596 offset += len;
597 set_iso_buffer_used(s, p->devep, offset);
599 /* Start the stream once we have buffered enough data */
600 if (!is_iso_started(s, p->devep) && i == 1 && j == 8) {
601 set_iso_started(s, p->devep);
604 aurb[i].iso_frame_idx++;
605 if (aurb[i].iso_frame_idx == ISO_FRAME_DESC_PER_URB) {
606 i = (i + 1) % ISO_URB_COUNT;
607 set_iso_urb_idx(s, p->devep, i);
609 } else {
610 if (in) {
611 set_iso_started(s, p->devep);
612 } else {
613 DPRINTF("hubs: iso out error no free buffer, dropping packet\n");
617 if (is_iso_started(s, p->devep)) {
618 /* (Re)-submit all fully consumed / filled urbs */
619 for (i = 0; i < ISO_URB_COUNT; i++) {
620 if (aurb[i].iso_frame_idx == ISO_FRAME_DESC_PER_URB) {
621 ret = ioctl(s->fd, USBDEVFS_SUBMITURB, &aurb[i]);
622 if (ret < 0) {
623 printf("husb error submitting iso urb %d: %d\n", i, errno);
624 if (!in || len == 0) {
625 switch(errno) {
626 case ETIMEDOUT:
627 len = USB_RET_NAK;
628 break;
629 case EPIPE:
630 default:
631 len = USB_RET_STALL;
634 break;
636 aurb[i].iso_frame_idx = -1;
641 return len;
644 static int usb_host_handle_data(USBDevice *dev, USBPacket *p)
646 USBHostDevice *s = DO_UPCAST(USBHostDevice, dev, dev);
647 struct usbdevfs_urb *urb;
648 AsyncURB *aurb;
649 int ret;
650 uint8_t ep;
652 if (!is_valid(s, p->devep)) {
653 return USB_RET_NAK;
656 if (p->pid == USB_TOKEN_IN) {
657 ep = p->devep | 0x80;
658 } else {
659 ep = p->devep;
662 if (is_halted(s, p->devep)) {
663 ret = ioctl(s->fd, USBDEVFS_CLEAR_HALT, &ep);
664 if (ret < 0) {
665 DPRINTF("husb: failed to clear halt. ep 0x%x errno %d\n",
666 ep, errno);
667 return USB_RET_NAK;
669 clear_halt(s, p->devep);
672 if (is_isoc(s, p->devep)) {
673 return usb_host_handle_iso_data(s, p, p->pid == USB_TOKEN_IN);
676 aurb = async_alloc(s);
677 aurb->packet = p;
679 urb = &aurb->urb;
681 urb->endpoint = ep;
682 urb->buffer = p->data;
683 urb->buffer_length = p->len;
684 urb->type = USBDEVFS_URB_TYPE_BULK;
685 urb->usercontext = s;
687 ret = ioctl(s->fd, USBDEVFS_SUBMITURB, urb);
689 DPRINTF("husb: data submit. ep 0x%x len %u aurb %p\n",
690 urb->endpoint, p->len, aurb);
692 if (ret < 0) {
693 DPRINTF("husb: submit failed. errno %d\n", errno);
694 async_free(aurb);
696 switch(errno) {
697 case ETIMEDOUT:
698 return USB_RET_NAK;
699 case EPIPE:
700 default:
701 return USB_RET_STALL;
705 usb_defer_packet(p, async_cancel, s);
706 return USB_RET_ASYNC;
709 static int ctrl_error(void)
711 if (errno == ETIMEDOUT) {
712 return USB_RET_NAK;
713 } else {
714 return USB_RET_STALL;
718 static int usb_host_set_address(USBHostDevice *s, int addr)
720 DPRINTF("husb: ctrl set addr %u\n", addr);
721 s->dev.addr = addr;
722 return 0;
725 static int usb_host_set_config(USBHostDevice *s, int config)
727 usb_host_release_interfaces(s);
729 int ret = ioctl(s->fd, USBDEVFS_SETCONFIGURATION, &config);
731 DPRINTF("husb: ctrl set config %d ret %d errno %d\n", config, ret, errno);
733 if (ret < 0) {
734 return ctrl_error();
736 usb_host_claim_interfaces(s, config);
737 return 0;
740 static int usb_host_set_interface(USBHostDevice *s, int iface, int alt)
742 struct usbdevfs_setinterface si;
743 int i, ret;
745 for (i = 1; i <= MAX_ENDPOINTS; i++) {
746 if (is_isoc(s, i)) {
747 usb_host_stop_n_free_iso(s, i);
751 si.interface = iface;
752 si.altsetting = alt;
753 ret = ioctl(s->fd, USBDEVFS_SETINTERFACE, &si);
755 DPRINTF("husb: ctrl set iface %d altset %d ret %d errno %d\n",
756 iface, alt, ret, errno);
758 if (ret < 0) {
759 return ctrl_error();
761 usb_linux_update_endp_table(s);
762 return 0;
765 static int usb_host_handle_control(USBDevice *dev, USBPacket *p,
766 int request, int value, int index, int length, uint8_t *data)
768 USBHostDevice *s = DO_UPCAST(USBHostDevice, dev, dev);
769 struct usbdevfs_urb *urb;
770 AsyncURB *aurb;
771 int ret;
774 * Process certain standard device requests.
775 * These are infrequent and are processed synchronously.
778 /* Note request is (bRequestType << 8) | bRequest */
779 DPRINTF("husb: ctrl type 0x%x req 0x%x val 0x%x index %u len %u\n",
780 request >> 8, request & 0xff, value, index, length);
782 switch (request) {
783 case DeviceOutRequest | USB_REQ_SET_ADDRESS:
784 return usb_host_set_address(s, value);
786 case DeviceOutRequest | USB_REQ_SET_CONFIGURATION:
787 return usb_host_set_config(s, value & 0xff);
789 case InterfaceOutRequest | USB_REQ_SET_INTERFACE:
790 return usb_host_set_interface(s, index, value);
793 /* The rest are asynchronous */
795 if (length > sizeof(dev->data_buf)) {
796 fprintf(stderr, "husb: ctrl buffer too small (%d > %zu)\n",
797 length, sizeof(dev->data_buf));
798 return USB_RET_STALL;
801 aurb = async_alloc(s);
802 aurb->packet = p;
805 * Setup ctrl transfer.
807 * s->ctrl is laid out such that data buffer immediately follows
808 * 'req' struct which is exactly what usbdevfs expects.
810 urb = &aurb->urb;
812 urb->type = USBDEVFS_URB_TYPE_CONTROL;
813 urb->endpoint = p->devep;
815 urb->buffer = &dev->setup_buf;
816 urb->buffer_length = length + 8;
818 urb->usercontext = s;
820 ret = ioctl(s->fd, USBDEVFS_SUBMITURB, urb);
822 DPRINTF("husb: submit ctrl. len %u aurb %p\n", urb->buffer_length, aurb);
824 if (ret < 0) {
825 DPRINTF("husb: submit failed. errno %d\n", errno);
826 async_free(aurb);
828 switch(errno) {
829 case ETIMEDOUT:
830 return USB_RET_NAK;
831 case EPIPE:
832 default:
833 return USB_RET_STALL;
837 usb_defer_packet(p, async_cancel, s);
838 return USB_RET_ASYNC;
841 static int usb_linux_get_configuration(USBHostDevice *s)
843 uint8_t configuration;
844 struct usb_ctrltransfer ct;
845 int ret;
847 if (usb_fs_type == USB_FS_SYS) {
848 char device_name[32], line[1024];
849 int configuration;
851 sprintf(device_name, "%d-%s", s->bus_num, s->port);
853 if (!usb_host_read_file(line, sizeof(line), "bConfigurationValue",
854 device_name)) {
855 goto usbdevfs;
857 if (sscanf(line, "%d", &configuration) != 1) {
858 goto usbdevfs;
860 return configuration;
863 usbdevfs:
864 ct.bRequestType = USB_DIR_IN;
865 ct.bRequest = USB_REQ_GET_CONFIGURATION;
866 ct.wValue = 0;
867 ct.wIndex = 0;
868 ct.wLength = 1;
869 ct.data = &configuration;
870 ct.timeout = 50;
872 ret = ioctl(s->fd, USBDEVFS_CONTROL, &ct);
873 if (ret < 0) {
874 perror("usb_linux_get_configuration");
875 return -1;
878 /* in address state */
879 if (configuration == 0) {
880 return -1;
883 return configuration;
886 static uint8_t usb_linux_get_alt_setting(USBHostDevice *s,
887 uint8_t configuration, uint8_t interface)
889 uint8_t alt_setting;
890 struct usb_ctrltransfer ct;
891 int ret;
893 if (usb_fs_type == USB_FS_SYS) {
894 char device_name[64], line[1024];
895 int alt_setting;
897 sprintf(device_name, "%d-%s:%d.%d", s->bus_num, s->port,
898 (int)configuration, (int)interface);
900 if (!usb_host_read_file(line, sizeof(line), "bAlternateSetting",
901 device_name)) {
902 goto usbdevfs;
904 if (sscanf(line, "%d", &alt_setting) != 1) {
905 goto usbdevfs;
907 return alt_setting;
910 usbdevfs:
911 ct.bRequestType = USB_DIR_IN | USB_RECIP_INTERFACE;
912 ct.bRequest = USB_REQ_GET_INTERFACE;
913 ct.wValue = 0;
914 ct.wIndex = interface;
915 ct.wLength = 1;
916 ct.data = &alt_setting;
917 ct.timeout = 50;
918 ret = ioctl(s->fd, USBDEVFS_CONTROL, &ct);
919 if (ret < 0) {
920 /* Assume alt 0 on error */
921 return 0;
924 return alt_setting;
927 /* returns 1 on problem encountered or 0 for success */
928 static int usb_linux_update_endp_table(USBHostDevice *s)
930 uint8_t *descriptors;
931 uint8_t devep, type, configuration, alt_interface;
932 int interface, length, i;
934 for (i = 0; i < MAX_ENDPOINTS; i++)
935 s->endp_table[i].type = INVALID_EP_TYPE;
937 i = usb_linux_get_configuration(s);
938 if (i < 0)
939 return 1;
940 configuration = i;
942 /* get the desired configuration, interface, and endpoint descriptors
943 * from device description */
944 descriptors = &s->descr[18];
945 length = s->descr_len - 18;
946 i = 0;
948 if (descriptors[i + 1] != USB_DT_CONFIG ||
949 descriptors[i + 5] != configuration) {
950 DPRINTF("invalid descriptor data - configuration\n");
951 return 1;
953 i += descriptors[i];
955 while (i < length) {
956 if (descriptors[i + 1] != USB_DT_INTERFACE ||
957 (descriptors[i + 1] == USB_DT_INTERFACE &&
958 descriptors[i + 4] == 0)) {
959 i += descriptors[i];
960 continue;
963 interface = descriptors[i + 2];
964 alt_interface = usb_linux_get_alt_setting(s, configuration, interface);
966 /* the current interface descriptor is the active interface
967 * and has endpoints */
968 if (descriptors[i + 3] != alt_interface) {
969 i += descriptors[i];
970 continue;
973 /* advance to the endpoints */
974 while (i < length && descriptors[i +1] != USB_DT_ENDPOINT) {
975 i += descriptors[i];
978 if (i >= length)
979 break;
981 while (i < length) {
982 if (descriptors[i + 1] != USB_DT_ENDPOINT) {
983 break;
986 devep = descriptors[i + 2];
987 switch (descriptors[i + 3] & 0x3) {
988 case 0x00:
989 type = USBDEVFS_URB_TYPE_CONTROL;
990 break;
991 case 0x01:
992 type = USBDEVFS_URB_TYPE_ISO;
993 s->endp_table[(devep & 0xf) - 1].max_packet_size =
994 descriptors[i + 4] + (descriptors[i + 5] << 8);
995 break;
996 case 0x02:
997 type = USBDEVFS_URB_TYPE_BULK;
998 break;
999 case 0x03:
1000 type = USBDEVFS_URB_TYPE_INTERRUPT;
1001 break;
1002 default:
1003 DPRINTF("usb_host: malformed endpoint type\n");
1004 type = USBDEVFS_URB_TYPE_BULK;
1006 s->endp_table[(devep & 0xf) - 1].type = type;
1007 s->endp_table[(devep & 0xf) - 1].halted = 0;
1009 i += descriptors[i];
1012 return 0;
1015 static int usb_host_open(USBHostDevice *dev, int bus_num,
1016 int addr, char *port, const char *prod_name)
1018 int fd = -1, ret;
1019 struct usbdevfs_connectinfo ci;
1020 char buf[1024];
1022 if (dev->fd != -1) {
1023 goto fail;
1025 printf("husb: open device %d.%d\n", bus_num, addr);
1027 if (!usb_host_device_path) {
1028 perror("husb: USB Host Device Path not set");
1029 goto fail;
1031 snprintf(buf, sizeof(buf), "%s/%03d/%03d", usb_host_device_path,
1032 bus_num, addr);
1033 fd = open(buf, O_RDWR | O_NONBLOCK);
1034 if (fd < 0) {
1035 perror(buf);
1036 goto fail;
1038 DPRINTF("husb: opened %s\n", buf);
1040 dev->bus_num = bus_num;
1041 dev->addr = addr;
1042 strcpy(dev->port, port);
1043 dev->fd = fd;
1045 /* read the device description */
1046 dev->descr_len = read(fd, dev->descr, sizeof(dev->descr));
1047 if (dev->descr_len <= 0) {
1048 perror("husb: reading device data failed");
1049 goto fail;
1052 #ifdef DEBUG
1054 int x;
1055 printf("=== begin dumping device descriptor data ===\n");
1056 for (x = 0; x < dev->descr_len; x++) {
1057 printf("%02x ", dev->descr[x]);
1059 printf("\n=== end dumping device descriptor data ===\n");
1061 #endif
1065 * Initial configuration is -1 which makes us claim first
1066 * available config. We used to start with 1, which does not
1067 * always work. I've seen devices where first config starts
1068 * with 2.
1070 if (!usb_host_claim_interfaces(dev, -1)) {
1071 goto fail;
1074 ret = ioctl(fd, USBDEVFS_CONNECTINFO, &ci);
1075 if (ret < 0) {
1076 perror("usb_host_device_open: USBDEVFS_CONNECTINFO");
1077 goto fail;
1080 printf("husb: grabbed usb device %d.%d\n", bus_num, addr);
1082 ret = usb_linux_update_endp_table(dev);
1083 if (ret) {
1084 goto fail;
1087 if (ci.slow) {
1088 dev->dev.speed = USB_SPEED_LOW;
1089 } else {
1090 dev->dev.speed = USB_SPEED_HIGH;
1093 if (!prod_name || prod_name[0] == '\0') {
1094 snprintf(dev->dev.product_desc, sizeof(dev->dev.product_desc),
1095 "host:%d.%d", bus_num, addr);
1096 } else {
1097 pstrcpy(dev->dev.product_desc, sizeof(dev->dev.product_desc),
1098 prod_name);
1101 /* USB devio uses 'write' flag to check for async completions */
1102 qemu_set_fd_handler(dev->fd, NULL, async_complete, dev);
1104 usb_device_attach(&dev->dev);
1105 return 0;
1107 fail:
1108 dev->fd = -1;
1109 if (fd != -1) {
1110 close(fd);
1112 return -1;
1115 static int usb_host_close(USBHostDevice *dev)
1117 int i;
1119 if (dev->fd == -1) {
1120 return -1;
1123 qemu_set_fd_handler(dev->fd, NULL, NULL, NULL);
1124 dev->closing = 1;
1125 for (i = 1; i <= MAX_ENDPOINTS; i++) {
1126 if (is_isoc(dev, i)) {
1127 usb_host_stop_n_free_iso(dev, i);
1130 async_complete(dev);
1131 dev->closing = 0;
1132 usb_device_detach(&dev->dev);
1133 ioctl(dev->fd, USBDEVFS_RESET);
1134 close(dev->fd);
1135 dev->fd = -1;
1136 return 0;
1139 static void usb_host_exit_notifier(struct Notifier* n)
1141 USBHostDevice *s = container_of(n, USBHostDevice, exit);
1143 if (s->fd != -1) {
1144 ioctl(s->fd, USBDEVFS_RESET);
1148 static int usb_host_initfn(USBDevice *dev)
1150 USBHostDevice *s = DO_UPCAST(USBHostDevice, dev, dev);
1152 dev->auto_attach = 0;
1153 s->fd = -1;
1154 QTAILQ_INSERT_TAIL(&hostdevs, s, next);
1155 s->exit.notify = usb_host_exit_notifier;
1156 qemu_add_exit_notifier(&s->exit);
1157 usb_host_auto_check(NULL);
1158 return 0;
1161 static struct USBDeviceInfo usb_host_dev_info = {
1162 .product_desc = "USB Host Device",
1163 .qdev.name = "usb-host",
1164 .qdev.size = sizeof(USBHostDevice),
1165 .init = usb_host_initfn,
1166 .handle_packet = usb_generic_handle_packet,
1167 .handle_data = usb_host_handle_data,
1168 .handle_control = usb_host_handle_control,
1169 .handle_reset = usb_host_handle_reset,
1170 .handle_destroy = usb_host_handle_destroy,
1171 .usbdevice_name = "host",
1172 .usbdevice_init = usb_host_device_open,
1173 .qdev.props = (Property[]) {
1174 DEFINE_PROP_UINT32("hostbus", USBHostDevice, match.bus_num, 0),
1175 DEFINE_PROP_UINT32("hostaddr", USBHostDevice, match.addr, 0),
1176 DEFINE_PROP_STRING("hostport", USBHostDevice, match.port),
1177 DEFINE_PROP_HEX32("vendorid", USBHostDevice, match.vendor_id, 0),
1178 DEFINE_PROP_HEX32("productid", USBHostDevice, match.product_id, 0),
1179 DEFINE_PROP_END_OF_LIST(),
1183 static void usb_host_register_devices(void)
1185 usb_qdev_register(&usb_host_dev_info);
1187 device_init(usb_host_register_devices)
1189 USBDevice *usb_host_device_open(const char *devname)
1191 struct USBAutoFilter filter;
1192 USBDevice *dev;
1193 char *p;
1195 dev = usb_create(NULL /* FIXME */, "usb-host");
1197 if (strstr(devname, "auto:")) {
1198 if (parse_filter(devname, &filter) < 0) {
1199 goto fail;
1201 } else {
1202 if ((p = strchr(devname, '.'))) {
1203 filter.bus_num = strtoul(devname, NULL, 0);
1204 filter.addr = strtoul(p + 1, NULL, 0);
1205 filter.vendor_id = 0;
1206 filter.product_id = 0;
1207 } else if ((p = strchr(devname, ':'))) {
1208 filter.bus_num = 0;
1209 filter.addr = 0;
1210 filter.vendor_id = strtoul(devname, NULL, 16);
1211 filter.product_id = strtoul(p + 1, NULL, 16);
1212 } else {
1213 goto fail;
1217 qdev_prop_set_uint32(&dev->qdev, "hostbus", filter.bus_num);
1218 qdev_prop_set_uint32(&dev->qdev, "hostaddr", filter.addr);
1219 qdev_prop_set_uint32(&dev->qdev, "vendorid", filter.vendor_id);
1220 qdev_prop_set_uint32(&dev->qdev, "productid", filter.product_id);
1221 qdev_init_nofail(&dev->qdev);
1222 return dev;
1224 fail:
1225 qdev_free(&dev->qdev);
1226 return NULL;
1229 int usb_host_device_close(const char *devname)
1231 #if 0
1232 char product_name[PRODUCT_NAME_SZ];
1233 int bus_num, addr;
1234 USBHostDevice *s;
1236 if (strstr(devname, "auto:")) {
1237 return usb_host_auto_del(devname);
1239 if (usb_host_find_device(&bus_num, &addr, product_name,
1240 sizeof(product_name), devname) < 0) {
1241 return -1;
1243 s = hostdev_find(bus_num, addr);
1244 if (s) {
1245 usb_device_delete_addr(s->bus_num, s->dev.addr);
1246 return 0;
1248 #endif
1250 return -1;
1253 static int get_tag_value(char *buf, int buf_size,
1254 const char *str, const char *tag,
1255 const char *stopchars)
1257 const char *p;
1258 char *q;
1259 p = strstr(str, tag);
1260 if (!p) {
1261 return -1;
1263 p += strlen(tag);
1264 while (qemu_isspace(*p)) {
1265 p++;
1267 q = buf;
1268 while (*p != '\0' && !strchr(stopchars, *p)) {
1269 if ((q - buf) < (buf_size - 1)) {
1270 *q++ = *p;
1272 p++;
1274 *q = '\0';
1275 return q - buf;
1279 * Use /proc/bus/usb/devices or /dev/bus/usb/devices file to determine
1280 * host's USB devices. This is legacy support since many distributions
1281 * are moving to /sys/bus/usb
1283 static int usb_host_scan_dev(void *opaque, USBScanFunc *func)
1285 FILE *f = NULL;
1286 char line[1024];
1287 char buf[1024];
1288 int bus_num, addr, speed, device_count, class_id, product_id, vendor_id;
1289 char product_name[512];
1290 int ret = 0;
1292 if (!usb_host_device_path) {
1293 perror("husb: USB Host Device Path not set");
1294 goto the_end;
1296 snprintf(line, sizeof(line), "%s/devices", usb_host_device_path);
1297 f = fopen(line, "r");
1298 if (!f) {
1299 perror("husb: cannot open devices file");
1300 goto the_end;
1303 device_count = 0;
1304 bus_num = addr = speed = class_id = product_id = vendor_id = 0;
1305 for(;;) {
1306 if (fgets(line, sizeof(line), f) == NULL) {
1307 break;
1309 if (strlen(line) > 0) {
1310 line[strlen(line) - 1] = '\0';
1312 if (line[0] == 'T' && line[1] == ':') {
1313 if (device_count && (vendor_id || product_id)) {
1314 /* New device. Add the previously discovered device. */
1315 ret = func(opaque, bus_num, addr, 0, class_id, vendor_id,
1316 product_id, product_name, speed);
1317 if (ret) {
1318 goto the_end;
1321 if (get_tag_value(buf, sizeof(buf), line, "Bus=", " ") < 0) {
1322 goto fail;
1324 bus_num = atoi(buf);
1325 if (get_tag_value(buf, sizeof(buf), line, "Dev#=", " ") < 0) {
1326 goto fail;
1328 addr = atoi(buf);
1329 if (get_tag_value(buf, sizeof(buf), line, "Spd=", " ") < 0) {
1330 goto fail;
1332 if (!strcmp(buf, "480")) {
1333 speed = USB_SPEED_HIGH;
1334 } else if (!strcmp(buf, "1.5")) {
1335 speed = USB_SPEED_LOW;
1336 } else {
1337 speed = USB_SPEED_FULL;
1339 product_name[0] = '\0';
1340 class_id = 0xff;
1341 device_count++;
1342 product_id = 0;
1343 vendor_id = 0;
1344 } else if (line[0] == 'P' && line[1] == ':') {
1345 if (get_tag_value(buf, sizeof(buf), line, "Vendor=", " ") < 0) {
1346 goto fail;
1348 vendor_id = strtoul(buf, NULL, 16);
1349 if (get_tag_value(buf, sizeof(buf), line, "ProdID=", " ") < 0) {
1350 goto fail;
1352 product_id = strtoul(buf, NULL, 16);
1353 } else if (line[0] == 'S' && line[1] == ':') {
1354 if (get_tag_value(buf, sizeof(buf), line, "Product=", "") < 0) {
1355 goto fail;
1357 pstrcpy(product_name, sizeof(product_name), buf);
1358 } else if (line[0] == 'D' && line[1] == ':') {
1359 if (get_tag_value(buf, sizeof(buf), line, "Cls=", " (") < 0) {
1360 goto fail;
1362 class_id = strtoul(buf, NULL, 16);
1364 fail: ;
1366 if (device_count && (vendor_id || product_id)) {
1367 /* Add the last device. */
1368 ret = func(opaque, bus_num, addr, 0, class_id, vendor_id,
1369 product_id, product_name, speed);
1371 the_end:
1372 if (f) {
1373 fclose(f);
1375 return ret;
1379 * Read sys file-system device file
1381 * @line address of buffer to put file contents in
1382 * @line_size size of line
1383 * @device_file path to device file (printf format string)
1384 * @device_name device being opened (inserted into device_file)
1386 * @return 0 failed, 1 succeeded ('line' contains data)
1388 static int usb_host_read_file(char *line, size_t line_size,
1389 const char *device_file, const char *device_name)
1391 FILE *f;
1392 int ret = 0;
1393 char filename[PATH_MAX];
1395 snprintf(filename, PATH_MAX, USBSYSBUS_PATH "/devices/%s/%s", device_name,
1396 device_file);
1397 f = fopen(filename, "r");
1398 if (f) {
1399 ret = fgets(line, line_size, f) != NULL;
1400 fclose(f);
1403 return ret;
1407 * Use /sys/bus/usb/devices/ directory to determine host's USB
1408 * devices.
1410 * This code is based on Robert Schiele's original patches posted to
1411 * the Novell bug-tracker https://bugzilla.novell.com/show_bug.cgi?id=241950
1413 static int usb_host_scan_sys(void *opaque, USBScanFunc *func)
1415 DIR *dir = NULL;
1416 char line[1024];
1417 int bus_num, addr, speed, class_id, product_id, vendor_id;
1418 int ret = 0;
1419 char port[MAX_PORTLEN];
1420 char product_name[512];
1421 struct dirent *de;
1423 dir = opendir(USBSYSBUS_PATH "/devices");
1424 if (!dir) {
1425 perror("husb: cannot open devices directory");
1426 goto the_end;
1429 while ((de = readdir(dir))) {
1430 if (de->d_name[0] != '.' && !strchr(de->d_name, ':')) {
1431 if (sscanf(de->d_name, "%d-%7[0-9.]", &bus_num, port) < 2) {
1432 continue;
1435 if (!usb_host_read_file(line, sizeof(line), "devnum", de->d_name)) {
1436 goto the_end;
1438 if (sscanf(line, "%d", &addr) != 1) {
1439 goto the_end;
1441 if (!usb_host_read_file(line, sizeof(line), "bDeviceClass",
1442 de->d_name)) {
1443 goto the_end;
1445 if (sscanf(line, "%x", &class_id) != 1) {
1446 goto the_end;
1449 if (!usb_host_read_file(line, sizeof(line), "idVendor",
1450 de->d_name)) {
1451 goto the_end;
1453 if (sscanf(line, "%x", &vendor_id) != 1) {
1454 goto the_end;
1456 if (!usb_host_read_file(line, sizeof(line), "idProduct",
1457 de->d_name)) {
1458 goto the_end;
1460 if (sscanf(line, "%x", &product_id) != 1) {
1461 goto the_end;
1463 if (!usb_host_read_file(line, sizeof(line), "product",
1464 de->d_name)) {
1465 *product_name = 0;
1466 } else {
1467 if (strlen(line) > 0) {
1468 line[strlen(line) - 1] = '\0';
1470 pstrcpy(product_name, sizeof(product_name), line);
1473 if (!usb_host_read_file(line, sizeof(line), "speed", de->d_name)) {
1474 goto the_end;
1476 if (!strcmp(line, "480\n")) {
1477 speed = USB_SPEED_HIGH;
1478 } else if (!strcmp(line, "1.5\n")) {
1479 speed = USB_SPEED_LOW;
1480 } else {
1481 speed = USB_SPEED_FULL;
1484 ret = func(opaque, bus_num, addr, port, class_id, vendor_id,
1485 product_id, product_name, speed);
1486 if (ret) {
1487 goto the_end;
1491 the_end:
1492 if (dir) {
1493 closedir(dir);
1495 return ret;
1499 * Determine how to access the host's USB devices and call the
1500 * specific support function.
1502 static int usb_host_scan(void *opaque, USBScanFunc *func)
1504 Monitor *mon = cur_mon;
1505 FILE *f = NULL;
1506 DIR *dir = NULL;
1507 int ret = 0;
1508 const char *fs_type[] = {"unknown", "proc", "dev", "sys"};
1509 char devpath[PATH_MAX];
1511 /* only check the host once */
1512 if (!usb_fs_type) {
1513 dir = opendir(USBSYSBUS_PATH "/devices");
1514 if (dir) {
1515 /* devices found in /dev/bus/usb/ (yes - not a mistake!) */
1516 strcpy(devpath, USBDEVBUS_PATH);
1517 usb_fs_type = USB_FS_SYS;
1518 closedir(dir);
1519 DPRINTF(USBDBG_DEVOPENED, USBSYSBUS_PATH);
1520 goto found_devices;
1522 f = fopen(USBPROCBUS_PATH "/devices", "r");
1523 if (f) {
1524 /* devices found in /proc/bus/usb/ */
1525 strcpy(devpath, USBPROCBUS_PATH);
1526 usb_fs_type = USB_FS_PROC;
1527 fclose(f);
1528 DPRINTF(USBDBG_DEVOPENED, USBPROCBUS_PATH);
1529 goto found_devices;
1531 /* try additional methods if an access method hasn't been found yet */
1532 f = fopen(USBDEVBUS_PATH "/devices", "r");
1533 if (f) {
1534 /* devices found in /dev/bus/usb/ */
1535 strcpy(devpath, USBDEVBUS_PATH);
1536 usb_fs_type = USB_FS_DEV;
1537 fclose(f);
1538 DPRINTF(USBDBG_DEVOPENED, USBDEVBUS_PATH);
1539 goto found_devices;
1541 found_devices:
1542 if (!usb_fs_type) {
1543 if (mon) {
1544 monitor_printf(mon, "husb: unable to access USB devices\n");
1546 return -ENOENT;
1549 /* the module setting (used later for opening devices) */
1550 usb_host_device_path = qemu_mallocz(strlen(devpath)+1);
1551 strcpy(usb_host_device_path, devpath);
1552 if (mon) {
1553 monitor_printf(mon, "husb: using %s file-system with %s\n",
1554 fs_type[usb_fs_type], usb_host_device_path);
1558 switch (usb_fs_type) {
1559 case USB_FS_PROC:
1560 case USB_FS_DEV:
1561 ret = usb_host_scan_dev(opaque, func);
1562 break;
1563 case USB_FS_SYS:
1564 ret = usb_host_scan_sys(opaque, func);
1565 break;
1566 default:
1567 ret = -EINVAL;
1568 break;
1570 return ret;
1573 static QEMUTimer *usb_auto_timer;
1575 static int usb_host_auto_scan(void *opaque, int bus_num, int addr, char *port,
1576 int class_id, int vendor_id, int product_id,
1577 const char *product_name, int speed)
1579 struct USBAutoFilter *f;
1580 struct USBHostDevice *s;
1582 /* Ignore hubs */
1583 if (class_id == 9)
1584 return 0;
1586 QTAILQ_FOREACH(s, &hostdevs, next) {
1587 f = &s->match;
1589 if (f->bus_num > 0 && f->bus_num != bus_num) {
1590 continue;
1592 if (f->addr > 0 && f->addr != addr) {
1593 continue;
1595 if (f->port != NULL && (port == NULL || strcmp(f->port, port) != 0)) {
1596 continue;
1599 if (f->vendor_id > 0 && f->vendor_id != vendor_id) {
1600 continue;
1603 if (f->product_id > 0 && f->product_id != product_id) {
1604 continue;
1606 /* We got a match */
1608 /* Already attached ? */
1609 if (s->fd != -1) {
1610 return 0;
1612 DPRINTF("husb: auto open: bus_num %d addr %d\n", bus_num, addr);
1614 usb_host_open(s, bus_num, addr, port, product_name);
1617 return 0;
1620 static void usb_host_auto_check(void *unused)
1622 struct USBHostDevice *s;
1623 int unconnected = 0;
1625 usb_host_scan(NULL, usb_host_auto_scan);
1627 QTAILQ_FOREACH(s, &hostdevs, next) {
1628 if (s->fd == -1) {
1629 unconnected++;
1633 if (unconnected == 0) {
1634 /* nothing to watch */
1635 if (usb_auto_timer) {
1636 qemu_del_timer(usb_auto_timer);
1638 return;
1641 if (!usb_auto_timer) {
1642 usb_auto_timer = qemu_new_timer_ms(rt_clock, usb_host_auto_check, NULL);
1643 if (!usb_auto_timer) {
1644 return;
1647 qemu_mod_timer(usb_auto_timer, qemu_get_clock_ms(rt_clock) + 2000);
1651 * Autoconnect filter
1652 * Format:
1653 * auto:bus:dev[:vid:pid]
1654 * auto:bus.dev[:vid:pid]
1656 * bus - bus number (dec, * means any)
1657 * dev - device number (dec, * means any)
1658 * vid - vendor id (hex, * means any)
1659 * pid - product id (hex, * means any)
1661 * See 'lsusb' output.
1663 static int parse_filter(const char *spec, struct USBAutoFilter *f)
1665 enum { BUS, DEV, VID, PID, DONE };
1666 const char *p = spec;
1667 int i;
1669 f->bus_num = 0;
1670 f->addr = 0;
1671 f->vendor_id = 0;
1672 f->product_id = 0;
1674 for (i = BUS; i < DONE; i++) {
1675 p = strpbrk(p, ":.");
1676 if (!p) {
1677 break;
1679 p++;
1681 if (*p == '*') {
1682 continue;
1684 switch(i) {
1685 case BUS: f->bus_num = strtol(p, NULL, 10); break;
1686 case DEV: f->addr = strtol(p, NULL, 10); break;
1687 case VID: f->vendor_id = strtol(p, NULL, 16); break;
1688 case PID: f->product_id = strtol(p, NULL, 16); break;
1692 if (i < DEV) {
1693 fprintf(stderr, "husb: invalid auto filter spec %s\n", spec);
1694 return -1;
1697 return 0;
1700 /**********************/
1701 /* USB host device info */
1703 struct usb_class_info {
1704 int class;
1705 const char *class_name;
1708 static const struct usb_class_info usb_class_info[] = {
1709 { USB_CLASS_AUDIO, "Audio"},
1710 { USB_CLASS_COMM, "Communication"},
1711 { USB_CLASS_HID, "HID"},
1712 { USB_CLASS_HUB, "Hub" },
1713 { USB_CLASS_PHYSICAL, "Physical" },
1714 { USB_CLASS_PRINTER, "Printer" },
1715 { USB_CLASS_MASS_STORAGE, "Storage" },
1716 { USB_CLASS_CDC_DATA, "Data" },
1717 { USB_CLASS_APP_SPEC, "Application Specific" },
1718 { USB_CLASS_VENDOR_SPEC, "Vendor Specific" },
1719 { USB_CLASS_STILL_IMAGE, "Still Image" },
1720 { USB_CLASS_CSCID, "Smart Card" },
1721 { USB_CLASS_CONTENT_SEC, "Content Security" },
1722 { -1, NULL }
1725 static const char *usb_class_str(uint8_t class)
1727 const struct usb_class_info *p;
1728 for(p = usb_class_info; p->class != -1; p++) {
1729 if (p->class == class) {
1730 break;
1733 return p->class_name;
1736 static void usb_info_device(Monitor *mon, int bus_num, int addr, char *port,
1737 int class_id, int vendor_id, int product_id,
1738 const char *product_name,
1739 int speed)
1741 const char *class_str, *speed_str;
1743 switch(speed) {
1744 case USB_SPEED_LOW:
1745 speed_str = "1.5";
1746 break;
1747 case USB_SPEED_FULL:
1748 speed_str = "12";
1749 break;
1750 case USB_SPEED_HIGH:
1751 speed_str = "480";
1752 break;
1753 default:
1754 speed_str = "?";
1755 break;
1758 monitor_printf(mon, " Bus %d, Addr %d, Port %s, Speed %s Mb/s\n",
1759 bus_num, addr, port, speed_str);
1760 class_str = usb_class_str(class_id);
1761 if (class_str) {
1762 monitor_printf(mon, " %s:", class_str);
1763 } else {
1764 monitor_printf(mon, " Class %02x:", class_id);
1766 monitor_printf(mon, " USB device %04x:%04x", vendor_id, product_id);
1767 if (product_name[0] != '\0') {
1768 monitor_printf(mon, ", %s", product_name);
1770 monitor_printf(mon, "\n");
1773 static int usb_host_info_device(void *opaque, int bus_num, int addr,
1774 char *path, int class_id,
1775 int vendor_id, int product_id,
1776 const char *product_name,
1777 int speed)
1779 Monitor *mon = opaque;
1781 usb_info_device(mon, bus_num, addr, path, class_id, vendor_id, product_id,
1782 product_name, speed);
1783 return 0;
1786 static void dec2str(int val, char *str, size_t size)
1788 if (val == 0) {
1789 snprintf(str, size, "*");
1790 } else {
1791 snprintf(str, size, "%d", val);
1795 static void hex2str(int val, char *str, size_t size)
1797 if (val == 0) {
1798 snprintf(str, size, "*");
1799 } else {
1800 snprintf(str, size, "%04x", val);
1804 void usb_host_info(Monitor *mon)
1806 struct USBAutoFilter *f;
1807 struct USBHostDevice *s;
1809 usb_host_scan(mon, usb_host_info_device);
1811 if (QTAILQ_EMPTY(&hostdevs)) {
1812 return;
1815 monitor_printf(mon, " Auto filters:\n");
1816 QTAILQ_FOREACH(s, &hostdevs, next) {
1817 char bus[10], addr[10], vid[10], pid[10];
1818 f = &s->match;
1819 dec2str(f->bus_num, bus, sizeof(bus));
1820 dec2str(f->addr, addr, sizeof(addr));
1821 hex2str(f->vendor_id, vid, sizeof(vid));
1822 hex2str(f->product_id, pid, sizeof(pid));
1823 monitor_printf(mon, " Bus %s, Addr %s, Port %s, ID %s:%s\n",
1824 bus, addr, f->port ? f->port : "*", vid, pid);