block: Parse 'detect-zeroes' in bdrv_open_common()
[qemu/kevin.git] / blockdev.c
blob511260ce9357c279171445f9db85e561a87ae3df
1 /*
2 * QEMU host block devices
4 * Copyright (c) 2003-2008 Fabrice Bellard
6 * This work is licensed under the terms of the GNU GPL, version 2 or
7 * later. See the COPYING file in the top-level directory.
9 * This file incorporates work covered by the following copyright and
10 * permission notice:
12 * Copyright (c) 2003-2008 Fabrice Bellard
14 * Permission is hereby granted, free of charge, to any person obtaining a copy
15 * of this software and associated documentation files (the "Software"), to deal
16 * in the Software without restriction, including without limitation the rights
17 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
18 * copies of the Software, and to permit persons to whom the Software is
19 * furnished to do so, subject to the following conditions:
21 * The above copyright notice and this permission notice shall be included in
22 * all copies or substantial portions of the Software.
24 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
25 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
26 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
27 * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
28 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
29 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
30 * THE SOFTWARE.
33 #include "qemu/osdep.h"
34 #include "sysemu/block-backend.h"
35 #include "sysemu/blockdev.h"
36 #include "hw/block/block.h"
37 #include "block/blockjob.h"
38 #include "block/throttle-groups.h"
39 #include "monitor/monitor.h"
40 #include "qemu/error-report.h"
41 #include "qemu/option.h"
42 #include "qemu/config-file.h"
43 #include "qapi/qmp/types.h"
44 #include "qapi-visit.h"
45 #include "qapi/qmp/qerror.h"
46 #include "qapi/qmp-output-visitor.h"
47 #include "qapi/util.h"
48 #include "sysemu/sysemu.h"
49 #include "block/block_int.h"
50 #include "qmp-commands.h"
51 #include "trace.h"
52 #include "sysemu/arch_init.h"
53 #include "qemu/cutils.h"
54 #include "qemu/help_option.h"
56 static QTAILQ_HEAD(, BlockDriverState) monitor_bdrv_states =
57 QTAILQ_HEAD_INITIALIZER(monitor_bdrv_states);
59 static int do_open_tray(const char *blk_name, const char *qdev_id,
60 bool force, Error **errp);
62 static const char *const if_name[IF_COUNT] = {
63 [IF_NONE] = "none",
64 [IF_IDE] = "ide",
65 [IF_SCSI] = "scsi",
66 [IF_FLOPPY] = "floppy",
67 [IF_PFLASH] = "pflash",
68 [IF_MTD] = "mtd",
69 [IF_SD] = "sd",
70 [IF_VIRTIO] = "virtio",
71 [IF_XEN] = "xen",
74 static int if_max_devs[IF_COUNT] = {
76 * Do not change these numbers! They govern how drive option
77 * index maps to unit and bus. That mapping is ABI.
79 * All controllers used to implement if=T drives need to support
80 * if_max_devs[T] units, for any T with if_max_devs[T] != 0.
81 * Otherwise, some index values map to "impossible" bus, unit
82 * values.
84 * For instance, if you change [IF_SCSI] to 255, -drive
85 * if=scsi,index=12 no longer means bus=1,unit=5, but
86 * bus=0,unit=12. With an lsi53c895a controller (7 units max),
87 * the drive can't be set up. Regression.
89 [IF_IDE] = 2,
90 [IF_SCSI] = 7,
93 /**
94 * Boards may call this to offer board-by-board overrides
95 * of the default, global values.
97 void override_max_devs(BlockInterfaceType type, int max_devs)
99 BlockBackend *blk;
100 DriveInfo *dinfo;
102 if (max_devs <= 0) {
103 return;
106 for (blk = blk_next(NULL); blk; blk = blk_next(blk)) {
107 dinfo = blk_legacy_dinfo(blk);
108 if (dinfo->type == type) {
109 fprintf(stderr, "Cannot override units-per-bus property of"
110 " the %s interface, because a drive of that type has"
111 " already been added.\n", if_name[type]);
112 g_assert_not_reached();
116 if_max_devs[type] = max_devs;
120 * We automatically delete the drive when a device using it gets
121 * unplugged. Questionable feature, but we can't just drop it.
122 * Device models call blockdev_mark_auto_del() to schedule the
123 * automatic deletion, and generic qdev code calls blockdev_auto_del()
124 * when deletion is actually safe.
126 void blockdev_mark_auto_del(BlockBackend *blk)
128 DriveInfo *dinfo = blk_legacy_dinfo(blk);
129 BlockDriverState *bs = blk_bs(blk);
130 AioContext *aio_context;
132 if (!dinfo) {
133 return;
136 if (bs) {
137 aio_context = bdrv_get_aio_context(bs);
138 aio_context_acquire(aio_context);
140 if (bs->job) {
141 block_job_cancel(bs->job);
144 aio_context_release(aio_context);
147 dinfo->auto_del = 1;
150 void blockdev_auto_del(BlockBackend *blk)
152 DriveInfo *dinfo = blk_legacy_dinfo(blk);
154 if (dinfo && dinfo->auto_del) {
155 monitor_remove_blk(blk);
156 blk_unref(blk);
161 * Returns the current mapping of how many units per bus
162 * a particular interface can support.
164 * A positive integer indicates n units per bus.
165 * 0 implies the mapping has not been established.
166 * -1 indicates an invalid BlockInterfaceType was given.
168 int drive_get_max_devs(BlockInterfaceType type)
170 if (type >= IF_IDE && type < IF_COUNT) {
171 return if_max_devs[type];
174 return -1;
177 static int drive_index_to_bus_id(BlockInterfaceType type, int index)
179 int max_devs = if_max_devs[type];
180 return max_devs ? index / max_devs : 0;
183 static int drive_index_to_unit_id(BlockInterfaceType type, int index)
185 int max_devs = if_max_devs[type];
186 return max_devs ? index % max_devs : index;
189 QemuOpts *drive_def(const char *optstr)
191 return qemu_opts_parse_noisily(qemu_find_opts("drive"), optstr, false);
194 QemuOpts *drive_add(BlockInterfaceType type, int index, const char *file,
195 const char *optstr)
197 QemuOpts *opts;
199 opts = drive_def(optstr);
200 if (!opts) {
201 return NULL;
203 if (type != IF_DEFAULT) {
204 qemu_opt_set(opts, "if", if_name[type], &error_abort);
206 if (index >= 0) {
207 qemu_opt_set_number(opts, "index", index, &error_abort);
209 if (file)
210 qemu_opt_set(opts, "file", file, &error_abort);
211 return opts;
214 DriveInfo *drive_get(BlockInterfaceType type, int bus, int unit)
216 BlockBackend *blk;
217 DriveInfo *dinfo;
219 for (blk = blk_next(NULL); blk; blk = blk_next(blk)) {
220 dinfo = blk_legacy_dinfo(blk);
221 if (dinfo && dinfo->type == type
222 && dinfo->bus == bus && dinfo->unit == unit) {
223 return dinfo;
227 return NULL;
230 bool drive_check_orphaned(void)
232 BlockBackend *blk;
233 DriveInfo *dinfo;
234 bool rs = false;
236 for (blk = blk_next(NULL); blk; blk = blk_next(blk)) {
237 dinfo = blk_legacy_dinfo(blk);
238 /* If dinfo->bdrv->dev is NULL, it has no device attached. */
239 /* Unless this is a default drive, this may be an oversight. */
240 if (!blk_get_attached_dev(blk) && !dinfo->is_default &&
241 dinfo->type != IF_NONE) {
242 fprintf(stderr, "Warning: Orphaned drive without device: "
243 "id=%s,file=%s,if=%s,bus=%d,unit=%d\n",
244 blk_name(blk), blk_bs(blk) ? blk_bs(blk)->filename : "",
245 if_name[dinfo->type], dinfo->bus, dinfo->unit);
246 rs = true;
250 return rs;
253 DriveInfo *drive_get_by_index(BlockInterfaceType type, int index)
255 return drive_get(type,
256 drive_index_to_bus_id(type, index),
257 drive_index_to_unit_id(type, index));
260 int drive_get_max_bus(BlockInterfaceType type)
262 int max_bus;
263 BlockBackend *blk;
264 DriveInfo *dinfo;
266 max_bus = -1;
267 for (blk = blk_next(NULL); blk; blk = blk_next(blk)) {
268 dinfo = blk_legacy_dinfo(blk);
269 if (dinfo && dinfo->type == type && dinfo->bus > max_bus) {
270 max_bus = dinfo->bus;
273 return max_bus;
276 /* Get a block device. This should only be used for single-drive devices
277 (e.g. SD/Floppy/MTD). Multi-disk devices (scsi/ide) should use the
278 appropriate bus. */
279 DriveInfo *drive_get_next(BlockInterfaceType type)
281 static int next_block_unit[IF_COUNT];
283 return drive_get(type, 0, next_block_unit[type]++);
286 static void bdrv_format_print(void *opaque, const char *name)
288 error_printf(" %s", name);
291 typedef struct {
292 QEMUBH *bh;
293 BlockDriverState *bs;
294 } BDRVPutRefBH;
296 static int parse_block_error_action(const char *buf, bool is_read, Error **errp)
298 if (!strcmp(buf, "ignore")) {
299 return BLOCKDEV_ON_ERROR_IGNORE;
300 } else if (!is_read && !strcmp(buf, "enospc")) {
301 return BLOCKDEV_ON_ERROR_ENOSPC;
302 } else if (!strcmp(buf, "stop")) {
303 return BLOCKDEV_ON_ERROR_STOP;
304 } else if (!strcmp(buf, "report")) {
305 return BLOCKDEV_ON_ERROR_REPORT;
306 } else {
307 error_setg(errp, "'%s' invalid %s error action",
308 buf, is_read ? "read" : "write");
309 return -1;
313 static bool parse_stats_intervals(BlockAcctStats *stats, QList *intervals,
314 Error **errp)
316 const QListEntry *entry;
317 for (entry = qlist_first(intervals); entry; entry = qlist_next(entry)) {
318 switch (qobject_type(entry->value)) {
320 case QTYPE_QSTRING: {
321 unsigned long long length;
322 const char *str = qstring_get_str(qobject_to_qstring(entry->value));
323 if (parse_uint_full(str, &length, 10) == 0 &&
324 length > 0 && length <= UINT_MAX) {
325 block_acct_add_interval(stats, (unsigned) length);
326 } else {
327 error_setg(errp, "Invalid interval length: %s", str);
328 return false;
330 break;
333 case QTYPE_QINT: {
334 int64_t length = qint_get_int(qobject_to_qint(entry->value));
335 if (length > 0 && length <= UINT_MAX) {
336 block_acct_add_interval(stats, (unsigned) length);
337 } else {
338 error_setg(errp, "Invalid interval length: %" PRId64, length);
339 return false;
341 break;
344 default:
345 error_setg(errp, "The specification of stats-intervals is invalid");
346 return false;
349 return true;
352 typedef enum { MEDIA_DISK, MEDIA_CDROM } DriveMediaType;
354 /* All parameters but @opts are optional and may be set to NULL. */
355 static void extract_common_blockdev_options(QemuOpts *opts, int *bdrv_flags,
356 const char **throttling_group, ThrottleConfig *throttle_cfg,
357 BlockdevDetectZeroesOptions *detect_zeroes, Error **errp)
359 const char *discard;
360 Error *local_error = NULL;
361 const char *aio;
363 if (bdrv_flags) {
364 if (qemu_opt_get_bool(opts, "copy-on-read", false)) {
365 *bdrv_flags |= BDRV_O_COPY_ON_READ;
368 if ((discard = qemu_opt_get(opts, "discard")) != NULL) {
369 if (bdrv_parse_discard_flags(discard, bdrv_flags) != 0) {
370 error_setg(errp, "Invalid discard option");
371 return;
375 if ((aio = qemu_opt_get(opts, "aio")) != NULL) {
376 if (!strcmp(aio, "native")) {
377 *bdrv_flags |= BDRV_O_NATIVE_AIO;
378 } else if (!strcmp(aio, "threads")) {
379 /* this is the default */
380 } else {
381 error_setg(errp, "invalid aio option");
382 return;
387 /* disk I/O throttling */
388 if (throttling_group) {
389 *throttling_group = qemu_opt_get(opts, "throttling.group");
392 if (throttle_cfg) {
393 throttle_config_init(throttle_cfg);
394 throttle_cfg->buckets[THROTTLE_BPS_TOTAL].avg =
395 qemu_opt_get_number(opts, "throttling.bps-total", 0);
396 throttle_cfg->buckets[THROTTLE_BPS_READ].avg =
397 qemu_opt_get_number(opts, "throttling.bps-read", 0);
398 throttle_cfg->buckets[THROTTLE_BPS_WRITE].avg =
399 qemu_opt_get_number(opts, "throttling.bps-write", 0);
400 throttle_cfg->buckets[THROTTLE_OPS_TOTAL].avg =
401 qemu_opt_get_number(opts, "throttling.iops-total", 0);
402 throttle_cfg->buckets[THROTTLE_OPS_READ].avg =
403 qemu_opt_get_number(opts, "throttling.iops-read", 0);
404 throttle_cfg->buckets[THROTTLE_OPS_WRITE].avg =
405 qemu_opt_get_number(opts, "throttling.iops-write", 0);
407 throttle_cfg->buckets[THROTTLE_BPS_TOTAL].max =
408 qemu_opt_get_number(opts, "throttling.bps-total-max", 0);
409 throttle_cfg->buckets[THROTTLE_BPS_READ].max =
410 qemu_opt_get_number(opts, "throttling.bps-read-max", 0);
411 throttle_cfg->buckets[THROTTLE_BPS_WRITE].max =
412 qemu_opt_get_number(opts, "throttling.bps-write-max", 0);
413 throttle_cfg->buckets[THROTTLE_OPS_TOTAL].max =
414 qemu_opt_get_number(opts, "throttling.iops-total-max", 0);
415 throttle_cfg->buckets[THROTTLE_OPS_READ].max =
416 qemu_opt_get_number(opts, "throttling.iops-read-max", 0);
417 throttle_cfg->buckets[THROTTLE_OPS_WRITE].max =
418 qemu_opt_get_number(opts, "throttling.iops-write-max", 0);
420 throttle_cfg->buckets[THROTTLE_BPS_TOTAL].burst_length =
421 qemu_opt_get_number(opts, "throttling.bps-total-max-length", 1);
422 throttle_cfg->buckets[THROTTLE_BPS_READ].burst_length =
423 qemu_opt_get_number(opts, "throttling.bps-read-max-length", 1);
424 throttle_cfg->buckets[THROTTLE_BPS_WRITE].burst_length =
425 qemu_opt_get_number(opts, "throttling.bps-write-max-length", 1);
426 throttle_cfg->buckets[THROTTLE_OPS_TOTAL].burst_length =
427 qemu_opt_get_number(opts, "throttling.iops-total-max-length", 1);
428 throttle_cfg->buckets[THROTTLE_OPS_READ].burst_length =
429 qemu_opt_get_number(opts, "throttling.iops-read-max-length", 1);
430 throttle_cfg->buckets[THROTTLE_OPS_WRITE].burst_length =
431 qemu_opt_get_number(opts, "throttling.iops-write-max-length", 1);
433 throttle_cfg->op_size =
434 qemu_opt_get_number(opts, "throttling.iops-size", 0);
436 if (!throttle_is_valid(throttle_cfg, errp)) {
437 return;
441 if (detect_zeroes) {
442 *detect_zeroes =
443 qapi_enum_parse(BlockdevDetectZeroesOptions_lookup,
444 qemu_opt_get(opts, "detect-zeroes"),
445 BLOCKDEV_DETECT_ZEROES_OPTIONS__MAX,
446 BLOCKDEV_DETECT_ZEROES_OPTIONS_OFF,
447 &local_error);
448 if (local_error) {
449 error_propagate(errp, local_error);
450 return;
453 if (bdrv_flags &&
454 *detect_zeroes == BLOCKDEV_DETECT_ZEROES_OPTIONS_UNMAP &&
455 !(*bdrv_flags & BDRV_O_UNMAP))
457 error_setg(errp, "setting detect-zeroes to unmap is not allowed "
458 "without setting discard operation to unmap");
459 return;
464 /* Takes the ownership of bs_opts */
465 static BlockBackend *blockdev_init(const char *file, QDict *bs_opts,
466 Error **errp)
468 const char *buf;
469 int bdrv_flags = 0;
470 int on_read_error, on_write_error;
471 bool account_invalid, account_failed;
472 bool writethrough, read_only;
473 BlockBackend *blk;
474 BlockDriverState *bs;
475 ThrottleConfig cfg;
476 int snapshot = 0;
477 Error *error = NULL;
478 QemuOpts *opts;
479 QDict *interval_dict = NULL;
480 QList *interval_list = NULL;
481 const char *id;
482 BlockdevDetectZeroesOptions detect_zeroes =
483 BLOCKDEV_DETECT_ZEROES_OPTIONS_OFF;
484 const char *throttling_group = NULL;
486 /* Check common options by copying from bs_opts to opts, all other options
487 * stay in bs_opts for processing by bdrv_open(). */
488 id = qdict_get_try_str(bs_opts, "id");
489 opts = qemu_opts_create(&qemu_common_drive_opts, id, 1, &error);
490 if (error) {
491 error_propagate(errp, error);
492 goto err_no_opts;
495 qemu_opts_absorb_qdict(opts, bs_opts, &error);
496 if (error) {
497 error_propagate(errp, error);
498 goto early_err;
501 if (id) {
502 qdict_del(bs_opts, "id");
505 /* extract parameters */
506 snapshot = qemu_opt_get_bool(opts, "snapshot", 0);
508 account_invalid = qemu_opt_get_bool(opts, "stats-account-invalid", true);
509 account_failed = qemu_opt_get_bool(opts, "stats-account-failed", true);
511 writethrough = !qemu_opt_get_bool(opts, BDRV_OPT_CACHE_WB, true);
513 id = qemu_opts_id(opts);
515 qdict_extract_subqdict(bs_opts, &interval_dict, "stats-intervals.");
516 qdict_array_split(interval_dict, &interval_list);
518 if (qdict_size(interval_dict) != 0) {
519 error_setg(errp, "Invalid option stats-intervals.%s",
520 qdict_first(interval_dict)->key);
521 goto early_err;
524 extract_common_blockdev_options(opts, &bdrv_flags, &throttling_group, &cfg,
525 &detect_zeroes, &error);
526 if (error) {
527 error_propagate(errp, error);
528 goto early_err;
531 if ((buf = qemu_opt_get(opts, "format")) != NULL) {
532 if (is_help_option(buf)) {
533 error_printf("Supported formats:");
534 bdrv_iterate_format(bdrv_format_print, NULL);
535 error_printf("\n");
536 goto early_err;
539 if (qdict_haskey(bs_opts, "driver")) {
540 error_setg(errp, "Cannot specify both 'driver' and 'format'");
541 goto early_err;
543 qdict_put(bs_opts, "driver", qstring_from_str(buf));
546 on_write_error = BLOCKDEV_ON_ERROR_ENOSPC;
547 if ((buf = qemu_opt_get(opts, "werror")) != NULL) {
548 on_write_error = parse_block_error_action(buf, 0, &error);
549 if (error) {
550 error_propagate(errp, error);
551 goto early_err;
555 on_read_error = BLOCKDEV_ON_ERROR_REPORT;
556 if ((buf = qemu_opt_get(opts, "rerror")) != NULL) {
557 on_read_error = parse_block_error_action(buf, 1, &error);
558 if (error) {
559 error_propagate(errp, error);
560 goto early_err;
564 if (snapshot) {
565 bdrv_flags |= BDRV_O_SNAPSHOT;
568 read_only = qemu_opt_get_bool(opts, BDRV_OPT_READ_ONLY, false);
570 /* init */
571 if ((!file || !*file) && !qdict_size(bs_opts)) {
572 BlockBackendRootState *blk_rs;
574 blk = blk_new();
575 blk_rs = blk_get_root_state(blk);
576 blk_rs->open_flags = bdrv_flags;
577 blk_rs->read_only = read_only;
578 blk_rs->detect_zeroes = detect_zeroes;
580 QDECREF(bs_opts);
581 } else {
582 if (file && !*file) {
583 file = NULL;
586 /* bdrv_open() defaults to the values in bdrv_flags (for compatibility
587 * with other callers) rather than what we want as the real defaults.
588 * Apply the defaults here instead. */
589 qdict_set_default_str(bs_opts, BDRV_OPT_CACHE_DIRECT, "off");
590 qdict_set_default_str(bs_opts, BDRV_OPT_CACHE_NO_FLUSH, "off");
591 qdict_set_default_str(bs_opts, BDRV_OPT_READ_ONLY,
592 read_only ? "on" : "off");
593 assert((bdrv_flags & BDRV_O_CACHE_MASK) == 0);
595 if (runstate_check(RUN_STATE_INMIGRATE)) {
596 bdrv_flags |= BDRV_O_INACTIVE;
599 blk = blk_new_open(file, NULL, bs_opts, bdrv_flags, errp);
600 if (!blk) {
601 goto err_no_bs_opts;
603 bs = blk_bs(blk);
605 bs->detect_zeroes = detect_zeroes;
607 if (bdrv_key_required(bs)) {
608 autostart = 0;
611 block_acct_init(blk_get_stats(blk), account_invalid, account_failed);
613 if (!parse_stats_intervals(blk_get_stats(blk), interval_list, errp)) {
614 blk_unref(blk);
615 blk = NULL;
616 goto err_no_bs_opts;
620 /* disk I/O throttling */
621 if (throttle_enabled(&cfg)) {
622 if (!throttling_group) {
623 throttling_group = id;
625 blk_io_limits_enable(blk, throttling_group);
626 blk_set_io_limits(blk, &cfg);
629 blk_set_enable_write_cache(blk, !writethrough);
630 blk_set_on_error(blk, on_read_error, on_write_error);
632 if (!monitor_add_blk(blk, id, errp)) {
633 blk_unref(blk);
634 blk = NULL;
635 goto err_no_bs_opts;
638 err_no_bs_opts:
639 qemu_opts_del(opts);
640 QDECREF(interval_dict);
641 QDECREF(interval_list);
642 return blk;
644 early_err:
645 qemu_opts_del(opts);
646 QDECREF(interval_dict);
647 QDECREF(interval_list);
648 err_no_opts:
649 QDECREF(bs_opts);
650 return NULL;
653 static QemuOptsList qemu_root_bds_opts;
655 /* Takes the ownership of bs_opts */
656 static BlockDriverState *bds_tree_init(QDict *bs_opts, Error **errp)
658 BlockDriverState *bs;
659 QemuOpts *opts;
660 Error *local_error = NULL;
661 int bdrv_flags = 0;
663 opts = qemu_opts_create(&qemu_root_bds_opts, NULL, 1, errp);
664 if (!opts) {
665 goto fail;
668 qemu_opts_absorb_qdict(opts, bs_opts, &local_error);
669 if (local_error) {
670 error_propagate(errp, local_error);
671 goto fail;
674 extract_common_blockdev_options(opts, &bdrv_flags, NULL, NULL,
675 NULL, &local_error);
676 if (local_error) {
677 error_propagate(errp, local_error);
678 goto fail;
681 /* bdrv_open() defaults to the values in bdrv_flags (for compatibility
682 * with other callers) rather than what we want as the real defaults.
683 * Apply the defaults here instead. */
684 qdict_set_default_str(bs_opts, BDRV_OPT_CACHE_DIRECT, "off");
685 qdict_set_default_str(bs_opts, BDRV_OPT_CACHE_NO_FLUSH, "off");
686 qdict_set_default_str(bs_opts, BDRV_OPT_READ_ONLY, "off");
688 if (runstate_check(RUN_STATE_INMIGRATE)) {
689 bdrv_flags |= BDRV_O_INACTIVE;
692 bs = bdrv_open(NULL, NULL, bs_opts, bdrv_flags, errp);
693 if (!bs) {
694 goto fail_no_bs_opts;
697 fail_no_bs_opts:
698 qemu_opts_del(opts);
699 return bs;
701 fail:
702 qemu_opts_del(opts);
703 QDECREF(bs_opts);
704 return NULL;
707 void blockdev_close_all_bdrv_states(void)
709 BlockDriverState *bs, *next_bs;
711 QTAILQ_FOREACH_SAFE(bs, &monitor_bdrv_states, monitor_list, next_bs) {
712 AioContext *ctx = bdrv_get_aio_context(bs);
714 aio_context_acquire(ctx);
715 bdrv_unref(bs);
716 aio_context_release(ctx);
720 /* Iterates over the list of monitor-owned BlockDriverStates */
721 BlockDriverState *bdrv_next_monitor_owned(BlockDriverState *bs)
723 return bs ? QTAILQ_NEXT(bs, monitor_list)
724 : QTAILQ_FIRST(&monitor_bdrv_states);
727 static void qemu_opt_rename(QemuOpts *opts, const char *from, const char *to,
728 Error **errp)
730 const char *value;
732 value = qemu_opt_get(opts, from);
733 if (value) {
734 if (qemu_opt_find(opts, to)) {
735 error_setg(errp, "'%s' and its alias '%s' can't be used at the "
736 "same time", to, from);
737 return;
741 /* rename all items in opts */
742 while ((value = qemu_opt_get(opts, from))) {
743 qemu_opt_set(opts, to, value, &error_abort);
744 qemu_opt_unset(opts, from);
748 QemuOptsList qemu_legacy_drive_opts = {
749 .name = "drive",
750 .head = QTAILQ_HEAD_INITIALIZER(qemu_legacy_drive_opts.head),
751 .desc = {
753 .name = "bus",
754 .type = QEMU_OPT_NUMBER,
755 .help = "bus number",
757 .name = "unit",
758 .type = QEMU_OPT_NUMBER,
759 .help = "unit number (i.e. lun for scsi)",
761 .name = "index",
762 .type = QEMU_OPT_NUMBER,
763 .help = "index number",
765 .name = "media",
766 .type = QEMU_OPT_STRING,
767 .help = "media type (disk, cdrom)",
769 .name = "if",
770 .type = QEMU_OPT_STRING,
771 .help = "interface (ide, scsi, sd, mtd, floppy, pflash, virtio)",
773 .name = "cyls",
774 .type = QEMU_OPT_NUMBER,
775 .help = "number of cylinders (ide disk geometry)",
777 .name = "heads",
778 .type = QEMU_OPT_NUMBER,
779 .help = "number of heads (ide disk geometry)",
781 .name = "secs",
782 .type = QEMU_OPT_NUMBER,
783 .help = "number of sectors (ide disk geometry)",
785 .name = "trans",
786 .type = QEMU_OPT_STRING,
787 .help = "chs translation (auto, lba, none)",
789 .name = "boot",
790 .type = QEMU_OPT_BOOL,
791 .help = "(deprecated, ignored)",
793 .name = "addr",
794 .type = QEMU_OPT_STRING,
795 .help = "pci address (virtio only)",
797 .name = "serial",
798 .type = QEMU_OPT_STRING,
799 .help = "disk serial number",
801 .name = "file",
802 .type = QEMU_OPT_STRING,
803 .help = "file name",
806 /* Options that are passed on, but have special semantics with -drive */
808 .name = BDRV_OPT_READ_ONLY,
809 .type = QEMU_OPT_BOOL,
810 .help = "open drive file as read-only",
812 .name = "rerror",
813 .type = QEMU_OPT_STRING,
814 .help = "read error action",
816 .name = "werror",
817 .type = QEMU_OPT_STRING,
818 .help = "write error action",
820 .name = "copy-on-read",
821 .type = QEMU_OPT_BOOL,
822 .help = "copy read data from backing file into image file",
825 { /* end of list */ }
829 DriveInfo *drive_new(QemuOpts *all_opts, BlockInterfaceType block_default_type)
831 const char *value;
832 BlockBackend *blk;
833 DriveInfo *dinfo = NULL;
834 QDict *bs_opts;
835 QemuOpts *legacy_opts;
836 DriveMediaType media = MEDIA_DISK;
837 BlockInterfaceType type;
838 int cyls, heads, secs, translation;
839 int max_devs, bus_id, unit_id, index;
840 const char *devaddr;
841 const char *werror, *rerror;
842 bool read_only = false;
843 bool copy_on_read;
844 const char *serial;
845 const char *filename;
846 Error *local_err = NULL;
847 int i;
849 /* Change legacy command line options into QMP ones */
850 static const struct {
851 const char *from;
852 const char *to;
853 } opt_renames[] = {
854 { "iops", "throttling.iops-total" },
855 { "iops_rd", "throttling.iops-read" },
856 { "iops_wr", "throttling.iops-write" },
858 { "bps", "throttling.bps-total" },
859 { "bps_rd", "throttling.bps-read" },
860 { "bps_wr", "throttling.bps-write" },
862 { "iops_max", "throttling.iops-total-max" },
863 { "iops_rd_max", "throttling.iops-read-max" },
864 { "iops_wr_max", "throttling.iops-write-max" },
866 { "bps_max", "throttling.bps-total-max" },
867 { "bps_rd_max", "throttling.bps-read-max" },
868 { "bps_wr_max", "throttling.bps-write-max" },
870 { "iops_size", "throttling.iops-size" },
872 { "group", "throttling.group" },
874 { "readonly", BDRV_OPT_READ_ONLY },
877 for (i = 0; i < ARRAY_SIZE(opt_renames); i++) {
878 qemu_opt_rename(all_opts, opt_renames[i].from, opt_renames[i].to,
879 &local_err);
880 if (local_err) {
881 error_report_err(local_err);
882 return NULL;
886 value = qemu_opt_get(all_opts, "cache");
887 if (value) {
888 int flags = 0;
889 bool writethrough;
891 if (bdrv_parse_cache_mode(value, &flags, &writethrough) != 0) {
892 error_report("invalid cache option");
893 return NULL;
896 /* Specific options take precedence */
897 if (!qemu_opt_get(all_opts, BDRV_OPT_CACHE_WB)) {
898 qemu_opt_set_bool(all_opts, BDRV_OPT_CACHE_WB,
899 !writethrough, &error_abort);
901 if (!qemu_opt_get(all_opts, BDRV_OPT_CACHE_DIRECT)) {
902 qemu_opt_set_bool(all_opts, BDRV_OPT_CACHE_DIRECT,
903 !!(flags & BDRV_O_NOCACHE), &error_abort);
905 if (!qemu_opt_get(all_opts, BDRV_OPT_CACHE_NO_FLUSH)) {
906 qemu_opt_set_bool(all_opts, BDRV_OPT_CACHE_NO_FLUSH,
907 !!(flags & BDRV_O_NO_FLUSH), &error_abort);
909 qemu_opt_unset(all_opts, "cache");
912 /* Get a QDict for processing the options */
913 bs_opts = qdict_new();
914 qemu_opts_to_qdict(all_opts, bs_opts);
916 legacy_opts = qemu_opts_create(&qemu_legacy_drive_opts, NULL, 0,
917 &error_abort);
918 qemu_opts_absorb_qdict(legacy_opts, bs_opts, &local_err);
919 if (local_err) {
920 error_report_err(local_err);
921 goto fail;
924 /* Deprecated option boot=[on|off] */
925 if (qemu_opt_get(legacy_opts, "boot") != NULL) {
926 fprintf(stderr, "qemu-kvm: boot=on|off is deprecated and will be "
927 "ignored. Future versions will reject this parameter. Please "
928 "update your scripts.\n");
931 /* Media type */
932 value = qemu_opt_get(legacy_opts, "media");
933 if (value) {
934 if (!strcmp(value, "disk")) {
935 media = MEDIA_DISK;
936 } else if (!strcmp(value, "cdrom")) {
937 media = MEDIA_CDROM;
938 read_only = true;
939 } else {
940 error_report("'%s' invalid media", value);
941 goto fail;
945 /* copy-on-read is disabled with a warning for read-only devices */
946 read_only |= qemu_opt_get_bool(legacy_opts, BDRV_OPT_READ_ONLY, false);
947 copy_on_read = qemu_opt_get_bool(legacy_opts, "copy-on-read", false);
949 if (read_only && copy_on_read) {
950 error_report("warning: disabling copy-on-read on read-only drive");
951 copy_on_read = false;
954 qdict_put(bs_opts, BDRV_OPT_READ_ONLY,
955 qstring_from_str(read_only ? "on" : "off"));
956 qdict_put(bs_opts, "copy-on-read",
957 qstring_from_str(copy_on_read ? "on" :"off"));
959 /* Controller type */
960 value = qemu_opt_get(legacy_opts, "if");
961 if (value) {
962 for (type = 0;
963 type < IF_COUNT && strcmp(value, if_name[type]);
964 type++) {
966 if (type == IF_COUNT) {
967 error_report("unsupported bus type '%s'", value);
968 goto fail;
970 } else {
971 type = block_default_type;
974 /* Geometry */
975 cyls = qemu_opt_get_number(legacy_opts, "cyls", 0);
976 heads = qemu_opt_get_number(legacy_opts, "heads", 0);
977 secs = qemu_opt_get_number(legacy_opts, "secs", 0);
979 if (cyls || heads || secs) {
980 if (cyls < 1) {
981 error_report("invalid physical cyls number");
982 goto fail;
984 if (heads < 1) {
985 error_report("invalid physical heads number");
986 goto fail;
988 if (secs < 1) {
989 error_report("invalid physical secs number");
990 goto fail;
994 translation = BIOS_ATA_TRANSLATION_AUTO;
995 value = qemu_opt_get(legacy_opts, "trans");
996 if (value != NULL) {
997 if (!cyls) {
998 error_report("'%s' trans must be used with cyls, heads and secs",
999 value);
1000 goto fail;
1002 if (!strcmp(value, "none")) {
1003 translation = BIOS_ATA_TRANSLATION_NONE;
1004 } else if (!strcmp(value, "lba")) {
1005 translation = BIOS_ATA_TRANSLATION_LBA;
1006 } else if (!strcmp(value, "large")) {
1007 translation = BIOS_ATA_TRANSLATION_LARGE;
1008 } else if (!strcmp(value, "rechs")) {
1009 translation = BIOS_ATA_TRANSLATION_RECHS;
1010 } else if (!strcmp(value, "auto")) {
1011 translation = BIOS_ATA_TRANSLATION_AUTO;
1012 } else {
1013 error_report("'%s' invalid translation type", value);
1014 goto fail;
1018 if (media == MEDIA_CDROM) {
1019 if (cyls || secs || heads) {
1020 error_report("CHS can't be set with media=cdrom");
1021 goto fail;
1025 /* Device address specified by bus/unit or index.
1026 * If none was specified, try to find the first free one. */
1027 bus_id = qemu_opt_get_number(legacy_opts, "bus", 0);
1028 unit_id = qemu_opt_get_number(legacy_opts, "unit", -1);
1029 index = qemu_opt_get_number(legacy_opts, "index", -1);
1031 max_devs = if_max_devs[type];
1033 if (index != -1) {
1034 if (bus_id != 0 || unit_id != -1) {
1035 error_report("index cannot be used with bus and unit");
1036 goto fail;
1038 bus_id = drive_index_to_bus_id(type, index);
1039 unit_id = drive_index_to_unit_id(type, index);
1042 if (unit_id == -1) {
1043 unit_id = 0;
1044 while (drive_get(type, bus_id, unit_id) != NULL) {
1045 unit_id++;
1046 if (max_devs && unit_id >= max_devs) {
1047 unit_id -= max_devs;
1048 bus_id++;
1053 if (max_devs && unit_id >= max_devs) {
1054 error_report("unit %d too big (max is %d)", unit_id, max_devs - 1);
1055 goto fail;
1058 if (drive_get(type, bus_id, unit_id) != NULL) {
1059 error_report("drive with bus=%d, unit=%d (index=%d) exists",
1060 bus_id, unit_id, index);
1061 goto fail;
1064 /* Serial number */
1065 serial = qemu_opt_get(legacy_opts, "serial");
1067 /* no id supplied -> create one */
1068 if (qemu_opts_id(all_opts) == NULL) {
1069 char *new_id;
1070 const char *mediastr = "";
1071 if (type == IF_IDE || type == IF_SCSI) {
1072 mediastr = (media == MEDIA_CDROM) ? "-cd" : "-hd";
1074 if (max_devs) {
1075 new_id = g_strdup_printf("%s%i%s%i", if_name[type], bus_id,
1076 mediastr, unit_id);
1077 } else {
1078 new_id = g_strdup_printf("%s%s%i", if_name[type],
1079 mediastr, unit_id);
1081 qdict_put(bs_opts, "id", qstring_from_str(new_id));
1082 g_free(new_id);
1085 /* Add virtio block device */
1086 devaddr = qemu_opt_get(legacy_opts, "addr");
1087 if (devaddr && type != IF_VIRTIO) {
1088 error_report("addr is not supported by this bus type");
1089 goto fail;
1092 if (type == IF_VIRTIO) {
1093 QemuOpts *devopts;
1094 devopts = qemu_opts_create(qemu_find_opts("device"), NULL, 0,
1095 &error_abort);
1096 if (arch_type == QEMU_ARCH_S390X) {
1097 qemu_opt_set(devopts, "driver", "virtio-blk-ccw", &error_abort);
1098 } else {
1099 qemu_opt_set(devopts, "driver", "virtio-blk-pci", &error_abort);
1101 qemu_opt_set(devopts, "drive", qdict_get_str(bs_opts, "id"),
1102 &error_abort);
1103 if (devaddr) {
1104 qemu_opt_set(devopts, "addr", devaddr, &error_abort);
1108 filename = qemu_opt_get(legacy_opts, "file");
1110 /* Check werror/rerror compatibility with if=... */
1111 werror = qemu_opt_get(legacy_opts, "werror");
1112 if (werror != NULL) {
1113 if (type != IF_IDE && type != IF_SCSI && type != IF_VIRTIO &&
1114 type != IF_NONE) {
1115 error_report("werror is not supported by this bus type");
1116 goto fail;
1118 qdict_put(bs_opts, "werror", qstring_from_str(werror));
1121 rerror = qemu_opt_get(legacy_opts, "rerror");
1122 if (rerror != NULL) {
1123 if (type != IF_IDE && type != IF_VIRTIO && type != IF_SCSI &&
1124 type != IF_NONE) {
1125 error_report("rerror is not supported by this bus type");
1126 goto fail;
1128 qdict_put(bs_opts, "rerror", qstring_from_str(rerror));
1131 /* Actual block device init: Functionality shared with blockdev-add */
1132 blk = blockdev_init(filename, bs_opts, &local_err);
1133 bs_opts = NULL;
1134 if (!blk) {
1135 if (local_err) {
1136 error_report_err(local_err);
1138 goto fail;
1139 } else {
1140 assert(!local_err);
1143 /* Create legacy DriveInfo */
1144 dinfo = g_malloc0(sizeof(*dinfo));
1145 dinfo->opts = all_opts;
1147 dinfo->cyls = cyls;
1148 dinfo->heads = heads;
1149 dinfo->secs = secs;
1150 dinfo->trans = translation;
1152 dinfo->type = type;
1153 dinfo->bus = bus_id;
1154 dinfo->unit = unit_id;
1155 dinfo->devaddr = devaddr;
1156 dinfo->serial = g_strdup(serial);
1158 blk_set_legacy_dinfo(blk, dinfo);
1160 switch(type) {
1161 case IF_IDE:
1162 case IF_SCSI:
1163 case IF_XEN:
1164 case IF_NONE:
1165 dinfo->media_cd = media == MEDIA_CDROM;
1166 break;
1167 default:
1168 break;
1171 fail:
1172 qemu_opts_del(legacy_opts);
1173 QDECREF(bs_opts);
1174 return dinfo;
1177 static BlockDriverState *qmp_get_root_bs(const char *name, Error **errp)
1179 BlockDriverState *bs;
1181 bs = bdrv_lookup_bs(name, name, errp);
1182 if (bs == NULL) {
1183 return NULL;
1186 if (!bdrv_is_root_node(bs)) {
1187 error_setg(errp, "Need a root block node");
1188 return NULL;
1191 if (!bdrv_is_inserted(bs)) {
1192 error_setg(errp, "Device has no medium");
1193 return NULL;
1196 return bs;
1199 static BlockBackend *qmp_get_blk(const char *blk_name, const char *qdev_id,
1200 Error **errp)
1202 BlockBackend *blk;
1204 if (!blk_name == !qdev_id) {
1205 error_setg(errp, "Need exactly one of 'device' and 'id'");
1206 return NULL;
1209 if (qdev_id) {
1210 blk = blk_by_qdev_id(qdev_id, errp);
1211 } else {
1212 blk = blk_by_name(blk_name);
1213 if (blk == NULL) {
1214 error_set(errp, ERROR_CLASS_DEVICE_NOT_FOUND,
1215 "Device '%s' not found", blk_name);
1219 return blk;
1222 void hmp_commit(Monitor *mon, const QDict *qdict)
1224 const char *device = qdict_get_str(qdict, "device");
1225 BlockBackend *blk;
1226 int ret;
1228 if (!strcmp(device, "all")) {
1229 ret = blk_commit_all();
1230 } else {
1231 BlockDriverState *bs;
1232 AioContext *aio_context;
1234 blk = blk_by_name(device);
1235 if (!blk) {
1236 monitor_printf(mon, "Device '%s' not found\n", device);
1237 return;
1239 if (!blk_is_available(blk)) {
1240 monitor_printf(mon, "Device '%s' has no medium\n", device);
1241 return;
1244 bs = blk_bs(blk);
1245 aio_context = bdrv_get_aio_context(bs);
1246 aio_context_acquire(aio_context);
1248 ret = bdrv_commit(bs);
1250 aio_context_release(aio_context);
1252 if (ret < 0) {
1253 monitor_printf(mon, "'commit' error for '%s': %s\n", device,
1254 strerror(-ret));
1258 static void blockdev_do_action(TransactionAction *action, Error **errp)
1260 TransactionActionList list;
1262 list.value = action;
1263 list.next = NULL;
1264 qmp_transaction(&list, false, NULL, errp);
1267 void qmp_blockdev_snapshot_sync(bool has_device, const char *device,
1268 bool has_node_name, const char *node_name,
1269 const char *snapshot_file,
1270 bool has_snapshot_node_name,
1271 const char *snapshot_node_name,
1272 bool has_format, const char *format,
1273 bool has_mode, NewImageMode mode, Error **errp)
1275 BlockdevSnapshotSync snapshot = {
1276 .has_device = has_device,
1277 .device = (char *) device,
1278 .has_node_name = has_node_name,
1279 .node_name = (char *) node_name,
1280 .snapshot_file = (char *) snapshot_file,
1281 .has_snapshot_node_name = has_snapshot_node_name,
1282 .snapshot_node_name = (char *) snapshot_node_name,
1283 .has_format = has_format,
1284 .format = (char *) format,
1285 .has_mode = has_mode,
1286 .mode = mode,
1288 TransactionAction action = {
1289 .type = TRANSACTION_ACTION_KIND_BLOCKDEV_SNAPSHOT_SYNC,
1290 .u.blockdev_snapshot_sync.data = &snapshot,
1292 blockdev_do_action(&action, errp);
1295 void qmp_blockdev_snapshot(const char *node, const char *overlay,
1296 Error **errp)
1298 BlockdevSnapshot snapshot_data = {
1299 .node = (char *) node,
1300 .overlay = (char *) overlay
1302 TransactionAction action = {
1303 .type = TRANSACTION_ACTION_KIND_BLOCKDEV_SNAPSHOT,
1304 .u.blockdev_snapshot.data = &snapshot_data,
1306 blockdev_do_action(&action, errp);
1309 void qmp_blockdev_snapshot_internal_sync(const char *device,
1310 const char *name,
1311 Error **errp)
1313 BlockdevSnapshotInternal snapshot = {
1314 .device = (char *) device,
1315 .name = (char *) name
1317 TransactionAction action = {
1318 .type = TRANSACTION_ACTION_KIND_BLOCKDEV_SNAPSHOT_INTERNAL_SYNC,
1319 .u.blockdev_snapshot_internal_sync.data = &snapshot,
1321 blockdev_do_action(&action, errp);
1324 SnapshotInfo *qmp_blockdev_snapshot_delete_internal_sync(const char *device,
1325 bool has_id,
1326 const char *id,
1327 bool has_name,
1328 const char *name,
1329 Error **errp)
1331 BlockDriverState *bs;
1332 AioContext *aio_context;
1333 QEMUSnapshotInfo sn;
1334 Error *local_err = NULL;
1335 SnapshotInfo *info = NULL;
1336 int ret;
1338 bs = qmp_get_root_bs(device, errp);
1339 if (!bs) {
1340 return NULL;
1342 aio_context = bdrv_get_aio_context(bs);
1343 aio_context_acquire(aio_context);
1345 if (!has_id) {
1346 id = NULL;
1349 if (!has_name) {
1350 name = NULL;
1353 if (!id && !name) {
1354 error_setg(errp, "Name or id must be provided");
1355 goto out_aio_context;
1358 if (bdrv_op_is_blocked(bs, BLOCK_OP_TYPE_INTERNAL_SNAPSHOT_DELETE, errp)) {
1359 goto out_aio_context;
1362 ret = bdrv_snapshot_find_by_id_and_name(bs, id, name, &sn, &local_err);
1363 if (local_err) {
1364 error_propagate(errp, local_err);
1365 goto out_aio_context;
1367 if (!ret) {
1368 error_setg(errp,
1369 "Snapshot with id '%s' and name '%s' does not exist on "
1370 "device '%s'",
1371 STR_OR_NULL(id), STR_OR_NULL(name), device);
1372 goto out_aio_context;
1375 bdrv_snapshot_delete(bs, id, name, &local_err);
1376 if (local_err) {
1377 error_propagate(errp, local_err);
1378 goto out_aio_context;
1381 aio_context_release(aio_context);
1383 info = g_new0(SnapshotInfo, 1);
1384 info->id = g_strdup(sn.id_str);
1385 info->name = g_strdup(sn.name);
1386 info->date_nsec = sn.date_nsec;
1387 info->date_sec = sn.date_sec;
1388 info->vm_state_size = sn.vm_state_size;
1389 info->vm_clock_nsec = sn.vm_clock_nsec % 1000000000;
1390 info->vm_clock_sec = sn.vm_clock_nsec / 1000000000;
1392 return info;
1394 out_aio_context:
1395 aio_context_release(aio_context);
1396 return NULL;
1400 * block_dirty_bitmap_lookup:
1401 * Return a dirty bitmap (if present), after validating
1402 * the node reference and bitmap names.
1404 * @node: The name of the BDS node to search for bitmaps
1405 * @name: The name of the bitmap to search for
1406 * @pbs: Output pointer for BDS lookup, if desired. Can be NULL.
1407 * @paio: Output pointer for aio_context acquisition, if desired. Can be NULL.
1408 * @errp: Output pointer for error information. Can be NULL.
1410 * @return: A bitmap object on success, or NULL on failure.
1412 static BdrvDirtyBitmap *block_dirty_bitmap_lookup(const char *node,
1413 const char *name,
1414 BlockDriverState **pbs,
1415 AioContext **paio,
1416 Error **errp)
1418 BlockDriverState *bs;
1419 BdrvDirtyBitmap *bitmap;
1420 AioContext *aio_context;
1422 if (!node) {
1423 error_setg(errp, "Node cannot be NULL");
1424 return NULL;
1426 if (!name) {
1427 error_setg(errp, "Bitmap name cannot be NULL");
1428 return NULL;
1430 bs = bdrv_lookup_bs(node, node, NULL);
1431 if (!bs) {
1432 error_setg(errp, "Node '%s' not found", node);
1433 return NULL;
1436 aio_context = bdrv_get_aio_context(bs);
1437 aio_context_acquire(aio_context);
1439 bitmap = bdrv_find_dirty_bitmap(bs, name);
1440 if (!bitmap) {
1441 error_setg(errp, "Dirty bitmap '%s' not found", name);
1442 goto fail;
1445 if (pbs) {
1446 *pbs = bs;
1448 if (paio) {
1449 *paio = aio_context;
1450 } else {
1451 aio_context_release(aio_context);
1454 return bitmap;
1456 fail:
1457 aio_context_release(aio_context);
1458 return NULL;
1461 /* New and old BlockDriverState structs for atomic group operations */
1463 typedef struct BlkActionState BlkActionState;
1466 * BlkActionOps:
1467 * Table of operations that define an Action.
1469 * @instance_size: Size of state struct, in bytes.
1470 * @prepare: Prepare the work, must NOT be NULL.
1471 * @commit: Commit the changes, can be NULL.
1472 * @abort: Abort the changes on fail, can be NULL.
1473 * @clean: Clean up resources after all transaction actions have called
1474 * commit() or abort(). Can be NULL.
1476 * Only prepare() may fail. In a single transaction, only one of commit() or
1477 * abort() will be called. clean() will always be called if it is present.
1479 typedef struct BlkActionOps {
1480 size_t instance_size;
1481 void (*prepare)(BlkActionState *common, Error **errp);
1482 void (*commit)(BlkActionState *common);
1483 void (*abort)(BlkActionState *common);
1484 void (*clean)(BlkActionState *common);
1485 } BlkActionOps;
1488 * BlkActionState:
1489 * Describes one Action's state within a Transaction.
1491 * @action: QAPI-defined enum identifying which Action to perform.
1492 * @ops: Table of ActionOps this Action can perform.
1493 * @block_job_txn: Transaction which this action belongs to.
1494 * @entry: List membership for all Actions in this Transaction.
1496 * This structure must be arranged as first member in a subclassed type,
1497 * assuming that the compiler will also arrange it to the same offsets as the
1498 * base class.
1500 struct BlkActionState {
1501 TransactionAction *action;
1502 const BlkActionOps *ops;
1503 BlockJobTxn *block_job_txn;
1504 TransactionProperties *txn_props;
1505 QSIMPLEQ_ENTRY(BlkActionState) entry;
1508 /* internal snapshot private data */
1509 typedef struct InternalSnapshotState {
1510 BlkActionState common;
1511 BlockDriverState *bs;
1512 AioContext *aio_context;
1513 QEMUSnapshotInfo sn;
1514 bool created;
1515 } InternalSnapshotState;
1518 static int action_check_completion_mode(BlkActionState *s, Error **errp)
1520 if (s->txn_props->completion_mode != ACTION_COMPLETION_MODE_INDIVIDUAL) {
1521 error_setg(errp,
1522 "Action '%s' does not support Transaction property "
1523 "completion-mode = %s",
1524 TransactionActionKind_lookup[s->action->type],
1525 ActionCompletionMode_lookup[s->txn_props->completion_mode]);
1526 return -1;
1528 return 0;
1531 static void internal_snapshot_prepare(BlkActionState *common,
1532 Error **errp)
1534 Error *local_err = NULL;
1535 const char *device;
1536 const char *name;
1537 BlockDriverState *bs;
1538 QEMUSnapshotInfo old_sn, *sn;
1539 bool ret;
1540 qemu_timeval tv;
1541 BlockdevSnapshotInternal *internal;
1542 InternalSnapshotState *state;
1543 int ret1;
1545 g_assert(common->action->type ==
1546 TRANSACTION_ACTION_KIND_BLOCKDEV_SNAPSHOT_INTERNAL_SYNC);
1547 internal = common->action->u.blockdev_snapshot_internal_sync.data;
1548 state = DO_UPCAST(InternalSnapshotState, common, common);
1550 /* 1. parse input */
1551 device = internal->device;
1552 name = internal->name;
1554 /* 2. check for validation */
1555 if (action_check_completion_mode(common, errp) < 0) {
1556 return;
1559 bs = qmp_get_root_bs(device, errp);
1560 if (!bs) {
1561 return;
1564 /* AioContext is released in .clean() */
1565 state->aio_context = bdrv_get_aio_context(bs);
1566 aio_context_acquire(state->aio_context);
1568 state->bs = bs;
1569 bdrv_drained_begin(bs);
1571 if (bdrv_op_is_blocked(bs, BLOCK_OP_TYPE_INTERNAL_SNAPSHOT, errp)) {
1572 return;
1575 if (bdrv_is_read_only(bs)) {
1576 error_setg(errp, "Device '%s' is read only", device);
1577 return;
1580 if (!bdrv_can_snapshot(bs)) {
1581 error_setg(errp, "Block format '%s' used by device '%s' "
1582 "does not support internal snapshots",
1583 bs->drv->format_name, device);
1584 return;
1587 if (!strlen(name)) {
1588 error_setg(errp, "Name is empty");
1589 return;
1592 /* check whether a snapshot with name exist */
1593 ret = bdrv_snapshot_find_by_id_and_name(bs, NULL, name, &old_sn,
1594 &local_err);
1595 if (local_err) {
1596 error_propagate(errp, local_err);
1597 return;
1598 } else if (ret) {
1599 error_setg(errp,
1600 "Snapshot with name '%s' already exists on device '%s'",
1601 name, device);
1602 return;
1605 /* 3. take the snapshot */
1606 sn = &state->sn;
1607 pstrcpy(sn->name, sizeof(sn->name), name);
1608 qemu_gettimeofday(&tv);
1609 sn->date_sec = tv.tv_sec;
1610 sn->date_nsec = tv.tv_usec * 1000;
1611 sn->vm_clock_nsec = qemu_clock_get_ns(QEMU_CLOCK_VIRTUAL);
1613 ret1 = bdrv_snapshot_create(bs, sn);
1614 if (ret1 < 0) {
1615 error_setg_errno(errp, -ret1,
1616 "Failed to create snapshot '%s' on device '%s'",
1617 name, device);
1618 return;
1621 /* 4. succeed, mark a snapshot is created */
1622 state->created = true;
1625 static void internal_snapshot_abort(BlkActionState *common)
1627 InternalSnapshotState *state =
1628 DO_UPCAST(InternalSnapshotState, common, common);
1629 BlockDriverState *bs = state->bs;
1630 QEMUSnapshotInfo *sn = &state->sn;
1631 Error *local_error = NULL;
1633 if (!state->created) {
1634 return;
1637 if (bdrv_snapshot_delete(bs, sn->id_str, sn->name, &local_error) < 0) {
1638 error_reportf_err(local_error,
1639 "Failed to delete snapshot with id '%s' and "
1640 "name '%s' on device '%s' in abort: ",
1641 sn->id_str, sn->name,
1642 bdrv_get_device_name(bs));
1646 static void internal_snapshot_clean(BlkActionState *common)
1648 InternalSnapshotState *state = DO_UPCAST(InternalSnapshotState,
1649 common, common);
1651 if (state->aio_context) {
1652 if (state->bs) {
1653 bdrv_drained_end(state->bs);
1655 aio_context_release(state->aio_context);
1659 /* external snapshot private data */
1660 typedef struct ExternalSnapshotState {
1661 BlkActionState common;
1662 BlockDriverState *old_bs;
1663 BlockDriverState *new_bs;
1664 AioContext *aio_context;
1665 } ExternalSnapshotState;
1667 static void external_snapshot_prepare(BlkActionState *common,
1668 Error **errp)
1670 int flags = 0;
1671 QDict *options = NULL;
1672 Error *local_err = NULL;
1673 /* Device and node name of the image to generate the snapshot from */
1674 const char *device;
1675 const char *node_name;
1676 /* Reference to the new image (for 'blockdev-snapshot') */
1677 const char *snapshot_ref;
1678 /* File name of the new image (for 'blockdev-snapshot-sync') */
1679 const char *new_image_file;
1680 ExternalSnapshotState *state =
1681 DO_UPCAST(ExternalSnapshotState, common, common);
1682 TransactionAction *action = common->action;
1684 /* 'blockdev-snapshot' and 'blockdev-snapshot-sync' have similar
1685 * purpose but a different set of parameters */
1686 switch (action->type) {
1687 case TRANSACTION_ACTION_KIND_BLOCKDEV_SNAPSHOT:
1689 BlockdevSnapshot *s = action->u.blockdev_snapshot.data;
1690 device = s->node;
1691 node_name = s->node;
1692 new_image_file = NULL;
1693 snapshot_ref = s->overlay;
1695 break;
1696 case TRANSACTION_ACTION_KIND_BLOCKDEV_SNAPSHOT_SYNC:
1698 BlockdevSnapshotSync *s = action->u.blockdev_snapshot_sync.data;
1699 device = s->has_device ? s->device : NULL;
1700 node_name = s->has_node_name ? s->node_name : NULL;
1701 new_image_file = s->snapshot_file;
1702 snapshot_ref = NULL;
1704 break;
1705 default:
1706 g_assert_not_reached();
1709 /* start processing */
1710 if (action_check_completion_mode(common, errp) < 0) {
1711 return;
1714 state->old_bs = bdrv_lookup_bs(device, node_name, errp);
1715 if (!state->old_bs) {
1716 return;
1719 /* Acquire AioContext now so any threads operating on old_bs stop */
1720 state->aio_context = bdrv_get_aio_context(state->old_bs);
1721 aio_context_acquire(state->aio_context);
1722 bdrv_drained_begin(state->old_bs);
1724 if (!bdrv_is_inserted(state->old_bs)) {
1725 error_setg(errp, QERR_DEVICE_HAS_NO_MEDIUM, device);
1726 return;
1729 if (bdrv_op_is_blocked(state->old_bs,
1730 BLOCK_OP_TYPE_EXTERNAL_SNAPSHOT, errp)) {
1731 return;
1734 if (!bdrv_is_read_only(state->old_bs)) {
1735 if (bdrv_flush(state->old_bs)) {
1736 error_setg(errp, QERR_IO_ERROR);
1737 return;
1741 if (!bdrv_is_first_non_filter(state->old_bs)) {
1742 error_setg(errp, QERR_FEATURE_DISABLED, "snapshot");
1743 return;
1746 if (action->type == TRANSACTION_ACTION_KIND_BLOCKDEV_SNAPSHOT_SYNC) {
1747 BlockdevSnapshotSync *s = action->u.blockdev_snapshot_sync.data;
1748 const char *format = s->has_format ? s->format : "qcow2";
1749 enum NewImageMode mode;
1750 const char *snapshot_node_name =
1751 s->has_snapshot_node_name ? s->snapshot_node_name : NULL;
1753 if (node_name && !snapshot_node_name) {
1754 error_setg(errp, "New snapshot node name missing");
1755 return;
1758 if (snapshot_node_name &&
1759 bdrv_lookup_bs(snapshot_node_name, snapshot_node_name, NULL)) {
1760 error_setg(errp, "New snapshot node name already in use");
1761 return;
1764 flags = state->old_bs->open_flags;
1765 flags &= ~(BDRV_O_SNAPSHOT | BDRV_O_NO_BACKING | BDRV_O_COPY_ON_READ);
1767 /* create new image w/backing file */
1768 mode = s->has_mode ? s->mode : NEW_IMAGE_MODE_ABSOLUTE_PATHS;
1769 if (mode != NEW_IMAGE_MODE_EXISTING) {
1770 int64_t size = bdrv_getlength(state->old_bs);
1771 if (size < 0) {
1772 error_setg_errno(errp, -size, "bdrv_getlength failed");
1773 return;
1775 bdrv_img_create(new_image_file, format,
1776 state->old_bs->filename,
1777 state->old_bs->drv->format_name,
1778 NULL, size, flags, &local_err, false);
1779 if (local_err) {
1780 error_propagate(errp, local_err);
1781 return;
1785 options = qdict_new();
1786 if (s->has_snapshot_node_name) {
1787 qdict_put(options, "node-name",
1788 qstring_from_str(snapshot_node_name));
1790 qdict_put(options, "driver", qstring_from_str(format));
1792 flags |= BDRV_O_NO_BACKING;
1795 state->new_bs = bdrv_open(new_image_file, snapshot_ref, options, flags,
1796 errp);
1797 /* We will manually add the backing_hd field to the bs later */
1798 if (!state->new_bs) {
1799 return;
1802 if (bdrv_has_blk(state->new_bs)) {
1803 error_setg(errp, "The snapshot is already in use");
1804 return;
1807 if (bdrv_op_is_blocked(state->new_bs, BLOCK_OP_TYPE_EXTERNAL_SNAPSHOT,
1808 errp)) {
1809 return;
1812 if (state->new_bs->backing != NULL) {
1813 error_setg(errp, "The snapshot already has a backing image");
1814 return;
1817 if (!state->new_bs->drv->supports_backing) {
1818 error_setg(errp, "The snapshot does not support backing images");
1822 static void external_snapshot_commit(BlkActionState *common)
1824 ExternalSnapshotState *state =
1825 DO_UPCAST(ExternalSnapshotState, common, common);
1827 bdrv_set_aio_context(state->new_bs, state->aio_context);
1829 /* This removes our old bs and adds the new bs */
1830 bdrv_append(state->new_bs, state->old_bs);
1831 /* We don't need (or want) to use the transactional
1832 * bdrv_reopen_multiple() across all the entries at once, because we
1833 * don't want to abort all of them if one of them fails the reopen */
1834 if (!state->old_bs->copy_on_read) {
1835 bdrv_reopen(state->old_bs, state->old_bs->open_flags & ~BDRV_O_RDWR,
1836 NULL);
1840 static void external_snapshot_abort(BlkActionState *common)
1842 ExternalSnapshotState *state =
1843 DO_UPCAST(ExternalSnapshotState, common, common);
1844 if (state->new_bs) {
1845 bdrv_unref(state->new_bs);
1849 static void external_snapshot_clean(BlkActionState *common)
1851 ExternalSnapshotState *state =
1852 DO_UPCAST(ExternalSnapshotState, common, common);
1853 if (state->aio_context) {
1854 bdrv_drained_end(state->old_bs);
1855 aio_context_release(state->aio_context);
1859 typedef struct DriveBackupState {
1860 BlkActionState common;
1861 BlockDriverState *bs;
1862 AioContext *aio_context;
1863 BlockJob *job;
1864 } DriveBackupState;
1866 static void 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 Error *local_err = NULL;
1876 assert(common->action->type == TRANSACTION_ACTION_KIND_DRIVE_BACKUP);
1877 backup = common->action->u.drive_backup.data;
1879 bs = qmp_get_root_bs(backup->device, errp);
1880 if (!bs) {
1881 return;
1884 /* AioContext is released in .clean() */
1885 state->aio_context = bdrv_get_aio_context(bs);
1886 aio_context_acquire(state->aio_context);
1887 bdrv_drained_begin(bs);
1888 state->bs = bs;
1890 do_drive_backup(backup, common->block_job_txn, &local_err);
1891 if (local_err) {
1892 error_propagate(errp, local_err);
1893 return;
1896 state->job = state->bs->job;
1899 static void drive_backup_abort(BlkActionState *common)
1901 DriveBackupState *state = DO_UPCAST(DriveBackupState, common, common);
1902 BlockDriverState *bs = state->bs;
1904 /* Only cancel if it's the job we started */
1905 if (bs && bs->job && bs->job == state->job) {
1906 block_job_cancel_sync(bs->job);
1910 static void drive_backup_clean(BlkActionState *common)
1912 DriveBackupState *state = DO_UPCAST(DriveBackupState, common, common);
1914 if (state->aio_context) {
1915 bdrv_drained_end(state->bs);
1916 aio_context_release(state->aio_context);
1920 typedef struct BlockdevBackupState {
1921 BlkActionState common;
1922 BlockDriverState *bs;
1923 BlockJob *job;
1924 AioContext *aio_context;
1925 } BlockdevBackupState;
1927 static void do_blockdev_backup(BlockdevBackup *backup, BlockJobTxn *txn,
1928 Error **errp);
1930 static void blockdev_backup_prepare(BlkActionState *common, Error **errp)
1932 BlockdevBackupState *state = DO_UPCAST(BlockdevBackupState, common, common);
1933 BlockdevBackup *backup;
1934 BlockDriverState *bs, *target;
1935 Error *local_err = NULL;
1937 assert(common->action->type == TRANSACTION_ACTION_KIND_BLOCKDEV_BACKUP);
1938 backup = common->action->u.blockdev_backup.data;
1940 bs = qmp_get_root_bs(backup->device, errp);
1941 if (!bs) {
1942 return;
1945 target = bdrv_lookup_bs(backup->target, backup->target, errp);
1946 if (!target) {
1947 return;
1950 /* AioContext is released in .clean() */
1951 state->aio_context = bdrv_get_aio_context(bs);
1952 if (state->aio_context != bdrv_get_aio_context(target)) {
1953 state->aio_context = NULL;
1954 error_setg(errp, "Backup between two IO threads is not implemented");
1955 return;
1957 aio_context_acquire(state->aio_context);
1958 state->bs = bs;
1959 bdrv_drained_begin(state->bs);
1961 do_blockdev_backup(backup, common->block_job_txn, &local_err);
1962 if (local_err) {
1963 error_propagate(errp, local_err);
1964 return;
1967 state->job = state->bs->job;
1970 static void blockdev_backup_abort(BlkActionState *common)
1972 BlockdevBackupState *state = DO_UPCAST(BlockdevBackupState, common, common);
1973 BlockDriverState *bs = state->bs;
1975 /* Only cancel if it's the job we started */
1976 if (bs && bs->job && bs->job == state->job) {
1977 block_job_cancel_sync(bs->job);
1981 static void blockdev_backup_clean(BlkActionState *common)
1983 BlockdevBackupState *state = DO_UPCAST(BlockdevBackupState, common, common);
1985 if (state->aio_context) {
1986 bdrv_drained_end(state->bs);
1987 aio_context_release(state->aio_context);
1991 typedef struct BlockDirtyBitmapState {
1992 BlkActionState common;
1993 BdrvDirtyBitmap *bitmap;
1994 BlockDriverState *bs;
1995 AioContext *aio_context;
1996 HBitmap *backup;
1997 bool prepared;
1998 } BlockDirtyBitmapState;
2000 static void block_dirty_bitmap_add_prepare(BlkActionState *common,
2001 Error **errp)
2003 Error *local_err = NULL;
2004 BlockDirtyBitmapAdd *action;
2005 BlockDirtyBitmapState *state = DO_UPCAST(BlockDirtyBitmapState,
2006 common, common);
2008 if (action_check_completion_mode(common, errp) < 0) {
2009 return;
2012 action = common->action->u.block_dirty_bitmap_add.data;
2013 /* AIO context taken and released within qmp_block_dirty_bitmap_add */
2014 qmp_block_dirty_bitmap_add(action->node, action->name,
2015 action->has_granularity, action->granularity,
2016 &local_err);
2018 if (!local_err) {
2019 state->prepared = true;
2020 } else {
2021 error_propagate(errp, local_err);
2025 static void block_dirty_bitmap_add_abort(BlkActionState *common)
2027 BlockDirtyBitmapAdd *action;
2028 BlockDirtyBitmapState *state = DO_UPCAST(BlockDirtyBitmapState,
2029 common, common);
2031 action = common->action->u.block_dirty_bitmap_add.data;
2032 /* Should not be able to fail: IF the bitmap was added via .prepare(),
2033 * then the node reference and bitmap name must have been valid.
2035 if (state->prepared) {
2036 qmp_block_dirty_bitmap_remove(action->node, action->name, &error_abort);
2040 static void block_dirty_bitmap_clear_prepare(BlkActionState *common,
2041 Error **errp)
2043 BlockDirtyBitmapState *state = DO_UPCAST(BlockDirtyBitmapState,
2044 common, common);
2045 BlockDirtyBitmap *action;
2047 if (action_check_completion_mode(common, errp) < 0) {
2048 return;
2051 action = common->action->u.block_dirty_bitmap_clear.data;
2052 state->bitmap = block_dirty_bitmap_lookup(action->node,
2053 action->name,
2054 &state->bs,
2055 &state->aio_context,
2056 errp);
2057 if (!state->bitmap) {
2058 return;
2061 if (bdrv_dirty_bitmap_frozen(state->bitmap)) {
2062 error_setg(errp, "Cannot modify a frozen bitmap");
2063 return;
2064 } else if (!bdrv_dirty_bitmap_enabled(state->bitmap)) {
2065 error_setg(errp, "Cannot clear a disabled bitmap");
2066 return;
2069 bdrv_clear_dirty_bitmap(state->bitmap, &state->backup);
2070 /* AioContext is released in .clean() */
2073 static void block_dirty_bitmap_clear_abort(BlkActionState *common)
2075 BlockDirtyBitmapState *state = DO_UPCAST(BlockDirtyBitmapState,
2076 common, common);
2078 bdrv_undo_clear_dirty_bitmap(state->bitmap, state->backup);
2081 static void block_dirty_bitmap_clear_commit(BlkActionState *common)
2083 BlockDirtyBitmapState *state = DO_UPCAST(BlockDirtyBitmapState,
2084 common, common);
2086 hbitmap_free(state->backup);
2089 static void block_dirty_bitmap_clear_clean(BlkActionState *common)
2091 BlockDirtyBitmapState *state = DO_UPCAST(BlockDirtyBitmapState,
2092 common, common);
2094 if (state->aio_context) {
2095 aio_context_release(state->aio_context);
2099 static void abort_prepare(BlkActionState *common, Error **errp)
2101 error_setg(errp, "Transaction aborted using Abort action");
2104 static void abort_commit(BlkActionState *common)
2106 g_assert_not_reached(); /* this action never succeeds */
2109 static const BlkActionOps actions[] = {
2110 [TRANSACTION_ACTION_KIND_BLOCKDEV_SNAPSHOT] = {
2111 .instance_size = sizeof(ExternalSnapshotState),
2112 .prepare = external_snapshot_prepare,
2113 .commit = external_snapshot_commit,
2114 .abort = external_snapshot_abort,
2115 .clean = external_snapshot_clean,
2117 [TRANSACTION_ACTION_KIND_BLOCKDEV_SNAPSHOT_SYNC] = {
2118 .instance_size = sizeof(ExternalSnapshotState),
2119 .prepare = external_snapshot_prepare,
2120 .commit = external_snapshot_commit,
2121 .abort = external_snapshot_abort,
2122 .clean = external_snapshot_clean,
2124 [TRANSACTION_ACTION_KIND_DRIVE_BACKUP] = {
2125 .instance_size = sizeof(DriveBackupState),
2126 .prepare = drive_backup_prepare,
2127 .abort = drive_backup_abort,
2128 .clean = drive_backup_clean,
2130 [TRANSACTION_ACTION_KIND_BLOCKDEV_BACKUP] = {
2131 .instance_size = sizeof(BlockdevBackupState),
2132 .prepare = blockdev_backup_prepare,
2133 .abort = blockdev_backup_abort,
2134 .clean = blockdev_backup_clean,
2136 [TRANSACTION_ACTION_KIND_ABORT] = {
2137 .instance_size = sizeof(BlkActionState),
2138 .prepare = abort_prepare,
2139 .commit = abort_commit,
2141 [TRANSACTION_ACTION_KIND_BLOCKDEV_SNAPSHOT_INTERNAL_SYNC] = {
2142 .instance_size = sizeof(InternalSnapshotState),
2143 .prepare = internal_snapshot_prepare,
2144 .abort = internal_snapshot_abort,
2145 .clean = internal_snapshot_clean,
2147 [TRANSACTION_ACTION_KIND_BLOCK_DIRTY_BITMAP_ADD] = {
2148 .instance_size = sizeof(BlockDirtyBitmapState),
2149 .prepare = block_dirty_bitmap_add_prepare,
2150 .abort = block_dirty_bitmap_add_abort,
2152 [TRANSACTION_ACTION_KIND_BLOCK_DIRTY_BITMAP_CLEAR] = {
2153 .instance_size = sizeof(BlockDirtyBitmapState),
2154 .prepare = block_dirty_bitmap_clear_prepare,
2155 .commit = block_dirty_bitmap_clear_commit,
2156 .abort = block_dirty_bitmap_clear_abort,
2157 .clean = block_dirty_bitmap_clear_clean,
2162 * Allocate a TransactionProperties structure if necessary, and fill
2163 * that structure with desired defaults if they are unset.
2165 static TransactionProperties *get_transaction_properties(
2166 TransactionProperties *props)
2168 if (!props) {
2169 props = g_new0(TransactionProperties, 1);
2172 if (!props->has_completion_mode) {
2173 props->has_completion_mode = true;
2174 props->completion_mode = ACTION_COMPLETION_MODE_INDIVIDUAL;
2177 return props;
2181 * 'Atomic' group operations. The operations are performed as a set, and if
2182 * any fail then we roll back all operations in the group.
2184 void qmp_transaction(TransactionActionList *dev_list,
2185 bool has_props,
2186 struct TransactionProperties *props,
2187 Error **errp)
2189 TransactionActionList *dev_entry = dev_list;
2190 BlockJobTxn *block_job_txn = NULL;
2191 BlkActionState *state, *next;
2192 Error *local_err = NULL;
2194 QSIMPLEQ_HEAD(snap_bdrv_states, BlkActionState) snap_bdrv_states;
2195 QSIMPLEQ_INIT(&snap_bdrv_states);
2197 /* Does this transaction get canceled as a group on failure?
2198 * If not, we don't really need to make a BlockJobTxn.
2200 props = get_transaction_properties(props);
2201 if (props->completion_mode != ACTION_COMPLETION_MODE_INDIVIDUAL) {
2202 block_job_txn = block_job_txn_new();
2205 /* drain all i/o before any operations */
2206 bdrv_drain_all();
2208 /* We don't do anything in this loop that commits us to the operations */
2209 while (NULL != dev_entry) {
2210 TransactionAction *dev_info = NULL;
2211 const BlkActionOps *ops;
2213 dev_info = dev_entry->value;
2214 dev_entry = dev_entry->next;
2216 assert(dev_info->type < ARRAY_SIZE(actions));
2218 ops = &actions[dev_info->type];
2219 assert(ops->instance_size > 0);
2221 state = g_malloc0(ops->instance_size);
2222 state->ops = ops;
2223 state->action = dev_info;
2224 state->block_job_txn = block_job_txn;
2225 state->txn_props = props;
2226 QSIMPLEQ_INSERT_TAIL(&snap_bdrv_states, state, entry);
2228 state->ops->prepare(state, &local_err);
2229 if (local_err) {
2230 error_propagate(errp, local_err);
2231 goto delete_and_fail;
2235 QSIMPLEQ_FOREACH(state, &snap_bdrv_states, entry) {
2236 if (state->ops->commit) {
2237 state->ops->commit(state);
2241 /* success */
2242 goto exit;
2244 delete_and_fail:
2245 /* failure, and it is all-or-none; roll back all operations */
2246 QSIMPLEQ_FOREACH(state, &snap_bdrv_states, entry) {
2247 if (state->ops->abort) {
2248 state->ops->abort(state);
2251 exit:
2252 QSIMPLEQ_FOREACH_SAFE(state, &snap_bdrv_states, entry, next) {
2253 if (state->ops->clean) {
2254 state->ops->clean(state);
2256 g_free(state);
2258 if (!has_props) {
2259 qapi_free_TransactionProperties(props);
2261 block_job_txn_unref(block_job_txn);
2264 void qmp_eject(bool has_device, const char *device,
2265 bool has_id, const char *id,
2266 bool has_force, bool force, Error **errp)
2268 Error *local_err = NULL;
2269 int rc;
2271 if (!has_force) {
2272 force = false;
2275 rc = do_open_tray(has_device ? device : NULL,
2276 has_id ? id : NULL,
2277 force, &local_err);
2278 if (rc && rc != -ENOSYS) {
2279 error_propagate(errp, local_err);
2280 return;
2282 error_free(local_err);
2284 qmp_x_blockdev_remove_medium(has_device, device, has_id, id, errp);
2287 void qmp_block_passwd(bool has_device, const char *device,
2288 bool has_node_name, const char *node_name,
2289 const char *password, Error **errp)
2291 Error *local_err = NULL;
2292 BlockDriverState *bs;
2293 AioContext *aio_context;
2295 bs = bdrv_lookup_bs(has_device ? device : NULL,
2296 has_node_name ? node_name : NULL,
2297 &local_err);
2298 if (local_err) {
2299 error_propagate(errp, local_err);
2300 return;
2303 aio_context = bdrv_get_aio_context(bs);
2304 aio_context_acquire(aio_context);
2306 bdrv_add_key(bs, password, errp);
2308 aio_context_release(aio_context);
2312 * Attempt to open the tray of @device.
2313 * If @force, ignore its tray lock.
2314 * Else, if the tray is locked, don't open it, but ask the guest to open it.
2315 * On error, store an error through @errp and return -errno.
2316 * If @device does not exist, return -ENODEV.
2317 * If it has no removable media, return -ENOTSUP.
2318 * If it has no tray, return -ENOSYS.
2319 * If the guest was asked to open the tray, return -EINPROGRESS.
2320 * Else, return 0.
2322 static int do_open_tray(const char *blk_name, const char *qdev_id,
2323 bool force, Error **errp)
2325 BlockBackend *blk;
2326 const char *device = qdev_id ?: blk_name;
2327 bool locked;
2329 blk = qmp_get_blk(blk_name, qdev_id, errp);
2330 if (!blk) {
2331 return -ENODEV;
2334 if (!blk_dev_has_removable_media(blk)) {
2335 error_setg(errp, "Device '%s' is not removable", device);
2336 return -ENOTSUP;
2339 if (!blk_dev_has_tray(blk)) {
2340 error_setg(errp, "Device '%s' does not have a tray", device);
2341 return -ENOSYS;
2344 if (blk_dev_is_tray_open(blk)) {
2345 return 0;
2348 locked = blk_dev_is_medium_locked(blk);
2349 if (locked) {
2350 blk_dev_eject_request(blk, force);
2353 if (!locked || force) {
2354 blk_dev_change_media_cb(blk, false);
2357 if (locked && !force) {
2358 error_setg(errp, "Device '%s' is locked and force was not specified, "
2359 "wait for tray to open and try again", device);
2360 return -EINPROGRESS;
2363 return 0;
2366 void qmp_blockdev_open_tray(bool has_device, const char *device,
2367 bool has_id, const char *id,
2368 bool has_force, bool force,
2369 Error **errp)
2371 Error *local_err = NULL;
2372 int rc;
2374 if (!has_force) {
2375 force = false;
2377 rc = do_open_tray(has_device ? device : NULL,
2378 has_id ? id : NULL,
2379 force, &local_err);
2380 if (rc && rc != -ENOSYS && rc != -EINPROGRESS) {
2381 error_propagate(errp, local_err);
2382 return;
2384 error_free(local_err);
2387 void qmp_blockdev_close_tray(bool has_device, const char *device,
2388 bool has_id, const char *id,
2389 Error **errp)
2391 BlockBackend *blk;
2393 device = has_device ? device : NULL;
2394 id = has_id ? id : NULL;
2396 blk = qmp_get_blk(device, id, errp);
2397 if (!blk) {
2398 return;
2401 if (!blk_dev_has_removable_media(blk)) {
2402 error_setg(errp, "Device '%s' is not removable", device ?: id);
2403 return;
2406 if (!blk_dev_has_tray(blk)) {
2407 /* Ignore this command on tray-less devices */
2408 return;
2411 if (!blk_dev_is_tray_open(blk)) {
2412 return;
2415 blk_dev_change_media_cb(blk, true);
2418 void qmp_x_blockdev_remove_medium(bool has_device, const char *device,
2419 bool has_id, const char *id, Error **errp)
2421 BlockBackend *blk;
2422 BlockDriverState *bs;
2423 AioContext *aio_context;
2424 bool has_attached_device;
2426 device = has_device ? device : NULL;
2427 id = has_id ? id : NULL;
2429 blk = qmp_get_blk(device, id, errp);
2430 if (!blk) {
2431 return;
2434 /* For BBs without a device, we can exchange the BDS tree at will */
2435 has_attached_device = blk_get_attached_dev(blk);
2437 if (has_attached_device && !blk_dev_has_removable_media(blk)) {
2438 error_setg(errp, "Device '%s' is not removable", device ?: id);
2439 return;
2442 if (has_attached_device && blk_dev_has_tray(blk) &&
2443 !blk_dev_is_tray_open(blk))
2445 error_setg(errp, "Tray of device '%s' is not open", device ?: id);
2446 return;
2449 bs = blk_bs(blk);
2450 if (!bs) {
2451 return;
2454 aio_context = bdrv_get_aio_context(bs);
2455 aio_context_acquire(aio_context);
2457 if (bdrv_op_is_blocked(bs, BLOCK_OP_TYPE_EJECT, errp)) {
2458 goto out;
2461 blk_remove_bs(blk);
2463 if (!blk_dev_has_tray(blk)) {
2464 /* For tray-less devices, blockdev-open-tray is a no-op (or may not be
2465 * called at all); therefore, the medium needs to be ejected here.
2466 * Do it after blk_remove_bs() so blk_is_inserted(blk) returns the @load
2467 * value passed here (i.e. false). */
2468 blk_dev_change_media_cb(blk, false);
2471 out:
2472 aio_context_release(aio_context);
2475 static void qmp_blockdev_insert_anon_medium(BlockBackend *blk,
2476 BlockDriverState *bs, Error **errp)
2478 bool has_device;
2480 /* For BBs without a device, we can exchange the BDS tree at will */
2481 has_device = blk_get_attached_dev(blk);
2483 if (has_device && !blk_dev_has_removable_media(blk)) {
2484 error_setg(errp, "Device is not removable");
2485 return;
2488 if (has_device && blk_dev_has_tray(blk) && !blk_dev_is_tray_open(blk)) {
2489 error_setg(errp, "Tray of the device is not open");
2490 return;
2493 if (blk_bs(blk)) {
2494 error_setg(errp, "There already is a medium in the device");
2495 return;
2498 blk_insert_bs(blk, bs);
2500 if (!blk_dev_has_tray(blk)) {
2501 /* For tray-less devices, blockdev-close-tray is a no-op (or may not be
2502 * called at all); therefore, the medium needs to be pushed into the
2503 * slot here.
2504 * Do it after blk_insert_bs() so blk_is_inserted(blk) returns the @load
2505 * value passed here (i.e. true). */
2506 blk_dev_change_media_cb(blk, true);
2510 void qmp_x_blockdev_insert_medium(bool has_device, const char *device,
2511 bool has_id, const char *id,
2512 const char *node_name, Error **errp)
2514 BlockBackend *blk;
2515 BlockDriverState *bs;
2517 blk = qmp_get_blk(has_device ? device : NULL,
2518 has_id ? id : NULL,
2519 errp);
2520 if (!blk) {
2521 return;
2524 bs = bdrv_find_node(node_name);
2525 if (!bs) {
2526 error_setg(errp, "Node '%s' not found", node_name);
2527 return;
2530 if (bdrv_has_blk(bs)) {
2531 error_setg(errp, "Node '%s' is already in use", node_name);
2532 return;
2535 qmp_blockdev_insert_anon_medium(blk, bs, errp);
2538 void qmp_blockdev_change_medium(bool has_device, const char *device,
2539 bool has_id, const char *id,
2540 const char *filename,
2541 bool has_format, const char *format,
2542 bool has_read_only,
2543 BlockdevChangeReadOnlyMode read_only,
2544 Error **errp)
2546 BlockBackend *blk;
2547 BlockDriverState *medium_bs = NULL;
2548 int bdrv_flags;
2549 int rc;
2550 QDict *options = NULL;
2551 Error *err = NULL;
2553 blk = qmp_get_blk(has_device ? device : NULL,
2554 has_id ? id : NULL,
2555 errp);
2556 if (!blk) {
2557 goto fail;
2560 if (blk_bs(blk)) {
2561 blk_update_root_state(blk);
2564 bdrv_flags = blk_get_open_flags_from_root_state(blk);
2565 bdrv_flags &= ~(BDRV_O_TEMPORARY | BDRV_O_SNAPSHOT | BDRV_O_NO_BACKING |
2566 BDRV_O_PROTOCOL);
2568 if (!has_read_only) {
2569 read_only = BLOCKDEV_CHANGE_READ_ONLY_MODE_RETAIN;
2572 switch (read_only) {
2573 case BLOCKDEV_CHANGE_READ_ONLY_MODE_RETAIN:
2574 break;
2576 case BLOCKDEV_CHANGE_READ_ONLY_MODE_READ_ONLY:
2577 bdrv_flags &= ~BDRV_O_RDWR;
2578 break;
2580 case BLOCKDEV_CHANGE_READ_ONLY_MODE_READ_WRITE:
2581 bdrv_flags |= BDRV_O_RDWR;
2582 break;
2584 default:
2585 abort();
2588 if (has_format) {
2589 options = qdict_new();
2590 qdict_put(options, "driver", qstring_from_str(format));
2593 medium_bs = bdrv_open(filename, NULL, options, bdrv_flags, errp);
2594 if (!medium_bs) {
2595 goto fail;
2598 bdrv_add_key(medium_bs, NULL, &err);
2599 if (err) {
2600 error_propagate(errp, err);
2601 goto fail;
2604 rc = do_open_tray(has_device ? device : NULL,
2605 has_id ? id : NULL,
2606 false, &err);
2607 if (rc && rc != -ENOSYS) {
2608 error_propagate(errp, err);
2609 goto fail;
2611 error_free(err);
2612 err = NULL;
2614 qmp_x_blockdev_remove_medium(has_device, device, has_id, id, &err);
2615 if (err) {
2616 error_propagate(errp, err);
2617 goto fail;
2620 qmp_blockdev_insert_anon_medium(blk, medium_bs, &err);
2621 if (err) {
2622 error_propagate(errp, err);
2623 goto fail;
2626 blk_apply_root_state(blk, medium_bs);
2628 qmp_blockdev_close_tray(has_device, device, has_id, id, errp);
2630 fail:
2631 /* If the medium has been inserted, the device has its own reference, so
2632 * ours must be relinquished; and if it has not been inserted successfully,
2633 * the reference must be relinquished anyway */
2634 bdrv_unref(medium_bs);
2637 /* throttling disk I/O limits */
2638 void qmp_block_set_io_throttle(BlockIOThrottle *arg, Error **errp)
2640 ThrottleConfig cfg;
2641 BlockDriverState *bs;
2642 BlockBackend *blk;
2643 AioContext *aio_context;
2645 blk = qmp_get_blk(arg->has_device ? arg->device : NULL,
2646 arg->has_id ? arg->id : NULL,
2647 errp);
2648 if (!blk) {
2649 return;
2652 aio_context = blk_get_aio_context(blk);
2653 aio_context_acquire(aio_context);
2655 bs = blk_bs(blk);
2656 if (!bs) {
2657 error_setg(errp, "Device has no medium");
2658 goto out;
2661 throttle_config_init(&cfg);
2662 cfg.buckets[THROTTLE_BPS_TOTAL].avg = arg->bps;
2663 cfg.buckets[THROTTLE_BPS_READ].avg = arg->bps_rd;
2664 cfg.buckets[THROTTLE_BPS_WRITE].avg = arg->bps_wr;
2666 cfg.buckets[THROTTLE_OPS_TOTAL].avg = arg->iops;
2667 cfg.buckets[THROTTLE_OPS_READ].avg = arg->iops_rd;
2668 cfg.buckets[THROTTLE_OPS_WRITE].avg = arg->iops_wr;
2670 if (arg->has_bps_max) {
2671 cfg.buckets[THROTTLE_BPS_TOTAL].max = arg->bps_max;
2673 if (arg->has_bps_rd_max) {
2674 cfg.buckets[THROTTLE_BPS_READ].max = arg->bps_rd_max;
2676 if (arg->has_bps_wr_max) {
2677 cfg.buckets[THROTTLE_BPS_WRITE].max = arg->bps_wr_max;
2679 if (arg->has_iops_max) {
2680 cfg.buckets[THROTTLE_OPS_TOTAL].max = arg->iops_max;
2682 if (arg->has_iops_rd_max) {
2683 cfg.buckets[THROTTLE_OPS_READ].max = arg->iops_rd_max;
2685 if (arg->has_iops_wr_max) {
2686 cfg.buckets[THROTTLE_OPS_WRITE].max = arg->iops_wr_max;
2689 if (arg->has_bps_max_length) {
2690 cfg.buckets[THROTTLE_BPS_TOTAL].burst_length = arg->bps_max_length;
2692 if (arg->has_bps_rd_max_length) {
2693 cfg.buckets[THROTTLE_BPS_READ].burst_length = arg->bps_rd_max_length;
2695 if (arg->has_bps_wr_max_length) {
2696 cfg.buckets[THROTTLE_BPS_WRITE].burst_length = arg->bps_wr_max_length;
2698 if (arg->has_iops_max_length) {
2699 cfg.buckets[THROTTLE_OPS_TOTAL].burst_length = arg->iops_max_length;
2701 if (arg->has_iops_rd_max_length) {
2702 cfg.buckets[THROTTLE_OPS_READ].burst_length = arg->iops_rd_max_length;
2704 if (arg->has_iops_wr_max_length) {
2705 cfg.buckets[THROTTLE_OPS_WRITE].burst_length = arg->iops_wr_max_length;
2708 if (arg->has_iops_size) {
2709 cfg.op_size = arg->iops_size;
2712 if (!throttle_is_valid(&cfg, errp)) {
2713 goto out;
2716 if (throttle_enabled(&cfg)) {
2717 /* Enable I/O limits if they're not enabled yet, otherwise
2718 * just update the throttling group. */
2719 if (!blk_get_public(blk)->throttle_state) {
2720 blk_io_limits_enable(blk,
2721 arg->has_group ? arg->group :
2722 arg->has_device ? arg->device :
2723 arg->id);
2724 } else if (arg->has_group) {
2725 blk_io_limits_update_group(blk, arg->group);
2727 /* Set the new throttling configuration */
2728 blk_set_io_limits(blk, &cfg);
2729 } else if (blk_get_public(blk)->throttle_state) {
2730 /* If all throttling settings are set to 0, disable I/O limits */
2731 blk_io_limits_disable(blk);
2734 out:
2735 aio_context_release(aio_context);
2738 void qmp_block_dirty_bitmap_add(const char *node, const char *name,
2739 bool has_granularity, uint32_t granularity,
2740 Error **errp)
2742 AioContext *aio_context;
2743 BlockDriverState *bs;
2745 if (!name || name[0] == '\0') {
2746 error_setg(errp, "Bitmap name cannot be empty");
2747 return;
2750 bs = bdrv_lookup_bs(node, node, errp);
2751 if (!bs) {
2752 return;
2755 aio_context = bdrv_get_aio_context(bs);
2756 aio_context_acquire(aio_context);
2758 if (has_granularity) {
2759 if (granularity < 512 || !is_power_of_2(granularity)) {
2760 error_setg(errp, "Granularity must be power of 2 "
2761 "and at least 512");
2762 goto out;
2764 } else {
2765 /* Default to cluster size, if available: */
2766 granularity = bdrv_get_default_bitmap_granularity(bs);
2769 bdrv_create_dirty_bitmap(bs, granularity, name, errp);
2771 out:
2772 aio_context_release(aio_context);
2775 void qmp_block_dirty_bitmap_remove(const char *node, const char *name,
2776 Error **errp)
2778 AioContext *aio_context;
2779 BlockDriverState *bs;
2780 BdrvDirtyBitmap *bitmap;
2782 bitmap = block_dirty_bitmap_lookup(node, name, &bs, &aio_context, errp);
2783 if (!bitmap || !bs) {
2784 return;
2787 if (bdrv_dirty_bitmap_frozen(bitmap)) {
2788 error_setg(errp,
2789 "Bitmap '%s' is currently frozen and cannot be removed",
2790 name);
2791 goto out;
2793 bdrv_dirty_bitmap_make_anon(bitmap);
2794 bdrv_release_dirty_bitmap(bs, bitmap);
2796 out:
2797 aio_context_release(aio_context);
2801 * Completely clear a bitmap, for the purposes of synchronizing a bitmap
2802 * immediately after a full backup operation.
2804 void qmp_block_dirty_bitmap_clear(const char *node, const char *name,
2805 Error **errp)
2807 AioContext *aio_context;
2808 BdrvDirtyBitmap *bitmap;
2809 BlockDriverState *bs;
2811 bitmap = block_dirty_bitmap_lookup(node, name, &bs, &aio_context, errp);
2812 if (!bitmap || !bs) {
2813 return;
2816 if (bdrv_dirty_bitmap_frozen(bitmap)) {
2817 error_setg(errp,
2818 "Bitmap '%s' is currently frozen and cannot be modified",
2819 name);
2820 goto out;
2821 } else if (!bdrv_dirty_bitmap_enabled(bitmap)) {
2822 error_setg(errp,
2823 "Bitmap '%s' is currently disabled and cannot be cleared",
2824 name);
2825 goto out;
2828 bdrv_clear_dirty_bitmap(bitmap, NULL);
2830 out:
2831 aio_context_release(aio_context);
2834 void hmp_drive_del(Monitor *mon, const QDict *qdict)
2836 const char *id = qdict_get_str(qdict, "id");
2837 BlockBackend *blk;
2838 BlockDriverState *bs;
2839 AioContext *aio_context;
2840 Error *local_err = NULL;
2842 bs = bdrv_find_node(id);
2843 if (bs) {
2844 qmp_x_blockdev_del(id, &local_err);
2845 if (local_err) {
2846 error_report_err(local_err);
2848 return;
2851 blk = blk_by_name(id);
2852 if (!blk) {
2853 error_report("Device '%s' not found", id);
2854 return;
2857 if (!blk_legacy_dinfo(blk)) {
2858 error_report("Deleting device added with blockdev-add"
2859 " is not supported");
2860 return;
2863 aio_context = blk_get_aio_context(blk);
2864 aio_context_acquire(aio_context);
2866 bs = blk_bs(blk);
2867 if (bs) {
2868 if (bdrv_op_is_blocked(bs, BLOCK_OP_TYPE_DRIVE_DEL, &local_err)) {
2869 error_report_err(local_err);
2870 aio_context_release(aio_context);
2871 return;
2874 blk_remove_bs(blk);
2877 /* Make the BlockBackend and the attached BlockDriverState anonymous */
2878 monitor_remove_blk(blk);
2880 /* If this BlockBackend has a device attached to it, its refcount will be
2881 * decremented when the device is removed; otherwise we have to do so here.
2883 if (blk_get_attached_dev(blk)) {
2884 /* Further I/O must not pause the guest */
2885 blk_set_on_error(blk, BLOCKDEV_ON_ERROR_REPORT,
2886 BLOCKDEV_ON_ERROR_REPORT);
2887 } else {
2888 blk_unref(blk);
2891 aio_context_release(aio_context);
2894 void qmp_block_resize(bool has_device, const char *device,
2895 bool has_node_name, const char *node_name,
2896 int64_t size, Error **errp)
2898 Error *local_err = NULL;
2899 BlockDriverState *bs;
2900 AioContext *aio_context;
2901 int ret;
2903 bs = bdrv_lookup_bs(has_device ? device : NULL,
2904 has_node_name ? node_name : NULL,
2905 &local_err);
2906 if (local_err) {
2907 error_propagate(errp, local_err);
2908 return;
2911 aio_context = bdrv_get_aio_context(bs);
2912 aio_context_acquire(aio_context);
2914 if (!bdrv_is_first_non_filter(bs)) {
2915 error_setg(errp, QERR_FEATURE_DISABLED, "resize");
2916 goto out;
2919 if (size < 0) {
2920 error_setg(errp, QERR_INVALID_PARAMETER_VALUE, "size", "a >0 size");
2921 goto out;
2924 if (bdrv_op_is_blocked(bs, BLOCK_OP_TYPE_RESIZE, NULL)) {
2925 error_setg(errp, QERR_DEVICE_IN_USE, device);
2926 goto out;
2929 /* complete all in-flight operations before resizing the device */
2930 bdrv_drain_all();
2932 ret = bdrv_truncate(bs, size);
2933 switch (ret) {
2934 case 0:
2935 break;
2936 case -ENOMEDIUM:
2937 error_setg(errp, QERR_DEVICE_HAS_NO_MEDIUM, device);
2938 break;
2939 case -ENOTSUP:
2940 error_setg(errp, QERR_UNSUPPORTED);
2941 break;
2942 case -EACCES:
2943 error_setg(errp, "Device '%s' is read only", device);
2944 break;
2945 case -EBUSY:
2946 error_setg(errp, QERR_DEVICE_IN_USE, device);
2947 break;
2948 default:
2949 error_setg_errno(errp, -ret, "Could not resize");
2950 break;
2953 out:
2954 aio_context_release(aio_context);
2957 static void block_job_cb(void *opaque, int ret)
2959 /* Note that this function may be executed from another AioContext besides
2960 * the QEMU main loop. If you need to access anything that assumes the
2961 * QEMU global mutex, use a BH or introduce a mutex.
2964 BlockDriverState *bs = opaque;
2965 const char *msg = NULL;
2967 trace_block_job_cb(bs, bs->job, ret);
2969 assert(bs->job);
2971 if (ret < 0) {
2972 msg = strerror(-ret);
2975 if (block_job_is_cancelled(bs->job)) {
2976 block_job_event_cancelled(bs->job);
2977 } else {
2978 block_job_event_completed(bs->job, msg);
2982 void qmp_block_stream(bool has_job_id, const char *job_id, const char *device,
2983 bool has_base, const char *base,
2984 bool has_backing_file, const char *backing_file,
2985 bool has_speed, int64_t speed,
2986 bool has_on_error, BlockdevOnError on_error,
2987 Error **errp)
2989 BlockDriverState *bs;
2990 BlockDriverState *base_bs = NULL;
2991 AioContext *aio_context;
2992 Error *local_err = NULL;
2993 const char *base_name = NULL;
2995 if (!has_on_error) {
2996 on_error = BLOCKDEV_ON_ERROR_REPORT;
2999 bs = qmp_get_root_bs(device, errp);
3000 if (!bs) {
3001 return;
3004 aio_context = bdrv_get_aio_context(bs);
3005 aio_context_acquire(aio_context);
3007 if (bdrv_op_is_blocked(bs, BLOCK_OP_TYPE_STREAM, errp)) {
3008 goto out;
3011 if (has_base) {
3012 base_bs = bdrv_find_backing_image(bs, base);
3013 if (base_bs == NULL) {
3014 error_setg(errp, QERR_BASE_NOT_FOUND, base);
3015 goto out;
3017 assert(bdrv_get_aio_context(base_bs) == aio_context);
3018 base_name = base;
3021 /* if we are streaming the entire chain, the result will have no backing
3022 * file, and specifying one is therefore an error */
3023 if (base_bs == NULL && has_backing_file) {
3024 error_setg(errp, "backing file specified, but streaming the "
3025 "entire chain");
3026 goto out;
3029 /* backing_file string overrides base bs filename */
3030 base_name = has_backing_file ? backing_file : base_name;
3032 stream_start(has_job_id ? job_id : NULL, bs, base_bs, base_name,
3033 has_speed ? speed : 0, on_error, block_job_cb, bs, &local_err);
3034 if (local_err) {
3035 error_propagate(errp, local_err);
3036 goto out;
3039 trace_qmp_block_stream(bs, bs->job);
3041 out:
3042 aio_context_release(aio_context);
3045 void qmp_block_commit(bool has_job_id, const char *job_id, const char *device,
3046 bool has_base, const char *base,
3047 bool has_top, const char *top,
3048 bool has_backing_file, const char *backing_file,
3049 bool has_speed, int64_t speed,
3050 Error **errp)
3052 BlockDriverState *bs;
3053 BlockDriverState *base_bs, *top_bs;
3054 AioContext *aio_context;
3055 Error *local_err = NULL;
3056 /* This will be part of the QMP command, if/when the
3057 * BlockdevOnError change for blkmirror makes it in
3059 BlockdevOnError on_error = BLOCKDEV_ON_ERROR_REPORT;
3061 if (!has_speed) {
3062 speed = 0;
3065 /* Important Note:
3066 * libvirt relies on the DeviceNotFound error class in order to probe for
3067 * live commit feature versions; for this to work, we must make sure to
3068 * perform the device lookup before any generic errors that may occur in a
3069 * scenario in which all optional arguments are omitted. */
3070 bs = qmp_get_root_bs(device, &local_err);
3071 if (!bs) {
3072 bs = bdrv_lookup_bs(device, device, NULL);
3073 if (!bs) {
3074 error_free(local_err);
3075 error_set(errp, ERROR_CLASS_DEVICE_NOT_FOUND,
3076 "Device '%s' not found", device);
3077 } else {
3078 error_propagate(errp, local_err);
3080 return;
3083 aio_context = bdrv_get_aio_context(bs);
3084 aio_context_acquire(aio_context);
3086 if (bdrv_op_is_blocked(bs, BLOCK_OP_TYPE_COMMIT_SOURCE, errp)) {
3087 goto out;
3090 /* default top_bs is the active layer */
3091 top_bs = bs;
3093 if (has_top && top) {
3094 if (strcmp(bs->filename, top) != 0) {
3095 top_bs = bdrv_find_backing_image(bs, top);
3099 if (top_bs == NULL) {
3100 error_setg(errp, "Top image file %s not found", top ? top : "NULL");
3101 goto out;
3104 assert(bdrv_get_aio_context(top_bs) == aio_context);
3106 if (has_base && base) {
3107 base_bs = bdrv_find_backing_image(top_bs, base);
3108 } else {
3109 base_bs = bdrv_find_base(top_bs);
3112 if (base_bs == NULL) {
3113 error_setg(errp, QERR_BASE_NOT_FOUND, base ? base : "NULL");
3114 goto out;
3117 assert(bdrv_get_aio_context(base_bs) == aio_context);
3119 if (bdrv_op_is_blocked(base_bs, BLOCK_OP_TYPE_COMMIT_TARGET, errp)) {
3120 goto out;
3123 /* Do not allow attempts to commit an image into itself */
3124 if (top_bs == base_bs) {
3125 error_setg(errp, "cannot commit an image into itself");
3126 goto out;
3129 if (top_bs == bs) {
3130 if (has_backing_file) {
3131 error_setg(errp, "'backing-file' specified,"
3132 " but 'top' is the active layer");
3133 goto out;
3135 commit_active_start(has_job_id ? job_id : NULL, bs, base_bs, speed,
3136 on_error, block_job_cb, bs, &local_err, false);
3137 } else {
3138 commit_start(has_job_id ? job_id : NULL, bs, base_bs, top_bs, speed,
3139 on_error, block_job_cb, bs,
3140 has_backing_file ? backing_file : NULL, &local_err);
3142 if (local_err != NULL) {
3143 error_propagate(errp, local_err);
3144 goto out;
3147 out:
3148 aio_context_release(aio_context);
3151 static void do_drive_backup(DriveBackup *backup, BlockJobTxn *txn, Error **errp)
3153 BlockDriverState *bs;
3154 BlockDriverState *target_bs;
3155 BlockDriverState *source = NULL;
3156 BdrvDirtyBitmap *bmap = NULL;
3157 AioContext *aio_context;
3158 QDict *options = NULL;
3159 Error *local_err = NULL;
3160 int flags;
3161 int64_t size;
3163 if (!backup->has_speed) {
3164 backup->speed = 0;
3166 if (!backup->has_on_source_error) {
3167 backup->on_source_error = BLOCKDEV_ON_ERROR_REPORT;
3169 if (!backup->has_on_target_error) {
3170 backup->on_target_error = BLOCKDEV_ON_ERROR_REPORT;
3172 if (!backup->has_mode) {
3173 backup->mode = NEW_IMAGE_MODE_ABSOLUTE_PATHS;
3175 if (!backup->has_job_id) {
3176 backup->job_id = NULL;
3178 if (!backup->has_compress) {
3179 backup->compress = false;
3182 bs = qmp_get_root_bs(backup->device, errp);
3183 if (!bs) {
3184 return;
3187 aio_context = bdrv_get_aio_context(bs);
3188 aio_context_acquire(aio_context);
3190 if (!backup->has_format) {
3191 backup->format = backup->mode == NEW_IMAGE_MODE_EXISTING ?
3192 NULL : (char*) bs->drv->format_name;
3195 /* Early check to avoid creating target */
3196 if (bdrv_op_is_blocked(bs, BLOCK_OP_TYPE_BACKUP_SOURCE, errp)) {
3197 goto out;
3200 flags = bs->open_flags | BDRV_O_RDWR;
3202 /* See if we have a backing HD we can use to create our new image
3203 * on top of. */
3204 if (backup->sync == MIRROR_SYNC_MODE_TOP) {
3205 source = backing_bs(bs);
3206 if (!source) {
3207 backup->sync = MIRROR_SYNC_MODE_FULL;
3210 if (backup->sync == MIRROR_SYNC_MODE_NONE) {
3211 source = bs;
3214 size = bdrv_getlength(bs);
3215 if (size < 0) {
3216 error_setg_errno(errp, -size, "bdrv_getlength failed");
3217 goto out;
3220 if (backup->mode != NEW_IMAGE_MODE_EXISTING) {
3221 assert(backup->format);
3222 if (source) {
3223 bdrv_img_create(backup->target, backup->format, source->filename,
3224 source->drv->format_name, NULL,
3225 size, flags, &local_err, false);
3226 } else {
3227 bdrv_img_create(backup->target, backup->format, NULL, NULL, NULL,
3228 size, flags, &local_err, false);
3232 if (local_err) {
3233 error_propagate(errp, local_err);
3234 goto out;
3237 if (backup->format) {
3238 options = qdict_new();
3239 qdict_put(options, "driver", qstring_from_str(backup->format));
3242 target_bs = bdrv_open(backup->target, NULL, options, flags, errp);
3243 if (!target_bs) {
3244 goto out;
3247 bdrv_set_aio_context(target_bs, aio_context);
3249 if (backup->has_bitmap) {
3250 bmap = bdrv_find_dirty_bitmap(bs, backup->bitmap);
3251 if (!bmap) {
3252 error_setg(errp, "Bitmap '%s' could not be found", backup->bitmap);
3253 bdrv_unref(target_bs);
3254 goto out;
3258 backup_start(backup->job_id, bs, target_bs, backup->speed, backup->sync,
3259 bmap, backup->compress, backup->on_source_error,
3260 backup->on_target_error, block_job_cb, bs, txn, &local_err);
3261 bdrv_unref(target_bs);
3262 if (local_err != NULL) {
3263 error_propagate(errp, local_err);
3264 goto out;
3267 out:
3268 aio_context_release(aio_context);
3271 void qmp_drive_backup(DriveBackup *arg, Error **errp)
3273 return do_drive_backup(arg, NULL, errp);
3276 BlockDeviceInfoList *qmp_query_named_block_nodes(Error **errp)
3278 return bdrv_named_nodes_list(errp);
3281 void do_blockdev_backup(BlockdevBackup *backup, BlockJobTxn *txn, Error **errp)
3283 BlockDriverState *bs;
3284 BlockDriverState *target_bs;
3285 Error *local_err = NULL;
3286 AioContext *aio_context;
3288 if (!backup->has_speed) {
3289 backup->speed = 0;
3291 if (!backup->has_on_source_error) {
3292 backup->on_source_error = BLOCKDEV_ON_ERROR_REPORT;
3294 if (!backup->has_on_target_error) {
3295 backup->on_target_error = BLOCKDEV_ON_ERROR_REPORT;
3297 if (!backup->has_job_id) {
3298 backup->job_id = NULL;
3300 if (!backup->has_compress) {
3301 backup->compress = false;
3304 bs = qmp_get_root_bs(backup->device, errp);
3305 if (!bs) {
3306 return;
3309 aio_context = bdrv_get_aio_context(bs);
3310 aio_context_acquire(aio_context);
3312 target_bs = bdrv_lookup_bs(backup->target, backup->target, errp);
3313 if (!target_bs) {
3314 goto out;
3317 if (bdrv_get_aio_context(target_bs) != aio_context) {
3318 if (!bdrv_has_blk(target_bs)) {
3319 /* The target BDS is not attached, we can safely move it to another
3320 * AioContext. */
3321 bdrv_set_aio_context(target_bs, aio_context);
3322 } else {
3323 error_setg(errp, "Target is attached to a different thread from "
3324 "source.");
3325 goto out;
3328 backup_start(backup->job_id, bs, target_bs, backup->speed, backup->sync,
3329 NULL, backup->compress, backup->on_source_error,
3330 backup->on_target_error, block_job_cb, bs, txn, &local_err);
3331 if (local_err != NULL) {
3332 error_propagate(errp, local_err);
3334 out:
3335 aio_context_release(aio_context);
3338 void qmp_blockdev_backup(BlockdevBackup *arg, Error **errp)
3340 do_blockdev_backup(arg, NULL, errp);
3343 /* Parameter check and block job starting for drive mirroring.
3344 * Caller should hold @device and @target's aio context (must be the same).
3346 static void blockdev_mirror_common(const char *job_id, BlockDriverState *bs,
3347 BlockDriverState *target,
3348 bool has_replaces, const char *replaces,
3349 enum MirrorSyncMode sync,
3350 BlockMirrorBackingMode backing_mode,
3351 bool has_speed, int64_t speed,
3352 bool has_granularity, uint32_t granularity,
3353 bool has_buf_size, int64_t buf_size,
3354 bool has_on_source_error,
3355 BlockdevOnError on_source_error,
3356 bool has_on_target_error,
3357 BlockdevOnError on_target_error,
3358 bool has_unmap, bool unmap,
3359 Error **errp)
3362 if (!has_speed) {
3363 speed = 0;
3365 if (!has_on_source_error) {
3366 on_source_error = BLOCKDEV_ON_ERROR_REPORT;
3368 if (!has_on_target_error) {
3369 on_target_error = BLOCKDEV_ON_ERROR_REPORT;
3371 if (!has_granularity) {
3372 granularity = 0;
3374 if (!has_buf_size) {
3375 buf_size = 0;
3377 if (!has_unmap) {
3378 unmap = true;
3381 if (granularity != 0 && (granularity < 512 || granularity > 1048576 * 64)) {
3382 error_setg(errp, QERR_INVALID_PARAMETER_VALUE, "granularity",
3383 "a value in range [512B, 64MB]");
3384 return;
3386 if (granularity & (granularity - 1)) {
3387 error_setg(errp, QERR_INVALID_PARAMETER_VALUE, "granularity",
3388 "power of 2");
3389 return;
3392 if (bdrv_op_is_blocked(bs, BLOCK_OP_TYPE_MIRROR_SOURCE, errp)) {
3393 return;
3395 if (bdrv_op_is_blocked(target, BLOCK_OP_TYPE_MIRROR_TARGET, errp)) {
3396 return;
3399 if (!bs->backing && sync == MIRROR_SYNC_MODE_TOP) {
3400 sync = MIRROR_SYNC_MODE_FULL;
3403 /* pass the node name to replace to mirror start since it's loose coupling
3404 * and will allow to check whether the node still exist at mirror completion
3406 mirror_start(job_id, bs, target,
3407 has_replaces ? replaces : NULL,
3408 speed, granularity, buf_size, sync, backing_mode,
3409 on_source_error, on_target_error, unmap,
3410 block_job_cb, bs, errp);
3413 void qmp_drive_mirror(DriveMirror *arg, Error **errp)
3415 BlockDriverState *bs;
3416 BlockDriverState *source, *target_bs;
3417 AioContext *aio_context;
3418 BlockMirrorBackingMode backing_mode;
3419 Error *local_err = NULL;
3420 QDict *options = NULL;
3421 int flags;
3422 int64_t size;
3423 const char *format = arg->format;
3425 bs = qmp_get_root_bs(arg->device, errp);
3426 if (!bs) {
3427 return;
3430 aio_context = bdrv_get_aio_context(bs);
3431 aio_context_acquire(aio_context);
3433 if (!arg->has_mode) {
3434 arg->mode = NEW_IMAGE_MODE_ABSOLUTE_PATHS;
3437 if (!arg->has_format) {
3438 format = (arg->mode == NEW_IMAGE_MODE_EXISTING
3439 ? NULL : bs->drv->format_name);
3442 flags = bs->open_flags | BDRV_O_RDWR;
3443 source = backing_bs(bs);
3444 if (!source && arg->sync == MIRROR_SYNC_MODE_TOP) {
3445 arg->sync = MIRROR_SYNC_MODE_FULL;
3447 if (arg->sync == MIRROR_SYNC_MODE_NONE) {
3448 source = bs;
3451 size = bdrv_getlength(bs);
3452 if (size < 0) {
3453 error_setg_errno(errp, -size, "bdrv_getlength failed");
3454 goto out;
3457 if (arg->has_replaces) {
3458 BlockDriverState *to_replace_bs;
3459 AioContext *replace_aio_context;
3460 int64_t replace_size;
3462 if (!arg->has_node_name) {
3463 error_setg(errp, "a node-name must be provided when replacing a"
3464 " named node of the graph");
3465 goto out;
3468 to_replace_bs = check_to_replace_node(bs, arg->replaces, &local_err);
3470 if (!to_replace_bs) {
3471 error_propagate(errp, local_err);
3472 goto out;
3475 replace_aio_context = bdrv_get_aio_context(to_replace_bs);
3476 aio_context_acquire(replace_aio_context);
3477 replace_size = bdrv_getlength(to_replace_bs);
3478 aio_context_release(replace_aio_context);
3480 if (size != replace_size) {
3481 error_setg(errp, "cannot replace image with a mirror image of "
3482 "different size");
3483 goto out;
3487 if (arg->mode == NEW_IMAGE_MODE_ABSOLUTE_PATHS) {
3488 backing_mode = MIRROR_SOURCE_BACKING_CHAIN;
3489 } else {
3490 backing_mode = MIRROR_OPEN_BACKING_CHAIN;
3493 if ((arg->sync == MIRROR_SYNC_MODE_FULL || !source)
3494 && arg->mode != NEW_IMAGE_MODE_EXISTING)
3496 /* create new image w/o backing file */
3497 assert(format);
3498 bdrv_img_create(arg->target, format,
3499 NULL, NULL, NULL, size, flags, &local_err, false);
3500 } else {
3501 switch (arg->mode) {
3502 case NEW_IMAGE_MODE_EXISTING:
3503 break;
3504 case NEW_IMAGE_MODE_ABSOLUTE_PATHS:
3505 /* create new image with backing file */
3506 bdrv_img_create(arg->target, format,
3507 source->filename,
3508 source->drv->format_name,
3509 NULL, size, flags, &local_err, false);
3510 break;
3511 default:
3512 abort();
3516 if (local_err) {
3517 error_propagate(errp, local_err);
3518 goto out;
3521 options = qdict_new();
3522 if (arg->has_node_name) {
3523 qdict_put(options, "node-name", qstring_from_str(arg->node_name));
3525 if (format) {
3526 qdict_put(options, "driver", qstring_from_str(format));
3529 /* Mirroring takes care of copy-on-write using the source's backing
3530 * file.
3532 target_bs = bdrv_open(arg->target, NULL, options,
3533 flags | BDRV_O_NO_BACKING, errp);
3534 if (!target_bs) {
3535 goto out;
3538 bdrv_set_aio_context(target_bs, aio_context);
3540 blockdev_mirror_common(arg->has_job_id ? arg->job_id : NULL, bs, target_bs,
3541 arg->has_replaces, arg->replaces, arg->sync,
3542 backing_mode, arg->has_speed, arg->speed,
3543 arg->has_granularity, arg->granularity,
3544 arg->has_buf_size, arg->buf_size,
3545 arg->has_on_source_error, arg->on_source_error,
3546 arg->has_on_target_error, arg->on_target_error,
3547 arg->has_unmap, arg->unmap,
3548 &local_err);
3549 bdrv_unref(target_bs);
3550 error_propagate(errp, local_err);
3551 out:
3552 aio_context_release(aio_context);
3555 void qmp_blockdev_mirror(bool has_job_id, const char *job_id,
3556 const char *device, const char *target,
3557 bool has_replaces, const char *replaces,
3558 MirrorSyncMode sync,
3559 bool has_speed, int64_t speed,
3560 bool has_granularity, uint32_t granularity,
3561 bool has_buf_size, int64_t buf_size,
3562 bool has_on_source_error,
3563 BlockdevOnError on_source_error,
3564 bool has_on_target_error,
3565 BlockdevOnError on_target_error,
3566 Error **errp)
3568 BlockDriverState *bs;
3569 BlockDriverState *target_bs;
3570 AioContext *aio_context;
3571 BlockMirrorBackingMode backing_mode = MIRROR_LEAVE_BACKING_CHAIN;
3572 Error *local_err = NULL;
3574 bs = qmp_get_root_bs(device, errp);
3575 if (!bs) {
3576 return;
3579 target_bs = bdrv_lookup_bs(target, target, errp);
3580 if (!target_bs) {
3581 return;
3584 aio_context = bdrv_get_aio_context(bs);
3585 aio_context_acquire(aio_context);
3587 bdrv_set_aio_context(target_bs, aio_context);
3589 blockdev_mirror_common(has_job_id ? job_id : NULL, bs, target_bs,
3590 has_replaces, replaces, sync, backing_mode,
3591 has_speed, speed,
3592 has_granularity, granularity,
3593 has_buf_size, buf_size,
3594 has_on_source_error, on_source_error,
3595 has_on_target_error, on_target_error,
3596 true, true,
3597 &local_err);
3598 error_propagate(errp, local_err);
3600 aio_context_release(aio_context);
3603 /* Get a block job using its ID and acquire its AioContext */
3604 static BlockJob *find_block_job(const char *id, AioContext **aio_context,
3605 Error **errp)
3607 BlockJob *job;
3609 assert(id != NULL);
3611 *aio_context = NULL;
3613 job = block_job_get(id);
3615 if (!job) {
3616 error_set(errp, ERROR_CLASS_DEVICE_NOT_ACTIVE,
3617 "Block job '%s' not found", id);
3618 return NULL;
3621 *aio_context = blk_get_aio_context(job->blk);
3622 aio_context_acquire(*aio_context);
3624 return job;
3627 void qmp_block_job_set_speed(const char *device, int64_t speed, Error **errp)
3629 AioContext *aio_context;
3630 BlockJob *job = find_block_job(device, &aio_context, errp);
3632 if (!job) {
3633 return;
3636 block_job_set_speed(job, speed, errp);
3637 aio_context_release(aio_context);
3640 void qmp_block_job_cancel(const char *device,
3641 bool has_force, bool force, Error **errp)
3643 AioContext *aio_context;
3644 BlockJob *job = find_block_job(device, &aio_context, errp);
3646 if (!job) {
3647 return;
3650 if (!has_force) {
3651 force = false;
3654 if (job->user_paused && !force) {
3655 error_setg(errp, "The block job for device '%s' is currently paused",
3656 device);
3657 goto out;
3660 trace_qmp_block_job_cancel(job);
3661 block_job_cancel(job);
3662 out:
3663 aio_context_release(aio_context);
3666 void qmp_block_job_pause(const char *device, Error **errp)
3668 AioContext *aio_context;
3669 BlockJob *job = find_block_job(device, &aio_context, errp);
3671 if (!job || job->user_paused) {
3672 return;
3675 job->user_paused = true;
3676 trace_qmp_block_job_pause(job);
3677 block_job_pause(job);
3678 aio_context_release(aio_context);
3681 void qmp_block_job_resume(const char *device, Error **errp)
3683 AioContext *aio_context;
3684 BlockJob *job = find_block_job(device, &aio_context, errp);
3686 if (!job || !job->user_paused) {
3687 return;
3690 job->user_paused = false;
3691 trace_qmp_block_job_resume(job);
3692 block_job_iostatus_reset(job);
3693 block_job_resume(job);
3694 aio_context_release(aio_context);
3697 void qmp_block_job_complete(const char *device, Error **errp)
3699 AioContext *aio_context;
3700 BlockJob *job = find_block_job(device, &aio_context, errp);
3702 if (!job) {
3703 return;
3706 trace_qmp_block_job_complete(job);
3707 block_job_complete(job, errp);
3708 aio_context_release(aio_context);
3711 void qmp_change_backing_file(const char *device,
3712 const char *image_node_name,
3713 const char *backing_file,
3714 Error **errp)
3716 BlockDriverState *bs = NULL;
3717 AioContext *aio_context;
3718 BlockDriverState *image_bs = NULL;
3719 Error *local_err = NULL;
3720 bool ro;
3721 int open_flags;
3722 int ret;
3724 bs = qmp_get_root_bs(device, errp);
3725 if (!bs) {
3726 return;
3729 aio_context = bdrv_get_aio_context(bs);
3730 aio_context_acquire(aio_context);
3732 image_bs = bdrv_lookup_bs(NULL, image_node_name, &local_err);
3733 if (local_err) {
3734 error_propagate(errp, local_err);
3735 goto out;
3738 if (!image_bs) {
3739 error_setg(errp, "image file not found");
3740 goto out;
3743 if (bdrv_find_base(image_bs) == image_bs) {
3744 error_setg(errp, "not allowing backing file change on an image "
3745 "without a backing file");
3746 goto out;
3749 /* even though we are not necessarily operating on bs, we need it to
3750 * determine if block ops are currently prohibited on the chain */
3751 if (bdrv_op_is_blocked(bs, BLOCK_OP_TYPE_CHANGE, errp)) {
3752 goto out;
3755 /* final sanity check */
3756 if (!bdrv_chain_contains(bs, image_bs)) {
3757 error_setg(errp, "'%s' and image file are not in the same chain",
3758 device);
3759 goto out;
3762 /* if not r/w, reopen to make r/w */
3763 open_flags = image_bs->open_flags;
3764 ro = bdrv_is_read_only(image_bs);
3766 if (ro) {
3767 bdrv_reopen(image_bs, open_flags | BDRV_O_RDWR, &local_err);
3768 if (local_err) {
3769 error_propagate(errp, local_err);
3770 goto out;
3774 ret = bdrv_change_backing_file(image_bs, backing_file,
3775 image_bs->drv ? image_bs->drv->format_name : "");
3777 if (ret < 0) {
3778 error_setg_errno(errp, -ret, "Could not change backing file to '%s'",
3779 backing_file);
3780 /* don't exit here, so we can try to restore open flags if
3781 * appropriate */
3784 if (ro) {
3785 bdrv_reopen(image_bs, open_flags, &local_err);
3786 error_propagate(errp, local_err);
3789 out:
3790 aio_context_release(aio_context);
3793 void hmp_drive_add_node(Monitor *mon, const char *optstr)
3795 QemuOpts *opts;
3796 QDict *qdict;
3797 Error *local_err = NULL;
3799 opts = qemu_opts_parse_noisily(&qemu_drive_opts, optstr, false);
3800 if (!opts) {
3801 return;
3804 qdict = qemu_opts_to_qdict(opts, NULL);
3806 if (!qdict_get_try_str(qdict, "node-name")) {
3807 QDECREF(qdict);
3808 error_report("'node-name' needs to be specified");
3809 goto out;
3812 BlockDriverState *bs = bds_tree_init(qdict, &local_err);
3813 if (!bs) {
3814 error_report_err(local_err);
3815 goto out;
3818 QTAILQ_INSERT_TAIL(&monitor_bdrv_states, bs, monitor_list);
3820 out:
3821 qemu_opts_del(opts);
3824 void qmp_blockdev_add(BlockdevOptions *options, Error **errp)
3826 BlockDriverState *bs;
3827 QObject *obj;
3828 Visitor *v = qmp_output_visitor_new(&obj);
3829 QDict *qdict;
3830 Error *local_err = NULL;
3832 visit_type_BlockdevOptions(v, NULL, &options, &local_err);
3833 if (local_err) {
3834 error_propagate(errp, local_err);
3835 goto fail;
3838 visit_complete(v, &obj);
3839 qdict = qobject_to_qdict(obj);
3841 qdict_flatten(qdict);
3843 if (!qdict_get_try_str(qdict, "node-name")) {
3844 error_setg(errp, "'node-name' must be specified for the root node");
3845 goto fail;
3848 bs = bds_tree_init(qdict, errp);
3849 if (!bs) {
3850 goto fail;
3853 QTAILQ_INSERT_TAIL(&monitor_bdrv_states, bs, monitor_list);
3855 if (bs && bdrv_key_required(bs)) {
3856 QTAILQ_REMOVE(&monitor_bdrv_states, bs, monitor_list);
3857 bdrv_unref(bs);
3858 error_setg(errp, "blockdev-add doesn't support encrypted devices");
3859 goto fail;
3862 fail:
3863 visit_free(v);
3866 void qmp_x_blockdev_del(const char *node_name, Error **errp)
3868 AioContext *aio_context;
3869 BlockDriverState *bs;
3871 bs = bdrv_find_node(node_name);
3872 if (!bs) {
3873 error_setg(errp, "Cannot find node %s", node_name);
3874 return;
3876 if (bdrv_has_blk(bs)) {
3877 error_setg(errp, "Node %s is in use", node_name);
3878 return;
3880 aio_context = bdrv_get_aio_context(bs);
3881 aio_context_acquire(aio_context);
3883 if (bdrv_op_is_blocked(bs, BLOCK_OP_TYPE_DRIVE_DEL, errp)) {
3884 goto out;
3887 if (!bs->monitor_list.tqe_prev) {
3888 error_setg(errp, "Node %s is not owned by the monitor",
3889 bs->node_name);
3890 goto out;
3893 if (bs->refcnt > 1) {
3894 error_setg(errp, "Block device %s is in use",
3895 bdrv_get_device_or_node_name(bs));
3896 goto out;
3899 QTAILQ_REMOVE(&monitor_bdrv_states, bs, monitor_list);
3900 bdrv_unref(bs);
3902 out:
3903 aio_context_release(aio_context);
3906 static BdrvChild *bdrv_find_child(BlockDriverState *parent_bs,
3907 const char *child_name)
3909 BdrvChild *child;
3911 QLIST_FOREACH(child, &parent_bs->children, next) {
3912 if (strcmp(child->name, child_name) == 0) {
3913 return child;
3917 return NULL;
3920 void qmp_x_blockdev_change(const char *parent, bool has_child,
3921 const char *child, bool has_node,
3922 const char *node, Error **errp)
3924 BlockDriverState *parent_bs, *new_bs = NULL;
3925 BdrvChild *p_child;
3927 parent_bs = bdrv_lookup_bs(parent, parent, errp);
3928 if (!parent_bs) {
3929 return;
3932 if (has_child == has_node) {
3933 if (has_child) {
3934 error_setg(errp, "The parameters child and node are in conflict");
3935 } else {
3936 error_setg(errp, "Either child or node must be specified");
3938 return;
3941 if (has_child) {
3942 p_child = bdrv_find_child(parent_bs, child);
3943 if (!p_child) {
3944 error_setg(errp, "Node '%s' does not have child '%s'",
3945 parent, child);
3946 return;
3948 bdrv_del_child(parent_bs, p_child, errp);
3951 if (has_node) {
3952 new_bs = bdrv_find_node(node);
3953 if (!new_bs) {
3954 error_setg(errp, "Node '%s' not found", node);
3955 return;
3957 bdrv_add_child(parent_bs, new_bs, errp);
3961 BlockJobInfoList *qmp_query_block_jobs(Error **errp)
3963 BlockJobInfoList *head = NULL, **p_next = &head;
3964 BlockJob *job;
3966 for (job = block_job_next(NULL); job; job = block_job_next(job)) {
3967 BlockJobInfoList *elem = g_new0(BlockJobInfoList, 1);
3968 AioContext *aio_context = blk_get_aio_context(job->blk);
3970 aio_context_acquire(aio_context);
3971 elem->value = block_job_query(job);
3972 aio_context_release(aio_context);
3974 *p_next = elem;
3975 p_next = &elem->next;
3978 return head;
3981 QemuOptsList qemu_common_drive_opts = {
3982 .name = "drive",
3983 .head = QTAILQ_HEAD_INITIALIZER(qemu_common_drive_opts.head),
3984 .desc = {
3986 .name = "snapshot",
3987 .type = QEMU_OPT_BOOL,
3988 .help = "enable/disable snapshot mode",
3990 .name = "discard",
3991 .type = QEMU_OPT_STRING,
3992 .help = "discard operation (ignore/off, unmap/on)",
3994 .name = "aio",
3995 .type = QEMU_OPT_STRING,
3996 .help = "host AIO implementation (threads, native)",
3998 .name = BDRV_OPT_CACHE_WB,
3999 .type = QEMU_OPT_BOOL,
4000 .help = "Enable writeback mode",
4002 .name = "format",
4003 .type = QEMU_OPT_STRING,
4004 .help = "disk format (raw, qcow2, ...)",
4006 .name = "rerror",
4007 .type = QEMU_OPT_STRING,
4008 .help = "read error action",
4010 .name = "werror",
4011 .type = QEMU_OPT_STRING,
4012 .help = "write error action",
4014 .name = BDRV_OPT_READ_ONLY,
4015 .type = QEMU_OPT_BOOL,
4016 .help = "open drive file as read-only",
4018 .name = "throttling.iops-total",
4019 .type = QEMU_OPT_NUMBER,
4020 .help = "limit total I/O operations per second",
4022 .name = "throttling.iops-read",
4023 .type = QEMU_OPT_NUMBER,
4024 .help = "limit read operations per second",
4026 .name = "throttling.iops-write",
4027 .type = QEMU_OPT_NUMBER,
4028 .help = "limit write operations per second",
4030 .name = "throttling.bps-total",
4031 .type = QEMU_OPT_NUMBER,
4032 .help = "limit total bytes per second",
4034 .name = "throttling.bps-read",
4035 .type = QEMU_OPT_NUMBER,
4036 .help = "limit read bytes per second",
4038 .name = "throttling.bps-write",
4039 .type = QEMU_OPT_NUMBER,
4040 .help = "limit write bytes per second",
4042 .name = "throttling.iops-total-max",
4043 .type = QEMU_OPT_NUMBER,
4044 .help = "I/O operations burst",
4046 .name = "throttling.iops-read-max",
4047 .type = QEMU_OPT_NUMBER,
4048 .help = "I/O operations read burst",
4050 .name = "throttling.iops-write-max",
4051 .type = QEMU_OPT_NUMBER,
4052 .help = "I/O operations write burst",
4054 .name = "throttling.bps-total-max",
4055 .type = QEMU_OPT_NUMBER,
4056 .help = "total bytes burst",
4058 .name = "throttling.bps-read-max",
4059 .type = QEMU_OPT_NUMBER,
4060 .help = "total bytes read burst",
4062 .name = "throttling.bps-write-max",
4063 .type = QEMU_OPT_NUMBER,
4064 .help = "total bytes write burst",
4066 .name = "throttling.iops-total-max-length",
4067 .type = QEMU_OPT_NUMBER,
4068 .help = "length of the iops-total-max burst period, in seconds",
4070 .name = "throttling.iops-read-max-length",
4071 .type = QEMU_OPT_NUMBER,
4072 .help = "length of the iops-read-max burst period, in seconds",
4074 .name = "throttling.iops-write-max-length",
4075 .type = QEMU_OPT_NUMBER,
4076 .help = "length of the iops-write-max burst period, in seconds",
4078 .name = "throttling.bps-total-max-length",
4079 .type = QEMU_OPT_NUMBER,
4080 .help = "length of the bps-total-max burst period, in seconds",
4082 .name = "throttling.bps-read-max-length",
4083 .type = QEMU_OPT_NUMBER,
4084 .help = "length of the bps-read-max burst period, in seconds",
4086 .name = "throttling.bps-write-max-length",
4087 .type = QEMU_OPT_NUMBER,
4088 .help = "length of the bps-write-max burst period, in seconds",
4090 .name = "throttling.iops-size",
4091 .type = QEMU_OPT_NUMBER,
4092 .help = "when limiting by iops max size of an I/O in bytes",
4094 .name = "throttling.group",
4095 .type = QEMU_OPT_STRING,
4096 .help = "name of the block throttling group",
4098 .name = "copy-on-read",
4099 .type = QEMU_OPT_BOOL,
4100 .help = "copy read data from backing file into image file",
4102 .name = "detect-zeroes",
4103 .type = QEMU_OPT_STRING,
4104 .help = "try to optimize zero writes (off, on, unmap)",
4106 .name = "stats-account-invalid",
4107 .type = QEMU_OPT_BOOL,
4108 .help = "whether to account for invalid I/O operations "
4109 "in the statistics",
4111 .name = "stats-account-failed",
4112 .type = QEMU_OPT_BOOL,
4113 .help = "whether to account for failed I/O operations "
4114 "in the statistics",
4116 { /* end of list */ }
4120 static QemuOptsList qemu_root_bds_opts = {
4121 .name = "root-bds",
4122 .head = QTAILQ_HEAD_INITIALIZER(qemu_root_bds_opts.head),
4123 .desc = {
4125 .name = "discard",
4126 .type = QEMU_OPT_STRING,
4127 .help = "discard operation (ignore/off, unmap/on)",
4129 .name = "aio",
4130 .type = QEMU_OPT_STRING,
4131 .help = "host AIO implementation (threads, native)",
4133 .name = "copy-on-read",
4134 .type = QEMU_OPT_BOOL,
4135 .help = "copy read data from backing file into image file",
4137 { /* end of list */ }
4141 QemuOptsList qemu_drive_opts = {
4142 .name = "drive",
4143 .head = QTAILQ_HEAD_INITIALIZER(qemu_drive_opts.head),
4144 .desc = {
4146 * no elements => accept any params
4147 * validation will happen later
4149 { /* end of list */ }