Statistics
| Branch: | Revision:

root / usb-linux.c @ 227ebeb5

History | View | Annotate | Download (49.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

    
38
#include <dirent.h>
39
#include <sys/ioctl.h>
40
#include <signal.h>
41

    
42
#include <linux/usbdevice_fs.h>
43
#include <linux/version.h>
44
#include "hw/usb.h"
45

    
46
/* We redefine it to avoid version problems */
47
struct usb_ctrltransfer {
48
    uint8_t  bRequestType;
49
    uint8_t  bRequest;
50
    uint16_t wValue;
51
    uint16_t wIndex;
52
    uint16_t wLength;
53
    uint32_t timeout;
54
    void *data;
55
};
56

    
57
typedef int USBScanFunc(void *opaque, int bus_num, int addr, char *port,
58
                        int class_id, int vendor_id, int product_id,
59
                        const char *product_name, int speed);
60

    
61
//#define DEBUG
62

    
63
#ifdef DEBUG
64
#define DPRINTF printf
65
#else
66
#define DPRINTF(...)
67
#endif
68

    
69
#define USBDBG_DEVOPENED "husb: opened %s/devices\n"
70

    
71
#define USBPROCBUS_PATH "/proc/bus/usb"
72
#define PRODUCT_NAME_SZ 32
73
#define MAX_ENDPOINTS 15
74
#define MAX_PORTLEN 16
75
#define USBDEVBUS_PATH "/dev/bus/usb"
76
#define USBSYSBUS_PATH "/sys/bus/usb"
77

    
78
static char *usb_host_device_path;
79

    
80
#define USB_FS_NONE 0
81
#define USB_FS_PROC 1
82
#define USB_FS_DEV 2
83
#define USB_FS_SYS 3
84

    
85
static int usb_fs_type;
86

    
87
/* endpoint association data */
88
#define ISO_FRAME_DESC_PER_URB 32
89
#define ISO_URB_COUNT 3
90
#define INVALID_EP_TYPE 255
91

    
92
typedef struct AsyncURB AsyncURB;
93

    
94
struct endp_data {
95
    uint8_t type;
96
    uint8_t halted;
97
    uint8_t iso_started;
98
    AsyncURB *iso_urb;
99
    int iso_urb_idx;
100
    int iso_buffer_used;
101
    int max_packet_size;
102
};
103

    
104
struct USBAutoFilter {
105
    uint32_t bus_num;
106
    uint32_t addr;
107
    char     *port;
108
    uint32_t vendor_id;
109
    uint32_t product_id;
110
};
111

    
112
typedef struct USBHostDevice {
113
    USBDevice dev;
114
    int       fd;
115

    
116
    uint8_t   descr[1024];
117
    int       descr_len;
118
    int       configuration;
119
    int       ninterfaces;
120
    int       closing;
121
    Notifier  exit;
122

    
123
    struct endp_data endp_table[MAX_ENDPOINTS];
124
    QLIST_HEAD(, AsyncURB) aurbs;
125

    
126
    /* Host side address */
127
    int bus_num;
128
    int addr;
129
    char port[MAX_PORTLEN];
130
    struct USBAutoFilter match;
131

    
132
    QTAILQ_ENTRY(USBHostDevice) next;
133
} USBHostDevice;
134

    
135
static QTAILQ_HEAD(, USBHostDevice) hostdevs = QTAILQ_HEAD_INITIALIZER(hostdevs);
136

    
137
static int usb_host_close(USBHostDevice *dev);
138
static int parse_filter(const char *spec, struct USBAutoFilter *f);
139
static void usb_host_auto_check(void *unused);
140
static int usb_host_read_file(char *line, size_t line_size,
141
                            const char *device_file, const char *device_name);
142

    
143
static int is_isoc(USBHostDevice *s, int ep)
144
{
145
    return s->endp_table[ep - 1].type == USBDEVFS_URB_TYPE_ISO;
146
}
147

    
148
static int is_valid(USBHostDevice *s, int ep)
149
{
150
    return s->endp_table[ep - 1].type != INVALID_EP_TYPE;
151
}
152

    
153
static int is_halted(USBHostDevice *s, int ep)
154
{
155
    return s->endp_table[ep - 1].halted;
156
}
157

    
158
static void clear_halt(USBHostDevice *s, int ep)
159
{
160
    s->endp_table[ep - 1].halted = 0;
161
}
162

    
163
static void set_halt(USBHostDevice *s, int ep)
164
{
165
    s->endp_table[ep - 1].halted = 1;
166
}
167

    
168
static int is_iso_started(USBHostDevice *s, int ep)
169
{
170
    return s->endp_table[ep - 1].iso_started;
171
}
172

    
173
static void clear_iso_started(USBHostDevice *s, int ep)
174
{
175
    s->endp_table[ep - 1].iso_started = 0;
176
}
177

    
178
static void set_iso_started(USBHostDevice *s, int ep)
179
{
180
    s->endp_table[ep - 1].iso_started = 1;
181
}
182

    
183
static void set_iso_urb(USBHostDevice *s, int ep, AsyncURB *iso_urb)
184
{
185
    s->endp_table[ep - 1].iso_urb = iso_urb;
186
}
187

    
188
static AsyncURB *get_iso_urb(USBHostDevice *s, int ep)
189
{
190
    return s->endp_table[ep - 1].iso_urb;
191
}
192

    
193
static void set_iso_urb_idx(USBHostDevice *s, int ep, int i)
194
{
195
    s->endp_table[ep - 1].iso_urb_idx = i;
196
}
197

    
198
static int get_iso_urb_idx(USBHostDevice *s, int ep)
199
{
200
    return s->endp_table[ep - 1].iso_urb_idx;
201
}
202

    
203
static void set_iso_buffer_used(USBHostDevice *s, int ep, int i)
204
{
205
    s->endp_table[ep - 1].iso_buffer_used = i;
206
}
207

    
208
static int get_iso_buffer_used(USBHostDevice *s, int ep)
209
{
210
    return s->endp_table[ep - 1].iso_buffer_used;
211
}
212

    
213
static int get_max_packet_size(USBHostDevice *s, int ep)
214
{
215
    return s->endp_table[ep - 1].max_packet_size;
216
}
217

    
218
/*
219
 * Async URB state.
220
 * We always allocate iso packet descriptors even for bulk transfers
221
 * to simplify allocation and casts.
222
 */
223
struct AsyncURB
224
{
225
    struct usbdevfs_urb urb;
226
    struct usbdevfs_iso_packet_desc isocpd[ISO_FRAME_DESC_PER_URB];
227
    USBHostDevice *hdev;
228
    QLIST_ENTRY(AsyncURB) next;
229

    
230
    /* For regular async urbs */
231
    USBPacket     *packet;
232

    
233
    /* For buffered iso handling */
234
    int iso_frame_idx; /* -1 means in flight */
235
};
236

    
237
static AsyncURB *async_alloc(USBHostDevice *s)
238
{
239
    AsyncURB *aurb = qemu_mallocz(sizeof(AsyncURB));
240
    aurb->hdev = s;
241
    QLIST_INSERT_HEAD(&s->aurbs, aurb, next);
242
    return aurb;
243
}
244

    
245
static void async_free(AsyncURB *aurb)
246
{
247
    QLIST_REMOVE(aurb, next);
248
    qemu_free(aurb);
249
}
250

    
251
static void async_complete(void *opaque)
252
{
253
    USBHostDevice *s = opaque;
254
    AsyncURB *aurb;
255

    
256
    while (1) {
257
        USBPacket *p;
258

    
259
        int r = ioctl(s->fd, USBDEVFS_REAPURBNDELAY, &aurb);
260
        if (r < 0) {
261
            if (errno == EAGAIN) {
262
                return;
263
            }
264
            if (errno == ENODEV && !s->closing) {
265
                printf("husb: device %d.%d disconnected\n",
266
                       s->bus_num, s->addr);
267
                usb_host_close(s);
268
                usb_host_auto_check(NULL);
269
                return;
270
            }
271

    
272
            DPRINTF("husb: async. reap urb failed errno %d\n", errno);
273
            return;
274
        }
275

    
276
        DPRINTF("husb: async completed. aurb %p status %d alen %d\n",
277
                aurb, aurb->urb.status, aurb->urb.actual_length);
278

    
279
        /* If this is a buffered iso urb mark it as complete and don't do
280
           anything else (it is handled further in usb_host_handle_iso_data) */
281
        if (aurb->iso_frame_idx == -1) {
282
            if (aurb->urb.status == -EPIPE) {
283
                set_halt(s, aurb->urb.endpoint & 0xf);
284
            }
285
            aurb->iso_frame_idx = 0;
286
            continue;
287
        }
288

    
289
        p = aurb->packet;
290

    
291
        if (p) {
292
            switch (aurb->urb.status) {
293
            case 0:
294
                p->len = aurb->urb.actual_length;
295
                break;
296

    
297
            case -EPIPE:
298
                set_halt(s, p->devep);
299
                p->len = USB_RET_STALL;
300
                break;
301

    
302
            default:
303
                p->len = USB_RET_NAK;
304
                break;
305
            }
306

    
307
            if (aurb->urb.type == USBDEVFS_URB_TYPE_CONTROL) {
308
                usb_generic_async_ctrl_complete(&s->dev, p);
309
            } else {
310
                usb_packet_complete(&s->dev, p);
311
            }
312
        }
313

    
314
        async_free(aurb);
315
    }
316
}
317

    
318
static void async_cancel(USBPacket *p, void *opaque)
319
{
320
    USBHostDevice *s = opaque;
321
    AsyncURB *aurb;
322

    
323
    QLIST_FOREACH(aurb, &s->aurbs, next) {
324
        if (p != aurb->packet) {
325
            continue;
326
        }
327

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

    
330
        /* Mark it as dead (see async_complete above) */
331
        aurb->packet = NULL;
332

    
333
        int r = ioctl(s->fd, USBDEVFS_DISCARDURB, aurb);
334
        if (r < 0) {
335
            DPRINTF("husb: async. discard urb failed errno %d\n", errno);
336
        }
337
    }
338
}
339

    
340
static int usb_host_claim_interfaces(USBHostDevice *dev, int configuration)
341
{
342
    int dev_descr_len, config_descr_len;
343
    int interface, nb_interfaces;
344
    int ret, i;
345

    
346
    if (configuration == 0) /* address state - ignore */
347
        return 1;
348

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

    
351
    i = 0;
352
    dev_descr_len = dev->descr[0];
353
    if (dev_descr_len > dev->descr_len) {
354
        goto fail;
355
    }
356

    
357
    i += dev_descr_len;
358
    while (i < dev->descr_len) {
359
        DPRINTF("husb: i is %d, descr_len is %d, dl %d, dt %d\n",
360
                i, dev->descr_len,
361
               dev->descr[i], dev->descr[i+1]);
362

    
363
        if (dev->descr[i+1] != USB_DT_CONFIG) {
364
            i += dev->descr[i];
365
            continue;
366
        }
367
        config_descr_len = dev->descr[i];
368

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

    
371
        if (configuration < 0 || configuration == dev->descr[i + 5]) {
372
            configuration = dev->descr[i + 5];
373
            break;
374
        }
375

    
376
        i += config_descr_len;
377
    }
378

    
379
    if (i >= dev->descr_len) {
380
        fprintf(stderr,
381
                "husb: update iface failed. no matching configuration\n");
382
        goto fail;
383
    }
384
    nb_interfaces = dev->descr[i + 4];
385

    
386
#ifdef USBDEVFS_DISCONNECT
387
    /* earlier Linux 2.4 do not support that */
388
    {
389
        struct usbdevfs_ioctl ctrl;
390
        for (interface = 0; interface < nb_interfaces; interface++) {
391
            ctrl.ioctl_code = USBDEVFS_DISCONNECT;
392
            ctrl.ifno = interface;
393
            ctrl.data = 0;
394
            ret = ioctl(dev->fd, USBDEVFS_IOCTL, &ctrl);
395
            if (ret < 0 && errno != ENODATA) {
396
                perror("USBDEVFS_DISCONNECT");
397
                goto fail;
398
            }
399
        }
400
    }
401
#endif
402

    
403
    /* XXX: only grab if all interfaces are free */
404
    for (interface = 0; interface < nb_interfaces; interface++) {
405
        ret = ioctl(dev->fd, USBDEVFS_CLAIMINTERFACE, &interface);
406
        if (ret < 0) {
407
            if (errno == EBUSY) {
408
                printf("husb: update iface. device already grabbed\n");
409
            } else {
410
                perror("husb: failed to claim interface");
411
            }
412
        fail:
413
            return 0;
414
        }
415
    }
416

    
417
    printf("husb: %d interfaces claimed for configuration %d\n",
418
           nb_interfaces, configuration);
419

    
420
    dev->ninterfaces   = nb_interfaces;
421
    dev->configuration = configuration;
422
    return 1;
423
}
424

    
425
static int usb_host_release_interfaces(USBHostDevice *s)
426
{
427
    int ret, i;
428

    
429
    DPRINTF("husb: releasing interfaces\n");
430

    
431
    for (i = 0; i < s->ninterfaces; i++) {
432
        ret = ioctl(s->fd, USBDEVFS_RELEASEINTERFACE, &i);
433
        if (ret < 0) {
434
            perror("husb: failed to release interface");
435
            return 0;
436
        }
437
    }
438

    
439
    return 1;
440
}
441

    
442
static void usb_host_handle_reset(USBDevice *dev)
443
{
444
    USBHostDevice *s = DO_UPCAST(USBHostDevice, dev, dev);
445

    
446
    DPRINTF("husb: reset device %u.%u\n", s->bus_num, s->addr);
447

    
448
    ioctl(s->fd, USBDEVFS_RESET);
449

    
450
    usb_host_claim_interfaces(s, s->configuration);
451
}
452

    
453
static void usb_host_handle_destroy(USBDevice *dev)
454
{
455
    USBHostDevice *s = (USBHostDevice *)dev;
456

    
457
    usb_host_close(s);
458
    QTAILQ_REMOVE(&hostdevs, s, next);
459
    qemu_remove_exit_notifier(&s->exit);
460
}
461

    
462
static int usb_linux_update_endp_table(USBHostDevice *s);
463

    
464
/* iso data is special, we need to keep enough urbs in flight to make sure
465
   that the controller never runs out of them, otherwise the device will
466
   likely suffer a buffer underrun / overrun. */
467
static AsyncURB *usb_host_alloc_iso(USBHostDevice *s, uint8_t ep, int in)
468
{
469
    AsyncURB *aurb;
470
    int i, j, len = get_max_packet_size(s, ep);
471

    
472
    aurb = qemu_mallocz(ISO_URB_COUNT * sizeof(*aurb));
473
    for (i = 0; i < ISO_URB_COUNT; i++) {
474
        aurb[i].urb.endpoint      = ep;
475
        aurb[i].urb.buffer_length = ISO_FRAME_DESC_PER_URB * len;
476
        aurb[i].urb.buffer        = qemu_malloc(aurb[i].urb.buffer_length);
477
        aurb[i].urb.type          = USBDEVFS_URB_TYPE_ISO;
478
        aurb[i].urb.flags         = USBDEVFS_URB_ISO_ASAP;
479
        aurb[i].urb.number_of_packets = ISO_FRAME_DESC_PER_URB;
480
        for (j = 0 ; j < ISO_FRAME_DESC_PER_URB; j++)
481
            aurb[i].urb.iso_frame_desc[j].length = len;
482
        if (in) {
483
            aurb[i].urb.endpoint |= 0x80;
484
            /* Mark as fully consumed (idle) */
485
            aurb[i].iso_frame_idx = ISO_FRAME_DESC_PER_URB;
486
        }
487
    }
488
    set_iso_urb(s, ep, aurb);
489

    
490
    return aurb;
491
}
492

    
493
static void usb_host_stop_n_free_iso(USBHostDevice *s, uint8_t ep)
494
{
495
    AsyncURB *aurb;
496
    int i, ret, killed = 0, free = 1;
497

    
498
    aurb = get_iso_urb(s, ep);
499
    if (!aurb) {
500
        return;
501
    }
502

    
503
    for (i = 0; i < ISO_URB_COUNT; i++) {
504
        /* in flight? */
505
        if (aurb[i].iso_frame_idx == -1) {
506
            ret = ioctl(s->fd, USBDEVFS_DISCARDURB, &aurb[i]);
507
            if (ret < 0) {
508
                printf("husb: discard isoc in urb failed errno %d\n", errno);
509
                free = 0;
510
                continue;
511
            }
512
            killed++;
513
        }
514
    }
515

    
516
    /* Make sure any urbs we've killed are reaped before we free them */
517
    if (killed) {
518
        async_complete(s);
519
    }
520

    
521
    for (i = 0; i < ISO_URB_COUNT; i++) {
522
        qemu_free(aurb[i].urb.buffer);
523
    }
524

    
525
    if (free)
526
        qemu_free(aurb);
527
    else
528
        printf("husb: leaking iso urbs because of discard failure\n");
529
    set_iso_urb(s, ep, NULL);
530
    set_iso_urb_idx(s, ep, 0);
531
    clear_iso_started(s, ep);
532
}
533

    
534
static int urb_status_to_usb_ret(int status)
535
{
536
    switch (status) {
537
    case -EPIPE:
538
        return USB_RET_STALL;
539
    default:
540
        return USB_RET_NAK;
541
    }
542
}
543

    
544
static int usb_host_handle_iso_data(USBHostDevice *s, USBPacket *p, int in)
545
{
546
    AsyncURB *aurb;
547
    int i, j, ret, max_packet_size, offset, len = 0;
548

    
549
    max_packet_size = get_max_packet_size(s, p->devep);
550
    if (max_packet_size == 0)
551
        return USB_RET_NAK;
552

    
553
    aurb = get_iso_urb(s, p->devep);
554
    if (!aurb) {
555
        aurb = usb_host_alloc_iso(s, p->devep, in);
556
    }
557

    
558
    i = get_iso_urb_idx(s, p->devep);
559
    j = aurb[i].iso_frame_idx;
560
    if (j >= 0 && j < ISO_FRAME_DESC_PER_URB) {
561
        if (in) {
562
            /* Check urb status  */
563
            if (aurb[i].urb.status) {
564
                len = urb_status_to_usb_ret(aurb[i].urb.status);
565
                /* Move to the next urb */
566
                aurb[i].iso_frame_idx = ISO_FRAME_DESC_PER_URB - 1;
567
            /* Check frame status */
568
            } else if (aurb[i].urb.iso_frame_desc[j].status) {
569
                len = urb_status_to_usb_ret(
570
                                        aurb[i].urb.iso_frame_desc[j].status);
571
            /* Check the frame fits */
572
            } else if (aurb[i].urb.iso_frame_desc[j].actual_length > p->len) {
573
                printf("husb: received iso data is larger then packet\n");
574
                len = USB_RET_NAK;
575
            /* All good copy data over */
576
            } else {
577
                len = aurb[i].urb.iso_frame_desc[j].actual_length;
578
                memcpy(p->data,
579
                       aurb[i].urb.buffer +
580
                           j * aurb[i].urb.iso_frame_desc[0].length,
581
                       len);
582
            }
583
        } else {
584
            len = p->len;
585
            offset = (j == 0) ? 0 : get_iso_buffer_used(s, p->devep);
586

    
587
            /* Check the frame fits */
588
            if (len > max_packet_size) {
589
                printf("husb: send iso data is larger then max packet size\n");
590
                return USB_RET_NAK;
591
            }
592

    
593
            /* All good copy data over */
594
            memcpy(aurb[i].urb.buffer + offset, p->data, len);
595
            aurb[i].urb.iso_frame_desc[j].length = len;
596
            offset += len;
597
            set_iso_buffer_used(s, p->devep, offset);
598

    
599
            /* Start the stream once we have buffered enough data */
600
            if (!is_iso_started(s, p->devep) && i == 1 && j == 8) {
601
                set_iso_started(s, p->devep);
602
            }
603
        }
604
        aurb[i].iso_frame_idx++;
605
        if (aurb[i].iso_frame_idx == ISO_FRAME_DESC_PER_URB) {
606
            i = (i + 1) % ISO_URB_COUNT;
607
            set_iso_urb_idx(s, p->devep, i);
608
        }
609
    } else {
610
        if (in) {
611
            set_iso_started(s, p->devep);
612
        } else {
613
            DPRINTF("hubs: iso out error no free buffer, dropping packet\n");
614
        }
615
    }
616

    
617
    if (is_iso_started(s, p->devep)) {
618
        /* (Re)-submit all fully consumed / filled urbs */
619
        for (i = 0; i < ISO_URB_COUNT; i++) {
620
            if (aurb[i].iso_frame_idx == ISO_FRAME_DESC_PER_URB) {
621
                ret = ioctl(s->fd, USBDEVFS_SUBMITURB, &aurb[i]);
622
                if (ret < 0) {
623
                    printf("husb error submitting iso urb %d: %d\n", i, errno);
624
                    if (!in || len == 0) {
625
                        switch(errno) {
626
                        case ETIMEDOUT:
627
                            len = USB_RET_NAK;
628
                            break;
629
                        case EPIPE:
630
                        default:
631
                            len = USB_RET_STALL;
632
                        }
633
                    }
634
                    break;
635
                }
636
                aurb[i].iso_frame_idx = -1;
637
            }
638
        }
639
    }
640

    
641
    return len;
642
}
643

    
644
static int usb_host_handle_data(USBDevice *dev, USBPacket *p)
645
{
646
    USBHostDevice *s = DO_UPCAST(USBHostDevice, dev, dev);
647
    struct usbdevfs_urb *urb;
648
    AsyncURB *aurb;
649
    int ret;
650
    uint8_t ep;
651

    
652
    if (!is_valid(s, p->devep)) {
653
        return USB_RET_NAK;
654
    }
655

    
656
    if (p->pid == USB_TOKEN_IN) {
657
        ep = p->devep | 0x80;
658
    } else {
659
        ep = p->devep;
660
    }
661

    
662
    if (is_halted(s, p->devep)) {
663
        ret = ioctl(s->fd, USBDEVFS_CLEAR_HALT, &ep);
664
        if (ret < 0) {
665
            DPRINTF("husb: failed to clear halt. ep 0x%x errno %d\n",
666
                   ep, errno);
667
            return USB_RET_NAK;
668
        }
669
        clear_halt(s, p->devep);
670
    }
671

    
672
    if (is_isoc(s, p->devep)) {
673
        return usb_host_handle_iso_data(s, p, p->pid == USB_TOKEN_IN);
674
    }
675

    
676
    aurb = async_alloc(s);
677
    aurb->packet = p;
678

    
679
    urb = &aurb->urb;
680

    
681
    urb->endpoint      = ep;
682
    urb->buffer        = p->data;
683
    urb->buffer_length = p->len;
684
    urb->type          = USBDEVFS_URB_TYPE_BULK;
685
    urb->usercontext   = s;
686

    
687
    ret = ioctl(s->fd, USBDEVFS_SUBMITURB, urb);
688

    
689
    DPRINTF("husb: data submit. ep 0x%x len %u aurb %p\n",
690
            urb->endpoint, p->len, aurb);
691

    
692
    if (ret < 0) {
693
        DPRINTF("husb: submit failed. errno %d\n", errno);
694
        async_free(aurb);
695

    
696
        switch(errno) {
697
        case ETIMEDOUT:
698
            return USB_RET_NAK;
699
        case EPIPE:
700
        default:
701
            return USB_RET_STALL;
702
        }
703
    }
704

    
705
    usb_defer_packet(p, async_cancel, s);
706
    return USB_RET_ASYNC;
707
}
708

    
709
static int ctrl_error(void)
710
{
711
    if (errno == ETIMEDOUT) {
712
        return USB_RET_NAK;
713
    } else {
714
        return USB_RET_STALL;
715
    }
716
}
717

    
718
static int usb_host_set_address(USBHostDevice *s, int addr)
719
{
720
    DPRINTF("husb: ctrl set addr %u\n", addr);
721
    s->dev.addr = addr;
722
    return 0;
723
}
724

    
725
static int usb_host_set_config(USBHostDevice *s, int config)
726
{
727
    usb_host_release_interfaces(s);
728

    
729
    int ret = ioctl(s->fd, USBDEVFS_SETCONFIGURATION, &config);
730

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

    
733
    if (ret < 0) {
734
        return ctrl_error();
735
    }
736
    usb_host_claim_interfaces(s, config);
737
    return 0;
738
}
739

    
740
static int usb_host_set_interface(USBHostDevice *s, int iface, int alt)
741
{
742
    struct usbdevfs_setinterface si;
743
    int i, ret;
744

    
745
    for (i = 1; i <= MAX_ENDPOINTS; i++) {
746
        if (is_isoc(s, i)) {
747
            usb_host_stop_n_free_iso(s, i);
748
        }
749
    }
750

    
751
    si.interface  = iface;
752
    si.altsetting = alt;
753
    ret = ioctl(s->fd, USBDEVFS_SETINTERFACE, &si);
754

    
755
    DPRINTF("husb: ctrl set iface %d altset %d ret %d errno %d\n",
756
            iface, alt, ret, errno);
757

    
758
    if (ret < 0) {
759
        return ctrl_error();
760
    }
761
    usb_linux_update_endp_table(s);
762
    return 0;
763
}
764

    
765
static int usb_host_handle_control(USBDevice *dev, USBPacket *p,
766
               int request, int value, int index, int length, uint8_t *data)
767
{
768
    USBHostDevice *s = DO_UPCAST(USBHostDevice, dev, dev);
769
    struct usbdevfs_urb *urb;
770
    AsyncURB *aurb;
771
    int ret;
772

    
773
    /*
774
     * Process certain standard device requests.
775
     * These are infrequent and are processed synchronously.
776
     */
777

    
778
    /* Note request is (bRequestType << 8) | bRequest */
779
    DPRINTF("husb: ctrl type 0x%x req 0x%x val 0x%x index %u len %u\n",
780
            request >> 8, request & 0xff, value, index, length);
781

    
782
    switch (request) {
783
    case DeviceOutRequest | USB_REQ_SET_ADDRESS:
784
        return usb_host_set_address(s, value);
785

    
786
    case DeviceOutRequest | USB_REQ_SET_CONFIGURATION:
787
        return usb_host_set_config(s, value & 0xff);
788

    
789
    case InterfaceOutRequest | USB_REQ_SET_INTERFACE:
790
        return usb_host_set_interface(s, index, value);
791
    }
792

    
793
    /* The rest are asynchronous */
794

    
795
    if (length > sizeof(dev->data_buf)) {
796
        fprintf(stderr, "husb: ctrl buffer too small (%d > %zu)\n",
797
                length, sizeof(dev->data_buf));
798
        return USB_RET_STALL;
799
    }
800

    
801
    aurb = async_alloc(s);
802
    aurb->packet = p;
803

    
804
    /*
805
     * Setup ctrl transfer.
806
     *
807
     * s->ctrl is laid out such that data buffer immediately follows
808
     * 'req' struct which is exactly what usbdevfs expects.
809
     */
810
    urb = &aurb->urb;
811

    
812
    urb->type     = USBDEVFS_URB_TYPE_CONTROL;
813
    urb->endpoint = p->devep;
814

    
815
    urb->buffer        = &dev->setup_buf;
816
    urb->buffer_length = length + 8;
817

    
818
    urb->usercontext = s;
819

    
820
    ret = ioctl(s->fd, USBDEVFS_SUBMITURB, urb);
821

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

    
824
    if (ret < 0) {
825
        DPRINTF("husb: submit failed. errno %d\n", errno);
826
        async_free(aurb);
827

    
828
        switch(errno) {
829
        case ETIMEDOUT:
830
            return USB_RET_NAK;
831
        case EPIPE:
832
        default:
833
            return USB_RET_STALL;
834
        }
835
    }
836

    
837
    usb_defer_packet(p, async_cancel, s);
838
    return USB_RET_ASYNC;
839
}
840

    
841
static int usb_linux_get_configuration(USBHostDevice *s)
842
{
843
    uint8_t configuration;
844
    struct usb_ctrltransfer ct;
845
    int ret;
846

    
847
    if (usb_fs_type == USB_FS_SYS) {
848
        char device_name[32], line[1024];
849
        int configuration;
850

    
851
        sprintf(device_name, "%d-%s", s->bus_num, s->port);
852

    
853
        if (!usb_host_read_file(line, sizeof(line), "bConfigurationValue",
854
                                device_name)) {
855
            goto usbdevfs;
856
        }
857
        if (sscanf(line, "%d", &configuration) != 1) {
858
            goto usbdevfs;
859
        }
860
        return configuration;
861
    }
862

    
863
usbdevfs:
864
    ct.bRequestType = USB_DIR_IN;
865
    ct.bRequest = USB_REQ_GET_CONFIGURATION;
866
    ct.wValue = 0;
867
    ct.wIndex = 0;
868
    ct.wLength = 1;
869
    ct.data = &configuration;
870
    ct.timeout = 50;
871

    
872
    ret = ioctl(s->fd, USBDEVFS_CONTROL, &ct);
873
    if (ret < 0) {
874
        perror("usb_linux_get_configuration");
875
        return -1;
876
    }
877

    
878
    /* in address state */
879
    if (configuration == 0) {
880
        return -1;
881
    }
882

    
883
    return configuration;
884
}
885

    
886
static uint8_t usb_linux_get_alt_setting(USBHostDevice *s,
887
    uint8_t configuration, uint8_t interface)
888
{
889
    uint8_t alt_setting;
890
    struct usb_ctrltransfer ct;
891
    int ret;
892

    
893
    if (usb_fs_type == USB_FS_SYS) {
894
        char device_name[64], line[1024];
895
        int alt_setting;
896

    
897
        sprintf(device_name, "%d-%s:%d.%d", s->bus_num, s->port,
898
                (int)configuration, (int)interface);
899

    
900
        if (!usb_host_read_file(line, sizeof(line), "bAlternateSetting",
901
                                device_name)) {
902
            goto usbdevfs;
903
        }
904
        if (sscanf(line, "%d", &alt_setting) != 1) {
905
            goto usbdevfs;
906
        }
907
        return alt_setting;
908
    }
909

    
910
usbdevfs:
911
    ct.bRequestType = USB_DIR_IN | USB_RECIP_INTERFACE;
912
    ct.bRequest = USB_REQ_GET_INTERFACE;
913
    ct.wValue = 0;
914
    ct.wIndex = interface;
915
    ct.wLength = 1;
916
    ct.data = &alt_setting;
917
    ct.timeout = 50;
918
    ret = ioctl(s->fd, USBDEVFS_CONTROL, &ct);
919
    if (ret < 0) {
920
        /* Assume alt 0 on error */
921
        return 0;
922
    }
923

    
924
    return alt_setting;
925
}
926

    
927
/* returns 1 on problem encountered or 0 for success */
928
static int usb_linux_update_endp_table(USBHostDevice *s)
929
{
930
    uint8_t *descriptors;
931
    uint8_t devep, type, configuration, alt_interface;
932
    int interface, length, i;
933

    
934
    for (i = 0; i < MAX_ENDPOINTS; i++)
935
        s->endp_table[i].type = INVALID_EP_TYPE;
936

    
937
    i = usb_linux_get_configuration(s);
938
    if (i < 0)
939
        return 1;
940
    configuration = i;
941

    
942
    /* get the desired configuration, interface, and endpoint descriptors
943
     * from device description */
944
    descriptors = &s->descr[18];
945
    length = s->descr_len - 18;
946
    i = 0;
947

    
948
    if (descriptors[i + 1] != USB_DT_CONFIG ||
949
        descriptors[i + 5] != configuration) {
950
        DPRINTF("invalid descriptor data - configuration\n");
951
        return 1;
952
    }
953
    i += descriptors[i];
954

    
955
    while (i < length) {
956
        if (descriptors[i + 1] != USB_DT_INTERFACE ||
957
            (descriptors[i + 1] == USB_DT_INTERFACE &&
958
             descriptors[i + 4] == 0)) {
959
            i += descriptors[i];
960
            continue;
961
        }
962

    
963
        interface = descriptors[i + 2];
964
        alt_interface = usb_linux_get_alt_setting(s, configuration, interface);
965

    
966
        /* the current interface descriptor is the active interface
967
         * and has endpoints */
968
        if (descriptors[i + 3] != alt_interface) {
969
            i += descriptors[i];
970
            continue;
971
        }
972

    
973
        /* advance to the endpoints */
974
        while (i < length && descriptors[i +1] != USB_DT_ENDPOINT) {
975
            i += descriptors[i];
976
        }
977

    
978
        if (i >= length)
979
            break;
980

    
981
        while (i < length) {
982
            if (descriptors[i + 1] != USB_DT_ENDPOINT) {
983
                break;
984
            }
985

    
986
            devep = descriptors[i + 2];
987
            switch (descriptors[i + 3] & 0x3) {
988
            case 0x00:
989
                type = USBDEVFS_URB_TYPE_CONTROL;
990
                break;
991
            case 0x01:
992
                type = USBDEVFS_URB_TYPE_ISO;
993
                s->endp_table[(devep & 0xf) - 1].max_packet_size =
994
                    descriptors[i + 4] + (descriptors[i + 5] << 8);
995
                break;
996
            case 0x02:
997
                type = USBDEVFS_URB_TYPE_BULK;
998
                break;
999
            case 0x03:
1000
                type = USBDEVFS_URB_TYPE_INTERRUPT;
1001
                break;
1002
            default:
1003
                DPRINTF("usb_host: malformed endpoint type\n");
1004
                type = USBDEVFS_URB_TYPE_BULK;
1005
            }
1006
            s->endp_table[(devep & 0xf) - 1].type = type;
1007
            s->endp_table[(devep & 0xf) - 1].halted = 0;
1008

    
1009
            i += descriptors[i];
1010
        }
1011
    }
1012
    return 0;
1013
}
1014

    
1015
static int usb_host_open(USBHostDevice *dev, int bus_num,
1016
                         int addr, char *port, const char *prod_name)
1017
{
1018
    int fd = -1, ret;
1019
    struct usbdevfs_connectinfo ci;
1020
    char buf[1024];
1021

    
1022
    if (dev->fd != -1) {
1023
        goto fail;
1024
    }
1025
    printf("husb: open device %d.%d\n", bus_num, addr);
1026

    
1027
    if (!usb_host_device_path) {
1028
        perror("husb: USB Host Device Path not set");
1029
        goto fail;
1030
    }
1031
    snprintf(buf, sizeof(buf), "%s/%03d/%03d", usb_host_device_path,
1032
             bus_num, addr);
1033
    fd = open(buf, O_RDWR | O_NONBLOCK);
1034
    if (fd < 0) {
1035
        perror(buf);
1036
        goto fail;
1037
    }
1038
    DPRINTF("husb: opened %s\n", buf);
1039

    
1040
    dev->bus_num = bus_num;
1041
    dev->addr = addr;
1042
    strcpy(dev->port, port);
1043
    dev->fd = fd;
1044

    
1045
    /* read the device description */
1046
    dev->descr_len = read(fd, dev->descr, sizeof(dev->descr));
1047
    if (dev->descr_len <= 0) {
1048
        perror("husb: reading device data failed");
1049
        goto fail;
1050
    }
1051

    
1052
#ifdef DEBUG
1053
    {
1054
        int x;
1055
        printf("=== begin dumping device descriptor data ===\n");
1056
        for (x = 0; x < dev->descr_len; x++) {
1057
            printf("%02x ", dev->descr[x]);
1058
        }
1059
        printf("\n=== end dumping device descriptor data ===\n");
1060
    }
1061
#endif
1062

    
1063

    
1064
    /*
1065
     * Initial configuration is -1 which makes us claim first
1066
     * available config. We used to start with 1, which does not
1067
     * always work. I've seen devices where first config starts
1068
     * with 2.
1069
     */
1070
    if (!usb_host_claim_interfaces(dev, -1)) {
1071
        goto fail;
1072
    }
1073

    
1074
    ret = ioctl(fd, USBDEVFS_CONNECTINFO, &ci);
1075
    if (ret < 0) {
1076
        perror("usb_host_device_open: USBDEVFS_CONNECTINFO");
1077
        goto fail;
1078
    }
1079

    
1080
    printf("husb: grabbed usb device %d.%d\n", bus_num, addr);
1081

    
1082
    ret = usb_linux_update_endp_table(dev);
1083
    if (ret) {
1084
        goto fail;
1085
    }
1086

    
1087
    if (ci.slow) {
1088
        dev->dev.speed = USB_SPEED_LOW;
1089
    } else {
1090
        dev->dev.speed = USB_SPEED_HIGH;
1091
    }
1092

    
1093
    if (!prod_name || prod_name[0] == '\0') {
1094
        snprintf(dev->dev.product_desc, sizeof(dev->dev.product_desc),
1095
                 "host:%d.%d", bus_num, addr);
1096
    } else {
1097
        pstrcpy(dev->dev.product_desc, sizeof(dev->dev.product_desc),
1098
                prod_name);
1099
    }
1100

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

    
1104
    usb_device_attach(&dev->dev);
1105
    return 0;
1106

    
1107
fail:
1108
    dev->fd = -1;
1109
    if (fd != -1) {
1110
        close(fd);
1111
    }
1112
    return -1;
1113
}
1114

    
1115
static int usb_host_close(USBHostDevice *dev)
1116
{
1117
    int i;
1118

    
1119
    if (dev->fd == -1) {
1120
        return -1;
1121
    }
1122

    
1123
    qemu_set_fd_handler(dev->fd, NULL, NULL, NULL);
1124
    dev->closing = 1;
1125
    for (i = 1; i <= MAX_ENDPOINTS; i++) {
1126
        if (is_isoc(dev, i)) {
1127
            usb_host_stop_n_free_iso(dev, i);
1128
        }
1129
    }
1130
    async_complete(dev);
1131
    dev->closing = 0;
1132
    usb_device_detach(&dev->dev);
1133
    ioctl(dev->fd, USBDEVFS_RESET);
1134
    close(dev->fd);
1135
    dev->fd = -1;
1136
    return 0;
1137
}
1138

    
1139
static void usb_host_exit_notifier(struct Notifier* n)
1140
{
1141
    USBHostDevice *s = container_of(n, USBHostDevice, exit);
1142

    
1143
    if (s->fd != -1) {
1144
        ioctl(s->fd, USBDEVFS_RESET);
1145
    }
1146
}
1147

    
1148
static int usb_host_initfn(USBDevice *dev)
1149
{
1150
    USBHostDevice *s = DO_UPCAST(USBHostDevice, dev, dev);
1151

    
1152
    dev->auto_attach = 0;
1153
    s->fd = -1;
1154
    QTAILQ_INSERT_TAIL(&hostdevs, s, next);
1155
    s->exit.notify = usb_host_exit_notifier;
1156
    qemu_add_exit_notifier(&s->exit);
1157
    usb_host_auto_check(NULL);
1158
    return 0;
1159
}
1160

    
1161
static struct USBDeviceInfo usb_host_dev_info = {
1162
    .product_desc   = "USB Host Device",
1163
    .qdev.name      = "usb-host",
1164
    .qdev.size      = sizeof(USBHostDevice),
1165
    .init           = usb_host_initfn,
1166
    .handle_packet  = usb_generic_handle_packet,
1167
    .handle_data    = usb_host_handle_data,
1168
    .handle_control = usb_host_handle_control,
1169
    .handle_reset   = usb_host_handle_reset,
1170
    .handle_destroy = usb_host_handle_destroy,
1171
    .usbdevice_name = "host",
1172
    .usbdevice_init = usb_host_device_open,
1173
    .qdev.props     = (Property[]) {
1174
        DEFINE_PROP_UINT32("hostbus",  USBHostDevice, match.bus_num,    0),
1175
        DEFINE_PROP_UINT32("hostaddr", USBHostDevice, match.addr,       0),
1176
        DEFINE_PROP_STRING("hostport", USBHostDevice, match.port),
1177
        DEFINE_PROP_HEX32("vendorid",  USBHostDevice, match.vendor_id,  0),
1178
        DEFINE_PROP_HEX32("productid", USBHostDevice, match.product_id, 0),
1179
        DEFINE_PROP_END_OF_LIST(),
1180
    },
1181
};
1182

    
1183
static void usb_host_register_devices(void)
1184
{
1185
    usb_qdev_register(&usb_host_dev_info);
1186
}
1187
device_init(usb_host_register_devices)
1188

    
1189
USBDevice *usb_host_device_open(const char *devname)
1190
{
1191
    struct USBAutoFilter filter;
1192
    USBDevice *dev;
1193
    char *p;
1194

    
1195
    dev = usb_create(NULL /* FIXME */, "usb-host");
1196

    
1197
    if (strstr(devname, "auto:")) {
1198
        if (parse_filter(devname, &filter) < 0) {
1199
            goto fail;
1200
        }
1201
    } else {
1202
        if ((p = strchr(devname, '.'))) {
1203
            filter.bus_num    = strtoul(devname, NULL, 0);
1204
            filter.addr       = strtoul(p + 1, NULL, 0);
1205
            filter.vendor_id  = 0;
1206
            filter.product_id = 0;
1207
        } else if ((p = strchr(devname, ':'))) {
1208
            filter.bus_num    = 0;
1209
            filter.addr       = 0;
1210
            filter.vendor_id  = strtoul(devname, NULL, 16);
1211
            filter.product_id = strtoul(p + 1, NULL, 16);
1212
        } else {
1213
            goto fail;
1214
        }
1215
    }
1216

    
1217
    qdev_prop_set_uint32(&dev->qdev, "hostbus",   filter.bus_num);
1218
    qdev_prop_set_uint32(&dev->qdev, "hostaddr",  filter.addr);
1219
    qdev_prop_set_uint32(&dev->qdev, "vendorid",  filter.vendor_id);
1220
    qdev_prop_set_uint32(&dev->qdev, "productid", filter.product_id);
1221
    qdev_init_nofail(&dev->qdev);
1222
    return dev;
1223

    
1224
fail:
1225
    qdev_free(&dev->qdev);
1226
    return NULL;
1227
}
1228

    
1229
int usb_host_device_close(const char *devname)
1230
{
1231
#if 0
1232
    char product_name[PRODUCT_NAME_SZ];
1233
    int bus_num, addr;
1234
    USBHostDevice *s;
1235

1236
    if (strstr(devname, "auto:")) {
1237
        return usb_host_auto_del(devname);
1238
    }
1239
    if (usb_host_find_device(&bus_num, &addr, product_name,
1240
                                    sizeof(product_name), devname) < 0) {
1241
        return -1;
1242
    }
1243
    s = hostdev_find(bus_num, addr);
1244
    if (s) {
1245
        usb_device_delete_addr(s->bus_num, s->dev.addr);
1246
        return 0;
1247
    }
1248
#endif
1249

    
1250
    return -1;
1251
}
1252

    
1253
static int get_tag_value(char *buf, int buf_size,
1254
                         const char *str, const char *tag,
1255
                         const char *stopchars)
1256
{
1257
    const char *p;
1258
    char *q;
1259
    p = strstr(str, tag);
1260
    if (!p) {
1261
        return -1;
1262
    }
1263
    p += strlen(tag);
1264
    while (qemu_isspace(*p)) {
1265
        p++;
1266
    }
1267
    q = buf;
1268
    while (*p != '\0' && !strchr(stopchars, *p)) {
1269
        if ((q - buf) < (buf_size - 1)) {
1270
            *q++ = *p;
1271
        }
1272
        p++;
1273
    }
1274
    *q = '\0';
1275
    return q - buf;
1276
}
1277

    
1278
/*
1279
 * Use /proc/bus/usb/devices or /dev/bus/usb/devices file to determine
1280
 * host's USB devices. This is legacy support since many distributions
1281
 * are moving to /sys/bus/usb
1282
 */
1283
static int usb_host_scan_dev(void *opaque, USBScanFunc *func)
1284
{
1285
    FILE *f = NULL;
1286
    char line[1024];
1287
    char buf[1024];
1288
    int bus_num, addr, speed, device_count, class_id, product_id, vendor_id;
1289
    char product_name[512];
1290
    int ret = 0;
1291

    
1292
    if (!usb_host_device_path) {
1293
        perror("husb: USB Host Device Path not set");
1294
        goto the_end;
1295
    }
1296
    snprintf(line, sizeof(line), "%s/devices", usb_host_device_path);
1297
    f = fopen(line, "r");
1298
    if (!f) {
1299
        perror("husb: cannot open devices file");
1300
        goto the_end;
1301
    }
1302

    
1303
    device_count = 0;
1304
    bus_num = addr = speed = class_id = product_id = vendor_id = 0;
1305
    for(;;) {
1306
        if (fgets(line, sizeof(line), f) == NULL) {
1307
            break;
1308
        }
1309
        if (strlen(line) > 0) {
1310
            line[strlen(line) - 1] = '\0';
1311
        }
1312
        if (line[0] == 'T' && line[1] == ':') {
1313
            if (device_count && (vendor_id || product_id)) {
1314
                /* New device.  Add the previously discovered device.  */
1315
                ret = func(opaque, bus_num, addr, 0, class_id, vendor_id,
1316
                           product_id, product_name, speed);
1317
                if (ret) {
1318
                    goto the_end;
1319
                }
1320
            }
1321
            if (get_tag_value(buf, sizeof(buf), line, "Bus=", " ") < 0) {
1322
                goto fail;
1323
            }
1324
            bus_num = atoi(buf);
1325
            if (get_tag_value(buf, sizeof(buf), line, "Dev#=", " ") < 0) {
1326
                goto fail;
1327
            }
1328
            addr = atoi(buf);
1329
            if (get_tag_value(buf, sizeof(buf), line, "Spd=", " ") < 0) {
1330
                goto fail;
1331
            }
1332
            if (!strcmp(buf, "480")) {
1333
                speed = USB_SPEED_HIGH;
1334
            } else if (!strcmp(buf, "1.5")) {
1335
                speed = USB_SPEED_LOW;
1336
            } else {
1337
                speed = USB_SPEED_FULL;
1338
            }
1339
            product_name[0] = '\0';
1340
            class_id = 0xff;
1341
            device_count++;
1342
            product_id = 0;
1343
            vendor_id = 0;
1344
        } else if (line[0] == 'P' && line[1] == ':') {
1345
            if (get_tag_value(buf, sizeof(buf), line, "Vendor=", " ") < 0) {
1346
                goto fail;
1347
            }
1348
            vendor_id = strtoul(buf, NULL, 16);
1349
            if (get_tag_value(buf, sizeof(buf), line, "ProdID=", " ") < 0) {
1350
                goto fail;
1351
            }
1352
            product_id = strtoul(buf, NULL, 16);
1353
        } else if (line[0] == 'S' && line[1] == ':') {
1354
            if (get_tag_value(buf, sizeof(buf), line, "Product=", "") < 0) {
1355
                goto fail;
1356
            }
1357
            pstrcpy(product_name, sizeof(product_name), buf);
1358
        } else if (line[0] == 'D' && line[1] == ':') {
1359
            if (get_tag_value(buf, sizeof(buf), line, "Cls=", " (") < 0) {
1360
                goto fail;
1361
            }
1362
            class_id = strtoul(buf, NULL, 16);
1363
        }
1364
    fail: ;
1365
    }
1366
    if (device_count && (vendor_id || product_id)) {
1367
        /* Add the last device.  */
1368
        ret = func(opaque, bus_num, addr, 0, class_id, vendor_id,
1369
                   product_id, product_name, speed);
1370
    }
1371
 the_end:
1372
    if (f) {
1373
        fclose(f);
1374
    }
1375
    return ret;
1376
}
1377

    
1378
/*
1379
 * Read sys file-system device file
1380
 *
1381
 * @line address of buffer to put file contents in
1382
 * @line_size size of line
1383
 * @device_file path to device file (printf format string)
1384
 * @device_name device being opened (inserted into device_file)
1385
 *
1386
 * @return 0 failed, 1 succeeded ('line' contains data)
1387
 */
1388
static int usb_host_read_file(char *line, size_t line_size,
1389
                              const char *device_file, const char *device_name)
1390
{
1391
    FILE *f;
1392
    int ret = 0;
1393
    char filename[PATH_MAX];
1394

    
1395
    snprintf(filename, PATH_MAX, USBSYSBUS_PATH "/devices/%s/%s", device_name,
1396
             device_file);
1397
    f = fopen(filename, "r");
1398
    if (f) {
1399
        ret = fgets(line, line_size, f) != NULL;
1400
        fclose(f);
1401
    }
1402

    
1403
    return ret;
1404
}
1405

    
1406
/*
1407
 * Use /sys/bus/usb/devices/ directory to determine host's USB
1408
 * devices.
1409
 *
1410
 * This code is based on Robert Schiele's original patches posted to
1411
 * the Novell bug-tracker https://bugzilla.novell.com/show_bug.cgi?id=241950
1412
 */
1413
static int usb_host_scan_sys(void *opaque, USBScanFunc *func)
1414
{
1415
    DIR *dir = NULL;
1416
    char line[1024];
1417
    int bus_num, addr, speed, class_id, product_id, vendor_id;
1418
    int ret = 0;
1419
    char port[MAX_PORTLEN];
1420
    char product_name[512];
1421
    struct dirent *de;
1422

    
1423
    dir = opendir(USBSYSBUS_PATH "/devices");
1424
    if (!dir) {
1425
        perror("husb: cannot open devices directory");
1426
        goto the_end;
1427
    }
1428

    
1429
    while ((de = readdir(dir))) {
1430
        if (de->d_name[0] != '.' && !strchr(de->d_name, ':')) {
1431
            if (sscanf(de->d_name, "%d-%7[0-9.]", &bus_num, port) < 2) {
1432
                continue;
1433
            }
1434

    
1435
            if (!usb_host_read_file(line, sizeof(line), "devnum", de->d_name)) {
1436
                goto the_end;
1437
            }
1438
            if (sscanf(line, "%d", &addr) != 1) {
1439
                goto the_end;
1440
            }
1441
            if (!usb_host_read_file(line, sizeof(line), "bDeviceClass",
1442
                                    de->d_name)) {
1443
                goto the_end;
1444
            }
1445
            if (sscanf(line, "%x", &class_id) != 1) {
1446
                goto the_end;
1447
            }
1448

    
1449
            if (!usb_host_read_file(line, sizeof(line), "idVendor",
1450
                                    de->d_name)) {
1451
                goto the_end;
1452
            }
1453
            if (sscanf(line, "%x", &vendor_id) != 1) {
1454
                goto the_end;
1455
            }
1456
            if (!usb_host_read_file(line, sizeof(line), "idProduct",
1457
                                    de->d_name)) {
1458
                goto the_end;
1459
            }
1460
            if (sscanf(line, "%x", &product_id) != 1) {
1461
                goto the_end;
1462
            }
1463
            if (!usb_host_read_file(line, sizeof(line), "product",
1464
                                    de->d_name)) {
1465
                *product_name = 0;
1466
            } else {
1467
                if (strlen(line) > 0) {
1468
                    line[strlen(line) - 1] = '\0';
1469
                }
1470
                pstrcpy(product_name, sizeof(product_name), line);
1471
            }
1472

    
1473
            if (!usb_host_read_file(line, sizeof(line), "speed", de->d_name)) {
1474
                goto the_end;
1475
            }
1476
            if (!strcmp(line, "480\n")) {
1477
                speed = USB_SPEED_HIGH;
1478
            } else if (!strcmp(line, "1.5\n")) {
1479
                speed = USB_SPEED_LOW;
1480
            } else {
1481
                speed = USB_SPEED_FULL;
1482
            }
1483

    
1484
            ret = func(opaque, bus_num, addr, port, class_id, vendor_id,
1485
                       product_id, product_name, speed);
1486
            if (ret) {
1487
                goto the_end;
1488
            }
1489
        }
1490
    }
1491
 the_end:
1492
    if (dir) {
1493
        closedir(dir);
1494
    }
1495
    return ret;
1496
}
1497

    
1498
/*
1499
 * Determine how to access the host's USB devices and call the
1500
 * specific support function.
1501
 */
1502
static int usb_host_scan(void *opaque, USBScanFunc *func)
1503
{
1504
    Monitor *mon = cur_mon;
1505
    FILE *f = NULL;
1506
    DIR *dir = NULL;
1507
    int ret = 0;
1508
    const char *fs_type[] = {"unknown", "proc", "dev", "sys"};
1509
    char devpath[PATH_MAX];
1510

    
1511
    /* only check the host once */
1512
    if (!usb_fs_type) {
1513
        dir = opendir(USBSYSBUS_PATH "/devices");
1514
        if (dir) {
1515
            /* devices found in /dev/bus/usb/ (yes - not a mistake!) */
1516
            strcpy(devpath, USBDEVBUS_PATH);
1517
            usb_fs_type = USB_FS_SYS;
1518
            closedir(dir);
1519
            DPRINTF(USBDBG_DEVOPENED, USBSYSBUS_PATH);
1520
            goto found_devices;
1521
        }
1522
        f = fopen(USBPROCBUS_PATH "/devices", "r");
1523
        if (f) {
1524
            /* devices found in /proc/bus/usb/ */
1525
            strcpy(devpath, USBPROCBUS_PATH);
1526
            usb_fs_type = USB_FS_PROC;
1527
            fclose(f);
1528
            DPRINTF(USBDBG_DEVOPENED, USBPROCBUS_PATH);
1529
            goto found_devices;
1530
        }
1531
        /* try additional methods if an access method hasn't been found yet */
1532
        f = fopen(USBDEVBUS_PATH "/devices", "r");
1533
        if (f) {
1534
            /* devices found in /dev/bus/usb/ */
1535
            strcpy(devpath, USBDEVBUS_PATH);
1536
            usb_fs_type = USB_FS_DEV;
1537
            fclose(f);
1538
            DPRINTF(USBDBG_DEVOPENED, USBDEVBUS_PATH);
1539
            goto found_devices;
1540
        }
1541
    found_devices:
1542
        if (!usb_fs_type) {
1543
            if (mon) {
1544
                monitor_printf(mon, "husb: unable to access USB devices\n");
1545
            }
1546
            return -ENOENT;
1547
        }
1548

    
1549
        /* the module setting (used later for opening devices) */
1550
        usb_host_device_path = qemu_mallocz(strlen(devpath)+1);
1551
        strcpy(usb_host_device_path, devpath);
1552
        if (mon) {
1553
            monitor_printf(mon, "husb: using %s file-system with %s\n",
1554
                           fs_type[usb_fs_type], usb_host_device_path);
1555
        }
1556
    }
1557

    
1558
    switch (usb_fs_type) {
1559
    case USB_FS_PROC:
1560
    case USB_FS_DEV:
1561
        ret = usb_host_scan_dev(opaque, func);
1562
        break;
1563
    case USB_FS_SYS:
1564
        ret = usb_host_scan_sys(opaque, func);
1565
        break;
1566
    default:
1567
        ret = -EINVAL;
1568
        break;
1569
    }
1570
    return ret;
1571
}
1572

    
1573
static QEMUTimer *usb_auto_timer;
1574

    
1575
static int usb_host_auto_scan(void *opaque, int bus_num, int addr, char *port,
1576
                              int class_id, int vendor_id, int product_id,
1577
                              const char *product_name, int speed)
1578
{
1579
    struct USBAutoFilter *f;
1580
    struct USBHostDevice *s;
1581

    
1582
    /* Ignore hubs */
1583
    if (class_id == 9)
1584
        return 0;
1585

    
1586
    QTAILQ_FOREACH(s, &hostdevs, next) {
1587
        f = &s->match;
1588

    
1589
        if (f->bus_num > 0 && f->bus_num != bus_num) {
1590
            continue;
1591
        }
1592
        if (f->addr > 0 && f->addr != addr) {
1593
            continue;
1594
        }
1595
        if (f->port != NULL && (port == NULL || strcmp(f->port, port) != 0)) {
1596
            continue;
1597
        }
1598

    
1599
        if (f->vendor_id > 0 && f->vendor_id != vendor_id) {
1600
            continue;
1601
        }
1602

    
1603
        if (f->product_id > 0 && f->product_id != product_id) {
1604
            continue;
1605
        }
1606
        /* We got a match */
1607

    
1608
        /* Already attached ? */
1609
        if (s->fd != -1) {
1610
            return 0;
1611
        }
1612
        DPRINTF("husb: auto open: bus_num %d addr %d\n", bus_num, addr);
1613

    
1614
        usb_host_open(s, bus_num, addr, port, product_name);
1615
    }
1616

    
1617
    return 0;
1618
}
1619

    
1620
static void usb_host_auto_check(void *unused)
1621
{
1622
    struct USBHostDevice *s;
1623
    int unconnected = 0;
1624

    
1625
    usb_host_scan(NULL, usb_host_auto_scan);
1626

    
1627
    QTAILQ_FOREACH(s, &hostdevs, next) {
1628
        if (s->fd == -1) {
1629
            unconnected++;
1630
        }
1631
    }
1632

    
1633
    if (unconnected == 0) {
1634
        /* nothing to watch */
1635
        if (usb_auto_timer) {
1636
            qemu_del_timer(usb_auto_timer);
1637
        }
1638
        return;
1639
    }
1640

    
1641
    if (!usb_auto_timer) {
1642
        usb_auto_timer = qemu_new_timer_ms(rt_clock, usb_host_auto_check, NULL);
1643
        if (!usb_auto_timer) {
1644
            return;
1645
        }
1646
    }
1647
    qemu_mod_timer(usb_auto_timer, qemu_get_clock_ms(rt_clock) + 2000);
1648
}
1649

    
1650
/*
1651
 * Autoconnect filter
1652
 * Format:
1653
 *    auto:bus:dev[:vid:pid]
1654
 *    auto:bus.dev[:vid:pid]
1655
 *
1656
 *    bus  - bus number    (dec, * means any)
1657
 *    dev  - device number (dec, * means any)
1658
 *    vid  - vendor id     (hex, * means any)
1659
 *    pid  - product id    (hex, * means any)
1660
 *
1661
 *    See 'lsusb' output.
1662
 */
1663
static int parse_filter(const char *spec, struct USBAutoFilter *f)
1664
{
1665
    enum { BUS, DEV, VID, PID, DONE };
1666
    const char *p = spec;
1667
    int i;
1668

    
1669
    f->bus_num    = 0;
1670
    f->addr       = 0;
1671
    f->vendor_id  = 0;
1672
    f->product_id = 0;
1673

    
1674
    for (i = BUS; i < DONE; i++) {
1675
        p = strpbrk(p, ":.");
1676
        if (!p) {
1677
            break;
1678
        }
1679
        p++;
1680

    
1681
        if (*p == '*') {
1682
            continue;
1683
        }
1684
        switch(i) {
1685
        case BUS: f->bus_num = strtol(p, NULL, 10);    break;
1686
        case DEV: f->addr    = strtol(p, NULL, 10);    break;
1687
        case VID: f->vendor_id  = strtol(p, NULL, 16); break;
1688
        case PID: f->product_id = strtol(p, NULL, 16); break;
1689
        }
1690
    }
1691

    
1692
    if (i < DEV) {
1693
        fprintf(stderr, "husb: invalid auto filter spec %s\n", spec);
1694
        return -1;
1695
    }
1696

    
1697
    return 0;
1698
}
1699

    
1700
/**********************/
1701
/* USB host device info */
1702

    
1703
struct usb_class_info {
1704
    int class;
1705
    const char *class_name;
1706
};
1707

    
1708
static const struct usb_class_info usb_class_info[] = {
1709
    { USB_CLASS_AUDIO, "Audio"},
1710
    { USB_CLASS_COMM, "Communication"},
1711
    { USB_CLASS_HID, "HID"},
1712
    { USB_CLASS_HUB, "Hub" },
1713
    { USB_CLASS_PHYSICAL, "Physical" },
1714
    { USB_CLASS_PRINTER, "Printer" },
1715
    { USB_CLASS_MASS_STORAGE, "Storage" },
1716
    { USB_CLASS_CDC_DATA, "Data" },
1717
    { USB_CLASS_APP_SPEC, "Application Specific" },
1718
    { USB_CLASS_VENDOR_SPEC, "Vendor Specific" },
1719
    { USB_CLASS_STILL_IMAGE, "Still Image" },
1720
    { USB_CLASS_CSCID, "Smart Card" },
1721
    { USB_CLASS_CONTENT_SEC, "Content Security" },
1722
    { -1, NULL }
1723
};
1724

    
1725
static const char *usb_class_str(uint8_t class)
1726
{
1727
    const struct usb_class_info *p;
1728
    for(p = usb_class_info; p->class != -1; p++) {
1729
        if (p->class == class) {
1730
            break;
1731
        }
1732
    }
1733
    return p->class_name;
1734
}
1735

    
1736
static void usb_info_device(Monitor *mon, int bus_num, int addr, char *port,
1737
                            int class_id, int vendor_id, int product_id,
1738
                            const char *product_name,
1739
                            int speed)
1740
{
1741
    const char *class_str, *speed_str;
1742

    
1743
    switch(speed) {
1744
    case USB_SPEED_LOW:
1745
        speed_str = "1.5";
1746
        break;
1747
    case USB_SPEED_FULL:
1748
        speed_str = "12";
1749
        break;
1750
    case USB_SPEED_HIGH:
1751
        speed_str = "480";
1752
        break;
1753
    default:
1754
        speed_str = "?";
1755
        break;
1756
    }
1757

    
1758
    monitor_printf(mon, "  Bus %d, Addr %d, Port %s, Speed %s Mb/s\n",
1759
                   bus_num, addr, port, speed_str);
1760
    class_str = usb_class_str(class_id);
1761
    if (class_str) {
1762
        monitor_printf(mon, "    %s:", class_str);
1763
    } else {
1764
        monitor_printf(mon, "    Class %02x:", class_id);
1765
    }
1766
    monitor_printf(mon, " USB device %04x:%04x", vendor_id, product_id);
1767
    if (product_name[0] != '\0') {
1768
        monitor_printf(mon, ", %s", product_name);
1769
    }
1770
    monitor_printf(mon, "\n");
1771
}
1772

    
1773
static int usb_host_info_device(void *opaque, int bus_num, int addr,
1774
                                char *path, int class_id,
1775
                                int vendor_id, int product_id,
1776
                                const char *product_name,
1777
                                int speed)
1778
{
1779
    Monitor *mon = opaque;
1780

    
1781
    usb_info_device(mon, bus_num, addr, path, class_id, vendor_id, product_id,
1782
                    product_name, speed);
1783
    return 0;
1784
}
1785

    
1786
static void dec2str(int val, char *str, size_t size)
1787
{
1788
    if (val == 0) {
1789
        snprintf(str, size, "*");
1790
    } else {
1791
        snprintf(str, size, "%d", val);
1792
    }
1793
}
1794

    
1795
static void hex2str(int val, char *str, size_t size)
1796
{
1797
    if (val == 0) {
1798
        snprintf(str, size, "*");
1799
    } else {
1800
        snprintf(str, size, "%04x", val);
1801
    }
1802
}
1803

    
1804
void usb_host_info(Monitor *mon)
1805
{
1806
    struct USBAutoFilter *f;
1807
    struct USBHostDevice *s;
1808

    
1809
    usb_host_scan(mon, usb_host_info_device);
1810

    
1811
    if (QTAILQ_EMPTY(&hostdevs)) {
1812
        return;
1813
    }
1814

    
1815
    monitor_printf(mon, "  Auto filters:\n");
1816
    QTAILQ_FOREACH(s, &hostdevs, next) {
1817
        char bus[10], addr[10], vid[10], pid[10];
1818
        f = &s->match;
1819
        dec2str(f->bus_num, bus, sizeof(bus));
1820
        dec2str(f->addr, addr, sizeof(addr));
1821
        hex2str(f->vendor_id, vid, sizeof(vid));
1822
        hex2str(f->product_id, pid, sizeof(pid));
1823
        monitor_printf(mon, "    Bus %s, Addr %s, Port %s, ID %s:%s\n",
1824
                       bus, addr, f->port ? f->port : "*", vid, pid);
1825
    }
1826
}