malta: Move PCI interrupt handling from gt64xxx_pci to piix4
[qemu/armbru.git] / blockdev.c
blobe46e8312121e23ab8ad9f0cd7b0735e904902b8b
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 /* Protected by BQL */
67 QTAILQ_HEAD(, BlockDriverState) monitor_bdrv_states =
68 QTAILQ_HEAD_INITIALIZER(monitor_bdrv_states);
70 void bdrv_set_monitor_owned(BlockDriverState *bs)
72 GLOBAL_STATE_CODE();
73 QTAILQ_INSERT_TAIL(&monitor_bdrv_states, bs, monitor_list);
76 static const char *const if_name[IF_COUNT] = {
77 [IF_NONE] = "none",
78 [IF_IDE] = "ide",
79 [IF_SCSI] = "scsi",
80 [IF_FLOPPY] = "floppy",
81 [IF_PFLASH] = "pflash",
82 [IF_MTD] = "mtd",
83 [IF_SD] = "sd",
84 [IF_VIRTIO] = "virtio",
85 [IF_XEN] = "xen",
88 static int if_max_devs[IF_COUNT] = {
90 * Do not change these numbers! They govern how drive option
91 * index maps to unit and bus. That mapping is ABI.
93 * All controllers used to implement if=T drives need to support
94 * if_max_devs[T] units, for any T with if_max_devs[T] != 0.
95 * Otherwise, some index values map to "impossible" bus, unit
96 * values.
98 * For instance, if you change [IF_SCSI] to 255, -drive
99 * if=scsi,index=12 no longer means bus=1,unit=5, but
100 * bus=0,unit=12. With an lsi53c895a controller (7 units max),
101 * the drive can't be set up. Regression.
103 [IF_IDE] = 2,
104 [IF_SCSI] = 7,
108 * Boards may call this to offer board-by-board overrides
109 * of the default, global values.
111 void override_max_devs(BlockInterfaceType type, int max_devs)
113 BlockBackend *blk;
114 DriveInfo *dinfo;
116 GLOBAL_STATE_CODE();
118 if (max_devs <= 0) {
119 return;
122 for (blk = blk_next(NULL); blk; blk = blk_next(blk)) {
123 dinfo = blk_legacy_dinfo(blk);
124 if (dinfo->type == type) {
125 fprintf(stderr, "Cannot override units-per-bus property of"
126 " the %s interface, because a drive of that type has"
127 " already been added.\n", if_name[type]);
128 g_assert_not_reached();
132 if_max_devs[type] = max_devs;
136 * We automatically delete the drive when a device using it gets
137 * unplugged. Questionable feature, but we can't just drop it.
138 * Device models call blockdev_mark_auto_del() to schedule the
139 * automatic deletion, and generic qdev code calls blockdev_auto_del()
140 * when deletion is actually safe.
142 void blockdev_mark_auto_del(BlockBackend *blk)
144 DriveInfo *dinfo = blk_legacy_dinfo(blk);
145 BlockJob *job;
147 GLOBAL_STATE_CODE();
149 if (!dinfo) {
150 return;
153 for (job = block_job_next(NULL); job; job = block_job_next(job)) {
154 if (block_job_has_bdrv(job, blk_bs(blk))) {
155 AioContext *aio_context = job->job.aio_context;
156 aio_context_acquire(aio_context);
158 job_cancel(&job->job, false);
160 aio_context_release(aio_context);
164 dinfo->auto_del = 1;
167 void blockdev_auto_del(BlockBackend *blk)
169 DriveInfo *dinfo = blk_legacy_dinfo(blk);
170 GLOBAL_STATE_CODE();
172 if (dinfo && dinfo->auto_del) {
173 monitor_remove_blk(blk);
174 blk_unref(blk);
178 static int drive_index_to_bus_id(BlockInterfaceType type, int index)
180 int max_devs = if_max_devs[type];
181 return max_devs ? index / max_devs : 0;
184 static int drive_index_to_unit_id(BlockInterfaceType type, int index)
186 int max_devs = if_max_devs[type];
187 return max_devs ? index % max_devs : index;
190 QemuOpts *drive_add(BlockInterfaceType type, int index, const char *file,
191 const char *optstr)
193 QemuOpts *opts;
195 GLOBAL_STATE_CODE();
197 opts = qemu_opts_parse_noisily(qemu_find_opts("drive"), optstr, false);
198 if (!opts) {
199 return NULL;
201 if (type != IF_DEFAULT) {
202 qemu_opt_set(opts, "if", if_name[type], &error_abort);
204 if (index >= 0) {
205 qemu_opt_set_number(opts, "index", index, &error_abort);
207 if (file)
208 qemu_opt_set(opts, "file", file, &error_abort);
209 return opts;
212 DriveInfo *drive_get(BlockInterfaceType type, int bus, int unit)
214 BlockBackend *blk;
215 DriveInfo *dinfo;
217 GLOBAL_STATE_CODE();
219 for (blk = blk_next(NULL); blk; blk = blk_next(blk)) {
220 dinfo = blk_legacy_dinfo(blk);
221 if (dinfo && dinfo->type == type
222 && dinfo->bus == bus && dinfo->unit == unit) {
223 return dinfo;
227 return NULL;
231 * Check board claimed all -drive that are meant to be claimed.
232 * Fatal error if any remain unclaimed.
234 void drive_check_orphaned(void)
236 BlockBackend *blk;
237 DriveInfo *dinfo;
238 Location loc;
239 bool orphans = false;
241 GLOBAL_STATE_CODE();
243 for (blk = blk_next(NULL); blk; blk = blk_next(blk)) {
244 dinfo = blk_legacy_dinfo(blk);
246 * Ignore default drives, because we create certain default
247 * drives unconditionally, then leave them unclaimed. Not the
248 * users fault.
249 * Ignore IF_VIRTIO, because it gets desugared into -device,
250 * so we can leave failing to -device.
251 * Ignore IF_NONE, because leaving unclaimed IF_NONE remains
252 * available for device_add is a feature.
254 if (dinfo->is_default || dinfo->type == IF_VIRTIO
255 || dinfo->type == IF_NONE) {
256 continue;
258 if (!blk_get_attached_dev(blk)) {
259 loc_push_none(&loc);
260 qemu_opts_loc_restore(dinfo->opts);
261 error_report("machine type does not support"
262 " if=%s,bus=%d,unit=%d",
263 if_name[dinfo->type], dinfo->bus, dinfo->unit);
264 loc_pop(&loc);
265 orphans = true;
269 if (orphans) {
270 exit(1);
274 DriveInfo *drive_get_by_index(BlockInterfaceType type, int index)
276 GLOBAL_STATE_CODE();
277 return drive_get(type,
278 drive_index_to_bus_id(type, index),
279 drive_index_to_unit_id(type, index));
282 int drive_get_max_bus(BlockInterfaceType type)
284 int max_bus;
285 BlockBackend *blk;
286 DriveInfo *dinfo;
288 GLOBAL_STATE_CODE();
290 max_bus = -1;
291 for (blk = blk_next(NULL); blk; blk = blk_next(blk)) {
292 dinfo = blk_legacy_dinfo(blk);
293 if (dinfo && dinfo->type == type && dinfo->bus > max_bus) {
294 max_bus = dinfo->bus;
297 return max_bus;
300 static void bdrv_format_print(void *opaque, const char *name)
302 qemu_printf(" %s", name);
305 typedef struct {
306 QEMUBH *bh;
307 BlockDriverState *bs;
308 } BDRVPutRefBH;
310 static int parse_block_error_action(const char *buf, bool is_read, Error **errp)
312 if (!strcmp(buf, "ignore")) {
313 return BLOCKDEV_ON_ERROR_IGNORE;
314 } else if (!is_read && !strcmp(buf, "enospc")) {
315 return BLOCKDEV_ON_ERROR_ENOSPC;
316 } else if (!strcmp(buf, "stop")) {
317 return BLOCKDEV_ON_ERROR_STOP;
318 } else if (!strcmp(buf, "report")) {
319 return BLOCKDEV_ON_ERROR_REPORT;
320 } else {
321 error_setg(errp, "'%s' invalid %s error action",
322 buf, is_read ? "read" : "write");
323 return -1;
327 static bool parse_stats_intervals(BlockAcctStats *stats, QList *intervals,
328 Error **errp)
330 const QListEntry *entry;
331 for (entry = qlist_first(intervals); entry; entry = qlist_next(entry)) {
332 switch (qobject_type(entry->value)) {
334 case QTYPE_QSTRING: {
335 unsigned long long length;
336 const char *str = qstring_get_str(qobject_to(QString,
337 entry->value));
338 if (parse_uint_full(str, &length, 10) == 0 &&
339 length > 0 && length <= UINT_MAX) {
340 block_acct_add_interval(stats, (unsigned) length);
341 } else {
342 error_setg(errp, "Invalid interval length: %s", str);
343 return false;
345 break;
348 case QTYPE_QNUM: {
349 int64_t length = qnum_get_int(qobject_to(QNum, entry->value));
351 if (length > 0 && length <= UINT_MAX) {
352 block_acct_add_interval(stats, (unsigned) length);
353 } else {
354 error_setg(errp, "Invalid interval length: %" PRId64, length);
355 return false;
357 break;
360 default:
361 error_setg(errp, "The specification of stats-intervals is invalid");
362 return false;
365 return true;
368 typedef enum { MEDIA_DISK, MEDIA_CDROM } DriveMediaType;
370 /* All parameters but @opts are optional and may be set to NULL. */
371 static void extract_common_blockdev_options(QemuOpts *opts, int *bdrv_flags,
372 const char **throttling_group, ThrottleConfig *throttle_cfg,
373 BlockdevDetectZeroesOptions *detect_zeroes, Error **errp)
375 Error *local_error = NULL;
376 const char *aio;
378 if (bdrv_flags) {
379 if (qemu_opt_get_bool(opts, "copy-on-read", false)) {
380 *bdrv_flags |= BDRV_O_COPY_ON_READ;
383 if ((aio = qemu_opt_get(opts, "aio")) != NULL) {
384 if (bdrv_parse_aio(aio, bdrv_flags) < 0) {
385 error_setg(errp, "invalid aio option");
386 return;
391 /* disk I/O throttling */
392 if (throttling_group) {
393 *throttling_group = qemu_opt_get(opts, "throttling.group");
396 if (throttle_cfg) {
397 throttle_config_init(throttle_cfg);
398 throttle_cfg->buckets[THROTTLE_BPS_TOTAL].avg =
399 qemu_opt_get_number(opts, "throttling.bps-total", 0);
400 throttle_cfg->buckets[THROTTLE_BPS_READ].avg =
401 qemu_opt_get_number(opts, "throttling.bps-read", 0);
402 throttle_cfg->buckets[THROTTLE_BPS_WRITE].avg =
403 qemu_opt_get_number(opts, "throttling.bps-write", 0);
404 throttle_cfg->buckets[THROTTLE_OPS_TOTAL].avg =
405 qemu_opt_get_number(opts, "throttling.iops-total", 0);
406 throttle_cfg->buckets[THROTTLE_OPS_READ].avg =
407 qemu_opt_get_number(opts, "throttling.iops-read", 0);
408 throttle_cfg->buckets[THROTTLE_OPS_WRITE].avg =
409 qemu_opt_get_number(opts, "throttling.iops-write", 0);
411 throttle_cfg->buckets[THROTTLE_BPS_TOTAL].max =
412 qemu_opt_get_number(opts, "throttling.bps-total-max", 0);
413 throttle_cfg->buckets[THROTTLE_BPS_READ].max =
414 qemu_opt_get_number(opts, "throttling.bps-read-max", 0);
415 throttle_cfg->buckets[THROTTLE_BPS_WRITE].max =
416 qemu_opt_get_number(opts, "throttling.bps-write-max", 0);
417 throttle_cfg->buckets[THROTTLE_OPS_TOTAL].max =
418 qemu_opt_get_number(opts, "throttling.iops-total-max", 0);
419 throttle_cfg->buckets[THROTTLE_OPS_READ].max =
420 qemu_opt_get_number(opts, "throttling.iops-read-max", 0);
421 throttle_cfg->buckets[THROTTLE_OPS_WRITE].max =
422 qemu_opt_get_number(opts, "throttling.iops-write-max", 0);
424 throttle_cfg->buckets[THROTTLE_BPS_TOTAL].burst_length =
425 qemu_opt_get_number(opts, "throttling.bps-total-max-length", 1);
426 throttle_cfg->buckets[THROTTLE_BPS_READ].burst_length =
427 qemu_opt_get_number(opts, "throttling.bps-read-max-length", 1);
428 throttle_cfg->buckets[THROTTLE_BPS_WRITE].burst_length =
429 qemu_opt_get_number(opts, "throttling.bps-write-max-length", 1);
430 throttle_cfg->buckets[THROTTLE_OPS_TOTAL].burst_length =
431 qemu_opt_get_number(opts, "throttling.iops-total-max-length", 1);
432 throttle_cfg->buckets[THROTTLE_OPS_READ].burst_length =
433 qemu_opt_get_number(opts, "throttling.iops-read-max-length", 1);
434 throttle_cfg->buckets[THROTTLE_OPS_WRITE].burst_length =
435 qemu_opt_get_number(opts, "throttling.iops-write-max-length", 1);
437 throttle_cfg->op_size =
438 qemu_opt_get_number(opts, "throttling.iops-size", 0);
440 if (!throttle_is_valid(throttle_cfg, errp)) {
441 return;
445 if (detect_zeroes) {
446 *detect_zeroes =
447 qapi_enum_parse(&BlockdevDetectZeroesOptions_lookup,
448 qemu_opt_get(opts, "detect-zeroes"),
449 BLOCKDEV_DETECT_ZEROES_OPTIONS_OFF,
450 &local_error);
451 if (local_error) {
452 error_propagate(errp, local_error);
453 return;
458 /* Takes the ownership of bs_opts */
459 static BlockBackend *blockdev_init(const char *file, QDict *bs_opts,
460 Error **errp)
462 const char *buf;
463 int bdrv_flags = 0;
464 int on_read_error, on_write_error;
465 bool account_invalid, account_failed;
466 bool writethrough, read_only;
467 BlockBackend *blk;
468 BlockDriverState *bs;
469 ThrottleConfig cfg;
470 int snapshot = 0;
471 Error *error = NULL;
472 QemuOpts *opts;
473 QDict *interval_dict = NULL;
474 QList *interval_list = NULL;
475 const char *id;
476 BlockdevDetectZeroesOptions detect_zeroes =
477 BLOCKDEV_DETECT_ZEROES_OPTIONS_OFF;
478 const char *throttling_group = NULL;
480 /* Check common options by copying from bs_opts to opts, all other options
481 * stay in bs_opts for processing by bdrv_open(). */
482 id = qdict_get_try_str(bs_opts, "id");
483 opts = qemu_opts_create(&qemu_common_drive_opts, id, 1, errp);
484 if (!opts) {
485 goto err_no_opts;
488 if (!qemu_opts_absorb_qdict(opts, bs_opts, errp)) {
489 goto early_err;
492 if (id) {
493 qdict_del(bs_opts, "id");
496 /* extract parameters */
497 snapshot = qemu_opt_get_bool(opts, "snapshot", 0);
499 account_invalid = qemu_opt_get_bool(opts, "stats-account-invalid", true);
500 account_failed = qemu_opt_get_bool(opts, "stats-account-failed", true);
502 writethrough = !qemu_opt_get_bool(opts, BDRV_OPT_CACHE_WB, true);
504 id = qemu_opts_id(opts);
506 qdict_extract_subqdict(bs_opts, &interval_dict, "stats-intervals.");
507 qdict_array_split(interval_dict, &interval_list);
509 if (qdict_size(interval_dict) != 0) {
510 error_setg(errp, "Invalid option stats-intervals.%s",
511 qdict_first(interval_dict)->key);
512 goto early_err;
515 extract_common_blockdev_options(opts, &bdrv_flags, &throttling_group, &cfg,
516 &detect_zeroes, &error);
517 if (error) {
518 error_propagate(errp, error);
519 goto early_err;
522 if ((buf = qemu_opt_get(opts, "format")) != NULL) {
523 if (is_help_option(buf)) {
524 qemu_printf("Supported formats:");
525 bdrv_iterate_format(bdrv_format_print, NULL, false);
526 qemu_printf("\nSupported formats (read-only):");
527 bdrv_iterate_format(bdrv_format_print, NULL, true);
528 qemu_printf("\n");
529 goto early_err;
532 if (qdict_haskey(bs_opts, "driver")) {
533 error_setg(errp, "Cannot specify both 'driver' and 'format'");
534 goto early_err;
536 qdict_put_str(bs_opts, "driver", buf);
539 on_write_error = BLOCKDEV_ON_ERROR_ENOSPC;
540 if ((buf = qemu_opt_get(opts, "werror")) != NULL) {
541 on_write_error = parse_block_error_action(buf, 0, &error);
542 if (error) {
543 error_propagate(errp, error);
544 goto early_err;
548 on_read_error = BLOCKDEV_ON_ERROR_REPORT;
549 if ((buf = qemu_opt_get(opts, "rerror")) != NULL) {
550 on_read_error = parse_block_error_action(buf, 1, &error);
551 if (error) {
552 error_propagate(errp, error);
553 goto early_err;
557 if (snapshot) {
558 bdrv_flags |= BDRV_O_SNAPSHOT;
561 read_only = qemu_opt_get_bool(opts, BDRV_OPT_READ_ONLY, false);
563 /* init */
564 if ((!file || !*file) && !qdict_size(bs_opts)) {
565 BlockBackendRootState *blk_rs;
567 blk = blk_new(qemu_get_aio_context(), 0, BLK_PERM_ALL);
568 blk_rs = blk_get_root_state(blk);
569 blk_rs->open_flags = bdrv_flags | (read_only ? 0 : BDRV_O_RDWR);
570 blk_rs->detect_zeroes = detect_zeroes;
572 qobject_unref(bs_opts);
573 } else {
574 if (file && !*file) {
575 file = NULL;
578 /* bdrv_open() defaults to the values in bdrv_flags (for compatibility
579 * with other callers) rather than what we want as the real defaults.
580 * Apply the defaults here instead. */
581 qdict_set_default_str(bs_opts, BDRV_OPT_CACHE_DIRECT, "off");
582 qdict_set_default_str(bs_opts, BDRV_OPT_CACHE_NO_FLUSH, "off");
583 qdict_set_default_str(bs_opts, BDRV_OPT_READ_ONLY,
584 read_only ? "on" : "off");
585 qdict_set_default_str(bs_opts, BDRV_OPT_AUTO_READ_ONLY, "on");
586 assert((bdrv_flags & BDRV_O_CACHE_MASK) == 0);
588 if (runstate_check(RUN_STATE_INMIGRATE)) {
589 bdrv_flags |= BDRV_O_INACTIVE;
592 blk = blk_new_open(file, NULL, bs_opts, bdrv_flags, errp);
593 if (!blk) {
594 goto err_no_bs_opts;
596 bs = blk_bs(blk);
598 bs->detect_zeroes = detect_zeroes;
600 block_acct_setup(blk_get_stats(blk), account_invalid, account_failed);
602 if (!parse_stats_intervals(blk_get_stats(blk), interval_list, errp)) {
603 blk_unref(blk);
604 blk = NULL;
605 goto err_no_bs_opts;
609 /* disk I/O throttling */
610 if (throttle_enabled(&cfg)) {
611 if (!throttling_group) {
612 throttling_group = id;
614 blk_io_limits_enable(blk, throttling_group);
615 blk_set_io_limits(blk, &cfg);
618 blk_set_enable_write_cache(blk, !writethrough);
619 blk_set_on_error(blk, on_read_error, on_write_error);
621 if (!monitor_add_blk(blk, id, errp)) {
622 blk_unref(blk);
623 blk = NULL;
624 goto err_no_bs_opts;
627 err_no_bs_opts:
628 qemu_opts_del(opts);
629 qobject_unref(interval_dict);
630 qobject_unref(interval_list);
631 return blk;
633 early_err:
634 qemu_opts_del(opts);
635 qobject_unref(interval_dict);
636 qobject_unref(interval_list);
637 err_no_opts:
638 qobject_unref(bs_opts);
639 return NULL;
642 /* Takes the ownership of bs_opts */
643 BlockDriverState *bds_tree_init(QDict *bs_opts, Error **errp)
645 int bdrv_flags = 0;
647 GLOBAL_STATE_CODE();
648 /* bdrv_open() defaults to the values in bdrv_flags (for compatibility
649 * with other callers) rather than what we want as the real defaults.
650 * Apply the defaults here instead. */
651 qdict_set_default_str(bs_opts, BDRV_OPT_CACHE_DIRECT, "off");
652 qdict_set_default_str(bs_opts, BDRV_OPT_CACHE_NO_FLUSH, "off");
653 qdict_set_default_str(bs_opts, BDRV_OPT_READ_ONLY, "off");
655 if (runstate_check(RUN_STATE_INMIGRATE)) {
656 bdrv_flags |= BDRV_O_INACTIVE;
659 return bdrv_open(NULL, NULL, bs_opts, bdrv_flags, errp);
662 void blockdev_close_all_bdrv_states(void)
664 BlockDriverState *bs, *next_bs;
666 GLOBAL_STATE_CODE();
667 QTAILQ_FOREACH_SAFE(bs, &monitor_bdrv_states, monitor_list, next_bs) {
668 AioContext *ctx = bdrv_get_aio_context(bs);
670 aio_context_acquire(ctx);
671 bdrv_unref(bs);
672 aio_context_release(ctx);
676 /* Iterates over the list of monitor-owned BlockDriverStates */
677 BlockDriverState *bdrv_next_monitor_owned(BlockDriverState *bs)
679 GLOBAL_STATE_CODE();
680 return bs ? QTAILQ_NEXT(bs, monitor_list)
681 : QTAILQ_FIRST(&monitor_bdrv_states);
684 static bool qemu_opt_rename(QemuOpts *opts, const char *from, const char *to,
685 Error **errp)
687 const char *value;
689 value = qemu_opt_get(opts, from);
690 if (value) {
691 if (qemu_opt_find(opts, to)) {
692 error_setg(errp, "'%s' and its alias '%s' can't be used at the "
693 "same time", to, from);
694 return false;
698 /* rename all items in opts */
699 while ((value = qemu_opt_get(opts, from))) {
700 qemu_opt_set(opts, to, value, &error_abort);
701 qemu_opt_unset(opts, from);
703 return true;
706 QemuOptsList qemu_legacy_drive_opts = {
707 .name = "drive",
708 .head = QTAILQ_HEAD_INITIALIZER(qemu_legacy_drive_opts.head),
709 .desc = {
711 .name = "bus",
712 .type = QEMU_OPT_NUMBER,
713 .help = "bus number",
715 .name = "unit",
716 .type = QEMU_OPT_NUMBER,
717 .help = "unit number (i.e. lun for scsi)",
719 .name = "index",
720 .type = QEMU_OPT_NUMBER,
721 .help = "index number",
723 .name = "media",
724 .type = QEMU_OPT_STRING,
725 .help = "media type (disk, cdrom)",
727 .name = "if",
728 .type = QEMU_OPT_STRING,
729 .help = "interface (ide, scsi, sd, mtd, floppy, pflash, virtio)",
731 .name = "file",
732 .type = QEMU_OPT_STRING,
733 .help = "file name",
736 /* Options that are passed on, but have special semantics with -drive */
738 .name = BDRV_OPT_READ_ONLY,
739 .type = QEMU_OPT_BOOL,
740 .help = "open drive file as read-only",
742 .name = "rerror",
743 .type = QEMU_OPT_STRING,
744 .help = "read error action",
746 .name = "werror",
747 .type = QEMU_OPT_STRING,
748 .help = "write error action",
750 .name = "copy-on-read",
751 .type = QEMU_OPT_BOOL,
752 .help = "copy read data from backing file into image file",
755 { /* end of list */ }
759 DriveInfo *drive_new(QemuOpts *all_opts, BlockInterfaceType block_default_type,
760 Error **errp)
762 const char *value;
763 BlockBackend *blk;
764 DriveInfo *dinfo = NULL;
765 QDict *bs_opts;
766 QemuOpts *legacy_opts;
767 DriveMediaType media = MEDIA_DISK;
768 BlockInterfaceType type;
769 int max_devs, bus_id, unit_id, index;
770 const char *werror, *rerror;
771 bool read_only = false;
772 bool copy_on_read;
773 const char *filename;
774 int i;
776 GLOBAL_STATE_CODE();
778 /* Change legacy command line options into QMP ones */
779 static const struct {
780 const char *from;
781 const char *to;
782 } opt_renames[] = {
783 { "iops", "throttling.iops-total" },
784 { "iops_rd", "throttling.iops-read" },
785 { "iops_wr", "throttling.iops-write" },
787 { "bps", "throttling.bps-total" },
788 { "bps_rd", "throttling.bps-read" },
789 { "bps_wr", "throttling.bps-write" },
791 { "iops_max", "throttling.iops-total-max" },
792 { "iops_rd_max", "throttling.iops-read-max" },
793 { "iops_wr_max", "throttling.iops-write-max" },
795 { "bps_max", "throttling.bps-total-max" },
796 { "bps_rd_max", "throttling.bps-read-max" },
797 { "bps_wr_max", "throttling.bps-write-max" },
799 { "iops_size", "throttling.iops-size" },
801 { "group", "throttling.group" },
803 { "readonly", BDRV_OPT_READ_ONLY },
806 for (i = 0; i < ARRAY_SIZE(opt_renames); i++) {
807 if (!qemu_opt_rename(all_opts, opt_renames[i].from,
808 opt_renames[i].to, errp)) {
809 return NULL;
813 value = qemu_opt_get(all_opts, "cache");
814 if (value) {
815 int flags = 0;
816 bool writethrough;
818 if (bdrv_parse_cache_mode(value, &flags, &writethrough) != 0) {
819 error_setg(errp, "invalid cache option");
820 return NULL;
823 /* Specific options take precedence */
824 if (!qemu_opt_get(all_opts, BDRV_OPT_CACHE_WB)) {
825 qemu_opt_set_bool(all_opts, BDRV_OPT_CACHE_WB,
826 !writethrough, &error_abort);
828 if (!qemu_opt_get(all_opts, BDRV_OPT_CACHE_DIRECT)) {
829 qemu_opt_set_bool(all_opts, BDRV_OPT_CACHE_DIRECT,
830 !!(flags & BDRV_O_NOCACHE), &error_abort);
832 if (!qemu_opt_get(all_opts, BDRV_OPT_CACHE_NO_FLUSH)) {
833 qemu_opt_set_bool(all_opts, BDRV_OPT_CACHE_NO_FLUSH,
834 !!(flags & BDRV_O_NO_FLUSH), &error_abort);
836 qemu_opt_unset(all_opts, "cache");
839 /* Get a QDict for processing the options */
840 bs_opts = qdict_new();
841 qemu_opts_to_qdict(all_opts, bs_opts);
843 legacy_opts = qemu_opts_create(&qemu_legacy_drive_opts, NULL, 0,
844 &error_abort);
845 if (!qemu_opts_absorb_qdict(legacy_opts, bs_opts, errp)) {
846 goto fail;
849 /* Media type */
850 value = qemu_opt_get(legacy_opts, "media");
851 if (value) {
852 if (!strcmp(value, "disk")) {
853 media = MEDIA_DISK;
854 } else if (!strcmp(value, "cdrom")) {
855 media = MEDIA_CDROM;
856 read_only = true;
857 } else {
858 error_setg(errp, "'%s' invalid media", value);
859 goto fail;
863 /* copy-on-read is disabled with a warning for read-only devices */
864 read_only |= qemu_opt_get_bool(legacy_opts, BDRV_OPT_READ_ONLY, false);
865 copy_on_read = qemu_opt_get_bool(legacy_opts, "copy-on-read", false);
867 if (read_only && copy_on_read) {
868 warn_report("disabling copy-on-read on read-only drive");
869 copy_on_read = false;
872 qdict_put_str(bs_opts, BDRV_OPT_READ_ONLY, read_only ? "on" : "off");
873 qdict_put_str(bs_opts, "copy-on-read", copy_on_read ? "on" : "off");
875 /* Controller type */
876 value = qemu_opt_get(legacy_opts, "if");
877 if (value) {
878 for (type = 0;
879 type < IF_COUNT && strcmp(value, if_name[type]);
880 type++) {
882 if (type == IF_COUNT) {
883 error_setg(errp, "unsupported bus type '%s'", value);
884 goto fail;
886 } else {
887 type = block_default_type;
890 /* Device address specified by bus/unit or index.
891 * If none was specified, try to find the first free one. */
892 bus_id = qemu_opt_get_number(legacy_opts, "bus", 0);
893 unit_id = qemu_opt_get_number(legacy_opts, "unit", -1);
894 index = qemu_opt_get_number(legacy_opts, "index", -1);
896 max_devs = if_max_devs[type];
898 if (index != -1) {
899 if (bus_id != 0 || unit_id != -1) {
900 error_setg(errp, "index cannot be used with bus and unit");
901 goto fail;
903 bus_id = drive_index_to_bus_id(type, index);
904 unit_id = drive_index_to_unit_id(type, index);
907 if (unit_id == -1) {
908 unit_id = 0;
909 while (drive_get(type, bus_id, unit_id) != NULL) {
910 unit_id++;
911 if (max_devs && unit_id >= max_devs) {
912 unit_id -= max_devs;
913 bus_id++;
918 if (max_devs && unit_id >= max_devs) {
919 error_setg(errp, "unit %d too big (max is %d)", unit_id, max_devs - 1);
920 goto fail;
923 if (drive_get(type, bus_id, unit_id) != NULL) {
924 error_setg(errp, "drive with bus=%d, unit=%d (index=%d) exists",
925 bus_id, unit_id, index);
926 goto fail;
929 /* no id supplied -> create one */
930 if (qemu_opts_id(all_opts) == NULL) {
931 char *new_id;
932 const char *mediastr = "";
933 if (type == IF_IDE || type == IF_SCSI) {
934 mediastr = (media == MEDIA_CDROM) ? "-cd" : "-hd";
936 if (max_devs) {
937 new_id = g_strdup_printf("%s%i%s%i", if_name[type], bus_id,
938 mediastr, unit_id);
939 } else {
940 new_id = g_strdup_printf("%s%s%i", if_name[type],
941 mediastr, unit_id);
943 qdict_put_str(bs_opts, "id", new_id);
944 g_free(new_id);
947 /* Add virtio block device */
948 if (type == IF_VIRTIO) {
949 QemuOpts *devopts;
950 devopts = qemu_opts_create(qemu_find_opts("device"), NULL, 0,
951 &error_abort);
952 qemu_opt_set(devopts, "driver", "virtio-blk", &error_abort);
953 qemu_opt_set(devopts, "drive", qdict_get_str(bs_opts, "id"),
954 &error_abort);
957 filename = qemu_opt_get(legacy_opts, "file");
959 /* Check werror/rerror compatibility with if=... */
960 werror = qemu_opt_get(legacy_opts, "werror");
961 if (werror != NULL) {
962 if (type != IF_IDE && type != IF_SCSI && type != IF_VIRTIO &&
963 type != IF_NONE) {
964 error_setg(errp, "werror is not supported by this bus type");
965 goto fail;
967 qdict_put_str(bs_opts, "werror", werror);
970 rerror = qemu_opt_get(legacy_opts, "rerror");
971 if (rerror != NULL) {
972 if (type != IF_IDE && type != IF_VIRTIO && type != IF_SCSI &&
973 type != IF_NONE) {
974 error_setg(errp, "rerror is not supported by this bus type");
975 goto fail;
977 qdict_put_str(bs_opts, "rerror", rerror);
980 /* Actual block device init: Functionality shared with blockdev-add */
981 blk = blockdev_init(filename, bs_opts, errp);
982 bs_opts = NULL;
983 if (!blk) {
984 goto fail;
987 /* Create legacy DriveInfo */
988 dinfo = g_malloc0(sizeof(*dinfo));
989 dinfo->opts = all_opts;
991 dinfo->type = type;
992 dinfo->bus = bus_id;
993 dinfo->unit = unit_id;
995 blk_set_legacy_dinfo(blk, dinfo);
997 switch(type) {
998 case IF_IDE:
999 case IF_SCSI:
1000 case IF_XEN:
1001 case IF_NONE:
1002 dinfo->media_cd = media == MEDIA_CDROM;
1003 break;
1004 default:
1005 break;
1008 fail:
1009 qemu_opts_del(legacy_opts);
1010 qobject_unref(bs_opts);
1011 return dinfo;
1014 static BlockDriverState *qmp_get_root_bs(const char *name, Error **errp)
1016 BlockDriverState *bs;
1018 bs = bdrv_lookup_bs(name, name, errp);
1019 if (bs == NULL) {
1020 return NULL;
1023 if (!bdrv_is_root_node(bs)) {
1024 error_setg(errp, "Need a root block node");
1025 return NULL;
1028 if (!bdrv_is_inserted(bs)) {
1029 error_setg(errp, "Device has no medium");
1030 return NULL;
1033 return bs;
1036 static void blockdev_do_action(TransactionAction *action, Error **errp)
1038 TransactionActionList list;
1040 list.value = action;
1041 list.next = NULL;
1042 qmp_transaction(&list, false, NULL, errp);
1045 void qmp_blockdev_snapshot_sync(bool has_device, const char *device,
1046 bool has_node_name, const char *node_name,
1047 const char *snapshot_file,
1048 bool has_snapshot_node_name,
1049 const char *snapshot_node_name,
1050 bool has_format, const char *format,
1051 bool has_mode, NewImageMode mode, Error **errp)
1053 BlockdevSnapshotSync snapshot = {
1054 .has_device = has_device,
1055 .device = (char *) device,
1056 .has_node_name = has_node_name,
1057 .node_name = (char *) node_name,
1058 .snapshot_file = (char *) snapshot_file,
1059 .has_snapshot_node_name = has_snapshot_node_name,
1060 .snapshot_node_name = (char *) snapshot_node_name,
1061 .has_format = has_format,
1062 .format = (char *) format,
1063 .has_mode = has_mode,
1064 .mode = mode,
1066 TransactionAction action = {
1067 .type = TRANSACTION_ACTION_KIND_BLOCKDEV_SNAPSHOT_SYNC,
1068 .u.blockdev_snapshot_sync.data = &snapshot,
1070 blockdev_do_action(&action, errp);
1073 void qmp_blockdev_snapshot(const char *node, const char *overlay,
1074 Error **errp)
1076 BlockdevSnapshot snapshot_data = {
1077 .node = (char *) node,
1078 .overlay = (char *) overlay
1080 TransactionAction action = {
1081 .type = TRANSACTION_ACTION_KIND_BLOCKDEV_SNAPSHOT,
1082 .u.blockdev_snapshot.data = &snapshot_data,
1084 blockdev_do_action(&action, errp);
1087 void qmp_blockdev_snapshot_internal_sync(const char *device,
1088 const char *name,
1089 Error **errp)
1091 BlockdevSnapshotInternal snapshot = {
1092 .device = (char *) device,
1093 .name = (char *) name
1095 TransactionAction action = {
1096 .type = TRANSACTION_ACTION_KIND_BLOCKDEV_SNAPSHOT_INTERNAL_SYNC,
1097 .u.blockdev_snapshot_internal_sync.data = &snapshot,
1099 blockdev_do_action(&action, errp);
1102 SnapshotInfo *qmp_blockdev_snapshot_delete_internal_sync(const char *device,
1103 bool has_id,
1104 const char *id,
1105 bool has_name,
1106 const char *name,
1107 Error **errp)
1109 BlockDriverState *bs;
1110 AioContext *aio_context;
1111 QEMUSnapshotInfo sn;
1112 Error *local_err = NULL;
1113 SnapshotInfo *info = NULL;
1114 int ret;
1116 bs = qmp_get_root_bs(device, errp);
1117 if (!bs) {
1118 return NULL;
1120 aio_context = bdrv_get_aio_context(bs);
1121 aio_context_acquire(aio_context);
1123 if (!has_id) {
1124 id = NULL;
1127 if (!has_name) {
1128 name = NULL;
1131 if (!id && !name) {
1132 error_setg(errp, "Name or id must be provided");
1133 goto out_aio_context;
1136 if (bdrv_op_is_blocked(bs, BLOCK_OP_TYPE_INTERNAL_SNAPSHOT_DELETE, errp)) {
1137 goto out_aio_context;
1140 ret = bdrv_snapshot_find_by_id_and_name(bs, id, name, &sn, &local_err);
1141 if (local_err) {
1142 error_propagate(errp, local_err);
1143 goto out_aio_context;
1145 if (!ret) {
1146 error_setg(errp,
1147 "Snapshot with id '%s' and name '%s' does not exist on "
1148 "device '%s'",
1149 STR_OR_NULL(id), STR_OR_NULL(name), device);
1150 goto out_aio_context;
1153 bdrv_snapshot_delete(bs, id, name, &local_err);
1154 if (local_err) {
1155 error_propagate(errp, local_err);
1156 goto out_aio_context;
1159 aio_context_release(aio_context);
1161 info = g_new0(SnapshotInfo, 1);
1162 info->id = g_strdup(sn.id_str);
1163 info->name = g_strdup(sn.name);
1164 info->date_nsec = sn.date_nsec;
1165 info->date_sec = sn.date_sec;
1166 info->vm_state_size = sn.vm_state_size;
1167 info->vm_clock_nsec = sn.vm_clock_nsec % 1000000000;
1168 info->vm_clock_sec = sn.vm_clock_nsec / 1000000000;
1169 if (sn.icount != -1ULL) {
1170 info->icount = sn.icount;
1171 info->has_icount = true;
1174 return info;
1176 out_aio_context:
1177 aio_context_release(aio_context);
1178 return NULL;
1181 /* New and old BlockDriverState structs for atomic group operations */
1183 typedef struct BlkActionState BlkActionState;
1186 * BlkActionOps:
1187 * Table of operations that define an Action.
1189 * @instance_size: Size of state struct, in bytes.
1190 * @prepare: Prepare the work, must NOT be NULL.
1191 * @commit: Commit the changes, can be NULL.
1192 * @abort: Abort the changes on fail, can be NULL.
1193 * @clean: Clean up resources after all transaction actions have called
1194 * commit() or abort(). Can be NULL.
1196 * Only prepare() may fail. In a single transaction, only one of commit() or
1197 * abort() will be called. clean() will always be called if it is present.
1199 * Always run under BQL.
1201 typedef struct BlkActionOps {
1202 size_t instance_size;
1203 void (*prepare)(BlkActionState *common, Error **errp);
1204 void (*commit)(BlkActionState *common);
1205 void (*abort)(BlkActionState *common);
1206 void (*clean)(BlkActionState *common);
1207 } BlkActionOps;
1210 * BlkActionState:
1211 * Describes one Action's state within a Transaction.
1213 * @action: QAPI-defined enum identifying which Action to perform.
1214 * @ops: Table of ActionOps this Action can perform.
1215 * @block_job_txn: Transaction which this action belongs to.
1216 * @entry: List membership for all Actions in this Transaction.
1218 * This structure must be arranged as first member in a subclassed type,
1219 * assuming that the compiler will also arrange it to the same offsets as the
1220 * base class.
1222 struct BlkActionState {
1223 TransactionAction *action;
1224 const BlkActionOps *ops;
1225 JobTxn *block_job_txn;
1226 TransactionProperties *txn_props;
1227 QTAILQ_ENTRY(BlkActionState) entry;
1230 /* internal snapshot private data */
1231 typedef struct InternalSnapshotState {
1232 BlkActionState common;
1233 BlockDriverState *bs;
1234 QEMUSnapshotInfo sn;
1235 bool created;
1236 } InternalSnapshotState;
1239 static int action_check_completion_mode(BlkActionState *s, Error **errp)
1241 if (s->txn_props->completion_mode != ACTION_COMPLETION_MODE_INDIVIDUAL) {
1242 error_setg(errp,
1243 "Action '%s' does not support Transaction property "
1244 "completion-mode = %s",
1245 TransactionActionKind_str(s->action->type),
1246 ActionCompletionMode_str(s->txn_props->completion_mode));
1247 return -1;
1249 return 0;
1252 static void internal_snapshot_prepare(BlkActionState *common,
1253 Error **errp)
1255 Error *local_err = NULL;
1256 const char *device;
1257 const char *name;
1258 BlockDriverState *bs;
1259 QEMUSnapshotInfo old_sn, *sn;
1260 bool ret;
1261 qemu_timeval tv;
1262 BlockdevSnapshotInternal *internal;
1263 InternalSnapshotState *state;
1264 AioContext *aio_context;
1265 int ret1;
1267 g_assert(common->action->type ==
1268 TRANSACTION_ACTION_KIND_BLOCKDEV_SNAPSHOT_INTERNAL_SYNC);
1269 internal = common->action->u.blockdev_snapshot_internal_sync.data;
1270 state = DO_UPCAST(InternalSnapshotState, common, common);
1272 /* 1. parse input */
1273 device = internal->device;
1274 name = internal->name;
1276 /* 2. check for validation */
1277 if (action_check_completion_mode(common, errp) < 0) {
1278 return;
1281 bs = qmp_get_root_bs(device, errp);
1282 if (!bs) {
1283 return;
1286 aio_context = bdrv_get_aio_context(bs);
1287 aio_context_acquire(aio_context);
1289 state->bs = bs;
1291 /* Paired with .clean() */
1292 bdrv_drained_begin(bs);
1294 if (bdrv_op_is_blocked(bs, BLOCK_OP_TYPE_INTERNAL_SNAPSHOT, errp)) {
1295 goto out;
1298 if (bdrv_is_read_only(bs)) {
1299 error_setg(errp, "Device '%s' is read only", device);
1300 goto out;
1303 if (!bdrv_can_snapshot(bs)) {
1304 error_setg(errp, "Block format '%s' used by device '%s' "
1305 "does not support internal snapshots",
1306 bs->drv->format_name, device);
1307 goto out;
1310 if (!strlen(name)) {
1311 error_setg(errp, "Name is empty");
1312 goto out;
1315 /* check whether a snapshot with name exist */
1316 ret = bdrv_snapshot_find_by_id_and_name(bs, NULL, name, &old_sn,
1317 &local_err);
1318 if (local_err) {
1319 error_propagate(errp, local_err);
1320 goto out;
1321 } else if (ret) {
1322 error_setg(errp,
1323 "Snapshot with name '%s' already exists on device '%s'",
1324 name, device);
1325 goto out;
1328 /* 3. take the snapshot */
1329 sn = &state->sn;
1330 pstrcpy(sn->name, sizeof(sn->name), name);
1331 qemu_gettimeofday(&tv);
1332 sn->date_sec = tv.tv_sec;
1333 sn->date_nsec = tv.tv_usec * 1000;
1334 sn->vm_clock_nsec = qemu_clock_get_ns(QEMU_CLOCK_VIRTUAL);
1335 if (replay_mode != REPLAY_MODE_NONE) {
1336 sn->icount = replay_get_current_icount();
1337 } else {
1338 sn->icount = -1ULL;
1341 ret1 = bdrv_snapshot_create(bs, sn);
1342 if (ret1 < 0) {
1343 error_setg_errno(errp, -ret1,
1344 "Failed to create snapshot '%s' on device '%s'",
1345 name, device);
1346 goto out;
1349 /* 4. succeed, mark a snapshot is created */
1350 state->created = true;
1352 out:
1353 aio_context_release(aio_context);
1356 static void internal_snapshot_abort(BlkActionState *common)
1358 InternalSnapshotState *state =
1359 DO_UPCAST(InternalSnapshotState, common, common);
1360 BlockDriverState *bs = state->bs;
1361 QEMUSnapshotInfo *sn = &state->sn;
1362 AioContext *aio_context;
1363 Error *local_error = NULL;
1365 if (!state->created) {
1366 return;
1369 aio_context = bdrv_get_aio_context(state->bs);
1370 aio_context_acquire(aio_context);
1372 if (bdrv_snapshot_delete(bs, sn->id_str, sn->name, &local_error) < 0) {
1373 error_reportf_err(local_error,
1374 "Failed to delete snapshot with id '%s' and "
1375 "name '%s' on device '%s' in abort: ",
1376 sn->id_str, sn->name,
1377 bdrv_get_device_name(bs));
1380 aio_context_release(aio_context);
1383 static void internal_snapshot_clean(BlkActionState *common)
1385 InternalSnapshotState *state = DO_UPCAST(InternalSnapshotState,
1386 common, common);
1387 AioContext *aio_context;
1389 if (!state->bs) {
1390 return;
1393 aio_context = bdrv_get_aio_context(state->bs);
1394 aio_context_acquire(aio_context);
1396 bdrv_drained_end(state->bs);
1398 aio_context_release(aio_context);
1401 /* external snapshot private data */
1402 typedef struct ExternalSnapshotState {
1403 BlkActionState common;
1404 BlockDriverState *old_bs;
1405 BlockDriverState *new_bs;
1406 bool overlay_appended;
1407 } ExternalSnapshotState;
1409 static void external_snapshot_prepare(BlkActionState *common,
1410 Error **errp)
1412 int ret;
1413 int flags = 0;
1414 QDict *options = NULL;
1415 Error *local_err = NULL;
1416 /* Device and node name of the image to generate the snapshot from */
1417 const char *device;
1418 const char *node_name;
1419 /* Reference to the new image (for 'blockdev-snapshot') */
1420 const char *snapshot_ref;
1421 /* File name of the new image (for 'blockdev-snapshot-sync') */
1422 const char *new_image_file;
1423 ExternalSnapshotState *state =
1424 DO_UPCAST(ExternalSnapshotState, common, common);
1425 TransactionAction *action = common->action;
1426 AioContext *aio_context;
1427 uint64_t perm, shared;
1429 /* 'blockdev-snapshot' and 'blockdev-snapshot-sync' have similar
1430 * purpose but a different set of parameters */
1431 switch (action->type) {
1432 case TRANSACTION_ACTION_KIND_BLOCKDEV_SNAPSHOT:
1434 BlockdevSnapshot *s = action->u.blockdev_snapshot.data;
1435 device = s->node;
1436 node_name = s->node;
1437 new_image_file = NULL;
1438 snapshot_ref = s->overlay;
1440 break;
1441 case TRANSACTION_ACTION_KIND_BLOCKDEV_SNAPSHOT_SYNC:
1443 BlockdevSnapshotSync *s = action->u.blockdev_snapshot_sync.data;
1444 device = s->has_device ? s->device : NULL;
1445 node_name = s->has_node_name ? s->node_name : NULL;
1446 new_image_file = s->snapshot_file;
1447 snapshot_ref = NULL;
1449 break;
1450 default:
1451 g_assert_not_reached();
1454 /* start processing */
1455 if (action_check_completion_mode(common, errp) < 0) {
1456 return;
1459 state->old_bs = bdrv_lookup_bs(device, node_name, errp);
1460 if (!state->old_bs) {
1461 return;
1464 aio_context = bdrv_get_aio_context(state->old_bs);
1465 aio_context_acquire(aio_context);
1467 /* Paired with .clean() */
1468 bdrv_drained_begin(state->old_bs);
1470 if (!bdrv_is_inserted(state->old_bs)) {
1471 error_setg(errp, QERR_DEVICE_HAS_NO_MEDIUM, device);
1472 goto out;
1475 if (bdrv_op_is_blocked(state->old_bs,
1476 BLOCK_OP_TYPE_EXTERNAL_SNAPSHOT, errp)) {
1477 goto out;
1480 if (!bdrv_is_read_only(state->old_bs)) {
1481 if (bdrv_flush(state->old_bs)) {
1482 error_setg(errp, QERR_IO_ERROR);
1483 goto out;
1487 if (action->type == TRANSACTION_ACTION_KIND_BLOCKDEV_SNAPSHOT_SYNC) {
1488 BlockdevSnapshotSync *s = action->u.blockdev_snapshot_sync.data;
1489 const char *format = s->has_format ? s->format : "qcow2";
1490 enum NewImageMode mode;
1491 const char *snapshot_node_name =
1492 s->has_snapshot_node_name ? s->snapshot_node_name : NULL;
1494 if (node_name && !snapshot_node_name) {
1495 error_setg(errp, "New overlay node-name missing");
1496 goto out;
1499 if (snapshot_node_name &&
1500 bdrv_lookup_bs(snapshot_node_name, snapshot_node_name, NULL)) {
1501 error_setg(errp, "New overlay node-name already in use");
1502 goto out;
1505 flags = state->old_bs->open_flags;
1506 flags &= ~(BDRV_O_SNAPSHOT | BDRV_O_COPY_ON_READ);
1507 flags |= BDRV_O_NO_BACKING;
1509 /* create new image w/backing file */
1510 mode = s->has_mode ? s->mode : NEW_IMAGE_MODE_ABSOLUTE_PATHS;
1511 if (mode != NEW_IMAGE_MODE_EXISTING) {
1512 int64_t size = bdrv_getlength(state->old_bs);
1513 if (size < 0) {
1514 error_setg_errno(errp, -size, "bdrv_getlength failed");
1515 goto out;
1517 bdrv_refresh_filename(state->old_bs);
1518 bdrv_img_create(new_image_file, format,
1519 state->old_bs->filename,
1520 state->old_bs->drv->format_name,
1521 NULL, size, flags, false, &local_err);
1522 if (local_err) {
1523 error_propagate(errp, local_err);
1524 goto out;
1528 options = qdict_new();
1529 if (snapshot_node_name) {
1530 qdict_put_str(options, "node-name", snapshot_node_name);
1532 qdict_put_str(options, "driver", format);
1535 state->new_bs = bdrv_open(new_image_file, snapshot_ref, options, flags,
1536 errp);
1537 /* We will manually add the backing_hd field to the bs later */
1538 if (!state->new_bs) {
1539 goto out;
1543 * Allow attaching a backing file to an overlay that's already in use only
1544 * if the parents don't assume that they are already seeing a valid image.
1545 * (Specifically, allow it as a mirror target, which is write-only access.)
1547 bdrv_get_cumulative_perm(state->new_bs, &perm, &shared);
1548 if (perm & BLK_PERM_CONSISTENT_READ) {
1549 error_setg(errp, "The overlay is already in use");
1550 goto out;
1553 if (state->new_bs->drv->is_filter) {
1554 error_setg(errp, "Filters cannot be used as overlays");
1555 goto out;
1558 if (bdrv_cow_child(state->new_bs)) {
1559 error_setg(errp, "The overlay already has a backing image");
1560 goto out;
1563 if (!state->new_bs->drv->supports_backing) {
1564 error_setg(errp, "The overlay does not support backing images");
1565 goto out;
1568 ret = bdrv_append(state->new_bs, state->old_bs, errp);
1569 if (ret < 0) {
1570 goto out;
1572 state->overlay_appended = true;
1574 out:
1575 aio_context_release(aio_context);
1578 static void external_snapshot_commit(BlkActionState *common)
1580 ExternalSnapshotState *state =
1581 DO_UPCAST(ExternalSnapshotState, common, common);
1582 AioContext *aio_context;
1584 aio_context = bdrv_get_aio_context(state->old_bs);
1585 aio_context_acquire(aio_context);
1587 /* We don't need (or want) to use the transactional
1588 * bdrv_reopen_multiple() across all the entries at once, because we
1589 * don't want to abort all of them if one of them fails the reopen */
1590 if (!qatomic_read(&state->old_bs->copy_on_read)) {
1591 bdrv_reopen_set_read_only(state->old_bs, true, NULL);
1594 aio_context_release(aio_context);
1597 static void external_snapshot_abort(BlkActionState *common)
1599 ExternalSnapshotState *state =
1600 DO_UPCAST(ExternalSnapshotState, common, common);
1601 if (state->new_bs) {
1602 if (state->overlay_appended) {
1603 AioContext *aio_context;
1604 AioContext *tmp_context;
1605 int ret;
1607 aio_context = bdrv_get_aio_context(state->old_bs);
1608 aio_context_acquire(aio_context);
1610 bdrv_ref(state->old_bs); /* we can't let bdrv_set_backind_hd()
1611 close state->old_bs; we need it */
1612 bdrv_set_backing_hd(state->new_bs, NULL, &error_abort);
1615 * The call to bdrv_set_backing_hd() above returns state->old_bs to
1616 * the main AioContext. As we're still going to be using it, return
1617 * it to the AioContext it was before.
1619 tmp_context = bdrv_get_aio_context(state->old_bs);
1620 if (aio_context != tmp_context) {
1621 aio_context_release(aio_context);
1622 aio_context_acquire(tmp_context);
1624 ret = bdrv_try_set_aio_context(state->old_bs,
1625 aio_context, NULL);
1626 assert(ret == 0);
1628 aio_context_release(tmp_context);
1629 aio_context_acquire(aio_context);
1632 bdrv_replace_node(state->new_bs, state->old_bs, &error_abort);
1633 bdrv_unref(state->old_bs); /* bdrv_replace_node() ref'ed old_bs */
1635 aio_context_release(aio_context);
1640 static void external_snapshot_clean(BlkActionState *common)
1642 ExternalSnapshotState *state =
1643 DO_UPCAST(ExternalSnapshotState, common, common);
1644 AioContext *aio_context;
1646 if (!state->old_bs) {
1647 return;
1650 aio_context = bdrv_get_aio_context(state->old_bs);
1651 aio_context_acquire(aio_context);
1653 bdrv_drained_end(state->old_bs);
1654 bdrv_unref(state->new_bs);
1656 aio_context_release(aio_context);
1659 typedef struct DriveBackupState {
1660 BlkActionState common;
1661 BlockDriverState *bs;
1662 BlockJob *job;
1663 } DriveBackupState;
1665 static BlockJob *do_backup_common(BackupCommon *backup,
1666 BlockDriverState *bs,
1667 BlockDriverState *target_bs,
1668 AioContext *aio_context,
1669 JobTxn *txn, Error **errp);
1671 static void drive_backup_prepare(BlkActionState *common, Error **errp)
1673 DriveBackupState *state = DO_UPCAST(DriveBackupState, common, common);
1674 DriveBackup *backup;
1675 BlockDriverState *bs;
1676 BlockDriverState *target_bs;
1677 BlockDriverState *source = NULL;
1678 AioContext *aio_context;
1679 AioContext *old_context;
1680 QDict *options;
1681 Error *local_err = NULL;
1682 int flags;
1683 int64_t size;
1684 bool set_backing_hd = false;
1685 int ret;
1687 assert(common->action->type == TRANSACTION_ACTION_KIND_DRIVE_BACKUP);
1688 backup = common->action->u.drive_backup.data;
1690 if (!backup->has_mode) {
1691 backup->mode = NEW_IMAGE_MODE_ABSOLUTE_PATHS;
1694 bs = bdrv_lookup_bs(backup->device, backup->device, errp);
1695 if (!bs) {
1696 return;
1699 if (!bs->drv) {
1700 error_setg(errp, "Device has no medium");
1701 return;
1704 aio_context = bdrv_get_aio_context(bs);
1705 aio_context_acquire(aio_context);
1707 state->bs = bs;
1708 /* Paired with .clean() */
1709 bdrv_drained_begin(bs);
1711 if (!backup->has_format) {
1712 backup->format = backup->mode == NEW_IMAGE_MODE_EXISTING ?
1713 NULL : (char *) bs->drv->format_name;
1716 /* Early check to avoid creating target */
1717 if (bdrv_op_is_blocked(bs, BLOCK_OP_TYPE_BACKUP_SOURCE, errp)) {
1718 goto out;
1721 flags = bs->open_flags | BDRV_O_RDWR;
1724 * See if we have a backing HD we can use to create our new image
1725 * on top of.
1727 if (backup->sync == MIRROR_SYNC_MODE_TOP) {
1729 * Backup will not replace the source by the target, so none
1730 * of the filters skipped here will be removed (in contrast to
1731 * mirror). Therefore, we can skip all of them when looking
1732 * for the first COW relationship.
1734 source = bdrv_cow_bs(bdrv_skip_filters(bs));
1735 if (!source) {
1736 backup->sync = MIRROR_SYNC_MODE_FULL;
1739 if (backup->sync == MIRROR_SYNC_MODE_NONE) {
1740 source = bs;
1741 flags |= BDRV_O_NO_BACKING;
1742 set_backing_hd = true;
1745 size = bdrv_getlength(bs);
1746 if (size < 0) {
1747 error_setg_errno(errp, -size, "bdrv_getlength failed");
1748 goto out;
1751 if (backup->mode != NEW_IMAGE_MODE_EXISTING) {
1752 assert(backup->format);
1753 if (source) {
1754 /* Implicit filters should not appear in the filename */
1755 BlockDriverState *explicit_backing =
1756 bdrv_skip_implicit_filters(source);
1758 bdrv_refresh_filename(explicit_backing);
1759 bdrv_img_create(backup->target, backup->format,
1760 explicit_backing->filename,
1761 explicit_backing->drv->format_name, NULL,
1762 size, flags, false, &local_err);
1763 } else {
1764 bdrv_img_create(backup->target, backup->format, NULL, NULL, NULL,
1765 size, flags, false, &local_err);
1769 if (local_err) {
1770 error_propagate(errp, local_err);
1771 goto out;
1774 options = qdict_new();
1775 qdict_put_str(options, "discard", "unmap");
1776 qdict_put_str(options, "detect-zeroes", "unmap");
1777 if (backup->format) {
1778 qdict_put_str(options, "driver", backup->format);
1781 target_bs = bdrv_open(backup->target, NULL, options, flags, errp);
1782 if (!target_bs) {
1783 goto out;
1786 /* Honor bdrv_try_set_aio_context() context acquisition requirements. */
1787 old_context = bdrv_get_aio_context(target_bs);
1788 aio_context_release(aio_context);
1789 aio_context_acquire(old_context);
1791 ret = bdrv_try_set_aio_context(target_bs, aio_context, errp);
1792 if (ret < 0) {
1793 bdrv_unref(target_bs);
1794 aio_context_release(old_context);
1795 return;
1798 aio_context_release(old_context);
1799 aio_context_acquire(aio_context);
1801 if (set_backing_hd) {
1802 if (bdrv_set_backing_hd(target_bs, source, errp) < 0) {
1803 goto unref;
1807 state->job = do_backup_common(qapi_DriveBackup_base(backup),
1808 bs, target_bs, aio_context,
1809 common->block_job_txn, errp);
1811 unref:
1812 bdrv_unref(target_bs);
1813 out:
1814 aio_context_release(aio_context);
1817 static void drive_backup_commit(BlkActionState *common)
1819 DriveBackupState *state = DO_UPCAST(DriveBackupState, common, common);
1820 AioContext *aio_context;
1822 aio_context = bdrv_get_aio_context(state->bs);
1823 aio_context_acquire(aio_context);
1825 assert(state->job);
1826 job_start(&state->job->job);
1828 aio_context_release(aio_context);
1831 static void drive_backup_abort(BlkActionState *common)
1833 DriveBackupState *state = DO_UPCAST(DriveBackupState, common, common);
1835 if (state->job) {
1836 AioContext *aio_context;
1838 aio_context = bdrv_get_aio_context(state->bs);
1839 aio_context_acquire(aio_context);
1841 job_cancel_sync(&state->job->job, true);
1843 aio_context_release(aio_context);
1847 static void drive_backup_clean(BlkActionState *common)
1849 DriveBackupState *state = DO_UPCAST(DriveBackupState, common, common);
1850 AioContext *aio_context;
1852 if (!state->bs) {
1853 return;
1856 aio_context = bdrv_get_aio_context(state->bs);
1857 aio_context_acquire(aio_context);
1859 bdrv_drained_end(state->bs);
1861 aio_context_release(aio_context);
1864 typedef struct BlockdevBackupState {
1865 BlkActionState common;
1866 BlockDriverState *bs;
1867 BlockJob *job;
1868 } BlockdevBackupState;
1870 static void blockdev_backup_prepare(BlkActionState *common, Error **errp)
1872 BlockdevBackupState *state = DO_UPCAST(BlockdevBackupState, common, common);
1873 BlockdevBackup *backup;
1874 BlockDriverState *bs;
1875 BlockDriverState *target_bs;
1876 AioContext *aio_context;
1877 AioContext *old_context;
1878 int ret;
1880 assert(common->action->type == TRANSACTION_ACTION_KIND_BLOCKDEV_BACKUP);
1881 backup = common->action->u.blockdev_backup.data;
1883 bs = bdrv_lookup_bs(backup->device, backup->device, errp);
1884 if (!bs) {
1885 return;
1888 target_bs = bdrv_lookup_bs(backup->target, backup->target, errp);
1889 if (!target_bs) {
1890 return;
1893 /* Honor bdrv_try_set_aio_context() context acquisition requirements. */
1894 aio_context = bdrv_get_aio_context(bs);
1895 old_context = bdrv_get_aio_context(target_bs);
1896 aio_context_acquire(old_context);
1898 ret = bdrv_try_set_aio_context(target_bs, aio_context, errp);
1899 if (ret < 0) {
1900 aio_context_release(old_context);
1901 return;
1904 aio_context_release(old_context);
1905 aio_context_acquire(aio_context);
1906 state->bs = bs;
1908 /* Paired with .clean() */
1909 bdrv_drained_begin(state->bs);
1911 state->job = do_backup_common(qapi_BlockdevBackup_base(backup),
1912 bs, target_bs, aio_context,
1913 common->block_job_txn, errp);
1915 aio_context_release(aio_context);
1918 static void blockdev_backup_commit(BlkActionState *common)
1920 BlockdevBackupState *state = DO_UPCAST(BlockdevBackupState, common, common);
1921 AioContext *aio_context;
1923 aio_context = bdrv_get_aio_context(state->bs);
1924 aio_context_acquire(aio_context);
1926 assert(state->job);
1927 job_start(&state->job->job);
1929 aio_context_release(aio_context);
1932 static void blockdev_backup_abort(BlkActionState *common)
1934 BlockdevBackupState *state = DO_UPCAST(BlockdevBackupState, common, common);
1936 if (state->job) {
1937 AioContext *aio_context;
1939 aio_context = bdrv_get_aio_context(state->bs);
1940 aio_context_acquire(aio_context);
1942 job_cancel_sync(&state->job->job, true);
1944 aio_context_release(aio_context);
1948 static void blockdev_backup_clean(BlkActionState *common)
1950 BlockdevBackupState *state = DO_UPCAST(BlockdevBackupState, common, common);
1951 AioContext *aio_context;
1953 if (!state->bs) {
1954 return;
1957 aio_context = bdrv_get_aio_context(state->bs);
1958 aio_context_acquire(aio_context);
1960 bdrv_drained_end(state->bs);
1962 aio_context_release(aio_context);
1965 typedef struct BlockDirtyBitmapState {
1966 BlkActionState common;
1967 BdrvDirtyBitmap *bitmap;
1968 BlockDriverState *bs;
1969 HBitmap *backup;
1970 bool prepared;
1971 bool was_enabled;
1972 } BlockDirtyBitmapState;
1974 static void block_dirty_bitmap_add_prepare(BlkActionState *common,
1975 Error **errp)
1977 Error *local_err = NULL;
1978 BlockDirtyBitmapAdd *action;
1979 BlockDirtyBitmapState *state = DO_UPCAST(BlockDirtyBitmapState,
1980 common, common);
1982 if (action_check_completion_mode(common, errp) < 0) {
1983 return;
1986 action = common->action->u.block_dirty_bitmap_add.data;
1987 /* AIO context taken and released within qmp_block_dirty_bitmap_add */
1988 qmp_block_dirty_bitmap_add(action->node, action->name,
1989 action->has_granularity, action->granularity,
1990 action->has_persistent, action->persistent,
1991 action->has_disabled, action->disabled,
1992 &local_err);
1994 if (!local_err) {
1995 state->prepared = true;
1996 } else {
1997 error_propagate(errp, local_err);
2001 static void block_dirty_bitmap_add_abort(BlkActionState *common)
2003 BlockDirtyBitmapAdd *action;
2004 BlockDirtyBitmapState *state = DO_UPCAST(BlockDirtyBitmapState,
2005 common, common);
2007 action = common->action->u.block_dirty_bitmap_add.data;
2008 /* Should not be able to fail: IF the bitmap was added via .prepare(),
2009 * then the node reference and bitmap name must have been valid.
2011 if (state->prepared) {
2012 qmp_block_dirty_bitmap_remove(action->node, action->name, &error_abort);
2016 static void block_dirty_bitmap_clear_prepare(BlkActionState *common,
2017 Error **errp)
2019 BlockDirtyBitmapState *state = DO_UPCAST(BlockDirtyBitmapState,
2020 common, common);
2021 BlockDirtyBitmap *action;
2023 if (action_check_completion_mode(common, errp) < 0) {
2024 return;
2027 action = common->action->u.block_dirty_bitmap_clear.data;
2028 state->bitmap = block_dirty_bitmap_lookup(action->node,
2029 action->name,
2030 &state->bs,
2031 errp);
2032 if (!state->bitmap) {
2033 return;
2036 if (bdrv_dirty_bitmap_check(state->bitmap, BDRV_BITMAP_DEFAULT, errp)) {
2037 return;
2040 bdrv_clear_dirty_bitmap(state->bitmap, &state->backup);
2043 static void block_dirty_bitmap_restore(BlkActionState *common)
2045 BlockDirtyBitmapState *state = DO_UPCAST(BlockDirtyBitmapState,
2046 common, common);
2048 if (state->backup) {
2049 bdrv_restore_dirty_bitmap(state->bitmap, state->backup);
2053 static void block_dirty_bitmap_free_backup(BlkActionState *common)
2055 BlockDirtyBitmapState *state = DO_UPCAST(BlockDirtyBitmapState,
2056 common, common);
2058 hbitmap_free(state->backup);
2061 static void block_dirty_bitmap_enable_prepare(BlkActionState *common,
2062 Error **errp)
2064 BlockDirtyBitmap *action;
2065 BlockDirtyBitmapState *state = DO_UPCAST(BlockDirtyBitmapState,
2066 common, common);
2068 if (action_check_completion_mode(common, errp) < 0) {
2069 return;
2072 action = common->action->u.block_dirty_bitmap_enable.data;
2073 state->bitmap = block_dirty_bitmap_lookup(action->node,
2074 action->name,
2075 NULL,
2076 errp);
2077 if (!state->bitmap) {
2078 return;
2081 if (bdrv_dirty_bitmap_check(state->bitmap, BDRV_BITMAP_ALLOW_RO, errp)) {
2082 return;
2085 state->was_enabled = bdrv_dirty_bitmap_enabled(state->bitmap);
2086 bdrv_enable_dirty_bitmap(state->bitmap);
2089 static void block_dirty_bitmap_enable_abort(BlkActionState *common)
2091 BlockDirtyBitmapState *state = DO_UPCAST(BlockDirtyBitmapState,
2092 common, common);
2094 if (!state->was_enabled) {
2095 bdrv_disable_dirty_bitmap(state->bitmap);
2099 static void block_dirty_bitmap_disable_prepare(BlkActionState *common,
2100 Error **errp)
2102 BlockDirtyBitmap *action;
2103 BlockDirtyBitmapState *state = DO_UPCAST(BlockDirtyBitmapState,
2104 common, common);
2106 if (action_check_completion_mode(common, errp) < 0) {
2107 return;
2110 action = common->action->u.block_dirty_bitmap_disable.data;
2111 state->bitmap = block_dirty_bitmap_lookup(action->node,
2112 action->name,
2113 NULL,
2114 errp);
2115 if (!state->bitmap) {
2116 return;
2119 if (bdrv_dirty_bitmap_check(state->bitmap, BDRV_BITMAP_ALLOW_RO, errp)) {
2120 return;
2123 state->was_enabled = bdrv_dirty_bitmap_enabled(state->bitmap);
2124 bdrv_disable_dirty_bitmap(state->bitmap);
2127 static void block_dirty_bitmap_disable_abort(BlkActionState *common)
2129 BlockDirtyBitmapState *state = DO_UPCAST(BlockDirtyBitmapState,
2130 common, common);
2132 if (state->was_enabled) {
2133 bdrv_enable_dirty_bitmap(state->bitmap);
2137 static void block_dirty_bitmap_merge_prepare(BlkActionState *common,
2138 Error **errp)
2140 BlockDirtyBitmapMerge *action;
2141 BlockDirtyBitmapState *state = DO_UPCAST(BlockDirtyBitmapState,
2142 common, common);
2144 if (action_check_completion_mode(common, errp) < 0) {
2145 return;
2148 action = common->action->u.block_dirty_bitmap_merge.data;
2150 state->bitmap = block_dirty_bitmap_merge(action->node, action->target,
2151 action->bitmaps, &state->backup,
2152 errp);
2155 static void block_dirty_bitmap_remove_prepare(BlkActionState *common,
2156 Error **errp)
2158 BlockDirtyBitmap *action;
2159 BlockDirtyBitmapState *state = DO_UPCAST(BlockDirtyBitmapState,
2160 common, common);
2162 if (action_check_completion_mode(common, errp) < 0) {
2163 return;
2166 action = common->action->u.block_dirty_bitmap_remove.data;
2168 state->bitmap = block_dirty_bitmap_remove(action->node, action->name,
2169 false, &state->bs, errp);
2170 if (state->bitmap) {
2171 bdrv_dirty_bitmap_skip_store(state->bitmap, true);
2172 bdrv_dirty_bitmap_set_busy(state->bitmap, true);
2176 static void block_dirty_bitmap_remove_abort(BlkActionState *common)
2178 BlockDirtyBitmapState *state = DO_UPCAST(BlockDirtyBitmapState,
2179 common, common);
2181 if (state->bitmap) {
2182 bdrv_dirty_bitmap_skip_store(state->bitmap, false);
2183 bdrv_dirty_bitmap_set_busy(state->bitmap, false);
2187 static void block_dirty_bitmap_remove_commit(BlkActionState *common)
2189 BlockDirtyBitmapState *state = DO_UPCAST(BlockDirtyBitmapState,
2190 common, common);
2192 bdrv_dirty_bitmap_set_busy(state->bitmap, false);
2193 bdrv_release_dirty_bitmap(state->bitmap);
2196 static void abort_prepare(BlkActionState *common, Error **errp)
2198 error_setg(errp, "Transaction aborted using Abort action");
2201 static void abort_commit(BlkActionState *common)
2203 g_assert_not_reached(); /* this action never succeeds */
2206 static const BlkActionOps actions[] = {
2207 [TRANSACTION_ACTION_KIND_BLOCKDEV_SNAPSHOT] = {
2208 .instance_size = sizeof(ExternalSnapshotState),
2209 .prepare = external_snapshot_prepare,
2210 .commit = external_snapshot_commit,
2211 .abort = external_snapshot_abort,
2212 .clean = external_snapshot_clean,
2214 [TRANSACTION_ACTION_KIND_BLOCKDEV_SNAPSHOT_SYNC] = {
2215 .instance_size = sizeof(ExternalSnapshotState),
2216 .prepare = external_snapshot_prepare,
2217 .commit = external_snapshot_commit,
2218 .abort = external_snapshot_abort,
2219 .clean = external_snapshot_clean,
2221 [TRANSACTION_ACTION_KIND_DRIVE_BACKUP] = {
2222 .instance_size = sizeof(DriveBackupState),
2223 .prepare = drive_backup_prepare,
2224 .commit = drive_backup_commit,
2225 .abort = drive_backup_abort,
2226 .clean = drive_backup_clean,
2228 [TRANSACTION_ACTION_KIND_BLOCKDEV_BACKUP] = {
2229 .instance_size = sizeof(BlockdevBackupState),
2230 .prepare = blockdev_backup_prepare,
2231 .commit = blockdev_backup_commit,
2232 .abort = blockdev_backup_abort,
2233 .clean = blockdev_backup_clean,
2235 [TRANSACTION_ACTION_KIND_ABORT] = {
2236 .instance_size = sizeof(BlkActionState),
2237 .prepare = abort_prepare,
2238 .commit = abort_commit,
2240 [TRANSACTION_ACTION_KIND_BLOCKDEV_SNAPSHOT_INTERNAL_SYNC] = {
2241 .instance_size = sizeof(InternalSnapshotState),
2242 .prepare = internal_snapshot_prepare,
2243 .abort = internal_snapshot_abort,
2244 .clean = internal_snapshot_clean,
2246 [TRANSACTION_ACTION_KIND_BLOCK_DIRTY_BITMAP_ADD] = {
2247 .instance_size = sizeof(BlockDirtyBitmapState),
2248 .prepare = block_dirty_bitmap_add_prepare,
2249 .abort = block_dirty_bitmap_add_abort,
2251 [TRANSACTION_ACTION_KIND_BLOCK_DIRTY_BITMAP_CLEAR] = {
2252 .instance_size = sizeof(BlockDirtyBitmapState),
2253 .prepare = block_dirty_bitmap_clear_prepare,
2254 .commit = block_dirty_bitmap_free_backup,
2255 .abort = block_dirty_bitmap_restore,
2257 [TRANSACTION_ACTION_KIND_BLOCK_DIRTY_BITMAP_ENABLE] = {
2258 .instance_size = sizeof(BlockDirtyBitmapState),
2259 .prepare = block_dirty_bitmap_enable_prepare,
2260 .abort = block_dirty_bitmap_enable_abort,
2262 [TRANSACTION_ACTION_KIND_BLOCK_DIRTY_BITMAP_DISABLE] = {
2263 .instance_size = sizeof(BlockDirtyBitmapState),
2264 .prepare = block_dirty_bitmap_disable_prepare,
2265 .abort = block_dirty_bitmap_disable_abort,
2267 [TRANSACTION_ACTION_KIND_BLOCK_DIRTY_BITMAP_MERGE] = {
2268 .instance_size = sizeof(BlockDirtyBitmapState),
2269 .prepare = block_dirty_bitmap_merge_prepare,
2270 .commit = block_dirty_bitmap_free_backup,
2271 .abort = block_dirty_bitmap_restore,
2273 [TRANSACTION_ACTION_KIND_BLOCK_DIRTY_BITMAP_REMOVE] = {
2274 .instance_size = sizeof(BlockDirtyBitmapState),
2275 .prepare = block_dirty_bitmap_remove_prepare,
2276 .commit = block_dirty_bitmap_remove_commit,
2277 .abort = block_dirty_bitmap_remove_abort,
2279 /* Where are transactions for MIRROR, COMMIT and STREAM?
2280 * Although these blockjobs use transaction callbacks like the backup job,
2281 * these jobs do not necessarily adhere to transaction semantics.
2282 * These jobs may not fully undo all of their actions on abort, nor do they
2283 * necessarily work in transactions with more than one job in them.
2288 * Allocate a TransactionProperties structure if necessary, and fill
2289 * that structure with desired defaults if they are unset.
2291 static TransactionProperties *get_transaction_properties(
2292 TransactionProperties *props)
2294 if (!props) {
2295 props = g_new0(TransactionProperties, 1);
2298 if (!props->has_completion_mode) {
2299 props->has_completion_mode = true;
2300 props->completion_mode = ACTION_COMPLETION_MODE_INDIVIDUAL;
2303 return props;
2307 * 'Atomic' group operations. The operations are performed as a set, and if
2308 * any fail then we roll back all operations in the group.
2310 * Always run under BQL.
2312 void qmp_transaction(TransactionActionList *dev_list,
2313 bool has_props,
2314 struct TransactionProperties *props,
2315 Error **errp)
2317 TransactionActionList *dev_entry = dev_list;
2318 JobTxn *block_job_txn = NULL;
2319 BlkActionState *state, *next;
2320 Error *local_err = NULL;
2322 GLOBAL_STATE_CODE();
2324 QTAILQ_HEAD(, BlkActionState) snap_bdrv_states;
2325 QTAILQ_INIT(&snap_bdrv_states);
2327 /* Does this transaction get canceled as a group on failure?
2328 * If not, we don't really need to make a JobTxn.
2330 props = get_transaction_properties(props);
2331 if (props->completion_mode != ACTION_COMPLETION_MODE_INDIVIDUAL) {
2332 block_job_txn = job_txn_new();
2335 /* drain all i/o before any operations */
2336 bdrv_drain_all();
2338 /* We don't do anything in this loop that commits us to the operations */
2339 while (NULL != dev_entry) {
2340 TransactionAction *dev_info = NULL;
2341 const BlkActionOps *ops;
2343 dev_info = dev_entry->value;
2344 dev_entry = dev_entry->next;
2346 assert(dev_info->type < ARRAY_SIZE(actions));
2348 ops = &actions[dev_info->type];
2349 assert(ops->instance_size > 0);
2351 state = g_malloc0(ops->instance_size);
2352 state->ops = ops;
2353 state->action = dev_info;
2354 state->block_job_txn = block_job_txn;
2355 state->txn_props = props;
2356 QTAILQ_INSERT_TAIL(&snap_bdrv_states, state, entry);
2358 state->ops->prepare(state, &local_err);
2359 if (local_err) {
2360 error_propagate(errp, local_err);
2361 goto delete_and_fail;
2365 QTAILQ_FOREACH(state, &snap_bdrv_states, entry) {
2366 if (state->ops->commit) {
2367 state->ops->commit(state);
2371 /* success */
2372 goto exit;
2374 delete_and_fail:
2375 /* failure, and it is all-or-none; roll back all operations */
2376 QTAILQ_FOREACH_REVERSE(state, &snap_bdrv_states, entry) {
2377 if (state->ops->abort) {
2378 state->ops->abort(state);
2381 exit:
2382 QTAILQ_FOREACH_SAFE(state, &snap_bdrv_states, entry, next) {
2383 if (state->ops->clean) {
2384 state->ops->clean(state);
2386 g_free(state);
2388 if (!has_props) {
2389 qapi_free_TransactionProperties(props);
2391 job_txn_unref(block_job_txn);
2394 BlockDirtyBitmapSha256 *qmp_x_debug_block_dirty_bitmap_sha256(const char *node,
2395 const char *name,
2396 Error **errp)
2398 BdrvDirtyBitmap *bitmap;
2399 BlockDriverState *bs;
2400 BlockDirtyBitmapSha256 *ret = NULL;
2401 char *sha256;
2403 bitmap = block_dirty_bitmap_lookup(node, name, &bs, errp);
2404 if (!bitmap || !bs) {
2405 return NULL;
2408 sha256 = bdrv_dirty_bitmap_sha256(bitmap, errp);
2409 if (sha256 == NULL) {
2410 return NULL;
2413 ret = g_new(BlockDirtyBitmapSha256, 1);
2414 ret->sha256 = sha256;
2416 return ret;
2419 void coroutine_fn qmp_block_resize(bool has_device, const char *device,
2420 bool has_node_name, const char *node_name,
2421 int64_t size, Error **errp)
2423 Error *local_err = NULL;
2424 BlockBackend *blk;
2425 BlockDriverState *bs;
2426 AioContext *old_ctx;
2428 bs = bdrv_lookup_bs(has_device ? device : NULL,
2429 has_node_name ? node_name : NULL,
2430 &local_err);
2431 if (local_err) {
2432 error_propagate(errp, local_err);
2433 return;
2436 if (size < 0) {
2437 error_setg(errp, QERR_INVALID_PARAMETER_VALUE, "size", "a >0 size");
2438 return;
2441 if (bdrv_op_is_blocked(bs, BLOCK_OP_TYPE_RESIZE, NULL)) {
2442 error_setg(errp, QERR_DEVICE_IN_USE, device);
2443 return;
2446 blk = blk_new_with_bs(bs, BLK_PERM_RESIZE, BLK_PERM_ALL, errp);
2447 if (!blk) {
2448 return;
2451 bdrv_co_lock(bs);
2452 bdrv_drained_begin(bs);
2453 bdrv_co_unlock(bs);
2455 old_ctx = bdrv_co_enter(bs);
2456 blk_truncate(blk, size, false, PREALLOC_MODE_OFF, 0, errp);
2457 bdrv_co_leave(bs, old_ctx);
2459 bdrv_co_lock(bs);
2460 bdrv_drained_end(bs);
2461 blk_unref(blk);
2462 bdrv_co_unlock(bs);
2465 void qmp_block_stream(bool has_job_id, const char *job_id, const char *device,
2466 bool has_base, const char *base,
2467 bool has_base_node, const char *base_node,
2468 bool has_backing_file, const char *backing_file,
2469 bool has_bottom, const char *bottom,
2470 bool has_speed, int64_t speed,
2471 bool has_on_error, BlockdevOnError on_error,
2472 bool has_filter_node_name, const char *filter_node_name,
2473 bool has_auto_finalize, bool auto_finalize,
2474 bool has_auto_dismiss, bool auto_dismiss,
2475 Error **errp)
2477 BlockDriverState *bs, *iter, *iter_end;
2478 BlockDriverState *base_bs = NULL;
2479 BlockDriverState *bottom_bs = NULL;
2480 AioContext *aio_context;
2481 Error *local_err = NULL;
2482 int job_flags = JOB_DEFAULT;
2484 if (has_base && has_base_node) {
2485 error_setg(errp, "'base' and 'base-node' cannot be specified "
2486 "at the same time");
2487 return;
2490 if (has_base && has_bottom) {
2491 error_setg(errp, "'base' and 'bottom' cannot be specified "
2492 "at the same time");
2493 return;
2496 if (has_bottom && has_base_node) {
2497 error_setg(errp, "'bottom' and 'base-node' cannot be specified "
2498 "at the same time");
2499 return;
2502 if (!has_on_error) {
2503 on_error = BLOCKDEV_ON_ERROR_REPORT;
2506 bs = bdrv_lookup_bs(device, device, errp);
2507 if (!bs) {
2508 return;
2511 aio_context = bdrv_get_aio_context(bs);
2512 aio_context_acquire(aio_context);
2514 if (has_base) {
2515 base_bs = bdrv_find_backing_image(bs, base);
2516 if (base_bs == NULL) {
2517 error_setg(errp, "Can't find '%s' in the backing chain", base);
2518 goto out;
2520 assert(bdrv_get_aio_context(base_bs) == aio_context);
2523 if (has_base_node) {
2524 base_bs = bdrv_lookup_bs(NULL, base_node, errp);
2525 if (!base_bs) {
2526 goto out;
2528 if (bs == base_bs || !bdrv_chain_contains(bs, base_bs)) {
2529 error_setg(errp, "Node '%s' is not a backing image of '%s'",
2530 base_node, device);
2531 goto out;
2533 assert(bdrv_get_aio_context(base_bs) == aio_context);
2534 bdrv_refresh_filename(base_bs);
2537 if (has_bottom) {
2538 bottom_bs = bdrv_lookup_bs(NULL, bottom, errp);
2539 if (!bottom_bs) {
2540 goto out;
2542 if (!bottom_bs->drv) {
2543 error_setg(errp, "Node '%s' is not open", bottom);
2544 goto out;
2546 if (bottom_bs->drv->is_filter) {
2547 error_setg(errp, "Node '%s' is a filter, use a non-filter node "
2548 "as 'bottom'", bottom);
2549 goto out;
2551 if (!bdrv_chain_contains(bs, bottom_bs)) {
2552 error_setg(errp, "Node '%s' is not in a chain starting from '%s'",
2553 bottom, device);
2554 goto out;
2556 assert(bdrv_get_aio_context(bottom_bs) == aio_context);
2560 * Check for op blockers in the whole chain between bs and base (or bottom)
2562 iter_end = has_bottom ? bdrv_filter_or_cow_bs(bottom_bs) : base_bs;
2563 for (iter = bs; iter && iter != iter_end;
2564 iter = bdrv_filter_or_cow_bs(iter))
2566 if (bdrv_op_is_blocked(iter, BLOCK_OP_TYPE_STREAM, errp)) {
2567 goto out;
2571 /* if we are streaming the entire chain, the result will have no backing
2572 * file, and specifying one is therefore an error */
2573 if (base_bs == NULL && has_backing_file) {
2574 error_setg(errp, "backing file specified, but streaming the "
2575 "entire chain");
2576 goto out;
2579 if (has_auto_finalize && !auto_finalize) {
2580 job_flags |= JOB_MANUAL_FINALIZE;
2582 if (has_auto_dismiss && !auto_dismiss) {
2583 job_flags |= JOB_MANUAL_DISMISS;
2586 stream_start(has_job_id ? job_id : NULL, bs, base_bs, backing_file,
2587 bottom_bs, job_flags, has_speed ? speed : 0, on_error,
2588 filter_node_name, &local_err);
2589 if (local_err) {
2590 error_propagate(errp, local_err);
2591 goto out;
2594 trace_qmp_block_stream(bs);
2596 out:
2597 aio_context_release(aio_context);
2600 void qmp_block_commit(bool has_job_id, const char *job_id, const char *device,
2601 bool has_base_node, const char *base_node,
2602 bool has_base, const char *base,
2603 bool has_top_node, const char *top_node,
2604 bool has_top, const char *top,
2605 bool has_backing_file, const char *backing_file,
2606 bool has_speed, int64_t speed,
2607 bool has_on_error, BlockdevOnError on_error,
2608 bool has_filter_node_name, const char *filter_node_name,
2609 bool has_auto_finalize, bool auto_finalize,
2610 bool has_auto_dismiss, bool auto_dismiss,
2611 Error **errp)
2613 BlockDriverState *bs;
2614 BlockDriverState *iter;
2615 BlockDriverState *base_bs, *top_bs;
2616 AioContext *aio_context;
2617 Error *local_err = NULL;
2618 int job_flags = JOB_DEFAULT;
2619 uint64_t top_perm, top_shared;
2621 if (!has_speed) {
2622 speed = 0;
2624 if (!has_on_error) {
2625 on_error = BLOCKDEV_ON_ERROR_REPORT;
2627 if (!has_filter_node_name) {
2628 filter_node_name = NULL;
2630 if (has_auto_finalize && !auto_finalize) {
2631 job_flags |= JOB_MANUAL_FINALIZE;
2633 if (has_auto_dismiss && !auto_dismiss) {
2634 job_flags |= JOB_MANUAL_DISMISS;
2637 /* Important Note:
2638 * libvirt relies on the DeviceNotFound error class in order to probe for
2639 * live commit feature versions; for this to work, we must make sure to
2640 * perform the device lookup before any generic errors that may occur in a
2641 * scenario in which all optional arguments are omitted. */
2642 bs = qmp_get_root_bs(device, &local_err);
2643 if (!bs) {
2644 bs = bdrv_lookup_bs(device, device, NULL);
2645 if (!bs) {
2646 error_free(local_err);
2647 error_set(errp, ERROR_CLASS_DEVICE_NOT_FOUND,
2648 "Device '%s' not found", device);
2649 } else {
2650 error_propagate(errp, local_err);
2652 return;
2655 aio_context = bdrv_get_aio_context(bs);
2656 aio_context_acquire(aio_context);
2658 if (bdrv_op_is_blocked(bs, BLOCK_OP_TYPE_COMMIT_SOURCE, errp)) {
2659 goto out;
2662 /* default top_bs is the active layer */
2663 top_bs = bs;
2665 if (has_top_node && has_top) {
2666 error_setg(errp, "'top-node' and 'top' are mutually exclusive");
2667 goto out;
2668 } else if (has_top_node) {
2669 top_bs = bdrv_lookup_bs(NULL, top_node, errp);
2670 if (top_bs == NULL) {
2671 goto out;
2673 if (!bdrv_chain_contains(bs, top_bs)) {
2674 error_setg(errp, "'%s' is not in this backing file chain",
2675 top_node);
2676 goto out;
2678 } else if (has_top && top) {
2679 /* This strcmp() is just a shortcut, there is no need to
2680 * refresh @bs's filename. If it mismatches,
2681 * bdrv_find_backing_image() will do the refresh and may still
2682 * return @bs. */
2683 if (strcmp(bs->filename, top) != 0) {
2684 top_bs = bdrv_find_backing_image(bs, top);
2688 if (top_bs == NULL) {
2689 error_setg(errp, "Top image file %s not found", top ? top : "NULL");
2690 goto out;
2693 assert(bdrv_get_aio_context(top_bs) == aio_context);
2695 if (has_base_node && has_base) {
2696 error_setg(errp, "'base-node' and 'base' are mutually exclusive");
2697 goto out;
2698 } else if (has_base_node) {
2699 base_bs = bdrv_lookup_bs(NULL, base_node, errp);
2700 if (base_bs == NULL) {
2701 goto out;
2703 if (!bdrv_chain_contains(top_bs, base_bs)) {
2704 error_setg(errp, "'%s' is not in this backing file chain",
2705 base_node);
2706 goto out;
2708 } else if (has_base && base) {
2709 base_bs = bdrv_find_backing_image(top_bs, base);
2710 if (base_bs == NULL) {
2711 error_setg(errp, "Can't find '%s' in the backing chain", base);
2712 goto out;
2714 } else {
2715 base_bs = bdrv_find_base(top_bs);
2716 if (base_bs == NULL) {
2717 error_setg(errp, "There is no backimg image");
2718 goto out;
2722 assert(bdrv_get_aio_context(base_bs) == aio_context);
2724 for (iter = top_bs; iter != bdrv_filter_or_cow_bs(base_bs);
2725 iter = bdrv_filter_or_cow_bs(iter))
2727 if (bdrv_op_is_blocked(iter, BLOCK_OP_TYPE_COMMIT_TARGET, errp)) {
2728 goto out;
2732 /* Do not allow attempts to commit an image into itself */
2733 if (top_bs == base_bs) {
2734 error_setg(errp, "cannot commit an image into itself");
2735 goto out;
2739 * Active commit is required if and only if someone has taken a
2740 * WRITE permission on the top node. Historically, we have always
2741 * used active commit for top nodes, so continue that practice
2742 * lest we possibly break clients that rely on this behavior, e.g.
2743 * to later attach this node to a writing parent.
2744 * (Active commit is never really wrong.)
2746 bdrv_get_cumulative_perm(top_bs, &top_perm, &top_shared);
2747 if (top_perm & BLK_PERM_WRITE ||
2748 bdrv_skip_filters(top_bs) == bdrv_skip_filters(bs))
2750 if (has_backing_file) {
2751 if (bdrv_skip_filters(top_bs) == bdrv_skip_filters(bs)) {
2752 error_setg(errp, "'backing-file' specified,"
2753 " but 'top' is the active layer");
2754 } else {
2755 error_setg(errp, "'backing-file' specified, but 'top' has a "
2756 "writer on it");
2758 goto out;
2760 if (!has_job_id) {
2762 * Emulate here what block_job_create() does, because it
2763 * is possible that @bs != @top_bs (the block job should
2764 * be named after @bs, even if @top_bs is the actual
2765 * source)
2767 job_id = bdrv_get_device_name(bs);
2769 commit_active_start(job_id, top_bs, base_bs, job_flags, speed, on_error,
2770 filter_node_name, NULL, NULL, false, &local_err);
2771 } else {
2772 BlockDriverState *overlay_bs = bdrv_find_overlay(bs, top_bs);
2773 if (bdrv_op_is_blocked(overlay_bs, BLOCK_OP_TYPE_COMMIT_TARGET, errp)) {
2774 goto out;
2776 commit_start(has_job_id ? job_id : NULL, bs, base_bs, top_bs, job_flags,
2777 speed, on_error, has_backing_file ? backing_file : NULL,
2778 filter_node_name, &local_err);
2780 if (local_err != NULL) {
2781 error_propagate(errp, local_err);
2782 goto out;
2785 out:
2786 aio_context_release(aio_context);
2789 /* Common QMP interface for drive-backup and blockdev-backup */
2790 static BlockJob *do_backup_common(BackupCommon *backup,
2791 BlockDriverState *bs,
2792 BlockDriverState *target_bs,
2793 AioContext *aio_context,
2794 JobTxn *txn, Error **errp)
2796 BlockJob *job = NULL;
2797 BdrvDirtyBitmap *bmap = NULL;
2798 BackupPerf perf = { .max_workers = 64 };
2799 int job_flags = JOB_DEFAULT;
2801 if (!backup->has_speed) {
2802 backup->speed = 0;
2804 if (!backup->has_on_source_error) {
2805 backup->on_source_error = BLOCKDEV_ON_ERROR_REPORT;
2807 if (!backup->has_on_target_error) {
2808 backup->on_target_error = BLOCKDEV_ON_ERROR_REPORT;
2810 if (!backup->has_job_id) {
2811 backup->job_id = NULL;
2813 if (!backup->has_auto_finalize) {
2814 backup->auto_finalize = true;
2816 if (!backup->has_auto_dismiss) {
2817 backup->auto_dismiss = true;
2819 if (!backup->has_compress) {
2820 backup->compress = false;
2823 if (backup->x_perf) {
2824 if (backup->x_perf->has_use_copy_range) {
2825 perf.use_copy_range = backup->x_perf->use_copy_range;
2827 if (backup->x_perf->has_max_workers) {
2828 perf.max_workers = backup->x_perf->max_workers;
2830 if (backup->x_perf->has_max_chunk) {
2831 perf.max_chunk = backup->x_perf->max_chunk;
2835 if ((backup->sync == MIRROR_SYNC_MODE_BITMAP) ||
2836 (backup->sync == MIRROR_SYNC_MODE_INCREMENTAL)) {
2837 /* done before desugaring 'incremental' to print the right message */
2838 if (!backup->has_bitmap) {
2839 error_setg(errp, "must provide a valid bitmap name for "
2840 "'%s' sync mode", MirrorSyncMode_str(backup->sync));
2841 return NULL;
2845 if (backup->sync == MIRROR_SYNC_MODE_INCREMENTAL) {
2846 if (backup->has_bitmap_mode &&
2847 backup->bitmap_mode != BITMAP_SYNC_MODE_ON_SUCCESS) {
2848 error_setg(errp, "Bitmap sync mode must be '%s' "
2849 "when using sync mode '%s'",
2850 BitmapSyncMode_str(BITMAP_SYNC_MODE_ON_SUCCESS),
2851 MirrorSyncMode_str(backup->sync));
2852 return NULL;
2854 backup->has_bitmap_mode = true;
2855 backup->sync = MIRROR_SYNC_MODE_BITMAP;
2856 backup->bitmap_mode = BITMAP_SYNC_MODE_ON_SUCCESS;
2859 if (backup->has_bitmap) {
2860 bmap = bdrv_find_dirty_bitmap(bs, backup->bitmap);
2861 if (!bmap) {
2862 error_setg(errp, "Bitmap '%s' could not be found", backup->bitmap);
2863 return NULL;
2865 if (!backup->has_bitmap_mode) {
2866 error_setg(errp, "Bitmap sync mode must be given "
2867 "when providing a bitmap");
2868 return NULL;
2870 if (bdrv_dirty_bitmap_check(bmap, BDRV_BITMAP_ALLOW_RO, errp)) {
2871 return NULL;
2874 /* This does not produce a useful bitmap artifact: */
2875 if (backup->sync == MIRROR_SYNC_MODE_NONE) {
2876 error_setg(errp, "sync mode '%s' does not produce meaningful bitmap"
2877 " outputs", MirrorSyncMode_str(backup->sync));
2878 return NULL;
2881 /* If the bitmap isn't used for input or output, this is useless: */
2882 if (backup->bitmap_mode == BITMAP_SYNC_MODE_NEVER &&
2883 backup->sync != MIRROR_SYNC_MODE_BITMAP) {
2884 error_setg(errp, "Bitmap sync mode '%s' has no meaningful effect"
2885 " when combined with sync mode '%s'",
2886 BitmapSyncMode_str(backup->bitmap_mode),
2887 MirrorSyncMode_str(backup->sync));
2888 return NULL;
2892 if (!backup->has_bitmap && backup->has_bitmap_mode) {
2893 error_setg(errp, "Cannot specify bitmap sync mode without a bitmap");
2894 return NULL;
2897 if (!backup->auto_finalize) {
2898 job_flags |= JOB_MANUAL_FINALIZE;
2900 if (!backup->auto_dismiss) {
2901 job_flags |= JOB_MANUAL_DISMISS;
2904 job = backup_job_create(backup->job_id, bs, target_bs, backup->speed,
2905 backup->sync, bmap, backup->bitmap_mode,
2906 backup->compress,
2907 backup->filter_node_name,
2908 &perf,
2909 backup->on_source_error,
2910 backup->on_target_error,
2911 job_flags, NULL, NULL, txn, errp);
2912 return job;
2915 void qmp_drive_backup(DriveBackup *backup, Error **errp)
2917 TransactionAction action = {
2918 .type = TRANSACTION_ACTION_KIND_DRIVE_BACKUP,
2919 .u.drive_backup.data = backup,
2921 blockdev_do_action(&action, errp);
2924 BlockDeviceInfoList *qmp_query_named_block_nodes(bool has_flat,
2925 bool flat,
2926 Error **errp)
2928 bool return_flat = has_flat && flat;
2930 return bdrv_named_nodes_list(return_flat, errp);
2933 XDbgBlockGraph *qmp_x_debug_query_block_graph(Error **errp)
2935 return bdrv_get_xdbg_block_graph(errp);
2938 void qmp_blockdev_backup(BlockdevBackup *backup, Error **errp)
2940 TransactionAction action = {
2941 .type = TRANSACTION_ACTION_KIND_BLOCKDEV_BACKUP,
2942 .u.blockdev_backup.data = backup,
2944 blockdev_do_action(&action, errp);
2947 /* Parameter check and block job starting for drive mirroring.
2948 * Caller should hold @device and @target's aio context (must be the same).
2950 static void blockdev_mirror_common(const char *job_id, BlockDriverState *bs,
2951 BlockDriverState *target,
2952 bool has_replaces, const char *replaces,
2953 enum MirrorSyncMode sync,
2954 BlockMirrorBackingMode backing_mode,
2955 bool zero_target,
2956 bool has_speed, int64_t speed,
2957 bool has_granularity, uint32_t granularity,
2958 bool has_buf_size, int64_t buf_size,
2959 bool has_on_source_error,
2960 BlockdevOnError on_source_error,
2961 bool has_on_target_error,
2962 BlockdevOnError on_target_error,
2963 bool has_unmap, bool unmap,
2964 bool has_filter_node_name,
2965 const char *filter_node_name,
2966 bool has_copy_mode, MirrorCopyMode copy_mode,
2967 bool has_auto_finalize, bool auto_finalize,
2968 bool has_auto_dismiss, bool auto_dismiss,
2969 Error **errp)
2971 BlockDriverState *unfiltered_bs;
2972 int job_flags = JOB_DEFAULT;
2974 if (!has_speed) {
2975 speed = 0;
2977 if (!has_on_source_error) {
2978 on_source_error = BLOCKDEV_ON_ERROR_REPORT;
2980 if (!has_on_target_error) {
2981 on_target_error = BLOCKDEV_ON_ERROR_REPORT;
2983 if (!has_granularity) {
2984 granularity = 0;
2986 if (!has_buf_size) {
2987 buf_size = 0;
2989 if (!has_unmap) {
2990 unmap = true;
2992 if (!has_filter_node_name) {
2993 filter_node_name = NULL;
2995 if (!has_copy_mode) {
2996 copy_mode = MIRROR_COPY_MODE_BACKGROUND;
2998 if (has_auto_finalize && !auto_finalize) {
2999 job_flags |= JOB_MANUAL_FINALIZE;
3001 if (has_auto_dismiss && !auto_dismiss) {
3002 job_flags |= JOB_MANUAL_DISMISS;
3005 if (granularity != 0 && (granularity < 512 || granularity > 1048576 * 64)) {
3006 error_setg(errp, QERR_INVALID_PARAMETER_VALUE, "granularity",
3007 "a value in range [512B, 64MB]");
3008 return;
3010 if (granularity & (granularity - 1)) {
3011 error_setg(errp, QERR_INVALID_PARAMETER_VALUE, "granularity",
3012 "a power of 2");
3013 return;
3016 if (bdrv_op_is_blocked(bs, BLOCK_OP_TYPE_MIRROR_SOURCE, errp)) {
3017 return;
3019 if (bdrv_op_is_blocked(target, BLOCK_OP_TYPE_MIRROR_TARGET, errp)) {
3020 return;
3023 if (!bdrv_backing_chain_next(bs) && sync == MIRROR_SYNC_MODE_TOP) {
3024 sync = MIRROR_SYNC_MODE_FULL;
3027 if (!has_replaces) {
3028 /* We want to mirror from @bs, but keep implicit filters on top */
3029 unfiltered_bs = bdrv_skip_implicit_filters(bs);
3030 if (unfiltered_bs != bs) {
3031 replaces = unfiltered_bs->node_name;
3032 has_replaces = true;
3036 if (has_replaces) {
3037 BlockDriverState *to_replace_bs;
3038 AioContext *replace_aio_context;
3039 int64_t bs_size, replace_size;
3041 bs_size = bdrv_getlength(bs);
3042 if (bs_size < 0) {
3043 error_setg_errno(errp, -bs_size, "Failed to query device's size");
3044 return;
3047 to_replace_bs = check_to_replace_node(bs, replaces, errp);
3048 if (!to_replace_bs) {
3049 return;
3052 replace_aio_context = bdrv_get_aio_context(to_replace_bs);
3053 aio_context_acquire(replace_aio_context);
3054 replace_size = bdrv_getlength(to_replace_bs);
3055 aio_context_release(replace_aio_context);
3057 if (replace_size < 0) {
3058 error_setg_errno(errp, -replace_size,
3059 "Failed to query the replacement node's size");
3060 return;
3062 if (bs_size != replace_size) {
3063 error_setg(errp, "cannot replace image with a mirror image of "
3064 "different size");
3065 return;
3069 /* pass the node name to replace to mirror start since it's loose coupling
3070 * and will allow to check whether the node still exist at mirror completion
3072 mirror_start(job_id, bs, target,
3073 has_replaces ? replaces : NULL, job_flags,
3074 speed, granularity, buf_size, sync, backing_mode, zero_target,
3075 on_source_error, on_target_error, unmap, filter_node_name,
3076 copy_mode, errp);
3079 void qmp_drive_mirror(DriveMirror *arg, Error **errp)
3081 BlockDriverState *bs;
3082 BlockDriverState *target_backing_bs, *target_bs;
3083 AioContext *aio_context;
3084 AioContext *old_context;
3085 BlockMirrorBackingMode backing_mode;
3086 Error *local_err = NULL;
3087 QDict *options = NULL;
3088 int flags;
3089 int64_t size;
3090 const char *format = arg->format;
3091 bool zero_target;
3092 int ret;
3094 bs = qmp_get_root_bs(arg->device, errp);
3095 if (!bs) {
3096 return;
3099 /* Early check to avoid creating target */
3100 if (bdrv_op_is_blocked(bs, BLOCK_OP_TYPE_MIRROR_SOURCE, errp)) {
3101 return;
3104 aio_context = bdrv_get_aio_context(bs);
3105 aio_context_acquire(aio_context);
3107 if (!arg->has_mode) {
3108 arg->mode = NEW_IMAGE_MODE_ABSOLUTE_PATHS;
3111 if (!arg->has_format) {
3112 format = (arg->mode == NEW_IMAGE_MODE_EXISTING
3113 ? NULL : bs->drv->format_name);
3116 flags = bs->open_flags | BDRV_O_RDWR;
3117 target_backing_bs = bdrv_cow_bs(bdrv_skip_filters(bs));
3118 if (!target_backing_bs && arg->sync == MIRROR_SYNC_MODE_TOP) {
3119 arg->sync = MIRROR_SYNC_MODE_FULL;
3121 if (arg->sync == MIRROR_SYNC_MODE_NONE) {
3122 target_backing_bs = bs;
3125 size = bdrv_getlength(bs);
3126 if (size < 0) {
3127 error_setg_errno(errp, -size, "bdrv_getlength failed");
3128 goto out;
3131 if (arg->has_replaces) {
3132 if (!arg->has_node_name) {
3133 error_setg(errp, "a node-name must be provided when replacing a"
3134 " named node of the graph");
3135 goto out;
3139 if (arg->mode == NEW_IMAGE_MODE_ABSOLUTE_PATHS) {
3140 backing_mode = MIRROR_SOURCE_BACKING_CHAIN;
3141 } else {
3142 backing_mode = MIRROR_OPEN_BACKING_CHAIN;
3145 /* Don't open backing image in create() */
3146 flags |= BDRV_O_NO_BACKING;
3148 if ((arg->sync == MIRROR_SYNC_MODE_FULL || !target_backing_bs)
3149 && arg->mode != NEW_IMAGE_MODE_EXISTING)
3151 /* create new image w/o backing file */
3152 assert(format);
3153 bdrv_img_create(arg->target, format,
3154 NULL, NULL, NULL, size, flags, false, &local_err);
3155 } else {
3156 /* Implicit filters should not appear in the filename */
3157 BlockDriverState *explicit_backing =
3158 bdrv_skip_implicit_filters(target_backing_bs);
3160 switch (arg->mode) {
3161 case NEW_IMAGE_MODE_EXISTING:
3162 break;
3163 case NEW_IMAGE_MODE_ABSOLUTE_PATHS:
3164 /* create new image with backing file */
3165 bdrv_refresh_filename(explicit_backing);
3166 bdrv_img_create(arg->target, format,
3167 explicit_backing->filename,
3168 explicit_backing->drv->format_name,
3169 NULL, size, flags, false, &local_err);
3170 break;
3171 default:
3172 abort();
3176 if (local_err) {
3177 error_propagate(errp, local_err);
3178 goto out;
3181 options = qdict_new();
3182 if (arg->has_node_name) {
3183 qdict_put_str(options, "node-name", arg->node_name);
3185 if (format) {
3186 qdict_put_str(options, "driver", format);
3189 /* Mirroring takes care of copy-on-write using the source's backing
3190 * file.
3192 target_bs = bdrv_open(arg->target, NULL, options, flags, errp);
3193 if (!target_bs) {
3194 goto out;
3197 zero_target = (arg->sync == MIRROR_SYNC_MODE_FULL &&
3198 (arg->mode == NEW_IMAGE_MODE_EXISTING ||
3199 !bdrv_has_zero_init(target_bs)));
3202 /* Honor bdrv_try_set_aio_context() context acquisition requirements. */
3203 old_context = bdrv_get_aio_context(target_bs);
3204 aio_context_release(aio_context);
3205 aio_context_acquire(old_context);
3207 ret = bdrv_try_set_aio_context(target_bs, aio_context, errp);
3208 if (ret < 0) {
3209 bdrv_unref(target_bs);
3210 aio_context_release(old_context);
3211 return;
3214 aio_context_release(old_context);
3215 aio_context_acquire(aio_context);
3217 blockdev_mirror_common(arg->has_job_id ? arg->job_id : NULL, bs, target_bs,
3218 arg->has_replaces, arg->replaces, arg->sync,
3219 backing_mode, zero_target,
3220 arg->has_speed, arg->speed,
3221 arg->has_granularity, arg->granularity,
3222 arg->has_buf_size, arg->buf_size,
3223 arg->has_on_source_error, arg->on_source_error,
3224 arg->has_on_target_error, arg->on_target_error,
3225 arg->has_unmap, arg->unmap,
3226 false, NULL,
3227 arg->has_copy_mode, arg->copy_mode,
3228 arg->has_auto_finalize, arg->auto_finalize,
3229 arg->has_auto_dismiss, arg->auto_dismiss,
3230 errp);
3231 bdrv_unref(target_bs);
3232 out:
3233 aio_context_release(aio_context);
3236 void qmp_blockdev_mirror(bool has_job_id, const char *job_id,
3237 const char *device, const char *target,
3238 bool has_replaces, const char *replaces,
3239 MirrorSyncMode sync,
3240 bool has_speed, int64_t speed,
3241 bool has_granularity, uint32_t granularity,
3242 bool has_buf_size, int64_t buf_size,
3243 bool has_on_source_error,
3244 BlockdevOnError on_source_error,
3245 bool has_on_target_error,
3246 BlockdevOnError on_target_error,
3247 bool has_filter_node_name,
3248 const char *filter_node_name,
3249 bool has_copy_mode, MirrorCopyMode copy_mode,
3250 bool has_auto_finalize, bool auto_finalize,
3251 bool has_auto_dismiss, bool auto_dismiss,
3252 Error **errp)
3254 BlockDriverState *bs;
3255 BlockDriverState *target_bs;
3256 AioContext *aio_context;
3257 AioContext *old_context;
3258 BlockMirrorBackingMode backing_mode = MIRROR_LEAVE_BACKING_CHAIN;
3259 bool zero_target;
3260 int ret;
3262 bs = qmp_get_root_bs(device, errp);
3263 if (!bs) {
3264 return;
3267 target_bs = bdrv_lookup_bs(target, target, errp);
3268 if (!target_bs) {
3269 return;
3272 zero_target = (sync == MIRROR_SYNC_MODE_FULL);
3274 /* Honor bdrv_try_set_aio_context() context acquisition requirements. */
3275 old_context = bdrv_get_aio_context(target_bs);
3276 aio_context = bdrv_get_aio_context(bs);
3277 aio_context_acquire(old_context);
3279 ret = bdrv_try_set_aio_context(target_bs, aio_context, errp);
3281 aio_context_release(old_context);
3282 aio_context_acquire(aio_context);
3284 if (ret < 0) {
3285 goto out;
3288 blockdev_mirror_common(has_job_id ? job_id : NULL, bs, target_bs,
3289 has_replaces, replaces, sync, backing_mode,
3290 zero_target, has_speed, speed,
3291 has_granularity, granularity,
3292 has_buf_size, buf_size,
3293 has_on_source_error, on_source_error,
3294 has_on_target_error, on_target_error,
3295 true, true,
3296 has_filter_node_name, filter_node_name,
3297 has_copy_mode, copy_mode,
3298 has_auto_finalize, auto_finalize,
3299 has_auto_dismiss, auto_dismiss,
3300 errp);
3301 out:
3302 aio_context_release(aio_context);
3305 /* Get a block job using its ID and acquire its AioContext */
3306 static BlockJob *find_block_job(const char *id, AioContext **aio_context,
3307 Error **errp)
3309 BlockJob *job;
3311 assert(id != NULL);
3313 *aio_context = NULL;
3315 job = block_job_get(id);
3317 if (!job) {
3318 error_set(errp, ERROR_CLASS_DEVICE_NOT_ACTIVE,
3319 "Block job '%s' not found", id);
3320 return NULL;
3323 *aio_context = block_job_get_aio_context(job);
3324 aio_context_acquire(*aio_context);
3326 return job;
3329 void qmp_block_job_set_speed(const char *device, int64_t speed, Error **errp)
3331 AioContext *aio_context;
3332 BlockJob *job = find_block_job(device, &aio_context, errp);
3334 if (!job) {
3335 return;
3338 block_job_set_speed(job, speed, errp);
3339 aio_context_release(aio_context);
3342 void qmp_block_job_cancel(const char *device,
3343 bool has_force, bool force, Error **errp)
3345 AioContext *aio_context;
3346 BlockJob *job = find_block_job(device, &aio_context, errp);
3348 if (!job) {
3349 return;
3352 if (!has_force) {
3353 force = false;
3356 if (job_user_paused(&job->job) && !force) {
3357 error_setg(errp, "The block job for device '%s' is currently paused",
3358 device);
3359 goto out;
3362 trace_qmp_block_job_cancel(job);
3363 job_user_cancel(&job->job, force, errp);
3364 out:
3365 aio_context_release(aio_context);
3368 void qmp_block_job_pause(const char *device, Error **errp)
3370 AioContext *aio_context;
3371 BlockJob *job = find_block_job(device, &aio_context, errp);
3373 if (!job) {
3374 return;
3377 trace_qmp_block_job_pause(job);
3378 job_user_pause(&job->job, errp);
3379 aio_context_release(aio_context);
3382 void qmp_block_job_resume(const char *device, Error **errp)
3384 AioContext *aio_context;
3385 BlockJob *job = find_block_job(device, &aio_context, errp);
3387 if (!job) {
3388 return;
3391 trace_qmp_block_job_resume(job);
3392 job_user_resume(&job->job, errp);
3393 aio_context_release(aio_context);
3396 void qmp_block_job_complete(const char *device, Error **errp)
3398 AioContext *aio_context;
3399 BlockJob *job = find_block_job(device, &aio_context, errp);
3401 if (!job) {
3402 return;
3405 trace_qmp_block_job_complete(job);
3406 job_complete(&job->job, errp);
3407 aio_context_release(aio_context);
3410 void qmp_block_job_finalize(const char *id, Error **errp)
3412 AioContext *aio_context;
3413 BlockJob *job = find_block_job(id, &aio_context, errp);
3415 if (!job) {
3416 return;
3419 trace_qmp_block_job_finalize(job);
3420 job_ref(&job->job);
3421 job_finalize(&job->job, errp);
3424 * Job's context might have changed via job_finalize (and job_txn_apply
3425 * automatically acquires the new one), so make sure we release the correct
3426 * one.
3428 aio_context = block_job_get_aio_context(job);
3429 job_unref(&job->job);
3430 aio_context_release(aio_context);
3433 void qmp_block_job_dismiss(const char *id, Error **errp)
3435 AioContext *aio_context;
3436 BlockJob *bjob = find_block_job(id, &aio_context, errp);
3437 Job *job;
3439 if (!bjob) {
3440 return;
3443 trace_qmp_block_job_dismiss(bjob);
3444 job = &bjob->job;
3445 job_dismiss(&job, errp);
3446 aio_context_release(aio_context);
3449 void qmp_change_backing_file(const char *device,
3450 const char *image_node_name,
3451 const char *backing_file,
3452 Error **errp)
3454 BlockDriverState *bs = NULL;
3455 AioContext *aio_context;
3456 BlockDriverState *image_bs = NULL;
3457 Error *local_err = NULL;
3458 bool ro;
3459 int ret;
3461 bs = qmp_get_root_bs(device, errp);
3462 if (!bs) {
3463 return;
3466 aio_context = bdrv_get_aio_context(bs);
3467 aio_context_acquire(aio_context);
3469 image_bs = bdrv_lookup_bs(NULL, image_node_name, &local_err);
3470 if (local_err) {
3471 error_propagate(errp, local_err);
3472 goto out;
3475 if (!image_bs) {
3476 error_setg(errp, "image file not found");
3477 goto out;
3480 if (bdrv_find_base(image_bs) == image_bs) {
3481 error_setg(errp, "not allowing backing file change on an image "
3482 "without a backing file");
3483 goto out;
3486 /* even though we are not necessarily operating on bs, we need it to
3487 * determine if block ops are currently prohibited on the chain */
3488 if (bdrv_op_is_blocked(bs, BLOCK_OP_TYPE_CHANGE, errp)) {
3489 goto out;
3492 /* final sanity check */
3493 if (!bdrv_chain_contains(bs, image_bs)) {
3494 error_setg(errp, "'%s' and image file are not in the same chain",
3495 device);
3496 goto out;
3499 /* if not r/w, reopen to make r/w */
3500 ro = bdrv_is_read_only(image_bs);
3502 if (ro) {
3503 if (bdrv_reopen_set_read_only(image_bs, false, errp) != 0) {
3504 goto out;
3508 ret = bdrv_change_backing_file(image_bs, backing_file,
3509 image_bs->drv ? image_bs->drv->format_name : "",
3510 false);
3512 if (ret < 0) {
3513 error_setg_errno(errp, -ret, "Could not change backing file to '%s'",
3514 backing_file);
3515 /* don't exit here, so we can try to restore open flags if
3516 * appropriate */
3519 if (ro) {
3520 bdrv_reopen_set_read_only(image_bs, true, errp);
3523 out:
3524 aio_context_release(aio_context);
3527 void qmp_blockdev_add(BlockdevOptions *options, Error **errp)
3529 BlockDriverState *bs;
3530 QObject *obj;
3531 Visitor *v = qobject_output_visitor_new(&obj);
3532 QDict *qdict;
3534 visit_type_BlockdevOptions(v, NULL, &options, &error_abort);
3535 visit_complete(v, &obj);
3536 qdict = qobject_to(QDict, obj);
3538 qdict_flatten(qdict);
3540 if (!qdict_get_try_str(qdict, "node-name")) {
3541 error_setg(errp, "'node-name' must be specified for the root node");
3542 goto fail;
3545 bs = bds_tree_init(qdict, errp);
3546 if (!bs) {
3547 goto fail;
3550 bdrv_set_monitor_owned(bs);
3552 fail:
3553 visit_free(v);
3556 void qmp_blockdev_reopen(BlockdevOptionsList *reopen_list, Error **errp)
3558 BlockReopenQueue *queue = NULL;
3559 GSList *drained = NULL;
3560 GSList *p;
3562 /* Add each one of the BDS that we want to reopen to the queue */
3563 for (; reopen_list != NULL; reopen_list = reopen_list->next) {
3564 BlockdevOptions *options = reopen_list->value;
3565 BlockDriverState *bs;
3566 AioContext *ctx;
3567 QObject *obj;
3568 Visitor *v;
3569 QDict *qdict;
3571 /* Check for the selected node name */
3572 if (!options->has_node_name) {
3573 error_setg(errp, "node-name not specified");
3574 goto fail;
3577 bs = bdrv_find_node(options->node_name);
3578 if (!bs) {
3579 error_setg(errp, "Failed to find node with node-name='%s'",
3580 options->node_name);
3581 goto fail;
3584 /* Put all options in a QDict and flatten it */
3585 v = qobject_output_visitor_new(&obj);
3586 visit_type_BlockdevOptions(v, NULL, &options, &error_abort);
3587 visit_complete(v, &obj);
3588 visit_free(v);
3590 qdict = qobject_to(QDict, obj);
3592 qdict_flatten(qdict);
3594 ctx = bdrv_get_aio_context(bs);
3595 aio_context_acquire(ctx);
3597 bdrv_subtree_drained_begin(bs);
3598 queue = bdrv_reopen_queue(queue, bs, qdict, false);
3599 drained = g_slist_prepend(drained, bs);
3601 aio_context_release(ctx);
3604 /* Perform the reopen operation */
3605 bdrv_reopen_multiple(queue, errp);
3606 queue = NULL;
3608 fail:
3609 bdrv_reopen_queue_free(queue);
3610 for (p = drained; p; p = p->next) {
3611 BlockDriverState *bs = p->data;
3612 AioContext *ctx = bdrv_get_aio_context(bs);
3614 aio_context_acquire(ctx);
3615 bdrv_subtree_drained_end(bs);
3616 aio_context_release(ctx);
3618 g_slist_free(drained);
3621 void qmp_blockdev_del(const char *node_name, Error **errp)
3623 AioContext *aio_context;
3624 BlockDriverState *bs;
3626 GLOBAL_STATE_CODE();
3628 bs = bdrv_find_node(node_name);
3629 if (!bs) {
3630 error_setg(errp, "Failed to find node with node-name='%s'", node_name);
3631 return;
3633 if (bdrv_has_blk(bs)) {
3634 error_setg(errp, "Node %s is in use", node_name);
3635 return;
3637 aio_context = bdrv_get_aio_context(bs);
3638 aio_context_acquire(aio_context);
3640 if (bdrv_op_is_blocked(bs, BLOCK_OP_TYPE_DRIVE_DEL, errp)) {
3641 goto out;
3644 if (!QTAILQ_IN_USE(bs, monitor_list)) {
3645 error_setg(errp, "Node %s is not owned by the monitor",
3646 bs->node_name);
3647 goto out;
3650 if (bs->refcnt > 1) {
3651 error_setg(errp, "Block device %s is in use",
3652 bdrv_get_device_or_node_name(bs));
3653 goto out;
3656 QTAILQ_REMOVE(&monitor_bdrv_states, bs, monitor_list);
3657 bdrv_unref(bs);
3659 out:
3660 aio_context_release(aio_context);
3663 static BdrvChild *bdrv_find_child(BlockDriverState *parent_bs,
3664 const char *child_name)
3666 BdrvChild *child;
3668 QLIST_FOREACH(child, &parent_bs->children, next) {
3669 if (strcmp(child->name, child_name) == 0) {
3670 return child;
3674 return NULL;
3677 void qmp_x_blockdev_change(const char *parent, bool has_child,
3678 const char *child, bool has_node,
3679 const char *node, Error **errp)
3681 BlockDriverState *parent_bs, *new_bs = NULL;
3682 BdrvChild *p_child;
3684 parent_bs = bdrv_lookup_bs(parent, parent, errp);
3685 if (!parent_bs) {
3686 return;
3689 if (has_child == has_node) {
3690 if (has_child) {
3691 error_setg(errp, "The parameters child and node are in conflict");
3692 } else {
3693 error_setg(errp, "Either child or node must be specified");
3695 return;
3698 if (has_child) {
3699 p_child = bdrv_find_child(parent_bs, child);
3700 if (!p_child) {
3701 error_setg(errp, "Node '%s' does not have child '%s'",
3702 parent, child);
3703 return;
3705 bdrv_del_child(parent_bs, p_child, errp);
3708 if (has_node) {
3709 new_bs = bdrv_find_node(node);
3710 if (!new_bs) {
3711 error_setg(errp, "Node '%s' not found", node);
3712 return;
3714 bdrv_add_child(parent_bs, new_bs, errp);
3718 BlockJobInfoList *qmp_query_block_jobs(Error **errp)
3720 BlockJobInfoList *head = NULL, **tail = &head;
3721 BlockJob *job;
3723 for (job = block_job_next(NULL); job; job = block_job_next(job)) {
3724 BlockJobInfo *value;
3725 AioContext *aio_context;
3727 if (block_job_is_internal(job)) {
3728 continue;
3730 aio_context = block_job_get_aio_context(job);
3731 aio_context_acquire(aio_context);
3732 value = block_job_query(job, errp);
3733 aio_context_release(aio_context);
3734 if (!value) {
3735 qapi_free_BlockJobInfoList(head);
3736 return NULL;
3738 QAPI_LIST_APPEND(tail, value);
3741 return head;
3744 void qmp_x_blockdev_set_iothread(const char *node_name, StrOrNull *iothread,
3745 bool has_force, bool force, Error **errp)
3747 AioContext *old_context;
3748 AioContext *new_context;
3749 BlockDriverState *bs;
3751 bs = bdrv_find_node(node_name);
3752 if (!bs) {
3753 error_setg(errp, "Failed to find node with node-name='%s'", node_name);
3754 return;
3757 /* Protects against accidents. */
3758 if (!(has_force && force) && bdrv_has_blk(bs)) {
3759 error_setg(errp, "Node %s is associated with a BlockBackend and could "
3760 "be in use (use force=true to override this check)",
3761 node_name);
3762 return;
3765 if (iothread->type == QTYPE_QSTRING) {
3766 IOThread *obj = iothread_by_id(iothread->u.s);
3767 if (!obj) {
3768 error_setg(errp, "Cannot find iothread %s", iothread->u.s);
3769 return;
3772 new_context = iothread_get_aio_context(obj);
3773 } else {
3774 new_context = qemu_get_aio_context();
3777 old_context = bdrv_get_aio_context(bs);
3778 aio_context_acquire(old_context);
3780 bdrv_try_set_aio_context(bs, new_context, errp);
3782 aio_context_release(old_context);
3785 QemuOptsList qemu_common_drive_opts = {
3786 .name = "drive",
3787 .head = QTAILQ_HEAD_INITIALIZER(qemu_common_drive_opts.head),
3788 .desc = {
3790 .name = "snapshot",
3791 .type = QEMU_OPT_BOOL,
3792 .help = "enable/disable snapshot mode",
3794 .name = "aio",
3795 .type = QEMU_OPT_STRING,
3796 .help = "host AIO implementation (threads, native, io_uring)",
3798 .name = BDRV_OPT_CACHE_WB,
3799 .type = QEMU_OPT_BOOL,
3800 .help = "Enable writeback mode",
3802 .name = "format",
3803 .type = QEMU_OPT_STRING,
3804 .help = "disk format (raw, qcow2, ...)",
3806 .name = "rerror",
3807 .type = QEMU_OPT_STRING,
3808 .help = "read error action",
3810 .name = "werror",
3811 .type = QEMU_OPT_STRING,
3812 .help = "write error action",
3814 .name = BDRV_OPT_READ_ONLY,
3815 .type = QEMU_OPT_BOOL,
3816 .help = "open drive file as read-only",
3819 THROTTLE_OPTS,
3822 .name = "throttling.group",
3823 .type = QEMU_OPT_STRING,
3824 .help = "name of the block throttling group",
3826 .name = "copy-on-read",
3827 .type = QEMU_OPT_BOOL,
3828 .help = "copy read data from backing file into image file",
3830 .name = "detect-zeroes",
3831 .type = QEMU_OPT_STRING,
3832 .help = "try to optimize zero writes (off, on, unmap)",
3834 .name = "stats-account-invalid",
3835 .type = QEMU_OPT_BOOL,
3836 .help = "whether to account for invalid I/O operations "
3837 "in the statistics",
3839 .name = "stats-account-failed",
3840 .type = QEMU_OPT_BOOL,
3841 .help = "whether to account for failed I/O operations "
3842 "in the statistics",
3844 { /* end of list */ }
3848 QemuOptsList qemu_drive_opts = {
3849 .name = "drive",
3850 .head = QTAILQ_HEAD_INITIALIZER(qemu_drive_opts.head),
3851 .desc = {
3853 * no elements => accept any params
3854 * validation will happen later
3856 { /* end of list */ }