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