Statistics
| Branch: | Revision:

root / usb-linux.c @ 7a8fc83f

History | View | Annotate | Download (49 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 *unused, void *opaque)
319
{
320
    AsyncURB *aurb = opaque;
321
    USBHostDevice *s = aurb->hdev;
322

    
323
    DPRINTF("husb: async cancel. aurb %p\n", aurb);
324

    
325
    /* Mark it as dead (see async_complete above) */
326
    aurb->packet = NULL;
327

    
328
    int r = ioctl(s->fd, USBDEVFS_DISCARDURB, aurb);
329
    if (r < 0) {
330
        DPRINTF("husb: async. discard urb failed errno %d\n", errno);
331
    }
332
}
333

    
334
static int usb_host_claim_interfaces(USBHostDevice *dev, int configuration)
335
{
336
    int dev_descr_len, config_descr_len;
337
    int interface, nb_interfaces;
338
    int ret, i;
339

    
340
    if (configuration == 0) /* address state - ignore */
341
        return 1;
342

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

    
345
    i = 0;
346
    dev_descr_len = dev->descr[0];
347
    if (dev_descr_len > dev->descr_len) {
348
        goto fail;
349
    }
350

    
351
    i += dev_descr_len;
352
    while (i < dev->descr_len) {
353
        DPRINTF("husb: i is %d, descr_len is %d, dl %d, dt %d\n",
354
                i, dev->descr_len,
355
               dev->descr[i], dev->descr[i+1]);
356

    
357
        if (dev->descr[i+1] != USB_DT_CONFIG) {
358
            i += dev->descr[i];
359
            continue;
360
        }
361
        config_descr_len = dev->descr[i];
362

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

    
365
        if (configuration < 0 || configuration == dev->descr[i + 5]) {
366
            configuration = dev->descr[i + 5];
367
            break;
368
        }
369

    
370
        i += config_descr_len;
371
    }
372

    
373
    if (i >= dev->descr_len) {
374
        fprintf(stderr,
375
                "husb: update iface failed. no matching configuration\n");
376
        goto fail;
377
    }
378
    nb_interfaces = dev->descr[i + 4];
379

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

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

    
411
    printf("husb: %d interfaces claimed for configuration %d\n",
412
           nb_interfaces, configuration);
413

    
414
    dev->ninterfaces   = nb_interfaces;
415
    dev->configuration = configuration;
416
    return 1;
417
}
418

    
419
static int usb_host_release_interfaces(USBHostDevice *s)
420
{
421
    int ret, i;
422

    
423
    DPRINTF("husb: releasing interfaces\n");
424

    
425
    for (i = 0; i < s->ninterfaces; i++) {
426
        ret = ioctl(s->fd, USBDEVFS_RELEASEINTERFACE, &i);
427
        if (ret < 0) {
428
            perror("husb: failed to release interface");
429
            return 0;
430
        }
431
    }
432

    
433
    return 1;
434
}
435

    
436
static void usb_host_handle_reset(USBDevice *dev)
437
{
438
    USBHostDevice *s = DO_UPCAST(USBHostDevice, dev, dev);
439

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

    
442
    ioctl(s->fd, USBDEVFS_RESET);
443

    
444
    usb_host_claim_interfaces(s, s->configuration);
445
}
446

    
447
static void usb_host_handle_destroy(USBDevice *dev)
448
{
449
    USBHostDevice *s = (USBHostDevice *)dev;
450

    
451
    usb_host_close(s);
452
    QTAILQ_REMOVE(&hostdevs, s, next);
453
    qemu_remove_exit_notifier(&s->exit);
454
}
455

    
456
static int usb_linux_update_endp_table(USBHostDevice *s);
457

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

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

    
484
    return aurb;
485
}
486

    
487
static void usb_host_stop_n_free_iso(USBHostDevice *s, uint8_t ep)
488
{
489
    AsyncURB *aurb;
490
    int i, ret, killed = 0, free = 1;
491

    
492
    aurb = get_iso_urb(s, ep);
493
    if (!aurb) {
494
        return;
495
    }
496

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

    
510
    /* Make sure any urbs we've killed are reaped before we free them */
511
    if (killed) {
512
        async_complete(s);
513
    }
514

    
515
    for (i = 0; i < ISO_URB_COUNT; i++) {
516
        qemu_free(aurb[i].urb.buffer);
517
    }
518

    
519
    if (free)
520
        qemu_free(aurb);
521
    else
522
        printf("husb: leaking iso urbs because of discard failure\n");
523
    set_iso_urb(s, ep, NULL);
524
    set_iso_urb_idx(s, ep, 0);
525
    clear_iso_started(s, ep);
526
}
527

    
528
static int urb_status_to_usb_ret(int status)
529
{
530
    switch (status) {
531
    case -EPIPE:
532
        return USB_RET_STALL;
533
    default:
534
        return USB_RET_NAK;
535
    }
536
}
537

    
538
static int usb_host_handle_iso_data(USBHostDevice *s, USBPacket *p, int in)
539
{
540
    AsyncURB *aurb;
541
    int i, j, ret, max_packet_size, offset, len = 0;
542

    
543
    max_packet_size = get_max_packet_size(s, p->devep);
544
    if (max_packet_size == 0)
545
        return USB_RET_NAK;
546

    
547
    aurb = get_iso_urb(s, p->devep);
548
    if (!aurb) {
549
        aurb = usb_host_alloc_iso(s, p->devep, in);
550
    }
551

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

    
581
            /* Check the frame fits */
582
            if (len > max_packet_size) {
583
                printf("husb: send iso data is larger then max packet size\n");
584
                return USB_RET_NAK;
585
            }
586

    
587
            /* All good copy data over */
588
            memcpy(aurb[i].urb.buffer + offset, p->data, len);
589
            aurb[i].urb.iso_frame_desc[j].length = len;
590
            offset += len;
591
            set_iso_buffer_used(s, p->devep, offset);
592

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

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

    
635
    return len;
636
}
637

    
638
static int usb_host_handle_data(USBDevice *dev, USBPacket *p)
639
{
640
    USBHostDevice *s = DO_UPCAST(USBHostDevice, dev, dev);
641
    struct usbdevfs_urb *urb;
642
    AsyncURB *aurb;
643
    int ret;
644
    uint8_t ep;
645

    
646
    if (!is_valid(s, p->devep)) {
647
        return USB_RET_NAK;
648
    }
649

    
650
    if (p->pid == USB_TOKEN_IN) {
651
        ep = p->devep | 0x80;
652
    } else {
653
        ep = p->devep;
654
    }
655

    
656
    if (is_halted(s, p->devep)) {
657
        ret = ioctl(s->fd, USBDEVFS_CLEAR_HALT, &ep);
658
        if (ret < 0) {
659
            DPRINTF("husb: failed to clear halt. ep 0x%x errno %d\n",
660
                   ep, errno);
661
            return USB_RET_NAK;
662
        }
663
        clear_halt(s, p->devep);
664
    }
665

    
666
    if (is_isoc(s, p->devep)) {
667
        return usb_host_handle_iso_data(s, p, p->pid == USB_TOKEN_IN);
668
    }
669

    
670
    aurb = async_alloc(s);
671
    aurb->packet = p;
672

    
673
    urb = &aurb->urb;
674

    
675
    urb->endpoint      = ep;
676
    urb->buffer        = p->data;
677
    urb->buffer_length = p->len;
678
    urb->type          = USBDEVFS_URB_TYPE_BULK;
679
    urb->usercontext   = s;
680

    
681
    ret = ioctl(s->fd, USBDEVFS_SUBMITURB, urb);
682

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

    
686
    if (ret < 0) {
687
        DPRINTF("husb: submit failed. errno %d\n", errno);
688
        async_free(aurb);
689

    
690
        switch(errno) {
691
        case ETIMEDOUT:
692
            return USB_RET_NAK;
693
        case EPIPE:
694
        default:
695
            return USB_RET_STALL;
696
        }
697
    }
698

    
699
    usb_defer_packet(p, async_cancel, aurb);
700
    return USB_RET_ASYNC;
701
}
702

    
703
static int ctrl_error(void)
704
{
705
    if (errno == ETIMEDOUT) {
706
        return USB_RET_NAK;
707
    } else {
708
        return USB_RET_STALL;
709
    }
710
}
711

    
712
static int usb_host_set_address(USBHostDevice *s, int addr)
713
{
714
    DPRINTF("husb: ctrl set addr %u\n", addr);
715
    s->dev.addr = addr;
716
    return 0;
717
}
718

    
719
static int usb_host_set_config(USBHostDevice *s, int config)
720
{
721
    usb_host_release_interfaces(s);
722

    
723
    int ret = ioctl(s->fd, USBDEVFS_SETCONFIGURATION, &config);
724

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

    
727
    if (ret < 0) {
728
        return ctrl_error();
729
    }
730
    usb_host_claim_interfaces(s, config);
731
    return 0;
732
}
733

    
734
static int usb_host_set_interface(USBHostDevice *s, int iface, int alt)
735
{
736
    struct usbdevfs_setinterface si;
737
    int i, ret;
738

    
739
    for (i = 1; i <= MAX_ENDPOINTS; i++) {
740
        if (is_isoc(s, i)) {
741
            usb_host_stop_n_free_iso(s, i);
742
        }
743
    }
744

    
745
    si.interface  = iface;
746
    si.altsetting = alt;
747
    ret = ioctl(s->fd, USBDEVFS_SETINTERFACE, &si);
748

    
749
    DPRINTF("husb: ctrl set iface %d altset %d ret %d errno %d\n",
750
            iface, alt, ret, errno);
751

    
752
    if (ret < 0) {
753
        return ctrl_error();
754
    }
755
    usb_linux_update_endp_table(s);
756
    return 0;
757
}
758

    
759
static int usb_host_handle_control(USBDevice *dev, USBPacket *p,
760
               int request, int value, int index, int length, uint8_t *data)
761
{
762
    USBHostDevice *s = DO_UPCAST(USBHostDevice, dev, dev);
763
    struct usbdevfs_urb *urb;
764
    AsyncURB *aurb;
765
    int ret;
766

    
767
    /*
768
     * Process certain standard device requests.
769
     * These are infrequent and are processed synchronously.
770
     */
771

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

    
776
    switch (request) {
777
    case DeviceOutRequest | USB_REQ_SET_ADDRESS:
778
        return usb_host_set_address(s, value);
779

    
780
    case DeviceOutRequest | USB_REQ_SET_CONFIGURATION:
781
        return usb_host_set_config(s, value & 0xff);
782

    
783
    case InterfaceOutRequest | USB_REQ_SET_INTERFACE:
784
        return usb_host_set_interface(s, index, value);
785
    }
786

    
787
    /* The rest are asynchronous */
788

    
789
    if (length > sizeof(dev->data_buf)) {
790
        fprintf(stderr, "husb: ctrl buffer too small (%d > %zu)\n",
791
                length, sizeof(dev->data_buf));
792
        return USB_RET_STALL;
793
    }
794

    
795
    aurb = async_alloc(s);
796
    aurb->packet = p;
797

    
798
    /*
799
     * Setup ctrl transfer.
800
     *
801
     * s->ctrl is laid out such that data buffer immediately follows
802
     * 'req' struct which is exactly what usbdevfs expects.
803
     */
804
    urb = &aurb->urb;
805

    
806
    urb->type     = USBDEVFS_URB_TYPE_CONTROL;
807
    urb->endpoint = p->devep;
808

    
809
    urb->buffer        = &dev->setup_buf;
810
    urb->buffer_length = length + 8;
811

    
812
    urb->usercontext = s;
813

    
814
    ret = ioctl(s->fd, USBDEVFS_SUBMITURB, urb);
815

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

    
818
    if (ret < 0) {
819
        DPRINTF("husb: submit failed. errno %d\n", errno);
820
        async_free(aurb);
821

    
822
        switch(errno) {
823
        case ETIMEDOUT:
824
            return USB_RET_NAK;
825
        case EPIPE:
826
        default:
827
            return USB_RET_STALL;
828
        }
829
    }
830

    
831
    usb_defer_packet(p, async_cancel, aurb);
832
    return USB_RET_ASYNC;
833
}
834

    
835
static int usb_linux_get_configuration(USBHostDevice *s)
836
{
837
    uint8_t configuration;
838
    struct usb_ctrltransfer ct;
839
    int ret;
840

    
841
    if (usb_fs_type == USB_FS_SYS) {
842
        char device_name[32], line[1024];
843
        int configuration;
844

    
845
        sprintf(device_name, "%d-%s", s->bus_num, s->port);
846

    
847
        if (!usb_host_read_file(line, sizeof(line), "bConfigurationValue",
848
                                device_name)) {
849
            goto usbdevfs;
850
        }
851
        if (sscanf(line, "%d", &configuration) != 1) {
852
            goto usbdevfs;
853
        }
854
        return configuration;
855
    }
856

    
857
usbdevfs:
858
    ct.bRequestType = USB_DIR_IN;
859
    ct.bRequest = USB_REQ_GET_CONFIGURATION;
860
    ct.wValue = 0;
861
    ct.wIndex = 0;
862
    ct.wLength = 1;
863
    ct.data = &configuration;
864
    ct.timeout = 50;
865

    
866
    ret = ioctl(s->fd, USBDEVFS_CONTROL, &ct);
867
    if (ret < 0) {
868
        perror("usb_linux_get_configuration");
869
        return -1;
870
    }
871

    
872
    /* in address state */
873
    if (configuration == 0) {
874
        return -1;
875
    }
876

    
877
    return configuration;
878
}
879

    
880
static uint8_t usb_linux_get_alt_setting(USBHostDevice *s,
881
    uint8_t configuration, uint8_t interface)
882
{
883
    uint8_t alt_setting;
884
    struct usb_ctrltransfer ct;
885
    int ret;
886

    
887
    if (usb_fs_type == USB_FS_SYS) {
888
        char device_name[64], line[1024];
889
        int alt_setting;
890

    
891
        sprintf(device_name, "%d-%s:%d.%d", s->bus_num, s->port,
892
                (int)configuration, (int)interface);
893

    
894
        if (!usb_host_read_file(line, sizeof(line), "bAlternateSetting",
895
                                device_name)) {
896
            goto usbdevfs;
897
        }
898
        if (sscanf(line, "%d", &alt_setting) != 1) {
899
            goto usbdevfs;
900
        }
901
        return alt_setting;
902
    }
903

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

    
918
    return alt_setting;
919
}
920

    
921
/* returns 1 on problem encountered or 0 for success */
922
static int usb_linux_update_endp_table(USBHostDevice *s)
923
{
924
    uint8_t *descriptors;
925
    uint8_t devep, type, configuration, alt_interface;
926
    int interface, length, i;
927

    
928
    for (i = 0; i < MAX_ENDPOINTS; i++)
929
        s->endp_table[i].type = INVALID_EP_TYPE;
930

    
931
    i = usb_linux_get_configuration(s);
932
    if (i < 0)
933
        return 1;
934
    configuration = i;
935

    
936
    /* get the desired configuration, interface, and endpoint descriptors
937
     * from device description */
938
    descriptors = &s->descr[18];
939
    length = s->descr_len - 18;
940
    i = 0;
941

    
942
    if (descriptors[i + 1] != USB_DT_CONFIG ||
943
        descriptors[i + 5] != configuration) {
944
        DPRINTF("invalid descriptor data - configuration\n");
945
        return 1;
946
    }
947
    i += descriptors[i];
948

    
949
    while (i < length) {
950
        if (descriptors[i + 1] != USB_DT_INTERFACE ||
951
            (descriptors[i + 1] == USB_DT_INTERFACE &&
952
             descriptors[i + 4] == 0)) {
953
            i += descriptors[i];
954
            continue;
955
        }
956

    
957
        interface = descriptors[i + 2];
958
        alt_interface = usb_linux_get_alt_setting(s, configuration, interface);
959

    
960
        /* the current interface descriptor is the active interface
961
         * and has endpoints */
962
        if (descriptors[i + 3] != alt_interface) {
963
            i += descriptors[i];
964
            continue;
965
        }
966

    
967
        /* advance to the endpoints */
968
        while (i < length && descriptors[i +1] != USB_DT_ENDPOINT) {
969
            i += descriptors[i];
970
        }
971

    
972
        if (i >= length)
973
            break;
974

    
975
        while (i < length) {
976
            if (descriptors[i + 1] != USB_DT_ENDPOINT) {
977
                break;
978
            }
979

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

    
1003
            i += descriptors[i];
1004
        }
1005
    }
1006
    return 0;
1007
}
1008

    
1009
static int usb_host_open(USBHostDevice *dev, int bus_num,
1010
                         int addr, char *port, const char *prod_name)
1011
{
1012
    int fd = -1, ret;
1013
    struct usbdevfs_connectinfo ci;
1014
    char buf[1024];
1015

    
1016
    if (dev->fd != -1) {
1017
        goto fail;
1018
    }
1019
    printf("husb: open device %d.%d\n", bus_num, addr);
1020

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

    
1034
    dev->bus_num = bus_num;
1035
    dev->addr = addr;
1036
    strcpy(dev->port, port);
1037
    dev->fd = fd;
1038

    
1039
    /* read the device description */
1040
    dev->descr_len = read(fd, dev->descr, sizeof(dev->descr));
1041
    if (dev->descr_len <= 0) {
1042
        perror("husb: reading device data failed");
1043
        goto fail;
1044
    }
1045

    
1046
#ifdef DEBUG
1047
    {
1048
        int x;
1049
        printf("=== begin dumping device descriptor data ===\n");
1050
        for (x = 0; x < dev->descr_len; x++) {
1051
            printf("%02x ", dev->descr[x]);
1052
        }
1053
        printf("\n=== end dumping device descriptor data ===\n");
1054
    }
1055
#endif
1056

    
1057

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

    
1068
    ret = ioctl(fd, USBDEVFS_CONNECTINFO, &ci);
1069
    if (ret < 0) {
1070
        perror("usb_host_device_open: USBDEVFS_CONNECTINFO");
1071
        goto fail;
1072
    }
1073

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

    
1076
    ret = usb_linux_update_endp_table(dev);
1077
    if (ret) {
1078
        goto fail;
1079
    }
1080

    
1081
    if (ci.slow) {
1082
        dev->dev.speed = USB_SPEED_LOW;
1083
    } else {
1084
        dev->dev.speed = USB_SPEED_HIGH;
1085
    }
1086

    
1087
    if (!prod_name || prod_name[0] == '\0') {
1088
        snprintf(dev->dev.product_desc, sizeof(dev->dev.product_desc),
1089
                 "host:%d.%d", bus_num, addr);
1090
    } else {
1091
        pstrcpy(dev->dev.product_desc, sizeof(dev->dev.product_desc),
1092
                prod_name);
1093
    }
1094

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

    
1098
    usb_device_attach(&dev->dev);
1099
    return 0;
1100

    
1101
fail:
1102
    dev->fd = -1;
1103
    if (fd != -1) {
1104
        close(fd);
1105
    }
1106
    return -1;
1107
}
1108

    
1109
static int usb_host_close(USBHostDevice *dev)
1110
{
1111
    int i;
1112

    
1113
    if (dev->fd == -1) {
1114
        return -1;
1115
    }
1116

    
1117
    qemu_set_fd_handler(dev->fd, NULL, NULL, NULL);
1118
    dev->closing = 1;
1119
    for (i = 1; i <= MAX_ENDPOINTS; i++) {
1120
        if (is_isoc(dev, i)) {
1121
            usb_host_stop_n_free_iso(dev, i);
1122
        }
1123
    }
1124
    async_complete(dev);
1125
    dev->closing = 0;
1126
    usb_device_detach(&dev->dev);
1127
    ioctl(dev->fd, USBDEVFS_RESET);
1128
    close(dev->fd);
1129
    dev->fd = -1;
1130
    return 0;
1131
}
1132

    
1133
static void usb_host_exit_notifier(struct Notifier* n)
1134
{
1135
    USBHostDevice *s = container_of(n, USBHostDevice, exit);
1136

    
1137
    if (s->fd != -1) {
1138
        ioctl(s->fd, USBDEVFS_RESET);
1139
    }
1140
}
1141

    
1142
static int usb_host_initfn(USBDevice *dev)
1143
{
1144
    USBHostDevice *s = DO_UPCAST(USBHostDevice, dev, dev);
1145

    
1146
    dev->auto_attach = 0;
1147
    s->fd = -1;
1148
    QTAILQ_INSERT_TAIL(&hostdevs, s, next);
1149
    s->exit.notify = usb_host_exit_notifier;
1150
    qemu_add_exit_notifier(&s->exit);
1151
    usb_host_auto_check(NULL);
1152
    return 0;
1153
}
1154

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

    
1177
static void usb_host_register_devices(void)
1178
{
1179
    usb_qdev_register(&usb_host_dev_info);
1180
}
1181
device_init(usb_host_register_devices)
1182

    
1183
USBDevice *usb_host_device_open(const char *devname)
1184
{
1185
    struct USBAutoFilter filter;
1186
    USBDevice *dev;
1187
    char *p;
1188

    
1189
    dev = usb_create(NULL /* FIXME */, "usb-host");
1190

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

    
1211
    qdev_prop_set_uint32(&dev->qdev, "hostbus",   filter.bus_num);
1212
    qdev_prop_set_uint32(&dev->qdev, "hostaddr",  filter.addr);
1213
    qdev_prop_set_uint32(&dev->qdev, "vendorid",  filter.vendor_id);
1214
    qdev_prop_set_uint32(&dev->qdev, "productid", filter.product_id);
1215
    qdev_init_nofail(&dev->qdev);
1216
    return dev;
1217

    
1218
fail:
1219
    qdev_free(&dev->qdev);
1220
    return NULL;
1221
}
1222

    
1223
int usb_host_device_close(const char *devname)
1224
{
1225
#if 0
1226
    char product_name[PRODUCT_NAME_SZ];
1227
    int bus_num, addr;
1228
    USBHostDevice *s;
1229

1230
    if (strstr(devname, "auto:")) {
1231
        return usb_host_auto_del(devname);
1232
    }
1233
    if (usb_host_find_device(&bus_num, &addr, product_name,
1234
                                    sizeof(product_name), devname) < 0) {
1235
        return -1;
1236
    }
1237
    s = hostdev_find(bus_num, addr);
1238
    if (s) {
1239
        usb_device_delete_addr(s->bus_num, s->dev.addr);
1240
        return 0;
1241
    }
1242
#endif
1243

    
1244
    return -1;
1245
}
1246

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

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

    
1286
    if (!usb_host_device_path) {
1287
        perror("husb: USB Host Device Path not set");
1288
        goto the_end;
1289
    }
1290
    snprintf(line, sizeof(line), "%s/devices", usb_host_device_path);
1291
    f = fopen(line, "r");
1292
    if (!f) {
1293
        perror("husb: cannot open devices file");
1294
        goto the_end;
1295
    }
1296

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

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

    
1389
    snprintf(filename, PATH_MAX, USBSYSBUS_PATH "/devices/%s/%s", device_name,
1390
             device_file);
1391
    f = fopen(filename, "r");
1392
    if (f) {
1393
        ret = fgets(line, line_size, f) != NULL;
1394
        fclose(f);
1395
    }
1396

    
1397
    return ret;
1398
}
1399

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

    
1417
    dir = opendir(USBSYSBUS_PATH "/devices");
1418
    if (!dir) {
1419
        perror("husb: cannot open devices directory");
1420
        goto the_end;
1421
    }
1422

    
1423
    while ((de = readdir(dir))) {
1424
        if (de->d_name[0] != '.' && !strchr(de->d_name, ':')) {
1425
            if (sscanf(de->d_name, "%d-%7[0-9.]", &bus_num, port) < 2) {
1426
                continue;
1427
            }
1428

    
1429
            if (!usb_host_read_file(line, sizeof(line), "devnum", de->d_name)) {
1430
                goto the_end;
1431
            }
1432
            if (sscanf(line, "%d", &addr) != 1) {
1433
                goto the_end;
1434
            }
1435
            if (!usb_host_read_file(line, sizeof(line), "bDeviceClass",
1436
                                    de->d_name)) {
1437
                goto the_end;
1438
            }
1439
            if (sscanf(line, "%x", &class_id) != 1) {
1440
                goto the_end;
1441
            }
1442

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

    
1467
            if (!usb_host_read_file(line, sizeof(line), "speed", de->d_name)) {
1468
                goto the_end;
1469
            }
1470
            if (!strcmp(line, "480\n")) {
1471
                speed = USB_SPEED_HIGH;
1472
            } else if (!strcmp(line, "1.5\n")) {
1473
                speed = USB_SPEED_LOW;
1474
            } else {
1475
                speed = USB_SPEED_FULL;
1476
            }
1477

    
1478
            ret = func(opaque, bus_num, addr, port, class_id, vendor_id,
1479
                       product_id, product_name, speed);
1480
            if (ret) {
1481
                goto the_end;
1482
            }
1483
        }
1484
    }
1485
 the_end:
1486
    if (dir) {
1487
        closedir(dir);
1488
    }
1489
    return ret;
1490
}
1491

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

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

    
1543
        /* the module setting (used later for opening devices) */
1544
        usb_host_device_path = qemu_mallocz(strlen(devpath)+1);
1545
        strcpy(usb_host_device_path, devpath);
1546
        if (mon) {
1547
            monitor_printf(mon, "husb: using %s file-system with %s\n",
1548
                           fs_type[usb_fs_type], usb_host_device_path);
1549
        }
1550
    }
1551

    
1552
    switch (usb_fs_type) {
1553
    case USB_FS_PROC:
1554
    case USB_FS_DEV:
1555
        ret = usb_host_scan_dev(opaque, func);
1556
        break;
1557
    case USB_FS_SYS:
1558
        ret = usb_host_scan_sys(opaque, func);
1559
        break;
1560
    default:
1561
        ret = -EINVAL;
1562
        break;
1563
    }
1564
    return ret;
1565
}
1566

    
1567
static QEMUTimer *usb_auto_timer;
1568

    
1569
static int usb_host_auto_scan(void *opaque, int bus_num, int addr, char *port,
1570
                              int class_id, int vendor_id, int product_id,
1571
                              const char *product_name, int speed)
1572
{
1573
    struct USBAutoFilter *f;
1574
    struct USBHostDevice *s;
1575

    
1576
    /* Ignore hubs */
1577
    if (class_id == 9)
1578
        return 0;
1579

    
1580
    QTAILQ_FOREACH(s, &hostdevs, next) {
1581
        f = &s->match;
1582

    
1583
        if (f->bus_num > 0 && f->bus_num != bus_num) {
1584
            continue;
1585
        }
1586
        if (f->addr > 0 && f->addr != addr) {
1587
            continue;
1588
        }
1589
        if (f->port != NULL && (port == NULL || strcmp(f->port, port) != 0)) {
1590
            continue;
1591
        }
1592

    
1593
        if (f->vendor_id > 0 && f->vendor_id != vendor_id) {
1594
            continue;
1595
        }
1596

    
1597
        if (f->product_id > 0 && f->product_id != product_id) {
1598
            continue;
1599
        }
1600
        /* We got a match */
1601

    
1602
        /* Already attached ? */
1603
        if (s->fd != -1) {
1604
            return 0;
1605
        }
1606
        DPRINTF("husb: auto open: bus_num %d addr %d\n", bus_num, addr);
1607

    
1608
        usb_host_open(s, bus_num, addr, port, product_name);
1609
    }
1610

    
1611
    return 0;
1612
}
1613

    
1614
static void usb_host_auto_check(void *unused)
1615
{
1616
    struct USBHostDevice *s;
1617
    int unconnected = 0;
1618

    
1619
    usb_host_scan(NULL, usb_host_auto_scan);
1620

    
1621
    QTAILQ_FOREACH(s, &hostdevs, next) {
1622
        if (s->fd == -1) {
1623
            unconnected++;
1624
        }
1625
    }
1626

    
1627
    if (unconnected == 0) {
1628
        /* nothing to watch */
1629
        if (usb_auto_timer) {
1630
            qemu_del_timer(usb_auto_timer);
1631
        }
1632
        return;
1633
    }
1634

    
1635
    if (!usb_auto_timer) {
1636
        usb_auto_timer = qemu_new_timer_ms(rt_clock, usb_host_auto_check, NULL);
1637
        if (!usb_auto_timer) {
1638
            return;
1639
        }
1640
    }
1641
    qemu_mod_timer(usb_auto_timer, qemu_get_clock_ms(rt_clock) + 2000);
1642
}
1643

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

    
1663
    f->bus_num    = 0;
1664
    f->addr       = 0;
1665
    f->vendor_id  = 0;
1666
    f->product_id = 0;
1667

    
1668
    for (i = BUS; i < DONE; i++) {
1669
        p = strpbrk(p, ":.");
1670
        if (!p) {
1671
            break;
1672
        }
1673
        p++;
1674

    
1675
        if (*p == '*') {
1676
            continue;
1677
        }
1678
        switch(i) {
1679
        case BUS: f->bus_num = strtol(p, NULL, 10);    break;
1680
        case DEV: f->addr    = strtol(p, NULL, 10);    break;
1681
        case VID: f->vendor_id  = strtol(p, NULL, 16); break;
1682
        case PID: f->product_id = strtol(p, NULL, 16); break;
1683
        }
1684
    }
1685

    
1686
    if (i < DEV) {
1687
        fprintf(stderr, "husb: invalid auto filter spec %s\n", spec);
1688
        return -1;
1689
    }
1690

    
1691
    return 0;
1692
}
1693

    
1694
/**********************/
1695
/* USB host device info */
1696

    
1697
struct usb_class_info {
1698
    int class;
1699
    const char *class_name;
1700
};
1701

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

    
1719
static const char *usb_class_str(uint8_t class)
1720
{
1721
    const struct usb_class_info *p;
1722
    for(p = usb_class_info; p->class != -1; p++) {
1723
        if (p->class == class) {
1724
            break;
1725
        }
1726
    }
1727
    return p->class_name;
1728
}
1729

    
1730
static void usb_info_device(Monitor *mon, int bus_num, int addr, char *port,
1731
                            int class_id, int vendor_id, int product_id,
1732
                            const char *product_name,
1733
                            int speed)
1734
{
1735
    const char *class_str, *speed_str;
1736

    
1737
    switch(speed) {
1738
    case USB_SPEED_LOW:
1739
        speed_str = "1.5";
1740
        break;
1741
    case USB_SPEED_FULL:
1742
        speed_str = "12";
1743
        break;
1744
    case USB_SPEED_HIGH:
1745
        speed_str = "480";
1746
        break;
1747
    default:
1748
        speed_str = "?";
1749
        break;
1750
    }
1751

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

    
1767
static int usb_host_info_device(void *opaque, int bus_num, int addr,
1768
                                char *path, int class_id,
1769
                                int vendor_id, int product_id,
1770
                                const char *product_name,
1771
                                int speed)
1772
{
1773
    Monitor *mon = opaque;
1774

    
1775
    usb_info_device(mon, bus_num, addr, path, class_id, vendor_id, product_id,
1776
                    product_name, speed);
1777
    return 0;
1778
}
1779

    
1780
static void dec2str(int val, char *str, size_t size)
1781
{
1782
    if (val == 0) {
1783
        snprintf(str, size, "*");
1784
    } else {
1785
        snprintf(str, size, "%d", val);
1786
    }
1787
}
1788

    
1789
static void hex2str(int val, char *str, size_t size)
1790
{
1791
    if (val == 0) {
1792
        snprintf(str, size, "*");
1793
    } else {
1794
        snprintf(str, size, "%04x", val);
1795
    }
1796
}
1797

    
1798
void usb_host_info(Monitor *mon)
1799
{
1800
    struct USBAutoFilter *f;
1801
    struct USBHostDevice *s;
1802

    
1803
    usb_host_scan(mon, usb_host_info_device);
1804

    
1805
    if (QTAILQ_EMPTY(&hostdevs)) {
1806
        return;
1807
    }
1808

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