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