2 * QEMU host block devices
4 * Copyright (c) 2003-2008 Fabrice Bellard
6 * This work is licensed under the terms of the GNU GPL, version 2 or
7 * later. See the COPYING file in the top-level directory.
9 * This file incorporates work covered by the following copyright and
12 * Copyright (c) 2003-2008 Fabrice Bellard
14 * Permission is hereby granted, free of charge, to any person obtaining a copy
15 * of this software and associated documentation files (the "Software"), to deal
16 * in the Software without restriction, including without limitation the rights
17 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
18 * copies of the Software, and to permit persons to whom the Software is
19 * furnished to do so, subject to the following conditions:
21 * The above copyright notice and this permission notice shall be included in
22 * all copies or substantial portions of the Software.
24 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
25 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
26 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
27 * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
28 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
29 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
33 #include "sysemu/block-backend.h"
34 #include "sysemu/blockdev.h"
35 #include "hw/block/block.h"
36 #include "block/blockjob.h"
37 #include "block/throttle-groups.h"
38 #include "monitor/monitor.h"
39 #include "qemu/error-report.h"
40 #include "qemu/option.h"
41 #include "qemu/config-file.h"
42 #include "qapi/qmp/types.h"
43 #include "qapi-visit.h"
44 #include "qapi/qmp/qerror.h"
45 #include "qapi/qmp-output-visitor.h"
46 #include "qapi/util.h"
47 #include "sysemu/sysemu.h"
48 #include "block/block_int.h"
49 #include "qmp-commands.h"
51 #include "sysemu/arch_init.h"
54 #include "tizen/src/util/exported_strings.h"
57 static const char *const if_name[IF_COUNT] = {
61 [IF_FLOPPY] = "floppy",
62 [IF_PFLASH] = "pflash",
65 [IF_VIRTIO] = "virtio",
69 static int if_max_devs[IF_COUNT] = {
71 * Do not change these numbers! They govern how drive option
72 * index maps to unit and bus. That mapping is ABI.
74 * All controllers used to imlement if=T drives need to support
75 * if_max_devs[T] units, for any T with if_max_devs[T] != 0.
76 * Otherwise, some index values map to "impossible" bus, unit
79 * For instance, if you change [IF_SCSI] to 255, -drive
80 * if=scsi,index=12 no longer means bus=1,unit=5, but
81 * bus=0,unit=12. With an lsi53c895a controller (7 units max),
82 * the drive can't be set up. Regression.
89 * Boards may call this to offer board-by-board overrides
90 * of the default, global values.
92 void override_max_devs(BlockInterfaceType type, int max_devs)
101 for (blk = blk_next(NULL); blk; blk = blk_next(blk)) {
102 dinfo = blk_legacy_dinfo(blk);
103 if (dinfo->type == type) {
104 fprintf(stderr, "Cannot override units-per-bus property of"
105 " the %s interface, because a drive of that type has"
106 " already been added.\n", if_name[type]);
107 g_assert_not_reached();
111 if_max_devs[type] = max_devs;
115 * We automatically delete the drive when a device using it gets
116 * unplugged. Questionable feature, but we can't just drop it.
117 * Device models call blockdev_mark_auto_del() to schedule the
118 * automatic deletion, and generic qdev code calls blockdev_auto_del()
119 * when deletion is actually safe.
121 void blockdev_mark_auto_del(BlockBackend *blk)
123 DriveInfo *dinfo = blk_legacy_dinfo(blk);
124 BlockDriverState *bs = blk_bs(blk);
125 AioContext *aio_context;
131 aio_context = bdrv_get_aio_context(bs);
132 aio_context_acquire(aio_context);
135 block_job_cancel(bs->job);
138 aio_context_release(aio_context);
143 void blockdev_auto_del(BlockBackend *blk)
145 DriveInfo *dinfo = blk_legacy_dinfo(blk);
147 if (dinfo && dinfo->auto_del) {
153 * Returns the current mapping of how many units per bus
154 * a particular interface can support.
156 * A positive integer indicates n units per bus.
157 * 0 implies the mapping has not been established.
158 * -1 indicates an invalid BlockInterfaceType was given.
160 int drive_get_max_devs(BlockInterfaceType type)
162 if (type >= IF_IDE && type < IF_COUNT) {
163 return if_max_devs[type];
169 static int drive_index_to_bus_id(BlockInterfaceType type, int index)
171 int max_devs = if_max_devs[type];
172 return max_devs ? index / max_devs : 0;
175 static int drive_index_to_unit_id(BlockInterfaceType type, int index)
177 int max_devs = if_max_devs[type];
178 return max_devs ? index % max_devs : index;
181 QemuOpts *drive_def(const char *optstr)
183 return qemu_opts_parse_noisily(qemu_find_opts("drive"), optstr, false);
186 QemuOpts *drive_add(BlockInterfaceType type, int index, const char *file,
191 opts = drive_def(optstr);
195 if (type != IF_DEFAULT) {
196 qemu_opt_set(opts, "if", if_name[type], &error_abort);
199 qemu_opt_set_number(opts, "index", index, &error_abort);
202 qemu_opt_set(opts, "file", file, &error_abort);
206 DriveInfo *drive_get(BlockInterfaceType type, int bus, int unit)
211 for (blk = blk_next(NULL); blk; blk = blk_next(blk)) {
212 dinfo = blk_legacy_dinfo(blk);
213 if (dinfo && dinfo->type == type
214 && dinfo->bus == bus && dinfo->unit == unit) {
222 bool drive_check_orphaned(void)
228 for (blk = blk_next(NULL); blk; blk = blk_next(blk)) {
229 dinfo = blk_legacy_dinfo(blk);
230 /* If dinfo->bdrv->dev is NULL, it has no device attached. */
231 /* Unless this is a default drive, this may be an oversight. */
232 if (!blk_get_attached_dev(blk) && !dinfo->is_default &&
233 dinfo->type != IF_NONE) {
234 fprintf(stderr, "Warning: Orphaned drive without device: "
235 "id=%s,file=%s,if=%s,bus=%d,unit=%d\n",
236 blk_name(blk), blk_bs(blk)->filename, if_name[dinfo->type],
237 dinfo->bus, dinfo->unit);
245 DriveInfo *drive_get_by_index(BlockInterfaceType type, int index)
247 return drive_get(type,
248 drive_index_to_bus_id(type, index),
249 drive_index_to_unit_id(type, index));
252 int drive_get_max_bus(BlockInterfaceType type)
259 for (blk = blk_next(NULL); blk; blk = blk_next(blk)) {
260 dinfo = blk_legacy_dinfo(blk);
261 if (dinfo && dinfo->type == type && dinfo->bus > max_bus) {
262 max_bus = dinfo->bus;
268 /* Get a block device. This should only be used for single-drive devices
269 (e.g. SD/Floppy/MTD). Multi-disk devices (scsi/ide) should use the
271 DriveInfo *drive_get_next(BlockInterfaceType type)
273 static int next_block_unit[IF_COUNT];
275 return drive_get(type, 0, next_block_unit[type]++);
278 static void bdrv_format_print(void *opaque, const char *name)
280 error_printf(" %s", name);
285 BlockDriverState *bs;
288 static void bdrv_put_ref_bh(void *opaque)
290 BDRVPutRefBH *s = opaque;
293 qemu_bh_delete(s->bh);
298 * Release a BDS reference in a BH
300 * It is not safe to use bdrv_unref() from a callback function when the callers
301 * still need the BlockDriverState. In such cases we schedule a BH to release
304 static void bdrv_put_ref_bh_schedule(BlockDriverState *bs)
308 s = g_new(BDRVPutRefBH, 1);
309 s->bh = qemu_bh_new(bdrv_put_ref_bh, s);
311 qemu_bh_schedule(s->bh);
314 static int parse_block_error_action(const char *buf, bool is_read, Error **errp)
316 if (!strcmp(buf, "ignore")) {
317 return BLOCKDEV_ON_ERROR_IGNORE;
318 } else if (!is_read && !strcmp(buf, "enospc")) {
319 return BLOCKDEV_ON_ERROR_ENOSPC;
320 } else if (!strcmp(buf, "stop")) {
321 return BLOCKDEV_ON_ERROR_STOP;
322 } else if (!strcmp(buf, "report")) {
323 return BLOCKDEV_ON_ERROR_REPORT;
325 error_setg(errp, "'%s' invalid %s error action",
326 buf, is_read ? "read" : "write");
331 static bool check_throttle_config(ThrottleConfig *cfg, Error **errp)
333 if (throttle_conflicting(cfg)) {
334 error_setg(errp, "bps/iops/max total values and read/write values"
335 " cannot be used at the same time");
339 if (!throttle_is_valid(cfg)) {
340 error_setg(errp, "bps/iops/maxs values must be 0 or greater");
347 typedef enum { MEDIA_DISK, MEDIA_CDROM } DriveMediaType;
349 /* Takes the ownership of bs_opts */
350 static BlockBackend *blockdev_init(const char *file, QDict *bs_opts,
356 int on_read_error, on_write_error;
358 BlockDriverState *bs;
365 bool has_driver_specific_opts;
366 BlockdevDetectZeroesOptions detect_zeroes;
367 const char *throttling_group;
369 /* Check common options by copying from bs_opts to opts, all other options
370 * stay in bs_opts for processing by bdrv_open(). */
371 id = qdict_get_try_str(bs_opts, "id");
372 opts = qemu_opts_create(&qemu_common_drive_opts, id, 1, &error);
374 error_propagate(errp, error);
378 qemu_opts_absorb_qdict(opts, bs_opts, &error);
380 error_propagate(errp, error);
385 qdict_del(bs_opts, "id");
388 has_driver_specific_opts = !!qdict_size(bs_opts);
390 /* extract parameters */
391 snapshot = qemu_opt_get_bool(opts, "snapshot", 0);
392 ro = qemu_opt_get_bool(opts, "read-only", 0);
393 copy_on_read = qemu_opt_get_bool(opts, "copy-on-read", false);
395 if ((buf = qemu_opt_get(opts, "discard")) != NULL) {
396 if (bdrv_parse_discard_flags(buf, &bdrv_flags) != 0) {
397 error_setg(errp, "invalid discard option");
402 if (qemu_opt_get_bool(opts, BDRV_OPT_CACHE_WB, true)) {
403 bdrv_flags |= BDRV_O_CACHE_WB;
405 if (qemu_opt_get_bool(opts, BDRV_OPT_CACHE_DIRECT, false)) {
406 bdrv_flags |= BDRV_O_NOCACHE;
408 if (qemu_opt_get_bool(opts, BDRV_OPT_CACHE_NO_FLUSH, false)) {
409 bdrv_flags |= BDRV_O_NO_FLUSH;
412 #ifdef CONFIG_LINUX_AIO
413 if ((buf = qemu_opt_get(opts, "aio")) != NULL) {
414 if (!strcmp(buf, "native")) {
415 bdrv_flags |= BDRV_O_NATIVE_AIO;
416 } else if (!strcmp(buf, "threads")) {
417 /* this is the default */
419 error_setg(errp, "invalid aio option");
425 if ((buf = qemu_opt_get(opts, "format")) != NULL) {
426 if (is_help_option(buf)) {
427 error_printf("Supported formats:");
428 bdrv_iterate_format(bdrv_format_print, NULL);
433 if (qdict_haskey(bs_opts, "driver")) {
434 error_setg(errp, "Cannot specify both 'driver' and 'format'");
437 qdict_put(bs_opts, "driver", qstring_from_str(buf));
440 /* disk I/O throttling */
441 memset(&cfg, 0, sizeof(cfg));
442 cfg.buckets[THROTTLE_BPS_TOTAL].avg =
443 qemu_opt_get_number(opts, "throttling.bps-total", 0);
444 cfg.buckets[THROTTLE_BPS_READ].avg =
445 qemu_opt_get_number(opts, "throttling.bps-read", 0);
446 cfg.buckets[THROTTLE_BPS_WRITE].avg =
447 qemu_opt_get_number(opts, "throttling.bps-write", 0);
448 cfg.buckets[THROTTLE_OPS_TOTAL].avg =
449 qemu_opt_get_number(opts, "throttling.iops-total", 0);
450 cfg.buckets[THROTTLE_OPS_READ].avg =
451 qemu_opt_get_number(opts, "throttling.iops-read", 0);
452 cfg.buckets[THROTTLE_OPS_WRITE].avg =
453 qemu_opt_get_number(opts, "throttling.iops-write", 0);
455 cfg.buckets[THROTTLE_BPS_TOTAL].max =
456 qemu_opt_get_number(opts, "throttling.bps-total-max", 0);
457 cfg.buckets[THROTTLE_BPS_READ].max =
458 qemu_opt_get_number(opts, "throttling.bps-read-max", 0);
459 cfg.buckets[THROTTLE_BPS_WRITE].max =
460 qemu_opt_get_number(opts, "throttling.bps-write-max", 0);
461 cfg.buckets[THROTTLE_OPS_TOTAL].max =
462 qemu_opt_get_number(opts, "throttling.iops-total-max", 0);
463 cfg.buckets[THROTTLE_OPS_READ].max =
464 qemu_opt_get_number(opts, "throttling.iops-read-max", 0);
465 cfg.buckets[THROTTLE_OPS_WRITE].max =
466 qemu_opt_get_number(opts, "throttling.iops-write-max", 0);
468 cfg.op_size = qemu_opt_get_number(opts, "throttling.iops-size", 0);
470 throttling_group = qemu_opt_get(opts, "throttling.group");
472 if (!check_throttle_config(&cfg, &error)) {
473 error_propagate(errp, error);
477 on_write_error = BLOCKDEV_ON_ERROR_ENOSPC;
478 if ((buf = qemu_opt_get(opts, "werror")) != NULL) {
479 on_write_error = parse_block_error_action(buf, 0, &error);
481 error_propagate(errp, error);
486 on_read_error = BLOCKDEV_ON_ERROR_REPORT;
487 if ((buf = qemu_opt_get(opts, "rerror")) != NULL) {
488 on_read_error = parse_block_error_action(buf, 1, &error);
490 error_propagate(errp, error);
496 qapi_enum_parse(BlockdevDetectZeroesOptions_lookup,
497 qemu_opt_get(opts, "detect-zeroes"),
498 BLOCKDEV_DETECT_ZEROES_OPTIONS_MAX,
499 BLOCKDEV_DETECT_ZEROES_OPTIONS_OFF,
502 error_propagate(errp, error);
506 if (detect_zeroes == BLOCKDEV_DETECT_ZEROES_OPTIONS_UNMAP &&
507 !(bdrv_flags & BDRV_O_UNMAP)) {
508 error_setg(errp, "setting detect-zeroes to unmap is not allowed "
509 "without setting discard operation to unmap");
514 if ((!file || !*file) && !has_driver_specific_opts) {
515 blk = blk_new_with_bs(qemu_opts_id(opts), errp);
521 bs->open_flags = snapshot ? BDRV_O_SNAPSHOT : 0;
526 if (file && !*file) {
531 /* always use cache=unsafe with snapshot */
532 bdrv_flags &= ~BDRV_O_CACHE_MASK;
533 bdrv_flags |= (BDRV_O_SNAPSHOT|BDRV_O_CACHE_WB|BDRV_O_NO_FLUSH);
537 bdrv_flags |= BDRV_O_COPY_ON_READ;
540 if (runstate_check(RUN_STATE_INMIGRATE)) {
541 bdrv_flags |= BDRV_O_INCOMING;
544 bdrv_flags |= ro ? 0 : BDRV_O_RDWR;
546 blk = blk_new_open(qemu_opts_id(opts), file, NULL, bs_opts, bdrv_flags,
554 bs->detect_zeroes = detect_zeroes;
556 bdrv_set_on_error(bs, on_read_error, on_write_error);
558 /* disk I/O throttling */
559 if (throttle_enabled(&cfg)) {
560 if (!throttling_group) {
561 throttling_group = blk_name(blk);
563 bdrv_io_limits_enable(bs, throttling_group);
564 bdrv_set_io_limits(bs, &cfg);
567 if (bdrv_key_required(bs)) {
582 static void qemu_opt_rename(QemuOpts *opts, const char *from, const char *to,
587 value = qemu_opt_get(opts, from);
589 if (qemu_opt_find(opts, to)) {
590 error_setg(errp, "'%s' and its alias '%s' can't be used at the "
591 "same time", to, from);
596 /* rename all items in opts */
597 while ((value = qemu_opt_get(opts, from))) {
598 qemu_opt_set(opts, to, value, &error_abort);
599 qemu_opt_unset(opts, from);
603 QemuOptsList qemu_legacy_drive_opts = {
605 .head = QTAILQ_HEAD_INITIALIZER(qemu_legacy_drive_opts.head),
609 .type = QEMU_OPT_NUMBER,
610 .help = "bus number",
613 .type = QEMU_OPT_NUMBER,
614 .help = "unit number (i.e. lun for scsi)",
617 .type = QEMU_OPT_NUMBER,
618 .help = "index number",
621 .type = QEMU_OPT_STRING,
622 .help = "media type (disk, cdrom)",
625 .type = QEMU_OPT_STRING,
626 .help = "interface (ide, scsi, sd, mtd, floppy, pflash, virtio)",
629 .type = QEMU_OPT_NUMBER,
630 .help = "number of cylinders (ide disk geometry)",
633 .type = QEMU_OPT_NUMBER,
634 .help = "number of heads (ide disk geometry)",
637 .type = QEMU_OPT_NUMBER,
638 .help = "number of sectors (ide disk geometry)",
641 .type = QEMU_OPT_STRING,
642 .help = "chs translation (auto, lba, none)",
645 .type = QEMU_OPT_BOOL,
646 .help = "(deprecated, ignored)",
649 .type = QEMU_OPT_STRING,
650 .help = "pci address (virtio only)",
653 .type = QEMU_OPT_STRING,
654 .help = "disk serial number",
657 .type = QEMU_OPT_STRING,
661 /* Options that are passed on, but have special semantics with -drive */
664 .type = QEMU_OPT_BOOL,
665 .help = "open drive file as read-only",
668 .type = QEMU_OPT_STRING,
669 .help = "read error action",
672 .type = QEMU_OPT_STRING,
673 .help = "write error action",
675 .name = "copy-on-read",
676 .type = QEMU_OPT_BOOL,
677 .help = "copy read data from backing file into image file",
680 { /* end of list */ }
684 DriveInfo *drive_new(QemuOpts *all_opts, BlockInterfaceType block_default_type)
688 DriveInfo *dinfo = NULL;
690 QemuOpts *legacy_opts;
691 DriveMediaType media = MEDIA_DISK;
692 BlockInterfaceType type;
693 int cyls, heads, secs, translation;
694 int max_devs, bus_id, unit_id, index;
696 const char *werror, *rerror;
697 bool read_only = false;
700 const char *filename;
701 Error *local_err = NULL;
704 /* Change legacy command line options into QMP ones */
705 static const struct {
709 { "iops", "throttling.iops-total" },
710 { "iops_rd", "throttling.iops-read" },
711 { "iops_wr", "throttling.iops-write" },
713 { "bps", "throttling.bps-total" },
714 { "bps_rd", "throttling.bps-read" },
715 { "bps_wr", "throttling.bps-write" },
717 { "iops_max", "throttling.iops-total-max" },
718 { "iops_rd_max", "throttling.iops-read-max" },
719 { "iops_wr_max", "throttling.iops-write-max" },
721 { "bps_max", "throttling.bps-total-max" },
722 { "bps_rd_max", "throttling.bps-read-max" },
723 { "bps_wr_max", "throttling.bps-write-max" },
725 { "iops_size", "throttling.iops-size" },
727 { "group", "throttling.group" },
729 { "readonly", "read-only" },
732 for (i = 0; i < ARRAY_SIZE(opt_renames); i++) {
733 qemu_opt_rename(all_opts, opt_renames[i].from, opt_renames[i].to,
736 error_report_err(local_err);
741 value = qemu_opt_get(all_opts, "cache");
745 if (bdrv_parse_cache_flags(value, &flags) != 0) {
746 error_report("invalid cache option");
750 /* Specific options take precedence */
751 if (!qemu_opt_get(all_opts, BDRV_OPT_CACHE_WB)) {
752 qemu_opt_set_bool(all_opts, BDRV_OPT_CACHE_WB,
753 !!(flags & BDRV_O_CACHE_WB), &error_abort);
755 if (!qemu_opt_get(all_opts, BDRV_OPT_CACHE_DIRECT)) {
756 qemu_opt_set_bool(all_opts, BDRV_OPT_CACHE_DIRECT,
757 !!(flags & BDRV_O_NOCACHE), &error_abort);
759 if (!qemu_opt_get(all_opts, BDRV_OPT_CACHE_NO_FLUSH)) {
760 qemu_opt_set_bool(all_opts, BDRV_OPT_CACHE_NO_FLUSH,
761 !!(flags & BDRV_O_NO_FLUSH), &error_abort);
763 qemu_opt_unset(all_opts, "cache");
766 /* Get a QDict for processing the options */
767 bs_opts = qdict_new();
768 qemu_opts_to_qdict(all_opts, bs_opts);
770 legacy_opts = qemu_opts_create(&qemu_legacy_drive_opts, NULL, 0,
772 qemu_opts_absorb_qdict(legacy_opts, bs_opts, &local_err);
774 error_report_err(local_err);
778 /* Deprecated option boot=[on|off] */
779 if (qemu_opt_get(legacy_opts, "boot") != NULL) {
780 fprintf(stderr, "qemu-kvm: boot=on|off is deprecated and will be "
781 "ignored. Future versions will reject this parameter. Please "
782 "update your scripts.\n");
786 value = qemu_opt_get(legacy_opts, "media");
788 if (!strcmp(value, "disk")) {
790 } else if (!strcmp(value, "cdrom")) {
794 error_report("'%s' invalid media", value);
799 /* copy-on-read is disabled with a warning for read-only devices */
800 read_only |= qemu_opt_get_bool(legacy_opts, "read-only", false);
801 copy_on_read = qemu_opt_get_bool(legacy_opts, "copy-on-read", false);
803 if (read_only && copy_on_read) {
804 error_report("warning: disabling copy-on-read on read-only drive");
805 copy_on_read = false;
808 qdict_put(bs_opts, "read-only",
809 qstring_from_str(read_only ? "on" : "off"));
810 qdict_put(bs_opts, "copy-on-read",
811 qstring_from_str(copy_on_read ? "on" :"off"));
813 /* Controller type */
814 value = qemu_opt_get(legacy_opts, "if");
817 type < IF_COUNT && strcmp(value, if_name[type]);
820 if (type == IF_COUNT) {
821 error_report("unsupported bus type '%s'", value);
825 type = block_default_type;
829 cyls = qemu_opt_get_number(legacy_opts, "cyls", 0);
830 heads = qemu_opt_get_number(legacy_opts, "heads", 0);
831 secs = qemu_opt_get_number(legacy_opts, "secs", 0);
833 if (cyls || heads || secs) {
835 error_report("invalid physical cyls number");
839 error_report("invalid physical heads number");
843 error_report("invalid physical secs number");
848 translation = BIOS_ATA_TRANSLATION_AUTO;
849 value = qemu_opt_get(legacy_opts, "trans");
852 error_report("'%s' trans must be used with cyls, heads and secs",
856 if (!strcmp(value, "none")) {
857 translation = BIOS_ATA_TRANSLATION_NONE;
858 } else if (!strcmp(value, "lba")) {
859 translation = BIOS_ATA_TRANSLATION_LBA;
860 } else if (!strcmp(value, "large")) {
861 translation = BIOS_ATA_TRANSLATION_LARGE;
862 } else if (!strcmp(value, "rechs")) {
863 translation = BIOS_ATA_TRANSLATION_RECHS;
864 } else if (!strcmp(value, "auto")) {
865 translation = BIOS_ATA_TRANSLATION_AUTO;
867 error_report("'%s' invalid translation type", value);
872 if (media == MEDIA_CDROM) {
873 if (cyls || secs || heads) {
874 error_report("CHS can't be set with media=cdrom");
879 /* Device address specified by bus/unit or index.
880 * If none was specified, try to find the first free one. */
881 bus_id = qemu_opt_get_number(legacy_opts, "bus", 0);
882 unit_id = qemu_opt_get_number(legacy_opts, "unit", -1);
883 index = qemu_opt_get_number(legacy_opts, "index", -1);
885 max_devs = if_max_devs[type];
888 if (bus_id != 0 || unit_id != -1) {
889 error_report("index cannot be used with bus and unit");
892 bus_id = drive_index_to_bus_id(type, index);
893 unit_id = drive_index_to_unit_id(type, index);
898 while (drive_get(type, bus_id, unit_id) != NULL) {
900 if (max_devs && unit_id >= max_devs) {
907 if (max_devs && unit_id >= max_devs) {
908 error_report("unit %d too big (max is %d)", unit_id, max_devs - 1);
912 if (drive_get(type, bus_id, unit_id) != NULL) {
913 error_report("drive with bus=%d, unit=%d (index=%d) exists",
914 bus_id, unit_id, index);
919 serial = qemu_opt_get(legacy_opts, "serial");
921 /* no id supplied -> create one */
922 if (qemu_opts_id(all_opts) == NULL) {
924 const char *mediastr = "";
925 if (type == IF_IDE || type == IF_SCSI) {
926 mediastr = (media == MEDIA_CDROM) ? "-cd" : "-hd";
929 new_id = g_strdup_printf("%s%i%s%i", if_name[type], bus_id,
932 new_id = g_strdup_printf("%s%s%i", if_name[type],
935 qdict_put(bs_opts, "id", qstring_from_str(new_id));
939 /* Add virtio block device */
940 devaddr = qemu_opt_get(legacy_opts, "addr");
941 if (devaddr && type != IF_VIRTIO) {
942 error_report("addr is not supported by this bus type");
946 if (type == IF_VIRTIO) {
948 devopts = qemu_opts_create(qemu_find_opts("device"), NULL, 0,
950 if (arch_type == QEMU_ARCH_S390X) {
951 qemu_opt_set(devopts, "driver", "virtio-blk-ccw", &error_abort);
953 qemu_opt_set(devopts, "driver", "virtio-blk-pci", &error_abort);
955 qemu_opt_set(devopts, "drive", qdict_get_str(bs_opts, "id"),
958 qemu_opt_set(devopts, "addr", devaddr, &error_abort);
962 filename = qemu_opt_get(legacy_opts, "file");
964 /* Check werror/rerror compatibility with if=... */
965 werror = qemu_opt_get(legacy_opts, "werror");
966 if (werror != NULL) {
967 if (type != IF_IDE && type != IF_SCSI && type != IF_VIRTIO &&
969 error_report("werror is not supported by this bus type");
972 qdict_put(bs_opts, "werror", qstring_from_str(werror));
975 rerror = qemu_opt_get(legacy_opts, "rerror");
976 if (rerror != NULL) {
977 if (type != IF_IDE && type != IF_VIRTIO && type != IF_SCSI &&
979 error_report("rerror is not supported by this bus type");
982 qdict_put(bs_opts, "rerror", qstring_from_str(rerror));
985 /* Actual block device init: Functionality shared with blockdev-add */
986 blk = blockdev_init(filename, bs_opts, &local_err);
990 error_report_err(local_err);
997 /* Create legacy DriveInfo */
998 dinfo = g_malloc0(sizeof(*dinfo));
999 dinfo->opts = all_opts;
1002 dinfo->heads = heads;
1004 dinfo->trans = translation;
1007 dinfo->bus = bus_id;
1008 dinfo->unit = unit_id;
1009 dinfo->devaddr = devaddr;
1010 dinfo->serial = g_strdup(serial);
1012 blk_set_legacy_dinfo(blk, dinfo);
1019 dinfo->media_cd = media == MEDIA_CDROM;
1026 qemu_opts_del(legacy_opts);
1031 void hmp_commit(Monitor *mon, const QDict *qdict)
1033 const char *device = qdict_get_str(qdict, "device");
1037 if (!strcmp(device, "all")) {
1038 ret = bdrv_commit_all();
1040 blk = blk_by_name(device);
1042 monitor_printf(mon, "Device '%s' not found\n", device);
1045 ret = bdrv_commit(blk_bs(blk));
1048 monitor_printf(mon, "'commit' error for '%s': %s\n", device,
1053 static void blockdev_do_action(int kind, void *data, Error **errp)
1055 TransactionAction action;
1056 TransactionActionList list;
1060 list.value = &action;
1062 qmp_transaction(&list, errp);
1065 void qmp_blockdev_snapshot_sync(bool has_device, const char *device,
1066 bool has_node_name, const char *node_name,
1067 const char *snapshot_file,
1068 bool has_snapshot_node_name,
1069 const char *snapshot_node_name,
1070 bool has_format, const char *format,
1071 bool has_mode, NewImageMode mode, Error **errp)
1073 BlockdevSnapshot snapshot = {
1074 .has_device = has_device,
1075 .device = (char *) device,
1076 .has_node_name = has_node_name,
1077 .node_name = (char *) node_name,
1078 .snapshot_file = (char *) snapshot_file,
1079 .has_snapshot_node_name = has_snapshot_node_name,
1080 .snapshot_node_name = (char *) snapshot_node_name,
1081 .has_format = has_format,
1082 .format = (char *) format,
1083 .has_mode = has_mode,
1086 blockdev_do_action(TRANSACTION_ACTION_KIND_BLOCKDEV_SNAPSHOT_SYNC,
1090 void qmp_blockdev_snapshot_internal_sync(const char *device,
1094 BlockdevSnapshotInternal snapshot = {
1095 .device = (char *) device,
1096 .name = (char *) name
1099 blockdev_do_action(TRANSACTION_ACTION_KIND_BLOCKDEV_SNAPSHOT_INTERNAL_SYNC,
1103 SnapshotInfo *qmp_blockdev_snapshot_delete_internal_sync(const char *device,
1110 BlockDriverState *bs;
1112 AioContext *aio_context;
1113 QEMUSnapshotInfo sn;
1114 Error *local_err = NULL;
1115 SnapshotInfo *info = NULL;
1118 blk = blk_by_name(device);
1120 error_set(errp, ERROR_CLASS_DEVICE_NOT_FOUND,
1121 "Device '%s' not found", device);
1135 error_setg(errp, "Name or id must be provided");
1139 aio_context = bdrv_get_aio_context(bs);
1140 aio_context_acquire(aio_context);
1142 if (bdrv_op_is_blocked(bs, BLOCK_OP_TYPE_INTERNAL_SNAPSHOT_DELETE, errp)) {
1143 goto out_aio_context;
1146 ret = bdrv_snapshot_find_by_id_and_name(bs, id, name, &sn, &local_err);
1148 error_propagate(errp, local_err);
1149 goto out_aio_context;
1153 "Snapshot with id '%s' and name '%s' does not exist on "
1155 STR_OR_NULL(id), STR_OR_NULL(name), device);
1156 goto out_aio_context;
1159 bdrv_snapshot_delete(bs, id, name, &local_err);
1161 error_propagate(errp, local_err);
1162 goto out_aio_context;
1165 aio_context_release(aio_context);
1167 info = g_new0(SnapshotInfo, 1);
1168 info->id = g_strdup(sn.id_str);
1169 info->name = g_strdup(sn.name);
1170 info->date_nsec = sn.date_nsec;
1171 info->date_sec = sn.date_sec;
1172 info->vm_state_size = sn.vm_state_size;
1173 info->vm_clock_nsec = sn.vm_clock_nsec % 1000000000;
1174 info->vm_clock_sec = sn.vm_clock_nsec / 1000000000;
1179 aio_context_release(aio_context);
1184 * block_dirty_bitmap_lookup:
1185 * Return a dirty bitmap (if present), after validating
1186 * the node reference and bitmap names.
1188 * @node: The name of the BDS node to search for bitmaps
1189 * @name: The name of the bitmap to search for
1190 * @pbs: Output pointer for BDS lookup, if desired. Can be NULL.
1191 * @paio: Output pointer for aio_context acquisition, if desired. Can be NULL.
1192 * @errp: Output pointer for error information. Can be NULL.
1194 * @return: A bitmap object on success, or NULL on failure.
1196 static BdrvDirtyBitmap *block_dirty_bitmap_lookup(const char *node,
1198 BlockDriverState **pbs,
1202 BlockDriverState *bs;
1203 BdrvDirtyBitmap *bitmap;
1204 AioContext *aio_context;
1207 error_setg(errp, "Node cannot be NULL");
1211 error_setg(errp, "Bitmap name cannot be NULL");
1214 bs = bdrv_lookup_bs(node, node, NULL);
1216 error_setg(errp, "Node '%s' not found", node);
1220 aio_context = bdrv_get_aio_context(bs);
1221 aio_context_acquire(aio_context);
1223 bitmap = bdrv_find_dirty_bitmap(bs, name);
1225 error_setg(errp, "Dirty bitmap '%s' not found", name);
1233 *paio = aio_context;
1235 aio_context_release(aio_context);
1241 aio_context_release(aio_context);
1245 /* New and old BlockDriverState structs for atomic group operations */
1247 typedef struct BlkTransactionState BlkTransactionState;
1249 /* Only prepare() may fail. In a single transaction, only one of commit() or
1250 abort() will be called, clean() will always be called if it present. */
1251 typedef struct BdrvActionOps {
1252 /* Size of state struct, in bytes. */
1253 size_t instance_size;
1254 /* Prepare the work, must NOT be NULL. */
1255 void (*prepare)(BlkTransactionState *common, Error **errp);
1256 /* Commit the changes, can be NULL. */
1257 void (*commit)(BlkTransactionState *common);
1258 /* Abort the changes on fail, can be NULL. */
1259 void (*abort)(BlkTransactionState *common);
1260 /* Clean up resource in the end, can be NULL. */
1261 void (*clean)(BlkTransactionState *common);
1265 * This structure must be arranged as first member in child type, assuming
1266 * that compiler will also arrange it to the same address with parent instance.
1267 * Later it will be used in free().
1269 struct BlkTransactionState {
1270 TransactionAction *action;
1271 const BdrvActionOps *ops;
1272 QSIMPLEQ_ENTRY(BlkTransactionState) entry;
1275 /* internal snapshot private data */
1276 typedef struct InternalSnapshotState {
1277 BlkTransactionState common;
1278 BlockDriverState *bs;
1279 AioContext *aio_context;
1280 QEMUSnapshotInfo sn;
1281 } InternalSnapshotState;
1283 static void internal_snapshot_prepare(BlkTransactionState *common,
1286 Error *local_err = NULL;
1290 BlockDriverState *bs;
1291 QEMUSnapshotInfo old_sn, *sn;
1294 BlockdevSnapshotInternal *internal;
1295 InternalSnapshotState *state;
1298 g_assert(common->action->kind ==
1299 TRANSACTION_ACTION_KIND_BLOCKDEV_SNAPSHOT_INTERNAL_SYNC);
1300 internal = common->action->blockdev_snapshot_internal_sync;
1301 state = DO_UPCAST(InternalSnapshotState, common, common);
1303 /* 1. parse input */
1304 device = internal->device;
1305 name = internal->name;
1307 /* 2. check for validation */
1308 blk = blk_by_name(device);
1310 error_set(errp, ERROR_CLASS_DEVICE_NOT_FOUND,
1311 "Device '%s' not found", device);
1316 /* AioContext is released in .clean() */
1317 state->aio_context = bdrv_get_aio_context(bs);
1318 aio_context_acquire(state->aio_context);
1320 if (!bdrv_is_inserted(bs)) {
1321 error_setg(errp, QERR_DEVICE_HAS_NO_MEDIUM, device);
1325 if (bdrv_op_is_blocked(bs, BLOCK_OP_TYPE_INTERNAL_SNAPSHOT, errp)) {
1329 if (bdrv_is_read_only(bs)) {
1330 error_setg(errp, "Device '%s' is read only", device);
1334 if (!bdrv_can_snapshot(bs)) {
1335 error_setg(errp, "Block format '%s' used by device '%s' "
1336 "does not support internal snapshots",
1337 bs->drv->format_name, device);
1341 if (!strlen(name)) {
1342 error_setg(errp, "Name is empty");
1346 /* check whether a snapshot with name exist */
1347 ret = bdrv_snapshot_find_by_id_and_name(bs, NULL, name, &old_sn,
1350 error_propagate(errp, local_err);
1354 "Snapshot with name '%s' already exists on device '%s'",
1359 /* 3. take the snapshot */
1361 pstrcpy(sn->name, sizeof(sn->name), name);
1362 qemu_gettimeofday(&tv);
1363 sn->date_sec = tv.tv_sec;
1364 sn->date_nsec = tv.tv_usec * 1000;
1365 sn->vm_clock_nsec = qemu_clock_get_ns(QEMU_CLOCK_VIRTUAL);
1367 ret1 = bdrv_snapshot_create(bs, sn);
1369 error_setg_errno(errp, -ret1,
1370 "Failed to create snapshot '%s' on device '%s'",
1375 /* 4. succeed, mark a snapshot is created */
1379 static void internal_snapshot_abort(BlkTransactionState *common)
1381 InternalSnapshotState *state =
1382 DO_UPCAST(InternalSnapshotState, common, common);
1383 BlockDriverState *bs = state->bs;
1384 QEMUSnapshotInfo *sn = &state->sn;
1385 Error *local_error = NULL;
1391 if (bdrv_snapshot_delete(bs, sn->id_str, sn->name, &local_error) < 0) {
1392 error_report("Failed to delete snapshot with id '%s' and name '%s' on "
1393 "device '%s' in abort: %s",
1396 bdrv_get_device_name(bs),
1397 error_get_pretty(local_error));
1398 error_free(local_error);
1402 static void internal_snapshot_clean(BlkTransactionState *common)
1404 InternalSnapshotState *state = DO_UPCAST(InternalSnapshotState,
1407 if (state->aio_context) {
1408 aio_context_release(state->aio_context);
1412 /* external snapshot private data */
1413 typedef struct ExternalSnapshotState {
1414 BlkTransactionState common;
1415 BlockDriverState *old_bs;
1416 BlockDriverState *new_bs;
1417 AioContext *aio_context;
1418 } ExternalSnapshotState;
1420 static void external_snapshot_prepare(BlkTransactionState *common,
1425 QDict *options = NULL;
1426 Error *local_err = NULL;
1427 bool has_device = false;
1429 bool has_node_name = false;
1430 const char *node_name;
1431 bool has_snapshot_node_name = false;
1432 const char *snapshot_node_name;
1433 const char *new_image_file;
1434 const char *format = "qcow2";
1435 enum NewImageMode mode = NEW_IMAGE_MODE_ABSOLUTE_PATHS;
1436 ExternalSnapshotState *state =
1437 DO_UPCAST(ExternalSnapshotState, common, common);
1438 TransactionAction *action = common->action;
1440 /* get parameters */
1441 g_assert(action->kind == TRANSACTION_ACTION_KIND_BLOCKDEV_SNAPSHOT_SYNC);
1443 has_device = action->blockdev_snapshot_sync->has_device;
1444 device = action->blockdev_snapshot_sync->device;
1445 has_node_name = action->blockdev_snapshot_sync->has_node_name;
1446 node_name = action->blockdev_snapshot_sync->node_name;
1447 has_snapshot_node_name =
1448 action->blockdev_snapshot_sync->has_snapshot_node_name;
1449 snapshot_node_name = action->blockdev_snapshot_sync->snapshot_node_name;
1451 new_image_file = action->blockdev_snapshot_sync->snapshot_file;
1452 if (action->blockdev_snapshot_sync->has_format) {
1453 format = action->blockdev_snapshot_sync->format;
1455 if (action->blockdev_snapshot_sync->has_mode) {
1456 mode = action->blockdev_snapshot_sync->mode;
1459 /* start processing */
1460 drv = bdrv_find_format(format);
1462 error_setg(errp, QERR_INVALID_BLOCK_FORMAT, format);
1466 state->old_bs = bdrv_lookup_bs(has_device ? device : NULL,
1467 has_node_name ? node_name : NULL,
1470 error_propagate(errp, local_err);
1474 if (has_node_name && !has_snapshot_node_name) {
1475 error_setg(errp, "New snapshot node name missing");
1479 if (has_snapshot_node_name && bdrv_find_node(snapshot_node_name)) {
1480 error_setg(errp, "New snapshot node name already existing");
1484 /* Acquire AioContext now so any threads operating on old_bs stop */
1485 state->aio_context = bdrv_get_aio_context(state->old_bs);
1486 aio_context_acquire(state->aio_context);
1488 if (!bdrv_is_inserted(state->old_bs)) {
1489 error_setg(errp, QERR_DEVICE_HAS_NO_MEDIUM, device);
1493 if (bdrv_op_is_blocked(state->old_bs,
1494 BLOCK_OP_TYPE_EXTERNAL_SNAPSHOT, errp)) {
1498 if (!bdrv_is_read_only(state->old_bs)) {
1499 if (bdrv_flush(state->old_bs)) {
1500 error_setg(errp, QERR_IO_ERROR);
1505 if (!bdrv_is_first_non_filter(state->old_bs)) {
1506 error_setg(errp, QERR_FEATURE_DISABLED, "snapshot");
1510 flags = state->old_bs->open_flags;
1512 /* create new image w/backing file */
1513 if (mode != NEW_IMAGE_MODE_EXISTING) {
1514 bdrv_img_create(new_image_file, format,
1515 state->old_bs->filename,
1516 state->old_bs->drv->format_name,
1517 NULL, -1, flags, &local_err, false);
1519 error_propagate(errp, local_err);
1524 if (has_snapshot_node_name) {
1525 options = qdict_new();
1526 qdict_put(options, "node-name",
1527 qstring_from_str(snapshot_node_name));
1530 /* TODO Inherit bs->options or only take explicit options with an
1531 * extended QMP command? */
1532 assert(state->new_bs == NULL);
1533 ret = bdrv_open(&state->new_bs, new_image_file, NULL, options,
1534 flags | BDRV_O_NO_BACKING, drv, &local_err);
1535 /* We will manually add the backing_hd field to the bs later */
1537 error_propagate(errp, local_err);
1541 static void external_snapshot_commit(BlkTransactionState *common)
1543 ExternalSnapshotState *state =
1544 DO_UPCAST(ExternalSnapshotState, common, common);
1546 bdrv_set_aio_context(state->new_bs, state->aio_context);
1548 /* This removes our old bs and adds the new bs */
1549 bdrv_append(state->new_bs, state->old_bs);
1550 /* We don't need (or want) to use the transactional
1551 * bdrv_reopen_multiple() across all the entries at once, because we
1552 * don't want to abort all of them if one of them fails the reopen */
1553 bdrv_reopen(state->new_bs, state->new_bs->open_flags & ~BDRV_O_RDWR,
1556 aio_context_release(state->aio_context);
1559 static void external_snapshot_abort(BlkTransactionState *common)
1561 ExternalSnapshotState *state =
1562 DO_UPCAST(ExternalSnapshotState, common, common);
1563 if (state->new_bs) {
1564 bdrv_unref(state->new_bs);
1566 if (state->aio_context) {
1567 aio_context_release(state->aio_context);
1571 typedef struct DriveBackupState {
1572 BlkTransactionState common;
1573 BlockDriverState *bs;
1574 AioContext *aio_context;
1578 static void drive_backup_prepare(BlkTransactionState *common, Error **errp)
1580 DriveBackupState *state = DO_UPCAST(DriveBackupState, common, common);
1581 BlockDriverState *bs;
1583 DriveBackup *backup;
1584 Error *local_err = NULL;
1586 assert(common->action->kind == TRANSACTION_ACTION_KIND_DRIVE_BACKUP);
1587 backup = common->action->drive_backup;
1589 blk = blk_by_name(backup->device);
1591 error_set(errp, ERROR_CLASS_DEVICE_NOT_FOUND,
1592 "Device '%s' not found", backup->device);
1597 /* AioContext is released in .clean() */
1598 state->aio_context = bdrv_get_aio_context(bs);
1599 aio_context_acquire(state->aio_context);
1601 qmp_drive_backup(backup->device, backup->target,
1602 backup->has_format, backup->format,
1604 backup->has_mode, backup->mode,
1605 backup->has_speed, backup->speed,
1606 backup->has_bitmap, backup->bitmap,
1607 backup->has_on_source_error, backup->on_source_error,
1608 backup->has_on_target_error, backup->on_target_error,
1611 error_propagate(errp, local_err);
1616 state->job = state->bs->job;
1619 static void drive_backup_abort(BlkTransactionState *common)
1621 DriveBackupState *state = DO_UPCAST(DriveBackupState, common, common);
1622 BlockDriverState *bs = state->bs;
1624 /* Only cancel if it's the job we started */
1625 if (bs && bs->job && bs->job == state->job) {
1626 block_job_cancel_sync(bs->job);
1630 static void drive_backup_clean(BlkTransactionState *common)
1632 DriveBackupState *state = DO_UPCAST(DriveBackupState, common, common);
1634 if (state->aio_context) {
1635 aio_context_release(state->aio_context);
1639 typedef struct BlockdevBackupState {
1640 BlkTransactionState common;
1641 BlockDriverState *bs;
1643 AioContext *aio_context;
1644 } BlockdevBackupState;
1646 static void blockdev_backup_prepare(BlkTransactionState *common, Error **errp)
1648 BlockdevBackupState *state = DO_UPCAST(BlockdevBackupState, common, common);
1649 BlockdevBackup *backup;
1650 BlockDriverState *bs, *target;
1652 Error *local_err = NULL;
1654 assert(common->action->kind == TRANSACTION_ACTION_KIND_BLOCKDEV_BACKUP);
1655 backup = common->action->blockdev_backup;
1657 blk = blk_by_name(backup->device);
1659 error_setg(errp, "Device '%s' not found", backup->device);
1664 blk = blk_by_name(backup->target);
1666 error_setg(errp, "Device '%s' not found", backup->target);
1669 target = blk_bs(blk);
1671 /* AioContext is released in .clean() */
1672 state->aio_context = bdrv_get_aio_context(bs);
1673 if (state->aio_context != bdrv_get_aio_context(target)) {
1674 state->aio_context = NULL;
1675 error_setg(errp, "Backup between two IO threads is not implemented");
1678 aio_context_acquire(state->aio_context);
1680 qmp_blockdev_backup(backup->device, backup->target,
1682 backup->has_speed, backup->speed,
1683 backup->has_on_source_error, backup->on_source_error,
1684 backup->has_on_target_error, backup->on_target_error,
1687 error_propagate(errp, local_err);
1692 state->job = state->bs->job;
1695 static void blockdev_backup_abort(BlkTransactionState *common)
1697 BlockdevBackupState *state = DO_UPCAST(BlockdevBackupState, common, common);
1698 BlockDriverState *bs = state->bs;
1700 /* Only cancel if it's the job we started */
1701 if (bs && bs->job && bs->job == state->job) {
1702 block_job_cancel_sync(bs->job);
1706 static void blockdev_backup_clean(BlkTransactionState *common)
1708 BlockdevBackupState *state = DO_UPCAST(BlockdevBackupState, common, common);
1710 if (state->aio_context) {
1711 aio_context_release(state->aio_context);
1715 static void abort_prepare(BlkTransactionState *common, Error **errp)
1717 error_setg(errp, "Transaction aborted using Abort action");
1720 static void abort_commit(BlkTransactionState *common)
1722 g_assert_not_reached(); /* this action never succeeds */
1725 static const BdrvActionOps actions[] = {
1726 [TRANSACTION_ACTION_KIND_BLOCKDEV_SNAPSHOT_SYNC] = {
1727 .instance_size = sizeof(ExternalSnapshotState),
1728 .prepare = external_snapshot_prepare,
1729 .commit = external_snapshot_commit,
1730 .abort = external_snapshot_abort,
1732 [TRANSACTION_ACTION_KIND_DRIVE_BACKUP] = {
1733 .instance_size = sizeof(DriveBackupState),
1734 .prepare = drive_backup_prepare,
1735 .abort = drive_backup_abort,
1736 .clean = drive_backup_clean,
1738 [TRANSACTION_ACTION_KIND_BLOCKDEV_BACKUP] = {
1739 .instance_size = sizeof(BlockdevBackupState),
1740 .prepare = blockdev_backup_prepare,
1741 .abort = blockdev_backup_abort,
1742 .clean = blockdev_backup_clean,
1744 [TRANSACTION_ACTION_KIND_ABORT] = {
1745 .instance_size = sizeof(BlkTransactionState),
1746 .prepare = abort_prepare,
1747 .commit = abort_commit,
1749 [TRANSACTION_ACTION_KIND_BLOCKDEV_SNAPSHOT_INTERNAL_SYNC] = {
1750 .instance_size = sizeof(InternalSnapshotState),
1751 .prepare = internal_snapshot_prepare,
1752 .abort = internal_snapshot_abort,
1753 .clean = internal_snapshot_clean,
1758 * 'Atomic' group operations. The operations are performed as a set, and if
1759 * any fail then we roll back all operations in the group.
1761 void qmp_transaction(TransactionActionList *dev_list, Error **errp)
1763 TransactionActionList *dev_entry = dev_list;
1764 BlkTransactionState *state, *next;
1765 Error *local_err = NULL;
1767 QSIMPLEQ_HEAD(snap_bdrv_states, BlkTransactionState) snap_bdrv_states;
1768 QSIMPLEQ_INIT(&snap_bdrv_states);
1770 /* drain all i/o before any operations */
1773 /* We don't do anything in this loop that commits us to the operations */
1774 while (NULL != dev_entry) {
1775 TransactionAction *dev_info = NULL;
1776 const BdrvActionOps *ops;
1778 dev_info = dev_entry->value;
1779 dev_entry = dev_entry->next;
1781 assert(dev_info->kind < ARRAY_SIZE(actions));
1783 ops = &actions[dev_info->kind];
1784 assert(ops->instance_size > 0);
1786 state = g_malloc0(ops->instance_size);
1788 state->action = dev_info;
1789 QSIMPLEQ_INSERT_TAIL(&snap_bdrv_states, state, entry);
1791 state->ops->prepare(state, &local_err);
1793 error_propagate(errp, local_err);
1794 goto delete_and_fail;
1798 QSIMPLEQ_FOREACH(state, &snap_bdrv_states, entry) {
1799 if (state->ops->commit) {
1800 state->ops->commit(state);
1808 /* failure, and it is all-or-none; roll back all operations */
1809 QSIMPLEQ_FOREACH(state, &snap_bdrv_states, entry) {
1810 if (state->ops->abort) {
1811 state->ops->abort(state);
1815 QSIMPLEQ_FOREACH_SAFE(state, &snap_bdrv_states, entry, next) {
1816 if (state->ops->clean) {
1817 state->ops->clean(state);
1824 static void eject_device(BlockBackend *blk, int force, Error **errp)
1826 BlockDriverState *bs = blk_bs(blk);
1827 AioContext *aio_context;
1829 aio_context = bdrv_get_aio_context(bs);
1830 aio_context_acquire(aio_context);
1832 if (bdrv_op_is_blocked(bs, BLOCK_OP_TYPE_EJECT, errp)) {
1835 if (!blk_dev_has_removable_media(blk)) {
1836 error_setg(errp, "Device '%s' is not removable",
1837 bdrv_get_device_name(bs));
1841 if (blk_dev_is_medium_locked(blk) && !blk_dev_is_tray_open(blk)) {
1842 blk_dev_eject_request(blk, force);
1844 error_setg(errp, "Device '%s' is locked",
1845 bdrv_get_device_name(bs));
1853 aio_context_release(aio_context);
1856 void qmp_eject(const char *device, bool has_force, bool force, Error **errp)
1860 blk = blk_by_name(device);
1862 error_set(errp, ERROR_CLASS_DEVICE_NOT_FOUND,
1863 "Device '%s' not found", device);
1867 eject_device(blk, force, errp);
1870 void qmp_block_passwd(bool has_device, const char *device,
1871 bool has_node_name, const char *node_name,
1872 const char *password, Error **errp)
1874 Error *local_err = NULL;
1875 BlockDriverState *bs;
1876 AioContext *aio_context;
1878 bs = bdrv_lookup_bs(has_device ? device : NULL,
1879 has_node_name ? node_name : NULL,
1882 error_propagate(errp, local_err);
1886 aio_context = bdrv_get_aio_context(bs);
1887 aio_context_acquire(aio_context);
1889 bdrv_add_key(bs, password, errp);
1891 aio_context_release(aio_context);
1894 /* Assumes AioContext is held */
1895 static void qmp_bdrv_open_encrypted(BlockDriverState *bs, const char *filename,
1896 int bdrv_flags, BlockDriver *drv,
1897 const char *password, Error **errp)
1899 Error *local_err = NULL;
1902 ret = bdrv_open(&bs, filename, NULL, NULL, bdrv_flags, drv, &local_err);
1904 error_propagate(errp, local_err);
1908 bdrv_add_key(bs, password, errp);
1911 void qmp_change_blockdev(const char *device, const char *filename,
1912 const char *format, Error **errp)
1915 BlockDriverState *bs;
1916 AioContext *aio_context;
1917 BlockDriver *drv = NULL;
1921 blk = blk_by_name(device);
1923 error_set(errp, ERROR_CLASS_DEVICE_NOT_FOUND,
1924 "Device '%s' not found", device);
1929 aio_context = bdrv_get_aio_context(bs);
1930 aio_context_acquire(aio_context);
1933 drv = bdrv_find_whitelisted_format(format, bs->read_only);
1935 error_setg(errp, QERR_INVALID_BLOCK_FORMAT, format);
1940 eject_device(blk, 0, &err);
1942 error_propagate(errp, err);
1946 bdrv_flags = bdrv_is_read_only(bs) ? 0 : BDRV_O_RDWR;
1947 bdrv_flags |= bdrv_is_snapshot(bs) ? BDRV_O_SNAPSHOT : 0;
1949 qmp_bdrv_open_encrypted(bs, filename, bdrv_flags, drv, NULL, errp);
1952 aio_context_release(aio_context);
1955 /* throttling disk I/O limits */
1956 void qmp_block_set_io_throttle(const char *device, int64_t bps, int64_t bps_rd,
1963 bool has_bps_rd_max,
1965 bool has_bps_wr_max,
1969 bool has_iops_rd_max,
1970 int64_t iops_rd_max,
1971 bool has_iops_wr_max,
1972 int64_t iops_wr_max,
1976 const char *group, Error **errp)
1979 BlockDriverState *bs;
1981 AioContext *aio_context;
1983 blk = blk_by_name(device);
1985 error_set(errp, ERROR_CLASS_DEVICE_NOT_FOUND,
1986 "Device '%s' not found", device);
1991 memset(&cfg, 0, sizeof(cfg));
1992 cfg.buckets[THROTTLE_BPS_TOTAL].avg = bps;
1993 cfg.buckets[THROTTLE_BPS_READ].avg = bps_rd;
1994 cfg.buckets[THROTTLE_BPS_WRITE].avg = bps_wr;
1996 cfg.buckets[THROTTLE_OPS_TOTAL].avg = iops;
1997 cfg.buckets[THROTTLE_OPS_READ].avg = iops_rd;
1998 cfg.buckets[THROTTLE_OPS_WRITE].avg = iops_wr;
2001 cfg.buckets[THROTTLE_BPS_TOTAL].max = bps_max;
2003 if (has_bps_rd_max) {
2004 cfg.buckets[THROTTLE_BPS_READ].max = bps_rd_max;
2006 if (has_bps_wr_max) {
2007 cfg.buckets[THROTTLE_BPS_WRITE].max = bps_wr_max;
2010 cfg.buckets[THROTTLE_OPS_TOTAL].max = iops_max;
2012 if (has_iops_rd_max) {
2013 cfg.buckets[THROTTLE_OPS_READ].max = iops_rd_max;
2015 if (has_iops_wr_max) {
2016 cfg.buckets[THROTTLE_OPS_WRITE].max = iops_wr_max;
2019 if (has_iops_size) {
2020 cfg.op_size = iops_size;
2023 if (!check_throttle_config(&cfg, errp)) {
2027 aio_context = bdrv_get_aio_context(bs);
2028 aio_context_acquire(aio_context);
2030 if (throttle_enabled(&cfg)) {
2031 /* Enable I/O limits if they're not enabled yet, otherwise
2032 * just update the throttling group. */
2033 if (!bs->io_limits_enabled) {
2034 bdrv_io_limits_enable(bs, has_group ? group : device);
2035 } else if (has_group) {
2036 bdrv_io_limits_update_group(bs, group);
2038 /* Set the new throttling configuration */
2039 bdrv_set_io_limits(bs, &cfg);
2040 } else if (bs->io_limits_enabled) {
2041 /* If all throttling settings are set to 0, disable I/O limits */
2042 bdrv_io_limits_disable(bs);
2045 aio_context_release(aio_context);
2048 void qmp_block_dirty_bitmap_add(const char *node, const char *name,
2049 bool has_granularity, uint32_t granularity,
2052 AioContext *aio_context;
2053 BlockDriverState *bs;
2055 if (!name || name[0] == '\0') {
2056 error_setg(errp, "Bitmap name cannot be empty");
2060 bs = bdrv_lookup_bs(node, node, errp);
2065 aio_context = bdrv_get_aio_context(bs);
2066 aio_context_acquire(aio_context);
2068 if (has_granularity) {
2069 if (granularity < 512 || !is_power_of_2(granularity)) {
2070 error_setg(errp, "Granularity must be power of 2 "
2071 "and at least 512");
2075 /* Default to cluster size, if available: */
2076 granularity = bdrv_get_default_bitmap_granularity(bs);
2079 bdrv_create_dirty_bitmap(bs, granularity, name, errp);
2082 aio_context_release(aio_context);
2085 void qmp_block_dirty_bitmap_remove(const char *node, const char *name,
2088 AioContext *aio_context;
2089 BlockDriverState *bs;
2090 BdrvDirtyBitmap *bitmap;
2092 bitmap = block_dirty_bitmap_lookup(node, name, &bs, &aio_context, errp);
2093 if (!bitmap || !bs) {
2097 if (bdrv_dirty_bitmap_frozen(bitmap)) {
2099 "Bitmap '%s' is currently frozen and cannot be removed",
2103 bdrv_dirty_bitmap_make_anon(bitmap);
2104 bdrv_release_dirty_bitmap(bs, bitmap);
2107 aio_context_release(aio_context);
2111 * Completely clear a bitmap, for the purposes of synchronizing a bitmap
2112 * immediately after a full backup operation.
2114 void qmp_block_dirty_bitmap_clear(const char *node, const char *name,
2117 AioContext *aio_context;
2118 BdrvDirtyBitmap *bitmap;
2119 BlockDriverState *bs;
2121 bitmap = block_dirty_bitmap_lookup(node, name, &bs, &aio_context, errp);
2122 if (!bitmap || !bs) {
2126 if (bdrv_dirty_bitmap_frozen(bitmap)) {
2128 "Bitmap '%s' is currently frozen and cannot be modified",
2131 } else if (!bdrv_dirty_bitmap_enabled(bitmap)) {
2133 "Bitmap '%s' is currently disabled and cannot be cleared",
2138 bdrv_clear_dirty_bitmap(bitmap);
2141 aio_context_release(aio_context);
2144 void hmp_drive_del(Monitor *mon, const QDict *qdict)
2146 const char *id = qdict_get_str(qdict, "id");
2148 BlockDriverState *bs;
2149 AioContext *aio_context;
2150 Error *local_err = NULL;
2152 blk = blk_by_name(id);
2154 error_report("Device '%s' not found", id);
2159 if (!blk_legacy_dinfo(blk)) {
2160 error_report("Deleting device added with blockdev-add"
2161 " is not supported");
2165 aio_context = bdrv_get_aio_context(bs);
2166 aio_context_acquire(aio_context);
2168 if (bdrv_op_is_blocked(bs, BLOCK_OP_TYPE_DRIVE_DEL, &local_err)) {
2169 error_report_err(local_err);
2170 aio_context_release(aio_context);
2176 /* if we have a device attached to this BlockDriverState
2177 * then we need to make the drive anonymous until the device
2178 * can be removed. If this is a drive with no device backing
2179 * then we can just get rid of the block driver state right here.
2181 if (blk_get_attached_dev(blk)) {
2182 blk_hide_on_behalf_of_hmp_drive_del(blk);
2183 /* Further I/O must not pause the guest */
2184 bdrv_set_on_error(bs, BLOCKDEV_ON_ERROR_REPORT,
2185 BLOCKDEV_ON_ERROR_REPORT);
2190 aio_context_release(aio_context);
2193 void qmp_block_resize(bool has_device, const char *device,
2194 bool has_node_name, const char *node_name,
2195 int64_t size, Error **errp)
2197 Error *local_err = NULL;
2198 BlockDriverState *bs;
2199 AioContext *aio_context;
2202 bs = bdrv_lookup_bs(has_device ? device : NULL,
2203 has_node_name ? node_name : NULL,
2206 error_propagate(errp, local_err);
2210 aio_context = bdrv_get_aio_context(bs);
2211 aio_context_acquire(aio_context);
2213 if (!bdrv_is_first_non_filter(bs)) {
2214 error_setg(errp, QERR_FEATURE_DISABLED, "resize");
2219 error_setg(errp, QERR_INVALID_PARAMETER_VALUE, "size", "a >0 size");
2223 if (bdrv_op_is_blocked(bs, BLOCK_OP_TYPE_RESIZE, NULL)) {
2224 error_setg(errp, QERR_DEVICE_IN_USE, device);
2228 /* complete all in-flight operations before resizing the device */
2231 ret = bdrv_truncate(bs, size);
2236 error_setg(errp, QERR_DEVICE_HAS_NO_MEDIUM, device);
2239 error_setg(errp, QERR_UNSUPPORTED);
2242 error_setg(errp, "Device '%s' is read only", device);
2245 error_setg(errp, QERR_DEVICE_IN_USE, device);
2248 error_setg_errno(errp, -ret, "Could not resize");
2253 aio_context_release(aio_context);
2256 static void block_job_cb(void *opaque, int ret)
2258 /* Note that this function may be executed from another AioContext besides
2259 * the QEMU main loop. If you need to access anything that assumes the
2260 * QEMU global mutex, use a BH or introduce a mutex.
2263 BlockDriverState *bs = opaque;
2264 const char *msg = NULL;
2266 trace_block_job_cb(bs, bs->job, ret);
2271 msg = strerror(-ret);
2274 if (block_job_is_cancelled(bs->job)) {
2275 block_job_event_cancelled(bs->job);
2277 block_job_event_completed(bs->job, msg);
2280 bdrv_put_ref_bh_schedule(bs);
2283 void qmp_block_stream(const char *device,
2284 bool has_base, const char *base,
2285 bool has_backing_file, const char *backing_file,
2286 bool has_speed, int64_t speed,
2287 bool has_on_error, BlockdevOnError on_error,
2291 BlockDriverState *bs;
2292 BlockDriverState *base_bs = NULL;
2293 AioContext *aio_context;
2294 Error *local_err = NULL;
2295 const char *base_name = NULL;
2297 if (!has_on_error) {
2298 on_error = BLOCKDEV_ON_ERROR_REPORT;
2301 blk = blk_by_name(device);
2303 error_set(errp, ERROR_CLASS_DEVICE_NOT_FOUND,
2304 "Device '%s' not found", device);
2309 aio_context = bdrv_get_aio_context(bs);
2310 aio_context_acquire(aio_context);
2312 if (bdrv_op_is_blocked(bs, BLOCK_OP_TYPE_STREAM, errp)) {
2317 base_bs = bdrv_find_backing_image(bs, base);
2318 if (base_bs == NULL) {
2319 error_setg(errp, QERR_BASE_NOT_FOUND, base);
2322 assert(bdrv_get_aio_context(base_bs) == aio_context);
2326 /* if we are streaming the entire chain, the result will have no backing
2327 * file, and specifying one is therefore an error */
2328 if (base_bs == NULL && has_backing_file) {
2329 error_setg(errp, "backing file specified, but streaming the "
2334 /* backing_file string overrides base bs filename */
2335 base_name = has_backing_file ? backing_file : base_name;
2337 stream_start(bs, base_bs, base_name, has_speed ? speed : 0,
2338 on_error, block_job_cb, bs, &local_err);
2340 error_propagate(errp, local_err);
2344 trace_qmp_block_stream(bs, bs->job);
2347 aio_context_release(aio_context);
2350 void qmp_block_commit(const char *device,
2351 bool has_base, const char *base,
2352 bool has_top, const char *top,
2353 bool has_backing_file, const char *backing_file,
2354 bool has_speed, int64_t speed,
2358 BlockDriverState *bs;
2359 BlockDriverState *base_bs, *top_bs;
2360 AioContext *aio_context;
2361 Error *local_err = NULL;
2362 /* This will be part of the QMP command, if/when the
2363 * BlockdevOnError change for blkmirror makes it in
2365 BlockdevOnError on_error = BLOCKDEV_ON_ERROR_REPORT;
2372 * libvirt relies on the DeviceNotFound error class in order to probe for
2373 * live commit feature versions; for this to work, we must make sure to
2374 * perform the device lookup before any generic errors that may occur in a
2375 * scenario in which all optional arguments are omitted. */
2376 blk = blk_by_name(device);
2378 error_set(errp, ERROR_CLASS_DEVICE_NOT_FOUND,
2379 "Device '%s' not found", device);
2384 aio_context = bdrv_get_aio_context(bs);
2385 aio_context_acquire(aio_context);
2387 if (bdrv_op_is_blocked(bs, BLOCK_OP_TYPE_COMMIT_SOURCE, errp)) {
2391 /* default top_bs is the active layer */
2394 if (has_top && top) {
2395 if (strcmp(bs->filename, top) != 0) {
2396 top_bs = bdrv_find_backing_image(bs, top);
2400 if (top_bs == NULL) {
2401 error_setg(errp, "Top image file %s not found", top ? top : "NULL");
2405 assert(bdrv_get_aio_context(top_bs) == aio_context);
2407 if (has_base && base) {
2408 base_bs = bdrv_find_backing_image(top_bs, base);
2410 base_bs = bdrv_find_base(top_bs);
2413 if (base_bs == NULL) {
2414 error_setg(errp, QERR_BASE_NOT_FOUND, base ? base : "NULL");
2418 assert(bdrv_get_aio_context(base_bs) == aio_context);
2420 if (bdrv_op_is_blocked(base_bs, BLOCK_OP_TYPE_COMMIT_TARGET, errp)) {
2424 /* Do not allow attempts to commit an image into itself */
2425 if (top_bs == base_bs) {
2426 error_setg(errp, "cannot commit an image into itself");
2431 if (has_backing_file) {
2432 error_setg(errp, "'backing-file' specified,"
2433 " but 'top' is the active layer");
2436 commit_active_start(bs, base_bs, speed, on_error, block_job_cb,
2439 commit_start(bs, base_bs, top_bs, speed, on_error, block_job_cb, bs,
2440 has_backing_file ? backing_file : NULL, &local_err);
2442 if (local_err != NULL) {
2443 error_propagate(errp, local_err);
2448 aio_context_release(aio_context);
2451 void qmp_drive_backup(const char *device, const char *target,
2452 bool has_format, const char *format,
2453 enum MirrorSyncMode sync,
2454 bool has_mode, enum NewImageMode mode,
2455 bool has_speed, int64_t speed,
2456 bool has_bitmap, const char *bitmap,
2457 bool has_on_source_error, BlockdevOnError on_source_error,
2458 bool has_on_target_error, BlockdevOnError on_target_error,
2462 BlockDriverState *bs;
2463 BlockDriverState *target_bs;
2464 BlockDriverState *source = NULL;
2465 BdrvDirtyBitmap *bmap = NULL;
2466 AioContext *aio_context;
2467 BlockDriver *drv = NULL;
2468 Error *local_err = NULL;
2476 if (!has_on_source_error) {
2477 on_source_error = BLOCKDEV_ON_ERROR_REPORT;
2479 if (!has_on_target_error) {
2480 on_target_error = BLOCKDEV_ON_ERROR_REPORT;
2483 mode = NEW_IMAGE_MODE_ABSOLUTE_PATHS;
2486 blk = blk_by_name(device);
2488 error_set(errp, ERROR_CLASS_DEVICE_NOT_FOUND,
2489 "Device '%s' not found", device);
2494 aio_context = bdrv_get_aio_context(bs);
2495 aio_context_acquire(aio_context);
2497 /* Although backup_run has this check too, we need to use bs->drv below, so
2498 * do an early check redundantly. */
2499 if (!bdrv_is_inserted(bs)) {
2500 error_setg(errp, QERR_DEVICE_HAS_NO_MEDIUM, device);
2505 format = mode == NEW_IMAGE_MODE_EXISTING ? NULL : bs->drv->format_name;
2508 drv = bdrv_find_format(format);
2510 error_setg(errp, QERR_INVALID_BLOCK_FORMAT, format);
2515 /* Early check to avoid creating target */
2516 if (bdrv_op_is_blocked(bs, BLOCK_OP_TYPE_BACKUP_SOURCE, errp)) {
2520 flags = bs->open_flags | BDRV_O_RDWR;
2522 /* See if we have a backing HD we can use to create our new image
2524 if (sync == MIRROR_SYNC_MODE_TOP) {
2525 source = bs->backing_hd;
2527 sync = MIRROR_SYNC_MODE_FULL;
2530 if (sync == MIRROR_SYNC_MODE_NONE) {
2534 size = bdrv_getlength(bs);
2536 error_setg_errno(errp, -size, "bdrv_getlength failed");
2540 if (mode != NEW_IMAGE_MODE_EXISTING) {
2541 assert(format && drv);
2543 bdrv_img_create(target, format, source->filename,
2544 source->drv->format_name, NULL,
2545 size, flags, &local_err, false);
2547 bdrv_img_create(target, format, NULL, NULL, NULL,
2548 size, flags, &local_err, false);
2553 error_propagate(errp, local_err);
2558 ret = bdrv_open(&target_bs, target, NULL, NULL, flags, drv, &local_err);
2560 error_propagate(errp, local_err);
2564 bdrv_set_aio_context(target_bs, aio_context);
2567 bmap = bdrv_find_dirty_bitmap(bs, bitmap);
2569 error_setg(errp, "Bitmap '%s' could not be found", bitmap);
2574 backup_start(bs, target_bs, speed, sync, bmap,
2575 on_source_error, on_target_error,
2576 block_job_cb, bs, &local_err);
2577 if (local_err != NULL) {
2578 bdrv_unref(target_bs);
2579 error_propagate(errp, local_err);
2584 aio_context_release(aio_context);
2587 BlockDeviceInfoList *qmp_query_named_block_nodes(Error **errp)
2589 return bdrv_named_nodes_list(errp);
2592 void qmp_blockdev_backup(const char *device, const char *target,
2593 enum MirrorSyncMode sync,
2594 bool has_speed, int64_t speed,
2595 bool has_on_source_error,
2596 BlockdevOnError on_source_error,
2597 bool has_on_target_error,
2598 BlockdevOnError on_target_error,
2602 BlockDriverState *bs;
2603 BlockDriverState *target_bs;
2604 Error *local_err = NULL;
2605 AioContext *aio_context;
2610 if (!has_on_source_error) {
2611 on_source_error = BLOCKDEV_ON_ERROR_REPORT;
2613 if (!has_on_target_error) {
2614 on_target_error = BLOCKDEV_ON_ERROR_REPORT;
2617 blk = blk_by_name(device);
2619 error_setg(errp, "Device '%s' not found", device);
2624 aio_context = bdrv_get_aio_context(bs);
2625 aio_context_acquire(aio_context);
2627 blk = blk_by_name(target);
2629 error_setg(errp, "Device '%s' not found", target);
2632 target_bs = blk_bs(blk);
2634 bdrv_ref(target_bs);
2635 bdrv_set_aio_context(target_bs, aio_context);
2636 backup_start(bs, target_bs, speed, sync, NULL, on_source_error,
2637 on_target_error, block_job_cb, bs, &local_err);
2638 if (local_err != NULL) {
2639 bdrv_unref(target_bs);
2640 error_propagate(errp, local_err);
2643 aio_context_release(aio_context);
2646 void qmp_drive_mirror(const char *device, const char *target,
2647 bool has_format, const char *format,
2648 bool has_node_name, const char *node_name,
2649 bool has_replaces, const char *replaces,
2650 enum MirrorSyncMode sync,
2651 bool has_mode, enum NewImageMode mode,
2652 bool has_speed, int64_t speed,
2653 bool has_granularity, uint32_t granularity,
2654 bool has_buf_size, int64_t buf_size,
2655 bool has_on_source_error, BlockdevOnError on_source_error,
2656 bool has_on_target_error, BlockdevOnError on_target_error,
2657 bool has_unmap, bool unmap,
2661 BlockDriverState *bs;
2662 BlockDriverState *source, *target_bs;
2663 AioContext *aio_context;
2664 BlockDriver *drv = NULL;
2665 Error *local_err = NULL;
2666 QDict *options = NULL;
2674 if (!has_on_source_error) {
2675 on_source_error = BLOCKDEV_ON_ERROR_REPORT;
2677 if (!has_on_target_error) {
2678 on_target_error = BLOCKDEV_ON_ERROR_REPORT;
2681 mode = NEW_IMAGE_MODE_ABSOLUTE_PATHS;
2683 if (!has_granularity) {
2686 if (!has_buf_size) {
2693 if (granularity != 0 && (granularity < 512 || granularity > 1048576 * 64)) {
2694 error_setg(errp, QERR_INVALID_PARAMETER_VALUE, "granularity",
2695 "a value in range [512B, 64MB]");
2698 if (granularity & (granularity - 1)) {
2699 error_setg(errp, QERR_INVALID_PARAMETER_VALUE, "granularity",
2704 blk = blk_by_name(device);
2706 error_set(errp, ERROR_CLASS_DEVICE_NOT_FOUND,
2707 "Device '%s' not found", device);
2712 aio_context = bdrv_get_aio_context(bs);
2713 aio_context_acquire(aio_context);
2715 if (!bdrv_is_inserted(bs)) {
2716 error_setg(errp, QERR_DEVICE_HAS_NO_MEDIUM, device);
2721 format = mode == NEW_IMAGE_MODE_EXISTING ? NULL : bs->drv->format_name;
2724 drv = bdrv_find_format(format);
2726 error_setg(errp, QERR_INVALID_BLOCK_FORMAT, format);
2731 if (bdrv_op_is_blocked(bs, BLOCK_OP_TYPE_MIRROR, errp)) {
2735 flags = bs->open_flags | BDRV_O_RDWR;
2736 source = bs->backing_hd;
2737 if (!source && sync == MIRROR_SYNC_MODE_TOP) {
2738 sync = MIRROR_SYNC_MODE_FULL;
2740 if (sync == MIRROR_SYNC_MODE_NONE) {
2744 size = bdrv_getlength(bs);
2746 error_setg_errno(errp, -size, "bdrv_getlength failed");
2751 BlockDriverState *to_replace_bs;
2752 AioContext *replace_aio_context;
2753 int64_t replace_size;
2755 if (!has_node_name) {
2756 error_setg(errp, "a node-name must be provided when replacing a"
2757 " named node of the graph");
2761 to_replace_bs = check_to_replace_node(replaces, &local_err);
2763 if (!to_replace_bs) {
2764 error_propagate(errp, local_err);
2768 replace_aio_context = bdrv_get_aio_context(to_replace_bs);
2769 aio_context_acquire(replace_aio_context);
2770 replace_size = bdrv_getlength(to_replace_bs);
2771 aio_context_release(replace_aio_context);
2773 if (size != replace_size) {
2774 error_setg(errp, "cannot replace image with a mirror image of "
2780 if ((sync == MIRROR_SYNC_MODE_FULL || !source)
2781 && mode != NEW_IMAGE_MODE_EXISTING)
2783 /* create new image w/o backing file */
2784 assert(format && drv);
2785 bdrv_img_create(target, format,
2786 NULL, NULL, NULL, size, flags, &local_err, false);
2789 case NEW_IMAGE_MODE_EXISTING:
2791 case NEW_IMAGE_MODE_ABSOLUTE_PATHS:
2792 /* create new image with backing file */
2793 bdrv_img_create(target, format,
2795 source->drv->format_name,
2796 NULL, size, flags, &local_err, false);
2804 error_propagate(errp, local_err);
2808 if (has_node_name) {
2809 options = qdict_new();
2810 qdict_put(options, "node-name", qstring_from_str(node_name));
2813 /* Mirroring takes care of copy-on-write using the source's backing
2817 ret = bdrv_open(&target_bs, target, NULL, options,
2818 flags | BDRV_O_NO_BACKING, drv, &local_err);
2820 error_propagate(errp, local_err);
2824 bdrv_set_aio_context(target_bs, aio_context);
2826 /* pass the node name to replace to mirror start since it's loose coupling
2827 * and will allow to check whether the node still exist at mirror completion
2829 mirror_start(bs, target_bs,
2830 has_replaces ? replaces : NULL,
2831 speed, granularity, buf_size, sync,
2832 on_source_error, on_target_error,
2834 block_job_cb, bs, &local_err);
2835 if (local_err != NULL) {
2836 bdrv_unref(target_bs);
2837 error_propagate(errp, local_err);
2842 aio_context_release(aio_context);
2845 /* Get the block job for a given device name and acquire its AioContext */
2846 static BlockJob *find_block_job(const char *device, AioContext **aio_context,
2850 BlockDriverState *bs;
2852 blk = blk_by_name(device);
2858 *aio_context = bdrv_get_aio_context(bs);
2859 aio_context_acquire(*aio_context);
2862 aio_context_release(*aio_context);
2869 error_set(errp, ERROR_CLASS_DEVICE_NOT_ACTIVE,
2870 "No active block job on device '%s'", device);
2871 *aio_context = NULL;
2875 void qmp_block_job_set_speed(const char *device, int64_t speed, Error **errp)
2877 AioContext *aio_context;
2878 BlockJob *job = find_block_job(device, &aio_context, errp);
2884 block_job_set_speed(job, speed, errp);
2885 aio_context_release(aio_context);
2888 void qmp_block_job_cancel(const char *device,
2889 bool has_force, bool force, Error **errp)
2891 AioContext *aio_context;
2892 BlockJob *job = find_block_job(device, &aio_context, errp);
2902 if (job->user_paused && !force) {
2903 error_setg(errp, "The block job for device '%s' is currently paused",
2908 trace_qmp_block_job_cancel(job);
2909 block_job_cancel(job);
2911 aio_context_release(aio_context);
2914 void qmp_block_job_pause(const char *device, Error **errp)
2916 AioContext *aio_context;
2917 BlockJob *job = find_block_job(device, &aio_context, errp);
2919 if (!job || job->user_paused) {
2923 job->user_paused = true;
2924 trace_qmp_block_job_pause(job);
2925 block_job_pause(job);
2926 aio_context_release(aio_context);
2929 void qmp_block_job_resume(const char *device, Error **errp)
2931 AioContext *aio_context;
2932 BlockJob *job = find_block_job(device, &aio_context, errp);
2934 if (!job || !job->user_paused) {
2938 job->user_paused = false;
2939 trace_qmp_block_job_resume(job);
2940 block_job_resume(job);
2941 aio_context_release(aio_context);
2944 void qmp_block_job_complete(const char *device, Error **errp)
2946 AioContext *aio_context;
2947 BlockJob *job = find_block_job(device, &aio_context, errp);
2953 trace_qmp_block_job_complete(job);
2954 block_job_complete(job, errp);
2955 aio_context_release(aio_context);
2958 void qmp_change_backing_file(const char *device,
2959 const char *image_node_name,
2960 const char *backing_file,
2964 BlockDriverState *bs = NULL;
2965 AioContext *aio_context;
2966 BlockDriverState *image_bs = NULL;
2967 Error *local_err = NULL;
2972 blk = blk_by_name(device);
2974 error_set(errp, ERROR_CLASS_DEVICE_NOT_FOUND,
2975 "Device '%s' not found", device);
2980 aio_context = bdrv_get_aio_context(bs);
2981 aio_context_acquire(aio_context);
2983 image_bs = bdrv_lookup_bs(NULL, image_node_name, &local_err);
2985 error_propagate(errp, local_err);
2990 error_setg(errp, "image file not found");
2994 if (bdrv_find_base(image_bs) == image_bs) {
2995 error_setg(errp, "not allowing backing file change on an image "
2996 "without a backing file");
3000 /* even though we are not necessarily operating on bs, we need it to
3001 * determine if block ops are currently prohibited on the chain */
3002 if (bdrv_op_is_blocked(bs, BLOCK_OP_TYPE_CHANGE, errp)) {
3006 /* final sanity check */
3007 if (!bdrv_chain_contains(bs, image_bs)) {
3008 error_setg(errp, "'%s' and image file are not in the same chain",
3013 /* if not r/w, reopen to make r/w */
3014 open_flags = image_bs->open_flags;
3015 ro = bdrv_is_read_only(image_bs);
3018 bdrv_reopen(image_bs, open_flags | BDRV_O_RDWR, &local_err);
3020 error_propagate(errp, local_err);
3025 ret = bdrv_change_backing_file(image_bs, backing_file,
3026 image_bs->drv ? image_bs->drv->format_name : "");
3029 error_setg_errno(errp, -ret, "Could not change backing file to '%s'",
3031 /* don't exit here, so we can try to restore open flags if
3036 bdrv_reopen(image_bs, open_flags, &local_err);
3038 error_propagate(errp, local_err); /* will preserve prior errp */
3043 aio_context_release(aio_context);
3046 void qmp_blockdev_add(BlockdevOptions *options, Error **errp)
3048 QmpOutputVisitor *ov = qmp_output_visitor_new();
3052 Error *local_err = NULL;
3054 /* Require an ID in the top level */
3055 if (!options->has_id) {
3056 error_setg(errp, "Block device needs an ID");
3060 /* TODO Sort it out in raw-posix and drive_new(): Reject aio=native with
3061 * cache.direct=false instead of silently switching to aio=threads, except
3062 * when called from drive_new().
3064 * For now, simply forbidding the combination for all drivers will do. */
3065 if (options->has_aio && options->aio == BLOCKDEV_AIO_OPTIONS_NATIVE) {
3066 bool direct = options->has_cache &&
3067 options->cache->has_direct &&
3068 options->cache->direct;
3070 error_setg(errp, "aio=native requires cache.direct=true");
3075 visit_type_BlockdevOptions(qmp_output_get_visitor(ov),
3076 &options, NULL, &local_err);
3078 error_propagate(errp, local_err);
3082 obj = qmp_output_get_qobject(ov);
3083 qdict = qobject_to_qdict(obj);
3085 qdict_flatten(qdict);
3087 blk = blockdev_init(NULL, qdict, &local_err);
3089 error_propagate(errp, local_err);
3093 if (bdrv_key_required(blk_bs(blk))) {
3095 error_setg(errp, "blockdev-add doesn't support encrypted devices");
3100 qmp_output_visitor_cleanup(ov);
3103 BlockJobInfoList *qmp_query_block_jobs(Error **errp)
3105 BlockJobInfoList *head = NULL, **p_next = &head;
3106 BlockDriverState *bs;
3108 for (bs = bdrv_next(NULL); bs; bs = bdrv_next(bs)) {
3109 AioContext *aio_context = bdrv_get_aio_context(bs);
3111 aio_context_acquire(aio_context);
3114 BlockJobInfoList *elem = g_new0(BlockJobInfoList, 1);
3115 elem->value = block_job_query(bs->job);
3117 p_next = &elem->next;
3120 aio_context_release(aio_context);
3126 QemuOptsList qemu_common_drive_opts = {
3128 .head = QTAILQ_HEAD_INITIALIZER(qemu_common_drive_opts.head),
3132 .type = QEMU_OPT_BOOL,
3133 .help = "enable/disable snapshot mode",
3136 .type = QEMU_OPT_STRING,
3137 .help = "discard operation (ignore/off, unmap/on)",
3139 .name = BDRV_OPT_CACHE_WB,
3140 .type = QEMU_OPT_BOOL,
3141 .help = "enables writeback mode for any caches",
3143 .name = BDRV_OPT_CACHE_DIRECT,
3144 .type = QEMU_OPT_BOOL,
3145 .help = "enables use of O_DIRECT (bypass the host page cache)",
3147 .name = BDRV_OPT_CACHE_NO_FLUSH,
3148 .type = QEMU_OPT_BOOL,
3149 .help = "ignore any flush requests for the device",
3152 .type = QEMU_OPT_STRING,
3153 .help = "host AIO implementation (threads, native)",
3156 .type = QEMU_OPT_STRING,
3157 .help = "disk format (raw, qcow2, ...)",
3160 .type = QEMU_OPT_STRING,
3161 .help = "read error action",
3164 .type = QEMU_OPT_STRING,
3165 .help = "write error action",
3167 .name = "read-only",
3168 .type = QEMU_OPT_BOOL,
3169 .help = "open drive file as read-only",
3171 .name = "throttling.iops-total",
3172 .type = QEMU_OPT_NUMBER,
3173 .help = "limit total I/O operations per second",
3175 .name = "throttling.iops-read",
3176 .type = QEMU_OPT_NUMBER,
3177 .help = "limit read operations per second",
3179 .name = "throttling.iops-write",
3180 .type = QEMU_OPT_NUMBER,
3181 .help = "limit write operations per second",
3183 .name = "throttling.bps-total",
3184 .type = QEMU_OPT_NUMBER,
3185 .help = "limit total bytes per second",
3187 .name = "throttling.bps-read",
3188 .type = QEMU_OPT_NUMBER,
3189 .help = "limit read bytes per second",
3191 .name = "throttling.bps-write",
3192 .type = QEMU_OPT_NUMBER,
3193 .help = "limit write bytes per second",
3195 .name = "throttling.iops-total-max",
3196 .type = QEMU_OPT_NUMBER,
3197 .help = "I/O operations burst",
3199 .name = "throttling.iops-read-max",
3200 .type = QEMU_OPT_NUMBER,
3201 .help = "I/O operations read burst",
3203 .name = "throttling.iops-write-max",
3204 .type = QEMU_OPT_NUMBER,
3205 .help = "I/O operations write burst",
3207 .name = "throttling.bps-total-max",
3208 .type = QEMU_OPT_NUMBER,
3209 .help = "total bytes burst",
3211 .name = "throttling.bps-read-max",
3212 .type = QEMU_OPT_NUMBER,
3213 .help = "total bytes read burst",
3215 .name = "throttling.bps-write-max",
3216 .type = QEMU_OPT_NUMBER,
3217 .help = "total bytes write burst",
3219 .name = "throttling.iops-size",
3220 .type = QEMU_OPT_NUMBER,
3221 .help = "when limiting by iops max size of an I/O in bytes",
3223 .name = "throttling.group",
3224 .type = QEMU_OPT_STRING,
3225 .help = "name of the block throttling group",
3227 .name = "copy-on-read",
3228 .type = QEMU_OPT_BOOL,
3229 .help = "copy read data from backing file into image file",
3231 .name = "detect-zeroes",
3232 .type = QEMU_OPT_STRING,
3233 .help = "try to optimize zero writes (off, on, unmap)",
3235 { /* end of list */ }
3239 QemuOptsList qemu_drive_opts = {
3241 .head = QTAILQ_HEAD_INITIALIZER(qemu_drive_opts.head),
3244 * no elements => accept any params
3245 * validation will happen later
3247 { /* end of list */ }