]> git.proxmox.com Git - mirror_qemu.git/blob - hw/usb/host-linux.c
usb-host: scan for usb devices when the vm starts
[mirror_qemu.git] / hw / usb / host-linux.c
1 /*
2 * Linux host USB redirector
3 *
4 * Copyright (c) 2005 Fabrice Bellard
5 *
6 * Copyright (c) 2008 Max Krasnyansky
7 * Support for host device auto connect & disconnect
8 * Major rewrite to support fully async operation
9 *
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
13 *
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:
20 *
21 * The above copyright notice and this permission notice shall be included in
22 * all copies or substantial portions of the Software.
23 *
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.
31 */
32
33 #include "qemu-common.h"
34 #include "qemu-timer.h"
35 #include "monitor.h"
36 #include "sysemu.h"
37 #include "trace.h"
38
39 #include <dirent.h>
40 #include <sys/ioctl.h>
41
42 #include <linux/usbdevice_fs.h>
43 #include <linux/version.h>
44 #include "hw/usb.h"
45 #include "hw/usb/desc.h"
46
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;
56 };
57
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);
61
62 //#define DEBUG
63
64 #ifdef DEBUG
65 #define DPRINTF printf
66 #else
67 #define DPRINTF(...)
68 #endif
69
70 #define PRODUCT_NAME_SZ 32
71 #define MAX_PORTLEN 16
72
73 /* endpoint association data */
74 #define ISO_FRAME_DESC_PER_URB 32
75
76 /* devio.c limits single requests to 16k */
77 #define MAX_USBFS_BUFFER_SIZE 16384
78
79 typedef struct AsyncURB AsyncURB;
80
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;
88 };
89
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;
96 };
97
98 enum USBHostDeviceOptions {
99 USB_HOST_OPT_PIPELINE,
100 };
101
102 typedef struct USBHostDevice {
103 USBDevice dev;
104 int fd;
105 int hub_fd;
106 int hub_port;
107
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;
115
116 struct endp_data ep_in[USB_MAX_ENDPOINTS];
117 struct endp_data ep_out[USB_MAX_ENDPOINTS];
118 QLIST_HEAD(, AsyncURB) aurbs;
119
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;
127
128 QTAILQ_ENTRY(USBHostDevice) next;
129 } USBHostDevice;
130
131 static QTAILQ_HEAD(, USBHostDevice) hostdevs = QTAILQ_HEAD_INITIALIZER(hostdevs);
132
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);
139
140 static int usb_host_usbfs_type(USBHostDevice *s, USBPacket *p)
141 {
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,
147 };
148 uint8_t type = p->ep->type;
149 assert(type < ARRAY_SIZE(usbfs));
150 return usbfs[type];
151 }
152
153 static int usb_host_do_reset(USBHostDevice *dev)
154 {
155 struct timeval s, e;
156 uint32_t usecs;
157 int ret;
158
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);
168 }
169 return ret;
170 }
171
172 static struct endp_data *get_endp(USBHostDevice *s, int pid, int ep)
173 {
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;
178 }
179
180 static int is_isoc(USBHostDevice *s, int pid, int ep)
181 {
182 return usb_ep_get_type(&s->dev, pid, ep) == USB_ENDPOINT_XFER_ISOC;
183 }
184
185 static int is_valid(USBHostDevice *s, int pid, int ep)
186 {
187 return usb_ep_get_type(&s->dev, pid, ep) != USB_ENDPOINT_XFER_INVALID;
188 }
189
190 static int is_halted(USBHostDevice *s, int pid, int ep)
191 {
192 return get_endp(s, pid, ep)->halted;
193 }
194
195 static void clear_halt(USBHostDevice *s, int pid, int ep)
196 {
197 trace_usb_host_ep_clear_halt(s->bus_num, s->addr, ep);
198 get_endp(s, pid, ep)->halted = 0;
199 }
200
201 static void set_halt(USBHostDevice *s, int pid, int ep)
202 {
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;
206 }
207 }
208
209 static int is_iso_started(USBHostDevice *s, int pid, int ep)
210 {
211 return get_endp(s, pid, ep)->iso_started;
212 }
213
214 static void clear_iso_started(USBHostDevice *s, int pid, int ep)
215 {
216 trace_usb_host_iso_stop(s->bus_num, s->addr, ep);
217 get_endp(s, pid, ep)->iso_started = 0;
218 }
219
220 static void set_iso_started(USBHostDevice *s, int pid, int ep)
221 {
222 struct endp_data *e = get_endp(s, pid, ep);
223
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;
228 }
229 }
230
231 static int change_iso_inflight(USBHostDevice *s, int pid, int ep, int value)
232 {
233 struct endp_data *e = get_endp(s, pid, ep);
234
235 e->inflight += value;
236 return e->inflight;
237 }
238
239 static void set_iso_urb(USBHostDevice *s, int pid, int ep, AsyncURB *iso_urb)
240 {
241 get_endp(s, pid, ep)->iso_urb = iso_urb;
242 }
243
244 static AsyncURB *get_iso_urb(USBHostDevice *s, int pid, int ep)
245 {
246 return get_endp(s, pid, ep)->iso_urb;
247 }
248
249 static void set_iso_urb_idx(USBHostDevice *s, int pid, int ep, int i)
250 {
251 get_endp(s, pid, ep)->iso_urb_idx = i;
252 }
253
254 static int get_iso_urb_idx(USBHostDevice *s, int pid, int ep)
255 {
256 return get_endp(s, pid, ep)->iso_urb_idx;
257 }
258
259 static void set_iso_buffer_used(USBHostDevice *s, int pid, int ep, int i)
260 {
261 get_endp(s, pid, ep)->iso_buffer_used = i;
262 }
263
264 static int get_iso_buffer_used(USBHostDevice *s, int pid, int ep)
265 {
266 return get_endp(s, pid, ep)->iso_buffer_used;
267 }
268
269 /*
270 * Async URB state.
271 * We always allocate iso packet descriptors even for bulk transfers
272 * to simplify allocation and casts.
273 */
274 struct AsyncURB
275 {
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;
280
281 /* For regular async urbs */
282 USBPacket *packet;
283 int more; /* large transfer, more urbs follow */
284
285 /* For buffered iso handling */
286 int iso_frame_idx; /* -1 means in flight */
287 };
288
289 static AsyncURB *async_alloc(USBHostDevice *s)
290 {
291 AsyncURB *aurb = g_malloc0(sizeof(AsyncURB));
292 aurb->hdev = s;
293 QLIST_INSERT_HEAD(&s->aurbs, aurb, next);
294 return aurb;
295 }
296
297 static void async_free(AsyncURB *aurb)
298 {
299 QLIST_REMOVE(aurb, next);
300 g_free(aurb);
301 }
302
303 static void do_disconnect(USBHostDevice *s)
304 {
305 usb_host_close(s);
306 usb_host_auto_check(NULL);
307 }
308
309 static void async_complete(void *opaque)
310 {
311 USBHostDevice *s = opaque;
312 AsyncURB *aurb;
313 int urbs = 0;
314
315 while (1) {
316 USBPacket *p;
317
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);
324 }
325 return;
326 }
327 if (errno == ENODEV) {
328 if (!s->closing) {
329 trace_usb_host_disconnect(s->bus_num, s->addr);
330 do_disconnect(s);
331 }
332 return;
333 }
334
335 perror("USBDEVFS_REAPURBNDELAY");
336 return;
337 }
338
339 DPRINTF("husb: async completed. aurb %p status %d alen %d\n",
340 aurb, aurb->urb.status, aurb->urb.actual_length);
341
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);
351 }
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);
358 }
359 continue;
360 }
361
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);
365
366 if (p) {
367 switch (aurb->urb.status) {
368 case 0:
369 p->actual_length = aurb->urb.actual_length;
370 p->status = USB_RET_SUCCESS; /* Clear previous ASYNC status */
371 break;
372
373 case -EPIPE:
374 set_halt(s, p->pid, p->ep->nr);
375 p->status = USB_RET_STALL;
376 break;
377
378 case -EOVERFLOW:
379 p->status = USB_RET_BABBLE;
380 break;
381
382 default:
383 p->status = USB_RET_IOERROR;
384 break;
385 }
386
387 if (aurb->urb.type == USBDEVFS_URB_TYPE_CONTROL) {
388 trace_usb_host_req_complete(s->bus_num, s->addr, p, p->status);
389 usb_generic_async_ctrl_complete(&s->dev, p);
390 } else if (!aurb->more) {
391 trace_usb_host_req_complete(s->bus_num, s->addr, p, p->status);
392 usb_packet_complete(&s->dev, p);
393 }
394 }
395
396 async_free(aurb);
397 }
398 }
399
400 static void usb_host_async_cancel(USBDevice *dev, USBPacket *p)
401 {
402 USBHostDevice *s = DO_UPCAST(USBHostDevice, dev, dev);
403 AsyncURB *aurb;
404
405 trace_usb_host_req_canceled(s->bus_num, s->addr, p);
406
407 QLIST_FOREACH(aurb, &s->aurbs, next) {
408 if (p != aurb->packet) {
409 continue;
410 }
411
412 trace_usb_host_urb_canceled(s->bus_num, s->addr, aurb);
413
414 /* Mark it as dead (see async_complete above) */
415 aurb->packet = NULL;
416
417 int r = ioctl(s->fd, USBDEVFS_DISCARDURB, aurb);
418 if (r < 0) {
419 DPRINTF("husb: async. discard urb failed errno %d\n", errno);
420 }
421 }
422 }
423
424 static int usb_host_open_device(int bus, int addr)
425 {
426 const char *usbfs = NULL;
427 char filename[32];
428 struct stat st;
429 int fd, rc;
430
431 rc = stat("/dev/bus/usb", &st);
432 if (rc == 0 && S_ISDIR(st.st_mode)) {
433 /* udev-created device nodes available */
434 usbfs = "/dev/bus/usb";
435 } else {
436 /* fallback: usbfs mounted below /proc */
437 usbfs = "/proc/bus/usb";
438 }
439
440 snprintf(filename, sizeof(filename), "%s/%03d/%03d",
441 usbfs, bus, addr);
442 fd = open(filename, O_RDWR | O_NONBLOCK);
443 if (fd < 0) {
444 fprintf(stderr, "husb: open %s: %s\n", filename, strerror(errno));
445 }
446 return fd;
447 }
448
449 static int usb_host_claim_port(USBHostDevice *s)
450 {
451 #ifdef USBDEVFS_CLAIM_PORT
452 char *h, hub_name[64], line[1024];
453 int hub_addr, ret;
454
455 snprintf(hub_name, sizeof(hub_name), "%d-%s",
456 s->match.bus_num, s->match.port);
457
458 /* try strip off last ".$portnr" to get hub */
459 h = strrchr(hub_name, '.');
460 if (h != NULL) {
461 s->hub_port = atoi(h+1);
462 *h = '\0';
463 } else {
464 /* no dot in there -> it is the root hub */
465 snprintf(hub_name, sizeof(hub_name), "usb%d",
466 s->match.bus_num);
467 s->hub_port = atoi(s->match.port);
468 }
469
470 if (!usb_host_read_file(line, sizeof(line), "devnum",
471 hub_name)) {
472 return -1;
473 }
474 if (sscanf(line, "%d", &hub_addr) != 1) {
475 return -1;
476 }
477
478 s->hub_fd = usb_host_open_device(s->match.bus_num, hub_addr);
479 if (s->hub_fd < 0) {
480 return -1;
481 }
482
483 ret = ioctl(s->hub_fd, USBDEVFS_CLAIM_PORT, &s->hub_port);
484 if (ret < 0) {
485 close(s->hub_fd);
486 s->hub_fd = -1;
487 return -1;
488 }
489
490 trace_usb_host_claim_port(s->match.bus_num, hub_addr, s->hub_port);
491 return 0;
492 #else
493 return -1;
494 #endif
495 }
496
497 static void usb_host_release_port(USBHostDevice *s)
498 {
499 if (s->hub_fd == -1) {
500 return;
501 }
502 #ifdef USBDEVFS_RELEASE_PORT
503 ioctl(s->hub_fd, USBDEVFS_RELEASE_PORT, &s->hub_port);
504 #endif
505 close(s->hub_fd);
506 s->hub_fd = -1;
507 }
508
509 static int usb_host_disconnect_ifaces(USBHostDevice *dev, int nb_interfaces)
510 {
511 /* earlier Linux 2.4 do not support that */
512 #ifdef USBDEVFS_DISCONNECT
513 struct usbdevfs_ioctl ctrl;
514 int ret, interface;
515
516 for (interface = 0; interface < nb_interfaces; interface++) {
517 ctrl.ioctl_code = USBDEVFS_DISCONNECT;
518 ctrl.ifno = interface;
519 ctrl.data = 0;
520 ret = ioctl(dev->fd, USBDEVFS_IOCTL, &ctrl);
521 if (ret < 0 && errno != ENODATA) {
522 perror("USBDEVFS_DISCONNECT");
523 return -1;
524 }
525 }
526 #endif
527 return 0;
528 }
529
530 static int usb_linux_get_num_interfaces(USBHostDevice *s)
531 {
532 char device_name[64], line[1024];
533 int num_interfaces = 0;
534
535 sprintf(device_name, "%d-%s", s->bus_num, s->port);
536 if (!usb_host_read_file(line, sizeof(line), "bNumInterfaces",
537 device_name)) {
538 return -1;
539 }
540 if (sscanf(line, "%d", &num_interfaces) != 1) {
541 return -1;
542 }
543 return num_interfaces;
544 }
545
546 static int usb_host_claim_interfaces(USBHostDevice *dev, int configuration)
547 {
548 const char *op = NULL;
549 int dev_descr_len, config_descr_len;
550 int interface, nb_interfaces;
551 int ret, i;
552
553 for (i = 0; i < USB_MAX_INTERFACES; i++) {
554 dev->dev.altsetting[i] = 0;
555 }
556
557 if (configuration == 0) { /* address state - ignore */
558 dev->dev.ninterfaces = 0;
559 dev->dev.configuration = 0;
560 return 1;
561 }
562
563 DPRINTF("husb: claiming interfaces. config %d\n", configuration);
564
565 i = 0;
566 dev_descr_len = dev->descr[0];
567 if (dev_descr_len > dev->descr_len) {
568 fprintf(stderr, "husb: update iface failed. descr too short\n");
569 return 0;
570 }
571
572 i += dev_descr_len;
573 while (i < dev->descr_len) {
574 DPRINTF("husb: i is %d, descr_len is %d, dl %d, dt %d\n",
575 i, dev->descr_len,
576 dev->descr[i], dev->descr[i+1]);
577
578 if (dev->descr[i+1] != USB_DT_CONFIG) {
579 i += dev->descr[i];
580 continue;
581 }
582 config_descr_len = dev->descr[i];
583
584 DPRINTF("husb: config #%d need %d\n", dev->descr[i + 5], configuration);
585
586 if (configuration == dev->descr[i + 5]) {
587 configuration = dev->descr[i + 5];
588 break;
589 }
590
591 i += config_descr_len;
592 }
593
594 if (i >= dev->descr_len) {
595 fprintf(stderr,
596 "husb: update iface failed. no matching configuration\n");
597 return 0;
598 }
599 nb_interfaces = dev->descr[i + 4];
600
601 if (usb_host_disconnect_ifaces(dev, nb_interfaces) < 0) {
602 goto fail;
603 }
604
605 /* XXX: only grab if all interfaces are free */
606 for (interface = 0; interface < nb_interfaces; interface++) {
607 op = "USBDEVFS_CLAIMINTERFACE";
608 ret = ioctl(dev->fd, USBDEVFS_CLAIMINTERFACE, &interface);
609 if (ret < 0) {
610 goto fail;
611 }
612 }
613
614 trace_usb_host_claim_interfaces(dev->bus_num, dev->addr,
615 nb_interfaces, configuration);
616
617 dev->dev.ninterfaces = nb_interfaces;
618 dev->dev.configuration = configuration;
619 return 1;
620
621 fail:
622 if (errno == ENODEV) {
623 do_disconnect(dev);
624 }
625 perror(op);
626 return 0;
627 }
628
629 static int usb_host_release_interfaces(USBHostDevice *s)
630 {
631 int ret, i;
632
633 trace_usb_host_release_interfaces(s->bus_num, s->addr);
634
635 for (i = 0; i < s->dev.ninterfaces; i++) {
636 ret = ioctl(s->fd, USBDEVFS_RELEASEINTERFACE, &i);
637 if (ret < 0) {
638 perror("USBDEVFS_RELEASEINTERFACE");
639 return 0;
640 }
641 }
642 return 1;
643 }
644
645 static void usb_host_handle_reset(USBDevice *dev)
646 {
647 USBHostDevice *s = DO_UPCAST(USBHostDevice, dev, dev);
648
649 trace_usb_host_reset(s->bus_num, s->addr);
650
651 usb_host_do_reset(s);;
652
653 usb_host_claim_interfaces(s, 0);
654 usb_linux_update_endp_table(s);
655 }
656
657 static void usb_host_handle_destroy(USBDevice *dev)
658 {
659 USBHostDevice *s = (USBHostDevice *)dev;
660
661 usb_host_release_port(s);
662 usb_host_close(s);
663 QTAILQ_REMOVE(&hostdevs, s, next);
664 qemu_remove_exit_notifier(&s->exit);
665 }
666
667 /* iso data is special, we need to keep enough urbs in flight to make sure
668 that the controller never runs out of them, otherwise the device will
669 likely suffer a buffer underrun / overrun. */
670 static AsyncURB *usb_host_alloc_iso(USBHostDevice *s, int pid, uint8_t ep)
671 {
672 AsyncURB *aurb;
673 int i, j, len = usb_ep_get_max_packet_size(&s->dev, pid, ep);
674
675 aurb = g_malloc0(s->iso_urb_count * sizeof(*aurb));
676 for (i = 0; i < s->iso_urb_count; i++) {
677 aurb[i].urb.endpoint = ep;
678 aurb[i].urb.buffer_length = ISO_FRAME_DESC_PER_URB * len;
679 aurb[i].urb.buffer = g_malloc(aurb[i].urb.buffer_length);
680 aurb[i].urb.type = USBDEVFS_URB_TYPE_ISO;
681 aurb[i].urb.flags = USBDEVFS_URB_ISO_ASAP;
682 aurb[i].urb.number_of_packets = ISO_FRAME_DESC_PER_URB;
683 for (j = 0 ; j < ISO_FRAME_DESC_PER_URB; j++)
684 aurb[i].urb.iso_frame_desc[j].length = len;
685 if (pid == USB_TOKEN_IN) {
686 aurb[i].urb.endpoint |= 0x80;
687 /* Mark as fully consumed (idle) */
688 aurb[i].iso_frame_idx = ISO_FRAME_DESC_PER_URB;
689 }
690 }
691 set_iso_urb(s, pid, ep, aurb);
692
693 return aurb;
694 }
695
696 static void usb_host_stop_n_free_iso(USBHostDevice *s, int pid, uint8_t ep)
697 {
698 AsyncURB *aurb;
699 int i, ret, killed = 0, free = 1;
700
701 aurb = get_iso_urb(s, pid, ep);
702 if (!aurb) {
703 return;
704 }
705
706 for (i = 0; i < s->iso_urb_count; i++) {
707 /* in flight? */
708 if (aurb[i].iso_frame_idx == -1) {
709 ret = ioctl(s->fd, USBDEVFS_DISCARDURB, &aurb[i]);
710 if (ret < 0) {
711 perror("USBDEVFS_DISCARDURB");
712 free = 0;
713 continue;
714 }
715 killed++;
716 }
717 }
718
719 /* Make sure any urbs we've killed are reaped before we free them */
720 if (killed) {
721 async_complete(s);
722 }
723
724 for (i = 0; i < s->iso_urb_count; i++) {
725 g_free(aurb[i].urb.buffer);
726 }
727
728 if (free)
729 g_free(aurb);
730 else
731 printf("husb: leaking iso urbs because of discard failure\n");
732 set_iso_urb(s, pid, ep, NULL);
733 set_iso_urb_idx(s, pid, ep, 0);
734 clear_iso_started(s, pid, ep);
735 }
736
737 static void urb_status_to_usb_ret(int status, USBPacket *p)
738 {
739 switch (status) {
740 case -EPIPE:
741 p->status = USB_RET_STALL;
742 break;
743 case -EOVERFLOW:
744 p->status = USB_RET_BABBLE;
745 break;
746 default:
747 p->status = USB_RET_IOERROR;
748 }
749 }
750
751 static void usb_host_handle_iso_data(USBHostDevice *s, USBPacket *p, int in)
752 {
753 AsyncURB *aurb;
754 int i, j, max_packet_size, offset, len;
755 uint8_t *buf;
756
757 max_packet_size = p->ep->max_packet_size;
758 if (max_packet_size == 0) {
759 p->status = USB_RET_NAK;
760 return;
761 }
762
763 aurb = get_iso_urb(s, p->pid, p->ep->nr);
764 if (!aurb) {
765 aurb = usb_host_alloc_iso(s, p->pid, p->ep->nr);
766 }
767
768 i = get_iso_urb_idx(s, p->pid, p->ep->nr);
769 j = aurb[i].iso_frame_idx;
770 if (j >= 0 && j < ISO_FRAME_DESC_PER_URB) {
771 if (in) {
772 /* Check urb status */
773 if (aurb[i].urb.status) {
774 urb_status_to_usb_ret(aurb[i].urb.status, p);
775 /* Move to the next urb */
776 aurb[i].iso_frame_idx = ISO_FRAME_DESC_PER_URB - 1;
777 /* Check frame status */
778 } else if (aurb[i].urb.iso_frame_desc[j].status) {
779 urb_status_to_usb_ret(aurb[i].urb.iso_frame_desc[j].status, p);
780 /* Check the frame fits */
781 } else if (aurb[i].urb.iso_frame_desc[j].actual_length
782 > p->iov.size) {
783 printf("husb: received iso data is larger then packet\n");
784 p->status = USB_RET_BABBLE;
785 /* All good copy data over */
786 } else {
787 len = aurb[i].urb.iso_frame_desc[j].actual_length;
788 buf = aurb[i].urb.buffer +
789 j * aurb[i].urb.iso_frame_desc[0].length;
790 usb_packet_copy(p, buf, len);
791 }
792 } else {
793 len = p->iov.size;
794 offset = (j == 0) ? 0 : get_iso_buffer_used(s, p->pid, p->ep->nr);
795
796 /* Check the frame fits */
797 if (len > max_packet_size) {
798 printf("husb: send iso data is larger then max packet size\n");
799 p->status = USB_RET_NAK;
800 return;
801 }
802
803 /* All good copy data over */
804 usb_packet_copy(p, aurb[i].urb.buffer + offset, len);
805 aurb[i].urb.iso_frame_desc[j].length = len;
806 offset += len;
807 set_iso_buffer_used(s, p->pid, p->ep->nr, offset);
808
809 /* Start the stream once we have buffered enough data */
810 if (!is_iso_started(s, p->pid, p->ep->nr) && i == 1 && j == 8) {
811 set_iso_started(s, p->pid, p->ep->nr);
812 }
813 }
814 aurb[i].iso_frame_idx++;
815 if (aurb[i].iso_frame_idx == ISO_FRAME_DESC_PER_URB) {
816 i = (i + 1) % s->iso_urb_count;
817 set_iso_urb_idx(s, p->pid, p->ep->nr, i);
818 }
819 } else {
820 if (in) {
821 set_iso_started(s, p->pid, p->ep->nr);
822 } else {
823 DPRINTF("hubs: iso out error no free buffer, dropping packet\n");
824 }
825 }
826
827 if (is_iso_started(s, p->pid, p->ep->nr)) {
828 /* (Re)-submit all fully consumed / filled urbs */
829 for (i = 0; i < s->iso_urb_count; i++) {
830 if (aurb[i].iso_frame_idx == ISO_FRAME_DESC_PER_URB) {
831 if (ioctl(s->fd, USBDEVFS_SUBMITURB, &aurb[i]) < 0) {
832 perror("USBDEVFS_SUBMITURB");
833 if (!in || p->status == USB_RET_SUCCESS) {
834 switch(errno) {
835 case ETIMEDOUT:
836 p->status = USB_RET_NAK;
837 break;
838 case EPIPE:
839 default:
840 p->status = USB_RET_STALL;
841 }
842 }
843 break;
844 }
845 aurb[i].iso_frame_idx = -1;
846 change_iso_inflight(s, p->pid, p->ep->nr, 1);
847 }
848 }
849 }
850 }
851
852 static void usb_host_handle_data(USBDevice *dev, USBPacket *p)
853 {
854 USBHostDevice *s = DO_UPCAST(USBHostDevice, dev, dev);
855 struct usbdevfs_urb *urb;
856 AsyncURB *aurb;
857 int ret, rem, prem, v;
858 uint8_t *pbuf;
859 uint8_t ep;
860
861 trace_usb_host_req_data(s->bus_num, s->addr, p,
862 p->pid == USB_TOKEN_IN,
863 p->ep->nr, p->iov.size);
864
865 if (!is_valid(s, p->pid, p->ep->nr)) {
866 trace_usb_host_req_complete(s->bus_num, s->addr, p, USB_RET_NAK);
867 p->status = USB_RET_NAK;
868 return;
869 }
870
871 if (p->pid == USB_TOKEN_IN) {
872 ep = p->ep->nr | 0x80;
873 } else {
874 ep = p->ep->nr;
875 }
876
877 if (is_halted(s, p->pid, p->ep->nr)) {
878 unsigned int arg = ep;
879 ret = ioctl(s->fd, USBDEVFS_CLEAR_HALT, &arg);
880 if (ret < 0) {
881 perror("USBDEVFS_CLEAR_HALT");
882 trace_usb_host_req_complete(s->bus_num, s->addr, p, USB_RET_NAK);
883 p->status = USB_RET_NAK;
884 return;
885 }
886 clear_halt(s, p->pid, p->ep->nr);
887 }
888
889 if (is_isoc(s, p->pid, p->ep->nr)) {
890 usb_host_handle_iso_data(s, p, p->pid == USB_TOKEN_IN);
891 return;
892 }
893
894 v = 0;
895 prem = 0;
896 pbuf = NULL;
897 rem = p->iov.size;
898 do {
899 if (prem == 0 && rem > 0) {
900 assert(v < p->iov.niov);
901 prem = p->iov.iov[v].iov_len;
902 pbuf = p->iov.iov[v].iov_base;
903 assert(prem <= rem);
904 v++;
905 }
906 aurb = async_alloc(s);
907 aurb->packet = p;
908
909 urb = &aurb->urb;
910 urb->endpoint = ep;
911 urb->type = usb_host_usbfs_type(s, p);
912 urb->usercontext = s;
913 urb->buffer = pbuf;
914 urb->buffer_length = prem;
915
916 if (urb->buffer_length > MAX_USBFS_BUFFER_SIZE) {
917 urb->buffer_length = MAX_USBFS_BUFFER_SIZE;
918 }
919 pbuf += urb->buffer_length;
920 prem -= urb->buffer_length;
921 rem -= urb->buffer_length;
922 if (rem) {
923 aurb->more = 1;
924 }
925
926 trace_usb_host_urb_submit(s->bus_num, s->addr, aurb,
927 urb->buffer_length, aurb->more);
928 ret = ioctl(s->fd, USBDEVFS_SUBMITURB, urb);
929
930 DPRINTF("husb: data submit: ep 0x%x, len %u, more %d, packet %p, aurb %p\n",
931 urb->endpoint, urb->buffer_length, aurb->more, p, aurb);
932
933 if (ret < 0) {
934 perror("USBDEVFS_SUBMITURB");
935 async_free(aurb);
936
937 switch(errno) {
938 case ETIMEDOUT:
939 trace_usb_host_req_complete(s->bus_num, s->addr, p,
940 USB_RET_NAK);
941 p->status = USB_RET_NAK;
942 break;
943 case EPIPE:
944 default:
945 trace_usb_host_req_complete(s->bus_num, s->addr, p,
946 USB_RET_STALL);
947 p->status = USB_RET_STALL;
948 }
949 return;
950 }
951 } while (rem > 0);
952
953 p->status = USB_RET_ASYNC;
954 }
955
956 static int ctrl_error(void)
957 {
958 if (errno == ETIMEDOUT) {
959 return USB_RET_NAK;
960 } else {
961 return USB_RET_STALL;
962 }
963 }
964
965 static void usb_host_set_address(USBHostDevice *s, int addr)
966 {
967 trace_usb_host_set_address(s->bus_num, s->addr, addr);
968 s->dev.addr = addr;
969 }
970
971 static void usb_host_set_config(USBHostDevice *s, int config, USBPacket *p)
972 {
973 int ret, first = 1;
974
975 trace_usb_host_set_config(s->bus_num, s->addr, config);
976
977 usb_host_release_interfaces(s);
978
979 again:
980 ret = ioctl(s->fd, USBDEVFS_SETCONFIGURATION, &config);
981
982 DPRINTF("husb: ctrl set config %d ret %d errno %d\n", config, ret, errno);
983
984 if (ret < 0 && errno == EBUSY && first) {
985 /* happens if usb device is in use by host drivers */
986 int count = usb_linux_get_num_interfaces(s);
987 if (count > 0) {
988 DPRINTF("husb: busy -> disconnecting %d interfaces\n", count);
989 usb_host_disconnect_ifaces(s, count);
990 first = 0;
991 goto again;
992 }
993 }
994
995 if (ret < 0) {
996 p->status = ctrl_error();
997 return;
998 }
999 usb_host_claim_interfaces(s, config);
1000 usb_linux_update_endp_table(s);
1001 }
1002
1003 static void usb_host_set_interface(USBHostDevice *s, int iface, int alt,
1004 USBPacket *p)
1005 {
1006 struct usbdevfs_setinterface si;
1007 int i, ret;
1008
1009 trace_usb_host_set_interface(s->bus_num, s->addr, iface, alt);
1010
1011 for (i = 1; i <= USB_MAX_ENDPOINTS; i++) {
1012 if (is_isoc(s, USB_TOKEN_IN, i)) {
1013 usb_host_stop_n_free_iso(s, USB_TOKEN_IN, i);
1014 }
1015 if (is_isoc(s, USB_TOKEN_OUT, i)) {
1016 usb_host_stop_n_free_iso(s, USB_TOKEN_OUT, i);
1017 }
1018 }
1019
1020 if (iface >= USB_MAX_INTERFACES) {
1021 p->status = USB_RET_STALL;
1022 return;
1023 }
1024
1025 si.interface = iface;
1026 si.altsetting = alt;
1027 ret = ioctl(s->fd, USBDEVFS_SETINTERFACE, &si);
1028
1029 DPRINTF("husb: ctrl set iface %d altset %d ret %d errno %d\n",
1030 iface, alt, ret, errno);
1031
1032 if (ret < 0) {
1033 p->status = ctrl_error();
1034 return;
1035 }
1036
1037 s->dev.altsetting[iface] = alt;
1038 usb_linux_update_endp_table(s);
1039 }
1040
1041 static void usb_host_handle_control(USBDevice *dev, USBPacket *p,
1042 int request, int value, int index, int length, uint8_t *data)
1043 {
1044 USBHostDevice *s = DO_UPCAST(USBHostDevice, dev, dev);
1045 struct usbdevfs_urb *urb;
1046 AsyncURB *aurb;
1047 int ret;
1048
1049 /*
1050 * Process certain standard device requests.
1051 * These are infrequent and are processed synchronously.
1052 */
1053
1054 /* Note request is (bRequestType << 8) | bRequest */
1055 trace_usb_host_req_control(s->bus_num, s->addr, p, request, value, index);
1056
1057 switch (request) {
1058 case DeviceOutRequest | USB_REQ_SET_ADDRESS:
1059 usb_host_set_address(s, value);
1060 trace_usb_host_req_emulated(s->bus_num, s->addr, p, p->status);
1061 return;
1062
1063 case DeviceOutRequest | USB_REQ_SET_CONFIGURATION:
1064 usb_host_set_config(s, value & 0xff, p);
1065 trace_usb_host_req_emulated(s->bus_num, s->addr, p, p->status);
1066 return;
1067
1068 case InterfaceOutRequest | USB_REQ_SET_INTERFACE:
1069 usb_host_set_interface(s, index, value, p);
1070 trace_usb_host_req_emulated(s->bus_num, s->addr, p, p->status);
1071 return;
1072
1073 case EndpointOutRequest | USB_REQ_CLEAR_FEATURE:
1074 if (value == 0) { /* clear halt */
1075 int pid = (index & USB_DIR_IN) ? USB_TOKEN_IN : USB_TOKEN_OUT;
1076 ioctl(s->fd, USBDEVFS_CLEAR_HALT, &index);
1077 clear_halt(s, pid, index & 0x0f);
1078 trace_usb_host_req_emulated(s->bus_num, s->addr, p, 0);
1079 return;
1080 }
1081 }
1082
1083 /* The rest are asynchronous */
1084 if (length > sizeof(dev->data_buf)) {
1085 fprintf(stderr, "husb: ctrl buffer too small (%d > %zu)\n",
1086 length, sizeof(dev->data_buf));
1087 p->status = USB_RET_STALL;
1088 return;
1089 }
1090
1091 aurb = async_alloc(s);
1092 aurb->packet = p;
1093
1094 /*
1095 * Setup ctrl transfer.
1096 *
1097 * s->ctrl is laid out such that data buffer immediately follows
1098 * 'req' struct which is exactly what usbdevfs expects.
1099 */
1100 urb = &aurb->urb;
1101
1102 urb->type = USBDEVFS_URB_TYPE_CONTROL;
1103 urb->endpoint = p->ep->nr;
1104
1105 urb->buffer = &dev->setup_buf;
1106 urb->buffer_length = length + 8;
1107
1108 urb->usercontext = s;
1109
1110 trace_usb_host_urb_submit(s->bus_num, s->addr, aurb,
1111 urb->buffer_length, aurb->more);
1112 ret = ioctl(s->fd, USBDEVFS_SUBMITURB, urb);
1113
1114 DPRINTF("husb: submit ctrl. len %u aurb %p\n", urb->buffer_length, aurb);
1115
1116 if (ret < 0) {
1117 DPRINTF("husb: submit failed. errno %d\n", errno);
1118 async_free(aurb);
1119
1120 switch(errno) {
1121 case ETIMEDOUT:
1122 p->status = USB_RET_NAK;
1123 break;
1124 case EPIPE:
1125 default:
1126 p->status = USB_RET_STALL;
1127 break;
1128 }
1129 return;
1130 }
1131
1132 p->status = USB_RET_ASYNC;
1133 }
1134
1135 /* returns 1 on problem encountered or 0 for success */
1136 static int usb_linux_update_endp_table(USBHostDevice *s)
1137 {
1138 static const char *tname[] = {
1139 [USB_ENDPOINT_XFER_CONTROL] = "control",
1140 [USB_ENDPOINT_XFER_ISOC] = "isoc",
1141 [USB_ENDPOINT_XFER_BULK] = "bulk",
1142 [USB_ENDPOINT_XFER_INT] = "int",
1143 };
1144 uint8_t devep, type;
1145 uint16_t mps, v, p;
1146 int ep, pid;
1147 unsigned int i, configuration = -1, interface = -1, altsetting = -1;
1148 struct endp_data *epd;
1149 USBDescriptor *d;
1150 bool active = false;
1151
1152 usb_ep_reset(&s->dev);
1153
1154 for (i = 0;; i += d->bLength) {
1155 if (i+2 >= s->descr_len) {
1156 break;
1157 }
1158 d = (void *)(s->descr + i);
1159 if (d->bLength < 2) {
1160 trace_usb_host_parse_error(s->bus_num, s->addr,
1161 "descriptor too short");
1162 goto error;
1163 }
1164 if (i + d->bLength > s->descr_len) {
1165 trace_usb_host_parse_error(s->bus_num, s->addr,
1166 "descriptor too long");
1167 goto error;
1168 }
1169 switch (d->bDescriptorType) {
1170 case 0:
1171 trace_usb_host_parse_error(s->bus_num, s->addr,
1172 "invalid descriptor type");
1173 goto error;
1174 case USB_DT_DEVICE:
1175 if (d->bLength < 0x12) {
1176 trace_usb_host_parse_error(s->bus_num, s->addr,
1177 "device descriptor too short");
1178 goto error;
1179 }
1180 v = (d->u.device.idVendor_hi << 8) | d->u.device.idVendor_lo;
1181 p = (d->u.device.idProduct_hi << 8) | d->u.device.idProduct_lo;
1182 trace_usb_host_parse_device(s->bus_num, s->addr, v, p);
1183 break;
1184 case USB_DT_CONFIG:
1185 if (d->bLength < 0x09) {
1186 trace_usb_host_parse_error(s->bus_num, s->addr,
1187 "config descriptor too short");
1188 goto error;
1189 }
1190 configuration = d->u.config.bConfigurationValue;
1191 active = (configuration == s->dev.configuration);
1192 trace_usb_host_parse_config(s->bus_num, s->addr,
1193 configuration, active);
1194 break;
1195 case USB_DT_INTERFACE:
1196 if (d->bLength < 0x09) {
1197 trace_usb_host_parse_error(s->bus_num, s->addr,
1198 "interface descriptor too short");
1199 goto error;
1200 }
1201 interface = d->u.interface.bInterfaceNumber;
1202 altsetting = d->u.interface.bAlternateSetting;
1203 active = (configuration == s->dev.configuration) &&
1204 (altsetting == s->dev.altsetting[interface]);
1205 trace_usb_host_parse_interface(s->bus_num, s->addr,
1206 interface, altsetting, active);
1207 break;
1208 case USB_DT_ENDPOINT:
1209 if (d->bLength < 0x07) {
1210 trace_usb_host_parse_error(s->bus_num, s->addr,
1211 "endpoint descriptor too short");
1212 goto error;
1213 }
1214 devep = d->u.endpoint.bEndpointAddress;
1215 pid = (devep & USB_DIR_IN) ? USB_TOKEN_IN : USB_TOKEN_OUT;
1216 ep = devep & 0xf;
1217 if (ep == 0) {
1218 trace_usb_host_parse_error(s->bus_num, s->addr,
1219 "invalid endpoint address");
1220 goto error;
1221 }
1222
1223 type = d->u.endpoint.bmAttributes & 0x3;
1224 mps = d->u.endpoint.wMaxPacketSize_lo |
1225 (d->u.endpoint.wMaxPacketSize_hi << 8);
1226 trace_usb_host_parse_endpoint(s->bus_num, s->addr, ep,
1227 (devep & USB_DIR_IN) ? "in" : "out",
1228 tname[type], active);
1229
1230 if (active) {
1231 usb_ep_set_max_packet_size(&s->dev, pid, ep, mps);
1232 assert(usb_ep_get_type(&s->dev, pid, ep) ==
1233 USB_ENDPOINT_XFER_INVALID);
1234 usb_ep_set_type(&s->dev, pid, ep, type);
1235 usb_ep_set_ifnum(&s->dev, pid, ep, interface);
1236 if ((s->options & (1 << USB_HOST_OPT_PIPELINE)) &&
1237 (type == USB_ENDPOINT_XFER_BULK) &&
1238 (pid == USB_TOKEN_OUT)) {
1239 usb_ep_set_pipeline(&s->dev, pid, ep, true);
1240 }
1241
1242 epd = get_endp(s, pid, ep);
1243 epd->halted = 0;
1244 }
1245
1246 break;
1247 default:
1248 trace_usb_host_parse_unknown(s->bus_num, s->addr,
1249 d->bLength, d->bDescriptorType);
1250 break;
1251 }
1252 }
1253 return 0;
1254
1255 error:
1256 usb_ep_reset(&s->dev);
1257 return 1;
1258 }
1259
1260 /*
1261 * Check if we can safely redirect a usb2 device to a usb1 virtual controller,
1262 * this function assumes this is safe, if:
1263 * 1) There are no isoc endpoints
1264 * 2) There are no interrupt endpoints with a max_packet_size > 64
1265 * Note bulk endpoints with a max_packet_size > 64 in theory also are not
1266 * usb1 compatible, but in practice this seems to work fine.
1267 */
1268 static int usb_linux_full_speed_compat(USBHostDevice *dev)
1269 {
1270 int i, packet_size;
1271
1272 /*
1273 * usb_linux_update_endp_table only registers info about ep in the current
1274 * interface altsettings, so we need to parse the descriptors again.
1275 */
1276 for (i = 0; (i + 5) < dev->descr_len; i += dev->descr[i]) {
1277 if (dev->descr[i + 1] == USB_DT_ENDPOINT) {
1278 switch (dev->descr[i + 3] & 0x3) {
1279 case 0x00: /* CONTROL */
1280 break;
1281 case 0x01: /* ISO */
1282 return 0;
1283 case 0x02: /* BULK */
1284 break;
1285 case 0x03: /* INTERRUPT */
1286 packet_size = dev->descr[i + 4] + (dev->descr[i + 5] << 8);
1287 if (packet_size > 64)
1288 return 0;
1289 break;
1290 }
1291 }
1292 }
1293 return 1;
1294 }
1295
1296 static int usb_host_open(USBHostDevice *dev, int bus_num,
1297 int addr, const char *port,
1298 const char *prod_name, int speed)
1299 {
1300 int fd = -1, ret;
1301
1302 trace_usb_host_open_started(bus_num, addr);
1303
1304 if (dev->fd != -1) {
1305 goto fail;
1306 }
1307
1308 fd = usb_host_open_device(bus_num, addr);
1309 if (fd < 0) {
1310 goto fail;
1311 }
1312 DPRINTF("husb: opened %s\n", buf);
1313
1314 dev->bus_num = bus_num;
1315 dev->addr = addr;
1316 strcpy(dev->port, port);
1317 dev->fd = fd;
1318
1319 /* read the device description */
1320 dev->descr_len = read(fd, dev->descr, sizeof(dev->descr));
1321 if (dev->descr_len <= 0) {
1322 perror("husb: reading device data failed");
1323 goto fail;
1324 }
1325
1326 #ifdef DEBUG
1327 {
1328 int x;
1329 printf("=== begin dumping device descriptor data ===\n");
1330 for (x = 0; x < dev->descr_len; x++) {
1331 printf("%02x ", dev->descr[x]);
1332 }
1333 printf("\n=== end dumping device descriptor data ===\n");
1334 }
1335 #endif
1336
1337
1338 /* start unconfigured -- we'll wait for the guest to set a configuration */
1339 if (!usb_host_claim_interfaces(dev, 0)) {
1340 goto fail;
1341 }
1342
1343 usb_ep_init(&dev->dev);
1344 ret = usb_linux_update_endp_table(dev);
1345 if (ret) {
1346 goto fail;
1347 }
1348
1349 if (speed == -1) {
1350 struct usbdevfs_connectinfo ci;
1351
1352 ret = ioctl(fd, USBDEVFS_CONNECTINFO, &ci);
1353 if (ret < 0) {
1354 perror("usb_host_device_open: USBDEVFS_CONNECTINFO");
1355 goto fail;
1356 }
1357
1358 if (ci.slow) {
1359 speed = USB_SPEED_LOW;
1360 } else {
1361 speed = USB_SPEED_HIGH;
1362 }
1363 }
1364 dev->dev.speed = speed;
1365 dev->dev.speedmask = (1 << speed);
1366 if (dev->dev.speed == USB_SPEED_HIGH && usb_linux_full_speed_compat(dev)) {
1367 dev->dev.speedmask |= USB_SPEED_MASK_FULL;
1368 }
1369
1370 trace_usb_host_open_success(bus_num, addr);
1371
1372 if (!prod_name || prod_name[0] == '\0') {
1373 snprintf(dev->dev.product_desc, sizeof(dev->dev.product_desc),
1374 "host:%d.%d", bus_num, addr);
1375 } else {
1376 pstrcpy(dev->dev.product_desc, sizeof(dev->dev.product_desc),
1377 prod_name);
1378 }
1379
1380 ret = usb_device_attach(&dev->dev);
1381 if (ret) {
1382 goto fail;
1383 }
1384
1385 /* USB devio uses 'write' flag to check for async completions */
1386 qemu_set_fd_handler(dev->fd, NULL, async_complete, dev);
1387
1388 return 0;
1389
1390 fail:
1391 trace_usb_host_open_failure(bus_num, addr);
1392 if (dev->fd != -1) {
1393 close(dev->fd);
1394 dev->fd = -1;
1395 }
1396 return -1;
1397 }
1398
1399 static int usb_host_close(USBHostDevice *dev)
1400 {
1401 int i;
1402
1403 if (dev->fd == -1) {
1404 return -1;
1405 }
1406
1407 trace_usb_host_close(dev->bus_num, dev->addr);
1408
1409 qemu_set_fd_handler(dev->fd, NULL, NULL, NULL);
1410 dev->closing = 1;
1411 for (i = 1; i <= USB_MAX_ENDPOINTS; i++) {
1412 if (is_isoc(dev, USB_TOKEN_IN, i)) {
1413 usb_host_stop_n_free_iso(dev, USB_TOKEN_IN, i);
1414 }
1415 if (is_isoc(dev, USB_TOKEN_OUT, i)) {
1416 usb_host_stop_n_free_iso(dev, USB_TOKEN_OUT, i);
1417 }
1418 }
1419 async_complete(dev);
1420 dev->closing = 0;
1421 if (dev->dev.attached) {
1422 usb_device_detach(&dev->dev);
1423 }
1424 usb_host_do_reset(dev);
1425 close(dev->fd);
1426 dev->fd = -1;
1427 return 0;
1428 }
1429
1430 static void usb_host_exit_notifier(struct Notifier *n, void *data)
1431 {
1432 USBHostDevice *s = container_of(n, USBHostDevice, exit);
1433
1434 usb_host_release_port(s);
1435 if (s->fd != -1) {
1436 usb_host_do_reset(s);;
1437 }
1438 }
1439
1440 /*
1441 * This is *NOT* about restoring state. We have absolutely no idea
1442 * what state the host device is in at the moment and whenever it is
1443 * still present in the first place. Attemping to contine where we
1444 * left off is impossible.
1445 *
1446 * What we are going to to to here is emulate a surprise removal of
1447 * the usb device passed through, then kick host scan so the device
1448 * will get re-attached (and re-initialized by the guest) in case it
1449 * is still present.
1450 *
1451 * As the device removal will change the state of other devices (usb
1452 * host controller, most likely interrupt controller too) we have to
1453 * wait with it until *all* vmstate is loaded. Thus post_load just
1454 * kicks a bottom half which then does the actual work.
1455 */
1456 static void usb_host_post_load_bh(void *opaque)
1457 {
1458 USBHostDevice *dev = opaque;
1459
1460 if (dev->fd != -1) {
1461 usb_host_close(dev);
1462 }
1463 if (dev->dev.attached) {
1464 usb_device_detach(&dev->dev);
1465 }
1466 usb_host_auto_check(NULL);
1467 }
1468
1469 static int usb_host_post_load(void *opaque, int version_id)
1470 {
1471 USBHostDevice *dev = opaque;
1472
1473 qemu_bh_schedule(dev->bh);
1474 return 0;
1475 }
1476
1477 static int usb_host_initfn(USBDevice *dev)
1478 {
1479 USBHostDevice *s = DO_UPCAST(USBHostDevice, dev, dev);
1480
1481 dev->auto_attach = 0;
1482 s->fd = -1;
1483 s->hub_fd = -1;
1484
1485 QTAILQ_INSERT_TAIL(&hostdevs, s, next);
1486 s->exit.notify = usb_host_exit_notifier;
1487 qemu_add_exit_notifier(&s->exit);
1488 s->bh = qemu_bh_new(usb_host_post_load_bh, s);
1489 usb_host_auto_check(NULL);
1490
1491 if (s->match.bus_num != 0 && s->match.port != NULL) {
1492 usb_host_claim_port(s);
1493 }
1494 add_boot_device_path(s->bootindex, &dev->qdev, NULL);
1495 return 0;
1496 }
1497
1498 static const VMStateDescription vmstate_usb_host = {
1499 .name = "usb-host",
1500 .version_id = 1,
1501 .minimum_version_id = 1,
1502 .post_load = usb_host_post_load,
1503 .fields = (VMStateField[]) {
1504 VMSTATE_USB_DEVICE(dev, USBHostDevice),
1505 VMSTATE_END_OF_LIST()
1506 }
1507 };
1508
1509 static Property usb_host_dev_properties[] = {
1510 DEFINE_PROP_UINT32("hostbus", USBHostDevice, match.bus_num, 0),
1511 DEFINE_PROP_UINT32("hostaddr", USBHostDevice, match.addr, 0),
1512 DEFINE_PROP_STRING("hostport", USBHostDevice, match.port),
1513 DEFINE_PROP_HEX32("vendorid", USBHostDevice, match.vendor_id, 0),
1514 DEFINE_PROP_HEX32("productid", USBHostDevice, match.product_id, 0),
1515 DEFINE_PROP_UINT32("isobufs", USBHostDevice, iso_urb_count, 4),
1516 DEFINE_PROP_INT32("bootindex", USBHostDevice, bootindex, -1),
1517 DEFINE_PROP_BIT("pipeline", USBHostDevice, options,
1518 USB_HOST_OPT_PIPELINE, true),
1519 DEFINE_PROP_END_OF_LIST(),
1520 };
1521
1522 static void usb_host_class_initfn(ObjectClass *klass, void *data)
1523 {
1524 DeviceClass *dc = DEVICE_CLASS(klass);
1525 USBDeviceClass *uc = USB_DEVICE_CLASS(klass);
1526
1527 uc->init = usb_host_initfn;
1528 uc->product_desc = "USB Host Device";
1529 uc->cancel_packet = usb_host_async_cancel;
1530 uc->handle_data = usb_host_handle_data;
1531 uc->handle_control = usb_host_handle_control;
1532 uc->handle_reset = usb_host_handle_reset;
1533 uc->handle_destroy = usb_host_handle_destroy;
1534 dc->vmsd = &vmstate_usb_host;
1535 dc->props = usb_host_dev_properties;
1536 }
1537
1538 static TypeInfo usb_host_dev_info = {
1539 .name = "usb-host",
1540 .parent = TYPE_USB_DEVICE,
1541 .instance_size = sizeof(USBHostDevice),
1542 .class_init = usb_host_class_initfn,
1543 };
1544
1545 static void usb_host_register_types(void)
1546 {
1547 type_register_static(&usb_host_dev_info);
1548 usb_legacy_register("usb-host", "host", usb_host_device_open);
1549 }
1550
1551 type_init(usb_host_register_types)
1552
1553 USBDevice *usb_host_device_open(USBBus *bus, const char *devname)
1554 {
1555 struct USBAutoFilter filter;
1556 USBDevice *dev;
1557 char *p;
1558
1559 dev = usb_create(bus, "usb-host");
1560
1561 if (strstr(devname, "auto:")) {
1562 if (parse_filter(devname, &filter) < 0) {
1563 goto fail;
1564 }
1565 } else {
1566 if ((p = strchr(devname, '.'))) {
1567 filter.bus_num = strtoul(devname, NULL, 0);
1568 filter.addr = strtoul(p + 1, NULL, 0);
1569 filter.vendor_id = 0;
1570 filter.product_id = 0;
1571 } else if ((p = strchr(devname, ':'))) {
1572 filter.bus_num = 0;
1573 filter.addr = 0;
1574 filter.vendor_id = strtoul(devname, NULL, 16);
1575 filter.product_id = strtoul(p + 1, NULL, 16);
1576 } else {
1577 goto fail;
1578 }
1579 }
1580
1581 qdev_prop_set_uint32(&dev->qdev, "hostbus", filter.bus_num);
1582 qdev_prop_set_uint32(&dev->qdev, "hostaddr", filter.addr);
1583 qdev_prop_set_uint32(&dev->qdev, "vendorid", filter.vendor_id);
1584 qdev_prop_set_uint32(&dev->qdev, "productid", filter.product_id);
1585 qdev_init_nofail(&dev->qdev);
1586 return dev;
1587
1588 fail:
1589 qdev_free(&dev->qdev);
1590 return NULL;
1591 }
1592
1593 int usb_host_device_close(const char *devname)
1594 {
1595 #if 0
1596 char product_name[PRODUCT_NAME_SZ];
1597 int bus_num, addr;
1598 USBHostDevice *s;
1599
1600 if (strstr(devname, "auto:")) {
1601 return usb_host_auto_del(devname);
1602 }
1603 if (usb_host_find_device(&bus_num, &addr, product_name,
1604 sizeof(product_name), devname) < 0) {
1605 return -1;
1606 }
1607 s = hostdev_find(bus_num, addr);
1608 if (s) {
1609 usb_device_delete_addr(s->bus_num, s->dev.addr);
1610 return 0;
1611 }
1612 #endif
1613
1614 return -1;
1615 }
1616
1617 /*
1618 * Read sys file-system device file
1619 *
1620 * @line address of buffer to put file contents in
1621 * @line_size size of line
1622 * @device_file path to device file (printf format string)
1623 * @device_name device being opened (inserted into device_file)
1624 *
1625 * @return 0 failed, 1 succeeded ('line' contains data)
1626 */
1627 static int usb_host_read_file(char *line, size_t line_size,
1628 const char *device_file, const char *device_name)
1629 {
1630 FILE *f;
1631 int ret = 0;
1632 char filename[PATH_MAX];
1633
1634 snprintf(filename, PATH_MAX, "/sys/bus/usb/devices/%s/%s", device_name,
1635 device_file);
1636 f = fopen(filename, "r");
1637 if (f) {
1638 ret = fgets(line, line_size, f) != NULL;
1639 fclose(f);
1640 }
1641
1642 return ret;
1643 }
1644
1645 /*
1646 * Use /sys/bus/usb/devices/ directory to determine host's USB
1647 * devices.
1648 *
1649 * This code is based on Robert Schiele's original patches posted to
1650 * the Novell bug-tracker https://bugzilla.novell.com/show_bug.cgi?id=241950
1651 */
1652 static int usb_host_scan(void *opaque, USBScanFunc *func)
1653 {
1654 DIR *dir = NULL;
1655 char line[1024];
1656 int bus_num, addr, speed, class_id, product_id, vendor_id;
1657 int ret = 0;
1658 char port[MAX_PORTLEN];
1659 char product_name[512];
1660 struct dirent *de;
1661
1662 dir = opendir("/sys/bus/usb/devices");
1663 if (!dir) {
1664 perror("husb: opendir /sys/bus/usb/devices");
1665 fprintf(stderr, "husb: please make sure sysfs is mounted at /sys\n");
1666 goto the_end;
1667 }
1668
1669 while ((de = readdir(dir))) {
1670 if (de->d_name[0] != '.' && !strchr(de->d_name, ':')) {
1671 if (sscanf(de->d_name, "%d-%7[0-9.]", &bus_num, port) < 2) {
1672 continue;
1673 }
1674
1675 if (!usb_host_read_file(line, sizeof(line), "devnum", de->d_name)) {
1676 goto the_end;
1677 }
1678 if (sscanf(line, "%d", &addr) != 1) {
1679 goto the_end;
1680 }
1681 if (!usb_host_read_file(line, sizeof(line), "bDeviceClass",
1682 de->d_name)) {
1683 goto the_end;
1684 }
1685 if (sscanf(line, "%x", &class_id) != 1) {
1686 goto the_end;
1687 }
1688
1689 if (!usb_host_read_file(line, sizeof(line), "idVendor",
1690 de->d_name)) {
1691 goto the_end;
1692 }
1693 if (sscanf(line, "%x", &vendor_id) != 1) {
1694 goto the_end;
1695 }
1696 if (!usb_host_read_file(line, sizeof(line), "idProduct",
1697 de->d_name)) {
1698 goto the_end;
1699 }
1700 if (sscanf(line, "%x", &product_id) != 1) {
1701 goto the_end;
1702 }
1703 if (!usb_host_read_file(line, sizeof(line), "product",
1704 de->d_name)) {
1705 *product_name = 0;
1706 } else {
1707 if (strlen(line) > 0) {
1708 line[strlen(line) - 1] = '\0';
1709 }
1710 pstrcpy(product_name, sizeof(product_name), line);
1711 }
1712
1713 if (!usb_host_read_file(line, sizeof(line), "speed", de->d_name)) {
1714 goto the_end;
1715 }
1716 if (!strcmp(line, "5000\n")) {
1717 speed = USB_SPEED_SUPER;
1718 } else if (!strcmp(line, "480\n")) {
1719 speed = USB_SPEED_HIGH;
1720 } else if (!strcmp(line, "1.5\n")) {
1721 speed = USB_SPEED_LOW;
1722 } else {
1723 speed = USB_SPEED_FULL;
1724 }
1725
1726 ret = func(opaque, bus_num, addr, port, class_id, vendor_id,
1727 product_id, product_name, speed);
1728 if (ret) {
1729 goto the_end;
1730 }
1731 }
1732 }
1733 the_end:
1734 if (dir) {
1735 closedir(dir);
1736 }
1737 return ret;
1738 }
1739
1740 static QEMUTimer *usb_auto_timer;
1741 static VMChangeStateEntry *usb_vmstate;
1742
1743 static int usb_host_auto_scan(void *opaque, int bus_num,
1744 int addr, const char *port,
1745 int class_id, int vendor_id, int product_id,
1746 const char *product_name, int speed)
1747 {
1748 struct USBAutoFilter *f;
1749 struct USBHostDevice *s;
1750
1751 /* Ignore hubs */
1752 if (class_id == 9)
1753 return 0;
1754
1755 QTAILQ_FOREACH(s, &hostdevs, next) {
1756 f = &s->match;
1757
1758 if (f->bus_num > 0 && f->bus_num != bus_num) {
1759 continue;
1760 }
1761 if (f->addr > 0 && f->addr != addr) {
1762 continue;
1763 }
1764 if (f->port != NULL && (port == NULL || strcmp(f->port, port) != 0)) {
1765 continue;
1766 }
1767
1768 if (f->vendor_id > 0 && f->vendor_id != vendor_id) {
1769 continue;
1770 }
1771
1772 if (f->product_id > 0 && f->product_id != product_id) {
1773 continue;
1774 }
1775 /* We got a match */
1776 s->seen++;
1777 if (s->errcount >= 3) {
1778 return 0;
1779 }
1780
1781 /* Already attached ? */
1782 if (s->fd != -1) {
1783 return 0;
1784 }
1785 DPRINTF("husb: auto open: bus_num %d addr %d\n", bus_num, addr);
1786
1787 if (usb_host_open(s, bus_num, addr, port, product_name, speed) < 0) {
1788 s->errcount++;
1789 }
1790 break;
1791 }
1792
1793 return 0;
1794 }
1795
1796 static void usb_host_vm_state(void *unused, int running, RunState state)
1797 {
1798 if (running) {
1799 usb_host_auto_check(unused);
1800 }
1801 }
1802
1803 static void usb_host_auto_check(void *unused)
1804 {
1805 struct USBHostDevice *s;
1806 int unconnected = 0;
1807
1808 if (runstate_is_running()) {
1809 usb_host_scan(NULL, usb_host_auto_scan);
1810
1811 QTAILQ_FOREACH(s, &hostdevs, next) {
1812 if (s->fd == -1) {
1813 unconnected++;
1814 }
1815 if (s->seen == 0) {
1816 s->errcount = 0;
1817 }
1818 s->seen = 0;
1819 }
1820
1821 if (unconnected == 0) {
1822 /* nothing to watch */
1823 if (usb_auto_timer) {
1824 qemu_del_timer(usb_auto_timer);
1825 trace_usb_host_auto_scan_disabled();
1826 }
1827 return;
1828 }
1829 }
1830
1831 if (!usb_vmstate) {
1832 usb_vmstate = qemu_add_vm_change_state_handler(usb_host_vm_state, NULL);
1833 }
1834 if (!usb_auto_timer) {
1835 usb_auto_timer = qemu_new_timer_ms(rt_clock, usb_host_auto_check, NULL);
1836 if (!usb_auto_timer) {
1837 return;
1838 }
1839 trace_usb_host_auto_scan_enabled();
1840 }
1841 qemu_mod_timer(usb_auto_timer, qemu_get_clock_ms(rt_clock) + 2000);
1842 }
1843
1844 /*
1845 * Autoconnect filter
1846 * Format:
1847 * auto:bus:dev[:vid:pid]
1848 * auto:bus.dev[:vid:pid]
1849 *
1850 * bus - bus number (dec, * means any)
1851 * dev - device number (dec, * means any)
1852 * vid - vendor id (hex, * means any)
1853 * pid - product id (hex, * means any)
1854 *
1855 * See 'lsusb' output.
1856 */
1857 static int parse_filter(const char *spec, struct USBAutoFilter *f)
1858 {
1859 enum { BUS, DEV, VID, PID, DONE };
1860 const char *p = spec;
1861 int i;
1862
1863 f->bus_num = 0;
1864 f->addr = 0;
1865 f->vendor_id = 0;
1866 f->product_id = 0;
1867
1868 for (i = BUS; i < DONE; i++) {
1869 p = strpbrk(p, ":.");
1870 if (!p) {
1871 break;
1872 }
1873 p++;
1874
1875 if (*p == '*') {
1876 continue;
1877 }
1878 switch(i) {
1879 case BUS: f->bus_num = strtol(p, NULL, 10); break;
1880 case DEV: f->addr = strtol(p, NULL, 10); break;
1881 case VID: f->vendor_id = strtol(p, NULL, 16); break;
1882 case PID: f->product_id = strtol(p, NULL, 16); break;
1883 }
1884 }
1885
1886 if (i < DEV) {
1887 fprintf(stderr, "husb: invalid auto filter spec %s\n", spec);
1888 return -1;
1889 }
1890
1891 return 0;
1892 }
1893
1894 /**********************/
1895 /* USB host device info */
1896
1897 struct usb_class_info {
1898 int class;
1899 const char *class_name;
1900 };
1901
1902 static const struct usb_class_info usb_class_info[] = {
1903 { USB_CLASS_AUDIO, "Audio"},
1904 { USB_CLASS_COMM, "Communication"},
1905 { USB_CLASS_HID, "HID"},
1906 { USB_CLASS_HUB, "Hub" },
1907 { USB_CLASS_PHYSICAL, "Physical" },
1908 { USB_CLASS_PRINTER, "Printer" },
1909 { USB_CLASS_MASS_STORAGE, "Storage" },
1910 { USB_CLASS_CDC_DATA, "Data" },
1911 { USB_CLASS_APP_SPEC, "Application Specific" },
1912 { USB_CLASS_VENDOR_SPEC, "Vendor Specific" },
1913 { USB_CLASS_STILL_IMAGE, "Still Image" },
1914 { USB_CLASS_CSCID, "Smart Card" },
1915 { USB_CLASS_CONTENT_SEC, "Content Security" },
1916 { -1, NULL }
1917 };
1918
1919 static const char *usb_class_str(uint8_t class)
1920 {
1921 const struct usb_class_info *p;
1922 for(p = usb_class_info; p->class != -1; p++) {
1923 if (p->class == class) {
1924 break;
1925 }
1926 }
1927 return p->class_name;
1928 }
1929
1930 static void usb_info_device(Monitor *mon, int bus_num,
1931 int addr, const char *port,
1932 int class_id, int vendor_id, int product_id,
1933 const char *product_name,
1934 int speed)
1935 {
1936 const char *class_str, *speed_str;
1937
1938 switch(speed) {
1939 case USB_SPEED_LOW:
1940 speed_str = "1.5";
1941 break;
1942 case USB_SPEED_FULL:
1943 speed_str = "12";
1944 break;
1945 case USB_SPEED_HIGH:
1946 speed_str = "480";
1947 break;
1948 case USB_SPEED_SUPER:
1949 speed_str = "5000";
1950 break;
1951 default:
1952 speed_str = "?";
1953 break;
1954 }
1955
1956 monitor_printf(mon, " Bus %d, Addr %d, Port %s, Speed %s Mb/s\n",
1957 bus_num, addr, port, speed_str);
1958 class_str = usb_class_str(class_id);
1959 if (class_str) {
1960 monitor_printf(mon, " %s:", class_str);
1961 } else {
1962 monitor_printf(mon, " Class %02x:", class_id);
1963 }
1964 monitor_printf(mon, " USB device %04x:%04x", vendor_id, product_id);
1965 if (product_name[0] != '\0') {
1966 monitor_printf(mon, ", %s", product_name);
1967 }
1968 monitor_printf(mon, "\n");
1969 }
1970
1971 static int usb_host_info_device(void *opaque, int bus_num, int addr,
1972 const char *path, int class_id,
1973 int vendor_id, int product_id,
1974 const char *product_name,
1975 int speed)
1976 {
1977 Monitor *mon = opaque;
1978
1979 usb_info_device(mon, bus_num, addr, path, class_id, vendor_id, product_id,
1980 product_name, speed);
1981 return 0;
1982 }
1983
1984 static void dec2str(int val, char *str, size_t size)
1985 {
1986 if (val == 0) {
1987 snprintf(str, size, "*");
1988 } else {
1989 snprintf(str, size, "%d", val);
1990 }
1991 }
1992
1993 static void hex2str(int val, char *str, size_t size)
1994 {
1995 if (val == 0) {
1996 snprintf(str, size, "*");
1997 } else {
1998 snprintf(str, size, "%04x", val);
1999 }
2000 }
2001
2002 void usb_host_info(Monitor *mon)
2003 {
2004 struct USBAutoFilter *f;
2005 struct USBHostDevice *s;
2006
2007 usb_host_scan(mon, usb_host_info_device);
2008
2009 if (QTAILQ_EMPTY(&hostdevs)) {
2010 return;
2011 }
2012
2013 monitor_printf(mon, " Auto filters:\n");
2014 QTAILQ_FOREACH(s, &hostdevs, next) {
2015 char bus[10], addr[10], vid[10], pid[10];
2016 f = &s->match;
2017 dec2str(f->bus_num, bus, sizeof(bus));
2018 dec2str(f->addr, addr, sizeof(addr));
2019 hex2str(f->vendor_id, vid, sizeof(vid));
2020 hex2str(f->product_id, pid, sizeof(pid));
2021 monitor_printf(mon, " Bus %s, Addr %s, Port %s, ID %s:%s\n",
2022 bus, addr, f->port ? f->port : "*", vid, pid);
2023 }
2024 }