block: fix deadlock in bdrv_co_flush
[qemu/kevin.git] / blockdev.c
blob21614004d1744200f42e727789b748a50c51ee2c
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 void hmp_commit(Monitor *mon, const QDict *qdict)
1179 const char *device = qdict_get_str(qdict, "device");
1180 BlockBackend *blk;
1181 int ret;
1183 if (!strcmp(device, "all")) {
1184 ret = blk_commit_all();
1185 } else {
1186 BlockDriverState *bs;
1187 AioContext *aio_context;
1189 blk = blk_by_name(device);
1190 if (!blk) {
1191 monitor_printf(mon, "Device '%s' not found\n", device);
1192 return;
1194 if (!blk_is_available(blk)) {
1195 monitor_printf(mon, "Device '%s' has no medium\n", device);
1196 return;
1199 bs = blk_bs(blk);
1200 aio_context = bdrv_get_aio_context(bs);
1201 aio_context_acquire(aio_context);
1203 ret = bdrv_commit(bs);
1205 aio_context_release(aio_context);
1207 if (ret < 0) {
1208 monitor_printf(mon, "'commit' error for '%s': %s\n", device,
1209 strerror(-ret));
1213 static void blockdev_do_action(TransactionAction *action, Error **errp)
1215 TransactionActionList list;
1217 list.value = action;
1218 list.next = NULL;
1219 qmp_transaction(&list, false, NULL, errp);
1222 void qmp_blockdev_snapshot_sync(bool has_device, const char *device,
1223 bool has_node_name, const char *node_name,
1224 const char *snapshot_file,
1225 bool has_snapshot_node_name,
1226 const char *snapshot_node_name,
1227 bool has_format, const char *format,
1228 bool has_mode, NewImageMode mode, Error **errp)
1230 BlockdevSnapshotSync snapshot = {
1231 .has_device = has_device,
1232 .device = (char *) device,
1233 .has_node_name = has_node_name,
1234 .node_name = (char *) node_name,
1235 .snapshot_file = (char *) snapshot_file,
1236 .has_snapshot_node_name = has_snapshot_node_name,
1237 .snapshot_node_name = (char *) snapshot_node_name,
1238 .has_format = has_format,
1239 .format = (char *) format,
1240 .has_mode = has_mode,
1241 .mode = mode,
1243 TransactionAction action = {
1244 .type = TRANSACTION_ACTION_KIND_BLOCKDEV_SNAPSHOT_SYNC,
1245 .u.blockdev_snapshot_sync.data = &snapshot,
1247 blockdev_do_action(&action, errp);
1250 void qmp_blockdev_snapshot(const char *node, const char *overlay,
1251 Error **errp)
1253 BlockdevSnapshot snapshot_data = {
1254 .node = (char *) node,
1255 .overlay = (char *) overlay
1257 TransactionAction action = {
1258 .type = TRANSACTION_ACTION_KIND_BLOCKDEV_SNAPSHOT,
1259 .u.blockdev_snapshot.data = &snapshot_data,
1261 blockdev_do_action(&action, errp);
1264 void qmp_blockdev_snapshot_internal_sync(const char *device,
1265 const char *name,
1266 Error **errp)
1268 BlockdevSnapshotInternal snapshot = {
1269 .device = (char *) device,
1270 .name = (char *) name
1272 TransactionAction action = {
1273 .type = TRANSACTION_ACTION_KIND_BLOCKDEV_SNAPSHOT_INTERNAL_SYNC,
1274 .u.blockdev_snapshot_internal_sync.data = &snapshot,
1276 blockdev_do_action(&action, errp);
1279 SnapshotInfo *qmp_blockdev_snapshot_delete_internal_sync(const char *device,
1280 bool has_id,
1281 const char *id,
1282 bool has_name,
1283 const char *name,
1284 Error **errp)
1286 BlockDriverState *bs;
1287 BlockBackend *blk;
1288 AioContext *aio_context;
1289 QEMUSnapshotInfo sn;
1290 Error *local_err = NULL;
1291 SnapshotInfo *info = NULL;
1292 int ret;
1294 blk = blk_by_name(device);
1295 if (!blk) {
1296 error_set(errp, ERROR_CLASS_DEVICE_NOT_FOUND,
1297 "Device '%s' not found", device);
1298 return NULL;
1301 aio_context = blk_get_aio_context(blk);
1302 aio_context_acquire(aio_context);
1304 if (!has_id) {
1305 id = NULL;
1308 if (!has_name) {
1309 name = NULL;
1312 if (!id && !name) {
1313 error_setg(errp, "Name or id must be provided");
1314 goto out_aio_context;
1317 if (!blk_is_available(blk)) {
1318 error_setg(errp, "Device '%s' has no medium", device);
1319 goto out_aio_context;
1321 bs = blk_bs(blk);
1323 if (bdrv_op_is_blocked(bs, BLOCK_OP_TYPE_INTERNAL_SNAPSHOT_DELETE, errp)) {
1324 goto out_aio_context;
1327 ret = bdrv_snapshot_find_by_id_and_name(bs, id, name, &sn, &local_err);
1328 if (local_err) {
1329 error_propagate(errp, local_err);
1330 goto out_aio_context;
1332 if (!ret) {
1333 error_setg(errp,
1334 "Snapshot with id '%s' and name '%s' does not exist on "
1335 "device '%s'",
1336 STR_OR_NULL(id), STR_OR_NULL(name), device);
1337 goto out_aio_context;
1340 bdrv_snapshot_delete(bs, id, name, &local_err);
1341 if (local_err) {
1342 error_propagate(errp, local_err);
1343 goto out_aio_context;
1346 aio_context_release(aio_context);
1348 info = g_new0(SnapshotInfo, 1);
1349 info->id = g_strdup(sn.id_str);
1350 info->name = g_strdup(sn.name);
1351 info->date_nsec = sn.date_nsec;
1352 info->date_sec = sn.date_sec;
1353 info->vm_state_size = sn.vm_state_size;
1354 info->vm_clock_nsec = sn.vm_clock_nsec % 1000000000;
1355 info->vm_clock_sec = sn.vm_clock_nsec / 1000000000;
1357 return info;
1359 out_aio_context:
1360 aio_context_release(aio_context);
1361 return NULL;
1365 * block_dirty_bitmap_lookup:
1366 * Return a dirty bitmap (if present), after validating
1367 * the node reference and bitmap names.
1369 * @node: The name of the BDS node to search for bitmaps
1370 * @name: The name of the bitmap to search for
1371 * @pbs: Output pointer for BDS lookup, if desired. Can be NULL.
1372 * @paio: Output pointer for aio_context acquisition, if desired. Can be NULL.
1373 * @errp: Output pointer for error information. Can be NULL.
1375 * @return: A bitmap object on success, or NULL on failure.
1377 static BdrvDirtyBitmap *block_dirty_bitmap_lookup(const char *node,
1378 const char *name,
1379 BlockDriverState **pbs,
1380 AioContext **paio,
1381 Error **errp)
1383 BlockDriverState *bs;
1384 BdrvDirtyBitmap *bitmap;
1385 AioContext *aio_context;
1387 if (!node) {
1388 error_setg(errp, "Node cannot be NULL");
1389 return NULL;
1391 if (!name) {
1392 error_setg(errp, "Bitmap name cannot be NULL");
1393 return NULL;
1395 bs = bdrv_lookup_bs(node, node, NULL);
1396 if (!bs) {
1397 error_setg(errp, "Node '%s' not found", node);
1398 return NULL;
1401 aio_context = bdrv_get_aio_context(bs);
1402 aio_context_acquire(aio_context);
1404 bitmap = bdrv_find_dirty_bitmap(bs, name);
1405 if (!bitmap) {
1406 error_setg(errp, "Dirty bitmap '%s' not found", name);
1407 goto fail;
1410 if (pbs) {
1411 *pbs = bs;
1413 if (paio) {
1414 *paio = aio_context;
1415 } else {
1416 aio_context_release(aio_context);
1419 return bitmap;
1421 fail:
1422 aio_context_release(aio_context);
1423 return NULL;
1426 /* New and old BlockDriverState structs for atomic group operations */
1428 typedef struct BlkActionState BlkActionState;
1431 * BlkActionOps:
1432 * Table of operations that define an Action.
1434 * @instance_size: Size of state struct, in bytes.
1435 * @prepare: Prepare the work, must NOT be NULL.
1436 * @commit: Commit the changes, can be NULL.
1437 * @abort: Abort the changes on fail, can be NULL.
1438 * @clean: Clean up resources after all transaction actions have called
1439 * commit() or abort(). Can be NULL.
1441 * Only prepare() may fail. In a single transaction, only one of commit() or
1442 * abort() will be called. clean() will always be called if it is present.
1444 typedef struct BlkActionOps {
1445 size_t instance_size;
1446 void (*prepare)(BlkActionState *common, Error **errp);
1447 void (*commit)(BlkActionState *common);
1448 void (*abort)(BlkActionState *common);
1449 void (*clean)(BlkActionState *common);
1450 } BlkActionOps;
1453 * BlkActionState:
1454 * Describes one Action's state within a Transaction.
1456 * @action: QAPI-defined enum identifying which Action to perform.
1457 * @ops: Table of ActionOps this Action can perform.
1458 * @block_job_txn: Transaction which this action belongs to.
1459 * @entry: List membership for all Actions in this Transaction.
1461 * This structure must be arranged as first member in a subclassed type,
1462 * assuming that the compiler will also arrange it to the same offsets as the
1463 * base class.
1465 struct BlkActionState {
1466 TransactionAction *action;
1467 const BlkActionOps *ops;
1468 BlockJobTxn *block_job_txn;
1469 TransactionProperties *txn_props;
1470 QSIMPLEQ_ENTRY(BlkActionState) entry;
1473 /* internal snapshot private data */
1474 typedef struct InternalSnapshotState {
1475 BlkActionState common;
1476 BlockDriverState *bs;
1477 AioContext *aio_context;
1478 QEMUSnapshotInfo sn;
1479 bool created;
1480 } InternalSnapshotState;
1483 static int action_check_completion_mode(BlkActionState *s, Error **errp)
1485 if (s->txn_props->completion_mode != ACTION_COMPLETION_MODE_INDIVIDUAL) {
1486 error_setg(errp,
1487 "Action '%s' does not support Transaction property "
1488 "completion-mode = %s",
1489 TransactionActionKind_lookup[s->action->type],
1490 ActionCompletionMode_lookup[s->txn_props->completion_mode]);
1491 return -1;
1493 return 0;
1496 static void internal_snapshot_prepare(BlkActionState *common,
1497 Error **errp)
1499 Error *local_err = NULL;
1500 const char *device;
1501 const char *name;
1502 BlockBackend *blk;
1503 BlockDriverState *bs;
1504 QEMUSnapshotInfo old_sn, *sn;
1505 bool ret;
1506 qemu_timeval tv;
1507 BlockdevSnapshotInternal *internal;
1508 InternalSnapshotState *state;
1509 int ret1;
1511 g_assert(common->action->type ==
1512 TRANSACTION_ACTION_KIND_BLOCKDEV_SNAPSHOT_INTERNAL_SYNC);
1513 internal = common->action->u.blockdev_snapshot_internal_sync.data;
1514 state = DO_UPCAST(InternalSnapshotState, common, common);
1516 /* 1. parse input */
1517 device = internal->device;
1518 name = internal->name;
1520 /* 2. check for validation */
1521 if (action_check_completion_mode(common, errp) < 0) {
1522 return;
1525 blk = blk_by_name(device);
1526 if (!blk) {
1527 error_set(errp, ERROR_CLASS_DEVICE_NOT_FOUND,
1528 "Device '%s' not found", device);
1529 return;
1532 /* AioContext is released in .clean() */
1533 state->aio_context = blk_get_aio_context(blk);
1534 aio_context_acquire(state->aio_context);
1536 if (!blk_is_available(blk)) {
1537 error_setg(errp, QERR_DEVICE_HAS_NO_MEDIUM, device);
1538 return;
1540 bs = blk_bs(blk);
1542 state->bs = bs;
1543 bdrv_drained_begin(bs);
1545 if (bdrv_op_is_blocked(bs, BLOCK_OP_TYPE_INTERNAL_SNAPSHOT, errp)) {
1546 return;
1549 if (bdrv_is_read_only(bs)) {
1550 error_setg(errp, "Device '%s' is read only", device);
1551 return;
1554 if (!bdrv_can_snapshot(bs)) {
1555 error_setg(errp, "Block format '%s' used by device '%s' "
1556 "does not support internal snapshots",
1557 bs->drv->format_name, device);
1558 return;
1561 if (!strlen(name)) {
1562 error_setg(errp, "Name is empty");
1563 return;
1566 /* check whether a snapshot with name exist */
1567 ret = bdrv_snapshot_find_by_id_and_name(bs, NULL, name, &old_sn,
1568 &local_err);
1569 if (local_err) {
1570 error_propagate(errp, local_err);
1571 return;
1572 } else if (ret) {
1573 error_setg(errp,
1574 "Snapshot with name '%s' already exists on device '%s'",
1575 name, device);
1576 return;
1579 /* 3. take the snapshot */
1580 sn = &state->sn;
1581 pstrcpy(sn->name, sizeof(sn->name), name);
1582 qemu_gettimeofday(&tv);
1583 sn->date_sec = tv.tv_sec;
1584 sn->date_nsec = tv.tv_usec * 1000;
1585 sn->vm_clock_nsec = qemu_clock_get_ns(QEMU_CLOCK_VIRTUAL);
1587 ret1 = bdrv_snapshot_create(bs, sn);
1588 if (ret1 < 0) {
1589 error_setg_errno(errp, -ret1,
1590 "Failed to create snapshot '%s' on device '%s'",
1591 name, device);
1592 return;
1595 /* 4. succeed, mark a snapshot is created */
1596 state->created = true;
1599 static void internal_snapshot_abort(BlkActionState *common)
1601 InternalSnapshotState *state =
1602 DO_UPCAST(InternalSnapshotState, common, common);
1603 BlockDriverState *bs = state->bs;
1604 QEMUSnapshotInfo *sn = &state->sn;
1605 Error *local_error = NULL;
1607 if (!state->created) {
1608 return;
1611 if (bdrv_snapshot_delete(bs, sn->id_str, sn->name, &local_error) < 0) {
1612 error_reportf_err(local_error,
1613 "Failed to delete snapshot with id '%s' and "
1614 "name '%s' on device '%s' in abort: ",
1615 sn->id_str, sn->name,
1616 bdrv_get_device_name(bs));
1620 static void internal_snapshot_clean(BlkActionState *common)
1622 InternalSnapshotState *state = DO_UPCAST(InternalSnapshotState,
1623 common, common);
1625 if (state->aio_context) {
1626 if (state->bs) {
1627 bdrv_drained_end(state->bs);
1629 aio_context_release(state->aio_context);
1633 /* external snapshot private data */
1634 typedef struct ExternalSnapshotState {
1635 BlkActionState common;
1636 BlockDriverState *old_bs;
1637 BlockDriverState *new_bs;
1638 AioContext *aio_context;
1639 } ExternalSnapshotState;
1641 static void external_snapshot_prepare(BlkActionState *common,
1642 Error **errp)
1644 int flags = 0;
1645 QDict *options = NULL;
1646 Error *local_err = NULL;
1647 /* Device and node name of the image to generate the snapshot from */
1648 const char *device;
1649 const char *node_name;
1650 /* Reference to the new image (for 'blockdev-snapshot') */
1651 const char *snapshot_ref;
1652 /* File name of the new image (for 'blockdev-snapshot-sync') */
1653 const char *new_image_file;
1654 ExternalSnapshotState *state =
1655 DO_UPCAST(ExternalSnapshotState, common, common);
1656 TransactionAction *action = common->action;
1658 /* 'blockdev-snapshot' and 'blockdev-snapshot-sync' have similar
1659 * purpose but a different set of parameters */
1660 switch (action->type) {
1661 case TRANSACTION_ACTION_KIND_BLOCKDEV_SNAPSHOT:
1663 BlockdevSnapshot *s = action->u.blockdev_snapshot.data;
1664 device = s->node;
1665 node_name = s->node;
1666 new_image_file = NULL;
1667 snapshot_ref = s->overlay;
1669 break;
1670 case TRANSACTION_ACTION_KIND_BLOCKDEV_SNAPSHOT_SYNC:
1672 BlockdevSnapshotSync *s = action->u.blockdev_snapshot_sync.data;
1673 device = s->has_device ? s->device : NULL;
1674 node_name = s->has_node_name ? s->node_name : NULL;
1675 new_image_file = s->snapshot_file;
1676 snapshot_ref = NULL;
1678 break;
1679 default:
1680 g_assert_not_reached();
1683 /* start processing */
1684 if (action_check_completion_mode(common, errp) < 0) {
1685 return;
1688 state->old_bs = bdrv_lookup_bs(device, node_name, errp);
1689 if (!state->old_bs) {
1690 return;
1693 /* Acquire AioContext now so any threads operating on old_bs stop */
1694 state->aio_context = bdrv_get_aio_context(state->old_bs);
1695 aio_context_acquire(state->aio_context);
1696 bdrv_drained_begin(state->old_bs);
1698 if (!bdrv_is_inserted(state->old_bs)) {
1699 error_setg(errp, QERR_DEVICE_HAS_NO_MEDIUM, device);
1700 return;
1703 if (bdrv_op_is_blocked(state->old_bs,
1704 BLOCK_OP_TYPE_EXTERNAL_SNAPSHOT, errp)) {
1705 return;
1708 if (!bdrv_is_read_only(state->old_bs)) {
1709 if (bdrv_flush(state->old_bs)) {
1710 error_setg(errp, QERR_IO_ERROR);
1711 return;
1715 if (!bdrv_is_first_non_filter(state->old_bs)) {
1716 error_setg(errp, QERR_FEATURE_DISABLED, "snapshot");
1717 return;
1720 if (action->type == TRANSACTION_ACTION_KIND_BLOCKDEV_SNAPSHOT_SYNC) {
1721 BlockdevSnapshotSync *s = action->u.blockdev_snapshot_sync.data;
1722 const char *format = s->has_format ? s->format : "qcow2";
1723 enum NewImageMode mode;
1724 const char *snapshot_node_name =
1725 s->has_snapshot_node_name ? s->snapshot_node_name : NULL;
1727 if (node_name && !snapshot_node_name) {
1728 error_setg(errp, "New snapshot node name missing");
1729 return;
1732 if (snapshot_node_name &&
1733 bdrv_lookup_bs(snapshot_node_name, snapshot_node_name, NULL)) {
1734 error_setg(errp, "New snapshot node name already in use");
1735 return;
1738 flags = state->old_bs->open_flags;
1739 flags &= ~(BDRV_O_SNAPSHOT | BDRV_O_NO_BACKING | BDRV_O_COPY_ON_READ);
1741 /* create new image w/backing file */
1742 mode = s->has_mode ? s->mode : NEW_IMAGE_MODE_ABSOLUTE_PATHS;
1743 if (mode != NEW_IMAGE_MODE_EXISTING) {
1744 int64_t size = bdrv_getlength(state->old_bs);
1745 if (size < 0) {
1746 error_setg_errno(errp, -size, "bdrv_getlength failed");
1747 return;
1749 bdrv_img_create(new_image_file, format,
1750 state->old_bs->filename,
1751 state->old_bs->drv->format_name,
1752 NULL, size, flags, &local_err, false);
1753 if (local_err) {
1754 error_propagate(errp, local_err);
1755 return;
1759 options = qdict_new();
1760 if (s->has_snapshot_node_name) {
1761 qdict_put(options, "node-name",
1762 qstring_from_str(snapshot_node_name));
1764 qdict_put(options, "driver", qstring_from_str(format));
1766 flags |= BDRV_O_NO_BACKING;
1769 state->new_bs = bdrv_open(new_image_file, snapshot_ref, options, flags,
1770 errp);
1771 /* We will manually add the backing_hd field to the bs later */
1772 if (!state->new_bs) {
1773 return;
1776 if (bdrv_has_blk(state->new_bs)) {
1777 error_setg(errp, "The snapshot is already in use by %s",
1778 bdrv_get_parent_name(state->new_bs));
1779 return;
1782 if (bdrv_op_is_blocked(state->new_bs, BLOCK_OP_TYPE_EXTERNAL_SNAPSHOT,
1783 errp)) {
1784 return;
1787 if (state->new_bs->backing != NULL) {
1788 error_setg(errp, "The snapshot already has a backing image");
1789 return;
1792 if (!state->new_bs->drv->supports_backing) {
1793 error_setg(errp, "The snapshot does not support backing images");
1797 static void external_snapshot_commit(BlkActionState *common)
1799 ExternalSnapshotState *state =
1800 DO_UPCAST(ExternalSnapshotState, common, common);
1802 bdrv_set_aio_context(state->new_bs, state->aio_context);
1804 /* This removes our old bs and adds the new bs */
1805 bdrv_append(state->new_bs, state->old_bs);
1806 /* We don't need (or want) to use the transactional
1807 * bdrv_reopen_multiple() across all the entries at once, because we
1808 * don't want to abort all of them if one of them fails the reopen */
1809 if (!state->old_bs->copy_on_read) {
1810 bdrv_reopen(state->old_bs, state->old_bs->open_flags & ~BDRV_O_RDWR,
1811 NULL);
1815 static void external_snapshot_abort(BlkActionState *common)
1817 ExternalSnapshotState *state =
1818 DO_UPCAST(ExternalSnapshotState, common, common);
1819 if (state->new_bs) {
1820 bdrv_unref(state->new_bs);
1824 static void external_snapshot_clean(BlkActionState *common)
1826 ExternalSnapshotState *state =
1827 DO_UPCAST(ExternalSnapshotState, common, common);
1828 if (state->aio_context) {
1829 bdrv_drained_end(state->old_bs);
1830 aio_context_release(state->aio_context);
1834 typedef struct DriveBackupState {
1835 BlkActionState common;
1836 BlockDriverState *bs;
1837 AioContext *aio_context;
1838 BlockJob *job;
1839 } DriveBackupState;
1841 static void do_drive_backup(const char *job_id, const char *device,
1842 const char *target, bool has_format,
1843 const char *format, enum MirrorSyncMode sync,
1844 bool has_mode, enum NewImageMode mode,
1845 bool has_speed, int64_t speed,
1846 bool has_bitmap, const char *bitmap,
1847 bool has_on_source_error,
1848 BlockdevOnError on_source_error,
1849 bool has_on_target_error,
1850 BlockdevOnError on_target_error,
1851 BlockJobTxn *txn, Error **errp);
1853 static void drive_backup_prepare(BlkActionState *common, Error **errp)
1855 DriveBackupState *state = DO_UPCAST(DriveBackupState, common, common);
1856 BlockBackend *blk;
1857 DriveBackup *backup;
1858 Error *local_err = NULL;
1860 assert(common->action->type == TRANSACTION_ACTION_KIND_DRIVE_BACKUP);
1861 backup = common->action->u.drive_backup.data;
1863 blk = blk_by_name(backup->device);
1864 if (!blk) {
1865 error_set(errp, ERROR_CLASS_DEVICE_NOT_FOUND,
1866 "Device '%s' not found", backup->device);
1867 return;
1870 if (!blk_is_available(blk)) {
1871 error_setg(errp, QERR_DEVICE_HAS_NO_MEDIUM, backup->device);
1872 return;
1875 /* AioContext is released in .clean() */
1876 state->aio_context = blk_get_aio_context(blk);
1877 aio_context_acquire(state->aio_context);
1878 bdrv_drained_begin(blk_bs(blk));
1879 state->bs = blk_bs(blk);
1881 do_drive_backup(backup->has_job_id ? backup->job_id : NULL,
1882 backup->device, backup->target,
1883 backup->has_format, backup->format,
1884 backup->sync,
1885 backup->has_mode, backup->mode,
1886 backup->has_speed, backup->speed,
1887 backup->has_bitmap, backup->bitmap,
1888 backup->has_on_source_error, backup->on_source_error,
1889 backup->has_on_target_error, backup->on_target_error,
1890 common->block_job_txn, &local_err);
1891 if (local_err) {
1892 error_propagate(errp, local_err);
1893 return;
1896 state->job = state->bs->job;
1899 static void drive_backup_abort(BlkActionState *common)
1901 DriveBackupState *state = DO_UPCAST(DriveBackupState, common, common);
1902 BlockDriverState *bs = state->bs;
1904 /* Only cancel if it's the job we started */
1905 if (bs && bs->job && bs->job == state->job) {
1906 block_job_cancel_sync(bs->job);
1910 static void drive_backup_clean(BlkActionState *common)
1912 DriveBackupState *state = DO_UPCAST(DriveBackupState, common, common);
1914 if (state->aio_context) {
1915 bdrv_drained_end(state->bs);
1916 aio_context_release(state->aio_context);
1920 typedef struct BlockdevBackupState {
1921 BlkActionState common;
1922 BlockDriverState *bs;
1923 BlockJob *job;
1924 AioContext *aio_context;
1925 } BlockdevBackupState;
1927 static void do_blockdev_backup(const char *job_id, const char *device,
1928 const char *target, enum MirrorSyncMode sync,
1929 bool has_speed, int64_t speed,
1930 bool has_on_source_error,
1931 BlockdevOnError on_source_error,
1932 bool has_on_target_error,
1933 BlockdevOnError on_target_error,
1934 BlockJobTxn *txn, Error **errp);
1936 static void blockdev_backup_prepare(BlkActionState *common, Error **errp)
1938 BlockdevBackupState *state = DO_UPCAST(BlockdevBackupState, common, common);
1939 BlockdevBackup *backup;
1940 BlockBackend *blk;
1941 BlockDriverState *target;
1942 Error *local_err = NULL;
1944 assert(common->action->type == TRANSACTION_ACTION_KIND_BLOCKDEV_BACKUP);
1945 backup = common->action->u.blockdev_backup.data;
1947 blk = blk_by_name(backup->device);
1948 if (!blk) {
1949 error_setg(errp, "Device '%s' not found", backup->device);
1950 return;
1953 if (!blk_is_available(blk)) {
1954 error_setg(errp, QERR_DEVICE_HAS_NO_MEDIUM, backup->device);
1955 return;
1958 target = bdrv_lookup_bs(backup->target, backup->target, errp);
1959 if (!target) {
1960 return;
1963 /* AioContext is released in .clean() */
1964 state->aio_context = blk_get_aio_context(blk);
1965 if (state->aio_context != bdrv_get_aio_context(target)) {
1966 state->aio_context = NULL;
1967 error_setg(errp, "Backup between two IO threads is not implemented");
1968 return;
1970 aio_context_acquire(state->aio_context);
1971 state->bs = blk_bs(blk);
1972 bdrv_drained_begin(state->bs);
1974 do_blockdev_backup(backup->has_job_id ? backup->job_id : NULL,
1975 backup->device, backup->target, backup->sync,
1976 backup->has_speed, backup->speed,
1977 backup->has_on_source_error, backup->on_source_error,
1978 backup->has_on_target_error, backup->on_target_error,
1979 common->block_job_txn, &local_err);
1980 if (local_err) {
1981 error_propagate(errp, local_err);
1982 return;
1985 state->job = state->bs->job;
1988 static void blockdev_backup_abort(BlkActionState *common)
1990 BlockdevBackupState *state = DO_UPCAST(BlockdevBackupState, common, common);
1991 BlockDriverState *bs = state->bs;
1993 /* Only cancel if it's the job we started */
1994 if (bs && bs->job && bs->job == state->job) {
1995 block_job_cancel_sync(bs->job);
1999 static void blockdev_backup_clean(BlkActionState *common)
2001 BlockdevBackupState *state = DO_UPCAST(BlockdevBackupState, common, common);
2003 if (state->aio_context) {
2004 bdrv_drained_end(state->bs);
2005 aio_context_release(state->aio_context);
2009 typedef struct BlockDirtyBitmapState {
2010 BlkActionState common;
2011 BdrvDirtyBitmap *bitmap;
2012 BlockDriverState *bs;
2013 AioContext *aio_context;
2014 HBitmap *backup;
2015 bool prepared;
2016 } BlockDirtyBitmapState;
2018 static void block_dirty_bitmap_add_prepare(BlkActionState *common,
2019 Error **errp)
2021 Error *local_err = NULL;
2022 BlockDirtyBitmapAdd *action;
2023 BlockDirtyBitmapState *state = DO_UPCAST(BlockDirtyBitmapState,
2024 common, common);
2026 if (action_check_completion_mode(common, errp) < 0) {
2027 return;
2030 action = common->action->u.block_dirty_bitmap_add.data;
2031 /* AIO context taken and released within qmp_block_dirty_bitmap_add */
2032 qmp_block_dirty_bitmap_add(action->node, action->name,
2033 action->has_granularity, action->granularity,
2034 &local_err);
2036 if (!local_err) {
2037 state->prepared = true;
2038 } else {
2039 error_propagate(errp, local_err);
2043 static void block_dirty_bitmap_add_abort(BlkActionState *common)
2045 BlockDirtyBitmapAdd *action;
2046 BlockDirtyBitmapState *state = DO_UPCAST(BlockDirtyBitmapState,
2047 common, common);
2049 action = common->action->u.block_dirty_bitmap_add.data;
2050 /* Should not be able to fail: IF the bitmap was added via .prepare(),
2051 * then the node reference and bitmap name must have been valid.
2053 if (state->prepared) {
2054 qmp_block_dirty_bitmap_remove(action->node, action->name, &error_abort);
2058 static void block_dirty_bitmap_clear_prepare(BlkActionState *common,
2059 Error **errp)
2061 BlockDirtyBitmapState *state = DO_UPCAST(BlockDirtyBitmapState,
2062 common, common);
2063 BlockDirtyBitmap *action;
2065 if (action_check_completion_mode(common, errp) < 0) {
2066 return;
2069 action = common->action->u.block_dirty_bitmap_clear.data;
2070 state->bitmap = block_dirty_bitmap_lookup(action->node,
2071 action->name,
2072 &state->bs,
2073 &state->aio_context,
2074 errp);
2075 if (!state->bitmap) {
2076 return;
2079 if (bdrv_dirty_bitmap_frozen(state->bitmap)) {
2080 error_setg(errp, "Cannot modify a frozen bitmap");
2081 return;
2082 } else if (!bdrv_dirty_bitmap_enabled(state->bitmap)) {
2083 error_setg(errp, "Cannot clear a disabled bitmap");
2084 return;
2087 bdrv_clear_dirty_bitmap(state->bitmap, &state->backup);
2088 /* AioContext is released in .clean() */
2091 static void block_dirty_bitmap_clear_abort(BlkActionState *common)
2093 BlockDirtyBitmapState *state = DO_UPCAST(BlockDirtyBitmapState,
2094 common, common);
2096 bdrv_undo_clear_dirty_bitmap(state->bitmap, state->backup);
2099 static void block_dirty_bitmap_clear_commit(BlkActionState *common)
2101 BlockDirtyBitmapState *state = DO_UPCAST(BlockDirtyBitmapState,
2102 common, common);
2104 hbitmap_free(state->backup);
2107 static void block_dirty_bitmap_clear_clean(BlkActionState *common)
2109 BlockDirtyBitmapState *state = DO_UPCAST(BlockDirtyBitmapState,
2110 common, common);
2112 if (state->aio_context) {
2113 aio_context_release(state->aio_context);
2117 static void abort_prepare(BlkActionState *common, Error **errp)
2119 error_setg(errp, "Transaction aborted using Abort action");
2122 static void abort_commit(BlkActionState *common)
2124 g_assert_not_reached(); /* this action never succeeds */
2127 static const BlkActionOps actions[] = {
2128 [TRANSACTION_ACTION_KIND_BLOCKDEV_SNAPSHOT] = {
2129 .instance_size = sizeof(ExternalSnapshotState),
2130 .prepare = external_snapshot_prepare,
2131 .commit = external_snapshot_commit,
2132 .abort = external_snapshot_abort,
2133 .clean = external_snapshot_clean,
2135 [TRANSACTION_ACTION_KIND_BLOCKDEV_SNAPSHOT_SYNC] = {
2136 .instance_size = sizeof(ExternalSnapshotState),
2137 .prepare = external_snapshot_prepare,
2138 .commit = external_snapshot_commit,
2139 .abort = external_snapshot_abort,
2140 .clean = external_snapshot_clean,
2142 [TRANSACTION_ACTION_KIND_DRIVE_BACKUP] = {
2143 .instance_size = sizeof(DriveBackupState),
2144 .prepare = drive_backup_prepare,
2145 .abort = drive_backup_abort,
2146 .clean = drive_backup_clean,
2148 [TRANSACTION_ACTION_KIND_BLOCKDEV_BACKUP] = {
2149 .instance_size = sizeof(BlockdevBackupState),
2150 .prepare = blockdev_backup_prepare,
2151 .abort = blockdev_backup_abort,
2152 .clean = blockdev_backup_clean,
2154 [TRANSACTION_ACTION_KIND_ABORT] = {
2155 .instance_size = sizeof(BlkActionState),
2156 .prepare = abort_prepare,
2157 .commit = abort_commit,
2159 [TRANSACTION_ACTION_KIND_BLOCKDEV_SNAPSHOT_INTERNAL_SYNC] = {
2160 .instance_size = sizeof(InternalSnapshotState),
2161 .prepare = internal_snapshot_prepare,
2162 .abort = internal_snapshot_abort,
2163 .clean = internal_snapshot_clean,
2165 [TRANSACTION_ACTION_KIND_BLOCK_DIRTY_BITMAP_ADD] = {
2166 .instance_size = sizeof(BlockDirtyBitmapState),
2167 .prepare = block_dirty_bitmap_add_prepare,
2168 .abort = block_dirty_bitmap_add_abort,
2170 [TRANSACTION_ACTION_KIND_BLOCK_DIRTY_BITMAP_CLEAR] = {
2171 .instance_size = sizeof(BlockDirtyBitmapState),
2172 .prepare = block_dirty_bitmap_clear_prepare,
2173 .commit = block_dirty_bitmap_clear_commit,
2174 .abort = block_dirty_bitmap_clear_abort,
2175 .clean = block_dirty_bitmap_clear_clean,
2180 * Allocate a TransactionProperties structure if necessary, and fill
2181 * that structure with desired defaults if they are unset.
2183 static TransactionProperties *get_transaction_properties(
2184 TransactionProperties *props)
2186 if (!props) {
2187 props = g_new0(TransactionProperties, 1);
2190 if (!props->has_completion_mode) {
2191 props->has_completion_mode = true;
2192 props->completion_mode = ACTION_COMPLETION_MODE_INDIVIDUAL;
2195 return props;
2199 * 'Atomic' group operations. The operations are performed as a set, and if
2200 * any fail then we roll back all operations in the group.
2202 void qmp_transaction(TransactionActionList *dev_list,
2203 bool has_props,
2204 struct TransactionProperties *props,
2205 Error **errp)
2207 TransactionActionList *dev_entry = dev_list;
2208 BlockJobTxn *block_job_txn = NULL;
2209 BlkActionState *state, *next;
2210 Error *local_err = NULL;
2212 QSIMPLEQ_HEAD(snap_bdrv_states, BlkActionState) snap_bdrv_states;
2213 QSIMPLEQ_INIT(&snap_bdrv_states);
2215 /* Does this transaction get canceled as a group on failure?
2216 * If not, we don't really need to make a BlockJobTxn.
2218 props = get_transaction_properties(props);
2219 if (props->completion_mode != ACTION_COMPLETION_MODE_INDIVIDUAL) {
2220 block_job_txn = block_job_txn_new();
2223 /* drain all i/o before any operations */
2224 bdrv_drain_all();
2226 /* We don't do anything in this loop that commits us to the operations */
2227 while (NULL != dev_entry) {
2228 TransactionAction *dev_info = NULL;
2229 const BlkActionOps *ops;
2231 dev_info = dev_entry->value;
2232 dev_entry = dev_entry->next;
2234 assert(dev_info->type < ARRAY_SIZE(actions));
2236 ops = &actions[dev_info->type];
2237 assert(ops->instance_size > 0);
2239 state = g_malloc0(ops->instance_size);
2240 state->ops = ops;
2241 state->action = dev_info;
2242 state->block_job_txn = block_job_txn;
2243 state->txn_props = props;
2244 QSIMPLEQ_INSERT_TAIL(&snap_bdrv_states, state, entry);
2246 state->ops->prepare(state, &local_err);
2247 if (local_err) {
2248 error_propagate(errp, local_err);
2249 goto delete_and_fail;
2253 QSIMPLEQ_FOREACH(state, &snap_bdrv_states, entry) {
2254 if (state->ops->commit) {
2255 state->ops->commit(state);
2259 /* success */
2260 goto exit;
2262 delete_and_fail:
2263 /* failure, and it is all-or-none; roll back all operations */
2264 QSIMPLEQ_FOREACH(state, &snap_bdrv_states, entry) {
2265 if (state->ops->abort) {
2266 state->ops->abort(state);
2269 exit:
2270 QSIMPLEQ_FOREACH_SAFE(state, &snap_bdrv_states, entry, next) {
2271 if (state->ops->clean) {
2272 state->ops->clean(state);
2274 g_free(state);
2276 if (!has_props) {
2277 qapi_free_TransactionProperties(props);
2279 block_job_txn_unref(block_job_txn);
2282 void qmp_eject(const char *device, bool has_force, bool force, Error **errp)
2284 Error *local_err = NULL;
2285 int rc;
2287 if (!has_force) {
2288 force = false;
2291 rc = do_open_tray(device, force, &local_err);
2292 if (rc && rc != -ENOSYS) {
2293 error_propagate(errp, local_err);
2294 return;
2296 error_free(local_err);
2298 qmp_x_blockdev_remove_medium(device, errp);
2301 void qmp_block_passwd(bool has_device, const char *device,
2302 bool has_node_name, const char *node_name,
2303 const char *password, Error **errp)
2305 Error *local_err = NULL;
2306 BlockDriverState *bs;
2307 AioContext *aio_context;
2309 bs = bdrv_lookup_bs(has_device ? device : NULL,
2310 has_node_name ? node_name : NULL,
2311 &local_err);
2312 if (local_err) {
2313 error_propagate(errp, local_err);
2314 return;
2317 aio_context = bdrv_get_aio_context(bs);
2318 aio_context_acquire(aio_context);
2320 bdrv_add_key(bs, password, errp);
2322 aio_context_release(aio_context);
2326 * Attempt to open the tray of @device.
2327 * If @force, ignore its tray lock.
2328 * Else, if the tray is locked, don't open it, but ask the guest to open it.
2329 * On error, store an error through @errp and return -errno.
2330 * If @device does not exist, return -ENODEV.
2331 * If it has no removable media, return -ENOTSUP.
2332 * If it has no tray, return -ENOSYS.
2333 * If the guest was asked to open the tray, return -EINPROGRESS.
2334 * Else, return 0.
2336 static int do_open_tray(const char *device, bool force, Error **errp)
2338 BlockBackend *blk;
2339 bool locked;
2341 blk = blk_by_name(device);
2342 if (!blk) {
2343 error_set(errp, ERROR_CLASS_DEVICE_NOT_FOUND,
2344 "Device '%s' not found", device);
2345 return -ENODEV;
2348 if (!blk_dev_has_removable_media(blk)) {
2349 error_setg(errp, "Device '%s' is not removable", device);
2350 return -ENOTSUP;
2353 if (!blk_dev_has_tray(blk)) {
2354 error_setg(errp, "Device '%s' does not have a tray", device);
2355 return -ENOSYS;
2358 if (blk_dev_is_tray_open(blk)) {
2359 return 0;
2362 locked = blk_dev_is_medium_locked(blk);
2363 if (locked) {
2364 blk_dev_eject_request(blk, force);
2367 if (!locked || force) {
2368 blk_dev_change_media_cb(blk, false);
2371 if (locked && !force) {
2372 error_setg(errp, "Device '%s' is locked and force was not specified, "
2373 "wait for tray to open and try again", device);
2374 return -EINPROGRESS;
2377 return 0;
2380 void qmp_blockdev_open_tray(const char *device, bool has_force, bool force,
2381 Error **errp)
2383 Error *local_err = NULL;
2384 int rc;
2386 if (!has_force) {
2387 force = false;
2389 rc = do_open_tray(device, force, &local_err);
2390 if (rc && rc != -ENOSYS && rc != -EINPROGRESS) {
2391 error_propagate(errp, local_err);
2392 return;
2394 error_free(local_err);
2397 void qmp_blockdev_close_tray(const char *device, Error **errp)
2399 BlockBackend *blk;
2401 blk = blk_by_name(device);
2402 if (!blk) {
2403 error_set(errp, ERROR_CLASS_DEVICE_NOT_FOUND,
2404 "Device '%s' not found", device);
2405 return;
2408 if (!blk_dev_has_removable_media(blk)) {
2409 error_setg(errp, "Device '%s' is not removable", device);
2410 return;
2413 if (!blk_dev_has_tray(blk)) {
2414 /* Ignore this command on tray-less devices */
2415 return;
2418 if (!blk_dev_is_tray_open(blk)) {
2419 return;
2422 blk_dev_change_media_cb(blk, true);
2425 void qmp_x_blockdev_remove_medium(const char *device, Error **errp)
2427 BlockBackend *blk;
2428 BlockDriverState *bs;
2429 AioContext *aio_context;
2430 bool has_device;
2432 blk = blk_by_name(device);
2433 if (!blk) {
2434 error_set(errp, ERROR_CLASS_DEVICE_NOT_FOUND,
2435 "Device '%s' not found", device);
2436 return;
2439 /* For BBs without a device, we can exchange the BDS tree at will */
2440 has_device = blk_get_attached_dev(blk);
2442 if (has_device && !blk_dev_has_removable_media(blk)) {
2443 error_setg(errp, "Device '%s' is not removable", device);
2444 return;
2447 if (has_device && blk_dev_has_tray(blk) && !blk_dev_is_tray_open(blk)) {
2448 error_setg(errp, "Tray of device '%s' is not open", device);
2449 return;
2452 bs = blk_bs(blk);
2453 if (!bs) {
2454 return;
2457 aio_context = bdrv_get_aio_context(bs);
2458 aio_context_acquire(aio_context);
2460 if (bdrv_op_is_blocked(bs, BLOCK_OP_TYPE_EJECT, errp)) {
2461 goto out;
2464 blk_remove_bs(blk);
2466 if (!blk_dev_has_tray(blk)) {
2467 /* For tray-less devices, blockdev-open-tray is a no-op (or may not be
2468 * called at all); therefore, the medium needs to be ejected here.
2469 * Do it after blk_remove_bs() so blk_is_inserted(blk) returns the @load
2470 * value passed here (i.e. false). */
2471 blk_dev_change_media_cb(blk, false);
2474 out:
2475 aio_context_release(aio_context);
2478 static void qmp_blockdev_insert_anon_medium(const char *device,
2479 BlockDriverState *bs, Error **errp)
2481 BlockBackend *blk;
2482 bool has_device;
2484 blk = blk_by_name(device);
2485 if (!blk) {
2486 error_set(errp, ERROR_CLASS_DEVICE_NOT_FOUND,
2487 "Device '%s' not found", device);
2488 return;
2491 /* For BBs without a device, we can exchange the BDS tree at will */
2492 has_device = blk_get_attached_dev(blk);
2494 if (has_device && !blk_dev_has_removable_media(blk)) {
2495 error_setg(errp, "Device '%s' is not removable", device);
2496 return;
2499 if (has_device && blk_dev_has_tray(blk) && !blk_dev_is_tray_open(blk)) {
2500 error_setg(errp, "Tray of device '%s' is not open", device);
2501 return;
2504 if (blk_bs(blk)) {
2505 error_setg(errp, "There already is a medium in device '%s'", device);
2506 return;
2509 blk_insert_bs(blk, bs);
2511 if (!blk_dev_has_tray(blk)) {
2512 /* For tray-less devices, blockdev-close-tray is a no-op (or may not be
2513 * called at all); therefore, the medium needs to be pushed into the
2514 * slot here.
2515 * Do it after blk_insert_bs() so blk_is_inserted(blk) returns the @load
2516 * value passed here (i.e. true). */
2517 blk_dev_change_media_cb(blk, true);
2521 void qmp_x_blockdev_insert_medium(const char *device, const char *node_name,
2522 Error **errp)
2524 BlockDriverState *bs;
2526 bs = bdrv_find_node(node_name);
2527 if (!bs) {
2528 error_setg(errp, "Node '%s' not found", node_name);
2529 return;
2532 if (bdrv_has_blk(bs)) {
2533 error_setg(errp, "Node '%s' is already in use by '%s'", node_name,
2534 bdrv_get_parent_name(bs));
2535 return;
2538 qmp_blockdev_insert_anon_medium(device, bs, errp);
2541 void qmp_blockdev_change_medium(const char *device, const char *filename,
2542 bool has_format, const char *format,
2543 bool has_read_only,
2544 BlockdevChangeReadOnlyMode read_only,
2545 Error **errp)
2547 BlockBackend *blk;
2548 BlockDriverState *medium_bs = NULL;
2549 int bdrv_flags;
2550 int rc;
2551 QDict *options = NULL;
2552 Error *err = NULL;
2554 blk = blk_by_name(device);
2555 if (!blk) {
2556 error_set(errp, ERROR_CLASS_DEVICE_NOT_FOUND,
2557 "Device '%s' not found", device);
2558 goto fail;
2561 if (blk_bs(blk)) {
2562 blk_update_root_state(blk);
2565 bdrv_flags = blk_get_open_flags_from_root_state(blk);
2566 bdrv_flags &= ~(BDRV_O_TEMPORARY | BDRV_O_SNAPSHOT | BDRV_O_NO_BACKING |
2567 BDRV_O_PROTOCOL);
2569 if (!has_read_only) {
2570 read_only = BLOCKDEV_CHANGE_READ_ONLY_MODE_RETAIN;
2573 switch (read_only) {
2574 case BLOCKDEV_CHANGE_READ_ONLY_MODE_RETAIN:
2575 break;
2577 case BLOCKDEV_CHANGE_READ_ONLY_MODE_READ_ONLY:
2578 bdrv_flags &= ~BDRV_O_RDWR;
2579 break;
2581 case BLOCKDEV_CHANGE_READ_ONLY_MODE_READ_WRITE:
2582 bdrv_flags |= BDRV_O_RDWR;
2583 break;
2585 default:
2586 abort();
2589 if (has_format) {
2590 options = qdict_new();
2591 qdict_put(options, "driver", qstring_from_str(format));
2594 medium_bs = bdrv_open(filename, NULL, options, bdrv_flags, errp);
2595 if (!medium_bs) {
2596 goto fail;
2599 bdrv_add_key(medium_bs, NULL, &err);
2600 if (err) {
2601 error_propagate(errp, err);
2602 goto fail;
2605 rc = do_open_tray(device, false, &err);
2606 if (rc && rc != -ENOSYS) {
2607 error_propagate(errp, err);
2608 goto fail;
2610 error_free(err);
2611 err = NULL;
2613 qmp_x_blockdev_remove_medium(device, &err);
2614 if (err) {
2615 error_propagate(errp, err);
2616 goto fail;
2619 qmp_blockdev_insert_anon_medium(device, medium_bs, &err);
2620 if (err) {
2621 error_propagate(errp, err);
2622 goto fail;
2625 blk_apply_root_state(blk, medium_bs);
2627 qmp_blockdev_close_tray(device, errp);
2629 fail:
2630 /* If the medium has been inserted, the device has its own reference, so
2631 * ours must be relinquished; and if it has not been inserted successfully,
2632 * the reference must be relinquished anyway */
2633 bdrv_unref(medium_bs);
2636 /* throttling disk I/O limits */
2637 void qmp_block_set_io_throttle(BlockIOThrottle *arg, Error **errp)
2639 ThrottleConfig cfg;
2640 BlockDriverState *bs;
2641 BlockBackend *blk;
2642 AioContext *aio_context;
2644 blk = blk_by_name(arg->device);
2645 if (!blk) {
2646 error_set(errp, ERROR_CLASS_DEVICE_NOT_FOUND,
2647 "Device '%s' not found", arg->device);
2648 return;
2651 aio_context = blk_get_aio_context(blk);
2652 aio_context_acquire(aio_context);
2654 bs = blk_bs(blk);
2655 if (!bs) {
2656 error_setg(errp, "Device '%s' has no medium", arg->device);
2657 goto out;
2660 throttle_config_init(&cfg);
2661 cfg.buckets[THROTTLE_BPS_TOTAL].avg = arg->bps;
2662 cfg.buckets[THROTTLE_BPS_READ].avg = arg->bps_rd;
2663 cfg.buckets[THROTTLE_BPS_WRITE].avg = arg->bps_wr;
2665 cfg.buckets[THROTTLE_OPS_TOTAL].avg = arg->iops;
2666 cfg.buckets[THROTTLE_OPS_READ].avg = arg->iops_rd;
2667 cfg.buckets[THROTTLE_OPS_WRITE].avg = arg->iops_wr;
2669 if (arg->has_bps_max) {
2670 cfg.buckets[THROTTLE_BPS_TOTAL].max = arg->bps_max;
2672 if (arg->has_bps_rd_max) {
2673 cfg.buckets[THROTTLE_BPS_READ].max = arg->bps_rd_max;
2675 if (arg->has_bps_wr_max) {
2676 cfg.buckets[THROTTLE_BPS_WRITE].max = arg->bps_wr_max;
2678 if (arg->has_iops_max) {
2679 cfg.buckets[THROTTLE_OPS_TOTAL].max = arg->iops_max;
2681 if (arg->has_iops_rd_max) {
2682 cfg.buckets[THROTTLE_OPS_READ].max = arg->iops_rd_max;
2684 if (arg->has_iops_wr_max) {
2685 cfg.buckets[THROTTLE_OPS_WRITE].max = arg->iops_wr_max;
2688 if (arg->has_bps_max_length) {
2689 cfg.buckets[THROTTLE_BPS_TOTAL].burst_length = arg->bps_max_length;
2691 if (arg->has_bps_rd_max_length) {
2692 cfg.buckets[THROTTLE_BPS_READ].burst_length = arg->bps_rd_max_length;
2694 if (arg->has_bps_wr_max_length) {
2695 cfg.buckets[THROTTLE_BPS_WRITE].burst_length = arg->bps_wr_max_length;
2697 if (arg->has_iops_max_length) {
2698 cfg.buckets[THROTTLE_OPS_TOTAL].burst_length = arg->iops_max_length;
2700 if (arg->has_iops_rd_max_length) {
2701 cfg.buckets[THROTTLE_OPS_READ].burst_length = arg->iops_rd_max_length;
2703 if (arg->has_iops_wr_max_length) {
2704 cfg.buckets[THROTTLE_OPS_WRITE].burst_length = arg->iops_wr_max_length;
2707 if (arg->has_iops_size) {
2708 cfg.op_size = arg->iops_size;
2711 if (!throttle_is_valid(&cfg, errp)) {
2712 goto out;
2715 if (throttle_enabled(&cfg)) {
2716 /* Enable I/O limits if they're not enabled yet, otherwise
2717 * just update the throttling group. */
2718 if (!blk_get_public(blk)->throttle_state) {
2719 blk_io_limits_enable(blk,
2720 arg->has_group ? arg->group : arg->device);
2721 } else if (arg->has_group) {
2722 blk_io_limits_update_group(blk, arg->group);
2724 /* Set the new throttling configuration */
2725 blk_set_io_limits(blk, &cfg);
2726 } else if (blk_get_public(blk)->throttle_state) {
2727 /* If all throttling settings are set to 0, disable I/O limits */
2728 blk_io_limits_disable(blk);
2731 out:
2732 aio_context_release(aio_context);
2735 void qmp_block_dirty_bitmap_add(const char *node, const char *name,
2736 bool has_granularity, uint32_t granularity,
2737 Error **errp)
2739 AioContext *aio_context;
2740 BlockDriverState *bs;
2742 if (!name || name[0] == '\0') {
2743 error_setg(errp, "Bitmap name cannot be empty");
2744 return;
2747 bs = bdrv_lookup_bs(node, node, errp);
2748 if (!bs) {
2749 return;
2752 aio_context = bdrv_get_aio_context(bs);
2753 aio_context_acquire(aio_context);
2755 if (has_granularity) {
2756 if (granularity < 512 || !is_power_of_2(granularity)) {
2757 error_setg(errp, "Granularity must be power of 2 "
2758 "and at least 512");
2759 goto out;
2761 } else {
2762 /* Default to cluster size, if available: */
2763 granularity = bdrv_get_default_bitmap_granularity(bs);
2766 bdrv_create_dirty_bitmap(bs, granularity, name, errp);
2768 out:
2769 aio_context_release(aio_context);
2772 void qmp_block_dirty_bitmap_remove(const char *node, const char *name,
2773 Error **errp)
2775 AioContext *aio_context;
2776 BlockDriverState *bs;
2777 BdrvDirtyBitmap *bitmap;
2779 bitmap = block_dirty_bitmap_lookup(node, name, &bs, &aio_context, errp);
2780 if (!bitmap || !bs) {
2781 return;
2784 if (bdrv_dirty_bitmap_frozen(bitmap)) {
2785 error_setg(errp,
2786 "Bitmap '%s' is currently frozen and cannot be removed",
2787 name);
2788 goto out;
2790 bdrv_dirty_bitmap_make_anon(bitmap);
2791 bdrv_release_dirty_bitmap(bs, bitmap);
2793 out:
2794 aio_context_release(aio_context);
2798 * Completely clear a bitmap, for the purposes of synchronizing a bitmap
2799 * immediately after a full backup operation.
2801 void qmp_block_dirty_bitmap_clear(const char *node, const char *name,
2802 Error **errp)
2804 AioContext *aio_context;
2805 BdrvDirtyBitmap *bitmap;
2806 BlockDriverState *bs;
2808 bitmap = block_dirty_bitmap_lookup(node, name, &bs, &aio_context, errp);
2809 if (!bitmap || !bs) {
2810 return;
2813 if (bdrv_dirty_bitmap_frozen(bitmap)) {
2814 error_setg(errp,
2815 "Bitmap '%s' is currently frozen and cannot be modified",
2816 name);
2817 goto out;
2818 } else if (!bdrv_dirty_bitmap_enabled(bitmap)) {
2819 error_setg(errp,
2820 "Bitmap '%s' is currently disabled and cannot be cleared",
2821 name);
2822 goto out;
2825 bdrv_clear_dirty_bitmap(bitmap, NULL);
2827 out:
2828 aio_context_release(aio_context);
2831 void hmp_drive_del(Monitor *mon, const QDict *qdict)
2833 const char *id = qdict_get_str(qdict, "id");
2834 BlockBackend *blk;
2835 BlockDriverState *bs;
2836 AioContext *aio_context;
2837 Error *local_err = NULL;
2839 bs = bdrv_find_node(id);
2840 if (bs) {
2841 qmp_x_blockdev_del(false, NULL, true, id, &local_err);
2842 if (local_err) {
2843 error_report_err(local_err);
2845 return;
2848 blk = blk_by_name(id);
2849 if (!blk) {
2850 error_report("Device '%s' not found", id);
2851 return;
2854 if (!blk_legacy_dinfo(blk)) {
2855 error_report("Deleting device added with blockdev-add"
2856 " is not supported");
2857 return;
2860 aio_context = blk_get_aio_context(blk);
2861 aio_context_acquire(aio_context);
2863 bs = blk_bs(blk);
2864 if (bs) {
2865 if (bdrv_op_is_blocked(bs, BLOCK_OP_TYPE_DRIVE_DEL, &local_err)) {
2866 error_report_err(local_err);
2867 aio_context_release(aio_context);
2868 return;
2871 blk_remove_bs(blk);
2874 /* Make the BlockBackend and the attached BlockDriverState anonymous */
2875 monitor_remove_blk(blk);
2877 /* If this BlockBackend has a device attached to it, its refcount will be
2878 * decremented when the device is removed; otherwise we have to do so here.
2880 if (blk_get_attached_dev(blk)) {
2881 /* Further I/O must not pause the guest */
2882 blk_set_on_error(blk, BLOCKDEV_ON_ERROR_REPORT,
2883 BLOCKDEV_ON_ERROR_REPORT);
2884 } else {
2885 blk_unref(blk);
2888 aio_context_release(aio_context);
2891 void qmp_block_resize(bool has_device, const char *device,
2892 bool has_node_name, const char *node_name,
2893 int64_t size, Error **errp)
2895 Error *local_err = NULL;
2896 BlockDriverState *bs;
2897 AioContext *aio_context;
2898 int ret;
2900 bs = bdrv_lookup_bs(has_device ? device : NULL,
2901 has_node_name ? node_name : NULL,
2902 &local_err);
2903 if (local_err) {
2904 error_propagate(errp, local_err);
2905 return;
2908 aio_context = bdrv_get_aio_context(bs);
2909 aio_context_acquire(aio_context);
2911 if (!bdrv_is_first_non_filter(bs)) {
2912 error_setg(errp, QERR_FEATURE_DISABLED, "resize");
2913 goto out;
2916 if (size < 0) {
2917 error_setg(errp, QERR_INVALID_PARAMETER_VALUE, "size", "a >0 size");
2918 goto out;
2921 if (bdrv_op_is_blocked(bs, BLOCK_OP_TYPE_RESIZE, NULL)) {
2922 error_setg(errp, QERR_DEVICE_IN_USE, device);
2923 goto out;
2926 /* complete all in-flight operations before resizing the device */
2927 bdrv_drain_all();
2929 ret = bdrv_truncate(bs, size);
2930 switch (ret) {
2931 case 0:
2932 break;
2933 case -ENOMEDIUM:
2934 error_setg(errp, QERR_DEVICE_HAS_NO_MEDIUM, device);
2935 break;
2936 case -ENOTSUP:
2937 error_setg(errp, QERR_UNSUPPORTED);
2938 break;
2939 case -EACCES:
2940 error_setg(errp, "Device '%s' is read only", device);
2941 break;
2942 case -EBUSY:
2943 error_setg(errp, QERR_DEVICE_IN_USE, device);
2944 break;
2945 default:
2946 error_setg_errno(errp, -ret, "Could not resize");
2947 break;
2950 out:
2951 aio_context_release(aio_context);
2954 static void block_job_cb(void *opaque, int ret)
2956 /* Note that this function may be executed from another AioContext besides
2957 * the QEMU main loop. If you need to access anything that assumes the
2958 * QEMU global mutex, use a BH or introduce a mutex.
2961 BlockDriverState *bs = opaque;
2962 const char *msg = NULL;
2964 trace_block_job_cb(bs, bs->job, ret);
2966 assert(bs->job);
2968 if (ret < 0) {
2969 msg = strerror(-ret);
2972 if (block_job_is_cancelled(bs->job)) {
2973 block_job_event_cancelled(bs->job);
2974 } else {
2975 block_job_event_completed(bs->job, msg);
2979 void qmp_block_stream(bool has_job_id, const char *job_id, const char *device,
2980 bool has_base, const char *base,
2981 bool has_backing_file, const char *backing_file,
2982 bool has_speed, int64_t speed,
2983 bool has_on_error, BlockdevOnError on_error,
2984 Error **errp)
2986 BlockBackend *blk;
2987 BlockDriverState *bs;
2988 BlockDriverState *base_bs = NULL;
2989 AioContext *aio_context;
2990 Error *local_err = NULL;
2991 const char *base_name = NULL;
2993 if (!has_on_error) {
2994 on_error = BLOCKDEV_ON_ERROR_REPORT;
2997 blk = blk_by_name(device);
2998 if (!blk) {
2999 error_set(errp, ERROR_CLASS_DEVICE_NOT_FOUND,
3000 "Device '%s' not found", device);
3001 return;
3004 aio_context = blk_get_aio_context(blk);
3005 aio_context_acquire(aio_context);
3007 if (!blk_is_available(blk)) {
3008 error_setg(errp, "Device '%s' has no medium", device);
3009 goto out;
3011 bs = blk_bs(blk);
3013 if (bdrv_op_is_blocked(bs, BLOCK_OP_TYPE_STREAM, errp)) {
3014 goto out;
3017 if (has_base) {
3018 base_bs = bdrv_find_backing_image(bs, base);
3019 if (base_bs == NULL) {
3020 error_setg(errp, QERR_BASE_NOT_FOUND, base);
3021 goto out;
3023 assert(bdrv_get_aio_context(base_bs) == aio_context);
3024 base_name = base;
3027 /* if we are streaming the entire chain, the result will have no backing
3028 * file, and specifying one is therefore an error */
3029 if (base_bs == NULL && has_backing_file) {
3030 error_setg(errp, "backing file specified, but streaming the "
3031 "entire chain");
3032 goto out;
3035 /* backing_file string overrides base bs filename */
3036 base_name = has_backing_file ? backing_file : base_name;
3038 stream_start(has_job_id ? job_id : NULL, bs, base_bs, base_name,
3039 has_speed ? speed : 0, on_error, block_job_cb, bs, &local_err);
3040 if (local_err) {
3041 error_propagate(errp, local_err);
3042 goto out;
3045 trace_qmp_block_stream(bs, bs->job);
3047 out:
3048 aio_context_release(aio_context);
3051 void qmp_block_commit(bool has_job_id, const char *job_id, const char *device,
3052 bool has_base, const char *base,
3053 bool has_top, const char *top,
3054 bool has_backing_file, const char *backing_file,
3055 bool has_speed, int64_t speed,
3056 Error **errp)
3058 BlockBackend *blk;
3059 BlockDriverState *bs;
3060 BlockDriverState *base_bs, *top_bs;
3061 AioContext *aio_context;
3062 Error *local_err = NULL;
3063 /* This will be part of the QMP command, if/when the
3064 * BlockdevOnError change for blkmirror makes it in
3066 BlockdevOnError on_error = BLOCKDEV_ON_ERROR_REPORT;
3068 if (!has_speed) {
3069 speed = 0;
3072 /* Important Note:
3073 * libvirt relies on the DeviceNotFound error class in order to probe for
3074 * live commit feature versions; for this to work, we must make sure to
3075 * perform the device lookup before any generic errors that may occur in a
3076 * scenario in which all optional arguments are omitted. */
3077 blk = blk_by_name(device);
3078 if (!blk) {
3079 error_set(errp, ERROR_CLASS_DEVICE_NOT_FOUND,
3080 "Device '%s' not found", device);
3081 return;
3084 aio_context = blk_get_aio_context(blk);
3085 aio_context_acquire(aio_context);
3087 if (!blk_is_available(blk)) {
3088 error_setg(errp, "Device '%s' has no medium", device);
3089 goto out;
3091 bs = blk_bs(blk);
3093 if (bdrv_op_is_blocked(bs, BLOCK_OP_TYPE_COMMIT_SOURCE, errp)) {
3094 goto out;
3097 /* default top_bs is the active layer */
3098 top_bs = bs;
3100 if (has_top && top) {
3101 if (strcmp(bs->filename, top) != 0) {
3102 top_bs = bdrv_find_backing_image(bs, top);
3106 if (top_bs == NULL) {
3107 error_setg(errp, "Top image file %s not found", top ? top : "NULL");
3108 goto out;
3111 assert(bdrv_get_aio_context(top_bs) == aio_context);
3113 if (has_base && base) {
3114 base_bs = bdrv_find_backing_image(top_bs, base);
3115 } else {
3116 base_bs = bdrv_find_base(top_bs);
3119 if (base_bs == NULL) {
3120 error_setg(errp, QERR_BASE_NOT_FOUND, base ? base : "NULL");
3121 goto out;
3124 assert(bdrv_get_aio_context(base_bs) == aio_context);
3126 if (bdrv_op_is_blocked(base_bs, BLOCK_OP_TYPE_COMMIT_TARGET, errp)) {
3127 goto out;
3130 /* Do not allow attempts to commit an image into itself */
3131 if (top_bs == base_bs) {
3132 error_setg(errp, "cannot commit an image into itself");
3133 goto out;
3136 if (top_bs == bs) {
3137 if (has_backing_file) {
3138 error_setg(errp, "'backing-file' specified,"
3139 " but 'top' is the active layer");
3140 goto out;
3142 commit_active_start(has_job_id ? job_id : NULL, bs, base_bs, speed,
3143 on_error, block_job_cb, bs, &local_err);
3144 } else {
3145 commit_start(has_job_id ? job_id : NULL, bs, base_bs, top_bs, speed,
3146 on_error, block_job_cb, bs,
3147 has_backing_file ? backing_file : NULL, &local_err);
3149 if (local_err != NULL) {
3150 error_propagate(errp, local_err);
3151 goto out;
3154 out:
3155 aio_context_release(aio_context);
3158 static void do_drive_backup(const char *job_id, const char *device,
3159 const char *target, bool has_format,
3160 const char *format, enum MirrorSyncMode sync,
3161 bool has_mode, enum NewImageMode mode,
3162 bool has_speed, int64_t speed,
3163 bool has_bitmap, const char *bitmap,
3164 bool has_on_source_error,
3165 BlockdevOnError on_source_error,
3166 bool has_on_target_error,
3167 BlockdevOnError on_target_error,
3168 BlockJobTxn *txn, Error **errp)
3170 BlockBackend *blk;
3171 BlockDriverState *bs;
3172 BlockDriverState *target_bs;
3173 BlockDriverState *source = NULL;
3174 BdrvDirtyBitmap *bmap = NULL;
3175 AioContext *aio_context;
3176 QDict *options = NULL;
3177 Error *local_err = NULL;
3178 int flags;
3179 int64_t size;
3181 if (!has_speed) {
3182 speed = 0;
3184 if (!has_on_source_error) {
3185 on_source_error = BLOCKDEV_ON_ERROR_REPORT;
3187 if (!has_on_target_error) {
3188 on_target_error = BLOCKDEV_ON_ERROR_REPORT;
3190 if (!has_mode) {
3191 mode = NEW_IMAGE_MODE_ABSOLUTE_PATHS;
3194 blk = blk_by_name(device);
3195 if (!blk) {
3196 error_set(errp, ERROR_CLASS_DEVICE_NOT_FOUND,
3197 "Device '%s' not found", device);
3198 return;
3201 aio_context = blk_get_aio_context(blk);
3202 aio_context_acquire(aio_context);
3204 /* Although backup_run has this check too, we need to use bs->drv below, so
3205 * do an early check redundantly. */
3206 if (!blk_is_available(blk)) {
3207 error_setg(errp, QERR_DEVICE_HAS_NO_MEDIUM, device);
3208 goto out;
3210 bs = blk_bs(blk);
3212 if (!has_format) {
3213 format = mode == NEW_IMAGE_MODE_EXISTING ? NULL : bs->drv->format_name;
3216 /* Early check to avoid creating target */
3217 if (bdrv_op_is_blocked(bs, BLOCK_OP_TYPE_BACKUP_SOURCE, errp)) {
3218 goto out;
3221 flags = bs->open_flags | BDRV_O_RDWR;
3223 /* See if we have a backing HD we can use to create our new image
3224 * on top of. */
3225 if (sync == MIRROR_SYNC_MODE_TOP) {
3226 source = backing_bs(bs);
3227 if (!source) {
3228 sync = MIRROR_SYNC_MODE_FULL;
3231 if (sync == MIRROR_SYNC_MODE_NONE) {
3232 source = bs;
3235 size = bdrv_getlength(bs);
3236 if (size < 0) {
3237 error_setg_errno(errp, -size, "bdrv_getlength failed");
3238 goto out;
3241 if (mode != NEW_IMAGE_MODE_EXISTING) {
3242 assert(format);
3243 if (source) {
3244 bdrv_img_create(target, format, source->filename,
3245 source->drv->format_name, NULL,
3246 size, flags, &local_err, false);
3247 } else {
3248 bdrv_img_create(target, format, NULL, NULL, NULL,
3249 size, flags, &local_err, false);
3253 if (local_err) {
3254 error_propagate(errp, local_err);
3255 goto out;
3258 if (format) {
3259 options = qdict_new();
3260 qdict_put(options, "driver", qstring_from_str(format));
3263 target_bs = bdrv_open(target, NULL, options, flags, errp);
3264 if (!target_bs) {
3265 goto out;
3268 bdrv_set_aio_context(target_bs, aio_context);
3270 if (has_bitmap) {
3271 bmap = bdrv_find_dirty_bitmap(bs, bitmap);
3272 if (!bmap) {
3273 error_setg(errp, "Bitmap '%s' could not be found", bitmap);
3274 bdrv_unref(target_bs);
3275 goto out;
3279 backup_start(job_id, bs, target_bs, speed, sync, bmap,
3280 on_source_error, on_target_error,
3281 block_job_cb, bs, txn, &local_err);
3282 bdrv_unref(target_bs);
3283 if (local_err != NULL) {
3284 error_propagate(errp, local_err);
3285 goto out;
3288 out:
3289 aio_context_release(aio_context);
3292 void qmp_drive_backup(bool has_job_id, const char *job_id,
3293 const char *device, const char *target,
3294 bool has_format, const char *format,
3295 enum MirrorSyncMode sync,
3296 bool has_mode, enum NewImageMode mode,
3297 bool has_speed, int64_t speed,
3298 bool has_bitmap, const char *bitmap,
3299 bool has_on_source_error, BlockdevOnError on_source_error,
3300 bool has_on_target_error, BlockdevOnError on_target_error,
3301 Error **errp)
3303 return do_drive_backup(has_job_id ? job_id : NULL, device, target,
3304 has_format, format, sync,
3305 has_mode, mode, has_speed, speed,
3306 has_bitmap, bitmap,
3307 has_on_source_error, on_source_error,
3308 has_on_target_error, on_target_error,
3309 NULL, errp);
3312 BlockDeviceInfoList *qmp_query_named_block_nodes(Error **errp)
3314 return bdrv_named_nodes_list(errp);
3317 void do_blockdev_backup(const char *job_id, const char *device,
3318 const char *target, enum MirrorSyncMode sync,
3319 bool has_speed, int64_t speed,
3320 bool has_on_source_error,
3321 BlockdevOnError on_source_error,
3322 bool has_on_target_error,
3323 BlockdevOnError on_target_error,
3324 BlockJobTxn *txn, Error **errp)
3326 BlockBackend *blk;
3327 BlockDriverState *bs;
3328 BlockDriverState *target_bs;
3329 Error *local_err = NULL;
3330 AioContext *aio_context;
3332 if (!has_speed) {
3333 speed = 0;
3335 if (!has_on_source_error) {
3336 on_source_error = BLOCKDEV_ON_ERROR_REPORT;
3338 if (!has_on_target_error) {
3339 on_target_error = BLOCKDEV_ON_ERROR_REPORT;
3342 blk = blk_by_name(device);
3343 if (!blk) {
3344 error_setg(errp, "Device '%s' not found", device);
3345 return;
3348 aio_context = blk_get_aio_context(blk);
3349 aio_context_acquire(aio_context);
3351 if (!blk_is_available(blk)) {
3352 error_setg(errp, "Device '%s' has no medium", device);
3353 goto out;
3355 bs = blk_bs(blk);
3357 target_bs = bdrv_lookup_bs(target, target, errp);
3358 if (!target_bs) {
3359 goto out;
3362 if (bdrv_get_aio_context(target_bs) != aio_context) {
3363 if (!bdrv_has_blk(target_bs)) {
3364 /* The target BDS is not attached, we can safely move it to another
3365 * AioContext. */
3366 bdrv_set_aio_context(target_bs, aio_context);
3367 } else {
3368 error_setg(errp, "Target is attached to a different thread from "
3369 "source.");
3370 goto out;
3373 backup_start(job_id, bs, target_bs, speed, sync, NULL, on_source_error,
3374 on_target_error, block_job_cb, bs, txn, &local_err);
3375 if (local_err != NULL) {
3376 error_propagate(errp, local_err);
3378 out:
3379 aio_context_release(aio_context);
3382 void qmp_blockdev_backup(bool has_job_id, const char *job_id,
3383 const char *device, const char *target,
3384 enum MirrorSyncMode sync,
3385 bool has_speed, int64_t speed,
3386 bool has_on_source_error,
3387 BlockdevOnError on_source_error,
3388 bool has_on_target_error,
3389 BlockdevOnError on_target_error,
3390 Error **errp)
3392 do_blockdev_backup(has_job_id ? job_id : NULL, device, target,
3393 sync, has_speed, speed,
3394 has_on_source_error, on_source_error,
3395 has_on_target_error, on_target_error,
3396 NULL, errp);
3399 /* Parameter check and block job starting for drive mirroring.
3400 * Caller should hold @device and @target's aio context (must be the same).
3402 static void blockdev_mirror_common(const char *job_id, BlockDriverState *bs,
3403 BlockDriverState *target,
3404 bool has_replaces, const char *replaces,
3405 enum MirrorSyncMode sync,
3406 BlockMirrorBackingMode backing_mode,
3407 bool has_speed, int64_t speed,
3408 bool has_granularity, uint32_t granularity,
3409 bool has_buf_size, int64_t buf_size,
3410 bool has_on_source_error,
3411 BlockdevOnError on_source_error,
3412 bool has_on_target_error,
3413 BlockdevOnError on_target_error,
3414 bool has_unmap, bool unmap,
3415 Error **errp)
3418 if (!has_speed) {
3419 speed = 0;
3421 if (!has_on_source_error) {
3422 on_source_error = BLOCKDEV_ON_ERROR_REPORT;
3424 if (!has_on_target_error) {
3425 on_target_error = BLOCKDEV_ON_ERROR_REPORT;
3427 if (!has_granularity) {
3428 granularity = 0;
3430 if (!has_buf_size) {
3431 buf_size = 0;
3433 if (!has_unmap) {
3434 unmap = true;
3437 if (granularity != 0 && (granularity < 512 || granularity > 1048576 * 64)) {
3438 error_setg(errp, QERR_INVALID_PARAMETER_VALUE, "granularity",
3439 "a value in range [512B, 64MB]");
3440 return;
3442 if (granularity & (granularity - 1)) {
3443 error_setg(errp, QERR_INVALID_PARAMETER_VALUE, "granularity",
3444 "power of 2");
3445 return;
3448 if (bdrv_op_is_blocked(bs, BLOCK_OP_TYPE_MIRROR_SOURCE, errp)) {
3449 return;
3451 if (bdrv_op_is_blocked(target, BLOCK_OP_TYPE_MIRROR_TARGET, errp)) {
3452 return;
3455 if (!bs->backing && sync == MIRROR_SYNC_MODE_TOP) {
3456 sync = MIRROR_SYNC_MODE_FULL;
3459 /* pass the node name to replace to mirror start since it's loose coupling
3460 * and will allow to check whether the node still exist at mirror completion
3462 mirror_start(job_id, bs, target,
3463 has_replaces ? replaces : NULL,
3464 speed, granularity, buf_size, sync, backing_mode,
3465 on_source_error, on_target_error, unmap,
3466 block_job_cb, bs, errp);
3469 void qmp_drive_mirror(DriveMirror *arg, Error **errp)
3471 BlockDriverState *bs;
3472 BlockBackend *blk;
3473 BlockDriverState *source, *target_bs;
3474 AioContext *aio_context;
3475 BlockMirrorBackingMode backing_mode;
3476 Error *local_err = NULL;
3477 QDict *options = NULL;
3478 int flags;
3479 int64_t size;
3480 const char *format = arg->format;
3482 blk = blk_by_name(arg->device);
3483 if (!blk) {
3484 error_set(errp, ERROR_CLASS_DEVICE_NOT_FOUND,
3485 "Device '%s' not found", arg->device);
3486 return;
3489 aio_context = blk_get_aio_context(blk);
3490 aio_context_acquire(aio_context);
3492 if (!blk_is_available(blk)) {
3493 error_setg(errp, QERR_DEVICE_HAS_NO_MEDIUM, arg->device);
3494 goto out;
3496 bs = blk_bs(blk);
3497 if (!arg->has_mode) {
3498 arg->mode = NEW_IMAGE_MODE_ABSOLUTE_PATHS;
3501 if (!arg->has_format) {
3502 format = (arg->mode == NEW_IMAGE_MODE_EXISTING
3503 ? NULL : bs->drv->format_name);
3506 flags = bs->open_flags | BDRV_O_RDWR;
3507 source = backing_bs(bs);
3508 if (!source && arg->sync == MIRROR_SYNC_MODE_TOP) {
3509 arg->sync = MIRROR_SYNC_MODE_FULL;
3511 if (arg->sync == MIRROR_SYNC_MODE_NONE) {
3512 source = bs;
3515 size = bdrv_getlength(bs);
3516 if (size < 0) {
3517 error_setg_errno(errp, -size, "bdrv_getlength failed");
3518 goto out;
3521 if (arg->has_replaces) {
3522 BlockDriverState *to_replace_bs;
3523 AioContext *replace_aio_context;
3524 int64_t replace_size;
3526 if (!arg->has_node_name) {
3527 error_setg(errp, "a node-name must be provided when replacing a"
3528 " named node of the graph");
3529 goto out;
3532 to_replace_bs = check_to_replace_node(bs, arg->replaces, &local_err);
3534 if (!to_replace_bs) {
3535 error_propagate(errp, local_err);
3536 goto out;
3539 replace_aio_context = bdrv_get_aio_context(to_replace_bs);
3540 aio_context_acquire(replace_aio_context);
3541 replace_size = bdrv_getlength(to_replace_bs);
3542 aio_context_release(replace_aio_context);
3544 if (size != replace_size) {
3545 error_setg(errp, "cannot replace image with a mirror image of "
3546 "different size");
3547 goto out;
3551 if (arg->mode == NEW_IMAGE_MODE_ABSOLUTE_PATHS) {
3552 backing_mode = MIRROR_SOURCE_BACKING_CHAIN;
3553 } else {
3554 backing_mode = MIRROR_OPEN_BACKING_CHAIN;
3557 if ((arg->sync == MIRROR_SYNC_MODE_FULL || !source)
3558 && arg->mode != NEW_IMAGE_MODE_EXISTING)
3560 /* create new image w/o backing file */
3561 assert(format);
3562 bdrv_img_create(arg->target, format,
3563 NULL, NULL, NULL, size, flags, &local_err, false);
3564 } else {
3565 switch (arg->mode) {
3566 case NEW_IMAGE_MODE_EXISTING:
3567 break;
3568 case NEW_IMAGE_MODE_ABSOLUTE_PATHS:
3569 /* create new image with backing file */
3570 bdrv_img_create(arg->target, format,
3571 source->filename,
3572 source->drv->format_name,
3573 NULL, size, flags, &local_err, false);
3574 break;
3575 default:
3576 abort();
3580 if (local_err) {
3581 error_propagate(errp, local_err);
3582 goto out;
3585 options = qdict_new();
3586 if (arg->has_node_name) {
3587 qdict_put(options, "node-name", qstring_from_str(arg->node_name));
3589 if (format) {
3590 qdict_put(options, "driver", qstring_from_str(format));
3593 /* Mirroring takes care of copy-on-write using the source's backing
3594 * file.
3596 target_bs = bdrv_open(arg->target, NULL, options,
3597 flags | BDRV_O_NO_BACKING, errp);
3598 if (!target_bs) {
3599 goto out;
3602 bdrv_set_aio_context(target_bs, aio_context);
3604 blockdev_mirror_common(arg->has_job_id ? arg->job_id : NULL, bs, target_bs,
3605 arg->has_replaces, arg->replaces, arg->sync,
3606 backing_mode, arg->has_speed, arg->speed,
3607 arg->has_granularity, arg->granularity,
3608 arg->has_buf_size, arg->buf_size,
3609 arg->has_on_source_error, arg->on_source_error,
3610 arg->has_on_target_error, arg->on_target_error,
3611 arg->has_unmap, arg->unmap,
3612 &local_err);
3613 bdrv_unref(target_bs);
3614 error_propagate(errp, local_err);
3615 out:
3616 aio_context_release(aio_context);
3619 void qmp_blockdev_mirror(bool has_job_id, const char *job_id,
3620 const char *device, const char *target,
3621 bool has_replaces, const char *replaces,
3622 MirrorSyncMode sync,
3623 bool has_speed, int64_t speed,
3624 bool has_granularity, uint32_t granularity,
3625 bool has_buf_size, int64_t buf_size,
3626 bool has_on_source_error,
3627 BlockdevOnError on_source_error,
3628 bool has_on_target_error,
3629 BlockdevOnError on_target_error,
3630 Error **errp)
3632 BlockDriverState *bs;
3633 BlockBackend *blk;
3634 BlockDriverState *target_bs;
3635 AioContext *aio_context;
3636 BlockMirrorBackingMode backing_mode = MIRROR_LEAVE_BACKING_CHAIN;
3637 Error *local_err = NULL;
3639 blk = blk_by_name(device);
3640 if (!blk) {
3641 error_setg(errp, "Device '%s' not found", device);
3642 return;
3644 bs = blk_bs(blk);
3646 if (!bs) {
3647 error_setg(errp, "Device '%s' has no media", device);
3648 return;
3651 target_bs = bdrv_lookup_bs(target, target, errp);
3652 if (!target_bs) {
3653 return;
3656 aio_context = bdrv_get_aio_context(bs);
3657 aio_context_acquire(aio_context);
3659 bdrv_set_aio_context(target_bs, aio_context);
3661 blockdev_mirror_common(has_job_id ? job_id : NULL, bs, target_bs,
3662 has_replaces, replaces, sync, backing_mode,
3663 has_speed, speed,
3664 has_granularity, granularity,
3665 has_buf_size, buf_size,
3666 has_on_source_error, on_source_error,
3667 has_on_target_error, on_target_error,
3668 true, true,
3669 &local_err);
3670 error_propagate(errp, local_err);
3672 aio_context_release(aio_context);
3675 /* Get a block job using its ID and acquire its AioContext */
3676 static BlockJob *find_block_job(const char *id, AioContext **aio_context,
3677 Error **errp)
3679 BlockJob *job;
3681 assert(id != NULL);
3683 *aio_context = NULL;
3685 job = block_job_get(id);
3687 if (!job) {
3688 error_set(errp, ERROR_CLASS_DEVICE_NOT_ACTIVE,
3689 "Block job '%s' not found", id);
3690 return NULL;
3693 *aio_context = blk_get_aio_context(job->blk);
3694 aio_context_acquire(*aio_context);
3696 return job;
3699 void qmp_block_job_set_speed(const char *device, int64_t speed, Error **errp)
3701 AioContext *aio_context;
3702 BlockJob *job = find_block_job(device, &aio_context, errp);
3704 if (!job) {
3705 return;
3708 block_job_set_speed(job, speed, errp);
3709 aio_context_release(aio_context);
3712 void qmp_block_job_cancel(const char *device,
3713 bool has_force, bool force, Error **errp)
3715 AioContext *aio_context;
3716 BlockJob *job = find_block_job(device, &aio_context, errp);
3718 if (!job) {
3719 return;
3722 if (!has_force) {
3723 force = false;
3726 if (job->user_paused && !force) {
3727 error_setg(errp, "The block job for device '%s' is currently paused",
3728 device);
3729 goto out;
3732 trace_qmp_block_job_cancel(job);
3733 block_job_cancel(job);
3734 out:
3735 aio_context_release(aio_context);
3738 void qmp_block_job_pause(const char *device, Error **errp)
3740 AioContext *aio_context;
3741 BlockJob *job = find_block_job(device, &aio_context, errp);
3743 if (!job || job->user_paused) {
3744 return;
3747 job->user_paused = true;
3748 trace_qmp_block_job_pause(job);
3749 block_job_pause(job);
3750 aio_context_release(aio_context);
3753 void qmp_block_job_resume(const char *device, Error **errp)
3755 AioContext *aio_context;
3756 BlockJob *job = find_block_job(device, &aio_context, errp);
3758 if (!job || !job->user_paused) {
3759 return;
3762 job->user_paused = false;
3763 trace_qmp_block_job_resume(job);
3764 block_job_iostatus_reset(job);
3765 block_job_resume(job);
3766 aio_context_release(aio_context);
3769 void qmp_block_job_complete(const char *device, Error **errp)
3771 AioContext *aio_context;
3772 BlockJob *job = find_block_job(device, &aio_context, errp);
3774 if (!job) {
3775 return;
3778 trace_qmp_block_job_complete(job);
3779 block_job_complete(job, errp);
3780 aio_context_release(aio_context);
3783 void qmp_change_backing_file(const char *device,
3784 const char *image_node_name,
3785 const char *backing_file,
3786 Error **errp)
3788 BlockBackend *blk;
3789 BlockDriverState *bs = NULL;
3790 AioContext *aio_context;
3791 BlockDriverState *image_bs = NULL;
3792 Error *local_err = NULL;
3793 bool ro;
3794 int open_flags;
3795 int ret;
3797 blk = blk_by_name(device);
3798 if (!blk) {
3799 error_set(errp, ERROR_CLASS_DEVICE_NOT_FOUND,
3800 "Device '%s' not found", device);
3801 return;
3804 aio_context = blk_get_aio_context(blk);
3805 aio_context_acquire(aio_context);
3807 if (!blk_is_available(blk)) {
3808 error_setg(errp, "Device '%s' has no medium", device);
3809 goto out;
3811 bs = blk_bs(blk);
3813 image_bs = bdrv_lookup_bs(NULL, image_node_name, &local_err);
3814 if (local_err) {
3815 error_propagate(errp, local_err);
3816 goto out;
3819 if (!image_bs) {
3820 error_setg(errp, "image file not found");
3821 goto out;
3824 if (bdrv_find_base(image_bs) == image_bs) {
3825 error_setg(errp, "not allowing backing file change on an image "
3826 "without a backing file");
3827 goto out;
3830 /* even though we are not necessarily operating on bs, we need it to
3831 * determine if block ops are currently prohibited on the chain */
3832 if (bdrv_op_is_blocked(bs, BLOCK_OP_TYPE_CHANGE, errp)) {
3833 goto out;
3836 /* final sanity check */
3837 if (!bdrv_chain_contains(bs, image_bs)) {
3838 error_setg(errp, "'%s' and image file are not in the same chain",
3839 device);
3840 goto out;
3843 /* if not r/w, reopen to make r/w */
3844 open_flags = image_bs->open_flags;
3845 ro = bdrv_is_read_only(image_bs);
3847 if (ro) {
3848 bdrv_reopen(image_bs, open_flags | BDRV_O_RDWR, &local_err);
3849 if (local_err) {
3850 error_propagate(errp, local_err);
3851 goto out;
3855 ret = bdrv_change_backing_file(image_bs, backing_file,
3856 image_bs->drv ? image_bs->drv->format_name : "");
3858 if (ret < 0) {
3859 error_setg_errno(errp, -ret, "Could not change backing file to '%s'",
3860 backing_file);
3861 /* don't exit here, so we can try to restore open flags if
3862 * appropriate */
3865 if (ro) {
3866 bdrv_reopen(image_bs, open_flags, &local_err);
3867 error_propagate(errp, local_err);
3870 out:
3871 aio_context_release(aio_context);
3874 void hmp_drive_add_node(Monitor *mon, const char *optstr)
3876 QemuOpts *opts;
3877 QDict *qdict;
3878 Error *local_err = NULL;
3880 opts = qemu_opts_parse_noisily(&qemu_drive_opts, optstr, false);
3881 if (!opts) {
3882 return;
3885 qdict = qemu_opts_to_qdict(opts, NULL);
3887 if (!qdict_get_try_str(qdict, "node-name")) {
3888 QDECREF(qdict);
3889 error_report("'node-name' needs to be specified");
3890 goto out;
3893 BlockDriverState *bs = bds_tree_init(qdict, &local_err);
3894 if (!bs) {
3895 error_report_err(local_err);
3896 goto out;
3899 QTAILQ_INSERT_TAIL(&monitor_bdrv_states, bs, monitor_list);
3901 out:
3902 qemu_opts_del(opts);
3905 void qmp_blockdev_add(BlockdevOptions *options, Error **errp)
3907 BlockDriverState *bs;
3908 BlockBackend *blk = NULL;
3909 QObject *obj;
3910 Visitor *v = qmp_output_visitor_new(&obj);
3911 QDict *qdict;
3912 Error *local_err = NULL;
3914 /* TODO Sort it out in raw-posix and drive_new(): Reject aio=native with
3915 * cache.direct=false instead of silently switching to aio=threads, except
3916 * when called from drive_new().
3918 * For now, simply forbidding the combination for all drivers will do. */
3919 if (options->has_aio && options->aio == BLOCKDEV_AIO_OPTIONS_NATIVE) {
3920 bool direct = options->has_cache &&
3921 options->cache->has_direct &&
3922 options->cache->direct;
3923 if (!direct) {
3924 error_setg(errp, "aio=native requires cache.direct=true");
3925 goto fail;
3929 visit_type_BlockdevOptions(v, NULL, &options, &local_err);
3930 if (local_err) {
3931 error_propagate(errp, local_err);
3932 goto fail;
3935 visit_complete(v, &obj);
3936 qdict = qobject_to_qdict(obj);
3938 qdict_flatten(qdict);
3940 if (options->has_id) {
3941 blk = blockdev_init(NULL, qdict, &local_err);
3942 if (local_err) {
3943 error_propagate(errp, local_err);
3944 goto fail;
3947 bs = blk_bs(blk);
3948 } else {
3949 if (!qdict_get_try_str(qdict, "node-name")) {
3950 error_setg(errp, "'id' and/or 'node-name' need to be specified for "
3951 "the root node");
3952 goto fail;
3955 bs = bds_tree_init(qdict, errp);
3956 if (!bs) {
3957 goto fail;
3960 QTAILQ_INSERT_TAIL(&monitor_bdrv_states, bs, monitor_list);
3963 if (bs && bdrv_key_required(bs)) {
3964 if (blk) {
3965 monitor_remove_blk(blk);
3966 blk_unref(blk);
3967 } else {
3968 QTAILQ_REMOVE(&monitor_bdrv_states, bs, monitor_list);
3969 bdrv_unref(bs);
3971 error_setg(errp, "blockdev-add doesn't support encrypted devices");
3972 goto fail;
3975 fail:
3976 visit_free(v);
3979 void qmp_x_blockdev_del(bool has_id, const char *id,
3980 bool has_node_name, const char *node_name, Error **errp)
3982 AioContext *aio_context;
3983 BlockBackend *blk;
3984 BlockDriverState *bs;
3986 if (has_id && has_node_name) {
3987 error_setg(errp, "Only one of id and node-name must be specified");
3988 return;
3989 } else if (!has_id && !has_node_name) {
3990 error_setg(errp, "No block device specified");
3991 return;
3994 if (has_id) {
3995 /* blk_by_name() never returns a BB that is not owned by the monitor */
3996 blk = blk_by_name(id);
3997 if (!blk) {
3998 error_setg(errp, "Cannot find block backend %s", id);
3999 return;
4001 if (blk_legacy_dinfo(blk)) {
4002 error_setg(errp, "Deleting block backend added with drive-add"
4003 " is not supported");
4004 return;
4006 if (blk_get_refcnt(blk) > 1) {
4007 error_setg(errp, "Block backend %s is in use", id);
4008 return;
4010 bs = blk_bs(blk);
4011 aio_context = blk_get_aio_context(blk);
4012 } else {
4013 blk = NULL;
4014 bs = bdrv_find_node(node_name);
4015 if (!bs) {
4016 error_setg(errp, "Cannot find node %s", node_name);
4017 return;
4019 if (bdrv_has_blk(bs)) {
4020 error_setg(errp, "Node %s is in use by %s",
4021 node_name, bdrv_get_parent_name(bs));
4022 return;
4024 aio_context = bdrv_get_aio_context(bs);
4027 aio_context_acquire(aio_context);
4029 if (bs) {
4030 if (bdrv_op_is_blocked(bs, BLOCK_OP_TYPE_DRIVE_DEL, errp)) {
4031 goto out;
4034 if (!blk && !bs->monitor_list.tqe_prev) {
4035 error_setg(errp, "Node %s is not owned by the monitor",
4036 bs->node_name);
4037 goto out;
4040 if (bs->refcnt > 1) {
4041 error_setg(errp, "Block device %s is in use",
4042 bdrv_get_device_or_node_name(bs));
4043 goto out;
4047 if (blk) {
4048 monitor_remove_blk(blk);
4049 blk_unref(blk);
4050 } else {
4051 QTAILQ_REMOVE(&monitor_bdrv_states, bs, monitor_list);
4052 bdrv_unref(bs);
4055 out:
4056 aio_context_release(aio_context);
4059 static BdrvChild *bdrv_find_child(BlockDriverState *parent_bs,
4060 const char *child_name)
4062 BdrvChild *child;
4064 QLIST_FOREACH(child, &parent_bs->children, next) {
4065 if (strcmp(child->name, child_name) == 0) {
4066 return child;
4070 return NULL;
4073 void qmp_x_blockdev_change(const char *parent, bool has_child,
4074 const char *child, bool has_node,
4075 const char *node, Error **errp)
4077 BlockDriverState *parent_bs, *new_bs = NULL;
4078 BdrvChild *p_child;
4080 parent_bs = bdrv_lookup_bs(parent, parent, errp);
4081 if (!parent_bs) {
4082 return;
4085 if (has_child == has_node) {
4086 if (has_child) {
4087 error_setg(errp, "The parameters child and node are in conflict");
4088 } else {
4089 error_setg(errp, "Either child or node must be specified");
4091 return;
4094 if (has_child) {
4095 p_child = bdrv_find_child(parent_bs, child);
4096 if (!p_child) {
4097 error_setg(errp, "Node '%s' does not have child '%s'",
4098 parent, child);
4099 return;
4101 bdrv_del_child(parent_bs, p_child, errp);
4104 if (has_node) {
4105 new_bs = bdrv_find_node(node);
4106 if (!new_bs) {
4107 error_setg(errp, "Node '%s' not found", node);
4108 return;
4110 bdrv_add_child(parent_bs, new_bs, errp);
4114 BlockJobInfoList *qmp_query_block_jobs(Error **errp)
4116 BlockJobInfoList *head = NULL, **p_next = &head;
4117 BlockJob *job;
4119 for (job = block_job_next(NULL); job; job = block_job_next(job)) {
4120 BlockJobInfoList *elem = g_new0(BlockJobInfoList, 1);
4121 AioContext *aio_context = blk_get_aio_context(job->blk);
4123 aio_context_acquire(aio_context);
4124 elem->value = block_job_query(job);
4125 aio_context_release(aio_context);
4127 *p_next = elem;
4128 p_next = &elem->next;
4131 return head;
4134 QemuOptsList qemu_common_drive_opts = {
4135 .name = "drive",
4136 .head = QTAILQ_HEAD_INITIALIZER(qemu_common_drive_opts.head),
4137 .desc = {
4139 .name = "snapshot",
4140 .type = QEMU_OPT_BOOL,
4141 .help = "enable/disable snapshot mode",
4143 .name = "discard",
4144 .type = QEMU_OPT_STRING,
4145 .help = "discard operation (ignore/off, unmap/on)",
4147 .name = "aio",
4148 .type = QEMU_OPT_STRING,
4149 .help = "host AIO implementation (threads, native)",
4151 .name = BDRV_OPT_CACHE_WB,
4152 .type = QEMU_OPT_BOOL,
4153 .help = "Enable writeback mode",
4155 .name = "format",
4156 .type = QEMU_OPT_STRING,
4157 .help = "disk format (raw, qcow2, ...)",
4159 .name = "rerror",
4160 .type = QEMU_OPT_STRING,
4161 .help = "read error action",
4163 .name = "werror",
4164 .type = QEMU_OPT_STRING,
4165 .help = "write error action",
4167 .name = "read-only",
4168 .type = QEMU_OPT_BOOL,
4169 .help = "open drive file as read-only",
4171 .name = "throttling.iops-total",
4172 .type = QEMU_OPT_NUMBER,
4173 .help = "limit total I/O operations per second",
4175 .name = "throttling.iops-read",
4176 .type = QEMU_OPT_NUMBER,
4177 .help = "limit read operations per second",
4179 .name = "throttling.iops-write",
4180 .type = QEMU_OPT_NUMBER,
4181 .help = "limit write operations per second",
4183 .name = "throttling.bps-total",
4184 .type = QEMU_OPT_NUMBER,
4185 .help = "limit total bytes per second",
4187 .name = "throttling.bps-read",
4188 .type = QEMU_OPT_NUMBER,
4189 .help = "limit read bytes per second",
4191 .name = "throttling.bps-write",
4192 .type = QEMU_OPT_NUMBER,
4193 .help = "limit write bytes per second",
4195 .name = "throttling.iops-total-max",
4196 .type = QEMU_OPT_NUMBER,
4197 .help = "I/O operations burst",
4199 .name = "throttling.iops-read-max",
4200 .type = QEMU_OPT_NUMBER,
4201 .help = "I/O operations read burst",
4203 .name = "throttling.iops-write-max",
4204 .type = QEMU_OPT_NUMBER,
4205 .help = "I/O operations write burst",
4207 .name = "throttling.bps-total-max",
4208 .type = QEMU_OPT_NUMBER,
4209 .help = "total bytes burst",
4211 .name = "throttling.bps-read-max",
4212 .type = QEMU_OPT_NUMBER,
4213 .help = "total bytes read burst",
4215 .name = "throttling.bps-write-max",
4216 .type = QEMU_OPT_NUMBER,
4217 .help = "total bytes write burst",
4219 .name = "throttling.iops-total-max-length",
4220 .type = QEMU_OPT_NUMBER,
4221 .help = "length of the iops-total-max burst period, in seconds",
4223 .name = "throttling.iops-read-max-length",
4224 .type = QEMU_OPT_NUMBER,
4225 .help = "length of the iops-read-max burst period, in seconds",
4227 .name = "throttling.iops-write-max-length",
4228 .type = QEMU_OPT_NUMBER,
4229 .help = "length of the iops-write-max burst period, in seconds",
4231 .name = "throttling.bps-total-max-length",
4232 .type = QEMU_OPT_NUMBER,
4233 .help = "length of the bps-total-max burst period, in seconds",
4235 .name = "throttling.bps-read-max-length",
4236 .type = QEMU_OPT_NUMBER,
4237 .help = "length of the bps-read-max burst period, in seconds",
4239 .name = "throttling.bps-write-max-length",
4240 .type = QEMU_OPT_NUMBER,
4241 .help = "length of the bps-write-max burst period, in seconds",
4243 .name = "throttling.iops-size",
4244 .type = QEMU_OPT_NUMBER,
4245 .help = "when limiting by iops max size of an I/O in bytes",
4247 .name = "throttling.group",
4248 .type = QEMU_OPT_STRING,
4249 .help = "name of the block throttling group",
4251 .name = "copy-on-read",
4252 .type = QEMU_OPT_BOOL,
4253 .help = "copy read data from backing file into image file",
4255 .name = "detect-zeroes",
4256 .type = QEMU_OPT_STRING,
4257 .help = "try to optimize zero writes (off, on, unmap)",
4259 .name = "stats-account-invalid",
4260 .type = QEMU_OPT_BOOL,
4261 .help = "whether to account for invalid I/O operations "
4262 "in the statistics",
4264 .name = "stats-account-failed",
4265 .type = QEMU_OPT_BOOL,
4266 .help = "whether to account for failed I/O operations "
4267 "in the statistics",
4269 { /* end of list */ }
4273 static QemuOptsList qemu_root_bds_opts = {
4274 .name = "root-bds",
4275 .head = QTAILQ_HEAD_INITIALIZER(qemu_root_bds_opts.head),
4276 .desc = {
4278 .name = "discard",
4279 .type = QEMU_OPT_STRING,
4280 .help = "discard operation (ignore/off, unmap/on)",
4282 .name = "aio",
4283 .type = QEMU_OPT_STRING,
4284 .help = "host AIO implementation (threads, native)",
4286 .name = "read-only",
4287 .type = QEMU_OPT_BOOL,
4288 .help = "open drive file as read-only",
4290 .name = "copy-on-read",
4291 .type = QEMU_OPT_BOOL,
4292 .help = "copy read data from backing file into image file",
4294 .name = "detect-zeroes",
4295 .type = QEMU_OPT_STRING,
4296 .help = "try to optimize zero writes (off, on, unmap)",
4298 { /* end of list */ }
4302 QemuOptsList qemu_drive_opts = {
4303 .name = "drive",
4304 .head = QTAILQ_HEAD_INITIALIZER(qemu_drive_opts.head),
4305 .desc = {
4307 * no elements => accept any params
4308 * validation will happen later
4310 { /* end of list */ }