Statistics
| Branch: | Revision:

root / hw / usb-msd.c @ fc4f0754

History | View | Annotate | Download (17.4 kB)

1
/*
2
 * USB Mass Storage Device emulation
3
 *
4
 * Copyright (c) 2006 CodeSourcery.
5
 * Written by Paul Brook
6
 *
7
 * This code is licenced 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 usb_len;
47
    uint8_t *usb_buf;
48
    uint32_t data_len;
49
    uint32_t residue;
50
    uint32_t tag;
51
    SCSIRequest *req;
52
    SCSIBus bus;
53
    BlockConf conf;
54
    SCSIDevice *scsi_dev;
55
    uint32_t removable;
56
    int result;
57
    /* For async completion.  */
58
    USBPacket *packet;
59
} MSDState;
60

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

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

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

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

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

    
113
static const USBDescDevice desc_device_full = {
114
    .bcdUSB                        = 0x0200,
115
    .bMaxPacketSize0               = 8,
116
    .bNumConfigurations            = 1,
117
    .confs = (USBDescConfig[]) {
118
        {
119
            .bNumInterfaces        = 1,
120
            .bConfigurationValue   = 1,
121
            .iConfiguration        = STR_CONFIG_FULL,
122
            .bmAttributes          = 0xc0,
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
            .ifs = &desc_iface_high,
158
        },
159
    },
160
};
161

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

    
176
static void usb_msd_copy_data(MSDState *s)
177
{
178
    uint32_t len;
179
    len = s->usb_len;
180
    if (len > s->scsi_len)
181
        len = s->scsi_len;
182
    if (s->mode == USB_MSDM_DATAIN) {
183
        memcpy(s->usb_buf, s->scsi_buf, len);
184
    } else {
185
        memcpy(s->scsi_buf, s->usb_buf, len);
186
    }
187
    s->usb_len -= len;
188
    s->scsi_len -= len;
189
    s->usb_buf += len;
190
    s->scsi_buf += len;
191
    s->data_len -= len;
192
    if (s->scsi_len == 0 || s->data_len == 0) {
193
        if (s->mode == USB_MSDM_DATAIN) {
194
            s->scsi_dev->info->read_data(s->req);
195
        } else if (s->mode == USB_MSDM_DATAOUT) {
196
            s->scsi_dev->info->write_data(s->req);
197
        }
198
    }
199
}
200

    
201
static void usb_msd_send_status(MSDState *s, USBPacket *p)
202
{
203
    struct usb_msd_csw csw;
204
    int len;
205

    
206
    csw.sig = cpu_to_le32(0x53425355);
207
    csw.tag = cpu_to_le32(s->tag);
208
    csw.residue = s->residue;
209
    csw.status = s->result;
210

    
211
    len = MIN(sizeof(csw), p->len);
212
    memcpy(p->data, &csw, len);
213
}
214

    
215
static void usb_msd_command_complete(SCSIRequest *req, int reason, uint32_t arg)
216
{
217
    MSDState *s = DO_UPCAST(MSDState, dev.qdev, req->bus->qbus.parent);
218
    USBPacket *p = s->packet;
219

    
220
    if (req->tag != s->tag) {
221
        fprintf(stderr, "usb-msd: Unexpected SCSI Tag 0x%x\n", req->tag);
222
    }
223
    if (reason == SCSI_REASON_DONE) {
224
        DPRINTF("Command complete %d\n", arg);
225
        s->residue = s->data_len;
226
        s->result = arg != 0;
227
        if (s->packet) {
228
            if (s->data_len == 0 && s->mode == USB_MSDM_DATAOUT) {
229
                /* A deferred packet with no write data remaining must be
230
                   the status read packet.  */
231
                usb_msd_send_status(s, p);
232
                s->mode = USB_MSDM_CBW;
233
            } else {
234
                if (s->data_len) {
235
                    s->data_len -= s->usb_len;
236
                    if (s->mode == USB_MSDM_DATAIN)
237
                        memset(s->usb_buf, 0, s->usb_len);
238
                    s->usb_len = 0;
239
                }
240
                if (s->data_len == 0)
241
                    s->mode = USB_MSDM_CSW;
242
            }
243
            s->packet = NULL;
244
            usb_packet_complete(&s->dev, p);
245
        } else if (s->data_len == 0) {
246
            s->mode = USB_MSDM_CSW;
247
        }
248
        scsi_req_unref(req);
249
        s->req = NULL;
250
        return;
251
    }
252
    s->scsi_len = arg;
253
    s->scsi_buf = s->scsi_dev->info->get_buf(req);
254
    if (p) {
255
        usb_msd_copy_data(s);
256
        if (s->usb_len == 0) {
257
            /* Set s->packet to NULL before calling usb_packet_complete
258
               because another request may be issued before
259
               usb_packet_complete returns.  */
260
            DPRINTF("Packet complete %p\n", p);
261
            s->packet = NULL;
262
            usb_packet_complete(&s->dev, p);
263
        }
264
    }
265
}
266

    
267
static void usb_msd_request_cancelled(SCSIRequest *req)
268
{
269
    MSDState *s = DO_UPCAST(MSDState, dev.qdev, req->bus->qbus.parent);
270

    
271
    if (req == s->req) {
272
        scsi_req_unref(s->req);
273
        s->req = NULL;
274
        s->packet = NULL;
275
        s->scsi_len = 0;
276
    }
277
}
278

    
279
static void usb_msd_handle_reset(USBDevice *dev)
280
{
281
    MSDState *s = (MSDState *)dev;
282

    
283
    DPRINTF("Reset\n");
284
    s->mode = USB_MSDM_CBW;
285
}
286

    
287
static int usb_msd_handle_control(USBDevice *dev, int request, int value,
288
                                  int index, int length, uint8_t *data)
289
{
290
    MSDState *s = (MSDState *)dev;
291
    int ret;
292

    
293
    ret = usb_desc_handle_control(dev, request, value, index, length, data);
294
    if (ret >= 0) {
295
        return ret;
296
    }
297

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

    
330
static void usb_msd_cancel_io(USBPacket *p, void *opaque)
331
{
332
    MSDState *s = opaque;
333
    scsi_req_cancel(s->req);
334
}
335

    
336
static int usb_msd_handle_data(USBDevice *dev, USBPacket *p)
337
{
338
    MSDState *s = (MSDState *)dev;
339
    int ret = 0;
340
    struct usb_msd_cbw cbw;
341
    uint8_t devep = p->devep;
342
    uint8_t *data = p->data;
343
    int len = p->len;
344

    
345
    switch (p->pid) {
346
    case USB_TOKEN_OUT:
347
        if (devep != 2)
348
            goto fail;
349

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

    
394
        case USB_MSDM_DATAOUT:
395
            DPRINTF("Data out %d/%d\n", len, s->data_len);
396
            if (len > s->data_len)
397
                goto fail;
398

    
399
            s->usb_buf = data;
400
            s->usb_len = len;
401
            if (s->scsi_len) {
402
                usb_msd_copy_data(s);
403
            }
404
            if (s->residue && s->usb_len) {
405
                s->data_len -= s->usb_len;
406
                if (s->data_len == 0)
407
                    s->mode = USB_MSDM_CSW;
408
                s->usb_len = 0;
409
            }
410
            if (s->usb_len) {
411
                DPRINTF("Deferring packet %p\n", p);
412
                usb_defer_packet(p, usb_msd_cancel_io, s);
413
                s->packet = p;
414
                ret = USB_RET_ASYNC;
415
            } else {
416
                ret = len;
417
            }
418
            break;
419

    
420
        default:
421
            DPRINTF("Unexpected write (len %d)\n", len);
422
            goto fail;
423
        }
424
        break;
425

    
426
    case USB_TOKEN_IN:
427
        if (devep != 1)
428
            goto fail;
429

    
430
        switch (s->mode) {
431
        case USB_MSDM_DATAOUT:
432
            if (s->data_len != 0 || len < 13)
433
                goto fail;
434
            /* Waiting for SCSI write to complete.  */
435
            usb_defer_packet(p, usb_msd_cancel_io, s);
436
            s->packet = p;
437
            ret = USB_RET_ASYNC;
438
            break;
439

    
440
        case USB_MSDM_CSW:
441
            DPRINTF("Command status %d tag 0x%x, len %d\n",
442
                    s->result, s->tag, len);
443
            if (len < 13)
444
                goto fail;
445

    
446
            usb_msd_send_status(s, p);
447
            s->mode = USB_MSDM_CBW;
448
            ret = 13;
449
            break;
450

    
451
        case USB_MSDM_DATAIN:
452
            DPRINTF("Data in %d/%d, scsi_len %d\n", len, s->data_len, s->scsi_len);
453
            if (len > s->data_len)
454
                len = s->data_len;
455
            s->usb_buf = data;
456
            s->usb_len = len;
457
            if (s->scsi_len) {
458
                usb_msd_copy_data(s);
459
            }
460
            if (s->residue && s->usb_len) {
461
                s->data_len -= s->usb_len;
462
                memset(s->usb_buf, 0, s->usb_len);
463
                if (s->data_len == 0)
464
                    s->mode = USB_MSDM_CSW;
465
                s->usb_len = 0;
466
            }
467
            if (s->usb_len) {
468
                DPRINTF("Deferring packet %p\n", p);
469
                usb_defer_packet(p, usb_msd_cancel_io, s);
470
                s->packet = p;
471
                ret = USB_RET_ASYNC;
472
            } else {
473
                ret = len;
474
            }
475
            break;
476

    
477
        default:
478
            DPRINTF("Unexpected read (len %d)\n", len);
479
            goto fail;
480
        }
481
        break;
482

    
483
    default:
484
        DPRINTF("Bad token\n");
485
    fail:
486
        ret = USB_RET_STALL;
487
        break;
488
    }
489

    
490
    return ret;
491
}
492

    
493
static void usb_msd_password_cb(void *opaque, int err)
494
{
495
    MSDState *s = opaque;
496

    
497
    if (!err)
498
        usb_device_attach(&s->dev);
499
    else
500
        qdev_unplug(&s->dev.qdev);
501
}
502

    
503
static const struct SCSIBusOps usb_msd_scsi_ops = {
504
    .complete = usb_msd_command_complete,
505
    .cancel = usb_msd_request_cancelled
506
};
507

    
508
static int usb_msd_initfn(USBDevice *dev)
509
{
510
    MSDState *s = DO_UPCAST(MSDState, dev, dev);
511
    BlockDriverState *bs = s->conf.bs;
512
    DriveInfo *dinfo;
513

    
514
    if (!bs) {
515
        error_report("usb-msd: drive property not set");
516
        return -1;
517
    }
518

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

    
531
    dinfo = drive_get_by_blockdev(bs);
532
    if (dinfo && dinfo->serial) {
533
        usb_desc_set_string(dev, STR_SERIALNUMBER, dinfo->serial);
534
    }
535

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

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

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

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

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

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

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

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

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

    
612
    return dev;
613
}
614

    
615
static struct USBDeviceInfo msd_info = {
616
    .product_desc   = "QEMU USB MSD",
617
    .qdev.name      = "usb-storage",
618
    .qdev.fw_name      = "storage",
619
    .qdev.size      = sizeof(MSDState),
620
    .usb_desc       = &desc,
621
    .init           = usb_msd_initfn,
622
    .handle_packet  = usb_generic_handle_packet,
623
    .handle_attach  = usb_desc_attach,
624
    .handle_reset   = usb_msd_handle_reset,
625
    .handle_control = usb_msd_handle_control,
626
    .handle_data    = usb_msd_handle_data,
627
    .usbdevice_name = "disk",
628
    .usbdevice_init = usb_msd_init,
629
    .qdev.props     = (Property[]) {
630
        DEFINE_BLOCK_PROPERTIES(MSDState, conf),
631
        DEFINE_PROP_BIT("removable", MSDState, removable, 0, false),
632
        DEFINE_PROP_END_OF_LIST(),
633
    },
634
};
635

    
636
static void usb_msd_register_devices(void)
637
{
638
    usb_qdev_register(&msd_info);
639
}
640
device_init(usb_msd_register_devices)