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 int do_open_tray(const char *device, bool force, Error **errp);
65 static const char *const if_name[IF_COUNT] = {
69 [IF_FLOPPY] = "floppy",
70 [IF_PFLASH] = "pflash",
73 [IF_VIRTIO] = "virtio",
77 static int if_max_devs[IF_COUNT] = {
79 * Do not change these numbers! They govern how drive option
80 * index maps to unit and bus. That mapping is ABI.
82 * All controllers used to implement if=T drives need to support
83 * if_max_devs[T] units, for any T with if_max_devs[T] != 0.
84 * Otherwise, some index values map to "impossible" bus, unit
87 * For instance, if you change [IF_SCSI] to 255, -drive
88 * if=scsi,index=12 no longer means bus=1,unit=5, but
89 * bus=0,unit=12. With an lsi53c895a controller (7 units max),
90 * the drive can't be set up. Regression.
97 * Boards may call this to offer board-by-board overrides
98 * of the default, global values.
100 void override_max_devs(BlockInterfaceType type, int max_devs)
109 for (blk = blk_next(NULL); blk; blk = blk_next(blk)) {
110 dinfo = blk_legacy_dinfo(blk);
111 if (dinfo->type == type) {
112 fprintf(stderr, "Cannot override units-per-bus property of"
113 " the %s interface, because a drive of that type has"
114 " already been added.\n", if_name[type]);
115 g_assert_not_reached();
119 if_max_devs[type] = max_devs;
123 * We automatically delete the drive when a device using it gets
124 * unplugged. Questionable feature, but we can't just drop it.
125 * Device models call blockdev_mark_auto_del() to schedule the
126 * automatic deletion, and generic qdev code calls blockdev_auto_del()
127 * when deletion is actually safe.
129 void blockdev_mark_auto_del(BlockBackend *blk)
131 DriveInfo *dinfo = blk_legacy_dinfo(blk);
132 BlockDriverState *bs = blk_bs(blk);
133 AioContext *aio_context;
140 aio_context = bdrv_get_aio_context(bs);
141 aio_context_acquire(aio_context);
144 block_job_cancel(bs->job);
147 aio_context_release(aio_context);
153 void blockdev_auto_del(BlockBackend *blk)
155 DriveInfo *dinfo = blk_legacy_dinfo(blk);
157 if (dinfo && dinfo->auto_del) {
158 monitor_remove_blk(blk);
164 * Returns the current mapping of how many units per bus
165 * a particular interface can support.
167 * A positive integer indicates n units per bus.
168 * 0 implies the mapping has not been established.
169 * -1 indicates an invalid BlockInterfaceType was given.
171 int drive_get_max_devs(BlockInterfaceType type)
173 if (type >= IF_IDE && type < IF_COUNT) {
174 return if_max_devs[type];
180 static int drive_index_to_bus_id(BlockInterfaceType type, int index)
182 int max_devs = if_max_devs[type];
183 return max_devs ? index / max_devs : 0;
186 static int drive_index_to_unit_id(BlockInterfaceType type, int index)
188 int max_devs = if_max_devs[type];
189 return max_devs ? index % max_devs : index;
192 QemuOpts *drive_def(const char *optstr)
194 return qemu_opts_parse_noisily(qemu_find_opts("drive"), optstr, false);
197 QemuOpts *drive_add(BlockInterfaceType type, int index, const char *file,
202 opts = drive_def(optstr);
206 if (type != IF_DEFAULT) {
207 qemu_opt_set(opts, "if", if_name[type], &error_abort);
210 qemu_opt_set_number(opts, "index", index, &error_abort);
213 qemu_opt_set(opts, "file", file, &error_abort);
217 DriveInfo *drive_get(BlockInterfaceType type, int bus, int unit)
222 for (blk = blk_next(NULL); blk; blk = blk_next(blk)) {
223 dinfo = blk_legacy_dinfo(blk);
224 if (dinfo && dinfo->type == type
225 && dinfo->bus == bus && dinfo->unit == unit) {
233 bool drive_check_orphaned(void)
239 for (blk = blk_next(NULL); blk; blk = blk_next(blk)) {
240 dinfo = blk_legacy_dinfo(blk);
241 /* If dinfo->bdrv->dev is NULL, it has no device attached. */
242 /* Unless this is a default drive, this may be an oversight. */
243 if (!blk_get_attached_dev(blk) && !dinfo->is_default &&
244 dinfo->type != IF_NONE) {
245 fprintf(stderr, "Warning: Orphaned drive without device: "
246 "id=%s,file=%s,if=%s,bus=%d,unit=%d\n",
247 blk_name(blk), blk_bs(blk) ? blk_bs(blk)->filename : "",
248 if_name[dinfo->type], dinfo->bus, dinfo->unit);
256 DriveInfo *drive_get_by_index(BlockInterfaceType type, int index)
258 return drive_get(type,
259 drive_index_to_bus_id(type, index),
260 drive_index_to_unit_id(type, index));
263 int drive_get_max_bus(BlockInterfaceType type)
270 for (blk = blk_next(NULL); blk; blk = blk_next(blk)) {
271 dinfo = blk_legacy_dinfo(blk);
272 if (dinfo && dinfo->type == type && dinfo->bus > max_bus) {
273 max_bus = dinfo->bus;
279 /* Get a block device. This should only be used for single-drive devices
280 (e.g. SD/Floppy/MTD). Multi-disk devices (scsi/ide) should use the
282 DriveInfo *drive_get_next(BlockInterfaceType type)
284 static int next_block_unit[IF_COUNT];
286 return drive_get(type, 0, next_block_unit[type]++);
289 static void bdrv_format_print(void *opaque, const char *name)
291 error_printf(" %s", name);
296 BlockDriverState *bs;
299 static int parse_block_error_action(const char *buf, bool is_read, Error **errp)
301 if (!strcmp(buf, "ignore")) {
302 return BLOCKDEV_ON_ERROR_IGNORE;
303 } else if (!is_read && !strcmp(buf, "enospc")) {
304 return BLOCKDEV_ON_ERROR_ENOSPC;
305 } else if (!strcmp(buf, "stop")) {
306 return BLOCKDEV_ON_ERROR_STOP;
307 } else if (!strcmp(buf, "report")) {
308 return BLOCKDEV_ON_ERROR_REPORT;
310 error_setg(errp, "'%s' invalid %s error action",
311 buf, is_read ? "read" : "write");
316 static bool parse_stats_intervals(BlockAcctStats *stats, QList *intervals,
319 const QListEntry *entry;
320 for (entry = qlist_first(intervals); entry; entry = qlist_next(entry)) {
321 switch (qobject_type(entry->value)) {
323 case QTYPE_QSTRING: {
324 unsigned long long length;
325 const char *str = qstring_get_str(qobject_to_qstring(entry->value));
326 if (parse_uint_full(str, &length, 10) == 0 &&
327 length > 0 && length <= UINT_MAX) {
328 block_acct_add_interval(stats, (unsigned) length);
330 error_setg(errp, "Invalid interval length: %s", str);
337 int64_t length = qint_get_int(qobject_to_qint(entry->value));
338 if (length > 0 && length <= UINT_MAX) {
339 block_acct_add_interval(stats, (unsigned) length);
341 error_setg(errp, "Invalid interval length: %" PRId64, length);
348 error_setg(errp, "The specification of stats-intervals is invalid");
355 typedef enum { MEDIA_DISK, MEDIA_CDROM } DriveMediaType;
357 /* All parameters but @opts are optional and may be set to NULL. */
358 static void extract_common_blockdev_options(QemuOpts *opts, int *bdrv_flags,
359 const char **throttling_group, ThrottleConfig *throttle_cfg,
360 BlockdevDetectZeroesOptions *detect_zeroes, Error **errp)
363 Error *local_error = NULL;
367 if (!qemu_opt_get_bool(opts, "read-only", false)) {
368 *bdrv_flags |= BDRV_O_RDWR;
370 if (qemu_opt_get_bool(opts, "copy-on-read", false)) {
371 *bdrv_flags |= BDRV_O_COPY_ON_READ;
374 if ((discard = qemu_opt_get(opts, "discard")) != NULL) {
375 if (bdrv_parse_discard_flags(discard, bdrv_flags) != 0) {
376 error_setg(errp, "Invalid discard option");
381 if ((aio = qemu_opt_get(opts, "aio")) != NULL) {
382 if (!strcmp(aio, "native")) {
383 *bdrv_flags |= BDRV_O_NATIVE_AIO;
384 } else if (!strcmp(aio, "threads")) {
385 /* this is the default */
387 error_setg(errp, "invalid aio option");
393 /* disk I/O throttling */
394 if (throttling_group) {
395 *throttling_group = qemu_opt_get(opts, "throttling.group");
399 throttle_config_init(throttle_cfg);
400 throttle_cfg->buckets[THROTTLE_BPS_TOTAL].avg =
401 qemu_opt_get_number(opts, "throttling.bps-total", 0);
402 throttle_cfg->buckets[THROTTLE_BPS_READ].avg =
403 qemu_opt_get_number(opts, "throttling.bps-read", 0);
404 throttle_cfg->buckets[THROTTLE_BPS_WRITE].avg =
405 qemu_opt_get_number(opts, "throttling.bps-write", 0);
406 throttle_cfg->buckets[THROTTLE_OPS_TOTAL].avg =
407 qemu_opt_get_number(opts, "throttling.iops-total", 0);
408 throttle_cfg->buckets[THROTTLE_OPS_READ].avg =
409 qemu_opt_get_number(opts, "throttling.iops-read", 0);
410 throttle_cfg->buckets[THROTTLE_OPS_WRITE].avg =
411 qemu_opt_get_number(opts, "throttling.iops-write", 0);
413 throttle_cfg->buckets[THROTTLE_BPS_TOTAL].max =
414 qemu_opt_get_number(opts, "throttling.bps-total-max", 0);
415 throttle_cfg->buckets[THROTTLE_BPS_READ].max =
416 qemu_opt_get_number(opts, "throttling.bps-read-max", 0);
417 throttle_cfg->buckets[THROTTLE_BPS_WRITE].max =
418 qemu_opt_get_number(opts, "throttling.bps-write-max", 0);
419 throttle_cfg->buckets[THROTTLE_OPS_TOTAL].max =
420 qemu_opt_get_number(opts, "throttling.iops-total-max", 0);
421 throttle_cfg->buckets[THROTTLE_OPS_READ].max =
422 qemu_opt_get_number(opts, "throttling.iops-read-max", 0);
423 throttle_cfg->buckets[THROTTLE_OPS_WRITE].max =
424 qemu_opt_get_number(opts, "throttling.iops-write-max", 0);
426 throttle_cfg->buckets[THROTTLE_BPS_TOTAL].burst_length =
427 qemu_opt_get_number(opts, "throttling.bps-total-max-length", 1);
428 throttle_cfg->buckets[THROTTLE_BPS_READ].burst_length =
429 qemu_opt_get_number(opts, "throttling.bps-read-max-length", 1);
430 throttle_cfg->buckets[THROTTLE_BPS_WRITE].burst_length =
431 qemu_opt_get_number(opts, "throttling.bps-write-max-length", 1);
432 throttle_cfg->buckets[THROTTLE_OPS_TOTAL].burst_length =
433 qemu_opt_get_number(opts, "throttling.iops-total-max-length", 1);
434 throttle_cfg->buckets[THROTTLE_OPS_READ].burst_length =
435 qemu_opt_get_number(opts, "throttling.iops-read-max-length", 1);
436 throttle_cfg->buckets[THROTTLE_OPS_WRITE].burst_length =
437 qemu_opt_get_number(opts, "throttling.iops-write-max-length", 1);
439 throttle_cfg->op_size =
440 qemu_opt_get_number(opts, "throttling.iops-size", 0);
442 if (!throttle_is_valid(throttle_cfg, errp)) {
449 qapi_enum_parse(BlockdevDetectZeroesOptions_lookup,
450 qemu_opt_get(opts, "detect-zeroes"),
451 BLOCKDEV_DETECT_ZEROES_OPTIONS__MAX,
452 BLOCKDEV_DETECT_ZEROES_OPTIONS_OFF,
455 error_propagate(errp, local_error);
460 *detect_zeroes == BLOCKDEV_DETECT_ZEROES_OPTIONS_UNMAP &&
461 !(*bdrv_flags & BDRV_O_UNMAP))
463 error_setg(errp, "setting detect-zeroes to unmap is not allowed "
464 "without setting discard operation to unmap");
470 /* Takes the ownership of bs_opts */
471 static BlockBackend *blockdev_init(const char *file, QDict *bs_opts,
476 int on_read_error, on_write_error;
477 bool account_invalid, account_failed;
480 BlockDriverState *bs;
485 QDict *interval_dict = NULL;
486 QList *interval_list = NULL;
488 BlockdevDetectZeroesOptions detect_zeroes =
489 BLOCKDEV_DETECT_ZEROES_OPTIONS_OFF;
490 const char *throttling_group = NULL;
492 /* Check common options by copying from bs_opts to opts, all other options
493 * stay in bs_opts for processing by bdrv_open(). */
494 id = qdict_get_try_str(bs_opts, "id");
495 opts = qemu_opts_create(&qemu_common_drive_opts, id, 1, &error);
497 error_propagate(errp, error);
501 qemu_opts_absorb_qdict(opts, bs_opts, &error);
503 error_propagate(errp, error);
508 qdict_del(bs_opts, "id");
511 /* extract parameters */
512 snapshot = qemu_opt_get_bool(opts, "snapshot", 0);
514 account_invalid = qemu_opt_get_bool(opts, "stats-account-invalid", true);
515 account_failed = qemu_opt_get_bool(opts, "stats-account-failed", true);
517 writethrough = !qemu_opt_get_bool(opts, BDRV_OPT_CACHE_WB, true);
519 id = qemu_opts_id(opts);
521 qdict_extract_subqdict(bs_opts, &interval_dict, "stats-intervals.");
522 qdict_array_split(interval_dict, &interval_list);
524 if (qdict_size(interval_dict) != 0) {
525 error_setg(errp, "Invalid option stats-intervals.%s",
526 qdict_first(interval_dict)->key);
530 extract_common_blockdev_options(opts, &bdrv_flags, &throttling_group, &cfg,
531 &detect_zeroes, &error);
533 error_propagate(errp, error);
537 if ((buf = qemu_opt_get(opts, "format")) != NULL) {
538 if (is_help_option(buf)) {
539 error_printf("Supported formats:");
540 bdrv_iterate_format(bdrv_format_print, NULL);
545 if (qdict_haskey(bs_opts, "driver")) {
546 error_setg(errp, "Cannot specify both 'driver' and 'format'");
549 qdict_put(bs_opts, "driver", qstring_from_str(buf));
552 on_write_error = BLOCKDEV_ON_ERROR_ENOSPC;
553 if ((buf = qemu_opt_get(opts, "werror")) != NULL) {
554 on_write_error = parse_block_error_action(buf, 0, &error);
556 error_propagate(errp, error);
561 on_read_error = BLOCKDEV_ON_ERROR_REPORT;
562 if ((buf = qemu_opt_get(opts, "rerror")) != NULL) {
563 on_read_error = parse_block_error_action(buf, 1, &error);
565 error_propagate(errp, error);
571 bdrv_flags |= BDRV_O_SNAPSHOT;
575 if ((!file || !*file) && !qdict_size(bs_opts)) {
576 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;
586 if (file && !*file) {
590 /* bdrv_open() defaults to the values in bdrv_flags (for compatibility
591 * with other callers) rather than what we want as the real defaults.
592 * Apply the defaults here instead. */
593 qdict_set_default_str(bs_opts, BDRV_OPT_CACHE_DIRECT, "off");
594 qdict_set_default_str(bs_opts, BDRV_OPT_CACHE_NO_FLUSH, "off");
595 assert((bdrv_flags & BDRV_O_CACHE_MASK) == 0);
597 if (runstate_check(RUN_STATE_INMIGRATE)) {
598 bdrv_flags |= BDRV_O_INACTIVE;
601 blk = blk_new_open(file, NULL, bs_opts, bdrv_flags, errp);
607 bs->detect_zeroes = detect_zeroes;
609 if (bdrv_key_required(bs)) {
613 block_acct_init(blk_get_stats(blk), account_invalid, account_failed);
615 if (!parse_stats_intervals(blk_get_stats(blk), interval_list, errp)) {
622 /* disk I/O throttling */
623 if (throttle_enabled(&cfg)) {
624 if (!throttling_group) {
625 throttling_group = id;
627 blk_io_limits_enable(blk, throttling_group);
628 blk_set_io_limits(blk, &cfg);
631 blk_set_enable_write_cache(blk, !writethrough);
632 blk_set_on_error(blk, on_read_error, on_write_error);
634 if (!monitor_add_blk(blk, id, errp)) {
642 QDECREF(interval_dict);
643 QDECREF(interval_list);
648 QDECREF(interval_dict);
649 QDECREF(interval_list);
655 static QemuOptsList qemu_root_bds_opts;
657 /* Takes the ownership of bs_opts */
658 static BlockDriverState *bds_tree_init(QDict *bs_opts, Error **errp)
660 BlockDriverState *bs;
662 Error *local_error = NULL;
663 BlockdevDetectZeroesOptions detect_zeroes;
666 opts = qemu_opts_create(&qemu_root_bds_opts, NULL, 1, errp);
671 qemu_opts_absorb_qdict(opts, bs_opts, &local_error);
673 error_propagate(errp, local_error);
677 extract_common_blockdev_options(opts, &bdrv_flags, NULL, NULL,
678 &detect_zeroes, &local_error);
680 error_propagate(errp, local_error);
684 /* bdrv_open() defaults to the values in bdrv_flags (for compatibility
685 * with other callers) rather than what we want as the real defaults.
686 * Apply the defaults here instead. */
687 qdict_set_default_str(bs_opts, BDRV_OPT_CACHE_DIRECT, "off");
688 qdict_set_default_str(bs_opts, BDRV_OPT_CACHE_NO_FLUSH, "off");
690 if (runstate_check(RUN_STATE_INMIGRATE)) {
691 bdrv_flags |= BDRV_O_INACTIVE;
694 bs = bdrv_open(NULL, NULL, bs_opts, bdrv_flags, errp);
696 goto fail_no_bs_opts;
699 bs->detect_zeroes = detect_zeroes;
711 void blockdev_close_all_bdrv_states(void)
713 BlockDriverState *bs, *next_bs;
715 QTAILQ_FOREACH_SAFE(bs, &monitor_bdrv_states, monitor_list, next_bs) {
716 AioContext *ctx = bdrv_get_aio_context(bs);
718 aio_context_acquire(ctx);
720 aio_context_release(ctx);
724 /* Iterates over the list of monitor-owned BlockDriverStates */
725 BlockDriverState *bdrv_next_monitor_owned(BlockDriverState *bs)
727 return bs ? QTAILQ_NEXT(bs, monitor_list)
728 : QTAILQ_FIRST(&monitor_bdrv_states);
731 static void qemu_opt_rename(QemuOpts *opts, const char *from, const char *to,
736 value = qemu_opt_get(opts, from);
738 if (qemu_opt_find(opts, to)) {
739 error_setg(errp, "'%s' and its alias '%s' can't be used at the "
740 "same time", to, from);
745 /* rename all items in opts */
746 while ((value = qemu_opt_get(opts, from))) {
747 qemu_opt_set(opts, to, value, &error_abort);
748 qemu_opt_unset(opts, from);
752 QemuOptsList qemu_legacy_drive_opts = {
754 .head = QTAILQ_HEAD_INITIALIZER(qemu_legacy_drive_opts.head),
758 .type = QEMU_OPT_NUMBER,
759 .help = "bus number",
762 .type = QEMU_OPT_NUMBER,
763 .help = "unit number (i.e. lun for scsi)",
766 .type = QEMU_OPT_NUMBER,
767 .help = "index number",
770 .type = QEMU_OPT_STRING,
771 .help = "media type (disk, cdrom)",
774 .type = QEMU_OPT_STRING,
775 .help = "interface (ide, scsi, sd, mtd, floppy, pflash, virtio)",
778 .type = QEMU_OPT_NUMBER,
779 .help = "number of cylinders (ide disk geometry)",
782 .type = QEMU_OPT_NUMBER,
783 .help = "number of heads (ide disk geometry)",
786 .type = QEMU_OPT_NUMBER,
787 .help = "number of sectors (ide disk geometry)",
790 .type = QEMU_OPT_STRING,
791 .help = "chs translation (auto, lba, none)",
794 .type = QEMU_OPT_BOOL,
795 .help = "(deprecated, ignored)",
798 .type = QEMU_OPT_STRING,
799 .help = "pci address (virtio only)",
802 .type = QEMU_OPT_STRING,
803 .help = "disk serial number",
806 .type = QEMU_OPT_STRING,
810 /* Options that are passed on, but have special semantics with -drive */
813 .type = QEMU_OPT_BOOL,
814 .help = "open drive file as read-only",
817 .type = QEMU_OPT_STRING,
818 .help = "read error action",
821 .type = QEMU_OPT_STRING,
822 .help = "write error action",
824 .name = "copy-on-read",
825 .type = QEMU_OPT_BOOL,
826 .help = "copy read data from backing file into image file",
829 { /* end of list */ }
833 DriveInfo *drive_new(QemuOpts *all_opts, BlockInterfaceType block_default_type)
837 DriveInfo *dinfo = NULL;
839 QemuOpts *legacy_opts;
840 DriveMediaType media = MEDIA_DISK;
841 BlockInterfaceType type;
842 int cyls, heads, secs, translation;
843 int max_devs, bus_id, unit_id, index;
845 const char *werror, *rerror;
846 bool read_only = false;
849 const char *filename;
850 Error *local_err = NULL;
853 /* Change legacy command line options into QMP ones */
854 static const struct {
858 { "iops", "throttling.iops-total" },
859 { "iops_rd", "throttling.iops-read" },
860 { "iops_wr", "throttling.iops-write" },
862 { "bps", "throttling.bps-total" },
863 { "bps_rd", "throttling.bps-read" },
864 { "bps_wr", "throttling.bps-write" },
866 { "iops_max", "throttling.iops-total-max" },
867 { "iops_rd_max", "throttling.iops-read-max" },
868 { "iops_wr_max", "throttling.iops-write-max" },
870 { "bps_max", "throttling.bps-total-max" },
871 { "bps_rd_max", "throttling.bps-read-max" },
872 { "bps_wr_max", "throttling.bps-write-max" },
874 { "iops_size", "throttling.iops-size" },
876 { "group", "throttling.group" },
878 { "readonly", "read-only" },
881 for (i = 0; i < ARRAY_SIZE(opt_renames); i++) {
882 qemu_opt_rename(all_opts, opt_renames[i].from, opt_renames[i].to,
885 error_report_err(local_err);
890 value = qemu_opt_get(all_opts, "cache");
895 if (bdrv_parse_cache_mode(value, &flags, &writethrough) != 0) {
896 error_report("invalid cache option");
900 /* Specific options take precedence */
901 if (!qemu_opt_get(all_opts, BDRV_OPT_CACHE_WB)) {
902 qemu_opt_set_bool(all_opts, BDRV_OPT_CACHE_WB,
903 !writethrough, &error_abort);
905 if (!qemu_opt_get(all_opts, BDRV_OPT_CACHE_DIRECT)) {
906 qemu_opt_set_bool(all_opts, BDRV_OPT_CACHE_DIRECT,
907 !!(flags & BDRV_O_NOCACHE), &error_abort);
909 if (!qemu_opt_get(all_opts, BDRV_OPT_CACHE_NO_FLUSH)) {
910 qemu_opt_set_bool(all_opts, BDRV_OPT_CACHE_NO_FLUSH,
911 !!(flags & BDRV_O_NO_FLUSH), &error_abort);
913 qemu_opt_unset(all_opts, "cache");
916 /* Get a QDict for processing the options */
917 bs_opts = qdict_new();
918 qemu_opts_to_qdict(all_opts, bs_opts);
920 legacy_opts = qemu_opts_create(&qemu_legacy_drive_opts, NULL, 0,
922 qemu_opts_absorb_qdict(legacy_opts, bs_opts, &local_err);
924 error_report_err(local_err);
928 /* Deprecated option boot=[on|off] */
929 if (qemu_opt_get(legacy_opts, "boot") != NULL) {
930 fprintf(stderr, "qemu-kvm: boot=on|off is deprecated and will be "
931 "ignored. Future versions will reject this parameter. Please "
932 "update your scripts.\n");
936 value = qemu_opt_get(legacy_opts, "media");
938 if (!strcmp(value, "disk")) {
940 } else if (!strcmp(value, "cdrom")) {
944 error_report("'%s' invalid media", value);
949 /* copy-on-read is disabled with a warning for read-only devices */
950 read_only |= qemu_opt_get_bool(legacy_opts, "read-only", false);
951 copy_on_read = qemu_opt_get_bool(legacy_opts, "copy-on-read", false);
953 if (read_only && copy_on_read) {
954 error_report("warning: disabling copy-on-read on read-only drive");
955 copy_on_read = false;
958 qdict_put(bs_opts, "read-only",
959 qstring_from_str(read_only ? "on" : "off"));
960 qdict_put(bs_opts, "copy-on-read",
961 qstring_from_str(copy_on_read ? "on" :"off"));
963 /* Controller type */
964 value = qemu_opt_get(legacy_opts, "if");
967 type < IF_COUNT && strcmp(value, if_name[type]);
970 if (type == IF_COUNT) {
971 error_report("unsupported bus type '%s'", value);
975 type = block_default_type;
979 cyls = qemu_opt_get_number(legacy_opts, "cyls", 0);
980 heads = qemu_opt_get_number(legacy_opts, "heads", 0);
981 secs = qemu_opt_get_number(legacy_opts, "secs", 0);
983 if (cyls || heads || secs) {
985 error_report("invalid physical cyls number");
989 error_report("invalid physical heads number");
993 error_report("invalid physical secs number");
998 translation = BIOS_ATA_TRANSLATION_AUTO;
999 value = qemu_opt_get(legacy_opts, "trans");
1000 if (value != NULL) {
1002 error_report("'%s' trans must be used with cyls, heads and secs",
1006 if (!strcmp(value, "none")) {
1007 translation = BIOS_ATA_TRANSLATION_NONE;
1008 } else if (!strcmp(value, "lba")) {
1009 translation = BIOS_ATA_TRANSLATION_LBA;
1010 } else if (!strcmp(value, "large")) {
1011 translation = BIOS_ATA_TRANSLATION_LARGE;
1012 } else if (!strcmp(value, "rechs")) {
1013 translation = BIOS_ATA_TRANSLATION_RECHS;
1014 } else if (!strcmp(value, "auto")) {
1015 translation = BIOS_ATA_TRANSLATION_AUTO;
1017 error_report("'%s' invalid translation type", value);
1022 if (media == MEDIA_CDROM) {
1023 if (cyls || secs || heads) {
1024 error_report("CHS can't be set with media=cdrom");
1029 /* Device address specified by bus/unit or index.
1030 * If none was specified, try to find the first free one. */
1031 bus_id = qemu_opt_get_number(legacy_opts, "bus", 0);
1032 unit_id = qemu_opt_get_number(legacy_opts, "unit", -1);
1033 index = qemu_opt_get_number(legacy_opts, "index", -1);
1035 max_devs = if_max_devs[type];
1038 if (bus_id != 0 || unit_id != -1) {
1039 error_report("index cannot be used with bus and unit");
1042 bus_id = drive_index_to_bus_id(type, index);
1043 unit_id = drive_index_to_unit_id(type, index);
1046 if (unit_id == -1) {
1048 while (drive_get(type, bus_id, unit_id) != NULL) {
1050 if (max_devs && unit_id >= max_devs) {
1051 unit_id -= max_devs;
1057 if (max_devs && unit_id >= max_devs) {
1058 error_report("unit %d too big (max is %d)", unit_id, max_devs - 1);
1062 if (drive_get(type, bus_id, unit_id) != NULL) {
1063 error_report("drive with bus=%d, unit=%d (index=%d) exists",
1064 bus_id, unit_id, index);
1069 serial = qemu_opt_get(legacy_opts, "serial");
1071 /* no id supplied -> create one */
1072 if (qemu_opts_id(all_opts) == NULL) {
1074 const char *mediastr = "";
1075 if (type == IF_IDE || type == IF_SCSI) {
1076 mediastr = (media == MEDIA_CDROM) ? "-cd" : "-hd";
1079 new_id = g_strdup_printf("%s%i%s%i", if_name[type], bus_id,
1082 new_id = g_strdup_printf("%s%s%i", if_name[type],
1085 qdict_put(bs_opts, "id", qstring_from_str(new_id));
1089 /* Add virtio block device */
1090 devaddr = qemu_opt_get(legacy_opts, "addr");
1091 if (devaddr && type != IF_VIRTIO) {
1092 error_report("addr is not supported by this bus type");
1096 if (type == IF_VIRTIO) {
1098 devopts = qemu_opts_create(qemu_find_opts("device"), NULL, 0,
1100 if (arch_type == QEMU_ARCH_S390X) {
1101 qemu_opt_set(devopts, "driver", "virtio-blk-ccw", &error_abort);
1103 qemu_opt_set(devopts, "driver", "virtio-blk-pci", &error_abort);
1105 qemu_opt_set(devopts, "drive", qdict_get_str(bs_opts, "id"),
1108 qemu_opt_set(devopts, "addr", devaddr, &error_abort);
1112 filename = qemu_opt_get(legacy_opts, "file");
1114 /* Check werror/rerror compatibility with if=... */
1115 werror = qemu_opt_get(legacy_opts, "werror");
1116 if (werror != NULL) {
1117 if (type != IF_IDE && type != IF_SCSI && type != IF_VIRTIO &&
1119 error_report("werror is not supported by this bus type");
1122 qdict_put(bs_opts, "werror", qstring_from_str(werror));
1125 rerror = qemu_opt_get(legacy_opts, "rerror");
1126 if (rerror != NULL) {
1127 if (type != IF_IDE && type != IF_VIRTIO && type != IF_SCSI &&
1129 error_report("rerror is not supported by this bus type");
1132 qdict_put(bs_opts, "rerror", qstring_from_str(rerror));
1135 /* Actual block device init: Functionality shared with blockdev-add */
1136 blk = blockdev_init(filename, bs_opts, &local_err);
1140 error_report_err(local_err);
1147 /* Create legacy DriveInfo */
1148 dinfo = g_malloc0(sizeof(*dinfo));
1149 dinfo->opts = all_opts;
1152 dinfo->heads = heads;
1154 dinfo->trans = translation;
1157 dinfo->bus = bus_id;
1158 dinfo->unit = unit_id;
1159 dinfo->devaddr = devaddr;
1160 dinfo->serial = g_strdup(serial);
1162 blk_set_legacy_dinfo(blk, dinfo);
1169 dinfo->media_cd = media == MEDIA_CDROM;
1176 qemu_opts_del(legacy_opts);
1181 void hmp_commit(Monitor *mon, const QDict *qdict)
1183 const char *device = qdict_get_str(qdict, "device");
1187 if (!strcmp(device, "all")) {
1188 ret = blk_commit_all();
1190 BlockDriverState *bs;
1191 AioContext *aio_context;
1193 blk = blk_by_name(device);
1195 monitor_printf(mon, "Device '%s' not found\n", device);
1198 if (!blk_is_available(blk)) {
1199 monitor_printf(mon, "Device '%s' has no medium\n", device);
1204 aio_context = bdrv_get_aio_context(bs);
1205 aio_context_acquire(aio_context);
1207 ret = bdrv_commit(bs);
1209 aio_context_release(aio_context);
1212 monitor_printf(mon, "'commit' error for '%s': %s\n", device,
1217 static void blockdev_do_action(TransactionAction *action, Error **errp)
1219 TransactionActionList list;
1221 list.value = action;
1223 qmp_transaction(&list, false, NULL, errp);
1226 void qmp_blockdev_snapshot_sync(bool has_device, const char *device,
1227 bool has_node_name, const char *node_name,
1228 const char *snapshot_file,
1229 bool has_snapshot_node_name,
1230 const char *snapshot_node_name,
1231 bool has_format, const char *format,
1232 bool has_mode, NewImageMode mode, Error **errp)
1234 BlockdevSnapshotSync snapshot = {
1235 .has_device = has_device,
1236 .device = (char *) device,
1237 .has_node_name = has_node_name,
1238 .node_name = (char *) node_name,
1239 .snapshot_file = (char *) snapshot_file,
1240 .has_snapshot_node_name = has_snapshot_node_name,
1241 .snapshot_node_name = (char *) snapshot_node_name,
1242 .has_format = has_format,
1243 .format = (char *) format,
1244 .has_mode = has_mode,
1247 TransactionAction action = {
1248 .type = TRANSACTION_ACTION_KIND_BLOCKDEV_SNAPSHOT_SYNC,
1249 .u.blockdev_snapshot_sync.data = &snapshot,
1251 blockdev_do_action(&action, errp);
1254 void qmp_blockdev_snapshot(const char *node, const char *overlay,
1257 BlockdevSnapshot snapshot_data = {
1258 .node = (char *) node,
1259 .overlay = (char *) overlay
1261 TransactionAction action = {
1262 .type = TRANSACTION_ACTION_KIND_BLOCKDEV_SNAPSHOT,
1263 .u.blockdev_snapshot.data = &snapshot_data,
1265 blockdev_do_action(&action, errp);
1268 void qmp_blockdev_snapshot_internal_sync(const char *device,
1272 BlockdevSnapshotInternal snapshot = {
1273 .device = (char *) device,
1274 .name = (char *) name
1276 TransactionAction action = {
1277 .type = TRANSACTION_ACTION_KIND_BLOCKDEV_SNAPSHOT_INTERNAL_SYNC,
1278 .u.blockdev_snapshot_internal_sync.data = &snapshot,
1280 blockdev_do_action(&action, errp);
1283 SnapshotInfo *qmp_blockdev_snapshot_delete_internal_sync(const char *device,
1290 BlockDriverState *bs;
1292 AioContext *aio_context;
1293 QEMUSnapshotInfo sn;
1294 Error *local_err = NULL;
1295 SnapshotInfo *info = NULL;
1298 blk = blk_by_name(device);
1300 error_set(errp, ERROR_CLASS_DEVICE_NOT_FOUND,
1301 "Device '%s' not found", device);
1305 aio_context = blk_get_aio_context(blk);
1306 aio_context_acquire(aio_context);
1317 error_setg(errp, "Name or id must be provided");
1318 goto out_aio_context;
1321 if (!blk_is_available(blk)) {
1322 error_setg(errp, "Device '%s' has no medium", device);
1323 goto out_aio_context;
1327 if (bdrv_op_is_blocked(bs, BLOCK_OP_TYPE_INTERNAL_SNAPSHOT_DELETE, errp)) {
1328 goto out_aio_context;
1331 ret = bdrv_snapshot_find_by_id_and_name(bs, id, name, &sn, &local_err);
1333 error_propagate(errp, local_err);
1334 goto out_aio_context;
1338 "Snapshot with id '%s' and name '%s' does not exist on "
1340 STR_OR_NULL(id), STR_OR_NULL(name), device);
1341 goto out_aio_context;
1344 bdrv_snapshot_delete(bs, id, name, &local_err);
1346 error_propagate(errp, local_err);
1347 goto out_aio_context;
1350 aio_context_release(aio_context);
1352 info = g_new0(SnapshotInfo, 1);
1353 info->id = g_strdup(sn.id_str);
1354 info->name = g_strdup(sn.name);
1355 info->date_nsec = sn.date_nsec;
1356 info->date_sec = sn.date_sec;
1357 info->vm_state_size = sn.vm_state_size;
1358 info->vm_clock_nsec = sn.vm_clock_nsec % 1000000000;
1359 info->vm_clock_sec = sn.vm_clock_nsec / 1000000000;
1364 aio_context_release(aio_context);
1369 * block_dirty_bitmap_lookup:
1370 * Return a dirty bitmap (if present), after validating
1371 * the node reference and bitmap names.
1373 * @node: The name of the BDS node to search for bitmaps
1374 * @name: The name of the bitmap to search for
1375 * @pbs: Output pointer for BDS lookup, if desired. Can be NULL.
1376 * @paio: Output pointer for aio_context acquisition, if desired. Can be NULL.
1377 * @errp: Output pointer for error information. Can be NULL.
1379 * @return: A bitmap object on success, or NULL on failure.
1381 static BdrvDirtyBitmap *block_dirty_bitmap_lookup(const char *node,
1383 BlockDriverState **pbs,
1387 BlockDriverState *bs;
1388 BdrvDirtyBitmap *bitmap;
1389 AioContext *aio_context;
1392 error_setg(errp, "Node cannot be NULL");
1396 error_setg(errp, "Bitmap name cannot be NULL");
1399 bs = bdrv_lookup_bs(node, node, NULL);
1401 error_setg(errp, "Node '%s' not found", node);
1405 aio_context = bdrv_get_aio_context(bs);
1406 aio_context_acquire(aio_context);
1408 bitmap = bdrv_find_dirty_bitmap(bs, name);
1410 error_setg(errp, "Dirty bitmap '%s' not found", name);
1418 *paio = aio_context;
1420 aio_context_release(aio_context);
1426 aio_context_release(aio_context);
1430 /* New and old BlockDriverState structs for atomic group operations */
1432 typedef struct BlkActionState BlkActionState;
1436 * Table of operations that define an Action.
1438 * @instance_size: Size of state struct, in bytes.
1439 * @prepare: Prepare the work, must NOT be NULL.
1440 * @commit: Commit the changes, can be NULL.
1441 * @abort: Abort the changes on fail, can be NULL.
1442 * @clean: Clean up resources after all transaction actions have called
1443 * commit() or abort(). Can be NULL.
1445 * Only prepare() may fail. In a single transaction, only one of commit() or
1446 * abort() will be called. clean() will always be called if it is present.
1448 typedef struct BlkActionOps {
1449 size_t instance_size;
1450 void (*prepare)(BlkActionState *common, Error **errp);
1451 void (*commit)(BlkActionState *common);
1452 void (*abort)(BlkActionState *common);
1453 void (*clean)(BlkActionState *common);
1458 * Describes one Action's state within a Transaction.
1460 * @action: QAPI-defined enum identifying which Action to perform.
1461 * @ops: Table of ActionOps this Action can perform.
1462 * @block_job_txn: Transaction which this action belongs to.
1463 * @entry: List membership for all Actions in this Transaction.
1465 * This structure must be arranged as first member in a subclassed type,
1466 * assuming that the compiler will also arrange it to the same offsets as the
1469 struct BlkActionState {
1470 TransactionAction *action;
1471 const BlkActionOps *ops;
1472 BlockJobTxn *block_job_txn;
1473 TransactionProperties *txn_props;
1474 QSIMPLEQ_ENTRY(BlkActionState) entry;
1477 /* internal snapshot private data */
1478 typedef struct InternalSnapshotState {
1479 BlkActionState common;
1480 BlockDriverState *bs;
1481 AioContext *aio_context;
1482 QEMUSnapshotInfo sn;
1484 } InternalSnapshotState;
1487 static int action_check_completion_mode(BlkActionState *s, Error **errp)
1489 if (s->txn_props->completion_mode != ACTION_COMPLETION_MODE_INDIVIDUAL) {
1491 "Action '%s' does not support Transaction property "
1492 "completion-mode = %s",
1493 TransactionActionKind_lookup[s->action->type],
1494 ActionCompletionMode_lookup[s->txn_props->completion_mode]);
1500 static void internal_snapshot_prepare(BlkActionState *common,
1503 Error *local_err = NULL;
1507 BlockDriverState *bs;
1508 QEMUSnapshotInfo old_sn, *sn;
1511 BlockdevSnapshotInternal *internal;
1512 InternalSnapshotState *state;
1515 g_assert(common->action->type ==
1516 TRANSACTION_ACTION_KIND_BLOCKDEV_SNAPSHOT_INTERNAL_SYNC);
1517 internal = common->action->u.blockdev_snapshot_internal_sync.data;
1518 state = DO_UPCAST(InternalSnapshotState, common, common);
1520 /* 1. parse input */
1521 device = internal->device;
1522 name = internal->name;
1524 /* 2. check for validation */
1525 if (action_check_completion_mode(common, errp) < 0) {
1529 blk = blk_by_name(device);
1531 error_set(errp, ERROR_CLASS_DEVICE_NOT_FOUND,
1532 "Device '%s' not found", device);
1536 /* AioContext is released in .clean() */
1537 state->aio_context = blk_get_aio_context(blk);
1538 aio_context_acquire(state->aio_context);
1540 if (!blk_is_available(blk)) {
1541 error_setg(errp, QERR_DEVICE_HAS_NO_MEDIUM, device);
1547 bdrv_drained_begin(bs);
1549 if (bdrv_op_is_blocked(bs, BLOCK_OP_TYPE_INTERNAL_SNAPSHOT, errp)) {
1553 if (bdrv_is_read_only(bs)) {
1554 error_setg(errp, "Device '%s' is read only", device);
1558 if (!bdrv_can_snapshot(bs)) {
1559 error_setg(errp, "Block format '%s' used by device '%s' "
1560 "does not support internal snapshots",
1561 bs->drv->format_name, device);
1565 if (!strlen(name)) {
1566 error_setg(errp, "Name is empty");
1570 /* check whether a snapshot with name exist */
1571 ret = bdrv_snapshot_find_by_id_and_name(bs, NULL, name, &old_sn,
1574 error_propagate(errp, local_err);
1578 "Snapshot with name '%s' already exists on device '%s'",
1583 /* 3. take the snapshot */
1585 pstrcpy(sn->name, sizeof(sn->name), name);
1586 qemu_gettimeofday(&tv);
1587 sn->date_sec = tv.tv_sec;
1588 sn->date_nsec = tv.tv_usec * 1000;
1589 sn->vm_clock_nsec = qemu_clock_get_ns(QEMU_CLOCK_VIRTUAL);
1591 ret1 = bdrv_snapshot_create(bs, sn);
1593 error_setg_errno(errp, -ret1,
1594 "Failed to create snapshot '%s' on device '%s'",
1599 /* 4. succeed, mark a snapshot is created */
1600 state->created = true;
1603 static void internal_snapshot_abort(BlkActionState *common)
1605 InternalSnapshotState *state =
1606 DO_UPCAST(InternalSnapshotState, common, common);
1607 BlockDriverState *bs = state->bs;
1608 QEMUSnapshotInfo *sn = &state->sn;
1609 Error *local_error = NULL;
1611 if (!state->created) {
1615 if (bdrv_snapshot_delete(bs, sn->id_str, sn->name, &local_error) < 0) {
1616 error_reportf_err(local_error,
1617 "Failed to delete snapshot with id '%s' and "
1618 "name '%s' on device '%s' in abort: ",
1619 sn->id_str, sn->name,
1620 bdrv_get_device_name(bs));
1624 static void internal_snapshot_clean(BlkActionState *common)
1626 InternalSnapshotState *state = DO_UPCAST(InternalSnapshotState,
1629 if (state->aio_context) {
1631 bdrv_drained_end(state->bs);
1633 aio_context_release(state->aio_context);
1637 /* external snapshot private data */
1638 typedef struct ExternalSnapshotState {
1639 BlkActionState common;
1640 BlockDriverState *old_bs;
1641 BlockDriverState *new_bs;
1642 AioContext *aio_context;
1643 } ExternalSnapshotState;
1645 static void external_snapshot_prepare(BlkActionState *common,
1649 QDict *options = NULL;
1650 Error *local_err = NULL;
1651 /* Device and node name of the image to generate the snapshot from */
1653 const char *node_name;
1654 /* Reference to the new image (for 'blockdev-snapshot') */
1655 const char *snapshot_ref;
1656 /* File name of the new image (for 'blockdev-snapshot-sync') */
1657 const char *new_image_file;
1658 ExternalSnapshotState *state =
1659 DO_UPCAST(ExternalSnapshotState, common, common);
1660 TransactionAction *action = common->action;
1662 /* 'blockdev-snapshot' and 'blockdev-snapshot-sync' have similar
1663 * purpose but a different set of parameters */
1664 switch (action->type) {
1665 case TRANSACTION_ACTION_KIND_BLOCKDEV_SNAPSHOT:
1667 BlockdevSnapshot *s = action->u.blockdev_snapshot.data;
1669 node_name = s->node;
1670 new_image_file = NULL;
1671 snapshot_ref = s->overlay;
1674 case TRANSACTION_ACTION_KIND_BLOCKDEV_SNAPSHOT_SYNC:
1676 BlockdevSnapshotSync *s = action->u.blockdev_snapshot_sync.data;
1677 device = s->has_device ? s->device : NULL;
1678 node_name = s->has_node_name ? s->node_name : NULL;
1679 new_image_file = s->snapshot_file;
1680 snapshot_ref = NULL;
1684 g_assert_not_reached();
1687 /* start processing */
1688 if (action_check_completion_mode(common, errp) < 0) {
1692 state->old_bs = bdrv_lookup_bs(device, node_name, errp);
1693 if (!state->old_bs) {
1697 /* Acquire AioContext now so any threads operating on old_bs stop */
1698 state->aio_context = bdrv_get_aio_context(state->old_bs);
1699 aio_context_acquire(state->aio_context);
1700 bdrv_drained_begin(state->old_bs);
1702 if (!bdrv_is_inserted(state->old_bs)) {
1703 error_setg(errp, QERR_DEVICE_HAS_NO_MEDIUM, device);
1707 if (bdrv_op_is_blocked(state->old_bs,
1708 BLOCK_OP_TYPE_EXTERNAL_SNAPSHOT, errp)) {
1712 if (!bdrv_is_read_only(state->old_bs)) {
1713 if (bdrv_flush(state->old_bs)) {
1714 error_setg(errp, QERR_IO_ERROR);
1719 if (!bdrv_is_first_non_filter(state->old_bs)) {
1720 error_setg(errp, QERR_FEATURE_DISABLED, "snapshot");
1724 if (action->type == TRANSACTION_ACTION_KIND_BLOCKDEV_SNAPSHOT_SYNC) {
1725 BlockdevSnapshotSync *s = action->u.blockdev_snapshot_sync.data;
1726 const char *format = s->has_format ? s->format : "qcow2";
1727 enum NewImageMode mode;
1728 const char *snapshot_node_name =
1729 s->has_snapshot_node_name ? s->snapshot_node_name : NULL;
1731 if (node_name && !snapshot_node_name) {
1732 error_setg(errp, "New snapshot node name missing");
1736 if (snapshot_node_name &&
1737 bdrv_lookup_bs(snapshot_node_name, snapshot_node_name, NULL)) {
1738 error_setg(errp, "New snapshot node name already in use");
1742 flags = state->old_bs->open_flags;
1743 flags &= ~(BDRV_O_SNAPSHOT | BDRV_O_NO_BACKING | BDRV_O_COPY_ON_READ);
1745 /* create new image w/backing file */
1746 mode = s->has_mode ? s->mode : NEW_IMAGE_MODE_ABSOLUTE_PATHS;
1747 if (mode != NEW_IMAGE_MODE_EXISTING) {
1748 int64_t size = bdrv_getlength(state->old_bs);
1750 error_setg_errno(errp, -size, "bdrv_getlength failed");
1753 bdrv_img_create(new_image_file, format,
1754 state->old_bs->filename,
1755 state->old_bs->drv->format_name,
1756 NULL, size, flags, &local_err, false);
1758 error_propagate(errp, local_err);
1763 options = qdict_new();
1764 if (s->has_snapshot_node_name) {
1765 qdict_put(options, "node-name",
1766 qstring_from_str(snapshot_node_name));
1768 qdict_put(options, "driver", qstring_from_str(format));
1770 flags |= BDRV_O_NO_BACKING;
1773 state->new_bs = bdrv_open(new_image_file, snapshot_ref, options, flags,
1775 /* We will manually add the backing_hd field to the bs later */
1776 if (!state->new_bs) {
1780 if (bdrv_has_blk(state->new_bs)) {
1781 error_setg(errp, "The snapshot is already in use by %s",
1782 bdrv_get_parent_name(state->new_bs));
1786 if (bdrv_op_is_blocked(state->new_bs, BLOCK_OP_TYPE_EXTERNAL_SNAPSHOT,
1791 if (state->new_bs->backing != NULL) {
1792 error_setg(errp, "The snapshot already has a backing image");
1796 if (!state->new_bs->drv->supports_backing) {
1797 error_setg(errp, "The snapshot does not support backing images");
1801 static void external_snapshot_commit(BlkActionState *common)
1803 ExternalSnapshotState *state =
1804 DO_UPCAST(ExternalSnapshotState, common, common);
1806 bdrv_set_aio_context(state->new_bs, state->aio_context);
1808 /* This removes our old bs and adds the new bs */
1809 bdrv_append(state->new_bs, state->old_bs);
1810 /* We don't need (or want) to use the transactional
1811 * bdrv_reopen_multiple() across all the entries at once, because we
1812 * don't want to abort all of them if one of them fails the reopen */
1813 if (!state->old_bs->copy_on_read) {
1814 bdrv_reopen(state->old_bs, state->old_bs->open_flags & ~BDRV_O_RDWR,
1819 static void external_snapshot_abort(BlkActionState *common)
1821 ExternalSnapshotState *state =
1822 DO_UPCAST(ExternalSnapshotState, common, common);
1823 if (state->new_bs) {
1824 bdrv_unref(state->new_bs);
1828 static void external_snapshot_clean(BlkActionState *common)
1830 ExternalSnapshotState *state =
1831 DO_UPCAST(ExternalSnapshotState, common, common);
1832 if (state->aio_context) {
1833 bdrv_drained_end(state->old_bs);
1834 aio_context_release(state->aio_context);
1838 typedef struct DriveBackupState {
1839 BlkActionState common;
1840 BlockDriverState *bs;
1841 AioContext *aio_context;
1845 static void do_drive_backup(const char *job_id, const char *device,
1846 const char *target, bool has_format,
1847 const char *format, enum MirrorSyncMode sync,
1848 bool has_mode, enum NewImageMode mode,
1849 bool has_speed, int64_t speed,
1850 bool has_bitmap, const char *bitmap,
1851 bool has_on_source_error,
1852 BlockdevOnError on_source_error,
1853 bool has_on_target_error,
1854 BlockdevOnError on_target_error,
1855 BlockJobTxn *txn, Error **errp);
1857 static void drive_backup_prepare(BlkActionState *common, Error **errp)
1859 DriveBackupState *state = DO_UPCAST(DriveBackupState, common, common);
1861 DriveBackup *backup;
1862 Error *local_err = NULL;
1864 assert(common->action->type == TRANSACTION_ACTION_KIND_DRIVE_BACKUP);
1865 backup = common->action->u.drive_backup.data;
1867 blk = blk_by_name(backup->device);
1869 error_set(errp, ERROR_CLASS_DEVICE_NOT_FOUND,
1870 "Device '%s' not found", backup->device);
1874 if (!blk_is_available(blk)) {
1875 error_setg(errp, QERR_DEVICE_HAS_NO_MEDIUM, backup->device);
1879 /* AioContext is released in .clean() */
1880 state->aio_context = blk_get_aio_context(blk);
1881 aio_context_acquire(state->aio_context);
1882 bdrv_drained_begin(blk_bs(blk));
1883 state->bs = blk_bs(blk);
1885 do_drive_backup(backup->has_job_id ? backup->job_id : NULL,
1886 backup->device, backup->target,
1887 backup->has_format, backup->format,
1889 backup->has_mode, backup->mode,
1890 backup->has_speed, backup->speed,
1891 backup->has_bitmap, backup->bitmap,
1892 backup->has_on_source_error, backup->on_source_error,
1893 backup->has_on_target_error, backup->on_target_error,
1894 common->block_job_txn, &local_err);
1896 error_propagate(errp, local_err);
1900 state->job = state->bs->job;
1903 static void drive_backup_abort(BlkActionState *common)
1905 DriveBackupState *state = DO_UPCAST(DriveBackupState, common, common);
1906 BlockDriverState *bs = state->bs;
1908 /* Only cancel if it's the job we started */
1909 if (bs && bs->job && bs->job == state->job) {
1910 block_job_cancel_sync(bs->job);
1914 static void drive_backup_clean(BlkActionState *common)
1916 DriveBackupState *state = DO_UPCAST(DriveBackupState, common, common);
1918 if (state->aio_context) {
1919 bdrv_drained_end(state->bs);
1920 aio_context_release(state->aio_context);
1924 typedef struct BlockdevBackupState {
1925 BlkActionState common;
1926 BlockDriverState *bs;
1928 AioContext *aio_context;
1929 } BlockdevBackupState;
1931 static void do_blockdev_backup(const char *job_id, const char *device,
1932 const char *target, enum MirrorSyncMode sync,
1933 bool has_speed, int64_t speed,
1934 bool has_on_source_error,
1935 BlockdevOnError on_source_error,
1936 bool has_on_target_error,
1937 BlockdevOnError on_target_error,
1938 BlockJobTxn *txn, Error **errp);
1940 static void blockdev_backup_prepare(BlkActionState *common, Error **errp)
1942 BlockdevBackupState *state = DO_UPCAST(BlockdevBackupState, common, common);
1943 BlockdevBackup *backup;
1945 BlockDriverState *target;
1946 Error *local_err = NULL;
1948 assert(common->action->type == TRANSACTION_ACTION_KIND_BLOCKDEV_BACKUP);
1949 backup = common->action->u.blockdev_backup.data;
1951 blk = blk_by_name(backup->device);
1953 error_setg(errp, "Device '%s' not found", backup->device);
1957 if (!blk_is_available(blk)) {
1958 error_setg(errp, QERR_DEVICE_HAS_NO_MEDIUM, backup->device);
1962 target = bdrv_lookup_bs(backup->target, backup->target, errp);
1967 /* AioContext is released in .clean() */
1968 state->aio_context = blk_get_aio_context(blk);
1969 if (state->aio_context != bdrv_get_aio_context(target)) {
1970 state->aio_context = NULL;
1971 error_setg(errp, "Backup between two IO threads is not implemented");
1974 aio_context_acquire(state->aio_context);
1975 state->bs = blk_bs(blk);
1976 bdrv_drained_begin(state->bs);
1978 do_blockdev_backup(backup->has_job_id ? backup->job_id : NULL,
1979 backup->device, backup->target, backup->sync,
1980 backup->has_speed, backup->speed,
1981 backup->has_on_source_error, backup->on_source_error,
1982 backup->has_on_target_error, backup->on_target_error,
1983 common->block_job_txn, &local_err);
1985 error_propagate(errp, local_err);
1989 state->job = state->bs->job;
1992 static void blockdev_backup_abort(BlkActionState *common)
1994 BlockdevBackupState *state = DO_UPCAST(BlockdevBackupState, common, common);
1995 BlockDriverState *bs = state->bs;
1997 /* Only cancel if it's the job we started */
1998 if (bs && bs->job && bs->job == state->job) {
1999 block_job_cancel_sync(bs->job);
2003 static void blockdev_backup_clean(BlkActionState *common)
2005 BlockdevBackupState *state = DO_UPCAST(BlockdevBackupState, common, common);
2007 if (state->aio_context) {
2008 bdrv_drained_end(state->bs);
2009 aio_context_release(state->aio_context);
2013 typedef struct BlockDirtyBitmapState {
2014 BlkActionState common;
2015 BdrvDirtyBitmap *bitmap;
2016 BlockDriverState *bs;
2017 AioContext *aio_context;
2020 } BlockDirtyBitmapState;
2022 static void block_dirty_bitmap_add_prepare(BlkActionState *common,
2025 Error *local_err = NULL;
2026 BlockDirtyBitmapAdd *action;
2027 BlockDirtyBitmapState *state = DO_UPCAST(BlockDirtyBitmapState,
2030 if (action_check_completion_mode(common, errp) < 0) {
2034 action = common->action->u.block_dirty_bitmap_add.data;
2035 /* AIO context taken and released within qmp_block_dirty_bitmap_add */
2036 qmp_block_dirty_bitmap_add(action->node, action->name,
2037 action->has_granularity, action->granularity,
2041 state->prepared = true;
2043 error_propagate(errp, local_err);
2047 static void block_dirty_bitmap_add_abort(BlkActionState *common)
2049 BlockDirtyBitmapAdd *action;
2050 BlockDirtyBitmapState *state = DO_UPCAST(BlockDirtyBitmapState,
2053 action = common->action->u.block_dirty_bitmap_add.data;
2054 /* Should not be able to fail: IF the bitmap was added via .prepare(),
2055 * then the node reference and bitmap name must have been valid.
2057 if (state->prepared) {
2058 qmp_block_dirty_bitmap_remove(action->node, action->name, &error_abort);
2062 static void block_dirty_bitmap_clear_prepare(BlkActionState *common,
2065 BlockDirtyBitmapState *state = DO_UPCAST(BlockDirtyBitmapState,
2067 BlockDirtyBitmap *action;
2069 if (action_check_completion_mode(common, errp) < 0) {
2073 action = common->action->u.block_dirty_bitmap_clear.data;
2074 state->bitmap = block_dirty_bitmap_lookup(action->node,
2077 &state->aio_context,
2079 if (!state->bitmap) {
2083 if (bdrv_dirty_bitmap_frozen(state->bitmap)) {
2084 error_setg(errp, "Cannot modify a frozen bitmap");
2086 } else if (!bdrv_dirty_bitmap_enabled(state->bitmap)) {
2087 error_setg(errp, "Cannot clear a disabled bitmap");
2091 bdrv_clear_dirty_bitmap(state->bitmap, &state->backup);
2092 /* AioContext is released in .clean() */
2095 static void block_dirty_bitmap_clear_abort(BlkActionState *common)
2097 BlockDirtyBitmapState *state = DO_UPCAST(BlockDirtyBitmapState,
2100 bdrv_undo_clear_dirty_bitmap(state->bitmap, state->backup);
2103 static void block_dirty_bitmap_clear_commit(BlkActionState *common)
2105 BlockDirtyBitmapState *state = DO_UPCAST(BlockDirtyBitmapState,
2108 hbitmap_free(state->backup);
2111 static void block_dirty_bitmap_clear_clean(BlkActionState *common)
2113 BlockDirtyBitmapState *state = DO_UPCAST(BlockDirtyBitmapState,
2116 if (state->aio_context) {
2117 aio_context_release(state->aio_context);
2121 static void abort_prepare(BlkActionState *common, Error **errp)
2123 error_setg(errp, "Transaction aborted using Abort action");
2126 static void abort_commit(BlkActionState *common)
2128 g_assert_not_reached(); /* this action never succeeds */
2131 static const BlkActionOps actions[] = {
2132 [TRANSACTION_ACTION_KIND_BLOCKDEV_SNAPSHOT] = {
2133 .instance_size = sizeof(ExternalSnapshotState),
2134 .prepare = external_snapshot_prepare,
2135 .commit = external_snapshot_commit,
2136 .abort = external_snapshot_abort,
2137 .clean = external_snapshot_clean,
2139 [TRANSACTION_ACTION_KIND_BLOCKDEV_SNAPSHOT_SYNC] = {
2140 .instance_size = sizeof(ExternalSnapshotState),
2141 .prepare = external_snapshot_prepare,
2142 .commit = external_snapshot_commit,
2143 .abort = external_snapshot_abort,
2144 .clean = external_snapshot_clean,
2146 [TRANSACTION_ACTION_KIND_DRIVE_BACKUP] = {
2147 .instance_size = sizeof(DriveBackupState),
2148 .prepare = drive_backup_prepare,
2149 .abort = drive_backup_abort,
2150 .clean = drive_backup_clean,
2152 [TRANSACTION_ACTION_KIND_BLOCKDEV_BACKUP] = {
2153 .instance_size = sizeof(BlockdevBackupState),
2154 .prepare = blockdev_backup_prepare,
2155 .abort = blockdev_backup_abort,
2156 .clean = blockdev_backup_clean,
2158 [TRANSACTION_ACTION_KIND_ABORT] = {
2159 .instance_size = sizeof(BlkActionState),
2160 .prepare = abort_prepare,
2161 .commit = abort_commit,
2163 [TRANSACTION_ACTION_KIND_BLOCKDEV_SNAPSHOT_INTERNAL_SYNC] = {
2164 .instance_size = sizeof(InternalSnapshotState),
2165 .prepare = internal_snapshot_prepare,
2166 .abort = internal_snapshot_abort,
2167 .clean = internal_snapshot_clean,
2169 [TRANSACTION_ACTION_KIND_BLOCK_DIRTY_BITMAP_ADD] = {
2170 .instance_size = sizeof(BlockDirtyBitmapState),
2171 .prepare = block_dirty_bitmap_add_prepare,
2172 .abort = block_dirty_bitmap_add_abort,
2174 [TRANSACTION_ACTION_KIND_BLOCK_DIRTY_BITMAP_CLEAR] = {
2175 .instance_size = sizeof(BlockDirtyBitmapState),
2176 .prepare = block_dirty_bitmap_clear_prepare,
2177 .commit = block_dirty_bitmap_clear_commit,
2178 .abort = block_dirty_bitmap_clear_abort,
2179 .clean = block_dirty_bitmap_clear_clean,
2184 * Allocate a TransactionProperties structure if necessary, and fill
2185 * that structure with desired defaults if they are unset.
2187 static TransactionProperties *get_transaction_properties(
2188 TransactionProperties *props)
2191 props = g_new0(TransactionProperties, 1);
2194 if (!props->has_completion_mode) {
2195 props->has_completion_mode = true;
2196 props->completion_mode = ACTION_COMPLETION_MODE_INDIVIDUAL;
2203 * 'Atomic' group operations. The operations are performed as a set, and if
2204 * any fail then we roll back all operations in the group.
2206 void qmp_transaction(TransactionActionList *dev_list,
2208 struct TransactionProperties *props,
2211 TransactionActionList *dev_entry = dev_list;
2212 BlockJobTxn *block_job_txn = NULL;
2213 BlkActionState *state, *next;
2214 Error *local_err = NULL;
2216 QSIMPLEQ_HEAD(snap_bdrv_states, BlkActionState) snap_bdrv_states;
2217 QSIMPLEQ_INIT(&snap_bdrv_states);
2219 /* Does this transaction get canceled as a group on failure?
2220 * If not, we don't really need to make a BlockJobTxn.
2222 props = get_transaction_properties(props);
2223 if (props->completion_mode != ACTION_COMPLETION_MODE_INDIVIDUAL) {
2224 block_job_txn = block_job_txn_new();
2227 /* drain all i/o before any operations */
2230 /* We don't do anything in this loop that commits us to the operations */
2231 while (NULL != dev_entry) {
2232 TransactionAction *dev_info = NULL;
2233 const BlkActionOps *ops;
2235 dev_info = dev_entry->value;
2236 dev_entry = dev_entry->next;
2238 assert(dev_info->type < ARRAY_SIZE(actions));
2240 ops = &actions[dev_info->type];
2241 assert(ops->instance_size > 0);
2243 state = g_malloc0(ops->instance_size);
2245 state->action = dev_info;
2246 state->block_job_txn = block_job_txn;
2247 state->txn_props = props;
2248 QSIMPLEQ_INSERT_TAIL(&snap_bdrv_states, state, entry);
2250 state->ops->prepare(state, &local_err);
2252 error_propagate(errp, local_err);
2253 goto delete_and_fail;
2257 QSIMPLEQ_FOREACH(state, &snap_bdrv_states, entry) {
2258 if (state->ops->commit) {
2259 state->ops->commit(state);
2267 /* failure, and it is all-or-none; roll back all operations */
2268 QSIMPLEQ_FOREACH(state, &snap_bdrv_states, entry) {
2269 if (state->ops->abort) {
2270 state->ops->abort(state);
2274 QSIMPLEQ_FOREACH_SAFE(state, &snap_bdrv_states, entry, next) {
2275 if (state->ops->clean) {
2276 state->ops->clean(state);
2281 qapi_free_TransactionProperties(props);
2283 block_job_txn_unref(block_job_txn);
2286 void qmp_eject(const char *device, bool has_force, bool force, Error **errp)
2288 Error *local_err = NULL;
2295 rc = do_open_tray(device, force, &local_err);
2296 if (rc && rc != -ENOSYS) {
2297 error_propagate(errp, local_err);
2300 error_free(local_err);
2302 qmp_x_blockdev_remove_medium(device, errp);
2305 void qmp_block_passwd(bool has_device, const char *device,
2306 bool has_node_name, const char *node_name,
2307 const char *password, Error **errp)
2309 Error *local_err = NULL;
2310 BlockDriverState *bs;
2311 AioContext *aio_context;
2313 bs = bdrv_lookup_bs(has_device ? device : NULL,
2314 has_node_name ? node_name : NULL,
2317 error_propagate(errp, local_err);
2321 aio_context = bdrv_get_aio_context(bs);
2322 aio_context_acquire(aio_context);
2324 bdrv_add_key(bs, password, errp);
2326 aio_context_release(aio_context);
2330 * Attempt to open the tray of @device.
2331 * If @force, ignore its tray lock.
2332 * Else, if the tray is locked, don't open it, but ask the guest to open it.
2333 * On error, store an error through @errp and return -errno.
2334 * If @device does not exist, return -ENODEV.
2335 * If it has no removable media, return -ENOTSUP.
2336 * If it has no tray, return -ENOSYS.
2337 * If the guest was asked to open the tray, return -EINPROGRESS.
2340 static int do_open_tray(const char *device, bool force, Error **errp)
2345 blk = blk_by_name(device);
2347 error_set(errp, ERROR_CLASS_DEVICE_NOT_FOUND,
2348 "Device '%s' not found", device);
2352 if (!blk_dev_has_removable_media(blk)) {
2353 error_setg(errp, "Device '%s' is not removable", device);
2357 if (!blk_dev_has_tray(blk)) {
2358 error_setg(errp, "Device '%s' does not have a tray", device);
2362 if (blk_dev_is_tray_open(blk)) {
2366 locked = blk_dev_is_medium_locked(blk);
2368 blk_dev_eject_request(blk, force);
2371 if (!locked || force) {
2372 blk_dev_change_media_cb(blk, false);
2375 if (locked && !force) {
2376 error_setg(errp, "Device '%s' is locked and force was not specified, "
2377 "wait for tray to open and try again", device);
2378 return -EINPROGRESS;
2384 void qmp_blockdev_open_tray(const char *device, bool has_force, bool force,
2387 Error *local_err = NULL;
2393 rc = do_open_tray(device, force, &local_err);
2394 if (rc && rc != -ENOSYS && rc != -EINPROGRESS) {
2395 error_propagate(errp, local_err);
2398 error_free(local_err);
2401 void qmp_blockdev_close_tray(const char *device, Error **errp)
2405 blk = blk_by_name(device);
2407 error_set(errp, ERROR_CLASS_DEVICE_NOT_FOUND,
2408 "Device '%s' not found", device);
2412 if (!blk_dev_has_removable_media(blk)) {
2413 error_setg(errp, "Device '%s' is not removable", device);
2417 if (!blk_dev_has_tray(blk)) {
2418 /* Ignore this command on tray-less devices */
2422 if (!blk_dev_is_tray_open(blk)) {
2426 blk_dev_change_media_cb(blk, true);
2429 void qmp_x_blockdev_remove_medium(const char *device, Error **errp)
2432 BlockDriverState *bs;
2433 AioContext *aio_context;
2436 blk = blk_by_name(device);
2438 error_set(errp, ERROR_CLASS_DEVICE_NOT_FOUND,
2439 "Device '%s' not found", device);
2443 /* For BBs without a device, we can exchange the BDS tree at will */
2444 has_device = blk_get_attached_dev(blk);
2446 if (has_device && !blk_dev_has_removable_media(blk)) {
2447 error_setg(errp, "Device '%s' is not removable", device);
2451 if (has_device && blk_dev_has_tray(blk) && !blk_dev_is_tray_open(blk)) {
2452 error_setg(errp, "Tray of device '%s' is not open", device);
2461 aio_context = bdrv_get_aio_context(bs);
2462 aio_context_acquire(aio_context);
2464 if (bdrv_op_is_blocked(bs, BLOCK_OP_TYPE_EJECT, errp)) {
2470 if (!blk_dev_has_tray(blk)) {
2471 /* For tray-less devices, blockdev-open-tray is a no-op (or may not be
2472 * called at all); therefore, the medium needs to be ejected here.
2473 * Do it after blk_remove_bs() so blk_is_inserted(blk) returns the @load
2474 * value passed here (i.e. false). */
2475 blk_dev_change_media_cb(blk, false);
2479 aio_context_release(aio_context);
2482 static void qmp_blockdev_insert_anon_medium(const char *device,
2483 BlockDriverState *bs, Error **errp)
2488 blk = blk_by_name(device);
2490 error_set(errp, ERROR_CLASS_DEVICE_NOT_FOUND,
2491 "Device '%s' not found", device);
2495 /* For BBs without a device, we can exchange the BDS tree at will */
2496 has_device = blk_get_attached_dev(blk);
2498 if (has_device && !blk_dev_has_removable_media(blk)) {
2499 error_setg(errp, "Device '%s' is not removable", device);
2503 if (has_device && blk_dev_has_tray(blk) && !blk_dev_is_tray_open(blk)) {
2504 error_setg(errp, "Tray of device '%s' is not open", device);
2509 error_setg(errp, "There already is a medium in device '%s'", device);
2513 blk_insert_bs(blk, bs);
2515 if (!blk_dev_has_tray(blk)) {
2516 /* For tray-less devices, blockdev-close-tray is a no-op (or may not be
2517 * called at all); therefore, the medium needs to be pushed into the
2519 * Do it after blk_insert_bs() so blk_is_inserted(blk) returns the @load
2520 * value passed here (i.e. true). */
2521 blk_dev_change_media_cb(blk, true);
2525 void qmp_x_blockdev_insert_medium(const char *device, const char *node_name,
2528 BlockDriverState *bs;
2530 bs = bdrv_find_node(node_name);
2532 error_setg(errp, "Node '%s' not found", node_name);
2536 if (bdrv_has_blk(bs)) {
2537 error_setg(errp, "Node '%s' is already in use by '%s'", node_name,
2538 bdrv_get_parent_name(bs));
2542 qmp_blockdev_insert_anon_medium(device, bs, errp);
2545 void qmp_blockdev_change_medium(const char *device, const char *filename,
2546 bool has_format, const char *format,
2548 BlockdevChangeReadOnlyMode read_only,
2552 BlockDriverState *medium_bs = NULL;
2555 QDict *options = NULL;
2558 blk = blk_by_name(device);
2560 error_set(errp, ERROR_CLASS_DEVICE_NOT_FOUND,
2561 "Device '%s' not found", device);
2566 blk_update_root_state(blk);
2569 bdrv_flags = blk_get_open_flags_from_root_state(blk);
2570 bdrv_flags &= ~(BDRV_O_TEMPORARY | BDRV_O_SNAPSHOT | BDRV_O_NO_BACKING |
2573 if (!has_read_only) {
2574 read_only = BLOCKDEV_CHANGE_READ_ONLY_MODE_RETAIN;
2577 switch (read_only) {
2578 case BLOCKDEV_CHANGE_READ_ONLY_MODE_RETAIN:
2581 case BLOCKDEV_CHANGE_READ_ONLY_MODE_READ_ONLY:
2582 bdrv_flags &= ~BDRV_O_RDWR;
2585 case BLOCKDEV_CHANGE_READ_ONLY_MODE_READ_WRITE:
2586 bdrv_flags |= BDRV_O_RDWR;
2594 options = qdict_new();
2595 qdict_put(options, "driver", qstring_from_str(format));
2598 medium_bs = bdrv_open(filename, NULL, options, bdrv_flags, errp);
2603 bdrv_add_key(medium_bs, NULL, &err);
2605 error_propagate(errp, err);
2609 rc = do_open_tray(device, false, &err);
2610 if (rc && rc != -ENOSYS) {
2611 error_propagate(errp, err);
2617 qmp_x_blockdev_remove_medium(device, &err);
2619 error_propagate(errp, err);
2623 qmp_blockdev_insert_anon_medium(device, medium_bs, &err);
2625 error_propagate(errp, err);
2629 blk_apply_root_state(blk, medium_bs);
2631 qmp_blockdev_close_tray(device, errp);
2634 /* If the medium has been inserted, the device has its own reference, so
2635 * ours must be relinquished; and if it has not been inserted successfully,
2636 * the reference must be relinquished anyway */
2637 bdrv_unref(medium_bs);
2640 /* throttling disk I/O limits */
2641 void qmp_block_set_io_throttle(BlockIOThrottle *arg, Error **errp)
2644 BlockDriverState *bs;
2646 AioContext *aio_context;
2648 blk = blk_by_name(arg->device);
2650 error_set(errp, ERROR_CLASS_DEVICE_NOT_FOUND,
2651 "Device '%s' not found", arg->device);
2655 aio_context = blk_get_aio_context(blk);
2656 aio_context_acquire(aio_context);
2660 error_setg(errp, "Device '%s' has no medium", arg->device);
2664 throttle_config_init(&cfg);
2665 cfg.buckets[THROTTLE_BPS_TOTAL].avg = arg->bps;
2666 cfg.buckets[THROTTLE_BPS_READ].avg = arg->bps_rd;
2667 cfg.buckets[THROTTLE_BPS_WRITE].avg = arg->bps_wr;
2669 cfg.buckets[THROTTLE_OPS_TOTAL].avg = arg->iops;
2670 cfg.buckets[THROTTLE_OPS_READ].avg = arg->iops_rd;
2671 cfg.buckets[THROTTLE_OPS_WRITE].avg = arg->iops_wr;
2673 if (arg->has_bps_max) {
2674 cfg.buckets[THROTTLE_BPS_TOTAL].max = arg->bps_max;
2676 if (arg->has_bps_rd_max) {
2677 cfg.buckets[THROTTLE_BPS_READ].max = arg->bps_rd_max;
2679 if (arg->has_bps_wr_max) {
2680 cfg.buckets[THROTTLE_BPS_WRITE].max = arg->bps_wr_max;
2682 if (arg->has_iops_max) {
2683 cfg.buckets[THROTTLE_OPS_TOTAL].max = arg->iops_max;
2685 if (arg->has_iops_rd_max) {
2686 cfg.buckets[THROTTLE_OPS_READ].max = arg->iops_rd_max;
2688 if (arg->has_iops_wr_max) {
2689 cfg.buckets[THROTTLE_OPS_WRITE].max = arg->iops_wr_max;
2692 if (arg->has_bps_max_length) {
2693 cfg.buckets[THROTTLE_BPS_TOTAL].burst_length = arg->bps_max_length;
2695 if (arg->has_bps_rd_max_length) {
2696 cfg.buckets[THROTTLE_BPS_READ].burst_length = arg->bps_rd_max_length;
2698 if (arg->has_bps_wr_max_length) {
2699 cfg.buckets[THROTTLE_BPS_WRITE].burst_length = arg->bps_wr_max_length;
2701 if (arg->has_iops_max_length) {
2702 cfg.buckets[THROTTLE_OPS_TOTAL].burst_length = arg->iops_max_length;
2704 if (arg->has_iops_rd_max_length) {
2705 cfg.buckets[THROTTLE_OPS_READ].burst_length = arg->iops_rd_max_length;
2707 if (arg->has_iops_wr_max_length) {
2708 cfg.buckets[THROTTLE_OPS_WRITE].burst_length = arg->iops_wr_max_length;
2711 if (arg->has_iops_size) {
2712 cfg.op_size = arg->iops_size;
2715 if (!throttle_is_valid(&cfg, errp)) {
2719 if (throttle_enabled(&cfg)) {
2720 /* Enable I/O limits if they're not enabled yet, otherwise
2721 * just update the throttling group. */
2722 if (!blk_get_public(blk)->throttle_state) {
2723 blk_io_limits_enable(blk,
2724 arg->has_group ? arg->group : arg->device);
2725 } else if (arg->has_group) {
2726 blk_io_limits_update_group(blk, arg->group);
2728 /* Set the new throttling configuration */
2729 blk_set_io_limits(blk, &cfg);
2730 } else if (blk_get_public(blk)->throttle_state) {
2731 /* If all throttling settings are set to 0, disable I/O limits */
2732 blk_io_limits_disable(blk);
2736 aio_context_release(aio_context);
2739 void qmp_block_dirty_bitmap_add(const char *node, const char *name,
2740 bool has_granularity, uint32_t granularity,
2743 AioContext *aio_context;
2744 BlockDriverState *bs;
2746 if (!name || name[0] == '\0') {
2747 error_setg(errp, "Bitmap name cannot be empty");
2751 bs = bdrv_lookup_bs(node, node, errp);
2756 aio_context = bdrv_get_aio_context(bs);
2757 aio_context_acquire(aio_context);
2759 if (has_granularity) {
2760 if (granularity < 512 || !is_power_of_2(granularity)) {
2761 error_setg(errp, "Granularity must be power of 2 "
2762 "and at least 512");
2766 /* Default to cluster size, if available: */
2767 granularity = bdrv_get_default_bitmap_granularity(bs);
2770 bdrv_create_dirty_bitmap(bs, granularity, name, errp);
2773 aio_context_release(aio_context);
2776 void qmp_block_dirty_bitmap_remove(const char *node, const char *name,
2779 AioContext *aio_context;
2780 BlockDriverState *bs;
2781 BdrvDirtyBitmap *bitmap;
2783 bitmap = block_dirty_bitmap_lookup(node, name, &bs, &aio_context, errp);
2784 if (!bitmap || !bs) {
2788 if (bdrv_dirty_bitmap_frozen(bitmap)) {
2790 "Bitmap '%s' is currently frozen and cannot be removed",
2794 bdrv_dirty_bitmap_make_anon(bitmap);
2795 bdrv_release_dirty_bitmap(bs, bitmap);
2798 aio_context_release(aio_context);
2802 * Completely clear a bitmap, for the purposes of synchronizing a bitmap
2803 * immediately after a full backup operation.
2805 void qmp_block_dirty_bitmap_clear(const char *node, const char *name,
2808 AioContext *aio_context;
2809 BdrvDirtyBitmap *bitmap;
2810 BlockDriverState *bs;
2812 bitmap = block_dirty_bitmap_lookup(node, name, &bs, &aio_context, errp);
2813 if (!bitmap || !bs) {
2817 if (bdrv_dirty_bitmap_frozen(bitmap)) {
2819 "Bitmap '%s' is currently frozen and cannot be modified",
2822 } else if (!bdrv_dirty_bitmap_enabled(bitmap)) {
2824 "Bitmap '%s' is currently disabled and cannot be cleared",
2829 bdrv_clear_dirty_bitmap(bitmap, NULL);
2832 aio_context_release(aio_context);
2835 void hmp_drive_del(Monitor *mon, const QDict *qdict)
2837 const char *id = qdict_get_str(qdict, "id");
2839 BlockDriverState *bs;
2840 AioContext *aio_context;
2841 Error *local_err = NULL;
2843 bs = bdrv_find_node(id);
2845 qmp_x_blockdev_del(false, NULL, true, id, &local_err);
2847 error_report_err(local_err);
2852 blk = blk_by_name(id);
2854 error_report("Device '%s' not found", id);
2858 if (!blk_legacy_dinfo(blk)) {
2859 error_report("Deleting device added with blockdev-add"
2860 " is not supported");
2864 aio_context = blk_get_aio_context(blk);
2865 aio_context_acquire(aio_context);
2869 if (bdrv_op_is_blocked(bs, BLOCK_OP_TYPE_DRIVE_DEL, &local_err)) {
2870 error_report_err(local_err);
2871 aio_context_release(aio_context);
2878 /* Make the BlockBackend and the attached BlockDriverState anonymous */
2879 monitor_remove_blk(blk);
2881 /* If this BlockBackend has a device attached to it, its refcount will be
2882 * decremented when the device is removed; otherwise we have to do so here.
2884 if (blk_get_attached_dev(blk)) {
2885 /* Further I/O must not pause the guest */
2886 blk_set_on_error(blk, BLOCKDEV_ON_ERROR_REPORT,
2887 BLOCKDEV_ON_ERROR_REPORT);
2892 aio_context_release(aio_context);
2895 void qmp_block_resize(bool has_device, const char *device,
2896 bool has_node_name, const char *node_name,
2897 int64_t size, Error **errp)
2899 Error *local_err = NULL;
2900 BlockDriverState *bs;
2901 AioContext *aio_context;
2904 bs = bdrv_lookup_bs(has_device ? device : NULL,
2905 has_node_name ? node_name : NULL,
2908 error_propagate(errp, local_err);
2912 aio_context = bdrv_get_aio_context(bs);
2913 aio_context_acquire(aio_context);
2915 if (!bdrv_is_first_non_filter(bs)) {
2916 error_setg(errp, QERR_FEATURE_DISABLED, "resize");
2921 error_setg(errp, QERR_INVALID_PARAMETER_VALUE, "size", "a >0 size");
2925 if (bdrv_op_is_blocked(bs, BLOCK_OP_TYPE_RESIZE, NULL)) {
2926 error_setg(errp, QERR_DEVICE_IN_USE, device);
2930 /* complete all in-flight operations before resizing the device */
2933 ret = bdrv_truncate(bs, size);
2938 error_setg(errp, QERR_DEVICE_HAS_NO_MEDIUM, device);
2941 error_setg(errp, QERR_UNSUPPORTED);
2944 error_setg(errp, "Device '%s' is read only", device);
2947 error_setg(errp, QERR_DEVICE_IN_USE, device);
2950 error_setg_errno(errp, -ret, "Could not resize");
2955 aio_context_release(aio_context);
2958 static void block_job_cb(void *opaque, int ret)
2960 /* Note that this function may be executed from another AioContext besides
2961 * the QEMU main loop. If you need to access anything that assumes the
2962 * QEMU global mutex, use a BH or introduce a mutex.
2965 BlockDriverState *bs = opaque;
2966 const char *msg = NULL;
2968 trace_block_job_cb(bs, bs->job, ret);
2973 msg = strerror(-ret);
2976 if (block_job_is_cancelled(bs->job)) {
2977 block_job_event_cancelled(bs->job);
2979 block_job_event_completed(bs->job, msg);
2983 void qmp_block_stream(bool has_job_id, const char *job_id, const char *device,
2984 bool has_base, const char *base,
2985 bool has_backing_file, const char *backing_file,
2986 bool has_speed, int64_t speed,
2987 bool has_on_error, BlockdevOnError on_error,
2991 BlockDriverState *bs;
2992 BlockDriverState *base_bs = NULL;
2993 AioContext *aio_context;
2994 Error *local_err = NULL;
2995 const char *base_name = NULL;
2997 if (!has_on_error) {
2998 on_error = BLOCKDEV_ON_ERROR_REPORT;
3001 blk = blk_by_name(device);
3003 error_set(errp, ERROR_CLASS_DEVICE_NOT_FOUND,
3004 "Device '%s' not found", device);
3008 aio_context = blk_get_aio_context(blk);
3009 aio_context_acquire(aio_context);
3011 if (!blk_is_available(blk)) {
3012 error_setg(errp, "Device '%s' has no medium", device);
3017 if (bdrv_op_is_blocked(bs, BLOCK_OP_TYPE_STREAM, errp)) {
3022 base_bs = bdrv_find_backing_image(bs, base);
3023 if (base_bs == NULL) {
3024 error_setg(errp, QERR_BASE_NOT_FOUND, base);
3027 assert(bdrv_get_aio_context(base_bs) == aio_context);
3031 /* if we are streaming the entire chain, the result will have no backing
3032 * file, and specifying one is therefore an error */
3033 if (base_bs == NULL && has_backing_file) {
3034 error_setg(errp, "backing file specified, but streaming the "
3039 /* backing_file string overrides base bs filename */
3040 base_name = has_backing_file ? backing_file : base_name;
3042 stream_start(has_job_id ? job_id : NULL, bs, base_bs, base_name,
3043 has_speed ? speed : 0, on_error, block_job_cb, bs, &local_err);
3045 error_propagate(errp, local_err);
3049 trace_qmp_block_stream(bs, bs->job);
3052 aio_context_release(aio_context);
3055 void qmp_block_commit(bool has_job_id, const char *job_id, const char *device,
3056 bool has_base, const char *base,
3057 bool has_top, const char *top,
3058 bool has_backing_file, const char *backing_file,
3059 bool has_speed, int64_t speed,
3063 BlockDriverState *bs;
3064 BlockDriverState *base_bs, *top_bs;
3065 AioContext *aio_context;
3066 Error *local_err = NULL;
3067 /* This will be part of the QMP command, if/when the
3068 * BlockdevOnError change for blkmirror makes it in
3070 BlockdevOnError on_error = BLOCKDEV_ON_ERROR_REPORT;
3077 * libvirt relies on the DeviceNotFound error class in order to probe for
3078 * live commit feature versions; for this to work, we must make sure to
3079 * perform the device lookup before any generic errors that may occur in a
3080 * scenario in which all optional arguments are omitted. */
3081 blk = blk_by_name(device);
3083 error_set(errp, ERROR_CLASS_DEVICE_NOT_FOUND,
3084 "Device '%s' not found", device);
3088 aio_context = blk_get_aio_context(blk);
3089 aio_context_acquire(aio_context);
3091 if (!blk_is_available(blk)) {
3092 error_setg(errp, "Device '%s' has no medium", device);
3097 if (bdrv_op_is_blocked(bs, BLOCK_OP_TYPE_COMMIT_SOURCE, errp)) {
3101 /* default top_bs is the active layer */
3104 if (has_top && top) {
3105 if (strcmp(bs->filename, top) != 0) {
3106 top_bs = bdrv_find_backing_image(bs, top);
3110 if (top_bs == NULL) {
3111 error_setg(errp, "Top image file %s not found", top ? top : "NULL");
3115 assert(bdrv_get_aio_context(top_bs) == aio_context);
3117 if (has_base && base) {
3118 base_bs = bdrv_find_backing_image(top_bs, base);
3120 base_bs = bdrv_find_base(top_bs);
3123 if (base_bs == NULL) {
3124 error_setg(errp, QERR_BASE_NOT_FOUND, base ? base : "NULL");
3128 assert(bdrv_get_aio_context(base_bs) == aio_context);
3130 if (bdrv_op_is_blocked(base_bs, BLOCK_OP_TYPE_COMMIT_TARGET, errp)) {
3134 /* Do not allow attempts to commit an image into itself */
3135 if (top_bs == base_bs) {
3136 error_setg(errp, "cannot commit an image into itself");
3141 if (has_backing_file) {
3142 error_setg(errp, "'backing-file' specified,"
3143 " but 'top' is the active layer");
3146 commit_active_start(has_job_id ? job_id : NULL, bs, base_bs, speed,
3147 on_error, block_job_cb, bs, &local_err);
3149 commit_start(has_job_id ? job_id : NULL, bs, base_bs, top_bs, speed,
3150 on_error, block_job_cb, bs,
3151 has_backing_file ? backing_file : NULL, &local_err);
3153 if (local_err != NULL) {
3154 error_propagate(errp, local_err);
3159 aio_context_release(aio_context);
3162 static void do_drive_backup(const char *job_id, const char *device,
3163 const char *target, bool has_format,
3164 const char *format, enum MirrorSyncMode sync,
3165 bool has_mode, enum NewImageMode mode,
3166 bool has_speed, int64_t speed,
3167 bool has_bitmap, const char *bitmap,
3168 bool has_on_source_error,
3169 BlockdevOnError on_source_error,
3170 bool has_on_target_error,
3171 BlockdevOnError on_target_error,
3172 BlockJobTxn *txn, Error **errp)
3175 BlockDriverState *bs;
3176 BlockDriverState *target_bs;
3177 BlockDriverState *source = NULL;
3178 BdrvDirtyBitmap *bmap = NULL;
3179 AioContext *aio_context;
3180 QDict *options = NULL;
3181 Error *local_err = NULL;
3188 if (!has_on_source_error) {
3189 on_source_error = BLOCKDEV_ON_ERROR_REPORT;
3191 if (!has_on_target_error) {
3192 on_target_error = BLOCKDEV_ON_ERROR_REPORT;
3195 mode = NEW_IMAGE_MODE_ABSOLUTE_PATHS;
3198 blk = blk_by_name(device);
3200 error_set(errp, ERROR_CLASS_DEVICE_NOT_FOUND,
3201 "Device '%s' not found", device);
3205 aio_context = blk_get_aio_context(blk);
3206 aio_context_acquire(aio_context);
3208 /* Although backup_run has this check too, we need to use bs->drv below, so
3209 * do an early check redundantly. */
3210 if (!blk_is_available(blk)) {
3211 error_setg(errp, QERR_DEVICE_HAS_NO_MEDIUM, device);
3217 format = mode == NEW_IMAGE_MODE_EXISTING ? NULL : bs->drv->format_name;
3220 /* Early check to avoid creating target */
3221 if (bdrv_op_is_blocked(bs, BLOCK_OP_TYPE_BACKUP_SOURCE, errp)) {
3225 flags = bs->open_flags | BDRV_O_RDWR;
3227 /* See if we have a backing HD we can use to create our new image
3229 if (sync == MIRROR_SYNC_MODE_TOP) {
3230 source = backing_bs(bs);
3232 sync = MIRROR_SYNC_MODE_FULL;
3235 if (sync == MIRROR_SYNC_MODE_NONE) {
3239 size = bdrv_getlength(bs);
3241 error_setg_errno(errp, -size, "bdrv_getlength failed");
3245 if (mode != NEW_IMAGE_MODE_EXISTING) {
3248 bdrv_img_create(target, format, source->filename,
3249 source->drv->format_name, NULL,
3250 size, flags, &local_err, false);
3252 bdrv_img_create(target, format, NULL, NULL, NULL,
3253 size, flags, &local_err, false);
3258 error_propagate(errp, local_err);
3263 options = qdict_new();
3264 qdict_put(options, "driver", qstring_from_str(format));
3267 target_bs = bdrv_open(target, NULL, options, flags, errp);
3272 bdrv_set_aio_context(target_bs, aio_context);
3275 bmap = bdrv_find_dirty_bitmap(bs, bitmap);
3277 error_setg(errp, "Bitmap '%s' could not be found", bitmap);
3278 bdrv_unref(target_bs);
3283 backup_start(job_id, bs, target_bs, speed, sync, bmap,
3284 on_source_error, on_target_error,
3285 block_job_cb, bs, txn, &local_err);
3286 bdrv_unref(target_bs);
3287 if (local_err != NULL) {
3288 error_propagate(errp, local_err);
3293 aio_context_release(aio_context);
3296 void qmp_drive_backup(bool has_job_id, const char *job_id,
3297 const char *device, const char *target,
3298 bool has_format, const char *format,
3299 enum MirrorSyncMode sync,
3300 bool has_mode, enum NewImageMode mode,
3301 bool has_speed, int64_t speed,
3302 bool has_bitmap, const char *bitmap,
3303 bool has_on_source_error, BlockdevOnError on_source_error,
3304 bool has_on_target_error, BlockdevOnError on_target_error,
3307 return do_drive_backup(has_job_id ? job_id : NULL, device, target,
3308 has_format, format, sync,
3309 has_mode, mode, has_speed, speed,
3311 has_on_source_error, on_source_error,
3312 has_on_target_error, on_target_error,
3316 BlockDeviceInfoList *qmp_query_named_block_nodes(Error **errp)
3318 return bdrv_named_nodes_list(errp);
3321 void do_blockdev_backup(const char *job_id, const char *device,
3322 const char *target, enum MirrorSyncMode sync,
3323 bool has_speed, int64_t speed,
3324 bool has_on_source_error,
3325 BlockdevOnError on_source_error,
3326 bool has_on_target_error,
3327 BlockdevOnError on_target_error,
3328 BlockJobTxn *txn, Error **errp)
3331 BlockDriverState *bs;
3332 BlockDriverState *target_bs;
3333 Error *local_err = NULL;
3334 AioContext *aio_context;
3339 if (!has_on_source_error) {
3340 on_source_error = BLOCKDEV_ON_ERROR_REPORT;
3342 if (!has_on_target_error) {
3343 on_target_error = BLOCKDEV_ON_ERROR_REPORT;
3346 blk = blk_by_name(device);
3348 error_setg(errp, "Device '%s' not found", device);
3352 aio_context = blk_get_aio_context(blk);
3353 aio_context_acquire(aio_context);
3355 if (!blk_is_available(blk)) {
3356 error_setg(errp, "Device '%s' has no medium", device);
3361 target_bs = bdrv_lookup_bs(target, target, errp);
3366 if (bdrv_get_aio_context(target_bs) != aio_context) {
3367 if (!bdrv_has_blk(target_bs)) {
3368 /* The target BDS is not attached, we can safely move it to another
3370 bdrv_set_aio_context(target_bs, aio_context);
3372 error_setg(errp, "Target is attached to a different thread from "
3377 backup_start(job_id, bs, target_bs, speed, sync, NULL, on_source_error,
3378 on_target_error, block_job_cb, bs, txn, &local_err);
3379 if (local_err != NULL) {
3380 error_propagate(errp, local_err);
3383 aio_context_release(aio_context);
3386 void qmp_blockdev_backup(bool has_job_id, const char *job_id,
3387 const char *device, const char *target,
3388 enum MirrorSyncMode sync,
3389 bool has_speed, int64_t speed,
3390 bool has_on_source_error,
3391 BlockdevOnError on_source_error,
3392 bool has_on_target_error,
3393 BlockdevOnError on_target_error,
3396 do_blockdev_backup(has_job_id ? job_id : NULL, device, target,
3397 sync, has_speed, speed,
3398 has_on_source_error, on_source_error,
3399 has_on_target_error, on_target_error,
3403 /* Parameter check and block job starting for drive mirroring.
3404 * Caller should hold @device and @target's aio context (must be the same).
3406 static void blockdev_mirror_common(const char *job_id, BlockDriverState *bs,
3407 BlockDriverState *target,
3408 bool has_replaces, const char *replaces,
3409 enum MirrorSyncMode sync,
3410 BlockMirrorBackingMode backing_mode,
3411 bool has_speed, int64_t speed,
3412 bool has_granularity, uint32_t granularity,
3413 bool has_buf_size, int64_t buf_size,
3414 bool has_on_source_error,
3415 BlockdevOnError on_source_error,
3416 bool has_on_target_error,
3417 BlockdevOnError on_target_error,
3418 bool has_unmap, bool unmap,
3425 if (!has_on_source_error) {
3426 on_source_error = BLOCKDEV_ON_ERROR_REPORT;
3428 if (!has_on_target_error) {
3429 on_target_error = BLOCKDEV_ON_ERROR_REPORT;
3431 if (!has_granularity) {
3434 if (!has_buf_size) {
3441 if (granularity != 0 && (granularity < 512 || granularity > 1048576 * 64)) {
3442 error_setg(errp, QERR_INVALID_PARAMETER_VALUE, "granularity",
3443 "a value in range [512B, 64MB]");
3446 if (granularity & (granularity - 1)) {
3447 error_setg(errp, QERR_INVALID_PARAMETER_VALUE, "granularity",
3452 if (bdrv_op_is_blocked(bs, BLOCK_OP_TYPE_MIRROR_SOURCE, errp)) {
3455 if (bdrv_op_is_blocked(target, BLOCK_OP_TYPE_MIRROR_TARGET, errp)) {
3459 if (!bs->backing && sync == MIRROR_SYNC_MODE_TOP) {
3460 sync = MIRROR_SYNC_MODE_FULL;
3463 /* pass the node name to replace to mirror start since it's loose coupling
3464 * and will allow to check whether the node still exist at mirror completion
3466 mirror_start(job_id, bs, target,
3467 has_replaces ? replaces : NULL,
3468 speed, granularity, buf_size, sync, backing_mode,
3469 on_source_error, on_target_error, unmap,
3470 block_job_cb, bs, errp);
3473 void qmp_drive_mirror(DriveMirror *arg, Error **errp)
3475 BlockDriverState *bs;
3477 BlockDriverState *source, *target_bs;
3478 AioContext *aio_context;
3479 BlockMirrorBackingMode backing_mode;
3480 Error *local_err = NULL;
3481 QDict *options = NULL;
3484 const char *format = arg->format;
3486 blk = blk_by_name(arg->device);
3488 error_set(errp, ERROR_CLASS_DEVICE_NOT_FOUND,
3489 "Device '%s' not found", arg->device);
3493 aio_context = blk_get_aio_context(blk);
3494 aio_context_acquire(aio_context);
3496 if (!blk_is_available(blk)) {
3497 error_setg(errp, QERR_DEVICE_HAS_NO_MEDIUM, arg->device);
3501 if (!arg->has_mode) {
3502 arg->mode = NEW_IMAGE_MODE_ABSOLUTE_PATHS;
3505 if (!arg->has_format) {
3506 format = (arg->mode == NEW_IMAGE_MODE_EXISTING
3507 ? NULL : bs->drv->format_name);
3510 flags = bs->open_flags | BDRV_O_RDWR;
3511 source = backing_bs(bs);
3512 if (!source && arg->sync == MIRROR_SYNC_MODE_TOP) {
3513 arg->sync = MIRROR_SYNC_MODE_FULL;
3515 if (arg->sync == MIRROR_SYNC_MODE_NONE) {
3519 size = bdrv_getlength(bs);
3521 error_setg_errno(errp, -size, "bdrv_getlength failed");
3525 if (arg->has_replaces) {
3526 BlockDriverState *to_replace_bs;
3527 AioContext *replace_aio_context;
3528 int64_t replace_size;
3530 if (!arg->has_node_name) {
3531 error_setg(errp, "a node-name must be provided when replacing a"
3532 " named node of the graph");
3536 to_replace_bs = check_to_replace_node(bs, arg->replaces, &local_err);
3538 if (!to_replace_bs) {
3539 error_propagate(errp, local_err);
3543 replace_aio_context = bdrv_get_aio_context(to_replace_bs);
3544 aio_context_acquire(replace_aio_context);
3545 replace_size = bdrv_getlength(to_replace_bs);
3546 aio_context_release(replace_aio_context);
3548 if (size != replace_size) {
3549 error_setg(errp, "cannot replace image with a mirror image of "
3555 if (arg->mode == NEW_IMAGE_MODE_ABSOLUTE_PATHS) {
3556 backing_mode = MIRROR_SOURCE_BACKING_CHAIN;
3558 backing_mode = MIRROR_OPEN_BACKING_CHAIN;
3561 if ((arg->sync == MIRROR_SYNC_MODE_FULL || !source)
3562 && arg->mode != NEW_IMAGE_MODE_EXISTING)
3564 /* create new image w/o backing file */
3566 bdrv_img_create(arg->target, format,
3567 NULL, NULL, NULL, size, flags, &local_err, false);
3569 switch (arg->mode) {
3570 case NEW_IMAGE_MODE_EXISTING:
3572 case NEW_IMAGE_MODE_ABSOLUTE_PATHS:
3573 /* create new image with backing file */
3574 bdrv_img_create(arg->target, format,
3576 source->drv->format_name,
3577 NULL, size, flags, &local_err, false);
3585 error_propagate(errp, local_err);
3589 options = qdict_new();
3590 if (arg->has_node_name) {
3591 qdict_put(options, "node-name", qstring_from_str(arg->node_name));
3594 qdict_put(options, "driver", qstring_from_str(format));
3597 /* Mirroring takes care of copy-on-write using the source's backing
3600 target_bs = bdrv_open(arg->target, NULL, options,
3601 flags | BDRV_O_NO_BACKING, errp);
3606 bdrv_set_aio_context(target_bs, aio_context);
3608 blockdev_mirror_common(arg->has_job_id ? arg->job_id : NULL, bs, target_bs,
3609 arg->has_replaces, arg->replaces, arg->sync,
3610 backing_mode, arg->has_speed, arg->speed,
3611 arg->has_granularity, arg->granularity,
3612 arg->has_buf_size, arg->buf_size,
3613 arg->has_on_source_error, arg->on_source_error,
3614 arg->has_on_target_error, arg->on_target_error,
3615 arg->has_unmap, arg->unmap,
3617 bdrv_unref(target_bs);
3618 error_propagate(errp, local_err);
3620 aio_context_release(aio_context);
3623 void qmp_blockdev_mirror(bool has_job_id, const char *job_id,
3624 const char *device, const char *target,
3625 bool has_replaces, const char *replaces,
3626 MirrorSyncMode sync,
3627 bool has_speed, int64_t speed,
3628 bool has_granularity, uint32_t granularity,
3629 bool has_buf_size, int64_t buf_size,
3630 bool has_on_source_error,
3631 BlockdevOnError on_source_error,
3632 bool has_on_target_error,
3633 BlockdevOnError on_target_error,
3636 BlockDriverState *bs;
3638 BlockDriverState *target_bs;
3639 AioContext *aio_context;
3640 BlockMirrorBackingMode backing_mode = MIRROR_LEAVE_BACKING_CHAIN;
3641 Error *local_err = NULL;
3643 blk = blk_by_name(device);
3645 error_setg(errp, "Device '%s' not found", device);
3651 error_setg(errp, "Device '%s' has no media", device);
3655 target_bs = bdrv_lookup_bs(target, target, errp);
3660 aio_context = bdrv_get_aio_context(bs);
3661 aio_context_acquire(aio_context);
3663 bdrv_set_aio_context(target_bs, aio_context);
3665 blockdev_mirror_common(has_job_id ? job_id : NULL, bs, target_bs,
3666 has_replaces, replaces, sync, backing_mode,
3668 has_granularity, granularity,
3669 has_buf_size, buf_size,
3670 has_on_source_error, on_source_error,
3671 has_on_target_error, on_target_error,
3674 error_propagate(errp, local_err);
3676 aio_context_release(aio_context);
3679 /* Get a block job using its ID and acquire its AioContext */
3680 static BlockJob *find_block_job(const char *id, AioContext **aio_context,
3687 *aio_context = NULL;
3689 job = block_job_get(id);
3692 error_set(errp, ERROR_CLASS_DEVICE_NOT_ACTIVE,
3693 "Block job '%s' not found", id);
3697 *aio_context = blk_get_aio_context(job->blk);
3698 aio_context_acquire(*aio_context);
3703 void qmp_block_job_set_speed(const char *device, int64_t speed, Error **errp)
3705 AioContext *aio_context;
3706 BlockJob *job = find_block_job(device, &aio_context, errp);
3712 block_job_set_speed(job, speed, errp);
3713 aio_context_release(aio_context);
3716 void qmp_block_job_cancel(const char *device,
3717 bool has_force, bool force, Error **errp)
3719 AioContext *aio_context;
3720 BlockJob *job = find_block_job(device, &aio_context, errp);
3730 if (job->user_paused && !force) {
3731 error_setg(errp, "The block job for device '%s' is currently paused",
3736 trace_qmp_block_job_cancel(job);
3737 block_job_cancel(job);
3739 aio_context_release(aio_context);
3742 void qmp_block_job_pause(const char *device, Error **errp)
3744 AioContext *aio_context;
3745 BlockJob *job = find_block_job(device, &aio_context, errp);
3747 if (!job || job->user_paused) {
3751 job->user_paused = true;
3752 trace_qmp_block_job_pause(job);
3753 block_job_pause(job);
3754 aio_context_release(aio_context);
3757 void qmp_block_job_resume(const char *device, Error **errp)
3759 AioContext *aio_context;
3760 BlockJob *job = find_block_job(device, &aio_context, errp);
3762 if (!job || !job->user_paused) {
3766 job->user_paused = false;
3767 trace_qmp_block_job_resume(job);
3768 block_job_iostatus_reset(job);
3769 block_job_resume(job);
3770 aio_context_release(aio_context);
3773 void qmp_block_job_complete(const char *device, Error **errp)
3775 AioContext *aio_context;
3776 BlockJob *job = find_block_job(device, &aio_context, errp);
3782 trace_qmp_block_job_complete(job);
3783 block_job_complete(job, errp);
3784 aio_context_release(aio_context);
3787 void qmp_change_backing_file(const char *device,
3788 const char *image_node_name,
3789 const char *backing_file,
3793 BlockDriverState *bs = NULL;
3794 AioContext *aio_context;
3795 BlockDriverState *image_bs = NULL;
3796 Error *local_err = NULL;
3801 blk = blk_by_name(device);
3803 error_set(errp, ERROR_CLASS_DEVICE_NOT_FOUND,
3804 "Device '%s' not found", device);
3808 aio_context = blk_get_aio_context(blk);
3809 aio_context_acquire(aio_context);
3811 if (!blk_is_available(blk)) {
3812 error_setg(errp, "Device '%s' has no medium", device);
3817 image_bs = bdrv_lookup_bs(NULL, image_node_name, &local_err);
3819 error_propagate(errp, local_err);
3824 error_setg(errp, "image file not found");
3828 if (bdrv_find_base(image_bs) == image_bs) {
3829 error_setg(errp, "not allowing backing file change on an image "
3830 "without a backing file");
3834 /* even though we are not necessarily operating on bs, we need it to
3835 * determine if block ops are currently prohibited on the chain */
3836 if (bdrv_op_is_blocked(bs, BLOCK_OP_TYPE_CHANGE, errp)) {
3840 /* final sanity check */
3841 if (!bdrv_chain_contains(bs, image_bs)) {
3842 error_setg(errp, "'%s' and image file are not in the same chain",
3847 /* if not r/w, reopen to make r/w */
3848 open_flags = image_bs->open_flags;
3849 ro = bdrv_is_read_only(image_bs);
3852 bdrv_reopen(image_bs, open_flags | BDRV_O_RDWR, &local_err);
3854 error_propagate(errp, local_err);
3859 ret = bdrv_change_backing_file(image_bs, backing_file,
3860 image_bs->drv ? image_bs->drv->format_name : "");
3863 error_setg_errno(errp, -ret, "Could not change backing file to '%s'",
3865 /* don't exit here, so we can try to restore open flags if
3870 bdrv_reopen(image_bs, open_flags, &local_err);
3871 error_propagate(errp, local_err);
3875 aio_context_release(aio_context);
3878 void hmp_drive_add_node(Monitor *mon, const char *optstr)
3882 Error *local_err = NULL;
3884 opts = qemu_opts_parse_noisily(&qemu_drive_opts, optstr, false);
3889 qdict = qemu_opts_to_qdict(opts, NULL);
3891 if (!qdict_get_try_str(qdict, "node-name")) {
3893 error_report("'node-name' needs to be specified");
3897 BlockDriverState *bs = bds_tree_init(qdict, &local_err);
3899 error_report_err(local_err);
3903 QTAILQ_INSERT_TAIL(&monitor_bdrv_states, bs, monitor_list);
3906 qemu_opts_del(opts);
3909 void qmp_blockdev_add(BlockdevOptions *options, Error **errp)
3911 BlockDriverState *bs;
3912 BlockBackend *blk = NULL;
3914 Visitor *v = qmp_output_visitor_new(&obj);
3916 Error *local_err = NULL;
3918 /* TODO Sort it out in raw-posix and drive_new(): Reject aio=native with
3919 * cache.direct=false instead of silently switching to aio=threads, except
3920 * when called from drive_new().
3922 * For now, simply forbidding the combination for all drivers will do. */
3923 if (options->has_aio && options->aio == BLOCKDEV_AIO_OPTIONS_NATIVE) {
3924 bool direct = options->has_cache &&
3925 options->cache->has_direct &&
3926 options->cache->direct;
3928 error_setg(errp, "aio=native requires cache.direct=true");
3933 visit_type_BlockdevOptions(v, NULL, &options, &local_err);
3935 error_propagate(errp, local_err);
3939 visit_complete(v, &obj);
3940 qdict = qobject_to_qdict(obj);
3942 qdict_flatten(qdict);
3944 if (options->has_id) {
3945 blk = blockdev_init(NULL, qdict, &local_err);
3947 error_propagate(errp, local_err);
3953 if (!qdict_get_try_str(qdict, "node-name")) {
3954 error_setg(errp, "'id' and/or 'node-name' need to be specified for "
3959 bs = bds_tree_init(qdict, errp);
3964 QTAILQ_INSERT_TAIL(&monitor_bdrv_states, bs, monitor_list);
3967 if (bs && bdrv_key_required(bs)) {
3969 monitor_remove_blk(blk);
3972 QTAILQ_REMOVE(&monitor_bdrv_states, bs, monitor_list);
3975 error_setg(errp, "blockdev-add doesn't support encrypted devices");
3983 void qmp_x_blockdev_del(bool has_id, const char *id,
3984 bool has_node_name, const char *node_name, Error **errp)
3986 AioContext *aio_context;
3988 BlockDriverState *bs;
3990 if (has_id && has_node_name) {
3991 error_setg(errp, "Only one of id and node-name must be specified");
3993 } else if (!has_id && !has_node_name) {
3994 error_setg(errp, "No block device specified");
3999 /* blk_by_name() never returns a BB that is not owned by the monitor */
4000 blk = blk_by_name(id);
4002 error_setg(errp, "Cannot find block backend %s", id);
4005 if (blk_legacy_dinfo(blk)) {
4006 error_setg(errp, "Deleting block backend added with drive-add"
4007 " is not supported");
4010 if (blk_get_refcnt(blk) > 1) {
4011 error_setg(errp, "Block backend %s is in use", id);
4015 aio_context = blk_get_aio_context(blk);
4018 bs = bdrv_find_node(node_name);
4020 error_setg(errp, "Cannot find node %s", node_name);
4023 if (bdrv_has_blk(bs)) {
4024 error_setg(errp, "Node %s is in use by %s",
4025 node_name, bdrv_get_parent_name(bs));
4028 aio_context = bdrv_get_aio_context(bs);
4031 aio_context_acquire(aio_context);
4034 if (bdrv_op_is_blocked(bs, BLOCK_OP_TYPE_DRIVE_DEL, errp)) {
4038 if (!blk && !bs->monitor_list.tqe_prev) {
4039 error_setg(errp, "Node %s is not owned by the monitor",
4044 if (bs->refcnt > 1) {
4045 error_setg(errp, "Block device %s is in use",
4046 bdrv_get_device_or_node_name(bs));
4052 monitor_remove_blk(blk);
4055 QTAILQ_REMOVE(&monitor_bdrv_states, bs, monitor_list);
4060 aio_context_release(aio_context);
4063 static BdrvChild *bdrv_find_child(BlockDriverState *parent_bs,
4064 const char *child_name)
4068 QLIST_FOREACH(child, &parent_bs->children, next) {
4069 if (strcmp(child->name, child_name) == 0) {
4077 void qmp_x_blockdev_change(const char *parent, bool has_child,
4078 const char *child, bool has_node,
4079 const char *node, Error **errp)
4081 BlockDriverState *parent_bs, *new_bs = NULL;
4084 parent_bs = bdrv_lookup_bs(parent, parent, errp);
4089 if (has_child == has_node) {
4091 error_setg(errp, "The parameters child and node are in conflict");
4093 error_setg(errp, "Either child or node must be specified");
4099 p_child = bdrv_find_child(parent_bs, child);
4101 error_setg(errp, "Node '%s' does not have child '%s'",
4105 bdrv_del_child(parent_bs, p_child, errp);
4109 new_bs = bdrv_find_node(node);
4111 error_setg(errp, "Node '%s' not found", node);
4114 bdrv_add_child(parent_bs, new_bs, errp);
4118 BlockJobInfoList *qmp_query_block_jobs(Error **errp)
4120 BlockJobInfoList *head = NULL, **p_next = &head;
4123 for (job = block_job_next(NULL); job; job = block_job_next(job)) {
4124 BlockJobInfoList *elem = g_new0(BlockJobInfoList, 1);
4125 AioContext *aio_context = blk_get_aio_context(job->blk);
4127 aio_context_acquire(aio_context);
4128 elem->value = block_job_query(job);
4129 aio_context_release(aio_context);
4132 p_next = &elem->next;
4138 QemuOptsList qemu_common_drive_opts = {
4140 .head = QTAILQ_HEAD_INITIALIZER(qemu_common_drive_opts.head),
4144 .type = QEMU_OPT_BOOL,
4145 .help = "enable/disable snapshot mode",
4148 .type = QEMU_OPT_STRING,
4149 .help = "discard operation (ignore/off, unmap/on)",
4152 .type = QEMU_OPT_STRING,
4153 .help = "host AIO implementation (threads, native)",
4155 .name = BDRV_OPT_CACHE_WB,
4156 .type = QEMU_OPT_BOOL,
4157 .help = "Enable writeback mode",
4160 .type = QEMU_OPT_STRING,
4161 .help = "disk format (raw, qcow2, ...)",
4164 .type = QEMU_OPT_STRING,
4165 .help = "read error action",
4168 .type = QEMU_OPT_STRING,
4169 .help = "write error action",
4171 .name = "read-only",
4172 .type = QEMU_OPT_BOOL,
4173 .help = "open drive file as read-only",
4175 .name = "throttling.iops-total",
4176 .type = QEMU_OPT_NUMBER,
4177 .help = "limit total I/O operations per second",
4179 .name = "throttling.iops-read",
4180 .type = QEMU_OPT_NUMBER,
4181 .help = "limit read operations per second",
4183 .name = "throttling.iops-write",
4184 .type = QEMU_OPT_NUMBER,
4185 .help = "limit write operations per second",
4187 .name = "throttling.bps-total",
4188 .type = QEMU_OPT_NUMBER,
4189 .help = "limit total bytes per second",
4191 .name = "throttling.bps-read",
4192 .type = QEMU_OPT_NUMBER,
4193 .help = "limit read bytes per second",
4195 .name = "throttling.bps-write",
4196 .type = QEMU_OPT_NUMBER,
4197 .help = "limit write bytes per second",
4199 .name = "throttling.iops-total-max",
4200 .type = QEMU_OPT_NUMBER,
4201 .help = "I/O operations burst",
4203 .name = "throttling.iops-read-max",
4204 .type = QEMU_OPT_NUMBER,
4205 .help = "I/O operations read burst",
4207 .name = "throttling.iops-write-max",
4208 .type = QEMU_OPT_NUMBER,
4209 .help = "I/O operations write burst",
4211 .name = "throttling.bps-total-max",
4212 .type = QEMU_OPT_NUMBER,
4213 .help = "total bytes burst",
4215 .name = "throttling.bps-read-max",
4216 .type = QEMU_OPT_NUMBER,
4217 .help = "total bytes read burst",
4219 .name = "throttling.bps-write-max",
4220 .type = QEMU_OPT_NUMBER,
4221 .help = "total bytes write burst",
4223 .name = "throttling.iops-total-max-length",
4224 .type = QEMU_OPT_NUMBER,
4225 .help = "length of the iops-total-max burst period, in seconds",
4227 .name = "throttling.iops-read-max-length",
4228 .type = QEMU_OPT_NUMBER,
4229 .help = "length of the iops-read-max burst period, in seconds",
4231 .name = "throttling.iops-write-max-length",
4232 .type = QEMU_OPT_NUMBER,
4233 .help = "length of the iops-write-max burst period, in seconds",
4235 .name = "throttling.bps-total-max-length",
4236 .type = QEMU_OPT_NUMBER,
4237 .help = "length of the bps-total-max burst period, in seconds",
4239 .name = "throttling.bps-read-max-length",
4240 .type = QEMU_OPT_NUMBER,
4241 .help = "length of the bps-read-max burst period, in seconds",
4243 .name = "throttling.bps-write-max-length",
4244 .type = QEMU_OPT_NUMBER,
4245 .help = "length of the bps-write-max burst period, in seconds",
4247 .name = "throttling.iops-size",
4248 .type = QEMU_OPT_NUMBER,
4249 .help = "when limiting by iops max size of an I/O in bytes",
4251 .name = "throttling.group",
4252 .type = QEMU_OPT_STRING,
4253 .help = "name of the block throttling group",
4255 .name = "copy-on-read",
4256 .type = QEMU_OPT_BOOL,
4257 .help = "copy read data from backing file into image file",
4259 .name = "detect-zeroes",
4260 .type = QEMU_OPT_STRING,
4261 .help = "try to optimize zero writes (off, on, unmap)",
4263 .name = "stats-account-invalid",
4264 .type = QEMU_OPT_BOOL,
4265 .help = "whether to account for invalid I/O operations "
4266 "in the statistics",
4268 .name = "stats-account-failed",
4269 .type = QEMU_OPT_BOOL,
4270 .help = "whether to account for failed I/O operations "
4271 "in the statistics",
4273 { /* end of list */ }
4277 static QemuOptsList qemu_root_bds_opts = {
4279 .head = QTAILQ_HEAD_INITIALIZER(qemu_root_bds_opts.head),
4283 .type = QEMU_OPT_STRING,
4284 .help = "discard operation (ignore/off, unmap/on)",
4287 .type = QEMU_OPT_STRING,
4288 .help = "host AIO implementation (threads, native)",
4290 .name = "read-only",
4291 .type = QEMU_OPT_BOOL,
4292 .help = "open drive file as read-only",
4294 .name = "copy-on-read",
4295 .type = QEMU_OPT_BOOL,
4296 .help = "copy read data from backing file into image file",
4298 .name = "detect-zeroes",
4299 .type = QEMU_OPT_STRING,
4300 .help = "try to optimize zero writes (off, on, unmap)",
4302 { /* end of list */ }
4306 QemuOptsList qemu_drive_opts = {
4308 .head = QTAILQ_HEAD_INITIALIZER(qemu_drive_opts.head),
4311 * no elements => accept any params
4312 * validation will happen later
4314 { /* end of list */ }