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