]> git.proxmox.com Git - qemu.git/blob - hw/usb/host-linux.c
Add bootindex support to usb-host and usb-redir
[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 return usb_host_set_address(s, value);
1039
1040 case DeviceOutRequest | USB_REQ_SET_CONFIGURATION:
1041 return usb_host_set_config(s, value & 0xff);
1042
1043 case InterfaceOutRequest | USB_REQ_SET_INTERFACE:
1044 return usb_host_set_interface(s, index, value);
1045 }
1046
1047 /* The rest are asynchronous */
1048
1049 if (length > sizeof(dev->data_buf)) {
1050 fprintf(stderr, "husb: ctrl buffer too small (%d > %zu)\n",
1051 length, sizeof(dev->data_buf));
1052 return USB_RET_STALL;
1053 }
1054
1055 aurb = async_alloc(s);
1056 aurb->packet = p;
1057
1058 /*
1059 * Setup ctrl transfer.
1060 *
1061 * s->ctrl is laid out such that data buffer immediately follows
1062 * 'req' struct which is exactly what usbdevfs expects.
1063 */
1064 urb = &aurb->urb;
1065
1066 urb->type = USBDEVFS_URB_TYPE_CONTROL;
1067 urb->endpoint = p->ep->nr;
1068
1069 urb->buffer = &dev->setup_buf;
1070 urb->buffer_length = length + 8;
1071
1072 urb->usercontext = s;
1073
1074 trace_usb_host_urb_submit(s->bus_num, s->addr, aurb,
1075 urb->buffer_length, aurb->more);
1076 ret = ioctl(s->fd, USBDEVFS_SUBMITURB, urb);
1077
1078 DPRINTF("husb: submit ctrl. len %u aurb %p\n", urb->buffer_length, aurb);
1079
1080 if (ret < 0) {
1081 DPRINTF("husb: submit failed. errno %d\n", errno);
1082 async_free(aurb);
1083
1084 switch(errno) {
1085 case ETIMEDOUT:
1086 return USB_RET_NAK;
1087 case EPIPE:
1088 default:
1089 return USB_RET_STALL;
1090 }
1091 }
1092
1093 return USB_RET_ASYNC;
1094 }
1095
1096 static uint8_t usb_linux_get_alt_setting(USBHostDevice *s,
1097 uint8_t configuration, uint8_t interface)
1098 {
1099 char device_name[64], line[1024];
1100 int alt_setting;
1101
1102 sprintf(device_name, "%d-%s:%d.%d", s->bus_num, s->port,
1103 (int)configuration, (int)interface);
1104
1105 if (!usb_host_read_file(line, sizeof(line), "bAlternateSetting",
1106 device_name)) {
1107 /* Assume alt 0 on error */
1108 return 0;
1109 }
1110 if (sscanf(line, "%d", &alt_setting) != 1) {
1111 /* Assume alt 0 on error */
1112 return 0;
1113 }
1114 return alt_setting;
1115 }
1116
1117 /* returns 1 on problem encountered or 0 for success */
1118 static int usb_linux_update_endp_table(USBHostDevice *s)
1119 {
1120 uint8_t *descriptors;
1121 uint8_t devep, type, alt_interface;
1122 uint16_t raw;
1123 int interface, length, i, ep, pid;
1124 struct endp_data *epd;
1125
1126 usb_ep_init(&s->dev);
1127
1128 if (s->dev.configuration == 0) {
1129 /* not configured yet -- leave all endpoints disabled */
1130 return 0;
1131 }
1132
1133 /* get the desired configuration, interface, and endpoint descriptors
1134 * from device description */
1135 descriptors = &s->descr[18];
1136 length = s->descr_len - 18;
1137 i = 0;
1138
1139 while (i < length) {
1140 if (descriptors[i + 1] != USB_DT_CONFIG) {
1141 fprintf(stderr, "invalid descriptor data\n");
1142 return 1;
1143 } else if (descriptors[i + 5] != s->dev.configuration) {
1144 DPRINTF("not requested configuration %d\n", s->dev.configuration);
1145 i += (descriptors[i + 3] << 8) + descriptors[i + 2];
1146 continue;
1147 }
1148 i += descriptors[i];
1149
1150 if (descriptors[i + 1] != USB_DT_INTERFACE ||
1151 (descriptors[i + 1] == USB_DT_INTERFACE &&
1152 descriptors[i + 4] == 0)) {
1153 i += descriptors[i];
1154 continue;
1155 }
1156
1157 interface = descriptors[i + 2];
1158 alt_interface = usb_linux_get_alt_setting(s, s->dev.configuration,
1159 interface);
1160
1161 /* the current interface descriptor is the active interface
1162 * and has endpoints */
1163 if (descriptors[i + 3] != alt_interface) {
1164 i += descriptors[i];
1165 continue;
1166 }
1167
1168 /* advance to the endpoints */
1169 while (i < length && descriptors[i +1] != USB_DT_ENDPOINT) {
1170 i += descriptors[i];
1171 }
1172
1173 if (i >= length)
1174 break;
1175
1176 while (i < length) {
1177 if (descriptors[i + 1] != USB_DT_ENDPOINT) {
1178 break;
1179 }
1180
1181 devep = descriptors[i + 2];
1182 pid = (devep & USB_DIR_IN) ? USB_TOKEN_IN : USB_TOKEN_OUT;
1183 ep = devep & 0xf;
1184 if (ep == 0) {
1185 fprintf(stderr, "usb-linux: invalid ep descriptor, ep == 0\n");
1186 return 1;
1187 }
1188
1189 type = descriptors[i + 3] & 0x3;
1190 raw = descriptors[i + 4] + (descriptors[i + 5] << 8);
1191 usb_ep_set_max_packet_size(&s->dev, pid, ep, raw);
1192 assert(usb_ep_get_type(&s->dev, pid, ep) ==
1193 USB_ENDPOINT_XFER_INVALID);
1194 usb_ep_set_type(&s->dev, pid, ep, type);
1195 usb_ep_set_ifnum(&s->dev, pid, ep, interface);
1196 if (type == USB_ENDPOINT_XFER_BULK) {
1197 usb_ep_set_pipeline(&s->dev, pid, ep, true);
1198 }
1199
1200 epd = get_endp(s, pid, ep);
1201 epd->halted = 0;
1202
1203 i += descriptors[i];
1204 }
1205 }
1206 #ifdef DEBUG
1207 usb_ep_dump(&s->dev);
1208 #endif
1209 return 0;
1210 }
1211
1212 /*
1213 * Check if we can safely redirect a usb2 device to a usb1 virtual controller,
1214 * this function assumes this is safe, if:
1215 * 1) There are no isoc endpoints
1216 * 2) There are no interrupt endpoints with a max_packet_size > 64
1217 * Note bulk endpoints with a max_packet_size > 64 in theory also are not
1218 * usb1 compatible, but in practice this seems to work fine.
1219 */
1220 static int usb_linux_full_speed_compat(USBHostDevice *dev)
1221 {
1222 int i, packet_size;
1223
1224 /*
1225 * usb_linux_update_endp_table only registers info about ep in the current
1226 * interface altsettings, so we need to parse the descriptors again.
1227 */
1228 for (i = 0; (i + 5) < dev->descr_len; i += dev->descr[i]) {
1229 if (dev->descr[i + 1] == USB_DT_ENDPOINT) {
1230 switch (dev->descr[i + 3] & 0x3) {
1231 case 0x00: /* CONTROL */
1232 break;
1233 case 0x01: /* ISO */
1234 return 0;
1235 case 0x02: /* BULK */
1236 break;
1237 case 0x03: /* INTERRUPT */
1238 packet_size = dev->descr[i + 4] + (dev->descr[i + 5] << 8);
1239 if (packet_size > 64)
1240 return 0;
1241 break;
1242 }
1243 }
1244 }
1245 return 1;
1246 }
1247
1248 static int usb_host_open(USBHostDevice *dev, int bus_num,
1249 int addr, const char *port,
1250 const char *prod_name, int speed)
1251 {
1252 int fd = -1, ret;
1253
1254 trace_usb_host_open_started(bus_num, addr);
1255
1256 if (dev->fd != -1) {
1257 goto fail;
1258 }
1259
1260 fd = usb_host_open_device(bus_num, addr);
1261 if (fd < 0) {
1262 goto fail;
1263 }
1264 DPRINTF("husb: opened %s\n", buf);
1265
1266 dev->bus_num = bus_num;
1267 dev->addr = addr;
1268 strcpy(dev->port, port);
1269 dev->fd = fd;
1270
1271 /* read the device description */
1272 dev->descr_len = read(fd, dev->descr, sizeof(dev->descr));
1273 if (dev->descr_len <= 0) {
1274 perror("husb: reading device data failed");
1275 goto fail;
1276 }
1277
1278 #ifdef DEBUG
1279 {
1280 int x;
1281 printf("=== begin dumping device descriptor data ===\n");
1282 for (x = 0; x < dev->descr_len; x++) {
1283 printf("%02x ", dev->descr[x]);
1284 }
1285 printf("\n=== end dumping device descriptor data ===\n");
1286 }
1287 #endif
1288
1289
1290 /* start unconfigured -- we'll wait for the guest to set a configuration */
1291 if (!usb_host_claim_interfaces(dev, 0)) {
1292 goto fail;
1293 }
1294
1295 ret = usb_linux_update_endp_table(dev);
1296 if (ret) {
1297 goto fail;
1298 }
1299
1300 if (speed == -1) {
1301 struct usbdevfs_connectinfo ci;
1302
1303 ret = ioctl(fd, USBDEVFS_CONNECTINFO, &ci);
1304 if (ret < 0) {
1305 perror("usb_host_device_open: USBDEVFS_CONNECTINFO");
1306 goto fail;
1307 }
1308
1309 if (ci.slow) {
1310 speed = USB_SPEED_LOW;
1311 } else {
1312 speed = USB_SPEED_HIGH;
1313 }
1314 }
1315 dev->dev.speed = speed;
1316 dev->dev.speedmask = (1 << speed);
1317 if (dev->dev.speed == USB_SPEED_HIGH && usb_linux_full_speed_compat(dev)) {
1318 dev->dev.speedmask |= USB_SPEED_MASK_FULL;
1319 }
1320
1321 trace_usb_host_open_success(bus_num, addr);
1322
1323 if (!prod_name || prod_name[0] == '\0') {
1324 snprintf(dev->dev.product_desc, sizeof(dev->dev.product_desc),
1325 "host:%d.%d", bus_num, addr);
1326 } else {
1327 pstrcpy(dev->dev.product_desc, sizeof(dev->dev.product_desc),
1328 prod_name);
1329 }
1330
1331 ret = usb_device_attach(&dev->dev);
1332 if (ret) {
1333 goto fail;
1334 }
1335
1336 /* USB devio uses 'write' flag to check for async completions */
1337 qemu_set_fd_handler(dev->fd, NULL, async_complete, dev);
1338
1339 return 0;
1340
1341 fail:
1342 trace_usb_host_open_failure(bus_num, addr);
1343 if (dev->fd != -1) {
1344 close(dev->fd);
1345 dev->fd = -1;
1346 }
1347 return -1;
1348 }
1349
1350 static int usb_host_close(USBHostDevice *dev)
1351 {
1352 int i;
1353
1354 if (dev->fd == -1) {
1355 return -1;
1356 }
1357
1358 trace_usb_host_close(dev->bus_num, dev->addr);
1359
1360 qemu_set_fd_handler(dev->fd, NULL, NULL, NULL);
1361 dev->closing = 1;
1362 for (i = 1; i <= USB_MAX_ENDPOINTS; i++) {
1363 if (is_isoc(dev, USB_TOKEN_IN, i)) {
1364 usb_host_stop_n_free_iso(dev, USB_TOKEN_IN, i);
1365 }
1366 if (is_isoc(dev, USB_TOKEN_OUT, i)) {
1367 usb_host_stop_n_free_iso(dev, USB_TOKEN_OUT, i);
1368 }
1369 }
1370 async_complete(dev);
1371 dev->closing = 0;
1372 if (dev->dev.attached) {
1373 usb_device_detach(&dev->dev);
1374 }
1375 usb_host_do_reset(dev);
1376 close(dev->fd);
1377 dev->fd = -1;
1378 return 0;
1379 }
1380
1381 static void usb_host_exit_notifier(struct Notifier *n, void *data)
1382 {
1383 USBHostDevice *s = container_of(n, USBHostDevice, exit);
1384
1385 usb_host_release_port(s);
1386 if (s->fd != -1) {
1387 usb_host_do_reset(s);;
1388 }
1389 }
1390
1391 static int usb_host_initfn(USBDevice *dev)
1392 {
1393 USBHostDevice *s = DO_UPCAST(USBHostDevice, dev, dev);
1394
1395 dev->auto_attach = 0;
1396 s->fd = -1;
1397 s->hub_fd = -1;
1398
1399 QTAILQ_INSERT_TAIL(&hostdevs, s, next);
1400 s->exit.notify = usb_host_exit_notifier;
1401 qemu_add_exit_notifier(&s->exit);
1402 usb_host_auto_check(NULL);
1403
1404 if (s->match.bus_num != 0 && s->match.port != NULL) {
1405 usb_host_claim_port(s);
1406 }
1407 add_boot_device_path(s->bootindex, &dev->qdev, NULL);
1408 return 0;
1409 }
1410
1411 static const VMStateDescription vmstate_usb_host = {
1412 .name = "usb-host",
1413 .unmigratable = 1,
1414 };
1415
1416 static Property usb_host_dev_properties[] = {
1417 DEFINE_PROP_UINT32("hostbus", USBHostDevice, match.bus_num, 0),
1418 DEFINE_PROP_UINT32("hostaddr", USBHostDevice, match.addr, 0),
1419 DEFINE_PROP_STRING("hostport", USBHostDevice, match.port),
1420 DEFINE_PROP_HEX32("vendorid", USBHostDevice, match.vendor_id, 0),
1421 DEFINE_PROP_HEX32("productid", USBHostDevice, match.product_id, 0),
1422 DEFINE_PROP_UINT32("isobufs", USBHostDevice, iso_urb_count, 4),
1423 DEFINE_PROP_INT32("bootindex", USBHostDevice, bootindex, -1),
1424 DEFINE_PROP_END_OF_LIST(),
1425 };
1426
1427 static void usb_host_class_initfn(ObjectClass *klass, void *data)
1428 {
1429 DeviceClass *dc = DEVICE_CLASS(klass);
1430 USBDeviceClass *uc = USB_DEVICE_CLASS(klass);
1431
1432 uc->init = usb_host_initfn;
1433 uc->product_desc = "USB Host Device";
1434 uc->cancel_packet = usb_host_async_cancel;
1435 uc->handle_data = usb_host_handle_data;
1436 uc->handle_control = usb_host_handle_control;
1437 uc->handle_reset = usb_host_handle_reset;
1438 uc->handle_destroy = usb_host_handle_destroy;
1439 dc->vmsd = &vmstate_usb_host;
1440 dc->props = usb_host_dev_properties;
1441 }
1442
1443 static TypeInfo usb_host_dev_info = {
1444 .name = "usb-host",
1445 .parent = TYPE_USB_DEVICE,
1446 .instance_size = sizeof(USBHostDevice),
1447 .class_init = usb_host_class_initfn,
1448 };
1449
1450 static void usb_host_register_types(void)
1451 {
1452 type_register_static(&usb_host_dev_info);
1453 usb_legacy_register("usb-host", "host", usb_host_device_open);
1454 }
1455
1456 type_init(usb_host_register_types)
1457
1458 USBDevice *usb_host_device_open(USBBus *bus, const char *devname)
1459 {
1460 struct USBAutoFilter filter;
1461 USBDevice *dev;
1462 char *p;
1463
1464 dev = usb_create(bus, "usb-host");
1465
1466 if (strstr(devname, "auto:")) {
1467 if (parse_filter(devname, &filter) < 0) {
1468 goto fail;
1469 }
1470 } else {
1471 if ((p = strchr(devname, '.'))) {
1472 filter.bus_num = strtoul(devname, NULL, 0);
1473 filter.addr = strtoul(p + 1, NULL, 0);
1474 filter.vendor_id = 0;
1475 filter.product_id = 0;
1476 } else if ((p = strchr(devname, ':'))) {
1477 filter.bus_num = 0;
1478 filter.addr = 0;
1479 filter.vendor_id = strtoul(devname, NULL, 16);
1480 filter.product_id = strtoul(p + 1, NULL, 16);
1481 } else {
1482 goto fail;
1483 }
1484 }
1485
1486 qdev_prop_set_uint32(&dev->qdev, "hostbus", filter.bus_num);
1487 qdev_prop_set_uint32(&dev->qdev, "hostaddr", filter.addr);
1488 qdev_prop_set_uint32(&dev->qdev, "vendorid", filter.vendor_id);
1489 qdev_prop_set_uint32(&dev->qdev, "productid", filter.product_id);
1490 qdev_init_nofail(&dev->qdev);
1491 return dev;
1492
1493 fail:
1494 qdev_free(&dev->qdev);
1495 return NULL;
1496 }
1497
1498 int usb_host_device_close(const char *devname)
1499 {
1500 #if 0
1501 char product_name[PRODUCT_NAME_SZ];
1502 int bus_num, addr;
1503 USBHostDevice *s;
1504
1505 if (strstr(devname, "auto:")) {
1506 return usb_host_auto_del(devname);
1507 }
1508 if (usb_host_find_device(&bus_num, &addr, product_name,
1509 sizeof(product_name), devname) < 0) {
1510 return -1;
1511 }
1512 s = hostdev_find(bus_num, addr);
1513 if (s) {
1514 usb_device_delete_addr(s->bus_num, s->dev.addr);
1515 return 0;
1516 }
1517 #endif
1518
1519 return -1;
1520 }
1521
1522 /*
1523 * Read sys file-system device file
1524 *
1525 * @line address of buffer to put file contents in
1526 * @line_size size of line
1527 * @device_file path to device file (printf format string)
1528 * @device_name device being opened (inserted into device_file)
1529 *
1530 * @return 0 failed, 1 succeeded ('line' contains data)
1531 */
1532 static int usb_host_read_file(char *line, size_t line_size,
1533 const char *device_file, const char *device_name)
1534 {
1535 FILE *f;
1536 int ret = 0;
1537 char filename[PATH_MAX];
1538
1539 snprintf(filename, PATH_MAX, "/sys/bus/usb/devices/%s/%s", device_name,
1540 device_file);
1541 f = fopen(filename, "r");
1542 if (f) {
1543 ret = fgets(line, line_size, f) != NULL;
1544 fclose(f);
1545 }
1546
1547 return ret;
1548 }
1549
1550 /*
1551 * Use /sys/bus/usb/devices/ directory to determine host's USB
1552 * devices.
1553 *
1554 * This code is based on Robert Schiele's original patches posted to
1555 * the Novell bug-tracker https://bugzilla.novell.com/show_bug.cgi?id=241950
1556 */
1557 static int usb_host_scan(void *opaque, USBScanFunc *func)
1558 {
1559 DIR *dir = NULL;
1560 char line[1024];
1561 int bus_num, addr, speed, class_id, product_id, vendor_id;
1562 int ret = 0;
1563 char port[MAX_PORTLEN];
1564 char product_name[512];
1565 struct dirent *de;
1566
1567 dir = opendir("/sys/bus/usb/devices");
1568 if (!dir) {
1569 perror("husb: opendir /sys/bus/usb/devices");
1570 fprintf(stderr, "husb: please make sure sysfs is mounted at /sys\n");
1571 goto the_end;
1572 }
1573
1574 while ((de = readdir(dir))) {
1575 if (de->d_name[0] != '.' && !strchr(de->d_name, ':')) {
1576 if (sscanf(de->d_name, "%d-%7[0-9.]", &bus_num, port) < 2) {
1577 continue;
1578 }
1579
1580 if (!usb_host_read_file(line, sizeof(line), "devnum", de->d_name)) {
1581 goto the_end;
1582 }
1583 if (sscanf(line, "%d", &addr) != 1) {
1584 goto the_end;
1585 }
1586 if (!usb_host_read_file(line, sizeof(line), "bDeviceClass",
1587 de->d_name)) {
1588 goto the_end;
1589 }
1590 if (sscanf(line, "%x", &class_id) != 1) {
1591 goto the_end;
1592 }
1593
1594 if (!usb_host_read_file(line, sizeof(line), "idVendor",
1595 de->d_name)) {
1596 goto the_end;
1597 }
1598 if (sscanf(line, "%x", &vendor_id) != 1) {
1599 goto the_end;
1600 }
1601 if (!usb_host_read_file(line, sizeof(line), "idProduct",
1602 de->d_name)) {
1603 goto the_end;
1604 }
1605 if (sscanf(line, "%x", &product_id) != 1) {
1606 goto the_end;
1607 }
1608 if (!usb_host_read_file(line, sizeof(line), "product",
1609 de->d_name)) {
1610 *product_name = 0;
1611 } else {
1612 if (strlen(line) > 0) {
1613 line[strlen(line) - 1] = '\0';
1614 }
1615 pstrcpy(product_name, sizeof(product_name), line);
1616 }
1617
1618 if (!usb_host_read_file(line, sizeof(line), "speed", de->d_name)) {
1619 goto the_end;
1620 }
1621 if (!strcmp(line, "5000\n")) {
1622 speed = USB_SPEED_SUPER;
1623 } else if (!strcmp(line, "480\n")) {
1624 speed = USB_SPEED_HIGH;
1625 } else if (!strcmp(line, "1.5\n")) {
1626 speed = USB_SPEED_LOW;
1627 } else {
1628 speed = USB_SPEED_FULL;
1629 }
1630
1631 ret = func(opaque, bus_num, addr, port, class_id, vendor_id,
1632 product_id, product_name, speed);
1633 if (ret) {
1634 goto the_end;
1635 }
1636 }
1637 }
1638 the_end:
1639 if (dir) {
1640 closedir(dir);
1641 }
1642 return ret;
1643 }
1644
1645 static QEMUTimer *usb_auto_timer;
1646
1647 static int usb_host_auto_scan(void *opaque, int bus_num,
1648 int addr, const char *port,
1649 int class_id, int vendor_id, int product_id,
1650 const char *product_name, int speed)
1651 {
1652 struct USBAutoFilter *f;
1653 struct USBHostDevice *s;
1654
1655 /* Ignore hubs */
1656 if (class_id == 9)
1657 return 0;
1658
1659 QTAILQ_FOREACH(s, &hostdevs, next) {
1660 f = &s->match;
1661
1662 if (f->bus_num > 0 && f->bus_num != bus_num) {
1663 continue;
1664 }
1665 if (f->addr > 0 && f->addr != addr) {
1666 continue;
1667 }
1668 if (f->port != NULL && (port == NULL || strcmp(f->port, port) != 0)) {
1669 continue;
1670 }
1671
1672 if (f->vendor_id > 0 && f->vendor_id != vendor_id) {
1673 continue;
1674 }
1675
1676 if (f->product_id > 0 && f->product_id != product_id) {
1677 continue;
1678 }
1679 /* We got a match */
1680 s->seen++;
1681 if (s->errcount >= 3) {
1682 return 0;
1683 }
1684
1685 /* Already attached ? */
1686 if (s->fd != -1) {
1687 return 0;
1688 }
1689 DPRINTF("husb: auto open: bus_num %d addr %d\n", bus_num, addr);
1690
1691 if (usb_host_open(s, bus_num, addr, port, product_name, speed) < 0) {
1692 s->errcount++;
1693 }
1694 break;
1695 }
1696
1697 return 0;
1698 }
1699
1700 static void usb_host_auto_check(void *unused)
1701 {
1702 struct USBHostDevice *s;
1703 int unconnected = 0;
1704
1705 usb_host_scan(NULL, usb_host_auto_scan);
1706
1707 QTAILQ_FOREACH(s, &hostdevs, next) {
1708 if (s->fd == -1) {
1709 unconnected++;
1710 }
1711 if (s->seen == 0) {
1712 s->errcount = 0;
1713 }
1714 s->seen = 0;
1715 }
1716
1717 if (unconnected == 0) {
1718 /* nothing to watch */
1719 if (usb_auto_timer) {
1720 qemu_del_timer(usb_auto_timer);
1721 trace_usb_host_auto_scan_disabled();
1722 }
1723 return;
1724 }
1725
1726 if (!usb_auto_timer) {
1727 usb_auto_timer = qemu_new_timer_ms(rt_clock, usb_host_auto_check, NULL);
1728 if (!usb_auto_timer) {
1729 return;
1730 }
1731 trace_usb_host_auto_scan_enabled();
1732 }
1733 qemu_mod_timer(usb_auto_timer, qemu_get_clock_ms(rt_clock) + 2000);
1734 }
1735
1736 /*
1737 * Autoconnect filter
1738 * Format:
1739 * auto:bus:dev[:vid:pid]
1740 * auto:bus.dev[:vid:pid]
1741 *
1742 * bus - bus number (dec, * means any)
1743 * dev - device number (dec, * means any)
1744 * vid - vendor id (hex, * means any)
1745 * pid - product id (hex, * means any)
1746 *
1747 * See 'lsusb' output.
1748 */
1749 static int parse_filter(const char *spec, struct USBAutoFilter *f)
1750 {
1751 enum { BUS, DEV, VID, PID, DONE };
1752 const char *p = spec;
1753 int i;
1754
1755 f->bus_num = 0;
1756 f->addr = 0;
1757 f->vendor_id = 0;
1758 f->product_id = 0;
1759
1760 for (i = BUS; i < DONE; i++) {
1761 p = strpbrk(p, ":.");
1762 if (!p) {
1763 break;
1764 }
1765 p++;
1766
1767 if (*p == '*') {
1768 continue;
1769 }
1770 switch(i) {
1771 case BUS: f->bus_num = strtol(p, NULL, 10); break;
1772 case DEV: f->addr = strtol(p, NULL, 10); break;
1773 case VID: f->vendor_id = strtol(p, NULL, 16); break;
1774 case PID: f->product_id = strtol(p, NULL, 16); break;
1775 }
1776 }
1777
1778 if (i < DEV) {
1779 fprintf(stderr, "husb: invalid auto filter spec %s\n", spec);
1780 return -1;
1781 }
1782
1783 return 0;
1784 }
1785
1786 /**********************/
1787 /* USB host device info */
1788
1789 struct usb_class_info {
1790 int class;
1791 const char *class_name;
1792 };
1793
1794 static const struct usb_class_info usb_class_info[] = {
1795 { USB_CLASS_AUDIO, "Audio"},
1796 { USB_CLASS_COMM, "Communication"},
1797 { USB_CLASS_HID, "HID"},
1798 { USB_CLASS_HUB, "Hub" },
1799 { USB_CLASS_PHYSICAL, "Physical" },
1800 { USB_CLASS_PRINTER, "Printer" },
1801 { USB_CLASS_MASS_STORAGE, "Storage" },
1802 { USB_CLASS_CDC_DATA, "Data" },
1803 { USB_CLASS_APP_SPEC, "Application Specific" },
1804 { USB_CLASS_VENDOR_SPEC, "Vendor Specific" },
1805 { USB_CLASS_STILL_IMAGE, "Still Image" },
1806 { USB_CLASS_CSCID, "Smart Card" },
1807 { USB_CLASS_CONTENT_SEC, "Content Security" },
1808 { -1, NULL }
1809 };
1810
1811 static const char *usb_class_str(uint8_t class)
1812 {
1813 const struct usb_class_info *p;
1814 for(p = usb_class_info; p->class != -1; p++) {
1815 if (p->class == class) {
1816 break;
1817 }
1818 }
1819 return p->class_name;
1820 }
1821
1822 static void usb_info_device(Monitor *mon, int bus_num,
1823 int addr, const char *port,
1824 int class_id, int vendor_id, int product_id,
1825 const char *product_name,
1826 int speed)
1827 {
1828 const char *class_str, *speed_str;
1829
1830 switch(speed) {
1831 case USB_SPEED_LOW:
1832 speed_str = "1.5";
1833 break;
1834 case USB_SPEED_FULL:
1835 speed_str = "12";
1836 break;
1837 case USB_SPEED_HIGH:
1838 speed_str = "480";
1839 break;
1840 case USB_SPEED_SUPER:
1841 speed_str = "5000";
1842 break;
1843 default:
1844 speed_str = "?";
1845 break;
1846 }
1847
1848 monitor_printf(mon, " Bus %d, Addr %d, Port %s, Speed %s Mb/s\n",
1849 bus_num, addr, port, speed_str);
1850 class_str = usb_class_str(class_id);
1851 if (class_str) {
1852 monitor_printf(mon, " %s:", class_str);
1853 } else {
1854 monitor_printf(mon, " Class %02x:", class_id);
1855 }
1856 monitor_printf(mon, " USB device %04x:%04x", vendor_id, product_id);
1857 if (product_name[0] != '\0') {
1858 monitor_printf(mon, ", %s", product_name);
1859 }
1860 monitor_printf(mon, "\n");
1861 }
1862
1863 static int usb_host_info_device(void *opaque, int bus_num, int addr,
1864 const char *path, int class_id,
1865 int vendor_id, int product_id,
1866 const char *product_name,
1867 int speed)
1868 {
1869 Monitor *mon = opaque;
1870
1871 usb_info_device(mon, bus_num, addr, path, class_id, vendor_id, product_id,
1872 product_name, speed);
1873 return 0;
1874 }
1875
1876 static void dec2str(int val, char *str, size_t size)
1877 {
1878 if (val == 0) {
1879 snprintf(str, size, "*");
1880 } else {
1881 snprintf(str, size, "%d", val);
1882 }
1883 }
1884
1885 static void hex2str(int val, char *str, size_t size)
1886 {
1887 if (val == 0) {
1888 snprintf(str, size, "*");
1889 } else {
1890 snprintf(str, size, "%04x", val);
1891 }
1892 }
1893
1894 void usb_host_info(Monitor *mon)
1895 {
1896 struct USBAutoFilter *f;
1897 struct USBHostDevice *s;
1898
1899 usb_host_scan(mon, usb_host_info_device);
1900
1901 if (QTAILQ_EMPTY(&hostdevs)) {
1902 return;
1903 }
1904
1905 monitor_printf(mon, " Auto filters:\n");
1906 QTAILQ_FOREACH(s, &hostdevs, next) {
1907 char bus[10], addr[10], vid[10], pid[10];
1908 f = &s->match;
1909 dec2str(f->bus_num, bus, sizeof(bus));
1910 dec2str(f->addr, addr, sizeof(addr));
1911 hex2str(f->vendor_id, vid, sizeof(vid));
1912 hex2str(f->product_id, pid, sizeof(pid));
1913 monitor_printf(mon, " Bus %s, Addr %s, Port %s, ID %s:%s\n",
1914 bus, addr, f->port ? f->port : "*", vid, pid);
1915 }
1916 }