]> git.proxmox.com Git - qemu.git/blob - hw/usb/host-linux.c
usb: split endpoint init and reset
[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_reset(&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_reset(&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 usb_ep_init(&dev->dev);
1330 ret = usb_linux_update_endp_table(dev);
1331 if (ret) {
1332 goto fail;
1333 }
1334
1335 if (speed == -1) {
1336 struct usbdevfs_connectinfo ci;
1337
1338 ret = ioctl(fd, USBDEVFS_CONNECTINFO, &ci);
1339 if (ret < 0) {
1340 perror("usb_host_device_open: USBDEVFS_CONNECTINFO");
1341 goto fail;
1342 }
1343
1344 if (ci.slow) {
1345 speed = USB_SPEED_LOW;
1346 } else {
1347 speed = USB_SPEED_HIGH;
1348 }
1349 }
1350 dev->dev.speed = speed;
1351 dev->dev.speedmask = (1 << speed);
1352 if (dev->dev.speed == USB_SPEED_HIGH && usb_linux_full_speed_compat(dev)) {
1353 dev->dev.speedmask |= USB_SPEED_MASK_FULL;
1354 }
1355
1356 trace_usb_host_open_success(bus_num, addr);
1357
1358 if (!prod_name || prod_name[0] == '\0') {
1359 snprintf(dev->dev.product_desc, sizeof(dev->dev.product_desc),
1360 "host:%d.%d", bus_num, addr);
1361 } else {
1362 pstrcpy(dev->dev.product_desc, sizeof(dev->dev.product_desc),
1363 prod_name);
1364 }
1365
1366 ret = usb_device_attach(&dev->dev);
1367 if (ret) {
1368 goto fail;
1369 }
1370
1371 /* USB devio uses 'write' flag to check for async completions */
1372 qemu_set_fd_handler(dev->fd, NULL, async_complete, dev);
1373
1374 return 0;
1375
1376 fail:
1377 trace_usb_host_open_failure(bus_num, addr);
1378 if (dev->fd != -1) {
1379 close(dev->fd);
1380 dev->fd = -1;
1381 }
1382 return -1;
1383 }
1384
1385 static int usb_host_close(USBHostDevice *dev)
1386 {
1387 int i;
1388
1389 if (dev->fd == -1) {
1390 return -1;
1391 }
1392
1393 trace_usb_host_close(dev->bus_num, dev->addr);
1394
1395 qemu_set_fd_handler(dev->fd, NULL, NULL, NULL);
1396 dev->closing = 1;
1397 for (i = 1; i <= USB_MAX_ENDPOINTS; i++) {
1398 if (is_isoc(dev, USB_TOKEN_IN, i)) {
1399 usb_host_stop_n_free_iso(dev, USB_TOKEN_IN, i);
1400 }
1401 if (is_isoc(dev, USB_TOKEN_OUT, i)) {
1402 usb_host_stop_n_free_iso(dev, USB_TOKEN_OUT, i);
1403 }
1404 }
1405 async_complete(dev);
1406 dev->closing = 0;
1407 if (dev->dev.attached) {
1408 usb_device_detach(&dev->dev);
1409 }
1410 usb_host_do_reset(dev);
1411 close(dev->fd);
1412 dev->fd = -1;
1413 return 0;
1414 }
1415
1416 static void usb_host_exit_notifier(struct Notifier *n, void *data)
1417 {
1418 USBHostDevice *s = container_of(n, USBHostDevice, exit);
1419
1420 usb_host_release_port(s);
1421 if (s->fd != -1) {
1422 usb_host_do_reset(s);;
1423 }
1424 }
1425
1426 /*
1427 * This is *NOT* about restoring state. We have absolutely no idea
1428 * what state the host device is in at the moment and whenever it is
1429 * still present in the first place. Attemping to contine where we
1430 * left off is impossible.
1431 *
1432 * What we are going to to to here is emulate a surprise removal of
1433 * the usb device passed through, then kick host scan so the device
1434 * will get re-attached (and re-initialized by the guest) in case it
1435 * is still present.
1436 *
1437 * As the device removal will change the state of other devices (usb
1438 * host controller, most likely interrupt controller too) we have to
1439 * wait with it until *all* vmstate is loaded. Thus post_load just
1440 * kicks a bottom half which then does the actual work.
1441 */
1442 static void usb_host_post_load_bh(void *opaque)
1443 {
1444 USBHostDevice *dev = opaque;
1445
1446 if (dev->fd != -1) {
1447 usb_host_close(dev);
1448 }
1449 if (dev->dev.attached) {
1450 usb_device_detach(&dev->dev);
1451 }
1452 usb_host_auto_check(NULL);
1453 }
1454
1455 static int usb_host_post_load(void *opaque, int version_id)
1456 {
1457 USBHostDevice *dev = opaque;
1458
1459 qemu_bh_schedule(dev->bh);
1460 return 0;
1461 }
1462
1463 static int usb_host_initfn(USBDevice *dev)
1464 {
1465 USBHostDevice *s = DO_UPCAST(USBHostDevice, dev, dev);
1466
1467 dev->auto_attach = 0;
1468 s->fd = -1;
1469 s->hub_fd = -1;
1470
1471 QTAILQ_INSERT_TAIL(&hostdevs, s, next);
1472 s->exit.notify = usb_host_exit_notifier;
1473 qemu_add_exit_notifier(&s->exit);
1474 s->bh = qemu_bh_new(usb_host_post_load_bh, s);
1475 usb_host_auto_check(NULL);
1476
1477 if (s->match.bus_num != 0 && s->match.port != NULL) {
1478 usb_host_claim_port(s);
1479 }
1480 add_boot_device_path(s->bootindex, &dev->qdev, NULL);
1481 return 0;
1482 }
1483
1484 static const VMStateDescription vmstate_usb_host = {
1485 .name = "usb-host",
1486 .version_id = 1,
1487 .minimum_version_id = 1,
1488 .post_load = usb_host_post_load,
1489 .fields = (VMStateField[]) {
1490 VMSTATE_USB_DEVICE(dev, USBHostDevice),
1491 VMSTATE_END_OF_LIST()
1492 }
1493 };
1494
1495 static Property usb_host_dev_properties[] = {
1496 DEFINE_PROP_UINT32("hostbus", USBHostDevice, match.bus_num, 0),
1497 DEFINE_PROP_UINT32("hostaddr", USBHostDevice, match.addr, 0),
1498 DEFINE_PROP_STRING("hostport", USBHostDevice, match.port),
1499 DEFINE_PROP_HEX32("vendorid", USBHostDevice, match.vendor_id, 0),
1500 DEFINE_PROP_HEX32("productid", USBHostDevice, match.product_id, 0),
1501 DEFINE_PROP_UINT32("isobufs", USBHostDevice, iso_urb_count, 4),
1502 DEFINE_PROP_INT32("bootindex", USBHostDevice, bootindex, -1),
1503 DEFINE_PROP_BIT("pipeline", USBHostDevice, options,
1504 USB_HOST_OPT_PIPELINE, true),
1505 DEFINE_PROP_END_OF_LIST(),
1506 };
1507
1508 static void usb_host_class_initfn(ObjectClass *klass, void *data)
1509 {
1510 DeviceClass *dc = DEVICE_CLASS(klass);
1511 USBDeviceClass *uc = USB_DEVICE_CLASS(klass);
1512
1513 uc->init = usb_host_initfn;
1514 uc->product_desc = "USB Host Device";
1515 uc->cancel_packet = usb_host_async_cancel;
1516 uc->handle_data = usb_host_handle_data;
1517 uc->handle_control = usb_host_handle_control;
1518 uc->handle_reset = usb_host_handle_reset;
1519 uc->handle_destroy = usb_host_handle_destroy;
1520 dc->vmsd = &vmstate_usb_host;
1521 dc->props = usb_host_dev_properties;
1522 }
1523
1524 static TypeInfo usb_host_dev_info = {
1525 .name = "usb-host",
1526 .parent = TYPE_USB_DEVICE,
1527 .instance_size = sizeof(USBHostDevice),
1528 .class_init = usb_host_class_initfn,
1529 };
1530
1531 static void usb_host_register_types(void)
1532 {
1533 type_register_static(&usb_host_dev_info);
1534 usb_legacy_register("usb-host", "host", usb_host_device_open);
1535 }
1536
1537 type_init(usb_host_register_types)
1538
1539 USBDevice *usb_host_device_open(USBBus *bus, const char *devname)
1540 {
1541 struct USBAutoFilter filter;
1542 USBDevice *dev;
1543 char *p;
1544
1545 dev = usb_create(bus, "usb-host");
1546
1547 if (strstr(devname, "auto:")) {
1548 if (parse_filter(devname, &filter) < 0) {
1549 goto fail;
1550 }
1551 } else {
1552 if ((p = strchr(devname, '.'))) {
1553 filter.bus_num = strtoul(devname, NULL, 0);
1554 filter.addr = strtoul(p + 1, NULL, 0);
1555 filter.vendor_id = 0;
1556 filter.product_id = 0;
1557 } else if ((p = strchr(devname, ':'))) {
1558 filter.bus_num = 0;
1559 filter.addr = 0;
1560 filter.vendor_id = strtoul(devname, NULL, 16);
1561 filter.product_id = strtoul(p + 1, NULL, 16);
1562 } else {
1563 goto fail;
1564 }
1565 }
1566
1567 qdev_prop_set_uint32(&dev->qdev, "hostbus", filter.bus_num);
1568 qdev_prop_set_uint32(&dev->qdev, "hostaddr", filter.addr);
1569 qdev_prop_set_uint32(&dev->qdev, "vendorid", filter.vendor_id);
1570 qdev_prop_set_uint32(&dev->qdev, "productid", filter.product_id);
1571 qdev_init_nofail(&dev->qdev);
1572 return dev;
1573
1574 fail:
1575 qdev_free(&dev->qdev);
1576 return NULL;
1577 }
1578
1579 int usb_host_device_close(const char *devname)
1580 {
1581 #if 0
1582 char product_name[PRODUCT_NAME_SZ];
1583 int bus_num, addr;
1584 USBHostDevice *s;
1585
1586 if (strstr(devname, "auto:")) {
1587 return usb_host_auto_del(devname);
1588 }
1589 if (usb_host_find_device(&bus_num, &addr, product_name,
1590 sizeof(product_name), devname) < 0) {
1591 return -1;
1592 }
1593 s = hostdev_find(bus_num, addr);
1594 if (s) {
1595 usb_device_delete_addr(s->bus_num, s->dev.addr);
1596 return 0;
1597 }
1598 #endif
1599
1600 return -1;
1601 }
1602
1603 /*
1604 * Read sys file-system device file
1605 *
1606 * @line address of buffer to put file contents in
1607 * @line_size size of line
1608 * @device_file path to device file (printf format string)
1609 * @device_name device being opened (inserted into device_file)
1610 *
1611 * @return 0 failed, 1 succeeded ('line' contains data)
1612 */
1613 static int usb_host_read_file(char *line, size_t line_size,
1614 const char *device_file, const char *device_name)
1615 {
1616 FILE *f;
1617 int ret = 0;
1618 char filename[PATH_MAX];
1619
1620 snprintf(filename, PATH_MAX, "/sys/bus/usb/devices/%s/%s", device_name,
1621 device_file);
1622 f = fopen(filename, "r");
1623 if (f) {
1624 ret = fgets(line, line_size, f) != NULL;
1625 fclose(f);
1626 }
1627
1628 return ret;
1629 }
1630
1631 /*
1632 * Use /sys/bus/usb/devices/ directory to determine host's USB
1633 * devices.
1634 *
1635 * This code is based on Robert Schiele's original patches posted to
1636 * the Novell bug-tracker https://bugzilla.novell.com/show_bug.cgi?id=241950
1637 */
1638 static int usb_host_scan(void *opaque, USBScanFunc *func)
1639 {
1640 DIR *dir = NULL;
1641 char line[1024];
1642 int bus_num, addr, speed, class_id, product_id, vendor_id;
1643 int ret = 0;
1644 char port[MAX_PORTLEN];
1645 char product_name[512];
1646 struct dirent *de;
1647
1648 dir = opendir("/sys/bus/usb/devices");
1649 if (!dir) {
1650 perror("husb: opendir /sys/bus/usb/devices");
1651 fprintf(stderr, "husb: please make sure sysfs is mounted at /sys\n");
1652 goto the_end;
1653 }
1654
1655 while ((de = readdir(dir))) {
1656 if (de->d_name[0] != '.' && !strchr(de->d_name, ':')) {
1657 if (sscanf(de->d_name, "%d-%7[0-9.]", &bus_num, port) < 2) {
1658 continue;
1659 }
1660
1661 if (!usb_host_read_file(line, sizeof(line), "devnum", de->d_name)) {
1662 goto the_end;
1663 }
1664 if (sscanf(line, "%d", &addr) != 1) {
1665 goto the_end;
1666 }
1667 if (!usb_host_read_file(line, sizeof(line), "bDeviceClass",
1668 de->d_name)) {
1669 goto the_end;
1670 }
1671 if (sscanf(line, "%x", &class_id) != 1) {
1672 goto the_end;
1673 }
1674
1675 if (!usb_host_read_file(line, sizeof(line), "idVendor",
1676 de->d_name)) {
1677 goto the_end;
1678 }
1679 if (sscanf(line, "%x", &vendor_id) != 1) {
1680 goto the_end;
1681 }
1682 if (!usb_host_read_file(line, sizeof(line), "idProduct",
1683 de->d_name)) {
1684 goto the_end;
1685 }
1686 if (sscanf(line, "%x", &product_id) != 1) {
1687 goto the_end;
1688 }
1689 if (!usb_host_read_file(line, sizeof(line), "product",
1690 de->d_name)) {
1691 *product_name = 0;
1692 } else {
1693 if (strlen(line) > 0) {
1694 line[strlen(line) - 1] = '\0';
1695 }
1696 pstrcpy(product_name, sizeof(product_name), line);
1697 }
1698
1699 if (!usb_host_read_file(line, sizeof(line), "speed", de->d_name)) {
1700 goto the_end;
1701 }
1702 if (!strcmp(line, "5000\n")) {
1703 speed = USB_SPEED_SUPER;
1704 } else if (!strcmp(line, "480\n")) {
1705 speed = USB_SPEED_HIGH;
1706 } else if (!strcmp(line, "1.5\n")) {
1707 speed = USB_SPEED_LOW;
1708 } else {
1709 speed = USB_SPEED_FULL;
1710 }
1711
1712 ret = func(opaque, bus_num, addr, port, class_id, vendor_id,
1713 product_id, product_name, speed);
1714 if (ret) {
1715 goto the_end;
1716 }
1717 }
1718 }
1719 the_end:
1720 if (dir) {
1721 closedir(dir);
1722 }
1723 return ret;
1724 }
1725
1726 static QEMUTimer *usb_auto_timer;
1727
1728 static int usb_host_auto_scan(void *opaque, int bus_num,
1729 int addr, const char *port,
1730 int class_id, int vendor_id, int product_id,
1731 const char *product_name, int speed)
1732 {
1733 struct USBAutoFilter *f;
1734 struct USBHostDevice *s;
1735
1736 /* Ignore hubs */
1737 if (class_id == 9)
1738 return 0;
1739
1740 QTAILQ_FOREACH(s, &hostdevs, next) {
1741 f = &s->match;
1742
1743 if (f->bus_num > 0 && f->bus_num != bus_num) {
1744 continue;
1745 }
1746 if (f->addr > 0 && f->addr != addr) {
1747 continue;
1748 }
1749 if (f->port != NULL && (port == NULL || strcmp(f->port, port) != 0)) {
1750 continue;
1751 }
1752
1753 if (f->vendor_id > 0 && f->vendor_id != vendor_id) {
1754 continue;
1755 }
1756
1757 if (f->product_id > 0 && f->product_id != product_id) {
1758 continue;
1759 }
1760 /* We got a match */
1761 s->seen++;
1762 if (s->errcount >= 3) {
1763 return 0;
1764 }
1765
1766 /* Already attached ? */
1767 if (s->fd != -1) {
1768 return 0;
1769 }
1770 DPRINTF("husb: auto open: bus_num %d addr %d\n", bus_num, addr);
1771
1772 if (usb_host_open(s, bus_num, addr, port, product_name, speed) < 0) {
1773 s->errcount++;
1774 }
1775 break;
1776 }
1777
1778 return 0;
1779 }
1780
1781 static void usb_host_auto_check(void *unused)
1782 {
1783 struct USBHostDevice *s;
1784 int unconnected = 0;
1785
1786 if (runstate_is_running()) {
1787 usb_host_scan(NULL, usb_host_auto_scan);
1788
1789 QTAILQ_FOREACH(s, &hostdevs, next) {
1790 if (s->fd == -1) {
1791 unconnected++;
1792 }
1793 if (s->seen == 0) {
1794 s->errcount = 0;
1795 }
1796 s->seen = 0;
1797 }
1798
1799 if (unconnected == 0) {
1800 /* nothing to watch */
1801 if (usb_auto_timer) {
1802 qemu_del_timer(usb_auto_timer);
1803 trace_usb_host_auto_scan_disabled();
1804 }
1805 return;
1806 }
1807 }
1808
1809 if (!usb_auto_timer) {
1810 usb_auto_timer = qemu_new_timer_ms(rt_clock, usb_host_auto_check, NULL);
1811 if (!usb_auto_timer) {
1812 return;
1813 }
1814 trace_usb_host_auto_scan_enabled();
1815 }
1816 qemu_mod_timer(usb_auto_timer, qemu_get_clock_ms(rt_clock) + 2000);
1817 }
1818
1819 /*
1820 * Autoconnect filter
1821 * Format:
1822 * auto:bus:dev[:vid:pid]
1823 * auto:bus.dev[:vid:pid]
1824 *
1825 * bus - bus number (dec, * means any)
1826 * dev - device number (dec, * means any)
1827 * vid - vendor id (hex, * means any)
1828 * pid - product id (hex, * means any)
1829 *
1830 * See 'lsusb' output.
1831 */
1832 static int parse_filter(const char *spec, struct USBAutoFilter *f)
1833 {
1834 enum { BUS, DEV, VID, PID, DONE };
1835 const char *p = spec;
1836 int i;
1837
1838 f->bus_num = 0;
1839 f->addr = 0;
1840 f->vendor_id = 0;
1841 f->product_id = 0;
1842
1843 for (i = BUS; i < DONE; i++) {
1844 p = strpbrk(p, ":.");
1845 if (!p) {
1846 break;
1847 }
1848 p++;
1849
1850 if (*p == '*') {
1851 continue;
1852 }
1853 switch(i) {
1854 case BUS: f->bus_num = strtol(p, NULL, 10); break;
1855 case DEV: f->addr = strtol(p, NULL, 10); break;
1856 case VID: f->vendor_id = strtol(p, NULL, 16); break;
1857 case PID: f->product_id = strtol(p, NULL, 16); break;
1858 }
1859 }
1860
1861 if (i < DEV) {
1862 fprintf(stderr, "husb: invalid auto filter spec %s\n", spec);
1863 return -1;
1864 }
1865
1866 return 0;
1867 }
1868
1869 /**********************/
1870 /* USB host device info */
1871
1872 struct usb_class_info {
1873 int class;
1874 const char *class_name;
1875 };
1876
1877 static const struct usb_class_info usb_class_info[] = {
1878 { USB_CLASS_AUDIO, "Audio"},
1879 { USB_CLASS_COMM, "Communication"},
1880 { USB_CLASS_HID, "HID"},
1881 { USB_CLASS_HUB, "Hub" },
1882 { USB_CLASS_PHYSICAL, "Physical" },
1883 { USB_CLASS_PRINTER, "Printer" },
1884 { USB_CLASS_MASS_STORAGE, "Storage" },
1885 { USB_CLASS_CDC_DATA, "Data" },
1886 { USB_CLASS_APP_SPEC, "Application Specific" },
1887 { USB_CLASS_VENDOR_SPEC, "Vendor Specific" },
1888 { USB_CLASS_STILL_IMAGE, "Still Image" },
1889 { USB_CLASS_CSCID, "Smart Card" },
1890 { USB_CLASS_CONTENT_SEC, "Content Security" },
1891 { -1, NULL }
1892 };
1893
1894 static const char *usb_class_str(uint8_t class)
1895 {
1896 const struct usb_class_info *p;
1897 for(p = usb_class_info; p->class != -1; p++) {
1898 if (p->class == class) {
1899 break;
1900 }
1901 }
1902 return p->class_name;
1903 }
1904
1905 static void usb_info_device(Monitor *mon, int bus_num,
1906 int addr, const char *port,
1907 int class_id, int vendor_id, int product_id,
1908 const char *product_name,
1909 int speed)
1910 {
1911 const char *class_str, *speed_str;
1912
1913 switch(speed) {
1914 case USB_SPEED_LOW:
1915 speed_str = "1.5";
1916 break;
1917 case USB_SPEED_FULL:
1918 speed_str = "12";
1919 break;
1920 case USB_SPEED_HIGH:
1921 speed_str = "480";
1922 break;
1923 case USB_SPEED_SUPER:
1924 speed_str = "5000";
1925 break;
1926 default:
1927 speed_str = "?";
1928 break;
1929 }
1930
1931 monitor_printf(mon, " Bus %d, Addr %d, Port %s, Speed %s Mb/s\n",
1932 bus_num, addr, port, speed_str);
1933 class_str = usb_class_str(class_id);
1934 if (class_str) {
1935 monitor_printf(mon, " %s:", class_str);
1936 } else {
1937 monitor_printf(mon, " Class %02x:", class_id);
1938 }
1939 monitor_printf(mon, " USB device %04x:%04x", vendor_id, product_id);
1940 if (product_name[0] != '\0') {
1941 monitor_printf(mon, ", %s", product_name);
1942 }
1943 monitor_printf(mon, "\n");
1944 }
1945
1946 static int usb_host_info_device(void *opaque, int bus_num, int addr,
1947 const char *path, int class_id,
1948 int vendor_id, int product_id,
1949 const char *product_name,
1950 int speed)
1951 {
1952 Monitor *mon = opaque;
1953
1954 usb_info_device(mon, bus_num, addr, path, class_id, vendor_id, product_id,
1955 product_name, speed);
1956 return 0;
1957 }
1958
1959 static void dec2str(int val, char *str, size_t size)
1960 {
1961 if (val == 0) {
1962 snprintf(str, size, "*");
1963 } else {
1964 snprintf(str, size, "%d", val);
1965 }
1966 }
1967
1968 static void hex2str(int val, char *str, size_t size)
1969 {
1970 if (val == 0) {
1971 snprintf(str, size, "*");
1972 } else {
1973 snprintf(str, size, "%04x", val);
1974 }
1975 }
1976
1977 void usb_host_info(Monitor *mon)
1978 {
1979 struct USBAutoFilter *f;
1980 struct USBHostDevice *s;
1981
1982 usb_host_scan(mon, usb_host_info_device);
1983
1984 if (QTAILQ_EMPTY(&hostdevs)) {
1985 return;
1986 }
1987
1988 monitor_printf(mon, " Auto filters:\n");
1989 QTAILQ_FOREACH(s, &hostdevs, next) {
1990 char bus[10], addr[10], vid[10], pid[10];
1991 f = &s->match;
1992 dec2str(f->bus_num, bus, sizeof(bus));
1993 dec2str(f->addr, addr, sizeof(addr));
1994 hex2str(f->vendor_id, vid, sizeof(vid));
1995 hex2str(f->product_id, pid, sizeof(pid));
1996 monitor_printf(mon, " Bus %s, Addr %s, Port %s, ID %s:%s\n",
1997 bus, addr, f->port ? f->port : "*", vid, pid);
1998 }
1999 }