tcg/i386: Detect AVX512
[qemu.git] / blockdev.c
blob42e098b458b1eb057fc6c0a5a077a7603dd638b4
1 /*
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
10 * permission notice:
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
30 * THE SOFTWARE.
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/qdict.h"
39 #include "block/throttle-groups.h"
40 #include "monitor/monitor.h"
41 #include "qemu/error-report.h"
42 #include "qemu/option.h"
43 #include "qemu/qemu-print.h"
44 #include "qemu/config-file.h"
45 #include "qapi/qapi-commands-block.h"
46 #include "qapi/qapi-commands-transaction.h"
47 #include "qapi/qapi-visit-block-core.h"
48 #include "qapi/qmp/qdict.h"
49 #include "qapi/qmp/qnum.h"
50 #include "qapi/qmp/qstring.h"
51 #include "qapi/error.h"
52 #include "qapi/qmp/qerror.h"
53 #include "qapi/qmp/qlist.h"
54 #include "qapi/qobject-output-visitor.h"
55 #include "sysemu/sysemu.h"
56 #include "sysemu/iothread.h"
57 #include "block/block_int.h"
58 #include "block/trace.h"
59 #include "sysemu/runstate.h"
60 #include "sysemu/replay.h"
61 #include "qemu/cutils.h"
62 #include "qemu/help_option.h"
63 #include "qemu/main-loop.h"
64 #include "qemu/throttle-options.h"
66 QTAILQ_HEAD(, BlockDriverState) monitor_bdrv_states =
67 QTAILQ_HEAD_INITIALIZER(monitor_bdrv_states);
69 void bdrv_set_monitor_owned(BlockDriverState *bs)
71 QTAILQ_INSERT_TAIL(&monitor_bdrv_states, bs, monitor_list);
74 static const char *const if_name[IF_COUNT] = {
75 [IF_NONE] = "none",
76 [IF_IDE] = "ide",
77 [IF_SCSI] = "scsi",
78 [IF_FLOPPY] = "floppy",
79 [IF_PFLASH] = "pflash",
80 [IF_MTD] = "mtd",
81 [IF_SD] = "sd",
82 [IF_VIRTIO] = "virtio",
83 [IF_XEN] = "xen",
86 static int if_max_devs[IF_COUNT] = {
88 * Do not change these numbers! They govern how drive option
89 * index maps to unit and bus. That mapping is ABI.
91 * All controllers used to implement if=T drives need to support
92 * if_max_devs[T] units, for any T with if_max_devs[T] != 0.
93 * Otherwise, some index values map to "impossible" bus, unit
94 * values.
96 * For instance, if you change [IF_SCSI] to 255, -drive
97 * if=scsi,index=12 no longer means bus=1,unit=5, but
98 * bus=0,unit=12. With an lsi53c895a controller (7 units max),
99 * the drive can't be set up. Regression.
101 [IF_IDE] = 2,
102 [IF_SCSI] = 7,
106 * Boards may call this to offer board-by-board overrides
107 * of the default, global values.
109 void override_max_devs(BlockInterfaceType type, int max_devs)
111 BlockBackend *blk;
112 DriveInfo *dinfo;
114 if (max_devs <= 0) {
115 return;
118 for (blk = blk_next(NULL); blk; blk = blk_next(blk)) {
119 dinfo = blk_legacy_dinfo(blk);
120 if (dinfo->type == type) {
121 fprintf(stderr, "Cannot override units-per-bus property of"
122 " the %s interface, because a drive of that type has"
123 " already been added.\n", if_name[type]);
124 g_assert_not_reached();
128 if_max_devs[type] = max_devs;
132 * We automatically delete the drive when a device using it gets
133 * unplugged. Questionable feature, but we can't just drop it.
134 * Device models call blockdev_mark_auto_del() to schedule the
135 * automatic deletion, and generic qdev code calls blockdev_auto_del()
136 * when deletion is actually safe.
138 void blockdev_mark_auto_del(BlockBackend *blk)
140 DriveInfo *dinfo = blk_legacy_dinfo(blk);
141 BlockJob *job;
143 if (!dinfo) {
144 return;
147 for (job = block_job_next(NULL); job; job = block_job_next(job)) {
148 if (block_job_has_bdrv(job, blk_bs(blk))) {
149 AioContext *aio_context = job->job.aio_context;
150 aio_context_acquire(aio_context);
152 job_cancel(&job->job, false);
154 aio_context_release(aio_context);
158 dinfo->auto_del = 1;
161 void blockdev_auto_del(BlockBackend *blk)
163 DriveInfo *dinfo = blk_legacy_dinfo(blk);
165 if (dinfo && dinfo->auto_del) {
166 monitor_remove_blk(blk);
167 blk_unref(blk);
171 static int drive_index_to_bus_id(BlockInterfaceType type, int index)
173 int max_devs = if_max_devs[type];
174 return max_devs ? index / max_devs : 0;
177 static int drive_index_to_unit_id(BlockInterfaceType type, int index)
179 int max_devs = if_max_devs[type];
180 return max_devs ? index % max_devs : index;
183 QemuOpts *drive_add(BlockInterfaceType type, int index, const char *file,
184 const char *optstr)
186 QemuOpts *opts;
188 opts = qemu_opts_parse_noisily(qemu_find_opts("drive"), optstr, false);
189 if (!opts) {
190 return NULL;
192 if (type != IF_DEFAULT) {
193 qemu_opt_set(opts, "if", if_name[type], &error_abort);
195 if (index >= 0) {
196 qemu_opt_set_number(opts, "index", index, &error_abort);
198 if (file)
199 qemu_opt_set(opts, "file", file, &error_abort);
200 return opts;
203 DriveInfo *drive_get(BlockInterfaceType type, int bus, int unit)
205 BlockBackend *blk;
206 DriveInfo *dinfo;
208 for (blk = blk_next(NULL); blk; blk = blk_next(blk)) {
209 dinfo = blk_legacy_dinfo(blk);
210 if (dinfo && dinfo->type == type
211 && dinfo->bus == bus && dinfo->unit == unit) {
212 return dinfo;
216 return NULL;
220 * Check board claimed all -drive that are meant to be claimed.
221 * Fatal error if any remain unclaimed.
223 void drive_check_orphaned(void)
225 BlockBackend *blk;
226 DriveInfo *dinfo;
227 Location loc;
228 bool orphans = false;
230 for (blk = blk_next(NULL); blk; blk = blk_next(blk)) {
231 dinfo = blk_legacy_dinfo(blk);
233 * Ignore default drives, because we create certain default
234 * drives unconditionally, then leave them unclaimed. Not the
235 * users fault.
236 * Ignore IF_VIRTIO, because it gets desugared into -device,
237 * so we can leave failing to -device.
238 * Ignore IF_NONE, because leaving unclaimed IF_NONE remains
239 * available for device_add is a feature.
241 if (dinfo->is_default || dinfo->type == IF_VIRTIO
242 || dinfo->type == IF_NONE) {
243 continue;
245 if (!blk_get_attached_dev(blk)) {
246 loc_push_none(&loc);
247 qemu_opts_loc_restore(dinfo->opts);
248 error_report("machine type does not support"
249 " if=%s,bus=%d,unit=%d",
250 if_name[dinfo->type], dinfo->bus, dinfo->unit);
251 loc_pop(&loc);
252 orphans = true;
256 if (orphans) {
257 exit(1);
261 DriveInfo *drive_get_by_index(BlockInterfaceType type, int index)
263 return drive_get(type,
264 drive_index_to_bus_id(type, index),
265 drive_index_to_unit_id(type, index));
268 int drive_get_max_bus(BlockInterfaceType type)
270 int max_bus;
271 BlockBackend *blk;
272 DriveInfo *dinfo;
274 max_bus = -1;
275 for (blk = blk_next(NULL); blk; blk = blk_next(blk)) {
276 dinfo = blk_legacy_dinfo(blk);
277 if (dinfo && dinfo->type == type && dinfo->bus > max_bus) {
278 max_bus = dinfo->bus;
281 return max_bus;
284 static void bdrv_format_print(void *opaque, const char *name)
286 qemu_printf(" %s", name);
289 typedef struct {
290 QEMUBH *bh;
291 BlockDriverState *bs;
292 } BDRVPutRefBH;
294 static int parse_block_error_action(const char *buf, bool is_read, Error **errp)
296 if (!strcmp(buf, "ignore")) {
297 return BLOCKDEV_ON_ERROR_IGNORE;
298 } else if (!is_read && !strcmp(buf, "enospc")) {
299 return BLOCKDEV_ON_ERROR_ENOSPC;
300 } else if (!strcmp(buf, "stop")) {
301 return BLOCKDEV_ON_ERROR_STOP;
302 } else if (!strcmp(buf, "report")) {
303 return BLOCKDEV_ON_ERROR_REPORT;
304 } else {
305 error_setg(errp, "'%s' invalid %s error action",
306 buf, is_read ? "read" : "write");
307 return -1;
311 static bool parse_stats_intervals(BlockAcctStats *stats, QList *intervals,
312 Error **errp)
314 const QListEntry *entry;
315 for (entry = qlist_first(intervals); entry; entry = qlist_next(entry)) {
316 switch (qobject_type(entry->value)) {
318 case QTYPE_QSTRING: {
319 unsigned long long length;
320 const char *str = qstring_get_str(qobject_to(QString,
321 entry->value));
322 if (parse_uint_full(str, &length, 10) == 0 &&
323 length > 0 && length <= UINT_MAX) {
324 block_acct_add_interval(stats, (unsigned) length);
325 } else {
326 error_setg(errp, "Invalid interval length: %s", str);
327 return false;
329 break;
332 case QTYPE_QNUM: {
333 int64_t length = qnum_get_int(qobject_to(QNum, entry->value));
335 if (length > 0 && length <= UINT_MAX) {
336 block_acct_add_interval(stats, (unsigned) length);
337 } else {
338 error_setg(errp, "Invalid interval length: %" PRId64, length);
339 return false;
341 break;
344 default:
345 error_setg(errp, "The specification of stats-intervals is invalid");
346 return false;
349 return true;
352 typedef enum { MEDIA_DISK, MEDIA_CDROM } DriveMediaType;
354 /* All parameters but @opts are optional and may be set to NULL. */
355 static void extract_common_blockdev_options(QemuOpts *opts, int *bdrv_flags,
356 const char **throttling_group, ThrottleConfig *throttle_cfg,
357 BlockdevDetectZeroesOptions *detect_zeroes, Error **errp)
359 Error *local_error = NULL;
360 const char *aio;
362 if (bdrv_flags) {
363 if (qemu_opt_get_bool(opts, "copy-on-read", false)) {
364 *bdrv_flags |= BDRV_O_COPY_ON_READ;
367 if ((aio = qemu_opt_get(opts, "aio")) != NULL) {
368 if (bdrv_parse_aio(aio, bdrv_flags) < 0) {
369 error_setg(errp, "invalid aio option");
370 return;
375 /* disk I/O throttling */
376 if (throttling_group) {
377 *throttling_group = qemu_opt_get(opts, "throttling.group");
380 if (throttle_cfg) {
381 throttle_config_init(throttle_cfg);
382 throttle_cfg->buckets[THROTTLE_BPS_TOTAL].avg =
383 qemu_opt_get_number(opts, "throttling.bps-total", 0);
384 throttle_cfg->buckets[THROTTLE_BPS_READ].avg =
385 qemu_opt_get_number(opts, "throttling.bps-read", 0);
386 throttle_cfg->buckets[THROTTLE_BPS_WRITE].avg =
387 qemu_opt_get_number(opts, "throttling.bps-write", 0);
388 throttle_cfg->buckets[THROTTLE_OPS_TOTAL].avg =
389 qemu_opt_get_number(opts, "throttling.iops-total", 0);
390 throttle_cfg->buckets[THROTTLE_OPS_READ].avg =
391 qemu_opt_get_number(opts, "throttling.iops-read", 0);
392 throttle_cfg->buckets[THROTTLE_OPS_WRITE].avg =
393 qemu_opt_get_number(opts, "throttling.iops-write", 0);
395 throttle_cfg->buckets[THROTTLE_BPS_TOTAL].max =
396 qemu_opt_get_number(opts, "throttling.bps-total-max", 0);
397 throttle_cfg->buckets[THROTTLE_BPS_READ].max =
398 qemu_opt_get_number(opts, "throttling.bps-read-max", 0);
399 throttle_cfg->buckets[THROTTLE_BPS_WRITE].max =
400 qemu_opt_get_number(opts, "throttling.bps-write-max", 0);
401 throttle_cfg->buckets[THROTTLE_OPS_TOTAL].max =
402 qemu_opt_get_number(opts, "throttling.iops-total-max", 0);
403 throttle_cfg->buckets[THROTTLE_OPS_READ].max =
404 qemu_opt_get_number(opts, "throttling.iops-read-max", 0);
405 throttle_cfg->buckets[THROTTLE_OPS_WRITE].max =
406 qemu_opt_get_number(opts, "throttling.iops-write-max", 0);
408 throttle_cfg->buckets[THROTTLE_BPS_TOTAL].burst_length =
409 qemu_opt_get_number(opts, "throttling.bps-total-max-length", 1);
410 throttle_cfg->buckets[THROTTLE_BPS_READ].burst_length =
411 qemu_opt_get_number(opts, "throttling.bps-read-max-length", 1);
412 throttle_cfg->buckets[THROTTLE_BPS_WRITE].burst_length =
413 qemu_opt_get_number(opts, "throttling.bps-write-max-length", 1);
414 throttle_cfg->buckets[THROTTLE_OPS_TOTAL].burst_length =
415 qemu_opt_get_number(opts, "throttling.iops-total-max-length", 1);
416 throttle_cfg->buckets[THROTTLE_OPS_READ].burst_length =
417 qemu_opt_get_number(opts, "throttling.iops-read-max-length", 1);
418 throttle_cfg->buckets[THROTTLE_OPS_WRITE].burst_length =
419 qemu_opt_get_number(opts, "throttling.iops-write-max-length", 1);
421 throttle_cfg->op_size =
422 qemu_opt_get_number(opts, "throttling.iops-size", 0);
424 if (!throttle_is_valid(throttle_cfg, errp)) {
425 return;
429 if (detect_zeroes) {
430 *detect_zeroes =
431 qapi_enum_parse(&BlockdevDetectZeroesOptions_lookup,
432 qemu_opt_get(opts, "detect-zeroes"),
433 BLOCKDEV_DETECT_ZEROES_OPTIONS_OFF,
434 &local_error);
435 if (local_error) {
436 error_propagate(errp, local_error);
437 return;
442 /* Takes the ownership of bs_opts */
443 static BlockBackend *blockdev_init(const char *file, QDict *bs_opts,
444 Error **errp)
446 const char *buf;
447 int bdrv_flags = 0;
448 int on_read_error, on_write_error;
449 bool account_invalid, account_failed;
450 bool writethrough, read_only;
451 BlockBackend *blk;
452 BlockDriverState *bs;
453 ThrottleConfig cfg;
454 int snapshot = 0;
455 Error *error = NULL;
456 QemuOpts *opts;
457 QDict *interval_dict = NULL;
458 QList *interval_list = NULL;
459 const char *id;
460 BlockdevDetectZeroesOptions detect_zeroes =
461 BLOCKDEV_DETECT_ZEROES_OPTIONS_OFF;
462 const char *throttling_group = NULL;
464 /* Check common options by copying from bs_opts to opts, all other options
465 * stay in bs_opts for processing by bdrv_open(). */
466 id = qdict_get_try_str(bs_opts, "id");
467 opts = qemu_opts_create(&qemu_common_drive_opts, id, 1, errp);
468 if (!opts) {
469 goto err_no_opts;
472 if (!qemu_opts_absorb_qdict(opts, bs_opts, errp)) {
473 goto early_err;
476 if (id) {
477 qdict_del(bs_opts, "id");
480 /* extract parameters */
481 snapshot = qemu_opt_get_bool(opts, "snapshot", 0);
483 account_invalid = qemu_opt_get_bool(opts, "stats-account-invalid", true);
484 account_failed = qemu_opt_get_bool(opts, "stats-account-failed", true);
486 writethrough = !qemu_opt_get_bool(opts, BDRV_OPT_CACHE_WB, true);
488 id = qemu_opts_id(opts);
490 qdict_extract_subqdict(bs_opts, &interval_dict, "stats-intervals.");
491 qdict_array_split(interval_dict, &interval_list);
493 if (qdict_size(interval_dict) != 0) {
494 error_setg(errp, "Invalid option stats-intervals.%s",
495 qdict_first(interval_dict)->key);
496 goto early_err;
499 extract_common_blockdev_options(opts, &bdrv_flags, &throttling_group, &cfg,
500 &detect_zeroes, &error);
501 if (error) {
502 error_propagate(errp, error);
503 goto early_err;
506 if ((buf = qemu_opt_get(opts, "format")) != NULL) {
507 if (is_help_option(buf)) {
508 qemu_printf("Supported formats:");
509 bdrv_iterate_format(bdrv_format_print, NULL, false);
510 qemu_printf("\nSupported formats (read-only):");
511 bdrv_iterate_format(bdrv_format_print, NULL, true);
512 qemu_printf("\n");
513 goto early_err;
516 if (qdict_haskey(bs_opts, "driver")) {
517 error_setg(errp, "Cannot specify both 'driver' and 'format'");
518 goto early_err;
520 qdict_put_str(bs_opts, "driver", buf);
523 on_write_error = BLOCKDEV_ON_ERROR_ENOSPC;
524 if ((buf = qemu_opt_get(opts, "werror")) != NULL) {
525 on_write_error = parse_block_error_action(buf, 0, &error);
526 if (error) {
527 error_propagate(errp, error);
528 goto early_err;
532 on_read_error = BLOCKDEV_ON_ERROR_REPORT;
533 if ((buf = qemu_opt_get(opts, "rerror")) != NULL) {
534 on_read_error = parse_block_error_action(buf, 1, &error);
535 if (error) {
536 error_propagate(errp, error);
537 goto early_err;
541 if (snapshot) {
542 bdrv_flags |= BDRV_O_SNAPSHOT;
545 read_only = qemu_opt_get_bool(opts, BDRV_OPT_READ_ONLY, false);
547 /* init */
548 if ((!file || !*file) && !qdict_size(bs_opts)) {
549 BlockBackendRootState *blk_rs;
551 blk = blk_new(qemu_get_aio_context(), 0, BLK_PERM_ALL);
552 blk_rs = blk_get_root_state(blk);
553 blk_rs->open_flags = bdrv_flags | (read_only ? 0 : BDRV_O_RDWR);
554 blk_rs->detect_zeroes = detect_zeroes;
556 qobject_unref(bs_opts);
557 } else {
558 if (file && !*file) {
559 file = NULL;
562 /* bdrv_open() defaults to the values in bdrv_flags (for compatibility
563 * with other callers) rather than what we want as the real defaults.
564 * Apply the defaults here instead. */
565 qdict_set_default_str(bs_opts, BDRV_OPT_CACHE_DIRECT, "off");
566 qdict_set_default_str(bs_opts, BDRV_OPT_CACHE_NO_FLUSH, "off");
567 qdict_set_default_str(bs_opts, BDRV_OPT_READ_ONLY,
568 read_only ? "on" : "off");
569 qdict_set_default_str(bs_opts, BDRV_OPT_AUTO_READ_ONLY, "on");
570 assert((bdrv_flags & BDRV_O_CACHE_MASK) == 0);
572 if (runstate_check(RUN_STATE_INMIGRATE)) {
573 bdrv_flags |= BDRV_O_INACTIVE;
576 blk = blk_new_open(file, NULL, bs_opts, bdrv_flags, errp);
577 if (!blk) {
578 goto err_no_bs_opts;
580 bs = blk_bs(blk);
582 bs->detect_zeroes = detect_zeroes;
584 block_acct_setup(blk_get_stats(blk), account_invalid, account_failed);
586 if (!parse_stats_intervals(blk_get_stats(blk), interval_list, errp)) {
587 blk_unref(blk);
588 blk = NULL;
589 goto err_no_bs_opts;
593 /* disk I/O throttling */
594 if (throttle_enabled(&cfg)) {
595 if (!throttling_group) {
596 throttling_group = id;
598 blk_io_limits_enable(blk, throttling_group);
599 blk_set_io_limits(blk, &cfg);
602 blk_set_enable_write_cache(blk, !writethrough);
603 blk_set_on_error(blk, on_read_error, on_write_error);
605 if (!monitor_add_blk(blk, id, errp)) {
606 blk_unref(blk);
607 blk = NULL;
608 goto err_no_bs_opts;
611 err_no_bs_opts:
612 qemu_opts_del(opts);
613 qobject_unref(interval_dict);
614 qobject_unref(interval_list);
615 return blk;
617 early_err:
618 qemu_opts_del(opts);
619 qobject_unref(interval_dict);
620 qobject_unref(interval_list);
621 err_no_opts:
622 qobject_unref(bs_opts);
623 return NULL;
626 /* Takes the ownership of bs_opts */
627 BlockDriverState *bds_tree_init(QDict *bs_opts, Error **errp)
629 int bdrv_flags = 0;
631 /* bdrv_open() defaults to the values in bdrv_flags (for compatibility
632 * with other callers) rather than what we want as the real defaults.
633 * Apply the defaults here instead. */
634 qdict_set_default_str(bs_opts, BDRV_OPT_CACHE_DIRECT, "off");
635 qdict_set_default_str(bs_opts, BDRV_OPT_CACHE_NO_FLUSH, "off");
636 qdict_set_default_str(bs_opts, BDRV_OPT_READ_ONLY, "off");
638 if (runstate_check(RUN_STATE_INMIGRATE)) {
639 bdrv_flags |= BDRV_O_INACTIVE;
642 return bdrv_open(NULL, NULL, bs_opts, bdrv_flags, errp);
645 void blockdev_close_all_bdrv_states(void)
647 BlockDriverState *bs, *next_bs;
649 QTAILQ_FOREACH_SAFE(bs, &monitor_bdrv_states, monitor_list, next_bs) {
650 AioContext *ctx = bdrv_get_aio_context(bs);
652 aio_context_acquire(ctx);
653 bdrv_unref(bs);
654 aio_context_release(ctx);
658 /* Iterates over the list of monitor-owned BlockDriverStates */
659 BlockDriverState *bdrv_next_monitor_owned(BlockDriverState *bs)
661 return bs ? QTAILQ_NEXT(bs, monitor_list)
662 : QTAILQ_FIRST(&monitor_bdrv_states);
665 static bool qemu_opt_rename(QemuOpts *opts, const char *from, const char *to,
666 Error **errp)
668 const char *value;
670 value = qemu_opt_get(opts, from);
671 if (value) {
672 if (qemu_opt_find(opts, to)) {
673 error_setg(errp, "'%s' and its alias '%s' can't be used at the "
674 "same time", to, from);
675 return false;
679 /* rename all items in opts */
680 while ((value = qemu_opt_get(opts, from))) {
681 qemu_opt_set(opts, to, value, &error_abort);
682 qemu_opt_unset(opts, from);
684 return true;
687 QemuOptsList qemu_legacy_drive_opts = {
688 .name = "drive",
689 .head = QTAILQ_HEAD_INITIALIZER(qemu_legacy_drive_opts.head),
690 .desc = {
692 .name = "bus",
693 .type = QEMU_OPT_NUMBER,
694 .help = "bus number",
696 .name = "unit",
697 .type = QEMU_OPT_NUMBER,
698 .help = "unit number (i.e. lun for scsi)",
700 .name = "index",
701 .type = QEMU_OPT_NUMBER,
702 .help = "index number",
704 .name = "media",
705 .type = QEMU_OPT_STRING,
706 .help = "media type (disk, cdrom)",
708 .name = "if",
709 .type = QEMU_OPT_STRING,
710 .help = "interface (ide, scsi, sd, mtd, floppy, pflash, virtio)",
712 .name = "file",
713 .type = QEMU_OPT_STRING,
714 .help = "file name",
717 /* Options that are passed on, but have special semantics with -drive */
719 .name = BDRV_OPT_READ_ONLY,
720 .type = QEMU_OPT_BOOL,
721 .help = "open drive file as read-only",
723 .name = "rerror",
724 .type = QEMU_OPT_STRING,
725 .help = "read error action",
727 .name = "werror",
728 .type = QEMU_OPT_STRING,
729 .help = "write error action",
731 .name = "copy-on-read",
732 .type = QEMU_OPT_BOOL,
733 .help = "copy read data from backing file into image file",
736 { /* end of list */ }
740 DriveInfo *drive_new(QemuOpts *all_opts, BlockInterfaceType block_default_type,
741 Error **errp)
743 const char *value;
744 BlockBackend *blk;
745 DriveInfo *dinfo = NULL;
746 QDict *bs_opts;
747 QemuOpts *legacy_opts;
748 DriveMediaType media = MEDIA_DISK;
749 BlockInterfaceType type;
750 int max_devs, bus_id, unit_id, index;
751 const char *werror, *rerror;
752 bool read_only = false;
753 bool copy_on_read;
754 const char *filename;
755 int i;
757 /* Change legacy command line options into QMP ones */
758 static const struct {
759 const char *from;
760 const char *to;
761 } opt_renames[] = {
762 { "iops", "throttling.iops-total" },
763 { "iops_rd", "throttling.iops-read" },
764 { "iops_wr", "throttling.iops-write" },
766 { "bps", "throttling.bps-total" },
767 { "bps_rd", "throttling.bps-read" },
768 { "bps_wr", "throttling.bps-write" },
770 { "iops_max", "throttling.iops-total-max" },
771 { "iops_rd_max", "throttling.iops-read-max" },
772 { "iops_wr_max", "throttling.iops-write-max" },
774 { "bps_max", "throttling.bps-total-max" },
775 { "bps_rd_max", "throttling.bps-read-max" },
776 { "bps_wr_max", "throttling.bps-write-max" },
778 { "iops_size", "throttling.iops-size" },
780 { "group", "throttling.group" },
782 { "readonly", BDRV_OPT_READ_ONLY },
785 for (i = 0; i < ARRAY_SIZE(opt_renames); i++) {
786 if (!qemu_opt_rename(all_opts, opt_renames[i].from,
787 opt_renames[i].to, errp)) {
788 return NULL;
792 value = qemu_opt_get(all_opts, "cache");
793 if (value) {
794 int flags = 0;
795 bool writethrough;
797 if (bdrv_parse_cache_mode(value, &flags, &writethrough) != 0) {
798 error_setg(errp, "invalid cache option");
799 return NULL;
802 /* Specific options take precedence */
803 if (!qemu_opt_get(all_opts, BDRV_OPT_CACHE_WB)) {
804 qemu_opt_set_bool(all_opts, BDRV_OPT_CACHE_WB,
805 !writethrough, &error_abort);
807 if (!qemu_opt_get(all_opts, BDRV_OPT_CACHE_DIRECT)) {
808 qemu_opt_set_bool(all_opts, BDRV_OPT_CACHE_DIRECT,
809 !!(flags & BDRV_O_NOCACHE), &error_abort);
811 if (!qemu_opt_get(all_opts, BDRV_OPT_CACHE_NO_FLUSH)) {
812 qemu_opt_set_bool(all_opts, BDRV_OPT_CACHE_NO_FLUSH,
813 !!(flags & BDRV_O_NO_FLUSH), &error_abort);
815 qemu_opt_unset(all_opts, "cache");
818 /* Get a QDict for processing the options */
819 bs_opts = qdict_new();
820 qemu_opts_to_qdict(all_opts, bs_opts);
822 legacy_opts = qemu_opts_create(&qemu_legacy_drive_opts, NULL, 0,
823 &error_abort);
824 if (!qemu_opts_absorb_qdict(legacy_opts, bs_opts, errp)) {
825 goto fail;
828 /* Media type */
829 value = qemu_opt_get(legacy_opts, "media");
830 if (value) {
831 if (!strcmp(value, "disk")) {
832 media = MEDIA_DISK;
833 } else if (!strcmp(value, "cdrom")) {
834 media = MEDIA_CDROM;
835 read_only = true;
836 } else {
837 error_setg(errp, "'%s' invalid media", value);
838 goto fail;
842 /* copy-on-read is disabled with a warning for read-only devices */
843 read_only |= qemu_opt_get_bool(legacy_opts, BDRV_OPT_READ_ONLY, false);
844 copy_on_read = qemu_opt_get_bool(legacy_opts, "copy-on-read", false);
846 if (read_only && copy_on_read) {
847 warn_report("disabling copy-on-read on read-only drive");
848 copy_on_read = false;
851 qdict_put_str(bs_opts, BDRV_OPT_READ_ONLY, read_only ? "on" : "off");
852 qdict_put_str(bs_opts, "copy-on-read", copy_on_read ? "on" : "off");
854 /* Controller type */
855 value = qemu_opt_get(legacy_opts, "if");
856 if (value) {
857 for (type = 0;
858 type < IF_COUNT && strcmp(value, if_name[type]);
859 type++) {
861 if (type == IF_COUNT) {
862 error_setg(errp, "unsupported bus type '%s'", value);
863 goto fail;
865 } else {
866 type = block_default_type;
869 /* Device address specified by bus/unit or index.
870 * If none was specified, try to find the first free one. */
871 bus_id = qemu_opt_get_number(legacy_opts, "bus", 0);
872 unit_id = qemu_opt_get_number(legacy_opts, "unit", -1);
873 index = qemu_opt_get_number(legacy_opts, "index", -1);
875 max_devs = if_max_devs[type];
877 if (index != -1) {
878 if (bus_id != 0 || unit_id != -1) {
879 error_setg(errp, "index cannot be used with bus and unit");
880 goto fail;
882 bus_id = drive_index_to_bus_id(type, index);
883 unit_id = drive_index_to_unit_id(type, index);
886 if (unit_id == -1) {
887 unit_id = 0;
888 while (drive_get(type, bus_id, unit_id) != NULL) {
889 unit_id++;
890 if (max_devs && unit_id >= max_devs) {
891 unit_id -= max_devs;
892 bus_id++;
897 if (max_devs && unit_id >= max_devs) {
898 error_setg(errp, "unit %d too big (max is %d)", unit_id, max_devs - 1);
899 goto fail;
902 if (drive_get(type, bus_id, unit_id) != NULL) {
903 error_setg(errp, "drive with bus=%d, unit=%d (index=%d) exists",
904 bus_id, unit_id, index);
905 goto fail;
908 /* no id supplied -> create one */
909 if (qemu_opts_id(all_opts) == NULL) {
910 char *new_id;
911 const char *mediastr = "";
912 if (type == IF_IDE || type == IF_SCSI) {
913 mediastr = (media == MEDIA_CDROM) ? "-cd" : "-hd";
915 if (max_devs) {
916 new_id = g_strdup_printf("%s%i%s%i", if_name[type], bus_id,
917 mediastr, unit_id);
918 } else {
919 new_id = g_strdup_printf("%s%s%i", if_name[type],
920 mediastr, unit_id);
922 qdict_put_str(bs_opts, "id", new_id);
923 g_free(new_id);
926 /* Add virtio block device */
927 if (type == IF_VIRTIO) {
928 QemuOpts *devopts;
929 devopts = qemu_opts_create(qemu_find_opts("device"), NULL, 0,
930 &error_abort);
931 qemu_opt_set(devopts, "driver", "virtio-blk", &error_abort);
932 qemu_opt_set(devopts, "drive", qdict_get_str(bs_opts, "id"),
933 &error_abort);
936 filename = qemu_opt_get(legacy_opts, "file");
938 /* Check werror/rerror compatibility with if=... */
939 werror = qemu_opt_get(legacy_opts, "werror");
940 if (werror != NULL) {
941 if (type != IF_IDE && type != IF_SCSI && type != IF_VIRTIO &&
942 type != IF_NONE) {
943 error_setg(errp, "werror is not supported by this bus type");
944 goto fail;
946 qdict_put_str(bs_opts, "werror", werror);
949 rerror = qemu_opt_get(legacy_opts, "rerror");
950 if (rerror != NULL) {
951 if (type != IF_IDE && type != IF_VIRTIO && type != IF_SCSI &&
952 type != IF_NONE) {
953 error_setg(errp, "rerror is not supported by this bus type");
954 goto fail;
956 qdict_put_str(bs_opts, "rerror", rerror);
959 /* Actual block device init: Functionality shared with blockdev-add */
960 blk = blockdev_init(filename, bs_opts, errp);
961 bs_opts = NULL;
962 if (!blk) {
963 goto fail;
966 /* Create legacy DriveInfo */
967 dinfo = g_malloc0(sizeof(*dinfo));
968 dinfo->opts = all_opts;
970 dinfo->type = type;
971 dinfo->bus = bus_id;
972 dinfo->unit = unit_id;
974 blk_set_legacy_dinfo(blk, dinfo);
976 switch(type) {
977 case IF_IDE:
978 case IF_SCSI:
979 case IF_XEN:
980 case IF_NONE:
981 dinfo->media_cd = media == MEDIA_CDROM;
982 break;
983 default:
984 break;
987 fail:
988 qemu_opts_del(legacy_opts);
989 qobject_unref(bs_opts);
990 return dinfo;
993 static BlockDriverState *qmp_get_root_bs(const char *name, Error **errp)
995 BlockDriverState *bs;
997 bs = bdrv_lookup_bs(name, name, errp);
998 if (bs == NULL) {
999 return NULL;
1002 if (!bdrv_is_root_node(bs)) {
1003 error_setg(errp, "Need a root block node");
1004 return NULL;
1007 if (!bdrv_is_inserted(bs)) {
1008 error_setg(errp, "Device has no medium");
1009 return NULL;
1012 return bs;
1015 static void blockdev_do_action(TransactionAction *action, Error **errp)
1017 TransactionActionList list;
1019 list.value = action;
1020 list.next = NULL;
1021 qmp_transaction(&list, false, NULL, errp);
1024 void qmp_blockdev_snapshot_sync(bool has_device, const char *device,
1025 bool has_node_name, const char *node_name,
1026 const char *snapshot_file,
1027 bool has_snapshot_node_name,
1028 const char *snapshot_node_name,
1029 bool has_format, const char *format,
1030 bool has_mode, NewImageMode mode, Error **errp)
1032 BlockdevSnapshotSync snapshot = {
1033 .has_device = has_device,
1034 .device = (char *) device,
1035 .has_node_name = has_node_name,
1036 .node_name = (char *) node_name,
1037 .snapshot_file = (char *) snapshot_file,
1038 .has_snapshot_node_name = has_snapshot_node_name,
1039 .snapshot_node_name = (char *) snapshot_node_name,
1040 .has_format = has_format,
1041 .format = (char *) format,
1042 .has_mode = has_mode,
1043 .mode = mode,
1045 TransactionAction action = {
1046 .type = TRANSACTION_ACTION_KIND_BLOCKDEV_SNAPSHOT_SYNC,
1047 .u.blockdev_snapshot_sync.data = &snapshot,
1049 blockdev_do_action(&action, errp);
1052 void qmp_blockdev_snapshot(const char *node, const char *overlay,
1053 Error **errp)
1055 BlockdevSnapshot snapshot_data = {
1056 .node = (char *) node,
1057 .overlay = (char *) overlay
1059 TransactionAction action = {
1060 .type = TRANSACTION_ACTION_KIND_BLOCKDEV_SNAPSHOT,
1061 .u.blockdev_snapshot.data = &snapshot_data,
1063 blockdev_do_action(&action, errp);
1066 void qmp_blockdev_snapshot_internal_sync(const char *device,
1067 const char *name,
1068 Error **errp)
1070 BlockdevSnapshotInternal snapshot = {
1071 .device = (char *) device,
1072 .name = (char *) name
1074 TransactionAction action = {
1075 .type = TRANSACTION_ACTION_KIND_BLOCKDEV_SNAPSHOT_INTERNAL_SYNC,
1076 .u.blockdev_snapshot_internal_sync.data = &snapshot,
1078 blockdev_do_action(&action, errp);
1081 SnapshotInfo *qmp_blockdev_snapshot_delete_internal_sync(const char *device,
1082 bool has_id,
1083 const char *id,
1084 bool has_name,
1085 const char *name,
1086 Error **errp)
1088 BlockDriverState *bs;
1089 AioContext *aio_context;
1090 QEMUSnapshotInfo sn;
1091 Error *local_err = NULL;
1092 SnapshotInfo *info = NULL;
1093 int ret;
1095 bs = qmp_get_root_bs(device, errp);
1096 if (!bs) {
1097 return NULL;
1099 aio_context = bdrv_get_aio_context(bs);
1100 aio_context_acquire(aio_context);
1102 if (!has_id) {
1103 id = NULL;
1106 if (!has_name) {
1107 name = NULL;
1110 if (!id && !name) {
1111 error_setg(errp, "Name or id must be provided");
1112 goto out_aio_context;
1115 if (bdrv_op_is_blocked(bs, BLOCK_OP_TYPE_INTERNAL_SNAPSHOT_DELETE, errp)) {
1116 goto out_aio_context;
1119 ret = bdrv_snapshot_find_by_id_and_name(bs, id, name, &sn, &local_err);
1120 if (local_err) {
1121 error_propagate(errp, local_err);
1122 goto out_aio_context;
1124 if (!ret) {
1125 error_setg(errp,
1126 "Snapshot with id '%s' and name '%s' does not exist on "
1127 "device '%s'",
1128 STR_OR_NULL(id), STR_OR_NULL(name), device);
1129 goto out_aio_context;
1132 bdrv_snapshot_delete(bs, id, name, &local_err);
1133 if (local_err) {
1134 error_propagate(errp, local_err);
1135 goto out_aio_context;
1138 aio_context_release(aio_context);
1140 info = g_new0(SnapshotInfo, 1);
1141 info->id = g_strdup(sn.id_str);
1142 info->name = g_strdup(sn.name);
1143 info->date_nsec = sn.date_nsec;
1144 info->date_sec = sn.date_sec;
1145 info->vm_state_size = sn.vm_state_size;
1146 info->vm_clock_nsec = sn.vm_clock_nsec % 1000000000;
1147 info->vm_clock_sec = sn.vm_clock_nsec / 1000000000;
1148 if (sn.icount != -1ULL) {
1149 info->icount = sn.icount;
1150 info->has_icount = true;
1153 return info;
1155 out_aio_context:
1156 aio_context_release(aio_context);
1157 return NULL;
1160 /* New and old BlockDriverState structs for atomic group operations */
1162 typedef struct BlkActionState BlkActionState;
1165 * BlkActionOps:
1166 * Table of operations that define an Action.
1168 * @instance_size: Size of state struct, in bytes.
1169 * @prepare: Prepare the work, must NOT be NULL.
1170 * @commit: Commit the changes, can be NULL.
1171 * @abort: Abort the changes on fail, can be NULL.
1172 * @clean: Clean up resources after all transaction actions have called
1173 * commit() or abort(). Can be NULL.
1175 * Only prepare() may fail. In a single transaction, only one of commit() or
1176 * abort() will be called. clean() will always be called if it is present.
1178 typedef struct BlkActionOps {
1179 size_t instance_size;
1180 void (*prepare)(BlkActionState *common, Error **errp);
1181 void (*commit)(BlkActionState *common);
1182 void (*abort)(BlkActionState *common);
1183 void (*clean)(BlkActionState *common);
1184 } BlkActionOps;
1187 * BlkActionState:
1188 * Describes one Action's state within a Transaction.
1190 * @action: QAPI-defined enum identifying which Action to perform.
1191 * @ops: Table of ActionOps this Action can perform.
1192 * @block_job_txn: Transaction which this action belongs to.
1193 * @entry: List membership for all Actions in this Transaction.
1195 * This structure must be arranged as first member in a subclassed type,
1196 * assuming that the compiler will also arrange it to the same offsets as the
1197 * base class.
1199 struct BlkActionState {
1200 TransactionAction *action;
1201 const BlkActionOps *ops;
1202 JobTxn *block_job_txn;
1203 TransactionProperties *txn_props;
1204 QTAILQ_ENTRY(BlkActionState) entry;
1207 /* internal snapshot private data */
1208 typedef struct InternalSnapshotState {
1209 BlkActionState common;
1210 BlockDriverState *bs;
1211 QEMUSnapshotInfo sn;
1212 bool created;
1213 } InternalSnapshotState;
1216 static int action_check_completion_mode(BlkActionState *s, Error **errp)
1218 if (s->txn_props->completion_mode != ACTION_COMPLETION_MODE_INDIVIDUAL) {
1219 error_setg(errp,
1220 "Action '%s' does not support Transaction property "
1221 "completion-mode = %s",
1222 TransactionActionKind_str(s->action->type),
1223 ActionCompletionMode_str(s->txn_props->completion_mode));
1224 return -1;
1226 return 0;
1229 static void internal_snapshot_prepare(BlkActionState *common,
1230 Error **errp)
1232 Error *local_err = NULL;
1233 const char *device;
1234 const char *name;
1235 BlockDriverState *bs;
1236 QEMUSnapshotInfo old_sn, *sn;
1237 bool ret;
1238 qemu_timeval tv;
1239 BlockdevSnapshotInternal *internal;
1240 InternalSnapshotState *state;
1241 AioContext *aio_context;
1242 int ret1;
1244 g_assert(common->action->type ==
1245 TRANSACTION_ACTION_KIND_BLOCKDEV_SNAPSHOT_INTERNAL_SYNC);
1246 internal = common->action->u.blockdev_snapshot_internal_sync.data;
1247 state = DO_UPCAST(InternalSnapshotState, common, common);
1249 /* 1. parse input */
1250 device = internal->device;
1251 name = internal->name;
1253 /* 2. check for validation */
1254 if (action_check_completion_mode(common, errp) < 0) {
1255 return;
1258 bs = qmp_get_root_bs(device, errp);
1259 if (!bs) {
1260 return;
1263 aio_context = bdrv_get_aio_context(bs);
1264 aio_context_acquire(aio_context);
1266 state->bs = bs;
1268 /* Paired with .clean() */
1269 bdrv_drained_begin(bs);
1271 if (bdrv_op_is_blocked(bs, BLOCK_OP_TYPE_INTERNAL_SNAPSHOT, errp)) {
1272 goto out;
1275 if (bdrv_is_read_only(bs)) {
1276 error_setg(errp, "Device '%s' is read only", device);
1277 goto out;
1280 if (!bdrv_can_snapshot(bs)) {
1281 error_setg(errp, "Block format '%s' used by device '%s' "
1282 "does not support internal snapshots",
1283 bs->drv->format_name, device);
1284 goto out;
1287 if (!strlen(name)) {
1288 error_setg(errp, "Name is empty");
1289 goto out;
1292 /* check whether a snapshot with name exist */
1293 ret = bdrv_snapshot_find_by_id_and_name(bs, NULL, name, &old_sn,
1294 &local_err);
1295 if (local_err) {
1296 error_propagate(errp, local_err);
1297 goto out;
1298 } else if (ret) {
1299 error_setg(errp,
1300 "Snapshot with name '%s' already exists on device '%s'",
1301 name, device);
1302 goto out;
1305 /* 3. take the snapshot */
1306 sn = &state->sn;
1307 pstrcpy(sn->name, sizeof(sn->name), name);
1308 qemu_gettimeofday(&tv);
1309 sn->date_sec = tv.tv_sec;
1310 sn->date_nsec = tv.tv_usec * 1000;
1311 sn->vm_clock_nsec = qemu_clock_get_ns(QEMU_CLOCK_VIRTUAL);
1312 if (replay_mode != REPLAY_MODE_NONE) {
1313 sn->icount = replay_get_current_icount();
1314 } else {
1315 sn->icount = -1ULL;
1318 ret1 = bdrv_snapshot_create(bs, sn);
1319 if (ret1 < 0) {
1320 error_setg_errno(errp, -ret1,
1321 "Failed to create snapshot '%s' on device '%s'",
1322 name, device);
1323 goto out;
1326 /* 4. succeed, mark a snapshot is created */
1327 state->created = true;
1329 out:
1330 aio_context_release(aio_context);
1333 static void internal_snapshot_abort(BlkActionState *common)
1335 InternalSnapshotState *state =
1336 DO_UPCAST(InternalSnapshotState, common, common);
1337 BlockDriverState *bs = state->bs;
1338 QEMUSnapshotInfo *sn = &state->sn;
1339 AioContext *aio_context;
1340 Error *local_error = NULL;
1342 if (!state->created) {
1343 return;
1346 aio_context = bdrv_get_aio_context(state->bs);
1347 aio_context_acquire(aio_context);
1349 if (bdrv_snapshot_delete(bs, sn->id_str, sn->name, &local_error) < 0) {
1350 error_reportf_err(local_error,
1351 "Failed to delete snapshot with id '%s' and "
1352 "name '%s' on device '%s' in abort: ",
1353 sn->id_str, sn->name,
1354 bdrv_get_device_name(bs));
1357 aio_context_release(aio_context);
1360 static void internal_snapshot_clean(BlkActionState *common)
1362 InternalSnapshotState *state = DO_UPCAST(InternalSnapshotState,
1363 common, common);
1364 AioContext *aio_context;
1366 if (!state->bs) {
1367 return;
1370 aio_context = bdrv_get_aio_context(state->bs);
1371 aio_context_acquire(aio_context);
1373 bdrv_drained_end(state->bs);
1375 aio_context_release(aio_context);
1378 /* external snapshot private data */
1379 typedef struct ExternalSnapshotState {
1380 BlkActionState common;
1381 BlockDriverState *old_bs;
1382 BlockDriverState *new_bs;
1383 bool overlay_appended;
1384 } ExternalSnapshotState;
1386 static void external_snapshot_prepare(BlkActionState *common,
1387 Error **errp)
1389 int ret;
1390 int flags = 0;
1391 QDict *options = NULL;
1392 Error *local_err = NULL;
1393 /* Device and node name of the image to generate the snapshot from */
1394 const char *device;
1395 const char *node_name;
1396 /* Reference to the new image (for 'blockdev-snapshot') */
1397 const char *snapshot_ref;
1398 /* File name of the new image (for 'blockdev-snapshot-sync') */
1399 const char *new_image_file;
1400 ExternalSnapshotState *state =
1401 DO_UPCAST(ExternalSnapshotState, common, common);
1402 TransactionAction *action = common->action;
1403 AioContext *aio_context;
1404 uint64_t perm, shared;
1406 /* 'blockdev-snapshot' and 'blockdev-snapshot-sync' have similar
1407 * purpose but a different set of parameters */
1408 switch (action->type) {
1409 case TRANSACTION_ACTION_KIND_BLOCKDEV_SNAPSHOT:
1411 BlockdevSnapshot *s = action->u.blockdev_snapshot.data;
1412 device = s->node;
1413 node_name = s->node;
1414 new_image_file = NULL;
1415 snapshot_ref = s->overlay;
1417 break;
1418 case TRANSACTION_ACTION_KIND_BLOCKDEV_SNAPSHOT_SYNC:
1420 BlockdevSnapshotSync *s = action->u.blockdev_snapshot_sync.data;
1421 device = s->has_device ? s->device : NULL;
1422 node_name = s->has_node_name ? s->node_name : NULL;
1423 new_image_file = s->snapshot_file;
1424 snapshot_ref = NULL;
1426 break;
1427 default:
1428 g_assert_not_reached();
1431 /* start processing */
1432 if (action_check_completion_mode(common, errp) < 0) {
1433 return;
1436 state->old_bs = bdrv_lookup_bs(device, node_name, errp);
1437 if (!state->old_bs) {
1438 return;
1441 aio_context = bdrv_get_aio_context(state->old_bs);
1442 aio_context_acquire(aio_context);
1444 /* Paired with .clean() */
1445 bdrv_drained_begin(state->old_bs);
1447 if (!bdrv_is_inserted(state->old_bs)) {
1448 error_setg(errp, QERR_DEVICE_HAS_NO_MEDIUM, device);
1449 goto out;
1452 if (bdrv_op_is_blocked(state->old_bs,
1453 BLOCK_OP_TYPE_EXTERNAL_SNAPSHOT, errp)) {
1454 goto out;
1457 if (!bdrv_is_read_only(state->old_bs)) {
1458 if (bdrv_flush(state->old_bs)) {
1459 error_setg(errp, QERR_IO_ERROR);
1460 goto out;
1464 if (action->type == TRANSACTION_ACTION_KIND_BLOCKDEV_SNAPSHOT_SYNC) {
1465 BlockdevSnapshotSync *s = action->u.blockdev_snapshot_sync.data;
1466 const char *format = s->has_format ? s->format : "qcow2";
1467 enum NewImageMode mode;
1468 const char *snapshot_node_name =
1469 s->has_snapshot_node_name ? s->snapshot_node_name : NULL;
1471 if (node_name && !snapshot_node_name) {
1472 error_setg(errp, "New overlay node-name missing");
1473 goto out;
1476 if (snapshot_node_name &&
1477 bdrv_lookup_bs(snapshot_node_name, snapshot_node_name, NULL)) {
1478 error_setg(errp, "New overlay node-name already in use");
1479 goto out;
1482 flags = state->old_bs->open_flags;
1483 flags &= ~(BDRV_O_SNAPSHOT | BDRV_O_COPY_ON_READ);
1484 flags |= BDRV_O_NO_BACKING;
1486 /* create new image w/backing file */
1487 mode = s->has_mode ? s->mode : NEW_IMAGE_MODE_ABSOLUTE_PATHS;
1488 if (mode != NEW_IMAGE_MODE_EXISTING) {
1489 int64_t size = bdrv_getlength(state->old_bs);
1490 if (size < 0) {
1491 error_setg_errno(errp, -size, "bdrv_getlength failed");
1492 goto out;
1494 bdrv_refresh_filename(state->old_bs);
1495 bdrv_img_create(new_image_file, format,
1496 state->old_bs->filename,
1497 state->old_bs->drv->format_name,
1498 NULL, size, flags, false, &local_err);
1499 if (local_err) {
1500 error_propagate(errp, local_err);
1501 goto out;
1505 options = qdict_new();
1506 if (snapshot_node_name) {
1507 qdict_put_str(options, "node-name", snapshot_node_name);
1509 qdict_put_str(options, "driver", format);
1512 state->new_bs = bdrv_open(new_image_file, snapshot_ref, options, flags,
1513 errp);
1514 /* We will manually add the backing_hd field to the bs later */
1515 if (!state->new_bs) {
1516 goto out;
1520 * Allow attaching a backing file to an overlay that's already in use only
1521 * if the parents don't assume that they are already seeing a valid image.
1522 * (Specifically, allow it as a mirror target, which is write-only access.)
1524 bdrv_get_cumulative_perm(state->new_bs, &perm, &shared);
1525 if (perm & BLK_PERM_CONSISTENT_READ) {
1526 error_setg(errp, "The overlay is already in use");
1527 goto out;
1530 if (state->new_bs->drv->is_filter) {
1531 error_setg(errp, "Filters cannot be used as overlays");
1532 goto out;
1535 if (bdrv_cow_child(state->new_bs)) {
1536 error_setg(errp, "The overlay already has a backing image");
1537 goto out;
1540 if (!state->new_bs->drv->supports_backing) {
1541 error_setg(errp, "The overlay does not support backing images");
1542 goto out;
1545 ret = bdrv_append(state->new_bs, state->old_bs, errp);
1546 if (ret < 0) {
1547 goto out;
1549 state->overlay_appended = true;
1551 out:
1552 aio_context_release(aio_context);
1555 static void external_snapshot_commit(BlkActionState *common)
1557 ExternalSnapshotState *state =
1558 DO_UPCAST(ExternalSnapshotState, common, common);
1559 AioContext *aio_context;
1561 aio_context = bdrv_get_aio_context(state->old_bs);
1562 aio_context_acquire(aio_context);
1564 /* We don't need (or want) to use the transactional
1565 * bdrv_reopen_multiple() across all the entries at once, because we
1566 * don't want to abort all of them if one of them fails the reopen */
1567 if (!qatomic_read(&state->old_bs->copy_on_read)) {
1568 bdrv_reopen_set_read_only(state->old_bs, true, NULL);
1571 aio_context_release(aio_context);
1574 static void external_snapshot_abort(BlkActionState *common)
1576 ExternalSnapshotState *state =
1577 DO_UPCAST(ExternalSnapshotState, common, common);
1578 if (state->new_bs) {
1579 if (state->overlay_appended) {
1580 AioContext *aio_context;
1581 AioContext *tmp_context;
1582 int ret;
1584 aio_context = bdrv_get_aio_context(state->old_bs);
1585 aio_context_acquire(aio_context);
1587 bdrv_ref(state->old_bs); /* we can't let bdrv_set_backind_hd()
1588 close state->old_bs; we need it */
1589 bdrv_set_backing_hd(state->new_bs, NULL, &error_abort);
1592 * The call to bdrv_set_backing_hd() above returns state->old_bs to
1593 * the main AioContext. As we're still going to be using it, return
1594 * it to the AioContext it was before.
1596 tmp_context = bdrv_get_aio_context(state->old_bs);
1597 if (aio_context != tmp_context) {
1598 aio_context_release(aio_context);
1599 aio_context_acquire(tmp_context);
1601 ret = bdrv_try_set_aio_context(state->old_bs,
1602 aio_context, NULL);
1603 assert(ret == 0);
1605 aio_context_release(tmp_context);
1606 aio_context_acquire(aio_context);
1609 bdrv_replace_node(state->new_bs, state->old_bs, &error_abort);
1610 bdrv_unref(state->old_bs); /* bdrv_replace_node() ref'ed old_bs */
1612 aio_context_release(aio_context);
1617 static void external_snapshot_clean(BlkActionState *common)
1619 ExternalSnapshotState *state =
1620 DO_UPCAST(ExternalSnapshotState, common, common);
1621 AioContext *aio_context;
1623 if (!state->old_bs) {
1624 return;
1627 aio_context = bdrv_get_aio_context(state->old_bs);
1628 aio_context_acquire(aio_context);
1630 bdrv_drained_end(state->old_bs);
1631 bdrv_unref(state->new_bs);
1633 aio_context_release(aio_context);
1636 typedef struct DriveBackupState {
1637 BlkActionState common;
1638 BlockDriverState *bs;
1639 BlockJob *job;
1640 } DriveBackupState;
1642 static BlockJob *do_backup_common(BackupCommon *backup,
1643 BlockDriverState *bs,
1644 BlockDriverState *target_bs,
1645 AioContext *aio_context,
1646 JobTxn *txn, Error **errp);
1648 static void drive_backup_prepare(BlkActionState *common, Error **errp)
1650 DriveBackupState *state = DO_UPCAST(DriveBackupState, common, common);
1651 DriveBackup *backup;
1652 BlockDriverState *bs;
1653 BlockDriverState *target_bs;
1654 BlockDriverState *source = NULL;
1655 AioContext *aio_context;
1656 AioContext *old_context;
1657 QDict *options;
1658 Error *local_err = NULL;
1659 int flags;
1660 int64_t size;
1661 bool set_backing_hd = false;
1662 int ret;
1664 assert(common->action->type == TRANSACTION_ACTION_KIND_DRIVE_BACKUP);
1665 backup = common->action->u.drive_backup.data;
1667 if (!backup->has_mode) {
1668 backup->mode = NEW_IMAGE_MODE_ABSOLUTE_PATHS;
1671 bs = bdrv_lookup_bs(backup->device, backup->device, errp);
1672 if (!bs) {
1673 return;
1676 if (!bs->drv) {
1677 error_setg(errp, "Device has no medium");
1678 return;
1681 aio_context = bdrv_get_aio_context(bs);
1682 aio_context_acquire(aio_context);
1684 state->bs = bs;
1685 /* Paired with .clean() */
1686 bdrv_drained_begin(bs);
1688 if (!backup->has_format) {
1689 backup->format = backup->mode == NEW_IMAGE_MODE_EXISTING ?
1690 NULL : (char *) bs->drv->format_name;
1693 /* Early check to avoid creating target */
1694 if (bdrv_op_is_blocked(bs, BLOCK_OP_TYPE_BACKUP_SOURCE, errp)) {
1695 goto out;
1698 flags = bs->open_flags | BDRV_O_RDWR;
1701 * See if we have a backing HD we can use to create our new image
1702 * on top of.
1704 if (backup->sync == MIRROR_SYNC_MODE_TOP) {
1706 * Backup will not replace the source by the target, so none
1707 * of the filters skipped here will be removed (in contrast to
1708 * mirror). Therefore, we can skip all of them when looking
1709 * for the first COW relationship.
1711 source = bdrv_cow_bs(bdrv_skip_filters(bs));
1712 if (!source) {
1713 backup->sync = MIRROR_SYNC_MODE_FULL;
1716 if (backup->sync == MIRROR_SYNC_MODE_NONE) {
1717 source = bs;
1718 flags |= BDRV_O_NO_BACKING;
1719 set_backing_hd = true;
1722 size = bdrv_getlength(bs);
1723 if (size < 0) {
1724 error_setg_errno(errp, -size, "bdrv_getlength failed");
1725 goto out;
1728 if (backup->mode != NEW_IMAGE_MODE_EXISTING) {
1729 assert(backup->format);
1730 if (source) {
1731 /* Implicit filters should not appear in the filename */
1732 BlockDriverState *explicit_backing =
1733 bdrv_skip_implicit_filters(source);
1735 bdrv_refresh_filename(explicit_backing);
1736 bdrv_img_create(backup->target, backup->format,
1737 explicit_backing->filename,
1738 explicit_backing->drv->format_name, NULL,
1739 size, flags, false, &local_err);
1740 } else {
1741 bdrv_img_create(backup->target, backup->format, NULL, NULL, NULL,
1742 size, flags, false, &local_err);
1746 if (local_err) {
1747 error_propagate(errp, local_err);
1748 goto out;
1751 options = qdict_new();
1752 qdict_put_str(options, "discard", "unmap");
1753 qdict_put_str(options, "detect-zeroes", "unmap");
1754 if (backup->format) {
1755 qdict_put_str(options, "driver", backup->format);
1758 target_bs = bdrv_open(backup->target, NULL, options, flags, errp);
1759 if (!target_bs) {
1760 goto out;
1763 /* Honor bdrv_try_set_aio_context() context acquisition requirements. */
1764 old_context = bdrv_get_aio_context(target_bs);
1765 aio_context_release(aio_context);
1766 aio_context_acquire(old_context);
1768 ret = bdrv_try_set_aio_context(target_bs, aio_context, errp);
1769 if (ret < 0) {
1770 bdrv_unref(target_bs);
1771 aio_context_release(old_context);
1772 return;
1775 aio_context_release(old_context);
1776 aio_context_acquire(aio_context);
1778 if (set_backing_hd) {
1779 if (bdrv_set_backing_hd(target_bs, source, errp) < 0) {
1780 goto unref;
1784 state->job = do_backup_common(qapi_DriveBackup_base(backup),
1785 bs, target_bs, aio_context,
1786 common->block_job_txn, errp);
1788 unref:
1789 bdrv_unref(target_bs);
1790 out:
1791 aio_context_release(aio_context);
1794 static void drive_backup_commit(BlkActionState *common)
1796 DriveBackupState *state = DO_UPCAST(DriveBackupState, common, common);
1797 AioContext *aio_context;
1799 aio_context = bdrv_get_aio_context(state->bs);
1800 aio_context_acquire(aio_context);
1802 assert(state->job);
1803 job_start(&state->job->job);
1805 aio_context_release(aio_context);
1808 static void drive_backup_abort(BlkActionState *common)
1810 DriveBackupState *state = DO_UPCAST(DriveBackupState, common, common);
1812 if (state->job) {
1813 AioContext *aio_context;
1815 aio_context = bdrv_get_aio_context(state->bs);
1816 aio_context_acquire(aio_context);
1818 job_cancel_sync(&state->job->job, true);
1820 aio_context_release(aio_context);
1824 static void drive_backup_clean(BlkActionState *common)
1826 DriveBackupState *state = DO_UPCAST(DriveBackupState, common, common);
1827 AioContext *aio_context;
1829 if (!state->bs) {
1830 return;
1833 aio_context = bdrv_get_aio_context(state->bs);
1834 aio_context_acquire(aio_context);
1836 bdrv_drained_end(state->bs);
1838 aio_context_release(aio_context);
1841 typedef struct BlockdevBackupState {
1842 BlkActionState common;
1843 BlockDriverState *bs;
1844 BlockJob *job;
1845 } BlockdevBackupState;
1847 static void blockdev_backup_prepare(BlkActionState *common, Error **errp)
1849 BlockdevBackupState *state = DO_UPCAST(BlockdevBackupState, common, common);
1850 BlockdevBackup *backup;
1851 BlockDriverState *bs;
1852 BlockDriverState *target_bs;
1853 AioContext *aio_context;
1854 AioContext *old_context;
1855 int ret;
1857 assert(common->action->type == TRANSACTION_ACTION_KIND_BLOCKDEV_BACKUP);
1858 backup = common->action->u.blockdev_backup.data;
1860 bs = bdrv_lookup_bs(backup->device, backup->device, errp);
1861 if (!bs) {
1862 return;
1865 target_bs = bdrv_lookup_bs(backup->target, backup->target, errp);
1866 if (!target_bs) {
1867 return;
1870 /* Honor bdrv_try_set_aio_context() context acquisition requirements. */
1871 aio_context = bdrv_get_aio_context(bs);
1872 old_context = bdrv_get_aio_context(target_bs);
1873 aio_context_acquire(old_context);
1875 ret = bdrv_try_set_aio_context(target_bs, aio_context, errp);
1876 if (ret < 0) {
1877 aio_context_release(old_context);
1878 return;
1881 aio_context_release(old_context);
1882 aio_context_acquire(aio_context);
1883 state->bs = bs;
1885 /* Paired with .clean() */
1886 bdrv_drained_begin(state->bs);
1888 state->job = do_backup_common(qapi_BlockdevBackup_base(backup),
1889 bs, target_bs, aio_context,
1890 common->block_job_txn, errp);
1892 aio_context_release(aio_context);
1895 static void blockdev_backup_commit(BlkActionState *common)
1897 BlockdevBackupState *state = DO_UPCAST(BlockdevBackupState, common, common);
1898 AioContext *aio_context;
1900 aio_context = bdrv_get_aio_context(state->bs);
1901 aio_context_acquire(aio_context);
1903 assert(state->job);
1904 job_start(&state->job->job);
1906 aio_context_release(aio_context);
1909 static void blockdev_backup_abort(BlkActionState *common)
1911 BlockdevBackupState *state = DO_UPCAST(BlockdevBackupState, common, common);
1913 if (state->job) {
1914 AioContext *aio_context;
1916 aio_context = bdrv_get_aio_context(state->bs);
1917 aio_context_acquire(aio_context);
1919 job_cancel_sync(&state->job->job, true);
1921 aio_context_release(aio_context);
1925 static void blockdev_backup_clean(BlkActionState *common)
1927 BlockdevBackupState *state = DO_UPCAST(BlockdevBackupState, common, common);
1928 AioContext *aio_context;
1930 if (!state->bs) {
1931 return;
1934 aio_context = bdrv_get_aio_context(state->bs);
1935 aio_context_acquire(aio_context);
1937 bdrv_drained_end(state->bs);
1939 aio_context_release(aio_context);
1942 typedef struct BlockDirtyBitmapState {
1943 BlkActionState common;
1944 BdrvDirtyBitmap *bitmap;
1945 BlockDriverState *bs;
1946 HBitmap *backup;
1947 bool prepared;
1948 bool was_enabled;
1949 } BlockDirtyBitmapState;
1951 static void block_dirty_bitmap_add_prepare(BlkActionState *common,
1952 Error **errp)
1954 Error *local_err = NULL;
1955 BlockDirtyBitmapAdd *action;
1956 BlockDirtyBitmapState *state = DO_UPCAST(BlockDirtyBitmapState,
1957 common, common);
1959 if (action_check_completion_mode(common, errp) < 0) {
1960 return;
1963 action = common->action->u.block_dirty_bitmap_add.data;
1964 /* AIO context taken and released within qmp_block_dirty_bitmap_add */
1965 qmp_block_dirty_bitmap_add(action->node, action->name,
1966 action->has_granularity, action->granularity,
1967 action->has_persistent, action->persistent,
1968 action->has_disabled, action->disabled,
1969 &local_err);
1971 if (!local_err) {
1972 state->prepared = true;
1973 } else {
1974 error_propagate(errp, local_err);
1978 static void block_dirty_bitmap_add_abort(BlkActionState *common)
1980 BlockDirtyBitmapAdd *action;
1981 BlockDirtyBitmapState *state = DO_UPCAST(BlockDirtyBitmapState,
1982 common, common);
1984 action = common->action->u.block_dirty_bitmap_add.data;
1985 /* Should not be able to fail: IF the bitmap was added via .prepare(),
1986 * then the node reference and bitmap name must have been valid.
1988 if (state->prepared) {
1989 qmp_block_dirty_bitmap_remove(action->node, action->name, &error_abort);
1993 static void block_dirty_bitmap_clear_prepare(BlkActionState *common,
1994 Error **errp)
1996 BlockDirtyBitmapState *state = DO_UPCAST(BlockDirtyBitmapState,
1997 common, common);
1998 BlockDirtyBitmap *action;
2000 if (action_check_completion_mode(common, errp) < 0) {
2001 return;
2004 action = common->action->u.block_dirty_bitmap_clear.data;
2005 state->bitmap = block_dirty_bitmap_lookup(action->node,
2006 action->name,
2007 &state->bs,
2008 errp);
2009 if (!state->bitmap) {
2010 return;
2013 if (bdrv_dirty_bitmap_check(state->bitmap, BDRV_BITMAP_DEFAULT, errp)) {
2014 return;
2017 bdrv_clear_dirty_bitmap(state->bitmap, &state->backup);
2020 static void block_dirty_bitmap_restore(BlkActionState *common)
2022 BlockDirtyBitmapState *state = DO_UPCAST(BlockDirtyBitmapState,
2023 common, common);
2025 if (state->backup) {
2026 bdrv_restore_dirty_bitmap(state->bitmap, state->backup);
2030 static void block_dirty_bitmap_free_backup(BlkActionState *common)
2032 BlockDirtyBitmapState *state = DO_UPCAST(BlockDirtyBitmapState,
2033 common, common);
2035 hbitmap_free(state->backup);
2038 static void block_dirty_bitmap_enable_prepare(BlkActionState *common,
2039 Error **errp)
2041 BlockDirtyBitmap *action;
2042 BlockDirtyBitmapState *state = DO_UPCAST(BlockDirtyBitmapState,
2043 common, common);
2045 if (action_check_completion_mode(common, errp) < 0) {
2046 return;
2049 action = common->action->u.block_dirty_bitmap_enable.data;
2050 state->bitmap = block_dirty_bitmap_lookup(action->node,
2051 action->name,
2052 NULL,
2053 errp);
2054 if (!state->bitmap) {
2055 return;
2058 if (bdrv_dirty_bitmap_check(state->bitmap, BDRV_BITMAP_ALLOW_RO, errp)) {
2059 return;
2062 state->was_enabled = bdrv_dirty_bitmap_enabled(state->bitmap);
2063 bdrv_enable_dirty_bitmap(state->bitmap);
2066 static void block_dirty_bitmap_enable_abort(BlkActionState *common)
2068 BlockDirtyBitmapState *state = DO_UPCAST(BlockDirtyBitmapState,
2069 common, common);
2071 if (!state->was_enabled) {
2072 bdrv_disable_dirty_bitmap(state->bitmap);
2076 static void block_dirty_bitmap_disable_prepare(BlkActionState *common,
2077 Error **errp)
2079 BlockDirtyBitmap *action;
2080 BlockDirtyBitmapState *state = DO_UPCAST(BlockDirtyBitmapState,
2081 common, common);
2083 if (action_check_completion_mode(common, errp) < 0) {
2084 return;
2087 action = common->action->u.block_dirty_bitmap_disable.data;
2088 state->bitmap = block_dirty_bitmap_lookup(action->node,
2089 action->name,
2090 NULL,
2091 errp);
2092 if (!state->bitmap) {
2093 return;
2096 if (bdrv_dirty_bitmap_check(state->bitmap, BDRV_BITMAP_ALLOW_RO, errp)) {
2097 return;
2100 state->was_enabled = bdrv_dirty_bitmap_enabled(state->bitmap);
2101 bdrv_disable_dirty_bitmap(state->bitmap);
2104 static void block_dirty_bitmap_disable_abort(BlkActionState *common)
2106 BlockDirtyBitmapState *state = DO_UPCAST(BlockDirtyBitmapState,
2107 common, common);
2109 if (state->was_enabled) {
2110 bdrv_enable_dirty_bitmap(state->bitmap);
2114 static void block_dirty_bitmap_merge_prepare(BlkActionState *common,
2115 Error **errp)
2117 BlockDirtyBitmapMerge *action;
2118 BlockDirtyBitmapState *state = DO_UPCAST(BlockDirtyBitmapState,
2119 common, common);
2121 if (action_check_completion_mode(common, errp) < 0) {
2122 return;
2125 action = common->action->u.block_dirty_bitmap_merge.data;
2127 state->bitmap = block_dirty_bitmap_merge(action->node, action->target,
2128 action->bitmaps, &state->backup,
2129 errp);
2132 static void block_dirty_bitmap_remove_prepare(BlkActionState *common,
2133 Error **errp)
2135 BlockDirtyBitmap *action;
2136 BlockDirtyBitmapState *state = DO_UPCAST(BlockDirtyBitmapState,
2137 common, common);
2139 if (action_check_completion_mode(common, errp) < 0) {
2140 return;
2143 action = common->action->u.block_dirty_bitmap_remove.data;
2145 state->bitmap = block_dirty_bitmap_remove(action->node, action->name,
2146 false, &state->bs, errp);
2147 if (state->bitmap) {
2148 bdrv_dirty_bitmap_skip_store(state->bitmap, true);
2149 bdrv_dirty_bitmap_set_busy(state->bitmap, true);
2153 static void block_dirty_bitmap_remove_abort(BlkActionState *common)
2155 BlockDirtyBitmapState *state = DO_UPCAST(BlockDirtyBitmapState,
2156 common, common);
2158 if (state->bitmap) {
2159 bdrv_dirty_bitmap_skip_store(state->bitmap, false);
2160 bdrv_dirty_bitmap_set_busy(state->bitmap, false);
2164 static void block_dirty_bitmap_remove_commit(BlkActionState *common)
2166 BlockDirtyBitmapState *state = DO_UPCAST(BlockDirtyBitmapState,
2167 common, common);
2169 bdrv_dirty_bitmap_set_busy(state->bitmap, false);
2170 bdrv_release_dirty_bitmap(state->bitmap);
2173 static void abort_prepare(BlkActionState *common, Error **errp)
2175 error_setg(errp, "Transaction aborted using Abort action");
2178 static void abort_commit(BlkActionState *common)
2180 g_assert_not_reached(); /* this action never succeeds */
2183 static const BlkActionOps actions[] = {
2184 [TRANSACTION_ACTION_KIND_BLOCKDEV_SNAPSHOT] = {
2185 .instance_size = sizeof(ExternalSnapshotState),
2186 .prepare = external_snapshot_prepare,
2187 .commit = external_snapshot_commit,
2188 .abort = external_snapshot_abort,
2189 .clean = external_snapshot_clean,
2191 [TRANSACTION_ACTION_KIND_BLOCKDEV_SNAPSHOT_SYNC] = {
2192 .instance_size = sizeof(ExternalSnapshotState),
2193 .prepare = external_snapshot_prepare,
2194 .commit = external_snapshot_commit,
2195 .abort = external_snapshot_abort,
2196 .clean = external_snapshot_clean,
2198 [TRANSACTION_ACTION_KIND_DRIVE_BACKUP] = {
2199 .instance_size = sizeof(DriveBackupState),
2200 .prepare = drive_backup_prepare,
2201 .commit = drive_backup_commit,
2202 .abort = drive_backup_abort,
2203 .clean = drive_backup_clean,
2205 [TRANSACTION_ACTION_KIND_BLOCKDEV_BACKUP] = {
2206 .instance_size = sizeof(BlockdevBackupState),
2207 .prepare = blockdev_backup_prepare,
2208 .commit = blockdev_backup_commit,
2209 .abort = blockdev_backup_abort,
2210 .clean = blockdev_backup_clean,
2212 [TRANSACTION_ACTION_KIND_ABORT] = {
2213 .instance_size = sizeof(BlkActionState),
2214 .prepare = abort_prepare,
2215 .commit = abort_commit,
2217 [TRANSACTION_ACTION_KIND_BLOCKDEV_SNAPSHOT_INTERNAL_SYNC] = {
2218 .instance_size = sizeof(InternalSnapshotState),
2219 .prepare = internal_snapshot_prepare,
2220 .abort = internal_snapshot_abort,
2221 .clean = internal_snapshot_clean,
2223 [TRANSACTION_ACTION_KIND_BLOCK_DIRTY_BITMAP_ADD] = {
2224 .instance_size = sizeof(BlockDirtyBitmapState),
2225 .prepare = block_dirty_bitmap_add_prepare,
2226 .abort = block_dirty_bitmap_add_abort,
2228 [TRANSACTION_ACTION_KIND_BLOCK_DIRTY_BITMAP_CLEAR] = {
2229 .instance_size = sizeof(BlockDirtyBitmapState),
2230 .prepare = block_dirty_bitmap_clear_prepare,
2231 .commit = block_dirty_bitmap_free_backup,
2232 .abort = block_dirty_bitmap_restore,
2234 [TRANSACTION_ACTION_KIND_BLOCK_DIRTY_BITMAP_ENABLE] = {
2235 .instance_size = sizeof(BlockDirtyBitmapState),
2236 .prepare = block_dirty_bitmap_enable_prepare,
2237 .abort = block_dirty_bitmap_enable_abort,
2239 [TRANSACTION_ACTION_KIND_BLOCK_DIRTY_BITMAP_DISABLE] = {
2240 .instance_size = sizeof(BlockDirtyBitmapState),
2241 .prepare = block_dirty_bitmap_disable_prepare,
2242 .abort = block_dirty_bitmap_disable_abort,
2244 [TRANSACTION_ACTION_KIND_BLOCK_DIRTY_BITMAP_MERGE] = {
2245 .instance_size = sizeof(BlockDirtyBitmapState),
2246 .prepare = block_dirty_bitmap_merge_prepare,
2247 .commit = block_dirty_bitmap_free_backup,
2248 .abort = block_dirty_bitmap_restore,
2250 [TRANSACTION_ACTION_KIND_BLOCK_DIRTY_BITMAP_REMOVE] = {
2251 .instance_size = sizeof(BlockDirtyBitmapState),
2252 .prepare = block_dirty_bitmap_remove_prepare,
2253 .commit = block_dirty_bitmap_remove_commit,
2254 .abort = block_dirty_bitmap_remove_abort,
2256 /* Where are transactions for MIRROR, COMMIT and STREAM?
2257 * Although these blockjobs use transaction callbacks like the backup job,
2258 * these jobs do not necessarily adhere to transaction semantics.
2259 * These jobs may not fully undo all of their actions on abort, nor do they
2260 * necessarily work in transactions with more than one job in them.
2265 * Allocate a TransactionProperties structure if necessary, and fill
2266 * that structure with desired defaults if they are unset.
2268 static TransactionProperties *get_transaction_properties(
2269 TransactionProperties *props)
2271 if (!props) {
2272 props = g_new0(TransactionProperties, 1);
2275 if (!props->has_completion_mode) {
2276 props->has_completion_mode = true;
2277 props->completion_mode = ACTION_COMPLETION_MODE_INDIVIDUAL;
2280 return props;
2284 * 'Atomic' group operations. The operations are performed as a set, and if
2285 * any fail then we roll back all operations in the group.
2287 void qmp_transaction(TransactionActionList *dev_list,
2288 bool has_props,
2289 struct TransactionProperties *props,
2290 Error **errp)
2292 TransactionActionList *dev_entry = dev_list;
2293 JobTxn *block_job_txn = NULL;
2294 BlkActionState *state, *next;
2295 Error *local_err = NULL;
2297 QTAILQ_HEAD(, BlkActionState) snap_bdrv_states;
2298 QTAILQ_INIT(&snap_bdrv_states);
2300 /* Does this transaction get canceled as a group on failure?
2301 * If not, we don't really need to make a JobTxn.
2303 props = get_transaction_properties(props);
2304 if (props->completion_mode != ACTION_COMPLETION_MODE_INDIVIDUAL) {
2305 block_job_txn = job_txn_new();
2308 /* drain all i/o before any operations */
2309 bdrv_drain_all();
2311 /* We don't do anything in this loop that commits us to the operations */
2312 while (NULL != dev_entry) {
2313 TransactionAction *dev_info = NULL;
2314 const BlkActionOps *ops;
2316 dev_info = dev_entry->value;
2317 dev_entry = dev_entry->next;
2319 assert(dev_info->type < ARRAY_SIZE(actions));
2321 ops = &actions[dev_info->type];
2322 assert(ops->instance_size > 0);
2324 state = g_malloc0(ops->instance_size);
2325 state->ops = ops;
2326 state->action = dev_info;
2327 state->block_job_txn = block_job_txn;
2328 state->txn_props = props;
2329 QTAILQ_INSERT_TAIL(&snap_bdrv_states, state, entry);
2331 state->ops->prepare(state, &local_err);
2332 if (local_err) {
2333 error_propagate(errp, local_err);
2334 goto delete_and_fail;
2338 QTAILQ_FOREACH(state, &snap_bdrv_states, entry) {
2339 if (state->ops->commit) {
2340 state->ops->commit(state);
2344 /* success */
2345 goto exit;
2347 delete_and_fail:
2348 /* failure, and it is all-or-none; roll back all operations */
2349 QTAILQ_FOREACH_REVERSE(state, &snap_bdrv_states, entry) {
2350 if (state->ops->abort) {
2351 state->ops->abort(state);
2354 exit:
2355 QTAILQ_FOREACH_SAFE(state, &snap_bdrv_states, entry, next) {
2356 if (state->ops->clean) {
2357 state->ops->clean(state);
2359 g_free(state);
2361 if (!has_props) {
2362 qapi_free_TransactionProperties(props);
2364 job_txn_unref(block_job_txn);
2367 BlockDirtyBitmapSha256 *qmp_x_debug_block_dirty_bitmap_sha256(const char *node,
2368 const char *name,
2369 Error **errp)
2371 BdrvDirtyBitmap *bitmap;
2372 BlockDriverState *bs;
2373 BlockDirtyBitmapSha256 *ret = NULL;
2374 char *sha256;
2376 bitmap = block_dirty_bitmap_lookup(node, name, &bs, errp);
2377 if (!bitmap || !bs) {
2378 return NULL;
2381 sha256 = bdrv_dirty_bitmap_sha256(bitmap, errp);
2382 if (sha256 == NULL) {
2383 return NULL;
2386 ret = g_new(BlockDirtyBitmapSha256, 1);
2387 ret->sha256 = sha256;
2389 return ret;
2392 void coroutine_fn qmp_block_resize(bool has_device, const char *device,
2393 bool has_node_name, const char *node_name,
2394 int64_t size, Error **errp)
2396 Error *local_err = NULL;
2397 BlockBackend *blk;
2398 BlockDriverState *bs;
2399 AioContext *old_ctx;
2401 bs = bdrv_lookup_bs(has_device ? device : NULL,
2402 has_node_name ? node_name : NULL,
2403 &local_err);
2404 if (local_err) {
2405 error_propagate(errp, local_err);
2406 return;
2409 if (size < 0) {
2410 error_setg(errp, QERR_INVALID_PARAMETER_VALUE, "size", "a >0 size");
2411 return;
2414 if (bdrv_op_is_blocked(bs, BLOCK_OP_TYPE_RESIZE, NULL)) {
2415 error_setg(errp, QERR_DEVICE_IN_USE, device);
2416 return;
2419 blk = blk_new_with_bs(bs, BLK_PERM_RESIZE, BLK_PERM_ALL, errp);
2420 if (!blk) {
2421 return;
2424 bdrv_co_lock(bs);
2425 bdrv_drained_begin(bs);
2426 bdrv_co_unlock(bs);
2428 old_ctx = bdrv_co_enter(bs);
2429 blk_truncate(blk, size, false, PREALLOC_MODE_OFF, 0, errp);
2430 bdrv_co_leave(bs, old_ctx);
2432 bdrv_co_lock(bs);
2433 bdrv_drained_end(bs);
2434 blk_unref(blk);
2435 bdrv_co_unlock(bs);
2438 void qmp_block_stream(bool has_job_id, const char *job_id, const char *device,
2439 bool has_base, const char *base,
2440 bool has_base_node, const char *base_node,
2441 bool has_backing_file, const char *backing_file,
2442 bool has_bottom, const char *bottom,
2443 bool has_speed, int64_t speed,
2444 bool has_on_error, BlockdevOnError on_error,
2445 bool has_filter_node_name, const char *filter_node_name,
2446 bool has_auto_finalize, bool auto_finalize,
2447 bool has_auto_dismiss, bool auto_dismiss,
2448 Error **errp)
2450 BlockDriverState *bs, *iter, *iter_end;
2451 BlockDriverState *base_bs = NULL;
2452 BlockDriverState *bottom_bs = NULL;
2453 AioContext *aio_context;
2454 Error *local_err = NULL;
2455 int job_flags = JOB_DEFAULT;
2457 if (has_base && has_base_node) {
2458 error_setg(errp, "'base' and 'base-node' cannot be specified "
2459 "at the same time");
2460 return;
2463 if (has_base && has_bottom) {
2464 error_setg(errp, "'base' and 'bottom' cannot be specified "
2465 "at the same time");
2466 return;
2469 if (has_bottom && has_base_node) {
2470 error_setg(errp, "'bottom' and 'base-node' cannot be specified "
2471 "at the same time");
2472 return;
2475 if (!has_on_error) {
2476 on_error = BLOCKDEV_ON_ERROR_REPORT;
2479 bs = bdrv_lookup_bs(device, device, errp);
2480 if (!bs) {
2481 return;
2484 aio_context = bdrv_get_aio_context(bs);
2485 aio_context_acquire(aio_context);
2487 if (has_base) {
2488 base_bs = bdrv_find_backing_image(bs, base);
2489 if (base_bs == NULL) {
2490 error_setg(errp, "Can't find '%s' in the backing chain", base);
2491 goto out;
2493 assert(bdrv_get_aio_context(base_bs) == aio_context);
2496 if (has_base_node) {
2497 base_bs = bdrv_lookup_bs(NULL, base_node, errp);
2498 if (!base_bs) {
2499 goto out;
2501 if (bs == base_bs || !bdrv_chain_contains(bs, base_bs)) {
2502 error_setg(errp, "Node '%s' is not a backing image of '%s'",
2503 base_node, device);
2504 goto out;
2506 assert(bdrv_get_aio_context(base_bs) == aio_context);
2507 bdrv_refresh_filename(base_bs);
2510 if (has_bottom) {
2511 bottom_bs = bdrv_lookup_bs(NULL, bottom, errp);
2512 if (!bottom_bs) {
2513 goto out;
2515 if (!bottom_bs->drv) {
2516 error_setg(errp, "Node '%s' is not open", bottom);
2517 goto out;
2519 if (bottom_bs->drv->is_filter) {
2520 error_setg(errp, "Node '%s' is a filter, use a non-filter node "
2521 "as 'bottom'", bottom);
2522 goto out;
2524 if (!bdrv_chain_contains(bs, bottom_bs)) {
2525 error_setg(errp, "Node '%s' is not in a chain starting from '%s'",
2526 bottom, device);
2527 goto out;
2529 assert(bdrv_get_aio_context(bottom_bs) == aio_context);
2533 * Check for op blockers in the whole chain between bs and base (or bottom)
2535 iter_end = has_bottom ? bdrv_filter_or_cow_bs(bottom_bs) : base_bs;
2536 for (iter = bs; iter && iter != iter_end;
2537 iter = bdrv_filter_or_cow_bs(iter))
2539 if (bdrv_op_is_blocked(iter, BLOCK_OP_TYPE_STREAM, errp)) {
2540 goto out;
2544 /* if we are streaming the entire chain, the result will have no backing
2545 * file, and specifying one is therefore an error */
2546 if (base_bs == NULL && has_backing_file) {
2547 error_setg(errp, "backing file specified, but streaming the "
2548 "entire chain");
2549 goto out;
2552 if (has_auto_finalize && !auto_finalize) {
2553 job_flags |= JOB_MANUAL_FINALIZE;
2555 if (has_auto_dismiss && !auto_dismiss) {
2556 job_flags |= JOB_MANUAL_DISMISS;
2559 stream_start(has_job_id ? job_id : NULL, bs, base_bs, backing_file,
2560 bottom_bs, job_flags, has_speed ? speed : 0, on_error,
2561 filter_node_name, &local_err);
2562 if (local_err) {
2563 error_propagate(errp, local_err);
2564 goto out;
2567 trace_qmp_block_stream(bs);
2569 out:
2570 aio_context_release(aio_context);
2573 void qmp_block_commit(bool has_job_id, const char *job_id, const char *device,
2574 bool has_base_node, const char *base_node,
2575 bool has_base, const char *base,
2576 bool has_top_node, const char *top_node,
2577 bool has_top, const char *top,
2578 bool has_backing_file, const char *backing_file,
2579 bool has_speed, int64_t speed,
2580 bool has_on_error, BlockdevOnError on_error,
2581 bool has_filter_node_name, const char *filter_node_name,
2582 bool has_auto_finalize, bool auto_finalize,
2583 bool has_auto_dismiss, bool auto_dismiss,
2584 Error **errp)
2586 BlockDriverState *bs;
2587 BlockDriverState *iter;
2588 BlockDriverState *base_bs, *top_bs;
2589 AioContext *aio_context;
2590 Error *local_err = NULL;
2591 int job_flags = JOB_DEFAULT;
2592 uint64_t top_perm, top_shared;
2594 if (!has_speed) {
2595 speed = 0;
2597 if (!has_on_error) {
2598 on_error = BLOCKDEV_ON_ERROR_REPORT;
2600 if (!has_filter_node_name) {
2601 filter_node_name = NULL;
2603 if (has_auto_finalize && !auto_finalize) {
2604 job_flags |= JOB_MANUAL_FINALIZE;
2606 if (has_auto_dismiss && !auto_dismiss) {
2607 job_flags |= JOB_MANUAL_DISMISS;
2610 /* Important Note:
2611 * libvirt relies on the DeviceNotFound error class in order to probe for
2612 * live commit feature versions; for this to work, we must make sure to
2613 * perform the device lookup before any generic errors that may occur in a
2614 * scenario in which all optional arguments are omitted. */
2615 bs = qmp_get_root_bs(device, &local_err);
2616 if (!bs) {
2617 bs = bdrv_lookup_bs(device, device, NULL);
2618 if (!bs) {
2619 error_free(local_err);
2620 error_set(errp, ERROR_CLASS_DEVICE_NOT_FOUND,
2621 "Device '%s' not found", device);
2622 } else {
2623 error_propagate(errp, local_err);
2625 return;
2628 aio_context = bdrv_get_aio_context(bs);
2629 aio_context_acquire(aio_context);
2631 if (bdrv_op_is_blocked(bs, BLOCK_OP_TYPE_COMMIT_SOURCE, errp)) {
2632 goto out;
2635 /* default top_bs is the active layer */
2636 top_bs = bs;
2638 if (has_top_node && has_top) {
2639 error_setg(errp, "'top-node' and 'top' are mutually exclusive");
2640 goto out;
2641 } else if (has_top_node) {
2642 top_bs = bdrv_lookup_bs(NULL, top_node, errp);
2643 if (top_bs == NULL) {
2644 goto out;
2646 if (!bdrv_chain_contains(bs, top_bs)) {
2647 error_setg(errp, "'%s' is not in this backing file chain",
2648 top_node);
2649 goto out;
2651 } else if (has_top && top) {
2652 /* This strcmp() is just a shortcut, there is no need to
2653 * refresh @bs's filename. If it mismatches,
2654 * bdrv_find_backing_image() will do the refresh and may still
2655 * return @bs. */
2656 if (strcmp(bs->filename, top) != 0) {
2657 top_bs = bdrv_find_backing_image(bs, top);
2661 if (top_bs == NULL) {
2662 error_setg(errp, "Top image file %s not found", top ? top : "NULL");
2663 goto out;
2666 assert(bdrv_get_aio_context(top_bs) == aio_context);
2668 if (has_base_node && has_base) {
2669 error_setg(errp, "'base-node' and 'base' are mutually exclusive");
2670 goto out;
2671 } else if (has_base_node) {
2672 base_bs = bdrv_lookup_bs(NULL, base_node, errp);
2673 if (base_bs == NULL) {
2674 goto out;
2676 if (!bdrv_chain_contains(top_bs, base_bs)) {
2677 error_setg(errp, "'%s' is not in this backing file chain",
2678 base_node);
2679 goto out;
2681 } else if (has_base && base) {
2682 base_bs = bdrv_find_backing_image(top_bs, base);
2683 if (base_bs == NULL) {
2684 error_setg(errp, "Can't find '%s' in the backing chain", base);
2685 goto out;
2687 } else {
2688 base_bs = bdrv_find_base(top_bs);
2689 if (base_bs == NULL) {
2690 error_setg(errp, "There is no backimg image");
2691 goto out;
2695 assert(bdrv_get_aio_context(base_bs) == aio_context);
2697 for (iter = top_bs; iter != bdrv_filter_or_cow_bs(base_bs);
2698 iter = bdrv_filter_or_cow_bs(iter))
2700 if (bdrv_op_is_blocked(iter, BLOCK_OP_TYPE_COMMIT_TARGET, errp)) {
2701 goto out;
2705 /* Do not allow attempts to commit an image into itself */
2706 if (top_bs == base_bs) {
2707 error_setg(errp, "cannot commit an image into itself");
2708 goto out;
2712 * Active commit is required if and only if someone has taken a
2713 * WRITE permission on the top node. Historically, we have always
2714 * used active commit for top nodes, so continue that practice
2715 * lest we possibly break clients that rely on this behavior, e.g.
2716 * to later attach this node to a writing parent.
2717 * (Active commit is never really wrong.)
2719 bdrv_get_cumulative_perm(top_bs, &top_perm, &top_shared);
2720 if (top_perm & BLK_PERM_WRITE ||
2721 bdrv_skip_filters(top_bs) == bdrv_skip_filters(bs))
2723 if (has_backing_file) {
2724 if (bdrv_skip_filters(top_bs) == bdrv_skip_filters(bs)) {
2725 error_setg(errp, "'backing-file' specified,"
2726 " but 'top' is the active layer");
2727 } else {
2728 error_setg(errp, "'backing-file' specified, but 'top' has a "
2729 "writer on it");
2731 goto out;
2733 if (!has_job_id) {
2735 * Emulate here what block_job_create() does, because it
2736 * is possible that @bs != @top_bs (the block job should
2737 * be named after @bs, even if @top_bs is the actual
2738 * source)
2740 job_id = bdrv_get_device_name(bs);
2742 commit_active_start(job_id, top_bs, base_bs, job_flags, speed, on_error,
2743 filter_node_name, NULL, NULL, false, &local_err);
2744 } else {
2745 BlockDriverState *overlay_bs = bdrv_find_overlay(bs, top_bs);
2746 if (bdrv_op_is_blocked(overlay_bs, BLOCK_OP_TYPE_COMMIT_TARGET, errp)) {
2747 goto out;
2749 commit_start(has_job_id ? job_id : NULL, bs, base_bs, top_bs, job_flags,
2750 speed, on_error, has_backing_file ? backing_file : NULL,
2751 filter_node_name, &local_err);
2753 if (local_err != NULL) {
2754 error_propagate(errp, local_err);
2755 goto out;
2758 out:
2759 aio_context_release(aio_context);
2762 /* Common QMP interface for drive-backup and blockdev-backup */
2763 static BlockJob *do_backup_common(BackupCommon *backup,
2764 BlockDriverState *bs,
2765 BlockDriverState *target_bs,
2766 AioContext *aio_context,
2767 JobTxn *txn, Error **errp)
2769 BlockJob *job = NULL;
2770 BdrvDirtyBitmap *bmap = NULL;
2771 BackupPerf perf = { .max_workers = 64 };
2772 int job_flags = JOB_DEFAULT;
2774 if (!backup->has_speed) {
2775 backup->speed = 0;
2777 if (!backup->has_on_source_error) {
2778 backup->on_source_error = BLOCKDEV_ON_ERROR_REPORT;
2780 if (!backup->has_on_target_error) {
2781 backup->on_target_error = BLOCKDEV_ON_ERROR_REPORT;
2783 if (!backup->has_job_id) {
2784 backup->job_id = NULL;
2786 if (!backup->has_auto_finalize) {
2787 backup->auto_finalize = true;
2789 if (!backup->has_auto_dismiss) {
2790 backup->auto_dismiss = true;
2792 if (!backup->has_compress) {
2793 backup->compress = false;
2796 if (backup->x_perf) {
2797 if (backup->x_perf->has_use_copy_range) {
2798 perf.use_copy_range = backup->x_perf->use_copy_range;
2800 if (backup->x_perf->has_max_workers) {
2801 perf.max_workers = backup->x_perf->max_workers;
2803 if (backup->x_perf->has_max_chunk) {
2804 perf.max_chunk = backup->x_perf->max_chunk;
2808 if ((backup->sync == MIRROR_SYNC_MODE_BITMAP) ||
2809 (backup->sync == MIRROR_SYNC_MODE_INCREMENTAL)) {
2810 /* done before desugaring 'incremental' to print the right message */
2811 if (!backup->has_bitmap) {
2812 error_setg(errp, "must provide a valid bitmap name for "
2813 "'%s' sync mode", MirrorSyncMode_str(backup->sync));
2814 return NULL;
2818 if (backup->sync == MIRROR_SYNC_MODE_INCREMENTAL) {
2819 if (backup->has_bitmap_mode &&
2820 backup->bitmap_mode != BITMAP_SYNC_MODE_ON_SUCCESS) {
2821 error_setg(errp, "Bitmap sync mode must be '%s' "
2822 "when using sync mode '%s'",
2823 BitmapSyncMode_str(BITMAP_SYNC_MODE_ON_SUCCESS),
2824 MirrorSyncMode_str(backup->sync));
2825 return NULL;
2827 backup->has_bitmap_mode = true;
2828 backup->sync = MIRROR_SYNC_MODE_BITMAP;
2829 backup->bitmap_mode = BITMAP_SYNC_MODE_ON_SUCCESS;
2832 if (backup->has_bitmap) {
2833 bmap = bdrv_find_dirty_bitmap(bs, backup->bitmap);
2834 if (!bmap) {
2835 error_setg(errp, "Bitmap '%s' could not be found", backup->bitmap);
2836 return NULL;
2838 if (!backup->has_bitmap_mode) {
2839 error_setg(errp, "Bitmap sync mode must be given "
2840 "when providing a bitmap");
2841 return NULL;
2843 if (bdrv_dirty_bitmap_check(bmap, BDRV_BITMAP_ALLOW_RO, errp)) {
2844 return NULL;
2847 /* This does not produce a useful bitmap artifact: */
2848 if (backup->sync == MIRROR_SYNC_MODE_NONE) {
2849 error_setg(errp, "sync mode '%s' does not produce meaningful bitmap"
2850 " outputs", MirrorSyncMode_str(backup->sync));
2851 return NULL;
2854 /* If the bitmap isn't used for input or output, this is useless: */
2855 if (backup->bitmap_mode == BITMAP_SYNC_MODE_NEVER &&
2856 backup->sync != MIRROR_SYNC_MODE_BITMAP) {
2857 error_setg(errp, "Bitmap sync mode '%s' has no meaningful effect"
2858 " when combined with sync mode '%s'",
2859 BitmapSyncMode_str(backup->bitmap_mode),
2860 MirrorSyncMode_str(backup->sync));
2861 return NULL;
2865 if (!backup->has_bitmap && backup->has_bitmap_mode) {
2866 error_setg(errp, "Cannot specify bitmap sync mode without a bitmap");
2867 return NULL;
2870 if (!backup->auto_finalize) {
2871 job_flags |= JOB_MANUAL_FINALIZE;
2873 if (!backup->auto_dismiss) {
2874 job_flags |= JOB_MANUAL_DISMISS;
2877 job = backup_job_create(backup->job_id, bs, target_bs, backup->speed,
2878 backup->sync, bmap, backup->bitmap_mode,
2879 backup->compress,
2880 backup->filter_node_name,
2881 &perf,
2882 backup->on_source_error,
2883 backup->on_target_error,
2884 job_flags, NULL, NULL, txn, errp);
2885 return job;
2888 void qmp_drive_backup(DriveBackup *backup, Error **errp)
2890 TransactionAction action = {
2891 .type = TRANSACTION_ACTION_KIND_DRIVE_BACKUP,
2892 .u.drive_backup.data = backup,
2894 blockdev_do_action(&action, errp);
2897 BlockDeviceInfoList *qmp_query_named_block_nodes(bool has_flat,
2898 bool flat,
2899 Error **errp)
2901 bool return_flat = has_flat && flat;
2903 return bdrv_named_nodes_list(return_flat, errp);
2906 XDbgBlockGraph *qmp_x_debug_query_block_graph(Error **errp)
2908 return bdrv_get_xdbg_block_graph(errp);
2911 void qmp_blockdev_backup(BlockdevBackup *backup, Error **errp)
2913 TransactionAction action = {
2914 .type = TRANSACTION_ACTION_KIND_BLOCKDEV_BACKUP,
2915 .u.blockdev_backup.data = backup,
2917 blockdev_do_action(&action, errp);
2920 /* Parameter check and block job starting for drive mirroring.
2921 * Caller should hold @device and @target's aio context (must be the same).
2923 static void blockdev_mirror_common(const char *job_id, BlockDriverState *bs,
2924 BlockDriverState *target,
2925 bool has_replaces, const char *replaces,
2926 enum MirrorSyncMode sync,
2927 BlockMirrorBackingMode backing_mode,
2928 bool zero_target,
2929 bool has_speed, int64_t speed,
2930 bool has_granularity, uint32_t granularity,
2931 bool has_buf_size, int64_t buf_size,
2932 bool has_on_source_error,
2933 BlockdevOnError on_source_error,
2934 bool has_on_target_error,
2935 BlockdevOnError on_target_error,
2936 bool has_unmap, bool unmap,
2937 bool has_filter_node_name,
2938 const char *filter_node_name,
2939 bool has_copy_mode, MirrorCopyMode copy_mode,
2940 bool has_auto_finalize, bool auto_finalize,
2941 bool has_auto_dismiss, bool auto_dismiss,
2942 Error **errp)
2944 BlockDriverState *unfiltered_bs;
2945 int job_flags = JOB_DEFAULT;
2947 if (!has_speed) {
2948 speed = 0;
2950 if (!has_on_source_error) {
2951 on_source_error = BLOCKDEV_ON_ERROR_REPORT;
2953 if (!has_on_target_error) {
2954 on_target_error = BLOCKDEV_ON_ERROR_REPORT;
2956 if (!has_granularity) {
2957 granularity = 0;
2959 if (!has_buf_size) {
2960 buf_size = 0;
2962 if (!has_unmap) {
2963 unmap = true;
2965 if (!has_filter_node_name) {
2966 filter_node_name = NULL;
2968 if (!has_copy_mode) {
2969 copy_mode = MIRROR_COPY_MODE_BACKGROUND;
2971 if (has_auto_finalize && !auto_finalize) {
2972 job_flags |= JOB_MANUAL_FINALIZE;
2974 if (has_auto_dismiss && !auto_dismiss) {
2975 job_flags |= JOB_MANUAL_DISMISS;
2978 if (granularity != 0 && (granularity < 512 || granularity > 1048576 * 64)) {
2979 error_setg(errp, QERR_INVALID_PARAMETER_VALUE, "granularity",
2980 "a value in range [512B, 64MB]");
2981 return;
2983 if (granularity & (granularity - 1)) {
2984 error_setg(errp, QERR_INVALID_PARAMETER_VALUE, "granularity",
2985 "a power of 2");
2986 return;
2989 if (bdrv_op_is_blocked(bs, BLOCK_OP_TYPE_MIRROR_SOURCE, errp)) {
2990 return;
2992 if (bdrv_op_is_blocked(target, BLOCK_OP_TYPE_MIRROR_TARGET, errp)) {
2993 return;
2996 if (!bdrv_backing_chain_next(bs) && sync == MIRROR_SYNC_MODE_TOP) {
2997 sync = MIRROR_SYNC_MODE_FULL;
3000 if (!has_replaces) {
3001 /* We want to mirror from @bs, but keep implicit filters on top */
3002 unfiltered_bs = bdrv_skip_implicit_filters(bs);
3003 if (unfiltered_bs != bs) {
3004 replaces = unfiltered_bs->node_name;
3005 has_replaces = true;
3009 if (has_replaces) {
3010 BlockDriverState *to_replace_bs;
3011 AioContext *replace_aio_context;
3012 int64_t bs_size, replace_size;
3014 bs_size = bdrv_getlength(bs);
3015 if (bs_size < 0) {
3016 error_setg_errno(errp, -bs_size, "Failed to query device's size");
3017 return;
3020 to_replace_bs = check_to_replace_node(bs, replaces, errp);
3021 if (!to_replace_bs) {
3022 return;
3025 replace_aio_context = bdrv_get_aio_context(to_replace_bs);
3026 aio_context_acquire(replace_aio_context);
3027 replace_size = bdrv_getlength(to_replace_bs);
3028 aio_context_release(replace_aio_context);
3030 if (replace_size < 0) {
3031 error_setg_errno(errp, -replace_size,
3032 "Failed to query the replacement node's size");
3033 return;
3035 if (bs_size != replace_size) {
3036 error_setg(errp, "cannot replace image with a mirror image of "
3037 "different size");
3038 return;
3042 /* pass the node name to replace to mirror start since it's loose coupling
3043 * and will allow to check whether the node still exist at mirror completion
3045 mirror_start(job_id, bs, target,
3046 has_replaces ? replaces : NULL, job_flags,
3047 speed, granularity, buf_size, sync, backing_mode, zero_target,
3048 on_source_error, on_target_error, unmap, filter_node_name,
3049 copy_mode, errp);
3052 void qmp_drive_mirror(DriveMirror *arg, Error **errp)
3054 BlockDriverState *bs;
3055 BlockDriverState *target_backing_bs, *target_bs;
3056 AioContext *aio_context;
3057 AioContext *old_context;
3058 BlockMirrorBackingMode backing_mode;
3059 Error *local_err = NULL;
3060 QDict *options = NULL;
3061 int flags;
3062 int64_t size;
3063 const char *format = arg->format;
3064 bool zero_target;
3065 int ret;
3067 bs = qmp_get_root_bs(arg->device, errp);
3068 if (!bs) {
3069 return;
3072 /* Early check to avoid creating target */
3073 if (bdrv_op_is_blocked(bs, BLOCK_OP_TYPE_MIRROR_SOURCE, errp)) {
3074 return;
3077 aio_context = bdrv_get_aio_context(bs);
3078 aio_context_acquire(aio_context);
3080 if (!arg->has_mode) {
3081 arg->mode = NEW_IMAGE_MODE_ABSOLUTE_PATHS;
3084 if (!arg->has_format) {
3085 format = (arg->mode == NEW_IMAGE_MODE_EXISTING
3086 ? NULL : bs->drv->format_name);
3089 flags = bs->open_flags | BDRV_O_RDWR;
3090 target_backing_bs = bdrv_cow_bs(bdrv_skip_filters(bs));
3091 if (!target_backing_bs && arg->sync == MIRROR_SYNC_MODE_TOP) {
3092 arg->sync = MIRROR_SYNC_MODE_FULL;
3094 if (arg->sync == MIRROR_SYNC_MODE_NONE) {
3095 target_backing_bs = bs;
3098 size = bdrv_getlength(bs);
3099 if (size < 0) {
3100 error_setg_errno(errp, -size, "bdrv_getlength failed");
3101 goto out;
3104 if (arg->has_replaces) {
3105 if (!arg->has_node_name) {
3106 error_setg(errp, "a node-name must be provided when replacing a"
3107 " named node of the graph");
3108 goto out;
3112 if (arg->mode == NEW_IMAGE_MODE_ABSOLUTE_PATHS) {
3113 backing_mode = MIRROR_SOURCE_BACKING_CHAIN;
3114 } else {
3115 backing_mode = MIRROR_OPEN_BACKING_CHAIN;
3118 /* Don't open backing image in create() */
3119 flags |= BDRV_O_NO_BACKING;
3121 if ((arg->sync == MIRROR_SYNC_MODE_FULL || !target_backing_bs)
3122 && arg->mode != NEW_IMAGE_MODE_EXISTING)
3124 /* create new image w/o backing file */
3125 assert(format);
3126 bdrv_img_create(arg->target, format,
3127 NULL, NULL, NULL, size, flags, false, &local_err);
3128 } else {
3129 /* Implicit filters should not appear in the filename */
3130 BlockDriverState *explicit_backing =
3131 bdrv_skip_implicit_filters(target_backing_bs);
3133 switch (arg->mode) {
3134 case NEW_IMAGE_MODE_EXISTING:
3135 break;
3136 case NEW_IMAGE_MODE_ABSOLUTE_PATHS:
3137 /* create new image with backing file */
3138 bdrv_refresh_filename(explicit_backing);
3139 bdrv_img_create(arg->target, format,
3140 explicit_backing->filename,
3141 explicit_backing->drv->format_name,
3142 NULL, size, flags, false, &local_err);
3143 break;
3144 default:
3145 abort();
3149 if (local_err) {
3150 error_propagate(errp, local_err);
3151 goto out;
3154 options = qdict_new();
3155 if (arg->has_node_name) {
3156 qdict_put_str(options, "node-name", arg->node_name);
3158 if (format) {
3159 qdict_put_str(options, "driver", format);
3162 /* Mirroring takes care of copy-on-write using the source's backing
3163 * file.
3165 target_bs = bdrv_open(arg->target, NULL, options, flags, errp);
3166 if (!target_bs) {
3167 goto out;
3170 zero_target = (arg->sync == MIRROR_SYNC_MODE_FULL &&
3171 (arg->mode == NEW_IMAGE_MODE_EXISTING ||
3172 !bdrv_has_zero_init(target_bs)));
3175 /* Honor bdrv_try_set_aio_context() context acquisition requirements. */
3176 old_context = bdrv_get_aio_context(target_bs);
3177 aio_context_release(aio_context);
3178 aio_context_acquire(old_context);
3180 ret = bdrv_try_set_aio_context(target_bs, aio_context, errp);
3181 if (ret < 0) {
3182 bdrv_unref(target_bs);
3183 aio_context_release(old_context);
3184 return;
3187 aio_context_release(old_context);
3188 aio_context_acquire(aio_context);
3190 blockdev_mirror_common(arg->has_job_id ? arg->job_id : NULL, bs, target_bs,
3191 arg->has_replaces, arg->replaces, arg->sync,
3192 backing_mode, zero_target,
3193 arg->has_speed, arg->speed,
3194 arg->has_granularity, arg->granularity,
3195 arg->has_buf_size, arg->buf_size,
3196 arg->has_on_source_error, arg->on_source_error,
3197 arg->has_on_target_error, arg->on_target_error,
3198 arg->has_unmap, arg->unmap,
3199 false, NULL,
3200 arg->has_copy_mode, arg->copy_mode,
3201 arg->has_auto_finalize, arg->auto_finalize,
3202 arg->has_auto_dismiss, arg->auto_dismiss,
3203 errp);
3204 bdrv_unref(target_bs);
3205 out:
3206 aio_context_release(aio_context);
3209 void qmp_blockdev_mirror(bool has_job_id, const char *job_id,
3210 const char *device, const char *target,
3211 bool has_replaces, const char *replaces,
3212 MirrorSyncMode sync,
3213 bool has_speed, int64_t speed,
3214 bool has_granularity, uint32_t granularity,
3215 bool has_buf_size, int64_t buf_size,
3216 bool has_on_source_error,
3217 BlockdevOnError on_source_error,
3218 bool has_on_target_error,
3219 BlockdevOnError on_target_error,
3220 bool has_filter_node_name,
3221 const char *filter_node_name,
3222 bool has_copy_mode, MirrorCopyMode copy_mode,
3223 bool has_auto_finalize, bool auto_finalize,
3224 bool has_auto_dismiss, bool auto_dismiss,
3225 Error **errp)
3227 BlockDriverState *bs;
3228 BlockDriverState *target_bs;
3229 AioContext *aio_context;
3230 AioContext *old_context;
3231 BlockMirrorBackingMode backing_mode = MIRROR_LEAVE_BACKING_CHAIN;
3232 bool zero_target;
3233 int ret;
3235 bs = qmp_get_root_bs(device, errp);
3236 if (!bs) {
3237 return;
3240 target_bs = bdrv_lookup_bs(target, target, errp);
3241 if (!target_bs) {
3242 return;
3245 zero_target = (sync == MIRROR_SYNC_MODE_FULL);
3247 /* Honor bdrv_try_set_aio_context() context acquisition requirements. */
3248 old_context = bdrv_get_aio_context(target_bs);
3249 aio_context = bdrv_get_aio_context(bs);
3250 aio_context_acquire(old_context);
3252 ret = bdrv_try_set_aio_context(target_bs, aio_context, errp);
3254 aio_context_release(old_context);
3255 aio_context_acquire(aio_context);
3257 if (ret < 0) {
3258 goto out;
3261 blockdev_mirror_common(has_job_id ? job_id : NULL, bs, target_bs,
3262 has_replaces, replaces, sync, backing_mode,
3263 zero_target, has_speed, speed,
3264 has_granularity, granularity,
3265 has_buf_size, buf_size,
3266 has_on_source_error, on_source_error,
3267 has_on_target_error, on_target_error,
3268 true, true,
3269 has_filter_node_name, filter_node_name,
3270 has_copy_mode, copy_mode,
3271 has_auto_finalize, auto_finalize,
3272 has_auto_dismiss, auto_dismiss,
3273 errp);
3274 out:
3275 aio_context_release(aio_context);
3278 /* Get a block job using its ID and acquire its AioContext */
3279 static BlockJob *find_block_job(const char *id, AioContext **aio_context,
3280 Error **errp)
3282 BlockJob *job;
3284 assert(id != NULL);
3286 *aio_context = NULL;
3288 job = block_job_get(id);
3290 if (!job) {
3291 error_set(errp, ERROR_CLASS_DEVICE_NOT_ACTIVE,
3292 "Block job '%s' not found", id);
3293 return NULL;
3296 *aio_context = block_job_get_aio_context(job);
3297 aio_context_acquire(*aio_context);
3299 return job;
3302 void qmp_block_job_set_speed(const char *device, int64_t speed, Error **errp)
3304 AioContext *aio_context;
3305 BlockJob *job = find_block_job(device, &aio_context, errp);
3307 if (!job) {
3308 return;
3311 block_job_set_speed(job, speed, errp);
3312 aio_context_release(aio_context);
3315 void qmp_block_job_cancel(const char *device,
3316 bool has_force, bool force, Error **errp)
3318 AioContext *aio_context;
3319 BlockJob *job = find_block_job(device, &aio_context, errp);
3321 if (!job) {
3322 return;
3325 if (!has_force) {
3326 force = false;
3329 if (job_user_paused(&job->job) && !force) {
3330 error_setg(errp, "The block job for device '%s' is currently paused",
3331 device);
3332 goto out;
3335 trace_qmp_block_job_cancel(job);
3336 job_user_cancel(&job->job, force, errp);
3337 out:
3338 aio_context_release(aio_context);
3341 void qmp_block_job_pause(const char *device, Error **errp)
3343 AioContext *aio_context;
3344 BlockJob *job = find_block_job(device, &aio_context, errp);
3346 if (!job) {
3347 return;
3350 trace_qmp_block_job_pause(job);
3351 job_user_pause(&job->job, errp);
3352 aio_context_release(aio_context);
3355 void qmp_block_job_resume(const char *device, Error **errp)
3357 AioContext *aio_context;
3358 BlockJob *job = find_block_job(device, &aio_context, errp);
3360 if (!job) {
3361 return;
3364 trace_qmp_block_job_resume(job);
3365 job_user_resume(&job->job, errp);
3366 aio_context_release(aio_context);
3369 void qmp_block_job_complete(const char *device, Error **errp)
3371 AioContext *aio_context;
3372 BlockJob *job = find_block_job(device, &aio_context, errp);
3374 if (!job) {
3375 return;
3378 trace_qmp_block_job_complete(job);
3379 job_complete(&job->job, errp);
3380 aio_context_release(aio_context);
3383 void qmp_block_job_finalize(const char *id, Error **errp)
3385 AioContext *aio_context;
3386 BlockJob *job = find_block_job(id, &aio_context, errp);
3388 if (!job) {
3389 return;
3392 trace_qmp_block_job_finalize(job);
3393 job_ref(&job->job);
3394 job_finalize(&job->job, errp);
3397 * Job's context might have changed via job_finalize (and job_txn_apply
3398 * automatically acquires the new one), so make sure we release the correct
3399 * one.
3401 aio_context = block_job_get_aio_context(job);
3402 job_unref(&job->job);
3403 aio_context_release(aio_context);
3406 void qmp_block_job_dismiss(const char *id, Error **errp)
3408 AioContext *aio_context;
3409 BlockJob *bjob = find_block_job(id, &aio_context, errp);
3410 Job *job;
3412 if (!bjob) {
3413 return;
3416 trace_qmp_block_job_dismiss(bjob);
3417 job = &bjob->job;
3418 job_dismiss(&job, errp);
3419 aio_context_release(aio_context);
3422 void qmp_change_backing_file(const char *device,
3423 const char *image_node_name,
3424 const char *backing_file,
3425 Error **errp)
3427 BlockDriverState *bs = NULL;
3428 AioContext *aio_context;
3429 BlockDriverState *image_bs = NULL;
3430 Error *local_err = NULL;
3431 bool ro;
3432 int ret;
3434 bs = qmp_get_root_bs(device, errp);
3435 if (!bs) {
3436 return;
3439 aio_context = bdrv_get_aio_context(bs);
3440 aio_context_acquire(aio_context);
3442 image_bs = bdrv_lookup_bs(NULL, image_node_name, &local_err);
3443 if (local_err) {
3444 error_propagate(errp, local_err);
3445 goto out;
3448 if (!image_bs) {
3449 error_setg(errp, "image file not found");
3450 goto out;
3453 if (bdrv_find_base(image_bs) == image_bs) {
3454 error_setg(errp, "not allowing backing file change on an image "
3455 "without a backing file");
3456 goto out;
3459 /* even though we are not necessarily operating on bs, we need it to
3460 * determine if block ops are currently prohibited on the chain */
3461 if (bdrv_op_is_blocked(bs, BLOCK_OP_TYPE_CHANGE, errp)) {
3462 goto out;
3465 /* final sanity check */
3466 if (!bdrv_chain_contains(bs, image_bs)) {
3467 error_setg(errp, "'%s' and image file are not in the same chain",
3468 device);
3469 goto out;
3472 /* if not r/w, reopen to make r/w */
3473 ro = bdrv_is_read_only(image_bs);
3475 if (ro) {
3476 if (bdrv_reopen_set_read_only(image_bs, false, errp) != 0) {
3477 goto out;
3481 ret = bdrv_change_backing_file(image_bs, backing_file,
3482 image_bs->drv ? image_bs->drv->format_name : "",
3483 false);
3485 if (ret < 0) {
3486 error_setg_errno(errp, -ret, "Could not change backing file to '%s'",
3487 backing_file);
3488 /* don't exit here, so we can try to restore open flags if
3489 * appropriate */
3492 if (ro) {
3493 bdrv_reopen_set_read_only(image_bs, true, errp);
3496 out:
3497 aio_context_release(aio_context);
3500 void qmp_blockdev_add(BlockdevOptions *options, Error **errp)
3502 BlockDriverState *bs;
3503 QObject *obj;
3504 Visitor *v = qobject_output_visitor_new(&obj);
3505 QDict *qdict;
3507 visit_type_BlockdevOptions(v, NULL, &options, &error_abort);
3508 visit_complete(v, &obj);
3509 qdict = qobject_to(QDict, obj);
3511 qdict_flatten(qdict);
3513 if (!qdict_get_try_str(qdict, "node-name")) {
3514 error_setg(errp, "'node-name' must be specified for the root node");
3515 goto fail;
3518 bs = bds_tree_init(qdict, errp);
3519 if (!bs) {
3520 goto fail;
3523 bdrv_set_monitor_owned(bs);
3525 fail:
3526 visit_free(v);
3529 void qmp_blockdev_reopen(BlockdevOptionsList *reopen_list, Error **errp)
3531 BlockReopenQueue *queue = NULL;
3532 GSList *drained = NULL;
3533 GSList *p;
3535 /* Add each one of the BDS that we want to reopen to the queue */
3536 for (; reopen_list != NULL; reopen_list = reopen_list->next) {
3537 BlockdevOptions *options = reopen_list->value;
3538 BlockDriverState *bs;
3539 AioContext *ctx;
3540 QObject *obj;
3541 Visitor *v;
3542 QDict *qdict;
3544 /* Check for the selected node name */
3545 if (!options->has_node_name) {
3546 error_setg(errp, "node-name not specified");
3547 goto fail;
3550 bs = bdrv_find_node(options->node_name);
3551 if (!bs) {
3552 error_setg(errp, "Failed to find node with node-name='%s'",
3553 options->node_name);
3554 goto fail;
3557 /* Put all options in a QDict and flatten it */
3558 v = qobject_output_visitor_new(&obj);
3559 visit_type_BlockdevOptions(v, NULL, &options, &error_abort);
3560 visit_complete(v, &obj);
3561 visit_free(v);
3563 qdict = qobject_to(QDict, obj);
3565 qdict_flatten(qdict);
3567 ctx = bdrv_get_aio_context(bs);
3568 aio_context_acquire(ctx);
3570 bdrv_subtree_drained_begin(bs);
3571 queue = bdrv_reopen_queue(queue, bs, qdict, false);
3572 drained = g_slist_prepend(drained, bs);
3574 aio_context_release(ctx);
3577 /* Perform the reopen operation */
3578 bdrv_reopen_multiple(queue, errp);
3579 queue = NULL;
3581 fail:
3582 bdrv_reopen_queue_free(queue);
3583 for (p = drained; p; p = p->next) {
3584 BlockDriverState *bs = p->data;
3585 AioContext *ctx = bdrv_get_aio_context(bs);
3587 aio_context_acquire(ctx);
3588 bdrv_subtree_drained_end(bs);
3589 aio_context_release(ctx);
3591 g_slist_free(drained);
3594 void qmp_blockdev_del(const char *node_name, Error **errp)
3596 AioContext *aio_context;
3597 BlockDriverState *bs;
3599 bs = bdrv_find_node(node_name);
3600 if (!bs) {
3601 error_setg(errp, "Failed to find node with node-name='%s'", node_name);
3602 return;
3604 if (bdrv_has_blk(bs)) {
3605 error_setg(errp, "Node %s is in use", node_name);
3606 return;
3608 aio_context = bdrv_get_aio_context(bs);
3609 aio_context_acquire(aio_context);
3611 if (bdrv_op_is_blocked(bs, BLOCK_OP_TYPE_DRIVE_DEL, errp)) {
3612 goto out;
3615 if (!QTAILQ_IN_USE(bs, monitor_list)) {
3616 error_setg(errp, "Node %s is not owned by the monitor",
3617 bs->node_name);
3618 goto out;
3621 if (bs->refcnt > 1) {
3622 error_setg(errp, "Block device %s is in use",
3623 bdrv_get_device_or_node_name(bs));
3624 goto out;
3627 QTAILQ_REMOVE(&monitor_bdrv_states, bs, monitor_list);
3628 bdrv_unref(bs);
3630 out:
3631 aio_context_release(aio_context);
3634 static BdrvChild *bdrv_find_child(BlockDriverState *parent_bs,
3635 const char *child_name)
3637 BdrvChild *child;
3639 QLIST_FOREACH(child, &parent_bs->children, next) {
3640 if (strcmp(child->name, child_name) == 0) {
3641 return child;
3645 return NULL;
3648 void qmp_x_blockdev_change(const char *parent, bool has_child,
3649 const char *child, bool has_node,
3650 const char *node, Error **errp)
3652 BlockDriverState *parent_bs, *new_bs = NULL;
3653 BdrvChild *p_child;
3655 parent_bs = bdrv_lookup_bs(parent, parent, errp);
3656 if (!parent_bs) {
3657 return;
3660 if (has_child == has_node) {
3661 if (has_child) {
3662 error_setg(errp, "The parameters child and node are in conflict");
3663 } else {
3664 error_setg(errp, "Either child or node must be specified");
3666 return;
3669 if (has_child) {
3670 p_child = bdrv_find_child(parent_bs, child);
3671 if (!p_child) {
3672 error_setg(errp, "Node '%s' does not have child '%s'",
3673 parent, child);
3674 return;
3676 bdrv_del_child(parent_bs, p_child, errp);
3679 if (has_node) {
3680 new_bs = bdrv_find_node(node);
3681 if (!new_bs) {
3682 error_setg(errp, "Node '%s' not found", node);
3683 return;
3685 bdrv_add_child(parent_bs, new_bs, errp);
3689 BlockJobInfoList *qmp_query_block_jobs(Error **errp)
3691 BlockJobInfoList *head = NULL, **tail = &head;
3692 BlockJob *job;
3694 for (job = block_job_next(NULL); job; job = block_job_next(job)) {
3695 BlockJobInfo *value;
3696 AioContext *aio_context;
3698 if (block_job_is_internal(job)) {
3699 continue;
3701 aio_context = block_job_get_aio_context(job);
3702 aio_context_acquire(aio_context);
3703 value = block_job_query(job, errp);
3704 aio_context_release(aio_context);
3705 if (!value) {
3706 qapi_free_BlockJobInfoList(head);
3707 return NULL;
3709 QAPI_LIST_APPEND(tail, value);
3712 return head;
3715 void qmp_x_blockdev_set_iothread(const char *node_name, StrOrNull *iothread,
3716 bool has_force, bool force, Error **errp)
3718 AioContext *old_context;
3719 AioContext *new_context;
3720 BlockDriverState *bs;
3722 bs = bdrv_find_node(node_name);
3723 if (!bs) {
3724 error_setg(errp, "Failed to find node with node-name='%s'", node_name);
3725 return;
3728 /* Protects against accidents. */
3729 if (!(has_force && force) && bdrv_has_blk(bs)) {
3730 error_setg(errp, "Node %s is associated with a BlockBackend and could "
3731 "be in use (use force=true to override this check)",
3732 node_name);
3733 return;
3736 if (iothread->type == QTYPE_QSTRING) {
3737 IOThread *obj = iothread_by_id(iothread->u.s);
3738 if (!obj) {
3739 error_setg(errp, "Cannot find iothread %s", iothread->u.s);
3740 return;
3743 new_context = iothread_get_aio_context(obj);
3744 } else {
3745 new_context = qemu_get_aio_context();
3748 old_context = bdrv_get_aio_context(bs);
3749 aio_context_acquire(old_context);
3751 bdrv_try_set_aio_context(bs, new_context, errp);
3753 aio_context_release(old_context);
3756 QemuOptsList qemu_common_drive_opts = {
3757 .name = "drive",
3758 .head = QTAILQ_HEAD_INITIALIZER(qemu_common_drive_opts.head),
3759 .desc = {
3761 .name = "snapshot",
3762 .type = QEMU_OPT_BOOL,
3763 .help = "enable/disable snapshot mode",
3765 .name = "aio",
3766 .type = QEMU_OPT_STRING,
3767 .help = "host AIO implementation (threads, native, io_uring)",
3769 .name = BDRV_OPT_CACHE_WB,
3770 .type = QEMU_OPT_BOOL,
3771 .help = "Enable writeback mode",
3773 .name = "format",
3774 .type = QEMU_OPT_STRING,
3775 .help = "disk format (raw, qcow2, ...)",
3777 .name = "rerror",
3778 .type = QEMU_OPT_STRING,
3779 .help = "read error action",
3781 .name = "werror",
3782 .type = QEMU_OPT_STRING,
3783 .help = "write error action",
3785 .name = BDRV_OPT_READ_ONLY,
3786 .type = QEMU_OPT_BOOL,
3787 .help = "open drive file as read-only",
3790 THROTTLE_OPTS,
3793 .name = "throttling.group",
3794 .type = QEMU_OPT_STRING,
3795 .help = "name of the block throttling group",
3797 .name = "copy-on-read",
3798 .type = QEMU_OPT_BOOL,
3799 .help = "copy read data from backing file into image file",
3801 .name = "detect-zeroes",
3802 .type = QEMU_OPT_STRING,
3803 .help = "try to optimize zero writes (off, on, unmap)",
3805 .name = "stats-account-invalid",
3806 .type = QEMU_OPT_BOOL,
3807 .help = "whether to account for invalid I/O operations "
3808 "in the statistics",
3810 .name = "stats-account-failed",
3811 .type = QEMU_OPT_BOOL,
3812 .help = "whether to account for failed I/O operations "
3813 "in the statistics",
3815 { /* end of list */ }
3819 QemuOptsList qemu_drive_opts = {
3820 .name = "drive",
3821 .head = QTAILQ_HEAD_INITIALIZER(qemu_drive_opts.head),
3822 .desc = {
3824 * no elements => accept any params
3825 * validation will happen later
3827 { /* end of list */ }