Statistics
| Branch: | Revision:

root / usb-linux.c @ 5557d820

History | View | Annotate | Download (48.6 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
    uint32_t vendor_id;
108
    uint32_t product_id;
109
};
110

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

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

    
122
    struct endp_data endp_table[MAX_ENDPOINTS];
123

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

    
130
    QTAILQ_ENTRY(USBHostDevice) next;
131
} USBHostDevice;
132

    
133
static QTAILQ_HEAD(, USBHostDevice) hostdevs = QTAILQ_HEAD_INITIALIZER(hostdevs);
134

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
216
/*
217
 * Async URB state.
218
 * We always allocate iso packet descriptors even for bulk transfers
219
 * to simplify allocation and casts.
220
 */
221
struct AsyncURB
222
{
223
    struct usbdevfs_urb urb;
224
    struct usbdevfs_iso_packet_desc isocpd[ISO_FRAME_DESC_PER_URB];
225

    
226
    /* For regular async urbs */
227
    USBPacket     *packet;
228
    USBHostDevice *hdev;
229

    
230
    /* For buffered iso handling */
231
    int iso_frame_idx; /* -1 means in flight */
232
};
233

    
234
static AsyncURB *async_alloc(void)
235
{
236
    return (AsyncURB *) qemu_mallocz(sizeof(AsyncURB));
237
}
238

    
239
static void async_free(AsyncURB *aurb)
240
{
241
    qemu_free(aurb);
242
}
243

    
244
static void async_complete(void *opaque)
245
{
246
    USBHostDevice *s = opaque;
247
    AsyncURB *aurb;
248

    
249
    while (1) {
250
        USBPacket *p;
251

    
252
        int r = ioctl(s->fd, USBDEVFS_REAPURBNDELAY, &aurb);
253
        if (r < 0) {
254
            if (errno == EAGAIN) {
255
                return;
256
            }
257
            if (errno == ENODEV && !s->closing) {
258
                printf("husb: device %d.%d disconnected\n",
259
                       s->bus_num, s->addr);
260
                usb_host_close(s);
261
                usb_host_auto_check(NULL);
262
                return;
263
            }
264

    
265
            DPRINTF("husb: async. reap urb failed errno %d\n", errno);
266
            return;
267
        }
268

    
269
        DPRINTF("husb: async completed. aurb %p status %d alen %d\n",
270
                aurb, aurb->urb.status, aurb->urb.actual_length);
271

    
272
        /* If this is a buffered iso urb mark it as complete and don't do
273
           anything else (it is handled further in usb_host_handle_iso_data) */
274
        if (aurb->iso_frame_idx == -1) {
275
            if (aurb->urb.status == -EPIPE) {
276
                set_halt(s, aurb->urb.endpoint & 0xf);
277
            }
278
            aurb->iso_frame_idx = 0;
279
            continue;
280
        }
281

    
282
        p = aurb->packet;
283

    
284
        if (p) {
285
            switch (aurb->urb.status) {
286
            case 0:
287
                p->len = aurb->urb.actual_length;
288
                break;
289

    
290
            case -EPIPE:
291
                set_halt(s, p->devep);
292
                p->len = USB_RET_STALL;
293
                break;
294

    
295
            default:
296
                p->len = USB_RET_NAK;
297
                break;
298
            }
299

    
300
            if (aurb->urb.type == USBDEVFS_URB_TYPE_CONTROL) {
301
                usb_generic_async_ctrl_complete(&s->dev, p);
302
            } else {
303
                usb_packet_complete(&s->dev, p);
304
            }
305
        }
306

    
307
        async_free(aurb);
308
    }
309
}
310

    
311
static void async_cancel(USBPacket *unused, void *opaque)
312
{
313
    AsyncURB *aurb = opaque;
314
    USBHostDevice *s = aurb->hdev;
315

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

    
318
    /* Mark it as dead (see async_complete above) */
319
    aurb->packet = NULL;
320

    
321
    int r = ioctl(s->fd, USBDEVFS_DISCARDURB, aurb);
322
    if (r < 0) {
323
        DPRINTF("husb: async. discard urb failed errno %d\n", errno);
324
    }
325
}
326

    
327
static int usb_host_claim_interfaces(USBHostDevice *dev, int configuration)
328
{
329
    int dev_descr_len, config_descr_len;
330
    int interface, nb_interfaces;
331
    int ret, i;
332

    
333
    if (configuration == 0) /* address state - ignore */
334
        return 1;
335

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

    
338
    i = 0;
339
    dev_descr_len = dev->descr[0];
340
    if (dev_descr_len > dev->descr_len) {
341
        goto fail;
342
    }
343

    
344
    i += dev_descr_len;
345
    while (i < dev->descr_len) {
346
        DPRINTF("husb: i is %d, descr_len is %d, dl %d, dt %d\n",
347
                i, dev->descr_len,
348
               dev->descr[i], dev->descr[i+1]);
349

    
350
        if (dev->descr[i+1] != USB_DT_CONFIG) {
351
            i += dev->descr[i];
352
            continue;
353
        }
354
        config_descr_len = dev->descr[i];
355

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

    
358
        if (configuration < 0 || configuration == dev->descr[i + 5]) {
359
            configuration = dev->descr[i + 5];
360
            break;
361
        }
362

    
363
        i += config_descr_len;
364
    }
365

    
366
    if (i >= dev->descr_len) {
367
        fprintf(stderr,
368
                "husb: update iface failed. no matching configuration\n");
369
        goto fail;
370
    }
371
    nb_interfaces = dev->descr[i + 4];
372

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

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

    
404
    printf("husb: %d interfaces claimed for configuration %d\n",
405
           nb_interfaces, configuration);
406

    
407
    dev->ninterfaces   = nb_interfaces;
408
    dev->configuration = configuration;
409
    return 1;
410
}
411

    
412
static int usb_host_release_interfaces(USBHostDevice *s)
413
{
414
    int ret, i;
415

    
416
    DPRINTF("husb: releasing interfaces\n");
417

    
418
    for (i = 0; i < s->ninterfaces; i++) {
419
        ret = ioctl(s->fd, USBDEVFS_RELEASEINTERFACE, &i);
420
        if (ret < 0) {
421
            perror("husb: failed to release interface");
422
            return 0;
423
        }
424
    }
425

    
426
    return 1;
427
}
428

    
429
static void usb_host_handle_reset(USBDevice *dev)
430
{
431
    USBHostDevice *s = DO_UPCAST(USBHostDevice, dev, dev);
432

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

    
435
    ioctl(s->fd, USBDEVFS_RESET);
436

    
437
    usb_host_claim_interfaces(s, s->configuration);
438
}
439

    
440
static void usb_host_handle_destroy(USBDevice *dev)
441
{
442
    USBHostDevice *s = (USBHostDevice *)dev;
443

    
444
    usb_host_close(s);
445
    QTAILQ_REMOVE(&hostdevs, s, next);
446
    qemu_remove_exit_notifier(&s->exit);
447
}
448

    
449
static int usb_linux_update_endp_table(USBHostDevice *s);
450

    
451
/* iso data is special, we need to keep enough urbs in flight to make sure
452
   that the controller never runs out of them, otherwise the device will
453
   likely suffer a buffer underrun / overrun. */
454
static AsyncURB *usb_host_alloc_iso(USBHostDevice *s, uint8_t ep, int in)
455
{
456
    AsyncURB *aurb;
457
    int i, j, len = get_max_packet_size(s, ep);
458

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

    
477
    return aurb;
478
}
479

    
480
static void usb_host_stop_n_free_iso(USBHostDevice *s, uint8_t ep)
481
{
482
    AsyncURB *aurb;
483
    int i, ret, killed = 0, free = 1;
484

    
485
    aurb = get_iso_urb(s, ep);
486
    if (!aurb) {
487
        return;
488
    }
489

    
490
    for (i = 0; i < ISO_URB_COUNT; i++) {
491
        /* in flight? */
492
        if (aurb[i].iso_frame_idx == -1) {
493
            ret = ioctl(s->fd, USBDEVFS_DISCARDURB, &aurb[i]);
494
            if (ret < 0) {
495
                printf("husb: discard isoc in urb failed errno %d\n", errno);
496
                free = 0;
497
                continue;
498
            }
499
            killed++;
500
        }
501
    }
502

    
503
    /* Make sure any urbs we've killed are reaped before we free them */
504
    if (killed) {
505
        async_complete(s);
506
    }
507

    
508
    for (i = 0; i < ISO_URB_COUNT; i++) {
509
        qemu_free(aurb[i].urb.buffer);
510
    }
511

    
512
    if (free)
513
        qemu_free(aurb);
514
    else
515
        printf("husb: leaking iso urbs because of discard failure\n");
516
    set_iso_urb(s, ep, NULL);
517
    set_iso_urb_idx(s, ep, 0);
518
    clear_iso_started(s, ep);
519
}
520

    
521
static int urb_status_to_usb_ret(int status)
522
{
523
    switch (status) {
524
    case -EPIPE:
525
        return USB_RET_STALL;
526
    default:
527
        return USB_RET_NAK;
528
    }
529
}
530

    
531
static int usb_host_handle_iso_data(USBHostDevice *s, USBPacket *p, int in)
532
{
533
    AsyncURB *aurb;
534
    int i, j, ret, max_packet_size, offset, len = 0;
535

    
536
    max_packet_size = get_max_packet_size(s, p->devep);
537
    if (max_packet_size == 0)
538
        return USB_RET_NAK;
539

    
540
    aurb = get_iso_urb(s, p->devep);
541
    if (!aurb) {
542
        aurb = usb_host_alloc_iso(s, p->devep, in);
543
    }
544

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

    
574
            /* Check the frame fits */
575
            if (len > max_packet_size) {
576
                printf("husb: send iso data is larger then max packet size\n");
577
                return USB_RET_NAK;
578
            }
579

    
580
            /* All good copy data over */
581
            memcpy(aurb[i].urb.buffer + offset, p->data, len);
582
            aurb[i].urb.iso_frame_desc[j].length = len;
583
            offset += len;
584
            set_iso_buffer_used(s, p->devep, offset);
585

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

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

    
628
    return len;
629
}
630

    
631
static int usb_host_handle_data(USBDevice *dev, USBPacket *p)
632
{
633
    USBHostDevice *s = DO_UPCAST(USBHostDevice, dev, dev);
634
    struct usbdevfs_urb *urb;
635
    AsyncURB *aurb;
636
    int ret;
637
    uint8_t ep;
638

    
639
    if (!is_valid(s, p->devep)) {
640
        return USB_RET_NAK;
641
    }
642

    
643
    if (p->pid == USB_TOKEN_IN) {
644
        ep = p->devep | 0x80;
645
    } else {
646
        ep = p->devep;
647
    }
648

    
649
    if (is_halted(s, p->devep)) {
650
        ret = ioctl(s->fd, USBDEVFS_CLEAR_HALT, &ep);
651
        if (ret < 0) {
652
            DPRINTF("husb: failed to clear halt. ep 0x%x errno %d\n",
653
                   ep, errno);
654
            return USB_RET_NAK;
655
        }
656
        clear_halt(s, p->devep);
657
    }
658

    
659
    if (is_isoc(s, p->devep)) {
660
        return usb_host_handle_iso_data(s, p, p->pid == USB_TOKEN_IN);
661
    }
662

    
663
    aurb = async_alloc();
664
    aurb->hdev   = s;
665
    aurb->packet = p;
666

    
667
    urb = &aurb->urb;
668

    
669
    urb->endpoint      = ep;
670
    urb->buffer        = p->data;
671
    urb->buffer_length = p->len;
672
    urb->type          = USBDEVFS_URB_TYPE_BULK;
673
    urb->usercontext   = s;
674

    
675
    ret = ioctl(s->fd, USBDEVFS_SUBMITURB, urb);
676

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

    
680
    if (ret < 0) {
681
        DPRINTF("husb: submit failed. errno %d\n", errno);
682
        async_free(aurb);
683

    
684
        switch(errno) {
685
        case ETIMEDOUT:
686
            return USB_RET_NAK;
687
        case EPIPE:
688
        default:
689
            return USB_RET_STALL;
690
        }
691
    }
692

    
693
    usb_defer_packet(p, async_cancel, aurb);
694
    return USB_RET_ASYNC;
695
}
696

    
697
static int ctrl_error(void)
698
{
699
    if (errno == ETIMEDOUT) {
700
        return USB_RET_NAK;
701
    } else {
702
        return USB_RET_STALL;
703
    }
704
}
705

    
706
static int usb_host_set_address(USBHostDevice *s, int addr)
707
{
708
    DPRINTF("husb: ctrl set addr %u\n", addr);
709
    s->dev.addr = addr;
710
    return 0;
711
}
712

    
713
static int usb_host_set_config(USBHostDevice *s, int config)
714
{
715
    usb_host_release_interfaces(s);
716

    
717
    int ret = ioctl(s->fd, USBDEVFS_SETCONFIGURATION, &config);
718

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

    
721
    if (ret < 0) {
722
        return ctrl_error();
723
    }
724
    usb_host_claim_interfaces(s, config);
725
    return 0;
726
}
727

    
728
static int usb_host_set_interface(USBHostDevice *s, int iface, int alt)
729
{
730
    struct usbdevfs_setinterface si;
731
    int i, ret;
732

    
733
    for (i = 1; i <= MAX_ENDPOINTS; i++) {
734
        if (is_isoc(s, i)) {
735
            usb_host_stop_n_free_iso(s, i);
736
        }
737
    }
738

    
739
    si.interface  = iface;
740
    si.altsetting = alt;
741
    ret = ioctl(s->fd, USBDEVFS_SETINTERFACE, &si);
742

    
743
    DPRINTF("husb: ctrl set iface %d altset %d ret %d errno %d\n",
744
            iface, alt, ret, errno);
745

    
746
    if (ret < 0) {
747
        return ctrl_error();
748
    }
749
    usb_linux_update_endp_table(s);
750
    return 0;
751
}
752

    
753
static int usb_host_handle_control(USBDevice *dev, USBPacket *p,
754
               int request, int value, int index, int length, uint8_t *data)
755
{
756
    USBHostDevice *s = DO_UPCAST(USBHostDevice, dev, dev);
757
    struct usbdevfs_urb *urb;
758
    AsyncURB *aurb;
759
    int ret;
760

    
761
    /*
762
     * Process certain standard device requests.
763
     * These are infrequent and are processed synchronously.
764
     */
765

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

    
770
    switch (request) {
771
    case DeviceOutRequest | USB_REQ_SET_ADDRESS:
772
        return usb_host_set_address(s, value);
773

    
774
    case DeviceOutRequest | USB_REQ_SET_CONFIGURATION:
775
        return usb_host_set_config(s, value & 0xff);
776

    
777
    case InterfaceOutRequest | USB_REQ_SET_INTERFACE:
778
        return usb_host_set_interface(s, index, value);
779
    }
780

    
781
    /* The rest are asynchronous */
782

    
783
    if (length > sizeof(dev->data_buf)) {
784
        fprintf(stderr, "husb: ctrl buffer too small (%d > %zu)\n",
785
                length, sizeof(dev->data_buf));
786
        return USB_RET_STALL;
787
    }
788

    
789
    aurb = async_alloc();
790
    aurb->hdev   = s;
791
    aurb->packet = p;
792

    
793
    /*
794
     * Setup ctrl transfer.
795
     *
796
     * s->ctrl is laid out such that data buffer immediately follows
797
     * 'req' struct which is exactly what usbdevfs expects.
798
     */
799
    urb = &aurb->urb;
800

    
801
    urb->type     = USBDEVFS_URB_TYPE_CONTROL;
802
    urb->endpoint = p->devep;
803

    
804
    urb->buffer        = &dev->setup_buf;
805
    urb->buffer_length = length + 8;
806

    
807
    urb->usercontext = s;
808

    
809
    ret = ioctl(s->fd, USBDEVFS_SUBMITURB, urb);
810

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

    
813
    if (ret < 0) {
814
        DPRINTF("husb: submit failed. errno %d\n", errno);
815
        async_free(aurb);
816

    
817
        switch(errno) {
818
        case ETIMEDOUT:
819
            return USB_RET_NAK;
820
        case EPIPE:
821
        default:
822
            return USB_RET_STALL;
823
        }
824
    }
825

    
826
    usb_defer_packet(p, async_cancel, aurb);
827
    return USB_RET_ASYNC;
828
}
829

    
830
static int usb_linux_get_configuration(USBHostDevice *s)
831
{
832
    uint8_t configuration;
833
    struct usb_ctrltransfer ct;
834
    int ret;
835

    
836
    if (usb_fs_type == USB_FS_SYS) {
837
        char device_name[32], line[1024];
838
        int configuration;
839

    
840
        sprintf(device_name, "%d-%s", s->bus_num, s->port);
841

    
842
        if (!usb_host_read_file(line, sizeof(line), "bConfigurationValue",
843
                                device_name)) {
844
            goto usbdevfs;
845
        }
846
        if (sscanf(line, "%d", &configuration) != 1) {
847
            goto usbdevfs;
848
        }
849
        return configuration;
850
    }
851

    
852
usbdevfs:
853
    ct.bRequestType = USB_DIR_IN;
854
    ct.bRequest = USB_REQ_GET_CONFIGURATION;
855
    ct.wValue = 0;
856
    ct.wIndex = 0;
857
    ct.wLength = 1;
858
    ct.data = &configuration;
859
    ct.timeout = 50;
860

    
861
    ret = ioctl(s->fd, USBDEVFS_CONTROL, &ct);
862
    if (ret < 0) {
863
        perror("usb_linux_get_configuration");
864
        return -1;
865
    }
866

    
867
    /* in address state */
868
    if (configuration == 0) {
869
        return -1;
870
    }
871

    
872
    return configuration;
873
}
874

    
875
static uint8_t usb_linux_get_alt_setting(USBHostDevice *s,
876
    uint8_t configuration, uint8_t interface)
877
{
878
    uint8_t alt_setting;
879
    struct usb_ctrltransfer ct;
880
    int ret;
881

    
882
    if (usb_fs_type == USB_FS_SYS) {
883
        char device_name[64], line[1024];
884
        int alt_setting;
885

    
886
        sprintf(device_name, "%d-%s:%d.%d", s->bus_num, s->port,
887
                (int)configuration, (int)interface);
888

    
889
        if (!usb_host_read_file(line, sizeof(line), "bAlternateSetting",
890
                                device_name)) {
891
            goto usbdevfs;
892
        }
893
        if (sscanf(line, "%d", &alt_setting) != 1) {
894
            goto usbdevfs;
895
        }
896
        return alt_setting;
897
    }
898

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

    
913
    return alt_setting;
914
}
915

    
916
/* returns 1 on problem encountered or 0 for success */
917
static int usb_linux_update_endp_table(USBHostDevice *s)
918
{
919
    uint8_t *descriptors;
920
    uint8_t devep, type, configuration, alt_interface;
921
    int interface, length, i;
922

    
923
    for (i = 0; i < MAX_ENDPOINTS; i++)
924
        s->endp_table[i].type = INVALID_EP_TYPE;
925

    
926
    i = usb_linux_get_configuration(s);
927
    if (i < 0)
928
        return 1;
929
    configuration = i;
930

    
931
    /* get the desired configuration, interface, and endpoint descriptors
932
     * from device description */
933
    descriptors = &s->descr[18];
934
    length = s->descr_len - 18;
935
    i = 0;
936

    
937
    if (descriptors[i + 1] != USB_DT_CONFIG ||
938
        descriptors[i + 5] != configuration) {
939
        DPRINTF("invalid descriptor data - configuration\n");
940
        return 1;
941
    }
942
    i += descriptors[i];
943

    
944
    while (i < length) {
945
        if (descriptors[i + 1] != USB_DT_INTERFACE ||
946
            (descriptors[i + 1] == USB_DT_INTERFACE &&
947
             descriptors[i + 4] == 0)) {
948
            i += descriptors[i];
949
            continue;
950
        }
951

    
952
        interface = descriptors[i + 2];
953
        alt_interface = usb_linux_get_alt_setting(s, configuration, interface);
954

    
955
        /* the current interface descriptor is the active interface
956
         * and has endpoints */
957
        if (descriptors[i + 3] != alt_interface) {
958
            i += descriptors[i];
959
            continue;
960
        }
961

    
962
        /* advance to the endpoints */
963
        while (i < length && descriptors[i +1] != USB_DT_ENDPOINT) {
964
            i += descriptors[i];
965
        }
966

    
967
        if (i >= length)
968
            break;
969

    
970
        while (i < length) {
971
            if (descriptors[i + 1] != USB_DT_ENDPOINT) {
972
                break;
973
            }
974

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

    
998
            i += descriptors[i];
999
        }
1000
    }
1001
    return 0;
1002
}
1003

    
1004
static int usb_host_open(USBHostDevice *dev, int bus_num,
1005
                         int addr, char *port, const char *prod_name)
1006
{
1007
    int fd = -1, ret;
1008
    struct usbdevfs_connectinfo ci;
1009
    char buf[1024];
1010

    
1011
    if (dev->fd != -1) {
1012
        goto fail;
1013
    }
1014
    printf("husb: open device %d.%d\n", bus_num, addr);
1015

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

    
1029
    dev->bus_num = bus_num;
1030
    dev->addr = addr;
1031
    strcpy(dev->port, port);
1032
    dev->fd = fd;
1033

    
1034
    /* read the device description */
1035
    dev->descr_len = read(fd, dev->descr, sizeof(dev->descr));
1036
    if (dev->descr_len <= 0) {
1037
        perror("husb: reading device data failed");
1038
        goto fail;
1039
    }
1040

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

    
1052

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

    
1063
    ret = ioctl(fd, USBDEVFS_CONNECTINFO, &ci);
1064
    if (ret < 0) {
1065
        perror("usb_host_device_open: USBDEVFS_CONNECTINFO");
1066
        goto fail;
1067
    }
1068

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

    
1071
    ret = usb_linux_update_endp_table(dev);
1072
    if (ret) {
1073
        goto fail;
1074
    }
1075

    
1076
    if (ci.slow) {
1077
        dev->dev.speed = USB_SPEED_LOW;
1078
    } else {
1079
        dev->dev.speed = USB_SPEED_HIGH;
1080
    }
1081

    
1082
    if (!prod_name || prod_name[0] == '\0') {
1083
        snprintf(dev->dev.product_desc, sizeof(dev->dev.product_desc),
1084
                 "host:%d.%d", bus_num, addr);
1085
    } else {
1086
        pstrcpy(dev->dev.product_desc, sizeof(dev->dev.product_desc),
1087
                prod_name);
1088
    }
1089

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

    
1093
    usb_device_attach(&dev->dev);
1094
    return 0;
1095

    
1096
fail:
1097
    dev->fd = -1;
1098
    if (fd != -1) {
1099
        close(fd);
1100
    }
1101
    return -1;
1102
}
1103

    
1104
static int usb_host_close(USBHostDevice *dev)
1105
{
1106
    int i;
1107

    
1108
    if (dev->fd == -1) {
1109
        return -1;
1110
    }
1111

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

    
1128
static void usb_host_exit_notifier(struct Notifier* n)
1129
{
1130
    USBHostDevice *s = container_of(n, USBHostDevice, exit);
1131

    
1132
    if (s->fd != -1) {
1133
        ioctl(s->fd, USBDEVFS_RESET);
1134
    }
1135
}
1136

    
1137
static int usb_host_initfn(USBDevice *dev)
1138
{
1139
    USBHostDevice *s = DO_UPCAST(USBHostDevice, dev, dev);
1140

    
1141
    dev->auto_attach = 0;
1142
    s->fd = -1;
1143
    QTAILQ_INSERT_TAIL(&hostdevs, s, next);
1144
    s->exit.notify = usb_host_exit_notifier;
1145
    qemu_add_exit_notifier(&s->exit);
1146
    usb_host_auto_check(NULL);
1147
    return 0;
1148
}
1149

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

    
1171
static void usb_host_register_devices(void)
1172
{
1173
    usb_qdev_register(&usb_host_dev_info);
1174
}
1175
device_init(usb_host_register_devices)
1176

    
1177
USBDevice *usb_host_device_open(const char *devname)
1178
{
1179
    struct USBAutoFilter filter;
1180
    USBDevice *dev;
1181
    char *p;
1182

    
1183
    dev = usb_create(NULL /* FIXME */, "usb-host");
1184

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

    
1205
    qdev_prop_set_uint32(&dev->qdev, "hostbus",   filter.bus_num);
1206
    qdev_prop_set_uint32(&dev->qdev, "hostaddr",  filter.addr);
1207
    qdev_prop_set_uint32(&dev->qdev, "vendorid",  filter.vendor_id);
1208
    qdev_prop_set_uint32(&dev->qdev, "productid", filter.product_id);
1209
    qdev_init_nofail(&dev->qdev);
1210
    return dev;
1211

    
1212
fail:
1213
    qdev_free(&dev->qdev);
1214
    return NULL;
1215
}
1216

    
1217
int usb_host_device_close(const char *devname)
1218
{
1219
#if 0
1220
    char product_name[PRODUCT_NAME_SZ];
1221
    int bus_num, addr;
1222
    USBHostDevice *s;
1223

1224
    if (strstr(devname, "auto:")) {
1225
        return usb_host_auto_del(devname);
1226
    }
1227
    if (usb_host_find_device(&bus_num, &addr, product_name,
1228
                                    sizeof(product_name), devname) < 0) {
1229
        return -1;
1230
    }
1231
    s = hostdev_find(bus_num, addr);
1232
    if (s) {
1233
        usb_device_delete_addr(s->bus_num, s->dev.addr);
1234
        return 0;
1235
    }
1236
#endif
1237

    
1238
    return -1;
1239
}
1240

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

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

    
1280
    if (!usb_host_device_path) {
1281
        perror("husb: USB Host Device Path not set");
1282
        goto the_end;
1283
    }
1284
    snprintf(line, sizeof(line), "%s/devices", usb_host_device_path);
1285
    f = fopen(line, "r");
1286
    if (!f) {
1287
        perror("husb: cannot open devices file");
1288
        goto the_end;
1289
    }
1290

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

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

    
1383
    snprintf(filename, PATH_MAX, USBSYSBUS_PATH "/devices/%s/%s", device_name,
1384
             device_file);
1385
    f = fopen(filename, "r");
1386
    if (f) {
1387
        ret = fgets(line, line_size, f) != NULL;
1388
        fclose(f);
1389
    }
1390

    
1391
    return ret;
1392
}
1393

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

    
1411
    dir = opendir(USBSYSBUS_PATH "/devices");
1412
    if (!dir) {
1413
        perror("husb: cannot open devices directory");
1414
        goto the_end;
1415
    }
1416

    
1417
    while ((de = readdir(dir))) {
1418
        if (de->d_name[0] != '.' && !strchr(de->d_name, ':')) {
1419
            if (sscanf(de->d_name, "%d-%7[0-9.]", &bus_num, port) < 2) {
1420
                continue;
1421
            }
1422

    
1423
            if (!usb_host_read_file(line, sizeof(line), "devnum", de->d_name)) {
1424
                goto the_end;
1425
            }
1426
            if (sscanf(line, "%d", &addr) != 1) {
1427
                goto the_end;
1428
            }
1429
            if (!usb_host_read_file(line, sizeof(line), "bDeviceClass",
1430
                                    de->d_name)) {
1431
                goto the_end;
1432
            }
1433
            if (sscanf(line, "%x", &class_id) != 1) {
1434
                goto the_end;
1435
            }
1436

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

    
1461
            if (!usb_host_read_file(line, sizeof(line), "speed", de->d_name)) {
1462
                goto the_end;
1463
            }
1464
            if (!strcmp(line, "480\n")) {
1465
                speed = USB_SPEED_HIGH;
1466
            } else if (!strcmp(line, "1.5\n")) {
1467
                speed = USB_SPEED_LOW;
1468
            } else {
1469
                speed = USB_SPEED_FULL;
1470
            }
1471

    
1472
            ret = func(opaque, bus_num, addr, port, class_id, vendor_id,
1473
                       product_id, product_name, speed);
1474
            if (ret) {
1475
                goto the_end;
1476
            }
1477
        }
1478
    }
1479
 the_end:
1480
    if (dir) {
1481
        closedir(dir);
1482
    }
1483
    return ret;
1484
}
1485

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

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

    
1537
        /* the module setting (used later for opening devices) */
1538
        usb_host_device_path = qemu_mallocz(strlen(devpath)+1);
1539
        strcpy(usb_host_device_path, devpath);
1540
        if (mon) {
1541
            monitor_printf(mon, "husb: using %s file-system with %s\n",
1542
                           fs_type[usb_fs_type], usb_host_device_path);
1543
        }
1544
    }
1545

    
1546
    switch (usb_fs_type) {
1547
    case USB_FS_PROC:
1548
    case USB_FS_DEV:
1549
        ret = usb_host_scan_dev(opaque, func);
1550
        break;
1551
    case USB_FS_SYS:
1552
        ret = usb_host_scan_sys(opaque, func);
1553
        break;
1554
    default:
1555
        ret = -EINVAL;
1556
        break;
1557
    }
1558
    return ret;
1559
}
1560

    
1561
static QEMUTimer *usb_auto_timer;
1562

    
1563
static int usb_host_auto_scan(void *opaque, int bus_num, int addr, char *port,
1564
                              int class_id, int vendor_id, int product_id,
1565
                              const char *product_name, int speed)
1566
{
1567
    struct USBAutoFilter *f;
1568
    struct USBHostDevice *s;
1569

    
1570
    /* Ignore hubs */
1571
    if (class_id == 9)
1572
        return 0;
1573

    
1574
    QTAILQ_FOREACH(s, &hostdevs, next) {
1575
        f = &s->match;
1576

    
1577
        if (f->bus_num > 0 && f->bus_num != bus_num) {
1578
            continue;
1579
        }
1580
        if (f->addr > 0 && f->addr != addr) {
1581
            continue;
1582
        }
1583

    
1584
        if (f->vendor_id > 0 && f->vendor_id != vendor_id) {
1585
            continue;
1586
        }
1587

    
1588
        if (f->product_id > 0 && f->product_id != product_id) {
1589
            continue;
1590
        }
1591
        /* We got a match */
1592

    
1593
        /* Already attached ? */
1594
        if (s->fd != -1) {
1595
            return 0;
1596
        }
1597
        DPRINTF("husb: auto open: bus_num %d addr %d\n", bus_num, addr);
1598

    
1599
        usb_host_open(s, bus_num, addr, port, product_name);
1600
    }
1601

    
1602
    return 0;
1603
}
1604

    
1605
static void usb_host_auto_check(void *unused)
1606
{
1607
    struct USBHostDevice *s;
1608
    int unconnected = 0;
1609

    
1610
    usb_host_scan(NULL, usb_host_auto_scan);
1611

    
1612
    QTAILQ_FOREACH(s, &hostdevs, next) {
1613
        if (s->fd == -1) {
1614
            unconnected++;
1615
        }
1616
    }
1617

    
1618
    if (unconnected == 0) {
1619
        /* nothing to watch */
1620
        if (usb_auto_timer) {
1621
            qemu_del_timer(usb_auto_timer);
1622
        }
1623
        return;
1624
    }
1625

    
1626
    if (!usb_auto_timer) {
1627
        usb_auto_timer = qemu_new_timer_ms(rt_clock, usb_host_auto_check, NULL);
1628
        if (!usb_auto_timer) {
1629
            return;
1630
        }
1631
    }
1632
    qemu_mod_timer(usb_auto_timer, qemu_get_clock_ms(rt_clock) + 2000);
1633
}
1634

    
1635
/*
1636
 * Autoconnect filter
1637
 * Format:
1638
 *    auto:bus:dev[:vid:pid]
1639
 *    auto:bus.dev[:vid:pid]
1640
 *
1641
 *    bus  - bus number    (dec, * means any)
1642
 *    dev  - device number (dec, * means any)
1643
 *    vid  - vendor id     (hex, * means any)
1644
 *    pid  - product id    (hex, * means any)
1645
 *
1646
 *    See 'lsusb' output.
1647
 */
1648
static int parse_filter(const char *spec, struct USBAutoFilter *f)
1649
{
1650
    enum { BUS, DEV, VID, PID, DONE };
1651
    const char *p = spec;
1652
    int i;
1653

    
1654
    f->bus_num    = 0;
1655
    f->addr       = 0;
1656
    f->vendor_id  = 0;
1657
    f->product_id = 0;
1658

    
1659
    for (i = BUS; i < DONE; i++) {
1660
        p = strpbrk(p, ":.");
1661
        if (!p) {
1662
            break;
1663
        }
1664
        p++;
1665

    
1666
        if (*p == '*') {
1667
            continue;
1668
        }
1669
        switch(i) {
1670
        case BUS: f->bus_num = strtol(p, NULL, 10);    break;
1671
        case DEV: f->addr    = strtol(p, NULL, 10);    break;
1672
        case VID: f->vendor_id  = strtol(p, NULL, 16); break;
1673
        case PID: f->product_id = strtol(p, NULL, 16); break;
1674
        }
1675
    }
1676

    
1677
    if (i < DEV) {
1678
        fprintf(stderr, "husb: invalid auto filter spec %s\n", spec);
1679
        return -1;
1680
    }
1681

    
1682
    return 0;
1683
}
1684

    
1685
/**********************/
1686
/* USB host device info */
1687

    
1688
struct usb_class_info {
1689
    int class;
1690
    const char *class_name;
1691
};
1692

    
1693
static const struct usb_class_info usb_class_info[] = {
1694
    { USB_CLASS_AUDIO, "Audio"},
1695
    { USB_CLASS_COMM, "Communication"},
1696
    { USB_CLASS_HID, "HID"},
1697
    { USB_CLASS_HUB, "Hub" },
1698
    { USB_CLASS_PHYSICAL, "Physical" },
1699
    { USB_CLASS_PRINTER, "Printer" },
1700
    { USB_CLASS_MASS_STORAGE, "Storage" },
1701
    { USB_CLASS_CDC_DATA, "Data" },
1702
    { USB_CLASS_APP_SPEC, "Application Specific" },
1703
    { USB_CLASS_VENDOR_SPEC, "Vendor Specific" },
1704
    { USB_CLASS_STILL_IMAGE, "Still Image" },
1705
    { USB_CLASS_CSCID, "Smart Card" },
1706
    { USB_CLASS_CONTENT_SEC, "Content Security" },
1707
    { -1, NULL }
1708
};
1709

    
1710
static const char *usb_class_str(uint8_t class)
1711
{
1712
    const struct usb_class_info *p;
1713
    for(p = usb_class_info; p->class != -1; p++) {
1714
        if (p->class == class) {
1715
            break;
1716
        }
1717
    }
1718
    return p->class_name;
1719
}
1720

    
1721
static void usb_info_device(Monitor *mon, int bus_num, int addr, char *port,
1722
                            int class_id, int vendor_id, int product_id,
1723
                            const char *product_name,
1724
                            int speed)
1725
{
1726
    const char *class_str, *speed_str;
1727

    
1728
    switch(speed) {
1729
    case USB_SPEED_LOW:
1730
        speed_str = "1.5";
1731
        break;
1732
    case USB_SPEED_FULL:
1733
        speed_str = "12";
1734
        break;
1735
    case USB_SPEED_HIGH:
1736
        speed_str = "480";
1737
        break;
1738
    default:
1739
        speed_str = "?";
1740
        break;
1741
    }
1742

    
1743
    monitor_printf(mon, "  Bus %d, Addr %d, Port %s, Speed %s Mb/s\n",
1744
                   bus_num, addr, port, speed_str);
1745
    class_str = usb_class_str(class_id);
1746
    if (class_str) {
1747
        monitor_printf(mon, "    %s:", class_str);
1748
    } else {
1749
        monitor_printf(mon, "    Class %02x:", class_id);
1750
    }
1751
    monitor_printf(mon, " USB device %04x:%04x", vendor_id, product_id);
1752
    if (product_name[0] != '\0') {
1753
        monitor_printf(mon, ", %s", product_name);
1754
    }
1755
    monitor_printf(mon, "\n");
1756
}
1757

    
1758
static int usb_host_info_device(void *opaque, int bus_num, int addr,
1759
                                char *path, int class_id,
1760
                                int vendor_id, int product_id,
1761
                                const char *product_name,
1762
                                int speed)
1763
{
1764
    Monitor *mon = opaque;
1765

    
1766
    usb_info_device(mon, bus_num, addr, path, class_id, vendor_id, product_id,
1767
                    product_name, speed);
1768
    return 0;
1769
}
1770

    
1771
static void dec2str(int val, char *str, size_t size)
1772
{
1773
    if (val == 0) {
1774
        snprintf(str, size, "*");
1775
    } else {
1776
        snprintf(str, size, "%d", val);
1777
    }
1778
}
1779

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

    
1789
void usb_host_info(Monitor *mon)
1790
{
1791
    struct USBAutoFilter *f;
1792
    struct USBHostDevice *s;
1793

    
1794
    usb_host_scan(mon, usb_host_info_device);
1795

    
1796
    if (QTAILQ_EMPTY(&hostdevs)) {
1797
        return;
1798
    }
1799

    
1800
    monitor_printf(mon, "  Auto filters:\n");
1801
    QTAILQ_FOREACH(s, &hostdevs, next) {
1802
        char bus[10], addr[10], vid[10], pid[10];
1803
        f = &s->match;
1804
        dec2str(f->bus_num, bus, sizeof(bus));
1805
        dec2str(f->addr, addr, sizeof(addr));
1806
        hex2str(f->vendor_id, vid, sizeof(vid));
1807
        hex2str(f->product_id, pid, sizeof(pid));
1808
        monitor_printf(mon, "    Device %s.%s ID %s:%s\n",
1809
                       bus, addr, vid, pid);
1810
    }
1811
}