hw/isa: Replace fprintf(stderr, "*\n" with error_report()
[qemu/ar7.git] / blockdev.c
blob29d569a24e1a2145397c269beb15b8cec136052f
1 /*
2 * QEMU host block devices
4 * Copyright (c) 2003-2008 Fabrice Bellard
6 * This work is licensed under the terms of the GNU GPL, version 2 or
7 * later. See the COPYING file in the top-level directory.
9 * This file incorporates work covered by the following copyright and
10 * permission notice:
12 * Copyright (c) 2003-2008 Fabrice Bellard
14 * Permission is hereby granted, free of charge, to any person obtaining a copy
15 * of this software and associated documentation files (the "Software"), to deal
16 * in the Software without restriction, including without limitation the rights
17 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
18 * copies of the Software, and to permit persons to whom the Software is
19 * furnished to do so, subject to the following conditions:
21 * The above copyright notice and this permission notice shall be included in
22 * all copies or substantial portions of the Software.
24 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
25 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
26 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
27 * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
28 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
29 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
30 * THE SOFTWARE.
33 #include "qemu/osdep.h"
34 #include "sysemu/block-backend.h"
35 #include "sysemu/blockdev.h"
36 #include "hw/block/block.h"
37 #include "block/blockjob.h"
38 #include "block/throttle-groups.h"
39 #include "monitor/monitor.h"
40 #include "qemu/error-report.h"
41 #include "qemu/option.h"
42 #include "qemu/config-file.h"
43 #include "qapi/qmp/types.h"
44 #include "qapi-visit.h"
45 #include "qapi/qmp/qerror.h"
46 #include "qapi/qobject-output-visitor.h"
47 #include "sysemu/sysemu.h"
48 #include "sysemu/iothread.h"
49 #include "block/block_int.h"
50 #include "qmp-commands.h"
51 #include "block/trace.h"
52 #include "sysemu/arch_init.h"
53 #include "sysemu/qtest.h"
54 #include "qemu/cutils.h"
55 #include "qemu/help_option.h"
56 #include "qemu/throttle-options.h"
58 static QTAILQ_HEAD(, BlockDriverState) monitor_bdrv_states =
59 QTAILQ_HEAD_INITIALIZER(monitor_bdrv_states);
61 static int do_open_tray(const char *blk_name, const char *qdev_id,
62 bool force, Error **errp);
64 static const char *const if_name[IF_COUNT] = {
65 [IF_NONE] = "none",
66 [IF_IDE] = "ide",
67 [IF_SCSI] = "scsi",
68 [IF_FLOPPY] = "floppy",
69 [IF_PFLASH] = "pflash",
70 [IF_MTD] = "mtd",
71 [IF_SD] = "sd",
72 [IF_VIRTIO] = "virtio",
73 [IF_XEN] = "xen",
76 static int if_max_devs[IF_COUNT] = {
78 * Do not change these numbers! They govern how drive option
79 * index maps to unit and bus. That mapping is ABI.
81 * All controllers used to implement if=T drives need to support
82 * if_max_devs[T] units, for any T with if_max_devs[T] != 0.
83 * Otherwise, some index values map to "impossible" bus, unit
84 * values.
86 * For instance, if you change [IF_SCSI] to 255, -drive
87 * if=scsi,index=12 no longer means bus=1,unit=5, but
88 * bus=0,unit=12. With an lsi53c895a controller (7 units max),
89 * the drive can't be set up. Regression.
91 [IF_IDE] = 2,
92 [IF_SCSI] = 7,
95 /**
96 * Boards may call this to offer board-by-board overrides
97 * of the default, global values.
99 void override_max_devs(BlockInterfaceType type, int max_devs)
101 BlockBackend *blk;
102 DriveInfo *dinfo;
104 if (max_devs <= 0) {
105 return;
108 for (blk = blk_next(NULL); blk; blk = blk_next(blk)) {
109 dinfo = blk_legacy_dinfo(blk);
110 if (dinfo->type == type) {
111 fprintf(stderr, "Cannot override units-per-bus property of"
112 " the %s interface, because a drive of that type has"
113 " already been added.\n", if_name[type]);
114 g_assert_not_reached();
118 if_max_devs[type] = max_devs;
122 * We automatically delete the drive when a device using it gets
123 * unplugged. Questionable feature, but we can't just drop it.
124 * Device models call blockdev_mark_auto_del() to schedule the
125 * automatic deletion, and generic qdev code calls blockdev_auto_del()
126 * when deletion is actually safe.
128 void blockdev_mark_auto_del(BlockBackend *blk)
130 DriveInfo *dinfo = blk_legacy_dinfo(blk);
131 BlockDriverState *bs = blk_bs(blk);
132 AioContext *aio_context;
134 if (!dinfo) {
135 return;
138 if (bs) {
139 aio_context = bdrv_get_aio_context(bs);
140 aio_context_acquire(aio_context);
142 if (bs->job) {
143 block_job_cancel(bs->job);
146 aio_context_release(aio_context);
149 dinfo->auto_del = 1;
152 void blockdev_auto_del(BlockBackend *blk)
154 DriveInfo *dinfo = blk_legacy_dinfo(blk);
156 if (dinfo && dinfo->auto_del) {
157 monitor_remove_blk(blk);
158 blk_unref(blk);
163 * Returns the current mapping of how many units per bus
164 * a particular interface can support.
166 * A positive integer indicates n units per bus.
167 * 0 implies the mapping has not been established.
168 * -1 indicates an invalid BlockInterfaceType was given.
170 int drive_get_max_devs(BlockInterfaceType type)
172 if (type >= IF_IDE && type < IF_COUNT) {
173 return if_max_devs[type];
176 return -1;
179 static int drive_index_to_bus_id(BlockInterfaceType type, int index)
181 int max_devs = if_max_devs[type];
182 return max_devs ? index / max_devs : 0;
185 static int drive_index_to_unit_id(BlockInterfaceType type, int index)
187 int max_devs = if_max_devs[type];
188 return max_devs ? index % max_devs : index;
191 QemuOpts *drive_def(const char *optstr)
193 return qemu_opts_parse_noisily(qemu_find_opts("drive"), optstr, false);
196 QemuOpts *drive_add(BlockInterfaceType type, int index, const char *file,
197 const char *optstr)
199 QemuOpts *opts;
201 opts = drive_def(optstr);
202 if (!opts) {
203 return NULL;
205 if (type != IF_DEFAULT) {
206 qemu_opt_set(opts, "if", if_name[type], &error_abort);
208 if (index >= 0) {
209 qemu_opt_set_number(opts, "index", index, &error_abort);
211 if (file)
212 qemu_opt_set(opts, "file", file, &error_abort);
213 return opts;
216 DriveInfo *drive_get(BlockInterfaceType type, int bus, int unit)
218 BlockBackend *blk;
219 DriveInfo *dinfo;
221 for (blk = blk_next(NULL); blk; blk = blk_next(blk)) {
222 dinfo = blk_legacy_dinfo(blk);
223 if (dinfo && dinfo->type == type
224 && dinfo->bus == bus && dinfo->unit == unit) {
225 return dinfo;
229 return NULL;
232 void drive_check_orphaned(void)
234 BlockBackend *blk;
235 DriveInfo *dinfo;
236 Location loc;
237 bool orphans = false;
239 for (blk = blk_next(NULL); blk; blk = blk_next(blk)) {
240 dinfo = blk_legacy_dinfo(blk);
241 if (!blk_get_attached_dev(blk) && !dinfo->is_default &&
242 dinfo->type != IF_NONE) {
243 loc_push_none(&loc);
244 qemu_opts_loc_restore(dinfo->opts);
245 error_report("machine type does not support"
246 " if=%s,bus=%d,unit=%d",
247 if_name[dinfo->type], dinfo->bus, dinfo->unit);
248 loc_pop(&loc);
249 orphans = true;
253 if (orphans) {
254 exit(1);
258 DriveInfo *drive_get_by_index(BlockInterfaceType type, int index)
260 return drive_get(type,
261 drive_index_to_bus_id(type, index),
262 drive_index_to_unit_id(type, index));
265 int drive_get_max_bus(BlockInterfaceType type)
267 int max_bus;
268 BlockBackend *blk;
269 DriveInfo *dinfo;
271 max_bus = -1;
272 for (blk = blk_next(NULL); blk; blk = blk_next(blk)) {
273 dinfo = blk_legacy_dinfo(blk);
274 if (dinfo && dinfo->type == type && dinfo->bus > max_bus) {
275 max_bus = dinfo->bus;
278 return max_bus;
281 /* Get a block device. This should only be used for single-drive devices
282 (e.g. SD/Floppy/MTD). Multi-disk devices (scsi/ide) should use the
283 appropriate bus. */
284 DriveInfo *drive_get_next(BlockInterfaceType type)
286 static int next_block_unit[IF_COUNT];
288 return drive_get(type, 0, next_block_unit[type]++);
291 static void bdrv_format_print(void *opaque, const char *name)
293 error_printf(" %s", name);
296 typedef struct {
297 QEMUBH *bh;
298 BlockDriverState *bs;
299 } BDRVPutRefBH;
301 static int parse_block_error_action(const char *buf, bool is_read, Error **errp)
303 if (!strcmp(buf, "ignore")) {
304 return BLOCKDEV_ON_ERROR_IGNORE;
305 } else if (!is_read && !strcmp(buf, "enospc")) {
306 return BLOCKDEV_ON_ERROR_ENOSPC;
307 } else if (!strcmp(buf, "stop")) {
308 return BLOCKDEV_ON_ERROR_STOP;
309 } else if (!strcmp(buf, "report")) {
310 return BLOCKDEV_ON_ERROR_REPORT;
311 } else {
312 error_setg(errp, "'%s' invalid %s error action",
313 buf, is_read ? "read" : "write");
314 return -1;
318 static bool parse_stats_intervals(BlockAcctStats *stats, QList *intervals,
319 Error **errp)
321 const QListEntry *entry;
322 for (entry = qlist_first(intervals); entry; entry = qlist_next(entry)) {
323 switch (qobject_type(entry->value)) {
325 case QTYPE_QSTRING: {
326 unsigned long long length;
327 const char *str = qstring_get_str(qobject_to_qstring(entry->value));
328 if (parse_uint_full(str, &length, 10) == 0 &&
329 length > 0 && length <= UINT_MAX) {
330 block_acct_add_interval(stats, (unsigned) length);
331 } else {
332 error_setg(errp, "Invalid interval length: %s", str);
333 return false;
335 break;
338 case QTYPE_QNUM: {
339 int64_t length = qnum_get_int(qobject_to_qnum(entry->value));
341 if (length > 0 && length <= UINT_MAX) {
342 block_acct_add_interval(stats, (unsigned) length);
343 } else {
344 error_setg(errp, "Invalid interval length: %" PRId64, length);
345 return false;
347 break;
350 default:
351 error_setg(errp, "The specification of stats-intervals is invalid");
352 return false;
355 return true;
358 typedef enum { MEDIA_DISK, MEDIA_CDROM } DriveMediaType;
360 /* All parameters but @opts are optional and may be set to NULL. */
361 static void extract_common_blockdev_options(QemuOpts *opts, int *bdrv_flags,
362 const char **throttling_group, ThrottleConfig *throttle_cfg,
363 BlockdevDetectZeroesOptions *detect_zeroes, Error **errp)
365 Error *local_error = NULL;
366 const char *aio;
368 if (bdrv_flags) {
369 if (qemu_opt_get_bool(opts, "copy-on-read", false)) {
370 *bdrv_flags |= BDRV_O_COPY_ON_READ;
373 if ((aio = qemu_opt_get(opts, "aio")) != NULL) {
374 if (!strcmp(aio, "native")) {
375 *bdrv_flags |= BDRV_O_NATIVE_AIO;
376 } else if (!strcmp(aio, "threads")) {
377 /* this is the default */
378 } else {
379 error_setg(errp, "invalid aio option");
380 return;
385 /* disk I/O throttling */
386 if (throttling_group) {
387 *throttling_group = qemu_opt_get(opts, "throttling.group");
390 if (throttle_cfg) {
391 throttle_config_init(throttle_cfg);
392 throttle_cfg->buckets[THROTTLE_BPS_TOTAL].avg =
393 qemu_opt_get_number(opts, "throttling.bps-total", 0);
394 throttle_cfg->buckets[THROTTLE_BPS_READ].avg =
395 qemu_opt_get_number(opts, "throttling.bps-read", 0);
396 throttle_cfg->buckets[THROTTLE_BPS_WRITE].avg =
397 qemu_opt_get_number(opts, "throttling.bps-write", 0);
398 throttle_cfg->buckets[THROTTLE_OPS_TOTAL].avg =
399 qemu_opt_get_number(opts, "throttling.iops-total", 0);
400 throttle_cfg->buckets[THROTTLE_OPS_READ].avg =
401 qemu_opt_get_number(opts, "throttling.iops-read", 0);
402 throttle_cfg->buckets[THROTTLE_OPS_WRITE].avg =
403 qemu_opt_get_number(opts, "throttling.iops-write", 0);
405 throttle_cfg->buckets[THROTTLE_BPS_TOTAL].max =
406 qemu_opt_get_number(opts, "throttling.bps-total-max", 0);
407 throttle_cfg->buckets[THROTTLE_BPS_READ].max =
408 qemu_opt_get_number(opts, "throttling.bps-read-max", 0);
409 throttle_cfg->buckets[THROTTLE_BPS_WRITE].max =
410 qemu_opt_get_number(opts, "throttling.bps-write-max", 0);
411 throttle_cfg->buckets[THROTTLE_OPS_TOTAL].max =
412 qemu_opt_get_number(opts, "throttling.iops-total-max", 0);
413 throttle_cfg->buckets[THROTTLE_OPS_READ].max =
414 qemu_opt_get_number(opts, "throttling.iops-read-max", 0);
415 throttle_cfg->buckets[THROTTLE_OPS_WRITE].max =
416 qemu_opt_get_number(opts, "throttling.iops-write-max", 0);
418 throttle_cfg->buckets[THROTTLE_BPS_TOTAL].burst_length =
419 qemu_opt_get_number(opts, "throttling.bps-total-max-length", 1);
420 throttle_cfg->buckets[THROTTLE_BPS_READ].burst_length =
421 qemu_opt_get_number(opts, "throttling.bps-read-max-length", 1);
422 throttle_cfg->buckets[THROTTLE_BPS_WRITE].burst_length =
423 qemu_opt_get_number(opts, "throttling.bps-write-max-length", 1);
424 throttle_cfg->buckets[THROTTLE_OPS_TOTAL].burst_length =
425 qemu_opt_get_number(opts, "throttling.iops-total-max-length", 1);
426 throttle_cfg->buckets[THROTTLE_OPS_READ].burst_length =
427 qemu_opt_get_number(opts, "throttling.iops-read-max-length", 1);
428 throttle_cfg->buckets[THROTTLE_OPS_WRITE].burst_length =
429 qemu_opt_get_number(opts, "throttling.iops-write-max-length", 1);
431 throttle_cfg->op_size =
432 qemu_opt_get_number(opts, "throttling.iops-size", 0);
434 if (!throttle_is_valid(throttle_cfg, errp)) {
435 return;
439 if (detect_zeroes) {
440 *detect_zeroes =
441 qapi_enum_parse(&BlockdevDetectZeroesOptions_lookup,
442 qemu_opt_get(opts, "detect-zeroes"),
443 BLOCKDEV_DETECT_ZEROES_OPTIONS_OFF,
444 &local_error);
445 if (local_error) {
446 error_propagate(errp, local_error);
447 return;
452 /* Takes the ownership of bs_opts */
453 static BlockBackend *blockdev_init(const char *file, QDict *bs_opts,
454 Error **errp)
456 const char *buf;
457 int bdrv_flags = 0;
458 int on_read_error, on_write_error;
459 bool account_invalid, account_failed;
460 bool writethrough, read_only;
461 BlockBackend *blk;
462 BlockDriverState *bs;
463 ThrottleConfig cfg;
464 int snapshot = 0;
465 Error *error = NULL;
466 QemuOpts *opts;
467 QDict *interval_dict = NULL;
468 QList *interval_list = NULL;
469 const char *id;
470 BlockdevDetectZeroesOptions detect_zeroes =
471 BLOCKDEV_DETECT_ZEROES_OPTIONS_OFF;
472 const char *throttling_group = NULL;
474 /* Check common options by copying from bs_opts to opts, all other options
475 * stay in bs_opts for processing by bdrv_open(). */
476 id = qdict_get_try_str(bs_opts, "id");
477 opts = qemu_opts_create(&qemu_common_drive_opts, id, 1, &error);
478 if (error) {
479 error_propagate(errp, error);
480 goto err_no_opts;
483 qemu_opts_absorb_qdict(opts, bs_opts, &error);
484 if (error) {
485 error_propagate(errp, error);
486 goto early_err;
489 if (id) {
490 qdict_del(bs_opts, "id");
493 /* extract parameters */
494 snapshot = qemu_opt_get_bool(opts, "snapshot", 0);
496 account_invalid = qemu_opt_get_bool(opts, "stats-account-invalid", true);
497 account_failed = qemu_opt_get_bool(opts, "stats-account-failed", true);
499 writethrough = !qemu_opt_get_bool(opts, BDRV_OPT_CACHE_WB, true);
501 id = qemu_opts_id(opts);
503 qdict_extract_subqdict(bs_opts, &interval_dict, "stats-intervals.");
504 qdict_array_split(interval_dict, &interval_list);
506 if (qdict_size(interval_dict) != 0) {
507 error_setg(errp, "Invalid option stats-intervals.%s",
508 qdict_first(interval_dict)->key);
509 goto early_err;
512 extract_common_blockdev_options(opts, &bdrv_flags, &throttling_group, &cfg,
513 &detect_zeroes, &error);
514 if (error) {
515 error_propagate(errp, error);
516 goto early_err;
519 if ((buf = qemu_opt_get(opts, "format")) != NULL) {
520 if (is_help_option(buf)) {
521 error_printf("Supported formats:");
522 bdrv_iterate_format(bdrv_format_print, NULL);
523 error_printf("\n");
524 goto early_err;
527 if (qdict_haskey(bs_opts, "driver")) {
528 error_setg(errp, "Cannot specify both 'driver' and 'format'");
529 goto early_err;
531 qdict_put_str(bs_opts, "driver", buf);
534 on_write_error = BLOCKDEV_ON_ERROR_ENOSPC;
535 if ((buf = qemu_opt_get(opts, "werror")) != NULL) {
536 on_write_error = parse_block_error_action(buf, 0, &error);
537 if (error) {
538 error_propagate(errp, error);
539 goto early_err;
543 on_read_error = BLOCKDEV_ON_ERROR_REPORT;
544 if ((buf = qemu_opt_get(opts, "rerror")) != NULL) {
545 on_read_error = parse_block_error_action(buf, 1, &error);
546 if (error) {
547 error_propagate(errp, error);
548 goto early_err;
552 if (snapshot) {
553 bdrv_flags |= BDRV_O_SNAPSHOT;
556 read_only = qemu_opt_get_bool(opts, BDRV_OPT_READ_ONLY, false);
558 /* init */
559 if ((!file || !*file) && !qdict_size(bs_opts)) {
560 BlockBackendRootState *blk_rs;
562 blk = blk_new(0, BLK_PERM_ALL);
563 blk_rs = blk_get_root_state(blk);
564 blk_rs->open_flags = bdrv_flags;
565 blk_rs->read_only = read_only;
566 blk_rs->detect_zeroes = detect_zeroes;
568 QDECREF(bs_opts);
569 } else {
570 if (file && !*file) {
571 file = NULL;
574 /* bdrv_open() defaults to the values in bdrv_flags (for compatibility
575 * with other callers) rather than what we want as the real defaults.
576 * Apply the defaults here instead. */
577 qdict_set_default_str(bs_opts, BDRV_OPT_CACHE_DIRECT, "off");
578 qdict_set_default_str(bs_opts, BDRV_OPT_CACHE_NO_FLUSH, "off");
579 qdict_set_default_str(bs_opts, BDRV_OPT_READ_ONLY,
580 read_only ? "on" : "off");
581 assert((bdrv_flags & BDRV_O_CACHE_MASK) == 0);
583 if (runstate_check(RUN_STATE_INMIGRATE)) {
584 bdrv_flags |= BDRV_O_INACTIVE;
587 blk = blk_new_open(file, NULL, bs_opts, bdrv_flags, errp);
588 if (!blk) {
589 goto err_no_bs_opts;
591 bs = blk_bs(blk);
593 bs->detect_zeroes = detect_zeroes;
595 block_acct_setup(blk_get_stats(blk), account_invalid, account_failed);
597 if (!parse_stats_intervals(blk_get_stats(blk), interval_list, errp)) {
598 blk_unref(blk);
599 blk = NULL;
600 goto err_no_bs_opts;
604 /* disk I/O throttling */
605 if (throttle_enabled(&cfg)) {
606 if (!throttling_group) {
607 throttling_group = id;
609 blk_io_limits_enable(blk, throttling_group);
610 blk_set_io_limits(blk, &cfg);
613 blk_set_enable_write_cache(blk, !writethrough);
614 blk_set_on_error(blk, on_read_error, on_write_error);
616 if (!monitor_add_blk(blk, id, errp)) {
617 blk_unref(blk);
618 blk = NULL;
619 goto err_no_bs_opts;
622 err_no_bs_opts:
623 qemu_opts_del(opts);
624 QDECREF(interval_dict);
625 QDECREF(interval_list);
626 return blk;
628 early_err:
629 qemu_opts_del(opts);
630 QDECREF(interval_dict);
631 QDECREF(interval_list);
632 err_no_opts:
633 QDECREF(bs_opts);
634 return NULL;
637 /* Takes the ownership of bs_opts */
638 static BlockDriverState *bds_tree_init(QDict *bs_opts, Error **errp)
640 int bdrv_flags = 0;
642 /* bdrv_open() defaults to the values in bdrv_flags (for compatibility
643 * with other callers) rather than what we want as the real defaults.
644 * Apply the defaults here instead. */
645 qdict_set_default_str(bs_opts, BDRV_OPT_CACHE_DIRECT, "off");
646 qdict_set_default_str(bs_opts, BDRV_OPT_CACHE_NO_FLUSH, "off");
647 qdict_set_default_str(bs_opts, BDRV_OPT_READ_ONLY, "off");
649 if (runstate_check(RUN_STATE_INMIGRATE)) {
650 bdrv_flags |= BDRV_O_INACTIVE;
653 return bdrv_open(NULL, NULL, bs_opts, bdrv_flags, errp);
656 void blockdev_close_all_bdrv_states(void)
658 BlockDriverState *bs, *next_bs;
660 QTAILQ_FOREACH_SAFE(bs, &monitor_bdrv_states, monitor_list, next_bs) {
661 AioContext *ctx = bdrv_get_aio_context(bs);
663 aio_context_acquire(ctx);
664 bdrv_unref(bs);
665 aio_context_release(ctx);
669 /* Iterates over the list of monitor-owned BlockDriverStates */
670 BlockDriverState *bdrv_next_monitor_owned(BlockDriverState *bs)
672 return bs ? QTAILQ_NEXT(bs, monitor_list)
673 : QTAILQ_FIRST(&monitor_bdrv_states);
676 static void qemu_opt_rename(QemuOpts *opts, const char *from, const char *to,
677 Error **errp)
679 const char *value;
681 value = qemu_opt_get(opts, from);
682 if (value) {
683 if (qemu_opt_find(opts, to)) {
684 error_setg(errp, "'%s' and its alias '%s' can't be used at the "
685 "same time", to, from);
686 return;
690 /* rename all items in opts */
691 while ((value = qemu_opt_get(opts, from))) {
692 qemu_opt_set(opts, to, value, &error_abort);
693 qemu_opt_unset(opts, from);
697 QemuOptsList qemu_legacy_drive_opts = {
698 .name = "drive",
699 .head = QTAILQ_HEAD_INITIALIZER(qemu_legacy_drive_opts.head),
700 .desc = {
702 .name = "bus",
703 .type = QEMU_OPT_NUMBER,
704 .help = "bus number",
706 .name = "unit",
707 .type = QEMU_OPT_NUMBER,
708 .help = "unit number (i.e. lun for scsi)",
710 .name = "index",
711 .type = QEMU_OPT_NUMBER,
712 .help = "index number",
714 .name = "media",
715 .type = QEMU_OPT_STRING,
716 .help = "media type (disk, cdrom)",
718 .name = "if",
719 .type = QEMU_OPT_STRING,
720 .help = "interface (ide, scsi, sd, mtd, floppy, pflash, virtio)",
722 .name = "cyls",
723 .type = QEMU_OPT_NUMBER,
724 .help = "number of cylinders (ide disk geometry)",
726 .name = "heads",
727 .type = QEMU_OPT_NUMBER,
728 .help = "number of heads (ide disk geometry)",
730 .name = "secs",
731 .type = QEMU_OPT_NUMBER,
732 .help = "number of sectors (ide disk geometry)",
734 .name = "trans",
735 .type = QEMU_OPT_STRING,
736 .help = "chs translation (auto, lba, none)",
738 .name = "addr",
739 .type = QEMU_OPT_STRING,
740 .help = "pci address (virtio only)",
742 .name = "serial",
743 .type = QEMU_OPT_STRING,
744 .help = "disk serial number",
746 .name = "file",
747 .type = QEMU_OPT_STRING,
748 .help = "file name",
751 /* Options that are passed on, but have special semantics with -drive */
753 .name = BDRV_OPT_READ_ONLY,
754 .type = QEMU_OPT_BOOL,
755 .help = "open drive file as read-only",
757 .name = "rerror",
758 .type = QEMU_OPT_STRING,
759 .help = "read error action",
761 .name = "werror",
762 .type = QEMU_OPT_STRING,
763 .help = "write error action",
765 .name = "copy-on-read",
766 .type = QEMU_OPT_BOOL,
767 .help = "copy read data from backing file into image file",
770 { /* end of list */ }
774 DriveInfo *drive_new(QemuOpts *all_opts, BlockInterfaceType block_default_type)
776 const char *value;
777 BlockBackend *blk;
778 DriveInfo *dinfo = NULL;
779 QDict *bs_opts;
780 QemuOpts *legacy_opts;
781 DriveMediaType media = MEDIA_DISK;
782 BlockInterfaceType type;
783 int cyls, heads, secs, translation;
784 int max_devs, bus_id, unit_id, index;
785 const char *devaddr;
786 const char *werror, *rerror;
787 bool read_only = false;
788 bool copy_on_read;
789 const char *serial;
790 const char *filename;
791 Error *local_err = NULL;
792 int i;
793 const char *deprecated[] = {
794 "serial", "trans", "secs", "heads", "cyls", "addr"
797 /* Change legacy command line options into QMP ones */
798 static const struct {
799 const char *from;
800 const char *to;
801 } opt_renames[] = {
802 { "iops", "throttling.iops-total" },
803 { "iops_rd", "throttling.iops-read" },
804 { "iops_wr", "throttling.iops-write" },
806 { "bps", "throttling.bps-total" },
807 { "bps_rd", "throttling.bps-read" },
808 { "bps_wr", "throttling.bps-write" },
810 { "iops_max", "throttling.iops-total-max" },
811 { "iops_rd_max", "throttling.iops-read-max" },
812 { "iops_wr_max", "throttling.iops-write-max" },
814 { "bps_max", "throttling.bps-total-max" },
815 { "bps_rd_max", "throttling.bps-read-max" },
816 { "bps_wr_max", "throttling.bps-write-max" },
818 { "iops_size", "throttling.iops-size" },
820 { "group", "throttling.group" },
822 { "readonly", BDRV_OPT_READ_ONLY },
825 for (i = 0; i < ARRAY_SIZE(opt_renames); i++) {
826 qemu_opt_rename(all_opts, opt_renames[i].from, opt_renames[i].to,
827 &local_err);
828 if (local_err) {
829 error_report_err(local_err);
830 return NULL;
834 value = qemu_opt_get(all_opts, "cache");
835 if (value) {
836 int flags = 0;
837 bool writethrough;
839 if (bdrv_parse_cache_mode(value, &flags, &writethrough) != 0) {
840 error_report("invalid cache option");
841 return NULL;
844 /* Specific options take precedence */
845 if (!qemu_opt_get(all_opts, BDRV_OPT_CACHE_WB)) {
846 qemu_opt_set_bool(all_opts, BDRV_OPT_CACHE_WB,
847 !writethrough, &error_abort);
849 if (!qemu_opt_get(all_opts, BDRV_OPT_CACHE_DIRECT)) {
850 qemu_opt_set_bool(all_opts, BDRV_OPT_CACHE_DIRECT,
851 !!(flags & BDRV_O_NOCACHE), &error_abort);
853 if (!qemu_opt_get(all_opts, BDRV_OPT_CACHE_NO_FLUSH)) {
854 qemu_opt_set_bool(all_opts, BDRV_OPT_CACHE_NO_FLUSH,
855 !!(flags & BDRV_O_NO_FLUSH), &error_abort);
857 qemu_opt_unset(all_opts, "cache");
860 /* Get a QDict for processing the options */
861 bs_opts = qdict_new();
862 qemu_opts_to_qdict(all_opts, bs_opts);
864 legacy_opts = qemu_opts_create(&qemu_legacy_drive_opts, NULL, 0,
865 &error_abort);
866 qemu_opts_absorb_qdict(legacy_opts, bs_opts, &local_err);
867 if (local_err) {
868 error_report_err(local_err);
869 goto fail;
872 /* Other deprecated options */
873 if (!qtest_enabled()) {
874 for (i = 0; i < ARRAY_SIZE(deprecated); i++) {
875 if (qemu_opt_get(legacy_opts, deprecated[i]) != NULL) {
876 error_report("'%s' is deprecated, please use the corresponding "
877 "option of '-device' instead", deprecated[i]);
882 /* Media type */
883 value = qemu_opt_get(legacy_opts, "media");
884 if (value) {
885 if (!strcmp(value, "disk")) {
886 media = MEDIA_DISK;
887 } else if (!strcmp(value, "cdrom")) {
888 media = MEDIA_CDROM;
889 read_only = true;
890 } else {
891 error_report("'%s' invalid media", value);
892 goto fail;
896 /* copy-on-read is disabled with a warning for read-only devices */
897 read_only |= qemu_opt_get_bool(legacy_opts, BDRV_OPT_READ_ONLY, false);
898 copy_on_read = qemu_opt_get_bool(legacy_opts, "copy-on-read", false);
900 if (read_only && copy_on_read) {
901 warn_report("disabling copy-on-read on read-only drive");
902 copy_on_read = false;
905 qdict_put_str(bs_opts, BDRV_OPT_READ_ONLY, read_only ? "on" : "off");
906 qdict_put_str(bs_opts, "copy-on-read", copy_on_read ? "on" : "off");
908 /* Controller type */
909 value = qemu_opt_get(legacy_opts, "if");
910 if (value) {
911 for (type = 0;
912 type < IF_COUNT && strcmp(value, if_name[type]);
913 type++) {
915 if (type == IF_COUNT) {
916 error_report("unsupported bus type '%s'", value);
917 goto fail;
919 } else {
920 type = block_default_type;
923 /* Geometry */
924 cyls = qemu_opt_get_number(legacy_opts, "cyls", 0);
925 heads = qemu_opt_get_number(legacy_opts, "heads", 0);
926 secs = qemu_opt_get_number(legacy_opts, "secs", 0);
928 if (cyls || heads || secs) {
929 if (cyls < 1) {
930 error_report("invalid physical cyls number");
931 goto fail;
933 if (heads < 1) {
934 error_report("invalid physical heads number");
935 goto fail;
937 if (secs < 1) {
938 error_report("invalid physical secs number");
939 goto fail;
943 translation = BIOS_ATA_TRANSLATION_AUTO;
944 value = qemu_opt_get(legacy_opts, "trans");
945 if (value != NULL) {
946 if (!cyls) {
947 error_report("'%s' trans must be used with cyls, heads and secs",
948 value);
949 goto fail;
951 if (!strcmp(value, "none")) {
952 translation = BIOS_ATA_TRANSLATION_NONE;
953 } else if (!strcmp(value, "lba")) {
954 translation = BIOS_ATA_TRANSLATION_LBA;
955 } else if (!strcmp(value, "large")) {
956 translation = BIOS_ATA_TRANSLATION_LARGE;
957 } else if (!strcmp(value, "rechs")) {
958 translation = BIOS_ATA_TRANSLATION_RECHS;
959 } else if (!strcmp(value, "auto")) {
960 translation = BIOS_ATA_TRANSLATION_AUTO;
961 } else {
962 error_report("'%s' invalid translation type", value);
963 goto fail;
967 if (media == MEDIA_CDROM) {
968 if (cyls || secs || heads) {
969 error_report("CHS can't be set with media=cdrom");
970 goto fail;
974 /* Device address specified by bus/unit or index.
975 * If none was specified, try to find the first free one. */
976 bus_id = qemu_opt_get_number(legacy_opts, "bus", 0);
977 unit_id = qemu_opt_get_number(legacy_opts, "unit", -1);
978 index = qemu_opt_get_number(legacy_opts, "index", -1);
980 max_devs = if_max_devs[type];
982 if (index != -1) {
983 if (bus_id != 0 || unit_id != -1) {
984 error_report("index cannot be used with bus and unit");
985 goto fail;
987 bus_id = drive_index_to_bus_id(type, index);
988 unit_id = drive_index_to_unit_id(type, index);
991 if (unit_id == -1) {
992 unit_id = 0;
993 while (drive_get(type, bus_id, unit_id) != NULL) {
994 unit_id++;
995 if (max_devs && unit_id >= max_devs) {
996 unit_id -= max_devs;
997 bus_id++;
1002 if (max_devs && unit_id >= max_devs) {
1003 error_report("unit %d too big (max is %d)", unit_id, max_devs - 1);
1004 goto fail;
1007 if (drive_get(type, bus_id, unit_id) != NULL) {
1008 error_report("drive with bus=%d, unit=%d (index=%d) exists",
1009 bus_id, unit_id, index);
1010 goto fail;
1013 /* Serial number */
1014 serial = qemu_opt_get(legacy_opts, "serial");
1016 /* no id supplied -> create one */
1017 if (qemu_opts_id(all_opts) == NULL) {
1018 char *new_id;
1019 const char *mediastr = "";
1020 if (type == IF_IDE || type == IF_SCSI) {
1021 mediastr = (media == MEDIA_CDROM) ? "-cd" : "-hd";
1023 if (max_devs) {
1024 new_id = g_strdup_printf("%s%i%s%i", if_name[type], bus_id,
1025 mediastr, unit_id);
1026 } else {
1027 new_id = g_strdup_printf("%s%s%i", if_name[type],
1028 mediastr, unit_id);
1030 qdict_put_str(bs_opts, "id", new_id);
1031 g_free(new_id);
1034 /* Add virtio block device */
1035 devaddr = qemu_opt_get(legacy_opts, "addr");
1036 if (devaddr && type != IF_VIRTIO) {
1037 error_report("addr is not supported by this bus type");
1038 goto fail;
1041 if (type == IF_VIRTIO) {
1042 QemuOpts *devopts;
1043 devopts = qemu_opts_create(qemu_find_opts("device"), NULL, 0,
1044 &error_abort);
1045 if (arch_type == QEMU_ARCH_S390X) {
1046 qemu_opt_set(devopts, "driver", "virtio-blk-ccw", &error_abort);
1047 } else {
1048 qemu_opt_set(devopts, "driver", "virtio-blk-pci", &error_abort);
1050 qemu_opt_set(devopts, "drive", qdict_get_str(bs_opts, "id"),
1051 &error_abort);
1052 if (devaddr) {
1053 qemu_opt_set(devopts, "addr", devaddr, &error_abort);
1057 filename = qemu_opt_get(legacy_opts, "file");
1059 /* Check werror/rerror compatibility with if=... */
1060 werror = qemu_opt_get(legacy_opts, "werror");
1061 if (werror != NULL) {
1062 if (type != IF_IDE && type != IF_SCSI && type != IF_VIRTIO &&
1063 type != IF_NONE) {
1064 error_report("werror is not supported by this bus type");
1065 goto fail;
1067 qdict_put_str(bs_opts, "werror", werror);
1070 rerror = qemu_opt_get(legacy_opts, "rerror");
1071 if (rerror != NULL) {
1072 if (type != IF_IDE && type != IF_VIRTIO && type != IF_SCSI &&
1073 type != IF_NONE) {
1074 error_report("rerror is not supported by this bus type");
1075 goto fail;
1077 qdict_put_str(bs_opts, "rerror", rerror);
1080 /* Actual block device init: Functionality shared with blockdev-add */
1081 blk = blockdev_init(filename, bs_opts, &local_err);
1082 bs_opts = NULL;
1083 if (!blk) {
1084 if (local_err) {
1085 error_report_err(local_err);
1087 goto fail;
1088 } else {
1089 assert(!local_err);
1092 /* Create legacy DriveInfo */
1093 dinfo = g_malloc0(sizeof(*dinfo));
1094 dinfo->opts = all_opts;
1096 dinfo->cyls = cyls;
1097 dinfo->heads = heads;
1098 dinfo->secs = secs;
1099 dinfo->trans = translation;
1101 dinfo->type = type;
1102 dinfo->bus = bus_id;
1103 dinfo->unit = unit_id;
1104 dinfo->devaddr = devaddr;
1105 dinfo->serial = g_strdup(serial);
1107 blk_set_legacy_dinfo(blk, dinfo);
1109 switch(type) {
1110 case IF_IDE:
1111 case IF_SCSI:
1112 case IF_XEN:
1113 case IF_NONE:
1114 dinfo->media_cd = media == MEDIA_CDROM;
1115 break;
1116 default:
1117 break;
1120 fail:
1121 qemu_opts_del(legacy_opts);
1122 QDECREF(bs_opts);
1123 return dinfo;
1126 static BlockDriverState *qmp_get_root_bs(const char *name, Error **errp)
1128 BlockDriverState *bs;
1130 bs = bdrv_lookup_bs(name, name, errp);
1131 if (bs == NULL) {
1132 return NULL;
1135 if (!bdrv_is_root_node(bs)) {
1136 error_setg(errp, "Need a root block node");
1137 return NULL;
1140 if (!bdrv_is_inserted(bs)) {
1141 error_setg(errp, "Device has no medium");
1142 return NULL;
1145 return bs;
1148 static BlockBackend *qmp_get_blk(const char *blk_name, const char *qdev_id,
1149 Error **errp)
1151 BlockBackend *blk;
1153 if (!blk_name == !qdev_id) {
1154 error_setg(errp, "Need exactly one of 'device' and 'id'");
1155 return NULL;
1158 if (qdev_id) {
1159 blk = blk_by_qdev_id(qdev_id, errp);
1160 } else {
1161 blk = blk_by_name(blk_name);
1162 if (blk == NULL) {
1163 error_set(errp, ERROR_CLASS_DEVICE_NOT_FOUND,
1164 "Device '%s' not found", blk_name);
1168 return blk;
1171 void hmp_commit(Monitor *mon, const QDict *qdict)
1173 const char *device = qdict_get_str(qdict, "device");
1174 BlockBackend *blk;
1175 int ret;
1177 if (!strcmp(device, "all")) {
1178 ret = blk_commit_all();
1179 } else {
1180 BlockDriverState *bs;
1181 AioContext *aio_context;
1183 blk = blk_by_name(device);
1184 if (!blk) {
1185 monitor_printf(mon, "Device '%s' not found\n", device);
1186 return;
1188 if (!blk_is_available(blk)) {
1189 monitor_printf(mon, "Device '%s' has no medium\n", device);
1190 return;
1193 bs = blk_bs(blk);
1194 aio_context = bdrv_get_aio_context(bs);
1195 aio_context_acquire(aio_context);
1197 ret = bdrv_commit(bs);
1199 aio_context_release(aio_context);
1201 if (ret < 0) {
1202 monitor_printf(mon, "'commit' error for '%s': %s\n", device,
1203 strerror(-ret));
1207 static void blockdev_do_action(TransactionAction *action, Error **errp)
1209 TransactionActionList list;
1211 list.value = action;
1212 list.next = NULL;
1213 qmp_transaction(&list, false, NULL, errp);
1216 void qmp_blockdev_snapshot_sync(bool has_device, const char *device,
1217 bool has_node_name, const char *node_name,
1218 const char *snapshot_file,
1219 bool has_snapshot_node_name,
1220 const char *snapshot_node_name,
1221 bool has_format, const char *format,
1222 bool has_mode, NewImageMode mode, Error **errp)
1224 BlockdevSnapshotSync snapshot = {
1225 .has_device = has_device,
1226 .device = (char *) device,
1227 .has_node_name = has_node_name,
1228 .node_name = (char *) node_name,
1229 .snapshot_file = (char *) snapshot_file,
1230 .has_snapshot_node_name = has_snapshot_node_name,
1231 .snapshot_node_name = (char *) snapshot_node_name,
1232 .has_format = has_format,
1233 .format = (char *) format,
1234 .has_mode = has_mode,
1235 .mode = mode,
1237 TransactionAction action = {
1238 .type = TRANSACTION_ACTION_KIND_BLOCKDEV_SNAPSHOT_SYNC,
1239 .u.blockdev_snapshot_sync.data = &snapshot,
1241 blockdev_do_action(&action, errp);
1244 void qmp_blockdev_snapshot(const char *node, const char *overlay,
1245 Error **errp)
1247 BlockdevSnapshot snapshot_data = {
1248 .node = (char *) node,
1249 .overlay = (char *) overlay
1251 TransactionAction action = {
1252 .type = TRANSACTION_ACTION_KIND_BLOCKDEV_SNAPSHOT,
1253 .u.blockdev_snapshot.data = &snapshot_data,
1255 blockdev_do_action(&action, errp);
1258 void qmp_blockdev_snapshot_internal_sync(const char *device,
1259 const char *name,
1260 Error **errp)
1262 BlockdevSnapshotInternal snapshot = {
1263 .device = (char *) device,
1264 .name = (char *) name
1266 TransactionAction action = {
1267 .type = TRANSACTION_ACTION_KIND_BLOCKDEV_SNAPSHOT_INTERNAL_SYNC,
1268 .u.blockdev_snapshot_internal_sync.data = &snapshot,
1270 blockdev_do_action(&action, errp);
1273 SnapshotInfo *qmp_blockdev_snapshot_delete_internal_sync(const char *device,
1274 bool has_id,
1275 const char *id,
1276 bool has_name,
1277 const char *name,
1278 Error **errp)
1280 BlockDriverState *bs;
1281 AioContext *aio_context;
1282 QEMUSnapshotInfo sn;
1283 Error *local_err = NULL;
1284 SnapshotInfo *info = NULL;
1285 int ret;
1287 bs = qmp_get_root_bs(device, errp);
1288 if (!bs) {
1289 return NULL;
1291 aio_context = bdrv_get_aio_context(bs);
1292 aio_context_acquire(aio_context);
1294 if (!has_id) {
1295 id = NULL;
1298 if (!has_name) {
1299 name = NULL;
1302 if (!id && !name) {
1303 error_setg(errp, "Name or id must be provided");
1304 goto out_aio_context;
1307 if (bdrv_op_is_blocked(bs, BLOCK_OP_TYPE_INTERNAL_SNAPSHOT_DELETE, errp)) {
1308 goto out_aio_context;
1311 ret = bdrv_snapshot_find_by_id_and_name(bs, id, name, &sn, &local_err);
1312 if (local_err) {
1313 error_propagate(errp, local_err);
1314 goto out_aio_context;
1316 if (!ret) {
1317 error_setg(errp,
1318 "Snapshot with id '%s' and name '%s' does not exist on "
1319 "device '%s'",
1320 STR_OR_NULL(id), STR_OR_NULL(name), device);
1321 goto out_aio_context;
1324 bdrv_snapshot_delete(bs, id, name, &local_err);
1325 if (local_err) {
1326 error_propagate(errp, local_err);
1327 goto out_aio_context;
1330 aio_context_release(aio_context);
1332 info = g_new0(SnapshotInfo, 1);
1333 info->id = g_strdup(sn.id_str);
1334 info->name = g_strdup(sn.name);
1335 info->date_nsec = sn.date_nsec;
1336 info->date_sec = sn.date_sec;
1337 info->vm_state_size = sn.vm_state_size;
1338 info->vm_clock_nsec = sn.vm_clock_nsec % 1000000000;
1339 info->vm_clock_sec = sn.vm_clock_nsec / 1000000000;
1341 return info;
1343 out_aio_context:
1344 aio_context_release(aio_context);
1345 return NULL;
1349 * block_dirty_bitmap_lookup:
1350 * Return a dirty bitmap (if present), after validating
1351 * the node reference and bitmap names.
1353 * @node: The name of the BDS node to search for bitmaps
1354 * @name: The name of the bitmap to search for
1355 * @pbs: Output pointer for BDS lookup, if desired. Can be NULL.
1356 * @paio: Output pointer for aio_context acquisition, if desired. Can be NULL.
1357 * @errp: Output pointer for error information. Can be NULL.
1359 * @return: A bitmap object on success, or NULL on failure.
1361 static BdrvDirtyBitmap *block_dirty_bitmap_lookup(const char *node,
1362 const char *name,
1363 BlockDriverState **pbs,
1364 Error **errp)
1366 BlockDriverState *bs;
1367 BdrvDirtyBitmap *bitmap;
1369 if (!node) {
1370 error_setg(errp, "Node cannot be NULL");
1371 return NULL;
1373 if (!name) {
1374 error_setg(errp, "Bitmap name cannot be NULL");
1375 return NULL;
1377 bs = bdrv_lookup_bs(node, node, NULL);
1378 if (!bs) {
1379 error_setg(errp, "Node '%s' not found", node);
1380 return NULL;
1383 bitmap = bdrv_find_dirty_bitmap(bs, name);
1384 if (!bitmap) {
1385 error_setg(errp, "Dirty bitmap '%s' not found", name);
1386 return NULL;
1389 if (pbs) {
1390 *pbs = bs;
1393 return bitmap;
1396 /* New and old BlockDriverState structs for atomic group operations */
1398 typedef struct BlkActionState BlkActionState;
1401 * BlkActionOps:
1402 * Table of operations that define an Action.
1404 * @instance_size: Size of state struct, in bytes.
1405 * @prepare: Prepare the work, must NOT be NULL.
1406 * @commit: Commit the changes, can be NULL.
1407 * @abort: Abort the changes on fail, can be NULL.
1408 * @clean: Clean up resources after all transaction actions have called
1409 * commit() or abort(). Can be NULL.
1411 * Only prepare() may fail. In a single transaction, only one of commit() or
1412 * abort() will be called. clean() will always be called if it is present.
1414 typedef struct BlkActionOps {
1415 size_t instance_size;
1416 void (*prepare)(BlkActionState *common, Error **errp);
1417 void (*commit)(BlkActionState *common);
1418 void (*abort)(BlkActionState *common);
1419 void (*clean)(BlkActionState *common);
1420 } BlkActionOps;
1423 * BlkActionState:
1424 * Describes one Action's state within a Transaction.
1426 * @action: QAPI-defined enum identifying which Action to perform.
1427 * @ops: Table of ActionOps this Action can perform.
1428 * @block_job_txn: Transaction which this action belongs to.
1429 * @entry: List membership for all Actions in this Transaction.
1431 * This structure must be arranged as first member in a subclassed type,
1432 * assuming that the compiler will also arrange it to the same offsets as the
1433 * base class.
1435 struct BlkActionState {
1436 TransactionAction *action;
1437 const BlkActionOps *ops;
1438 BlockJobTxn *block_job_txn;
1439 TransactionProperties *txn_props;
1440 QSIMPLEQ_ENTRY(BlkActionState) entry;
1443 /* internal snapshot private data */
1444 typedef struct InternalSnapshotState {
1445 BlkActionState common;
1446 BlockDriverState *bs;
1447 QEMUSnapshotInfo sn;
1448 bool created;
1449 } InternalSnapshotState;
1452 static int action_check_completion_mode(BlkActionState *s, Error **errp)
1454 if (s->txn_props->completion_mode != ACTION_COMPLETION_MODE_INDIVIDUAL) {
1455 error_setg(errp,
1456 "Action '%s' does not support Transaction property "
1457 "completion-mode = %s",
1458 TransactionActionKind_str(s->action->type),
1459 ActionCompletionMode_str(s->txn_props->completion_mode));
1460 return -1;
1462 return 0;
1465 static void internal_snapshot_prepare(BlkActionState *common,
1466 Error **errp)
1468 Error *local_err = NULL;
1469 const char *device;
1470 const char *name;
1471 BlockDriverState *bs;
1472 QEMUSnapshotInfo old_sn, *sn;
1473 bool ret;
1474 qemu_timeval tv;
1475 BlockdevSnapshotInternal *internal;
1476 InternalSnapshotState *state;
1477 AioContext *aio_context;
1478 int ret1;
1480 g_assert(common->action->type ==
1481 TRANSACTION_ACTION_KIND_BLOCKDEV_SNAPSHOT_INTERNAL_SYNC);
1482 internal = common->action->u.blockdev_snapshot_internal_sync.data;
1483 state = DO_UPCAST(InternalSnapshotState, common, common);
1485 /* 1. parse input */
1486 device = internal->device;
1487 name = internal->name;
1489 /* 2. check for validation */
1490 if (action_check_completion_mode(common, errp) < 0) {
1491 return;
1494 bs = qmp_get_root_bs(device, errp);
1495 if (!bs) {
1496 return;
1499 aio_context = bdrv_get_aio_context(bs);
1500 aio_context_acquire(aio_context);
1502 state->bs = bs;
1504 /* Paired with .clean() */
1505 bdrv_drained_begin(bs);
1507 if (bdrv_op_is_blocked(bs, BLOCK_OP_TYPE_INTERNAL_SNAPSHOT, errp)) {
1508 goto out;
1511 if (bdrv_is_read_only(bs)) {
1512 error_setg(errp, "Device '%s' is read only", device);
1513 goto out;
1516 if (!bdrv_can_snapshot(bs)) {
1517 error_setg(errp, "Block format '%s' used by device '%s' "
1518 "does not support internal snapshots",
1519 bs->drv->format_name, device);
1520 goto out;
1523 if (!strlen(name)) {
1524 error_setg(errp, "Name is empty");
1525 goto out;
1528 /* check whether a snapshot with name exist */
1529 ret = bdrv_snapshot_find_by_id_and_name(bs, NULL, name, &old_sn,
1530 &local_err);
1531 if (local_err) {
1532 error_propagate(errp, local_err);
1533 goto out;
1534 } else if (ret) {
1535 error_setg(errp,
1536 "Snapshot with name '%s' already exists on device '%s'",
1537 name, device);
1538 goto out;
1541 /* 3. take the snapshot */
1542 sn = &state->sn;
1543 pstrcpy(sn->name, sizeof(sn->name), name);
1544 qemu_gettimeofday(&tv);
1545 sn->date_sec = tv.tv_sec;
1546 sn->date_nsec = tv.tv_usec * 1000;
1547 sn->vm_clock_nsec = qemu_clock_get_ns(QEMU_CLOCK_VIRTUAL);
1549 ret1 = bdrv_snapshot_create(bs, sn);
1550 if (ret1 < 0) {
1551 error_setg_errno(errp, -ret1,
1552 "Failed to create snapshot '%s' on device '%s'",
1553 name, device);
1554 goto out;
1557 /* 4. succeed, mark a snapshot is created */
1558 state->created = true;
1560 out:
1561 aio_context_release(aio_context);
1564 static void internal_snapshot_abort(BlkActionState *common)
1566 InternalSnapshotState *state =
1567 DO_UPCAST(InternalSnapshotState, common, common);
1568 BlockDriverState *bs = state->bs;
1569 QEMUSnapshotInfo *sn = &state->sn;
1570 AioContext *aio_context;
1571 Error *local_error = NULL;
1573 if (!state->created) {
1574 return;
1577 aio_context = bdrv_get_aio_context(state->bs);
1578 aio_context_acquire(aio_context);
1580 if (bdrv_snapshot_delete(bs, sn->id_str, sn->name, &local_error) < 0) {
1581 error_reportf_err(local_error,
1582 "Failed to delete snapshot with id '%s' and "
1583 "name '%s' on device '%s' in abort: ",
1584 sn->id_str, sn->name,
1585 bdrv_get_device_name(bs));
1588 aio_context_release(aio_context);
1591 static void internal_snapshot_clean(BlkActionState *common)
1593 InternalSnapshotState *state = DO_UPCAST(InternalSnapshotState,
1594 common, common);
1595 AioContext *aio_context;
1597 if (!state->bs) {
1598 return;
1601 aio_context = bdrv_get_aio_context(state->bs);
1602 aio_context_acquire(aio_context);
1604 bdrv_drained_end(state->bs);
1606 aio_context_release(aio_context);
1609 /* external snapshot private data */
1610 typedef struct ExternalSnapshotState {
1611 BlkActionState common;
1612 BlockDriverState *old_bs;
1613 BlockDriverState *new_bs;
1614 bool overlay_appended;
1615 } ExternalSnapshotState;
1617 static void external_snapshot_prepare(BlkActionState *common,
1618 Error **errp)
1620 int flags = 0;
1621 QDict *options = NULL;
1622 Error *local_err = NULL;
1623 /* Device and node name of the image to generate the snapshot from */
1624 const char *device;
1625 const char *node_name;
1626 /* Reference to the new image (for 'blockdev-snapshot') */
1627 const char *snapshot_ref;
1628 /* File name of the new image (for 'blockdev-snapshot-sync') */
1629 const char *new_image_file;
1630 ExternalSnapshotState *state =
1631 DO_UPCAST(ExternalSnapshotState, common, common);
1632 TransactionAction *action = common->action;
1633 AioContext *aio_context;
1635 /* 'blockdev-snapshot' and 'blockdev-snapshot-sync' have similar
1636 * purpose but a different set of parameters */
1637 switch (action->type) {
1638 case TRANSACTION_ACTION_KIND_BLOCKDEV_SNAPSHOT:
1640 BlockdevSnapshot *s = action->u.blockdev_snapshot.data;
1641 device = s->node;
1642 node_name = s->node;
1643 new_image_file = NULL;
1644 snapshot_ref = s->overlay;
1646 break;
1647 case TRANSACTION_ACTION_KIND_BLOCKDEV_SNAPSHOT_SYNC:
1649 BlockdevSnapshotSync *s = action->u.blockdev_snapshot_sync.data;
1650 device = s->has_device ? s->device : NULL;
1651 node_name = s->has_node_name ? s->node_name : NULL;
1652 new_image_file = s->snapshot_file;
1653 snapshot_ref = NULL;
1655 break;
1656 default:
1657 g_assert_not_reached();
1660 /* start processing */
1661 if (action_check_completion_mode(common, errp) < 0) {
1662 return;
1665 state->old_bs = bdrv_lookup_bs(device, node_name, errp);
1666 if (!state->old_bs) {
1667 return;
1670 aio_context = bdrv_get_aio_context(state->old_bs);
1671 aio_context_acquire(aio_context);
1673 /* Paired with .clean() */
1674 bdrv_drained_begin(state->old_bs);
1676 if (!bdrv_is_inserted(state->old_bs)) {
1677 error_setg(errp, QERR_DEVICE_HAS_NO_MEDIUM, device);
1678 goto out;
1681 if (bdrv_op_is_blocked(state->old_bs,
1682 BLOCK_OP_TYPE_EXTERNAL_SNAPSHOT, errp)) {
1683 goto out;
1686 if (!bdrv_is_read_only(state->old_bs)) {
1687 if (bdrv_flush(state->old_bs)) {
1688 error_setg(errp, QERR_IO_ERROR);
1689 goto out;
1693 if (!bdrv_is_first_non_filter(state->old_bs)) {
1694 error_setg(errp, QERR_FEATURE_DISABLED, "snapshot");
1695 goto out;
1698 if (action->type == TRANSACTION_ACTION_KIND_BLOCKDEV_SNAPSHOT_SYNC) {
1699 BlockdevSnapshotSync *s = action->u.blockdev_snapshot_sync.data;
1700 const char *format = s->has_format ? s->format : "qcow2";
1701 enum NewImageMode mode;
1702 const char *snapshot_node_name =
1703 s->has_snapshot_node_name ? s->snapshot_node_name : NULL;
1705 if (node_name && !snapshot_node_name) {
1706 error_setg(errp, "New snapshot node name missing");
1707 goto out;
1710 if (snapshot_node_name &&
1711 bdrv_lookup_bs(snapshot_node_name, snapshot_node_name, NULL)) {
1712 error_setg(errp, "New snapshot node name already in use");
1713 goto out;
1716 flags = state->old_bs->open_flags;
1717 flags &= ~(BDRV_O_SNAPSHOT | BDRV_O_COPY_ON_READ);
1718 flags |= BDRV_O_NO_BACKING;
1720 /* create new image w/backing file */
1721 mode = s->has_mode ? s->mode : NEW_IMAGE_MODE_ABSOLUTE_PATHS;
1722 if (mode != NEW_IMAGE_MODE_EXISTING) {
1723 int64_t size = bdrv_getlength(state->old_bs);
1724 if (size < 0) {
1725 error_setg_errno(errp, -size, "bdrv_getlength failed");
1726 goto out;
1728 bdrv_img_create(new_image_file, format,
1729 state->old_bs->filename,
1730 state->old_bs->drv->format_name,
1731 NULL, size, flags, false, &local_err);
1732 if (local_err) {
1733 error_propagate(errp, local_err);
1734 goto out;
1738 options = qdict_new();
1739 if (s->has_snapshot_node_name) {
1740 qdict_put_str(options, "node-name", snapshot_node_name);
1742 qdict_put_str(options, "driver", format);
1745 state->new_bs = bdrv_open(new_image_file, snapshot_ref, options, flags,
1746 errp);
1747 /* We will manually add the backing_hd field to the bs later */
1748 if (!state->new_bs) {
1749 goto out;
1752 if (bdrv_has_blk(state->new_bs)) {
1753 error_setg(errp, "The snapshot is already in use");
1754 goto out;
1757 if (bdrv_op_is_blocked(state->new_bs, BLOCK_OP_TYPE_EXTERNAL_SNAPSHOT,
1758 errp)) {
1759 goto out;
1762 if (state->new_bs->backing != NULL) {
1763 error_setg(errp, "The snapshot already has a backing image");
1764 goto out;
1767 if (!state->new_bs->drv->supports_backing) {
1768 error_setg(errp, "The snapshot does not support backing images");
1769 goto out;
1772 bdrv_set_aio_context(state->new_bs, aio_context);
1774 /* This removes our old bs and adds the new bs. This is an operation that
1775 * can fail, so we need to do it in .prepare; undoing it for abort is
1776 * always possible. */
1777 bdrv_ref(state->new_bs);
1778 bdrv_append(state->new_bs, state->old_bs, &local_err);
1779 if (local_err) {
1780 error_propagate(errp, local_err);
1781 goto out;
1783 state->overlay_appended = true;
1785 out:
1786 aio_context_release(aio_context);
1789 static void external_snapshot_commit(BlkActionState *common)
1791 ExternalSnapshotState *state =
1792 DO_UPCAST(ExternalSnapshotState, common, common);
1793 AioContext *aio_context;
1795 aio_context = bdrv_get_aio_context(state->old_bs);
1796 aio_context_acquire(aio_context);
1798 /* We don't need (or want) to use the transactional
1799 * bdrv_reopen_multiple() across all the entries at once, because we
1800 * don't want to abort all of them if one of them fails the reopen */
1801 if (!atomic_read(&state->old_bs->copy_on_read)) {
1802 bdrv_reopen(state->old_bs, state->old_bs->open_flags & ~BDRV_O_RDWR,
1803 NULL);
1806 aio_context_release(aio_context);
1809 static void external_snapshot_abort(BlkActionState *common)
1811 ExternalSnapshotState *state =
1812 DO_UPCAST(ExternalSnapshotState, common, common);
1813 if (state->new_bs) {
1814 if (state->overlay_appended) {
1815 AioContext *aio_context;
1817 aio_context = bdrv_get_aio_context(state->old_bs);
1818 aio_context_acquire(aio_context);
1820 bdrv_ref(state->old_bs); /* we can't let bdrv_set_backind_hd()
1821 close state->old_bs; we need it */
1822 bdrv_set_backing_hd(state->new_bs, NULL, &error_abort);
1823 bdrv_replace_node(state->new_bs, state->old_bs, &error_abort);
1824 bdrv_unref(state->old_bs); /* bdrv_replace_node() ref'ed old_bs */
1826 aio_context_release(aio_context);
1831 static void external_snapshot_clean(BlkActionState *common)
1833 ExternalSnapshotState *state =
1834 DO_UPCAST(ExternalSnapshotState, common, common);
1835 AioContext *aio_context;
1837 if (!state->old_bs) {
1838 return;
1841 aio_context = bdrv_get_aio_context(state->old_bs);
1842 aio_context_acquire(aio_context);
1844 bdrv_drained_end(state->old_bs);
1845 bdrv_unref(state->new_bs);
1847 aio_context_release(aio_context);
1850 typedef struct DriveBackupState {
1851 BlkActionState common;
1852 BlockDriverState *bs;
1853 BlockJob *job;
1854 } DriveBackupState;
1856 static BlockJob *do_drive_backup(DriveBackup *backup, BlockJobTxn *txn,
1857 Error **errp);
1859 static void drive_backup_prepare(BlkActionState *common, Error **errp)
1861 DriveBackupState *state = DO_UPCAST(DriveBackupState, common, common);
1862 BlockDriverState *bs;
1863 DriveBackup *backup;
1864 AioContext *aio_context;
1865 Error *local_err = NULL;
1867 assert(common->action->type == TRANSACTION_ACTION_KIND_DRIVE_BACKUP);
1868 backup = common->action->u.drive_backup.data;
1870 bs = qmp_get_root_bs(backup->device, errp);
1871 if (!bs) {
1872 return;
1875 aio_context = bdrv_get_aio_context(bs);
1876 aio_context_acquire(aio_context);
1878 /* Paired with .clean() */
1879 bdrv_drained_begin(bs);
1881 state->bs = bs;
1883 state->job = do_drive_backup(backup, common->block_job_txn, &local_err);
1884 if (local_err) {
1885 error_propagate(errp, local_err);
1886 goto out;
1889 out:
1890 aio_context_release(aio_context);
1893 static void drive_backup_commit(BlkActionState *common)
1895 DriveBackupState *state = DO_UPCAST(DriveBackupState, common, common);
1896 AioContext *aio_context;
1898 aio_context = bdrv_get_aio_context(state->bs);
1899 aio_context_acquire(aio_context);
1901 assert(state->job);
1902 block_job_start(state->job);
1904 aio_context_release(aio_context);
1907 static void drive_backup_abort(BlkActionState *common)
1909 DriveBackupState *state = DO_UPCAST(DriveBackupState, common, common);
1911 if (state->job) {
1912 AioContext *aio_context;
1914 aio_context = bdrv_get_aio_context(state->bs);
1915 aio_context_acquire(aio_context);
1917 block_job_cancel_sync(state->job);
1919 aio_context_release(aio_context);
1923 static void drive_backup_clean(BlkActionState *common)
1925 DriveBackupState *state = DO_UPCAST(DriveBackupState, common, common);
1926 AioContext *aio_context;
1928 if (!state->bs) {
1929 return;
1932 aio_context = bdrv_get_aio_context(state->bs);
1933 aio_context_acquire(aio_context);
1935 bdrv_drained_end(state->bs);
1937 aio_context_release(aio_context);
1940 typedef struct BlockdevBackupState {
1941 BlkActionState common;
1942 BlockDriverState *bs;
1943 BlockJob *job;
1944 } BlockdevBackupState;
1946 static BlockJob *do_blockdev_backup(BlockdevBackup *backup, BlockJobTxn *txn,
1947 Error **errp);
1949 static void blockdev_backup_prepare(BlkActionState *common, Error **errp)
1951 BlockdevBackupState *state = DO_UPCAST(BlockdevBackupState, common, common);
1952 BlockdevBackup *backup;
1953 BlockDriverState *bs, *target;
1954 AioContext *aio_context;
1955 Error *local_err = NULL;
1957 assert(common->action->type == TRANSACTION_ACTION_KIND_BLOCKDEV_BACKUP);
1958 backup = common->action->u.blockdev_backup.data;
1960 bs = qmp_get_root_bs(backup->device, errp);
1961 if (!bs) {
1962 return;
1965 target = bdrv_lookup_bs(backup->target, backup->target, errp);
1966 if (!target) {
1967 return;
1970 aio_context = bdrv_get_aio_context(bs);
1971 if (aio_context != bdrv_get_aio_context(target)) {
1972 error_setg(errp, "Backup between two IO threads is not implemented");
1973 return;
1975 aio_context_acquire(aio_context);
1976 state->bs = bs;
1978 /* Paired with .clean() */
1979 bdrv_drained_begin(state->bs);
1981 state->job = do_blockdev_backup(backup, common->block_job_txn, &local_err);
1982 if (local_err) {
1983 error_propagate(errp, local_err);
1984 goto out;
1987 out:
1988 aio_context_release(aio_context);
1991 static void blockdev_backup_commit(BlkActionState *common)
1993 BlockdevBackupState *state = DO_UPCAST(BlockdevBackupState, common, common);
1994 AioContext *aio_context;
1996 aio_context = bdrv_get_aio_context(state->bs);
1997 aio_context_acquire(aio_context);
1999 assert(state->job);
2000 block_job_start(state->job);
2002 aio_context_release(aio_context);
2005 static void blockdev_backup_abort(BlkActionState *common)
2007 BlockdevBackupState *state = DO_UPCAST(BlockdevBackupState, common, common);
2009 if (state->job) {
2010 AioContext *aio_context;
2012 aio_context = bdrv_get_aio_context(state->bs);
2013 aio_context_acquire(aio_context);
2015 block_job_cancel_sync(state->job);
2017 aio_context_release(aio_context);
2021 static void blockdev_backup_clean(BlkActionState *common)
2023 BlockdevBackupState *state = DO_UPCAST(BlockdevBackupState, common, common);
2024 AioContext *aio_context;
2026 if (!state->bs) {
2027 return;
2030 aio_context = bdrv_get_aio_context(state->bs);
2031 aio_context_acquire(aio_context);
2033 bdrv_drained_end(state->bs);
2035 aio_context_release(aio_context);
2038 typedef struct BlockDirtyBitmapState {
2039 BlkActionState common;
2040 BdrvDirtyBitmap *bitmap;
2041 BlockDriverState *bs;
2042 HBitmap *backup;
2043 bool prepared;
2044 } BlockDirtyBitmapState;
2046 static void block_dirty_bitmap_add_prepare(BlkActionState *common,
2047 Error **errp)
2049 Error *local_err = NULL;
2050 BlockDirtyBitmapAdd *action;
2051 BlockDirtyBitmapState *state = DO_UPCAST(BlockDirtyBitmapState,
2052 common, common);
2054 if (action_check_completion_mode(common, errp) < 0) {
2055 return;
2058 action = common->action->u.block_dirty_bitmap_add.data;
2059 /* AIO context taken and released within qmp_block_dirty_bitmap_add */
2060 qmp_block_dirty_bitmap_add(action->node, action->name,
2061 action->has_granularity, action->granularity,
2062 action->has_persistent, action->persistent,
2063 action->has_autoload, action->autoload,
2064 &local_err);
2066 if (!local_err) {
2067 state->prepared = true;
2068 } else {
2069 error_propagate(errp, local_err);
2073 static void block_dirty_bitmap_add_abort(BlkActionState *common)
2075 BlockDirtyBitmapAdd *action;
2076 BlockDirtyBitmapState *state = DO_UPCAST(BlockDirtyBitmapState,
2077 common, common);
2079 action = common->action->u.block_dirty_bitmap_add.data;
2080 /* Should not be able to fail: IF the bitmap was added via .prepare(),
2081 * then the node reference and bitmap name must have been valid.
2083 if (state->prepared) {
2084 qmp_block_dirty_bitmap_remove(action->node, action->name, &error_abort);
2088 static void block_dirty_bitmap_clear_prepare(BlkActionState *common,
2089 Error **errp)
2091 BlockDirtyBitmapState *state = DO_UPCAST(BlockDirtyBitmapState,
2092 common, common);
2093 BlockDirtyBitmap *action;
2095 if (action_check_completion_mode(common, errp) < 0) {
2096 return;
2099 action = common->action->u.block_dirty_bitmap_clear.data;
2100 state->bitmap = block_dirty_bitmap_lookup(action->node,
2101 action->name,
2102 &state->bs,
2103 errp);
2104 if (!state->bitmap) {
2105 return;
2108 if (bdrv_dirty_bitmap_frozen(state->bitmap)) {
2109 error_setg(errp, "Cannot modify a frozen bitmap");
2110 return;
2111 } else if (!bdrv_dirty_bitmap_enabled(state->bitmap)) {
2112 error_setg(errp, "Cannot clear a disabled bitmap");
2113 return;
2114 } else if (bdrv_dirty_bitmap_readonly(state->bitmap)) {
2115 error_setg(errp, "Cannot clear a readonly bitmap");
2116 return;
2119 bdrv_clear_dirty_bitmap(state->bitmap, &state->backup);
2122 static void block_dirty_bitmap_clear_abort(BlkActionState *common)
2124 BlockDirtyBitmapState *state = DO_UPCAST(BlockDirtyBitmapState,
2125 common, common);
2127 if (state->backup) {
2128 bdrv_undo_clear_dirty_bitmap(state->bitmap, state->backup);
2132 static void block_dirty_bitmap_clear_commit(BlkActionState *common)
2134 BlockDirtyBitmapState *state = DO_UPCAST(BlockDirtyBitmapState,
2135 common, common);
2137 hbitmap_free(state->backup);
2140 static void abort_prepare(BlkActionState *common, Error **errp)
2142 error_setg(errp, "Transaction aborted using Abort action");
2145 static void abort_commit(BlkActionState *common)
2147 g_assert_not_reached(); /* this action never succeeds */
2150 static const BlkActionOps actions[] = {
2151 [TRANSACTION_ACTION_KIND_BLOCKDEV_SNAPSHOT] = {
2152 .instance_size = sizeof(ExternalSnapshotState),
2153 .prepare = external_snapshot_prepare,
2154 .commit = external_snapshot_commit,
2155 .abort = external_snapshot_abort,
2156 .clean = external_snapshot_clean,
2158 [TRANSACTION_ACTION_KIND_BLOCKDEV_SNAPSHOT_SYNC] = {
2159 .instance_size = sizeof(ExternalSnapshotState),
2160 .prepare = external_snapshot_prepare,
2161 .commit = external_snapshot_commit,
2162 .abort = external_snapshot_abort,
2163 .clean = external_snapshot_clean,
2165 [TRANSACTION_ACTION_KIND_DRIVE_BACKUP] = {
2166 .instance_size = sizeof(DriveBackupState),
2167 .prepare = drive_backup_prepare,
2168 .commit = drive_backup_commit,
2169 .abort = drive_backup_abort,
2170 .clean = drive_backup_clean,
2172 [TRANSACTION_ACTION_KIND_BLOCKDEV_BACKUP] = {
2173 .instance_size = sizeof(BlockdevBackupState),
2174 .prepare = blockdev_backup_prepare,
2175 .commit = blockdev_backup_commit,
2176 .abort = blockdev_backup_abort,
2177 .clean = blockdev_backup_clean,
2179 [TRANSACTION_ACTION_KIND_ABORT] = {
2180 .instance_size = sizeof(BlkActionState),
2181 .prepare = abort_prepare,
2182 .commit = abort_commit,
2184 [TRANSACTION_ACTION_KIND_BLOCKDEV_SNAPSHOT_INTERNAL_SYNC] = {
2185 .instance_size = sizeof(InternalSnapshotState),
2186 .prepare = internal_snapshot_prepare,
2187 .abort = internal_snapshot_abort,
2188 .clean = internal_snapshot_clean,
2190 [TRANSACTION_ACTION_KIND_BLOCK_DIRTY_BITMAP_ADD] = {
2191 .instance_size = sizeof(BlockDirtyBitmapState),
2192 .prepare = block_dirty_bitmap_add_prepare,
2193 .abort = block_dirty_bitmap_add_abort,
2195 [TRANSACTION_ACTION_KIND_BLOCK_DIRTY_BITMAP_CLEAR] = {
2196 .instance_size = sizeof(BlockDirtyBitmapState),
2197 .prepare = block_dirty_bitmap_clear_prepare,
2198 .commit = block_dirty_bitmap_clear_commit,
2199 .abort = block_dirty_bitmap_clear_abort,
2204 * Allocate a TransactionProperties structure if necessary, and fill
2205 * that structure with desired defaults if they are unset.
2207 static TransactionProperties *get_transaction_properties(
2208 TransactionProperties *props)
2210 if (!props) {
2211 props = g_new0(TransactionProperties, 1);
2214 if (!props->has_completion_mode) {
2215 props->has_completion_mode = true;
2216 props->completion_mode = ACTION_COMPLETION_MODE_INDIVIDUAL;
2219 return props;
2223 * 'Atomic' group operations. The operations are performed as a set, and if
2224 * any fail then we roll back all operations in the group.
2226 void qmp_transaction(TransactionActionList *dev_list,
2227 bool has_props,
2228 struct TransactionProperties *props,
2229 Error **errp)
2231 TransactionActionList *dev_entry = dev_list;
2232 BlockJobTxn *block_job_txn = NULL;
2233 BlkActionState *state, *next;
2234 Error *local_err = NULL;
2236 QSIMPLEQ_HEAD(snap_bdrv_states, BlkActionState) snap_bdrv_states;
2237 QSIMPLEQ_INIT(&snap_bdrv_states);
2239 /* Does this transaction get canceled as a group on failure?
2240 * If not, we don't really need to make a BlockJobTxn.
2242 props = get_transaction_properties(props);
2243 if (props->completion_mode != ACTION_COMPLETION_MODE_INDIVIDUAL) {
2244 block_job_txn = block_job_txn_new();
2247 /* drain all i/o before any operations */
2248 bdrv_drain_all();
2250 /* We don't do anything in this loop that commits us to the operations */
2251 while (NULL != dev_entry) {
2252 TransactionAction *dev_info = NULL;
2253 const BlkActionOps *ops;
2255 dev_info = dev_entry->value;
2256 dev_entry = dev_entry->next;
2258 assert(dev_info->type < ARRAY_SIZE(actions));
2260 ops = &actions[dev_info->type];
2261 assert(ops->instance_size > 0);
2263 state = g_malloc0(ops->instance_size);
2264 state->ops = ops;
2265 state->action = dev_info;
2266 state->block_job_txn = block_job_txn;
2267 state->txn_props = props;
2268 QSIMPLEQ_INSERT_TAIL(&snap_bdrv_states, state, entry);
2270 state->ops->prepare(state, &local_err);
2271 if (local_err) {
2272 error_propagate(errp, local_err);
2273 goto delete_and_fail;
2277 QSIMPLEQ_FOREACH(state, &snap_bdrv_states, entry) {
2278 if (state->ops->commit) {
2279 state->ops->commit(state);
2283 /* success */
2284 goto exit;
2286 delete_and_fail:
2287 /* failure, and it is all-or-none; roll back all operations */
2288 QSIMPLEQ_FOREACH(state, &snap_bdrv_states, entry) {
2289 if (state->ops->abort) {
2290 state->ops->abort(state);
2293 exit:
2294 QSIMPLEQ_FOREACH_SAFE(state, &snap_bdrv_states, entry, next) {
2295 if (state->ops->clean) {
2296 state->ops->clean(state);
2298 g_free(state);
2300 if (!has_props) {
2301 qapi_free_TransactionProperties(props);
2303 block_job_txn_unref(block_job_txn);
2306 void qmp_eject(bool has_device, const char *device,
2307 bool has_id, const char *id,
2308 bool has_force, bool force, Error **errp)
2310 Error *local_err = NULL;
2311 int rc;
2313 if (!has_force) {
2314 force = false;
2317 rc = do_open_tray(has_device ? device : NULL,
2318 has_id ? id : NULL,
2319 force, &local_err);
2320 if (rc && rc != -ENOSYS) {
2321 error_propagate(errp, local_err);
2322 return;
2324 error_free(local_err);
2326 qmp_x_blockdev_remove_medium(has_device, device, has_id, id, errp);
2329 void qmp_block_passwd(bool has_device, const char *device,
2330 bool has_node_name, const char *node_name,
2331 const char *password, Error **errp)
2333 error_setg(errp,
2334 "Setting block passwords directly is no longer supported");
2338 * Attempt to open the tray of @device.
2339 * If @force, ignore its tray lock.
2340 * Else, if the tray is locked, don't open it, but ask the guest to open it.
2341 * On error, store an error through @errp and return -errno.
2342 * If @device does not exist, return -ENODEV.
2343 * If it has no removable media, return -ENOTSUP.
2344 * If it has no tray, return -ENOSYS.
2345 * If the guest was asked to open the tray, return -EINPROGRESS.
2346 * Else, return 0.
2348 static int do_open_tray(const char *blk_name, const char *qdev_id,
2349 bool force, Error **errp)
2351 BlockBackend *blk;
2352 const char *device = qdev_id ?: blk_name;
2353 bool locked;
2355 blk = qmp_get_blk(blk_name, qdev_id, errp);
2356 if (!blk) {
2357 return -ENODEV;
2360 if (!blk_dev_has_removable_media(blk)) {
2361 error_setg(errp, "Device '%s' is not removable", device);
2362 return -ENOTSUP;
2365 if (!blk_dev_has_tray(blk)) {
2366 error_setg(errp, "Device '%s' does not have a tray", device);
2367 return -ENOSYS;
2370 if (blk_dev_is_tray_open(blk)) {
2371 return 0;
2374 locked = blk_dev_is_medium_locked(blk);
2375 if (locked) {
2376 blk_dev_eject_request(blk, force);
2379 if (!locked || force) {
2380 blk_dev_change_media_cb(blk, false, &error_abort);
2383 if (locked && !force) {
2384 error_setg(errp, "Device '%s' is locked and force was not specified, "
2385 "wait for tray to open and try again", device);
2386 return -EINPROGRESS;
2389 return 0;
2392 void qmp_blockdev_open_tray(bool has_device, const char *device,
2393 bool has_id, const char *id,
2394 bool has_force, bool force,
2395 Error **errp)
2397 Error *local_err = NULL;
2398 int rc;
2400 if (!has_force) {
2401 force = false;
2403 rc = do_open_tray(has_device ? device : NULL,
2404 has_id ? id : NULL,
2405 force, &local_err);
2406 if (rc && rc != -ENOSYS && rc != -EINPROGRESS) {
2407 error_propagate(errp, local_err);
2408 return;
2410 error_free(local_err);
2413 void qmp_blockdev_close_tray(bool has_device, const char *device,
2414 bool has_id, const char *id,
2415 Error **errp)
2417 BlockBackend *blk;
2418 Error *local_err = NULL;
2420 device = has_device ? device : NULL;
2421 id = has_id ? id : NULL;
2423 blk = qmp_get_blk(device, id, errp);
2424 if (!blk) {
2425 return;
2428 if (!blk_dev_has_removable_media(blk)) {
2429 error_setg(errp, "Device '%s' is not removable", device ?: id);
2430 return;
2433 if (!blk_dev_has_tray(blk)) {
2434 /* Ignore this command on tray-less devices */
2435 return;
2438 if (!blk_dev_is_tray_open(blk)) {
2439 return;
2442 blk_dev_change_media_cb(blk, true, &local_err);
2443 if (local_err) {
2444 error_propagate(errp, local_err);
2445 return;
2449 void qmp_x_blockdev_remove_medium(bool has_device, const char *device,
2450 bool has_id, const char *id, Error **errp)
2452 BlockBackend *blk;
2453 BlockDriverState *bs;
2454 AioContext *aio_context;
2455 bool has_attached_device;
2457 device = has_device ? device : NULL;
2458 id = has_id ? id : NULL;
2460 blk = qmp_get_blk(device, id, errp);
2461 if (!blk) {
2462 return;
2465 /* For BBs without a device, we can exchange the BDS tree at will */
2466 has_attached_device = blk_get_attached_dev(blk);
2468 if (has_attached_device && !blk_dev_has_removable_media(blk)) {
2469 error_setg(errp, "Device '%s' is not removable", device ?: id);
2470 return;
2473 if (has_attached_device && blk_dev_has_tray(blk) &&
2474 !blk_dev_is_tray_open(blk))
2476 error_setg(errp, "Tray of device '%s' is not open", device ?: id);
2477 return;
2480 bs = blk_bs(blk);
2481 if (!bs) {
2482 return;
2485 aio_context = bdrv_get_aio_context(bs);
2486 aio_context_acquire(aio_context);
2488 if (bdrv_op_is_blocked(bs, BLOCK_OP_TYPE_EJECT, errp)) {
2489 goto out;
2492 blk_remove_bs(blk);
2494 if (!blk_dev_has_tray(blk)) {
2495 /* For tray-less devices, blockdev-open-tray is a no-op (or may not be
2496 * called at all); therefore, the medium needs to be ejected here.
2497 * Do it after blk_remove_bs() so blk_is_inserted(blk) returns the @load
2498 * value passed here (i.e. false). */
2499 blk_dev_change_media_cb(blk, false, &error_abort);
2502 out:
2503 aio_context_release(aio_context);
2506 static void qmp_blockdev_insert_anon_medium(BlockBackend *blk,
2507 BlockDriverState *bs, Error **errp)
2509 Error *local_err = NULL;
2510 bool has_device;
2511 int ret;
2513 /* For BBs without a device, we can exchange the BDS tree at will */
2514 has_device = blk_get_attached_dev(blk);
2516 if (has_device && !blk_dev_has_removable_media(blk)) {
2517 error_setg(errp, "Device is not removable");
2518 return;
2521 if (has_device && blk_dev_has_tray(blk) && !blk_dev_is_tray_open(blk)) {
2522 error_setg(errp, "Tray of the device is not open");
2523 return;
2526 if (blk_bs(blk)) {
2527 error_setg(errp, "There already is a medium in the device");
2528 return;
2531 ret = blk_insert_bs(blk, bs, errp);
2532 if (ret < 0) {
2533 return;
2536 if (!blk_dev_has_tray(blk)) {
2537 /* For tray-less devices, blockdev-close-tray is a no-op (or may not be
2538 * called at all); therefore, the medium needs to be pushed into the
2539 * slot here.
2540 * Do it after blk_insert_bs() so blk_is_inserted(blk) returns the @load
2541 * value passed here (i.e. true). */
2542 blk_dev_change_media_cb(blk, true, &local_err);
2543 if (local_err) {
2544 error_propagate(errp, local_err);
2545 blk_remove_bs(blk);
2546 return;
2551 void qmp_x_blockdev_insert_medium(bool has_device, const char *device,
2552 bool has_id, const char *id,
2553 const char *node_name, Error **errp)
2555 BlockBackend *blk;
2556 BlockDriverState *bs;
2558 blk = qmp_get_blk(has_device ? device : NULL,
2559 has_id ? id : NULL,
2560 errp);
2561 if (!blk) {
2562 return;
2565 bs = bdrv_find_node(node_name);
2566 if (!bs) {
2567 error_setg(errp, "Node '%s' not found", node_name);
2568 return;
2571 if (bdrv_has_blk(bs)) {
2572 error_setg(errp, "Node '%s' is already in use", node_name);
2573 return;
2576 qmp_blockdev_insert_anon_medium(blk, bs, errp);
2579 void qmp_blockdev_change_medium(bool has_device, const char *device,
2580 bool has_id, const char *id,
2581 const char *filename,
2582 bool has_format, const char *format,
2583 bool has_read_only,
2584 BlockdevChangeReadOnlyMode read_only,
2585 Error **errp)
2587 BlockBackend *blk;
2588 BlockDriverState *medium_bs = NULL;
2589 int bdrv_flags;
2590 bool detect_zeroes;
2591 int rc;
2592 QDict *options = NULL;
2593 Error *err = NULL;
2595 blk = qmp_get_blk(has_device ? device : NULL,
2596 has_id ? id : NULL,
2597 errp);
2598 if (!blk) {
2599 goto fail;
2602 if (blk_bs(blk)) {
2603 blk_update_root_state(blk);
2606 bdrv_flags = blk_get_open_flags_from_root_state(blk);
2607 bdrv_flags &= ~(BDRV_O_TEMPORARY | BDRV_O_SNAPSHOT | BDRV_O_NO_BACKING |
2608 BDRV_O_PROTOCOL);
2610 if (!has_read_only) {
2611 read_only = BLOCKDEV_CHANGE_READ_ONLY_MODE_RETAIN;
2614 switch (read_only) {
2615 case BLOCKDEV_CHANGE_READ_ONLY_MODE_RETAIN:
2616 break;
2618 case BLOCKDEV_CHANGE_READ_ONLY_MODE_READ_ONLY:
2619 bdrv_flags &= ~BDRV_O_RDWR;
2620 break;
2622 case BLOCKDEV_CHANGE_READ_ONLY_MODE_READ_WRITE:
2623 bdrv_flags |= BDRV_O_RDWR;
2624 break;
2626 default:
2627 abort();
2630 options = qdict_new();
2631 detect_zeroes = blk_get_detect_zeroes_from_root_state(blk);
2632 qdict_put_str(options, "detect-zeroes", detect_zeroes ? "on" : "off");
2634 if (has_format) {
2635 qdict_put_str(options, "driver", format);
2638 medium_bs = bdrv_open(filename, NULL, options, bdrv_flags, errp);
2639 if (!medium_bs) {
2640 goto fail;
2643 rc = do_open_tray(has_device ? device : NULL,
2644 has_id ? id : NULL,
2645 false, &err);
2646 if (rc && rc != -ENOSYS) {
2647 error_propagate(errp, err);
2648 goto fail;
2650 error_free(err);
2651 err = NULL;
2653 qmp_x_blockdev_remove_medium(has_device, device, has_id, id, &err);
2654 if (err) {
2655 error_propagate(errp, err);
2656 goto fail;
2659 qmp_blockdev_insert_anon_medium(blk, medium_bs, &err);
2660 if (err) {
2661 error_propagate(errp, err);
2662 goto fail;
2665 qmp_blockdev_close_tray(has_device, device, has_id, id, errp);
2667 fail:
2668 /* If the medium has been inserted, the device has its own reference, so
2669 * ours must be relinquished; and if it has not been inserted successfully,
2670 * the reference must be relinquished anyway */
2671 bdrv_unref(medium_bs);
2674 /* throttling disk I/O limits */
2675 void qmp_block_set_io_throttle(BlockIOThrottle *arg, Error **errp)
2677 ThrottleConfig cfg;
2678 BlockDriverState *bs;
2679 BlockBackend *blk;
2680 AioContext *aio_context;
2682 blk = qmp_get_blk(arg->has_device ? arg->device : NULL,
2683 arg->has_id ? arg->id : NULL,
2684 errp);
2685 if (!blk) {
2686 return;
2689 aio_context = blk_get_aio_context(blk);
2690 aio_context_acquire(aio_context);
2692 bs = blk_bs(blk);
2693 if (!bs) {
2694 error_setg(errp, "Device has no medium");
2695 goto out;
2698 throttle_config_init(&cfg);
2699 cfg.buckets[THROTTLE_BPS_TOTAL].avg = arg->bps;
2700 cfg.buckets[THROTTLE_BPS_READ].avg = arg->bps_rd;
2701 cfg.buckets[THROTTLE_BPS_WRITE].avg = arg->bps_wr;
2703 cfg.buckets[THROTTLE_OPS_TOTAL].avg = arg->iops;
2704 cfg.buckets[THROTTLE_OPS_READ].avg = arg->iops_rd;
2705 cfg.buckets[THROTTLE_OPS_WRITE].avg = arg->iops_wr;
2707 if (arg->has_bps_max) {
2708 cfg.buckets[THROTTLE_BPS_TOTAL].max = arg->bps_max;
2710 if (arg->has_bps_rd_max) {
2711 cfg.buckets[THROTTLE_BPS_READ].max = arg->bps_rd_max;
2713 if (arg->has_bps_wr_max) {
2714 cfg.buckets[THROTTLE_BPS_WRITE].max = arg->bps_wr_max;
2716 if (arg->has_iops_max) {
2717 cfg.buckets[THROTTLE_OPS_TOTAL].max = arg->iops_max;
2719 if (arg->has_iops_rd_max) {
2720 cfg.buckets[THROTTLE_OPS_READ].max = arg->iops_rd_max;
2722 if (arg->has_iops_wr_max) {
2723 cfg.buckets[THROTTLE_OPS_WRITE].max = arg->iops_wr_max;
2726 if (arg->has_bps_max_length) {
2727 cfg.buckets[THROTTLE_BPS_TOTAL].burst_length = arg->bps_max_length;
2729 if (arg->has_bps_rd_max_length) {
2730 cfg.buckets[THROTTLE_BPS_READ].burst_length = arg->bps_rd_max_length;
2732 if (arg->has_bps_wr_max_length) {
2733 cfg.buckets[THROTTLE_BPS_WRITE].burst_length = arg->bps_wr_max_length;
2735 if (arg->has_iops_max_length) {
2736 cfg.buckets[THROTTLE_OPS_TOTAL].burst_length = arg->iops_max_length;
2738 if (arg->has_iops_rd_max_length) {
2739 cfg.buckets[THROTTLE_OPS_READ].burst_length = arg->iops_rd_max_length;
2741 if (arg->has_iops_wr_max_length) {
2742 cfg.buckets[THROTTLE_OPS_WRITE].burst_length = arg->iops_wr_max_length;
2745 if (arg->has_iops_size) {
2746 cfg.op_size = arg->iops_size;
2749 if (!throttle_is_valid(&cfg, errp)) {
2750 goto out;
2753 if (throttle_enabled(&cfg)) {
2754 /* Enable I/O limits if they're not enabled yet, otherwise
2755 * just update the throttling group. */
2756 if (!blk_get_public(blk)->throttle_group_member.throttle_state) {
2757 blk_io_limits_enable(blk,
2758 arg->has_group ? arg->group :
2759 arg->has_device ? arg->device :
2760 arg->id);
2761 } else if (arg->has_group) {
2762 blk_io_limits_update_group(blk, arg->group);
2764 /* Set the new throttling configuration */
2765 blk_set_io_limits(blk, &cfg);
2766 } else if (blk_get_public(blk)->throttle_group_member.throttle_state) {
2767 /* If all throttling settings are set to 0, disable I/O limits */
2768 blk_io_limits_disable(blk);
2771 out:
2772 aio_context_release(aio_context);
2775 void qmp_block_dirty_bitmap_add(const char *node, const char *name,
2776 bool has_granularity, uint32_t granularity,
2777 bool has_persistent, bool persistent,
2778 bool has_autoload, bool autoload,
2779 Error **errp)
2781 BlockDriverState *bs;
2782 BdrvDirtyBitmap *bitmap;
2784 if (!name || name[0] == '\0') {
2785 error_setg(errp, "Bitmap name cannot be empty");
2786 return;
2789 bs = bdrv_lookup_bs(node, node, errp);
2790 if (!bs) {
2791 return;
2794 if (has_granularity) {
2795 if (granularity < 512 || !is_power_of_2(granularity)) {
2796 error_setg(errp, "Granularity must be power of 2 "
2797 "and at least 512");
2798 return;
2800 } else {
2801 /* Default to cluster size, if available: */
2802 granularity = bdrv_get_default_bitmap_granularity(bs);
2805 if (!has_persistent) {
2806 persistent = false;
2808 if (!has_autoload) {
2809 autoload = false;
2812 if (has_autoload && !persistent) {
2813 error_setg(errp, "Autoload flag must be used only for persistent "
2814 "bitmaps");
2815 return;
2818 if (persistent &&
2819 !bdrv_can_store_new_dirty_bitmap(bs, name, granularity, errp))
2821 return;
2824 bitmap = bdrv_create_dirty_bitmap(bs, granularity, name, errp);
2825 if (bitmap == NULL) {
2826 return;
2829 bdrv_dirty_bitmap_set_persistance(bitmap, persistent);
2830 bdrv_dirty_bitmap_set_autoload(bitmap, autoload);
2833 void qmp_block_dirty_bitmap_remove(const char *node, const char *name,
2834 Error **errp)
2836 BlockDriverState *bs;
2837 BdrvDirtyBitmap *bitmap;
2838 Error *local_err = NULL;
2840 bitmap = block_dirty_bitmap_lookup(node, name, &bs, errp);
2841 if (!bitmap || !bs) {
2842 return;
2845 if (bdrv_dirty_bitmap_frozen(bitmap)) {
2846 error_setg(errp,
2847 "Bitmap '%s' is currently frozen and cannot be removed",
2848 name);
2849 return;
2852 if (bdrv_dirty_bitmap_get_persistance(bitmap)) {
2853 bdrv_remove_persistent_dirty_bitmap(bs, name, &local_err);
2854 if (local_err != NULL) {
2855 error_propagate(errp, local_err);
2856 return;
2860 bdrv_dirty_bitmap_make_anon(bitmap);
2861 bdrv_release_dirty_bitmap(bs, bitmap);
2865 * Completely clear a bitmap, for the purposes of synchronizing a bitmap
2866 * immediately after a full backup operation.
2868 void qmp_block_dirty_bitmap_clear(const char *node, const char *name,
2869 Error **errp)
2871 BdrvDirtyBitmap *bitmap;
2872 BlockDriverState *bs;
2874 bitmap = block_dirty_bitmap_lookup(node, name, &bs, errp);
2875 if (!bitmap || !bs) {
2876 return;
2879 if (bdrv_dirty_bitmap_frozen(bitmap)) {
2880 error_setg(errp,
2881 "Bitmap '%s' is currently frozen and cannot be modified",
2882 name);
2883 return;
2884 } else if (!bdrv_dirty_bitmap_enabled(bitmap)) {
2885 error_setg(errp,
2886 "Bitmap '%s' is currently disabled and cannot be cleared",
2887 name);
2888 return;
2889 } else if (bdrv_dirty_bitmap_readonly(bitmap)) {
2890 error_setg(errp, "Bitmap '%s' is readonly and cannot be cleared", name);
2891 return;
2894 bdrv_clear_dirty_bitmap(bitmap, NULL);
2897 BlockDirtyBitmapSha256 *qmp_x_debug_block_dirty_bitmap_sha256(const char *node,
2898 const char *name,
2899 Error **errp)
2901 BdrvDirtyBitmap *bitmap;
2902 BlockDriverState *bs;
2903 BlockDirtyBitmapSha256 *ret = NULL;
2904 char *sha256;
2906 bitmap = block_dirty_bitmap_lookup(node, name, &bs, errp);
2907 if (!bitmap || !bs) {
2908 return NULL;
2911 sha256 = bdrv_dirty_bitmap_sha256(bitmap, errp);
2912 if (sha256 == NULL) {
2913 return NULL;
2916 ret = g_new(BlockDirtyBitmapSha256, 1);
2917 ret->sha256 = sha256;
2919 return ret;
2922 void hmp_drive_del(Monitor *mon, const QDict *qdict)
2924 const char *id = qdict_get_str(qdict, "id");
2925 BlockBackend *blk;
2926 BlockDriverState *bs;
2927 AioContext *aio_context;
2928 Error *local_err = NULL;
2930 bs = bdrv_find_node(id);
2931 if (bs) {
2932 qmp_blockdev_del(id, &local_err);
2933 if (local_err) {
2934 error_report_err(local_err);
2936 return;
2939 blk = blk_by_name(id);
2940 if (!blk) {
2941 error_report("Device '%s' not found", id);
2942 return;
2945 if (!blk_legacy_dinfo(blk)) {
2946 error_report("Deleting device added with blockdev-add"
2947 " is not supported");
2948 return;
2951 aio_context = blk_get_aio_context(blk);
2952 aio_context_acquire(aio_context);
2954 bs = blk_bs(blk);
2955 if (bs) {
2956 if (bdrv_op_is_blocked(bs, BLOCK_OP_TYPE_DRIVE_DEL, &local_err)) {
2957 error_report_err(local_err);
2958 aio_context_release(aio_context);
2959 return;
2962 blk_remove_bs(blk);
2965 /* Make the BlockBackend and the attached BlockDriverState anonymous */
2966 monitor_remove_blk(blk);
2968 /* If this BlockBackend has a device attached to it, its refcount will be
2969 * decremented when the device is removed; otherwise we have to do so here.
2971 if (blk_get_attached_dev(blk)) {
2972 /* Further I/O must not pause the guest */
2973 blk_set_on_error(blk, BLOCKDEV_ON_ERROR_REPORT,
2974 BLOCKDEV_ON_ERROR_REPORT);
2975 } else {
2976 blk_unref(blk);
2979 aio_context_release(aio_context);
2982 void qmp_block_resize(bool has_device, const char *device,
2983 bool has_node_name, const char *node_name,
2984 int64_t size, Error **errp)
2986 Error *local_err = NULL;
2987 BlockBackend *blk = NULL;
2988 BlockDriverState *bs;
2989 AioContext *aio_context;
2990 int ret;
2992 bs = bdrv_lookup_bs(has_device ? device : NULL,
2993 has_node_name ? node_name : NULL,
2994 &local_err);
2995 if (local_err) {
2996 error_propagate(errp, local_err);
2997 return;
3000 aio_context = bdrv_get_aio_context(bs);
3001 aio_context_acquire(aio_context);
3003 if (!bdrv_is_first_non_filter(bs)) {
3004 error_setg(errp, QERR_FEATURE_DISABLED, "resize");
3005 goto out;
3008 if (size < 0) {
3009 error_setg(errp, QERR_INVALID_PARAMETER_VALUE, "size", "a >0 size");
3010 goto out;
3013 if (bdrv_op_is_blocked(bs, BLOCK_OP_TYPE_RESIZE, NULL)) {
3014 error_setg(errp, QERR_DEVICE_IN_USE, device);
3015 goto out;
3018 blk = blk_new(BLK_PERM_RESIZE, BLK_PERM_ALL);
3019 ret = blk_insert_bs(blk, bs, errp);
3020 if (ret < 0) {
3021 goto out;
3024 bdrv_drained_begin(bs);
3025 ret = blk_truncate(blk, size, PREALLOC_MODE_OFF, errp);
3026 bdrv_drained_end(bs);
3028 out:
3029 blk_unref(blk);
3030 aio_context_release(aio_context);
3033 void qmp_block_stream(bool has_job_id, const char *job_id, const char *device,
3034 bool has_base, const char *base,
3035 bool has_base_node, const char *base_node,
3036 bool has_backing_file, const char *backing_file,
3037 bool has_speed, int64_t speed,
3038 bool has_on_error, BlockdevOnError on_error,
3039 Error **errp)
3041 BlockDriverState *bs, *iter;
3042 BlockDriverState *base_bs = NULL;
3043 AioContext *aio_context;
3044 Error *local_err = NULL;
3045 const char *base_name = NULL;
3047 if (!has_on_error) {
3048 on_error = BLOCKDEV_ON_ERROR_REPORT;
3051 bs = bdrv_lookup_bs(device, device, errp);
3052 if (!bs) {
3053 return;
3056 aio_context = bdrv_get_aio_context(bs);
3057 aio_context_acquire(aio_context);
3059 if (has_base && has_base_node) {
3060 error_setg(errp, "'base' and 'base-node' cannot be specified "
3061 "at the same time");
3062 goto out;
3065 if (has_base) {
3066 base_bs = bdrv_find_backing_image(bs, base);
3067 if (base_bs == NULL) {
3068 error_setg(errp, QERR_BASE_NOT_FOUND, base);
3069 goto out;
3071 assert(bdrv_get_aio_context(base_bs) == aio_context);
3072 base_name = base;
3075 if (has_base_node) {
3076 base_bs = bdrv_lookup_bs(NULL, base_node, errp);
3077 if (!base_bs) {
3078 goto out;
3080 if (bs == base_bs || !bdrv_chain_contains(bs, base_bs)) {
3081 error_setg(errp, "Node '%s' is not a backing image of '%s'",
3082 base_node, device);
3083 goto out;
3085 assert(bdrv_get_aio_context(base_bs) == aio_context);
3086 base_name = base_bs->filename;
3089 /* Check for op blockers in the whole chain between bs and base */
3090 for (iter = bs; iter && iter != base_bs; iter = backing_bs(iter)) {
3091 if (bdrv_op_is_blocked(iter, BLOCK_OP_TYPE_STREAM, errp)) {
3092 goto out;
3096 /* if we are streaming the entire chain, the result will have no backing
3097 * file, and specifying one is therefore an error */
3098 if (base_bs == NULL && has_backing_file) {
3099 error_setg(errp, "backing file specified, but streaming the "
3100 "entire chain");
3101 goto out;
3104 /* backing_file string overrides base bs filename */
3105 base_name = has_backing_file ? backing_file : base_name;
3107 stream_start(has_job_id ? job_id : NULL, bs, base_bs, base_name,
3108 has_speed ? speed : 0, on_error, &local_err);
3109 if (local_err) {
3110 error_propagate(errp, local_err);
3111 goto out;
3114 trace_qmp_block_stream(bs, bs->job);
3116 out:
3117 aio_context_release(aio_context);
3120 void qmp_block_commit(bool has_job_id, const char *job_id, const char *device,
3121 bool has_base, const char *base,
3122 bool has_top, const char *top,
3123 bool has_backing_file, const char *backing_file,
3124 bool has_speed, int64_t speed,
3125 bool has_filter_node_name, const char *filter_node_name,
3126 Error **errp)
3128 BlockDriverState *bs;
3129 BlockDriverState *iter;
3130 BlockDriverState *base_bs, *top_bs;
3131 AioContext *aio_context;
3132 Error *local_err = NULL;
3133 /* This will be part of the QMP command, if/when the
3134 * BlockdevOnError change for blkmirror makes it in
3136 BlockdevOnError on_error = BLOCKDEV_ON_ERROR_REPORT;
3138 if (!has_speed) {
3139 speed = 0;
3141 if (!has_filter_node_name) {
3142 filter_node_name = NULL;
3145 /* Important Note:
3146 * libvirt relies on the DeviceNotFound error class in order to probe for
3147 * live commit feature versions; for this to work, we must make sure to
3148 * perform the device lookup before any generic errors that may occur in a
3149 * scenario in which all optional arguments are omitted. */
3150 bs = qmp_get_root_bs(device, &local_err);
3151 if (!bs) {
3152 bs = bdrv_lookup_bs(device, device, NULL);
3153 if (!bs) {
3154 error_free(local_err);
3155 error_set(errp, ERROR_CLASS_DEVICE_NOT_FOUND,
3156 "Device '%s' not found", device);
3157 } else {
3158 error_propagate(errp, local_err);
3160 return;
3163 aio_context = bdrv_get_aio_context(bs);
3164 aio_context_acquire(aio_context);
3166 if (bdrv_op_is_blocked(bs, BLOCK_OP_TYPE_COMMIT_SOURCE, errp)) {
3167 goto out;
3170 /* default top_bs is the active layer */
3171 top_bs = bs;
3173 if (has_top && top) {
3174 if (strcmp(bs->filename, top) != 0) {
3175 top_bs = bdrv_find_backing_image(bs, top);
3179 if (top_bs == NULL) {
3180 error_setg(errp, "Top image file %s not found", top ? top : "NULL");
3181 goto out;
3184 assert(bdrv_get_aio_context(top_bs) == aio_context);
3186 if (has_base && base) {
3187 base_bs = bdrv_find_backing_image(top_bs, base);
3188 } else {
3189 base_bs = bdrv_find_base(top_bs);
3192 if (base_bs == NULL) {
3193 error_setg(errp, QERR_BASE_NOT_FOUND, base ? base : "NULL");
3194 goto out;
3197 assert(bdrv_get_aio_context(base_bs) == aio_context);
3199 for (iter = top_bs; iter != backing_bs(base_bs); iter = backing_bs(iter)) {
3200 if (bdrv_op_is_blocked(iter, BLOCK_OP_TYPE_COMMIT_TARGET, errp)) {
3201 goto out;
3205 /* Do not allow attempts to commit an image into itself */
3206 if (top_bs == base_bs) {
3207 error_setg(errp, "cannot commit an image into itself");
3208 goto out;
3211 if (top_bs == bs) {
3212 if (has_backing_file) {
3213 error_setg(errp, "'backing-file' specified,"
3214 " but 'top' is the active layer");
3215 goto out;
3217 commit_active_start(has_job_id ? job_id : NULL, bs, base_bs,
3218 BLOCK_JOB_DEFAULT, speed, on_error,
3219 filter_node_name, NULL, NULL, false, &local_err);
3220 } else {
3221 BlockDriverState *overlay_bs = bdrv_find_overlay(bs, top_bs);
3222 if (bdrv_op_is_blocked(overlay_bs, BLOCK_OP_TYPE_COMMIT_TARGET, errp)) {
3223 goto out;
3225 commit_start(has_job_id ? job_id : NULL, bs, base_bs, top_bs, speed,
3226 on_error, has_backing_file ? backing_file : NULL,
3227 filter_node_name, &local_err);
3229 if (local_err != NULL) {
3230 error_propagate(errp, local_err);
3231 goto out;
3234 out:
3235 aio_context_release(aio_context);
3238 static BlockJob *do_drive_backup(DriveBackup *backup, BlockJobTxn *txn,
3239 Error **errp)
3241 BlockDriverState *bs;
3242 BlockDriverState *target_bs;
3243 BlockDriverState *source = NULL;
3244 BlockJob *job = NULL;
3245 BdrvDirtyBitmap *bmap = NULL;
3246 AioContext *aio_context;
3247 QDict *options = NULL;
3248 Error *local_err = NULL;
3249 int flags;
3250 int64_t size;
3251 bool set_backing_hd = false;
3253 if (!backup->has_speed) {
3254 backup->speed = 0;
3256 if (!backup->has_on_source_error) {
3257 backup->on_source_error = BLOCKDEV_ON_ERROR_REPORT;
3259 if (!backup->has_on_target_error) {
3260 backup->on_target_error = BLOCKDEV_ON_ERROR_REPORT;
3262 if (!backup->has_mode) {
3263 backup->mode = NEW_IMAGE_MODE_ABSOLUTE_PATHS;
3265 if (!backup->has_job_id) {
3266 backup->job_id = NULL;
3268 if (!backup->has_compress) {
3269 backup->compress = false;
3272 bs = qmp_get_root_bs(backup->device, errp);
3273 if (!bs) {
3274 return NULL;
3277 aio_context = bdrv_get_aio_context(bs);
3278 aio_context_acquire(aio_context);
3280 if (!backup->has_format) {
3281 backup->format = backup->mode == NEW_IMAGE_MODE_EXISTING ?
3282 NULL : (char*) bs->drv->format_name;
3285 /* Early check to avoid creating target */
3286 if (bdrv_op_is_blocked(bs, BLOCK_OP_TYPE_BACKUP_SOURCE, errp)) {
3287 goto out;
3290 flags = bs->open_flags | BDRV_O_RDWR;
3292 /* See if we have a backing HD we can use to create our new image
3293 * on top of. */
3294 if (backup->sync == MIRROR_SYNC_MODE_TOP) {
3295 source = backing_bs(bs);
3296 if (!source) {
3297 backup->sync = MIRROR_SYNC_MODE_FULL;
3300 if (backup->sync == MIRROR_SYNC_MODE_NONE) {
3301 source = bs;
3302 flags |= BDRV_O_NO_BACKING;
3303 set_backing_hd = true;
3306 size = bdrv_getlength(bs);
3307 if (size < 0) {
3308 error_setg_errno(errp, -size, "bdrv_getlength failed");
3309 goto out;
3312 if (backup->mode != NEW_IMAGE_MODE_EXISTING) {
3313 assert(backup->format);
3314 if (source) {
3315 bdrv_img_create(backup->target, backup->format, source->filename,
3316 source->drv->format_name, NULL,
3317 size, flags, false, &local_err);
3318 } else {
3319 bdrv_img_create(backup->target, backup->format, NULL, NULL, NULL,
3320 size, flags, false, &local_err);
3324 if (local_err) {
3325 error_propagate(errp, local_err);
3326 goto out;
3329 if (backup->format) {
3330 if (!options) {
3331 options = qdict_new();
3333 qdict_put_str(options, "driver", backup->format);
3336 target_bs = bdrv_open(backup->target, NULL, options, flags, errp);
3337 if (!target_bs) {
3338 goto out;
3341 bdrv_set_aio_context(target_bs, aio_context);
3343 if (set_backing_hd) {
3344 bdrv_set_backing_hd(target_bs, source, &local_err);
3345 if (local_err) {
3346 bdrv_unref(target_bs);
3347 goto out;
3351 if (backup->has_bitmap) {
3352 bmap = bdrv_find_dirty_bitmap(bs, backup->bitmap);
3353 if (!bmap) {
3354 error_setg(errp, "Bitmap '%s' could not be found", backup->bitmap);
3355 bdrv_unref(target_bs);
3356 goto out;
3360 job = backup_job_create(backup->job_id, bs, target_bs, backup->speed,
3361 backup->sync, bmap, backup->compress,
3362 backup->on_source_error, backup->on_target_error,
3363 BLOCK_JOB_DEFAULT, NULL, NULL, txn, &local_err);
3364 bdrv_unref(target_bs);
3365 if (local_err != NULL) {
3366 error_propagate(errp, local_err);
3367 goto out;
3370 out:
3371 aio_context_release(aio_context);
3372 return job;
3375 void qmp_drive_backup(DriveBackup *arg, Error **errp)
3378 BlockJob *job;
3379 job = do_drive_backup(arg, NULL, errp);
3380 if (job) {
3381 block_job_start(job);
3385 BlockDeviceInfoList *qmp_query_named_block_nodes(Error **errp)
3387 return bdrv_named_nodes_list(errp);
3390 BlockJob *do_blockdev_backup(BlockdevBackup *backup, BlockJobTxn *txn,
3391 Error **errp)
3393 BlockDriverState *bs;
3394 BlockDriverState *target_bs;
3395 Error *local_err = NULL;
3396 AioContext *aio_context;
3397 BlockJob *job = NULL;
3399 if (!backup->has_speed) {
3400 backup->speed = 0;
3402 if (!backup->has_on_source_error) {
3403 backup->on_source_error = BLOCKDEV_ON_ERROR_REPORT;
3405 if (!backup->has_on_target_error) {
3406 backup->on_target_error = BLOCKDEV_ON_ERROR_REPORT;
3408 if (!backup->has_job_id) {
3409 backup->job_id = NULL;
3411 if (!backup->has_compress) {
3412 backup->compress = false;
3415 bs = qmp_get_root_bs(backup->device, errp);
3416 if (!bs) {
3417 return NULL;
3420 aio_context = bdrv_get_aio_context(bs);
3421 aio_context_acquire(aio_context);
3423 target_bs = bdrv_lookup_bs(backup->target, backup->target, errp);
3424 if (!target_bs) {
3425 goto out;
3428 if (bdrv_get_aio_context(target_bs) != aio_context) {
3429 if (!bdrv_has_blk(target_bs)) {
3430 /* The target BDS is not attached, we can safely move it to another
3431 * AioContext. */
3432 bdrv_set_aio_context(target_bs, aio_context);
3433 } else {
3434 error_setg(errp, "Target is attached to a different thread from "
3435 "source.");
3436 goto out;
3439 job = backup_job_create(backup->job_id, bs, target_bs, backup->speed,
3440 backup->sync, NULL, backup->compress,
3441 backup->on_source_error, backup->on_target_error,
3442 BLOCK_JOB_DEFAULT, NULL, NULL, txn, &local_err);
3443 if (local_err != NULL) {
3444 error_propagate(errp, local_err);
3446 out:
3447 aio_context_release(aio_context);
3448 return job;
3451 void qmp_blockdev_backup(BlockdevBackup *arg, Error **errp)
3453 BlockJob *job;
3454 job = do_blockdev_backup(arg, NULL, errp);
3455 if (job) {
3456 block_job_start(job);
3460 /* Parameter check and block job starting for drive mirroring.
3461 * Caller should hold @device and @target's aio context (must be the same).
3463 static void blockdev_mirror_common(const char *job_id, BlockDriverState *bs,
3464 BlockDriverState *target,
3465 bool has_replaces, const char *replaces,
3466 enum MirrorSyncMode sync,
3467 BlockMirrorBackingMode backing_mode,
3468 bool has_speed, int64_t speed,
3469 bool has_granularity, uint32_t granularity,
3470 bool has_buf_size, int64_t buf_size,
3471 bool has_on_source_error,
3472 BlockdevOnError on_source_error,
3473 bool has_on_target_error,
3474 BlockdevOnError on_target_error,
3475 bool has_unmap, bool unmap,
3476 bool has_filter_node_name,
3477 const char *filter_node_name,
3478 Error **errp)
3481 if (!has_speed) {
3482 speed = 0;
3484 if (!has_on_source_error) {
3485 on_source_error = BLOCKDEV_ON_ERROR_REPORT;
3487 if (!has_on_target_error) {
3488 on_target_error = BLOCKDEV_ON_ERROR_REPORT;
3490 if (!has_granularity) {
3491 granularity = 0;
3493 if (!has_buf_size) {
3494 buf_size = 0;
3496 if (!has_unmap) {
3497 unmap = true;
3499 if (!has_filter_node_name) {
3500 filter_node_name = NULL;
3503 if (granularity != 0 && (granularity < 512 || granularity > 1048576 * 64)) {
3504 error_setg(errp, QERR_INVALID_PARAMETER_VALUE, "granularity",
3505 "a value in range [512B, 64MB]");
3506 return;
3508 if (granularity & (granularity - 1)) {
3509 error_setg(errp, QERR_INVALID_PARAMETER_VALUE, "granularity",
3510 "power of 2");
3511 return;
3514 if (bdrv_op_is_blocked(bs, BLOCK_OP_TYPE_MIRROR_SOURCE, errp)) {
3515 return;
3517 if (bdrv_op_is_blocked(target, BLOCK_OP_TYPE_MIRROR_TARGET, errp)) {
3518 return;
3521 if (!bs->backing && sync == MIRROR_SYNC_MODE_TOP) {
3522 sync = MIRROR_SYNC_MODE_FULL;
3525 /* pass the node name to replace to mirror start since it's loose coupling
3526 * and will allow to check whether the node still exist at mirror completion
3528 mirror_start(job_id, bs, target,
3529 has_replaces ? replaces : NULL,
3530 speed, granularity, buf_size, sync, backing_mode,
3531 on_source_error, on_target_error, unmap, filter_node_name,
3532 errp);
3535 void qmp_drive_mirror(DriveMirror *arg, Error **errp)
3537 BlockDriverState *bs;
3538 BlockDriverState *source, *target_bs;
3539 AioContext *aio_context;
3540 BlockMirrorBackingMode backing_mode;
3541 Error *local_err = NULL;
3542 QDict *options = NULL;
3543 int flags;
3544 int64_t size;
3545 const char *format = arg->format;
3547 bs = qmp_get_root_bs(arg->device, errp);
3548 if (!bs) {
3549 return;
3552 aio_context = bdrv_get_aio_context(bs);
3553 aio_context_acquire(aio_context);
3555 if (!arg->has_mode) {
3556 arg->mode = NEW_IMAGE_MODE_ABSOLUTE_PATHS;
3559 if (!arg->has_format) {
3560 format = (arg->mode == NEW_IMAGE_MODE_EXISTING
3561 ? NULL : bs->drv->format_name);
3564 flags = bs->open_flags | BDRV_O_RDWR;
3565 source = backing_bs(bs);
3566 if (!source && arg->sync == MIRROR_SYNC_MODE_TOP) {
3567 arg->sync = MIRROR_SYNC_MODE_FULL;
3569 if (arg->sync == MIRROR_SYNC_MODE_NONE) {
3570 source = bs;
3573 size = bdrv_getlength(bs);
3574 if (size < 0) {
3575 error_setg_errno(errp, -size, "bdrv_getlength failed");
3576 goto out;
3579 if (arg->has_replaces) {
3580 BlockDriverState *to_replace_bs;
3581 AioContext *replace_aio_context;
3582 int64_t replace_size;
3584 if (!arg->has_node_name) {
3585 error_setg(errp, "a node-name must be provided when replacing a"
3586 " named node of the graph");
3587 goto out;
3590 to_replace_bs = check_to_replace_node(bs, arg->replaces, &local_err);
3592 if (!to_replace_bs) {
3593 error_propagate(errp, local_err);
3594 goto out;
3597 replace_aio_context = bdrv_get_aio_context(to_replace_bs);
3598 aio_context_acquire(replace_aio_context);
3599 replace_size = bdrv_getlength(to_replace_bs);
3600 aio_context_release(replace_aio_context);
3602 if (size != replace_size) {
3603 error_setg(errp, "cannot replace image with a mirror image of "
3604 "different size");
3605 goto out;
3609 if (arg->mode == NEW_IMAGE_MODE_ABSOLUTE_PATHS) {
3610 backing_mode = MIRROR_SOURCE_BACKING_CHAIN;
3611 } else {
3612 backing_mode = MIRROR_OPEN_BACKING_CHAIN;
3615 /* Don't open backing image in create() */
3616 flags |= BDRV_O_NO_BACKING;
3618 if ((arg->sync == MIRROR_SYNC_MODE_FULL || !source)
3619 && arg->mode != NEW_IMAGE_MODE_EXISTING)
3621 /* create new image w/o backing file */
3622 assert(format);
3623 bdrv_img_create(arg->target, format,
3624 NULL, NULL, NULL, size, flags, false, &local_err);
3625 } else {
3626 switch (arg->mode) {
3627 case NEW_IMAGE_MODE_EXISTING:
3628 break;
3629 case NEW_IMAGE_MODE_ABSOLUTE_PATHS:
3630 /* create new image with backing file */
3631 bdrv_img_create(arg->target, format,
3632 source->filename,
3633 source->drv->format_name,
3634 NULL, size, flags, false, &local_err);
3635 break;
3636 default:
3637 abort();
3641 if (local_err) {
3642 error_propagate(errp, local_err);
3643 goto out;
3646 options = qdict_new();
3647 if (arg->has_node_name) {
3648 qdict_put_str(options, "node-name", arg->node_name);
3650 if (format) {
3651 qdict_put_str(options, "driver", format);
3654 /* Mirroring takes care of copy-on-write using the source's backing
3655 * file.
3657 target_bs = bdrv_open(arg->target, NULL, options, flags, errp);
3658 if (!target_bs) {
3659 goto out;
3662 bdrv_set_aio_context(target_bs, aio_context);
3664 blockdev_mirror_common(arg->has_job_id ? arg->job_id : NULL, bs, target_bs,
3665 arg->has_replaces, arg->replaces, arg->sync,
3666 backing_mode, arg->has_speed, arg->speed,
3667 arg->has_granularity, arg->granularity,
3668 arg->has_buf_size, arg->buf_size,
3669 arg->has_on_source_error, arg->on_source_error,
3670 arg->has_on_target_error, arg->on_target_error,
3671 arg->has_unmap, arg->unmap,
3672 false, NULL,
3673 &local_err);
3674 bdrv_unref(target_bs);
3675 error_propagate(errp, local_err);
3676 out:
3677 aio_context_release(aio_context);
3680 void qmp_blockdev_mirror(bool has_job_id, const char *job_id,
3681 const char *device, const char *target,
3682 bool has_replaces, const char *replaces,
3683 MirrorSyncMode sync,
3684 bool has_speed, int64_t speed,
3685 bool has_granularity, uint32_t granularity,
3686 bool has_buf_size, int64_t buf_size,
3687 bool has_on_source_error,
3688 BlockdevOnError on_source_error,
3689 bool has_on_target_error,
3690 BlockdevOnError on_target_error,
3691 bool has_filter_node_name,
3692 const char *filter_node_name,
3693 Error **errp)
3695 BlockDriverState *bs;
3696 BlockDriverState *target_bs;
3697 AioContext *aio_context;
3698 BlockMirrorBackingMode backing_mode = MIRROR_LEAVE_BACKING_CHAIN;
3699 Error *local_err = NULL;
3701 bs = qmp_get_root_bs(device, errp);
3702 if (!bs) {
3703 return;
3706 target_bs = bdrv_lookup_bs(target, target, errp);
3707 if (!target_bs) {
3708 return;
3711 aio_context = bdrv_get_aio_context(bs);
3712 aio_context_acquire(aio_context);
3714 bdrv_set_aio_context(target_bs, aio_context);
3716 blockdev_mirror_common(has_job_id ? job_id : NULL, bs, target_bs,
3717 has_replaces, replaces, sync, backing_mode,
3718 has_speed, speed,
3719 has_granularity, granularity,
3720 has_buf_size, buf_size,
3721 has_on_source_error, on_source_error,
3722 has_on_target_error, on_target_error,
3723 true, true,
3724 has_filter_node_name, filter_node_name,
3725 &local_err);
3726 error_propagate(errp, local_err);
3728 aio_context_release(aio_context);
3731 /* Get a block job using its ID and acquire its AioContext */
3732 static BlockJob *find_block_job(const char *id, AioContext **aio_context,
3733 Error **errp)
3735 BlockJob *job;
3737 assert(id != NULL);
3739 *aio_context = NULL;
3741 job = block_job_get(id);
3743 if (!job) {
3744 error_set(errp, ERROR_CLASS_DEVICE_NOT_ACTIVE,
3745 "Block job '%s' not found", id);
3746 return NULL;
3749 *aio_context = blk_get_aio_context(job->blk);
3750 aio_context_acquire(*aio_context);
3752 return job;
3755 void qmp_block_job_set_speed(const char *device, int64_t speed, Error **errp)
3757 AioContext *aio_context;
3758 BlockJob *job = find_block_job(device, &aio_context, errp);
3760 if (!job) {
3761 return;
3764 block_job_set_speed(job, speed, errp);
3765 aio_context_release(aio_context);
3768 void qmp_block_job_cancel(const char *device,
3769 bool has_force, bool force, Error **errp)
3771 AioContext *aio_context;
3772 BlockJob *job = find_block_job(device, &aio_context, errp);
3774 if (!job) {
3775 return;
3778 if (!has_force) {
3779 force = false;
3782 if (block_job_user_paused(job) && !force) {
3783 error_setg(errp, "The block job for device '%s' is currently paused",
3784 device);
3785 goto out;
3788 trace_qmp_block_job_cancel(job);
3789 block_job_cancel(job);
3790 out:
3791 aio_context_release(aio_context);
3794 void qmp_block_job_pause(const char *device, Error **errp)
3796 AioContext *aio_context;
3797 BlockJob *job = find_block_job(device, &aio_context, errp);
3799 if (!job || block_job_user_paused(job)) {
3800 return;
3803 trace_qmp_block_job_pause(job);
3804 block_job_user_pause(job);
3805 aio_context_release(aio_context);
3808 void qmp_block_job_resume(const char *device, Error **errp)
3810 AioContext *aio_context;
3811 BlockJob *job = find_block_job(device, &aio_context, errp);
3813 if (!job || !block_job_user_paused(job)) {
3814 return;
3817 trace_qmp_block_job_resume(job);
3818 block_job_user_resume(job);
3819 aio_context_release(aio_context);
3822 void qmp_block_job_complete(const char *device, Error **errp)
3824 AioContext *aio_context;
3825 BlockJob *job = find_block_job(device, &aio_context, errp);
3827 if (!job) {
3828 return;
3831 trace_qmp_block_job_complete(job);
3832 block_job_complete(job, errp);
3833 aio_context_release(aio_context);
3836 void qmp_change_backing_file(const char *device,
3837 const char *image_node_name,
3838 const char *backing_file,
3839 Error **errp)
3841 BlockDriverState *bs = NULL;
3842 AioContext *aio_context;
3843 BlockDriverState *image_bs = NULL;
3844 Error *local_err = NULL;
3845 bool ro;
3846 int open_flags;
3847 int ret;
3849 bs = qmp_get_root_bs(device, errp);
3850 if (!bs) {
3851 return;
3854 aio_context = bdrv_get_aio_context(bs);
3855 aio_context_acquire(aio_context);
3857 image_bs = bdrv_lookup_bs(NULL, image_node_name, &local_err);
3858 if (local_err) {
3859 error_propagate(errp, local_err);
3860 goto out;
3863 if (!image_bs) {
3864 error_setg(errp, "image file not found");
3865 goto out;
3868 if (bdrv_find_base(image_bs) == image_bs) {
3869 error_setg(errp, "not allowing backing file change on an image "
3870 "without a backing file");
3871 goto out;
3874 /* even though we are not necessarily operating on bs, we need it to
3875 * determine if block ops are currently prohibited on the chain */
3876 if (bdrv_op_is_blocked(bs, BLOCK_OP_TYPE_CHANGE, errp)) {
3877 goto out;
3880 /* final sanity check */
3881 if (!bdrv_chain_contains(bs, image_bs)) {
3882 error_setg(errp, "'%s' and image file are not in the same chain",
3883 device);
3884 goto out;
3887 /* if not r/w, reopen to make r/w */
3888 open_flags = image_bs->open_flags;
3889 ro = bdrv_is_read_only(image_bs);
3891 if (ro) {
3892 bdrv_reopen(image_bs, open_flags | BDRV_O_RDWR, &local_err);
3893 if (local_err) {
3894 error_propagate(errp, local_err);
3895 goto out;
3899 ret = bdrv_change_backing_file(image_bs, backing_file,
3900 image_bs->drv ? image_bs->drv->format_name : "");
3902 if (ret < 0) {
3903 error_setg_errno(errp, -ret, "Could not change backing file to '%s'",
3904 backing_file);
3905 /* don't exit here, so we can try to restore open flags if
3906 * appropriate */
3909 if (ro) {
3910 bdrv_reopen(image_bs, open_flags, &local_err);
3911 error_propagate(errp, local_err);
3914 out:
3915 aio_context_release(aio_context);
3918 void hmp_drive_add_node(Monitor *mon, const char *optstr)
3920 QemuOpts *opts;
3921 QDict *qdict;
3922 Error *local_err = NULL;
3924 opts = qemu_opts_parse_noisily(&qemu_drive_opts, optstr, false);
3925 if (!opts) {
3926 return;
3929 qdict = qemu_opts_to_qdict(opts, NULL);
3931 if (!qdict_get_try_str(qdict, "node-name")) {
3932 QDECREF(qdict);
3933 error_report("'node-name' needs to be specified");
3934 goto out;
3937 BlockDriverState *bs = bds_tree_init(qdict, &local_err);
3938 if (!bs) {
3939 error_report_err(local_err);
3940 goto out;
3943 QTAILQ_INSERT_TAIL(&monitor_bdrv_states, bs, monitor_list);
3945 out:
3946 qemu_opts_del(opts);
3949 void qmp_blockdev_add(BlockdevOptions *options, Error **errp)
3951 BlockDriverState *bs;
3952 QObject *obj;
3953 Visitor *v = qobject_output_visitor_new(&obj);
3954 QDict *qdict;
3955 const QDictEntry *ent;
3956 Error *local_err = NULL;
3958 visit_type_BlockdevOptions(v, NULL, &options, &local_err);
3959 if (local_err) {
3960 error_propagate(errp, local_err);
3961 goto fail;
3964 visit_complete(v, &obj);
3965 qdict = qobject_to_qdict(obj);
3967 qdict_flatten(qdict);
3970 * Rewrite "backing": null to "backing": ""
3971 * TODO Rewrite "" to null instead, and perhaps not even here
3973 for (ent = qdict_first(qdict); ent; ent = qdict_next(qdict, ent)) {
3974 char *dot = strrchr(ent->key, '.');
3976 if (!strcmp(dot ? dot + 1 : ent->key, "backing")
3977 && qobject_type(ent->value) == QTYPE_QNULL) {
3978 qdict_put(qdict, ent->key, qstring_new());
3982 if (!qdict_get_try_str(qdict, "node-name")) {
3983 error_setg(errp, "'node-name' must be specified for the root node");
3984 goto fail;
3987 bs = bds_tree_init(qdict, errp);
3988 if (!bs) {
3989 goto fail;
3992 QTAILQ_INSERT_TAIL(&monitor_bdrv_states, bs, monitor_list);
3994 fail:
3995 visit_free(v);
3998 void qmp_blockdev_del(const char *node_name, Error **errp)
4000 AioContext *aio_context;
4001 BlockDriverState *bs;
4003 bs = bdrv_find_node(node_name);
4004 if (!bs) {
4005 error_setg(errp, "Cannot find node %s", node_name);
4006 return;
4008 if (bdrv_has_blk(bs)) {
4009 error_setg(errp, "Node %s is in use", node_name);
4010 return;
4012 aio_context = bdrv_get_aio_context(bs);
4013 aio_context_acquire(aio_context);
4015 if (bdrv_op_is_blocked(bs, BLOCK_OP_TYPE_DRIVE_DEL, errp)) {
4016 goto out;
4019 if (!bs->monitor_list.tqe_prev) {
4020 error_setg(errp, "Node %s is not owned by the monitor",
4021 bs->node_name);
4022 goto out;
4025 if (bs->refcnt > 1) {
4026 error_setg(errp, "Block device %s is in use",
4027 bdrv_get_device_or_node_name(bs));
4028 goto out;
4031 QTAILQ_REMOVE(&monitor_bdrv_states, bs, monitor_list);
4032 bdrv_unref(bs);
4034 out:
4035 aio_context_release(aio_context);
4038 static BdrvChild *bdrv_find_child(BlockDriverState *parent_bs,
4039 const char *child_name)
4041 BdrvChild *child;
4043 QLIST_FOREACH(child, &parent_bs->children, next) {
4044 if (strcmp(child->name, child_name) == 0) {
4045 return child;
4049 return NULL;
4052 void qmp_x_blockdev_change(const char *parent, bool has_child,
4053 const char *child, bool has_node,
4054 const char *node, Error **errp)
4056 BlockDriverState *parent_bs, *new_bs = NULL;
4057 BdrvChild *p_child;
4059 parent_bs = bdrv_lookup_bs(parent, parent, errp);
4060 if (!parent_bs) {
4061 return;
4064 if (has_child == has_node) {
4065 if (has_child) {
4066 error_setg(errp, "The parameters child and node are in conflict");
4067 } else {
4068 error_setg(errp, "Either child or node must be specified");
4070 return;
4073 if (has_child) {
4074 p_child = bdrv_find_child(parent_bs, child);
4075 if (!p_child) {
4076 error_setg(errp, "Node '%s' does not have child '%s'",
4077 parent, child);
4078 return;
4080 bdrv_del_child(parent_bs, p_child, errp);
4083 if (has_node) {
4084 new_bs = bdrv_find_node(node);
4085 if (!new_bs) {
4086 error_setg(errp, "Node '%s' not found", node);
4087 return;
4089 bdrv_add_child(parent_bs, new_bs, errp);
4093 BlockJobInfoList *qmp_query_block_jobs(Error **errp)
4095 BlockJobInfoList *head = NULL, **p_next = &head;
4096 BlockJob *job;
4098 for (job = block_job_next(NULL); job; job = block_job_next(job)) {
4099 BlockJobInfoList *elem;
4100 AioContext *aio_context;
4102 if (block_job_is_internal(job)) {
4103 continue;
4105 elem = g_new0(BlockJobInfoList, 1);
4106 aio_context = blk_get_aio_context(job->blk);
4107 aio_context_acquire(aio_context);
4108 elem->value = block_job_query(job, errp);
4109 aio_context_release(aio_context);
4110 if (!elem->value) {
4111 g_free(elem);
4112 qapi_free_BlockJobInfoList(head);
4113 return NULL;
4115 *p_next = elem;
4116 p_next = &elem->next;
4119 return head;
4122 void qmp_x_blockdev_set_iothread(const char *node_name, StrOrNull *iothread,
4123 bool has_force, bool force, Error **errp)
4125 AioContext *old_context;
4126 AioContext *new_context;
4127 BlockDriverState *bs;
4129 bs = bdrv_find_node(node_name);
4130 if (!bs) {
4131 error_setg(errp, "Cannot find node %s", node_name);
4132 return;
4135 /* Protects against accidents. */
4136 if (!(has_force && force) && bdrv_has_blk(bs)) {
4137 error_setg(errp, "Node %s is associated with a BlockBackend and could "
4138 "be in use (use force=true to override this check)",
4139 node_name);
4140 return;
4143 if (iothread->type == QTYPE_QSTRING) {
4144 IOThread *obj = iothread_by_id(iothread->u.s);
4145 if (!obj) {
4146 error_setg(errp, "Cannot find iothread %s", iothread->u.s);
4147 return;
4150 new_context = iothread_get_aio_context(obj);
4151 } else {
4152 new_context = qemu_get_aio_context();
4155 old_context = bdrv_get_aio_context(bs);
4156 aio_context_acquire(old_context);
4158 bdrv_set_aio_context(bs, new_context);
4160 aio_context_release(old_context);
4163 QemuOptsList qemu_common_drive_opts = {
4164 .name = "drive",
4165 .head = QTAILQ_HEAD_INITIALIZER(qemu_common_drive_opts.head),
4166 .desc = {
4168 .name = "snapshot",
4169 .type = QEMU_OPT_BOOL,
4170 .help = "enable/disable snapshot mode",
4172 .name = "aio",
4173 .type = QEMU_OPT_STRING,
4174 .help = "host AIO implementation (threads, native)",
4176 .name = BDRV_OPT_CACHE_WB,
4177 .type = QEMU_OPT_BOOL,
4178 .help = "Enable writeback mode",
4180 .name = "format",
4181 .type = QEMU_OPT_STRING,
4182 .help = "disk format (raw, qcow2, ...)",
4184 .name = "rerror",
4185 .type = QEMU_OPT_STRING,
4186 .help = "read error action",
4188 .name = "werror",
4189 .type = QEMU_OPT_STRING,
4190 .help = "write error action",
4192 .name = BDRV_OPT_READ_ONLY,
4193 .type = QEMU_OPT_BOOL,
4194 .help = "open drive file as read-only",
4197 THROTTLE_OPTS,
4200 .name = "throttling.group",
4201 .type = QEMU_OPT_STRING,
4202 .help = "name of the block throttling group",
4204 .name = "copy-on-read",
4205 .type = QEMU_OPT_BOOL,
4206 .help = "copy read data from backing file into image file",
4208 .name = "detect-zeroes",
4209 .type = QEMU_OPT_STRING,
4210 .help = "try to optimize zero writes (off, on, unmap)",
4212 .name = "stats-account-invalid",
4213 .type = QEMU_OPT_BOOL,
4214 .help = "whether to account for invalid I/O operations "
4215 "in the statistics",
4217 .name = "stats-account-failed",
4218 .type = QEMU_OPT_BOOL,
4219 .help = "whether to account for failed I/O operations "
4220 "in the statistics",
4222 { /* end of list */ }
4226 QemuOptsList qemu_drive_opts = {
4227 .name = "drive",
4228 .head = QTAILQ_HEAD_INITIALIZER(qemu_drive_opts.head),
4229 .desc = {
4231 * no elements => accept any params
4232 * validation will happen later
4234 { /* end of list */ }