block: Accept node-name for blockdev-snapshot-internal-sync
[qemu.git] / blockdev.c
blobf775bbdf9dd5dfee225e4e6dbf8e0d840ee62905
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/qmp-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 "trace.h"
52 #include "sysemu/arch_init.h"
53 #include "qemu/cutils.h"
54 #include "qemu/help_option.h"
56 static QTAILQ_HEAD(, BlockDriverState) monitor_bdrv_states =
57 QTAILQ_HEAD_INITIALIZER(monitor_bdrv_states);
59 static int do_open_tray(const char *device, bool force, Error **errp);
61 static const char *const if_name[IF_COUNT] = {
62 [IF_NONE] = "none",
63 [IF_IDE] = "ide",
64 [IF_SCSI] = "scsi",
65 [IF_FLOPPY] = "floppy",
66 [IF_PFLASH] = "pflash",
67 [IF_MTD] = "mtd",
68 [IF_SD] = "sd",
69 [IF_VIRTIO] = "virtio",
70 [IF_XEN] = "xen",
73 static int if_max_devs[IF_COUNT] = {
75 * Do not change these numbers! They govern how drive option
76 * index maps to unit and bus. That mapping is ABI.
78 * All controllers used to implement if=T drives need to support
79 * if_max_devs[T] units, for any T with if_max_devs[T] != 0.
80 * Otherwise, some index values map to "impossible" bus, unit
81 * values.
83 * For instance, if you change [IF_SCSI] to 255, -drive
84 * if=scsi,index=12 no longer means bus=1,unit=5, but
85 * bus=0,unit=12. With an lsi53c895a controller (7 units max),
86 * the drive can't be set up. Regression.
88 [IF_IDE] = 2,
89 [IF_SCSI] = 7,
92 /**
93 * Boards may call this to offer board-by-board overrides
94 * of the default, global values.
96 void override_max_devs(BlockInterfaceType type, int max_devs)
98 BlockBackend *blk;
99 DriveInfo *dinfo;
101 if (max_devs <= 0) {
102 return;
105 for (blk = blk_next(NULL); blk; blk = blk_next(blk)) {
106 dinfo = blk_legacy_dinfo(blk);
107 if (dinfo->type == type) {
108 fprintf(stderr, "Cannot override units-per-bus property of"
109 " the %s interface, because a drive of that type has"
110 " already been added.\n", if_name[type]);
111 g_assert_not_reached();
115 if_max_devs[type] = max_devs;
119 * We automatically delete the drive when a device using it gets
120 * unplugged. Questionable feature, but we can't just drop it.
121 * Device models call blockdev_mark_auto_del() to schedule the
122 * automatic deletion, and generic qdev code calls blockdev_auto_del()
123 * when deletion is actually safe.
125 void blockdev_mark_auto_del(BlockBackend *blk)
127 DriveInfo *dinfo = blk_legacy_dinfo(blk);
128 BlockDriverState *bs = blk_bs(blk);
129 AioContext *aio_context;
131 if (!dinfo) {
132 return;
135 if (bs) {
136 aio_context = bdrv_get_aio_context(bs);
137 aio_context_acquire(aio_context);
139 if (bs->job) {
140 block_job_cancel(bs->job);
143 aio_context_release(aio_context);
146 dinfo->auto_del = 1;
149 void blockdev_auto_del(BlockBackend *blk)
151 DriveInfo *dinfo = blk_legacy_dinfo(blk);
153 if (dinfo && dinfo->auto_del) {
154 monitor_remove_blk(blk);
155 blk_unref(blk);
160 * Returns the current mapping of how many units per bus
161 * a particular interface can support.
163 * A positive integer indicates n units per bus.
164 * 0 implies the mapping has not been established.
165 * -1 indicates an invalid BlockInterfaceType was given.
167 int drive_get_max_devs(BlockInterfaceType type)
169 if (type >= IF_IDE && type < IF_COUNT) {
170 return if_max_devs[type];
173 return -1;
176 static int drive_index_to_bus_id(BlockInterfaceType type, int index)
178 int max_devs = if_max_devs[type];
179 return max_devs ? index / max_devs : 0;
182 static int drive_index_to_unit_id(BlockInterfaceType type, int index)
184 int max_devs = if_max_devs[type];
185 return max_devs ? index % max_devs : index;
188 QemuOpts *drive_def(const char *optstr)
190 return qemu_opts_parse_noisily(qemu_find_opts("drive"), optstr, false);
193 QemuOpts *drive_add(BlockInterfaceType type, int index, const char *file,
194 const char *optstr)
196 QemuOpts *opts;
198 opts = drive_def(optstr);
199 if (!opts) {
200 return NULL;
202 if (type != IF_DEFAULT) {
203 qemu_opt_set(opts, "if", if_name[type], &error_abort);
205 if (index >= 0) {
206 qemu_opt_set_number(opts, "index", index, &error_abort);
208 if (file)
209 qemu_opt_set(opts, "file", file, &error_abort);
210 return opts;
213 DriveInfo *drive_get(BlockInterfaceType type, int bus, int unit)
215 BlockBackend *blk;
216 DriveInfo *dinfo;
218 for (blk = blk_next(NULL); blk; blk = blk_next(blk)) {
219 dinfo = blk_legacy_dinfo(blk);
220 if (dinfo && dinfo->type == type
221 && dinfo->bus == bus && dinfo->unit == unit) {
222 return dinfo;
226 return NULL;
229 bool drive_check_orphaned(void)
231 BlockBackend *blk;
232 DriveInfo *dinfo;
233 bool rs = false;
235 for (blk = blk_next(NULL); blk; blk = blk_next(blk)) {
236 dinfo = blk_legacy_dinfo(blk);
237 /* If dinfo->bdrv->dev is NULL, it has no device attached. */
238 /* Unless this is a default drive, this may be an oversight. */
239 if (!blk_get_attached_dev(blk) && !dinfo->is_default &&
240 dinfo->type != IF_NONE) {
241 fprintf(stderr, "Warning: Orphaned drive without device: "
242 "id=%s,file=%s,if=%s,bus=%d,unit=%d\n",
243 blk_name(blk), blk_bs(blk) ? blk_bs(blk)->filename : "",
244 if_name[dinfo->type], dinfo->bus, dinfo->unit);
245 rs = true;
249 return rs;
252 DriveInfo *drive_get_by_index(BlockInterfaceType type, int index)
254 return drive_get(type,
255 drive_index_to_bus_id(type, index),
256 drive_index_to_unit_id(type, index));
259 int drive_get_max_bus(BlockInterfaceType type)
261 int max_bus;
262 BlockBackend *blk;
263 DriveInfo *dinfo;
265 max_bus = -1;
266 for (blk = blk_next(NULL); blk; blk = blk_next(blk)) {
267 dinfo = blk_legacy_dinfo(blk);
268 if (dinfo && dinfo->type == type && dinfo->bus > max_bus) {
269 max_bus = dinfo->bus;
272 return max_bus;
275 /* Get a block device. This should only be used for single-drive devices
276 (e.g. SD/Floppy/MTD). Multi-disk devices (scsi/ide) should use the
277 appropriate bus. */
278 DriveInfo *drive_get_next(BlockInterfaceType type)
280 static int next_block_unit[IF_COUNT];
282 return drive_get(type, 0, next_block_unit[type]++);
285 static void bdrv_format_print(void *opaque, const char *name)
287 error_printf(" %s", name);
290 typedef struct {
291 QEMUBH *bh;
292 BlockDriverState *bs;
293 } BDRVPutRefBH;
295 static int parse_block_error_action(const char *buf, bool is_read, Error **errp)
297 if (!strcmp(buf, "ignore")) {
298 return BLOCKDEV_ON_ERROR_IGNORE;
299 } else if (!is_read && !strcmp(buf, "enospc")) {
300 return BLOCKDEV_ON_ERROR_ENOSPC;
301 } else if (!strcmp(buf, "stop")) {
302 return BLOCKDEV_ON_ERROR_STOP;
303 } else if (!strcmp(buf, "report")) {
304 return BLOCKDEV_ON_ERROR_REPORT;
305 } else {
306 error_setg(errp, "'%s' invalid %s error action",
307 buf, is_read ? "read" : "write");
308 return -1;
312 static bool parse_stats_intervals(BlockAcctStats *stats, QList *intervals,
313 Error **errp)
315 const QListEntry *entry;
316 for (entry = qlist_first(intervals); entry; entry = qlist_next(entry)) {
317 switch (qobject_type(entry->value)) {
319 case QTYPE_QSTRING: {
320 unsigned long long length;
321 const char *str = qstring_get_str(qobject_to_qstring(entry->value));
322 if (parse_uint_full(str, &length, 10) == 0 &&
323 length > 0 && length <= UINT_MAX) {
324 block_acct_add_interval(stats, (unsigned) length);
325 } else {
326 error_setg(errp, "Invalid interval length: %s", str);
327 return false;
329 break;
332 case QTYPE_QINT: {
333 int64_t length = qint_get_int(qobject_to_qint(entry->value));
334 if (length > 0 && length <= UINT_MAX) {
335 block_acct_add_interval(stats, (unsigned) length);
336 } else {
337 error_setg(errp, "Invalid interval length: %" PRId64, length);
338 return false;
340 break;
343 default:
344 error_setg(errp, "The specification of stats-intervals is invalid");
345 return false;
348 return true;
351 typedef enum { MEDIA_DISK, MEDIA_CDROM } DriveMediaType;
353 /* All parameters but @opts are optional and may be set to NULL. */
354 static void extract_common_blockdev_options(QemuOpts *opts, int *bdrv_flags,
355 const char **throttling_group, ThrottleConfig *throttle_cfg,
356 BlockdevDetectZeroesOptions *detect_zeroes, Error **errp)
358 const char *discard;
359 Error *local_error = NULL;
360 const char *aio;
362 if (bdrv_flags) {
363 if (!qemu_opt_get_bool(opts, "read-only", false)) {
364 *bdrv_flags |= BDRV_O_RDWR;
366 if (qemu_opt_get_bool(opts, "copy-on-read", false)) {
367 *bdrv_flags |= BDRV_O_COPY_ON_READ;
370 if ((discard = qemu_opt_get(opts, "discard")) != NULL) {
371 if (bdrv_parse_discard_flags(discard, bdrv_flags) != 0) {
372 error_setg(errp, "Invalid discard option");
373 return;
377 if ((aio = qemu_opt_get(opts, "aio")) != NULL) {
378 if (!strcmp(aio, "native")) {
379 *bdrv_flags |= BDRV_O_NATIVE_AIO;
380 } else if (!strcmp(aio, "threads")) {
381 /* this is the default */
382 } else {
383 error_setg(errp, "invalid aio option");
384 return;
389 /* disk I/O throttling */
390 if (throttling_group) {
391 *throttling_group = qemu_opt_get(opts, "throttling.group");
394 if (throttle_cfg) {
395 throttle_config_init(throttle_cfg);
396 throttle_cfg->buckets[THROTTLE_BPS_TOTAL].avg =
397 qemu_opt_get_number(opts, "throttling.bps-total", 0);
398 throttle_cfg->buckets[THROTTLE_BPS_READ].avg =
399 qemu_opt_get_number(opts, "throttling.bps-read", 0);
400 throttle_cfg->buckets[THROTTLE_BPS_WRITE].avg =
401 qemu_opt_get_number(opts, "throttling.bps-write", 0);
402 throttle_cfg->buckets[THROTTLE_OPS_TOTAL].avg =
403 qemu_opt_get_number(opts, "throttling.iops-total", 0);
404 throttle_cfg->buckets[THROTTLE_OPS_READ].avg =
405 qemu_opt_get_number(opts, "throttling.iops-read", 0);
406 throttle_cfg->buckets[THROTTLE_OPS_WRITE].avg =
407 qemu_opt_get_number(opts, "throttling.iops-write", 0);
409 throttle_cfg->buckets[THROTTLE_BPS_TOTAL].max =
410 qemu_opt_get_number(opts, "throttling.bps-total-max", 0);
411 throttle_cfg->buckets[THROTTLE_BPS_READ].max =
412 qemu_opt_get_number(opts, "throttling.bps-read-max", 0);
413 throttle_cfg->buckets[THROTTLE_BPS_WRITE].max =
414 qemu_opt_get_number(opts, "throttling.bps-write-max", 0);
415 throttle_cfg->buckets[THROTTLE_OPS_TOTAL].max =
416 qemu_opt_get_number(opts, "throttling.iops-total-max", 0);
417 throttle_cfg->buckets[THROTTLE_OPS_READ].max =
418 qemu_opt_get_number(opts, "throttling.iops-read-max", 0);
419 throttle_cfg->buckets[THROTTLE_OPS_WRITE].max =
420 qemu_opt_get_number(opts, "throttling.iops-write-max", 0);
422 throttle_cfg->buckets[THROTTLE_BPS_TOTAL].burst_length =
423 qemu_opt_get_number(opts, "throttling.bps-total-max-length", 1);
424 throttle_cfg->buckets[THROTTLE_BPS_READ].burst_length =
425 qemu_opt_get_number(opts, "throttling.bps-read-max-length", 1);
426 throttle_cfg->buckets[THROTTLE_BPS_WRITE].burst_length =
427 qemu_opt_get_number(opts, "throttling.bps-write-max-length", 1);
428 throttle_cfg->buckets[THROTTLE_OPS_TOTAL].burst_length =
429 qemu_opt_get_number(opts, "throttling.iops-total-max-length", 1);
430 throttle_cfg->buckets[THROTTLE_OPS_READ].burst_length =
431 qemu_opt_get_number(opts, "throttling.iops-read-max-length", 1);
432 throttle_cfg->buckets[THROTTLE_OPS_WRITE].burst_length =
433 qemu_opt_get_number(opts, "throttling.iops-write-max-length", 1);
435 throttle_cfg->op_size =
436 qemu_opt_get_number(opts, "throttling.iops-size", 0);
438 if (!throttle_is_valid(throttle_cfg, errp)) {
439 return;
443 if (detect_zeroes) {
444 *detect_zeroes =
445 qapi_enum_parse(BlockdevDetectZeroesOptions_lookup,
446 qemu_opt_get(opts, "detect-zeroes"),
447 BLOCKDEV_DETECT_ZEROES_OPTIONS__MAX,
448 BLOCKDEV_DETECT_ZEROES_OPTIONS_OFF,
449 &local_error);
450 if (local_error) {
451 error_propagate(errp, local_error);
452 return;
455 if (bdrv_flags &&
456 *detect_zeroes == BLOCKDEV_DETECT_ZEROES_OPTIONS_UNMAP &&
457 !(*bdrv_flags & BDRV_O_UNMAP))
459 error_setg(errp, "setting detect-zeroes to unmap is not allowed "
460 "without setting discard operation to unmap");
461 return;
466 /* Takes the ownership of bs_opts */
467 static BlockBackend *blockdev_init(const char *file, QDict *bs_opts,
468 Error **errp)
470 const char *buf;
471 int bdrv_flags = 0;
472 int on_read_error, on_write_error;
473 bool account_invalid, account_failed;
474 bool writethrough;
475 BlockBackend *blk;
476 BlockDriverState *bs;
477 ThrottleConfig cfg;
478 int snapshot = 0;
479 Error *error = NULL;
480 QemuOpts *opts;
481 QDict *interval_dict = NULL;
482 QList *interval_list = NULL;
483 const char *id;
484 BlockdevDetectZeroesOptions detect_zeroes =
485 BLOCKDEV_DETECT_ZEROES_OPTIONS_OFF;
486 const char *throttling_group = NULL;
488 /* Check common options by copying from bs_opts to opts, all other options
489 * stay in bs_opts for processing by bdrv_open(). */
490 id = qdict_get_try_str(bs_opts, "id");
491 opts = qemu_opts_create(&qemu_common_drive_opts, id, 1, &error);
492 if (error) {
493 error_propagate(errp, error);
494 goto err_no_opts;
497 qemu_opts_absorb_qdict(opts, bs_opts, &error);
498 if (error) {
499 error_propagate(errp, error);
500 goto early_err;
503 if (id) {
504 qdict_del(bs_opts, "id");
507 /* extract parameters */
508 snapshot = qemu_opt_get_bool(opts, "snapshot", 0);
510 account_invalid = qemu_opt_get_bool(opts, "stats-account-invalid", true);
511 account_failed = qemu_opt_get_bool(opts, "stats-account-failed", true);
513 writethrough = !qemu_opt_get_bool(opts, BDRV_OPT_CACHE_WB, true);
515 id = qemu_opts_id(opts);
517 qdict_extract_subqdict(bs_opts, &interval_dict, "stats-intervals.");
518 qdict_array_split(interval_dict, &interval_list);
520 if (qdict_size(interval_dict) != 0) {
521 error_setg(errp, "Invalid option stats-intervals.%s",
522 qdict_first(interval_dict)->key);
523 goto early_err;
526 extract_common_blockdev_options(opts, &bdrv_flags, &throttling_group, &cfg,
527 &detect_zeroes, &error);
528 if (error) {
529 error_propagate(errp, error);
530 goto early_err;
533 if ((buf = qemu_opt_get(opts, "format")) != NULL) {
534 if (is_help_option(buf)) {
535 error_printf("Supported formats:");
536 bdrv_iterate_format(bdrv_format_print, NULL);
537 error_printf("\n");
538 goto early_err;
541 if (qdict_haskey(bs_opts, "driver")) {
542 error_setg(errp, "Cannot specify both 'driver' and 'format'");
543 goto early_err;
545 qdict_put(bs_opts, "driver", qstring_from_str(buf));
548 on_write_error = BLOCKDEV_ON_ERROR_ENOSPC;
549 if ((buf = qemu_opt_get(opts, "werror")) != NULL) {
550 on_write_error = parse_block_error_action(buf, 0, &error);
551 if (error) {
552 error_propagate(errp, error);
553 goto early_err;
557 on_read_error = BLOCKDEV_ON_ERROR_REPORT;
558 if ((buf = qemu_opt_get(opts, "rerror")) != NULL) {
559 on_read_error = parse_block_error_action(buf, 1, &error);
560 if (error) {
561 error_propagate(errp, error);
562 goto early_err;
566 if (snapshot) {
567 bdrv_flags |= BDRV_O_SNAPSHOT;
570 /* init */
571 if ((!file || !*file) && !qdict_size(bs_opts)) {
572 BlockBackendRootState *blk_rs;
574 blk = blk_new();
575 blk_rs = blk_get_root_state(blk);
576 blk_rs->open_flags = bdrv_flags;
577 blk_rs->read_only = !(bdrv_flags & BDRV_O_RDWR);
578 blk_rs->detect_zeroes = detect_zeroes;
580 QDECREF(bs_opts);
581 } else {
582 if (file && !*file) {
583 file = NULL;
586 /* bdrv_open() defaults to the values in bdrv_flags (for compatibility
587 * with other callers) rather than what we want as the real defaults.
588 * Apply the defaults here instead. */
589 qdict_set_default_str(bs_opts, BDRV_OPT_CACHE_DIRECT, "off");
590 qdict_set_default_str(bs_opts, BDRV_OPT_CACHE_NO_FLUSH, "off");
591 assert((bdrv_flags & BDRV_O_CACHE_MASK) == 0);
593 if (runstate_check(RUN_STATE_INMIGRATE)) {
594 bdrv_flags |= BDRV_O_INACTIVE;
597 blk = blk_new_open(file, NULL, bs_opts, bdrv_flags, errp);
598 if (!blk) {
599 goto err_no_bs_opts;
601 bs = blk_bs(blk);
603 bs->detect_zeroes = detect_zeroes;
605 if (bdrv_key_required(bs)) {
606 autostart = 0;
609 block_acct_init(blk_get_stats(blk), account_invalid, account_failed);
611 if (!parse_stats_intervals(blk_get_stats(blk), interval_list, errp)) {
612 blk_unref(blk);
613 blk = NULL;
614 goto err_no_bs_opts;
618 /* disk I/O throttling */
619 if (throttle_enabled(&cfg)) {
620 if (!throttling_group) {
621 throttling_group = id;
623 blk_io_limits_enable(blk, throttling_group);
624 blk_set_io_limits(blk, &cfg);
627 blk_set_enable_write_cache(blk, !writethrough);
628 blk_set_on_error(blk, on_read_error, on_write_error);
630 if (!monitor_add_blk(blk, id, errp)) {
631 blk_unref(blk);
632 blk = NULL;
633 goto err_no_bs_opts;
636 err_no_bs_opts:
637 qemu_opts_del(opts);
638 QDECREF(interval_dict);
639 QDECREF(interval_list);
640 return blk;
642 early_err:
643 qemu_opts_del(opts);
644 QDECREF(interval_dict);
645 QDECREF(interval_list);
646 err_no_opts:
647 QDECREF(bs_opts);
648 return NULL;
651 static QemuOptsList qemu_root_bds_opts;
653 /* Takes the ownership of bs_opts */
654 static BlockDriverState *bds_tree_init(QDict *bs_opts, Error **errp)
656 BlockDriverState *bs;
657 QemuOpts *opts;
658 Error *local_error = NULL;
659 BlockdevDetectZeroesOptions detect_zeroes;
660 int bdrv_flags = 0;
662 opts = qemu_opts_create(&qemu_root_bds_opts, NULL, 1, errp);
663 if (!opts) {
664 goto fail;
667 qemu_opts_absorb_qdict(opts, bs_opts, &local_error);
668 if (local_error) {
669 error_propagate(errp, local_error);
670 goto fail;
673 extract_common_blockdev_options(opts, &bdrv_flags, NULL, NULL,
674 &detect_zeroes, &local_error);
675 if (local_error) {
676 error_propagate(errp, local_error);
677 goto fail;
680 /* bdrv_open() defaults to the values in bdrv_flags (for compatibility
681 * with other callers) rather than what we want as the real defaults.
682 * Apply the defaults here instead. */
683 qdict_set_default_str(bs_opts, BDRV_OPT_CACHE_DIRECT, "off");
684 qdict_set_default_str(bs_opts, BDRV_OPT_CACHE_NO_FLUSH, "off");
686 if (runstate_check(RUN_STATE_INMIGRATE)) {
687 bdrv_flags |= BDRV_O_INACTIVE;
690 bs = bdrv_open(NULL, NULL, bs_opts, bdrv_flags, errp);
691 if (!bs) {
692 goto fail_no_bs_opts;
695 bs->detect_zeroes = detect_zeroes;
697 fail_no_bs_opts:
698 qemu_opts_del(opts);
699 return bs;
701 fail:
702 qemu_opts_del(opts);
703 QDECREF(bs_opts);
704 return NULL;
707 void blockdev_close_all_bdrv_states(void)
709 BlockDriverState *bs, *next_bs;
711 QTAILQ_FOREACH_SAFE(bs, &monitor_bdrv_states, monitor_list, next_bs) {
712 AioContext *ctx = bdrv_get_aio_context(bs);
714 aio_context_acquire(ctx);
715 bdrv_unref(bs);
716 aio_context_release(ctx);
720 /* Iterates over the list of monitor-owned BlockDriverStates */
721 BlockDriverState *bdrv_next_monitor_owned(BlockDriverState *bs)
723 return bs ? QTAILQ_NEXT(bs, monitor_list)
724 : QTAILQ_FIRST(&monitor_bdrv_states);
727 static void qemu_opt_rename(QemuOpts *opts, const char *from, const char *to,
728 Error **errp)
730 const char *value;
732 value = qemu_opt_get(opts, from);
733 if (value) {
734 if (qemu_opt_find(opts, to)) {
735 error_setg(errp, "'%s' and its alias '%s' can't be used at the "
736 "same time", to, from);
737 return;
741 /* rename all items in opts */
742 while ((value = qemu_opt_get(opts, from))) {
743 qemu_opt_set(opts, to, value, &error_abort);
744 qemu_opt_unset(opts, from);
748 QemuOptsList qemu_legacy_drive_opts = {
749 .name = "drive",
750 .head = QTAILQ_HEAD_INITIALIZER(qemu_legacy_drive_opts.head),
751 .desc = {
753 .name = "bus",
754 .type = QEMU_OPT_NUMBER,
755 .help = "bus number",
757 .name = "unit",
758 .type = QEMU_OPT_NUMBER,
759 .help = "unit number (i.e. lun for scsi)",
761 .name = "index",
762 .type = QEMU_OPT_NUMBER,
763 .help = "index number",
765 .name = "media",
766 .type = QEMU_OPT_STRING,
767 .help = "media type (disk, cdrom)",
769 .name = "if",
770 .type = QEMU_OPT_STRING,
771 .help = "interface (ide, scsi, sd, mtd, floppy, pflash, virtio)",
773 .name = "cyls",
774 .type = QEMU_OPT_NUMBER,
775 .help = "number of cylinders (ide disk geometry)",
777 .name = "heads",
778 .type = QEMU_OPT_NUMBER,
779 .help = "number of heads (ide disk geometry)",
781 .name = "secs",
782 .type = QEMU_OPT_NUMBER,
783 .help = "number of sectors (ide disk geometry)",
785 .name = "trans",
786 .type = QEMU_OPT_STRING,
787 .help = "chs translation (auto, lba, none)",
789 .name = "boot",
790 .type = QEMU_OPT_BOOL,
791 .help = "(deprecated, ignored)",
793 .name = "addr",
794 .type = QEMU_OPT_STRING,
795 .help = "pci address (virtio only)",
797 .name = "serial",
798 .type = QEMU_OPT_STRING,
799 .help = "disk serial number",
801 .name = "file",
802 .type = QEMU_OPT_STRING,
803 .help = "file name",
806 /* Options that are passed on, but have special semantics with -drive */
808 .name = "read-only",
809 .type = QEMU_OPT_BOOL,
810 .help = "open drive file as read-only",
812 .name = "rerror",
813 .type = QEMU_OPT_STRING,
814 .help = "read error action",
816 .name = "werror",
817 .type = QEMU_OPT_STRING,
818 .help = "write error action",
820 .name = "copy-on-read",
821 .type = QEMU_OPT_BOOL,
822 .help = "copy read data from backing file into image file",
825 { /* end of list */ }
829 DriveInfo *drive_new(QemuOpts *all_opts, BlockInterfaceType block_default_type)
831 const char *value;
832 BlockBackend *blk;
833 DriveInfo *dinfo = NULL;
834 QDict *bs_opts;
835 QemuOpts *legacy_opts;
836 DriveMediaType media = MEDIA_DISK;
837 BlockInterfaceType type;
838 int cyls, heads, secs, translation;
839 int max_devs, bus_id, unit_id, index;
840 const char *devaddr;
841 const char *werror, *rerror;
842 bool read_only = false;
843 bool copy_on_read;
844 const char *serial;
845 const char *filename;
846 Error *local_err = NULL;
847 int i;
849 /* Change legacy command line options into QMP ones */
850 static const struct {
851 const char *from;
852 const char *to;
853 } opt_renames[] = {
854 { "iops", "throttling.iops-total" },
855 { "iops_rd", "throttling.iops-read" },
856 { "iops_wr", "throttling.iops-write" },
858 { "bps", "throttling.bps-total" },
859 { "bps_rd", "throttling.bps-read" },
860 { "bps_wr", "throttling.bps-write" },
862 { "iops_max", "throttling.iops-total-max" },
863 { "iops_rd_max", "throttling.iops-read-max" },
864 { "iops_wr_max", "throttling.iops-write-max" },
866 { "bps_max", "throttling.bps-total-max" },
867 { "bps_rd_max", "throttling.bps-read-max" },
868 { "bps_wr_max", "throttling.bps-write-max" },
870 { "iops_size", "throttling.iops-size" },
872 { "group", "throttling.group" },
874 { "readonly", "read-only" },
877 for (i = 0; i < ARRAY_SIZE(opt_renames); i++) {
878 qemu_opt_rename(all_opts, opt_renames[i].from, opt_renames[i].to,
879 &local_err);
880 if (local_err) {
881 error_report_err(local_err);
882 return NULL;
886 value = qemu_opt_get(all_opts, "cache");
887 if (value) {
888 int flags = 0;
889 bool writethrough;
891 if (bdrv_parse_cache_mode(value, &flags, &writethrough) != 0) {
892 error_report("invalid cache option");
893 return NULL;
896 /* Specific options take precedence */
897 if (!qemu_opt_get(all_opts, BDRV_OPT_CACHE_WB)) {
898 qemu_opt_set_bool(all_opts, BDRV_OPT_CACHE_WB,
899 !writethrough, &error_abort);
901 if (!qemu_opt_get(all_opts, BDRV_OPT_CACHE_DIRECT)) {
902 qemu_opt_set_bool(all_opts, BDRV_OPT_CACHE_DIRECT,
903 !!(flags & BDRV_O_NOCACHE), &error_abort);
905 if (!qemu_opt_get(all_opts, BDRV_OPT_CACHE_NO_FLUSH)) {
906 qemu_opt_set_bool(all_opts, BDRV_OPT_CACHE_NO_FLUSH,
907 !!(flags & BDRV_O_NO_FLUSH), &error_abort);
909 qemu_opt_unset(all_opts, "cache");
912 /* Get a QDict for processing the options */
913 bs_opts = qdict_new();
914 qemu_opts_to_qdict(all_opts, bs_opts);
916 legacy_opts = qemu_opts_create(&qemu_legacy_drive_opts, NULL, 0,
917 &error_abort);
918 qemu_opts_absorb_qdict(legacy_opts, bs_opts, &local_err);
919 if (local_err) {
920 error_report_err(local_err);
921 goto fail;
924 /* Deprecated option boot=[on|off] */
925 if (qemu_opt_get(legacy_opts, "boot") != NULL) {
926 fprintf(stderr, "qemu-kvm: boot=on|off is deprecated and will be "
927 "ignored. Future versions will reject this parameter. Please "
928 "update your scripts.\n");
931 /* Media type */
932 value = qemu_opt_get(legacy_opts, "media");
933 if (value) {
934 if (!strcmp(value, "disk")) {
935 media = MEDIA_DISK;
936 } else if (!strcmp(value, "cdrom")) {
937 media = MEDIA_CDROM;
938 read_only = true;
939 } else {
940 error_report("'%s' invalid media", value);
941 goto fail;
945 /* copy-on-read is disabled with a warning for read-only devices */
946 read_only |= qemu_opt_get_bool(legacy_opts, "read-only", false);
947 copy_on_read = qemu_opt_get_bool(legacy_opts, "copy-on-read", false);
949 if (read_only && copy_on_read) {
950 error_report("warning: disabling copy-on-read on read-only drive");
951 copy_on_read = false;
954 qdict_put(bs_opts, "read-only",
955 qstring_from_str(read_only ? "on" : "off"));
956 qdict_put(bs_opts, "copy-on-read",
957 qstring_from_str(copy_on_read ? "on" :"off"));
959 /* Controller type */
960 value = qemu_opt_get(legacy_opts, "if");
961 if (value) {
962 for (type = 0;
963 type < IF_COUNT && strcmp(value, if_name[type]);
964 type++) {
966 if (type == IF_COUNT) {
967 error_report("unsupported bus type '%s'", value);
968 goto fail;
970 } else {
971 type = block_default_type;
974 /* Geometry */
975 cyls = qemu_opt_get_number(legacy_opts, "cyls", 0);
976 heads = qemu_opt_get_number(legacy_opts, "heads", 0);
977 secs = qemu_opt_get_number(legacy_opts, "secs", 0);
979 if (cyls || heads || secs) {
980 if (cyls < 1) {
981 error_report("invalid physical cyls number");
982 goto fail;
984 if (heads < 1) {
985 error_report("invalid physical heads number");
986 goto fail;
988 if (secs < 1) {
989 error_report("invalid physical secs number");
990 goto fail;
994 translation = BIOS_ATA_TRANSLATION_AUTO;
995 value = qemu_opt_get(legacy_opts, "trans");
996 if (value != NULL) {
997 if (!cyls) {
998 error_report("'%s' trans must be used with cyls, heads and secs",
999 value);
1000 goto fail;
1002 if (!strcmp(value, "none")) {
1003 translation = BIOS_ATA_TRANSLATION_NONE;
1004 } else if (!strcmp(value, "lba")) {
1005 translation = BIOS_ATA_TRANSLATION_LBA;
1006 } else if (!strcmp(value, "large")) {
1007 translation = BIOS_ATA_TRANSLATION_LARGE;
1008 } else if (!strcmp(value, "rechs")) {
1009 translation = BIOS_ATA_TRANSLATION_RECHS;
1010 } else if (!strcmp(value, "auto")) {
1011 translation = BIOS_ATA_TRANSLATION_AUTO;
1012 } else {
1013 error_report("'%s' invalid translation type", value);
1014 goto fail;
1018 if (media == MEDIA_CDROM) {
1019 if (cyls || secs || heads) {
1020 error_report("CHS can't be set with media=cdrom");
1021 goto fail;
1025 /* Device address specified by bus/unit or index.
1026 * If none was specified, try to find the first free one. */
1027 bus_id = qemu_opt_get_number(legacy_opts, "bus", 0);
1028 unit_id = qemu_opt_get_number(legacy_opts, "unit", -1);
1029 index = qemu_opt_get_number(legacy_opts, "index", -1);
1031 max_devs = if_max_devs[type];
1033 if (index != -1) {
1034 if (bus_id != 0 || unit_id != -1) {
1035 error_report("index cannot be used with bus and unit");
1036 goto fail;
1038 bus_id = drive_index_to_bus_id(type, index);
1039 unit_id = drive_index_to_unit_id(type, index);
1042 if (unit_id == -1) {
1043 unit_id = 0;
1044 while (drive_get(type, bus_id, unit_id) != NULL) {
1045 unit_id++;
1046 if (max_devs && unit_id >= max_devs) {
1047 unit_id -= max_devs;
1048 bus_id++;
1053 if (max_devs && unit_id >= max_devs) {
1054 error_report("unit %d too big (max is %d)", unit_id, max_devs - 1);
1055 goto fail;
1058 if (drive_get(type, bus_id, unit_id) != NULL) {
1059 error_report("drive with bus=%d, unit=%d (index=%d) exists",
1060 bus_id, unit_id, index);
1061 goto fail;
1064 /* Serial number */
1065 serial = qemu_opt_get(legacy_opts, "serial");
1067 /* no id supplied -> create one */
1068 if (qemu_opts_id(all_opts) == NULL) {
1069 char *new_id;
1070 const char *mediastr = "";
1071 if (type == IF_IDE || type == IF_SCSI) {
1072 mediastr = (media == MEDIA_CDROM) ? "-cd" : "-hd";
1074 if (max_devs) {
1075 new_id = g_strdup_printf("%s%i%s%i", if_name[type], bus_id,
1076 mediastr, unit_id);
1077 } else {
1078 new_id = g_strdup_printf("%s%s%i", if_name[type],
1079 mediastr, unit_id);
1081 qdict_put(bs_opts, "id", qstring_from_str(new_id));
1082 g_free(new_id);
1085 /* Add virtio block device */
1086 devaddr = qemu_opt_get(legacy_opts, "addr");
1087 if (devaddr && type != IF_VIRTIO) {
1088 error_report("addr is not supported by this bus type");
1089 goto fail;
1092 if (type == IF_VIRTIO) {
1093 QemuOpts *devopts;
1094 devopts = qemu_opts_create(qemu_find_opts("device"), NULL, 0,
1095 &error_abort);
1096 if (arch_type == QEMU_ARCH_S390X) {
1097 qemu_opt_set(devopts, "driver", "virtio-blk-ccw", &error_abort);
1098 } else {
1099 qemu_opt_set(devopts, "driver", "virtio-blk-pci", &error_abort);
1101 qemu_opt_set(devopts, "drive", qdict_get_str(bs_opts, "id"),
1102 &error_abort);
1103 if (devaddr) {
1104 qemu_opt_set(devopts, "addr", devaddr, &error_abort);
1108 filename = qemu_opt_get(legacy_opts, "file");
1110 /* Check werror/rerror compatibility with if=... */
1111 werror = qemu_opt_get(legacy_opts, "werror");
1112 if (werror != NULL) {
1113 if (type != IF_IDE && type != IF_SCSI && type != IF_VIRTIO &&
1114 type != IF_NONE) {
1115 error_report("werror is not supported by this bus type");
1116 goto fail;
1118 qdict_put(bs_opts, "werror", qstring_from_str(werror));
1121 rerror = qemu_opt_get(legacy_opts, "rerror");
1122 if (rerror != NULL) {
1123 if (type != IF_IDE && type != IF_VIRTIO && type != IF_SCSI &&
1124 type != IF_NONE) {
1125 error_report("rerror is not supported by this bus type");
1126 goto fail;
1128 qdict_put(bs_opts, "rerror", qstring_from_str(rerror));
1131 /* Actual block device init: Functionality shared with blockdev-add */
1132 blk = blockdev_init(filename, bs_opts, &local_err);
1133 bs_opts = NULL;
1134 if (!blk) {
1135 if (local_err) {
1136 error_report_err(local_err);
1138 goto fail;
1139 } else {
1140 assert(!local_err);
1143 /* Create legacy DriveInfo */
1144 dinfo = g_malloc0(sizeof(*dinfo));
1145 dinfo->opts = all_opts;
1147 dinfo->cyls = cyls;
1148 dinfo->heads = heads;
1149 dinfo->secs = secs;
1150 dinfo->trans = translation;
1152 dinfo->type = type;
1153 dinfo->bus = bus_id;
1154 dinfo->unit = unit_id;
1155 dinfo->devaddr = devaddr;
1156 dinfo->serial = g_strdup(serial);
1158 blk_set_legacy_dinfo(blk, dinfo);
1160 switch(type) {
1161 case IF_IDE:
1162 case IF_SCSI:
1163 case IF_XEN:
1164 case IF_NONE:
1165 dinfo->media_cd = media == MEDIA_CDROM;
1166 break;
1167 default:
1168 break;
1171 fail:
1172 qemu_opts_del(legacy_opts);
1173 QDECREF(bs_opts);
1174 return dinfo;
1177 static BlockDriverState *qmp_get_root_bs(const char *name, Error **errp)
1179 BlockDriverState *bs;
1181 bs = bdrv_lookup_bs(name, name, errp);
1182 if (bs == NULL) {
1183 return NULL;
1186 if (!bdrv_is_root_node(bs)) {
1187 error_setg(errp, "Need a root block node");
1188 return NULL;
1191 if (!bdrv_is_inserted(bs)) {
1192 error_setg(errp, "Device has no medium");
1193 return NULL;
1196 return bs;
1199 void hmp_commit(Monitor *mon, const QDict *qdict)
1201 const char *device = qdict_get_str(qdict, "device");
1202 BlockBackend *blk;
1203 int ret;
1205 if (!strcmp(device, "all")) {
1206 ret = blk_commit_all();
1207 } else {
1208 BlockDriverState *bs;
1209 AioContext *aio_context;
1211 blk = blk_by_name(device);
1212 if (!blk) {
1213 monitor_printf(mon, "Device '%s' not found\n", device);
1214 return;
1216 if (!blk_is_available(blk)) {
1217 monitor_printf(mon, "Device '%s' has no medium\n", device);
1218 return;
1221 bs = blk_bs(blk);
1222 aio_context = bdrv_get_aio_context(bs);
1223 aio_context_acquire(aio_context);
1225 ret = bdrv_commit(bs);
1227 aio_context_release(aio_context);
1229 if (ret < 0) {
1230 monitor_printf(mon, "'commit' error for '%s': %s\n", device,
1231 strerror(-ret));
1235 static void blockdev_do_action(TransactionAction *action, Error **errp)
1237 TransactionActionList list;
1239 list.value = action;
1240 list.next = NULL;
1241 qmp_transaction(&list, false, NULL, errp);
1244 void qmp_blockdev_snapshot_sync(bool has_device, const char *device,
1245 bool has_node_name, const char *node_name,
1246 const char *snapshot_file,
1247 bool has_snapshot_node_name,
1248 const char *snapshot_node_name,
1249 bool has_format, const char *format,
1250 bool has_mode, NewImageMode mode, Error **errp)
1252 BlockdevSnapshotSync snapshot = {
1253 .has_device = has_device,
1254 .device = (char *) device,
1255 .has_node_name = has_node_name,
1256 .node_name = (char *) node_name,
1257 .snapshot_file = (char *) snapshot_file,
1258 .has_snapshot_node_name = has_snapshot_node_name,
1259 .snapshot_node_name = (char *) snapshot_node_name,
1260 .has_format = has_format,
1261 .format = (char *) format,
1262 .has_mode = has_mode,
1263 .mode = mode,
1265 TransactionAction action = {
1266 .type = TRANSACTION_ACTION_KIND_BLOCKDEV_SNAPSHOT_SYNC,
1267 .u.blockdev_snapshot_sync.data = &snapshot,
1269 blockdev_do_action(&action, errp);
1272 void qmp_blockdev_snapshot(const char *node, const char *overlay,
1273 Error **errp)
1275 BlockdevSnapshot snapshot_data = {
1276 .node = (char *) node,
1277 .overlay = (char *) overlay
1279 TransactionAction action = {
1280 .type = TRANSACTION_ACTION_KIND_BLOCKDEV_SNAPSHOT,
1281 .u.blockdev_snapshot.data = &snapshot_data,
1283 blockdev_do_action(&action, errp);
1286 void qmp_blockdev_snapshot_internal_sync(const char *device,
1287 const char *name,
1288 Error **errp)
1290 BlockdevSnapshotInternal snapshot = {
1291 .device = (char *) device,
1292 .name = (char *) name
1294 TransactionAction action = {
1295 .type = TRANSACTION_ACTION_KIND_BLOCKDEV_SNAPSHOT_INTERNAL_SYNC,
1296 .u.blockdev_snapshot_internal_sync.data = &snapshot,
1298 blockdev_do_action(&action, errp);
1301 SnapshotInfo *qmp_blockdev_snapshot_delete_internal_sync(const char *device,
1302 bool has_id,
1303 const char *id,
1304 bool has_name,
1305 const char *name,
1306 Error **errp)
1308 BlockDriverState *bs;
1309 AioContext *aio_context;
1310 QEMUSnapshotInfo sn;
1311 Error *local_err = NULL;
1312 SnapshotInfo *info = NULL;
1313 int ret;
1315 bs = qmp_get_root_bs(device, errp);
1316 if (!bs) {
1317 return NULL;
1319 aio_context = bdrv_get_aio_context(bs);
1320 aio_context_acquire(aio_context);
1322 if (!has_id) {
1323 id = NULL;
1326 if (!has_name) {
1327 name = NULL;
1330 if (!id && !name) {
1331 error_setg(errp, "Name or id must be provided");
1332 goto out_aio_context;
1335 if (bdrv_op_is_blocked(bs, BLOCK_OP_TYPE_INTERNAL_SNAPSHOT_DELETE, errp)) {
1336 goto out_aio_context;
1339 ret = bdrv_snapshot_find_by_id_and_name(bs, id, name, &sn, &local_err);
1340 if (local_err) {
1341 error_propagate(errp, local_err);
1342 goto out_aio_context;
1344 if (!ret) {
1345 error_setg(errp,
1346 "Snapshot with id '%s' and name '%s' does not exist on "
1347 "device '%s'",
1348 STR_OR_NULL(id), STR_OR_NULL(name), device);
1349 goto out_aio_context;
1352 bdrv_snapshot_delete(bs, id, name, &local_err);
1353 if (local_err) {
1354 error_propagate(errp, local_err);
1355 goto out_aio_context;
1358 aio_context_release(aio_context);
1360 info = g_new0(SnapshotInfo, 1);
1361 info->id = g_strdup(sn.id_str);
1362 info->name = g_strdup(sn.name);
1363 info->date_nsec = sn.date_nsec;
1364 info->date_sec = sn.date_sec;
1365 info->vm_state_size = sn.vm_state_size;
1366 info->vm_clock_nsec = sn.vm_clock_nsec % 1000000000;
1367 info->vm_clock_sec = sn.vm_clock_nsec / 1000000000;
1369 return info;
1371 out_aio_context:
1372 aio_context_release(aio_context);
1373 return NULL;
1377 * block_dirty_bitmap_lookup:
1378 * Return a dirty bitmap (if present), after validating
1379 * the node reference and bitmap names.
1381 * @node: The name of the BDS node to search for bitmaps
1382 * @name: The name of the bitmap to search for
1383 * @pbs: Output pointer for BDS lookup, if desired. Can be NULL.
1384 * @paio: Output pointer for aio_context acquisition, if desired. Can be NULL.
1385 * @errp: Output pointer for error information. Can be NULL.
1387 * @return: A bitmap object on success, or NULL on failure.
1389 static BdrvDirtyBitmap *block_dirty_bitmap_lookup(const char *node,
1390 const char *name,
1391 BlockDriverState **pbs,
1392 AioContext **paio,
1393 Error **errp)
1395 BlockDriverState *bs;
1396 BdrvDirtyBitmap *bitmap;
1397 AioContext *aio_context;
1399 if (!node) {
1400 error_setg(errp, "Node cannot be NULL");
1401 return NULL;
1403 if (!name) {
1404 error_setg(errp, "Bitmap name cannot be NULL");
1405 return NULL;
1407 bs = bdrv_lookup_bs(node, node, NULL);
1408 if (!bs) {
1409 error_setg(errp, "Node '%s' not found", node);
1410 return NULL;
1413 aio_context = bdrv_get_aio_context(bs);
1414 aio_context_acquire(aio_context);
1416 bitmap = bdrv_find_dirty_bitmap(bs, name);
1417 if (!bitmap) {
1418 error_setg(errp, "Dirty bitmap '%s' not found", name);
1419 goto fail;
1422 if (pbs) {
1423 *pbs = bs;
1425 if (paio) {
1426 *paio = aio_context;
1427 } else {
1428 aio_context_release(aio_context);
1431 return bitmap;
1433 fail:
1434 aio_context_release(aio_context);
1435 return NULL;
1438 /* New and old BlockDriverState structs for atomic group operations */
1440 typedef struct BlkActionState BlkActionState;
1443 * BlkActionOps:
1444 * Table of operations that define an Action.
1446 * @instance_size: Size of state struct, in bytes.
1447 * @prepare: Prepare the work, must NOT be NULL.
1448 * @commit: Commit the changes, can be NULL.
1449 * @abort: Abort the changes on fail, can be NULL.
1450 * @clean: Clean up resources after all transaction actions have called
1451 * commit() or abort(). Can be NULL.
1453 * Only prepare() may fail. In a single transaction, only one of commit() or
1454 * abort() will be called. clean() will always be called if it is present.
1456 typedef struct BlkActionOps {
1457 size_t instance_size;
1458 void (*prepare)(BlkActionState *common, Error **errp);
1459 void (*commit)(BlkActionState *common);
1460 void (*abort)(BlkActionState *common);
1461 void (*clean)(BlkActionState *common);
1462 } BlkActionOps;
1465 * BlkActionState:
1466 * Describes one Action's state within a Transaction.
1468 * @action: QAPI-defined enum identifying which Action to perform.
1469 * @ops: Table of ActionOps this Action can perform.
1470 * @block_job_txn: Transaction which this action belongs to.
1471 * @entry: List membership for all Actions in this Transaction.
1473 * This structure must be arranged as first member in a subclassed type,
1474 * assuming that the compiler will also arrange it to the same offsets as the
1475 * base class.
1477 struct BlkActionState {
1478 TransactionAction *action;
1479 const BlkActionOps *ops;
1480 BlockJobTxn *block_job_txn;
1481 TransactionProperties *txn_props;
1482 QSIMPLEQ_ENTRY(BlkActionState) entry;
1485 /* internal snapshot private data */
1486 typedef struct InternalSnapshotState {
1487 BlkActionState common;
1488 BlockDriverState *bs;
1489 AioContext *aio_context;
1490 QEMUSnapshotInfo sn;
1491 bool created;
1492 } InternalSnapshotState;
1495 static int action_check_completion_mode(BlkActionState *s, Error **errp)
1497 if (s->txn_props->completion_mode != ACTION_COMPLETION_MODE_INDIVIDUAL) {
1498 error_setg(errp,
1499 "Action '%s' does not support Transaction property "
1500 "completion-mode = %s",
1501 TransactionActionKind_lookup[s->action->type],
1502 ActionCompletionMode_lookup[s->txn_props->completion_mode]);
1503 return -1;
1505 return 0;
1508 static void internal_snapshot_prepare(BlkActionState *common,
1509 Error **errp)
1511 Error *local_err = NULL;
1512 const char *device;
1513 const char *name;
1514 BlockDriverState *bs;
1515 QEMUSnapshotInfo old_sn, *sn;
1516 bool ret;
1517 qemu_timeval tv;
1518 BlockdevSnapshotInternal *internal;
1519 InternalSnapshotState *state;
1520 int ret1;
1522 g_assert(common->action->type ==
1523 TRANSACTION_ACTION_KIND_BLOCKDEV_SNAPSHOT_INTERNAL_SYNC);
1524 internal = common->action->u.blockdev_snapshot_internal_sync.data;
1525 state = DO_UPCAST(InternalSnapshotState, common, common);
1527 /* 1. parse input */
1528 device = internal->device;
1529 name = internal->name;
1531 /* 2. check for validation */
1532 if (action_check_completion_mode(common, errp) < 0) {
1533 return;
1536 bs = qmp_get_root_bs(device, errp);
1537 if (!bs) {
1538 return;
1541 /* AioContext is released in .clean() */
1542 state->aio_context = bdrv_get_aio_context(bs);
1543 aio_context_acquire(state->aio_context);
1545 state->bs = bs;
1546 bdrv_drained_begin(bs);
1548 if (bdrv_op_is_blocked(bs, BLOCK_OP_TYPE_INTERNAL_SNAPSHOT, errp)) {
1549 return;
1552 if (bdrv_is_read_only(bs)) {
1553 error_setg(errp, "Device '%s' is read only", device);
1554 return;
1557 if (!bdrv_can_snapshot(bs)) {
1558 error_setg(errp, "Block format '%s' used by device '%s' "
1559 "does not support internal snapshots",
1560 bs->drv->format_name, device);
1561 return;
1564 if (!strlen(name)) {
1565 error_setg(errp, "Name is empty");
1566 return;
1569 /* check whether a snapshot with name exist */
1570 ret = bdrv_snapshot_find_by_id_and_name(bs, NULL, name, &old_sn,
1571 &local_err);
1572 if (local_err) {
1573 error_propagate(errp, local_err);
1574 return;
1575 } else if (ret) {
1576 error_setg(errp,
1577 "Snapshot with name '%s' already exists on device '%s'",
1578 name, device);
1579 return;
1582 /* 3. take the snapshot */
1583 sn = &state->sn;
1584 pstrcpy(sn->name, sizeof(sn->name), name);
1585 qemu_gettimeofday(&tv);
1586 sn->date_sec = tv.tv_sec;
1587 sn->date_nsec = tv.tv_usec * 1000;
1588 sn->vm_clock_nsec = qemu_clock_get_ns(QEMU_CLOCK_VIRTUAL);
1590 ret1 = bdrv_snapshot_create(bs, sn);
1591 if (ret1 < 0) {
1592 error_setg_errno(errp, -ret1,
1593 "Failed to create snapshot '%s' on device '%s'",
1594 name, device);
1595 return;
1598 /* 4. succeed, mark a snapshot is created */
1599 state->created = true;
1602 static void internal_snapshot_abort(BlkActionState *common)
1604 InternalSnapshotState *state =
1605 DO_UPCAST(InternalSnapshotState, common, common);
1606 BlockDriverState *bs = state->bs;
1607 QEMUSnapshotInfo *sn = &state->sn;
1608 Error *local_error = NULL;
1610 if (!state->created) {
1611 return;
1614 if (bdrv_snapshot_delete(bs, sn->id_str, sn->name, &local_error) < 0) {
1615 error_reportf_err(local_error,
1616 "Failed to delete snapshot with id '%s' and "
1617 "name '%s' on device '%s' in abort: ",
1618 sn->id_str, sn->name,
1619 bdrv_get_device_name(bs));
1623 static void internal_snapshot_clean(BlkActionState *common)
1625 InternalSnapshotState *state = DO_UPCAST(InternalSnapshotState,
1626 common, common);
1628 if (state->aio_context) {
1629 if (state->bs) {
1630 bdrv_drained_end(state->bs);
1632 aio_context_release(state->aio_context);
1636 /* external snapshot private data */
1637 typedef struct ExternalSnapshotState {
1638 BlkActionState common;
1639 BlockDriverState *old_bs;
1640 BlockDriverState *new_bs;
1641 AioContext *aio_context;
1642 } ExternalSnapshotState;
1644 static void external_snapshot_prepare(BlkActionState *common,
1645 Error **errp)
1647 int flags = 0;
1648 QDict *options = NULL;
1649 Error *local_err = NULL;
1650 /* Device and node name of the image to generate the snapshot from */
1651 const char *device;
1652 const char *node_name;
1653 /* Reference to the new image (for 'blockdev-snapshot') */
1654 const char *snapshot_ref;
1655 /* File name of the new image (for 'blockdev-snapshot-sync') */
1656 const char *new_image_file;
1657 ExternalSnapshotState *state =
1658 DO_UPCAST(ExternalSnapshotState, common, common);
1659 TransactionAction *action = common->action;
1661 /* 'blockdev-snapshot' and 'blockdev-snapshot-sync' have similar
1662 * purpose but a different set of parameters */
1663 switch (action->type) {
1664 case TRANSACTION_ACTION_KIND_BLOCKDEV_SNAPSHOT:
1666 BlockdevSnapshot *s = action->u.blockdev_snapshot.data;
1667 device = s->node;
1668 node_name = s->node;
1669 new_image_file = NULL;
1670 snapshot_ref = s->overlay;
1672 break;
1673 case TRANSACTION_ACTION_KIND_BLOCKDEV_SNAPSHOT_SYNC:
1675 BlockdevSnapshotSync *s = action->u.blockdev_snapshot_sync.data;
1676 device = s->has_device ? s->device : NULL;
1677 node_name = s->has_node_name ? s->node_name : NULL;
1678 new_image_file = s->snapshot_file;
1679 snapshot_ref = NULL;
1681 break;
1682 default:
1683 g_assert_not_reached();
1686 /* start processing */
1687 if (action_check_completion_mode(common, errp) < 0) {
1688 return;
1691 state->old_bs = bdrv_lookup_bs(device, node_name, errp);
1692 if (!state->old_bs) {
1693 return;
1696 /* Acquire AioContext now so any threads operating on old_bs stop */
1697 state->aio_context = bdrv_get_aio_context(state->old_bs);
1698 aio_context_acquire(state->aio_context);
1699 bdrv_drained_begin(state->old_bs);
1701 if (!bdrv_is_inserted(state->old_bs)) {
1702 error_setg(errp, QERR_DEVICE_HAS_NO_MEDIUM, device);
1703 return;
1706 if (bdrv_op_is_blocked(state->old_bs,
1707 BLOCK_OP_TYPE_EXTERNAL_SNAPSHOT, errp)) {
1708 return;
1711 if (!bdrv_is_read_only(state->old_bs)) {
1712 if (bdrv_flush(state->old_bs)) {
1713 error_setg(errp, QERR_IO_ERROR);
1714 return;
1718 if (!bdrv_is_first_non_filter(state->old_bs)) {
1719 error_setg(errp, QERR_FEATURE_DISABLED, "snapshot");
1720 return;
1723 if (action->type == TRANSACTION_ACTION_KIND_BLOCKDEV_SNAPSHOT_SYNC) {
1724 BlockdevSnapshotSync *s = action->u.blockdev_snapshot_sync.data;
1725 const char *format = s->has_format ? s->format : "qcow2";
1726 enum NewImageMode mode;
1727 const char *snapshot_node_name =
1728 s->has_snapshot_node_name ? s->snapshot_node_name : NULL;
1730 if (node_name && !snapshot_node_name) {
1731 error_setg(errp, "New snapshot node name missing");
1732 return;
1735 if (snapshot_node_name &&
1736 bdrv_lookup_bs(snapshot_node_name, snapshot_node_name, NULL)) {
1737 error_setg(errp, "New snapshot node name already in use");
1738 return;
1741 flags = state->old_bs->open_flags;
1742 flags &= ~(BDRV_O_SNAPSHOT | BDRV_O_NO_BACKING | BDRV_O_COPY_ON_READ);
1744 /* create new image w/backing file */
1745 mode = s->has_mode ? s->mode : NEW_IMAGE_MODE_ABSOLUTE_PATHS;
1746 if (mode != NEW_IMAGE_MODE_EXISTING) {
1747 int64_t size = bdrv_getlength(state->old_bs);
1748 if (size < 0) {
1749 error_setg_errno(errp, -size, "bdrv_getlength failed");
1750 return;
1752 bdrv_img_create(new_image_file, format,
1753 state->old_bs->filename,
1754 state->old_bs->drv->format_name,
1755 NULL, size, flags, &local_err, false);
1756 if (local_err) {
1757 error_propagate(errp, local_err);
1758 return;
1762 options = qdict_new();
1763 if (s->has_snapshot_node_name) {
1764 qdict_put(options, "node-name",
1765 qstring_from_str(snapshot_node_name));
1767 qdict_put(options, "driver", qstring_from_str(format));
1769 flags |= BDRV_O_NO_BACKING;
1772 state->new_bs = bdrv_open(new_image_file, snapshot_ref, options, flags,
1773 errp);
1774 /* We will manually add the backing_hd field to the bs later */
1775 if (!state->new_bs) {
1776 return;
1779 if (bdrv_has_blk(state->new_bs)) {
1780 error_setg(errp, "The snapshot is already in use by %s",
1781 bdrv_get_parent_name(state->new_bs));
1782 return;
1785 if (bdrv_op_is_blocked(state->new_bs, BLOCK_OP_TYPE_EXTERNAL_SNAPSHOT,
1786 errp)) {
1787 return;
1790 if (state->new_bs->backing != NULL) {
1791 error_setg(errp, "The snapshot already has a backing image");
1792 return;
1795 if (!state->new_bs->drv->supports_backing) {
1796 error_setg(errp, "The snapshot does not support backing images");
1800 static void external_snapshot_commit(BlkActionState *common)
1802 ExternalSnapshotState *state =
1803 DO_UPCAST(ExternalSnapshotState, common, common);
1805 bdrv_set_aio_context(state->new_bs, state->aio_context);
1807 /* This removes our old bs and adds the new bs */
1808 bdrv_append(state->new_bs, state->old_bs);
1809 /* We don't need (or want) to use the transactional
1810 * bdrv_reopen_multiple() across all the entries at once, because we
1811 * don't want to abort all of them if one of them fails the reopen */
1812 if (!state->old_bs->copy_on_read) {
1813 bdrv_reopen(state->old_bs, state->old_bs->open_flags & ~BDRV_O_RDWR,
1814 NULL);
1818 static void external_snapshot_abort(BlkActionState *common)
1820 ExternalSnapshotState *state =
1821 DO_UPCAST(ExternalSnapshotState, common, common);
1822 if (state->new_bs) {
1823 bdrv_unref(state->new_bs);
1827 static void external_snapshot_clean(BlkActionState *common)
1829 ExternalSnapshotState *state =
1830 DO_UPCAST(ExternalSnapshotState, common, common);
1831 if (state->aio_context) {
1832 bdrv_drained_end(state->old_bs);
1833 aio_context_release(state->aio_context);
1837 typedef struct DriveBackupState {
1838 BlkActionState common;
1839 BlockDriverState *bs;
1840 AioContext *aio_context;
1841 BlockJob *job;
1842 } DriveBackupState;
1844 static void do_drive_backup(const char *job_id, const char *device,
1845 const char *target, bool has_format,
1846 const char *format, enum MirrorSyncMode sync,
1847 bool has_mode, enum NewImageMode mode,
1848 bool has_speed, int64_t speed,
1849 bool has_bitmap, const char *bitmap,
1850 bool has_on_source_error,
1851 BlockdevOnError on_source_error,
1852 bool has_on_target_error,
1853 BlockdevOnError on_target_error,
1854 BlockJobTxn *txn, Error **errp);
1856 static void drive_backup_prepare(BlkActionState *common, Error **errp)
1858 DriveBackupState *state = DO_UPCAST(DriveBackupState, common, common);
1859 BlockBackend *blk;
1860 DriveBackup *backup;
1861 Error *local_err = NULL;
1863 assert(common->action->type == TRANSACTION_ACTION_KIND_DRIVE_BACKUP);
1864 backup = common->action->u.drive_backup.data;
1866 blk = blk_by_name(backup->device);
1867 if (!blk) {
1868 error_set(errp, ERROR_CLASS_DEVICE_NOT_FOUND,
1869 "Device '%s' not found", backup->device);
1870 return;
1873 if (!blk_is_available(blk)) {
1874 error_setg(errp, QERR_DEVICE_HAS_NO_MEDIUM, backup->device);
1875 return;
1878 /* AioContext is released in .clean() */
1879 state->aio_context = blk_get_aio_context(blk);
1880 aio_context_acquire(state->aio_context);
1881 bdrv_drained_begin(blk_bs(blk));
1882 state->bs = blk_bs(blk);
1884 do_drive_backup(backup->has_job_id ? backup->job_id : NULL,
1885 backup->device, backup->target,
1886 backup->has_format, backup->format,
1887 backup->sync,
1888 backup->has_mode, backup->mode,
1889 backup->has_speed, backup->speed,
1890 backup->has_bitmap, backup->bitmap,
1891 backup->has_on_source_error, backup->on_source_error,
1892 backup->has_on_target_error, backup->on_target_error,
1893 common->block_job_txn, &local_err);
1894 if (local_err) {
1895 error_propagate(errp, local_err);
1896 return;
1899 state->job = state->bs->job;
1902 static void drive_backup_abort(BlkActionState *common)
1904 DriveBackupState *state = DO_UPCAST(DriveBackupState, common, common);
1905 BlockDriverState *bs = state->bs;
1907 /* Only cancel if it's the job we started */
1908 if (bs && bs->job && bs->job == state->job) {
1909 block_job_cancel_sync(bs->job);
1913 static void drive_backup_clean(BlkActionState *common)
1915 DriveBackupState *state = DO_UPCAST(DriveBackupState, common, common);
1917 if (state->aio_context) {
1918 bdrv_drained_end(state->bs);
1919 aio_context_release(state->aio_context);
1923 typedef struct BlockdevBackupState {
1924 BlkActionState common;
1925 BlockDriverState *bs;
1926 BlockJob *job;
1927 AioContext *aio_context;
1928 } BlockdevBackupState;
1930 static void do_blockdev_backup(const char *job_id, const char *device,
1931 const char *target, enum MirrorSyncMode sync,
1932 bool has_speed, int64_t speed,
1933 bool has_on_source_error,
1934 BlockdevOnError on_source_error,
1935 bool has_on_target_error,
1936 BlockdevOnError on_target_error,
1937 BlockJobTxn *txn, Error **errp);
1939 static void blockdev_backup_prepare(BlkActionState *common, Error **errp)
1941 BlockdevBackupState *state = DO_UPCAST(BlockdevBackupState, common, common);
1942 BlockdevBackup *backup;
1943 BlockDriverState *bs, *target;
1944 Error *local_err = NULL;
1946 assert(common->action->type == TRANSACTION_ACTION_KIND_BLOCKDEV_BACKUP);
1947 backup = common->action->u.blockdev_backup.data;
1949 bs = qmp_get_root_bs(backup->device, errp);
1950 if (!bs) {
1951 return;
1954 target = bdrv_lookup_bs(backup->target, backup->target, errp);
1955 if (!target) {
1956 return;
1959 /* AioContext is released in .clean() */
1960 state->aio_context = bdrv_get_aio_context(bs);
1961 if (state->aio_context != bdrv_get_aio_context(target)) {
1962 state->aio_context = NULL;
1963 error_setg(errp, "Backup between two IO threads is not implemented");
1964 return;
1966 aio_context_acquire(state->aio_context);
1967 state->bs = bs;
1968 bdrv_drained_begin(state->bs);
1970 do_blockdev_backup(backup->has_job_id ? backup->job_id : NULL,
1971 backup->device, backup->target, backup->sync,
1972 backup->has_speed, backup->speed,
1973 backup->has_on_source_error, backup->on_source_error,
1974 backup->has_on_target_error, backup->on_target_error,
1975 common->block_job_txn, &local_err);
1976 if (local_err) {
1977 error_propagate(errp, local_err);
1978 return;
1981 state->job = state->bs->job;
1984 static void blockdev_backup_abort(BlkActionState *common)
1986 BlockdevBackupState *state = DO_UPCAST(BlockdevBackupState, common, common);
1987 BlockDriverState *bs = state->bs;
1989 /* Only cancel if it's the job we started */
1990 if (bs && bs->job && bs->job == state->job) {
1991 block_job_cancel_sync(bs->job);
1995 static void blockdev_backup_clean(BlkActionState *common)
1997 BlockdevBackupState *state = DO_UPCAST(BlockdevBackupState, common, common);
1999 if (state->aio_context) {
2000 bdrv_drained_end(state->bs);
2001 aio_context_release(state->aio_context);
2005 typedef struct BlockDirtyBitmapState {
2006 BlkActionState common;
2007 BdrvDirtyBitmap *bitmap;
2008 BlockDriverState *bs;
2009 AioContext *aio_context;
2010 HBitmap *backup;
2011 bool prepared;
2012 } BlockDirtyBitmapState;
2014 static void block_dirty_bitmap_add_prepare(BlkActionState *common,
2015 Error **errp)
2017 Error *local_err = NULL;
2018 BlockDirtyBitmapAdd *action;
2019 BlockDirtyBitmapState *state = DO_UPCAST(BlockDirtyBitmapState,
2020 common, common);
2022 if (action_check_completion_mode(common, errp) < 0) {
2023 return;
2026 action = common->action->u.block_dirty_bitmap_add.data;
2027 /* AIO context taken and released within qmp_block_dirty_bitmap_add */
2028 qmp_block_dirty_bitmap_add(action->node, action->name,
2029 action->has_granularity, action->granularity,
2030 &local_err);
2032 if (!local_err) {
2033 state->prepared = true;
2034 } else {
2035 error_propagate(errp, local_err);
2039 static void block_dirty_bitmap_add_abort(BlkActionState *common)
2041 BlockDirtyBitmapAdd *action;
2042 BlockDirtyBitmapState *state = DO_UPCAST(BlockDirtyBitmapState,
2043 common, common);
2045 action = common->action->u.block_dirty_bitmap_add.data;
2046 /* Should not be able to fail: IF the bitmap was added via .prepare(),
2047 * then the node reference and bitmap name must have been valid.
2049 if (state->prepared) {
2050 qmp_block_dirty_bitmap_remove(action->node, action->name, &error_abort);
2054 static void block_dirty_bitmap_clear_prepare(BlkActionState *common,
2055 Error **errp)
2057 BlockDirtyBitmapState *state = DO_UPCAST(BlockDirtyBitmapState,
2058 common, common);
2059 BlockDirtyBitmap *action;
2061 if (action_check_completion_mode(common, errp) < 0) {
2062 return;
2065 action = common->action->u.block_dirty_bitmap_clear.data;
2066 state->bitmap = block_dirty_bitmap_lookup(action->node,
2067 action->name,
2068 &state->bs,
2069 &state->aio_context,
2070 errp);
2071 if (!state->bitmap) {
2072 return;
2075 if (bdrv_dirty_bitmap_frozen(state->bitmap)) {
2076 error_setg(errp, "Cannot modify a frozen bitmap");
2077 return;
2078 } else if (!bdrv_dirty_bitmap_enabled(state->bitmap)) {
2079 error_setg(errp, "Cannot clear a disabled bitmap");
2080 return;
2083 bdrv_clear_dirty_bitmap(state->bitmap, &state->backup);
2084 /* AioContext is released in .clean() */
2087 static void block_dirty_bitmap_clear_abort(BlkActionState *common)
2089 BlockDirtyBitmapState *state = DO_UPCAST(BlockDirtyBitmapState,
2090 common, common);
2092 bdrv_undo_clear_dirty_bitmap(state->bitmap, state->backup);
2095 static void block_dirty_bitmap_clear_commit(BlkActionState *common)
2097 BlockDirtyBitmapState *state = DO_UPCAST(BlockDirtyBitmapState,
2098 common, common);
2100 hbitmap_free(state->backup);
2103 static void block_dirty_bitmap_clear_clean(BlkActionState *common)
2105 BlockDirtyBitmapState *state = DO_UPCAST(BlockDirtyBitmapState,
2106 common, common);
2108 if (state->aio_context) {
2109 aio_context_release(state->aio_context);
2113 static void abort_prepare(BlkActionState *common, Error **errp)
2115 error_setg(errp, "Transaction aborted using Abort action");
2118 static void abort_commit(BlkActionState *common)
2120 g_assert_not_reached(); /* this action never succeeds */
2123 static const BlkActionOps actions[] = {
2124 [TRANSACTION_ACTION_KIND_BLOCKDEV_SNAPSHOT] = {
2125 .instance_size = sizeof(ExternalSnapshotState),
2126 .prepare = external_snapshot_prepare,
2127 .commit = external_snapshot_commit,
2128 .abort = external_snapshot_abort,
2129 .clean = external_snapshot_clean,
2131 [TRANSACTION_ACTION_KIND_BLOCKDEV_SNAPSHOT_SYNC] = {
2132 .instance_size = sizeof(ExternalSnapshotState),
2133 .prepare = external_snapshot_prepare,
2134 .commit = external_snapshot_commit,
2135 .abort = external_snapshot_abort,
2136 .clean = external_snapshot_clean,
2138 [TRANSACTION_ACTION_KIND_DRIVE_BACKUP] = {
2139 .instance_size = sizeof(DriveBackupState),
2140 .prepare = drive_backup_prepare,
2141 .abort = drive_backup_abort,
2142 .clean = drive_backup_clean,
2144 [TRANSACTION_ACTION_KIND_BLOCKDEV_BACKUP] = {
2145 .instance_size = sizeof(BlockdevBackupState),
2146 .prepare = blockdev_backup_prepare,
2147 .abort = blockdev_backup_abort,
2148 .clean = blockdev_backup_clean,
2150 [TRANSACTION_ACTION_KIND_ABORT] = {
2151 .instance_size = sizeof(BlkActionState),
2152 .prepare = abort_prepare,
2153 .commit = abort_commit,
2155 [TRANSACTION_ACTION_KIND_BLOCKDEV_SNAPSHOT_INTERNAL_SYNC] = {
2156 .instance_size = sizeof(InternalSnapshotState),
2157 .prepare = internal_snapshot_prepare,
2158 .abort = internal_snapshot_abort,
2159 .clean = internal_snapshot_clean,
2161 [TRANSACTION_ACTION_KIND_BLOCK_DIRTY_BITMAP_ADD] = {
2162 .instance_size = sizeof(BlockDirtyBitmapState),
2163 .prepare = block_dirty_bitmap_add_prepare,
2164 .abort = block_dirty_bitmap_add_abort,
2166 [TRANSACTION_ACTION_KIND_BLOCK_DIRTY_BITMAP_CLEAR] = {
2167 .instance_size = sizeof(BlockDirtyBitmapState),
2168 .prepare = block_dirty_bitmap_clear_prepare,
2169 .commit = block_dirty_bitmap_clear_commit,
2170 .abort = block_dirty_bitmap_clear_abort,
2171 .clean = block_dirty_bitmap_clear_clean,
2176 * Allocate a TransactionProperties structure if necessary, and fill
2177 * that structure with desired defaults if they are unset.
2179 static TransactionProperties *get_transaction_properties(
2180 TransactionProperties *props)
2182 if (!props) {
2183 props = g_new0(TransactionProperties, 1);
2186 if (!props->has_completion_mode) {
2187 props->has_completion_mode = true;
2188 props->completion_mode = ACTION_COMPLETION_MODE_INDIVIDUAL;
2191 return props;
2195 * 'Atomic' group operations. The operations are performed as a set, and if
2196 * any fail then we roll back all operations in the group.
2198 void qmp_transaction(TransactionActionList *dev_list,
2199 bool has_props,
2200 struct TransactionProperties *props,
2201 Error **errp)
2203 TransactionActionList *dev_entry = dev_list;
2204 BlockJobTxn *block_job_txn = NULL;
2205 BlkActionState *state, *next;
2206 Error *local_err = NULL;
2208 QSIMPLEQ_HEAD(snap_bdrv_states, BlkActionState) snap_bdrv_states;
2209 QSIMPLEQ_INIT(&snap_bdrv_states);
2211 /* Does this transaction get canceled as a group on failure?
2212 * If not, we don't really need to make a BlockJobTxn.
2214 props = get_transaction_properties(props);
2215 if (props->completion_mode != ACTION_COMPLETION_MODE_INDIVIDUAL) {
2216 block_job_txn = block_job_txn_new();
2219 /* drain all i/o before any operations */
2220 bdrv_drain_all();
2222 /* We don't do anything in this loop that commits us to the operations */
2223 while (NULL != dev_entry) {
2224 TransactionAction *dev_info = NULL;
2225 const BlkActionOps *ops;
2227 dev_info = dev_entry->value;
2228 dev_entry = dev_entry->next;
2230 assert(dev_info->type < ARRAY_SIZE(actions));
2232 ops = &actions[dev_info->type];
2233 assert(ops->instance_size > 0);
2235 state = g_malloc0(ops->instance_size);
2236 state->ops = ops;
2237 state->action = dev_info;
2238 state->block_job_txn = block_job_txn;
2239 state->txn_props = props;
2240 QSIMPLEQ_INSERT_TAIL(&snap_bdrv_states, state, entry);
2242 state->ops->prepare(state, &local_err);
2243 if (local_err) {
2244 error_propagate(errp, local_err);
2245 goto delete_and_fail;
2249 QSIMPLEQ_FOREACH(state, &snap_bdrv_states, entry) {
2250 if (state->ops->commit) {
2251 state->ops->commit(state);
2255 /* success */
2256 goto exit;
2258 delete_and_fail:
2259 /* failure, and it is all-or-none; roll back all operations */
2260 QSIMPLEQ_FOREACH(state, &snap_bdrv_states, entry) {
2261 if (state->ops->abort) {
2262 state->ops->abort(state);
2265 exit:
2266 QSIMPLEQ_FOREACH_SAFE(state, &snap_bdrv_states, entry, next) {
2267 if (state->ops->clean) {
2268 state->ops->clean(state);
2270 g_free(state);
2272 if (!has_props) {
2273 qapi_free_TransactionProperties(props);
2275 block_job_txn_unref(block_job_txn);
2278 void qmp_eject(const char *device, bool has_force, bool force, Error **errp)
2280 Error *local_err = NULL;
2281 int rc;
2283 if (!has_force) {
2284 force = false;
2287 rc = do_open_tray(device, force, &local_err);
2288 if (rc && rc != -ENOSYS) {
2289 error_propagate(errp, local_err);
2290 return;
2292 error_free(local_err);
2294 qmp_x_blockdev_remove_medium(device, errp);
2297 void qmp_block_passwd(bool has_device, const char *device,
2298 bool has_node_name, const char *node_name,
2299 const char *password, Error **errp)
2301 Error *local_err = NULL;
2302 BlockDriverState *bs;
2303 AioContext *aio_context;
2305 bs = bdrv_lookup_bs(has_device ? device : NULL,
2306 has_node_name ? node_name : NULL,
2307 &local_err);
2308 if (local_err) {
2309 error_propagate(errp, local_err);
2310 return;
2313 aio_context = bdrv_get_aio_context(bs);
2314 aio_context_acquire(aio_context);
2316 bdrv_add_key(bs, password, errp);
2318 aio_context_release(aio_context);
2322 * Attempt to open the tray of @device.
2323 * If @force, ignore its tray lock.
2324 * Else, if the tray is locked, don't open it, but ask the guest to open it.
2325 * On error, store an error through @errp and return -errno.
2326 * If @device does not exist, return -ENODEV.
2327 * If it has no removable media, return -ENOTSUP.
2328 * If it has no tray, return -ENOSYS.
2329 * If the guest was asked to open the tray, return -EINPROGRESS.
2330 * Else, return 0.
2332 static int do_open_tray(const char *device, bool force, Error **errp)
2334 BlockBackend *blk;
2335 bool locked;
2337 blk = blk_by_name(device);
2338 if (!blk) {
2339 error_set(errp, ERROR_CLASS_DEVICE_NOT_FOUND,
2340 "Device '%s' not found", device);
2341 return -ENODEV;
2344 if (!blk_dev_has_removable_media(blk)) {
2345 error_setg(errp, "Device '%s' is not removable", device);
2346 return -ENOTSUP;
2349 if (!blk_dev_has_tray(blk)) {
2350 error_setg(errp, "Device '%s' does not have a tray", device);
2351 return -ENOSYS;
2354 if (blk_dev_is_tray_open(blk)) {
2355 return 0;
2358 locked = blk_dev_is_medium_locked(blk);
2359 if (locked) {
2360 blk_dev_eject_request(blk, force);
2363 if (!locked || force) {
2364 blk_dev_change_media_cb(blk, false);
2367 if (locked && !force) {
2368 error_setg(errp, "Device '%s' is locked and force was not specified, "
2369 "wait for tray to open and try again", device);
2370 return -EINPROGRESS;
2373 return 0;
2376 void qmp_blockdev_open_tray(const char *device, bool has_force, bool force,
2377 Error **errp)
2379 Error *local_err = NULL;
2380 int rc;
2382 if (!has_force) {
2383 force = false;
2385 rc = do_open_tray(device, force, &local_err);
2386 if (rc && rc != -ENOSYS && rc != -EINPROGRESS) {
2387 error_propagate(errp, local_err);
2388 return;
2390 error_free(local_err);
2393 void qmp_blockdev_close_tray(const char *device, Error **errp)
2395 BlockBackend *blk;
2397 blk = blk_by_name(device);
2398 if (!blk) {
2399 error_set(errp, ERROR_CLASS_DEVICE_NOT_FOUND,
2400 "Device '%s' not found", device);
2401 return;
2404 if (!blk_dev_has_removable_media(blk)) {
2405 error_setg(errp, "Device '%s' is not removable", device);
2406 return;
2409 if (!blk_dev_has_tray(blk)) {
2410 /* Ignore this command on tray-less devices */
2411 return;
2414 if (!blk_dev_is_tray_open(blk)) {
2415 return;
2418 blk_dev_change_media_cb(blk, true);
2421 void qmp_x_blockdev_remove_medium(const char *device, Error **errp)
2423 BlockBackend *blk;
2424 BlockDriverState *bs;
2425 AioContext *aio_context;
2426 bool has_device;
2428 blk = blk_by_name(device);
2429 if (!blk) {
2430 error_set(errp, ERROR_CLASS_DEVICE_NOT_FOUND,
2431 "Device '%s' not found", device);
2432 return;
2435 /* For BBs without a device, we can exchange the BDS tree at will */
2436 has_device = blk_get_attached_dev(blk);
2438 if (has_device && !blk_dev_has_removable_media(blk)) {
2439 error_setg(errp, "Device '%s' is not removable", device);
2440 return;
2443 if (has_device && blk_dev_has_tray(blk) && !blk_dev_is_tray_open(blk)) {
2444 error_setg(errp, "Tray of device '%s' is not open", device);
2445 return;
2448 bs = blk_bs(blk);
2449 if (!bs) {
2450 return;
2453 aio_context = bdrv_get_aio_context(bs);
2454 aio_context_acquire(aio_context);
2456 if (bdrv_op_is_blocked(bs, BLOCK_OP_TYPE_EJECT, errp)) {
2457 goto out;
2460 blk_remove_bs(blk);
2462 if (!blk_dev_has_tray(blk)) {
2463 /* For tray-less devices, blockdev-open-tray is a no-op (or may not be
2464 * called at all); therefore, the medium needs to be ejected here.
2465 * Do it after blk_remove_bs() so blk_is_inserted(blk) returns the @load
2466 * value passed here (i.e. false). */
2467 blk_dev_change_media_cb(blk, false);
2470 out:
2471 aio_context_release(aio_context);
2474 static void qmp_blockdev_insert_anon_medium(const char *device,
2475 BlockDriverState *bs, Error **errp)
2477 BlockBackend *blk;
2478 bool has_device;
2480 blk = blk_by_name(device);
2481 if (!blk) {
2482 error_set(errp, ERROR_CLASS_DEVICE_NOT_FOUND,
2483 "Device '%s' not found", device);
2484 return;
2487 /* For BBs without a device, we can exchange the BDS tree at will */
2488 has_device = blk_get_attached_dev(blk);
2490 if (has_device && !blk_dev_has_removable_media(blk)) {
2491 error_setg(errp, "Device '%s' is not removable", device);
2492 return;
2495 if (has_device && blk_dev_has_tray(blk) && !blk_dev_is_tray_open(blk)) {
2496 error_setg(errp, "Tray of device '%s' is not open", device);
2497 return;
2500 if (blk_bs(blk)) {
2501 error_setg(errp, "There already is a medium in device '%s'", device);
2502 return;
2505 blk_insert_bs(blk, bs);
2507 if (!blk_dev_has_tray(blk)) {
2508 /* For tray-less devices, blockdev-close-tray is a no-op (or may not be
2509 * called at all); therefore, the medium needs to be pushed into the
2510 * slot here.
2511 * Do it after blk_insert_bs() so blk_is_inserted(blk) returns the @load
2512 * value passed here (i.e. true). */
2513 blk_dev_change_media_cb(blk, true);
2517 void qmp_x_blockdev_insert_medium(const char *device, const char *node_name,
2518 Error **errp)
2520 BlockDriverState *bs;
2522 bs = bdrv_find_node(node_name);
2523 if (!bs) {
2524 error_setg(errp, "Node '%s' not found", node_name);
2525 return;
2528 if (bdrv_has_blk(bs)) {
2529 error_setg(errp, "Node '%s' is already in use by '%s'", node_name,
2530 bdrv_get_parent_name(bs));
2531 return;
2534 qmp_blockdev_insert_anon_medium(device, bs, errp);
2537 void qmp_blockdev_change_medium(const char *device, const char *filename,
2538 bool has_format, const char *format,
2539 bool has_read_only,
2540 BlockdevChangeReadOnlyMode read_only,
2541 Error **errp)
2543 BlockBackend *blk;
2544 BlockDriverState *medium_bs = NULL;
2545 int bdrv_flags;
2546 int rc;
2547 QDict *options = NULL;
2548 Error *err = NULL;
2550 blk = blk_by_name(device);
2551 if (!blk) {
2552 error_set(errp, ERROR_CLASS_DEVICE_NOT_FOUND,
2553 "Device '%s' not found", device);
2554 goto fail;
2557 if (blk_bs(blk)) {
2558 blk_update_root_state(blk);
2561 bdrv_flags = blk_get_open_flags_from_root_state(blk);
2562 bdrv_flags &= ~(BDRV_O_TEMPORARY | BDRV_O_SNAPSHOT | BDRV_O_NO_BACKING |
2563 BDRV_O_PROTOCOL);
2565 if (!has_read_only) {
2566 read_only = BLOCKDEV_CHANGE_READ_ONLY_MODE_RETAIN;
2569 switch (read_only) {
2570 case BLOCKDEV_CHANGE_READ_ONLY_MODE_RETAIN:
2571 break;
2573 case BLOCKDEV_CHANGE_READ_ONLY_MODE_READ_ONLY:
2574 bdrv_flags &= ~BDRV_O_RDWR;
2575 break;
2577 case BLOCKDEV_CHANGE_READ_ONLY_MODE_READ_WRITE:
2578 bdrv_flags |= BDRV_O_RDWR;
2579 break;
2581 default:
2582 abort();
2585 if (has_format) {
2586 options = qdict_new();
2587 qdict_put(options, "driver", qstring_from_str(format));
2590 medium_bs = bdrv_open(filename, NULL, options, bdrv_flags, errp);
2591 if (!medium_bs) {
2592 goto fail;
2595 bdrv_add_key(medium_bs, NULL, &err);
2596 if (err) {
2597 error_propagate(errp, err);
2598 goto fail;
2601 rc = do_open_tray(device, false, &err);
2602 if (rc && rc != -ENOSYS) {
2603 error_propagate(errp, err);
2604 goto fail;
2606 error_free(err);
2607 err = NULL;
2609 qmp_x_blockdev_remove_medium(device, &err);
2610 if (err) {
2611 error_propagate(errp, err);
2612 goto fail;
2615 qmp_blockdev_insert_anon_medium(device, medium_bs, &err);
2616 if (err) {
2617 error_propagate(errp, err);
2618 goto fail;
2621 blk_apply_root_state(blk, medium_bs);
2623 qmp_blockdev_close_tray(device, errp);
2625 fail:
2626 /* If the medium has been inserted, the device has its own reference, so
2627 * ours must be relinquished; and if it has not been inserted successfully,
2628 * the reference must be relinquished anyway */
2629 bdrv_unref(medium_bs);
2632 /* throttling disk I/O limits */
2633 void qmp_block_set_io_throttle(BlockIOThrottle *arg, Error **errp)
2635 ThrottleConfig cfg;
2636 BlockDriverState *bs;
2637 BlockBackend *blk;
2638 AioContext *aio_context;
2640 blk = blk_by_name(arg->device);
2641 if (!blk) {
2642 error_set(errp, ERROR_CLASS_DEVICE_NOT_FOUND,
2643 "Device '%s' not found", arg->device);
2644 return;
2647 aio_context = blk_get_aio_context(blk);
2648 aio_context_acquire(aio_context);
2650 bs = blk_bs(blk);
2651 if (!bs) {
2652 error_setg(errp, "Device '%s' has no medium", arg->device);
2653 goto out;
2656 throttle_config_init(&cfg);
2657 cfg.buckets[THROTTLE_BPS_TOTAL].avg = arg->bps;
2658 cfg.buckets[THROTTLE_BPS_READ].avg = arg->bps_rd;
2659 cfg.buckets[THROTTLE_BPS_WRITE].avg = arg->bps_wr;
2661 cfg.buckets[THROTTLE_OPS_TOTAL].avg = arg->iops;
2662 cfg.buckets[THROTTLE_OPS_READ].avg = arg->iops_rd;
2663 cfg.buckets[THROTTLE_OPS_WRITE].avg = arg->iops_wr;
2665 if (arg->has_bps_max) {
2666 cfg.buckets[THROTTLE_BPS_TOTAL].max = arg->bps_max;
2668 if (arg->has_bps_rd_max) {
2669 cfg.buckets[THROTTLE_BPS_READ].max = arg->bps_rd_max;
2671 if (arg->has_bps_wr_max) {
2672 cfg.buckets[THROTTLE_BPS_WRITE].max = arg->bps_wr_max;
2674 if (arg->has_iops_max) {
2675 cfg.buckets[THROTTLE_OPS_TOTAL].max = arg->iops_max;
2677 if (arg->has_iops_rd_max) {
2678 cfg.buckets[THROTTLE_OPS_READ].max = arg->iops_rd_max;
2680 if (arg->has_iops_wr_max) {
2681 cfg.buckets[THROTTLE_OPS_WRITE].max = arg->iops_wr_max;
2684 if (arg->has_bps_max_length) {
2685 cfg.buckets[THROTTLE_BPS_TOTAL].burst_length = arg->bps_max_length;
2687 if (arg->has_bps_rd_max_length) {
2688 cfg.buckets[THROTTLE_BPS_READ].burst_length = arg->bps_rd_max_length;
2690 if (arg->has_bps_wr_max_length) {
2691 cfg.buckets[THROTTLE_BPS_WRITE].burst_length = arg->bps_wr_max_length;
2693 if (arg->has_iops_max_length) {
2694 cfg.buckets[THROTTLE_OPS_TOTAL].burst_length = arg->iops_max_length;
2696 if (arg->has_iops_rd_max_length) {
2697 cfg.buckets[THROTTLE_OPS_READ].burst_length = arg->iops_rd_max_length;
2699 if (arg->has_iops_wr_max_length) {
2700 cfg.buckets[THROTTLE_OPS_WRITE].burst_length = arg->iops_wr_max_length;
2703 if (arg->has_iops_size) {
2704 cfg.op_size = arg->iops_size;
2707 if (!throttle_is_valid(&cfg, errp)) {
2708 goto out;
2711 if (throttle_enabled(&cfg)) {
2712 /* Enable I/O limits if they're not enabled yet, otherwise
2713 * just update the throttling group. */
2714 if (!blk_get_public(blk)->throttle_state) {
2715 blk_io_limits_enable(blk,
2716 arg->has_group ? arg->group : arg->device);
2717 } else if (arg->has_group) {
2718 blk_io_limits_update_group(blk, arg->group);
2720 /* Set the new throttling configuration */
2721 blk_set_io_limits(blk, &cfg);
2722 } else if (blk_get_public(blk)->throttle_state) {
2723 /* If all throttling settings are set to 0, disable I/O limits */
2724 blk_io_limits_disable(blk);
2727 out:
2728 aio_context_release(aio_context);
2731 void qmp_block_dirty_bitmap_add(const char *node, const char *name,
2732 bool has_granularity, uint32_t granularity,
2733 Error **errp)
2735 AioContext *aio_context;
2736 BlockDriverState *bs;
2738 if (!name || name[0] == '\0') {
2739 error_setg(errp, "Bitmap name cannot be empty");
2740 return;
2743 bs = bdrv_lookup_bs(node, node, errp);
2744 if (!bs) {
2745 return;
2748 aio_context = bdrv_get_aio_context(bs);
2749 aio_context_acquire(aio_context);
2751 if (has_granularity) {
2752 if (granularity < 512 || !is_power_of_2(granularity)) {
2753 error_setg(errp, "Granularity must be power of 2 "
2754 "and at least 512");
2755 goto out;
2757 } else {
2758 /* Default to cluster size, if available: */
2759 granularity = bdrv_get_default_bitmap_granularity(bs);
2762 bdrv_create_dirty_bitmap(bs, granularity, name, errp);
2764 out:
2765 aio_context_release(aio_context);
2768 void qmp_block_dirty_bitmap_remove(const char *node, const char *name,
2769 Error **errp)
2771 AioContext *aio_context;
2772 BlockDriverState *bs;
2773 BdrvDirtyBitmap *bitmap;
2775 bitmap = block_dirty_bitmap_lookup(node, name, &bs, &aio_context, errp);
2776 if (!bitmap || !bs) {
2777 return;
2780 if (bdrv_dirty_bitmap_frozen(bitmap)) {
2781 error_setg(errp,
2782 "Bitmap '%s' is currently frozen and cannot be removed",
2783 name);
2784 goto out;
2786 bdrv_dirty_bitmap_make_anon(bitmap);
2787 bdrv_release_dirty_bitmap(bs, bitmap);
2789 out:
2790 aio_context_release(aio_context);
2794 * Completely clear a bitmap, for the purposes of synchronizing a bitmap
2795 * immediately after a full backup operation.
2797 void qmp_block_dirty_bitmap_clear(const char *node, const char *name,
2798 Error **errp)
2800 AioContext *aio_context;
2801 BdrvDirtyBitmap *bitmap;
2802 BlockDriverState *bs;
2804 bitmap = block_dirty_bitmap_lookup(node, name, &bs, &aio_context, errp);
2805 if (!bitmap || !bs) {
2806 return;
2809 if (bdrv_dirty_bitmap_frozen(bitmap)) {
2810 error_setg(errp,
2811 "Bitmap '%s' is currently frozen and cannot be modified",
2812 name);
2813 goto out;
2814 } else if (!bdrv_dirty_bitmap_enabled(bitmap)) {
2815 error_setg(errp,
2816 "Bitmap '%s' is currently disabled and cannot be cleared",
2817 name);
2818 goto out;
2821 bdrv_clear_dirty_bitmap(bitmap, NULL);
2823 out:
2824 aio_context_release(aio_context);
2827 void hmp_drive_del(Monitor *mon, const QDict *qdict)
2829 const char *id = qdict_get_str(qdict, "id");
2830 BlockBackend *blk;
2831 BlockDriverState *bs;
2832 AioContext *aio_context;
2833 Error *local_err = NULL;
2835 bs = bdrv_find_node(id);
2836 if (bs) {
2837 qmp_x_blockdev_del(false, NULL, true, id, &local_err);
2838 if (local_err) {
2839 error_report_err(local_err);
2841 return;
2844 blk = blk_by_name(id);
2845 if (!blk) {
2846 error_report("Device '%s' not found", id);
2847 return;
2850 if (!blk_legacy_dinfo(blk)) {
2851 error_report("Deleting device added with blockdev-add"
2852 " is not supported");
2853 return;
2856 aio_context = blk_get_aio_context(blk);
2857 aio_context_acquire(aio_context);
2859 bs = blk_bs(blk);
2860 if (bs) {
2861 if (bdrv_op_is_blocked(bs, BLOCK_OP_TYPE_DRIVE_DEL, &local_err)) {
2862 error_report_err(local_err);
2863 aio_context_release(aio_context);
2864 return;
2867 blk_remove_bs(blk);
2870 /* Make the BlockBackend and the attached BlockDriverState anonymous */
2871 monitor_remove_blk(blk);
2873 /* If this BlockBackend has a device attached to it, its refcount will be
2874 * decremented when the device is removed; otherwise we have to do so here.
2876 if (blk_get_attached_dev(blk)) {
2877 /* Further I/O must not pause the guest */
2878 blk_set_on_error(blk, BLOCKDEV_ON_ERROR_REPORT,
2879 BLOCKDEV_ON_ERROR_REPORT);
2880 } else {
2881 blk_unref(blk);
2884 aio_context_release(aio_context);
2887 void qmp_block_resize(bool has_device, const char *device,
2888 bool has_node_name, const char *node_name,
2889 int64_t size, Error **errp)
2891 Error *local_err = 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 /* complete all in-flight operations before resizing the device */
2923 bdrv_drain_all();
2925 ret = bdrv_truncate(bs, size);
2926 switch (ret) {
2927 case 0:
2928 break;
2929 case -ENOMEDIUM:
2930 error_setg(errp, QERR_DEVICE_HAS_NO_MEDIUM, device);
2931 break;
2932 case -ENOTSUP:
2933 error_setg(errp, QERR_UNSUPPORTED);
2934 break;
2935 case -EACCES:
2936 error_setg(errp, "Device '%s' is read only", device);
2937 break;
2938 case -EBUSY:
2939 error_setg(errp, QERR_DEVICE_IN_USE, device);
2940 break;
2941 default:
2942 error_setg_errno(errp, -ret, "Could not resize");
2943 break;
2946 out:
2947 aio_context_release(aio_context);
2950 static void block_job_cb(void *opaque, int ret)
2952 /* Note that this function may be executed from another AioContext besides
2953 * the QEMU main loop. If you need to access anything that assumes the
2954 * QEMU global mutex, use a BH or introduce a mutex.
2957 BlockDriverState *bs = opaque;
2958 const char *msg = NULL;
2960 trace_block_job_cb(bs, bs->job, ret);
2962 assert(bs->job);
2964 if (ret < 0) {
2965 msg = strerror(-ret);
2968 if (block_job_is_cancelled(bs->job)) {
2969 block_job_event_cancelled(bs->job);
2970 } else {
2971 block_job_event_completed(bs->job, msg);
2975 void qmp_block_stream(bool has_job_id, const char *job_id, const char *device,
2976 bool has_base, const char *base,
2977 bool has_backing_file, const char *backing_file,
2978 bool has_speed, int64_t speed,
2979 bool has_on_error, BlockdevOnError on_error,
2980 Error **errp)
2982 BlockDriverState *bs;
2983 BlockDriverState *base_bs = NULL;
2984 AioContext *aio_context;
2985 Error *local_err = NULL;
2986 const char *base_name = NULL;
2988 if (!has_on_error) {
2989 on_error = BLOCKDEV_ON_ERROR_REPORT;
2992 bs = qmp_get_root_bs(device, errp);
2993 if (!bs) {
2994 return;
2997 aio_context = bdrv_get_aio_context(bs);
2998 aio_context_acquire(aio_context);
3000 if (bdrv_op_is_blocked(bs, BLOCK_OP_TYPE_STREAM, errp)) {
3001 goto out;
3004 if (has_base) {
3005 base_bs = bdrv_find_backing_image(bs, base);
3006 if (base_bs == NULL) {
3007 error_setg(errp, QERR_BASE_NOT_FOUND, base);
3008 goto out;
3010 assert(bdrv_get_aio_context(base_bs) == aio_context);
3011 base_name = base;
3014 /* if we are streaming the entire chain, the result will have no backing
3015 * file, and specifying one is therefore an error */
3016 if (base_bs == NULL && has_backing_file) {
3017 error_setg(errp, "backing file specified, but streaming the "
3018 "entire chain");
3019 goto out;
3022 /* backing_file string overrides base bs filename */
3023 base_name = has_backing_file ? backing_file : base_name;
3025 stream_start(has_job_id ? job_id : NULL, bs, base_bs, base_name,
3026 has_speed ? speed : 0, on_error, block_job_cb, bs, &local_err);
3027 if (local_err) {
3028 error_propagate(errp, local_err);
3029 goto out;
3032 trace_qmp_block_stream(bs, bs->job);
3034 out:
3035 aio_context_release(aio_context);
3038 void qmp_block_commit(bool has_job_id, const char *job_id, const char *device,
3039 bool has_base, const char *base,
3040 bool has_top, const char *top,
3041 bool has_backing_file, const char *backing_file,
3042 bool has_speed, int64_t speed,
3043 Error **errp)
3045 BlockDriverState *bs;
3046 BlockDriverState *base_bs, *top_bs;
3047 AioContext *aio_context;
3048 Error *local_err = NULL;
3049 /* This will be part of the QMP command, if/when the
3050 * BlockdevOnError change for blkmirror makes it in
3052 BlockdevOnError on_error = BLOCKDEV_ON_ERROR_REPORT;
3054 if (!has_speed) {
3055 speed = 0;
3058 /* Important Note:
3059 * libvirt relies on the DeviceNotFound error class in order to probe for
3060 * live commit feature versions; for this to work, we must make sure to
3061 * perform the device lookup before any generic errors that may occur in a
3062 * scenario in which all optional arguments are omitted. */
3063 bs = qmp_get_root_bs(device, &local_err);
3064 if (!bs) {
3065 bs = bdrv_lookup_bs(device, device, NULL);
3066 if (!bs) {
3067 error_free(local_err);
3068 error_set(errp, ERROR_CLASS_DEVICE_NOT_FOUND,
3069 "Device '%s' not found", device);
3070 } else {
3071 error_propagate(errp, local_err);
3073 return;
3076 aio_context = bdrv_get_aio_context(bs);
3077 aio_context_acquire(aio_context);
3079 if (bdrv_op_is_blocked(bs, BLOCK_OP_TYPE_COMMIT_SOURCE, errp)) {
3080 goto out;
3083 /* default top_bs is the active layer */
3084 top_bs = bs;
3086 if (has_top && top) {
3087 if (strcmp(bs->filename, top) != 0) {
3088 top_bs = bdrv_find_backing_image(bs, top);
3092 if (top_bs == NULL) {
3093 error_setg(errp, "Top image file %s not found", top ? top : "NULL");
3094 goto out;
3097 assert(bdrv_get_aio_context(top_bs) == aio_context);
3099 if (has_base && base) {
3100 base_bs = bdrv_find_backing_image(top_bs, base);
3101 } else {
3102 base_bs = bdrv_find_base(top_bs);
3105 if (base_bs == NULL) {
3106 error_setg(errp, QERR_BASE_NOT_FOUND, base ? base : "NULL");
3107 goto out;
3110 assert(bdrv_get_aio_context(base_bs) == aio_context);
3112 if (bdrv_op_is_blocked(base_bs, BLOCK_OP_TYPE_COMMIT_TARGET, errp)) {
3113 goto out;
3116 /* Do not allow attempts to commit an image into itself */
3117 if (top_bs == base_bs) {
3118 error_setg(errp, "cannot commit an image into itself");
3119 goto out;
3122 if (top_bs == bs) {
3123 if (has_backing_file) {
3124 error_setg(errp, "'backing-file' specified,"
3125 " but 'top' is the active layer");
3126 goto out;
3128 commit_active_start(has_job_id ? job_id : NULL, bs, base_bs, speed,
3129 on_error, block_job_cb, bs, &local_err);
3130 } else {
3131 commit_start(has_job_id ? job_id : NULL, bs, base_bs, top_bs, speed,
3132 on_error, block_job_cb, bs,
3133 has_backing_file ? backing_file : NULL, &local_err);
3135 if (local_err != NULL) {
3136 error_propagate(errp, local_err);
3137 goto out;
3140 out:
3141 aio_context_release(aio_context);
3144 static void do_drive_backup(const char *job_id, const char *device,
3145 const char *target, bool has_format,
3146 const char *format, enum MirrorSyncMode sync,
3147 bool has_mode, enum NewImageMode mode,
3148 bool has_speed, int64_t speed,
3149 bool has_bitmap, const char *bitmap,
3150 bool has_on_source_error,
3151 BlockdevOnError on_source_error,
3152 bool has_on_target_error,
3153 BlockdevOnError on_target_error,
3154 BlockJobTxn *txn, Error **errp)
3156 BlockBackend *blk;
3157 BlockDriverState *bs;
3158 BlockDriverState *target_bs;
3159 BlockDriverState *source = NULL;
3160 BdrvDirtyBitmap *bmap = NULL;
3161 AioContext *aio_context;
3162 QDict *options = NULL;
3163 Error *local_err = NULL;
3164 int flags;
3165 int64_t size;
3167 if (!has_speed) {
3168 speed = 0;
3170 if (!has_on_source_error) {
3171 on_source_error = BLOCKDEV_ON_ERROR_REPORT;
3173 if (!has_on_target_error) {
3174 on_target_error = BLOCKDEV_ON_ERROR_REPORT;
3176 if (!has_mode) {
3177 mode = NEW_IMAGE_MODE_ABSOLUTE_PATHS;
3180 blk = blk_by_name(device);
3181 if (!blk) {
3182 error_set(errp, ERROR_CLASS_DEVICE_NOT_FOUND,
3183 "Device '%s' not found", device);
3184 return;
3187 aio_context = blk_get_aio_context(blk);
3188 aio_context_acquire(aio_context);
3190 /* Although backup_run has this check too, we need to use bs->drv below, so
3191 * do an early check redundantly. */
3192 if (!blk_is_available(blk)) {
3193 error_setg(errp, QERR_DEVICE_HAS_NO_MEDIUM, device);
3194 goto out;
3196 bs = blk_bs(blk);
3198 if (!has_format) {
3199 format = mode == NEW_IMAGE_MODE_EXISTING ? NULL : bs->drv->format_name;
3202 /* Early check to avoid creating target */
3203 if (bdrv_op_is_blocked(bs, BLOCK_OP_TYPE_BACKUP_SOURCE, errp)) {
3204 goto out;
3207 flags = bs->open_flags | BDRV_O_RDWR;
3209 /* See if we have a backing HD we can use to create our new image
3210 * on top of. */
3211 if (sync == MIRROR_SYNC_MODE_TOP) {
3212 source = backing_bs(bs);
3213 if (!source) {
3214 sync = MIRROR_SYNC_MODE_FULL;
3217 if (sync == MIRROR_SYNC_MODE_NONE) {
3218 source = bs;
3221 size = bdrv_getlength(bs);
3222 if (size < 0) {
3223 error_setg_errno(errp, -size, "bdrv_getlength failed");
3224 goto out;
3227 if (mode != NEW_IMAGE_MODE_EXISTING) {
3228 assert(format);
3229 if (source) {
3230 bdrv_img_create(target, format, source->filename,
3231 source->drv->format_name, NULL,
3232 size, flags, &local_err, false);
3233 } else {
3234 bdrv_img_create(target, format, NULL, NULL, NULL,
3235 size, flags, &local_err, false);
3239 if (local_err) {
3240 error_propagate(errp, local_err);
3241 goto out;
3244 if (format) {
3245 options = qdict_new();
3246 qdict_put(options, "driver", qstring_from_str(format));
3249 target_bs = bdrv_open(target, NULL, options, flags, errp);
3250 if (!target_bs) {
3251 goto out;
3254 bdrv_set_aio_context(target_bs, aio_context);
3256 if (has_bitmap) {
3257 bmap = bdrv_find_dirty_bitmap(bs, bitmap);
3258 if (!bmap) {
3259 error_setg(errp, "Bitmap '%s' could not be found", bitmap);
3260 bdrv_unref(target_bs);
3261 goto out;
3265 backup_start(job_id, bs, target_bs, speed, sync, bmap,
3266 on_source_error, on_target_error,
3267 block_job_cb, bs, txn, &local_err);
3268 bdrv_unref(target_bs);
3269 if (local_err != NULL) {
3270 error_propagate(errp, local_err);
3271 goto out;
3274 out:
3275 aio_context_release(aio_context);
3278 void qmp_drive_backup(bool has_job_id, const char *job_id,
3279 const char *device, const char *target,
3280 bool has_format, const char *format,
3281 enum MirrorSyncMode sync,
3282 bool has_mode, enum NewImageMode mode,
3283 bool has_speed, int64_t speed,
3284 bool has_bitmap, const char *bitmap,
3285 bool has_on_source_error, BlockdevOnError on_source_error,
3286 bool has_on_target_error, BlockdevOnError on_target_error,
3287 Error **errp)
3289 return do_drive_backup(has_job_id ? job_id : NULL, device, target,
3290 has_format, format, sync,
3291 has_mode, mode, has_speed, speed,
3292 has_bitmap, bitmap,
3293 has_on_source_error, on_source_error,
3294 has_on_target_error, on_target_error,
3295 NULL, errp);
3298 BlockDeviceInfoList *qmp_query_named_block_nodes(Error **errp)
3300 return bdrv_named_nodes_list(errp);
3303 void do_blockdev_backup(const char *job_id, const char *device,
3304 const char *target, enum MirrorSyncMode sync,
3305 bool has_speed, int64_t speed,
3306 bool has_on_source_error,
3307 BlockdevOnError on_source_error,
3308 bool has_on_target_error,
3309 BlockdevOnError on_target_error,
3310 BlockJobTxn *txn, Error **errp)
3312 BlockDriverState *bs;
3313 BlockDriverState *target_bs;
3314 Error *local_err = NULL;
3315 AioContext *aio_context;
3317 if (!has_speed) {
3318 speed = 0;
3320 if (!has_on_source_error) {
3321 on_source_error = BLOCKDEV_ON_ERROR_REPORT;
3323 if (!has_on_target_error) {
3324 on_target_error = BLOCKDEV_ON_ERROR_REPORT;
3327 bs = qmp_get_root_bs(device, errp);
3328 if (!bs) {
3329 return;
3332 aio_context = bdrv_get_aio_context(bs);
3333 aio_context_acquire(aio_context);
3335 target_bs = bdrv_lookup_bs(target, target, errp);
3336 if (!target_bs) {
3337 goto out;
3340 if (bdrv_get_aio_context(target_bs) != aio_context) {
3341 if (!bdrv_has_blk(target_bs)) {
3342 /* The target BDS is not attached, we can safely move it to another
3343 * AioContext. */
3344 bdrv_set_aio_context(target_bs, aio_context);
3345 } else {
3346 error_setg(errp, "Target is attached to a different thread from "
3347 "source.");
3348 goto out;
3351 backup_start(job_id, bs, target_bs, speed, sync, NULL, on_source_error,
3352 on_target_error, block_job_cb, bs, txn, &local_err);
3353 if (local_err != NULL) {
3354 error_propagate(errp, local_err);
3356 out:
3357 aio_context_release(aio_context);
3360 void qmp_blockdev_backup(bool has_job_id, const char *job_id,
3361 const char *device, const char *target,
3362 enum MirrorSyncMode sync,
3363 bool has_speed, int64_t speed,
3364 bool has_on_source_error,
3365 BlockdevOnError on_source_error,
3366 bool has_on_target_error,
3367 BlockdevOnError on_target_error,
3368 Error **errp)
3370 do_blockdev_backup(has_job_id ? job_id : NULL, device, target,
3371 sync, has_speed, speed,
3372 has_on_source_error, on_source_error,
3373 has_on_target_error, on_target_error,
3374 NULL, errp);
3377 /* Parameter check and block job starting for drive mirroring.
3378 * Caller should hold @device and @target's aio context (must be the same).
3380 static void blockdev_mirror_common(const char *job_id, BlockDriverState *bs,
3381 BlockDriverState *target,
3382 bool has_replaces, const char *replaces,
3383 enum MirrorSyncMode sync,
3384 BlockMirrorBackingMode backing_mode,
3385 bool has_speed, int64_t speed,
3386 bool has_granularity, uint32_t granularity,
3387 bool has_buf_size, int64_t buf_size,
3388 bool has_on_source_error,
3389 BlockdevOnError on_source_error,
3390 bool has_on_target_error,
3391 BlockdevOnError on_target_error,
3392 bool has_unmap, bool unmap,
3393 Error **errp)
3396 if (!has_speed) {
3397 speed = 0;
3399 if (!has_on_source_error) {
3400 on_source_error = BLOCKDEV_ON_ERROR_REPORT;
3402 if (!has_on_target_error) {
3403 on_target_error = BLOCKDEV_ON_ERROR_REPORT;
3405 if (!has_granularity) {
3406 granularity = 0;
3408 if (!has_buf_size) {
3409 buf_size = 0;
3411 if (!has_unmap) {
3412 unmap = true;
3415 if (granularity != 0 && (granularity < 512 || granularity > 1048576 * 64)) {
3416 error_setg(errp, QERR_INVALID_PARAMETER_VALUE, "granularity",
3417 "a value in range [512B, 64MB]");
3418 return;
3420 if (granularity & (granularity - 1)) {
3421 error_setg(errp, QERR_INVALID_PARAMETER_VALUE, "granularity",
3422 "power of 2");
3423 return;
3426 if (bdrv_op_is_blocked(bs, BLOCK_OP_TYPE_MIRROR_SOURCE, errp)) {
3427 return;
3429 if (bdrv_op_is_blocked(target, BLOCK_OP_TYPE_MIRROR_TARGET, errp)) {
3430 return;
3433 if (!bs->backing && sync == MIRROR_SYNC_MODE_TOP) {
3434 sync = MIRROR_SYNC_MODE_FULL;
3437 /* pass the node name to replace to mirror start since it's loose coupling
3438 * and will allow to check whether the node still exist at mirror completion
3440 mirror_start(job_id, bs, target,
3441 has_replaces ? replaces : NULL,
3442 speed, granularity, buf_size, sync, backing_mode,
3443 on_source_error, on_target_error, unmap,
3444 block_job_cb, bs, errp);
3447 void qmp_drive_mirror(DriveMirror *arg, Error **errp)
3449 BlockDriverState *bs;
3450 BlockBackend *blk;
3451 BlockDriverState *source, *target_bs;
3452 AioContext *aio_context;
3453 BlockMirrorBackingMode backing_mode;
3454 Error *local_err = NULL;
3455 QDict *options = NULL;
3456 int flags;
3457 int64_t size;
3458 const char *format = arg->format;
3460 blk = blk_by_name(arg->device);
3461 if (!blk) {
3462 error_set(errp, ERROR_CLASS_DEVICE_NOT_FOUND,
3463 "Device '%s' not found", arg->device);
3464 return;
3467 aio_context = blk_get_aio_context(blk);
3468 aio_context_acquire(aio_context);
3470 if (!blk_is_available(blk)) {
3471 error_setg(errp, QERR_DEVICE_HAS_NO_MEDIUM, arg->device);
3472 goto out;
3474 bs = blk_bs(blk);
3475 if (!arg->has_mode) {
3476 arg->mode = NEW_IMAGE_MODE_ABSOLUTE_PATHS;
3479 if (!arg->has_format) {
3480 format = (arg->mode == NEW_IMAGE_MODE_EXISTING
3481 ? NULL : bs->drv->format_name);
3484 flags = bs->open_flags | BDRV_O_RDWR;
3485 source = backing_bs(bs);
3486 if (!source && arg->sync == MIRROR_SYNC_MODE_TOP) {
3487 arg->sync = MIRROR_SYNC_MODE_FULL;
3489 if (arg->sync == MIRROR_SYNC_MODE_NONE) {
3490 source = bs;
3493 size = bdrv_getlength(bs);
3494 if (size < 0) {
3495 error_setg_errno(errp, -size, "bdrv_getlength failed");
3496 goto out;
3499 if (arg->has_replaces) {
3500 BlockDriverState *to_replace_bs;
3501 AioContext *replace_aio_context;
3502 int64_t replace_size;
3504 if (!arg->has_node_name) {
3505 error_setg(errp, "a node-name must be provided when replacing a"
3506 " named node of the graph");
3507 goto out;
3510 to_replace_bs = check_to_replace_node(bs, arg->replaces, &local_err);
3512 if (!to_replace_bs) {
3513 error_propagate(errp, local_err);
3514 goto out;
3517 replace_aio_context = bdrv_get_aio_context(to_replace_bs);
3518 aio_context_acquire(replace_aio_context);
3519 replace_size = bdrv_getlength(to_replace_bs);
3520 aio_context_release(replace_aio_context);
3522 if (size != replace_size) {
3523 error_setg(errp, "cannot replace image with a mirror image of "
3524 "different size");
3525 goto out;
3529 if (arg->mode == NEW_IMAGE_MODE_ABSOLUTE_PATHS) {
3530 backing_mode = MIRROR_SOURCE_BACKING_CHAIN;
3531 } else {
3532 backing_mode = MIRROR_OPEN_BACKING_CHAIN;
3535 if ((arg->sync == MIRROR_SYNC_MODE_FULL || !source)
3536 && arg->mode != NEW_IMAGE_MODE_EXISTING)
3538 /* create new image w/o backing file */
3539 assert(format);
3540 bdrv_img_create(arg->target, format,
3541 NULL, NULL, NULL, size, flags, &local_err, false);
3542 } else {
3543 switch (arg->mode) {
3544 case NEW_IMAGE_MODE_EXISTING:
3545 break;
3546 case NEW_IMAGE_MODE_ABSOLUTE_PATHS:
3547 /* create new image with backing file */
3548 bdrv_img_create(arg->target, format,
3549 source->filename,
3550 source->drv->format_name,
3551 NULL, size, flags, &local_err, false);
3552 break;
3553 default:
3554 abort();
3558 if (local_err) {
3559 error_propagate(errp, local_err);
3560 goto out;
3563 options = qdict_new();
3564 if (arg->has_node_name) {
3565 qdict_put(options, "node-name", qstring_from_str(arg->node_name));
3567 if (format) {
3568 qdict_put(options, "driver", qstring_from_str(format));
3571 /* Mirroring takes care of copy-on-write using the source's backing
3572 * file.
3574 target_bs = bdrv_open(arg->target, NULL, options,
3575 flags | BDRV_O_NO_BACKING, errp);
3576 if (!target_bs) {
3577 goto out;
3580 bdrv_set_aio_context(target_bs, aio_context);
3582 blockdev_mirror_common(arg->has_job_id ? arg->job_id : NULL, bs, target_bs,
3583 arg->has_replaces, arg->replaces, arg->sync,
3584 backing_mode, arg->has_speed, arg->speed,
3585 arg->has_granularity, arg->granularity,
3586 arg->has_buf_size, arg->buf_size,
3587 arg->has_on_source_error, arg->on_source_error,
3588 arg->has_on_target_error, arg->on_target_error,
3589 arg->has_unmap, arg->unmap,
3590 &local_err);
3591 bdrv_unref(target_bs);
3592 error_propagate(errp, local_err);
3593 out:
3594 aio_context_release(aio_context);
3597 void qmp_blockdev_mirror(bool has_job_id, const char *job_id,
3598 const char *device, const char *target,
3599 bool has_replaces, const char *replaces,
3600 MirrorSyncMode sync,
3601 bool has_speed, int64_t speed,
3602 bool has_granularity, uint32_t granularity,
3603 bool has_buf_size, int64_t buf_size,
3604 bool has_on_source_error,
3605 BlockdevOnError on_source_error,
3606 bool has_on_target_error,
3607 BlockdevOnError on_target_error,
3608 Error **errp)
3610 BlockDriverState *bs;
3611 BlockDriverState *target_bs;
3612 AioContext *aio_context;
3613 BlockMirrorBackingMode backing_mode = MIRROR_LEAVE_BACKING_CHAIN;
3614 Error *local_err = NULL;
3616 bs = qmp_get_root_bs(device, errp);
3617 if (!bs) {
3618 return;
3621 target_bs = bdrv_lookup_bs(target, target, errp);
3622 if (!target_bs) {
3623 return;
3626 aio_context = bdrv_get_aio_context(bs);
3627 aio_context_acquire(aio_context);
3629 bdrv_set_aio_context(target_bs, aio_context);
3631 blockdev_mirror_common(has_job_id ? job_id : NULL, bs, target_bs,
3632 has_replaces, replaces, sync, backing_mode,
3633 has_speed, speed,
3634 has_granularity, granularity,
3635 has_buf_size, buf_size,
3636 has_on_source_error, on_source_error,
3637 has_on_target_error, on_target_error,
3638 true, true,
3639 &local_err);
3640 error_propagate(errp, local_err);
3642 aio_context_release(aio_context);
3645 /* Get a block job using its ID and acquire its AioContext */
3646 static BlockJob *find_block_job(const char *id, AioContext **aio_context,
3647 Error **errp)
3649 BlockJob *job;
3651 assert(id != NULL);
3653 *aio_context = NULL;
3655 job = block_job_get(id);
3657 if (!job) {
3658 error_set(errp, ERROR_CLASS_DEVICE_NOT_ACTIVE,
3659 "Block job '%s' not found", id);
3660 return NULL;
3663 *aio_context = blk_get_aio_context(job->blk);
3664 aio_context_acquire(*aio_context);
3666 return job;
3669 void qmp_block_job_set_speed(const char *device, int64_t speed, Error **errp)
3671 AioContext *aio_context;
3672 BlockJob *job = find_block_job(device, &aio_context, errp);
3674 if (!job) {
3675 return;
3678 block_job_set_speed(job, speed, errp);
3679 aio_context_release(aio_context);
3682 void qmp_block_job_cancel(const char *device,
3683 bool has_force, bool force, Error **errp)
3685 AioContext *aio_context;
3686 BlockJob *job = find_block_job(device, &aio_context, errp);
3688 if (!job) {
3689 return;
3692 if (!has_force) {
3693 force = false;
3696 if (job->user_paused && !force) {
3697 error_setg(errp, "The block job for device '%s' is currently paused",
3698 device);
3699 goto out;
3702 trace_qmp_block_job_cancel(job);
3703 block_job_cancel(job);
3704 out:
3705 aio_context_release(aio_context);
3708 void qmp_block_job_pause(const char *device, Error **errp)
3710 AioContext *aio_context;
3711 BlockJob *job = find_block_job(device, &aio_context, errp);
3713 if (!job || job->user_paused) {
3714 return;
3717 job->user_paused = true;
3718 trace_qmp_block_job_pause(job);
3719 block_job_pause(job);
3720 aio_context_release(aio_context);
3723 void qmp_block_job_resume(const char *device, Error **errp)
3725 AioContext *aio_context;
3726 BlockJob *job = find_block_job(device, &aio_context, errp);
3728 if (!job || !job->user_paused) {
3729 return;
3732 job->user_paused = false;
3733 trace_qmp_block_job_resume(job);
3734 block_job_iostatus_reset(job);
3735 block_job_resume(job);
3736 aio_context_release(aio_context);
3739 void qmp_block_job_complete(const char *device, Error **errp)
3741 AioContext *aio_context;
3742 BlockJob *job = find_block_job(device, &aio_context, errp);
3744 if (!job) {
3745 return;
3748 trace_qmp_block_job_complete(job);
3749 block_job_complete(job, errp);
3750 aio_context_release(aio_context);
3753 void qmp_change_backing_file(const char *device,
3754 const char *image_node_name,
3755 const char *backing_file,
3756 Error **errp)
3758 BlockBackend *blk;
3759 BlockDriverState *bs = NULL;
3760 AioContext *aio_context;
3761 BlockDriverState *image_bs = NULL;
3762 Error *local_err = NULL;
3763 bool ro;
3764 int open_flags;
3765 int ret;
3767 blk = blk_by_name(device);
3768 if (!blk) {
3769 error_set(errp, ERROR_CLASS_DEVICE_NOT_FOUND,
3770 "Device '%s' not found", device);
3771 return;
3774 aio_context = blk_get_aio_context(blk);
3775 aio_context_acquire(aio_context);
3777 if (!blk_is_available(blk)) {
3778 error_setg(errp, "Device '%s' has no medium", device);
3779 goto out;
3781 bs = blk_bs(blk);
3783 image_bs = bdrv_lookup_bs(NULL, image_node_name, &local_err);
3784 if (local_err) {
3785 error_propagate(errp, local_err);
3786 goto out;
3789 if (!image_bs) {
3790 error_setg(errp, "image file not found");
3791 goto out;
3794 if (bdrv_find_base(image_bs) == image_bs) {
3795 error_setg(errp, "not allowing backing file change on an image "
3796 "without a backing file");
3797 goto out;
3800 /* even though we are not necessarily operating on bs, we need it to
3801 * determine if block ops are currently prohibited on the chain */
3802 if (bdrv_op_is_blocked(bs, BLOCK_OP_TYPE_CHANGE, errp)) {
3803 goto out;
3806 /* final sanity check */
3807 if (!bdrv_chain_contains(bs, image_bs)) {
3808 error_setg(errp, "'%s' and image file are not in the same chain",
3809 device);
3810 goto out;
3813 /* if not r/w, reopen to make r/w */
3814 open_flags = image_bs->open_flags;
3815 ro = bdrv_is_read_only(image_bs);
3817 if (ro) {
3818 bdrv_reopen(image_bs, open_flags | BDRV_O_RDWR, &local_err);
3819 if (local_err) {
3820 error_propagate(errp, local_err);
3821 goto out;
3825 ret = bdrv_change_backing_file(image_bs, backing_file,
3826 image_bs->drv ? image_bs->drv->format_name : "");
3828 if (ret < 0) {
3829 error_setg_errno(errp, -ret, "Could not change backing file to '%s'",
3830 backing_file);
3831 /* don't exit here, so we can try to restore open flags if
3832 * appropriate */
3835 if (ro) {
3836 bdrv_reopen(image_bs, open_flags, &local_err);
3837 error_propagate(errp, local_err);
3840 out:
3841 aio_context_release(aio_context);
3844 void hmp_drive_add_node(Monitor *mon, const char *optstr)
3846 QemuOpts *opts;
3847 QDict *qdict;
3848 Error *local_err = NULL;
3850 opts = qemu_opts_parse_noisily(&qemu_drive_opts, optstr, false);
3851 if (!opts) {
3852 return;
3855 qdict = qemu_opts_to_qdict(opts, NULL);
3857 if (!qdict_get_try_str(qdict, "node-name")) {
3858 QDECREF(qdict);
3859 error_report("'node-name' needs to be specified");
3860 goto out;
3863 BlockDriverState *bs = bds_tree_init(qdict, &local_err);
3864 if (!bs) {
3865 error_report_err(local_err);
3866 goto out;
3869 QTAILQ_INSERT_TAIL(&monitor_bdrv_states, bs, monitor_list);
3871 out:
3872 qemu_opts_del(opts);
3875 void qmp_blockdev_add(BlockdevOptions *options, Error **errp)
3877 BlockDriverState *bs;
3878 BlockBackend *blk = NULL;
3879 QObject *obj;
3880 Visitor *v = qmp_output_visitor_new(&obj);
3881 QDict *qdict;
3882 Error *local_err = NULL;
3884 /* TODO Sort it out in raw-posix and drive_new(): Reject aio=native with
3885 * cache.direct=false instead of silently switching to aio=threads, except
3886 * when called from drive_new().
3888 * For now, simply forbidding the combination for all drivers will do. */
3889 if (options->has_aio && options->aio == BLOCKDEV_AIO_OPTIONS_NATIVE) {
3890 bool direct = options->has_cache &&
3891 options->cache->has_direct &&
3892 options->cache->direct;
3893 if (!direct) {
3894 error_setg(errp, "aio=native requires cache.direct=true");
3895 goto fail;
3899 visit_type_BlockdevOptions(v, NULL, &options, &local_err);
3900 if (local_err) {
3901 error_propagate(errp, local_err);
3902 goto fail;
3905 visit_complete(v, &obj);
3906 qdict = qobject_to_qdict(obj);
3908 qdict_flatten(qdict);
3910 if (options->has_id) {
3911 blk = blockdev_init(NULL, qdict, &local_err);
3912 if (local_err) {
3913 error_propagate(errp, local_err);
3914 goto fail;
3917 bs = blk_bs(blk);
3918 } else {
3919 if (!qdict_get_try_str(qdict, "node-name")) {
3920 error_setg(errp, "'id' and/or 'node-name' need to be specified for "
3921 "the root node");
3922 goto fail;
3925 bs = bds_tree_init(qdict, errp);
3926 if (!bs) {
3927 goto fail;
3930 QTAILQ_INSERT_TAIL(&monitor_bdrv_states, bs, monitor_list);
3933 if (bs && bdrv_key_required(bs)) {
3934 if (blk) {
3935 monitor_remove_blk(blk);
3936 blk_unref(blk);
3937 } else {
3938 QTAILQ_REMOVE(&monitor_bdrv_states, bs, monitor_list);
3939 bdrv_unref(bs);
3941 error_setg(errp, "blockdev-add doesn't support encrypted devices");
3942 goto fail;
3945 fail:
3946 visit_free(v);
3949 void qmp_x_blockdev_del(bool has_id, const char *id,
3950 bool has_node_name, const char *node_name, Error **errp)
3952 AioContext *aio_context;
3953 BlockBackend *blk;
3954 BlockDriverState *bs;
3956 if (has_id && has_node_name) {
3957 error_setg(errp, "Only one of id and node-name must be specified");
3958 return;
3959 } else if (!has_id && !has_node_name) {
3960 error_setg(errp, "No block device specified");
3961 return;
3964 if (has_id) {
3965 /* blk_by_name() never returns a BB that is not owned by the monitor */
3966 blk = blk_by_name(id);
3967 if (!blk) {
3968 error_setg(errp, "Cannot find block backend %s", id);
3969 return;
3971 if (blk_legacy_dinfo(blk)) {
3972 error_setg(errp, "Deleting block backend added with drive-add"
3973 " is not supported");
3974 return;
3976 if (blk_get_refcnt(blk) > 1) {
3977 error_setg(errp, "Block backend %s is in use", id);
3978 return;
3980 bs = blk_bs(blk);
3981 aio_context = blk_get_aio_context(blk);
3982 } else {
3983 blk = NULL;
3984 bs = bdrv_find_node(node_name);
3985 if (!bs) {
3986 error_setg(errp, "Cannot find node %s", node_name);
3987 return;
3989 if (bdrv_has_blk(bs)) {
3990 error_setg(errp, "Node %s is in use by %s",
3991 node_name, bdrv_get_parent_name(bs));
3992 return;
3994 aio_context = bdrv_get_aio_context(bs);
3997 aio_context_acquire(aio_context);
3999 if (bs) {
4000 if (bdrv_op_is_blocked(bs, BLOCK_OP_TYPE_DRIVE_DEL, errp)) {
4001 goto out;
4004 if (!blk && !bs->monitor_list.tqe_prev) {
4005 error_setg(errp, "Node %s is not owned by the monitor",
4006 bs->node_name);
4007 goto out;
4010 if (bs->refcnt > 1) {
4011 error_setg(errp, "Block device %s is in use",
4012 bdrv_get_device_or_node_name(bs));
4013 goto out;
4017 if (blk) {
4018 monitor_remove_blk(blk);
4019 blk_unref(blk);
4020 } else {
4021 QTAILQ_REMOVE(&monitor_bdrv_states, bs, monitor_list);
4022 bdrv_unref(bs);
4025 out:
4026 aio_context_release(aio_context);
4029 static BdrvChild *bdrv_find_child(BlockDriverState *parent_bs,
4030 const char *child_name)
4032 BdrvChild *child;
4034 QLIST_FOREACH(child, &parent_bs->children, next) {
4035 if (strcmp(child->name, child_name) == 0) {
4036 return child;
4040 return NULL;
4043 void qmp_x_blockdev_change(const char *parent, bool has_child,
4044 const char *child, bool has_node,
4045 const char *node, Error **errp)
4047 BlockDriverState *parent_bs, *new_bs = NULL;
4048 BdrvChild *p_child;
4050 parent_bs = bdrv_lookup_bs(parent, parent, errp);
4051 if (!parent_bs) {
4052 return;
4055 if (has_child == has_node) {
4056 if (has_child) {
4057 error_setg(errp, "The parameters child and node are in conflict");
4058 } else {
4059 error_setg(errp, "Either child or node must be specified");
4061 return;
4064 if (has_child) {
4065 p_child = bdrv_find_child(parent_bs, child);
4066 if (!p_child) {
4067 error_setg(errp, "Node '%s' does not have child '%s'",
4068 parent, child);
4069 return;
4071 bdrv_del_child(parent_bs, p_child, errp);
4074 if (has_node) {
4075 new_bs = bdrv_find_node(node);
4076 if (!new_bs) {
4077 error_setg(errp, "Node '%s' not found", node);
4078 return;
4080 bdrv_add_child(parent_bs, new_bs, errp);
4084 BlockJobInfoList *qmp_query_block_jobs(Error **errp)
4086 BlockJobInfoList *head = NULL, **p_next = &head;
4087 BlockJob *job;
4089 for (job = block_job_next(NULL); job; job = block_job_next(job)) {
4090 BlockJobInfoList *elem = g_new0(BlockJobInfoList, 1);
4091 AioContext *aio_context = blk_get_aio_context(job->blk);
4093 aio_context_acquire(aio_context);
4094 elem->value = block_job_query(job);
4095 aio_context_release(aio_context);
4097 *p_next = elem;
4098 p_next = &elem->next;
4101 return head;
4104 QemuOptsList qemu_common_drive_opts = {
4105 .name = "drive",
4106 .head = QTAILQ_HEAD_INITIALIZER(qemu_common_drive_opts.head),
4107 .desc = {
4109 .name = "snapshot",
4110 .type = QEMU_OPT_BOOL,
4111 .help = "enable/disable snapshot mode",
4113 .name = "discard",
4114 .type = QEMU_OPT_STRING,
4115 .help = "discard operation (ignore/off, unmap/on)",
4117 .name = "aio",
4118 .type = QEMU_OPT_STRING,
4119 .help = "host AIO implementation (threads, native)",
4121 .name = BDRV_OPT_CACHE_WB,
4122 .type = QEMU_OPT_BOOL,
4123 .help = "Enable writeback mode",
4125 .name = "format",
4126 .type = QEMU_OPT_STRING,
4127 .help = "disk format (raw, qcow2, ...)",
4129 .name = "rerror",
4130 .type = QEMU_OPT_STRING,
4131 .help = "read error action",
4133 .name = "werror",
4134 .type = QEMU_OPT_STRING,
4135 .help = "write error action",
4137 .name = "read-only",
4138 .type = QEMU_OPT_BOOL,
4139 .help = "open drive file as read-only",
4141 .name = "throttling.iops-total",
4142 .type = QEMU_OPT_NUMBER,
4143 .help = "limit total I/O operations per second",
4145 .name = "throttling.iops-read",
4146 .type = QEMU_OPT_NUMBER,
4147 .help = "limit read operations per second",
4149 .name = "throttling.iops-write",
4150 .type = QEMU_OPT_NUMBER,
4151 .help = "limit write operations per second",
4153 .name = "throttling.bps-total",
4154 .type = QEMU_OPT_NUMBER,
4155 .help = "limit total bytes per second",
4157 .name = "throttling.bps-read",
4158 .type = QEMU_OPT_NUMBER,
4159 .help = "limit read bytes per second",
4161 .name = "throttling.bps-write",
4162 .type = QEMU_OPT_NUMBER,
4163 .help = "limit write bytes per second",
4165 .name = "throttling.iops-total-max",
4166 .type = QEMU_OPT_NUMBER,
4167 .help = "I/O operations burst",
4169 .name = "throttling.iops-read-max",
4170 .type = QEMU_OPT_NUMBER,
4171 .help = "I/O operations read burst",
4173 .name = "throttling.iops-write-max",
4174 .type = QEMU_OPT_NUMBER,
4175 .help = "I/O operations write burst",
4177 .name = "throttling.bps-total-max",
4178 .type = QEMU_OPT_NUMBER,
4179 .help = "total bytes burst",
4181 .name = "throttling.bps-read-max",
4182 .type = QEMU_OPT_NUMBER,
4183 .help = "total bytes read burst",
4185 .name = "throttling.bps-write-max",
4186 .type = QEMU_OPT_NUMBER,
4187 .help = "total bytes write burst",
4189 .name = "throttling.iops-total-max-length",
4190 .type = QEMU_OPT_NUMBER,
4191 .help = "length of the iops-total-max burst period, in seconds",
4193 .name = "throttling.iops-read-max-length",
4194 .type = QEMU_OPT_NUMBER,
4195 .help = "length of the iops-read-max burst period, in seconds",
4197 .name = "throttling.iops-write-max-length",
4198 .type = QEMU_OPT_NUMBER,
4199 .help = "length of the iops-write-max burst period, in seconds",
4201 .name = "throttling.bps-total-max-length",
4202 .type = QEMU_OPT_NUMBER,
4203 .help = "length of the bps-total-max burst period, in seconds",
4205 .name = "throttling.bps-read-max-length",
4206 .type = QEMU_OPT_NUMBER,
4207 .help = "length of the bps-read-max burst period, in seconds",
4209 .name = "throttling.bps-write-max-length",
4210 .type = QEMU_OPT_NUMBER,
4211 .help = "length of the bps-write-max burst period, in seconds",
4213 .name = "throttling.iops-size",
4214 .type = QEMU_OPT_NUMBER,
4215 .help = "when limiting by iops max size of an I/O in bytes",
4217 .name = "throttling.group",
4218 .type = QEMU_OPT_STRING,
4219 .help = "name of the block throttling group",
4221 .name = "copy-on-read",
4222 .type = QEMU_OPT_BOOL,
4223 .help = "copy read data from backing file into image file",
4225 .name = "detect-zeroes",
4226 .type = QEMU_OPT_STRING,
4227 .help = "try to optimize zero writes (off, on, unmap)",
4229 .name = "stats-account-invalid",
4230 .type = QEMU_OPT_BOOL,
4231 .help = "whether to account for invalid I/O operations "
4232 "in the statistics",
4234 .name = "stats-account-failed",
4235 .type = QEMU_OPT_BOOL,
4236 .help = "whether to account for failed I/O operations "
4237 "in the statistics",
4239 { /* end of list */ }
4243 static QemuOptsList qemu_root_bds_opts = {
4244 .name = "root-bds",
4245 .head = QTAILQ_HEAD_INITIALIZER(qemu_root_bds_opts.head),
4246 .desc = {
4248 .name = "discard",
4249 .type = QEMU_OPT_STRING,
4250 .help = "discard operation (ignore/off, unmap/on)",
4252 .name = "aio",
4253 .type = QEMU_OPT_STRING,
4254 .help = "host AIO implementation (threads, native)",
4256 .name = "read-only",
4257 .type = QEMU_OPT_BOOL,
4258 .help = "open drive file as read-only",
4260 .name = "copy-on-read",
4261 .type = QEMU_OPT_BOOL,
4262 .help = "copy read data from backing file into image file",
4264 .name = "detect-zeroes",
4265 .type = QEMU_OPT_STRING,
4266 .help = "try to optimize zero writes (off, on, unmap)",
4268 { /* end of list */ }
4272 QemuOptsList qemu_drive_opts = {
4273 .name = "drive",
4274 .head = QTAILQ_HEAD_INITIALIZER(qemu_drive_opts.head),
4275 .desc = {
4277 * no elements => accept any params
4278 * validation will happen later
4280 { /* end of list */ }