blockdev.c 79.8 KB
Newer Older
1 2 3 4 5 6 7
/*
 * QEMU host block devices
 *
 * Copyright (c) 2003-2008 Fabrice Bellard
 *
 * This work is licensed under the terms of the GNU GPL, version 2 or
 * later.  See the COPYING file in the top-level directory.
8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30
 *
 * This file incorporates work covered by the following copyright and
 * permission notice:
 *
 * Copyright (c) 2003-2008 Fabrice Bellard
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
 * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 * THE SOFTWARE.
31 32
 */

Markus Armbruster's avatar
Markus Armbruster committed
33
#include "sysemu/block-backend.h"
34
#include "sysemu/blockdev.h"
Paolo Bonzini's avatar
Paolo Bonzini committed
35
#include "hw/block/block.h"
36
#include "block/blockjob.h"
37
#include "monitor/monitor.h"
38 39
#include "qemu/option.h"
#include "qemu/config-file.h"
40
#include "qapi/qmp/types.h"
41 42
#include "qapi-visit.h"
#include "qapi/qmp-output-visitor.h"
43
#include "qapi/util.h"
44
#include "sysemu/sysemu.h"
45
#include "block/block_int.h"
Luiz Capitulino's avatar
Luiz Capitulino committed
46
#include "qmp-commands.h"
47
#include "trace.h"
48
#include "sysemu/arch_init.h"
49

50 51 52 53 54 55 56 57 58 59 60 61
static const char *const if_name[IF_COUNT] = {
    [IF_NONE] = "none",
    [IF_IDE] = "ide",
    [IF_SCSI] = "scsi",
    [IF_FLOPPY] = "floppy",
    [IF_PFLASH] = "pflash",
    [IF_MTD] = "mtd",
    [IF_SD] = "sd",
    [IF_VIRTIO] = "virtio",
    [IF_XEN] = "xen",
};

62
static int if_max_devs[IF_COUNT] = {
63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78
    /*
     * Do not change these numbers!  They govern how drive option
     * index maps to unit and bus.  That mapping is ABI.
     *
     * All controllers used to imlement if=T drives need to support
     * if_max_devs[T] units, for any T with if_max_devs[T] != 0.
     * Otherwise, some index values map to "impossible" bus, unit
     * values.
     *
     * For instance, if you change [IF_SCSI] to 255, -drive
     * if=scsi,index=12 no longer means bus=1,unit=5, but
     * bus=0,unit=12.  With an lsi53c895a controller (7 units max),
     * the drive can't be set up.  Regression.
     */
    [IF_IDE] = 2,
    [IF_SCSI] = 7,
79 80
};

81 82 83 84 85 86
/**
 * Boards may call this to offer board-by-board overrides
 * of the default, global values.
 */
void override_max_devs(BlockInterfaceType type, int max_devs)
{
87
    BlockBackend *blk;
88 89 90 91 92 93
    DriveInfo *dinfo;

    if (max_devs <= 0) {
        return;
    }

94 95
    for (blk = blk_next(NULL); blk; blk = blk_next(blk)) {
        dinfo = blk_legacy_dinfo(blk);
96 97 98 99 100 101 102 103 104 105 106
        if (dinfo->type == type) {
            fprintf(stderr, "Cannot override units-per-bus property of"
                    " the %s interface, because a drive of that type has"
                    " already been added.\n", if_name[type]);
            g_assert_not_reached();
        }
    }

    if_max_devs[type] = max_devs;
}

107 108 109 110 111 112 113 114 115
/*
 * We automatically delete the drive when a device using it gets
 * unplugged.  Questionable feature, but we can't just drop it.
 * Device models call blockdev_mark_auto_del() to schedule the
 * automatic deletion, and generic qdev code calls blockdev_auto_del()
 * when deletion is actually safe.
 */
void blockdev_mark_auto_del(BlockDriverState *bs)
{
116 117
    BlockBackend *blk = bs->blk;
    DriveInfo *dinfo = blk_legacy_dinfo(blk);
118

119 120 121 122
    if (dinfo && !dinfo->enable_auto_del) {
        return;
    }

123 124 125
    if (bs->job) {
        block_job_cancel(bs->job);
    }
126 127 128
    if (dinfo) {
        dinfo->auto_del = 1;
    }
129 130 131 132
}

void blockdev_auto_del(BlockDriverState *bs)
{
133 134
    BlockBackend *blk = bs->blk;
    DriveInfo *dinfo = blk_legacy_dinfo(blk);
135

136
    if (dinfo && dinfo->auto_del) {
137
        drive_del(dinfo);
138 139 140
    }
}

141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157
/**
 * Returns the current mapping of how many units per bus
 * a particular interface can support.
 *
 *  A positive integer indicates n units per bus.
 *  0 implies the mapping has not been established.
 * -1 indicates an invalid BlockInterfaceType was given.
 */
int drive_get_max_devs(BlockInterfaceType type)
{
    if (type >= IF_IDE && type < IF_COUNT) {
        return if_max_devs[type];
    }

    return -1;
}

158 159 160 161 162 163 164 165 166 167 168 169
static int drive_index_to_bus_id(BlockInterfaceType type, int index)
{
    int max_devs = if_max_devs[type];
    return max_devs ? index / max_devs : 0;
}

static int drive_index_to_unit_id(BlockInterfaceType type, int index)
{
    int max_devs = if_max_devs[type];
    return max_devs ? index % max_devs : index;
}

170 171 172 173 174 175
QemuOpts *drive_def(const char *optstr)
{
    return qemu_opts_parse(qemu_find_opts("drive"), optstr, 0);
}

QemuOpts *drive_add(BlockInterfaceType type, int index, const char *file,
176
                    const char *optstr)
177 178
{
    QemuOpts *opts;
179
    char buf[32];
180

181
    opts = drive_def(optstr);
182 183 184
    if (!opts) {
        return NULL;
    }
185 186 187 188 189 190 191
    if (type != IF_DEFAULT) {
        qemu_opt_set(opts, "if", if_name[type]);
    }
    if (index >= 0) {
        snprintf(buf, sizeof(buf), "%d", index);
        qemu_opt_set(opts, "index", buf);
    }
192 193 194 195 196 197 198
    if (file)
        qemu_opt_set(opts, "file", file);
    return opts;
}

DriveInfo *drive_get(BlockInterfaceType type, int bus, int unit)
{
199
    BlockBackend *blk;
200 201
    DriveInfo *dinfo;

202 203 204 205
    for (blk = blk_next(NULL); blk; blk = blk_next(blk)) {
        dinfo = blk_legacy_dinfo(blk);
        if (dinfo && dinfo->type == type
            && dinfo->bus == bus && dinfo->unit == unit) {
206
            return dinfo;
207
        }
208 209 210 211 212
    }

    return NULL;
}

John Snow's avatar
John Snow committed
213 214
bool drive_check_orphaned(void)
{
215
    BlockBackend *blk;
John Snow's avatar
John Snow committed
216 217 218
    DriveInfo *dinfo;
    bool rs = false;

219 220
    for (blk = blk_next(NULL); blk; blk = blk_next(blk)) {
        dinfo = blk_legacy_dinfo(blk);
John Snow's avatar
John Snow committed
221 222 223 224 225 226 227 228 229 230 231 232 233 234 235
        /* If dinfo->bdrv->dev is NULL, it has no device attached. */
        /* Unless this is a default drive, this may be an oversight. */
        if (!dinfo->bdrv->dev && !dinfo->is_default &&
            dinfo->type != IF_NONE) {
            fprintf(stderr, "Warning: Orphaned drive without device: "
                    "id=%s,file=%s,if=%s,bus=%d,unit=%d\n",
                    dinfo->id, dinfo->bdrv->filename, if_name[dinfo->type],
                    dinfo->bus, dinfo->unit);
            rs = true;
        }
    }

    return rs;
}

236 237 238 239 240 241 242
DriveInfo *drive_get_by_index(BlockInterfaceType type, int index)
{
    return drive_get(type,
                     drive_index_to_bus_id(type, index),
                     drive_index_to_unit_id(type, index));
}

243 244 245
int drive_get_max_bus(BlockInterfaceType type)
{
    int max_bus;
246
    BlockBackend *blk;
247 248 249
    DriveInfo *dinfo;

    max_bus = -1;
250 251 252
    for (blk = blk_next(NULL); blk; blk = blk_next(blk)) {
        dinfo = blk_legacy_dinfo(blk);
        if (dinfo && dinfo->type == type && dinfo->bus > max_bus) {
253
            max_bus = dinfo->bus;
254
        }
255 256 257 258
    }
    return max_bus;
}

259 260 261 262 263 264 265 266 267 268
/* Get a block device.  This should only be used for single-drive devices
   (e.g. SD/Floppy/MTD).  Multi-disk devices (scsi/ide) should use the
   appropriate bus.  */
DriveInfo *drive_get_next(BlockInterfaceType type)
{
    static int next_block_unit[IF_COUNT];

    return drive_get(type, 0, next_block_unit[type]++);
}

269
DriveInfo *drive_get_by_blockdev(BlockDriverState *bs)
270
{
271
    return bs->blk ? blk_legacy_dinfo(bs->blk) : NULL;
272 273 274 275
}

static void bdrv_format_print(void *opaque, const char *name)
{
276
    error_printf(" %s", name);
277 278
}

279
void drive_del(DriveInfo *dinfo)
280
{
281
    BlockBackend *blk = dinfo->bdrv->blk;
Markus Armbruster's avatar
Markus Armbruster committed
282

283
    bdrv_unref(dinfo->bdrv);
Markus Armbruster's avatar
Markus Armbruster committed
284
    blk_unref(blk);
285 286
}

287 288
typedef struct {
    QEMUBH *bh;
Fam Zheng's avatar
Fam Zheng committed
289 290
    BlockDriverState *bs;
} BDRVPutRefBH;
291

Fam Zheng's avatar
Fam Zheng committed
292
static void bdrv_put_ref_bh(void *opaque)
293
{
Fam Zheng's avatar
Fam Zheng committed
294
    BDRVPutRefBH *s = opaque;
295

Fam Zheng's avatar
Fam Zheng committed
296
    bdrv_unref(s->bs);
297 298 299 300 301
    qemu_bh_delete(s->bh);
    g_free(s);
}

/*
Fam Zheng's avatar
Fam Zheng committed
302
 * Release a BDS reference in a BH
303
 *
Fam Zheng's avatar
Fam Zheng committed
304 305 306
 * It is not safe to use bdrv_unref() from a callback function when the callers
 * still need the BlockDriverState.  In such cases we schedule a BH to release
 * the reference.
307
 */
Fam Zheng's avatar
Fam Zheng committed
308
static void bdrv_put_ref_bh_schedule(BlockDriverState *bs)
309
{
Fam Zheng's avatar
Fam Zheng committed
310
    BDRVPutRefBH *s;
311

Fam Zheng's avatar
Fam Zheng committed
312 313 314
    s = g_new(BDRVPutRefBH, 1);
    s->bh = qemu_bh_new(bdrv_put_ref_bh, s);
    s->bs = bs;
315 316 317
    qemu_bh_schedule(s->bh);
}

318
static int parse_block_error_action(const char *buf, bool is_read, Error **errp)
319 320
{
    if (!strcmp(buf, "ignore")) {
321
        return BLOCKDEV_ON_ERROR_IGNORE;
322
    } else if (!is_read && !strcmp(buf, "enospc")) {
323
        return BLOCKDEV_ON_ERROR_ENOSPC;
324
    } else if (!strcmp(buf, "stop")) {
325
        return BLOCKDEV_ON_ERROR_STOP;
326
    } else if (!strcmp(buf, "report")) {
327
        return BLOCKDEV_ON_ERROR_REPORT;
328
    } else {
329 330
        error_setg(errp, "'%s' invalid %s error action",
                   buf, is_read ? "read" : "write");
331 332 333 334
        return -1;
    }
}

335
static bool check_throttle_config(ThrottleConfig *cfg, Error **errp)
336
{
337 338 339
    if (throttle_conflicting(cfg)) {
        error_setg(errp, "bps/iops/max total values and read/write values"
                         " cannot be used at the same time");
340 341 342
        return false;
    }

343 344
    if (!throttle_is_valid(cfg)) {
        error_setg(errp, "bps/iops/maxs values must be 0 or greater");
345 346 347
        return false;
    }

348 349 350
    return true;
}

351 352
typedef enum { MEDIA_DISK, MEDIA_CDROM } DriveMediaType;

353
/* Takes the ownership of bs_opts */
354 355
static BlockBackend *blockdev_init(const char *file, QDict *bs_opts,
                                   Error **errp)
356 357 358 359 360
{
    const char *buf;
    int ro = 0;
    int bdrv_flags = 0;
    int on_read_error, on_write_error;
Markus Armbruster's avatar
Markus Armbruster committed
361
    BlockBackend *blk;
362
    BlockDriverState *bs;
363
    DriveInfo *dinfo;
364
    ThrottleConfig cfg;
365
    int snapshot = 0;
366
    bool copy_on_read;
367
    int ret;
368
    Error *error = NULL;
369 370
    QemuOpts *opts;
    const char *id;
371
    bool has_driver_specific_opts;
372
    BlockdevDetectZeroesOptions detect_zeroes;
373
    BlockDriver *drv = NULL;
374

375 376 377
    /* Check common options by copying from bs_opts to opts, all other options
     * stay in bs_opts for processing by bdrv_open(). */
    id = qdict_get_try_str(bs_opts, "id");
378
    opts = qemu_opts_create(&qemu_common_drive_opts, id, 1, &error);
379
    if (error) {
380
        error_propagate(errp, error);
381
        goto err_no_opts;
382 383 384
    }

    qemu_opts_absorb_qdict(opts, bs_opts, &error);
385
    if (error) {
386
        error_propagate(errp, error);
387
        goto early_err;
388 389 390 391 392 393
    }

    if (id) {
        qdict_del(bs_opts, "id");
    }

394 395
    has_driver_specific_opts = !!qdict_size(bs_opts);

396 397
    /* extract parameters */
    snapshot = qemu_opt_get_bool(opts, "snapshot", 0);
398
    ro = qemu_opt_get_bool(opts, "read-only", 0);
399
    copy_on_read = qemu_opt_get_bool(opts, "copy-on-read", false);
400

401 402
    if ((buf = qemu_opt_get(opts, "discard")) != NULL) {
        if (bdrv_parse_discard_flags(buf, &bdrv_flags) != 0) {
403
            error_setg(errp, "invalid discard option");
404
            goto early_err;
405 406 407
        }
    }

Kevin Wolf's avatar
Kevin Wolf committed
408 409 410 411 412 413
    if (qemu_opt_get_bool(opts, "cache.writeback", true)) {
        bdrv_flags |= BDRV_O_CACHE_WB;
    }
    if (qemu_opt_get_bool(opts, "cache.direct", false)) {
        bdrv_flags |= BDRV_O_NOCACHE;
    }
414
    if (qemu_opt_get_bool(opts, "cache.no-flush", false)) {
Kevin Wolf's avatar
Kevin Wolf committed
415
        bdrv_flags |= BDRV_O_NO_FLUSH;
416 417 418 419 420 421 422 423 424
    }

#ifdef CONFIG_LINUX_AIO
    if ((buf = qemu_opt_get(opts, "aio")) != NULL) {
        if (!strcmp(buf, "native")) {
            bdrv_flags |= BDRV_O_NATIVE_AIO;
        } else if (!strcmp(buf, "threads")) {
            /* this is the default */
        } else {
425
           error_setg(errp, "invalid aio option");
426
           goto early_err;
427 428 429 430 431
        }
    }
#endif

    if ((buf = qemu_opt_get(opts, "format")) != NULL) {
432 433 434 435
        if (is_help_option(buf)) {
            error_printf("Supported formats:");
            bdrv_iterate_format(bdrv_format_print, NULL);
            error_printf("\n");
436
            goto early_err;
437
        }
438

439
        drv = bdrv_find_format(buf);
440
        if (!drv) {
441
            error_setg(errp, "'%s' invalid format", buf);
442
            goto early_err;
443
        }
444 445
    }

446
    /* disk I/O throttling */
447 448
    memset(&cfg, 0, sizeof(cfg));
    cfg.buckets[THROTTLE_BPS_TOTAL].avg =
449
        qemu_opt_get_number(opts, "throttling.bps-total", 0);
450
    cfg.buckets[THROTTLE_BPS_READ].avg  =
451
        qemu_opt_get_number(opts, "throttling.bps-read", 0);
452
    cfg.buckets[THROTTLE_BPS_WRITE].avg =
453
        qemu_opt_get_number(opts, "throttling.bps-write", 0);
454
    cfg.buckets[THROTTLE_OPS_TOTAL].avg =
455
        qemu_opt_get_number(opts, "throttling.iops-total", 0);
456
    cfg.buckets[THROTTLE_OPS_READ].avg =
457
        qemu_opt_get_number(opts, "throttling.iops-read", 0);
458
    cfg.buckets[THROTTLE_OPS_WRITE].avg =
459
        qemu_opt_get_number(opts, "throttling.iops-write", 0);
460

461 462 463 464 465 466 467 468 469 470 471 472
    cfg.buckets[THROTTLE_BPS_TOTAL].max =
        qemu_opt_get_number(opts, "throttling.bps-total-max", 0);
    cfg.buckets[THROTTLE_BPS_READ].max  =
        qemu_opt_get_number(opts, "throttling.bps-read-max", 0);
    cfg.buckets[THROTTLE_BPS_WRITE].max =
        qemu_opt_get_number(opts, "throttling.bps-write-max", 0);
    cfg.buckets[THROTTLE_OPS_TOTAL].max =
        qemu_opt_get_number(opts, "throttling.iops-total-max", 0);
    cfg.buckets[THROTTLE_OPS_READ].max =
        qemu_opt_get_number(opts, "throttling.iops-read-max", 0);
    cfg.buckets[THROTTLE_OPS_WRITE].max =
        qemu_opt_get_number(opts, "throttling.iops-write-max", 0);
473

474
    cfg.op_size = qemu_opt_get_number(opts, "throttling.iops-size", 0);
475 476

    if (!check_throttle_config(&cfg, &error)) {
477
        error_propagate(errp, error);
478
        goto early_err;
479 480
    }

481
    on_write_error = BLOCKDEV_ON_ERROR_ENOSPC;
482
    if ((buf = qemu_opt_get(opts, "werror")) != NULL) {
483
        on_write_error = parse_block_error_action(buf, 0, &error);
484
        if (error) {
485
            error_propagate(errp, error);
486
            goto early_err;
487 488 489
        }
    }

490
    on_read_error = BLOCKDEV_ON_ERROR_REPORT;
491
    if ((buf = qemu_opt_get(opts, "rerror")) != NULL) {
492
        on_read_error = parse_block_error_action(buf, 1, &error);
493
        if (error) {
494
            error_propagate(errp, error);
495
            goto early_err;
496 497 498
        }
    }

499
    detect_zeroes =
500 501 502 503 504
        qapi_enum_parse(BlockdevDetectZeroesOptions_lookup,
                        qemu_opt_get(opts, "detect-zeroes"),
                        BLOCKDEV_DETECT_ZEROES_OPTIONS_MAX,
                        BLOCKDEV_DETECT_ZEROES_OPTIONS_OFF,
                        &error);
505 506 507 508 509 510 511 512 513 514 515 516
    if (error) {
        error_propagate(errp, error);
        goto early_err;
    }

    if (detect_zeroes == BLOCKDEV_DETECT_ZEROES_OPTIONS_UNMAP &&
        !(bdrv_flags & BDRV_O_UNMAP)) {
        error_setg(errp, "setting detect-zeroes to unmap is not allowed "
                         "without setting discard operation to unmap");
        goto early_err;
    }

517
    /* init */
518
    blk = blk_new_with_bs(qemu_opts_id(opts), errp);
Markus Armbruster's avatar
Markus Armbruster committed
519 520 521
    if (!blk) {
        goto early_err;
    }
522
    bs = blk_bs(blk);
523 524 525
    bs->open_flags = snapshot ? BDRV_O_SNAPSHOT : 0;
    bs->read_only = ro;
    bs->detect_zeroes = detect_zeroes;
526

527
    bdrv_set_on_error(bs, on_read_error, on_write_error);
528

529
    /* disk I/O throttling */
530
    if (throttle_enabled(&cfg)) {
531 532
        bdrv_io_limits_enable(bs);
        bdrv_set_io_limits(bs, &cfg);
533
    }
534

535 536 537
    dinfo = g_malloc0(sizeof(*dinfo));
    dinfo->id = g_strdup(qemu_opts_id(opts));
    dinfo->bdrv = bs;
538
    blk_set_legacy_dinfo(blk, dinfo);
539

540
    if (!file || !*file) {
541
        if (has_driver_specific_opts) {
542 543
            file = NULL;
        } else {
544 545
            QDECREF(bs_opts);
            qemu_opts_del(opts);
546
            return blk;
547
        }
548 549 550 551 552 553 554
    }
    if (snapshot) {
        /* always use cache=unsafe with snapshot */
        bdrv_flags &= ~BDRV_O_CACHE_MASK;
        bdrv_flags |= (BDRV_O_SNAPSHOT|BDRV_O_CACHE_WB|BDRV_O_NO_FLUSH);
    }

555 556 557 558
    if (copy_on_read) {
        bdrv_flags |= BDRV_O_COPY_ON_READ;
    }

559 560 561 562
    if (runstate_check(RUN_STATE_INMIGRATE)) {
        bdrv_flags |= BDRV_O_INCOMING;
    }

563 564
    bdrv_flags |= ro ? 0 : BDRV_O_RDWR;

565
    QINCREF(bs_opts);
566 567
    ret = bdrv_open(&bs, file, NULL, bs_opts, bdrv_flags, drv, &error);
    assert(bs == dinfo->bdrv);
568

569
    if (ret < 0) {
570 571 572
        error_setg(errp, "could not open disk image %s: %s",
                   file ?: dinfo->id, error_get_pretty(error));
        error_free(error);
573
        goto err;
574 575
    }

576
    if (bdrv_key_required(bs)) {
577
        autostart = 0;
578
    }
579

580
    QDECREF(bs_opts);
581 582
    qemu_opts_del(opts);

583
    return blk;
584 585

err:
586
    bdrv_unref(bs);
Markus Armbruster's avatar
Markus Armbruster committed
587
    blk_unref(blk);
588 589
early_err:
    qemu_opts_del(opts);
590 591
err_no_opts:
    QDECREF(bs_opts);
592
    return NULL;
593 594
}

595 596
static void qemu_opt_rename(QemuOpts *opts, const char *from, const char *to,
                            Error **errp)
597 598 599 600 601
{
    const char *value;

    value = qemu_opt_get(opts, from);
    if (value) {
602 603 604 605 606
        if (qemu_opt_find(opts, to)) {
            error_setg(errp, "'%s' and its alias '%s' can't be used at the "
                       "same time", to, from);
            return;
        }
607 608 609 610
    }

    /* rename all items in opts */
    while ((value = qemu_opt_get(opts, from))) {
611 612 613 614 615
        qemu_opt_set(opts, to, value);
        qemu_opt_unset(opts, from);
    }
}

616 617 618 619 620
QemuOptsList qemu_legacy_drive_opts = {
    .name = "drive",
    .head = QTAILQ_HEAD_INITIALIZER(qemu_legacy_drive_opts.head),
    .desc = {
        {
621 622 623 624 625 626 627 628 629 630 631 632
            .name = "bus",
            .type = QEMU_OPT_NUMBER,
            .help = "bus number",
        },{
            .name = "unit",
            .type = QEMU_OPT_NUMBER,
            .help = "unit number (i.e. lun for scsi)",
        },{
            .name = "index",
            .type = QEMU_OPT_NUMBER,
            .help = "index number",
        },{
633 634 635
            .name = "media",
            .type = QEMU_OPT_STRING,
            .help = "media type (disk, cdrom)",
636 637 638 639
        },{
            .name = "if",
            .type = QEMU_OPT_STRING,
            .help = "interface (ide, scsi, sd, mtd, floppy, pflash, virtio)",
640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655
        },{
            .name = "cyls",
            .type = QEMU_OPT_NUMBER,
            .help = "number of cylinders (ide disk geometry)",
        },{
            .name = "heads",
            .type = QEMU_OPT_NUMBER,
            .help = "number of heads (ide disk geometry)",
        },{
            .name = "secs",
            .type = QEMU_OPT_NUMBER,
            .help = "number of sectors (ide disk geometry)",
        },{
            .name = "trans",
            .type = QEMU_OPT_STRING,
            .help = "chs translation (auto, lba, none)",
656 657 658 659
        },{
            .name = "boot",
            .type = QEMU_OPT_BOOL,
            .help = "(deprecated, ignored)",
660 661 662 663
        },{
            .name = "addr",
            .type = QEMU_OPT_STRING,
            .help = "pci address (virtio only)",
664 665 666 667
        },{
            .name = "serial",
            .type = QEMU_OPT_STRING,
            .help = "disk serial number",
668 669 670 671
        },{
            .name = "file",
            .type = QEMU_OPT_STRING,
            .help = "file name",
672
        },
673 674 675 676 677 678

        /* Options that are passed on, but have special semantics with -drive */
        {
            .name = "read-only",
            .type = QEMU_OPT_BOOL,
            .help = "open drive file as read-only",
679 680 681 682 683 684 685 686
        },{
            .name = "rerror",
            .type = QEMU_OPT_STRING,
            .help = "read error action",
        },{
            .name = "werror",
            .type = QEMU_OPT_STRING,
            .help = "write error action",
687 688 689 690 691 692
        },{
            .name = "copy-on-read",
            .type = QEMU_OPT_BOOL,
            .help = "copy read data from backing file into image file",
        },

693 694 695 696
        { /* end of list */ }
    },
};

697
DriveInfo *drive_new(QemuOpts *all_opts, BlockInterfaceType block_default_type)
698
{
Kevin Wolf's avatar
Kevin Wolf committed
699
    const char *value;
700
    BlockBackend *blk;
701
    DriveInfo *dinfo = NULL;
702
    QDict *bs_opts;
703 704
    QemuOpts *legacy_opts;
    DriveMediaType media = MEDIA_DISK;
705
    BlockInterfaceType type;
706
    int cyls, heads, secs, translation;
707
    int max_devs, bus_id, unit_id, index;
708
    const char *devaddr;
709
    const char *werror, *rerror;
Fam Zheng's avatar
Fam Zheng committed
710 711
    bool read_only = false;
    bool copy_on_read;
712
    const char *serial;
713
    const char *filename;
714
    Error *local_err = NULL;
715
    int i;
Kevin Wolf's avatar
Kevin Wolf committed
716

717
    /* Change legacy command line options into QMP ones */
718 719 720 721 722 723 724
    static const struct {
        const char *from;
        const char *to;
    } opt_renames[] = {
        { "iops",           "throttling.iops-total" },
        { "iops_rd",        "throttling.iops-read" },
        { "iops_wr",        "throttling.iops-write" },
725

726 727 728
        { "bps",            "throttling.bps-total" },
        { "bps_rd",         "throttling.bps-read" },
        { "bps_wr",         "throttling.bps-write" },
729

730 731 732
        { "iops_max",       "throttling.iops-total-max" },
        { "iops_rd_max",    "throttling.iops-read-max" },
        { "iops_wr_max",    "throttling.iops-write-max" },
733

734 735 736
        { "bps_max",        "throttling.bps-total-max" },
        { "bps_rd_max",     "throttling.bps-read-max" },
        { "bps_wr_max",     "throttling.bps-write-max" },
737

738
        { "iops_size",      "throttling.iops-size" },
739

740 741 742 743
        { "readonly",       "read-only" },
    };

    for (i = 0; i < ARRAY_SIZE(opt_renames); i++) {
744 745 746 747 748 749 750
        qemu_opt_rename(all_opts, opt_renames[i].from, opt_renames[i].to,
                        &local_err);
        if (local_err) {
            error_report("%s", error_get_pretty(local_err));
            error_free(local_err);
            return NULL;
        }
751
    }
752

Kevin Wolf's avatar
Kevin Wolf committed
753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777
    value = qemu_opt_get(all_opts, "cache");
    if (value) {
        int flags = 0;

        if (bdrv_parse_cache_flags(value, &flags) != 0) {
            error_report("invalid cache option");
            return NULL;
        }

        /* Specific options take precedence */
        if (!qemu_opt_get(all_opts, "cache.writeback")) {
            qemu_opt_set_bool(all_opts, "cache.writeback",
                              !!(flags & BDRV_O_CACHE_WB));
        }
        if (!qemu_opt_get(all_opts, "cache.direct")) {
            qemu_opt_set_bool(all_opts, "cache.direct",
                              !!(flags & BDRV_O_NOCACHE));
        }
        if (!qemu_opt_get(all_opts, "cache.no-flush")) {
            qemu_opt_set_bool(all_opts, "cache.no-flush",
                              !!(flags & BDRV_O_NO_FLUSH));
        }
        qemu_opt_unset(all_opts, "cache");
    }

778 779 780 781
    /* Get a QDict for processing the options */
    bs_opts = qdict_new();
    qemu_opts_to_qdict(all_opts, bs_opts);

782 783
    legacy_opts = qemu_opts_create(&qemu_legacy_drive_opts, NULL, 0,
                                   &error_abort);
784
    qemu_opts_absorb_qdict(legacy_opts, bs_opts, &local_err);
785
    if (local_err) {
786
        error_report("%s", error_get_pretty(local_err));
787 788 789 790
        error_free(local_err);
        goto fail;
    }

791 792 793 794 795 796 797
    /* Deprecated option boot=[on|off] */
    if (qemu_opt_get(legacy_opts, "boot") != NULL) {
        fprintf(stderr, "qemu-kvm: boot=on|off is deprecated and will be "
                "ignored. Future versions will reject this parameter. Please "
                "update your scripts.\n");
    }

798 799 800 801 802 803 804
    /* Media type */
    value = qemu_opt_get(legacy_opts, "media");
    if (value) {
        if (!strcmp(value, "disk")) {
            media = MEDIA_DISK;
        } else if (!strcmp(value, "cdrom")) {
            media = MEDIA_CDROM;
Fam Zheng's avatar
Fam Zheng committed
805
            read_only = true;
806 807 808 809 810 811
        } else {
            error_report("'%s' invalid media", value);
            goto fail;
        }
    }

812
    /* copy-on-read is disabled with a warning for read-only devices */
Fam Zheng's avatar
Fam Zheng committed
813
    read_only |= qemu_opt_get_bool(legacy_opts, "read-only", false);
814 815 816 817 818 819 820 821 822 823 824 825
    copy_on_read = qemu_opt_get_bool(legacy_opts, "copy-on-read", false);

    if (read_only && copy_on_read) {
        error_report("warning: disabling copy-on-read on read-only drive");
        copy_on_read = false;
    }

    qdict_put(bs_opts, "read-only",
              qstring_from_str(read_only ? "on" : "off"));
    qdict_put(bs_opts, "copy-on-read",
              qstring_from_str(copy_on_read ? "on" :"off"));

826 827 828 829 830 831 832 833 834 835 836 837 838 839 840
    /* Controller type */
    value = qemu_opt_get(legacy_opts, "if");
    if (value) {
        for (type = 0;
             type < IF_COUNT && strcmp(value, if_name[type]);
             type++) {
        }
        if (type == IF_COUNT) {
            error_report("unsupported bus type '%s'", value);
            goto fail;
        }
    } else {
        type = block_default_type;
    }

841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872
    /* Geometry */
    cyls  = qemu_opt_get_number(legacy_opts, "cyls", 0);
    heads = qemu_opt_get_number(legacy_opts, "heads", 0);
    secs  = qemu_opt_get_number(legacy_opts, "secs", 0);

    if (cyls || heads || secs) {
        if (cyls < 1) {
            error_report("invalid physical cyls number");
            goto fail;
        }
        if (heads < 1) {
            error_report("invalid physical heads number");
            goto fail;
        }
        if (secs < 1) {
            error_report("invalid physical secs number");
            goto fail;
        }
    }

    translation = BIOS_ATA_TRANSLATION_AUTO;
    value = qemu_opt_get(legacy_opts, "trans");
    if (value != NULL) {
        if (!cyls) {
            error_report("'%s' trans must be used with cyls, heads and secs",
                         value);
            goto fail;
        }
        if (!strcmp(value, "none")) {
            translation = BIOS_ATA_TRANSLATION_NONE;
        } else if (!strcmp(value, "lba")) {
            translation = BIOS_ATA_TRANSLATION_LBA;
873 874 875 876
        } else if (!strcmp(value, "large")) {
            translation = BIOS_ATA_TRANSLATION_LARGE;
        } else if (!strcmp(value, "rechs")) {
            translation = BIOS_ATA_TRANSLATION_RECHS;
877 878 879 880 881 882 883 884 885 886 887 888 889 890 891
        } else if (!strcmp(value, "auto")) {
            translation = BIOS_ATA_TRANSLATION_AUTO;
        } else {
            error_report("'%s' invalid translation type", value);
            goto fail;
        }
    }

    if (media == MEDIA_CDROM) {
        if (cyls || secs || heads) {
            error_report("CHS can't be set with media=cdrom");
            goto fail;
        }
    }

892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930
    /* Device address specified by bus/unit or index.
     * If none was specified, try to find the first free one. */
    bus_id  = qemu_opt_get_number(legacy_opts, "bus", 0);
    unit_id = qemu_opt_get_number(legacy_opts, "unit", -1);
    index   = qemu_opt_get_number(legacy_opts, "index", -1);

    max_devs = if_max_devs[type];

    if (index != -1) {
        if (bus_id != 0 || unit_id != -1) {
            error_report("index cannot be used with bus and unit");
            goto fail;
        }
        bus_id = drive_index_to_bus_id(type, index);
        unit_id = drive_index_to_unit_id(type, index);
    }

    if (unit_id == -1) {
       unit_id = 0;
       while (drive_get(type, bus_id, unit_id) != NULL) {
           unit_id++;
           if (max_devs && unit_id >= max_devs) {
               unit_id -= max_devs;
               bus_id++;
           }
       }
    }

    if (max_devs && unit_id >= max_devs) {
        error_report("unit %d too big (max is %d)", unit_id, max_devs - 1);
        goto fail;
    }

    if (drive_get(type, bus_id, unit_id) != NULL) {
        error_report("drive with bus=%d, unit=%d (index=%d) exists",
                     bus_id, unit_id, index);
        goto fail;
    }

931 932 933
    /* Serial number */
    serial = qemu_opt_get(legacy_opts, "serial");

934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951
    /* no id supplied -> create one */
    if (qemu_opts_id(all_opts) == NULL) {
        char *new_id;
        const char *mediastr = "";
        if (type == IF_IDE || type == IF_SCSI) {
            mediastr = (media == MEDIA_CDROM) ? "-cd" : "-hd";
        }
        if (max_devs) {
            new_id = g_strdup_printf("%s%i%s%i", if_name[type], bus_id,
                                     mediastr, unit_id);
        } else {
            new_id = g_strdup_printf("%s%s%i", if_name[type],
                                     mediastr, unit_id);
        }
        qdict_put(bs_opts, "id", qstring_from_str(new_id));
        g_free(new_id);
    }

952 953 954 955 956 957 958 959 960
    /* Add virtio block device */
    devaddr = qemu_opt_get(legacy_opts, "addr");
    if (devaddr && type != IF_VIRTIO) {
        error_report("addr is not supported by this bus type");
        goto fail;
    }

    if (type == IF_VIRTIO) {
        QemuOpts *devopts;
961 962
        devopts = qemu_opts_create(qemu_find_opts("device"), NULL, 0,
                                   &error_abort);
963 964 965 966 967 968 969 970 971 972 973
        if (arch_type == QEMU_ARCH_S390X) {
            qemu_opt_set(devopts, "driver", "virtio-blk-s390");
        } else {
            qemu_opt_set(devopts, "driver", "virtio-blk-pci");
        }
        qemu_opt_set(devopts, "drive", qdict_get_str(bs_opts, "id"));
        if (devaddr) {
            qemu_opt_set(devopts, "addr", devaddr);
        }
    }

974 975
    filename = qemu_opt_get(legacy_opts, "file");

976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996
    /* Check werror/rerror compatibility with if=... */
    werror = qemu_opt_get(legacy_opts, "werror");
    if (werror != NULL) {
        if (type != IF_IDE && type != IF_SCSI && type != IF_VIRTIO &&
            type != IF_NONE) {
            error_report("werror is not supported by this bus type");
            goto fail;
        }
        qdict_put(bs_opts, "werror", qstring_from_str(werror));
    }

    rerror = qemu_opt_get(legacy_opts, "rerror");
    if (rerror != NULL) {
        if (type != IF_IDE && type != IF_VIRTIO && type != IF_SCSI &&
            type != IF_NONE) {
            error_report("rerror is not supported by this bus type");
            goto fail;
        }
        qdict_put(bs_opts, "rerror", qstring_from_str(rerror));
    }

997
    /* Actual block device init: Functionality shared with blockdev-add */
998
    blk = blockdev_init(filename, bs_opts, &local_err);
999
    bs_opts = NULL;
1000
    if (!blk) {
1001
        if (local_err) {
1002
            error_report("%s", error_get_pretty(local_err));
1003 1004
            error_free(local_err);
        }
1005
        goto fail;
1006
    } else {
1007
        assert(!local_err);
1008 1009 1010
    }

    /* Set legacy DriveInfo fields */
1011
    dinfo = blk_legacy_dinfo(blk);
1012
    dinfo->enable_auto_del = true;
1013
    dinfo->opts = all_opts;
1014

1015 1016 1017 1018 1019
    dinfo->cyls = cyls;
    dinfo->heads = heads;
    dinfo->secs = secs;
    dinfo->trans = translation;

1020
    dinfo->type = type;
1021 1022
    dinfo->bus = bus_id;
    dinfo->unit = unit_id;
1023
    dinfo->devaddr = devaddr;
1024

1025 1026
    dinfo->serial = g_strdup(serial);

1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037
    switch(type) {
    case IF_IDE:
    case IF_SCSI:
    case IF_XEN:
    case IF_NONE:
        dinfo->media_cd = media == MEDIA_CDROM;
        break;
    default:
        break;
    }

1038
fail:
1039
    qemu_opts_del(legacy_opts);
1040
    QDECREF(bs_opts);
1041
    return dinfo;
1042 1043
}

1044 1045 1046
void do_commit(Monitor *mon, const QDict *qdict)
{
    const char *device = qdict_get_str(qdict, "device");
1047
    BlockDriverState *bs;
1048
    int ret;
1049

1050
    if (!strcmp(device, "all")) {
1051
        ret = bdrv_commit_all();
1052 1053
    } else {
        bs = bdrv_find(device);
1054
        if (!bs) {
1055
            monitor_printf(mon, "Device '%s' not found\n", device);
1056
            return;
1057
        }
1058
        ret = bdrv_commit(bs);
1059 1060 1061 1062
    }
    if (ret < 0) {
        monitor_printf(mon, "'commit' error for '%s': %s\n", device,
                       strerror(-ret));
1063 1064 1065
    }
}

1066 1067
static void blockdev_do_action(int kind, void *data, Error **errp)
{
1068 1069
    TransactionAction action;
    TransactionActionList list;
1070 1071 1072 1073 1074 1075 1076 1077

    action.kind = kind;
    action.data = data;
    list.value = &action;
    list.next = NULL;
    qmp_transaction(&list, errp);
}

1078 1079 1080 1081 1082
void qmp_blockdev_snapshot_sync(bool has_device, const char *device,
                                bool has_node_name, const char *node_name,
                                const char *snapshot_file