2 * QEMU host block devices
4 * Copyright (c) 2003-2008 Fabrice Bellard
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.
9 * This file incorporates work covered by the following copyright and
12 * Copyright (c) 2003-2008 Fabrice Bellard
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:
21 * The above copyright notice and this permission notice shall be included in
22 * all copies or substantial portions of the Software.
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
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"
52 #include "sysemu/arch_init.h"
53 #include "qemu/cutils.h"
54 #include "qemu/help_option.h"
56 static QTAILQ_HEAD(, BlockDriverState) monitor_bdrv_states =
57 QTAILQ_HEAD_INITIALIZER(monitor_bdrv_states);
60 #include "tizen/src/util/exported_strings.h"
63 static const char *const if_name[IF_COUNT] = {
67 [IF_FLOPPY] = "floppy",
68 [IF_PFLASH] = "pflash",
71 [IF_VIRTIO] = "virtio",
75 static int if_max_devs[IF_COUNT] = {
77 * Do not change these numbers! They govern how drive option
78 * index maps to unit and bus. That mapping is ABI.
80 * All controllers used to imlement if=T drives need to support
81 * if_max_devs[T] units, for any T with if_max_devs[T] != 0.
82 * Otherwise, some index values map to "impossible" bus, unit
85 * For instance, if you change [IF_SCSI] to 255, -drive
86 * if=scsi,index=12 no longer means bus=1,unit=5, but
87 * bus=0,unit=12. With an lsi53c895a controller (7 units max),
88 * the drive can't be set up. Regression.
95 * Boards may call this to offer board-by-board overrides
96 * of the default, global values.
98 void override_max_devs(BlockInterfaceType type, int max_devs)
107 for (blk = blk_next(NULL); blk; blk = blk_next(blk)) {
108 dinfo = blk_legacy_dinfo(blk);
109 if (dinfo->type == type) {
110 fprintf(stderr, "Cannot override units-per-bus property of"
111 " the %s interface, because a drive of that type has"
112 " already been added.\n", if_name[type]);
113 g_assert_not_reached();
117 if_max_devs[type] = max_devs;
121 * We automatically delete the drive when a device using it gets
122 * unplugged. Questionable feature, but we can't just drop it.
123 * Device models call blockdev_mark_auto_del() to schedule the
124 * automatic deletion, and generic qdev code calls blockdev_auto_del()
125 * when deletion is actually safe.
127 void blockdev_mark_auto_del(BlockBackend *blk)
129 DriveInfo *dinfo = blk_legacy_dinfo(blk);
130 BlockDriverState *bs = blk_bs(blk);
131 AioContext *aio_context;
138 aio_context = bdrv_get_aio_context(bs);
139 aio_context_acquire(aio_context);
142 block_job_cancel(bs->job);
145 aio_context_release(aio_context);
151 void blockdev_auto_del(BlockBackend *blk)
153 DriveInfo *dinfo = blk_legacy_dinfo(blk);
155 if (dinfo && dinfo->auto_del) {
156 monitor_remove_blk(blk);
162 * Returns the current mapping of how many units per bus
163 * a particular interface can support.
165 * A positive integer indicates n units per bus.
166 * 0 implies the mapping has not been established.
167 * -1 indicates an invalid BlockInterfaceType was given.
169 int drive_get_max_devs(BlockInterfaceType type)
171 if (type >= IF_IDE && type < IF_COUNT) {
172 return if_max_devs[type];
178 static int drive_index_to_bus_id(BlockInterfaceType type, int index)
180 int max_devs = if_max_devs[type];
181 return max_devs ? index / max_devs : 0;
184 static int drive_index_to_unit_id(BlockInterfaceType type, int index)
186 int max_devs = if_max_devs[type];
187 return max_devs ? index % max_devs : index;
190 QemuOpts *drive_def(const char *optstr)
192 return qemu_opts_parse_noisily(qemu_find_opts("drive"), optstr, false);
195 QemuOpts *drive_add(BlockInterfaceType type, int index, const char *file,
200 opts = drive_def(optstr);
204 if (type != IF_DEFAULT) {
205 qemu_opt_set(opts, "if", if_name[type], &error_abort);
208 qemu_opt_set_number(opts, "index", index, &error_abort);
211 qemu_opt_set(opts, "file", file, &error_abort);
215 DriveInfo *drive_get(BlockInterfaceType type, int bus, int unit)
220 for (blk = blk_next(NULL); blk; blk = blk_next(blk)) {
221 dinfo = blk_legacy_dinfo(blk);
222 if (dinfo && dinfo->type == type
223 && dinfo->bus == bus && dinfo->unit == unit) {
231 bool drive_check_orphaned(void)
237 for (blk = blk_next(NULL); blk; blk = blk_next(blk)) {
238 dinfo = blk_legacy_dinfo(blk);
239 /* If dinfo->bdrv->dev is NULL, it has no device attached. */
240 /* Unless this is a default drive, this may be an oversight. */
241 if (!blk_get_attached_dev(blk) && !dinfo->is_default &&
242 dinfo->type != IF_NONE) {
243 fprintf(stderr, "Warning: Orphaned drive without device: "
244 "id=%s,file=%s,if=%s,bus=%d,unit=%d\n",
245 blk_name(blk), blk_bs(blk) ? blk_bs(blk)->filename : "",
246 if_name[dinfo->type], dinfo->bus, dinfo->unit);
254 DriveInfo *drive_get_by_index(BlockInterfaceType type, int index)
256 return drive_get(type,
257 drive_index_to_bus_id(type, index),
258 drive_index_to_unit_id(type, index));
261 int drive_get_max_bus(BlockInterfaceType type)
268 for (blk = blk_next(NULL); blk; blk = blk_next(blk)) {
269 dinfo = blk_legacy_dinfo(blk);
270 if (dinfo && dinfo->type == type && dinfo->bus > max_bus) {
271 max_bus = dinfo->bus;
277 /* Get a block device. This should only be used for single-drive devices
278 (e.g. SD/Floppy/MTD). Multi-disk devices (scsi/ide) should use the
280 DriveInfo *drive_get_next(BlockInterfaceType type)
282 static int next_block_unit[IF_COUNT];
284 return drive_get(type, 0, next_block_unit[type]++);
287 static void bdrv_format_print(void *opaque, const char *name)
289 error_printf(" %s", name);
294 BlockDriverState *bs;
297 static int parse_block_error_action(const char *buf, bool is_read, Error **errp)
299 if (!strcmp(buf, "ignore")) {
300 return BLOCKDEV_ON_ERROR_IGNORE;
301 } else if (!is_read && !strcmp(buf, "enospc")) {
302 return BLOCKDEV_ON_ERROR_ENOSPC;
303 } else if (!strcmp(buf, "stop")) {
304 return BLOCKDEV_ON_ERROR_STOP;
305 } else if (!strcmp(buf, "report")) {
306 return BLOCKDEV_ON_ERROR_REPORT;
308 error_setg(errp, "'%s' invalid %s error action",
309 buf, is_read ? "read" : "write");
314 static bool parse_stats_intervals(BlockAcctStats *stats, QList *intervals,
317 const QListEntry *entry;
318 for (entry = qlist_first(intervals); entry; entry = qlist_next(entry)) {
319 switch (qobject_type(entry->value)) {
321 case QTYPE_QSTRING: {
322 unsigned long long length;
323 const char *str = qstring_get_str(qobject_to_qstring(entry->value));
324 if (parse_uint_full(str, &length, 10) == 0 &&
325 length > 0 && length <= UINT_MAX) {
326 block_acct_add_interval(stats, (unsigned) length);
328 error_setg(errp, "Invalid interval length: %s", str);
335 int64_t length = qint_get_int(qobject_to_qint(entry->value));
336 if (length > 0 && length <= UINT_MAX) {
337 block_acct_add_interval(stats, (unsigned) length);
339 error_setg(errp, "Invalid interval length: %" PRId64, length);
346 error_setg(errp, "The specification of stats-intervals is invalid");
353 typedef enum { MEDIA_DISK, MEDIA_CDROM } DriveMediaType;
355 /* All parameters but @opts are optional and may be set to NULL. */
356 static void extract_common_blockdev_options(QemuOpts *opts, int *bdrv_flags,
357 const char **throttling_group, ThrottleConfig *throttle_cfg,
358 BlockdevDetectZeroesOptions *detect_zeroes, Error **errp)
361 Error *local_error = NULL;
365 if (!qemu_opt_get_bool(opts, "read-only", false)) {
366 *bdrv_flags |= BDRV_O_RDWR;
368 if (qemu_opt_get_bool(opts, "copy-on-read", false)) {
369 *bdrv_flags |= BDRV_O_COPY_ON_READ;
372 if ((discard = qemu_opt_get(opts, "discard")) != NULL) {
373 if (bdrv_parse_discard_flags(discard, bdrv_flags) != 0) {
374 error_setg(errp, "Invalid discard option");
379 if ((aio = qemu_opt_get(opts, "aio")) != NULL) {
380 if (!strcmp(aio, "native")) {
381 *bdrv_flags |= BDRV_O_NATIVE_AIO;
382 } else if (!strcmp(aio, "threads")) {
383 /* this is the default */
385 error_setg(errp, "invalid aio option");
391 /* disk I/O throttling */
392 if (throttling_group) {
393 *throttling_group = qemu_opt_get(opts, "throttling.group");
397 throttle_config_init(throttle_cfg);
398 throttle_cfg->buckets[THROTTLE_BPS_TOTAL].avg =
399 qemu_opt_get_number(opts, "throttling.bps-total", 0);
400 throttle_cfg->buckets[THROTTLE_BPS_READ].avg =
401 qemu_opt_get_number(opts, "throttling.bps-read", 0);
402 throttle_cfg->buckets[THROTTLE_BPS_WRITE].avg =
403 qemu_opt_get_number(opts, "throttling.bps-write", 0);
404 throttle_cfg->buckets[THROTTLE_OPS_TOTAL].avg =
405 qemu_opt_get_number(opts, "throttling.iops-total", 0);
406 throttle_cfg->buckets[THROTTLE_OPS_READ].avg =
407 qemu_opt_get_number(opts, "throttling.iops-read", 0);
408 throttle_cfg->buckets[THROTTLE_OPS_WRITE].avg =
409 qemu_opt_get_number(opts, "throttling.iops-write", 0);
411 throttle_cfg->buckets[THROTTLE_BPS_TOTAL].max =
412 qemu_opt_get_number(opts, "throttling.bps-total-max", 0);
413 throttle_cfg->buckets[THROTTLE_BPS_READ].max =
414 qemu_opt_get_number(opts, "throttling.bps-read-max", 0);
415 throttle_cfg->buckets[THROTTLE_BPS_WRITE].max =
416 qemu_opt_get_number(opts, "throttling.bps-write-max", 0);
417 throttle_cfg->buckets[THROTTLE_OPS_TOTAL].max =
418 qemu_opt_get_number(opts, "throttling.iops-total-max", 0);
419 throttle_cfg->buckets[THROTTLE_OPS_READ].max =
420 qemu_opt_get_number(opts, "throttling.iops-read-max", 0);
421 throttle_cfg->buckets[THROTTLE_OPS_WRITE].max =
422 qemu_opt_get_number(opts, "throttling.iops-write-max", 0);
424 throttle_cfg->buckets[THROTTLE_BPS_TOTAL].burst_length =
425 qemu_opt_get_number(opts, "throttling.bps-total-max-length", 1);
426 throttle_cfg->buckets[THROTTLE_BPS_READ].burst_length =
427 qemu_opt_get_number(opts, "throttling.bps-read-max-length", 1);
428 throttle_cfg->buckets[THROTTLE_BPS_WRITE].burst_length =
429 qemu_opt_get_number(opts, "throttling.bps-write-max-length", 1);
430 throttle_cfg->buckets[THROTTLE_OPS_TOTAL].burst_length =
431 qemu_opt_get_number(opts, "throttling.iops-total-max-length", 1);
432 throttle_cfg->buckets[THROTTLE_OPS_READ].burst_length =
433 qemu_opt_get_number(opts, "throttling.iops-read-max-length", 1);
434 throttle_cfg->buckets[THROTTLE_OPS_WRITE].burst_length =
435 qemu_opt_get_number(opts, "throttling.iops-write-max-length", 1);
437 throttle_cfg->op_size =
438 qemu_opt_get_number(opts, "throttling.iops-size", 0);
440 if (!throttle_is_valid(throttle_cfg, errp)) {
447 qapi_enum_parse(BlockdevDetectZeroesOptions_lookup,
448 qemu_opt_get(opts, "detect-zeroes"),
449 BLOCKDEV_DETECT_ZEROES_OPTIONS__MAX,
450 BLOCKDEV_DETECT_ZEROES_OPTIONS_OFF,
453 error_propagate(errp, local_error);
458 *detect_zeroes == BLOCKDEV_DETECT_ZEROES_OPTIONS_UNMAP &&
459 !(*bdrv_flags & BDRV_O_UNMAP))
461 error_setg(errp, "setting detect-zeroes to unmap is not allowed "
462 "without setting discard operation to unmap");
468 /* Takes the ownership of bs_opts */
469 static BlockBackend *blockdev_init(const char *file, QDict *bs_opts,
474 int on_read_error, on_write_error;
475 bool account_invalid, account_failed;
478 BlockDriverState *bs;
483 QDict *interval_dict = NULL;
484 QList *interval_list = NULL;
486 BlockdevDetectZeroesOptions detect_zeroes =
487 BLOCKDEV_DETECT_ZEROES_OPTIONS_OFF;
488 const char *throttling_group = NULL;
490 /* Check common options by copying from bs_opts to opts, all other options
491 * stay in bs_opts for processing by bdrv_open(). */
492 id = qdict_get_try_str(bs_opts, "id");
493 opts = qemu_opts_create(&qemu_common_drive_opts, id, 1, &error);
495 error_propagate(errp, error);
499 qemu_opts_absorb_qdict(opts, bs_opts, &error);
501 error_propagate(errp, error);
506 qdict_del(bs_opts, "id");
509 /* extract parameters */
510 snapshot = qemu_opt_get_bool(opts, "snapshot", 0);
512 account_invalid = qemu_opt_get_bool(opts, "stats-account-invalid", true);
513 account_failed = qemu_opt_get_bool(opts, "stats-account-failed", true);
515 writethrough = !qemu_opt_get_bool(opts, BDRV_OPT_CACHE_WB, true);
517 qdict_extract_subqdict(bs_opts, &interval_dict, "stats-intervals.");
518 qdict_array_split(interval_dict, &interval_list);
520 if (qdict_size(interval_dict) != 0) {
521 error_setg(errp, "Invalid option stats-intervals.%s",
522 qdict_first(interval_dict)->key);
526 extract_common_blockdev_options(opts, &bdrv_flags, &throttling_group, &cfg,
527 &detect_zeroes, &error);
529 error_propagate(errp, error);
533 if ((buf = qemu_opt_get(opts, "format")) != NULL) {
534 if (is_help_option(buf)) {
535 error_printf("Supported formats:");
536 bdrv_iterate_format(bdrv_format_print, NULL);
541 if (qdict_haskey(bs_opts, "driver")) {
542 error_setg(errp, "Cannot specify both 'driver' and 'format'");
545 qdict_put(bs_opts, "driver", qstring_from_str(buf));
548 on_write_error = BLOCKDEV_ON_ERROR_ENOSPC;
549 if ((buf = qemu_opt_get(opts, "werror")) != NULL) {
550 on_write_error = parse_block_error_action(buf, 0, &error);
552 error_propagate(errp, error);
557 on_read_error = BLOCKDEV_ON_ERROR_REPORT;
558 if ((buf = qemu_opt_get(opts, "rerror")) != NULL) {
559 on_read_error = parse_block_error_action(buf, 1, &error);
561 error_propagate(errp, error);
567 bdrv_flags |= BDRV_O_SNAPSHOT;
571 if ((!file || !*file) && !qdict_size(bs_opts)) {
572 BlockBackendRootState *blk_rs;
579 blk_rs = blk_get_root_state(blk);
580 blk_rs->open_flags = bdrv_flags;
581 blk_rs->read_only = !(bdrv_flags & BDRV_O_RDWR);
582 blk_rs->detect_zeroes = detect_zeroes;
584 if (throttle_enabled(&cfg)) {
585 if (!throttling_group) {
586 throttling_group = blk_name(blk);
588 blk_rs->throttle_group = g_strdup(throttling_group);
589 blk_rs->throttle_state = throttle_group_incref(throttling_group);
590 blk_rs->throttle_state->cfg = cfg;
595 if (file && !*file) {
599 /* bdrv_open() defaults to the values in bdrv_flags (for compatibility
600 * with other callers) rather than what we want as the real defaults.
601 * Apply the defaults here instead. */
602 qdict_set_default_str(bs_opts, BDRV_OPT_CACHE_DIRECT, "off");
603 qdict_set_default_str(bs_opts, BDRV_OPT_CACHE_NO_FLUSH, "off");
604 assert((bdrv_flags & BDRV_O_CACHE_MASK) == 0);
606 if (runstate_check(RUN_STATE_INMIGRATE)) {
607 bdrv_flags |= BDRV_O_INACTIVE;
610 blk = blk_new_open(file, NULL, bs_opts, bdrv_flags, errp);
616 bs->detect_zeroes = detect_zeroes;
618 /* disk I/O throttling */
619 if (throttle_enabled(&cfg)) {
620 if (!throttling_group) {
621 throttling_group = blk_name(blk);
623 bdrv_io_limits_enable(bs, throttling_group);
624 bdrv_set_io_limits(bs, &cfg);
627 if (bdrv_key_required(bs)) {
631 block_acct_init(blk_get_stats(blk), account_invalid, account_failed);
633 if (!parse_stats_intervals(blk_get_stats(blk), interval_list, errp)) {
640 blk_set_enable_write_cache(blk, !writethrough);
641 blk_set_on_error(blk, on_read_error, on_write_error);
643 if (!monitor_add_blk(blk, qemu_opts_id(opts), errp)) {
651 QDECREF(interval_dict);
652 QDECREF(interval_list);
657 QDECREF(interval_dict);
658 QDECREF(interval_list);
664 static QemuOptsList qemu_root_bds_opts;
666 /* Takes the ownership of bs_opts */
667 static BlockDriverState *bds_tree_init(QDict *bs_opts, Error **errp)
669 BlockDriverState *bs;
671 Error *local_error = NULL;
672 BlockdevDetectZeroesOptions detect_zeroes;
676 opts = qemu_opts_create(&qemu_root_bds_opts, NULL, 1, errp);
681 qemu_opts_absorb_qdict(opts, bs_opts, &local_error);
683 error_propagate(errp, local_error);
687 extract_common_blockdev_options(opts, &bdrv_flags, NULL, NULL,
688 &detect_zeroes, &local_error);
690 error_propagate(errp, local_error);
694 /* bdrv_open() defaults to the values in bdrv_flags (for compatibility
695 * with other callers) rather than what we want as the real defaults.
696 * Apply the defaults here instead. */
697 qdict_set_default_str(bs_opts, BDRV_OPT_CACHE_DIRECT, "off");
698 qdict_set_default_str(bs_opts, BDRV_OPT_CACHE_NO_FLUSH, "off");
700 if (runstate_check(RUN_STATE_INMIGRATE)) {
701 bdrv_flags |= BDRV_O_INACTIVE;
705 ret = bdrv_open(&bs, NULL, NULL, bs_opts, bdrv_flags, errp);
707 goto fail_no_bs_opts;
710 bs->detect_zeroes = detect_zeroes;
722 void blockdev_close_all_bdrv_states(void)
724 BlockDriverState *bs, *next_bs;
726 QTAILQ_FOREACH_SAFE(bs, &monitor_bdrv_states, monitor_list, next_bs) {
727 AioContext *ctx = bdrv_get_aio_context(bs);
729 aio_context_acquire(ctx);
731 aio_context_release(ctx);
735 /* Iterates over the list of monitor-owned BlockDriverStates */
736 BlockDriverState *bdrv_next_monitor_owned(BlockDriverState *bs)
738 return bs ? QTAILQ_NEXT(bs, monitor_list)
739 : QTAILQ_FIRST(&monitor_bdrv_states);
742 static void qemu_opt_rename(QemuOpts *opts, const char *from, const char *to,
747 value = qemu_opt_get(opts, from);
749 if (qemu_opt_find(opts, to)) {
750 error_setg(errp, "'%s' and its alias '%s' can't be used at the "
751 "same time", to, from);
756 /* rename all items in opts */
757 while ((value = qemu_opt_get(opts, from))) {
758 qemu_opt_set(opts, to, value, &error_abort);
759 qemu_opt_unset(opts, from);
763 QemuOptsList qemu_legacy_drive_opts = {
765 .head = QTAILQ_HEAD_INITIALIZER(qemu_legacy_drive_opts.head),
769 .type = QEMU_OPT_NUMBER,
770 .help = "bus number",
773 .type = QEMU_OPT_NUMBER,
774 .help = "unit number (i.e. lun for scsi)",
777 .type = QEMU_OPT_NUMBER,
778 .help = "index number",
781 .type = QEMU_OPT_STRING,
782 .help = "media type (disk, cdrom)",
785 .type = QEMU_OPT_STRING,
786 .help = "interface (ide, scsi, sd, mtd, floppy, pflash, virtio)",
789 .type = QEMU_OPT_NUMBER,
790 .help = "number of cylinders (ide disk geometry)",
793 .type = QEMU_OPT_NUMBER,
794 .help = "number of heads (ide disk geometry)",
797 .type = QEMU_OPT_NUMBER,
798 .help = "number of sectors (ide disk geometry)",
801 .type = QEMU_OPT_STRING,
802 .help = "chs translation (auto, lba, none)",
805 .type = QEMU_OPT_BOOL,
806 .help = "(deprecated, ignored)",
809 .type = QEMU_OPT_STRING,
810 .help = "pci address (virtio only)",
813 .type = QEMU_OPT_STRING,
814 .help = "disk serial number",
817 .type = QEMU_OPT_STRING,
821 /* Options that are passed on, but have special semantics with -drive */
824 .type = QEMU_OPT_BOOL,
825 .help = "open drive file as read-only",
828 .type = QEMU_OPT_STRING,
829 .help = "read error action",
832 .type = QEMU_OPT_STRING,
833 .help = "write error action",
835 .name = "copy-on-read",
836 .type = QEMU_OPT_BOOL,
837 .help = "copy read data from backing file into image file",
840 { /* end of list */ }
844 DriveInfo *drive_new(QemuOpts *all_opts, BlockInterfaceType block_default_type)
848 DriveInfo *dinfo = NULL;
850 QemuOpts *legacy_opts;
851 DriveMediaType media = MEDIA_DISK;
852 BlockInterfaceType type;
853 int cyls, heads, secs, translation;
854 int max_devs, bus_id, unit_id, index;
856 const char *werror, *rerror;
857 bool read_only = false;
860 const char *filename;
861 Error *local_err = NULL;
864 /* Change legacy command line options into QMP ones */
865 static const struct {
869 { "iops", "throttling.iops-total" },
870 { "iops_rd", "throttling.iops-read" },
871 { "iops_wr", "throttling.iops-write" },
873 { "bps", "throttling.bps-total" },
874 { "bps_rd", "throttling.bps-read" },
875 { "bps_wr", "throttling.bps-write" },
877 { "iops_max", "throttling.iops-total-max" },
878 { "iops_rd_max", "throttling.iops-read-max" },
879 { "iops_wr_max", "throttling.iops-write-max" },
881 { "bps_max", "throttling.bps-total-max" },
882 { "bps_rd_max", "throttling.bps-read-max" },
883 { "bps_wr_max", "throttling.bps-write-max" },
885 { "iops_size", "throttling.iops-size" },
887 { "group", "throttling.group" },
889 { "readonly", "read-only" },
892 for (i = 0; i < ARRAY_SIZE(opt_renames); i++) {
893 qemu_opt_rename(all_opts, opt_renames[i].from, opt_renames[i].to,
896 error_report_err(local_err);
901 value = qemu_opt_get(all_opts, "cache");
906 if (bdrv_parse_cache_mode(value, &flags, &writethrough) != 0) {
907 error_report("invalid cache option");
911 /* Specific options take precedence */
912 if (!qemu_opt_get(all_opts, BDRV_OPT_CACHE_WB)) {
913 qemu_opt_set_bool(all_opts, BDRV_OPT_CACHE_WB,
914 !writethrough, &error_abort);
916 if (!qemu_opt_get(all_opts, BDRV_OPT_CACHE_DIRECT)) {
917 qemu_opt_set_bool(all_opts, BDRV_OPT_CACHE_DIRECT,
918 !!(flags & BDRV_O_NOCACHE), &error_abort);
920 if (!qemu_opt_get(all_opts, BDRV_OPT_CACHE_NO_FLUSH)) {
921 qemu_opt_set_bool(all_opts, BDRV_OPT_CACHE_NO_FLUSH,
922 !!(flags & BDRV_O_NO_FLUSH), &error_abort);
924 qemu_opt_unset(all_opts, "cache");
927 /* Get a QDict for processing the options */
928 bs_opts = qdict_new();
929 qemu_opts_to_qdict(all_opts, bs_opts);
931 legacy_opts = qemu_opts_create(&qemu_legacy_drive_opts, NULL, 0,
933 qemu_opts_absorb_qdict(legacy_opts, bs_opts, &local_err);
935 error_report_err(local_err);
939 /* Deprecated option boot=[on|off] */
940 if (qemu_opt_get(legacy_opts, "boot") != NULL) {
941 fprintf(stderr, "qemu-kvm: boot=on|off is deprecated and will be "
942 "ignored. Future versions will reject this parameter. Please "
943 "update your scripts.\n");
947 value = qemu_opt_get(legacy_opts, "media");
949 if (!strcmp(value, "disk")) {
951 } else if (!strcmp(value, "cdrom")) {
955 error_report("'%s' invalid media", value);
960 /* copy-on-read is disabled with a warning for read-only devices */
961 read_only |= qemu_opt_get_bool(legacy_opts, "read-only", false);
962 copy_on_read = qemu_opt_get_bool(legacy_opts, "copy-on-read", false);
964 if (read_only && copy_on_read) {
965 error_report("warning: disabling copy-on-read on read-only drive");
966 copy_on_read = false;
969 qdict_put(bs_opts, "read-only",
970 qstring_from_str(read_only ? "on" : "off"));
971 qdict_put(bs_opts, "copy-on-read",
972 qstring_from_str(copy_on_read ? "on" :"off"));
974 /* Controller type */
975 value = qemu_opt_get(legacy_opts, "if");
978 type < IF_COUNT && strcmp(value, if_name[type]);
981 if (type == IF_COUNT) {
982 error_report("unsupported bus type '%s'", value);
986 type = block_default_type;
990 cyls = qemu_opt_get_number(legacy_opts, "cyls", 0);
991 heads = qemu_opt_get_number(legacy_opts, "heads", 0);
992 secs = qemu_opt_get_number(legacy_opts, "secs", 0);
994 if (cyls || heads || secs) {
996 error_report("invalid physical cyls number");
1000 error_report("invalid physical heads number");
1004 error_report("invalid physical secs number");
1009 translation = BIOS_ATA_TRANSLATION_AUTO;
1010 value = qemu_opt_get(legacy_opts, "trans");
1011 if (value != NULL) {
1013 error_report("'%s' trans must be used with cyls, heads and secs",
1017 if (!strcmp(value, "none")) {
1018 translation = BIOS_ATA_TRANSLATION_NONE;
1019 } else if (!strcmp(value, "lba")) {
1020 translation = BIOS_ATA_TRANSLATION_LBA;
1021 } else if (!strcmp(value, "large")) {
1022 translation = BIOS_ATA_TRANSLATION_LARGE;
1023 } else if (!strcmp(value, "rechs")) {
1024 translation = BIOS_ATA_TRANSLATION_RECHS;
1025 } else if (!strcmp(value, "auto")) {
1026 translation = BIOS_ATA_TRANSLATION_AUTO;
1028 error_report("'%s' invalid translation type", value);
1033 if (media == MEDIA_CDROM) {
1034 if (cyls || secs || heads) {
1035 error_report("CHS can't be set with media=cdrom");
1040 /* Device address specified by bus/unit or index.
1041 * If none was specified, try to find the first free one. */
1042 bus_id = qemu_opt_get_number(legacy_opts, "bus", 0);
1043 unit_id = qemu_opt_get_number(legacy_opts, "unit", -1);
1044 index = qemu_opt_get_number(legacy_opts, "index", -1);
1046 max_devs = if_max_devs[type];
1049 if (bus_id != 0 || unit_id != -1) {
1050 error_report("index cannot be used with bus and unit");
1053 bus_id = drive_index_to_bus_id(type, index);
1054 unit_id = drive_index_to_unit_id(type, index);
1057 if (unit_id == -1) {
1059 while (drive_get(type, bus_id, unit_id) != NULL) {
1061 if (max_devs && unit_id >= max_devs) {
1062 unit_id -= max_devs;
1068 if (max_devs && unit_id >= max_devs) {
1069 error_report("unit %d too big (max is %d)", unit_id, max_devs - 1);
1073 if (drive_get(type, bus_id, unit_id) != NULL) {
1074 error_report("drive with bus=%d, unit=%d (index=%d) exists",
1075 bus_id, unit_id, index);
1080 serial = qemu_opt_get(legacy_opts, "serial");
1082 /* no id supplied -> create one */
1083 if (qemu_opts_id(all_opts) == NULL) {
1085 const char *mediastr = "";
1086 if (type == IF_IDE || type == IF_SCSI) {
1087 mediastr = (media == MEDIA_CDROM) ? "-cd" : "-hd";
1090 new_id = g_strdup_printf("%s%i%s%i", if_name[type], bus_id,
1093 new_id = g_strdup_printf("%s%s%i", if_name[type],
1096 qdict_put(bs_opts, "id", qstring_from_str(new_id));
1100 /* Add virtio block device */
1101 devaddr = qemu_opt_get(legacy_opts, "addr");
1102 if (devaddr && type != IF_VIRTIO) {
1103 error_report("addr is not supported by this bus type");
1107 if (type == IF_VIRTIO) {
1109 devopts = qemu_opts_create(qemu_find_opts("device"), NULL, 0,
1111 if (arch_type == QEMU_ARCH_S390X) {
1112 qemu_opt_set(devopts, "driver", "virtio-blk-ccw", &error_abort);
1114 qemu_opt_set(devopts, "driver", "virtio-blk-pci", &error_abort);
1116 qemu_opt_set(devopts, "drive", qdict_get_str(bs_opts, "id"),
1119 qemu_opt_set(devopts, "addr", devaddr, &error_abort);
1123 filename = qemu_opt_get(legacy_opts, "file");
1125 /* Check werror/rerror compatibility with if=... */
1126 werror = qemu_opt_get(legacy_opts, "werror");
1127 if (werror != NULL) {
1128 if (type != IF_IDE && type != IF_SCSI && type != IF_VIRTIO &&
1130 error_report("werror is not supported by this bus type");
1133 qdict_put(bs_opts, "werror", qstring_from_str(werror));
1136 rerror = qemu_opt_get(legacy_opts, "rerror");
1137 if (rerror != NULL) {
1138 if (type != IF_IDE && type != IF_VIRTIO && type != IF_SCSI &&
1140 error_report("rerror is not supported by this bus type");
1143 qdict_put(bs_opts, "rerror", qstring_from_str(rerror));
1146 /* Actual block device init: Functionality shared with blockdev-add */
1147 blk = blockdev_init(filename, bs_opts, &local_err);
1151 error_report_err(local_err);
1158 /* Create legacy DriveInfo */
1159 dinfo = g_malloc0(sizeof(*dinfo));
1160 dinfo->opts = all_opts;
1163 dinfo->heads = heads;
1165 dinfo->trans = translation;
1168 dinfo->bus = bus_id;
1169 dinfo->unit = unit_id;
1170 dinfo->devaddr = devaddr;
1171 dinfo->serial = g_strdup(serial);
1173 blk_set_legacy_dinfo(blk, dinfo);
1180 dinfo->media_cd = media == MEDIA_CDROM;
1187 qemu_opts_del(legacy_opts);
1192 void hmp_commit(Monitor *mon, const QDict *qdict)
1194 const char *device = qdict_get_str(qdict, "device");
1198 if (!strcmp(device, "all")) {
1199 ret = blk_commit_all();
1201 BlockDriverState *bs;
1202 AioContext *aio_context;
1204 blk = blk_by_name(device);
1206 monitor_printf(mon, "Device '%s' not found\n", device);
1209 if (!blk_is_available(blk)) {
1210 monitor_printf(mon, "Device '%s' has no medium\n", device);
1215 aio_context = bdrv_get_aio_context(bs);
1216 aio_context_acquire(aio_context);
1218 ret = bdrv_commit(bs);
1220 aio_context_release(aio_context);
1223 monitor_printf(mon, "'commit' error for '%s': %s\n", device,
1228 static void blockdev_do_action(TransactionAction *action, Error **errp)
1230 TransactionActionList list;
1232 list.value = action;
1234 qmp_transaction(&list, false, NULL, errp);
1237 void qmp_blockdev_snapshot_sync(bool has_device, const char *device,
1238 bool has_node_name, const char *node_name,
1239 const char *snapshot_file,
1240 bool has_snapshot_node_name,
1241 const char *snapshot_node_name,
1242 bool has_format, const char *format,
1243 bool has_mode, NewImageMode mode, Error **errp)
1245 BlockdevSnapshotSync snapshot = {
1246 .has_device = has_device,
1247 .device = (char *) device,
1248 .has_node_name = has_node_name,
1249 .node_name = (char *) node_name,
1250 .snapshot_file = (char *) snapshot_file,
1251 .has_snapshot_node_name = has_snapshot_node_name,
1252 .snapshot_node_name = (char *) snapshot_node_name,
1253 .has_format = has_format,
1254 .format = (char *) format,
1255 .has_mode = has_mode,
1258 TransactionAction action = {
1259 .type = TRANSACTION_ACTION_KIND_BLOCKDEV_SNAPSHOT_SYNC,
1260 .u.blockdev_snapshot_sync.data = &snapshot,
1262 blockdev_do_action(&action, errp);
1265 void qmp_blockdev_snapshot(const char *node, const char *overlay,
1268 BlockdevSnapshot snapshot_data = {
1269 .node = (char *) node,
1270 .overlay = (char *) overlay
1272 TransactionAction action = {
1273 .type = TRANSACTION_ACTION_KIND_BLOCKDEV_SNAPSHOT,
1274 .u.blockdev_snapshot.data = &snapshot_data,
1276 blockdev_do_action(&action, errp);
1279 void qmp_blockdev_snapshot_internal_sync(const char *device,
1283 BlockdevSnapshotInternal snapshot = {
1284 .device = (char *) device,
1285 .name = (char *) name
1287 TransactionAction action = {
1288 .type = TRANSACTION_ACTION_KIND_BLOCKDEV_SNAPSHOT_INTERNAL_SYNC,
1289 .u.blockdev_snapshot_internal_sync.data = &snapshot,
1291 blockdev_do_action(&action, errp);
1294 SnapshotInfo *qmp_blockdev_snapshot_delete_internal_sync(const char *device,
1301 BlockDriverState *bs;
1303 AioContext *aio_context;
1304 QEMUSnapshotInfo sn;
1305 Error *local_err = NULL;
1306 SnapshotInfo *info = NULL;
1309 blk = blk_by_name(device);
1311 error_set(errp, ERROR_CLASS_DEVICE_NOT_FOUND,
1312 "Device '%s' not found", device);
1316 aio_context = blk_get_aio_context(blk);
1317 aio_context_acquire(aio_context);
1328 error_setg(errp, "Name or id must be provided");
1329 goto out_aio_context;
1332 if (!blk_is_available(blk)) {
1333 error_setg(errp, "Device '%s' has no medium", device);
1334 goto out_aio_context;
1338 if (bdrv_op_is_blocked(bs, BLOCK_OP_TYPE_INTERNAL_SNAPSHOT_DELETE, errp)) {
1339 goto out_aio_context;
1342 ret = bdrv_snapshot_find_by_id_and_name(bs, id, name, &sn, &local_err);
1344 error_propagate(errp, local_err);
1345 goto out_aio_context;
1349 "Snapshot with id '%s' and name '%s' does not exist on "
1351 STR_OR_NULL(id), STR_OR_NULL(name), device);
1352 goto out_aio_context;
1355 bdrv_snapshot_delete(bs, id, name, &local_err);
1357 error_propagate(errp, local_err);
1358 goto out_aio_context;
1361 aio_context_release(aio_context);
1363 info = g_new0(SnapshotInfo, 1);
1364 info->id = g_strdup(sn.id_str);
1365 info->name = g_strdup(sn.name);
1366 info->date_nsec = sn.date_nsec;
1367 info->date_sec = sn.date_sec;
1368 info->vm_state_size = sn.vm_state_size;
1369 info->vm_clock_nsec = sn.vm_clock_nsec % 1000000000;
1370 info->vm_clock_sec = sn.vm_clock_nsec / 1000000000;
1375 aio_context_release(aio_context);
1380 * block_dirty_bitmap_lookup:
1381 * Return a dirty bitmap (if present), after validating
1382 * the node reference and bitmap names.
1384 * @node: The name of the BDS node to search for bitmaps
1385 * @name: The name of the bitmap to search for
1386 * @pbs: Output pointer for BDS lookup, if desired. Can be NULL.
1387 * @paio: Output pointer for aio_context acquisition, if desired. Can be NULL.
1388 * @errp: Output pointer for error information. Can be NULL.
1390 * @return: A bitmap object on success, or NULL on failure.
1392 static BdrvDirtyBitmap *block_dirty_bitmap_lookup(const char *node,
1394 BlockDriverState **pbs,
1398 BlockDriverState *bs;
1399 BdrvDirtyBitmap *bitmap;
1400 AioContext *aio_context;
1403 error_setg(errp, "Node cannot be NULL");
1407 error_setg(errp, "Bitmap name cannot be NULL");
1410 bs = bdrv_lookup_bs(node, node, NULL);
1412 error_setg(errp, "Node '%s' not found", node);
1416 aio_context = bdrv_get_aio_context(bs);
1417 aio_context_acquire(aio_context);
1419 bitmap = bdrv_find_dirty_bitmap(bs, name);
1421 error_setg(errp, "Dirty bitmap '%s' not found", name);
1429 *paio = aio_context;
1431 aio_context_release(aio_context);
1437 aio_context_release(aio_context);
1441 /* New and old BlockDriverState structs for atomic group operations */
1443 typedef struct BlkActionState BlkActionState;
1447 * Table of operations that define an Action.
1449 * @instance_size: Size of state struct, in bytes.
1450 * @prepare: Prepare the work, must NOT be NULL.
1451 * @commit: Commit the changes, can be NULL.
1452 * @abort: Abort the changes on fail, can be NULL.
1453 * @clean: Clean up resources after all transaction actions have called
1454 * commit() or abort(). Can be NULL.
1456 * Only prepare() may fail. In a single transaction, only one of commit() or
1457 * abort() will be called. clean() will always be called if it is present.
1459 typedef struct BlkActionOps {
1460 size_t instance_size;
1461 void (*prepare)(BlkActionState *common, Error **errp);
1462 void (*commit)(BlkActionState *common);
1463 void (*abort)(BlkActionState *common);
1464 void (*clean)(BlkActionState *common);
1469 * Describes one Action's state within a Transaction.
1471 * @action: QAPI-defined enum identifying which Action to perform.
1472 * @ops: Table of ActionOps this Action can perform.
1473 * @block_job_txn: Transaction which this action belongs to.
1474 * @entry: List membership for all Actions in this Transaction.
1476 * This structure must be arranged as first member in a subclassed type,
1477 * assuming that the compiler will also arrange it to the same offsets as the
1480 struct BlkActionState {
1481 TransactionAction *action;
1482 const BlkActionOps *ops;
1483 BlockJobTxn *block_job_txn;
1484 TransactionProperties *txn_props;
1485 QSIMPLEQ_ENTRY(BlkActionState) entry;
1488 /* internal snapshot private data */
1489 typedef struct InternalSnapshotState {
1490 BlkActionState common;
1491 BlockDriverState *bs;
1492 AioContext *aio_context;
1493 QEMUSnapshotInfo sn;
1495 } InternalSnapshotState;
1498 static int action_check_completion_mode(BlkActionState *s, Error **errp)
1500 if (s->txn_props->completion_mode != ACTION_COMPLETION_MODE_INDIVIDUAL) {
1502 "Action '%s' does not support Transaction property "
1503 "completion-mode = %s",
1504 TransactionActionKind_lookup[s->action->type],
1505 ActionCompletionMode_lookup[s->txn_props->completion_mode]);
1511 static void internal_snapshot_prepare(BlkActionState *common,
1514 Error *local_err = NULL;
1518 BlockDriverState *bs;
1519 QEMUSnapshotInfo old_sn, *sn;
1522 BlockdevSnapshotInternal *internal;
1523 InternalSnapshotState *state;
1526 g_assert(common->action->type ==
1527 TRANSACTION_ACTION_KIND_BLOCKDEV_SNAPSHOT_INTERNAL_SYNC);
1528 internal = common->action->u.blockdev_snapshot_internal_sync.data;
1529 state = DO_UPCAST(InternalSnapshotState, common, common);
1531 /* 1. parse input */
1532 device = internal->device;
1533 name = internal->name;
1535 /* 2. check for validation */
1536 if (action_check_completion_mode(common, errp) < 0) {
1540 blk = blk_by_name(device);
1542 error_set(errp, ERROR_CLASS_DEVICE_NOT_FOUND,
1543 "Device '%s' not found", device);
1547 /* AioContext is released in .clean() */
1548 state->aio_context = blk_get_aio_context(blk);
1549 aio_context_acquire(state->aio_context);
1551 if (!blk_is_available(blk)) {
1552 error_setg(errp, QERR_DEVICE_HAS_NO_MEDIUM, device);
1558 bdrv_drained_begin(bs);
1560 if (bdrv_op_is_blocked(bs, BLOCK_OP_TYPE_INTERNAL_SNAPSHOT, errp)) {
1564 if (bdrv_is_read_only(bs)) {
1565 error_setg(errp, "Device '%s' is read only", device);
1569 if (!bdrv_can_snapshot(bs)) {
1570 error_setg(errp, "Block format '%s' used by device '%s' "
1571 "does not support internal snapshots",
1572 bs->drv->format_name, device);
1576 if (!strlen(name)) {
1577 error_setg(errp, "Name is empty");
1581 /* check whether a snapshot with name exist */
1582 ret = bdrv_snapshot_find_by_id_and_name(bs, NULL, name, &old_sn,
1585 error_propagate(errp, local_err);
1589 "Snapshot with name '%s' already exists on device '%s'",
1594 /* 3. take the snapshot */
1596 pstrcpy(sn->name, sizeof(sn->name), name);
1597 qemu_gettimeofday(&tv);
1598 sn->date_sec = tv.tv_sec;
1599 sn->date_nsec = tv.tv_usec * 1000;
1600 sn->vm_clock_nsec = qemu_clock_get_ns(QEMU_CLOCK_VIRTUAL);
1602 ret1 = bdrv_snapshot_create(bs, sn);
1604 error_setg_errno(errp, -ret1,
1605 "Failed to create snapshot '%s' on device '%s'",
1610 /* 4. succeed, mark a snapshot is created */
1611 state->created = true;
1614 static void internal_snapshot_abort(BlkActionState *common)
1616 InternalSnapshotState *state =
1617 DO_UPCAST(InternalSnapshotState, common, common);
1618 BlockDriverState *bs = state->bs;
1619 QEMUSnapshotInfo *sn = &state->sn;
1620 Error *local_error = NULL;
1622 if (!state->created) {
1626 if (bdrv_snapshot_delete(bs, sn->id_str, sn->name, &local_error) < 0) {
1627 error_reportf_err(local_error,
1628 "Failed to delete snapshot with id '%s' and "
1629 "name '%s' on device '%s' in abort: ",
1630 sn->id_str, sn->name,
1631 bdrv_get_device_name(bs));
1635 static void internal_snapshot_clean(BlkActionState *common)
1637 InternalSnapshotState *state = DO_UPCAST(InternalSnapshotState,
1640 if (state->aio_context) {
1642 bdrv_drained_end(state->bs);
1644 aio_context_release(state->aio_context);
1648 /* external snapshot private data */
1649 typedef struct ExternalSnapshotState {
1650 BlkActionState common;
1651 BlockDriverState *old_bs;
1652 BlockDriverState *new_bs;
1653 AioContext *aio_context;
1654 } ExternalSnapshotState;
1656 static void external_snapshot_prepare(BlkActionState *common,
1660 QDict *options = NULL;
1661 Error *local_err = NULL;
1662 /* Device and node name of the image to generate the snapshot from */
1664 const char *node_name;
1665 /* Reference to the new image (for 'blockdev-snapshot') */
1666 const char *snapshot_ref;
1667 /* File name of the new image (for 'blockdev-snapshot-sync') */
1668 const char *new_image_file;
1669 ExternalSnapshotState *state =
1670 DO_UPCAST(ExternalSnapshotState, common, common);
1671 TransactionAction *action = common->action;
1673 /* 'blockdev-snapshot' and 'blockdev-snapshot-sync' have similar
1674 * purpose but a different set of parameters */
1675 switch (action->type) {
1676 case TRANSACTION_ACTION_KIND_BLOCKDEV_SNAPSHOT:
1678 BlockdevSnapshot *s = action->u.blockdev_snapshot.data;
1680 node_name = s->node;
1681 new_image_file = NULL;
1682 snapshot_ref = s->overlay;
1685 case TRANSACTION_ACTION_KIND_BLOCKDEV_SNAPSHOT_SYNC:
1687 BlockdevSnapshotSync *s = action->u.blockdev_snapshot_sync.data;
1688 device = s->has_device ? s->device : NULL;
1689 node_name = s->has_node_name ? s->node_name : NULL;
1690 new_image_file = s->snapshot_file;
1691 snapshot_ref = NULL;
1695 g_assert_not_reached();
1698 /* start processing */
1699 if (action_check_completion_mode(common, errp) < 0) {
1703 state->old_bs = bdrv_lookup_bs(device, node_name, errp);
1704 if (!state->old_bs) {
1708 /* Acquire AioContext now so any threads operating on old_bs stop */
1709 state->aio_context = bdrv_get_aio_context(state->old_bs);
1710 aio_context_acquire(state->aio_context);
1711 bdrv_drained_begin(state->old_bs);
1713 if (!bdrv_is_inserted(state->old_bs)) {
1714 error_setg(errp, QERR_DEVICE_HAS_NO_MEDIUM, device);
1718 if (bdrv_op_is_blocked(state->old_bs,
1719 BLOCK_OP_TYPE_EXTERNAL_SNAPSHOT, errp)) {
1723 if (!bdrv_is_read_only(state->old_bs)) {
1724 if (bdrv_flush(state->old_bs)) {
1725 error_setg(errp, QERR_IO_ERROR);
1730 if (!bdrv_is_first_non_filter(state->old_bs)) {
1731 error_setg(errp, QERR_FEATURE_DISABLED, "snapshot");
1735 if (action->type == TRANSACTION_ACTION_KIND_BLOCKDEV_SNAPSHOT_SYNC) {
1736 BlockdevSnapshotSync *s = action->u.blockdev_snapshot_sync.data;
1737 const char *format = s->has_format ? s->format : "qcow2";
1738 enum NewImageMode mode;
1739 const char *snapshot_node_name =
1740 s->has_snapshot_node_name ? s->snapshot_node_name : NULL;
1742 if (node_name && !snapshot_node_name) {
1743 error_setg(errp, "New snapshot node name missing");
1747 if (snapshot_node_name &&
1748 bdrv_lookup_bs(snapshot_node_name, snapshot_node_name, NULL)) {
1749 error_setg(errp, "New snapshot node name already in use");
1753 flags = state->old_bs->open_flags;
1754 flags &= ~(BDRV_O_SNAPSHOT | BDRV_O_NO_BACKING | BDRV_O_COPY_ON_READ);
1756 /* create new image w/backing file */
1757 mode = s->has_mode ? s->mode : NEW_IMAGE_MODE_ABSOLUTE_PATHS;
1758 if (mode != NEW_IMAGE_MODE_EXISTING) {
1759 int64_t size = bdrv_getlength(state->old_bs);
1761 error_setg_errno(errp, -size, "bdrv_getlength failed");
1764 bdrv_img_create(new_image_file, format,
1765 state->old_bs->filename,
1766 state->old_bs->drv->format_name,
1767 NULL, size, flags, &local_err, false);
1769 error_propagate(errp, local_err);
1774 options = qdict_new();
1775 if (s->has_snapshot_node_name) {
1776 qdict_put(options, "node-name",
1777 qstring_from_str(snapshot_node_name));
1779 qdict_put(options, "driver", qstring_from_str(format));
1781 flags |= BDRV_O_NO_BACKING;
1784 assert(state->new_bs == NULL);
1785 ret = bdrv_open(&state->new_bs, new_image_file, snapshot_ref, options,
1787 /* We will manually add the backing_hd field to the bs later */
1792 if (state->new_bs->blk != NULL) {
1793 error_setg(errp, "The snapshot is already in use by %s",
1794 blk_name(state->new_bs->blk));
1798 if (bdrv_op_is_blocked(state->new_bs, BLOCK_OP_TYPE_EXTERNAL_SNAPSHOT,
1803 if (state->new_bs->backing != NULL) {
1804 error_setg(errp, "The snapshot already has a backing image");
1808 if (!state->new_bs->drv->supports_backing) {
1809 error_setg(errp, "The snapshot does not support backing images");
1813 static void external_snapshot_commit(BlkActionState *common)
1815 ExternalSnapshotState *state =
1816 DO_UPCAST(ExternalSnapshotState, common, common);
1818 bdrv_set_aio_context(state->new_bs, state->aio_context);
1820 /* This removes our old bs and adds the new bs */
1821 bdrv_append(state->new_bs, state->old_bs);
1822 /* We don't need (or want) to use the transactional
1823 * bdrv_reopen_multiple() across all the entries at once, because we
1824 * don't want to abort all of them if one of them fails the reopen */
1825 if (!state->old_bs->copy_on_read) {
1826 bdrv_reopen(state->old_bs, state->old_bs->open_flags & ~BDRV_O_RDWR,
1831 static void external_snapshot_abort(BlkActionState *common)
1833 ExternalSnapshotState *state =
1834 DO_UPCAST(ExternalSnapshotState, common, common);
1835 if (state->new_bs) {
1836 bdrv_unref(state->new_bs);
1840 static void external_snapshot_clean(BlkActionState *common)
1842 ExternalSnapshotState *state =
1843 DO_UPCAST(ExternalSnapshotState, common, common);
1844 if (state->aio_context) {
1845 bdrv_drained_end(state->old_bs);
1846 aio_context_release(state->aio_context);
1850 typedef struct DriveBackupState {
1851 BlkActionState common;
1852 BlockDriverState *bs;
1853 AioContext *aio_context;
1857 static void do_drive_backup(const char *device, const char *target,
1858 bool has_format, const char *format,
1859 enum MirrorSyncMode sync,
1860 bool has_mode, enum NewImageMode mode,
1861 bool has_speed, int64_t speed,
1862 bool has_bitmap, const char *bitmap,
1863 bool has_on_source_error,
1864 BlockdevOnError on_source_error,
1865 bool has_on_target_error,
1866 BlockdevOnError on_target_error,
1867 BlockJobTxn *txn, Error **errp);
1869 static void drive_backup_prepare(BlkActionState *common, Error **errp)
1871 DriveBackupState *state = DO_UPCAST(DriveBackupState, common, common);
1873 DriveBackup *backup;
1874 Error *local_err = NULL;
1876 assert(common->action->type == TRANSACTION_ACTION_KIND_DRIVE_BACKUP);
1877 backup = common->action->u.drive_backup.data;
1879 blk = blk_by_name(backup->device);
1881 error_set(errp, ERROR_CLASS_DEVICE_NOT_FOUND,
1882 "Device '%s' not found", backup->device);
1886 if (!blk_is_available(blk)) {
1887 error_setg(errp, QERR_DEVICE_HAS_NO_MEDIUM, backup->device);
1891 /* AioContext is released in .clean() */
1892 state->aio_context = blk_get_aio_context(blk);
1893 aio_context_acquire(state->aio_context);
1894 bdrv_drained_begin(blk_bs(blk));
1895 state->bs = blk_bs(blk);
1897 do_drive_backup(backup->device, backup->target,
1898 backup->has_format, backup->format,
1900 backup->has_mode, backup->mode,
1901 backup->has_speed, backup->speed,
1902 backup->has_bitmap, backup->bitmap,
1903 backup->has_on_source_error, backup->on_source_error,
1904 backup->has_on_target_error, backup->on_target_error,
1905 common->block_job_txn, &local_err);
1907 error_propagate(errp, local_err);
1911 state->job = state->bs->job;
1914 static void drive_backup_abort(BlkActionState *common)
1916 DriveBackupState *state = DO_UPCAST(DriveBackupState, common, common);
1917 BlockDriverState *bs = state->bs;
1919 /* Only cancel if it's the job we started */
1920 if (bs && bs->job && bs->job == state->job) {
1921 block_job_cancel_sync(bs->job);
1925 static void drive_backup_clean(BlkActionState *common)
1927 DriveBackupState *state = DO_UPCAST(DriveBackupState, common, common);
1929 if (state->aio_context) {
1930 bdrv_drained_end(state->bs);
1931 aio_context_release(state->aio_context);
1935 typedef struct BlockdevBackupState {
1936 BlkActionState common;
1937 BlockDriverState *bs;
1939 AioContext *aio_context;
1940 } BlockdevBackupState;
1942 static void do_blockdev_backup(const char *device, const char *target,
1943 enum MirrorSyncMode sync,
1944 bool has_speed, int64_t speed,
1945 bool has_on_source_error,
1946 BlockdevOnError on_source_error,
1947 bool has_on_target_error,
1948 BlockdevOnError on_target_error,
1949 BlockJobTxn *txn, Error **errp);
1951 static void blockdev_backup_prepare(BlkActionState *common, Error **errp)
1953 BlockdevBackupState *state = DO_UPCAST(BlockdevBackupState, common, common);
1954 BlockdevBackup *backup;
1955 BlockBackend *blk, *target;
1956 Error *local_err = NULL;
1958 assert(common->action->type == TRANSACTION_ACTION_KIND_BLOCKDEV_BACKUP);
1959 backup = common->action->u.blockdev_backup.data;
1961 blk = blk_by_name(backup->device);
1963 error_setg(errp, "Device '%s' not found", backup->device);
1967 if (!blk_is_available(blk)) {
1968 error_setg(errp, QERR_DEVICE_HAS_NO_MEDIUM, backup->device);
1972 target = blk_by_name(backup->target);
1974 error_setg(errp, "Device '%s' not found", backup->target);
1978 /* AioContext is released in .clean() */
1979 state->aio_context = blk_get_aio_context(blk);
1980 if (state->aio_context != blk_get_aio_context(target)) {
1981 state->aio_context = NULL;
1982 error_setg(errp, "Backup between two IO threads is not implemented");
1985 aio_context_acquire(state->aio_context);
1986 state->bs = blk_bs(blk);
1987 bdrv_drained_begin(state->bs);
1989 do_blockdev_backup(backup->device, backup->target,
1991 backup->has_speed, backup->speed,
1992 backup->has_on_source_error, backup->on_source_error,
1993 backup->has_on_target_error, backup->on_target_error,
1994 common->block_job_txn, &local_err);
1996 error_propagate(errp, local_err);
2000 state->job = state->bs->job;
2003 static void blockdev_backup_abort(BlkActionState *common)
2005 BlockdevBackupState *state = DO_UPCAST(BlockdevBackupState, common, common);
2006 BlockDriverState *bs = state->bs;
2008 /* Only cancel if it's the job we started */
2009 if (bs && bs->job && bs->job == state->job) {
2010 block_job_cancel_sync(bs->job);
2014 static void blockdev_backup_clean(BlkActionState *common)
2016 BlockdevBackupState *state = DO_UPCAST(BlockdevBackupState, common, common);
2018 if (state->aio_context) {
2019 bdrv_drained_end(state->bs);
2020 aio_context_release(state->aio_context);
2024 typedef struct BlockDirtyBitmapState {
2025 BlkActionState common;
2026 BdrvDirtyBitmap *bitmap;
2027 BlockDriverState *bs;
2028 AioContext *aio_context;
2031 } BlockDirtyBitmapState;
2033 static void block_dirty_bitmap_add_prepare(BlkActionState *common,
2036 Error *local_err = NULL;
2037 BlockDirtyBitmapAdd *action;
2038 BlockDirtyBitmapState *state = DO_UPCAST(BlockDirtyBitmapState,
2041 if (action_check_completion_mode(common, errp) < 0) {
2045 action = common->action->u.block_dirty_bitmap_add.data;
2046 /* AIO context taken and released within qmp_block_dirty_bitmap_add */
2047 qmp_block_dirty_bitmap_add(action->node, action->name,
2048 action->has_granularity, action->granularity,
2052 state->prepared = true;
2054 error_propagate(errp, local_err);
2058 static void block_dirty_bitmap_add_abort(BlkActionState *common)
2060 BlockDirtyBitmapAdd *action;
2061 BlockDirtyBitmapState *state = DO_UPCAST(BlockDirtyBitmapState,
2064 action = common->action->u.block_dirty_bitmap_add.data;
2065 /* Should not be able to fail: IF the bitmap was added via .prepare(),
2066 * then the node reference and bitmap name must have been valid.
2068 if (state->prepared) {
2069 qmp_block_dirty_bitmap_remove(action->node, action->name, &error_abort);
2073 static void block_dirty_bitmap_clear_prepare(BlkActionState *common,
2076 BlockDirtyBitmapState *state = DO_UPCAST(BlockDirtyBitmapState,
2078 BlockDirtyBitmap *action;
2080 if (action_check_completion_mode(common, errp) < 0) {
2084 action = common->action->u.block_dirty_bitmap_clear.data;
2085 state->bitmap = block_dirty_bitmap_lookup(action->node,
2088 &state->aio_context,
2090 if (!state->bitmap) {
2094 if (bdrv_dirty_bitmap_frozen(state->bitmap)) {
2095 error_setg(errp, "Cannot modify a frozen bitmap");
2097 } else if (!bdrv_dirty_bitmap_enabled(state->bitmap)) {
2098 error_setg(errp, "Cannot clear a disabled bitmap");
2102 bdrv_clear_dirty_bitmap(state->bitmap, &state->backup);
2103 /* AioContext is released in .clean() */
2106 static void block_dirty_bitmap_clear_abort(BlkActionState *common)
2108 BlockDirtyBitmapState *state = DO_UPCAST(BlockDirtyBitmapState,
2111 bdrv_undo_clear_dirty_bitmap(state->bitmap, state->backup);
2114 static void block_dirty_bitmap_clear_commit(BlkActionState *common)
2116 BlockDirtyBitmapState *state = DO_UPCAST(BlockDirtyBitmapState,
2119 hbitmap_free(state->backup);
2122 static void block_dirty_bitmap_clear_clean(BlkActionState *common)
2124 BlockDirtyBitmapState *state = DO_UPCAST(BlockDirtyBitmapState,
2127 if (state->aio_context) {
2128 aio_context_release(state->aio_context);
2132 static void abort_prepare(BlkActionState *common, Error **errp)
2134 error_setg(errp, "Transaction aborted using Abort action");
2137 static void abort_commit(BlkActionState *common)
2139 g_assert_not_reached(); /* this action never succeeds */
2142 static const BlkActionOps actions[] = {
2143 [TRANSACTION_ACTION_KIND_BLOCKDEV_SNAPSHOT] = {
2144 .instance_size = sizeof(ExternalSnapshotState),
2145 .prepare = external_snapshot_prepare,
2146 .commit = external_snapshot_commit,
2147 .abort = external_snapshot_abort,
2148 .clean = external_snapshot_clean,
2150 [TRANSACTION_ACTION_KIND_BLOCKDEV_SNAPSHOT_SYNC] = {
2151 .instance_size = sizeof(ExternalSnapshotState),
2152 .prepare = external_snapshot_prepare,
2153 .commit = external_snapshot_commit,
2154 .abort = external_snapshot_abort,
2155 .clean = external_snapshot_clean,
2157 [TRANSACTION_ACTION_KIND_DRIVE_BACKUP] = {
2158 .instance_size = sizeof(DriveBackupState),
2159 .prepare = drive_backup_prepare,
2160 .abort = drive_backup_abort,
2161 .clean = drive_backup_clean,
2163 [TRANSACTION_ACTION_KIND_BLOCKDEV_BACKUP] = {
2164 .instance_size = sizeof(BlockdevBackupState),
2165 .prepare = blockdev_backup_prepare,
2166 .abort = blockdev_backup_abort,
2167 .clean = blockdev_backup_clean,
2169 [TRANSACTION_ACTION_KIND_ABORT] = {
2170 .instance_size = sizeof(BlkActionState),
2171 .prepare = abort_prepare,
2172 .commit = abort_commit,
2174 [TRANSACTION_ACTION_KIND_BLOCKDEV_SNAPSHOT_INTERNAL_SYNC] = {
2175 .instance_size = sizeof(InternalSnapshotState),
2176 .prepare = internal_snapshot_prepare,
2177 .abort = internal_snapshot_abort,
2178 .clean = internal_snapshot_clean,
2180 [TRANSACTION_ACTION_KIND_BLOCK_DIRTY_BITMAP_ADD] = {
2181 .instance_size = sizeof(BlockDirtyBitmapState),
2182 .prepare = block_dirty_bitmap_add_prepare,
2183 .abort = block_dirty_bitmap_add_abort,
2185 [TRANSACTION_ACTION_KIND_BLOCK_DIRTY_BITMAP_CLEAR] = {
2186 .instance_size = sizeof(BlockDirtyBitmapState),
2187 .prepare = block_dirty_bitmap_clear_prepare,
2188 .commit = block_dirty_bitmap_clear_commit,
2189 .abort = block_dirty_bitmap_clear_abort,
2190 .clean = block_dirty_bitmap_clear_clean,
2195 * Allocate a TransactionProperties structure if necessary, and fill
2196 * that structure with desired defaults if they are unset.
2198 static TransactionProperties *get_transaction_properties(
2199 TransactionProperties *props)
2202 props = g_new0(TransactionProperties, 1);
2205 if (!props->has_completion_mode) {
2206 props->has_completion_mode = true;
2207 props->completion_mode = ACTION_COMPLETION_MODE_INDIVIDUAL;
2214 * 'Atomic' group operations. The operations are performed as a set, and if
2215 * any fail then we roll back all operations in the group.
2217 void qmp_transaction(TransactionActionList *dev_list,
2219 struct TransactionProperties *props,
2222 TransactionActionList *dev_entry = dev_list;
2223 BlockJobTxn *block_job_txn = NULL;
2224 BlkActionState *state, *next;
2225 Error *local_err = NULL;
2227 QSIMPLEQ_HEAD(snap_bdrv_states, BlkActionState) snap_bdrv_states;
2228 QSIMPLEQ_INIT(&snap_bdrv_states);
2230 /* Does this transaction get canceled as a group on failure?
2231 * If not, we don't really need to make a BlockJobTxn.
2233 props = get_transaction_properties(props);
2234 if (props->completion_mode != ACTION_COMPLETION_MODE_INDIVIDUAL) {
2235 block_job_txn = block_job_txn_new();
2238 /* drain all i/o before any operations */
2241 /* We don't do anything in this loop that commits us to the operations */
2242 while (NULL != dev_entry) {
2243 TransactionAction *dev_info = NULL;
2244 const BlkActionOps *ops;
2246 dev_info = dev_entry->value;
2247 dev_entry = dev_entry->next;
2249 assert(dev_info->type < ARRAY_SIZE(actions));
2251 ops = &actions[dev_info->type];
2252 assert(ops->instance_size > 0);
2254 state = g_malloc0(ops->instance_size);
2256 state->action = dev_info;
2257 state->block_job_txn = block_job_txn;
2258 state->txn_props = props;
2259 QSIMPLEQ_INSERT_TAIL(&snap_bdrv_states, state, entry);
2261 state->ops->prepare(state, &local_err);
2263 error_propagate(errp, local_err);
2264 goto delete_and_fail;
2268 QSIMPLEQ_FOREACH(state, &snap_bdrv_states, entry) {
2269 if (state->ops->commit) {
2270 state->ops->commit(state);
2278 /* failure, and it is all-or-none; roll back all operations */
2279 QSIMPLEQ_FOREACH(state, &snap_bdrv_states, entry) {
2280 if (state->ops->abort) {
2281 state->ops->abort(state);
2285 QSIMPLEQ_FOREACH_SAFE(state, &snap_bdrv_states, entry, next) {
2286 if (state->ops->clean) {
2287 state->ops->clean(state);
2292 qapi_free_TransactionProperties(props);
2294 block_job_txn_unref(block_job_txn);
2297 void qmp_eject(const char *device, bool has_force, bool force, Error **errp)
2299 Error *local_err = NULL;
2301 qmp_blockdev_open_tray(device, has_force, force, &local_err);
2303 error_propagate(errp, local_err);
2307 qmp_x_blockdev_remove_medium(device, errp);
2310 void qmp_block_passwd(bool has_device, const char *device,
2311 bool has_node_name, const char *node_name,
2312 const char *password, Error **errp)
2314 Error *local_err = NULL;
2315 BlockDriverState *bs;
2316 AioContext *aio_context;
2318 bs = bdrv_lookup_bs(has_device ? device : NULL,
2319 has_node_name ? node_name : NULL,
2322 error_propagate(errp, local_err);
2326 aio_context = bdrv_get_aio_context(bs);
2327 aio_context_acquire(aio_context);
2329 bdrv_add_key(bs, password, errp);
2331 aio_context_release(aio_context);
2334 void qmp_blockdev_open_tray(const char *device, bool has_force, bool force,
2344 blk = blk_by_name(device);
2346 error_set(errp, ERROR_CLASS_DEVICE_NOT_FOUND,
2347 "Device '%s' not found", device);
2351 if (!blk_dev_has_removable_media(blk)) {
2352 error_setg(errp, "Device '%s' is not removable", device);
2356 if (!blk_dev_has_tray(blk)) {
2357 /* Ignore this command on tray-less devices */
2361 if (blk_dev_is_tray_open(blk)) {
2365 locked = blk_dev_is_medium_locked(blk);
2367 blk_dev_eject_request(blk, force);
2370 if (!locked || force) {
2371 blk_dev_change_media_cb(blk, false);
2375 void qmp_blockdev_close_tray(const char *device, Error **errp)
2379 blk = blk_by_name(device);
2381 error_set(errp, ERROR_CLASS_DEVICE_NOT_FOUND,
2382 "Device '%s' not found", device);
2386 if (!blk_dev_has_removable_media(blk)) {
2387 error_setg(errp, "Device '%s' is not removable", device);
2391 if (!blk_dev_has_tray(blk)) {
2392 /* Ignore this command on tray-less devices */
2396 if (!blk_dev_is_tray_open(blk)) {
2400 blk_dev_change_media_cb(blk, true);
2403 void qmp_x_blockdev_remove_medium(const char *device, Error **errp)
2406 BlockDriverState *bs;
2407 AioContext *aio_context;
2410 blk = blk_by_name(device);
2412 error_set(errp, ERROR_CLASS_DEVICE_NOT_FOUND,
2413 "Device '%s' not found", device);
2417 /* For BBs without a device, we can exchange the BDS tree at will */
2418 has_device = blk_get_attached_dev(blk);
2420 if (has_device && !blk_dev_has_removable_media(blk)) {
2421 error_setg(errp, "Device '%s' is not removable", device);
2425 if (has_device && blk_dev_has_tray(blk) && !blk_dev_is_tray_open(blk)) {
2426 error_setg(errp, "Tray of device '%s' is not open", device);
2435 aio_context = bdrv_get_aio_context(bs);
2436 aio_context_acquire(aio_context);
2438 if (bdrv_op_is_blocked(bs, BLOCK_OP_TYPE_EJECT, errp)) {
2444 if (!blk_dev_has_tray(blk)) {
2445 /* For tray-less devices, blockdev-open-tray is a no-op (or may not be
2446 * called at all); therefore, the medium needs to be ejected here.
2447 * Do it after blk_remove_bs() so blk_is_inserted(blk) returns the @load
2448 * value passed here (i.e. false). */
2449 blk_dev_change_media_cb(blk, false);
2453 aio_context_release(aio_context);
2456 static void qmp_blockdev_insert_anon_medium(const char *device,
2457 BlockDriverState *bs, Error **errp)
2462 blk = blk_by_name(device);
2464 error_set(errp, ERROR_CLASS_DEVICE_NOT_FOUND,
2465 "Device '%s' not found", device);
2469 /* For BBs without a device, we can exchange the BDS tree at will */
2470 has_device = blk_get_attached_dev(blk);
2472 if (has_device && !blk_dev_has_removable_media(blk)) {
2473 error_setg(errp, "Device '%s' is not removable", device);
2477 if (has_device && blk_dev_has_tray(blk) && !blk_dev_is_tray_open(blk)) {
2478 error_setg(errp, "Tray of device '%s' is not open", device);
2483 error_setg(errp, "There already is a medium in device '%s'", device);
2487 blk_insert_bs(blk, bs);
2489 if (!blk_dev_has_tray(blk)) {
2490 /* For tray-less devices, blockdev-close-tray is a no-op (or may not be
2491 * called at all); therefore, the medium needs to be pushed into the
2493 * Do it after blk_insert_bs() so blk_is_inserted(blk) returns the @load
2494 * value passed here (i.e. true). */
2495 blk_dev_change_media_cb(blk, true);
2499 void qmp_x_blockdev_insert_medium(const char *device, const char *node_name,
2502 BlockDriverState *bs;
2504 bs = bdrv_find_node(node_name);
2506 error_setg(errp, "Node '%s' not found", node_name);
2511 error_setg(errp, "Node '%s' is already in use by '%s'", node_name,
2516 qmp_blockdev_insert_anon_medium(device, bs, errp);
2519 void qmp_blockdev_change_medium(const char *device, const char *filename,
2520 bool has_format, const char *format,
2522 BlockdevChangeReadOnlyMode read_only,
2526 BlockDriverState *medium_bs = NULL;
2527 int bdrv_flags, ret;
2528 QDict *options = NULL;
2531 blk = blk_by_name(device);
2533 error_set(errp, ERROR_CLASS_DEVICE_NOT_FOUND,
2534 "Device '%s' not found", device);
2539 blk_update_root_state(blk);
2542 bdrv_flags = blk_get_open_flags_from_root_state(blk);
2543 bdrv_flags &= ~(BDRV_O_TEMPORARY | BDRV_O_SNAPSHOT | BDRV_O_NO_BACKING |
2546 if (!has_read_only) {
2547 read_only = BLOCKDEV_CHANGE_READ_ONLY_MODE_RETAIN;
2550 switch (read_only) {
2551 case BLOCKDEV_CHANGE_READ_ONLY_MODE_RETAIN:
2554 case BLOCKDEV_CHANGE_READ_ONLY_MODE_READ_ONLY:
2555 bdrv_flags &= ~BDRV_O_RDWR;
2558 case BLOCKDEV_CHANGE_READ_ONLY_MODE_READ_WRITE:
2559 bdrv_flags |= BDRV_O_RDWR;
2567 options = qdict_new();
2568 qdict_put(options, "driver", qstring_from_str(format));
2572 ret = bdrv_open(&medium_bs, filename, NULL, options, bdrv_flags, errp);
2577 blk_apply_root_state(blk, medium_bs);
2579 bdrv_add_key(medium_bs, NULL, &err);
2581 error_propagate(errp, err);
2585 qmp_blockdev_open_tray(device, false, false, &err);
2587 error_propagate(errp, err);
2591 qmp_x_blockdev_remove_medium(device, &err);
2593 error_propagate(errp, err);
2597 qmp_blockdev_insert_anon_medium(device, medium_bs, &err);
2599 error_propagate(errp, err);
2603 qmp_blockdev_close_tray(device, errp);
2606 /* If the medium has been inserted, the device has its own reference, so
2607 * ours must be relinquished; and if it has not been inserted successfully,
2608 * the reference must be relinquished anyway */
2609 bdrv_unref(medium_bs);
2612 /* throttling disk I/O limits */
2613 void qmp_block_set_io_throttle(const char *device, int64_t bps, int64_t bps_rd,
2620 bool has_bps_rd_max,
2622 bool has_bps_wr_max,
2626 bool has_iops_rd_max,
2627 int64_t iops_rd_max,
2628 bool has_iops_wr_max,
2629 int64_t iops_wr_max,
2630 bool has_bps_max_length,
2631 int64_t bps_max_length,
2632 bool has_bps_rd_max_length,
2633 int64_t bps_rd_max_length,
2634 bool has_bps_wr_max_length,
2635 int64_t bps_wr_max_length,
2636 bool has_iops_max_length,
2637 int64_t iops_max_length,
2638 bool has_iops_rd_max_length,
2639 int64_t iops_rd_max_length,
2640 bool has_iops_wr_max_length,
2641 int64_t iops_wr_max_length,
2645 const char *group, Error **errp)
2648 BlockDriverState *bs;
2650 AioContext *aio_context;
2652 blk = blk_by_name(device);
2654 error_set(errp, ERROR_CLASS_DEVICE_NOT_FOUND,
2655 "Device '%s' not found", device);
2659 aio_context = blk_get_aio_context(blk);
2660 aio_context_acquire(aio_context);
2664 error_setg(errp, "Device '%s' has no medium", device);
2668 /* The BlockBackend must be the only parent */
2669 assert(QLIST_FIRST(&bs->parents));
2670 if (QLIST_NEXT(QLIST_FIRST(&bs->parents), next_parent)) {
2671 error_setg(errp, "Cannot throttle device with multiple parents");
2675 throttle_config_init(&cfg);
2676 cfg.buckets[THROTTLE_BPS_TOTAL].avg = bps;
2677 cfg.buckets[THROTTLE_BPS_READ].avg = bps_rd;
2678 cfg.buckets[THROTTLE_BPS_WRITE].avg = bps_wr;
2680 cfg.buckets[THROTTLE_OPS_TOTAL].avg = iops;
2681 cfg.buckets[THROTTLE_OPS_READ].avg = iops_rd;
2682 cfg.buckets[THROTTLE_OPS_WRITE].avg = iops_wr;
2685 cfg.buckets[THROTTLE_BPS_TOTAL].max = bps_max;
2687 if (has_bps_rd_max) {
2688 cfg.buckets[THROTTLE_BPS_READ].max = bps_rd_max;
2690 if (has_bps_wr_max) {
2691 cfg.buckets[THROTTLE_BPS_WRITE].max = bps_wr_max;
2694 cfg.buckets[THROTTLE_OPS_TOTAL].max = iops_max;
2696 if (has_iops_rd_max) {
2697 cfg.buckets[THROTTLE_OPS_READ].max = iops_rd_max;
2699 if (has_iops_wr_max) {
2700 cfg.buckets[THROTTLE_OPS_WRITE].max = iops_wr_max;
2703 if (has_bps_max_length) {
2704 cfg.buckets[THROTTLE_BPS_TOTAL].burst_length = bps_max_length;
2706 if (has_bps_rd_max_length) {
2707 cfg.buckets[THROTTLE_BPS_READ].burst_length = bps_rd_max_length;
2709 if (has_bps_wr_max_length) {
2710 cfg.buckets[THROTTLE_BPS_WRITE].burst_length = bps_wr_max_length;
2712 if (has_iops_max_length) {
2713 cfg.buckets[THROTTLE_OPS_TOTAL].burst_length = iops_max_length;
2715 if (has_iops_rd_max_length) {
2716 cfg.buckets[THROTTLE_OPS_READ].burst_length = iops_rd_max_length;
2718 if (has_iops_wr_max_length) {
2719 cfg.buckets[THROTTLE_OPS_WRITE].burst_length = iops_wr_max_length;
2722 if (has_iops_size) {
2723 cfg.op_size = iops_size;
2726 if (!throttle_is_valid(&cfg, errp)) {
2730 if (throttle_enabled(&cfg)) {
2731 /* Enable I/O limits if they're not enabled yet, otherwise
2732 * just update the throttling group. */
2733 if (!bs->throttle_state) {
2734 bdrv_io_limits_enable(bs, has_group ? group : device);
2735 } else if (has_group) {
2736 bdrv_io_limits_update_group(bs, group);
2738 /* Set the new throttling configuration */
2739 bdrv_set_io_limits(bs, &cfg);
2740 } else if (bs->throttle_state) {
2741 /* If all throttling settings are set to 0, disable I/O limits */
2742 bdrv_io_limits_disable(bs);
2746 aio_context_release(aio_context);
2749 void qmp_block_dirty_bitmap_add(const char *node, const char *name,
2750 bool has_granularity, uint32_t granularity,
2753 AioContext *aio_context;
2754 BlockDriverState *bs;
2756 if (!name || name[0] == '\0') {
2757 error_setg(errp, "Bitmap name cannot be empty");
2761 bs = bdrv_lookup_bs(node, node, errp);
2766 aio_context = bdrv_get_aio_context(bs);
2767 aio_context_acquire(aio_context);
2769 if (has_granularity) {
2770 if (granularity < 512 || !is_power_of_2(granularity)) {
2771 error_setg(errp, "Granularity must be power of 2 "
2772 "and at least 512");
2776 /* Default to cluster size, if available: */
2777 granularity = bdrv_get_default_bitmap_granularity(bs);
2780 bdrv_create_dirty_bitmap(bs, granularity, name, errp);
2783 aio_context_release(aio_context);
2786 void qmp_block_dirty_bitmap_remove(const char *node, const char *name,
2789 AioContext *aio_context;
2790 BlockDriverState *bs;
2791 BdrvDirtyBitmap *bitmap;
2793 bitmap = block_dirty_bitmap_lookup(node, name, &bs, &aio_context, errp);
2794 if (!bitmap || !bs) {
2798 if (bdrv_dirty_bitmap_frozen(bitmap)) {
2800 "Bitmap '%s' is currently frozen and cannot be removed",
2804 bdrv_dirty_bitmap_make_anon(bitmap);
2805 bdrv_release_dirty_bitmap(bs, bitmap);
2808 aio_context_release(aio_context);
2812 * Completely clear a bitmap, for the purposes of synchronizing a bitmap
2813 * immediately after a full backup operation.
2815 void qmp_block_dirty_bitmap_clear(const char *node, const char *name,
2818 AioContext *aio_context;
2819 BdrvDirtyBitmap *bitmap;
2820 BlockDriverState *bs;
2822 bitmap = block_dirty_bitmap_lookup(node, name, &bs, &aio_context, errp);
2823 if (!bitmap || !bs) {
2827 if (bdrv_dirty_bitmap_frozen(bitmap)) {
2829 "Bitmap '%s' is currently frozen and cannot be modified",
2832 } else if (!bdrv_dirty_bitmap_enabled(bitmap)) {
2834 "Bitmap '%s' is currently disabled and cannot be cleared",
2839 bdrv_clear_dirty_bitmap(bitmap, NULL);
2842 aio_context_release(aio_context);
2845 void hmp_drive_del(Monitor *mon, const QDict *qdict)
2847 const char *id = qdict_get_str(qdict, "id");
2849 BlockDriverState *bs;
2850 AioContext *aio_context;
2851 Error *local_err = NULL;
2853 bs = bdrv_find_node(id);
2855 qmp_x_blockdev_del(false, NULL, true, id, &local_err);
2857 error_report_err(local_err);
2862 blk = blk_by_name(id);
2864 error_report("Device '%s' not found", id);
2868 if (!blk_legacy_dinfo(blk)) {
2869 error_report("Deleting device added with blockdev-add"
2870 " is not supported");
2874 aio_context = blk_get_aio_context(blk);
2875 aio_context_acquire(aio_context);
2879 if (bdrv_op_is_blocked(bs, BLOCK_OP_TYPE_DRIVE_DEL, &local_err)) {
2880 error_report_err(local_err);
2881 aio_context_release(aio_context);
2888 /* Make the BlockBackend and the attached BlockDriverState anonymous */
2889 monitor_remove_blk(blk);
2891 /* If this BlockBackend has a device attached to it, its refcount will be
2892 * decremented when the device is removed; otherwise we have to do so here.
2894 if (blk_get_attached_dev(blk)) {
2895 /* Further I/O must not pause the guest */
2896 blk_set_on_error(blk, BLOCKDEV_ON_ERROR_REPORT,
2897 BLOCKDEV_ON_ERROR_REPORT);
2902 aio_context_release(aio_context);
2905 void qmp_block_resize(bool has_device, const char *device,
2906 bool has_node_name, const char *node_name,
2907 int64_t size, Error **errp)
2909 Error *local_err = NULL;
2910 BlockDriverState *bs;
2911 AioContext *aio_context;
2914 bs = bdrv_lookup_bs(has_device ? device : NULL,
2915 has_node_name ? node_name : NULL,
2918 error_propagate(errp, local_err);
2922 aio_context = bdrv_get_aio_context(bs);
2923 aio_context_acquire(aio_context);
2925 if (!bdrv_is_first_non_filter(bs)) {
2926 error_setg(errp, QERR_FEATURE_DISABLED, "resize");
2931 error_setg(errp, QERR_INVALID_PARAMETER_VALUE, "size", "a >0 size");
2935 if (bdrv_op_is_blocked(bs, BLOCK_OP_TYPE_RESIZE, NULL)) {
2936 error_setg(errp, QERR_DEVICE_IN_USE, device);
2940 /* complete all in-flight operations before resizing the device */
2943 ret = bdrv_truncate(bs, size);
2948 error_setg(errp, QERR_DEVICE_HAS_NO_MEDIUM, device);
2951 error_setg(errp, QERR_UNSUPPORTED);
2954 error_setg(errp, "Device '%s' is read only", device);
2957 error_setg(errp, QERR_DEVICE_IN_USE, device);
2960 error_setg_errno(errp, -ret, "Could not resize");
2965 aio_context_release(aio_context);
2968 static void block_job_cb(void *opaque, int ret)
2970 /* Note that this function may be executed from another AioContext besides
2971 * the QEMU main loop. If you need to access anything that assumes the
2972 * QEMU global mutex, use a BH or introduce a mutex.
2975 BlockDriverState *bs = opaque;
2976 const char *msg = NULL;
2978 trace_block_job_cb(bs, bs->job, ret);
2983 msg = strerror(-ret);
2986 if (block_job_is_cancelled(bs->job)) {
2987 block_job_event_cancelled(bs->job);
2989 block_job_event_completed(bs->job, msg);
2993 void qmp_block_stream(const char *device,
2994 bool has_base, const char *base,
2995 bool has_backing_file, const char *backing_file,
2996 bool has_speed, int64_t speed,
2997 bool has_on_error, BlockdevOnError on_error,
3001 BlockDriverState *bs;
3002 BlockDriverState *base_bs = NULL;
3003 AioContext *aio_context;
3004 Error *local_err = NULL;
3005 const char *base_name = NULL;
3007 if (!has_on_error) {
3008 on_error = BLOCKDEV_ON_ERROR_REPORT;
3011 blk = blk_by_name(device);
3013 error_set(errp, ERROR_CLASS_DEVICE_NOT_FOUND,
3014 "Device '%s' not found", device);
3018 aio_context = blk_get_aio_context(blk);
3019 aio_context_acquire(aio_context);
3021 if (!blk_is_available(blk)) {
3022 error_setg(errp, "Device '%s' has no medium", device);
3027 if (bdrv_op_is_blocked(bs, BLOCK_OP_TYPE_STREAM, errp)) {
3032 base_bs = bdrv_find_backing_image(bs, base);
3033 if (base_bs == NULL) {
3034 error_setg(errp, QERR_BASE_NOT_FOUND, base);
3037 assert(bdrv_get_aio_context(base_bs) == aio_context);
3041 /* if we are streaming the entire chain, the result will have no backing
3042 * file, and specifying one is therefore an error */
3043 if (base_bs == NULL && has_backing_file) {
3044 error_setg(errp, "backing file specified, but streaming the "
3049 /* backing_file string overrides base bs filename */
3050 base_name = has_backing_file ? backing_file : base_name;
3052 stream_start(bs, base_bs, base_name, has_speed ? speed : 0,
3053 on_error, block_job_cb, bs, &local_err);
3055 error_propagate(errp, local_err);
3059 trace_qmp_block_stream(bs, bs->job);
3062 aio_context_release(aio_context);
3065 void qmp_block_commit(const char *device,
3066 bool has_base, const char *base,
3067 bool has_top, const char *top,
3068 bool has_backing_file, const char *backing_file,
3069 bool has_speed, int64_t speed,
3073 BlockDriverState *bs;
3074 BlockDriverState *base_bs, *top_bs;
3075 AioContext *aio_context;
3076 Error *local_err = NULL;
3077 /* This will be part of the QMP command, if/when the
3078 * BlockdevOnError change for blkmirror makes it in
3080 BlockdevOnError on_error = BLOCKDEV_ON_ERROR_REPORT;
3087 * libvirt relies on the DeviceNotFound error class in order to probe for
3088 * live commit feature versions; for this to work, we must make sure to
3089 * perform the device lookup before any generic errors that may occur in a
3090 * scenario in which all optional arguments are omitted. */
3091 blk = blk_by_name(device);
3093 error_set(errp, ERROR_CLASS_DEVICE_NOT_FOUND,
3094 "Device '%s' not found", device);
3098 aio_context = blk_get_aio_context(blk);
3099 aio_context_acquire(aio_context);
3101 if (!blk_is_available(blk)) {
3102 error_setg(errp, "Device '%s' has no medium", device);
3107 if (bdrv_op_is_blocked(bs, BLOCK_OP_TYPE_COMMIT_SOURCE, errp)) {
3111 /* default top_bs is the active layer */
3114 if (has_top && top) {
3115 if (strcmp(bs->filename, top) != 0) {
3116 top_bs = bdrv_find_backing_image(bs, top);
3120 if (top_bs == NULL) {
3121 error_setg(errp, "Top image file %s not found", top ? top : "NULL");
3125 assert(bdrv_get_aio_context(top_bs) == aio_context);
3127 if (has_base && base) {
3128 base_bs = bdrv_find_backing_image(top_bs, base);
3130 base_bs = bdrv_find_base(top_bs);
3133 if (base_bs == NULL) {
3134 error_setg(errp, QERR_BASE_NOT_FOUND, base ? base : "NULL");
3138 assert(bdrv_get_aio_context(base_bs) == aio_context);
3140 if (bdrv_op_is_blocked(base_bs, BLOCK_OP_TYPE_COMMIT_TARGET, errp)) {
3144 /* Do not allow attempts to commit an image into itself */
3145 if (top_bs == base_bs) {
3146 error_setg(errp, "cannot commit an image into itself");
3151 if (has_backing_file) {
3152 error_setg(errp, "'backing-file' specified,"
3153 " but 'top' is the active layer");
3156 commit_active_start(bs, base_bs, speed, on_error, block_job_cb,
3159 commit_start(bs, base_bs, top_bs, speed, on_error, block_job_cb, bs,
3160 has_backing_file ? backing_file : NULL, &local_err);
3162 if (local_err != NULL) {
3163 error_propagate(errp, local_err);
3168 aio_context_release(aio_context);
3171 static void do_drive_backup(const char *device, const char *target,
3172 bool has_format, const char *format,
3173 enum MirrorSyncMode sync,
3174 bool has_mode, enum NewImageMode mode,
3175 bool has_speed, int64_t speed,
3176 bool has_bitmap, const char *bitmap,
3177 bool has_on_source_error,
3178 BlockdevOnError on_source_error,
3179 bool has_on_target_error,
3180 BlockdevOnError on_target_error,
3181 BlockJobTxn *txn, Error **errp)
3184 BlockDriverState *bs;
3185 BlockDriverState *target_bs;
3186 BlockDriverState *source = NULL;
3187 BdrvDirtyBitmap *bmap = NULL;
3188 AioContext *aio_context;
3189 QDict *options = NULL;
3190 Error *local_err = NULL;
3198 if (!has_on_source_error) {
3199 on_source_error = BLOCKDEV_ON_ERROR_REPORT;
3201 if (!has_on_target_error) {
3202 on_target_error = BLOCKDEV_ON_ERROR_REPORT;
3205 mode = NEW_IMAGE_MODE_ABSOLUTE_PATHS;
3208 blk = blk_by_name(device);
3210 error_set(errp, ERROR_CLASS_DEVICE_NOT_FOUND,
3211 "Device '%s' not found", device);
3215 aio_context = blk_get_aio_context(blk);
3216 aio_context_acquire(aio_context);
3218 /* Although backup_run has this check too, we need to use bs->drv below, so
3219 * do an early check redundantly. */
3220 if (!blk_is_available(blk)) {
3221 error_setg(errp, QERR_DEVICE_HAS_NO_MEDIUM, device);
3227 format = mode == NEW_IMAGE_MODE_EXISTING ? NULL : bs->drv->format_name;
3230 /* Early check to avoid creating target */
3231 if (bdrv_op_is_blocked(bs, BLOCK_OP_TYPE_BACKUP_SOURCE, errp)) {
3235 flags = bs->open_flags | BDRV_O_RDWR;
3237 /* See if we have a backing HD we can use to create our new image
3239 if (sync == MIRROR_SYNC_MODE_TOP) {
3240 source = backing_bs(bs);
3242 sync = MIRROR_SYNC_MODE_FULL;
3245 if (sync == MIRROR_SYNC_MODE_NONE) {
3249 size = bdrv_getlength(bs);
3251 error_setg_errno(errp, -size, "bdrv_getlength failed");
3255 if (mode != NEW_IMAGE_MODE_EXISTING) {
3258 bdrv_img_create(target, format, source->filename,
3259 source->drv->format_name, NULL,
3260 size, flags, &local_err, false);
3262 bdrv_img_create(target, format, NULL, NULL, NULL,
3263 size, flags, &local_err, false);
3268 error_propagate(errp, local_err);
3273 options = qdict_new();
3274 qdict_put(options, "driver", qstring_from_str(format));
3278 ret = bdrv_open(&target_bs, target, NULL, options, flags, &local_err);
3280 error_propagate(errp, local_err);
3284 bdrv_set_aio_context(target_bs, aio_context);
3287 bmap = bdrv_find_dirty_bitmap(bs, bitmap);
3289 error_setg(errp, "Bitmap '%s' could not be found", bitmap);
3290 bdrv_unref(target_bs);
3295 backup_start(bs, target_bs, speed, sync, bmap,
3296 on_source_error, on_target_error,
3297 block_job_cb, bs, txn, &local_err);
3298 if (local_err != NULL) {
3299 bdrv_unref(target_bs);
3300 error_propagate(errp, local_err);
3305 aio_context_release(aio_context);
3308 void qmp_drive_backup(const char *device, const char *target,
3309 bool has_format, const char *format,
3310 enum MirrorSyncMode sync,
3311 bool has_mode, enum NewImageMode mode,
3312 bool has_speed, int64_t speed,
3313 bool has_bitmap, const char *bitmap,
3314 bool has_on_source_error, BlockdevOnError on_source_error,
3315 bool has_on_target_error, BlockdevOnError on_target_error,
3318 return do_drive_backup(device, target, has_format, format, sync,
3319 has_mode, mode, has_speed, speed,
3321 has_on_source_error, on_source_error,
3322 has_on_target_error, on_target_error,
3326 BlockDeviceInfoList *qmp_query_named_block_nodes(Error **errp)
3328 return bdrv_named_nodes_list(errp);
3331 void do_blockdev_backup(const char *device, const char *target,
3332 enum MirrorSyncMode sync,
3333 bool has_speed, int64_t speed,
3334 bool has_on_source_error,
3335 BlockdevOnError on_source_error,
3336 bool has_on_target_error,
3337 BlockdevOnError on_target_error,
3338 BlockJobTxn *txn, Error **errp)
3340 BlockBackend *blk, *target_blk;
3341 BlockDriverState *bs;
3342 BlockDriverState *target_bs;
3343 Error *local_err = NULL;
3344 AioContext *aio_context;
3349 if (!has_on_source_error) {
3350 on_source_error = BLOCKDEV_ON_ERROR_REPORT;
3352 if (!has_on_target_error) {
3353 on_target_error = BLOCKDEV_ON_ERROR_REPORT;
3356 blk = blk_by_name(device);
3358 error_setg(errp, "Device '%s' not found", device);
3362 aio_context = blk_get_aio_context(blk);
3363 aio_context_acquire(aio_context);
3365 if (!blk_is_available(blk)) {
3366 error_setg(errp, "Device '%s' has no medium", device);
3371 target_blk = blk_by_name(target);
3373 error_setg(errp, "Device '%s' not found", target);
3377 if (!blk_is_available(target_blk)) {
3378 error_setg(errp, "Device '%s' has no medium", target);
3381 target_bs = blk_bs(target_blk);
3383 bdrv_ref(target_bs);
3384 bdrv_set_aio_context(target_bs, aio_context);
3385 backup_start(bs, target_bs, speed, sync, NULL, on_source_error,
3386 on_target_error, block_job_cb, bs, txn, &local_err);
3387 if (local_err != NULL) {
3388 bdrv_unref(target_bs);
3389 error_propagate(errp, local_err);
3392 aio_context_release(aio_context);
3395 void qmp_blockdev_backup(const char *device, const char *target,
3396 enum MirrorSyncMode sync,
3397 bool has_speed, int64_t speed,
3398 bool has_on_source_error,
3399 BlockdevOnError on_source_error,
3400 bool has_on_target_error,
3401 BlockdevOnError on_target_error,
3404 do_blockdev_backup(device, target, sync, has_speed, speed,
3405 has_on_source_error, on_source_error,
3406 has_on_target_error, on_target_error,
3410 /* Parameter check and block job starting for drive mirroring.
3411 * Caller should hold @device and @target's aio context (must be the same).
3413 static void blockdev_mirror_common(BlockDriverState *bs,
3414 BlockDriverState *target,
3415 bool has_replaces, const char *replaces,
3416 enum MirrorSyncMode sync,
3417 bool has_speed, int64_t speed,
3418 bool has_granularity, uint32_t granularity,
3419 bool has_buf_size, int64_t buf_size,
3420 bool has_on_source_error,
3421 BlockdevOnError on_source_error,
3422 bool has_on_target_error,
3423 BlockdevOnError on_target_error,
3424 bool has_unmap, bool unmap,
3431 if (!has_on_source_error) {
3432 on_source_error = BLOCKDEV_ON_ERROR_REPORT;
3434 if (!has_on_target_error) {
3435 on_target_error = BLOCKDEV_ON_ERROR_REPORT;
3437 if (!has_granularity) {
3440 if (!has_buf_size) {
3447 if (granularity != 0 && (granularity < 512 || granularity > 1048576 * 64)) {
3448 error_setg(errp, QERR_INVALID_PARAMETER_VALUE, "granularity",
3449 "a value in range [512B, 64MB]");
3452 if (granularity & (granularity - 1)) {
3453 error_setg(errp, QERR_INVALID_PARAMETER_VALUE, "granularity",
3458 if (bdrv_op_is_blocked(bs, BLOCK_OP_TYPE_MIRROR_SOURCE, errp)) {
3461 if (bdrv_op_is_blocked(target, BLOCK_OP_TYPE_MIRROR_TARGET, errp)) {
3465 error_setg(errp, "Cannot mirror to an attached block device");
3469 if (!bs->backing && sync == MIRROR_SYNC_MODE_TOP) {
3470 sync = MIRROR_SYNC_MODE_FULL;
3473 /* pass the node name to replace to mirror start since it's loose coupling
3474 * and will allow to check whether the node still exist at mirror completion
3476 mirror_start(bs, target,
3477 has_replaces ? replaces : NULL,
3478 speed, granularity, buf_size, sync,
3479 on_source_error, on_target_error, unmap,
3480 block_job_cb, bs, errp);
3483 void qmp_drive_mirror(const char *device, const char *target,
3484 bool has_format, const char *format,
3485 bool has_node_name, const char *node_name,
3486 bool has_replaces, const char *replaces,
3487 enum MirrorSyncMode sync,
3488 bool has_mode, enum NewImageMode mode,
3489 bool has_speed, int64_t speed,
3490 bool has_granularity, uint32_t granularity,
3491 bool has_buf_size, int64_t buf_size,
3492 bool has_on_source_error, BlockdevOnError on_source_error,
3493 bool has_on_target_error, BlockdevOnError on_target_error,
3494 bool has_unmap, bool unmap,
3497 BlockDriverState *bs;
3499 BlockDriverState *source, *target_bs;
3500 AioContext *aio_context;
3501 Error *local_err = NULL;
3502 QDict *options = NULL;
3507 blk = blk_by_name(device);
3509 error_set(errp, ERROR_CLASS_DEVICE_NOT_FOUND,
3510 "Device '%s' not found", device);
3514 aio_context = blk_get_aio_context(blk);
3515 aio_context_acquire(aio_context);
3517 if (!blk_is_available(blk)) {
3518 error_setg(errp, QERR_DEVICE_HAS_NO_MEDIUM, device);
3523 mode = NEW_IMAGE_MODE_ABSOLUTE_PATHS;
3527 format = mode == NEW_IMAGE_MODE_EXISTING ? NULL : bs->drv->format_name;
3530 flags = bs->open_flags | BDRV_O_RDWR;
3531 source = backing_bs(bs);
3532 if (!source && sync == MIRROR_SYNC_MODE_TOP) {
3533 sync = MIRROR_SYNC_MODE_FULL;
3535 if (sync == MIRROR_SYNC_MODE_NONE) {
3539 size = bdrv_getlength(bs);
3541 error_setg_errno(errp, -size, "bdrv_getlength failed");
3546 BlockDriverState *to_replace_bs;
3547 AioContext *replace_aio_context;
3548 int64_t replace_size;
3550 if (!has_node_name) {
3551 error_setg(errp, "a node-name must be provided when replacing a"
3552 " named node of the graph");
3556 to_replace_bs = check_to_replace_node(bs, replaces, &local_err);
3558 if (!to_replace_bs) {
3559 error_propagate(errp, local_err);
3563 replace_aio_context = bdrv_get_aio_context(to_replace_bs);
3564 aio_context_acquire(replace_aio_context);
3565 replace_size = bdrv_getlength(to_replace_bs);
3566 aio_context_release(replace_aio_context);
3568 if (size != replace_size) {
3569 error_setg(errp, "cannot replace image with a mirror image of "
3575 if ((sync == MIRROR_SYNC_MODE_FULL || !source)
3576 && mode != NEW_IMAGE_MODE_EXISTING)
3578 /* create new image w/o backing file */
3580 bdrv_img_create(target, format,
3581 NULL, NULL, NULL, size, flags, &local_err, false);
3584 case NEW_IMAGE_MODE_EXISTING:
3586 case NEW_IMAGE_MODE_ABSOLUTE_PATHS:
3587 /* create new image with backing file */
3588 bdrv_img_create(target, format,
3590 source->drv->format_name,
3591 NULL, size, flags, &local_err, false);
3599 error_propagate(errp, local_err);
3603 options = qdict_new();
3604 if (has_node_name) {
3605 qdict_put(options, "node-name", qstring_from_str(node_name));
3608 qdict_put(options, "driver", qstring_from_str(format));
3611 /* Mirroring takes care of copy-on-write using the source's backing
3615 ret = bdrv_open(&target_bs, target, NULL, options,
3616 flags | BDRV_O_NO_BACKING, &local_err);
3618 error_propagate(errp, local_err);
3622 bdrv_set_aio_context(target_bs, aio_context);
3624 blockdev_mirror_common(bs, target_bs,
3625 has_replaces, replaces, sync,
3627 has_granularity, granularity,
3628 has_buf_size, buf_size,
3629 has_on_source_error, on_source_error,
3630 has_on_target_error, on_target_error,
3634 error_propagate(errp, local_err);
3635 bdrv_unref(target_bs);
3638 aio_context_release(aio_context);
3641 void qmp_blockdev_mirror(const char *device, const char *target,
3642 bool has_replaces, const char *replaces,
3643 MirrorSyncMode sync,
3644 bool has_speed, int64_t speed,
3645 bool has_granularity, uint32_t granularity,
3646 bool has_buf_size, int64_t buf_size,
3647 bool has_on_source_error,
3648 BlockdevOnError on_source_error,
3649 bool has_on_target_error,
3650 BlockdevOnError on_target_error,
3653 BlockDriverState *bs;
3655 BlockDriverState *target_bs;
3656 AioContext *aio_context;
3657 Error *local_err = NULL;
3659 blk = blk_by_name(device);
3661 error_setg(errp, "Device '%s' not found", device);
3667 error_setg(errp, "Device '%s' has no media", device);
3671 target_bs = bdrv_lookup_bs(target, target, errp);
3676 aio_context = bdrv_get_aio_context(bs);
3677 aio_context_acquire(aio_context);
3679 bdrv_ref(target_bs);
3680 bdrv_set_aio_context(target_bs, aio_context);
3682 blockdev_mirror_common(bs, target_bs,
3683 has_replaces, replaces, sync,
3685 has_granularity, granularity,
3686 has_buf_size, buf_size,
3687 has_on_source_error, on_source_error,
3688 has_on_target_error, on_target_error,
3692 error_propagate(errp, local_err);
3693 bdrv_unref(target_bs);
3696 aio_context_release(aio_context);
3699 /* Get the block job for a given device name and acquire its AioContext */
3700 static BlockJob *find_block_job(const char *device, AioContext **aio_context,
3704 BlockDriverState *bs;
3706 *aio_context = NULL;
3708 blk = blk_by_name(device);
3713 *aio_context = blk_get_aio_context(blk);
3714 aio_context_acquire(*aio_context);
3716 if (!blk_is_available(blk)) {
3728 error_set(errp, ERROR_CLASS_DEVICE_NOT_ACTIVE,
3729 "No active block job on device '%s'", device);
3731 aio_context_release(*aio_context);
3732 *aio_context = NULL;
3737 void qmp_block_job_set_speed(const char *device, int64_t speed, Error **errp)
3739 AioContext *aio_context;
3740 BlockJob *job = find_block_job(device, &aio_context, errp);
3746 block_job_set_speed(job, speed, errp);
3747 aio_context_release(aio_context);
3750 void qmp_block_job_cancel(const char *device,
3751 bool has_force, bool force, Error **errp)
3753 AioContext *aio_context;
3754 BlockJob *job = find_block_job(device, &aio_context, errp);
3764 if (job->user_paused && !force) {
3765 error_setg(errp, "The block job for device '%s' is currently paused",
3770 trace_qmp_block_job_cancel(job);
3771 block_job_cancel(job);
3773 aio_context_release(aio_context);
3776 void qmp_block_job_pause(const char *device, Error **errp)
3778 AioContext *aio_context;
3779 BlockJob *job = find_block_job(device, &aio_context, errp);
3781 if (!job || job->user_paused) {
3785 job->user_paused = true;
3786 trace_qmp_block_job_pause(job);
3787 block_job_pause(job);
3788 aio_context_release(aio_context);
3791 void qmp_block_job_resume(const char *device, Error **errp)
3793 AioContext *aio_context;
3794 BlockJob *job = find_block_job(device, &aio_context, errp);
3796 if (!job || !job->user_paused) {
3800 job->user_paused = false;
3801 trace_qmp_block_job_resume(job);
3802 block_job_resume(job);
3803 aio_context_release(aio_context);
3806 void qmp_block_job_complete(const char *device, Error **errp)
3808 AioContext *aio_context;
3809 BlockJob *job = find_block_job(device, &aio_context, errp);
3815 trace_qmp_block_job_complete(job);
3816 block_job_complete(job, errp);
3817 aio_context_release(aio_context);
3820 void qmp_change_backing_file(const char *device,
3821 const char *image_node_name,
3822 const char *backing_file,
3826 BlockDriverState *bs = NULL;
3827 AioContext *aio_context;
3828 BlockDriverState *image_bs = NULL;
3829 Error *local_err = NULL;
3834 blk = blk_by_name(device);
3836 error_set(errp, ERROR_CLASS_DEVICE_NOT_FOUND,
3837 "Device '%s' not found", device);
3841 aio_context = blk_get_aio_context(blk);
3842 aio_context_acquire(aio_context);
3844 if (!blk_is_available(blk)) {
3845 error_setg(errp, "Device '%s' has no medium", device);
3850 image_bs = bdrv_lookup_bs(NULL, image_node_name, &local_err);
3852 error_propagate(errp, local_err);
3857 error_setg(errp, "image file not found");
3861 if (bdrv_find_base(image_bs) == image_bs) {
3862 error_setg(errp, "not allowing backing file change on an image "
3863 "without a backing file");
3867 /* even though we are not necessarily operating on bs, we need it to
3868 * determine if block ops are currently prohibited on the chain */
3869 if (bdrv_op_is_blocked(bs, BLOCK_OP_TYPE_CHANGE, errp)) {
3873 /* final sanity check */
3874 if (!bdrv_chain_contains(bs, image_bs)) {
3875 error_setg(errp, "'%s' and image file are not in the same chain",
3880 /* if not r/w, reopen to make r/w */
3881 open_flags = image_bs->open_flags;
3882 ro = bdrv_is_read_only(image_bs);
3885 bdrv_reopen(image_bs, open_flags | BDRV_O_RDWR, &local_err);
3887 error_propagate(errp, local_err);
3892 ret = bdrv_change_backing_file(image_bs, backing_file,
3893 image_bs->drv ? image_bs->drv->format_name : "");
3896 error_setg_errno(errp, -ret, "Could not change backing file to '%s'",
3898 /* don't exit here, so we can try to restore open flags if
3903 bdrv_reopen(image_bs, open_flags, &local_err);
3905 error_propagate(errp, local_err); /* will preserve prior errp */
3910 aio_context_release(aio_context);
3913 void hmp_drive_add_node(Monitor *mon, const char *optstr)
3917 Error *local_err = NULL;
3919 opts = qemu_opts_parse_noisily(&qemu_drive_opts, optstr, false);
3924 qdict = qemu_opts_to_qdict(opts, NULL);
3926 if (!qdict_get_try_str(qdict, "node-name")) {
3928 error_report("'node-name' needs to be specified");
3932 BlockDriverState *bs = bds_tree_init(qdict, &local_err);
3934 error_report_err(local_err);
3938 QTAILQ_INSERT_TAIL(&monitor_bdrv_states, bs, monitor_list);
3941 qemu_opts_del(opts);
3944 void qmp_blockdev_add(BlockdevOptions *options, Error **errp)
3946 QmpOutputVisitor *ov = qmp_output_visitor_new();
3947 BlockDriverState *bs;
3948 BlockBackend *blk = NULL;
3951 Error *local_err = NULL;
3953 /* TODO Sort it out in raw-posix and drive_new(): Reject aio=native with
3954 * cache.direct=false instead of silently switching to aio=threads, except
3955 * when called from drive_new().
3957 * For now, simply forbidding the combination for all drivers will do. */
3958 if (options->has_aio && options->aio == BLOCKDEV_AIO_OPTIONS_NATIVE) {
3959 bool direct = options->has_cache &&
3960 options->cache->has_direct &&
3961 options->cache->direct;
3963 error_setg(errp, "aio=native requires cache.direct=true");
3968 visit_type_BlockdevOptions(qmp_output_get_visitor(ov), NULL, &options,
3971 error_propagate(errp, local_err);
3975 obj = qmp_output_get_qobject(ov);
3976 qdict = qobject_to_qdict(obj);
3978 qdict_flatten(qdict);
3980 if (options->has_id) {
3981 blk = blockdev_init(NULL, qdict, &local_err);
3983 error_propagate(errp, local_err);
3989 if (!qdict_get_try_str(qdict, "node-name")) {
3990 error_setg(errp, "'id' and/or 'node-name' need to be specified for "
3995 bs = bds_tree_init(qdict, errp);
4000 QTAILQ_INSERT_TAIL(&monitor_bdrv_states, bs, monitor_list);
4003 if (bs && bdrv_key_required(bs)) {
4005 monitor_remove_blk(blk);
4008 QTAILQ_REMOVE(&monitor_bdrv_states, bs, monitor_list);
4011 error_setg(errp, "blockdev-add doesn't support encrypted devices");
4016 qmp_output_visitor_cleanup(ov);
4019 void qmp_x_blockdev_del(bool has_id, const char *id,
4020 bool has_node_name, const char *node_name, Error **errp)
4022 AioContext *aio_context;
4024 BlockDriverState *bs;
4026 if (has_id && has_node_name) {
4027 error_setg(errp, "Only one of id and node-name must be specified");
4029 } else if (!has_id && !has_node_name) {
4030 error_setg(errp, "No block device specified");
4035 /* blk_by_name() never returns a BB that is not owned by the monitor */
4036 blk = blk_by_name(id);
4038 error_setg(errp, "Cannot find block backend %s", id);
4041 if (blk_legacy_dinfo(blk)) {
4042 error_setg(errp, "Deleting block backend added with drive-add"
4043 " is not supported");
4046 if (blk_get_refcnt(blk) > 1) {
4047 error_setg(errp, "Block backend %s is in use", id);
4051 aio_context = blk_get_aio_context(blk);
4053 bs = bdrv_find_node(node_name);
4055 error_setg(errp, "Cannot find node %s", node_name);
4060 error_setg(errp, "Node %s is in use by %s",
4061 node_name, blk_name(blk));
4064 aio_context = bdrv_get_aio_context(bs);
4067 aio_context_acquire(aio_context);
4070 if (bdrv_op_is_blocked(bs, BLOCK_OP_TYPE_DRIVE_DEL, errp)) {
4074 if (!blk && !bs->monitor_list.tqe_prev) {
4075 error_setg(errp, "Node %s is not owned by the monitor",
4080 if (bs->refcnt > 1) {
4081 error_setg(errp, "Block device %s is in use",
4082 bdrv_get_device_or_node_name(bs));
4088 monitor_remove_blk(blk);
4091 QTAILQ_REMOVE(&monitor_bdrv_states, bs, monitor_list);
4096 aio_context_release(aio_context);
4099 BlockJobInfoList *qmp_query_block_jobs(Error **errp)
4101 BlockJobInfoList *head = NULL, **p_next = &head;
4102 BlockDriverState *bs;
4104 for (bs = bdrv_next(NULL); bs; bs = bdrv_next(bs)) {
4105 AioContext *aio_context = bdrv_get_aio_context(bs);
4107 aio_context_acquire(aio_context);
4110 BlockJobInfoList *elem = g_new0(BlockJobInfoList, 1);
4111 elem->value = block_job_query(bs->job);
4113 p_next = &elem->next;
4116 aio_context_release(aio_context);
4122 QemuOptsList qemu_common_drive_opts = {
4124 .head = QTAILQ_HEAD_INITIALIZER(qemu_common_drive_opts.head),
4128 .type = QEMU_OPT_BOOL,
4129 .help = "enable/disable snapshot mode",
4132 .type = QEMU_OPT_STRING,
4133 .help = "discard operation (ignore/off, unmap/on)",
4136 .type = QEMU_OPT_STRING,
4137 .help = "host AIO implementation (threads, native)",
4139 .name = BDRV_OPT_CACHE_WB,
4140 .type = QEMU_OPT_BOOL,
4141 .help = "Enable writeback mode",
4144 .type = QEMU_OPT_STRING,
4145 .help = "disk format (raw, qcow2, ...)",
4148 .type = QEMU_OPT_STRING,
4149 .help = "read error action",
4152 .type = QEMU_OPT_STRING,
4153 .help = "write error action",
4155 .name = "read-only",
4156 .type = QEMU_OPT_BOOL,
4157 .help = "open drive file as read-only",
4159 .name = "throttling.iops-total",
4160 .type = QEMU_OPT_NUMBER,
4161 .help = "limit total I/O operations per second",
4163 .name = "throttling.iops-read",
4164 .type = QEMU_OPT_NUMBER,
4165 .help = "limit read operations per second",
4167 .name = "throttling.iops-write",
4168 .type = QEMU_OPT_NUMBER,
4169 .help = "limit write operations per second",
4171 .name = "throttling.bps-total",
4172 .type = QEMU_OPT_NUMBER,
4173 .help = "limit total bytes per second",
4175 .name = "throttling.bps-read",
4176 .type = QEMU_OPT_NUMBER,
4177 .help = "limit read bytes per second",
4179 .name = "throttling.bps-write",
4180 .type = QEMU_OPT_NUMBER,
4181 .help = "limit write bytes per second",
4183 .name = "throttling.iops-total-max",
4184 .type = QEMU_OPT_NUMBER,
4185 .help = "I/O operations burst",
4187 .name = "throttling.iops-read-max",
4188 .type = QEMU_OPT_NUMBER,
4189 .help = "I/O operations read burst",
4191 .name = "throttling.iops-write-max",
4192 .type = QEMU_OPT_NUMBER,
4193 .help = "I/O operations write burst",
4195 .name = "throttling.bps-total-max",
4196 .type = QEMU_OPT_NUMBER,
4197 .help = "total bytes burst",
4199 .name = "throttling.bps-read-max",
4200 .type = QEMU_OPT_NUMBER,
4201 .help = "total bytes read burst",
4203 .name = "throttling.bps-write-max",
4204 .type = QEMU_OPT_NUMBER,
4205 .help = "total bytes write burst",
4207 .name = "throttling.iops-total-max-length",
4208 .type = QEMU_OPT_NUMBER,
4209 .help = "length of the iops-total-max burst period, in seconds",
4211 .name = "throttling.iops-read-max-length",
4212 .type = QEMU_OPT_NUMBER,
4213 .help = "length of the iops-read-max burst period, in seconds",
4215 .name = "throttling.iops-write-max-length",
4216 .type = QEMU_OPT_NUMBER,
4217 .help = "length of the iops-write-max burst period, in seconds",
4219 .name = "throttling.bps-total-max-length",
4220 .type = QEMU_OPT_NUMBER,
4221 .help = "length of the bps-total-max burst period, in seconds",
4223 .name = "throttling.bps-read-max-length",
4224 .type = QEMU_OPT_NUMBER,
4225 .help = "length of the bps-read-max burst period, in seconds",
4227 .name = "throttling.bps-write-max-length",
4228 .type = QEMU_OPT_NUMBER,
4229 .help = "length of the bps-write-max burst period, in seconds",
4231 .name = "throttling.iops-size",
4232 .type = QEMU_OPT_NUMBER,
4233 .help = "when limiting by iops max size of an I/O in bytes",
4235 .name = "throttling.group",
4236 .type = QEMU_OPT_STRING,
4237 .help = "name of the block throttling group",
4239 .name = "copy-on-read",
4240 .type = QEMU_OPT_BOOL,
4241 .help = "copy read data from backing file into image file",
4243 .name = "detect-zeroes",
4244 .type = QEMU_OPT_STRING,
4245 .help = "try to optimize zero writes (off, on, unmap)",
4247 .name = "stats-account-invalid",
4248 .type = QEMU_OPT_BOOL,
4249 .help = "whether to account for invalid I/O operations "
4250 "in the statistics",
4252 .name = "stats-account-failed",
4253 .type = QEMU_OPT_BOOL,
4254 .help = "whether to account for failed I/O operations "
4255 "in the statistics",
4257 { /* end of list */ }
4261 static QemuOptsList qemu_root_bds_opts = {
4263 .head = QTAILQ_HEAD_INITIALIZER(qemu_root_bds_opts.head),
4267 .type = QEMU_OPT_STRING,
4268 .help = "discard operation (ignore/off, unmap/on)",
4271 .type = QEMU_OPT_STRING,
4272 .help = "host AIO implementation (threads, native)",
4274 .name = "read-only",
4275 .type = QEMU_OPT_BOOL,
4276 .help = "open drive file as read-only",
4278 .name = "copy-on-read",
4279 .type = QEMU_OPT_BOOL,
4280 .help = "copy read data from backing file into image file",
4282 .name = "detect-zeroes",
4283 .type = QEMU_OPT_STRING,
4284 .help = "try to optimize zero writes (off, on, unmap)",
4286 { /* end of list */ }
4290 QemuOptsList qemu_drive_opts = {
4292 .head = QTAILQ_HEAD_INITIALIZER(qemu_drive_opts.head),
4295 * no elements => accept any params
4296 * validation will happen later
4298 { /* end of list */ }