gdbstub: rename cpu_index -> cpu_gdb_index
[qemu/kevin.git] / blockdev.c
blob9c6dd270b7c4f27cddb91ab56d6877e9d7e94c5f
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 error_report("warning: 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_NO_BACKING | BDRV_O_COPY_ON_READ);
1715 /* create new image w/backing file */
1716 mode = s->has_mode ? s->mode : NEW_IMAGE_MODE_ABSOLUTE_PATHS;
1717 if (mode != NEW_IMAGE_MODE_EXISTING) {
1718 int64_t size = bdrv_getlength(state->old_bs);
1719 if (size < 0) {
1720 error_setg_errno(errp, -size, "bdrv_getlength failed");
1721 return;
1723 bdrv_img_create(new_image_file, format,
1724 state->old_bs->filename,
1725 state->old_bs->drv->format_name,
1726 NULL, size, flags, false, &local_err);
1727 if (local_err) {
1728 error_propagate(errp, local_err);
1729 return;
1733 options = qdict_new();
1734 if (s->has_snapshot_node_name) {
1735 qdict_put_str(options, "node-name", snapshot_node_name);
1737 qdict_put_str(options, "driver", format);
1739 flags |= BDRV_O_NO_BACKING;
1742 state->new_bs = bdrv_open(new_image_file, snapshot_ref, options, flags,
1743 errp);
1744 /* We will manually add the backing_hd field to the bs later */
1745 if (!state->new_bs) {
1746 return;
1749 if (bdrv_has_blk(state->new_bs)) {
1750 error_setg(errp, "The snapshot is already in use");
1751 return;
1754 if (bdrv_op_is_blocked(state->new_bs, BLOCK_OP_TYPE_EXTERNAL_SNAPSHOT,
1755 errp)) {
1756 return;
1759 if (state->new_bs->backing != NULL) {
1760 error_setg(errp, "The snapshot already has a backing image");
1761 return;
1764 if (!state->new_bs->drv->supports_backing) {
1765 error_setg(errp, "The snapshot does not support backing images");
1766 return;
1769 bdrv_set_aio_context(state->new_bs, state->aio_context);
1771 /* This removes our old bs and adds the new bs. This is an operation that
1772 * can fail, so we need to do it in .prepare; undoing it for abort is
1773 * always possible. */
1774 bdrv_ref(state->new_bs);
1775 bdrv_append(state->new_bs, state->old_bs, &local_err);
1776 if (local_err) {
1777 error_propagate(errp, local_err);
1778 return;
1780 state->overlay_appended = true;
1783 static void external_snapshot_commit(BlkActionState *common)
1785 ExternalSnapshotState *state =
1786 DO_UPCAST(ExternalSnapshotState, common, common);
1788 /* We don't need (or want) to use the transactional
1789 * bdrv_reopen_multiple() across all the entries at once, because we
1790 * don't want to abort all of them if one of them fails the reopen */
1791 if (!atomic_read(&state->old_bs->copy_on_read)) {
1792 bdrv_reopen(state->old_bs, state->old_bs->open_flags & ~BDRV_O_RDWR,
1793 NULL);
1797 static void external_snapshot_abort(BlkActionState *common)
1799 ExternalSnapshotState *state =
1800 DO_UPCAST(ExternalSnapshotState, common, common);
1801 if (state->new_bs) {
1802 if (state->overlay_appended) {
1803 bdrv_ref(state->old_bs); /* we can't let bdrv_set_backind_hd()
1804 close state->old_bs; we need it */
1805 bdrv_set_backing_hd(state->new_bs, NULL, &error_abort);
1806 bdrv_replace_node(state->new_bs, state->old_bs, &error_abort);
1807 bdrv_unref(state->old_bs); /* bdrv_replace_node() ref'ed old_bs */
1812 static void external_snapshot_clean(BlkActionState *common)
1814 ExternalSnapshotState *state =
1815 DO_UPCAST(ExternalSnapshotState, common, common);
1816 if (state->aio_context) {
1817 bdrv_drained_end(state->old_bs);
1818 aio_context_release(state->aio_context);
1819 bdrv_unref(state->new_bs);
1823 typedef struct DriveBackupState {
1824 BlkActionState common;
1825 BlockDriverState *bs;
1826 AioContext *aio_context;
1827 BlockJob *job;
1828 } DriveBackupState;
1830 static BlockJob *do_drive_backup(DriveBackup *backup, BlockJobTxn *txn,
1831 Error **errp);
1833 static void drive_backup_prepare(BlkActionState *common, Error **errp)
1835 DriveBackupState *state = DO_UPCAST(DriveBackupState, common, common);
1836 BlockDriverState *bs;
1837 DriveBackup *backup;
1838 Error *local_err = NULL;
1840 assert(common->action->type == TRANSACTION_ACTION_KIND_DRIVE_BACKUP);
1841 backup = common->action->u.drive_backup.data;
1843 bs = qmp_get_root_bs(backup->device, errp);
1844 if (!bs) {
1845 return;
1848 /* AioContext is released in .clean() */
1849 state->aio_context = bdrv_get_aio_context(bs);
1850 aio_context_acquire(state->aio_context);
1851 bdrv_drained_begin(bs);
1852 state->bs = bs;
1854 state->job = do_drive_backup(backup, common->block_job_txn, &local_err);
1855 if (local_err) {
1856 error_propagate(errp, local_err);
1857 return;
1861 static void drive_backup_commit(BlkActionState *common)
1863 DriveBackupState *state = DO_UPCAST(DriveBackupState, common, common);
1864 assert(state->job);
1865 block_job_start(state->job);
1868 static void drive_backup_abort(BlkActionState *common)
1870 DriveBackupState *state = DO_UPCAST(DriveBackupState, common, common);
1872 if (state->job) {
1873 block_job_cancel_sync(state->job);
1877 static void drive_backup_clean(BlkActionState *common)
1879 DriveBackupState *state = DO_UPCAST(DriveBackupState, common, common);
1881 if (state->aio_context) {
1882 bdrv_drained_end(state->bs);
1883 aio_context_release(state->aio_context);
1887 typedef struct BlockdevBackupState {
1888 BlkActionState common;
1889 BlockDriverState *bs;
1890 BlockJob *job;
1891 AioContext *aio_context;
1892 } BlockdevBackupState;
1894 static BlockJob *do_blockdev_backup(BlockdevBackup *backup, BlockJobTxn *txn,
1895 Error **errp);
1897 static void blockdev_backup_prepare(BlkActionState *common, Error **errp)
1899 BlockdevBackupState *state = DO_UPCAST(BlockdevBackupState, common, common);
1900 BlockdevBackup *backup;
1901 BlockDriverState *bs, *target;
1902 Error *local_err = NULL;
1904 assert(common->action->type == TRANSACTION_ACTION_KIND_BLOCKDEV_BACKUP);
1905 backup = common->action->u.blockdev_backup.data;
1907 bs = qmp_get_root_bs(backup->device, errp);
1908 if (!bs) {
1909 return;
1912 target = bdrv_lookup_bs(backup->target, backup->target, errp);
1913 if (!target) {
1914 return;
1917 /* AioContext is released in .clean() */
1918 state->aio_context = bdrv_get_aio_context(bs);
1919 if (state->aio_context != bdrv_get_aio_context(target)) {
1920 state->aio_context = NULL;
1921 error_setg(errp, "Backup between two IO threads is not implemented");
1922 return;
1924 aio_context_acquire(state->aio_context);
1925 state->bs = bs;
1926 bdrv_drained_begin(state->bs);
1928 state->job = do_blockdev_backup(backup, common->block_job_txn, &local_err);
1929 if (local_err) {
1930 error_propagate(errp, local_err);
1931 return;
1935 static void blockdev_backup_commit(BlkActionState *common)
1937 BlockdevBackupState *state = DO_UPCAST(BlockdevBackupState, common, common);
1938 assert(state->job);
1939 block_job_start(state->job);
1942 static void blockdev_backup_abort(BlkActionState *common)
1944 BlockdevBackupState *state = DO_UPCAST(BlockdevBackupState, common, common);
1946 if (state->job) {
1947 block_job_cancel_sync(state->job);
1951 static void blockdev_backup_clean(BlkActionState *common)
1953 BlockdevBackupState *state = DO_UPCAST(BlockdevBackupState, common, common);
1955 if (state->aio_context) {
1956 bdrv_drained_end(state->bs);
1957 aio_context_release(state->aio_context);
1961 typedef struct BlockDirtyBitmapState {
1962 BlkActionState common;
1963 BdrvDirtyBitmap *bitmap;
1964 BlockDriverState *bs;
1965 AioContext *aio_context;
1966 HBitmap *backup;
1967 bool prepared;
1968 } BlockDirtyBitmapState;
1970 static void block_dirty_bitmap_add_prepare(BlkActionState *common,
1971 Error **errp)
1973 Error *local_err = NULL;
1974 BlockDirtyBitmapAdd *action;
1975 BlockDirtyBitmapState *state = DO_UPCAST(BlockDirtyBitmapState,
1976 common, common);
1978 if (action_check_completion_mode(common, errp) < 0) {
1979 return;
1982 action = common->action->u.block_dirty_bitmap_add.data;
1983 /* AIO context taken and released within qmp_block_dirty_bitmap_add */
1984 qmp_block_dirty_bitmap_add(action->node, action->name,
1985 action->has_granularity, action->granularity,
1986 action->has_persistent, action->persistent,
1987 action->has_autoload, action->autoload,
1988 &local_err);
1990 if (!local_err) {
1991 state->prepared = true;
1992 } else {
1993 error_propagate(errp, local_err);
1997 static void block_dirty_bitmap_add_abort(BlkActionState *common)
1999 BlockDirtyBitmapAdd *action;
2000 BlockDirtyBitmapState *state = DO_UPCAST(BlockDirtyBitmapState,
2001 common, common);
2003 action = common->action->u.block_dirty_bitmap_add.data;
2004 /* Should not be able to fail: IF the bitmap was added via .prepare(),
2005 * then the node reference and bitmap name must have been valid.
2007 if (state->prepared) {
2008 qmp_block_dirty_bitmap_remove(action->node, action->name, &error_abort);
2012 static void block_dirty_bitmap_clear_prepare(BlkActionState *common,
2013 Error **errp)
2015 BlockDirtyBitmapState *state = DO_UPCAST(BlockDirtyBitmapState,
2016 common, common);
2017 BlockDirtyBitmap *action;
2019 if (action_check_completion_mode(common, errp) < 0) {
2020 return;
2023 action = common->action->u.block_dirty_bitmap_clear.data;
2024 state->bitmap = block_dirty_bitmap_lookup(action->node,
2025 action->name,
2026 &state->bs,
2027 errp);
2028 if (!state->bitmap) {
2029 return;
2032 if (bdrv_dirty_bitmap_frozen(state->bitmap)) {
2033 error_setg(errp, "Cannot modify a frozen bitmap");
2034 return;
2035 } else if (!bdrv_dirty_bitmap_enabled(state->bitmap)) {
2036 error_setg(errp, "Cannot clear a disabled bitmap");
2037 return;
2038 } else if (bdrv_dirty_bitmap_readonly(state->bitmap)) {
2039 error_setg(errp, "Cannot clear a readonly bitmap");
2040 return;
2043 bdrv_clear_dirty_bitmap(state->bitmap, &state->backup);
2044 /* AioContext is released in .clean() */
2047 static void block_dirty_bitmap_clear_abort(BlkActionState *common)
2049 BlockDirtyBitmapState *state = DO_UPCAST(BlockDirtyBitmapState,
2050 common, common);
2052 if (state->backup) {
2053 bdrv_undo_clear_dirty_bitmap(state->bitmap, state->backup);
2057 static void block_dirty_bitmap_clear_commit(BlkActionState *common)
2059 BlockDirtyBitmapState *state = DO_UPCAST(BlockDirtyBitmapState,
2060 common, common);
2062 hbitmap_free(state->backup);
2065 static void block_dirty_bitmap_clear_clean(BlkActionState *common)
2067 BlockDirtyBitmapState *state = DO_UPCAST(BlockDirtyBitmapState,
2068 common, common);
2070 if (state->aio_context) {
2071 aio_context_release(state->aio_context);
2075 static void abort_prepare(BlkActionState *common, Error **errp)
2077 error_setg(errp, "Transaction aborted using Abort action");
2080 static void abort_commit(BlkActionState *common)
2082 g_assert_not_reached(); /* this action never succeeds */
2085 static const BlkActionOps actions[] = {
2086 [TRANSACTION_ACTION_KIND_BLOCKDEV_SNAPSHOT] = {
2087 .instance_size = sizeof(ExternalSnapshotState),
2088 .prepare = external_snapshot_prepare,
2089 .commit = external_snapshot_commit,
2090 .abort = external_snapshot_abort,
2091 .clean = external_snapshot_clean,
2093 [TRANSACTION_ACTION_KIND_BLOCKDEV_SNAPSHOT_SYNC] = {
2094 .instance_size = sizeof(ExternalSnapshotState),
2095 .prepare = external_snapshot_prepare,
2096 .commit = external_snapshot_commit,
2097 .abort = external_snapshot_abort,
2098 .clean = external_snapshot_clean,
2100 [TRANSACTION_ACTION_KIND_DRIVE_BACKUP] = {
2101 .instance_size = sizeof(DriveBackupState),
2102 .prepare = drive_backup_prepare,
2103 .commit = drive_backup_commit,
2104 .abort = drive_backup_abort,
2105 .clean = drive_backup_clean,
2107 [TRANSACTION_ACTION_KIND_BLOCKDEV_BACKUP] = {
2108 .instance_size = sizeof(BlockdevBackupState),
2109 .prepare = blockdev_backup_prepare,
2110 .commit = blockdev_backup_commit,
2111 .abort = blockdev_backup_abort,
2112 .clean = blockdev_backup_clean,
2114 [TRANSACTION_ACTION_KIND_ABORT] = {
2115 .instance_size = sizeof(BlkActionState),
2116 .prepare = abort_prepare,
2117 .commit = abort_commit,
2119 [TRANSACTION_ACTION_KIND_BLOCKDEV_SNAPSHOT_INTERNAL_SYNC] = {
2120 .instance_size = sizeof(InternalSnapshotState),
2121 .prepare = internal_snapshot_prepare,
2122 .abort = internal_snapshot_abort,
2123 .clean = internal_snapshot_clean,
2125 [TRANSACTION_ACTION_KIND_BLOCK_DIRTY_BITMAP_ADD] = {
2126 .instance_size = sizeof(BlockDirtyBitmapState),
2127 .prepare = block_dirty_bitmap_add_prepare,
2128 .abort = block_dirty_bitmap_add_abort,
2130 [TRANSACTION_ACTION_KIND_BLOCK_DIRTY_BITMAP_CLEAR] = {
2131 .instance_size = sizeof(BlockDirtyBitmapState),
2132 .prepare = block_dirty_bitmap_clear_prepare,
2133 .commit = block_dirty_bitmap_clear_commit,
2134 .abort = block_dirty_bitmap_clear_abort,
2135 .clean = block_dirty_bitmap_clear_clean,
2140 * Allocate a TransactionProperties structure if necessary, and fill
2141 * that structure with desired defaults if they are unset.
2143 static TransactionProperties *get_transaction_properties(
2144 TransactionProperties *props)
2146 if (!props) {
2147 props = g_new0(TransactionProperties, 1);
2150 if (!props->has_completion_mode) {
2151 props->has_completion_mode = true;
2152 props->completion_mode = ACTION_COMPLETION_MODE_INDIVIDUAL;
2155 return props;
2159 * 'Atomic' group operations. The operations are performed as a set, and if
2160 * any fail then we roll back all operations in the group.
2162 void qmp_transaction(TransactionActionList *dev_list,
2163 bool has_props,
2164 struct TransactionProperties *props,
2165 Error **errp)
2167 TransactionActionList *dev_entry = dev_list;
2168 BlockJobTxn *block_job_txn = NULL;
2169 BlkActionState *state, *next;
2170 Error *local_err = NULL;
2172 QSIMPLEQ_HEAD(snap_bdrv_states, BlkActionState) snap_bdrv_states;
2173 QSIMPLEQ_INIT(&snap_bdrv_states);
2175 /* Does this transaction get canceled as a group on failure?
2176 * If not, we don't really need to make a BlockJobTxn.
2178 props = get_transaction_properties(props);
2179 if (props->completion_mode != ACTION_COMPLETION_MODE_INDIVIDUAL) {
2180 block_job_txn = block_job_txn_new();
2183 /* drain all i/o before any operations */
2184 bdrv_drain_all();
2186 /* We don't do anything in this loop that commits us to the operations */
2187 while (NULL != dev_entry) {
2188 TransactionAction *dev_info = NULL;
2189 const BlkActionOps *ops;
2191 dev_info = dev_entry->value;
2192 dev_entry = dev_entry->next;
2194 assert(dev_info->type < ARRAY_SIZE(actions));
2196 ops = &actions[dev_info->type];
2197 assert(ops->instance_size > 0);
2199 state = g_malloc0(ops->instance_size);
2200 state->ops = ops;
2201 state->action = dev_info;
2202 state->block_job_txn = block_job_txn;
2203 state->txn_props = props;
2204 QSIMPLEQ_INSERT_TAIL(&snap_bdrv_states, state, entry);
2206 state->ops->prepare(state, &local_err);
2207 if (local_err) {
2208 error_propagate(errp, local_err);
2209 goto delete_and_fail;
2213 QSIMPLEQ_FOREACH(state, &snap_bdrv_states, entry) {
2214 if (state->ops->commit) {
2215 state->ops->commit(state);
2219 /* success */
2220 goto exit;
2222 delete_and_fail:
2223 /* failure, and it is all-or-none; roll back all operations */
2224 QSIMPLEQ_FOREACH(state, &snap_bdrv_states, entry) {
2225 if (state->ops->abort) {
2226 state->ops->abort(state);
2229 exit:
2230 QSIMPLEQ_FOREACH_SAFE(state, &snap_bdrv_states, entry, next) {
2231 if (state->ops->clean) {
2232 state->ops->clean(state);
2234 g_free(state);
2236 if (!has_props) {
2237 qapi_free_TransactionProperties(props);
2239 block_job_txn_unref(block_job_txn);
2242 void qmp_eject(bool has_device, const char *device,
2243 bool has_id, const char *id,
2244 bool has_force, bool force, Error **errp)
2246 Error *local_err = NULL;
2247 int rc;
2249 if (!has_force) {
2250 force = false;
2253 rc = do_open_tray(has_device ? device : NULL,
2254 has_id ? id : NULL,
2255 force, &local_err);
2256 if (rc && rc != -ENOSYS) {
2257 error_propagate(errp, local_err);
2258 return;
2260 error_free(local_err);
2262 qmp_x_blockdev_remove_medium(has_device, device, has_id, id, errp);
2265 void qmp_block_passwd(bool has_device, const char *device,
2266 bool has_node_name, const char *node_name,
2267 const char *password, Error **errp)
2269 error_setg(errp,
2270 "Setting block passwords directly is no longer supported");
2274 * Attempt to open the tray of @device.
2275 * If @force, ignore its tray lock.
2276 * Else, if the tray is locked, don't open it, but ask the guest to open it.
2277 * On error, store an error through @errp and return -errno.
2278 * If @device does not exist, return -ENODEV.
2279 * If it has no removable media, return -ENOTSUP.
2280 * If it has no tray, return -ENOSYS.
2281 * If the guest was asked to open the tray, return -EINPROGRESS.
2282 * Else, return 0.
2284 static int do_open_tray(const char *blk_name, const char *qdev_id,
2285 bool force, Error **errp)
2287 BlockBackend *blk;
2288 const char *device = qdev_id ?: blk_name;
2289 bool locked;
2291 blk = qmp_get_blk(blk_name, qdev_id, errp);
2292 if (!blk) {
2293 return -ENODEV;
2296 if (!blk_dev_has_removable_media(blk)) {
2297 error_setg(errp, "Device '%s' is not removable", device);
2298 return -ENOTSUP;
2301 if (!blk_dev_has_tray(blk)) {
2302 error_setg(errp, "Device '%s' does not have a tray", device);
2303 return -ENOSYS;
2306 if (blk_dev_is_tray_open(blk)) {
2307 return 0;
2310 locked = blk_dev_is_medium_locked(blk);
2311 if (locked) {
2312 blk_dev_eject_request(blk, force);
2315 if (!locked || force) {
2316 blk_dev_change_media_cb(blk, false, &error_abort);
2319 if (locked && !force) {
2320 error_setg(errp, "Device '%s' is locked and force was not specified, "
2321 "wait for tray to open and try again", device);
2322 return -EINPROGRESS;
2325 return 0;
2328 void qmp_blockdev_open_tray(bool has_device, const char *device,
2329 bool has_id, const char *id,
2330 bool has_force, bool force,
2331 Error **errp)
2333 Error *local_err = NULL;
2334 int rc;
2336 if (!has_force) {
2337 force = false;
2339 rc = do_open_tray(has_device ? device : NULL,
2340 has_id ? id : NULL,
2341 force, &local_err);
2342 if (rc && rc != -ENOSYS && rc != -EINPROGRESS) {
2343 error_propagate(errp, local_err);
2344 return;
2346 error_free(local_err);
2349 void qmp_blockdev_close_tray(bool has_device, const char *device,
2350 bool has_id, const char *id,
2351 Error **errp)
2353 BlockBackend *blk;
2354 Error *local_err = NULL;
2356 device = has_device ? device : NULL;
2357 id = has_id ? id : NULL;
2359 blk = qmp_get_blk(device, id, errp);
2360 if (!blk) {
2361 return;
2364 if (!blk_dev_has_removable_media(blk)) {
2365 error_setg(errp, "Device '%s' is not removable", device ?: id);
2366 return;
2369 if (!blk_dev_has_tray(blk)) {
2370 /* Ignore this command on tray-less devices */
2371 return;
2374 if (!blk_dev_is_tray_open(blk)) {
2375 return;
2378 blk_dev_change_media_cb(blk, true, &local_err);
2379 if (local_err) {
2380 error_propagate(errp, local_err);
2381 return;
2385 void qmp_x_blockdev_remove_medium(bool has_device, const char *device,
2386 bool has_id, const char *id, Error **errp)
2388 BlockBackend *blk;
2389 BlockDriverState *bs;
2390 AioContext *aio_context;
2391 bool has_attached_device;
2393 device = has_device ? device : NULL;
2394 id = has_id ? id : NULL;
2396 blk = qmp_get_blk(device, id, errp);
2397 if (!blk) {
2398 return;
2401 /* For BBs without a device, we can exchange the BDS tree at will */
2402 has_attached_device = blk_get_attached_dev(blk);
2404 if (has_attached_device && !blk_dev_has_removable_media(blk)) {
2405 error_setg(errp, "Device '%s' is not removable", device ?: id);
2406 return;
2409 if (has_attached_device && blk_dev_has_tray(blk) &&
2410 !blk_dev_is_tray_open(blk))
2412 error_setg(errp, "Tray of device '%s' is not open", device ?: id);
2413 return;
2416 bs = blk_bs(blk);
2417 if (!bs) {
2418 return;
2421 aio_context = bdrv_get_aio_context(bs);
2422 aio_context_acquire(aio_context);
2424 if (bdrv_op_is_blocked(bs, BLOCK_OP_TYPE_EJECT, errp)) {
2425 goto out;
2428 blk_remove_bs(blk);
2430 if (!blk_dev_has_tray(blk)) {
2431 /* For tray-less devices, blockdev-open-tray is a no-op (or may not be
2432 * called at all); therefore, the medium needs to be ejected here.
2433 * Do it after blk_remove_bs() so blk_is_inserted(blk) returns the @load
2434 * value passed here (i.e. false). */
2435 blk_dev_change_media_cb(blk, false, &error_abort);
2438 out:
2439 aio_context_release(aio_context);
2442 static void qmp_blockdev_insert_anon_medium(BlockBackend *blk,
2443 BlockDriverState *bs, Error **errp)
2445 Error *local_err = NULL;
2446 bool has_device;
2447 int ret;
2449 /* For BBs without a device, we can exchange the BDS tree at will */
2450 has_device = blk_get_attached_dev(blk);
2452 if (has_device && !blk_dev_has_removable_media(blk)) {
2453 error_setg(errp, "Device is not removable");
2454 return;
2457 if (has_device && blk_dev_has_tray(blk) && !blk_dev_is_tray_open(blk)) {
2458 error_setg(errp, "Tray of the device is not open");
2459 return;
2462 if (blk_bs(blk)) {
2463 error_setg(errp, "There already is a medium in the device");
2464 return;
2467 ret = blk_insert_bs(blk, bs, errp);
2468 if (ret < 0) {
2469 return;
2472 if (!blk_dev_has_tray(blk)) {
2473 /* For tray-less devices, blockdev-close-tray is a no-op (or may not be
2474 * called at all); therefore, the medium needs to be pushed into the
2475 * slot here.
2476 * Do it after blk_insert_bs() so blk_is_inserted(blk) returns the @load
2477 * value passed here (i.e. true). */
2478 blk_dev_change_media_cb(blk, true, &local_err);
2479 if (local_err) {
2480 error_propagate(errp, local_err);
2481 blk_remove_bs(blk);
2482 return;
2487 void qmp_x_blockdev_insert_medium(bool has_device, const char *device,
2488 bool has_id, const char *id,
2489 const char *node_name, Error **errp)
2491 BlockBackend *blk;
2492 BlockDriverState *bs;
2494 blk = qmp_get_blk(has_device ? device : NULL,
2495 has_id ? id : NULL,
2496 errp);
2497 if (!blk) {
2498 return;
2501 bs = bdrv_find_node(node_name);
2502 if (!bs) {
2503 error_setg(errp, "Node '%s' not found", node_name);
2504 return;
2507 if (bdrv_has_blk(bs)) {
2508 error_setg(errp, "Node '%s' is already in use", node_name);
2509 return;
2512 qmp_blockdev_insert_anon_medium(blk, bs, errp);
2515 void qmp_blockdev_change_medium(bool has_device, const char *device,
2516 bool has_id, const char *id,
2517 const char *filename,
2518 bool has_format, const char *format,
2519 bool has_read_only,
2520 BlockdevChangeReadOnlyMode read_only,
2521 Error **errp)
2523 BlockBackend *blk;
2524 BlockDriverState *medium_bs = NULL;
2525 int bdrv_flags;
2526 bool detect_zeroes;
2527 int rc;
2528 QDict *options = NULL;
2529 Error *err = NULL;
2531 blk = qmp_get_blk(has_device ? device : NULL,
2532 has_id ? id : NULL,
2533 errp);
2534 if (!blk) {
2535 goto fail;
2538 if (blk_bs(blk)) {
2539 blk_update_root_state(blk);
2542 bdrv_flags = blk_get_open_flags_from_root_state(blk);
2543 bdrv_flags &= ~(BDRV_O_TEMPORARY | BDRV_O_SNAPSHOT | BDRV_O_NO_BACKING |
2544 BDRV_O_PROTOCOL);
2546 if (!has_read_only) {
2547 read_only = BLOCKDEV_CHANGE_READ_ONLY_MODE_RETAIN;
2550 switch (read_only) {
2551 case BLOCKDEV_CHANGE_READ_ONLY_MODE_RETAIN:
2552 break;
2554 case BLOCKDEV_CHANGE_READ_ONLY_MODE_READ_ONLY:
2555 bdrv_flags &= ~BDRV_O_RDWR;
2556 break;
2558 case BLOCKDEV_CHANGE_READ_ONLY_MODE_READ_WRITE:
2559 bdrv_flags |= BDRV_O_RDWR;
2560 break;
2562 default:
2563 abort();
2566 options = qdict_new();
2567 detect_zeroes = blk_get_detect_zeroes_from_root_state(blk);
2568 qdict_put_str(options, "detect-zeroes", detect_zeroes ? "on" : "off");
2570 if (has_format) {
2571 qdict_put_str(options, "driver", format);
2574 medium_bs = bdrv_open(filename, NULL, options, bdrv_flags, errp);
2575 if (!medium_bs) {
2576 goto fail;
2579 rc = do_open_tray(has_device ? device : NULL,
2580 has_id ? id : NULL,
2581 false, &err);
2582 if (rc && rc != -ENOSYS) {
2583 error_propagate(errp, err);
2584 goto fail;
2586 error_free(err);
2587 err = NULL;
2589 qmp_x_blockdev_remove_medium(has_device, device, has_id, id, &err);
2590 if (err) {
2591 error_propagate(errp, err);
2592 goto fail;
2595 qmp_blockdev_insert_anon_medium(blk, medium_bs, &err);
2596 if (err) {
2597 error_propagate(errp, err);
2598 goto fail;
2601 qmp_blockdev_close_tray(has_device, device, has_id, id, errp);
2603 fail:
2604 /* If the medium has been inserted, the device has its own reference, so
2605 * ours must be relinquished; and if it has not been inserted successfully,
2606 * the reference must be relinquished anyway */
2607 bdrv_unref(medium_bs);
2610 /* throttling disk I/O limits */
2611 void qmp_block_set_io_throttle(BlockIOThrottle *arg, Error **errp)
2613 ThrottleConfig cfg;
2614 BlockDriverState *bs;
2615 BlockBackend *blk;
2616 AioContext *aio_context;
2618 blk = qmp_get_blk(arg->has_device ? arg->device : NULL,
2619 arg->has_id ? arg->id : NULL,
2620 errp);
2621 if (!blk) {
2622 return;
2625 aio_context = blk_get_aio_context(blk);
2626 aio_context_acquire(aio_context);
2628 bs = blk_bs(blk);
2629 if (!bs) {
2630 error_setg(errp, "Device has no medium");
2631 goto out;
2634 throttle_config_init(&cfg);
2635 cfg.buckets[THROTTLE_BPS_TOTAL].avg = arg->bps;
2636 cfg.buckets[THROTTLE_BPS_READ].avg = arg->bps_rd;
2637 cfg.buckets[THROTTLE_BPS_WRITE].avg = arg->bps_wr;
2639 cfg.buckets[THROTTLE_OPS_TOTAL].avg = arg->iops;
2640 cfg.buckets[THROTTLE_OPS_READ].avg = arg->iops_rd;
2641 cfg.buckets[THROTTLE_OPS_WRITE].avg = arg->iops_wr;
2643 if (arg->has_bps_max) {
2644 cfg.buckets[THROTTLE_BPS_TOTAL].max = arg->bps_max;
2646 if (arg->has_bps_rd_max) {
2647 cfg.buckets[THROTTLE_BPS_READ].max = arg->bps_rd_max;
2649 if (arg->has_bps_wr_max) {
2650 cfg.buckets[THROTTLE_BPS_WRITE].max = arg->bps_wr_max;
2652 if (arg->has_iops_max) {
2653 cfg.buckets[THROTTLE_OPS_TOTAL].max = arg->iops_max;
2655 if (arg->has_iops_rd_max) {
2656 cfg.buckets[THROTTLE_OPS_READ].max = arg->iops_rd_max;
2658 if (arg->has_iops_wr_max) {
2659 cfg.buckets[THROTTLE_OPS_WRITE].max = arg->iops_wr_max;
2662 if (arg->has_bps_max_length) {
2663 cfg.buckets[THROTTLE_BPS_TOTAL].burst_length = arg->bps_max_length;
2665 if (arg->has_bps_rd_max_length) {
2666 cfg.buckets[THROTTLE_BPS_READ].burst_length = arg->bps_rd_max_length;
2668 if (arg->has_bps_wr_max_length) {
2669 cfg.buckets[THROTTLE_BPS_WRITE].burst_length = arg->bps_wr_max_length;
2671 if (arg->has_iops_max_length) {
2672 cfg.buckets[THROTTLE_OPS_TOTAL].burst_length = arg->iops_max_length;
2674 if (arg->has_iops_rd_max_length) {
2675 cfg.buckets[THROTTLE_OPS_READ].burst_length = arg->iops_rd_max_length;
2677 if (arg->has_iops_wr_max_length) {
2678 cfg.buckets[THROTTLE_OPS_WRITE].burst_length = arg->iops_wr_max_length;
2681 if (arg->has_iops_size) {
2682 cfg.op_size = arg->iops_size;
2685 if (!throttle_is_valid(&cfg, errp)) {
2686 goto out;
2689 if (throttle_enabled(&cfg)) {
2690 /* Enable I/O limits if they're not enabled yet, otherwise
2691 * just update the throttling group. */
2692 if (!blk_get_public(blk)->throttle_state) {
2693 blk_io_limits_enable(blk,
2694 arg->has_group ? arg->group :
2695 arg->has_device ? arg->device :
2696 arg->id);
2697 } else if (arg->has_group) {
2698 blk_io_limits_update_group(blk, arg->group);
2700 /* Set the new throttling configuration */
2701 blk_set_io_limits(blk, &cfg);
2702 } else if (blk_get_public(blk)->throttle_state) {
2703 /* If all throttling settings are set to 0, disable I/O limits */
2704 blk_io_limits_disable(blk);
2707 out:
2708 aio_context_release(aio_context);
2711 void qmp_block_dirty_bitmap_add(const char *node, const char *name,
2712 bool has_granularity, uint32_t granularity,
2713 bool has_persistent, bool persistent,
2714 bool has_autoload, bool autoload,
2715 Error **errp)
2717 BlockDriverState *bs;
2718 BdrvDirtyBitmap *bitmap;
2720 if (!name || name[0] == '\0') {
2721 error_setg(errp, "Bitmap name cannot be empty");
2722 return;
2725 bs = bdrv_lookup_bs(node, node, errp);
2726 if (!bs) {
2727 return;
2730 if (has_granularity) {
2731 if (granularity < 512 || !is_power_of_2(granularity)) {
2732 error_setg(errp, "Granularity must be power of 2 "
2733 "and at least 512");
2734 return;
2736 } else {
2737 /* Default to cluster size, if available: */
2738 granularity = bdrv_get_default_bitmap_granularity(bs);
2741 if (!has_persistent) {
2742 persistent = false;
2744 if (!has_autoload) {
2745 autoload = false;
2748 if (has_autoload && !persistent) {
2749 error_setg(errp, "Autoload flag must be used only for persistent "
2750 "bitmaps");
2751 return;
2754 if (persistent &&
2755 !bdrv_can_store_new_dirty_bitmap(bs, name, granularity, errp))
2757 return;
2760 bitmap = bdrv_create_dirty_bitmap(bs, granularity, name, errp);
2761 if (bitmap == NULL) {
2762 return;
2765 bdrv_dirty_bitmap_set_persistance(bitmap, persistent);
2766 bdrv_dirty_bitmap_set_autoload(bitmap, autoload);
2769 void qmp_block_dirty_bitmap_remove(const char *node, const char *name,
2770 Error **errp)
2772 BlockDriverState *bs;
2773 BdrvDirtyBitmap *bitmap;
2774 Error *local_err = NULL;
2776 bitmap = block_dirty_bitmap_lookup(node, name, &bs, errp);
2777 if (!bitmap || !bs) {
2778 return;
2781 if (bdrv_dirty_bitmap_frozen(bitmap)) {
2782 error_setg(errp,
2783 "Bitmap '%s' is currently frozen and cannot be removed",
2784 name);
2785 return;
2788 if (bdrv_dirty_bitmap_get_persistance(bitmap)) {
2789 bdrv_remove_persistent_dirty_bitmap(bs, name, &local_err);
2790 if (local_err != NULL) {
2791 error_propagate(errp, local_err);
2792 return;
2796 bdrv_dirty_bitmap_make_anon(bitmap);
2797 bdrv_release_dirty_bitmap(bs, bitmap);
2801 * Completely clear a bitmap, for the purposes of synchronizing a bitmap
2802 * immediately after a full backup operation.
2804 void qmp_block_dirty_bitmap_clear(const char *node, const char *name,
2805 Error **errp)
2807 BdrvDirtyBitmap *bitmap;
2808 BlockDriverState *bs;
2810 bitmap = block_dirty_bitmap_lookup(node, name, &bs, errp);
2811 if (!bitmap || !bs) {
2812 return;
2815 if (bdrv_dirty_bitmap_frozen(bitmap)) {
2816 error_setg(errp,
2817 "Bitmap '%s' is currently frozen and cannot be modified",
2818 name);
2819 return;
2820 } else if (!bdrv_dirty_bitmap_enabled(bitmap)) {
2821 error_setg(errp,
2822 "Bitmap '%s' is currently disabled and cannot be cleared",
2823 name);
2824 return;
2825 } else if (bdrv_dirty_bitmap_readonly(bitmap)) {
2826 error_setg(errp, "Bitmap '%s' is readonly and cannot be cleared", name);
2827 return;
2830 bdrv_clear_dirty_bitmap(bitmap, NULL);
2833 BlockDirtyBitmapSha256 *qmp_x_debug_block_dirty_bitmap_sha256(const char *node,
2834 const char *name,
2835 Error **errp)
2837 BdrvDirtyBitmap *bitmap;
2838 BlockDriverState *bs;
2839 BlockDirtyBitmapSha256 *ret = NULL;
2840 char *sha256;
2842 bitmap = block_dirty_bitmap_lookup(node, name, &bs, errp);
2843 if (!bitmap || !bs) {
2844 return NULL;
2847 sha256 = bdrv_dirty_bitmap_sha256(bitmap, errp);
2848 if (sha256 == NULL) {
2849 return NULL;
2852 ret = g_new(BlockDirtyBitmapSha256, 1);
2853 ret->sha256 = sha256;
2855 return ret;
2858 void hmp_drive_del(Monitor *mon, const QDict *qdict)
2860 const char *id = qdict_get_str(qdict, "id");
2861 BlockBackend *blk;
2862 BlockDriverState *bs;
2863 AioContext *aio_context;
2864 Error *local_err = NULL;
2866 bs = bdrv_find_node(id);
2867 if (bs) {
2868 qmp_blockdev_del(id, &local_err);
2869 if (local_err) {
2870 error_report_err(local_err);
2872 return;
2875 blk = blk_by_name(id);
2876 if (!blk) {
2877 error_report("Device '%s' not found", id);
2878 return;
2881 if (!blk_legacy_dinfo(blk)) {
2882 error_report("Deleting device added with blockdev-add"
2883 " is not supported");
2884 return;
2887 aio_context = blk_get_aio_context(blk);
2888 aio_context_acquire(aio_context);
2890 bs = blk_bs(blk);
2891 if (bs) {
2892 if (bdrv_op_is_blocked(bs, BLOCK_OP_TYPE_DRIVE_DEL, &local_err)) {
2893 error_report_err(local_err);
2894 aio_context_release(aio_context);
2895 return;
2898 blk_remove_bs(blk);
2901 /* Make the BlockBackend and the attached BlockDriverState anonymous */
2902 monitor_remove_blk(blk);
2904 /* If this BlockBackend has a device attached to it, its refcount will be
2905 * decremented when the device is removed; otherwise we have to do so here.
2907 if (blk_get_attached_dev(blk)) {
2908 /* Further I/O must not pause the guest */
2909 blk_set_on_error(blk, BLOCKDEV_ON_ERROR_REPORT,
2910 BLOCKDEV_ON_ERROR_REPORT);
2911 } else {
2912 blk_unref(blk);
2915 aio_context_release(aio_context);
2918 void qmp_block_resize(bool has_device, const char *device,
2919 bool has_node_name, const char *node_name,
2920 int64_t size, Error **errp)
2922 Error *local_err = NULL;
2923 BlockBackend *blk = NULL;
2924 BlockDriverState *bs;
2925 AioContext *aio_context;
2926 int ret;
2928 bs = bdrv_lookup_bs(has_device ? device : NULL,
2929 has_node_name ? node_name : NULL,
2930 &local_err);
2931 if (local_err) {
2932 error_propagate(errp, local_err);
2933 return;
2936 aio_context = bdrv_get_aio_context(bs);
2937 aio_context_acquire(aio_context);
2939 if (!bdrv_is_first_non_filter(bs)) {
2940 error_setg(errp, QERR_FEATURE_DISABLED, "resize");
2941 goto out;
2944 if (size < 0) {
2945 error_setg(errp, QERR_INVALID_PARAMETER_VALUE, "size", "a >0 size");
2946 goto out;
2949 if (bdrv_op_is_blocked(bs, BLOCK_OP_TYPE_RESIZE, NULL)) {
2950 error_setg(errp, QERR_DEVICE_IN_USE, device);
2951 goto out;
2954 blk = blk_new(BLK_PERM_RESIZE, BLK_PERM_ALL);
2955 ret = blk_insert_bs(blk, bs, errp);
2956 if (ret < 0) {
2957 goto out;
2960 bdrv_drained_begin(bs);
2961 ret = blk_truncate(blk, size, PREALLOC_MODE_OFF, errp);
2962 bdrv_drained_end(bs);
2964 out:
2965 blk_unref(blk);
2966 aio_context_release(aio_context);
2969 void qmp_block_stream(bool has_job_id, const char *job_id, const char *device,
2970 bool has_base, const char *base,
2971 bool has_base_node, const char *base_node,
2972 bool has_backing_file, const char *backing_file,
2973 bool has_speed, int64_t speed,
2974 bool has_on_error, BlockdevOnError on_error,
2975 Error **errp)
2977 BlockDriverState *bs, *iter;
2978 BlockDriverState *base_bs = NULL;
2979 AioContext *aio_context;
2980 Error *local_err = NULL;
2981 const char *base_name = NULL;
2983 if (!has_on_error) {
2984 on_error = BLOCKDEV_ON_ERROR_REPORT;
2987 bs = bdrv_lookup_bs(device, device, errp);
2988 if (!bs) {
2989 return;
2992 aio_context = bdrv_get_aio_context(bs);
2993 aio_context_acquire(aio_context);
2995 if (has_base && has_base_node) {
2996 error_setg(errp, "'base' and 'base-node' cannot be specified "
2997 "at the same time");
2998 goto out;
3001 if (has_base) {
3002 base_bs = bdrv_find_backing_image(bs, base);
3003 if (base_bs == NULL) {
3004 error_setg(errp, QERR_BASE_NOT_FOUND, base);
3005 goto out;
3007 assert(bdrv_get_aio_context(base_bs) == aio_context);
3008 base_name = base;
3011 if (has_base_node) {
3012 base_bs = bdrv_lookup_bs(NULL, base_node, errp);
3013 if (!base_bs) {
3014 goto out;
3016 if (bs == base_bs || !bdrv_chain_contains(bs, base_bs)) {
3017 error_setg(errp, "Node '%s' is not a backing image of '%s'",
3018 base_node, device);
3019 goto out;
3021 assert(bdrv_get_aio_context(base_bs) == aio_context);
3022 base_name = base_bs->filename;
3025 /* Check for op blockers in the whole chain between bs and base */
3026 for (iter = bs; iter && iter != base_bs; iter = backing_bs(iter)) {
3027 if (bdrv_op_is_blocked(iter, BLOCK_OP_TYPE_STREAM, errp)) {
3028 goto out;
3032 /* if we are streaming the entire chain, the result will have no backing
3033 * file, and specifying one is therefore an error */
3034 if (base_bs == NULL && has_backing_file) {
3035 error_setg(errp, "backing file specified, but streaming the "
3036 "entire chain");
3037 goto out;
3040 /* backing_file string overrides base bs filename */
3041 base_name = has_backing_file ? backing_file : base_name;
3043 stream_start(has_job_id ? job_id : NULL, bs, base_bs, base_name,
3044 has_speed ? speed : 0, on_error, &local_err);
3045 if (local_err) {
3046 error_propagate(errp, local_err);
3047 goto out;
3050 trace_qmp_block_stream(bs, bs->job);
3052 out:
3053 aio_context_release(aio_context);
3056 void qmp_block_commit(bool has_job_id, const char *job_id, const char *device,
3057 bool has_base, const char *base,
3058 bool has_top, const char *top,
3059 bool has_backing_file, const char *backing_file,
3060 bool has_speed, int64_t speed,
3061 bool has_filter_node_name, const char *filter_node_name,
3062 Error **errp)
3064 BlockDriverState *bs;
3065 BlockDriverState *iter;
3066 BlockDriverState *base_bs, *top_bs;
3067 AioContext *aio_context;
3068 Error *local_err = NULL;
3069 /* This will be part of the QMP command, if/when the
3070 * BlockdevOnError change for blkmirror makes it in
3072 BlockdevOnError on_error = BLOCKDEV_ON_ERROR_REPORT;
3074 if (!has_speed) {
3075 speed = 0;
3077 if (!has_filter_node_name) {
3078 filter_node_name = NULL;
3081 /* Important Note:
3082 * libvirt relies on the DeviceNotFound error class in order to probe for
3083 * live commit feature versions; for this to work, we must make sure to
3084 * perform the device lookup before any generic errors that may occur in a
3085 * scenario in which all optional arguments are omitted. */
3086 bs = qmp_get_root_bs(device, &local_err);
3087 if (!bs) {
3088 bs = bdrv_lookup_bs(device, device, NULL);
3089 if (!bs) {
3090 error_free(local_err);
3091 error_set(errp, ERROR_CLASS_DEVICE_NOT_FOUND,
3092 "Device '%s' not found", device);
3093 } else {
3094 error_propagate(errp, local_err);
3096 return;
3099 aio_context = bdrv_get_aio_context(bs);
3100 aio_context_acquire(aio_context);
3102 if (bdrv_op_is_blocked(bs, BLOCK_OP_TYPE_COMMIT_SOURCE, errp)) {
3103 goto out;
3106 /* default top_bs is the active layer */
3107 top_bs = bs;
3109 if (has_top && top) {
3110 if (strcmp(bs->filename, top) != 0) {
3111 top_bs = bdrv_find_backing_image(bs, top);
3115 if (top_bs == NULL) {
3116 error_setg(errp, "Top image file %s not found", top ? top : "NULL");
3117 goto out;
3120 assert(bdrv_get_aio_context(top_bs) == aio_context);
3122 if (has_base && base) {
3123 base_bs = bdrv_find_backing_image(top_bs, base);
3124 } else {
3125 base_bs = bdrv_find_base(top_bs);
3128 if (base_bs == NULL) {
3129 error_setg(errp, QERR_BASE_NOT_FOUND, base ? base : "NULL");
3130 goto out;
3133 assert(bdrv_get_aio_context(base_bs) == aio_context);
3135 for (iter = top_bs; iter != backing_bs(base_bs); iter = backing_bs(iter)) {
3136 if (bdrv_op_is_blocked(iter, BLOCK_OP_TYPE_COMMIT_TARGET, errp)) {
3137 goto out;
3141 /* Do not allow attempts to commit an image into itself */
3142 if (top_bs == base_bs) {
3143 error_setg(errp, "cannot commit an image into itself");
3144 goto out;
3147 if (top_bs == bs) {
3148 if (has_backing_file) {
3149 error_setg(errp, "'backing-file' specified,"
3150 " but 'top' is the active layer");
3151 goto out;
3153 commit_active_start(has_job_id ? job_id : NULL, bs, base_bs,
3154 BLOCK_JOB_DEFAULT, speed, on_error,
3155 filter_node_name, NULL, NULL, false, &local_err);
3156 } else {
3157 BlockDriverState *overlay_bs = bdrv_find_overlay(bs, top_bs);
3158 if (bdrv_op_is_blocked(overlay_bs, BLOCK_OP_TYPE_COMMIT_TARGET, errp)) {
3159 goto out;
3161 commit_start(has_job_id ? job_id : NULL, bs, base_bs, top_bs, speed,
3162 on_error, has_backing_file ? backing_file : NULL,
3163 filter_node_name, &local_err);
3165 if (local_err != NULL) {
3166 error_propagate(errp, local_err);
3167 goto out;
3170 out:
3171 aio_context_release(aio_context);
3174 static BlockJob *do_drive_backup(DriveBackup *backup, BlockJobTxn *txn,
3175 Error **errp)
3177 BlockDriverState *bs;
3178 BlockDriverState *target_bs;
3179 BlockDriverState *source = NULL;
3180 BlockJob *job = NULL;
3181 BdrvDirtyBitmap *bmap = NULL;
3182 AioContext *aio_context;
3183 QDict *options = NULL;
3184 Error *local_err = NULL;
3185 int flags;
3186 int64_t size;
3187 bool set_backing_hd = false;
3189 if (!backup->has_speed) {
3190 backup->speed = 0;
3192 if (!backup->has_on_source_error) {
3193 backup->on_source_error = BLOCKDEV_ON_ERROR_REPORT;
3195 if (!backup->has_on_target_error) {
3196 backup->on_target_error = BLOCKDEV_ON_ERROR_REPORT;
3198 if (!backup->has_mode) {
3199 backup->mode = NEW_IMAGE_MODE_ABSOLUTE_PATHS;
3201 if (!backup->has_job_id) {
3202 backup->job_id = NULL;
3204 if (!backup->has_compress) {
3205 backup->compress = false;
3208 bs = qmp_get_root_bs(backup->device, errp);
3209 if (!bs) {
3210 return NULL;
3213 aio_context = bdrv_get_aio_context(bs);
3214 aio_context_acquire(aio_context);
3216 if (!backup->has_format) {
3217 backup->format = backup->mode == NEW_IMAGE_MODE_EXISTING ?
3218 NULL : (char*) bs->drv->format_name;
3221 /* Early check to avoid creating target */
3222 if (bdrv_op_is_blocked(bs, BLOCK_OP_TYPE_BACKUP_SOURCE, errp)) {
3223 goto out;
3226 flags = bs->open_flags | BDRV_O_RDWR;
3228 /* See if we have a backing HD we can use to create our new image
3229 * on top of. */
3230 if (backup->sync == MIRROR_SYNC_MODE_TOP) {
3231 source = backing_bs(bs);
3232 if (!source) {
3233 backup->sync = MIRROR_SYNC_MODE_FULL;
3236 if (backup->sync == MIRROR_SYNC_MODE_NONE) {
3237 source = bs;
3238 flags |= BDRV_O_NO_BACKING;
3239 set_backing_hd = true;
3242 size = bdrv_getlength(bs);
3243 if (size < 0) {
3244 error_setg_errno(errp, -size, "bdrv_getlength failed");
3245 goto out;
3248 if (backup->mode != NEW_IMAGE_MODE_EXISTING) {
3249 assert(backup->format);
3250 if (source) {
3251 bdrv_img_create(backup->target, backup->format, source->filename,
3252 source->drv->format_name, NULL,
3253 size, flags, false, &local_err);
3254 } else {
3255 bdrv_img_create(backup->target, backup->format, NULL, NULL, NULL,
3256 size, flags, false, &local_err);
3260 if (local_err) {
3261 error_propagate(errp, local_err);
3262 goto out;
3265 if (backup->format) {
3266 if (!options) {
3267 options = qdict_new();
3269 qdict_put_str(options, "driver", backup->format);
3272 target_bs = bdrv_open(backup->target, NULL, options, flags, errp);
3273 if (!target_bs) {
3274 goto out;
3277 bdrv_set_aio_context(target_bs, aio_context);
3279 if (set_backing_hd) {
3280 bdrv_set_backing_hd(target_bs, source, &local_err);
3281 if (local_err) {
3282 bdrv_unref(target_bs);
3283 goto out;
3287 if (backup->has_bitmap) {
3288 bmap = bdrv_find_dirty_bitmap(bs, backup->bitmap);
3289 if (!bmap) {
3290 error_setg(errp, "Bitmap '%s' could not be found", backup->bitmap);
3291 bdrv_unref(target_bs);
3292 goto out;
3296 job = backup_job_create(backup->job_id, bs, target_bs, backup->speed,
3297 backup->sync, bmap, backup->compress,
3298 backup->on_source_error, backup->on_target_error,
3299 BLOCK_JOB_DEFAULT, NULL, NULL, txn, &local_err);
3300 bdrv_unref(target_bs);
3301 if (local_err != NULL) {
3302 error_propagate(errp, local_err);
3303 goto out;
3306 out:
3307 aio_context_release(aio_context);
3308 return job;
3311 void qmp_drive_backup(DriveBackup *arg, Error **errp)
3314 BlockJob *job;
3315 job = do_drive_backup(arg, NULL, errp);
3316 if (job) {
3317 block_job_start(job);
3321 BlockDeviceInfoList *qmp_query_named_block_nodes(Error **errp)
3323 return bdrv_named_nodes_list(errp);
3326 BlockJob *do_blockdev_backup(BlockdevBackup *backup, BlockJobTxn *txn,
3327 Error **errp)
3329 BlockDriverState *bs;
3330 BlockDriverState *target_bs;
3331 Error *local_err = NULL;
3332 AioContext *aio_context;
3333 BlockJob *job = NULL;
3335 if (!backup->has_speed) {
3336 backup->speed = 0;
3338 if (!backup->has_on_source_error) {
3339 backup->on_source_error = BLOCKDEV_ON_ERROR_REPORT;
3341 if (!backup->has_on_target_error) {
3342 backup->on_target_error = BLOCKDEV_ON_ERROR_REPORT;
3344 if (!backup->has_job_id) {
3345 backup->job_id = NULL;
3347 if (!backup->has_compress) {
3348 backup->compress = false;
3351 bs = qmp_get_root_bs(backup->device, errp);
3352 if (!bs) {
3353 return NULL;
3356 aio_context = bdrv_get_aio_context(bs);
3357 aio_context_acquire(aio_context);
3359 target_bs = bdrv_lookup_bs(backup->target, backup->target, errp);
3360 if (!target_bs) {
3361 goto out;
3364 if (bdrv_get_aio_context(target_bs) != aio_context) {
3365 if (!bdrv_has_blk(target_bs)) {
3366 /* The target BDS is not attached, we can safely move it to another
3367 * AioContext. */
3368 bdrv_set_aio_context(target_bs, aio_context);
3369 } else {
3370 error_setg(errp, "Target is attached to a different thread from "
3371 "source.");
3372 goto out;
3375 job = backup_job_create(backup->job_id, bs, target_bs, backup->speed,
3376 backup->sync, NULL, backup->compress,
3377 backup->on_source_error, backup->on_target_error,
3378 BLOCK_JOB_DEFAULT, NULL, NULL, txn, &local_err);
3379 if (local_err != NULL) {
3380 error_propagate(errp, local_err);
3382 out:
3383 aio_context_release(aio_context);
3384 return job;
3387 void qmp_blockdev_backup(BlockdevBackup *arg, Error **errp)
3389 BlockJob *job;
3390 job = do_blockdev_backup(arg, NULL, errp);
3391 if (job) {
3392 block_job_start(job);
3396 /* Parameter check and block job starting for drive mirroring.
3397 * Caller should hold @device and @target's aio context (must be the same).
3399 static void blockdev_mirror_common(const char *job_id, BlockDriverState *bs,
3400 BlockDriverState *target,
3401 bool has_replaces, const char *replaces,
3402 enum MirrorSyncMode sync,
3403 BlockMirrorBackingMode backing_mode,
3404 bool has_speed, int64_t speed,
3405 bool has_granularity, uint32_t granularity,
3406 bool has_buf_size, int64_t buf_size,
3407 bool has_on_source_error,
3408 BlockdevOnError on_source_error,
3409 bool has_on_target_error,
3410 BlockdevOnError on_target_error,
3411 bool has_unmap, bool unmap,
3412 bool has_filter_node_name,
3413 const char *filter_node_name,
3414 Error **errp)
3417 if (!has_speed) {
3418 speed = 0;
3420 if (!has_on_source_error) {
3421 on_source_error = BLOCKDEV_ON_ERROR_REPORT;
3423 if (!has_on_target_error) {
3424 on_target_error = BLOCKDEV_ON_ERROR_REPORT;
3426 if (!has_granularity) {
3427 granularity = 0;
3429 if (!has_buf_size) {
3430 buf_size = 0;
3432 if (!has_unmap) {
3433 unmap = true;
3435 if (!has_filter_node_name) {
3436 filter_node_name = NULL;
3439 if (granularity != 0 && (granularity < 512 || granularity > 1048576 * 64)) {
3440 error_setg(errp, QERR_INVALID_PARAMETER_VALUE, "granularity",
3441 "a value in range [512B, 64MB]");
3442 return;
3444 if (granularity & (granularity - 1)) {
3445 error_setg(errp, QERR_INVALID_PARAMETER_VALUE, "granularity",
3446 "power of 2");
3447 return;
3450 if (bdrv_op_is_blocked(bs, BLOCK_OP_TYPE_MIRROR_SOURCE, errp)) {
3451 return;
3453 if (bdrv_op_is_blocked(target, BLOCK_OP_TYPE_MIRROR_TARGET, errp)) {
3454 return;
3457 if (!bs->backing && sync == MIRROR_SYNC_MODE_TOP) {
3458 sync = MIRROR_SYNC_MODE_FULL;
3461 /* pass the node name to replace to mirror start since it's loose coupling
3462 * and will allow to check whether the node still exist at mirror completion
3464 mirror_start(job_id, bs, target,
3465 has_replaces ? replaces : NULL,
3466 speed, granularity, buf_size, sync, backing_mode,
3467 on_source_error, on_target_error, unmap, filter_node_name,
3468 errp);
3471 void qmp_drive_mirror(DriveMirror *arg, Error **errp)
3473 BlockDriverState *bs;
3474 BlockDriverState *source, *target_bs;
3475 AioContext *aio_context;
3476 BlockMirrorBackingMode backing_mode;
3477 Error *local_err = NULL;
3478 QDict *options = NULL;
3479 int flags;
3480 int64_t size;
3481 const char *format = arg->format;
3483 bs = qmp_get_root_bs(arg->device, errp);
3484 if (!bs) {
3485 return;
3488 aio_context = bdrv_get_aio_context(bs);
3489 aio_context_acquire(aio_context);
3491 if (!arg->has_mode) {
3492 arg->mode = NEW_IMAGE_MODE_ABSOLUTE_PATHS;
3495 if (!arg->has_format) {
3496 format = (arg->mode == NEW_IMAGE_MODE_EXISTING
3497 ? NULL : bs->drv->format_name);
3500 flags = bs->open_flags | BDRV_O_RDWR;
3501 source = backing_bs(bs);
3502 if (!source && arg->sync == MIRROR_SYNC_MODE_TOP) {
3503 arg->sync = MIRROR_SYNC_MODE_FULL;
3505 if (arg->sync == MIRROR_SYNC_MODE_NONE) {
3506 source = bs;
3509 size = bdrv_getlength(bs);
3510 if (size < 0) {
3511 error_setg_errno(errp, -size, "bdrv_getlength failed");
3512 goto out;
3515 if (arg->has_replaces) {
3516 BlockDriverState *to_replace_bs;
3517 AioContext *replace_aio_context;
3518 int64_t replace_size;
3520 if (!arg->has_node_name) {
3521 error_setg(errp, "a node-name must be provided when replacing a"
3522 " named node of the graph");
3523 goto out;
3526 to_replace_bs = check_to_replace_node(bs, arg->replaces, &local_err);
3528 if (!to_replace_bs) {
3529 error_propagate(errp, local_err);
3530 goto out;
3533 replace_aio_context = bdrv_get_aio_context(to_replace_bs);
3534 aio_context_acquire(replace_aio_context);
3535 replace_size = bdrv_getlength(to_replace_bs);
3536 aio_context_release(replace_aio_context);
3538 if (size != replace_size) {
3539 error_setg(errp, "cannot replace image with a mirror image of "
3540 "different size");
3541 goto out;
3545 if (arg->mode == NEW_IMAGE_MODE_ABSOLUTE_PATHS) {
3546 backing_mode = MIRROR_SOURCE_BACKING_CHAIN;
3547 } else {
3548 backing_mode = MIRROR_OPEN_BACKING_CHAIN;
3551 if ((arg->sync == MIRROR_SYNC_MODE_FULL || !source)
3552 && arg->mode != NEW_IMAGE_MODE_EXISTING)
3554 /* create new image w/o backing file */
3555 assert(format);
3556 bdrv_img_create(arg->target, format,
3557 NULL, NULL, NULL, size, flags, false, &local_err);
3558 } else {
3559 switch (arg->mode) {
3560 case NEW_IMAGE_MODE_EXISTING:
3561 break;
3562 case NEW_IMAGE_MODE_ABSOLUTE_PATHS:
3563 /* create new image with backing file */
3564 bdrv_img_create(arg->target, format,
3565 source->filename,
3566 source->drv->format_name,
3567 NULL, size, flags, false, &local_err);
3568 break;
3569 default:
3570 abort();
3574 if (local_err) {
3575 error_propagate(errp, local_err);
3576 goto out;
3579 options = qdict_new();
3580 if (arg->has_node_name) {
3581 qdict_put_str(options, "node-name", arg->node_name);
3583 if (format) {
3584 qdict_put_str(options, "driver", format);
3587 /* Mirroring takes care of copy-on-write using the source's backing
3588 * file.
3590 target_bs = bdrv_open(arg->target, NULL, options,
3591 flags | BDRV_O_NO_BACKING, errp);
3592 if (!target_bs) {
3593 goto out;
3596 bdrv_set_aio_context(target_bs, aio_context);
3598 blockdev_mirror_common(arg->has_job_id ? arg->job_id : NULL, bs, target_bs,
3599 arg->has_replaces, arg->replaces, arg->sync,
3600 backing_mode, arg->has_speed, arg->speed,
3601 arg->has_granularity, arg->granularity,
3602 arg->has_buf_size, arg->buf_size,
3603 arg->has_on_source_error, arg->on_source_error,
3604 arg->has_on_target_error, arg->on_target_error,
3605 arg->has_unmap, arg->unmap,
3606 false, NULL,
3607 &local_err);
3608 bdrv_unref(target_bs);
3609 error_propagate(errp, local_err);
3610 out:
3611 aio_context_release(aio_context);
3614 void qmp_blockdev_mirror(bool has_job_id, const char *job_id,
3615 const char *device, const char *target,
3616 bool has_replaces, const char *replaces,
3617 MirrorSyncMode sync,
3618 bool has_speed, int64_t speed,
3619 bool has_granularity, uint32_t granularity,
3620 bool has_buf_size, int64_t buf_size,
3621 bool has_on_source_error,
3622 BlockdevOnError on_source_error,
3623 bool has_on_target_error,
3624 BlockdevOnError on_target_error,
3625 bool has_filter_node_name,
3626 const char *filter_node_name,
3627 Error **errp)
3629 BlockDriverState *bs;
3630 BlockDriverState *target_bs;
3631 AioContext *aio_context;
3632 BlockMirrorBackingMode backing_mode = MIRROR_LEAVE_BACKING_CHAIN;
3633 Error *local_err = NULL;
3635 bs = qmp_get_root_bs(device, errp);
3636 if (!bs) {
3637 return;
3640 target_bs = bdrv_lookup_bs(target, target, errp);
3641 if (!target_bs) {
3642 return;
3645 aio_context = bdrv_get_aio_context(bs);
3646 aio_context_acquire(aio_context);
3648 bdrv_set_aio_context(target_bs, aio_context);
3650 blockdev_mirror_common(has_job_id ? job_id : NULL, bs, target_bs,
3651 has_replaces, replaces, sync, backing_mode,
3652 has_speed, speed,
3653 has_granularity, granularity,
3654 has_buf_size, buf_size,
3655 has_on_source_error, on_source_error,
3656 has_on_target_error, on_target_error,
3657 true, true,
3658 has_filter_node_name, filter_node_name,
3659 &local_err);
3660 error_propagate(errp, local_err);
3662 aio_context_release(aio_context);
3665 /* Get a block job using its ID and acquire its AioContext */
3666 static BlockJob *find_block_job(const char *id, AioContext **aio_context,
3667 Error **errp)
3669 BlockJob *job;
3671 assert(id != NULL);
3673 *aio_context = NULL;
3675 job = block_job_get(id);
3677 if (!job) {
3678 error_set(errp, ERROR_CLASS_DEVICE_NOT_ACTIVE,
3679 "Block job '%s' not found", id);
3680 return NULL;
3683 *aio_context = blk_get_aio_context(job->blk);
3684 aio_context_acquire(*aio_context);
3686 return job;
3689 void qmp_block_job_set_speed(const char *device, int64_t speed, Error **errp)
3691 AioContext *aio_context;
3692 BlockJob *job = find_block_job(device, &aio_context, errp);
3694 if (!job) {
3695 return;
3698 block_job_set_speed(job, speed, errp);
3699 aio_context_release(aio_context);
3702 void qmp_block_job_cancel(const char *device,
3703 bool has_force, bool force, Error **errp)
3705 AioContext *aio_context;
3706 BlockJob *job = find_block_job(device, &aio_context, errp);
3708 if (!job) {
3709 return;
3712 if (!has_force) {
3713 force = false;
3716 if (block_job_user_paused(job) && !force) {
3717 error_setg(errp, "The block job for device '%s' is currently paused",
3718 device);
3719 goto out;
3722 trace_qmp_block_job_cancel(job);
3723 block_job_cancel(job);
3724 out:
3725 aio_context_release(aio_context);
3728 void qmp_block_job_pause(const char *device, Error **errp)
3730 AioContext *aio_context;
3731 BlockJob *job = find_block_job(device, &aio_context, errp);
3733 if (!job || block_job_user_paused(job)) {
3734 return;
3737 trace_qmp_block_job_pause(job);
3738 block_job_user_pause(job);
3739 aio_context_release(aio_context);
3742 void qmp_block_job_resume(const char *device, Error **errp)
3744 AioContext *aio_context;
3745 BlockJob *job = find_block_job(device, &aio_context, errp);
3747 if (!job || !block_job_user_paused(job)) {
3748 return;
3751 trace_qmp_block_job_resume(job);
3752 block_job_user_resume(job);
3753 aio_context_release(aio_context);
3756 void qmp_block_job_complete(const char *device, Error **errp)
3758 AioContext *aio_context;
3759 BlockJob *job = find_block_job(device, &aio_context, errp);
3761 if (!job) {
3762 return;
3765 trace_qmp_block_job_complete(job);
3766 block_job_complete(job, errp);
3767 aio_context_release(aio_context);
3770 void qmp_change_backing_file(const char *device,
3771 const char *image_node_name,
3772 const char *backing_file,
3773 Error **errp)
3775 BlockDriverState *bs = NULL;
3776 AioContext *aio_context;
3777 BlockDriverState *image_bs = NULL;
3778 Error *local_err = NULL;
3779 bool ro;
3780 int open_flags;
3781 int ret;
3783 bs = qmp_get_root_bs(device, errp);
3784 if (!bs) {
3785 return;
3788 aio_context = bdrv_get_aio_context(bs);
3789 aio_context_acquire(aio_context);
3791 image_bs = bdrv_lookup_bs(NULL, image_node_name, &local_err);
3792 if (local_err) {
3793 error_propagate(errp, local_err);
3794 goto out;
3797 if (!image_bs) {
3798 error_setg(errp, "image file not found");
3799 goto out;
3802 if (bdrv_find_base(image_bs) == image_bs) {
3803 error_setg(errp, "not allowing backing file change on an image "
3804 "without a backing file");
3805 goto out;
3808 /* even though we are not necessarily operating on bs, we need it to
3809 * determine if block ops are currently prohibited on the chain */
3810 if (bdrv_op_is_blocked(bs, BLOCK_OP_TYPE_CHANGE, errp)) {
3811 goto out;
3814 /* final sanity check */
3815 if (!bdrv_chain_contains(bs, image_bs)) {
3816 error_setg(errp, "'%s' and image file are not in the same chain",
3817 device);
3818 goto out;
3821 /* if not r/w, reopen to make r/w */
3822 open_flags = image_bs->open_flags;
3823 ro = bdrv_is_read_only(image_bs);
3825 if (ro) {
3826 bdrv_reopen(image_bs, open_flags | BDRV_O_RDWR, &local_err);
3827 if (local_err) {
3828 error_propagate(errp, local_err);
3829 goto out;
3833 ret = bdrv_change_backing_file(image_bs, backing_file,
3834 image_bs->drv ? image_bs->drv->format_name : "");
3836 if (ret < 0) {
3837 error_setg_errno(errp, -ret, "Could not change backing file to '%s'",
3838 backing_file);
3839 /* don't exit here, so we can try to restore open flags if
3840 * appropriate */
3843 if (ro) {
3844 bdrv_reopen(image_bs, open_flags, &local_err);
3845 error_propagate(errp, local_err);
3848 out:
3849 aio_context_release(aio_context);
3852 void hmp_drive_add_node(Monitor *mon, const char *optstr)
3854 QemuOpts *opts;
3855 QDict *qdict;
3856 Error *local_err = NULL;
3858 opts = qemu_opts_parse_noisily(&qemu_drive_opts, optstr, false);
3859 if (!opts) {
3860 return;
3863 qdict = qemu_opts_to_qdict(opts, NULL);
3865 if (!qdict_get_try_str(qdict, "node-name")) {
3866 QDECREF(qdict);
3867 error_report("'node-name' needs to be specified");
3868 goto out;
3871 BlockDriverState *bs = bds_tree_init(qdict, &local_err);
3872 if (!bs) {
3873 error_report_err(local_err);
3874 goto out;
3877 QTAILQ_INSERT_TAIL(&monitor_bdrv_states, bs, monitor_list);
3879 out:
3880 qemu_opts_del(opts);
3883 void qmp_blockdev_add(BlockdevOptions *options, Error **errp)
3885 BlockDriverState *bs;
3886 QObject *obj;
3887 Visitor *v = qobject_output_visitor_new(&obj);
3888 QDict *qdict;
3889 Error *local_err = NULL;
3891 visit_type_BlockdevOptions(v, NULL, &options, &local_err);
3892 if (local_err) {
3893 error_propagate(errp, local_err);
3894 goto fail;
3897 visit_complete(v, &obj);
3898 qdict = qobject_to_qdict(obj);
3900 qdict_flatten(qdict);
3902 if (!qdict_get_try_str(qdict, "node-name")) {
3903 error_setg(errp, "'node-name' must be specified for the root node");
3904 goto fail;
3907 bs = bds_tree_init(qdict, errp);
3908 if (!bs) {
3909 goto fail;
3912 QTAILQ_INSERT_TAIL(&monitor_bdrv_states, bs, monitor_list);
3914 fail:
3915 visit_free(v);
3918 void qmp_blockdev_del(const char *node_name, Error **errp)
3920 AioContext *aio_context;
3921 BlockDriverState *bs;
3923 bs = bdrv_find_node(node_name);
3924 if (!bs) {
3925 error_setg(errp, "Cannot find node %s", node_name);
3926 return;
3928 if (bdrv_has_blk(bs)) {
3929 error_setg(errp, "Node %s is in use", node_name);
3930 return;
3932 aio_context = bdrv_get_aio_context(bs);
3933 aio_context_acquire(aio_context);
3935 if (bdrv_op_is_blocked(bs, BLOCK_OP_TYPE_DRIVE_DEL, errp)) {
3936 goto out;
3939 if (!bs->monitor_list.tqe_prev) {
3940 error_setg(errp, "Node %s is not owned by the monitor",
3941 bs->node_name);
3942 goto out;
3945 if (bs->refcnt > 1) {
3946 error_setg(errp, "Block device %s is in use",
3947 bdrv_get_device_or_node_name(bs));
3948 goto out;
3951 QTAILQ_REMOVE(&monitor_bdrv_states, bs, monitor_list);
3952 bdrv_unref(bs);
3954 out:
3955 aio_context_release(aio_context);
3958 static BdrvChild *bdrv_find_child(BlockDriverState *parent_bs,
3959 const char *child_name)
3961 BdrvChild *child;
3963 QLIST_FOREACH(child, &parent_bs->children, next) {
3964 if (strcmp(child->name, child_name) == 0) {
3965 return child;
3969 return NULL;
3972 void qmp_x_blockdev_change(const char *parent, bool has_child,
3973 const char *child, bool has_node,
3974 const char *node, Error **errp)
3976 BlockDriverState *parent_bs, *new_bs = NULL;
3977 BdrvChild *p_child;
3979 parent_bs = bdrv_lookup_bs(parent, parent, errp);
3980 if (!parent_bs) {
3981 return;
3984 if (has_child == has_node) {
3985 if (has_child) {
3986 error_setg(errp, "The parameters child and node are in conflict");
3987 } else {
3988 error_setg(errp, "Either child or node must be specified");
3990 return;
3993 if (has_child) {
3994 p_child = bdrv_find_child(parent_bs, child);
3995 if (!p_child) {
3996 error_setg(errp, "Node '%s' does not have child '%s'",
3997 parent, child);
3998 return;
4000 bdrv_del_child(parent_bs, p_child, errp);
4003 if (has_node) {
4004 new_bs = bdrv_find_node(node);
4005 if (!new_bs) {
4006 error_setg(errp, "Node '%s' not found", node);
4007 return;
4009 bdrv_add_child(parent_bs, new_bs, errp);
4013 BlockJobInfoList *qmp_query_block_jobs(Error **errp)
4015 BlockJobInfoList *head = NULL, **p_next = &head;
4016 BlockJob *job;
4018 for (job = block_job_next(NULL); job; job = block_job_next(job)) {
4019 BlockJobInfoList *elem;
4020 AioContext *aio_context;
4022 if (block_job_is_internal(job)) {
4023 continue;
4025 elem = g_new0(BlockJobInfoList, 1);
4026 aio_context = blk_get_aio_context(job->blk);
4027 aio_context_acquire(aio_context);
4028 elem->value = block_job_query(job, errp);
4029 aio_context_release(aio_context);
4030 if (!elem->value) {
4031 g_free(elem);
4032 qapi_free_BlockJobInfoList(head);
4033 return NULL;
4035 *p_next = elem;
4036 p_next = &elem->next;
4039 return head;
4042 QemuOptsList qemu_common_drive_opts = {
4043 .name = "drive",
4044 .head = QTAILQ_HEAD_INITIALIZER(qemu_common_drive_opts.head),
4045 .desc = {
4047 .name = "snapshot",
4048 .type = QEMU_OPT_BOOL,
4049 .help = "enable/disable snapshot mode",
4051 .name = "aio",
4052 .type = QEMU_OPT_STRING,
4053 .help = "host AIO implementation (threads, native)",
4055 .name = BDRV_OPT_CACHE_WB,
4056 .type = QEMU_OPT_BOOL,
4057 .help = "Enable writeback mode",
4059 .name = "format",
4060 .type = QEMU_OPT_STRING,
4061 .help = "disk format (raw, qcow2, ...)",
4063 .name = "rerror",
4064 .type = QEMU_OPT_STRING,
4065 .help = "read error action",
4067 .name = "werror",
4068 .type = QEMU_OPT_STRING,
4069 .help = "write error action",
4071 .name = BDRV_OPT_READ_ONLY,
4072 .type = QEMU_OPT_BOOL,
4073 .help = "open drive file as read-only",
4076 THROTTLE_OPTS,
4079 .name = "throttling.group",
4080 .type = QEMU_OPT_STRING,
4081 .help = "name of the block throttling group",
4083 .name = "copy-on-read",
4084 .type = QEMU_OPT_BOOL,
4085 .help = "copy read data from backing file into image file",
4087 .name = "detect-zeroes",
4088 .type = QEMU_OPT_STRING,
4089 .help = "try to optimize zero writes (off, on, unmap)",
4091 .name = "stats-account-invalid",
4092 .type = QEMU_OPT_BOOL,
4093 .help = "whether to account for invalid I/O operations "
4094 "in the statistics",
4096 .name = "stats-account-failed",
4097 .type = QEMU_OPT_BOOL,
4098 .help = "whether to account for failed I/O operations "
4099 "in the statistics",
4101 { /* end of list */ }
4105 QemuOptsList qemu_drive_opts = {
4106 .name = "drive",
4107 .head = QTAILQ_HEAD_INITIALIZER(qemu_drive_opts.head),
4108 .desc = {
4110 * no elements => accept any params
4111 * validation will happen later
4113 { /* end of list */ }