blockdev.c 66.6 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
 */

33
#include "sysemu/blockdev.h"
Paolo Bonzini's avatar
Paolo Bonzini committed
34
#include "hw/block/block.h"
35
#include "block/blockjob.h"
36
#include "monitor/monitor.h"
37
#include "qapi/qmp/qerror.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 "sysemu/sysemu.h"
44
#include "block/block_int.h"
Luiz Capitulino's avatar
Luiz Capitulino committed
45
#include "qmp-commands.h"
46
#include "trace.h"
47
#include "sysemu/arch_init.h"
48

49
static QTAILQ_HEAD(drivelist, DriveInfo) drives = QTAILQ_HEAD_INITIALIZER(drives);
50
extern QemuOptsList qemu_common_drive_opts;
51

52 53 54 55 56 57 58 59 60 61 62 63 64
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",
};

static const int if_max_devs[IF_COUNT] = {
65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80
    /*
     * 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,
81 82
};

83 84 85 86 87 88 89 90 91 92 93
/*
 * 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)
{
    DriveInfo *dinfo = drive_get_by_blockdev(bs);

94 95 96 97
    if (dinfo && !dinfo->enable_auto_del) {
        return;
    }

98 99 100
    if (bs->job) {
        block_job_cancel(bs->job);
    }
101 102 103
    if (dinfo) {
        dinfo->auto_del = 1;
    }
104 105 106 107 108 109
}

void blockdev_auto_del(BlockDriverState *bs)
{
    DriveInfo *dinfo = drive_get_by_blockdev(bs);

110
    if (dinfo && dinfo->auto_del) {
111
        drive_put_ref(dinfo);
112 113 114
    }
}

115 116 117 118 119 120 121 122 123 124 125 126
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;
}

127 128 129 130 131 132
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,
133
                    const char *optstr)
134 135
{
    QemuOpts *opts;
136
    char buf[32];
137

138
    opts = drive_def(optstr);
139 140 141
    if (!opts) {
        return NULL;
    }
142 143 144 145 146 147 148
    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);
    }
149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169
    if (file)
        qemu_opt_set(opts, "file", file);
    return opts;
}

DriveInfo *drive_get(BlockInterfaceType type, int bus, int unit)
{
    DriveInfo *dinfo;

    /* seek interface, bus and unit */

    QTAILQ_FOREACH(dinfo, &drives, next) {
        if (dinfo->type == type &&
	    dinfo->bus == bus &&
	    dinfo->unit == unit)
            return dinfo;
    }

    return NULL;
}

170 171 172 173 174 175 176
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));
}

177 178 179 180 181 182 183 184 185 186 187 188 189 190
int drive_get_max_bus(BlockInterfaceType type)
{
    int max_bus;
    DriveInfo *dinfo;

    max_bus = -1;
    QTAILQ_FOREACH(dinfo, &drives, next) {
        if(dinfo->type == type &&
           dinfo->bus > max_bus)
            max_bus = dinfo->bus;
    }
    return max_bus;
}

191 192 193 194 195 196 197 198 199 200
/* 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]++);
}

201
DriveInfo *drive_get_by_blockdev(BlockDriverState *bs)
202 203 204 205
{
    DriveInfo *dinfo;

    QTAILQ_FOREACH(dinfo, &drives, next) {
206 207 208
        if (dinfo->bdrv == bs) {
            return dinfo;
        }
209
    }
210
    return NULL;
211 212 213 214
}

static void bdrv_format_print(void *opaque, const char *name)
{
215
    error_printf(" %s", name);
216 217
}

218
static void drive_uninit(DriveInfo *dinfo)
219
{
220 221 222 223
    if (dinfo->opts) {
        qemu_opts_del(dinfo->opts);
    }

Fam Zheng's avatar
Fam Zheng committed
224
    bdrv_unref(dinfo->bdrv);
225
    g_free(dinfo->id);
226
    QTAILQ_REMOVE(&drives, dinfo, next);
227
    g_free(dinfo->serial);
228
    g_free(dinfo);
229 230
}

231 232 233 234 235 236 237 238 239 240 241 242 243
void drive_put_ref(DriveInfo *dinfo)
{
    assert(dinfo->refcount);
    if (--dinfo->refcount == 0) {
        drive_uninit(dinfo);
    }
}

void drive_get_ref(DriveInfo *dinfo)
{
    dinfo->refcount++;
}

244 245
typedef struct {
    QEMUBH *bh;
246 247
    BlockDriverState *bs;
} BDRVPutRefBH;
248

249
static void bdrv_put_ref_bh(void *opaque)
250
{
251
    BDRVPutRefBH *s = opaque;
252

253
    bdrv_unref(s->bs);
254 255 256 257 258
    qemu_bh_delete(s->bh);
    g_free(s);
}

/*
259
 * Release a BDS reference in a BH
260
 *
261 262 263
 * 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.
264
 */
265
static void bdrv_put_ref_bh_schedule(BlockDriverState *bs)
266
{
267
    BDRVPutRefBH *s;
268

269 270 271
    s = g_new(BDRVPutRefBH, 1);
    s->bh = qemu_bh_new(bdrv_put_ref_bh, s);
    s->bs = bs;
272 273 274
    qemu_bh_schedule(s->bh);
}

275
static int parse_block_error_action(const char *buf, bool is_read)
276 277
{
    if (!strcmp(buf, "ignore")) {
278
        return BLOCKDEV_ON_ERROR_IGNORE;
279
    } else if (!is_read && !strcmp(buf, "enospc")) {
280
        return BLOCKDEV_ON_ERROR_ENOSPC;
281
    } else if (!strcmp(buf, "stop")) {
282
        return BLOCKDEV_ON_ERROR_STOP;
283
    } else if (!strcmp(buf, "report")) {
284
        return BLOCKDEV_ON_ERROR_REPORT;
285
    } else {
286 287
        error_report("'%s' invalid %s error action",
                     buf, is_read ? "read" : "write");
288 289 290 291
        return -1;
    }
}

292
static bool check_throttle_config(ThrottleConfig *cfg, Error **errp)
293
{
294 295 296
    if (throttle_conflicting(cfg)) {
        error_setg(errp, "bps/iops/max total values and read/write values"
                         " cannot be used at the same time");
297 298 299
        return false;
    }

300 301
    if (!throttle_is_valid(cfg)) {
        error_setg(errp, "bps/iops/maxs values must be 0 or greater");
302 303 304
        return false;
    }

305 306 307
    return true;
}

308 309
typedef enum { MEDIA_DISK, MEDIA_CDROM } DriveMediaType;

310 311
/* Takes the ownership of bs_opts */
static DriveInfo *blockdev_init(QDict *bs_opts,
312
                                BlockInterfaceType type,
313
                                DriveMediaType media)
314 315 316 317 318 319 320 321 322 323 324 325 326
{
    const char *buf;
    const char *file = NULL;
    const char *serial;
    const char *mediastr = "";
    int bus_id, unit_id;
    int max_devs;
    int index;
    int ro = 0;
    int bdrv_flags = 0;
    int on_read_error, on_write_error;
    const char *devaddr;
    DriveInfo *dinfo;
327
    ThrottleConfig cfg;
328
    int snapshot = 0;
329
    bool copy_on_read;
330
    int ret;
331
    Error *error = NULL;
332 333
    QemuOpts *opts;
    const char *id;
334
    bool has_driver_specific_opts;
335
    BlockDriver *drv = NULL;
336

337 338 339
    /* 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");
340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357
    opts = qemu_opts_create(&qemu_common_drive_opts, id, 1, &error);
    if (error_is_set(&error)) {
        qerror_report_err(error);
        error_free(error);
        return NULL;
    }

    qemu_opts_absorb_qdict(opts, bs_opts, &error);
    if (error_is_set(&error)) {
        qerror_report_err(error);
        error_free(error);
        return NULL;
    }

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

358 359
    has_driver_specific_opts = !!qdict_size(bs_opts);

360 361 362 363 364 365
    /* extract parameters */
    bus_id  = qemu_opt_get_number(opts, "bus", 0);
    unit_id = qemu_opt_get_number(opts, "unit", -1);
    index   = qemu_opt_get_number(opts, "index", -1);

    snapshot = qemu_opt_get_bool(opts, "snapshot", 0);
366
    ro = qemu_opt_get_bool(opts, "read-only", 0);
367
    copy_on_read = qemu_opt_get_bool(opts, "copy-on-read", false);
368 369 370 371

    file = qemu_opt_get(opts, "file");
    serial = qemu_opt_get(opts, "serial");

372
    max_devs = if_max_devs[type];
373

374 375 376 377 378 379 380
    if ((buf = qemu_opt_get(opts, "discard")) != NULL) {
        if (bdrv_parse_discard_flags(buf, &bdrv_flags) != 0) {
            error_report("invalid discard option");
            return NULL;
        }
    }

381 382 383 384 385 386
    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;
    }
387
    if (qemu_opt_get_bool(opts, "cache.no-flush", false)) {
388
        bdrv_flags |= BDRV_O_NO_FLUSH;
389 390 391 392 393 394 395 396 397
    }

#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 {
398
           error_report("invalid aio option");
399 400 401 402 403 404
           return NULL;
        }
    }
#endif

    if ((buf = qemu_opt_get(opts, "format")) != NULL) {
405 406 407 408 409
        if (is_help_option(buf)) {
            error_printf("Supported formats:");
            bdrv_iterate_format(bdrv_format_print, NULL);
            error_printf("\n");
            return NULL;
410
        }
411

412
        drv = bdrv_find_format(buf);
413
        if (!drv) {
414
            error_report("'%s' invalid format", buf);
415 416
            return NULL;
        }
417 418
    }

419
    /* disk I/O throttling */
420 421
    memset(&cfg, 0, sizeof(cfg));
    cfg.buckets[THROTTLE_BPS_TOTAL].avg =
422
        qemu_opt_get_number(opts, "throttling.bps-total", 0);
423
    cfg.buckets[THROTTLE_BPS_READ].avg  =
424
        qemu_opt_get_number(opts, "throttling.bps-read", 0);
425
    cfg.buckets[THROTTLE_BPS_WRITE].avg =
426
        qemu_opt_get_number(opts, "throttling.bps-write", 0);
427
    cfg.buckets[THROTTLE_OPS_TOTAL].avg =
428
        qemu_opt_get_number(opts, "throttling.iops-total", 0);
429
    cfg.buckets[THROTTLE_OPS_READ].avg =
430
        qemu_opt_get_number(opts, "throttling.iops-read", 0);
431
    cfg.buckets[THROTTLE_OPS_WRITE].avg =
432
        qemu_opt_get_number(opts, "throttling.iops-write", 0);
433

434 435 436 437 438 439 440 441 442 443 444 445
    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);
446

447
    cfg.op_size = qemu_opt_get_number(opts, "throttling.iops-size", 0);
448 449

    if (!check_throttle_config(&cfg, &error)) {
450 451
        error_report("%s", error_get_pretty(error));
        error_free(error);
452 453 454
        return NULL;
    }

455
    on_write_error = BLOCKDEV_ON_ERROR_ENOSPC;
456 457
    if ((buf = qemu_opt_get(opts, "werror")) != NULL) {
        if (type != IF_IDE && type != IF_SCSI && type != IF_VIRTIO && type != IF_NONE) {
458
            error_report("werror is not supported by this bus type");
459 460 461 462 463 464 465 466 467
            return NULL;
        }

        on_write_error = parse_block_error_action(buf, 0);
        if (on_write_error < 0) {
            return NULL;
        }
    }

468
    on_read_error = BLOCKDEV_ON_ERROR_REPORT;
469
    if ((buf = qemu_opt_get(opts, "rerror")) != NULL) {
470
        if (type != IF_IDE && type != IF_VIRTIO && type != IF_SCSI && type != IF_NONE) {
471
            error_report("rerror is not supported by this bus type");
472 473 474 475 476 477 478 479 480 481 482
            return NULL;
        }

        on_read_error = parse_block_error_action(buf, 1);
        if (on_read_error < 0) {
            return NULL;
        }
    }

    if ((devaddr = qemu_opt_get(opts, "addr")) != NULL) {
        if (type != IF_VIRTIO) {
483
            error_report("addr is not supported by this bus type");
484 485 486 487 488 489 490 491
            return NULL;
        }
    }

    /* compute bus and unit according index */

    if (index != -1) {
        if (bus_id != 0 || unit_id != -1) {
492
            error_report("index cannot be used with bus and unit");
493 494
            return NULL;
        }
495 496
        bus_id = drive_index_to_bus_id(type, index);
        unit_id = drive_index_to_unit_id(type, index);
497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516
    }

    /* if user doesn't specify a unit_id,
     * try to find the first free
     */

    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++;
           }
       }
    }

    /* check unit id */

    if (max_devs && unit_id >= max_devs) {
517 518
        error_report("unit %d too big (max is %d)",
                     unit_id, max_devs - 1);
519 520 521 522
        return NULL;
    }

    /*
523
     * catch multiple definitions
524 525 526
     */

    if (drive_get(type, bus_id, unit_id) != NULL) {
527 528
        error_report("drive with bus=%d, unit=%d (index=%d) exists",
                     bus_id, unit_id, index);
529 530 531
        return NULL;
    }

532 533 534 535
    /* no id supplied -> create one */
    if (qemu_opts_id(opts) == NULL) {
        char *new_id;
        if (type == IF_IDE || type == IF_SCSI) {
536
            mediastr = (media == MEDIA_CDROM) ? "-cd" : "-hd";
537 538 539 540 541 542 543 544 545
        }
        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);
        }
        qemu_opts_set_id(opts, new_id);
546
    }
547 548 549 550

    /* init */
    dinfo = g_malloc0(sizeof(*dinfo));
    dinfo->id = g_strdup(qemu_opts_id(opts));
551
    dinfo->bdrv = bdrv_new(dinfo->id);
552 553
    dinfo->bdrv->open_flags = snapshot ? BDRV_O_SNAPSHOT : 0;
    dinfo->bdrv->read_only = ro;
554 555 556 557
    dinfo->devaddr = devaddr;
    dinfo->type = type;
    dinfo->bus = bus_id;
    dinfo->unit = unit_id;
558
    dinfo->refcount = 1;
559 560 561
    if (serial != NULL) {
        dinfo->serial = g_strdup(serial);
    }
562 563
    QTAILQ_INSERT_TAIL(&drives, dinfo, next);

564 565
    bdrv_set_on_error(dinfo->bdrv, on_read_error, on_write_error);

566
    /* disk I/O throttling */
567 568 569 570
    if (throttle_enabled(&cfg)) {
        bdrv_io_limits_enable(dinfo->bdrv);
        bdrv_set_io_limits(dinfo->bdrv, &cfg);
    }
571

572 573 574 575 576
    switch(type) {
    case IF_IDE:
    case IF_SCSI:
    case IF_XEN:
    case IF_NONE:
577
        dinfo->media_cd = media == MEDIA_CDROM;
578 579 580 581 582 583 584
        break;
    case IF_SD:
    case IF_FLOPPY:
    case IF_PFLASH:
    case IF_MTD:
        break;
    case IF_VIRTIO:
585
    {
586
        /* add virtio block device */
587 588
        QemuOpts *devopts;
        devopts = qemu_opts_create_nofail(qemu_find_opts("device"));
589
        if (arch_type == QEMU_ARCH_S390X) {
590
            qemu_opt_set(devopts, "driver", "virtio-blk-s390");
591
        } else {
592
            qemu_opt_set(devopts, "driver", "virtio-blk-pci");
593
        }
594
        qemu_opt_set(devopts, "drive", dinfo->id);
595
        if (devaddr)
596
            qemu_opt_set(devopts, "addr", devaddr);
597
        break;
598
    }
599
    default:
600 601
        abort();
    }
602
    if (!file || !*file) {
603
        if (has_driver_specific_opts) {
604 605 606 607
            file = NULL;
        } else {
            return dinfo;
        }
608 609 610 611 612 613 614
    }
    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);
    }

615 616 617 618
    if (copy_on_read) {
        bdrv_flags |= BDRV_O_COPY_ON_READ;
    }

619 620 621 622
    if (runstate_check(RUN_STATE_INMIGRATE)) {
        bdrv_flags |= BDRV_O_INCOMING;
    }

623 624 625 626
    if (media == MEDIA_CDROM) {
        /* CDROM is fine for any interface, don't check.  */
        ro = 1;
    } else if (ro == 1) {
627 628
        if (type != IF_SCSI && type != IF_VIRTIO && type != IF_FLOPPY &&
            type != IF_NONE && type != IF_PFLASH) {
629
            error_report("read-only not supported by this bus type");
630
            goto err;
631 632 633 634 635
        }
    }

    bdrv_flags |= ro ? 0 : BDRV_O_RDWR;

636
    if (ro && copy_on_read) {
637
        error_report("warning: disabling copy_on_read on read-only drive");
638 639
    }

640
    QINCREF(bs_opts);
641
    ret = bdrv_open(dinfo->bdrv, file, bs_opts, bdrv_flags, drv, &error);
642

643
    if (ret < 0) {
644 645
        error_report("could not open disk image %s: %s",
                     file ?: dinfo->id, error_get_pretty(error));
646
        goto err;
647 648 649 650
    }

    if (bdrv_key_required(dinfo->bdrv))
        autostart = 0;
651

652
    QDECREF(bs_opts);
653 654
    qemu_opts_del(opts);

655
    return dinfo;
656 657

err:
658 659
    qemu_opts_del(opts);
    QDECREF(bs_opts);
Fam Zheng's avatar
Fam Zheng committed
660
    bdrv_unref(dinfo->bdrv);
661
    g_free(dinfo->id);
662
    QTAILQ_REMOVE(&drives, dinfo, next);
663
    g_free(dinfo);
664
    return NULL;
665 666
}

667 668 669 670 671 672 673 674 675 676 677
static void qemu_opt_rename(QemuOpts *opts, const char *from, const char *to)
{
    const char *value;

    value = qemu_opt_get(opts, from);
    if (value) {
        qemu_opt_set(opts, to, value);
        qemu_opt_unset(opts, from);
    }
}

678 679 680 681 682 683 684 685
QemuOptsList qemu_legacy_drive_opts = {
    .name = "drive",
    .head = QTAILQ_HEAD_INITIALIZER(qemu_legacy_drive_opts.head),
    .desc = {
        {
            .name = "media",
            .type = QEMU_OPT_STRING,
            .help = "media type (disk, cdrom)",
686 687 688 689
        },{
            .name = "if",
            .type = QEMU_OPT_STRING,
            .help = "interface (ide, scsi, sd, mtd, floppy, pflash, virtio)",
690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705
        },{
            .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)",
706 707 708 709
        },{
            .name = "boot",
            .type = QEMU_OPT_BOOL,
            .help = "(deprecated, ignored)",
710 711 712 713 714
        },
        { /* end of list */ }
    },
};

715 716
DriveInfo *drive_init(QemuOpts *all_opts, BlockInterfaceType block_default_type)
{
717
    const char *value;
718
    DriveInfo *dinfo = NULL;
719
    QDict *bs_opts;
720 721
    QemuOpts *legacy_opts;
    DriveMediaType media = MEDIA_DISK;
722
    BlockInterfaceType type;
723
    int cyls, heads, secs, translation;
724
    Error *local_err = NULL;
725

726 727 728 729 730 731 732 733 734
    /* Change legacy command line options into QMP ones */
    qemu_opt_rename(all_opts, "iops", "throttling.iops-total");
    qemu_opt_rename(all_opts, "iops_rd", "throttling.iops-read");
    qemu_opt_rename(all_opts, "iops_wr", "throttling.iops-write");

    qemu_opt_rename(all_opts, "bps", "throttling.bps-total");
    qemu_opt_rename(all_opts, "bps_rd", "throttling.bps-read");
    qemu_opt_rename(all_opts, "bps_wr", "throttling.bps-write");

735 736 737 738 739 740 741 742
    qemu_opt_rename(all_opts, "iops_max", "throttling.iops-total-max");
    qemu_opt_rename(all_opts, "iops_rd_max", "throttling.iops-read-max");
    qemu_opt_rename(all_opts, "iops_wr_max", "throttling.iops-write-max");

    qemu_opt_rename(all_opts, "bps_max", "throttling.bps-total-max");
    qemu_opt_rename(all_opts, "bps_rd_max", "throttling.bps-read-max");
    qemu_opt_rename(all_opts, "bps_wr_max", "throttling.bps-write-max");

743 744 745
    qemu_opt_rename(all_opts,
                    "iops_size", "throttling.iops-size");

746 747
    qemu_opt_rename(all_opts, "readonly", "read-only");

748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772
    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");
    }

773 774 775 776
    /* Get a QDict for processing the options */
    bs_opts = qdict_new();
    qemu_opts_to_qdict(all_opts, bs_opts);

777 778 779 780 781 782 783 784
    legacy_opts = qemu_opts_create_nofail(&qemu_legacy_drive_opts);
    qemu_opts_absorb_qdict(legacy_opts, bs_opts, &local_err);
    if (error_is_set(&local_err)) {
        qerror_report_err(local_err);
        error_free(local_err);
        goto fail;
    }

785 786 787 788 789 790 791
    /* 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");
    }

792 793 794 795 796 797 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;
        } else {
            error_report("'%s' invalid media", value);
            goto fail;
        }
    }

805 806 807 808 809 810 811 812 813 814 815 816 817 818 819
    /* 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;
    }

820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 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
    /* 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;
        } 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;
        }
    }

867
    /* Actual block device init: Functionality shared with blockdev-add */
868
    dinfo = blockdev_init(bs_opts, type, media);
869 870 871 872 873 874
    if (dinfo == NULL) {
        goto fail;
    }

    /* Set legacy DriveInfo fields */
    dinfo->enable_auto_del = true;
875
    dinfo->opts = all_opts;
876

877 878 879 880 881
    dinfo->cyls = cyls;
    dinfo->heads = heads;
    dinfo->secs = secs;
    dinfo->trans = translation;

882
fail:
883
    qemu_opts_del(legacy_opts);
884
    return dinfo;
885 886
}

887 888 889
void do_commit(Monitor *mon, const QDict *qdict)
{
    const char *device = qdict_get_str(qdict, "device");
890
    BlockDriverState *bs;
891
    int ret;
892

893
    if (!strcmp(device, "all")) {
894
        ret = bdrv_commit_all();
895 896
    } else {
        bs = bdrv_find(device);
897
        if (!bs) {
898
            monitor_printf(mon, "Device '%s' not found\n", device);
899
            return;
900
        }
901
        ret = bdrv_commit(bs);
902 903 904 905
    }
    if (ret < 0) {
        monitor_printf(mon, "'commit' error for '%s': %s\n", device,
                       strerror(-ret));
906 907 908
    }
}

909 910
static void blockdev_do_action(int kind, void *data, Error **errp)
{
911 912
    TransactionAction action;
    TransactionActionList list;
913 914 915 916 917 918 919 920

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

921 922
void qmp_blockdev_snapshot_sync(const char *device, const char *snapshot_file,
                                bool has_format, const char *format,
923
                                bool has_mode, enum NewImageMode mode,
924
                                Error **errp)
925
{
926 927 928 929 930 931 932 933
    BlockdevSnapshot snapshot = {
        .device = (char *) device,
        .snapshot_file = (char *) snapshot_file,
        .has_format = has_format,
        .format = (char *) format,
        .has_mode = has_mode,
        .mode = mode,
    };
934 935
    blockdev_do_action(TRANSACTION_ACTION_KIND_BLOCKDEV_SNAPSHOT_SYNC,
                       &snapshot, errp);
936 937
}

938 939 940 941 942 943 944 945 946 947 948 949 950
void qmp_blockdev_snapshot_internal_sync(const char *device,
                                         const char *name,
                                         Error **errp)
{
    BlockdevSnapshotInternal snapshot = {
        .device = (char *) device,
        .name = (char *) name
    };

    blockdev_do_action(TRANSACTION_ACTION_KIND_BLOCKDEV_SNAPSHOT_INTERNAL_SYNC,
                       &snapshot, errp);
}

951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011
SnapshotInfo *qmp_blockdev_snapshot_delete_internal_sync(const char *device,
                                                         bool has_id,
                                                         const char *id,
                                                         bool has_name,
                                                         const char *name,
                                                         Error **errp)
{
    BlockDriverState *bs = bdrv_find(device);
    QEMUSnapshotInfo sn;
    Error *local_err = NULL;
    SnapshotInfo *info = NULL;
    int ret;

    if (!bs) {
        error_set(errp, QERR_DEVICE_NOT_FOUND, device);
        return NULL;
    }

    if (!has_id) {
        id = NULL;
    }

    if (!has_name) {
        name = NULL;
    }

    if (!id && !name) {
        error_setg(errp, "Name or id must be provided");
        return NULL;
    }

    ret = bdrv_snapshot_find_by_id_and_name(bs, id, name, &sn, &local_err);
    if (error_is_set(&local_err)) {
        error_propagate(errp, local_err);
        return NULL;
    }
    if (!ret) {
        error_setg(errp,
                   "Snapshot with id '%s' and name '%s' does not exist on "
                   "device '%s'",
                   STR_OR_NULL(id), STR_OR_NULL(name), device);
        return NULL;
    }

    bdrv_snapshot_delete(bs, id, name, &local_err);
    if (error_is_set(&local_err)) {
        error_propagate(errp, local_err);
        return NULL;
    }

    info = g_malloc0(sizeof(SnapshotInfo));
    info->id = g_strdup(sn.id_str);
    info->name = g_strdup(sn.name);
    info->date_nsec = sn.date_nsec;
    info->date_sec = sn.date_sec;
    info->vm_state_size = sn.vm_state_size;
    info->vm_clock_nsec = sn.vm_clock_nsec % 1000000000;
    info->vm_clock_sec = sn.vm_clock_nsec / 1000000000;

    return info;
}
1012 1013

/* New and old BlockDriverState structs for group snapshots */
1014

1015
typedef struct BlkTransactionState BlkTransactionState;
1016 1017 1018 1019 1020 1021 1022

/* Only prepare() may fail. In a single transaction, only one of commit() or
   abort() will be called, clean() will always be called if it present. */
typedef struct BdrvActionOps {
    /* Size of state struct, in bytes. */
    size_t instance_size;
    /* Prepare the work, must NOT be NULL. */
1023
    void (*prepare)(BlkTransactionState *common, Error **errp);
1024
    /* Commit the changes, can be NULL. */
1025
    void (*commit)(BlkTransactionState *common);
1026
    /* Abort the changes on fail, can be NULL. */
1027
    void (*abort)(BlkTransactionState *common);
1028
    /* Clean up resource in the end, can be NULL. */
1029
    void (*clean)(BlkTransactionState *common);
1030 1031 1032 1033 1034 1035 1036
} BdrvActionOps;

/*
 * This structure must be arranged as first member in child type, assuming
 * that compiler will also arrange it to the same address with parent instance.
 * Later it will be used in free().
 */
1037
struct BlkTransactionState {
1038
    TransactionAction *action;
1039
    const BdrvActionOps *ops;
1040
    QSIMPLEQ_ENTRY(BlkTransactionState) entry;
1041 1042
};

1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153
/* internal snapshot private data */
typedef struct InternalSnapshotState {
    BlkTransactionState common;
    BlockDriverState *bs;
    QEMUSnapshotInfo sn;
} InternalSnapshotState;

static void internal_snapshot_prepare(BlkTransactionState *common,
                                      Error **errp)
{
    const char *device;
    const char *name;
    BlockDriverState *bs;
    QEMUSnapshotInfo old_sn, *sn;
    bool ret;
    qemu_timeval tv;
    BlockdevSnapshotInternal *internal;
    InternalSnapshotState *state;
    int ret1;

    g_assert(common->action->kind ==
             TRANSACTION_ACTION_KIND_BLOCKDEV_SNAPSHOT_INTERNAL_SYNC);
    internal = common->action->blockdev_snapshot_internal_sync;
    state = DO_UPCAST(InternalSnapshotState, common, common);

    /* 1. parse input */
    device = internal->device;
    name = internal->name;

    /* 2. check for validation */
    bs = bdrv_find(device);
    if (!bs) {
        error_set(errp, QERR_DEVICE_NOT_FOUND, device);
        return;
    }

    if (!bdrv_is_inserted(bs)) {
        error_set(errp, QERR_DEVICE_HAS_NO_MEDIUM, device);
        return;
    }

    if (bdrv_is_read_only(bs)) {
        error_set(errp, QERR_DEVICE_IS_READ_ONLY, device);
        return;
    }

    if (!bdrv_can_snapshot(bs)) {
        error_set(errp, QERR_BLOCK_FORMAT_FEATURE_NOT_SUPPORTED,
                  bs->drv->format_name, device, "internal snapshot");
        return;
    }

    if (!strlen(name)) {
        error_setg(errp, "Name is empty");
        return;
    }

    /* check whether a snapshot with name exist */
    ret = bdrv_snapshot_find_by_id_and_name(bs, NULL, name, &old_sn, errp);
    if (error_is_set(errp)) {
        return;
    } else if (ret) {
        error_setg(errp,
                   "Snapshot with name '%s' already exists on device '%s'",
                   name, device);
        return;
    }

    /* 3. take the snapshot */
    sn = &state->sn;
    pstrcpy(sn->name, sizeof(sn->name), name);
    qemu_gettimeofday(&tv);
    sn->date_sec = tv.tv_sec;
    sn->date_nsec = tv.tv_usec * 1000;
    sn->vm_clock_nsec = qemu_clock_get_ns(QEMU_CLOCK_VIRTUAL);

    ret1 = bdrv_snapshot_create(bs, sn);
    if (ret1 < 0) {
        error_setg_errno(errp, -ret1,
                         "Failed to create snapshot '%s' on device '%s'",
                         name, device);
        return;
    }

    /* 4. succeed, mark a snapshot is created */
    state->bs = bs;
}

static void internal_snapshot_abort(BlkTransactionState *common)
{
    InternalSnapshotState *state =
                             DO_UPCAST(InternalSnapshotState, common, common);
    BlockDriverState *bs = state->bs;
    QEMUSnapshotInfo *sn = &state->sn;
    Error *local_error = NULL;

    if (!bs) {
        return;
    }

    if (bdrv_snapshot_delete(bs, sn->id_str, sn->name, &local_error) < 0) {
        error_report("Failed to delete snapshot with id '%s' and name '%s' on "
                     "device '%s' in abort: %s",
                     sn->id_str,
                     sn->name,
                     bdrv_get_device_name(bs),
                     error_get_pretty(local_error));
        error_free(local_error);
    }
}

1154
/* external snapshot private data */
1155 1156
typedef struct ExternalSnapshotState {
    BlkTransactionState common;
1157 1158
    BlockDriverState *old_bs;
    BlockDriverState *new_bs;
1159
} ExternalSnapshotState;
1160

1161
static void external_snapshot_prepare(BlkTransactionState *common,
1162 1163 1164 1165 1166
                                      Error **errp)
{
    BlockDriver *drv;
    int flags, ret;
    Error *local_err = NULL;
1167 1168 1169 1170
    const char *device;
    const char *new_image_file;
    const char *format = "qcow2";
    enum NewImageMode mode = NEW_IMAGE_MODE_ABSOLUTE_PATHS;
1171 1172
    ExternalSnapshotState *state =
                             DO_UPCAST(ExternalSnapshotState, common, common);
1173
    TransactionAction *action = common->action;
1174

1175
    /* get parameters */
1176
    g_assert(action->kind == TRANSACTION_ACTION_KIND_BLOCKDEV_SNAPSHOT_SYNC);
1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187

    device = action->blockdev_snapshot_sync->device;
    new_image_file = action->blockdev_snapshot_sync->snapshot_file;
    if (action->blockdev_snapshot_sync->has_format) {
        format = action->blockdev_snapshot_sync->format;
    }
    if (action->blockdev_snapshot_sync->has_mode) {
        mode = action->blockdev_snapshot_sync->mode;
    }

    /* start processing */
1188 1189 1190 1191 1192 1193
    drv = bdrv_find_format(format);
    if (!drv) {
        error_set(errp, QERR_INVALID_BLOCK_FORMAT, format);
        return;
    }

1194 1195
    state->old_bs = bdrv_find(device);
    if (!state->old_bs) {
1196 1197 1198 1199
        error_set(errp, QERR_DEVICE_NOT_FOUND, device);
        return;
    }

1200
    if (!bdrv_is_inserted(state->old_bs)) {
1201 1202 1203 1204
        error_set(errp, QERR_DEVICE_HAS_NO_MEDIUM, device);
        return;
    }

1205
    if (bdrv_in_use(state->old_bs)) {
1206 1207 1208 1209
        error_set(errp, QERR_DEVICE_IN_USE, device);
        return;
    }

1210 1211
    if (!bdrv_is_read_only(state->old_bs)) {
        if (bdrv_flush(state->old_bs)) {
1212 1213 1214 1215 1216
            error_set(errp, QERR_IO_ERROR);
            return;
        }
    }

1217 1218 1219 1220 1221
    if (bdrv_check_ext_snapshot(state->old_bs) != EXT_SNAPSHOT_ALLOWED) {
        error_set(errp, QERR_FEATURE_DISABLED, "snapshot");
        return;
    }

1222
    flags = state->old_bs->open_flags;
1223 1224 1225 1226

    /* create new image w/backing file */
    if (mode != NEW_IMAGE_MODE_EXISTING) {
        bdrv_img_create(new_image_file, format,
1227 1228
                        state->old_bs->filename,
                        state->old_bs->drv->format_name,
1229 1230 1231 1232 1233 1234 1235 1236
                        NULL, -1, flags, &local_err, false);
        if (error_is_set(&local_err)) {
            error_propagate(errp, local_err);
            return;
        }
    }

    /* We will manually add the backing_hd field to the bs later */
1237
    state->new_bs = bdrv_new("");
1238 1239
    /* TODO Inherit bs->options or only take explicit options with an
     * extended QMP command? */
1240
    ret = bdrv_open(state->new_bs, new_image_file, NULL,
1241
                    flags | BDRV_O_NO_BACKING, drv, &local_err);
1242
    if (ret != 0) {
1243
        error_propagate(errp, local_err);
1244 1245 1246
    }
}

1247
static void external_snapshot_commit(BlkTransactionState *common)
1248
{
1249 1250
    ExternalSnapshotState *state =
                             DO_UPCAST(ExternalSnapshotState, common, common);
1251

1252 1253
    /* This removes our old bs and adds the new bs */
    bdrv_append(state->new_bs, state->old_bs);
1254 1255 1256
    /* We don't need (or want) to use the transactional
     * bdrv_reopen_multiple() across all the entries at once, because we
     * don't want to abort all of them if one of them fails the reopen */
1257
    bdrv_reopen(state->new_bs, state->new_bs->open_flags & ~BDRV_O_RDWR,
1258 1259 1260
                NULL);
}

1261
static void external_snapshot_abort(BlkTransactionState *common)
1262
{
1263 1264 1265
    ExternalSnapshotState *state =
                             DO_UPCAST(ExternalSnapshotState, common, common);
    if (state->new_bs) {
Fam Zheng's avatar
Fam Zheng committed
1266
        bdrv_unref(state->new_bs);
1267 1268 1269
    }
}

1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286
typedef struct DriveBackupState {
    BlkTransactionState common;
    BlockDriverState *bs;
    BlockJob *job;
} DriveBackupState;

static void drive_backup_prepare(BlkTransactionState *common, Error **errp)
{
    DriveBackupState *state = DO_UPCAST(DriveBackupState, common, common);
    DriveBackup *backup;
    Error *local_err = NULL;

    assert(common->action->kind == TRANSACTION_ACTION_KIND_DRIVE_BACKUP);
    backup = common->action->drive_backup;

    qmp_drive_backup(backup->device, backup->target,
                     backup->has_format, backup->format,
1287
                     backup->sync,
1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314
                     backup->has_mode, backup->mode,
                     backup->has_speed, backup->speed,
                     backup->has_on_source_error, backup->on_source_error,
                     backup->has_on_target_error, backup->on_target_error,
                     &local_err);
    if (error_is_set(&local_err)) {
        error_propagate(errp, local_err);
        state->bs = NULL;
        state->job = NULL;
        return;
    }

    state->bs = bdrv_find(backup->device);
    state->job = state->bs->job;
}

static void drive_backup_abort(BlkTransactionState *common)
{
    DriveBackupState *state = DO_UPCAST(DriveBackupState, common, common);
    BlockDriverState *bs = state->bs;

    /* Only cancel if it's the job we started */
    if (bs && bs->job && bs->job == state->job) {
        block_job_cancel_sync(bs->job);
    }
}

1315 1316 1317 1318 1319 1320 1321
static void abort_prepare(BlkTransactionState *common, Error **errp)
{
    error_setg(errp, "Transaction aborted using Abort action");
}

static void abort_commit(BlkTransactionState *common)
{
1322
    g_assert_not_reached(); /* this action never succeeds */
1323 1324
}

1325
static const BdrvActionOps actions[] = {
1326
    [TRANSACTION_ACTION_KIND_BLOCKDEV_SNAPSHOT_SYNC] = {
1327
        .instance_size = sizeof(ExternalSnapshotState),
1328 1329 1330 1331
        .prepare  = external_snapshot_prepare,
        .commit   = external_snapshot_commit,
        .abort = external_snapshot_abort,
    },
1332 1333 1334 1335 1336
    [TRANSACTION_ACTION_KIND_DRIVE_BACKUP] = {
        .instance_size = sizeof(DriveBackupState),
        .prepare = drive_backup_prepare,
        .abort = drive_backup_abort,
    },
1337 1338 1339 1340 1341
    [TRANSACTION_ACTION_KIND_ABORT] = {
        .instance_size = sizeof(BlkTransactionState),
        .prepare = abort_prepare,
        .commit = abort_commit,
    },
1342 1343 1344 1345 1346
    [TRANSACTION_ACTION_KIND_BLOCKDEV_SNAPSHOT_INTERNAL_SYNC] = {
        .instance_size = sizeof(InternalSnapshotState),
        .prepare  = internal_snapshot_prepare,
        .abort = internal_snapshot_abort,
    },
1347 1348
};

1349 1350 1351 1352 1353
/*
 * 'Atomic' group snapshots.  The snapshots are taken as a set, and if any fail
 *  then we do not pivot any of the devices in the group, and abandon the
 *  snapshots
 */
1354
void qmp_transaction(TransactionActionList *dev_list, Error **errp)
1355
{
1356
    TransactionActionList *dev_entry = dev_list;
1357
    BlkTransactionState *state, *next;
1358
    Error *local_err = NULL;
1359

1360
    QSIMPLEQ_HEAD(snap_bdrv_states, BlkTransactionState) snap_bdrv_states;
1361 1362 1363 1364 1365 1366 1367
    QSIMPLEQ_INIT(&snap_bdrv_states);

    /* drain all i/o before any snapshots */
    bdrv_drain_all();