target/arm: Restore M-profile CONTROL.SPSEL before any tailchaining
[qemu/ar7.git] / blockdev.c
blobdcf8c8d2ab95d45aa9efdab63a09308648612adb
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/config-file.h"
44 #include "qapi/qapi-commands-block.h"
45 #include "qapi/qapi-commands-transaction.h"
46 #include "qapi/qapi-visit-block-core.h"
47 #include "qapi/qmp/qdict.h"
48 #include "qapi/qmp/qnum.h"
49 #include "qapi/qmp/qstring.h"
50 #include "qapi/error.h"
51 #include "qapi/qmp/qerror.h"
52 #include "qapi/qmp/qlist.h"
53 #include "qapi/qobject-output-visitor.h"
54 #include "sysemu/sysemu.h"
55 #include "sysemu/iothread.h"
56 #include "block/block_int.h"
57 #include "block/trace.h"
58 #include "sysemu/arch_init.h"
59 #include "sysemu/qtest.h"
60 #include "qemu/cutils.h"
61 #include "qemu/help_option.h"
62 #include "qemu/throttle-options.h"
64 static QTAILQ_HEAD(, BlockDriverState) monitor_bdrv_states =
65 QTAILQ_HEAD_INITIALIZER(monitor_bdrv_states);
67 static int do_open_tray(const char *blk_name, const char *qdev_id,
68 bool force, Error **errp);
69 static void blockdev_remove_medium(bool has_device, const char *device,
70 bool has_id, const char *id, Error **errp);
71 static void blockdev_insert_medium(bool has_device, const char *device,
72 bool has_id, const char *id,
73 const char *node_name, Error **errp);
75 static const char *const if_name[IF_COUNT] = {
76 [IF_NONE] = "none",
77 [IF_IDE] = "ide",
78 [IF_SCSI] = "scsi",
79 [IF_FLOPPY] = "floppy",
80 [IF_PFLASH] = "pflash",
81 [IF_MTD] = "mtd",
82 [IF_SD] = "sd",
83 [IF_VIRTIO] = "virtio",
84 [IF_XEN] = "xen",
87 static int if_max_devs[IF_COUNT] = {
89 * Do not change these numbers! They govern how drive option
90 * index maps to unit and bus. That mapping is ABI.
92 * All controllers used to implement if=T drives need to support
93 * if_max_devs[T] units, for any T with if_max_devs[T] != 0.
94 * Otherwise, some index values map to "impossible" bus, unit
95 * values.
97 * For instance, if you change [IF_SCSI] to 255, -drive
98 * if=scsi,index=12 no longer means bus=1,unit=5, but
99 * bus=0,unit=12. With an lsi53c895a controller (7 units max),
100 * the drive can't be set up. Regression.
102 [IF_IDE] = 2,
103 [IF_SCSI] = 7,
107 * Boards may call this to offer board-by-board overrides
108 * of the default, global values.
110 void override_max_devs(BlockInterfaceType type, int max_devs)
112 BlockBackend *blk;
113 DriveInfo *dinfo;
115 if (max_devs <= 0) {
116 return;
119 for (blk = blk_next(NULL); blk; blk = blk_next(blk)) {
120 dinfo = blk_legacy_dinfo(blk);
121 if (dinfo->type == type) {
122 fprintf(stderr, "Cannot override units-per-bus property of"
123 " the %s interface, because a drive of that type has"
124 " already been added.\n", if_name[type]);
125 g_assert_not_reached();
129 if_max_devs[type] = max_devs;
133 * We automatically delete the drive when a device using it gets
134 * unplugged. Questionable feature, but we can't just drop it.
135 * Device models call blockdev_mark_auto_del() to schedule the
136 * automatic deletion, and generic qdev code calls blockdev_auto_del()
137 * when deletion is actually safe.
139 void blockdev_mark_auto_del(BlockBackend *blk)
141 DriveInfo *dinfo = blk_legacy_dinfo(blk);
142 BlockDriverState *bs = blk_bs(blk);
143 AioContext *aio_context;
145 if (!dinfo) {
146 return;
149 if (bs) {
150 aio_context = bdrv_get_aio_context(bs);
151 aio_context_acquire(aio_context);
153 if (bs->job) {
154 job_cancel(&bs->job->job, false);
157 aio_context_release(aio_context);
160 dinfo->auto_del = 1;
163 void blockdev_auto_del(BlockBackend *blk)
165 DriveInfo *dinfo = blk_legacy_dinfo(blk);
167 if (dinfo && dinfo->auto_del) {
168 monitor_remove_blk(blk);
169 blk_unref(blk);
174 * Returns the current mapping of how many units per bus
175 * a particular interface can support.
177 * A positive integer indicates n units per bus.
178 * 0 implies the mapping has not been established.
179 * -1 indicates an invalid BlockInterfaceType was given.
181 int drive_get_max_devs(BlockInterfaceType type)
183 if (type >= IF_IDE && type < IF_COUNT) {
184 return if_max_devs[type];
187 return -1;
190 static int drive_index_to_bus_id(BlockInterfaceType type, int index)
192 int max_devs = if_max_devs[type];
193 return max_devs ? index / max_devs : 0;
196 static int drive_index_to_unit_id(BlockInterfaceType type, int index)
198 int max_devs = if_max_devs[type];
199 return max_devs ? index % max_devs : index;
202 QemuOpts *drive_def(const char *optstr)
204 return qemu_opts_parse_noisily(qemu_find_opts("drive"), optstr, false);
207 QemuOpts *drive_add(BlockInterfaceType type, int index, const char *file,
208 const char *optstr)
210 QemuOpts *opts;
212 opts = drive_def(optstr);
213 if (!opts) {
214 return NULL;
216 if (type != IF_DEFAULT) {
217 qemu_opt_set(opts, "if", if_name[type], &error_abort);
219 if (index >= 0) {
220 qemu_opt_set_number(opts, "index", index, &error_abort);
222 if (file)
223 qemu_opt_set(opts, "file", file, &error_abort);
224 return opts;
227 DriveInfo *drive_get(BlockInterfaceType type, int bus, int unit)
229 BlockBackend *blk;
230 DriveInfo *dinfo;
232 for (blk = blk_next(NULL); blk; blk = blk_next(blk)) {
233 dinfo = blk_legacy_dinfo(blk);
234 if (dinfo && dinfo->type == type
235 && dinfo->bus == bus && dinfo->unit == unit) {
236 return dinfo;
240 return NULL;
243 void drive_check_orphaned(void)
245 BlockBackend *blk;
246 DriveInfo *dinfo;
247 Location loc;
248 bool orphans = false;
250 for (blk = blk_next(NULL); blk; blk = blk_next(blk)) {
251 dinfo = blk_legacy_dinfo(blk);
252 if (!blk_get_attached_dev(blk) && !dinfo->is_default &&
253 dinfo->type != IF_NONE) {
254 loc_push_none(&loc);
255 qemu_opts_loc_restore(dinfo->opts);
256 error_report("machine type does not support"
257 " if=%s,bus=%d,unit=%d",
258 if_name[dinfo->type], dinfo->bus, dinfo->unit);
259 loc_pop(&loc);
260 orphans = true;
264 if (orphans) {
265 exit(1);
269 DriveInfo *drive_get_by_index(BlockInterfaceType type, int index)
271 return drive_get(type,
272 drive_index_to_bus_id(type, index),
273 drive_index_to_unit_id(type, index));
276 int drive_get_max_bus(BlockInterfaceType type)
278 int max_bus;
279 BlockBackend *blk;
280 DriveInfo *dinfo;
282 max_bus = -1;
283 for (blk = blk_next(NULL); blk; blk = blk_next(blk)) {
284 dinfo = blk_legacy_dinfo(blk);
285 if (dinfo && dinfo->type == type && dinfo->bus > max_bus) {
286 max_bus = dinfo->bus;
289 return max_bus;
292 /* Get a block device. This should only be used for single-drive devices
293 (e.g. SD/Floppy/MTD). Multi-disk devices (scsi/ide) should use the
294 appropriate bus. */
295 DriveInfo *drive_get_next(BlockInterfaceType type)
297 static int next_block_unit[IF_COUNT];
299 return drive_get(type, 0, next_block_unit[type]++);
302 static void bdrv_format_print(void *opaque, const char *name)
304 error_printf(" %s", name);
307 typedef struct {
308 QEMUBH *bh;
309 BlockDriverState *bs;
310 } BDRVPutRefBH;
312 static int parse_block_error_action(const char *buf, bool is_read, Error **errp)
314 if (!strcmp(buf, "ignore")) {
315 return BLOCKDEV_ON_ERROR_IGNORE;
316 } else if (!is_read && !strcmp(buf, "enospc")) {
317 return BLOCKDEV_ON_ERROR_ENOSPC;
318 } else if (!strcmp(buf, "stop")) {
319 return BLOCKDEV_ON_ERROR_STOP;
320 } else if (!strcmp(buf, "report")) {
321 return BLOCKDEV_ON_ERROR_REPORT;
322 } else {
323 error_setg(errp, "'%s' invalid %s error action",
324 buf, is_read ? "read" : "write");
325 return -1;
329 static bool parse_stats_intervals(BlockAcctStats *stats, QList *intervals,
330 Error **errp)
332 const QListEntry *entry;
333 for (entry = qlist_first(intervals); entry; entry = qlist_next(entry)) {
334 switch (qobject_type(entry->value)) {
336 case QTYPE_QSTRING: {
337 unsigned long long length;
338 const char *str = qstring_get_str(qobject_to(QString,
339 entry->value));
340 if (parse_uint_full(str, &length, 10) == 0 &&
341 length > 0 && length <= UINT_MAX) {
342 block_acct_add_interval(stats, (unsigned) length);
343 } else {
344 error_setg(errp, "Invalid interval length: %s", str);
345 return false;
347 break;
350 case QTYPE_QNUM: {
351 int64_t length = qnum_get_int(qobject_to(QNum, entry->value));
353 if (length > 0 && length <= UINT_MAX) {
354 block_acct_add_interval(stats, (unsigned) length);
355 } else {
356 error_setg(errp, "Invalid interval length: %" PRId64, length);
357 return false;
359 break;
362 default:
363 error_setg(errp, "The specification of stats-intervals is invalid");
364 return false;
367 return true;
370 typedef enum { MEDIA_DISK, MEDIA_CDROM } DriveMediaType;
372 /* All parameters but @opts are optional and may be set to NULL. */
373 static void extract_common_blockdev_options(QemuOpts *opts, int *bdrv_flags,
374 const char **throttling_group, ThrottleConfig *throttle_cfg,
375 BlockdevDetectZeroesOptions *detect_zeroes, Error **errp)
377 Error *local_error = NULL;
378 const char *aio;
380 if (bdrv_flags) {
381 if (qemu_opt_get_bool(opts, "copy-on-read", false)) {
382 *bdrv_flags |= BDRV_O_COPY_ON_READ;
385 if ((aio = qemu_opt_get(opts, "aio")) != NULL) {
386 if (!strcmp(aio, "native")) {
387 *bdrv_flags |= BDRV_O_NATIVE_AIO;
388 } else if (!strcmp(aio, "threads")) {
389 /* this is the default */
390 } else {
391 error_setg(errp, "invalid aio option");
392 return;
397 /* disk I/O throttling */
398 if (throttling_group) {
399 *throttling_group = qemu_opt_get(opts, "throttling.group");
402 if (throttle_cfg) {
403 throttle_config_init(throttle_cfg);
404 throttle_cfg->buckets[THROTTLE_BPS_TOTAL].avg =
405 qemu_opt_get_number(opts, "throttling.bps-total", 0);
406 throttle_cfg->buckets[THROTTLE_BPS_READ].avg =
407 qemu_opt_get_number(opts, "throttling.bps-read", 0);
408 throttle_cfg->buckets[THROTTLE_BPS_WRITE].avg =
409 qemu_opt_get_number(opts, "throttling.bps-write", 0);
410 throttle_cfg->buckets[THROTTLE_OPS_TOTAL].avg =
411 qemu_opt_get_number(opts, "throttling.iops-total", 0);
412 throttle_cfg->buckets[THROTTLE_OPS_READ].avg =
413 qemu_opt_get_number(opts, "throttling.iops-read", 0);
414 throttle_cfg->buckets[THROTTLE_OPS_WRITE].avg =
415 qemu_opt_get_number(opts, "throttling.iops-write", 0);
417 throttle_cfg->buckets[THROTTLE_BPS_TOTAL].max =
418 qemu_opt_get_number(opts, "throttling.bps-total-max", 0);
419 throttle_cfg->buckets[THROTTLE_BPS_READ].max =
420 qemu_opt_get_number(opts, "throttling.bps-read-max", 0);
421 throttle_cfg->buckets[THROTTLE_BPS_WRITE].max =
422 qemu_opt_get_number(opts, "throttling.bps-write-max", 0);
423 throttle_cfg->buckets[THROTTLE_OPS_TOTAL].max =
424 qemu_opt_get_number(opts, "throttling.iops-total-max", 0);
425 throttle_cfg->buckets[THROTTLE_OPS_READ].max =
426 qemu_opt_get_number(opts, "throttling.iops-read-max", 0);
427 throttle_cfg->buckets[THROTTLE_OPS_WRITE].max =
428 qemu_opt_get_number(opts, "throttling.iops-write-max", 0);
430 throttle_cfg->buckets[THROTTLE_BPS_TOTAL].burst_length =
431 qemu_opt_get_number(opts, "throttling.bps-total-max-length", 1);
432 throttle_cfg->buckets[THROTTLE_BPS_READ].burst_length =
433 qemu_opt_get_number(opts, "throttling.bps-read-max-length", 1);
434 throttle_cfg->buckets[THROTTLE_BPS_WRITE].burst_length =
435 qemu_opt_get_number(opts, "throttling.bps-write-max-length", 1);
436 throttle_cfg->buckets[THROTTLE_OPS_TOTAL].burst_length =
437 qemu_opt_get_number(opts, "throttling.iops-total-max-length", 1);
438 throttle_cfg->buckets[THROTTLE_OPS_READ].burst_length =
439 qemu_opt_get_number(opts, "throttling.iops-read-max-length", 1);
440 throttle_cfg->buckets[THROTTLE_OPS_WRITE].burst_length =
441 qemu_opt_get_number(opts, "throttling.iops-write-max-length", 1);
443 throttle_cfg->op_size =
444 qemu_opt_get_number(opts, "throttling.iops-size", 0);
446 if (!throttle_is_valid(throttle_cfg, errp)) {
447 return;
451 if (detect_zeroes) {
452 *detect_zeroes =
453 qapi_enum_parse(&BlockdevDetectZeroesOptions_lookup,
454 qemu_opt_get(opts, "detect-zeroes"),
455 BLOCKDEV_DETECT_ZEROES_OPTIONS_OFF,
456 &local_error);
457 if (local_error) {
458 error_propagate(errp, local_error);
459 return;
464 /* Takes the ownership of bs_opts */
465 static BlockBackend *blockdev_init(const char *file, QDict *bs_opts,
466 Error **errp)
468 const char *buf;
469 int bdrv_flags = 0;
470 int on_read_error, on_write_error;
471 bool account_invalid, account_failed;
472 bool writethrough, read_only;
473 BlockBackend *blk;
474 BlockDriverState *bs;
475 ThrottleConfig cfg;
476 int snapshot = 0;
477 Error *error = NULL;
478 QemuOpts *opts;
479 QDict *interval_dict = NULL;
480 QList *interval_list = NULL;
481 const char *id;
482 BlockdevDetectZeroesOptions detect_zeroes =
483 BLOCKDEV_DETECT_ZEROES_OPTIONS_OFF;
484 const char *throttling_group = NULL;
486 /* Check common options by copying from bs_opts to opts, all other options
487 * stay in bs_opts for processing by bdrv_open(). */
488 id = qdict_get_try_str(bs_opts, "id");
489 opts = qemu_opts_create(&qemu_common_drive_opts, id, 1, &error);
490 if (error) {
491 error_propagate(errp, error);
492 goto err_no_opts;
495 qemu_opts_absorb_qdict(opts, bs_opts, &error);
496 if (error) {
497 error_propagate(errp, error);
498 goto early_err;
501 if (id) {
502 qdict_del(bs_opts, "id");
505 /* extract parameters */
506 snapshot = qemu_opt_get_bool(opts, "snapshot", 0);
508 account_invalid = qemu_opt_get_bool(opts, "stats-account-invalid", true);
509 account_failed = qemu_opt_get_bool(opts, "stats-account-failed", true);
511 writethrough = !qemu_opt_get_bool(opts, BDRV_OPT_CACHE_WB, true);
513 id = qemu_opts_id(opts);
515 qdict_extract_subqdict(bs_opts, &interval_dict, "stats-intervals.");
516 qdict_array_split(interval_dict, &interval_list);
518 if (qdict_size(interval_dict) != 0) {
519 error_setg(errp, "Invalid option stats-intervals.%s",
520 qdict_first(interval_dict)->key);
521 goto early_err;
524 extract_common_blockdev_options(opts, &bdrv_flags, &throttling_group, &cfg,
525 &detect_zeroes, &error);
526 if (error) {
527 error_propagate(errp, error);
528 goto early_err;
531 if ((buf = qemu_opt_get(opts, "format")) != NULL) {
532 if (is_help_option(buf)) {
533 error_printf("Supported formats:");
534 bdrv_iterate_format(bdrv_format_print, NULL);
535 error_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(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 assert((bdrv_flags & BDRV_O_CACHE_MASK) == 0);
595 if (runstate_check(RUN_STATE_INMIGRATE)) {
596 bdrv_flags |= BDRV_O_INACTIVE;
599 blk = blk_new_open(file, NULL, bs_opts, bdrv_flags, errp);
600 if (!blk) {
601 goto err_no_bs_opts;
603 bs = blk_bs(blk);
605 bs->detect_zeroes = detect_zeroes;
607 block_acct_setup(blk_get_stats(blk), account_invalid, account_failed);
609 if (!parse_stats_intervals(blk_get_stats(blk), interval_list, errp)) {
610 blk_unref(blk);
611 blk = NULL;
612 goto err_no_bs_opts;
616 /* disk I/O throttling */
617 if (throttle_enabled(&cfg)) {
618 if (!throttling_group) {
619 throttling_group = id;
621 blk_io_limits_enable(blk, throttling_group);
622 blk_set_io_limits(blk, &cfg);
625 blk_set_enable_write_cache(blk, !writethrough);
626 blk_set_on_error(blk, on_read_error, on_write_error);
628 if (!monitor_add_blk(blk, id, errp)) {
629 blk_unref(blk);
630 blk = NULL;
631 goto err_no_bs_opts;
634 err_no_bs_opts:
635 qemu_opts_del(opts);
636 qobject_unref(interval_dict);
637 qobject_unref(interval_list);
638 return blk;
640 early_err:
641 qemu_opts_del(opts);
642 qobject_unref(interval_dict);
643 qobject_unref(interval_list);
644 err_no_opts:
645 qobject_unref(bs_opts);
646 return NULL;
649 /* Takes the ownership of bs_opts */
650 static BlockDriverState *bds_tree_init(QDict *bs_opts, Error **errp)
652 int bdrv_flags = 0;
654 /* bdrv_open() defaults to the values in bdrv_flags (for compatibility
655 * with other callers) rather than what we want as the real defaults.
656 * Apply the defaults here instead. */
657 qdict_set_default_str(bs_opts, BDRV_OPT_CACHE_DIRECT, "off");
658 qdict_set_default_str(bs_opts, BDRV_OPT_CACHE_NO_FLUSH, "off");
659 qdict_set_default_str(bs_opts, BDRV_OPT_READ_ONLY, "off");
661 if (runstate_check(RUN_STATE_INMIGRATE)) {
662 bdrv_flags |= BDRV_O_INACTIVE;
665 return bdrv_open(NULL, NULL, bs_opts, bdrv_flags, errp);
668 void blockdev_close_all_bdrv_states(void)
670 BlockDriverState *bs, *next_bs;
672 QTAILQ_FOREACH_SAFE(bs, &monitor_bdrv_states, monitor_list, next_bs) {
673 AioContext *ctx = bdrv_get_aio_context(bs);
675 aio_context_acquire(ctx);
676 bdrv_unref(bs);
677 aio_context_release(ctx);
681 /* Iterates over the list of monitor-owned BlockDriverStates */
682 BlockDriverState *bdrv_next_monitor_owned(BlockDriverState *bs)
684 return bs ? QTAILQ_NEXT(bs, monitor_list)
685 : QTAILQ_FIRST(&monitor_bdrv_states);
688 static void qemu_opt_rename(QemuOpts *opts, const char *from, const char *to,
689 Error **errp)
691 const char *value;
693 value = qemu_opt_get(opts, from);
694 if (value) {
695 if (qemu_opt_find(opts, to)) {
696 error_setg(errp, "'%s' and its alias '%s' can't be used at the "
697 "same time", to, from);
698 return;
702 /* rename all items in opts */
703 while ((value = qemu_opt_get(opts, from))) {
704 qemu_opt_set(opts, to, value, &error_abort);
705 qemu_opt_unset(opts, from);
709 QemuOptsList qemu_legacy_drive_opts = {
710 .name = "drive",
711 .head = QTAILQ_HEAD_INITIALIZER(qemu_legacy_drive_opts.head),
712 .desc = {
714 .name = "bus",
715 .type = QEMU_OPT_NUMBER,
716 .help = "bus number",
718 .name = "unit",
719 .type = QEMU_OPT_NUMBER,
720 .help = "unit number (i.e. lun for scsi)",
722 .name = "index",
723 .type = QEMU_OPT_NUMBER,
724 .help = "index number",
726 .name = "media",
727 .type = QEMU_OPT_STRING,
728 .help = "media type (disk, cdrom)",
730 .name = "if",
731 .type = QEMU_OPT_STRING,
732 .help = "interface (ide, scsi, sd, mtd, floppy, pflash, virtio)",
734 .name = "cyls",
735 .type = QEMU_OPT_NUMBER,
736 .help = "number of cylinders (ide disk geometry)",
738 .name = "heads",
739 .type = QEMU_OPT_NUMBER,
740 .help = "number of heads (ide disk geometry)",
742 .name = "secs",
743 .type = QEMU_OPT_NUMBER,
744 .help = "number of sectors (ide disk geometry)",
746 .name = "trans",
747 .type = QEMU_OPT_STRING,
748 .help = "chs translation (auto, lba, none)",
750 .name = "addr",
751 .type = QEMU_OPT_STRING,
752 .help = "pci address (virtio only)",
754 .name = "serial",
755 .type = QEMU_OPT_STRING,
756 .help = "disk serial number",
758 .name = "file",
759 .type = QEMU_OPT_STRING,
760 .help = "file name",
763 /* Options that are passed on, but have special semantics with -drive */
765 .name = BDRV_OPT_READ_ONLY,
766 .type = QEMU_OPT_BOOL,
767 .help = "open drive file as read-only",
769 .name = "rerror",
770 .type = QEMU_OPT_STRING,
771 .help = "read error action",
773 .name = "werror",
774 .type = QEMU_OPT_STRING,
775 .help = "write error action",
777 .name = "copy-on-read",
778 .type = QEMU_OPT_BOOL,
779 .help = "copy read data from backing file into image file",
782 { /* end of list */ }
786 DriveInfo *drive_new(QemuOpts *all_opts, BlockInterfaceType block_default_type)
788 const char *value;
789 BlockBackend *blk;
790 DriveInfo *dinfo = NULL;
791 QDict *bs_opts;
792 QemuOpts *legacy_opts;
793 DriveMediaType media = MEDIA_DISK;
794 BlockInterfaceType type;
795 int cyls, heads, secs, translation;
796 int max_devs, bus_id, unit_id, index;
797 const char *devaddr;
798 const char *werror, *rerror;
799 bool read_only = false;
800 bool copy_on_read;
801 const char *serial;
802 const char *filename;
803 Error *local_err = NULL;
804 int i;
805 const char *deprecated[] = {
806 "serial", "trans", "secs", "heads", "cyls", "addr"
809 /* Change legacy command line options into QMP ones */
810 static const struct {
811 const char *from;
812 const char *to;
813 } opt_renames[] = {
814 { "iops", "throttling.iops-total" },
815 { "iops_rd", "throttling.iops-read" },
816 { "iops_wr", "throttling.iops-write" },
818 { "bps", "throttling.bps-total" },
819 { "bps_rd", "throttling.bps-read" },
820 { "bps_wr", "throttling.bps-write" },
822 { "iops_max", "throttling.iops-total-max" },
823 { "iops_rd_max", "throttling.iops-read-max" },
824 { "iops_wr_max", "throttling.iops-write-max" },
826 { "bps_max", "throttling.bps-total-max" },
827 { "bps_rd_max", "throttling.bps-read-max" },
828 { "bps_wr_max", "throttling.bps-write-max" },
830 { "iops_size", "throttling.iops-size" },
832 { "group", "throttling.group" },
834 { "readonly", BDRV_OPT_READ_ONLY },
837 for (i = 0; i < ARRAY_SIZE(opt_renames); i++) {
838 qemu_opt_rename(all_opts, opt_renames[i].from, opt_renames[i].to,
839 &local_err);
840 if (local_err) {
841 error_report_err(local_err);
842 return NULL;
846 value = qemu_opt_get(all_opts, "cache");
847 if (value) {
848 int flags = 0;
849 bool writethrough;
851 if (bdrv_parse_cache_mode(value, &flags, &writethrough) != 0) {
852 error_report("invalid cache option");
853 return NULL;
856 /* Specific options take precedence */
857 if (!qemu_opt_get(all_opts, BDRV_OPT_CACHE_WB)) {
858 qemu_opt_set_bool(all_opts, BDRV_OPT_CACHE_WB,
859 !writethrough, &error_abort);
861 if (!qemu_opt_get(all_opts, BDRV_OPT_CACHE_DIRECT)) {
862 qemu_opt_set_bool(all_opts, BDRV_OPT_CACHE_DIRECT,
863 !!(flags & BDRV_O_NOCACHE), &error_abort);
865 if (!qemu_opt_get(all_opts, BDRV_OPT_CACHE_NO_FLUSH)) {
866 qemu_opt_set_bool(all_opts, BDRV_OPT_CACHE_NO_FLUSH,
867 !!(flags & BDRV_O_NO_FLUSH), &error_abort);
869 qemu_opt_unset(all_opts, "cache");
872 /* Get a QDict for processing the options */
873 bs_opts = qdict_new();
874 qemu_opts_to_qdict(all_opts, bs_opts);
876 legacy_opts = qemu_opts_create(&qemu_legacy_drive_opts, NULL, 0,
877 &error_abort);
878 qemu_opts_absorb_qdict(legacy_opts, bs_opts, &local_err);
879 if (local_err) {
880 error_report_err(local_err);
881 goto fail;
884 /* Other deprecated options */
885 if (!qtest_enabled()) {
886 for (i = 0; i < ARRAY_SIZE(deprecated); i++) {
887 if (qemu_opt_get(legacy_opts, deprecated[i]) != NULL) {
888 error_report("'%s' is deprecated, please use the corresponding "
889 "option of '-device' instead", deprecated[i]);
894 /* Media type */
895 value = qemu_opt_get(legacy_opts, "media");
896 if (value) {
897 if (!strcmp(value, "disk")) {
898 media = MEDIA_DISK;
899 } else if (!strcmp(value, "cdrom")) {
900 media = MEDIA_CDROM;
901 read_only = true;
902 } else {
903 error_report("'%s' invalid media", value);
904 goto fail;
908 /* copy-on-read is disabled with a warning for read-only devices */
909 read_only |= qemu_opt_get_bool(legacy_opts, BDRV_OPT_READ_ONLY, false);
910 copy_on_read = qemu_opt_get_bool(legacy_opts, "copy-on-read", false);
912 if (read_only && copy_on_read) {
913 warn_report("disabling copy-on-read on read-only drive");
914 copy_on_read = false;
917 qdict_put_str(bs_opts, BDRV_OPT_READ_ONLY, read_only ? "on" : "off");
918 qdict_put_str(bs_opts, "copy-on-read", copy_on_read ? "on" : "off");
920 /* Controller type */
921 value = qemu_opt_get(legacy_opts, "if");
922 if (value) {
923 for (type = 0;
924 type < IF_COUNT && strcmp(value, if_name[type]);
925 type++) {
927 if (type == IF_COUNT) {
928 error_report("unsupported bus type '%s'", value);
929 goto fail;
931 } else {
932 type = block_default_type;
935 /* Geometry */
936 cyls = qemu_opt_get_number(legacy_opts, "cyls", 0);
937 heads = qemu_opt_get_number(legacy_opts, "heads", 0);
938 secs = qemu_opt_get_number(legacy_opts, "secs", 0);
940 if (cyls || heads || secs) {
941 if (cyls < 1) {
942 error_report("invalid physical cyls number");
943 goto fail;
945 if (heads < 1) {
946 error_report("invalid physical heads number");
947 goto fail;
949 if (secs < 1) {
950 error_report("invalid physical secs number");
951 goto fail;
955 translation = BIOS_ATA_TRANSLATION_AUTO;
956 value = qemu_opt_get(legacy_opts, "trans");
957 if (value != NULL) {
958 if (!cyls) {
959 error_report("'%s' trans must be used with cyls, heads and secs",
960 value);
961 goto fail;
963 if (!strcmp(value, "none")) {
964 translation = BIOS_ATA_TRANSLATION_NONE;
965 } else if (!strcmp(value, "lba")) {
966 translation = BIOS_ATA_TRANSLATION_LBA;
967 } else if (!strcmp(value, "large")) {
968 translation = BIOS_ATA_TRANSLATION_LARGE;
969 } else if (!strcmp(value, "rechs")) {
970 translation = BIOS_ATA_TRANSLATION_RECHS;
971 } else if (!strcmp(value, "auto")) {
972 translation = BIOS_ATA_TRANSLATION_AUTO;
973 } else {
974 error_report("'%s' invalid translation type", value);
975 goto fail;
979 if (media == MEDIA_CDROM) {
980 if (cyls || secs || heads) {
981 error_report("CHS can't be set with media=cdrom");
982 goto fail;
986 /* Device address specified by bus/unit or index.
987 * If none was specified, try to find the first free one. */
988 bus_id = qemu_opt_get_number(legacy_opts, "bus", 0);
989 unit_id = qemu_opt_get_number(legacy_opts, "unit", -1);
990 index = qemu_opt_get_number(legacy_opts, "index", -1);
992 max_devs = if_max_devs[type];
994 if (index != -1) {
995 if (bus_id != 0 || unit_id != -1) {
996 error_report("index cannot be used with bus and unit");
997 goto fail;
999 bus_id = drive_index_to_bus_id(type, index);
1000 unit_id = drive_index_to_unit_id(type, index);
1003 if (unit_id == -1) {
1004 unit_id = 0;
1005 while (drive_get(type, bus_id, unit_id) != NULL) {
1006 unit_id++;
1007 if (max_devs && unit_id >= max_devs) {
1008 unit_id -= max_devs;
1009 bus_id++;
1014 if (max_devs && unit_id >= max_devs) {
1015 error_report("unit %d too big (max is %d)", unit_id, max_devs - 1);
1016 goto fail;
1019 if (drive_get(type, bus_id, unit_id) != NULL) {
1020 error_report("drive with bus=%d, unit=%d (index=%d) exists",
1021 bus_id, unit_id, index);
1022 goto fail;
1025 /* Serial number */
1026 serial = qemu_opt_get(legacy_opts, "serial");
1028 /* no id supplied -> create one */
1029 if (qemu_opts_id(all_opts) == NULL) {
1030 char *new_id;
1031 const char *mediastr = "";
1032 if (type == IF_IDE || type == IF_SCSI) {
1033 mediastr = (media == MEDIA_CDROM) ? "-cd" : "-hd";
1035 if (max_devs) {
1036 new_id = g_strdup_printf("%s%i%s%i", if_name[type], bus_id,
1037 mediastr, unit_id);
1038 } else {
1039 new_id = g_strdup_printf("%s%s%i", if_name[type],
1040 mediastr, unit_id);
1042 qdict_put_str(bs_opts, "id", new_id);
1043 g_free(new_id);
1046 /* Add virtio block device */
1047 devaddr = qemu_opt_get(legacy_opts, "addr");
1048 if (devaddr && type != IF_VIRTIO) {
1049 error_report("addr is not supported by this bus type");
1050 goto fail;
1053 if (type == IF_VIRTIO) {
1054 QemuOpts *devopts;
1055 devopts = qemu_opts_create(qemu_find_opts("device"), NULL, 0,
1056 &error_abort);
1057 if (arch_type == QEMU_ARCH_S390X) {
1058 qemu_opt_set(devopts, "driver", "virtio-blk-ccw", &error_abort);
1059 } else {
1060 qemu_opt_set(devopts, "driver", "virtio-blk-pci", &error_abort);
1062 qemu_opt_set(devopts, "drive", qdict_get_str(bs_opts, "id"),
1063 &error_abort);
1064 if (devaddr) {
1065 qemu_opt_set(devopts, "addr", devaddr, &error_abort);
1069 filename = qemu_opt_get(legacy_opts, "file");
1071 /* Check werror/rerror compatibility with if=... */
1072 werror = qemu_opt_get(legacy_opts, "werror");
1073 if (werror != NULL) {
1074 if (type != IF_IDE && type != IF_SCSI && type != IF_VIRTIO &&
1075 type != IF_NONE) {
1076 error_report("werror is not supported by this bus type");
1077 goto fail;
1079 qdict_put_str(bs_opts, "werror", werror);
1082 rerror = qemu_opt_get(legacy_opts, "rerror");
1083 if (rerror != NULL) {
1084 if (type != IF_IDE && type != IF_VIRTIO && type != IF_SCSI &&
1085 type != IF_NONE) {
1086 error_report("rerror is not supported by this bus type");
1087 goto fail;
1089 qdict_put_str(bs_opts, "rerror", rerror);
1092 /* Actual block device init: Functionality shared with blockdev-add */
1093 blk = blockdev_init(filename, bs_opts, &local_err);
1094 bs_opts = NULL;
1095 if (!blk) {
1096 if (local_err) {
1097 error_report_err(local_err);
1099 goto fail;
1100 } else {
1101 assert(!local_err);
1104 /* Create legacy DriveInfo */
1105 dinfo = g_malloc0(sizeof(*dinfo));
1106 dinfo->opts = all_opts;
1108 dinfo->cyls = cyls;
1109 dinfo->heads = heads;
1110 dinfo->secs = secs;
1111 dinfo->trans = translation;
1113 dinfo->type = type;
1114 dinfo->bus = bus_id;
1115 dinfo->unit = unit_id;
1116 dinfo->devaddr = devaddr;
1117 dinfo->serial = g_strdup(serial);
1119 blk_set_legacy_dinfo(blk, dinfo);
1121 switch(type) {
1122 case IF_IDE:
1123 case IF_SCSI:
1124 case IF_XEN:
1125 case IF_NONE:
1126 dinfo->media_cd = media == MEDIA_CDROM;
1127 break;
1128 default:
1129 break;
1132 fail:
1133 qemu_opts_del(legacy_opts);
1134 qobject_unref(bs_opts);
1135 return dinfo;
1138 static BlockDriverState *qmp_get_root_bs(const char *name, Error **errp)
1140 BlockDriverState *bs;
1142 bs = bdrv_lookup_bs(name, name, errp);
1143 if (bs == NULL) {
1144 return NULL;
1147 if (!bdrv_is_root_node(bs)) {
1148 error_setg(errp, "Need a root block node");
1149 return NULL;
1152 if (!bdrv_is_inserted(bs)) {
1153 error_setg(errp, "Device has no medium");
1154 return NULL;
1157 return bs;
1160 static BlockBackend *qmp_get_blk(const char *blk_name, const char *qdev_id,
1161 Error **errp)
1163 BlockBackend *blk;
1165 if (!blk_name == !qdev_id) {
1166 error_setg(errp, "Need exactly one of 'device' and 'id'");
1167 return NULL;
1170 if (qdev_id) {
1171 blk = blk_by_qdev_id(qdev_id, errp);
1172 } else {
1173 blk = blk_by_name(blk_name);
1174 if (blk == NULL) {
1175 error_set(errp, ERROR_CLASS_DEVICE_NOT_FOUND,
1176 "Device '%s' not found", blk_name);
1180 return blk;
1183 void hmp_commit(Monitor *mon, const QDict *qdict)
1185 const char *device = qdict_get_str(qdict, "device");
1186 BlockBackend *blk;
1187 int ret;
1189 if (!strcmp(device, "all")) {
1190 ret = blk_commit_all();
1191 } else {
1192 BlockDriverState *bs;
1193 AioContext *aio_context;
1195 blk = blk_by_name(device);
1196 if (!blk) {
1197 monitor_printf(mon, "Device '%s' not found\n", device);
1198 return;
1200 if (!blk_is_available(blk)) {
1201 monitor_printf(mon, "Device '%s' has no medium\n", device);
1202 return;
1205 bs = blk_bs(blk);
1206 aio_context = bdrv_get_aio_context(bs);
1207 aio_context_acquire(aio_context);
1209 ret = bdrv_commit(bs);
1211 aio_context_release(aio_context);
1213 if (ret < 0) {
1214 monitor_printf(mon, "'commit' error for '%s': %s\n", device,
1215 strerror(-ret));
1219 static void blockdev_do_action(TransactionAction *action, Error **errp)
1221 TransactionActionList list;
1223 list.value = action;
1224 list.next = NULL;
1225 qmp_transaction(&list, false, NULL, errp);
1228 void qmp_blockdev_snapshot_sync(bool has_device, const char *device,
1229 bool has_node_name, const char *node_name,
1230 const char *snapshot_file,
1231 bool has_snapshot_node_name,
1232 const char *snapshot_node_name,
1233 bool has_format, const char *format,
1234 bool has_mode, NewImageMode mode, Error **errp)
1236 BlockdevSnapshotSync snapshot = {
1237 .has_device = has_device,
1238 .device = (char *) device,
1239 .has_node_name = has_node_name,
1240 .node_name = (char *) node_name,
1241 .snapshot_file = (char *) snapshot_file,
1242 .has_snapshot_node_name = has_snapshot_node_name,
1243 .snapshot_node_name = (char *) snapshot_node_name,
1244 .has_format = has_format,
1245 .format = (char *) format,
1246 .has_mode = has_mode,
1247 .mode = mode,
1249 TransactionAction action = {
1250 .type = TRANSACTION_ACTION_KIND_BLOCKDEV_SNAPSHOT_SYNC,
1251 .u.blockdev_snapshot_sync.data = &snapshot,
1253 blockdev_do_action(&action, errp);
1256 void qmp_blockdev_snapshot(const char *node, const char *overlay,
1257 Error **errp)
1259 BlockdevSnapshot snapshot_data = {
1260 .node = (char *) node,
1261 .overlay = (char *) overlay
1263 TransactionAction action = {
1264 .type = TRANSACTION_ACTION_KIND_BLOCKDEV_SNAPSHOT,
1265 .u.blockdev_snapshot.data = &snapshot_data,
1267 blockdev_do_action(&action, errp);
1270 void qmp_blockdev_snapshot_internal_sync(const char *device,
1271 const char *name,
1272 Error **errp)
1274 BlockdevSnapshotInternal snapshot = {
1275 .device = (char *) device,
1276 .name = (char *) name
1278 TransactionAction action = {
1279 .type = TRANSACTION_ACTION_KIND_BLOCKDEV_SNAPSHOT_INTERNAL_SYNC,
1280 .u.blockdev_snapshot_internal_sync.data = &snapshot,
1282 blockdev_do_action(&action, errp);
1285 SnapshotInfo *qmp_blockdev_snapshot_delete_internal_sync(const char *device,
1286 bool has_id,
1287 const char *id,
1288 bool has_name,
1289 const char *name,
1290 Error **errp)
1292 BlockDriverState *bs;
1293 AioContext *aio_context;
1294 QEMUSnapshotInfo sn;
1295 Error *local_err = NULL;
1296 SnapshotInfo *info = NULL;
1297 int ret;
1299 bs = qmp_get_root_bs(device, errp);
1300 if (!bs) {
1301 return NULL;
1303 aio_context = bdrv_get_aio_context(bs);
1304 aio_context_acquire(aio_context);
1306 if (!has_id) {
1307 id = NULL;
1310 if (!has_name) {
1311 name = NULL;
1314 if (!id && !name) {
1315 error_setg(errp, "Name or id must be provided");
1316 goto out_aio_context;
1319 if (bdrv_op_is_blocked(bs, BLOCK_OP_TYPE_INTERNAL_SNAPSHOT_DELETE, errp)) {
1320 goto out_aio_context;
1323 ret = bdrv_snapshot_find_by_id_and_name(bs, id, name, &sn, &local_err);
1324 if (local_err) {
1325 error_propagate(errp, local_err);
1326 goto out_aio_context;
1328 if (!ret) {
1329 error_setg(errp,
1330 "Snapshot with id '%s' and name '%s' does not exist on "
1331 "device '%s'",
1332 STR_OR_NULL(id), STR_OR_NULL(name), device);
1333 goto out_aio_context;
1336 bdrv_snapshot_delete(bs, id, name, &local_err);
1337 if (local_err) {
1338 error_propagate(errp, local_err);
1339 goto out_aio_context;
1342 aio_context_release(aio_context);
1344 info = g_new0(SnapshotInfo, 1);
1345 info->id = g_strdup(sn.id_str);
1346 info->name = g_strdup(sn.name);
1347 info->date_nsec = sn.date_nsec;
1348 info->date_sec = sn.date_sec;
1349 info->vm_state_size = sn.vm_state_size;
1350 info->vm_clock_nsec = sn.vm_clock_nsec % 1000000000;
1351 info->vm_clock_sec = sn.vm_clock_nsec / 1000000000;
1353 return info;
1355 out_aio_context:
1356 aio_context_release(aio_context);
1357 return NULL;
1361 * block_dirty_bitmap_lookup:
1362 * Return a dirty bitmap (if present), after validating
1363 * the node reference and bitmap names.
1365 * @node: The name of the BDS node to search for bitmaps
1366 * @name: The name of the bitmap to search for
1367 * @pbs: Output pointer for BDS lookup, if desired. Can be NULL.
1368 * @paio: Output pointer for aio_context acquisition, if desired. Can be NULL.
1369 * @errp: Output pointer for error information. Can be NULL.
1371 * @return: A bitmap object on success, or NULL on failure.
1373 static BdrvDirtyBitmap *block_dirty_bitmap_lookup(const char *node,
1374 const char *name,
1375 BlockDriverState **pbs,
1376 Error **errp)
1378 BlockDriverState *bs;
1379 BdrvDirtyBitmap *bitmap;
1381 if (!node) {
1382 error_setg(errp, "Node cannot be NULL");
1383 return NULL;
1385 if (!name) {
1386 error_setg(errp, "Bitmap name cannot be NULL");
1387 return NULL;
1389 bs = bdrv_lookup_bs(node, node, NULL);
1390 if (!bs) {
1391 error_setg(errp, "Node '%s' not found", node);
1392 return NULL;
1395 bitmap = bdrv_find_dirty_bitmap(bs, name);
1396 if (!bitmap) {
1397 error_setg(errp, "Dirty bitmap '%s' not found", name);
1398 return NULL;
1401 if (pbs) {
1402 *pbs = bs;
1405 return bitmap;
1408 /* New and old BlockDriverState structs for atomic group operations */
1410 typedef struct BlkActionState BlkActionState;
1413 * BlkActionOps:
1414 * Table of operations that define an Action.
1416 * @instance_size: Size of state struct, in bytes.
1417 * @prepare: Prepare the work, must NOT be NULL.
1418 * @commit: Commit the changes, can be NULL.
1419 * @abort: Abort the changes on fail, can be NULL.
1420 * @clean: Clean up resources after all transaction actions have called
1421 * commit() or abort(). Can be NULL.
1423 * Only prepare() may fail. In a single transaction, only one of commit() or
1424 * abort() will be called. clean() will always be called if it is present.
1426 typedef struct BlkActionOps {
1427 size_t instance_size;
1428 void (*prepare)(BlkActionState *common, Error **errp);
1429 void (*commit)(BlkActionState *common);
1430 void (*abort)(BlkActionState *common);
1431 void (*clean)(BlkActionState *common);
1432 } BlkActionOps;
1435 * BlkActionState:
1436 * Describes one Action's state within a Transaction.
1438 * @action: QAPI-defined enum identifying which Action to perform.
1439 * @ops: Table of ActionOps this Action can perform.
1440 * @block_job_txn: Transaction which this action belongs to.
1441 * @entry: List membership for all Actions in this Transaction.
1443 * This structure must be arranged as first member in a subclassed type,
1444 * assuming that the compiler will also arrange it to the same offsets as the
1445 * base class.
1447 struct BlkActionState {
1448 TransactionAction *action;
1449 const BlkActionOps *ops;
1450 JobTxn *block_job_txn;
1451 TransactionProperties *txn_props;
1452 QSIMPLEQ_ENTRY(BlkActionState) entry;
1455 /* internal snapshot private data */
1456 typedef struct InternalSnapshotState {
1457 BlkActionState common;
1458 BlockDriverState *bs;
1459 QEMUSnapshotInfo sn;
1460 bool created;
1461 } InternalSnapshotState;
1464 static int action_check_completion_mode(BlkActionState *s, Error **errp)
1466 if (s->txn_props->completion_mode != ACTION_COMPLETION_MODE_INDIVIDUAL) {
1467 error_setg(errp,
1468 "Action '%s' does not support Transaction property "
1469 "completion-mode = %s",
1470 TransactionActionKind_str(s->action->type),
1471 ActionCompletionMode_str(s->txn_props->completion_mode));
1472 return -1;
1474 return 0;
1477 static void internal_snapshot_prepare(BlkActionState *common,
1478 Error **errp)
1480 Error *local_err = NULL;
1481 const char *device;
1482 const char *name;
1483 BlockDriverState *bs;
1484 QEMUSnapshotInfo old_sn, *sn;
1485 bool ret;
1486 qemu_timeval tv;
1487 BlockdevSnapshotInternal *internal;
1488 InternalSnapshotState *state;
1489 AioContext *aio_context;
1490 int ret1;
1492 g_assert(common->action->type ==
1493 TRANSACTION_ACTION_KIND_BLOCKDEV_SNAPSHOT_INTERNAL_SYNC);
1494 internal = common->action->u.blockdev_snapshot_internal_sync.data;
1495 state = DO_UPCAST(InternalSnapshotState, common, common);
1497 /* 1. parse input */
1498 device = internal->device;
1499 name = internal->name;
1501 /* 2. check for validation */
1502 if (action_check_completion_mode(common, errp) < 0) {
1503 return;
1506 bs = qmp_get_root_bs(device, errp);
1507 if (!bs) {
1508 return;
1511 aio_context = bdrv_get_aio_context(bs);
1512 aio_context_acquire(aio_context);
1514 state->bs = bs;
1516 /* Paired with .clean() */
1517 bdrv_drained_begin(bs);
1519 if (bdrv_op_is_blocked(bs, BLOCK_OP_TYPE_INTERNAL_SNAPSHOT, errp)) {
1520 goto out;
1523 if (bdrv_is_read_only(bs)) {
1524 error_setg(errp, "Device '%s' is read only", device);
1525 goto out;
1528 if (!bdrv_can_snapshot(bs)) {
1529 error_setg(errp, "Block format '%s' used by device '%s' "
1530 "does not support internal snapshots",
1531 bs->drv->format_name, device);
1532 goto out;
1535 if (!strlen(name)) {
1536 error_setg(errp, "Name is empty");
1537 goto out;
1540 /* check whether a snapshot with name exist */
1541 ret = bdrv_snapshot_find_by_id_and_name(bs, NULL, name, &old_sn,
1542 &local_err);
1543 if (local_err) {
1544 error_propagate(errp, local_err);
1545 goto out;
1546 } else if (ret) {
1547 error_setg(errp,
1548 "Snapshot with name '%s' already exists on device '%s'",
1549 name, device);
1550 goto out;
1553 /* 3. take the snapshot */
1554 sn = &state->sn;
1555 pstrcpy(sn->name, sizeof(sn->name), name);
1556 qemu_gettimeofday(&tv);
1557 sn->date_sec = tv.tv_sec;
1558 sn->date_nsec = tv.tv_usec * 1000;
1559 sn->vm_clock_nsec = qemu_clock_get_ns(QEMU_CLOCK_VIRTUAL);
1561 ret1 = bdrv_snapshot_create(bs, sn);
1562 if (ret1 < 0) {
1563 error_setg_errno(errp, -ret1,
1564 "Failed to create snapshot '%s' on device '%s'",
1565 name, device);
1566 goto out;
1569 /* 4. succeed, mark a snapshot is created */
1570 state->created = true;
1572 out:
1573 aio_context_release(aio_context);
1576 static void internal_snapshot_abort(BlkActionState *common)
1578 InternalSnapshotState *state =
1579 DO_UPCAST(InternalSnapshotState, common, common);
1580 BlockDriverState *bs = state->bs;
1581 QEMUSnapshotInfo *sn = &state->sn;
1582 AioContext *aio_context;
1583 Error *local_error = NULL;
1585 if (!state->created) {
1586 return;
1589 aio_context = bdrv_get_aio_context(state->bs);
1590 aio_context_acquire(aio_context);
1592 if (bdrv_snapshot_delete(bs, sn->id_str, sn->name, &local_error) < 0) {
1593 error_reportf_err(local_error,
1594 "Failed to delete snapshot with id '%s' and "
1595 "name '%s' on device '%s' in abort: ",
1596 sn->id_str, sn->name,
1597 bdrv_get_device_name(bs));
1600 aio_context_release(aio_context);
1603 static void internal_snapshot_clean(BlkActionState *common)
1605 InternalSnapshotState *state = DO_UPCAST(InternalSnapshotState,
1606 common, common);
1607 AioContext *aio_context;
1609 if (!state->bs) {
1610 return;
1613 aio_context = bdrv_get_aio_context(state->bs);
1614 aio_context_acquire(aio_context);
1616 bdrv_drained_end(state->bs);
1618 aio_context_release(aio_context);
1621 /* external snapshot private data */
1622 typedef struct ExternalSnapshotState {
1623 BlkActionState common;
1624 BlockDriverState *old_bs;
1625 BlockDriverState *new_bs;
1626 bool overlay_appended;
1627 } ExternalSnapshotState;
1629 static void external_snapshot_prepare(BlkActionState *common,
1630 Error **errp)
1632 int flags = 0;
1633 QDict *options = NULL;
1634 Error *local_err = NULL;
1635 /* Device and node name of the image to generate the snapshot from */
1636 const char *device;
1637 const char *node_name;
1638 /* Reference to the new image (for 'blockdev-snapshot') */
1639 const char *snapshot_ref;
1640 /* File name of the new image (for 'blockdev-snapshot-sync') */
1641 const char *new_image_file;
1642 ExternalSnapshotState *state =
1643 DO_UPCAST(ExternalSnapshotState, common, common);
1644 TransactionAction *action = common->action;
1645 AioContext *aio_context;
1647 /* 'blockdev-snapshot' and 'blockdev-snapshot-sync' have similar
1648 * purpose but a different set of parameters */
1649 switch (action->type) {
1650 case TRANSACTION_ACTION_KIND_BLOCKDEV_SNAPSHOT:
1652 BlockdevSnapshot *s = action->u.blockdev_snapshot.data;
1653 device = s->node;
1654 node_name = s->node;
1655 new_image_file = NULL;
1656 snapshot_ref = s->overlay;
1658 break;
1659 case TRANSACTION_ACTION_KIND_BLOCKDEV_SNAPSHOT_SYNC:
1661 BlockdevSnapshotSync *s = action->u.blockdev_snapshot_sync.data;
1662 device = s->has_device ? s->device : NULL;
1663 node_name = s->has_node_name ? s->node_name : NULL;
1664 new_image_file = s->snapshot_file;
1665 snapshot_ref = NULL;
1667 break;
1668 default:
1669 g_assert_not_reached();
1672 /* start processing */
1673 if (action_check_completion_mode(common, errp) < 0) {
1674 return;
1677 state->old_bs = bdrv_lookup_bs(device, node_name, errp);
1678 if (!state->old_bs) {
1679 return;
1682 aio_context = bdrv_get_aio_context(state->old_bs);
1683 aio_context_acquire(aio_context);
1685 /* Paired with .clean() */
1686 bdrv_drained_begin(state->old_bs);
1688 if (!bdrv_is_inserted(state->old_bs)) {
1689 error_setg(errp, QERR_DEVICE_HAS_NO_MEDIUM, device);
1690 goto out;
1693 if (bdrv_op_is_blocked(state->old_bs,
1694 BLOCK_OP_TYPE_EXTERNAL_SNAPSHOT, errp)) {
1695 goto out;
1698 if (!bdrv_is_read_only(state->old_bs)) {
1699 if (bdrv_flush(state->old_bs)) {
1700 error_setg(errp, QERR_IO_ERROR);
1701 goto out;
1705 if (!bdrv_is_first_non_filter(state->old_bs)) {
1706 error_setg(errp, QERR_FEATURE_DISABLED, "snapshot");
1707 goto out;
1710 if (action->type == TRANSACTION_ACTION_KIND_BLOCKDEV_SNAPSHOT_SYNC) {
1711 BlockdevSnapshotSync *s = action->u.blockdev_snapshot_sync.data;
1712 const char *format = s->has_format ? s->format : "qcow2";
1713 enum NewImageMode mode;
1714 const char *snapshot_node_name =
1715 s->has_snapshot_node_name ? s->snapshot_node_name : NULL;
1717 if (node_name && !snapshot_node_name) {
1718 error_setg(errp, "New snapshot node name missing");
1719 goto out;
1722 if (snapshot_node_name &&
1723 bdrv_lookup_bs(snapshot_node_name, snapshot_node_name, NULL)) {
1724 error_setg(errp, "New snapshot node name already in use");
1725 goto out;
1728 flags = state->old_bs->open_flags;
1729 flags &= ~(BDRV_O_SNAPSHOT | BDRV_O_COPY_ON_READ);
1730 flags |= BDRV_O_NO_BACKING;
1732 /* create new image w/backing file */
1733 mode = s->has_mode ? s->mode : NEW_IMAGE_MODE_ABSOLUTE_PATHS;
1734 if (mode != NEW_IMAGE_MODE_EXISTING) {
1735 int64_t size = bdrv_getlength(state->old_bs);
1736 if (size < 0) {
1737 error_setg_errno(errp, -size, "bdrv_getlength failed");
1738 goto out;
1740 bdrv_img_create(new_image_file, format,
1741 state->old_bs->filename,
1742 state->old_bs->drv->format_name,
1743 NULL, size, flags, false, &local_err);
1744 if (local_err) {
1745 error_propagate(errp, local_err);
1746 goto out;
1750 options = qdict_new();
1751 if (s->has_snapshot_node_name) {
1752 qdict_put_str(options, "node-name", snapshot_node_name);
1754 qdict_put_str(options, "driver", format);
1757 state->new_bs = bdrv_open(new_image_file, snapshot_ref, options, flags,
1758 errp);
1759 /* We will manually add the backing_hd field to the bs later */
1760 if (!state->new_bs) {
1761 goto out;
1764 if (bdrv_has_blk(state->new_bs)) {
1765 error_setg(errp, "The snapshot is already in use");
1766 goto out;
1769 if (bdrv_op_is_blocked(state->new_bs, BLOCK_OP_TYPE_EXTERNAL_SNAPSHOT,
1770 errp)) {
1771 goto out;
1774 if (state->new_bs->backing != NULL) {
1775 error_setg(errp, "The snapshot already has a backing image");
1776 goto out;
1779 if (!state->new_bs->drv->supports_backing) {
1780 error_setg(errp, "The snapshot does not support backing images");
1781 goto out;
1784 bdrv_set_aio_context(state->new_bs, aio_context);
1786 /* This removes our old bs and adds the new bs. This is an operation that
1787 * can fail, so we need to do it in .prepare; undoing it for abort is
1788 * always possible. */
1789 bdrv_ref(state->new_bs);
1790 bdrv_append(state->new_bs, state->old_bs, &local_err);
1791 if (local_err) {
1792 error_propagate(errp, local_err);
1793 goto out;
1795 state->overlay_appended = true;
1797 out:
1798 aio_context_release(aio_context);
1801 static void external_snapshot_commit(BlkActionState *common)
1803 ExternalSnapshotState *state =
1804 DO_UPCAST(ExternalSnapshotState, common, common);
1805 AioContext *aio_context;
1807 aio_context = bdrv_get_aio_context(state->old_bs);
1808 aio_context_acquire(aio_context);
1810 /* We don't need (or want) to use the transactional
1811 * bdrv_reopen_multiple() across all the entries at once, because we
1812 * don't want to abort all of them if one of them fails the reopen */
1813 if (!atomic_read(&state->old_bs->copy_on_read)) {
1814 bdrv_reopen(state->old_bs, state->old_bs->open_flags & ~BDRV_O_RDWR,
1815 NULL);
1818 aio_context_release(aio_context);
1821 static void external_snapshot_abort(BlkActionState *common)
1823 ExternalSnapshotState *state =
1824 DO_UPCAST(ExternalSnapshotState, common, common);
1825 if (state->new_bs) {
1826 if (state->overlay_appended) {
1827 AioContext *aio_context;
1829 aio_context = bdrv_get_aio_context(state->old_bs);
1830 aio_context_acquire(aio_context);
1832 bdrv_ref(state->old_bs); /* we can't let bdrv_set_backind_hd()
1833 close state->old_bs; we need it */
1834 bdrv_set_backing_hd(state->new_bs, NULL, &error_abort);
1835 bdrv_replace_node(state->new_bs, state->old_bs, &error_abort);
1836 bdrv_unref(state->old_bs); /* bdrv_replace_node() ref'ed old_bs */
1838 aio_context_release(aio_context);
1843 static void external_snapshot_clean(BlkActionState *common)
1845 ExternalSnapshotState *state =
1846 DO_UPCAST(ExternalSnapshotState, common, common);
1847 AioContext *aio_context;
1849 if (!state->old_bs) {
1850 return;
1853 aio_context = bdrv_get_aio_context(state->old_bs);
1854 aio_context_acquire(aio_context);
1856 bdrv_drained_end(state->old_bs);
1857 bdrv_unref(state->new_bs);
1859 aio_context_release(aio_context);
1862 typedef struct DriveBackupState {
1863 BlkActionState common;
1864 BlockDriverState *bs;
1865 BlockJob *job;
1866 } DriveBackupState;
1868 static BlockJob *do_drive_backup(DriveBackup *backup, JobTxn *txn,
1869 Error **errp);
1871 static void drive_backup_prepare(BlkActionState *common, Error **errp)
1873 DriveBackupState *state = DO_UPCAST(DriveBackupState, common, common);
1874 BlockDriverState *bs;
1875 DriveBackup *backup;
1876 AioContext *aio_context;
1877 Error *local_err = NULL;
1879 assert(common->action->type == TRANSACTION_ACTION_KIND_DRIVE_BACKUP);
1880 backup = common->action->u.drive_backup.data;
1882 bs = qmp_get_root_bs(backup->device, errp);
1883 if (!bs) {
1884 return;
1887 aio_context = bdrv_get_aio_context(bs);
1888 aio_context_acquire(aio_context);
1890 /* Paired with .clean() */
1891 bdrv_drained_begin(bs);
1893 state->bs = bs;
1895 state->job = do_drive_backup(backup, common->block_job_txn, &local_err);
1896 if (local_err) {
1897 error_propagate(errp, local_err);
1898 goto out;
1901 out:
1902 aio_context_release(aio_context);
1905 static void drive_backup_commit(BlkActionState *common)
1907 DriveBackupState *state = DO_UPCAST(DriveBackupState, common, common);
1908 AioContext *aio_context;
1910 aio_context = bdrv_get_aio_context(state->bs);
1911 aio_context_acquire(aio_context);
1913 assert(state->job);
1914 job_start(&state->job->job);
1916 aio_context_release(aio_context);
1919 static void drive_backup_abort(BlkActionState *common)
1921 DriveBackupState *state = DO_UPCAST(DriveBackupState, common, common);
1923 if (state->job) {
1924 AioContext *aio_context;
1926 aio_context = bdrv_get_aio_context(state->bs);
1927 aio_context_acquire(aio_context);
1929 job_cancel_sync(&state->job->job);
1931 aio_context_release(aio_context);
1935 static void drive_backup_clean(BlkActionState *common)
1937 DriveBackupState *state = DO_UPCAST(DriveBackupState, common, common);
1938 AioContext *aio_context;
1940 if (!state->bs) {
1941 return;
1944 aio_context = bdrv_get_aio_context(state->bs);
1945 aio_context_acquire(aio_context);
1947 bdrv_drained_end(state->bs);
1949 aio_context_release(aio_context);
1952 typedef struct BlockdevBackupState {
1953 BlkActionState common;
1954 BlockDriverState *bs;
1955 BlockJob *job;
1956 } BlockdevBackupState;
1958 static BlockJob *do_blockdev_backup(BlockdevBackup *backup, JobTxn *txn,
1959 Error **errp);
1961 static void blockdev_backup_prepare(BlkActionState *common, Error **errp)
1963 BlockdevBackupState *state = DO_UPCAST(BlockdevBackupState, common, common);
1964 BlockdevBackup *backup;
1965 BlockDriverState *bs, *target;
1966 AioContext *aio_context;
1967 Error *local_err = NULL;
1969 assert(common->action->type == TRANSACTION_ACTION_KIND_BLOCKDEV_BACKUP);
1970 backup = common->action->u.blockdev_backup.data;
1972 bs = bdrv_lookup_bs(backup->device, backup->device, errp);
1973 if (!bs) {
1974 return;
1977 target = bdrv_lookup_bs(backup->target, backup->target, errp);
1978 if (!target) {
1979 return;
1982 aio_context = bdrv_get_aio_context(bs);
1983 if (aio_context != bdrv_get_aio_context(target)) {
1984 error_setg(errp, "Backup between two IO threads is not implemented");
1985 return;
1987 aio_context_acquire(aio_context);
1988 state->bs = bs;
1990 /* Paired with .clean() */
1991 bdrv_drained_begin(state->bs);
1993 state->job = do_blockdev_backup(backup, common->block_job_txn, &local_err);
1994 if (local_err) {
1995 error_propagate(errp, local_err);
1996 goto out;
1999 out:
2000 aio_context_release(aio_context);
2003 static void blockdev_backup_commit(BlkActionState *common)
2005 BlockdevBackupState *state = DO_UPCAST(BlockdevBackupState, common, common);
2006 AioContext *aio_context;
2008 aio_context = bdrv_get_aio_context(state->bs);
2009 aio_context_acquire(aio_context);
2011 assert(state->job);
2012 job_start(&state->job->job);
2014 aio_context_release(aio_context);
2017 static void blockdev_backup_abort(BlkActionState *common)
2019 BlockdevBackupState *state = DO_UPCAST(BlockdevBackupState, common, common);
2021 if (state->job) {
2022 AioContext *aio_context;
2024 aio_context = bdrv_get_aio_context(state->bs);
2025 aio_context_acquire(aio_context);
2027 job_cancel_sync(&state->job->job);
2029 aio_context_release(aio_context);
2033 static void blockdev_backup_clean(BlkActionState *common)
2035 BlockdevBackupState *state = DO_UPCAST(BlockdevBackupState, common, common);
2036 AioContext *aio_context;
2038 if (!state->bs) {
2039 return;
2042 aio_context = bdrv_get_aio_context(state->bs);
2043 aio_context_acquire(aio_context);
2045 bdrv_drained_end(state->bs);
2047 aio_context_release(aio_context);
2050 typedef struct BlockDirtyBitmapState {
2051 BlkActionState common;
2052 BdrvDirtyBitmap *bitmap;
2053 BlockDriverState *bs;
2054 HBitmap *backup;
2055 bool prepared;
2056 bool was_enabled;
2057 } BlockDirtyBitmapState;
2059 static void block_dirty_bitmap_add_prepare(BlkActionState *common,
2060 Error **errp)
2062 Error *local_err = NULL;
2063 BlockDirtyBitmapAdd *action;
2064 BlockDirtyBitmapState *state = DO_UPCAST(BlockDirtyBitmapState,
2065 common, common);
2067 if (action_check_completion_mode(common, errp) < 0) {
2068 return;
2071 action = common->action->u.block_dirty_bitmap_add.data;
2072 /* AIO context taken and released within qmp_block_dirty_bitmap_add */
2073 qmp_block_dirty_bitmap_add(action->node, action->name,
2074 action->has_granularity, action->granularity,
2075 action->has_persistent, action->persistent,
2076 action->has_autoload, action->autoload,
2077 action->has_x_disabled, action->x_disabled,
2078 &local_err);
2080 if (!local_err) {
2081 state->prepared = true;
2082 } else {
2083 error_propagate(errp, local_err);
2087 static void block_dirty_bitmap_add_abort(BlkActionState *common)
2089 BlockDirtyBitmapAdd *action;
2090 BlockDirtyBitmapState *state = DO_UPCAST(BlockDirtyBitmapState,
2091 common, common);
2093 action = common->action->u.block_dirty_bitmap_add.data;
2094 /* Should not be able to fail: IF the bitmap was added via .prepare(),
2095 * then the node reference and bitmap name must have been valid.
2097 if (state->prepared) {
2098 qmp_block_dirty_bitmap_remove(action->node, action->name, &error_abort);
2102 static void block_dirty_bitmap_clear_prepare(BlkActionState *common,
2103 Error **errp)
2105 BlockDirtyBitmapState *state = DO_UPCAST(BlockDirtyBitmapState,
2106 common, common);
2107 BlockDirtyBitmap *action;
2109 if (action_check_completion_mode(common, errp) < 0) {
2110 return;
2113 action = common->action->u.block_dirty_bitmap_clear.data;
2114 state->bitmap = block_dirty_bitmap_lookup(action->node,
2115 action->name,
2116 &state->bs,
2117 errp);
2118 if (!state->bitmap) {
2119 return;
2122 if (bdrv_dirty_bitmap_frozen(state->bitmap)) {
2123 error_setg(errp, "Cannot modify a frozen bitmap");
2124 return;
2125 } else if (bdrv_dirty_bitmap_qmp_locked(state->bitmap)) {
2126 error_setg(errp, "Cannot modify a locked bitmap");
2127 return;
2128 } else if (!bdrv_dirty_bitmap_enabled(state->bitmap)) {
2129 error_setg(errp, "Cannot clear a disabled bitmap");
2130 return;
2131 } else if (bdrv_dirty_bitmap_readonly(state->bitmap)) {
2132 error_setg(errp, "Cannot clear a readonly bitmap");
2133 return;
2136 bdrv_clear_dirty_bitmap(state->bitmap, &state->backup);
2139 static void block_dirty_bitmap_clear_abort(BlkActionState *common)
2141 BlockDirtyBitmapState *state = DO_UPCAST(BlockDirtyBitmapState,
2142 common, common);
2144 if (state->backup) {
2145 bdrv_undo_clear_dirty_bitmap(state->bitmap, state->backup);
2149 static void block_dirty_bitmap_clear_commit(BlkActionState *common)
2151 BlockDirtyBitmapState *state = DO_UPCAST(BlockDirtyBitmapState,
2152 common, common);
2154 hbitmap_free(state->backup);
2157 static void block_dirty_bitmap_enable_prepare(BlkActionState *common,
2158 Error **errp)
2160 BlockDirtyBitmap *action;
2161 BlockDirtyBitmapState *state = DO_UPCAST(BlockDirtyBitmapState,
2162 common, common);
2164 if (action_check_completion_mode(common, errp) < 0) {
2165 return;
2168 action = common->action->u.x_block_dirty_bitmap_enable.data;
2169 state->bitmap = block_dirty_bitmap_lookup(action->node,
2170 action->name,
2171 NULL,
2172 errp);
2173 if (!state->bitmap) {
2174 return;
2177 state->was_enabled = bdrv_dirty_bitmap_enabled(state->bitmap);
2178 bdrv_enable_dirty_bitmap(state->bitmap);
2181 static void block_dirty_bitmap_enable_abort(BlkActionState *common)
2183 BlockDirtyBitmapState *state = DO_UPCAST(BlockDirtyBitmapState,
2184 common, common);
2186 if (!state->was_enabled) {
2187 bdrv_disable_dirty_bitmap(state->bitmap);
2191 static void block_dirty_bitmap_disable_prepare(BlkActionState *common,
2192 Error **errp)
2194 BlockDirtyBitmap *action;
2195 BlockDirtyBitmapState *state = DO_UPCAST(BlockDirtyBitmapState,
2196 common, common);
2198 if (action_check_completion_mode(common, errp) < 0) {
2199 return;
2202 action = common->action->u.x_block_dirty_bitmap_disable.data;
2203 state->bitmap = block_dirty_bitmap_lookup(action->node,
2204 action->name,
2205 NULL,
2206 errp);
2207 if (!state->bitmap) {
2208 return;
2211 state->was_enabled = bdrv_dirty_bitmap_enabled(state->bitmap);
2212 bdrv_disable_dirty_bitmap(state->bitmap);
2215 static void block_dirty_bitmap_disable_abort(BlkActionState *common)
2217 BlockDirtyBitmapState *state = DO_UPCAST(BlockDirtyBitmapState,
2218 common, common);
2220 if (state->was_enabled) {
2221 bdrv_enable_dirty_bitmap(state->bitmap);
2225 static void abort_prepare(BlkActionState *common, Error **errp)
2227 error_setg(errp, "Transaction aborted using Abort action");
2230 static void abort_commit(BlkActionState *common)
2232 g_assert_not_reached(); /* this action never succeeds */
2235 static const BlkActionOps actions[] = {
2236 [TRANSACTION_ACTION_KIND_BLOCKDEV_SNAPSHOT] = {
2237 .instance_size = sizeof(ExternalSnapshotState),
2238 .prepare = external_snapshot_prepare,
2239 .commit = external_snapshot_commit,
2240 .abort = external_snapshot_abort,
2241 .clean = external_snapshot_clean,
2243 [TRANSACTION_ACTION_KIND_BLOCKDEV_SNAPSHOT_SYNC] = {
2244 .instance_size = sizeof(ExternalSnapshotState),
2245 .prepare = external_snapshot_prepare,
2246 .commit = external_snapshot_commit,
2247 .abort = external_snapshot_abort,
2248 .clean = external_snapshot_clean,
2250 [TRANSACTION_ACTION_KIND_DRIVE_BACKUP] = {
2251 .instance_size = sizeof(DriveBackupState),
2252 .prepare = drive_backup_prepare,
2253 .commit = drive_backup_commit,
2254 .abort = drive_backup_abort,
2255 .clean = drive_backup_clean,
2257 [TRANSACTION_ACTION_KIND_BLOCKDEV_BACKUP] = {
2258 .instance_size = sizeof(BlockdevBackupState),
2259 .prepare = blockdev_backup_prepare,
2260 .commit = blockdev_backup_commit,
2261 .abort = blockdev_backup_abort,
2262 .clean = blockdev_backup_clean,
2264 [TRANSACTION_ACTION_KIND_ABORT] = {
2265 .instance_size = sizeof(BlkActionState),
2266 .prepare = abort_prepare,
2267 .commit = abort_commit,
2269 [TRANSACTION_ACTION_KIND_BLOCKDEV_SNAPSHOT_INTERNAL_SYNC] = {
2270 .instance_size = sizeof(InternalSnapshotState),
2271 .prepare = internal_snapshot_prepare,
2272 .abort = internal_snapshot_abort,
2273 .clean = internal_snapshot_clean,
2275 [TRANSACTION_ACTION_KIND_BLOCK_DIRTY_BITMAP_ADD] = {
2276 .instance_size = sizeof(BlockDirtyBitmapState),
2277 .prepare = block_dirty_bitmap_add_prepare,
2278 .abort = block_dirty_bitmap_add_abort,
2280 [TRANSACTION_ACTION_KIND_BLOCK_DIRTY_BITMAP_CLEAR] = {
2281 .instance_size = sizeof(BlockDirtyBitmapState),
2282 .prepare = block_dirty_bitmap_clear_prepare,
2283 .commit = block_dirty_bitmap_clear_commit,
2284 .abort = block_dirty_bitmap_clear_abort,
2286 [TRANSACTION_ACTION_KIND_X_BLOCK_DIRTY_BITMAP_ENABLE] = {
2287 .instance_size = sizeof(BlockDirtyBitmapState),
2288 .prepare = block_dirty_bitmap_enable_prepare,
2289 .abort = block_dirty_bitmap_enable_abort,
2291 [TRANSACTION_ACTION_KIND_X_BLOCK_DIRTY_BITMAP_DISABLE] = {
2292 .instance_size = sizeof(BlockDirtyBitmapState),
2293 .prepare = block_dirty_bitmap_disable_prepare,
2294 .abort = block_dirty_bitmap_disable_abort,
2299 * Allocate a TransactionProperties structure if necessary, and fill
2300 * that structure with desired defaults if they are unset.
2302 static TransactionProperties *get_transaction_properties(
2303 TransactionProperties *props)
2305 if (!props) {
2306 props = g_new0(TransactionProperties, 1);
2309 if (!props->has_completion_mode) {
2310 props->has_completion_mode = true;
2311 props->completion_mode = ACTION_COMPLETION_MODE_INDIVIDUAL;
2314 return props;
2318 * 'Atomic' group operations. The operations are performed as a set, and if
2319 * any fail then we roll back all operations in the group.
2321 void qmp_transaction(TransactionActionList *dev_list,
2322 bool has_props,
2323 struct TransactionProperties *props,
2324 Error **errp)
2326 TransactionActionList *dev_entry = dev_list;
2327 JobTxn *block_job_txn = NULL;
2328 BlkActionState *state, *next;
2329 Error *local_err = NULL;
2331 QSIMPLEQ_HEAD(snap_bdrv_states, BlkActionState) snap_bdrv_states;
2332 QSIMPLEQ_INIT(&snap_bdrv_states);
2334 /* Does this transaction get canceled as a group on failure?
2335 * If not, we don't really need to make a JobTxn.
2337 props = get_transaction_properties(props);
2338 if (props->completion_mode != ACTION_COMPLETION_MODE_INDIVIDUAL) {
2339 block_job_txn = job_txn_new();
2342 /* drain all i/o before any operations */
2343 bdrv_drain_all();
2345 /* We don't do anything in this loop that commits us to the operations */
2346 while (NULL != dev_entry) {
2347 TransactionAction *dev_info = NULL;
2348 const BlkActionOps *ops;
2350 dev_info = dev_entry->value;
2351 dev_entry = dev_entry->next;
2353 assert(dev_info->type < ARRAY_SIZE(actions));
2355 ops = &actions[dev_info->type];
2356 assert(ops->instance_size > 0);
2358 state = g_malloc0(ops->instance_size);
2359 state->ops = ops;
2360 state->action = dev_info;
2361 state->block_job_txn = block_job_txn;
2362 state->txn_props = props;
2363 QSIMPLEQ_INSERT_TAIL(&snap_bdrv_states, state, entry);
2365 state->ops->prepare(state, &local_err);
2366 if (local_err) {
2367 error_propagate(errp, local_err);
2368 goto delete_and_fail;
2372 QSIMPLEQ_FOREACH(state, &snap_bdrv_states, entry) {
2373 if (state->ops->commit) {
2374 state->ops->commit(state);
2378 /* success */
2379 goto exit;
2381 delete_and_fail:
2382 /* failure, and it is all-or-none; roll back all operations */
2383 QSIMPLEQ_FOREACH(state, &snap_bdrv_states, entry) {
2384 if (state->ops->abort) {
2385 state->ops->abort(state);
2388 exit:
2389 QSIMPLEQ_FOREACH_SAFE(state, &snap_bdrv_states, entry, next) {
2390 if (state->ops->clean) {
2391 state->ops->clean(state);
2393 g_free(state);
2395 if (!has_props) {
2396 qapi_free_TransactionProperties(props);
2398 job_txn_unref(block_job_txn);
2401 void qmp_eject(bool has_device, const char *device,
2402 bool has_id, const char *id,
2403 bool has_force, bool force, Error **errp)
2405 Error *local_err = NULL;
2406 int rc;
2408 if (!has_force) {
2409 force = false;
2412 rc = do_open_tray(has_device ? device : NULL,
2413 has_id ? id : NULL,
2414 force, &local_err);
2415 if (rc && rc != -ENOSYS) {
2416 error_propagate(errp, local_err);
2417 return;
2419 error_free(local_err);
2421 blockdev_remove_medium(has_device, device, has_id, id, errp);
2424 void qmp_block_passwd(bool has_device, const char *device,
2425 bool has_node_name, const char *node_name,
2426 const char *password, Error **errp)
2428 error_setg(errp,
2429 "Setting block passwords directly is no longer supported");
2433 * Attempt to open the tray of @device.
2434 * If @force, ignore its tray lock.
2435 * Else, if the tray is locked, don't open it, but ask the guest to open it.
2436 * On error, store an error through @errp and return -errno.
2437 * If @device does not exist, return -ENODEV.
2438 * If it has no removable media, return -ENOTSUP.
2439 * If it has no tray, return -ENOSYS.
2440 * If the guest was asked to open the tray, return -EINPROGRESS.
2441 * Else, return 0.
2443 static int do_open_tray(const char *blk_name, const char *qdev_id,
2444 bool force, Error **errp)
2446 BlockBackend *blk;
2447 const char *device = qdev_id ?: blk_name;
2448 bool locked;
2450 blk = qmp_get_blk(blk_name, qdev_id, errp);
2451 if (!blk) {
2452 return -ENODEV;
2455 if (!blk_dev_has_removable_media(blk)) {
2456 error_setg(errp, "Device '%s' is not removable", device);
2457 return -ENOTSUP;
2460 if (!blk_dev_has_tray(blk)) {
2461 error_setg(errp, "Device '%s' does not have a tray", device);
2462 return -ENOSYS;
2465 if (blk_dev_is_tray_open(blk)) {
2466 return 0;
2469 locked = blk_dev_is_medium_locked(blk);
2470 if (locked) {
2471 blk_dev_eject_request(blk, force);
2474 if (!locked || force) {
2475 blk_dev_change_media_cb(blk, false, &error_abort);
2478 if (locked && !force) {
2479 error_setg(errp, "Device '%s' is locked and force was not specified, "
2480 "wait for tray to open and try again", device);
2481 return -EINPROGRESS;
2484 return 0;
2487 void qmp_blockdev_open_tray(bool has_device, const char *device,
2488 bool has_id, const char *id,
2489 bool has_force, bool force,
2490 Error **errp)
2492 Error *local_err = NULL;
2493 int rc;
2495 if (!has_force) {
2496 force = false;
2498 rc = do_open_tray(has_device ? device : NULL,
2499 has_id ? id : NULL,
2500 force, &local_err);
2501 if (rc && rc != -ENOSYS && rc != -EINPROGRESS) {
2502 error_propagate(errp, local_err);
2503 return;
2505 error_free(local_err);
2508 void qmp_blockdev_close_tray(bool has_device, const char *device,
2509 bool has_id, const char *id,
2510 Error **errp)
2512 BlockBackend *blk;
2513 Error *local_err = NULL;
2515 device = has_device ? device : NULL;
2516 id = has_id ? id : NULL;
2518 blk = qmp_get_blk(device, id, errp);
2519 if (!blk) {
2520 return;
2523 if (!blk_dev_has_removable_media(blk)) {
2524 error_setg(errp, "Device '%s' is not removable", device ?: id);
2525 return;
2528 if (!blk_dev_has_tray(blk)) {
2529 /* Ignore this command on tray-less devices */
2530 return;
2533 if (!blk_dev_is_tray_open(blk)) {
2534 return;
2537 blk_dev_change_media_cb(blk, true, &local_err);
2538 if (local_err) {
2539 error_propagate(errp, local_err);
2540 return;
2544 static void blockdev_remove_medium(bool has_device, const char *device,
2545 bool has_id, const char *id, Error **errp)
2547 BlockBackend *blk;
2548 BlockDriverState *bs;
2549 AioContext *aio_context;
2550 bool has_attached_device;
2552 device = has_device ? device : NULL;
2553 id = has_id ? id : NULL;
2555 blk = qmp_get_blk(device, id, errp);
2556 if (!blk) {
2557 return;
2560 /* For BBs without a device, we can exchange the BDS tree at will */
2561 has_attached_device = blk_get_attached_dev(blk);
2563 if (has_attached_device && !blk_dev_has_removable_media(blk)) {
2564 error_setg(errp, "Device '%s' is not removable", device ?: id);
2565 return;
2568 if (has_attached_device && blk_dev_has_tray(blk) &&
2569 !blk_dev_is_tray_open(blk))
2571 error_setg(errp, "Tray of device '%s' is not open", device ?: id);
2572 return;
2575 bs = blk_bs(blk);
2576 if (!bs) {
2577 return;
2580 aio_context = bdrv_get_aio_context(bs);
2581 aio_context_acquire(aio_context);
2583 if (bdrv_op_is_blocked(bs, BLOCK_OP_TYPE_EJECT, errp)) {
2584 goto out;
2587 blk_remove_bs(blk);
2589 if (!blk_dev_has_tray(blk)) {
2590 /* For tray-less devices, blockdev-open-tray is a no-op (or may not be
2591 * called at all); therefore, the medium needs to be ejected here.
2592 * Do it after blk_remove_bs() so blk_is_inserted(blk) returns the @load
2593 * value passed here (i.e. false). */
2594 blk_dev_change_media_cb(blk, false, &error_abort);
2597 out:
2598 aio_context_release(aio_context);
2601 void qmp_blockdev_remove_medium(const char *id, Error **errp)
2603 blockdev_remove_medium(false, NULL, true, id, errp);
2606 static void qmp_blockdev_insert_anon_medium(BlockBackend *blk,
2607 BlockDriverState *bs, Error **errp)
2609 Error *local_err = NULL;
2610 bool has_device;
2611 int ret;
2613 /* For BBs without a device, we can exchange the BDS tree at will */
2614 has_device = blk_get_attached_dev(blk);
2616 if (has_device && !blk_dev_has_removable_media(blk)) {
2617 error_setg(errp, "Device is not removable");
2618 return;
2621 if (has_device && blk_dev_has_tray(blk) && !blk_dev_is_tray_open(blk)) {
2622 error_setg(errp, "Tray of the device is not open");
2623 return;
2626 if (blk_bs(blk)) {
2627 error_setg(errp, "There already is a medium in the device");
2628 return;
2631 ret = blk_insert_bs(blk, bs, errp);
2632 if (ret < 0) {
2633 return;
2636 if (!blk_dev_has_tray(blk)) {
2637 /* For tray-less devices, blockdev-close-tray is a no-op (or may not be
2638 * called at all); therefore, the medium needs to be pushed into the
2639 * slot here.
2640 * Do it after blk_insert_bs() so blk_is_inserted(blk) returns the @load
2641 * value passed here (i.e. true). */
2642 blk_dev_change_media_cb(blk, true, &local_err);
2643 if (local_err) {
2644 error_propagate(errp, local_err);
2645 blk_remove_bs(blk);
2646 return;
2651 static void blockdev_insert_medium(bool has_device, const char *device,
2652 bool has_id, const char *id,
2653 const char *node_name, Error **errp)
2655 BlockBackend *blk;
2656 BlockDriverState *bs;
2658 blk = qmp_get_blk(has_device ? device : NULL,
2659 has_id ? id : NULL,
2660 errp);
2661 if (!blk) {
2662 return;
2665 bs = bdrv_find_node(node_name);
2666 if (!bs) {
2667 error_setg(errp, "Node '%s' not found", node_name);
2668 return;
2671 if (bdrv_has_blk(bs)) {
2672 error_setg(errp, "Node '%s' is already in use", node_name);
2673 return;
2676 qmp_blockdev_insert_anon_medium(blk, bs, errp);
2679 void qmp_blockdev_insert_medium(const char *id, const char *node_name,
2680 Error **errp)
2682 blockdev_insert_medium(false, NULL, true, id, node_name, errp);
2685 void qmp_blockdev_change_medium(bool has_device, const char *device,
2686 bool has_id, const char *id,
2687 const char *filename,
2688 bool has_format, const char *format,
2689 bool has_read_only,
2690 BlockdevChangeReadOnlyMode read_only,
2691 Error **errp)
2693 BlockBackend *blk;
2694 BlockDriverState *medium_bs = NULL;
2695 int bdrv_flags;
2696 bool detect_zeroes;
2697 int rc;
2698 QDict *options = NULL;
2699 Error *err = NULL;
2701 blk = qmp_get_blk(has_device ? device : NULL,
2702 has_id ? id : NULL,
2703 errp);
2704 if (!blk) {
2705 goto fail;
2708 if (blk_bs(blk)) {
2709 blk_update_root_state(blk);
2712 bdrv_flags = blk_get_open_flags_from_root_state(blk);
2713 bdrv_flags &= ~(BDRV_O_TEMPORARY | BDRV_O_SNAPSHOT | BDRV_O_NO_BACKING |
2714 BDRV_O_PROTOCOL);
2716 if (!has_read_only) {
2717 read_only = BLOCKDEV_CHANGE_READ_ONLY_MODE_RETAIN;
2720 switch (read_only) {
2721 case BLOCKDEV_CHANGE_READ_ONLY_MODE_RETAIN:
2722 break;
2724 case BLOCKDEV_CHANGE_READ_ONLY_MODE_READ_ONLY:
2725 bdrv_flags &= ~BDRV_O_RDWR;
2726 break;
2728 case BLOCKDEV_CHANGE_READ_ONLY_MODE_READ_WRITE:
2729 bdrv_flags |= BDRV_O_RDWR;
2730 break;
2732 default:
2733 abort();
2736 options = qdict_new();
2737 detect_zeroes = blk_get_detect_zeroes_from_root_state(blk);
2738 qdict_put_str(options, "detect-zeroes", detect_zeroes ? "on" : "off");
2740 if (has_format) {
2741 qdict_put_str(options, "driver", format);
2744 medium_bs = bdrv_open(filename, NULL, options, bdrv_flags, errp);
2745 if (!medium_bs) {
2746 goto fail;
2749 rc = do_open_tray(has_device ? device : NULL,
2750 has_id ? id : NULL,
2751 false, &err);
2752 if (rc && rc != -ENOSYS) {
2753 error_propagate(errp, err);
2754 goto fail;
2756 error_free(err);
2757 err = NULL;
2759 blockdev_remove_medium(has_device, device, has_id, id, &err);
2760 if (err) {
2761 error_propagate(errp, err);
2762 goto fail;
2765 qmp_blockdev_insert_anon_medium(blk, medium_bs, &err);
2766 if (err) {
2767 error_propagate(errp, err);
2768 goto fail;
2771 qmp_blockdev_close_tray(has_device, device, has_id, id, errp);
2773 fail:
2774 /* If the medium has been inserted, the device has its own reference, so
2775 * ours must be relinquished; and if it has not been inserted successfully,
2776 * the reference must be relinquished anyway */
2777 bdrv_unref(medium_bs);
2780 /* throttling disk I/O limits */
2781 void qmp_block_set_io_throttle(BlockIOThrottle *arg, Error **errp)
2783 ThrottleConfig cfg;
2784 BlockDriverState *bs;
2785 BlockBackend *blk;
2786 AioContext *aio_context;
2788 blk = qmp_get_blk(arg->has_device ? arg->device : NULL,
2789 arg->has_id ? arg->id : NULL,
2790 errp);
2791 if (!blk) {
2792 return;
2795 aio_context = blk_get_aio_context(blk);
2796 aio_context_acquire(aio_context);
2798 bs = blk_bs(blk);
2799 if (!bs) {
2800 error_setg(errp, "Device has no medium");
2801 goto out;
2804 throttle_config_init(&cfg);
2805 cfg.buckets[THROTTLE_BPS_TOTAL].avg = arg->bps;
2806 cfg.buckets[THROTTLE_BPS_READ].avg = arg->bps_rd;
2807 cfg.buckets[THROTTLE_BPS_WRITE].avg = arg->bps_wr;
2809 cfg.buckets[THROTTLE_OPS_TOTAL].avg = arg->iops;
2810 cfg.buckets[THROTTLE_OPS_READ].avg = arg->iops_rd;
2811 cfg.buckets[THROTTLE_OPS_WRITE].avg = arg->iops_wr;
2813 if (arg->has_bps_max) {
2814 cfg.buckets[THROTTLE_BPS_TOTAL].max = arg->bps_max;
2816 if (arg->has_bps_rd_max) {
2817 cfg.buckets[THROTTLE_BPS_READ].max = arg->bps_rd_max;
2819 if (arg->has_bps_wr_max) {
2820 cfg.buckets[THROTTLE_BPS_WRITE].max = arg->bps_wr_max;
2822 if (arg->has_iops_max) {
2823 cfg.buckets[THROTTLE_OPS_TOTAL].max = arg->iops_max;
2825 if (arg->has_iops_rd_max) {
2826 cfg.buckets[THROTTLE_OPS_READ].max = arg->iops_rd_max;
2828 if (arg->has_iops_wr_max) {
2829 cfg.buckets[THROTTLE_OPS_WRITE].max = arg->iops_wr_max;
2832 if (arg->has_bps_max_length) {
2833 cfg.buckets[THROTTLE_BPS_TOTAL].burst_length = arg->bps_max_length;
2835 if (arg->has_bps_rd_max_length) {
2836 cfg.buckets[THROTTLE_BPS_READ].burst_length = arg->bps_rd_max_length;
2838 if (arg->has_bps_wr_max_length) {
2839 cfg.buckets[THROTTLE_BPS_WRITE].burst_length = arg->bps_wr_max_length;
2841 if (arg->has_iops_max_length) {
2842 cfg.buckets[THROTTLE_OPS_TOTAL].burst_length = arg->iops_max_length;
2844 if (arg->has_iops_rd_max_length) {
2845 cfg.buckets[THROTTLE_OPS_READ].burst_length = arg->iops_rd_max_length;
2847 if (arg->has_iops_wr_max_length) {
2848 cfg.buckets[THROTTLE_OPS_WRITE].burst_length = arg->iops_wr_max_length;
2851 if (arg->has_iops_size) {
2852 cfg.op_size = arg->iops_size;
2855 if (!throttle_is_valid(&cfg, errp)) {
2856 goto out;
2859 if (throttle_enabled(&cfg)) {
2860 /* Enable I/O limits if they're not enabled yet, otherwise
2861 * just update the throttling group. */
2862 if (!blk_get_public(blk)->throttle_group_member.throttle_state) {
2863 blk_io_limits_enable(blk,
2864 arg->has_group ? arg->group :
2865 arg->has_device ? arg->device :
2866 arg->id);
2867 } else if (arg->has_group) {
2868 blk_io_limits_update_group(blk, arg->group);
2870 /* Set the new throttling configuration */
2871 blk_set_io_limits(blk, &cfg);
2872 } else if (blk_get_public(blk)->throttle_group_member.throttle_state) {
2873 /* If all throttling settings are set to 0, disable I/O limits */
2874 blk_io_limits_disable(blk);
2877 out:
2878 aio_context_release(aio_context);
2881 void qmp_block_dirty_bitmap_add(const char *node, const char *name,
2882 bool has_granularity, uint32_t granularity,
2883 bool has_persistent, bool persistent,
2884 bool has_autoload, bool autoload,
2885 bool has_disabled, bool disabled,
2886 Error **errp)
2888 BlockDriverState *bs;
2889 BdrvDirtyBitmap *bitmap;
2891 if (!name || name[0] == '\0') {
2892 error_setg(errp, "Bitmap name cannot be empty");
2893 return;
2896 bs = bdrv_lookup_bs(node, node, errp);
2897 if (!bs) {
2898 return;
2901 if (has_granularity) {
2902 if (granularity < 512 || !is_power_of_2(granularity)) {
2903 error_setg(errp, "Granularity must be power of 2 "
2904 "and at least 512");
2905 return;
2907 } else {
2908 /* Default to cluster size, if available: */
2909 granularity = bdrv_get_default_bitmap_granularity(bs);
2912 if (!has_persistent) {
2913 persistent = false;
2916 if (has_autoload) {
2917 warn_report("Autoload option is deprecated and its value is ignored");
2920 if (!has_disabled) {
2921 disabled = false;
2924 if (persistent &&
2925 !bdrv_can_store_new_dirty_bitmap(bs, name, granularity, errp))
2927 return;
2930 bitmap = bdrv_create_dirty_bitmap(bs, granularity, name, errp);
2931 if (bitmap == NULL) {
2932 return;
2935 if (disabled) {
2936 bdrv_disable_dirty_bitmap(bitmap);
2939 bdrv_dirty_bitmap_set_persistance(bitmap, persistent);
2942 void qmp_block_dirty_bitmap_remove(const char *node, const char *name,
2943 Error **errp)
2945 BlockDriverState *bs;
2946 BdrvDirtyBitmap *bitmap;
2947 Error *local_err = NULL;
2949 bitmap = block_dirty_bitmap_lookup(node, name, &bs, errp);
2950 if (!bitmap || !bs) {
2951 return;
2954 if (bdrv_dirty_bitmap_frozen(bitmap)) {
2955 error_setg(errp,
2956 "Bitmap '%s' is currently frozen and cannot be removed",
2957 name);
2958 return;
2959 } else if (bdrv_dirty_bitmap_qmp_locked(bitmap)) {
2960 error_setg(errp,
2961 "Bitmap '%s' is currently locked and cannot be removed",
2962 name);
2963 return;
2966 if (bdrv_dirty_bitmap_get_persistance(bitmap)) {
2967 bdrv_remove_persistent_dirty_bitmap(bs, name, &local_err);
2968 if (local_err != NULL) {
2969 error_propagate(errp, local_err);
2970 return;
2974 bdrv_release_dirty_bitmap(bs, bitmap);
2978 * Completely clear a bitmap, for the purposes of synchronizing a bitmap
2979 * immediately after a full backup operation.
2981 void qmp_block_dirty_bitmap_clear(const char *node, const char *name,
2982 Error **errp)
2984 BdrvDirtyBitmap *bitmap;
2985 BlockDriverState *bs;
2987 bitmap = block_dirty_bitmap_lookup(node, name, &bs, errp);
2988 if (!bitmap || !bs) {
2989 return;
2992 if (bdrv_dirty_bitmap_frozen(bitmap)) {
2993 error_setg(errp,
2994 "Bitmap '%s' is currently frozen and cannot be modified",
2995 name);
2996 return;
2997 } else if (bdrv_dirty_bitmap_qmp_locked(bitmap)) {
2998 error_setg(errp,
2999 "Bitmap '%s' is currently locked and cannot be modified",
3000 name);
3001 return;
3002 } else if (!bdrv_dirty_bitmap_enabled(bitmap)) {
3003 error_setg(errp,
3004 "Bitmap '%s' is currently disabled and cannot be cleared",
3005 name);
3006 return;
3007 } else if (bdrv_dirty_bitmap_readonly(bitmap)) {
3008 error_setg(errp, "Bitmap '%s' is readonly and cannot be cleared", name);
3009 return;
3012 bdrv_clear_dirty_bitmap(bitmap, NULL);
3015 void qmp_x_block_dirty_bitmap_enable(const char *node, const char *name,
3016 Error **errp)
3018 BlockDriverState *bs;
3019 BdrvDirtyBitmap *bitmap;
3021 bitmap = block_dirty_bitmap_lookup(node, name, &bs, errp);
3022 if (!bitmap) {
3023 return;
3026 if (bdrv_dirty_bitmap_frozen(bitmap)) {
3027 error_setg(errp,
3028 "Bitmap '%s' is currently frozen and cannot be enabled",
3029 name);
3030 return;
3033 bdrv_enable_dirty_bitmap(bitmap);
3036 void qmp_x_block_dirty_bitmap_disable(const char *node, const char *name,
3037 Error **errp)
3039 BlockDriverState *bs;
3040 BdrvDirtyBitmap *bitmap;
3042 bitmap = block_dirty_bitmap_lookup(node, name, &bs, errp);
3043 if (!bitmap) {
3044 return;
3047 if (bdrv_dirty_bitmap_frozen(bitmap)) {
3048 error_setg(errp,
3049 "Bitmap '%s' is currently frozen and cannot be disabled",
3050 name);
3051 return;
3054 bdrv_disable_dirty_bitmap(bitmap);
3057 void qmp_x_block_dirty_bitmap_merge(const char *node, const char *dst_name,
3058 const char *src_name, Error **errp)
3060 BlockDriverState *bs;
3061 BdrvDirtyBitmap *dst, *src;
3063 dst = block_dirty_bitmap_lookup(node, dst_name, &bs, errp);
3064 if (!dst) {
3065 return;
3068 if (bdrv_dirty_bitmap_frozen(dst)) {
3069 error_setg(errp, "Bitmap '%s' is frozen and cannot be modified",
3070 dst_name);
3071 return;
3072 } else if (bdrv_dirty_bitmap_readonly(dst)) {
3073 error_setg(errp, "Bitmap '%s' is readonly and cannot be modified",
3074 dst_name);
3075 return;
3078 src = bdrv_find_dirty_bitmap(bs, src_name);
3079 if (!src) {
3080 error_setg(errp, "Dirty bitmap '%s' not found", src_name);
3081 return;
3084 bdrv_merge_dirty_bitmap(dst, src, errp);
3087 BlockDirtyBitmapSha256 *qmp_x_debug_block_dirty_bitmap_sha256(const char *node,
3088 const char *name,
3089 Error **errp)
3091 BdrvDirtyBitmap *bitmap;
3092 BlockDriverState *bs;
3093 BlockDirtyBitmapSha256 *ret = NULL;
3094 char *sha256;
3096 bitmap = block_dirty_bitmap_lookup(node, name, &bs, errp);
3097 if (!bitmap || !bs) {
3098 return NULL;
3101 sha256 = bdrv_dirty_bitmap_sha256(bitmap, errp);
3102 if (sha256 == NULL) {
3103 return NULL;
3106 ret = g_new(BlockDirtyBitmapSha256, 1);
3107 ret->sha256 = sha256;
3109 return ret;
3112 void hmp_drive_del(Monitor *mon, const QDict *qdict)
3114 const char *id = qdict_get_str(qdict, "id");
3115 BlockBackend *blk;
3116 BlockDriverState *bs;
3117 AioContext *aio_context;
3118 Error *local_err = NULL;
3120 bs = bdrv_find_node(id);
3121 if (bs) {
3122 qmp_blockdev_del(id, &local_err);
3123 if (local_err) {
3124 error_report_err(local_err);
3126 return;
3129 blk = blk_by_name(id);
3130 if (!blk) {
3131 error_report("Device '%s' not found", id);
3132 return;
3135 if (!blk_legacy_dinfo(blk)) {
3136 error_report("Deleting device added with blockdev-add"
3137 " is not supported");
3138 return;
3141 aio_context = blk_get_aio_context(blk);
3142 aio_context_acquire(aio_context);
3144 bs = blk_bs(blk);
3145 if (bs) {
3146 if (bdrv_op_is_blocked(bs, BLOCK_OP_TYPE_DRIVE_DEL, &local_err)) {
3147 error_report_err(local_err);
3148 aio_context_release(aio_context);
3149 return;
3152 blk_remove_bs(blk);
3155 /* Make the BlockBackend and the attached BlockDriverState anonymous */
3156 monitor_remove_blk(blk);
3158 /* If this BlockBackend has a device attached to it, its refcount will be
3159 * decremented when the device is removed; otherwise we have to do so here.
3161 if (blk_get_attached_dev(blk)) {
3162 /* Further I/O must not pause the guest */
3163 blk_set_on_error(blk, BLOCKDEV_ON_ERROR_REPORT,
3164 BLOCKDEV_ON_ERROR_REPORT);
3165 } else {
3166 blk_unref(blk);
3169 aio_context_release(aio_context);
3172 void qmp_block_resize(bool has_device, const char *device,
3173 bool has_node_name, const char *node_name,
3174 int64_t size, Error **errp)
3176 Error *local_err = NULL;
3177 BlockBackend *blk = NULL;
3178 BlockDriverState *bs;
3179 AioContext *aio_context;
3180 int ret;
3182 bs = bdrv_lookup_bs(has_device ? device : NULL,
3183 has_node_name ? node_name : NULL,
3184 &local_err);
3185 if (local_err) {
3186 error_propagate(errp, local_err);
3187 return;
3190 aio_context = bdrv_get_aio_context(bs);
3191 aio_context_acquire(aio_context);
3193 if (!bdrv_is_first_non_filter(bs)) {
3194 error_setg(errp, QERR_FEATURE_DISABLED, "resize");
3195 goto out;
3198 if (size < 0) {
3199 error_setg(errp, QERR_INVALID_PARAMETER_VALUE, "size", "a >0 size");
3200 goto out;
3203 if (bdrv_op_is_blocked(bs, BLOCK_OP_TYPE_RESIZE, NULL)) {
3204 error_setg(errp, QERR_DEVICE_IN_USE, device);
3205 goto out;
3208 blk = blk_new(BLK_PERM_RESIZE, BLK_PERM_ALL);
3209 ret = blk_insert_bs(blk, bs, errp);
3210 if (ret < 0) {
3211 goto out;
3214 bdrv_drained_begin(bs);
3215 ret = blk_truncate(blk, size, PREALLOC_MODE_OFF, errp);
3216 bdrv_drained_end(bs);
3218 out:
3219 blk_unref(blk);
3220 aio_context_release(aio_context);
3223 void qmp_block_stream(bool has_job_id, const char *job_id, const char *device,
3224 bool has_base, const char *base,
3225 bool has_base_node, const char *base_node,
3226 bool has_backing_file, const char *backing_file,
3227 bool has_speed, int64_t speed,
3228 bool has_on_error, BlockdevOnError on_error,
3229 Error **errp)
3231 BlockDriverState *bs, *iter;
3232 BlockDriverState *base_bs = NULL;
3233 AioContext *aio_context;
3234 Error *local_err = NULL;
3235 const char *base_name = NULL;
3237 if (!has_on_error) {
3238 on_error = BLOCKDEV_ON_ERROR_REPORT;
3241 bs = bdrv_lookup_bs(device, device, errp);
3242 if (!bs) {
3243 return;
3246 aio_context = bdrv_get_aio_context(bs);
3247 aio_context_acquire(aio_context);
3249 if (has_base && has_base_node) {
3250 error_setg(errp, "'base' and 'base-node' cannot be specified "
3251 "at the same time");
3252 goto out;
3255 if (has_base) {
3256 base_bs = bdrv_find_backing_image(bs, base);
3257 if (base_bs == NULL) {
3258 error_setg(errp, QERR_BASE_NOT_FOUND, base);
3259 goto out;
3261 assert(bdrv_get_aio_context(base_bs) == aio_context);
3262 base_name = base;
3265 if (has_base_node) {
3266 base_bs = bdrv_lookup_bs(NULL, base_node, errp);
3267 if (!base_bs) {
3268 goto out;
3270 if (bs == base_bs || !bdrv_chain_contains(bs, base_bs)) {
3271 error_setg(errp, "Node '%s' is not a backing image of '%s'",
3272 base_node, device);
3273 goto out;
3275 assert(bdrv_get_aio_context(base_bs) == aio_context);
3276 base_name = base_bs->filename;
3279 /* Check for op blockers in the whole chain between bs and base */
3280 for (iter = bs; iter && iter != base_bs; iter = backing_bs(iter)) {
3281 if (bdrv_op_is_blocked(iter, BLOCK_OP_TYPE_STREAM, errp)) {
3282 goto out;
3286 /* if we are streaming the entire chain, the result will have no backing
3287 * file, and specifying one is therefore an error */
3288 if (base_bs == NULL && has_backing_file) {
3289 error_setg(errp, "backing file specified, but streaming the "
3290 "entire chain");
3291 goto out;
3294 /* backing_file string overrides base bs filename */
3295 base_name = has_backing_file ? backing_file : base_name;
3297 stream_start(has_job_id ? job_id : NULL, bs, base_bs, base_name,
3298 has_speed ? speed : 0, on_error, &local_err);
3299 if (local_err) {
3300 error_propagate(errp, local_err);
3301 goto out;
3304 trace_qmp_block_stream(bs, bs->job);
3306 out:
3307 aio_context_release(aio_context);
3310 void qmp_block_commit(bool has_job_id, const char *job_id, const char *device,
3311 bool has_base, const char *base,
3312 bool has_top, const char *top,
3313 bool has_backing_file, const char *backing_file,
3314 bool has_speed, int64_t speed,
3315 bool has_filter_node_name, const char *filter_node_name,
3316 Error **errp)
3318 BlockDriverState *bs;
3319 BlockDriverState *iter;
3320 BlockDriverState *base_bs, *top_bs;
3321 AioContext *aio_context;
3322 Error *local_err = NULL;
3323 /* This will be part of the QMP command, if/when the
3324 * BlockdevOnError change for blkmirror makes it in
3326 BlockdevOnError on_error = BLOCKDEV_ON_ERROR_REPORT;
3328 if (!has_speed) {
3329 speed = 0;
3331 if (!has_filter_node_name) {
3332 filter_node_name = NULL;
3335 /* Important Note:
3336 * libvirt relies on the DeviceNotFound error class in order to probe for
3337 * live commit feature versions; for this to work, we must make sure to
3338 * perform the device lookup before any generic errors that may occur in a
3339 * scenario in which all optional arguments are omitted. */
3340 bs = qmp_get_root_bs(device, &local_err);
3341 if (!bs) {
3342 bs = bdrv_lookup_bs(device, device, NULL);
3343 if (!bs) {
3344 error_free(local_err);
3345 error_set(errp, ERROR_CLASS_DEVICE_NOT_FOUND,
3346 "Device '%s' not found", device);
3347 } else {
3348 error_propagate(errp, local_err);
3350 return;
3353 aio_context = bdrv_get_aio_context(bs);
3354 aio_context_acquire(aio_context);
3356 if (bdrv_op_is_blocked(bs, BLOCK_OP_TYPE_COMMIT_SOURCE, errp)) {
3357 goto out;
3360 /* default top_bs is the active layer */
3361 top_bs = bs;
3363 if (has_top && top) {
3364 if (strcmp(bs->filename, top) != 0) {
3365 top_bs = bdrv_find_backing_image(bs, top);
3369 if (top_bs == NULL) {
3370 error_setg(errp, "Top image file %s not found", top ? top : "NULL");
3371 goto out;
3374 assert(bdrv_get_aio_context(top_bs) == aio_context);
3376 if (has_base && base) {
3377 base_bs = bdrv_find_backing_image(top_bs, base);
3378 } else {
3379 base_bs = bdrv_find_base(top_bs);
3382 if (base_bs == NULL) {
3383 error_setg(errp, QERR_BASE_NOT_FOUND, base ? base : "NULL");
3384 goto out;
3387 assert(bdrv_get_aio_context(base_bs) == aio_context);
3389 for (iter = top_bs; iter != backing_bs(base_bs); iter = backing_bs(iter)) {
3390 if (bdrv_op_is_blocked(iter, BLOCK_OP_TYPE_COMMIT_TARGET, errp)) {
3391 goto out;
3395 /* Do not allow attempts to commit an image into itself */
3396 if (top_bs == base_bs) {
3397 error_setg(errp, "cannot commit an image into itself");
3398 goto out;
3401 if (top_bs == bs) {
3402 if (has_backing_file) {
3403 error_setg(errp, "'backing-file' specified,"
3404 " but 'top' is the active layer");
3405 goto out;
3407 commit_active_start(has_job_id ? job_id : NULL, bs, base_bs,
3408 JOB_DEFAULT, speed, on_error,
3409 filter_node_name, NULL, NULL, false, &local_err);
3410 } else {
3411 BlockDriverState *overlay_bs = bdrv_find_overlay(bs, top_bs);
3412 if (bdrv_op_is_blocked(overlay_bs, BLOCK_OP_TYPE_COMMIT_TARGET, errp)) {
3413 goto out;
3415 commit_start(has_job_id ? job_id : NULL, bs, base_bs, top_bs, speed,
3416 on_error, has_backing_file ? backing_file : NULL,
3417 filter_node_name, &local_err);
3419 if (local_err != NULL) {
3420 error_propagate(errp, local_err);
3421 goto out;
3424 out:
3425 aio_context_release(aio_context);
3428 static BlockJob *do_drive_backup(DriveBackup *backup, JobTxn *txn,
3429 Error **errp)
3431 BlockDriverState *bs;
3432 BlockDriverState *target_bs;
3433 BlockDriverState *source = NULL;
3434 BlockJob *job = NULL;
3435 BdrvDirtyBitmap *bmap = NULL;
3436 AioContext *aio_context;
3437 QDict *options = NULL;
3438 Error *local_err = NULL;
3439 int flags, job_flags = JOB_DEFAULT;
3440 int64_t size;
3441 bool set_backing_hd = false;
3443 if (!backup->has_speed) {
3444 backup->speed = 0;
3446 if (!backup->has_on_source_error) {
3447 backup->on_source_error = BLOCKDEV_ON_ERROR_REPORT;
3449 if (!backup->has_on_target_error) {
3450 backup->on_target_error = BLOCKDEV_ON_ERROR_REPORT;
3452 if (!backup->has_mode) {
3453 backup->mode = NEW_IMAGE_MODE_ABSOLUTE_PATHS;
3455 if (!backup->has_job_id) {
3456 backup->job_id = NULL;
3458 if (!backup->has_auto_finalize) {
3459 backup->auto_finalize = true;
3461 if (!backup->has_auto_dismiss) {
3462 backup->auto_dismiss = true;
3464 if (!backup->has_compress) {
3465 backup->compress = false;
3468 bs = qmp_get_root_bs(backup->device, errp);
3469 if (!bs) {
3470 return NULL;
3473 aio_context = bdrv_get_aio_context(bs);
3474 aio_context_acquire(aio_context);
3476 if (!backup->has_format) {
3477 backup->format = backup->mode == NEW_IMAGE_MODE_EXISTING ?
3478 NULL : (char*) bs->drv->format_name;
3481 /* Early check to avoid creating target */
3482 if (bdrv_op_is_blocked(bs, BLOCK_OP_TYPE_BACKUP_SOURCE, errp)) {
3483 goto out;
3486 flags = bs->open_flags | BDRV_O_RDWR;
3488 /* See if we have a backing HD we can use to create our new image
3489 * on top of. */
3490 if (backup->sync == MIRROR_SYNC_MODE_TOP) {
3491 source = backing_bs(bs);
3492 if (!source) {
3493 backup->sync = MIRROR_SYNC_MODE_FULL;
3496 if (backup->sync == MIRROR_SYNC_MODE_NONE) {
3497 source = bs;
3498 flags |= BDRV_O_NO_BACKING;
3499 set_backing_hd = true;
3502 size = bdrv_getlength(bs);
3503 if (size < 0) {
3504 error_setg_errno(errp, -size, "bdrv_getlength failed");
3505 goto out;
3508 if (backup->mode != NEW_IMAGE_MODE_EXISTING) {
3509 assert(backup->format);
3510 if (source) {
3511 bdrv_img_create(backup->target, backup->format, source->filename,
3512 source->drv->format_name, NULL,
3513 size, flags, false, &local_err);
3514 } else {
3515 bdrv_img_create(backup->target, backup->format, NULL, NULL, NULL,
3516 size, flags, false, &local_err);
3520 if (local_err) {
3521 error_propagate(errp, local_err);
3522 goto out;
3525 if (backup->format) {
3526 if (!options) {
3527 options = qdict_new();
3529 qdict_put_str(options, "driver", backup->format);
3532 target_bs = bdrv_open(backup->target, NULL, options, flags, errp);
3533 if (!target_bs) {
3534 goto out;
3537 bdrv_set_aio_context(target_bs, aio_context);
3539 if (set_backing_hd) {
3540 bdrv_set_backing_hd(target_bs, source, &local_err);
3541 if (local_err) {
3542 bdrv_unref(target_bs);
3543 goto out;
3547 if (backup->has_bitmap) {
3548 bmap = bdrv_find_dirty_bitmap(bs, backup->bitmap);
3549 if (!bmap) {
3550 error_setg(errp, "Bitmap '%s' could not be found", backup->bitmap);
3551 bdrv_unref(target_bs);
3552 goto out;
3554 if (bdrv_dirty_bitmap_qmp_locked(bmap)) {
3555 error_setg(errp,
3556 "Bitmap '%s' is currently locked and cannot be used for "
3557 "backup", backup->bitmap);
3558 goto out;
3561 if (!backup->auto_finalize) {
3562 job_flags |= JOB_MANUAL_FINALIZE;
3564 if (!backup->auto_dismiss) {
3565 job_flags |= JOB_MANUAL_DISMISS;
3568 job = backup_job_create(backup->job_id, bs, target_bs, backup->speed,
3569 backup->sync, bmap, backup->compress,
3570 backup->on_source_error, backup->on_target_error,
3571 job_flags, NULL, NULL, txn, &local_err);
3572 bdrv_unref(target_bs);
3573 if (local_err != NULL) {
3574 error_propagate(errp, local_err);
3575 goto out;
3578 out:
3579 aio_context_release(aio_context);
3580 return job;
3583 void qmp_drive_backup(DriveBackup *arg, Error **errp)
3586 BlockJob *job;
3587 job = do_drive_backup(arg, NULL, errp);
3588 if (job) {
3589 job_start(&job->job);
3593 BlockDeviceInfoList *qmp_query_named_block_nodes(Error **errp)
3595 return bdrv_named_nodes_list(errp);
3598 BlockJob *do_blockdev_backup(BlockdevBackup *backup, JobTxn *txn,
3599 Error **errp)
3601 BlockDriverState *bs;
3602 BlockDriverState *target_bs;
3603 Error *local_err = NULL;
3604 AioContext *aio_context;
3605 BlockJob *job = NULL;
3606 int job_flags = JOB_DEFAULT;
3608 if (!backup->has_speed) {
3609 backup->speed = 0;
3611 if (!backup->has_on_source_error) {
3612 backup->on_source_error = BLOCKDEV_ON_ERROR_REPORT;
3614 if (!backup->has_on_target_error) {
3615 backup->on_target_error = BLOCKDEV_ON_ERROR_REPORT;
3617 if (!backup->has_job_id) {
3618 backup->job_id = NULL;
3620 if (!backup->has_auto_finalize) {
3621 backup->auto_finalize = true;
3623 if (!backup->has_auto_dismiss) {
3624 backup->auto_dismiss = true;
3626 if (!backup->has_compress) {
3627 backup->compress = false;
3630 bs = bdrv_lookup_bs(backup->device, backup->device, errp);
3631 if (!bs) {
3632 return NULL;
3635 aio_context = bdrv_get_aio_context(bs);
3636 aio_context_acquire(aio_context);
3638 target_bs = bdrv_lookup_bs(backup->target, backup->target, errp);
3639 if (!target_bs) {
3640 goto out;
3643 if (bdrv_get_aio_context(target_bs) != aio_context) {
3644 if (!bdrv_has_blk(target_bs)) {
3645 /* The target BDS is not attached, we can safely move it to another
3646 * AioContext. */
3647 bdrv_set_aio_context(target_bs, aio_context);
3648 } else {
3649 error_setg(errp, "Target is attached to a different thread from "
3650 "source.");
3651 goto out;
3654 if (!backup->auto_finalize) {
3655 job_flags |= JOB_MANUAL_FINALIZE;
3657 if (!backup->auto_dismiss) {
3658 job_flags |= JOB_MANUAL_DISMISS;
3660 job = backup_job_create(backup->job_id, bs, target_bs, backup->speed,
3661 backup->sync, NULL, backup->compress,
3662 backup->on_source_error, backup->on_target_error,
3663 job_flags, NULL, NULL, txn, &local_err);
3664 if (local_err != NULL) {
3665 error_propagate(errp, local_err);
3667 out:
3668 aio_context_release(aio_context);
3669 return job;
3672 void qmp_blockdev_backup(BlockdevBackup *arg, Error **errp)
3674 BlockJob *job;
3675 job = do_blockdev_backup(arg, NULL, errp);
3676 if (job) {
3677 job_start(&job->job);
3681 /* Parameter check and block job starting for drive mirroring.
3682 * Caller should hold @device and @target's aio context (must be the same).
3684 static void blockdev_mirror_common(const char *job_id, BlockDriverState *bs,
3685 BlockDriverState *target,
3686 bool has_replaces, const char *replaces,
3687 enum MirrorSyncMode sync,
3688 BlockMirrorBackingMode backing_mode,
3689 bool has_speed, int64_t speed,
3690 bool has_granularity, uint32_t granularity,
3691 bool has_buf_size, int64_t buf_size,
3692 bool has_on_source_error,
3693 BlockdevOnError on_source_error,
3694 bool has_on_target_error,
3695 BlockdevOnError on_target_error,
3696 bool has_unmap, bool unmap,
3697 bool has_filter_node_name,
3698 const char *filter_node_name,
3699 bool has_copy_mode, MirrorCopyMode copy_mode,
3700 Error **errp)
3703 if (!has_speed) {
3704 speed = 0;
3706 if (!has_on_source_error) {
3707 on_source_error = BLOCKDEV_ON_ERROR_REPORT;
3709 if (!has_on_target_error) {
3710 on_target_error = BLOCKDEV_ON_ERROR_REPORT;
3712 if (!has_granularity) {
3713 granularity = 0;
3715 if (!has_buf_size) {
3716 buf_size = 0;
3718 if (!has_unmap) {
3719 unmap = true;
3721 if (!has_filter_node_name) {
3722 filter_node_name = NULL;
3724 if (!has_copy_mode) {
3725 copy_mode = MIRROR_COPY_MODE_BACKGROUND;
3728 if (granularity != 0 && (granularity < 512 || granularity > 1048576 * 64)) {
3729 error_setg(errp, QERR_INVALID_PARAMETER_VALUE, "granularity",
3730 "a value in range [512B, 64MB]");
3731 return;
3733 if (granularity & (granularity - 1)) {
3734 error_setg(errp, QERR_INVALID_PARAMETER_VALUE, "granularity",
3735 "power of 2");
3736 return;
3739 if (bdrv_op_is_blocked(bs, BLOCK_OP_TYPE_MIRROR_SOURCE, errp)) {
3740 return;
3742 if (bdrv_op_is_blocked(target, BLOCK_OP_TYPE_MIRROR_TARGET, errp)) {
3743 return;
3746 if (!bs->backing && sync == MIRROR_SYNC_MODE_TOP) {
3747 sync = MIRROR_SYNC_MODE_FULL;
3750 /* pass the node name to replace to mirror start since it's loose coupling
3751 * and will allow to check whether the node still exist at mirror completion
3753 mirror_start(job_id, bs, target,
3754 has_replaces ? replaces : NULL,
3755 speed, granularity, buf_size, sync, backing_mode,
3756 on_source_error, on_target_error, unmap, filter_node_name,
3757 copy_mode, errp);
3760 void qmp_drive_mirror(DriveMirror *arg, Error **errp)
3762 BlockDriverState *bs;
3763 BlockDriverState *source, *target_bs;
3764 AioContext *aio_context;
3765 BlockMirrorBackingMode backing_mode;
3766 Error *local_err = NULL;
3767 QDict *options = NULL;
3768 int flags;
3769 int64_t size;
3770 const char *format = arg->format;
3772 bs = qmp_get_root_bs(arg->device, errp);
3773 if (!bs) {
3774 return;
3777 /* Early check to avoid creating target */
3778 if (bdrv_op_is_blocked(bs, BLOCK_OP_TYPE_MIRROR_SOURCE, errp)) {
3779 return;
3782 aio_context = bdrv_get_aio_context(bs);
3783 aio_context_acquire(aio_context);
3785 if (!arg->has_mode) {
3786 arg->mode = NEW_IMAGE_MODE_ABSOLUTE_PATHS;
3789 if (!arg->has_format) {
3790 format = (arg->mode == NEW_IMAGE_MODE_EXISTING
3791 ? NULL : bs->drv->format_name);
3794 flags = bs->open_flags | BDRV_O_RDWR;
3795 source = backing_bs(bs);
3796 if (!source && arg->sync == MIRROR_SYNC_MODE_TOP) {
3797 arg->sync = MIRROR_SYNC_MODE_FULL;
3799 if (arg->sync == MIRROR_SYNC_MODE_NONE) {
3800 source = bs;
3803 size = bdrv_getlength(bs);
3804 if (size < 0) {
3805 error_setg_errno(errp, -size, "bdrv_getlength failed");
3806 goto out;
3809 if (arg->has_replaces) {
3810 BlockDriverState *to_replace_bs;
3811 AioContext *replace_aio_context;
3812 int64_t replace_size;
3814 if (!arg->has_node_name) {
3815 error_setg(errp, "a node-name must be provided when replacing a"
3816 " named node of the graph");
3817 goto out;
3820 to_replace_bs = check_to_replace_node(bs, arg->replaces, &local_err);
3822 if (!to_replace_bs) {
3823 error_propagate(errp, local_err);
3824 goto out;
3827 replace_aio_context = bdrv_get_aio_context(to_replace_bs);
3828 aio_context_acquire(replace_aio_context);
3829 replace_size = bdrv_getlength(to_replace_bs);
3830 aio_context_release(replace_aio_context);
3832 if (size != replace_size) {
3833 error_setg(errp, "cannot replace image with a mirror image of "
3834 "different size");
3835 goto out;
3839 if (arg->mode == NEW_IMAGE_MODE_ABSOLUTE_PATHS) {
3840 backing_mode = MIRROR_SOURCE_BACKING_CHAIN;
3841 } else {
3842 backing_mode = MIRROR_OPEN_BACKING_CHAIN;
3845 /* Don't open backing image in create() */
3846 flags |= BDRV_O_NO_BACKING;
3848 if ((arg->sync == MIRROR_SYNC_MODE_FULL || !source)
3849 && arg->mode != NEW_IMAGE_MODE_EXISTING)
3851 /* create new image w/o backing file */
3852 assert(format);
3853 bdrv_img_create(arg->target, format,
3854 NULL, NULL, NULL, size, flags, false, &local_err);
3855 } else {
3856 switch (arg->mode) {
3857 case NEW_IMAGE_MODE_EXISTING:
3858 break;
3859 case NEW_IMAGE_MODE_ABSOLUTE_PATHS:
3860 /* create new image with backing file */
3861 bdrv_img_create(arg->target, format,
3862 source->filename,
3863 source->drv->format_name,
3864 NULL, size, flags, false, &local_err);
3865 break;
3866 default:
3867 abort();
3871 if (local_err) {
3872 error_propagate(errp, local_err);
3873 goto out;
3876 options = qdict_new();
3877 if (arg->has_node_name) {
3878 qdict_put_str(options, "node-name", arg->node_name);
3880 if (format) {
3881 qdict_put_str(options, "driver", format);
3884 /* Mirroring takes care of copy-on-write using the source's backing
3885 * file.
3887 target_bs = bdrv_open(arg->target, NULL, options, flags, errp);
3888 if (!target_bs) {
3889 goto out;
3892 bdrv_set_aio_context(target_bs, aio_context);
3894 blockdev_mirror_common(arg->has_job_id ? arg->job_id : NULL, bs, target_bs,
3895 arg->has_replaces, arg->replaces, arg->sync,
3896 backing_mode, arg->has_speed, arg->speed,
3897 arg->has_granularity, arg->granularity,
3898 arg->has_buf_size, arg->buf_size,
3899 arg->has_on_source_error, arg->on_source_error,
3900 arg->has_on_target_error, arg->on_target_error,
3901 arg->has_unmap, arg->unmap,
3902 false, NULL,
3903 arg->has_copy_mode, arg->copy_mode,
3904 &local_err);
3905 bdrv_unref(target_bs);
3906 error_propagate(errp, local_err);
3907 out:
3908 aio_context_release(aio_context);
3911 void qmp_blockdev_mirror(bool has_job_id, const char *job_id,
3912 const char *device, const char *target,
3913 bool has_replaces, const char *replaces,
3914 MirrorSyncMode sync,
3915 bool has_speed, int64_t speed,
3916 bool has_granularity, uint32_t granularity,
3917 bool has_buf_size, int64_t buf_size,
3918 bool has_on_source_error,
3919 BlockdevOnError on_source_error,
3920 bool has_on_target_error,
3921 BlockdevOnError on_target_error,
3922 bool has_filter_node_name,
3923 const char *filter_node_name,
3924 bool has_copy_mode, MirrorCopyMode copy_mode,
3925 Error **errp)
3927 BlockDriverState *bs;
3928 BlockDriverState *target_bs;
3929 AioContext *aio_context;
3930 BlockMirrorBackingMode backing_mode = MIRROR_LEAVE_BACKING_CHAIN;
3931 Error *local_err = NULL;
3933 bs = qmp_get_root_bs(device, errp);
3934 if (!bs) {
3935 return;
3938 target_bs = bdrv_lookup_bs(target, target, errp);
3939 if (!target_bs) {
3940 return;
3943 aio_context = bdrv_get_aio_context(bs);
3944 aio_context_acquire(aio_context);
3946 bdrv_set_aio_context(target_bs, aio_context);
3948 blockdev_mirror_common(has_job_id ? job_id : NULL, bs, target_bs,
3949 has_replaces, replaces, sync, backing_mode,
3950 has_speed, speed,
3951 has_granularity, granularity,
3952 has_buf_size, buf_size,
3953 has_on_source_error, on_source_error,
3954 has_on_target_error, on_target_error,
3955 true, true,
3956 has_filter_node_name, filter_node_name,
3957 has_copy_mode, copy_mode,
3958 &local_err);
3959 error_propagate(errp, local_err);
3961 aio_context_release(aio_context);
3964 /* Get a block job using its ID and acquire its AioContext */
3965 static BlockJob *find_block_job(const char *id, AioContext **aio_context,
3966 Error **errp)
3968 BlockJob *job;
3970 assert(id != NULL);
3972 *aio_context = NULL;
3974 job = block_job_get(id);
3976 if (!job) {
3977 error_set(errp, ERROR_CLASS_DEVICE_NOT_ACTIVE,
3978 "Block job '%s' not found", id);
3979 return NULL;
3982 *aio_context = blk_get_aio_context(job->blk);
3983 aio_context_acquire(*aio_context);
3985 return job;
3988 void qmp_block_job_set_speed(const char *device, int64_t speed, Error **errp)
3990 AioContext *aio_context;
3991 BlockJob *job = find_block_job(device, &aio_context, errp);
3993 if (!job) {
3994 return;
3997 block_job_set_speed(job, speed, errp);
3998 aio_context_release(aio_context);
4001 void qmp_block_job_cancel(const char *device,
4002 bool has_force, bool force, Error **errp)
4004 AioContext *aio_context;
4005 BlockJob *job = find_block_job(device, &aio_context, errp);
4007 if (!job) {
4008 return;
4011 if (!has_force) {
4012 force = false;
4015 if (job_user_paused(&job->job) && !force) {
4016 error_setg(errp, "The block job for device '%s' is currently paused",
4017 device);
4018 goto out;
4021 trace_qmp_block_job_cancel(job);
4022 job_user_cancel(&job->job, force, errp);
4023 out:
4024 aio_context_release(aio_context);
4027 void qmp_block_job_pause(const char *device, Error **errp)
4029 AioContext *aio_context;
4030 BlockJob *job = find_block_job(device, &aio_context, errp);
4032 if (!job) {
4033 return;
4036 trace_qmp_block_job_pause(job);
4037 job_user_pause(&job->job, errp);
4038 aio_context_release(aio_context);
4041 void qmp_block_job_resume(const char *device, Error **errp)
4043 AioContext *aio_context;
4044 BlockJob *job = find_block_job(device, &aio_context, errp);
4046 if (!job) {
4047 return;
4050 trace_qmp_block_job_resume(job);
4051 job_user_resume(&job->job, errp);
4052 aio_context_release(aio_context);
4055 void qmp_block_job_complete(const char *device, Error **errp)
4057 AioContext *aio_context;
4058 BlockJob *job = find_block_job(device, &aio_context, errp);
4060 if (!job) {
4061 return;
4064 trace_qmp_block_job_complete(job);
4065 job_complete(&job->job, errp);
4066 aio_context_release(aio_context);
4069 void qmp_block_job_finalize(const char *id, Error **errp)
4071 AioContext *aio_context;
4072 BlockJob *job = find_block_job(id, &aio_context, errp);
4074 if (!job) {
4075 return;
4078 trace_qmp_block_job_finalize(job);
4079 job_finalize(&job->job, errp);
4080 aio_context_release(aio_context);
4083 void qmp_block_job_dismiss(const char *id, Error **errp)
4085 AioContext *aio_context;
4086 BlockJob *bjob = find_block_job(id, &aio_context, errp);
4087 Job *job;
4089 if (!bjob) {
4090 return;
4093 trace_qmp_block_job_dismiss(bjob);
4094 job = &bjob->job;
4095 job_dismiss(&job, errp);
4096 aio_context_release(aio_context);
4099 void qmp_change_backing_file(const char *device,
4100 const char *image_node_name,
4101 const char *backing_file,
4102 Error **errp)
4104 BlockDriverState *bs = NULL;
4105 AioContext *aio_context;
4106 BlockDriverState *image_bs = NULL;
4107 Error *local_err = NULL;
4108 bool ro;
4109 int open_flags;
4110 int ret;
4112 bs = qmp_get_root_bs(device, errp);
4113 if (!bs) {
4114 return;
4117 aio_context = bdrv_get_aio_context(bs);
4118 aio_context_acquire(aio_context);
4120 image_bs = bdrv_lookup_bs(NULL, image_node_name, &local_err);
4121 if (local_err) {
4122 error_propagate(errp, local_err);
4123 goto out;
4126 if (!image_bs) {
4127 error_setg(errp, "image file not found");
4128 goto out;
4131 if (bdrv_find_base(image_bs) == image_bs) {
4132 error_setg(errp, "not allowing backing file change on an image "
4133 "without a backing file");
4134 goto out;
4137 /* even though we are not necessarily operating on bs, we need it to
4138 * determine if block ops are currently prohibited on the chain */
4139 if (bdrv_op_is_blocked(bs, BLOCK_OP_TYPE_CHANGE, errp)) {
4140 goto out;
4143 /* final sanity check */
4144 if (!bdrv_chain_contains(bs, image_bs)) {
4145 error_setg(errp, "'%s' and image file are not in the same chain",
4146 device);
4147 goto out;
4150 /* if not r/w, reopen to make r/w */
4151 open_flags = image_bs->open_flags;
4152 ro = bdrv_is_read_only(image_bs);
4154 if (ro) {
4155 bdrv_reopen(image_bs, open_flags | BDRV_O_RDWR, &local_err);
4156 if (local_err) {
4157 error_propagate(errp, local_err);
4158 goto out;
4162 ret = bdrv_change_backing_file(image_bs, backing_file,
4163 image_bs->drv ? image_bs->drv->format_name : "");
4165 if (ret < 0) {
4166 error_setg_errno(errp, -ret, "Could not change backing file to '%s'",
4167 backing_file);
4168 /* don't exit here, so we can try to restore open flags if
4169 * appropriate */
4172 if (ro) {
4173 bdrv_reopen(image_bs, open_flags, &local_err);
4174 error_propagate(errp, local_err);
4177 out:
4178 aio_context_release(aio_context);
4181 void hmp_drive_add_node(Monitor *mon, const char *optstr)
4183 QemuOpts *opts;
4184 QDict *qdict;
4185 Error *local_err = NULL;
4187 opts = qemu_opts_parse_noisily(&qemu_drive_opts, optstr, false);
4188 if (!opts) {
4189 return;
4192 qdict = qemu_opts_to_qdict(opts, NULL);
4194 if (!qdict_get_try_str(qdict, "node-name")) {
4195 qobject_unref(qdict);
4196 error_report("'node-name' needs to be specified");
4197 goto out;
4200 BlockDriverState *bs = bds_tree_init(qdict, &local_err);
4201 if (!bs) {
4202 error_report_err(local_err);
4203 goto out;
4206 QTAILQ_INSERT_TAIL(&monitor_bdrv_states, bs, monitor_list);
4208 out:
4209 qemu_opts_del(opts);
4212 void qmp_blockdev_add(BlockdevOptions *options, Error **errp)
4214 BlockDriverState *bs;
4215 QObject *obj;
4216 Visitor *v = qobject_output_visitor_new(&obj);
4217 QDict *qdict;
4218 Error *local_err = NULL;
4220 visit_type_BlockdevOptions(v, NULL, &options, &local_err);
4221 if (local_err) {
4222 error_propagate(errp, local_err);
4223 goto fail;
4226 visit_complete(v, &obj);
4227 qdict = qobject_to(QDict, obj);
4229 qdict_flatten(qdict);
4231 if (!qdict_get_try_str(qdict, "node-name")) {
4232 error_setg(errp, "'node-name' must be specified for the root node");
4233 goto fail;
4236 bs = bds_tree_init(qdict, errp);
4237 if (!bs) {
4238 goto fail;
4241 QTAILQ_INSERT_TAIL(&monitor_bdrv_states, bs, monitor_list);
4243 fail:
4244 visit_free(v);
4247 void qmp_blockdev_del(const char *node_name, Error **errp)
4249 AioContext *aio_context;
4250 BlockDriverState *bs;
4252 bs = bdrv_find_node(node_name);
4253 if (!bs) {
4254 error_setg(errp, "Cannot find node %s", node_name);
4255 return;
4257 if (bdrv_has_blk(bs)) {
4258 error_setg(errp, "Node %s is in use", node_name);
4259 return;
4261 aio_context = bdrv_get_aio_context(bs);
4262 aio_context_acquire(aio_context);
4264 if (bdrv_op_is_blocked(bs, BLOCK_OP_TYPE_DRIVE_DEL, errp)) {
4265 goto out;
4268 if (!bs->monitor_list.tqe_prev) {
4269 error_setg(errp, "Node %s is not owned by the monitor",
4270 bs->node_name);
4271 goto out;
4274 if (bs->refcnt > 1) {
4275 error_setg(errp, "Block device %s is in use",
4276 bdrv_get_device_or_node_name(bs));
4277 goto out;
4280 QTAILQ_REMOVE(&monitor_bdrv_states, bs, monitor_list);
4281 bdrv_unref(bs);
4283 out:
4284 aio_context_release(aio_context);
4287 static BdrvChild *bdrv_find_child(BlockDriverState *parent_bs,
4288 const char *child_name)
4290 BdrvChild *child;
4292 QLIST_FOREACH(child, &parent_bs->children, next) {
4293 if (strcmp(child->name, child_name) == 0) {
4294 return child;
4298 return NULL;
4301 void qmp_x_blockdev_change(const char *parent, bool has_child,
4302 const char *child, bool has_node,
4303 const char *node, Error **errp)
4305 BlockDriverState *parent_bs, *new_bs = NULL;
4306 BdrvChild *p_child;
4308 parent_bs = bdrv_lookup_bs(parent, parent, errp);
4309 if (!parent_bs) {
4310 return;
4313 if (has_child == has_node) {
4314 if (has_child) {
4315 error_setg(errp, "The parameters child and node are in conflict");
4316 } else {
4317 error_setg(errp, "Either child or node must be specified");
4319 return;
4322 if (has_child) {
4323 p_child = bdrv_find_child(parent_bs, child);
4324 if (!p_child) {
4325 error_setg(errp, "Node '%s' does not have child '%s'",
4326 parent, child);
4327 return;
4329 bdrv_del_child(parent_bs, p_child, errp);
4332 if (has_node) {
4333 new_bs = bdrv_find_node(node);
4334 if (!new_bs) {
4335 error_setg(errp, "Node '%s' not found", node);
4336 return;
4338 bdrv_add_child(parent_bs, new_bs, errp);
4342 BlockJobInfoList *qmp_query_block_jobs(Error **errp)
4344 BlockJobInfoList *head = NULL, **p_next = &head;
4345 BlockJob *job;
4347 for (job = block_job_next(NULL); job; job = block_job_next(job)) {
4348 BlockJobInfoList *elem;
4349 AioContext *aio_context;
4351 if (block_job_is_internal(job)) {
4352 continue;
4354 elem = g_new0(BlockJobInfoList, 1);
4355 aio_context = blk_get_aio_context(job->blk);
4356 aio_context_acquire(aio_context);
4357 elem->value = block_job_query(job, errp);
4358 aio_context_release(aio_context);
4359 if (!elem->value) {
4360 g_free(elem);
4361 qapi_free_BlockJobInfoList(head);
4362 return NULL;
4364 *p_next = elem;
4365 p_next = &elem->next;
4368 return head;
4371 void qmp_x_blockdev_set_iothread(const char *node_name, StrOrNull *iothread,
4372 bool has_force, bool force, Error **errp)
4374 AioContext *old_context;
4375 AioContext *new_context;
4376 BlockDriverState *bs;
4378 bs = bdrv_find_node(node_name);
4379 if (!bs) {
4380 error_setg(errp, "Cannot find node %s", node_name);
4381 return;
4384 /* Protects against accidents. */
4385 if (!(has_force && force) && bdrv_has_blk(bs)) {
4386 error_setg(errp, "Node %s is associated with a BlockBackend and could "
4387 "be in use (use force=true to override this check)",
4388 node_name);
4389 return;
4392 if (iothread->type == QTYPE_QSTRING) {
4393 IOThread *obj = iothread_by_id(iothread->u.s);
4394 if (!obj) {
4395 error_setg(errp, "Cannot find iothread %s", iothread->u.s);
4396 return;
4399 new_context = iothread_get_aio_context(obj);
4400 } else {
4401 new_context = qemu_get_aio_context();
4404 old_context = bdrv_get_aio_context(bs);
4405 aio_context_acquire(old_context);
4407 bdrv_set_aio_context(bs, new_context);
4409 aio_context_release(old_context);
4412 void qmp_x_block_latency_histogram_set(
4413 const char *device,
4414 bool has_boundaries, uint64List *boundaries,
4415 bool has_boundaries_read, uint64List *boundaries_read,
4416 bool has_boundaries_write, uint64List *boundaries_write,
4417 bool has_boundaries_flush, uint64List *boundaries_flush,
4418 Error **errp)
4420 BlockBackend *blk = blk_by_name(device);
4421 BlockAcctStats *stats;
4423 if (!blk) {
4424 error_setg(errp, "Device '%s' not found", device);
4425 return;
4427 stats = blk_get_stats(blk);
4429 if (!has_boundaries && !has_boundaries_read && !has_boundaries_write &&
4430 !has_boundaries_flush)
4432 block_latency_histograms_clear(stats);
4433 return;
4436 if (has_boundaries || has_boundaries_read) {
4437 block_latency_histogram_set(
4438 stats, BLOCK_ACCT_READ,
4439 has_boundaries_read ? boundaries_read : boundaries);
4442 if (has_boundaries || has_boundaries_write) {
4443 block_latency_histogram_set(
4444 stats, BLOCK_ACCT_WRITE,
4445 has_boundaries_write ? boundaries_write : boundaries);
4448 if (has_boundaries || has_boundaries_flush) {
4449 block_latency_histogram_set(
4450 stats, BLOCK_ACCT_FLUSH,
4451 has_boundaries_flush ? boundaries_flush : boundaries);
4455 QemuOptsList qemu_common_drive_opts = {
4456 .name = "drive",
4457 .head = QTAILQ_HEAD_INITIALIZER(qemu_common_drive_opts.head),
4458 .desc = {
4460 .name = "snapshot",
4461 .type = QEMU_OPT_BOOL,
4462 .help = "enable/disable snapshot mode",
4464 .name = "aio",
4465 .type = QEMU_OPT_STRING,
4466 .help = "host AIO implementation (threads, native)",
4468 .name = BDRV_OPT_CACHE_WB,
4469 .type = QEMU_OPT_BOOL,
4470 .help = "Enable writeback mode",
4472 .name = "format",
4473 .type = QEMU_OPT_STRING,
4474 .help = "disk format (raw, qcow2, ...)",
4476 .name = "rerror",
4477 .type = QEMU_OPT_STRING,
4478 .help = "read error action",
4480 .name = "werror",
4481 .type = QEMU_OPT_STRING,
4482 .help = "write error action",
4484 .name = BDRV_OPT_READ_ONLY,
4485 .type = QEMU_OPT_BOOL,
4486 .help = "open drive file as read-only",
4489 THROTTLE_OPTS,
4492 .name = "throttling.group",
4493 .type = QEMU_OPT_STRING,
4494 .help = "name of the block throttling group",
4496 .name = "copy-on-read",
4497 .type = QEMU_OPT_BOOL,
4498 .help = "copy read data from backing file into image file",
4500 .name = "detect-zeroes",
4501 .type = QEMU_OPT_STRING,
4502 .help = "try to optimize zero writes (off, on, unmap)",
4504 .name = "stats-account-invalid",
4505 .type = QEMU_OPT_BOOL,
4506 .help = "whether to account for invalid I/O operations "
4507 "in the statistics",
4509 .name = "stats-account-failed",
4510 .type = QEMU_OPT_BOOL,
4511 .help = "whether to account for failed I/O operations "
4512 "in the statistics",
4514 { /* end of list */ }
4518 QemuOptsList qemu_drive_opts = {
4519 .name = "drive",
4520 .head = QTAILQ_HEAD_INITIALIZER(qemu_drive_opts.head),
4521 .desc = {
4523 * no elements => accept any params
4524 * validation will happen later
4526 { /* end of list */ }