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