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