sheepdog: Mark sd_snapshot_delete() lossage FIXME
[qemu/ar7.git] / blockdev.c
blobf1f49bd3ca9aa99776af5f64e50d0aa60a7d938c
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 "qemu/cutils.h"
54 #include "qemu/help_option.h"
55 #include "qemu/throttle-options.h"
57 static QTAILQ_HEAD(, BlockDriverState) monitor_bdrv_states =
58 QTAILQ_HEAD_INITIALIZER(monitor_bdrv_states);
60 static int do_open_tray(const char *blk_name, const char *qdev_id,
61 bool force, Error **errp);
63 static const char *const if_name[IF_COUNT] = {
64 [IF_NONE] = "none",
65 [IF_IDE] = "ide",
66 [IF_SCSI] = "scsi",
67 [IF_FLOPPY] = "floppy",
68 [IF_PFLASH] = "pflash",
69 [IF_MTD] = "mtd",
70 [IF_SD] = "sd",
71 [IF_VIRTIO] = "virtio",
72 [IF_XEN] = "xen",
75 static int if_max_devs[IF_COUNT] = {
77 * Do not change these numbers! They govern how drive option
78 * index maps to unit and bus. That mapping is ABI.
80 * All controllers used to implement if=T drives need to support
81 * if_max_devs[T] units, for any T with if_max_devs[T] != 0.
82 * Otherwise, some index values map to "impossible" bus, unit
83 * values.
85 * For instance, if you change [IF_SCSI] to 255, -drive
86 * if=scsi,index=12 no longer means bus=1,unit=5, but
87 * bus=0,unit=12. With an lsi53c895a controller (7 units max),
88 * the drive can't be set up. Regression.
90 [IF_IDE] = 2,
91 [IF_SCSI] = 7,
94 /**
95 * Boards may call this to offer board-by-board overrides
96 * of the default, global values.
98 void override_max_devs(BlockInterfaceType type, int max_devs)
100 BlockBackend *blk;
101 DriveInfo *dinfo;
103 if (max_devs <= 0) {
104 return;
107 for (blk = blk_next(NULL); blk; blk = blk_next(blk)) {
108 dinfo = blk_legacy_dinfo(blk);
109 if (dinfo->type == type) {
110 fprintf(stderr, "Cannot override units-per-bus property of"
111 " the %s interface, because a drive of that type has"
112 " already been added.\n", if_name[type]);
113 g_assert_not_reached();
117 if_max_devs[type] = max_devs;
121 * We automatically delete the drive when a device using it gets
122 * unplugged. Questionable feature, but we can't just drop it.
123 * Device models call blockdev_mark_auto_del() to schedule the
124 * automatic deletion, and generic qdev code calls blockdev_auto_del()
125 * when deletion is actually safe.
127 void blockdev_mark_auto_del(BlockBackend *blk)
129 DriveInfo *dinfo = blk_legacy_dinfo(blk);
130 BlockDriverState *bs = blk_bs(blk);
131 AioContext *aio_context;
133 if (!dinfo) {
134 return;
137 if (bs) {
138 aio_context = bdrv_get_aio_context(bs);
139 aio_context_acquire(aio_context);
141 if (bs->job) {
142 block_job_cancel(bs->job);
145 aio_context_release(aio_context);
148 dinfo->auto_del = 1;
151 void blockdev_auto_del(BlockBackend *blk)
153 DriveInfo *dinfo = blk_legacy_dinfo(blk);
155 if (dinfo && dinfo->auto_del) {
156 monitor_remove_blk(blk);
157 blk_unref(blk);
162 * Returns the current mapping of how many units per bus
163 * a particular interface can support.
165 * A positive integer indicates n units per bus.
166 * 0 implies the mapping has not been established.
167 * -1 indicates an invalid BlockInterfaceType was given.
169 int drive_get_max_devs(BlockInterfaceType type)
171 if (type >= IF_IDE && type < IF_COUNT) {
172 return if_max_devs[type];
175 return -1;
178 static int drive_index_to_bus_id(BlockInterfaceType type, int index)
180 int max_devs = if_max_devs[type];
181 return max_devs ? index / max_devs : 0;
184 static int drive_index_to_unit_id(BlockInterfaceType type, int index)
186 int max_devs = if_max_devs[type];
187 return max_devs ? index % max_devs : index;
190 QemuOpts *drive_def(const char *optstr)
192 return qemu_opts_parse_noisily(qemu_find_opts("drive"), optstr, false);
195 QemuOpts *drive_add(BlockInterfaceType type, int index, const char *file,
196 const char *optstr)
198 QemuOpts *opts;
200 opts = drive_def(optstr);
201 if (!opts) {
202 return NULL;
204 if (type != IF_DEFAULT) {
205 qemu_opt_set(opts, "if", if_name[type], &error_abort);
207 if (index >= 0) {
208 qemu_opt_set_number(opts, "index", index, &error_abort);
210 if (file)
211 qemu_opt_set(opts, "file", file, &error_abort);
212 return opts;
215 DriveInfo *drive_get(BlockInterfaceType type, int bus, int unit)
217 BlockBackend *blk;
218 DriveInfo *dinfo;
220 for (blk = blk_next(NULL); blk; blk = blk_next(blk)) {
221 dinfo = blk_legacy_dinfo(blk);
222 if (dinfo && dinfo->type == type
223 && dinfo->bus == bus && dinfo->unit == unit) {
224 return dinfo;
228 return NULL;
231 void drive_check_orphaned(void)
233 BlockBackend *blk;
234 DriveInfo *dinfo;
235 Location loc;
236 bool orphans = false;
238 for (blk = blk_next(NULL); blk; blk = blk_next(blk)) {
239 dinfo = blk_legacy_dinfo(blk);
240 if (!blk_get_attached_dev(blk) && !dinfo->is_default &&
241 dinfo->type != IF_NONE) {
242 loc_push_none(&loc);
243 qemu_opts_loc_restore(dinfo->opts);
244 error_report("machine type does not support"
245 " if=%s,bus=%d,unit=%d",
246 if_name[dinfo->type], dinfo->bus, dinfo->unit);
247 loc_pop(&loc);
248 orphans = true;
252 if (orphans) {
253 exit(1);
257 DriveInfo *drive_get_by_index(BlockInterfaceType type, int index)
259 return drive_get(type,
260 drive_index_to_bus_id(type, index),
261 drive_index_to_unit_id(type, index));
264 int drive_get_max_bus(BlockInterfaceType type)
266 int max_bus;
267 BlockBackend *blk;
268 DriveInfo *dinfo;
270 max_bus = -1;
271 for (blk = blk_next(NULL); blk; blk = blk_next(blk)) {
272 dinfo = blk_legacy_dinfo(blk);
273 if (dinfo && dinfo->type == type && dinfo->bus > max_bus) {
274 max_bus = dinfo->bus;
277 return max_bus;
280 /* Get a block device. This should only be used for single-drive devices
281 (e.g. SD/Floppy/MTD). Multi-disk devices (scsi/ide) should use the
282 appropriate bus. */
283 DriveInfo *drive_get_next(BlockInterfaceType type)
285 static int next_block_unit[IF_COUNT];
287 return drive_get(type, 0, next_block_unit[type]++);
290 static void bdrv_format_print(void *opaque, const char *name)
292 error_printf(" %s", name);
295 typedef struct {
296 QEMUBH *bh;
297 BlockDriverState *bs;
298 } BDRVPutRefBH;
300 static int parse_block_error_action(const char *buf, bool is_read, Error **errp)
302 if (!strcmp(buf, "ignore")) {
303 return BLOCKDEV_ON_ERROR_IGNORE;
304 } else if (!is_read && !strcmp(buf, "enospc")) {
305 return BLOCKDEV_ON_ERROR_ENOSPC;
306 } else if (!strcmp(buf, "stop")) {
307 return BLOCKDEV_ON_ERROR_STOP;
308 } else if (!strcmp(buf, "report")) {
309 return BLOCKDEV_ON_ERROR_REPORT;
310 } else {
311 error_setg(errp, "'%s' invalid %s error action",
312 buf, is_read ? "read" : "write");
313 return -1;
317 static bool parse_stats_intervals(BlockAcctStats *stats, QList *intervals,
318 Error **errp)
320 const QListEntry *entry;
321 for (entry = qlist_first(intervals); entry; entry = qlist_next(entry)) {
322 switch (qobject_type(entry->value)) {
324 case QTYPE_QSTRING: {
325 unsigned long long length;
326 const char *str = qstring_get_str(qobject_to_qstring(entry->value));
327 if (parse_uint_full(str, &length, 10) == 0 &&
328 length > 0 && length <= UINT_MAX) {
329 block_acct_add_interval(stats, (unsigned) length);
330 } else {
331 error_setg(errp, "Invalid interval length: %s", str);
332 return false;
334 break;
337 case QTYPE_QINT: {
338 int64_t length = qint_get_int(qobject_to_qint(entry->value));
339 if (length > 0 && length <= UINT_MAX) {
340 block_acct_add_interval(stats, (unsigned) length);
341 } else {
342 error_setg(errp, "Invalid interval length: %" PRId64, length);
343 return false;
345 break;
348 default:
349 error_setg(errp, "The specification of stats-intervals is invalid");
350 return false;
353 return true;
356 typedef enum { MEDIA_DISK, MEDIA_CDROM } DriveMediaType;
358 /* All parameters but @opts are optional and may be set to NULL. */
359 static void extract_common_blockdev_options(QemuOpts *opts, int *bdrv_flags,
360 const char **throttling_group, ThrottleConfig *throttle_cfg,
361 BlockdevDetectZeroesOptions *detect_zeroes, Error **errp)
363 Error *local_error = NULL;
364 const char *aio;
366 if (bdrv_flags) {
367 if (qemu_opt_get_bool(opts, "copy-on-read", false)) {
368 *bdrv_flags |= BDRV_O_COPY_ON_READ;
371 if ((aio = qemu_opt_get(opts, "aio")) != NULL) {
372 if (!strcmp(aio, "native")) {
373 *bdrv_flags |= BDRV_O_NATIVE_AIO;
374 } else if (!strcmp(aio, "threads")) {
375 /* this is the default */
376 } else {
377 error_setg(errp, "invalid aio option");
378 return;
383 /* disk I/O throttling */
384 if (throttling_group) {
385 *throttling_group = qemu_opt_get(opts, "throttling.group");
388 if (throttle_cfg) {
389 throttle_config_init(throttle_cfg);
390 throttle_cfg->buckets[THROTTLE_BPS_TOTAL].avg =
391 qemu_opt_get_number(opts, "throttling.bps-total", 0);
392 throttle_cfg->buckets[THROTTLE_BPS_READ].avg =
393 qemu_opt_get_number(opts, "throttling.bps-read", 0);
394 throttle_cfg->buckets[THROTTLE_BPS_WRITE].avg =
395 qemu_opt_get_number(opts, "throttling.bps-write", 0);
396 throttle_cfg->buckets[THROTTLE_OPS_TOTAL].avg =
397 qemu_opt_get_number(opts, "throttling.iops-total", 0);
398 throttle_cfg->buckets[THROTTLE_OPS_READ].avg =
399 qemu_opt_get_number(opts, "throttling.iops-read", 0);
400 throttle_cfg->buckets[THROTTLE_OPS_WRITE].avg =
401 qemu_opt_get_number(opts, "throttling.iops-write", 0);
403 throttle_cfg->buckets[THROTTLE_BPS_TOTAL].max =
404 qemu_opt_get_number(opts, "throttling.bps-total-max", 0);
405 throttle_cfg->buckets[THROTTLE_BPS_READ].max =
406 qemu_opt_get_number(opts, "throttling.bps-read-max", 0);
407 throttle_cfg->buckets[THROTTLE_BPS_WRITE].max =
408 qemu_opt_get_number(opts, "throttling.bps-write-max", 0);
409 throttle_cfg->buckets[THROTTLE_OPS_TOTAL].max =
410 qemu_opt_get_number(opts, "throttling.iops-total-max", 0);
411 throttle_cfg->buckets[THROTTLE_OPS_READ].max =
412 qemu_opt_get_number(opts, "throttling.iops-read-max", 0);
413 throttle_cfg->buckets[THROTTLE_OPS_WRITE].max =
414 qemu_opt_get_number(opts, "throttling.iops-write-max", 0);
416 throttle_cfg->buckets[THROTTLE_BPS_TOTAL].burst_length =
417 qemu_opt_get_number(opts, "throttling.bps-total-max-length", 1);
418 throttle_cfg->buckets[THROTTLE_BPS_READ].burst_length =
419 qemu_opt_get_number(opts, "throttling.bps-read-max-length", 1);
420 throttle_cfg->buckets[THROTTLE_BPS_WRITE].burst_length =
421 qemu_opt_get_number(opts, "throttling.bps-write-max-length", 1);
422 throttle_cfg->buckets[THROTTLE_OPS_TOTAL].burst_length =
423 qemu_opt_get_number(opts, "throttling.iops-total-max-length", 1);
424 throttle_cfg->buckets[THROTTLE_OPS_READ].burst_length =
425 qemu_opt_get_number(opts, "throttling.iops-read-max-length", 1);
426 throttle_cfg->buckets[THROTTLE_OPS_WRITE].burst_length =
427 qemu_opt_get_number(opts, "throttling.iops-write-max-length", 1);
429 throttle_cfg->op_size =
430 qemu_opt_get_number(opts, "throttling.iops-size", 0);
432 if (!throttle_is_valid(throttle_cfg, errp)) {
433 return;
437 if (detect_zeroes) {
438 *detect_zeroes =
439 qapi_enum_parse(BlockdevDetectZeroesOptions_lookup,
440 qemu_opt_get(opts, "detect-zeroes"),
441 BLOCKDEV_DETECT_ZEROES_OPTIONS__MAX,
442 BLOCKDEV_DETECT_ZEROES_OPTIONS_OFF,
443 &local_error);
444 if (local_error) {
445 error_propagate(errp, local_error);
446 return;
451 /* Takes the ownership of bs_opts */
452 static BlockBackend *blockdev_init(const char *file, QDict *bs_opts,
453 Error **errp)
455 const char *buf;
456 int bdrv_flags = 0;
457 int on_read_error, on_write_error;
458 bool account_invalid, account_failed;
459 bool writethrough, read_only;
460 BlockBackend *blk;
461 BlockDriverState *bs;
462 ThrottleConfig cfg;
463 int snapshot = 0;
464 Error *error = NULL;
465 QemuOpts *opts;
466 QDict *interval_dict = NULL;
467 QList *interval_list = NULL;
468 const char *id;
469 BlockdevDetectZeroesOptions detect_zeroes =
470 BLOCKDEV_DETECT_ZEROES_OPTIONS_OFF;
471 const char *throttling_group = NULL;
473 /* Check common options by copying from bs_opts to opts, all other options
474 * stay in bs_opts for processing by bdrv_open(). */
475 id = qdict_get_try_str(bs_opts, "id");
476 opts = qemu_opts_create(&qemu_common_drive_opts, id, 1, &error);
477 if (error) {
478 error_propagate(errp, error);
479 goto err_no_opts;
482 qemu_opts_absorb_qdict(opts, bs_opts, &error);
483 if (error) {
484 error_propagate(errp, error);
485 goto early_err;
488 if (id) {
489 qdict_del(bs_opts, "id");
492 /* extract parameters */
493 snapshot = qemu_opt_get_bool(opts, "snapshot", 0);
495 account_invalid = qemu_opt_get_bool(opts, "stats-account-invalid", true);
496 account_failed = qemu_opt_get_bool(opts, "stats-account-failed", true);
498 writethrough = !qemu_opt_get_bool(opts, BDRV_OPT_CACHE_WB, true);
500 id = qemu_opts_id(opts);
502 qdict_extract_subqdict(bs_opts, &interval_dict, "stats-intervals.");
503 qdict_array_split(interval_dict, &interval_list);
505 if (qdict_size(interval_dict) != 0) {
506 error_setg(errp, "Invalid option stats-intervals.%s",
507 qdict_first(interval_dict)->key);
508 goto early_err;
511 extract_common_blockdev_options(opts, &bdrv_flags, &throttling_group, &cfg,
512 &detect_zeroes, &error);
513 if (error) {
514 error_propagate(errp, error);
515 goto early_err;
518 if ((buf = qemu_opt_get(opts, "format")) != NULL) {
519 if (is_help_option(buf)) {
520 error_printf("Supported formats:");
521 bdrv_iterate_format(bdrv_format_print, NULL);
522 error_printf("\n");
523 goto early_err;
526 if (qdict_haskey(bs_opts, "driver")) {
527 error_setg(errp, "Cannot specify both 'driver' and 'format'");
528 goto early_err;
530 qdict_put(bs_opts, "driver", qstring_from_str(buf));
533 on_write_error = BLOCKDEV_ON_ERROR_ENOSPC;
534 if ((buf = qemu_opt_get(opts, "werror")) != NULL) {
535 on_write_error = parse_block_error_action(buf, 0, &error);
536 if (error) {
537 error_propagate(errp, error);
538 goto early_err;
542 on_read_error = BLOCKDEV_ON_ERROR_REPORT;
543 if ((buf = qemu_opt_get(opts, "rerror")) != NULL) {
544 on_read_error = parse_block_error_action(buf, 1, &error);
545 if (error) {
546 error_propagate(errp, error);
547 goto early_err;
551 if (snapshot) {
552 bdrv_flags |= BDRV_O_SNAPSHOT;
555 read_only = qemu_opt_get_bool(opts, BDRV_OPT_READ_ONLY, false);
557 /* init */
558 if ((!file || !*file) && !qdict_size(bs_opts)) {
559 BlockBackendRootState *blk_rs;
561 blk = blk_new(0, BLK_PERM_ALL);
562 blk_rs = blk_get_root_state(blk);
563 blk_rs->open_flags = bdrv_flags;
564 blk_rs->read_only = read_only;
565 blk_rs->detect_zeroes = detect_zeroes;
567 QDECREF(bs_opts);
568 } else {
569 if (file && !*file) {
570 file = NULL;
573 /* bdrv_open() defaults to the values in bdrv_flags (for compatibility
574 * with other callers) rather than what we want as the real defaults.
575 * Apply the defaults here instead. */
576 qdict_set_default_str(bs_opts, BDRV_OPT_CACHE_DIRECT, "off");
577 qdict_set_default_str(bs_opts, BDRV_OPT_CACHE_NO_FLUSH, "off");
578 qdict_set_default_str(bs_opts, BDRV_OPT_READ_ONLY,
579 read_only ? "on" : "off");
580 assert((bdrv_flags & BDRV_O_CACHE_MASK) == 0);
582 if (runstate_check(RUN_STATE_INMIGRATE)) {
583 bdrv_flags |= BDRV_O_INACTIVE;
586 blk = blk_new_open(file, NULL, bs_opts, bdrv_flags, errp);
587 if (!blk) {
588 goto err_no_bs_opts;
590 bs = blk_bs(blk);
592 bs->detect_zeroes = detect_zeroes;
594 if (bdrv_key_required(bs)) {
595 autostart = 0;
598 block_acct_init(blk_get_stats(blk), account_invalid, account_failed);
600 if (!parse_stats_intervals(blk_get_stats(blk), interval_list, errp)) {
601 blk_unref(blk);
602 blk = NULL;
603 goto err_no_bs_opts;
607 /* disk I/O throttling */
608 if (throttle_enabled(&cfg)) {
609 if (!throttling_group) {
610 throttling_group = id;
612 blk_io_limits_enable(blk, throttling_group);
613 blk_set_io_limits(blk, &cfg);
616 blk_set_enable_write_cache(blk, !writethrough);
617 blk_set_on_error(blk, on_read_error, on_write_error);
619 if (!monitor_add_blk(blk, id, errp)) {
620 blk_unref(blk);
621 blk = NULL;
622 goto err_no_bs_opts;
625 err_no_bs_opts:
626 qemu_opts_del(opts);
627 QDECREF(interval_dict);
628 QDECREF(interval_list);
629 return blk;
631 early_err:
632 qemu_opts_del(opts);
633 QDECREF(interval_dict);
634 QDECREF(interval_list);
635 err_no_opts:
636 QDECREF(bs_opts);
637 return NULL;
640 /* Takes the ownership of bs_opts */
641 static BlockDriverState *bds_tree_init(QDict *bs_opts, Error **errp)
643 int bdrv_flags = 0;
645 /* bdrv_open() defaults to the values in bdrv_flags (for compatibility
646 * with other callers) rather than what we want as the real defaults.
647 * Apply the defaults here instead. */
648 qdict_set_default_str(bs_opts, BDRV_OPT_CACHE_DIRECT, "off");
649 qdict_set_default_str(bs_opts, BDRV_OPT_CACHE_NO_FLUSH, "off");
650 qdict_set_default_str(bs_opts, BDRV_OPT_READ_ONLY, "off");
652 if (runstate_check(RUN_STATE_INMIGRATE)) {
653 bdrv_flags |= BDRV_O_INACTIVE;
656 return bdrv_open(NULL, NULL, bs_opts, bdrv_flags, errp);
659 void blockdev_close_all_bdrv_states(void)
661 BlockDriverState *bs, *next_bs;
663 QTAILQ_FOREACH_SAFE(bs, &monitor_bdrv_states, monitor_list, next_bs) {
664 AioContext *ctx = bdrv_get_aio_context(bs);
666 aio_context_acquire(ctx);
667 bdrv_unref(bs);
668 aio_context_release(ctx);
672 /* Iterates over the list of monitor-owned BlockDriverStates */
673 BlockDriverState *bdrv_next_monitor_owned(BlockDriverState *bs)
675 return bs ? QTAILQ_NEXT(bs, monitor_list)
676 : QTAILQ_FIRST(&monitor_bdrv_states);
679 static void qemu_opt_rename(QemuOpts *opts, const char *from, const char *to,
680 Error **errp)
682 const char *value;
684 value = qemu_opt_get(opts, from);
685 if (value) {
686 if (qemu_opt_find(opts, to)) {
687 error_setg(errp, "'%s' and its alias '%s' can't be used at the "
688 "same time", to, from);
689 return;
693 /* rename all items in opts */
694 while ((value = qemu_opt_get(opts, from))) {
695 qemu_opt_set(opts, to, value, &error_abort);
696 qemu_opt_unset(opts, from);
700 QemuOptsList qemu_legacy_drive_opts = {
701 .name = "drive",
702 .head = QTAILQ_HEAD_INITIALIZER(qemu_legacy_drive_opts.head),
703 .desc = {
705 .name = "bus",
706 .type = QEMU_OPT_NUMBER,
707 .help = "bus number",
709 .name = "unit",
710 .type = QEMU_OPT_NUMBER,
711 .help = "unit number (i.e. lun for scsi)",
713 .name = "index",
714 .type = QEMU_OPT_NUMBER,
715 .help = "index number",
717 .name = "media",
718 .type = QEMU_OPT_STRING,
719 .help = "media type (disk, cdrom)",
721 .name = "if",
722 .type = QEMU_OPT_STRING,
723 .help = "interface (ide, scsi, sd, mtd, floppy, pflash, virtio)",
725 .name = "cyls",
726 .type = QEMU_OPT_NUMBER,
727 .help = "number of cylinders (ide disk geometry)",
729 .name = "heads",
730 .type = QEMU_OPT_NUMBER,
731 .help = "number of heads (ide disk geometry)",
733 .name = "secs",
734 .type = QEMU_OPT_NUMBER,
735 .help = "number of sectors (ide disk geometry)",
737 .name = "trans",
738 .type = QEMU_OPT_STRING,
739 .help = "chs translation (auto, lba, none)",
741 .name = "boot",
742 .type = QEMU_OPT_BOOL,
743 .help = "(deprecated, ignored)",
745 .name = "addr",
746 .type = QEMU_OPT_STRING,
747 .help = "pci address (virtio only)",
749 .name = "serial",
750 .type = QEMU_OPT_STRING,
751 .help = "disk serial number",
753 .name = "file",
754 .type = QEMU_OPT_STRING,
755 .help = "file name",
758 /* Options that are passed on, but have special semantics with -drive */
760 .name = BDRV_OPT_READ_ONLY,
761 .type = QEMU_OPT_BOOL,
762 .help = "open drive file as read-only",
764 .name = "rerror",
765 .type = QEMU_OPT_STRING,
766 .help = "read error action",
768 .name = "werror",
769 .type = QEMU_OPT_STRING,
770 .help = "write error action",
772 .name = "copy-on-read",
773 .type = QEMU_OPT_BOOL,
774 .help = "copy read data from backing file into image file",
777 { /* end of list */ }
781 DriveInfo *drive_new(QemuOpts *all_opts, BlockInterfaceType block_default_type)
783 const char *value;
784 BlockBackend *blk;
785 DriveInfo *dinfo = NULL;
786 QDict *bs_opts;
787 QemuOpts *legacy_opts;
788 DriveMediaType media = MEDIA_DISK;
789 BlockInterfaceType type;
790 int cyls, heads, secs, translation;
791 int max_devs, bus_id, unit_id, index;
792 const char *devaddr;
793 const char *werror, *rerror;
794 bool read_only = false;
795 bool copy_on_read;
796 const char *serial;
797 const char *filename;
798 Error *local_err = NULL;
799 int i;
801 /* Change legacy command line options into QMP ones */
802 static const struct {
803 const char *from;
804 const char *to;
805 } opt_renames[] = {
806 { "iops", "throttling.iops-total" },
807 { "iops_rd", "throttling.iops-read" },
808 { "iops_wr", "throttling.iops-write" },
810 { "bps", "throttling.bps-total" },
811 { "bps_rd", "throttling.bps-read" },
812 { "bps_wr", "throttling.bps-write" },
814 { "iops_max", "throttling.iops-total-max" },
815 { "iops_rd_max", "throttling.iops-read-max" },
816 { "iops_wr_max", "throttling.iops-write-max" },
818 { "bps_max", "throttling.bps-total-max" },
819 { "bps_rd_max", "throttling.bps-read-max" },
820 { "bps_wr_max", "throttling.bps-write-max" },
822 { "iops_size", "throttling.iops-size" },
824 { "group", "throttling.group" },
826 { "readonly", BDRV_OPT_READ_ONLY },
829 for (i = 0; i < ARRAY_SIZE(opt_renames); i++) {
830 qemu_opt_rename(all_opts, opt_renames[i].from, opt_renames[i].to,
831 &local_err);
832 if (local_err) {
833 error_report_err(local_err);
834 return NULL;
838 value = qemu_opt_get(all_opts, "cache");
839 if (value) {
840 int flags = 0;
841 bool writethrough;
843 if (bdrv_parse_cache_mode(value, &flags, &writethrough) != 0) {
844 error_report("invalid cache option");
845 return NULL;
848 /* Specific options take precedence */
849 if (!qemu_opt_get(all_opts, BDRV_OPT_CACHE_WB)) {
850 qemu_opt_set_bool(all_opts, BDRV_OPT_CACHE_WB,
851 !writethrough, &error_abort);
853 if (!qemu_opt_get(all_opts, BDRV_OPT_CACHE_DIRECT)) {
854 qemu_opt_set_bool(all_opts, BDRV_OPT_CACHE_DIRECT,
855 !!(flags & BDRV_O_NOCACHE), &error_abort);
857 if (!qemu_opt_get(all_opts, BDRV_OPT_CACHE_NO_FLUSH)) {
858 qemu_opt_set_bool(all_opts, BDRV_OPT_CACHE_NO_FLUSH,
859 !!(flags & BDRV_O_NO_FLUSH), &error_abort);
861 qemu_opt_unset(all_opts, "cache");
864 /* Get a QDict for processing the options */
865 bs_opts = qdict_new();
866 qemu_opts_to_qdict(all_opts, bs_opts);
868 legacy_opts = qemu_opts_create(&qemu_legacy_drive_opts, NULL, 0,
869 &error_abort);
870 qemu_opts_absorb_qdict(legacy_opts, bs_opts, &local_err);
871 if (local_err) {
872 error_report_err(local_err);
873 goto fail;
876 /* Deprecated option boot=[on|off] */
877 if (qemu_opt_get(legacy_opts, "boot") != NULL) {
878 fprintf(stderr, "qemu-kvm: boot=on|off is deprecated and will be "
879 "ignored. Future versions will reject this parameter. Please "
880 "update your scripts.\n");
883 /* Media type */
884 value = qemu_opt_get(legacy_opts, "media");
885 if (value) {
886 if (!strcmp(value, "disk")) {
887 media = MEDIA_DISK;
888 } else if (!strcmp(value, "cdrom")) {
889 media = MEDIA_CDROM;
890 read_only = true;
891 } else {
892 error_report("'%s' invalid media", value);
893 goto fail;
897 /* copy-on-read is disabled with a warning for read-only devices */
898 read_only |= qemu_opt_get_bool(legacy_opts, BDRV_OPT_READ_ONLY, false);
899 copy_on_read = qemu_opt_get_bool(legacy_opts, "copy-on-read", false);
901 if (read_only && copy_on_read) {
902 error_report("warning: disabling copy-on-read on read-only drive");
903 copy_on_read = false;
906 qdict_put(bs_opts, BDRV_OPT_READ_ONLY,
907 qstring_from_str(read_only ? "on" : "off"));
908 qdict_put(bs_opts, "copy-on-read",
909 qstring_from_str(copy_on_read ? "on" :"off"));
911 /* Controller type */
912 value = qemu_opt_get(legacy_opts, "if");
913 if (value) {
914 for (type = 0;
915 type < IF_COUNT && strcmp(value, if_name[type]);
916 type++) {
918 if (type == IF_COUNT) {
919 error_report("unsupported bus type '%s'", value);
920 goto fail;
922 } else {
923 type = block_default_type;
926 /* Geometry */
927 cyls = qemu_opt_get_number(legacy_opts, "cyls", 0);
928 heads = qemu_opt_get_number(legacy_opts, "heads", 0);
929 secs = qemu_opt_get_number(legacy_opts, "secs", 0);
931 if (cyls || heads || secs) {
932 if (cyls < 1) {
933 error_report("invalid physical cyls number");
934 goto fail;
936 if (heads < 1) {
937 error_report("invalid physical heads number");
938 goto fail;
940 if (secs < 1) {
941 error_report("invalid physical secs number");
942 goto fail;
946 translation = BIOS_ATA_TRANSLATION_AUTO;
947 value = qemu_opt_get(legacy_opts, "trans");
948 if (value != NULL) {
949 if (!cyls) {
950 error_report("'%s' trans must be used with cyls, heads and secs",
951 value);
952 goto fail;
954 if (!strcmp(value, "none")) {
955 translation = BIOS_ATA_TRANSLATION_NONE;
956 } else if (!strcmp(value, "lba")) {
957 translation = BIOS_ATA_TRANSLATION_LBA;
958 } else if (!strcmp(value, "large")) {
959 translation = BIOS_ATA_TRANSLATION_LARGE;
960 } else if (!strcmp(value, "rechs")) {
961 translation = BIOS_ATA_TRANSLATION_RECHS;
962 } else if (!strcmp(value, "auto")) {
963 translation = BIOS_ATA_TRANSLATION_AUTO;
964 } else {
965 error_report("'%s' invalid translation type", value);
966 goto fail;
970 if (media == MEDIA_CDROM) {
971 if (cyls || secs || heads) {
972 error_report("CHS can't be set with media=cdrom");
973 goto fail;
977 /* Device address specified by bus/unit or index.
978 * If none was specified, try to find the first free one. */
979 bus_id = qemu_opt_get_number(legacy_opts, "bus", 0);
980 unit_id = qemu_opt_get_number(legacy_opts, "unit", -1);
981 index = qemu_opt_get_number(legacy_opts, "index", -1);
983 max_devs = if_max_devs[type];
985 if (index != -1) {
986 if (bus_id != 0 || unit_id != -1) {
987 error_report("index cannot be used with bus and unit");
988 goto fail;
990 bus_id = drive_index_to_bus_id(type, index);
991 unit_id = drive_index_to_unit_id(type, index);
994 if (unit_id == -1) {
995 unit_id = 0;
996 while (drive_get(type, bus_id, unit_id) != NULL) {
997 unit_id++;
998 if (max_devs && unit_id >= max_devs) {
999 unit_id -= max_devs;
1000 bus_id++;
1005 if (max_devs && unit_id >= max_devs) {
1006 error_report("unit %d too big (max is %d)", unit_id, max_devs - 1);
1007 goto fail;
1010 if (drive_get(type, bus_id, unit_id) != NULL) {
1011 error_report("drive with bus=%d, unit=%d (index=%d) exists",
1012 bus_id, unit_id, index);
1013 goto fail;
1016 /* Serial number */
1017 serial = qemu_opt_get(legacy_opts, "serial");
1019 /* no id supplied -> create one */
1020 if (qemu_opts_id(all_opts) == NULL) {
1021 char *new_id;
1022 const char *mediastr = "";
1023 if (type == IF_IDE || type == IF_SCSI) {
1024 mediastr = (media == MEDIA_CDROM) ? "-cd" : "-hd";
1026 if (max_devs) {
1027 new_id = g_strdup_printf("%s%i%s%i", if_name[type], bus_id,
1028 mediastr, unit_id);
1029 } else {
1030 new_id = g_strdup_printf("%s%s%i", if_name[type],
1031 mediastr, unit_id);
1033 qdict_put(bs_opts, "id", qstring_from_str(new_id));
1034 g_free(new_id);
1037 /* Add virtio block device */
1038 devaddr = qemu_opt_get(legacy_opts, "addr");
1039 if (devaddr && type != IF_VIRTIO) {
1040 error_report("addr is not supported by this bus type");
1041 goto fail;
1044 if (type == IF_VIRTIO) {
1045 QemuOpts *devopts;
1046 devopts = qemu_opts_create(qemu_find_opts("device"), NULL, 0,
1047 &error_abort);
1048 if (arch_type == QEMU_ARCH_S390X) {
1049 qemu_opt_set(devopts, "driver", "virtio-blk-ccw", &error_abort);
1050 } else {
1051 qemu_opt_set(devopts, "driver", "virtio-blk-pci", &error_abort);
1053 qemu_opt_set(devopts, "drive", qdict_get_str(bs_opts, "id"),
1054 &error_abort);
1055 if (devaddr) {
1056 qemu_opt_set(devopts, "addr", devaddr, &error_abort);
1060 filename = qemu_opt_get(legacy_opts, "file");
1062 /* Check werror/rerror compatibility with if=... */
1063 werror = qemu_opt_get(legacy_opts, "werror");
1064 if (werror != NULL) {
1065 if (type != IF_IDE && type != IF_SCSI && type != IF_VIRTIO &&
1066 type != IF_NONE) {
1067 error_report("werror is not supported by this bus type");
1068 goto fail;
1070 qdict_put(bs_opts, "werror", qstring_from_str(werror));
1073 rerror = qemu_opt_get(legacy_opts, "rerror");
1074 if (rerror != NULL) {
1075 if (type != IF_IDE && type != IF_VIRTIO && type != IF_SCSI &&
1076 type != IF_NONE) {
1077 error_report("rerror is not supported by this bus type");
1078 goto fail;
1080 qdict_put(bs_opts, "rerror", qstring_from_str(rerror));
1083 /* Actual block device init: Functionality shared with blockdev-add */
1084 blk = blockdev_init(filename, bs_opts, &local_err);
1085 bs_opts = NULL;
1086 if (!blk) {
1087 if (local_err) {
1088 error_report_err(local_err);
1090 goto fail;
1091 } else {
1092 assert(!local_err);
1095 /* Create legacy DriveInfo */
1096 dinfo = g_malloc0(sizeof(*dinfo));
1097 dinfo->opts = all_opts;
1099 dinfo->cyls = cyls;
1100 dinfo->heads = heads;
1101 dinfo->secs = secs;
1102 dinfo->trans = translation;
1104 dinfo->type = type;
1105 dinfo->bus = bus_id;
1106 dinfo->unit = unit_id;
1107 dinfo->devaddr = devaddr;
1108 dinfo->serial = g_strdup(serial);
1110 blk_set_legacy_dinfo(blk, dinfo);
1112 switch(type) {
1113 case IF_IDE:
1114 case IF_SCSI:
1115 case IF_XEN:
1116 case IF_NONE:
1117 dinfo->media_cd = media == MEDIA_CDROM;
1118 break;
1119 default:
1120 break;
1123 fail:
1124 qemu_opts_del(legacy_opts);
1125 QDECREF(bs_opts);
1126 return dinfo;
1129 static BlockDriverState *qmp_get_root_bs(const char *name, Error **errp)
1131 BlockDriverState *bs;
1133 bs = bdrv_lookup_bs(name, name, errp);
1134 if (bs == NULL) {
1135 return NULL;
1138 if (!bdrv_is_root_node(bs)) {
1139 error_setg(errp, "Need a root block node");
1140 return NULL;
1143 if (!bdrv_is_inserted(bs)) {
1144 error_setg(errp, "Device has no medium");
1145 return NULL;
1148 return bs;
1151 static BlockBackend *qmp_get_blk(const char *blk_name, const char *qdev_id,
1152 Error **errp)
1154 BlockBackend *blk;
1156 if (!blk_name == !qdev_id) {
1157 error_setg(errp, "Need exactly one of 'device' and 'id'");
1158 return NULL;
1161 if (qdev_id) {
1162 blk = blk_by_qdev_id(qdev_id, errp);
1163 } else {
1164 blk = blk_by_name(blk_name);
1165 if (blk == NULL) {
1166 error_set(errp, ERROR_CLASS_DEVICE_NOT_FOUND,
1167 "Device '%s' not found", blk_name);
1171 return blk;
1174 void hmp_commit(Monitor *mon, const QDict *qdict)
1176 const char *device = qdict_get_str(qdict, "device");
1177 BlockBackend *blk;
1178 int ret;
1180 if (!strcmp(device, "all")) {
1181 ret = blk_commit_all();
1182 } else {
1183 BlockDriverState *bs;
1184 AioContext *aio_context;
1186 blk = blk_by_name(device);
1187 if (!blk) {
1188 monitor_printf(mon, "Device '%s' not found\n", device);
1189 return;
1191 if (!blk_is_available(blk)) {
1192 monitor_printf(mon, "Device '%s' has no medium\n", device);
1193 return;
1196 bs = blk_bs(blk);
1197 aio_context = bdrv_get_aio_context(bs);
1198 aio_context_acquire(aio_context);
1200 ret = bdrv_commit(bs);
1202 aio_context_release(aio_context);
1204 if (ret < 0) {
1205 monitor_printf(mon, "'commit' error for '%s': %s\n", device,
1206 strerror(-ret));
1210 static void blockdev_do_action(TransactionAction *action, Error **errp)
1212 TransactionActionList list;
1214 list.value = action;
1215 list.next = NULL;
1216 qmp_transaction(&list, false, NULL, errp);
1219 void qmp_blockdev_snapshot_sync(bool has_device, const char *device,
1220 bool has_node_name, const char *node_name,
1221 const char *snapshot_file,
1222 bool has_snapshot_node_name,
1223 const char *snapshot_node_name,
1224 bool has_format, const char *format,
1225 bool has_mode, NewImageMode mode, Error **errp)
1227 BlockdevSnapshotSync snapshot = {
1228 .has_device = has_device,
1229 .device = (char *) device,
1230 .has_node_name = has_node_name,
1231 .node_name = (char *) node_name,
1232 .snapshot_file = (char *) snapshot_file,
1233 .has_snapshot_node_name = has_snapshot_node_name,
1234 .snapshot_node_name = (char *) snapshot_node_name,
1235 .has_format = has_format,
1236 .format = (char *) format,
1237 .has_mode = has_mode,
1238 .mode = mode,
1240 TransactionAction action = {
1241 .type = TRANSACTION_ACTION_KIND_BLOCKDEV_SNAPSHOT_SYNC,
1242 .u.blockdev_snapshot_sync.data = &snapshot,
1244 blockdev_do_action(&action, errp);
1247 void qmp_blockdev_snapshot(const char *node, const char *overlay,
1248 Error **errp)
1250 BlockdevSnapshot snapshot_data = {
1251 .node = (char *) node,
1252 .overlay = (char *) overlay
1254 TransactionAction action = {
1255 .type = TRANSACTION_ACTION_KIND_BLOCKDEV_SNAPSHOT,
1256 .u.blockdev_snapshot.data = &snapshot_data,
1258 blockdev_do_action(&action, errp);
1261 void qmp_blockdev_snapshot_internal_sync(const char *device,
1262 const char *name,
1263 Error **errp)
1265 BlockdevSnapshotInternal snapshot = {
1266 .device = (char *) device,
1267 .name = (char *) name
1269 TransactionAction action = {
1270 .type = TRANSACTION_ACTION_KIND_BLOCKDEV_SNAPSHOT_INTERNAL_SYNC,
1271 .u.blockdev_snapshot_internal_sync.data = &snapshot,
1273 blockdev_do_action(&action, errp);
1276 SnapshotInfo *qmp_blockdev_snapshot_delete_internal_sync(const char *device,
1277 bool has_id,
1278 const char *id,
1279 bool has_name,
1280 const char *name,
1281 Error **errp)
1283 BlockDriverState *bs;
1284 AioContext *aio_context;
1285 QEMUSnapshotInfo sn;
1286 Error *local_err = NULL;
1287 SnapshotInfo *info = NULL;
1288 int ret;
1290 bs = qmp_get_root_bs(device, errp);
1291 if (!bs) {
1292 return NULL;
1294 aio_context = bdrv_get_aio_context(bs);
1295 aio_context_acquire(aio_context);
1297 if (!has_id) {
1298 id = NULL;
1301 if (!has_name) {
1302 name = NULL;
1305 if (!id && !name) {
1306 error_setg(errp, "Name or id must be provided");
1307 goto out_aio_context;
1310 if (bdrv_op_is_blocked(bs, BLOCK_OP_TYPE_INTERNAL_SNAPSHOT_DELETE, errp)) {
1311 goto out_aio_context;
1314 ret = bdrv_snapshot_find_by_id_and_name(bs, id, name, &sn, &local_err);
1315 if (local_err) {
1316 error_propagate(errp, local_err);
1317 goto out_aio_context;
1319 if (!ret) {
1320 error_setg(errp,
1321 "Snapshot with id '%s' and name '%s' does not exist on "
1322 "device '%s'",
1323 STR_OR_NULL(id), STR_OR_NULL(name), device);
1324 goto out_aio_context;
1327 bdrv_snapshot_delete(bs, id, name, &local_err);
1328 if (local_err) {
1329 error_propagate(errp, local_err);
1330 goto out_aio_context;
1333 aio_context_release(aio_context);
1335 info = g_new0(SnapshotInfo, 1);
1336 info->id = g_strdup(sn.id_str);
1337 info->name = g_strdup(sn.name);
1338 info->date_nsec = sn.date_nsec;
1339 info->date_sec = sn.date_sec;
1340 info->vm_state_size = sn.vm_state_size;
1341 info->vm_clock_nsec = sn.vm_clock_nsec % 1000000000;
1342 info->vm_clock_sec = sn.vm_clock_nsec / 1000000000;
1344 return info;
1346 out_aio_context:
1347 aio_context_release(aio_context);
1348 return NULL;
1352 * block_dirty_bitmap_lookup:
1353 * Return a dirty bitmap (if present), after validating
1354 * the node reference and bitmap names.
1356 * @node: The name of the BDS node to search for bitmaps
1357 * @name: The name of the bitmap to search for
1358 * @pbs: Output pointer for BDS lookup, if desired. Can be NULL.
1359 * @paio: Output pointer for aio_context acquisition, if desired. Can be NULL.
1360 * @errp: Output pointer for error information. Can be NULL.
1362 * @return: A bitmap object on success, or NULL on failure.
1364 static BdrvDirtyBitmap *block_dirty_bitmap_lookup(const char *node,
1365 const char *name,
1366 BlockDriverState **pbs,
1367 AioContext **paio,
1368 Error **errp)
1370 BlockDriverState *bs;
1371 BdrvDirtyBitmap *bitmap;
1372 AioContext *aio_context;
1374 if (!node) {
1375 error_setg(errp, "Node cannot be NULL");
1376 return NULL;
1378 if (!name) {
1379 error_setg(errp, "Bitmap name cannot be NULL");
1380 return NULL;
1382 bs = bdrv_lookup_bs(node, node, NULL);
1383 if (!bs) {
1384 error_setg(errp, "Node '%s' not found", node);
1385 return NULL;
1388 aio_context = bdrv_get_aio_context(bs);
1389 aio_context_acquire(aio_context);
1391 bitmap = bdrv_find_dirty_bitmap(bs, name);
1392 if (!bitmap) {
1393 error_setg(errp, "Dirty bitmap '%s' not found", name);
1394 goto fail;
1397 if (pbs) {
1398 *pbs = bs;
1400 if (paio) {
1401 *paio = aio_context;
1402 } else {
1403 aio_context_release(aio_context);
1406 return bitmap;
1408 fail:
1409 aio_context_release(aio_context);
1410 return NULL;
1413 /* New and old BlockDriverState structs for atomic group operations */
1415 typedef struct BlkActionState BlkActionState;
1418 * BlkActionOps:
1419 * Table of operations that define an Action.
1421 * @instance_size: Size of state struct, in bytes.
1422 * @prepare: Prepare the work, must NOT be NULL.
1423 * @commit: Commit the changes, can be NULL.
1424 * @abort: Abort the changes on fail, can be NULL.
1425 * @clean: Clean up resources after all transaction actions have called
1426 * commit() or abort(). Can be NULL.
1428 * Only prepare() may fail. In a single transaction, only one of commit() or
1429 * abort() will be called. clean() will always be called if it is present.
1431 typedef struct BlkActionOps {
1432 size_t instance_size;
1433 void (*prepare)(BlkActionState *common, Error **errp);
1434 void (*commit)(BlkActionState *common);
1435 void (*abort)(BlkActionState *common);
1436 void (*clean)(BlkActionState *common);
1437 } BlkActionOps;
1440 * BlkActionState:
1441 * Describes one Action's state within a Transaction.
1443 * @action: QAPI-defined enum identifying which Action to perform.
1444 * @ops: Table of ActionOps this Action can perform.
1445 * @block_job_txn: Transaction which this action belongs to.
1446 * @entry: List membership for all Actions in this Transaction.
1448 * This structure must be arranged as first member in a subclassed type,
1449 * assuming that the compiler will also arrange it to the same offsets as the
1450 * base class.
1452 struct BlkActionState {
1453 TransactionAction *action;
1454 const BlkActionOps *ops;
1455 BlockJobTxn *block_job_txn;
1456 TransactionProperties *txn_props;
1457 QSIMPLEQ_ENTRY(BlkActionState) entry;
1460 /* internal snapshot private data */
1461 typedef struct InternalSnapshotState {
1462 BlkActionState common;
1463 BlockDriverState *bs;
1464 AioContext *aio_context;
1465 QEMUSnapshotInfo sn;
1466 bool created;
1467 } InternalSnapshotState;
1470 static int action_check_completion_mode(BlkActionState *s, Error **errp)
1472 if (s->txn_props->completion_mode != ACTION_COMPLETION_MODE_INDIVIDUAL) {
1473 error_setg(errp,
1474 "Action '%s' does not support Transaction property "
1475 "completion-mode = %s",
1476 TransactionActionKind_lookup[s->action->type],
1477 ActionCompletionMode_lookup[s->txn_props->completion_mode]);
1478 return -1;
1480 return 0;
1483 static void internal_snapshot_prepare(BlkActionState *common,
1484 Error **errp)
1486 Error *local_err = NULL;
1487 const char *device;
1488 const char *name;
1489 BlockDriverState *bs;
1490 QEMUSnapshotInfo old_sn, *sn;
1491 bool ret;
1492 qemu_timeval tv;
1493 BlockdevSnapshotInternal *internal;
1494 InternalSnapshotState *state;
1495 int ret1;
1497 g_assert(common->action->type ==
1498 TRANSACTION_ACTION_KIND_BLOCKDEV_SNAPSHOT_INTERNAL_SYNC);
1499 internal = common->action->u.blockdev_snapshot_internal_sync.data;
1500 state = DO_UPCAST(InternalSnapshotState, common, common);
1502 /* 1. parse input */
1503 device = internal->device;
1504 name = internal->name;
1506 /* 2. check for validation */
1507 if (action_check_completion_mode(common, errp) < 0) {
1508 return;
1511 bs = qmp_get_root_bs(device, errp);
1512 if (!bs) {
1513 return;
1516 /* AioContext is released in .clean() */
1517 state->aio_context = bdrv_get_aio_context(bs);
1518 aio_context_acquire(state->aio_context);
1520 state->bs = bs;
1521 bdrv_drained_begin(bs);
1523 if (bdrv_op_is_blocked(bs, BLOCK_OP_TYPE_INTERNAL_SNAPSHOT, errp)) {
1524 return;
1527 if (bdrv_is_read_only(bs)) {
1528 error_setg(errp, "Device '%s' is read only", device);
1529 return;
1532 if (!bdrv_can_snapshot(bs)) {
1533 error_setg(errp, "Block format '%s' used by device '%s' "
1534 "does not support internal snapshots",
1535 bs->drv->format_name, device);
1536 return;
1539 if (!strlen(name)) {
1540 error_setg(errp, "Name is empty");
1541 return;
1544 /* check whether a snapshot with name exist */
1545 ret = bdrv_snapshot_find_by_id_and_name(bs, NULL, name, &old_sn,
1546 &local_err);
1547 if (local_err) {
1548 error_propagate(errp, local_err);
1549 return;
1550 } else if (ret) {
1551 error_setg(errp,
1552 "Snapshot with name '%s' already exists on device '%s'",
1553 name, device);
1554 return;
1557 /* 3. take the snapshot */
1558 sn = &state->sn;
1559 pstrcpy(sn->name, sizeof(sn->name), name);
1560 qemu_gettimeofday(&tv);
1561 sn->date_sec = tv.tv_sec;
1562 sn->date_nsec = tv.tv_usec * 1000;
1563 sn->vm_clock_nsec = qemu_clock_get_ns(QEMU_CLOCK_VIRTUAL);
1565 ret1 = bdrv_snapshot_create(bs, sn);
1566 if (ret1 < 0) {
1567 error_setg_errno(errp, -ret1,
1568 "Failed to create snapshot '%s' on device '%s'",
1569 name, device);
1570 return;
1573 /* 4. succeed, mark a snapshot is created */
1574 state->created = true;
1577 static void internal_snapshot_abort(BlkActionState *common)
1579 InternalSnapshotState *state =
1580 DO_UPCAST(InternalSnapshotState, common, common);
1581 BlockDriverState *bs = state->bs;
1582 QEMUSnapshotInfo *sn = &state->sn;
1583 Error *local_error = NULL;
1585 if (!state->created) {
1586 return;
1589 if (bdrv_snapshot_delete(bs, sn->id_str, sn->name, &local_error) < 0) {
1590 error_reportf_err(local_error,
1591 "Failed to delete snapshot with id '%s' and "
1592 "name '%s' on device '%s' in abort: ",
1593 sn->id_str, sn->name,
1594 bdrv_get_device_name(bs));
1598 static void internal_snapshot_clean(BlkActionState *common)
1600 InternalSnapshotState *state = DO_UPCAST(InternalSnapshotState,
1601 common, common);
1603 if (state->aio_context) {
1604 if (state->bs) {
1605 bdrv_drained_end(state->bs);
1607 aio_context_release(state->aio_context);
1611 /* external snapshot private data */
1612 typedef struct ExternalSnapshotState {
1613 BlkActionState common;
1614 BlockDriverState *old_bs;
1615 BlockDriverState *new_bs;
1616 AioContext *aio_context;
1617 bool overlay_appended;
1618 } ExternalSnapshotState;
1620 static void external_snapshot_prepare(BlkActionState *common,
1621 Error **errp)
1623 int flags = 0;
1624 QDict *options = NULL;
1625 Error *local_err = NULL;
1626 /* Device and node name of the image to generate the snapshot from */
1627 const char *device;
1628 const char *node_name;
1629 /* Reference to the new image (for 'blockdev-snapshot') */
1630 const char *snapshot_ref;
1631 /* File name of the new image (for 'blockdev-snapshot-sync') */
1632 const char *new_image_file;
1633 ExternalSnapshotState *state =
1634 DO_UPCAST(ExternalSnapshotState, common, common);
1635 TransactionAction *action = common->action;
1637 /* 'blockdev-snapshot' and 'blockdev-snapshot-sync' have similar
1638 * purpose but a different set of parameters */
1639 switch (action->type) {
1640 case TRANSACTION_ACTION_KIND_BLOCKDEV_SNAPSHOT:
1642 BlockdevSnapshot *s = action->u.blockdev_snapshot.data;
1643 device = s->node;
1644 node_name = s->node;
1645 new_image_file = NULL;
1646 snapshot_ref = s->overlay;
1648 break;
1649 case TRANSACTION_ACTION_KIND_BLOCKDEV_SNAPSHOT_SYNC:
1651 BlockdevSnapshotSync *s = action->u.blockdev_snapshot_sync.data;
1652 device = s->has_device ? s->device : NULL;
1653 node_name = s->has_node_name ? s->node_name : NULL;
1654 new_image_file = s->snapshot_file;
1655 snapshot_ref = NULL;
1657 break;
1658 default:
1659 g_assert_not_reached();
1662 /* start processing */
1663 if (action_check_completion_mode(common, errp) < 0) {
1664 return;
1667 state->old_bs = bdrv_lookup_bs(device, node_name, errp);
1668 if (!state->old_bs) {
1669 return;
1672 /* Acquire AioContext now so any threads operating on old_bs stop */
1673 state->aio_context = bdrv_get_aio_context(state->old_bs);
1674 aio_context_acquire(state->aio_context);
1675 bdrv_drained_begin(state->old_bs);
1677 if (!bdrv_is_inserted(state->old_bs)) {
1678 error_setg(errp, QERR_DEVICE_HAS_NO_MEDIUM, device);
1679 return;
1682 if (bdrv_op_is_blocked(state->old_bs,
1683 BLOCK_OP_TYPE_EXTERNAL_SNAPSHOT, errp)) {
1684 return;
1687 if (!bdrv_is_read_only(state->old_bs)) {
1688 if (bdrv_flush(state->old_bs)) {
1689 error_setg(errp, QERR_IO_ERROR);
1690 return;
1694 if (!bdrv_is_first_non_filter(state->old_bs)) {
1695 error_setg(errp, QERR_FEATURE_DISABLED, "snapshot");
1696 return;
1699 if (action->type == TRANSACTION_ACTION_KIND_BLOCKDEV_SNAPSHOT_SYNC) {
1700 BlockdevSnapshotSync *s = action->u.blockdev_snapshot_sync.data;
1701 const char *format = s->has_format ? s->format : "qcow2";
1702 enum NewImageMode mode;
1703 const char *snapshot_node_name =
1704 s->has_snapshot_node_name ? s->snapshot_node_name : NULL;
1706 if (node_name && !snapshot_node_name) {
1707 error_setg(errp, "New snapshot node name missing");
1708 return;
1711 if (snapshot_node_name &&
1712 bdrv_lookup_bs(snapshot_node_name, snapshot_node_name, NULL)) {
1713 error_setg(errp, "New snapshot node name already in use");
1714 return;
1717 flags = state->old_bs->open_flags;
1718 flags &= ~(BDRV_O_SNAPSHOT | BDRV_O_NO_BACKING | BDRV_O_COPY_ON_READ);
1720 /* create new image w/backing file */
1721 mode = s->has_mode ? s->mode : NEW_IMAGE_MODE_ABSOLUTE_PATHS;
1722 if (mode != NEW_IMAGE_MODE_EXISTING) {
1723 int64_t size = bdrv_getlength(state->old_bs);
1724 if (size < 0) {
1725 error_setg_errno(errp, -size, "bdrv_getlength failed");
1726 return;
1728 bdrv_img_create(new_image_file, format,
1729 state->old_bs->filename,
1730 state->old_bs->drv->format_name,
1731 NULL, size, flags, &local_err, false);
1732 if (local_err) {
1733 error_propagate(errp, local_err);
1734 return;
1738 options = qdict_new();
1739 if (s->has_snapshot_node_name) {
1740 qdict_put(options, "node-name",
1741 qstring_from_str(snapshot_node_name));
1743 qdict_put(options, "driver", qstring_from_str(format));
1745 flags |= BDRV_O_NO_BACKING;
1748 state->new_bs = bdrv_open(new_image_file, snapshot_ref, options, flags,
1749 errp);
1750 /* We will manually add the backing_hd field to the bs later */
1751 if (!state->new_bs) {
1752 return;
1755 if (bdrv_has_blk(state->new_bs)) {
1756 error_setg(errp, "The snapshot is already in use");
1757 return;
1760 if (bdrv_op_is_blocked(state->new_bs, BLOCK_OP_TYPE_EXTERNAL_SNAPSHOT,
1761 errp)) {
1762 return;
1765 if (state->new_bs->backing != NULL) {
1766 error_setg(errp, "The snapshot already has a backing image");
1767 return;
1770 if (!state->new_bs->drv->supports_backing) {
1771 error_setg(errp, "The snapshot does not support backing images");
1772 return;
1775 /* This removes our old bs and adds the new bs. This is an operation that
1776 * can fail, so we need to do it in .prepare; undoing it for abort is
1777 * always possible. */
1778 bdrv_ref(state->new_bs);
1779 bdrv_append(state->new_bs, state->old_bs, &local_err);
1780 if (local_err) {
1781 error_propagate(errp, local_err);
1782 return;
1784 state->overlay_appended = true;
1787 static void external_snapshot_commit(BlkActionState *common)
1789 ExternalSnapshotState *state =
1790 DO_UPCAST(ExternalSnapshotState, common, common);
1792 bdrv_set_aio_context(state->new_bs, state->aio_context);
1794 /* We don't need (or want) to use the transactional
1795 * bdrv_reopen_multiple() across all the entries at once, because we
1796 * don't want to abort all of them if one of them fails the reopen */
1797 if (!state->old_bs->copy_on_read) {
1798 bdrv_reopen(state->old_bs, state->old_bs->open_flags & ~BDRV_O_RDWR,
1799 NULL);
1803 static void external_snapshot_abort(BlkActionState *common)
1805 ExternalSnapshotState *state =
1806 DO_UPCAST(ExternalSnapshotState, common, common);
1807 if (state->new_bs) {
1808 if (state->overlay_appended) {
1809 bdrv_replace_node(state->new_bs, state->old_bs, &error_abort);
1814 static void external_snapshot_clean(BlkActionState *common)
1816 ExternalSnapshotState *state =
1817 DO_UPCAST(ExternalSnapshotState, common, common);
1818 if (state->aio_context) {
1819 bdrv_drained_end(state->old_bs);
1820 aio_context_release(state->aio_context);
1821 bdrv_unref(state->new_bs);
1825 typedef struct DriveBackupState {
1826 BlkActionState common;
1827 BlockDriverState *bs;
1828 AioContext *aio_context;
1829 BlockJob *job;
1830 } DriveBackupState;
1832 static BlockJob *do_drive_backup(DriveBackup *backup, BlockJobTxn *txn,
1833 Error **errp);
1835 static void drive_backup_prepare(BlkActionState *common, Error **errp)
1837 DriveBackupState *state = DO_UPCAST(DriveBackupState, common, common);
1838 BlockDriverState *bs;
1839 DriveBackup *backup;
1840 Error *local_err = NULL;
1842 assert(common->action->type == TRANSACTION_ACTION_KIND_DRIVE_BACKUP);
1843 backup = common->action->u.drive_backup.data;
1845 bs = qmp_get_root_bs(backup->device, errp);
1846 if (!bs) {
1847 return;
1850 /* AioContext is released in .clean() */
1851 state->aio_context = bdrv_get_aio_context(bs);
1852 aio_context_acquire(state->aio_context);
1853 bdrv_drained_begin(bs);
1854 state->bs = bs;
1856 state->job = do_drive_backup(backup, common->block_job_txn, &local_err);
1857 if (local_err) {
1858 error_propagate(errp, local_err);
1859 return;
1863 static void drive_backup_commit(BlkActionState *common)
1865 DriveBackupState *state = DO_UPCAST(DriveBackupState, common, common);
1866 assert(state->job);
1867 block_job_start(state->job);
1870 static void drive_backup_abort(BlkActionState *common)
1872 DriveBackupState *state = DO_UPCAST(DriveBackupState, common, common);
1874 if (state->job) {
1875 block_job_cancel_sync(state->job);
1879 static void drive_backup_clean(BlkActionState *common)
1881 DriveBackupState *state = DO_UPCAST(DriveBackupState, common, common);
1883 if (state->aio_context) {
1884 bdrv_drained_end(state->bs);
1885 aio_context_release(state->aio_context);
1889 typedef struct BlockdevBackupState {
1890 BlkActionState common;
1891 BlockDriverState *bs;
1892 BlockJob *job;
1893 AioContext *aio_context;
1894 } BlockdevBackupState;
1896 static BlockJob *do_blockdev_backup(BlockdevBackup *backup, BlockJobTxn *txn,
1897 Error **errp);
1899 static void blockdev_backup_prepare(BlkActionState *common, Error **errp)
1901 BlockdevBackupState *state = DO_UPCAST(BlockdevBackupState, common, common);
1902 BlockdevBackup *backup;
1903 BlockDriverState *bs, *target;
1904 Error *local_err = NULL;
1906 assert(common->action->type == TRANSACTION_ACTION_KIND_BLOCKDEV_BACKUP);
1907 backup = common->action->u.blockdev_backup.data;
1909 bs = qmp_get_root_bs(backup->device, errp);
1910 if (!bs) {
1911 return;
1914 target = bdrv_lookup_bs(backup->target, backup->target, errp);
1915 if (!target) {
1916 return;
1919 /* AioContext is released in .clean() */
1920 state->aio_context = bdrv_get_aio_context(bs);
1921 if (state->aio_context != bdrv_get_aio_context(target)) {
1922 state->aio_context = NULL;
1923 error_setg(errp, "Backup between two IO threads is not implemented");
1924 return;
1926 aio_context_acquire(state->aio_context);
1927 state->bs = bs;
1928 bdrv_drained_begin(state->bs);
1930 state->job = do_blockdev_backup(backup, common->block_job_txn, &local_err);
1931 if (local_err) {
1932 error_propagate(errp, local_err);
1933 return;
1937 static void blockdev_backup_commit(BlkActionState *common)
1939 BlockdevBackupState *state = DO_UPCAST(BlockdevBackupState, common, common);
1940 assert(state->job);
1941 block_job_start(state->job);
1944 static void blockdev_backup_abort(BlkActionState *common)
1946 BlockdevBackupState *state = DO_UPCAST(BlockdevBackupState, common, common);
1948 if (state->job) {
1949 block_job_cancel_sync(state->job);
1953 static void blockdev_backup_clean(BlkActionState *common)
1955 BlockdevBackupState *state = DO_UPCAST(BlockdevBackupState, common, common);
1957 if (state->aio_context) {
1958 bdrv_drained_end(state->bs);
1959 aio_context_release(state->aio_context);
1963 typedef struct BlockDirtyBitmapState {
1964 BlkActionState common;
1965 BdrvDirtyBitmap *bitmap;
1966 BlockDriverState *bs;
1967 AioContext *aio_context;
1968 HBitmap *backup;
1969 bool prepared;
1970 } BlockDirtyBitmapState;
1972 static void block_dirty_bitmap_add_prepare(BlkActionState *common,
1973 Error **errp)
1975 Error *local_err = NULL;
1976 BlockDirtyBitmapAdd *action;
1977 BlockDirtyBitmapState *state = DO_UPCAST(BlockDirtyBitmapState,
1978 common, common);
1980 if (action_check_completion_mode(common, errp) < 0) {
1981 return;
1984 action = common->action->u.block_dirty_bitmap_add.data;
1985 /* AIO context taken and released within qmp_block_dirty_bitmap_add */
1986 qmp_block_dirty_bitmap_add(action->node, action->name,
1987 action->has_granularity, action->granularity,
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 &state->aio_context,
2028 errp);
2029 if (!state->bitmap) {
2030 return;
2033 if (bdrv_dirty_bitmap_frozen(state->bitmap)) {
2034 error_setg(errp, "Cannot modify a frozen bitmap");
2035 return;
2036 } else if (!bdrv_dirty_bitmap_enabled(state->bitmap)) {
2037 error_setg(errp, "Cannot clear a disabled bitmap");
2038 return;
2041 bdrv_clear_dirty_bitmap(state->bitmap, &state->backup);
2042 /* AioContext is released in .clean() */
2045 static void block_dirty_bitmap_clear_abort(BlkActionState *common)
2047 BlockDirtyBitmapState *state = DO_UPCAST(BlockDirtyBitmapState,
2048 common, common);
2050 bdrv_undo_clear_dirty_bitmap(state->bitmap, state->backup);
2053 static void block_dirty_bitmap_clear_commit(BlkActionState *common)
2055 BlockDirtyBitmapState *state = DO_UPCAST(BlockDirtyBitmapState,
2056 common, common);
2058 hbitmap_free(state->backup);
2061 static void block_dirty_bitmap_clear_clean(BlkActionState *common)
2063 BlockDirtyBitmapState *state = DO_UPCAST(BlockDirtyBitmapState,
2064 common, common);
2066 if (state->aio_context) {
2067 aio_context_release(state->aio_context);
2071 static void abort_prepare(BlkActionState *common, Error **errp)
2073 error_setg(errp, "Transaction aborted using Abort action");
2076 static void abort_commit(BlkActionState *common)
2078 g_assert_not_reached(); /* this action never succeeds */
2081 static const BlkActionOps actions[] = {
2082 [TRANSACTION_ACTION_KIND_BLOCKDEV_SNAPSHOT] = {
2083 .instance_size = sizeof(ExternalSnapshotState),
2084 .prepare = external_snapshot_prepare,
2085 .commit = external_snapshot_commit,
2086 .abort = external_snapshot_abort,
2087 .clean = external_snapshot_clean,
2089 [TRANSACTION_ACTION_KIND_BLOCKDEV_SNAPSHOT_SYNC] = {
2090 .instance_size = sizeof(ExternalSnapshotState),
2091 .prepare = external_snapshot_prepare,
2092 .commit = external_snapshot_commit,
2093 .abort = external_snapshot_abort,
2094 .clean = external_snapshot_clean,
2096 [TRANSACTION_ACTION_KIND_DRIVE_BACKUP] = {
2097 .instance_size = sizeof(DriveBackupState),
2098 .prepare = drive_backup_prepare,
2099 .commit = drive_backup_commit,
2100 .abort = drive_backup_abort,
2101 .clean = drive_backup_clean,
2103 [TRANSACTION_ACTION_KIND_BLOCKDEV_BACKUP] = {
2104 .instance_size = sizeof(BlockdevBackupState),
2105 .prepare = blockdev_backup_prepare,
2106 .commit = blockdev_backup_commit,
2107 .abort = blockdev_backup_abort,
2108 .clean = blockdev_backup_clean,
2110 [TRANSACTION_ACTION_KIND_ABORT] = {
2111 .instance_size = sizeof(BlkActionState),
2112 .prepare = abort_prepare,
2113 .commit = abort_commit,
2115 [TRANSACTION_ACTION_KIND_BLOCKDEV_SNAPSHOT_INTERNAL_SYNC] = {
2116 .instance_size = sizeof(InternalSnapshotState),
2117 .prepare = internal_snapshot_prepare,
2118 .abort = internal_snapshot_abort,
2119 .clean = internal_snapshot_clean,
2121 [TRANSACTION_ACTION_KIND_BLOCK_DIRTY_BITMAP_ADD] = {
2122 .instance_size = sizeof(BlockDirtyBitmapState),
2123 .prepare = block_dirty_bitmap_add_prepare,
2124 .abort = block_dirty_bitmap_add_abort,
2126 [TRANSACTION_ACTION_KIND_BLOCK_DIRTY_BITMAP_CLEAR] = {
2127 .instance_size = sizeof(BlockDirtyBitmapState),
2128 .prepare = block_dirty_bitmap_clear_prepare,
2129 .commit = block_dirty_bitmap_clear_commit,
2130 .abort = block_dirty_bitmap_clear_abort,
2131 .clean = block_dirty_bitmap_clear_clean,
2136 * Allocate a TransactionProperties structure if necessary, and fill
2137 * that structure with desired defaults if they are unset.
2139 static TransactionProperties *get_transaction_properties(
2140 TransactionProperties *props)
2142 if (!props) {
2143 props = g_new0(TransactionProperties, 1);
2146 if (!props->has_completion_mode) {
2147 props->has_completion_mode = true;
2148 props->completion_mode = ACTION_COMPLETION_MODE_INDIVIDUAL;
2151 return props;
2155 * 'Atomic' group operations. The operations are performed as a set, and if
2156 * any fail then we roll back all operations in the group.
2158 void qmp_transaction(TransactionActionList *dev_list,
2159 bool has_props,
2160 struct TransactionProperties *props,
2161 Error **errp)
2163 TransactionActionList *dev_entry = dev_list;
2164 BlockJobTxn *block_job_txn = NULL;
2165 BlkActionState *state, *next;
2166 Error *local_err = NULL;
2168 QSIMPLEQ_HEAD(snap_bdrv_states, BlkActionState) snap_bdrv_states;
2169 QSIMPLEQ_INIT(&snap_bdrv_states);
2171 /* Does this transaction get canceled as a group on failure?
2172 * If not, we don't really need to make a BlockJobTxn.
2174 props = get_transaction_properties(props);
2175 if (props->completion_mode != ACTION_COMPLETION_MODE_INDIVIDUAL) {
2176 block_job_txn = block_job_txn_new();
2179 /* drain all i/o before any operations */
2180 bdrv_drain_all();
2182 /* We don't do anything in this loop that commits us to the operations */
2183 while (NULL != dev_entry) {
2184 TransactionAction *dev_info = NULL;
2185 const BlkActionOps *ops;
2187 dev_info = dev_entry->value;
2188 dev_entry = dev_entry->next;
2190 assert(dev_info->type < ARRAY_SIZE(actions));
2192 ops = &actions[dev_info->type];
2193 assert(ops->instance_size > 0);
2195 state = g_malloc0(ops->instance_size);
2196 state->ops = ops;
2197 state->action = dev_info;
2198 state->block_job_txn = block_job_txn;
2199 state->txn_props = props;
2200 QSIMPLEQ_INSERT_TAIL(&snap_bdrv_states, state, entry);
2202 state->ops->prepare(state, &local_err);
2203 if (local_err) {
2204 error_propagate(errp, local_err);
2205 goto delete_and_fail;
2209 QSIMPLEQ_FOREACH(state, &snap_bdrv_states, entry) {
2210 if (state->ops->commit) {
2211 state->ops->commit(state);
2215 /* success */
2216 goto exit;
2218 delete_and_fail:
2219 /* failure, and it is all-or-none; roll back all operations */
2220 QSIMPLEQ_FOREACH(state, &snap_bdrv_states, entry) {
2221 if (state->ops->abort) {
2222 state->ops->abort(state);
2225 exit:
2226 QSIMPLEQ_FOREACH_SAFE(state, &snap_bdrv_states, entry, next) {
2227 if (state->ops->clean) {
2228 state->ops->clean(state);
2230 g_free(state);
2232 if (!has_props) {
2233 qapi_free_TransactionProperties(props);
2235 block_job_txn_unref(block_job_txn);
2238 void qmp_eject(bool has_device, const char *device,
2239 bool has_id, const char *id,
2240 bool has_force, bool force, Error **errp)
2242 Error *local_err = NULL;
2243 int rc;
2245 if (!has_force) {
2246 force = false;
2249 rc = do_open_tray(has_device ? device : NULL,
2250 has_id ? id : NULL,
2251 force, &local_err);
2252 if (rc && rc != -ENOSYS) {
2253 error_propagate(errp, local_err);
2254 return;
2256 error_free(local_err);
2258 qmp_x_blockdev_remove_medium(has_device, device, has_id, id, errp);
2261 void qmp_block_passwd(bool has_device, const char *device,
2262 bool has_node_name, const char *node_name,
2263 const char *password, Error **errp)
2265 Error *local_err = NULL;
2266 BlockDriverState *bs;
2267 AioContext *aio_context;
2269 bs = bdrv_lookup_bs(has_device ? device : NULL,
2270 has_node_name ? node_name : NULL,
2271 &local_err);
2272 if (local_err) {
2273 error_propagate(errp, local_err);
2274 return;
2277 aio_context = bdrv_get_aio_context(bs);
2278 aio_context_acquire(aio_context);
2280 bdrv_add_key(bs, password, errp);
2282 aio_context_release(aio_context);
2286 * Attempt to open the tray of @device.
2287 * If @force, ignore its tray lock.
2288 * Else, if the tray is locked, don't open it, but ask the guest to open it.
2289 * On error, store an error through @errp and return -errno.
2290 * If @device does not exist, return -ENODEV.
2291 * If it has no removable media, return -ENOTSUP.
2292 * If it has no tray, return -ENOSYS.
2293 * If the guest was asked to open the tray, return -EINPROGRESS.
2294 * Else, return 0.
2296 static int do_open_tray(const char *blk_name, const char *qdev_id,
2297 bool force, Error **errp)
2299 BlockBackend *blk;
2300 const char *device = qdev_id ?: blk_name;
2301 bool locked;
2303 blk = qmp_get_blk(blk_name, qdev_id, errp);
2304 if (!blk) {
2305 return -ENODEV;
2308 if (!blk_dev_has_removable_media(blk)) {
2309 error_setg(errp, "Device '%s' is not removable", device);
2310 return -ENOTSUP;
2313 if (!blk_dev_has_tray(blk)) {
2314 error_setg(errp, "Device '%s' does not have a tray", device);
2315 return -ENOSYS;
2318 if (blk_dev_is_tray_open(blk)) {
2319 return 0;
2322 locked = blk_dev_is_medium_locked(blk);
2323 if (locked) {
2324 blk_dev_eject_request(blk, force);
2327 if (!locked || force) {
2328 blk_dev_change_media_cb(blk, false, &error_abort);
2331 if (locked && !force) {
2332 error_setg(errp, "Device '%s' is locked and force was not specified, "
2333 "wait for tray to open and try again", device);
2334 return -EINPROGRESS;
2337 return 0;
2340 void qmp_blockdev_open_tray(bool has_device, const char *device,
2341 bool has_id, const char *id,
2342 bool has_force, bool force,
2343 Error **errp)
2345 Error *local_err = NULL;
2346 int rc;
2348 if (!has_force) {
2349 force = false;
2351 rc = do_open_tray(has_device ? device : NULL,
2352 has_id ? id : NULL,
2353 force, &local_err);
2354 if (rc && rc != -ENOSYS && rc != -EINPROGRESS) {
2355 error_propagate(errp, local_err);
2356 return;
2358 error_free(local_err);
2361 void qmp_blockdev_close_tray(bool has_device, const char *device,
2362 bool has_id, const char *id,
2363 Error **errp)
2365 BlockBackend *blk;
2366 Error *local_err = NULL;
2368 device = has_device ? device : NULL;
2369 id = has_id ? id : NULL;
2371 blk = qmp_get_blk(device, id, errp);
2372 if (!blk) {
2373 return;
2376 if (!blk_dev_has_removable_media(blk)) {
2377 error_setg(errp, "Device '%s' is not removable", device ?: id);
2378 return;
2381 if (!blk_dev_has_tray(blk)) {
2382 /* Ignore this command on tray-less devices */
2383 return;
2386 if (!blk_dev_is_tray_open(blk)) {
2387 return;
2390 blk_dev_change_media_cb(blk, true, &local_err);
2391 if (local_err) {
2392 error_propagate(errp, local_err);
2393 return;
2397 void qmp_x_blockdev_remove_medium(bool has_device, const char *device,
2398 bool has_id, const char *id, Error **errp)
2400 BlockBackend *blk;
2401 BlockDriverState *bs;
2402 AioContext *aio_context;
2403 bool has_attached_device;
2405 device = has_device ? device : NULL;
2406 id = has_id ? id : NULL;
2408 blk = qmp_get_blk(device, id, errp);
2409 if (!blk) {
2410 return;
2413 /* For BBs without a device, we can exchange the BDS tree at will */
2414 has_attached_device = blk_get_attached_dev(blk);
2416 if (has_attached_device && !blk_dev_has_removable_media(blk)) {
2417 error_setg(errp, "Device '%s' is not removable", device ?: id);
2418 return;
2421 if (has_attached_device && blk_dev_has_tray(blk) &&
2422 !blk_dev_is_tray_open(blk))
2424 error_setg(errp, "Tray of device '%s' is not open", device ?: id);
2425 return;
2428 bs = blk_bs(blk);
2429 if (!bs) {
2430 return;
2433 aio_context = bdrv_get_aio_context(bs);
2434 aio_context_acquire(aio_context);
2436 if (bdrv_op_is_blocked(bs, BLOCK_OP_TYPE_EJECT, errp)) {
2437 goto out;
2440 blk_remove_bs(blk);
2442 if (!blk_dev_has_tray(blk)) {
2443 /* For tray-less devices, blockdev-open-tray is a no-op (or may not be
2444 * called at all); therefore, the medium needs to be ejected here.
2445 * Do it after blk_remove_bs() so blk_is_inserted(blk) returns the @load
2446 * value passed here (i.e. false). */
2447 blk_dev_change_media_cb(blk, false, &error_abort);
2450 out:
2451 aio_context_release(aio_context);
2454 static void qmp_blockdev_insert_anon_medium(BlockBackend *blk,
2455 BlockDriverState *bs, Error **errp)
2457 Error *local_err = NULL;
2458 bool has_device;
2459 int ret;
2461 /* For BBs without a device, we can exchange the BDS tree at will */
2462 has_device = blk_get_attached_dev(blk);
2464 if (has_device && !blk_dev_has_removable_media(blk)) {
2465 error_setg(errp, "Device is not removable");
2466 return;
2469 if (has_device && blk_dev_has_tray(blk) && !blk_dev_is_tray_open(blk)) {
2470 error_setg(errp, "Tray of the device is not open");
2471 return;
2474 if (blk_bs(blk)) {
2475 error_setg(errp, "There already is a medium in the device");
2476 return;
2479 ret = blk_insert_bs(blk, bs, errp);
2480 if (ret < 0) {
2481 return;
2484 if (!blk_dev_has_tray(blk)) {
2485 /* For tray-less devices, blockdev-close-tray is a no-op (or may not be
2486 * called at all); therefore, the medium needs to be pushed into the
2487 * slot here.
2488 * Do it after blk_insert_bs() so blk_is_inserted(blk) returns the @load
2489 * value passed here (i.e. true). */
2490 blk_dev_change_media_cb(blk, true, &local_err);
2491 if (local_err) {
2492 error_propagate(errp, local_err);
2493 blk_remove_bs(blk);
2494 return;
2499 void qmp_x_blockdev_insert_medium(bool has_device, const char *device,
2500 bool has_id, const char *id,
2501 const char *node_name, Error **errp)
2503 BlockBackend *blk;
2504 BlockDriverState *bs;
2506 blk = qmp_get_blk(has_device ? device : NULL,
2507 has_id ? id : NULL,
2508 errp);
2509 if (!blk) {
2510 return;
2513 bs = bdrv_find_node(node_name);
2514 if (!bs) {
2515 error_setg(errp, "Node '%s' not found", node_name);
2516 return;
2519 if (bdrv_has_blk(bs)) {
2520 error_setg(errp, "Node '%s' is already in use", node_name);
2521 return;
2524 qmp_blockdev_insert_anon_medium(blk, bs, errp);
2527 void qmp_blockdev_change_medium(bool has_device, const char *device,
2528 bool has_id, const char *id,
2529 const char *filename,
2530 bool has_format, const char *format,
2531 bool has_read_only,
2532 BlockdevChangeReadOnlyMode read_only,
2533 Error **errp)
2535 BlockBackend *blk;
2536 BlockDriverState *medium_bs = NULL;
2537 int bdrv_flags;
2538 bool detect_zeroes;
2539 int rc;
2540 QDict *options = NULL;
2541 Error *err = NULL;
2543 blk = qmp_get_blk(has_device ? device : NULL,
2544 has_id ? id : NULL,
2545 errp);
2546 if (!blk) {
2547 goto fail;
2550 if (blk_bs(blk)) {
2551 blk_update_root_state(blk);
2554 bdrv_flags = blk_get_open_flags_from_root_state(blk);
2555 bdrv_flags &= ~(BDRV_O_TEMPORARY | BDRV_O_SNAPSHOT | BDRV_O_NO_BACKING |
2556 BDRV_O_PROTOCOL);
2558 if (!has_read_only) {
2559 read_only = BLOCKDEV_CHANGE_READ_ONLY_MODE_RETAIN;
2562 switch (read_only) {
2563 case BLOCKDEV_CHANGE_READ_ONLY_MODE_RETAIN:
2564 break;
2566 case BLOCKDEV_CHANGE_READ_ONLY_MODE_READ_ONLY:
2567 bdrv_flags &= ~BDRV_O_RDWR;
2568 break;
2570 case BLOCKDEV_CHANGE_READ_ONLY_MODE_READ_WRITE:
2571 bdrv_flags |= BDRV_O_RDWR;
2572 break;
2574 default:
2575 abort();
2578 options = qdict_new();
2579 detect_zeroes = blk_get_detect_zeroes_from_root_state(blk);
2580 qdict_put(options, "detect-zeroes",
2581 qstring_from_str(detect_zeroes ? "on" : "off"));
2583 if (has_format) {
2584 qdict_put(options, "driver", qstring_from_str(format));
2587 medium_bs = bdrv_open(filename, NULL, options, bdrv_flags, errp);
2588 if (!medium_bs) {
2589 goto fail;
2592 bdrv_add_key(medium_bs, NULL, &err);
2593 if (err) {
2594 error_propagate(errp, err);
2595 goto fail;
2598 rc = do_open_tray(has_device ? device : NULL,
2599 has_id ? id : NULL,
2600 false, &err);
2601 if (rc && rc != -ENOSYS) {
2602 error_propagate(errp, err);
2603 goto fail;
2605 error_free(err);
2606 err = NULL;
2608 qmp_x_blockdev_remove_medium(has_device, device, has_id, id, &err);
2609 if (err) {
2610 error_propagate(errp, err);
2611 goto fail;
2614 qmp_blockdev_insert_anon_medium(blk, medium_bs, &err);
2615 if (err) {
2616 error_propagate(errp, err);
2617 goto fail;
2620 qmp_blockdev_close_tray(has_device, device, has_id, id, errp);
2622 fail:
2623 /* If the medium has been inserted, the device has its own reference, so
2624 * ours must be relinquished; and if it has not been inserted successfully,
2625 * the reference must be relinquished anyway */
2626 bdrv_unref(medium_bs);
2629 /* throttling disk I/O limits */
2630 void qmp_block_set_io_throttle(BlockIOThrottle *arg, Error **errp)
2632 ThrottleConfig cfg;
2633 BlockDriverState *bs;
2634 BlockBackend *blk;
2635 AioContext *aio_context;
2637 blk = qmp_get_blk(arg->has_device ? arg->device : NULL,
2638 arg->has_id ? arg->id : NULL,
2639 errp);
2640 if (!blk) {
2641 return;
2644 aio_context = blk_get_aio_context(blk);
2645 aio_context_acquire(aio_context);
2647 bs = blk_bs(blk);
2648 if (!bs) {
2649 error_setg(errp, "Device has no medium");
2650 goto out;
2653 throttle_config_init(&cfg);
2654 cfg.buckets[THROTTLE_BPS_TOTAL].avg = arg->bps;
2655 cfg.buckets[THROTTLE_BPS_READ].avg = arg->bps_rd;
2656 cfg.buckets[THROTTLE_BPS_WRITE].avg = arg->bps_wr;
2658 cfg.buckets[THROTTLE_OPS_TOTAL].avg = arg->iops;
2659 cfg.buckets[THROTTLE_OPS_READ].avg = arg->iops_rd;
2660 cfg.buckets[THROTTLE_OPS_WRITE].avg = arg->iops_wr;
2662 if (arg->has_bps_max) {
2663 cfg.buckets[THROTTLE_BPS_TOTAL].max = arg->bps_max;
2665 if (arg->has_bps_rd_max) {
2666 cfg.buckets[THROTTLE_BPS_READ].max = arg->bps_rd_max;
2668 if (arg->has_bps_wr_max) {
2669 cfg.buckets[THROTTLE_BPS_WRITE].max = arg->bps_wr_max;
2671 if (arg->has_iops_max) {
2672 cfg.buckets[THROTTLE_OPS_TOTAL].max = arg->iops_max;
2674 if (arg->has_iops_rd_max) {
2675 cfg.buckets[THROTTLE_OPS_READ].max = arg->iops_rd_max;
2677 if (arg->has_iops_wr_max) {
2678 cfg.buckets[THROTTLE_OPS_WRITE].max = arg->iops_wr_max;
2681 if (arg->has_bps_max_length) {
2682 cfg.buckets[THROTTLE_BPS_TOTAL].burst_length = arg->bps_max_length;
2684 if (arg->has_bps_rd_max_length) {
2685 cfg.buckets[THROTTLE_BPS_READ].burst_length = arg->bps_rd_max_length;
2687 if (arg->has_bps_wr_max_length) {
2688 cfg.buckets[THROTTLE_BPS_WRITE].burst_length = arg->bps_wr_max_length;
2690 if (arg->has_iops_max_length) {
2691 cfg.buckets[THROTTLE_OPS_TOTAL].burst_length = arg->iops_max_length;
2693 if (arg->has_iops_rd_max_length) {
2694 cfg.buckets[THROTTLE_OPS_READ].burst_length = arg->iops_rd_max_length;
2696 if (arg->has_iops_wr_max_length) {
2697 cfg.buckets[THROTTLE_OPS_WRITE].burst_length = arg->iops_wr_max_length;
2700 if (arg->has_iops_size) {
2701 cfg.op_size = arg->iops_size;
2704 if (!throttle_is_valid(&cfg, errp)) {
2705 goto out;
2708 if (throttle_enabled(&cfg)) {
2709 /* Enable I/O limits if they're not enabled yet, otherwise
2710 * just update the throttling group. */
2711 if (!blk_get_public(blk)->throttle_state) {
2712 blk_io_limits_enable(blk,
2713 arg->has_group ? arg->group :
2714 arg->has_device ? arg->device :
2715 arg->id);
2716 } else if (arg->has_group) {
2717 blk_io_limits_update_group(blk, arg->group);
2719 /* Set the new throttling configuration */
2720 blk_set_io_limits(blk, &cfg);
2721 } else if (blk_get_public(blk)->throttle_state) {
2722 /* If all throttling settings are set to 0, disable I/O limits */
2723 blk_io_limits_disable(blk);
2726 out:
2727 aio_context_release(aio_context);
2730 void qmp_block_dirty_bitmap_add(const char *node, const char *name,
2731 bool has_granularity, uint32_t granularity,
2732 Error **errp)
2734 AioContext *aio_context;
2735 BlockDriverState *bs;
2737 if (!name || name[0] == '\0') {
2738 error_setg(errp, "Bitmap name cannot be empty");
2739 return;
2742 bs = bdrv_lookup_bs(node, node, errp);
2743 if (!bs) {
2744 return;
2747 aio_context = bdrv_get_aio_context(bs);
2748 aio_context_acquire(aio_context);
2750 if (has_granularity) {
2751 if (granularity < 512 || !is_power_of_2(granularity)) {
2752 error_setg(errp, "Granularity must be power of 2 "
2753 "and at least 512");
2754 goto out;
2756 } else {
2757 /* Default to cluster size, if available: */
2758 granularity = bdrv_get_default_bitmap_granularity(bs);
2761 bdrv_create_dirty_bitmap(bs, granularity, name, errp);
2763 out:
2764 aio_context_release(aio_context);
2767 void qmp_block_dirty_bitmap_remove(const char *node, const char *name,
2768 Error **errp)
2770 AioContext *aio_context;
2771 BlockDriverState *bs;
2772 BdrvDirtyBitmap *bitmap;
2774 bitmap = block_dirty_bitmap_lookup(node, name, &bs, &aio_context, errp);
2775 if (!bitmap || !bs) {
2776 return;
2779 if (bdrv_dirty_bitmap_frozen(bitmap)) {
2780 error_setg(errp,
2781 "Bitmap '%s' is currently frozen and cannot be removed",
2782 name);
2783 goto out;
2785 bdrv_dirty_bitmap_make_anon(bitmap);
2786 bdrv_release_dirty_bitmap(bs, bitmap);
2788 out:
2789 aio_context_release(aio_context);
2793 * Completely clear a bitmap, for the purposes of synchronizing a bitmap
2794 * immediately after a full backup operation.
2796 void qmp_block_dirty_bitmap_clear(const char *node, const char *name,
2797 Error **errp)
2799 AioContext *aio_context;
2800 BdrvDirtyBitmap *bitmap;
2801 BlockDriverState *bs;
2803 bitmap = block_dirty_bitmap_lookup(node, name, &bs, &aio_context, errp);
2804 if (!bitmap || !bs) {
2805 return;
2808 if (bdrv_dirty_bitmap_frozen(bitmap)) {
2809 error_setg(errp,
2810 "Bitmap '%s' is currently frozen and cannot be modified",
2811 name);
2812 goto out;
2813 } else if (!bdrv_dirty_bitmap_enabled(bitmap)) {
2814 error_setg(errp,
2815 "Bitmap '%s' is currently disabled and cannot be cleared",
2816 name);
2817 goto out;
2820 bdrv_clear_dirty_bitmap(bitmap, NULL);
2822 out:
2823 aio_context_release(aio_context);
2826 void hmp_drive_del(Monitor *mon, const QDict *qdict)
2828 const char *id = qdict_get_str(qdict, "id");
2829 BlockBackend *blk;
2830 BlockDriverState *bs;
2831 AioContext *aio_context;
2832 Error *local_err = NULL;
2834 bs = bdrv_find_node(id);
2835 if (bs) {
2836 qmp_x_blockdev_del(id, &local_err);
2837 if (local_err) {
2838 error_report_err(local_err);
2840 return;
2843 blk = blk_by_name(id);
2844 if (!blk) {
2845 error_report("Device '%s' not found", id);
2846 return;
2849 if (!blk_legacy_dinfo(blk)) {
2850 error_report("Deleting device added with blockdev-add"
2851 " is not supported");
2852 return;
2855 aio_context = blk_get_aio_context(blk);
2856 aio_context_acquire(aio_context);
2858 bs = blk_bs(blk);
2859 if (bs) {
2860 if (bdrv_op_is_blocked(bs, BLOCK_OP_TYPE_DRIVE_DEL, &local_err)) {
2861 error_report_err(local_err);
2862 aio_context_release(aio_context);
2863 return;
2866 blk_remove_bs(blk);
2869 /* Make the BlockBackend and the attached BlockDriverState anonymous */
2870 monitor_remove_blk(blk);
2872 /* If this BlockBackend has a device attached to it, its refcount will be
2873 * decremented when the device is removed; otherwise we have to do so here.
2875 if (blk_get_attached_dev(blk)) {
2876 /* Further I/O must not pause the guest */
2877 blk_set_on_error(blk, BLOCKDEV_ON_ERROR_REPORT,
2878 BLOCKDEV_ON_ERROR_REPORT);
2879 } else {
2880 blk_unref(blk);
2883 aio_context_release(aio_context);
2886 void qmp_block_resize(bool has_device, const char *device,
2887 bool has_node_name, const char *node_name,
2888 int64_t size, Error **errp)
2890 Error *local_err = NULL;
2891 BlockBackend *blk = NULL;
2892 BlockDriverState *bs;
2893 AioContext *aio_context;
2894 int ret;
2896 bs = bdrv_lookup_bs(has_device ? device : NULL,
2897 has_node_name ? node_name : NULL,
2898 &local_err);
2899 if (local_err) {
2900 error_propagate(errp, local_err);
2901 return;
2904 aio_context = bdrv_get_aio_context(bs);
2905 aio_context_acquire(aio_context);
2907 if (!bdrv_is_first_non_filter(bs)) {
2908 error_setg(errp, QERR_FEATURE_DISABLED, "resize");
2909 goto out;
2912 if (size < 0) {
2913 error_setg(errp, QERR_INVALID_PARAMETER_VALUE, "size", "a >0 size");
2914 goto out;
2917 if (bdrv_op_is_blocked(bs, BLOCK_OP_TYPE_RESIZE, NULL)) {
2918 error_setg(errp, QERR_DEVICE_IN_USE, device);
2919 goto out;
2922 blk = blk_new(BLK_PERM_RESIZE, BLK_PERM_ALL);
2923 ret = blk_insert_bs(blk, bs, errp);
2924 if (ret < 0) {
2925 goto out;
2928 /* complete all in-flight operations before resizing the device */
2929 bdrv_drain_all();
2931 ret = blk_truncate(blk, size);
2932 switch (ret) {
2933 case 0:
2934 break;
2935 case -ENOMEDIUM:
2936 error_setg(errp, QERR_DEVICE_HAS_NO_MEDIUM, device);
2937 break;
2938 case -ENOTSUP:
2939 error_setg(errp, QERR_UNSUPPORTED);
2940 break;
2941 case -EACCES:
2942 error_setg(errp, "Device '%s' is read only", device);
2943 break;
2944 case -EBUSY:
2945 error_setg(errp, QERR_DEVICE_IN_USE, device);
2946 break;
2947 default:
2948 error_setg_errno(errp, -ret, "Could not resize");
2949 break;
2952 out:
2953 blk_unref(blk);
2954 aio_context_release(aio_context);
2957 void qmp_block_stream(bool has_job_id, const char *job_id, const char *device,
2958 bool has_base, const char *base,
2959 bool has_base_node, const char *base_node,
2960 bool has_backing_file, const char *backing_file,
2961 bool has_speed, int64_t speed,
2962 bool has_on_error, BlockdevOnError on_error,
2963 Error **errp)
2965 BlockDriverState *bs, *iter;
2966 BlockDriverState *base_bs = NULL;
2967 AioContext *aio_context;
2968 Error *local_err = NULL;
2969 const char *base_name = NULL;
2971 if (!has_on_error) {
2972 on_error = BLOCKDEV_ON_ERROR_REPORT;
2975 bs = bdrv_lookup_bs(device, device, errp);
2976 if (!bs) {
2977 return;
2980 aio_context = bdrv_get_aio_context(bs);
2981 aio_context_acquire(aio_context);
2983 if (has_base && has_base_node) {
2984 error_setg(errp, "'base' and 'base-node' cannot be specified "
2985 "at the same time");
2986 goto out;
2989 if (has_base) {
2990 base_bs = bdrv_find_backing_image(bs, base);
2991 if (base_bs == NULL) {
2992 error_setg(errp, QERR_BASE_NOT_FOUND, base);
2993 goto out;
2995 assert(bdrv_get_aio_context(base_bs) == aio_context);
2996 base_name = base;
2999 if (has_base_node) {
3000 base_bs = bdrv_lookup_bs(NULL, base_node, errp);
3001 if (!base_bs) {
3002 goto out;
3004 if (bs == base_bs || !bdrv_chain_contains(bs, base_bs)) {
3005 error_setg(errp, "Node '%s' is not a backing image of '%s'",
3006 base_node, device);
3007 goto out;
3009 assert(bdrv_get_aio_context(base_bs) == aio_context);
3010 base_name = base_bs->filename;
3013 /* Check for op blockers in the whole chain between bs and base */
3014 for (iter = bs; iter && iter != base_bs; iter = backing_bs(iter)) {
3015 if (bdrv_op_is_blocked(iter, BLOCK_OP_TYPE_STREAM, errp)) {
3016 goto out;
3020 /* if we are streaming the entire chain, the result will have no backing
3021 * file, and specifying one is therefore an error */
3022 if (base_bs == NULL && has_backing_file) {
3023 error_setg(errp, "backing file specified, but streaming the "
3024 "entire chain");
3025 goto out;
3028 /* backing_file string overrides base bs filename */
3029 base_name = has_backing_file ? backing_file : base_name;
3031 stream_start(has_job_id ? job_id : NULL, bs, base_bs, base_name,
3032 has_speed ? speed : 0, on_error, &local_err);
3033 if (local_err) {
3034 error_propagate(errp, local_err);
3035 goto out;
3038 trace_qmp_block_stream(bs, bs->job);
3040 out:
3041 aio_context_release(aio_context);
3044 void qmp_block_commit(bool has_job_id, const char *job_id, const char *device,
3045 bool has_base, const char *base,
3046 bool has_top, const char *top,
3047 bool has_backing_file, const char *backing_file,
3048 bool has_speed, int64_t speed,
3049 bool has_filter_node_name, const char *filter_node_name,
3050 Error **errp)
3052 BlockDriverState *bs;
3053 BlockDriverState *iter;
3054 BlockDriverState *base_bs, *top_bs;
3055 AioContext *aio_context;
3056 Error *local_err = NULL;
3057 /* This will be part of the QMP command, if/when the
3058 * BlockdevOnError change for blkmirror makes it in
3060 BlockdevOnError on_error = BLOCKDEV_ON_ERROR_REPORT;
3062 if (!has_speed) {
3063 speed = 0;
3065 if (!has_filter_node_name) {
3066 filter_node_name = NULL;
3069 /* Important Note:
3070 * libvirt relies on the DeviceNotFound error class in order to probe for
3071 * live commit feature versions; for this to work, we must make sure to
3072 * perform the device lookup before any generic errors that may occur in a
3073 * scenario in which all optional arguments are omitted. */
3074 bs = qmp_get_root_bs(device, &local_err);
3075 if (!bs) {
3076 bs = bdrv_lookup_bs(device, device, NULL);
3077 if (!bs) {
3078 error_free(local_err);
3079 error_set(errp, ERROR_CLASS_DEVICE_NOT_FOUND,
3080 "Device '%s' not found", device);
3081 } else {
3082 error_propagate(errp, local_err);
3084 return;
3087 aio_context = bdrv_get_aio_context(bs);
3088 aio_context_acquire(aio_context);
3090 if (bdrv_op_is_blocked(bs, BLOCK_OP_TYPE_COMMIT_SOURCE, errp)) {
3091 goto out;
3094 /* default top_bs is the active layer */
3095 top_bs = bs;
3097 if (has_top && top) {
3098 if (strcmp(bs->filename, top) != 0) {
3099 top_bs = bdrv_find_backing_image(bs, top);
3103 if (top_bs == NULL) {
3104 error_setg(errp, "Top image file %s not found", top ? top : "NULL");
3105 goto out;
3108 assert(bdrv_get_aio_context(top_bs) == aio_context);
3110 if (has_base && base) {
3111 base_bs = bdrv_find_backing_image(top_bs, base);
3112 } else {
3113 base_bs = bdrv_find_base(top_bs);
3116 if (base_bs == NULL) {
3117 error_setg(errp, QERR_BASE_NOT_FOUND, base ? base : "NULL");
3118 goto out;
3121 assert(bdrv_get_aio_context(base_bs) == aio_context);
3123 for (iter = top_bs; iter != backing_bs(base_bs); iter = backing_bs(iter)) {
3124 if (bdrv_op_is_blocked(iter, BLOCK_OP_TYPE_COMMIT_TARGET, errp)) {
3125 goto out;
3129 /* Do not allow attempts to commit an image into itself */
3130 if (top_bs == base_bs) {
3131 error_setg(errp, "cannot commit an image into itself");
3132 goto out;
3135 if (top_bs == bs) {
3136 if (has_backing_file) {
3137 error_setg(errp, "'backing-file' specified,"
3138 " but 'top' is the active layer");
3139 goto out;
3141 commit_active_start(has_job_id ? job_id : NULL, bs, base_bs,
3142 BLOCK_JOB_DEFAULT, speed, on_error,
3143 filter_node_name, NULL, NULL, &local_err, false);
3144 } else {
3145 BlockDriverState *overlay_bs = bdrv_find_overlay(bs, top_bs);
3146 if (bdrv_op_is_blocked(overlay_bs, BLOCK_OP_TYPE_COMMIT_TARGET, errp)) {
3147 goto out;
3149 commit_start(has_job_id ? job_id : NULL, bs, base_bs, top_bs, speed,
3150 on_error, has_backing_file ? backing_file : NULL,
3151 filter_node_name, &local_err);
3153 if (local_err != NULL) {
3154 error_propagate(errp, local_err);
3155 goto out;
3158 out:
3159 aio_context_release(aio_context);
3162 static BlockJob *do_drive_backup(DriveBackup *backup, BlockJobTxn *txn,
3163 Error **errp)
3165 BlockDriverState *bs;
3166 BlockDriverState *target_bs;
3167 BlockDriverState *source = NULL;
3168 BlockJob *job = NULL;
3169 BdrvDirtyBitmap *bmap = NULL;
3170 AioContext *aio_context;
3171 QDict *options = NULL;
3172 Error *local_err = NULL;
3173 int flags;
3174 int64_t size;
3176 if (!backup->has_speed) {
3177 backup->speed = 0;
3179 if (!backup->has_on_source_error) {
3180 backup->on_source_error = BLOCKDEV_ON_ERROR_REPORT;
3182 if (!backup->has_on_target_error) {
3183 backup->on_target_error = BLOCKDEV_ON_ERROR_REPORT;
3185 if (!backup->has_mode) {
3186 backup->mode = NEW_IMAGE_MODE_ABSOLUTE_PATHS;
3188 if (!backup->has_job_id) {
3189 backup->job_id = NULL;
3191 if (!backup->has_compress) {
3192 backup->compress = false;
3195 bs = qmp_get_root_bs(backup->device, errp);
3196 if (!bs) {
3197 return NULL;
3200 aio_context = bdrv_get_aio_context(bs);
3201 aio_context_acquire(aio_context);
3203 if (!backup->has_format) {
3204 backup->format = backup->mode == NEW_IMAGE_MODE_EXISTING ?
3205 NULL : (char*) bs->drv->format_name;
3208 /* Early check to avoid creating target */
3209 if (bdrv_op_is_blocked(bs, BLOCK_OP_TYPE_BACKUP_SOURCE, errp)) {
3210 goto out;
3213 flags = bs->open_flags | BDRV_O_RDWR;
3215 /* See if we have a backing HD we can use to create our new image
3216 * on top of. */
3217 if (backup->sync == MIRROR_SYNC_MODE_TOP) {
3218 source = backing_bs(bs);
3219 if (!source) {
3220 backup->sync = MIRROR_SYNC_MODE_FULL;
3223 if (backup->sync == MIRROR_SYNC_MODE_NONE) {
3224 source = bs;
3227 size = bdrv_getlength(bs);
3228 if (size < 0) {
3229 error_setg_errno(errp, -size, "bdrv_getlength failed");
3230 goto out;
3233 if (backup->mode != NEW_IMAGE_MODE_EXISTING) {
3234 assert(backup->format);
3235 if (source) {
3236 bdrv_img_create(backup->target, backup->format, source->filename,
3237 source->drv->format_name, NULL,
3238 size, flags, &local_err, false);
3239 } else {
3240 bdrv_img_create(backup->target, backup->format, NULL, NULL, NULL,
3241 size, flags, &local_err, false);
3245 if (local_err) {
3246 error_propagate(errp, local_err);
3247 goto out;
3250 if (backup->format) {
3251 options = qdict_new();
3252 qdict_put(options, "driver", qstring_from_str(backup->format));
3255 target_bs = bdrv_open(backup->target, NULL, options, flags, errp);
3256 if (!target_bs) {
3257 goto out;
3260 bdrv_set_aio_context(target_bs, aio_context);
3262 if (backup->has_bitmap) {
3263 bmap = bdrv_find_dirty_bitmap(bs, backup->bitmap);
3264 if (!bmap) {
3265 error_setg(errp, "Bitmap '%s' could not be found", backup->bitmap);
3266 bdrv_unref(target_bs);
3267 goto out;
3271 job = backup_job_create(backup->job_id, bs, target_bs, backup->speed,
3272 backup->sync, bmap, backup->compress,
3273 backup->on_source_error, backup->on_target_error,
3274 BLOCK_JOB_DEFAULT, NULL, NULL, txn, &local_err);
3275 bdrv_unref(target_bs);
3276 if (local_err != NULL) {
3277 error_propagate(errp, local_err);
3278 goto out;
3281 out:
3282 aio_context_release(aio_context);
3283 return job;
3286 void qmp_drive_backup(DriveBackup *arg, Error **errp)
3289 BlockJob *job;
3290 job = do_drive_backup(arg, NULL, errp);
3291 if (job) {
3292 block_job_start(job);
3296 BlockDeviceInfoList *qmp_query_named_block_nodes(Error **errp)
3298 return bdrv_named_nodes_list(errp);
3301 BlockJob *do_blockdev_backup(BlockdevBackup *backup, BlockJobTxn *txn,
3302 Error **errp)
3304 BlockDriverState *bs;
3305 BlockDriverState *target_bs;
3306 Error *local_err = NULL;
3307 AioContext *aio_context;
3308 BlockJob *job = NULL;
3310 if (!backup->has_speed) {
3311 backup->speed = 0;
3313 if (!backup->has_on_source_error) {
3314 backup->on_source_error = BLOCKDEV_ON_ERROR_REPORT;
3316 if (!backup->has_on_target_error) {
3317 backup->on_target_error = BLOCKDEV_ON_ERROR_REPORT;
3319 if (!backup->has_job_id) {
3320 backup->job_id = NULL;
3322 if (!backup->has_compress) {
3323 backup->compress = false;
3326 bs = qmp_get_root_bs(backup->device, errp);
3327 if (!bs) {
3328 return NULL;
3331 aio_context = bdrv_get_aio_context(bs);
3332 aio_context_acquire(aio_context);
3334 target_bs = bdrv_lookup_bs(backup->target, backup->target, errp);
3335 if (!target_bs) {
3336 goto out;
3339 if (bdrv_get_aio_context(target_bs) != aio_context) {
3340 if (!bdrv_has_blk(target_bs)) {
3341 /* The target BDS is not attached, we can safely move it to another
3342 * AioContext. */
3343 bdrv_set_aio_context(target_bs, aio_context);
3344 } else {
3345 error_setg(errp, "Target is attached to a different thread from "
3346 "source.");
3347 goto out;
3350 job = backup_job_create(backup->job_id, bs, target_bs, backup->speed,
3351 backup->sync, NULL, backup->compress,
3352 backup->on_source_error, backup->on_target_error,
3353 BLOCK_JOB_DEFAULT, NULL, NULL, txn, &local_err);
3354 if (local_err != NULL) {
3355 error_propagate(errp, local_err);
3357 out:
3358 aio_context_release(aio_context);
3359 return job;
3362 void qmp_blockdev_backup(BlockdevBackup *arg, Error **errp)
3364 BlockJob *job;
3365 job = do_blockdev_backup(arg, NULL, errp);
3366 if (job) {
3367 block_job_start(job);
3371 /* Parameter check and block job starting for drive mirroring.
3372 * Caller should hold @device and @target's aio context (must be the same).
3374 static void blockdev_mirror_common(const char *job_id, BlockDriverState *bs,
3375 BlockDriverState *target,
3376 bool has_replaces, const char *replaces,
3377 enum MirrorSyncMode sync,
3378 BlockMirrorBackingMode backing_mode,
3379 bool has_speed, int64_t speed,
3380 bool has_granularity, uint32_t granularity,
3381 bool has_buf_size, int64_t buf_size,
3382 bool has_on_source_error,
3383 BlockdevOnError on_source_error,
3384 bool has_on_target_error,
3385 BlockdevOnError on_target_error,
3386 bool has_unmap, bool unmap,
3387 bool has_filter_node_name,
3388 const char *filter_node_name,
3389 Error **errp)
3392 if (!has_speed) {
3393 speed = 0;
3395 if (!has_on_source_error) {
3396 on_source_error = BLOCKDEV_ON_ERROR_REPORT;
3398 if (!has_on_target_error) {
3399 on_target_error = BLOCKDEV_ON_ERROR_REPORT;
3401 if (!has_granularity) {
3402 granularity = 0;
3404 if (!has_buf_size) {
3405 buf_size = 0;
3407 if (!has_unmap) {
3408 unmap = true;
3410 if (!has_filter_node_name) {
3411 filter_node_name = NULL;
3414 if (granularity != 0 && (granularity < 512 || granularity > 1048576 * 64)) {
3415 error_setg(errp, QERR_INVALID_PARAMETER_VALUE, "granularity",
3416 "a value in range [512B, 64MB]");
3417 return;
3419 if (granularity & (granularity - 1)) {
3420 error_setg(errp, QERR_INVALID_PARAMETER_VALUE, "granularity",
3421 "power of 2");
3422 return;
3425 if (bdrv_op_is_blocked(bs, BLOCK_OP_TYPE_MIRROR_SOURCE, errp)) {
3426 return;
3428 if (bdrv_op_is_blocked(target, BLOCK_OP_TYPE_MIRROR_TARGET, errp)) {
3429 return;
3432 if (!bs->backing && sync == MIRROR_SYNC_MODE_TOP) {
3433 sync = MIRROR_SYNC_MODE_FULL;
3436 /* pass the node name to replace to mirror start since it's loose coupling
3437 * and will allow to check whether the node still exist at mirror completion
3439 mirror_start(job_id, bs, target,
3440 has_replaces ? replaces : NULL,
3441 speed, granularity, buf_size, sync, backing_mode,
3442 on_source_error, on_target_error, unmap, filter_node_name,
3443 errp);
3446 void qmp_drive_mirror(DriveMirror *arg, Error **errp)
3448 BlockDriverState *bs;
3449 BlockDriverState *source, *target_bs;
3450 AioContext *aio_context;
3451 BlockMirrorBackingMode backing_mode;
3452 Error *local_err = NULL;
3453 QDict *options = NULL;
3454 int flags;
3455 int64_t size;
3456 const char *format = arg->format;
3458 bs = qmp_get_root_bs(arg->device, errp);
3459 if (!bs) {
3460 return;
3463 aio_context = bdrv_get_aio_context(bs);
3464 aio_context_acquire(aio_context);
3466 if (!arg->has_mode) {
3467 arg->mode = NEW_IMAGE_MODE_ABSOLUTE_PATHS;
3470 if (!arg->has_format) {
3471 format = (arg->mode == NEW_IMAGE_MODE_EXISTING
3472 ? NULL : bs->drv->format_name);
3475 flags = bs->open_flags | BDRV_O_RDWR;
3476 source = backing_bs(bs);
3477 if (!source && arg->sync == MIRROR_SYNC_MODE_TOP) {
3478 arg->sync = MIRROR_SYNC_MODE_FULL;
3480 if (arg->sync == MIRROR_SYNC_MODE_NONE) {
3481 source = bs;
3484 size = bdrv_getlength(bs);
3485 if (size < 0) {
3486 error_setg_errno(errp, -size, "bdrv_getlength failed");
3487 goto out;
3490 if (arg->has_replaces) {
3491 BlockDriverState *to_replace_bs;
3492 AioContext *replace_aio_context;
3493 int64_t replace_size;
3495 if (!arg->has_node_name) {
3496 error_setg(errp, "a node-name must be provided when replacing a"
3497 " named node of the graph");
3498 goto out;
3501 to_replace_bs = check_to_replace_node(bs, arg->replaces, &local_err);
3503 if (!to_replace_bs) {
3504 error_propagate(errp, local_err);
3505 goto out;
3508 replace_aio_context = bdrv_get_aio_context(to_replace_bs);
3509 aio_context_acquire(replace_aio_context);
3510 replace_size = bdrv_getlength(to_replace_bs);
3511 aio_context_release(replace_aio_context);
3513 if (size != replace_size) {
3514 error_setg(errp, "cannot replace image with a mirror image of "
3515 "different size");
3516 goto out;
3520 if (arg->mode == NEW_IMAGE_MODE_ABSOLUTE_PATHS) {
3521 backing_mode = MIRROR_SOURCE_BACKING_CHAIN;
3522 } else {
3523 backing_mode = MIRROR_OPEN_BACKING_CHAIN;
3526 if ((arg->sync == MIRROR_SYNC_MODE_FULL || !source)
3527 && arg->mode != NEW_IMAGE_MODE_EXISTING)
3529 /* create new image w/o backing file */
3530 assert(format);
3531 bdrv_img_create(arg->target, format,
3532 NULL, NULL, NULL, size, flags, &local_err, false);
3533 } else {
3534 switch (arg->mode) {
3535 case NEW_IMAGE_MODE_EXISTING:
3536 break;
3537 case NEW_IMAGE_MODE_ABSOLUTE_PATHS:
3538 /* create new image with backing file */
3539 bdrv_img_create(arg->target, format,
3540 source->filename,
3541 source->drv->format_name,
3542 NULL, size, flags, &local_err, false);
3543 break;
3544 default:
3545 abort();
3549 if (local_err) {
3550 error_propagate(errp, local_err);
3551 goto out;
3554 options = qdict_new();
3555 if (arg->has_node_name) {
3556 qdict_put(options, "node-name", qstring_from_str(arg->node_name));
3558 if (format) {
3559 qdict_put(options, "driver", qstring_from_str(format));
3562 /* Mirroring takes care of copy-on-write using the source's backing
3563 * file.
3565 target_bs = bdrv_open(arg->target, NULL, options,
3566 flags | BDRV_O_NO_BACKING, errp);
3567 if (!target_bs) {
3568 goto out;
3571 bdrv_set_aio_context(target_bs, aio_context);
3573 blockdev_mirror_common(arg->has_job_id ? arg->job_id : NULL, bs, target_bs,
3574 arg->has_replaces, arg->replaces, arg->sync,
3575 backing_mode, arg->has_speed, arg->speed,
3576 arg->has_granularity, arg->granularity,
3577 arg->has_buf_size, arg->buf_size,
3578 arg->has_on_source_error, arg->on_source_error,
3579 arg->has_on_target_error, arg->on_target_error,
3580 arg->has_unmap, arg->unmap,
3581 false, NULL,
3582 &local_err);
3583 bdrv_unref(target_bs);
3584 error_propagate(errp, local_err);
3585 out:
3586 aio_context_release(aio_context);
3589 void qmp_blockdev_mirror(bool has_job_id, const char *job_id,
3590 const char *device, const char *target,
3591 bool has_replaces, const char *replaces,
3592 MirrorSyncMode sync,
3593 bool has_speed, int64_t speed,
3594 bool has_granularity, uint32_t granularity,
3595 bool has_buf_size, int64_t buf_size,
3596 bool has_on_source_error,
3597 BlockdevOnError on_source_error,
3598 bool has_on_target_error,
3599 BlockdevOnError on_target_error,
3600 bool has_filter_node_name,
3601 const char *filter_node_name,
3602 Error **errp)
3604 BlockDriverState *bs;
3605 BlockDriverState *target_bs;
3606 AioContext *aio_context;
3607 BlockMirrorBackingMode backing_mode = MIRROR_LEAVE_BACKING_CHAIN;
3608 Error *local_err = NULL;
3610 bs = qmp_get_root_bs(device, errp);
3611 if (!bs) {
3612 return;
3615 target_bs = bdrv_lookup_bs(target, target, errp);
3616 if (!target_bs) {
3617 return;
3620 aio_context = bdrv_get_aio_context(bs);
3621 aio_context_acquire(aio_context);
3623 bdrv_set_aio_context(target_bs, aio_context);
3625 blockdev_mirror_common(has_job_id ? job_id : NULL, bs, target_bs,
3626 has_replaces, replaces, sync, backing_mode,
3627 has_speed, speed,
3628 has_granularity, granularity,
3629 has_buf_size, buf_size,
3630 has_on_source_error, on_source_error,
3631 has_on_target_error, on_target_error,
3632 true, true,
3633 has_filter_node_name, filter_node_name,
3634 &local_err);
3635 error_propagate(errp, local_err);
3637 aio_context_release(aio_context);
3640 /* Get a block job using its ID and acquire its AioContext */
3641 static BlockJob *find_block_job(const char *id, AioContext **aio_context,
3642 Error **errp)
3644 BlockJob *job;
3646 assert(id != NULL);
3648 *aio_context = NULL;
3650 job = block_job_get(id);
3652 if (!job) {
3653 error_set(errp, ERROR_CLASS_DEVICE_NOT_ACTIVE,
3654 "Block job '%s' not found", id);
3655 return NULL;
3658 *aio_context = blk_get_aio_context(job->blk);
3659 aio_context_acquire(*aio_context);
3661 return job;
3664 void qmp_block_job_set_speed(const char *device, int64_t speed, Error **errp)
3666 AioContext *aio_context;
3667 BlockJob *job = find_block_job(device, &aio_context, errp);
3669 if (!job) {
3670 return;
3673 block_job_set_speed(job, speed, errp);
3674 aio_context_release(aio_context);
3677 void qmp_block_job_cancel(const char *device,
3678 bool has_force, bool force, Error **errp)
3680 AioContext *aio_context;
3681 BlockJob *job = find_block_job(device, &aio_context, errp);
3683 if (!job) {
3684 return;
3687 if (!has_force) {
3688 force = false;
3691 if (block_job_user_paused(job) && !force) {
3692 error_setg(errp, "The block job for device '%s' is currently paused",
3693 device);
3694 goto out;
3697 trace_qmp_block_job_cancel(job);
3698 block_job_cancel(job);
3699 out:
3700 aio_context_release(aio_context);
3703 void qmp_block_job_pause(const char *device, Error **errp)
3705 AioContext *aio_context;
3706 BlockJob *job = find_block_job(device, &aio_context, errp);
3708 if (!job || block_job_user_paused(job)) {
3709 return;
3712 trace_qmp_block_job_pause(job);
3713 block_job_user_pause(job);
3714 aio_context_release(aio_context);
3717 void qmp_block_job_resume(const char *device, Error **errp)
3719 AioContext *aio_context;
3720 BlockJob *job = find_block_job(device, &aio_context, errp);
3722 if (!job || !block_job_user_paused(job)) {
3723 return;
3726 trace_qmp_block_job_resume(job);
3727 block_job_iostatus_reset(job);
3728 block_job_user_resume(job);
3729 aio_context_release(aio_context);
3732 void qmp_block_job_complete(const char *device, Error **errp)
3734 AioContext *aio_context;
3735 BlockJob *job = find_block_job(device, &aio_context, errp);
3737 if (!job) {
3738 return;
3741 trace_qmp_block_job_complete(job);
3742 block_job_complete(job, errp);
3743 aio_context_release(aio_context);
3746 void qmp_change_backing_file(const char *device,
3747 const char *image_node_name,
3748 const char *backing_file,
3749 Error **errp)
3751 BlockDriverState *bs = NULL;
3752 AioContext *aio_context;
3753 BlockDriverState *image_bs = NULL;
3754 Error *local_err = NULL;
3755 bool ro;
3756 int open_flags;
3757 int ret;
3759 bs = qmp_get_root_bs(device, errp);
3760 if (!bs) {
3761 return;
3764 aio_context = bdrv_get_aio_context(bs);
3765 aio_context_acquire(aio_context);
3767 image_bs = bdrv_lookup_bs(NULL, image_node_name, &local_err);
3768 if (local_err) {
3769 error_propagate(errp, local_err);
3770 goto out;
3773 if (!image_bs) {
3774 error_setg(errp, "image file not found");
3775 goto out;
3778 if (bdrv_find_base(image_bs) == image_bs) {
3779 error_setg(errp, "not allowing backing file change on an image "
3780 "without a backing file");
3781 goto out;
3784 /* even though we are not necessarily operating on bs, we need it to
3785 * determine if block ops are currently prohibited on the chain */
3786 if (bdrv_op_is_blocked(bs, BLOCK_OP_TYPE_CHANGE, errp)) {
3787 goto out;
3790 /* final sanity check */
3791 if (!bdrv_chain_contains(bs, image_bs)) {
3792 error_setg(errp, "'%s' and image file are not in the same chain",
3793 device);
3794 goto out;
3797 /* if not r/w, reopen to make r/w */
3798 open_flags = image_bs->open_flags;
3799 ro = bdrv_is_read_only(image_bs);
3801 if (ro) {
3802 bdrv_reopen(image_bs, open_flags | BDRV_O_RDWR, &local_err);
3803 if (local_err) {
3804 error_propagate(errp, local_err);
3805 goto out;
3809 ret = bdrv_change_backing_file(image_bs, backing_file,
3810 image_bs->drv ? image_bs->drv->format_name : "");
3812 if (ret < 0) {
3813 error_setg_errno(errp, -ret, "Could not change backing file to '%s'",
3814 backing_file);
3815 /* don't exit here, so we can try to restore open flags if
3816 * appropriate */
3819 if (ro) {
3820 bdrv_reopen(image_bs, open_flags, &local_err);
3821 error_propagate(errp, local_err);
3824 out:
3825 aio_context_release(aio_context);
3828 void hmp_drive_add_node(Monitor *mon, const char *optstr)
3830 QemuOpts *opts;
3831 QDict *qdict;
3832 Error *local_err = NULL;
3834 opts = qemu_opts_parse_noisily(&qemu_drive_opts, optstr, false);
3835 if (!opts) {
3836 return;
3839 qdict = qemu_opts_to_qdict(opts, NULL);
3841 if (!qdict_get_try_str(qdict, "node-name")) {
3842 QDECREF(qdict);
3843 error_report("'node-name' needs to be specified");
3844 goto out;
3847 BlockDriverState *bs = bds_tree_init(qdict, &local_err);
3848 if (!bs) {
3849 error_report_err(local_err);
3850 goto out;
3853 QTAILQ_INSERT_TAIL(&monitor_bdrv_states, bs, monitor_list);
3855 out:
3856 qemu_opts_del(opts);
3859 void qmp_blockdev_add(BlockdevOptions *options, Error **errp)
3861 BlockDriverState *bs;
3862 QObject *obj;
3863 Visitor *v = qobject_output_visitor_new(&obj);
3864 QDict *qdict;
3865 Error *local_err = NULL;
3867 visit_type_BlockdevOptions(v, NULL, &options, &local_err);
3868 if (local_err) {
3869 error_propagate(errp, local_err);
3870 goto fail;
3873 visit_complete(v, &obj);
3874 qdict = qobject_to_qdict(obj);
3876 qdict_flatten(qdict);
3878 if (!qdict_get_try_str(qdict, "node-name")) {
3879 error_setg(errp, "'node-name' must be specified for the root node");
3880 goto fail;
3883 bs = bds_tree_init(qdict, errp);
3884 if (!bs) {
3885 goto fail;
3888 QTAILQ_INSERT_TAIL(&monitor_bdrv_states, bs, monitor_list);
3890 if (bs && bdrv_key_required(bs)) {
3891 QTAILQ_REMOVE(&monitor_bdrv_states, bs, monitor_list);
3892 bdrv_unref(bs);
3893 error_setg(errp, "blockdev-add doesn't support encrypted devices");
3894 goto fail;
3897 fail:
3898 visit_free(v);
3901 void qmp_x_blockdev_del(const char *node_name, Error **errp)
3903 AioContext *aio_context;
3904 BlockDriverState *bs;
3906 bs = bdrv_find_node(node_name);
3907 if (!bs) {
3908 error_setg(errp, "Cannot find node %s", node_name);
3909 return;
3911 if (bdrv_has_blk(bs)) {
3912 error_setg(errp, "Node %s is in use", node_name);
3913 return;
3915 aio_context = bdrv_get_aio_context(bs);
3916 aio_context_acquire(aio_context);
3918 if (bdrv_op_is_blocked(bs, BLOCK_OP_TYPE_DRIVE_DEL, errp)) {
3919 goto out;
3922 if (!bs->monitor_list.tqe_prev) {
3923 error_setg(errp, "Node %s is not owned by the monitor",
3924 bs->node_name);
3925 goto out;
3928 if (bs->refcnt > 1) {
3929 error_setg(errp, "Block device %s is in use",
3930 bdrv_get_device_or_node_name(bs));
3931 goto out;
3934 QTAILQ_REMOVE(&monitor_bdrv_states, bs, monitor_list);
3935 bdrv_unref(bs);
3937 out:
3938 aio_context_release(aio_context);
3941 static BdrvChild *bdrv_find_child(BlockDriverState *parent_bs,
3942 const char *child_name)
3944 BdrvChild *child;
3946 QLIST_FOREACH(child, &parent_bs->children, next) {
3947 if (strcmp(child->name, child_name) == 0) {
3948 return child;
3952 return NULL;
3955 void qmp_x_blockdev_change(const char *parent, bool has_child,
3956 const char *child, bool has_node,
3957 const char *node, Error **errp)
3959 BlockDriverState *parent_bs, *new_bs = NULL;
3960 BdrvChild *p_child;
3962 parent_bs = bdrv_lookup_bs(parent, parent, errp);
3963 if (!parent_bs) {
3964 return;
3967 if (has_child == has_node) {
3968 if (has_child) {
3969 error_setg(errp, "The parameters child and node are in conflict");
3970 } else {
3971 error_setg(errp, "Either child or node must be specified");
3973 return;
3976 if (has_child) {
3977 p_child = bdrv_find_child(parent_bs, child);
3978 if (!p_child) {
3979 error_setg(errp, "Node '%s' does not have child '%s'",
3980 parent, child);
3981 return;
3983 bdrv_del_child(parent_bs, p_child, errp);
3986 if (has_node) {
3987 new_bs = bdrv_find_node(node);
3988 if (!new_bs) {
3989 error_setg(errp, "Node '%s' not found", node);
3990 return;
3992 bdrv_add_child(parent_bs, new_bs, errp);
3996 BlockJobInfoList *qmp_query_block_jobs(Error **errp)
3998 BlockJobInfoList *head = NULL, **p_next = &head;
3999 BlockJob *job;
4001 for (job = block_job_next(NULL); job; job = block_job_next(job)) {
4002 BlockJobInfoList *elem;
4003 AioContext *aio_context;
4005 if (block_job_is_internal(job)) {
4006 continue;
4008 elem = g_new0(BlockJobInfoList, 1);
4009 aio_context = blk_get_aio_context(job->blk);
4010 aio_context_acquire(aio_context);
4011 elem->value = block_job_query(job, errp);
4012 aio_context_release(aio_context);
4013 if (!elem->value) {
4014 g_free(elem);
4015 qapi_free_BlockJobInfoList(head);
4016 return NULL;
4018 *p_next = elem;
4019 p_next = &elem->next;
4022 return head;
4025 QemuOptsList qemu_common_drive_opts = {
4026 .name = "drive",
4027 .head = QTAILQ_HEAD_INITIALIZER(qemu_common_drive_opts.head),
4028 .desc = {
4030 .name = "snapshot",
4031 .type = QEMU_OPT_BOOL,
4032 .help = "enable/disable snapshot mode",
4034 .name = "aio",
4035 .type = QEMU_OPT_STRING,
4036 .help = "host AIO implementation (threads, native)",
4038 .name = BDRV_OPT_CACHE_WB,
4039 .type = QEMU_OPT_BOOL,
4040 .help = "Enable writeback mode",
4042 .name = "format",
4043 .type = QEMU_OPT_STRING,
4044 .help = "disk format (raw, qcow2, ...)",
4046 .name = "rerror",
4047 .type = QEMU_OPT_STRING,
4048 .help = "read error action",
4050 .name = "werror",
4051 .type = QEMU_OPT_STRING,
4052 .help = "write error action",
4054 .name = BDRV_OPT_READ_ONLY,
4055 .type = QEMU_OPT_BOOL,
4056 .help = "open drive file as read-only",
4059 THROTTLE_OPTS,
4062 .name = "throttling.group",
4063 .type = QEMU_OPT_STRING,
4064 .help = "name of the block throttling group",
4066 .name = "copy-on-read",
4067 .type = QEMU_OPT_BOOL,
4068 .help = "copy read data from backing file into image file",
4070 .name = "detect-zeroes",
4071 .type = QEMU_OPT_STRING,
4072 .help = "try to optimize zero writes (off, on, unmap)",
4074 .name = "stats-account-invalid",
4075 .type = QEMU_OPT_BOOL,
4076 .help = "whether to account for invalid I/O operations "
4077 "in the statistics",
4079 .name = "stats-account-failed",
4080 .type = QEMU_OPT_BOOL,
4081 .help = "whether to account for failed I/O operations "
4082 "in the statistics",
4084 { /* end of list */ }
4088 QemuOptsList qemu_drive_opts = {
4089 .name = "drive",
4090 .head = QTAILQ_HEAD_INITIALIZER(qemu_drive_opts.head),
4091 .desc = {
4093 * no elements => accept any params
4094 * validation will happen later
4096 { /* end of list */ }