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