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