Statistics
| Branch: | Revision:

root / usb-linux.c @ ed3a328d

History | View | Annotate | Download (44.8 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
struct usb_ctrlrequest {
58
    uint8_t bRequestType;
59
    uint8_t bRequest;
60
    uint16_t wValue;
61
    uint16_t wIndex;
62
    uint16_t wLength;
63
};
64

    
65
typedef int USBScanFunc(void *opaque, int bus_num, int addr, int devpath,
66
                        int class_id, int vendor_id, int product_id,
67
                        const char *product_name, int speed);
68

    
69
//#define DEBUG
70

    
71
#ifdef DEBUG
72
#define DPRINTF printf
73
#else
74
#define DPRINTF(...)
75
#endif
76

    
77
#define USBDBG_DEVOPENED "husb: opened %s/devices\n"
78

    
79
#define USBPROCBUS_PATH "/proc/bus/usb"
80
#define PRODUCT_NAME_SZ 32
81
#define MAX_ENDPOINTS 16
82
#define USBDEVBUS_PATH "/dev/bus/usb"
83
#define USBSYSBUS_PATH "/sys/bus/usb"
84

    
85
static char *usb_host_device_path;
86

    
87
#define USB_FS_NONE 0
88
#define USB_FS_PROC 1
89
#define USB_FS_DEV 2
90
#define USB_FS_SYS 3
91

    
92
static int usb_fs_type;
93

    
94
/* endpoint association data */
95
struct endp_data {
96
    uint8_t type;
97
    uint8_t halted;
98
};
99

    
100
enum {
101
    CTRL_STATE_IDLE = 0,
102
    CTRL_STATE_SETUP,
103
    CTRL_STATE_DATA,
104
    CTRL_STATE_ACK
105
};
106

    
107
/*
108
 * Control transfer state.
109
 * Note that 'buffer' _must_ follow 'req' field because
110
 * we need contiguous buffer when we submit control URB.
111
 */
112
struct ctrl_struct {
113
    uint16_t len;
114
    uint16_t offset;
115
    uint8_t  state;
116
    struct   usb_ctrlrequest req;
117
    uint8_t  buffer[8192];
118
};
119

    
120
struct USBAutoFilter {
121
    uint32_t bus_num;
122
    uint32_t addr;
123
    uint32_t vendor_id;
124
    uint32_t product_id;
125
};
126

    
127
typedef struct USBHostDevice {
128
    USBDevice dev;
129
    int       fd;
130

    
131
    uint8_t   descr[1024];
132
    int       descr_len;
133
    int       configuration;
134
    int       ninterfaces;
135
    int       closing;
136
    Notifier  exit;
137

    
138
    struct ctrl_struct ctrl;
139
    struct endp_data endp_table[MAX_ENDPOINTS];
140

    
141
    /* Host side address */
142
    int bus_num;
143
    int addr;
144
    int devpath;
145
    struct USBAutoFilter match;
146

    
147
    QTAILQ_ENTRY(USBHostDevice) next;
148
} USBHostDevice;
149

    
150
static QTAILQ_HEAD(, USBHostDevice) hostdevs = QTAILQ_HEAD_INITIALIZER(hostdevs);
151

    
152
static int usb_host_close(USBHostDevice *dev);
153
static int parse_filter(const char *spec, struct USBAutoFilter *f);
154
static void usb_host_auto_check(void *unused);
155
static int usb_host_read_file(char *line, size_t line_size,
156
                            const char *device_file, const char *device_name);
157

    
158
static int is_isoc(USBHostDevice *s, int ep)
159
{
160
    return s->endp_table[ep - 1].type == USBDEVFS_URB_TYPE_ISO;
161
}
162

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

    
168
static void clear_halt(USBHostDevice *s, int ep)
169
{
170
    s->endp_table[ep - 1].halted = 0;
171
}
172

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

    
178
/*
179
 * Async URB state.
180
 * We always allocate one isoc descriptor even for bulk transfers
181
 * to simplify allocation and casts.
182
 */
183
typedef struct AsyncURB
184
{
185
    struct usbdevfs_urb urb;
186
    struct usbdevfs_iso_packet_desc isocpd;
187

    
188
    USBPacket     *packet;
189
    USBHostDevice *hdev;
190
} AsyncURB;
191

    
192
static AsyncURB *async_alloc(void)
193
{
194
    return (AsyncURB *) qemu_mallocz(sizeof(AsyncURB));
195
}
196

    
197
static void async_free(AsyncURB *aurb)
198
{
199
    qemu_free(aurb);
200
}
201

    
202
static void async_complete_ctrl(USBHostDevice *s, USBPacket *p)
203
{
204
    switch(s->ctrl.state) {
205
    case CTRL_STATE_SETUP:
206
        if (p->len < s->ctrl.len)
207
            s->ctrl.len = p->len;
208
        s->ctrl.state = CTRL_STATE_DATA;
209
        p->len = 8;
210
        break;
211

    
212
    case CTRL_STATE_ACK:
213
        s->ctrl.state = CTRL_STATE_IDLE;
214
        p->len = 0;
215
        break;
216

    
217
    default:
218
        break;
219
    }
220
}
221

    
222
static void async_complete(void *opaque)
223
{
224
    USBHostDevice *s = opaque;
225
    AsyncURB *aurb;
226

    
227
    while (1) {
228
        USBPacket *p;
229

    
230
        int r = ioctl(s->fd, USBDEVFS_REAPURBNDELAY, &aurb);
231
        if (r < 0) {
232
            if (errno == EAGAIN) {
233
                return;
234
            }
235
            if (errno == ENODEV && !s->closing) {
236
                printf("husb: device %d.%d disconnected\n",
237
                       s->bus_num, s->addr);
238
                usb_host_close(s);
239
                usb_host_auto_check(NULL);
240
                return;
241
            }
242

    
243
            DPRINTF("husb: async. reap urb failed errno %d\n", errno);
244
            return;
245
        }
246

    
247
        p = aurb->packet;
248

    
249
        DPRINTF("husb: async completed. aurb %p status %d alen %d\n",
250
                aurb, aurb->urb.status, aurb->urb.actual_length);
251

    
252
        if (p) {
253
            switch (aurb->urb.status) {
254
            case 0:
255
                p->len = aurb->urb.actual_length;
256
                if (aurb->urb.type == USBDEVFS_URB_TYPE_CONTROL) {
257
                    async_complete_ctrl(s, p);
258
                }
259
                break;
260

    
261
            case -EPIPE:
262
                set_halt(s, p->devep);
263
                p->len = USB_RET_STALL;
264
                break;
265

    
266
            default:
267
                p->len = USB_RET_NAK;
268
                break;
269
            }
270

    
271
            usb_packet_complete(p);
272
        }
273

    
274
        async_free(aurb);
275
    }
276
}
277

    
278
static void async_cancel(USBPacket *unused, void *opaque)
279
{
280
    AsyncURB *aurb = opaque;
281
    USBHostDevice *s = aurb->hdev;
282

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

    
285
    /* Mark it as dead (see async_complete above) */
286
    aurb->packet = NULL;
287

    
288
    int r = ioctl(s->fd, USBDEVFS_DISCARDURB, aurb);
289
    if (r < 0) {
290
        DPRINTF("husb: async. discard urb failed errno %d\n", errno);
291
    }
292
}
293

    
294
static int usb_host_claim_interfaces(USBHostDevice *dev, int configuration)
295
{
296
    int dev_descr_len, config_descr_len;
297
    int interface, nb_interfaces;
298
    int ret, i;
299

    
300
    if (configuration == 0) /* address state - ignore */
301
        return 1;
302

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

    
305
    i = 0;
306
    dev_descr_len = dev->descr[0];
307
    if (dev_descr_len > dev->descr_len) {
308
        goto fail;
309
    }
310

    
311
    i += dev_descr_len;
312
    while (i < dev->descr_len) {
313
        DPRINTF("husb: i is %d, descr_len is %d, dl %d, dt %d\n",
314
                i, dev->descr_len,
315
               dev->descr[i], dev->descr[i+1]);
316

    
317
        if (dev->descr[i+1] != USB_DT_CONFIG) {
318
            i += dev->descr[i];
319
            continue;
320
        }
321
        config_descr_len = dev->descr[i];
322

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

    
325
        if (configuration < 0 || configuration == dev->descr[i + 5]) {
326
            configuration = dev->descr[i + 5];
327
            break;
328
        }
329

    
330
        i += config_descr_len;
331
    }
332

    
333
    if (i >= dev->descr_len) {
334
        fprintf(stderr,
335
                "husb: update iface failed. no matching configuration\n");
336
        goto fail;
337
    }
338
    nb_interfaces = dev->descr[i + 4];
339

    
340
#ifdef USBDEVFS_DISCONNECT
341
    /* earlier Linux 2.4 do not support that */
342
    {
343
        struct usbdevfs_ioctl ctrl;
344
        for (interface = 0; interface < nb_interfaces; interface++) {
345
            ctrl.ioctl_code = USBDEVFS_DISCONNECT;
346
            ctrl.ifno = interface;
347
            ctrl.data = 0;
348
            ret = ioctl(dev->fd, USBDEVFS_IOCTL, &ctrl);
349
            if (ret < 0 && errno != ENODATA) {
350
                perror("USBDEVFS_DISCONNECT");
351
                goto fail;
352
            }
353
        }
354
    }
355
#endif
356

    
357
    /* XXX: only grab if all interfaces are free */
358
    for (interface = 0; interface < nb_interfaces; interface++) {
359
        ret = ioctl(dev->fd, USBDEVFS_CLAIMINTERFACE, &interface);
360
        if (ret < 0) {
361
            if (errno == EBUSY) {
362
                printf("husb: update iface. device already grabbed\n");
363
            } else {
364
                perror("husb: failed to claim interface");
365
            }
366
        fail:
367
            return 0;
368
        }
369
    }
370

    
371
    printf("husb: %d interfaces claimed for configuration %d\n",
372
           nb_interfaces, configuration);
373

    
374
    dev->ninterfaces   = nb_interfaces;
375
    dev->configuration = configuration;
376
    return 1;
377
}
378

    
379
static int usb_host_release_interfaces(USBHostDevice *s)
380
{
381
    int ret, i;
382

    
383
    DPRINTF("husb: releasing interfaces\n");
384

    
385
    for (i = 0; i < s->ninterfaces; i++) {
386
        ret = ioctl(s->fd, USBDEVFS_RELEASEINTERFACE, &i);
387
        if (ret < 0) {
388
            perror("husb: failed to release interface");
389
            return 0;
390
        }
391
    }
392

    
393
    return 1;
394
}
395

    
396
static void usb_host_handle_reset(USBDevice *dev)
397
{
398
    USBHostDevice *s = DO_UPCAST(USBHostDevice, dev, dev);
399

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

    
402
    ioctl(s->fd, USBDEVFS_RESET);
403

    
404
    usb_host_claim_interfaces(s, s->configuration);
405
}
406

    
407
static void usb_host_handle_destroy(USBDevice *dev)
408
{
409
    USBHostDevice *s = (USBHostDevice *)dev;
410

    
411
    usb_host_close(s);
412
    QTAILQ_REMOVE(&hostdevs, s, next);
413
    qemu_remove_exit_notifier(&s->exit);
414
}
415

    
416
static int usb_linux_update_endp_table(USBHostDevice *s);
417

    
418
static int usb_host_handle_data(USBHostDevice *s, USBPacket *p)
419
{
420
    struct usbdevfs_urb *urb;
421
    AsyncURB *aurb;
422
    int ret;
423

    
424
    aurb = async_alloc();
425
    aurb->hdev   = s;
426
    aurb->packet = p;
427

    
428
    urb = &aurb->urb;
429

    
430
    if (p->pid == USB_TOKEN_IN) {
431
        urb->endpoint = p->devep | 0x80;
432
    } else {
433
        urb->endpoint = p->devep;
434
    }
435

    
436
    if (is_halted(s, p->devep)) {
437
        ret = ioctl(s->fd, USBDEVFS_CLEAR_HALT, &urb->endpoint);
438
        if (ret < 0) {
439
            DPRINTF("husb: failed to clear halt. ep 0x%x errno %d\n",
440
                   urb->endpoint, errno);
441
            return USB_RET_NAK;
442
        }
443
        clear_halt(s, p->devep);
444
    }
445

    
446
    urb->buffer        = p->data;
447
    urb->buffer_length = p->len;
448

    
449
    if (is_isoc(s, p->devep)) {
450
        /* Setup ISOC transfer */
451
        urb->type     = USBDEVFS_URB_TYPE_ISO;
452
        urb->flags    = USBDEVFS_URB_ISO_ASAP;
453
        urb->number_of_packets = 1;
454
        urb->iso_frame_desc[0].length = p->len;
455
    } else {
456
        /* Setup bulk transfer */
457
        urb->type     = USBDEVFS_URB_TYPE_BULK;
458
    }
459

    
460
    urb->usercontext = s;
461

    
462
    ret = ioctl(s->fd, USBDEVFS_SUBMITURB, urb);
463

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

    
467
    if (ret < 0) {
468
        DPRINTF("husb: submit failed. errno %d\n", errno);
469
        async_free(aurb);
470

    
471
        switch(errno) {
472
        case ETIMEDOUT:
473
            return USB_RET_NAK;
474
        case EPIPE:
475
        default:
476
            return USB_RET_STALL;
477
        }
478
    }
479

    
480
    usb_defer_packet(p, async_cancel, aurb);
481
    return USB_RET_ASYNC;
482
}
483

    
484
static int ctrl_error(void)
485
{
486
    if (errno == ETIMEDOUT) {
487
        return USB_RET_NAK;
488
    } else {
489
        return USB_RET_STALL;
490
    }
491
}
492

    
493
static int usb_host_set_address(USBHostDevice *s, int addr)
494
{
495
    DPRINTF("husb: ctrl set addr %u\n", addr);
496
    s->dev.addr = addr;
497
    return 0;
498
}
499

    
500
static int usb_host_set_config(USBHostDevice *s, int config)
501
{
502
    usb_host_release_interfaces(s);
503

    
504
    int ret = ioctl(s->fd, USBDEVFS_SETCONFIGURATION, &config);
505

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

    
508
    if (ret < 0) {
509
        return ctrl_error();
510
    }
511
    usb_host_claim_interfaces(s, config);
512
    return 0;
513
}
514

    
515
static int usb_host_set_interface(USBHostDevice *s, int iface, int alt)
516
{
517
    struct usbdevfs_setinterface si;
518
    int ret;
519

    
520
    si.interface  = iface;
521
    si.altsetting = alt;
522
    ret = ioctl(s->fd, USBDEVFS_SETINTERFACE, &si);
523

    
524
    DPRINTF("husb: ctrl set iface %d altset %d ret %d errno %d\n",
525
            iface, alt, ret, errno);
526

    
527
    if (ret < 0) {
528
        return ctrl_error();
529
    }
530
    usb_linux_update_endp_table(s);
531
    return 0;
532
}
533

    
534
static int usb_host_handle_control(USBHostDevice *s, USBPacket *p)
535
{
536
    struct usbdevfs_urb *urb;
537
    AsyncURB *aurb;
538
    int ret, value, index;
539
    int buffer_len;
540

    
541
    /*
542
     * Process certain standard device requests.
543
     * These are infrequent and are processed synchronously.
544
     */
545
    value = le16_to_cpu(s->ctrl.req.wValue);
546
    index = le16_to_cpu(s->ctrl.req.wIndex);
547

    
548
    DPRINTF("husb: ctrl type 0x%x req 0x%x val 0x%x index %u len %u\n",
549
            s->ctrl.req.bRequestType, s->ctrl.req.bRequest, value, index,
550
            s->ctrl.len);
551

    
552
    if (s->ctrl.req.bRequestType == 0) {
553
        switch (s->ctrl.req.bRequest) {
554
        case USB_REQ_SET_ADDRESS:
555
            return usb_host_set_address(s, value);
556

    
557
        case USB_REQ_SET_CONFIGURATION:
558
            return usb_host_set_config(s, value & 0xff);
559
        }
560
    }
561

    
562
    if (s->ctrl.req.bRequestType == 1 &&
563
                  s->ctrl.req.bRequest == USB_REQ_SET_INTERFACE) {
564
        return usb_host_set_interface(s, index, value);
565
    }
566

    
567
    /* The rest are asynchronous */
568

    
569
    buffer_len = 8 + s->ctrl.len;
570
    if (buffer_len > sizeof(s->ctrl.buffer)) {
571
        fprintf(stderr, "husb: ctrl buffer too small (%u > %zu)\n",
572
                buffer_len, sizeof(s->ctrl.buffer));
573
        return USB_RET_STALL;
574
    }
575

    
576
    aurb = async_alloc();
577
    aurb->hdev   = s;
578
    aurb->packet = p;
579

    
580
    /*
581
     * Setup ctrl transfer.
582
     *
583
     * s->ctrl is laid out such that data buffer immediately follows
584
     * 'req' struct which is exactly what usbdevfs expects.
585
     */
586
    urb = &aurb->urb;
587

    
588
    urb->type     = USBDEVFS_URB_TYPE_CONTROL;
589
    urb->endpoint = p->devep;
590

    
591
    urb->buffer        = &s->ctrl.req;
592
    urb->buffer_length = buffer_len;
593

    
594
    urb->usercontext = s;
595

    
596
    ret = ioctl(s->fd, USBDEVFS_SUBMITURB, urb);
597

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

    
600
    if (ret < 0) {
601
        DPRINTF("husb: submit failed. errno %d\n", errno);
602
        async_free(aurb);
603

    
604
        switch(errno) {
605
        case ETIMEDOUT:
606
            return USB_RET_NAK;
607
        case EPIPE:
608
        default:
609
            return USB_RET_STALL;
610
        }
611
    }
612

    
613
    usb_defer_packet(p, async_cancel, aurb);
614
    return USB_RET_ASYNC;
615
}
616

    
617
static int do_token_setup(USBDevice *dev, USBPacket *p)
618
{
619
    USBHostDevice *s = (USBHostDevice *) dev;
620
    int ret = 0;
621

    
622
    if (p->len != 8) {
623
        return USB_RET_STALL;
624
    }
625

    
626
    memcpy(&s->ctrl.req, p->data, 8);
627
    s->ctrl.len    = le16_to_cpu(s->ctrl.req.wLength);
628
    s->ctrl.offset = 0;
629
    s->ctrl.state  = CTRL_STATE_SETUP;
630

    
631
    if (s->ctrl.req.bRequestType & USB_DIR_IN) {
632
        ret = usb_host_handle_control(s, p);
633
        if (ret < 0) {
634
            return ret;
635
        }
636

    
637
        if (ret < s->ctrl.len) {
638
            s->ctrl.len = ret;
639
        }
640
        s->ctrl.state = CTRL_STATE_DATA;
641
    } else {
642
        if (s->ctrl.len == 0) {
643
            s->ctrl.state = CTRL_STATE_ACK;
644
        } else {
645
            s->ctrl.state = CTRL_STATE_DATA;
646
        }
647
    }
648

    
649
    return ret;
650
}
651

    
652
static int do_token_in(USBDevice *dev, USBPacket *p)
653
{
654
    USBHostDevice *s = (USBHostDevice *) dev;
655
    int ret = 0;
656

    
657
    if (p->devep != 0) {
658
        return usb_host_handle_data(s, p);
659
    }
660

    
661
    switch(s->ctrl.state) {
662
    case CTRL_STATE_ACK:
663
        if (!(s->ctrl.req.bRequestType & USB_DIR_IN)) {
664
            ret = usb_host_handle_control(s, p);
665
            if (ret == USB_RET_ASYNC) {
666
                return USB_RET_ASYNC;
667
            }
668
            s->ctrl.state = CTRL_STATE_IDLE;
669
            return ret > 0 ? 0 : ret;
670
        }
671

    
672
        return 0;
673

    
674
    case CTRL_STATE_DATA:
675
        if (s->ctrl.req.bRequestType & USB_DIR_IN) {
676
            int len = s->ctrl.len - s->ctrl.offset;
677
            if (len > p->len) {
678
                len = p->len;
679
            }
680
            memcpy(p->data, s->ctrl.buffer + s->ctrl.offset, len);
681
            s->ctrl.offset += len;
682
            if (s->ctrl.offset >= s->ctrl.len) {
683
                s->ctrl.state = CTRL_STATE_ACK;
684
            }
685
            return len;
686
        }
687

    
688
        s->ctrl.state = CTRL_STATE_IDLE;
689
        return USB_RET_STALL;
690

    
691
    default:
692
        return USB_RET_STALL;
693
    }
694
}
695

    
696
static int do_token_out(USBDevice *dev, USBPacket *p)
697
{
698
    USBHostDevice *s = (USBHostDevice *) dev;
699

    
700
    if (p->devep != 0) {
701
        return usb_host_handle_data(s, p);
702
    }
703

    
704
    switch(s->ctrl.state) {
705
    case CTRL_STATE_ACK:
706
        if (s->ctrl.req.bRequestType & USB_DIR_IN) {
707
            s->ctrl.state = CTRL_STATE_IDLE;
708
            /* transfer OK */
709
        } else {
710
            /* ignore additional output */
711
        }
712
        return 0;
713

    
714
    case CTRL_STATE_DATA:
715
        if (!(s->ctrl.req.bRequestType & USB_DIR_IN)) {
716
            int len = s->ctrl.len - s->ctrl.offset;
717
            if (len > p->len) {
718
                len = p->len;
719
            }
720
            memcpy(s->ctrl.buffer + s->ctrl.offset, p->data, len);
721
            s->ctrl.offset += len;
722
            if (s->ctrl.offset >= s->ctrl.len) {
723
                s->ctrl.state = CTRL_STATE_ACK;
724
            }
725
            return len;
726
        }
727

    
728
        s->ctrl.state = CTRL_STATE_IDLE;
729
        return USB_RET_STALL;
730

    
731
    default:
732
        return USB_RET_STALL;
733
    }
734
}
735

    
736
/*
737
 * Packet handler.
738
 * Called by the HC (host controller).
739
 *
740
 * Returns length of the transaction or one of the USB_RET_XXX codes.
741
 */
742
static int usb_host_handle_packet(USBDevice *s, USBPacket *p)
743
{
744
    switch(p->pid) {
745
    case USB_MSG_ATTACH:
746
        s->state = USB_STATE_ATTACHED;
747
        return 0;
748

    
749
    case USB_MSG_DETACH:
750
        s->state = USB_STATE_NOTATTACHED;
751
        return 0;
752

    
753
    case USB_MSG_RESET:
754
        s->remote_wakeup = 0;
755
        s->addr = 0;
756
        s->state = USB_STATE_DEFAULT;
757
        s->info->handle_reset(s);
758
        return 0;
759
    }
760

    
761
    /* Rest of the PIDs must match our address */
762
    if (s->state < USB_STATE_DEFAULT || p->devaddr != s->addr) {
763
        return USB_RET_NODEV;
764
    }
765

    
766
    switch (p->pid) {
767
    case USB_TOKEN_SETUP:
768
        return do_token_setup(s, p);
769

    
770
    case USB_TOKEN_IN:
771
        return do_token_in(s, p);
772

    
773
    case USB_TOKEN_OUT:
774
        return do_token_out(s, p);
775

    
776
    default:
777
        return USB_RET_STALL;
778
    }
779
}
780

    
781
static int usb_linux_get_configuration(USBHostDevice *s)
782
{
783
    uint8_t configuration;
784
    struct usb_ctrltransfer ct;
785
    int ret;
786

    
787
    if (usb_fs_type == USB_FS_SYS) {
788
        char device_name[32], line[1024];
789
        int configuration;
790

    
791
        sprintf(device_name, "%d-%d", s->bus_num, s->devpath);
792

    
793
        if (!usb_host_read_file(line, sizeof(line), "bConfigurationValue",
794
                                device_name)) {
795
            goto usbdevfs;
796
        }
797
        if (sscanf(line, "%d", &configuration) != 1) {
798
            goto usbdevfs;
799
        }
800
        return configuration;
801
    }
802

    
803
usbdevfs:
804
    ct.bRequestType = USB_DIR_IN;
805
    ct.bRequest = USB_REQ_GET_CONFIGURATION;
806
    ct.wValue = 0;
807
    ct.wIndex = 0;
808
    ct.wLength = 1;
809
    ct.data = &configuration;
810
    ct.timeout = 50;
811

    
812
    ret = ioctl(s->fd, USBDEVFS_CONTROL, &ct);
813
    if (ret < 0) {
814
        perror("usb_linux_get_configuration");
815
        return -1;
816
    }
817

    
818
    /* in address state */
819
    if (configuration == 0) {
820
        return -1;
821
    }
822

    
823
    return configuration;
824
}
825

    
826
static uint8_t usb_linux_get_alt_setting(USBHostDevice *s,
827
    uint8_t configuration, uint8_t interface)
828
{
829
    uint8_t alt_setting;
830
    struct usb_ctrltransfer ct;
831
    int ret;
832

    
833
    ct.bRequestType = USB_DIR_IN | USB_RECIP_INTERFACE;
834
    ct.bRequest = USB_REQ_GET_INTERFACE;
835
    ct.wValue = 0;
836
    ct.wIndex = interface;
837
    ct.wLength = 1;
838
    ct.data = &alt_setting;
839
    ct.timeout = 50;
840
    ret = ioctl(s->fd, USBDEVFS_CONTROL, &ct);
841
    if (ret < 0) {
842
        /* Assume alt 0 on error */
843
        return 0;
844
    }
845

    
846
    return alt_setting;
847
}
848

    
849
/* returns 1 on problem encountered or 0 for success */
850
static int usb_linux_update_endp_table(USBHostDevice *s)
851
{
852
    uint8_t *descriptors;
853
    uint8_t devep, type, configuration, alt_interface;
854
    int interface, length, i;
855

    
856
    i = usb_linux_get_configuration(s);
857
    if (i < 0)
858
        return 1;
859
    configuration = i;
860

    
861
    /* get the desired configuration, interface, and endpoint descriptors
862
     * from device description */
863
    descriptors = &s->descr[18];
864
    length = s->descr_len - 18;
865
    i = 0;
866

    
867
    if (descriptors[i + 1] != USB_DT_CONFIG ||
868
        descriptors[i + 5] != configuration) {
869
        DPRINTF("invalid descriptor data - configuration\n");
870
        return 1;
871
    }
872
    i += descriptors[i];
873

    
874
    while (i < length) {
875
        if (descriptors[i + 1] != USB_DT_INTERFACE ||
876
            (descriptors[i + 1] == USB_DT_INTERFACE &&
877
             descriptors[i + 4] == 0)) {
878
            i += descriptors[i];
879
            continue;
880
        }
881

    
882
        interface = descriptors[i + 2];
883
        alt_interface = usb_linux_get_alt_setting(s, configuration, interface);
884

    
885
        /* the current interface descriptor is the active interface
886
         * and has endpoints */
887
        if (descriptors[i + 3] != alt_interface) {
888
            i += descriptors[i];
889
            continue;
890
        }
891

    
892
        /* advance to the endpoints */
893
        while (i < length && descriptors[i +1] != USB_DT_ENDPOINT) {
894
            i += descriptors[i];
895
        }
896

    
897
        if (i >= length)
898
            break;
899

    
900
        while (i < length) {
901
            if (descriptors[i + 1] != USB_DT_ENDPOINT) {
902
                break;
903
            }
904

    
905
            devep = descriptors[i + 2];
906
            switch (descriptors[i + 3] & 0x3) {
907
            case 0x00:
908
                type = USBDEVFS_URB_TYPE_CONTROL;
909
                break;
910
            case 0x01:
911
                type = USBDEVFS_URB_TYPE_ISO;
912
                break;
913
            case 0x02:
914
                type = USBDEVFS_URB_TYPE_BULK;
915
                break;
916
            case 0x03:
917
                type = USBDEVFS_URB_TYPE_INTERRUPT;
918
                break;
919
            default:
920
                DPRINTF("usb_host: malformed endpoint type\n");
921
                type = USBDEVFS_URB_TYPE_BULK;
922
            }
923
            s->endp_table[(devep & 0xf) - 1].type = type;
924
            s->endp_table[(devep & 0xf) - 1].halted = 0;
925

    
926
            i += descriptors[i];
927
        }
928
    }
929
    return 0;
930
}
931

    
932
static int usb_host_open(USBHostDevice *dev, int bus_num,
933
                         int addr, int devpath, const char *prod_name)
934
{
935
    int fd = -1, ret;
936
    struct usbdevfs_connectinfo ci;
937
    char buf[1024];
938

    
939
    if (dev->fd != -1) {
940
        goto fail;
941
    }
942
    printf("husb: open device %d.%d\n", bus_num, addr);
943

    
944
    if (!usb_host_device_path) {
945
        perror("husb: USB Host Device Path not set");
946
        goto fail;
947
    }
948
    snprintf(buf, sizeof(buf), "%s/%03d/%03d", usb_host_device_path,
949
             bus_num, addr);
950
    fd = open(buf, O_RDWR | O_NONBLOCK);
951
    if (fd < 0) {
952
        perror(buf);
953
        goto fail;
954
    }
955
    DPRINTF("husb: opened %s\n", buf);
956

    
957
    dev->bus_num = bus_num;
958
    dev->addr = addr;
959
    dev->devpath = devpath;
960
    dev->fd = fd;
961

    
962
    /* read the device description */
963
    dev->descr_len = read(fd, dev->descr, sizeof(dev->descr));
964
    if (dev->descr_len <= 0) {
965
        perror("husb: reading device data failed");
966
        goto fail;
967
    }
968

    
969
#ifdef DEBUG
970
    {
971
        int x;
972
        printf("=== begin dumping device descriptor data ===\n");
973
        for (x = 0; x < dev->descr_len; x++) {
974
            printf("%02x ", dev->descr[x]);
975
        }
976
        printf("\n=== end dumping device descriptor data ===\n");
977
    }
978
#endif
979

    
980

    
981
    /*
982
     * Initial configuration is -1 which makes us claim first
983
     * available config. We used to start with 1, which does not
984
     * always work. I've seen devices where first config starts
985
     * with 2.
986
     */
987
    if (!usb_host_claim_interfaces(dev, -1)) {
988
        goto fail;
989
    }
990

    
991
    ret = ioctl(fd, USBDEVFS_CONNECTINFO, &ci);
992
    if (ret < 0) {
993
        perror("usb_host_device_open: USBDEVFS_CONNECTINFO");
994
        goto fail;
995
    }
996

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

    
999
    ret = usb_linux_update_endp_table(dev);
1000
    if (ret) {
1001
        goto fail;
1002
    }
1003

    
1004
    if (ci.slow) {
1005
        dev->dev.speed = USB_SPEED_LOW;
1006
    } else {
1007
        dev->dev.speed = USB_SPEED_HIGH;
1008
    }
1009

    
1010
    if (!prod_name || prod_name[0] == '\0') {
1011
        snprintf(dev->dev.product_desc, sizeof(dev->dev.product_desc),
1012
                 "host:%d.%d", bus_num, addr);
1013
    } else {
1014
        pstrcpy(dev->dev.product_desc, sizeof(dev->dev.product_desc),
1015
                prod_name);
1016
    }
1017

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

    
1021
    usb_device_attach(&dev->dev);
1022
    return 0;
1023

    
1024
fail:
1025
    dev->fd = -1;
1026
    if (fd != -1) {
1027
        close(fd);
1028
    }
1029
    return -1;
1030
}
1031

    
1032
static int usb_host_close(USBHostDevice *dev)
1033
{
1034
    if (dev->fd == -1) {
1035
        return -1;
1036
    }
1037

    
1038
    qemu_set_fd_handler(dev->fd, NULL, NULL, NULL);
1039
    dev->closing = 1;
1040
    async_complete(dev);
1041
    dev->closing = 0;
1042
    usb_device_detach(&dev->dev);
1043
    ioctl(dev->fd, USBDEVFS_RESET);
1044
    close(dev->fd);
1045
    dev->fd = -1;
1046
    return 0;
1047
}
1048

    
1049
static void usb_host_exit_notifier(struct Notifier* n)
1050
{
1051
    USBHostDevice *s = container_of(n, USBHostDevice, exit);
1052

    
1053
    if (s->fd != -1) {
1054
        ioctl(s->fd, USBDEVFS_RESET);
1055
    }
1056
}
1057

    
1058
static int usb_host_initfn(USBDevice *dev)
1059
{
1060
    USBHostDevice *s = DO_UPCAST(USBHostDevice, dev, dev);
1061

    
1062
    dev->auto_attach = 0;
1063
    s->fd = -1;
1064
    QTAILQ_INSERT_TAIL(&hostdevs, s, next);
1065
    s->exit.notify = usb_host_exit_notifier;
1066
    qemu_add_exit_notifier(&s->exit);
1067
    usb_host_auto_check(NULL);
1068
    return 0;
1069
}
1070

    
1071
static struct USBDeviceInfo usb_host_dev_info = {
1072
    .product_desc   = "USB Host Device",
1073
    .qdev.name      = "usb-host",
1074
    .qdev.size      = sizeof(USBHostDevice),
1075
    .init           = usb_host_initfn,
1076
    .handle_packet  = usb_host_handle_packet,
1077
    .handle_reset   = usb_host_handle_reset,
1078
    .handle_destroy = usb_host_handle_destroy,
1079
    .usbdevice_name = "host",
1080
    .usbdevice_init = usb_host_device_open,
1081
    .qdev.props     = (Property[]) {
1082
        DEFINE_PROP_UINT32("hostbus",  USBHostDevice, match.bus_num,    0),
1083
        DEFINE_PROP_UINT32("hostaddr", USBHostDevice, match.addr,       0),
1084
        DEFINE_PROP_HEX32("vendorid",  USBHostDevice, match.vendor_id,  0),
1085
        DEFINE_PROP_HEX32("productid", USBHostDevice, match.product_id, 0),
1086
        DEFINE_PROP_END_OF_LIST(),
1087
    },
1088
};
1089

    
1090
static void usb_host_register_devices(void)
1091
{
1092
    usb_qdev_register(&usb_host_dev_info);
1093
}
1094
device_init(usb_host_register_devices)
1095

    
1096
USBDevice *usb_host_device_open(const char *devname)
1097
{
1098
    struct USBAutoFilter filter;
1099
    USBDevice *dev;
1100
    char *p;
1101

    
1102
    dev = usb_create(NULL /* FIXME */, "usb-host");
1103

    
1104
    if (strstr(devname, "auto:")) {
1105
        if (parse_filter(devname, &filter) < 0) {
1106
            goto fail;
1107
        }
1108
    } else {
1109
        if ((p = strchr(devname, '.'))) {
1110
            filter.bus_num    = strtoul(devname, NULL, 0);
1111
            filter.addr       = strtoul(p + 1, NULL, 0);
1112
            filter.vendor_id  = 0;
1113
            filter.product_id = 0;
1114
        } else if ((p = strchr(devname, ':'))) {
1115
            filter.bus_num    = 0;
1116
            filter.addr       = 0;
1117
            filter.vendor_id  = strtoul(devname, NULL, 16);
1118
            filter.product_id = strtoul(p + 1, NULL, 16);
1119
        } else {
1120
            goto fail;
1121
        }
1122
    }
1123

    
1124
    qdev_prop_set_uint32(&dev->qdev, "hostbus",   filter.bus_num);
1125
    qdev_prop_set_uint32(&dev->qdev, "hostaddr",  filter.addr);
1126
    qdev_prop_set_uint32(&dev->qdev, "vendorid",  filter.vendor_id);
1127
    qdev_prop_set_uint32(&dev->qdev, "productid", filter.product_id);
1128
    qdev_init_nofail(&dev->qdev);
1129
    return dev;
1130

    
1131
fail:
1132
    qdev_free(&dev->qdev);
1133
    return NULL;
1134
}
1135

    
1136
int usb_host_device_close(const char *devname)
1137
{
1138
#if 0
1139
    char product_name[PRODUCT_NAME_SZ];
1140
    int bus_num, addr;
1141
    USBHostDevice *s;
1142

1143
    if (strstr(devname, "auto:")) {
1144
        return usb_host_auto_del(devname);
1145
    }
1146
    if (usb_host_find_device(&bus_num, &addr, product_name,
1147
                                    sizeof(product_name), devname) < 0) {
1148
        return -1;
1149
    }
1150
    s = hostdev_find(bus_num, addr);
1151
    if (s) {
1152
        usb_device_delete_addr(s->bus_num, s->dev.addr);
1153
        return 0;
1154
    }
1155
#endif
1156

    
1157
    return -1;
1158
}
1159

    
1160
static int get_tag_value(char *buf, int buf_size,
1161
                         const char *str, const char *tag,
1162
                         const char *stopchars)
1163
{
1164
    const char *p;
1165
    char *q;
1166
    p = strstr(str, tag);
1167
    if (!p) {
1168
        return -1;
1169
    }
1170
    p += strlen(tag);
1171
    while (qemu_isspace(*p)) {
1172
        p++;
1173
    }
1174
    q = buf;
1175
    while (*p != '\0' && !strchr(stopchars, *p)) {
1176
        if ((q - buf) < (buf_size - 1)) {
1177
            *q++ = *p;
1178
        }
1179
        p++;
1180
    }
1181
    *q = '\0';
1182
    return q - buf;
1183
}
1184

    
1185
/*
1186
 * Use /proc/bus/usb/devices or /dev/bus/usb/devices file to determine
1187
 * host's USB devices. This is legacy support since many distributions
1188
 * are moving to /sys/bus/usb
1189
 */
1190
static int usb_host_scan_dev(void *opaque, USBScanFunc *func)
1191
{
1192
    FILE *f = NULL;
1193
    char line[1024];
1194
    char buf[1024];
1195
    int bus_num, addr, speed, device_count, class_id, product_id, vendor_id;
1196
    char product_name[512];
1197
    int ret = 0;
1198

    
1199
    if (!usb_host_device_path) {
1200
        perror("husb: USB Host Device Path not set");
1201
        goto the_end;
1202
    }
1203
    snprintf(line, sizeof(line), "%s/devices", usb_host_device_path);
1204
    f = fopen(line, "r");
1205
    if (!f) {
1206
        perror("husb: cannot open devices file");
1207
        goto the_end;
1208
    }
1209

    
1210
    device_count = 0;
1211
    bus_num = addr = speed = class_id = product_id = vendor_id = 0;
1212
    for(;;) {
1213
        if (fgets(line, sizeof(line), f) == NULL) {
1214
            break;
1215
        }
1216
        if (strlen(line) > 0) {
1217
            line[strlen(line) - 1] = '\0';
1218
        }
1219
        if (line[0] == 'T' && line[1] == ':') {
1220
            if (device_count && (vendor_id || product_id)) {
1221
                /* New device.  Add the previously discovered device.  */
1222
                ret = func(opaque, bus_num, addr, 0, class_id, vendor_id,
1223
                           product_id, product_name, speed);
1224
                if (ret) {
1225
                    goto the_end;
1226
                }
1227
            }
1228
            if (get_tag_value(buf, sizeof(buf), line, "Bus=", " ") < 0) {
1229
                goto fail;
1230
            }
1231
            bus_num = atoi(buf);
1232
            if (get_tag_value(buf, sizeof(buf), line, "Dev#=", " ") < 0) {
1233
                goto fail;
1234
            }
1235
            addr = atoi(buf);
1236
            if (get_tag_value(buf, sizeof(buf), line, "Spd=", " ") < 0) {
1237
                goto fail;
1238
            }
1239
            if (!strcmp(buf, "480")) {
1240
                speed = USB_SPEED_HIGH;
1241
            } else if (!strcmp(buf, "1.5")) {
1242
                speed = USB_SPEED_LOW;
1243
            } else {
1244
                speed = USB_SPEED_FULL;
1245
            }
1246
            product_name[0] = '\0';
1247
            class_id = 0xff;
1248
            device_count++;
1249
            product_id = 0;
1250
            vendor_id = 0;
1251
        } else if (line[0] == 'P' && line[1] == ':') {
1252
            if (get_tag_value(buf, sizeof(buf), line, "Vendor=", " ") < 0) {
1253
                goto fail;
1254
            }
1255
            vendor_id = strtoul(buf, NULL, 16);
1256
            if (get_tag_value(buf, sizeof(buf), line, "ProdID=", " ") < 0) {
1257
                goto fail;
1258
            }
1259
            product_id = strtoul(buf, NULL, 16);
1260
        } else if (line[0] == 'S' && line[1] == ':') {
1261
            if (get_tag_value(buf, sizeof(buf), line, "Product=", "") < 0) {
1262
                goto fail;
1263
            }
1264
            pstrcpy(product_name, sizeof(product_name), buf);
1265
        } else if (line[0] == 'D' && line[1] == ':') {
1266
            if (get_tag_value(buf, sizeof(buf), line, "Cls=", " (") < 0) {
1267
                goto fail;
1268
            }
1269
            class_id = strtoul(buf, NULL, 16);
1270
        }
1271
    fail: ;
1272
    }
1273
    if (device_count && (vendor_id || product_id)) {
1274
        /* Add the last device.  */
1275
        ret = func(opaque, bus_num, addr, 0, class_id, vendor_id,
1276
                   product_id, product_name, speed);
1277
    }
1278
 the_end:
1279
    if (f) {
1280
        fclose(f);
1281
    }
1282
    return ret;
1283
}
1284

    
1285
/*
1286
 * Read sys file-system device file
1287
 *
1288
 * @line address of buffer to put file contents in
1289
 * @line_size size of line
1290
 * @device_file path to device file (printf format string)
1291
 * @device_name device being opened (inserted into device_file)
1292
 *
1293
 * @return 0 failed, 1 succeeded ('line' contains data)
1294
 */
1295
static int usb_host_read_file(char *line, size_t line_size,
1296
                              const char *device_file, const char *device_name)
1297
{
1298
    FILE *f;
1299
    int ret = 0;
1300
    char filename[PATH_MAX];
1301

    
1302
    snprintf(filename, PATH_MAX, USBSYSBUS_PATH "/devices/%s/%s", device_name,
1303
             device_file);
1304
    f = fopen(filename, "r");
1305
    if (f) {
1306
        ret = fgets(line, line_size, f) != NULL;
1307
        fclose(f);
1308
    }
1309

    
1310
    return ret;
1311
}
1312

    
1313
/*
1314
 * Use /sys/bus/usb/devices/ directory to determine host's USB
1315
 * devices.
1316
 *
1317
 * This code is based on Robert Schiele's original patches posted to
1318
 * the Novell bug-tracker https://bugzilla.novell.com/show_bug.cgi?id=241950
1319
 */
1320
static int usb_host_scan_sys(void *opaque, USBScanFunc *func)
1321
{
1322
    DIR *dir = NULL;
1323
    char line[1024];
1324
    int bus_num, addr, devpath, speed, class_id, product_id, vendor_id;
1325
    int ret = 0;
1326
    char product_name[512];
1327
    struct dirent *de;
1328

    
1329
    dir = opendir(USBSYSBUS_PATH "/devices");
1330
    if (!dir) {
1331
        perror("husb: cannot open devices directory");
1332
        goto the_end;
1333
    }
1334

    
1335
    while ((de = readdir(dir))) {
1336
        if (de->d_name[0] != '.' && !strchr(de->d_name, ':')) {
1337
            char *tmpstr = de->d_name;
1338
            if (!strncmp(de->d_name, "usb", 3)) {
1339
                tmpstr += 3;
1340
            }
1341
            if (sscanf(tmpstr, "%d-%d", &bus_num, &devpath) < 1) {
1342
                goto the_end;
1343
            }
1344

    
1345
            if (!usb_host_read_file(line, sizeof(line), "devnum", de->d_name)) {
1346
                goto the_end;
1347
            }
1348
            if (sscanf(line, "%d", &addr) != 1) {
1349
                goto the_end;
1350
            }
1351
            if (!usb_host_read_file(line, sizeof(line), "bDeviceClass",
1352
                                    de->d_name)) {
1353
                goto the_end;
1354
            }
1355
            if (sscanf(line, "%x", &class_id) != 1) {
1356
                goto the_end;
1357
            }
1358

    
1359
            if (!usb_host_read_file(line, sizeof(line), "idVendor",
1360
                                    de->d_name)) {
1361
                goto the_end;
1362
            }
1363
            if (sscanf(line, "%x", &vendor_id) != 1) {
1364
                goto the_end;
1365
            }
1366
            if (!usb_host_read_file(line, sizeof(line), "idProduct",
1367
                                    de->d_name)) {
1368
                goto the_end;
1369
            }
1370
            if (sscanf(line, "%x", &product_id) != 1) {
1371
                goto the_end;
1372
            }
1373
            if (!usb_host_read_file(line, sizeof(line), "product",
1374
                                    de->d_name)) {
1375
                *product_name = 0;
1376
            } else {
1377
                if (strlen(line) > 0) {
1378
                    line[strlen(line) - 1] = '\0';
1379
                }
1380
                pstrcpy(product_name, sizeof(product_name), line);
1381
            }
1382

    
1383
            if (!usb_host_read_file(line, sizeof(line), "speed", de->d_name)) {
1384
                goto the_end;
1385
            }
1386
            if (!strcmp(line, "480\n")) {
1387
                speed = USB_SPEED_HIGH;
1388
            } else if (!strcmp(line, "1.5\n")) {
1389
                speed = USB_SPEED_LOW;
1390
            } else {
1391
                speed = USB_SPEED_FULL;
1392
            }
1393

    
1394
            ret = func(opaque, bus_num, addr, devpath, class_id, vendor_id,
1395
                       product_id, product_name, speed);
1396
            if (ret) {
1397
                goto the_end;
1398
            }
1399
        }
1400
    }
1401
 the_end:
1402
    if (dir) {
1403
        closedir(dir);
1404
    }
1405
    return ret;
1406
}
1407

    
1408
/*
1409
 * Determine how to access the host's USB devices and call the
1410
 * specific support function.
1411
 */
1412
static int usb_host_scan(void *opaque, USBScanFunc *func)
1413
{
1414
    Monitor *mon = cur_mon;
1415
    FILE *f = NULL;
1416
    DIR *dir = NULL;
1417
    int ret = 0;
1418
    const char *fs_type[] = {"unknown", "proc", "dev", "sys"};
1419
    char devpath[PATH_MAX];
1420

    
1421
    /* only check the host once */
1422
    if (!usb_fs_type) {
1423
        dir = opendir(USBSYSBUS_PATH "/devices");
1424
        if (dir) {
1425
            /* devices found in /dev/bus/usb/ (yes - not a mistake!) */
1426
            strcpy(devpath, USBDEVBUS_PATH);
1427
            usb_fs_type = USB_FS_SYS;
1428
            closedir(dir);
1429
            DPRINTF(USBDBG_DEVOPENED, USBSYSBUS_PATH);
1430
            goto found_devices;
1431
        }
1432
        f = fopen(USBPROCBUS_PATH "/devices", "r");
1433
        if (f) {
1434
            /* devices found in /proc/bus/usb/ */
1435
            strcpy(devpath, USBPROCBUS_PATH);
1436
            usb_fs_type = USB_FS_PROC;
1437
            fclose(f);
1438
            DPRINTF(USBDBG_DEVOPENED, USBPROCBUS_PATH);
1439
            goto found_devices;
1440
        }
1441
        /* try additional methods if an access method hasn't been found yet */
1442
        f = fopen(USBDEVBUS_PATH "/devices", "r");
1443
        if (f) {
1444
            /* devices found in /dev/bus/usb/ */
1445
            strcpy(devpath, USBDEVBUS_PATH);
1446
            usb_fs_type = USB_FS_DEV;
1447
            fclose(f);
1448
            DPRINTF(USBDBG_DEVOPENED, USBDEVBUS_PATH);
1449
            goto found_devices;
1450
        }
1451
    found_devices:
1452
        if (!usb_fs_type) {
1453
            if (mon) {
1454
                monitor_printf(mon, "husb: unable to access USB devices\n");
1455
            }
1456
            return -ENOENT;
1457
        }
1458

    
1459
        /* the module setting (used later for opening devices) */
1460
        usb_host_device_path = qemu_mallocz(strlen(devpath)+1);
1461
        strcpy(usb_host_device_path, devpath);
1462
        if (mon) {
1463
            monitor_printf(mon, "husb: using %s file-system with %s\n",
1464
                           fs_type[usb_fs_type], usb_host_device_path);
1465
        }
1466
    }
1467

    
1468
    switch (usb_fs_type) {
1469
    case USB_FS_PROC:
1470
    case USB_FS_DEV:
1471
        ret = usb_host_scan_dev(opaque, func);
1472
        break;
1473
    case USB_FS_SYS:
1474
        ret = usb_host_scan_sys(opaque, func);
1475
        break;
1476
    default:
1477
        ret = -EINVAL;
1478
        break;
1479
    }
1480
    return ret;
1481
}
1482

    
1483
static QEMUTimer *usb_auto_timer;
1484

    
1485
static int usb_host_auto_scan(void *opaque, int bus_num, int addr, int devpath,
1486
                              int class_id, int vendor_id, int product_id,
1487
                              const char *product_name, int speed)
1488
{
1489
    struct USBAutoFilter *f;
1490
    struct USBHostDevice *s;
1491

    
1492
    /* Ignore hubs */
1493
    if (class_id == 9)
1494
        return 0;
1495

    
1496
    QTAILQ_FOREACH(s, &hostdevs, next) {
1497
        f = &s->match;
1498

    
1499
        if (f->bus_num > 0 && f->bus_num != bus_num) {
1500
            continue;
1501
        }
1502
        if (f->addr > 0 && f->addr != addr) {
1503
            continue;
1504
        }
1505

    
1506
        if (f->vendor_id > 0 && f->vendor_id != vendor_id) {
1507
            continue;
1508
        }
1509

    
1510
        if (f->product_id > 0 && f->product_id != product_id) {
1511
            continue;
1512
        }
1513
        /* We got a match */
1514

    
1515
        /* Already attached ? */
1516
        if (s->fd != -1) {
1517
            return 0;
1518
        }
1519
        DPRINTF("husb: auto open: bus_num %d addr %d\n", bus_num, addr);
1520

    
1521
        usb_host_open(s, bus_num, addr, devpath, product_name);
1522
    }
1523

    
1524
    return 0;
1525
}
1526

    
1527
static void usb_host_auto_check(void *unused)
1528
{
1529
    struct USBHostDevice *s;
1530
    int unconnected = 0;
1531

    
1532
    usb_host_scan(NULL, usb_host_auto_scan);
1533

    
1534
    QTAILQ_FOREACH(s, &hostdevs, next) {
1535
        if (s->fd == -1) {
1536
            unconnected++;
1537
        }
1538
    }
1539

    
1540
    if (unconnected == 0) {
1541
        /* nothing to watch */
1542
        if (usb_auto_timer) {
1543
            qemu_del_timer(usb_auto_timer);
1544
        }
1545
        return;
1546
    }
1547

    
1548
    if (!usb_auto_timer) {
1549
        usb_auto_timer = qemu_new_timer_ms(rt_clock, usb_host_auto_check, NULL);
1550
        if (!usb_auto_timer) {
1551
            return;
1552
        }
1553
    }
1554
    qemu_mod_timer(usb_auto_timer, qemu_get_clock_ms(rt_clock) + 2000);
1555
}
1556

    
1557
/*
1558
 * Autoconnect filter
1559
 * Format:
1560
 *    auto:bus:dev[:vid:pid]
1561
 *    auto:bus.dev[:vid:pid]
1562
 *
1563
 *    bus  - bus number    (dec, * means any)
1564
 *    dev  - device number (dec, * means any)
1565
 *    vid  - vendor id     (hex, * means any)
1566
 *    pid  - product id    (hex, * means any)
1567
 *
1568
 *    See 'lsusb' output.
1569
 */
1570
static int parse_filter(const char *spec, struct USBAutoFilter *f)
1571
{
1572
    enum { BUS, DEV, VID, PID, DONE };
1573
    const char *p = spec;
1574
    int i;
1575

    
1576
    f->bus_num    = 0;
1577
    f->addr       = 0;
1578
    f->vendor_id  = 0;
1579
    f->product_id = 0;
1580

    
1581
    for (i = BUS; i < DONE; i++) {
1582
        p = strpbrk(p, ":.");
1583
        if (!p) {
1584
            break;
1585
        }
1586
        p++;
1587

    
1588
        if (*p == '*') {
1589
            continue;
1590
        }
1591
        switch(i) {
1592
        case BUS: f->bus_num = strtol(p, NULL, 10);    break;
1593
        case DEV: f->addr    = strtol(p, NULL, 10);    break;
1594
        case VID: f->vendor_id  = strtol(p, NULL, 16); break;
1595
        case PID: f->product_id = strtol(p, NULL, 16); break;
1596
        }
1597
    }
1598

    
1599
    if (i < DEV) {
1600
        fprintf(stderr, "husb: invalid auto filter spec %s\n", spec);
1601
        return -1;
1602
    }
1603

    
1604
    return 0;
1605
}
1606

    
1607
/**********************/
1608
/* USB host device info */
1609

    
1610
struct usb_class_info {
1611
    int class;
1612
    const char *class_name;
1613
};
1614

    
1615
static const struct usb_class_info usb_class_info[] = {
1616
    { USB_CLASS_AUDIO, "Audio"},
1617
    { USB_CLASS_COMM, "Communication"},
1618
    { USB_CLASS_HID, "HID"},
1619
    { USB_CLASS_HUB, "Hub" },
1620
    { USB_CLASS_PHYSICAL, "Physical" },
1621
    { USB_CLASS_PRINTER, "Printer" },
1622
    { USB_CLASS_MASS_STORAGE, "Storage" },
1623
    { USB_CLASS_CDC_DATA, "Data" },
1624
    { USB_CLASS_APP_SPEC, "Application Specific" },
1625
    { USB_CLASS_VENDOR_SPEC, "Vendor Specific" },
1626
    { USB_CLASS_STILL_IMAGE, "Still Image" },
1627
    { USB_CLASS_CSCID, "Smart Card" },
1628
    { USB_CLASS_CONTENT_SEC, "Content Security" },
1629
    { -1, NULL }
1630
};
1631

    
1632
static const char *usb_class_str(uint8_t class)
1633
{
1634
    const struct usb_class_info *p;
1635
    for(p = usb_class_info; p->class != -1; p++) {
1636
        if (p->class == class) {
1637
            break;
1638
        }
1639
    }
1640
    return p->class_name;
1641
}
1642

    
1643
static void usb_info_device(Monitor *mon, int bus_num, int addr, int class_id,
1644
                            int vendor_id, int product_id,
1645
                            const char *product_name,
1646
                            int speed)
1647
{
1648
    const char *class_str, *speed_str;
1649

    
1650
    switch(speed) {
1651
    case USB_SPEED_LOW:
1652
        speed_str = "1.5";
1653
        break;
1654
    case USB_SPEED_FULL:
1655
        speed_str = "12";
1656
        break;
1657
    case USB_SPEED_HIGH:
1658
        speed_str = "480";
1659
        break;
1660
    default:
1661
        speed_str = "?";
1662
        break;
1663
    }
1664

    
1665
    monitor_printf(mon, "  Device %d.%d, speed %s Mb/s\n",
1666
                bus_num, addr, speed_str);
1667
    class_str = usb_class_str(class_id);
1668
    if (class_str) {
1669
        monitor_printf(mon, "    %s:", class_str);
1670
    } else {
1671
        monitor_printf(mon, "    Class %02x:", class_id);
1672
    }
1673
    monitor_printf(mon, " USB device %04x:%04x", vendor_id, product_id);
1674
    if (product_name[0] != '\0') {
1675
        monitor_printf(mon, ", %s", product_name);
1676
    }
1677
    monitor_printf(mon, "\n");
1678
}
1679

    
1680
static int usb_host_info_device(void *opaque, int bus_num, int addr,
1681
                                int devpath, int class_id,
1682
                                int vendor_id, int product_id,
1683
                                const char *product_name,
1684
                                int speed)
1685
{
1686
    Monitor *mon = opaque;
1687

    
1688
    usb_info_device(mon, bus_num, addr, class_id, vendor_id, product_id,
1689
                    product_name, speed);
1690
    return 0;
1691
}
1692

    
1693
static void dec2str(int val, char *str, size_t size)
1694
{
1695
    if (val == 0) {
1696
        snprintf(str, size, "*");
1697
    } else {
1698
        snprintf(str, size, "%d", val);
1699
    }
1700
}
1701

    
1702
static void hex2str(int val, char *str, size_t size)
1703
{
1704
    if (val == 0) {
1705
        snprintf(str, size, "*");
1706
    } else {
1707
        snprintf(str, size, "%04x", val);
1708
    }
1709
}
1710

    
1711
void usb_host_info(Monitor *mon)
1712
{
1713
    struct USBAutoFilter *f;
1714
    struct USBHostDevice *s;
1715

    
1716
    usb_host_scan(mon, usb_host_info_device);
1717

    
1718
    if (QTAILQ_EMPTY(&hostdevs)) {
1719
        return;
1720
    }
1721

    
1722
    monitor_printf(mon, "  Auto filters:\n");
1723
    QTAILQ_FOREACH(s, &hostdevs, next) {
1724
        char bus[10], addr[10], vid[10], pid[10];
1725
        f = &s->match;
1726
        dec2str(f->bus_num, bus, sizeof(bus));
1727
        dec2str(f->addr, addr, sizeof(addr));
1728
        hex2str(f->vendor_id, vid, sizeof(vid));
1729
        hex2str(f->product_id, pid, sizeof(pid));
1730
        monitor_printf(mon, "    Device %s.%s ID %s:%s\n",
1731
                       bus, addr, vid, pid);
1732
    }
1733
}