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);
59 static const char *const if_name[IF_COUNT] = {
63 [IF_FLOPPY] = "floppy",
64 [IF_PFLASH] = "pflash",
67 [IF_VIRTIO] = "virtio",
71 static int if_max_devs[IF_COUNT] = {
73 * Do not change these numbers! They govern how drive option
74 * index maps to unit and bus. That mapping is ABI.
76 * All controllers used to imlement if=T drives need to support
77 * if_max_devs[T] units, for any T with if_max_devs[T] != 0.
78 * Otherwise, some index values map to "impossible" bus, unit
81 * For instance, if you change [IF_SCSI] to 255, -drive
82 * if=scsi,index=12 no longer means bus=1,unit=5, but
83 * bus=0,unit=12. With an lsi53c895a controller (7 units max),
84 * the drive can't be set up. Regression.
91 * Boards may call this to offer board-by-board overrides
92 * of the default, global values.
94 void override_max_devs(BlockInterfaceType type, int max_devs)
103 for (blk = blk_next(NULL); blk; blk = blk_next(blk)) {
104 dinfo = blk_legacy_dinfo(blk);
105 if (dinfo->type == type) {
106 fprintf(stderr, "Cannot override units-per-bus property of"
107 " the %s interface, because a drive of that type has"
108 " already been added.\n", if_name[type]);
109 g_assert_not_reached();
113 if_max_devs[type] = max_devs;
117 * We automatically delete the drive when a device using it gets
118 * unplugged. Questionable feature, but we can't just drop it.
119 * Device models call blockdev_mark_auto_del() to schedule the
120 * automatic deletion, and generic qdev code calls blockdev_auto_del()
121 * when deletion is actually safe.
123 void blockdev_mark_auto_del(BlockBackend *blk)
125 DriveInfo *dinfo = blk_legacy_dinfo(blk);
126 BlockDriverState *bs = blk_bs(blk);
127 AioContext *aio_context;
134 aio_context = bdrv_get_aio_context(bs);
135 aio_context_acquire(aio_context);
138 block_job_cancel(bs->job);
141 aio_context_release(aio_context);
147 void blockdev_auto_del(BlockBackend *blk)
149 DriveInfo *dinfo = blk_legacy_dinfo(blk);
151 if (dinfo && dinfo->auto_del) {
152 monitor_remove_blk(blk);
158 * Returns the current mapping of how many units per bus
159 * a particular interface can support.
161 * A positive integer indicates n units per bus.
162 * 0 implies the mapping has not been established.
163 * -1 indicates an invalid BlockInterfaceType was given.
165 int drive_get_max_devs(BlockInterfaceType type)
167 if (type >= IF_IDE && type < IF_COUNT) {
168 return if_max_devs[type];
174 static int drive_index_to_bus_id(BlockInterfaceType type, int index)
176 int max_devs = if_max_devs[type];
177 return max_devs ? index / max_devs : 0;
180 static int drive_index_to_unit_id(BlockInterfaceType type, int index)
182 int max_devs = if_max_devs[type];
183 return max_devs ? index % max_devs : index;
186 QemuOpts *drive_def(const char *optstr)
188 return qemu_opts_parse_noisily(qemu_find_opts("drive"), optstr, false);
191 QemuOpts *drive_add(BlockInterfaceType type, int index, const char *file,
196 opts = drive_def(optstr);
200 if (type != IF_DEFAULT) {
201 qemu_opt_set(opts, "if", if_name[type], &error_abort);
204 qemu_opt_set_number(opts, "index", index, &error_abort);
207 qemu_opt_set(opts, "file", file, &error_abort);
211 DriveInfo *drive_get(BlockInterfaceType type, int bus, int unit)
216 for (blk = blk_next(NULL); blk; blk = blk_next(blk)) {
217 dinfo = blk_legacy_dinfo(blk);
218 if (dinfo && dinfo->type == type
219 && dinfo->bus == bus && dinfo->unit == unit) {
227 bool drive_check_orphaned(void)
233 for (blk = blk_next(NULL); blk; blk = blk_next(blk)) {
234 dinfo = blk_legacy_dinfo(blk);
235 /* If dinfo->bdrv->dev is NULL, it has no device attached. */
236 /* Unless this is a default drive, this may be an oversight. */
237 if (!blk_get_attached_dev(blk) && !dinfo->is_default &&
238 dinfo->type != IF_NONE) {
239 fprintf(stderr, "Warning: Orphaned drive without device: "
240 "id=%s,file=%s,if=%s,bus=%d,unit=%d\n",
241 blk_name(blk), blk_bs(blk) ? blk_bs(blk)->filename : "",
242 if_name[dinfo->type], dinfo->bus, dinfo->unit);
250 DriveInfo *drive_get_by_index(BlockInterfaceType type, int index)
252 return drive_get(type,
253 drive_index_to_bus_id(type, index),
254 drive_index_to_unit_id(type, index));
257 int drive_get_max_bus(BlockInterfaceType type)
264 for (blk = blk_next(NULL); blk; blk = blk_next(blk)) {
265 dinfo = blk_legacy_dinfo(blk);
266 if (dinfo && dinfo->type == type && dinfo->bus > max_bus) {
267 max_bus = dinfo->bus;
273 /* Get a block device. This should only be used for single-drive devices
274 (e.g. SD/Floppy/MTD). Multi-disk devices (scsi/ide) should use the
276 DriveInfo *drive_get_next(BlockInterfaceType type)
278 static int next_block_unit[IF_COUNT];
280 return drive_get(type, 0, next_block_unit[type]++);
283 static void bdrv_format_print(void *opaque, const char *name)
285 error_printf(" %s", name);
290 BlockDriverState *bs;
293 static int parse_block_error_action(const char *buf, bool is_read, Error **errp)
295 if (!strcmp(buf, "ignore")) {
296 return BLOCKDEV_ON_ERROR_IGNORE;
297 } else if (!is_read && !strcmp(buf, "enospc")) {
298 return BLOCKDEV_ON_ERROR_ENOSPC;
299 } else if (!strcmp(buf, "stop")) {
300 return BLOCKDEV_ON_ERROR_STOP;
301 } else if (!strcmp(buf, "report")) {
302 return BLOCKDEV_ON_ERROR_REPORT;
304 error_setg(errp, "'%s' invalid %s error action",
305 buf, is_read ? "read" : "write");
310 static bool parse_stats_intervals(BlockAcctStats *stats, QList *intervals,
313 const QListEntry *entry;
314 for (entry = qlist_first(intervals); entry; entry = qlist_next(entry)) {
315 switch (qobject_type(entry->value)) {
317 case QTYPE_QSTRING: {
318 unsigned long long length;
319 const char *str = qstring_get_str(qobject_to_qstring(entry->value));
320 if (parse_uint_full(str, &length, 10) == 0 &&
321 length > 0 && length <= UINT_MAX) {
322 block_acct_add_interval(stats, (unsigned) length);
324 error_setg(errp, "Invalid interval length: %s", str);
331 int64_t length = qint_get_int(qobject_to_qint(entry->value));
332 if (length > 0 && length <= UINT_MAX) {
333 block_acct_add_interval(stats, (unsigned) length);
335 error_setg(errp, "Invalid interval length: %" PRId64, length);
342 error_setg(errp, "The specification of stats-intervals is invalid");
349 typedef enum { MEDIA_DISK, MEDIA_CDROM } DriveMediaType;
351 /* All parameters but @opts are optional and may be set to NULL. */
352 static void extract_common_blockdev_options(QemuOpts *opts, int *bdrv_flags,
353 const char **throttling_group, ThrottleConfig *throttle_cfg,
354 BlockdevDetectZeroesOptions *detect_zeroes, Error **errp)
357 Error *local_error = NULL;
361 if (!qemu_opt_get_bool(opts, "read-only", false)) {
362 *bdrv_flags |= BDRV_O_RDWR;
364 if (qemu_opt_get_bool(opts, "copy-on-read", false)) {
365 *bdrv_flags |= BDRV_O_COPY_ON_READ;
368 if ((discard = qemu_opt_get(opts, "discard")) != NULL) {
369 if (bdrv_parse_discard_flags(discard, bdrv_flags) != 0) {
370 error_setg(errp, "Invalid discard option");
375 if ((aio = qemu_opt_get(opts, "aio")) != NULL) {
376 if (!strcmp(aio, "native")) {
377 *bdrv_flags |= BDRV_O_NATIVE_AIO;
378 } else if (!strcmp(aio, "threads")) {
379 /* this is the default */
381 error_setg(errp, "invalid aio option");
387 /* disk I/O throttling */
388 if (throttling_group) {
389 *throttling_group = qemu_opt_get(opts, "throttling.group");
393 throttle_config_init(throttle_cfg);
394 throttle_cfg->buckets[THROTTLE_BPS_TOTAL].avg =
395 qemu_opt_get_number(opts, "throttling.bps-total", 0);
396 throttle_cfg->buckets[THROTTLE_BPS_READ].avg =
397 qemu_opt_get_number(opts, "throttling.bps-read", 0);
398 throttle_cfg->buckets[THROTTLE_BPS_WRITE].avg =
399 qemu_opt_get_number(opts, "throttling.bps-write", 0);
400 throttle_cfg->buckets[THROTTLE_OPS_TOTAL].avg =
401 qemu_opt_get_number(opts, "throttling.iops-total", 0);
402 throttle_cfg->buckets[THROTTLE_OPS_READ].avg =
403 qemu_opt_get_number(opts, "throttling.iops-read", 0);
404 throttle_cfg->buckets[THROTTLE_OPS_WRITE].avg =
405 qemu_opt_get_number(opts, "throttling.iops-write", 0);
407 throttle_cfg->buckets[THROTTLE_BPS_TOTAL].max =
408 qemu_opt_get_number(opts, "throttling.bps-total-max", 0);
409 throttle_cfg->buckets[THROTTLE_BPS_READ].max =
410 qemu_opt_get_number(opts, "throttling.bps-read-max", 0);
411 throttle_cfg->buckets[THROTTLE_BPS_WRITE].max =
412 qemu_opt_get_number(opts, "throttling.bps-write-max", 0);
413 throttle_cfg->buckets[THROTTLE_OPS_TOTAL].max =
414 qemu_opt_get_number(opts, "throttling.iops-total-max", 0);
415 throttle_cfg->buckets[THROTTLE_OPS_READ].max =
416 qemu_opt_get_number(opts, "throttling.iops-read-max", 0);
417 throttle_cfg->buckets[THROTTLE_OPS_WRITE].max =
418 qemu_opt_get_number(opts, "throttling.iops-write-max", 0);
420 throttle_cfg->buckets[THROTTLE_BPS_TOTAL].burst_length =
421 qemu_opt_get_number(opts, "throttling.bps-total-max-length", 1);
422 throttle_cfg->buckets[THROTTLE_BPS_READ].burst_length =
423 qemu_opt_get_number(opts, "throttling.bps-read-max-length", 1);
424 throttle_cfg->buckets[THROTTLE_BPS_WRITE].burst_length =
425 qemu_opt_get_number(opts, "throttling.bps-write-max-length", 1);
426 throttle_cfg->buckets[THROTTLE_OPS_TOTAL].burst_length =
427 qemu_opt_get_number(opts, "throttling.iops-total-max-length", 1);
428 throttle_cfg->buckets[THROTTLE_OPS_READ].burst_length =
429 qemu_opt_get_number(opts, "throttling.iops-read-max-length", 1);
430 throttle_cfg->buckets[THROTTLE_OPS_WRITE].burst_length =
431 qemu_opt_get_number(opts, "throttling.iops-write-max-length", 1);
433 throttle_cfg->op_size =
434 qemu_opt_get_number(opts, "throttling.iops-size", 0);
436 if (!throttle_is_valid(throttle_cfg, errp)) {
443 qapi_enum_parse(BlockdevDetectZeroesOptions_lookup,
444 qemu_opt_get(opts, "detect-zeroes"),
445 BLOCKDEV_DETECT_ZEROES_OPTIONS__MAX,
446 BLOCKDEV_DETECT_ZEROES_OPTIONS_OFF,
449 error_propagate(errp, local_error);
454 *detect_zeroes == BLOCKDEV_DETECT_ZEROES_OPTIONS_UNMAP &&
455 !(*bdrv_flags & BDRV_O_UNMAP))
457 error_setg(errp, "setting detect-zeroes to unmap is not allowed "
458 "without setting discard operation to unmap");
464 /* Takes the ownership of bs_opts */
465 static BlockBackend *blockdev_init(const char *file, QDict *bs_opts,
470 int on_read_error, on_write_error;
471 bool account_invalid, account_failed;
474 BlockDriverState *bs;
479 QDict *interval_dict = NULL;
480 QList *interval_list = NULL;
482 BlockdevDetectZeroesOptions detect_zeroes =
483 BLOCKDEV_DETECT_ZEROES_OPTIONS_OFF;
484 const char *throttling_group = NULL;
486 /* Check common options by copying from bs_opts to opts, all other options
487 * stay in bs_opts for processing by bdrv_open(). */
488 id = qdict_get_try_str(bs_opts, "id");
489 opts = qemu_opts_create(&qemu_common_drive_opts, id, 1, &error);
491 error_propagate(errp, error);
495 qemu_opts_absorb_qdict(opts, bs_opts, &error);
497 error_propagate(errp, error);
502 qdict_del(bs_opts, "id");
505 /* extract parameters */
506 snapshot = qemu_opt_get_bool(opts, "snapshot", 0);
508 account_invalid = qemu_opt_get_bool(opts, "stats-account-invalid", true);
509 account_failed = qemu_opt_get_bool(opts, "stats-account-failed", true);
511 writethrough = !qemu_opt_get_bool(opts, BDRV_OPT_CACHE_WB, true);
513 qdict_extract_subqdict(bs_opts, &interval_dict, "stats-intervals.");
514 qdict_array_split(interval_dict, &interval_list);
516 if (qdict_size(interval_dict) != 0) {
517 error_setg(errp, "Invalid option stats-intervals.%s",
518 qdict_first(interval_dict)->key);
522 extract_common_blockdev_options(opts, &bdrv_flags, &throttling_group, &cfg,
523 &detect_zeroes, &error);
525 error_propagate(errp, error);
529 if ((buf = qemu_opt_get(opts, "format")) != NULL) {
530 if (is_help_option(buf)) {
531 error_printf("Supported formats:");
532 bdrv_iterate_format(bdrv_format_print, NULL);
537 if (qdict_haskey(bs_opts, "driver")) {
538 error_setg(errp, "Cannot specify both 'driver' and 'format'");
541 qdict_put(bs_opts, "driver", qstring_from_str(buf));
544 on_write_error = BLOCKDEV_ON_ERROR_ENOSPC;
545 if ((buf = qemu_opt_get(opts, "werror")) != NULL) {
546 on_write_error = parse_block_error_action(buf, 0, &error);
548 error_propagate(errp, error);
553 on_read_error = BLOCKDEV_ON_ERROR_REPORT;
554 if ((buf = qemu_opt_get(opts, "rerror")) != NULL) {
555 on_read_error = parse_block_error_action(buf, 1, &error);
557 error_propagate(errp, error);
563 bdrv_flags |= BDRV_O_SNAPSHOT;
567 if ((!file || !*file) && !qdict_size(bs_opts)) {
568 BlockBackendRootState *blk_rs;
575 blk_rs = blk_get_root_state(blk);
576 blk_rs->open_flags = bdrv_flags;
577 blk_rs->read_only = !(bdrv_flags & BDRV_O_RDWR);
578 blk_rs->detect_zeroes = detect_zeroes;
580 if (throttle_enabled(&cfg)) {
581 if (!throttling_group) {
582 throttling_group = blk_name(blk);
584 blk_rs->throttle_group = g_strdup(throttling_group);
585 blk_rs->throttle_state = throttle_group_incref(throttling_group);
586 blk_rs->throttle_state->cfg = cfg;
591 if (file && !*file) {
595 /* bdrv_open() defaults to the values in bdrv_flags (for compatibility
596 * with other callers) rather than what we want as the real defaults.
597 * Apply the defaults here instead. */
598 qdict_set_default_str(bs_opts, BDRV_OPT_CACHE_WB, writethrough ? "off" : "on");
599 qdict_set_default_str(bs_opts, BDRV_OPT_CACHE_DIRECT, "off");
600 qdict_set_default_str(bs_opts, BDRV_OPT_CACHE_NO_FLUSH, "off");
601 assert((bdrv_flags & BDRV_O_CACHE_MASK) == 0);
603 if (runstate_check(RUN_STATE_INMIGRATE)) {
604 bdrv_flags |= BDRV_O_INACTIVE;
607 blk = blk_new_open(file, NULL, bs_opts, bdrv_flags, errp);
613 bs->detect_zeroes = detect_zeroes;
615 /* disk I/O throttling */
616 if (throttle_enabled(&cfg)) {
617 if (!throttling_group) {
618 throttling_group = blk_name(blk);
620 bdrv_io_limits_enable(bs, throttling_group);
621 bdrv_set_io_limits(bs, &cfg);
624 if (bdrv_key_required(bs)) {
628 block_acct_init(blk_get_stats(blk), account_invalid, account_failed);
630 if (!parse_stats_intervals(blk_get_stats(blk), interval_list, errp)) {
637 blk_set_enable_write_cache(blk, !writethrough);
638 blk_set_on_error(blk, on_read_error, on_write_error);
640 if (!monitor_add_blk(blk, qemu_opts_id(opts), errp)) {
648 QDECREF(interval_dict);
649 QDECREF(interval_list);
654 QDECREF(interval_dict);
655 QDECREF(interval_list);
661 static QemuOptsList qemu_root_bds_opts;
663 /* Takes the ownership of bs_opts */
664 static BlockDriverState *bds_tree_init(QDict *bs_opts, Error **errp)
666 BlockDriverState *bs;
668 Error *local_error = NULL;
669 BlockdevDetectZeroesOptions detect_zeroes;
673 opts = qemu_opts_create(&qemu_root_bds_opts, NULL, 1, errp);
678 qemu_opts_absorb_qdict(opts, bs_opts, &local_error);
680 error_propagate(errp, local_error);
684 extract_common_blockdev_options(opts, &bdrv_flags, NULL, NULL,
685 &detect_zeroes, &local_error);
687 error_propagate(errp, local_error);
691 /* bdrv_open() defaults to the values in bdrv_flags (for compatibility
692 * with other callers) rather than what we want as the real defaults.
693 * Apply the defaults here instead. */
694 qdict_set_default_str(bs_opts, BDRV_OPT_CACHE_WB, "on");
695 qdict_set_default_str(bs_opts, BDRV_OPT_CACHE_DIRECT, "off");
696 qdict_set_default_str(bs_opts, BDRV_OPT_CACHE_NO_FLUSH, "off");
698 if (runstate_check(RUN_STATE_INMIGRATE)) {
699 bdrv_flags |= BDRV_O_INACTIVE;
703 ret = bdrv_open(&bs, NULL, NULL, bs_opts, bdrv_flags, errp);
705 goto fail_no_bs_opts;
708 bs->detect_zeroes = detect_zeroes;
720 void blockdev_close_all_bdrv_states(void)
722 BlockDriverState *bs, *next_bs;
724 QTAILQ_FOREACH_SAFE(bs, &monitor_bdrv_states, monitor_list, next_bs) {
725 AioContext *ctx = bdrv_get_aio_context(bs);
727 aio_context_acquire(ctx);
729 aio_context_release(ctx);
733 /* Iterates over the list of monitor-owned BlockDriverStates */
734 BlockDriverState *bdrv_next_monitor_owned(BlockDriverState *bs)
736 return bs ? QTAILQ_NEXT(bs, monitor_list)
737 : QTAILQ_FIRST(&monitor_bdrv_states);
740 static void qemu_opt_rename(QemuOpts *opts, const char *from, const char *to,
745 value = qemu_opt_get(opts, from);
747 if (qemu_opt_find(opts, to)) {
748 error_setg(errp, "'%s' and its alias '%s' can't be used at the "
749 "same time", to, from);
754 /* rename all items in opts */
755 while ((value = qemu_opt_get(opts, from))) {
756 qemu_opt_set(opts, to, value, &error_abort);
757 qemu_opt_unset(opts, from);
761 QemuOptsList qemu_legacy_drive_opts = {
763 .head = QTAILQ_HEAD_INITIALIZER(qemu_legacy_drive_opts.head),
767 .type = QEMU_OPT_NUMBER,
768 .help = "bus number",
771 .type = QEMU_OPT_NUMBER,
772 .help = "unit number (i.e. lun for scsi)",
775 .type = QEMU_OPT_NUMBER,
776 .help = "index number",
779 .type = QEMU_OPT_STRING,
780 .help = "media type (disk, cdrom)",
783 .type = QEMU_OPT_STRING,
784 .help = "interface (ide, scsi, sd, mtd, floppy, pflash, virtio)",
787 .type = QEMU_OPT_NUMBER,
788 .help = "number of cylinders (ide disk geometry)",
791 .type = QEMU_OPT_NUMBER,
792 .help = "number of heads (ide disk geometry)",
795 .type = QEMU_OPT_NUMBER,
796 .help = "number of sectors (ide disk geometry)",
799 .type = QEMU_OPT_STRING,
800 .help = "chs translation (auto, lba, none)",
803 .type = QEMU_OPT_BOOL,
804 .help = "(deprecated, ignored)",
807 .type = QEMU_OPT_STRING,
808 .help = "pci address (virtio only)",
811 .type = QEMU_OPT_STRING,
812 .help = "disk serial number",
815 .type = QEMU_OPT_STRING,
819 /* Options that are passed on, but have special semantics with -drive */
822 .type = QEMU_OPT_BOOL,
823 .help = "open drive file as read-only",
826 .type = QEMU_OPT_STRING,
827 .help = "read error action",
830 .type = QEMU_OPT_STRING,
831 .help = "write error action",
833 .name = "copy-on-read",
834 .type = QEMU_OPT_BOOL,
835 .help = "copy read data from backing file into image file",
838 { /* end of list */ }
842 DriveInfo *drive_new(QemuOpts *all_opts, BlockInterfaceType block_default_type)
846 DriveInfo *dinfo = NULL;
848 QemuOpts *legacy_opts;
849 DriveMediaType media = MEDIA_DISK;
850 BlockInterfaceType type;
851 int cyls, heads, secs, translation;
852 int max_devs, bus_id, unit_id, index;
854 const char *werror, *rerror;
855 bool read_only = false;
858 const char *filename;
859 Error *local_err = NULL;
862 /* Change legacy command line options into QMP ones */
863 static const struct {
867 { "iops", "throttling.iops-total" },
868 { "iops_rd", "throttling.iops-read" },
869 { "iops_wr", "throttling.iops-write" },
871 { "bps", "throttling.bps-total" },
872 { "bps_rd", "throttling.bps-read" },
873 { "bps_wr", "throttling.bps-write" },
875 { "iops_max", "throttling.iops-total-max" },
876 { "iops_rd_max", "throttling.iops-read-max" },
877 { "iops_wr_max", "throttling.iops-write-max" },
879 { "bps_max", "throttling.bps-total-max" },
880 { "bps_rd_max", "throttling.bps-read-max" },
881 { "bps_wr_max", "throttling.bps-write-max" },
883 { "iops_size", "throttling.iops-size" },
885 { "group", "throttling.group" },
887 { "readonly", "read-only" },
890 for (i = 0; i < ARRAY_SIZE(opt_renames); i++) {
891 qemu_opt_rename(all_opts, opt_renames[i].from, opt_renames[i].to,
894 error_report_err(local_err);
899 value = qemu_opt_get(all_opts, "cache");
903 if (bdrv_parse_cache_flags(value, &flags) != 0) {
904 error_report("invalid cache option");
908 /* Specific options take precedence */
909 if (!qemu_opt_get(all_opts, BDRV_OPT_CACHE_WB)) {
910 qemu_opt_set_bool(all_opts, BDRV_OPT_CACHE_WB,
911 !!(flags & BDRV_O_CACHE_WB), &error_abort);
913 if (!qemu_opt_get(all_opts, BDRV_OPT_CACHE_DIRECT)) {
914 qemu_opt_set_bool(all_opts, BDRV_OPT_CACHE_DIRECT,
915 !!(flags & BDRV_O_NOCACHE), &error_abort);
917 if (!qemu_opt_get(all_opts, BDRV_OPT_CACHE_NO_FLUSH)) {
918 qemu_opt_set_bool(all_opts, BDRV_OPT_CACHE_NO_FLUSH,
919 !!(flags & BDRV_O_NO_FLUSH), &error_abort);
921 qemu_opt_unset(all_opts, "cache");
924 /* Get a QDict for processing the options */
925 bs_opts = qdict_new();
926 qemu_opts_to_qdict(all_opts, bs_opts);
928 legacy_opts = qemu_opts_create(&qemu_legacy_drive_opts, NULL, 0,
930 qemu_opts_absorb_qdict(legacy_opts, bs_opts, &local_err);
932 error_report_err(local_err);
936 /* Deprecated option boot=[on|off] */
937 if (qemu_opt_get(legacy_opts, "boot") != NULL) {
938 fprintf(stderr, "qemu-kvm: boot=on|off is deprecated and will be "
939 "ignored. Future versions will reject this parameter. Please "
940 "update your scripts.\n");
944 value = qemu_opt_get(legacy_opts, "media");
946 if (!strcmp(value, "disk")) {
948 } else if (!strcmp(value, "cdrom")) {
952 error_report("'%s' invalid media", value);
957 /* copy-on-read is disabled with a warning for read-only devices */
958 read_only |= qemu_opt_get_bool(legacy_opts, "read-only", false);
959 copy_on_read = qemu_opt_get_bool(legacy_opts, "copy-on-read", false);
961 if (read_only && copy_on_read) {
962 error_report("warning: disabling copy-on-read on read-only drive");
963 copy_on_read = false;
966 qdict_put(bs_opts, "read-only",
967 qstring_from_str(read_only ? "on" : "off"));
968 qdict_put(bs_opts, "copy-on-read",
969 qstring_from_str(copy_on_read ? "on" :"off"));
971 /* Controller type */
972 value = qemu_opt_get(legacy_opts, "if");
975 type < IF_COUNT && strcmp(value, if_name[type]);
978 if (type == IF_COUNT) {
979 error_report("unsupported bus type '%s'", value);
983 type = block_default_type;
987 cyls = qemu_opt_get_number(legacy_opts, "cyls", 0);
988 heads = qemu_opt_get_number(legacy_opts, "heads", 0);
989 secs = qemu_opt_get_number(legacy_opts, "secs", 0);
991 if (cyls || heads || secs) {
993 error_report("invalid physical cyls number");
997 error_report("invalid physical heads number");
1001 error_report("invalid physical secs number");
1006 translation = BIOS_ATA_TRANSLATION_AUTO;
1007 value = qemu_opt_get(legacy_opts, "trans");
1008 if (value != NULL) {
1010 error_report("'%s' trans must be used with cyls, heads and secs",
1014 if (!strcmp(value, "none")) {
1015 translation = BIOS_ATA_TRANSLATION_NONE;
1016 } else if (!strcmp(value, "lba")) {
1017 translation = BIOS_ATA_TRANSLATION_LBA;
1018 } else if (!strcmp(value, "large")) {
1019 translation = BIOS_ATA_TRANSLATION_LARGE;
1020 } else if (!strcmp(value, "rechs")) {
1021 translation = BIOS_ATA_TRANSLATION_RECHS;
1022 } else if (!strcmp(value, "auto")) {
1023 translation = BIOS_ATA_TRANSLATION_AUTO;
1025 error_report("'%s' invalid translation type", value);
1030 if (media == MEDIA_CDROM) {
1031 if (cyls || secs || heads) {
1032 error_report("CHS can't be set with media=cdrom");
1037 /* Device address specified by bus/unit or index.
1038 * If none was specified, try to find the first free one. */
1039 bus_id = qemu_opt_get_number(legacy_opts, "bus", 0);
1040 unit_id = qemu_opt_get_number(legacy_opts, "unit", -1);
1041 index = qemu_opt_get_number(legacy_opts, "index", -1);
1043 max_devs = if_max_devs[type];
1046 if (bus_id != 0 || unit_id != -1) {
1047 error_report("index cannot be used with bus and unit");
1050 bus_id = drive_index_to_bus_id(type, index);
1051 unit_id = drive_index_to_unit_id(type, index);
1054 if (unit_id == -1) {
1056 while (drive_get(type, bus_id, unit_id) != NULL) {
1058 if (max_devs && unit_id >= max_devs) {
1059 unit_id -= max_devs;
1065 if (max_devs && unit_id >= max_devs) {
1066 error_report("unit %d too big (max is %d)", unit_id, max_devs - 1);
1070 if (drive_get(type, bus_id, unit_id) != NULL) {
1071 error_report("drive with bus=%d, unit=%d (index=%d) exists",
1072 bus_id, unit_id, index);
1077 serial = qemu_opt_get(legacy_opts, "serial");
1079 /* no id supplied -> create one */
1080 if (qemu_opts_id(all_opts) == NULL) {
1082 const char *mediastr = "";
1083 if (type == IF_IDE || type == IF_SCSI) {
1084 mediastr = (media == MEDIA_CDROM) ? "-cd" : "-hd";
1087 new_id = g_strdup_printf("%s%i%s%i", if_name[type], bus_id,
1090 new_id = g_strdup_printf("%s%s%i", if_name[type],
1093 qdict_put(bs_opts, "id", qstring_from_str(new_id));
1097 /* Add virtio block device */
1098 devaddr = qemu_opt_get(legacy_opts, "addr");
1099 if (devaddr && type != IF_VIRTIO) {
1100 error_report("addr is not supported by this bus type");
1104 if (type == IF_VIRTIO) {
1106 devopts = qemu_opts_create(qemu_find_opts("device"), NULL, 0,
1108 if (arch_type == QEMU_ARCH_S390X) {
1109 qemu_opt_set(devopts, "driver", "virtio-blk-ccw", &error_abort);
1111 qemu_opt_set(devopts, "driver", "virtio-blk-pci", &error_abort);
1113 qemu_opt_set(devopts, "drive", qdict_get_str(bs_opts, "id"),
1116 qemu_opt_set(devopts, "addr", devaddr, &error_abort);
1120 filename = qemu_opt_get(legacy_opts, "file");
1122 /* Check werror/rerror compatibility with if=... */
1123 werror = qemu_opt_get(legacy_opts, "werror");
1124 if (werror != NULL) {
1125 if (type != IF_IDE && type != IF_SCSI && type != IF_VIRTIO &&
1127 error_report("werror is not supported by this bus type");
1130 qdict_put(bs_opts, "werror", qstring_from_str(werror));
1133 rerror = qemu_opt_get(legacy_opts, "rerror");
1134 if (rerror != NULL) {
1135 if (type != IF_IDE && type != IF_VIRTIO && type != IF_SCSI &&
1137 error_report("rerror is not supported by this bus type");
1140 qdict_put(bs_opts, "rerror", qstring_from_str(rerror));
1143 /* Actual block device init: Functionality shared with blockdev-add */
1144 blk = blockdev_init(filename, bs_opts, &local_err);
1148 error_report_err(local_err);
1155 /* Create legacy DriveInfo */
1156 dinfo = g_malloc0(sizeof(*dinfo));
1157 dinfo->opts = all_opts;
1160 dinfo->heads = heads;
1162 dinfo->trans = translation;
1165 dinfo->bus = bus_id;
1166 dinfo->unit = unit_id;
1167 dinfo->devaddr = devaddr;
1168 dinfo->serial = g_strdup(serial);
1170 blk_set_legacy_dinfo(blk, dinfo);
1177 dinfo->media_cd = media == MEDIA_CDROM;
1184 qemu_opts_del(legacy_opts);
1189 void hmp_commit(Monitor *mon, const QDict *qdict)
1191 const char *device = qdict_get_str(qdict, "device");
1195 if (!strcmp(device, "all")) {
1196 ret = blk_commit_all();
1198 BlockDriverState *bs;
1199 AioContext *aio_context;
1201 blk = blk_by_name(device);
1203 monitor_printf(mon, "Device '%s' not found\n", device);
1206 if (!blk_is_available(blk)) {
1207 monitor_printf(mon, "Device '%s' has no medium\n", device);
1212 aio_context = bdrv_get_aio_context(bs);
1213 aio_context_acquire(aio_context);
1215 ret = bdrv_commit(bs);
1217 aio_context_release(aio_context);
1220 monitor_printf(mon, "'commit' error for '%s': %s\n", device,
1225 static void blockdev_do_action(TransactionAction *action, Error **errp)
1227 TransactionActionList list;
1229 list.value = action;
1231 qmp_transaction(&list, false, NULL, errp);
1234 void qmp_blockdev_snapshot_sync(bool has_device, const char *device,
1235 bool has_node_name, const char *node_name,
1236 const char *snapshot_file,
1237 bool has_snapshot_node_name,
1238 const char *snapshot_node_name,
1239 bool has_format, const char *format,
1240 bool has_mode, NewImageMode mode, Error **errp)
1242 BlockdevSnapshotSync snapshot = {
1243 .has_device = has_device,
1244 .device = (char *) device,
1245 .has_node_name = has_node_name,
1246 .node_name = (char *) node_name,
1247 .snapshot_file = (char *) snapshot_file,
1248 .has_snapshot_node_name = has_snapshot_node_name,
1249 .snapshot_node_name = (char *) snapshot_node_name,
1250 .has_format = has_format,
1251 .format = (char *) format,
1252 .has_mode = has_mode,
1255 TransactionAction action = {
1256 .type = TRANSACTION_ACTION_KIND_BLOCKDEV_SNAPSHOT_SYNC,
1257 .u.blockdev_snapshot_sync.data = &snapshot,
1259 blockdev_do_action(&action, errp);
1262 void qmp_blockdev_snapshot(const char *node, const char *overlay,
1265 BlockdevSnapshot snapshot_data = {
1266 .node = (char *) node,
1267 .overlay = (char *) overlay
1269 TransactionAction action = {
1270 .type = TRANSACTION_ACTION_KIND_BLOCKDEV_SNAPSHOT,
1271 .u.blockdev_snapshot.data = &snapshot_data,
1273 blockdev_do_action(&action, errp);
1276 void qmp_blockdev_snapshot_internal_sync(const char *device,
1280 BlockdevSnapshotInternal snapshot = {
1281 .device = (char *) device,
1282 .name = (char *) name
1284 TransactionAction action = {
1285 .type = TRANSACTION_ACTION_KIND_BLOCKDEV_SNAPSHOT_INTERNAL_SYNC,
1286 .u.blockdev_snapshot_internal_sync.data = &snapshot,
1288 blockdev_do_action(&action, errp);
1291 SnapshotInfo *qmp_blockdev_snapshot_delete_internal_sync(const char *device,
1298 BlockDriverState *bs;
1300 AioContext *aio_context;
1301 QEMUSnapshotInfo sn;
1302 Error *local_err = NULL;
1303 SnapshotInfo *info = NULL;
1306 blk = blk_by_name(device);
1308 error_set(errp, ERROR_CLASS_DEVICE_NOT_FOUND,
1309 "Device '%s' not found", device);
1313 aio_context = blk_get_aio_context(blk);
1314 aio_context_acquire(aio_context);
1325 error_setg(errp, "Name or id must be provided");
1326 goto out_aio_context;
1329 if (!blk_is_available(blk)) {
1330 error_setg(errp, "Device '%s' has no medium", device);
1331 goto out_aio_context;
1335 if (bdrv_op_is_blocked(bs, BLOCK_OP_TYPE_INTERNAL_SNAPSHOT_DELETE, errp)) {
1336 goto out_aio_context;
1339 ret = bdrv_snapshot_find_by_id_and_name(bs, id, name, &sn, &local_err);
1341 error_propagate(errp, local_err);
1342 goto out_aio_context;
1346 "Snapshot with id '%s' and name '%s' does not exist on "
1348 STR_OR_NULL(id), STR_OR_NULL(name), device);
1349 goto out_aio_context;
1352 bdrv_snapshot_delete(bs, id, name, &local_err);
1354 error_propagate(errp, local_err);
1355 goto out_aio_context;
1358 aio_context_release(aio_context);
1360 info = g_new0(SnapshotInfo, 1);
1361 info->id = g_strdup(sn.id_str);
1362 info->name = g_strdup(sn.name);
1363 info->date_nsec = sn.date_nsec;
1364 info->date_sec = sn.date_sec;
1365 info->vm_state_size = sn.vm_state_size;
1366 info->vm_clock_nsec = sn.vm_clock_nsec % 1000000000;
1367 info->vm_clock_sec = sn.vm_clock_nsec / 1000000000;
1372 aio_context_release(aio_context);
1377 * block_dirty_bitmap_lookup:
1378 * Return a dirty bitmap (if present), after validating
1379 * the node reference and bitmap names.
1381 * @node: The name of the BDS node to search for bitmaps
1382 * @name: The name of the bitmap to search for
1383 * @pbs: Output pointer for BDS lookup, if desired. Can be NULL.
1384 * @paio: Output pointer for aio_context acquisition, if desired. Can be NULL.
1385 * @errp: Output pointer for error information. Can be NULL.
1387 * @return: A bitmap object on success, or NULL on failure.
1389 static BdrvDirtyBitmap *block_dirty_bitmap_lookup(const char *node,
1391 BlockDriverState **pbs,
1395 BlockDriverState *bs;
1396 BdrvDirtyBitmap *bitmap;
1397 AioContext *aio_context;
1400 error_setg(errp, "Node cannot be NULL");
1404 error_setg(errp, "Bitmap name cannot be NULL");
1407 bs = bdrv_lookup_bs(node, node, NULL);
1409 error_setg(errp, "Node '%s' not found", node);
1413 aio_context = bdrv_get_aio_context(bs);
1414 aio_context_acquire(aio_context);
1416 bitmap = bdrv_find_dirty_bitmap(bs, name);
1418 error_setg(errp, "Dirty bitmap '%s' not found", name);
1426 *paio = aio_context;
1428 aio_context_release(aio_context);
1434 aio_context_release(aio_context);
1438 /* New and old BlockDriverState structs for atomic group operations */
1440 typedef struct BlkActionState BlkActionState;
1444 * Table of operations that define an Action.
1446 * @instance_size: Size of state struct, in bytes.
1447 * @prepare: Prepare the work, must NOT be NULL.
1448 * @commit: Commit the changes, can be NULL.
1449 * @abort: Abort the changes on fail, can be NULL.
1450 * @clean: Clean up resources after all transaction actions have called
1451 * commit() or abort(). Can be NULL.
1453 * Only prepare() may fail. In a single transaction, only one of commit() or
1454 * abort() will be called. clean() will always be called if it is present.
1456 typedef struct BlkActionOps {
1457 size_t instance_size;
1458 void (*prepare)(BlkActionState *common, Error **errp);
1459 void (*commit)(BlkActionState *common);
1460 void (*abort)(BlkActionState *common);
1461 void (*clean)(BlkActionState *common);
1466 * Describes one Action's state within a Transaction.
1468 * @action: QAPI-defined enum identifying which Action to perform.
1469 * @ops: Table of ActionOps this Action can perform.
1470 * @block_job_txn: Transaction which this action belongs to.
1471 * @entry: List membership for all Actions in this Transaction.
1473 * This structure must be arranged as first member in a subclassed type,
1474 * assuming that the compiler will also arrange it to the same offsets as the
1477 struct BlkActionState {
1478 TransactionAction *action;
1479 const BlkActionOps *ops;
1480 BlockJobTxn *block_job_txn;
1481 TransactionProperties *txn_props;
1482 QSIMPLEQ_ENTRY(BlkActionState) entry;
1485 /* internal snapshot private data */
1486 typedef struct InternalSnapshotState {
1487 BlkActionState common;
1488 BlockDriverState *bs;
1489 AioContext *aio_context;
1490 QEMUSnapshotInfo sn;
1492 } InternalSnapshotState;
1495 static int action_check_completion_mode(BlkActionState *s, Error **errp)
1497 if (s->txn_props->completion_mode != ACTION_COMPLETION_MODE_INDIVIDUAL) {
1499 "Action '%s' does not support Transaction property "
1500 "completion-mode = %s",
1501 TransactionActionKind_lookup[s->action->type],
1502 ActionCompletionMode_lookup[s->txn_props->completion_mode]);
1508 static void internal_snapshot_prepare(BlkActionState *common,
1511 Error *local_err = NULL;
1515 BlockDriverState *bs;
1516 QEMUSnapshotInfo old_sn, *sn;
1519 BlockdevSnapshotInternal *internal;
1520 InternalSnapshotState *state;
1523 g_assert(common->action->type ==
1524 TRANSACTION_ACTION_KIND_BLOCKDEV_SNAPSHOT_INTERNAL_SYNC);
1525 internal = common->action->u.blockdev_snapshot_internal_sync.data;
1526 state = DO_UPCAST(InternalSnapshotState, common, common);
1528 /* 1. parse input */
1529 device = internal->device;
1530 name = internal->name;
1532 /* 2. check for validation */
1533 if (action_check_completion_mode(common, errp) < 0) {
1537 blk = blk_by_name(device);
1539 error_set(errp, ERROR_CLASS_DEVICE_NOT_FOUND,
1540 "Device '%s' not found", device);
1544 /* AioContext is released in .clean() */
1545 state->aio_context = blk_get_aio_context(blk);
1546 aio_context_acquire(state->aio_context);
1548 if (!blk_is_available(blk)) {
1549 error_setg(errp, QERR_DEVICE_HAS_NO_MEDIUM, device);
1555 bdrv_drained_begin(bs);
1557 if (bdrv_op_is_blocked(bs, BLOCK_OP_TYPE_INTERNAL_SNAPSHOT, errp)) {
1561 if (bdrv_is_read_only(bs)) {
1562 error_setg(errp, "Device '%s' is read only", device);
1566 if (!bdrv_can_snapshot(bs)) {
1567 error_setg(errp, "Block format '%s' used by device '%s' "
1568 "does not support internal snapshots",
1569 bs->drv->format_name, device);
1573 if (!strlen(name)) {
1574 error_setg(errp, "Name is empty");
1578 /* check whether a snapshot with name exist */
1579 ret = bdrv_snapshot_find_by_id_and_name(bs, NULL, name, &old_sn,
1582 error_propagate(errp, local_err);
1586 "Snapshot with name '%s' already exists on device '%s'",
1591 /* 3. take the snapshot */
1593 pstrcpy(sn->name, sizeof(sn->name), name);
1594 qemu_gettimeofday(&tv);
1595 sn->date_sec = tv.tv_sec;
1596 sn->date_nsec = tv.tv_usec * 1000;
1597 sn->vm_clock_nsec = qemu_clock_get_ns(QEMU_CLOCK_VIRTUAL);
1599 ret1 = bdrv_snapshot_create(bs, sn);
1601 error_setg_errno(errp, -ret1,
1602 "Failed to create snapshot '%s' on device '%s'",
1607 /* 4. succeed, mark a snapshot is created */
1608 state->created = true;
1611 static void internal_snapshot_abort(BlkActionState *common)
1613 InternalSnapshotState *state =
1614 DO_UPCAST(InternalSnapshotState, common, common);
1615 BlockDriverState *bs = state->bs;
1616 QEMUSnapshotInfo *sn = &state->sn;
1617 Error *local_error = NULL;
1619 if (!state->created) {
1623 if (bdrv_snapshot_delete(bs, sn->id_str, sn->name, &local_error) < 0) {
1624 error_reportf_err(local_error,
1625 "Failed to delete snapshot with id '%s' and "
1626 "name '%s' on device '%s' in abort: ",
1627 sn->id_str, sn->name,
1628 bdrv_get_device_name(bs));
1632 static void internal_snapshot_clean(BlkActionState *common)
1634 InternalSnapshotState *state = DO_UPCAST(InternalSnapshotState,
1637 if (state->aio_context) {
1639 bdrv_drained_end(state->bs);
1641 aio_context_release(state->aio_context);
1645 /* external snapshot private data */
1646 typedef struct ExternalSnapshotState {
1647 BlkActionState common;
1648 BlockDriverState *old_bs;
1649 BlockDriverState *new_bs;
1650 AioContext *aio_context;
1651 } ExternalSnapshotState;
1653 static void external_snapshot_prepare(BlkActionState *common,
1657 QDict *options = NULL;
1658 Error *local_err = NULL;
1659 /* Device and node name of the image to generate the snapshot from */
1661 const char *node_name;
1662 /* Reference to the new image (for 'blockdev-snapshot') */
1663 const char *snapshot_ref;
1664 /* File name of the new image (for 'blockdev-snapshot-sync') */
1665 const char *new_image_file;
1666 ExternalSnapshotState *state =
1667 DO_UPCAST(ExternalSnapshotState, common, common);
1668 TransactionAction *action = common->action;
1670 /* 'blockdev-snapshot' and 'blockdev-snapshot-sync' have similar
1671 * purpose but a different set of parameters */
1672 switch (action->type) {
1673 case TRANSACTION_ACTION_KIND_BLOCKDEV_SNAPSHOT:
1675 BlockdevSnapshot *s = action->u.blockdev_snapshot.data;
1677 node_name = s->node;
1678 new_image_file = NULL;
1679 snapshot_ref = s->overlay;
1682 case TRANSACTION_ACTION_KIND_BLOCKDEV_SNAPSHOT_SYNC:
1684 BlockdevSnapshotSync *s = action->u.blockdev_snapshot_sync.data;
1685 device = s->has_device ? s->device : NULL;
1686 node_name = s->has_node_name ? s->node_name : NULL;
1687 new_image_file = s->snapshot_file;
1688 snapshot_ref = NULL;
1692 g_assert_not_reached();
1695 /* start processing */
1696 if (action_check_completion_mode(common, errp) < 0) {
1700 state->old_bs = bdrv_lookup_bs(device, node_name, errp);
1701 if (!state->old_bs) {
1705 /* Acquire AioContext now so any threads operating on old_bs stop */
1706 state->aio_context = bdrv_get_aio_context(state->old_bs);
1707 aio_context_acquire(state->aio_context);
1708 bdrv_drained_begin(state->old_bs);
1710 if (!bdrv_is_inserted(state->old_bs)) {
1711 error_setg(errp, QERR_DEVICE_HAS_NO_MEDIUM, device);
1715 if (bdrv_op_is_blocked(state->old_bs,
1716 BLOCK_OP_TYPE_EXTERNAL_SNAPSHOT, errp)) {
1720 if (!bdrv_is_read_only(state->old_bs)) {
1721 if (bdrv_flush(state->old_bs)) {
1722 error_setg(errp, QERR_IO_ERROR);
1727 if (!bdrv_is_first_non_filter(state->old_bs)) {
1728 error_setg(errp, QERR_FEATURE_DISABLED, "snapshot");
1732 if (action->type == TRANSACTION_ACTION_KIND_BLOCKDEV_SNAPSHOT_SYNC) {
1733 BlockdevSnapshotSync *s = action->u.blockdev_snapshot_sync.data;
1734 const char *format = s->has_format ? s->format : "qcow2";
1735 enum NewImageMode mode;
1736 const char *snapshot_node_name =
1737 s->has_snapshot_node_name ? s->snapshot_node_name : NULL;
1739 if (node_name && !snapshot_node_name) {
1740 error_setg(errp, "New snapshot node name missing");
1744 if (snapshot_node_name &&
1745 bdrv_lookup_bs(snapshot_node_name, snapshot_node_name, NULL)) {
1746 error_setg(errp, "New snapshot node name already in use");
1750 flags = state->old_bs->open_flags;
1751 flags &= ~(BDRV_O_SNAPSHOT | BDRV_O_NO_BACKING | BDRV_O_COPY_ON_READ);
1753 /* create new image w/backing file */
1754 mode = s->has_mode ? s->mode : NEW_IMAGE_MODE_ABSOLUTE_PATHS;
1755 if (mode != NEW_IMAGE_MODE_EXISTING) {
1756 int64_t size = bdrv_getlength(state->old_bs);
1758 error_setg_errno(errp, -size, "bdrv_getlength failed");
1761 bdrv_img_create(new_image_file, format,
1762 state->old_bs->filename,
1763 state->old_bs->drv->format_name,
1764 NULL, size, flags, &local_err, false);
1766 error_propagate(errp, local_err);
1771 options = qdict_new();
1772 if (s->has_snapshot_node_name) {
1773 qdict_put(options, "node-name",
1774 qstring_from_str(snapshot_node_name));
1776 qdict_put(options, "driver", qstring_from_str(format));
1778 flags |= BDRV_O_NO_BACKING;
1781 /* There is no BB attached during bdrv_open(), so we can't set a
1782 * writethrough mode. bdrv_append() will swap the WCE setting so that the
1783 * backing file becomes unconditionally writeback (which is what backing
1784 * files should always be) and the new overlay gets the original setting. */
1785 flags |= BDRV_O_CACHE_WB;
1787 assert(state->new_bs == NULL);
1788 ret = bdrv_open(&state->new_bs, new_image_file, snapshot_ref, options,
1790 /* We will manually add the backing_hd field to the bs later */
1795 if (state->new_bs->blk != NULL) {
1796 error_setg(errp, "The snapshot is already in use by %s",
1797 blk_name(state->new_bs->blk));
1801 if (bdrv_op_is_blocked(state->new_bs, BLOCK_OP_TYPE_EXTERNAL_SNAPSHOT,
1806 if (state->new_bs->backing != NULL) {
1807 error_setg(errp, "The snapshot already has a backing image");
1811 if (!state->new_bs->drv->supports_backing) {
1812 error_setg(errp, "The snapshot does not support backing images");
1816 static void external_snapshot_commit(BlkActionState *common)
1818 ExternalSnapshotState *state =
1819 DO_UPCAST(ExternalSnapshotState, common, common);
1821 bdrv_set_aio_context(state->new_bs, state->aio_context);
1823 /* This removes our old bs and adds the new bs */
1824 bdrv_append(state->new_bs, state->old_bs);
1825 /* We don't need (or want) to use the transactional
1826 * bdrv_reopen_multiple() across all the entries at once, because we
1827 * don't want to abort all of them if one of them fails the reopen */
1828 if (!state->old_bs->copy_on_read) {
1829 bdrv_reopen(state->old_bs, state->old_bs->open_flags & ~BDRV_O_RDWR,
1834 static void external_snapshot_abort(BlkActionState *common)
1836 ExternalSnapshotState *state =
1837 DO_UPCAST(ExternalSnapshotState, common, common);
1838 if (state->new_bs) {
1839 bdrv_unref(state->new_bs);
1843 static void external_snapshot_clean(BlkActionState *common)
1845 ExternalSnapshotState *state =
1846 DO_UPCAST(ExternalSnapshotState, common, common);
1847 if (state->aio_context) {
1848 bdrv_drained_end(state->old_bs);
1849 aio_context_release(state->aio_context);
1853 typedef struct DriveBackupState {
1854 BlkActionState common;
1855 BlockDriverState *bs;
1856 AioContext *aio_context;
1860 static void do_drive_backup(const char *device, const char *target,
1861 bool has_format, const char *format,
1862 enum MirrorSyncMode sync,
1863 bool has_mode, enum NewImageMode mode,
1864 bool has_speed, int64_t speed,
1865 bool has_bitmap, const char *bitmap,
1866 bool has_on_source_error,
1867 BlockdevOnError on_source_error,
1868 bool has_on_target_error,
1869 BlockdevOnError on_target_error,
1870 BlockJobTxn *txn, Error **errp);
1872 static void drive_backup_prepare(BlkActionState *common, Error **errp)
1874 DriveBackupState *state = DO_UPCAST(DriveBackupState, common, common);
1876 DriveBackup *backup;
1877 Error *local_err = NULL;
1879 assert(common->action->type == TRANSACTION_ACTION_KIND_DRIVE_BACKUP);
1880 backup = common->action->u.drive_backup.data;
1882 blk = blk_by_name(backup->device);
1884 error_set(errp, ERROR_CLASS_DEVICE_NOT_FOUND,
1885 "Device '%s' not found", backup->device);
1889 if (!blk_is_available(blk)) {
1890 error_setg(errp, QERR_DEVICE_HAS_NO_MEDIUM, backup->device);
1894 /* AioContext is released in .clean() */
1895 state->aio_context = blk_get_aio_context(blk);
1896 aio_context_acquire(state->aio_context);
1897 bdrv_drained_begin(blk_bs(blk));
1898 state->bs = blk_bs(blk);
1900 do_drive_backup(backup->device, backup->target,
1901 backup->has_format, backup->format,
1903 backup->has_mode, backup->mode,
1904 backup->has_speed, backup->speed,
1905 backup->has_bitmap, backup->bitmap,
1906 backup->has_on_source_error, backup->on_source_error,
1907 backup->has_on_target_error, backup->on_target_error,
1908 common->block_job_txn, &local_err);
1910 error_propagate(errp, local_err);
1914 state->job = state->bs->job;
1917 static void drive_backup_abort(BlkActionState *common)
1919 DriveBackupState *state = DO_UPCAST(DriveBackupState, common, common);
1920 BlockDriverState *bs = state->bs;
1922 /* Only cancel if it's the job we started */
1923 if (bs && bs->job && bs->job == state->job) {
1924 block_job_cancel_sync(bs->job);
1928 static void drive_backup_clean(BlkActionState *common)
1930 DriveBackupState *state = DO_UPCAST(DriveBackupState, common, common);
1932 if (state->aio_context) {
1933 bdrv_drained_end(state->bs);
1934 aio_context_release(state->aio_context);
1938 typedef struct BlockdevBackupState {
1939 BlkActionState common;
1940 BlockDriverState *bs;
1942 AioContext *aio_context;
1943 } BlockdevBackupState;
1945 static void do_blockdev_backup(const char *device, const char *target,
1946 enum MirrorSyncMode sync,
1947 bool has_speed, int64_t speed,
1948 bool has_on_source_error,
1949 BlockdevOnError on_source_error,
1950 bool has_on_target_error,
1951 BlockdevOnError on_target_error,
1952 BlockJobTxn *txn, Error **errp);
1954 static void blockdev_backup_prepare(BlkActionState *common, Error **errp)
1956 BlockdevBackupState *state = DO_UPCAST(BlockdevBackupState, common, common);
1957 BlockdevBackup *backup;
1958 BlockBackend *blk, *target;
1959 Error *local_err = NULL;
1961 assert(common->action->type == TRANSACTION_ACTION_KIND_BLOCKDEV_BACKUP);
1962 backup = common->action->u.blockdev_backup.data;
1964 blk = blk_by_name(backup->device);
1966 error_setg(errp, "Device '%s' not found", backup->device);
1970 if (!blk_is_available(blk)) {
1971 error_setg(errp, QERR_DEVICE_HAS_NO_MEDIUM, backup->device);
1975 target = blk_by_name(backup->target);
1977 error_setg(errp, "Device '%s' not found", backup->target);
1981 /* AioContext is released in .clean() */
1982 state->aio_context = blk_get_aio_context(blk);
1983 if (state->aio_context != blk_get_aio_context(target)) {
1984 state->aio_context = NULL;
1985 error_setg(errp, "Backup between two IO threads is not implemented");
1988 aio_context_acquire(state->aio_context);
1989 state->bs = blk_bs(blk);
1990 bdrv_drained_begin(state->bs);
1992 do_blockdev_backup(backup->device, backup->target,
1994 backup->has_speed, backup->speed,
1995 backup->has_on_source_error, backup->on_source_error,
1996 backup->has_on_target_error, backup->on_target_error,
1997 common->block_job_txn, &local_err);
1999 error_propagate(errp, local_err);
2003 state->job = state->bs->job;
2006 static void blockdev_backup_abort(BlkActionState *common)
2008 BlockdevBackupState *state = DO_UPCAST(BlockdevBackupState, common, common);
2009 BlockDriverState *bs = state->bs;
2011 /* Only cancel if it's the job we started */
2012 if (bs && bs->job && bs->job == state->job) {
2013 block_job_cancel_sync(bs->job);
2017 static void blockdev_backup_clean(BlkActionState *common)
2019 BlockdevBackupState *state = DO_UPCAST(BlockdevBackupState, common, common);
2021 if (state->aio_context) {
2022 bdrv_drained_end(state->bs);
2023 aio_context_release(state->aio_context);
2027 typedef struct BlockDirtyBitmapState {
2028 BlkActionState common;
2029 BdrvDirtyBitmap *bitmap;
2030 BlockDriverState *bs;
2031 AioContext *aio_context;
2034 } BlockDirtyBitmapState;
2036 static void block_dirty_bitmap_add_prepare(BlkActionState *common,
2039 Error *local_err = NULL;
2040 BlockDirtyBitmapAdd *action;
2041 BlockDirtyBitmapState *state = DO_UPCAST(BlockDirtyBitmapState,
2044 if (action_check_completion_mode(common, errp) < 0) {
2048 action = common->action->u.block_dirty_bitmap_add.data;
2049 /* AIO context taken and released within qmp_block_dirty_bitmap_add */
2050 qmp_block_dirty_bitmap_add(action->node, action->name,
2051 action->has_granularity, action->granularity,
2055 state->prepared = true;
2057 error_propagate(errp, local_err);
2061 static void block_dirty_bitmap_add_abort(BlkActionState *common)
2063 BlockDirtyBitmapAdd *action;
2064 BlockDirtyBitmapState *state = DO_UPCAST(BlockDirtyBitmapState,
2067 action = common->action->u.block_dirty_bitmap_add.data;
2068 /* Should not be able to fail: IF the bitmap was added via .prepare(),
2069 * then the node reference and bitmap name must have been valid.
2071 if (state->prepared) {
2072 qmp_block_dirty_bitmap_remove(action->node, action->name, &error_abort);
2076 static void block_dirty_bitmap_clear_prepare(BlkActionState *common,
2079 BlockDirtyBitmapState *state = DO_UPCAST(BlockDirtyBitmapState,
2081 BlockDirtyBitmap *action;
2083 if (action_check_completion_mode(common, errp) < 0) {
2087 action = common->action->u.block_dirty_bitmap_clear.data;
2088 state->bitmap = block_dirty_bitmap_lookup(action->node,
2091 &state->aio_context,
2093 if (!state->bitmap) {
2097 if (bdrv_dirty_bitmap_frozen(state->bitmap)) {
2098 error_setg(errp, "Cannot modify a frozen bitmap");
2100 } else if (!bdrv_dirty_bitmap_enabled(state->bitmap)) {
2101 error_setg(errp, "Cannot clear a disabled bitmap");
2105 bdrv_clear_dirty_bitmap(state->bitmap, &state->backup);
2106 /* AioContext is released in .clean() */
2109 static void block_dirty_bitmap_clear_abort(BlkActionState *common)
2111 BlockDirtyBitmapState *state = DO_UPCAST(BlockDirtyBitmapState,
2114 bdrv_undo_clear_dirty_bitmap(state->bitmap, state->backup);
2117 static void block_dirty_bitmap_clear_commit(BlkActionState *common)
2119 BlockDirtyBitmapState *state = DO_UPCAST(BlockDirtyBitmapState,
2122 hbitmap_free(state->backup);
2125 static void block_dirty_bitmap_clear_clean(BlkActionState *common)
2127 BlockDirtyBitmapState *state = DO_UPCAST(BlockDirtyBitmapState,
2130 if (state->aio_context) {
2131 aio_context_release(state->aio_context);
2135 static void abort_prepare(BlkActionState *common, Error **errp)
2137 error_setg(errp, "Transaction aborted using Abort action");
2140 static void abort_commit(BlkActionState *common)
2142 g_assert_not_reached(); /* this action never succeeds */
2145 static const BlkActionOps actions[] = {
2146 [TRANSACTION_ACTION_KIND_BLOCKDEV_SNAPSHOT] = {
2147 .instance_size = sizeof(ExternalSnapshotState),
2148 .prepare = external_snapshot_prepare,
2149 .commit = external_snapshot_commit,
2150 .abort = external_snapshot_abort,
2151 .clean = external_snapshot_clean,
2153 [TRANSACTION_ACTION_KIND_BLOCKDEV_SNAPSHOT_SYNC] = {
2154 .instance_size = sizeof(ExternalSnapshotState),
2155 .prepare = external_snapshot_prepare,
2156 .commit = external_snapshot_commit,
2157 .abort = external_snapshot_abort,
2158 .clean = external_snapshot_clean,
2160 [TRANSACTION_ACTION_KIND_DRIVE_BACKUP] = {
2161 .instance_size = sizeof(DriveBackupState),
2162 .prepare = drive_backup_prepare,
2163 .abort = drive_backup_abort,
2164 .clean = drive_backup_clean,
2166 [TRANSACTION_ACTION_KIND_BLOCKDEV_BACKUP] = {
2167 .instance_size = sizeof(BlockdevBackupState),
2168 .prepare = blockdev_backup_prepare,
2169 .abort = blockdev_backup_abort,
2170 .clean = blockdev_backup_clean,
2172 [TRANSACTION_ACTION_KIND_ABORT] = {
2173 .instance_size = sizeof(BlkActionState),
2174 .prepare = abort_prepare,
2175 .commit = abort_commit,
2177 [TRANSACTION_ACTION_KIND_BLOCKDEV_SNAPSHOT_INTERNAL_SYNC] = {
2178 .instance_size = sizeof(InternalSnapshotState),
2179 .prepare = internal_snapshot_prepare,
2180 .abort = internal_snapshot_abort,
2181 .clean = internal_snapshot_clean,
2183 [TRANSACTION_ACTION_KIND_BLOCK_DIRTY_BITMAP_ADD] = {
2184 .instance_size = sizeof(BlockDirtyBitmapState),
2185 .prepare = block_dirty_bitmap_add_prepare,
2186 .abort = block_dirty_bitmap_add_abort,
2188 [TRANSACTION_ACTION_KIND_BLOCK_DIRTY_BITMAP_CLEAR] = {
2189 .instance_size = sizeof(BlockDirtyBitmapState),
2190 .prepare = block_dirty_bitmap_clear_prepare,
2191 .commit = block_dirty_bitmap_clear_commit,
2192 .abort = block_dirty_bitmap_clear_abort,
2193 .clean = block_dirty_bitmap_clear_clean,
2198 * Allocate a TransactionProperties structure if necessary, and fill
2199 * that structure with desired defaults if they are unset.
2201 static TransactionProperties *get_transaction_properties(
2202 TransactionProperties *props)
2205 props = g_new0(TransactionProperties, 1);
2208 if (!props->has_completion_mode) {
2209 props->has_completion_mode = true;
2210 props->completion_mode = ACTION_COMPLETION_MODE_INDIVIDUAL;
2217 * 'Atomic' group operations. The operations are performed as a set, and if
2218 * any fail then we roll back all operations in the group.
2220 void qmp_transaction(TransactionActionList *dev_list,
2222 struct TransactionProperties *props,
2225 TransactionActionList *dev_entry = dev_list;
2226 BlockJobTxn *block_job_txn = NULL;
2227 BlkActionState *state, *next;
2228 Error *local_err = NULL;
2230 QSIMPLEQ_HEAD(snap_bdrv_states, BlkActionState) snap_bdrv_states;
2231 QSIMPLEQ_INIT(&snap_bdrv_states);
2233 /* Does this transaction get canceled as a group on failure?
2234 * If not, we don't really need to make a BlockJobTxn.
2236 props = get_transaction_properties(props);
2237 if (props->completion_mode != ACTION_COMPLETION_MODE_INDIVIDUAL) {
2238 block_job_txn = block_job_txn_new();
2241 /* drain all i/o before any operations */
2244 /* We don't do anything in this loop that commits us to the operations */
2245 while (NULL != dev_entry) {
2246 TransactionAction *dev_info = NULL;
2247 const BlkActionOps *ops;
2249 dev_info = dev_entry->value;
2250 dev_entry = dev_entry->next;
2252 assert(dev_info->type < ARRAY_SIZE(actions));
2254 ops = &actions[dev_info->type];
2255 assert(ops->instance_size > 0);
2257 state = g_malloc0(ops->instance_size);
2259 state->action = dev_info;
2260 state->block_job_txn = block_job_txn;
2261 state->txn_props = props;
2262 QSIMPLEQ_INSERT_TAIL(&snap_bdrv_states, state, entry);
2264 state->ops->prepare(state, &local_err);
2266 error_propagate(errp, local_err);
2267 goto delete_and_fail;
2271 QSIMPLEQ_FOREACH(state, &snap_bdrv_states, entry) {
2272 if (state->ops->commit) {
2273 state->ops->commit(state);
2281 /* failure, and it is all-or-none; roll back all operations */
2282 QSIMPLEQ_FOREACH(state, &snap_bdrv_states, entry) {
2283 if (state->ops->abort) {
2284 state->ops->abort(state);
2288 QSIMPLEQ_FOREACH_SAFE(state, &snap_bdrv_states, entry, next) {
2289 if (state->ops->clean) {
2290 state->ops->clean(state);
2295 qapi_free_TransactionProperties(props);
2297 block_job_txn_unref(block_job_txn);
2300 void qmp_eject(const char *device, bool has_force, bool force, Error **errp)
2302 Error *local_err = NULL;
2304 qmp_blockdev_open_tray(device, has_force, force, &local_err);
2306 error_propagate(errp, local_err);
2310 qmp_x_blockdev_remove_medium(device, errp);
2313 void qmp_block_passwd(bool has_device, const char *device,
2314 bool has_node_name, const char *node_name,
2315 const char *password, Error **errp)
2317 Error *local_err = NULL;
2318 BlockDriverState *bs;
2319 AioContext *aio_context;
2321 bs = bdrv_lookup_bs(has_device ? device : NULL,
2322 has_node_name ? node_name : NULL,
2325 error_propagate(errp, local_err);
2329 aio_context = bdrv_get_aio_context(bs);
2330 aio_context_acquire(aio_context);
2332 bdrv_add_key(bs, password, errp);
2334 aio_context_release(aio_context);
2337 void qmp_blockdev_open_tray(const char *device, bool has_force, bool force,
2347 blk = blk_by_name(device);
2349 error_set(errp, ERROR_CLASS_DEVICE_NOT_FOUND,
2350 "Device '%s' not found", device);
2354 if (!blk_dev_has_removable_media(blk)) {
2355 error_setg(errp, "Device '%s' is not removable", device);
2359 if (!blk_dev_has_tray(blk)) {
2360 /* Ignore this command on tray-less devices */
2364 if (blk_dev_is_tray_open(blk)) {
2368 locked = blk_dev_is_medium_locked(blk);
2370 blk_dev_eject_request(blk, force);
2373 if (!locked || force) {
2374 blk_dev_change_media_cb(blk, false);
2378 void qmp_blockdev_close_tray(const char *device, Error **errp)
2382 blk = blk_by_name(device);
2384 error_set(errp, ERROR_CLASS_DEVICE_NOT_FOUND,
2385 "Device '%s' not found", device);
2389 if (!blk_dev_has_removable_media(blk)) {
2390 error_setg(errp, "Device '%s' is not removable", device);
2394 if (!blk_dev_has_tray(blk)) {
2395 /* Ignore this command on tray-less devices */
2399 if (!blk_dev_is_tray_open(blk)) {
2403 blk_dev_change_media_cb(blk, true);
2406 void qmp_x_blockdev_remove_medium(const char *device, Error **errp)
2409 BlockDriverState *bs;
2410 AioContext *aio_context;
2413 blk = blk_by_name(device);
2415 error_set(errp, ERROR_CLASS_DEVICE_NOT_FOUND,
2416 "Device '%s' not found", device);
2420 /* For BBs without a device, we can exchange the BDS tree at will */
2421 has_device = blk_get_attached_dev(blk);
2423 if (has_device && !blk_dev_has_removable_media(blk)) {
2424 error_setg(errp, "Device '%s' is not removable", device);
2428 if (has_device && blk_dev_has_tray(blk) && !blk_dev_is_tray_open(blk)) {
2429 error_setg(errp, "Tray of device '%s' is not open", device);
2438 aio_context = bdrv_get_aio_context(bs);
2439 aio_context_acquire(aio_context);
2441 if (bdrv_op_is_blocked(bs, BLOCK_OP_TYPE_EJECT, errp)) {
2447 if (!blk_dev_has_tray(blk)) {
2448 /* For tray-less devices, blockdev-open-tray is a no-op (or may not be
2449 * called at all); therefore, the medium needs to be ejected here.
2450 * Do it after blk_remove_bs() so blk_is_inserted(blk) returns the @load
2451 * value passed here (i.e. false). */
2452 blk_dev_change_media_cb(blk, false);
2456 aio_context_release(aio_context);
2459 static void qmp_blockdev_insert_anon_medium(const char *device,
2460 BlockDriverState *bs, Error **errp)
2465 blk = blk_by_name(device);
2467 error_set(errp, ERROR_CLASS_DEVICE_NOT_FOUND,
2468 "Device '%s' not found", device);
2472 /* For BBs without a device, we can exchange the BDS tree at will */
2473 has_device = blk_get_attached_dev(blk);
2475 if (has_device && !blk_dev_has_removable_media(blk)) {
2476 error_setg(errp, "Device '%s' is not removable", device);
2480 if (has_device && blk_dev_has_tray(blk) && !blk_dev_is_tray_open(blk)) {
2481 error_setg(errp, "Tray of device '%s' is not open", device);
2486 error_setg(errp, "There already is a medium in device '%s'", device);
2490 blk_insert_bs(blk, bs);
2492 if (!blk_dev_has_tray(blk)) {
2493 /* For tray-less devices, blockdev-close-tray is a no-op (or may not be
2494 * called at all); therefore, the medium needs to be pushed into the
2496 * Do it after blk_insert_bs() so blk_is_inserted(blk) returns the @load
2497 * value passed here (i.e. true). */
2498 blk_dev_change_media_cb(blk, true);
2502 void qmp_x_blockdev_insert_medium(const char *device, const char *node_name,
2505 BlockDriverState *bs;
2507 bs = bdrv_find_node(node_name);
2509 error_setg(errp, "Node '%s' not found", node_name);
2514 error_setg(errp, "Node '%s' is already in use by '%s'", node_name,
2519 qmp_blockdev_insert_anon_medium(device, bs, errp);
2522 void qmp_blockdev_change_medium(const char *device, const char *filename,
2523 bool has_format, const char *format,
2525 BlockdevChangeReadOnlyMode read_only,
2529 BlockDriverState *medium_bs = NULL;
2530 int bdrv_flags, ret;
2532 QDict *options = NULL;
2535 blk = blk_by_name(device);
2537 error_set(errp, ERROR_CLASS_DEVICE_NOT_FOUND,
2538 "Device '%s' not found", device);
2543 blk_update_root_state(blk);
2546 bdrv_flags = blk_get_open_flags_from_root_state(blk);
2547 bdrv_flags &= ~(BDRV_O_TEMPORARY | BDRV_O_SNAPSHOT | BDRV_O_NO_BACKING |
2550 /* Must open the image in writeback mode as long as no BlockBackend is
2551 * attached. The right mode can be set as the final step after changing the
2553 writethrough = !(bdrv_flags & BDRV_O_CACHE_WB);
2554 bdrv_flags |= BDRV_O_CACHE_WB;
2556 if (!has_read_only) {
2557 read_only = BLOCKDEV_CHANGE_READ_ONLY_MODE_RETAIN;
2560 switch (read_only) {
2561 case BLOCKDEV_CHANGE_READ_ONLY_MODE_RETAIN:
2564 case BLOCKDEV_CHANGE_READ_ONLY_MODE_READ_ONLY:
2565 bdrv_flags &= ~BDRV_O_RDWR;
2568 case BLOCKDEV_CHANGE_READ_ONLY_MODE_READ_WRITE:
2569 bdrv_flags |= BDRV_O_RDWR;
2577 options = qdict_new();
2578 qdict_put(options, "driver", qstring_from_str(format));
2582 ret = bdrv_open(&medium_bs, filename, NULL, options, bdrv_flags, errp);
2587 blk_apply_root_state(blk, medium_bs);
2589 bdrv_add_key(medium_bs, NULL, &err);
2591 error_propagate(errp, err);
2595 qmp_blockdev_open_tray(device, false, false, &err);
2597 error_propagate(errp, err);
2601 qmp_x_blockdev_remove_medium(device, &err);
2603 error_propagate(errp, err);
2607 qmp_blockdev_insert_anon_medium(device, medium_bs, &err);
2609 error_propagate(errp, err);
2613 bdrv_set_enable_write_cache(medium_bs, !writethrough);
2615 qmp_blockdev_close_tray(device, errp);
2618 /* If the medium has been inserted, the device has its own reference, so
2619 * ours must be relinquished; and if it has not been inserted successfully,
2620 * the reference must be relinquished anyway */
2621 bdrv_unref(medium_bs);
2624 /* throttling disk I/O limits */
2625 void qmp_block_set_io_throttle(const char *device, int64_t bps, int64_t bps_rd,
2632 bool has_bps_rd_max,
2634 bool has_bps_wr_max,
2638 bool has_iops_rd_max,
2639 int64_t iops_rd_max,
2640 bool has_iops_wr_max,
2641 int64_t iops_wr_max,
2642 bool has_bps_max_length,
2643 int64_t bps_max_length,
2644 bool has_bps_rd_max_length,
2645 int64_t bps_rd_max_length,
2646 bool has_bps_wr_max_length,
2647 int64_t bps_wr_max_length,
2648 bool has_iops_max_length,
2649 int64_t iops_max_length,
2650 bool has_iops_rd_max_length,
2651 int64_t iops_rd_max_length,
2652 bool has_iops_wr_max_length,
2653 int64_t iops_wr_max_length,
2657 const char *group, Error **errp)
2660 BlockDriverState *bs;
2662 AioContext *aio_context;
2664 blk = blk_by_name(device);
2666 error_set(errp, ERROR_CLASS_DEVICE_NOT_FOUND,
2667 "Device '%s' not found", device);
2671 aio_context = blk_get_aio_context(blk);
2672 aio_context_acquire(aio_context);
2676 error_setg(errp, "Device '%s' has no medium", device);
2680 throttle_config_init(&cfg);
2681 cfg.buckets[THROTTLE_BPS_TOTAL].avg = bps;
2682 cfg.buckets[THROTTLE_BPS_READ].avg = bps_rd;
2683 cfg.buckets[THROTTLE_BPS_WRITE].avg = bps_wr;
2685 cfg.buckets[THROTTLE_OPS_TOTAL].avg = iops;
2686 cfg.buckets[THROTTLE_OPS_READ].avg = iops_rd;
2687 cfg.buckets[THROTTLE_OPS_WRITE].avg = iops_wr;
2690 cfg.buckets[THROTTLE_BPS_TOTAL].max = bps_max;
2692 if (has_bps_rd_max) {
2693 cfg.buckets[THROTTLE_BPS_READ].max = bps_rd_max;
2695 if (has_bps_wr_max) {
2696 cfg.buckets[THROTTLE_BPS_WRITE].max = bps_wr_max;
2699 cfg.buckets[THROTTLE_OPS_TOTAL].max = iops_max;
2701 if (has_iops_rd_max) {
2702 cfg.buckets[THROTTLE_OPS_READ].max = iops_rd_max;
2704 if (has_iops_wr_max) {
2705 cfg.buckets[THROTTLE_OPS_WRITE].max = iops_wr_max;
2708 if (has_bps_max_length) {
2709 cfg.buckets[THROTTLE_BPS_TOTAL].burst_length = bps_max_length;
2711 if (has_bps_rd_max_length) {
2712 cfg.buckets[THROTTLE_BPS_READ].burst_length = bps_rd_max_length;
2714 if (has_bps_wr_max_length) {
2715 cfg.buckets[THROTTLE_BPS_WRITE].burst_length = bps_wr_max_length;
2717 if (has_iops_max_length) {
2718 cfg.buckets[THROTTLE_OPS_TOTAL].burst_length = iops_max_length;
2720 if (has_iops_rd_max_length) {
2721 cfg.buckets[THROTTLE_OPS_READ].burst_length = iops_rd_max_length;
2723 if (has_iops_wr_max_length) {
2724 cfg.buckets[THROTTLE_OPS_WRITE].burst_length = iops_wr_max_length;
2727 if (has_iops_size) {
2728 cfg.op_size = iops_size;
2731 if (!throttle_is_valid(&cfg, errp)) {
2735 if (throttle_enabled(&cfg)) {
2736 /* Enable I/O limits if they're not enabled yet, otherwise
2737 * just update the throttling group. */
2738 if (!bs->throttle_state) {
2739 bdrv_io_limits_enable(bs, has_group ? group : device);
2740 } else if (has_group) {
2741 bdrv_io_limits_update_group(bs, group);
2743 /* Set the new throttling configuration */
2744 bdrv_set_io_limits(bs, &cfg);
2745 } else if (bs->throttle_state) {
2746 /* If all throttling settings are set to 0, disable I/O limits */
2747 bdrv_io_limits_disable(bs);
2751 aio_context_release(aio_context);
2754 void qmp_block_dirty_bitmap_add(const char *node, const char *name,
2755 bool has_granularity, uint32_t granularity,
2758 AioContext *aio_context;
2759 BlockDriverState *bs;
2761 if (!name || name[0] == '\0') {
2762 error_setg(errp, "Bitmap name cannot be empty");
2766 bs = bdrv_lookup_bs(node, node, errp);
2771 aio_context = bdrv_get_aio_context(bs);
2772 aio_context_acquire(aio_context);
2774 if (has_granularity) {
2775 if (granularity < 512 || !is_power_of_2(granularity)) {
2776 error_setg(errp, "Granularity must be power of 2 "
2777 "and at least 512");
2781 /* Default to cluster size, if available: */
2782 granularity = bdrv_get_default_bitmap_granularity(bs);
2785 bdrv_create_dirty_bitmap(bs, granularity, name, errp);
2788 aio_context_release(aio_context);
2791 void qmp_block_dirty_bitmap_remove(const char *node, const char *name,
2794 AioContext *aio_context;
2795 BlockDriverState *bs;
2796 BdrvDirtyBitmap *bitmap;
2798 bitmap = block_dirty_bitmap_lookup(node, name, &bs, &aio_context, errp);
2799 if (!bitmap || !bs) {
2803 if (bdrv_dirty_bitmap_frozen(bitmap)) {
2805 "Bitmap '%s' is currently frozen and cannot be removed",
2809 bdrv_dirty_bitmap_make_anon(bitmap);
2810 bdrv_release_dirty_bitmap(bs, bitmap);
2813 aio_context_release(aio_context);
2817 * Completely clear a bitmap, for the purposes of synchronizing a bitmap
2818 * immediately after a full backup operation.
2820 void qmp_block_dirty_bitmap_clear(const char *node, const char *name,
2823 AioContext *aio_context;
2824 BdrvDirtyBitmap *bitmap;
2825 BlockDriverState *bs;
2827 bitmap = block_dirty_bitmap_lookup(node, name, &bs, &aio_context, errp);
2828 if (!bitmap || !bs) {
2832 if (bdrv_dirty_bitmap_frozen(bitmap)) {
2834 "Bitmap '%s' is currently frozen and cannot be modified",
2837 } else if (!bdrv_dirty_bitmap_enabled(bitmap)) {
2839 "Bitmap '%s' is currently disabled and cannot be cleared",
2844 bdrv_clear_dirty_bitmap(bitmap, NULL);
2847 aio_context_release(aio_context);
2850 void hmp_drive_del(Monitor *mon, const QDict *qdict)
2852 const char *id = qdict_get_str(qdict, "id");
2854 BlockDriverState *bs;
2855 AioContext *aio_context;
2856 Error *local_err = NULL;
2858 bs = bdrv_find_node(id);
2860 qmp_x_blockdev_del(false, NULL, true, id, &local_err);
2862 error_report_err(local_err);
2867 blk = blk_by_name(id);
2869 error_report("Device '%s' not found", id);
2873 if (!blk_legacy_dinfo(blk)) {
2874 error_report("Deleting device added with blockdev-add"
2875 " is not supported");
2879 aio_context = blk_get_aio_context(blk);
2880 aio_context_acquire(aio_context);
2884 if (bdrv_op_is_blocked(bs, BLOCK_OP_TYPE_DRIVE_DEL, &local_err)) {
2885 error_report_err(local_err);
2886 aio_context_release(aio_context);
2893 /* Make the BlockBackend and the attached BlockDriverState anonymous */
2894 monitor_remove_blk(blk);
2896 /* If this BlockBackend has a device attached to it, its refcount will be
2897 * decremented when the device is removed; otherwise we have to do so here.
2899 if (blk_get_attached_dev(blk)) {
2900 /* Further I/O must not pause the guest */
2901 blk_set_on_error(blk, BLOCKDEV_ON_ERROR_REPORT,
2902 BLOCKDEV_ON_ERROR_REPORT);
2907 aio_context_release(aio_context);
2910 void qmp_block_resize(bool has_device, const char *device,
2911 bool has_node_name, const char *node_name,
2912 int64_t size, Error **errp)
2914 Error *local_err = NULL;
2915 BlockDriverState *bs;
2916 AioContext *aio_context;
2919 bs = bdrv_lookup_bs(has_device ? device : NULL,
2920 has_node_name ? node_name : NULL,
2923 error_propagate(errp, local_err);
2927 aio_context = bdrv_get_aio_context(bs);
2928 aio_context_acquire(aio_context);
2930 if (!bdrv_is_first_non_filter(bs)) {
2931 error_setg(errp, QERR_FEATURE_DISABLED, "resize");
2936 error_setg(errp, QERR_INVALID_PARAMETER_VALUE, "size", "a >0 size");
2940 if (bdrv_op_is_blocked(bs, BLOCK_OP_TYPE_RESIZE, NULL)) {
2941 error_setg(errp, QERR_DEVICE_IN_USE, device);
2945 /* complete all in-flight operations before resizing the device */
2948 ret = bdrv_truncate(bs, size);
2953 error_setg(errp, QERR_DEVICE_HAS_NO_MEDIUM, device);
2956 error_setg(errp, QERR_UNSUPPORTED);
2959 error_setg(errp, "Device '%s' is read only", device);
2962 error_setg(errp, QERR_DEVICE_IN_USE, device);
2965 error_setg_errno(errp, -ret, "Could not resize");
2970 aio_context_release(aio_context);
2973 static void block_job_cb(void *opaque, int ret)
2975 /* Note that this function may be executed from another AioContext besides
2976 * the QEMU main loop. If you need to access anything that assumes the
2977 * QEMU global mutex, use a BH or introduce a mutex.
2980 BlockDriverState *bs = opaque;
2981 const char *msg = NULL;
2983 trace_block_job_cb(bs, bs->job, ret);
2988 msg = strerror(-ret);
2991 if (block_job_is_cancelled(bs->job)) {
2992 block_job_event_cancelled(bs->job);
2994 block_job_event_completed(bs->job, msg);
2998 void qmp_block_stream(const char *device,
2999 bool has_base, const char *base,
3000 bool has_backing_file, const char *backing_file,
3001 bool has_speed, int64_t speed,
3002 bool has_on_error, BlockdevOnError on_error,
3006 BlockDriverState *bs;
3007 BlockDriverState *base_bs = NULL;
3008 AioContext *aio_context;
3009 Error *local_err = NULL;
3010 const char *base_name = NULL;
3012 if (!has_on_error) {
3013 on_error = BLOCKDEV_ON_ERROR_REPORT;
3016 blk = blk_by_name(device);
3018 error_set(errp, ERROR_CLASS_DEVICE_NOT_FOUND,
3019 "Device '%s' not found", device);
3023 aio_context = blk_get_aio_context(blk);
3024 aio_context_acquire(aio_context);
3026 if (!blk_is_available(blk)) {
3027 error_setg(errp, "Device '%s' has no medium", device);
3032 if (bdrv_op_is_blocked(bs, BLOCK_OP_TYPE_STREAM, errp)) {
3037 base_bs = bdrv_find_backing_image(bs, base);
3038 if (base_bs == NULL) {
3039 error_setg(errp, QERR_BASE_NOT_FOUND, base);
3042 assert(bdrv_get_aio_context(base_bs) == aio_context);
3046 /* if we are streaming the entire chain, the result will have no backing
3047 * file, and specifying one is therefore an error */
3048 if (base_bs == NULL && has_backing_file) {
3049 error_setg(errp, "backing file specified, but streaming the "
3054 /* backing_file string overrides base bs filename */
3055 base_name = has_backing_file ? backing_file : base_name;
3057 stream_start(bs, base_bs, base_name, has_speed ? speed : 0,
3058 on_error, block_job_cb, bs, &local_err);
3060 error_propagate(errp, local_err);
3064 trace_qmp_block_stream(bs, bs->job);
3067 aio_context_release(aio_context);
3070 void qmp_block_commit(const char *device,
3071 bool has_base, const char *base,
3072 bool has_top, const char *top,
3073 bool has_backing_file, const char *backing_file,
3074 bool has_speed, int64_t speed,
3078 BlockDriverState *bs;
3079 BlockDriverState *base_bs, *top_bs;
3080 AioContext *aio_context;
3081 Error *local_err = NULL;
3082 /* This will be part of the QMP command, if/when the
3083 * BlockdevOnError change for blkmirror makes it in
3085 BlockdevOnError on_error = BLOCKDEV_ON_ERROR_REPORT;
3092 * libvirt relies on the DeviceNotFound error class in order to probe for
3093 * live commit feature versions; for this to work, we must make sure to
3094 * perform the device lookup before any generic errors that may occur in a
3095 * scenario in which all optional arguments are omitted. */
3096 blk = blk_by_name(device);
3098 error_set(errp, ERROR_CLASS_DEVICE_NOT_FOUND,
3099 "Device '%s' not found", device);
3103 aio_context = blk_get_aio_context(blk);
3104 aio_context_acquire(aio_context);
3106 if (!blk_is_available(blk)) {
3107 error_setg(errp, "Device '%s' has no medium", device);
3112 if (bdrv_op_is_blocked(bs, BLOCK_OP_TYPE_COMMIT_SOURCE, errp)) {
3116 /* default top_bs is the active layer */
3119 if (has_top && top) {
3120 if (strcmp(bs->filename, top) != 0) {
3121 top_bs = bdrv_find_backing_image(bs, top);
3125 if (top_bs == NULL) {
3126 error_setg(errp, "Top image file %s not found", top ? top : "NULL");
3130 assert(bdrv_get_aio_context(top_bs) == aio_context);
3132 if (has_base && base) {
3133 base_bs = bdrv_find_backing_image(top_bs, base);
3135 base_bs = bdrv_find_base(top_bs);
3138 if (base_bs == NULL) {
3139 error_setg(errp, QERR_BASE_NOT_FOUND, base ? base : "NULL");
3143 assert(bdrv_get_aio_context(base_bs) == aio_context);
3145 if (bdrv_op_is_blocked(base_bs, BLOCK_OP_TYPE_COMMIT_TARGET, errp)) {
3149 /* Do not allow attempts to commit an image into itself */
3150 if (top_bs == base_bs) {
3151 error_setg(errp, "cannot commit an image into itself");
3156 if (has_backing_file) {
3157 error_setg(errp, "'backing-file' specified,"
3158 " but 'top' is the active layer");
3161 commit_active_start(bs, base_bs, speed, on_error, block_job_cb,
3164 commit_start(bs, base_bs, top_bs, speed, on_error, block_job_cb, bs,
3165 has_backing_file ? backing_file : NULL, &local_err);
3167 if (local_err != NULL) {
3168 error_propagate(errp, local_err);
3173 aio_context_release(aio_context);
3176 static void do_drive_backup(const char *device, const char *target,
3177 bool has_format, const char *format,
3178 enum MirrorSyncMode sync,
3179 bool has_mode, enum NewImageMode mode,
3180 bool has_speed, int64_t speed,
3181 bool has_bitmap, const char *bitmap,
3182 bool has_on_source_error,
3183 BlockdevOnError on_source_error,
3184 bool has_on_target_error,
3185 BlockdevOnError on_target_error,
3186 BlockJobTxn *txn, Error **errp)
3189 BlockDriverState *bs;
3190 BlockDriverState *target_bs;
3191 BlockDriverState *source = NULL;
3192 BdrvDirtyBitmap *bmap = NULL;
3193 AioContext *aio_context;
3194 QDict *options = NULL;
3195 Error *local_err = NULL;
3203 if (!has_on_source_error) {
3204 on_source_error = BLOCKDEV_ON_ERROR_REPORT;
3206 if (!has_on_target_error) {
3207 on_target_error = BLOCKDEV_ON_ERROR_REPORT;
3210 mode = NEW_IMAGE_MODE_ABSOLUTE_PATHS;
3213 blk = blk_by_name(device);
3215 error_set(errp, ERROR_CLASS_DEVICE_NOT_FOUND,
3216 "Device '%s' not found", device);
3220 aio_context = blk_get_aio_context(blk);
3221 aio_context_acquire(aio_context);
3223 /* Although backup_run has this check too, we need to use bs->drv below, so
3224 * do an early check redundantly. */
3225 if (!blk_is_available(blk)) {
3226 error_setg(errp, QERR_DEVICE_HAS_NO_MEDIUM, device);
3232 format = mode == NEW_IMAGE_MODE_EXISTING ? NULL : bs->drv->format_name;
3235 /* Early check to avoid creating target */
3236 if (bdrv_op_is_blocked(bs, BLOCK_OP_TYPE_BACKUP_SOURCE, errp)) {
3240 flags = bs->open_flags | BDRV_O_CACHE_WB | BDRV_O_RDWR;
3242 /* See if we have a backing HD we can use to create our new image
3244 if (sync == MIRROR_SYNC_MODE_TOP) {
3245 source = backing_bs(bs);
3247 sync = MIRROR_SYNC_MODE_FULL;
3250 if (sync == MIRROR_SYNC_MODE_NONE) {
3254 size = bdrv_getlength(bs);
3256 error_setg_errno(errp, -size, "bdrv_getlength failed");
3260 if (mode != NEW_IMAGE_MODE_EXISTING) {
3263 bdrv_img_create(target, format, source->filename,
3264 source->drv->format_name, NULL,
3265 size, flags, &local_err, false);
3267 bdrv_img_create(target, format, NULL, NULL, NULL,
3268 size, flags, &local_err, false);
3273 error_propagate(errp, local_err);
3278 options = qdict_new();
3279 qdict_put(options, "driver", qstring_from_str(format));
3283 ret = bdrv_open(&target_bs, target, NULL, options, flags, &local_err);
3285 error_propagate(errp, local_err);
3289 bdrv_set_aio_context(target_bs, aio_context);
3292 bmap = bdrv_find_dirty_bitmap(bs, bitmap);
3294 error_setg(errp, "Bitmap '%s' could not be found", bitmap);
3295 bdrv_unref(target_bs);
3300 backup_start(bs, target_bs, speed, sync, bmap,
3301 on_source_error, on_target_error,
3302 block_job_cb, bs, txn, &local_err);
3303 if (local_err != NULL) {
3304 bdrv_unref(target_bs);
3305 error_propagate(errp, local_err);
3310 aio_context_release(aio_context);
3313 void qmp_drive_backup(const char *device, const char *target,
3314 bool has_format, const char *format,
3315 enum MirrorSyncMode sync,
3316 bool has_mode, enum NewImageMode mode,
3317 bool has_speed, int64_t speed,
3318 bool has_bitmap, const char *bitmap,
3319 bool has_on_source_error, BlockdevOnError on_source_error,
3320 bool has_on_target_error, BlockdevOnError on_target_error,
3323 return do_drive_backup(device, target, has_format, format, sync,
3324 has_mode, mode, has_speed, speed,
3326 has_on_source_error, on_source_error,
3327 has_on_target_error, on_target_error,
3331 BlockDeviceInfoList *qmp_query_named_block_nodes(Error **errp)
3333 return bdrv_named_nodes_list(errp);
3336 void do_blockdev_backup(const char *device, const char *target,
3337 enum MirrorSyncMode sync,
3338 bool has_speed, int64_t speed,
3339 bool has_on_source_error,
3340 BlockdevOnError on_source_error,
3341 bool has_on_target_error,
3342 BlockdevOnError on_target_error,
3343 BlockJobTxn *txn, Error **errp)
3345 BlockBackend *blk, *target_blk;
3346 BlockDriverState *bs;
3347 BlockDriverState *target_bs;
3348 Error *local_err = NULL;
3349 AioContext *aio_context;
3354 if (!has_on_source_error) {
3355 on_source_error = BLOCKDEV_ON_ERROR_REPORT;
3357 if (!has_on_target_error) {
3358 on_target_error = BLOCKDEV_ON_ERROR_REPORT;
3361 blk = blk_by_name(device);
3363 error_setg(errp, "Device '%s' not found", device);
3367 aio_context = blk_get_aio_context(blk);
3368 aio_context_acquire(aio_context);
3370 if (!blk_is_available(blk)) {
3371 error_setg(errp, "Device '%s' has no medium", device);
3376 target_blk = blk_by_name(target);
3378 error_setg(errp, "Device '%s' not found", target);
3382 if (!blk_is_available(target_blk)) {
3383 error_setg(errp, "Device '%s' has no medium", target);
3386 target_bs = blk_bs(target_blk);
3388 bdrv_ref(target_bs);
3389 bdrv_set_aio_context(target_bs, aio_context);
3390 backup_start(bs, target_bs, speed, sync, NULL, on_source_error,
3391 on_target_error, block_job_cb, bs, txn, &local_err);
3392 if (local_err != NULL) {
3393 bdrv_unref(target_bs);
3394 error_propagate(errp, local_err);
3397 aio_context_release(aio_context);
3400 void qmp_blockdev_backup(const char *device, const char *target,
3401 enum MirrorSyncMode sync,
3402 bool has_speed, int64_t speed,
3403 bool has_on_source_error,
3404 BlockdevOnError on_source_error,
3405 bool has_on_target_error,
3406 BlockdevOnError on_target_error,
3409 do_blockdev_backup(device, target, sync, has_speed, speed,
3410 has_on_source_error, on_source_error,
3411 has_on_target_error, on_target_error,
3415 /* Parameter check and block job starting for drive mirroring.
3416 * Caller should hold @device and @target's aio context (must be the same).
3418 static void blockdev_mirror_common(BlockDriverState *bs,
3419 BlockDriverState *target,
3420 bool has_replaces, const char *replaces,
3421 enum MirrorSyncMode sync,
3422 bool has_speed, int64_t speed,
3423 bool has_granularity, uint32_t granularity,
3424 bool has_buf_size, int64_t buf_size,
3425 bool has_on_source_error,
3426 BlockdevOnError on_source_error,
3427 bool has_on_target_error,
3428 BlockdevOnError on_target_error,
3429 bool has_unmap, bool unmap,
3436 if (!has_on_source_error) {
3437 on_source_error = BLOCKDEV_ON_ERROR_REPORT;
3439 if (!has_on_target_error) {
3440 on_target_error = BLOCKDEV_ON_ERROR_REPORT;
3442 if (!has_granularity) {
3445 if (!has_buf_size) {
3452 if (granularity != 0 && (granularity < 512 || granularity > 1048576 * 64)) {
3453 error_setg(errp, QERR_INVALID_PARAMETER_VALUE, "granularity",
3454 "a value in range [512B, 64MB]");
3457 if (granularity & (granularity - 1)) {
3458 error_setg(errp, QERR_INVALID_PARAMETER_VALUE, "granularity",
3463 if (bdrv_op_is_blocked(bs, BLOCK_OP_TYPE_MIRROR_SOURCE, errp)) {
3466 if (bdrv_op_is_blocked(target, BLOCK_OP_TYPE_MIRROR_TARGET, errp)) {
3470 error_setg(errp, "Cannot mirror to an attached block device");
3474 if (!bs->backing && sync == MIRROR_SYNC_MODE_TOP) {
3475 sync = MIRROR_SYNC_MODE_FULL;
3478 /* pass the node name to replace to mirror start since it's loose coupling
3479 * and will allow to check whether the node still exist at mirror completion
3481 mirror_start(bs, target,
3482 has_replaces ? replaces : NULL,
3483 speed, granularity, buf_size, sync,
3484 on_source_error, on_target_error, unmap,
3485 block_job_cb, bs, errp);
3488 void qmp_drive_mirror(const char *device, const char *target,
3489 bool has_format, const char *format,
3490 bool has_node_name, const char *node_name,
3491 bool has_replaces, const char *replaces,
3492 enum MirrorSyncMode sync,
3493 bool has_mode, enum NewImageMode mode,
3494 bool has_speed, int64_t speed,
3495 bool has_granularity, uint32_t granularity,
3496 bool has_buf_size, int64_t buf_size,
3497 bool has_on_source_error, BlockdevOnError on_source_error,
3498 bool has_on_target_error, BlockdevOnError on_target_error,
3499 bool has_unmap, bool unmap,
3502 BlockDriverState *bs;
3504 BlockDriverState *source, *target_bs;
3505 AioContext *aio_context;
3506 Error *local_err = NULL;
3507 QDict *options = NULL;
3512 blk = blk_by_name(device);
3514 error_set(errp, ERROR_CLASS_DEVICE_NOT_FOUND,
3515 "Device '%s' not found", device);
3519 aio_context = blk_get_aio_context(blk);
3520 aio_context_acquire(aio_context);
3522 if (!blk_is_available(blk)) {
3523 error_setg(errp, QERR_DEVICE_HAS_NO_MEDIUM, device);
3528 mode = NEW_IMAGE_MODE_ABSOLUTE_PATHS;
3532 format = mode == NEW_IMAGE_MODE_EXISTING ? NULL : bs->drv->format_name;
3535 flags = bs->open_flags | BDRV_O_CACHE_WB | BDRV_O_RDWR;
3536 source = backing_bs(bs);
3537 if (!source && sync == MIRROR_SYNC_MODE_TOP) {
3538 sync = MIRROR_SYNC_MODE_FULL;
3540 if (sync == MIRROR_SYNC_MODE_NONE) {
3544 size = bdrv_getlength(bs);
3546 error_setg_errno(errp, -size, "bdrv_getlength failed");
3551 BlockDriverState *to_replace_bs;
3552 AioContext *replace_aio_context;
3553 int64_t replace_size;
3555 if (!has_node_name) {
3556 error_setg(errp, "a node-name must be provided when replacing a"
3557 " named node of the graph");
3561 to_replace_bs = check_to_replace_node(bs, replaces, &local_err);
3563 if (!to_replace_bs) {
3564 error_propagate(errp, local_err);
3568 replace_aio_context = bdrv_get_aio_context(to_replace_bs);
3569 aio_context_acquire(replace_aio_context);
3570 replace_size = bdrv_getlength(to_replace_bs);
3571 aio_context_release(replace_aio_context);
3573 if (size != replace_size) {
3574 error_setg(errp, "cannot replace image with a mirror image of "
3580 if ((sync == MIRROR_SYNC_MODE_FULL || !source)
3581 && mode != NEW_IMAGE_MODE_EXISTING)
3583 /* create new image w/o backing file */
3585 bdrv_img_create(target, format,
3586 NULL, NULL, NULL, size, flags, &local_err, false);
3589 case NEW_IMAGE_MODE_EXISTING:
3591 case NEW_IMAGE_MODE_ABSOLUTE_PATHS:
3592 /* create new image with backing file */
3593 bdrv_img_create(target, format,
3595 source->drv->format_name,
3596 NULL, size, flags, &local_err, false);
3604 error_propagate(errp, local_err);
3608 options = qdict_new();
3609 if (has_node_name) {
3610 qdict_put(options, "node-name", qstring_from_str(node_name));
3613 qdict_put(options, "driver", qstring_from_str(format));
3616 /* Mirroring takes care of copy-on-write using the source's backing
3620 ret = bdrv_open(&target_bs, target, NULL, options,
3621 flags | BDRV_O_NO_BACKING, &local_err);
3623 error_propagate(errp, local_err);
3627 bdrv_set_aio_context(target_bs, aio_context);
3629 blockdev_mirror_common(bs, target_bs,
3630 has_replaces, replaces, sync,
3632 has_granularity, granularity,
3633 has_buf_size, buf_size,
3634 has_on_source_error, on_source_error,
3635 has_on_target_error, on_target_error,
3639 error_propagate(errp, local_err);
3640 bdrv_unref(target_bs);
3643 aio_context_release(aio_context);
3646 void qmp_blockdev_mirror(const char *device, const char *target,
3647 bool has_replaces, const char *replaces,
3648 MirrorSyncMode sync,
3649 bool has_speed, int64_t speed,
3650 bool has_granularity, uint32_t granularity,
3651 bool has_buf_size, int64_t buf_size,
3652 bool has_on_source_error,
3653 BlockdevOnError on_source_error,
3654 bool has_on_target_error,
3655 BlockdevOnError on_target_error,
3658 BlockDriverState *bs;
3660 BlockDriverState *target_bs;
3661 AioContext *aio_context;
3662 Error *local_err = NULL;
3664 blk = blk_by_name(device);
3666 error_setg(errp, "Device '%s' not found", device);
3672 error_setg(errp, "Device '%s' has no media", device);
3676 target_bs = bdrv_lookup_bs(target, target, errp);
3681 aio_context = bdrv_get_aio_context(bs);
3682 aio_context_acquire(aio_context);
3684 bdrv_ref(target_bs);
3685 bdrv_set_aio_context(target_bs, aio_context);
3687 blockdev_mirror_common(bs, target_bs,
3688 has_replaces, replaces, sync,
3690 has_granularity, granularity,
3691 has_buf_size, buf_size,
3692 has_on_source_error, on_source_error,
3693 has_on_target_error, on_target_error,
3697 error_propagate(errp, local_err);
3698 bdrv_unref(target_bs);
3701 aio_context_release(aio_context);
3704 /* Get the block job for a given device name and acquire its AioContext */
3705 static BlockJob *find_block_job(const char *device, AioContext **aio_context,
3709 BlockDriverState *bs;
3711 *aio_context = NULL;
3713 blk = blk_by_name(device);
3718 *aio_context = blk_get_aio_context(blk);
3719 aio_context_acquire(*aio_context);
3721 if (!blk_is_available(blk)) {
3733 error_set(errp, ERROR_CLASS_DEVICE_NOT_ACTIVE,
3734 "No active block job on device '%s'", device);
3736 aio_context_release(*aio_context);
3737 *aio_context = NULL;
3742 void qmp_block_job_set_speed(const char *device, int64_t speed, Error **errp)
3744 AioContext *aio_context;
3745 BlockJob *job = find_block_job(device, &aio_context, errp);
3751 block_job_set_speed(job, speed, errp);
3752 aio_context_release(aio_context);
3755 void qmp_block_job_cancel(const char *device,
3756 bool has_force, bool force, Error **errp)
3758 AioContext *aio_context;
3759 BlockJob *job = find_block_job(device, &aio_context, errp);
3769 if (job->user_paused && !force) {
3770 error_setg(errp, "The block job for device '%s' is currently paused",
3775 trace_qmp_block_job_cancel(job);
3776 block_job_cancel(job);
3778 aio_context_release(aio_context);
3781 void qmp_block_job_pause(const char *device, Error **errp)
3783 AioContext *aio_context;
3784 BlockJob *job = find_block_job(device, &aio_context, errp);
3786 if (!job || job->user_paused) {
3790 job->user_paused = true;
3791 trace_qmp_block_job_pause(job);
3792 block_job_pause(job);
3793 aio_context_release(aio_context);
3796 void qmp_block_job_resume(const char *device, Error **errp)
3798 AioContext *aio_context;
3799 BlockJob *job = find_block_job(device, &aio_context, errp);
3801 if (!job || !job->user_paused) {
3805 job->user_paused = false;
3806 trace_qmp_block_job_resume(job);
3807 block_job_resume(job);
3808 aio_context_release(aio_context);
3811 void qmp_block_job_complete(const char *device, Error **errp)
3813 AioContext *aio_context;
3814 BlockJob *job = find_block_job(device, &aio_context, errp);
3820 trace_qmp_block_job_complete(job);
3821 block_job_complete(job, errp);
3822 aio_context_release(aio_context);
3825 void qmp_change_backing_file(const char *device,
3826 const char *image_node_name,
3827 const char *backing_file,
3831 BlockDriverState *bs = NULL;
3832 AioContext *aio_context;
3833 BlockDriverState *image_bs = NULL;
3834 Error *local_err = NULL;
3839 blk = blk_by_name(device);
3841 error_set(errp, ERROR_CLASS_DEVICE_NOT_FOUND,
3842 "Device '%s' not found", device);
3846 aio_context = blk_get_aio_context(blk);
3847 aio_context_acquire(aio_context);
3849 if (!blk_is_available(blk)) {
3850 error_setg(errp, "Device '%s' has no medium", device);
3855 image_bs = bdrv_lookup_bs(NULL, image_node_name, &local_err);
3857 error_propagate(errp, local_err);
3862 error_setg(errp, "image file not found");
3866 if (bdrv_find_base(image_bs) == image_bs) {
3867 error_setg(errp, "not allowing backing file change on an image "
3868 "without a backing file");
3872 /* even though we are not necessarily operating on bs, we need it to
3873 * determine if block ops are currently prohibited on the chain */
3874 if (bdrv_op_is_blocked(bs, BLOCK_OP_TYPE_CHANGE, errp)) {
3878 /* final sanity check */
3879 if (!bdrv_chain_contains(bs, image_bs)) {
3880 error_setg(errp, "'%s' and image file are not in the same chain",
3885 /* if not r/w, reopen to make r/w */
3886 open_flags = image_bs->open_flags;
3887 ro = bdrv_is_read_only(image_bs);
3890 bdrv_reopen(image_bs, open_flags | BDRV_O_RDWR, &local_err);
3892 error_propagate(errp, local_err);
3897 ret = bdrv_change_backing_file(image_bs, backing_file,
3898 image_bs->drv ? image_bs->drv->format_name : "");
3901 error_setg_errno(errp, -ret, "Could not change backing file to '%s'",
3903 /* don't exit here, so we can try to restore open flags if
3908 bdrv_reopen(image_bs, open_flags, &local_err);
3910 error_propagate(errp, local_err); /* will preserve prior errp */
3915 aio_context_release(aio_context);
3918 void hmp_drive_add_node(Monitor *mon, const char *optstr)
3922 Error *local_err = NULL;
3924 opts = qemu_opts_parse_noisily(&qemu_drive_opts, optstr, false);
3929 qdict = qemu_opts_to_qdict(opts, NULL);
3931 if (!qdict_get_try_str(qdict, "node-name")) {
3933 error_report("'node-name' needs to be specified");
3937 BlockDriverState *bs = bds_tree_init(qdict, &local_err);
3939 error_report_err(local_err);
3943 QTAILQ_INSERT_TAIL(&monitor_bdrv_states, bs, monitor_list);
3946 qemu_opts_del(opts);
3949 void qmp_blockdev_add(BlockdevOptions *options, Error **errp)
3951 QmpOutputVisitor *ov = qmp_output_visitor_new();
3952 BlockDriverState *bs;
3953 BlockBackend *blk = NULL;
3956 Error *local_err = NULL;
3958 /* TODO Sort it out in raw-posix and drive_new(): Reject aio=native with
3959 * cache.direct=false instead of silently switching to aio=threads, except
3960 * when called from drive_new().
3962 * For now, simply forbidding the combination for all drivers will do. */
3963 if (options->has_aio && options->aio == BLOCKDEV_AIO_OPTIONS_NATIVE) {
3964 bool direct = options->has_cache &&
3965 options->cache->has_direct &&
3966 options->cache->direct;
3968 error_setg(errp, "aio=native requires cache.direct=true");
3973 visit_type_BlockdevOptions(qmp_output_get_visitor(ov), NULL, &options,
3976 error_propagate(errp, local_err);
3980 obj = qmp_output_get_qobject(ov);
3981 qdict = qobject_to_qdict(obj);
3983 qdict_flatten(qdict);
3985 if (options->has_id) {
3986 blk = blockdev_init(NULL, qdict, &local_err);
3988 error_propagate(errp, local_err);
3994 if (!qdict_get_try_str(qdict, "node-name")) {
3995 error_setg(errp, "'id' and/or 'node-name' need to be specified for "
4000 bs = bds_tree_init(qdict, errp);
4005 QTAILQ_INSERT_TAIL(&monitor_bdrv_states, bs, monitor_list);
4008 if (bs && bdrv_key_required(bs)) {
4010 monitor_remove_blk(blk);
4013 QTAILQ_REMOVE(&monitor_bdrv_states, bs, monitor_list);
4016 error_setg(errp, "blockdev-add doesn't support encrypted devices");
4021 qmp_output_visitor_cleanup(ov);
4024 void qmp_x_blockdev_del(bool has_id, const char *id,
4025 bool has_node_name, const char *node_name, Error **errp)
4027 AioContext *aio_context;
4029 BlockDriverState *bs;
4031 if (has_id && has_node_name) {
4032 error_setg(errp, "Only one of id and node-name must be specified");
4034 } else if (!has_id && !has_node_name) {
4035 error_setg(errp, "No block device specified");
4040 /* blk_by_name() never returns a BB that is not owned by the monitor */
4041 blk = blk_by_name(id);
4043 error_setg(errp, "Cannot find block backend %s", id);
4046 if (blk_get_refcnt(blk) > 1) {
4047 error_setg(errp, "Block backend %s is in use", id);
4051 aio_context = blk_get_aio_context(blk);
4053 bs = bdrv_find_node(node_name);
4055 error_setg(errp, "Cannot find node %s", node_name);
4060 error_setg(errp, "Node %s is in use by %s",
4061 node_name, blk_name(blk));
4064 aio_context = bdrv_get_aio_context(bs);
4067 aio_context_acquire(aio_context);
4070 if (bdrv_op_is_blocked(bs, BLOCK_OP_TYPE_DRIVE_DEL, errp)) {
4074 if (!blk && !bs->monitor_list.tqe_prev) {
4075 error_setg(errp, "Node %s is not owned by the monitor",
4080 if (bs->refcnt > 1) {
4081 error_setg(errp, "Block device %s is in use",
4082 bdrv_get_device_or_node_name(bs));
4088 monitor_remove_blk(blk);
4091 QTAILQ_REMOVE(&monitor_bdrv_states, bs, monitor_list);
4096 aio_context_release(aio_context);
4099 BlockJobInfoList *qmp_query_block_jobs(Error **errp)
4101 BlockJobInfoList *head = NULL, **p_next = &head;
4102 BlockDriverState *bs;
4104 for (bs = bdrv_next(NULL); bs; bs = bdrv_next(bs)) {
4105 AioContext *aio_context = bdrv_get_aio_context(bs);
4107 aio_context_acquire(aio_context);
4110 BlockJobInfoList *elem = g_new0(BlockJobInfoList, 1);
4111 elem->value = block_job_query(bs->job);
4113 p_next = &elem->next;
4116 aio_context_release(aio_context);
4122 QemuOptsList qemu_common_drive_opts = {
4124 .head = QTAILQ_HEAD_INITIALIZER(qemu_common_drive_opts.head),
4128 .type = QEMU_OPT_BOOL,
4129 .help = "enable/disable snapshot mode",
4132 .type = QEMU_OPT_STRING,
4133 .help = "discard operation (ignore/off, unmap/on)",
4136 .type = QEMU_OPT_STRING,
4137 .help = "host AIO implementation (threads, native)",
4139 .name = BDRV_OPT_CACHE_WB,
4140 .type = QEMU_OPT_BOOL,
4141 .help = "Enable writeback mode",
4144 .type = QEMU_OPT_STRING,
4145 .help = "disk format (raw, qcow2, ...)",
4148 .type = QEMU_OPT_STRING,
4149 .help = "read error action",
4152 .type = QEMU_OPT_STRING,
4153 .help = "write error action",
4155 .name = "read-only",
4156 .type = QEMU_OPT_BOOL,
4157 .help = "open drive file as read-only",
4159 .name = "throttling.iops-total",
4160 .type = QEMU_OPT_NUMBER,
4161 .help = "limit total I/O operations per second",
4163 .name = "throttling.iops-read",
4164 .type = QEMU_OPT_NUMBER,
4165 .help = "limit read operations per second",
4167 .name = "throttling.iops-write",
4168 .type = QEMU_OPT_NUMBER,
4169 .help = "limit write operations per second",
4171 .name = "throttling.bps-total",
4172 .type = QEMU_OPT_NUMBER,
4173 .help = "limit total bytes per second",
4175 .name = "throttling.bps-read",
4176 .type = QEMU_OPT_NUMBER,
4177 .help = "limit read bytes per second",
4179 .name = "throttling.bps-write",
4180 .type = QEMU_OPT_NUMBER,
4181 .help = "limit write bytes per second",
4183 .name = "throttling.iops-total-max",
4184 .type = QEMU_OPT_NUMBER,
4185 .help = "I/O operations burst",
4187 .name = "throttling.iops-read-max",
4188 .type = QEMU_OPT_NUMBER,
4189 .help = "I/O operations read burst",
4191 .name = "throttling.iops-write-max",
4192 .type = QEMU_OPT_NUMBER,
4193 .help = "I/O operations write burst",
4195 .name = "throttling.bps-total-max",
4196 .type = QEMU_OPT_NUMBER,
4197 .help = "total bytes burst",
4199 .name = "throttling.bps-read-max",
4200 .type = QEMU_OPT_NUMBER,
4201 .help = "total bytes read burst",
4203 .name = "throttling.bps-write-max",
4204 .type = QEMU_OPT_NUMBER,
4205 .help = "total bytes write burst",
4207 .name = "throttling.iops-total-max-length",
4208 .type = QEMU_OPT_NUMBER,
4209 .help = "length of the iops-total-max burst period, in seconds",
4211 .name = "throttling.iops-read-max-length",
4212 .type = QEMU_OPT_NUMBER,
4213 .help = "length of the iops-read-max burst period, in seconds",
4215 .name = "throttling.iops-write-max-length",
4216 .type = QEMU_OPT_NUMBER,
4217 .help = "length of the iops-write-max burst period, in seconds",
4219 .name = "throttling.bps-total-max-length",
4220 .type = QEMU_OPT_NUMBER,
4221 .help = "length of the bps-total-max burst period, in seconds",
4223 .name = "throttling.bps-read-max-length",
4224 .type = QEMU_OPT_NUMBER,
4225 .help = "length of the bps-read-max burst period, in seconds",
4227 .name = "throttling.bps-write-max-length",
4228 .type = QEMU_OPT_NUMBER,
4229 .help = "length of the bps-write-max burst period, in seconds",
4231 .name = "throttling.iops-size",
4232 .type = QEMU_OPT_NUMBER,
4233 .help = "when limiting by iops max size of an I/O in bytes",
4235 .name = "throttling.group",
4236 .type = QEMU_OPT_STRING,
4237 .help = "name of the block throttling group",
4239 .name = "copy-on-read",
4240 .type = QEMU_OPT_BOOL,
4241 .help = "copy read data from backing file into image file",
4243 .name = "detect-zeroes",
4244 .type = QEMU_OPT_STRING,
4245 .help = "try to optimize zero writes (off, on, unmap)",
4247 .name = "stats-account-invalid",
4248 .type = QEMU_OPT_BOOL,
4249 .help = "whether to account for invalid I/O operations "
4250 "in the statistics",
4252 .name = "stats-account-failed",
4253 .type = QEMU_OPT_BOOL,
4254 .help = "whether to account for failed I/O operations "
4255 "in the statistics",
4257 { /* end of list */ }
4261 static QemuOptsList qemu_root_bds_opts = {
4263 .head = QTAILQ_HEAD_INITIALIZER(qemu_root_bds_opts.head),
4267 .type = QEMU_OPT_STRING,
4268 .help = "discard operation (ignore/off, unmap/on)",
4271 .type = QEMU_OPT_STRING,
4272 .help = "host AIO implementation (threads, native)",
4274 .name = "read-only",
4275 .type = QEMU_OPT_BOOL,
4276 .help = "open drive file as read-only",
4278 .name = "copy-on-read",
4279 .type = QEMU_OPT_BOOL,
4280 .help = "copy read data from backing file into image file",
4282 .name = "detect-zeroes",
4283 .type = QEMU_OPT_STRING,
4284 .help = "try to optimize zero writes (off, on, unmap)",
4286 { /* end of list */ }
4290 QemuOptsList qemu_drive_opts = {
4292 .head = QTAILQ_HEAD_INITIALIZER(qemu_drive_opts.head),
4295 * no elements => accept any params
4296 * validation will happen later
4298 { /* end of list */ }