Statistics
| Branch: | Revision:

root / usb-linux.c @ ba02430f

History | View | Annotate | Download (52.1 kB)

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_PORTLEN 16
71

    
72
/* endpoint association data */
73
#define ISO_FRAME_DESC_PER_URB 32
74

    
75
/* devio.c limits single requests to 16k */
76
#define MAX_USBFS_BUFFER_SIZE 16384
77

    
78
typedef struct AsyncURB AsyncURB;
79

    
80
struct endp_data {
81
    uint8_t halted;
82
    uint8_t iso_started;
83
    AsyncURB *iso_urb;
84
    int iso_urb_idx;
85
    int iso_buffer_used;
86
    int inflight;
87
};
88

    
89
struct USBAutoFilter {
90
    uint32_t bus_num;
91
    uint32_t addr;
92
    char     *port;
93
    uint32_t vendor_id;
94
    uint32_t product_id;
95
};
96

    
97
typedef struct USBHostDevice {
98
    USBDevice dev;
99
    int       fd;
100
    int       hub_fd;
101
    int       hub_port;
102

    
103
    uint8_t   descr[8192];
104
    int       descr_len;
105
    int       closing;
106
    uint32_t  iso_urb_count;
107
    Notifier  exit;
108

    
109
    struct endp_data ep_in[USB_MAX_ENDPOINTS];
110
    struct endp_data ep_out[USB_MAX_ENDPOINTS];
111
    QLIST_HEAD(, AsyncURB) aurbs;
112

    
113
    /* Host side address */
114
    int bus_num;
115
    int addr;
116
    char port[MAX_PORTLEN];
117
    struct USBAutoFilter match;
118
    int seen, errcount;
119

    
120
    QTAILQ_ENTRY(USBHostDevice) next;
121
} USBHostDevice;
122

    
123
static QTAILQ_HEAD(, USBHostDevice) hostdevs = QTAILQ_HEAD_INITIALIZER(hostdevs);
124

    
125
static int usb_host_close(USBHostDevice *dev);
126
static int parse_filter(const char *spec, struct USBAutoFilter *f);
127
static void usb_host_auto_check(void *unused);
128
static int usb_host_read_file(char *line, size_t line_size,
129
                            const char *device_file, const char *device_name);
130
static int usb_linux_update_endp_table(USBHostDevice *s);
131

    
132
static int usb_host_usbfs_type(USBHostDevice *s, USBPacket *p)
133
{
134
    static const int usbfs[] = {
135
        [USB_ENDPOINT_XFER_CONTROL] = USBDEVFS_URB_TYPE_CONTROL,
136
        [USB_ENDPOINT_XFER_ISOC]    = USBDEVFS_URB_TYPE_ISO,
137
        [USB_ENDPOINT_XFER_BULK]    = USBDEVFS_URB_TYPE_BULK,
138
        [USB_ENDPOINT_XFER_INT]     = USBDEVFS_URB_TYPE_INTERRUPT,
139
    };
140
    uint8_t type = usb_ep_get_type(&s->dev, p->pid, p->devep);
141
    assert(type < ARRAY_SIZE(usbfs));
142
    return usbfs[type];
143
}
144

    
145
static int usb_host_do_reset(USBHostDevice *dev)
146
{
147
    struct timeval s, e;
148
    uint32_t usecs;
149
    int ret;
150

    
151
    gettimeofday(&s, NULL);
152
    ret = ioctl(dev->fd, USBDEVFS_RESET);
153
    gettimeofday(&e, NULL);
154
    usecs = (e.tv_sec  - s.tv_sec) * 1000000;
155
    usecs += e.tv_usec - s.tv_usec;
156
    if (usecs > 1000000) {
157
        /* more than a second, something is fishy, broken usb device? */
158
        fprintf(stderr, "husb: device %d:%d reset took %d.%06d seconds\n",
159
                dev->bus_num, dev->addr, usecs / 1000000, usecs % 1000000);
160
    }
161
    return ret;
162
}
163

    
164
static struct endp_data *get_endp(USBHostDevice *s, int pid, int ep)
165
{
166
    struct endp_data *eps = pid == USB_TOKEN_IN ? s->ep_in : s->ep_out;
167
    assert(pid == USB_TOKEN_IN || pid == USB_TOKEN_OUT);
168
    assert(ep > 0 && ep <= USB_MAX_ENDPOINTS);
169
    return eps + ep - 1;
170
}
171

    
172
static int is_isoc(USBHostDevice *s, int pid, int ep)
173
{
174
    return usb_ep_get_type(&s->dev, pid, ep) == USB_ENDPOINT_XFER_ISOC;
175
}
176

    
177
static int is_valid(USBHostDevice *s, int pid, int ep)
178
{
179
    return usb_ep_get_type(&s->dev, pid, ep) != USB_ENDPOINT_XFER_INVALID;
180
}
181

    
182
static int is_halted(USBHostDevice *s, int pid, int ep)
183
{
184
    return get_endp(s, pid, ep)->halted;
185
}
186

    
187
static void clear_halt(USBHostDevice *s, int pid, int ep)
188
{
189
    trace_usb_host_ep_clear_halt(s->bus_num, s->addr, ep);
190
    get_endp(s, pid, ep)->halted = 0;
191
}
192

    
193
static void set_halt(USBHostDevice *s, int pid, int ep)
194
{
195
    if (ep != 0) {
196
        trace_usb_host_ep_set_halt(s->bus_num, s->addr, ep);
197
        get_endp(s, pid, ep)->halted = 1;
198
    }
199
}
200

    
201
static int is_iso_started(USBHostDevice *s, int pid, int ep)
202
{
203
    return get_endp(s, pid, ep)->iso_started;
204
}
205

    
206
static void clear_iso_started(USBHostDevice *s, int pid, int ep)
207
{
208
    trace_usb_host_ep_stop_iso(s->bus_num, s->addr, ep);
209
    get_endp(s, pid, ep)->iso_started = 0;
210
}
211

    
212
static void set_iso_started(USBHostDevice *s, int pid, int ep)
213
{
214
    struct endp_data *e = get_endp(s, pid, ep);
215

    
216
    trace_usb_host_ep_start_iso(s->bus_num, s->addr, ep);
217
    if (!e->iso_started) {
218
        e->iso_started = 1;
219
        e->inflight = 0;
220
    }
221
}
222

    
223
static int change_iso_inflight(USBHostDevice *s, int pid, int ep, int value)
224
{
225
    struct endp_data *e = get_endp(s, pid, ep);
226

    
227
    e->inflight += value;
228
    return e->inflight;
229
}
230

    
231
static void set_iso_urb(USBHostDevice *s, int pid, int ep, AsyncURB *iso_urb)
232
{
233
    get_endp(s, pid, ep)->iso_urb = iso_urb;
234
}
235

    
236
static AsyncURB *get_iso_urb(USBHostDevice *s, int pid, int ep)
237
{
238
    return get_endp(s, pid, ep)->iso_urb;
239
}
240

    
241
static void set_iso_urb_idx(USBHostDevice *s, int pid, int ep, int i)
242
{
243
    get_endp(s, pid, ep)->iso_urb_idx = i;
244
}
245

    
246
static int get_iso_urb_idx(USBHostDevice *s, int pid, int ep)
247
{
248
    return get_endp(s, pid, ep)->iso_urb_idx;
249
}
250

    
251
static void set_iso_buffer_used(USBHostDevice *s, int pid, int ep, int i)
252
{
253
    get_endp(s, pid, ep)->iso_buffer_used = i;
254
}
255

    
256
static int get_iso_buffer_used(USBHostDevice *s, int pid, int ep)
257
{
258
    return get_endp(s, pid, ep)->iso_buffer_used;
259
}
260

    
261
/*
262
 * Async URB state.
263
 * We always allocate iso packet descriptors even for bulk transfers
264
 * to simplify allocation and casts.
265
 */
266
struct AsyncURB
267
{
268
    struct usbdevfs_urb urb;
269
    struct usbdevfs_iso_packet_desc isocpd[ISO_FRAME_DESC_PER_URB];
270
    USBHostDevice *hdev;
271
    QLIST_ENTRY(AsyncURB) next;
272

    
273
    /* For regular async urbs */
274
    USBPacket     *packet;
275
    int more; /* large transfer, more urbs follow */
276

    
277
    /* For buffered iso handling */
278
    int iso_frame_idx; /* -1 means in flight */
279
};
280

    
281
static AsyncURB *async_alloc(USBHostDevice *s)
282
{
283
    AsyncURB *aurb = g_malloc0(sizeof(AsyncURB));
284
    aurb->hdev = s;
285
    QLIST_INSERT_HEAD(&s->aurbs, aurb, next);
286
    return aurb;
287
}
288

    
289
static void async_free(AsyncURB *aurb)
290
{
291
    QLIST_REMOVE(aurb, next);
292
    g_free(aurb);
293
}
294

    
295
static void do_disconnect(USBHostDevice *s)
296
{
297
    usb_host_close(s);
298
    usb_host_auto_check(NULL);
299
}
300

    
301
static void async_complete(void *opaque)
302
{
303
    USBHostDevice *s = opaque;
304
    AsyncURB *aurb;
305
    int urbs = 0;
306

    
307
    while (1) {
308
        USBPacket *p;
309

    
310
        int r = ioctl(s->fd, USBDEVFS_REAPURBNDELAY, &aurb);
311
        if (r < 0) {
312
            if (errno == EAGAIN) {
313
                if (urbs > 2) {
314
                    fprintf(stderr, "husb: %d iso urbs finished at once\n", urbs);
315
                }
316
                return;
317
            }
318
            if (errno == ENODEV) {
319
                if (!s->closing) {
320
                    trace_usb_host_disconnect(s->bus_num, s->addr);
321
                    do_disconnect(s);
322
                }
323
                return;
324
            }
325

    
326
            perror("USBDEVFS_REAPURBNDELAY");
327
            return;
328
        }
329

    
330
        DPRINTF("husb: async completed. aurb %p status %d alen %d\n",
331
                aurb, aurb->urb.status, aurb->urb.actual_length);
332

    
333
        /* If this is a buffered iso urb mark it as complete and don't do
334
           anything else (it is handled further in usb_host_handle_iso_data) */
335
        if (aurb->iso_frame_idx == -1) {
336
            int inflight;
337
            int pid = (aurb->urb.endpoint & USB_DIR_IN) ?
338
                USB_TOKEN_IN : USB_TOKEN_OUT;
339
            int ep = aurb->urb.endpoint & 0xf;
340
            if (aurb->urb.status == -EPIPE) {
341
                set_halt(s, pid, ep);
342
            }
343
            aurb->iso_frame_idx = 0;
344
            urbs++;
345
            inflight = change_iso_inflight(s, pid, ep, -1);
346
            if (inflight == 0 && is_iso_started(s, pid, ep)) {
347
                fprintf(stderr, "husb: out of buffers for iso stream\n");
348
            }
349
            continue;
350
        }
351

    
352
        p = aurb->packet;
353
        trace_usb_host_urb_complete(s->bus_num, s->addr, aurb, aurb->urb.status,
354
                                    aurb->urb.actual_length, aurb->more);
355

    
356
        if (p) {
357
            switch (aurb->urb.status) {
358
            case 0:
359
                p->result += aurb->urb.actual_length;
360
                break;
361

    
362
            case -EPIPE:
363
                set_halt(s, p->pid, p->devep);
364
                p->result = USB_RET_STALL;
365
                break;
366

    
367
            default:
368
                p->result = USB_RET_NAK;
369
                break;
370
            }
371

    
372
            if (aurb->urb.type == USBDEVFS_URB_TYPE_CONTROL) {
373
                trace_usb_host_req_complete(s->bus_num, s->addr, p->result);
374
                usb_generic_async_ctrl_complete(&s->dev, p);
375
            } else if (!aurb->more) {
376
                trace_usb_host_req_complete(s->bus_num, s->addr, p->result);
377
                usb_packet_complete(&s->dev, p);
378
            }
379
        }
380

    
381
        async_free(aurb);
382
    }
383
}
384

    
385
static void usb_host_async_cancel(USBDevice *dev, USBPacket *p)
386
{
387
    USBHostDevice *s = DO_UPCAST(USBHostDevice, dev, dev);
388
    AsyncURB *aurb;
389

    
390
    QLIST_FOREACH(aurb, &s->aurbs, next) {
391
        if (p != aurb->packet) {
392
            continue;
393
        }
394

    
395
        DPRINTF("husb: async cancel: packet %p, aurb %p\n", p, aurb);
396

    
397
        /* Mark it as dead (see async_complete above) */
398
        aurb->packet = NULL;
399

    
400
        int r = ioctl(s->fd, USBDEVFS_DISCARDURB, aurb);
401
        if (r < 0) {
402
            DPRINTF("husb: async. discard urb failed errno %d\n", errno);
403
        }
404
    }
405
}
406

    
407
static int usb_host_open_device(int bus, int addr)
408
{
409
    const char *usbfs = NULL;
410
    char filename[32];
411
    struct stat st;
412
    int fd, rc;
413

    
414
    rc = stat("/dev/bus/usb", &st);
415
    if (rc == 0 && S_ISDIR(st.st_mode)) {
416
        /* udev-created device nodes available */
417
        usbfs = "/dev/bus/usb";
418
    } else {
419
        /* fallback: usbfs mounted below /proc */
420
        usbfs = "/proc/bus/usb";
421
    }
422

    
423
    snprintf(filename, sizeof(filename), "%s/%03d/%03d",
424
             usbfs, bus, addr);
425
    fd = open(filename, O_RDWR | O_NONBLOCK);
426
    if (fd < 0) {
427
        fprintf(stderr, "husb: open %s: %s\n", filename, strerror(errno));
428
    }
429
    return fd;
430
}
431

    
432
static int usb_host_claim_port(USBHostDevice *s)
433
{
434
#ifdef USBDEVFS_CLAIM_PORT
435
    char *h, hub_name[64], line[1024];
436
    int hub_addr, ret;
437

    
438
    snprintf(hub_name, sizeof(hub_name), "%d-%s",
439
             s->match.bus_num, s->match.port);
440

    
441
    /* try strip off last ".$portnr" to get hub */
442
    h = strrchr(hub_name, '.');
443
    if (h != NULL) {
444
        s->hub_port = atoi(h+1);
445
        *h = '\0';
446
    } else {
447
        /* no dot in there -> it is the root hub */
448
        snprintf(hub_name, sizeof(hub_name), "usb%d",
449
                 s->match.bus_num);
450
        s->hub_port = atoi(s->match.port);
451
    }
452

    
453
    if (!usb_host_read_file(line, sizeof(line), "devnum",
454
                            hub_name)) {
455
        return -1;
456
    }
457
    if (sscanf(line, "%d", &hub_addr) != 1) {
458
        return -1;
459
    }
460

    
461
    s->hub_fd = usb_host_open_device(s->match.bus_num, hub_addr);
462
    if (s->hub_fd < 0) {
463
        return -1;
464
    }
465

    
466
    ret = ioctl(s->hub_fd, USBDEVFS_CLAIM_PORT, &s->hub_port);
467
    if (ret < 0) {
468
        close(s->hub_fd);
469
        s->hub_fd = -1;
470
        return -1;
471
    }
472

    
473
    trace_usb_host_claim_port(s->match.bus_num, hub_addr, s->hub_port);
474
    return 0;
475
#else
476
    return -1;
477
#endif
478
}
479

    
480
static void usb_host_release_port(USBHostDevice *s)
481
{
482
    if (s->hub_fd == -1) {
483
        return;
484
    }
485
#ifdef USBDEVFS_RELEASE_PORT
486
    ioctl(s->hub_fd, USBDEVFS_RELEASE_PORT, &s->hub_port);
487
#endif
488
    close(s->hub_fd);
489
    s->hub_fd = -1;
490
}
491

    
492
static int usb_host_disconnect_ifaces(USBHostDevice *dev, int nb_interfaces)
493
{
494
    /* earlier Linux 2.4 do not support that */
495
#ifdef USBDEVFS_DISCONNECT
496
    struct usbdevfs_ioctl ctrl;
497
    int ret, interface;
498

    
499
    for (interface = 0; interface < nb_interfaces; interface++) {
500
        ctrl.ioctl_code = USBDEVFS_DISCONNECT;
501
        ctrl.ifno = interface;
502
        ctrl.data = 0;
503
        ret = ioctl(dev->fd, USBDEVFS_IOCTL, &ctrl);
504
        if (ret < 0 && errno != ENODATA) {
505
            perror("USBDEVFS_DISCONNECT");
506
            return -1;
507
        }
508
    }
509
#endif
510
    return 0;
511
}
512

    
513
static int usb_linux_get_num_interfaces(USBHostDevice *s)
514
{
515
    char device_name[64], line[1024];
516
    int num_interfaces = 0;
517

    
518
    sprintf(device_name, "%d-%s", s->bus_num, s->port);
519
    if (!usb_host_read_file(line, sizeof(line), "bNumInterfaces",
520
                            device_name)) {
521
        return -1;
522
    }
523
    if (sscanf(line, "%d", &num_interfaces) != 1) {
524
        return -1;
525
    }
526
    return num_interfaces;
527
}
528

    
529
static int usb_host_claim_interfaces(USBHostDevice *dev, int configuration)
530
{
531
    const char *op = NULL;
532
    int dev_descr_len, config_descr_len;
533
    int interface, nb_interfaces;
534
    int ret, i;
535

    
536
    for (i = 0; i < USB_MAX_INTERFACES; i++) {
537
        dev->dev.altsetting[i] = 0;
538
    }
539

    
540
    if (configuration == 0) { /* address state - ignore */
541
        dev->dev.ninterfaces   = 0;
542
        dev->dev.configuration = 0;
543
        return 1;
544
    }
545

    
546
    DPRINTF("husb: claiming interfaces. config %d\n", configuration);
547

    
548
    i = 0;
549
    dev_descr_len = dev->descr[0];
550
    if (dev_descr_len > dev->descr_len) {
551
        fprintf(stderr, "husb: update iface failed. descr too short\n");
552
        return 0;
553
    }
554

    
555
    i += dev_descr_len;
556
    while (i < dev->descr_len) {
557
        DPRINTF("husb: i is %d, descr_len is %d, dl %d, dt %d\n",
558
                i, dev->descr_len,
559
               dev->descr[i], dev->descr[i+1]);
560

    
561
        if (dev->descr[i+1] != USB_DT_CONFIG) {
562
            i += dev->descr[i];
563
            continue;
564
        }
565
        config_descr_len = dev->descr[i];
566

    
567
        DPRINTF("husb: config #%d need %d\n", dev->descr[i + 5], configuration);
568

    
569
        if (configuration == dev->descr[i + 5]) {
570
            configuration = dev->descr[i + 5];
571
            break;
572
        }
573

    
574
        i += config_descr_len;
575
    }
576

    
577
    if (i >= dev->descr_len) {
578
        fprintf(stderr,
579
                "husb: update iface failed. no matching configuration\n");
580
        return 0;
581
    }
582
    nb_interfaces = dev->descr[i + 4];
583

    
584
    if (usb_host_disconnect_ifaces(dev, nb_interfaces) < 0) {
585
        goto fail;
586
    }
587

    
588
    /* XXX: only grab if all interfaces are free */
589
    for (interface = 0; interface < nb_interfaces; interface++) {
590
        op = "USBDEVFS_CLAIMINTERFACE";
591
        ret = ioctl(dev->fd, USBDEVFS_CLAIMINTERFACE, &interface);
592
        if (ret < 0) {
593
            goto fail;
594
        }
595
    }
596

    
597
    trace_usb_host_claim_interfaces(dev->bus_num, dev->addr,
598
                                    nb_interfaces, configuration);
599

    
600
    dev->dev.ninterfaces   = nb_interfaces;
601
    dev->dev.configuration = configuration;
602
    return 1;
603

    
604
fail:
605
    if (errno == ENODEV) {
606
        do_disconnect(dev);
607
    }
608
    perror(op);
609
    return 0;
610
}
611

    
612
static int usb_host_release_interfaces(USBHostDevice *s)
613
{
614
    int ret, i;
615

    
616
    trace_usb_host_release_interfaces(s->bus_num, s->addr);
617

    
618
    for (i = 0; i < s->dev.ninterfaces; i++) {
619
        ret = ioctl(s->fd, USBDEVFS_RELEASEINTERFACE, &i);
620
        if (ret < 0) {
621
            perror("USBDEVFS_RELEASEINTERFACE");
622
            return 0;
623
        }
624
    }
625
    return 1;
626
}
627

    
628
static void usb_host_handle_reset(USBDevice *dev)
629
{
630
    USBHostDevice *s = DO_UPCAST(USBHostDevice, dev, dev);
631

    
632
    trace_usb_host_reset(s->bus_num, s->addr);
633

    
634
    usb_host_do_reset(s);;
635

    
636
    usb_host_claim_interfaces(s, 0);
637
    usb_linux_update_endp_table(s);
638
}
639

    
640
static void usb_host_handle_destroy(USBDevice *dev)
641
{
642
    USBHostDevice *s = (USBHostDevice *)dev;
643

    
644
    usb_host_release_port(s);
645
    usb_host_close(s);
646
    QTAILQ_REMOVE(&hostdevs, s, next);
647
    qemu_remove_exit_notifier(&s->exit);
648
}
649

    
650
/* iso data is special, we need to keep enough urbs in flight to make sure
651
   that the controller never runs out of them, otherwise the device will
652
   likely suffer a buffer underrun / overrun. */
653
static AsyncURB *usb_host_alloc_iso(USBHostDevice *s, int pid, uint8_t ep)
654
{
655
    AsyncURB *aurb;
656
    int i, j, len = usb_ep_get_max_packet_size(&s->dev, pid, ep);
657

    
658
    aurb = g_malloc0(s->iso_urb_count * sizeof(*aurb));
659
    for (i = 0; i < s->iso_urb_count; i++) {
660
        aurb[i].urb.endpoint      = ep;
661
        aurb[i].urb.buffer_length = ISO_FRAME_DESC_PER_URB * len;
662
        aurb[i].urb.buffer        = g_malloc(aurb[i].urb.buffer_length);
663
        aurb[i].urb.type          = USBDEVFS_URB_TYPE_ISO;
664
        aurb[i].urb.flags         = USBDEVFS_URB_ISO_ASAP;
665
        aurb[i].urb.number_of_packets = ISO_FRAME_DESC_PER_URB;
666
        for (j = 0 ; j < ISO_FRAME_DESC_PER_URB; j++)
667
            aurb[i].urb.iso_frame_desc[j].length = len;
668
        if (pid == USB_TOKEN_IN) {
669
            aurb[i].urb.endpoint |= 0x80;
670
            /* Mark as fully consumed (idle) */
671
            aurb[i].iso_frame_idx = ISO_FRAME_DESC_PER_URB;
672
        }
673
    }
674
    set_iso_urb(s, pid, ep, aurb);
675

    
676
    return aurb;
677
}
678

    
679
static void usb_host_stop_n_free_iso(USBHostDevice *s, int pid, uint8_t ep)
680
{
681
    AsyncURB *aurb;
682
    int i, ret, killed = 0, free = 1;
683

    
684
    aurb = get_iso_urb(s, pid, ep);
685
    if (!aurb) {
686
        return;
687
    }
688

    
689
    for (i = 0; i < s->iso_urb_count; i++) {
690
        /* in flight? */
691
        if (aurb[i].iso_frame_idx == -1) {
692
            ret = ioctl(s->fd, USBDEVFS_DISCARDURB, &aurb[i]);
693
            if (ret < 0) {
694
                perror("USBDEVFS_DISCARDURB");
695
                free = 0;
696
                continue;
697
            }
698
            killed++;
699
        }
700
    }
701

    
702
    /* Make sure any urbs we've killed are reaped before we free them */
703
    if (killed) {
704
        async_complete(s);
705
    }
706

    
707
    for (i = 0; i < s->iso_urb_count; i++) {
708
        g_free(aurb[i].urb.buffer);
709
    }
710

    
711
    if (free)
712
        g_free(aurb);
713
    else
714
        printf("husb: leaking iso urbs because of discard failure\n");
715
    set_iso_urb(s, pid, ep, NULL);
716
    set_iso_urb_idx(s, pid, ep, 0);
717
    clear_iso_started(s, pid, ep);
718
}
719

    
720
static int urb_status_to_usb_ret(int status)
721
{
722
    switch (status) {
723
    case -EPIPE:
724
        return USB_RET_STALL;
725
    default:
726
        return USB_RET_NAK;
727
    }
728
}
729

    
730
static int usb_host_handle_iso_data(USBHostDevice *s, USBPacket *p, int in)
731
{
732
    AsyncURB *aurb;
733
    int i, j, ret, max_packet_size, offset, len = 0;
734
    uint8_t *buf;
735

    
736
    max_packet_size = usb_ep_get_max_packet_size(&s->dev, p->pid, p->devep);
737
    if (max_packet_size == 0)
738
        return USB_RET_NAK;
739

    
740
    aurb = get_iso_urb(s, p->pid, p->devep);
741
    if (!aurb) {
742
        aurb = usb_host_alloc_iso(s, p->pid, p->devep);
743
    }
744

    
745
    i = get_iso_urb_idx(s, p->pid, p->devep);
746
    j = aurb[i].iso_frame_idx;
747
    if (j >= 0 && j < ISO_FRAME_DESC_PER_URB) {
748
        if (in) {
749
            /* Check urb status  */
750
            if (aurb[i].urb.status) {
751
                len = urb_status_to_usb_ret(aurb[i].urb.status);
752
                /* Move to the next urb */
753
                aurb[i].iso_frame_idx = ISO_FRAME_DESC_PER_URB - 1;
754
            /* Check frame status */
755
            } else if (aurb[i].urb.iso_frame_desc[j].status) {
756
                len = urb_status_to_usb_ret(
757
                                        aurb[i].urb.iso_frame_desc[j].status);
758
            /* Check the frame fits */
759
            } else if (aurb[i].urb.iso_frame_desc[j].actual_length
760
                       > p->iov.size) {
761
                printf("husb: received iso data is larger then packet\n");
762
                len = USB_RET_NAK;
763
            /* All good copy data over */
764
            } else {
765
                len = aurb[i].urb.iso_frame_desc[j].actual_length;
766
                buf  = aurb[i].urb.buffer +
767
                    j * aurb[i].urb.iso_frame_desc[0].length;
768
                usb_packet_copy(p, buf, len);
769
            }
770
        } else {
771
            len = p->iov.size;
772
            offset = (j == 0) ? 0 : get_iso_buffer_used(s, p->pid, p->devep);
773

    
774
            /* Check the frame fits */
775
            if (len > max_packet_size) {
776
                printf("husb: send iso data is larger then max packet size\n");
777
                return USB_RET_NAK;
778
            }
779

    
780
            /* All good copy data over */
781
            usb_packet_copy(p, aurb[i].urb.buffer + offset, len);
782
            aurb[i].urb.iso_frame_desc[j].length = len;
783
            offset += len;
784
            set_iso_buffer_used(s, p->pid, p->devep, offset);
785

    
786
            /* Start the stream once we have buffered enough data */
787
            if (!is_iso_started(s, p->pid, p->devep) && i == 1 && j == 8) {
788
                set_iso_started(s, p->pid, p->devep);
789
            }
790
        }
791
        aurb[i].iso_frame_idx++;
792
        if (aurb[i].iso_frame_idx == ISO_FRAME_DESC_PER_URB) {
793
            i = (i + 1) % s->iso_urb_count;
794
            set_iso_urb_idx(s, p->pid, p->devep, i);
795
        }
796
    } else {
797
        if (in) {
798
            set_iso_started(s, p->pid, p->devep);
799
        } else {
800
            DPRINTF("hubs: iso out error no free buffer, dropping packet\n");
801
        }
802
    }
803

    
804
    if (is_iso_started(s, p->pid, p->devep)) {
805
        /* (Re)-submit all fully consumed / filled urbs */
806
        for (i = 0; i < s->iso_urb_count; i++) {
807
            if (aurb[i].iso_frame_idx == ISO_FRAME_DESC_PER_URB) {
808
                ret = ioctl(s->fd, USBDEVFS_SUBMITURB, &aurb[i]);
809
                if (ret < 0) {
810
                    perror("USBDEVFS_SUBMITURB");
811
                    if (!in || len == 0) {
812
                        switch(errno) {
813
                        case ETIMEDOUT:
814
                            len = USB_RET_NAK;
815
                            break;
816
                        case EPIPE:
817
                        default:
818
                            len = USB_RET_STALL;
819
                        }
820
                    }
821
                    break;
822
                }
823
                aurb[i].iso_frame_idx = -1;
824
                change_iso_inflight(s, p->pid, p->devep, 1);
825
            }
826
        }
827
    }
828

    
829
    return len;
830
}
831

    
832
static int usb_host_handle_data(USBDevice *dev, USBPacket *p)
833
{
834
    USBHostDevice *s = DO_UPCAST(USBHostDevice, dev, dev);
835
    struct usbdevfs_urb *urb;
836
    AsyncURB *aurb;
837
    int ret, rem, prem, v;
838
    uint8_t *pbuf;
839
    uint8_t ep;
840

    
841
    trace_usb_host_req_data(s->bus_num, s->addr,
842
                            p->pid == USB_TOKEN_IN,
843
                            p->devep, p->iov.size);
844

    
845
    if (!is_valid(s, p->pid, p->devep)) {
846
        trace_usb_host_req_complete(s->bus_num, s->addr, USB_RET_NAK);
847
        return USB_RET_NAK;
848
    }
849

    
850
    if (p->pid == USB_TOKEN_IN) {
851
        ep = p->devep | 0x80;
852
    } else {
853
        ep = p->devep;
854
    }
855

    
856
    if (is_halted(s, p->pid, p->devep)) {
857
        unsigned int arg = ep;
858
        ret = ioctl(s->fd, USBDEVFS_CLEAR_HALT, &arg);
859
        if (ret < 0) {
860
            perror("USBDEVFS_CLEAR_HALT");
861
            trace_usb_host_req_complete(s->bus_num, s->addr, USB_RET_NAK);
862
            return USB_RET_NAK;
863
        }
864
        clear_halt(s, p->pid, p->devep);
865
    }
866

    
867
    if (is_isoc(s, p->pid, p->devep)) {
868
        return usb_host_handle_iso_data(s, p, p->pid == USB_TOKEN_IN);
869
    }
870

    
871
    v = 0;
872
    prem = p->iov.iov[v].iov_len;
873
    pbuf = p->iov.iov[v].iov_base;
874
    rem = p->iov.size;
875
    while (rem) {
876
        if (prem == 0) {
877
            v++;
878
            assert(v < p->iov.niov);
879
            prem = p->iov.iov[v].iov_len;
880
            pbuf = p->iov.iov[v].iov_base;
881
            assert(prem <= rem);
882
        }
883
        aurb = async_alloc(s);
884
        aurb->packet = p;
885

    
886
        urb = &aurb->urb;
887
        urb->endpoint      = ep;
888
        urb->type          = usb_host_usbfs_type(s, p);
889
        urb->usercontext   = s;
890
        urb->buffer        = pbuf;
891
        urb->buffer_length = prem;
892

    
893
        if (urb->buffer_length > MAX_USBFS_BUFFER_SIZE) {
894
            urb->buffer_length = MAX_USBFS_BUFFER_SIZE;
895
        }
896
        pbuf += urb->buffer_length;
897
        prem -= urb->buffer_length;
898
        rem  -= urb->buffer_length;
899
        if (rem) {
900
            aurb->more         = 1;
901
        }
902

    
903
        trace_usb_host_urb_submit(s->bus_num, s->addr, aurb,
904
                                  urb->buffer_length, aurb->more);
905
        ret = ioctl(s->fd, USBDEVFS_SUBMITURB, urb);
906

    
907
        DPRINTF("husb: data submit: ep 0x%x, len %u, more %d, packet %p, aurb %p\n",
908
                urb->endpoint, urb->buffer_length, aurb->more, p, aurb);
909

    
910
        if (ret < 0) {
911
            perror("USBDEVFS_SUBMITURB");
912
            async_free(aurb);
913

    
914
            switch(errno) {
915
            case ETIMEDOUT:
916
                trace_usb_host_req_complete(s->bus_num, s->addr, USB_RET_NAK);
917
                return USB_RET_NAK;
918
            case EPIPE:
919
            default:
920
                trace_usb_host_req_complete(s->bus_num, s->addr, USB_RET_STALL);
921
                return USB_RET_STALL;
922
            }
923
        }
924
    }
925

    
926
    return USB_RET_ASYNC;
927
}
928

    
929
static int ctrl_error(void)
930
{
931
    if (errno == ETIMEDOUT) {
932
        return USB_RET_NAK;
933
    } else {
934
        return USB_RET_STALL;
935
    }
936
}
937

    
938
static int usb_host_set_address(USBHostDevice *s, int addr)
939
{
940
    trace_usb_host_set_address(s->bus_num, s->addr, addr);
941
    s->dev.addr = addr;
942
    return 0;
943
}
944

    
945
static int usb_host_set_config(USBHostDevice *s, int config)
946
{
947
    int ret, first = 1;
948

    
949
    trace_usb_host_set_config(s->bus_num, s->addr, config);
950

    
951
    usb_host_release_interfaces(s);
952

    
953
again:
954
    ret = ioctl(s->fd, USBDEVFS_SETCONFIGURATION, &config);
955

    
956
    DPRINTF("husb: ctrl set config %d ret %d errno %d\n", config, ret, errno);
957

    
958
    if (ret < 0 && errno == EBUSY && first) {
959
        /* happens if usb device is in use by host drivers */
960
        int count = usb_linux_get_num_interfaces(s);
961
        if (count > 0) {
962
            DPRINTF("husb: busy -> disconnecting %d interfaces\n", count);
963
            usb_host_disconnect_ifaces(s, count);
964
            first = 0;
965
            goto again;
966
        }
967
    }
968

    
969
    if (ret < 0) {
970
        return ctrl_error();
971
    }
972
    usb_host_claim_interfaces(s, config);
973
    usb_linux_update_endp_table(s);
974
    return 0;
975
}
976

    
977
static int usb_host_set_interface(USBHostDevice *s, int iface, int alt)
978
{
979
    struct usbdevfs_setinterface si;
980
    int i, ret;
981

    
982
    trace_usb_host_set_interface(s->bus_num, s->addr, iface, alt);
983

    
984
    for (i = 1; i <= USB_MAX_ENDPOINTS; i++) {
985
        if (is_isoc(s, USB_TOKEN_IN, i)) {
986
            usb_host_stop_n_free_iso(s, USB_TOKEN_IN, i);
987
        }
988
        if (is_isoc(s, USB_TOKEN_OUT, i)) {
989
            usb_host_stop_n_free_iso(s, USB_TOKEN_OUT, i);
990
        }
991
    }
992

    
993
    if (iface >= USB_MAX_INTERFACES) {
994
        return USB_RET_STALL;
995
    }
996

    
997
    si.interface  = iface;
998
    si.altsetting = alt;
999
    ret = ioctl(s->fd, USBDEVFS_SETINTERFACE, &si);
1000

    
1001
    DPRINTF("husb: ctrl set iface %d altset %d ret %d errno %d\n",
1002
            iface, alt, ret, errno);
1003

    
1004
    if (ret < 0) {
1005
        return ctrl_error();
1006
    }
1007

    
1008
    s->dev.altsetting[iface] = alt;
1009
    usb_linux_update_endp_table(s);
1010
    return 0;
1011
}
1012

    
1013
static int usb_host_handle_control(USBDevice *dev, USBPacket *p,
1014
               int request, int value, int index, int length, uint8_t *data)
1015
{
1016
    USBHostDevice *s = DO_UPCAST(USBHostDevice, dev, dev);
1017
    struct usbdevfs_urb *urb;
1018
    AsyncURB *aurb;
1019
    int ret;
1020

    
1021
    /*
1022
     * Process certain standard device requests.
1023
     * These are infrequent and are processed synchronously.
1024
     */
1025

    
1026
    /* Note request is (bRequestType << 8) | bRequest */
1027
    trace_usb_host_req_control(s->bus_num, s->addr, request, value, index);
1028

    
1029
    switch (request) {
1030
    case DeviceOutRequest | USB_REQ_SET_ADDRESS:
1031
        return usb_host_set_address(s, value);
1032

    
1033
    case DeviceOutRequest | USB_REQ_SET_CONFIGURATION:
1034
        return usb_host_set_config(s, value & 0xff);
1035

    
1036
    case InterfaceOutRequest | USB_REQ_SET_INTERFACE:
1037
        return usb_host_set_interface(s, index, value);
1038
    }
1039

    
1040
    /* The rest are asynchronous */
1041

    
1042
    if (length > sizeof(dev->data_buf)) {
1043
        fprintf(stderr, "husb: ctrl buffer too small (%d > %zu)\n",
1044
                length, sizeof(dev->data_buf));
1045
        return USB_RET_STALL;
1046
    }
1047

    
1048
    aurb = async_alloc(s);
1049
    aurb->packet = p;
1050

    
1051
    /*
1052
     * Setup ctrl transfer.
1053
     *
1054
     * s->ctrl is laid out such that data buffer immediately follows
1055
     * 'req' struct which is exactly what usbdevfs expects.
1056
     */
1057
    urb = &aurb->urb;
1058

    
1059
    urb->type     = USBDEVFS_URB_TYPE_CONTROL;
1060
    urb->endpoint = p->devep;
1061

    
1062
    urb->buffer        = &dev->setup_buf;
1063
    urb->buffer_length = length + 8;
1064

    
1065
    urb->usercontext = s;
1066

    
1067
    trace_usb_host_urb_submit(s->bus_num, s->addr, aurb,
1068
                              urb->buffer_length, aurb->more);
1069
    ret = ioctl(s->fd, USBDEVFS_SUBMITURB, urb);
1070

    
1071
    DPRINTF("husb: submit ctrl. len %u aurb %p\n", urb->buffer_length, aurb);
1072

    
1073
    if (ret < 0) {
1074
        DPRINTF("husb: submit failed. errno %d\n", errno);
1075
        async_free(aurb);
1076

    
1077
        switch(errno) {
1078
        case ETIMEDOUT:
1079
            return USB_RET_NAK;
1080
        case EPIPE:
1081
        default:
1082
            return USB_RET_STALL;
1083
        }
1084
    }
1085

    
1086
    return USB_RET_ASYNC;
1087
}
1088

    
1089
static uint8_t usb_linux_get_alt_setting(USBHostDevice *s,
1090
    uint8_t configuration, uint8_t interface)
1091
{
1092
    char device_name[64], line[1024];
1093
    int alt_setting;
1094

    
1095
    sprintf(device_name, "%d-%s:%d.%d", s->bus_num, s->port,
1096
            (int)configuration, (int)interface);
1097

    
1098
    if (!usb_host_read_file(line, sizeof(line), "bAlternateSetting",
1099
                            device_name)) {
1100
        /* Assume alt 0 on error */
1101
        return 0;
1102
    }
1103
    if (sscanf(line, "%d", &alt_setting) != 1) {
1104
        /* Assume alt 0 on error */
1105
        return 0;
1106
    }
1107
    return alt_setting;
1108
}
1109

    
1110
/* returns 1 on problem encountered or 0 for success */
1111
static int usb_linux_update_endp_table(USBHostDevice *s)
1112
{
1113
    uint8_t *descriptors;
1114
    uint8_t devep, type, alt_interface;
1115
    uint16_t raw;
1116
    int interface, length, i, ep, pid;
1117
    struct endp_data *epd;
1118

    
1119
    usb_ep_init(&s->dev);
1120

    
1121
    if (s->dev.configuration == 0) {
1122
        /* not configured yet -- leave all endpoints disabled */
1123
        return 0;
1124
    }
1125

    
1126
    /* get the desired configuration, interface, and endpoint descriptors
1127
     * from device description */
1128
    descriptors = &s->descr[18];
1129
    length = s->descr_len - 18;
1130
    i = 0;
1131

    
1132
    while (i < length) {
1133
        if (descriptors[i + 1] != USB_DT_CONFIG) {
1134
            fprintf(stderr, "invalid descriptor data\n");
1135
            return 1;
1136
        } else if (descriptors[i + 5] != s->dev.configuration) {
1137
            DPRINTF("not requested configuration %d\n", s->dev.configuration);
1138
            i += (descriptors[i + 3] << 8) + descriptors[i + 2];
1139
            continue;
1140
        }
1141
        i += descriptors[i];
1142

    
1143
        if (descriptors[i + 1] != USB_DT_INTERFACE ||
1144
            (descriptors[i + 1] == USB_DT_INTERFACE &&
1145
             descriptors[i + 4] == 0)) {
1146
            i += descriptors[i];
1147
            continue;
1148
        }
1149

    
1150
        interface = descriptors[i + 2];
1151
        alt_interface = usb_linux_get_alt_setting(s, s->dev.configuration,
1152
                                                  interface);
1153

    
1154
        /* the current interface descriptor is the active interface
1155
         * and has endpoints */
1156
        if (descriptors[i + 3] != alt_interface) {
1157
            i += descriptors[i];
1158
            continue;
1159
        }
1160

    
1161
        /* advance to the endpoints */
1162
        while (i < length && descriptors[i +1] != USB_DT_ENDPOINT) {
1163
            i += descriptors[i];
1164
        }
1165

    
1166
        if (i >= length)
1167
            break;
1168

    
1169
        while (i < length) {
1170
            if (descriptors[i + 1] != USB_DT_ENDPOINT) {
1171
                break;
1172
            }
1173

    
1174
            devep = descriptors[i + 2];
1175
            pid = (devep & USB_DIR_IN) ? USB_TOKEN_IN : USB_TOKEN_OUT;
1176
            ep = devep & 0xf;
1177
            if (ep == 0) {
1178
                fprintf(stderr, "usb-linux: invalid ep descriptor, ep == 0\n");
1179
                return 1;
1180
            }
1181

    
1182
            type = descriptors[i + 3] & 0x3;
1183
            raw = descriptors[i + 4] + (descriptors[i + 5] << 8);
1184
            usb_ep_set_max_packet_size(&s->dev, pid, ep, raw);
1185
            assert(usb_ep_get_type(&s->dev, pid, ep) ==
1186
                   USB_ENDPOINT_XFER_INVALID);
1187
            usb_ep_set_type(&s->dev, pid, ep, type);
1188
            usb_ep_set_ifnum(&s->dev, pid, ep, interface);
1189

    
1190
            epd = get_endp(s, pid, ep);
1191
            epd->halted = 0;
1192

    
1193
            i += descriptors[i];
1194
        }
1195
    }
1196
#ifdef DEBUG
1197
    usb_ep_dump(&s->dev);
1198
#endif
1199
    return 0;
1200
}
1201

    
1202
/*
1203
 * Check if we can safely redirect a usb2 device to a usb1 virtual controller,
1204
 * this function assumes this is safe, if:
1205
 * 1) There are no isoc endpoints
1206
 * 2) There are no interrupt endpoints with a max_packet_size > 64
1207
 * Note bulk endpoints with a max_packet_size > 64 in theory also are not
1208
 * usb1 compatible, but in practice this seems to work fine.
1209
 */
1210
static int usb_linux_full_speed_compat(USBHostDevice *dev)
1211
{
1212
    int i, packet_size;
1213

    
1214
    /*
1215
     * usb_linux_update_endp_table only registers info about ep in the current
1216
     * interface altsettings, so we need to parse the descriptors again.
1217
     */
1218
    for (i = 0; (i + 5) < dev->descr_len; i += dev->descr[i]) {
1219
        if (dev->descr[i + 1] == USB_DT_ENDPOINT) {
1220
            switch (dev->descr[i + 3] & 0x3) {
1221
            case 0x00: /* CONTROL */
1222
                break;
1223
            case 0x01: /* ISO */
1224
                return 0;
1225
            case 0x02: /* BULK */
1226
                break;
1227
            case 0x03: /* INTERRUPT */
1228
                packet_size = dev->descr[i + 4] + (dev->descr[i + 5] << 8);
1229
                if (packet_size > 64)
1230
                    return 0;
1231
                break;
1232
            }
1233
        }
1234
    }
1235
    return 1;
1236
}
1237

    
1238
static int usb_host_open(USBHostDevice *dev, int bus_num,
1239
                         int addr, const char *port,
1240
                         const char *prod_name, int speed)
1241
{
1242
    int fd = -1, ret;
1243

    
1244
    trace_usb_host_open_started(bus_num, addr);
1245

    
1246
    if (dev->fd != -1) {
1247
        goto fail;
1248
    }
1249

    
1250
    fd = usb_host_open_device(bus_num, addr);
1251
    if (fd < 0) {
1252
        goto fail;
1253
    }
1254
    DPRINTF("husb: opened %s\n", buf);
1255

    
1256
    dev->bus_num = bus_num;
1257
    dev->addr = addr;
1258
    strcpy(dev->port, port);
1259
    dev->fd = fd;
1260

    
1261
    /* read the device description */
1262
    dev->descr_len = read(fd, dev->descr, sizeof(dev->descr));
1263
    if (dev->descr_len <= 0) {
1264
        perror("husb: reading device data failed");
1265
        goto fail;
1266
    }
1267

    
1268
#ifdef DEBUG
1269
    {
1270
        int x;
1271
        printf("=== begin dumping device descriptor data ===\n");
1272
        for (x = 0; x < dev->descr_len; x++) {
1273
            printf("%02x ", dev->descr[x]);
1274
        }
1275
        printf("\n=== end dumping device descriptor data ===\n");
1276
    }
1277
#endif
1278

    
1279

    
1280
    /* start unconfigured -- we'll wait for the guest to set a configuration */
1281
    if (!usb_host_claim_interfaces(dev, 0)) {
1282
        goto fail;
1283
    }
1284

    
1285
    ret = usb_linux_update_endp_table(dev);
1286
    if (ret) {
1287
        goto fail;
1288
    }
1289

    
1290
    if (speed == -1) {
1291
        struct usbdevfs_connectinfo ci;
1292

    
1293
        ret = ioctl(fd, USBDEVFS_CONNECTINFO, &ci);
1294
        if (ret < 0) {
1295
            perror("usb_host_device_open: USBDEVFS_CONNECTINFO");
1296
            goto fail;
1297
        }
1298

    
1299
        if (ci.slow) {
1300
            speed = USB_SPEED_LOW;
1301
        } else {
1302
            speed = USB_SPEED_HIGH;
1303
        }
1304
    }
1305
    dev->dev.speed = speed;
1306
    dev->dev.speedmask = (1 << speed);
1307
    if (dev->dev.speed == USB_SPEED_HIGH && usb_linux_full_speed_compat(dev)) {
1308
        dev->dev.speedmask |= USB_SPEED_MASK_FULL;
1309
    }
1310

    
1311
    trace_usb_host_open_success(bus_num, addr);
1312

    
1313
    if (!prod_name || prod_name[0] == '\0') {
1314
        snprintf(dev->dev.product_desc, sizeof(dev->dev.product_desc),
1315
                 "host:%d.%d", bus_num, addr);
1316
    } else {
1317
        pstrcpy(dev->dev.product_desc, sizeof(dev->dev.product_desc),
1318
                prod_name);
1319
    }
1320

    
1321
    ret = usb_device_attach(&dev->dev);
1322
    if (ret) {
1323
        goto fail;
1324
    }
1325

    
1326
    /* USB devio uses 'write' flag to check for async completions */
1327
    qemu_set_fd_handler(dev->fd, NULL, async_complete, dev);
1328

    
1329
    return 0;
1330

    
1331
fail:
1332
    trace_usb_host_open_failure(bus_num, addr);
1333
    if (dev->fd != -1) {
1334
        close(dev->fd);
1335
        dev->fd = -1;
1336
    }
1337
    return -1;
1338
}
1339

    
1340
static int usb_host_close(USBHostDevice *dev)
1341
{
1342
    int i;
1343

    
1344
    if (dev->fd == -1) {
1345
        return -1;
1346
    }
1347

    
1348
    trace_usb_host_close(dev->bus_num, dev->addr);
1349

    
1350
    qemu_set_fd_handler(dev->fd, NULL, NULL, NULL);
1351
    dev->closing = 1;
1352
    for (i = 1; i <= USB_MAX_ENDPOINTS; i++) {
1353
        if (is_isoc(dev, USB_TOKEN_IN, i)) {
1354
            usb_host_stop_n_free_iso(dev, USB_TOKEN_IN, i);
1355
        }
1356
        if (is_isoc(dev, USB_TOKEN_OUT, i)) {
1357
            usb_host_stop_n_free_iso(dev, USB_TOKEN_OUT, i);
1358
        }
1359
    }
1360
    async_complete(dev);
1361
    dev->closing = 0;
1362
    if (dev->dev.attached) {
1363
        usb_device_detach(&dev->dev);
1364
    }
1365
    usb_host_do_reset(dev);
1366
    close(dev->fd);
1367
    dev->fd = -1;
1368
    return 0;
1369
}
1370

    
1371
static void usb_host_exit_notifier(struct Notifier *n, void *data)
1372
{
1373
    USBHostDevice *s = container_of(n, USBHostDevice, exit);
1374

    
1375
    usb_host_release_port(s);
1376
    if (s->fd != -1) {
1377
        usb_host_do_reset(s);;
1378
    }
1379
}
1380

    
1381
static int usb_host_initfn(USBDevice *dev)
1382
{
1383
    USBHostDevice *s = DO_UPCAST(USBHostDevice, dev, dev);
1384

    
1385
    dev->auto_attach = 0;
1386
    s->fd = -1;
1387
    s->hub_fd = -1;
1388

    
1389
    QTAILQ_INSERT_TAIL(&hostdevs, s, next);
1390
    s->exit.notify = usb_host_exit_notifier;
1391
    qemu_add_exit_notifier(&s->exit);
1392
    usb_host_auto_check(NULL);
1393

    
1394
    if (s->match.bus_num != 0 && s->match.port != NULL) {
1395
        usb_host_claim_port(s);
1396
    }
1397
    return 0;
1398
}
1399

    
1400
static const VMStateDescription vmstate_usb_host = {
1401
    .name = "usb-host",
1402
    .unmigratable = 1,
1403
};
1404

    
1405
static void usb_host_class_initfn(ObjectClass *klass, void *data)
1406
{
1407
    USBDeviceClass *uc = USB_DEVICE_CLASS(klass);
1408

    
1409
    uc->init           = usb_host_initfn;
1410
    uc->product_desc   = "USB Host Device";
1411
    uc->handle_packet  = usb_generic_handle_packet;
1412
    uc->cancel_packet  = usb_host_async_cancel;
1413
    uc->handle_data    = usb_host_handle_data;
1414
    uc->handle_control = usb_host_handle_control;
1415
    uc->handle_reset   = usb_host_handle_reset;
1416
    uc->handle_destroy = usb_host_handle_destroy;
1417
}
1418

    
1419
static struct DeviceInfo usb_host_dev_info = {
1420
    .name      = "usb-host",
1421
    .size      = sizeof(USBHostDevice),
1422
    .vmsd      = &vmstate_usb_host,
1423
    .class_init= usb_host_class_initfn,
1424
    .props     = (Property[]) {
1425
        DEFINE_PROP_UINT32("hostbus",  USBHostDevice, match.bus_num,    0),
1426
        DEFINE_PROP_UINT32("hostaddr", USBHostDevice, match.addr,       0),
1427
        DEFINE_PROP_STRING("hostport", USBHostDevice, match.port),
1428
        DEFINE_PROP_HEX32("vendorid",  USBHostDevice, match.vendor_id,  0),
1429
        DEFINE_PROP_HEX32("productid", USBHostDevice, match.product_id, 0),
1430
        DEFINE_PROP_UINT32("isobufs",  USBHostDevice, iso_urb_count,    4),
1431
        DEFINE_PROP_END_OF_LIST(),
1432
    },
1433
};
1434

    
1435
static void usb_host_register_devices(void)
1436
{
1437
    usb_qdev_register(&usb_host_dev_info);
1438
    usb_legacy_register("usb-host", "host", usb_host_device_open);
1439
}
1440
device_init(usb_host_register_devices)
1441

    
1442
USBDevice *usb_host_device_open(const char *devname)
1443
{
1444
    struct USBAutoFilter filter;
1445
    USBDevice *dev;
1446
    char *p;
1447

    
1448
    dev = usb_create(NULL /* FIXME */, "usb-host");
1449

    
1450
    if (strstr(devname, "auto:")) {
1451
        if (parse_filter(devname, &filter) < 0) {
1452
            goto fail;
1453
        }
1454
    } else {
1455
        if ((p = strchr(devname, '.'))) {
1456
            filter.bus_num    = strtoul(devname, NULL, 0);
1457
            filter.addr       = strtoul(p + 1, NULL, 0);
1458
            filter.vendor_id  = 0;
1459
            filter.product_id = 0;
1460
        } else if ((p = strchr(devname, ':'))) {
1461
            filter.bus_num    = 0;
1462
            filter.addr       = 0;
1463
            filter.vendor_id  = strtoul(devname, NULL, 16);
1464
            filter.product_id = strtoul(p + 1, NULL, 16);
1465
        } else {
1466
            goto fail;
1467
        }
1468
    }
1469

    
1470
    qdev_prop_set_uint32(&dev->qdev, "hostbus",   filter.bus_num);
1471
    qdev_prop_set_uint32(&dev->qdev, "hostaddr",  filter.addr);
1472
    qdev_prop_set_uint32(&dev->qdev, "vendorid",  filter.vendor_id);
1473
    qdev_prop_set_uint32(&dev->qdev, "productid", filter.product_id);
1474
    qdev_init_nofail(&dev->qdev);
1475
    return dev;
1476

    
1477
fail:
1478
    qdev_free(&dev->qdev);
1479
    return NULL;
1480
}
1481

    
1482
int usb_host_device_close(const char *devname)
1483
{
1484
#if 0
1485
    char product_name[PRODUCT_NAME_SZ];
1486
    int bus_num, addr;
1487
    USBHostDevice *s;
1488

1489
    if (strstr(devname, "auto:")) {
1490
        return usb_host_auto_del(devname);
1491
    }
1492
    if (usb_host_find_device(&bus_num, &addr, product_name,
1493
                                    sizeof(product_name), devname) < 0) {
1494
        return -1;
1495
    }
1496
    s = hostdev_find(bus_num, addr);
1497
    if (s) {
1498
        usb_device_delete_addr(s->bus_num, s->dev.addr);
1499
        return 0;
1500
    }
1501
#endif
1502

    
1503
    return -1;
1504
}
1505

    
1506
/*
1507
 * Read sys file-system device file
1508
 *
1509
 * @line address of buffer to put file contents in
1510
 * @line_size size of line
1511
 * @device_file path to device file (printf format string)
1512
 * @device_name device being opened (inserted into device_file)
1513
 *
1514
 * @return 0 failed, 1 succeeded ('line' contains data)
1515
 */
1516
static int usb_host_read_file(char *line, size_t line_size,
1517
                              const char *device_file, const char *device_name)
1518
{
1519
    FILE *f;
1520
    int ret = 0;
1521
    char filename[PATH_MAX];
1522

    
1523
    snprintf(filename, PATH_MAX, "/sys/bus/usb/devices/%s/%s", device_name,
1524
             device_file);
1525
    f = fopen(filename, "r");
1526
    if (f) {
1527
        ret = fgets(line, line_size, f) != NULL;
1528
        fclose(f);
1529
    }
1530

    
1531
    return ret;
1532
}
1533

    
1534
/*
1535
 * Use /sys/bus/usb/devices/ directory to determine host's USB
1536
 * devices.
1537
 *
1538
 * This code is based on Robert Schiele's original patches posted to
1539
 * the Novell bug-tracker https://bugzilla.novell.com/show_bug.cgi?id=241950
1540
 */
1541
static int usb_host_scan(void *opaque, USBScanFunc *func)
1542
{
1543
    DIR *dir = NULL;
1544
    char line[1024];
1545
    int bus_num, addr, speed, class_id, product_id, vendor_id;
1546
    int ret = 0;
1547
    char port[MAX_PORTLEN];
1548
    char product_name[512];
1549
    struct dirent *de;
1550

    
1551
    dir = opendir("/sys/bus/usb/devices");
1552
    if (!dir) {
1553
        perror("husb: opendir /sys/bus/usb/devices");
1554
        fprintf(stderr, "husb: please make sure sysfs is mounted at /sys\n");
1555
        goto the_end;
1556
    }
1557

    
1558
    while ((de = readdir(dir))) {
1559
        if (de->d_name[0] != '.' && !strchr(de->d_name, ':')) {
1560
            if (sscanf(de->d_name, "%d-%7[0-9.]", &bus_num, port) < 2) {
1561
                continue;
1562
            }
1563

    
1564
            if (!usb_host_read_file(line, sizeof(line), "devnum", de->d_name)) {
1565
                goto the_end;
1566
            }
1567
            if (sscanf(line, "%d", &addr) != 1) {
1568
                goto the_end;
1569
            }
1570
            if (!usb_host_read_file(line, sizeof(line), "bDeviceClass",
1571
                                    de->d_name)) {
1572
                goto the_end;
1573
            }
1574
            if (sscanf(line, "%x", &class_id) != 1) {
1575
                goto the_end;
1576
            }
1577

    
1578
            if (!usb_host_read_file(line, sizeof(line), "idVendor",
1579
                                    de->d_name)) {
1580
                goto the_end;
1581
            }
1582
            if (sscanf(line, "%x", &vendor_id) != 1) {
1583
                goto the_end;
1584
            }
1585
            if (!usb_host_read_file(line, sizeof(line), "idProduct",
1586
                                    de->d_name)) {
1587
                goto the_end;
1588
            }
1589
            if (sscanf(line, "%x", &product_id) != 1) {
1590
                goto the_end;
1591
            }
1592
            if (!usb_host_read_file(line, sizeof(line), "product",
1593
                                    de->d_name)) {
1594
                *product_name = 0;
1595
            } else {
1596
                if (strlen(line) > 0) {
1597
                    line[strlen(line) - 1] = '\0';
1598
                }
1599
                pstrcpy(product_name, sizeof(product_name), line);
1600
            }
1601

    
1602
            if (!usb_host_read_file(line, sizeof(line), "speed", de->d_name)) {
1603
                goto the_end;
1604
            }
1605
            if (!strcmp(line, "5000\n")) {
1606
                speed = USB_SPEED_SUPER;
1607
            } else if (!strcmp(line, "480\n")) {
1608
                speed = USB_SPEED_HIGH;
1609
            } else if (!strcmp(line, "1.5\n")) {
1610
                speed = USB_SPEED_LOW;
1611
            } else {
1612
                speed = USB_SPEED_FULL;
1613
            }
1614

    
1615
            ret = func(opaque, bus_num, addr, port, class_id, vendor_id,
1616
                       product_id, product_name, speed);
1617
            if (ret) {
1618
                goto the_end;
1619
            }
1620
        }
1621
    }
1622
 the_end:
1623
    if (dir) {
1624
        closedir(dir);
1625
    }
1626
    return ret;
1627
}
1628

    
1629
static QEMUTimer *usb_auto_timer;
1630

    
1631
static int usb_host_auto_scan(void *opaque, int bus_num,
1632
                              int addr, const char *port,
1633
                              int class_id, int vendor_id, int product_id,
1634
                              const char *product_name, int speed)
1635
{
1636
    struct USBAutoFilter *f;
1637
    struct USBHostDevice *s;
1638

    
1639
    /* Ignore hubs */
1640
    if (class_id == 9)
1641
        return 0;
1642

    
1643
    QTAILQ_FOREACH(s, &hostdevs, next) {
1644
        f = &s->match;
1645

    
1646
        if (f->bus_num > 0 && f->bus_num != bus_num) {
1647
            continue;
1648
        }
1649
        if (f->addr > 0 && f->addr != addr) {
1650
            continue;
1651
        }
1652
        if (f->port != NULL && (port == NULL || strcmp(f->port, port) != 0)) {
1653
            continue;
1654
        }
1655

    
1656
        if (f->vendor_id > 0 && f->vendor_id != vendor_id) {
1657
            continue;
1658
        }
1659

    
1660
        if (f->product_id > 0 && f->product_id != product_id) {
1661
            continue;
1662
        }
1663
        /* We got a match */
1664
        s->seen++;
1665
        if (s->errcount >= 3) {
1666
            return 0;
1667
        }
1668

    
1669
        /* Already attached ? */
1670
        if (s->fd != -1) {
1671
            return 0;
1672
        }
1673
        DPRINTF("husb: auto open: bus_num %d addr %d\n", bus_num, addr);
1674

    
1675
        if (usb_host_open(s, bus_num, addr, port, product_name, speed) < 0) {
1676
            s->errcount++;
1677
        }
1678
        break;
1679
    }
1680

    
1681
    return 0;
1682
}
1683

    
1684
static void usb_host_auto_check(void *unused)
1685
{
1686
    struct USBHostDevice *s;
1687
    int unconnected = 0;
1688

    
1689
    usb_host_scan(NULL, usb_host_auto_scan);
1690

    
1691
    QTAILQ_FOREACH(s, &hostdevs, next) {
1692
        if (s->fd == -1) {
1693
            unconnected++;
1694
        }
1695
        if (s->seen == 0) {
1696
            s->errcount = 0;
1697
        }
1698
        s->seen = 0;
1699
    }
1700

    
1701
    if (unconnected == 0) {
1702
        /* nothing to watch */
1703
        if (usb_auto_timer) {
1704
            qemu_del_timer(usb_auto_timer);
1705
            trace_usb_host_auto_scan_disabled();
1706
        }
1707
        return;
1708
    }
1709

    
1710
    if (!usb_auto_timer) {
1711
        usb_auto_timer = qemu_new_timer_ms(rt_clock, usb_host_auto_check, NULL);
1712
        if (!usb_auto_timer) {
1713
            return;
1714
        }
1715
        trace_usb_host_auto_scan_enabled();
1716
    }
1717
    qemu_mod_timer(usb_auto_timer, qemu_get_clock_ms(rt_clock) + 2000);
1718
}
1719

    
1720
/*
1721
 * Autoconnect filter
1722
 * Format:
1723
 *    auto:bus:dev[:vid:pid]
1724
 *    auto:bus.dev[:vid:pid]
1725
 *
1726
 *    bus  - bus number    (dec, * means any)
1727
 *    dev  - device number (dec, * means any)
1728
 *    vid  - vendor id     (hex, * means any)
1729
 *    pid  - product id    (hex, * means any)
1730
 *
1731
 *    See 'lsusb' output.
1732
 */
1733
static int parse_filter(const char *spec, struct USBAutoFilter *f)
1734
{
1735
    enum { BUS, DEV, VID, PID, DONE };
1736
    const char *p = spec;
1737
    int i;
1738

    
1739
    f->bus_num    = 0;
1740
    f->addr       = 0;
1741
    f->vendor_id  = 0;
1742
    f->product_id = 0;
1743

    
1744
    for (i = BUS; i < DONE; i++) {
1745
        p = strpbrk(p, ":.");
1746
        if (!p) {
1747
            break;
1748
        }
1749
        p++;
1750

    
1751
        if (*p == '*') {
1752
            continue;
1753
        }
1754
        switch(i) {
1755
        case BUS: f->bus_num = strtol(p, NULL, 10);    break;
1756
        case DEV: f->addr    = strtol(p, NULL, 10);    break;
1757
        case VID: f->vendor_id  = strtol(p, NULL, 16); break;
1758
        case PID: f->product_id = strtol(p, NULL, 16); break;
1759
        }
1760
    }
1761

    
1762
    if (i < DEV) {
1763
        fprintf(stderr, "husb: invalid auto filter spec %s\n", spec);
1764
        return -1;
1765
    }
1766

    
1767
    return 0;
1768
}
1769

    
1770
/**********************/
1771
/* USB host device info */
1772

    
1773
struct usb_class_info {
1774
    int class;
1775
    const char *class_name;
1776
};
1777

    
1778
static const struct usb_class_info usb_class_info[] = {
1779
    { USB_CLASS_AUDIO, "Audio"},
1780
    { USB_CLASS_COMM, "Communication"},
1781
    { USB_CLASS_HID, "HID"},
1782
    { USB_CLASS_HUB, "Hub" },
1783
    { USB_CLASS_PHYSICAL, "Physical" },
1784
    { USB_CLASS_PRINTER, "Printer" },
1785
    { USB_CLASS_MASS_STORAGE, "Storage" },
1786
    { USB_CLASS_CDC_DATA, "Data" },
1787
    { USB_CLASS_APP_SPEC, "Application Specific" },
1788
    { USB_CLASS_VENDOR_SPEC, "Vendor Specific" },
1789
    { USB_CLASS_STILL_IMAGE, "Still Image" },
1790
    { USB_CLASS_CSCID, "Smart Card" },
1791
    { USB_CLASS_CONTENT_SEC, "Content Security" },
1792
    { -1, NULL }
1793
};
1794

    
1795
static const char *usb_class_str(uint8_t class)
1796
{
1797
    const struct usb_class_info *p;
1798
    for(p = usb_class_info; p->class != -1; p++) {
1799
        if (p->class == class) {
1800
            break;
1801
        }
1802
    }
1803
    return p->class_name;
1804
}
1805

    
1806
static void usb_info_device(Monitor *mon, int bus_num,
1807
                            int addr, const char *port,
1808
                            int class_id, int vendor_id, int product_id,
1809
                            const char *product_name,
1810
                            int speed)
1811
{
1812
    const char *class_str, *speed_str;
1813

    
1814
    switch(speed) {
1815
    case USB_SPEED_LOW:
1816
        speed_str = "1.5";
1817
        break;
1818
    case USB_SPEED_FULL:
1819
        speed_str = "12";
1820
        break;
1821
    case USB_SPEED_HIGH:
1822
        speed_str = "480";
1823
        break;
1824
    case USB_SPEED_SUPER:
1825
        speed_str = "5000";
1826
        break;
1827
    default:
1828
        speed_str = "?";
1829
        break;
1830
    }
1831

    
1832
    monitor_printf(mon, "  Bus %d, Addr %d, Port %s, Speed %s Mb/s\n",
1833
                   bus_num, addr, port, speed_str);
1834
    class_str = usb_class_str(class_id);
1835
    if (class_str) {
1836
        monitor_printf(mon, "    %s:", class_str);
1837
    } else {
1838
        monitor_printf(mon, "    Class %02x:", class_id);
1839
    }
1840
    monitor_printf(mon, " USB device %04x:%04x", vendor_id, product_id);
1841
    if (product_name[0] != '\0') {
1842
        monitor_printf(mon, ", %s", product_name);
1843
    }
1844
    monitor_printf(mon, "\n");
1845
}
1846

    
1847
static int usb_host_info_device(void *opaque, int bus_num, int addr,
1848
                                const char *path, int class_id,
1849
                                int vendor_id, int product_id,
1850
                                const char *product_name,
1851
                                int speed)
1852
{
1853
    Monitor *mon = opaque;
1854

    
1855
    usb_info_device(mon, bus_num, addr, path, class_id, vendor_id, product_id,
1856
                    product_name, speed);
1857
    return 0;
1858
}
1859

    
1860
static void dec2str(int val, char *str, size_t size)
1861
{
1862
    if (val == 0) {
1863
        snprintf(str, size, "*");
1864
    } else {
1865
        snprintf(str, size, "%d", val);
1866
    }
1867
}
1868

    
1869
static void hex2str(int val, char *str, size_t size)
1870
{
1871
    if (val == 0) {
1872
        snprintf(str, size, "*");
1873
    } else {
1874
        snprintf(str, size, "%04x", val);
1875
    }
1876
}
1877

    
1878
void usb_host_info(Monitor *mon)
1879
{
1880
    struct USBAutoFilter *f;
1881
    struct USBHostDevice *s;
1882

    
1883
    usb_host_scan(mon, usb_host_info_device);
1884

    
1885
    if (QTAILQ_EMPTY(&hostdevs)) {
1886
        return;
1887
    }
1888

    
1889
    monitor_printf(mon, "  Auto filters:\n");
1890
    QTAILQ_FOREACH(s, &hostdevs, next) {
1891
        char bus[10], addr[10], vid[10], pid[10];
1892
        f = &s->match;
1893
        dec2str(f->bus_num, bus, sizeof(bus));
1894
        dec2str(f->addr, addr, sizeof(addr));
1895
        hex2str(f->vendor_id, vid, sizeof(vid));
1896
        hex2str(f->product_id, pid, sizeof(pid));
1897
        monitor_printf(mon, "    Bus %s, Addr %s, Port %s, ID %s:%s\n",
1898
                       bus, addr, f->port ? f->port : "*", vid, pid);
1899
    }
1900
}