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