vvfat: Switch to .bdrv_co_block_status()
[qemu/ericb.git] / blockdev.c
blob3fb1ca803c58653dee99bb4a0fed97380c4f88f9
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/qdict.h"
44 #include "qapi/qmp/qnum.h"
45 #include "qapi/qmp/qstring.h"
46 #include "qapi-visit.h"
47 #include "qapi/error.h"
48 #include "qapi/qmp/qerror.h"
49 #include "qapi/qmp/qlist.h"
50 #include "qapi/qobject-output-visitor.h"
51 #include "sysemu/sysemu.h"
52 #include "sysemu/iothread.h"
53 #include "block/block_int.h"
54 #include "qmp-commands.h"
55 #include "block/trace.h"
56 #include "sysemu/arch_init.h"
57 #include "sysemu/qtest.h"
58 #include "qemu/cutils.h"
59 #include "qemu/help_option.h"
60 #include "qemu/throttle-options.h"
62 static QTAILQ_HEAD(, BlockDriverState) monitor_bdrv_states =
63 QTAILQ_HEAD_INITIALIZER(monitor_bdrv_states);
65 static int do_open_tray(const char *blk_name, const char *qdev_id,
66 bool force, Error **errp);
67 static void blockdev_remove_medium(bool has_device, const char *device,
68 bool has_id, const char *id, Error **errp);
69 static void blockdev_insert_medium(bool has_device, const char *device,
70 bool has_id, const char *id,
71 const char *node_name, Error **errp);
73 static const char *const if_name[IF_COUNT] = {
74 [IF_NONE] = "none",
75 [IF_IDE] = "ide",
76 [IF_SCSI] = "scsi",
77 [IF_FLOPPY] = "floppy",
78 [IF_PFLASH] = "pflash",
79 [IF_MTD] = "mtd",
80 [IF_SD] = "sd",
81 [IF_VIRTIO] = "virtio",
82 [IF_XEN] = "xen",
85 static int if_max_devs[IF_COUNT] = {
87 * Do not change these numbers! They govern how drive option
88 * index maps to unit and bus. That mapping is ABI.
90 * All controllers used to implement if=T drives need to support
91 * if_max_devs[T] units, for any T with if_max_devs[T] != 0.
92 * Otherwise, some index values map to "impossible" bus, unit
93 * values.
95 * For instance, if you change [IF_SCSI] to 255, -drive
96 * if=scsi,index=12 no longer means bus=1,unit=5, but
97 * bus=0,unit=12. With an lsi53c895a controller (7 units max),
98 * the drive can't be set up. Regression.
100 [IF_IDE] = 2,
101 [IF_SCSI] = 7,
105 * Boards may call this to offer board-by-board overrides
106 * of the default, global values.
108 void override_max_devs(BlockInterfaceType type, int max_devs)
110 BlockBackend *blk;
111 DriveInfo *dinfo;
113 if (max_devs <= 0) {
114 return;
117 for (blk = blk_next(NULL); blk; blk = blk_next(blk)) {
118 dinfo = blk_legacy_dinfo(blk);
119 if (dinfo->type == type) {
120 fprintf(stderr, "Cannot override units-per-bus property of"
121 " the %s interface, because a drive of that type has"
122 " already been added.\n", if_name[type]);
123 g_assert_not_reached();
127 if_max_devs[type] = max_devs;
131 * We automatically delete the drive when a device using it gets
132 * unplugged. Questionable feature, but we can't just drop it.
133 * Device models call blockdev_mark_auto_del() to schedule the
134 * automatic deletion, and generic qdev code calls blockdev_auto_del()
135 * when deletion is actually safe.
137 void blockdev_mark_auto_del(BlockBackend *blk)
139 DriveInfo *dinfo = blk_legacy_dinfo(blk);
140 BlockDriverState *bs = blk_bs(blk);
141 AioContext *aio_context;
143 if (!dinfo) {
144 return;
147 if (bs) {
148 aio_context = bdrv_get_aio_context(bs);
149 aio_context_acquire(aio_context);
151 if (bs->job) {
152 block_job_cancel(bs->job);
155 aio_context_release(aio_context);
158 dinfo->auto_del = 1;
161 void blockdev_auto_del(BlockBackend *blk)
163 DriveInfo *dinfo = blk_legacy_dinfo(blk);
165 if (dinfo && dinfo->auto_del) {
166 monitor_remove_blk(blk);
167 blk_unref(blk);
172 * Returns the current mapping of how many units per bus
173 * a particular interface can support.
175 * A positive integer indicates n units per bus.
176 * 0 implies the mapping has not been established.
177 * -1 indicates an invalid BlockInterfaceType was given.
179 int drive_get_max_devs(BlockInterfaceType type)
181 if (type >= IF_IDE && type < IF_COUNT) {
182 return if_max_devs[type];
185 return -1;
188 static int drive_index_to_bus_id(BlockInterfaceType type, int index)
190 int max_devs = if_max_devs[type];
191 return max_devs ? index / max_devs : 0;
194 static int drive_index_to_unit_id(BlockInterfaceType type, int index)
196 int max_devs = if_max_devs[type];
197 return max_devs ? index % max_devs : index;
200 QemuOpts *drive_def(const char *optstr)
202 return qemu_opts_parse_noisily(qemu_find_opts("drive"), optstr, false);
205 QemuOpts *drive_add(BlockInterfaceType type, int index, const char *file,
206 const char *optstr)
208 QemuOpts *opts;
210 opts = drive_def(optstr);
211 if (!opts) {
212 return NULL;
214 if (type != IF_DEFAULT) {
215 qemu_opt_set(opts, "if", if_name[type], &error_abort);
217 if (index >= 0) {
218 qemu_opt_set_number(opts, "index", index, &error_abort);
220 if (file)
221 qemu_opt_set(opts, "file", file, &error_abort);
222 return opts;
225 DriveInfo *drive_get(BlockInterfaceType type, int bus, int unit)
227 BlockBackend *blk;
228 DriveInfo *dinfo;
230 for (blk = blk_next(NULL); blk; blk = blk_next(blk)) {
231 dinfo = blk_legacy_dinfo(blk);
232 if (dinfo && dinfo->type == type
233 && dinfo->bus == bus && dinfo->unit == unit) {
234 return dinfo;
238 return NULL;
241 void drive_check_orphaned(void)
243 BlockBackend *blk;
244 DriveInfo *dinfo;
245 Location loc;
246 bool orphans = false;
248 for (blk = blk_next(NULL); blk; blk = blk_next(blk)) {
249 dinfo = blk_legacy_dinfo(blk);
250 if (!blk_get_attached_dev(blk) && !dinfo->is_default &&
251 dinfo->type != IF_NONE) {
252 loc_push_none(&loc);
253 qemu_opts_loc_restore(dinfo->opts);
254 error_report("machine type does not support"
255 " if=%s,bus=%d,unit=%d",
256 if_name[dinfo->type], dinfo->bus, dinfo->unit);
257 loc_pop(&loc);
258 orphans = true;
262 if (orphans) {
263 exit(1);
267 DriveInfo *drive_get_by_index(BlockInterfaceType type, int index)
269 return drive_get(type,
270 drive_index_to_bus_id(type, index),
271 drive_index_to_unit_id(type, index));
274 int drive_get_max_bus(BlockInterfaceType type)
276 int max_bus;
277 BlockBackend *blk;
278 DriveInfo *dinfo;
280 max_bus = -1;
281 for (blk = blk_next(NULL); blk; blk = blk_next(blk)) {
282 dinfo = blk_legacy_dinfo(blk);
283 if (dinfo && dinfo->type == type && dinfo->bus > max_bus) {
284 max_bus = dinfo->bus;
287 return max_bus;
290 /* Get a block device. This should only be used for single-drive devices
291 (e.g. SD/Floppy/MTD). Multi-disk devices (scsi/ide) should use the
292 appropriate bus. */
293 DriveInfo *drive_get_next(BlockInterfaceType type)
295 static int next_block_unit[IF_COUNT];
297 return drive_get(type, 0, next_block_unit[type]++);
300 static void bdrv_format_print(void *opaque, const char *name)
302 error_printf(" %s", name);
305 typedef struct {
306 QEMUBH *bh;
307 BlockDriverState *bs;
308 } BDRVPutRefBH;
310 static int parse_block_error_action(const char *buf, bool is_read, Error **errp)
312 if (!strcmp(buf, "ignore")) {
313 return BLOCKDEV_ON_ERROR_IGNORE;
314 } else if (!is_read && !strcmp(buf, "enospc")) {
315 return BLOCKDEV_ON_ERROR_ENOSPC;
316 } else if (!strcmp(buf, "stop")) {
317 return BLOCKDEV_ON_ERROR_STOP;
318 } else if (!strcmp(buf, "report")) {
319 return BLOCKDEV_ON_ERROR_REPORT;
320 } else {
321 error_setg(errp, "'%s' invalid %s error action",
322 buf, is_read ? "read" : "write");
323 return -1;
327 static bool parse_stats_intervals(BlockAcctStats *stats, QList *intervals,
328 Error **errp)
330 const QListEntry *entry;
331 for (entry = qlist_first(intervals); entry; entry = qlist_next(entry)) {
332 switch (qobject_type(entry->value)) {
334 case QTYPE_QSTRING: {
335 unsigned long long length;
336 const char *str = qstring_get_str(qobject_to_qstring(entry->value));
337 if (parse_uint_full(str, &length, 10) == 0 &&
338 length > 0 && length <= UINT_MAX) {
339 block_acct_add_interval(stats, (unsigned) length);
340 } else {
341 error_setg(errp, "Invalid interval length: %s", str);
342 return false;
344 break;
347 case QTYPE_QNUM: {
348 int64_t length = qnum_get_int(qobject_to_qnum(entry->value));
350 if (length > 0 && length <= UINT_MAX) {
351 block_acct_add_interval(stats, (unsigned) length);
352 } else {
353 error_setg(errp, "Invalid interval length: %" PRId64, length);
354 return false;
356 break;
359 default:
360 error_setg(errp, "The specification of stats-intervals is invalid");
361 return false;
364 return true;
367 typedef enum { MEDIA_DISK, MEDIA_CDROM } DriveMediaType;
369 /* All parameters but @opts are optional and may be set to NULL. */
370 static void extract_common_blockdev_options(QemuOpts *opts, int *bdrv_flags,
371 const char **throttling_group, ThrottleConfig *throttle_cfg,
372 BlockdevDetectZeroesOptions *detect_zeroes, Error **errp)
374 Error *local_error = NULL;
375 const char *aio;
377 if (bdrv_flags) {
378 if (qemu_opt_get_bool(opts, "copy-on-read", false)) {
379 *bdrv_flags |= BDRV_O_COPY_ON_READ;
382 if ((aio = qemu_opt_get(opts, "aio")) != NULL) {
383 if (!strcmp(aio, "native")) {
384 *bdrv_flags |= BDRV_O_NATIVE_AIO;
385 } else if (!strcmp(aio, "threads")) {
386 /* this is the default */
387 } else {
388 error_setg(errp, "invalid aio option");
389 return;
394 /* disk I/O throttling */
395 if (throttling_group) {
396 *throttling_group = qemu_opt_get(opts, "throttling.group");
399 if (throttle_cfg) {
400 throttle_config_init(throttle_cfg);
401 throttle_cfg->buckets[THROTTLE_BPS_TOTAL].avg =
402 qemu_opt_get_number(opts, "throttling.bps-total", 0);
403 throttle_cfg->buckets[THROTTLE_BPS_READ].avg =
404 qemu_opt_get_number(opts, "throttling.bps-read", 0);
405 throttle_cfg->buckets[THROTTLE_BPS_WRITE].avg =
406 qemu_opt_get_number(opts, "throttling.bps-write", 0);
407 throttle_cfg->buckets[THROTTLE_OPS_TOTAL].avg =
408 qemu_opt_get_number(opts, "throttling.iops-total", 0);
409 throttle_cfg->buckets[THROTTLE_OPS_READ].avg =
410 qemu_opt_get_number(opts, "throttling.iops-read", 0);
411 throttle_cfg->buckets[THROTTLE_OPS_WRITE].avg =
412 qemu_opt_get_number(opts, "throttling.iops-write", 0);
414 throttle_cfg->buckets[THROTTLE_BPS_TOTAL].max =
415 qemu_opt_get_number(opts, "throttling.bps-total-max", 0);
416 throttle_cfg->buckets[THROTTLE_BPS_READ].max =
417 qemu_opt_get_number(opts, "throttling.bps-read-max", 0);
418 throttle_cfg->buckets[THROTTLE_BPS_WRITE].max =
419 qemu_opt_get_number(opts, "throttling.bps-write-max", 0);
420 throttle_cfg->buckets[THROTTLE_OPS_TOTAL].max =
421 qemu_opt_get_number(opts, "throttling.iops-total-max", 0);
422 throttle_cfg->buckets[THROTTLE_OPS_READ].max =
423 qemu_opt_get_number(opts, "throttling.iops-read-max", 0);
424 throttle_cfg->buckets[THROTTLE_OPS_WRITE].max =
425 qemu_opt_get_number(opts, "throttling.iops-write-max", 0);
427 throttle_cfg->buckets[THROTTLE_BPS_TOTAL].burst_length =
428 qemu_opt_get_number(opts, "throttling.bps-total-max-length", 1);
429 throttle_cfg->buckets[THROTTLE_BPS_READ].burst_length =
430 qemu_opt_get_number(opts, "throttling.bps-read-max-length", 1);
431 throttle_cfg->buckets[THROTTLE_BPS_WRITE].burst_length =
432 qemu_opt_get_number(opts, "throttling.bps-write-max-length", 1);
433 throttle_cfg->buckets[THROTTLE_OPS_TOTAL].burst_length =
434 qemu_opt_get_number(opts, "throttling.iops-total-max-length", 1);
435 throttle_cfg->buckets[THROTTLE_OPS_READ].burst_length =
436 qemu_opt_get_number(opts, "throttling.iops-read-max-length", 1);
437 throttle_cfg->buckets[THROTTLE_OPS_WRITE].burst_length =
438 qemu_opt_get_number(opts, "throttling.iops-write-max-length", 1);
440 throttle_cfg->op_size =
441 qemu_opt_get_number(opts, "throttling.iops-size", 0);
443 if (!throttle_is_valid(throttle_cfg, errp)) {
444 return;
448 if (detect_zeroes) {
449 *detect_zeroes =
450 qapi_enum_parse(&BlockdevDetectZeroesOptions_lookup,
451 qemu_opt_get(opts, "detect-zeroes"),
452 BLOCKDEV_DETECT_ZEROES_OPTIONS_OFF,
453 &local_error);
454 if (local_error) {
455 error_propagate(errp, local_error);
456 return;
461 /* Takes the ownership of bs_opts */
462 static BlockBackend *blockdev_init(const char *file, QDict *bs_opts,
463 Error **errp)
465 const char *buf;
466 int bdrv_flags = 0;
467 int on_read_error, on_write_error;
468 bool account_invalid, account_failed;
469 bool writethrough, read_only;
470 BlockBackend *blk;
471 BlockDriverState *bs;
472 ThrottleConfig cfg;
473 int snapshot = 0;
474 Error *error = NULL;
475 QemuOpts *opts;
476 QDict *interval_dict = NULL;
477 QList *interval_list = NULL;
478 const char *id;
479 BlockdevDetectZeroesOptions detect_zeroes =
480 BLOCKDEV_DETECT_ZEROES_OPTIONS_OFF;
481 const char *throttling_group = NULL;
483 /* Check common options by copying from bs_opts to opts, all other options
484 * stay in bs_opts for processing by bdrv_open(). */
485 id = qdict_get_try_str(bs_opts, "id");
486 opts = qemu_opts_create(&qemu_common_drive_opts, id, 1, &error);
487 if (error) {
488 error_propagate(errp, error);
489 goto err_no_opts;
492 qemu_opts_absorb_qdict(opts, bs_opts, &error);
493 if (error) {
494 error_propagate(errp, error);
495 goto early_err;
498 if (id) {
499 qdict_del(bs_opts, "id");
502 /* extract parameters */
503 snapshot = qemu_opt_get_bool(opts, "snapshot", 0);
505 account_invalid = qemu_opt_get_bool(opts, "stats-account-invalid", true);
506 account_failed = qemu_opt_get_bool(opts, "stats-account-failed", true);
508 writethrough = !qemu_opt_get_bool(opts, BDRV_OPT_CACHE_WB, true);
510 id = qemu_opts_id(opts);
512 qdict_extract_subqdict(bs_opts, &interval_dict, "stats-intervals.");
513 qdict_array_split(interval_dict, &interval_list);
515 if (qdict_size(interval_dict) != 0) {
516 error_setg(errp, "Invalid option stats-intervals.%s",
517 qdict_first(interval_dict)->key);
518 goto early_err;
521 extract_common_blockdev_options(opts, &bdrv_flags, &throttling_group, &cfg,
522 &detect_zeroes, &error);
523 if (error) {
524 error_propagate(errp, error);
525 goto early_err;
528 if ((buf = qemu_opt_get(opts, "format")) != NULL) {
529 if (is_help_option(buf)) {
530 error_printf("Supported formats:");
531 bdrv_iterate_format(bdrv_format_print, NULL);
532 error_printf("\n");
533 goto early_err;
536 if (qdict_haskey(bs_opts, "driver")) {
537 error_setg(errp, "Cannot specify both 'driver' and 'format'");
538 goto early_err;
540 qdict_put_str(bs_opts, "driver", buf);
543 on_write_error = BLOCKDEV_ON_ERROR_ENOSPC;
544 if ((buf = qemu_opt_get(opts, "werror")) != NULL) {
545 on_write_error = parse_block_error_action(buf, 0, &error);
546 if (error) {
547 error_propagate(errp, error);
548 goto early_err;
552 on_read_error = BLOCKDEV_ON_ERROR_REPORT;
553 if ((buf = qemu_opt_get(opts, "rerror")) != NULL) {
554 on_read_error = parse_block_error_action(buf, 1, &error);
555 if (error) {
556 error_propagate(errp, error);
557 goto early_err;
561 if (snapshot) {
562 bdrv_flags |= BDRV_O_SNAPSHOT;
565 read_only = qemu_opt_get_bool(opts, BDRV_OPT_READ_ONLY, false);
567 /* init */
568 if ((!file || !*file) && !qdict_size(bs_opts)) {
569 BlockBackendRootState *blk_rs;
571 blk = blk_new(0, BLK_PERM_ALL);
572 blk_rs = blk_get_root_state(blk);
573 blk_rs->open_flags = bdrv_flags;
574 blk_rs->read_only = read_only;
575 blk_rs->detect_zeroes = detect_zeroes;
577 QDECREF(bs_opts);
578 } else {
579 if (file && !*file) {
580 file = NULL;
583 /* bdrv_open() defaults to the values in bdrv_flags (for compatibility
584 * with other callers) rather than what we want as the real defaults.
585 * Apply the defaults here instead. */
586 qdict_set_default_str(bs_opts, BDRV_OPT_CACHE_DIRECT, "off");
587 qdict_set_default_str(bs_opts, BDRV_OPT_CACHE_NO_FLUSH, "off");
588 qdict_set_default_str(bs_opts, BDRV_OPT_READ_ONLY,
589 read_only ? "on" : "off");
590 assert((bdrv_flags & BDRV_O_CACHE_MASK) == 0);
592 if (runstate_check(RUN_STATE_INMIGRATE)) {
593 bdrv_flags |= BDRV_O_INACTIVE;
596 blk = blk_new_open(file, NULL, bs_opts, bdrv_flags, errp);
597 if (!blk) {
598 goto err_no_bs_opts;
600 bs = blk_bs(blk);
602 bs->detect_zeroes = detect_zeroes;
604 block_acct_setup(blk_get_stats(blk), account_invalid, account_failed);
606 if (!parse_stats_intervals(blk_get_stats(blk), interval_list, errp)) {
607 blk_unref(blk);
608 blk = NULL;
609 goto err_no_bs_opts;
613 /* disk I/O throttling */
614 if (throttle_enabled(&cfg)) {
615 if (!throttling_group) {
616 throttling_group = id;
618 blk_io_limits_enable(blk, throttling_group);
619 blk_set_io_limits(blk, &cfg);
622 blk_set_enable_write_cache(blk, !writethrough);
623 blk_set_on_error(blk, on_read_error, on_write_error);
625 if (!monitor_add_blk(blk, id, errp)) {
626 blk_unref(blk);
627 blk = NULL;
628 goto err_no_bs_opts;
631 err_no_bs_opts:
632 qemu_opts_del(opts);
633 QDECREF(interval_dict);
634 QDECREF(interval_list);
635 return blk;
637 early_err:
638 qemu_opts_del(opts);
639 QDECREF(interval_dict);
640 QDECREF(interval_list);
641 err_no_opts:
642 QDECREF(bs_opts);
643 return NULL;
646 /* Takes the ownership of bs_opts */
647 static BlockDriverState *bds_tree_init(QDict *bs_opts, Error **errp)
649 int bdrv_flags = 0;
651 /* bdrv_open() defaults to the values in bdrv_flags (for compatibility
652 * with other callers) rather than what we want as the real defaults.
653 * Apply the defaults here instead. */
654 qdict_set_default_str(bs_opts, BDRV_OPT_CACHE_DIRECT, "off");
655 qdict_set_default_str(bs_opts, BDRV_OPT_CACHE_NO_FLUSH, "off");
656 qdict_set_default_str(bs_opts, BDRV_OPT_READ_ONLY, "off");
658 if (runstate_check(RUN_STATE_INMIGRATE)) {
659 bdrv_flags |= BDRV_O_INACTIVE;
662 return bdrv_open(NULL, NULL, bs_opts, bdrv_flags, errp);
665 void blockdev_close_all_bdrv_states(void)
667 BlockDriverState *bs, *next_bs;
669 QTAILQ_FOREACH_SAFE(bs, &monitor_bdrv_states, monitor_list, next_bs) {
670 AioContext *ctx = bdrv_get_aio_context(bs);
672 aio_context_acquire(ctx);
673 bdrv_unref(bs);
674 aio_context_release(ctx);
678 /* Iterates over the list of monitor-owned BlockDriverStates */
679 BlockDriverState *bdrv_next_monitor_owned(BlockDriverState *bs)
681 return bs ? QTAILQ_NEXT(bs, monitor_list)
682 : QTAILQ_FIRST(&monitor_bdrv_states);
685 static void qemu_opt_rename(QemuOpts *opts, const char *from, const char *to,
686 Error **errp)
688 const char *value;
690 value = qemu_opt_get(opts, from);
691 if (value) {
692 if (qemu_opt_find(opts, to)) {
693 error_setg(errp, "'%s' and its alias '%s' can't be used at the "
694 "same time", to, from);
695 return;
699 /* rename all items in opts */
700 while ((value = qemu_opt_get(opts, from))) {
701 qemu_opt_set(opts, to, value, &error_abort);
702 qemu_opt_unset(opts, from);
706 QemuOptsList qemu_legacy_drive_opts = {
707 .name = "drive",
708 .head = QTAILQ_HEAD_INITIALIZER(qemu_legacy_drive_opts.head),
709 .desc = {
711 .name = "bus",
712 .type = QEMU_OPT_NUMBER,
713 .help = "bus number",
715 .name = "unit",
716 .type = QEMU_OPT_NUMBER,
717 .help = "unit number (i.e. lun for scsi)",
719 .name = "index",
720 .type = QEMU_OPT_NUMBER,
721 .help = "index number",
723 .name = "media",
724 .type = QEMU_OPT_STRING,
725 .help = "media type (disk, cdrom)",
727 .name = "if",
728 .type = QEMU_OPT_STRING,
729 .help = "interface (ide, scsi, sd, mtd, floppy, pflash, virtio)",
731 .name = "cyls",
732 .type = QEMU_OPT_NUMBER,
733 .help = "number of cylinders (ide disk geometry)",
735 .name = "heads",
736 .type = QEMU_OPT_NUMBER,
737 .help = "number of heads (ide disk geometry)",
739 .name = "secs",
740 .type = QEMU_OPT_NUMBER,
741 .help = "number of sectors (ide disk geometry)",
743 .name = "trans",
744 .type = QEMU_OPT_STRING,
745 .help = "chs translation (auto, lba, none)",
747 .name = "addr",
748 .type = QEMU_OPT_STRING,
749 .help = "pci address (virtio only)",
751 .name = "serial",
752 .type = QEMU_OPT_STRING,
753 .help = "disk serial number",
755 .name = "file",
756 .type = QEMU_OPT_STRING,
757 .help = "file name",
760 /* Options that are passed on, but have special semantics with -drive */
762 .name = BDRV_OPT_READ_ONLY,
763 .type = QEMU_OPT_BOOL,
764 .help = "open drive file as read-only",
766 .name = "rerror",
767 .type = QEMU_OPT_STRING,
768 .help = "read error action",
770 .name = "werror",
771 .type = QEMU_OPT_STRING,
772 .help = "write error action",
774 .name = "copy-on-read",
775 .type = QEMU_OPT_BOOL,
776 .help = "copy read data from backing file into image file",
779 { /* end of list */ }
783 DriveInfo *drive_new(QemuOpts *all_opts, BlockInterfaceType block_default_type)
785 const char *value;
786 BlockBackend *blk;
787 DriveInfo *dinfo = NULL;
788 QDict *bs_opts;
789 QemuOpts *legacy_opts;
790 DriveMediaType media = MEDIA_DISK;
791 BlockInterfaceType type;
792 int cyls, heads, secs, translation;
793 int max_devs, bus_id, unit_id, index;
794 const char *devaddr;
795 const char *werror, *rerror;
796 bool read_only = false;
797 bool copy_on_read;
798 const char *serial;
799 const char *filename;
800 Error *local_err = NULL;
801 int i;
802 const char *deprecated[] = {
803 "serial", "trans", "secs", "heads", "cyls", "addr"
806 /* Change legacy command line options into QMP ones */
807 static const struct {
808 const char *from;
809 const char *to;
810 } opt_renames[] = {
811 { "iops", "throttling.iops-total" },
812 { "iops_rd", "throttling.iops-read" },
813 { "iops_wr", "throttling.iops-write" },
815 { "bps", "throttling.bps-total" },
816 { "bps_rd", "throttling.bps-read" },
817 { "bps_wr", "throttling.bps-write" },
819 { "iops_max", "throttling.iops-total-max" },
820 { "iops_rd_max", "throttling.iops-read-max" },
821 { "iops_wr_max", "throttling.iops-write-max" },
823 { "bps_max", "throttling.bps-total-max" },
824 { "bps_rd_max", "throttling.bps-read-max" },
825 { "bps_wr_max", "throttling.bps-write-max" },
827 { "iops_size", "throttling.iops-size" },
829 { "group", "throttling.group" },
831 { "readonly", BDRV_OPT_READ_ONLY },
834 for (i = 0; i < ARRAY_SIZE(opt_renames); i++) {
835 qemu_opt_rename(all_opts, opt_renames[i].from, opt_renames[i].to,
836 &local_err);
837 if (local_err) {
838 error_report_err(local_err);
839 return NULL;
843 value = qemu_opt_get(all_opts, "cache");
844 if (value) {
845 int flags = 0;
846 bool writethrough;
848 if (bdrv_parse_cache_mode(value, &flags, &writethrough) != 0) {
849 error_report("invalid cache option");
850 return NULL;
853 /* Specific options take precedence */
854 if (!qemu_opt_get(all_opts, BDRV_OPT_CACHE_WB)) {
855 qemu_opt_set_bool(all_opts, BDRV_OPT_CACHE_WB,
856 !writethrough, &error_abort);
858 if (!qemu_opt_get(all_opts, BDRV_OPT_CACHE_DIRECT)) {
859 qemu_opt_set_bool(all_opts, BDRV_OPT_CACHE_DIRECT,
860 !!(flags & BDRV_O_NOCACHE), &error_abort);
862 if (!qemu_opt_get(all_opts, BDRV_OPT_CACHE_NO_FLUSH)) {
863 qemu_opt_set_bool(all_opts, BDRV_OPT_CACHE_NO_FLUSH,
864 !!(flags & BDRV_O_NO_FLUSH), &error_abort);
866 qemu_opt_unset(all_opts, "cache");
869 /* Get a QDict for processing the options */
870 bs_opts = qdict_new();
871 qemu_opts_to_qdict(all_opts, bs_opts);
873 legacy_opts = qemu_opts_create(&qemu_legacy_drive_opts, NULL, 0,
874 &error_abort);
875 qemu_opts_absorb_qdict(legacy_opts, bs_opts, &local_err);
876 if (local_err) {
877 error_report_err(local_err);
878 goto fail;
881 /* Other deprecated options */
882 if (!qtest_enabled()) {
883 for (i = 0; i < ARRAY_SIZE(deprecated); i++) {
884 if (qemu_opt_get(legacy_opts, deprecated[i]) != NULL) {
885 error_report("'%s' is deprecated, please use the corresponding "
886 "option of '-device' instead", deprecated[i]);
891 /* Media type */
892 value = qemu_opt_get(legacy_opts, "media");
893 if (value) {
894 if (!strcmp(value, "disk")) {
895 media = MEDIA_DISK;
896 } else if (!strcmp(value, "cdrom")) {
897 media = MEDIA_CDROM;
898 read_only = true;
899 } else {
900 error_report("'%s' invalid media", value);
901 goto fail;
905 /* copy-on-read is disabled with a warning for read-only devices */
906 read_only |= qemu_opt_get_bool(legacy_opts, BDRV_OPT_READ_ONLY, false);
907 copy_on_read = qemu_opt_get_bool(legacy_opts, "copy-on-read", false);
909 if (read_only && copy_on_read) {
910 warn_report("disabling copy-on-read on read-only drive");
911 copy_on_read = false;
914 qdict_put_str(bs_opts, BDRV_OPT_READ_ONLY, read_only ? "on" : "off");
915 qdict_put_str(bs_opts, "copy-on-read", copy_on_read ? "on" : "off");
917 /* Controller type */
918 value = qemu_opt_get(legacy_opts, "if");
919 if (value) {
920 for (type = 0;
921 type < IF_COUNT && strcmp(value, if_name[type]);
922 type++) {
924 if (type == IF_COUNT) {
925 error_report("unsupported bus type '%s'", value);
926 goto fail;
928 } else {
929 type = block_default_type;
932 /* Geometry */
933 cyls = qemu_opt_get_number(legacy_opts, "cyls", 0);
934 heads = qemu_opt_get_number(legacy_opts, "heads", 0);
935 secs = qemu_opt_get_number(legacy_opts, "secs", 0);
937 if (cyls || heads || secs) {
938 if (cyls < 1) {
939 error_report("invalid physical cyls number");
940 goto fail;
942 if (heads < 1) {
943 error_report("invalid physical heads number");
944 goto fail;
946 if (secs < 1) {
947 error_report("invalid physical secs number");
948 goto fail;
952 translation = BIOS_ATA_TRANSLATION_AUTO;
953 value = qemu_opt_get(legacy_opts, "trans");
954 if (value != NULL) {
955 if (!cyls) {
956 error_report("'%s' trans must be used with cyls, heads and secs",
957 value);
958 goto fail;
960 if (!strcmp(value, "none")) {
961 translation = BIOS_ATA_TRANSLATION_NONE;
962 } else if (!strcmp(value, "lba")) {
963 translation = BIOS_ATA_TRANSLATION_LBA;
964 } else if (!strcmp(value, "large")) {
965 translation = BIOS_ATA_TRANSLATION_LARGE;
966 } else if (!strcmp(value, "rechs")) {
967 translation = BIOS_ATA_TRANSLATION_RECHS;
968 } else if (!strcmp(value, "auto")) {
969 translation = BIOS_ATA_TRANSLATION_AUTO;
970 } else {
971 error_report("'%s' invalid translation type", value);
972 goto fail;
976 if (media == MEDIA_CDROM) {
977 if (cyls || secs || heads) {
978 error_report("CHS can't be set with media=cdrom");
979 goto fail;
983 /* Device address specified by bus/unit or index.
984 * If none was specified, try to find the first free one. */
985 bus_id = qemu_opt_get_number(legacy_opts, "bus", 0);
986 unit_id = qemu_opt_get_number(legacy_opts, "unit", -1);
987 index = qemu_opt_get_number(legacy_opts, "index", -1);
989 max_devs = if_max_devs[type];
991 if (index != -1) {
992 if (bus_id != 0 || unit_id != -1) {
993 error_report("index cannot be used with bus and unit");
994 goto fail;
996 bus_id = drive_index_to_bus_id(type, index);
997 unit_id = drive_index_to_unit_id(type, index);
1000 if (unit_id == -1) {
1001 unit_id = 0;
1002 while (drive_get(type, bus_id, unit_id) != NULL) {
1003 unit_id++;
1004 if (max_devs && unit_id >= max_devs) {
1005 unit_id -= max_devs;
1006 bus_id++;
1011 if (max_devs && unit_id >= max_devs) {
1012 error_report("unit %d too big (max is %d)", unit_id, max_devs - 1);
1013 goto fail;
1016 if (drive_get(type, bus_id, unit_id) != NULL) {
1017 error_report("drive with bus=%d, unit=%d (index=%d) exists",
1018 bus_id, unit_id, index);
1019 goto fail;
1022 /* Serial number */
1023 serial = qemu_opt_get(legacy_opts, "serial");
1025 /* no id supplied -> create one */
1026 if (qemu_opts_id(all_opts) == NULL) {
1027 char *new_id;
1028 const char *mediastr = "";
1029 if (type == IF_IDE || type == IF_SCSI) {
1030 mediastr = (media == MEDIA_CDROM) ? "-cd" : "-hd";
1032 if (max_devs) {
1033 new_id = g_strdup_printf("%s%i%s%i", if_name[type], bus_id,
1034 mediastr, unit_id);
1035 } else {
1036 new_id = g_strdup_printf("%s%s%i", if_name[type],
1037 mediastr, unit_id);
1039 qdict_put_str(bs_opts, "id", new_id);
1040 g_free(new_id);
1043 /* Add virtio block device */
1044 devaddr = qemu_opt_get(legacy_opts, "addr");
1045 if (devaddr && type != IF_VIRTIO) {
1046 error_report("addr is not supported by this bus type");
1047 goto fail;
1050 if (type == IF_VIRTIO) {
1051 QemuOpts *devopts;
1052 devopts = qemu_opts_create(qemu_find_opts("device"), NULL, 0,
1053 &error_abort);
1054 if (arch_type == QEMU_ARCH_S390X) {
1055 qemu_opt_set(devopts, "driver", "virtio-blk-ccw", &error_abort);
1056 } else {
1057 qemu_opt_set(devopts, "driver", "virtio-blk-pci", &error_abort);
1059 qemu_opt_set(devopts, "drive", qdict_get_str(bs_opts, "id"),
1060 &error_abort);
1061 if (devaddr) {
1062 qemu_opt_set(devopts, "addr", devaddr, &error_abort);
1066 filename = qemu_opt_get(legacy_opts, "file");
1068 /* Check werror/rerror compatibility with if=... */
1069 werror = qemu_opt_get(legacy_opts, "werror");
1070 if (werror != NULL) {
1071 if (type != IF_IDE && type != IF_SCSI && type != IF_VIRTIO &&
1072 type != IF_NONE) {
1073 error_report("werror is not supported by this bus type");
1074 goto fail;
1076 qdict_put_str(bs_opts, "werror", werror);
1079 rerror = qemu_opt_get(legacy_opts, "rerror");
1080 if (rerror != NULL) {
1081 if (type != IF_IDE && type != IF_VIRTIO && type != IF_SCSI &&
1082 type != IF_NONE) {
1083 error_report("rerror is not supported by this bus type");
1084 goto fail;
1086 qdict_put_str(bs_opts, "rerror", rerror);
1089 /* Actual block device init: Functionality shared with blockdev-add */
1090 blk = blockdev_init(filename, bs_opts, &local_err);
1091 bs_opts = NULL;
1092 if (!blk) {
1093 if (local_err) {
1094 error_report_err(local_err);
1096 goto fail;
1097 } else {
1098 assert(!local_err);
1101 /* Create legacy DriveInfo */
1102 dinfo = g_malloc0(sizeof(*dinfo));
1103 dinfo->opts = all_opts;
1105 dinfo->cyls = cyls;
1106 dinfo->heads = heads;
1107 dinfo->secs = secs;
1108 dinfo->trans = translation;
1110 dinfo->type = type;
1111 dinfo->bus = bus_id;
1112 dinfo->unit = unit_id;
1113 dinfo->devaddr = devaddr;
1114 dinfo->serial = g_strdup(serial);
1116 blk_set_legacy_dinfo(blk, dinfo);
1118 switch(type) {
1119 case IF_IDE:
1120 case IF_SCSI:
1121 case IF_XEN:
1122 case IF_NONE:
1123 dinfo->media_cd = media == MEDIA_CDROM;
1124 break;
1125 default:
1126 break;
1129 fail:
1130 qemu_opts_del(legacy_opts);
1131 QDECREF(bs_opts);
1132 return dinfo;
1135 static BlockDriverState *qmp_get_root_bs(const char *name, Error **errp)
1137 BlockDriverState *bs;
1139 bs = bdrv_lookup_bs(name, name, errp);
1140 if (bs == NULL) {
1141 return NULL;
1144 if (!bdrv_is_root_node(bs)) {
1145 error_setg(errp, "Need a root block node");
1146 return NULL;
1149 if (!bdrv_is_inserted(bs)) {
1150 error_setg(errp, "Device has no medium");
1151 return NULL;
1154 return bs;
1157 static BlockBackend *qmp_get_blk(const char *blk_name, const char *qdev_id,
1158 Error **errp)
1160 BlockBackend *blk;
1162 if (!blk_name == !qdev_id) {
1163 error_setg(errp, "Need exactly one of 'device' and 'id'");
1164 return NULL;
1167 if (qdev_id) {
1168 blk = blk_by_qdev_id(qdev_id, errp);
1169 } else {
1170 blk = blk_by_name(blk_name);
1171 if (blk == NULL) {
1172 error_set(errp, ERROR_CLASS_DEVICE_NOT_FOUND,
1173 "Device '%s' not found", blk_name);
1177 return blk;
1180 void hmp_commit(Monitor *mon, const QDict *qdict)
1182 const char *device = qdict_get_str(qdict, "device");
1183 BlockBackend *blk;
1184 int ret;
1186 if (!strcmp(device, "all")) {
1187 ret = blk_commit_all();
1188 } else {
1189 BlockDriverState *bs;
1190 AioContext *aio_context;
1192 blk = blk_by_name(device);
1193 if (!blk) {
1194 monitor_printf(mon, "Device '%s' not found\n", device);
1195 return;
1197 if (!blk_is_available(blk)) {
1198 monitor_printf(mon, "Device '%s' has no medium\n", device);
1199 return;
1202 bs = blk_bs(blk);
1203 aio_context = bdrv_get_aio_context(bs);
1204 aio_context_acquire(aio_context);
1206 ret = bdrv_commit(bs);
1208 aio_context_release(aio_context);
1210 if (ret < 0) {
1211 monitor_printf(mon, "'commit' error for '%s': %s\n", device,
1212 strerror(-ret));
1216 static void blockdev_do_action(TransactionAction *action, Error **errp)
1218 TransactionActionList list;
1220 list.value = action;
1221 list.next = NULL;
1222 qmp_transaction(&list, false, NULL, errp);
1225 void qmp_blockdev_snapshot_sync(bool has_device, const char *device,
1226 bool has_node_name, const char *node_name,
1227 const char *snapshot_file,
1228 bool has_snapshot_node_name,
1229 const char *snapshot_node_name,
1230 bool has_format, const char *format,
1231 bool has_mode, NewImageMode mode, Error **errp)
1233 BlockdevSnapshotSync snapshot = {
1234 .has_device = has_device,
1235 .device = (char *) device,
1236 .has_node_name = has_node_name,
1237 .node_name = (char *) node_name,
1238 .snapshot_file = (char *) snapshot_file,
1239 .has_snapshot_node_name = has_snapshot_node_name,
1240 .snapshot_node_name = (char *) snapshot_node_name,
1241 .has_format = has_format,
1242 .format = (char *) format,
1243 .has_mode = has_mode,
1244 .mode = mode,
1246 TransactionAction action = {
1247 .type = TRANSACTION_ACTION_KIND_BLOCKDEV_SNAPSHOT_SYNC,
1248 .u.blockdev_snapshot_sync.data = &snapshot,
1250 blockdev_do_action(&action, errp);
1253 void qmp_blockdev_snapshot(const char *node, const char *overlay,
1254 Error **errp)
1256 BlockdevSnapshot snapshot_data = {
1257 .node = (char *) node,
1258 .overlay = (char *) overlay
1260 TransactionAction action = {
1261 .type = TRANSACTION_ACTION_KIND_BLOCKDEV_SNAPSHOT,
1262 .u.blockdev_snapshot.data = &snapshot_data,
1264 blockdev_do_action(&action, errp);
1267 void qmp_blockdev_snapshot_internal_sync(const char *device,
1268 const char *name,
1269 Error **errp)
1271 BlockdevSnapshotInternal snapshot = {
1272 .device = (char *) device,
1273 .name = (char *) name
1275 TransactionAction action = {
1276 .type = TRANSACTION_ACTION_KIND_BLOCKDEV_SNAPSHOT_INTERNAL_SYNC,
1277 .u.blockdev_snapshot_internal_sync.data = &snapshot,
1279 blockdev_do_action(&action, errp);
1282 SnapshotInfo *qmp_blockdev_snapshot_delete_internal_sync(const char *device,
1283 bool has_id,
1284 const char *id,
1285 bool has_name,
1286 const char *name,
1287 Error **errp)
1289 BlockDriverState *bs;
1290 AioContext *aio_context;
1291 QEMUSnapshotInfo sn;
1292 Error *local_err = NULL;
1293 SnapshotInfo *info = NULL;
1294 int ret;
1296 bs = qmp_get_root_bs(device, errp);
1297 if (!bs) {
1298 return NULL;
1300 aio_context = bdrv_get_aio_context(bs);
1301 aio_context_acquire(aio_context);
1303 if (!has_id) {
1304 id = NULL;
1307 if (!has_name) {
1308 name = NULL;
1311 if (!id && !name) {
1312 error_setg(errp, "Name or id must be provided");
1313 goto out_aio_context;
1316 if (bdrv_op_is_blocked(bs, BLOCK_OP_TYPE_INTERNAL_SNAPSHOT_DELETE, errp)) {
1317 goto out_aio_context;
1320 ret = bdrv_snapshot_find_by_id_and_name(bs, id, name, &sn, &local_err);
1321 if (local_err) {
1322 error_propagate(errp, local_err);
1323 goto out_aio_context;
1325 if (!ret) {
1326 error_setg(errp,
1327 "Snapshot with id '%s' and name '%s' does not exist on "
1328 "device '%s'",
1329 STR_OR_NULL(id), STR_OR_NULL(name), device);
1330 goto out_aio_context;
1333 bdrv_snapshot_delete(bs, id, name, &local_err);
1334 if (local_err) {
1335 error_propagate(errp, local_err);
1336 goto out_aio_context;
1339 aio_context_release(aio_context);
1341 info = g_new0(SnapshotInfo, 1);
1342 info->id = g_strdup(sn.id_str);
1343 info->name = g_strdup(sn.name);
1344 info->date_nsec = sn.date_nsec;
1345 info->date_sec = sn.date_sec;
1346 info->vm_state_size = sn.vm_state_size;
1347 info->vm_clock_nsec = sn.vm_clock_nsec % 1000000000;
1348 info->vm_clock_sec = sn.vm_clock_nsec / 1000000000;
1350 return info;
1352 out_aio_context:
1353 aio_context_release(aio_context);
1354 return NULL;
1358 * block_dirty_bitmap_lookup:
1359 * Return a dirty bitmap (if present), after validating
1360 * the node reference and bitmap names.
1362 * @node: The name of the BDS node to search for bitmaps
1363 * @name: The name of the bitmap to search for
1364 * @pbs: Output pointer for BDS lookup, if desired. Can be NULL.
1365 * @paio: Output pointer for aio_context acquisition, if desired. Can be NULL.
1366 * @errp: Output pointer for error information. Can be NULL.
1368 * @return: A bitmap object on success, or NULL on failure.
1370 static BdrvDirtyBitmap *block_dirty_bitmap_lookup(const char *node,
1371 const char *name,
1372 BlockDriverState **pbs,
1373 Error **errp)
1375 BlockDriverState *bs;
1376 BdrvDirtyBitmap *bitmap;
1378 if (!node) {
1379 error_setg(errp, "Node cannot be NULL");
1380 return NULL;
1382 if (!name) {
1383 error_setg(errp, "Bitmap name cannot be NULL");
1384 return NULL;
1386 bs = bdrv_lookup_bs(node, node, NULL);
1387 if (!bs) {
1388 error_setg(errp, "Node '%s' not found", node);
1389 return NULL;
1392 bitmap = bdrv_find_dirty_bitmap(bs, name);
1393 if (!bitmap) {
1394 error_setg(errp, "Dirty bitmap '%s' not found", name);
1395 return NULL;
1398 if (pbs) {
1399 *pbs = bs;
1402 return bitmap;
1405 /* New and old BlockDriverState structs for atomic group operations */
1407 typedef struct BlkActionState BlkActionState;
1410 * BlkActionOps:
1411 * Table of operations that define an Action.
1413 * @instance_size: Size of state struct, in bytes.
1414 * @prepare: Prepare the work, must NOT be NULL.
1415 * @commit: Commit the changes, can be NULL.
1416 * @abort: Abort the changes on fail, can be NULL.
1417 * @clean: Clean up resources after all transaction actions have called
1418 * commit() or abort(). Can be NULL.
1420 * Only prepare() may fail. In a single transaction, only one of commit() or
1421 * abort() will be called. clean() will always be called if it is present.
1423 typedef struct BlkActionOps {
1424 size_t instance_size;
1425 void (*prepare)(BlkActionState *common, Error **errp);
1426 void (*commit)(BlkActionState *common);
1427 void (*abort)(BlkActionState *common);
1428 void (*clean)(BlkActionState *common);
1429 } BlkActionOps;
1432 * BlkActionState:
1433 * Describes one Action's state within a Transaction.
1435 * @action: QAPI-defined enum identifying which Action to perform.
1436 * @ops: Table of ActionOps this Action can perform.
1437 * @block_job_txn: Transaction which this action belongs to.
1438 * @entry: List membership for all Actions in this Transaction.
1440 * This structure must be arranged as first member in a subclassed type,
1441 * assuming that the compiler will also arrange it to the same offsets as the
1442 * base class.
1444 struct BlkActionState {
1445 TransactionAction *action;
1446 const BlkActionOps *ops;
1447 BlockJobTxn *block_job_txn;
1448 TransactionProperties *txn_props;
1449 QSIMPLEQ_ENTRY(BlkActionState) entry;
1452 /* internal snapshot private data */
1453 typedef struct InternalSnapshotState {
1454 BlkActionState common;
1455 BlockDriverState *bs;
1456 QEMUSnapshotInfo sn;
1457 bool created;
1458 } InternalSnapshotState;
1461 static int action_check_completion_mode(BlkActionState *s, Error **errp)
1463 if (s->txn_props->completion_mode != ACTION_COMPLETION_MODE_INDIVIDUAL) {
1464 error_setg(errp,
1465 "Action '%s' does not support Transaction property "
1466 "completion-mode = %s",
1467 TransactionActionKind_str(s->action->type),
1468 ActionCompletionMode_str(s->txn_props->completion_mode));
1469 return -1;
1471 return 0;
1474 static void internal_snapshot_prepare(BlkActionState *common,
1475 Error **errp)
1477 Error *local_err = NULL;
1478 const char *device;
1479 const char *name;
1480 BlockDriverState *bs;
1481 QEMUSnapshotInfo old_sn, *sn;
1482 bool ret;
1483 qemu_timeval tv;
1484 BlockdevSnapshotInternal *internal;
1485 InternalSnapshotState *state;
1486 AioContext *aio_context;
1487 int ret1;
1489 g_assert(common->action->type ==
1490 TRANSACTION_ACTION_KIND_BLOCKDEV_SNAPSHOT_INTERNAL_SYNC);
1491 internal = common->action->u.blockdev_snapshot_internal_sync.data;
1492 state = DO_UPCAST(InternalSnapshotState, common, common);
1494 /* 1. parse input */
1495 device = internal->device;
1496 name = internal->name;
1498 /* 2. check for validation */
1499 if (action_check_completion_mode(common, errp) < 0) {
1500 return;
1503 bs = qmp_get_root_bs(device, errp);
1504 if (!bs) {
1505 return;
1508 aio_context = bdrv_get_aio_context(bs);
1509 aio_context_acquire(aio_context);
1511 state->bs = bs;
1513 /* Paired with .clean() */
1514 bdrv_drained_begin(bs);
1516 if (bdrv_op_is_blocked(bs, BLOCK_OP_TYPE_INTERNAL_SNAPSHOT, errp)) {
1517 goto out;
1520 if (bdrv_is_read_only(bs)) {
1521 error_setg(errp, "Device '%s' is read only", device);
1522 goto out;
1525 if (!bdrv_can_snapshot(bs)) {
1526 error_setg(errp, "Block format '%s' used by device '%s' "
1527 "does not support internal snapshots",
1528 bs->drv->format_name, device);
1529 goto out;
1532 if (!strlen(name)) {
1533 error_setg(errp, "Name is empty");
1534 goto out;
1537 /* check whether a snapshot with name exist */
1538 ret = bdrv_snapshot_find_by_id_and_name(bs, NULL, name, &old_sn,
1539 &local_err);
1540 if (local_err) {
1541 error_propagate(errp, local_err);
1542 goto out;
1543 } else if (ret) {
1544 error_setg(errp,
1545 "Snapshot with name '%s' already exists on device '%s'",
1546 name, device);
1547 goto out;
1550 /* 3. take the snapshot */
1551 sn = &state->sn;
1552 pstrcpy(sn->name, sizeof(sn->name), name);
1553 qemu_gettimeofday(&tv);
1554 sn->date_sec = tv.tv_sec;
1555 sn->date_nsec = tv.tv_usec * 1000;
1556 sn->vm_clock_nsec = qemu_clock_get_ns(QEMU_CLOCK_VIRTUAL);
1558 ret1 = bdrv_snapshot_create(bs, sn);
1559 if (ret1 < 0) {
1560 error_setg_errno(errp, -ret1,
1561 "Failed to create snapshot '%s' on device '%s'",
1562 name, device);
1563 goto out;
1566 /* 4. succeed, mark a snapshot is created */
1567 state->created = true;
1569 out:
1570 aio_context_release(aio_context);
1573 static void internal_snapshot_abort(BlkActionState *common)
1575 InternalSnapshotState *state =
1576 DO_UPCAST(InternalSnapshotState, common, common);
1577 BlockDriverState *bs = state->bs;
1578 QEMUSnapshotInfo *sn = &state->sn;
1579 AioContext *aio_context;
1580 Error *local_error = NULL;
1582 if (!state->created) {
1583 return;
1586 aio_context = bdrv_get_aio_context(state->bs);
1587 aio_context_acquire(aio_context);
1589 if (bdrv_snapshot_delete(bs, sn->id_str, sn->name, &local_error) < 0) {
1590 error_reportf_err(local_error,
1591 "Failed to delete snapshot with id '%s' and "
1592 "name '%s' on device '%s' in abort: ",
1593 sn->id_str, sn->name,
1594 bdrv_get_device_name(bs));
1597 aio_context_release(aio_context);
1600 static void internal_snapshot_clean(BlkActionState *common)
1602 InternalSnapshotState *state = DO_UPCAST(InternalSnapshotState,
1603 common, common);
1604 AioContext *aio_context;
1606 if (!state->bs) {
1607 return;
1610 aio_context = bdrv_get_aio_context(state->bs);
1611 aio_context_acquire(aio_context);
1613 bdrv_drained_end(state->bs);
1615 aio_context_release(aio_context);
1618 /* external snapshot private data */
1619 typedef struct ExternalSnapshotState {
1620 BlkActionState common;
1621 BlockDriverState *old_bs;
1622 BlockDriverState *new_bs;
1623 bool overlay_appended;
1624 } ExternalSnapshotState;
1626 static void external_snapshot_prepare(BlkActionState *common,
1627 Error **errp)
1629 int flags = 0;
1630 QDict *options = NULL;
1631 Error *local_err = NULL;
1632 /* Device and node name of the image to generate the snapshot from */
1633 const char *device;
1634 const char *node_name;
1635 /* Reference to the new image (for 'blockdev-snapshot') */
1636 const char *snapshot_ref;
1637 /* File name of the new image (for 'blockdev-snapshot-sync') */
1638 const char *new_image_file;
1639 ExternalSnapshotState *state =
1640 DO_UPCAST(ExternalSnapshotState, common, common);
1641 TransactionAction *action = common->action;
1642 AioContext *aio_context;
1644 /* 'blockdev-snapshot' and 'blockdev-snapshot-sync' have similar
1645 * purpose but a different set of parameters */
1646 switch (action->type) {
1647 case TRANSACTION_ACTION_KIND_BLOCKDEV_SNAPSHOT:
1649 BlockdevSnapshot *s = action->u.blockdev_snapshot.data;
1650 device = s->node;
1651 node_name = s->node;
1652 new_image_file = NULL;
1653 snapshot_ref = s->overlay;
1655 break;
1656 case TRANSACTION_ACTION_KIND_BLOCKDEV_SNAPSHOT_SYNC:
1658 BlockdevSnapshotSync *s = action->u.blockdev_snapshot_sync.data;
1659 device = s->has_device ? s->device : NULL;
1660 node_name = s->has_node_name ? s->node_name : NULL;
1661 new_image_file = s->snapshot_file;
1662 snapshot_ref = NULL;
1664 break;
1665 default:
1666 g_assert_not_reached();
1669 /* start processing */
1670 if (action_check_completion_mode(common, errp) < 0) {
1671 return;
1674 state->old_bs = bdrv_lookup_bs(device, node_name, errp);
1675 if (!state->old_bs) {
1676 return;
1679 aio_context = bdrv_get_aio_context(state->old_bs);
1680 aio_context_acquire(aio_context);
1682 /* Paired with .clean() */
1683 bdrv_drained_begin(state->old_bs);
1685 if (!bdrv_is_inserted(state->old_bs)) {
1686 error_setg(errp, QERR_DEVICE_HAS_NO_MEDIUM, device);
1687 goto out;
1690 if (bdrv_op_is_blocked(state->old_bs,
1691 BLOCK_OP_TYPE_EXTERNAL_SNAPSHOT, errp)) {
1692 goto out;
1695 if (!bdrv_is_read_only(state->old_bs)) {
1696 if (bdrv_flush(state->old_bs)) {
1697 error_setg(errp, QERR_IO_ERROR);
1698 goto out;
1702 if (!bdrv_is_first_non_filter(state->old_bs)) {
1703 error_setg(errp, QERR_FEATURE_DISABLED, "snapshot");
1704 goto out;
1707 if (action->type == TRANSACTION_ACTION_KIND_BLOCKDEV_SNAPSHOT_SYNC) {
1708 BlockdevSnapshotSync *s = action->u.blockdev_snapshot_sync.data;
1709 const char *format = s->has_format ? s->format : "qcow2";
1710 enum NewImageMode mode;
1711 const char *snapshot_node_name =
1712 s->has_snapshot_node_name ? s->snapshot_node_name : NULL;
1714 if (node_name && !snapshot_node_name) {
1715 error_setg(errp, "New snapshot node name missing");
1716 goto out;
1719 if (snapshot_node_name &&
1720 bdrv_lookup_bs(snapshot_node_name, snapshot_node_name, NULL)) {
1721 error_setg(errp, "New snapshot node name already in use");
1722 goto out;
1725 flags = state->old_bs->open_flags;
1726 flags &= ~(BDRV_O_SNAPSHOT | BDRV_O_COPY_ON_READ);
1727 flags |= BDRV_O_NO_BACKING;
1729 /* create new image w/backing file */
1730 mode = s->has_mode ? s->mode : NEW_IMAGE_MODE_ABSOLUTE_PATHS;
1731 if (mode != NEW_IMAGE_MODE_EXISTING) {
1732 int64_t size = bdrv_getlength(state->old_bs);
1733 if (size < 0) {
1734 error_setg_errno(errp, -size, "bdrv_getlength failed");
1735 goto out;
1737 bdrv_img_create(new_image_file, format,
1738 state->old_bs->filename,
1739 state->old_bs->drv->format_name,
1740 NULL, size, flags, false, &local_err);
1741 if (local_err) {
1742 error_propagate(errp, local_err);
1743 goto out;
1747 options = qdict_new();
1748 if (s->has_snapshot_node_name) {
1749 qdict_put_str(options, "node-name", snapshot_node_name);
1751 qdict_put_str(options, "driver", format);
1754 state->new_bs = bdrv_open(new_image_file, snapshot_ref, options, flags,
1755 errp);
1756 /* We will manually add the backing_hd field to the bs later */
1757 if (!state->new_bs) {
1758 goto out;
1761 if (bdrv_has_blk(state->new_bs)) {
1762 error_setg(errp, "The snapshot is already in use");
1763 goto out;
1766 if (bdrv_op_is_blocked(state->new_bs, BLOCK_OP_TYPE_EXTERNAL_SNAPSHOT,
1767 errp)) {
1768 goto out;
1771 if (state->new_bs->backing != NULL) {
1772 error_setg(errp, "The snapshot already has a backing image");
1773 goto out;
1776 if (!state->new_bs->drv->supports_backing) {
1777 error_setg(errp, "The snapshot does not support backing images");
1778 goto out;
1781 bdrv_set_aio_context(state->new_bs, aio_context);
1783 /* This removes our old bs and adds the new bs. This is an operation that
1784 * can fail, so we need to do it in .prepare; undoing it for abort is
1785 * always possible. */
1786 bdrv_ref(state->new_bs);
1787 bdrv_append(state->new_bs, state->old_bs, &local_err);
1788 if (local_err) {
1789 error_propagate(errp, local_err);
1790 goto out;
1792 state->overlay_appended = true;
1794 out:
1795 aio_context_release(aio_context);
1798 static void external_snapshot_commit(BlkActionState *common)
1800 ExternalSnapshotState *state =
1801 DO_UPCAST(ExternalSnapshotState, common, common);
1802 AioContext *aio_context;
1804 aio_context = bdrv_get_aio_context(state->old_bs);
1805 aio_context_acquire(aio_context);
1807 /* We don't need (or want) to use the transactional
1808 * bdrv_reopen_multiple() across all the entries at once, because we
1809 * don't want to abort all of them if one of them fails the reopen */
1810 if (!atomic_read(&state->old_bs->copy_on_read)) {
1811 bdrv_reopen(state->old_bs, state->old_bs->open_flags & ~BDRV_O_RDWR,
1812 NULL);
1815 aio_context_release(aio_context);
1818 static void external_snapshot_abort(BlkActionState *common)
1820 ExternalSnapshotState *state =
1821 DO_UPCAST(ExternalSnapshotState, common, common);
1822 if (state->new_bs) {
1823 if (state->overlay_appended) {
1824 AioContext *aio_context;
1826 aio_context = bdrv_get_aio_context(state->old_bs);
1827 aio_context_acquire(aio_context);
1829 bdrv_ref(state->old_bs); /* we can't let bdrv_set_backind_hd()
1830 close state->old_bs; we need it */
1831 bdrv_set_backing_hd(state->new_bs, NULL, &error_abort);
1832 bdrv_replace_node(state->new_bs, state->old_bs, &error_abort);
1833 bdrv_unref(state->old_bs); /* bdrv_replace_node() ref'ed old_bs */
1835 aio_context_release(aio_context);
1840 static void external_snapshot_clean(BlkActionState *common)
1842 ExternalSnapshotState *state =
1843 DO_UPCAST(ExternalSnapshotState, common, common);
1844 AioContext *aio_context;
1846 if (!state->old_bs) {
1847 return;
1850 aio_context = bdrv_get_aio_context(state->old_bs);
1851 aio_context_acquire(aio_context);
1853 bdrv_drained_end(state->old_bs);
1854 bdrv_unref(state->new_bs);
1856 aio_context_release(aio_context);
1859 typedef struct DriveBackupState {
1860 BlkActionState common;
1861 BlockDriverState *bs;
1862 BlockJob *job;
1863 } DriveBackupState;
1865 static BlockJob *do_drive_backup(DriveBackup *backup, BlockJobTxn *txn,
1866 Error **errp);
1868 static void drive_backup_prepare(BlkActionState *common, Error **errp)
1870 DriveBackupState *state = DO_UPCAST(DriveBackupState, common, common);
1871 BlockDriverState *bs;
1872 DriveBackup *backup;
1873 AioContext *aio_context;
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 aio_context = bdrv_get_aio_context(bs);
1885 aio_context_acquire(aio_context);
1887 /* Paired with .clean() */
1888 bdrv_drained_begin(bs);
1890 state->bs = bs;
1892 state->job = do_drive_backup(backup, common->block_job_txn, &local_err);
1893 if (local_err) {
1894 error_propagate(errp, local_err);
1895 goto out;
1898 out:
1899 aio_context_release(aio_context);
1902 static void drive_backup_commit(BlkActionState *common)
1904 DriveBackupState *state = DO_UPCAST(DriveBackupState, common, common);
1905 AioContext *aio_context;
1907 aio_context = bdrv_get_aio_context(state->bs);
1908 aio_context_acquire(aio_context);
1910 assert(state->job);
1911 block_job_start(state->job);
1913 aio_context_release(aio_context);
1916 static void drive_backup_abort(BlkActionState *common)
1918 DriveBackupState *state = DO_UPCAST(DriveBackupState, common, common);
1920 if (state->job) {
1921 AioContext *aio_context;
1923 aio_context = bdrv_get_aio_context(state->bs);
1924 aio_context_acquire(aio_context);
1926 block_job_cancel_sync(state->job);
1928 aio_context_release(aio_context);
1932 static void drive_backup_clean(BlkActionState *common)
1934 DriveBackupState *state = DO_UPCAST(DriveBackupState, common, common);
1935 AioContext *aio_context;
1937 if (!state->bs) {
1938 return;
1941 aio_context = bdrv_get_aio_context(state->bs);
1942 aio_context_acquire(aio_context);
1944 bdrv_drained_end(state->bs);
1946 aio_context_release(aio_context);
1949 typedef struct BlockdevBackupState {
1950 BlkActionState common;
1951 BlockDriverState *bs;
1952 BlockJob *job;
1953 } BlockdevBackupState;
1955 static BlockJob *do_blockdev_backup(BlockdevBackup *backup, BlockJobTxn *txn,
1956 Error **errp);
1958 static void blockdev_backup_prepare(BlkActionState *common, Error **errp)
1960 BlockdevBackupState *state = DO_UPCAST(BlockdevBackupState, common, common);
1961 BlockdevBackup *backup;
1962 BlockDriverState *bs, *target;
1963 AioContext *aio_context;
1964 Error *local_err = NULL;
1966 assert(common->action->type == TRANSACTION_ACTION_KIND_BLOCKDEV_BACKUP);
1967 backup = common->action->u.blockdev_backup.data;
1969 bs = qmp_get_root_bs(backup->device, errp);
1970 if (!bs) {
1971 return;
1974 target = bdrv_lookup_bs(backup->target, backup->target, errp);
1975 if (!target) {
1976 return;
1979 aio_context = bdrv_get_aio_context(bs);
1980 if (aio_context != bdrv_get_aio_context(target)) {
1981 error_setg(errp, "Backup between two IO threads is not implemented");
1982 return;
1984 aio_context_acquire(aio_context);
1985 state->bs = bs;
1987 /* Paired with .clean() */
1988 bdrv_drained_begin(state->bs);
1990 state->job = do_blockdev_backup(backup, common->block_job_txn, &local_err);
1991 if (local_err) {
1992 error_propagate(errp, local_err);
1993 goto out;
1996 out:
1997 aio_context_release(aio_context);
2000 static void blockdev_backup_commit(BlkActionState *common)
2002 BlockdevBackupState *state = DO_UPCAST(BlockdevBackupState, common, common);
2003 AioContext *aio_context;
2005 aio_context = bdrv_get_aio_context(state->bs);
2006 aio_context_acquire(aio_context);
2008 assert(state->job);
2009 block_job_start(state->job);
2011 aio_context_release(aio_context);
2014 static void blockdev_backup_abort(BlkActionState *common)
2016 BlockdevBackupState *state = DO_UPCAST(BlockdevBackupState, common, common);
2018 if (state->job) {
2019 AioContext *aio_context;
2021 aio_context = bdrv_get_aio_context(state->bs);
2022 aio_context_acquire(aio_context);
2024 block_job_cancel_sync(state->job);
2026 aio_context_release(aio_context);
2030 static void blockdev_backup_clean(BlkActionState *common)
2032 BlockdevBackupState *state = DO_UPCAST(BlockdevBackupState, common, common);
2033 AioContext *aio_context;
2035 if (!state->bs) {
2036 return;
2039 aio_context = bdrv_get_aio_context(state->bs);
2040 aio_context_acquire(aio_context);
2042 bdrv_drained_end(state->bs);
2044 aio_context_release(aio_context);
2047 typedef struct BlockDirtyBitmapState {
2048 BlkActionState common;
2049 BdrvDirtyBitmap *bitmap;
2050 BlockDriverState *bs;
2051 HBitmap *backup;
2052 bool prepared;
2053 } BlockDirtyBitmapState;
2055 static void block_dirty_bitmap_add_prepare(BlkActionState *common,
2056 Error **errp)
2058 Error *local_err = NULL;
2059 BlockDirtyBitmapAdd *action;
2060 BlockDirtyBitmapState *state = DO_UPCAST(BlockDirtyBitmapState,
2061 common, common);
2063 if (action_check_completion_mode(common, errp) < 0) {
2064 return;
2067 action = common->action->u.block_dirty_bitmap_add.data;
2068 /* AIO context taken and released within qmp_block_dirty_bitmap_add */
2069 qmp_block_dirty_bitmap_add(action->node, action->name,
2070 action->has_granularity, action->granularity,
2071 action->has_persistent, action->persistent,
2072 action->has_autoload, action->autoload,
2073 &local_err);
2075 if (!local_err) {
2076 state->prepared = true;
2077 } else {
2078 error_propagate(errp, local_err);
2082 static void block_dirty_bitmap_add_abort(BlkActionState *common)
2084 BlockDirtyBitmapAdd *action;
2085 BlockDirtyBitmapState *state = DO_UPCAST(BlockDirtyBitmapState,
2086 common, common);
2088 action = common->action->u.block_dirty_bitmap_add.data;
2089 /* Should not be able to fail: IF the bitmap was added via .prepare(),
2090 * then the node reference and bitmap name must have been valid.
2092 if (state->prepared) {
2093 qmp_block_dirty_bitmap_remove(action->node, action->name, &error_abort);
2097 static void block_dirty_bitmap_clear_prepare(BlkActionState *common,
2098 Error **errp)
2100 BlockDirtyBitmapState *state = DO_UPCAST(BlockDirtyBitmapState,
2101 common, common);
2102 BlockDirtyBitmap *action;
2104 if (action_check_completion_mode(common, errp) < 0) {
2105 return;
2108 action = common->action->u.block_dirty_bitmap_clear.data;
2109 state->bitmap = block_dirty_bitmap_lookup(action->node,
2110 action->name,
2111 &state->bs,
2112 errp);
2113 if (!state->bitmap) {
2114 return;
2117 if (bdrv_dirty_bitmap_frozen(state->bitmap)) {
2118 error_setg(errp, "Cannot modify a frozen bitmap");
2119 return;
2120 } else if (!bdrv_dirty_bitmap_enabled(state->bitmap)) {
2121 error_setg(errp, "Cannot clear a disabled bitmap");
2122 return;
2123 } else if (bdrv_dirty_bitmap_readonly(state->bitmap)) {
2124 error_setg(errp, "Cannot clear a readonly bitmap");
2125 return;
2128 bdrv_clear_dirty_bitmap(state->bitmap, &state->backup);
2131 static void block_dirty_bitmap_clear_abort(BlkActionState *common)
2133 BlockDirtyBitmapState *state = DO_UPCAST(BlockDirtyBitmapState,
2134 common, common);
2136 if (state->backup) {
2137 bdrv_undo_clear_dirty_bitmap(state->bitmap, state->backup);
2141 static void block_dirty_bitmap_clear_commit(BlkActionState *common)
2143 BlockDirtyBitmapState *state = DO_UPCAST(BlockDirtyBitmapState,
2144 common, common);
2146 hbitmap_free(state->backup);
2149 static void abort_prepare(BlkActionState *common, Error **errp)
2151 error_setg(errp, "Transaction aborted using Abort action");
2154 static void abort_commit(BlkActionState *common)
2156 g_assert_not_reached(); /* this action never succeeds */
2159 static const BlkActionOps actions[] = {
2160 [TRANSACTION_ACTION_KIND_BLOCKDEV_SNAPSHOT] = {
2161 .instance_size = sizeof(ExternalSnapshotState),
2162 .prepare = external_snapshot_prepare,
2163 .commit = external_snapshot_commit,
2164 .abort = external_snapshot_abort,
2165 .clean = external_snapshot_clean,
2167 [TRANSACTION_ACTION_KIND_BLOCKDEV_SNAPSHOT_SYNC] = {
2168 .instance_size = sizeof(ExternalSnapshotState),
2169 .prepare = external_snapshot_prepare,
2170 .commit = external_snapshot_commit,
2171 .abort = external_snapshot_abort,
2172 .clean = external_snapshot_clean,
2174 [TRANSACTION_ACTION_KIND_DRIVE_BACKUP] = {
2175 .instance_size = sizeof(DriveBackupState),
2176 .prepare = drive_backup_prepare,
2177 .commit = drive_backup_commit,
2178 .abort = drive_backup_abort,
2179 .clean = drive_backup_clean,
2181 [TRANSACTION_ACTION_KIND_BLOCKDEV_BACKUP] = {
2182 .instance_size = sizeof(BlockdevBackupState),
2183 .prepare = blockdev_backup_prepare,
2184 .commit = blockdev_backup_commit,
2185 .abort = blockdev_backup_abort,
2186 .clean = blockdev_backup_clean,
2188 [TRANSACTION_ACTION_KIND_ABORT] = {
2189 .instance_size = sizeof(BlkActionState),
2190 .prepare = abort_prepare,
2191 .commit = abort_commit,
2193 [TRANSACTION_ACTION_KIND_BLOCKDEV_SNAPSHOT_INTERNAL_SYNC] = {
2194 .instance_size = sizeof(InternalSnapshotState),
2195 .prepare = internal_snapshot_prepare,
2196 .abort = internal_snapshot_abort,
2197 .clean = internal_snapshot_clean,
2199 [TRANSACTION_ACTION_KIND_BLOCK_DIRTY_BITMAP_ADD] = {
2200 .instance_size = sizeof(BlockDirtyBitmapState),
2201 .prepare = block_dirty_bitmap_add_prepare,
2202 .abort = block_dirty_bitmap_add_abort,
2204 [TRANSACTION_ACTION_KIND_BLOCK_DIRTY_BITMAP_CLEAR] = {
2205 .instance_size = sizeof(BlockDirtyBitmapState),
2206 .prepare = block_dirty_bitmap_clear_prepare,
2207 .commit = block_dirty_bitmap_clear_commit,
2208 .abort = block_dirty_bitmap_clear_abort,
2213 * Allocate a TransactionProperties structure if necessary, and fill
2214 * that structure with desired defaults if they are unset.
2216 static TransactionProperties *get_transaction_properties(
2217 TransactionProperties *props)
2219 if (!props) {
2220 props = g_new0(TransactionProperties, 1);
2223 if (!props->has_completion_mode) {
2224 props->has_completion_mode = true;
2225 props->completion_mode = ACTION_COMPLETION_MODE_INDIVIDUAL;
2228 return props;
2232 * 'Atomic' group operations. The operations are performed as a set, and if
2233 * any fail then we roll back all operations in the group.
2235 void qmp_transaction(TransactionActionList *dev_list,
2236 bool has_props,
2237 struct TransactionProperties *props,
2238 Error **errp)
2240 TransactionActionList *dev_entry = dev_list;
2241 BlockJobTxn *block_job_txn = NULL;
2242 BlkActionState *state, *next;
2243 Error *local_err = NULL;
2245 QSIMPLEQ_HEAD(snap_bdrv_states, BlkActionState) snap_bdrv_states;
2246 QSIMPLEQ_INIT(&snap_bdrv_states);
2248 /* Does this transaction get canceled as a group on failure?
2249 * If not, we don't really need to make a BlockJobTxn.
2251 props = get_transaction_properties(props);
2252 if (props->completion_mode != ACTION_COMPLETION_MODE_INDIVIDUAL) {
2253 block_job_txn = block_job_txn_new();
2256 /* drain all i/o before any operations */
2257 bdrv_drain_all();
2259 /* We don't do anything in this loop that commits us to the operations */
2260 while (NULL != dev_entry) {
2261 TransactionAction *dev_info = NULL;
2262 const BlkActionOps *ops;
2264 dev_info = dev_entry->value;
2265 dev_entry = dev_entry->next;
2267 assert(dev_info->type < ARRAY_SIZE(actions));
2269 ops = &actions[dev_info->type];
2270 assert(ops->instance_size > 0);
2272 state = g_malloc0(ops->instance_size);
2273 state->ops = ops;
2274 state->action = dev_info;
2275 state->block_job_txn = block_job_txn;
2276 state->txn_props = props;
2277 QSIMPLEQ_INSERT_TAIL(&snap_bdrv_states, state, entry);
2279 state->ops->prepare(state, &local_err);
2280 if (local_err) {
2281 error_propagate(errp, local_err);
2282 goto delete_and_fail;
2286 QSIMPLEQ_FOREACH(state, &snap_bdrv_states, entry) {
2287 if (state->ops->commit) {
2288 state->ops->commit(state);
2292 /* success */
2293 goto exit;
2295 delete_and_fail:
2296 /* failure, and it is all-or-none; roll back all operations */
2297 QSIMPLEQ_FOREACH(state, &snap_bdrv_states, entry) {
2298 if (state->ops->abort) {
2299 state->ops->abort(state);
2302 exit:
2303 QSIMPLEQ_FOREACH_SAFE(state, &snap_bdrv_states, entry, next) {
2304 if (state->ops->clean) {
2305 state->ops->clean(state);
2307 g_free(state);
2309 if (!has_props) {
2310 qapi_free_TransactionProperties(props);
2312 block_job_txn_unref(block_job_txn);
2315 void qmp_eject(bool has_device, const char *device,
2316 bool has_id, const char *id,
2317 bool has_force, bool force, Error **errp)
2319 Error *local_err = NULL;
2320 int rc;
2322 if (!has_force) {
2323 force = false;
2326 rc = do_open_tray(has_device ? device : NULL,
2327 has_id ? id : NULL,
2328 force, &local_err);
2329 if (rc && rc != -ENOSYS) {
2330 error_propagate(errp, local_err);
2331 return;
2333 error_free(local_err);
2335 blockdev_remove_medium(has_device, device, has_id, id, errp);
2338 void qmp_block_passwd(bool has_device, const char *device,
2339 bool has_node_name, const char *node_name,
2340 const char *password, Error **errp)
2342 error_setg(errp,
2343 "Setting block passwords directly is no longer supported");
2347 * Attempt to open the tray of @device.
2348 * If @force, ignore its tray lock.
2349 * Else, if the tray is locked, don't open it, but ask the guest to open it.
2350 * On error, store an error through @errp and return -errno.
2351 * If @device does not exist, return -ENODEV.
2352 * If it has no removable media, return -ENOTSUP.
2353 * If it has no tray, return -ENOSYS.
2354 * If the guest was asked to open the tray, return -EINPROGRESS.
2355 * Else, return 0.
2357 static int do_open_tray(const char *blk_name, const char *qdev_id,
2358 bool force, Error **errp)
2360 BlockBackend *blk;
2361 const char *device = qdev_id ?: blk_name;
2362 bool locked;
2364 blk = qmp_get_blk(blk_name, qdev_id, errp);
2365 if (!blk) {
2366 return -ENODEV;
2369 if (!blk_dev_has_removable_media(blk)) {
2370 error_setg(errp, "Device '%s' is not removable", device);
2371 return -ENOTSUP;
2374 if (!blk_dev_has_tray(blk)) {
2375 error_setg(errp, "Device '%s' does not have a tray", device);
2376 return -ENOSYS;
2379 if (blk_dev_is_tray_open(blk)) {
2380 return 0;
2383 locked = blk_dev_is_medium_locked(blk);
2384 if (locked) {
2385 blk_dev_eject_request(blk, force);
2388 if (!locked || force) {
2389 blk_dev_change_media_cb(blk, false, &error_abort);
2392 if (locked && !force) {
2393 error_setg(errp, "Device '%s' is locked and force was not specified, "
2394 "wait for tray to open and try again", device);
2395 return -EINPROGRESS;
2398 return 0;
2401 void qmp_blockdev_open_tray(bool has_device, const char *device,
2402 bool has_id, const char *id,
2403 bool has_force, bool force,
2404 Error **errp)
2406 Error *local_err = NULL;
2407 int rc;
2409 if (!has_force) {
2410 force = false;
2412 rc = do_open_tray(has_device ? device : NULL,
2413 has_id ? id : NULL,
2414 force, &local_err);
2415 if (rc && rc != -ENOSYS && rc != -EINPROGRESS) {
2416 error_propagate(errp, local_err);
2417 return;
2419 error_free(local_err);
2422 void qmp_blockdev_close_tray(bool has_device, const char *device,
2423 bool has_id, const char *id,
2424 Error **errp)
2426 BlockBackend *blk;
2427 Error *local_err = NULL;
2429 device = has_device ? device : NULL;
2430 id = has_id ? id : NULL;
2432 blk = qmp_get_blk(device, id, errp);
2433 if (!blk) {
2434 return;
2437 if (!blk_dev_has_removable_media(blk)) {
2438 error_setg(errp, "Device '%s' is not removable", device ?: id);
2439 return;
2442 if (!blk_dev_has_tray(blk)) {
2443 /* Ignore this command on tray-less devices */
2444 return;
2447 if (!blk_dev_is_tray_open(blk)) {
2448 return;
2451 blk_dev_change_media_cb(blk, true, &local_err);
2452 if (local_err) {
2453 error_propagate(errp, local_err);
2454 return;
2458 static void blockdev_remove_medium(bool has_device, const char *device,
2459 bool has_id, const char *id, Error **errp)
2461 BlockBackend *blk;
2462 BlockDriverState *bs;
2463 AioContext *aio_context;
2464 bool has_attached_device;
2466 device = has_device ? device : NULL;
2467 id = has_id ? id : NULL;
2469 blk = qmp_get_blk(device, id, errp);
2470 if (!blk) {
2471 return;
2474 /* For BBs without a device, we can exchange the BDS tree at will */
2475 has_attached_device = blk_get_attached_dev(blk);
2477 if (has_attached_device && !blk_dev_has_removable_media(blk)) {
2478 error_setg(errp, "Device '%s' is not removable", device ?: id);
2479 return;
2482 if (has_attached_device && blk_dev_has_tray(blk) &&
2483 !blk_dev_is_tray_open(blk))
2485 error_setg(errp, "Tray of device '%s' is not open", device ?: id);
2486 return;
2489 bs = blk_bs(blk);
2490 if (!bs) {
2491 return;
2494 aio_context = bdrv_get_aio_context(bs);
2495 aio_context_acquire(aio_context);
2497 if (bdrv_op_is_blocked(bs, BLOCK_OP_TYPE_EJECT, errp)) {
2498 goto out;
2501 blk_remove_bs(blk);
2503 if (!blk_dev_has_tray(blk)) {
2504 /* For tray-less devices, blockdev-open-tray is a no-op (or may not be
2505 * called at all); therefore, the medium needs to be ejected here.
2506 * Do it after blk_remove_bs() so blk_is_inserted(blk) returns the @load
2507 * value passed here (i.e. false). */
2508 blk_dev_change_media_cb(blk, false, &error_abort);
2511 out:
2512 aio_context_release(aio_context);
2515 void qmp_blockdev_remove_medium(const char *id, Error **errp)
2517 blockdev_remove_medium(false, NULL, true, id, errp);
2520 static void qmp_blockdev_insert_anon_medium(BlockBackend *blk,
2521 BlockDriverState *bs, Error **errp)
2523 Error *local_err = NULL;
2524 bool has_device;
2525 int ret;
2527 /* For BBs without a device, we can exchange the BDS tree at will */
2528 has_device = blk_get_attached_dev(blk);
2530 if (has_device && !blk_dev_has_removable_media(blk)) {
2531 error_setg(errp, "Device is not removable");
2532 return;
2535 if (has_device && blk_dev_has_tray(blk) && !blk_dev_is_tray_open(blk)) {
2536 error_setg(errp, "Tray of the device is not open");
2537 return;
2540 if (blk_bs(blk)) {
2541 error_setg(errp, "There already is a medium in the device");
2542 return;
2545 ret = blk_insert_bs(blk, bs, errp);
2546 if (ret < 0) {
2547 return;
2550 if (!blk_dev_has_tray(blk)) {
2551 /* For tray-less devices, blockdev-close-tray is a no-op (or may not be
2552 * called at all); therefore, the medium needs to be pushed into the
2553 * slot here.
2554 * Do it after blk_insert_bs() so blk_is_inserted(blk) returns the @load
2555 * value passed here (i.e. true). */
2556 blk_dev_change_media_cb(blk, true, &local_err);
2557 if (local_err) {
2558 error_propagate(errp, local_err);
2559 blk_remove_bs(blk);
2560 return;
2565 static void blockdev_insert_medium(bool has_device, const char *device,
2566 bool has_id, const char *id,
2567 const char *node_name, Error **errp)
2569 BlockBackend *blk;
2570 BlockDriverState *bs;
2572 blk = qmp_get_blk(has_device ? device : NULL,
2573 has_id ? id : NULL,
2574 errp);
2575 if (!blk) {
2576 return;
2579 bs = bdrv_find_node(node_name);
2580 if (!bs) {
2581 error_setg(errp, "Node '%s' not found", node_name);
2582 return;
2585 if (bdrv_has_blk(bs)) {
2586 error_setg(errp, "Node '%s' is already in use", node_name);
2587 return;
2590 qmp_blockdev_insert_anon_medium(blk, bs, errp);
2593 void qmp_blockdev_insert_medium(const char *id, const char *node_name,
2594 Error **errp)
2596 blockdev_insert_medium(false, NULL, true, id, node_name, errp);
2599 void qmp_blockdev_change_medium(bool has_device, const char *device,
2600 bool has_id, const char *id,
2601 const char *filename,
2602 bool has_format, const char *format,
2603 bool has_read_only,
2604 BlockdevChangeReadOnlyMode read_only,
2605 Error **errp)
2607 BlockBackend *blk;
2608 BlockDriverState *medium_bs = NULL;
2609 int bdrv_flags;
2610 bool detect_zeroes;
2611 int rc;
2612 QDict *options = NULL;
2613 Error *err = NULL;
2615 blk = qmp_get_blk(has_device ? device : NULL,
2616 has_id ? id : NULL,
2617 errp);
2618 if (!blk) {
2619 goto fail;
2622 if (blk_bs(blk)) {
2623 blk_update_root_state(blk);
2626 bdrv_flags = blk_get_open_flags_from_root_state(blk);
2627 bdrv_flags &= ~(BDRV_O_TEMPORARY | BDRV_O_SNAPSHOT | BDRV_O_NO_BACKING |
2628 BDRV_O_PROTOCOL);
2630 if (!has_read_only) {
2631 read_only = BLOCKDEV_CHANGE_READ_ONLY_MODE_RETAIN;
2634 switch (read_only) {
2635 case BLOCKDEV_CHANGE_READ_ONLY_MODE_RETAIN:
2636 break;
2638 case BLOCKDEV_CHANGE_READ_ONLY_MODE_READ_ONLY:
2639 bdrv_flags &= ~BDRV_O_RDWR;
2640 break;
2642 case BLOCKDEV_CHANGE_READ_ONLY_MODE_READ_WRITE:
2643 bdrv_flags |= BDRV_O_RDWR;
2644 break;
2646 default:
2647 abort();
2650 options = qdict_new();
2651 detect_zeroes = blk_get_detect_zeroes_from_root_state(blk);
2652 qdict_put_str(options, "detect-zeroes", detect_zeroes ? "on" : "off");
2654 if (has_format) {
2655 qdict_put_str(options, "driver", format);
2658 medium_bs = bdrv_open(filename, NULL, options, bdrv_flags, errp);
2659 if (!medium_bs) {
2660 goto fail;
2663 rc = do_open_tray(has_device ? device : NULL,
2664 has_id ? id : NULL,
2665 false, &err);
2666 if (rc && rc != -ENOSYS) {
2667 error_propagate(errp, err);
2668 goto fail;
2670 error_free(err);
2671 err = NULL;
2673 blockdev_remove_medium(has_device, device, has_id, id, &err);
2674 if (err) {
2675 error_propagate(errp, err);
2676 goto fail;
2679 qmp_blockdev_insert_anon_medium(blk, medium_bs, &err);
2680 if (err) {
2681 error_propagate(errp, err);
2682 goto fail;
2685 qmp_blockdev_close_tray(has_device, device, has_id, id, errp);
2687 fail:
2688 /* If the medium has been inserted, the device has its own reference, so
2689 * ours must be relinquished; and if it has not been inserted successfully,
2690 * the reference must be relinquished anyway */
2691 bdrv_unref(medium_bs);
2694 /* throttling disk I/O limits */
2695 void qmp_block_set_io_throttle(BlockIOThrottle *arg, Error **errp)
2697 ThrottleConfig cfg;
2698 BlockDriverState *bs;
2699 BlockBackend *blk;
2700 AioContext *aio_context;
2702 blk = qmp_get_blk(arg->has_device ? arg->device : NULL,
2703 arg->has_id ? arg->id : NULL,
2704 errp);
2705 if (!blk) {
2706 return;
2709 aio_context = blk_get_aio_context(blk);
2710 aio_context_acquire(aio_context);
2712 bs = blk_bs(blk);
2713 if (!bs) {
2714 error_setg(errp, "Device has no medium");
2715 goto out;
2718 throttle_config_init(&cfg);
2719 cfg.buckets[THROTTLE_BPS_TOTAL].avg = arg->bps;
2720 cfg.buckets[THROTTLE_BPS_READ].avg = arg->bps_rd;
2721 cfg.buckets[THROTTLE_BPS_WRITE].avg = arg->bps_wr;
2723 cfg.buckets[THROTTLE_OPS_TOTAL].avg = arg->iops;
2724 cfg.buckets[THROTTLE_OPS_READ].avg = arg->iops_rd;
2725 cfg.buckets[THROTTLE_OPS_WRITE].avg = arg->iops_wr;
2727 if (arg->has_bps_max) {
2728 cfg.buckets[THROTTLE_BPS_TOTAL].max = arg->bps_max;
2730 if (arg->has_bps_rd_max) {
2731 cfg.buckets[THROTTLE_BPS_READ].max = arg->bps_rd_max;
2733 if (arg->has_bps_wr_max) {
2734 cfg.buckets[THROTTLE_BPS_WRITE].max = arg->bps_wr_max;
2736 if (arg->has_iops_max) {
2737 cfg.buckets[THROTTLE_OPS_TOTAL].max = arg->iops_max;
2739 if (arg->has_iops_rd_max) {
2740 cfg.buckets[THROTTLE_OPS_READ].max = arg->iops_rd_max;
2742 if (arg->has_iops_wr_max) {
2743 cfg.buckets[THROTTLE_OPS_WRITE].max = arg->iops_wr_max;
2746 if (arg->has_bps_max_length) {
2747 cfg.buckets[THROTTLE_BPS_TOTAL].burst_length = arg->bps_max_length;
2749 if (arg->has_bps_rd_max_length) {
2750 cfg.buckets[THROTTLE_BPS_READ].burst_length = arg->bps_rd_max_length;
2752 if (arg->has_bps_wr_max_length) {
2753 cfg.buckets[THROTTLE_BPS_WRITE].burst_length = arg->bps_wr_max_length;
2755 if (arg->has_iops_max_length) {
2756 cfg.buckets[THROTTLE_OPS_TOTAL].burst_length = arg->iops_max_length;
2758 if (arg->has_iops_rd_max_length) {
2759 cfg.buckets[THROTTLE_OPS_READ].burst_length = arg->iops_rd_max_length;
2761 if (arg->has_iops_wr_max_length) {
2762 cfg.buckets[THROTTLE_OPS_WRITE].burst_length = arg->iops_wr_max_length;
2765 if (arg->has_iops_size) {
2766 cfg.op_size = arg->iops_size;
2769 if (!throttle_is_valid(&cfg, errp)) {
2770 goto out;
2773 if (throttle_enabled(&cfg)) {
2774 /* Enable I/O limits if they're not enabled yet, otherwise
2775 * just update the throttling group. */
2776 if (!blk_get_public(blk)->throttle_group_member.throttle_state) {
2777 blk_io_limits_enable(blk,
2778 arg->has_group ? arg->group :
2779 arg->has_device ? arg->device :
2780 arg->id);
2781 } else if (arg->has_group) {
2782 blk_io_limits_update_group(blk, arg->group);
2784 /* Set the new throttling configuration */
2785 blk_set_io_limits(blk, &cfg);
2786 } else if (blk_get_public(blk)->throttle_group_member.throttle_state) {
2787 /* If all throttling settings are set to 0, disable I/O limits */
2788 blk_io_limits_disable(blk);
2791 out:
2792 aio_context_release(aio_context);
2795 void qmp_block_dirty_bitmap_add(const char *node, const char *name,
2796 bool has_granularity, uint32_t granularity,
2797 bool has_persistent, bool persistent,
2798 bool has_autoload, bool autoload,
2799 Error **errp)
2801 BlockDriverState *bs;
2802 BdrvDirtyBitmap *bitmap;
2804 if (!name || name[0] == '\0') {
2805 error_setg(errp, "Bitmap name cannot be empty");
2806 return;
2809 bs = bdrv_lookup_bs(node, node, errp);
2810 if (!bs) {
2811 return;
2814 if (has_granularity) {
2815 if (granularity < 512 || !is_power_of_2(granularity)) {
2816 error_setg(errp, "Granularity must be power of 2 "
2817 "and at least 512");
2818 return;
2820 } else {
2821 /* Default to cluster size, if available: */
2822 granularity = bdrv_get_default_bitmap_granularity(bs);
2825 if (!has_persistent) {
2826 persistent = false;
2829 if (has_autoload) {
2830 warn_report("Autoload option is deprecated and its value is ignored");
2833 if (persistent &&
2834 !bdrv_can_store_new_dirty_bitmap(bs, name, granularity, errp))
2836 return;
2839 bitmap = bdrv_create_dirty_bitmap(bs, granularity, name, errp);
2840 if (bitmap == NULL) {
2841 return;
2844 bdrv_dirty_bitmap_set_persistance(bitmap, persistent);
2847 void qmp_block_dirty_bitmap_remove(const char *node, const char *name,
2848 Error **errp)
2850 BlockDriverState *bs;
2851 BdrvDirtyBitmap *bitmap;
2852 Error *local_err = NULL;
2854 bitmap = block_dirty_bitmap_lookup(node, name, &bs, errp);
2855 if (!bitmap || !bs) {
2856 return;
2859 if (bdrv_dirty_bitmap_frozen(bitmap)) {
2860 error_setg(errp,
2861 "Bitmap '%s' is currently frozen and cannot be removed",
2862 name);
2863 return;
2866 if (bdrv_dirty_bitmap_get_persistance(bitmap)) {
2867 bdrv_remove_persistent_dirty_bitmap(bs, name, &local_err);
2868 if (local_err != NULL) {
2869 error_propagate(errp, local_err);
2870 return;
2874 bdrv_dirty_bitmap_make_anon(bitmap);
2875 bdrv_release_dirty_bitmap(bs, bitmap);
2879 * Completely clear a bitmap, for the purposes of synchronizing a bitmap
2880 * immediately after a full backup operation.
2882 void qmp_block_dirty_bitmap_clear(const char *node, const char *name,
2883 Error **errp)
2885 BdrvDirtyBitmap *bitmap;
2886 BlockDriverState *bs;
2888 bitmap = block_dirty_bitmap_lookup(node, name, &bs, errp);
2889 if (!bitmap || !bs) {
2890 return;
2893 if (bdrv_dirty_bitmap_frozen(bitmap)) {
2894 error_setg(errp,
2895 "Bitmap '%s' is currently frozen and cannot be modified",
2896 name);
2897 return;
2898 } else if (!bdrv_dirty_bitmap_enabled(bitmap)) {
2899 error_setg(errp,
2900 "Bitmap '%s' is currently disabled and cannot be cleared",
2901 name);
2902 return;
2903 } else if (bdrv_dirty_bitmap_readonly(bitmap)) {
2904 error_setg(errp, "Bitmap '%s' is readonly and cannot be cleared", name);
2905 return;
2908 bdrv_clear_dirty_bitmap(bitmap, NULL);
2911 BlockDirtyBitmapSha256 *qmp_x_debug_block_dirty_bitmap_sha256(const char *node,
2912 const char *name,
2913 Error **errp)
2915 BdrvDirtyBitmap *bitmap;
2916 BlockDriverState *bs;
2917 BlockDirtyBitmapSha256 *ret = NULL;
2918 char *sha256;
2920 bitmap = block_dirty_bitmap_lookup(node, name, &bs, errp);
2921 if (!bitmap || !bs) {
2922 return NULL;
2925 sha256 = bdrv_dirty_bitmap_sha256(bitmap, errp);
2926 if (sha256 == NULL) {
2927 return NULL;
2930 ret = g_new(BlockDirtyBitmapSha256, 1);
2931 ret->sha256 = sha256;
2933 return ret;
2936 void hmp_drive_del(Monitor *mon, const QDict *qdict)
2938 const char *id = qdict_get_str(qdict, "id");
2939 BlockBackend *blk;
2940 BlockDriverState *bs;
2941 AioContext *aio_context;
2942 Error *local_err = NULL;
2944 bs = bdrv_find_node(id);
2945 if (bs) {
2946 qmp_blockdev_del(id, &local_err);
2947 if (local_err) {
2948 error_report_err(local_err);
2950 return;
2953 blk = blk_by_name(id);
2954 if (!blk) {
2955 error_report("Device '%s' not found", id);
2956 return;
2959 if (!blk_legacy_dinfo(blk)) {
2960 error_report("Deleting device added with blockdev-add"
2961 " is not supported");
2962 return;
2965 aio_context = blk_get_aio_context(blk);
2966 aio_context_acquire(aio_context);
2968 bs = blk_bs(blk);
2969 if (bs) {
2970 if (bdrv_op_is_blocked(bs, BLOCK_OP_TYPE_DRIVE_DEL, &local_err)) {
2971 error_report_err(local_err);
2972 aio_context_release(aio_context);
2973 return;
2976 blk_remove_bs(blk);
2979 /* Make the BlockBackend and the attached BlockDriverState anonymous */
2980 monitor_remove_blk(blk);
2982 /* If this BlockBackend has a device attached to it, its refcount will be
2983 * decremented when the device is removed; otherwise we have to do so here.
2985 if (blk_get_attached_dev(blk)) {
2986 /* Further I/O must not pause the guest */
2987 blk_set_on_error(blk, BLOCKDEV_ON_ERROR_REPORT,
2988 BLOCKDEV_ON_ERROR_REPORT);
2989 } else {
2990 blk_unref(blk);
2993 aio_context_release(aio_context);
2996 void qmp_block_resize(bool has_device, const char *device,
2997 bool has_node_name, const char *node_name,
2998 int64_t size, Error **errp)
3000 Error *local_err = NULL;
3001 BlockBackend *blk = NULL;
3002 BlockDriverState *bs;
3003 AioContext *aio_context;
3004 int ret;
3006 bs = bdrv_lookup_bs(has_device ? device : NULL,
3007 has_node_name ? node_name : NULL,
3008 &local_err);
3009 if (local_err) {
3010 error_propagate(errp, local_err);
3011 return;
3014 aio_context = bdrv_get_aio_context(bs);
3015 aio_context_acquire(aio_context);
3017 if (!bdrv_is_first_non_filter(bs)) {
3018 error_setg(errp, QERR_FEATURE_DISABLED, "resize");
3019 goto out;
3022 if (size < 0) {
3023 error_setg(errp, QERR_INVALID_PARAMETER_VALUE, "size", "a >0 size");
3024 goto out;
3027 if (bdrv_op_is_blocked(bs, BLOCK_OP_TYPE_RESIZE, NULL)) {
3028 error_setg(errp, QERR_DEVICE_IN_USE, device);
3029 goto out;
3032 blk = blk_new(BLK_PERM_RESIZE, BLK_PERM_ALL);
3033 ret = blk_insert_bs(blk, bs, errp);
3034 if (ret < 0) {
3035 goto out;
3038 bdrv_drained_begin(bs);
3039 ret = blk_truncate(blk, size, PREALLOC_MODE_OFF, errp);
3040 bdrv_drained_end(bs);
3042 out:
3043 blk_unref(blk);
3044 aio_context_release(aio_context);
3047 void qmp_block_stream(bool has_job_id, const char *job_id, const char *device,
3048 bool has_base, const char *base,
3049 bool has_base_node, const char *base_node,
3050 bool has_backing_file, const char *backing_file,
3051 bool has_speed, int64_t speed,
3052 bool has_on_error, BlockdevOnError on_error,
3053 Error **errp)
3055 BlockDriverState *bs, *iter;
3056 BlockDriverState *base_bs = NULL;
3057 AioContext *aio_context;
3058 Error *local_err = NULL;
3059 const char *base_name = NULL;
3061 if (!has_on_error) {
3062 on_error = BLOCKDEV_ON_ERROR_REPORT;
3065 bs = bdrv_lookup_bs(device, device, errp);
3066 if (!bs) {
3067 return;
3070 aio_context = bdrv_get_aio_context(bs);
3071 aio_context_acquire(aio_context);
3073 if (has_base && has_base_node) {
3074 error_setg(errp, "'base' and 'base-node' cannot be specified "
3075 "at the same time");
3076 goto out;
3079 if (has_base) {
3080 base_bs = bdrv_find_backing_image(bs, base);
3081 if (base_bs == NULL) {
3082 error_setg(errp, QERR_BASE_NOT_FOUND, base);
3083 goto out;
3085 assert(bdrv_get_aio_context(base_bs) == aio_context);
3086 base_name = base;
3089 if (has_base_node) {
3090 base_bs = bdrv_lookup_bs(NULL, base_node, errp);
3091 if (!base_bs) {
3092 goto out;
3094 if (bs == base_bs || !bdrv_chain_contains(bs, base_bs)) {
3095 error_setg(errp, "Node '%s' is not a backing image of '%s'",
3096 base_node, device);
3097 goto out;
3099 assert(bdrv_get_aio_context(base_bs) == aio_context);
3100 base_name = base_bs->filename;
3103 /* Check for op blockers in the whole chain between bs and base */
3104 for (iter = bs; iter && iter != base_bs; iter = backing_bs(iter)) {
3105 if (bdrv_op_is_blocked(iter, BLOCK_OP_TYPE_STREAM, errp)) {
3106 goto out;
3110 /* if we are streaming the entire chain, the result will have no backing
3111 * file, and specifying one is therefore an error */
3112 if (base_bs == NULL && has_backing_file) {
3113 error_setg(errp, "backing file specified, but streaming the "
3114 "entire chain");
3115 goto out;
3118 /* backing_file string overrides base bs filename */
3119 base_name = has_backing_file ? backing_file : base_name;
3121 stream_start(has_job_id ? job_id : NULL, bs, base_bs, base_name,
3122 has_speed ? speed : 0, on_error, &local_err);
3123 if (local_err) {
3124 error_propagate(errp, local_err);
3125 goto out;
3128 trace_qmp_block_stream(bs, bs->job);
3130 out:
3131 aio_context_release(aio_context);
3134 void qmp_block_commit(bool has_job_id, const char *job_id, const char *device,
3135 bool has_base, const char *base,
3136 bool has_top, const char *top,
3137 bool has_backing_file, const char *backing_file,
3138 bool has_speed, int64_t speed,
3139 bool has_filter_node_name, const char *filter_node_name,
3140 Error **errp)
3142 BlockDriverState *bs;
3143 BlockDriverState *iter;
3144 BlockDriverState *base_bs, *top_bs;
3145 AioContext *aio_context;
3146 Error *local_err = NULL;
3147 /* This will be part of the QMP command, if/when the
3148 * BlockdevOnError change for blkmirror makes it in
3150 BlockdevOnError on_error = BLOCKDEV_ON_ERROR_REPORT;
3152 if (!has_speed) {
3153 speed = 0;
3155 if (!has_filter_node_name) {
3156 filter_node_name = NULL;
3159 /* Important Note:
3160 * libvirt relies on the DeviceNotFound error class in order to probe for
3161 * live commit feature versions; for this to work, we must make sure to
3162 * perform the device lookup before any generic errors that may occur in a
3163 * scenario in which all optional arguments are omitted. */
3164 bs = qmp_get_root_bs(device, &local_err);
3165 if (!bs) {
3166 bs = bdrv_lookup_bs(device, device, NULL);
3167 if (!bs) {
3168 error_free(local_err);
3169 error_set(errp, ERROR_CLASS_DEVICE_NOT_FOUND,
3170 "Device '%s' not found", device);
3171 } else {
3172 error_propagate(errp, local_err);
3174 return;
3177 aio_context = bdrv_get_aio_context(bs);
3178 aio_context_acquire(aio_context);
3180 if (bdrv_op_is_blocked(bs, BLOCK_OP_TYPE_COMMIT_SOURCE, errp)) {
3181 goto out;
3184 /* default top_bs is the active layer */
3185 top_bs = bs;
3187 if (has_top && top) {
3188 if (strcmp(bs->filename, top) != 0) {
3189 top_bs = bdrv_find_backing_image(bs, top);
3193 if (top_bs == NULL) {
3194 error_setg(errp, "Top image file %s not found", top ? top : "NULL");
3195 goto out;
3198 assert(bdrv_get_aio_context(top_bs) == aio_context);
3200 if (has_base && base) {
3201 base_bs = bdrv_find_backing_image(top_bs, base);
3202 } else {
3203 base_bs = bdrv_find_base(top_bs);
3206 if (base_bs == NULL) {
3207 error_setg(errp, QERR_BASE_NOT_FOUND, base ? base : "NULL");
3208 goto out;
3211 assert(bdrv_get_aio_context(base_bs) == aio_context);
3213 for (iter = top_bs; iter != backing_bs(base_bs); iter = backing_bs(iter)) {
3214 if (bdrv_op_is_blocked(iter, BLOCK_OP_TYPE_COMMIT_TARGET, errp)) {
3215 goto out;
3219 /* Do not allow attempts to commit an image into itself */
3220 if (top_bs == base_bs) {
3221 error_setg(errp, "cannot commit an image into itself");
3222 goto out;
3225 if (top_bs == bs) {
3226 if (has_backing_file) {
3227 error_setg(errp, "'backing-file' specified,"
3228 " but 'top' is the active layer");
3229 goto out;
3231 commit_active_start(has_job_id ? job_id : NULL, bs, base_bs,
3232 BLOCK_JOB_DEFAULT, speed, on_error,
3233 filter_node_name, NULL, NULL, false, &local_err);
3234 } else {
3235 BlockDriverState *overlay_bs = bdrv_find_overlay(bs, top_bs);
3236 if (bdrv_op_is_blocked(overlay_bs, BLOCK_OP_TYPE_COMMIT_TARGET, errp)) {
3237 goto out;
3239 commit_start(has_job_id ? job_id : NULL, bs, base_bs, top_bs, speed,
3240 on_error, has_backing_file ? backing_file : NULL,
3241 filter_node_name, &local_err);
3243 if (local_err != NULL) {
3244 error_propagate(errp, local_err);
3245 goto out;
3248 out:
3249 aio_context_release(aio_context);
3252 static BlockJob *do_drive_backup(DriveBackup *backup, BlockJobTxn *txn,
3253 Error **errp)
3255 BlockDriverState *bs;
3256 BlockDriverState *target_bs;
3257 BlockDriverState *source = NULL;
3258 BlockJob *job = NULL;
3259 BdrvDirtyBitmap *bmap = NULL;
3260 AioContext *aio_context;
3261 QDict *options = NULL;
3262 Error *local_err = NULL;
3263 int flags;
3264 int64_t size;
3265 bool set_backing_hd = false;
3267 if (!backup->has_speed) {
3268 backup->speed = 0;
3270 if (!backup->has_on_source_error) {
3271 backup->on_source_error = BLOCKDEV_ON_ERROR_REPORT;
3273 if (!backup->has_on_target_error) {
3274 backup->on_target_error = BLOCKDEV_ON_ERROR_REPORT;
3276 if (!backup->has_mode) {
3277 backup->mode = NEW_IMAGE_MODE_ABSOLUTE_PATHS;
3279 if (!backup->has_job_id) {
3280 backup->job_id = NULL;
3282 if (!backup->has_compress) {
3283 backup->compress = false;
3286 bs = qmp_get_root_bs(backup->device, errp);
3287 if (!bs) {
3288 return NULL;
3291 aio_context = bdrv_get_aio_context(bs);
3292 aio_context_acquire(aio_context);
3294 if (!backup->has_format) {
3295 backup->format = backup->mode == NEW_IMAGE_MODE_EXISTING ?
3296 NULL : (char*) bs->drv->format_name;
3299 /* Early check to avoid creating target */
3300 if (bdrv_op_is_blocked(bs, BLOCK_OP_TYPE_BACKUP_SOURCE, errp)) {
3301 goto out;
3304 flags = bs->open_flags | BDRV_O_RDWR;
3306 /* See if we have a backing HD we can use to create our new image
3307 * on top of. */
3308 if (backup->sync == MIRROR_SYNC_MODE_TOP) {
3309 source = backing_bs(bs);
3310 if (!source) {
3311 backup->sync = MIRROR_SYNC_MODE_FULL;
3314 if (backup->sync == MIRROR_SYNC_MODE_NONE) {
3315 source = bs;
3316 flags |= BDRV_O_NO_BACKING;
3317 set_backing_hd = true;
3320 size = bdrv_getlength(bs);
3321 if (size < 0) {
3322 error_setg_errno(errp, -size, "bdrv_getlength failed");
3323 goto out;
3326 if (backup->mode != NEW_IMAGE_MODE_EXISTING) {
3327 assert(backup->format);
3328 if (source) {
3329 bdrv_img_create(backup->target, backup->format, source->filename,
3330 source->drv->format_name, NULL,
3331 size, flags, false, &local_err);
3332 } else {
3333 bdrv_img_create(backup->target, backup->format, NULL, NULL, NULL,
3334 size, flags, false, &local_err);
3338 if (local_err) {
3339 error_propagate(errp, local_err);
3340 goto out;
3343 if (backup->format) {
3344 if (!options) {
3345 options = qdict_new();
3347 qdict_put_str(options, "driver", backup->format);
3350 target_bs = bdrv_open(backup->target, NULL, options, flags, errp);
3351 if (!target_bs) {
3352 goto out;
3355 bdrv_set_aio_context(target_bs, aio_context);
3357 if (set_backing_hd) {
3358 bdrv_set_backing_hd(target_bs, source, &local_err);
3359 if (local_err) {
3360 bdrv_unref(target_bs);
3361 goto out;
3365 if (backup->has_bitmap) {
3366 bmap = bdrv_find_dirty_bitmap(bs, backup->bitmap);
3367 if (!bmap) {
3368 error_setg(errp, "Bitmap '%s' could not be found", backup->bitmap);
3369 bdrv_unref(target_bs);
3370 goto out;
3374 job = backup_job_create(backup->job_id, bs, target_bs, backup->speed,
3375 backup->sync, bmap, backup->compress,
3376 backup->on_source_error, backup->on_target_error,
3377 BLOCK_JOB_DEFAULT, NULL, NULL, txn, &local_err);
3378 bdrv_unref(target_bs);
3379 if (local_err != NULL) {
3380 error_propagate(errp, local_err);
3381 goto out;
3384 out:
3385 aio_context_release(aio_context);
3386 return job;
3389 void qmp_drive_backup(DriveBackup *arg, Error **errp)
3392 BlockJob *job;
3393 job = do_drive_backup(arg, NULL, errp);
3394 if (job) {
3395 block_job_start(job);
3399 BlockDeviceInfoList *qmp_query_named_block_nodes(Error **errp)
3401 return bdrv_named_nodes_list(errp);
3404 BlockJob *do_blockdev_backup(BlockdevBackup *backup, BlockJobTxn *txn,
3405 Error **errp)
3407 BlockDriverState *bs;
3408 BlockDriverState *target_bs;
3409 Error *local_err = NULL;
3410 AioContext *aio_context;
3411 BlockJob *job = NULL;
3413 if (!backup->has_speed) {
3414 backup->speed = 0;
3416 if (!backup->has_on_source_error) {
3417 backup->on_source_error = BLOCKDEV_ON_ERROR_REPORT;
3419 if (!backup->has_on_target_error) {
3420 backup->on_target_error = BLOCKDEV_ON_ERROR_REPORT;
3422 if (!backup->has_job_id) {
3423 backup->job_id = NULL;
3425 if (!backup->has_compress) {
3426 backup->compress = false;
3429 bs = qmp_get_root_bs(backup->device, errp);
3430 if (!bs) {
3431 return NULL;
3434 aio_context = bdrv_get_aio_context(bs);
3435 aio_context_acquire(aio_context);
3437 target_bs = bdrv_lookup_bs(backup->target, backup->target, errp);
3438 if (!target_bs) {
3439 goto out;
3442 if (bdrv_get_aio_context(target_bs) != aio_context) {
3443 if (!bdrv_has_blk(target_bs)) {
3444 /* The target BDS is not attached, we can safely move it to another
3445 * AioContext. */
3446 bdrv_set_aio_context(target_bs, aio_context);
3447 } else {
3448 error_setg(errp, "Target is attached to a different thread from "
3449 "source.");
3450 goto out;
3453 job = backup_job_create(backup->job_id, bs, target_bs, backup->speed,
3454 backup->sync, NULL, backup->compress,
3455 backup->on_source_error, backup->on_target_error,
3456 BLOCK_JOB_DEFAULT, NULL, NULL, txn, &local_err);
3457 if (local_err != NULL) {
3458 error_propagate(errp, local_err);
3460 out:
3461 aio_context_release(aio_context);
3462 return job;
3465 void qmp_blockdev_backup(BlockdevBackup *arg, Error **errp)
3467 BlockJob *job;
3468 job = do_blockdev_backup(arg, NULL, errp);
3469 if (job) {
3470 block_job_start(job);
3474 /* Parameter check and block job starting for drive mirroring.
3475 * Caller should hold @device and @target's aio context (must be the same).
3477 static void blockdev_mirror_common(const char *job_id, BlockDriverState *bs,
3478 BlockDriverState *target,
3479 bool has_replaces, const char *replaces,
3480 enum MirrorSyncMode sync,
3481 BlockMirrorBackingMode backing_mode,
3482 bool has_speed, int64_t speed,
3483 bool has_granularity, uint32_t granularity,
3484 bool has_buf_size, int64_t buf_size,
3485 bool has_on_source_error,
3486 BlockdevOnError on_source_error,
3487 bool has_on_target_error,
3488 BlockdevOnError on_target_error,
3489 bool has_unmap, bool unmap,
3490 bool has_filter_node_name,
3491 const char *filter_node_name,
3492 Error **errp)
3495 if (!has_speed) {
3496 speed = 0;
3498 if (!has_on_source_error) {
3499 on_source_error = BLOCKDEV_ON_ERROR_REPORT;
3501 if (!has_on_target_error) {
3502 on_target_error = BLOCKDEV_ON_ERROR_REPORT;
3504 if (!has_granularity) {
3505 granularity = 0;
3507 if (!has_buf_size) {
3508 buf_size = 0;
3510 if (!has_unmap) {
3511 unmap = true;
3513 if (!has_filter_node_name) {
3514 filter_node_name = NULL;
3517 if (granularity != 0 && (granularity < 512 || granularity > 1048576 * 64)) {
3518 error_setg(errp, QERR_INVALID_PARAMETER_VALUE, "granularity",
3519 "a value in range [512B, 64MB]");
3520 return;
3522 if (granularity & (granularity - 1)) {
3523 error_setg(errp, QERR_INVALID_PARAMETER_VALUE, "granularity",
3524 "power of 2");
3525 return;
3528 if (bdrv_op_is_blocked(bs, BLOCK_OP_TYPE_MIRROR_SOURCE, errp)) {
3529 return;
3531 if (bdrv_op_is_blocked(target, BLOCK_OP_TYPE_MIRROR_TARGET, errp)) {
3532 return;
3535 if (!bs->backing && sync == MIRROR_SYNC_MODE_TOP) {
3536 sync = MIRROR_SYNC_MODE_FULL;
3539 /* pass the node name to replace to mirror start since it's loose coupling
3540 * and will allow to check whether the node still exist at mirror completion
3542 mirror_start(job_id, bs, target,
3543 has_replaces ? replaces : NULL,
3544 speed, granularity, buf_size, sync, backing_mode,
3545 on_source_error, on_target_error, unmap, filter_node_name,
3546 errp);
3549 void qmp_drive_mirror(DriveMirror *arg, Error **errp)
3551 BlockDriverState *bs;
3552 BlockDriverState *source, *target_bs;
3553 AioContext *aio_context;
3554 BlockMirrorBackingMode backing_mode;
3555 Error *local_err = NULL;
3556 QDict *options = NULL;
3557 int flags;
3558 int64_t size;
3559 const char *format = arg->format;
3561 bs = qmp_get_root_bs(arg->device, errp);
3562 if (!bs) {
3563 return;
3566 /* Early check to avoid creating target */
3567 if (bdrv_op_is_blocked(bs, BLOCK_OP_TYPE_MIRROR_SOURCE, errp)) {
3568 return;
3571 aio_context = bdrv_get_aio_context(bs);
3572 aio_context_acquire(aio_context);
3574 if (!arg->has_mode) {
3575 arg->mode = NEW_IMAGE_MODE_ABSOLUTE_PATHS;
3578 if (!arg->has_format) {
3579 format = (arg->mode == NEW_IMAGE_MODE_EXISTING
3580 ? NULL : bs->drv->format_name);
3583 flags = bs->open_flags | BDRV_O_RDWR;
3584 source = backing_bs(bs);
3585 if (!source && arg->sync == MIRROR_SYNC_MODE_TOP) {
3586 arg->sync = MIRROR_SYNC_MODE_FULL;
3588 if (arg->sync == MIRROR_SYNC_MODE_NONE) {
3589 source = bs;
3592 size = bdrv_getlength(bs);
3593 if (size < 0) {
3594 error_setg_errno(errp, -size, "bdrv_getlength failed");
3595 goto out;
3598 if (arg->has_replaces) {
3599 BlockDriverState *to_replace_bs;
3600 AioContext *replace_aio_context;
3601 int64_t replace_size;
3603 if (!arg->has_node_name) {
3604 error_setg(errp, "a node-name must be provided when replacing a"
3605 " named node of the graph");
3606 goto out;
3609 to_replace_bs = check_to_replace_node(bs, arg->replaces, &local_err);
3611 if (!to_replace_bs) {
3612 error_propagate(errp, local_err);
3613 goto out;
3616 replace_aio_context = bdrv_get_aio_context(to_replace_bs);
3617 aio_context_acquire(replace_aio_context);
3618 replace_size = bdrv_getlength(to_replace_bs);
3619 aio_context_release(replace_aio_context);
3621 if (size != replace_size) {
3622 error_setg(errp, "cannot replace image with a mirror image of "
3623 "different size");
3624 goto out;
3628 if (arg->mode == NEW_IMAGE_MODE_ABSOLUTE_PATHS) {
3629 backing_mode = MIRROR_SOURCE_BACKING_CHAIN;
3630 } else {
3631 backing_mode = MIRROR_OPEN_BACKING_CHAIN;
3634 /* Don't open backing image in create() */
3635 flags |= BDRV_O_NO_BACKING;
3637 if ((arg->sync == MIRROR_SYNC_MODE_FULL || !source)
3638 && arg->mode != NEW_IMAGE_MODE_EXISTING)
3640 /* create new image w/o backing file */
3641 assert(format);
3642 bdrv_img_create(arg->target, format,
3643 NULL, NULL, NULL, size, flags, false, &local_err);
3644 } else {
3645 switch (arg->mode) {
3646 case NEW_IMAGE_MODE_EXISTING:
3647 break;
3648 case NEW_IMAGE_MODE_ABSOLUTE_PATHS:
3649 /* create new image with backing file */
3650 bdrv_img_create(arg->target, format,
3651 source->filename,
3652 source->drv->format_name,
3653 NULL, size, flags, false, &local_err);
3654 break;
3655 default:
3656 abort();
3660 if (local_err) {
3661 error_propagate(errp, local_err);
3662 goto out;
3665 options = qdict_new();
3666 if (arg->has_node_name) {
3667 qdict_put_str(options, "node-name", arg->node_name);
3669 if (format) {
3670 qdict_put_str(options, "driver", format);
3673 /* Mirroring takes care of copy-on-write using the source's backing
3674 * file.
3676 target_bs = bdrv_open(arg->target, NULL, options, flags, errp);
3677 if (!target_bs) {
3678 goto out;
3681 bdrv_set_aio_context(target_bs, aio_context);
3683 blockdev_mirror_common(arg->has_job_id ? arg->job_id : NULL, bs, target_bs,
3684 arg->has_replaces, arg->replaces, arg->sync,
3685 backing_mode, arg->has_speed, arg->speed,
3686 arg->has_granularity, arg->granularity,
3687 arg->has_buf_size, arg->buf_size,
3688 arg->has_on_source_error, arg->on_source_error,
3689 arg->has_on_target_error, arg->on_target_error,
3690 arg->has_unmap, arg->unmap,
3691 false, NULL,
3692 &local_err);
3693 bdrv_unref(target_bs);
3694 error_propagate(errp, local_err);
3695 out:
3696 aio_context_release(aio_context);
3699 void qmp_blockdev_mirror(bool has_job_id, const char *job_id,
3700 const char *device, const char *target,
3701 bool has_replaces, const char *replaces,
3702 MirrorSyncMode sync,
3703 bool has_speed, int64_t speed,
3704 bool has_granularity, uint32_t granularity,
3705 bool has_buf_size, int64_t buf_size,
3706 bool has_on_source_error,
3707 BlockdevOnError on_source_error,
3708 bool has_on_target_error,
3709 BlockdevOnError on_target_error,
3710 bool has_filter_node_name,
3711 const char *filter_node_name,
3712 Error **errp)
3714 BlockDriverState *bs;
3715 BlockDriverState *target_bs;
3716 AioContext *aio_context;
3717 BlockMirrorBackingMode backing_mode = MIRROR_LEAVE_BACKING_CHAIN;
3718 Error *local_err = NULL;
3720 bs = qmp_get_root_bs(device, errp);
3721 if (!bs) {
3722 return;
3725 target_bs = bdrv_lookup_bs(target, target, errp);
3726 if (!target_bs) {
3727 return;
3730 aio_context = bdrv_get_aio_context(bs);
3731 aio_context_acquire(aio_context);
3733 bdrv_set_aio_context(target_bs, aio_context);
3735 blockdev_mirror_common(has_job_id ? job_id : NULL, bs, target_bs,
3736 has_replaces, replaces, sync, backing_mode,
3737 has_speed, speed,
3738 has_granularity, granularity,
3739 has_buf_size, buf_size,
3740 has_on_source_error, on_source_error,
3741 has_on_target_error, on_target_error,
3742 true, true,
3743 has_filter_node_name, filter_node_name,
3744 &local_err);
3745 error_propagate(errp, local_err);
3747 aio_context_release(aio_context);
3750 /* Get a block job using its ID and acquire its AioContext */
3751 static BlockJob *find_block_job(const char *id, AioContext **aio_context,
3752 Error **errp)
3754 BlockJob *job;
3756 assert(id != NULL);
3758 *aio_context = NULL;
3760 job = block_job_get(id);
3762 if (!job) {
3763 error_set(errp, ERROR_CLASS_DEVICE_NOT_ACTIVE,
3764 "Block job '%s' not found", id);
3765 return NULL;
3768 *aio_context = blk_get_aio_context(job->blk);
3769 aio_context_acquire(*aio_context);
3771 return job;
3774 void qmp_block_job_set_speed(const char *device, int64_t speed, Error **errp)
3776 AioContext *aio_context;
3777 BlockJob *job = find_block_job(device, &aio_context, errp);
3779 if (!job) {
3780 return;
3783 block_job_set_speed(job, speed, errp);
3784 aio_context_release(aio_context);
3787 void qmp_block_job_cancel(const char *device,
3788 bool has_force, bool force, Error **errp)
3790 AioContext *aio_context;
3791 BlockJob *job = find_block_job(device, &aio_context, errp);
3793 if (!job) {
3794 return;
3797 if (!has_force) {
3798 force = false;
3801 if (block_job_user_paused(job) && !force) {
3802 error_setg(errp, "The block job for device '%s' is currently paused",
3803 device);
3804 goto out;
3807 trace_qmp_block_job_cancel(job);
3808 block_job_cancel(job);
3809 out:
3810 aio_context_release(aio_context);
3813 void qmp_block_job_pause(const char *device, Error **errp)
3815 AioContext *aio_context;
3816 BlockJob *job = find_block_job(device, &aio_context, errp);
3818 if (!job || block_job_user_paused(job)) {
3819 return;
3822 trace_qmp_block_job_pause(job);
3823 block_job_user_pause(job);
3824 aio_context_release(aio_context);
3827 void qmp_block_job_resume(const char *device, Error **errp)
3829 AioContext *aio_context;
3830 BlockJob *job = find_block_job(device, &aio_context, errp);
3832 if (!job || !block_job_user_paused(job)) {
3833 return;
3836 trace_qmp_block_job_resume(job);
3837 block_job_user_resume(job);
3838 aio_context_release(aio_context);
3841 void qmp_block_job_complete(const char *device, Error **errp)
3843 AioContext *aio_context;
3844 BlockJob *job = find_block_job(device, &aio_context, errp);
3846 if (!job) {
3847 return;
3850 trace_qmp_block_job_complete(job);
3851 block_job_complete(job, errp);
3852 aio_context_release(aio_context);
3855 void qmp_change_backing_file(const char *device,
3856 const char *image_node_name,
3857 const char *backing_file,
3858 Error **errp)
3860 BlockDriverState *bs = NULL;
3861 AioContext *aio_context;
3862 BlockDriverState *image_bs = NULL;
3863 Error *local_err = NULL;
3864 bool ro;
3865 int open_flags;
3866 int ret;
3868 bs = qmp_get_root_bs(device, errp);
3869 if (!bs) {
3870 return;
3873 aio_context = bdrv_get_aio_context(bs);
3874 aio_context_acquire(aio_context);
3876 image_bs = bdrv_lookup_bs(NULL, image_node_name, &local_err);
3877 if (local_err) {
3878 error_propagate(errp, local_err);
3879 goto out;
3882 if (!image_bs) {
3883 error_setg(errp, "image file not found");
3884 goto out;
3887 if (bdrv_find_base(image_bs) == image_bs) {
3888 error_setg(errp, "not allowing backing file change on an image "
3889 "without a backing file");
3890 goto out;
3893 /* even though we are not necessarily operating on bs, we need it to
3894 * determine if block ops are currently prohibited on the chain */
3895 if (bdrv_op_is_blocked(bs, BLOCK_OP_TYPE_CHANGE, errp)) {
3896 goto out;
3899 /* final sanity check */
3900 if (!bdrv_chain_contains(bs, image_bs)) {
3901 error_setg(errp, "'%s' and image file are not in the same chain",
3902 device);
3903 goto out;
3906 /* if not r/w, reopen to make r/w */
3907 open_flags = image_bs->open_flags;
3908 ro = bdrv_is_read_only(image_bs);
3910 if (ro) {
3911 bdrv_reopen(image_bs, open_flags | BDRV_O_RDWR, &local_err);
3912 if (local_err) {
3913 error_propagate(errp, local_err);
3914 goto out;
3918 ret = bdrv_change_backing_file(image_bs, backing_file,
3919 image_bs->drv ? image_bs->drv->format_name : "");
3921 if (ret < 0) {
3922 error_setg_errno(errp, -ret, "Could not change backing file to '%s'",
3923 backing_file);
3924 /* don't exit here, so we can try to restore open flags if
3925 * appropriate */
3928 if (ro) {
3929 bdrv_reopen(image_bs, open_flags, &local_err);
3930 error_propagate(errp, local_err);
3933 out:
3934 aio_context_release(aio_context);
3937 void hmp_drive_add_node(Monitor *mon, const char *optstr)
3939 QemuOpts *opts;
3940 QDict *qdict;
3941 Error *local_err = NULL;
3943 opts = qemu_opts_parse_noisily(&qemu_drive_opts, optstr, false);
3944 if (!opts) {
3945 return;
3948 qdict = qemu_opts_to_qdict(opts, NULL);
3950 if (!qdict_get_try_str(qdict, "node-name")) {
3951 QDECREF(qdict);
3952 error_report("'node-name' needs to be specified");
3953 goto out;
3956 BlockDriverState *bs = bds_tree_init(qdict, &local_err);
3957 if (!bs) {
3958 error_report_err(local_err);
3959 goto out;
3962 QTAILQ_INSERT_TAIL(&monitor_bdrv_states, bs, monitor_list);
3964 out:
3965 qemu_opts_del(opts);
3968 void qmp_blockdev_add(BlockdevOptions *options, Error **errp)
3970 BlockDriverState *bs;
3971 QObject *obj;
3972 Visitor *v = qobject_output_visitor_new(&obj);
3973 QDict *qdict;
3974 const QDictEntry *ent;
3975 Error *local_err = NULL;
3977 visit_type_BlockdevOptions(v, NULL, &options, &local_err);
3978 if (local_err) {
3979 error_propagate(errp, local_err);
3980 goto fail;
3983 visit_complete(v, &obj);
3984 qdict = qobject_to_qdict(obj);
3986 qdict_flatten(qdict);
3989 * Rewrite "backing": null to "backing": ""
3990 * TODO Rewrite "" to null instead, and perhaps not even here
3992 for (ent = qdict_first(qdict); ent; ent = qdict_next(qdict, ent)) {
3993 char *dot = strrchr(ent->key, '.');
3995 if (!strcmp(dot ? dot + 1 : ent->key, "backing")
3996 && qobject_type(ent->value) == QTYPE_QNULL) {
3997 qdict_put(qdict, ent->key, qstring_new());
4001 if (!qdict_get_try_str(qdict, "node-name")) {
4002 error_setg(errp, "'node-name' must be specified for the root node");
4003 goto fail;
4006 bs = bds_tree_init(qdict, errp);
4007 if (!bs) {
4008 goto fail;
4011 QTAILQ_INSERT_TAIL(&monitor_bdrv_states, bs, monitor_list);
4013 fail:
4014 visit_free(v);
4017 void qmp_blockdev_del(const char *node_name, Error **errp)
4019 AioContext *aio_context;
4020 BlockDriverState *bs;
4022 bs = bdrv_find_node(node_name);
4023 if (!bs) {
4024 error_setg(errp, "Cannot find node %s", node_name);
4025 return;
4027 if (bdrv_has_blk(bs)) {
4028 error_setg(errp, "Node %s is in use", node_name);
4029 return;
4031 aio_context = bdrv_get_aio_context(bs);
4032 aio_context_acquire(aio_context);
4034 if (bdrv_op_is_blocked(bs, BLOCK_OP_TYPE_DRIVE_DEL, errp)) {
4035 goto out;
4038 if (!bs->monitor_list.tqe_prev) {
4039 error_setg(errp, "Node %s is not owned by the monitor",
4040 bs->node_name);
4041 goto out;
4044 if (bs->refcnt > 1) {
4045 error_setg(errp, "Block device %s is in use",
4046 bdrv_get_device_or_node_name(bs));
4047 goto out;
4050 QTAILQ_REMOVE(&monitor_bdrv_states, bs, monitor_list);
4051 bdrv_unref(bs);
4053 out:
4054 aio_context_release(aio_context);
4057 static BdrvChild *bdrv_find_child(BlockDriverState *parent_bs,
4058 const char *child_name)
4060 BdrvChild *child;
4062 QLIST_FOREACH(child, &parent_bs->children, next) {
4063 if (strcmp(child->name, child_name) == 0) {
4064 return child;
4068 return NULL;
4071 void qmp_x_blockdev_change(const char *parent, bool has_child,
4072 const char *child, bool has_node,
4073 const char *node, Error **errp)
4075 BlockDriverState *parent_bs, *new_bs = NULL;
4076 BdrvChild *p_child;
4078 parent_bs = bdrv_lookup_bs(parent, parent, errp);
4079 if (!parent_bs) {
4080 return;
4083 if (has_child == has_node) {
4084 if (has_child) {
4085 error_setg(errp, "The parameters child and node are in conflict");
4086 } else {
4087 error_setg(errp, "Either child or node must be specified");
4089 return;
4092 if (has_child) {
4093 p_child = bdrv_find_child(parent_bs, child);
4094 if (!p_child) {
4095 error_setg(errp, "Node '%s' does not have child '%s'",
4096 parent, child);
4097 return;
4099 bdrv_del_child(parent_bs, p_child, errp);
4102 if (has_node) {
4103 new_bs = bdrv_find_node(node);
4104 if (!new_bs) {
4105 error_setg(errp, "Node '%s' not found", node);
4106 return;
4108 bdrv_add_child(parent_bs, new_bs, errp);
4112 BlockJobInfoList *qmp_query_block_jobs(Error **errp)
4114 BlockJobInfoList *head = NULL, **p_next = &head;
4115 BlockJob *job;
4117 for (job = block_job_next(NULL); job; job = block_job_next(job)) {
4118 BlockJobInfoList *elem;
4119 AioContext *aio_context;
4121 if (block_job_is_internal(job)) {
4122 continue;
4124 elem = g_new0(BlockJobInfoList, 1);
4125 aio_context = blk_get_aio_context(job->blk);
4126 aio_context_acquire(aio_context);
4127 elem->value = block_job_query(job, errp);
4128 aio_context_release(aio_context);
4129 if (!elem->value) {
4130 g_free(elem);
4131 qapi_free_BlockJobInfoList(head);
4132 return NULL;
4134 *p_next = elem;
4135 p_next = &elem->next;
4138 return head;
4141 void qmp_x_blockdev_set_iothread(const char *node_name, StrOrNull *iothread,
4142 bool has_force, bool force, Error **errp)
4144 AioContext *old_context;
4145 AioContext *new_context;
4146 BlockDriverState *bs;
4148 bs = bdrv_find_node(node_name);
4149 if (!bs) {
4150 error_setg(errp, "Cannot find node %s", node_name);
4151 return;
4154 /* Protects against accidents. */
4155 if (!(has_force && force) && bdrv_has_blk(bs)) {
4156 error_setg(errp, "Node %s is associated with a BlockBackend and could "
4157 "be in use (use force=true to override this check)",
4158 node_name);
4159 return;
4162 if (iothread->type == QTYPE_QSTRING) {
4163 IOThread *obj = iothread_by_id(iothread->u.s);
4164 if (!obj) {
4165 error_setg(errp, "Cannot find iothread %s", iothread->u.s);
4166 return;
4169 new_context = iothread_get_aio_context(obj);
4170 } else {
4171 new_context = qemu_get_aio_context();
4174 old_context = bdrv_get_aio_context(bs);
4175 aio_context_acquire(old_context);
4177 bdrv_set_aio_context(bs, new_context);
4179 aio_context_release(old_context);
4182 QemuOptsList qemu_common_drive_opts = {
4183 .name = "drive",
4184 .head = QTAILQ_HEAD_INITIALIZER(qemu_common_drive_opts.head),
4185 .desc = {
4187 .name = "snapshot",
4188 .type = QEMU_OPT_BOOL,
4189 .help = "enable/disable snapshot mode",
4191 .name = "aio",
4192 .type = QEMU_OPT_STRING,
4193 .help = "host AIO implementation (threads, native)",
4195 .name = BDRV_OPT_CACHE_WB,
4196 .type = QEMU_OPT_BOOL,
4197 .help = "Enable writeback mode",
4199 .name = "format",
4200 .type = QEMU_OPT_STRING,
4201 .help = "disk format (raw, qcow2, ...)",
4203 .name = "rerror",
4204 .type = QEMU_OPT_STRING,
4205 .help = "read error action",
4207 .name = "werror",
4208 .type = QEMU_OPT_STRING,
4209 .help = "write error action",
4211 .name = BDRV_OPT_READ_ONLY,
4212 .type = QEMU_OPT_BOOL,
4213 .help = "open drive file as read-only",
4216 THROTTLE_OPTS,
4219 .name = "throttling.group",
4220 .type = QEMU_OPT_STRING,
4221 .help = "name of the block throttling group",
4223 .name = "copy-on-read",
4224 .type = QEMU_OPT_BOOL,
4225 .help = "copy read data from backing file into image file",
4227 .name = "detect-zeroes",
4228 .type = QEMU_OPT_STRING,
4229 .help = "try to optimize zero writes (off, on, unmap)",
4231 .name = "stats-account-invalid",
4232 .type = QEMU_OPT_BOOL,
4233 .help = "whether to account for invalid I/O operations "
4234 "in the statistics",
4236 .name = "stats-account-failed",
4237 .type = QEMU_OPT_BOOL,
4238 .help = "whether to account for failed I/O operations "
4239 "in the statistics",
4241 { /* end of list */ }
4245 QemuOptsList qemu_drive_opts = {
4246 .name = "drive",
4247 .head = QTAILQ_HEAD_INITIALIZER(qemu_drive_opts.head),
4248 .desc = {
4250 * no elements => accept any params
4251 * validation will happen later
4253 { /* end of list */ }