Merge remote-tracking branch 'remotes/dgilbert-gitlab/tags/pull-virtiofs-20200221...
[qemu/ar7.git] / blockdev.c
blob011dcfec27704514884b7a5684bbc97d57d0772b
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/arch_init.h"
60 #include "sysemu/qtest.h"
61 #include "sysemu/runstate.h"
62 #include "qemu/cutils.h"
63 #include "qemu/help_option.h"
64 #include "qemu/main-loop.h"
65 #include "qemu/throttle-options.h"
67 static QTAILQ_HEAD(, BlockDriverState) monitor_bdrv_states =
68 QTAILQ_HEAD_INITIALIZER(monitor_bdrv_states);
70 static int do_open_tray(const char *blk_name, const char *qdev_id,
71 bool force, Error **errp);
72 static void blockdev_remove_medium(bool has_device, const char *device,
73 bool has_id, const char *id, Error **errp);
74 static void blockdev_insert_medium(bool has_device, const char *device,
75 bool has_id, const char *id,
76 const char *node_name, Error **errp);
78 static const char *const if_name[IF_COUNT] = {
79 [IF_NONE] = "none",
80 [IF_IDE] = "ide",
81 [IF_SCSI] = "scsi",
82 [IF_FLOPPY] = "floppy",
83 [IF_PFLASH] = "pflash",
84 [IF_MTD] = "mtd",
85 [IF_SD] = "sd",
86 [IF_VIRTIO] = "virtio",
87 [IF_XEN] = "xen",
90 static int if_max_devs[IF_COUNT] = {
92 * Do not change these numbers! They govern how drive option
93 * index maps to unit and bus. That mapping is ABI.
95 * All controllers used to implement if=T drives need to support
96 * if_max_devs[T] units, for any T with if_max_devs[T] != 0.
97 * Otherwise, some index values map to "impossible" bus, unit
98 * values.
100 * For instance, if you change [IF_SCSI] to 255, -drive
101 * if=scsi,index=12 no longer means bus=1,unit=5, but
102 * bus=0,unit=12. With an lsi53c895a controller (7 units max),
103 * the drive can't be set up. Regression.
105 [IF_IDE] = 2,
106 [IF_SCSI] = 7,
110 * Boards may call this to offer board-by-board overrides
111 * of the default, global values.
113 void override_max_devs(BlockInterfaceType type, int max_devs)
115 BlockBackend *blk;
116 DriveInfo *dinfo;
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 if (!dinfo) {
148 return;
151 for (job = block_job_next(NULL); job; job = block_job_next(job)) {
152 if (block_job_has_bdrv(job, blk_bs(blk))) {
153 AioContext *aio_context = job->job.aio_context;
154 aio_context_acquire(aio_context);
156 job_cancel(&job->job, false);
158 aio_context_release(aio_context);
162 dinfo->auto_del = 1;
165 void blockdev_auto_del(BlockBackend *blk)
167 DriveInfo *dinfo = blk_legacy_dinfo(blk);
169 if (dinfo && dinfo->auto_del) {
170 monitor_remove_blk(blk);
171 blk_unref(blk);
176 * Returns the current mapping of how many units per bus
177 * a particular interface can support.
179 * A positive integer indicates n units per bus.
180 * 0 implies the mapping has not been established.
181 * -1 indicates an invalid BlockInterfaceType was given.
183 int drive_get_max_devs(BlockInterfaceType type)
185 if (type >= IF_IDE && type < IF_COUNT) {
186 return if_max_devs[type];
189 return -1;
192 static int drive_index_to_bus_id(BlockInterfaceType type, int index)
194 int max_devs = if_max_devs[type];
195 return max_devs ? index / max_devs : 0;
198 static int drive_index_to_unit_id(BlockInterfaceType type, int index)
200 int max_devs = if_max_devs[type];
201 return max_devs ? index % max_devs : index;
204 QemuOpts *drive_def(const char *optstr)
206 return qemu_opts_parse_noisily(qemu_find_opts("drive"), optstr, false);
209 QemuOpts *drive_add(BlockInterfaceType type, int index, const char *file,
210 const char *optstr)
212 QemuOpts *opts;
214 opts = drive_def(optstr);
215 if (!opts) {
216 return NULL;
218 if (type != IF_DEFAULT) {
219 qemu_opt_set(opts, "if", if_name[type], &error_abort);
221 if (index >= 0) {
222 qemu_opt_set_number(opts, "index", index, &error_abort);
224 if (file)
225 qemu_opt_set(opts, "file", file, &error_abort);
226 return opts;
229 DriveInfo *drive_get(BlockInterfaceType type, int bus, int unit)
231 BlockBackend *blk;
232 DriveInfo *dinfo;
234 for (blk = blk_next(NULL); blk; blk = blk_next(blk)) {
235 dinfo = blk_legacy_dinfo(blk);
236 if (dinfo && dinfo->type == type
237 && dinfo->bus == bus && dinfo->unit == unit) {
238 return dinfo;
242 return NULL;
245 void drive_check_orphaned(void)
247 BlockBackend *blk;
248 DriveInfo *dinfo;
249 Location loc;
250 bool orphans = false;
252 for (blk = blk_next(NULL); blk; blk = blk_next(blk)) {
253 dinfo = blk_legacy_dinfo(blk);
254 if (!blk_get_attached_dev(blk) && !dinfo->is_default &&
255 dinfo->type != IF_NONE) {
256 loc_push_none(&loc);
257 qemu_opts_loc_restore(dinfo->opts);
258 error_report("machine type does not support"
259 " if=%s,bus=%d,unit=%d",
260 if_name[dinfo->type], dinfo->bus, dinfo->unit);
261 loc_pop(&loc);
262 orphans = true;
266 if (orphans) {
267 exit(1);
271 DriveInfo *drive_get_by_index(BlockInterfaceType type, int index)
273 return drive_get(type,
274 drive_index_to_bus_id(type, index),
275 drive_index_to_unit_id(type, index));
278 int drive_get_max_bus(BlockInterfaceType type)
280 int max_bus;
281 BlockBackend *blk;
282 DriveInfo *dinfo;
284 max_bus = -1;
285 for (blk = blk_next(NULL); blk; blk = blk_next(blk)) {
286 dinfo = blk_legacy_dinfo(blk);
287 if (dinfo && dinfo->type == type && dinfo->bus > max_bus) {
288 max_bus = dinfo->bus;
291 return max_bus;
294 /* Get a block device. This should only be used for single-drive devices
295 (e.g. SD/Floppy/MTD). Multi-disk devices (scsi/ide) should use the
296 appropriate bus. */
297 DriveInfo *drive_get_next(BlockInterfaceType type)
299 static int next_block_unit[IF_COUNT];
301 return drive_get(type, 0, next_block_unit[type]++);
304 static void bdrv_format_print(void *opaque, const char *name)
306 qemu_printf(" %s", name);
309 typedef struct {
310 QEMUBH *bh;
311 BlockDriverState *bs;
312 } BDRVPutRefBH;
314 static int parse_block_error_action(const char *buf, bool is_read, Error **errp)
316 if (!strcmp(buf, "ignore")) {
317 return BLOCKDEV_ON_ERROR_IGNORE;
318 } else if (!is_read && !strcmp(buf, "enospc")) {
319 return BLOCKDEV_ON_ERROR_ENOSPC;
320 } else if (!strcmp(buf, "stop")) {
321 return BLOCKDEV_ON_ERROR_STOP;
322 } else if (!strcmp(buf, "report")) {
323 return BLOCKDEV_ON_ERROR_REPORT;
324 } else {
325 error_setg(errp, "'%s' invalid %s error action",
326 buf, is_read ? "read" : "write");
327 return -1;
331 static bool parse_stats_intervals(BlockAcctStats *stats, QList *intervals,
332 Error **errp)
334 const QListEntry *entry;
335 for (entry = qlist_first(intervals); entry; entry = qlist_next(entry)) {
336 switch (qobject_type(entry->value)) {
338 case QTYPE_QSTRING: {
339 unsigned long long length;
340 const char *str = qstring_get_str(qobject_to(QString,
341 entry->value));
342 if (parse_uint_full(str, &length, 10) == 0 &&
343 length > 0 && length <= UINT_MAX) {
344 block_acct_add_interval(stats, (unsigned) length);
345 } else {
346 error_setg(errp, "Invalid interval length: %s", str);
347 return false;
349 break;
352 case QTYPE_QNUM: {
353 int64_t length = qnum_get_int(qobject_to(QNum, entry->value));
355 if (length > 0 && length <= UINT_MAX) {
356 block_acct_add_interval(stats, (unsigned) length);
357 } else {
358 error_setg(errp, "Invalid interval length: %" PRId64, length);
359 return false;
361 break;
364 default:
365 error_setg(errp, "The specification of stats-intervals is invalid");
366 return false;
369 return true;
372 typedef enum { MEDIA_DISK, MEDIA_CDROM } DriveMediaType;
374 /* All parameters but @opts are optional and may be set to NULL. */
375 static void extract_common_blockdev_options(QemuOpts *opts, int *bdrv_flags,
376 const char **throttling_group, ThrottleConfig *throttle_cfg,
377 BlockdevDetectZeroesOptions *detect_zeroes, Error **errp)
379 Error *local_error = NULL;
380 const char *aio;
382 if (bdrv_flags) {
383 if (qemu_opt_get_bool(opts, "copy-on-read", false)) {
384 *bdrv_flags |= BDRV_O_COPY_ON_READ;
387 if ((aio = qemu_opt_get(opts, "aio")) != NULL) {
388 if (bdrv_parse_aio(aio, bdrv_flags) < 0) {
389 error_setg(errp, "invalid aio option");
390 return;
395 /* disk I/O throttling */
396 if (throttling_group) {
397 *throttling_group = qemu_opt_get(opts, "throttling.group");
400 if (throttle_cfg) {
401 throttle_config_init(throttle_cfg);
402 throttle_cfg->buckets[THROTTLE_BPS_TOTAL].avg =
403 qemu_opt_get_number(opts, "throttling.bps-total", 0);
404 throttle_cfg->buckets[THROTTLE_BPS_READ].avg =
405 qemu_opt_get_number(opts, "throttling.bps-read", 0);
406 throttle_cfg->buckets[THROTTLE_BPS_WRITE].avg =
407 qemu_opt_get_number(opts, "throttling.bps-write", 0);
408 throttle_cfg->buckets[THROTTLE_OPS_TOTAL].avg =
409 qemu_opt_get_number(opts, "throttling.iops-total", 0);
410 throttle_cfg->buckets[THROTTLE_OPS_READ].avg =
411 qemu_opt_get_number(opts, "throttling.iops-read", 0);
412 throttle_cfg->buckets[THROTTLE_OPS_WRITE].avg =
413 qemu_opt_get_number(opts, "throttling.iops-write", 0);
415 throttle_cfg->buckets[THROTTLE_BPS_TOTAL].max =
416 qemu_opt_get_number(opts, "throttling.bps-total-max", 0);
417 throttle_cfg->buckets[THROTTLE_BPS_READ].max =
418 qemu_opt_get_number(opts, "throttling.bps-read-max", 0);
419 throttle_cfg->buckets[THROTTLE_BPS_WRITE].max =
420 qemu_opt_get_number(opts, "throttling.bps-write-max", 0);
421 throttle_cfg->buckets[THROTTLE_OPS_TOTAL].max =
422 qemu_opt_get_number(opts, "throttling.iops-total-max", 0);
423 throttle_cfg->buckets[THROTTLE_OPS_READ].max =
424 qemu_opt_get_number(opts, "throttling.iops-read-max", 0);
425 throttle_cfg->buckets[THROTTLE_OPS_WRITE].max =
426 qemu_opt_get_number(opts, "throttling.iops-write-max", 0);
428 throttle_cfg->buckets[THROTTLE_BPS_TOTAL].burst_length =
429 qemu_opt_get_number(opts, "throttling.bps-total-max-length", 1);
430 throttle_cfg->buckets[THROTTLE_BPS_READ].burst_length =
431 qemu_opt_get_number(opts, "throttling.bps-read-max-length", 1);
432 throttle_cfg->buckets[THROTTLE_BPS_WRITE].burst_length =
433 qemu_opt_get_number(opts, "throttling.bps-write-max-length", 1);
434 throttle_cfg->buckets[THROTTLE_OPS_TOTAL].burst_length =
435 qemu_opt_get_number(opts, "throttling.iops-total-max-length", 1);
436 throttle_cfg->buckets[THROTTLE_OPS_READ].burst_length =
437 qemu_opt_get_number(opts, "throttling.iops-read-max-length", 1);
438 throttle_cfg->buckets[THROTTLE_OPS_WRITE].burst_length =
439 qemu_opt_get_number(opts, "throttling.iops-write-max-length", 1);
441 throttle_cfg->op_size =
442 qemu_opt_get_number(opts, "throttling.iops-size", 0);
444 if (!throttle_is_valid(throttle_cfg, errp)) {
445 return;
449 if (detect_zeroes) {
450 *detect_zeroes =
451 qapi_enum_parse(&BlockdevDetectZeroesOptions_lookup,
452 qemu_opt_get(opts, "detect-zeroes"),
453 BLOCKDEV_DETECT_ZEROES_OPTIONS_OFF,
454 &local_error);
455 if (local_error) {
456 error_propagate(errp, local_error);
457 return;
462 /* Takes the ownership of bs_opts */
463 static BlockBackend *blockdev_init(const char *file, QDict *bs_opts,
464 Error **errp)
466 const char *buf;
467 int bdrv_flags = 0;
468 int on_read_error, on_write_error;
469 bool account_invalid, account_failed;
470 bool writethrough, read_only;
471 BlockBackend *blk;
472 BlockDriverState *bs;
473 ThrottleConfig cfg;
474 int snapshot = 0;
475 Error *error = NULL;
476 QemuOpts *opts;
477 QDict *interval_dict = NULL;
478 QList *interval_list = NULL;
479 const char *id;
480 BlockdevDetectZeroesOptions detect_zeroes =
481 BLOCKDEV_DETECT_ZEROES_OPTIONS_OFF;
482 const char *throttling_group = NULL;
484 /* Check common options by copying from bs_opts to opts, all other options
485 * stay in bs_opts for processing by bdrv_open(). */
486 id = qdict_get_try_str(bs_opts, "id");
487 opts = qemu_opts_create(&qemu_common_drive_opts, id, 1, &error);
488 if (error) {
489 error_propagate(errp, error);
490 goto err_no_opts;
493 qemu_opts_absorb_qdict(opts, bs_opts, &error);
494 if (error) {
495 error_propagate(errp, error);
496 goto early_err;
499 if (id) {
500 qdict_del(bs_opts, "id");
503 /* extract parameters */
504 snapshot = qemu_opt_get_bool(opts, "snapshot", 0);
506 account_invalid = qemu_opt_get_bool(opts, "stats-account-invalid", true);
507 account_failed = qemu_opt_get_bool(opts, "stats-account-failed", true);
509 writethrough = !qemu_opt_get_bool(opts, BDRV_OPT_CACHE_WB, true);
511 id = qemu_opts_id(opts);
513 qdict_extract_subqdict(bs_opts, &interval_dict, "stats-intervals.");
514 qdict_array_split(interval_dict, &interval_list);
516 if (qdict_size(interval_dict) != 0) {
517 error_setg(errp, "Invalid option stats-intervals.%s",
518 qdict_first(interval_dict)->key);
519 goto early_err;
522 extract_common_blockdev_options(opts, &bdrv_flags, &throttling_group, &cfg,
523 &detect_zeroes, &error);
524 if (error) {
525 error_propagate(errp, error);
526 goto early_err;
529 if ((buf = qemu_opt_get(opts, "format")) != NULL) {
530 if (is_help_option(buf)) {
531 qemu_printf("Supported formats:");
532 bdrv_iterate_format(bdrv_format_print, NULL, false);
533 qemu_printf("\nSupported formats (read-only):");
534 bdrv_iterate_format(bdrv_format_print, NULL, true);
535 qemu_printf("\n");
536 goto early_err;
539 if (qdict_haskey(bs_opts, "driver")) {
540 error_setg(errp, "Cannot specify both 'driver' and 'format'");
541 goto early_err;
543 qdict_put_str(bs_opts, "driver", buf);
546 on_write_error = BLOCKDEV_ON_ERROR_ENOSPC;
547 if ((buf = qemu_opt_get(opts, "werror")) != NULL) {
548 on_write_error = parse_block_error_action(buf, 0, &error);
549 if (error) {
550 error_propagate(errp, error);
551 goto early_err;
555 on_read_error = BLOCKDEV_ON_ERROR_REPORT;
556 if ((buf = qemu_opt_get(opts, "rerror")) != NULL) {
557 on_read_error = parse_block_error_action(buf, 1, &error);
558 if (error) {
559 error_propagate(errp, error);
560 goto early_err;
564 if (snapshot) {
565 bdrv_flags |= BDRV_O_SNAPSHOT;
568 read_only = qemu_opt_get_bool(opts, BDRV_OPT_READ_ONLY, false);
570 /* init */
571 if ((!file || !*file) && !qdict_size(bs_opts)) {
572 BlockBackendRootState *blk_rs;
574 blk = blk_new(qemu_get_aio_context(), 0, BLK_PERM_ALL);
575 blk_rs = blk_get_root_state(blk);
576 blk_rs->open_flags = bdrv_flags;
577 blk_rs->read_only = read_only;
578 blk_rs->detect_zeroes = detect_zeroes;
580 qobject_unref(bs_opts);
581 } else {
582 if (file && !*file) {
583 file = NULL;
586 /* bdrv_open() defaults to the values in bdrv_flags (for compatibility
587 * with other callers) rather than what we want as the real defaults.
588 * Apply the defaults here instead. */
589 qdict_set_default_str(bs_opts, BDRV_OPT_CACHE_DIRECT, "off");
590 qdict_set_default_str(bs_opts, BDRV_OPT_CACHE_NO_FLUSH, "off");
591 qdict_set_default_str(bs_opts, BDRV_OPT_READ_ONLY,
592 read_only ? "on" : "off");
593 qdict_set_default_str(bs_opts, BDRV_OPT_AUTO_READ_ONLY, "on");
594 assert((bdrv_flags & BDRV_O_CACHE_MASK) == 0);
596 if (runstate_check(RUN_STATE_INMIGRATE)) {
597 bdrv_flags |= BDRV_O_INACTIVE;
600 blk = blk_new_open(file, NULL, bs_opts, bdrv_flags, errp);
601 if (!blk) {
602 goto err_no_bs_opts;
604 bs = blk_bs(blk);
606 bs->detect_zeroes = detect_zeroes;
608 block_acct_setup(blk_get_stats(blk), account_invalid, account_failed);
610 if (!parse_stats_intervals(blk_get_stats(blk), interval_list, errp)) {
611 blk_unref(blk);
612 blk = NULL;
613 goto err_no_bs_opts;
617 /* disk I/O throttling */
618 if (throttle_enabled(&cfg)) {
619 if (!throttling_group) {
620 throttling_group = id;
622 blk_io_limits_enable(blk, throttling_group);
623 blk_set_io_limits(blk, &cfg);
626 blk_set_enable_write_cache(blk, !writethrough);
627 blk_set_on_error(blk, on_read_error, on_write_error);
629 if (!monitor_add_blk(blk, id, errp)) {
630 blk_unref(blk);
631 blk = NULL;
632 goto err_no_bs_opts;
635 err_no_bs_opts:
636 qemu_opts_del(opts);
637 qobject_unref(interval_dict);
638 qobject_unref(interval_list);
639 return blk;
641 early_err:
642 qemu_opts_del(opts);
643 qobject_unref(interval_dict);
644 qobject_unref(interval_list);
645 err_no_opts:
646 qobject_unref(bs_opts);
647 return NULL;
650 /* Takes the ownership of bs_opts */
651 static BlockDriverState *bds_tree_init(QDict *bs_opts, Error **errp)
653 int bdrv_flags = 0;
655 /* bdrv_open() defaults to the values in bdrv_flags (for compatibility
656 * with other callers) rather than what we want as the real defaults.
657 * Apply the defaults here instead. */
658 qdict_set_default_str(bs_opts, BDRV_OPT_CACHE_DIRECT, "off");
659 qdict_set_default_str(bs_opts, BDRV_OPT_CACHE_NO_FLUSH, "off");
660 qdict_set_default_str(bs_opts, BDRV_OPT_READ_ONLY, "off");
662 if (runstate_check(RUN_STATE_INMIGRATE)) {
663 bdrv_flags |= BDRV_O_INACTIVE;
666 return bdrv_open(NULL, NULL, bs_opts, bdrv_flags, errp);
669 void blockdev_close_all_bdrv_states(void)
671 BlockDriverState *bs, *next_bs;
673 QTAILQ_FOREACH_SAFE(bs, &monitor_bdrv_states, monitor_list, next_bs) {
674 AioContext *ctx = bdrv_get_aio_context(bs);
676 aio_context_acquire(ctx);
677 bdrv_unref(bs);
678 aio_context_release(ctx);
682 /* Iterates over the list of monitor-owned BlockDriverStates */
683 BlockDriverState *bdrv_next_monitor_owned(BlockDriverState *bs)
685 return bs ? QTAILQ_NEXT(bs, monitor_list)
686 : QTAILQ_FIRST(&monitor_bdrv_states);
689 static void qemu_opt_rename(QemuOpts *opts, const char *from, const char *to,
690 Error **errp)
692 const char *value;
694 value = qemu_opt_get(opts, from);
695 if (value) {
696 if (qemu_opt_find(opts, to)) {
697 error_setg(errp, "'%s' and its alias '%s' can't be used at the "
698 "same time", to, from);
699 return;
703 /* rename all items in opts */
704 while ((value = qemu_opt_get(opts, from))) {
705 qemu_opt_set(opts, to, value, &error_abort);
706 qemu_opt_unset(opts, from);
710 QemuOptsList qemu_legacy_drive_opts = {
711 .name = "drive",
712 .head = QTAILQ_HEAD_INITIALIZER(qemu_legacy_drive_opts.head),
713 .desc = {
715 .name = "bus",
716 .type = QEMU_OPT_NUMBER,
717 .help = "bus number",
719 .name = "unit",
720 .type = QEMU_OPT_NUMBER,
721 .help = "unit number (i.e. lun for scsi)",
723 .name = "index",
724 .type = QEMU_OPT_NUMBER,
725 .help = "index number",
727 .name = "media",
728 .type = QEMU_OPT_STRING,
729 .help = "media type (disk, cdrom)",
731 .name = "if",
732 .type = QEMU_OPT_STRING,
733 .help = "interface (ide, scsi, sd, mtd, floppy, pflash, virtio)",
735 .name = "file",
736 .type = QEMU_OPT_STRING,
737 .help = "file name",
740 /* Options that are passed on, but have special semantics with -drive */
742 .name = BDRV_OPT_READ_ONLY,
743 .type = QEMU_OPT_BOOL,
744 .help = "open drive file as read-only",
746 .name = "rerror",
747 .type = QEMU_OPT_STRING,
748 .help = "read error action",
750 .name = "werror",
751 .type = QEMU_OPT_STRING,
752 .help = "write error action",
754 .name = "copy-on-read",
755 .type = QEMU_OPT_BOOL,
756 .help = "copy read data from backing file into image file",
759 { /* end of list */ }
763 DriveInfo *drive_new(QemuOpts *all_opts, BlockInterfaceType block_default_type,
764 Error **errp)
766 const char *value;
767 BlockBackend *blk;
768 DriveInfo *dinfo = NULL;
769 QDict *bs_opts;
770 QemuOpts *legacy_opts;
771 DriveMediaType media = MEDIA_DISK;
772 BlockInterfaceType type;
773 int max_devs, bus_id, unit_id, index;
774 const char *werror, *rerror;
775 bool read_only = false;
776 bool copy_on_read;
777 const char *filename;
778 Error *local_err = NULL;
779 int i;
781 /* Change legacy command line options into QMP ones */
782 static const struct {
783 const char *from;
784 const char *to;
785 } opt_renames[] = {
786 { "iops", "throttling.iops-total" },
787 { "iops_rd", "throttling.iops-read" },
788 { "iops_wr", "throttling.iops-write" },
790 { "bps", "throttling.bps-total" },
791 { "bps_rd", "throttling.bps-read" },
792 { "bps_wr", "throttling.bps-write" },
794 { "iops_max", "throttling.iops-total-max" },
795 { "iops_rd_max", "throttling.iops-read-max" },
796 { "iops_wr_max", "throttling.iops-write-max" },
798 { "bps_max", "throttling.bps-total-max" },
799 { "bps_rd_max", "throttling.bps-read-max" },
800 { "bps_wr_max", "throttling.bps-write-max" },
802 { "iops_size", "throttling.iops-size" },
804 { "group", "throttling.group" },
806 { "readonly", BDRV_OPT_READ_ONLY },
809 for (i = 0; i < ARRAY_SIZE(opt_renames); i++) {
810 qemu_opt_rename(all_opts, opt_renames[i].from, opt_renames[i].to,
811 &local_err);
812 if (local_err) {
813 error_propagate(errp, local_err);
814 return NULL;
818 value = qemu_opt_get(all_opts, "cache");
819 if (value) {
820 int flags = 0;
821 bool writethrough;
823 if (bdrv_parse_cache_mode(value, &flags, &writethrough) != 0) {
824 error_setg(errp, "invalid cache option");
825 return NULL;
828 /* Specific options take precedence */
829 if (!qemu_opt_get(all_opts, BDRV_OPT_CACHE_WB)) {
830 qemu_opt_set_bool(all_opts, BDRV_OPT_CACHE_WB,
831 !writethrough, &error_abort);
833 if (!qemu_opt_get(all_opts, BDRV_OPT_CACHE_DIRECT)) {
834 qemu_opt_set_bool(all_opts, BDRV_OPT_CACHE_DIRECT,
835 !!(flags & BDRV_O_NOCACHE), &error_abort);
837 if (!qemu_opt_get(all_opts, BDRV_OPT_CACHE_NO_FLUSH)) {
838 qemu_opt_set_bool(all_opts, BDRV_OPT_CACHE_NO_FLUSH,
839 !!(flags & BDRV_O_NO_FLUSH), &error_abort);
841 qemu_opt_unset(all_opts, "cache");
844 /* Get a QDict for processing the options */
845 bs_opts = qdict_new();
846 qemu_opts_to_qdict(all_opts, bs_opts);
848 legacy_opts = qemu_opts_create(&qemu_legacy_drive_opts, NULL, 0,
849 &error_abort);
850 qemu_opts_absorb_qdict(legacy_opts, bs_opts, &local_err);
851 if (local_err) {
852 error_propagate(errp, local_err);
853 goto fail;
856 /* Media type */
857 value = qemu_opt_get(legacy_opts, "media");
858 if (value) {
859 if (!strcmp(value, "disk")) {
860 media = MEDIA_DISK;
861 } else if (!strcmp(value, "cdrom")) {
862 media = MEDIA_CDROM;
863 read_only = true;
864 } else {
865 error_setg(errp, "'%s' invalid media", value);
866 goto fail;
870 /* copy-on-read is disabled with a warning for read-only devices */
871 read_only |= qemu_opt_get_bool(legacy_opts, BDRV_OPT_READ_ONLY, false);
872 copy_on_read = qemu_opt_get_bool(legacy_opts, "copy-on-read", false);
874 if (read_only && copy_on_read) {
875 warn_report("disabling copy-on-read on read-only drive");
876 copy_on_read = false;
879 qdict_put_str(bs_opts, BDRV_OPT_READ_ONLY, read_only ? "on" : "off");
880 qdict_put_str(bs_opts, "copy-on-read", copy_on_read ? "on" : "off");
882 /* Controller type */
883 value = qemu_opt_get(legacy_opts, "if");
884 if (value) {
885 for (type = 0;
886 type < IF_COUNT && strcmp(value, if_name[type]);
887 type++) {
889 if (type == IF_COUNT) {
890 error_setg(errp, "unsupported bus type '%s'", value);
891 goto fail;
893 } else {
894 type = block_default_type;
897 /* Device address specified by bus/unit or index.
898 * If none was specified, try to find the first free one. */
899 bus_id = qemu_opt_get_number(legacy_opts, "bus", 0);
900 unit_id = qemu_opt_get_number(legacy_opts, "unit", -1);
901 index = qemu_opt_get_number(legacy_opts, "index", -1);
903 max_devs = if_max_devs[type];
905 if (index != -1) {
906 if (bus_id != 0 || unit_id != -1) {
907 error_setg(errp, "index cannot be used with bus and unit");
908 goto fail;
910 bus_id = drive_index_to_bus_id(type, index);
911 unit_id = drive_index_to_unit_id(type, index);
914 if (unit_id == -1) {
915 unit_id = 0;
916 while (drive_get(type, bus_id, unit_id) != NULL) {
917 unit_id++;
918 if (max_devs && unit_id >= max_devs) {
919 unit_id -= max_devs;
920 bus_id++;
925 if (max_devs && unit_id >= max_devs) {
926 error_setg(errp, "unit %d too big (max is %d)", unit_id, max_devs - 1);
927 goto fail;
930 if (drive_get(type, bus_id, unit_id) != NULL) {
931 error_setg(errp, "drive with bus=%d, unit=%d (index=%d) exists",
932 bus_id, unit_id, index);
933 goto fail;
936 /* no id supplied -> create one */
937 if (qemu_opts_id(all_opts) == NULL) {
938 char *new_id;
939 const char *mediastr = "";
940 if (type == IF_IDE || type == IF_SCSI) {
941 mediastr = (media == MEDIA_CDROM) ? "-cd" : "-hd";
943 if (max_devs) {
944 new_id = g_strdup_printf("%s%i%s%i", if_name[type], bus_id,
945 mediastr, unit_id);
946 } else {
947 new_id = g_strdup_printf("%s%s%i", if_name[type],
948 mediastr, unit_id);
950 qdict_put_str(bs_opts, "id", new_id);
951 g_free(new_id);
954 /* Add virtio block device */
955 if (type == IF_VIRTIO) {
956 QemuOpts *devopts;
957 devopts = qemu_opts_create(qemu_find_opts("device"), NULL, 0,
958 &error_abort);
959 if (arch_type == QEMU_ARCH_S390X) {
960 qemu_opt_set(devopts, "driver", "virtio-blk-ccw", &error_abort);
961 } else {
962 qemu_opt_set(devopts, "driver", "virtio-blk-pci", &error_abort);
964 qemu_opt_set(devopts, "drive", qdict_get_str(bs_opts, "id"),
965 &error_abort);
968 filename = qemu_opt_get(legacy_opts, "file");
970 /* Check werror/rerror compatibility with if=... */
971 werror = qemu_opt_get(legacy_opts, "werror");
972 if (werror != NULL) {
973 if (type != IF_IDE && type != IF_SCSI && type != IF_VIRTIO &&
974 type != IF_NONE) {
975 error_setg(errp, "werror is not supported by this bus type");
976 goto fail;
978 qdict_put_str(bs_opts, "werror", werror);
981 rerror = qemu_opt_get(legacy_opts, "rerror");
982 if (rerror != NULL) {
983 if (type != IF_IDE && type != IF_VIRTIO && type != IF_SCSI &&
984 type != IF_NONE) {
985 error_setg(errp, "rerror is not supported by this bus type");
986 goto fail;
988 qdict_put_str(bs_opts, "rerror", rerror);
991 /* Actual block device init: Functionality shared with blockdev-add */
992 blk = blockdev_init(filename, bs_opts, &local_err);
993 bs_opts = NULL;
994 if (!blk) {
995 error_propagate(errp, local_err);
996 goto fail;
997 } else {
998 assert(!local_err);
1001 /* Create legacy DriveInfo */
1002 dinfo = g_malloc0(sizeof(*dinfo));
1003 dinfo->opts = all_opts;
1005 dinfo->type = type;
1006 dinfo->bus = bus_id;
1007 dinfo->unit = unit_id;
1009 blk_set_legacy_dinfo(blk, dinfo);
1011 switch(type) {
1012 case IF_IDE:
1013 case IF_SCSI:
1014 case IF_XEN:
1015 case IF_NONE:
1016 dinfo->media_cd = media == MEDIA_CDROM;
1017 break;
1018 default:
1019 break;
1022 fail:
1023 qemu_opts_del(legacy_opts);
1024 qobject_unref(bs_opts);
1025 return dinfo;
1028 static BlockDriverState *qmp_get_root_bs(const char *name, Error **errp)
1030 BlockDriverState *bs;
1032 bs = bdrv_lookup_bs(name, name, errp);
1033 if (bs == NULL) {
1034 return NULL;
1037 if (!bdrv_is_root_node(bs)) {
1038 error_setg(errp, "Need a root block node");
1039 return NULL;
1042 if (!bdrv_is_inserted(bs)) {
1043 error_setg(errp, "Device has no medium");
1044 return NULL;
1047 return bs;
1050 static BlockBackend *qmp_get_blk(const char *blk_name, const char *qdev_id,
1051 Error **errp)
1053 BlockBackend *blk;
1055 if (!blk_name == !qdev_id) {
1056 error_setg(errp, "Need exactly one of 'device' and 'id'");
1057 return NULL;
1060 if (qdev_id) {
1061 blk = blk_by_qdev_id(qdev_id, errp);
1062 } else {
1063 blk = blk_by_name(blk_name);
1064 if (blk == NULL) {
1065 error_set(errp, ERROR_CLASS_DEVICE_NOT_FOUND,
1066 "Device '%s' not found", blk_name);
1070 return blk;
1073 void hmp_commit(Monitor *mon, const QDict *qdict)
1075 const char *device = qdict_get_str(qdict, "device");
1076 BlockBackend *blk;
1077 int ret;
1079 if (!strcmp(device, "all")) {
1080 ret = blk_commit_all();
1081 } else {
1082 BlockDriverState *bs;
1083 AioContext *aio_context;
1085 blk = blk_by_name(device);
1086 if (!blk) {
1087 error_report("Device '%s' not found", device);
1088 return;
1090 if (!blk_is_available(blk)) {
1091 error_report("Device '%s' has no medium", device);
1092 return;
1095 bs = blk_bs(blk);
1096 aio_context = bdrv_get_aio_context(bs);
1097 aio_context_acquire(aio_context);
1099 ret = bdrv_commit(bs);
1101 aio_context_release(aio_context);
1103 if (ret < 0) {
1104 error_report("'commit' error for '%s': %s", device, strerror(-ret));
1108 static void blockdev_do_action(TransactionAction *action, Error **errp)
1110 TransactionActionList list;
1112 list.value = action;
1113 list.next = NULL;
1114 qmp_transaction(&list, false, NULL, errp);
1117 void qmp_blockdev_snapshot_sync(bool has_device, const char *device,
1118 bool has_node_name, const char *node_name,
1119 const char *snapshot_file,
1120 bool has_snapshot_node_name,
1121 const char *snapshot_node_name,
1122 bool has_format, const char *format,
1123 bool has_mode, NewImageMode mode, Error **errp)
1125 BlockdevSnapshotSync snapshot = {
1126 .has_device = has_device,
1127 .device = (char *) device,
1128 .has_node_name = has_node_name,
1129 .node_name = (char *) node_name,
1130 .snapshot_file = (char *) snapshot_file,
1131 .has_snapshot_node_name = has_snapshot_node_name,
1132 .snapshot_node_name = (char *) snapshot_node_name,
1133 .has_format = has_format,
1134 .format = (char *) format,
1135 .has_mode = has_mode,
1136 .mode = mode,
1138 TransactionAction action = {
1139 .type = TRANSACTION_ACTION_KIND_BLOCKDEV_SNAPSHOT_SYNC,
1140 .u.blockdev_snapshot_sync.data = &snapshot,
1142 blockdev_do_action(&action, errp);
1145 void qmp_blockdev_snapshot(const char *node, const char *overlay,
1146 Error **errp)
1148 BlockdevSnapshot snapshot_data = {
1149 .node = (char *) node,
1150 .overlay = (char *) overlay
1152 TransactionAction action = {
1153 .type = TRANSACTION_ACTION_KIND_BLOCKDEV_SNAPSHOT,
1154 .u.blockdev_snapshot.data = &snapshot_data,
1156 blockdev_do_action(&action, errp);
1159 void qmp_blockdev_snapshot_internal_sync(const char *device,
1160 const char *name,
1161 Error **errp)
1163 BlockdevSnapshotInternal snapshot = {
1164 .device = (char *) device,
1165 .name = (char *) name
1167 TransactionAction action = {
1168 .type = TRANSACTION_ACTION_KIND_BLOCKDEV_SNAPSHOT_INTERNAL_SYNC,
1169 .u.blockdev_snapshot_internal_sync.data = &snapshot,
1171 blockdev_do_action(&action, errp);
1174 SnapshotInfo *qmp_blockdev_snapshot_delete_internal_sync(const char *device,
1175 bool has_id,
1176 const char *id,
1177 bool has_name,
1178 const char *name,
1179 Error **errp)
1181 BlockDriverState *bs;
1182 AioContext *aio_context;
1183 QEMUSnapshotInfo sn;
1184 Error *local_err = NULL;
1185 SnapshotInfo *info = NULL;
1186 int ret;
1188 bs = qmp_get_root_bs(device, errp);
1189 if (!bs) {
1190 return NULL;
1192 aio_context = bdrv_get_aio_context(bs);
1193 aio_context_acquire(aio_context);
1195 if (!has_id) {
1196 id = NULL;
1199 if (!has_name) {
1200 name = NULL;
1203 if (!id && !name) {
1204 error_setg(errp, "Name or id must be provided");
1205 goto out_aio_context;
1208 if (bdrv_op_is_blocked(bs, BLOCK_OP_TYPE_INTERNAL_SNAPSHOT_DELETE, errp)) {
1209 goto out_aio_context;
1212 ret = bdrv_snapshot_find_by_id_and_name(bs, id, name, &sn, &local_err);
1213 if (local_err) {
1214 error_propagate(errp, local_err);
1215 goto out_aio_context;
1217 if (!ret) {
1218 error_setg(errp,
1219 "Snapshot with id '%s' and name '%s' does not exist on "
1220 "device '%s'",
1221 STR_OR_NULL(id), STR_OR_NULL(name), device);
1222 goto out_aio_context;
1225 bdrv_snapshot_delete(bs, id, name, &local_err);
1226 if (local_err) {
1227 error_propagate(errp, local_err);
1228 goto out_aio_context;
1231 aio_context_release(aio_context);
1233 info = g_new0(SnapshotInfo, 1);
1234 info->id = g_strdup(sn.id_str);
1235 info->name = g_strdup(sn.name);
1236 info->date_nsec = sn.date_nsec;
1237 info->date_sec = sn.date_sec;
1238 info->vm_state_size = sn.vm_state_size;
1239 info->vm_clock_nsec = sn.vm_clock_nsec % 1000000000;
1240 info->vm_clock_sec = sn.vm_clock_nsec / 1000000000;
1242 return info;
1244 out_aio_context:
1245 aio_context_release(aio_context);
1246 return NULL;
1250 * block_dirty_bitmap_lookup:
1251 * Return a dirty bitmap (if present), after validating
1252 * the node reference and bitmap names.
1254 * @node: The name of the BDS node to search for bitmaps
1255 * @name: The name of the bitmap to search for
1256 * @pbs: Output pointer for BDS lookup, if desired. Can be NULL.
1257 * @errp: Output pointer for error information. Can be NULL.
1259 * @return: A bitmap object on success, or NULL on failure.
1261 static BdrvDirtyBitmap *block_dirty_bitmap_lookup(const char *node,
1262 const char *name,
1263 BlockDriverState **pbs,
1264 Error **errp)
1266 BlockDriverState *bs;
1267 BdrvDirtyBitmap *bitmap;
1269 if (!node) {
1270 error_setg(errp, "Node cannot be NULL");
1271 return NULL;
1273 if (!name) {
1274 error_setg(errp, "Bitmap name cannot be NULL");
1275 return NULL;
1277 bs = bdrv_lookup_bs(node, node, NULL);
1278 if (!bs) {
1279 error_setg(errp, "Node '%s' not found", node);
1280 return NULL;
1283 bitmap = bdrv_find_dirty_bitmap(bs, name);
1284 if (!bitmap) {
1285 error_setg(errp, "Dirty bitmap '%s' not found", name);
1286 return NULL;
1289 if (pbs) {
1290 *pbs = bs;
1293 return bitmap;
1296 /* New and old BlockDriverState structs for atomic group operations */
1298 typedef struct BlkActionState BlkActionState;
1301 * BlkActionOps:
1302 * Table of operations that define an Action.
1304 * @instance_size: Size of state struct, in bytes.
1305 * @prepare: Prepare the work, must NOT be NULL.
1306 * @commit: Commit the changes, can be NULL.
1307 * @abort: Abort the changes on fail, can be NULL.
1308 * @clean: Clean up resources after all transaction actions have called
1309 * commit() or abort(). Can be NULL.
1311 * Only prepare() may fail. In a single transaction, only one of commit() or
1312 * abort() will be called. clean() will always be called if it is present.
1314 typedef struct BlkActionOps {
1315 size_t instance_size;
1316 void (*prepare)(BlkActionState *common, Error **errp);
1317 void (*commit)(BlkActionState *common);
1318 void (*abort)(BlkActionState *common);
1319 void (*clean)(BlkActionState *common);
1320 } BlkActionOps;
1323 * BlkActionState:
1324 * Describes one Action's state within a Transaction.
1326 * @action: QAPI-defined enum identifying which Action to perform.
1327 * @ops: Table of ActionOps this Action can perform.
1328 * @block_job_txn: Transaction which this action belongs to.
1329 * @entry: List membership for all Actions in this Transaction.
1331 * This structure must be arranged as first member in a subclassed type,
1332 * assuming that the compiler will also arrange it to the same offsets as the
1333 * base class.
1335 struct BlkActionState {
1336 TransactionAction *action;
1337 const BlkActionOps *ops;
1338 JobTxn *block_job_txn;
1339 TransactionProperties *txn_props;
1340 QTAILQ_ENTRY(BlkActionState) entry;
1343 /* internal snapshot private data */
1344 typedef struct InternalSnapshotState {
1345 BlkActionState common;
1346 BlockDriverState *bs;
1347 QEMUSnapshotInfo sn;
1348 bool created;
1349 } InternalSnapshotState;
1352 static int action_check_completion_mode(BlkActionState *s, Error **errp)
1354 if (s->txn_props->completion_mode != ACTION_COMPLETION_MODE_INDIVIDUAL) {
1355 error_setg(errp,
1356 "Action '%s' does not support Transaction property "
1357 "completion-mode = %s",
1358 TransactionActionKind_str(s->action->type),
1359 ActionCompletionMode_str(s->txn_props->completion_mode));
1360 return -1;
1362 return 0;
1365 static void internal_snapshot_prepare(BlkActionState *common,
1366 Error **errp)
1368 Error *local_err = NULL;
1369 const char *device;
1370 const char *name;
1371 BlockDriverState *bs;
1372 QEMUSnapshotInfo old_sn, *sn;
1373 bool ret;
1374 qemu_timeval tv;
1375 BlockdevSnapshotInternal *internal;
1376 InternalSnapshotState *state;
1377 AioContext *aio_context;
1378 int ret1;
1380 g_assert(common->action->type ==
1381 TRANSACTION_ACTION_KIND_BLOCKDEV_SNAPSHOT_INTERNAL_SYNC);
1382 internal = common->action->u.blockdev_snapshot_internal_sync.data;
1383 state = DO_UPCAST(InternalSnapshotState, common, common);
1385 /* 1. parse input */
1386 device = internal->device;
1387 name = internal->name;
1389 /* 2. check for validation */
1390 if (action_check_completion_mode(common, errp) < 0) {
1391 return;
1394 bs = qmp_get_root_bs(device, errp);
1395 if (!bs) {
1396 return;
1399 aio_context = bdrv_get_aio_context(bs);
1400 aio_context_acquire(aio_context);
1402 state->bs = bs;
1404 /* Paired with .clean() */
1405 bdrv_drained_begin(bs);
1407 if (bdrv_op_is_blocked(bs, BLOCK_OP_TYPE_INTERNAL_SNAPSHOT, errp)) {
1408 goto out;
1411 if (bdrv_is_read_only(bs)) {
1412 error_setg(errp, "Device '%s' is read only", device);
1413 goto out;
1416 if (!bdrv_can_snapshot(bs)) {
1417 error_setg(errp, "Block format '%s' used by device '%s' "
1418 "does not support internal snapshots",
1419 bs->drv->format_name, device);
1420 goto out;
1423 if (!strlen(name)) {
1424 error_setg(errp, "Name is empty");
1425 goto out;
1428 /* check whether a snapshot with name exist */
1429 ret = bdrv_snapshot_find_by_id_and_name(bs, NULL, name, &old_sn,
1430 &local_err);
1431 if (local_err) {
1432 error_propagate(errp, local_err);
1433 goto out;
1434 } else if (ret) {
1435 error_setg(errp,
1436 "Snapshot with name '%s' already exists on device '%s'",
1437 name, device);
1438 goto out;
1441 /* 3. take the snapshot */
1442 sn = &state->sn;
1443 pstrcpy(sn->name, sizeof(sn->name), name);
1444 qemu_gettimeofday(&tv);
1445 sn->date_sec = tv.tv_sec;
1446 sn->date_nsec = tv.tv_usec * 1000;
1447 sn->vm_clock_nsec = qemu_clock_get_ns(QEMU_CLOCK_VIRTUAL);
1449 ret1 = bdrv_snapshot_create(bs, sn);
1450 if (ret1 < 0) {
1451 error_setg_errno(errp, -ret1,
1452 "Failed to create snapshot '%s' on device '%s'",
1453 name, device);
1454 goto out;
1457 /* 4. succeed, mark a snapshot is created */
1458 state->created = true;
1460 out:
1461 aio_context_release(aio_context);
1464 static void internal_snapshot_abort(BlkActionState *common)
1466 InternalSnapshotState *state =
1467 DO_UPCAST(InternalSnapshotState, common, common);
1468 BlockDriverState *bs = state->bs;
1469 QEMUSnapshotInfo *sn = &state->sn;
1470 AioContext *aio_context;
1471 Error *local_error = NULL;
1473 if (!state->created) {
1474 return;
1477 aio_context = bdrv_get_aio_context(state->bs);
1478 aio_context_acquire(aio_context);
1480 if (bdrv_snapshot_delete(bs, sn->id_str, sn->name, &local_error) < 0) {
1481 error_reportf_err(local_error,
1482 "Failed to delete snapshot with id '%s' and "
1483 "name '%s' on device '%s' in abort: ",
1484 sn->id_str, sn->name,
1485 bdrv_get_device_name(bs));
1488 aio_context_release(aio_context);
1491 static void internal_snapshot_clean(BlkActionState *common)
1493 InternalSnapshotState *state = DO_UPCAST(InternalSnapshotState,
1494 common, common);
1495 AioContext *aio_context;
1497 if (!state->bs) {
1498 return;
1501 aio_context = bdrv_get_aio_context(state->bs);
1502 aio_context_acquire(aio_context);
1504 bdrv_drained_end(state->bs);
1506 aio_context_release(aio_context);
1509 /* external snapshot private data */
1510 typedef struct ExternalSnapshotState {
1511 BlkActionState common;
1512 BlockDriverState *old_bs;
1513 BlockDriverState *new_bs;
1514 bool overlay_appended;
1515 } ExternalSnapshotState;
1517 static void external_snapshot_prepare(BlkActionState *common,
1518 Error **errp)
1520 int flags = 0;
1521 QDict *options = NULL;
1522 Error *local_err = NULL;
1523 /* Device and node name of the image to generate the snapshot from */
1524 const char *device;
1525 const char *node_name;
1526 /* Reference to the new image (for 'blockdev-snapshot') */
1527 const char *snapshot_ref;
1528 /* File name of the new image (for 'blockdev-snapshot-sync') */
1529 const char *new_image_file;
1530 ExternalSnapshotState *state =
1531 DO_UPCAST(ExternalSnapshotState, common, common);
1532 TransactionAction *action = common->action;
1533 AioContext *aio_context;
1534 AioContext *old_context;
1535 int ret;
1537 /* 'blockdev-snapshot' and 'blockdev-snapshot-sync' have similar
1538 * purpose but a different set of parameters */
1539 switch (action->type) {
1540 case TRANSACTION_ACTION_KIND_BLOCKDEV_SNAPSHOT:
1542 BlockdevSnapshot *s = action->u.blockdev_snapshot.data;
1543 device = s->node;
1544 node_name = s->node;
1545 new_image_file = NULL;
1546 snapshot_ref = s->overlay;
1548 break;
1549 case TRANSACTION_ACTION_KIND_BLOCKDEV_SNAPSHOT_SYNC:
1551 BlockdevSnapshotSync *s = action->u.blockdev_snapshot_sync.data;
1552 device = s->has_device ? s->device : NULL;
1553 node_name = s->has_node_name ? s->node_name : NULL;
1554 new_image_file = s->snapshot_file;
1555 snapshot_ref = NULL;
1557 break;
1558 default:
1559 g_assert_not_reached();
1562 /* start processing */
1563 if (action_check_completion_mode(common, errp) < 0) {
1564 return;
1567 state->old_bs = bdrv_lookup_bs(device, node_name, errp);
1568 if (!state->old_bs) {
1569 return;
1572 aio_context = bdrv_get_aio_context(state->old_bs);
1573 aio_context_acquire(aio_context);
1575 /* Paired with .clean() */
1576 bdrv_drained_begin(state->old_bs);
1578 if (!bdrv_is_inserted(state->old_bs)) {
1579 error_setg(errp, QERR_DEVICE_HAS_NO_MEDIUM, device);
1580 goto out;
1583 if (bdrv_op_is_blocked(state->old_bs,
1584 BLOCK_OP_TYPE_EXTERNAL_SNAPSHOT, errp)) {
1585 goto out;
1588 if (!bdrv_is_read_only(state->old_bs)) {
1589 if (bdrv_flush(state->old_bs)) {
1590 error_setg(errp, QERR_IO_ERROR);
1591 goto out;
1595 if (action->type == TRANSACTION_ACTION_KIND_BLOCKDEV_SNAPSHOT_SYNC) {
1596 BlockdevSnapshotSync *s = action->u.blockdev_snapshot_sync.data;
1597 const char *format = s->has_format ? s->format : "qcow2";
1598 enum NewImageMode mode;
1599 const char *snapshot_node_name =
1600 s->has_snapshot_node_name ? s->snapshot_node_name : NULL;
1602 if (node_name && !snapshot_node_name) {
1603 error_setg(errp, "New overlay node name missing");
1604 goto out;
1607 if (snapshot_node_name &&
1608 bdrv_lookup_bs(snapshot_node_name, snapshot_node_name, NULL)) {
1609 error_setg(errp, "New overlay node name already in use");
1610 goto out;
1613 flags = state->old_bs->open_flags;
1614 flags &= ~(BDRV_O_SNAPSHOT | BDRV_O_COPY_ON_READ);
1615 flags |= BDRV_O_NO_BACKING;
1617 /* create new image w/backing file */
1618 mode = s->has_mode ? s->mode : NEW_IMAGE_MODE_ABSOLUTE_PATHS;
1619 if (mode != NEW_IMAGE_MODE_EXISTING) {
1620 int64_t size = bdrv_getlength(state->old_bs);
1621 if (size < 0) {
1622 error_setg_errno(errp, -size, "bdrv_getlength failed");
1623 goto out;
1625 bdrv_refresh_filename(state->old_bs);
1626 bdrv_img_create(new_image_file, format,
1627 state->old_bs->filename,
1628 state->old_bs->drv->format_name,
1629 NULL, size, flags, false, &local_err);
1630 if (local_err) {
1631 error_propagate(errp, local_err);
1632 goto out;
1636 options = qdict_new();
1637 if (snapshot_node_name) {
1638 qdict_put_str(options, "node-name", snapshot_node_name);
1640 qdict_put_str(options, "driver", format);
1643 state->new_bs = bdrv_open(new_image_file, snapshot_ref, options, flags,
1644 errp);
1645 /* We will manually add the backing_hd field to the bs later */
1646 if (!state->new_bs) {
1647 goto out;
1650 if (bdrv_has_blk(state->new_bs)) {
1651 error_setg(errp, "The overlay is already in use");
1652 goto out;
1655 if (bdrv_op_is_blocked(state->new_bs, BLOCK_OP_TYPE_EXTERNAL_SNAPSHOT,
1656 errp)) {
1657 goto out;
1660 if (state->new_bs->backing != NULL) {
1661 error_setg(errp, "The overlay already has a backing image");
1662 goto out;
1665 if (!state->new_bs->drv->supports_backing) {
1666 error_setg(errp, "The overlay does not support backing images");
1667 goto out;
1670 /* Honor bdrv_try_set_aio_context() context acquisition requirements. */
1671 old_context = bdrv_get_aio_context(state->new_bs);
1672 aio_context_release(aio_context);
1673 aio_context_acquire(old_context);
1675 ret = bdrv_try_set_aio_context(state->new_bs, aio_context, errp);
1677 aio_context_release(old_context);
1678 aio_context_acquire(aio_context);
1680 if (ret < 0) {
1681 goto out;
1684 /* This removes our old bs and adds the new bs. This is an operation that
1685 * can fail, so we need to do it in .prepare; undoing it for abort is
1686 * always possible. */
1687 bdrv_ref(state->new_bs);
1688 bdrv_append(state->new_bs, state->old_bs, &local_err);
1689 if (local_err) {
1690 error_propagate(errp, local_err);
1691 goto out;
1693 state->overlay_appended = true;
1695 out:
1696 aio_context_release(aio_context);
1699 static void external_snapshot_commit(BlkActionState *common)
1701 ExternalSnapshotState *state =
1702 DO_UPCAST(ExternalSnapshotState, common, common);
1703 AioContext *aio_context;
1705 aio_context = bdrv_get_aio_context(state->old_bs);
1706 aio_context_acquire(aio_context);
1708 /* We don't need (or want) to use the transactional
1709 * bdrv_reopen_multiple() across all the entries at once, because we
1710 * don't want to abort all of them if one of them fails the reopen */
1711 if (!atomic_read(&state->old_bs->copy_on_read)) {
1712 bdrv_reopen_set_read_only(state->old_bs, true, NULL);
1715 aio_context_release(aio_context);
1718 static void external_snapshot_abort(BlkActionState *common)
1720 ExternalSnapshotState *state =
1721 DO_UPCAST(ExternalSnapshotState, common, common);
1722 if (state->new_bs) {
1723 if (state->overlay_appended) {
1724 AioContext *aio_context;
1725 AioContext *tmp_context;
1726 int ret;
1728 aio_context = bdrv_get_aio_context(state->old_bs);
1729 aio_context_acquire(aio_context);
1731 bdrv_ref(state->old_bs); /* we can't let bdrv_set_backind_hd()
1732 close state->old_bs; we need it */
1733 bdrv_set_backing_hd(state->new_bs, NULL, &error_abort);
1736 * The call to bdrv_set_backing_hd() above returns state->old_bs to
1737 * the main AioContext. As we're still going to be using it, return
1738 * it to the AioContext it was before.
1740 tmp_context = bdrv_get_aio_context(state->old_bs);
1741 if (aio_context != tmp_context) {
1742 aio_context_release(aio_context);
1743 aio_context_acquire(tmp_context);
1745 ret = bdrv_try_set_aio_context(state->old_bs,
1746 aio_context, NULL);
1747 assert(ret == 0);
1749 aio_context_release(tmp_context);
1750 aio_context_acquire(aio_context);
1753 bdrv_replace_node(state->new_bs, state->old_bs, &error_abort);
1754 bdrv_unref(state->old_bs); /* bdrv_replace_node() ref'ed old_bs */
1756 aio_context_release(aio_context);
1761 static void external_snapshot_clean(BlkActionState *common)
1763 ExternalSnapshotState *state =
1764 DO_UPCAST(ExternalSnapshotState, common, common);
1765 AioContext *aio_context;
1767 if (!state->old_bs) {
1768 return;
1771 aio_context = bdrv_get_aio_context(state->old_bs);
1772 aio_context_acquire(aio_context);
1774 bdrv_drained_end(state->old_bs);
1775 bdrv_unref(state->new_bs);
1777 aio_context_release(aio_context);
1780 typedef struct DriveBackupState {
1781 BlkActionState common;
1782 BlockDriverState *bs;
1783 BlockJob *job;
1784 } DriveBackupState;
1786 static BlockJob *do_backup_common(BackupCommon *backup,
1787 BlockDriverState *bs,
1788 BlockDriverState *target_bs,
1789 AioContext *aio_context,
1790 JobTxn *txn, Error **errp);
1792 static void drive_backup_prepare(BlkActionState *common, Error **errp)
1794 DriveBackupState *state = DO_UPCAST(DriveBackupState, common, common);
1795 DriveBackup *backup;
1796 BlockDriverState *bs;
1797 BlockDriverState *target_bs;
1798 BlockDriverState *source = NULL;
1799 AioContext *aio_context;
1800 AioContext *old_context;
1801 QDict *options;
1802 Error *local_err = NULL;
1803 int flags;
1804 int64_t size;
1805 bool set_backing_hd = false;
1806 int ret;
1808 assert(common->action->type == TRANSACTION_ACTION_KIND_DRIVE_BACKUP);
1809 backup = common->action->u.drive_backup.data;
1811 if (!backup->has_mode) {
1812 backup->mode = NEW_IMAGE_MODE_ABSOLUTE_PATHS;
1815 bs = bdrv_lookup_bs(backup->device, backup->device, errp);
1816 if (!bs) {
1817 return;
1820 if (!bs->drv) {
1821 error_setg(errp, "Device has no medium");
1822 return;
1825 aio_context = bdrv_get_aio_context(bs);
1826 aio_context_acquire(aio_context);
1828 /* Paired with .clean() */
1829 bdrv_drained_begin(bs);
1831 if (!backup->has_format) {
1832 backup->format = backup->mode == NEW_IMAGE_MODE_EXISTING ?
1833 NULL : (char *) bs->drv->format_name;
1836 /* Early check to avoid creating target */
1837 if (bdrv_op_is_blocked(bs, BLOCK_OP_TYPE_BACKUP_SOURCE, errp)) {
1838 goto out;
1841 flags = bs->open_flags | BDRV_O_RDWR;
1844 * See if we have a backing HD we can use to create our new image
1845 * on top of.
1847 if (backup->sync == MIRROR_SYNC_MODE_TOP) {
1848 source = backing_bs(bs);
1849 if (!source) {
1850 backup->sync = MIRROR_SYNC_MODE_FULL;
1853 if (backup->sync == MIRROR_SYNC_MODE_NONE) {
1854 source = bs;
1855 flags |= BDRV_O_NO_BACKING;
1856 set_backing_hd = true;
1859 size = bdrv_getlength(bs);
1860 if (size < 0) {
1861 error_setg_errno(errp, -size, "bdrv_getlength failed");
1862 goto out;
1865 if (backup->mode != NEW_IMAGE_MODE_EXISTING) {
1866 assert(backup->format);
1867 if (source) {
1868 bdrv_refresh_filename(source);
1869 bdrv_img_create(backup->target, backup->format, source->filename,
1870 source->drv->format_name, NULL,
1871 size, flags, false, &local_err);
1872 } else {
1873 bdrv_img_create(backup->target, backup->format, NULL, NULL, NULL,
1874 size, flags, false, &local_err);
1878 if (local_err) {
1879 error_propagate(errp, local_err);
1880 goto out;
1883 options = qdict_new();
1884 qdict_put_str(options, "discard", "unmap");
1885 qdict_put_str(options, "detect-zeroes", "unmap");
1886 if (backup->format) {
1887 qdict_put_str(options, "driver", backup->format);
1890 target_bs = bdrv_open(backup->target, NULL, options, flags, errp);
1891 if (!target_bs) {
1892 goto out;
1895 /* Honor bdrv_try_set_aio_context() context acquisition requirements. */
1896 old_context = bdrv_get_aio_context(target_bs);
1897 aio_context_release(aio_context);
1898 aio_context_acquire(old_context);
1900 ret = bdrv_try_set_aio_context(target_bs, aio_context, errp);
1901 if (ret < 0) {
1902 bdrv_unref(target_bs);
1903 aio_context_release(old_context);
1904 return;
1907 aio_context_release(old_context);
1908 aio_context_acquire(aio_context);
1910 if (set_backing_hd) {
1911 bdrv_set_backing_hd(target_bs, source, &local_err);
1912 if (local_err) {
1913 goto unref;
1917 state->bs = bs;
1919 state->job = do_backup_common(qapi_DriveBackup_base(backup),
1920 bs, target_bs, aio_context,
1921 common->block_job_txn, errp);
1923 unref:
1924 bdrv_unref(target_bs);
1925 out:
1926 aio_context_release(aio_context);
1929 static void drive_backup_commit(BlkActionState *common)
1931 DriveBackupState *state = DO_UPCAST(DriveBackupState, common, common);
1932 AioContext *aio_context;
1934 aio_context = bdrv_get_aio_context(state->bs);
1935 aio_context_acquire(aio_context);
1937 assert(state->job);
1938 job_start(&state->job->job);
1940 aio_context_release(aio_context);
1943 static void drive_backup_abort(BlkActionState *common)
1945 DriveBackupState *state = DO_UPCAST(DriveBackupState, common, common);
1947 if (state->job) {
1948 AioContext *aio_context;
1950 aio_context = bdrv_get_aio_context(state->bs);
1951 aio_context_acquire(aio_context);
1953 job_cancel_sync(&state->job->job);
1955 aio_context_release(aio_context);
1959 static void drive_backup_clean(BlkActionState *common)
1961 DriveBackupState *state = DO_UPCAST(DriveBackupState, common, common);
1962 AioContext *aio_context;
1964 if (!state->bs) {
1965 return;
1968 aio_context = bdrv_get_aio_context(state->bs);
1969 aio_context_acquire(aio_context);
1971 bdrv_drained_end(state->bs);
1973 aio_context_release(aio_context);
1976 typedef struct BlockdevBackupState {
1977 BlkActionState common;
1978 BlockDriverState *bs;
1979 BlockJob *job;
1980 } BlockdevBackupState;
1982 static void blockdev_backup_prepare(BlkActionState *common, Error **errp)
1984 BlockdevBackupState *state = DO_UPCAST(BlockdevBackupState, common, common);
1985 BlockdevBackup *backup;
1986 BlockDriverState *bs;
1987 BlockDriverState *target_bs;
1988 AioContext *aio_context;
1989 AioContext *old_context;
1990 int ret;
1992 assert(common->action->type == TRANSACTION_ACTION_KIND_BLOCKDEV_BACKUP);
1993 backup = common->action->u.blockdev_backup.data;
1995 bs = bdrv_lookup_bs(backup->device, backup->device, errp);
1996 if (!bs) {
1997 return;
2000 target_bs = bdrv_lookup_bs(backup->target, backup->target, errp);
2001 if (!target_bs) {
2002 return;
2005 /* Honor bdrv_try_set_aio_context() context acquisition requirements. */
2006 aio_context = bdrv_get_aio_context(bs);
2007 old_context = bdrv_get_aio_context(target_bs);
2008 aio_context_acquire(old_context);
2010 ret = bdrv_try_set_aio_context(target_bs, aio_context, errp);
2011 if (ret < 0) {
2012 aio_context_release(old_context);
2013 return;
2016 aio_context_release(old_context);
2017 aio_context_acquire(aio_context);
2018 state->bs = bs;
2020 /* Paired with .clean() */
2021 bdrv_drained_begin(state->bs);
2023 state->job = do_backup_common(qapi_BlockdevBackup_base(backup),
2024 bs, target_bs, aio_context,
2025 common->block_job_txn, errp);
2027 aio_context_release(aio_context);
2030 static void blockdev_backup_commit(BlkActionState *common)
2032 BlockdevBackupState *state = DO_UPCAST(BlockdevBackupState, common, common);
2033 AioContext *aio_context;
2035 aio_context = bdrv_get_aio_context(state->bs);
2036 aio_context_acquire(aio_context);
2038 assert(state->job);
2039 job_start(&state->job->job);
2041 aio_context_release(aio_context);
2044 static void blockdev_backup_abort(BlkActionState *common)
2046 BlockdevBackupState *state = DO_UPCAST(BlockdevBackupState, common, common);
2048 if (state->job) {
2049 AioContext *aio_context;
2051 aio_context = bdrv_get_aio_context(state->bs);
2052 aio_context_acquire(aio_context);
2054 job_cancel_sync(&state->job->job);
2056 aio_context_release(aio_context);
2060 static void blockdev_backup_clean(BlkActionState *common)
2062 BlockdevBackupState *state = DO_UPCAST(BlockdevBackupState, common, common);
2063 AioContext *aio_context;
2065 if (!state->bs) {
2066 return;
2069 aio_context = bdrv_get_aio_context(state->bs);
2070 aio_context_acquire(aio_context);
2072 bdrv_drained_end(state->bs);
2074 aio_context_release(aio_context);
2077 typedef struct BlockDirtyBitmapState {
2078 BlkActionState common;
2079 BdrvDirtyBitmap *bitmap;
2080 BlockDriverState *bs;
2081 HBitmap *backup;
2082 bool prepared;
2083 bool was_enabled;
2084 } BlockDirtyBitmapState;
2086 static void block_dirty_bitmap_add_prepare(BlkActionState *common,
2087 Error **errp)
2089 Error *local_err = NULL;
2090 BlockDirtyBitmapAdd *action;
2091 BlockDirtyBitmapState *state = DO_UPCAST(BlockDirtyBitmapState,
2092 common, common);
2094 if (action_check_completion_mode(common, errp) < 0) {
2095 return;
2098 action = common->action->u.block_dirty_bitmap_add.data;
2099 /* AIO context taken and released within qmp_block_dirty_bitmap_add */
2100 qmp_block_dirty_bitmap_add(action->node, action->name,
2101 action->has_granularity, action->granularity,
2102 action->has_persistent, action->persistent,
2103 action->has_disabled, action->disabled,
2104 &local_err);
2106 if (!local_err) {
2107 state->prepared = true;
2108 } else {
2109 error_propagate(errp, local_err);
2113 static void block_dirty_bitmap_add_abort(BlkActionState *common)
2115 BlockDirtyBitmapAdd *action;
2116 BlockDirtyBitmapState *state = DO_UPCAST(BlockDirtyBitmapState,
2117 common, common);
2119 action = common->action->u.block_dirty_bitmap_add.data;
2120 /* Should not be able to fail: IF the bitmap was added via .prepare(),
2121 * then the node reference and bitmap name must have been valid.
2123 if (state->prepared) {
2124 qmp_block_dirty_bitmap_remove(action->node, action->name, &error_abort);
2128 static void block_dirty_bitmap_clear_prepare(BlkActionState *common,
2129 Error **errp)
2131 BlockDirtyBitmapState *state = DO_UPCAST(BlockDirtyBitmapState,
2132 common, common);
2133 BlockDirtyBitmap *action;
2135 if (action_check_completion_mode(common, errp) < 0) {
2136 return;
2139 action = common->action->u.block_dirty_bitmap_clear.data;
2140 state->bitmap = block_dirty_bitmap_lookup(action->node,
2141 action->name,
2142 &state->bs,
2143 errp);
2144 if (!state->bitmap) {
2145 return;
2148 if (bdrv_dirty_bitmap_check(state->bitmap, BDRV_BITMAP_DEFAULT, errp)) {
2149 return;
2152 bdrv_clear_dirty_bitmap(state->bitmap, &state->backup);
2155 static void block_dirty_bitmap_restore(BlkActionState *common)
2157 BlockDirtyBitmapState *state = DO_UPCAST(BlockDirtyBitmapState,
2158 common, common);
2160 if (state->backup) {
2161 bdrv_restore_dirty_bitmap(state->bitmap, state->backup);
2165 static void block_dirty_bitmap_free_backup(BlkActionState *common)
2167 BlockDirtyBitmapState *state = DO_UPCAST(BlockDirtyBitmapState,
2168 common, common);
2170 hbitmap_free(state->backup);
2173 static void block_dirty_bitmap_enable_prepare(BlkActionState *common,
2174 Error **errp)
2176 BlockDirtyBitmap *action;
2177 BlockDirtyBitmapState *state = DO_UPCAST(BlockDirtyBitmapState,
2178 common, common);
2180 if (action_check_completion_mode(common, errp) < 0) {
2181 return;
2184 action = common->action->u.block_dirty_bitmap_enable.data;
2185 state->bitmap = block_dirty_bitmap_lookup(action->node,
2186 action->name,
2187 NULL,
2188 errp);
2189 if (!state->bitmap) {
2190 return;
2193 if (bdrv_dirty_bitmap_check(state->bitmap, BDRV_BITMAP_ALLOW_RO, errp)) {
2194 return;
2197 state->was_enabled = bdrv_dirty_bitmap_enabled(state->bitmap);
2198 bdrv_enable_dirty_bitmap(state->bitmap);
2201 static void block_dirty_bitmap_enable_abort(BlkActionState *common)
2203 BlockDirtyBitmapState *state = DO_UPCAST(BlockDirtyBitmapState,
2204 common, common);
2206 if (!state->was_enabled) {
2207 bdrv_disable_dirty_bitmap(state->bitmap);
2211 static void block_dirty_bitmap_disable_prepare(BlkActionState *common,
2212 Error **errp)
2214 BlockDirtyBitmap *action;
2215 BlockDirtyBitmapState *state = DO_UPCAST(BlockDirtyBitmapState,
2216 common, common);
2218 if (action_check_completion_mode(common, errp) < 0) {
2219 return;
2222 action = common->action->u.block_dirty_bitmap_disable.data;
2223 state->bitmap = block_dirty_bitmap_lookup(action->node,
2224 action->name,
2225 NULL,
2226 errp);
2227 if (!state->bitmap) {
2228 return;
2231 if (bdrv_dirty_bitmap_check(state->bitmap, BDRV_BITMAP_ALLOW_RO, errp)) {
2232 return;
2235 state->was_enabled = bdrv_dirty_bitmap_enabled(state->bitmap);
2236 bdrv_disable_dirty_bitmap(state->bitmap);
2239 static void block_dirty_bitmap_disable_abort(BlkActionState *common)
2241 BlockDirtyBitmapState *state = DO_UPCAST(BlockDirtyBitmapState,
2242 common, common);
2244 if (state->was_enabled) {
2245 bdrv_enable_dirty_bitmap(state->bitmap);
2249 static BdrvDirtyBitmap *do_block_dirty_bitmap_merge(
2250 const char *node, const char *target,
2251 BlockDirtyBitmapMergeSourceList *bitmaps,
2252 HBitmap **backup, Error **errp);
2254 static void block_dirty_bitmap_merge_prepare(BlkActionState *common,
2255 Error **errp)
2257 BlockDirtyBitmapMerge *action;
2258 BlockDirtyBitmapState *state = DO_UPCAST(BlockDirtyBitmapState,
2259 common, common);
2261 if (action_check_completion_mode(common, errp) < 0) {
2262 return;
2265 action = common->action->u.block_dirty_bitmap_merge.data;
2267 state->bitmap = do_block_dirty_bitmap_merge(action->node, action->target,
2268 action->bitmaps, &state->backup,
2269 errp);
2272 static BdrvDirtyBitmap *do_block_dirty_bitmap_remove(
2273 const char *node, const char *name, bool release,
2274 BlockDriverState **bitmap_bs, Error **errp);
2276 static void block_dirty_bitmap_remove_prepare(BlkActionState *common,
2277 Error **errp)
2279 BlockDirtyBitmap *action;
2280 BlockDirtyBitmapState *state = DO_UPCAST(BlockDirtyBitmapState,
2281 common, common);
2283 if (action_check_completion_mode(common, errp) < 0) {
2284 return;
2287 action = common->action->u.block_dirty_bitmap_remove.data;
2289 state->bitmap = do_block_dirty_bitmap_remove(action->node, action->name,
2290 false, &state->bs, errp);
2291 if (state->bitmap) {
2292 bdrv_dirty_bitmap_skip_store(state->bitmap, true);
2293 bdrv_dirty_bitmap_set_busy(state->bitmap, true);
2297 static void block_dirty_bitmap_remove_abort(BlkActionState *common)
2299 BlockDirtyBitmapState *state = DO_UPCAST(BlockDirtyBitmapState,
2300 common, common);
2302 if (state->bitmap) {
2303 bdrv_dirty_bitmap_skip_store(state->bitmap, false);
2304 bdrv_dirty_bitmap_set_busy(state->bitmap, false);
2308 static void block_dirty_bitmap_remove_commit(BlkActionState *common)
2310 BlockDirtyBitmapState *state = DO_UPCAST(BlockDirtyBitmapState,
2311 common, common);
2313 bdrv_dirty_bitmap_set_busy(state->bitmap, false);
2314 bdrv_release_dirty_bitmap(state->bitmap);
2317 static void abort_prepare(BlkActionState *common, Error **errp)
2319 error_setg(errp, "Transaction aborted using Abort action");
2322 static void abort_commit(BlkActionState *common)
2324 g_assert_not_reached(); /* this action never succeeds */
2327 static const BlkActionOps actions[] = {
2328 [TRANSACTION_ACTION_KIND_BLOCKDEV_SNAPSHOT] = {
2329 .instance_size = sizeof(ExternalSnapshotState),
2330 .prepare = external_snapshot_prepare,
2331 .commit = external_snapshot_commit,
2332 .abort = external_snapshot_abort,
2333 .clean = external_snapshot_clean,
2335 [TRANSACTION_ACTION_KIND_BLOCKDEV_SNAPSHOT_SYNC] = {
2336 .instance_size = sizeof(ExternalSnapshotState),
2337 .prepare = external_snapshot_prepare,
2338 .commit = external_snapshot_commit,
2339 .abort = external_snapshot_abort,
2340 .clean = external_snapshot_clean,
2342 [TRANSACTION_ACTION_KIND_DRIVE_BACKUP] = {
2343 .instance_size = sizeof(DriveBackupState),
2344 .prepare = drive_backup_prepare,
2345 .commit = drive_backup_commit,
2346 .abort = drive_backup_abort,
2347 .clean = drive_backup_clean,
2349 [TRANSACTION_ACTION_KIND_BLOCKDEV_BACKUP] = {
2350 .instance_size = sizeof(BlockdevBackupState),
2351 .prepare = blockdev_backup_prepare,
2352 .commit = blockdev_backup_commit,
2353 .abort = blockdev_backup_abort,
2354 .clean = blockdev_backup_clean,
2356 [TRANSACTION_ACTION_KIND_ABORT] = {
2357 .instance_size = sizeof(BlkActionState),
2358 .prepare = abort_prepare,
2359 .commit = abort_commit,
2361 [TRANSACTION_ACTION_KIND_BLOCKDEV_SNAPSHOT_INTERNAL_SYNC] = {
2362 .instance_size = sizeof(InternalSnapshotState),
2363 .prepare = internal_snapshot_prepare,
2364 .abort = internal_snapshot_abort,
2365 .clean = internal_snapshot_clean,
2367 [TRANSACTION_ACTION_KIND_BLOCK_DIRTY_BITMAP_ADD] = {
2368 .instance_size = sizeof(BlockDirtyBitmapState),
2369 .prepare = block_dirty_bitmap_add_prepare,
2370 .abort = block_dirty_bitmap_add_abort,
2372 [TRANSACTION_ACTION_KIND_BLOCK_DIRTY_BITMAP_CLEAR] = {
2373 .instance_size = sizeof(BlockDirtyBitmapState),
2374 .prepare = block_dirty_bitmap_clear_prepare,
2375 .commit = block_dirty_bitmap_free_backup,
2376 .abort = block_dirty_bitmap_restore,
2378 [TRANSACTION_ACTION_KIND_BLOCK_DIRTY_BITMAP_ENABLE] = {
2379 .instance_size = sizeof(BlockDirtyBitmapState),
2380 .prepare = block_dirty_bitmap_enable_prepare,
2381 .abort = block_dirty_bitmap_enable_abort,
2383 [TRANSACTION_ACTION_KIND_BLOCK_DIRTY_BITMAP_DISABLE] = {
2384 .instance_size = sizeof(BlockDirtyBitmapState),
2385 .prepare = block_dirty_bitmap_disable_prepare,
2386 .abort = block_dirty_bitmap_disable_abort,
2388 [TRANSACTION_ACTION_KIND_BLOCK_DIRTY_BITMAP_MERGE] = {
2389 .instance_size = sizeof(BlockDirtyBitmapState),
2390 .prepare = block_dirty_bitmap_merge_prepare,
2391 .commit = block_dirty_bitmap_free_backup,
2392 .abort = block_dirty_bitmap_restore,
2394 [TRANSACTION_ACTION_KIND_BLOCK_DIRTY_BITMAP_REMOVE] = {
2395 .instance_size = sizeof(BlockDirtyBitmapState),
2396 .prepare = block_dirty_bitmap_remove_prepare,
2397 .commit = block_dirty_bitmap_remove_commit,
2398 .abort = block_dirty_bitmap_remove_abort,
2400 /* Where are transactions for MIRROR, COMMIT and STREAM?
2401 * Although these blockjobs use transaction callbacks like the backup job,
2402 * these jobs do not necessarily adhere to transaction semantics.
2403 * These jobs may not fully undo all of their actions on abort, nor do they
2404 * necessarily work in transactions with more than one job in them.
2409 * Allocate a TransactionProperties structure if necessary, and fill
2410 * that structure with desired defaults if they are unset.
2412 static TransactionProperties *get_transaction_properties(
2413 TransactionProperties *props)
2415 if (!props) {
2416 props = g_new0(TransactionProperties, 1);
2419 if (!props->has_completion_mode) {
2420 props->has_completion_mode = true;
2421 props->completion_mode = ACTION_COMPLETION_MODE_INDIVIDUAL;
2424 return props;
2428 * 'Atomic' group operations. The operations are performed as a set, and if
2429 * any fail then we roll back all operations in the group.
2431 void qmp_transaction(TransactionActionList *dev_list,
2432 bool has_props,
2433 struct TransactionProperties *props,
2434 Error **errp)
2436 TransactionActionList *dev_entry = dev_list;
2437 JobTxn *block_job_txn = NULL;
2438 BlkActionState *state, *next;
2439 Error *local_err = NULL;
2441 QTAILQ_HEAD(, BlkActionState) snap_bdrv_states;
2442 QTAILQ_INIT(&snap_bdrv_states);
2444 /* Does this transaction get canceled as a group on failure?
2445 * If not, we don't really need to make a JobTxn.
2447 props = get_transaction_properties(props);
2448 if (props->completion_mode != ACTION_COMPLETION_MODE_INDIVIDUAL) {
2449 block_job_txn = job_txn_new();
2452 /* drain all i/o before any operations */
2453 bdrv_drain_all();
2455 /* We don't do anything in this loop that commits us to the operations */
2456 while (NULL != dev_entry) {
2457 TransactionAction *dev_info = NULL;
2458 const BlkActionOps *ops;
2460 dev_info = dev_entry->value;
2461 dev_entry = dev_entry->next;
2463 assert(dev_info->type < ARRAY_SIZE(actions));
2465 ops = &actions[dev_info->type];
2466 assert(ops->instance_size > 0);
2468 state = g_malloc0(ops->instance_size);
2469 state->ops = ops;
2470 state->action = dev_info;
2471 state->block_job_txn = block_job_txn;
2472 state->txn_props = props;
2473 QTAILQ_INSERT_TAIL(&snap_bdrv_states, state, entry);
2475 state->ops->prepare(state, &local_err);
2476 if (local_err) {
2477 error_propagate(errp, local_err);
2478 goto delete_and_fail;
2482 QTAILQ_FOREACH(state, &snap_bdrv_states, entry) {
2483 if (state->ops->commit) {
2484 state->ops->commit(state);
2488 /* success */
2489 goto exit;
2491 delete_and_fail:
2492 /* failure, and it is all-or-none; roll back all operations */
2493 QTAILQ_FOREACH_REVERSE(state, &snap_bdrv_states, entry) {
2494 if (state->ops->abort) {
2495 state->ops->abort(state);
2498 exit:
2499 QTAILQ_FOREACH_SAFE(state, &snap_bdrv_states, entry, next) {
2500 if (state->ops->clean) {
2501 state->ops->clean(state);
2503 g_free(state);
2505 if (!has_props) {
2506 qapi_free_TransactionProperties(props);
2508 job_txn_unref(block_job_txn);
2511 void qmp_eject(bool has_device, const char *device,
2512 bool has_id, const char *id,
2513 bool has_force, bool force, Error **errp)
2515 Error *local_err = NULL;
2516 int rc;
2518 if (!has_force) {
2519 force = false;
2522 rc = do_open_tray(has_device ? device : NULL,
2523 has_id ? id : NULL,
2524 force, &local_err);
2525 if (rc && rc != -ENOSYS) {
2526 error_propagate(errp, local_err);
2527 return;
2529 error_free(local_err);
2531 blockdev_remove_medium(has_device, device, has_id, id, errp);
2534 void qmp_block_passwd(bool has_device, const char *device,
2535 bool has_node_name, const char *node_name,
2536 const char *password, Error **errp)
2538 error_setg(errp,
2539 "Setting block passwords directly is no longer supported");
2543 * Attempt to open the tray of @device.
2544 * If @force, ignore its tray lock.
2545 * Else, if the tray is locked, don't open it, but ask the guest to open it.
2546 * On error, store an error through @errp and return -errno.
2547 * If @device does not exist, return -ENODEV.
2548 * If it has no removable media, return -ENOTSUP.
2549 * If it has no tray, return -ENOSYS.
2550 * If the guest was asked to open the tray, return -EINPROGRESS.
2551 * Else, return 0.
2553 static int do_open_tray(const char *blk_name, const char *qdev_id,
2554 bool force, Error **errp)
2556 BlockBackend *blk;
2557 const char *device = qdev_id ?: blk_name;
2558 bool locked;
2560 blk = qmp_get_blk(blk_name, qdev_id, errp);
2561 if (!blk) {
2562 return -ENODEV;
2565 if (!blk_dev_has_removable_media(blk)) {
2566 error_setg(errp, "Device '%s' is not removable", device);
2567 return -ENOTSUP;
2570 if (!blk_dev_has_tray(blk)) {
2571 error_setg(errp, "Device '%s' does not have a tray", device);
2572 return -ENOSYS;
2575 if (blk_dev_is_tray_open(blk)) {
2576 return 0;
2579 locked = blk_dev_is_medium_locked(blk);
2580 if (locked) {
2581 blk_dev_eject_request(blk, force);
2584 if (!locked || force) {
2585 blk_dev_change_media_cb(blk, false, &error_abort);
2588 if (locked && !force) {
2589 error_setg(errp, "Device '%s' is locked and force was not specified, "
2590 "wait for tray to open and try again", device);
2591 return -EINPROGRESS;
2594 return 0;
2597 void qmp_blockdev_open_tray(bool has_device, const char *device,
2598 bool has_id, const char *id,
2599 bool has_force, bool force,
2600 Error **errp)
2602 Error *local_err = NULL;
2603 int rc;
2605 if (!has_force) {
2606 force = false;
2608 rc = do_open_tray(has_device ? device : NULL,
2609 has_id ? id : NULL,
2610 force, &local_err);
2611 if (rc && rc != -ENOSYS && rc != -EINPROGRESS) {
2612 error_propagate(errp, local_err);
2613 return;
2615 error_free(local_err);
2618 void qmp_blockdev_close_tray(bool has_device, const char *device,
2619 bool has_id, const char *id,
2620 Error **errp)
2622 BlockBackend *blk;
2623 Error *local_err = NULL;
2625 device = has_device ? device : NULL;
2626 id = has_id ? id : NULL;
2628 blk = qmp_get_blk(device, id, errp);
2629 if (!blk) {
2630 return;
2633 if (!blk_dev_has_removable_media(blk)) {
2634 error_setg(errp, "Device '%s' is not removable", device ?: id);
2635 return;
2638 if (!blk_dev_has_tray(blk)) {
2639 /* Ignore this command on tray-less devices */
2640 return;
2643 if (!blk_dev_is_tray_open(blk)) {
2644 return;
2647 blk_dev_change_media_cb(blk, true, &local_err);
2648 if (local_err) {
2649 error_propagate(errp, local_err);
2650 return;
2654 static void blockdev_remove_medium(bool has_device, const char *device,
2655 bool has_id, const char *id, Error **errp)
2657 BlockBackend *blk;
2658 BlockDriverState *bs;
2659 AioContext *aio_context;
2660 bool has_attached_device;
2662 device = has_device ? device : NULL;
2663 id = has_id ? id : NULL;
2665 blk = qmp_get_blk(device, id, errp);
2666 if (!blk) {
2667 return;
2670 /* For BBs without a device, we can exchange the BDS tree at will */
2671 has_attached_device = blk_get_attached_dev(blk);
2673 if (has_attached_device && !blk_dev_has_removable_media(blk)) {
2674 error_setg(errp, "Device '%s' is not removable", device ?: id);
2675 return;
2678 if (has_attached_device && blk_dev_has_tray(blk) &&
2679 !blk_dev_is_tray_open(blk))
2681 error_setg(errp, "Tray of device '%s' is not open", device ?: id);
2682 return;
2685 bs = blk_bs(blk);
2686 if (!bs) {
2687 return;
2690 aio_context = bdrv_get_aio_context(bs);
2691 aio_context_acquire(aio_context);
2693 if (bdrv_op_is_blocked(bs, BLOCK_OP_TYPE_EJECT, errp)) {
2694 goto out;
2697 blk_remove_bs(blk);
2699 if (!blk_dev_has_tray(blk)) {
2700 /* For tray-less devices, blockdev-open-tray is a no-op (or may not be
2701 * called at all); therefore, the medium needs to be ejected here.
2702 * Do it after blk_remove_bs() so blk_is_inserted(blk) returns the @load
2703 * value passed here (i.e. false). */
2704 blk_dev_change_media_cb(blk, false, &error_abort);
2707 out:
2708 aio_context_release(aio_context);
2711 void qmp_blockdev_remove_medium(const char *id, Error **errp)
2713 blockdev_remove_medium(false, NULL, true, id, errp);
2716 static void qmp_blockdev_insert_anon_medium(BlockBackend *blk,
2717 BlockDriverState *bs, Error **errp)
2719 Error *local_err = NULL;
2720 bool has_device;
2721 int ret;
2723 /* For BBs without a device, we can exchange the BDS tree at will */
2724 has_device = blk_get_attached_dev(blk);
2726 if (has_device && !blk_dev_has_removable_media(blk)) {
2727 error_setg(errp, "Device is not removable");
2728 return;
2731 if (has_device && blk_dev_has_tray(blk) && !blk_dev_is_tray_open(blk)) {
2732 error_setg(errp, "Tray of the device is not open");
2733 return;
2736 if (blk_bs(blk)) {
2737 error_setg(errp, "There already is a medium in the device");
2738 return;
2741 ret = blk_insert_bs(blk, bs, errp);
2742 if (ret < 0) {
2743 return;
2746 if (!blk_dev_has_tray(blk)) {
2747 /* For tray-less devices, blockdev-close-tray is a no-op (or may not be
2748 * called at all); therefore, the medium needs to be pushed into the
2749 * slot here.
2750 * Do it after blk_insert_bs() so blk_is_inserted(blk) returns the @load
2751 * value passed here (i.e. true). */
2752 blk_dev_change_media_cb(blk, true, &local_err);
2753 if (local_err) {
2754 error_propagate(errp, local_err);
2755 blk_remove_bs(blk);
2756 return;
2761 static void blockdev_insert_medium(bool has_device, const char *device,
2762 bool has_id, const char *id,
2763 const char *node_name, Error **errp)
2765 BlockBackend *blk;
2766 BlockDriverState *bs;
2768 blk = qmp_get_blk(has_device ? device : NULL,
2769 has_id ? id : NULL,
2770 errp);
2771 if (!blk) {
2772 return;
2775 bs = bdrv_find_node(node_name);
2776 if (!bs) {
2777 error_setg(errp, "Node '%s' not found", node_name);
2778 return;
2781 if (bdrv_has_blk(bs)) {
2782 error_setg(errp, "Node '%s' is already in use", node_name);
2783 return;
2786 qmp_blockdev_insert_anon_medium(blk, bs, errp);
2789 void qmp_blockdev_insert_medium(const char *id, const char *node_name,
2790 Error **errp)
2792 blockdev_insert_medium(false, NULL, true, id, node_name, errp);
2795 void qmp_blockdev_change_medium(bool has_device, const char *device,
2796 bool has_id, const char *id,
2797 const char *filename,
2798 bool has_format, const char *format,
2799 bool has_read_only,
2800 BlockdevChangeReadOnlyMode read_only,
2801 Error **errp)
2803 BlockBackend *blk;
2804 BlockDriverState *medium_bs = NULL;
2805 int bdrv_flags;
2806 bool detect_zeroes;
2807 int rc;
2808 QDict *options = NULL;
2809 Error *err = NULL;
2811 blk = qmp_get_blk(has_device ? device : NULL,
2812 has_id ? id : NULL,
2813 errp);
2814 if (!blk) {
2815 goto fail;
2818 if (blk_bs(blk)) {
2819 blk_update_root_state(blk);
2822 bdrv_flags = blk_get_open_flags_from_root_state(blk);
2823 bdrv_flags &= ~(BDRV_O_TEMPORARY | BDRV_O_SNAPSHOT | BDRV_O_NO_BACKING |
2824 BDRV_O_PROTOCOL | BDRV_O_AUTO_RDONLY);
2826 if (!has_read_only) {
2827 read_only = BLOCKDEV_CHANGE_READ_ONLY_MODE_RETAIN;
2830 switch (read_only) {
2831 case BLOCKDEV_CHANGE_READ_ONLY_MODE_RETAIN:
2832 break;
2834 case BLOCKDEV_CHANGE_READ_ONLY_MODE_READ_ONLY:
2835 bdrv_flags &= ~BDRV_O_RDWR;
2836 break;
2838 case BLOCKDEV_CHANGE_READ_ONLY_MODE_READ_WRITE:
2839 bdrv_flags |= BDRV_O_RDWR;
2840 break;
2842 default:
2843 abort();
2846 options = qdict_new();
2847 detect_zeroes = blk_get_detect_zeroes_from_root_state(blk);
2848 qdict_put_str(options, "detect-zeroes", detect_zeroes ? "on" : "off");
2850 if (has_format) {
2851 qdict_put_str(options, "driver", format);
2854 medium_bs = bdrv_open(filename, NULL, options, bdrv_flags, errp);
2855 if (!medium_bs) {
2856 goto fail;
2859 rc = do_open_tray(has_device ? device : NULL,
2860 has_id ? id : NULL,
2861 false, &err);
2862 if (rc && rc != -ENOSYS) {
2863 error_propagate(errp, err);
2864 goto fail;
2866 error_free(err);
2867 err = NULL;
2869 blockdev_remove_medium(has_device, device, has_id, id, &err);
2870 if (err) {
2871 error_propagate(errp, err);
2872 goto fail;
2875 qmp_blockdev_insert_anon_medium(blk, medium_bs, &err);
2876 if (err) {
2877 error_propagate(errp, err);
2878 goto fail;
2881 qmp_blockdev_close_tray(has_device, device, has_id, id, errp);
2883 fail:
2884 /* If the medium has been inserted, the device has its own reference, so
2885 * ours must be relinquished; and if it has not been inserted successfully,
2886 * the reference must be relinquished anyway */
2887 bdrv_unref(medium_bs);
2890 /* throttling disk I/O limits */
2891 void qmp_block_set_io_throttle(BlockIOThrottle *arg, Error **errp)
2893 ThrottleConfig cfg;
2894 BlockDriverState *bs;
2895 BlockBackend *blk;
2896 AioContext *aio_context;
2898 blk = qmp_get_blk(arg->has_device ? arg->device : NULL,
2899 arg->has_id ? arg->id : NULL,
2900 errp);
2901 if (!blk) {
2902 return;
2905 aio_context = blk_get_aio_context(blk);
2906 aio_context_acquire(aio_context);
2908 bs = blk_bs(blk);
2909 if (!bs) {
2910 error_setg(errp, "Device has no medium");
2911 goto out;
2914 throttle_config_init(&cfg);
2915 cfg.buckets[THROTTLE_BPS_TOTAL].avg = arg->bps;
2916 cfg.buckets[THROTTLE_BPS_READ].avg = arg->bps_rd;
2917 cfg.buckets[THROTTLE_BPS_WRITE].avg = arg->bps_wr;
2919 cfg.buckets[THROTTLE_OPS_TOTAL].avg = arg->iops;
2920 cfg.buckets[THROTTLE_OPS_READ].avg = arg->iops_rd;
2921 cfg.buckets[THROTTLE_OPS_WRITE].avg = arg->iops_wr;
2923 if (arg->has_bps_max) {
2924 cfg.buckets[THROTTLE_BPS_TOTAL].max = arg->bps_max;
2926 if (arg->has_bps_rd_max) {
2927 cfg.buckets[THROTTLE_BPS_READ].max = arg->bps_rd_max;
2929 if (arg->has_bps_wr_max) {
2930 cfg.buckets[THROTTLE_BPS_WRITE].max = arg->bps_wr_max;
2932 if (arg->has_iops_max) {
2933 cfg.buckets[THROTTLE_OPS_TOTAL].max = arg->iops_max;
2935 if (arg->has_iops_rd_max) {
2936 cfg.buckets[THROTTLE_OPS_READ].max = arg->iops_rd_max;
2938 if (arg->has_iops_wr_max) {
2939 cfg.buckets[THROTTLE_OPS_WRITE].max = arg->iops_wr_max;
2942 if (arg->has_bps_max_length) {
2943 cfg.buckets[THROTTLE_BPS_TOTAL].burst_length = arg->bps_max_length;
2945 if (arg->has_bps_rd_max_length) {
2946 cfg.buckets[THROTTLE_BPS_READ].burst_length = arg->bps_rd_max_length;
2948 if (arg->has_bps_wr_max_length) {
2949 cfg.buckets[THROTTLE_BPS_WRITE].burst_length = arg->bps_wr_max_length;
2951 if (arg->has_iops_max_length) {
2952 cfg.buckets[THROTTLE_OPS_TOTAL].burst_length = arg->iops_max_length;
2954 if (arg->has_iops_rd_max_length) {
2955 cfg.buckets[THROTTLE_OPS_READ].burst_length = arg->iops_rd_max_length;
2957 if (arg->has_iops_wr_max_length) {
2958 cfg.buckets[THROTTLE_OPS_WRITE].burst_length = arg->iops_wr_max_length;
2961 if (arg->has_iops_size) {
2962 cfg.op_size = arg->iops_size;
2965 if (!throttle_is_valid(&cfg, errp)) {
2966 goto out;
2969 if (throttle_enabled(&cfg)) {
2970 /* Enable I/O limits if they're not enabled yet, otherwise
2971 * just update the throttling group. */
2972 if (!blk_get_public(blk)->throttle_group_member.throttle_state) {
2973 blk_io_limits_enable(blk,
2974 arg->has_group ? arg->group :
2975 arg->has_device ? arg->device :
2976 arg->id);
2977 } else if (arg->has_group) {
2978 blk_io_limits_update_group(blk, arg->group);
2980 /* Set the new throttling configuration */
2981 blk_set_io_limits(blk, &cfg);
2982 } else if (blk_get_public(blk)->throttle_group_member.throttle_state) {
2983 /* If all throttling settings are set to 0, disable I/O limits */
2984 blk_io_limits_disable(blk);
2987 out:
2988 aio_context_release(aio_context);
2991 void qmp_block_dirty_bitmap_add(const char *node, const char *name,
2992 bool has_granularity, uint32_t granularity,
2993 bool has_persistent, bool persistent,
2994 bool has_disabled, bool disabled,
2995 Error **errp)
2997 BlockDriverState *bs;
2998 BdrvDirtyBitmap *bitmap;
2999 AioContext *aio_context;
3001 if (!name || name[0] == '\0') {
3002 error_setg(errp, "Bitmap name cannot be empty");
3003 return;
3006 bs = bdrv_lookup_bs(node, node, errp);
3007 if (!bs) {
3008 return;
3011 aio_context = bdrv_get_aio_context(bs);
3012 aio_context_acquire(aio_context);
3014 if (has_granularity) {
3015 if (granularity < 512 || !is_power_of_2(granularity)) {
3016 error_setg(errp, "Granularity must be power of 2 "
3017 "and at least 512");
3018 goto out;
3020 } else {
3021 /* Default to cluster size, if available: */
3022 granularity = bdrv_get_default_bitmap_granularity(bs);
3025 if (!has_persistent) {
3026 persistent = false;
3029 if (!has_disabled) {
3030 disabled = false;
3033 if (persistent &&
3034 !bdrv_can_store_new_dirty_bitmap(bs, name, granularity, errp))
3036 goto out;
3039 bitmap = bdrv_create_dirty_bitmap(bs, granularity, name, errp);
3040 if (bitmap == NULL) {
3041 goto out;
3044 if (disabled) {
3045 bdrv_disable_dirty_bitmap(bitmap);
3048 bdrv_dirty_bitmap_set_persistence(bitmap, persistent);
3050 out:
3051 aio_context_release(aio_context);
3054 static BdrvDirtyBitmap *do_block_dirty_bitmap_remove(
3055 const char *node, const char *name, bool release,
3056 BlockDriverState **bitmap_bs, Error **errp)
3058 BlockDriverState *bs;
3059 BdrvDirtyBitmap *bitmap;
3060 AioContext *aio_context;
3062 bitmap = block_dirty_bitmap_lookup(node, name, &bs, errp);
3063 if (!bitmap || !bs) {
3064 return NULL;
3067 aio_context = bdrv_get_aio_context(bs);
3068 aio_context_acquire(aio_context);
3070 if (bdrv_dirty_bitmap_check(bitmap, BDRV_BITMAP_BUSY | BDRV_BITMAP_RO,
3071 errp)) {
3072 aio_context_release(aio_context);
3073 return NULL;
3076 if (bdrv_dirty_bitmap_get_persistence(bitmap) &&
3077 bdrv_remove_persistent_dirty_bitmap(bs, name, errp) < 0)
3079 aio_context_release(aio_context);
3080 return NULL;
3083 if (release) {
3084 bdrv_release_dirty_bitmap(bitmap);
3087 if (bitmap_bs) {
3088 *bitmap_bs = bs;
3091 aio_context_release(aio_context);
3092 return release ? NULL : bitmap;
3095 void qmp_block_dirty_bitmap_remove(const char *node, const char *name,
3096 Error **errp)
3098 do_block_dirty_bitmap_remove(node, name, true, NULL, errp);
3102 * Completely clear a bitmap, for the purposes of synchronizing a bitmap
3103 * immediately after a full backup operation.
3105 void qmp_block_dirty_bitmap_clear(const char *node, const char *name,
3106 Error **errp)
3108 BdrvDirtyBitmap *bitmap;
3109 BlockDriverState *bs;
3111 bitmap = block_dirty_bitmap_lookup(node, name, &bs, errp);
3112 if (!bitmap || !bs) {
3113 return;
3116 if (bdrv_dirty_bitmap_check(bitmap, BDRV_BITMAP_DEFAULT, errp)) {
3117 return;
3120 bdrv_clear_dirty_bitmap(bitmap, NULL);
3123 void qmp_block_dirty_bitmap_enable(const char *node, const char *name,
3124 Error **errp)
3126 BlockDriverState *bs;
3127 BdrvDirtyBitmap *bitmap;
3129 bitmap = block_dirty_bitmap_lookup(node, name, &bs, errp);
3130 if (!bitmap) {
3131 return;
3134 if (bdrv_dirty_bitmap_check(bitmap, BDRV_BITMAP_ALLOW_RO, errp)) {
3135 return;
3138 bdrv_enable_dirty_bitmap(bitmap);
3141 void qmp_block_dirty_bitmap_disable(const char *node, const char *name,
3142 Error **errp)
3144 BlockDriverState *bs;
3145 BdrvDirtyBitmap *bitmap;
3147 bitmap = block_dirty_bitmap_lookup(node, name, &bs, errp);
3148 if (!bitmap) {
3149 return;
3152 if (bdrv_dirty_bitmap_check(bitmap, BDRV_BITMAP_ALLOW_RO, errp)) {
3153 return;
3156 bdrv_disable_dirty_bitmap(bitmap);
3159 static BdrvDirtyBitmap *do_block_dirty_bitmap_merge(
3160 const char *node, const char *target,
3161 BlockDirtyBitmapMergeSourceList *bitmaps,
3162 HBitmap **backup, Error **errp)
3164 BlockDriverState *bs;
3165 BdrvDirtyBitmap *dst, *src, *anon;
3166 BlockDirtyBitmapMergeSourceList *lst;
3167 Error *local_err = NULL;
3169 dst = block_dirty_bitmap_lookup(node, target, &bs, errp);
3170 if (!dst) {
3171 return NULL;
3174 anon = bdrv_create_dirty_bitmap(bs, bdrv_dirty_bitmap_granularity(dst),
3175 NULL, errp);
3176 if (!anon) {
3177 return NULL;
3180 for (lst = bitmaps; lst; lst = lst->next) {
3181 switch (lst->value->type) {
3182 const char *name, *node;
3183 case QTYPE_QSTRING:
3184 name = lst->value->u.local;
3185 src = bdrv_find_dirty_bitmap(bs, name);
3186 if (!src) {
3187 error_setg(errp, "Dirty bitmap '%s' not found", name);
3188 dst = NULL;
3189 goto out;
3191 break;
3192 case QTYPE_QDICT:
3193 node = lst->value->u.external.node;
3194 name = lst->value->u.external.name;
3195 src = block_dirty_bitmap_lookup(node, name, NULL, errp);
3196 if (!src) {
3197 dst = NULL;
3198 goto out;
3200 break;
3201 default:
3202 abort();
3205 bdrv_merge_dirty_bitmap(anon, src, NULL, &local_err);
3206 if (local_err) {
3207 error_propagate(errp, local_err);
3208 dst = NULL;
3209 goto out;
3213 /* Merge into dst; dst is unchanged on failure. */
3214 bdrv_merge_dirty_bitmap(dst, anon, backup, errp);
3216 out:
3217 bdrv_release_dirty_bitmap(anon);
3218 return dst;
3221 void qmp_block_dirty_bitmap_merge(const char *node, const char *target,
3222 BlockDirtyBitmapMergeSourceList *bitmaps,
3223 Error **errp)
3225 do_block_dirty_bitmap_merge(node, target, bitmaps, NULL, errp);
3228 BlockDirtyBitmapSha256 *qmp_x_debug_block_dirty_bitmap_sha256(const char *node,
3229 const char *name,
3230 Error **errp)
3232 BdrvDirtyBitmap *bitmap;
3233 BlockDriverState *bs;
3234 BlockDirtyBitmapSha256 *ret = NULL;
3235 char *sha256;
3237 bitmap = block_dirty_bitmap_lookup(node, name, &bs, errp);
3238 if (!bitmap || !bs) {
3239 return NULL;
3242 sha256 = bdrv_dirty_bitmap_sha256(bitmap, errp);
3243 if (sha256 == NULL) {
3244 return NULL;
3247 ret = g_new(BlockDirtyBitmapSha256, 1);
3248 ret->sha256 = sha256;
3250 return ret;
3253 void hmp_drive_del(Monitor *mon, const QDict *qdict)
3255 const char *id = qdict_get_str(qdict, "id");
3256 BlockBackend *blk;
3257 BlockDriverState *bs;
3258 AioContext *aio_context;
3259 Error *local_err = NULL;
3261 bs = bdrv_find_node(id);
3262 if (bs) {
3263 qmp_blockdev_del(id, &local_err);
3264 if (local_err) {
3265 error_report_err(local_err);
3267 return;
3270 blk = blk_by_name(id);
3271 if (!blk) {
3272 error_report("Device '%s' not found", id);
3273 return;
3276 if (!blk_legacy_dinfo(blk)) {
3277 error_report("Deleting device added with blockdev-add"
3278 " is not supported");
3279 return;
3282 aio_context = blk_get_aio_context(blk);
3283 aio_context_acquire(aio_context);
3285 bs = blk_bs(blk);
3286 if (bs) {
3287 if (bdrv_op_is_blocked(bs, BLOCK_OP_TYPE_DRIVE_DEL, &local_err)) {
3288 error_report_err(local_err);
3289 aio_context_release(aio_context);
3290 return;
3293 blk_remove_bs(blk);
3296 /* Make the BlockBackend and the attached BlockDriverState anonymous */
3297 monitor_remove_blk(blk);
3299 /* If this BlockBackend has a device attached to it, its refcount will be
3300 * decremented when the device is removed; otherwise we have to do so here.
3302 if (blk_get_attached_dev(blk)) {
3303 /* Further I/O must not pause the guest */
3304 blk_set_on_error(blk, BLOCKDEV_ON_ERROR_REPORT,
3305 BLOCKDEV_ON_ERROR_REPORT);
3306 } else {
3307 blk_unref(blk);
3310 aio_context_release(aio_context);
3313 void qmp_block_resize(bool has_device, const char *device,
3314 bool has_node_name, const char *node_name,
3315 int64_t size, Error **errp)
3317 Error *local_err = NULL;
3318 BlockBackend *blk = NULL;
3319 BlockDriverState *bs;
3320 AioContext *aio_context;
3321 int ret;
3323 bs = bdrv_lookup_bs(has_device ? device : NULL,
3324 has_node_name ? node_name : NULL,
3325 &local_err);
3326 if (local_err) {
3327 error_propagate(errp, local_err);
3328 return;
3331 aio_context = bdrv_get_aio_context(bs);
3332 aio_context_acquire(aio_context);
3334 if (size < 0) {
3335 error_setg(errp, QERR_INVALID_PARAMETER_VALUE, "size", "a >0 size");
3336 goto out;
3339 if (bdrv_op_is_blocked(bs, BLOCK_OP_TYPE_RESIZE, NULL)) {
3340 error_setg(errp, QERR_DEVICE_IN_USE, device);
3341 goto out;
3344 blk = blk_new(bdrv_get_aio_context(bs), BLK_PERM_RESIZE, BLK_PERM_ALL);
3345 ret = blk_insert_bs(blk, bs, errp);
3346 if (ret < 0) {
3347 goto out;
3350 bdrv_drained_begin(bs);
3351 ret = blk_truncate(blk, size, false, PREALLOC_MODE_OFF, errp);
3352 bdrv_drained_end(bs);
3354 out:
3355 blk_unref(blk);
3356 aio_context_release(aio_context);
3359 void qmp_block_stream(bool has_job_id, const char *job_id, const char *device,
3360 bool has_base, const char *base,
3361 bool has_base_node, const char *base_node,
3362 bool has_backing_file, const char *backing_file,
3363 bool has_speed, int64_t speed,
3364 bool has_on_error, BlockdevOnError on_error,
3365 bool has_auto_finalize, bool auto_finalize,
3366 bool has_auto_dismiss, bool auto_dismiss,
3367 Error **errp)
3369 BlockDriverState *bs, *iter;
3370 BlockDriverState *base_bs = NULL;
3371 AioContext *aio_context;
3372 Error *local_err = NULL;
3373 const char *base_name = NULL;
3374 int job_flags = JOB_DEFAULT;
3376 if (!has_on_error) {
3377 on_error = BLOCKDEV_ON_ERROR_REPORT;
3380 bs = bdrv_lookup_bs(device, device, errp);
3381 if (!bs) {
3382 return;
3385 aio_context = bdrv_get_aio_context(bs);
3386 aio_context_acquire(aio_context);
3388 if (has_base && has_base_node) {
3389 error_setg(errp, "'base' and 'base-node' cannot be specified "
3390 "at the same time");
3391 goto out;
3394 if (has_base) {
3395 base_bs = bdrv_find_backing_image(bs, base);
3396 if (base_bs == NULL) {
3397 error_setg(errp, QERR_BASE_NOT_FOUND, base);
3398 goto out;
3400 assert(bdrv_get_aio_context(base_bs) == aio_context);
3401 base_name = base;
3404 if (has_base_node) {
3405 base_bs = bdrv_lookup_bs(NULL, base_node, errp);
3406 if (!base_bs) {
3407 goto out;
3409 if (bs == base_bs || !bdrv_chain_contains(bs, base_bs)) {
3410 error_setg(errp, "Node '%s' is not a backing image of '%s'",
3411 base_node, device);
3412 goto out;
3414 assert(bdrv_get_aio_context(base_bs) == aio_context);
3415 bdrv_refresh_filename(base_bs);
3416 base_name = base_bs->filename;
3419 /* Check for op blockers in the whole chain between bs and base */
3420 for (iter = bs; iter && iter != base_bs; iter = backing_bs(iter)) {
3421 if (bdrv_op_is_blocked(iter, BLOCK_OP_TYPE_STREAM, errp)) {
3422 goto out;
3426 /* if we are streaming the entire chain, the result will have no backing
3427 * file, and specifying one is therefore an error */
3428 if (base_bs == NULL && has_backing_file) {
3429 error_setg(errp, "backing file specified, but streaming the "
3430 "entire chain");
3431 goto out;
3434 /* backing_file string overrides base bs filename */
3435 base_name = has_backing_file ? backing_file : base_name;
3437 if (has_auto_finalize && !auto_finalize) {
3438 job_flags |= JOB_MANUAL_FINALIZE;
3440 if (has_auto_dismiss && !auto_dismiss) {
3441 job_flags |= JOB_MANUAL_DISMISS;
3444 stream_start(has_job_id ? job_id : NULL, bs, base_bs, base_name,
3445 job_flags, has_speed ? speed : 0, on_error, &local_err);
3446 if (local_err) {
3447 error_propagate(errp, local_err);
3448 goto out;
3451 trace_qmp_block_stream(bs);
3453 out:
3454 aio_context_release(aio_context);
3457 void qmp_block_commit(bool has_job_id, const char *job_id, const char *device,
3458 bool has_base_node, const char *base_node,
3459 bool has_base, const char *base,
3460 bool has_top_node, const char *top_node,
3461 bool has_top, const char *top,
3462 bool has_backing_file, const char *backing_file,
3463 bool has_speed, int64_t speed,
3464 bool has_on_error, BlockdevOnError on_error,
3465 bool has_filter_node_name, const char *filter_node_name,
3466 bool has_auto_finalize, bool auto_finalize,
3467 bool has_auto_dismiss, bool auto_dismiss,
3468 Error **errp)
3470 BlockDriverState *bs;
3471 BlockDriverState *iter;
3472 BlockDriverState *base_bs, *top_bs;
3473 AioContext *aio_context;
3474 Error *local_err = NULL;
3475 int job_flags = JOB_DEFAULT;
3477 if (!has_speed) {
3478 speed = 0;
3480 if (!has_on_error) {
3481 on_error = BLOCKDEV_ON_ERROR_REPORT;
3483 if (!has_filter_node_name) {
3484 filter_node_name = NULL;
3486 if (has_auto_finalize && !auto_finalize) {
3487 job_flags |= JOB_MANUAL_FINALIZE;
3489 if (has_auto_dismiss && !auto_dismiss) {
3490 job_flags |= JOB_MANUAL_DISMISS;
3493 /* Important Note:
3494 * libvirt relies on the DeviceNotFound error class in order to probe for
3495 * live commit feature versions; for this to work, we must make sure to
3496 * perform the device lookup before any generic errors that may occur in a
3497 * scenario in which all optional arguments are omitted. */
3498 bs = qmp_get_root_bs(device, &local_err);
3499 if (!bs) {
3500 bs = bdrv_lookup_bs(device, device, NULL);
3501 if (!bs) {
3502 error_free(local_err);
3503 error_set(errp, ERROR_CLASS_DEVICE_NOT_FOUND,
3504 "Device '%s' not found", device);
3505 } else {
3506 error_propagate(errp, local_err);
3508 return;
3511 aio_context = bdrv_get_aio_context(bs);
3512 aio_context_acquire(aio_context);
3514 if (bdrv_op_is_blocked(bs, BLOCK_OP_TYPE_COMMIT_SOURCE, errp)) {
3515 goto out;
3518 /* default top_bs is the active layer */
3519 top_bs = bs;
3521 if (has_top_node && has_top) {
3522 error_setg(errp, "'top-node' and 'top' are mutually exclusive");
3523 goto out;
3524 } else if (has_top_node) {
3525 top_bs = bdrv_lookup_bs(NULL, top_node, errp);
3526 if (top_bs == NULL) {
3527 goto out;
3529 if (!bdrv_chain_contains(bs, top_bs)) {
3530 error_setg(errp, "'%s' is not in this backing file chain",
3531 top_node);
3532 goto out;
3534 } else if (has_top && top) {
3535 /* This strcmp() is just a shortcut, there is no need to
3536 * refresh @bs's filename. If it mismatches,
3537 * bdrv_find_backing_image() will do the refresh and may still
3538 * return @bs. */
3539 if (strcmp(bs->filename, top) != 0) {
3540 top_bs = bdrv_find_backing_image(bs, top);
3544 if (top_bs == NULL) {
3545 error_setg(errp, "Top image file %s not found", top ? top : "NULL");
3546 goto out;
3549 assert(bdrv_get_aio_context(top_bs) == aio_context);
3551 if (has_base_node && has_base) {
3552 error_setg(errp, "'base-node' and 'base' are mutually exclusive");
3553 goto out;
3554 } else if (has_base_node) {
3555 base_bs = bdrv_lookup_bs(NULL, base_node, errp);
3556 if (base_bs == NULL) {
3557 goto out;
3559 if (!bdrv_chain_contains(top_bs, base_bs)) {
3560 error_setg(errp, "'%s' is not in this backing file chain",
3561 base_node);
3562 goto out;
3564 } else if (has_base && base) {
3565 base_bs = bdrv_find_backing_image(top_bs, base);
3566 } else {
3567 base_bs = bdrv_find_base(top_bs);
3570 if (base_bs == NULL) {
3571 error_setg(errp, QERR_BASE_NOT_FOUND, base ? base : "NULL");
3572 goto out;
3575 assert(bdrv_get_aio_context(base_bs) == aio_context);
3577 for (iter = top_bs; iter != backing_bs(base_bs); iter = backing_bs(iter)) {
3578 if (bdrv_op_is_blocked(iter, BLOCK_OP_TYPE_COMMIT_TARGET, errp)) {
3579 goto out;
3583 /* Do not allow attempts to commit an image into itself */
3584 if (top_bs == base_bs) {
3585 error_setg(errp, "cannot commit an image into itself");
3586 goto out;
3589 if (top_bs == bs) {
3590 if (has_backing_file) {
3591 error_setg(errp, "'backing-file' specified,"
3592 " but 'top' is the active layer");
3593 goto out;
3595 commit_active_start(has_job_id ? job_id : NULL, bs, base_bs,
3596 job_flags, speed, on_error,
3597 filter_node_name, NULL, NULL, false, &local_err);
3598 } else {
3599 BlockDriverState *overlay_bs = bdrv_find_overlay(bs, top_bs);
3600 if (bdrv_op_is_blocked(overlay_bs, BLOCK_OP_TYPE_COMMIT_TARGET, errp)) {
3601 goto out;
3603 commit_start(has_job_id ? job_id : NULL, bs, base_bs, top_bs, job_flags,
3604 speed, on_error, has_backing_file ? backing_file : NULL,
3605 filter_node_name, &local_err);
3607 if (local_err != NULL) {
3608 error_propagate(errp, local_err);
3609 goto out;
3612 out:
3613 aio_context_release(aio_context);
3616 /* Common QMP interface for drive-backup and blockdev-backup */
3617 static BlockJob *do_backup_common(BackupCommon *backup,
3618 BlockDriverState *bs,
3619 BlockDriverState *target_bs,
3620 AioContext *aio_context,
3621 JobTxn *txn, Error **errp)
3623 BlockJob *job = NULL;
3624 BdrvDirtyBitmap *bmap = NULL;
3625 int job_flags = JOB_DEFAULT;
3627 if (!backup->has_speed) {
3628 backup->speed = 0;
3630 if (!backup->has_on_source_error) {
3631 backup->on_source_error = BLOCKDEV_ON_ERROR_REPORT;
3633 if (!backup->has_on_target_error) {
3634 backup->on_target_error = BLOCKDEV_ON_ERROR_REPORT;
3636 if (!backup->has_job_id) {
3637 backup->job_id = NULL;
3639 if (!backup->has_auto_finalize) {
3640 backup->auto_finalize = true;
3642 if (!backup->has_auto_dismiss) {
3643 backup->auto_dismiss = true;
3645 if (!backup->has_compress) {
3646 backup->compress = false;
3649 if ((backup->sync == MIRROR_SYNC_MODE_BITMAP) ||
3650 (backup->sync == MIRROR_SYNC_MODE_INCREMENTAL)) {
3651 /* done before desugaring 'incremental' to print the right message */
3652 if (!backup->has_bitmap) {
3653 error_setg(errp, "must provide a valid bitmap name for "
3654 "'%s' sync mode", MirrorSyncMode_str(backup->sync));
3655 return NULL;
3659 if (backup->sync == MIRROR_SYNC_MODE_INCREMENTAL) {
3660 if (backup->has_bitmap_mode &&
3661 backup->bitmap_mode != BITMAP_SYNC_MODE_ON_SUCCESS) {
3662 error_setg(errp, "Bitmap sync mode must be '%s' "
3663 "when using sync mode '%s'",
3664 BitmapSyncMode_str(BITMAP_SYNC_MODE_ON_SUCCESS),
3665 MirrorSyncMode_str(backup->sync));
3666 return NULL;
3668 backup->has_bitmap_mode = true;
3669 backup->sync = MIRROR_SYNC_MODE_BITMAP;
3670 backup->bitmap_mode = BITMAP_SYNC_MODE_ON_SUCCESS;
3673 if (backup->has_bitmap) {
3674 bmap = bdrv_find_dirty_bitmap(bs, backup->bitmap);
3675 if (!bmap) {
3676 error_setg(errp, "Bitmap '%s' could not be found", backup->bitmap);
3677 return NULL;
3679 if (!backup->has_bitmap_mode) {
3680 error_setg(errp, "Bitmap sync mode must be given "
3681 "when providing a bitmap");
3682 return NULL;
3684 if (bdrv_dirty_bitmap_check(bmap, BDRV_BITMAP_ALLOW_RO, errp)) {
3685 return NULL;
3688 /* This does not produce a useful bitmap artifact: */
3689 if (backup->sync == MIRROR_SYNC_MODE_NONE) {
3690 error_setg(errp, "sync mode '%s' does not produce meaningful bitmap"
3691 " outputs", MirrorSyncMode_str(backup->sync));
3692 return NULL;
3695 /* If the bitmap isn't used for input or output, this is useless: */
3696 if (backup->bitmap_mode == BITMAP_SYNC_MODE_NEVER &&
3697 backup->sync != MIRROR_SYNC_MODE_BITMAP) {
3698 error_setg(errp, "Bitmap sync mode '%s' has no meaningful effect"
3699 " when combined with sync mode '%s'",
3700 BitmapSyncMode_str(backup->bitmap_mode),
3701 MirrorSyncMode_str(backup->sync));
3702 return NULL;
3706 if (!backup->has_bitmap && backup->has_bitmap_mode) {
3707 error_setg(errp, "Cannot specify bitmap sync mode without a bitmap");
3708 return NULL;
3711 if (!backup->auto_finalize) {
3712 job_flags |= JOB_MANUAL_FINALIZE;
3714 if (!backup->auto_dismiss) {
3715 job_flags |= JOB_MANUAL_DISMISS;
3718 job = backup_job_create(backup->job_id, bs, target_bs, backup->speed,
3719 backup->sync, bmap, backup->bitmap_mode,
3720 backup->compress,
3721 backup->filter_node_name,
3722 backup->on_source_error,
3723 backup->on_target_error,
3724 job_flags, NULL, NULL, txn, errp);
3725 return job;
3728 void qmp_drive_backup(DriveBackup *backup, Error **errp)
3730 TransactionAction action = {
3731 .type = TRANSACTION_ACTION_KIND_DRIVE_BACKUP,
3732 .u.drive_backup.data = backup,
3734 blockdev_do_action(&action, errp);
3737 BlockDeviceInfoList *qmp_query_named_block_nodes(bool has_flat,
3738 bool flat,
3739 Error **errp)
3741 bool return_flat = has_flat && flat;
3743 return bdrv_named_nodes_list(return_flat, errp);
3746 XDbgBlockGraph *qmp_x_debug_query_block_graph(Error **errp)
3748 return bdrv_get_xdbg_block_graph(errp);
3751 void qmp_blockdev_backup(BlockdevBackup *backup, Error **errp)
3753 TransactionAction action = {
3754 .type = TRANSACTION_ACTION_KIND_BLOCKDEV_BACKUP,
3755 .u.blockdev_backup.data = backup,
3757 blockdev_do_action(&action, errp);
3760 /* Parameter check and block job starting for drive mirroring.
3761 * Caller should hold @device and @target's aio context (must be the same).
3763 static void blockdev_mirror_common(const char *job_id, BlockDriverState *bs,
3764 BlockDriverState *target,
3765 bool has_replaces, const char *replaces,
3766 enum MirrorSyncMode sync,
3767 BlockMirrorBackingMode backing_mode,
3768 bool zero_target,
3769 bool has_speed, int64_t speed,
3770 bool has_granularity, uint32_t granularity,
3771 bool has_buf_size, int64_t buf_size,
3772 bool has_on_source_error,
3773 BlockdevOnError on_source_error,
3774 bool has_on_target_error,
3775 BlockdevOnError on_target_error,
3776 bool has_unmap, bool unmap,
3777 bool has_filter_node_name,
3778 const char *filter_node_name,
3779 bool has_copy_mode, MirrorCopyMode copy_mode,
3780 bool has_auto_finalize, bool auto_finalize,
3781 bool has_auto_dismiss, bool auto_dismiss,
3782 Error **errp)
3784 int job_flags = JOB_DEFAULT;
3786 if (!has_speed) {
3787 speed = 0;
3789 if (!has_on_source_error) {
3790 on_source_error = BLOCKDEV_ON_ERROR_REPORT;
3792 if (!has_on_target_error) {
3793 on_target_error = BLOCKDEV_ON_ERROR_REPORT;
3795 if (!has_granularity) {
3796 granularity = 0;
3798 if (!has_buf_size) {
3799 buf_size = 0;
3801 if (!has_unmap) {
3802 unmap = true;
3804 if (!has_filter_node_name) {
3805 filter_node_name = NULL;
3807 if (!has_copy_mode) {
3808 copy_mode = MIRROR_COPY_MODE_BACKGROUND;
3810 if (has_auto_finalize && !auto_finalize) {
3811 job_flags |= JOB_MANUAL_FINALIZE;
3813 if (has_auto_dismiss && !auto_dismiss) {
3814 job_flags |= JOB_MANUAL_DISMISS;
3817 if (granularity != 0 && (granularity < 512 || granularity > 1048576 * 64)) {
3818 error_setg(errp, QERR_INVALID_PARAMETER_VALUE, "granularity",
3819 "a value in range [512B, 64MB]");
3820 return;
3822 if (granularity & (granularity - 1)) {
3823 error_setg(errp, QERR_INVALID_PARAMETER_VALUE, "granularity",
3824 "power of 2");
3825 return;
3828 if (bdrv_op_is_blocked(bs, BLOCK_OP_TYPE_MIRROR_SOURCE, errp)) {
3829 return;
3831 if (bdrv_op_is_blocked(target, BLOCK_OP_TYPE_MIRROR_TARGET, errp)) {
3832 return;
3835 if (!bs->backing && sync == MIRROR_SYNC_MODE_TOP) {
3836 sync = MIRROR_SYNC_MODE_FULL;
3839 if (has_replaces) {
3840 BlockDriverState *to_replace_bs;
3841 AioContext *replace_aio_context;
3842 int64_t bs_size, replace_size;
3844 bs_size = bdrv_getlength(bs);
3845 if (bs_size < 0) {
3846 error_setg_errno(errp, -bs_size, "Failed to query device's size");
3847 return;
3850 to_replace_bs = check_to_replace_node(bs, replaces, errp);
3851 if (!to_replace_bs) {
3852 return;
3855 replace_aio_context = bdrv_get_aio_context(to_replace_bs);
3856 aio_context_acquire(replace_aio_context);
3857 replace_size = bdrv_getlength(to_replace_bs);
3858 aio_context_release(replace_aio_context);
3860 if (replace_size < 0) {
3861 error_setg_errno(errp, -replace_size,
3862 "Failed to query the replacement node's size");
3863 return;
3865 if (bs_size != replace_size) {
3866 error_setg(errp, "cannot replace image with a mirror image of "
3867 "different size");
3868 return;
3872 /* pass the node name to replace to mirror start since it's loose coupling
3873 * and will allow to check whether the node still exist at mirror completion
3875 mirror_start(job_id, bs, target,
3876 has_replaces ? replaces : NULL, job_flags,
3877 speed, granularity, buf_size, sync, backing_mode, zero_target,
3878 on_source_error, on_target_error, unmap, filter_node_name,
3879 copy_mode, errp);
3882 void qmp_drive_mirror(DriveMirror *arg, Error **errp)
3884 BlockDriverState *bs;
3885 BlockDriverState *source, *target_bs;
3886 AioContext *aio_context;
3887 AioContext *old_context;
3888 BlockMirrorBackingMode backing_mode;
3889 Error *local_err = NULL;
3890 QDict *options = NULL;
3891 int flags;
3892 int64_t size;
3893 const char *format = arg->format;
3894 bool zero_target;
3895 int ret;
3897 bs = qmp_get_root_bs(arg->device, errp);
3898 if (!bs) {
3899 return;
3902 /* Early check to avoid creating target */
3903 if (bdrv_op_is_blocked(bs, BLOCK_OP_TYPE_MIRROR_SOURCE, errp)) {
3904 return;
3907 aio_context = bdrv_get_aio_context(bs);
3908 aio_context_acquire(aio_context);
3910 if (!arg->has_mode) {
3911 arg->mode = NEW_IMAGE_MODE_ABSOLUTE_PATHS;
3914 if (!arg->has_format) {
3915 format = (arg->mode == NEW_IMAGE_MODE_EXISTING
3916 ? NULL : bs->drv->format_name);
3919 flags = bs->open_flags | BDRV_O_RDWR;
3920 source = backing_bs(bs);
3921 if (!source && arg->sync == MIRROR_SYNC_MODE_TOP) {
3922 arg->sync = MIRROR_SYNC_MODE_FULL;
3924 if (arg->sync == MIRROR_SYNC_MODE_NONE) {
3925 source = bs;
3928 size = bdrv_getlength(bs);
3929 if (size < 0) {
3930 error_setg_errno(errp, -size, "bdrv_getlength failed");
3931 goto out;
3934 if (arg->has_replaces) {
3935 if (!arg->has_node_name) {
3936 error_setg(errp, "a node-name must be provided when replacing a"
3937 " named node of the graph");
3938 goto out;
3942 if (arg->mode == NEW_IMAGE_MODE_ABSOLUTE_PATHS) {
3943 backing_mode = MIRROR_SOURCE_BACKING_CHAIN;
3944 } else {
3945 backing_mode = MIRROR_OPEN_BACKING_CHAIN;
3948 /* Don't open backing image in create() */
3949 flags |= BDRV_O_NO_BACKING;
3951 if ((arg->sync == MIRROR_SYNC_MODE_FULL || !source)
3952 && arg->mode != NEW_IMAGE_MODE_EXISTING)
3954 /* create new image w/o backing file */
3955 assert(format);
3956 bdrv_img_create(arg->target, format,
3957 NULL, NULL, NULL, size, flags, false, &local_err);
3958 } else {
3959 switch (arg->mode) {
3960 case NEW_IMAGE_MODE_EXISTING:
3961 break;
3962 case NEW_IMAGE_MODE_ABSOLUTE_PATHS:
3963 /* create new image with backing file */
3964 bdrv_refresh_filename(source);
3965 bdrv_img_create(arg->target, format,
3966 source->filename,
3967 source->drv->format_name,
3968 NULL, size, flags, false, &local_err);
3969 break;
3970 default:
3971 abort();
3975 if (local_err) {
3976 error_propagate(errp, local_err);
3977 goto out;
3980 options = qdict_new();
3981 if (arg->has_node_name) {
3982 qdict_put_str(options, "node-name", arg->node_name);
3984 if (format) {
3985 qdict_put_str(options, "driver", format);
3988 /* Mirroring takes care of copy-on-write using the source's backing
3989 * file.
3991 target_bs = bdrv_open(arg->target, NULL, options, flags, errp);
3992 if (!target_bs) {
3993 goto out;
3996 zero_target = (arg->sync == MIRROR_SYNC_MODE_FULL &&
3997 (arg->mode == NEW_IMAGE_MODE_EXISTING ||
3998 !bdrv_has_zero_init(target_bs)));
4001 /* Honor bdrv_try_set_aio_context() context acquisition requirements. */
4002 old_context = bdrv_get_aio_context(target_bs);
4003 aio_context_release(aio_context);
4004 aio_context_acquire(old_context);
4006 ret = bdrv_try_set_aio_context(target_bs, aio_context, errp);
4007 if (ret < 0) {
4008 bdrv_unref(target_bs);
4009 aio_context_release(old_context);
4010 return;
4013 aio_context_release(old_context);
4014 aio_context_acquire(aio_context);
4016 blockdev_mirror_common(arg->has_job_id ? arg->job_id : NULL, bs, target_bs,
4017 arg->has_replaces, arg->replaces, arg->sync,
4018 backing_mode, zero_target,
4019 arg->has_speed, arg->speed,
4020 arg->has_granularity, arg->granularity,
4021 arg->has_buf_size, arg->buf_size,
4022 arg->has_on_source_error, arg->on_source_error,
4023 arg->has_on_target_error, arg->on_target_error,
4024 arg->has_unmap, arg->unmap,
4025 false, NULL,
4026 arg->has_copy_mode, arg->copy_mode,
4027 arg->has_auto_finalize, arg->auto_finalize,
4028 arg->has_auto_dismiss, arg->auto_dismiss,
4029 &local_err);
4030 bdrv_unref(target_bs);
4031 error_propagate(errp, local_err);
4032 out:
4033 aio_context_release(aio_context);
4036 void qmp_blockdev_mirror(bool has_job_id, const char *job_id,
4037 const char *device, const char *target,
4038 bool has_replaces, const char *replaces,
4039 MirrorSyncMode sync,
4040 bool has_speed, int64_t speed,
4041 bool has_granularity, uint32_t granularity,
4042 bool has_buf_size, int64_t buf_size,
4043 bool has_on_source_error,
4044 BlockdevOnError on_source_error,
4045 bool has_on_target_error,
4046 BlockdevOnError on_target_error,
4047 bool has_filter_node_name,
4048 const char *filter_node_name,
4049 bool has_copy_mode, MirrorCopyMode copy_mode,
4050 bool has_auto_finalize, bool auto_finalize,
4051 bool has_auto_dismiss, bool auto_dismiss,
4052 Error **errp)
4054 BlockDriverState *bs;
4055 BlockDriverState *target_bs;
4056 AioContext *aio_context;
4057 AioContext *old_context;
4058 BlockMirrorBackingMode backing_mode = MIRROR_LEAVE_BACKING_CHAIN;
4059 Error *local_err = NULL;
4060 bool zero_target;
4061 int ret;
4063 bs = qmp_get_root_bs(device, errp);
4064 if (!bs) {
4065 return;
4068 target_bs = bdrv_lookup_bs(target, target, errp);
4069 if (!target_bs) {
4070 return;
4073 zero_target = (sync == MIRROR_SYNC_MODE_FULL);
4075 /* Honor bdrv_try_set_aio_context() context acquisition requirements. */
4076 old_context = bdrv_get_aio_context(target_bs);
4077 aio_context = bdrv_get_aio_context(bs);
4078 aio_context_acquire(old_context);
4080 ret = bdrv_try_set_aio_context(target_bs, aio_context, errp);
4082 aio_context_release(old_context);
4083 aio_context_acquire(aio_context);
4085 if (ret < 0) {
4086 goto out;
4089 blockdev_mirror_common(has_job_id ? job_id : NULL, bs, target_bs,
4090 has_replaces, replaces, sync, backing_mode,
4091 zero_target, has_speed, speed,
4092 has_granularity, granularity,
4093 has_buf_size, buf_size,
4094 has_on_source_error, on_source_error,
4095 has_on_target_error, on_target_error,
4096 true, true,
4097 has_filter_node_name, filter_node_name,
4098 has_copy_mode, copy_mode,
4099 has_auto_finalize, auto_finalize,
4100 has_auto_dismiss, auto_dismiss,
4101 &local_err);
4102 error_propagate(errp, local_err);
4103 out:
4104 aio_context_release(aio_context);
4107 /* Get a block job using its ID and acquire its AioContext */
4108 static BlockJob *find_block_job(const char *id, AioContext **aio_context,
4109 Error **errp)
4111 BlockJob *job;
4113 assert(id != NULL);
4115 *aio_context = NULL;
4117 job = block_job_get(id);
4119 if (!job) {
4120 error_set(errp, ERROR_CLASS_DEVICE_NOT_ACTIVE,
4121 "Block job '%s' not found", id);
4122 return NULL;
4125 *aio_context = blk_get_aio_context(job->blk);
4126 aio_context_acquire(*aio_context);
4128 return job;
4131 void qmp_block_job_set_speed(const char *device, int64_t speed, Error **errp)
4133 AioContext *aio_context;
4134 BlockJob *job = find_block_job(device, &aio_context, errp);
4136 if (!job) {
4137 return;
4140 block_job_set_speed(job, speed, errp);
4141 aio_context_release(aio_context);
4144 void qmp_block_job_cancel(const char *device,
4145 bool has_force, bool force, Error **errp)
4147 AioContext *aio_context;
4148 BlockJob *job = find_block_job(device, &aio_context, errp);
4150 if (!job) {
4151 return;
4154 if (!has_force) {
4155 force = false;
4158 if (job_user_paused(&job->job) && !force) {
4159 error_setg(errp, "The block job for device '%s' is currently paused",
4160 device);
4161 goto out;
4164 trace_qmp_block_job_cancel(job);
4165 job_user_cancel(&job->job, force, errp);
4166 out:
4167 aio_context_release(aio_context);
4170 void qmp_block_job_pause(const char *device, Error **errp)
4172 AioContext *aio_context;
4173 BlockJob *job = find_block_job(device, &aio_context, errp);
4175 if (!job) {
4176 return;
4179 trace_qmp_block_job_pause(job);
4180 job_user_pause(&job->job, errp);
4181 aio_context_release(aio_context);
4184 void qmp_block_job_resume(const char *device, Error **errp)
4186 AioContext *aio_context;
4187 BlockJob *job = find_block_job(device, &aio_context, errp);
4189 if (!job) {
4190 return;
4193 trace_qmp_block_job_resume(job);
4194 job_user_resume(&job->job, errp);
4195 aio_context_release(aio_context);
4198 void qmp_block_job_complete(const char *device, Error **errp)
4200 AioContext *aio_context;
4201 BlockJob *job = find_block_job(device, &aio_context, errp);
4203 if (!job) {
4204 return;
4207 trace_qmp_block_job_complete(job);
4208 job_complete(&job->job, errp);
4209 aio_context_release(aio_context);
4212 void qmp_block_job_finalize(const char *id, Error **errp)
4214 AioContext *aio_context;
4215 BlockJob *job = find_block_job(id, &aio_context, errp);
4217 if (!job) {
4218 return;
4221 trace_qmp_block_job_finalize(job);
4222 job_finalize(&job->job, errp);
4223 aio_context_release(aio_context);
4226 void qmp_block_job_dismiss(const char *id, Error **errp)
4228 AioContext *aio_context;
4229 BlockJob *bjob = find_block_job(id, &aio_context, errp);
4230 Job *job;
4232 if (!bjob) {
4233 return;
4236 trace_qmp_block_job_dismiss(bjob);
4237 job = &bjob->job;
4238 job_dismiss(&job, errp);
4239 aio_context_release(aio_context);
4242 void qmp_change_backing_file(const char *device,
4243 const char *image_node_name,
4244 const char *backing_file,
4245 Error **errp)
4247 BlockDriverState *bs = NULL;
4248 AioContext *aio_context;
4249 BlockDriverState *image_bs = NULL;
4250 Error *local_err = NULL;
4251 bool ro;
4252 int ret;
4254 bs = qmp_get_root_bs(device, errp);
4255 if (!bs) {
4256 return;
4259 aio_context = bdrv_get_aio_context(bs);
4260 aio_context_acquire(aio_context);
4262 image_bs = bdrv_lookup_bs(NULL, image_node_name, &local_err);
4263 if (local_err) {
4264 error_propagate(errp, local_err);
4265 goto out;
4268 if (!image_bs) {
4269 error_setg(errp, "image file not found");
4270 goto out;
4273 if (bdrv_find_base(image_bs) == image_bs) {
4274 error_setg(errp, "not allowing backing file change on an image "
4275 "without a backing file");
4276 goto out;
4279 /* even though we are not necessarily operating on bs, we need it to
4280 * determine if block ops are currently prohibited on the chain */
4281 if (bdrv_op_is_blocked(bs, BLOCK_OP_TYPE_CHANGE, errp)) {
4282 goto out;
4285 /* final sanity check */
4286 if (!bdrv_chain_contains(bs, image_bs)) {
4287 error_setg(errp, "'%s' and image file are not in the same chain",
4288 device);
4289 goto out;
4292 /* if not r/w, reopen to make r/w */
4293 ro = bdrv_is_read_only(image_bs);
4295 if (ro) {
4296 if (bdrv_reopen_set_read_only(image_bs, false, errp) != 0) {
4297 goto out;
4301 ret = bdrv_change_backing_file(image_bs, backing_file,
4302 image_bs->drv ? image_bs->drv->format_name : "");
4304 if (ret < 0) {
4305 error_setg_errno(errp, -ret, "Could not change backing file to '%s'",
4306 backing_file);
4307 /* don't exit here, so we can try to restore open flags if
4308 * appropriate */
4311 if (ro) {
4312 bdrv_reopen_set_read_only(image_bs, true, &local_err);
4313 error_propagate(errp, local_err);
4316 out:
4317 aio_context_release(aio_context);
4320 void hmp_drive_add_node(Monitor *mon, const char *optstr)
4322 QemuOpts *opts;
4323 QDict *qdict;
4324 Error *local_err = NULL;
4326 opts = qemu_opts_parse_noisily(&qemu_drive_opts, optstr, false);
4327 if (!opts) {
4328 return;
4331 qdict = qemu_opts_to_qdict(opts, NULL);
4333 if (!qdict_get_try_str(qdict, "node-name")) {
4334 qobject_unref(qdict);
4335 error_report("'node-name' needs to be specified");
4336 goto out;
4339 BlockDriverState *bs = bds_tree_init(qdict, &local_err);
4340 if (!bs) {
4341 error_report_err(local_err);
4342 goto out;
4345 QTAILQ_INSERT_TAIL(&monitor_bdrv_states, bs, monitor_list);
4347 out:
4348 qemu_opts_del(opts);
4351 void qmp_blockdev_add(BlockdevOptions *options, Error **errp)
4353 BlockDriverState *bs;
4354 QObject *obj;
4355 Visitor *v = qobject_output_visitor_new(&obj);
4356 QDict *qdict;
4357 Error *local_err = NULL;
4359 visit_type_BlockdevOptions(v, NULL, &options, &local_err);
4360 if (local_err) {
4361 error_propagate(errp, local_err);
4362 goto fail;
4365 visit_complete(v, &obj);
4366 qdict = qobject_to(QDict, obj);
4368 qdict_flatten(qdict);
4370 if (!qdict_get_try_str(qdict, "node-name")) {
4371 error_setg(errp, "'node-name' must be specified for the root node");
4372 goto fail;
4375 bs = bds_tree_init(qdict, errp);
4376 if (!bs) {
4377 goto fail;
4380 QTAILQ_INSERT_TAIL(&monitor_bdrv_states, bs, monitor_list);
4382 fail:
4383 visit_free(v);
4386 void qmp_x_blockdev_reopen(BlockdevOptions *options, Error **errp)
4388 BlockDriverState *bs;
4389 AioContext *ctx;
4390 QObject *obj;
4391 Visitor *v = qobject_output_visitor_new(&obj);
4392 Error *local_err = NULL;
4393 BlockReopenQueue *queue;
4394 QDict *qdict;
4396 /* Check for the selected node name */
4397 if (!options->has_node_name) {
4398 error_setg(errp, "Node name not specified");
4399 goto fail;
4402 bs = bdrv_find_node(options->node_name);
4403 if (!bs) {
4404 error_setg(errp, "Cannot find node named '%s'", options->node_name);
4405 goto fail;
4408 /* Put all options in a QDict and flatten it */
4409 visit_type_BlockdevOptions(v, NULL, &options, &local_err);
4410 if (local_err) {
4411 error_propagate(errp, local_err);
4412 goto fail;
4415 visit_complete(v, &obj);
4416 qdict = qobject_to(QDict, obj);
4418 qdict_flatten(qdict);
4420 /* Perform the reopen operation */
4421 ctx = bdrv_get_aio_context(bs);
4422 aio_context_acquire(ctx);
4423 bdrv_subtree_drained_begin(bs);
4424 queue = bdrv_reopen_queue(NULL, bs, qdict, false);
4425 bdrv_reopen_multiple(queue, errp);
4426 bdrv_subtree_drained_end(bs);
4427 aio_context_release(ctx);
4429 fail:
4430 visit_free(v);
4433 void qmp_blockdev_del(const char *node_name, Error **errp)
4435 AioContext *aio_context;
4436 BlockDriverState *bs;
4438 bs = bdrv_find_node(node_name);
4439 if (!bs) {
4440 error_setg(errp, "Cannot find node %s", node_name);
4441 return;
4443 if (bdrv_has_blk(bs)) {
4444 error_setg(errp, "Node %s is in use", node_name);
4445 return;
4447 aio_context = bdrv_get_aio_context(bs);
4448 aio_context_acquire(aio_context);
4450 if (bdrv_op_is_blocked(bs, BLOCK_OP_TYPE_DRIVE_DEL, errp)) {
4451 goto out;
4454 if (!QTAILQ_IN_USE(bs, monitor_list)) {
4455 error_setg(errp, "Node %s is not owned by the monitor",
4456 bs->node_name);
4457 goto out;
4460 if (bs->refcnt > 1) {
4461 error_setg(errp, "Block device %s is in use",
4462 bdrv_get_device_or_node_name(bs));
4463 goto out;
4466 QTAILQ_REMOVE(&monitor_bdrv_states, bs, monitor_list);
4467 bdrv_unref(bs);
4469 out:
4470 aio_context_release(aio_context);
4473 static BdrvChild *bdrv_find_child(BlockDriverState *parent_bs,
4474 const char *child_name)
4476 BdrvChild *child;
4478 QLIST_FOREACH(child, &parent_bs->children, next) {
4479 if (strcmp(child->name, child_name) == 0) {
4480 return child;
4484 return NULL;
4487 void qmp_x_blockdev_change(const char *parent, bool has_child,
4488 const char *child, bool has_node,
4489 const char *node, Error **errp)
4491 BlockDriverState *parent_bs, *new_bs = NULL;
4492 BdrvChild *p_child;
4494 parent_bs = bdrv_lookup_bs(parent, parent, errp);
4495 if (!parent_bs) {
4496 return;
4499 if (has_child == has_node) {
4500 if (has_child) {
4501 error_setg(errp, "The parameters child and node are in conflict");
4502 } else {
4503 error_setg(errp, "Either child or node must be specified");
4505 return;
4508 if (has_child) {
4509 p_child = bdrv_find_child(parent_bs, child);
4510 if (!p_child) {
4511 error_setg(errp, "Node '%s' does not have child '%s'",
4512 parent, child);
4513 return;
4515 bdrv_del_child(parent_bs, p_child, errp);
4518 if (has_node) {
4519 new_bs = bdrv_find_node(node);
4520 if (!new_bs) {
4521 error_setg(errp, "Node '%s' not found", node);
4522 return;
4524 bdrv_add_child(parent_bs, new_bs, errp);
4528 BlockJobInfoList *qmp_query_block_jobs(Error **errp)
4530 BlockJobInfoList *head = NULL, **p_next = &head;
4531 BlockJob *job;
4533 for (job = block_job_next(NULL); job; job = block_job_next(job)) {
4534 BlockJobInfoList *elem;
4535 AioContext *aio_context;
4537 if (block_job_is_internal(job)) {
4538 continue;
4540 elem = g_new0(BlockJobInfoList, 1);
4541 aio_context = blk_get_aio_context(job->blk);
4542 aio_context_acquire(aio_context);
4543 elem->value = block_job_query(job, errp);
4544 aio_context_release(aio_context);
4545 if (!elem->value) {
4546 g_free(elem);
4547 qapi_free_BlockJobInfoList(head);
4548 return NULL;
4550 *p_next = elem;
4551 p_next = &elem->next;
4554 return head;
4557 void qmp_x_blockdev_set_iothread(const char *node_name, StrOrNull *iothread,
4558 bool has_force, bool force, Error **errp)
4560 AioContext *old_context;
4561 AioContext *new_context;
4562 BlockDriverState *bs;
4564 bs = bdrv_find_node(node_name);
4565 if (!bs) {
4566 error_setg(errp, "Cannot find node %s", node_name);
4567 return;
4570 /* Protects against accidents. */
4571 if (!(has_force && force) && bdrv_has_blk(bs)) {
4572 error_setg(errp, "Node %s is associated with a BlockBackend and could "
4573 "be in use (use force=true to override this check)",
4574 node_name);
4575 return;
4578 if (iothread->type == QTYPE_QSTRING) {
4579 IOThread *obj = iothread_by_id(iothread->u.s);
4580 if (!obj) {
4581 error_setg(errp, "Cannot find iothread %s", iothread->u.s);
4582 return;
4585 new_context = iothread_get_aio_context(obj);
4586 } else {
4587 new_context = qemu_get_aio_context();
4590 old_context = bdrv_get_aio_context(bs);
4591 aio_context_acquire(old_context);
4593 bdrv_try_set_aio_context(bs, new_context, errp);
4595 aio_context_release(old_context);
4598 void qmp_block_latency_histogram_set(
4599 const char *id,
4600 bool has_boundaries, uint64List *boundaries,
4601 bool has_boundaries_read, uint64List *boundaries_read,
4602 bool has_boundaries_write, uint64List *boundaries_write,
4603 bool has_boundaries_flush, uint64List *boundaries_flush,
4604 Error **errp)
4606 BlockBackend *blk = qmp_get_blk(NULL, id, errp);
4607 BlockAcctStats *stats;
4608 int ret;
4610 if (!blk) {
4611 return;
4614 stats = blk_get_stats(blk);
4616 if (!has_boundaries && !has_boundaries_read && !has_boundaries_write &&
4617 !has_boundaries_flush)
4619 block_latency_histograms_clear(stats);
4620 return;
4623 if (has_boundaries || has_boundaries_read) {
4624 ret = block_latency_histogram_set(
4625 stats, BLOCK_ACCT_READ,
4626 has_boundaries_read ? boundaries_read : boundaries);
4627 if (ret) {
4628 error_setg(errp, "Device '%s' set read boundaries fail", id);
4629 return;
4633 if (has_boundaries || has_boundaries_write) {
4634 ret = block_latency_histogram_set(
4635 stats, BLOCK_ACCT_WRITE,
4636 has_boundaries_write ? boundaries_write : boundaries);
4637 if (ret) {
4638 error_setg(errp, "Device '%s' set write boundaries fail", id);
4639 return;
4643 if (has_boundaries || has_boundaries_flush) {
4644 ret = block_latency_histogram_set(
4645 stats, BLOCK_ACCT_FLUSH,
4646 has_boundaries_flush ? boundaries_flush : boundaries);
4647 if (ret) {
4648 error_setg(errp, "Device '%s' set flush boundaries fail", id);
4649 return;
4654 QemuOptsList qemu_common_drive_opts = {
4655 .name = "drive",
4656 .head = QTAILQ_HEAD_INITIALIZER(qemu_common_drive_opts.head),
4657 .desc = {
4659 .name = "snapshot",
4660 .type = QEMU_OPT_BOOL,
4661 .help = "enable/disable snapshot mode",
4663 .name = "aio",
4664 .type = QEMU_OPT_STRING,
4665 .help = "host AIO implementation (threads, native, io_uring)",
4667 .name = BDRV_OPT_CACHE_WB,
4668 .type = QEMU_OPT_BOOL,
4669 .help = "Enable writeback mode",
4671 .name = "format",
4672 .type = QEMU_OPT_STRING,
4673 .help = "disk format (raw, qcow2, ...)",
4675 .name = "rerror",
4676 .type = QEMU_OPT_STRING,
4677 .help = "read error action",
4679 .name = "werror",
4680 .type = QEMU_OPT_STRING,
4681 .help = "write error action",
4683 .name = BDRV_OPT_READ_ONLY,
4684 .type = QEMU_OPT_BOOL,
4685 .help = "open drive file as read-only",
4688 THROTTLE_OPTS,
4691 .name = "throttling.group",
4692 .type = QEMU_OPT_STRING,
4693 .help = "name of the block throttling group",
4695 .name = "copy-on-read",
4696 .type = QEMU_OPT_BOOL,
4697 .help = "copy read data from backing file into image file",
4699 .name = "detect-zeroes",
4700 .type = QEMU_OPT_STRING,
4701 .help = "try to optimize zero writes (off, on, unmap)",
4703 .name = "stats-account-invalid",
4704 .type = QEMU_OPT_BOOL,
4705 .help = "whether to account for invalid I/O operations "
4706 "in the statistics",
4708 .name = "stats-account-failed",
4709 .type = QEMU_OPT_BOOL,
4710 .help = "whether to account for failed I/O operations "
4711 "in the statistics",
4713 { /* end of list */ }
4717 QemuOptsList qemu_drive_opts = {
4718 .name = "drive",
4719 .head = QTAILQ_HEAD_INITIALIZER(qemu_drive_opts.head),
4720 .desc = {
4722 * no elements => accept any params
4723 * validation will happen later
4725 { /* end of list */ }