Statistics
| Branch: | Revision:

root / usb-linux.c @ b373a63a

History | View | Annotate | Download (43.5 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 class_id,
66
                        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 contigious 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
    struct USBAutoFilter match;
145

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

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

    
151
static int usb_host_close(USBHostDevice *dev);
152
static int parse_filter(const char *spec, struct USBAutoFilter *f);
153
static void usb_host_auto_check(void *unused);
154

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

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

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

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

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

    
185
    USBPacket     *packet;
186
    USBHostDevice *hdev;
187
} AsyncURB;
188

    
189
static AsyncURB *async_alloc(void)
190
{
191
    return (AsyncURB *) qemu_mallocz(sizeof(AsyncURB));
192
}
193

    
194
static void async_free(AsyncURB *aurb)
195
{
196
    qemu_free(aurb);
197
}
198

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

    
209
    case CTRL_STATE_ACK:
210
        s->ctrl.state = CTRL_STATE_IDLE;
211
        p->len = 0;
212
        break;
213

    
214
    default:
215
        break;
216
    }
217
}
218

    
219
static void async_complete(void *opaque)
220
{
221
    USBHostDevice *s = opaque;
222
    AsyncURB *aurb;
223

    
224
    while (1) {
225
        USBPacket *p;
226

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

    
240
            DPRINTF("husb: async. reap urb failed errno %d\n", errno);
241
            return;
242
        }
243

    
244
        p = aurb->packet;
245

    
246
        DPRINTF("husb: async completed. aurb %p status %d alen %d\n",
247
                aurb, aurb->urb.status, aurb->urb.actual_length);
248

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

    
258
            case -EPIPE:
259
                set_halt(s, p->devep);
260
                p->len = USB_RET_STALL;
261
                break;
262

    
263
            default:
264
                p->len = USB_RET_NAK;
265
                break;
266
            }
267

    
268
            usb_packet_complete(p);
269
        }
270

    
271
        async_free(aurb);
272
    }
273
}
274

    
275
static void async_cancel(USBPacket *unused, void *opaque)
276
{
277
    AsyncURB *aurb = opaque;
278
    USBHostDevice *s = aurb->hdev;
279

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

    
282
    /* Mark it as dead (see async_complete above) */
283
    aurb->packet = NULL;
284

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

    
291
static int usb_host_claim_interfaces(USBHostDevice *dev, int configuration)
292
{
293
    int dev_descr_len, config_descr_len;
294
    int interface, nb_interfaces;
295
    int ret, i;
296

    
297
    if (configuration == 0) /* address state - ignore */
298
        return 1;
299

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

    
302
    i = 0;
303
    dev_descr_len = dev->descr[0];
304
    if (dev_descr_len > dev->descr_len) {
305
        goto fail;
306
    }
307

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

    
314
        if (dev->descr[i+1] != USB_DT_CONFIG) {
315
            i += dev->descr[i];
316
            continue;
317
        }
318
        config_descr_len = dev->descr[i];
319

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

    
322
        if (configuration < 0 || configuration == dev->descr[i + 5]) {
323
            configuration = dev->descr[i + 5];
324
            break;
325
        }
326

    
327
        i += config_descr_len;
328
    }
329

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

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

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

    
367
    printf("husb: %d interfaces claimed for configuration %d\n",
368
           nb_interfaces, configuration);
369

    
370
    dev->ninterfaces   = nb_interfaces;
371
    dev->configuration = configuration;
372
    return 1;
373
}
374

    
375
static int usb_host_release_interfaces(USBHostDevice *s)
376
{
377
    int ret, i;
378

    
379
    DPRINTF("husb: releasing interfaces\n");
380

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

    
389
    return 1;
390
}
391

    
392
static void usb_host_handle_reset(USBDevice *dev)
393
{
394
    USBHostDevice *s = DO_UPCAST(USBHostDevice, dev, dev);
395

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

    
398
    ioctl(s->fd, USBDEVFS_RESET);
399

    
400
    usb_host_claim_interfaces(s, s->configuration);
401
}
402

    
403
static void usb_host_handle_destroy(USBDevice *dev)
404
{
405
    USBHostDevice *s = (USBHostDevice *)dev;
406

    
407
    usb_host_close(s);
408
    QTAILQ_REMOVE(&hostdevs, s, next);
409
    qemu_remove_exit_notifier(&s->exit);
410
}
411

    
412
static int usb_linux_update_endp_table(USBHostDevice *s);
413

    
414
static int usb_host_handle_data(USBHostDevice *s, USBPacket *p)
415
{
416
    struct usbdevfs_urb *urb;
417
    AsyncURB *aurb;
418
    int ret;
419

    
420
    aurb = async_alloc();
421
    aurb->hdev   = s;
422
    aurb->packet = p;
423

    
424
    urb = &aurb->urb;
425

    
426
    if (p->pid == USB_TOKEN_IN) {
427
        urb->endpoint = p->devep | 0x80;
428
    } else {
429
        urb->endpoint = p->devep;
430
    }
431

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

    
442
    urb->buffer        = p->data;
443
    urb->buffer_length = p->len;
444

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

    
456
    urb->usercontext = s;
457

    
458
    ret = ioctl(s->fd, USBDEVFS_SUBMITURB, urb);
459

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

    
463
    if (ret < 0) {
464
        DPRINTF("husb: submit failed. errno %d\n", errno);
465
        async_free(aurb);
466

    
467
        switch(errno) {
468
        case ETIMEDOUT:
469
            return USB_RET_NAK;
470
        case EPIPE:
471
        default:
472
            return USB_RET_STALL;
473
        }
474
    }
475

    
476
    usb_defer_packet(p, async_cancel, aurb);
477
    return USB_RET_ASYNC;
478
}
479

    
480
static int ctrl_error(void)
481
{
482
    if (errno == ETIMEDOUT) {
483
        return USB_RET_NAK;
484
    } else {
485
        return USB_RET_STALL;
486
    }
487
}
488

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

    
496
static int usb_host_set_config(USBHostDevice *s, int config)
497
{
498
    usb_host_release_interfaces(s);
499

    
500
    int ret = ioctl(s->fd, USBDEVFS_SETCONFIGURATION, &config);
501

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

    
504
    if (ret < 0) {
505
        return ctrl_error();
506
    }
507
    usb_host_claim_interfaces(s, config);
508
    return 0;
509
}
510

    
511
static int usb_host_set_interface(USBHostDevice *s, int iface, int alt)
512
{
513
    struct usbdevfs_setinterface si;
514
    int ret;
515

    
516
    si.interface  = iface;
517
    si.altsetting = alt;
518
    ret = ioctl(s->fd, USBDEVFS_SETINTERFACE, &si);
519

    
520
    DPRINTF("husb: ctrl set iface %d altset %d ret %d errno %d\n",
521
            iface, alt, ret, errno);
522

    
523
    if (ret < 0) {
524
        return ctrl_error();
525
    }
526
    usb_linux_update_endp_table(s);
527
    return 0;
528
}
529

    
530
static int usb_host_handle_control(USBHostDevice *s, USBPacket *p)
531
{
532
    struct usbdevfs_urb *urb;
533
    AsyncURB *aurb;
534
    int ret, value, index;
535
    int buffer_len;
536

    
537
    /*
538
     * Process certain standard device requests.
539
     * These are infrequent and are processed synchronously.
540
     */
541
    value = le16_to_cpu(s->ctrl.req.wValue);
542
    index = le16_to_cpu(s->ctrl.req.wIndex);
543

    
544
    DPRINTF("husb: ctrl type 0x%x req 0x%x val 0x%x index %u len %u\n",
545
            s->ctrl.req.bRequestType, s->ctrl.req.bRequest, value, index,
546
            s->ctrl.len);
547

    
548
    if (s->ctrl.req.bRequestType == 0) {
549
        switch (s->ctrl.req.bRequest) {
550
        case USB_REQ_SET_ADDRESS:
551
            return usb_host_set_address(s, value);
552

    
553
        case USB_REQ_SET_CONFIGURATION:
554
            return usb_host_set_config(s, value & 0xff);
555
        }
556
    }
557

    
558
    if (s->ctrl.req.bRequestType == 1 &&
559
                  s->ctrl.req.bRequest == USB_REQ_SET_INTERFACE) {
560
        return usb_host_set_interface(s, index, value);
561
    }
562

    
563
    /* The rest are asynchronous */
564

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

    
572
    aurb = async_alloc();
573
    aurb->hdev   = s;
574
    aurb->packet = p;
575

    
576
    /*
577
     * Setup ctrl transfer.
578
     *
579
     * s->ctrl is layed out such that data buffer immediately follows
580
     * 'req' struct which is exactly what usbdevfs expects.
581
     */
582
    urb = &aurb->urb;
583

    
584
    urb->type     = USBDEVFS_URB_TYPE_CONTROL;
585
    urb->endpoint = p->devep;
586

    
587
    urb->buffer        = &s->ctrl.req;
588
    urb->buffer_length = buffer_len;
589

    
590
    urb->usercontext = s;
591

    
592
    ret = ioctl(s->fd, USBDEVFS_SUBMITURB, urb);
593

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

    
596
    if (ret < 0) {
597
        DPRINTF("husb: submit failed. errno %d\n", errno);
598
        async_free(aurb);
599

    
600
        switch(errno) {
601
        case ETIMEDOUT:
602
            return USB_RET_NAK;
603
        case EPIPE:
604
        default:
605
            return USB_RET_STALL;
606
        }
607
    }
608

    
609
    usb_defer_packet(p, async_cancel, aurb);
610
    return USB_RET_ASYNC;
611
}
612

    
613
static int do_token_setup(USBDevice *dev, USBPacket *p)
614
{
615
    USBHostDevice *s = (USBHostDevice *) dev;
616
    int ret = 0;
617

    
618
    if (p->len != 8) {
619
        return USB_RET_STALL;
620
    }
621

    
622
    memcpy(&s->ctrl.req, p->data, 8);
623
    s->ctrl.len    = le16_to_cpu(s->ctrl.req.wLength);
624
    s->ctrl.offset = 0;
625
    s->ctrl.state  = CTRL_STATE_SETUP;
626

    
627
    if (s->ctrl.req.bRequestType & USB_DIR_IN) {
628
        ret = usb_host_handle_control(s, p);
629
        if (ret < 0) {
630
            return ret;
631
        }
632

    
633
        if (ret < s->ctrl.len) {
634
            s->ctrl.len = ret;
635
        }
636
        s->ctrl.state = CTRL_STATE_DATA;
637
    } else {
638
        if (s->ctrl.len == 0) {
639
            s->ctrl.state = CTRL_STATE_ACK;
640
        } else {
641
            s->ctrl.state = CTRL_STATE_DATA;
642
        }
643
    }
644

    
645
    return ret;
646
}
647

    
648
static int do_token_in(USBDevice *dev, USBPacket *p)
649
{
650
    USBHostDevice *s = (USBHostDevice *) dev;
651
    int ret = 0;
652

    
653
    if (p->devep != 0) {
654
        return usb_host_handle_data(s, p);
655
    }
656

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

    
668
        return 0;
669

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

    
684
        s->ctrl.state = CTRL_STATE_IDLE;
685
        return USB_RET_STALL;
686

    
687
    default:
688
        return USB_RET_STALL;
689
    }
690
}
691

    
692
static int do_token_out(USBDevice *dev, USBPacket *p)
693
{
694
    USBHostDevice *s = (USBHostDevice *) dev;
695

    
696
    if (p->devep != 0) {
697
        return usb_host_handle_data(s, p);
698
    }
699

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

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

    
724
        s->ctrl.state = CTRL_STATE_IDLE;
725
        return USB_RET_STALL;
726

    
727
    default:
728
        return USB_RET_STALL;
729
    }
730
}
731

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

    
745
    case USB_MSG_DETACH:
746
        s->state = USB_STATE_NOTATTACHED;
747
        return 0;
748

    
749
    case USB_MSG_RESET:
750
        s->remote_wakeup = 0;
751
        s->addr = 0;
752
        s->state = USB_STATE_DEFAULT;
753
        s->info->handle_reset(s);
754
        return 0;
755
    }
756

    
757
    /* Rest of the PIDs must match our address */
758
    if (s->state < USB_STATE_DEFAULT || p->devaddr != s->addr) {
759
        return USB_RET_NODEV;
760
    }
761

    
762
    switch (p->pid) {
763
    case USB_TOKEN_SETUP:
764
        return do_token_setup(s, p);
765

    
766
    case USB_TOKEN_IN:
767
        return do_token_in(s, p);
768

    
769
    case USB_TOKEN_OUT:
770
        return do_token_out(s, p);
771

    
772
    default:
773
        return USB_RET_STALL;
774
    }
775
}
776

    
777
/* returns 1 on problem encountered or 0 for success */
778
static int usb_linux_update_endp_table(USBHostDevice *s)
779
{
780
    uint8_t *descriptors;
781
    uint8_t devep, type, configuration, alt_interface;
782
    struct usb_ctrltransfer ct;
783
    int interface, ret, length, i;
784

    
785
    ct.bRequestType = USB_DIR_IN;
786
    ct.bRequest = USB_REQ_GET_CONFIGURATION;
787
    ct.wValue = 0;
788
    ct.wIndex = 0;
789
    ct.wLength = 1;
790
    ct.data = &configuration;
791
    ct.timeout = 50;
792

    
793
    ret = ioctl(s->fd, USBDEVFS_CONTROL, &ct);
794
    if (ret < 0) {
795
        perror("usb_linux_update_endp_table");
796
        return 1;
797
    }
798

    
799
    /* in address state */
800
    if (configuration == 0) {
801
        return 1;
802
    }
803

    
804
    /* get the desired configuration, interface, and endpoint descriptors
805
     * from device description */
806
    descriptors = &s->descr[18];
807
    length = s->descr_len - 18;
808
    i = 0;
809

    
810
    if (descriptors[i + 1] != USB_DT_CONFIG ||
811
        descriptors[i + 5] != configuration) {
812
        DPRINTF("invalid descriptor data - configuration\n");
813
        return 1;
814
    }
815
    i += descriptors[i];
816

    
817
    while (i < length) {
818
        if (descriptors[i + 1] != USB_DT_INTERFACE ||
819
            (descriptors[i + 1] == USB_DT_INTERFACE &&
820
             descriptors[i + 4] == 0)) {
821
            i += descriptors[i];
822
            continue;
823
        }
824

    
825
        interface = descriptors[i + 2];
826

    
827
        ct.bRequestType = USB_DIR_IN | USB_RECIP_INTERFACE;
828
        ct.bRequest = USB_REQ_GET_INTERFACE;
829
        ct.wValue = 0;
830
        ct.wIndex = interface;
831
        ct.wLength = 1;
832
        ct.data = &alt_interface;
833
        ct.timeout = 50;
834

    
835
        ret = ioctl(s->fd, USBDEVFS_CONTROL, &ct);
836
        if (ret < 0) {
837
            alt_interface = interface;
838
        }
839

    
840
        /* the current interface descriptor is the active interface
841
         * and has endpoints */
842
        if (descriptors[i + 3] != alt_interface) {
843
            i += descriptors[i];
844
            continue;
845
        }
846

    
847
        /* advance to the endpoints */
848
        while (i < length && descriptors[i +1] != USB_DT_ENDPOINT) {
849
            i += descriptors[i];
850
        }
851

    
852
        if (i >= length)
853
            break;
854

    
855
        while (i < length) {
856
            if (descriptors[i + 1] != USB_DT_ENDPOINT) {
857
                break;
858
            }
859

    
860
            devep = descriptors[i + 2];
861
            switch (descriptors[i + 3] & 0x3) {
862
            case 0x00:
863
                type = USBDEVFS_URB_TYPE_CONTROL;
864
                break;
865
            case 0x01:
866
                type = USBDEVFS_URB_TYPE_ISO;
867
                break;
868
            case 0x02:
869
                type = USBDEVFS_URB_TYPE_BULK;
870
                break;
871
            case 0x03:
872
                type = USBDEVFS_URB_TYPE_INTERRUPT;
873
                break;
874
            default:
875
                DPRINTF("usb_host: malformed endpoint type\n");
876
                type = USBDEVFS_URB_TYPE_BULK;
877
            }
878
            s->endp_table[(devep & 0xf) - 1].type = type;
879
            s->endp_table[(devep & 0xf) - 1].halted = 0;
880

    
881
            i += descriptors[i];
882
        }
883
    }
884
    return 0;
885
}
886

    
887
static int usb_host_open(USBHostDevice *dev, int bus_num,
888
                         int addr, const char *prod_name)
889
{
890
    int fd = -1, ret;
891
    struct usbdevfs_connectinfo ci;
892
    char buf[1024];
893

    
894
    if (dev->fd != -1) {
895
        goto fail;
896
    }
897
    printf("husb: open device %d.%d\n", bus_num, addr);
898

    
899
    if (!usb_host_device_path) {
900
        perror("husb: USB Host Device Path not set");
901
        goto fail;
902
    }
903
    snprintf(buf, sizeof(buf), "%s/%03d/%03d", usb_host_device_path,
904
             bus_num, addr);
905
    fd = open(buf, O_RDWR | O_NONBLOCK);
906
    if (fd < 0) {
907
        perror(buf);
908
        goto fail;
909
    }
910
    DPRINTF("husb: opened %s\n", buf);
911

    
912
    dev->bus_num = bus_num;
913
    dev->addr = addr;
914
    dev->fd = fd;
915

    
916
    /* read the device description */
917
    dev->descr_len = read(fd, dev->descr, sizeof(dev->descr));
918
    if (dev->descr_len <= 0) {
919
        perror("husb: reading device data failed");
920
        goto fail;
921
    }
922

    
923
#ifdef DEBUG
924
    {
925
        int x;
926
        printf("=== begin dumping device descriptor data ===\n");
927
        for (x = 0; x < dev->descr_len; x++) {
928
            printf("%02x ", dev->descr[x]);
929
        }
930
        printf("\n=== end dumping device descriptor data ===\n");
931
    }
932
#endif
933

    
934

    
935
    /*
936
     * Initial configuration is -1 which makes us claim first
937
     * available config. We used to start with 1, which does not
938
     * always work. I've seen devices where first config starts
939
     * with 2.
940
     */
941
    if (!usb_host_claim_interfaces(dev, -1)) {
942
        goto fail;
943
    }
944

    
945
    ret = ioctl(fd, USBDEVFS_CONNECTINFO, &ci);
946
    if (ret < 0) {
947
        perror("usb_host_device_open: USBDEVFS_CONNECTINFO");
948
        goto fail;
949
    }
950

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

    
953
    ret = usb_linux_update_endp_table(dev);
954
    if (ret) {
955
        goto fail;
956
    }
957

    
958
    if (ci.slow) {
959
        dev->dev.speed = USB_SPEED_LOW;
960
    } else {
961
        dev->dev.speed = USB_SPEED_HIGH;
962
    }
963

    
964
    if (!prod_name || prod_name[0] == '\0') {
965
        snprintf(dev->dev.product_desc, sizeof(dev->dev.product_desc),
966
                 "host:%d.%d", bus_num, addr);
967
    } else {
968
        pstrcpy(dev->dev.product_desc, sizeof(dev->dev.product_desc),
969
                prod_name);
970
    }
971

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

    
975
    usb_device_attach(&dev->dev);
976
    return 0;
977

    
978
fail:
979
    dev->fd = -1;
980
    if (fd != -1) {
981
        close(fd);
982
    }
983
    return -1;
984
}
985

    
986
static int usb_host_close(USBHostDevice *dev)
987
{
988
    if (dev->fd == -1) {
989
        return -1;
990
    }
991

    
992
    qemu_set_fd_handler(dev->fd, NULL, NULL, NULL);
993
    dev->closing = 1;
994
    async_complete(dev);
995
    dev->closing = 0;
996
    usb_device_detach(&dev->dev);
997
    ioctl(dev->fd, USBDEVFS_RESET);
998
    close(dev->fd);
999
    dev->fd = -1;
1000
    return 0;
1001
}
1002

    
1003
static void usb_host_exit_notifier(struct Notifier* n)
1004
{
1005
    USBHostDevice *s = container_of(n, USBHostDevice, exit);
1006

    
1007
    if (s->fd != -1) {
1008
        ioctl(s->fd, USBDEVFS_RESET);
1009
    }
1010
}
1011

    
1012
static int usb_host_initfn(USBDevice *dev)
1013
{
1014
    USBHostDevice *s = DO_UPCAST(USBHostDevice, dev, dev);
1015

    
1016
    dev->auto_attach = 0;
1017
    s->fd = -1;
1018
    QTAILQ_INSERT_TAIL(&hostdevs, s, next);
1019
    s->exit.notify = usb_host_exit_notifier;
1020
    qemu_add_exit_notifier(&s->exit);
1021
    usb_host_auto_check(NULL);
1022
    return 0;
1023
}
1024

    
1025
static struct USBDeviceInfo usb_host_dev_info = {
1026
    .product_desc   = "USB Host Device",
1027
    .qdev.name      = "usb-host",
1028
    .qdev.size      = sizeof(USBHostDevice),
1029
    .init           = usb_host_initfn,
1030
    .handle_packet  = usb_host_handle_packet,
1031
    .handle_reset   = usb_host_handle_reset,
1032
    .handle_destroy = usb_host_handle_destroy,
1033
    .usbdevice_name = "host",
1034
    .usbdevice_init = usb_host_device_open,
1035
    .qdev.props     = (Property[]) {
1036
        DEFINE_PROP_UINT32("hostbus",  USBHostDevice, match.bus_num,    0),
1037
        DEFINE_PROP_UINT32("hostaddr", USBHostDevice, match.addr,       0),
1038
        DEFINE_PROP_HEX32("vendorid",  USBHostDevice, match.vendor_id,  0),
1039
        DEFINE_PROP_HEX32("productid", USBHostDevice, match.product_id, 0),
1040
        DEFINE_PROP_END_OF_LIST(),
1041
    },
1042
};
1043

    
1044
static void usb_host_register_devices(void)
1045
{
1046
    usb_qdev_register(&usb_host_dev_info);
1047
}
1048
device_init(usb_host_register_devices)
1049

    
1050
USBDevice *usb_host_device_open(const char *devname)
1051
{
1052
    struct USBAutoFilter filter;
1053
    USBDevice *dev;
1054
    char *p;
1055

    
1056
    dev = usb_create(NULL /* FIXME */, "usb-host");
1057

    
1058
    if (strstr(devname, "auto:")) {
1059
        if (parse_filter(devname, &filter) < 0) {
1060
            goto fail;
1061
        }
1062
    } else {
1063
        if ((p = strchr(devname, '.'))) {
1064
            filter.bus_num    = strtoul(devname, NULL, 0);
1065
            filter.addr       = strtoul(p + 1, NULL, 0);
1066
            filter.vendor_id  = 0;
1067
            filter.product_id = 0;
1068
        } else if ((p = strchr(devname, ':'))) {
1069
            filter.bus_num    = 0;
1070
            filter.addr       = 0;
1071
            filter.vendor_id  = strtoul(devname, NULL, 16);
1072
            filter.product_id = strtoul(p + 1, NULL, 16);
1073
        } else {
1074
            goto fail;
1075
        }
1076
    }
1077

    
1078
    qdev_prop_set_uint32(&dev->qdev, "hostbus",   filter.bus_num);
1079
    qdev_prop_set_uint32(&dev->qdev, "hostaddr",  filter.addr);
1080
    qdev_prop_set_uint32(&dev->qdev, "vendorid",  filter.vendor_id);
1081
    qdev_prop_set_uint32(&dev->qdev, "productid", filter.product_id);
1082
    qdev_init_nofail(&dev->qdev);
1083
    return dev;
1084

    
1085
fail:
1086
    qdev_free(&dev->qdev);
1087
    return NULL;
1088
}
1089

    
1090
int usb_host_device_close(const char *devname)
1091
{
1092
#if 0
1093
    char product_name[PRODUCT_NAME_SZ];
1094
    int bus_num, addr;
1095
    USBHostDevice *s;
1096

1097
    if (strstr(devname, "auto:")) {
1098
        return usb_host_auto_del(devname);
1099
    }
1100
    if (usb_host_find_device(&bus_num, &addr, product_name,
1101
                                    sizeof(product_name), devname) < 0) {
1102
        return -1;
1103
    }
1104
    s = hostdev_find(bus_num, addr);
1105
    if (s) {
1106
        usb_device_delete_addr(s->bus_num, s->dev.addr);
1107
        return 0;
1108
    }
1109
#endif
1110

    
1111
    return -1;
1112
}
1113

    
1114
static int get_tag_value(char *buf, int buf_size,
1115
                         const char *str, const char *tag,
1116
                         const char *stopchars)
1117
{
1118
    const char *p;
1119
    char *q;
1120
    p = strstr(str, tag);
1121
    if (!p) {
1122
        return -1;
1123
    }
1124
    p += strlen(tag);
1125
    while (qemu_isspace(*p)) {
1126
        p++;
1127
    }
1128
    q = buf;
1129
    while (*p != '\0' && !strchr(stopchars, *p)) {
1130
        if ((q - buf) < (buf_size - 1)) {
1131
            *q++ = *p;
1132
        }
1133
        p++;
1134
    }
1135
    *q = '\0';
1136
    return q - buf;
1137
}
1138

    
1139
/*
1140
 * Use /proc/bus/usb/devices or /dev/bus/usb/devices file to determine
1141
 * host's USB devices. This is legacy support since many distributions
1142
 * are moving to /sys/bus/usb
1143
 */
1144
static int usb_host_scan_dev(void *opaque, USBScanFunc *func)
1145
{
1146
    FILE *f = NULL;
1147
    char line[1024];
1148
    char buf[1024];
1149
    int bus_num, addr, speed, device_count, class_id, product_id, vendor_id;
1150
    char product_name[512];
1151
    int ret = 0;
1152

    
1153
    if (!usb_host_device_path) {
1154
        perror("husb: USB Host Device Path not set");
1155
        goto the_end;
1156
    }
1157
    snprintf(line, sizeof(line), "%s/devices", usb_host_device_path);
1158
    f = fopen(line, "r");
1159
    if (!f) {
1160
        perror("husb: cannot open devices file");
1161
        goto the_end;
1162
    }
1163

    
1164
    device_count = 0;
1165
    bus_num = addr = speed = class_id = product_id = vendor_id = 0;
1166
    for(;;) {
1167
        if (fgets(line, sizeof(line), f) == NULL) {
1168
            break;
1169
        }
1170
        if (strlen(line) > 0) {
1171
            line[strlen(line) - 1] = '\0';
1172
        }
1173
        if (line[0] == 'T' && line[1] == ':') {
1174
            if (device_count && (vendor_id || product_id)) {
1175
                /* New device.  Add the previously discovered device.  */
1176
                ret = func(opaque, bus_num, addr, class_id, vendor_id,
1177
                           product_id, product_name, speed);
1178
                if (ret) {
1179
                    goto the_end;
1180
                }
1181
            }
1182
            if (get_tag_value(buf, sizeof(buf), line, "Bus=", " ") < 0) {
1183
                goto fail;
1184
            }
1185
            bus_num = atoi(buf);
1186
            if (get_tag_value(buf, sizeof(buf), line, "Dev#=", " ") < 0) {
1187
                goto fail;
1188
            }
1189
            addr = atoi(buf);
1190
            if (get_tag_value(buf, sizeof(buf), line, "Spd=", " ") < 0) {
1191
                goto fail;
1192
            }
1193
            if (!strcmp(buf, "480")) {
1194
                speed = USB_SPEED_HIGH;
1195
            } else if (!strcmp(buf, "1.5")) {
1196
                speed = USB_SPEED_LOW;
1197
            } else {
1198
                speed = USB_SPEED_FULL;
1199
            }
1200
            product_name[0] = '\0';
1201
            class_id = 0xff;
1202
            device_count++;
1203
            product_id = 0;
1204
            vendor_id = 0;
1205
        } else if (line[0] == 'P' && line[1] == ':') {
1206
            if (get_tag_value(buf, sizeof(buf), line, "Vendor=", " ") < 0) {
1207
                goto fail;
1208
            }
1209
            vendor_id = strtoul(buf, NULL, 16);
1210
            if (get_tag_value(buf, sizeof(buf), line, "ProdID=", " ") < 0) {
1211
                goto fail;
1212
            }
1213
            product_id = strtoul(buf, NULL, 16);
1214
        } else if (line[0] == 'S' && line[1] == ':') {
1215
            if (get_tag_value(buf, sizeof(buf), line, "Product=", "") < 0) {
1216
                goto fail;
1217
            }
1218
            pstrcpy(product_name, sizeof(product_name), buf);
1219
        } else if (line[0] == 'D' && line[1] == ':') {
1220
            if (get_tag_value(buf, sizeof(buf), line, "Cls=", " (") < 0) {
1221
                goto fail;
1222
            }
1223
            class_id = strtoul(buf, NULL, 16);
1224
        }
1225
    fail: ;
1226
    }
1227
    if (device_count && (vendor_id || product_id)) {
1228
        /* Add the last device.  */
1229
        ret = func(opaque, bus_num, addr, class_id, vendor_id,
1230
                   product_id, product_name, speed);
1231
    }
1232
 the_end:
1233
    if (f) {
1234
        fclose(f);
1235
    }
1236
    return ret;
1237
}
1238

    
1239
/*
1240
 * Read sys file-system device file
1241
 *
1242
 * @line address of buffer to put file contents in
1243
 * @line_size size of line
1244
 * @device_file path to device file (printf format string)
1245
 * @device_name device being opened (inserted into device_file)
1246
 *
1247
 * @return 0 failed, 1 succeeded ('line' contains data)
1248
 */
1249
static int usb_host_read_file(char *line, size_t line_size,
1250
                              const char *device_file, const char *device_name)
1251
{
1252
    FILE *f;
1253
    int ret = 0;
1254
    char filename[PATH_MAX];
1255

    
1256
    snprintf(filename, PATH_MAX, USBSYSBUS_PATH "/devices/%s/%s", device_name,
1257
             device_file);
1258
    f = fopen(filename, "r");
1259
    if (f) {
1260
        ret = fgets(line, line_size, f) != NULL;
1261
        fclose(f);
1262
    }
1263

    
1264
    return ret;
1265
}
1266

    
1267
/*
1268
 * Use /sys/bus/usb/devices/ directory to determine host's USB
1269
 * devices.
1270
 *
1271
 * This code is based on Robert Schiele's original patches posted to
1272
 * the Novell bug-tracker https://bugzilla.novell.com/show_bug.cgi?id=241950
1273
 */
1274
static int usb_host_scan_sys(void *opaque, USBScanFunc *func)
1275
{
1276
    DIR *dir = NULL;
1277
    char line[1024];
1278
    int bus_num, addr, speed, class_id, product_id, vendor_id;
1279
    int ret = 0;
1280
    char product_name[512];
1281
    struct dirent *de;
1282

    
1283
    dir = opendir(USBSYSBUS_PATH "/devices");
1284
    if (!dir) {
1285
        perror("husb: cannot open devices directory");
1286
        goto the_end;
1287
    }
1288

    
1289
    while ((de = readdir(dir))) {
1290
        if (de->d_name[0] != '.' && !strchr(de->d_name, ':')) {
1291
            char *tmpstr = de->d_name;
1292
            if (!strncmp(de->d_name, "usb", 3)) {
1293
                tmpstr += 3;
1294
            }
1295
            bus_num = atoi(tmpstr);
1296

    
1297
            if (!usb_host_read_file(line, sizeof(line), "devnum", de->d_name)) {
1298
                goto the_end;
1299
            }
1300
            if (sscanf(line, "%d", &addr) != 1) {
1301
                goto the_end;
1302
            }
1303
            if (!usb_host_read_file(line, sizeof(line), "bDeviceClass",
1304
                                    de->d_name)) {
1305
                goto the_end;
1306
            }
1307
            if (sscanf(line, "%x", &class_id) != 1) {
1308
                goto the_end;
1309
            }
1310

    
1311
            if (!usb_host_read_file(line, sizeof(line), "idVendor",
1312
                                    de->d_name)) {
1313
                goto the_end;
1314
            }
1315
            if (sscanf(line, "%x", &vendor_id) != 1) {
1316
                goto the_end;
1317
            }
1318
            if (!usb_host_read_file(line, sizeof(line), "idProduct",
1319
                                    de->d_name)) {
1320
                goto the_end;
1321
            }
1322
            if (sscanf(line, "%x", &product_id) != 1) {
1323
                goto the_end;
1324
            }
1325
            if (!usb_host_read_file(line, sizeof(line), "product",
1326
                                    de->d_name)) {
1327
                *product_name = 0;
1328
            } else {
1329
                if (strlen(line) > 0) {
1330
                    line[strlen(line) - 1] = '\0';
1331
                }
1332
                pstrcpy(product_name, sizeof(product_name), line);
1333
            }
1334

    
1335
            if (!usb_host_read_file(line, sizeof(line), "speed", de->d_name)) {
1336
                goto the_end;
1337
            }
1338
            if (!strcmp(line, "480\n")) {
1339
                speed = USB_SPEED_HIGH;
1340
            } else if (!strcmp(line, "1.5\n")) {
1341
                speed = USB_SPEED_LOW;
1342
            } else {
1343
                speed = USB_SPEED_FULL;
1344
            }
1345

    
1346
            ret = func(opaque, bus_num, addr, class_id, vendor_id,
1347
                       product_id, product_name, speed);
1348
            if (ret) {
1349
                goto the_end;
1350
            }
1351
        }
1352
    }
1353
 the_end:
1354
    if (dir) {
1355
        closedir(dir);
1356
    }
1357
    return ret;
1358
}
1359

    
1360
/*
1361
 * Determine how to access the host's USB devices and call the
1362
 * specific support function.
1363
 */
1364
static int usb_host_scan(void *opaque, USBScanFunc *func)
1365
{
1366
    Monitor *mon = cur_mon;
1367
    FILE *f = NULL;
1368
    DIR *dir = NULL;
1369
    int ret = 0;
1370
    const char *fs_type[] = {"unknown", "proc", "dev", "sys"};
1371
    char devpath[PATH_MAX];
1372

    
1373
    /* only check the host once */
1374
    if (!usb_fs_type) {
1375
        dir = opendir(USBSYSBUS_PATH "/devices");
1376
        if (dir) {
1377
            /* devices found in /dev/bus/usb/ (yes - not a mistake!) */
1378
            strcpy(devpath, USBDEVBUS_PATH);
1379
            usb_fs_type = USB_FS_SYS;
1380
            closedir(dir);
1381
            DPRINTF(USBDBG_DEVOPENED, USBSYSBUS_PATH);
1382
            goto found_devices;
1383
        }
1384
        f = fopen(USBPROCBUS_PATH "/devices", "r");
1385
        if (f) {
1386
            /* devices found in /proc/bus/usb/ */
1387
            strcpy(devpath, USBPROCBUS_PATH);
1388
            usb_fs_type = USB_FS_PROC;
1389
            fclose(f);
1390
            DPRINTF(USBDBG_DEVOPENED, USBPROCBUS_PATH);
1391
            goto found_devices;
1392
        }
1393
        /* try additional methods if an access method hasn't been found yet */
1394
        f = fopen(USBDEVBUS_PATH "/devices", "r");
1395
        if (f) {
1396
            /* devices found in /dev/bus/usb/ */
1397
            strcpy(devpath, USBDEVBUS_PATH);
1398
            usb_fs_type = USB_FS_DEV;
1399
            fclose(f);
1400
            DPRINTF(USBDBG_DEVOPENED, USBDEVBUS_PATH);
1401
            goto found_devices;
1402
        }
1403
    found_devices:
1404
        if (!usb_fs_type) {
1405
            if (mon) {
1406
                monitor_printf(mon, "husb: unable to access USB devices\n");
1407
            }
1408
            return -ENOENT;
1409
        }
1410

    
1411
        /* the module setting (used later for opening devices) */
1412
        usb_host_device_path = qemu_mallocz(strlen(devpath)+1);
1413
        strcpy(usb_host_device_path, devpath);
1414
        if (mon) {
1415
            monitor_printf(mon, "husb: using %s file-system with %s\n",
1416
                           fs_type[usb_fs_type], usb_host_device_path);
1417
        }
1418
    }
1419

    
1420
    switch (usb_fs_type) {
1421
    case USB_FS_PROC:
1422
    case USB_FS_DEV:
1423
        ret = usb_host_scan_dev(opaque, func);
1424
        break;
1425
    case USB_FS_SYS:
1426
        ret = usb_host_scan_sys(opaque, func);
1427
        break;
1428
    default:
1429
        ret = -EINVAL;
1430
        break;
1431
    }
1432
    return ret;
1433
}
1434

    
1435
static QEMUTimer *usb_auto_timer;
1436

    
1437
static int usb_host_auto_scan(void *opaque, int bus_num, int addr,
1438
                              int class_id, int vendor_id, int product_id,
1439
                              const char *product_name, int speed)
1440
{
1441
    struct USBAutoFilter *f;
1442
    struct USBHostDevice *s;
1443

    
1444
    /* Ignore hubs */
1445
    if (class_id == 9)
1446
        return 0;
1447

    
1448
    QTAILQ_FOREACH(s, &hostdevs, next) {
1449
        f = &s->match;
1450

    
1451
        if (f->bus_num > 0 && f->bus_num != bus_num) {
1452
            continue;
1453
        }
1454
        if (f->addr > 0 && f->addr != addr) {
1455
            continue;
1456
        }
1457

    
1458
        if (f->vendor_id > 0 && f->vendor_id != vendor_id) {
1459
            continue;
1460
        }
1461

    
1462
        if (f->product_id > 0 && f->product_id != product_id) {
1463
            continue;
1464
        }
1465
        /* We got a match */
1466

    
1467
        /* Already attached ? */
1468
        if (s->fd != -1) {
1469
            return 0;
1470
        }
1471
        DPRINTF("husb: auto open: bus_num %d addr %d\n", bus_num, addr);
1472

    
1473
        usb_host_open(s, bus_num, addr, product_name);
1474
    }
1475

    
1476
    return 0;
1477
}
1478

    
1479
static void usb_host_auto_check(void *unused)
1480
{
1481
    struct USBHostDevice *s;
1482
    int unconnected = 0;
1483

    
1484
    usb_host_scan(NULL, usb_host_auto_scan);
1485

    
1486
    QTAILQ_FOREACH(s, &hostdevs, next) {
1487
        if (s->fd == -1) {
1488
            unconnected++;
1489
        }
1490
    }
1491

    
1492
    if (unconnected == 0) {
1493
        /* nothing to watch */
1494
        if (usb_auto_timer) {
1495
            qemu_del_timer(usb_auto_timer);
1496
        }
1497
        return;
1498
    }
1499

    
1500
    if (!usb_auto_timer) {
1501
        usb_auto_timer = qemu_new_timer(rt_clock, usb_host_auto_check, NULL);
1502
        if (!usb_auto_timer) {
1503
            return;
1504
        }
1505
    }
1506
    qemu_mod_timer(usb_auto_timer, qemu_get_clock(rt_clock) + 2000);
1507
}
1508

    
1509
/*
1510
 * Autoconnect filter
1511
 * Format:
1512
 *    auto:bus:dev[:vid:pid]
1513
 *    auto:bus.dev[:vid:pid]
1514
 *
1515
 *    bus  - bus number    (dec, * means any)
1516
 *    dev  - device number (dec, * means any)
1517
 *    vid  - vendor id     (hex, * means any)
1518
 *    pid  - product id    (hex, * means any)
1519
 *
1520
 *    See 'lsusb' output.
1521
 */
1522
static int parse_filter(const char *spec, struct USBAutoFilter *f)
1523
{
1524
    enum { BUS, DEV, VID, PID, DONE };
1525
    const char *p = spec;
1526
    int i;
1527

    
1528
    f->bus_num    = 0;
1529
    f->addr       = 0;
1530
    f->vendor_id  = 0;
1531
    f->product_id = 0;
1532

    
1533
    for (i = BUS; i < DONE; i++) {
1534
        p = strpbrk(p, ":.");
1535
        if (!p) {
1536
            break;
1537
        }
1538
        p++;
1539

    
1540
        if (*p == '*') {
1541
            continue;
1542
        }
1543
        switch(i) {
1544
        case BUS: f->bus_num = strtol(p, NULL, 10);    break;
1545
        case DEV: f->addr    = strtol(p, NULL, 10);    break;
1546
        case VID: f->vendor_id  = strtol(p, NULL, 16); break;
1547
        case PID: f->product_id = strtol(p, NULL, 16); break;
1548
        }
1549
    }
1550

    
1551
    if (i < DEV) {
1552
        fprintf(stderr, "husb: invalid auto filter spec %s\n", spec);
1553
        return -1;
1554
    }
1555

    
1556
    return 0;
1557
}
1558

    
1559
/**********************/
1560
/* USB host device info */
1561

    
1562
struct usb_class_info {
1563
    int class;
1564
    const char *class_name;
1565
};
1566

    
1567
static const struct usb_class_info usb_class_info[] = {
1568
    { USB_CLASS_AUDIO, "Audio"},
1569
    { USB_CLASS_COMM, "Communication"},
1570
    { USB_CLASS_HID, "HID"},
1571
    { USB_CLASS_HUB, "Hub" },
1572
    { USB_CLASS_PHYSICAL, "Physical" },
1573
    { USB_CLASS_PRINTER, "Printer" },
1574
    { USB_CLASS_MASS_STORAGE, "Storage" },
1575
    { USB_CLASS_CDC_DATA, "Data" },
1576
    { USB_CLASS_APP_SPEC, "Application Specific" },
1577
    { USB_CLASS_VENDOR_SPEC, "Vendor Specific" },
1578
    { USB_CLASS_STILL_IMAGE, "Still Image" },
1579
    { USB_CLASS_CSCID, "Smart Card" },
1580
    { USB_CLASS_CONTENT_SEC, "Content Security" },
1581
    { -1, NULL }
1582
};
1583

    
1584
static const char *usb_class_str(uint8_t class)
1585
{
1586
    const struct usb_class_info *p;
1587
    for(p = usb_class_info; p->class != -1; p++) {
1588
        if (p->class == class) {
1589
            break;
1590
        }
1591
    }
1592
    return p->class_name;
1593
}
1594

    
1595
static void usb_info_device(Monitor *mon, int bus_num, int addr, int class_id,
1596
                            int vendor_id, int product_id,
1597
                            const char *product_name,
1598
                            int speed)
1599
{
1600
    const char *class_str, *speed_str;
1601

    
1602
    switch(speed) {
1603
    case USB_SPEED_LOW:
1604
        speed_str = "1.5";
1605
        break;
1606
    case USB_SPEED_FULL:
1607
        speed_str = "12";
1608
        break;
1609
    case USB_SPEED_HIGH:
1610
        speed_str = "480";
1611
        break;
1612
    default:
1613
        speed_str = "?";
1614
        break;
1615
    }
1616

    
1617
    monitor_printf(mon, "  Device %d.%d, speed %s Mb/s\n",
1618
                bus_num, addr, speed_str);
1619
    class_str = usb_class_str(class_id);
1620
    if (class_str) {
1621
        monitor_printf(mon, "    %s:", class_str);
1622
    } else {
1623
        monitor_printf(mon, "    Class %02x:", class_id);
1624
    }
1625
    monitor_printf(mon, " USB device %04x:%04x", vendor_id, product_id);
1626
    if (product_name[0] != '\0') {
1627
        monitor_printf(mon, ", %s", product_name);
1628
    }
1629
    monitor_printf(mon, "\n");
1630
}
1631

    
1632
static int usb_host_info_device(void *opaque, int bus_num, int addr,
1633
                                int class_id,
1634
                                int vendor_id, int product_id,
1635
                                const char *product_name,
1636
                                int speed)
1637
{
1638
    Monitor *mon = opaque;
1639

    
1640
    usb_info_device(mon, bus_num, addr, class_id, vendor_id, product_id,
1641
                    product_name, speed);
1642
    return 0;
1643
}
1644

    
1645
static void dec2str(int val, char *str, size_t size)
1646
{
1647
    if (val == 0) {
1648
        snprintf(str, size, "*");
1649
    } else {
1650
        snprintf(str, size, "%d", val);
1651
    }
1652
}
1653

    
1654
static void hex2str(int val, char *str, size_t size)
1655
{
1656
    if (val == 0) {
1657
        snprintf(str, size, "*");
1658
    } else {
1659
        snprintf(str, size, "%04x", val);
1660
    }
1661
}
1662

    
1663
void usb_host_info(Monitor *mon)
1664
{
1665
    struct USBAutoFilter *f;
1666
    struct USBHostDevice *s;
1667

    
1668
    usb_host_scan(mon, usb_host_info_device);
1669

    
1670
    if (QTAILQ_EMPTY(&hostdevs)) {
1671
        return;
1672
    }
1673

    
1674
    monitor_printf(mon, "  Auto filters:\n");
1675
    QTAILQ_FOREACH(s, &hostdevs, next) {
1676
        char bus[10], addr[10], vid[10], pid[10];
1677
        f = &s->match;
1678
        dec2str(f->bus_num, bus, sizeof(bus));
1679
        dec2str(f->addr, addr, sizeof(addr));
1680
        hex2str(f->vendor_id, vid, sizeof(vid));
1681
        hex2str(f->product_id, pid, sizeof(pid));
1682
        monitor_printf(mon, "    Device %s.%s ID %s:%s\n",
1683
                       bus, addr, vid, pid);
1684
    }
1685
}