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