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