Statistics
| Branch: | Revision:

root / hw / usb-msd.c @ d3ac1a87

History | View | Annotate | Download (17.7 kB)

1
/*
2
 * USB Mass Storage Device emulation
3
 *
4
 * Copyright (c) 2006 CodeSourcery.
5
 * Written by Paul Brook
6
 *
7
 * This code is licensed under the LGPL.
8
 */
9

    
10
#include "qemu-common.h"
11
#include "qemu-option.h"
12
#include "qemu-config.h"
13
#include "usb.h"
14
#include "usb-desc.h"
15
#include "scsi.h"
16
#include "console.h"
17
#include "monitor.h"
18
#include "sysemu.h"
19
#include "blockdev.h"
20

    
21
//#define DEBUG_MSD
22

    
23
#ifdef DEBUG_MSD
24
#define DPRINTF(fmt, ...) \
25
do { printf("usb-msd: " fmt , ## __VA_ARGS__); } while (0)
26
#else
27
#define DPRINTF(fmt, ...) do {} while(0)
28
#endif
29

    
30
/* USB requests.  */
31
#define MassStorageReset  0xff
32
#define GetMaxLun         0xfe
33

    
34
enum USBMSDMode {
35
    USB_MSDM_CBW, /* Command Block.  */
36
    USB_MSDM_DATAOUT, /* Transfer data to device.  */
37
    USB_MSDM_DATAIN, /* Transfer data from device.  */
38
    USB_MSDM_CSW /* Command Status.  */
39
};
40

    
41
typedef struct {
42
    USBDevice dev;
43
    enum USBMSDMode mode;
44
    uint32_t scsi_len;
45
    uint8_t *scsi_buf;
46
    uint32_t data_len;
47
    uint32_t residue;
48
    uint32_t tag;
49
    SCSIRequest *req;
50
    SCSIBus bus;
51
    BlockConf conf;
52
    char *serial;
53
    SCSIDevice *scsi_dev;
54
    uint32_t removable;
55
    int result;
56
    /* For async completion.  */
57
    USBPacket *packet;
58
} MSDState;
59

    
60
struct usb_msd_cbw {
61
    uint32_t sig;
62
    uint32_t tag;
63
    uint32_t data_len;
64
    uint8_t flags;
65
    uint8_t lun;
66
    uint8_t cmd_len;
67
    uint8_t cmd[16];
68
};
69

    
70
struct usb_msd_csw {
71
    uint32_t sig;
72
    uint32_t tag;
73
    uint32_t residue;
74
    uint8_t status;
75
};
76

    
77
enum {
78
    STR_MANUFACTURER = 1,
79
    STR_PRODUCT,
80
    STR_SERIALNUMBER,
81
    STR_CONFIG_FULL,
82
    STR_CONFIG_HIGH,
83
};
84

    
85
static const USBDescStrings desc_strings = {
86
    [STR_MANUFACTURER] = "QEMU " QEMU_VERSION,
87
    [STR_PRODUCT]      = "QEMU USB HARDDRIVE",
88
    [STR_SERIALNUMBER] = "1",
89
    [STR_CONFIG_FULL]  = "Full speed config (usb 1.1)",
90
    [STR_CONFIG_HIGH]  = "High speed config (usb 2.0)",
91
};
92

    
93
static const USBDescIface desc_iface_full = {
94
    .bInterfaceNumber              = 0,
95
    .bNumEndpoints                 = 2,
96
    .bInterfaceClass               = USB_CLASS_MASS_STORAGE,
97
    .bInterfaceSubClass            = 0x06, /* SCSI */
98
    .bInterfaceProtocol            = 0x50, /* Bulk */
99
    .eps = (USBDescEndpoint[]) {
100
        {
101
            .bEndpointAddress      = USB_DIR_IN | 0x01,
102
            .bmAttributes          = USB_ENDPOINT_XFER_BULK,
103
            .wMaxPacketSize        = 64,
104
        },{
105
            .bEndpointAddress      = USB_DIR_OUT | 0x02,
106
            .bmAttributes          = USB_ENDPOINT_XFER_BULK,
107
            .wMaxPacketSize        = 64,
108
        },
109
    }
110
};
111

    
112
static const USBDescDevice desc_device_full = {
113
    .bcdUSB                        = 0x0200,
114
    .bMaxPacketSize0               = 8,
115
    .bNumConfigurations            = 1,
116
    .confs = (USBDescConfig[]) {
117
        {
118
            .bNumInterfaces        = 1,
119
            .bConfigurationValue   = 1,
120
            .iConfiguration        = STR_CONFIG_FULL,
121
            .bmAttributes          = 0xc0,
122
            .nif = 1,
123
            .ifs = &desc_iface_full,
124
        },
125
    },
126
};
127

    
128
static const USBDescIface desc_iface_high = {
129
    .bInterfaceNumber              = 0,
130
    .bNumEndpoints                 = 2,
131
    .bInterfaceClass               = USB_CLASS_MASS_STORAGE,
132
    .bInterfaceSubClass            = 0x06, /* SCSI */
133
    .bInterfaceProtocol            = 0x50, /* Bulk */
134
    .eps = (USBDescEndpoint[]) {
135
        {
136
            .bEndpointAddress      = USB_DIR_IN | 0x01,
137
            .bmAttributes          = USB_ENDPOINT_XFER_BULK,
138
            .wMaxPacketSize        = 512,
139
        },{
140
            .bEndpointAddress      = USB_DIR_OUT | 0x02,
141
            .bmAttributes          = USB_ENDPOINT_XFER_BULK,
142
            .wMaxPacketSize        = 512,
143
        },
144
    }
145
};
146

    
147
static const USBDescDevice desc_device_high = {
148
    .bcdUSB                        = 0x0200,
149
    .bMaxPacketSize0               = 64,
150
    .bNumConfigurations            = 1,
151
    .confs = (USBDescConfig[]) {
152
        {
153
            .bNumInterfaces        = 1,
154
            .bConfigurationValue   = 1,
155
            .iConfiguration        = STR_CONFIG_HIGH,
156
            .bmAttributes          = 0xc0,
157
            .nif = 1,
158
            .ifs = &desc_iface_high,
159
        },
160
    },
161
};
162

    
163
static const USBDesc desc = {
164
    .id = {
165
        .idVendor          = 0,
166
        .idProduct         = 0,
167
        .bcdDevice         = 0,
168
        .iManufacturer     = STR_MANUFACTURER,
169
        .iProduct          = STR_PRODUCT,
170
        .iSerialNumber     = STR_SERIALNUMBER,
171
    },
172
    .full = &desc_device_full,
173
    .high = &desc_device_high,
174
    .str  = desc_strings,
175
};
176

    
177
static void usb_msd_copy_data(MSDState *s, USBPacket *p)
178
{
179
    uint32_t len;
180
    len = p->iov.size - p->result;
181
    if (len > s->scsi_len)
182
        len = s->scsi_len;
183
    usb_packet_copy(p, s->scsi_buf, len);
184
    s->scsi_len -= len;
185
    s->scsi_buf += len;
186
    s->data_len -= len;
187
    if (s->scsi_len == 0 || s->data_len == 0) {
188
        scsi_req_continue(s->req);
189
    }
190
}
191

    
192
static void usb_msd_send_status(MSDState *s, USBPacket *p)
193
{
194
    struct usb_msd_csw csw;
195
    int len;
196

    
197
    csw.sig = cpu_to_le32(0x53425355);
198
    csw.tag = cpu_to_le32(s->tag);
199
    csw.residue = s->residue;
200
    csw.status = s->result;
201

    
202
    len = MIN(sizeof(csw), p->iov.size);
203
    usb_packet_copy(p, &csw, len);
204
    p->result = len;
205
}
206

    
207
static void usb_msd_transfer_data(SCSIRequest *req, uint32_t len)
208
{
209
    MSDState *s = DO_UPCAST(MSDState, dev.qdev, req->bus->qbus.parent);
210
    USBPacket *p = s->packet;
211

    
212
    assert((s->mode == USB_MSDM_DATAOUT) == (req->cmd.mode == SCSI_XFER_TO_DEV));
213
    s->scsi_len = len;
214
    s->scsi_buf = scsi_req_get_buf(req);
215
    if (p) {
216
        usb_msd_copy_data(s, p);
217
        p = s->packet;
218
        if (p && p->result == p->iov.size) {
219
            /* Set s->packet to NULL before calling usb_packet_complete
220
               because another request may be issued before
221
               usb_packet_complete returns.  */
222
            DPRINTF("Packet complete %p\n", p);
223
            s->packet = NULL;
224
            usb_packet_complete(&s->dev, p);
225
        }
226
    }
227
}
228

    
229
static void usb_msd_command_complete(SCSIRequest *req, uint32_t status)
230
{
231
    MSDState *s = DO_UPCAST(MSDState, dev.qdev, req->bus->qbus.parent);
232
    USBPacket *p = s->packet;
233

    
234
    DPRINTF("Command complete %d\n", status);
235
    s->residue = s->data_len;
236
    s->result = status != 0;
237
    if (s->packet) {
238
        if (s->data_len == 0 && s->mode == USB_MSDM_DATAOUT) {
239
            /* A deferred packet with no write data remaining must be
240
               the status read packet.  */
241
            usb_msd_send_status(s, p);
242
            s->mode = USB_MSDM_CBW;
243
        } else {
244
            if (s->data_len) {
245
                int len = (p->iov.size - p->result);
246
                usb_packet_skip(p, len);
247
                s->data_len -= len;
248
            }
249
            if (s->data_len == 0) {
250
                s->mode = USB_MSDM_CSW;
251
            }
252
        }
253
        s->packet = NULL;
254
        usb_packet_complete(&s->dev, p);
255
    } else if (s->data_len == 0) {
256
        s->mode = USB_MSDM_CSW;
257
    }
258
    scsi_req_unref(req);
259
    s->req = NULL;
260
}
261

    
262
static void usb_msd_request_cancelled(SCSIRequest *req)
263
{
264
    MSDState *s = DO_UPCAST(MSDState, dev.qdev, req->bus->qbus.parent);
265

    
266
    if (req == s->req) {
267
        scsi_req_unref(s->req);
268
        s->req = NULL;
269
        s->packet = NULL;
270
        s->scsi_len = 0;
271
    }
272
}
273

    
274
static void usb_msd_handle_reset(USBDevice *dev)
275
{
276
    MSDState *s = (MSDState *)dev;
277

    
278
    DPRINTF("Reset\n");
279
    s->mode = USB_MSDM_CBW;
280
}
281

    
282
static int usb_msd_handle_control(USBDevice *dev, USBPacket *p,
283
               int request, int value, int index, int length, uint8_t *data)
284
{
285
    MSDState *s = (MSDState *)dev;
286
    int ret;
287

    
288
    ret = usb_desc_handle_control(dev, p, request, value, index, length, data);
289
    if (ret >= 0) {
290
        return ret;
291
    }
292

    
293
    ret = 0;
294
    switch (request) {
295
    case DeviceRequest | USB_REQ_GET_INTERFACE:
296
        data[0] = 0;
297
        ret = 1;
298
        break;
299
    case DeviceOutRequest | USB_REQ_SET_INTERFACE:
300
        ret = 0;
301
        break;
302
    case EndpointOutRequest | USB_REQ_CLEAR_FEATURE:
303
        ret = 0;
304
        break;
305
    case InterfaceOutRequest | USB_REQ_SET_INTERFACE:
306
        ret = 0;
307
        break;
308
        /* Class specific requests.  */
309
    case ClassInterfaceOutRequest | MassStorageReset:
310
        /* Reset state ready for the next CBW.  */
311
        s->mode = USB_MSDM_CBW;
312
        ret = 0;
313
        break;
314
    case ClassInterfaceRequest | GetMaxLun:
315
        data[0] = 0;
316
        ret = 1;
317
        break;
318
    default:
319
        ret = USB_RET_STALL;
320
        break;
321
    }
322
    return ret;
323
}
324

    
325
static void usb_msd_cancel_io(USBDevice *dev, USBPacket *p)
326
{
327
    MSDState *s = DO_UPCAST(MSDState, dev, dev);
328

    
329
    if (s->req) {
330
        scsi_req_cancel(s->req);
331
    }
332
}
333

    
334
static int usb_msd_handle_data(USBDevice *dev, USBPacket *p)
335
{
336
    MSDState *s = (MSDState *)dev;
337
    int ret = 0;
338
    struct usb_msd_cbw cbw;
339
    uint8_t devep = p->devep;
340

    
341
    switch (p->pid) {
342
    case USB_TOKEN_OUT:
343
        if (devep != 2)
344
            goto fail;
345

    
346
        switch (s->mode) {
347
        case USB_MSDM_CBW:
348
            if (p->iov.size != 31) {
349
                fprintf(stderr, "usb-msd: Bad CBW size");
350
                goto fail;
351
            }
352
            usb_packet_copy(p, &cbw, 31);
353
            if (le32_to_cpu(cbw.sig) != 0x43425355) {
354
                fprintf(stderr, "usb-msd: Bad signature %08x\n",
355
                        le32_to_cpu(cbw.sig));
356
                goto fail;
357
            }
358
            DPRINTF("Command on LUN %d\n", cbw.lun);
359
            if (cbw.lun != 0) {
360
                fprintf(stderr, "usb-msd: Bad LUN %d\n", cbw.lun);
361
                goto fail;
362
            }
363
            s->tag = le32_to_cpu(cbw.tag);
364
            s->data_len = le32_to_cpu(cbw.data_len);
365
            if (s->data_len == 0) {
366
                s->mode = USB_MSDM_CSW;
367
            } else if (cbw.flags & 0x80) {
368
                s->mode = USB_MSDM_DATAIN;
369
            } else {
370
                s->mode = USB_MSDM_DATAOUT;
371
            }
372
            DPRINTF("Command tag 0x%x flags %08x len %d data %d\n",
373
                    s->tag, cbw.flags, cbw.cmd_len, s->data_len);
374
            s->residue = 0;
375
            s->scsi_len = 0;
376
            s->req = scsi_req_new(s->scsi_dev, s->tag, 0, cbw.cmd, NULL);
377
            scsi_req_enqueue(s->req);
378
            /* ??? Should check that USB and SCSI data transfer
379
               directions match.  */
380
            if (s->mode != USB_MSDM_CSW && s->residue == 0) {
381
                scsi_req_continue(s->req);
382
            }
383
            ret = p->result;
384
            break;
385

    
386
        case USB_MSDM_DATAOUT:
387
            DPRINTF("Data out %zd/%d\n", p->iov.size, s->data_len);
388
            if (p->iov.size > s->data_len) {
389
                goto fail;
390
            }
391

    
392
            if (s->scsi_len) {
393
                usb_msd_copy_data(s, p);
394
            }
395
            if (s->residue) {
396
                int len = p->iov.size - p->result;
397
                if (len) {
398
                    usb_packet_skip(p, len);
399
                    s->data_len -= len;
400
                    if (s->data_len == 0) {
401
                        s->mode = USB_MSDM_CSW;
402
                    }
403
                }
404
            }
405
            if (p->result < p->iov.size) {
406
                DPRINTF("Deferring packet %p\n", p);
407
                s->packet = p;
408
                ret = USB_RET_ASYNC;
409
            } else {
410
                ret = p->result;
411
            }
412
            break;
413

    
414
        default:
415
            DPRINTF("Unexpected write (len %zd)\n", p->iov.size);
416
            goto fail;
417
        }
418
        break;
419

    
420
    case USB_TOKEN_IN:
421
        if (devep != 1)
422
            goto fail;
423

    
424
        switch (s->mode) {
425
        case USB_MSDM_DATAOUT:
426
            if (s->data_len != 0 || p->iov.size < 13) {
427
                goto fail;
428
            }
429
            /* Waiting for SCSI write to complete.  */
430
            s->packet = p;
431
            ret = USB_RET_ASYNC;
432
            break;
433

    
434
        case USB_MSDM_CSW:
435
            DPRINTF("Command status %d tag 0x%x, len %zd\n",
436
                    s->result, s->tag, p->iov.size);
437
            if (p->iov.size < 13) {
438
                goto fail;
439
            }
440

    
441
            usb_msd_send_status(s, p);
442
            s->mode = USB_MSDM_CBW;
443
            ret = 13;
444
            break;
445

    
446
        case USB_MSDM_DATAIN:
447
            DPRINTF("Data in %zd/%d, scsi_len %d\n",
448
                    p->iov.size, s->data_len, s->scsi_len);
449
            if (s->scsi_len) {
450
                usb_msd_copy_data(s, p);
451
            }
452
            if (s->residue) {
453
                int len = p->iov.size - p->result;
454
                if (len) {
455
                    usb_packet_skip(p, len);
456
                    s->data_len -= len;
457
                    if (s->data_len == 0) {
458
                        s->mode = USB_MSDM_CSW;
459
                    }
460
                }
461
            }
462
            if (p->result < p->iov.size) {
463
                DPRINTF("Deferring packet %p\n", p);
464
                s->packet = p;
465
                ret = USB_RET_ASYNC;
466
            } else {
467
                ret = p->result;
468
            }
469
            break;
470

    
471
        default:
472
            DPRINTF("Unexpected read (len %zd)\n", p->iov.size);
473
            goto fail;
474
        }
475
        break;
476

    
477
    default:
478
        DPRINTF("Bad token\n");
479
    fail:
480
        ret = USB_RET_STALL;
481
        break;
482
    }
483

    
484
    return ret;
485
}
486

    
487
static void usb_msd_password_cb(void *opaque, int err)
488
{
489
    MSDState *s = opaque;
490

    
491
    if (!err)
492
        err = usb_device_attach(&s->dev);
493

    
494
    if (err)
495
        qdev_unplug(&s->dev.qdev);
496
}
497

    
498
static const struct SCSIBusOps usb_msd_scsi_ops = {
499
    .transfer_data = usb_msd_transfer_data,
500
    .complete = usb_msd_command_complete,
501
    .cancel = usb_msd_request_cancelled
502
};
503

    
504
static int usb_msd_initfn(USBDevice *dev)
505
{
506
    MSDState *s = DO_UPCAST(MSDState, dev, dev);
507
    BlockDriverState *bs = s->conf.bs;
508
    DriveInfo *dinfo;
509

    
510
    if (!bs) {
511
        error_report("usb-msd: drive property not set");
512
        return -1;
513
    }
514

    
515
    /*
516
     * Hack alert: this pretends to be a block device, but it's really
517
     * a SCSI bus that can serve only a single device, which it
518
     * creates automatically.  But first it needs to detach from its
519
     * blockdev, or else scsi_bus_legacy_add_drive() dies when it
520
     * attaches again.
521
     *
522
     * The hack is probably a bad idea.
523
     */
524
    bdrv_detach_dev(bs, &s->dev.qdev);
525
    s->conf.bs = NULL;
526

    
527
    if (!s->serial) {
528
        /* try to fall back to value set with legacy -drive serial=... */
529
        dinfo = drive_get_by_blockdev(bs);
530
        if (*dinfo->serial) {
531
            s->serial = strdup(dinfo->serial);
532
        }
533
    }
534
    if (s->serial) {
535
        usb_desc_set_string(dev, STR_SERIALNUMBER, s->serial);
536
    }
537

    
538
    usb_desc_init(dev);
539
    scsi_bus_new(&s->bus, &s->dev.qdev, 0, 1, &usb_msd_scsi_ops);
540
    s->scsi_dev = scsi_bus_legacy_add_drive(&s->bus, bs, 0, !!s->removable);
541
    if (!s->scsi_dev) {
542
        return -1;
543
    }
544
    s->bus.qbus.allow_hotplug = 0;
545
    usb_msd_handle_reset(dev);
546

    
547
    if (bdrv_key_required(bs)) {
548
        if (cur_mon) {
549
            monitor_read_bdrv_key_start(cur_mon, bs, usb_msd_password_cb, s);
550
            s->dev.auto_attach = 0;
551
        } else {
552
            autostart = 0;
553
        }
554
    }
555

    
556
    add_boot_device_path(s->conf.bootindex, &dev->qdev, "/disk@0,0");
557
    return 0;
558
}
559

    
560
static USBDevice *usb_msd_init(const char *filename)
561
{
562
    static int nr=0;
563
    char id[8];
564
    QemuOpts *opts;
565
    DriveInfo *dinfo;
566
    USBDevice *dev;
567
    const char *p1;
568
    char fmt[32];
569

    
570
    /* parse -usbdevice disk: syntax into drive opts */
571
    snprintf(id, sizeof(id), "usb%d", nr++);
572
    opts = qemu_opts_create(qemu_find_opts("drive"), id, 0);
573

    
574
    p1 = strchr(filename, ':');
575
    if (p1++) {
576
        const char *p2;
577

    
578
        if (strstart(filename, "format=", &p2)) {
579
            int len = MIN(p1 - p2, sizeof(fmt));
580
            pstrcpy(fmt, len, p2);
581
            qemu_opt_set(opts, "format", fmt);
582
        } else if (*filename != ':') {
583
            printf("unrecognized USB mass-storage option %s\n", filename);
584
            return NULL;
585
        }
586
        filename = p1;
587
    }
588
    if (!*filename) {
589
        printf("block device specification needed\n");
590
        return NULL;
591
    }
592
    qemu_opt_set(opts, "file", filename);
593
    qemu_opt_set(opts, "if", "none");
594

    
595
    /* create host drive */
596
    dinfo = drive_init(opts, 0);
597
    if (!dinfo) {
598
        qemu_opts_del(opts);
599
        return NULL;
600
    }
601

    
602
    /* create guest device */
603
    dev = usb_create(NULL /* FIXME */, "usb-storage");
604
    if (!dev) {
605
        return NULL;
606
    }
607
    if (qdev_prop_set_drive(&dev->qdev, "drive", dinfo->bdrv) < 0) {
608
        qdev_free(&dev->qdev);
609
        return NULL;
610
    }
611
    if (qdev_init(&dev->qdev) < 0)
612
        return NULL;
613

    
614
    return dev;
615
}
616

    
617
static const VMStateDescription vmstate_usb_msd = {
618
    .name = "usb-storage",
619
    .unmigratable = 1, /* FIXME: handle transactions which are in flight */
620
    .version_id = 1,
621
    .minimum_version_id = 1,
622
    .fields = (VMStateField []) {
623
        VMSTATE_USB_DEVICE(dev, MSDState),
624
        VMSTATE_END_OF_LIST()
625
    }
626
};
627

    
628
static struct USBDeviceInfo msd_info = {
629
    .product_desc   = "QEMU USB MSD",
630
    .qdev.name      = "usb-storage",
631
    .qdev.fw_name      = "storage",
632
    .qdev.size      = sizeof(MSDState),
633
    .qdev.vmsd      = &vmstate_usb_msd,
634
    .usb_desc       = &desc,
635
    .init           = usb_msd_initfn,
636
    .handle_packet  = usb_generic_handle_packet,
637
    .cancel_packet  = usb_msd_cancel_io,
638
    .handle_attach  = usb_desc_attach,
639
    .handle_reset   = usb_msd_handle_reset,
640
    .handle_control = usb_msd_handle_control,
641
    .handle_data    = usb_msd_handle_data,
642
    .usbdevice_name = "disk",
643
    .usbdevice_init = usb_msd_init,
644
    .qdev.props     = (Property[]) {
645
        DEFINE_BLOCK_PROPERTIES(MSDState, conf),
646
        DEFINE_PROP_STRING("serial", MSDState, serial),
647
        DEFINE_PROP_BIT("removable", MSDState, removable, 0, false),
648
        DEFINE_PROP_END_OF_LIST(),
649
    },
650
};
651

    
652
static void usb_msd_register_devices(void)
653
{
654
    usb_qdev_register(&msd_info);
655
}
656
device_init(usb_msd_register_devices)