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 "sysemu/block-backend.h"
34 #include "sysemu/blockdev.h"
35 #include "hw/block/block.h"
36 #include "block/blockjob.h"
37 #include "block/throttle-groups.h"
38 #include "monitor/monitor.h"
39 #include "qemu/error-report.h"
40 #include "qemu/option.h"
41 #include "qemu/config-file.h"
42 #include "qapi/qmp/types.h"
43 #include "qapi-visit.h"
44 #include "qapi/qmp/qerror.h"
45 #include "qapi/qmp-output-visitor.h"
46 #include "qapi/util.h"
47 #include "sysemu/sysemu.h"
48 #include "block/block_int.h"
49 #include "qmp-commands.h"
51 #include "sysemu/arch_init.h"
54 #include "tizen/src/util/exported_strings.h"
57 static const char *const if_name[IF_COUNT] = {
61 [IF_FLOPPY] = "floppy",
62 [IF_PFLASH] = "pflash",
65 [IF_VIRTIO] = "virtio",
69 static int if_max_devs[IF_COUNT] = {
71 * Do not change these numbers! They govern how drive option
72 * index maps to unit and bus. That mapping is ABI.
74 * All controllers used to imlement if=T drives need to support
75 * if_max_devs[T] units, for any T with if_max_devs[T] != 0.
76 * Otherwise, some index values map to "impossible" bus, unit
79 * For instance, if you change [IF_SCSI] to 255, -drive
80 * if=scsi,index=12 no longer means bus=1,unit=5, but
81 * bus=0,unit=12. With an lsi53c895a controller (7 units max),
82 * the drive can't be set up. Regression.
89 * Boards may call this to offer board-by-board overrides
90 * of the default, global values.
92 void override_max_devs(BlockInterfaceType type, int max_devs)
101 for (blk = blk_next(NULL); blk; blk = blk_next(blk)) {
102 dinfo = blk_legacy_dinfo(blk);
103 if (dinfo->type == type) {
104 fprintf(stderr, "Cannot override units-per-bus property of"
105 " the %s interface, because a drive of that type has"
106 " already been added.\n", if_name[type]);
107 g_assert_not_reached();
111 if_max_devs[type] = max_devs;
115 * We automatically delete the drive when a device using it gets
116 * unplugged. Questionable feature, but we can't just drop it.
117 * Device models call blockdev_mark_auto_del() to schedule the
118 * automatic deletion, and generic qdev code calls blockdev_auto_del()
119 * when deletion is actually safe.
121 void blockdev_mark_auto_del(BlockBackend *blk)
123 DriveInfo *dinfo = blk_legacy_dinfo(blk);
124 BlockDriverState *bs = blk_bs(blk);
125 AioContext *aio_context;
132 aio_context = bdrv_get_aio_context(bs);
133 aio_context_acquire(aio_context);
136 block_job_cancel(bs->job);
139 aio_context_release(aio_context);
145 void blockdev_auto_del(BlockBackend *blk)
147 DriveInfo *dinfo = blk_legacy_dinfo(blk);
149 if (dinfo && dinfo->auto_del) {
155 * Returns the current mapping of how many units per bus
156 * a particular interface can support.
158 * A positive integer indicates n units per bus.
159 * 0 implies the mapping has not been established.
160 * -1 indicates an invalid BlockInterfaceType was given.
162 int drive_get_max_devs(BlockInterfaceType type)
164 if (type >= IF_IDE && type < IF_COUNT) {
165 return if_max_devs[type];
171 static int drive_index_to_bus_id(BlockInterfaceType type, int index)
173 int max_devs = if_max_devs[type];
174 return max_devs ? index / max_devs : 0;
177 static int drive_index_to_unit_id(BlockInterfaceType type, int index)
179 int max_devs = if_max_devs[type];
180 return max_devs ? index % max_devs : index;
183 QemuOpts *drive_def(const char *optstr)
185 return qemu_opts_parse_noisily(qemu_find_opts("drive"), optstr, false);
188 QemuOpts *drive_add(BlockInterfaceType type, int index, const char *file,
193 opts = drive_def(optstr);
197 if (type != IF_DEFAULT) {
198 qemu_opt_set(opts, "if", if_name[type], &error_abort);
201 qemu_opt_set_number(opts, "index", index, &error_abort);
204 qemu_opt_set(opts, "file", file, &error_abort);
208 DriveInfo *drive_get(BlockInterfaceType type, int bus, int unit)
213 for (blk = blk_next(NULL); blk; blk = blk_next(blk)) {
214 dinfo = blk_legacy_dinfo(blk);
215 if (dinfo && dinfo->type == type
216 && dinfo->bus == bus && dinfo->unit == unit) {
224 bool drive_check_orphaned(void)
230 for (blk = blk_next(NULL); blk; blk = blk_next(blk)) {
231 dinfo = blk_legacy_dinfo(blk);
232 /* If dinfo->bdrv->dev is NULL, it has no device attached. */
233 /* Unless this is a default drive, this may be an oversight. */
234 if (!blk_get_attached_dev(blk) && !dinfo->is_default &&
235 dinfo->type != IF_NONE) {
236 fprintf(stderr, "Warning: Orphaned drive without device: "
237 "id=%s,file=%s,if=%s,bus=%d,unit=%d\n",
238 blk_name(blk), blk_bs(blk) ? blk_bs(blk)->filename : "",
239 if_name[dinfo->type], dinfo->bus, dinfo->unit);
247 DriveInfo *drive_get_by_index(BlockInterfaceType type, int index)
249 return drive_get(type,
250 drive_index_to_bus_id(type, index),
251 drive_index_to_unit_id(type, index));
254 int drive_get_max_bus(BlockInterfaceType type)
261 for (blk = blk_next(NULL); blk; blk = blk_next(blk)) {
262 dinfo = blk_legacy_dinfo(blk);
263 if (dinfo && dinfo->type == type && dinfo->bus > max_bus) {
264 max_bus = dinfo->bus;
270 /* Get a block device. This should only be used for single-drive devices
271 (e.g. SD/Floppy/MTD). Multi-disk devices (scsi/ide) should use the
273 DriveInfo *drive_get_next(BlockInterfaceType type)
275 static int next_block_unit[IF_COUNT];
277 return drive_get(type, 0, next_block_unit[type]++);
280 static void bdrv_format_print(void *opaque, const char *name)
282 error_printf(" %s", name);
287 BlockDriverState *bs;
290 static int parse_block_error_action(const char *buf, bool is_read, Error **errp)
292 if (!strcmp(buf, "ignore")) {
293 return BLOCKDEV_ON_ERROR_IGNORE;
294 } else if (!is_read && !strcmp(buf, "enospc")) {
295 return BLOCKDEV_ON_ERROR_ENOSPC;
296 } else if (!strcmp(buf, "stop")) {
297 return BLOCKDEV_ON_ERROR_STOP;
298 } else if (!strcmp(buf, "report")) {
299 return BLOCKDEV_ON_ERROR_REPORT;
301 error_setg(errp, "'%s' invalid %s error action",
302 buf, is_read ? "read" : "write");
307 static bool parse_stats_intervals(BlockAcctStats *stats, QList *intervals,
310 const QListEntry *entry;
311 for (entry = qlist_first(intervals); entry; entry = qlist_next(entry)) {
312 switch (qobject_type(entry->value)) {
314 case QTYPE_QSTRING: {
315 unsigned long long length;
316 const char *str = qstring_get_str(qobject_to_qstring(entry->value));
317 if (parse_uint_full(str, &length, 10) == 0 &&
318 length > 0 && length <= UINT_MAX) {
319 block_acct_add_interval(stats, (unsigned) length);
321 error_setg(errp, "Invalid interval length: %s", str);
328 int64_t length = qint_get_int(qobject_to_qint(entry->value));
329 if (length > 0 && length <= UINT_MAX) {
330 block_acct_add_interval(stats, (unsigned) length);
332 error_setg(errp, "Invalid interval length: %" PRId64, length);
339 error_setg(errp, "The specification of stats-intervals is invalid");
346 static bool check_throttle_config(ThrottleConfig *cfg, Error **errp)
348 if (throttle_conflicting(cfg)) {
349 error_setg(errp, "bps/iops/max total values and read/write values"
350 " cannot be used at the same time");
354 if (!throttle_is_valid(cfg)) {
355 error_setg(errp, "bps/iops/maxs values must be 0 or greater");
359 if (throttle_max_is_missing_limit(cfg)) {
360 error_setg(errp, "bps_max/iops_max require corresponding"
368 typedef enum { MEDIA_DISK, MEDIA_CDROM } DriveMediaType;
370 /* All parameters but @opts are optional and may be set to NULL. */
371 static void extract_common_blockdev_options(QemuOpts *opts, int *bdrv_flags,
372 const char **throttling_group, ThrottleConfig *throttle_cfg,
373 BlockdevDetectZeroesOptions *detect_zeroes, Error **errp)
376 Error *local_error = NULL;
380 if (!qemu_opt_get_bool(opts, "read-only", false)) {
381 *bdrv_flags |= BDRV_O_RDWR;
383 if (qemu_opt_get_bool(opts, "copy-on-read", false)) {
384 *bdrv_flags |= BDRV_O_COPY_ON_READ;
387 if ((discard = qemu_opt_get(opts, "discard")) != NULL) {
388 if (bdrv_parse_discard_flags(discard, bdrv_flags) != 0) {
389 error_setg(errp, "Invalid discard option");
394 if (qemu_opt_get_bool(opts, BDRV_OPT_CACHE_WB, true)) {
395 *bdrv_flags |= BDRV_O_CACHE_WB;
397 if (qemu_opt_get_bool(opts, BDRV_OPT_CACHE_DIRECT, false)) {
398 *bdrv_flags |= BDRV_O_NOCACHE;
400 if (qemu_opt_get_bool(opts, BDRV_OPT_CACHE_NO_FLUSH, false)) {
401 *bdrv_flags |= BDRV_O_NO_FLUSH;
404 if ((aio = qemu_opt_get(opts, "aio")) != NULL) {
405 if (!strcmp(aio, "native")) {
406 *bdrv_flags |= BDRV_O_NATIVE_AIO;
407 } else if (!strcmp(aio, "threads")) {
408 /* this is the default */
410 error_setg(errp, "invalid aio option");
416 /* disk I/O throttling */
417 if (throttling_group) {
418 *throttling_group = qemu_opt_get(opts, "throttling.group");
422 memset(throttle_cfg, 0, sizeof(*throttle_cfg));
423 throttle_cfg->buckets[THROTTLE_BPS_TOTAL].avg =
424 qemu_opt_get_number(opts, "throttling.bps-total", 0);
425 throttle_cfg->buckets[THROTTLE_BPS_READ].avg =
426 qemu_opt_get_number(opts, "throttling.bps-read", 0);
427 throttle_cfg->buckets[THROTTLE_BPS_WRITE].avg =
428 qemu_opt_get_number(opts, "throttling.bps-write", 0);
429 throttle_cfg->buckets[THROTTLE_OPS_TOTAL].avg =
430 qemu_opt_get_number(opts, "throttling.iops-total", 0);
431 throttle_cfg->buckets[THROTTLE_OPS_READ].avg =
432 qemu_opt_get_number(opts, "throttling.iops-read", 0);
433 throttle_cfg->buckets[THROTTLE_OPS_WRITE].avg =
434 qemu_opt_get_number(opts, "throttling.iops-write", 0);
436 throttle_cfg->buckets[THROTTLE_BPS_TOTAL].max =
437 qemu_opt_get_number(opts, "throttling.bps-total-max", 0);
438 throttle_cfg->buckets[THROTTLE_BPS_READ].max =
439 qemu_opt_get_number(opts, "throttling.bps-read-max", 0);
440 throttle_cfg->buckets[THROTTLE_BPS_WRITE].max =
441 qemu_opt_get_number(opts, "throttling.bps-write-max", 0);
442 throttle_cfg->buckets[THROTTLE_OPS_TOTAL].max =
443 qemu_opt_get_number(opts, "throttling.iops-total-max", 0);
444 throttle_cfg->buckets[THROTTLE_OPS_READ].max =
445 qemu_opt_get_number(opts, "throttling.iops-read-max", 0);
446 throttle_cfg->buckets[THROTTLE_OPS_WRITE].max =
447 qemu_opt_get_number(opts, "throttling.iops-write-max", 0);
449 throttle_cfg->op_size =
450 qemu_opt_get_number(opts, "throttling.iops-size", 0);
452 if (!check_throttle_config(throttle_cfg, errp)) {
459 qapi_enum_parse(BlockdevDetectZeroesOptions_lookup,
460 qemu_opt_get(opts, "detect-zeroes"),
461 BLOCKDEV_DETECT_ZEROES_OPTIONS_MAX,
462 BLOCKDEV_DETECT_ZEROES_OPTIONS_OFF,
465 error_propagate(errp, local_error);
470 *detect_zeroes == BLOCKDEV_DETECT_ZEROES_OPTIONS_UNMAP &&
471 !(*bdrv_flags & BDRV_O_UNMAP))
473 error_setg(errp, "setting detect-zeroes to unmap is not allowed "
474 "without setting discard operation to unmap");
480 /* Takes the ownership of bs_opts */
481 static BlockBackend *blockdev_init(const char *file, QDict *bs_opts,
486 int on_read_error, on_write_error;
487 bool account_invalid, account_failed;
489 BlockDriverState *bs;
494 QDict *interval_dict = NULL;
495 QList *interval_list = NULL;
497 bool has_driver_specific_opts;
498 BlockdevDetectZeroesOptions detect_zeroes =
499 BLOCKDEV_DETECT_ZEROES_OPTIONS_OFF;
500 const char *throttling_group = NULL;
502 /* Check common options by copying from bs_opts to opts, all other options
503 * stay in bs_opts for processing by bdrv_open(). */
504 id = qdict_get_try_str(bs_opts, "id");
505 opts = qemu_opts_create(&qemu_common_drive_opts, id, 1, &error);
507 error_propagate(errp, error);
511 qemu_opts_absorb_qdict(opts, bs_opts, &error);
513 error_propagate(errp, error);
518 qdict_del(bs_opts, "id");
521 has_driver_specific_opts = !!qdict_size(bs_opts);
523 /* extract parameters */
524 snapshot = qemu_opt_get_bool(opts, "snapshot", 0);
526 account_invalid = qemu_opt_get_bool(opts, "stats-account-invalid", true);
527 account_failed = qemu_opt_get_bool(opts, "stats-account-failed", true);
529 qdict_extract_subqdict(bs_opts, &interval_dict, "stats-intervals.");
530 qdict_array_split(interval_dict, &interval_list);
532 if (qdict_size(interval_dict) != 0) {
533 error_setg(errp, "Invalid option stats-intervals.%s",
534 qdict_first(interval_dict)->key);
538 extract_common_blockdev_options(opts, &bdrv_flags, &throttling_group, &cfg,
539 &detect_zeroes, &error);
541 error_propagate(errp, error);
545 if ((buf = qemu_opt_get(opts, "format")) != NULL) {
546 if (is_help_option(buf)) {
547 error_printf("Supported formats:");
548 bdrv_iterate_format(bdrv_format_print, NULL);
553 if (qdict_haskey(bs_opts, "driver")) {
554 error_setg(errp, "Cannot specify both 'driver' and 'format'");
557 qdict_put(bs_opts, "driver", qstring_from_str(buf));
560 on_write_error = BLOCKDEV_ON_ERROR_ENOSPC;
561 if ((buf = qemu_opt_get(opts, "werror")) != NULL) {
562 on_write_error = parse_block_error_action(buf, 0, &error);
564 error_propagate(errp, error);
569 on_read_error = BLOCKDEV_ON_ERROR_REPORT;
570 if ((buf = qemu_opt_get(opts, "rerror")) != NULL) {
571 on_read_error = parse_block_error_action(buf, 1, &error);
573 error_propagate(errp, error);
579 /* always use cache=unsafe with snapshot */
580 bdrv_flags &= ~BDRV_O_CACHE_MASK;
581 bdrv_flags |= (BDRV_O_SNAPSHOT|BDRV_O_CACHE_WB|BDRV_O_NO_FLUSH);
585 if ((!file || !*file) && !has_driver_specific_opts) {
586 BlockBackendRootState *blk_rs;
588 blk = blk_new(qemu_opts_id(opts), errp);
593 blk_rs = blk_get_root_state(blk);
594 blk_rs->open_flags = bdrv_flags;
595 blk_rs->read_only = !(bdrv_flags & BDRV_O_RDWR);
596 blk_rs->detect_zeroes = detect_zeroes;
598 if (throttle_enabled(&cfg)) {
599 if (!throttling_group) {
600 throttling_group = blk_name(blk);
602 blk_rs->throttle_group = g_strdup(throttling_group);
603 blk_rs->throttle_state = throttle_group_incref(throttling_group);
604 blk_rs->throttle_state->cfg = cfg;
609 if (file && !*file) {
613 blk = blk_new_open(qemu_opts_id(opts), file, NULL, bs_opts, bdrv_flags,
620 bs->detect_zeroes = detect_zeroes;
622 /* disk I/O throttling */
623 if (throttle_enabled(&cfg)) {
624 if (!throttling_group) {
625 throttling_group = blk_name(blk);
627 bdrv_io_limits_enable(bs, throttling_group);
628 bdrv_set_io_limits(bs, &cfg);
631 if (bdrv_key_required(bs)) {
635 block_acct_init(blk_get_stats(blk), account_invalid, account_failed);
637 if (!parse_stats_intervals(blk_get_stats(blk), interval_list, errp)) {
644 blk_set_on_error(blk, on_read_error, on_write_error);
648 QDECREF(interval_dict);
649 QDECREF(interval_list);
654 QDECREF(interval_dict);
655 QDECREF(interval_list);
661 static QemuOptsList qemu_root_bds_opts;
663 /* Takes the ownership of bs_opts */
664 static BlockDriverState *bds_tree_init(QDict *bs_opts, Error **errp)
666 BlockDriverState *bs;
668 Error *local_error = NULL;
669 BlockdevDetectZeroesOptions detect_zeroes;
673 opts = qemu_opts_create(&qemu_root_bds_opts, NULL, 1, errp);
678 qemu_opts_absorb_qdict(opts, bs_opts, &local_error);
680 error_propagate(errp, local_error);
684 extract_common_blockdev_options(opts, &bdrv_flags, NULL, NULL,
685 &detect_zeroes, &local_error);
687 error_propagate(errp, local_error);
692 ret = bdrv_open(&bs, NULL, NULL, bs_opts, bdrv_flags, errp);
694 goto fail_no_bs_opts;
697 bs->detect_zeroes = detect_zeroes;
709 static void qemu_opt_rename(QemuOpts *opts, const char *from, const char *to,
714 value = qemu_opt_get(opts, from);
716 if (qemu_opt_find(opts, to)) {
717 error_setg(errp, "'%s' and its alias '%s' can't be used at the "
718 "same time", to, from);
723 /* rename all items in opts */
724 while ((value = qemu_opt_get(opts, from))) {
725 qemu_opt_set(opts, to, value, &error_abort);
726 qemu_opt_unset(opts, from);
730 QemuOptsList qemu_legacy_drive_opts = {
732 .head = QTAILQ_HEAD_INITIALIZER(qemu_legacy_drive_opts.head),
736 .type = QEMU_OPT_NUMBER,
737 .help = "bus number",
740 .type = QEMU_OPT_NUMBER,
741 .help = "unit number (i.e. lun for scsi)",
744 .type = QEMU_OPT_NUMBER,
745 .help = "index number",
748 .type = QEMU_OPT_STRING,
749 .help = "media type (disk, cdrom)",
752 .type = QEMU_OPT_STRING,
753 .help = "interface (ide, scsi, sd, mtd, floppy, pflash, virtio)",
756 .type = QEMU_OPT_NUMBER,
757 .help = "number of cylinders (ide disk geometry)",
760 .type = QEMU_OPT_NUMBER,
761 .help = "number of heads (ide disk geometry)",
764 .type = QEMU_OPT_NUMBER,
765 .help = "number of sectors (ide disk geometry)",
768 .type = QEMU_OPT_STRING,
769 .help = "chs translation (auto, lba, none)",
772 .type = QEMU_OPT_BOOL,
773 .help = "(deprecated, ignored)",
776 .type = QEMU_OPT_STRING,
777 .help = "pci address (virtio only)",
780 .type = QEMU_OPT_STRING,
781 .help = "disk serial number",
784 .type = QEMU_OPT_STRING,
788 /* Options that are passed on, but have special semantics with -drive */
791 .type = QEMU_OPT_BOOL,
792 .help = "open drive file as read-only",
795 .type = QEMU_OPT_STRING,
796 .help = "read error action",
799 .type = QEMU_OPT_STRING,
800 .help = "write error action",
802 .name = "copy-on-read",
803 .type = QEMU_OPT_BOOL,
804 .help = "copy read data from backing file into image file",
807 { /* end of list */ }
811 DriveInfo *drive_new(QemuOpts *all_opts, BlockInterfaceType block_default_type)
815 DriveInfo *dinfo = NULL;
817 QemuOpts *legacy_opts;
818 DriveMediaType media = MEDIA_DISK;
819 BlockInterfaceType type;
820 int cyls, heads, secs, translation;
821 int max_devs, bus_id, unit_id, index;
823 const char *werror, *rerror;
824 bool read_only = false;
827 const char *filename;
828 Error *local_err = NULL;
831 /* Change legacy command line options into QMP ones */
832 static const struct {
836 { "iops", "throttling.iops-total" },
837 { "iops_rd", "throttling.iops-read" },
838 { "iops_wr", "throttling.iops-write" },
840 { "bps", "throttling.bps-total" },
841 { "bps_rd", "throttling.bps-read" },
842 { "bps_wr", "throttling.bps-write" },
844 { "iops_max", "throttling.iops-total-max" },
845 { "iops_rd_max", "throttling.iops-read-max" },
846 { "iops_wr_max", "throttling.iops-write-max" },
848 { "bps_max", "throttling.bps-total-max" },
849 { "bps_rd_max", "throttling.bps-read-max" },
850 { "bps_wr_max", "throttling.bps-write-max" },
852 { "iops_size", "throttling.iops-size" },
854 { "group", "throttling.group" },
856 { "readonly", "read-only" },
859 for (i = 0; i < ARRAY_SIZE(opt_renames); i++) {
860 qemu_opt_rename(all_opts, opt_renames[i].from, opt_renames[i].to,
863 error_report_err(local_err);
868 value = qemu_opt_get(all_opts, "cache");
872 if (bdrv_parse_cache_flags(value, &flags) != 0) {
873 error_report("invalid cache option");
877 /* Specific options take precedence */
878 if (!qemu_opt_get(all_opts, BDRV_OPT_CACHE_WB)) {
879 qemu_opt_set_bool(all_opts, BDRV_OPT_CACHE_WB,
880 !!(flags & BDRV_O_CACHE_WB), &error_abort);
882 if (!qemu_opt_get(all_opts, BDRV_OPT_CACHE_DIRECT)) {
883 qemu_opt_set_bool(all_opts, BDRV_OPT_CACHE_DIRECT,
884 !!(flags & BDRV_O_NOCACHE), &error_abort);
886 if (!qemu_opt_get(all_opts, BDRV_OPT_CACHE_NO_FLUSH)) {
887 qemu_opt_set_bool(all_opts, BDRV_OPT_CACHE_NO_FLUSH,
888 !!(flags & BDRV_O_NO_FLUSH), &error_abort);
890 qemu_opt_unset(all_opts, "cache");
893 /* Get a QDict for processing the options */
894 bs_opts = qdict_new();
895 qemu_opts_to_qdict(all_opts, bs_opts);
897 legacy_opts = qemu_opts_create(&qemu_legacy_drive_opts, NULL, 0,
899 qemu_opts_absorb_qdict(legacy_opts, bs_opts, &local_err);
901 error_report_err(local_err);
905 /* Deprecated option boot=[on|off] */
906 if (qemu_opt_get(legacy_opts, "boot") != NULL) {
907 fprintf(stderr, "qemu-kvm: boot=on|off is deprecated and will be "
908 "ignored. Future versions will reject this parameter. Please "
909 "update your scripts.\n");
913 value = qemu_opt_get(legacy_opts, "media");
915 if (!strcmp(value, "disk")) {
917 } else if (!strcmp(value, "cdrom")) {
921 error_report("'%s' invalid media", value);
926 /* copy-on-read is disabled with a warning for read-only devices */
927 read_only |= qemu_opt_get_bool(legacy_opts, "read-only", false);
928 copy_on_read = qemu_opt_get_bool(legacy_opts, "copy-on-read", false);
930 if (read_only && copy_on_read) {
931 error_report("warning: disabling copy-on-read on read-only drive");
932 copy_on_read = false;
935 qdict_put(bs_opts, "read-only",
936 qstring_from_str(read_only ? "on" : "off"));
937 qdict_put(bs_opts, "copy-on-read",
938 qstring_from_str(copy_on_read ? "on" :"off"));
940 /* Controller type */
941 value = qemu_opt_get(legacy_opts, "if");
944 type < IF_COUNT && strcmp(value, if_name[type]);
947 if (type == IF_COUNT) {
948 error_report("unsupported bus type '%s'", value);
952 type = block_default_type;
956 cyls = qemu_opt_get_number(legacy_opts, "cyls", 0);
957 heads = qemu_opt_get_number(legacy_opts, "heads", 0);
958 secs = qemu_opt_get_number(legacy_opts, "secs", 0);
960 if (cyls || heads || secs) {
962 error_report("invalid physical cyls number");
966 error_report("invalid physical heads number");
970 error_report("invalid physical secs number");
975 translation = BIOS_ATA_TRANSLATION_AUTO;
976 value = qemu_opt_get(legacy_opts, "trans");
979 error_report("'%s' trans must be used with cyls, heads and secs",
983 if (!strcmp(value, "none")) {
984 translation = BIOS_ATA_TRANSLATION_NONE;
985 } else if (!strcmp(value, "lba")) {
986 translation = BIOS_ATA_TRANSLATION_LBA;
987 } else if (!strcmp(value, "large")) {
988 translation = BIOS_ATA_TRANSLATION_LARGE;
989 } else if (!strcmp(value, "rechs")) {
990 translation = BIOS_ATA_TRANSLATION_RECHS;
991 } else if (!strcmp(value, "auto")) {
992 translation = BIOS_ATA_TRANSLATION_AUTO;
994 error_report("'%s' invalid translation type", value);
999 if (media == MEDIA_CDROM) {
1000 if (cyls || secs || heads) {
1001 error_report("CHS can't be set with media=cdrom");
1006 /* Device address specified by bus/unit or index.
1007 * If none was specified, try to find the first free one. */
1008 bus_id = qemu_opt_get_number(legacy_opts, "bus", 0);
1009 unit_id = qemu_opt_get_number(legacy_opts, "unit", -1);
1010 index = qemu_opt_get_number(legacy_opts, "index", -1);
1012 max_devs = if_max_devs[type];
1015 if (bus_id != 0 || unit_id != -1) {
1016 error_report("index cannot be used with bus and unit");
1019 bus_id = drive_index_to_bus_id(type, index);
1020 unit_id = drive_index_to_unit_id(type, index);
1023 if (unit_id == -1) {
1025 while (drive_get(type, bus_id, unit_id) != NULL) {
1027 if (max_devs && unit_id >= max_devs) {
1028 unit_id -= max_devs;
1034 if (max_devs && unit_id >= max_devs) {
1035 error_report("unit %d too big (max is %d)", unit_id, max_devs - 1);
1039 if (drive_get(type, bus_id, unit_id) != NULL) {
1040 error_report("drive with bus=%d, unit=%d (index=%d) exists",
1041 bus_id, unit_id, index);
1046 serial = qemu_opt_get(legacy_opts, "serial");
1048 /* no id supplied -> create one */
1049 if (qemu_opts_id(all_opts) == NULL) {
1051 const char *mediastr = "";
1052 if (type == IF_IDE || type == IF_SCSI) {
1053 mediastr = (media == MEDIA_CDROM) ? "-cd" : "-hd";
1056 new_id = g_strdup_printf("%s%i%s%i", if_name[type], bus_id,
1059 new_id = g_strdup_printf("%s%s%i", if_name[type],
1062 qdict_put(bs_opts, "id", qstring_from_str(new_id));
1066 /* Add virtio block device */
1067 devaddr = qemu_opt_get(legacy_opts, "addr");
1068 if (devaddr && type != IF_VIRTIO) {
1069 error_report("addr is not supported by this bus type");
1073 if (type == IF_VIRTIO) {
1075 devopts = qemu_opts_create(qemu_find_opts("device"), NULL, 0,
1077 if (arch_type == QEMU_ARCH_S390X) {
1078 qemu_opt_set(devopts, "driver", "virtio-blk-ccw", &error_abort);
1080 qemu_opt_set(devopts, "driver", "virtio-blk-pci", &error_abort);
1082 qemu_opt_set(devopts, "drive", qdict_get_str(bs_opts, "id"),
1085 qemu_opt_set(devopts, "addr", devaddr, &error_abort);
1089 filename = qemu_opt_get(legacy_opts, "file");
1091 /* Check werror/rerror compatibility with if=... */
1092 werror = qemu_opt_get(legacy_opts, "werror");
1093 if (werror != NULL) {
1094 if (type != IF_IDE && type != IF_SCSI && type != IF_VIRTIO &&
1096 error_report("werror is not supported by this bus type");
1099 qdict_put(bs_opts, "werror", qstring_from_str(werror));
1102 rerror = qemu_opt_get(legacy_opts, "rerror");
1103 if (rerror != NULL) {
1104 if (type != IF_IDE && type != IF_VIRTIO && type != IF_SCSI &&
1106 error_report("rerror is not supported by this bus type");
1109 qdict_put(bs_opts, "rerror", qstring_from_str(rerror));
1112 /* Actual block device init: Functionality shared with blockdev-add */
1113 blk = blockdev_init(filename, bs_opts, &local_err);
1117 error_report_err(local_err);
1124 /* Create legacy DriveInfo */
1125 dinfo = g_malloc0(sizeof(*dinfo));
1126 dinfo->opts = all_opts;
1129 dinfo->heads = heads;
1131 dinfo->trans = translation;
1134 dinfo->bus = bus_id;
1135 dinfo->unit = unit_id;
1136 dinfo->devaddr = devaddr;
1137 dinfo->serial = g_strdup(serial);
1139 blk_set_legacy_dinfo(blk, dinfo);
1146 dinfo->media_cd = media == MEDIA_CDROM;
1153 qemu_opts_del(legacy_opts);
1158 void hmp_commit(Monitor *mon, const QDict *qdict)
1160 const char *device = qdict_get_str(qdict, "device");
1164 if (!strcmp(device, "all")) {
1165 ret = bdrv_commit_all();
1167 BlockDriverState *bs;
1168 AioContext *aio_context;
1170 blk = blk_by_name(device);
1172 monitor_printf(mon, "Device '%s' not found\n", device);
1175 if (!blk_is_available(blk)) {
1176 monitor_printf(mon, "Device '%s' has no medium\n", device);
1181 aio_context = bdrv_get_aio_context(bs);
1182 aio_context_acquire(aio_context);
1184 ret = bdrv_commit(bs);
1186 aio_context_release(aio_context);
1189 monitor_printf(mon, "'commit' error for '%s': %s\n", device,
1194 static void blockdev_do_action(TransactionActionKind type, void *data,
1197 TransactionAction action;
1198 TransactionActionList list;
1201 action.u.data = data;
1202 list.value = &action;
1204 qmp_transaction(&list, false, NULL, errp);
1207 void qmp_blockdev_snapshot_sync(bool has_device, const char *device,
1208 bool has_node_name, const char *node_name,
1209 const char *snapshot_file,
1210 bool has_snapshot_node_name,
1211 const char *snapshot_node_name,
1212 bool has_format, const char *format,
1213 bool has_mode, NewImageMode mode, Error **errp)
1215 BlockdevSnapshotSync snapshot = {
1216 .has_device = has_device,
1217 .device = (char *) device,
1218 .has_node_name = has_node_name,
1219 .node_name = (char *) node_name,
1220 .snapshot_file = (char *) snapshot_file,
1221 .has_snapshot_node_name = has_snapshot_node_name,
1222 .snapshot_node_name = (char *) snapshot_node_name,
1223 .has_format = has_format,
1224 .format = (char *) format,
1225 .has_mode = has_mode,
1228 blockdev_do_action(TRANSACTION_ACTION_KIND_BLOCKDEV_SNAPSHOT_SYNC,
1232 void qmp_blockdev_snapshot(const char *node, const char *overlay,
1235 BlockdevSnapshot snapshot_data = {
1236 .node = (char *) node,
1237 .overlay = (char *) overlay
1240 blockdev_do_action(TRANSACTION_ACTION_KIND_BLOCKDEV_SNAPSHOT,
1241 &snapshot_data, errp);
1244 void qmp_blockdev_snapshot_internal_sync(const char *device,
1248 BlockdevSnapshotInternal snapshot = {
1249 .device = (char *) device,
1250 .name = (char *) name
1253 blockdev_do_action(TRANSACTION_ACTION_KIND_BLOCKDEV_SNAPSHOT_INTERNAL_SYNC,
1257 SnapshotInfo *qmp_blockdev_snapshot_delete_internal_sync(const char *device,
1264 BlockDriverState *bs;
1266 AioContext *aio_context;
1267 QEMUSnapshotInfo sn;
1268 Error *local_err = NULL;
1269 SnapshotInfo *info = NULL;
1272 blk = blk_by_name(device);
1274 error_set(errp, ERROR_CLASS_DEVICE_NOT_FOUND,
1275 "Device '%s' not found", device);
1279 aio_context = blk_get_aio_context(blk);
1280 aio_context_acquire(aio_context);
1291 error_setg(errp, "Name or id must be provided");
1292 goto out_aio_context;
1295 if (!blk_is_available(blk)) {
1296 error_setg(errp, "Device '%s' has no medium", device);
1297 goto out_aio_context;
1301 if (bdrv_op_is_blocked(bs, BLOCK_OP_TYPE_INTERNAL_SNAPSHOT_DELETE, errp)) {
1302 goto out_aio_context;
1305 ret = bdrv_snapshot_find_by_id_and_name(bs, id, name, &sn, &local_err);
1307 error_propagate(errp, local_err);
1308 goto out_aio_context;
1312 "Snapshot with id '%s' and name '%s' does not exist on "
1314 STR_OR_NULL(id), STR_OR_NULL(name), device);
1315 goto out_aio_context;
1318 bdrv_snapshot_delete(bs, id, name, &local_err);
1320 error_propagate(errp, local_err);
1321 goto out_aio_context;
1324 aio_context_release(aio_context);
1326 info = g_new0(SnapshotInfo, 1);
1327 info->id = g_strdup(sn.id_str);
1328 info->name = g_strdup(sn.name);
1329 info->date_nsec = sn.date_nsec;
1330 info->date_sec = sn.date_sec;
1331 info->vm_state_size = sn.vm_state_size;
1332 info->vm_clock_nsec = sn.vm_clock_nsec % 1000000000;
1333 info->vm_clock_sec = sn.vm_clock_nsec / 1000000000;
1338 aio_context_release(aio_context);
1343 * block_dirty_bitmap_lookup:
1344 * Return a dirty bitmap (if present), after validating
1345 * the node reference and bitmap names.
1347 * @node: The name of the BDS node to search for bitmaps
1348 * @name: The name of the bitmap to search for
1349 * @pbs: Output pointer for BDS lookup, if desired. Can be NULL.
1350 * @paio: Output pointer for aio_context acquisition, if desired. Can be NULL.
1351 * @errp: Output pointer for error information. Can be NULL.
1353 * @return: A bitmap object on success, or NULL on failure.
1355 static BdrvDirtyBitmap *block_dirty_bitmap_lookup(const char *node,
1357 BlockDriverState **pbs,
1361 BlockDriverState *bs;
1362 BdrvDirtyBitmap *bitmap;
1363 AioContext *aio_context;
1366 error_setg(errp, "Node cannot be NULL");
1370 error_setg(errp, "Bitmap name cannot be NULL");
1373 bs = bdrv_lookup_bs(node, node, NULL);
1375 error_setg(errp, "Node '%s' not found", node);
1379 aio_context = bdrv_get_aio_context(bs);
1380 aio_context_acquire(aio_context);
1382 bitmap = bdrv_find_dirty_bitmap(bs, name);
1384 error_setg(errp, "Dirty bitmap '%s' not found", name);
1392 *paio = aio_context;
1394 aio_context_release(aio_context);
1400 aio_context_release(aio_context);
1404 /* New and old BlockDriverState structs for atomic group operations */
1406 typedef struct BlkActionState BlkActionState;
1410 * Table of operations that define an Action.
1412 * @instance_size: Size of state struct, in bytes.
1413 * @prepare: Prepare the work, must NOT be NULL.
1414 * @commit: Commit the changes, can be NULL.
1415 * @abort: Abort the changes on fail, can be NULL.
1416 * @clean: Clean up resources after all transaction actions have called
1417 * commit() or abort(). Can be NULL.
1419 * Only prepare() may fail. In a single transaction, only one of commit() or
1420 * abort() will be called. clean() will always be called if it is present.
1422 typedef struct BlkActionOps {
1423 size_t instance_size;
1424 void (*prepare)(BlkActionState *common, Error **errp);
1425 void (*commit)(BlkActionState *common);
1426 void (*abort)(BlkActionState *common);
1427 void (*clean)(BlkActionState *common);
1432 * Describes one Action's state within a Transaction.
1434 * @action: QAPI-defined enum identifying which Action to perform.
1435 * @ops: Table of ActionOps this Action can perform.
1436 * @block_job_txn: Transaction which this action belongs to.
1437 * @entry: List membership for all Actions in this Transaction.
1439 * This structure must be arranged as first member in a subclassed type,
1440 * assuming that the compiler will also arrange it to the same offsets as the
1443 struct BlkActionState {
1444 TransactionAction *action;
1445 const BlkActionOps *ops;
1446 BlockJobTxn *block_job_txn;
1447 TransactionProperties *txn_props;
1448 QSIMPLEQ_ENTRY(BlkActionState) entry;
1451 /* internal snapshot private data */
1452 typedef struct InternalSnapshotState {
1453 BlkActionState common;
1454 BlockDriverState *bs;
1455 AioContext *aio_context;
1456 QEMUSnapshotInfo sn;
1458 } InternalSnapshotState;
1461 static int action_check_completion_mode(BlkActionState *s, Error **errp)
1463 if (s->txn_props->completion_mode != ACTION_COMPLETION_MODE_INDIVIDUAL) {
1465 "Action '%s' does not support Transaction property "
1466 "completion-mode = %s",
1467 TransactionActionKind_lookup[s->action->type],
1468 ActionCompletionMode_lookup[s->txn_props->completion_mode]);
1474 static void internal_snapshot_prepare(BlkActionState *common,
1477 Error *local_err = NULL;
1481 BlockDriverState *bs;
1482 QEMUSnapshotInfo old_sn, *sn;
1485 BlockdevSnapshotInternal *internal;
1486 InternalSnapshotState *state;
1489 g_assert(common->action->type ==
1490 TRANSACTION_ACTION_KIND_BLOCKDEV_SNAPSHOT_INTERNAL_SYNC);
1491 internal = common->action->u.blockdev_snapshot_internal_sync;
1492 state = DO_UPCAST(InternalSnapshotState, common, common);
1494 /* 1. parse input */
1495 device = internal->device;
1496 name = internal->name;
1498 /* 2. check for validation */
1499 if (action_check_completion_mode(common, errp) < 0) {
1503 blk = blk_by_name(device);
1505 error_set(errp, ERROR_CLASS_DEVICE_NOT_FOUND,
1506 "Device '%s' not found", device);
1510 /* AioContext is released in .clean() */
1511 state->aio_context = blk_get_aio_context(blk);
1512 aio_context_acquire(state->aio_context);
1514 if (!blk_is_available(blk)) {
1515 error_setg(errp, QERR_DEVICE_HAS_NO_MEDIUM, device);
1521 bdrv_drained_begin(bs);
1523 if (bdrv_op_is_blocked(bs, BLOCK_OP_TYPE_INTERNAL_SNAPSHOT, errp)) {
1527 if (bdrv_is_read_only(bs)) {
1528 error_setg(errp, "Device '%s' is read only", device);
1532 if (!bdrv_can_snapshot(bs)) {
1533 error_setg(errp, "Block format '%s' used by device '%s' "
1534 "does not support internal snapshots",
1535 bs->drv->format_name, device);
1539 if (!strlen(name)) {
1540 error_setg(errp, "Name is empty");
1544 /* check whether a snapshot with name exist */
1545 ret = bdrv_snapshot_find_by_id_and_name(bs, NULL, name, &old_sn,
1548 error_propagate(errp, local_err);
1552 "Snapshot with name '%s' already exists on device '%s'",
1557 /* 3. take the snapshot */
1559 pstrcpy(sn->name, sizeof(sn->name), name);
1560 qemu_gettimeofday(&tv);
1561 sn->date_sec = tv.tv_sec;
1562 sn->date_nsec = tv.tv_usec * 1000;
1563 sn->vm_clock_nsec = qemu_clock_get_ns(QEMU_CLOCK_VIRTUAL);
1565 ret1 = bdrv_snapshot_create(bs, sn);
1567 error_setg_errno(errp, -ret1,
1568 "Failed to create snapshot '%s' on device '%s'",
1573 /* 4. succeed, mark a snapshot is created */
1574 state->created = true;
1577 static void internal_snapshot_abort(BlkActionState *common)
1579 InternalSnapshotState *state =
1580 DO_UPCAST(InternalSnapshotState, common, common);
1581 BlockDriverState *bs = state->bs;
1582 QEMUSnapshotInfo *sn = &state->sn;
1583 Error *local_error = NULL;
1585 if (!state->created) {
1589 if (bdrv_snapshot_delete(bs, sn->id_str, sn->name, &local_error) < 0) {
1590 error_report("Failed to delete snapshot with id '%s' and name '%s' on "
1591 "device '%s' in abort: %s",
1594 bdrv_get_device_name(bs),
1595 error_get_pretty(local_error));
1596 error_free(local_error);
1600 static void internal_snapshot_clean(BlkActionState *common)
1602 InternalSnapshotState *state = DO_UPCAST(InternalSnapshotState,
1605 if (state->aio_context) {
1607 bdrv_drained_end(state->bs);
1609 aio_context_release(state->aio_context);
1613 /* external snapshot private data */
1614 typedef struct ExternalSnapshotState {
1615 BlkActionState common;
1616 BlockDriverState *old_bs;
1617 BlockDriverState *new_bs;
1618 AioContext *aio_context;
1619 } ExternalSnapshotState;
1621 static void external_snapshot_prepare(BlkActionState *common,
1625 QDict *options = NULL;
1626 Error *local_err = NULL;
1627 /* Device and node name of the image to generate the snapshot from */
1629 const char *node_name;
1630 /* Reference to the new image (for 'blockdev-snapshot') */
1631 const char *snapshot_ref;
1632 /* File name of the new image (for 'blockdev-snapshot-sync') */
1633 const char *new_image_file;
1634 ExternalSnapshotState *state =
1635 DO_UPCAST(ExternalSnapshotState, common, common);
1636 TransactionAction *action = common->action;
1638 /* 'blockdev-snapshot' and 'blockdev-snapshot-sync' have similar
1639 * purpose but a different set of parameters */
1640 switch (action->type) {
1641 case TRANSACTION_ACTION_KIND_BLOCKDEV_SNAPSHOT:
1643 BlockdevSnapshot *s = action->u.blockdev_snapshot;
1645 node_name = s->node;
1646 new_image_file = NULL;
1647 snapshot_ref = s->overlay;
1650 case TRANSACTION_ACTION_KIND_BLOCKDEV_SNAPSHOT_SYNC:
1652 BlockdevSnapshotSync *s = action->u.blockdev_snapshot_sync;
1653 device = s->has_device ? s->device : NULL;
1654 node_name = s->has_node_name ? s->node_name : NULL;
1655 new_image_file = s->snapshot_file;
1656 snapshot_ref = NULL;
1660 g_assert_not_reached();
1663 /* start processing */
1664 if (action_check_completion_mode(common, errp) < 0) {
1668 state->old_bs = bdrv_lookup_bs(device, node_name, errp);
1669 if (!state->old_bs) {
1673 /* Acquire AioContext now so any threads operating on old_bs stop */
1674 state->aio_context = bdrv_get_aio_context(state->old_bs);
1675 aio_context_acquire(state->aio_context);
1676 bdrv_drained_begin(state->old_bs);
1678 if (!bdrv_is_inserted(state->old_bs)) {
1679 error_setg(errp, QERR_DEVICE_HAS_NO_MEDIUM, device);
1683 if (bdrv_op_is_blocked(state->old_bs,
1684 BLOCK_OP_TYPE_EXTERNAL_SNAPSHOT, errp)) {
1688 if (!bdrv_is_read_only(state->old_bs)) {
1689 if (bdrv_flush(state->old_bs)) {
1690 error_setg(errp, QERR_IO_ERROR);
1695 if (!bdrv_is_first_non_filter(state->old_bs)) {
1696 error_setg(errp, QERR_FEATURE_DISABLED, "snapshot");
1700 if (action->type == TRANSACTION_ACTION_KIND_BLOCKDEV_SNAPSHOT_SYNC) {
1701 BlockdevSnapshotSync *s = action->u.blockdev_snapshot_sync;
1702 const char *format = s->has_format ? s->format : "qcow2";
1703 enum NewImageMode mode;
1704 const char *snapshot_node_name =
1705 s->has_snapshot_node_name ? s->snapshot_node_name : NULL;
1707 if (node_name && !snapshot_node_name) {
1708 error_setg(errp, "New snapshot node name missing");
1712 if (snapshot_node_name &&
1713 bdrv_lookup_bs(snapshot_node_name, snapshot_node_name, NULL)) {
1714 error_setg(errp, "New snapshot node name already in use");
1718 flags = state->old_bs->open_flags;
1720 /* create new image w/backing file */
1721 mode = s->has_mode ? s->mode : NEW_IMAGE_MODE_ABSOLUTE_PATHS;
1722 if (mode != NEW_IMAGE_MODE_EXISTING) {
1723 bdrv_img_create(new_image_file, format,
1724 state->old_bs->filename,
1725 state->old_bs->drv->format_name,
1726 NULL, -1, flags, &local_err, false);
1728 error_propagate(errp, local_err);
1733 options = qdict_new();
1734 if (s->has_snapshot_node_name) {
1735 qdict_put(options, "node-name",
1736 qstring_from_str(snapshot_node_name));
1738 qdict_put(options, "driver", qstring_from_str(format));
1740 flags |= BDRV_O_NO_BACKING;
1743 assert(state->new_bs == NULL);
1744 ret = bdrv_open(&state->new_bs, new_image_file, snapshot_ref, options,
1746 /* We will manually add the backing_hd field to the bs later */
1751 if (state->new_bs->blk != NULL) {
1752 error_setg(errp, "The snapshot is already in use by %s",
1753 blk_name(state->new_bs->blk));
1757 if (bdrv_op_is_blocked(state->new_bs, BLOCK_OP_TYPE_EXTERNAL_SNAPSHOT,
1762 if (state->new_bs->backing != NULL) {
1763 error_setg(errp, "The snapshot already has a backing image");
1767 if (!state->new_bs->drv->supports_backing) {
1768 error_setg(errp, "The snapshot does not support backing images");
1772 static void external_snapshot_commit(BlkActionState *common)
1774 ExternalSnapshotState *state =
1775 DO_UPCAST(ExternalSnapshotState, common, common);
1777 bdrv_set_aio_context(state->new_bs, state->aio_context);
1779 /* This removes our old bs and adds the new bs */
1780 bdrv_append(state->new_bs, state->old_bs);
1781 /* We don't need (or want) to use the transactional
1782 * bdrv_reopen_multiple() across all the entries at once, because we
1783 * don't want to abort all of them if one of them fails the reopen */
1784 bdrv_reopen(state->old_bs, state->old_bs->open_flags & ~BDRV_O_RDWR,
1788 static void external_snapshot_abort(BlkActionState *common)
1790 ExternalSnapshotState *state =
1791 DO_UPCAST(ExternalSnapshotState, common, common);
1792 if (state->new_bs) {
1793 bdrv_unref(state->new_bs);
1797 static void external_snapshot_clean(BlkActionState *common)
1799 ExternalSnapshotState *state =
1800 DO_UPCAST(ExternalSnapshotState, common, common);
1801 if (state->aio_context) {
1802 bdrv_drained_end(state->old_bs);
1803 aio_context_release(state->aio_context);
1807 typedef struct DriveBackupState {
1808 BlkActionState common;
1809 BlockDriverState *bs;
1810 AioContext *aio_context;
1814 static void do_drive_backup(const char *device, const char *target,
1815 bool has_format, const char *format,
1816 enum MirrorSyncMode sync,
1817 bool has_mode, enum NewImageMode mode,
1818 bool has_speed, int64_t speed,
1819 bool has_bitmap, const char *bitmap,
1820 bool has_on_source_error,
1821 BlockdevOnError on_source_error,
1822 bool has_on_target_error,
1823 BlockdevOnError on_target_error,
1824 BlockJobTxn *txn, Error **errp);
1826 static void drive_backup_prepare(BlkActionState *common, Error **errp)
1828 DriveBackupState *state = DO_UPCAST(DriveBackupState, common, common);
1830 DriveBackup *backup;
1831 Error *local_err = NULL;
1833 assert(common->action->type == TRANSACTION_ACTION_KIND_DRIVE_BACKUP);
1834 backup = common->action->u.drive_backup;
1836 blk = blk_by_name(backup->device);
1838 error_set(errp, ERROR_CLASS_DEVICE_NOT_FOUND,
1839 "Device '%s' not found", backup->device);
1843 if (!blk_is_available(blk)) {
1844 error_setg(errp, QERR_DEVICE_HAS_NO_MEDIUM, backup->device);
1848 /* AioContext is released in .clean() */
1849 state->aio_context = blk_get_aio_context(blk);
1850 aio_context_acquire(state->aio_context);
1851 bdrv_drained_begin(blk_bs(blk));
1852 state->bs = blk_bs(blk);
1854 do_drive_backup(backup->device, backup->target,
1855 backup->has_format, backup->format,
1857 backup->has_mode, backup->mode,
1858 backup->has_speed, backup->speed,
1859 backup->has_bitmap, backup->bitmap,
1860 backup->has_on_source_error, backup->on_source_error,
1861 backup->has_on_target_error, backup->on_target_error,
1862 common->block_job_txn, &local_err);
1864 error_propagate(errp, local_err);
1868 state->job = state->bs->job;
1871 static void drive_backup_abort(BlkActionState *common)
1873 DriveBackupState *state = DO_UPCAST(DriveBackupState, common, common);
1874 BlockDriverState *bs = state->bs;
1876 /* Only cancel if it's the job we started */
1877 if (bs && bs->job && bs->job == state->job) {
1878 block_job_cancel_sync(bs->job);
1882 static void drive_backup_clean(BlkActionState *common)
1884 DriveBackupState *state = DO_UPCAST(DriveBackupState, common, common);
1886 if (state->aio_context) {
1887 bdrv_drained_end(state->bs);
1888 aio_context_release(state->aio_context);
1892 typedef struct BlockdevBackupState {
1893 BlkActionState common;
1894 BlockDriverState *bs;
1896 AioContext *aio_context;
1897 } BlockdevBackupState;
1899 static void do_blockdev_backup(const char *device, const char *target,
1900 enum MirrorSyncMode sync,
1901 bool has_speed, int64_t speed,
1902 bool has_on_source_error,
1903 BlockdevOnError on_source_error,
1904 bool has_on_target_error,
1905 BlockdevOnError on_target_error,
1906 BlockJobTxn *txn, Error **errp);
1908 static void blockdev_backup_prepare(BlkActionState *common, Error **errp)
1910 BlockdevBackupState *state = DO_UPCAST(BlockdevBackupState, common, common);
1911 BlockdevBackup *backup;
1912 BlockBackend *blk, *target;
1913 Error *local_err = NULL;
1915 assert(common->action->type == TRANSACTION_ACTION_KIND_BLOCKDEV_BACKUP);
1916 backup = common->action->u.blockdev_backup;
1918 blk = blk_by_name(backup->device);
1920 error_setg(errp, "Device '%s' not found", backup->device);
1924 if (!blk_is_available(blk)) {
1925 error_setg(errp, QERR_DEVICE_HAS_NO_MEDIUM, backup->device);
1929 target = blk_by_name(backup->target);
1931 error_setg(errp, "Device '%s' not found", backup->target);
1935 /* AioContext is released in .clean() */
1936 state->aio_context = blk_get_aio_context(blk);
1937 if (state->aio_context != blk_get_aio_context(target)) {
1938 state->aio_context = NULL;
1939 error_setg(errp, "Backup between two IO threads is not implemented");
1942 aio_context_acquire(state->aio_context);
1943 state->bs = blk_bs(blk);
1944 bdrv_drained_begin(state->bs);
1946 do_blockdev_backup(backup->device, backup->target,
1948 backup->has_speed, backup->speed,
1949 backup->has_on_source_error, backup->on_source_error,
1950 backup->has_on_target_error, backup->on_target_error,
1951 common->block_job_txn, &local_err);
1953 error_propagate(errp, local_err);
1957 state->job = state->bs->job;
1960 static void blockdev_backup_abort(BlkActionState *common)
1962 BlockdevBackupState *state = DO_UPCAST(BlockdevBackupState, common, common);
1963 BlockDriverState *bs = state->bs;
1965 /* Only cancel if it's the job we started */
1966 if (bs && bs->job && bs->job == state->job) {
1967 block_job_cancel_sync(bs->job);
1971 static void blockdev_backup_clean(BlkActionState *common)
1973 BlockdevBackupState *state = DO_UPCAST(BlockdevBackupState, common, common);
1975 if (state->aio_context) {
1976 bdrv_drained_end(state->bs);
1977 aio_context_release(state->aio_context);
1981 typedef struct BlockDirtyBitmapState {
1982 BlkActionState common;
1983 BdrvDirtyBitmap *bitmap;
1984 BlockDriverState *bs;
1985 AioContext *aio_context;
1988 } BlockDirtyBitmapState;
1990 static void block_dirty_bitmap_add_prepare(BlkActionState *common,
1993 Error *local_err = NULL;
1994 BlockDirtyBitmapAdd *action;
1995 BlockDirtyBitmapState *state = DO_UPCAST(BlockDirtyBitmapState,
1998 if (action_check_completion_mode(common, errp) < 0) {
2002 action = common->action->u.block_dirty_bitmap_add;
2003 /* AIO context taken and released within qmp_block_dirty_bitmap_add */
2004 qmp_block_dirty_bitmap_add(action->node, action->name,
2005 action->has_granularity, action->granularity,
2009 state->prepared = true;
2011 error_propagate(errp, local_err);
2015 static void block_dirty_bitmap_add_abort(BlkActionState *common)
2017 BlockDirtyBitmapAdd *action;
2018 BlockDirtyBitmapState *state = DO_UPCAST(BlockDirtyBitmapState,
2021 action = common->action->u.block_dirty_bitmap_add;
2022 /* Should not be able to fail: IF the bitmap was added via .prepare(),
2023 * then the node reference and bitmap name must have been valid.
2025 if (state->prepared) {
2026 qmp_block_dirty_bitmap_remove(action->node, action->name, &error_abort);
2030 static void block_dirty_bitmap_clear_prepare(BlkActionState *common,
2033 BlockDirtyBitmapState *state = DO_UPCAST(BlockDirtyBitmapState,
2035 BlockDirtyBitmap *action;
2037 if (action_check_completion_mode(common, errp) < 0) {
2041 action = common->action->u.block_dirty_bitmap_clear;
2042 state->bitmap = block_dirty_bitmap_lookup(action->node,
2045 &state->aio_context,
2047 if (!state->bitmap) {
2051 if (bdrv_dirty_bitmap_frozen(state->bitmap)) {
2052 error_setg(errp, "Cannot modify a frozen bitmap");
2054 } else if (!bdrv_dirty_bitmap_enabled(state->bitmap)) {
2055 error_setg(errp, "Cannot clear a disabled bitmap");
2059 bdrv_clear_dirty_bitmap(state->bitmap, &state->backup);
2060 /* AioContext is released in .clean() */
2063 static void block_dirty_bitmap_clear_abort(BlkActionState *common)
2065 BlockDirtyBitmapState *state = DO_UPCAST(BlockDirtyBitmapState,
2068 bdrv_undo_clear_dirty_bitmap(state->bitmap, state->backup);
2071 static void block_dirty_bitmap_clear_commit(BlkActionState *common)
2073 BlockDirtyBitmapState *state = DO_UPCAST(BlockDirtyBitmapState,
2076 hbitmap_free(state->backup);
2079 static void block_dirty_bitmap_clear_clean(BlkActionState *common)
2081 BlockDirtyBitmapState *state = DO_UPCAST(BlockDirtyBitmapState,
2084 if (state->aio_context) {
2085 aio_context_release(state->aio_context);
2089 static void abort_prepare(BlkActionState *common, Error **errp)
2091 error_setg(errp, "Transaction aborted using Abort action");
2094 static void abort_commit(BlkActionState *common)
2096 g_assert_not_reached(); /* this action never succeeds */
2099 static const BlkActionOps actions[] = {
2100 [TRANSACTION_ACTION_KIND_BLOCKDEV_SNAPSHOT] = {
2101 .instance_size = sizeof(ExternalSnapshotState),
2102 .prepare = external_snapshot_prepare,
2103 .commit = external_snapshot_commit,
2104 .abort = external_snapshot_abort,
2105 .clean = external_snapshot_clean,
2107 [TRANSACTION_ACTION_KIND_BLOCKDEV_SNAPSHOT_SYNC] = {
2108 .instance_size = sizeof(ExternalSnapshotState),
2109 .prepare = external_snapshot_prepare,
2110 .commit = external_snapshot_commit,
2111 .abort = external_snapshot_abort,
2112 .clean = external_snapshot_clean,
2114 [TRANSACTION_ACTION_KIND_DRIVE_BACKUP] = {
2115 .instance_size = sizeof(DriveBackupState),
2116 .prepare = drive_backup_prepare,
2117 .abort = drive_backup_abort,
2118 .clean = drive_backup_clean,
2120 [TRANSACTION_ACTION_KIND_BLOCKDEV_BACKUP] = {
2121 .instance_size = sizeof(BlockdevBackupState),
2122 .prepare = blockdev_backup_prepare,
2123 .abort = blockdev_backup_abort,
2124 .clean = blockdev_backup_clean,
2126 [TRANSACTION_ACTION_KIND_ABORT] = {
2127 .instance_size = sizeof(BlkActionState),
2128 .prepare = abort_prepare,
2129 .commit = abort_commit,
2131 [TRANSACTION_ACTION_KIND_BLOCKDEV_SNAPSHOT_INTERNAL_SYNC] = {
2132 .instance_size = sizeof(InternalSnapshotState),
2133 .prepare = internal_snapshot_prepare,
2134 .abort = internal_snapshot_abort,
2135 .clean = internal_snapshot_clean,
2137 [TRANSACTION_ACTION_KIND_BLOCK_DIRTY_BITMAP_ADD] = {
2138 .instance_size = sizeof(BlockDirtyBitmapState),
2139 .prepare = block_dirty_bitmap_add_prepare,
2140 .abort = block_dirty_bitmap_add_abort,
2142 [TRANSACTION_ACTION_KIND_BLOCK_DIRTY_BITMAP_CLEAR] = {
2143 .instance_size = sizeof(BlockDirtyBitmapState),
2144 .prepare = block_dirty_bitmap_clear_prepare,
2145 .commit = block_dirty_bitmap_clear_commit,
2146 .abort = block_dirty_bitmap_clear_abort,
2147 .clean = block_dirty_bitmap_clear_clean,
2152 * Allocate a TransactionProperties structure if necessary, and fill
2153 * that structure with desired defaults if they are unset.
2155 static TransactionProperties *get_transaction_properties(
2156 TransactionProperties *props)
2159 props = g_new0(TransactionProperties, 1);
2162 if (!props->has_completion_mode) {
2163 props->has_completion_mode = true;
2164 props->completion_mode = ACTION_COMPLETION_MODE_INDIVIDUAL;
2171 * 'Atomic' group operations. The operations are performed as a set, and if
2172 * any fail then we roll back all operations in the group.
2174 void qmp_transaction(TransactionActionList *dev_list,
2176 struct TransactionProperties *props,
2179 TransactionActionList *dev_entry = dev_list;
2180 BlockJobTxn *block_job_txn = NULL;
2181 BlkActionState *state, *next;
2182 Error *local_err = NULL;
2184 QSIMPLEQ_HEAD(snap_bdrv_states, BlkActionState) snap_bdrv_states;
2185 QSIMPLEQ_INIT(&snap_bdrv_states);
2187 /* Does this transaction get canceled as a group on failure?
2188 * If not, we don't really need to make a BlockJobTxn.
2190 props = get_transaction_properties(props);
2191 if (props->completion_mode != ACTION_COMPLETION_MODE_INDIVIDUAL) {
2192 block_job_txn = block_job_txn_new();
2195 /* drain all i/o before any operations */
2198 /* We don't do anything in this loop that commits us to the operations */
2199 while (NULL != dev_entry) {
2200 TransactionAction *dev_info = NULL;
2201 const BlkActionOps *ops;
2203 dev_info = dev_entry->value;
2204 dev_entry = dev_entry->next;
2206 assert(dev_info->type < ARRAY_SIZE(actions));
2208 ops = &actions[dev_info->type];
2209 assert(ops->instance_size > 0);
2211 state = g_malloc0(ops->instance_size);
2213 state->action = dev_info;
2214 state->block_job_txn = block_job_txn;
2215 state->txn_props = props;
2216 QSIMPLEQ_INSERT_TAIL(&snap_bdrv_states, state, entry);
2218 state->ops->prepare(state, &local_err);
2220 error_propagate(errp, local_err);
2221 goto delete_and_fail;
2225 QSIMPLEQ_FOREACH(state, &snap_bdrv_states, entry) {
2226 if (state->ops->commit) {
2227 state->ops->commit(state);
2235 /* failure, and it is all-or-none; roll back all operations */
2236 QSIMPLEQ_FOREACH(state, &snap_bdrv_states, entry) {
2237 if (state->ops->abort) {
2238 state->ops->abort(state);
2242 QSIMPLEQ_FOREACH_SAFE(state, &snap_bdrv_states, entry, next) {
2243 if (state->ops->clean) {
2244 state->ops->clean(state);
2249 qapi_free_TransactionProperties(props);
2251 block_job_txn_unref(block_job_txn);
2254 void qmp_eject(const char *device, bool has_force, bool force, Error **errp)
2256 Error *local_err = NULL;
2258 qmp_blockdev_open_tray(device, has_force, force, &local_err);
2260 error_propagate(errp, local_err);
2264 qmp_x_blockdev_remove_medium(device, errp);
2267 void qmp_block_passwd(bool has_device, const char *device,
2268 bool has_node_name, const char *node_name,
2269 const char *password, Error **errp)
2271 Error *local_err = NULL;
2272 BlockDriverState *bs;
2273 AioContext *aio_context;
2275 bs = bdrv_lookup_bs(has_device ? device : NULL,
2276 has_node_name ? node_name : NULL,
2279 error_propagate(errp, local_err);
2283 aio_context = bdrv_get_aio_context(bs);
2284 aio_context_acquire(aio_context);
2286 bdrv_add_key(bs, password, errp);
2288 aio_context_release(aio_context);
2291 void qmp_blockdev_open_tray(const char *device, bool has_force, bool force,
2301 blk = blk_by_name(device);
2303 error_set(errp, ERROR_CLASS_DEVICE_NOT_FOUND,
2304 "Device '%s' not found", device);
2308 if (!blk_dev_has_removable_media(blk)) {
2309 error_setg(errp, "Device '%s' is not removable", device);
2313 if (blk_dev_is_tray_open(blk)) {
2317 locked = blk_dev_is_medium_locked(blk);
2319 blk_dev_eject_request(blk, force);
2322 if (!locked || force) {
2323 blk_dev_change_media_cb(blk, false);
2327 void qmp_blockdev_close_tray(const char *device, Error **errp)
2331 blk = blk_by_name(device);
2333 error_set(errp, ERROR_CLASS_DEVICE_NOT_FOUND,
2334 "Device '%s' not found", device);
2338 if (!blk_dev_has_removable_media(blk)) {
2339 error_setg(errp, "Device '%s' is not removable", device);
2343 if (!blk_dev_is_tray_open(blk)) {
2347 blk_dev_change_media_cb(blk, true);
2350 void qmp_x_blockdev_remove_medium(const char *device, Error **errp)
2353 BlockDriverState *bs;
2354 AioContext *aio_context;
2357 blk = blk_by_name(device);
2359 error_set(errp, ERROR_CLASS_DEVICE_NOT_FOUND,
2360 "Device '%s' not found", device);
2364 /* For BBs without a device, we can exchange the BDS tree at will */
2365 has_device = blk_get_attached_dev(blk);
2367 if (has_device && !blk_dev_has_removable_media(blk)) {
2368 error_setg(errp, "Device '%s' is not removable", device);
2372 if (has_device && !blk_dev_is_tray_open(blk)) {
2373 error_setg(errp, "Tray of device '%s' is not open", device);
2382 aio_context = bdrv_get_aio_context(bs);
2383 aio_context_acquire(aio_context);
2385 if (bdrv_op_is_blocked(bs, BLOCK_OP_TYPE_EJECT, errp)) {
2389 /* This follows the convention established by bdrv_make_anon() */
2390 if (bs->device_list.tqe_prev) {
2391 QTAILQ_REMOVE(&bdrv_states, bs, device_list);
2392 bs->device_list.tqe_prev = NULL;
2398 aio_context_release(aio_context);
2401 static void qmp_blockdev_insert_anon_medium(const char *device,
2402 BlockDriverState *bs, Error **errp)
2407 blk = blk_by_name(device);
2409 error_set(errp, ERROR_CLASS_DEVICE_NOT_FOUND,
2410 "Device '%s' not found", device);
2414 /* For BBs without a device, we can exchange the BDS tree at will */
2415 has_device = blk_get_attached_dev(blk);
2417 if (has_device && !blk_dev_has_removable_media(blk)) {
2418 error_setg(errp, "Device '%s' is not removable", device);
2422 if (has_device && !blk_dev_is_tray_open(blk)) {
2423 error_setg(errp, "Tray of device '%s' is not open", device);
2428 error_setg(errp, "There already is a medium in device '%s'", device);
2432 blk_insert_bs(blk, bs);
2434 QTAILQ_INSERT_TAIL(&bdrv_states, bs, device_list);
2437 void qmp_x_blockdev_insert_medium(const char *device, const char *node_name,
2440 BlockDriverState *bs;
2442 bs = bdrv_find_node(node_name);
2444 error_setg(errp, "Node '%s' not found", node_name);
2449 error_setg(errp, "Node '%s' is already in use by '%s'", node_name,
2454 qmp_blockdev_insert_anon_medium(device, bs, errp);
2457 void qmp_blockdev_change_medium(const char *device, const char *filename,
2458 bool has_format, const char *format,
2460 BlockdevChangeReadOnlyMode read_only,
2464 BlockDriverState *medium_bs = NULL;
2465 int bdrv_flags, ret;
2466 QDict *options = NULL;
2469 blk = blk_by_name(device);
2471 error_set(errp, ERROR_CLASS_DEVICE_NOT_FOUND,
2472 "Device '%s' not found", device);
2477 blk_update_root_state(blk);
2480 bdrv_flags = blk_get_open_flags_from_root_state(blk);
2482 if (!has_read_only) {
2483 read_only = BLOCKDEV_CHANGE_READ_ONLY_MODE_RETAIN;
2486 switch (read_only) {
2487 case BLOCKDEV_CHANGE_READ_ONLY_MODE_RETAIN:
2490 case BLOCKDEV_CHANGE_READ_ONLY_MODE_READ_ONLY:
2491 bdrv_flags &= ~BDRV_O_RDWR;
2494 case BLOCKDEV_CHANGE_READ_ONLY_MODE_READ_WRITE:
2495 bdrv_flags |= BDRV_O_RDWR;
2503 options = qdict_new();
2504 qdict_put(options, "driver", qstring_from_str(format));
2508 ret = bdrv_open(&medium_bs, filename, NULL, options, bdrv_flags, errp);
2513 blk_apply_root_state(blk, medium_bs);
2515 bdrv_add_key(medium_bs, NULL, &err);
2517 error_propagate(errp, err);
2521 qmp_blockdev_open_tray(device, false, false, &err);
2523 error_propagate(errp, err);
2527 qmp_x_blockdev_remove_medium(device, &err);
2529 error_propagate(errp, err);
2533 qmp_blockdev_insert_anon_medium(device, medium_bs, &err);
2535 error_propagate(errp, err);
2539 qmp_blockdev_close_tray(device, errp);
2542 /* If the medium has been inserted, the device has its own reference, so
2543 * ours must be relinquished; and if it has not been inserted successfully,
2544 * the reference must be relinquished anyway */
2545 bdrv_unref(medium_bs);
2548 /* throttling disk I/O limits */
2549 void qmp_block_set_io_throttle(const char *device, int64_t bps, int64_t bps_rd,
2556 bool has_bps_rd_max,
2558 bool has_bps_wr_max,
2562 bool has_iops_rd_max,
2563 int64_t iops_rd_max,
2564 bool has_iops_wr_max,
2565 int64_t iops_wr_max,
2569 const char *group, Error **errp)
2572 BlockDriverState *bs;
2574 AioContext *aio_context;
2576 blk = blk_by_name(device);
2578 error_set(errp, ERROR_CLASS_DEVICE_NOT_FOUND,
2579 "Device '%s' not found", device);
2583 aio_context = blk_get_aio_context(blk);
2584 aio_context_acquire(aio_context);
2588 error_setg(errp, "Device '%s' has no medium", device);
2592 memset(&cfg, 0, sizeof(cfg));
2593 cfg.buckets[THROTTLE_BPS_TOTAL].avg = bps;
2594 cfg.buckets[THROTTLE_BPS_READ].avg = bps_rd;
2595 cfg.buckets[THROTTLE_BPS_WRITE].avg = bps_wr;
2597 cfg.buckets[THROTTLE_OPS_TOTAL].avg = iops;
2598 cfg.buckets[THROTTLE_OPS_READ].avg = iops_rd;
2599 cfg.buckets[THROTTLE_OPS_WRITE].avg = iops_wr;
2602 cfg.buckets[THROTTLE_BPS_TOTAL].max = bps_max;
2604 if (has_bps_rd_max) {
2605 cfg.buckets[THROTTLE_BPS_READ].max = bps_rd_max;
2607 if (has_bps_wr_max) {
2608 cfg.buckets[THROTTLE_BPS_WRITE].max = bps_wr_max;
2611 cfg.buckets[THROTTLE_OPS_TOTAL].max = iops_max;
2613 if (has_iops_rd_max) {
2614 cfg.buckets[THROTTLE_OPS_READ].max = iops_rd_max;
2616 if (has_iops_wr_max) {
2617 cfg.buckets[THROTTLE_OPS_WRITE].max = iops_wr_max;
2620 if (has_iops_size) {
2621 cfg.op_size = iops_size;
2624 if (!check_throttle_config(&cfg, errp)) {
2628 if (throttle_enabled(&cfg)) {
2629 /* Enable I/O limits if they're not enabled yet, otherwise
2630 * just update the throttling group. */
2631 if (!bs->throttle_state) {
2632 bdrv_io_limits_enable(bs, has_group ? group : device);
2633 } else if (has_group) {
2634 bdrv_io_limits_update_group(bs, group);
2636 /* Set the new throttling configuration */
2637 bdrv_set_io_limits(bs, &cfg);
2638 } else if (bs->throttle_state) {
2639 /* If all throttling settings are set to 0, disable I/O limits */
2640 bdrv_io_limits_disable(bs);
2644 aio_context_release(aio_context);
2647 void qmp_block_dirty_bitmap_add(const char *node, const char *name,
2648 bool has_granularity, uint32_t granularity,
2651 AioContext *aio_context;
2652 BlockDriverState *bs;
2654 if (!name || name[0] == '\0') {
2655 error_setg(errp, "Bitmap name cannot be empty");
2659 bs = bdrv_lookup_bs(node, node, errp);
2664 aio_context = bdrv_get_aio_context(bs);
2665 aio_context_acquire(aio_context);
2667 if (has_granularity) {
2668 if (granularity < 512 || !is_power_of_2(granularity)) {
2669 error_setg(errp, "Granularity must be power of 2 "
2670 "and at least 512");
2674 /* Default to cluster size, if available: */
2675 granularity = bdrv_get_default_bitmap_granularity(bs);
2678 bdrv_create_dirty_bitmap(bs, granularity, name, errp);
2681 aio_context_release(aio_context);
2684 void qmp_block_dirty_bitmap_remove(const char *node, const char *name,
2687 AioContext *aio_context;
2688 BlockDriverState *bs;
2689 BdrvDirtyBitmap *bitmap;
2691 bitmap = block_dirty_bitmap_lookup(node, name, &bs, &aio_context, errp);
2692 if (!bitmap || !bs) {
2696 if (bdrv_dirty_bitmap_frozen(bitmap)) {
2698 "Bitmap '%s' is currently frozen and cannot be removed",
2702 bdrv_dirty_bitmap_make_anon(bitmap);
2703 bdrv_release_dirty_bitmap(bs, bitmap);
2706 aio_context_release(aio_context);
2710 * Completely clear a bitmap, for the purposes of synchronizing a bitmap
2711 * immediately after a full backup operation.
2713 void qmp_block_dirty_bitmap_clear(const char *node, const char *name,
2716 AioContext *aio_context;
2717 BdrvDirtyBitmap *bitmap;
2718 BlockDriverState *bs;
2720 bitmap = block_dirty_bitmap_lookup(node, name, &bs, &aio_context, errp);
2721 if (!bitmap || !bs) {
2725 if (bdrv_dirty_bitmap_frozen(bitmap)) {
2727 "Bitmap '%s' is currently frozen and cannot be modified",
2730 } else if (!bdrv_dirty_bitmap_enabled(bitmap)) {
2732 "Bitmap '%s' is currently disabled and cannot be cleared",
2737 bdrv_clear_dirty_bitmap(bitmap, NULL);
2740 aio_context_release(aio_context);
2743 void hmp_drive_del(Monitor *mon, const QDict *qdict)
2745 const char *id = qdict_get_str(qdict, "id");
2747 BlockDriverState *bs;
2748 AioContext *aio_context;
2749 Error *local_err = NULL;
2751 blk = blk_by_name(id);
2753 error_report("Device '%s' not found", id);
2757 if (!blk_legacy_dinfo(blk)) {
2758 error_report("Deleting device added with blockdev-add"
2759 " is not supported");
2763 aio_context = blk_get_aio_context(blk);
2764 aio_context_acquire(aio_context);
2768 if (bdrv_op_is_blocked(bs, BLOCK_OP_TYPE_DRIVE_DEL, &local_err)) {
2769 error_report_err(local_err);
2770 aio_context_release(aio_context);
2777 /* if we have a device attached to this BlockDriverState
2778 * then we need to make the drive anonymous until the device
2779 * can be removed. If this is a drive with no device backing
2780 * then we can just get rid of the block driver state right here.
2782 if (blk_get_attached_dev(blk)) {
2783 blk_hide_on_behalf_of_hmp_drive_del(blk);
2784 /* Further I/O must not pause the guest */
2785 blk_set_on_error(blk, BLOCKDEV_ON_ERROR_REPORT,
2786 BLOCKDEV_ON_ERROR_REPORT);
2791 aio_context_release(aio_context);
2794 void qmp_block_resize(bool has_device, const char *device,
2795 bool has_node_name, const char *node_name,
2796 int64_t size, Error **errp)
2798 Error *local_err = NULL;
2799 BlockDriverState *bs;
2800 AioContext *aio_context;
2803 bs = bdrv_lookup_bs(has_device ? device : NULL,
2804 has_node_name ? node_name : NULL,
2807 error_propagate(errp, local_err);
2811 aio_context = bdrv_get_aio_context(bs);
2812 aio_context_acquire(aio_context);
2814 if (!bdrv_is_first_non_filter(bs)) {
2815 error_setg(errp, QERR_FEATURE_DISABLED, "resize");
2820 error_setg(errp, QERR_INVALID_PARAMETER_VALUE, "size", "a >0 size");
2824 if (bdrv_op_is_blocked(bs, BLOCK_OP_TYPE_RESIZE, NULL)) {
2825 error_setg(errp, QERR_DEVICE_IN_USE, device);
2829 /* complete all in-flight operations before resizing the device */
2832 ret = bdrv_truncate(bs, size);
2837 error_setg(errp, QERR_DEVICE_HAS_NO_MEDIUM, device);
2840 error_setg(errp, QERR_UNSUPPORTED);
2843 error_setg(errp, "Device '%s' is read only", device);
2846 error_setg(errp, QERR_DEVICE_IN_USE, device);
2849 error_setg_errno(errp, -ret, "Could not resize");
2854 aio_context_release(aio_context);
2857 static void block_job_cb(void *opaque, int ret)
2859 /* Note that this function may be executed from another AioContext besides
2860 * the QEMU main loop. If you need to access anything that assumes the
2861 * QEMU global mutex, use a BH or introduce a mutex.
2864 BlockDriverState *bs = opaque;
2865 const char *msg = NULL;
2867 trace_block_job_cb(bs, bs->job, ret);
2872 msg = strerror(-ret);
2875 if (block_job_is_cancelled(bs->job)) {
2876 block_job_event_cancelled(bs->job);
2878 block_job_event_completed(bs->job, msg);
2882 void qmp_block_stream(const char *device,
2883 bool has_base, const char *base,
2884 bool has_backing_file, const char *backing_file,
2885 bool has_speed, int64_t speed,
2886 bool has_on_error, BlockdevOnError on_error,
2890 BlockDriverState *bs;
2891 BlockDriverState *base_bs = NULL;
2892 AioContext *aio_context;
2893 Error *local_err = NULL;
2894 const char *base_name = NULL;
2896 if (!has_on_error) {
2897 on_error = BLOCKDEV_ON_ERROR_REPORT;
2900 blk = blk_by_name(device);
2902 error_set(errp, ERROR_CLASS_DEVICE_NOT_FOUND,
2903 "Device '%s' not found", device);
2907 aio_context = blk_get_aio_context(blk);
2908 aio_context_acquire(aio_context);
2910 if (!blk_is_available(blk)) {
2911 error_setg(errp, "Device '%s' has no medium", device);
2916 if (bdrv_op_is_blocked(bs, BLOCK_OP_TYPE_STREAM, errp)) {
2921 base_bs = bdrv_find_backing_image(bs, base);
2922 if (base_bs == NULL) {
2923 error_setg(errp, QERR_BASE_NOT_FOUND, base);
2926 assert(bdrv_get_aio_context(base_bs) == aio_context);
2930 /* if we are streaming the entire chain, the result will have no backing
2931 * file, and specifying one is therefore an error */
2932 if (base_bs == NULL && has_backing_file) {
2933 error_setg(errp, "backing file specified, but streaming the "
2938 /* backing_file string overrides base bs filename */
2939 base_name = has_backing_file ? backing_file : base_name;
2941 stream_start(bs, base_bs, base_name, has_speed ? speed : 0,
2942 on_error, block_job_cb, bs, &local_err);
2944 error_propagate(errp, local_err);
2948 trace_qmp_block_stream(bs, bs->job);
2951 aio_context_release(aio_context);
2954 void qmp_block_commit(const char *device,
2955 bool has_base, const char *base,
2956 bool has_top, const char *top,
2957 bool has_backing_file, const char *backing_file,
2958 bool has_speed, int64_t speed,
2962 BlockDriverState *bs;
2963 BlockDriverState *base_bs, *top_bs;
2964 AioContext *aio_context;
2965 Error *local_err = NULL;
2966 /* This will be part of the QMP command, if/when the
2967 * BlockdevOnError change for blkmirror makes it in
2969 BlockdevOnError on_error = BLOCKDEV_ON_ERROR_REPORT;
2976 * libvirt relies on the DeviceNotFound error class in order to probe for
2977 * live commit feature versions; for this to work, we must make sure to
2978 * perform the device lookup before any generic errors that may occur in a
2979 * scenario in which all optional arguments are omitted. */
2980 blk = blk_by_name(device);
2982 error_set(errp, ERROR_CLASS_DEVICE_NOT_FOUND,
2983 "Device '%s' not found", device);
2987 aio_context = blk_get_aio_context(blk);
2988 aio_context_acquire(aio_context);
2990 if (!blk_is_available(blk)) {
2991 error_setg(errp, "Device '%s' has no medium", device);
2996 if (bdrv_op_is_blocked(bs, BLOCK_OP_TYPE_COMMIT_SOURCE, errp)) {
3000 /* default top_bs is the active layer */
3003 if (has_top && top) {
3004 if (strcmp(bs->filename, top) != 0) {
3005 top_bs = bdrv_find_backing_image(bs, top);
3009 if (top_bs == NULL) {
3010 error_setg(errp, "Top image file %s not found", top ? top : "NULL");
3014 assert(bdrv_get_aio_context(top_bs) == aio_context);
3016 if (has_base && base) {
3017 base_bs = bdrv_find_backing_image(top_bs, base);
3019 base_bs = bdrv_find_base(top_bs);
3022 if (base_bs == NULL) {
3023 error_setg(errp, QERR_BASE_NOT_FOUND, base ? base : "NULL");
3027 assert(bdrv_get_aio_context(base_bs) == aio_context);
3029 if (bdrv_op_is_blocked(base_bs, BLOCK_OP_TYPE_COMMIT_TARGET, errp)) {
3033 /* Do not allow attempts to commit an image into itself */
3034 if (top_bs == base_bs) {
3035 error_setg(errp, "cannot commit an image into itself");
3040 if (has_backing_file) {
3041 error_setg(errp, "'backing-file' specified,"
3042 " but 'top' is the active layer");
3045 commit_active_start(bs, base_bs, speed, on_error, block_job_cb,
3048 commit_start(bs, base_bs, top_bs, speed, on_error, block_job_cb, bs,
3049 has_backing_file ? backing_file : NULL, &local_err);
3051 if (local_err != NULL) {
3052 error_propagate(errp, local_err);
3057 aio_context_release(aio_context);
3060 static void do_drive_backup(const char *device, const char *target,
3061 bool has_format, const char *format,
3062 enum MirrorSyncMode sync,
3063 bool has_mode, enum NewImageMode mode,
3064 bool has_speed, int64_t speed,
3065 bool has_bitmap, const char *bitmap,
3066 bool has_on_source_error,
3067 BlockdevOnError on_source_error,
3068 bool has_on_target_error,
3069 BlockdevOnError on_target_error,
3070 BlockJobTxn *txn, Error **errp)
3073 BlockDriverState *bs;
3074 BlockDriverState *target_bs;
3075 BlockDriverState *source = NULL;
3076 BdrvDirtyBitmap *bmap = NULL;
3077 AioContext *aio_context;
3078 QDict *options = NULL;
3079 Error *local_err = NULL;
3087 if (!has_on_source_error) {
3088 on_source_error = BLOCKDEV_ON_ERROR_REPORT;
3090 if (!has_on_target_error) {
3091 on_target_error = BLOCKDEV_ON_ERROR_REPORT;
3094 mode = NEW_IMAGE_MODE_ABSOLUTE_PATHS;
3097 blk = blk_by_name(device);
3099 error_set(errp, ERROR_CLASS_DEVICE_NOT_FOUND,
3100 "Device '%s' not found", device);
3104 aio_context = blk_get_aio_context(blk);
3105 aio_context_acquire(aio_context);
3107 /* Although backup_run has this check too, we need to use bs->drv below, so
3108 * do an early check redundantly. */
3109 if (!blk_is_available(blk)) {
3110 error_setg(errp, QERR_DEVICE_HAS_NO_MEDIUM, device);
3116 format = mode == NEW_IMAGE_MODE_EXISTING ? NULL : bs->drv->format_name;
3119 /* Early check to avoid creating target */
3120 if (bdrv_op_is_blocked(bs, BLOCK_OP_TYPE_BACKUP_SOURCE, errp)) {
3124 flags = bs->open_flags | BDRV_O_RDWR;
3126 /* See if we have a backing HD we can use to create our new image
3128 if (sync == MIRROR_SYNC_MODE_TOP) {
3129 source = backing_bs(bs);
3131 sync = MIRROR_SYNC_MODE_FULL;
3134 if (sync == MIRROR_SYNC_MODE_NONE) {
3138 size = bdrv_getlength(bs);
3140 error_setg_errno(errp, -size, "bdrv_getlength failed");
3144 if (mode != NEW_IMAGE_MODE_EXISTING) {
3147 bdrv_img_create(target, format, source->filename,
3148 source->drv->format_name, NULL,
3149 size, flags, &local_err, false);
3151 bdrv_img_create(target, format, NULL, NULL, NULL,
3152 size, flags, &local_err, false);
3157 error_propagate(errp, local_err);
3162 options = qdict_new();
3163 qdict_put(options, "driver", qstring_from_str(format));
3167 ret = bdrv_open(&target_bs, target, NULL, options, flags, &local_err);
3169 error_propagate(errp, local_err);
3173 bdrv_set_aio_context(target_bs, aio_context);
3176 bmap = bdrv_find_dirty_bitmap(bs, bitmap);
3178 error_setg(errp, "Bitmap '%s' could not be found", bitmap);
3179 bdrv_unref(target_bs);
3184 backup_start(bs, target_bs, speed, sync, bmap,
3185 on_source_error, on_target_error,
3186 block_job_cb, bs, txn, &local_err);
3187 if (local_err != NULL) {
3188 bdrv_unref(target_bs);
3189 error_propagate(errp, local_err);
3194 aio_context_release(aio_context);
3197 void qmp_drive_backup(const char *device, const char *target,
3198 bool has_format, const char *format,
3199 enum MirrorSyncMode sync,
3200 bool has_mode, enum NewImageMode mode,
3201 bool has_speed, int64_t speed,
3202 bool has_bitmap, const char *bitmap,
3203 bool has_on_source_error, BlockdevOnError on_source_error,
3204 bool has_on_target_error, BlockdevOnError on_target_error,
3207 return do_drive_backup(device, target, has_format, format, sync,
3208 has_mode, mode, has_speed, speed,
3210 has_on_source_error, on_source_error,
3211 has_on_target_error, on_target_error,
3215 BlockDeviceInfoList *qmp_query_named_block_nodes(Error **errp)
3217 return bdrv_named_nodes_list(errp);
3220 void do_blockdev_backup(const char *device, const char *target,
3221 enum MirrorSyncMode sync,
3222 bool has_speed, int64_t speed,
3223 bool has_on_source_error,
3224 BlockdevOnError on_source_error,
3225 bool has_on_target_error,
3226 BlockdevOnError on_target_error,
3227 BlockJobTxn *txn, Error **errp)
3229 BlockBackend *blk, *target_blk;
3230 BlockDriverState *bs;
3231 BlockDriverState *target_bs;
3232 Error *local_err = NULL;
3233 AioContext *aio_context;
3238 if (!has_on_source_error) {
3239 on_source_error = BLOCKDEV_ON_ERROR_REPORT;
3241 if (!has_on_target_error) {
3242 on_target_error = BLOCKDEV_ON_ERROR_REPORT;
3245 blk = blk_by_name(device);
3247 error_setg(errp, "Device '%s' not found", device);
3251 aio_context = blk_get_aio_context(blk);
3252 aio_context_acquire(aio_context);
3254 if (!blk_is_available(blk)) {
3255 error_setg(errp, "Device '%s' has no medium", device);
3260 target_blk = blk_by_name(target);
3262 error_setg(errp, "Device '%s' not found", target);
3266 if (!blk_is_available(target_blk)) {
3267 error_setg(errp, "Device '%s' has no medium", target);
3270 target_bs = blk_bs(target_blk);
3272 bdrv_ref(target_bs);
3273 bdrv_set_aio_context(target_bs, aio_context);
3274 backup_start(bs, target_bs, speed, sync, NULL, on_source_error,
3275 on_target_error, block_job_cb, bs, txn, &local_err);
3276 if (local_err != NULL) {
3277 bdrv_unref(target_bs);
3278 error_propagate(errp, local_err);
3281 aio_context_release(aio_context);
3284 void qmp_blockdev_backup(const char *device, const char *target,
3285 enum MirrorSyncMode sync,
3286 bool has_speed, int64_t speed,
3287 bool has_on_source_error,
3288 BlockdevOnError on_source_error,
3289 bool has_on_target_error,
3290 BlockdevOnError on_target_error,
3293 do_blockdev_backup(device, target, sync, has_speed, speed,
3294 has_on_source_error, on_source_error,
3295 has_on_target_error, on_target_error,
3299 void qmp_drive_mirror(const char *device, const char *target,
3300 bool has_format, const char *format,
3301 bool has_node_name, const char *node_name,
3302 bool has_replaces, const char *replaces,
3303 enum MirrorSyncMode sync,
3304 bool has_mode, enum NewImageMode mode,
3305 bool has_speed, int64_t speed,
3306 bool has_granularity, uint32_t granularity,
3307 bool has_buf_size, int64_t buf_size,
3308 bool has_on_source_error, BlockdevOnError on_source_error,
3309 bool has_on_target_error, BlockdevOnError on_target_error,
3310 bool has_unmap, bool unmap,
3314 BlockDriverState *bs;
3315 BlockDriverState *source, *target_bs;
3316 AioContext *aio_context;
3317 Error *local_err = NULL;
3326 if (!has_on_source_error) {
3327 on_source_error = BLOCKDEV_ON_ERROR_REPORT;
3329 if (!has_on_target_error) {
3330 on_target_error = BLOCKDEV_ON_ERROR_REPORT;
3333 mode = NEW_IMAGE_MODE_ABSOLUTE_PATHS;
3335 if (!has_granularity) {
3338 if (!has_buf_size) {
3345 if (granularity != 0 && (granularity < 512 || granularity > 1048576 * 64)) {
3346 error_setg(errp, QERR_INVALID_PARAMETER_VALUE, "granularity",
3347 "a value in range [512B, 64MB]");
3350 if (granularity & (granularity - 1)) {
3351 error_setg(errp, QERR_INVALID_PARAMETER_VALUE, "granularity",
3356 blk = blk_by_name(device);
3358 error_set(errp, ERROR_CLASS_DEVICE_NOT_FOUND,
3359 "Device '%s' not found", device);
3363 aio_context = blk_get_aio_context(blk);
3364 aio_context_acquire(aio_context);
3366 if (!blk_is_available(blk)) {
3367 error_setg(errp, QERR_DEVICE_HAS_NO_MEDIUM, device);
3373 format = mode == NEW_IMAGE_MODE_EXISTING ? NULL : bs->drv->format_name;
3376 if (bdrv_op_is_blocked(bs, BLOCK_OP_TYPE_MIRROR, errp)) {
3380 flags = bs->open_flags | BDRV_O_RDWR;
3381 source = backing_bs(bs);
3382 if (!source && sync == MIRROR_SYNC_MODE_TOP) {
3383 sync = MIRROR_SYNC_MODE_FULL;
3385 if (sync == MIRROR_SYNC_MODE_NONE) {
3389 size = bdrv_getlength(bs);
3391 error_setg_errno(errp, -size, "bdrv_getlength failed");
3396 BlockDriverState *to_replace_bs;
3397 AioContext *replace_aio_context;
3398 int64_t replace_size;
3400 if (!has_node_name) {
3401 error_setg(errp, "a node-name must be provided when replacing a"
3402 " named node of the graph");
3406 to_replace_bs = check_to_replace_node(bs, replaces, &local_err);
3408 if (!to_replace_bs) {
3409 error_propagate(errp, local_err);
3413 replace_aio_context = bdrv_get_aio_context(to_replace_bs);
3414 aio_context_acquire(replace_aio_context);
3415 replace_size = bdrv_getlength(to_replace_bs);
3416 aio_context_release(replace_aio_context);
3418 if (size != replace_size) {
3419 error_setg(errp, "cannot replace image with a mirror image of "
3425 if ((sync == MIRROR_SYNC_MODE_FULL || !source)
3426 && mode != NEW_IMAGE_MODE_EXISTING)
3428 /* create new image w/o backing file */
3430 bdrv_img_create(target, format,
3431 NULL, NULL, NULL, size, flags, &local_err, false);
3434 case NEW_IMAGE_MODE_EXISTING:
3436 case NEW_IMAGE_MODE_ABSOLUTE_PATHS:
3437 /* create new image with backing file */
3438 bdrv_img_create(target, format,
3440 source->drv->format_name,
3441 NULL, size, flags, &local_err, false);
3449 error_propagate(errp, local_err);
3453 options = qdict_new();
3454 if (has_node_name) {
3455 qdict_put(options, "node-name", qstring_from_str(node_name));
3458 qdict_put(options, "driver", qstring_from_str(format));
3461 /* Mirroring takes care of copy-on-write using the source's backing
3465 ret = bdrv_open(&target_bs, target, NULL, options,
3466 flags | BDRV_O_NO_BACKING, &local_err);
3468 error_propagate(errp, local_err);
3472 bdrv_set_aio_context(target_bs, aio_context);
3474 /* pass the node name to replace to mirror start since it's loose coupling
3475 * and will allow to check whether the node still exist at mirror completion
3477 mirror_start(bs, target_bs,
3478 has_replaces ? replaces : NULL,
3479 speed, granularity, buf_size, sync,
3480 on_source_error, on_target_error,
3482 block_job_cb, bs, &local_err);
3483 if (local_err != NULL) {
3484 bdrv_unref(target_bs);
3485 error_propagate(errp, local_err);
3490 aio_context_release(aio_context);
3493 /* Get the block job for a given device name and acquire its AioContext */
3494 static BlockJob *find_block_job(const char *device, AioContext **aio_context,
3498 BlockDriverState *bs;
3500 *aio_context = NULL;
3502 blk = blk_by_name(device);
3507 *aio_context = blk_get_aio_context(blk);
3508 aio_context_acquire(*aio_context);
3510 if (!blk_is_available(blk)) {
3522 error_set(errp, ERROR_CLASS_DEVICE_NOT_ACTIVE,
3523 "No active block job on device '%s'", device);
3525 aio_context_release(*aio_context);
3526 *aio_context = NULL;
3531 void qmp_block_job_set_speed(const char *device, int64_t speed, Error **errp)
3533 AioContext *aio_context;
3534 BlockJob *job = find_block_job(device, &aio_context, errp);
3540 block_job_set_speed(job, speed, errp);
3541 aio_context_release(aio_context);
3544 void qmp_block_job_cancel(const char *device,
3545 bool has_force, bool force, Error **errp)
3547 AioContext *aio_context;
3548 BlockJob *job = find_block_job(device, &aio_context, errp);
3558 if (job->user_paused && !force) {
3559 error_setg(errp, "The block job for device '%s' is currently paused",
3564 trace_qmp_block_job_cancel(job);
3565 block_job_cancel(job);
3567 aio_context_release(aio_context);
3570 void qmp_block_job_pause(const char *device, Error **errp)
3572 AioContext *aio_context;
3573 BlockJob *job = find_block_job(device, &aio_context, errp);
3575 if (!job || job->user_paused) {
3579 job->user_paused = true;
3580 trace_qmp_block_job_pause(job);
3581 block_job_pause(job);
3582 aio_context_release(aio_context);
3585 void qmp_block_job_resume(const char *device, Error **errp)
3587 AioContext *aio_context;
3588 BlockJob *job = find_block_job(device, &aio_context, errp);
3590 if (!job || !job->user_paused) {
3594 job->user_paused = false;
3595 trace_qmp_block_job_resume(job);
3596 block_job_resume(job);
3597 aio_context_release(aio_context);
3600 void qmp_block_job_complete(const char *device, Error **errp)
3602 AioContext *aio_context;
3603 BlockJob *job = find_block_job(device, &aio_context, errp);
3609 trace_qmp_block_job_complete(job);
3610 block_job_complete(job, errp);
3611 aio_context_release(aio_context);
3614 void qmp_change_backing_file(const char *device,
3615 const char *image_node_name,
3616 const char *backing_file,
3620 BlockDriverState *bs = NULL;
3621 AioContext *aio_context;
3622 BlockDriverState *image_bs = NULL;
3623 Error *local_err = NULL;
3628 blk = blk_by_name(device);
3630 error_set(errp, ERROR_CLASS_DEVICE_NOT_FOUND,
3631 "Device '%s' not found", device);
3635 aio_context = blk_get_aio_context(blk);
3636 aio_context_acquire(aio_context);
3638 if (!blk_is_available(blk)) {
3639 error_setg(errp, "Device '%s' has no medium", device);
3644 image_bs = bdrv_lookup_bs(NULL, image_node_name, &local_err);
3646 error_propagate(errp, local_err);
3651 error_setg(errp, "image file not found");
3655 if (bdrv_find_base(image_bs) == image_bs) {
3656 error_setg(errp, "not allowing backing file change on an image "
3657 "without a backing file");
3661 /* even though we are not necessarily operating on bs, we need it to
3662 * determine if block ops are currently prohibited on the chain */
3663 if (bdrv_op_is_blocked(bs, BLOCK_OP_TYPE_CHANGE, errp)) {
3667 /* final sanity check */
3668 if (!bdrv_chain_contains(bs, image_bs)) {
3669 error_setg(errp, "'%s' and image file are not in the same chain",
3674 /* if not r/w, reopen to make r/w */
3675 open_flags = image_bs->open_flags;
3676 ro = bdrv_is_read_only(image_bs);
3679 bdrv_reopen(image_bs, open_flags | BDRV_O_RDWR, &local_err);
3681 error_propagate(errp, local_err);
3686 ret = bdrv_change_backing_file(image_bs, backing_file,
3687 image_bs->drv ? image_bs->drv->format_name : "");
3690 error_setg_errno(errp, -ret, "Could not change backing file to '%s'",
3692 /* don't exit here, so we can try to restore open flags if
3697 bdrv_reopen(image_bs, open_flags, &local_err);
3699 error_propagate(errp, local_err); /* will preserve prior errp */
3704 aio_context_release(aio_context);
3707 void qmp_blockdev_add(BlockdevOptions *options, Error **errp)
3709 QmpOutputVisitor *ov = qmp_output_visitor_new();
3710 BlockDriverState *bs;
3711 BlockBackend *blk = NULL;
3714 Error *local_err = NULL;
3716 /* TODO Sort it out in raw-posix and drive_new(): Reject aio=native with
3717 * cache.direct=false instead of silently switching to aio=threads, except
3718 * when called from drive_new().
3720 * For now, simply forbidding the combination for all drivers will do. */
3721 if (options->has_aio && options->aio == BLOCKDEV_AIO_OPTIONS_NATIVE) {
3722 bool direct = options->has_cache &&
3723 options->cache->has_direct &&
3724 options->cache->direct;
3726 error_setg(errp, "aio=native requires cache.direct=true");
3731 visit_type_BlockdevOptions(qmp_output_get_visitor(ov),
3732 &options, NULL, &local_err);
3734 error_propagate(errp, local_err);
3738 obj = qmp_output_get_qobject(ov);
3739 qdict = qobject_to_qdict(obj);
3741 qdict_flatten(qdict);
3743 if (options->has_id) {
3744 blk = blockdev_init(NULL, qdict, &local_err);
3746 error_propagate(errp, local_err);
3752 if (!qdict_get_try_str(qdict, "node-name")) {
3753 error_setg(errp, "'id' and/or 'node-name' need to be specified for "
3758 bs = bds_tree_init(qdict, errp);
3764 if (bs && bdrv_key_required(bs)) {
3770 error_setg(errp, "blockdev-add doesn't support encrypted devices");
3775 qmp_output_visitor_cleanup(ov);
3778 void qmp_x_blockdev_del(bool has_id, const char *id,
3779 bool has_node_name, const char *node_name, Error **errp)
3781 AioContext *aio_context;
3783 BlockDriverState *bs;
3785 if (has_id && has_node_name) {
3786 error_setg(errp, "Only one of id and node-name must be specified");
3788 } else if (!has_id && !has_node_name) {
3789 error_setg(errp, "No block device specified");
3794 blk = blk_by_name(id);
3796 error_setg(errp, "Cannot find block backend %s", id);
3799 if (blk_get_refcnt(blk) > 1) {
3800 error_setg(errp, "Block backend %s is in use", id);
3804 aio_context = blk_get_aio_context(blk);
3806 bs = bdrv_find_node(node_name);
3808 error_setg(errp, "Cannot find node %s", node_name);
3813 error_setg(errp, "Node %s is in use by %s",
3814 node_name, blk_name(blk));
3817 aio_context = bdrv_get_aio_context(bs);
3820 aio_context_acquire(aio_context);
3823 if (bdrv_op_is_blocked(bs, BLOCK_OP_TYPE_DRIVE_DEL, errp)) {
3827 if (bs->refcnt > 1 || !QLIST_EMPTY(&bs->parents)) {
3828 error_setg(errp, "Block device %s is in use",
3829 bdrv_get_device_or_node_name(bs));
3841 aio_context_release(aio_context);
3844 BlockJobInfoList *qmp_query_block_jobs(Error **errp)
3846 BlockJobInfoList *head = NULL, **p_next = &head;
3847 BlockDriverState *bs;
3849 for (bs = bdrv_next(NULL); bs; bs = bdrv_next(bs)) {
3850 AioContext *aio_context = bdrv_get_aio_context(bs);
3852 aio_context_acquire(aio_context);
3855 BlockJobInfoList *elem = g_new0(BlockJobInfoList, 1);
3856 elem->value = block_job_query(bs->job);
3858 p_next = &elem->next;
3861 aio_context_release(aio_context);
3867 QemuOptsList qemu_common_drive_opts = {
3869 .head = QTAILQ_HEAD_INITIALIZER(qemu_common_drive_opts.head),
3873 .type = QEMU_OPT_BOOL,
3874 .help = "enable/disable snapshot mode",
3877 .type = QEMU_OPT_STRING,
3878 .help = "discard operation (ignore/off, unmap/on)",
3880 .name = BDRV_OPT_CACHE_WB,
3881 .type = QEMU_OPT_BOOL,
3882 .help = "enables writeback mode for any caches",
3884 .name = BDRV_OPT_CACHE_DIRECT,
3885 .type = QEMU_OPT_BOOL,
3886 .help = "enables use of O_DIRECT (bypass the host page cache)",
3888 .name = BDRV_OPT_CACHE_NO_FLUSH,
3889 .type = QEMU_OPT_BOOL,
3890 .help = "ignore any flush requests for the device",
3893 .type = QEMU_OPT_STRING,
3894 .help = "host AIO implementation (threads, native)",
3897 .type = QEMU_OPT_STRING,
3898 .help = "disk format (raw, qcow2, ...)",
3901 .type = QEMU_OPT_STRING,
3902 .help = "read error action",
3905 .type = QEMU_OPT_STRING,
3906 .help = "write error action",
3908 .name = "read-only",
3909 .type = QEMU_OPT_BOOL,
3910 .help = "open drive file as read-only",
3912 .name = "throttling.iops-total",
3913 .type = QEMU_OPT_NUMBER,
3914 .help = "limit total I/O operations per second",
3916 .name = "throttling.iops-read",
3917 .type = QEMU_OPT_NUMBER,
3918 .help = "limit read operations per second",
3920 .name = "throttling.iops-write",
3921 .type = QEMU_OPT_NUMBER,
3922 .help = "limit write operations per second",
3924 .name = "throttling.bps-total",
3925 .type = QEMU_OPT_NUMBER,
3926 .help = "limit total bytes per second",
3928 .name = "throttling.bps-read",
3929 .type = QEMU_OPT_NUMBER,
3930 .help = "limit read bytes per second",
3932 .name = "throttling.bps-write",
3933 .type = QEMU_OPT_NUMBER,
3934 .help = "limit write bytes per second",
3936 .name = "throttling.iops-total-max",
3937 .type = QEMU_OPT_NUMBER,
3938 .help = "I/O operations burst",
3940 .name = "throttling.iops-read-max",
3941 .type = QEMU_OPT_NUMBER,
3942 .help = "I/O operations read burst",
3944 .name = "throttling.iops-write-max",
3945 .type = QEMU_OPT_NUMBER,
3946 .help = "I/O operations write burst",
3948 .name = "throttling.bps-total-max",
3949 .type = QEMU_OPT_NUMBER,
3950 .help = "total bytes burst",
3952 .name = "throttling.bps-read-max",
3953 .type = QEMU_OPT_NUMBER,
3954 .help = "total bytes read burst",
3956 .name = "throttling.bps-write-max",
3957 .type = QEMU_OPT_NUMBER,
3958 .help = "total bytes write burst",
3960 .name = "throttling.iops-size",
3961 .type = QEMU_OPT_NUMBER,
3962 .help = "when limiting by iops max size of an I/O in bytes",
3964 .name = "throttling.group",
3965 .type = QEMU_OPT_STRING,
3966 .help = "name of the block throttling group",
3968 .name = "copy-on-read",
3969 .type = QEMU_OPT_BOOL,
3970 .help = "copy read data from backing file into image file",
3972 .name = "detect-zeroes",
3973 .type = QEMU_OPT_STRING,
3974 .help = "try to optimize zero writes (off, on, unmap)",
3976 .name = "stats-account-invalid",
3977 .type = QEMU_OPT_BOOL,
3978 .help = "whether to account for invalid I/O operations "
3979 "in the statistics",
3981 .name = "stats-account-failed",
3982 .type = QEMU_OPT_BOOL,
3983 .help = "whether to account for failed I/O operations "
3984 "in the statistics",
3986 { /* end of list */ }
3990 static QemuOptsList qemu_root_bds_opts = {
3992 .head = QTAILQ_HEAD_INITIALIZER(qemu_common_drive_opts.head),
3996 .type = QEMU_OPT_STRING,
3997 .help = "discard operation (ignore/off, unmap/on)",
3999 .name = "cache.writeback",
4000 .type = QEMU_OPT_BOOL,
4001 .help = "enables writeback mode for any caches",
4003 .name = "cache.direct",
4004 .type = QEMU_OPT_BOOL,
4005 .help = "enables use of O_DIRECT (bypass the host page cache)",
4007 .name = "cache.no-flush",
4008 .type = QEMU_OPT_BOOL,
4009 .help = "ignore any flush requests for the device",
4012 .type = QEMU_OPT_STRING,
4013 .help = "host AIO implementation (threads, native)",
4015 .name = "read-only",
4016 .type = QEMU_OPT_BOOL,
4017 .help = "open drive file as read-only",
4019 .name = "copy-on-read",
4020 .type = QEMU_OPT_BOOL,
4021 .help = "copy read data from backing file into image file",
4023 .name = "detect-zeroes",
4024 .type = QEMU_OPT_STRING,
4025 .help = "try to optimize zero writes (off, on, unmap)",
4027 { /* end of list */ }
4031 QemuOptsList qemu_drive_opts = {
4033 .head = QTAILQ_HEAD_INITIALIZER(qemu_drive_opts.head),
4036 * no elements => accept any params
4037 * validation will happen later
4039 { /* end of list */ }