qemu/blockdev.c
<<
>>
Prefs
   1/*
   2 * QEMU host block devices
   3 *
   4 * Copyright (c) 2003-2008 Fabrice Bellard
   5 *
   6 * This work is licensed under the terms of the GNU GPL, version 2 or
   7 * later.  See the COPYING file in the top-level directory.
   8 *
   9 * This file incorporates work covered by the following copyright and
  10 * permission notice:
  11 *
  12 * Copyright (c) 2003-2008 Fabrice Bellard
  13 *
  14 * Permission is hereby granted, free of charge, to any person obtaining a copy
  15 * of this software and associated documentation files (the "Software"), to deal
  16 * in the Software without restriction, including without limitation the rights
  17 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  18 * copies of the Software, and to permit persons to whom the Software is
  19 * furnished to do so, subject to the following conditions:
  20 *
  21 * The above copyright notice and this permission notice shall be included in
  22 * all copies or substantial portions of the Software.
  23 *
  24 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  25 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  26 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
  27 * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  28 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  29 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  30 * THE SOFTWARE.
  31 */
  32
  33#include "qemu/osdep.h"
  34#include "sysemu/block-backend.h"
  35#include "sysemu/blockdev.h"
  36#include "hw/block/block.h"
  37#include "block/blockjob.h"
  38#include "block/throttle-groups.h"
  39#include "monitor/monitor.h"
  40#include "qemu/error-report.h"
  41#include "qemu/option.h"
  42#include "qemu/config-file.h"
  43#include "qapi/qmp/types.h"
  44#include "qapi-visit.h"
  45#include "qapi/qmp/qerror.h"
  46#include "qapi/qmp-output-visitor.h"
  47#include "qapi/util.h"
  48#include "sysemu/sysemu.h"
  49#include "block/block_int.h"
  50#include "qmp-commands.h"
  51#include "trace.h"
  52#include "sysemu/arch_init.h"
  53#include "qemu/cutils.h"
  54#include "qemu/help_option.h"
  55
  56static QTAILQ_HEAD(, BlockDriverState) monitor_bdrv_states =
  57    QTAILQ_HEAD_INITIALIZER(monitor_bdrv_states);
  58
  59static const char *const if_name[IF_COUNT] = {
  60    [IF_NONE] = "none",
  61    [IF_IDE] = "ide",
  62    [IF_SCSI] = "scsi",
  63    [IF_FLOPPY] = "floppy",
  64    [IF_PFLASH] = "pflash",
  65    [IF_MTD] = "mtd",
  66    [IF_SD] = "sd",
  67    [IF_VIRTIO] = "virtio",
  68    [IF_XEN] = "xen",
  69};
  70
  71static int if_max_devs[IF_COUNT] = {
  72    /*
  73     * Do not change these numbers!  They govern how drive option
  74     * index maps to unit and bus.  That mapping is ABI.
  75     *
  76     * All controllers used to imlement if=T drives need to support
  77     * if_max_devs[T] units, for any T with if_max_devs[T] != 0.
  78     * Otherwise, some index values map to "impossible" bus, unit
  79     * values.
  80     *
  81     * For instance, if you change [IF_SCSI] to 255, -drive
  82     * if=scsi,index=12 no longer means bus=1,unit=5, but
  83     * bus=0,unit=12.  With an lsi53c895a controller (7 units max),
  84     * the drive can't be set up.  Regression.
  85     */
  86    [IF_IDE] = 2,
  87    [IF_SCSI] = 7,
  88};
  89
  90/**
  91 * Boards may call this to offer board-by-board overrides
  92 * of the default, global values.
  93 */
  94void override_max_devs(BlockInterfaceType type, int max_devs)
  95{
  96    BlockBackend *blk;
  97    DriveInfo *dinfo;
  98
  99    if (max_devs <= 0) {
 100        return;
 101    }
 102
 103    for (blk = blk_next(NULL); blk; blk = blk_next(blk)) {
 104        dinfo = blk_legacy_dinfo(blk);
 105        if (dinfo->type == type) {
 106            fprintf(stderr, "Cannot override units-per-bus property of"
 107                    " the %s interface, because a drive of that type has"
 108                    " already been added.\n", if_name[type]);
 109            g_assert_not_reached();
 110        }
 111    }
 112
 113    if_max_devs[type] = max_devs;
 114}
 115
 116/*
 117 * We automatically delete the drive when a device using it gets
 118 * unplugged.  Questionable feature, but we can't just drop it.
 119 * Device models call blockdev_mark_auto_del() to schedule the
 120 * automatic deletion, and generic qdev code calls blockdev_auto_del()
 121 * when deletion is actually safe.
 122 */
 123void blockdev_mark_auto_del(BlockBackend *blk)
 124{
 125    DriveInfo *dinfo = blk_legacy_dinfo(blk);
 126    BlockDriverState *bs = blk_bs(blk);
 127    AioContext *aio_context;
 128
 129    if (!dinfo) {
 130        return;
 131    }
 132
 133    if (bs) {
 134        aio_context = bdrv_get_aio_context(bs);
 135        aio_context_acquire(aio_context);
 136
 137        if (bs->job) {
 138            block_job_cancel(bs->job);
 139        }
 140
 141        aio_context_release(aio_context);
 142    }
 143
 144    dinfo->auto_del = 1;
 145}
 146
 147void blockdev_auto_del(BlockBackend *blk)
 148{
 149    DriveInfo *dinfo = blk_legacy_dinfo(blk);
 150
 151    if (dinfo && dinfo->auto_del) {
 152        monitor_remove_blk(blk);
 153        blk_unref(blk);
 154    }
 155}
 156
 157/**
 158 * Returns the current mapping of how many units per bus
 159 * a particular interface can support.
 160 *
 161 *  A positive integer indicates n units per bus.
 162 *  0 implies the mapping has not been established.
 163 * -1 indicates an invalid BlockInterfaceType was given.
 164 */
 165int drive_get_max_devs(BlockInterfaceType type)
 166{
 167    if (type >= IF_IDE && type < IF_COUNT) {
 168        return if_max_devs[type];
 169    }
 170
 171    return -1;
 172}
 173
 174static int drive_index_to_bus_id(BlockInterfaceType type, int index)
 175{
 176    int max_devs = if_max_devs[type];
 177    return max_devs ? index / max_devs : 0;
 178}
 179
 180static int drive_index_to_unit_id(BlockInterfaceType type, int index)
 181{
 182    int max_devs = if_max_devs[type];
 183    return max_devs ? index % max_devs : index;
 184}
 185
 186QemuOpts *drive_def(const char *optstr)
 187{
 188    return qemu_opts_parse_noisily(qemu_find_opts("drive"), optstr, false);
 189}
 190
 191QemuOpts *drive_add(BlockInterfaceType type, int index, const char *file,
 192                    const char *optstr)
 193{
 194    QemuOpts *opts;
 195
 196    opts = drive_def(optstr);
 197    if (!opts) {
 198        return NULL;
 199    }
 200    if (type != IF_DEFAULT) {
 201        qemu_opt_set(opts, "if", if_name[type], &error_abort);
 202    }
 203    if (index >= 0) {
 204        qemu_opt_set_number(opts, "index", index, &error_abort);
 205    }
 206    if (file)
 207        qemu_opt_set(opts, "file", file, &error_abort);
 208    return opts;
 209}
 210
 211DriveInfo *drive_get(BlockInterfaceType type, int bus, int unit)
 212{
 213    BlockBackend *blk;
 214    DriveInfo *dinfo;
 215
 216    for (blk = blk_next(NULL); blk; blk = blk_next(blk)) {
 217        dinfo = blk_legacy_dinfo(blk);
 218        if (dinfo && dinfo->type == type
 219            && dinfo->bus == bus && dinfo->unit == unit) {
 220            return dinfo;
 221        }
 222    }
 223
 224    return NULL;
 225}
 226
 227bool drive_check_orphaned(void)
 228{
 229    BlockBackend *blk;
 230    DriveInfo *dinfo;
 231    bool rs = false;
 232
 233    for (blk = blk_next(NULL); blk; blk = blk_next(blk)) {
 234        dinfo = blk_legacy_dinfo(blk);
 235        /* If dinfo->bdrv->dev is NULL, it has no device attached. */
 236        /* Unless this is a default drive, this may be an oversight. */
 237        if (!blk_get_attached_dev(blk) && !dinfo->is_default &&
 238            dinfo->type != IF_NONE) {
 239            fprintf(stderr, "Warning: Orphaned drive without device: "
 240                    "id=%s,file=%s,if=%s,bus=%d,unit=%d\n",
 241                    blk_name(blk), blk_bs(blk) ? blk_bs(blk)->filename : "",
 242                    if_name[dinfo->type], dinfo->bus, dinfo->unit);
 243            rs = true;
 244        }
 245    }
 246
 247    return rs;
 248}
 249
 250DriveInfo *drive_get_by_index(BlockInterfaceType type, int index)
 251{
 252    return drive_get(type,
 253                     drive_index_to_bus_id(type, index),
 254                     drive_index_to_unit_id(type, index));
 255}
 256
 257int drive_get_max_bus(BlockInterfaceType type)
 258{
 259    int max_bus;
 260    BlockBackend *blk;
 261    DriveInfo *dinfo;
 262
 263    max_bus = -1;
 264    for (blk = blk_next(NULL); blk; blk = blk_next(blk)) {
 265        dinfo = blk_legacy_dinfo(blk);
 266        if (dinfo && dinfo->type == type && dinfo->bus > max_bus) {
 267            max_bus = dinfo->bus;
 268        }
 269    }
 270    return max_bus;
 271}
 272
 273/* Get a block device.  This should only be used for single-drive devices
 274   (e.g. SD/Floppy/MTD).  Multi-disk devices (scsi/ide) should use the
 275   appropriate bus.  */
 276DriveInfo *drive_get_next(BlockInterfaceType type)
 277{
 278    static int next_block_unit[IF_COUNT];
 279
 280    return drive_get(type, 0, next_block_unit[type]++);
 281}
 282
 283static void bdrv_format_print(void *opaque, const char *name)
 284{
 285    error_printf(" %s", name);
 286}
 287
 288typedef struct {
 289    QEMUBH *bh;
 290    BlockDriverState *bs;
 291} BDRVPutRefBH;
 292
 293static int parse_block_error_action(const char *buf, bool is_read, Error **errp)
 294{
 295    if (!strcmp(buf, "ignore")) {
 296        return BLOCKDEV_ON_ERROR_IGNORE;
 297    } else if (!is_read && !strcmp(buf, "enospc")) {
 298        return BLOCKDEV_ON_ERROR_ENOSPC;
 299    } else if (!strcmp(buf, "stop")) {
 300        return BLOCKDEV_ON_ERROR_STOP;
 301    } else if (!strcmp(buf, "report")) {
 302        return BLOCKDEV_ON_ERROR_REPORT;
 303    } else {
 304        error_setg(errp, "'%s' invalid %s error action",
 305                   buf, is_read ? "read" : "write");
 306        return -1;
 307    }
 308}
 309
 310static bool parse_stats_intervals(BlockAcctStats *stats, QList *intervals,
 311                                  Error **errp)
 312{
 313    const QListEntry *entry;
 314    for (entry = qlist_first(intervals); entry; entry = qlist_next(entry)) {
 315        switch (qobject_type(entry->value)) {
 316
 317        case QTYPE_QSTRING: {
 318            unsigned long long length;
 319            const char *str = qstring_get_str(qobject_to_qstring(entry->value));
 320            if (parse_uint_full(str, &length, 10) == 0 &&
 321                length > 0 && length <= UINT_MAX) {
 322                block_acct_add_interval(stats, (unsigned) length);
 323            } else {
 324                error_setg(errp, "Invalid interval length: %s", str);
 325                return false;
 326            }
 327            break;
 328        }
 329
 330        case QTYPE_QINT: {
 331            int64_t length = qint_get_int(qobject_to_qint(entry->value));
 332            if (length > 0 && length <= UINT_MAX) {
 333                block_acct_add_interval(stats, (unsigned) length);
 334            } else {
 335                error_setg(errp, "Invalid interval length: %" PRId64, length);
 336                return false;
 337            }
 338            break;
 339        }
 340
 341        default:
 342            error_setg(errp, "The specification of stats-intervals is invalid");
 343            return false;
 344        }
 345    }
 346    return true;
 347}
 348
 349typedef enum { MEDIA_DISK, MEDIA_CDROM } DriveMediaType;
 350
 351/* All parameters but @opts are optional and may be set to NULL. */
 352static void extract_common_blockdev_options(QemuOpts *opts, int *bdrv_flags,
 353    const char **throttling_group, ThrottleConfig *throttle_cfg,
 354    BlockdevDetectZeroesOptions *detect_zeroes, Error **errp)
 355{
 356    const char *discard;
 357    Error *local_error = NULL;
 358    const char *aio;
 359
 360    if (bdrv_flags) {
 361        if (!qemu_opt_get_bool(opts, "read-only", false)) {
 362            *bdrv_flags |= BDRV_O_RDWR;
 363        }
 364        if (qemu_opt_get_bool(opts, "copy-on-read", false)) {
 365            *bdrv_flags |= BDRV_O_COPY_ON_READ;
 366        }
 367
 368        if ((discard = qemu_opt_get(opts, "discard")) != NULL) {
 369            if (bdrv_parse_discard_flags(discard, bdrv_flags) != 0) {
 370                error_setg(errp, "Invalid discard option");
 371                return;
 372            }
 373        }
 374
 375        if ((aio = qemu_opt_get(opts, "aio")) != NULL) {
 376            if (!strcmp(aio, "native")) {
 377                *bdrv_flags |= BDRV_O_NATIVE_AIO;
 378            } else if (!strcmp(aio, "threads")) {
 379                /* this is the default */
 380            } else {
 381               error_setg(errp, "invalid aio option");
 382               return;
 383            }
 384        }
 385    }
 386
 387    /* disk I/O throttling */
 388    if (throttling_group) {
 389        *throttling_group = qemu_opt_get(opts, "throttling.group");
 390    }
 391
 392    if (throttle_cfg) {
 393        throttle_config_init(throttle_cfg);
 394        throttle_cfg->buckets[THROTTLE_BPS_TOTAL].avg =
 395            qemu_opt_get_number(opts, "throttling.bps-total", 0);
 396        throttle_cfg->buckets[THROTTLE_BPS_READ].avg  =
 397            qemu_opt_get_number(opts, "throttling.bps-read", 0);
 398        throttle_cfg->buckets[THROTTLE_BPS_WRITE].avg =
 399            qemu_opt_get_number(opts, "throttling.bps-write", 0);
 400        throttle_cfg->buckets[THROTTLE_OPS_TOTAL].avg =
 401            qemu_opt_get_number(opts, "throttling.iops-total", 0);
 402        throttle_cfg->buckets[THROTTLE_OPS_READ].avg =
 403            qemu_opt_get_number(opts, "throttling.iops-read", 0);
 404        throttle_cfg->buckets[THROTTLE_OPS_WRITE].avg =
 405            qemu_opt_get_number(opts, "throttling.iops-write", 0);
 406
 407        throttle_cfg->buckets[THROTTLE_BPS_TOTAL].max =
 408            qemu_opt_get_number(opts, "throttling.bps-total-max", 0);
 409        throttle_cfg->buckets[THROTTLE_BPS_READ].max  =
 410            qemu_opt_get_number(opts, "throttling.bps-read-max", 0);
 411        throttle_cfg->buckets[THROTTLE_BPS_WRITE].max =
 412            qemu_opt_get_number(opts, "throttling.bps-write-max", 0);
 413        throttle_cfg->buckets[THROTTLE_OPS_TOTAL].max =
 414            qemu_opt_get_number(opts, "throttling.iops-total-max", 0);
 415        throttle_cfg->buckets[THROTTLE_OPS_READ].max =
 416            qemu_opt_get_number(opts, "throttling.iops-read-max", 0);
 417        throttle_cfg->buckets[THROTTLE_OPS_WRITE].max =
 418            qemu_opt_get_number(opts, "throttling.iops-write-max", 0);
 419
 420        throttle_cfg->buckets[THROTTLE_BPS_TOTAL].burst_length =
 421            qemu_opt_get_number(opts, "throttling.bps-total-max-length", 1);
 422        throttle_cfg->buckets[THROTTLE_BPS_READ].burst_length  =
 423            qemu_opt_get_number(opts, "throttling.bps-read-max-length", 1);
 424        throttle_cfg->buckets[THROTTLE_BPS_WRITE].burst_length =
 425            qemu_opt_get_number(opts, "throttling.bps-write-max-length", 1);
 426        throttle_cfg->buckets[THROTTLE_OPS_TOTAL].burst_length =
 427            qemu_opt_get_number(opts, "throttling.iops-total-max-length", 1);
 428        throttle_cfg->buckets[THROTTLE_OPS_READ].burst_length =
 429            qemu_opt_get_number(opts, "throttling.iops-read-max-length", 1);
 430        throttle_cfg->buckets[THROTTLE_OPS_WRITE].burst_length =
 431            qemu_opt_get_number(opts, "throttling.iops-write-max-length", 1);
 432
 433        throttle_cfg->op_size =
 434            qemu_opt_get_number(opts, "throttling.iops-size", 0);
 435
 436        if (!throttle_is_valid(throttle_cfg, errp)) {
 437            return;
 438        }
 439    }
 440
 441    if (detect_zeroes) {
 442        *detect_zeroes =
 443            qapi_enum_parse(BlockdevDetectZeroesOptions_lookup,
 444                            qemu_opt_get(opts, "detect-zeroes"),
 445                            BLOCKDEV_DETECT_ZEROES_OPTIONS__MAX,
 446                            BLOCKDEV_DETECT_ZEROES_OPTIONS_OFF,
 447                            &local_error);
 448        if (local_error) {
 449            error_propagate(errp, local_error);
 450            return;
 451        }
 452
 453        if (bdrv_flags &&
 454            *detect_zeroes == BLOCKDEV_DETECT_ZEROES_OPTIONS_UNMAP &&
 455            !(*bdrv_flags & BDRV_O_UNMAP))
 456        {
 457            error_setg(errp, "setting detect-zeroes to unmap is not allowed "
 458                             "without setting discard operation to unmap");
 459            return;
 460        }
 461    }
 462}
 463
 464/* Takes the ownership of bs_opts */
 465static BlockBackend *blockdev_init(const char *file, QDict *bs_opts,
 466                                   Error **errp)
 467{
 468    const char *buf;
 469    int bdrv_flags = 0;
 470    int on_read_error, on_write_error;
 471    bool account_invalid, account_failed;
 472    bool writethrough;
 473    BlockBackend *blk;
 474    BlockDriverState *bs;
 475    ThrottleConfig cfg;
 476    int snapshot = 0;
 477    Error *error = NULL;
 478    QemuOpts *opts;
 479    QDict *interval_dict = NULL;
 480    QList *interval_list = NULL;
 481    const char *id;
 482    BlockdevDetectZeroesOptions detect_zeroes =
 483        BLOCKDEV_DETECT_ZEROES_OPTIONS_OFF;
 484    const char *blk_id;
 485    const char *throttling_group = NULL;
 486
 487    /* Check common options by copying from bs_opts to opts, all other options
 488     * stay in bs_opts for processing by bdrv_open(). */
 489    id = qdict_get_try_str(bs_opts, "id");
 490    opts = qemu_opts_create(&qemu_common_drive_opts, id, 1, &error);
 491    if (error) {
 492        error_propagate(errp, error);
 493        goto err_no_opts;
 494    }
 495
 496    qemu_opts_absorb_qdict(opts, bs_opts, &error);
 497    if (error) {
 498        error_propagate(errp, error);
 499        goto early_err;
 500    }
 501
 502    if (id) {
 503        qdict_del(bs_opts, "id");
 504    }
 505
 506    /* extract parameters */
 507    snapshot = qemu_opt_get_bool(opts, "snapshot", 0);
 508
 509    account_invalid = qemu_opt_get_bool(opts, "stats-account-invalid", true);
 510    account_failed = qemu_opt_get_bool(opts, "stats-account-failed", true);
 511
 512    writethrough = !qemu_opt_get_bool(opts, BDRV_OPT_CACHE_WB, true);
 513
 514    blk_id = qemu_opts_id(opts);
 515
 516    qdict_extract_subqdict(bs_opts, &interval_dict, "stats-intervals.");
 517    qdict_array_split(interval_dict, &interval_list);
 518
 519    if (qdict_size(interval_dict) != 0) {
 520        error_setg(errp, "Invalid option stats-intervals.%s",
 521                   qdict_first(interval_dict)->key);
 522        goto early_err;
 523    }
 524
 525    extract_common_blockdev_options(opts, &bdrv_flags, &throttling_group, &cfg,
 526                                    &detect_zeroes, &error);
 527    if (error) {
 528        error_propagate(errp, error);
 529        goto early_err;
 530    }
 531
 532    if ((buf = qemu_opt_get(opts, "format")) != NULL) {
 533        if (is_help_option(buf)) {
 534            error_printf("Supported formats:");
 535            bdrv_iterate_format(bdrv_format_print, NULL);
 536            error_printf("\n");
 537            goto early_err;
 538        }
 539
 540        if (qdict_haskey(bs_opts, "driver")) {
 541            error_setg(errp, "Cannot specify both 'driver' and 'format'");
 542            goto early_err;
 543        }
 544        qdict_put(bs_opts, "driver", qstring_from_str(buf));
 545    }
 546
 547    on_write_error = BLOCKDEV_ON_ERROR_ENOSPC;
 548    if ((buf = qemu_opt_get(opts, "werror")) != NULL) {
 549        on_write_error = parse_block_error_action(buf, 0, &error);
 550        if (error) {
 551            error_propagate(errp, error);
 552            goto early_err;
 553        }
 554    }
 555
 556    on_read_error = BLOCKDEV_ON_ERROR_REPORT;
 557    if ((buf = qemu_opt_get(opts, "rerror")) != NULL) {
 558        on_read_error = parse_block_error_action(buf, 1, &error);
 559        if (error) {
 560            error_propagate(errp, error);
 561            goto early_err;
 562        }
 563    }
 564
 565    if (snapshot) {
 566        bdrv_flags |= BDRV_O_SNAPSHOT;
 567    }
 568
 569    /* init */
 570    if ((!file || !*file) && !qdict_size(bs_opts)) {
 571        BlockBackendRootState *blk_rs;
 572
 573        blk = blk_new(errp);
 574        if (!blk) {
 575            goto early_err;
 576        }
 577
 578        blk_rs = blk_get_root_state(blk);
 579        blk_rs->open_flags    = bdrv_flags;
 580        blk_rs->read_only     = !(bdrv_flags & BDRV_O_RDWR);
 581        blk_rs->detect_zeroes = detect_zeroes;
 582
 583        if (throttle_enabled(&cfg)) {
 584            if (!throttling_group) {
 585                throttling_group = blk_id;
 586            }
 587            blk_rs->throttle_group = g_strdup(throttling_group);
 588            blk_rs->throttle_state = throttle_group_incref(throttling_group);
 589            blk_rs->throttle_state->cfg = cfg;
 590        }
 591
 592        QDECREF(bs_opts);
 593    } else {
 594        if (file && !*file) {
 595            file = NULL;
 596        }
 597
 598        /* bdrv_open() defaults to the values in bdrv_flags (for compatibility
 599         * with other callers) rather than what we want as the real defaults.
 600         * Apply the defaults here instead. */
 601        qdict_set_default_str(bs_opts, BDRV_OPT_CACHE_DIRECT, "off");
 602        qdict_set_default_str(bs_opts, BDRV_OPT_CACHE_NO_FLUSH, "off");
 603        assert((bdrv_flags & BDRV_O_CACHE_MASK) == 0);
 604
 605        if (runstate_check(RUN_STATE_INMIGRATE)) {
 606            bdrv_flags |= BDRV_O_INACTIVE;
 607        }
 608
 609        blk = blk_new_open(file, NULL, bs_opts, bdrv_flags, errp);
 610        if (!blk) {
 611            goto err_no_bs_opts;
 612        }
 613        bs = blk_bs(blk);
 614
 615        bs->detect_zeroes = detect_zeroes;
 616
 617        /* disk I/O throttling */
 618        if (throttle_enabled(&cfg)) {
 619            if (!throttling_group) {
 620                throttling_group = blk_id;
 621            }
 622            bdrv_io_limits_enable(bs, throttling_group);
 623            bdrv_set_io_limits(bs, &cfg);
 624        }
 625
 626        if (bdrv_key_required(bs)) {
 627            autostart = 0;
 628        }
 629
 630        block_acct_init(blk_get_stats(blk), account_invalid, account_failed);
 631
 632        if (!parse_stats_intervals(blk_get_stats(blk), interval_list, errp)) {
 633            blk_unref(blk);
 634            blk = NULL;
 635            goto err_no_bs_opts;
 636        }
 637    }
 638
 639    blk_set_enable_write_cache(blk, !writethrough);
 640    blk_set_on_error(blk, on_read_error, on_write_error);
 641
 642    if (!monitor_add_blk(blk, blk_id, errp)) {
 643        blk_unref(blk);
 644        blk = NULL;
 645        goto err_no_bs_opts;
 646    }
 647
 648err_no_bs_opts:
 649    qemu_opts_del(opts);
 650    QDECREF(interval_dict);
 651    QDECREF(interval_list);
 652    return blk;
 653
 654early_err:
 655    qemu_opts_del(opts);
 656    QDECREF(interval_dict);
 657    QDECREF(interval_list);
 658err_no_opts:
 659    QDECREF(bs_opts);
 660    return NULL;
 661}
 662
 663static QemuOptsList qemu_root_bds_opts;
 664
 665/* Takes the ownership of bs_opts */
 666static BlockDriverState *bds_tree_init(QDict *bs_opts, Error **errp)
 667{
 668    BlockDriverState *bs;
 669    QemuOpts *opts;
 670    Error *local_error = NULL;
 671    BlockdevDetectZeroesOptions detect_zeroes;
 672    int ret;
 673    int bdrv_flags = 0;
 674
 675    opts = qemu_opts_create(&qemu_root_bds_opts, NULL, 1, errp);
 676    if (!opts) {
 677        goto fail;
 678    }
 679
 680    qemu_opts_absorb_qdict(opts, bs_opts, &local_error);
 681    if (local_error) {
 682        error_propagate(errp, local_error);
 683        goto fail;
 684    }
 685
 686    extract_common_blockdev_options(opts, &bdrv_flags, NULL, NULL,
 687                                    &detect_zeroes, &local_error);
 688    if (local_error) {
 689        error_propagate(errp, local_error);
 690        goto fail;
 691    }
 692
 693    /* bdrv_open() defaults to the values in bdrv_flags (for compatibility
 694     * with other callers) rather than what we want as the real defaults.
 695     * Apply the defaults here instead. */
 696    qdict_set_default_str(bs_opts, BDRV_OPT_CACHE_DIRECT, "off");
 697    qdict_set_default_str(bs_opts, BDRV_OPT_CACHE_NO_FLUSH, "off");
 698
 699    if (runstate_check(RUN_STATE_INMIGRATE)) {
 700        bdrv_flags |= BDRV_O_INACTIVE;
 701    }
 702
 703    bs = NULL;
 704    ret = bdrv_open(&bs, NULL, NULL, bs_opts, bdrv_flags, errp);
 705    if (ret < 0) {
 706        goto fail_no_bs_opts;
 707    }
 708
 709    bs->detect_zeroes = detect_zeroes;
 710
 711fail_no_bs_opts:
 712    qemu_opts_del(opts);
 713    return bs;
 714
 715fail:
 716    qemu_opts_del(opts);
 717    QDECREF(bs_opts);
 718    return NULL;
 719}
 720
 721void blockdev_close_all_bdrv_states(void)
 722{
 723    BlockDriverState *bs, *next_bs;
 724
 725    QTAILQ_FOREACH_SAFE(bs, &monitor_bdrv_states, monitor_list, next_bs) {
 726        AioContext *ctx = bdrv_get_aio_context(bs);
 727
 728        aio_context_acquire(ctx);
 729        bdrv_unref(bs);
 730        aio_context_release(ctx);
 731    }
 732}
 733
 734/* Iterates over the list of monitor-owned BlockDriverStates */
 735BlockDriverState *bdrv_next_monitor_owned(BlockDriverState *bs)
 736{
 737    return bs ? QTAILQ_NEXT(bs, monitor_list)
 738              : QTAILQ_FIRST(&monitor_bdrv_states);
 739}
 740
 741static void qemu_opt_rename(QemuOpts *opts, const char *from, const char *to,
 742                            Error **errp)
 743{
 744    const char *value;
 745
 746    value = qemu_opt_get(opts, from);
 747    if (value) {
 748        if (qemu_opt_find(opts, to)) {
 749            error_setg(errp, "'%s' and its alias '%s' can't be used at the "
 750                       "same time", to, from);
 751            return;
 752        }
 753    }
 754
 755    /* rename all items in opts */
 756    while ((value = qemu_opt_get(opts, from))) {
 757        qemu_opt_set(opts, to, value, &error_abort);
 758        qemu_opt_unset(opts, from);
 759    }
 760}
 761
 762QemuOptsList qemu_legacy_drive_opts = {
 763    .name = "drive",
 764    .head = QTAILQ_HEAD_INITIALIZER(qemu_legacy_drive_opts.head),
 765    .desc = {
 766        {
 767            .name = "bus",
 768            .type = QEMU_OPT_NUMBER,
 769            .help = "bus number",
 770        },{
 771            .name = "unit",
 772            .type = QEMU_OPT_NUMBER,
 773            .help = "unit number (i.e. lun for scsi)",
 774        },{
 775            .name = "index",
 776            .type = QEMU_OPT_NUMBER,
 777            .help = "index number",
 778        },{
 779            .name = "media",
 780            .type = QEMU_OPT_STRING,
 781            .help = "media type (disk, cdrom)",
 782        },{
 783            .name = "if",
 784            .type = QEMU_OPT_STRING,
 785            .help = "interface (ide, scsi, sd, mtd, floppy, pflash, virtio)",
 786        },{
 787            .name = "cyls",
 788            .type = QEMU_OPT_NUMBER,
 789            .help = "number of cylinders (ide disk geometry)",
 790        },{
 791            .name = "heads",
 792            .type = QEMU_OPT_NUMBER,
 793            .help = "number of heads (ide disk geometry)",
 794        },{
 795            .name = "secs",
 796            .type = QEMU_OPT_NUMBER,
 797            .help = "number of sectors (ide disk geometry)",
 798        },{
 799            .name = "trans",
 800            .type = QEMU_OPT_STRING,
 801            .help = "chs translation (auto, lba, none)",
 802        },{
 803            .name = "boot",
 804            .type = QEMU_OPT_BOOL,
 805            .help = "(deprecated, ignored)",
 806        },{
 807            .name = "addr",
 808            .type = QEMU_OPT_STRING,
 809            .help = "pci address (virtio only)",
 810        },{
 811            .name = "serial",
 812            .type = QEMU_OPT_STRING,
 813            .help = "disk serial number",
 814        },{
 815            .name = "file",
 816            .type = QEMU_OPT_STRING,
 817            .help = "file name",
 818        },
 819
 820        /* Options that are passed on, but have special semantics with -drive */
 821        {
 822            .name = "read-only",
 823            .type = QEMU_OPT_BOOL,
 824            .help = "open drive file as read-only",
 825        },{
 826            .name = "rerror",
 827            .type = QEMU_OPT_STRING,
 828            .help = "read error action",
 829        },{
 830            .name = "werror",
 831            .type = QEMU_OPT_STRING,
 832            .help = "write error action",
 833        },{
 834            .name = "copy-on-read",
 835            .type = QEMU_OPT_BOOL,
 836            .help = "copy read data from backing file into image file",
 837        },
 838
 839        { /* end of list */ }
 840    },
 841};
 842
 843DriveInfo *drive_new(QemuOpts *all_opts, BlockInterfaceType block_default_type)
 844{
 845    const char *value;
 846    BlockBackend *blk;
 847    DriveInfo *dinfo = NULL;
 848    QDict *bs_opts;
 849    QemuOpts *legacy_opts;
 850    DriveMediaType media = MEDIA_DISK;
 851    BlockInterfaceType type;
 852    int cyls, heads, secs, translation;
 853    int max_devs, bus_id, unit_id, index;
 854    const char *devaddr;
 855    const char *werror, *rerror;
 856    bool read_only = false;
 857    bool copy_on_read;
 858    const char *serial;
 859    const char *filename;
 860    Error *local_err = NULL;
 861    int i;
 862
 863    /* Change legacy command line options into QMP ones */
 864    static const struct {
 865        const char *from;
 866        const char *to;
 867    } opt_renames[] = {
 868        { "iops",           "throttling.iops-total" },
 869        { "iops_rd",        "throttling.iops-read" },
 870        { "iops_wr",        "throttling.iops-write" },
 871
 872        { "bps",            "throttling.bps-total" },
 873        { "bps_rd",         "throttling.bps-read" },
 874        { "bps_wr",         "throttling.bps-write" },
 875
 876        { "iops_max",       "throttling.iops-total-max" },
 877        { "iops_rd_max",    "throttling.iops-read-max" },
 878        { "iops_wr_max",    "throttling.iops-write-max" },
 879
 880        { "bps_max",        "throttling.bps-total-max" },
 881        { "bps_rd_max",     "throttling.bps-read-max" },
 882        { "bps_wr_max",     "throttling.bps-write-max" },
 883
 884        { "iops_size",      "throttling.iops-size" },
 885
 886        { "group",          "throttling.group" },
 887
 888        { "readonly",       "read-only" },
 889    };
 890
 891    for (i = 0; i < ARRAY_SIZE(opt_renames); i++) {
 892        qemu_opt_rename(all_opts, opt_renames[i].from, opt_renames[i].to,
 893                        &local_err);
 894        if (local_err) {
 895            error_report_err(local_err);
 896            return NULL;
 897        }
 898    }
 899
 900    value = qemu_opt_get(all_opts, "cache");
 901    if (value) {
 902        int flags = 0;
 903        bool writethrough;
 904
 905        if (bdrv_parse_cache_mode(value, &flags, &writethrough) != 0) {
 906            error_report("invalid cache option");
 907            return NULL;
 908        }
 909
 910        /* Specific options take precedence */
 911        if (!qemu_opt_get(all_opts, BDRV_OPT_CACHE_WB)) {
 912            qemu_opt_set_bool(all_opts, BDRV_OPT_CACHE_WB,
 913                              !writethrough, &error_abort);
 914        }
 915        if (!qemu_opt_get(all_opts, BDRV_OPT_CACHE_DIRECT)) {
 916            qemu_opt_set_bool(all_opts, BDRV_OPT_CACHE_DIRECT,
 917                              !!(flags & BDRV_O_NOCACHE), &error_abort);
 918        }
 919        if (!qemu_opt_get(all_opts, BDRV_OPT_CACHE_NO_FLUSH)) {
 920            qemu_opt_set_bool(all_opts, BDRV_OPT_CACHE_NO_FLUSH,
 921                              !!(flags & BDRV_O_NO_FLUSH), &error_abort);
 922        }
 923        qemu_opt_unset(all_opts, "cache");
 924    }
 925
 926    /* Get a QDict for processing the options */
 927    bs_opts = qdict_new();
 928    qemu_opts_to_qdict(all_opts, bs_opts);
 929
 930    legacy_opts = qemu_opts_create(&qemu_legacy_drive_opts, NULL, 0,
 931                                   &error_abort);
 932    qemu_opts_absorb_qdict(legacy_opts, bs_opts, &local_err);
 933    if (local_err) {
 934        error_report_err(local_err);
 935        goto fail;
 936    }
 937
 938    /* Deprecated option boot=[on|off] */
 939    if (qemu_opt_get(legacy_opts, "boot") != NULL) {
 940        fprintf(stderr, "qemu-kvm: boot=on|off is deprecated and will be "
 941                "ignored. Future versions will reject this parameter. Please "
 942                "update your scripts.\n");
 943    }
 944
 945    /* Media type */
 946    value = qemu_opt_get(legacy_opts, "media");
 947    if (value) {
 948        if (!strcmp(value, "disk")) {
 949            media = MEDIA_DISK;
 950        } else if (!strcmp(value, "cdrom")) {
 951            media = MEDIA_CDROM;
 952            read_only = true;
 953        } else {
 954            error_report("'%s' invalid media", value);
 955            goto fail;
 956        }
 957    }
 958
 959    /* copy-on-read is disabled with a warning for read-only devices */
 960    read_only |= qemu_opt_get_bool(legacy_opts, "read-only", false);
 961    copy_on_read = qemu_opt_get_bool(legacy_opts, "copy-on-read", false);
 962
 963    if (read_only && copy_on_read) {
 964        error_report("warning: disabling copy-on-read on read-only drive");
 965        copy_on_read = false;
 966    }
 967
 968    qdict_put(bs_opts, "read-only",
 969              qstring_from_str(read_only ? "on" : "off"));
 970    qdict_put(bs_opts, "copy-on-read",
 971              qstring_from_str(copy_on_read ? "on" :"off"));
 972
 973    /* Controller type */
 974    value = qemu_opt_get(legacy_opts, "if");
 975    if (value) {
 976        for (type = 0;
 977             type < IF_COUNT && strcmp(value, if_name[type]);
 978             type++) {
 979        }
 980        if (type == IF_COUNT) {
 981            error_report("unsupported bus type '%s'", value);
 982            goto fail;
 983        }
 984    } else {
 985        type = block_default_type;
 986    }
 987
 988    /* Geometry */
 989    cyls  = qemu_opt_get_number(legacy_opts, "cyls", 0);
 990    heads = qemu_opt_get_number(legacy_opts, "heads", 0);
 991    secs  = qemu_opt_get_number(legacy_opts, "secs", 0);
 992
 993    if (cyls || heads || secs) {
 994        if (cyls < 1) {
 995            error_report("invalid physical cyls number");
 996            goto fail;
 997        }
 998        if (heads < 1) {
 999            error_report("invalid physical heads number");
1000            goto fail;
1001        }
1002        if (secs < 1) {
1003            error_report("invalid physical secs number");
1004            goto fail;
1005        }
1006    }
1007
1008    translation = BIOS_ATA_TRANSLATION_AUTO;
1009    value = qemu_opt_get(legacy_opts, "trans");
1010    if (value != NULL) {
1011        if (!cyls) {
1012            error_report("'%s' trans must be used with cyls, heads and secs",
1013                         value);
1014            goto fail;
1015        }
1016        if (!strcmp(value, "none")) {
1017            translation = BIOS_ATA_TRANSLATION_NONE;
1018        } else if (!strcmp(value, "lba")) {
1019            translation = BIOS_ATA_TRANSLATION_LBA;
1020        } else if (!strcmp(value, "large")) {
1021            translation = BIOS_ATA_TRANSLATION_LARGE;
1022        } else if (!strcmp(value, "rechs")) {
1023            translation = BIOS_ATA_TRANSLATION_RECHS;
1024        } else if (!strcmp(value, "auto")) {
1025            translation = BIOS_ATA_TRANSLATION_AUTO;
1026        } else {
1027            error_report("'%s' invalid translation type", value);
1028            goto fail;
1029        }
1030    }
1031
1032    if (media == MEDIA_CDROM) {
1033        if (cyls || secs || heads) {
1034            error_report("CHS can't be set with media=cdrom");
1035            goto fail;
1036        }
1037    }
1038
1039    /* Device address specified by bus/unit or index.
1040     * If none was specified, try to find the first free one. */
1041    bus_id  = qemu_opt_get_number(legacy_opts, "bus", 0);
1042    unit_id = qemu_opt_get_number(legacy_opts, "unit", -1);
1043    index   = qemu_opt_get_number(legacy_opts, "index", -1);
1044
1045    max_devs = if_max_devs[type];
1046
1047    if (index != -1) {
1048        if (bus_id != 0 || unit_id != -1) {
1049            error_report("index cannot be used with bus and unit");
1050            goto fail;
1051        }
1052        bus_id = drive_index_to_bus_id(type, index);
1053        unit_id = drive_index_to_unit_id(type, index);
1054    }
1055
1056    if (unit_id == -1) {
1057       unit_id = 0;
1058       while (drive_get(type, bus_id, unit_id) != NULL) {
1059           unit_id++;
1060           if (max_devs && unit_id >= max_devs) {
1061               unit_id -= max_devs;
1062               bus_id++;
1063           }
1064       }
1065    }
1066
1067    if (max_devs && unit_id >= max_devs) {
1068        error_report("unit %d too big (max is %d)", unit_id, max_devs - 1);
1069        goto fail;
1070    }
1071
1072    if (drive_get(type, bus_id, unit_id) != NULL) {
1073        error_report("drive with bus=%d, unit=%d (index=%d) exists",
1074                     bus_id, unit_id, index);
1075        goto fail;
1076    }
1077
1078    /* Serial number */
1079    serial = qemu_opt_get(legacy_opts, "serial");
1080
1081    /* no id supplied -> create one */
1082    if (qemu_opts_id(all_opts) == NULL) {
1083        char *new_id;
1084        const char *mediastr = "";
1085        if (type == IF_IDE || type == IF_SCSI) {
1086            mediastr = (media == MEDIA_CDROM) ? "-cd" : "-hd";
1087        }
1088        if (max_devs) {
1089            new_id = g_strdup_printf("%s%i%s%i", if_name[type], bus_id,
1090                                     mediastr, unit_id);
1091        } else {
1092            new_id = g_strdup_printf("%s%s%i", if_name[type],
1093                                     mediastr, unit_id);
1094        }
1095        qdict_put(bs_opts, "id", qstring_from_str(new_id));
1096        g_free(new_id);
1097    }
1098
1099    /* Add virtio block device */
1100    devaddr = qemu_opt_get(legacy_opts, "addr");
1101    if (devaddr && type != IF_VIRTIO) {
1102        error_report("addr is not supported by this bus type");
1103        goto fail;
1104    }
1105
1106    if (type == IF_VIRTIO) {
1107        QemuOpts *devopts;
1108        devopts = qemu_opts_create(qemu_find_opts("device"), NULL, 0,
1109                                   &error_abort);
1110        if (arch_type == QEMU_ARCH_S390X) {
1111            qemu_opt_set(devopts, "driver", "virtio-blk-ccw", &error_abort);
1112        } else {
1113            qemu_opt_set(devopts, "driver", "virtio-blk-pci", &error_abort);
1114        }
1115        qemu_opt_set(devopts, "drive", qdict_get_str(bs_opts, "id"),
1116                     &error_abort);
1117        if (devaddr) {
1118            qemu_opt_set(devopts, "addr", devaddr, &error_abort);
1119        }
1120    }
1121
1122    filename = qemu_opt_get(legacy_opts, "file");
1123
1124    /* Check werror/rerror compatibility with if=... */
1125    werror = qemu_opt_get(legacy_opts, "werror");
1126    if (werror != NULL) {
1127        if (type != IF_IDE && type != IF_SCSI && type != IF_VIRTIO &&
1128            type != IF_NONE) {
1129            error_report("werror is not supported by this bus type");
1130            goto fail;
1131        }
1132        qdict_put(bs_opts, "werror", qstring_from_str(werror));
1133    }
1134
1135    rerror = qemu_opt_get(legacy_opts, "rerror");
1136    if (rerror != NULL) {
1137        if (type != IF_IDE && type != IF_VIRTIO && type != IF_SCSI &&
1138            type != IF_NONE) {
1139            error_report("rerror is not supported by this bus type");
1140            goto fail;
1141        }
1142        qdict_put(bs_opts, "rerror", qstring_from_str(rerror));
1143    }
1144
1145    /* Actual block device init: Functionality shared with blockdev-add */
1146    blk = blockdev_init(filename, bs_opts, &local_err);
1147    bs_opts = NULL;
1148    if (!blk) {
1149        if (local_err) {
1150            error_report_err(local_err);
1151        }
1152        goto fail;
1153    } else {
1154        assert(!local_err);
1155    }
1156
1157    /* Create legacy DriveInfo */
1158    dinfo = g_malloc0(sizeof(*dinfo));
1159    dinfo->opts = all_opts;
1160
1161    dinfo->cyls = cyls;
1162    dinfo->heads = heads;
1163    dinfo->secs = secs;
1164    dinfo->trans = translation;
1165
1166    dinfo->type = type;
1167    dinfo->bus = bus_id;
1168    dinfo->unit = unit_id;
1169    dinfo->devaddr = devaddr;
1170    dinfo->serial = g_strdup(serial);
1171
1172    blk_set_legacy_dinfo(blk, dinfo);
1173
1174    switch(type) {
1175    case IF_IDE:
1176    case IF_SCSI:
1177    case IF_XEN:
1178    case IF_NONE:
1179        dinfo->media_cd = media == MEDIA_CDROM;
1180        break;
1181    default:
1182        break;
1183    }
1184
1185fail:
1186    qemu_opts_del(legacy_opts);
1187    QDECREF(bs_opts);
1188    return dinfo;
1189}
1190
1191void hmp_commit(Monitor *mon, const QDict *qdict)
1192{
1193    const char *device = qdict_get_str(qdict, "device");
1194    BlockBackend *blk;
1195    int ret;
1196
1197    if (!strcmp(device, "all")) {
1198        ret = blk_commit_all();
1199    } else {
1200        BlockDriverState *bs;
1201        AioContext *aio_context;
1202
1203        blk = blk_by_name(device);
1204        if (!blk) {
1205            monitor_printf(mon, "Device '%s' not found\n", device);
1206            return;
1207        }
1208        if (!blk_is_available(blk)) {
1209            monitor_printf(mon, "Device '%s' has no medium\n", device);
1210            return;
1211        }
1212
1213        bs = blk_bs(blk);
1214        aio_context = bdrv_get_aio_context(bs);
1215        aio_context_acquire(aio_context);
1216
1217        ret = bdrv_commit(bs);
1218
1219        aio_context_release(aio_context);
1220    }
1221    if (ret < 0) {
1222        monitor_printf(mon, "'commit' error for '%s': %s\n", device,
1223                       strerror(-ret));
1224    }
1225}
1226
1227static void blockdev_do_action(TransactionAction *action, Error **errp)
1228{
1229    TransactionActionList list;
1230
1231    list.value = action;
1232    list.next = NULL;
1233    qmp_transaction(&list, false, NULL, errp);
1234}
1235
1236void qmp_blockdev_snapshot_sync(bool has_device, const char *device,
1237                                bool has_node_name, const char *node_name,
1238                                const char *snapshot_file,
1239                                bool has_snapshot_node_name,
1240                                const char *snapshot_node_name,
1241                                bool has_format, const char *format,
1242                                bool has_mode, NewImageMode mode, Error **errp)
1243{
1244    BlockdevSnapshotSync snapshot = {
1245        .has_device = has_device,
1246        .device = (char *) device,
1247        .has_node_name = has_node_name,
1248        .node_name = (char *) node_name,
1249        .snapshot_file = (char *) snapshot_file,
1250        .has_snapshot_node_name = has_snapshot_node_name,
1251        .snapshot_node_name = (char *) snapshot_node_name,
1252        .has_format = has_format,
1253        .format = (char *) format,
1254        .has_mode = has_mode,
1255        .mode = mode,
1256    };
1257    TransactionAction action = {
1258        .type = TRANSACTION_ACTION_KIND_BLOCKDEV_SNAPSHOT_SYNC,
1259        .u.blockdev_snapshot_sync.data = &snapshot,
1260    };
1261    blockdev_do_action(&action, errp);
1262}
1263
1264void qmp_blockdev_snapshot(const char *node, const char *overlay,
1265                           Error **errp)
1266{
1267    BlockdevSnapshot snapshot_data = {
1268        .node = (char *) node,
1269        .overlay = (char *) overlay
1270    };
1271    TransactionAction action = {
1272        .type = TRANSACTION_ACTION_KIND_BLOCKDEV_SNAPSHOT,
1273        .u.blockdev_snapshot.data = &snapshot_data,
1274    };
1275    blockdev_do_action(&action, errp);
1276}
1277
1278void qmp_blockdev_snapshot_internal_sync(const char *device,
1279                                         const char *name,
1280                                         Error **errp)
1281{
1282    BlockdevSnapshotInternal snapshot = {
1283        .device = (char *) device,
1284        .name = (char *) name
1285    };
1286    TransactionAction action = {
1287        .type = TRANSACTION_ACTION_KIND_BLOCKDEV_SNAPSHOT_INTERNAL_SYNC,
1288        .u.blockdev_snapshot_internal_sync.data = &snapshot,
1289    };
1290    blockdev_do_action(&action, errp);
1291}
1292
1293SnapshotInfo *qmp_blockdev_snapshot_delete_internal_sync(const char *device,
1294                                                         bool has_id,
1295                                                         const char *id,
1296                                                         bool has_name,
1297                                                         const char *name,
1298                                                         Error **errp)
1299{
1300    BlockDriverState *bs;
1301    BlockBackend *blk;
1302    AioContext *aio_context;
1303    QEMUSnapshotInfo sn;
1304    Error *local_err = NULL;
1305    SnapshotInfo *info = NULL;
1306    int ret;
1307
1308    blk = blk_by_name(device);
1309    if (!blk) {
1310        error_set(errp, ERROR_CLASS_DEVICE_NOT_FOUND,
1311                  "Device '%s' not found", device);
1312        return NULL;
1313    }
1314
1315    aio_context = blk_get_aio_context(blk);
1316    aio_context_acquire(aio_context);
1317
1318    if (!has_id) {
1319        id = NULL;
1320    }
1321
1322    if (!has_name) {
1323        name = NULL;
1324    }
1325
1326    if (!id && !name) {
1327        error_setg(errp, "Name or id must be provided");
1328        goto out_aio_context;
1329    }
1330
1331    if (!blk_is_available(blk)) {
1332        error_setg(errp, "Device '%s' has no medium", device);
1333        goto out_aio_context;
1334    }
1335    bs = blk_bs(blk);
1336
1337    if (bdrv_op_is_blocked(bs, BLOCK_OP_TYPE_INTERNAL_SNAPSHOT_DELETE, errp)) {
1338        goto out_aio_context;
1339    }
1340
1341    ret = bdrv_snapshot_find_by_id_and_name(bs, id, name, &sn, &local_err);
1342    if (local_err) {
1343        error_propagate(errp, local_err);
1344        goto out_aio_context;
1345    }
1346    if (!ret) {
1347        error_setg(errp,
1348                   "Snapshot with id '%s' and name '%s' does not exist on "
1349                   "device '%s'",
1350                   STR_OR_NULL(id), STR_OR_NULL(name), device);
1351        goto out_aio_context;
1352    }
1353
1354    bdrv_snapshot_delete(bs, id, name, &local_err);
1355    if (local_err) {
1356        error_propagate(errp, local_err);
1357        goto out_aio_context;
1358    }
1359
1360    aio_context_release(aio_context);
1361
1362    info = g_new0(SnapshotInfo, 1);
1363    info->id = g_strdup(sn.id_str);
1364    info->name = g_strdup(sn.name);
1365    info->date_nsec = sn.date_nsec;
1366    info->date_sec = sn.date_sec;
1367    info->vm_state_size = sn.vm_state_size;
1368    info->vm_clock_nsec = sn.vm_clock_nsec % 1000000000;
1369    info->vm_clock_sec = sn.vm_clock_nsec / 1000000000;
1370
1371    return info;
1372
1373out_aio_context:
1374    aio_context_release(aio_context);
1375    return NULL;
1376}
1377
1378/**
1379 * block_dirty_bitmap_lookup:
1380 * Return a dirty bitmap (if present), after validating
1381 * the node reference and bitmap names.
1382 *
1383 * @node: The name of the BDS node to search for bitmaps
1384 * @name: The name of the bitmap to search for
1385 * @pbs: Output pointer for BDS lookup, if desired. Can be NULL.
1386 * @paio: Output pointer for aio_context acquisition, if desired. Can be NULL.
1387 * @errp: Output pointer for error information. Can be NULL.
1388 *
1389 * @return: A bitmap object on success, or NULL on failure.
1390 */
1391static BdrvDirtyBitmap *block_dirty_bitmap_lookup(const char *node,
1392                                                  const char *name,
1393                                                  BlockDriverState **pbs,
1394                                                  AioContext **paio,
1395                                                  Error **errp)
1396{
1397    BlockDriverState *bs;
1398    BdrvDirtyBitmap *bitmap;
1399    AioContext *aio_context;
1400
1401    if (!node) {
1402        error_setg(errp, "Node cannot be NULL");
1403        return NULL;
1404    }
1405    if (!name) {
1406        error_setg(errp, "Bitmap name cannot be NULL");
1407        return NULL;
1408    }
1409    bs = bdrv_lookup_bs(node, node, NULL);
1410    if (!bs) {
1411        error_setg(errp, "Node '%s' not found", node);
1412        return NULL;
1413    }
1414
1415    aio_context = bdrv_get_aio_context(bs);
1416    aio_context_acquire(aio_context);
1417
1418    bitmap = bdrv_find_dirty_bitmap(bs, name);
1419    if (!bitmap) {
1420        error_setg(errp, "Dirty bitmap '%s' not found", name);
1421        goto fail;
1422    }
1423
1424    if (pbs) {
1425        *pbs = bs;
1426    }
1427    if (paio) {
1428        *paio = aio_context;
1429    } else {
1430        aio_context_release(aio_context);
1431    }
1432
1433    return bitmap;
1434
1435 fail:
1436    aio_context_release(aio_context);
1437    return NULL;
1438}
1439
1440/* New and old BlockDriverState structs for atomic group operations */
1441
1442typedef struct BlkActionState BlkActionState;
1443
1444/**
1445 * BlkActionOps:
1446 * Table of operations that define an Action.
1447 *
1448 * @instance_size: Size of state struct, in bytes.
1449 * @prepare: Prepare the work, must NOT be NULL.
1450 * @commit: Commit the changes, can be NULL.
1451 * @abort: Abort the changes on fail, can be NULL.
1452 * @clean: Clean up resources after all transaction actions have called
1453 *         commit() or abort(). Can be NULL.
1454 *
1455 * Only prepare() may fail. In a single transaction, only one of commit() or
1456 * abort() will be called. clean() will always be called if it is present.
1457 */
1458typedef struct BlkActionOps {
1459    size_t instance_size;
1460    void (*prepare)(BlkActionState *common, Error **errp);
1461    void (*commit)(BlkActionState *common);
1462    void (*abort)(BlkActionState *common);
1463    void (*clean)(BlkActionState *common);
1464} BlkActionOps;
1465
1466/**
1467 * BlkActionState:
1468 * Describes one Action's state within a Transaction.
1469 *
1470 * @action: QAPI-defined enum identifying which Action to perform.
1471 * @ops: Table of ActionOps this Action can perform.
1472 * @block_job_txn: Transaction which this action belongs to.
1473 * @entry: List membership for all Actions in this Transaction.
1474 *
1475 * This structure must be arranged as first member in a subclassed type,
1476 * assuming that the compiler will also arrange it to the same offsets as the
1477 * base class.
1478 */
1479struct BlkActionState {
1480    TransactionAction *action;
1481    const BlkActionOps *ops;
1482    BlockJobTxn *block_job_txn;
1483    TransactionProperties *txn_props;
1484    QSIMPLEQ_ENTRY(BlkActionState) entry;
1485};
1486
1487/* internal snapshot private data */
1488typedef struct InternalSnapshotState {
1489    BlkActionState common;
1490    BlockDriverState *bs;
1491    AioContext *aio_context;
1492    QEMUSnapshotInfo sn;
1493    bool created;
1494} InternalSnapshotState;
1495
1496
1497static int action_check_completion_mode(BlkActionState *s, Error **errp)
1498{
1499    if (s->txn_props->completion_mode != ACTION_COMPLETION_MODE_INDIVIDUAL) {
1500        error_setg(errp,
1501                   "Action '%s' does not support Transaction property "
1502                   "completion-mode = %s",
1503                   TransactionActionKind_lookup[s->action->type],
1504                   ActionCompletionMode_lookup[s->txn_props->completion_mode]);
1505        return -1;
1506    }
1507    return 0;
1508}
1509
1510static void internal_snapshot_prepare(BlkActionState *common,
1511                                      Error **errp)
1512{
1513    Error *local_err = NULL;
1514    const char *device;
1515    const char *name;
1516    BlockBackend *blk;
1517    BlockDriverState *bs;
1518    QEMUSnapshotInfo old_sn, *sn;
1519    bool ret;
1520    qemu_timeval tv;
1521    BlockdevSnapshotInternal *internal;
1522    InternalSnapshotState *state;
1523    int ret1;
1524
1525    g_assert(common->action->type ==
1526             TRANSACTION_ACTION_KIND_BLOCKDEV_SNAPSHOT_INTERNAL_SYNC);
1527    internal = common->action->u.blockdev_snapshot_internal_sync.data;
1528    state = DO_UPCAST(InternalSnapshotState, common, common);
1529
1530    /* 1. parse input */
1531    device = internal->device;
1532    name = internal->name;
1533
1534    /* 2. check for validation */
1535    if (action_check_completion_mode(common, errp) < 0) {
1536        return;
1537    }
1538
1539    blk = blk_by_name(device);
1540    if (!blk) {
1541        error_set(errp, ERROR_CLASS_DEVICE_NOT_FOUND,
1542                  "Device '%s' not found", device);
1543        return;
1544    }
1545
1546    /* AioContext is released in .clean() */
1547    state->aio_context = blk_get_aio_context(blk);
1548    aio_context_acquire(state->aio_context);
1549
1550    if (!blk_is_available(blk)) {
1551        error_setg(errp, QERR_DEVICE_HAS_NO_MEDIUM, device);
1552        return;
1553    }
1554    bs = blk_bs(blk);
1555
1556    state->bs = bs;
1557    bdrv_drained_begin(bs);
1558
1559    if (bdrv_op_is_blocked(bs, BLOCK_OP_TYPE_INTERNAL_SNAPSHOT, errp)) {
1560        return;
1561    }
1562
1563    if (bdrv_is_read_only(bs)) {
1564        error_setg(errp, "Device '%s' is read only", device);
1565        return;
1566    }
1567
1568    if (!bdrv_can_snapshot(bs)) {
1569        error_setg(errp, "Block format '%s' used by device '%s' "
1570                   "does not support internal snapshots",
1571                   bs->drv->format_name, device);
1572        return;
1573    }
1574
1575    if (!strlen(name)) {
1576        error_setg(errp, "Name is empty");
1577        return;
1578    }
1579
1580    /* check whether a snapshot with name exist */
1581    ret = bdrv_snapshot_find_by_id_and_name(bs, NULL, name, &old_sn,
1582                                            &local_err);
1583    if (local_err) {
1584        error_propagate(errp, local_err);
1585        return;
1586    } else if (ret) {
1587        error_setg(errp,
1588                   "Snapshot with name '%s' already exists on device '%s'",
1589                   name, device);
1590        return;
1591    }
1592
1593    /* 3. take the snapshot */
1594    sn = &state->sn;
1595    pstrcpy(sn->name, sizeof(sn->name), name);
1596    qemu_gettimeofday(&tv);
1597    sn->date_sec = tv.tv_sec;
1598    sn->date_nsec = tv.tv_usec * 1000;
1599    sn->vm_clock_nsec = qemu_clock_get_ns(QEMU_CLOCK_VIRTUAL);
1600
1601    ret1 = bdrv_snapshot_create(bs, sn);
1602    if (ret1 < 0) {
1603        error_setg_errno(errp, -ret1,
1604                         "Failed to create snapshot '%s' on device '%s'",
1605                         name, device);
1606        return;
1607    }
1608
1609    /* 4. succeed, mark a snapshot is created */
1610    state->created = true;
1611}
1612
1613static void internal_snapshot_abort(BlkActionState *common)
1614{
1615    InternalSnapshotState *state =
1616                             DO_UPCAST(InternalSnapshotState, common, common);
1617    BlockDriverState *bs = state->bs;
1618    QEMUSnapshotInfo *sn = &state->sn;
1619    Error *local_error = NULL;
1620
1621    if (!state->created) {
1622        return;
1623    }
1624
1625    if (bdrv_snapshot_delete(bs, sn->id_str, sn->name, &local_error) < 0) {
1626        error_reportf_err(local_error,
1627                          "Failed to delete snapshot with id '%s' and "
1628                          "name '%s' on device '%s' in abort: ",
1629                          sn->id_str, sn->name,
1630                          bdrv_get_device_name(bs));
1631    }
1632}
1633
1634static void internal_snapshot_clean(BlkActionState *common)
1635{
1636    InternalSnapshotState *state = DO_UPCAST(InternalSnapshotState,
1637                                             common, common);
1638
1639    if (state->aio_context) {
1640        if (state->bs) {
1641            bdrv_drained_end(state->bs);
1642        }
1643        aio_context_release(state->aio_context);
1644    }
1645}
1646
1647/* external snapshot private data */
1648typedef struct ExternalSnapshotState {
1649    BlkActionState common;
1650    BlockDriverState *old_bs;
1651    BlockDriverState *new_bs;
1652    AioContext *aio_context;
1653} ExternalSnapshotState;
1654
1655static void external_snapshot_prepare(BlkActionState *common,
1656                                      Error **errp)
1657{
1658    int flags = 0, ret;
1659    QDict *options = NULL;
1660    Error *local_err = NULL;
1661    /* Device and node name of the image to generate the snapshot from */
1662    const char *device;
1663    const char *node_name;
1664    /* Reference to the new image (for 'blockdev-snapshot') */
1665    const char *snapshot_ref;
1666    /* File name of the new image (for 'blockdev-snapshot-sync') */
1667    const char *new_image_file;
1668    ExternalSnapshotState *state =
1669                             DO_UPCAST(ExternalSnapshotState, common, common);
1670    TransactionAction *action = common->action;
1671
1672    /* 'blockdev-snapshot' and 'blockdev-snapshot-sync' have similar
1673     * purpose but a different set of parameters */
1674    switch (action->type) {
1675    case TRANSACTION_ACTION_KIND_BLOCKDEV_SNAPSHOT:
1676        {
1677            BlockdevSnapshot *s = action->u.blockdev_snapshot.data;
1678            device = s->node;
1679            node_name = s->node;
1680            new_image_file = NULL;
1681            snapshot_ref = s->overlay;
1682        }
1683        break;
1684    case TRANSACTION_ACTION_KIND_BLOCKDEV_SNAPSHOT_SYNC:
1685        {
1686            BlockdevSnapshotSync *s = action->u.blockdev_snapshot_sync.data;
1687            device = s->has_device ? s->device : NULL;
1688            node_name = s->has_node_name ? s->node_name : NULL;
1689            new_image_file = s->snapshot_file;
1690            snapshot_ref = NULL;
1691        }
1692        break;
1693    default:
1694        g_assert_not_reached();
1695    }
1696
1697    /* start processing */
1698    if (action_check_completion_mode(common, errp) < 0) {
1699        return;
1700    }
1701
1702    state->old_bs = bdrv_lookup_bs(device, node_name, errp);
1703    if (!state->old_bs) {
1704        return;
1705    }
1706
1707    /* Acquire AioContext now so any threads operating on old_bs stop */
1708    state->aio_context = bdrv_get_aio_context(state->old_bs);
1709    aio_context_acquire(state->aio_context);
1710    bdrv_drained_begin(state->old_bs);
1711
1712    if (!bdrv_is_inserted(state->old_bs)) {
1713        error_setg(errp, QERR_DEVICE_HAS_NO_MEDIUM, device);
1714        return;
1715    }
1716
1717    if (bdrv_op_is_blocked(state->old_bs,
1718                           BLOCK_OP_TYPE_EXTERNAL_SNAPSHOT, errp)) {
1719        return;
1720    }
1721
1722    if (!bdrv_is_read_only(state->old_bs)) {
1723        if (bdrv_flush(state->old_bs)) {
1724            error_setg(errp, QERR_IO_ERROR);
1725            return;
1726        }
1727    }
1728
1729    if (!bdrv_is_first_non_filter(state->old_bs)) {
1730        error_setg(errp, QERR_FEATURE_DISABLED, "snapshot");
1731        return;
1732    }
1733
1734    if (action->type == TRANSACTION_ACTION_KIND_BLOCKDEV_SNAPSHOT_SYNC) {
1735        BlockdevSnapshotSync *s = action->u.blockdev_snapshot_sync.data;
1736        const char *format = s->has_format ? s->format : "qcow2";
1737        enum NewImageMode mode;
1738        const char *snapshot_node_name =
1739            s->has_snapshot_node_name ? s->snapshot_node_name : NULL;
1740
1741        if (node_name && !snapshot_node_name) {
1742            error_setg(errp, "New snapshot node name missing");
1743            return;
1744        }
1745
1746        if (snapshot_node_name &&
1747            bdrv_lookup_bs(snapshot_node_name, snapshot_node_name, NULL)) {
1748            error_setg(errp, "New snapshot node name already in use");
1749            return;
1750        }
1751
1752        flags = state->old_bs->open_flags;
1753        flags &= ~(BDRV_O_SNAPSHOT | BDRV_O_NO_BACKING | BDRV_O_COPY_ON_READ);
1754
1755        /* create new image w/backing file */
1756        mode = s->has_mode ? s->mode : NEW_IMAGE_MODE_ABSOLUTE_PATHS;
1757        if (mode != NEW_IMAGE_MODE_EXISTING) {
1758            int64_t size = bdrv_getlength(state->old_bs);
1759            if (size < 0) {
1760                error_setg_errno(errp, -size, "bdrv_getlength failed");
1761                return;
1762            }
1763            bdrv_img_create(new_image_file, format,
1764                            state->old_bs->filename,
1765                            state->old_bs->drv->format_name,
1766                            NULL, size, flags, &local_err, false);
1767            if (local_err) {
1768                error_propagate(errp, local_err);
1769                return;
1770            }
1771        }
1772
1773        options = qdict_new();
1774        if (s->has_snapshot_node_name) {
1775            qdict_put(options, "node-name",
1776                      qstring_from_str(snapshot_node_name));
1777        }
1778        qdict_put(options, "driver", qstring_from_str(format));
1779
1780        flags |= BDRV_O_NO_BACKING;
1781    }
1782
1783    assert(state->new_bs == NULL);
1784    ret = bdrv_open(&state->new_bs, new_image_file, snapshot_ref, options,
1785                    flags, errp);
1786    /* We will manually add the backing_hd field to the bs later */
1787    if (ret != 0) {
1788        return;
1789    }
1790
1791    if (state->new_bs->blk != NULL) {
1792        error_setg(errp, "The snapshot is already in use by %s",
1793                   blk_name(state->new_bs->blk));
1794        return;
1795    }
1796
1797    if (bdrv_op_is_blocked(state->new_bs, BLOCK_OP_TYPE_EXTERNAL_SNAPSHOT,
1798                           errp)) {
1799        return;
1800    }
1801
1802    if (state->new_bs->backing != NULL) {
1803        error_setg(errp, "The snapshot already has a backing image");
1804        return;
1805    }
1806
1807    if (!state->new_bs->drv->supports_backing) {
1808        error_setg(errp, "The snapshot does not support backing images");
1809    }
1810}
1811
1812static void external_snapshot_commit(BlkActionState *common)
1813{
1814    ExternalSnapshotState *state =
1815                             DO_UPCAST(ExternalSnapshotState, common, common);
1816
1817    bdrv_set_aio_context(state->new_bs, state->aio_context);
1818
1819    /* This removes our old bs and adds the new bs */
1820    bdrv_append(state->new_bs, state->old_bs);
1821    /* We don't need (or want) to use the transactional
1822     * bdrv_reopen_multiple() across all the entries at once, because we
1823     * don't want to abort all of them if one of them fails the reopen */
1824    if (!state->old_bs->copy_on_read) {
1825        bdrv_reopen(state->old_bs, state->old_bs->open_flags & ~BDRV_O_RDWR,
1826                    NULL);
1827    }
1828}
1829
1830static void external_snapshot_abort(BlkActionState *common)
1831{
1832    ExternalSnapshotState *state =
1833                             DO_UPCAST(ExternalSnapshotState, common, common);
1834    if (state->new_bs) {
1835        bdrv_unref(state->new_bs);
1836    }
1837}
1838
1839static void external_snapshot_clean(BlkActionState *common)
1840{
1841    ExternalSnapshotState *state =
1842                             DO_UPCAST(ExternalSnapshotState, common, common);
1843    if (state->aio_context) {
1844        bdrv_drained_end(state->old_bs);
1845        aio_context_release(state->aio_context);
1846    }
1847}
1848
1849typedef struct DriveBackupState {
1850    BlkActionState common;
1851    BlockDriverState *bs;
1852    AioContext *aio_context;
1853    BlockJob *job;
1854} DriveBackupState;
1855
1856static void do_drive_backup(const char *device, const char *target,
1857                            bool has_format, const char *format,
1858                            enum MirrorSyncMode sync,
1859                            bool has_mode, enum NewImageMode mode,
1860                            bool has_speed, int64_t speed,
1861                            bool has_bitmap, const char *bitmap,
1862                            bool has_on_source_error,
1863                            BlockdevOnError on_source_error,
1864                            bool has_on_target_error,
1865                            BlockdevOnError on_target_error,
1866                            BlockJobTxn *txn, Error **errp);
1867
1868static void drive_backup_prepare(BlkActionState *common, Error **errp)
1869{
1870    DriveBackupState *state = DO_UPCAST(DriveBackupState, common, common);
1871    BlockBackend *blk;
1872    DriveBackup *backup;
1873    Error *local_err = NULL;
1874
1875    assert(common->action->type == TRANSACTION_ACTION_KIND_DRIVE_BACKUP);
1876    backup = common->action->u.drive_backup.data;
1877
1878    blk = blk_by_name(backup->device);
1879    if (!blk) {
1880        error_set(errp, ERROR_CLASS_DEVICE_NOT_FOUND,
1881                  "Device '%s' not found", backup->device);
1882        return;
1883    }
1884
1885    if (!blk_is_available(blk)) {
1886        error_setg(errp, QERR_DEVICE_HAS_NO_MEDIUM, backup->device);
1887        return;
1888    }
1889
1890    /* AioContext is released in .clean() */
1891    state->aio_context = blk_get_aio_context(blk);
1892    aio_context_acquire(state->aio_context);
1893    bdrv_drained_begin(blk_bs(blk));
1894    state->bs = blk_bs(blk);
1895
1896    do_drive_backup(backup->device, backup->target,
1897                    backup->has_format, backup->format,
1898                    backup->sync,
1899                    backup->has_mode, backup->mode,
1900                    backup->has_speed, backup->speed,
1901                    backup->has_bitmap, backup->bitmap,
1902                    backup->has_on_source_error, backup->on_source_error,
1903                    backup->has_on_target_error, backup->on_target_error,
1904                    common->block_job_txn, &local_err);
1905    if (local_err) {
1906        error_propagate(errp, local_err);
1907        return;
1908    }
1909
1910    state->job = state->bs->job;
1911}
1912
1913static void drive_backup_abort(BlkActionState *common)
1914{
1915    DriveBackupState *state = DO_UPCAST(DriveBackupState, common, common);
1916    BlockDriverState *bs = state->bs;
1917
1918    /* Only cancel if it's the job we started */
1919    if (bs && bs->job && bs->job == state->job) {
1920        block_job_cancel_sync(bs->job);
1921    }
1922}
1923
1924static void drive_backup_clean(BlkActionState *common)
1925{
1926    DriveBackupState *state = DO_UPCAST(DriveBackupState, common, common);
1927
1928    if (state->aio_context) {
1929        bdrv_drained_end(state->bs);
1930        aio_context_release(state->aio_context);
1931    }
1932}
1933
1934typedef struct BlockdevBackupState {
1935    BlkActionState common;
1936    BlockDriverState *bs;
1937    BlockJob *job;
1938    AioContext *aio_context;
1939} BlockdevBackupState;
1940
1941static void do_blockdev_backup(const char *device, const char *target,
1942                               enum MirrorSyncMode sync,
1943                               bool has_speed, int64_t speed,
1944                               bool has_on_source_error,
1945                               BlockdevOnError on_source_error,
1946                               bool has_on_target_error,
1947                               BlockdevOnError on_target_error,
1948                               BlockJobTxn *txn, Error **errp);
1949
1950static void blockdev_backup_prepare(BlkActionState *common, Error **errp)
1951{
1952    BlockdevBackupState *state = DO_UPCAST(BlockdevBackupState, common, common);
1953    BlockdevBackup *backup;
1954    BlockBackend *blk, *target;
1955    Error *local_err = NULL;
1956
1957    assert(common->action->type == TRANSACTION_ACTION_KIND_BLOCKDEV_BACKUP);
1958    backup = common->action->u.blockdev_backup.data;
1959
1960    blk = blk_by_name(backup->device);
1961    if (!blk) {
1962        error_setg(errp, "Device '%s' not found", backup->device);
1963        return;
1964    }
1965
1966    if (!blk_is_available(blk)) {
1967        error_setg(errp, QERR_DEVICE_HAS_NO_MEDIUM, backup->device);
1968        return;
1969    }
1970
1971    target = blk_by_name(backup->target);
1972    if (!target) {
1973        error_setg(errp, "Device '%s' not found", backup->target);
1974        return;
1975    }
1976
1977    /* AioContext is released in .clean() */
1978    state->aio_context = blk_get_aio_context(blk);
1979    if (state->aio_context != blk_get_aio_context(target)) {
1980        state->aio_context = NULL;
1981        error_setg(errp, "Backup between two IO threads is not implemented");
1982        return;
1983    }
1984    aio_context_acquire(state->aio_context);
1985    state->bs = blk_bs(blk);
1986    bdrv_drained_begin(state->bs);
1987
1988    do_blockdev_backup(backup->device, backup->target,
1989                       backup->sync,
1990                       backup->has_speed, backup->speed,
1991                       backup->has_on_source_error, backup->on_source_error,
1992                       backup->has_on_target_error, backup->on_target_error,
1993                       common->block_job_txn, &local_err);
1994    if (local_err) {
1995        error_propagate(errp, local_err);
1996        return;
1997    }
1998
1999    state->job = state->bs->job;
2000}
2001
2002static void blockdev_backup_abort(BlkActionState *common)
2003{
2004    BlockdevBackupState *state = DO_UPCAST(BlockdevBackupState, common, common);
2005    BlockDriverState *bs = state->bs;
2006
2007    /* Only cancel if it's the job we started */
2008    if (bs && bs->job && bs->job == state->job) {
2009        block_job_cancel_sync(bs->job);
2010    }
2011}
2012
2013static void blockdev_backup_clean(BlkActionState *common)
2014{
2015    BlockdevBackupState *state = DO_UPCAST(BlockdevBackupState, common, common);
2016
2017    if (state->aio_context) {
2018        bdrv_drained_end(state->bs);
2019        aio_context_release(state->aio_context);
2020    }
2021}
2022
2023typedef struct BlockDirtyBitmapState {
2024    BlkActionState common;
2025    BdrvDirtyBitmap *bitmap;
2026    BlockDriverState *bs;
2027    AioContext *aio_context;
2028    HBitmap *backup;
2029    bool prepared;
2030} BlockDirtyBitmapState;
2031
2032static void block_dirty_bitmap_add_prepare(BlkActionState *common,
2033                                           Error **errp)
2034{
2035    Error *local_err = NULL;
2036    BlockDirtyBitmapAdd *action;
2037    BlockDirtyBitmapState *state = DO_UPCAST(BlockDirtyBitmapState,
2038                                             common, common);
2039
2040    if (action_check_completion_mode(common, errp) < 0) {
2041        return;
2042    }
2043
2044    action = common->action->u.block_dirty_bitmap_add.data;
2045    /* AIO context taken and released within qmp_block_dirty_bitmap_add */
2046    qmp_block_dirty_bitmap_add(action->node, action->name,
2047                               action->has_granularity, action->granularity,
2048                               &local_err);
2049
2050    if (!local_err) {
2051        state->prepared = true;
2052    } else {
2053        error_propagate(errp, local_err);
2054    }
2055}
2056
2057static void block_dirty_bitmap_add_abort(BlkActionState *common)
2058{
2059    BlockDirtyBitmapAdd *action;
2060    BlockDirtyBitmapState *state = DO_UPCAST(BlockDirtyBitmapState,
2061                                             common, common);
2062
2063    action = common->action->u.block_dirty_bitmap_add.data;
2064    /* Should not be able to fail: IF the bitmap was added via .prepare(),
2065     * then the node reference and bitmap name must have been valid.
2066     */
2067    if (state->prepared) {
2068        qmp_block_dirty_bitmap_remove(action->node, action->name, &error_abort);
2069    }
2070}
2071
2072static void block_dirty_bitmap_clear_prepare(BlkActionState *common,
2073                                             Error **errp)
2074{
2075    BlockDirtyBitmapState *state = DO_UPCAST(BlockDirtyBitmapState,
2076                                             common, common);
2077    BlockDirtyBitmap *action;
2078
2079    if (action_check_completion_mode(common, errp) < 0) {
2080        return;
2081    }
2082
2083    action = common->action->u.block_dirty_bitmap_clear.data;
2084    state->bitmap = block_dirty_bitmap_lookup(action->node,
2085                                              action->name,
2086                                              &state->bs,
2087                                              &state->aio_context,
2088                                              errp);
2089    if (!state->bitmap) {
2090        return;
2091    }
2092
2093    if (bdrv_dirty_bitmap_frozen(state->bitmap)) {
2094        error_setg(errp, "Cannot modify a frozen bitmap");
2095        return;
2096    } else if (!bdrv_dirty_bitmap_enabled(state->bitmap)) {
2097        error_setg(errp, "Cannot clear a disabled bitmap");
2098        return;
2099    }
2100
2101    bdrv_clear_dirty_bitmap(state->bitmap, &state->backup);
2102    /* AioContext is released in .clean() */
2103}
2104
2105static void block_dirty_bitmap_clear_abort(BlkActionState *common)
2106{
2107    BlockDirtyBitmapState *state = DO_UPCAST(BlockDirtyBitmapState,
2108                                             common, common);
2109
2110    bdrv_undo_clear_dirty_bitmap(state->bitmap, state->backup);
2111}
2112
2113static void block_dirty_bitmap_clear_commit(BlkActionState *common)
2114{
2115    BlockDirtyBitmapState *state = DO_UPCAST(BlockDirtyBitmapState,
2116                                             common, common);
2117
2118    hbitmap_free(state->backup);
2119}
2120
2121static void block_dirty_bitmap_clear_clean(BlkActionState *common)
2122{
2123    BlockDirtyBitmapState *state = DO_UPCAST(BlockDirtyBitmapState,
2124                                             common, common);
2125
2126    if (state->aio_context) {
2127        aio_context_release(state->aio_context);
2128    }
2129}
2130
2131static void abort_prepare(BlkActionState *common, Error **errp)
2132{
2133    error_setg(errp, "Transaction aborted using Abort action");
2134}
2135
2136static void abort_commit(BlkActionState *common)
2137{
2138    g_assert_not_reached(); /* this action never succeeds */
2139}
2140
2141static const BlkActionOps actions[] = {
2142    [TRANSACTION_ACTION_KIND_BLOCKDEV_SNAPSHOT] = {
2143        .instance_size = sizeof(ExternalSnapshotState),
2144        .prepare  = external_snapshot_prepare,
2145        .commit   = external_snapshot_commit,
2146        .abort = external_snapshot_abort,
2147        .clean = external_snapshot_clean,
2148    },
2149    [TRANSACTION_ACTION_KIND_BLOCKDEV_SNAPSHOT_SYNC] = {
2150        .instance_size = sizeof(ExternalSnapshotState),
2151        .prepare  = external_snapshot_prepare,
2152        .commit   = external_snapshot_commit,
2153        .abort = external_snapshot_abort,
2154        .clean = external_snapshot_clean,
2155    },
2156    [TRANSACTION_ACTION_KIND_DRIVE_BACKUP] = {
2157        .instance_size = sizeof(DriveBackupState),
2158        .prepare = drive_backup_prepare,
2159        .abort = drive_backup_abort,
2160        .clean = drive_backup_clean,
2161    },
2162    [TRANSACTION_ACTION_KIND_BLOCKDEV_BACKUP] = {
2163        .instance_size = sizeof(BlockdevBackupState),
2164        .prepare = blockdev_backup_prepare,
2165        .abort = blockdev_backup_abort,
2166        .clean = blockdev_backup_clean,
2167    },
2168    [TRANSACTION_ACTION_KIND_ABORT] = {
2169        .instance_size = sizeof(BlkActionState),
2170        .prepare = abort_prepare,
2171        .commit = abort_commit,
2172    },
2173    [TRANSACTION_ACTION_KIND_BLOCKDEV_SNAPSHOT_INTERNAL_SYNC] = {
2174        .instance_size = sizeof(InternalSnapshotState),
2175        .prepare  = internal_snapshot_prepare,
2176        .abort = internal_snapshot_abort,
2177        .clean = internal_snapshot_clean,
2178    },
2179    [TRANSACTION_ACTION_KIND_BLOCK_DIRTY_BITMAP_ADD] = {
2180        .instance_size = sizeof(BlockDirtyBitmapState),
2181        .prepare = block_dirty_bitmap_add_prepare,
2182        .abort = block_dirty_bitmap_add_abort,
2183    },
2184    [TRANSACTION_ACTION_KIND_BLOCK_DIRTY_BITMAP_CLEAR] = {
2185        .instance_size = sizeof(BlockDirtyBitmapState),
2186        .prepare = block_dirty_bitmap_clear_prepare,
2187        .commit = block_dirty_bitmap_clear_commit,
2188        .abort = block_dirty_bitmap_clear_abort,
2189        .clean = block_dirty_bitmap_clear_clean,
2190    }
2191};
2192
2193/**
2194 * Allocate a TransactionProperties structure if necessary, and fill
2195 * that structure with desired defaults if they are unset.
2196 */
2197static TransactionProperties *get_transaction_properties(
2198    TransactionProperties *props)
2199{
2200    if (!props) {
2201        props = g_new0(TransactionProperties, 1);
2202    }
2203
2204    if (!props->has_completion_mode) {
2205        props->has_completion_mode = true;
2206        props->completion_mode = ACTION_COMPLETION_MODE_INDIVIDUAL;
2207    }
2208
2209    return props;
2210}
2211
2212/*
2213 * 'Atomic' group operations.  The operations are performed as a set, and if
2214 * any fail then we roll back all operations in the group.
2215 */
2216void qmp_transaction(TransactionActionList *dev_list,
2217                     bool has_props,
2218                     struct TransactionProperties *props,
2219                     Error **errp)
2220{
2221    TransactionActionList *dev_entry = dev_list;
2222    BlockJobTxn *block_job_txn = NULL;
2223    BlkActionState *state, *next;
2224    Error *local_err = NULL;
2225
2226    QSIMPLEQ_HEAD(snap_bdrv_states, BlkActionState) snap_bdrv_states;
2227    QSIMPLEQ_INIT(&snap_bdrv_states);
2228
2229    /* Does this transaction get canceled as a group on failure?
2230     * If not, we don't really need to make a BlockJobTxn.
2231     */
2232    props = get_transaction_properties(props);
2233    if (props->completion_mode != ACTION_COMPLETION_MODE_INDIVIDUAL) {
2234        block_job_txn = block_job_txn_new();
2235    }
2236
2237    /* drain all i/o before any operations */
2238    bdrv_drain_all();
2239
2240    /* We don't do anything in this loop that commits us to the operations */
2241    while (NULL != dev_entry) {
2242        TransactionAction *dev_info = NULL;
2243        const BlkActionOps *ops;
2244
2245        dev_info = dev_entry->value;
2246        dev_entry = dev_entry->next;
2247
2248        assert(dev_info->type < ARRAY_SIZE(actions));
2249
2250        ops = &actions[dev_info->type];
2251        assert(ops->instance_size > 0);
2252
2253        state = g_malloc0(ops->instance_size);
2254        state->ops = ops;
2255        state->action = dev_info;
2256        state->block_job_txn = block_job_txn;
2257        state->txn_props = props;
2258        QSIMPLEQ_INSERT_TAIL(&snap_bdrv_states, state, entry);
2259
2260        state->ops->prepare(state, &local_err);
2261        if (local_err) {
2262            error_propagate(errp, local_err);
2263            goto delete_and_fail;
2264        }
2265    }
2266
2267    QSIMPLEQ_FOREACH(state, &snap_bdrv_states, entry) {
2268        if (state->ops->commit) {
2269            state->ops->commit(state);
2270        }
2271    }
2272
2273    /* success */
2274    goto exit;
2275
2276delete_and_fail:
2277    /* failure, and it is all-or-none; roll back all operations */
2278    QSIMPLEQ_FOREACH(state, &snap_bdrv_states, entry) {
2279        if (state->ops->abort) {
2280            state->ops->abort(state);
2281        }
2282    }
2283exit:
2284    QSIMPLEQ_FOREACH_SAFE(state, &snap_bdrv_states, entry, next) {
2285        if (state->ops->clean) {
2286            state->ops->clean(state);
2287        }
2288        g_free(state);
2289    }
2290    if (!has_props) {
2291        qapi_free_TransactionProperties(props);
2292    }
2293    block_job_txn_unref(block_job_txn);
2294}
2295
2296void qmp_eject(const char *device, bool has_force, bool force, Error **errp)
2297{
2298    Error *local_err = NULL;
2299
2300    qmp_blockdev_open_tray(device, has_force, force, &local_err);
2301    if (local_err) {
2302        error_propagate(errp, local_err);
2303        return;
2304    }
2305
2306    qmp_x_blockdev_remove_medium(device, errp);
2307}
2308
2309void qmp_block_passwd(bool has_device, const char *device,
2310                      bool has_node_name, const char *node_name,
2311                      const char *password, Error **errp)
2312{
2313    Error *local_err = NULL;
2314    BlockDriverState *bs;
2315    AioContext *aio_context;
2316
2317    bs = bdrv_lookup_bs(has_device ? device : NULL,
2318                        has_node_name ? node_name : NULL,
2319                        &local_err);
2320    if (local_err) {
2321        error_propagate(errp, local_err);
2322        return;
2323    }
2324
2325    aio_context = bdrv_get_aio_context(bs);
2326    aio_context_acquire(aio_context);
2327
2328    bdrv_add_key(bs, password, errp);
2329
2330    aio_context_release(aio_context);
2331}
2332
2333void qmp_blockdev_open_tray(const char *device, bool has_force, bool force,
2334                            Error **errp)
2335{
2336    BlockBackend *blk;
2337    bool locked;
2338
2339    if (!has_force) {
2340        force = false;
2341    }
2342
2343    blk = blk_by_name(device);
2344    if (!blk) {
2345        error_set(errp, ERROR_CLASS_DEVICE_NOT_FOUND,
2346                  "Device '%s' not found", device);
2347        return;
2348    }
2349
2350    if (!blk_dev_has_removable_media(blk)) {
2351        error_setg(errp, "Device '%s' is not removable", device);
2352        return;
2353    }
2354
2355    if (!blk_dev_has_tray(blk)) {
2356        /* Ignore this command on tray-less devices */
2357        return;
2358    }
2359
2360    if (blk_dev_is_tray_open(blk)) {
2361        return;
2362    }
2363
2364    locked = blk_dev_is_medium_locked(blk);
2365    if (locked) {
2366        blk_dev_eject_request(blk, force);
2367    }
2368
2369    if (!locked || force) {
2370        blk_dev_change_media_cb(blk, false);
2371    }
2372}
2373
2374void qmp_blockdev_close_tray(const char *device, Error **errp)
2375{
2376    BlockBackend *blk;
2377
2378    blk = blk_by_name(device);
2379    if (!blk) {
2380        error_set(errp, ERROR_CLASS_DEVICE_NOT_FOUND,
2381                  "Device '%s' not found", device);
2382        return;
2383    }
2384
2385    if (!blk_dev_has_removable_media(blk)) {
2386        error_setg(errp, "Device '%s' is not removable", device);
2387        return;
2388    }
2389
2390    if (!blk_dev_has_tray(blk)) {
2391        /* Ignore this command on tray-less devices */
2392        return;
2393    }
2394
2395    if (!blk_dev_is_tray_open(blk)) {
2396        return;
2397    }
2398
2399    blk_dev_change_media_cb(blk, true);
2400}
2401
2402void qmp_x_blockdev_remove_medium(const char *device, Error **errp)
2403{
2404    BlockBackend *blk;
2405    BlockDriverState *bs;
2406    AioContext *aio_context;
2407    bool has_device;
2408
2409    blk = blk_by_name(device);
2410    if (!blk) {
2411        error_set(errp, ERROR_CLASS_DEVICE_NOT_FOUND,
2412                  "Device '%s' not found", device);
2413        return;
2414    }
2415
2416    /* For BBs without a device, we can exchange the BDS tree at will */
2417    has_device = blk_get_attached_dev(blk);
2418
2419    if (has_device && !blk_dev_has_removable_media(blk)) {
2420        error_setg(errp, "Device '%s' is not removable", device);
2421        return;
2422    }
2423
2424    if (has_device && blk_dev_has_tray(blk) && !blk_dev_is_tray_open(blk)) {
2425        error_setg(errp, "Tray of device '%s' is not open", device);
2426        return;
2427    }
2428
2429    bs = blk_bs(blk);
2430    if (!bs) {
2431        return;
2432    }
2433
2434    aio_context = bdrv_get_aio_context(bs);
2435    aio_context_acquire(aio_context);
2436
2437    if (bdrv_op_is_blocked(bs, BLOCK_OP_TYPE_EJECT, errp)) {
2438        goto out;
2439    }
2440
2441    blk_remove_bs(blk);
2442
2443    if (!blk_dev_has_tray(blk)) {
2444        /* For tray-less devices, blockdev-open-tray is a no-op (or may not be
2445         * called at all); therefore, the medium needs to be ejected here.
2446         * Do it after blk_remove_bs() so blk_is_inserted(blk) returns the @load
2447         * value passed here (i.e. false). */
2448        blk_dev_change_media_cb(blk, false);
2449    }
2450
2451out:
2452    aio_context_release(aio_context);
2453}
2454
2455static void qmp_blockdev_insert_anon_medium(const char *device,
2456                                            BlockDriverState *bs, Error **errp)
2457{
2458    BlockBackend *blk;
2459    bool has_device;
2460
2461    blk = blk_by_name(device);
2462    if (!blk) {
2463        error_set(errp, ERROR_CLASS_DEVICE_NOT_FOUND,
2464                  "Device '%s' not found", device);
2465        return;
2466    }
2467
2468    /* For BBs without a device, we can exchange the BDS tree at will */
2469    has_device = blk_get_attached_dev(blk);
2470
2471    if (has_device && !blk_dev_has_removable_media(blk)) {
2472        error_setg(errp, "Device '%s' is not removable", device);
2473        return;
2474    }
2475
2476    if (has_device && blk_dev_has_tray(blk) && !blk_dev_is_tray_open(blk)) {
2477        error_setg(errp, "Tray of device '%s' is not open", device);
2478        return;
2479    }
2480
2481    if (blk_bs(blk)) {
2482        error_setg(errp, "There already is a medium in device '%s'", device);
2483        return;
2484    }
2485
2486    blk_insert_bs(blk, bs);
2487
2488    if (!blk_dev_has_tray(blk)) {
2489        /* For tray-less devices, blockdev-close-tray is a no-op (or may not be
2490         * called at all); therefore, the medium needs to be pushed into the
2491         * slot here.
2492         * Do it after blk_insert_bs() so blk_is_inserted(blk) returns the @load
2493         * value passed here (i.e. true). */
2494        blk_dev_change_media_cb(blk, true);
2495    }
2496}
2497
2498void qmp_x_blockdev_insert_medium(const char *device, const char *node_name,
2499                                  Error **errp)
2500{
2501    BlockDriverState *bs;
2502
2503    bs = bdrv_find_node(node_name);
2504    if (!bs) {
2505        error_setg(errp, "Node '%s' not found", node_name);
2506        return;
2507    }
2508
2509    if (bs->blk) {
2510        error_setg(errp, "Node '%s' is already in use by '%s'", node_name,
2511                   blk_name(bs->blk));
2512        return;
2513    }
2514
2515    qmp_blockdev_insert_anon_medium(device, bs, errp);
2516}
2517
2518void qmp_blockdev_change_medium(const char *device, const char *filename,
2519                                bool has_format, const char *format,
2520                                bool has_read_only,
2521                                BlockdevChangeReadOnlyMode read_only,
2522                                Error **errp)
2523{
2524    BlockBackend *blk;
2525    BlockDriverState *medium_bs = NULL;
2526    int bdrv_flags, ret;
2527    QDict *options = NULL;
2528    Error *err = NULL;
2529
2530    blk = blk_by_name(device);
2531    if (!blk) {
2532        error_set(errp, ERROR_CLASS_DEVICE_NOT_FOUND,
2533                  "Device '%s' not found", device);
2534        goto fail;
2535    }
2536
2537    if (blk_bs(blk)) {
2538        blk_update_root_state(blk);
2539    }
2540
2541    bdrv_flags = blk_get_open_flags_from_root_state(blk);
2542    bdrv_flags &= ~(BDRV_O_TEMPORARY | BDRV_O_SNAPSHOT | BDRV_O_NO_BACKING |
2543        BDRV_O_PROTOCOL);
2544
2545    if (!has_read_only) {
2546        read_only = BLOCKDEV_CHANGE_READ_ONLY_MODE_RETAIN;
2547    }
2548
2549    switch (read_only) {
2550    case BLOCKDEV_CHANGE_READ_ONLY_MODE_RETAIN:
2551        break;
2552
2553    case BLOCKDEV_CHANGE_READ_ONLY_MODE_READ_ONLY:
2554        bdrv_flags &= ~BDRV_O_RDWR;
2555        break;
2556
2557    case BLOCKDEV_CHANGE_READ_ONLY_MODE_READ_WRITE:
2558        bdrv_flags |= BDRV_O_RDWR;
2559        break;
2560
2561    default:
2562        abort();
2563    }
2564
2565    if (has_format) {
2566        options = qdict_new();
2567        qdict_put(options, "driver", qstring_from_str(format));
2568    }
2569
2570    assert(!medium_bs);
2571    ret = bdrv_open(&medium_bs, filename, NULL, options, bdrv_flags, errp);
2572    if (ret < 0) {
2573        goto fail;
2574    }
2575
2576    blk_apply_root_state(blk, medium_bs);
2577
2578    bdrv_add_key(medium_bs, NULL, &err);
2579    if (err) {
2580        error_propagate(errp, err);
2581        goto fail;
2582    }
2583
2584    qmp_blockdev_open_tray(device, false, false, &err);
2585    if (err) {
2586        error_propagate(errp, err);
2587        goto fail;
2588    }
2589
2590    qmp_x_blockdev_remove_medium(device, &err);
2591    if (err) {
2592        error_propagate(errp, err);
2593        goto fail;
2594    }
2595
2596    qmp_blockdev_insert_anon_medium(device, medium_bs, &err);
2597    if (err) {
2598        error_propagate(errp, err);
2599        goto fail;
2600    }
2601
2602    qmp_blockdev_close_tray(device, errp);
2603
2604fail:
2605    /* If the medium has been inserted, the device has its own reference, so
2606     * ours must be relinquished; and if it has not been inserted successfully,
2607     * the reference must be relinquished anyway */
2608    bdrv_unref(medium_bs);
2609}
2610
2611/* throttling disk I/O limits */
2612void qmp_block_set_io_throttle(const char *device, int64_t bps, int64_t bps_rd,
2613                               int64_t bps_wr,
2614                               int64_t iops,
2615                               int64_t iops_rd,
2616                               int64_t iops_wr,
2617                               bool has_bps_max,
2618                               int64_t bps_max,
2619                               bool has_bps_rd_max,
2620                               int64_t bps_rd_max,
2621                               bool has_bps_wr_max,
2622                               int64_t bps_wr_max,
2623                               bool has_iops_max,
2624                               int64_t iops_max,
2625                               bool has_iops_rd_max,
2626                               int64_t iops_rd_max,
2627                               bool has_iops_wr_max,
2628                               int64_t iops_wr_max,
2629                               bool has_bps_max_length,
2630                               int64_t bps_max_length,
2631                               bool has_bps_rd_max_length,
2632                               int64_t bps_rd_max_length,
2633                               bool has_bps_wr_max_length,
2634                               int64_t bps_wr_max_length,
2635                               bool has_iops_max_length,
2636                               int64_t iops_max_length,
2637                               bool has_iops_rd_max_length,
2638                               int64_t iops_rd_max_length,
2639                               bool has_iops_wr_max_length,
2640                               int64_t iops_wr_max_length,
2641                               bool has_iops_size,
2642                               int64_t iops_size,
2643                               bool has_group,
2644                               const char *group, Error **errp)
2645{
2646    ThrottleConfig cfg;
2647    BlockDriverState *bs;
2648    BlockBackend *blk;
2649    AioContext *aio_context;
2650
2651    blk = blk_by_name(device);
2652    if (!blk) {
2653        error_set(errp, ERROR_CLASS_DEVICE_NOT_FOUND,
2654                  "Device '%s' not found", device);
2655        return;
2656    }
2657
2658    aio_context = blk_get_aio_context(blk);
2659    aio_context_acquire(aio_context);
2660
2661    bs = blk_bs(blk);
2662    if (!bs) {
2663        error_setg(errp, "Device '%s' has no medium", device);
2664        goto out;
2665    }
2666
2667    /* The BlockBackend must be the only parent */
2668    assert(QLIST_FIRST(&bs->parents));
2669    if (QLIST_NEXT(QLIST_FIRST(&bs->parents), next_parent)) {
2670        error_setg(errp, "Cannot throttle device with multiple parents");
2671        goto out;
2672    }
2673
2674    throttle_config_init(&cfg);
2675    cfg.buckets[THROTTLE_BPS_TOTAL].avg = bps;
2676    cfg.buckets[THROTTLE_BPS_READ].avg  = bps_rd;
2677    cfg.buckets[THROTTLE_BPS_WRITE].avg = bps_wr;
2678
2679    cfg.buckets[THROTTLE_OPS_TOTAL].avg = iops;
2680    cfg.buckets[THROTTLE_OPS_READ].avg  = iops_rd;
2681    cfg.buckets[THROTTLE_OPS_WRITE].avg = iops_wr;
2682
2683    if (has_bps_max) {
2684        cfg.buckets[THROTTLE_BPS_TOTAL].max = bps_max;
2685    }
2686    if (has_bps_rd_max) {
2687        cfg.buckets[THROTTLE_BPS_READ].max = bps_rd_max;
2688    }
2689    if (has_bps_wr_max) {
2690        cfg.buckets[THROTTLE_BPS_WRITE].max = bps_wr_max;
2691    }
2692    if (has_iops_max) {
2693        cfg.buckets[THROTTLE_OPS_TOTAL].max = iops_max;
2694    }
2695    if (has_iops_rd_max) {
2696        cfg.buckets[THROTTLE_OPS_READ].max = iops_rd_max;
2697    }
2698    if (has_iops_wr_max) {
2699        cfg.buckets[THROTTLE_OPS_WRITE].max = iops_wr_max;
2700    }
2701
2702    if (has_bps_max_length) {
2703        cfg.buckets[THROTTLE_BPS_TOTAL].burst_length = bps_max_length;
2704    }
2705    if (has_bps_rd_max_length) {
2706        cfg.buckets[THROTTLE_BPS_READ].burst_length = bps_rd_max_length;
2707    }
2708    if (has_bps_wr_max_length) {
2709        cfg.buckets[THROTTLE_BPS_WRITE].burst_length = bps_wr_max_length;
2710    }
2711    if (has_iops_max_length) {
2712        cfg.buckets[THROTTLE_OPS_TOTAL].burst_length = iops_max_length;
2713    }
2714    if (has_iops_rd_max_length) {
2715        cfg.buckets[THROTTLE_OPS_READ].burst_length = iops_rd_max_length;
2716    }
2717    if (has_iops_wr_max_length) {
2718        cfg.buckets[THROTTLE_OPS_WRITE].burst_length = iops_wr_max_length;
2719    }
2720
2721    if (has_iops_size) {
2722        cfg.op_size = iops_size;
2723    }
2724
2725    if (!throttle_is_valid(&cfg, errp)) {
2726        goto out;
2727    }
2728
2729    if (throttle_enabled(&cfg)) {
2730        /* Enable I/O limits if they're not enabled yet, otherwise
2731         * just update the throttling group. */
2732        if (!bs->throttle_state) {
2733            bdrv_io_limits_enable(bs, has_group ? group : device);
2734        } else if (has_group) {
2735            bdrv_io_limits_update_group(bs, group);
2736        }
2737        /* Set the new throttling configuration */
2738        bdrv_set_io_limits(bs, &cfg);
2739    } else if (bs->throttle_state) {
2740        /* If all throttling settings are set to 0, disable I/O limits */
2741        bdrv_io_limits_disable(bs);
2742    }
2743
2744out:
2745    aio_context_release(aio_context);
2746}
2747
2748void qmp_block_dirty_bitmap_add(const char *node, const char *name,
2749                                bool has_granularity, uint32_t granularity,
2750                                Error **errp)
2751{
2752    AioContext *aio_context;
2753    BlockDriverState *bs;
2754
2755    if (!name || name[0] == '\0') {
2756        error_setg(errp, "Bitmap name cannot be empty");
2757        return;
2758    }
2759
2760    bs = bdrv_lookup_bs(node, node, errp);
2761    if (!bs) {
2762        return;
2763    }
2764
2765    aio_context = bdrv_get_aio_context(bs);
2766    aio_context_acquire(aio_context);
2767
2768    if (has_granularity) {
2769        if (granularity < 512 || !is_power_of_2(granularity)) {
2770            error_setg(errp, "Granularity must be power of 2 "
2771                             "and at least 512");
2772            goto out;
2773        }
2774    } else {
2775        /* Default to cluster size, if available: */
2776        granularity = bdrv_get_default_bitmap_granularity(bs);
2777    }
2778
2779    bdrv_create_dirty_bitmap(bs, granularity, name, errp);
2780
2781 out:
2782    aio_context_release(aio_context);
2783}
2784
2785void qmp_block_dirty_bitmap_remove(const char *node, const char *name,
2786                                   Error **errp)
2787{
2788    AioContext *aio_context;
2789    BlockDriverState *bs;
2790    BdrvDirtyBitmap *bitmap;
2791
2792    bitmap = block_dirty_bitmap_lookup(node, name, &bs, &aio_context, errp);
2793    if (!bitmap || !bs) {
2794        return;
2795    }
2796
2797    if (bdrv_dirty_bitmap_frozen(bitmap)) {
2798        error_setg(errp,
2799                   "Bitmap '%s' is currently frozen and cannot be removed",
2800                   name);
2801        goto out;
2802    }
2803    bdrv_dirty_bitmap_make_anon(bitmap);
2804    bdrv_release_dirty_bitmap(bs, bitmap);
2805
2806 out:
2807    aio_context_release(aio_context);
2808}
2809
2810/**
2811 * Completely clear a bitmap, for the purposes of synchronizing a bitmap
2812 * immediately after a full backup operation.
2813 */
2814void qmp_block_dirty_bitmap_clear(const char *node, const char *name,
2815                                  Error **errp)
2816{
2817    AioContext *aio_context;
2818    BdrvDirtyBitmap *bitmap;
2819    BlockDriverState *bs;
2820
2821    bitmap = block_dirty_bitmap_lookup(node, name, &bs, &aio_context, errp);
2822    if (!bitmap || !bs) {
2823        return;
2824    }
2825
2826    if (bdrv_dirty_bitmap_frozen(bitmap)) {
2827        error_setg(errp,
2828                   "Bitmap '%s' is currently frozen and cannot be modified",
2829                   name);
2830        goto out;
2831    } else if (!bdrv_dirty_bitmap_enabled(bitmap)) {
2832        error_setg(errp,
2833                   "Bitmap '%s' is currently disabled and cannot be cleared",
2834                   name);
2835        goto out;
2836    }
2837
2838    bdrv_clear_dirty_bitmap(bitmap, NULL);
2839
2840 out:
2841    aio_context_release(aio_context);
2842}
2843
2844void hmp_drive_del(Monitor *mon, const QDict *qdict)
2845{
2846    const char *id = qdict_get_str(qdict, "id");
2847    BlockBackend *blk;
2848    BlockDriverState *bs;
2849    AioContext *aio_context;
2850    Error *local_err = NULL;
2851
2852    bs = bdrv_find_node(id);
2853    if (bs) {
2854        qmp_x_blockdev_del(false, NULL, true, id, &local_err);
2855        if (local_err) {
2856            error_report_err(local_err);
2857        }
2858        return;
2859    }
2860
2861    blk = blk_by_name(id);
2862    if (!blk) {
2863        error_report("Device '%s' not found", id);
2864        return;
2865    }
2866
2867    if (!blk_legacy_dinfo(blk)) {
2868        error_report("Deleting device added with blockdev-add"
2869                     " is not supported");
2870        return;
2871    }
2872
2873    aio_context = blk_get_aio_context(blk);
2874    aio_context_acquire(aio_context);
2875
2876    bs = blk_bs(blk);
2877    if (bs) {
2878        if (bdrv_op_is_blocked(bs, BLOCK_OP_TYPE_DRIVE_DEL, &local_err)) {
2879            error_report_err(local_err);
2880            aio_context_release(aio_context);
2881            return;
2882        }
2883
2884        blk_remove_bs(blk);
2885    }
2886
2887    /* Make the BlockBackend and the attached BlockDriverState anonymous */
2888    monitor_remove_blk(blk);
2889
2890    /* If this BlockBackend has a device attached to it, its refcount will be
2891     * decremented when the device is removed; otherwise we have to do so here.
2892     */
2893    if (blk_get_attached_dev(blk)) {
2894        /* Further I/O must not pause the guest */
2895        blk_set_on_error(blk, BLOCKDEV_ON_ERROR_REPORT,
2896                         BLOCKDEV_ON_ERROR_REPORT);
2897    } else {
2898        blk_unref(blk);
2899    }
2900
2901    aio_context_release(aio_context);
2902}
2903
2904void qmp_block_resize(bool has_device, const char *device,
2905                      bool has_node_name, const char *node_name,
2906                      int64_t size, Error **errp)
2907{
2908    Error *local_err = NULL;
2909    BlockDriverState *bs;
2910    AioContext *aio_context;
2911    int ret;
2912
2913    bs = bdrv_lookup_bs(has_device ? device : NULL,
2914                        has_node_name ? node_name : NULL,
2915                        &local_err);
2916    if (local_err) {
2917        error_propagate(errp, local_err);
2918        return;
2919    }
2920
2921    aio_context = bdrv_get_aio_context(bs);
2922    aio_context_acquire(aio_context);
2923
2924    if (!bdrv_is_first_non_filter(bs)) {
2925        error_setg(errp, QERR_FEATURE_DISABLED, "resize");
2926        goto out;
2927    }
2928
2929    if (size < 0) {
2930        error_setg(errp, QERR_INVALID_PARAMETER_VALUE, "size", "a >0 size");
2931        goto out;
2932    }
2933
2934    if (bdrv_op_is_blocked(bs, BLOCK_OP_TYPE_RESIZE, NULL)) {
2935        error_setg(errp, QERR_DEVICE_IN_USE, device);
2936        goto out;
2937    }
2938
2939    /* complete all in-flight operations before resizing the device */
2940    bdrv_drain_all();
2941
2942    ret = bdrv_truncate(bs, size);
2943    switch (ret) {
2944    case 0:
2945        break;
2946    case -ENOMEDIUM:
2947        error_setg(errp, QERR_DEVICE_HAS_NO_MEDIUM, device);
2948        break;
2949    case -ENOTSUP:
2950        error_setg(errp, QERR_UNSUPPORTED);
2951        break;
2952    case -EACCES:
2953        error_setg(errp, "Device '%s' is read only", device);
2954        break;
2955    case -EBUSY:
2956        error_setg(errp, QERR_DEVICE_IN_USE, device);
2957        break;
2958    default:
2959        error_setg_errno(errp, -ret, "Could not resize");
2960        break;
2961    }
2962
2963out:
2964    aio_context_release(aio_context);
2965}
2966
2967static void block_job_cb(void *opaque, int ret)
2968{
2969    /* Note that this function may be executed from another AioContext besides
2970     * the QEMU main loop.  If you need to access anything that assumes the
2971     * QEMU global mutex, use a BH or introduce a mutex.
2972     */
2973
2974    BlockDriverState *bs = opaque;
2975    const char *msg = NULL;
2976
2977    trace_block_job_cb(bs, bs->job, ret);
2978
2979    assert(bs->job);
2980
2981    if (ret < 0) {
2982        msg = strerror(-ret);
2983    }
2984
2985    if (block_job_is_cancelled(bs->job)) {
2986        block_job_event_cancelled(bs->job);
2987    } else {
2988        block_job_event_completed(bs->job, msg);
2989    }
2990}
2991
2992void qmp_block_stream(const char *device,
2993                      bool has_base, const char *base,
2994                      bool has_backing_file, const char *backing_file,
2995                      bool has_speed, int64_t speed,
2996                      bool has_on_error, BlockdevOnError on_error,
2997                      Error **errp)
2998{
2999    BlockBackend *blk;
3000    BlockDriverState *bs;
3001    BlockDriverState *base_bs = NULL;
3002    AioContext *aio_context;
3003    Error *local_err = NULL;
3004    const char *base_name = NULL;
3005
3006    if (!has_on_error) {
3007        on_error = BLOCKDEV_ON_ERROR_REPORT;
3008    }
3009
3010    blk = blk_by_name(device);
3011    if (!blk) {
3012        error_set(errp, ERROR_CLASS_DEVICE_NOT_FOUND,
3013                  "Device '%s' not found", device);
3014        return;
3015    }
3016
3017    aio_context = blk_get_aio_context(blk);
3018    aio_context_acquire(aio_context);
3019
3020    if (!blk_is_available(blk)) {
3021        error_setg(errp, "Device '%s' has no medium", device);
3022        goto out;
3023    }
3024    bs = blk_bs(blk);
3025
3026    if (bdrv_op_is_blocked(bs, BLOCK_OP_TYPE_STREAM, errp)) {
3027        goto out;
3028    }
3029
3030    if (has_base) {
3031        base_bs = bdrv_find_backing_image(bs, base);
3032        if (base_bs == NULL) {
3033            error_setg(errp, QERR_BASE_NOT_FOUND, base);
3034            goto out;
3035        }
3036        assert(bdrv_get_aio_context(base_bs) == aio_context);
3037        base_name = base;
3038    }
3039
3040    /* if we are streaming the entire chain, the result will have no backing
3041     * file, and specifying one is therefore an error */
3042    if (base_bs == NULL && has_backing_file) {
3043        error_setg(errp, "backing file specified, but streaming the "
3044                         "entire chain");
3045        goto out;
3046    }
3047
3048    /* backing_file string overrides base bs filename */
3049    base_name = has_backing_file ? backing_file : base_name;
3050
3051    stream_start(bs, base_bs, base_name, has_speed ? speed : 0,
3052                 on_error, block_job_cb, bs, &local_err);
3053    if (local_err) {
3054        error_propagate(errp, local_err);
3055        goto out;
3056    }
3057
3058    trace_qmp_block_stream(bs, bs->job);
3059
3060out:
3061    aio_context_release(aio_context);
3062}
3063
3064void qmp_block_commit(const char *device,
3065                      bool has_base, const char *base,
3066                      bool has_top, const char *top,
3067                      bool has_backing_file, const char *backing_file,
3068                      bool has_speed, int64_t speed,
3069                      Error **errp)
3070{
3071    BlockBackend *blk;
3072    BlockDriverState *bs;
3073    BlockDriverState *base_bs, *top_bs;
3074    AioContext *aio_context;
3075    Error *local_err = NULL;
3076    /* This will be part of the QMP command, if/when the
3077     * BlockdevOnError change for blkmirror makes it in
3078     */
3079    BlockdevOnError on_error = BLOCKDEV_ON_ERROR_REPORT;
3080
3081    if (!has_speed) {
3082        speed = 0;
3083    }
3084
3085    /* Important Note:
3086     *  libvirt relies on the DeviceNotFound error class in order to probe for
3087     *  live commit feature versions; for this to work, we must make sure to
3088     *  perform the device lookup before any generic errors that may occur in a
3089     *  scenario in which all optional arguments are omitted. */
3090    blk = blk_by_name(device);
3091    if (!blk) {
3092        error_set(errp, ERROR_CLASS_DEVICE_NOT_FOUND,
3093                  "Device '%s' not found", device);
3094        return;
3095    }
3096
3097    aio_context = blk_get_aio_context(blk);
3098    aio_context_acquire(aio_context);
3099
3100    if (!blk_is_available(blk)) {
3101        error_setg(errp, "Device '%s' has no medium", device);
3102        goto out;
3103    }
3104    bs = blk_bs(blk);
3105
3106    if (bdrv_op_is_blocked(bs, BLOCK_OP_TYPE_COMMIT_SOURCE, errp)) {
3107        goto out;
3108    }
3109
3110    /* default top_bs is the active layer */
3111    top_bs = bs;
3112
3113    if (has_top && top) {
3114        if (strcmp(bs->filename, top) != 0) {
3115            top_bs = bdrv_find_backing_image(bs, top);
3116        }
3117    }
3118
3119    if (top_bs == NULL) {
3120        error_setg(errp, "Top image file %s not found", top ? top : "NULL");
3121        goto out;
3122    }
3123
3124    assert(bdrv_get_aio_context(top_bs) == aio_context);
3125
3126    if (has_base && base) {
3127        base_bs = bdrv_find_backing_image(top_bs, base);
3128    } else {
3129        base_bs = bdrv_find_base(top_bs);
3130    }
3131
3132    if (base_bs == NULL) {
3133        error_setg(errp, QERR_BASE_NOT_FOUND, base ? base : "NULL");
3134        goto out;
3135    }
3136
3137    assert(bdrv_get_aio_context(base_bs) == aio_context);
3138
3139    if (bdrv_op_is_blocked(base_bs, BLOCK_OP_TYPE_COMMIT_TARGET, errp)) {
3140        goto out;
3141    }
3142
3143    /* Do not allow attempts to commit an image into itself */
3144    if (top_bs == base_bs) {
3145        error_setg(errp, "cannot commit an image into itself");
3146        goto out;
3147    }
3148
3149    if (top_bs == bs) {
3150        if (has_backing_file) {
3151            error_setg(errp, "'backing-file' specified,"
3152                             " but 'top' is the active layer");
3153            goto out;
3154        }
3155        commit_active_start(bs, base_bs, speed, on_error, block_job_cb,
3156                            bs, &local_err);
3157    } else {
3158        commit_start(bs, base_bs, top_bs, speed, on_error, block_job_cb, bs,
3159                     has_backing_file ? backing_file : NULL, &local_err);
3160    }
3161    if (local_err != NULL) {
3162        error_propagate(errp, local_err);
3163        goto out;
3164    }
3165
3166out:
3167    aio_context_release(aio_context);
3168}
3169
3170static void do_drive_backup(const char *device, const char *target,
3171                            bool has_format, const char *format,
3172                            enum MirrorSyncMode sync,
3173                            bool has_mode, enum NewImageMode mode,
3174                            bool has_speed, int64_t speed,
3175                            bool has_bitmap, const char *bitmap,
3176                            bool has_on_source_error,
3177                            BlockdevOnError on_source_error,
3178                            bool has_on_target_error,
3179                            BlockdevOnError on_target_error,
3180                            BlockJobTxn *txn, Error **errp)
3181{
3182    BlockBackend *blk;
3183    BlockDriverState *bs;
3184    BlockDriverState *target_bs;
3185    BlockDriverState *source = NULL;
3186    BdrvDirtyBitmap *bmap = NULL;
3187    AioContext *aio_context;
3188    QDict *options = NULL;
3189    Error *local_err = NULL;
3190    int flags;
3191    int64_t size;
3192    int ret;
3193
3194    if (!has_speed) {
3195        speed = 0;
3196    }
3197    if (!has_on_source_error) {
3198        on_source_error = BLOCKDEV_ON_ERROR_REPORT;
3199    }
3200    if (!has_on_target_error) {
3201        on_target_error = BLOCKDEV_ON_ERROR_REPORT;
3202    }
3203    if (!has_mode) {
3204        mode = NEW_IMAGE_MODE_ABSOLUTE_PATHS;
3205    }
3206
3207    blk = blk_by_name(device);
3208    if (!blk) {
3209        error_set(errp, ERROR_CLASS_DEVICE_NOT_FOUND,
3210                  "Device '%s' not found", device);
3211        return;
3212    }
3213
3214    aio_context = blk_get_aio_context(blk);
3215    aio_context_acquire(aio_context);
3216
3217    /* Although backup_run has this check too, we need to use bs->drv below, so
3218     * do an early check redundantly. */
3219    if (!blk_is_available(blk)) {
3220        error_setg(errp, QERR_DEVICE_HAS_NO_MEDIUM, device);
3221        goto out;
3222    }
3223    bs = blk_bs(blk);
3224
3225    if (!has_format) {
3226        format = mode == NEW_IMAGE_MODE_EXISTING ? NULL : bs->drv->format_name;
3227    }
3228
3229    /* Early check to avoid creating target */
3230    if (bdrv_op_is_blocked(bs, BLOCK_OP_TYPE_BACKUP_SOURCE, errp)) {
3231        goto out;
3232    }
3233
3234    flags = bs->open_flags | BDRV_O_RDWR;
3235
3236    /* See if we have a backing HD we can use to create our new image
3237     * on top of. */
3238    if (sync == MIRROR_SYNC_MODE_TOP) {
3239        source = backing_bs(bs);
3240        if (!source) {
3241            sync = MIRROR_SYNC_MODE_FULL;
3242        }
3243    }
3244    if (sync == MIRROR_SYNC_MODE_NONE) {
3245        source = bs;
3246    }
3247
3248    size = bdrv_getlength(bs);
3249    if (size < 0) {
3250        error_setg_errno(errp, -size, "bdrv_getlength failed");
3251        goto out;
3252    }
3253
3254    if (mode != NEW_IMAGE_MODE_EXISTING) {
3255        assert(format);
3256        if (source) {
3257            bdrv_img_create(target, format, source->filename,
3258                            source->drv->format_name, NULL,
3259                            size, flags, &local_err, false);
3260        } else {
3261            bdrv_img_create(target, format, NULL, NULL, NULL,
3262                            size, flags, &local_err, false);
3263        }
3264    }
3265
3266    if (local_err) {
3267        error_propagate(errp, local_err);
3268        goto out;
3269    }
3270
3271    if (format) {
3272        options = qdict_new();
3273        qdict_put(options, "driver", qstring_from_str(format));
3274    }
3275
3276    target_bs = NULL;
3277    ret = bdrv_open(&target_bs, target, NULL, options, flags, &local_err);
3278    if (ret < 0) {
3279        error_propagate(errp, local_err);
3280        goto out;
3281    }
3282
3283    bdrv_set_aio_context(target_bs, aio_context);
3284
3285    if (has_bitmap) {
3286        bmap = bdrv_find_dirty_bitmap(bs, bitmap);
3287        if (!bmap) {
3288            error_setg(errp, "Bitmap '%s' could not be found", bitmap);
3289            bdrv_unref(target_bs);
3290            goto out;
3291        }
3292    }
3293
3294    backup_start(bs, target_bs, speed, sync, bmap,
3295                 on_source_error, on_target_error,
3296                 block_job_cb, bs, txn, &local_err);
3297    if (local_err != NULL) {
3298        bdrv_unref(target_bs);
3299        error_propagate(errp, local_err);
3300        goto out;
3301    }
3302
3303out:
3304    aio_context_release(aio_context);
3305}
3306
3307void qmp_drive_backup(const char *device, const char *target,
3308                      bool has_format, const char *format,
3309                      enum MirrorSyncMode sync,
3310                      bool has_mode, enum NewImageMode mode,
3311                      bool has_speed, int64_t speed,
3312                      bool has_bitmap, const char *bitmap,
3313                      bool has_on_source_error, BlockdevOnError on_source_error,
3314                      bool has_on_target_error, BlockdevOnError on_target_error,
3315                      Error **errp)
3316{
3317    return do_drive_backup(device, target, has_format, format, sync,
3318                           has_mode, mode, has_speed, speed,
3319                           has_bitmap, bitmap,
3320                           has_on_source_error, on_source_error,
3321                           has_on_target_error, on_target_error,
3322                           NULL, errp);
3323}
3324
3325BlockDeviceInfoList *qmp_query_named_block_nodes(Error **errp)
3326{
3327    return bdrv_named_nodes_list(errp);
3328}
3329
3330void do_blockdev_backup(const char *device, const char *target,
3331                         enum MirrorSyncMode sync,
3332                         bool has_speed, int64_t speed,
3333                         bool has_on_source_error,
3334                         BlockdevOnError on_source_error,
3335                         bool has_on_target_error,
3336                         BlockdevOnError on_target_error,
3337                         BlockJobTxn *txn, Error **errp)
3338{
3339    BlockBackend *blk, *target_blk;
3340    BlockDriverState *bs;
3341    BlockDriverState *target_bs;
3342    Error *local_err = NULL;
3343    AioContext *aio_context;
3344
3345    if (!has_speed) {
3346        speed = 0;
3347    }
3348    if (!has_on_source_error) {
3349        on_source_error = BLOCKDEV_ON_ERROR_REPORT;
3350    }
3351    if (!has_on_target_error) {
3352        on_target_error = BLOCKDEV_ON_ERROR_REPORT;
3353    }
3354
3355    blk = blk_by_name(device);
3356    if (!blk) {
3357        error_setg(errp, "Device '%s' not found", device);
3358        return;
3359    }
3360
3361    aio_context = blk_get_aio_context(blk);
3362    aio_context_acquire(aio_context);
3363
3364    if (!blk_is_available(blk)) {
3365        error_setg(errp, "Device '%s' has no medium", device);
3366        goto out;
3367    }
3368    bs = blk_bs(blk);
3369
3370    target_blk = blk_by_name(target);
3371    if (!target_blk) {
3372        error_setg(errp, "Device '%s' not found", target);
3373        goto out;
3374    }
3375
3376    if (!blk_is_available(target_blk)) {
3377        error_setg(errp, "Device '%s' has no medium", target);
3378        goto out;
3379    }
3380    target_bs = blk_bs(target_blk);
3381
3382    bdrv_ref(target_bs);
3383    bdrv_set_aio_context(target_bs, aio_context);
3384    backup_start(bs, target_bs, speed, sync, NULL, on_source_error,
3385                 on_target_error, block_job_cb, bs, txn, &local_err);
3386    if (local_err != NULL) {
3387        bdrv_unref(target_bs);
3388        error_propagate(errp, local_err);
3389    }
3390out:
3391    aio_context_release(aio_context);
3392}
3393
3394void qmp_blockdev_backup(const char *device, const char *target,
3395                         enum MirrorSyncMode sync,
3396                         bool has_speed, int64_t speed,
3397                         bool has_on_source_error,
3398                         BlockdevOnError on_source_error,
3399                         bool has_on_target_error,
3400                         BlockdevOnError on_target_error,
3401                         Error **errp)
3402{
3403    do_blockdev_backup(device, target, sync, has_speed, speed,
3404                       has_on_source_error, on_source_error,
3405                       has_on_target_error, on_target_error,
3406                       NULL, errp);
3407}
3408
3409/* Parameter check and block job starting for drive mirroring.
3410 * Caller should hold @device and @target's aio context (must be the same).
3411 **/
3412static void blockdev_mirror_common(BlockDriverState *bs,
3413                                   BlockDriverState *target,
3414                                   bool has_replaces, const char *replaces,
3415                                   enum MirrorSyncMode sync,
3416                                   bool has_speed, int64_t speed,
3417                                   bool has_granularity, uint32_t granularity,
3418                                   bool has_buf_size, int64_t buf_size,
3419                                   bool has_on_source_error,
3420                                   BlockdevOnError on_source_error,
3421                                   bool has_on_target_error,
3422                                   BlockdevOnError on_target_error,
3423                                   bool has_unmap, bool unmap,
3424                                   Error **errp)
3425{
3426
3427    if (!has_speed) {
3428        speed = 0;
3429    }
3430    if (!has_on_source_error) {
3431        on_source_error = BLOCKDEV_ON_ERROR_REPORT;
3432    }
3433    if (!has_on_target_error) {
3434        on_target_error = BLOCKDEV_ON_ERROR_REPORT;
3435    }
3436    if (!has_granularity) {
3437        granularity = 0;
3438    }
3439    if (!has_buf_size) {
3440        buf_size = 0;
3441    }
3442    if (!has_unmap) {
3443        unmap = true;
3444    }
3445
3446    if (granularity != 0 && (granularity < 512 || granularity > 1048576 * 64)) {
3447        error_setg(errp, QERR_INVALID_PARAMETER_VALUE, "granularity",
3448                   "a value in range [512B, 64MB]");
3449        return;
3450    }
3451    if (granularity & (granularity - 1)) {
3452        error_setg(errp, QERR_INVALID_PARAMETER_VALUE, "granularity",
3453                   "power of 2");
3454        return;
3455    }
3456
3457    if (bdrv_op_is_blocked(bs, BLOCK_OP_TYPE_MIRROR_SOURCE, errp)) {
3458        return;
3459    }
3460    if (bdrv_op_is_blocked(target, BLOCK_OP_TYPE_MIRROR_TARGET, errp)) {
3461        return;
3462    }
3463    if (target->blk) {
3464        error_setg(errp, "Cannot mirror to an attached block device");
3465        return;
3466    }
3467
3468    if (!bs->backing && sync == MIRROR_SYNC_MODE_TOP) {
3469        sync = MIRROR_SYNC_MODE_FULL;
3470    }
3471
3472    /* pass the node name to replace to mirror start since it's loose coupling
3473     * and will allow to check whether the node still exist at mirror completion
3474     */
3475    mirror_start(bs, target,
3476                 has_replaces ? replaces : NULL,
3477                 speed, granularity, buf_size, sync,
3478                 on_source_error, on_target_error, unmap,
3479                 block_job_cb, bs, errp);
3480}
3481
3482void qmp_drive_mirror(const char *device, const char *target,
3483                      bool has_format, const char *format,
3484                      bool has_node_name, const char *node_name,
3485                      bool has_replaces, const char *replaces,
3486                      enum MirrorSyncMode sync,
3487                      bool has_mode, enum NewImageMode mode,
3488                      bool has_speed, int64_t speed,
3489                      bool has_granularity, uint32_t granularity,
3490                      bool has_buf_size, int64_t buf_size,
3491                      bool has_on_source_error, BlockdevOnError on_source_error,
3492                      bool has_on_target_error, BlockdevOnError on_target_error,
3493                      bool has_unmap, bool unmap,
3494                      Error **errp)
3495{
3496    BlockDriverState *bs;
3497    BlockBackend *blk;
3498    BlockDriverState *source, *target_bs;
3499    AioContext *aio_context;
3500    Error *local_err = NULL;
3501    QDict *options = NULL;
3502    int flags;
3503    int64_t size;
3504    int ret;
3505
3506    blk = blk_by_name(device);
3507    if (!blk) {
3508        error_set(errp, ERROR_CLASS_DEVICE_NOT_FOUND,
3509                  "Device '%s' not found", device);
3510        return;
3511    }
3512
3513    aio_context = blk_get_aio_context(blk);
3514    aio_context_acquire(aio_context);
3515
3516    if (!blk_is_available(blk)) {
3517        error_setg(errp, QERR_DEVICE_HAS_NO_MEDIUM, device);
3518        goto out;
3519    }
3520    bs = blk_bs(blk);
3521    if (!has_mode) {
3522        mode = NEW_IMAGE_MODE_ABSOLUTE_PATHS;
3523    }
3524
3525    if (!has_format) {
3526        format = mode == NEW_IMAGE_MODE_EXISTING ? NULL : bs->drv->format_name;
3527    }
3528
3529    flags = bs->open_flags | BDRV_O_RDWR;
3530    source = backing_bs(bs);
3531    if (!source && sync == MIRROR_SYNC_MODE_TOP) {
3532        sync = MIRROR_SYNC_MODE_FULL;
3533    }
3534    if (sync == MIRROR_SYNC_MODE_NONE) {
3535        source = bs;
3536    }
3537
3538    size = bdrv_getlength(bs);
3539    if (size < 0) {
3540        error_setg_errno(errp, -size, "bdrv_getlength failed");
3541        goto out;
3542    }
3543
3544    if (has_replaces) {
3545        BlockDriverState *to_replace_bs;
3546        AioContext *replace_aio_context;
3547        int64_t replace_size;
3548
3549        if (!has_node_name) {
3550            error_setg(errp, "a node-name must be provided when replacing a"
3551                             " named node of the graph");
3552            goto out;
3553        }
3554
3555        to_replace_bs = check_to_replace_node(bs, replaces, &local_err);
3556
3557        if (!to_replace_bs) {
3558            error_propagate(errp, local_err);
3559            goto out;
3560        }
3561
3562        replace_aio_context = bdrv_get_aio_context(to_replace_bs);
3563        aio_context_acquire(replace_aio_context);
3564        replace_size = bdrv_getlength(to_replace_bs);
3565        aio_context_release(replace_aio_context);
3566
3567        if (size != replace_size) {
3568            error_setg(errp, "cannot replace image with a mirror image of "
3569                             "different size");
3570            goto out;
3571        }
3572    }
3573
3574    if ((sync == MIRROR_SYNC_MODE_FULL || !source)
3575        && mode != NEW_IMAGE_MODE_EXISTING)
3576    {
3577        /* create new image w/o backing file */
3578        assert(format);
3579        bdrv_img_create(target, format,
3580                        NULL, NULL, NULL, size, flags, &local_err, false);
3581    } else {
3582        switch (mode) {
3583        case NEW_IMAGE_MODE_EXISTING:
3584            break;
3585        case NEW_IMAGE_MODE_ABSOLUTE_PATHS:
3586            /* create new image with backing file */
3587            bdrv_img_create(target, format,
3588                            source->filename,
3589                            source->drv->format_name,
3590                            NULL, size, flags, &local_err, false);
3591            break;
3592        default:
3593            abort();
3594        }
3595    }
3596
3597    if (local_err) {
3598        error_propagate(errp, local_err);
3599        goto out;
3600    }
3601
3602    options = qdict_new();
3603    if (has_node_name) {
3604        qdict_put(options, "node-name", qstring_from_str(node_name));
3605    }
3606    if (format) {
3607        qdict_put(options, "driver", qstring_from_str(format));
3608    }
3609
3610    /* Mirroring takes care of copy-on-write using the source's backing
3611     * file.
3612     */
3613    target_bs = NULL;
3614    ret = bdrv_open(&target_bs, target, NULL, options,
3615                    flags | BDRV_O_NO_BACKING, &local_err);
3616    if (ret < 0) {
3617        error_propagate(errp, local_err);
3618        goto out;
3619    }
3620
3621    bdrv_set_aio_context(target_bs, aio_context);
3622
3623    blockdev_mirror_common(bs, target_bs,
3624                           has_replaces, replaces, sync,
3625                           has_speed, speed,
3626                           has_granularity, granularity,
3627                           has_buf_size, buf_size,
3628                           has_on_source_error, on_source_error,
3629                           has_on_target_error, on_target_error,
3630                           has_unmap, unmap,
3631                           &local_err);
3632    if (local_err) {
3633        error_propagate(errp, local_err);
3634        bdrv_unref(target_bs);
3635    }
3636out:
3637    aio_context_release(aio_context);
3638}
3639
3640void qmp_blockdev_mirror(const char *device, const char *target,
3641                         bool has_replaces, const char *replaces,
3642                         MirrorSyncMode sync,
3643                         bool has_speed, int64_t speed,
3644                         bool has_granularity, uint32_t granularity,
3645                         bool has_buf_size, int64_t buf_size,
3646                         bool has_on_source_error,
3647                         BlockdevOnError on_source_error,
3648                         bool has_on_target_error,
3649                         BlockdevOnError on_target_error,
3650                         Error **errp)
3651{
3652    BlockDriverState *bs;
3653    BlockBackend *blk;
3654    BlockDriverState *target_bs;
3655    AioContext *aio_context;
3656    Error *local_err = NULL;
3657
3658    blk = blk_by_name(device);
3659    if (!blk) {
3660        error_setg(errp, "Device '%s' not found", device);
3661        return;
3662    }
3663    bs = blk_bs(blk);
3664
3665    if (!bs) {
3666        error_setg(errp, "Device '%s' has no media", device);
3667        return;
3668    }
3669
3670    target_bs = bdrv_lookup_bs(target, target, errp);
3671    if (!target_bs) {
3672        return;
3673    }
3674
3675    aio_context = bdrv_get_aio_context(bs);
3676    aio_context_acquire(aio_context);
3677
3678    bdrv_ref(target_bs);
3679    bdrv_set_aio_context(target_bs, aio_context);
3680
3681    blockdev_mirror_common(bs, target_bs,
3682                           has_replaces, replaces, sync,
3683                           has_speed, speed,
3684                           has_granularity, granularity,
3685                           has_buf_size, buf_size,
3686                           has_on_source_error, on_source_error,
3687                           has_on_target_error, on_target_error,
3688                           true, true,
3689                           &local_err);
3690    if (local_err) {
3691        error_propagate(errp, local_err);
3692        bdrv_unref(target_bs);
3693    }
3694
3695    aio_context_release(aio_context);
3696}
3697
3698/* Get the block job for a given device name and acquire its AioContext */
3699static BlockJob *find_block_job(const char *device, AioContext **aio_context,
3700                                Error **errp)
3701{
3702    BlockBackend *blk;
3703    BlockDriverState *bs;
3704
3705    *aio_context = NULL;
3706
3707    blk = blk_by_name(device);
3708    if (!blk) {
3709        goto notfound;
3710    }
3711
3712    *aio_context = blk_get_aio_context(blk);
3713    aio_context_acquire(*aio_context);
3714
3715    if (!blk_is_available(blk)) {
3716        goto notfound;
3717    }
3718    bs = blk_bs(blk);
3719
3720    if (!bs->job) {
3721        goto notfound;
3722    }
3723
3724    return bs->job;
3725
3726notfound:
3727    error_set(errp, ERROR_CLASS_DEVICE_NOT_ACTIVE,
3728              "No active block job on device '%s'", device);
3729    if (*aio_context) {
3730        aio_context_release(*aio_context);
3731        *aio_context = NULL;
3732    }
3733    return NULL;
3734}
3735
3736void qmp_block_job_set_speed(const char *device, int64_t speed, Error **errp)
3737{
3738    AioContext *aio_context;
3739    BlockJob *job = find_block_job(device, &aio_context, errp);
3740
3741    if (!job) {
3742        return;
3743    }
3744
3745    block_job_set_speed(job, speed, errp);
3746    aio_context_release(aio_context);
3747}
3748
3749void qmp_block_job_cancel(const char *device,
3750                          bool has_force, bool force, Error **errp)
3751{
3752    AioContext *aio_context;
3753    BlockJob *job = find_block_job(device, &aio_context, errp);
3754
3755    if (!job) {
3756        return;
3757    }
3758
3759    if (!has_force) {
3760        force = false;
3761    }
3762
3763    if (job->user_paused && !force) {
3764        error_setg(errp, "The block job for device '%s' is currently paused",
3765                   device);
3766        goto out;
3767    }
3768
3769    trace_qmp_block_job_cancel(job);
3770    block_job_cancel(job);
3771out:
3772    aio_context_release(aio_context);
3773}
3774
3775void qmp_block_job_pause(const char *device, Error **errp)
3776{
3777    AioContext *aio_context;
3778    BlockJob *job = find_block_job(device, &aio_context, errp);
3779
3780    if (!job || job->user_paused) {
3781        return;
3782    }
3783
3784    job->user_paused = true;
3785    trace_qmp_block_job_pause(job);
3786    block_job_pause(job);
3787    aio_context_release(aio_context);
3788}
3789
3790void qmp_block_job_resume(const char *device, Error **errp)
3791{
3792    AioContext *aio_context;
3793    BlockJob *job = find_block_job(device, &aio_context, errp);
3794
3795    if (!job || !job->user_paused) {
3796        return;
3797    }
3798
3799    job->user_paused = false;
3800    trace_qmp_block_job_resume(job);
3801    block_job_resume(job);
3802    aio_context_release(aio_context);
3803}
3804
3805void qmp_block_job_complete(const char *device, Error **errp)
3806{
3807    AioContext *aio_context;
3808    BlockJob *job = find_block_job(device, &aio_context, errp);
3809
3810    if (!job) {
3811        return;
3812    }
3813
3814    trace_qmp_block_job_complete(job);
3815    block_job_complete(job, errp);
3816    aio_context_release(aio_context);
3817}
3818
3819void qmp_change_backing_file(const char *device,
3820                             const char *image_node_name,
3821                             const char *backing_file,
3822                             Error **errp)
3823{
3824    BlockBackend *blk;
3825    BlockDriverState *bs = NULL;
3826    AioContext *aio_context;
3827    BlockDriverState *image_bs = NULL;
3828    Error *local_err = NULL;
3829    bool ro;
3830    int open_flags;
3831    int ret;
3832
3833    blk = blk_by_name(device);
3834    if (!blk) {
3835        error_set(errp, ERROR_CLASS_DEVICE_NOT_FOUND,
3836                  "Device '%s' not found", device);
3837        return;
3838    }
3839
3840    aio_context = blk_get_aio_context(blk);
3841    aio_context_acquire(aio_context);
3842
3843    if (!blk_is_available(blk)) {
3844        error_setg(errp, "Device '%s' has no medium", device);
3845        goto out;
3846    }
3847    bs = blk_bs(blk);
3848
3849    image_bs = bdrv_lookup_bs(NULL, image_node_name, &local_err);
3850    if (local_err) {
3851        error_propagate(errp, local_err);
3852        goto out;
3853    }
3854
3855    if (!image_bs) {
3856        error_setg(errp, "image file not found");
3857        goto out;
3858    }
3859
3860    if (bdrv_find_base(image_bs) == image_bs) {
3861        error_setg(errp, "not allowing backing file change on an image "
3862                         "without a backing file");
3863        goto out;
3864    }
3865
3866    /* even though we are not necessarily operating on bs, we need it to
3867     * determine if block ops are currently prohibited on the chain */
3868    if (bdrv_op_is_blocked(bs, BLOCK_OP_TYPE_CHANGE, errp)) {
3869        goto out;
3870    }
3871
3872    /* final sanity check */
3873    if (!bdrv_chain_contains(bs, image_bs)) {
3874        error_setg(errp, "'%s' and image file are not in the same chain",
3875                   device);
3876        goto out;
3877    }
3878
3879    /* if not r/w, reopen to make r/w */
3880    open_flags = image_bs->open_flags;
3881    ro = bdrv_is_read_only(image_bs);
3882
3883    if (ro) {
3884        bdrv_reopen(image_bs, open_flags | BDRV_O_RDWR, &local_err);
3885        if (local_err) {
3886            error_propagate(errp, local_err);
3887            goto out;
3888        }
3889    }
3890
3891    ret = bdrv_change_backing_file(image_bs, backing_file,
3892                               image_bs->drv ? image_bs->drv->format_name : "");
3893
3894    if (ret < 0) {
3895        error_setg_errno(errp, -ret, "Could not change backing file to '%s'",
3896                         backing_file);
3897        /* don't exit here, so we can try to restore open flags if
3898         * appropriate */
3899    }
3900
3901    if (ro) {
3902        bdrv_reopen(image_bs, open_flags, &local_err);
3903        if (local_err) {
3904            error_propagate(errp, local_err); /* will preserve prior errp */
3905        }
3906    }
3907
3908out:
3909    aio_context_release(aio_context);
3910}
3911
3912void hmp_drive_add_node(Monitor *mon, const char *optstr)
3913{
3914    QemuOpts *opts;
3915    QDict *qdict;
3916    Error *local_err = NULL;
3917
3918    opts = qemu_opts_parse_noisily(&qemu_drive_opts, optstr, false);
3919    if (!opts) {
3920        return;
3921    }
3922
3923    qdict = qemu_opts_to_qdict(opts, NULL);
3924
3925    if (!qdict_get_try_str(qdict, "node-name")) {
3926        QDECREF(qdict);
3927        error_report("'node-name' needs to be specified");
3928        goto out;
3929    }
3930
3931    BlockDriverState *bs = bds_tree_init(qdict, &local_err);
3932    if (!bs) {
3933        error_report_err(local_err);
3934        goto out;
3935    }
3936
3937    QTAILQ_INSERT_TAIL(&monitor_bdrv_states, bs, monitor_list);
3938
3939out:
3940    qemu_opts_del(opts);
3941}
3942
3943void qmp_blockdev_add(BlockdevOptions *options, Error **errp)
3944{
3945    QmpOutputVisitor *ov = qmp_output_visitor_new();
3946    BlockDriverState *bs;
3947    BlockBackend *blk = NULL;
3948    QObject *obj;
3949    QDict *qdict;
3950    Error *local_err = NULL;
3951
3952    /* TODO Sort it out in raw-posix and drive_new(): Reject aio=native with
3953     * cache.direct=false instead of silently switching to aio=threads, except
3954     * when called from drive_new().
3955     *
3956     * For now, simply forbidding the combination for all drivers will do. */
3957    if (options->has_aio && options->aio == BLOCKDEV_AIO_OPTIONS_NATIVE) {
3958        bool direct = options->has_cache &&
3959                      options->cache->has_direct &&
3960                      options->cache->direct;
3961        if (!direct) {
3962            error_setg(errp, "aio=native requires cache.direct=true");
3963            goto fail;
3964        }
3965    }
3966
3967    visit_type_BlockdevOptions(qmp_output_get_visitor(ov), NULL, &options,
3968                               &local_err);
3969    if (local_err) {
3970        error_propagate(errp, local_err);
3971        goto fail;
3972    }
3973
3974    obj = qmp_output_get_qobject(ov);
3975    qdict = qobject_to_qdict(obj);
3976
3977    qdict_flatten(qdict);
3978
3979    if (options->has_id) {
3980        blk = blockdev_init(NULL, qdict, &local_err);
3981        if (local_err) {
3982            error_propagate(errp, local_err);
3983            goto fail;
3984        }
3985
3986        bs = blk_bs(blk);
3987    } else {
3988        if (!qdict_get_try_str(qdict, "node-name")) {
3989            error_setg(errp, "'id' and/or 'node-name' need to be specified for "
3990                       "the root node");
3991            goto fail;
3992        }
3993
3994        bs = bds_tree_init(qdict, errp);
3995        if (!bs) {
3996            goto fail;
3997        }
3998
3999        QTAILQ_INSERT_TAIL(&monitor_bdrv_states, bs, monitor_list);
4000    }
4001
4002    if (bs && bdrv_key_required(bs)) {
4003        if (blk) {
4004            monitor_remove_blk(blk);
4005            blk_unref(blk);
4006        } else {
4007            QTAILQ_REMOVE(&monitor_bdrv_states, bs, monitor_list);
4008            bdrv_unref(bs);
4009        }
4010        error_setg(errp, "blockdev-add doesn't support encrypted devices");
4011        goto fail;
4012    }
4013
4014fail:
4015    qmp_output_visitor_cleanup(ov);
4016}
4017
4018void qmp_x_blockdev_del(bool has_id, const char *id,
4019                        bool has_node_name, const char *node_name, Error **errp)
4020{
4021    AioContext *aio_context;
4022    BlockBackend *blk;
4023    BlockDriverState *bs;
4024
4025    if (has_id && has_node_name) {
4026        error_setg(errp, "Only one of id and node-name must be specified");
4027        return;
4028    } else if (!has_id && !has_node_name) {
4029        error_setg(errp, "No block device specified");
4030        return;
4031    }
4032
4033    if (has_id) {
4034        /* blk_by_name() never returns a BB that is not owned by the monitor */
4035        blk = blk_by_name(id);
4036        if (!blk) {
4037            error_setg(errp, "Cannot find block backend %s", id);
4038            return;
4039        }
4040        if (blk_legacy_dinfo(blk)) {
4041            error_setg(errp, "Deleting block backend added with drive-add"
4042                       " is not supported");
4043            return;
4044        }
4045        if (blk_get_refcnt(blk) > 1) {
4046            error_setg(errp, "Block backend %s is in use", id);
4047            return;
4048        }
4049        bs = blk_bs(blk);
4050        aio_context = blk_get_aio_context(blk);
4051    } else {
4052        bs = bdrv_find_node(node_name);
4053        if (!bs) {
4054            error_setg(errp, "Cannot find node %s", node_name);
4055            return;
4056        }
4057        blk = bs->blk;
4058        if (blk) {
4059            error_setg(errp, "Node %s is in use by %s",
4060                       node_name, blk_name(blk));
4061            return;
4062        }
4063        aio_context = bdrv_get_aio_context(bs);
4064    }
4065
4066    aio_context_acquire(aio_context);
4067
4068    if (bs) {
4069        if (bdrv_op_is_blocked(bs, BLOCK_OP_TYPE_DRIVE_DEL, errp)) {
4070            goto out;
4071        }
4072
4073        if (!blk && !bs->monitor_list.tqe_prev) {
4074            error_setg(errp, "Node %s is not owned by the monitor",
4075                       bs->node_name);
4076            goto out;
4077        }
4078
4079        if (bs->refcnt > 1) {
4080            error_setg(errp, "Block device %s is in use",
4081                       bdrv_get_device_or_node_name(bs));
4082            goto out;
4083        }
4084    }
4085
4086    if (blk) {
4087        monitor_remove_blk(blk);
4088        blk_unref(blk);
4089    } else {
4090        QTAILQ_REMOVE(&monitor_bdrv_states, bs, monitor_list);
4091        bdrv_unref(bs);
4092    }
4093
4094out:
4095    aio_context_release(aio_context);
4096}
4097
4098BlockJobInfoList *qmp_query_block_jobs(Error **errp)
4099{
4100    BlockJobInfoList *head = NULL, **p_next = &head;
4101    BlockDriverState *bs;
4102
4103    for (bs = bdrv_next(NULL); bs; bs = bdrv_next(bs)) {
4104        AioContext *aio_context = bdrv_get_aio_context(bs);
4105
4106        aio_context_acquire(aio_context);
4107
4108        if (bs->job) {
4109            BlockJobInfoList *elem = g_new0(BlockJobInfoList, 1);
4110            elem->value = block_job_query(bs->job);
4111            *p_next = elem;
4112            p_next = &elem->next;
4113        }
4114
4115        aio_context_release(aio_context);
4116    }
4117
4118    return head;
4119}
4120
4121QemuOptsList qemu_common_drive_opts = {
4122    .name = "drive",
4123    .head = QTAILQ_HEAD_INITIALIZER(qemu_common_drive_opts.head),
4124    .desc = {
4125        {
4126            .name = "snapshot",
4127            .type = QEMU_OPT_BOOL,
4128            .help = "enable/disable snapshot mode",
4129        },{
4130            .name = "discard",
4131            .type = QEMU_OPT_STRING,
4132            .help = "discard operation (ignore/off, unmap/on)",
4133        },{
4134            .name = "aio",
4135            .type = QEMU_OPT_STRING,
4136            .help = "host AIO implementation (threads, native)",
4137        },{
4138            .name = BDRV_OPT_CACHE_WB,
4139            .type = QEMU_OPT_BOOL,
4140            .help = "Enable writeback mode",
4141        },{
4142            .name = "format",
4143            .type = QEMU_OPT_STRING,
4144            .help = "disk format (raw, qcow2, ...)",
4145        },{
4146            .name = "rerror",
4147            .type = QEMU_OPT_STRING,
4148            .help = "read error action",
4149        },{
4150            .name = "werror",
4151            .type = QEMU_OPT_STRING,
4152            .help = "write error action",
4153        },{
4154            .name = "read-only",
4155            .type = QEMU_OPT_BOOL,
4156            .help = "open drive file as read-only",
4157        },{
4158            .name = "throttling.iops-total",
4159            .type = QEMU_OPT_NUMBER,
4160            .help = "limit total I/O operations per second",
4161        },{
4162            .name = "throttling.iops-read",
4163            .type = QEMU_OPT_NUMBER,
4164            .help = "limit read operations per second",
4165        },{
4166            .name = "throttling.iops-write",
4167            .type = QEMU_OPT_NUMBER,
4168            .help = "limit write operations per second",
4169        },{
4170            .name = "throttling.bps-total",
4171            .type = QEMU_OPT_NUMBER,
4172            .help = "limit total bytes per second",
4173        },{
4174            .name = "throttling.bps-read",
4175            .type = QEMU_OPT_NUMBER,
4176            .help = "limit read bytes per second",
4177        },{
4178            .name = "throttling.bps-write",
4179            .type = QEMU_OPT_NUMBER,
4180            .help = "limit write bytes per second",
4181        },{
4182            .name = "throttling.iops-total-max",
4183            .type = QEMU_OPT_NUMBER,
4184            .help = "I/O operations burst",
4185        },{
4186            .name = "throttling.iops-read-max",
4187            .type = QEMU_OPT_NUMBER,
4188            .help = "I/O operations read burst",
4189        },{
4190            .name = "throttling.iops-write-max",
4191            .type = QEMU_OPT_NUMBER,
4192            .help = "I/O operations write burst",
4193        },{
4194            .name = "throttling.bps-total-max",
4195            .type = QEMU_OPT_NUMBER,
4196            .help = "total bytes burst",
4197        },{
4198            .name = "throttling.bps-read-max",
4199            .type = QEMU_OPT_NUMBER,
4200            .help = "total bytes read burst",
4201        },{
4202            .name = "throttling.bps-write-max",
4203            .type = QEMU_OPT_NUMBER,
4204            .help = "total bytes write burst",
4205        },{
4206            .name = "throttling.iops-total-max-length",
4207            .type = QEMU_OPT_NUMBER,
4208            .help = "length of the iops-total-max burst period, in seconds",
4209        },{
4210            .name = "throttling.iops-read-max-length",
4211            .type = QEMU_OPT_NUMBER,
4212            .help = "length of the iops-read-max burst period, in seconds",
4213        },{
4214            .name = "throttling.iops-write-max-length",
4215            .type = QEMU_OPT_NUMBER,
4216            .help = "length of the iops-write-max burst period, in seconds",
4217        },{
4218            .name = "throttling.bps-total-max-length",
4219            .type = QEMU_OPT_NUMBER,
4220            .help = "length of the bps-total-max burst period, in seconds",
4221        },{
4222            .name = "throttling.bps-read-max-length",
4223            .type = QEMU_OPT_NUMBER,
4224            .help = "length of the bps-read-max burst period, in seconds",
4225        },{
4226            .name = "throttling.bps-write-max-length",
4227            .type = QEMU_OPT_NUMBER,
4228            .help = "length of the bps-write-max burst period, in seconds",
4229        },{
4230            .name = "throttling.iops-size",
4231            .type = QEMU_OPT_NUMBER,
4232            .help = "when limiting by iops max size of an I/O in bytes",
4233        },{
4234            .name = "throttling.group",
4235            .type = QEMU_OPT_STRING,
4236            .help = "name of the block throttling group",
4237        },{
4238            .name = "copy-on-read",
4239            .type = QEMU_OPT_BOOL,
4240            .help = "copy read data from backing file into image file",
4241        },{
4242            .name = "detect-zeroes",
4243            .type = QEMU_OPT_STRING,
4244            .help = "try to optimize zero writes (off, on, unmap)",
4245        },{
4246            .name = "stats-account-invalid",
4247            .type = QEMU_OPT_BOOL,
4248            .help = "whether to account for invalid I/O operations "
4249                    "in the statistics",
4250        },{
4251            .name = "stats-account-failed",
4252            .type = QEMU_OPT_BOOL,
4253            .help = "whether to account for failed I/O operations "
4254                    "in the statistics",
4255        },
4256        { /* end of list */ }
4257    },
4258};
4259
4260static QemuOptsList qemu_root_bds_opts = {
4261    .name = "root-bds",
4262    .head = QTAILQ_HEAD_INITIALIZER(qemu_root_bds_opts.head),
4263    .desc = {
4264        {
4265            .name = "discard",
4266            .type = QEMU_OPT_STRING,
4267            .help = "discard operation (ignore/off, unmap/on)",
4268        },{
4269            .name = "aio",
4270            .type = QEMU_OPT_STRING,
4271            .help = "host AIO implementation (threads, native)",
4272        },{
4273            .name = "read-only",
4274            .type = QEMU_OPT_BOOL,
4275            .help = "open drive file as read-only",
4276        },{
4277            .name = "copy-on-read",
4278            .type = QEMU_OPT_BOOL,
4279            .help = "copy read data from backing file into image file",
4280        },{
4281            .name = "detect-zeroes",
4282            .type = QEMU_OPT_STRING,
4283            .help = "try to optimize zero writes (off, on, unmap)",
4284        },
4285        { /* end of list */ }
4286    },
4287};
4288
4289QemuOptsList qemu_drive_opts = {
4290    .name = "drive",
4291    .head = QTAILQ_HEAD_INITIALIZER(qemu_drive_opts.head),
4292    .desc = {
4293        /*
4294         * no elements => accept any params
4295         * validation will happen later
4296         */
4297        { /* end of list */ }
4298    },
4299};
4300