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