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