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