block: drop unused BlockDirtyBitmapState->aio_context field
[qemu.git] / blockdev.c
blobe865ae4873d5aaae86e2a35bd0afe57254395270
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 "block/block_int.h"
49 #include "qmp-commands.h"
50 #include "block/trace.h"
51 #include "sysemu/arch_init.h"
52 #include "sysemu/qtest.h"
53 #include "qemu/cutils.h"
54 #include "qemu/help_option.h"
55 #include "qemu/throttle-options.h"
57 static QTAILQ_HEAD(, BlockDriverState) monitor_bdrv_states =
58 QTAILQ_HEAD_INITIALIZER(monitor_bdrv_states);
60 static int do_open_tray(const char *blk_name, const char *qdev_id,
61 bool force, Error **errp);
63 static const char *const if_name[IF_COUNT] = {
64 [IF_NONE] = "none",
65 [IF_IDE] = "ide",
66 [IF_SCSI] = "scsi",
67 [IF_FLOPPY] = "floppy",
68 [IF_PFLASH] = "pflash",
69 [IF_MTD] = "mtd",
70 [IF_SD] = "sd",
71 [IF_VIRTIO] = "virtio",
72 [IF_XEN] = "xen",
75 static int if_max_devs[IF_COUNT] = {
77 * Do not change these numbers! They govern how drive option
78 * index maps to unit and bus. That mapping is ABI.
80 * All controllers used to implement if=T drives need to support
81 * if_max_devs[T] units, for any T with if_max_devs[T] != 0.
82 * Otherwise, some index values map to "impossible" bus, unit
83 * values.
85 * For instance, if you change [IF_SCSI] to 255, -drive
86 * if=scsi,index=12 no longer means bus=1,unit=5, but
87 * bus=0,unit=12. With an lsi53c895a controller (7 units max),
88 * the drive can't be set up. Regression.
90 [IF_IDE] = 2,
91 [IF_SCSI] = 7,
94 /**
95 * Boards may call this to offer board-by-board overrides
96 * of the default, global values.
98 void override_max_devs(BlockInterfaceType type, int max_devs)
100 BlockBackend *blk;
101 DriveInfo *dinfo;
103 if (max_devs <= 0) {
104 return;
107 for (blk = blk_next(NULL); blk; blk = blk_next(blk)) {
108 dinfo = blk_legacy_dinfo(blk);
109 if (dinfo->type == type) {
110 fprintf(stderr, "Cannot override units-per-bus property of"
111 " the %s interface, because a drive of that type has"
112 " already been added.\n", if_name[type]);
113 g_assert_not_reached();
117 if_max_devs[type] = max_devs;
121 * We automatically delete the drive when a device using it gets
122 * unplugged. Questionable feature, but we can't just drop it.
123 * Device models call blockdev_mark_auto_del() to schedule the
124 * automatic deletion, and generic qdev code calls blockdev_auto_del()
125 * when deletion is actually safe.
127 void blockdev_mark_auto_del(BlockBackend *blk)
129 DriveInfo *dinfo = blk_legacy_dinfo(blk);
130 BlockDriverState *bs = blk_bs(blk);
131 AioContext *aio_context;
133 if (!dinfo) {
134 return;
137 if (bs) {
138 aio_context = bdrv_get_aio_context(bs);
139 aio_context_acquire(aio_context);
141 if (bs->job) {
142 block_job_cancel(bs->job);
145 aio_context_release(aio_context);
148 dinfo->auto_del = 1;
151 void blockdev_auto_del(BlockBackend *blk)
153 DriveInfo *dinfo = blk_legacy_dinfo(blk);
155 if (dinfo && dinfo->auto_del) {
156 monitor_remove_blk(blk);
157 blk_unref(blk);
162 * Returns the current mapping of how many units per bus
163 * a particular interface can support.
165 * A positive integer indicates n units per bus.
166 * 0 implies the mapping has not been established.
167 * -1 indicates an invalid BlockInterfaceType was given.
169 int drive_get_max_devs(BlockInterfaceType type)
171 if (type >= IF_IDE && type < IF_COUNT) {
172 return if_max_devs[type];
175 return -1;
178 static int drive_index_to_bus_id(BlockInterfaceType type, int index)
180 int max_devs = if_max_devs[type];
181 return max_devs ? index / max_devs : 0;
184 static int drive_index_to_unit_id(BlockInterfaceType type, int index)
186 int max_devs = if_max_devs[type];
187 return max_devs ? index % max_devs : index;
190 QemuOpts *drive_def(const char *optstr)
192 return qemu_opts_parse_noisily(qemu_find_opts("drive"), optstr, false);
195 QemuOpts *drive_add(BlockInterfaceType type, int index, const char *file,
196 const char *optstr)
198 QemuOpts *opts;
200 opts = drive_def(optstr);
201 if (!opts) {
202 return NULL;
204 if (type != IF_DEFAULT) {
205 qemu_opt_set(opts, "if", if_name[type], &error_abort);
207 if (index >= 0) {
208 qemu_opt_set_number(opts, "index", index, &error_abort);
210 if (file)
211 qemu_opt_set(opts, "file", file, &error_abort);
212 return opts;
215 DriveInfo *drive_get(BlockInterfaceType type, int bus, int unit)
217 BlockBackend *blk;
218 DriveInfo *dinfo;
220 for (blk = blk_next(NULL); blk; blk = blk_next(blk)) {
221 dinfo = blk_legacy_dinfo(blk);
222 if (dinfo && dinfo->type == type
223 && dinfo->bus == bus && dinfo->unit == unit) {
224 return dinfo;
228 return NULL;
231 void drive_check_orphaned(void)
233 BlockBackend *blk;
234 DriveInfo *dinfo;
235 Location loc;
236 bool orphans = false;
238 for (blk = blk_next(NULL); blk; blk = blk_next(blk)) {
239 dinfo = blk_legacy_dinfo(blk);
240 if (!blk_get_attached_dev(blk) && !dinfo->is_default &&
241 dinfo->type != IF_NONE) {
242 loc_push_none(&loc);
243 qemu_opts_loc_restore(dinfo->opts);
244 error_report("machine type does not support"
245 " if=%s,bus=%d,unit=%d",
246 if_name[dinfo->type], dinfo->bus, dinfo->unit);
247 loc_pop(&loc);
248 orphans = true;
252 if (orphans) {
253 exit(1);
257 DriveInfo *drive_get_by_index(BlockInterfaceType type, int index)
259 return drive_get(type,
260 drive_index_to_bus_id(type, index),
261 drive_index_to_unit_id(type, index));
264 int drive_get_max_bus(BlockInterfaceType type)
266 int max_bus;
267 BlockBackend *blk;
268 DriveInfo *dinfo;
270 max_bus = -1;
271 for (blk = blk_next(NULL); blk; blk = blk_next(blk)) {
272 dinfo = blk_legacy_dinfo(blk);
273 if (dinfo && dinfo->type == type && dinfo->bus > max_bus) {
274 max_bus = dinfo->bus;
277 return max_bus;
280 /* Get a block device. This should only be used for single-drive devices
281 (e.g. SD/Floppy/MTD). Multi-disk devices (scsi/ide) should use the
282 appropriate bus. */
283 DriveInfo *drive_get_next(BlockInterfaceType type)
285 static int next_block_unit[IF_COUNT];
287 return drive_get(type, 0, next_block_unit[type]++);
290 static void bdrv_format_print(void *opaque, const char *name)
292 error_printf(" %s", name);
295 typedef struct {
296 QEMUBH *bh;
297 BlockDriverState *bs;
298 } BDRVPutRefBH;
300 static int parse_block_error_action(const char *buf, bool is_read, Error **errp)
302 if (!strcmp(buf, "ignore")) {
303 return BLOCKDEV_ON_ERROR_IGNORE;
304 } else if (!is_read && !strcmp(buf, "enospc")) {
305 return BLOCKDEV_ON_ERROR_ENOSPC;
306 } else if (!strcmp(buf, "stop")) {
307 return BLOCKDEV_ON_ERROR_STOP;
308 } else if (!strcmp(buf, "report")) {
309 return BLOCKDEV_ON_ERROR_REPORT;
310 } else {
311 error_setg(errp, "'%s' invalid %s error action",
312 buf, is_read ? "read" : "write");
313 return -1;
317 static bool parse_stats_intervals(BlockAcctStats *stats, QList *intervals,
318 Error **errp)
320 const QListEntry *entry;
321 for (entry = qlist_first(intervals); entry; entry = qlist_next(entry)) {
322 switch (qobject_type(entry->value)) {
324 case QTYPE_QSTRING: {
325 unsigned long long length;
326 const char *str = qstring_get_str(qobject_to_qstring(entry->value));
327 if (parse_uint_full(str, &length, 10) == 0 &&
328 length > 0 && length <= UINT_MAX) {
329 block_acct_add_interval(stats, (unsigned) length);
330 } else {
331 error_setg(errp, "Invalid interval length: %s", str);
332 return false;
334 break;
337 case QTYPE_QNUM: {
338 int64_t length = qnum_get_int(qobject_to_qnum(entry->value));
340 if (length > 0 && length <= UINT_MAX) {
341 block_acct_add_interval(stats, (unsigned) length);
342 } else {
343 error_setg(errp, "Invalid interval length: %" PRId64, length);
344 return false;
346 break;
349 default:
350 error_setg(errp, "The specification of stats-intervals is invalid");
351 return false;
354 return true;
357 typedef enum { MEDIA_DISK, MEDIA_CDROM } DriveMediaType;
359 /* All parameters but @opts are optional and may be set to NULL. */
360 static void extract_common_blockdev_options(QemuOpts *opts, int *bdrv_flags,
361 const char **throttling_group, ThrottleConfig *throttle_cfg,
362 BlockdevDetectZeroesOptions *detect_zeroes, Error **errp)
364 Error *local_error = NULL;
365 const char *aio;
367 if (bdrv_flags) {
368 if (qemu_opt_get_bool(opts, "copy-on-read", false)) {
369 *bdrv_flags |= BDRV_O_COPY_ON_READ;
372 if ((aio = qemu_opt_get(opts, "aio")) != NULL) {
373 if (!strcmp(aio, "native")) {
374 *bdrv_flags |= BDRV_O_NATIVE_AIO;
375 } else if (!strcmp(aio, "threads")) {
376 /* this is the default */
377 } else {
378 error_setg(errp, "invalid aio option");
379 return;
384 /* disk I/O throttling */
385 if (throttling_group) {
386 *throttling_group = qemu_opt_get(opts, "throttling.group");
389 if (throttle_cfg) {
390 throttle_config_init(throttle_cfg);
391 throttle_cfg->buckets[THROTTLE_BPS_TOTAL].avg =
392 qemu_opt_get_number(opts, "throttling.bps-total", 0);
393 throttle_cfg->buckets[THROTTLE_BPS_READ].avg =
394 qemu_opt_get_number(opts, "throttling.bps-read", 0);
395 throttle_cfg->buckets[THROTTLE_BPS_WRITE].avg =
396 qemu_opt_get_number(opts, "throttling.bps-write", 0);
397 throttle_cfg->buckets[THROTTLE_OPS_TOTAL].avg =
398 qemu_opt_get_number(opts, "throttling.iops-total", 0);
399 throttle_cfg->buckets[THROTTLE_OPS_READ].avg =
400 qemu_opt_get_number(opts, "throttling.iops-read", 0);
401 throttle_cfg->buckets[THROTTLE_OPS_WRITE].avg =
402 qemu_opt_get_number(opts, "throttling.iops-write", 0);
404 throttle_cfg->buckets[THROTTLE_BPS_TOTAL].max =
405 qemu_opt_get_number(opts, "throttling.bps-total-max", 0);
406 throttle_cfg->buckets[THROTTLE_BPS_READ].max =
407 qemu_opt_get_number(opts, "throttling.bps-read-max", 0);
408 throttle_cfg->buckets[THROTTLE_BPS_WRITE].max =
409 qemu_opt_get_number(opts, "throttling.bps-write-max", 0);
410 throttle_cfg->buckets[THROTTLE_OPS_TOTAL].max =
411 qemu_opt_get_number(opts, "throttling.iops-total-max", 0);
412 throttle_cfg->buckets[THROTTLE_OPS_READ].max =
413 qemu_opt_get_number(opts, "throttling.iops-read-max", 0);
414 throttle_cfg->buckets[THROTTLE_OPS_WRITE].max =
415 qemu_opt_get_number(opts, "throttling.iops-write-max", 0);
417 throttle_cfg->buckets[THROTTLE_BPS_TOTAL].burst_length =
418 qemu_opt_get_number(opts, "throttling.bps-total-max-length", 1);
419 throttle_cfg->buckets[THROTTLE_BPS_READ].burst_length =
420 qemu_opt_get_number(opts, "throttling.bps-read-max-length", 1);
421 throttle_cfg->buckets[THROTTLE_BPS_WRITE].burst_length =
422 qemu_opt_get_number(opts, "throttling.bps-write-max-length", 1);
423 throttle_cfg->buckets[THROTTLE_OPS_TOTAL].burst_length =
424 qemu_opt_get_number(opts, "throttling.iops-total-max-length", 1);
425 throttle_cfg->buckets[THROTTLE_OPS_READ].burst_length =
426 qemu_opt_get_number(opts, "throttling.iops-read-max-length", 1);
427 throttle_cfg->buckets[THROTTLE_OPS_WRITE].burst_length =
428 qemu_opt_get_number(opts, "throttling.iops-write-max-length", 1);
430 throttle_cfg->op_size =
431 qemu_opt_get_number(opts, "throttling.iops-size", 0);
433 if (!throttle_is_valid(throttle_cfg, errp)) {
434 return;
438 if (detect_zeroes) {
439 *detect_zeroes =
440 qapi_enum_parse(&BlockdevDetectZeroesOptions_lookup,
441 qemu_opt_get(opts, "detect-zeroes"),
442 BLOCKDEV_DETECT_ZEROES_OPTIONS_OFF,
443 &local_error);
444 if (local_error) {
445 error_propagate(errp, local_error);
446 return;
451 /* Takes the ownership of bs_opts */
452 static BlockBackend *blockdev_init(const char *file, QDict *bs_opts,
453 Error **errp)
455 const char *buf;
456 int bdrv_flags = 0;
457 int on_read_error, on_write_error;
458 bool account_invalid, account_failed;
459 bool writethrough, read_only;
460 BlockBackend *blk;
461 BlockDriverState *bs;
462 ThrottleConfig cfg;
463 int snapshot = 0;
464 Error *error = NULL;
465 QemuOpts *opts;
466 QDict *interval_dict = NULL;
467 QList *interval_list = NULL;
468 const char *id;
469 BlockdevDetectZeroesOptions detect_zeroes =
470 BLOCKDEV_DETECT_ZEROES_OPTIONS_OFF;
471 const char *throttling_group = NULL;
473 /* Check common options by copying from bs_opts to opts, all other options
474 * stay in bs_opts for processing by bdrv_open(). */
475 id = qdict_get_try_str(bs_opts, "id");
476 opts = qemu_opts_create(&qemu_common_drive_opts, id, 1, &error);
477 if (error) {
478 error_propagate(errp, error);
479 goto err_no_opts;
482 qemu_opts_absorb_qdict(opts, bs_opts, &error);
483 if (error) {
484 error_propagate(errp, error);
485 goto early_err;
488 if (id) {
489 qdict_del(bs_opts, "id");
492 /* extract parameters */
493 snapshot = qemu_opt_get_bool(opts, "snapshot", 0);
495 account_invalid = qemu_opt_get_bool(opts, "stats-account-invalid", true);
496 account_failed = qemu_opt_get_bool(opts, "stats-account-failed", true);
498 writethrough = !qemu_opt_get_bool(opts, BDRV_OPT_CACHE_WB, true);
500 id = qemu_opts_id(opts);
502 qdict_extract_subqdict(bs_opts, &interval_dict, "stats-intervals.");
503 qdict_array_split(interval_dict, &interval_list);
505 if (qdict_size(interval_dict) != 0) {
506 error_setg(errp, "Invalid option stats-intervals.%s",
507 qdict_first(interval_dict)->key);
508 goto early_err;
511 extract_common_blockdev_options(opts, &bdrv_flags, &throttling_group, &cfg,
512 &detect_zeroes, &error);
513 if (error) {
514 error_propagate(errp, error);
515 goto early_err;
518 if ((buf = qemu_opt_get(opts, "format")) != NULL) {
519 if (is_help_option(buf)) {
520 error_printf("Supported formats:");
521 bdrv_iterate_format(bdrv_format_print, NULL);
522 error_printf("\n");
523 goto early_err;
526 if (qdict_haskey(bs_opts, "driver")) {
527 error_setg(errp, "Cannot specify both 'driver' and 'format'");
528 goto early_err;
530 qdict_put_str(bs_opts, "driver", buf);
533 on_write_error = BLOCKDEV_ON_ERROR_ENOSPC;
534 if ((buf = qemu_opt_get(opts, "werror")) != NULL) {
535 on_write_error = parse_block_error_action(buf, 0, &error);
536 if (error) {
537 error_propagate(errp, error);
538 goto early_err;
542 on_read_error = BLOCKDEV_ON_ERROR_REPORT;
543 if ((buf = qemu_opt_get(opts, "rerror")) != NULL) {
544 on_read_error = parse_block_error_action(buf, 1, &error);
545 if (error) {
546 error_propagate(errp, error);
547 goto early_err;
551 if (snapshot) {
552 bdrv_flags |= BDRV_O_SNAPSHOT;
555 read_only = qemu_opt_get_bool(opts, BDRV_OPT_READ_ONLY, false);
557 /* init */
558 if ((!file || !*file) && !qdict_size(bs_opts)) {
559 BlockBackendRootState *blk_rs;
561 blk = blk_new(0, BLK_PERM_ALL);
562 blk_rs = blk_get_root_state(blk);
563 blk_rs->open_flags = bdrv_flags;
564 blk_rs->read_only = read_only;
565 blk_rs->detect_zeroes = detect_zeroes;
567 QDECREF(bs_opts);
568 } else {
569 if (file && !*file) {
570 file = NULL;
573 /* bdrv_open() defaults to the values in bdrv_flags (for compatibility
574 * with other callers) rather than what we want as the real defaults.
575 * Apply the defaults here instead. */
576 qdict_set_default_str(bs_opts, BDRV_OPT_CACHE_DIRECT, "off");
577 qdict_set_default_str(bs_opts, BDRV_OPT_CACHE_NO_FLUSH, "off");
578 qdict_set_default_str(bs_opts, BDRV_OPT_READ_ONLY,
579 read_only ? "on" : "off");
580 assert((bdrv_flags & BDRV_O_CACHE_MASK) == 0);
582 if (runstate_check(RUN_STATE_INMIGRATE)) {
583 bdrv_flags |= BDRV_O_INACTIVE;
586 blk = blk_new_open(file, NULL, bs_opts, bdrv_flags, errp);
587 if (!blk) {
588 goto err_no_bs_opts;
590 bs = blk_bs(blk);
592 bs->detect_zeroes = detect_zeroes;
594 block_acct_setup(blk_get_stats(blk), account_invalid, account_failed);
596 if (!parse_stats_intervals(blk_get_stats(blk), interval_list, errp)) {
597 blk_unref(blk);
598 blk = NULL;
599 goto err_no_bs_opts;
603 /* disk I/O throttling */
604 if (throttle_enabled(&cfg)) {
605 if (!throttling_group) {
606 throttling_group = id;
608 blk_io_limits_enable(blk, throttling_group);
609 blk_set_io_limits(blk, &cfg);
612 blk_set_enable_write_cache(blk, !writethrough);
613 blk_set_on_error(blk, on_read_error, on_write_error);
615 if (!monitor_add_blk(blk, id, errp)) {
616 blk_unref(blk);
617 blk = NULL;
618 goto err_no_bs_opts;
621 err_no_bs_opts:
622 qemu_opts_del(opts);
623 QDECREF(interval_dict);
624 QDECREF(interval_list);
625 return blk;
627 early_err:
628 qemu_opts_del(opts);
629 QDECREF(interval_dict);
630 QDECREF(interval_list);
631 err_no_opts:
632 QDECREF(bs_opts);
633 return NULL;
636 /* Takes the ownership of bs_opts */
637 static BlockDriverState *bds_tree_init(QDict *bs_opts, Error **errp)
639 int bdrv_flags = 0;
641 /* bdrv_open() defaults to the values in bdrv_flags (for compatibility
642 * with other callers) rather than what we want as the real defaults.
643 * Apply the defaults here instead. */
644 qdict_set_default_str(bs_opts, BDRV_OPT_CACHE_DIRECT, "off");
645 qdict_set_default_str(bs_opts, BDRV_OPT_CACHE_NO_FLUSH, "off");
646 qdict_set_default_str(bs_opts, BDRV_OPT_READ_ONLY, "off");
648 if (runstate_check(RUN_STATE_INMIGRATE)) {
649 bdrv_flags |= BDRV_O_INACTIVE;
652 return bdrv_open(NULL, NULL, bs_opts, bdrv_flags, errp);
655 void blockdev_close_all_bdrv_states(void)
657 BlockDriverState *bs, *next_bs;
659 QTAILQ_FOREACH_SAFE(bs, &monitor_bdrv_states, monitor_list, next_bs) {
660 AioContext *ctx = bdrv_get_aio_context(bs);
662 aio_context_acquire(ctx);
663 bdrv_unref(bs);
664 aio_context_release(ctx);
668 /* Iterates over the list of monitor-owned BlockDriverStates */
669 BlockDriverState *bdrv_next_monitor_owned(BlockDriverState *bs)
671 return bs ? QTAILQ_NEXT(bs, monitor_list)
672 : QTAILQ_FIRST(&monitor_bdrv_states);
675 static void qemu_opt_rename(QemuOpts *opts, const char *from, const char *to,
676 Error **errp)
678 const char *value;
680 value = qemu_opt_get(opts, from);
681 if (value) {
682 if (qemu_opt_find(opts, to)) {
683 error_setg(errp, "'%s' and its alias '%s' can't be used at the "
684 "same time", to, from);
685 return;
689 /* rename all items in opts */
690 while ((value = qemu_opt_get(opts, from))) {
691 qemu_opt_set(opts, to, value, &error_abort);
692 qemu_opt_unset(opts, from);
696 QemuOptsList qemu_legacy_drive_opts = {
697 .name = "drive",
698 .head = QTAILQ_HEAD_INITIALIZER(qemu_legacy_drive_opts.head),
699 .desc = {
701 .name = "bus",
702 .type = QEMU_OPT_NUMBER,
703 .help = "bus number",
705 .name = "unit",
706 .type = QEMU_OPT_NUMBER,
707 .help = "unit number (i.e. lun for scsi)",
709 .name = "index",
710 .type = QEMU_OPT_NUMBER,
711 .help = "index number",
713 .name = "media",
714 .type = QEMU_OPT_STRING,
715 .help = "media type (disk, cdrom)",
717 .name = "if",
718 .type = QEMU_OPT_STRING,
719 .help = "interface (ide, scsi, sd, mtd, floppy, pflash, virtio)",
721 .name = "cyls",
722 .type = QEMU_OPT_NUMBER,
723 .help = "number of cylinders (ide disk geometry)",
725 .name = "heads",
726 .type = QEMU_OPT_NUMBER,
727 .help = "number of heads (ide disk geometry)",
729 .name = "secs",
730 .type = QEMU_OPT_NUMBER,
731 .help = "number of sectors (ide disk geometry)",
733 .name = "trans",
734 .type = QEMU_OPT_STRING,
735 .help = "chs translation (auto, lba, none)",
737 .name = "boot",
738 .type = QEMU_OPT_BOOL,
739 .help = "(deprecated, ignored)",
741 .name = "addr",
742 .type = QEMU_OPT_STRING,
743 .help = "pci address (virtio only)",
745 .name = "serial",
746 .type = QEMU_OPT_STRING,
747 .help = "disk serial number",
749 .name = "file",
750 .type = QEMU_OPT_STRING,
751 .help = "file name",
754 /* Options that are passed on, but have special semantics with -drive */
756 .name = BDRV_OPT_READ_ONLY,
757 .type = QEMU_OPT_BOOL,
758 .help = "open drive file as read-only",
760 .name = "rerror",
761 .type = QEMU_OPT_STRING,
762 .help = "read error action",
764 .name = "werror",
765 .type = QEMU_OPT_STRING,
766 .help = "write error action",
768 .name = "copy-on-read",
769 .type = QEMU_OPT_BOOL,
770 .help = "copy read data from backing file into image file",
773 { /* end of list */ }
777 DriveInfo *drive_new(QemuOpts *all_opts, BlockInterfaceType block_default_type)
779 const char *value;
780 BlockBackend *blk;
781 DriveInfo *dinfo = NULL;
782 QDict *bs_opts;
783 QemuOpts *legacy_opts;
784 DriveMediaType media = MEDIA_DISK;
785 BlockInterfaceType type;
786 int cyls, heads, secs, translation;
787 int max_devs, bus_id, unit_id, index;
788 const char *devaddr;
789 const char *werror, *rerror;
790 bool read_only = false;
791 bool copy_on_read;
792 const char *serial;
793 const char *filename;
794 Error *local_err = NULL;
795 int i;
796 const char *deprecated[] = {
797 "serial", "trans", "secs", "heads", "cyls", "addr"
800 /* Change legacy command line options into QMP ones */
801 static const struct {
802 const char *from;
803 const char *to;
804 } opt_renames[] = {
805 { "iops", "throttling.iops-total" },
806 { "iops_rd", "throttling.iops-read" },
807 { "iops_wr", "throttling.iops-write" },
809 { "bps", "throttling.bps-total" },
810 { "bps_rd", "throttling.bps-read" },
811 { "bps_wr", "throttling.bps-write" },
813 { "iops_max", "throttling.iops-total-max" },
814 { "iops_rd_max", "throttling.iops-read-max" },
815 { "iops_wr_max", "throttling.iops-write-max" },
817 { "bps_max", "throttling.bps-total-max" },
818 { "bps_rd_max", "throttling.bps-read-max" },
819 { "bps_wr_max", "throttling.bps-write-max" },
821 { "iops_size", "throttling.iops-size" },
823 { "group", "throttling.group" },
825 { "readonly", BDRV_OPT_READ_ONLY },
828 for (i = 0; i < ARRAY_SIZE(opt_renames); i++) {
829 qemu_opt_rename(all_opts, opt_renames[i].from, opt_renames[i].to,
830 &local_err);
831 if (local_err) {
832 error_report_err(local_err);
833 return NULL;
837 value = qemu_opt_get(all_opts, "cache");
838 if (value) {
839 int flags = 0;
840 bool writethrough;
842 if (bdrv_parse_cache_mode(value, &flags, &writethrough) != 0) {
843 error_report("invalid cache option");
844 return NULL;
847 /* Specific options take precedence */
848 if (!qemu_opt_get(all_opts, BDRV_OPT_CACHE_WB)) {
849 qemu_opt_set_bool(all_opts, BDRV_OPT_CACHE_WB,
850 !writethrough, &error_abort);
852 if (!qemu_opt_get(all_opts, BDRV_OPT_CACHE_DIRECT)) {
853 qemu_opt_set_bool(all_opts, BDRV_OPT_CACHE_DIRECT,
854 !!(flags & BDRV_O_NOCACHE), &error_abort);
856 if (!qemu_opt_get(all_opts, BDRV_OPT_CACHE_NO_FLUSH)) {
857 qemu_opt_set_bool(all_opts, BDRV_OPT_CACHE_NO_FLUSH,
858 !!(flags & BDRV_O_NO_FLUSH), &error_abort);
860 qemu_opt_unset(all_opts, "cache");
863 /* Get a QDict for processing the options */
864 bs_opts = qdict_new();
865 qemu_opts_to_qdict(all_opts, bs_opts);
867 legacy_opts = qemu_opts_create(&qemu_legacy_drive_opts, NULL, 0,
868 &error_abort);
869 qemu_opts_absorb_qdict(legacy_opts, bs_opts, &local_err);
870 if (local_err) {
871 error_report_err(local_err);
872 goto fail;
875 /* Deprecated option boot=[on|off] */
876 if (qemu_opt_get(legacy_opts, "boot") != NULL) {
877 fprintf(stderr, "qemu-kvm: boot=on|off is deprecated and will be "
878 "ignored. Future versions will reject this parameter. Please "
879 "update your scripts.\n");
882 /* Other deprecated options */
883 if (!qtest_enabled()) {
884 for (i = 0; i < ARRAY_SIZE(deprecated); i++) {
885 if (qemu_opt_get(legacy_opts, deprecated[i]) != NULL) {
886 error_report("'%s' is deprecated, please use the corresponding "
887 "option of '-device' instead", deprecated[i]);
892 /* Media type */
893 value = qemu_opt_get(legacy_opts, "media");
894 if (value) {
895 if (!strcmp(value, "disk")) {
896 media = MEDIA_DISK;
897 } else if (!strcmp(value, "cdrom")) {
898 media = MEDIA_CDROM;
899 read_only = true;
900 } else {
901 error_report("'%s' invalid media", value);
902 goto fail;
906 /* copy-on-read is disabled with a warning for read-only devices */
907 read_only |= qemu_opt_get_bool(legacy_opts, BDRV_OPT_READ_ONLY, false);
908 copy_on_read = qemu_opt_get_bool(legacy_opts, "copy-on-read", false);
910 if (read_only && copy_on_read) {
911 warn_report("disabling copy-on-read on read-only drive");
912 copy_on_read = false;
915 qdict_put_str(bs_opts, BDRV_OPT_READ_ONLY, read_only ? "on" : "off");
916 qdict_put_str(bs_opts, "copy-on-read", copy_on_read ? "on" : "off");
918 /* Controller type */
919 value = qemu_opt_get(legacy_opts, "if");
920 if (value) {
921 for (type = 0;
922 type < IF_COUNT && strcmp(value, if_name[type]);
923 type++) {
925 if (type == IF_COUNT) {
926 error_report("unsupported bus type '%s'", value);
927 goto fail;
929 } else {
930 type = block_default_type;
933 /* Geometry */
934 cyls = qemu_opt_get_number(legacy_opts, "cyls", 0);
935 heads = qemu_opt_get_number(legacy_opts, "heads", 0);
936 secs = qemu_opt_get_number(legacy_opts, "secs", 0);
938 if (cyls || heads || secs) {
939 if (cyls < 1) {
940 error_report("invalid physical cyls number");
941 goto fail;
943 if (heads < 1) {
944 error_report("invalid physical heads number");
945 goto fail;
947 if (secs < 1) {
948 error_report("invalid physical secs number");
949 goto fail;
953 translation = BIOS_ATA_TRANSLATION_AUTO;
954 value = qemu_opt_get(legacy_opts, "trans");
955 if (value != NULL) {
956 if (!cyls) {
957 error_report("'%s' trans must be used with cyls, heads and secs",
958 value);
959 goto fail;
961 if (!strcmp(value, "none")) {
962 translation = BIOS_ATA_TRANSLATION_NONE;
963 } else if (!strcmp(value, "lba")) {
964 translation = BIOS_ATA_TRANSLATION_LBA;
965 } else if (!strcmp(value, "large")) {
966 translation = BIOS_ATA_TRANSLATION_LARGE;
967 } else if (!strcmp(value, "rechs")) {
968 translation = BIOS_ATA_TRANSLATION_RECHS;
969 } else if (!strcmp(value, "auto")) {
970 translation = BIOS_ATA_TRANSLATION_AUTO;
971 } else {
972 error_report("'%s' invalid translation type", value);
973 goto fail;
977 if (media == MEDIA_CDROM) {
978 if (cyls || secs || heads) {
979 error_report("CHS can't be set with media=cdrom");
980 goto fail;
984 /* Device address specified by bus/unit or index.
985 * If none was specified, try to find the first free one. */
986 bus_id = qemu_opt_get_number(legacy_opts, "bus", 0);
987 unit_id = qemu_opt_get_number(legacy_opts, "unit", -1);
988 index = qemu_opt_get_number(legacy_opts, "index", -1);
990 max_devs = if_max_devs[type];
992 if (index != -1) {
993 if (bus_id != 0 || unit_id != -1) {
994 error_report("index cannot be used with bus and unit");
995 goto fail;
997 bus_id = drive_index_to_bus_id(type, index);
998 unit_id = drive_index_to_unit_id(type, index);
1001 if (unit_id == -1) {
1002 unit_id = 0;
1003 while (drive_get(type, bus_id, unit_id) != NULL) {
1004 unit_id++;
1005 if (max_devs && unit_id >= max_devs) {
1006 unit_id -= max_devs;
1007 bus_id++;
1012 if (max_devs && unit_id >= max_devs) {
1013 error_report("unit %d too big (max is %d)", unit_id, max_devs - 1);
1014 goto fail;
1017 if (drive_get(type, bus_id, unit_id) != NULL) {
1018 error_report("drive with bus=%d, unit=%d (index=%d) exists",
1019 bus_id, unit_id, index);
1020 goto fail;
1023 /* Serial number */
1024 serial = qemu_opt_get(legacy_opts, "serial");
1026 /* no id supplied -> create one */
1027 if (qemu_opts_id(all_opts) == NULL) {
1028 char *new_id;
1029 const char *mediastr = "";
1030 if (type == IF_IDE || type == IF_SCSI) {
1031 mediastr = (media == MEDIA_CDROM) ? "-cd" : "-hd";
1033 if (max_devs) {
1034 new_id = g_strdup_printf("%s%i%s%i", if_name[type], bus_id,
1035 mediastr, unit_id);
1036 } else {
1037 new_id = g_strdup_printf("%s%s%i", if_name[type],
1038 mediastr, unit_id);
1040 qdict_put_str(bs_opts, "id", new_id);
1041 g_free(new_id);
1044 /* Add virtio block device */
1045 devaddr = qemu_opt_get(legacy_opts, "addr");
1046 if (devaddr && type != IF_VIRTIO) {
1047 error_report("addr is not supported by this bus type");
1048 goto fail;
1051 if (type == IF_VIRTIO) {
1052 QemuOpts *devopts;
1053 devopts = qemu_opts_create(qemu_find_opts("device"), NULL, 0,
1054 &error_abort);
1055 if (arch_type == QEMU_ARCH_S390X) {
1056 qemu_opt_set(devopts, "driver", "virtio-blk-ccw", &error_abort);
1057 } else {
1058 qemu_opt_set(devopts, "driver", "virtio-blk-pci", &error_abort);
1060 qemu_opt_set(devopts, "drive", qdict_get_str(bs_opts, "id"),
1061 &error_abort);
1062 if (devaddr) {
1063 qemu_opt_set(devopts, "addr", devaddr, &error_abort);
1067 filename = qemu_opt_get(legacy_opts, "file");
1069 /* Check werror/rerror compatibility with if=... */
1070 werror = qemu_opt_get(legacy_opts, "werror");
1071 if (werror != NULL) {
1072 if (type != IF_IDE && type != IF_SCSI && type != IF_VIRTIO &&
1073 type != IF_NONE) {
1074 error_report("werror is not supported by this bus type");
1075 goto fail;
1077 qdict_put_str(bs_opts, "werror", werror);
1080 rerror = qemu_opt_get(legacy_opts, "rerror");
1081 if (rerror != NULL) {
1082 if (type != IF_IDE && type != IF_VIRTIO && type != IF_SCSI &&
1083 type != IF_NONE) {
1084 error_report("rerror is not supported by this bus type");
1085 goto fail;
1087 qdict_put_str(bs_opts, "rerror", rerror);
1090 /* Actual block device init: Functionality shared with blockdev-add */
1091 blk = blockdev_init(filename, bs_opts, &local_err);
1092 bs_opts = NULL;
1093 if (!blk) {
1094 if (local_err) {
1095 error_report_err(local_err);
1097 goto fail;
1098 } else {
1099 assert(!local_err);
1102 /* Create legacy DriveInfo */
1103 dinfo = g_malloc0(sizeof(*dinfo));
1104 dinfo->opts = all_opts;
1106 dinfo->cyls = cyls;
1107 dinfo->heads = heads;
1108 dinfo->secs = secs;
1109 dinfo->trans = translation;
1111 dinfo->type = type;
1112 dinfo->bus = bus_id;
1113 dinfo->unit = unit_id;
1114 dinfo->devaddr = devaddr;
1115 dinfo->serial = g_strdup(serial);
1117 blk_set_legacy_dinfo(blk, dinfo);
1119 switch(type) {
1120 case IF_IDE:
1121 case IF_SCSI:
1122 case IF_XEN:
1123 case IF_NONE:
1124 dinfo->media_cd = media == MEDIA_CDROM;
1125 break;
1126 default:
1127 break;
1130 fail:
1131 qemu_opts_del(legacy_opts);
1132 QDECREF(bs_opts);
1133 return dinfo;
1136 static BlockDriverState *qmp_get_root_bs(const char *name, Error **errp)
1138 BlockDriverState *bs;
1140 bs = bdrv_lookup_bs(name, name, errp);
1141 if (bs == NULL) {
1142 return NULL;
1145 if (!bdrv_is_root_node(bs)) {
1146 error_setg(errp, "Need a root block node");
1147 return NULL;
1150 if (!bdrv_is_inserted(bs)) {
1151 error_setg(errp, "Device has no medium");
1152 return NULL;
1155 return bs;
1158 static BlockBackend *qmp_get_blk(const char *blk_name, const char *qdev_id,
1159 Error **errp)
1161 BlockBackend *blk;
1163 if (!blk_name == !qdev_id) {
1164 error_setg(errp, "Need exactly one of 'device' and 'id'");
1165 return NULL;
1168 if (qdev_id) {
1169 blk = blk_by_qdev_id(qdev_id, errp);
1170 } else {
1171 blk = blk_by_name(blk_name);
1172 if (blk == NULL) {
1173 error_set(errp, ERROR_CLASS_DEVICE_NOT_FOUND,
1174 "Device '%s' not found", blk_name);
1178 return blk;
1181 void hmp_commit(Monitor *mon, const QDict *qdict)
1183 const char *device = qdict_get_str(qdict, "device");
1184 BlockBackend *blk;
1185 int ret;
1187 if (!strcmp(device, "all")) {
1188 ret = blk_commit_all();
1189 } else {
1190 BlockDriverState *bs;
1191 AioContext *aio_context;
1193 blk = blk_by_name(device);
1194 if (!blk) {
1195 monitor_printf(mon, "Device '%s' not found\n", device);
1196 return;
1198 if (!blk_is_available(blk)) {
1199 monitor_printf(mon, "Device '%s' has no medium\n", device);
1200 return;
1203 bs = blk_bs(blk);
1204 aio_context = bdrv_get_aio_context(bs);
1205 aio_context_acquire(aio_context);
1207 ret = bdrv_commit(bs);
1209 aio_context_release(aio_context);
1211 if (ret < 0) {
1212 monitor_printf(mon, "'commit' error for '%s': %s\n", device,
1213 strerror(-ret));
1217 static void blockdev_do_action(TransactionAction *action, Error **errp)
1219 TransactionActionList list;
1221 list.value = action;
1222 list.next = NULL;
1223 qmp_transaction(&list, false, NULL, errp);
1226 void qmp_blockdev_snapshot_sync(bool has_device, const char *device,
1227 bool has_node_name, const char *node_name,
1228 const char *snapshot_file,
1229 bool has_snapshot_node_name,
1230 const char *snapshot_node_name,
1231 bool has_format, const char *format,
1232 bool has_mode, NewImageMode mode, Error **errp)
1234 BlockdevSnapshotSync snapshot = {
1235 .has_device = has_device,
1236 .device = (char *) device,
1237 .has_node_name = has_node_name,
1238 .node_name = (char *) node_name,
1239 .snapshot_file = (char *) snapshot_file,
1240 .has_snapshot_node_name = has_snapshot_node_name,
1241 .snapshot_node_name = (char *) snapshot_node_name,
1242 .has_format = has_format,
1243 .format = (char *) format,
1244 .has_mode = has_mode,
1245 .mode = mode,
1247 TransactionAction action = {
1248 .type = TRANSACTION_ACTION_KIND_BLOCKDEV_SNAPSHOT_SYNC,
1249 .u.blockdev_snapshot_sync.data = &snapshot,
1251 blockdev_do_action(&action, errp);
1254 void qmp_blockdev_snapshot(const char *node, const char *overlay,
1255 Error **errp)
1257 BlockdevSnapshot snapshot_data = {
1258 .node = (char *) node,
1259 .overlay = (char *) overlay
1261 TransactionAction action = {
1262 .type = TRANSACTION_ACTION_KIND_BLOCKDEV_SNAPSHOT,
1263 .u.blockdev_snapshot.data = &snapshot_data,
1265 blockdev_do_action(&action, errp);
1268 void qmp_blockdev_snapshot_internal_sync(const char *device,
1269 const char *name,
1270 Error **errp)
1272 BlockdevSnapshotInternal snapshot = {
1273 .device = (char *) device,
1274 .name = (char *) name
1276 TransactionAction action = {
1277 .type = TRANSACTION_ACTION_KIND_BLOCKDEV_SNAPSHOT_INTERNAL_SYNC,
1278 .u.blockdev_snapshot_internal_sync.data = &snapshot,
1280 blockdev_do_action(&action, errp);
1283 SnapshotInfo *qmp_blockdev_snapshot_delete_internal_sync(const char *device,
1284 bool has_id,
1285 const char *id,
1286 bool has_name,
1287 const char *name,
1288 Error **errp)
1290 BlockDriverState *bs;
1291 AioContext *aio_context;
1292 QEMUSnapshotInfo sn;
1293 Error *local_err = NULL;
1294 SnapshotInfo *info = NULL;
1295 int ret;
1297 bs = qmp_get_root_bs(device, errp);
1298 if (!bs) {
1299 return NULL;
1301 aio_context = bdrv_get_aio_context(bs);
1302 aio_context_acquire(aio_context);
1304 if (!has_id) {
1305 id = NULL;
1308 if (!has_name) {
1309 name = NULL;
1312 if (!id && !name) {
1313 error_setg(errp, "Name or id must be provided");
1314 goto out_aio_context;
1317 if (bdrv_op_is_blocked(bs, BLOCK_OP_TYPE_INTERNAL_SNAPSHOT_DELETE, errp)) {
1318 goto out_aio_context;
1321 ret = bdrv_snapshot_find_by_id_and_name(bs, id, name, &sn, &local_err);
1322 if (local_err) {
1323 error_propagate(errp, local_err);
1324 goto out_aio_context;
1326 if (!ret) {
1327 error_setg(errp,
1328 "Snapshot with id '%s' and name '%s' does not exist on "
1329 "device '%s'",
1330 STR_OR_NULL(id), STR_OR_NULL(name), device);
1331 goto out_aio_context;
1334 bdrv_snapshot_delete(bs, id, name, &local_err);
1335 if (local_err) {
1336 error_propagate(errp, local_err);
1337 goto out_aio_context;
1340 aio_context_release(aio_context);
1342 info = g_new0(SnapshotInfo, 1);
1343 info->id = g_strdup(sn.id_str);
1344 info->name = g_strdup(sn.name);
1345 info->date_nsec = sn.date_nsec;
1346 info->date_sec = sn.date_sec;
1347 info->vm_state_size = sn.vm_state_size;
1348 info->vm_clock_nsec = sn.vm_clock_nsec % 1000000000;
1349 info->vm_clock_sec = sn.vm_clock_nsec / 1000000000;
1351 return info;
1353 out_aio_context:
1354 aio_context_release(aio_context);
1355 return NULL;
1359 * block_dirty_bitmap_lookup:
1360 * Return a dirty bitmap (if present), after validating
1361 * the node reference and bitmap names.
1363 * @node: The name of the BDS node to search for bitmaps
1364 * @name: The name of the bitmap to search for
1365 * @pbs: Output pointer for BDS lookup, if desired. Can be NULL.
1366 * @paio: Output pointer for aio_context acquisition, if desired. Can be NULL.
1367 * @errp: Output pointer for error information. Can be NULL.
1369 * @return: A bitmap object on success, or NULL on failure.
1371 static BdrvDirtyBitmap *block_dirty_bitmap_lookup(const char *node,
1372 const char *name,
1373 BlockDriverState **pbs,
1374 Error **errp)
1376 BlockDriverState *bs;
1377 BdrvDirtyBitmap *bitmap;
1379 if (!node) {
1380 error_setg(errp, "Node cannot be NULL");
1381 return NULL;
1383 if (!name) {
1384 error_setg(errp, "Bitmap name cannot be NULL");
1385 return NULL;
1387 bs = bdrv_lookup_bs(node, node, NULL);
1388 if (!bs) {
1389 error_setg(errp, "Node '%s' not found", node);
1390 return NULL;
1393 bitmap = bdrv_find_dirty_bitmap(bs, name);
1394 if (!bitmap) {
1395 error_setg(errp, "Dirty bitmap '%s' not found", name);
1396 return NULL;
1399 if (pbs) {
1400 *pbs = bs;
1403 return bitmap;
1406 /* New and old BlockDriverState structs for atomic group operations */
1408 typedef struct BlkActionState BlkActionState;
1411 * BlkActionOps:
1412 * Table of operations that define an Action.
1414 * @instance_size: Size of state struct, in bytes.
1415 * @prepare: Prepare the work, must NOT be NULL.
1416 * @commit: Commit the changes, can be NULL.
1417 * @abort: Abort the changes on fail, can be NULL.
1418 * @clean: Clean up resources after all transaction actions have called
1419 * commit() or abort(). Can be NULL.
1421 * Only prepare() may fail. In a single transaction, only one of commit() or
1422 * abort() will be called. clean() will always be called if it is present.
1424 typedef struct BlkActionOps {
1425 size_t instance_size;
1426 void (*prepare)(BlkActionState *common, Error **errp);
1427 void (*commit)(BlkActionState *common);
1428 void (*abort)(BlkActionState *common);
1429 void (*clean)(BlkActionState *common);
1430 } BlkActionOps;
1433 * BlkActionState:
1434 * Describes one Action's state within a Transaction.
1436 * @action: QAPI-defined enum identifying which Action to perform.
1437 * @ops: Table of ActionOps this Action can perform.
1438 * @block_job_txn: Transaction which this action belongs to.
1439 * @entry: List membership for all Actions in this Transaction.
1441 * This structure must be arranged as first member in a subclassed type,
1442 * assuming that the compiler will also arrange it to the same offsets as the
1443 * base class.
1445 struct BlkActionState {
1446 TransactionAction *action;
1447 const BlkActionOps *ops;
1448 BlockJobTxn *block_job_txn;
1449 TransactionProperties *txn_props;
1450 QSIMPLEQ_ENTRY(BlkActionState) entry;
1453 /* internal snapshot private data */
1454 typedef struct InternalSnapshotState {
1455 BlkActionState common;
1456 BlockDriverState *bs;
1457 QEMUSnapshotInfo sn;
1458 bool created;
1459 } InternalSnapshotState;
1462 static int action_check_completion_mode(BlkActionState *s, Error **errp)
1464 if (s->txn_props->completion_mode != ACTION_COMPLETION_MODE_INDIVIDUAL) {
1465 error_setg(errp,
1466 "Action '%s' does not support Transaction property "
1467 "completion-mode = %s",
1468 TransactionActionKind_str(s->action->type),
1469 ActionCompletionMode_str(s->txn_props->completion_mode));
1470 return -1;
1472 return 0;
1475 static void internal_snapshot_prepare(BlkActionState *common,
1476 Error **errp)
1478 Error *local_err = NULL;
1479 const char *device;
1480 const char *name;
1481 BlockDriverState *bs;
1482 QEMUSnapshotInfo old_sn, *sn;
1483 bool ret;
1484 qemu_timeval tv;
1485 BlockdevSnapshotInternal *internal;
1486 InternalSnapshotState *state;
1487 AioContext *aio_context;
1488 int ret1;
1490 g_assert(common->action->type ==
1491 TRANSACTION_ACTION_KIND_BLOCKDEV_SNAPSHOT_INTERNAL_SYNC);
1492 internal = common->action->u.blockdev_snapshot_internal_sync.data;
1493 state = DO_UPCAST(InternalSnapshotState, common, common);
1495 /* 1. parse input */
1496 device = internal->device;
1497 name = internal->name;
1499 /* 2. check for validation */
1500 if (action_check_completion_mode(common, errp) < 0) {
1501 return;
1504 bs = qmp_get_root_bs(device, errp);
1505 if (!bs) {
1506 return;
1509 aio_context = bdrv_get_aio_context(bs);
1510 aio_context_acquire(aio_context);
1512 state->bs = bs;
1514 /* Paired with .clean() */
1515 bdrv_drained_begin(bs);
1517 if (bdrv_op_is_blocked(bs, BLOCK_OP_TYPE_INTERNAL_SNAPSHOT, errp)) {
1518 goto out;
1521 if (bdrv_is_read_only(bs)) {
1522 error_setg(errp, "Device '%s' is read only", device);
1523 goto out;
1526 if (!bdrv_can_snapshot(bs)) {
1527 error_setg(errp, "Block format '%s' used by device '%s' "
1528 "does not support internal snapshots",
1529 bs->drv->format_name, device);
1530 goto out;
1533 if (!strlen(name)) {
1534 error_setg(errp, "Name is empty");
1535 goto out;
1538 /* check whether a snapshot with name exist */
1539 ret = bdrv_snapshot_find_by_id_and_name(bs, NULL, name, &old_sn,
1540 &local_err);
1541 if (local_err) {
1542 error_propagate(errp, local_err);
1543 goto out;
1544 } else if (ret) {
1545 error_setg(errp,
1546 "Snapshot with name '%s' already exists on device '%s'",
1547 name, device);
1548 goto out;
1551 /* 3. take the snapshot */
1552 sn = &state->sn;
1553 pstrcpy(sn->name, sizeof(sn->name), name);
1554 qemu_gettimeofday(&tv);
1555 sn->date_sec = tv.tv_sec;
1556 sn->date_nsec = tv.tv_usec * 1000;
1557 sn->vm_clock_nsec = qemu_clock_get_ns(QEMU_CLOCK_VIRTUAL);
1559 ret1 = bdrv_snapshot_create(bs, sn);
1560 if (ret1 < 0) {
1561 error_setg_errno(errp, -ret1,
1562 "Failed to create snapshot '%s' on device '%s'",
1563 name, device);
1564 goto out;
1567 /* 4. succeed, mark a snapshot is created */
1568 state->created = true;
1570 out:
1571 aio_context_release(aio_context);
1574 static void internal_snapshot_abort(BlkActionState *common)
1576 InternalSnapshotState *state =
1577 DO_UPCAST(InternalSnapshotState, common, common);
1578 BlockDriverState *bs = state->bs;
1579 QEMUSnapshotInfo *sn = &state->sn;
1580 AioContext *aio_context;
1581 Error *local_error = NULL;
1583 if (!state->created) {
1584 return;
1587 aio_context = bdrv_get_aio_context(state->bs);
1588 aio_context_acquire(aio_context);
1590 if (bdrv_snapshot_delete(bs, sn->id_str, sn->name, &local_error) < 0) {
1591 error_reportf_err(local_error,
1592 "Failed to delete snapshot with id '%s' and "
1593 "name '%s' on device '%s' in abort: ",
1594 sn->id_str, sn->name,
1595 bdrv_get_device_name(bs));
1598 aio_context_release(aio_context);
1601 static void internal_snapshot_clean(BlkActionState *common)
1603 InternalSnapshotState *state = DO_UPCAST(InternalSnapshotState,
1604 common, common);
1605 AioContext *aio_context;
1607 if (!state->bs) {
1608 return;
1611 aio_context = bdrv_get_aio_context(state->bs);
1612 aio_context_acquire(aio_context);
1614 bdrv_drained_end(state->bs);
1616 aio_context_release(aio_context);
1619 /* external snapshot private data */
1620 typedef struct ExternalSnapshotState {
1621 BlkActionState common;
1622 BlockDriverState *old_bs;
1623 BlockDriverState *new_bs;
1624 bool overlay_appended;
1625 } ExternalSnapshotState;
1627 static void external_snapshot_prepare(BlkActionState *common,
1628 Error **errp)
1630 int flags = 0;
1631 QDict *options = NULL;
1632 Error *local_err = NULL;
1633 /* Device and node name of the image to generate the snapshot from */
1634 const char *device;
1635 const char *node_name;
1636 /* Reference to the new image (for 'blockdev-snapshot') */
1637 const char *snapshot_ref;
1638 /* File name of the new image (for 'blockdev-snapshot-sync') */
1639 const char *new_image_file;
1640 ExternalSnapshotState *state =
1641 DO_UPCAST(ExternalSnapshotState, common, common);
1642 TransactionAction *action = common->action;
1643 AioContext *aio_context;
1645 /* 'blockdev-snapshot' and 'blockdev-snapshot-sync' have similar
1646 * purpose but a different set of parameters */
1647 switch (action->type) {
1648 case TRANSACTION_ACTION_KIND_BLOCKDEV_SNAPSHOT:
1650 BlockdevSnapshot *s = action->u.blockdev_snapshot.data;
1651 device = s->node;
1652 node_name = s->node;
1653 new_image_file = NULL;
1654 snapshot_ref = s->overlay;
1656 break;
1657 case TRANSACTION_ACTION_KIND_BLOCKDEV_SNAPSHOT_SYNC:
1659 BlockdevSnapshotSync *s = action->u.blockdev_snapshot_sync.data;
1660 device = s->has_device ? s->device : NULL;
1661 node_name = s->has_node_name ? s->node_name : NULL;
1662 new_image_file = s->snapshot_file;
1663 snapshot_ref = NULL;
1665 break;
1666 default:
1667 g_assert_not_reached();
1670 /* start processing */
1671 if (action_check_completion_mode(common, errp) < 0) {
1672 return;
1675 state->old_bs = bdrv_lookup_bs(device, node_name, errp);
1676 if (!state->old_bs) {
1677 return;
1680 aio_context = bdrv_get_aio_context(state->old_bs);
1681 aio_context_acquire(aio_context);
1683 /* Paired with .clean() */
1684 bdrv_drained_begin(state->old_bs);
1686 if (!bdrv_is_inserted(state->old_bs)) {
1687 error_setg(errp, QERR_DEVICE_HAS_NO_MEDIUM, device);
1688 goto out;
1691 if (bdrv_op_is_blocked(state->old_bs,
1692 BLOCK_OP_TYPE_EXTERNAL_SNAPSHOT, errp)) {
1693 goto out;
1696 if (!bdrv_is_read_only(state->old_bs)) {
1697 if (bdrv_flush(state->old_bs)) {
1698 error_setg(errp, QERR_IO_ERROR);
1699 goto out;
1703 if (!bdrv_is_first_non_filter(state->old_bs)) {
1704 error_setg(errp, QERR_FEATURE_DISABLED, "snapshot");
1705 goto out;
1708 if (action->type == TRANSACTION_ACTION_KIND_BLOCKDEV_SNAPSHOT_SYNC) {
1709 BlockdevSnapshotSync *s = action->u.blockdev_snapshot_sync.data;
1710 const char *format = s->has_format ? s->format : "qcow2";
1711 enum NewImageMode mode;
1712 const char *snapshot_node_name =
1713 s->has_snapshot_node_name ? s->snapshot_node_name : NULL;
1715 if (node_name && !snapshot_node_name) {
1716 error_setg(errp, "New snapshot node name missing");
1717 goto out;
1720 if (snapshot_node_name &&
1721 bdrv_lookup_bs(snapshot_node_name, snapshot_node_name, NULL)) {
1722 error_setg(errp, "New snapshot node name already in use");
1723 goto out;
1726 flags = state->old_bs->open_flags;
1727 flags &= ~(BDRV_O_SNAPSHOT | BDRV_O_COPY_ON_READ);
1728 flags |= BDRV_O_NO_BACKING;
1730 /* create new image w/backing file */
1731 mode = s->has_mode ? s->mode : NEW_IMAGE_MODE_ABSOLUTE_PATHS;
1732 if (mode != NEW_IMAGE_MODE_EXISTING) {
1733 int64_t size = bdrv_getlength(state->old_bs);
1734 if (size < 0) {
1735 error_setg_errno(errp, -size, "bdrv_getlength failed");
1736 goto out;
1738 bdrv_img_create(new_image_file, format,
1739 state->old_bs->filename,
1740 state->old_bs->drv->format_name,
1741 NULL, size, flags, false, &local_err);
1742 if (local_err) {
1743 error_propagate(errp, local_err);
1744 goto out;
1748 options = qdict_new();
1749 if (s->has_snapshot_node_name) {
1750 qdict_put_str(options, "node-name", snapshot_node_name);
1752 qdict_put_str(options, "driver", format);
1755 state->new_bs = bdrv_open(new_image_file, snapshot_ref, options, flags,
1756 errp);
1757 /* We will manually add the backing_hd field to the bs later */
1758 if (!state->new_bs) {
1759 goto out;
1762 if (bdrv_has_blk(state->new_bs)) {
1763 error_setg(errp, "The snapshot is already in use");
1764 goto out;
1767 if (bdrv_op_is_blocked(state->new_bs, BLOCK_OP_TYPE_EXTERNAL_SNAPSHOT,
1768 errp)) {
1769 goto out;
1772 if (state->new_bs->backing != NULL) {
1773 error_setg(errp, "The snapshot already has a backing image");
1774 goto out;
1777 if (!state->new_bs->drv->supports_backing) {
1778 error_setg(errp, "The snapshot does not support backing images");
1779 goto out;
1782 bdrv_set_aio_context(state->new_bs, aio_context);
1784 /* This removes our old bs and adds the new bs. This is an operation that
1785 * can fail, so we need to do it in .prepare; undoing it for abort is
1786 * always possible. */
1787 bdrv_ref(state->new_bs);
1788 bdrv_append(state->new_bs, state->old_bs, &local_err);
1789 if (local_err) {
1790 error_propagate(errp, local_err);
1791 goto out;
1793 state->overlay_appended = true;
1795 out:
1796 aio_context_release(aio_context);
1799 static void external_snapshot_commit(BlkActionState *common)
1801 ExternalSnapshotState *state =
1802 DO_UPCAST(ExternalSnapshotState, common, common);
1803 AioContext *aio_context;
1805 aio_context = bdrv_get_aio_context(state->old_bs);
1806 aio_context_acquire(aio_context);
1808 /* We don't need (or want) to use the transactional
1809 * bdrv_reopen_multiple() across all the entries at once, because we
1810 * don't want to abort all of them if one of them fails the reopen */
1811 if (!atomic_read(&state->old_bs->copy_on_read)) {
1812 bdrv_reopen(state->old_bs, state->old_bs->open_flags & ~BDRV_O_RDWR,
1813 NULL);
1816 aio_context_release(aio_context);
1819 static void external_snapshot_abort(BlkActionState *common)
1821 ExternalSnapshotState *state =
1822 DO_UPCAST(ExternalSnapshotState, common, common);
1823 if (state->new_bs) {
1824 if (state->overlay_appended) {
1825 AioContext *aio_context;
1827 aio_context = bdrv_get_aio_context(state->old_bs);
1828 aio_context_acquire(aio_context);
1830 bdrv_ref(state->old_bs); /* we can't let bdrv_set_backind_hd()
1831 close state->old_bs; we need it */
1832 bdrv_set_backing_hd(state->new_bs, NULL, &error_abort);
1833 bdrv_replace_node(state->new_bs, state->old_bs, &error_abort);
1834 bdrv_unref(state->old_bs); /* bdrv_replace_node() ref'ed old_bs */
1836 aio_context_release(aio_context);
1841 static void external_snapshot_clean(BlkActionState *common)
1843 ExternalSnapshotState *state =
1844 DO_UPCAST(ExternalSnapshotState, common, common);
1845 AioContext *aio_context;
1847 if (!state->old_bs) {
1848 return;
1851 aio_context = bdrv_get_aio_context(state->old_bs);
1852 aio_context_acquire(aio_context);
1854 bdrv_drained_end(state->old_bs);
1855 bdrv_unref(state->new_bs);
1857 aio_context_release(aio_context);
1860 typedef struct DriveBackupState {
1861 BlkActionState common;
1862 BlockDriverState *bs;
1863 BlockJob *job;
1864 } DriveBackupState;
1866 static BlockJob *do_drive_backup(DriveBackup *backup, BlockJobTxn *txn,
1867 Error **errp);
1869 static void drive_backup_prepare(BlkActionState *common, Error **errp)
1871 DriveBackupState *state = DO_UPCAST(DriveBackupState, common, common);
1872 BlockDriverState *bs;
1873 DriveBackup *backup;
1874 AioContext *aio_context;
1875 Error *local_err = NULL;
1877 assert(common->action->type == TRANSACTION_ACTION_KIND_DRIVE_BACKUP);
1878 backup = common->action->u.drive_backup.data;
1880 bs = qmp_get_root_bs(backup->device, errp);
1881 if (!bs) {
1882 return;
1885 aio_context = bdrv_get_aio_context(bs);
1886 aio_context_acquire(aio_context);
1888 /* Paired with .clean() */
1889 bdrv_drained_begin(bs);
1891 state->bs = bs;
1893 state->job = do_drive_backup(backup, common->block_job_txn, &local_err);
1894 if (local_err) {
1895 error_propagate(errp, local_err);
1896 goto out;
1899 out:
1900 aio_context_release(aio_context);
1903 static void drive_backup_commit(BlkActionState *common)
1905 DriveBackupState *state = DO_UPCAST(DriveBackupState, common, common);
1906 AioContext *aio_context;
1908 aio_context = bdrv_get_aio_context(state->bs);
1909 aio_context_acquire(aio_context);
1911 assert(state->job);
1912 block_job_start(state->job);
1914 aio_context_release(aio_context);
1917 static void drive_backup_abort(BlkActionState *common)
1919 DriveBackupState *state = DO_UPCAST(DriveBackupState, common, common);
1921 if (state->job) {
1922 AioContext *aio_context;
1924 aio_context = bdrv_get_aio_context(state->bs);
1925 aio_context_acquire(aio_context);
1927 block_job_cancel_sync(state->job);
1929 aio_context_release(aio_context);
1933 static void drive_backup_clean(BlkActionState *common)
1935 DriveBackupState *state = DO_UPCAST(DriveBackupState, common, common);
1936 AioContext *aio_context;
1938 if (!state->bs) {
1939 return;
1942 aio_context = bdrv_get_aio_context(state->bs);
1943 aio_context_acquire(aio_context);
1945 bdrv_drained_end(state->bs);
1947 aio_context_release(aio_context);
1950 typedef struct BlockdevBackupState {
1951 BlkActionState common;
1952 BlockDriverState *bs;
1953 BlockJob *job;
1954 } BlockdevBackupState;
1956 static BlockJob *do_blockdev_backup(BlockdevBackup *backup, BlockJobTxn *txn,
1957 Error **errp);
1959 static void blockdev_backup_prepare(BlkActionState *common, Error **errp)
1961 BlockdevBackupState *state = DO_UPCAST(BlockdevBackupState, common, common);
1962 BlockdevBackup *backup;
1963 BlockDriverState *bs, *target;
1964 AioContext *aio_context;
1965 Error *local_err = NULL;
1967 assert(common->action->type == TRANSACTION_ACTION_KIND_BLOCKDEV_BACKUP);
1968 backup = common->action->u.blockdev_backup.data;
1970 bs = qmp_get_root_bs(backup->device, errp);
1971 if (!bs) {
1972 return;
1975 target = bdrv_lookup_bs(backup->target, backup->target, errp);
1976 if (!target) {
1977 return;
1980 aio_context = bdrv_get_aio_context(bs);
1981 if (aio_context != bdrv_get_aio_context(target)) {
1982 error_setg(errp, "Backup between two IO threads is not implemented");
1983 return;
1985 aio_context_acquire(aio_context);
1986 state->bs = bs;
1988 /* Paired with .clean() */
1989 bdrv_drained_begin(state->bs);
1991 state->job = do_blockdev_backup(backup, common->block_job_txn, &local_err);
1992 if (local_err) {
1993 error_propagate(errp, local_err);
1994 goto out;
1997 out:
1998 aio_context_release(aio_context);
2001 static void blockdev_backup_commit(BlkActionState *common)
2003 BlockdevBackupState *state = DO_UPCAST(BlockdevBackupState, common, common);
2004 AioContext *aio_context;
2006 aio_context = bdrv_get_aio_context(state->bs);
2007 aio_context_acquire(aio_context);
2009 assert(state->job);
2010 block_job_start(state->job);
2012 aio_context_release(aio_context);
2015 static void blockdev_backup_abort(BlkActionState *common)
2017 BlockdevBackupState *state = DO_UPCAST(BlockdevBackupState, common, common);
2019 if (state->job) {
2020 AioContext *aio_context;
2022 aio_context = bdrv_get_aio_context(state->bs);
2023 aio_context_acquire(aio_context);
2025 block_job_cancel_sync(state->job);
2027 aio_context_release(aio_context);
2031 static void blockdev_backup_clean(BlkActionState *common)
2033 BlockdevBackupState *state = DO_UPCAST(BlockdevBackupState, common, common);
2034 AioContext *aio_context;
2036 if (!state->bs) {
2037 return;
2040 aio_context = bdrv_get_aio_context(state->bs);
2041 aio_context_acquire(aio_context);
2043 bdrv_drained_end(state->bs);
2045 aio_context_release(aio_context);
2048 typedef struct BlockDirtyBitmapState {
2049 BlkActionState common;
2050 BdrvDirtyBitmap *bitmap;
2051 BlockDriverState *bs;
2052 HBitmap *backup;
2053 bool prepared;
2054 } BlockDirtyBitmapState;
2056 static void block_dirty_bitmap_add_prepare(BlkActionState *common,
2057 Error **errp)
2059 Error *local_err = NULL;
2060 BlockDirtyBitmapAdd *action;
2061 BlockDirtyBitmapState *state = DO_UPCAST(BlockDirtyBitmapState,
2062 common, common);
2064 if (action_check_completion_mode(common, errp) < 0) {
2065 return;
2068 action = common->action->u.block_dirty_bitmap_add.data;
2069 /* AIO context taken and released within qmp_block_dirty_bitmap_add */
2070 qmp_block_dirty_bitmap_add(action->node, action->name,
2071 action->has_granularity, action->granularity,
2072 action->has_persistent, action->persistent,
2073 action->has_autoload, action->autoload,
2074 &local_err);
2076 if (!local_err) {
2077 state->prepared = true;
2078 } else {
2079 error_propagate(errp, local_err);
2083 static void block_dirty_bitmap_add_abort(BlkActionState *common)
2085 BlockDirtyBitmapAdd *action;
2086 BlockDirtyBitmapState *state = DO_UPCAST(BlockDirtyBitmapState,
2087 common, common);
2089 action = common->action->u.block_dirty_bitmap_add.data;
2090 /* Should not be able to fail: IF the bitmap was added via .prepare(),
2091 * then the node reference and bitmap name must have been valid.
2093 if (state->prepared) {
2094 qmp_block_dirty_bitmap_remove(action->node, action->name, &error_abort);
2098 static void block_dirty_bitmap_clear_prepare(BlkActionState *common,
2099 Error **errp)
2101 BlockDirtyBitmapState *state = DO_UPCAST(BlockDirtyBitmapState,
2102 common, common);
2103 BlockDirtyBitmap *action;
2105 if (action_check_completion_mode(common, errp) < 0) {
2106 return;
2109 action = common->action->u.block_dirty_bitmap_clear.data;
2110 state->bitmap = block_dirty_bitmap_lookup(action->node,
2111 action->name,
2112 &state->bs,
2113 errp);
2114 if (!state->bitmap) {
2115 return;
2118 if (bdrv_dirty_bitmap_frozen(state->bitmap)) {
2119 error_setg(errp, "Cannot modify a frozen bitmap");
2120 return;
2121 } else if (!bdrv_dirty_bitmap_enabled(state->bitmap)) {
2122 error_setg(errp, "Cannot clear a disabled bitmap");
2123 return;
2124 } else if (bdrv_dirty_bitmap_readonly(state->bitmap)) {
2125 error_setg(errp, "Cannot clear a readonly bitmap");
2126 return;
2129 bdrv_clear_dirty_bitmap(state->bitmap, &state->backup);
2132 static void block_dirty_bitmap_clear_abort(BlkActionState *common)
2134 BlockDirtyBitmapState *state = DO_UPCAST(BlockDirtyBitmapState,
2135 common, common);
2137 if (state->backup) {
2138 bdrv_undo_clear_dirty_bitmap(state->bitmap, state->backup);
2142 static void block_dirty_bitmap_clear_commit(BlkActionState *common)
2144 BlockDirtyBitmapState *state = DO_UPCAST(BlockDirtyBitmapState,
2145 common, common);
2147 hbitmap_free(state->backup);
2150 static void abort_prepare(BlkActionState *common, Error **errp)
2152 error_setg(errp, "Transaction aborted using Abort action");
2155 static void abort_commit(BlkActionState *common)
2157 g_assert_not_reached(); /* this action never succeeds */
2160 static const BlkActionOps actions[] = {
2161 [TRANSACTION_ACTION_KIND_BLOCKDEV_SNAPSHOT] = {
2162 .instance_size = sizeof(ExternalSnapshotState),
2163 .prepare = external_snapshot_prepare,
2164 .commit = external_snapshot_commit,
2165 .abort = external_snapshot_abort,
2166 .clean = external_snapshot_clean,
2168 [TRANSACTION_ACTION_KIND_BLOCKDEV_SNAPSHOT_SYNC] = {
2169 .instance_size = sizeof(ExternalSnapshotState),
2170 .prepare = external_snapshot_prepare,
2171 .commit = external_snapshot_commit,
2172 .abort = external_snapshot_abort,
2173 .clean = external_snapshot_clean,
2175 [TRANSACTION_ACTION_KIND_DRIVE_BACKUP] = {
2176 .instance_size = sizeof(DriveBackupState),
2177 .prepare = drive_backup_prepare,
2178 .commit = drive_backup_commit,
2179 .abort = drive_backup_abort,
2180 .clean = drive_backup_clean,
2182 [TRANSACTION_ACTION_KIND_BLOCKDEV_BACKUP] = {
2183 .instance_size = sizeof(BlockdevBackupState),
2184 .prepare = blockdev_backup_prepare,
2185 .commit = blockdev_backup_commit,
2186 .abort = blockdev_backup_abort,
2187 .clean = blockdev_backup_clean,
2189 [TRANSACTION_ACTION_KIND_ABORT] = {
2190 .instance_size = sizeof(BlkActionState),
2191 .prepare = abort_prepare,
2192 .commit = abort_commit,
2194 [TRANSACTION_ACTION_KIND_BLOCKDEV_SNAPSHOT_INTERNAL_SYNC] = {
2195 .instance_size = sizeof(InternalSnapshotState),
2196 .prepare = internal_snapshot_prepare,
2197 .abort = internal_snapshot_abort,
2198 .clean = internal_snapshot_clean,
2200 [TRANSACTION_ACTION_KIND_BLOCK_DIRTY_BITMAP_ADD] = {
2201 .instance_size = sizeof(BlockDirtyBitmapState),
2202 .prepare = block_dirty_bitmap_add_prepare,
2203 .abort = block_dirty_bitmap_add_abort,
2205 [TRANSACTION_ACTION_KIND_BLOCK_DIRTY_BITMAP_CLEAR] = {
2206 .instance_size = sizeof(BlockDirtyBitmapState),
2207 .prepare = block_dirty_bitmap_clear_prepare,
2208 .commit = block_dirty_bitmap_clear_commit,
2209 .abort = block_dirty_bitmap_clear_abort,
2214 * Allocate a TransactionProperties structure if necessary, and fill
2215 * that structure with desired defaults if they are unset.
2217 static TransactionProperties *get_transaction_properties(
2218 TransactionProperties *props)
2220 if (!props) {
2221 props = g_new0(TransactionProperties, 1);
2224 if (!props->has_completion_mode) {
2225 props->has_completion_mode = true;
2226 props->completion_mode = ACTION_COMPLETION_MODE_INDIVIDUAL;
2229 return props;
2233 * 'Atomic' group operations. The operations are performed as a set, and if
2234 * any fail then we roll back all operations in the group.
2236 void qmp_transaction(TransactionActionList *dev_list,
2237 bool has_props,
2238 struct TransactionProperties *props,
2239 Error **errp)
2241 TransactionActionList *dev_entry = dev_list;
2242 BlockJobTxn *block_job_txn = NULL;
2243 BlkActionState *state, *next;
2244 Error *local_err = NULL;
2246 QSIMPLEQ_HEAD(snap_bdrv_states, BlkActionState) snap_bdrv_states;
2247 QSIMPLEQ_INIT(&snap_bdrv_states);
2249 /* Does this transaction get canceled as a group on failure?
2250 * If not, we don't really need to make a BlockJobTxn.
2252 props = get_transaction_properties(props);
2253 if (props->completion_mode != ACTION_COMPLETION_MODE_INDIVIDUAL) {
2254 block_job_txn = block_job_txn_new();
2257 /* drain all i/o before any operations */
2258 bdrv_drain_all();
2260 /* We don't do anything in this loop that commits us to the operations */
2261 while (NULL != dev_entry) {
2262 TransactionAction *dev_info = NULL;
2263 const BlkActionOps *ops;
2265 dev_info = dev_entry->value;
2266 dev_entry = dev_entry->next;
2268 assert(dev_info->type < ARRAY_SIZE(actions));
2270 ops = &actions[dev_info->type];
2271 assert(ops->instance_size > 0);
2273 state = g_malloc0(ops->instance_size);
2274 state->ops = ops;
2275 state->action = dev_info;
2276 state->block_job_txn = block_job_txn;
2277 state->txn_props = props;
2278 QSIMPLEQ_INSERT_TAIL(&snap_bdrv_states, state, entry);
2280 state->ops->prepare(state, &local_err);
2281 if (local_err) {
2282 error_propagate(errp, local_err);
2283 goto delete_and_fail;
2287 QSIMPLEQ_FOREACH(state, &snap_bdrv_states, entry) {
2288 if (state->ops->commit) {
2289 state->ops->commit(state);
2293 /* success */
2294 goto exit;
2296 delete_and_fail:
2297 /* failure, and it is all-or-none; roll back all operations */
2298 QSIMPLEQ_FOREACH(state, &snap_bdrv_states, entry) {
2299 if (state->ops->abort) {
2300 state->ops->abort(state);
2303 exit:
2304 QSIMPLEQ_FOREACH_SAFE(state, &snap_bdrv_states, entry, next) {
2305 if (state->ops->clean) {
2306 state->ops->clean(state);
2308 g_free(state);
2310 if (!has_props) {
2311 qapi_free_TransactionProperties(props);
2313 block_job_txn_unref(block_job_txn);
2316 void qmp_eject(bool has_device, const char *device,
2317 bool has_id, const char *id,
2318 bool has_force, bool force, Error **errp)
2320 Error *local_err = NULL;
2321 int rc;
2323 if (!has_force) {
2324 force = false;
2327 rc = do_open_tray(has_device ? device : NULL,
2328 has_id ? id : NULL,
2329 force, &local_err);
2330 if (rc && rc != -ENOSYS) {
2331 error_propagate(errp, local_err);
2332 return;
2334 error_free(local_err);
2336 qmp_x_blockdev_remove_medium(has_device, device, has_id, id, errp);
2339 void qmp_block_passwd(bool has_device, const char *device,
2340 bool has_node_name, const char *node_name,
2341 const char *password, Error **errp)
2343 error_setg(errp,
2344 "Setting block passwords directly is no longer supported");
2348 * Attempt to open the tray of @device.
2349 * If @force, ignore its tray lock.
2350 * Else, if the tray is locked, don't open it, but ask the guest to open it.
2351 * On error, store an error through @errp and return -errno.
2352 * If @device does not exist, return -ENODEV.
2353 * If it has no removable media, return -ENOTSUP.
2354 * If it has no tray, return -ENOSYS.
2355 * If the guest was asked to open the tray, return -EINPROGRESS.
2356 * Else, return 0.
2358 static int do_open_tray(const char *blk_name, const char *qdev_id,
2359 bool force, Error **errp)
2361 BlockBackend *blk;
2362 const char *device = qdev_id ?: blk_name;
2363 bool locked;
2365 blk = qmp_get_blk(blk_name, qdev_id, errp);
2366 if (!blk) {
2367 return -ENODEV;
2370 if (!blk_dev_has_removable_media(blk)) {
2371 error_setg(errp, "Device '%s' is not removable", device);
2372 return -ENOTSUP;
2375 if (!blk_dev_has_tray(blk)) {
2376 error_setg(errp, "Device '%s' does not have a tray", device);
2377 return -ENOSYS;
2380 if (blk_dev_is_tray_open(blk)) {
2381 return 0;
2384 locked = blk_dev_is_medium_locked(blk);
2385 if (locked) {
2386 blk_dev_eject_request(blk, force);
2389 if (!locked || force) {
2390 blk_dev_change_media_cb(blk, false, &error_abort);
2393 if (locked && !force) {
2394 error_setg(errp, "Device '%s' is locked and force was not specified, "
2395 "wait for tray to open and try again", device);
2396 return -EINPROGRESS;
2399 return 0;
2402 void qmp_blockdev_open_tray(bool has_device, const char *device,
2403 bool has_id, const char *id,
2404 bool has_force, bool force,
2405 Error **errp)
2407 Error *local_err = NULL;
2408 int rc;
2410 if (!has_force) {
2411 force = false;
2413 rc = do_open_tray(has_device ? device : NULL,
2414 has_id ? id : NULL,
2415 force, &local_err);
2416 if (rc && rc != -ENOSYS && rc != -EINPROGRESS) {
2417 error_propagate(errp, local_err);
2418 return;
2420 error_free(local_err);
2423 void qmp_blockdev_close_tray(bool has_device, const char *device,
2424 bool has_id, const char *id,
2425 Error **errp)
2427 BlockBackend *blk;
2428 Error *local_err = NULL;
2430 device = has_device ? device : NULL;
2431 id = has_id ? id : NULL;
2433 blk = qmp_get_blk(device, id, errp);
2434 if (!blk) {
2435 return;
2438 if (!blk_dev_has_removable_media(blk)) {
2439 error_setg(errp, "Device '%s' is not removable", device ?: id);
2440 return;
2443 if (!blk_dev_has_tray(blk)) {
2444 /* Ignore this command on tray-less devices */
2445 return;
2448 if (!blk_dev_is_tray_open(blk)) {
2449 return;
2452 blk_dev_change_media_cb(blk, true, &local_err);
2453 if (local_err) {
2454 error_propagate(errp, local_err);
2455 return;
2459 void qmp_x_blockdev_remove_medium(bool has_device, const char *device,
2460 bool has_id, const char *id, Error **errp)
2462 BlockBackend *blk;
2463 BlockDriverState *bs;
2464 AioContext *aio_context;
2465 bool has_attached_device;
2467 device = has_device ? device : NULL;
2468 id = has_id ? id : NULL;
2470 blk = qmp_get_blk(device, id, errp);
2471 if (!blk) {
2472 return;
2475 /* For BBs without a device, we can exchange the BDS tree at will */
2476 has_attached_device = blk_get_attached_dev(blk);
2478 if (has_attached_device && !blk_dev_has_removable_media(blk)) {
2479 error_setg(errp, "Device '%s' is not removable", device ?: id);
2480 return;
2483 if (has_attached_device && blk_dev_has_tray(blk) &&
2484 !blk_dev_is_tray_open(blk))
2486 error_setg(errp, "Tray of device '%s' is not open", device ?: id);
2487 return;
2490 bs = blk_bs(blk);
2491 if (!bs) {
2492 return;
2495 aio_context = bdrv_get_aio_context(bs);
2496 aio_context_acquire(aio_context);
2498 if (bdrv_op_is_blocked(bs, BLOCK_OP_TYPE_EJECT, errp)) {
2499 goto out;
2502 blk_remove_bs(blk);
2504 if (!blk_dev_has_tray(blk)) {
2505 /* For tray-less devices, blockdev-open-tray is a no-op (or may not be
2506 * called at all); therefore, the medium needs to be ejected here.
2507 * Do it after blk_remove_bs() so blk_is_inserted(blk) returns the @load
2508 * value passed here (i.e. false). */
2509 blk_dev_change_media_cb(blk, false, &error_abort);
2512 out:
2513 aio_context_release(aio_context);
2516 static void qmp_blockdev_insert_anon_medium(BlockBackend *blk,
2517 BlockDriverState *bs, Error **errp)
2519 Error *local_err = NULL;
2520 bool has_device;
2521 int ret;
2523 /* For BBs without a device, we can exchange the BDS tree at will */
2524 has_device = blk_get_attached_dev(blk);
2526 if (has_device && !blk_dev_has_removable_media(blk)) {
2527 error_setg(errp, "Device is not removable");
2528 return;
2531 if (has_device && blk_dev_has_tray(blk) && !blk_dev_is_tray_open(blk)) {
2532 error_setg(errp, "Tray of the device is not open");
2533 return;
2536 if (blk_bs(blk)) {
2537 error_setg(errp, "There already is a medium in the device");
2538 return;
2541 ret = blk_insert_bs(blk, bs, errp);
2542 if (ret < 0) {
2543 return;
2546 if (!blk_dev_has_tray(blk)) {
2547 /* For tray-less devices, blockdev-close-tray is a no-op (or may not be
2548 * called at all); therefore, the medium needs to be pushed into the
2549 * slot here.
2550 * Do it after blk_insert_bs() so blk_is_inserted(blk) returns the @load
2551 * value passed here (i.e. true). */
2552 blk_dev_change_media_cb(blk, true, &local_err);
2553 if (local_err) {
2554 error_propagate(errp, local_err);
2555 blk_remove_bs(blk);
2556 return;
2561 void qmp_x_blockdev_insert_medium(bool has_device, const char *device,
2562 bool has_id, const char *id,
2563 const char *node_name, Error **errp)
2565 BlockBackend *blk;
2566 BlockDriverState *bs;
2568 blk = qmp_get_blk(has_device ? device : NULL,
2569 has_id ? id : NULL,
2570 errp);
2571 if (!blk) {
2572 return;
2575 bs = bdrv_find_node(node_name);
2576 if (!bs) {
2577 error_setg(errp, "Node '%s' not found", node_name);
2578 return;
2581 if (bdrv_has_blk(bs)) {
2582 error_setg(errp, "Node '%s' is already in use", node_name);
2583 return;
2586 qmp_blockdev_insert_anon_medium(blk, bs, errp);
2589 void qmp_blockdev_change_medium(bool has_device, const char *device,
2590 bool has_id, const char *id,
2591 const char *filename,
2592 bool has_format, const char *format,
2593 bool has_read_only,
2594 BlockdevChangeReadOnlyMode read_only,
2595 Error **errp)
2597 BlockBackend *blk;
2598 BlockDriverState *medium_bs = NULL;
2599 int bdrv_flags;
2600 bool detect_zeroes;
2601 int rc;
2602 QDict *options = NULL;
2603 Error *err = NULL;
2605 blk = qmp_get_blk(has_device ? device : NULL,
2606 has_id ? id : NULL,
2607 errp);
2608 if (!blk) {
2609 goto fail;
2612 if (blk_bs(blk)) {
2613 blk_update_root_state(blk);
2616 bdrv_flags = blk_get_open_flags_from_root_state(blk);
2617 bdrv_flags &= ~(BDRV_O_TEMPORARY | BDRV_O_SNAPSHOT | BDRV_O_NO_BACKING |
2618 BDRV_O_PROTOCOL);
2620 if (!has_read_only) {
2621 read_only = BLOCKDEV_CHANGE_READ_ONLY_MODE_RETAIN;
2624 switch (read_only) {
2625 case BLOCKDEV_CHANGE_READ_ONLY_MODE_RETAIN:
2626 break;
2628 case BLOCKDEV_CHANGE_READ_ONLY_MODE_READ_ONLY:
2629 bdrv_flags &= ~BDRV_O_RDWR;
2630 break;
2632 case BLOCKDEV_CHANGE_READ_ONLY_MODE_READ_WRITE:
2633 bdrv_flags |= BDRV_O_RDWR;
2634 break;
2636 default:
2637 abort();
2640 options = qdict_new();
2641 detect_zeroes = blk_get_detect_zeroes_from_root_state(blk);
2642 qdict_put_str(options, "detect-zeroes", detect_zeroes ? "on" : "off");
2644 if (has_format) {
2645 qdict_put_str(options, "driver", format);
2648 medium_bs = bdrv_open(filename, NULL, options, bdrv_flags, errp);
2649 if (!medium_bs) {
2650 goto fail;
2653 rc = do_open_tray(has_device ? device : NULL,
2654 has_id ? id : NULL,
2655 false, &err);
2656 if (rc && rc != -ENOSYS) {
2657 error_propagate(errp, err);
2658 goto fail;
2660 error_free(err);
2661 err = NULL;
2663 qmp_x_blockdev_remove_medium(has_device, device, has_id, id, &err);
2664 if (err) {
2665 error_propagate(errp, err);
2666 goto fail;
2669 qmp_blockdev_insert_anon_medium(blk, medium_bs, &err);
2670 if (err) {
2671 error_propagate(errp, err);
2672 goto fail;
2675 qmp_blockdev_close_tray(has_device, device, has_id, id, errp);
2677 fail:
2678 /* If the medium has been inserted, the device has its own reference, so
2679 * ours must be relinquished; and if it has not been inserted successfully,
2680 * the reference must be relinquished anyway */
2681 bdrv_unref(medium_bs);
2684 /* throttling disk I/O limits */
2685 void qmp_block_set_io_throttle(BlockIOThrottle *arg, Error **errp)
2687 ThrottleConfig cfg;
2688 BlockDriverState *bs;
2689 BlockBackend *blk;
2690 AioContext *aio_context;
2692 blk = qmp_get_blk(arg->has_device ? arg->device : NULL,
2693 arg->has_id ? arg->id : NULL,
2694 errp);
2695 if (!blk) {
2696 return;
2699 aio_context = blk_get_aio_context(blk);
2700 aio_context_acquire(aio_context);
2702 bs = blk_bs(blk);
2703 if (!bs) {
2704 error_setg(errp, "Device has no medium");
2705 goto out;
2708 throttle_config_init(&cfg);
2709 cfg.buckets[THROTTLE_BPS_TOTAL].avg = arg->bps;
2710 cfg.buckets[THROTTLE_BPS_READ].avg = arg->bps_rd;
2711 cfg.buckets[THROTTLE_BPS_WRITE].avg = arg->bps_wr;
2713 cfg.buckets[THROTTLE_OPS_TOTAL].avg = arg->iops;
2714 cfg.buckets[THROTTLE_OPS_READ].avg = arg->iops_rd;
2715 cfg.buckets[THROTTLE_OPS_WRITE].avg = arg->iops_wr;
2717 if (arg->has_bps_max) {
2718 cfg.buckets[THROTTLE_BPS_TOTAL].max = arg->bps_max;
2720 if (arg->has_bps_rd_max) {
2721 cfg.buckets[THROTTLE_BPS_READ].max = arg->bps_rd_max;
2723 if (arg->has_bps_wr_max) {
2724 cfg.buckets[THROTTLE_BPS_WRITE].max = arg->bps_wr_max;
2726 if (arg->has_iops_max) {
2727 cfg.buckets[THROTTLE_OPS_TOTAL].max = arg->iops_max;
2729 if (arg->has_iops_rd_max) {
2730 cfg.buckets[THROTTLE_OPS_READ].max = arg->iops_rd_max;
2732 if (arg->has_iops_wr_max) {
2733 cfg.buckets[THROTTLE_OPS_WRITE].max = arg->iops_wr_max;
2736 if (arg->has_bps_max_length) {
2737 cfg.buckets[THROTTLE_BPS_TOTAL].burst_length = arg->bps_max_length;
2739 if (arg->has_bps_rd_max_length) {
2740 cfg.buckets[THROTTLE_BPS_READ].burst_length = arg->bps_rd_max_length;
2742 if (arg->has_bps_wr_max_length) {
2743 cfg.buckets[THROTTLE_BPS_WRITE].burst_length = arg->bps_wr_max_length;
2745 if (arg->has_iops_max_length) {
2746 cfg.buckets[THROTTLE_OPS_TOTAL].burst_length = arg->iops_max_length;
2748 if (arg->has_iops_rd_max_length) {
2749 cfg.buckets[THROTTLE_OPS_READ].burst_length = arg->iops_rd_max_length;
2751 if (arg->has_iops_wr_max_length) {
2752 cfg.buckets[THROTTLE_OPS_WRITE].burst_length = arg->iops_wr_max_length;
2755 if (arg->has_iops_size) {
2756 cfg.op_size = arg->iops_size;
2759 if (!throttle_is_valid(&cfg, errp)) {
2760 goto out;
2763 if (throttle_enabled(&cfg)) {
2764 /* Enable I/O limits if they're not enabled yet, otherwise
2765 * just update the throttling group. */
2766 if (!blk_get_public(blk)->throttle_group_member.throttle_state) {
2767 blk_io_limits_enable(blk,
2768 arg->has_group ? arg->group :
2769 arg->has_device ? arg->device :
2770 arg->id);
2771 } else if (arg->has_group) {
2772 blk_io_limits_update_group(blk, arg->group);
2774 /* Set the new throttling configuration */
2775 blk_set_io_limits(blk, &cfg);
2776 } else if (blk_get_public(blk)->throttle_group_member.throttle_state) {
2777 /* If all throttling settings are set to 0, disable I/O limits */
2778 blk_io_limits_disable(blk);
2781 out:
2782 aio_context_release(aio_context);
2785 void qmp_block_dirty_bitmap_add(const char *node, const char *name,
2786 bool has_granularity, uint32_t granularity,
2787 bool has_persistent, bool persistent,
2788 bool has_autoload, bool autoload,
2789 Error **errp)
2791 BlockDriverState *bs;
2792 BdrvDirtyBitmap *bitmap;
2794 if (!name || name[0] == '\0') {
2795 error_setg(errp, "Bitmap name cannot be empty");
2796 return;
2799 bs = bdrv_lookup_bs(node, node, errp);
2800 if (!bs) {
2801 return;
2804 if (has_granularity) {
2805 if (granularity < 512 || !is_power_of_2(granularity)) {
2806 error_setg(errp, "Granularity must be power of 2 "
2807 "and at least 512");
2808 return;
2810 } else {
2811 /* Default to cluster size, if available: */
2812 granularity = bdrv_get_default_bitmap_granularity(bs);
2815 if (!has_persistent) {
2816 persistent = false;
2818 if (!has_autoload) {
2819 autoload = false;
2822 if (has_autoload && !persistent) {
2823 error_setg(errp, "Autoload flag must be used only for persistent "
2824 "bitmaps");
2825 return;
2828 if (persistent &&
2829 !bdrv_can_store_new_dirty_bitmap(bs, name, granularity, errp))
2831 return;
2834 bitmap = bdrv_create_dirty_bitmap(bs, granularity, name, errp);
2835 if (bitmap == NULL) {
2836 return;
2839 bdrv_dirty_bitmap_set_persistance(bitmap, persistent);
2840 bdrv_dirty_bitmap_set_autoload(bitmap, autoload);
2843 void qmp_block_dirty_bitmap_remove(const char *node, const char *name,
2844 Error **errp)
2846 BlockDriverState *bs;
2847 BdrvDirtyBitmap *bitmap;
2848 Error *local_err = NULL;
2850 bitmap = block_dirty_bitmap_lookup(node, name, &bs, errp);
2851 if (!bitmap || !bs) {
2852 return;
2855 if (bdrv_dirty_bitmap_frozen(bitmap)) {
2856 error_setg(errp,
2857 "Bitmap '%s' is currently frozen and cannot be removed",
2858 name);
2859 return;
2862 if (bdrv_dirty_bitmap_get_persistance(bitmap)) {
2863 bdrv_remove_persistent_dirty_bitmap(bs, name, &local_err);
2864 if (local_err != NULL) {
2865 error_propagate(errp, local_err);
2866 return;
2870 bdrv_dirty_bitmap_make_anon(bitmap);
2871 bdrv_release_dirty_bitmap(bs, bitmap);
2875 * Completely clear a bitmap, for the purposes of synchronizing a bitmap
2876 * immediately after a full backup operation.
2878 void qmp_block_dirty_bitmap_clear(const char *node, const char *name,
2879 Error **errp)
2881 BdrvDirtyBitmap *bitmap;
2882 BlockDriverState *bs;
2884 bitmap = block_dirty_bitmap_lookup(node, name, &bs, errp);
2885 if (!bitmap || !bs) {
2886 return;
2889 if (bdrv_dirty_bitmap_frozen(bitmap)) {
2890 error_setg(errp,
2891 "Bitmap '%s' is currently frozen and cannot be modified",
2892 name);
2893 return;
2894 } else if (!bdrv_dirty_bitmap_enabled(bitmap)) {
2895 error_setg(errp,
2896 "Bitmap '%s' is currently disabled and cannot be cleared",
2897 name);
2898 return;
2899 } else if (bdrv_dirty_bitmap_readonly(bitmap)) {
2900 error_setg(errp, "Bitmap '%s' is readonly and cannot be cleared", name);
2901 return;
2904 bdrv_clear_dirty_bitmap(bitmap, NULL);
2907 BlockDirtyBitmapSha256 *qmp_x_debug_block_dirty_bitmap_sha256(const char *node,
2908 const char *name,
2909 Error **errp)
2911 BdrvDirtyBitmap *bitmap;
2912 BlockDriverState *bs;
2913 BlockDirtyBitmapSha256 *ret = NULL;
2914 char *sha256;
2916 bitmap = block_dirty_bitmap_lookup(node, name, &bs, errp);
2917 if (!bitmap || !bs) {
2918 return NULL;
2921 sha256 = bdrv_dirty_bitmap_sha256(bitmap, errp);
2922 if (sha256 == NULL) {
2923 return NULL;
2926 ret = g_new(BlockDirtyBitmapSha256, 1);
2927 ret->sha256 = sha256;
2929 return ret;
2932 void hmp_drive_del(Monitor *mon, const QDict *qdict)
2934 const char *id = qdict_get_str(qdict, "id");
2935 BlockBackend *blk;
2936 BlockDriverState *bs;
2937 AioContext *aio_context;
2938 Error *local_err = NULL;
2940 bs = bdrv_find_node(id);
2941 if (bs) {
2942 qmp_blockdev_del(id, &local_err);
2943 if (local_err) {
2944 error_report_err(local_err);
2946 return;
2949 blk = blk_by_name(id);
2950 if (!blk) {
2951 error_report("Device '%s' not found", id);
2952 return;
2955 if (!blk_legacy_dinfo(blk)) {
2956 error_report("Deleting device added with blockdev-add"
2957 " is not supported");
2958 return;
2961 aio_context = blk_get_aio_context(blk);
2962 aio_context_acquire(aio_context);
2964 bs = blk_bs(blk);
2965 if (bs) {
2966 if (bdrv_op_is_blocked(bs, BLOCK_OP_TYPE_DRIVE_DEL, &local_err)) {
2967 error_report_err(local_err);
2968 aio_context_release(aio_context);
2969 return;
2972 blk_remove_bs(blk);
2975 /* Make the BlockBackend and the attached BlockDriverState anonymous */
2976 monitor_remove_blk(blk);
2978 /* If this BlockBackend has a device attached to it, its refcount will be
2979 * decremented when the device is removed; otherwise we have to do so here.
2981 if (blk_get_attached_dev(blk)) {
2982 /* Further I/O must not pause the guest */
2983 blk_set_on_error(blk, BLOCKDEV_ON_ERROR_REPORT,
2984 BLOCKDEV_ON_ERROR_REPORT);
2985 } else {
2986 blk_unref(blk);
2989 aio_context_release(aio_context);
2992 void qmp_block_resize(bool has_device, const char *device,
2993 bool has_node_name, const char *node_name,
2994 int64_t size, Error **errp)
2996 Error *local_err = NULL;
2997 BlockBackend *blk = NULL;
2998 BlockDriverState *bs;
2999 AioContext *aio_context;
3000 int ret;
3002 bs = bdrv_lookup_bs(has_device ? device : NULL,
3003 has_node_name ? node_name : NULL,
3004 &local_err);
3005 if (local_err) {
3006 error_propagate(errp, local_err);
3007 return;
3010 aio_context = bdrv_get_aio_context(bs);
3011 aio_context_acquire(aio_context);
3013 if (!bdrv_is_first_non_filter(bs)) {
3014 error_setg(errp, QERR_FEATURE_DISABLED, "resize");
3015 goto out;
3018 if (size < 0) {
3019 error_setg(errp, QERR_INVALID_PARAMETER_VALUE, "size", "a >0 size");
3020 goto out;
3023 if (bdrv_op_is_blocked(bs, BLOCK_OP_TYPE_RESIZE, NULL)) {
3024 error_setg(errp, QERR_DEVICE_IN_USE, device);
3025 goto out;
3028 blk = blk_new(BLK_PERM_RESIZE, BLK_PERM_ALL);
3029 ret = blk_insert_bs(blk, bs, errp);
3030 if (ret < 0) {
3031 goto out;
3034 bdrv_drained_begin(bs);
3035 ret = blk_truncate(blk, size, PREALLOC_MODE_OFF, errp);
3036 bdrv_drained_end(bs);
3038 out:
3039 blk_unref(blk);
3040 aio_context_release(aio_context);
3043 void qmp_block_stream(bool has_job_id, const char *job_id, const char *device,
3044 bool has_base, const char *base,
3045 bool has_base_node, const char *base_node,
3046 bool has_backing_file, const char *backing_file,
3047 bool has_speed, int64_t speed,
3048 bool has_on_error, BlockdevOnError on_error,
3049 Error **errp)
3051 BlockDriverState *bs, *iter;
3052 BlockDriverState *base_bs = NULL;
3053 AioContext *aio_context;
3054 Error *local_err = NULL;
3055 const char *base_name = NULL;
3057 if (!has_on_error) {
3058 on_error = BLOCKDEV_ON_ERROR_REPORT;
3061 bs = bdrv_lookup_bs(device, device, errp);
3062 if (!bs) {
3063 return;
3066 aio_context = bdrv_get_aio_context(bs);
3067 aio_context_acquire(aio_context);
3069 if (has_base && has_base_node) {
3070 error_setg(errp, "'base' and 'base-node' cannot be specified "
3071 "at the same time");
3072 goto out;
3075 if (has_base) {
3076 base_bs = bdrv_find_backing_image(bs, base);
3077 if (base_bs == NULL) {
3078 error_setg(errp, QERR_BASE_NOT_FOUND, base);
3079 goto out;
3081 assert(bdrv_get_aio_context(base_bs) == aio_context);
3082 base_name = base;
3085 if (has_base_node) {
3086 base_bs = bdrv_lookup_bs(NULL, base_node, errp);
3087 if (!base_bs) {
3088 goto out;
3090 if (bs == base_bs || !bdrv_chain_contains(bs, base_bs)) {
3091 error_setg(errp, "Node '%s' is not a backing image of '%s'",
3092 base_node, device);
3093 goto out;
3095 assert(bdrv_get_aio_context(base_bs) == aio_context);
3096 base_name = base_bs->filename;
3099 /* Check for op blockers in the whole chain between bs and base */
3100 for (iter = bs; iter && iter != base_bs; iter = backing_bs(iter)) {
3101 if (bdrv_op_is_blocked(iter, BLOCK_OP_TYPE_STREAM, errp)) {
3102 goto out;
3106 /* if we are streaming the entire chain, the result will have no backing
3107 * file, and specifying one is therefore an error */
3108 if (base_bs == NULL && has_backing_file) {
3109 error_setg(errp, "backing file specified, but streaming the "
3110 "entire chain");
3111 goto out;
3114 /* backing_file string overrides base bs filename */
3115 base_name = has_backing_file ? backing_file : base_name;
3117 stream_start(has_job_id ? job_id : NULL, bs, base_bs, base_name,
3118 has_speed ? speed : 0, on_error, &local_err);
3119 if (local_err) {
3120 error_propagate(errp, local_err);
3121 goto out;
3124 trace_qmp_block_stream(bs, bs->job);
3126 out:
3127 aio_context_release(aio_context);
3130 void qmp_block_commit(bool has_job_id, const char *job_id, const char *device,
3131 bool has_base, const char *base,
3132 bool has_top, const char *top,
3133 bool has_backing_file, const char *backing_file,
3134 bool has_speed, int64_t speed,
3135 bool has_filter_node_name, const char *filter_node_name,
3136 Error **errp)
3138 BlockDriverState *bs;
3139 BlockDriverState *iter;
3140 BlockDriverState *base_bs, *top_bs;
3141 AioContext *aio_context;
3142 Error *local_err = NULL;
3143 /* This will be part of the QMP command, if/when the
3144 * BlockdevOnError change for blkmirror makes it in
3146 BlockdevOnError on_error = BLOCKDEV_ON_ERROR_REPORT;
3148 if (!has_speed) {
3149 speed = 0;
3151 if (!has_filter_node_name) {
3152 filter_node_name = NULL;
3155 /* Important Note:
3156 * libvirt relies on the DeviceNotFound error class in order to probe for
3157 * live commit feature versions; for this to work, we must make sure to
3158 * perform the device lookup before any generic errors that may occur in a
3159 * scenario in which all optional arguments are omitted. */
3160 bs = qmp_get_root_bs(device, &local_err);
3161 if (!bs) {
3162 bs = bdrv_lookup_bs(device, device, NULL);
3163 if (!bs) {
3164 error_free(local_err);
3165 error_set(errp, ERROR_CLASS_DEVICE_NOT_FOUND,
3166 "Device '%s' not found", device);
3167 } else {
3168 error_propagate(errp, local_err);
3170 return;
3173 aio_context = bdrv_get_aio_context(bs);
3174 aio_context_acquire(aio_context);
3176 if (bdrv_op_is_blocked(bs, BLOCK_OP_TYPE_COMMIT_SOURCE, errp)) {
3177 goto out;
3180 /* default top_bs is the active layer */
3181 top_bs = bs;
3183 if (has_top && top) {
3184 if (strcmp(bs->filename, top) != 0) {
3185 top_bs = bdrv_find_backing_image(bs, top);
3189 if (top_bs == NULL) {
3190 error_setg(errp, "Top image file %s not found", top ? top : "NULL");
3191 goto out;
3194 assert(bdrv_get_aio_context(top_bs) == aio_context);
3196 if (has_base && base) {
3197 base_bs = bdrv_find_backing_image(top_bs, base);
3198 } else {
3199 base_bs = bdrv_find_base(top_bs);
3202 if (base_bs == NULL) {
3203 error_setg(errp, QERR_BASE_NOT_FOUND, base ? base : "NULL");
3204 goto out;
3207 assert(bdrv_get_aio_context(base_bs) == aio_context);
3209 for (iter = top_bs; iter != backing_bs(base_bs); iter = backing_bs(iter)) {
3210 if (bdrv_op_is_blocked(iter, BLOCK_OP_TYPE_COMMIT_TARGET, errp)) {
3211 goto out;
3215 /* Do not allow attempts to commit an image into itself */
3216 if (top_bs == base_bs) {
3217 error_setg(errp, "cannot commit an image into itself");
3218 goto out;
3221 if (top_bs == bs) {
3222 if (has_backing_file) {
3223 error_setg(errp, "'backing-file' specified,"
3224 " but 'top' is the active layer");
3225 goto out;
3227 commit_active_start(has_job_id ? job_id : NULL, bs, base_bs,
3228 BLOCK_JOB_DEFAULT, speed, on_error,
3229 filter_node_name, NULL, NULL, false, &local_err);
3230 } else {
3231 BlockDriverState *overlay_bs = bdrv_find_overlay(bs, top_bs);
3232 if (bdrv_op_is_blocked(overlay_bs, BLOCK_OP_TYPE_COMMIT_TARGET, errp)) {
3233 goto out;
3235 commit_start(has_job_id ? job_id : NULL, bs, base_bs, top_bs, speed,
3236 on_error, has_backing_file ? backing_file : NULL,
3237 filter_node_name, &local_err);
3239 if (local_err != NULL) {
3240 error_propagate(errp, local_err);
3241 goto out;
3244 out:
3245 aio_context_release(aio_context);
3248 static BlockJob *do_drive_backup(DriveBackup *backup, BlockJobTxn *txn,
3249 Error **errp)
3251 BlockDriverState *bs;
3252 BlockDriverState *target_bs;
3253 BlockDriverState *source = NULL;
3254 BlockJob *job = NULL;
3255 BdrvDirtyBitmap *bmap = NULL;
3256 AioContext *aio_context;
3257 QDict *options = NULL;
3258 Error *local_err = NULL;
3259 int flags;
3260 int64_t size;
3261 bool set_backing_hd = false;
3263 if (!backup->has_speed) {
3264 backup->speed = 0;
3266 if (!backup->has_on_source_error) {
3267 backup->on_source_error = BLOCKDEV_ON_ERROR_REPORT;
3269 if (!backup->has_on_target_error) {
3270 backup->on_target_error = BLOCKDEV_ON_ERROR_REPORT;
3272 if (!backup->has_mode) {
3273 backup->mode = NEW_IMAGE_MODE_ABSOLUTE_PATHS;
3275 if (!backup->has_job_id) {
3276 backup->job_id = NULL;
3278 if (!backup->has_compress) {
3279 backup->compress = false;
3282 bs = qmp_get_root_bs(backup->device, errp);
3283 if (!bs) {
3284 return NULL;
3287 aio_context = bdrv_get_aio_context(bs);
3288 aio_context_acquire(aio_context);
3290 if (!backup->has_format) {
3291 backup->format = backup->mode == NEW_IMAGE_MODE_EXISTING ?
3292 NULL : (char*) bs->drv->format_name;
3295 /* Early check to avoid creating target */
3296 if (bdrv_op_is_blocked(bs, BLOCK_OP_TYPE_BACKUP_SOURCE, errp)) {
3297 goto out;
3300 flags = bs->open_flags | BDRV_O_RDWR;
3302 /* See if we have a backing HD we can use to create our new image
3303 * on top of. */
3304 if (backup->sync == MIRROR_SYNC_MODE_TOP) {
3305 source = backing_bs(bs);
3306 if (!source) {
3307 backup->sync = MIRROR_SYNC_MODE_FULL;
3310 if (backup->sync == MIRROR_SYNC_MODE_NONE) {
3311 source = bs;
3312 flags |= BDRV_O_NO_BACKING;
3313 set_backing_hd = true;
3316 size = bdrv_getlength(bs);
3317 if (size < 0) {
3318 error_setg_errno(errp, -size, "bdrv_getlength failed");
3319 goto out;
3322 if (backup->mode != NEW_IMAGE_MODE_EXISTING) {
3323 assert(backup->format);
3324 if (source) {
3325 bdrv_img_create(backup->target, backup->format, source->filename,
3326 source->drv->format_name, NULL,
3327 size, flags, false, &local_err);
3328 } else {
3329 bdrv_img_create(backup->target, backup->format, NULL, NULL, NULL,
3330 size, flags, false, &local_err);
3334 if (local_err) {
3335 error_propagate(errp, local_err);
3336 goto out;
3339 if (backup->format) {
3340 if (!options) {
3341 options = qdict_new();
3343 qdict_put_str(options, "driver", backup->format);
3346 target_bs = bdrv_open(backup->target, NULL, options, flags, errp);
3347 if (!target_bs) {
3348 goto out;
3351 bdrv_set_aio_context(target_bs, aio_context);
3353 if (set_backing_hd) {
3354 bdrv_set_backing_hd(target_bs, source, &local_err);
3355 if (local_err) {
3356 bdrv_unref(target_bs);
3357 goto out;
3361 if (backup->has_bitmap) {
3362 bmap = bdrv_find_dirty_bitmap(bs, backup->bitmap);
3363 if (!bmap) {
3364 error_setg(errp, "Bitmap '%s' could not be found", backup->bitmap);
3365 bdrv_unref(target_bs);
3366 goto out;
3370 job = backup_job_create(backup->job_id, bs, target_bs, backup->speed,
3371 backup->sync, bmap, backup->compress,
3372 backup->on_source_error, backup->on_target_error,
3373 BLOCK_JOB_DEFAULT, NULL, NULL, txn, &local_err);
3374 bdrv_unref(target_bs);
3375 if (local_err != NULL) {
3376 error_propagate(errp, local_err);
3377 goto out;
3380 out:
3381 aio_context_release(aio_context);
3382 return job;
3385 void qmp_drive_backup(DriveBackup *arg, Error **errp)
3388 BlockJob *job;
3389 job = do_drive_backup(arg, NULL, errp);
3390 if (job) {
3391 block_job_start(job);
3395 BlockDeviceInfoList *qmp_query_named_block_nodes(Error **errp)
3397 return bdrv_named_nodes_list(errp);
3400 BlockJob *do_blockdev_backup(BlockdevBackup *backup, BlockJobTxn *txn,
3401 Error **errp)
3403 BlockDriverState *bs;
3404 BlockDriverState *target_bs;
3405 Error *local_err = NULL;
3406 AioContext *aio_context;
3407 BlockJob *job = NULL;
3409 if (!backup->has_speed) {
3410 backup->speed = 0;
3412 if (!backup->has_on_source_error) {
3413 backup->on_source_error = BLOCKDEV_ON_ERROR_REPORT;
3415 if (!backup->has_on_target_error) {
3416 backup->on_target_error = BLOCKDEV_ON_ERROR_REPORT;
3418 if (!backup->has_job_id) {
3419 backup->job_id = NULL;
3421 if (!backup->has_compress) {
3422 backup->compress = false;
3425 bs = qmp_get_root_bs(backup->device, errp);
3426 if (!bs) {
3427 return NULL;
3430 aio_context = bdrv_get_aio_context(bs);
3431 aio_context_acquire(aio_context);
3433 target_bs = bdrv_lookup_bs(backup->target, backup->target, errp);
3434 if (!target_bs) {
3435 goto out;
3438 if (bdrv_get_aio_context(target_bs) != aio_context) {
3439 if (!bdrv_has_blk(target_bs)) {
3440 /* The target BDS is not attached, we can safely move it to another
3441 * AioContext. */
3442 bdrv_set_aio_context(target_bs, aio_context);
3443 } else {
3444 error_setg(errp, "Target is attached to a different thread from "
3445 "source.");
3446 goto out;
3449 job = backup_job_create(backup->job_id, bs, target_bs, backup->speed,
3450 backup->sync, NULL, backup->compress,
3451 backup->on_source_error, backup->on_target_error,
3452 BLOCK_JOB_DEFAULT, NULL, NULL, txn, &local_err);
3453 if (local_err != NULL) {
3454 error_propagate(errp, local_err);
3456 out:
3457 aio_context_release(aio_context);
3458 return job;
3461 void qmp_blockdev_backup(BlockdevBackup *arg, Error **errp)
3463 BlockJob *job;
3464 job = do_blockdev_backup(arg, NULL, errp);
3465 if (job) {
3466 block_job_start(job);
3470 /* Parameter check and block job starting for drive mirroring.
3471 * Caller should hold @device and @target's aio context (must be the same).
3473 static void blockdev_mirror_common(const char *job_id, BlockDriverState *bs,
3474 BlockDriverState *target,
3475 bool has_replaces, const char *replaces,
3476 enum MirrorSyncMode sync,
3477 BlockMirrorBackingMode backing_mode,
3478 bool has_speed, int64_t speed,
3479 bool has_granularity, uint32_t granularity,
3480 bool has_buf_size, int64_t buf_size,
3481 bool has_on_source_error,
3482 BlockdevOnError on_source_error,
3483 bool has_on_target_error,
3484 BlockdevOnError on_target_error,
3485 bool has_unmap, bool unmap,
3486 bool has_filter_node_name,
3487 const char *filter_node_name,
3488 Error **errp)
3491 if (!has_speed) {
3492 speed = 0;
3494 if (!has_on_source_error) {
3495 on_source_error = BLOCKDEV_ON_ERROR_REPORT;
3497 if (!has_on_target_error) {
3498 on_target_error = BLOCKDEV_ON_ERROR_REPORT;
3500 if (!has_granularity) {
3501 granularity = 0;
3503 if (!has_buf_size) {
3504 buf_size = 0;
3506 if (!has_unmap) {
3507 unmap = true;
3509 if (!has_filter_node_name) {
3510 filter_node_name = NULL;
3513 if (granularity != 0 && (granularity < 512 || granularity > 1048576 * 64)) {
3514 error_setg(errp, QERR_INVALID_PARAMETER_VALUE, "granularity",
3515 "a value in range [512B, 64MB]");
3516 return;
3518 if (granularity & (granularity - 1)) {
3519 error_setg(errp, QERR_INVALID_PARAMETER_VALUE, "granularity",
3520 "power of 2");
3521 return;
3524 if (bdrv_op_is_blocked(bs, BLOCK_OP_TYPE_MIRROR_SOURCE, errp)) {
3525 return;
3527 if (bdrv_op_is_blocked(target, BLOCK_OP_TYPE_MIRROR_TARGET, errp)) {
3528 return;
3531 if (!bs->backing && sync == MIRROR_SYNC_MODE_TOP) {
3532 sync = MIRROR_SYNC_MODE_FULL;
3535 /* pass the node name to replace to mirror start since it's loose coupling
3536 * and will allow to check whether the node still exist at mirror completion
3538 mirror_start(job_id, bs, target,
3539 has_replaces ? replaces : NULL,
3540 speed, granularity, buf_size, sync, backing_mode,
3541 on_source_error, on_target_error, unmap, filter_node_name,
3542 errp);
3545 void qmp_drive_mirror(DriveMirror *arg, Error **errp)
3547 BlockDriverState *bs;
3548 BlockDriverState *source, *target_bs;
3549 AioContext *aio_context;
3550 BlockMirrorBackingMode backing_mode;
3551 Error *local_err = NULL;
3552 QDict *options = NULL;
3553 int flags;
3554 int64_t size;
3555 const char *format = arg->format;
3557 bs = qmp_get_root_bs(arg->device, errp);
3558 if (!bs) {
3559 return;
3562 aio_context = bdrv_get_aio_context(bs);
3563 aio_context_acquire(aio_context);
3565 if (!arg->has_mode) {
3566 arg->mode = NEW_IMAGE_MODE_ABSOLUTE_PATHS;
3569 if (!arg->has_format) {
3570 format = (arg->mode == NEW_IMAGE_MODE_EXISTING
3571 ? NULL : bs->drv->format_name);
3574 flags = bs->open_flags | BDRV_O_RDWR;
3575 source = backing_bs(bs);
3576 if (!source && arg->sync == MIRROR_SYNC_MODE_TOP) {
3577 arg->sync = MIRROR_SYNC_MODE_FULL;
3579 if (arg->sync == MIRROR_SYNC_MODE_NONE) {
3580 source = bs;
3583 size = bdrv_getlength(bs);
3584 if (size < 0) {
3585 error_setg_errno(errp, -size, "bdrv_getlength failed");
3586 goto out;
3589 if (arg->has_replaces) {
3590 BlockDriverState *to_replace_bs;
3591 AioContext *replace_aio_context;
3592 int64_t replace_size;
3594 if (!arg->has_node_name) {
3595 error_setg(errp, "a node-name must be provided when replacing a"
3596 " named node of the graph");
3597 goto out;
3600 to_replace_bs = check_to_replace_node(bs, arg->replaces, &local_err);
3602 if (!to_replace_bs) {
3603 error_propagate(errp, local_err);
3604 goto out;
3607 replace_aio_context = bdrv_get_aio_context(to_replace_bs);
3608 aio_context_acquire(replace_aio_context);
3609 replace_size = bdrv_getlength(to_replace_bs);
3610 aio_context_release(replace_aio_context);
3612 if (size != replace_size) {
3613 error_setg(errp, "cannot replace image with a mirror image of "
3614 "different size");
3615 goto out;
3619 if (arg->mode == NEW_IMAGE_MODE_ABSOLUTE_PATHS) {
3620 backing_mode = MIRROR_SOURCE_BACKING_CHAIN;
3621 } else {
3622 backing_mode = MIRROR_OPEN_BACKING_CHAIN;
3625 /* Don't open backing image in create() */
3626 flags |= BDRV_O_NO_BACKING;
3628 if ((arg->sync == MIRROR_SYNC_MODE_FULL || !source)
3629 && arg->mode != NEW_IMAGE_MODE_EXISTING)
3631 /* create new image w/o backing file */
3632 assert(format);
3633 bdrv_img_create(arg->target, format,
3634 NULL, NULL, NULL, size, flags, false, &local_err);
3635 } else {
3636 switch (arg->mode) {
3637 case NEW_IMAGE_MODE_EXISTING:
3638 break;
3639 case NEW_IMAGE_MODE_ABSOLUTE_PATHS:
3640 /* create new image with backing file */
3641 bdrv_img_create(arg->target, format,
3642 source->filename,
3643 source->drv->format_name,
3644 NULL, size, flags, false, &local_err);
3645 break;
3646 default:
3647 abort();
3651 if (local_err) {
3652 error_propagate(errp, local_err);
3653 goto out;
3656 options = qdict_new();
3657 if (arg->has_node_name) {
3658 qdict_put_str(options, "node-name", arg->node_name);
3660 if (format) {
3661 qdict_put_str(options, "driver", format);
3664 /* Mirroring takes care of copy-on-write using the source's backing
3665 * file.
3667 target_bs = bdrv_open(arg->target, NULL, options, flags, errp);
3668 if (!target_bs) {
3669 goto out;
3672 bdrv_set_aio_context(target_bs, aio_context);
3674 blockdev_mirror_common(arg->has_job_id ? arg->job_id : NULL, bs, target_bs,
3675 arg->has_replaces, arg->replaces, arg->sync,
3676 backing_mode, arg->has_speed, arg->speed,
3677 arg->has_granularity, arg->granularity,
3678 arg->has_buf_size, arg->buf_size,
3679 arg->has_on_source_error, arg->on_source_error,
3680 arg->has_on_target_error, arg->on_target_error,
3681 arg->has_unmap, arg->unmap,
3682 false, NULL,
3683 &local_err);
3684 bdrv_unref(target_bs);
3685 error_propagate(errp, local_err);
3686 out:
3687 aio_context_release(aio_context);
3690 void qmp_blockdev_mirror(bool has_job_id, const char *job_id,
3691 const char *device, const char *target,
3692 bool has_replaces, const char *replaces,
3693 MirrorSyncMode sync,
3694 bool has_speed, int64_t speed,
3695 bool has_granularity, uint32_t granularity,
3696 bool has_buf_size, int64_t buf_size,
3697 bool has_on_source_error,
3698 BlockdevOnError on_source_error,
3699 bool has_on_target_error,
3700 BlockdevOnError on_target_error,
3701 bool has_filter_node_name,
3702 const char *filter_node_name,
3703 Error **errp)
3705 BlockDriverState *bs;
3706 BlockDriverState *target_bs;
3707 AioContext *aio_context;
3708 BlockMirrorBackingMode backing_mode = MIRROR_LEAVE_BACKING_CHAIN;
3709 Error *local_err = NULL;
3711 bs = qmp_get_root_bs(device, errp);
3712 if (!bs) {
3713 return;
3716 target_bs = bdrv_lookup_bs(target, target, errp);
3717 if (!target_bs) {
3718 return;
3721 aio_context = bdrv_get_aio_context(bs);
3722 aio_context_acquire(aio_context);
3724 bdrv_set_aio_context(target_bs, aio_context);
3726 blockdev_mirror_common(has_job_id ? job_id : NULL, bs, target_bs,
3727 has_replaces, replaces, sync, backing_mode,
3728 has_speed, speed,
3729 has_granularity, granularity,
3730 has_buf_size, buf_size,
3731 has_on_source_error, on_source_error,
3732 has_on_target_error, on_target_error,
3733 true, true,
3734 has_filter_node_name, filter_node_name,
3735 &local_err);
3736 error_propagate(errp, local_err);
3738 aio_context_release(aio_context);
3741 /* Get a block job using its ID and acquire its AioContext */
3742 static BlockJob *find_block_job(const char *id, AioContext **aio_context,
3743 Error **errp)
3745 BlockJob *job;
3747 assert(id != NULL);
3749 *aio_context = NULL;
3751 job = block_job_get(id);
3753 if (!job) {
3754 error_set(errp, ERROR_CLASS_DEVICE_NOT_ACTIVE,
3755 "Block job '%s' not found", id);
3756 return NULL;
3759 *aio_context = blk_get_aio_context(job->blk);
3760 aio_context_acquire(*aio_context);
3762 return job;
3765 void qmp_block_job_set_speed(const char *device, int64_t speed, Error **errp)
3767 AioContext *aio_context;
3768 BlockJob *job = find_block_job(device, &aio_context, errp);
3770 if (!job) {
3771 return;
3774 block_job_set_speed(job, speed, errp);
3775 aio_context_release(aio_context);
3778 void qmp_block_job_cancel(const char *device,
3779 bool has_force, bool force, Error **errp)
3781 AioContext *aio_context;
3782 BlockJob *job = find_block_job(device, &aio_context, errp);
3784 if (!job) {
3785 return;
3788 if (!has_force) {
3789 force = false;
3792 if (block_job_user_paused(job) && !force) {
3793 error_setg(errp, "The block job for device '%s' is currently paused",
3794 device);
3795 goto out;
3798 trace_qmp_block_job_cancel(job);
3799 block_job_cancel(job);
3800 out:
3801 aio_context_release(aio_context);
3804 void qmp_block_job_pause(const char *device, Error **errp)
3806 AioContext *aio_context;
3807 BlockJob *job = find_block_job(device, &aio_context, errp);
3809 if (!job || block_job_user_paused(job)) {
3810 return;
3813 trace_qmp_block_job_pause(job);
3814 block_job_user_pause(job);
3815 aio_context_release(aio_context);
3818 void qmp_block_job_resume(const char *device, Error **errp)
3820 AioContext *aio_context;
3821 BlockJob *job = find_block_job(device, &aio_context, errp);
3823 if (!job || !block_job_user_paused(job)) {
3824 return;
3827 trace_qmp_block_job_resume(job);
3828 block_job_user_resume(job);
3829 aio_context_release(aio_context);
3832 void qmp_block_job_complete(const char *device, Error **errp)
3834 AioContext *aio_context;
3835 BlockJob *job = find_block_job(device, &aio_context, errp);
3837 if (!job) {
3838 return;
3841 trace_qmp_block_job_complete(job);
3842 block_job_complete(job, errp);
3843 aio_context_release(aio_context);
3846 void qmp_change_backing_file(const char *device,
3847 const char *image_node_name,
3848 const char *backing_file,
3849 Error **errp)
3851 BlockDriverState *bs = NULL;
3852 AioContext *aio_context;
3853 BlockDriverState *image_bs = NULL;
3854 Error *local_err = NULL;
3855 bool ro;
3856 int open_flags;
3857 int ret;
3859 bs = qmp_get_root_bs(device, errp);
3860 if (!bs) {
3861 return;
3864 aio_context = bdrv_get_aio_context(bs);
3865 aio_context_acquire(aio_context);
3867 image_bs = bdrv_lookup_bs(NULL, image_node_name, &local_err);
3868 if (local_err) {
3869 error_propagate(errp, local_err);
3870 goto out;
3873 if (!image_bs) {
3874 error_setg(errp, "image file not found");
3875 goto out;
3878 if (bdrv_find_base(image_bs) == image_bs) {
3879 error_setg(errp, "not allowing backing file change on an image "
3880 "without a backing file");
3881 goto out;
3884 /* even though we are not necessarily operating on bs, we need it to
3885 * determine if block ops are currently prohibited on the chain */
3886 if (bdrv_op_is_blocked(bs, BLOCK_OP_TYPE_CHANGE, errp)) {
3887 goto out;
3890 /* final sanity check */
3891 if (!bdrv_chain_contains(bs, image_bs)) {
3892 error_setg(errp, "'%s' and image file are not in the same chain",
3893 device);
3894 goto out;
3897 /* if not r/w, reopen to make r/w */
3898 open_flags = image_bs->open_flags;
3899 ro = bdrv_is_read_only(image_bs);
3901 if (ro) {
3902 bdrv_reopen(image_bs, open_flags | BDRV_O_RDWR, &local_err);
3903 if (local_err) {
3904 error_propagate(errp, local_err);
3905 goto out;
3909 ret = bdrv_change_backing_file(image_bs, backing_file,
3910 image_bs->drv ? image_bs->drv->format_name : "");
3912 if (ret < 0) {
3913 error_setg_errno(errp, -ret, "Could not change backing file to '%s'",
3914 backing_file);
3915 /* don't exit here, so we can try to restore open flags if
3916 * appropriate */
3919 if (ro) {
3920 bdrv_reopen(image_bs, open_flags, &local_err);
3921 error_propagate(errp, local_err);
3924 out:
3925 aio_context_release(aio_context);
3928 void hmp_drive_add_node(Monitor *mon, const char *optstr)
3930 QemuOpts *opts;
3931 QDict *qdict;
3932 Error *local_err = NULL;
3934 opts = qemu_opts_parse_noisily(&qemu_drive_opts, optstr, false);
3935 if (!opts) {
3936 return;
3939 qdict = qemu_opts_to_qdict(opts, NULL);
3941 if (!qdict_get_try_str(qdict, "node-name")) {
3942 QDECREF(qdict);
3943 error_report("'node-name' needs to be specified");
3944 goto out;
3947 BlockDriverState *bs = bds_tree_init(qdict, &local_err);
3948 if (!bs) {
3949 error_report_err(local_err);
3950 goto out;
3953 QTAILQ_INSERT_TAIL(&monitor_bdrv_states, bs, monitor_list);
3955 out:
3956 qemu_opts_del(opts);
3959 void qmp_blockdev_add(BlockdevOptions *options, Error **errp)
3961 BlockDriverState *bs;
3962 QObject *obj;
3963 Visitor *v = qobject_output_visitor_new(&obj);
3964 QDict *qdict;
3965 const QDictEntry *ent;
3966 Error *local_err = NULL;
3968 visit_type_BlockdevOptions(v, NULL, &options, &local_err);
3969 if (local_err) {
3970 error_propagate(errp, local_err);
3971 goto fail;
3974 visit_complete(v, &obj);
3975 qdict = qobject_to_qdict(obj);
3977 qdict_flatten(qdict);
3980 * Rewrite "backing": null to "backing": ""
3981 * TODO Rewrite "" to null instead, and perhaps not even here
3983 for (ent = qdict_first(qdict); ent; ent = qdict_next(qdict, ent)) {
3984 char *dot = strrchr(ent->key, '.');
3986 if (!strcmp(dot ? dot + 1 : ent->key, "backing")
3987 && qobject_type(ent->value) == QTYPE_QNULL) {
3988 qdict_put(qdict, ent->key, qstring_new());
3992 if (!qdict_get_try_str(qdict, "node-name")) {
3993 error_setg(errp, "'node-name' must be specified for the root node");
3994 goto fail;
3997 bs = bds_tree_init(qdict, errp);
3998 if (!bs) {
3999 goto fail;
4002 QTAILQ_INSERT_TAIL(&monitor_bdrv_states, bs, monitor_list);
4004 fail:
4005 visit_free(v);
4008 void qmp_blockdev_del(const char *node_name, Error **errp)
4010 AioContext *aio_context;
4011 BlockDriverState *bs;
4013 bs = bdrv_find_node(node_name);
4014 if (!bs) {
4015 error_setg(errp, "Cannot find node %s", node_name);
4016 return;
4018 if (bdrv_has_blk(bs)) {
4019 error_setg(errp, "Node %s is in use", node_name);
4020 return;
4022 aio_context = bdrv_get_aio_context(bs);
4023 aio_context_acquire(aio_context);
4025 if (bdrv_op_is_blocked(bs, BLOCK_OP_TYPE_DRIVE_DEL, errp)) {
4026 goto out;
4029 if (!bs->monitor_list.tqe_prev) {
4030 error_setg(errp, "Node %s is not owned by the monitor",
4031 bs->node_name);
4032 goto out;
4035 if (bs->refcnt > 1) {
4036 error_setg(errp, "Block device %s is in use",
4037 bdrv_get_device_or_node_name(bs));
4038 goto out;
4041 QTAILQ_REMOVE(&monitor_bdrv_states, bs, monitor_list);
4042 bdrv_unref(bs);
4044 out:
4045 aio_context_release(aio_context);
4048 static BdrvChild *bdrv_find_child(BlockDriverState *parent_bs,
4049 const char *child_name)
4051 BdrvChild *child;
4053 QLIST_FOREACH(child, &parent_bs->children, next) {
4054 if (strcmp(child->name, child_name) == 0) {
4055 return child;
4059 return NULL;
4062 void qmp_x_blockdev_change(const char *parent, bool has_child,
4063 const char *child, bool has_node,
4064 const char *node, Error **errp)
4066 BlockDriverState *parent_bs, *new_bs = NULL;
4067 BdrvChild *p_child;
4069 parent_bs = bdrv_lookup_bs(parent, parent, errp);
4070 if (!parent_bs) {
4071 return;
4074 if (has_child == has_node) {
4075 if (has_child) {
4076 error_setg(errp, "The parameters child and node are in conflict");
4077 } else {
4078 error_setg(errp, "Either child or node must be specified");
4080 return;
4083 if (has_child) {
4084 p_child = bdrv_find_child(parent_bs, child);
4085 if (!p_child) {
4086 error_setg(errp, "Node '%s' does not have child '%s'",
4087 parent, child);
4088 return;
4090 bdrv_del_child(parent_bs, p_child, errp);
4093 if (has_node) {
4094 new_bs = bdrv_find_node(node);
4095 if (!new_bs) {
4096 error_setg(errp, "Node '%s' not found", node);
4097 return;
4099 bdrv_add_child(parent_bs, new_bs, errp);
4103 BlockJobInfoList *qmp_query_block_jobs(Error **errp)
4105 BlockJobInfoList *head = NULL, **p_next = &head;
4106 BlockJob *job;
4108 for (job = block_job_next(NULL); job; job = block_job_next(job)) {
4109 BlockJobInfoList *elem;
4110 AioContext *aio_context;
4112 if (block_job_is_internal(job)) {
4113 continue;
4115 elem = g_new0(BlockJobInfoList, 1);
4116 aio_context = blk_get_aio_context(job->blk);
4117 aio_context_acquire(aio_context);
4118 elem->value = block_job_query(job, errp);
4119 aio_context_release(aio_context);
4120 if (!elem->value) {
4121 g_free(elem);
4122 qapi_free_BlockJobInfoList(head);
4123 return NULL;
4125 *p_next = elem;
4126 p_next = &elem->next;
4129 return head;
4132 QemuOptsList qemu_common_drive_opts = {
4133 .name = "drive",
4134 .head = QTAILQ_HEAD_INITIALIZER(qemu_common_drive_opts.head),
4135 .desc = {
4137 .name = "snapshot",
4138 .type = QEMU_OPT_BOOL,
4139 .help = "enable/disable snapshot mode",
4141 .name = "aio",
4142 .type = QEMU_OPT_STRING,
4143 .help = "host AIO implementation (threads, native)",
4145 .name = BDRV_OPT_CACHE_WB,
4146 .type = QEMU_OPT_BOOL,
4147 .help = "Enable writeback mode",
4149 .name = "format",
4150 .type = QEMU_OPT_STRING,
4151 .help = "disk format (raw, qcow2, ...)",
4153 .name = "rerror",
4154 .type = QEMU_OPT_STRING,
4155 .help = "read error action",
4157 .name = "werror",
4158 .type = QEMU_OPT_STRING,
4159 .help = "write error action",
4161 .name = BDRV_OPT_READ_ONLY,
4162 .type = QEMU_OPT_BOOL,
4163 .help = "open drive file as read-only",
4166 THROTTLE_OPTS,
4169 .name = "throttling.group",
4170 .type = QEMU_OPT_STRING,
4171 .help = "name of the block throttling group",
4173 .name = "copy-on-read",
4174 .type = QEMU_OPT_BOOL,
4175 .help = "copy read data from backing file into image file",
4177 .name = "detect-zeroes",
4178 .type = QEMU_OPT_STRING,
4179 .help = "try to optimize zero writes (off, on, unmap)",
4181 .name = "stats-account-invalid",
4182 .type = QEMU_OPT_BOOL,
4183 .help = "whether to account for invalid I/O operations "
4184 "in the statistics",
4186 .name = "stats-account-failed",
4187 .type = QEMU_OPT_BOOL,
4188 .help = "whether to account for failed I/O operations "
4189 "in the statistics",
4191 { /* end of list */ }
4195 QemuOptsList qemu_drive_opts = {
4196 .name = "drive",
4197 .head = QTAILQ_HEAD_INITIALIZER(qemu_drive_opts.head),
4198 .desc = {
4200 * no elements => accept any params
4201 * validation will happen later
4203 { /* end of list */ }