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