maint: Reorder include directives for qemu-{nbd, io}
[qemu/kevin.git] / blockdev.c
blob02cd69bc21ad9859c6bfe72d14ee5a3c8fe1a19d
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/throttle-groups.h"
39 #include "monitor/monitor.h"
40 #include "qemu/error-report.h"
41 #include "qemu/option.h"
42 #include "qemu/config-file.h"
43 #include "qapi/qmp/types.h"
44 #include "qapi-visit.h"
45 #include "qapi/qmp/qerror.h"
46 #include "qapi/qobject-output-visitor.h"
47 #include "qapi/util.h"
48 #include "sysemu/sysemu.h"
49 #include "block/block_int.h"
50 #include "qmp-commands.h"
51 #include "block/trace.h"
52 #include "sysemu/arch_init.h"
53 #include "sysemu/qtest.h"
54 #include "qemu/cutils.h"
55 #include "qemu/help_option.h"
56 #include "qemu/throttle-options.h"
58 static QTAILQ_HEAD(, BlockDriverState) monitor_bdrv_states =
59 QTAILQ_HEAD_INITIALIZER(monitor_bdrv_states);
61 static int do_open_tray(const char *blk_name, const char *qdev_id,
62 bool force, Error **errp);
64 static const char *const if_name[IF_COUNT] = {
65 [IF_NONE] = "none",
66 [IF_IDE] = "ide",
67 [IF_SCSI] = "scsi",
68 [IF_FLOPPY] = "floppy",
69 [IF_PFLASH] = "pflash",
70 [IF_MTD] = "mtd",
71 [IF_SD] = "sd",
72 [IF_VIRTIO] = "virtio",
73 [IF_XEN] = "xen",
76 static int if_max_devs[IF_COUNT] = {
78 * Do not change these numbers! They govern how drive option
79 * index maps to unit and bus. That mapping is ABI.
81 * All controllers used to implement if=T drives need to support
82 * if_max_devs[T] units, for any T with if_max_devs[T] != 0.
83 * Otherwise, some index values map to "impossible" bus, unit
84 * values.
86 * For instance, if you change [IF_SCSI] to 255, -drive
87 * if=scsi,index=12 no longer means bus=1,unit=5, but
88 * bus=0,unit=12. With an lsi53c895a controller (7 units max),
89 * the drive can't be set up. Regression.
91 [IF_IDE] = 2,
92 [IF_SCSI] = 7,
95 /**
96 * Boards may call this to offer board-by-board overrides
97 * of the default, global values.
99 void override_max_devs(BlockInterfaceType type, int max_devs)
101 BlockBackend *blk;
102 DriveInfo *dinfo;
104 if (max_devs <= 0) {
105 return;
108 for (blk = blk_next(NULL); blk; blk = blk_next(blk)) {
109 dinfo = blk_legacy_dinfo(blk);
110 if (dinfo->type == type) {
111 fprintf(stderr, "Cannot override units-per-bus property of"
112 " the %s interface, because a drive of that type has"
113 " already been added.\n", if_name[type]);
114 g_assert_not_reached();
118 if_max_devs[type] = max_devs;
122 * We automatically delete the drive when a device using it gets
123 * unplugged. Questionable feature, but we can't just drop it.
124 * Device models call blockdev_mark_auto_del() to schedule the
125 * automatic deletion, and generic qdev code calls blockdev_auto_del()
126 * when deletion is actually safe.
128 void blockdev_mark_auto_del(BlockBackend *blk)
130 DriveInfo *dinfo = blk_legacy_dinfo(blk);
131 BlockDriverState *bs = blk_bs(blk);
132 AioContext *aio_context;
134 if (!dinfo) {
135 return;
138 if (bs) {
139 aio_context = bdrv_get_aio_context(bs);
140 aio_context_acquire(aio_context);
142 if (bs->job) {
143 block_job_cancel(bs->job);
146 aio_context_release(aio_context);
149 dinfo->auto_del = 1;
152 void blockdev_auto_del(BlockBackend *blk)
154 DriveInfo *dinfo = blk_legacy_dinfo(blk);
156 if (dinfo && dinfo->auto_del) {
157 monitor_remove_blk(blk);
158 blk_unref(blk);
163 * Returns the current mapping of how many units per bus
164 * a particular interface can support.
166 * A positive integer indicates n units per bus.
167 * 0 implies the mapping has not been established.
168 * -1 indicates an invalid BlockInterfaceType was given.
170 int drive_get_max_devs(BlockInterfaceType type)
172 if (type >= IF_IDE && type < IF_COUNT) {
173 return if_max_devs[type];
176 return -1;
179 static int drive_index_to_bus_id(BlockInterfaceType type, int index)
181 int max_devs = if_max_devs[type];
182 return max_devs ? index / max_devs : 0;
185 static int drive_index_to_unit_id(BlockInterfaceType type, int index)
187 int max_devs = if_max_devs[type];
188 return max_devs ? index % max_devs : index;
191 QemuOpts *drive_def(const char *optstr)
193 return qemu_opts_parse_noisily(qemu_find_opts("drive"), optstr, false);
196 QemuOpts *drive_add(BlockInterfaceType type, int index, const char *file,
197 const char *optstr)
199 QemuOpts *opts;
201 opts = drive_def(optstr);
202 if (!opts) {
203 return NULL;
205 if (type != IF_DEFAULT) {
206 qemu_opt_set(opts, "if", if_name[type], &error_abort);
208 if (index >= 0) {
209 qemu_opt_set_number(opts, "index", index, &error_abort);
211 if (file)
212 qemu_opt_set(opts, "file", file, &error_abort);
213 return opts;
216 DriveInfo *drive_get(BlockInterfaceType type, int bus, int unit)
218 BlockBackend *blk;
219 DriveInfo *dinfo;
221 for (blk = blk_next(NULL); blk; blk = blk_next(blk)) {
222 dinfo = blk_legacy_dinfo(blk);
223 if (dinfo && dinfo->type == type
224 && dinfo->bus == bus && dinfo->unit == unit) {
225 return dinfo;
229 return NULL;
232 void drive_check_orphaned(void)
234 BlockBackend *blk;
235 DriveInfo *dinfo;
236 Location loc;
237 bool orphans = false;
239 for (blk = blk_next(NULL); blk; blk = blk_next(blk)) {
240 dinfo = blk_legacy_dinfo(blk);
241 if (!blk_get_attached_dev(blk) && !dinfo->is_default &&
242 dinfo->type != IF_NONE) {
243 loc_push_none(&loc);
244 qemu_opts_loc_restore(dinfo->opts);
245 error_report("machine type does not support"
246 " if=%s,bus=%d,unit=%d",
247 if_name[dinfo->type], dinfo->bus, dinfo->unit);
248 loc_pop(&loc);
249 orphans = true;
253 if (orphans) {
254 exit(1);
258 DriveInfo *drive_get_by_index(BlockInterfaceType type, int index)
260 return drive_get(type,
261 drive_index_to_bus_id(type, index),
262 drive_index_to_unit_id(type, index));
265 int drive_get_max_bus(BlockInterfaceType type)
267 int max_bus;
268 BlockBackend *blk;
269 DriveInfo *dinfo;
271 max_bus = -1;
272 for (blk = blk_next(NULL); blk; blk = blk_next(blk)) {
273 dinfo = blk_legacy_dinfo(blk);
274 if (dinfo && dinfo->type == type && dinfo->bus > max_bus) {
275 max_bus = dinfo->bus;
278 return max_bus;
281 /* Get a block device. This should only be used for single-drive devices
282 (e.g. SD/Floppy/MTD). Multi-disk devices (scsi/ide) should use the
283 appropriate bus. */
284 DriveInfo *drive_get_next(BlockInterfaceType type)
286 static int next_block_unit[IF_COUNT];
288 return drive_get(type, 0, next_block_unit[type]++);
291 static void bdrv_format_print(void *opaque, const char *name)
293 error_printf(" %s", name);
296 typedef struct {
297 QEMUBH *bh;
298 BlockDriverState *bs;
299 } BDRVPutRefBH;
301 static int parse_block_error_action(const char *buf, bool is_read, Error **errp)
303 if (!strcmp(buf, "ignore")) {
304 return BLOCKDEV_ON_ERROR_IGNORE;
305 } else if (!is_read && !strcmp(buf, "enospc")) {
306 return BLOCKDEV_ON_ERROR_ENOSPC;
307 } else if (!strcmp(buf, "stop")) {
308 return BLOCKDEV_ON_ERROR_STOP;
309 } else if (!strcmp(buf, "report")) {
310 return BLOCKDEV_ON_ERROR_REPORT;
311 } else {
312 error_setg(errp, "'%s' invalid %s error action",
313 buf, is_read ? "read" : "write");
314 return -1;
318 static bool parse_stats_intervals(BlockAcctStats *stats, QList *intervals,
319 Error **errp)
321 const QListEntry *entry;
322 for (entry = qlist_first(intervals); entry; entry = qlist_next(entry)) {
323 switch (qobject_type(entry->value)) {
325 case QTYPE_QSTRING: {
326 unsigned long long length;
327 const char *str = qstring_get_str(qobject_to_qstring(entry->value));
328 if (parse_uint_full(str, &length, 10) == 0 &&
329 length > 0 && length <= UINT_MAX) {
330 block_acct_add_interval(stats, (unsigned) length);
331 } else {
332 error_setg(errp, "Invalid interval length: %s", str);
333 return false;
335 break;
338 case QTYPE_QNUM: {
339 int64_t length = qnum_get_int(qobject_to_qnum(entry->value));
341 if (length > 0 && length <= UINT_MAX) {
342 block_acct_add_interval(stats, (unsigned) length);
343 } else {
344 error_setg(errp, "Invalid interval length: %" PRId64, length);
345 return false;
347 break;
350 default:
351 error_setg(errp, "The specification of stats-intervals is invalid");
352 return false;
355 return true;
358 typedef enum { MEDIA_DISK, MEDIA_CDROM } DriveMediaType;
360 /* All parameters but @opts are optional and may be set to NULL. */
361 static void extract_common_blockdev_options(QemuOpts *opts, int *bdrv_flags,
362 const char **throttling_group, ThrottleConfig *throttle_cfg,
363 BlockdevDetectZeroesOptions *detect_zeroes, Error **errp)
365 Error *local_error = NULL;
366 const char *aio;
368 if (bdrv_flags) {
369 if (qemu_opt_get_bool(opts, "copy-on-read", false)) {
370 *bdrv_flags |= BDRV_O_COPY_ON_READ;
373 if ((aio = qemu_opt_get(opts, "aio")) != NULL) {
374 if (!strcmp(aio, "native")) {
375 *bdrv_flags |= BDRV_O_NATIVE_AIO;
376 } else if (!strcmp(aio, "threads")) {
377 /* this is the default */
378 } else {
379 error_setg(errp, "invalid aio option");
380 return;
385 /* disk I/O throttling */
386 if (throttling_group) {
387 *throttling_group = qemu_opt_get(opts, "throttling.group");
390 if (throttle_cfg) {
391 throttle_config_init(throttle_cfg);
392 throttle_cfg->buckets[THROTTLE_BPS_TOTAL].avg =
393 qemu_opt_get_number(opts, "throttling.bps-total", 0);
394 throttle_cfg->buckets[THROTTLE_BPS_READ].avg =
395 qemu_opt_get_number(opts, "throttling.bps-read", 0);
396 throttle_cfg->buckets[THROTTLE_BPS_WRITE].avg =
397 qemu_opt_get_number(opts, "throttling.bps-write", 0);
398 throttle_cfg->buckets[THROTTLE_OPS_TOTAL].avg =
399 qemu_opt_get_number(opts, "throttling.iops-total", 0);
400 throttle_cfg->buckets[THROTTLE_OPS_READ].avg =
401 qemu_opt_get_number(opts, "throttling.iops-read", 0);
402 throttle_cfg->buckets[THROTTLE_OPS_WRITE].avg =
403 qemu_opt_get_number(opts, "throttling.iops-write", 0);
405 throttle_cfg->buckets[THROTTLE_BPS_TOTAL].max =
406 qemu_opt_get_number(opts, "throttling.bps-total-max", 0);
407 throttle_cfg->buckets[THROTTLE_BPS_READ].max =
408 qemu_opt_get_number(opts, "throttling.bps-read-max", 0);
409 throttle_cfg->buckets[THROTTLE_BPS_WRITE].max =
410 qemu_opt_get_number(opts, "throttling.bps-write-max", 0);
411 throttle_cfg->buckets[THROTTLE_OPS_TOTAL].max =
412 qemu_opt_get_number(opts, "throttling.iops-total-max", 0);
413 throttle_cfg->buckets[THROTTLE_OPS_READ].max =
414 qemu_opt_get_number(opts, "throttling.iops-read-max", 0);
415 throttle_cfg->buckets[THROTTLE_OPS_WRITE].max =
416 qemu_opt_get_number(opts, "throttling.iops-write-max", 0);
418 throttle_cfg->buckets[THROTTLE_BPS_TOTAL].burst_length =
419 qemu_opt_get_number(opts, "throttling.bps-total-max-length", 1);
420 throttle_cfg->buckets[THROTTLE_BPS_READ].burst_length =
421 qemu_opt_get_number(opts, "throttling.bps-read-max-length", 1);
422 throttle_cfg->buckets[THROTTLE_BPS_WRITE].burst_length =
423 qemu_opt_get_number(opts, "throttling.bps-write-max-length", 1);
424 throttle_cfg->buckets[THROTTLE_OPS_TOTAL].burst_length =
425 qemu_opt_get_number(opts, "throttling.iops-total-max-length", 1);
426 throttle_cfg->buckets[THROTTLE_OPS_READ].burst_length =
427 qemu_opt_get_number(opts, "throttling.iops-read-max-length", 1);
428 throttle_cfg->buckets[THROTTLE_OPS_WRITE].burst_length =
429 qemu_opt_get_number(opts, "throttling.iops-write-max-length", 1);
431 throttle_cfg->op_size =
432 qemu_opt_get_number(opts, "throttling.iops-size", 0);
434 if (!throttle_is_valid(throttle_cfg, errp)) {
435 return;
439 if (detect_zeroes) {
440 *detect_zeroes =
441 qapi_enum_parse(BlockdevDetectZeroesOptions_lookup,
442 qemu_opt_get(opts, "detect-zeroes"),
443 BLOCKDEV_DETECT_ZEROES_OPTIONS__MAX,
444 BLOCKDEV_DETECT_ZEROES_OPTIONS_OFF,
445 &local_error);
446 if (local_error) {
447 error_propagate(errp, local_error);
448 return;
453 /* Takes the ownership of bs_opts */
454 static BlockBackend *blockdev_init(const char *file, QDict *bs_opts,
455 Error **errp)
457 const char *buf;
458 int bdrv_flags = 0;
459 int on_read_error, on_write_error;
460 bool account_invalid, account_failed;
461 bool writethrough, read_only;
462 BlockBackend *blk;
463 BlockDriverState *bs;
464 ThrottleConfig cfg;
465 int snapshot = 0;
466 Error *error = NULL;
467 QemuOpts *opts;
468 QDict *interval_dict = NULL;
469 QList *interval_list = NULL;
470 const char *id;
471 BlockdevDetectZeroesOptions detect_zeroes =
472 BLOCKDEV_DETECT_ZEROES_OPTIONS_OFF;
473 const char *throttling_group = NULL;
475 /* Check common options by copying from bs_opts to opts, all other options
476 * stay in bs_opts for processing by bdrv_open(). */
477 id = qdict_get_try_str(bs_opts, "id");
478 opts = qemu_opts_create(&qemu_common_drive_opts, id, 1, &error);
479 if (error) {
480 error_propagate(errp, error);
481 goto err_no_opts;
484 qemu_opts_absorb_qdict(opts, bs_opts, &error);
485 if (error) {
486 error_propagate(errp, error);
487 goto early_err;
490 if (id) {
491 qdict_del(bs_opts, "id");
494 /* extract parameters */
495 snapshot = qemu_opt_get_bool(opts, "snapshot", 0);
497 account_invalid = qemu_opt_get_bool(opts, "stats-account-invalid", true);
498 account_failed = qemu_opt_get_bool(opts, "stats-account-failed", true);
500 writethrough = !qemu_opt_get_bool(opts, BDRV_OPT_CACHE_WB, true);
502 id = qemu_opts_id(opts);
504 qdict_extract_subqdict(bs_opts, &interval_dict, "stats-intervals.");
505 qdict_array_split(interval_dict, &interval_list);
507 if (qdict_size(interval_dict) != 0) {
508 error_setg(errp, "Invalid option stats-intervals.%s",
509 qdict_first(interval_dict)->key);
510 goto early_err;
513 extract_common_blockdev_options(opts, &bdrv_flags, &throttling_group, &cfg,
514 &detect_zeroes, &error);
515 if (error) {
516 error_propagate(errp, error);
517 goto early_err;
520 if ((buf = qemu_opt_get(opts, "format")) != NULL) {
521 if (is_help_option(buf)) {
522 error_printf("Supported formats:");
523 bdrv_iterate_format(bdrv_format_print, NULL);
524 error_printf("\n");
525 goto early_err;
528 if (qdict_haskey(bs_opts, "driver")) {
529 error_setg(errp, "Cannot specify both 'driver' and 'format'");
530 goto early_err;
532 qdict_put_str(bs_opts, "driver", buf);
535 on_write_error = BLOCKDEV_ON_ERROR_ENOSPC;
536 if ((buf = qemu_opt_get(opts, "werror")) != NULL) {
537 on_write_error = parse_block_error_action(buf, 0, &error);
538 if (error) {
539 error_propagate(errp, error);
540 goto early_err;
544 on_read_error = BLOCKDEV_ON_ERROR_REPORT;
545 if ((buf = qemu_opt_get(opts, "rerror")) != NULL) {
546 on_read_error = parse_block_error_action(buf, 1, &error);
547 if (error) {
548 error_propagate(errp, error);
549 goto early_err;
553 if (snapshot) {
554 bdrv_flags |= BDRV_O_SNAPSHOT;
557 read_only = qemu_opt_get_bool(opts, BDRV_OPT_READ_ONLY, false);
559 /* init */
560 if ((!file || !*file) && !qdict_size(bs_opts)) {
561 BlockBackendRootState *blk_rs;
563 blk = blk_new(0, BLK_PERM_ALL);
564 blk_rs = blk_get_root_state(blk);
565 blk_rs->open_flags = bdrv_flags;
566 blk_rs->read_only = read_only;
567 blk_rs->detect_zeroes = detect_zeroes;
569 QDECREF(bs_opts);
570 } else {
571 if (file && !*file) {
572 file = NULL;
575 /* bdrv_open() defaults to the values in bdrv_flags (for compatibility
576 * with other callers) rather than what we want as the real defaults.
577 * Apply the defaults here instead. */
578 qdict_set_default_str(bs_opts, BDRV_OPT_CACHE_DIRECT, "off");
579 qdict_set_default_str(bs_opts, BDRV_OPT_CACHE_NO_FLUSH, "off");
580 qdict_set_default_str(bs_opts, BDRV_OPT_READ_ONLY,
581 read_only ? "on" : "off");
582 assert((bdrv_flags & BDRV_O_CACHE_MASK) == 0);
584 if (runstate_check(RUN_STATE_INMIGRATE)) {
585 bdrv_flags |= BDRV_O_INACTIVE;
588 blk = blk_new_open(file, NULL, bs_opts, bdrv_flags, errp);
589 if (!blk) {
590 goto err_no_bs_opts;
592 bs = blk_bs(blk);
594 bs->detect_zeroes = detect_zeroes;
596 block_acct_setup(blk_get_stats(blk), account_invalid, account_failed);
598 if (!parse_stats_intervals(blk_get_stats(blk), interval_list, errp)) {
599 blk_unref(blk);
600 blk = NULL;
601 goto err_no_bs_opts;
605 /* disk I/O throttling */
606 if (throttle_enabled(&cfg)) {
607 if (!throttling_group) {
608 throttling_group = id;
610 blk_io_limits_enable(blk, throttling_group);
611 blk_set_io_limits(blk, &cfg);
614 blk_set_enable_write_cache(blk, !writethrough);
615 blk_set_on_error(blk, on_read_error, on_write_error);
617 if (!monitor_add_blk(blk, id, errp)) {
618 blk_unref(blk);
619 blk = NULL;
620 goto err_no_bs_opts;
623 err_no_bs_opts:
624 qemu_opts_del(opts);
625 QDECREF(interval_dict);
626 QDECREF(interval_list);
627 return blk;
629 early_err:
630 qemu_opts_del(opts);
631 QDECREF(interval_dict);
632 QDECREF(interval_list);
633 err_no_opts:
634 QDECREF(bs_opts);
635 return NULL;
638 /* Takes the ownership of bs_opts */
639 static BlockDriverState *bds_tree_init(QDict *bs_opts, Error **errp)
641 int bdrv_flags = 0;
643 /* bdrv_open() defaults to the values in bdrv_flags (for compatibility
644 * with other callers) rather than what we want as the real defaults.
645 * Apply the defaults here instead. */
646 qdict_set_default_str(bs_opts, BDRV_OPT_CACHE_DIRECT, "off");
647 qdict_set_default_str(bs_opts, BDRV_OPT_CACHE_NO_FLUSH, "off");
648 qdict_set_default_str(bs_opts, BDRV_OPT_READ_ONLY, "off");
650 if (runstate_check(RUN_STATE_INMIGRATE)) {
651 bdrv_flags |= BDRV_O_INACTIVE;
654 return bdrv_open(NULL, NULL, bs_opts, bdrv_flags, errp);
657 void blockdev_close_all_bdrv_states(void)
659 BlockDriverState *bs, *next_bs;
661 QTAILQ_FOREACH_SAFE(bs, &monitor_bdrv_states, monitor_list, next_bs) {
662 AioContext *ctx = bdrv_get_aio_context(bs);
664 aio_context_acquire(ctx);
665 bdrv_unref(bs);
666 aio_context_release(ctx);
670 /* Iterates over the list of monitor-owned BlockDriverStates */
671 BlockDriverState *bdrv_next_monitor_owned(BlockDriverState *bs)
673 return bs ? QTAILQ_NEXT(bs, monitor_list)
674 : QTAILQ_FIRST(&monitor_bdrv_states);
677 static void qemu_opt_rename(QemuOpts *opts, const char *from, const char *to,
678 Error **errp)
680 const char *value;
682 value = qemu_opt_get(opts, from);
683 if (value) {
684 if (qemu_opt_find(opts, to)) {
685 error_setg(errp, "'%s' and its alias '%s' can't be used at the "
686 "same time", to, from);
687 return;
691 /* rename all items in opts */
692 while ((value = qemu_opt_get(opts, from))) {
693 qemu_opt_set(opts, to, value, &error_abort);
694 qemu_opt_unset(opts, from);
698 QemuOptsList qemu_legacy_drive_opts = {
699 .name = "drive",
700 .head = QTAILQ_HEAD_INITIALIZER(qemu_legacy_drive_opts.head),
701 .desc = {
703 .name = "bus",
704 .type = QEMU_OPT_NUMBER,
705 .help = "bus number",
707 .name = "unit",
708 .type = QEMU_OPT_NUMBER,
709 .help = "unit number (i.e. lun for scsi)",
711 .name = "index",
712 .type = QEMU_OPT_NUMBER,
713 .help = "index number",
715 .name = "media",
716 .type = QEMU_OPT_STRING,
717 .help = "media type (disk, cdrom)",
719 .name = "if",
720 .type = QEMU_OPT_STRING,
721 .help = "interface (ide, scsi, sd, mtd, floppy, pflash, virtio)",
723 .name = "cyls",
724 .type = QEMU_OPT_NUMBER,
725 .help = "number of cylinders (ide disk geometry)",
727 .name = "heads",
728 .type = QEMU_OPT_NUMBER,
729 .help = "number of heads (ide disk geometry)",
731 .name = "secs",
732 .type = QEMU_OPT_NUMBER,
733 .help = "number of sectors (ide disk geometry)",
735 .name = "trans",
736 .type = QEMU_OPT_STRING,
737 .help = "chs translation (auto, lba, none)",
739 .name = "boot",
740 .type = QEMU_OPT_BOOL,
741 .help = "(deprecated, ignored)",
743 .name = "addr",
744 .type = QEMU_OPT_STRING,
745 .help = "pci address (virtio only)",
747 .name = "serial",
748 .type = QEMU_OPT_STRING,
749 .help = "disk serial number",
751 .name = "file",
752 .type = QEMU_OPT_STRING,
753 .help = "file name",
756 /* Options that are passed on, but have special semantics with -drive */
758 .name = BDRV_OPT_READ_ONLY,
759 .type = QEMU_OPT_BOOL,
760 .help = "open drive file as read-only",
762 .name = "rerror",
763 .type = QEMU_OPT_STRING,
764 .help = "read error action",
766 .name = "werror",
767 .type = QEMU_OPT_STRING,
768 .help = "write error action",
770 .name = "copy-on-read",
771 .type = QEMU_OPT_BOOL,
772 .help = "copy read data from backing file into image file",
775 { /* end of list */ }
779 DriveInfo *drive_new(QemuOpts *all_opts, BlockInterfaceType block_default_type)
781 const char *value;
782 BlockBackend *blk;
783 DriveInfo *dinfo = NULL;
784 QDict *bs_opts;
785 QemuOpts *legacy_opts;
786 DriveMediaType media = MEDIA_DISK;
787 BlockInterfaceType type;
788 int cyls, heads, secs, translation;
789 int max_devs, bus_id, unit_id, index;
790 const char *devaddr;
791 const char *werror, *rerror;
792 bool read_only = false;
793 bool copy_on_read;
794 const char *serial;
795 const char *filename;
796 Error *local_err = NULL;
797 int i;
798 const char *deprecated[] = {
799 "serial", "trans", "secs", "heads", "cyls", "addr"
802 /* Change legacy command line options into QMP ones */
803 static const struct {
804 const char *from;
805 const char *to;
806 } opt_renames[] = {
807 { "iops", "throttling.iops-total" },
808 { "iops_rd", "throttling.iops-read" },
809 { "iops_wr", "throttling.iops-write" },
811 { "bps", "throttling.bps-total" },
812 { "bps_rd", "throttling.bps-read" },
813 { "bps_wr", "throttling.bps-write" },
815 { "iops_max", "throttling.iops-total-max" },
816 { "iops_rd_max", "throttling.iops-read-max" },
817 { "iops_wr_max", "throttling.iops-write-max" },
819 { "bps_max", "throttling.bps-total-max" },
820 { "bps_rd_max", "throttling.bps-read-max" },
821 { "bps_wr_max", "throttling.bps-write-max" },
823 { "iops_size", "throttling.iops-size" },
825 { "group", "throttling.group" },
827 { "readonly", BDRV_OPT_READ_ONLY },
830 for (i = 0; i < ARRAY_SIZE(opt_renames); i++) {
831 qemu_opt_rename(all_opts, opt_renames[i].from, opt_renames[i].to,
832 &local_err);
833 if (local_err) {
834 error_report_err(local_err);
835 return NULL;
839 value = qemu_opt_get(all_opts, "cache");
840 if (value) {
841 int flags = 0;
842 bool writethrough;
844 if (bdrv_parse_cache_mode(value, &flags, &writethrough) != 0) {
845 error_report("invalid cache option");
846 return NULL;
849 /* Specific options take precedence */
850 if (!qemu_opt_get(all_opts, BDRV_OPT_CACHE_WB)) {
851 qemu_opt_set_bool(all_opts, BDRV_OPT_CACHE_WB,
852 !writethrough, &error_abort);
854 if (!qemu_opt_get(all_opts, BDRV_OPT_CACHE_DIRECT)) {
855 qemu_opt_set_bool(all_opts, BDRV_OPT_CACHE_DIRECT,
856 !!(flags & BDRV_O_NOCACHE), &error_abort);
858 if (!qemu_opt_get(all_opts, BDRV_OPT_CACHE_NO_FLUSH)) {
859 qemu_opt_set_bool(all_opts, BDRV_OPT_CACHE_NO_FLUSH,
860 !!(flags & BDRV_O_NO_FLUSH), &error_abort);
862 qemu_opt_unset(all_opts, "cache");
865 /* Get a QDict for processing the options */
866 bs_opts = qdict_new();
867 qemu_opts_to_qdict(all_opts, bs_opts);
869 legacy_opts = qemu_opts_create(&qemu_legacy_drive_opts, NULL, 0,
870 &error_abort);
871 qemu_opts_absorb_qdict(legacy_opts, bs_opts, &local_err);
872 if (local_err) {
873 error_report_err(local_err);
874 goto fail;
877 /* Deprecated option boot=[on|off] */
878 if (qemu_opt_get(legacy_opts, "boot") != NULL) {
879 fprintf(stderr, "qemu-kvm: boot=on|off is deprecated and will be "
880 "ignored. Future versions will reject this parameter. Please "
881 "update your scripts.\n");
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 QDECREF(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 BlockJobTxn *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 AioContext *aio_context;
1460 QEMUSnapshotInfo sn;
1461 bool created;
1462 } InternalSnapshotState;
1465 static int action_check_completion_mode(BlkActionState *s, Error **errp)
1467 if (s->txn_props->completion_mode != ACTION_COMPLETION_MODE_INDIVIDUAL) {
1468 error_setg(errp,
1469 "Action '%s' does not support Transaction property "
1470 "completion-mode = %s",
1471 TransactionActionKind_lookup[s->action->type],
1472 ActionCompletionMode_lookup[s->txn_props->completion_mode]);
1473 return -1;
1475 return 0;
1478 static void internal_snapshot_prepare(BlkActionState *common,
1479 Error **errp)
1481 Error *local_err = NULL;
1482 const char *device;
1483 const char *name;
1484 BlockDriverState *bs;
1485 QEMUSnapshotInfo old_sn, *sn;
1486 bool ret;
1487 qemu_timeval tv;
1488 BlockdevSnapshotInternal *internal;
1489 InternalSnapshotState *state;
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 /* AioContext is released in .clean() */
1512 state->aio_context = bdrv_get_aio_context(bs);
1513 aio_context_acquire(state->aio_context);
1515 state->bs = bs;
1516 bdrv_drained_begin(bs);
1518 if (bdrv_op_is_blocked(bs, BLOCK_OP_TYPE_INTERNAL_SNAPSHOT, errp)) {
1519 return;
1522 if (bdrv_is_read_only(bs)) {
1523 error_setg(errp, "Device '%s' is read only", device);
1524 return;
1527 if (!bdrv_can_snapshot(bs)) {
1528 error_setg(errp, "Block format '%s' used by device '%s' "
1529 "does not support internal snapshots",
1530 bs->drv->format_name, device);
1531 return;
1534 if (!strlen(name)) {
1535 error_setg(errp, "Name is empty");
1536 return;
1539 /* check whether a snapshot with name exist */
1540 ret = bdrv_snapshot_find_by_id_and_name(bs, NULL, name, &old_sn,
1541 &local_err);
1542 if (local_err) {
1543 error_propagate(errp, local_err);
1544 return;
1545 } else if (ret) {
1546 error_setg(errp,
1547 "Snapshot with name '%s' already exists on device '%s'",
1548 name, device);
1549 return;
1552 /* 3. take the snapshot */
1553 sn = &state->sn;
1554 pstrcpy(sn->name, sizeof(sn->name), name);
1555 qemu_gettimeofday(&tv);
1556 sn->date_sec = tv.tv_sec;
1557 sn->date_nsec = tv.tv_usec * 1000;
1558 sn->vm_clock_nsec = qemu_clock_get_ns(QEMU_CLOCK_VIRTUAL);
1560 ret1 = bdrv_snapshot_create(bs, sn);
1561 if (ret1 < 0) {
1562 error_setg_errno(errp, -ret1,
1563 "Failed to create snapshot '%s' on device '%s'",
1564 name, device);
1565 return;
1568 /* 4. succeed, mark a snapshot is created */
1569 state->created = true;
1572 static void internal_snapshot_abort(BlkActionState *common)
1574 InternalSnapshotState *state =
1575 DO_UPCAST(InternalSnapshotState, common, common);
1576 BlockDriverState *bs = state->bs;
1577 QEMUSnapshotInfo *sn = &state->sn;
1578 Error *local_error = NULL;
1580 if (!state->created) {
1581 return;
1584 if (bdrv_snapshot_delete(bs, sn->id_str, sn->name, &local_error) < 0) {
1585 error_reportf_err(local_error,
1586 "Failed to delete snapshot with id '%s' and "
1587 "name '%s' on device '%s' in abort: ",
1588 sn->id_str, sn->name,
1589 bdrv_get_device_name(bs));
1593 static void internal_snapshot_clean(BlkActionState *common)
1595 InternalSnapshotState *state = DO_UPCAST(InternalSnapshotState,
1596 common, common);
1598 if (state->aio_context) {
1599 if (state->bs) {
1600 bdrv_drained_end(state->bs);
1602 aio_context_release(state->aio_context);
1606 /* external snapshot private data */
1607 typedef struct ExternalSnapshotState {
1608 BlkActionState common;
1609 BlockDriverState *old_bs;
1610 BlockDriverState *new_bs;
1611 AioContext *aio_context;
1612 bool overlay_appended;
1613 } ExternalSnapshotState;
1615 static void external_snapshot_prepare(BlkActionState *common,
1616 Error **errp)
1618 int flags = 0;
1619 QDict *options = NULL;
1620 Error *local_err = NULL;
1621 /* Device and node name of the image to generate the snapshot from */
1622 const char *device;
1623 const char *node_name;
1624 /* Reference to the new image (for 'blockdev-snapshot') */
1625 const char *snapshot_ref;
1626 /* File name of the new image (for 'blockdev-snapshot-sync') */
1627 const char *new_image_file;
1628 ExternalSnapshotState *state =
1629 DO_UPCAST(ExternalSnapshotState, common, common);
1630 TransactionAction *action = common->action;
1632 /* 'blockdev-snapshot' and 'blockdev-snapshot-sync' have similar
1633 * purpose but a different set of parameters */
1634 switch (action->type) {
1635 case TRANSACTION_ACTION_KIND_BLOCKDEV_SNAPSHOT:
1637 BlockdevSnapshot *s = action->u.blockdev_snapshot.data;
1638 device = s->node;
1639 node_name = s->node;
1640 new_image_file = NULL;
1641 snapshot_ref = s->overlay;
1643 break;
1644 case TRANSACTION_ACTION_KIND_BLOCKDEV_SNAPSHOT_SYNC:
1646 BlockdevSnapshotSync *s = action->u.blockdev_snapshot_sync.data;
1647 device = s->has_device ? s->device : NULL;
1648 node_name = s->has_node_name ? s->node_name : NULL;
1649 new_image_file = s->snapshot_file;
1650 snapshot_ref = NULL;
1652 break;
1653 default:
1654 g_assert_not_reached();
1657 /* start processing */
1658 if (action_check_completion_mode(common, errp) < 0) {
1659 return;
1662 state->old_bs = bdrv_lookup_bs(device, node_name, errp);
1663 if (!state->old_bs) {
1664 return;
1667 /* Acquire AioContext now so any threads operating on old_bs stop */
1668 state->aio_context = bdrv_get_aio_context(state->old_bs);
1669 aio_context_acquire(state->aio_context);
1670 bdrv_drained_begin(state->old_bs);
1672 if (!bdrv_is_inserted(state->old_bs)) {
1673 error_setg(errp, QERR_DEVICE_HAS_NO_MEDIUM, device);
1674 return;
1677 if (bdrv_op_is_blocked(state->old_bs,
1678 BLOCK_OP_TYPE_EXTERNAL_SNAPSHOT, errp)) {
1679 return;
1682 if (!bdrv_is_read_only(state->old_bs)) {
1683 if (bdrv_flush(state->old_bs)) {
1684 error_setg(errp, QERR_IO_ERROR);
1685 return;
1689 if (!bdrv_is_first_non_filter(state->old_bs)) {
1690 error_setg(errp, QERR_FEATURE_DISABLED, "snapshot");
1691 return;
1694 if (action->type == TRANSACTION_ACTION_KIND_BLOCKDEV_SNAPSHOT_SYNC) {
1695 BlockdevSnapshotSync *s = action->u.blockdev_snapshot_sync.data;
1696 const char *format = s->has_format ? s->format : "qcow2";
1697 enum NewImageMode mode;
1698 const char *snapshot_node_name =
1699 s->has_snapshot_node_name ? s->snapshot_node_name : NULL;
1701 if (node_name && !snapshot_node_name) {
1702 error_setg(errp, "New snapshot node name missing");
1703 return;
1706 if (snapshot_node_name &&
1707 bdrv_lookup_bs(snapshot_node_name, snapshot_node_name, NULL)) {
1708 error_setg(errp, "New snapshot node name already in use");
1709 return;
1712 flags = state->old_bs->open_flags;
1713 flags &= ~(BDRV_O_SNAPSHOT | BDRV_O_COPY_ON_READ);
1714 flags |= BDRV_O_NO_BACKING;
1716 /* create new image w/backing file */
1717 mode = s->has_mode ? s->mode : NEW_IMAGE_MODE_ABSOLUTE_PATHS;
1718 if (mode != NEW_IMAGE_MODE_EXISTING) {
1719 int64_t size = bdrv_getlength(state->old_bs);
1720 if (size < 0) {
1721 error_setg_errno(errp, -size, "bdrv_getlength failed");
1722 return;
1724 bdrv_img_create(new_image_file, format,
1725 state->old_bs->filename,
1726 state->old_bs->drv->format_name,
1727 NULL, size, flags, false, &local_err);
1728 if (local_err) {
1729 error_propagate(errp, local_err);
1730 return;
1734 options = qdict_new();
1735 if (s->has_snapshot_node_name) {
1736 qdict_put_str(options, "node-name", snapshot_node_name);
1738 qdict_put_str(options, "driver", format);
1741 state->new_bs = bdrv_open(new_image_file, snapshot_ref, options, flags,
1742 errp);
1743 /* We will manually add the backing_hd field to the bs later */
1744 if (!state->new_bs) {
1745 return;
1748 if (bdrv_has_blk(state->new_bs)) {
1749 error_setg(errp, "The snapshot is already in use");
1750 return;
1753 if (bdrv_op_is_blocked(state->new_bs, BLOCK_OP_TYPE_EXTERNAL_SNAPSHOT,
1754 errp)) {
1755 return;
1758 if (state->new_bs->backing != NULL) {
1759 error_setg(errp, "The snapshot already has a backing image");
1760 return;
1763 if (!state->new_bs->drv->supports_backing) {
1764 error_setg(errp, "The snapshot does not support backing images");
1765 return;
1768 bdrv_set_aio_context(state->new_bs, state->aio_context);
1770 /* This removes our old bs and adds the new bs. This is an operation that
1771 * can fail, so we need to do it in .prepare; undoing it for abort is
1772 * always possible. */
1773 bdrv_ref(state->new_bs);
1774 bdrv_append(state->new_bs, state->old_bs, &local_err);
1775 if (local_err) {
1776 error_propagate(errp, local_err);
1777 return;
1779 state->overlay_appended = true;
1782 static void external_snapshot_commit(BlkActionState *common)
1784 ExternalSnapshotState *state =
1785 DO_UPCAST(ExternalSnapshotState, common, common);
1787 /* We don't need (or want) to use the transactional
1788 * bdrv_reopen_multiple() across all the entries at once, because we
1789 * don't want to abort all of them if one of them fails the reopen */
1790 if (!atomic_read(&state->old_bs->copy_on_read)) {
1791 bdrv_reopen(state->old_bs, state->old_bs->open_flags & ~BDRV_O_RDWR,
1792 NULL);
1796 static void external_snapshot_abort(BlkActionState *common)
1798 ExternalSnapshotState *state =
1799 DO_UPCAST(ExternalSnapshotState, common, common);
1800 if (state->new_bs) {
1801 if (state->overlay_appended) {
1802 bdrv_ref(state->old_bs); /* we can't let bdrv_set_backind_hd()
1803 close state->old_bs; we need it */
1804 bdrv_set_backing_hd(state->new_bs, NULL, &error_abort);
1805 bdrv_replace_node(state->new_bs, state->old_bs, &error_abort);
1806 bdrv_unref(state->old_bs); /* bdrv_replace_node() ref'ed old_bs */
1811 static void external_snapshot_clean(BlkActionState *common)
1813 ExternalSnapshotState *state =
1814 DO_UPCAST(ExternalSnapshotState, common, common);
1815 if (state->aio_context) {
1816 bdrv_drained_end(state->old_bs);
1817 aio_context_release(state->aio_context);
1818 bdrv_unref(state->new_bs);
1822 typedef struct DriveBackupState {
1823 BlkActionState common;
1824 BlockDriverState *bs;
1825 AioContext *aio_context;
1826 BlockJob *job;
1827 } DriveBackupState;
1829 static BlockJob *do_drive_backup(DriveBackup *backup, BlockJobTxn *txn,
1830 Error **errp);
1832 static void drive_backup_prepare(BlkActionState *common, Error **errp)
1834 DriveBackupState *state = DO_UPCAST(DriveBackupState, common, common);
1835 BlockDriverState *bs;
1836 DriveBackup *backup;
1837 Error *local_err = NULL;
1839 assert(common->action->type == TRANSACTION_ACTION_KIND_DRIVE_BACKUP);
1840 backup = common->action->u.drive_backup.data;
1842 bs = qmp_get_root_bs(backup->device, errp);
1843 if (!bs) {
1844 return;
1847 /* AioContext is released in .clean() */
1848 state->aio_context = bdrv_get_aio_context(bs);
1849 aio_context_acquire(state->aio_context);
1850 bdrv_drained_begin(bs);
1851 state->bs = bs;
1853 state->job = do_drive_backup(backup, common->block_job_txn, &local_err);
1854 if (local_err) {
1855 error_propagate(errp, local_err);
1856 return;
1860 static void drive_backup_commit(BlkActionState *common)
1862 DriveBackupState *state = DO_UPCAST(DriveBackupState, common, common);
1863 assert(state->job);
1864 block_job_start(state->job);
1867 static void drive_backup_abort(BlkActionState *common)
1869 DriveBackupState *state = DO_UPCAST(DriveBackupState, common, common);
1871 if (state->job) {
1872 block_job_cancel_sync(state->job);
1876 static void drive_backup_clean(BlkActionState *common)
1878 DriveBackupState *state = DO_UPCAST(DriveBackupState, common, common);
1880 if (state->aio_context) {
1881 bdrv_drained_end(state->bs);
1882 aio_context_release(state->aio_context);
1886 typedef struct BlockdevBackupState {
1887 BlkActionState common;
1888 BlockDriverState *bs;
1889 BlockJob *job;
1890 AioContext *aio_context;
1891 } BlockdevBackupState;
1893 static BlockJob *do_blockdev_backup(BlockdevBackup *backup, BlockJobTxn *txn,
1894 Error **errp);
1896 static void blockdev_backup_prepare(BlkActionState *common, Error **errp)
1898 BlockdevBackupState *state = DO_UPCAST(BlockdevBackupState, common, common);
1899 BlockdevBackup *backup;
1900 BlockDriverState *bs, *target;
1901 Error *local_err = NULL;
1903 assert(common->action->type == TRANSACTION_ACTION_KIND_BLOCKDEV_BACKUP);
1904 backup = common->action->u.blockdev_backup.data;
1906 bs = qmp_get_root_bs(backup->device, errp);
1907 if (!bs) {
1908 return;
1911 target = bdrv_lookup_bs(backup->target, backup->target, errp);
1912 if (!target) {
1913 return;
1916 /* AioContext is released in .clean() */
1917 state->aio_context = bdrv_get_aio_context(bs);
1918 if (state->aio_context != bdrv_get_aio_context(target)) {
1919 state->aio_context = NULL;
1920 error_setg(errp, "Backup between two IO threads is not implemented");
1921 return;
1923 aio_context_acquire(state->aio_context);
1924 state->bs = bs;
1925 bdrv_drained_begin(state->bs);
1927 state->job = do_blockdev_backup(backup, common->block_job_txn, &local_err);
1928 if (local_err) {
1929 error_propagate(errp, local_err);
1930 return;
1934 static void blockdev_backup_commit(BlkActionState *common)
1936 BlockdevBackupState *state = DO_UPCAST(BlockdevBackupState, common, common);
1937 assert(state->job);
1938 block_job_start(state->job);
1941 static void blockdev_backup_abort(BlkActionState *common)
1943 BlockdevBackupState *state = DO_UPCAST(BlockdevBackupState, common, common);
1945 if (state->job) {
1946 block_job_cancel_sync(state->job);
1950 static void blockdev_backup_clean(BlkActionState *common)
1952 BlockdevBackupState *state = DO_UPCAST(BlockdevBackupState, common, common);
1954 if (state->aio_context) {
1955 bdrv_drained_end(state->bs);
1956 aio_context_release(state->aio_context);
1960 typedef struct BlockDirtyBitmapState {
1961 BlkActionState common;
1962 BdrvDirtyBitmap *bitmap;
1963 BlockDriverState *bs;
1964 AioContext *aio_context;
1965 HBitmap *backup;
1966 bool prepared;
1967 } BlockDirtyBitmapState;
1969 static void block_dirty_bitmap_add_prepare(BlkActionState *common,
1970 Error **errp)
1972 Error *local_err = NULL;
1973 BlockDirtyBitmapAdd *action;
1974 BlockDirtyBitmapState *state = DO_UPCAST(BlockDirtyBitmapState,
1975 common, common);
1977 if (action_check_completion_mode(common, errp) < 0) {
1978 return;
1981 action = common->action->u.block_dirty_bitmap_add.data;
1982 /* AIO context taken and released within qmp_block_dirty_bitmap_add */
1983 qmp_block_dirty_bitmap_add(action->node, action->name,
1984 action->has_granularity, action->granularity,
1985 action->has_persistent, action->persistent,
1986 action->has_autoload, action->autoload,
1987 &local_err);
1989 if (!local_err) {
1990 state->prepared = true;
1991 } else {
1992 error_propagate(errp, local_err);
1996 static void block_dirty_bitmap_add_abort(BlkActionState *common)
1998 BlockDirtyBitmapAdd *action;
1999 BlockDirtyBitmapState *state = DO_UPCAST(BlockDirtyBitmapState,
2000 common, common);
2002 action = common->action->u.block_dirty_bitmap_add.data;
2003 /* Should not be able to fail: IF the bitmap was added via .prepare(),
2004 * then the node reference and bitmap name must have been valid.
2006 if (state->prepared) {
2007 qmp_block_dirty_bitmap_remove(action->node, action->name, &error_abort);
2011 static void block_dirty_bitmap_clear_prepare(BlkActionState *common,
2012 Error **errp)
2014 BlockDirtyBitmapState *state = DO_UPCAST(BlockDirtyBitmapState,
2015 common, common);
2016 BlockDirtyBitmap *action;
2018 if (action_check_completion_mode(common, errp) < 0) {
2019 return;
2022 action = common->action->u.block_dirty_bitmap_clear.data;
2023 state->bitmap = block_dirty_bitmap_lookup(action->node,
2024 action->name,
2025 &state->bs,
2026 errp);
2027 if (!state->bitmap) {
2028 return;
2031 if (bdrv_dirty_bitmap_frozen(state->bitmap)) {
2032 error_setg(errp, "Cannot modify a frozen bitmap");
2033 return;
2034 } else if (!bdrv_dirty_bitmap_enabled(state->bitmap)) {
2035 error_setg(errp, "Cannot clear a disabled bitmap");
2036 return;
2037 } else if (bdrv_dirty_bitmap_readonly(state->bitmap)) {
2038 error_setg(errp, "Cannot clear a readonly bitmap");
2039 return;
2042 bdrv_clear_dirty_bitmap(state->bitmap, &state->backup);
2043 /* AioContext is released in .clean() */
2046 static void block_dirty_bitmap_clear_abort(BlkActionState *common)
2048 BlockDirtyBitmapState *state = DO_UPCAST(BlockDirtyBitmapState,
2049 common, common);
2051 if (state->backup) {
2052 bdrv_undo_clear_dirty_bitmap(state->bitmap, state->backup);
2056 static void block_dirty_bitmap_clear_commit(BlkActionState *common)
2058 BlockDirtyBitmapState *state = DO_UPCAST(BlockDirtyBitmapState,
2059 common, common);
2061 hbitmap_free(state->backup);
2064 static void block_dirty_bitmap_clear_clean(BlkActionState *common)
2066 BlockDirtyBitmapState *state = DO_UPCAST(BlockDirtyBitmapState,
2067 common, common);
2069 if (state->aio_context) {
2070 aio_context_release(state->aio_context);
2074 static void abort_prepare(BlkActionState *common, Error **errp)
2076 error_setg(errp, "Transaction aborted using Abort action");
2079 static void abort_commit(BlkActionState *common)
2081 g_assert_not_reached(); /* this action never succeeds */
2084 static const BlkActionOps actions[] = {
2085 [TRANSACTION_ACTION_KIND_BLOCKDEV_SNAPSHOT] = {
2086 .instance_size = sizeof(ExternalSnapshotState),
2087 .prepare = external_snapshot_prepare,
2088 .commit = external_snapshot_commit,
2089 .abort = external_snapshot_abort,
2090 .clean = external_snapshot_clean,
2092 [TRANSACTION_ACTION_KIND_BLOCKDEV_SNAPSHOT_SYNC] = {
2093 .instance_size = sizeof(ExternalSnapshotState),
2094 .prepare = external_snapshot_prepare,
2095 .commit = external_snapshot_commit,
2096 .abort = external_snapshot_abort,
2097 .clean = external_snapshot_clean,
2099 [TRANSACTION_ACTION_KIND_DRIVE_BACKUP] = {
2100 .instance_size = sizeof(DriveBackupState),
2101 .prepare = drive_backup_prepare,
2102 .commit = drive_backup_commit,
2103 .abort = drive_backup_abort,
2104 .clean = drive_backup_clean,
2106 [TRANSACTION_ACTION_KIND_BLOCKDEV_BACKUP] = {
2107 .instance_size = sizeof(BlockdevBackupState),
2108 .prepare = blockdev_backup_prepare,
2109 .commit = blockdev_backup_commit,
2110 .abort = blockdev_backup_abort,
2111 .clean = blockdev_backup_clean,
2113 [TRANSACTION_ACTION_KIND_ABORT] = {
2114 .instance_size = sizeof(BlkActionState),
2115 .prepare = abort_prepare,
2116 .commit = abort_commit,
2118 [TRANSACTION_ACTION_KIND_BLOCKDEV_SNAPSHOT_INTERNAL_SYNC] = {
2119 .instance_size = sizeof(InternalSnapshotState),
2120 .prepare = internal_snapshot_prepare,
2121 .abort = internal_snapshot_abort,
2122 .clean = internal_snapshot_clean,
2124 [TRANSACTION_ACTION_KIND_BLOCK_DIRTY_BITMAP_ADD] = {
2125 .instance_size = sizeof(BlockDirtyBitmapState),
2126 .prepare = block_dirty_bitmap_add_prepare,
2127 .abort = block_dirty_bitmap_add_abort,
2129 [TRANSACTION_ACTION_KIND_BLOCK_DIRTY_BITMAP_CLEAR] = {
2130 .instance_size = sizeof(BlockDirtyBitmapState),
2131 .prepare = block_dirty_bitmap_clear_prepare,
2132 .commit = block_dirty_bitmap_clear_commit,
2133 .abort = block_dirty_bitmap_clear_abort,
2134 .clean = block_dirty_bitmap_clear_clean,
2139 * Allocate a TransactionProperties structure if necessary, and fill
2140 * that structure with desired defaults if they are unset.
2142 static TransactionProperties *get_transaction_properties(
2143 TransactionProperties *props)
2145 if (!props) {
2146 props = g_new0(TransactionProperties, 1);
2149 if (!props->has_completion_mode) {
2150 props->has_completion_mode = true;
2151 props->completion_mode = ACTION_COMPLETION_MODE_INDIVIDUAL;
2154 return props;
2158 * 'Atomic' group operations. The operations are performed as a set, and if
2159 * any fail then we roll back all operations in the group.
2161 void qmp_transaction(TransactionActionList *dev_list,
2162 bool has_props,
2163 struct TransactionProperties *props,
2164 Error **errp)
2166 TransactionActionList *dev_entry = dev_list;
2167 BlockJobTxn *block_job_txn = NULL;
2168 BlkActionState *state, *next;
2169 Error *local_err = NULL;
2171 QSIMPLEQ_HEAD(snap_bdrv_states, BlkActionState) snap_bdrv_states;
2172 QSIMPLEQ_INIT(&snap_bdrv_states);
2174 /* Does this transaction get canceled as a group on failure?
2175 * If not, we don't really need to make a BlockJobTxn.
2177 props = get_transaction_properties(props);
2178 if (props->completion_mode != ACTION_COMPLETION_MODE_INDIVIDUAL) {
2179 block_job_txn = block_job_txn_new();
2182 /* drain all i/o before any operations */
2183 bdrv_drain_all();
2185 /* We don't do anything in this loop that commits us to the operations */
2186 while (NULL != dev_entry) {
2187 TransactionAction *dev_info = NULL;
2188 const BlkActionOps *ops;
2190 dev_info = dev_entry->value;
2191 dev_entry = dev_entry->next;
2193 assert(dev_info->type < ARRAY_SIZE(actions));
2195 ops = &actions[dev_info->type];
2196 assert(ops->instance_size > 0);
2198 state = g_malloc0(ops->instance_size);
2199 state->ops = ops;
2200 state->action = dev_info;
2201 state->block_job_txn = block_job_txn;
2202 state->txn_props = props;
2203 QSIMPLEQ_INSERT_TAIL(&snap_bdrv_states, state, entry);
2205 state->ops->prepare(state, &local_err);
2206 if (local_err) {
2207 error_propagate(errp, local_err);
2208 goto delete_and_fail;
2212 QSIMPLEQ_FOREACH(state, &snap_bdrv_states, entry) {
2213 if (state->ops->commit) {
2214 state->ops->commit(state);
2218 /* success */
2219 goto exit;
2221 delete_and_fail:
2222 /* failure, and it is all-or-none; roll back all operations */
2223 QSIMPLEQ_FOREACH(state, &snap_bdrv_states, entry) {
2224 if (state->ops->abort) {
2225 state->ops->abort(state);
2228 exit:
2229 QSIMPLEQ_FOREACH_SAFE(state, &snap_bdrv_states, entry, next) {
2230 if (state->ops->clean) {
2231 state->ops->clean(state);
2233 g_free(state);
2235 if (!has_props) {
2236 qapi_free_TransactionProperties(props);
2238 block_job_txn_unref(block_job_txn);
2241 void qmp_eject(bool has_device, const char *device,
2242 bool has_id, const char *id,
2243 bool has_force, bool force, Error **errp)
2245 Error *local_err = NULL;
2246 int rc;
2248 if (!has_force) {
2249 force = false;
2252 rc = do_open_tray(has_device ? device : NULL,
2253 has_id ? id : NULL,
2254 force, &local_err);
2255 if (rc && rc != -ENOSYS) {
2256 error_propagate(errp, local_err);
2257 return;
2259 error_free(local_err);
2261 qmp_x_blockdev_remove_medium(has_device, device, has_id, id, errp);
2264 void qmp_block_passwd(bool has_device, const char *device,
2265 bool has_node_name, const char *node_name,
2266 const char *password, Error **errp)
2268 error_setg(errp,
2269 "Setting block passwords directly is no longer supported");
2273 * Attempt to open the tray of @device.
2274 * If @force, ignore its tray lock.
2275 * Else, if the tray is locked, don't open it, but ask the guest to open it.
2276 * On error, store an error through @errp and return -errno.
2277 * If @device does not exist, return -ENODEV.
2278 * If it has no removable media, return -ENOTSUP.
2279 * If it has no tray, return -ENOSYS.
2280 * If the guest was asked to open the tray, return -EINPROGRESS.
2281 * Else, return 0.
2283 static int do_open_tray(const char *blk_name, const char *qdev_id,
2284 bool force, Error **errp)
2286 BlockBackend *blk;
2287 const char *device = qdev_id ?: blk_name;
2288 bool locked;
2290 blk = qmp_get_blk(blk_name, qdev_id, errp);
2291 if (!blk) {
2292 return -ENODEV;
2295 if (!blk_dev_has_removable_media(blk)) {
2296 error_setg(errp, "Device '%s' is not removable", device);
2297 return -ENOTSUP;
2300 if (!blk_dev_has_tray(blk)) {
2301 error_setg(errp, "Device '%s' does not have a tray", device);
2302 return -ENOSYS;
2305 if (blk_dev_is_tray_open(blk)) {
2306 return 0;
2309 locked = blk_dev_is_medium_locked(blk);
2310 if (locked) {
2311 blk_dev_eject_request(blk, force);
2314 if (!locked || force) {
2315 blk_dev_change_media_cb(blk, false, &error_abort);
2318 if (locked && !force) {
2319 error_setg(errp, "Device '%s' is locked and force was not specified, "
2320 "wait for tray to open and try again", device);
2321 return -EINPROGRESS;
2324 return 0;
2327 void qmp_blockdev_open_tray(bool has_device, const char *device,
2328 bool has_id, const char *id,
2329 bool has_force, bool force,
2330 Error **errp)
2332 Error *local_err = NULL;
2333 int rc;
2335 if (!has_force) {
2336 force = false;
2338 rc = do_open_tray(has_device ? device : NULL,
2339 has_id ? id : NULL,
2340 force, &local_err);
2341 if (rc && rc != -ENOSYS && rc != -EINPROGRESS) {
2342 error_propagate(errp, local_err);
2343 return;
2345 error_free(local_err);
2348 void qmp_blockdev_close_tray(bool has_device, const char *device,
2349 bool has_id, const char *id,
2350 Error **errp)
2352 BlockBackend *blk;
2353 Error *local_err = NULL;
2355 device = has_device ? device : NULL;
2356 id = has_id ? id : NULL;
2358 blk = qmp_get_blk(device, id, errp);
2359 if (!blk) {
2360 return;
2363 if (!blk_dev_has_removable_media(blk)) {
2364 error_setg(errp, "Device '%s' is not removable", device ?: id);
2365 return;
2368 if (!blk_dev_has_tray(blk)) {
2369 /* Ignore this command on tray-less devices */
2370 return;
2373 if (!blk_dev_is_tray_open(blk)) {
2374 return;
2377 blk_dev_change_media_cb(blk, true, &local_err);
2378 if (local_err) {
2379 error_propagate(errp, local_err);
2380 return;
2384 void qmp_x_blockdev_remove_medium(bool has_device, const char *device,
2385 bool has_id, const char *id, Error **errp)
2387 BlockBackend *blk;
2388 BlockDriverState *bs;
2389 AioContext *aio_context;
2390 bool has_attached_device;
2392 device = has_device ? device : NULL;
2393 id = has_id ? id : NULL;
2395 blk = qmp_get_blk(device, id, errp);
2396 if (!blk) {
2397 return;
2400 /* For BBs without a device, we can exchange the BDS tree at will */
2401 has_attached_device = blk_get_attached_dev(blk);
2403 if (has_attached_device && !blk_dev_has_removable_media(blk)) {
2404 error_setg(errp, "Device '%s' is not removable", device ?: id);
2405 return;
2408 if (has_attached_device && blk_dev_has_tray(blk) &&
2409 !blk_dev_is_tray_open(blk))
2411 error_setg(errp, "Tray of device '%s' is not open", device ?: id);
2412 return;
2415 bs = blk_bs(blk);
2416 if (!bs) {
2417 return;
2420 aio_context = bdrv_get_aio_context(bs);
2421 aio_context_acquire(aio_context);
2423 if (bdrv_op_is_blocked(bs, BLOCK_OP_TYPE_EJECT, errp)) {
2424 goto out;
2427 blk_remove_bs(blk);
2429 if (!blk_dev_has_tray(blk)) {
2430 /* For tray-less devices, blockdev-open-tray is a no-op (or may not be
2431 * called at all); therefore, the medium needs to be ejected here.
2432 * Do it after blk_remove_bs() so blk_is_inserted(blk) returns the @load
2433 * value passed here (i.e. false). */
2434 blk_dev_change_media_cb(blk, false, &error_abort);
2437 out:
2438 aio_context_release(aio_context);
2441 static void qmp_blockdev_insert_anon_medium(BlockBackend *blk,
2442 BlockDriverState *bs, Error **errp)
2444 Error *local_err = NULL;
2445 bool has_device;
2446 int ret;
2448 /* For BBs without a device, we can exchange the BDS tree at will */
2449 has_device = blk_get_attached_dev(blk);
2451 if (has_device && !blk_dev_has_removable_media(blk)) {
2452 error_setg(errp, "Device is not removable");
2453 return;
2456 if (has_device && blk_dev_has_tray(blk) && !blk_dev_is_tray_open(blk)) {
2457 error_setg(errp, "Tray of the device is not open");
2458 return;
2461 if (blk_bs(blk)) {
2462 error_setg(errp, "There already is a medium in the device");
2463 return;
2466 ret = blk_insert_bs(blk, bs, errp);
2467 if (ret < 0) {
2468 return;
2471 if (!blk_dev_has_tray(blk)) {
2472 /* For tray-less devices, blockdev-close-tray is a no-op (or may not be
2473 * called at all); therefore, the medium needs to be pushed into the
2474 * slot here.
2475 * Do it after blk_insert_bs() so blk_is_inserted(blk) returns the @load
2476 * value passed here (i.e. true). */
2477 blk_dev_change_media_cb(blk, true, &local_err);
2478 if (local_err) {
2479 error_propagate(errp, local_err);
2480 blk_remove_bs(blk);
2481 return;
2486 void qmp_x_blockdev_insert_medium(bool has_device, const char *device,
2487 bool has_id, const char *id,
2488 const char *node_name, Error **errp)
2490 BlockBackend *blk;
2491 BlockDriverState *bs;
2493 blk = qmp_get_blk(has_device ? device : NULL,
2494 has_id ? id : NULL,
2495 errp);
2496 if (!blk) {
2497 return;
2500 bs = bdrv_find_node(node_name);
2501 if (!bs) {
2502 error_setg(errp, "Node '%s' not found", node_name);
2503 return;
2506 if (bdrv_has_blk(bs)) {
2507 error_setg(errp, "Node '%s' is already in use", node_name);
2508 return;
2511 qmp_blockdev_insert_anon_medium(blk, bs, errp);
2514 void qmp_blockdev_change_medium(bool has_device, const char *device,
2515 bool has_id, const char *id,
2516 const char *filename,
2517 bool has_format, const char *format,
2518 bool has_read_only,
2519 BlockdevChangeReadOnlyMode read_only,
2520 Error **errp)
2522 BlockBackend *blk;
2523 BlockDriverState *medium_bs = NULL;
2524 int bdrv_flags;
2525 bool detect_zeroes;
2526 int rc;
2527 QDict *options = NULL;
2528 Error *err = NULL;
2530 blk = qmp_get_blk(has_device ? device : NULL,
2531 has_id ? id : NULL,
2532 errp);
2533 if (!blk) {
2534 goto fail;
2537 if (blk_bs(blk)) {
2538 blk_update_root_state(blk);
2541 bdrv_flags = blk_get_open_flags_from_root_state(blk);
2542 bdrv_flags &= ~(BDRV_O_TEMPORARY | BDRV_O_SNAPSHOT | BDRV_O_NO_BACKING |
2543 BDRV_O_PROTOCOL);
2545 if (!has_read_only) {
2546 read_only = BLOCKDEV_CHANGE_READ_ONLY_MODE_RETAIN;
2549 switch (read_only) {
2550 case BLOCKDEV_CHANGE_READ_ONLY_MODE_RETAIN:
2551 break;
2553 case BLOCKDEV_CHANGE_READ_ONLY_MODE_READ_ONLY:
2554 bdrv_flags &= ~BDRV_O_RDWR;
2555 break;
2557 case BLOCKDEV_CHANGE_READ_ONLY_MODE_READ_WRITE:
2558 bdrv_flags |= BDRV_O_RDWR;
2559 break;
2561 default:
2562 abort();
2565 options = qdict_new();
2566 detect_zeroes = blk_get_detect_zeroes_from_root_state(blk);
2567 qdict_put_str(options, "detect-zeroes", detect_zeroes ? "on" : "off");
2569 if (has_format) {
2570 qdict_put_str(options, "driver", format);
2573 medium_bs = bdrv_open(filename, NULL, options, bdrv_flags, errp);
2574 if (!medium_bs) {
2575 goto fail;
2578 rc = do_open_tray(has_device ? device : NULL,
2579 has_id ? id : NULL,
2580 false, &err);
2581 if (rc && rc != -ENOSYS) {
2582 error_propagate(errp, err);
2583 goto fail;
2585 error_free(err);
2586 err = NULL;
2588 qmp_x_blockdev_remove_medium(has_device, device, has_id, id, &err);
2589 if (err) {
2590 error_propagate(errp, err);
2591 goto fail;
2594 qmp_blockdev_insert_anon_medium(blk, medium_bs, &err);
2595 if (err) {
2596 error_propagate(errp, err);
2597 goto fail;
2600 qmp_blockdev_close_tray(has_device, device, has_id, id, errp);
2602 fail:
2603 /* If the medium has been inserted, the device has its own reference, so
2604 * ours must be relinquished; and if it has not been inserted successfully,
2605 * the reference must be relinquished anyway */
2606 bdrv_unref(medium_bs);
2609 /* throttling disk I/O limits */
2610 void qmp_block_set_io_throttle(BlockIOThrottle *arg, Error **errp)
2612 ThrottleConfig cfg;
2613 BlockDriverState *bs;
2614 BlockBackend *blk;
2615 AioContext *aio_context;
2617 blk = qmp_get_blk(arg->has_device ? arg->device : NULL,
2618 arg->has_id ? arg->id : NULL,
2619 errp);
2620 if (!blk) {
2621 return;
2624 aio_context = blk_get_aio_context(blk);
2625 aio_context_acquire(aio_context);
2627 bs = blk_bs(blk);
2628 if (!bs) {
2629 error_setg(errp, "Device has no medium");
2630 goto out;
2633 throttle_config_init(&cfg);
2634 cfg.buckets[THROTTLE_BPS_TOTAL].avg = arg->bps;
2635 cfg.buckets[THROTTLE_BPS_READ].avg = arg->bps_rd;
2636 cfg.buckets[THROTTLE_BPS_WRITE].avg = arg->bps_wr;
2638 cfg.buckets[THROTTLE_OPS_TOTAL].avg = arg->iops;
2639 cfg.buckets[THROTTLE_OPS_READ].avg = arg->iops_rd;
2640 cfg.buckets[THROTTLE_OPS_WRITE].avg = arg->iops_wr;
2642 if (arg->has_bps_max) {
2643 cfg.buckets[THROTTLE_BPS_TOTAL].max = arg->bps_max;
2645 if (arg->has_bps_rd_max) {
2646 cfg.buckets[THROTTLE_BPS_READ].max = arg->bps_rd_max;
2648 if (arg->has_bps_wr_max) {
2649 cfg.buckets[THROTTLE_BPS_WRITE].max = arg->bps_wr_max;
2651 if (arg->has_iops_max) {
2652 cfg.buckets[THROTTLE_OPS_TOTAL].max = arg->iops_max;
2654 if (arg->has_iops_rd_max) {
2655 cfg.buckets[THROTTLE_OPS_READ].max = arg->iops_rd_max;
2657 if (arg->has_iops_wr_max) {
2658 cfg.buckets[THROTTLE_OPS_WRITE].max = arg->iops_wr_max;
2661 if (arg->has_bps_max_length) {
2662 cfg.buckets[THROTTLE_BPS_TOTAL].burst_length = arg->bps_max_length;
2664 if (arg->has_bps_rd_max_length) {
2665 cfg.buckets[THROTTLE_BPS_READ].burst_length = arg->bps_rd_max_length;
2667 if (arg->has_bps_wr_max_length) {
2668 cfg.buckets[THROTTLE_BPS_WRITE].burst_length = arg->bps_wr_max_length;
2670 if (arg->has_iops_max_length) {
2671 cfg.buckets[THROTTLE_OPS_TOTAL].burst_length = arg->iops_max_length;
2673 if (arg->has_iops_rd_max_length) {
2674 cfg.buckets[THROTTLE_OPS_READ].burst_length = arg->iops_rd_max_length;
2676 if (arg->has_iops_wr_max_length) {
2677 cfg.buckets[THROTTLE_OPS_WRITE].burst_length = arg->iops_wr_max_length;
2680 if (arg->has_iops_size) {
2681 cfg.op_size = arg->iops_size;
2684 if (!throttle_is_valid(&cfg, errp)) {
2685 goto out;
2688 if (throttle_enabled(&cfg)) {
2689 /* Enable I/O limits if they're not enabled yet, otherwise
2690 * just update the throttling group. */
2691 if (!blk_get_public(blk)->throttle_state) {
2692 blk_io_limits_enable(blk,
2693 arg->has_group ? arg->group :
2694 arg->has_device ? arg->device :
2695 arg->id);
2696 } else if (arg->has_group) {
2697 blk_io_limits_update_group(blk, arg->group);
2699 /* Set the new throttling configuration */
2700 blk_set_io_limits(blk, &cfg);
2701 } else if (blk_get_public(blk)->throttle_state) {
2702 /* If all throttling settings are set to 0, disable I/O limits */
2703 blk_io_limits_disable(blk);
2706 out:
2707 aio_context_release(aio_context);
2710 void qmp_block_dirty_bitmap_add(const char *node, const char *name,
2711 bool has_granularity, uint32_t granularity,
2712 bool has_persistent, bool persistent,
2713 bool has_autoload, bool autoload,
2714 Error **errp)
2716 BlockDriverState *bs;
2717 BdrvDirtyBitmap *bitmap;
2719 if (!name || name[0] == '\0') {
2720 error_setg(errp, "Bitmap name cannot be empty");
2721 return;
2724 bs = bdrv_lookup_bs(node, node, errp);
2725 if (!bs) {
2726 return;
2729 if (has_granularity) {
2730 if (granularity < 512 || !is_power_of_2(granularity)) {
2731 error_setg(errp, "Granularity must be power of 2 "
2732 "and at least 512");
2733 return;
2735 } else {
2736 /* Default to cluster size, if available: */
2737 granularity = bdrv_get_default_bitmap_granularity(bs);
2740 if (!has_persistent) {
2741 persistent = false;
2743 if (!has_autoload) {
2744 autoload = false;
2747 if (has_autoload && !persistent) {
2748 error_setg(errp, "Autoload flag must be used only for persistent "
2749 "bitmaps");
2750 return;
2753 if (persistent &&
2754 !bdrv_can_store_new_dirty_bitmap(bs, name, granularity, errp))
2756 return;
2759 bitmap = bdrv_create_dirty_bitmap(bs, granularity, name, errp);
2760 if (bitmap == NULL) {
2761 return;
2764 bdrv_dirty_bitmap_set_persistance(bitmap, persistent);
2765 bdrv_dirty_bitmap_set_autoload(bitmap, autoload);
2768 void qmp_block_dirty_bitmap_remove(const char *node, const char *name,
2769 Error **errp)
2771 BlockDriverState *bs;
2772 BdrvDirtyBitmap *bitmap;
2773 Error *local_err = NULL;
2775 bitmap = block_dirty_bitmap_lookup(node, name, &bs, errp);
2776 if (!bitmap || !bs) {
2777 return;
2780 if (bdrv_dirty_bitmap_frozen(bitmap)) {
2781 error_setg(errp,
2782 "Bitmap '%s' is currently frozen and cannot be removed",
2783 name);
2784 return;
2787 if (bdrv_dirty_bitmap_get_persistance(bitmap)) {
2788 bdrv_remove_persistent_dirty_bitmap(bs, name, &local_err);
2789 if (local_err != NULL) {
2790 error_propagate(errp, local_err);
2791 return;
2795 bdrv_dirty_bitmap_make_anon(bitmap);
2796 bdrv_release_dirty_bitmap(bs, bitmap);
2800 * Completely clear a bitmap, for the purposes of synchronizing a bitmap
2801 * immediately after a full backup operation.
2803 void qmp_block_dirty_bitmap_clear(const char *node, const char *name,
2804 Error **errp)
2806 BdrvDirtyBitmap *bitmap;
2807 BlockDriverState *bs;
2809 bitmap = block_dirty_bitmap_lookup(node, name, &bs, errp);
2810 if (!bitmap || !bs) {
2811 return;
2814 if (bdrv_dirty_bitmap_frozen(bitmap)) {
2815 error_setg(errp,
2816 "Bitmap '%s' is currently frozen and cannot be modified",
2817 name);
2818 return;
2819 } else if (!bdrv_dirty_bitmap_enabled(bitmap)) {
2820 error_setg(errp,
2821 "Bitmap '%s' is currently disabled and cannot be cleared",
2822 name);
2823 return;
2824 } else if (bdrv_dirty_bitmap_readonly(bitmap)) {
2825 error_setg(errp, "Bitmap '%s' is readonly and cannot be cleared", name);
2826 return;
2829 bdrv_clear_dirty_bitmap(bitmap, NULL);
2832 BlockDirtyBitmapSha256 *qmp_x_debug_block_dirty_bitmap_sha256(const char *node,
2833 const char *name,
2834 Error **errp)
2836 BdrvDirtyBitmap *bitmap;
2837 BlockDriverState *bs;
2838 BlockDirtyBitmapSha256 *ret = NULL;
2839 char *sha256;
2841 bitmap = block_dirty_bitmap_lookup(node, name, &bs, errp);
2842 if (!bitmap || !bs) {
2843 return NULL;
2846 sha256 = bdrv_dirty_bitmap_sha256(bitmap, errp);
2847 if (sha256 == NULL) {
2848 return NULL;
2851 ret = g_new(BlockDirtyBitmapSha256, 1);
2852 ret->sha256 = sha256;
2854 return ret;
2857 void hmp_drive_del(Monitor *mon, const QDict *qdict)
2859 const char *id = qdict_get_str(qdict, "id");
2860 BlockBackend *blk;
2861 BlockDriverState *bs;
2862 AioContext *aio_context;
2863 Error *local_err = NULL;
2865 bs = bdrv_find_node(id);
2866 if (bs) {
2867 qmp_blockdev_del(id, &local_err);
2868 if (local_err) {
2869 error_report_err(local_err);
2871 return;
2874 blk = blk_by_name(id);
2875 if (!blk) {
2876 error_report("Device '%s' not found", id);
2877 return;
2880 if (!blk_legacy_dinfo(blk)) {
2881 error_report("Deleting device added with blockdev-add"
2882 " is not supported");
2883 return;
2886 aio_context = blk_get_aio_context(blk);
2887 aio_context_acquire(aio_context);
2889 bs = blk_bs(blk);
2890 if (bs) {
2891 if (bdrv_op_is_blocked(bs, BLOCK_OP_TYPE_DRIVE_DEL, &local_err)) {
2892 error_report_err(local_err);
2893 aio_context_release(aio_context);
2894 return;
2897 blk_remove_bs(blk);
2900 /* Make the BlockBackend and the attached BlockDriverState anonymous */
2901 monitor_remove_blk(blk);
2903 /* If this BlockBackend has a device attached to it, its refcount will be
2904 * decremented when the device is removed; otherwise we have to do so here.
2906 if (blk_get_attached_dev(blk)) {
2907 /* Further I/O must not pause the guest */
2908 blk_set_on_error(blk, BLOCKDEV_ON_ERROR_REPORT,
2909 BLOCKDEV_ON_ERROR_REPORT);
2910 } else {
2911 blk_unref(blk);
2914 aio_context_release(aio_context);
2917 void qmp_block_resize(bool has_device, const char *device,
2918 bool has_node_name, const char *node_name,
2919 int64_t size, Error **errp)
2921 Error *local_err = NULL;
2922 BlockBackend *blk = NULL;
2923 BlockDriverState *bs;
2924 AioContext *aio_context;
2925 int ret;
2927 bs = bdrv_lookup_bs(has_device ? device : NULL,
2928 has_node_name ? node_name : NULL,
2929 &local_err);
2930 if (local_err) {
2931 error_propagate(errp, local_err);
2932 return;
2935 aio_context = bdrv_get_aio_context(bs);
2936 aio_context_acquire(aio_context);
2938 if (!bdrv_is_first_non_filter(bs)) {
2939 error_setg(errp, QERR_FEATURE_DISABLED, "resize");
2940 goto out;
2943 if (size < 0) {
2944 error_setg(errp, QERR_INVALID_PARAMETER_VALUE, "size", "a >0 size");
2945 goto out;
2948 if (bdrv_op_is_blocked(bs, BLOCK_OP_TYPE_RESIZE, NULL)) {
2949 error_setg(errp, QERR_DEVICE_IN_USE, device);
2950 goto out;
2953 blk = blk_new(BLK_PERM_RESIZE, BLK_PERM_ALL);
2954 ret = blk_insert_bs(blk, bs, errp);
2955 if (ret < 0) {
2956 goto out;
2959 bdrv_drained_begin(bs);
2960 ret = blk_truncate(blk, size, PREALLOC_MODE_OFF, errp);
2961 bdrv_drained_end(bs);
2963 out:
2964 blk_unref(blk);
2965 aio_context_release(aio_context);
2968 void qmp_block_stream(bool has_job_id, const char *job_id, const char *device,
2969 bool has_base, const char *base,
2970 bool has_base_node, const char *base_node,
2971 bool has_backing_file, const char *backing_file,
2972 bool has_speed, int64_t speed,
2973 bool has_on_error, BlockdevOnError on_error,
2974 Error **errp)
2976 BlockDriverState *bs, *iter;
2977 BlockDriverState *base_bs = NULL;
2978 AioContext *aio_context;
2979 Error *local_err = NULL;
2980 const char *base_name = NULL;
2982 if (!has_on_error) {
2983 on_error = BLOCKDEV_ON_ERROR_REPORT;
2986 bs = bdrv_lookup_bs(device, device, errp);
2987 if (!bs) {
2988 return;
2991 aio_context = bdrv_get_aio_context(bs);
2992 aio_context_acquire(aio_context);
2994 if (has_base && has_base_node) {
2995 error_setg(errp, "'base' and 'base-node' cannot be specified "
2996 "at the same time");
2997 goto out;
3000 if (has_base) {
3001 base_bs = bdrv_find_backing_image(bs, base);
3002 if (base_bs == NULL) {
3003 error_setg(errp, QERR_BASE_NOT_FOUND, base);
3004 goto out;
3006 assert(bdrv_get_aio_context(base_bs) == aio_context);
3007 base_name = base;
3010 if (has_base_node) {
3011 base_bs = bdrv_lookup_bs(NULL, base_node, errp);
3012 if (!base_bs) {
3013 goto out;
3015 if (bs == base_bs || !bdrv_chain_contains(bs, base_bs)) {
3016 error_setg(errp, "Node '%s' is not a backing image of '%s'",
3017 base_node, device);
3018 goto out;
3020 assert(bdrv_get_aio_context(base_bs) == aio_context);
3021 base_name = base_bs->filename;
3024 /* Check for op blockers in the whole chain between bs and base */
3025 for (iter = bs; iter && iter != base_bs; iter = backing_bs(iter)) {
3026 if (bdrv_op_is_blocked(iter, BLOCK_OP_TYPE_STREAM, errp)) {
3027 goto out;
3031 /* if we are streaming the entire chain, the result will have no backing
3032 * file, and specifying one is therefore an error */
3033 if (base_bs == NULL && has_backing_file) {
3034 error_setg(errp, "backing file specified, but streaming the "
3035 "entire chain");
3036 goto out;
3039 /* backing_file string overrides base bs filename */
3040 base_name = has_backing_file ? backing_file : base_name;
3042 stream_start(has_job_id ? job_id : NULL, bs, base_bs, base_name,
3043 has_speed ? speed : 0, on_error, &local_err);
3044 if (local_err) {
3045 error_propagate(errp, local_err);
3046 goto out;
3049 trace_qmp_block_stream(bs, bs->job);
3051 out:
3052 aio_context_release(aio_context);
3055 void qmp_block_commit(bool has_job_id, const char *job_id, const char *device,
3056 bool has_base, const char *base,
3057 bool has_top, const char *top,
3058 bool has_backing_file, const char *backing_file,
3059 bool has_speed, int64_t speed,
3060 bool has_filter_node_name, const char *filter_node_name,
3061 Error **errp)
3063 BlockDriverState *bs;
3064 BlockDriverState *iter;
3065 BlockDriverState *base_bs, *top_bs;
3066 AioContext *aio_context;
3067 Error *local_err = NULL;
3068 /* This will be part of the QMP command, if/when the
3069 * BlockdevOnError change for blkmirror makes it in
3071 BlockdevOnError on_error = BLOCKDEV_ON_ERROR_REPORT;
3073 if (!has_speed) {
3074 speed = 0;
3076 if (!has_filter_node_name) {
3077 filter_node_name = NULL;
3080 /* Important Note:
3081 * libvirt relies on the DeviceNotFound error class in order to probe for
3082 * live commit feature versions; for this to work, we must make sure to
3083 * perform the device lookup before any generic errors that may occur in a
3084 * scenario in which all optional arguments are omitted. */
3085 bs = qmp_get_root_bs(device, &local_err);
3086 if (!bs) {
3087 bs = bdrv_lookup_bs(device, device, NULL);
3088 if (!bs) {
3089 error_free(local_err);
3090 error_set(errp, ERROR_CLASS_DEVICE_NOT_FOUND,
3091 "Device '%s' not found", device);
3092 } else {
3093 error_propagate(errp, local_err);
3095 return;
3098 aio_context = bdrv_get_aio_context(bs);
3099 aio_context_acquire(aio_context);
3101 if (bdrv_op_is_blocked(bs, BLOCK_OP_TYPE_COMMIT_SOURCE, errp)) {
3102 goto out;
3105 /* default top_bs is the active layer */
3106 top_bs = bs;
3108 if (has_top && top) {
3109 if (strcmp(bs->filename, top) != 0) {
3110 top_bs = bdrv_find_backing_image(bs, top);
3114 if (top_bs == NULL) {
3115 error_setg(errp, "Top image file %s not found", top ? top : "NULL");
3116 goto out;
3119 assert(bdrv_get_aio_context(top_bs) == aio_context);
3121 if (has_base && base) {
3122 base_bs = bdrv_find_backing_image(top_bs, base);
3123 } else {
3124 base_bs = bdrv_find_base(top_bs);
3127 if (base_bs == NULL) {
3128 error_setg(errp, QERR_BASE_NOT_FOUND, base ? base : "NULL");
3129 goto out;
3132 assert(bdrv_get_aio_context(base_bs) == aio_context);
3134 for (iter = top_bs; iter != backing_bs(base_bs); iter = backing_bs(iter)) {
3135 if (bdrv_op_is_blocked(iter, BLOCK_OP_TYPE_COMMIT_TARGET, errp)) {
3136 goto out;
3140 /* Do not allow attempts to commit an image into itself */
3141 if (top_bs == base_bs) {
3142 error_setg(errp, "cannot commit an image into itself");
3143 goto out;
3146 if (top_bs == bs) {
3147 if (has_backing_file) {
3148 error_setg(errp, "'backing-file' specified,"
3149 " but 'top' is the active layer");
3150 goto out;
3152 commit_active_start(has_job_id ? job_id : NULL, bs, base_bs,
3153 BLOCK_JOB_DEFAULT, speed, on_error,
3154 filter_node_name, NULL, NULL, false, &local_err);
3155 } else {
3156 BlockDriverState *overlay_bs = bdrv_find_overlay(bs, top_bs);
3157 if (bdrv_op_is_blocked(overlay_bs, BLOCK_OP_TYPE_COMMIT_TARGET, errp)) {
3158 goto out;
3160 commit_start(has_job_id ? job_id : NULL, bs, base_bs, top_bs, speed,
3161 on_error, has_backing_file ? backing_file : NULL,
3162 filter_node_name, &local_err);
3164 if (local_err != NULL) {
3165 error_propagate(errp, local_err);
3166 goto out;
3169 out:
3170 aio_context_release(aio_context);
3173 static BlockJob *do_drive_backup(DriveBackup *backup, BlockJobTxn *txn,
3174 Error **errp)
3176 BlockDriverState *bs;
3177 BlockDriverState *target_bs;
3178 BlockDriverState *source = NULL;
3179 BlockJob *job = NULL;
3180 BdrvDirtyBitmap *bmap = NULL;
3181 AioContext *aio_context;
3182 QDict *options = NULL;
3183 Error *local_err = NULL;
3184 int flags;
3185 int64_t size;
3186 bool set_backing_hd = false;
3188 if (!backup->has_speed) {
3189 backup->speed = 0;
3191 if (!backup->has_on_source_error) {
3192 backup->on_source_error = BLOCKDEV_ON_ERROR_REPORT;
3194 if (!backup->has_on_target_error) {
3195 backup->on_target_error = BLOCKDEV_ON_ERROR_REPORT;
3197 if (!backup->has_mode) {
3198 backup->mode = NEW_IMAGE_MODE_ABSOLUTE_PATHS;
3200 if (!backup->has_job_id) {
3201 backup->job_id = NULL;
3203 if (!backup->has_compress) {
3204 backup->compress = false;
3207 bs = qmp_get_root_bs(backup->device, errp);
3208 if (!bs) {
3209 return NULL;
3212 aio_context = bdrv_get_aio_context(bs);
3213 aio_context_acquire(aio_context);
3215 if (!backup->has_format) {
3216 backup->format = backup->mode == NEW_IMAGE_MODE_EXISTING ?
3217 NULL : (char*) bs->drv->format_name;
3220 /* Early check to avoid creating target */
3221 if (bdrv_op_is_blocked(bs, BLOCK_OP_TYPE_BACKUP_SOURCE, errp)) {
3222 goto out;
3225 flags = bs->open_flags | BDRV_O_RDWR;
3227 /* See if we have a backing HD we can use to create our new image
3228 * on top of. */
3229 if (backup->sync == MIRROR_SYNC_MODE_TOP) {
3230 source = backing_bs(bs);
3231 if (!source) {
3232 backup->sync = MIRROR_SYNC_MODE_FULL;
3235 if (backup->sync == MIRROR_SYNC_MODE_NONE) {
3236 source = bs;
3237 flags |= BDRV_O_NO_BACKING;
3238 set_backing_hd = true;
3241 size = bdrv_getlength(bs);
3242 if (size < 0) {
3243 error_setg_errno(errp, -size, "bdrv_getlength failed");
3244 goto out;
3247 if (backup->mode != NEW_IMAGE_MODE_EXISTING) {
3248 assert(backup->format);
3249 if (source) {
3250 bdrv_img_create(backup->target, backup->format, source->filename,
3251 source->drv->format_name, NULL,
3252 size, flags, false, &local_err);
3253 } else {
3254 bdrv_img_create(backup->target, backup->format, NULL, NULL, NULL,
3255 size, flags, false, &local_err);
3259 if (local_err) {
3260 error_propagate(errp, local_err);
3261 goto out;
3264 if (backup->format) {
3265 if (!options) {
3266 options = qdict_new();
3268 qdict_put_str(options, "driver", backup->format);
3271 target_bs = bdrv_open(backup->target, NULL, options, flags, errp);
3272 if (!target_bs) {
3273 goto out;
3276 bdrv_set_aio_context(target_bs, aio_context);
3278 if (set_backing_hd) {
3279 bdrv_set_backing_hd(target_bs, source, &local_err);
3280 if (local_err) {
3281 bdrv_unref(target_bs);
3282 goto out;
3286 if (backup->has_bitmap) {
3287 bmap = bdrv_find_dirty_bitmap(bs, backup->bitmap);
3288 if (!bmap) {
3289 error_setg(errp, "Bitmap '%s' could not be found", backup->bitmap);
3290 bdrv_unref(target_bs);
3291 goto out;
3295 job = backup_job_create(backup->job_id, bs, target_bs, backup->speed,
3296 backup->sync, bmap, backup->compress,
3297 backup->on_source_error, backup->on_target_error,
3298 BLOCK_JOB_DEFAULT, NULL, NULL, txn, &local_err);
3299 bdrv_unref(target_bs);
3300 if (local_err != NULL) {
3301 error_propagate(errp, local_err);
3302 goto out;
3305 out:
3306 aio_context_release(aio_context);
3307 return job;
3310 void qmp_drive_backup(DriveBackup *arg, Error **errp)
3313 BlockJob *job;
3314 job = do_drive_backup(arg, NULL, errp);
3315 if (job) {
3316 block_job_start(job);
3320 BlockDeviceInfoList *qmp_query_named_block_nodes(Error **errp)
3322 return bdrv_named_nodes_list(errp);
3325 BlockJob *do_blockdev_backup(BlockdevBackup *backup, BlockJobTxn *txn,
3326 Error **errp)
3328 BlockDriverState *bs;
3329 BlockDriverState *target_bs;
3330 Error *local_err = NULL;
3331 AioContext *aio_context;
3332 BlockJob *job = NULL;
3334 if (!backup->has_speed) {
3335 backup->speed = 0;
3337 if (!backup->has_on_source_error) {
3338 backup->on_source_error = BLOCKDEV_ON_ERROR_REPORT;
3340 if (!backup->has_on_target_error) {
3341 backup->on_target_error = BLOCKDEV_ON_ERROR_REPORT;
3343 if (!backup->has_job_id) {
3344 backup->job_id = NULL;
3346 if (!backup->has_compress) {
3347 backup->compress = false;
3350 bs = qmp_get_root_bs(backup->device, errp);
3351 if (!bs) {
3352 return NULL;
3355 aio_context = bdrv_get_aio_context(bs);
3356 aio_context_acquire(aio_context);
3358 target_bs = bdrv_lookup_bs(backup->target, backup->target, errp);
3359 if (!target_bs) {
3360 goto out;
3363 if (bdrv_get_aio_context(target_bs) != aio_context) {
3364 if (!bdrv_has_blk(target_bs)) {
3365 /* The target BDS is not attached, we can safely move it to another
3366 * AioContext. */
3367 bdrv_set_aio_context(target_bs, aio_context);
3368 } else {
3369 error_setg(errp, "Target is attached to a different thread from "
3370 "source.");
3371 goto out;
3374 job = backup_job_create(backup->job_id, bs, target_bs, backup->speed,
3375 backup->sync, NULL, backup->compress,
3376 backup->on_source_error, backup->on_target_error,
3377 BLOCK_JOB_DEFAULT, NULL, NULL, txn, &local_err);
3378 if (local_err != NULL) {
3379 error_propagate(errp, local_err);
3381 out:
3382 aio_context_release(aio_context);
3383 return job;
3386 void qmp_blockdev_backup(BlockdevBackup *arg, Error **errp)
3388 BlockJob *job;
3389 job = do_blockdev_backup(arg, NULL, errp);
3390 if (job) {
3391 block_job_start(job);
3395 /* Parameter check and block job starting for drive mirroring.
3396 * Caller should hold @device and @target's aio context (must be the same).
3398 static void blockdev_mirror_common(const char *job_id, BlockDriverState *bs,
3399 BlockDriverState *target,
3400 bool has_replaces, const char *replaces,
3401 enum MirrorSyncMode sync,
3402 BlockMirrorBackingMode backing_mode,
3403 bool has_speed, int64_t speed,
3404 bool has_granularity, uint32_t granularity,
3405 bool has_buf_size, int64_t buf_size,
3406 bool has_on_source_error,
3407 BlockdevOnError on_source_error,
3408 bool has_on_target_error,
3409 BlockdevOnError on_target_error,
3410 bool has_unmap, bool unmap,
3411 bool has_filter_node_name,
3412 const char *filter_node_name,
3413 Error **errp)
3416 if (!has_speed) {
3417 speed = 0;
3419 if (!has_on_source_error) {
3420 on_source_error = BLOCKDEV_ON_ERROR_REPORT;
3422 if (!has_on_target_error) {
3423 on_target_error = BLOCKDEV_ON_ERROR_REPORT;
3425 if (!has_granularity) {
3426 granularity = 0;
3428 if (!has_buf_size) {
3429 buf_size = 0;
3431 if (!has_unmap) {
3432 unmap = true;
3434 if (!has_filter_node_name) {
3435 filter_node_name = NULL;
3438 if (granularity != 0 && (granularity < 512 || granularity > 1048576 * 64)) {
3439 error_setg(errp, QERR_INVALID_PARAMETER_VALUE, "granularity",
3440 "a value in range [512B, 64MB]");
3441 return;
3443 if (granularity & (granularity - 1)) {
3444 error_setg(errp, QERR_INVALID_PARAMETER_VALUE, "granularity",
3445 "power of 2");
3446 return;
3449 if (bdrv_op_is_blocked(bs, BLOCK_OP_TYPE_MIRROR_SOURCE, errp)) {
3450 return;
3452 if (bdrv_op_is_blocked(target, BLOCK_OP_TYPE_MIRROR_TARGET, errp)) {
3453 return;
3456 if (!bs->backing && sync == MIRROR_SYNC_MODE_TOP) {
3457 sync = MIRROR_SYNC_MODE_FULL;
3460 /* pass the node name to replace to mirror start since it's loose coupling
3461 * and will allow to check whether the node still exist at mirror completion
3463 mirror_start(job_id, bs, target,
3464 has_replaces ? replaces : NULL,
3465 speed, granularity, buf_size, sync, backing_mode,
3466 on_source_error, on_target_error, unmap, filter_node_name,
3467 errp);
3470 void qmp_drive_mirror(DriveMirror *arg, Error **errp)
3472 BlockDriverState *bs;
3473 BlockDriverState *source, *target_bs;
3474 AioContext *aio_context;
3475 BlockMirrorBackingMode backing_mode;
3476 Error *local_err = NULL;
3477 QDict *options = NULL;
3478 int flags;
3479 int64_t size;
3480 const char *format = arg->format;
3482 bs = qmp_get_root_bs(arg->device, errp);
3483 if (!bs) {
3484 return;
3487 aio_context = bdrv_get_aio_context(bs);
3488 aio_context_acquire(aio_context);
3490 if (!arg->has_mode) {
3491 arg->mode = NEW_IMAGE_MODE_ABSOLUTE_PATHS;
3494 if (!arg->has_format) {
3495 format = (arg->mode == NEW_IMAGE_MODE_EXISTING
3496 ? NULL : bs->drv->format_name);
3499 flags = bs->open_flags | BDRV_O_RDWR;
3500 source = backing_bs(bs);
3501 if (!source && arg->sync == MIRROR_SYNC_MODE_TOP) {
3502 arg->sync = MIRROR_SYNC_MODE_FULL;
3504 if (arg->sync == MIRROR_SYNC_MODE_NONE) {
3505 source = bs;
3508 size = bdrv_getlength(bs);
3509 if (size < 0) {
3510 error_setg_errno(errp, -size, "bdrv_getlength failed");
3511 goto out;
3514 if (arg->has_replaces) {
3515 BlockDriverState *to_replace_bs;
3516 AioContext *replace_aio_context;
3517 int64_t replace_size;
3519 if (!arg->has_node_name) {
3520 error_setg(errp, "a node-name must be provided when replacing a"
3521 " named node of the graph");
3522 goto out;
3525 to_replace_bs = check_to_replace_node(bs, arg->replaces, &local_err);
3527 if (!to_replace_bs) {
3528 error_propagate(errp, local_err);
3529 goto out;
3532 replace_aio_context = bdrv_get_aio_context(to_replace_bs);
3533 aio_context_acquire(replace_aio_context);
3534 replace_size = bdrv_getlength(to_replace_bs);
3535 aio_context_release(replace_aio_context);
3537 if (size != replace_size) {
3538 error_setg(errp, "cannot replace image with a mirror image of "
3539 "different size");
3540 goto out;
3544 if (arg->mode == NEW_IMAGE_MODE_ABSOLUTE_PATHS) {
3545 backing_mode = MIRROR_SOURCE_BACKING_CHAIN;
3546 } else {
3547 backing_mode = MIRROR_OPEN_BACKING_CHAIN;
3550 /* Don't open backing image in create() */
3551 flags |= BDRV_O_NO_BACKING;
3553 if ((arg->sync == MIRROR_SYNC_MODE_FULL || !source)
3554 && arg->mode != NEW_IMAGE_MODE_EXISTING)
3556 /* create new image w/o backing file */
3557 assert(format);
3558 bdrv_img_create(arg->target, format,
3559 NULL, NULL, NULL, size, flags, false, &local_err);
3560 } else {
3561 switch (arg->mode) {
3562 case NEW_IMAGE_MODE_EXISTING:
3563 break;
3564 case NEW_IMAGE_MODE_ABSOLUTE_PATHS:
3565 /* create new image with backing file */
3566 bdrv_img_create(arg->target, format,
3567 source->filename,
3568 source->drv->format_name,
3569 NULL, size, flags, false, &local_err);
3570 break;
3571 default:
3572 abort();
3576 if (local_err) {
3577 error_propagate(errp, local_err);
3578 goto out;
3581 options = qdict_new();
3582 if (arg->has_node_name) {
3583 qdict_put_str(options, "node-name", arg->node_name);
3585 if (format) {
3586 qdict_put_str(options, "driver", format);
3589 /* Mirroring takes care of copy-on-write using the source's backing
3590 * file.
3592 target_bs = bdrv_open(arg->target, NULL, options, flags, errp);
3593 if (!target_bs) {
3594 goto out;
3597 bdrv_set_aio_context(target_bs, aio_context);
3599 blockdev_mirror_common(arg->has_job_id ? arg->job_id : NULL, bs, target_bs,
3600 arg->has_replaces, arg->replaces, arg->sync,
3601 backing_mode, arg->has_speed, arg->speed,
3602 arg->has_granularity, arg->granularity,
3603 arg->has_buf_size, arg->buf_size,
3604 arg->has_on_source_error, arg->on_source_error,
3605 arg->has_on_target_error, arg->on_target_error,
3606 arg->has_unmap, arg->unmap,
3607 false, NULL,
3608 &local_err);
3609 bdrv_unref(target_bs);
3610 error_propagate(errp, local_err);
3611 out:
3612 aio_context_release(aio_context);
3615 void qmp_blockdev_mirror(bool has_job_id, const char *job_id,
3616 const char *device, const char *target,
3617 bool has_replaces, const char *replaces,
3618 MirrorSyncMode sync,
3619 bool has_speed, int64_t speed,
3620 bool has_granularity, uint32_t granularity,
3621 bool has_buf_size, int64_t buf_size,
3622 bool has_on_source_error,
3623 BlockdevOnError on_source_error,
3624 bool has_on_target_error,
3625 BlockdevOnError on_target_error,
3626 bool has_filter_node_name,
3627 const char *filter_node_name,
3628 Error **errp)
3630 BlockDriverState *bs;
3631 BlockDriverState *target_bs;
3632 AioContext *aio_context;
3633 BlockMirrorBackingMode backing_mode = MIRROR_LEAVE_BACKING_CHAIN;
3634 Error *local_err = NULL;
3636 bs = qmp_get_root_bs(device, errp);
3637 if (!bs) {
3638 return;
3641 target_bs = bdrv_lookup_bs(target, target, errp);
3642 if (!target_bs) {
3643 return;
3646 aio_context = bdrv_get_aio_context(bs);
3647 aio_context_acquire(aio_context);
3649 bdrv_set_aio_context(target_bs, aio_context);
3651 blockdev_mirror_common(has_job_id ? job_id : NULL, bs, target_bs,
3652 has_replaces, replaces, sync, backing_mode,
3653 has_speed, speed,
3654 has_granularity, granularity,
3655 has_buf_size, buf_size,
3656 has_on_source_error, on_source_error,
3657 has_on_target_error, on_target_error,
3658 true, true,
3659 has_filter_node_name, filter_node_name,
3660 &local_err);
3661 error_propagate(errp, local_err);
3663 aio_context_release(aio_context);
3666 /* Get a block job using its ID and acquire its AioContext */
3667 static BlockJob *find_block_job(const char *id, AioContext **aio_context,
3668 Error **errp)
3670 BlockJob *job;
3672 assert(id != NULL);
3674 *aio_context = NULL;
3676 job = block_job_get(id);
3678 if (!job) {
3679 error_set(errp, ERROR_CLASS_DEVICE_NOT_ACTIVE,
3680 "Block job '%s' not found", id);
3681 return NULL;
3684 *aio_context = blk_get_aio_context(job->blk);
3685 aio_context_acquire(*aio_context);
3687 return job;
3690 void qmp_block_job_set_speed(const char *device, int64_t speed, Error **errp)
3692 AioContext *aio_context;
3693 BlockJob *job = find_block_job(device, &aio_context, errp);
3695 if (!job) {
3696 return;
3699 block_job_set_speed(job, speed, errp);
3700 aio_context_release(aio_context);
3703 void qmp_block_job_cancel(const char *device,
3704 bool has_force, bool force, Error **errp)
3706 AioContext *aio_context;
3707 BlockJob *job = find_block_job(device, &aio_context, errp);
3709 if (!job) {
3710 return;
3713 if (!has_force) {
3714 force = false;
3717 if (block_job_user_paused(job) && !force) {
3718 error_setg(errp, "The block job for device '%s' is currently paused",
3719 device);
3720 goto out;
3723 trace_qmp_block_job_cancel(job);
3724 block_job_cancel(job);
3725 out:
3726 aio_context_release(aio_context);
3729 void qmp_block_job_pause(const char *device, Error **errp)
3731 AioContext *aio_context;
3732 BlockJob *job = find_block_job(device, &aio_context, errp);
3734 if (!job || block_job_user_paused(job)) {
3735 return;
3738 trace_qmp_block_job_pause(job);
3739 block_job_user_pause(job);
3740 aio_context_release(aio_context);
3743 void qmp_block_job_resume(const char *device, Error **errp)
3745 AioContext *aio_context;
3746 BlockJob *job = find_block_job(device, &aio_context, errp);
3748 if (!job || !block_job_user_paused(job)) {
3749 return;
3752 trace_qmp_block_job_resume(job);
3753 block_job_user_resume(job);
3754 aio_context_release(aio_context);
3757 void qmp_block_job_complete(const char *device, Error **errp)
3759 AioContext *aio_context;
3760 BlockJob *job = find_block_job(device, &aio_context, errp);
3762 if (!job) {
3763 return;
3766 trace_qmp_block_job_complete(job);
3767 block_job_complete(job, errp);
3768 aio_context_release(aio_context);
3771 void qmp_change_backing_file(const char *device,
3772 const char *image_node_name,
3773 const char *backing_file,
3774 Error **errp)
3776 BlockDriverState *bs = NULL;
3777 AioContext *aio_context;
3778 BlockDriverState *image_bs = NULL;
3779 Error *local_err = NULL;
3780 bool ro;
3781 int open_flags;
3782 int ret;
3784 bs = qmp_get_root_bs(device, errp);
3785 if (!bs) {
3786 return;
3789 aio_context = bdrv_get_aio_context(bs);
3790 aio_context_acquire(aio_context);
3792 image_bs = bdrv_lookup_bs(NULL, image_node_name, &local_err);
3793 if (local_err) {
3794 error_propagate(errp, local_err);
3795 goto out;
3798 if (!image_bs) {
3799 error_setg(errp, "image file not found");
3800 goto out;
3803 if (bdrv_find_base(image_bs) == image_bs) {
3804 error_setg(errp, "not allowing backing file change on an image "
3805 "without a backing file");
3806 goto out;
3809 /* even though we are not necessarily operating on bs, we need it to
3810 * determine if block ops are currently prohibited on the chain */
3811 if (bdrv_op_is_blocked(bs, BLOCK_OP_TYPE_CHANGE, errp)) {
3812 goto out;
3815 /* final sanity check */
3816 if (!bdrv_chain_contains(bs, image_bs)) {
3817 error_setg(errp, "'%s' and image file are not in the same chain",
3818 device);
3819 goto out;
3822 /* if not r/w, reopen to make r/w */
3823 open_flags = image_bs->open_flags;
3824 ro = bdrv_is_read_only(image_bs);
3826 if (ro) {
3827 bdrv_reopen(image_bs, open_flags | BDRV_O_RDWR, &local_err);
3828 if (local_err) {
3829 error_propagate(errp, local_err);
3830 goto out;
3834 ret = bdrv_change_backing_file(image_bs, backing_file,
3835 image_bs->drv ? image_bs->drv->format_name : "");
3837 if (ret < 0) {
3838 error_setg_errno(errp, -ret, "Could not change backing file to '%s'",
3839 backing_file);
3840 /* don't exit here, so we can try to restore open flags if
3841 * appropriate */
3844 if (ro) {
3845 bdrv_reopen(image_bs, open_flags, &local_err);
3846 error_propagate(errp, local_err);
3849 out:
3850 aio_context_release(aio_context);
3853 void hmp_drive_add_node(Monitor *mon, const char *optstr)
3855 QemuOpts *opts;
3856 QDict *qdict;
3857 Error *local_err = NULL;
3859 opts = qemu_opts_parse_noisily(&qemu_drive_opts, optstr, false);
3860 if (!opts) {
3861 return;
3864 qdict = qemu_opts_to_qdict(opts, NULL);
3866 if (!qdict_get_try_str(qdict, "node-name")) {
3867 QDECREF(qdict);
3868 error_report("'node-name' needs to be specified");
3869 goto out;
3872 BlockDriverState *bs = bds_tree_init(qdict, &local_err);
3873 if (!bs) {
3874 error_report_err(local_err);
3875 goto out;
3878 QTAILQ_INSERT_TAIL(&monitor_bdrv_states, bs, monitor_list);
3880 out:
3881 qemu_opts_del(opts);
3884 void qmp_blockdev_add(BlockdevOptions *options, Error **errp)
3886 BlockDriverState *bs;
3887 QObject *obj;
3888 Visitor *v = qobject_output_visitor_new(&obj);
3889 QDict *qdict;
3890 const QDictEntry *ent;
3891 Error *local_err = NULL;
3893 visit_type_BlockdevOptions(v, NULL, &options, &local_err);
3894 if (local_err) {
3895 error_propagate(errp, local_err);
3896 goto fail;
3899 visit_complete(v, &obj);
3900 qdict = qobject_to_qdict(obj);
3902 qdict_flatten(qdict);
3905 * Rewrite "backing": null to "backing": ""
3906 * TODO Rewrite "" to null instead, and perhaps not even here
3908 for (ent = qdict_first(qdict); ent; ent = qdict_next(qdict, ent)) {
3909 char *dot = strrchr(ent->key, '.');
3911 if (!strcmp(dot ? dot + 1 : ent->key, "backing")
3912 && qobject_type(ent->value) == QTYPE_QNULL) {
3913 qdict_put(qdict, ent->key, qstring_new());
3917 if (!qdict_get_try_str(qdict, "node-name")) {
3918 error_setg(errp, "'node-name' must be specified for the root node");
3919 goto fail;
3922 bs = bds_tree_init(qdict, errp);
3923 if (!bs) {
3924 goto fail;
3927 QTAILQ_INSERT_TAIL(&monitor_bdrv_states, bs, monitor_list);
3929 fail:
3930 visit_free(v);
3933 void qmp_blockdev_del(const char *node_name, Error **errp)
3935 AioContext *aio_context;
3936 BlockDriverState *bs;
3938 bs = bdrv_find_node(node_name);
3939 if (!bs) {
3940 error_setg(errp, "Cannot find node %s", node_name);
3941 return;
3943 if (bdrv_has_blk(bs)) {
3944 error_setg(errp, "Node %s is in use", node_name);
3945 return;
3947 aio_context = bdrv_get_aio_context(bs);
3948 aio_context_acquire(aio_context);
3950 if (bdrv_op_is_blocked(bs, BLOCK_OP_TYPE_DRIVE_DEL, errp)) {
3951 goto out;
3954 if (!bs->monitor_list.tqe_prev) {
3955 error_setg(errp, "Node %s is not owned by the monitor",
3956 bs->node_name);
3957 goto out;
3960 if (bs->refcnt > 1) {
3961 error_setg(errp, "Block device %s is in use",
3962 bdrv_get_device_or_node_name(bs));
3963 goto out;
3966 QTAILQ_REMOVE(&monitor_bdrv_states, bs, monitor_list);
3967 bdrv_unref(bs);
3969 out:
3970 aio_context_release(aio_context);
3973 static BdrvChild *bdrv_find_child(BlockDriverState *parent_bs,
3974 const char *child_name)
3976 BdrvChild *child;
3978 QLIST_FOREACH(child, &parent_bs->children, next) {
3979 if (strcmp(child->name, child_name) == 0) {
3980 return child;
3984 return NULL;
3987 void qmp_x_blockdev_change(const char *parent, bool has_child,
3988 const char *child, bool has_node,
3989 const char *node, Error **errp)
3991 BlockDriverState *parent_bs, *new_bs = NULL;
3992 BdrvChild *p_child;
3994 parent_bs = bdrv_lookup_bs(parent, parent, errp);
3995 if (!parent_bs) {
3996 return;
3999 if (has_child == has_node) {
4000 if (has_child) {
4001 error_setg(errp, "The parameters child and node are in conflict");
4002 } else {
4003 error_setg(errp, "Either child or node must be specified");
4005 return;
4008 if (has_child) {
4009 p_child = bdrv_find_child(parent_bs, child);
4010 if (!p_child) {
4011 error_setg(errp, "Node '%s' does not have child '%s'",
4012 parent, child);
4013 return;
4015 bdrv_del_child(parent_bs, p_child, errp);
4018 if (has_node) {
4019 new_bs = bdrv_find_node(node);
4020 if (!new_bs) {
4021 error_setg(errp, "Node '%s' not found", node);
4022 return;
4024 bdrv_add_child(parent_bs, new_bs, errp);
4028 BlockJobInfoList *qmp_query_block_jobs(Error **errp)
4030 BlockJobInfoList *head = NULL, **p_next = &head;
4031 BlockJob *job;
4033 for (job = block_job_next(NULL); job; job = block_job_next(job)) {
4034 BlockJobInfoList *elem;
4035 AioContext *aio_context;
4037 if (block_job_is_internal(job)) {
4038 continue;
4040 elem = g_new0(BlockJobInfoList, 1);
4041 aio_context = blk_get_aio_context(job->blk);
4042 aio_context_acquire(aio_context);
4043 elem->value = block_job_query(job, errp);
4044 aio_context_release(aio_context);
4045 if (!elem->value) {
4046 g_free(elem);
4047 qapi_free_BlockJobInfoList(head);
4048 return NULL;
4050 *p_next = elem;
4051 p_next = &elem->next;
4054 return head;
4057 QemuOptsList qemu_common_drive_opts = {
4058 .name = "drive",
4059 .head = QTAILQ_HEAD_INITIALIZER(qemu_common_drive_opts.head),
4060 .desc = {
4062 .name = "snapshot",
4063 .type = QEMU_OPT_BOOL,
4064 .help = "enable/disable snapshot mode",
4066 .name = "aio",
4067 .type = QEMU_OPT_STRING,
4068 .help = "host AIO implementation (threads, native)",
4070 .name = BDRV_OPT_CACHE_WB,
4071 .type = QEMU_OPT_BOOL,
4072 .help = "Enable writeback mode",
4074 .name = "format",
4075 .type = QEMU_OPT_STRING,
4076 .help = "disk format (raw, qcow2, ...)",
4078 .name = "rerror",
4079 .type = QEMU_OPT_STRING,
4080 .help = "read error action",
4082 .name = "werror",
4083 .type = QEMU_OPT_STRING,
4084 .help = "write error action",
4086 .name = BDRV_OPT_READ_ONLY,
4087 .type = QEMU_OPT_BOOL,
4088 .help = "open drive file as read-only",
4091 THROTTLE_OPTS,
4094 .name = "throttling.group",
4095 .type = QEMU_OPT_STRING,
4096 .help = "name of the block throttling group",
4098 .name = "copy-on-read",
4099 .type = QEMU_OPT_BOOL,
4100 .help = "copy read data from backing file into image file",
4102 .name = "detect-zeroes",
4103 .type = QEMU_OPT_STRING,
4104 .help = "try to optimize zero writes (off, on, unmap)",
4106 .name = "stats-account-invalid",
4107 .type = QEMU_OPT_BOOL,
4108 .help = "whether to account for invalid I/O operations "
4109 "in the statistics",
4111 .name = "stats-account-failed",
4112 .type = QEMU_OPT_BOOL,
4113 .help = "whether to account for failed I/O operations "
4114 "in the statistics",
4116 { /* end of list */ }
4120 QemuOptsList qemu_drive_opts = {
4121 .name = "drive",
4122 .head = QTAILQ_HEAD_INITIALIZER(qemu_drive_opts.head),
4123 .desc = {
4125 * no elements => accept any params
4126 * validation will happen later
4128 { /* end of list */ }