usb-host: allow emulated (non-async) control requests without USBPacket
[qemu/ar7.git] / hw / usb / host-linux.c
blob44f1a64b35cc05214747a1a1e6be93d4ec0fef0f
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"
37 #include "trace.h"
39 #include <dirent.h>
40 #include <sys/ioctl.h>
42 #include <linux/usbdevice_fs.h>
43 #include <linux/version.h>
44 #include "hw/usb.h"
45 #include "hw/usb/desc.h"
47 /* We redefine it to avoid version problems */
48 struct usb_ctrltransfer {
49 uint8_t bRequestType;
50 uint8_t bRequest;
51 uint16_t wValue;
52 uint16_t wIndex;
53 uint16_t wLength;
54 uint32_t timeout;
55 void *data;
58 typedef int USBScanFunc(void *opaque, int bus_num, int addr, const char *port,
59 int class_id, int vendor_id, int product_id,
60 const char *product_name, int speed);
62 //#define DEBUG
64 #ifdef DEBUG
65 #define DPRINTF printf
66 #else
67 #define DPRINTF(...)
68 #endif
70 #define PRODUCT_NAME_SZ 32
71 #define MAX_PORTLEN 16
73 /* endpoint association data */
74 #define ISO_FRAME_DESC_PER_URB 32
76 /* devio.c limits single requests to 16k */
77 #define MAX_USBFS_BUFFER_SIZE 16384
79 typedef struct AsyncURB AsyncURB;
81 struct endp_data {
82 uint8_t halted;
83 uint8_t iso_started;
84 AsyncURB *iso_urb;
85 int iso_urb_idx;
86 int iso_buffer_used;
87 int inflight;
90 struct USBAutoFilter {
91 uint32_t bus_num;
92 uint32_t addr;
93 char *port;
94 uint32_t vendor_id;
95 uint32_t product_id;
98 enum USBHostDeviceOptions {
99 USB_HOST_OPT_PIPELINE,
102 typedef struct USBHostDevice {
103 USBDevice dev;
104 int fd;
105 int hub_fd;
106 int hub_port;
108 uint8_t descr[8192];
109 int descr_len;
110 int closing;
111 uint32_t iso_urb_count;
112 uint32_t options;
113 Notifier exit;
114 QEMUBH *bh;
116 struct endp_data ep_in[USB_MAX_ENDPOINTS];
117 struct endp_data ep_out[USB_MAX_ENDPOINTS];
118 QLIST_HEAD(, AsyncURB) aurbs;
120 /* Host side address */
121 int bus_num;
122 int addr;
123 char port[MAX_PORTLEN];
124 struct USBAutoFilter match;
125 int32_t bootindex;
126 int seen, errcount;
128 QTAILQ_ENTRY(USBHostDevice) next;
129 } USBHostDevice;
131 static QTAILQ_HEAD(, USBHostDevice) hostdevs = QTAILQ_HEAD_INITIALIZER(hostdevs);
133 static int usb_host_close(USBHostDevice *dev);
134 static int parse_filter(const char *spec, struct USBAutoFilter *f);
135 static void usb_host_auto_check(void *unused);
136 static int usb_host_read_file(char *line, size_t line_size,
137 const char *device_file, const char *device_name);
138 static int usb_linux_update_endp_table(USBHostDevice *s);
140 static int usb_host_usbfs_type(USBHostDevice *s, USBPacket *p)
142 static const int usbfs[] = {
143 [USB_ENDPOINT_XFER_CONTROL] = USBDEVFS_URB_TYPE_CONTROL,
144 [USB_ENDPOINT_XFER_ISOC] = USBDEVFS_URB_TYPE_ISO,
145 [USB_ENDPOINT_XFER_BULK] = USBDEVFS_URB_TYPE_BULK,
146 [USB_ENDPOINT_XFER_INT] = USBDEVFS_URB_TYPE_INTERRUPT,
148 uint8_t type = p->ep->type;
149 assert(type < ARRAY_SIZE(usbfs));
150 return usbfs[type];
153 static int usb_host_do_reset(USBHostDevice *dev)
155 struct timeval s, e;
156 uint32_t usecs;
157 int ret;
159 gettimeofday(&s, NULL);
160 ret = ioctl(dev->fd, USBDEVFS_RESET);
161 gettimeofday(&e, NULL);
162 usecs = (e.tv_sec - s.tv_sec) * 1000000;
163 usecs += e.tv_usec - s.tv_usec;
164 if (usecs > 1000000) {
165 /* more than a second, something is fishy, broken usb device? */
166 fprintf(stderr, "husb: device %d:%d reset took %d.%06d seconds\n",
167 dev->bus_num, dev->addr, usecs / 1000000, usecs % 1000000);
169 return ret;
172 static struct endp_data *get_endp(USBHostDevice *s, int pid, int ep)
174 struct endp_data *eps = pid == USB_TOKEN_IN ? s->ep_in : s->ep_out;
175 assert(pid == USB_TOKEN_IN || pid == USB_TOKEN_OUT);
176 assert(ep > 0 && ep <= USB_MAX_ENDPOINTS);
177 return eps + ep - 1;
180 static int is_isoc(USBHostDevice *s, int pid, int ep)
182 return usb_ep_get_type(&s->dev, pid, ep) == USB_ENDPOINT_XFER_ISOC;
185 static int is_valid(USBHostDevice *s, int pid, int ep)
187 return usb_ep_get_type(&s->dev, pid, ep) != USB_ENDPOINT_XFER_INVALID;
190 static int is_halted(USBHostDevice *s, int pid, int ep)
192 return get_endp(s, pid, ep)->halted;
195 static void clear_halt(USBHostDevice *s, int pid, int ep)
197 trace_usb_host_ep_clear_halt(s->bus_num, s->addr, ep);
198 get_endp(s, pid, ep)->halted = 0;
201 static void set_halt(USBHostDevice *s, int pid, int ep)
203 if (ep != 0) {
204 trace_usb_host_ep_set_halt(s->bus_num, s->addr, ep);
205 get_endp(s, pid, ep)->halted = 1;
209 static int is_iso_started(USBHostDevice *s, int pid, int ep)
211 return get_endp(s, pid, ep)->iso_started;
214 static void clear_iso_started(USBHostDevice *s, int pid, int ep)
216 trace_usb_host_iso_stop(s->bus_num, s->addr, ep);
217 get_endp(s, pid, ep)->iso_started = 0;
220 static void set_iso_started(USBHostDevice *s, int pid, int ep)
222 struct endp_data *e = get_endp(s, pid, ep);
224 trace_usb_host_iso_start(s->bus_num, s->addr, ep);
225 if (!e->iso_started) {
226 e->iso_started = 1;
227 e->inflight = 0;
231 static int change_iso_inflight(USBHostDevice *s, int pid, int ep, int value)
233 struct endp_data *e = get_endp(s, pid, ep);
235 e->inflight += value;
236 return e->inflight;
239 static void set_iso_urb(USBHostDevice *s, int pid, int ep, AsyncURB *iso_urb)
241 get_endp(s, pid, ep)->iso_urb = iso_urb;
244 static AsyncURB *get_iso_urb(USBHostDevice *s, int pid, int ep)
246 return get_endp(s, pid, ep)->iso_urb;
249 static void set_iso_urb_idx(USBHostDevice *s, int pid, int ep, int i)
251 get_endp(s, pid, ep)->iso_urb_idx = i;
254 static int get_iso_urb_idx(USBHostDevice *s, int pid, int ep)
256 return get_endp(s, pid, ep)->iso_urb_idx;
259 static void set_iso_buffer_used(USBHostDevice *s, int pid, int ep, int i)
261 get_endp(s, pid, ep)->iso_buffer_used = i;
264 static int get_iso_buffer_used(USBHostDevice *s, int pid, int ep)
266 return get_endp(s, pid, ep)->iso_buffer_used;
270 * Async URB state.
271 * We always allocate iso packet descriptors even for bulk transfers
272 * to simplify allocation and casts.
274 struct AsyncURB
276 struct usbdevfs_urb urb;
277 struct usbdevfs_iso_packet_desc isocpd[ISO_FRAME_DESC_PER_URB];
278 USBHostDevice *hdev;
279 QLIST_ENTRY(AsyncURB) next;
281 /* For regular async urbs */
282 USBPacket *packet;
283 int more; /* large transfer, more urbs follow */
285 /* For buffered iso handling */
286 int iso_frame_idx; /* -1 means in flight */
289 static AsyncURB *async_alloc(USBHostDevice *s)
291 AsyncURB *aurb = g_malloc0(sizeof(AsyncURB));
292 aurb->hdev = s;
293 QLIST_INSERT_HEAD(&s->aurbs, aurb, next);
294 return aurb;
297 static void async_free(AsyncURB *aurb)
299 QLIST_REMOVE(aurb, next);
300 g_free(aurb);
303 static void do_disconnect(USBHostDevice *s)
305 usb_host_close(s);
306 usb_host_auto_check(NULL);
309 static void async_complete(void *opaque)
311 USBHostDevice *s = opaque;
312 AsyncURB *aurb;
313 int urbs = 0;
315 while (1) {
316 USBPacket *p;
318 int r = ioctl(s->fd, USBDEVFS_REAPURBNDELAY, &aurb);
319 if (r < 0) {
320 if (errno == EAGAIN) {
321 if (urbs > 2) {
322 /* indicates possible latency issues */
323 trace_usb_host_iso_many_urbs(s->bus_num, s->addr, urbs);
325 return;
327 if (errno == ENODEV) {
328 if (!s->closing) {
329 trace_usb_host_disconnect(s->bus_num, s->addr);
330 do_disconnect(s);
332 return;
335 perror("USBDEVFS_REAPURBNDELAY");
336 return;
339 DPRINTF("husb: async completed. aurb %p status %d alen %d\n",
340 aurb, aurb->urb.status, aurb->urb.actual_length);
342 /* If this is a buffered iso urb mark it as complete and don't do
343 anything else (it is handled further in usb_host_handle_iso_data) */
344 if (aurb->iso_frame_idx == -1) {
345 int inflight;
346 int pid = (aurb->urb.endpoint & USB_DIR_IN) ?
347 USB_TOKEN_IN : USB_TOKEN_OUT;
348 int ep = aurb->urb.endpoint & 0xf;
349 if (aurb->urb.status == -EPIPE) {
350 set_halt(s, pid, ep);
352 aurb->iso_frame_idx = 0;
353 urbs++;
354 inflight = change_iso_inflight(s, pid, ep, -1);
355 if (inflight == 0 && is_iso_started(s, pid, ep)) {
356 /* can be latency issues, or simply end of stream */
357 trace_usb_host_iso_out_of_bufs(s->bus_num, s->addr, ep);
359 continue;
362 p = aurb->packet;
363 trace_usb_host_urb_complete(s->bus_num, s->addr, aurb, aurb->urb.status,
364 aurb->urb.actual_length, aurb->more);
366 if (p) {
367 switch (aurb->urb.status) {
368 case 0:
369 p->result += aurb->urb.actual_length;
370 break;
372 case -EPIPE:
373 set_halt(s, p->pid, p->ep->nr);
374 p->result = USB_RET_STALL;
375 break;
377 case -EOVERFLOW:
378 p->result = USB_RET_BABBLE;
379 break;
381 default:
382 p->result = USB_RET_IOERROR;
383 break;
386 if (aurb->urb.type == USBDEVFS_URB_TYPE_CONTROL) {
387 trace_usb_host_req_complete(s->bus_num, s->addr, p, p->result);
388 usb_generic_async_ctrl_complete(&s->dev, p);
389 } else if (!aurb->more) {
390 trace_usb_host_req_complete(s->bus_num, s->addr, p, p->result);
391 usb_packet_complete(&s->dev, p);
395 async_free(aurb);
399 static void usb_host_async_cancel(USBDevice *dev, USBPacket *p)
401 USBHostDevice *s = DO_UPCAST(USBHostDevice, dev, dev);
402 AsyncURB *aurb;
404 trace_usb_host_req_canceled(s->bus_num, s->addr, p);
406 QLIST_FOREACH(aurb, &s->aurbs, next) {
407 if (p != aurb->packet) {
408 continue;
411 trace_usb_host_urb_canceled(s->bus_num, s->addr, aurb);
413 /* Mark it as dead (see async_complete above) */
414 aurb->packet = NULL;
416 int r = ioctl(s->fd, USBDEVFS_DISCARDURB, aurb);
417 if (r < 0) {
418 DPRINTF("husb: async. discard urb failed errno %d\n", errno);
423 static int usb_host_open_device(int bus, int addr)
425 const char *usbfs = NULL;
426 char filename[32];
427 struct stat st;
428 int fd, rc;
430 rc = stat("/dev/bus/usb", &st);
431 if (rc == 0 && S_ISDIR(st.st_mode)) {
432 /* udev-created device nodes available */
433 usbfs = "/dev/bus/usb";
434 } else {
435 /* fallback: usbfs mounted below /proc */
436 usbfs = "/proc/bus/usb";
439 snprintf(filename, sizeof(filename), "%s/%03d/%03d",
440 usbfs, bus, addr);
441 fd = open(filename, O_RDWR | O_NONBLOCK);
442 if (fd < 0) {
443 fprintf(stderr, "husb: open %s: %s\n", filename, strerror(errno));
445 return fd;
448 static int usb_host_claim_port(USBHostDevice *s)
450 #ifdef USBDEVFS_CLAIM_PORT
451 char *h, hub_name[64], line[1024];
452 int hub_addr, ret;
454 snprintf(hub_name, sizeof(hub_name), "%d-%s",
455 s->match.bus_num, s->match.port);
457 /* try strip off last ".$portnr" to get hub */
458 h = strrchr(hub_name, '.');
459 if (h != NULL) {
460 s->hub_port = atoi(h+1);
461 *h = '\0';
462 } else {
463 /* no dot in there -> it is the root hub */
464 snprintf(hub_name, sizeof(hub_name), "usb%d",
465 s->match.bus_num);
466 s->hub_port = atoi(s->match.port);
469 if (!usb_host_read_file(line, sizeof(line), "devnum",
470 hub_name)) {
471 return -1;
473 if (sscanf(line, "%d", &hub_addr) != 1) {
474 return -1;
477 s->hub_fd = usb_host_open_device(s->match.bus_num, hub_addr);
478 if (s->hub_fd < 0) {
479 return -1;
482 ret = ioctl(s->hub_fd, USBDEVFS_CLAIM_PORT, &s->hub_port);
483 if (ret < 0) {
484 close(s->hub_fd);
485 s->hub_fd = -1;
486 return -1;
489 trace_usb_host_claim_port(s->match.bus_num, hub_addr, s->hub_port);
490 return 0;
491 #else
492 return -1;
493 #endif
496 static void usb_host_release_port(USBHostDevice *s)
498 if (s->hub_fd == -1) {
499 return;
501 #ifdef USBDEVFS_RELEASE_PORT
502 ioctl(s->hub_fd, USBDEVFS_RELEASE_PORT, &s->hub_port);
503 #endif
504 close(s->hub_fd);
505 s->hub_fd = -1;
508 static int usb_host_disconnect_ifaces(USBHostDevice *dev, int nb_interfaces)
510 /* earlier Linux 2.4 do not support that */
511 #ifdef USBDEVFS_DISCONNECT
512 struct usbdevfs_ioctl ctrl;
513 int ret, interface;
515 for (interface = 0; interface < nb_interfaces; interface++) {
516 ctrl.ioctl_code = USBDEVFS_DISCONNECT;
517 ctrl.ifno = interface;
518 ctrl.data = 0;
519 ret = ioctl(dev->fd, USBDEVFS_IOCTL, &ctrl);
520 if (ret < 0 && errno != ENODATA) {
521 perror("USBDEVFS_DISCONNECT");
522 return -1;
525 #endif
526 return 0;
529 static int usb_linux_get_num_interfaces(USBHostDevice *s)
531 char device_name[64], line[1024];
532 int num_interfaces = 0;
534 sprintf(device_name, "%d-%s", s->bus_num, s->port);
535 if (!usb_host_read_file(line, sizeof(line), "bNumInterfaces",
536 device_name)) {
537 return -1;
539 if (sscanf(line, "%d", &num_interfaces) != 1) {
540 return -1;
542 return num_interfaces;
545 static int usb_host_claim_interfaces(USBHostDevice *dev, int configuration)
547 const char *op = NULL;
548 int dev_descr_len, config_descr_len;
549 int interface, nb_interfaces;
550 int ret, i;
552 for (i = 0; i < USB_MAX_INTERFACES; i++) {
553 dev->dev.altsetting[i] = 0;
556 if (configuration == 0) { /* address state - ignore */
557 dev->dev.ninterfaces = 0;
558 dev->dev.configuration = 0;
559 return 1;
562 DPRINTF("husb: claiming interfaces. config %d\n", configuration);
564 i = 0;
565 dev_descr_len = dev->descr[0];
566 if (dev_descr_len > dev->descr_len) {
567 fprintf(stderr, "husb: update iface failed. descr too short\n");
568 return 0;
571 i += dev_descr_len;
572 while (i < dev->descr_len) {
573 DPRINTF("husb: i is %d, descr_len is %d, dl %d, dt %d\n",
574 i, dev->descr_len,
575 dev->descr[i], dev->descr[i+1]);
577 if (dev->descr[i+1] != USB_DT_CONFIG) {
578 i += dev->descr[i];
579 continue;
581 config_descr_len = dev->descr[i];
583 DPRINTF("husb: config #%d need %d\n", dev->descr[i + 5], configuration);
585 if (configuration == dev->descr[i + 5]) {
586 configuration = dev->descr[i + 5];
587 break;
590 i += config_descr_len;
593 if (i >= dev->descr_len) {
594 fprintf(stderr,
595 "husb: update iface failed. no matching configuration\n");
596 return 0;
598 nb_interfaces = dev->descr[i + 4];
600 if (usb_host_disconnect_ifaces(dev, nb_interfaces) < 0) {
601 goto fail;
604 /* XXX: only grab if all interfaces are free */
605 for (interface = 0; interface < nb_interfaces; interface++) {
606 op = "USBDEVFS_CLAIMINTERFACE";
607 ret = ioctl(dev->fd, USBDEVFS_CLAIMINTERFACE, &interface);
608 if (ret < 0) {
609 goto fail;
613 trace_usb_host_claim_interfaces(dev->bus_num, dev->addr,
614 nb_interfaces, configuration);
616 dev->dev.ninterfaces = nb_interfaces;
617 dev->dev.configuration = configuration;
618 return 1;
620 fail:
621 if (errno == ENODEV) {
622 do_disconnect(dev);
624 perror(op);
625 return 0;
628 static int usb_host_release_interfaces(USBHostDevice *s)
630 int ret, i;
632 trace_usb_host_release_interfaces(s->bus_num, s->addr);
634 for (i = 0; i < s->dev.ninterfaces; i++) {
635 ret = ioctl(s->fd, USBDEVFS_RELEASEINTERFACE, &i);
636 if (ret < 0) {
637 perror("USBDEVFS_RELEASEINTERFACE");
638 return 0;
641 return 1;
644 static void usb_host_handle_reset(USBDevice *dev)
646 USBHostDevice *s = DO_UPCAST(USBHostDevice, dev, dev);
648 trace_usb_host_reset(s->bus_num, s->addr);
650 usb_host_do_reset(s);;
652 usb_host_claim_interfaces(s, 0);
653 usb_linux_update_endp_table(s);
656 static void usb_host_handle_destroy(USBDevice *dev)
658 USBHostDevice *s = (USBHostDevice *)dev;
660 usb_host_release_port(s);
661 usb_host_close(s);
662 QTAILQ_REMOVE(&hostdevs, s, next);
663 qemu_remove_exit_notifier(&s->exit);
666 /* iso data is special, we need to keep enough urbs in flight to make sure
667 that the controller never runs out of them, otherwise the device will
668 likely suffer a buffer underrun / overrun. */
669 static AsyncURB *usb_host_alloc_iso(USBHostDevice *s, int pid, uint8_t ep)
671 AsyncURB *aurb;
672 int i, j, len = usb_ep_get_max_packet_size(&s->dev, pid, ep);
674 aurb = g_malloc0(s->iso_urb_count * sizeof(*aurb));
675 for (i = 0; i < s->iso_urb_count; i++) {
676 aurb[i].urb.endpoint = ep;
677 aurb[i].urb.buffer_length = ISO_FRAME_DESC_PER_URB * len;
678 aurb[i].urb.buffer = g_malloc(aurb[i].urb.buffer_length);
679 aurb[i].urb.type = USBDEVFS_URB_TYPE_ISO;
680 aurb[i].urb.flags = USBDEVFS_URB_ISO_ASAP;
681 aurb[i].urb.number_of_packets = ISO_FRAME_DESC_PER_URB;
682 for (j = 0 ; j < ISO_FRAME_DESC_PER_URB; j++)
683 aurb[i].urb.iso_frame_desc[j].length = len;
684 if (pid == USB_TOKEN_IN) {
685 aurb[i].urb.endpoint |= 0x80;
686 /* Mark as fully consumed (idle) */
687 aurb[i].iso_frame_idx = ISO_FRAME_DESC_PER_URB;
690 set_iso_urb(s, pid, ep, aurb);
692 return aurb;
695 static void usb_host_stop_n_free_iso(USBHostDevice *s, int pid, uint8_t ep)
697 AsyncURB *aurb;
698 int i, ret, killed = 0, free = 1;
700 aurb = get_iso_urb(s, pid, ep);
701 if (!aurb) {
702 return;
705 for (i = 0; i < s->iso_urb_count; i++) {
706 /* in flight? */
707 if (aurb[i].iso_frame_idx == -1) {
708 ret = ioctl(s->fd, USBDEVFS_DISCARDURB, &aurb[i]);
709 if (ret < 0) {
710 perror("USBDEVFS_DISCARDURB");
711 free = 0;
712 continue;
714 killed++;
718 /* Make sure any urbs we've killed are reaped before we free them */
719 if (killed) {
720 async_complete(s);
723 for (i = 0; i < s->iso_urb_count; i++) {
724 g_free(aurb[i].urb.buffer);
727 if (free)
728 g_free(aurb);
729 else
730 printf("husb: leaking iso urbs because of discard failure\n");
731 set_iso_urb(s, pid, ep, NULL);
732 set_iso_urb_idx(s, pid, ep, 0);
733 clear_iso_started(s, pid, ep);
736 static int urb_status_to_usb_ret(int status)
738 switch (status) {
739 case -EPIPE:
740 return USB_RET_STALL;
741 case -EOVERFLOW:
742 return USB_RET_BABBLE;
743 default:
744 return USB_RET_IOERROR;
748 static int usb_host_handle_iso_data(USBHostDevice *s, USBPacket *p, int in)
750 AsyncURB *aurb;
751 int i, j, ret, max_packet_size, offset, len = 0;
752 uint8_t *buf;
754 max_packet_size = p->ep->max_packet_size;
755 if (max_packet_size == 0)
756 return USB_RET_NAK;
758 aurb = get_iso_urb(s, p->pid, p->ep->nr);
759 if (!aurb) {
760 aurb = usb_host_alloc_iso(s, p->pid, p->ep->nr);
763 i = get_iso_urb_idx(s, p->pid, p->ep->nr);
764 j = aurb[i].iso_frame_idx;
765 if (j >= 0 && j < ISO_FRAME_DESC_PER_URB) {
766 if (in) {
767 /* Check urb status */
768 if (aurb[i].urb.status) {
769 len = urb_status_to_usb_ret(aurb[i].urb.status);
770 /* Move to the next urb */
771 aurb[i].iso_frame_idx = ISO_FRAME_DESC_PER_URB - 1;
772 /* Check frame status */
773 } else if (aurb[i].urb.iso_frame_desc[j].status) {
774 len = urb_status_to_usb_ret(
775 aurb[i].urb.iso_frame_desc[j].status);
776 /* Check the frame fits */
777 } else if (aurb[i].urb.iso_frame_desc[j].actual_length
778 > p->iov.size) {
779 printf("husb: received iso data is larger then packet\n");
780 len = USB_RET_BABBLE;
781 /* All good copy data over */
782 } else {
783 len = aurb[i].urb.iso_frame_desc[j].actual_length;
784 buf = aurb[i].urb.buffer +
785 j * aurb[i].urb.iso_frame_desc[0].length;
786 usb_packet_copy(p, buf, len);
788 } else {
789 len = p->iov.size;
790 offset = (j == 0) ? 0 : get_iso_buffer_used(s, p->pid, p->ep->nr);
792 /* Check the frame fits */
793 if (len > max_packet_size) {
794 printf("husb: send iso data is larger then max packet size\n");
795 return USB_RET_NAK;
798 /* All good copy data over */
799 usb_packet_copy(p, aurb[i].urb.buffer + offset, len);
800 aurb[i].urb.iso_frame_desc[j].length = len;
801 offset += len;
802 set_iso_buffer_used(s, p->pid, p->ep->nr, offset);
804 /* Start the stream once we have buffered enough data */
805 if (!is_iso_started(s, p->pid, p->ep->nr) && i == 1 && j == 8) {
806 set_iso_started(s, p->pid, p->ep->nr);
809 aurb[i].iso_frame_idx++;
810 if (aurb[i].iso_frame_idx == ISO_FRAME_DESC_PER_URB) {
811 i = (i + 1) % s->iso_urb_count;
812 set_iso_urb_idx(s, p->pid, p->ep->nr, i);
814 } else {
815 if (in) {
816 set_iso_started(s, p->pid, p->ep->nr);
817 } else {
818 DPRINTF("hubs: iso out error no free buffer, dropping packet\n");
822 if (is_iso_started(s, p->pid, p->ep->nr)) {
823 /* (Re)-submit all fully consumed / filled urbs */
824 for (i = 0; i < s->iso_urb_count; i++) {
825 if (aurb[i].iso_frame_idx == ISO_FRAME_DESC_PER_URB) {
826 ret = ioctl(s->fd, USBDEVFS_SUBMITURB, &aurb[i]);
827 if (ret < 0) {
828 perror("USBDEVFS_SUBMITURB");
829 if (!in || len == 0) {
830 switch(errno) {
831 case ETIMEDOUT:
832 len = USB_RET_NAK;
833 break;
834 case EPIPE:
835 default:
836 len = USB_RET_STALL;
839 break;
841 aurb[i].iso_frame_idx = -1;
842 change_iso_inflight(s, p->pid, p->ep->nr, 1);
847 return len;
850 static int usb_host_handle_data(USBDevice *dev, USBPacket *p)
852 USBHostDevice *s = DO_UPCAST(USBHostDevice, dev, dev);
853 struct usbdevfs_urb *urb;
854 AsyncURB *aurb;
855 int ret, rem, prem, v;
856 uint8_t *pbuf;
857 uint8_t ep;
859 trace_usb_host_req_data(s->bus_num, s->addr, p,
860 p->pid == USB_TOKEN_IN,
861 p->ep->nr, p->iov.size);
863 if (!is_valid(s, p->pid, p->ep->nr)) {
864 trace_usb_host_req_complete(s->bus_num, s->addr, p, USB_RET_NAK);
865 return USB_RET_NAK;
868 if (p->pid == USB_TOKEN_IN) {
869 ep = p->ep->nr | 0x80;
870 } else {
871 ep = p->ep->nr;
874 if (is_halted(s, p->pid, p->ep->nr)) {
875 unsigned int arg = ep;
876 ret = ioctl(s->fd, USBDEVFS_CLEAR_HALT, &arg);
877 if (ret < 0) {
878 perror("USBDEVFS_CLEAR_HALT");
879 trace_usb_host_req_complete(s->bus_num, s->addr, p, USB_RET_NAK);
880 return USB_RET_NAK;
882 clear_halt(s, p->pid, p->ep->nr);
885 if (is_isoc(s, p->pid, p->ep->nr)) {
886 return usb_host_handle_iso_data(s, p, p->pid == USB_TOKEN_IN);
889 v = 0;
890 prem = 0;
891 pbuf = NULL;
892 rem = p->iov.size;
893 do {
894 if (prem == 0 && rem > 0) {
895 assert(v < p->iov.niov);
896 prem = p->iov.iov[v].iov_len;
897 pbuf = p->iov.iov[v].iov_base;
898 assert(prem <= rem);
899 v++;
901 aurb = async_alloc(s);
902 aurb->packet = p;
904 urb = &aurb->urb;
905 urb->endpoint = ep;
906 urb->type = usb_host_usbfs_type(s, p);
907 urb->usercontext = s;
908 urb->buffer = pbuf;
909 urb->buffer_length = prem;
911 if (urb->buffer_length > MAX_USBFS_BUFFER_SIZE) {
912 urb->buffer_length = MAX_USBFS_BUFFER_SIZE;
914 pbuf += urb->buffer_length;
915 prem -= urb->buffer_length;
916 rem -= urb->buffer_length;
917 if (rem) {
918 aurb->more = 1;
921 trace_usb_host_urb_submit(s->bus_num, s->addr, aurb,
922 urb->buffer_length, aurb->more);
923 ret = ioctl(s->fd, USBDEVFS_SUBMITURB, urb);
925 DPRINTF("husb: data submit: ep 0x%x, len %u, more %d, packet %p, aurb %p\n",
926 urb->endpoint, urb->buffer_length, aurb->more, p, aurb);
928 if (ret < 0) {
929 perror("USBDEVFS_SUBMITURB");
930 async_free(aurb);
932 switch(errno) {
933 case ETIMEDOUT:
934 trace_usb_host_req_complete(s->bus_num, s->addr, p,
935 USB_RET_NAK);
936 return USB_RET_NAK;
937 case EPIPE:
938 default:
939 trace_usb_host_req_complete(s->bus_num, s->addr, p,
940 USB_RET_STALL);
941 return USB_RET_STALL;
944 } while (rem > 0);
946 return USB_RET_ASYNC;
949 static int ctrl_error(void)
951 if (errno == ETIMEDOUT) {
952 return USB_RET_NAK;
953 } else {
954 return USB_RET_STALL;
958 static int usb_host_set_address(USBHostDevice *s, int addr)
960 trace_usb_host_set_address(s->bus_num, s->addr, addr);
961 s->dev.addr = addr;
962 return 0;
965 static int usb_host_set_config(USBHostDevice *s, int config)
967 int ret, first = 1;
969 trace_usb_host_set_config(s->bus_num, s->addr, config);
971 usb_host_release_interfaces(s);
973 again:
974 ret = ioctl(s->fd, USBDEVFS_SETCONFIGURATION, &config);
976 DPRINTF("husb: ctrl set config %d ret %d errno %d\n", config, ret, errno);
978 if (ret < 0 && errno == EBUSY && first) {
979 /* happens if usb device is in use by host drivers */
980 int count = usb_linux_get_num_interfaces(s);
981 if (count > 0) {
982 DPRINTF("husb: busy -> disconnecting %d interfaces\n", count);
983 usb_host_disconnect_ifaces(s, count);
984 first = 0;
985 goto again;
989 if (ret < 0) {
990 return ctrl_error();
992 usb_host_claim_interfaces(s, config);
993 usb_linux_update_endp_table(s);
994 return 0;
997 static int usb_host_set_interface(USBHostDevice *s, int iface, int alt)
999 struct usbdevfs_setinterface si;
1000 int i, ret;
1002 trace_usb_host_set_interface(s->bus_num, s->addr, iface, alt);
1004 for (i = 1; i <= USB_MAX_ENDPOINTS; i++) {
1005 if (is_isoc(s, USB_TOKEN_IN, i)) {
1006 usb_host_stop_n_free_iso(s, USB_TOKEN_IN, i);
1008 if (is_isoc(s, USB_TOKEN_OUT, i)) {
1009 usb_host_stop_n_free_iso(s, USB_TOKEN_OUT, i);
1013 if (iface >= USB_MAX_INTERFACES) {
1014 return USB_RET_STALL;
1017 si.interface = iface;
1018 si.altsetting = alt;
1019 ret = ioctl(s->fd, USBDEVFS_SETINTERFACE, &si);
1021 DPRINTF("husb: ctrl set iface %d altset %d ret %d errno %d\n",
1022 iface, alt, ret, errno);
1024 if (ret < 0) {
1025 return ctrl_error();
1028 s->dev.altsetting[iface] = alt;
1029 usb_linux_update_endp_table(s);
1030 return 0;
1033 static int usb_host_handle_control(USBDevice *dev, USBPacket *p,
1034 int request, int value, int index, int length, uint8_t *data)
1036 USBHostDevice *s = DO_UPCAST(USBHostDevice, dev, dev);
1037 struct usbdevfs_urb *urb;
1038 AsyncURB *aurb;
1039 int ret;
1042 * Process certain standard device requests.
1043 * These are infrequent and are processed synchronously.
1046 /* Note request is (bRequestType << 8) | bRequest */
1047 trace_usb_host_req_control(s->bus_num, s->addr, p, request, value, index);
1049 switch (request) {
1050 case DeviceOutRequest | USB_REQ_SET_ADDRESS:
1051 ret = usb_host_set_address(s, value);
1052 trace_usb_host_req_emulated(s->bus_num, s->addr, p, ret);
1053 return ret;
1055 case DeviceOutRequest | USB_REQ_SET_CONFIGURATION:
1056 ret = usb_host_set_config(s, value & 0xff);
1057 trace_usb_host_req_emulated(s->bus_num, s->addr, p, ret);
1058 return ret;
1060 case InterfaceOutRequest | USB_REQ_SET_INTERFACE:
1061 ret = usb_host_set_interface(s, index, value);
1062 trace_usb_host_req_emulated(s->bus_num, s->addr, p, ret);
1063 return ret;
1065 case EndpointOutRequest | USB_REQ_CLEAR_FEATURE:
1066 if (value == 0) { /* clear halt */
1067 int pid = (index & USB_DIR_IN) ? USB_TOKEN_IN : USB_TOKEN_OUT;
1068 ioctl(s->fd, USBDEVFS_CLEAR_HALT, &index);
1069 clear_halt(s, pid, index & 0x0f);
1070 trace_usb_host_req_emulated(s->bus_num, s->addr, p, 0);
1071 return 0;
1075 /* The rest are asynchronous */
1076 assert(p && p->result == 0);
1078 if (length > sizeof(dev->data_buf)) {
1079 fprintf(stderr, "husb: ctrl buffer too small (%d > %zu)\n",
1080 length, sizeof(dev->data_buf));
1081 return USB_RET_STALL;
1084 aurb = async_alloc(s);
1085 aurb->packet = p;
1088 * Setup ctrl transfer.
1090 * s->ctrl is laid out such that data buffer immediately follows
1091 * 'req' struct which is exactly what usbdevfs expects.
1093 urb = &aurb->urb;
1095 urb->type = USBDEVFS_URB_TYPE_CONTROL;
1096 urb->endpoint = p->ep->nr;
1098 urb->buffer = &dev->setup_buf;
1099 urb->buffer_length = length + 8;
1101 urb->usercontext = s;
1103 trace_usb_host_urb_submit(s->bus_num, s->addr, aurb,
1104 urb->buffer_length, aurb->more);
1105 ret = ioctl(s->fd, USBDEVFS_SUBMITURB, urb);
1107 DPRINTF("husb: submit ctrl. len %u aurb %p\n", urb->buffer_length, aurb);
1109 if (ret < 0) {
1110 DPRINTF("husb: submit failed. errno %d\n", errno);
1111 async_free(aurb);
1113 switch(errno) {
1114 case ETIMEDOUT:
1115 return USB_RET_NAK;
1116 case EPIPE:
1117 default:
1118 return USB_RET_STALL;
1122 return USB_RET_ASYNC;
1125 /* returns 1 on problem encountered or 0 for success */
1126 static int usb_linux_update_endp_table(USBHostDevice *s)
1128 static const char *tname[] = {
1129 [USB_ENDPOINT_XFER_CONTROL] = "control",
1130 [USB_ENDPOINT_XFER_ISOC] = "isoc",
1131 [USB_ENDPOINT_XFER_BULK] = "bulk",
1132 [USB_ENDPOINT_XFER_INT] = "int",
1134 uint8_t devep, type;
1135 uint16_t mps, v, p;
1136 int ep, pid;
1137 unsigned int i, configuration = -1, interface = -1, altsetting = -1;
1138 struct endp_data *epd;
1139 USBDescriptor *d;
1140 bool active = false;
1142 usb_ep_reset(&s->dev);
1144 for (i = 0;; i += d->bLength) {
1145 if (i+2 >= s->descr_len) {
1146 break;
1148 d = (void *)(s->descr + i);
1149 if (d->bLength < 2) {
1150 trace_usb_host_parse_error(s->bus_num, s->addr,
1151 "descriptor too short");
1152 goto error;
1154 if (i + d->bLength > s->descr_len) {
1155 trace_usb_host_parse_error(s->bus_num, s->addr,
1156 "descriptor too long");
1157 goto error;
1159 switch (d->bDescriptorType) {
1160 case 0:
1161 trace_usb_host_parse_error(s->bus_num, s->addr,
1162 "invalid descriptor type");
1163 goto error;
1164 case USB_DT_DEVICE:
1165 if (d->bLength < 0x12) {
1166 trace_usb_host_parse_error(s->bus_num, s->addr,
1167 "device descriptor too short");
1168 goto error;
1170 v = (d->u.device.idVendor_hi << 8) | d->u.device.idVendor_lo;
1171 p = (d->u.device.idProduct_hi << 8) | d->u.device.idProduct_lo;
1172 trace_usb_host_parse_device(s->bus_num, s->addr, v, p);
1173 break;
1174 case USB_DT_CONFIG:
1175 if (d->bLength < 0x09) {
1176 trace_usb_host_parse_error(s->bus_num, s->addr,
1177 "config descriptor too short");
1178 goto error;
1180 configuration = d->u.config.bConfigurationValue;
1181 active = (configuration == s->dev.configuration);
1182 trace_usb_host_parse_config(s->bus_num, s->addr,
1183 configuration, active);
1184 break;
1185 case USB_DT_INTERFACE:
1186 if (d->bLength < 0x09) {
1187 trace_usb_host_parse_error(s->bus_num, s->addr,
1188 "interface descriptor too short");
1189 goto error;
1191 interface = d->u.interface.bInterfaceNumber;
1192 altsetting = d->u.interface.bAlternateSetting;
1193 active = (configuration == s->dev.configuration) &&
1194 (altsetting == s->dev.altsetting[interface]);
1195 trace_usb_host_parse_interface(s->bus_num, s->addr,
1196 interface, altsetting, active);
1197 break;
1198 case USB_DT_ENDPOINT:
1199 if (d->bLength < 0x07) {
1200 trace_usb_host_parse_error(s->bus_num, s->addr,
1201 "endpoint descriptor too short");
1202 goto error;
1204 devep = d->u.endpoint.bEndpointAddress;
1205 pid = (devep & USB_DIR_IN) ? USB_TOKEN_IN : USB_TOKEN_OUT;
1206 ep = devep & 0xf;
1207 if (ep == 0) {
1208 trace_usb_host_parse_error(s->bus_num, s->addr,
1209 "invalid endpoint address");
1210 goto error;
1213 type = d->u.endpoint.bmAttributes & 0x3;
1214 mps = d->u.endpoint.wMaxPacketSize_lo |
1215 (d->u.endpoint.wMaxPacketSize_hi << 8);
1216 trace_usb_host_parse_endpoint(s->bus_num, s->addr, ep,
1217 (devep & USB_DIR_IN) ? "in" : "out",
1218 tname[type], active);
1220 if (active) {
1221 usb_ep_set_max_packet_size(&s->dev, pid, ep, mps);
1222 assert(usb_ep_get_type(&s->dev, pid, ep) ==
1223 USB_ENDPOINT_XFER_INVALID);
1224 usb_ep_set_type(&s->dev, pid, ep, type);
1225 usb_ep_set_ifnum(&s->dev, pid, ep, interface);
1226 if ((s->options & (1 << USB_HOST_OPT_PIPELINE)) &&
1227 (type == USB_ENDPOINT_XFER_BULK)) {
1228 usb_ep_set_pipeline(&s->dev, pid, ep, true);
1231 epd = get_endp(s, pid, ep);
1232 epd->halted = 0;
1235 break;
1236 default:
1237 trace_usb_host_parse_unknown(s->bus_num, s->addr,
1238 d->bLength, d->bDescriptorType);
1239 break;
1242 return 0;
1244 error:
1245 usb_ep_reset(&s->dev);
1246 return 1;
1250 * Check if we can safely redirect a usb2 device to a usb1 virtual controller,
1251 * this function assumes this is safe, if:
1252 * 1) There are no isoc endpoints
1253 * 2) There are no interrupt endpoints with a max_packet_size > 64
1254 * Note bulk endpoints with a max_packet_size > 64 in theory also are not
1255 * usb1 compatible, but in practice this seems to work fine.
1257 static int usb_linux_full_speed_compat(USBHostDevice *dev)
1259 int i, packet_size;
1262 * usb_linux_update_endp_table only registers info about ep in the current
1263 * interface altsettings, so we need to parse the descriptors again.
1265 for (i = 0; (i + 5) < dev->descr_len; i += dev->descr[i]) {
1266 if (dev->descr[i + 1] == USB_DT_ENDPOINT) {
1267 switch (dev->descr[i + 3] & 0x3) {
1268 case 0x00: /* CONTROL */
1269 break;
1270 case 0x01: /* ISO */
1271 return 0;
1272 case 0x02: /* BULK */
1273 break;
1274 case 0x03: /* INTERRUPT */
1275 packet_size = dev->descr[i + 4] + (dev->descr[i + 5] << 8);
1276 if (packet_size > 64)
1277 return 0;
1278 break;
1282 return 1;
1285 static int usb_host_open(USBHostDevice *dev, int bus_num,
1286 int addr, const char *port,
1287 const char *prod_name, int speed)
1289 int fd = -1, ret;
1291 trace_usb_host_open_started(bus_num, addr);
1293 if (dev->fd != -1) {
1294 goto fail;
1297 fd = usb_host_open_device(bus_num, addr);
1298 if (fd < 0) {
1299 goto fail;
1301 DPRINTF("husb: opened %s\n", buf);
1303 dev->bus_num = bus_num;
1304 dev->addr = addr;
1305 strcpy(dev->port, port);
1306 dev->fd = fd;
1308 /* read the device description */
1309 dev->descr_len = read(fd, dev->descr, sizeof(dev->descr));
1310 if (dev->descr_len <= 0) {
1311 perror("husb: reading device data failed");
1312 goto fail;
1315 #ifdef DEBUG
1317 int x;
1318 printf("=== begin dumping device descriptor data ===\n");
1319 for (x = 0; x < dev->descr_len; x++) {
1320 printf("%02x ", dev->descr[x]);
1322 printf("\n=== end dumping device descriptor data ===\n");
1324 #endif
1327 /* start unconfigured -- we'll wait for the guest to set a configuration */
1328 if (!usb_host_claim_interfaces(dev, 0)) {
1329 goto fail;
1332 usb_ep_init(&dev->dev);
1333 ret = usb_linux_update_endp_table(dev);
1334 if (ret) {
1335 goto fail;
1338 if (speed == -1) {
1339 struct usbdevfs_connectinfo ci;
1341 ret = ioctl(fd, USBDEVFS_CONNECTINFO, &ci);
1342 if (ret < 0) {
1343 perror("usb_host_device_open: USBDEVFS_CONNECTINFO");
1344 goto fail;
1347 if (ci.slow) {
1348 speed = USB_SPEED_LOW;
1349 } else {
1350 speed = USB_SPEED_HIGH;
1353 dev->dev.speed = speed;
1354 dev->dev.speedmask = (1 << speed);
1355 if (dev->dev.speed == USB_SPEED_HIGH && usb_linux_full_speed_compat(dev)) {
1356 dev->dev.speedmask |= USB_SPEED_MASK_FULL;
1359 trace_usb_host_open_success(bus_num, addr);
1361 if (!prod_name || prod_name[0] == '\0') {
1362 snprintf(dev->dev.product_desc, sizeof(dev->dev.product_desc),
1363 "host:%d.%d", bus_num, addr);
1364 } else {
1365 pstrcpy(dev->dev.product_desc, sizeof(dev->dev.product_desc),
1366 prod_name);
1369 ret = usb_device_attach(&dev->dev);
1370 if (ret) {
1371 goto fail;
1374 /* USB devio uses 'write' flag to check for async completions */
1375 qemu_set_fd_handler(dev->fd, NULL, async_complete, dev);
1377 return 0;
1379 fail:
1380 trace_usb_host_open_failure(bus_num, addr);
1381 if (dev->fd != -1) {
1382 close(dev->fd);
1383 dev->fd = -1;
1385 return -1;
1388 static int usb_host_close(USBHostDevice *dev)
1390 int i;
1392 if (dev->fd == -1) {
1393 return -1;
1396 trace_usb_host_close(dev->bus_num, dev->addr);
1398 qemu_set_fd_handler(dev->fd, NULL, NULL, NULL);
1399 dev->closing = 1;
1400 for (i = 1; i <= USB_MAX_ENDPOINTS; i++) {
1401 if (is_isoc(dev, USB_TOKEN_IN, i)) {
1402 usb_host_stop_n_free_iso(dev, USB_TOKEN_IN, i);
1404 if (is_isoc(dev, USB_TOKEN_OUT, i)) {
1405 usb_host_stop_n_free_iso(dev, USB_TOKEN_OUT, i);
1408 async_complete(dev);
1409 dev->closing = 0;
1410 if (dev->dev.attached) {
1411 usb_device_detach(&dev->dev);
1413 usb_host_do_reset(dev);
1414 close(dev->fd);
1415 dev->fd = -1;
1416 return 0;
1419 static void usb_host_exit_notifier(struct Notifier *n, void *data)
1421 USBHostDevice *s = container_of(n, USBHostDevice, exit);
1423 usb_host_release_port(s);
1424 if (s->fd != -1) {
1425 usb_host_do_reset(s);;
1430 * This is *NOT* about restoring state. We have absolutely no idea
1431 * what state the host device is in at the moment and whenever it is
1432 * still present in the first place. Attemping to contine where we
1433 * left off is impossible.
1435 * What we are going to to to here is emulate a surprise removal of
1436 * the usb device passed through, then kick host scan so the device
1437 * will get re-attached (and re-initialized by the guest) in case it
1438 * is still present.
1440 * As the device removal will change the state of other devices (usb
1441 * host controller, most likely interrupt controller too) we have to
1442 * wait with it until *all* vmstate is loaded. Thus post_load just
1443 * kicks a bottom half which then does the actual work.
1445 static void usb_host_post_load_bh(void *opaque)
1447 USBHostDevice *dev = opaque;
1449 if (dev->fd != -1) {
1450 usb_host_close(dev);
1452 if (dev->dev.attached) {
1453 usb_device_detach(&dev->dev);
1455 usb_host_auto_check(NULL);
1458 static int usb_host_post_load(void *opaque, int version_id)
1460 USBHostDevice *dev = opaque;
1462 qemu_bh_schedule(dev->bh);
1463 return 0;
1466 static int usb_host_initfn(USBDevice *dev)
1468 USBHostDevice *s = DO_UPCAST(USBHostDevice, dev, dev);
1470 dev->auto_attach = 0;
1471 s->fd = -1;
1472 s->hub_fd = -1;
1474 QTAILQ_INSERT_TAIL(&hostdevs, s, next);
1475 s->exit.notify = usb_host_exit_notifier;
1476 qemu_add_exit_notifier(&s->exit);
1477 s->bh = qemu_bh_new(usb_host_post_load_bh, s);
1478 usb_host_auto_check(NULL);
1480 if (s->match.bus_num != 0 && s->match.port != NULL) {
1481 usb_host_claim_port(s);
1483 add_boot_device_path(s->bootindex, &dev->qdev, NULL);
1484 return 0;
1487 static const VMStateDescription vmstate_usb_host = {
1488 .name = "usb-host",
1489 .version_id = 1,
1490 .minimum_version_id = 1,
1491 .post_load = usb_host_post_load,
1492 .fields = (VMStateField[]) {
1493 VMSTATE_USB_DEVICE(dev, USBHostDevice),
1494 VMSTATE_END_OF_LIST()
1498 static Property usb_host_dev_properties[] = {
1499 DEFINE_PROP_UINT32("hostbus", USBHostDevice, match.bus_num, 0),
1500 DEFINE_PROP_UINT32("hostaddr", USBHostDevice, match.addr, 0),
1501 DEFINE_PROP_STRING("hostport", USBHostDevice, match.port),
1502 DEFINE_PROP_HEX32("vendorid", USBHostDevice, match.vendor_id, 0),
1503 DEFINE_PROP_HEX32("productid", USBHostDevice, match.product_id, 0),
1504 DEFINE_PROP_UINT32("isobufs", USBHostDevice, iso_urb_count, 4),
1505 DEFINE_PROP_INT32("bootindex", USBHostDevice, bootindex, -1),
1506 DEFINE_PROP_BIT("pipeline", USBHostDevice, options,
1507 USB_HOST_OPT_PIPELINE, true),
1508 DEFINE_PROP_END_OF_LIST(),
1511 static void usb_host_class_initfn(ObjectClass *klass, void *data)
1513 DeviceClass *dc = DEVICE_CLASS(klass);
1514 USBDeviceClass *uc = USB_DEVICE_CLASS(klass);
1516 uc->init = usb_host_initfn;
1517 uc->product_desc = "USB Host Device";
1518 uc->cancel_packet = usb_host_async_cancel;
1519 uc->handle_data = usb_host_handle_data;
1520 uc->handle_control = usb_host_handle_control;
1521 uc->handle_reset = usb_host_handle_reset;
1522 uc->handle_destroy = usb_host_handle_destroy;
1523 dc->vmsd = &vmstate_usb_host;
1524 dc->props = usb_host_dev_properties;
1527 static TypeInfo usb_host_dev_info = {
1528 .name = "usb-host",
1529 .parent = TYPE_USB_DEVICE,
1530 .instance_size = sizeof(USBHostDevice),
1531 .class_init = usb_host_class_initfn,
1534 static void usb_host_register_types(void)
1536 type_register_static(&usb_host_dev_info);
1537 usb_legacy_register("usb-host", "host", usb_host_device_open);
1540 type_init(usb_host_register_types)
1542 USBDevice *usb_host_device_open(USBBus *bus, const char *devname)
1544 struct USBAutoFilter filter;
1545 USBDevice *dev;
1546 char *p;
1548 dev = usb_create(bus, "usb-host");
1550 if (strstr(devname, "auto:")) {
1551 if (parse_filter(devname, &filter) < 0) {
1552 goto fail;
1554 } else {
1555 if ((p = strchr(devname, '.'))) {
1556 filter.bus_num = strtoul(devname, NULL, 0);
1557 filter.addr = strtoul(p + 1, NULL, 0);
1558 filter.vendor_id = 0;
1559 filter.product_id = 0;
1560 } else if ((p = strchr(devname, ':'))) {
1561 filter.bus_num = 0;
1562 filter.addr = 0;
1563 filter.vendor_id = strtoul(devname, NULL, 16);
1564 filter.product_id = strtoul(p + 1, NULL, 16);
1565 } else {
1566 goto fail;
1570 qdev_prop_set_uint32(&dev->qdev, "hostbus", filter.bus_num);
1571 qdev_prop_set_uint32(&dev->qdev, "hostaddr", filter.addr);
1572 qdev_prop_set_uint32(&dev->qdev, "vendorid", filter.vendor_id);
1573 qdev_prop_set_uint32(&dev->qdev, "productid", filter.product_id);
1574 qdev_init_nofail(&dev->qdev);
1575 return dev;
1577 fail:
1578 qdev_free(&dev->qdev);
1579 return NULL;
1582 int usb_host_device_close(const char *devname)
1584 #if 0
1585 char product_name[PRODUCT_NAME_SZ];
1586 int bus_num, addr;
1587 USBHostDevice *s;
1589 if (strstr(devname, "auto:")) {
1590 return usb_host_auto_del(devname);
1592 if (usb_host_find_device(&bus_num, &addr, product_name,
1593 sizeof(product_name), devname) < 0) {
1594 return -1;
1596 s = hostdev_find(bus_num, addr);
1597 if (s) {
1598 usb_device_delete_addr(s->bus_num, s->dev.addr);
1599 return 0;
1601 #endif
1603 return -1;
1607 * Read sys file-system device file
1609 * @line address of buffer to put file contents in
1610 * @line_size size of line
1611 * @device_file path to device file (printf format string)
1612 * @device_name device being opened (inserted into device_file)
1614 * @return 0 failed, 1 succeeded ('line' contains data)
1616 static int usb_host_read_file(char *line, size_t line_size,
1617 const char *device_file, const char *device_name)
1619 FILE *f;
1620 int ret = 0;
1621 char filename[PATH_MAX];
1623 snprintf(filename, PATH_MAX, "/sys/bus/usb/devices/%s/%s", device_name,
1624 device_file);
1625 f = fopen(filename, "r");
1626 if (f) {
1627 ret = fgets(line, line_size, f) != NULL;
1628 fclose(f);
1631 return ret;
1635 * Use /sys/bus/usb/devices/ directory to determine host's USB
1636 * devices.
1638 * This code is based on Robert Schiele's original patches posted to
1639 * the Novell bug-tracker https://bugzilla.novell.com/show_bug.cgi?id=241950
1641 static int usb_host_scan(void *opaque, USBScanFunc *func)
1643 DIR *dir = NULL;
1644 char line[1024];
1645 int bus_num, addr, speed, class_id, product_id, vendor_id;
1646 int ret = 0;
1647 char port[MAX_PORTLEN];
1648 char product_name[512];
1649 struct dirent *de;
1651 dir = opendir("/sys/bus/usb/devices");
1652 if (!dir) {
1653 perror("husb: opendir /sys/bus/usb/devices");
1654 fprintf(stderr, "husb: please make sure sysfs is mounted at /sys\n");
1655 goto the_end;
1658 while ((de = readdir(dir))) {
1659 if (de->d_name[0] != '.' && !strchr(de->d_name, ':')) {
1660 if (sscanf(de->d_name, "%d-%7[0-9.]", &bus_num, port) < 2) {
1661 continue;
1664 if (!usb_host_read_file(line, sizeof(line), "devnum", de->d_name)) {
1665 goto the_end;
1667 if (sscanf(line, "%d", &addr) != 1) {
1668 goto the_end;
1670 if (!usb_host_read_file(line, sizeof(line), "bDeviceClass",
1671 de->d_name)) {
1672 goto the_end;
1674 if (sscanf(line, "%x", &class_id) != 1) {
1675 goto the_end;
1678 if (!usb_host_read_file(line, sizeof(line), "idVendor",
1679 de->d_name)) {
1680 goto the_end;
1682 if (sscanf(line, "%x", &vendor_id) != 1) {
1683 goto the_end;
1685 if (!usb_host_read_file(line, sizeof(line), "idProduct",
1686 de->d_name)) {
1687 goto the_end;
1689 if (sscanf(line, "%x", &product_id) != 1) {
1690 goto the_end;
1692 if (!usb_host_read_file(line, sizeof(line), "product",
1693 de->d_name)) {
1694 *product_name = 0;
1695 } else {
1696 if (strlen(line) > 0) {
1697 line[strlen(line) - 1] = '\0';
1699 pstrcpy(product_name, sizeof(product_name), line);
1702 if (!usb_host_read_file(line, sizeof(line), "speed", de->d_name)) {
1703 goto the_end;
1705 if (!strcmp(line, "5000\n")) {
1706 speed = USB_SPEED_SUPER;
1707 } else if (!strcmp(line, "480\n")) {
1708 speed = USB_SPEED_HIGH;
1709 } else if (!strcmp(line, "1.5\n")) {
1710 speed = USB_SPEED_LOW;
1711 } else {
1712 speed = USB_SPEED_FULL;
1715 ret = func(opaque, bus_num, addr, port, class_id, vendor_id,
1716 product_id, product_name, speed);
1717 if (ret) {
1718 goto the_end;
1722 the_end:
1723 if (dir) {
1724 closedir(dir);
1726 return ret;
1729 static QEMUTimer *usb_auto_timer;
1731 static int usb_host_auto_scan(void *opaque, int bus_num,
1732 int addr, const char *port,
1733 int class_id, int vendor_id, int product_id,
1734 const char *product_name, int speed)
1736 struct USBAutoFilter *f;
1737 struct USBHostDevice *s;
1739 /* Ignore hubs */
1740 if (class_id == 9)
1741 return 0;
1743 QTAILQ_FOREACH(s, &hostdevs, next) {
1744 f = &s->match;
1746 if (f->bus_num > 0 && f->bus_num != bus_num) {
1747 continue;
1749 if (f->addr > 0 && f->addr != addr) {
1750 continue;
1752 if (f->port != NULL && (port == NULL || strcmp(f->port, port) != 0)) {
1753 continue;
1756 if (f->vendor_id > 0 && f->vendor_id != vendor_id) {
1757 continue;
1760 if (f->product_id > 0 && f->product_id != product_id) {
1761 continue;
1763 /* We got a match */
1764 s->seen++;
1765 if (s->errcount >= 3) {
1766 return 0;
1769 /* Already attached ? */
1770 if (s->fd != -1) {
1771 return 0;
1773 DPRINTF("husb: auto open: bus_num %d addr %d\n", bus_num, addr);
1775 if (usb_host_open(s, bus_num, addr, port, product_name, speed) < 0) {
1776 s->errcount++;
1778 break;
1781 return 0;
1784 static void usb_host_auto_check(void *unused)
1786 struct USBHostDevice *s;
1787 int unconnected = 0;
1789 if (runstate_is_running()) {
1790 usb_host_scan(NULL, usb_host_auto_scan);
1792 QTAILQ_FOREACH(s, &hostdevs, next) {
1793 if (s->fd == -1) {
1794 unconnected++;
1796 if (s->seen == 0) {
1797 s->errcount = 0;
1799 s->seen = 0;
1802 if (unconnected == 0) {
1803 /* nothing to watch */
1804 if (usb_auto_timer) {
1805 qemu_del_timer(usb_auto_timer);
1806 trace_usb_host_auto_scan_disabled();
1808 return;
1812 if (!usb_auto_timer) {
1813 usb_auto_timer = qemu_new_timer_ms(rt_clock, usb_host_auto_check, NULL);
1814 if (!usb_auto_timer) {
1815 return;
1817 trace_usb_host_auto_scan_enabled();
1819 qemu_mod_timer(usb_auto_timer, qemu_get_clock_ms(rt_clock) + 2000);
1823 * Autoconnect filter
1824 * Format:
1825 * auto:bus:dev[:vid:pid]
1826 * auto:bus.dev[:vid:pid]
1828 * bus - bus number (dec, * means any)
1829 * dev - device number (dec, * means any)
1830 * vid - vendor id (hex, * means any)
1831 * pid - product id (hex, * means any)
1833 * See 'lsusb' output.
1835 static int parse_filter(const char *spec, struct USBAutoFilter *f)
1837 enum { BUS, DEV, VID, PID, DONE };
1838 const char *p = spec;
1839 int i;
1841 f->bus_num = 0;
1842 f->addr = 0;
1843 f->vendor_id = 0;
1844 f->product_id = 0;
1846 for (i = BUS; i < DONE; i++) {
1847 p = strpbrk(p, ":.");
1848 if (!p) {
1849 break;
1851 p++;
1853 if (*p == '*') {
1854 continue;
1856 switch(i) {
1857 case BUS: f->bus_num = strtol(p, NULL, 10); break;
1858 case DEV: f->addr = strtol(p, NULL, 10); break;
1859 case VID: f->vendor_id = strtol(p, NULL, 16); break;
1860 case PID: f->product_id = strtol(p, NULL, 16); break;
1864 if (i < DEV) {
1865 fprintf(stderr, "husb: invalid auto filter spec %s\n", spec);
1866 return -1;
1869 return 0;
1872 /**********************/
1873 /* USB host device info */
1875 struct usb_class_info {
1876 int class;
1877 const char *class_name;
1880 static const struct usb_class_info usb_class_info[] = {
1881 { USB_CLASS_AUDIO, "Audio"},
1882 { USB_CLASS_COMM, "Communication"},
1883 { USB_CLASS_HID, "HID"},
1884 { USB_CLASS_HUB, "Hub" },
1885 { USB_CLASS_PHYSICAL, "Physical" },
1886 { USB_CLASS_PRINTER, "Printer" },
1887 { USB_CLASS_MASS_STORAGE, "Storage" },
1888 { USB_CLASS_CDC_DATA, "Data" },
1889 { USB_CLASS_APP_SPEC, "Application Specific" },
1890 { USB_CLASS_VENDOR_SPEC, "Vendor Specific" },
1891 { USB_CLASS_STILL_IMAGE, "Still Image" },
1892 { USB_CLASS_CSCID, "Smart Card" },
1893 { USB_CLASS_CONTENT_SEC, "Content Security" },
1894 { -1, NULL }
1897 static const char *usb_class_str(uint8_t class)
1899 const struct usb_class_info *p;
1900 for(p = usb_class_info; p->class != -1; p++) {
1901 if (p->class == class) {
1902 break;
1905 return p->class_name;
1908 static void usb_info_device(Monitor *mon, int bus_num,
1909 int addr, const char *port,
1910 int class_id, int vendor_id, int product_id,
1911 const char *product_name,
1912 int speed)
1914 const char *class_str, *speed_str;
1916 switch(speed) {
1917 case USB_SPEED_LOW:
1918 speed_str = "1.5";
1919 break;
1920 case USB_SPEED_FULL:
1921 speed_str = "12";
1922 break;
1923 case USB_SPEED_HIGH:
1924 speed_str = "480";
1925 break;
1926 case USB_SPEED_SUPER:
1927 speed_str = "5000";
1928 break;
1929 default:
1930 speed_str = "?";
1931 break;
1934 monitor_printf(mon, " Bus %d, Addr %d, Port %s, Speed %s Mb/s\n",
1935 bus_num, addr, port, speed_str);
1936 class_str = usb_class_str(class_id);
1937 if (class_str) {
1938 monitor_printf(mon, " %s:", class_str);
1939 } else {
1940 monitor_printf(mon, " Class %02x:", class_id);
1942 monitor_printf(mon, " USB device %04x:%04x", vendor_id, product_id);
1943 if (product_name[0] != '\0') {
1944 monitor_printf(mon, ", %s", product_name);
1946 monitor_printf(mon, "\n");
1949 static int usb_host_info_device(void *opaque, int bus_num, int addr,
1950 const char *path, int class_id,
1951 int vendor_id, int product_id,
1952 const char *product_name,
1953 int speed)
1955 Monitor *mon = opaque;
1957 usb_info_device(mon, bus_num, addr, path, class_id, vendor_id, product_id,
1958 product_name, speed);
1959 return 0;
1962 static void dec2str(int val, char *str, size_t size)
1964 if (val == 0) {
1965 snprintf(str, size, "*");
1966 } else {
1967 snprintf(str, size, "%d", val);
1971 static void hex2str(int val, char *str, size_t size)
1973 if (val == 0) {
1974 snprintf(str, size, "*");
1975 } else {
1976 snprintf(str, size, "%04x", val);
1980 void usb_host_info(Monitor *mon)
1982 struct USBAutoFilter *f;
1983 struct USBHostDevice *s;
1985 usb_host_scan(mon, usb_host_info_device);
1987 if (QTAILQ_EMPTY(&hostdevs)) {
1988 return;
1991 monitor_printf(mon, " Auto filters:\n");
1992 QTAILQ_FOREACH(s, &hostdevs, next) {
1993 char bus[10], addr[10], vid[10], pid[10];
1994 f = &s->match;
1995 dec2str(f->bus_num, bus, sizeof(bus));
1996 dec2str(f->addr, addr, sizeof(addr));
1997 hex2str(f->vendor_id, vid, sizeof(vid));
1998 hex2str(f->product_id, pid, sizeof(pid));
1999 monitor_printf(mon, " Bus %s, Addr %s, Port %s, ID %s:%s\n",
2000 bus, addr, f->port ? f->port : "*", vid, pid);