aio-posix: simplify aio_epoll_update
[qemu.git] / blockdev.c
blob102ca9fe01fdcb902475d3afc20b145ebe85437a
1 /*
2 * QEMU host block devices
4 * Copyright (c) 2003-2008 Fabrice Bellard
6 * This work is licensed under the terms of the GNU GPL, version 2 or
7 * later. See the COPYING file in the top-level directory.
9 * This file incorporates work covered by the following copyright and
10 * permission notice:
12 * Copyright (c) 2003-2008 Fabrice Bellard
14 * Permission is hereby granted, free of charge, to any person obtaining a copy
15 * of this software and associated documentation files (the "Software"), to deal
16 * in the Software without restriction, including without limitation the rights
17 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
18 * copies of the Software, and to permit persons to whom the Software is
19 * furnished to do so, subject to the following conditions:
21 * The above copyright notice and this permission notice shall be included in
22 * all copies or substantial portions of the Software.
24 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
25 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
26 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
27 * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
28 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
29 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
30 * THE SOFTWARE.
33 #include "qemu/osdep.h"
34 #include "sysemu/block-backend.h"
35 #include "sysemu/blockdev.h"
36 #include "hw/block/block.h"
37 #include "block/blockjob.h"
38 #include "block/throttle-groups.h"
39 #include "monitor/monitor.h"
40 #include "qemu/error-report.h"
41 #include "qemu/option.h"
42 #include "qemu/config-file.h"
43 #include "qapi/qmp/types.h"
44 #include "qapi-visit.h"
45 #include "qapi/qmp/qerror.h"
46 #include "qapi/qobject-output-visitor.h"
47 #include "qapi/util.h"
48 #include "sysemu/sysemu.h"
49 #include "block/block_int.h"
50 #include "qmp-commands.h"
51 #include "trace.h"
52 #include "sysemu/arch_init.h"
53 #include "qemu/cutils.h"
54 #include "qemu/help_option.h"
56 static QTAILQ_HEAD(, BlockDriverState) monitor_bdrv_states =
57 QTAILQ_HEAD_INITIALIZER(monitor_bdrv_states);
59 static int do_open_tray(const char *blk_name, const char *qdev_id,
60 bool force, Error **errp);
62 static const char *const if_name[IF_COUNT] = {
63 [IF_NONE] = "none",
64 [IF_IDE] = "ide",
65 [IF_SCSI] = "scsi",
66 [IF_FLOPPY] = "floppy",
67 [IF_PFLASH] = "pflash",
68 [IF_MTD] = "mtd",
69 [IF_SD] = "sd",
70 [IF_VIRTIO] = "virtio",
71 [IF_XEN] = "xen",
74 static int if_max_devs[IF_COUNT] = {
76 * Do not change these numbers! They govern how drive option
77 * index maps to unit and bus. That mapping is ABI.
79 * All controllers used to implement if=T drives need to support
80 * if_max_devs[T] units, for any T with if_max_devs[T] != 0.
81 * Otherwise, some index values map to "impossible" bus, unit
82 * values.
84 * For instance, if you change [IF_SCSI] to 255, -drive
85 * if=scsi,index=12 no longer means bus=1,unit=5, but
86 * bus=0,unit=12. With an lsi53c895a controller (7 units max),
87 * the drive can't be set up. Regression.
89 [IF_IDE] = 2,
90 [IF_SCSI] = 7,
93 /**
94 * Boards may call this to offer board-by-board overrides
95 * of the default, global values.
97 void override_max_devs(BlockInterfaceType type, int max_devs)
99 BlockBackend *blk;
100 DriveInfo *dinfo;
102 if (max_devs <= 0) {
103 return;
106 for (blk = blk_next(NULL); blk; blk = blk_next(blk)) {
107 dinfo = blk_legacy_dinfo(blk);
108 if (dinfo->type == type) {
109 fprintf(stderr, "Cannot override units-per-bus property of"
110 " the %s interface, because a drive of that type has"
111 " already been added.\n", if_name[type]);
112 g_assert_not_reached();
116 if_max_devs[type] = max_devs;
120 * We automatically delete the drive when a device using it gets
121 * unplugged. Questionable feature, but we can't just drop it.
122 * Device models call blockdev_mark_auto_del() to schedule the
123 * automatic deletion, and generic qdev code calls blockdev_auto_del()
124 * when deletion is actually safe.
126 void blockdev_mark_auto_del(BlockBackend *blk)
128 DriveInfo *dinfo = blk_legacy_dinfo(blk);
129 BlockDriverState *bs = blk_bs(blk);
130 AioContext *aio_context;
132 if (!dinfo) {
133 return;
136 if (bs) {
137 aio_context = bdrv_get_aio_context(bs);
138 aio_context_acquire(aio_context);
140 if (bs->job) {
141 block_job_cancel(bs->job);
144 aio_context_release(aio_context);
147 dinfo->auto_del = 1;
150 void blockdev_auto_del(BlockBackend *blk)
152 DriveInfo *dinfo = blk_legacy_dinfo(blk);
154 if (dinfo && dinfo->auto_del) {
155 monitor_remove_blk(blk);
156 blk_unref(blk);
161 * Returns the current mapping of how many units per bus
162 * a particular interface can support.
164 * A positive integer indicates n units per bus.
165 * 0 implies the mapping has not been established.
166 * -1 indicates an invalid BlockInterfaceType was given.
168 int drive_get_max_devs(BlockInterfaceType type)
170 if (type >= IF_IDE && type < IF_COUNT) {
171 return if_max_devs[type];
174 return -1;
177 static int drive_index_to_bus_id(BlockInterfaceType type, int index)
179 int max_devs = if_max_devs[type];
180 return max_devs ? index / max_devs : 0;
183 static int drive_index_to_unit_id(BlockInterfaceType type, int index)
185 int max_devs = if_max_devs[type];
186 return max_devs ? index % max_devs : index;
189 QemuOpts *drive_def(const char *optstr)
191 return qemu_opts_parse_noisily(qemu_find_opts("drive"), optstr, false);
194 QemuOpts *drive_add(BlockInterfaceType type, int index, const char *file,
195 const char *optstr)
197 QemuOpts *opts;
199 opts = drive_def(optstr);
200 if (!opts) {
201 return NULL;
203 if (type != IF_DEFAULT) {
204 qemu_opt_set(opts, "if", if_name[type], &error_abort);
206 if (index >= 0) {
207 qemu_opt_set_number(opts, "index", index, &error_abort);
209 if (file)
210 qemu_opt_set(opts, "file", file, &error_abort);
211 return opts;
214 DriveInfo *drive_get(BlockInterfaceType type, int bus, int unit)
216 BlockBackend *blk;
217 DriveInfo *dinfo;
219 for (blk = blk_next(NULL); blk; blk = blk_next(blk)) {
220 dinfo = blk_legacy_dinfo(blk);
221 if (dinfo && dinfo->type == type
222 && dinfo->bus == bus && dinfo->unit == unit) {
223 return dinfo;
227 return NULL;
230 bool drive_check_orphaned(void)
232 BlockBackend *blk;
233 DriveInfo *dinfo;
234 bool rs = false;
236 for (blk = blk_next(NULL); blk; blk = blk_next(blk)) {
237 dinfo = blk_legacy_dinfo(blk);
238 /* If dinfo->bdrv->dev is NULL, it has no device attached. */
239 /* Unless this is a default drive, this may be an oversight. */
240 if (!blk_get_attached_dev(blk) && !dinfo->is_default &&
241 dinfo->type != IF_NONE) {
242 fprintf(stderr, "Warning: Orphaned drive without device: "
243 "id=%s,file=%s,if=%s,bus=%d,unit=%d\n",
244 blk_name(blk), blk_bs(blk) ? blk_bs(blk)->filename : "",
245 if_name[dinfo->type], dinfo->bus, dinfo->unit);
246 rs = true;
250 return rs;
253 DriveInfo *drive_get_by_index(BlockInterfaceType type, int index)
255 return drive_get(type,
256 drive_index_to_bus_id(type, index),
257 drive_index_to_unit_id(type, index));
260 int drive_get_max_bus(BlockInterfaceType type)
262 int max_bus;
263 BlockBackend *blk;
264 DriveInfo *dinfo;
266 max_bus = -1;
267 for (blk = blk_next(NULL); blk; blk = blk_next(blk)) {
268 dinfo = blk_legacy_dinfo(blk);
269 if (dinfo && dinfo->type == type && dinfo->bus > max_bus) {
270 max_bus = dinfo->bus;
273 return max_bus;
276 /* Get a block device. This should only be used for single-drive devices
277 (e.g. SD/Floppy/MTD). Multi-disk devices (scsi/ide) should use the
278 appropriate bus. */
279 DriveInfo *drive_get_next(BlockInterfaceType type)
281 static int next_block_unit[IF_COUNT];
283 return drive_get(type, 0, next_block_unit[type]++);
286 static void bdrv_format_print(void *opaque, const char *name)
288 error_printf(" %s", name);
291 typedef struct {
292 QEMUBH *bh;
293 BlockDriverState *bs;
294 } BDRVPutRefBH;
296 static int parse_block_error_action(const char *buf, bool is_read, Error **errp)
298 if (!strcmp(buf, "ignore")) {
299 return BLOCKDEV_ON_ERROR_IGNORE;
300 } else if (!is_read && !strcmp(buf, "enospc")) {
301 return BLOCKDEV_ON_ERROR_ENOSPC;
302 } else if (!strcmp(buf, "stop")) {
303 return BLOCKDEV_ON_ERROR_STOP;
304 } else if (!strcmp(buf, "report")) {
305 return BLOCKDEV_ON_ERROR_REPORT;
306 } else {
307 error_setg(errp, "'%s' invalid %s error action",
308 buf, is_read ? "read" : "write");
309 return -1;
313 static bool parse_stats_intervals(BlockAcctStats *stats, QList *intervals,
314 Error **errp)
316 const QListEntry *entry;
317 for (entry = qlist_first(intervals); entry; entry = qlist_next(entry)) {
318 switch (qobject_type(entry->value)) {
320 case QTYPE_QSTRING: {
321 unsigned long long length;
322 const char *str = qstring_get_str(qobject_to_qstring(entry->value));
323 if (parse_uint_full(str, &length, 10) == 0 &&
324 length > 0 && length <= UINT_MAX) {
325 block_acct_add_interval(stats, (unsigned) length);
326 } else {
327 error_setg(errp, "Invalid interval length: %s", str);
328 return false;
330 break;
333 case QTYPE_QINT: {
334 int64_t length = qint_get_int(qobject_to_qint(entry->value));
335 if (length > 0 && length <= UINT_MAX) {
336 block_acct_add_interval(stats, (unsigned) length);
337 } else {
338 error_setg(errp, "Invalid interval length: %" PRId64, length);
339 return false;
341 break;
344 default:
345 error_setg(errp, "The specification of stats-intervals is invalid");
346 return false;
349 return true;
352 typedef enum { MEDIA_DISK, MEDIA_CDROM } DriveMediaType;
354 /* All parameters but @opts are optional and may be set to NULL. */
355 static void extract_common_blockdev_options(QemuOpts *opts, int *bdrv_flags,
356 const char **throttling_group, ThrottleConfig *throttle_cfg,
357 BlockdevDetectZeroesOptions *detect_zeroes, Error **errp)
359 Error *local_error = NULL;
360 const char *aio;
362 if (bdrv_flags) {
363 if (qemu_opt_get_bool(opts, "copy-on-read", false)) {
364 *bdrv_flags |= BDRV_O_COPY_ON_READ;
367 if ((aio = qemu_opt_get(opts, "aio")) != NULL) {
368 if (!strcmp(aio, "native")) {
369 *bdrv_flags |= BDRV_O_NATIVE_AIO;
370 } else if (!strcmp(aio, "threads")) {
371 /* this is the default */
372 } else {
373 error_setg(errp, "invalid aio option");
374 return;
379 /* disk I/O throttling */
380 if (throttling_group) {
381 *throttling_group = qemu_opt_get(opts, "throttling.group");
384 if (throttle_cfg) {
385 throttle_config_init(throttle_cfg);
386 throttle_cfg->buckets[THROTTLE_BPS_TOTAL].avg =
387 qemu_opt_get_number(opts, "throttling.bps-total", 0);
388 throttle_cfg->buckets[THROTTLE_BPS_READ].avg =
389 qemu_opt_get_number(opts, "throttling.bps-read", 0);
390 throttle_cfg->buckets[THROTTLE_BPS_WRITE].avg =
391 qemu_opt_get_number(opts, "throttling.bps-write", 0);
392 throttle_cfg->buckets[THROTTLE_OPS_TOTAL].avg =
393 qemu_opt_get_number(opts, "throttling.iops-total", 0);
394 throttle_cfg->buckets[THROTTLE_OPS_READ].avg =
395 qemu_opt_get_number(opts, "throttling.iops-read", 0);
396 throttle_cfg->buckets[THROTTLE_OPS_WRITE].avg =
397 qemu_opt_get_number(opts, "throttling.iops-write", 0);
399 throttle_cfg->buckets[THROTTLE_BPS_TOTAL].max =
400 qemu_opt_get_number(opts, "throttling.bps-total-max", 0);
401 throttle_cfg->buckets[THROTTLE_BPS_READ].max =
402 qemu_opt_get_number(opts, "throttling.bps-read-max", 0);
403 throttle_cfg->buckets[THROTTLE_BPS_WRITE].max =
404 qemu_opt_get_number(opts, "throttling.bps-write-max", 0);
405 throttle_cfg->buckets[THROTTLE_OPS_TOTAL].max =
406 qemu_opt_get_number(opts, "throttling.iops-total-max", 0);
407 throttle_cfg->buckets[THROTTLE_OPS_READ].max =
408 qemu_opt_get_number(opts, "throttling.iops-read-max", 0);
409 throttle_cfg->buckets[THROTTLE_OPS_WRITE].max =
410 qemu_opt_get_number(opts, "throttling.iops-write-max", 0);
412 throttle_cfg->buckets[THROTTLE_BPS_TOTAL].burst_length =
413 qemu_opt_get_number(opts, "throttling.bps-total-max-length", 1);
414 throttle_cfg->buckets[THROTTLE_BPS_READ].burst_length =
415 qemu_opt_get_number(opts, "throttling.bps-read-max-length", 1);
416 throttle_cfg->buckets[THROTTLE_BPS_WRITE].burst_length =
417 qemu_opt_get_number(opts, "throttling.bps-write-max-length", 1);
418 throttle_cfg->buckets[THROTTLE_OPS_TOTAL].burst_length =
419 qemu_opt_get_number(opts, "throttling.iops-total-max-length", 1);
420 throttle_cfg->buckets[THROTTLE_OPS_READ].burst_length =
421 qemu_opt_get_number(opts, "throttling.iops-read-max-length", 1);
422 throttle_cfg->buckets[THROTTLE_OPS_WRITE].burst_length =
423 qemu_opt_get_number(opts, "throttling.iops-write-max-length", 1);
425 throttle_cfg->op_size =
426 qemu_opt_get_number(opts, "throttling.iops-size", 0);
428 if (!throttle_is_valid(throttle_cfg, errp)) {
429 return;
433 if (detect_zeroes) {
434 *detect_zeroes =
435 qapi_enum_parse(BlockdevDetectZeroesOptions_lookup,
436 qemu_opt_get(opts, "detect-zeroes"),
437 BLOCKDEV_DETECT_ZEROES_OPTIONS__MAX,
438 BLOCKDEV_DETECT_ZEROES_OPTIONS_OFF,
439 &local_error);
440 if (local_error) {
441 error_propagate(errp, local_error);
442 return;
447 /* Takes the ownership of bs_opts */
448 static BlockBackend *blockdev_init(const char *file, QDict *bs_opts,
449 Error **errp)
451 const char *buf;
452 int bdrv_flags = 0;
453 int on_read_error, on_write_error;
454 bool account_invalid, account_failed;
455 bool writethrough, read_only;
456 BlockBackend *blk;
457 BlockDriverState *bs;
458 ThrottleConfig cfg;
459 int snapshot = 0;
460 Error *error = NULL;
461 QemuOpts *opts;
462 QDict *interval_dict = NULL;
463 QList *interval_list = NULL;
464 const char *id;
465 BlockdevDetectZeroesOptions detect_zeroes =
466 BLOCKDEV_DETECT_ZEROES_OPTIONS_OFF;
467 const char *throttling_group = NULL;
469 /* Check common options by copying from bs_opts to opts, all other options
470 * stay in bs_opts for processing by bdrv_open(). */
471 id = qdict_get_try_str(bs_opts, "id");
472 opts = qemu_opts_create(&qemu_common_drive_opts, id, 1, &error);
473 if (error) {
474 error_propagate(errp, error);
475 goto err_no_opts;
478 qemu_opts_absorb_qdict(opts, bs_opts, &error);
479 if (error) {
480 error_propagate(errp, error);
481 goto early_err;
484 if (id) {
485 qdict_del(bs_opts, "id");
488 /* extract parameters */
489 snapshot = qemu_opt_get_bool(opts, "snapshot", 0);
491 account_invalid = qemu_opt_get_bool(opts, "stats-account-invalid", true);
492 account_failed = qemu_opt_get_bool(opts, "stats-account-failed", true);
494 writethrough = !qemu_opt_get_bool(opts, BDRV_OPT_CACHE_WB, true);
496 id = qemu_opts_id(opts);
498 qdict_extract_subqdict(bs_opts, &interval_dict, "stats-intervals.");
499 qdict_array_split(interval_dict, &interval_list);
501 if (qdict_size(interval_dict) != 0) {
502 error_setg(errp, "Invalid option stats-intervals.%s",
503 qdict_first(interval_dict)->key);
504 goto early_err;
507 extract_common_blockdev_options(opts, &bdrv_flags, &throttling_group, &cfg,
508 &detect_zeroes, &error);
509 if (error) {
510 error_propagate(errp, error);
511 goto early_err;
514 if ((buf = qemu_opt_get(opts, "format")) != NULL) {
515 if (is_help_option(buf)) {
516 error_printf("Supported formats:");
517 bdrv_iterate_format(bdrv_format_print, NULL);
518 error_printf("\n");
519 goto early_err;
522 if (qdict_haskey(bs_opts, "driver")) {
523 error_setg(errp, "Cannot specify both 'driver' and 'format'");
524 goto early_err;
526 qdict_put(bs_opts, "driver", qstring_from_str(buf));
529 on_write_error = BLOCKDEV_ON_ERROR_ENOSPC;
530 if ((buf = qemu_opt_get(opts, "werror")) != NULL) {
531 on_write_error = parse_block_error_action(buf, 0, &error);
532 if (error) {
533 error_propagate(errp, error);
534 goto early_err;
538 on_read_error = BLOCKDEV_ON_ERROR_REPORT;
539 if ((buf = qemu_opt_get(opts, "rerror")) != NULL) {
540 on_read_error = parse_block_error_action(buf, 1, &error);
541 if (error) {
542 error_propagate(errp, error);
543 goto early_err;
547 if (snapshot) {
548 bdrv_flags |= BDRV_O_SNAPSHOT;
551 read_only = qemu_opt_get_bool(opts, BDRV_OPT_READ_ONLY, false);
553 /* init */
554 if ((!file || !*file) && !qdict_size(bs_opts)) {
555 BlockBackendRootState *blk_rs;
557 blk = blk_new();
558 blk_rs = blk_get_root_state(blk);
559 blk_rs->open_flags = bdrv_flags;
560 blk_rs->read_only = read_only;
561 blk_rs->detect_zeroes = detect_zeroes;
563 QDECREF(bs_opts);
564 } else {
565 if (file && !*file) {
566 file = NULL;
569 /* bdrv_open() defaults to the values in bdrv_flags (for compatibility
570 * with other callers) rather than what we want as the real defaults.
571 * Apply the defaults here instead. */
572 qdict_set_default_str(bs_opts, BDRV_OPT_CACHE_DIRECT, "off");
573 qdict_set_default_str(bs_opts, BDRV_OPT_CACHE_NO_FLUSH, "off");
574 qdict_set_default_str(bs_opts, BDRV_OPT_READ_ONLY,
575 read_only ? "on" : "off");
576 assert((bdrv_flags & BDRV_O_CACHE_MASK) == 0);
578 if (runstate_check(RUN_STATE_INMIGRATE)) {
579 bdrv_flags |= BDRV_O_INACTIVE;
582 blk = blk_new_open(file, NULL, bs_opts, bdrv_flags, errp);
583 if (!blk) {
584 goto err_no_bs_opts;
586 bs = blk_bs(blk);
588 bs->detect_zeroes = detect_zeroes;
590 if (bdrv_key_required(bs)) {
591 autostart = 0;
594 block_acct_init(blk_get_stats(blk), account_invalid, account_failed);
596 if (!parse_stats_intervals(blk_get_stats(blk), interval_list, errp)) {
597 blk_unref(blk);
598 blk = NULL;
599 goto err_no_bs_opts;
603 /* disk I/O throttling */
604 if (throttle_enabled(&cfg)) {
605 if (!throttling_group) {
606 throttling_group = id;
608 blk_io_limits_enable(blk, throttling_group);
609 blk_set_io_limits(blk, &cfg);
612 blk_set_enable_write_cache(blk, !writethrough);
613 blk_set_on_error(blk, on_read_error, on_write_error);
615 if (!monitor_add_blk(blk, id, errp)) {
616 blk_unref(blk);
617 blk = NULL;
618 goto err_no_bs_opts;
621 err_no_bs_opts:
622 qemu_opts_del(opts);
623 QDECREF(interval_dict);
624 QDECREF(interval_list);
625 return blk;
627 early_err:
628 qemu_opts_del(opts);
629 QDECREF(interval_dict);
630 QDECREF(interval_list);
631 err_no_opts:
632 QDECREF(bs_opts);
633 return NULL;
636 /* Takes the ownership of bs_opts */
637 static BlockDriverState *bds_tree_init(QDict *bs_opts, Error **errp)
639 int bdrv_flags = 0;
641 /* bdrv_open() defaults to the values in bdrv_flags (for compatibility
642 * with other callers) rather than what we want as the real defaults.
643 * Apply the defaults here instead. */
644 qdict_set_default_str(bs_opts, BDRV_OPT_CACHE_DIRECT, "off");
645 qdict_set_default_str(bs_opts, BDRV_OPT_CACHE_NO_FLUSH, "off");
646 qdict_set_default_str(bs_opts, BDRV_OPT_READ_ONLY, "off");
648 if (runstate_check(RUN_STATE_INMIGRATE)) {
649 bdrv_flags |= BDRV_O_INACTIVE;
652 return bdrv_open(NULL, NULL, bs_opts, bdrv_flags, errp);
655 void blockdev_close_all_bdrv_states(void)
657 BlockDriverState *bs, *next_bs;
659 QTAILQ_FOREACH_SAFE(bs, &monitor_bdrv_states, monitor_list, next_bs) {
660 AioContext *ctx = bdrv_get_aio_context(bs);
662 aio_context_acquire(ctx);
663 bdrv_unref(bs);
664 aio_context_release(ctx);
668 /* Iterates over the list of monitor-owned BlockDriverStates */
669 BlockDriverState *bdrv_next_monitor_owned(BlockDriverState *bs)
671 return bs ? QTAILQ_NEXT(bs, monitor_list)
672 : QTAILQ_FIRST(&monitor_bdrv_states);
675 static void qemu_opt_rename(QemuOpts *opts, const char *from, const char *to,
676 Error **errp)
678 const char *value;
680 value = qemu_opt_get(opts, from);
681 if (value) {
682 if (qemu_opt_find(opts, to)) {
683 error_setg(errp, "'%s' and its alias '%s' can't be used at the "
684 "same time", to, from);
685 return;
689 /* rename all items in opts */
690 while ((value = qemu_opt_get(opts, from))) {
691 qemu_opt_set(opts, to, value, &error_abort);
692 qemu_opt_unset(opts, from);
696 QemuOptsList qemu_legacy_drive_opts = {
697 .name = "drive",
698 .head = QTAILQ_HEAD_INITIALIZER(qemu_legacy_drive_opts.head),
699 .desc = {
701 .name = "bus",
702 .type = QEMU_OPT_NUMBER,
703 .help = "bus number",
705 .name = "unit",
706 .type = QEMU_OPT_NUMBER,
707 .help = "unit number (i.e. lun for scsi)",
709 .name = "index",
710 .type = QEMU_OPT_NUMBER,
711 .help = "index number",
713 .name = "media",
714 .type = QEMU_OPT_STRING,
715 .help = "media type (disk, cdrom)",
717 .name = "if",
718 .type = QEMU_OPT_STRING,
719 .help = "interface (ide, scsi, sd, mtd, floppy, pflash, virtio)",
721 .name = "cyls",
722 .type = QEMU_OPT_NUMBER,
723 .help = "number of cylinders (ide disk geometry)",
725 .name = "heads",
726 .type = QEMU_OPT_NUMBER,
727 .help = "number of heads (ide disk geometry)",
729 .name = "secs",
730 .type = QEMU_OPT_NUMBER,
731 .help = "number of sectors (ide disk geometry)",
733 .name = "trans",
734 .type = QEMU_OPT_STRING,
735 .help = "chs translation (auto, lba, none)",
737 .name = "boot",
738 .type = QEMU_OPT_BOOL,
739 .help = "(deprecated, ignored)",
741 .name = "addr",
742 .type = QEMU_OPT_STRING,
743 .help = "pci address (virtio only)",
745 .name = "serial",
746 .type = QEMU_OPT_STRING,
747 .help = "disk serial number",
749 .name = "file",
750 .type = QEMU_OPT_STRING,
751 .help = "file name",
754 /* Options that are passed on, but have special semantics with -drive */
756 .name = BDRV_OPT_READ_ONLY,
757 .type = QEMU_OPT_BOOL,
758 .help = "open drive file as read-only",
760 .name = "rerror",
761 .type = QEMU_OPT_STRING,
762 .help = "read error action",
764 .name = "werror",
765 .type = QEMU_OPT_STRING,
766 .help = "write error action",
768 .name = "copy-on-read",
769 .type = QEMU_OPT_BOOL,
770 .help = "copy read data from backing file into image file",
773 { /* end of list */ }
777 DriveInfo *drive_new(QemuOpts *all_opts, BlockInterfaceType block_default_type)
779 const char *value;
780 BlockBackend *blk;
781 DriveInfo *dinfo = NULL;
782 QDict *bs_opts;
783 QemuOpts *legacy_opts;
784 DriveMediaType media = MEDIA_DISK;
785 BlockInterfaceType type;
786 int cyls, heads, secs, translation;
787 int max_devs, bus_id, unit_id, index;
788 const char *devaddr;
789 const char *werror, *rerror;
790 bool read_only = false;
791 bool copy_on_read;
792 const char *serial;
793 const char *filename;
794 Error *local_err = NULL;
795 int i;
797 /* Change legacy command line options into QMP ones */
798 static const struct {
799 const char *from;
800 const char *to;
801 } opt_renames[] = {
802 { "iops", "throttling.iops-total" },
803 { "iops_rd", "throttling.iops-read" },
804 { "iops_wr", "throttling.iops-write" },
806 { "bps", "throttling.bps-total" },
807 { "bps_rd", "throttling.bps-read" },
808 { "bps_wr", "throttling.bps-write" },
810 { "iops_max", "throttling.iops-total-max" },
811 { "iops_rd_max", "throttling.iops-read-max" },
812 { "iops_wr_max", "throttling.iops-write-max" },
814 { "bps_max", "throttling.bps-total-max" },
815 { "bps_rd_max", "throttling.bps-read-max" },
816 { "bps_wr_max", "throttling.bps-write-max" },
818 { "iops_size", "throttling.iops-size" },
820 { "group", "throttling.group" },
822 { "readonly", BDRV_OPT_READ_ONLY },
825 for (i = 0; i < ARRAY_SIZE(opt_renames); i++) {
826 qemu_opt_rename(all_opts, opt_renames[i].from, opt_renames[i].to,
827 &local_err);
828 if (local_err) {
829 error_report_err(local_err);
830 return NULL;
834 value = qemu_opt_get(all_opts, "cache");
835 if (value) {
836 int flags = 0;
837 bool writethrough;
839 if (bdrv_parse_cache_mode(value, &flags, &writethrough) != 0) {
840 error_report("invalid cache option");
841 return NULL;
844 /* Specific options take precedence */
845 if (!qemu_opt_get(all_opts, BDRV_OPT_CACHE_WB)) {
846 qemu_opt_set_bool(all_opts, BDRV_OPT_CACHE_WB,
847 !writethrough, &error_abort);
849 if (!qemu_opt_get(all_opts, BDRV_OPT_CACHE_DIRECT)) {
850 qemu_opt_set_bool(all_opts, BDRV_OPT_CACHE_DIRECT,
851 !!(flags & BDRV_O_NOCACHE), &error_abort);
853 if (!qemu_opt_get(all_opts, BDRV_OPT_CACHE_NO_FLUSH)) {
854 qemu_opt_set_bool(all_opts, BDRV_OPT_CACHE_NO_FLUSH,
855 !!(flags & BDRV_O_NO_FLUSH), &error_abort);
857 qemu_opt_unset(all_opts, "cache");
860 /* Get a QDict for processing the options */
861 bs_opts = qdict_new();
862 qemu_opts_to_qdict(all_opts, bs_opts);
864 legacy_opts = qemu_opts_create(&qemu_legacy_drive_opts, NULL, 0,
865 &error_abort);
866 qemu_opts_absorb_qdict(legacy_opts, bs_opts, &local_err);
867 if (local_err) {
868 error_report_err(local_err);
869 goto fail;
872 /* Deprecated option boot=[on|off] */
873 if (qemu_opt_get(legacy_opts, "boot") != NULL) {
874 fprintf(stderr, "qemu-kvm: boot=on|off is deprecated and will be "
875 "ignored. Future versions will reject this parameter. Please "
876 "update your scripts.\n");
879 /* Media type */
880 value = qemu_opt_get(legacy_opts, "media");
881 if (value) {
882 if (!strcmp(value, "disk")) {
883 media = MEDIA_DISK;
884 } else if (!strcmp(value, "cdrom")) {
885 media = MEDIA_CDROM;
886 read_only = true;
887 } else {
888 error_report("'%s' invalid media", value);
889 goto fail;
893 /* copy-on-read is disabled with a warning for read-only devices */
894 read_only |= qemu_opt_get_bool(legacy_opts, BDRV_OPT_READ_ONLY, false);
895 copy_on_read = qemu_opt_get_bool(legacy_opts, "copy-on-read", false);
897 if (read_only && copy_on_read) {
898 error_report("warning: disabling copy-on-read on read-only drive");
899 copy_on_read = false;
902 qdict_put(bs_opts, BDRV_OPT_READ_ONLY,
903 qstring_from_str(read_only ? "on" : "off"));
904 qdict_put(bs_opts, "copy-on-read",
905 qstring_from_str(copy_on_read ? "on" :"off"));
907 /* Controller type */
908 value = qemu_opt_get(legacy_opts, "if");
909 if (value) {
910 for (type = 0;
911 type < IF_COUNT && strcmp(value, if_name[type]);
912 type++) {
914 if (type == IF_COUNT) {
915 error_report("unsupported bus type '%s'", value);
916 goto fail;
918 } else {
919 type = block_default_type;
922 /* Geometry */
923 cyls = qemu_opt_get_number(legacy_opts, "cyls", 0);
924 heads = qemu_opt_get_number(legacy_opts, "heads", 0);
925 secs = qemu_opt_get_number(legacy_opts, "secs", 0);
927 if (cyls || heads || secs) {
928 if (cyls < 1) {
929 error_report("invalid physical cyls number");
930 goto fail;
932 if (heads < 1) {
933 error_report("invalid physical heads number");
934 goto fail;
936 if (secs < 1) {
937 error_report("invalid physical secs number");
938 goto fail;
942 translation = BIOS_ATA_TRANSLATION_AUTO;
943 value = qemu_opt_get(legacy_opts, "trans");
944 if (value != NULL) {
945 if (!cyls) {
946 error_report("'%s' trans must be used with cyls, heads and secs",
947 value);
948 goto fail;
950 if (!strcmp(value, "none")) {
951 translation = BIOS_ATA_TRANSLATION_NONE;
952 } else if (!strcmp(value, "lba")) {
953 translation = BIOS_ATA_TRANSLATION_LBA;
954 } else if (!strcmp(value, "large")) {
955 translation = BIOS_ATA_TRANSLATION_LARGE;
956 } else if (!strcmp(value, "rechs")) {
957 translation = BIOS_ATA_TRANSLATION_RECHS;
958 } else if (!strcmp(value, "auto")) {
959 translation = BIOS_ATA_TRANSLATION_AUTO;
960 } else {
961 error_report("'%s' invalid translation type", value);
962 goto fail;
966 if (media == MEDIA_CDROM) {
967 if (cyls || secs || heads) {
968 error_report("CHS can't be set with media=cdrom");
969 goto fail;
973 /* Device address specified by bus/unit or index.
974 * If none was specified, try to find the first free one. */
975 bus_id = qemu_opt_get_number(legacy_opts, "bus", 0);
976 unit_id = qemu_opt_get_number(legacy_opts, "unit", -1);
977 index = qemu_opt_get_number(legacy_opts, "index", -1);
979 max_devs = if_max_devs[type];
981 if (index != -1) {
982 if (bus_id != 0 || unit_id != -1) {
983 error_report("index cannot be used with bus and unit");
984 goto fail;
986 bus_id = drive_index_to_bus_id(type, index);
987 unit_id = drive_index_to_unit_id(type, index);
990 if (unit_id == -1) {
991 unit_id = 0;
992 while (drive_get(type, bus_id, unit_id) != NULL) {
993 unit_id++;
994 if (max_devs && unit_id >= max_devs) {
995 unit_id -= max_devs;
996 bus_id++;
1001 if (max_devs && unit_id >= max_devs) {
1002 error_report("unit %d too big (max is %d)", unit_id, max_devs - 1);
1003 goto fail;
1006 if (drive_get(type, bus_id, unit_id) != NULL) {
1007 error_report("drive with bus=%d, unit=%d (index=%d) exists",
1008 bus_id, unit_id, index);
1009 goto fail;
1012 /* Serial number */
1013 serial = qemu_opt_get(legacy_opts, "serial");
1015 /* no id supplied -> create one */
1016 if (qemu_opts_id(all_opts) == NULL) {
1017 char *new_id;
1018 const char *mediastr = "";
1019 if (type == IF_IDE || type == IF_SCSI) {
1020 mediastr = (media == MEDIA_CDROM) ? "-cd" : "-hd";
1022 if (max_devs) {
1023 new_id = g_strdup_printf("%s%i%s%i", if_name[type], bus_id,
1024 mediastr, unit_id);
1025 } else {
1026 new_id = g_strdup_printf("%s%s%i", if_name[type],
1027 mediastr, unit_id);
1029 qdict_put(bs_opts, "id", qstring_from_str(new_id));
1030 g_free(new_id);
1033 /* Add virtio block device */
1034 devaddr = qemu_opt_get(legacy_opts, "addr");
1035 if (devaddr && type != IF_VIRTIO) {
1036 error_report("addr is not supported by this bus type");
1037 goto fail;
1040 if (type == IF_VIRTIO) {
1041 QemuOpts *devopts;
1042 devopts = qemu_opts_create(qemu_find_opts("device"), NULL, 0,
1043 &error_abort);
1044 if (arch_type == QEMU_ARCH_S390X) {
1045 qemu_opt_set(devopts, "driver", "virtio-blk-ccw", &error_abort);
1046 } else {
1047 qemu_opt_set(devopts, "driver", "virtio-blk-pci", &error_abort);
1049 qemu_opt_set(devopts, "drive", qdict_get_str(bs_opts, "id"),
1050 &error_abort);
1051 if (devaddr) {
1052 qemu_opt_set(devopts, "addr", devaddr, &error_abort);
1056 filename = qemu_opt_get(legacy_opts, "file");
1058 /* Check werror/rerror compatibility with if=... */
1059 werror = qemu_opt_get(legacy_opts, "werror");
1060 if (werror != NULL) {
1061 if (type != IF_IDE && type != IF_SCSI && type != IF_VIRTIO &&
1062 type != IF_NONE) {
1063 error_report("werror is not supported by this bus type");
1064 goto fail;
1066 qdict_put(bs_opts, "werror", qstring_from_str(werror));
1069 rerror = qemu_opt_get(legacy_opts, "rerror");
1070 if (rerror != NULL) {
1071 if (type != IF_IDE && type != IF_VIRTIO && type != IF_SCSI &&
1072 type != IF_NONE) {
1073 error_report("rerror is not supported by this bus type");
1074 goto fail;
1076 qdict_put(bs_opts, "rerror", qstring_from_str(rerror));
1079 /* Actual block device init: Functionality shared with blockdev-add */
1080 blk = blockdev_init(filename, bs_opts, &local_err);
1081 bs_opts = NULL;
1082 if (!blk) {
1083 if (local_err) {
1084 error_report_err(local_err);
1086 goto fail;
1087 } else {
1088 assert(!local_err);
1091 /* Create legacy DriveInfo */
1092 dinfo = g_malloc0(sizeof(*dinfo));
1093 dinfo->opts = all_opts;
1095 dinfo->cyls = cyls;
1096 dinfo->heads = heads;
1097 dinfo->secs = secs;
1098 dinfo->trans = translation;
1100 dinfo->type = type;
1101 dinfo->bus = bus_id;
1102 dinfo->unit = unit_id;
1103 dinfo->devaddr = devaddr;
1104 dinfo->serial = g_strdup(serial);
1106 blk_set_legacy_dinfo(blk, dinfo);
1108 switch(type) {
1109 case IF_IDE:
1110 case IF_SCSI:
1111 case IF_XEN:
1112 case IF_NONE:
1113 dinfo->media_cd = media == MEDIA_CDROM;
1114 break;
1115 default:
1116 break;
1119 fail:
1120 qemu_opts_del(legacy_opts);
1121 QDECREF(bs_opts);
1122 return dinfo;
1125 static BlockDriverState *qmp_get_root_bs(const char *name, Error **errp)
1127 BlockDriverState *bs;
1129 bs = bdrv_lookup_bs(name, name, errp);
1130 if (bs == NULL) {
1131 return NULL;
1134 if (!bdrv_is_root_node(bs)) {
1135 error_setg(errp, "Need a root block node");
1136 return NULL;
1139 if (!bdrv_is_inserted(bs)) {
1140 error_setg(errp, "Device has no medium");
1141 return NULL;
1144 return bs;
1147 static BlockBackend *qmp_get_blk(const char *blk_name, const char *qdev_id,
1148 Error **errp)
1150 BlockBackend *blk;
1152 if (!blk_name == !qdev_id) {
1153 error_setg(errp, "Need exactly one of 'device' and 'id'");
1154 return NULL;
1157 if (qdev_id) {
1158 blk = blk_by_qdev_id(qdev_id, errp);
1159 } else {
1160 blk = blk_by_name(blk_name);
1161 if (blk == NULL) {
1162 error_set(errp, ERROR_CLASS_DEVICE_NOT_FOUND,
1163 "Device '%s' not found", blk_name);
1167 return blk;
1170 void hmp_commit(Monitor *mon, const QDict *qdict)
1172 const char *device = qdict_get_str(qdict, "device");
1173 BlockBackend *blk;
1174 int ret;
1176 if (!strcmp(device, "all")) {
1177 ret = blk_commit_all();
1178 } else {
1179 BlockDriverState *bs;
1180 AioContext *aio_context;
1182 blk = blk_by_name(device);
1183 if (!blk) {
1184 monitor_printf(mon, "Device '%s' not found\n", device);
1185 return;
1187 if (!blk_is_available(blk)) {
1188 monitor_printf(mon, "Device '%s' has no medium\n", device);
1189 return;
1192 bs = blk_bs(blk);
1193 aio_context = bdrv_get_aio_context(bs);
1194 aio_context_acquire(aio_context);
1196 ret = bdrv_commit(bs);
1198 aio_context_release(aio_context);
1200 if (ret < 0) {
1201 monitor_printf(mon, "'commit' error for '%s': %s\n", device,
1202 strerror(-ret));
1206 static void blockdev_do_action(TransactionAction *action, Error **errp)
1208 TransactionActionList list;
1210 list.value = action;
1211 list.next = NULL;
1212 qmp_transaction(&list, false, NULL, errp);
1215 void qmp_blockdev_snapshot_sync(bool has_device, const char *device,
1216 bool has_node_name, const char *node_name,
1217 const char *snapshot_file,
1218 bool has_snapshot_node_name,
1219 const char *snapshot_node_name,
1220 bool has_format, const char *format,
1221 bool has_mode, NewImageMode mode, Error **errp)
1223 BlockdevSnapshotSync snapshot = {
1224 .has_device = has_device,
1225 .device = (char *) device,
1226 .has_node_name = has_node_name,
1227 .node_name = (char *) node_name,
1228 .snapshot_file = (char *) snapshot_file,
1229 .has_snapshot_node_name = has_snapshot_node_name,
1230 .snapshot_node_name = (char *) snapshot_node_name,
1231 .has_format = has_format,
1232 .format = (char *) format,
1233 .has_mode = has_mode,
1234 .mode = mode,
1236 TransactionAction action = {
1237 .type = TRANSACTION_ACTION_KIND_BLOCKDEV_SNAPSHOT_SYNC,
1238 .u.blockdev_snapshot_sync.data = &snapshot,
1240 blockdev_do_action(&action, errp);
1243 void qmp_blockdev_snapshot(const char *node, const char *overlay,
1244 Error **errp)
1246 BlockdevSnapshot snapshot_data = {
1247 .node = (char *) node,
1248 .overlay = (char *) overlay
1250 TransactionAction action = {
1251 .type = TRANSACTION_ACTION_KIND_BLOCKDEV_SNAPSHOT,
1252 .u.blockdev_snapshot.data = &snapshot_data,
1254 blockdev_do_action(&action, errp);
1257 void qmp_blockdev_snapshot_internal_sync(const char *device,
1258 const char *name,
1259 Error **errp)
1261 BlockdevSnapshotInternal snapshot = {
1262 .device = (char *) device,
1263 .name = (char *) name
1265 TransactionAction action = {
1266 .type = TRANSACTION_ACTION_KIND_BLOCKDEV_SNAPSHOT_INTERNAL_SYNC,
1267 .u.blockdev_snapshot_internal_sync.data = &snapshot,
1269 blockdev_do_action(&action, errp);
1272 SnapshotInfo *qmp_blockdev_snapshot_delete_internal_sync(const char *device,
1273 bool has_id,
1274 const char *id,
1275 bool has_name,
1276 const char *name,
1277 Error **errp)
1279 BlockDriverState *bs;
1280 AioContext *aio_context;
1281 QEMUSnapshotInfo sn;
1282 Error *local_err = NULL;
1283 SnapshotInfo *info = NULL;
1284 int ret;
1286 bs = qmp_get_root_bs(device, errp);
1287 if (!bs) {
1288 return NULL;
1290 aio_context = bdrv_get_aio_context(bs);
1291 aio_context_acquire(aio_context);
1293 if (!has_id) {
1294 id = NULL;
1297 if (!has_name) {
1298 name = NULL;
1301 if (!id && !name) {
1302 error_setg(errp, "Name or id must be provided");
1303 goto out_aio_context;
1306 if (bdrv_op_is_blocked(bs, BLOCK_OP_TYPE_INTERNAL_SNAPSHOT_DELETE, errp)) {
1307 goto out_aio_context;
1310 ret = bdrv_snapshot_find_by_id_and_name(bs, id, name, &sn, &local_err);
1311 if (local_err) {
1312 error_propagate(errp, local_err);
1313 goto out_aio_context;
1315 if (!ret) {
1316 error_setg(errp,
1317 "Snapshot with id '%s' and name '%s' does not exist on "
1318 "device '%s'",
1319 STR_OR_NULL(id), STR_OR_NULL(name), device);
1320 goto out_aio_context;
1323 bdrv_snapshot_delete(bs, id, name, &local_err);
1324 if (local_err) {
1325 error_propagate(errp, local_err);
1326 goto out_aio_context;
1329 aio_context_release(aio_context);
1331 info = g_new0(SnapshotInfo, 1);
1332 info->id = g_strdup(sn.id_str);
1333 info->name = g_strdup(sn.name);
1334 info->date_nsec = sn.date_nsec;
1335 info->date_sec = sn.date_sec;
1336 info->vm_state_size = sn.vm_state_size;
1337 info->vm_clock_nsec = sn.vm_clock_nsec % 1000000000;
1338 info->vm_clock_sec = sn.vm_clock_nsec / 1000000000;
1340 return info;
1342 out_aio_context:
1343 aio_context_release(aio_context);
1344 return NULL;
1348 * block_dirty_bitmap_lookup:
1349 * Return a dirty bitmap (if present), after validating
1350 * the node reference and bitmap names.
1352 * @node: The name of the BDS node to search for bitmaps
1353 * @name: The name of the bitmap to search for
1354 * @pbs: Output pointer for BDS lookup, if desired. Can be NULL.
1355 * @paio: Output pointer for aio_context acquisition, if desired. Can be NULL.
1356 * @errp: Output pointer for error information. Can be NULL.
1358 * @return: A bitmap object on success, or NULL on failure.
1360 static BdrvDirtyBitmap *block_dirty_bitmap_lookup(const char *node,
1361 const char *name,
1362 BlockDriverState **pbs,
1363 AioContext **paio,
1364 Error **errp)
1366 BlockDriverState *bs;
1367 BdrvDirtyBitmap *bitmap;
1368 AioContext *aio_context;
1370 if (!node) {
1371 error_setg(errp, "Node cannot be NULL");
1372 return NULL;
1374 if (!name) {
1375 error_setg(errp, "Bitmap name cannot be NULL");
1376 return NULL;
1378 bs = bdrv_lookup_bs(node, node, NULL);
1379 if (!bs) {
1380 error_setg(errp, "Node '%s' not found", node);
1381 return NULL;
1384 aio_context = bdrv_get_aio_context(bs);
1385 aio_context_acquire(aio_context);
1387 bitmap = bdrv_find_dirty_bitmap(bs, name);
1388 if (!bitmap) {
1389 error_setg(errp, "Dirty bitmap '%s' not found", name);
1390 goto fail;
1393 if (pbs) {
1394 *pbs = bs;
1396 if (paio) {
1397 *paio = aio_context;
1398 } else {
1399 aio_context_release(aio_context);
1402 return bitmap;
1404 fail:
1405 aio_context_release(aio_context);
1406 return NULL;
1409 /* New and old BlockDriverState structs for atomic group operations */
1411 typedef struct BlkActionState BlkActionState;
1414 * BlkActionOps:
1415 * Table of operations that define an Action.
1417 * @instance_size: Size of state struct, in bytes.
1418 * @prepare: Prepare the work, must NOT be NULL.
1419 * @commit: Commit the changes, can be NULL.
1420 * @abort: Abort the changes on fail, can be NULL.
1421 * @clean: Clean up resources after all transaction actions have called
1422 * commit() or abort(). Can be NULL.
1424 * Only prepare() may fail. In a single transaction, only one of commit() or
1425 * abort() will be called. clean() will always be called if it is present.
1427 typedef struct BlkActionOps {
1428 size_t instance_size;
1429 void (*prepare)(BlkActionState *common, Error **errp);
1430 void (*commit)(BlkActionState *common);
1431 void (*abort)(BlkActionState *common);
1432 void (*clean)(BlkActionState *common);
1433 } BlkActionOps;
1436 * BlkActionState:
1437 * Describes one Action's state within a Transaction.
1439 * @action: QAPI-defined enum identifying which Action to perform.
1440 * @ops: Table of ActionOps this Action can perform.
1441 * @block_job_txn: Transaction which this action belongs to.
1442 * @entry: List membership for all Actions in this Transaction.
1444 * This structure must be arranged as first member in a subclassed type,
1445 * assuming that the compiler will also arrange it to the same offsets as the
1446 * base class.
1448 struct BlkActionState {
1449 TransactionAction *action;
1450 const BlkActionOps *ops;
1451 BlockJobTxn *block_job_txn;
1452 TransactionProperties *txn_props;
1453 QSIMPLEQ_ENTRY(BlkActionState) entry;
1456 /* internal snapshot private data */
1457 typedef struct InternalSnapshotState {
1458 BlkActionState common;
1459 BlockDriverState *bs;
1460 AioContext *aio_context;
1461 QEMUSnapshotInfo sn;
1462 bool created;
1463 } InternalSnapshotState;
1466 static int action_check_completion_mode(BlkActionState *s, Error **errp)
1468 if (s->txn_props->completion_mode != ACTION_COMPLETION_MODE_INDIVIDUAL) {
1469 error_setg(errp,
1470 "Action '%s' does not support Transaction property "
1471 "completion-mode = %s",
1472 TransactionActionKind_lookup[s->action->type],
1473 ActionCompletionMode_lookup[s->txn_props->completion_mode]);
1474 return -1;
1476 return 0;
1479 static void internal_snapshot_prepare(BlkActionState *common,
1480 Error **errp)
1482 Error *local_err = NULL;
1483 const char *device;
1484 const char *name;
1485 BlockDriverState *bs;
1486 QEMUSnapshotInfo old_sn, *sn;
1487 bool ret;
1488 qemu_timeval tv;
1489 BlockdevSnapshotInternal *internal;
1490 InternalSnapshotState *state;
1491 int ret1;
1493 g_assert(common->action->type ==
1494 TRANSACTION_ACTION_KIND_BLOCKDEV_SNAPSHOT_INTERNAL_SYNC);
1495 internal = common->action->u.blockdev_snapshot_internal_sync.data;
1496 state = DO_UPCAST(InternalSnapshotState, common, common);
1498 /* 1. parse input */
1499 device = internal->device;
1500 name = internal->name;
1502 /* 2. check for validation */
1503 if (action_check_completion_mode(common, errp) < 0) {
1504 return;
1507 bs = qmp_get_root_bs(device, errp);
1508 if (!bs) {
1509 return;
1512 /* AioContext is released in .clean() */
1513 state->aio_context = bdrv_get_aio_context(bs);
1514 aio_context_acquire(state->aio_context);
1516 state->bs = bs;
1517 bdrv_drained_begin(bs);
1519 if (bdrv_op_is_blocked(bs, BLOCK_OP_TYPE_INTERNAL_SNAPSHOT, errp)) {
1520 return;
1523 if (bdrv_is_read_only(bs)) {
1524 error_setg(errp, "Device '%s' is read only", device);
1525 return;
1528 if (!bdrv_can_snapshot(bs)) {
1529 error_setg(errp, "Block format '%s' used by device '%s' "
1530 "does not support internal snapshots",
1531 bs->drv->format_name, device);
1532 return;
1535 if (!strlen(name)) {
1536 error_setg(errp, "Name is empty");
1537 return;
1540 /* check whether a snapshot with name exist */
1541 ret = bdrv_snapshot_find_by_id_and_name(bs, NULL, name, &old_sn,
1542 &local_err);
1543 if (local_err) {
1544 error_propagate(errp, local_err);
1545 return;
1546 } else if (ret) {
1547 error_setg(errp,
1548 "Snapshot with name '%s' already exists on device '%s'",
1549 name, device);
1550 return;
1553 /* 3. take the snapshot */
1554 sn = &state->sn;
1555 pstrcpy(sn->name, sizeof(sn->name), name);
1556 qemu_gettimeofday(&tv);
1557 sn->date_sec = tv.tv_sec;
1558 sn->date_nsec = tv.tv_usec * 1000;
1559 sn->vm_clock_nsec = qemu_clock_get_ns(QEMU_CLOCK_VIRTUAL);
1561 ret1 = bdrv_snapshot_create(bs, sn);
1562 if (ret1 < 0) {
1563 error_setg_errno(errp, -ret1,
1564 "Failed to create snapshot '%s' on device '%s'",
1565 name, device);
1566 return;
1569 /* 4. succeed, mark a snapshot is created */
1570 state->created = true;
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 Error *local_error = NULL;
1581 if (!state->created) {
1582 return;
1585 if (bdrv_snapshot_delete(bs, sn->id_str, sn->name, &local_error) < 0) {
1586 error_reportf_err(local_error,
1587 "Failed to delete snapshot with id '%s' and "
1588 "name '%s' on device '%s' in abort: ",
1589 sn->id_str, sn->name,
1590 bdrv_get_device_name(bs));
1594 static void internal_snapshot_clean(BlkActionState *common)
1596 InternalSnapshotState *state = DO_UPCAST(InternalSnapshotState,
1597 common, common);
1599 if (state->aio_context) {
1600 if (state->bs) {
1601 bdrv_drained_end(state->bs);
1603 aio_context_release(state->aio_context);
1607 /* external snapshot private data */
1608 typedef struct ExternalSnapshotState {
1609 BlkActionState common;
1610 BlockDriverState *old_bs;
1611 BlockDriverState *new_bs;
1612 AioContext *aio_context;
1613 } ExternalSnapshotState;
1615 static void external_snapshot_prepare(BlkActionState *common,
1616 Error **errp)
1618 int flags = 0;
1619 QDict *options = NULL;
1620 Error *local_err = NULL;
1621 /* Device and node name of the image to generate the snapshot from */
1622 const char *device;
1623 const char *node_name;
1624 /* Reference to the new image (for 'blockdev-snapshot') */
1625 const char *snapshot_ref;
1626 /* File name of the new image (for 'blockdev-snapshot-sync') */
1627 const char *new_image_file;
1628 ExternalSnapshotState *state =
1629 DO_UPCAST(ExternalSnapshotState, common, common);
1630 TransactionAction *action = common->action;
1632 /* 'blockdev-snapshot' and 'blockdev-snapshot-sync' have similar
1633 * purpose but a different set of parameters */
1634 switch (action->type) {
1635 case TRANSACTION_ACTION_KIND_BLOCKDEV_SNAPSHOT:
1637 BlockdevSnapshot *s = action->u.blockdev_snapshot.data;
1638 device = s->node;
1639 node_name = s->node;
1640 new_image_file = NULL;
1641 snapshot_ref = s->overlay;
1643 break;
1644 case TRANSACTION_ACTION_KIND_BLOCKDEV_SNAPSHOT_SYNC:
1646 BlockdevSnapshotSync *s = action->u.blockdev_snapshot_sync.data;
1647 device = s->has_device ? s->device : NULL;
1648 node_name = s->has_node_name ? s->node_name : NULL;
1649 new_image_file = s->snapshot_file;
1650 snapshot_ref = NULL;
1652 break;
1653 default:
1654 g_assert_not_reached();
1657 /* start processing */
1658 if (action_check_completion_mode(common, errp) < 0) {
1659 return;
1662 state->old_bs = bdrv_lookup_bs(device, node_name, errp);
1663 if (!state->old_bs) {
1664 return;
1667 /* Acquire AioContext now so any threads operating on old_bs stop */
1668 state->aio_context = bdrv_get_aio_context(state->old_bs);
1669 aio_context_acquire(state->aio_context);
1670 bdrv_drained_begin(state->old_bs);
1672 if (!bdrv_is_inserted(state->old_bs)) {
1673 error_setg(errp, QERR_DEVICE_HAS_NO_MEDIUM, device);
1674 return;
1677 if (bdrv_op_is_blocked(state->old_bs,
1678 BLOCK_OP_TYPE_EXTERNAL_SNAPSHOT, errp)) {
1679 return;
1682 if (!bdrv_is_read_only(state->old_bs)) {
1683 if (bdrv_flush(state->old_bs)) {
1684 error_setg(errp, QERR_IO_ERROR);
1685 return;
1689 if (!bdrv_is_first_non_filter(state->old_bs)) {
1690 error_setg(errp, QERR_FEATURE_DISABLED, "snapshot");
1691 return;
1694 if (action->type == TRANSACTION_ACTION_KIND_BLOCKDEV_SNAPSHOT_SYNC) {
1695 BlockdevSnapshotSync *s = action->u.blockdev_snapshot_sync.data;
1696 const char *format = s->has_format ? s->format : "qcow2";
1697 enum NewImageMode mode;
1698 const char *snapshot_node_name =
1699 s->has_snapshot_node_name ? s->snapshot_node_name : NULL;
1701 if (node_name && !snapshot_node_name) {
1702 error_setg(errp, "New snapshot node name missing");
1703 return;
1706 if (snapshot_node_name &&
1707 bdrv_lookup_bs(snapshot_node_name, snapshot_node_name, NULL)) {
1708 error_setg(errp, "New snapshot node name already in use");
1709 return;
1712 flags = state->old_bs->open_flags;
1713 flags &= ~(BDRV_O_SNAPSHOT | BDRV_O_NO_BACKING | BDRV_O_COPY_ON_READ);
1715 /* create new image w/backing file */
1716 mode = s->has_mode ? s->mode : NEW_IMAGE_MODE_ABSOLUTE_PATHS;
1717 if (mode != NEW_IMAGE_MODE_EXISTING) {
1718 int64_t size = bdrv_getlength(state->old_bs);
1719 if (size < 0) {
1720 error_setg_errno(errp, -size, "bdrv_getlength failed");
1721 return;
1723 bdrv_img_create(new_image_file, format,
1724 state->old_bs->filename,
1725 state->old_bs->drv->format_name,
1726 NULL, size, flags, &local_err, false);
1727 if (local_err) {
1728 error_propagate(errp, local_err);
1729 return;
1733 options = qdict_new();
1734 if (s->has_snapshot_node_name) {
1735 qdict_put(options, "node-name",
1736 qstring_from_str(snapshot_node_name));
1738 qdict_put(options, "driver", qstring_from_str(format));
1740 flags |= BDRV_O_NO_BACKING;
1743 state->new_bs = bdrv_open(new_image_file, snapshot_ref, options, flags,
1744 errp);
1745 /* We will manually add the backing_hd field to the bs later */
1746 if (!state->new_bs) {
1747 return;
1750 if (bdrv_has_blk(state->new_bs)) {
1751 error_setg(errp, "The snapshot is already in use");
1752 return;
1755 if (bdrv_op_is_blocked(state->new_bs, BLOCK_OP_TYPE_EXTERNAL_SNAPSHOT,
1756 errp)) {
1757 return;
1760 if (state->new_bs->backing != NULL) {
1761 error_setg(errp, "The snapshot already has a backing image");
1762 return;
1765 if (!state->new_bs->drv->supports_backing) {
1766 error_setg(errp, "The snapshot does not support backing images");
1770 static void external_snapshot_commit(BlkActionState *common)
1772 ExternalSnapshotState *state =
1773 DO_UPCAST(ExternalSnapshotState, common, common);
1775 bdrv_set_aio_context(state->new_bs, state->aio_context);
1777 /* This removes our old bs and adds the new bs */
1778 bdrv_append(state->new_bs, state->old_bs);
1779 /* We don't need (or want) to use the transactional
1780 * bdrv_reopen_multiple() across all the entries at once, because we
1781 * don't want to abort all of them if one of them fails the reopen */
1782 if (!state->old_bs->copy_on_read) {
1783 bdrv_reopen(state->old_bs, state->old_bs->open_flags & ~BDRV_O_RDWR,
1784 NULL);
1788 static void external_snapshot_abort(BlkActionState *common)
1790 ExternalSnapshotState *state =
1791 DO_UPCAST(ExternalSnapshotState, common, common);
1792 if (state->new_bs) {
1793 bdrv_unref(state->new_bs);
1797 static void external_snapshot_clean(BlkActionState *common)
1799 ExternalSnapshotState *state =
1800 DO_UPCAST(ExternalSnapshotState, common, common);
1801 if (state->aio_context) {
1802 bdrv_drained_end(state->old_bs);
1803 aio_context_release(state->aio_context);
1807 typedef struct DriveBackupState {
1808 BlkActionState common;
1809 BlockDriverState *bs;
1810 AioContext *aio_context;
1811 BlockJob *job;
1812 } DriveBackupState;
1814 static void do_drive_backup(DriveBackup *backup, BlockJobTxn *txn,
1815 Error **errp);
1817 static void drive_backup_prepare(BlkActionState *common, Error **errp)
1819 DriveBackupState *state = DO_UPCAST(DriveBackupState, common, common);
1820 BlockDriverState *bs;
1821 DriveBackup *backup;
1822 Error *local_err = NULL;
1824 assert(common->action->type == TRANSACTION_ACTION_KIND_DRIVE_BACKUP);
1825 backup = common->action->u.drive_backup.data;
1827 bs = qmp_get_root_bs(backup->device, errp);
1828 if (!bs) {
1829 return;
1832 /* AioContext is released in .clean() */
1833 state->aio_context = bdrv_get_aio_context(bs);
1834 aio_context_acquire(state->aio_context);
1835 bdrv_drained_begin(bs);
1836 state->bs = bs;
1838 do_drive_backup(backup, common->block_job_txn, &local_err);
1839 if (local_err) {
1840 error_propagate(errp, local_err);
1841 return;
1844 state->job = state->bs->job;
1847 static void drive_backup_abort(BlkActionState *common)
1849 DriveBackupState *state = DO_UPCAST(DriveBackupState, common, common);
1850 BlockDriverState *bs = state->bs;
1852 /* Only cancel if it's the job we started */
1853 if (bs && bs->job && bs->job == state->job) {
1854 block_job_cancel_sync(bs->job);
1858 static void drive_backup_clean(BlkActionState *common)
1860 DriveBackupState *state = DO_UPCAST(DriveBackupState, common, common);
1862 if (state->aio_context) {
1863 bdrv_drained_end(state->bs);
1864 aio_context_release(state->aio_context);
1868 typedef struct BlockdevBackupState {
1869 BlkActionState common;
1870 BlockDriverState *bs;
1871 BlockJob *job;
1872 AioContext *aio_context;
1873 } BlockdevBackupState;
1875 static void do_blockdev_backup(BlockdevBackup *backup, BlockJobTxn *txn,
1876 Error **errp);
1878 static void blockdev_backup_prepare(BlkActionState *common, Error **errp)
1880 BlockdevBackupState *state = DO_UPCAST(BlockdevBackupState, common, common);
1881 BlockdevBackup *backup;
1882 BlockDriverState *bs, *target;
1883 Error *local_err = NULL;
1885 assert(common->action->type == TRANSACTION_ACTION_KIND_BLOCKDEV_BACKUP);
1886 backup = common->action->u.blockdev_backup.data;
1888 bs = qmp_get_root_bs(backup->device, errp);
1889 if (!bs) {
1890 return;
1893 target = bdrv_lookup_bs(backup->target, backup->target, errp);
1894 if (!target) {
1895 return;
1898 /* AioContext is released in .clean() */
1899 state->aio_context = bdrv_get_aio_context(bs);
1900 if (state->aio_context != bdrv_get_aio_context(target)) {
1901 state->aio_context = NULL;
1902 error_setg(errp, "Backup between two IO threads is not implemented");
1903 return;
1905 aio_context_acquire(state->aio_context);
1906 state->bs = bs;
1907 bdrv_drained_begin(state->bs);
1909 do_blockdev_backup(backup, common->block_job_txn, &local_err);
1910 if (local_err) {
1911 error_propagate(errp, local_err);
1912 return;
1915 state->job = state->bs->job;
1918 static void blockdev_backup_abort(BlkActionState *common)
1920 BlockdevBackupState *state = DO_UPCAST(BlockdevBackupState, common, common);
1921 BlockDriverState *bs = state->bs;
1923 /* Only cancel if it's the job we started */
1924 if (bs && bs->job && bs->job == state->job) {
1925 block_job_cancel_sync(bs->job);
1929 static void blockdev_backup_clean(BlkActionState *common)
1931 BlockdevBackupState *state = DO_UPCAST(BlockdevBackupState, common, common);
1933 if (state->aio_context) {
1934 bdrv_drained_end(state->bs);
1935 aio_context_release(state->aio_context);
1939 typedef struct BlockDirtyBitmapState {
1940 BlkActionState common;
1941 BdrvDirtyBitmap *bitmap;
1942 BlockDriverState *bs;
1943 AioContext *aio_context;
1944 HBitmap *backup;
1945 bool prepared;
1946 } BlockDirtyBitmapState;
1948 static void block_dirty_bitmap_add_prepare(BlkActionState *common,
1949 Error **errp)
1951 Error *local_err = NULL;
1952 BlockDirtyBitmapAdd *action;
1953 BlockDirtyBitmapState *state = DO_UPCAST(BlockDirtyBitmapState,
1954 common, common);
1956 if (action_check_completion_mode(common, errp) < 0) {
1957 return;
1960 action = common->action->u.block_dirty_bitmap_add.data;
1961 /* AIO context taken and released within qmp_block_dirty_bitmap_add */
1962 qmp_block_dirty_bitmap_add(action->node, action->name,
1963 action->has_granularity, action->granularity,
1964 &local_err);
1966 if (!local_err) {
1967 state->prepared = true;
1968 } else {
1969 error_propagate(errp, local_err);
1973 static void block_dirty_bitmap_add_abort(BlkActionState *common)
1975 BlockDirtyBitmapAdd *action;
1976 BlockDirtyBitmapState *state = DO_UPCAST(BlockDirtyBitmapState,
1977 common, common);
1979 action = common->action->u.block_dirty_bitmap_add.data;
1980 /* Should not be able to fail: IF the bitmap was added via .prepare(),
1981 * then the node reference and bitmap name must have been valid.
1983 if (state->prepared) {
1984 qmp_block_dirty_bitmap_remove(action->node, action->name, &error_abort);
1988 static void block_dirty_bitmap_clear_prepare(BlkActionState *common,
1989 Error **errp)
1991 BlockDirtyBitmapState *state = DO_UPCAST(BlockDirtyBitmapState,
1992 common, common);
1993 BlockDirtyBitmap *action;
1995 if (action_check_completion_mode(common, errp) < 0) {
1996 return;
1999 action = common->action->u.block_dirty_bitmap_clear.data;
2000 state->bitmap = block_dirty_bitmap_lookup(action->node,
2001 action->name,
2002 &state->bs,
2003 &state->aio_context,
2004 errp);
2005 if (!state->bitmap) {
2006 return;
2009 if (bdrv_dirty_bitmap_frozen(state->bitmap)) {
2010 error_setg(errp, "Cannot modify a frozen bitmap");
2011 return;
2012 } else if (!bdrv_dirty_bitmap_enabled(state->bitmap)) {
2013 error_setg(errp, "Cannot clear a disabled bitmap");
2014 return;
2017 bdrv_clear_dirty_bitmap(state->bitmap, &state->backup);
2018 /* AioContext is released in .clean() */
2021 static void block_dirty_bitmap_clear_abort(BlkActionState *common)
2023 BlockDirtyBitmapState *state = DO_UPCAST(BlockDirtyBitmapState,
2024 common, common);
2026 bdrv_undo_clear_dirty_bitmap(state->bitmap, state->backup);
2029 static void block_dirty_bitmap_clear_commit(BlkActionState *common)
2031 BlockDirtyBitmapState *state = DO_UPCAST(BlockDirtyBitmapState,
2032 common, common);
2034 hbitmap_free(state->backup);
2037 static void block_dirty_bitmap_clear_clean(BlkActionState *common)
2039 BlockDirtyBitmapState *state = DO_UPCAST(BlockDirtyBitmapState,
2040 common, common);
2042 if (state->aio_context) {
2043 aio_context_release(state->aio_context);
2047 static void abort_prepare(BlkActionState *common, Error **errp)
2049 error_setg(errp, "Transaction aborted using Abort action");
2052 static void abort_commit(BlkActionState *common)
2054 g_assert_not_reached(); /* this action never succeeds */
2057 static const BlkActionOps actions[] = {
2058 [TRANSACTION_ACTION_KIND_BLOCKDEV_SNAPSHOT] = {
2059 .instance_size = sizeof(ExternalSnapshotState),
2060 .prepare = external_snapshot_prepare,
2061 .commit = external_snapshot_commit,
2062 .abort = external_snapshot_abort,
2063 .clean = external_snapshot_clean,
2065 [TRANSACTION_ACTION_KIND_BLOCKDEV_SNAPSHOT_SYNC] = {
2066 .instance_size = sizeof(ExternalSnapshotState),
2067 .prepare = external_snapshot_prepare,
2068 .commit = external_snapshot_commit,
2069 .abort = external_snapshot_abort,
2070 .clean = external_snapshot_clean,
2072 [TRANSACTION_ACTION_KIND_DRIVE_BACKUP] = {
2073 .instance_size = sizeof(DriveBackupState),
2074 .prepare = drive_backup_prepare,
2075 .abort = drive_backup_abort,
2076 .clean = drive_backup_clean,
2078 [TRANSACTION_ACTION_KIND_BLOCKDEV_BACKUP] = {
2079 .instance_size = sizeof(BlockdevBackupState),
2080 .prepare = blockdev_backup_prepare,
2081 .abort = blockdev_backup_abort,
2082 .clean = blockdev_backup_clean,
2084 [TRANSACTION_ACTION_KIND_ABORT] = {
2085 .instance_size = sizeof(BlkActionState),
2086 .prepare = abort_prepare,
2087 .commit = abort_commit,
2089 [TRANSACTION_ACTION_KIND_BLOCKDEV_SNAPSHOT_INTERNAL_SYNC] = {
2090 .instance_size = sizeof(InternalSnapshotState),
2091 .prepare = internal_snapshot_prepare,
2092 .abort = internal_snapshot_abort,
2093 .clean = internal_snapshot_clean,
2095 [TRANSACTION_ACTION_KIND_BLOCK_DIRTY_BITMAP_ADD] = {
2096 .instance_size = sizeof(BlockDirtyBitmapState),
2097 .prepare = block_dirty_bitmap_add_prepare,
2098 .abort = block_dirty_bitmap_add_abort,
2100 [TRANSACTION_ACTION_KIND_BLOCK_DIRTY_BITMAP_CLEAR] = {
2101 .instance_size = sizeof(BlockDirtyBitmapState),
2102 .prepare = block_dirty_bitmap_clear_prepare,
2103 .commit = block_dirty_bitmap_clear_commit,
2104 .abort = block_dirty_bitmap_clear_abort,
2105 .clean = block_dirty_bitmap_clear_clean,
2110 * Allocate a TransactionProperties structure if necessary, and fill
2111 * that structure with desired defaults if they are unset.
2113 static TransactionProperties *get_transaction_properties(
2114 TransactionProperties *props)
2116 if (!props) {
2117 props = g_new0(TransactionProperties, 1);
2120 if (!props->has_completion_mode) {
2121 props->has_completion_mode = true;
2122 props->completion_mode = ACTION_COMPLETION_MODE_INDIVIDUAL;
2125 return props;
2129 * 'Atomic' group operations. The operations are performed as a set, and if
2130 * any fail then we roll back all operations in the group.
2132 void qmp_transaction(TransactionActionList *dev_list,
2133 bool has_props,
2134 struct TransactionProperties *props,
2135 Error **errp)
2137 TransactionActionList *dev_entry = dev_list;
2138 BlockJobTxn *block_job_txn = NULL;
2139 BlkActionState *state, *next;
2140 Error *local_err = NULL;
2142 QSIMPLEQ_HEAD(snap_bdrv_states, BlkActionState) snap_bdrv_states;
2143 QSIMPLEQ_INIT(&snap_bdrv_states);
2145 /* Does this transaction get canceled as a group on failure?
2146 * If not, we don't really need to make a BlockJobTxn.
2148 props = get_transaction_properties(props);
2149 if (props->completion_mode != ACTION_COMPLETION_MODE_INDIVIDUAL) {
2150 block_job_txn = block_job_txn_new();
2153 /* drain all i/o before any operations */
2154 bdrv_drain_all();
2156 /* We don't do anything in this loop that commits us to the operations */
2157 while (NULL != dev_entry) {
2158 TransactionAction *dev_info = NULL;
2159 const BlkActionOps *ops;
2161 dev_info = dev_entry->value;
2162 dev_entry = dev_entry->next;
2164 assert(dev_info->type < ARRAY_SIZE(actions));
2166 ops = &actions[dev_info->type];
2167 assert(ops->instance_size > 0);
2169 state = g_malloc0(ops->instance_size);
2170 state->ops = ops;
2171 state->action = dev_info;
2172 state->block_job_txn = block_job_txn;
2173 state->txn_props = props;
2174 QSIMPLEQ_INSERT_TAIL(&snap_bdrv_states, state, entry);
2176 state->ops->prepare(state, &local_err);
2177 if (local_err) {
2178 error_propagate(errp, local_err);
2179 goto delete_and_fail;
2183 QSIMPLEQ_FOREACH(state, &snap_bdrv_states, entry) {
2184 if (state->ops->commit) {
2185 state->ops->commit(state);
2189 /* success */
2190 goto exit;
2192 delete_and_fail:
2193 /* failure, and it is all-or-none; roll back all operations */
2194 QSIMPLEQ_FOREACH(state, &snap_bdrv_states, entry) {
2195 if (state->ops->abort) {
2196 state->ops->abort(state);
2199 exit:
2200 QSIMPLEQ_FOREACH_SAFE(state, &snap_bdrv_states, entry, next) {
2201 if (state->ops->clean) {
2202 state->ops->clean(state);
2204 g_free(state);
2206 if (!has_props) {
2207 qapi_free_TransactionProperties(props);
2209 block_job_txn_unref(block_job_txn);
2212 void qmp_eject(bool has_device, const char *device,
2213 bool has_id, const char *id,
2214 bool has_force, bool force, Error **errp)
2216 Error *local_err = NULL;
2217 int rc;
2219 if (!has_force) {
2220 force = false;
2223 rc = do_open_tray(has_device ? device : NULL,
2224 has_id ? id : NULL,
2225 force, &local_err);
2226 if (rc && rc != -ENOSYS) {
2227 error_propagate(errp, local_err);
2228 return;
2230 error_free(local_err);
2232 qmp_x_blockdev_remove_medium(has_device, device, has_id, id, errp);
2235 void qmp_block_passwd(bool has_device, const char *device,
2236 bool has_node_name, const char *node_name,
2237 const char *password, Error **errp)
2239 Error *local_err = NULL;
2240 BlockDriverState *bs;
2241 AioContext *aio_context;
2243 bs = bdrv_lookup_bs(has_device ? device : NULL,
2244 has_node_name ? node_name : NULL,
2245 &local_err);
2246 if (local_err) {
2247 error_propagate(errp, local_err);
2248 return;
2251 aio_context = bdrv_get_aio_context(bs);
2252 aio_context_acquire(aio_context);
2254 bdrv_add_key(bs, password, errp);
2256 aio_context_release(aio_context);
2260 * Attempt to open the tray of @device.
2261 * If @force, ignore its tray lock.
2262 * Else, if the tray is locked, don't open it, but ask the guest to open it.
2263 * On error, store an error through @errp and return -errno.
2264 * If @device does not exist, return -ENODEV.
2265 * If it has no removable media, return -ENOTSUP.
2266 * If it has no tray, return -ENOSYS.
2267 * If the guest was asked to open the tray, return -EINPROGRESS.
2268 * Else, return 0.
2270 static int do_open_tray(const char *blk_name, const char *qdev_id,
2271 bool force, Error **errp)
2273 BlockBackend *blk;
2274 const char *device = qdev_id ?: blk_name;
2275 bool locked;
2277 blk = qmp_get_blk(blk_name, qdev_id, errp);
2278 if (!blk) {
2279 return -ENODEV;
2282 if (!blk_dev_has_removable_media(blk)) {
2283 error_setg(errp, "Device '%s' is not removable", device);
2284 return -ENOTSUP;
2287 if (!blk_dev_has_tray(blk)) {
2288 error_setg(errp, "Device '%s' does not have a tray", device);
2289 return -ENOSYS;
2292 if (blk_dev_is_tray_open(blk)) {
2293 return 0;
2296 locked = blk_dev_is_medium_locked(blk);
2297 if (locked) {
2298 blk_dev_eject_request(blk, force);
2301 if (!locked || force) {
2302 blk_dev_change_media_cb(blk, false);
2305 if (locked && !force) {
2306 error_setg(errp, "Device '%s' is locked and force was not specified, "
2307 "wait for tray to open and try again", device);
2308 return -EINPROGRESS;
2311 return 0;
2314 void qmp_blockdev_open_tray(bool has_device, const char *device,
2315 bool has_id, const char *id,
2316 bool has_force, bool force,
2317 Error **errp)
2319 Error *local_err = NULL;
2320 int rc;
2322 if (!has_force) {
2323 force = false;
2325 rc = do_open_tray(has_device ? device : NULL,
2326 has_id ? id : NULL,
2327 force, &local_err);
2328 if (rc && rc != -ENOSYS && rc != -EINPROGRESS) {
2329 error_propagate(errp, local_err);
2330 return;
2332 error_free(local_err);
2335 void qmp_blockdev_close_tray(bool has_device, const char *device,
2336 bool has_id, const char *id,
2337 Error **errp)
2339 BlockBackend *blk;
2341 device = has_device ? device : NULL;
2342 id = has_id ? id : NULL;
2344 blk = qmp_get_blk(device, id, errp);
2345 if (!blk) {
2346 return;
2349 if (!blk_dev_has_removable_media(blk)) {
2350 error_setg(errp, "Device '%s' is not removable", device ?: id);
2351 return;
2354 if (!blk_dev_has_tray(blk)) {
2355 /* Ignore this command on tray-less devices */
2356 return;
2359 if (!blk_dev_is_tray_open(blk)) {
2360 return;
2363 blk_dev_change_media_cb(blk, true);
2366 void qmp_x_blockdev_remove_medium(bool has_device, const char *device,
2367 bool has_id, const char *id, Error **errp)
2369 BlockBackend *blk;
2370 BlockDriverState *bs;
2371 AioContext *aio_context;
2372 bool has_attached_device;
2374 device = has_device ? device : NULL;
2375 id = has_id ? id : NULL;
2377 blk = qmp_get_blk(device, id, errp);
2378 if (!blk) {
2379 return;
2382 /* For BBs without a device, we can exchange the BDS tree at will */
2383 has_attached_device = blk_get_attached_dev(blk);
2385 if (has_attached_device && !blk_dev_has_removable_media(blk)) {
2386 error_setg(errp, "Device '%s' is not removable", device ?: id);
2387 return;
2390 if (has_attached_device && blk_dev_has_tray(blk) &&
2391 !blk_dev_is_tray_open(blk))
2393 error_setg(errp, "Tray of device '%s' is not open", device ?: id);
2394 return;
2397 bs = blk_bs(blk);
2398 if (!bs) {
2399 return;
2402 aio_context = bdrv_get_aio_context(bs);
2403 aio_context_acquire(aio_context);
2405 if (bdrv_op_is_blocked(bs, BLOCK_OP_TYPE_EJECT, errp)) {
2406 goto out;
2409 blk_remove_bs(blk);
2411 if (!blk_dev_has_tray(blk)) {
2412 /* For tray-less devices, blockdev-open-tray is a no-op (or may not be
2413 * called at all); therefore, the medium needs to be ejected here.
2414 * Do it after blk_remove_bs() so blk_is_inserted(blk) returns the @load
2415 * value passed here (i.e. false). */
2416 blk_dev_change_media_cb(blk, false);
2419 out:
2420 aio_context_release(aio_context);
2423 static void qmp_blockdev_insert_anon_medium(BlockBackend *blk,
2424 BlockDriverState *bs, Error **errp)
2426 bool has_device;
2428 /* For BBs without a device, we can exchange the BDS tree at will */
2429 has_device = blk_get_attached_dev(blk);
2431 if (has_device && !blk_dev_has_removable_media(blk)) {
2432 error_setg(errp, "Device is not removable");
2433 return;
2436 if (has_device && blk_dev_has_tray(blk) && !blk_dev_is_tray_open(blk)) {
2437 error_setg(errp, "Tray of the device is not open");
2438 return;
2441 if (blk_bs(blk)) {
2442 error_setg(errp, "There already is a medium in the device");
2443 return;
2446 blk_insert_bs(blk, bs);
2448 if (!blk_dev_has_tray(blk)) {
2449 /* For tray-less devices, blockdev-close-tray is a no-op (or may not be
2450 * called at all); therefore, the medium needs to be pushed into the
2451 * slot here.
2452 * Do it after blk_insert_bs() so blk_is_inserted(blk) returns the @load
2453 * value passed here (i.e. true). */
2454 blk_dev_change_media_cb(blk, true);
2458 void qmp_x_blockdev_insert_medium(bool has_device, const char *device,
2459 bool has_id, const char *id,
2460 const char *node_name, Error **errp)
2462 BlockBackend *blk;
2463 BlockDriverState *bs;
2465 blk = qmp_get_blk(has_device ? device : NULL,
2466 has_id ? id : NULL,
2467 errp);
2468 if (!blk) {
2469 return;
2472 bs = bdrv_find_node(node_name);
2473 if (!bs) {
2474 error_setg(errp, "Node '%s' not found", node_name);
2475 return;
2478 if (bdrv_has_blk(bs)) {
2479 error_setg(errp, "Node '%s' is already in use", node_name);
2480 return;
2483 qmp_blockdev_insert_anon_medium(blk, bs, errp);
2486 void qmp_blockdev_change_medium(bool has_device, const char *device,
2487 bool has_id, const char *id,
2488 const char *filename,
2489 bool has_format, const char *format,
2490 bool has_read_only,
2491 BlockdevChangeReadOnlyMode read_only,
2492 Error **errp)
2494 BlockBackend *blk;
2495 BlockDriverState *medium_bs = NULL;
2496 int bdrv_flags;
2497 bool detect_zeroes;
2498 int rc;
2499 QDict *options = NULL;
2500 Error *err = NULL;
2502 blk = qmp_get_blk(has_device ? device : NULL,
2503 has_id ? id : NULL,
2504 errp);
2505 if (!blk) {
2506 goto fail;
2509 if (blk_bs(blk)) {
2510 blk_update_root_state(blk);
2513 bdrv_flags = blk_get_open_flags_from_root_state(blk);
2514 bdrv_flags &= ~(BDRV_O_TEMPORARY | BDRV_O_SNAPSHOT | BDRV_O_NO_BACKING |
2515 BDRV_O_PROTOCOL);
2517 if (!has_read_only) {
2518 read_only = BLOCKDEV_CHANGE_READ_ONLY_MODE_RETAIN;
2521 switch (read_only) {
2522 case BLOCKDEV_CHANGE_READ_ONLY_MODE_RETAIN:
2523 break;
2525 case BLOCKDEV_CHANGE_READ_ONLY_MODE_READ_ONLY:
2526 bdrv_flags &= ~BDRV_O_RDWR;
2527 break;
2529 case BLOCKDEV_CHANGE_READ_ONLY_MODE_READ_WRITE:
2530 bdrv_flags |= BDRV_O_RDWR;
2531 break;
2533 default:
2534 abort();
2537 options = qdict_new();
2538 detect_zeroes = blk_get_detect_zeroes_from_root_state(blk);
2539 qdict_put(options, "detect-zeroes",
2540 qstring_from_str(detect_zeroes ? "on" : "off"));
2542 if (has_format) {
2543 qdict_put(options, "driver", qstring_from_str(format));
2546 medium_bs = bdrv_open(filename, NULL, options, bdrv_flags, errp);
2547 if (!medium_bs) {
2548 goto fail;
2551 bdrv_add_key(medium_bs, NULL, &err);
2552 if (err) {
2553 error_propagate(errp, err);
2554 goto fail;
2557 rc = do_open_tray(has_device ? device : NULL,
2558 has_id ? id : NULL,
2559 false, &err);
2560 if (rc && rc != -ENOSYS) {
2561 error_propagate(errp, err);
2562 goto fail;
2564 error_free(err);
2565 err = NULL;
2567 qmp_x_blockdev_remove_medium(has_device, device, has_id, id, &err);
2568 if (err) {
2569 error_propagate(errp, err);
2570 goto fail;
2573 qmp_blockdev_insert_anon_medium(blk, medium_bs, &err);
2574 if (err) {
2575 error_propagate(errp, err);
2576 goto fail;
2579 qmp_blockdev_close_tray(has_device, device, has_id, id, errp);
2581 fail:
2582 /* If the medium has been inserted, the device has its own reference, so
2583 * ours must be relinquished; and if it has not been inserted successfully,
2584 * the reference must be relinquished anyway */
2585 bdrv_unref(medium_bs);
2588 /* throttling disk I/O limits */
2589 void qmp_block_set_io_throttle(BlockIOThrottle *arg, Error **errp)
2591 ThrottleConfig cfg;
2592 BlockDriverState *bs;
2593 BlockBackend *blk;
2594 AioContext *aio_context;
2596 blk = qmp_get_blk(arg->has_device ? arg->device : NULL,
2597 arg->has_id ? arg->id : NULL,
2598 errp);
2599 if (!blk) {
2600 return;
2603 aio_context = blk_get_aio_context(blk);
2604 aio_context_acquire(aio_context);
2606 bs = blk_bs(blk);
2607 if (!bs) {
2608 error_setg(errp, "Device has no medium");
2609 goto out;
2612 throttle_config_init(&cfg);
2613 cfg.buckets[THROTTLE_BPS_TOTAL].avg = arg->bps;
2614 cfg.buckets[THROTTLE_BPS_READ].avg = arg->bps_rd;
2615 cfg.buckets[THROTTLE_BPS_WRITE].avg = arg->bps_wr;
2617 cfg.buckets[THROTTLE_OPS_TOTAL].avg = arg->iops;
2618 cfg.buckets[THROTTLE_OPS_READ].avg = arg->iops_rd;
2619 cfg.buckets[THROTTLE_OPS_WRITE].avg = arg->iops_wr;
2621 if (arg->has_bps_max) {
2622 cfg.buckets[THROTTLE_BPS_TOTAL].max = arg->bps_max;
2624 if (arg->has_bps_rd_max) {
2625 cfg.buckets[THROTTLE_BPS_READ].max = arg->bps_rd_max;
2627 if (arg->has_bps_wr_max) {
2628 cfg.buckets[THROTTLE_BPS_WRITE].max = arg->bps_wr_max;
2630 if (arg->has_iops_max) {
2631 cfg.buckets[THROTTLE_OPS_TOTAL].max = arg->iops_max;
2633 if (arg->has_iops_rd_max) {
2634 cfg.buckets[THROTTLE_OPS_READ].max = arg->iops_rd_max;
2636 if (arg->has_iops_wr_max) {
2637 cfg.buckets[THROTTLE_OPS_WRITE].max = arg->iops_wr_max;
2640 if (arg->has_bps_max_length) {
2641 cfg.buckets[THROTTLE_BPS_TOTAL].burst_length = arg->bps_max_length;
2643 if (arg->has_bps_rd_max_length) {
2644 cfg.buckets[THROTTLE_BPS_READ].burst_length = arg->bps_rd_max_length;
2646 if (arg->has_bps_wr_max_length) {
2647 cfg.buckets[THROTTLE_BPS_WRITE].burst_length = arg->bps_wr_max_length;
2649 if (arg->has_iops_max_length) {
2650 cfg.buckets[THROTTLE_OPS_TOTAL].burst_length = arg->iops_max_length;
2652 if (arg->has_iops_rd_max_length) {
2653 cfg.buckets[THROTTLE_OPS_READ].burst_length = arg->iops_rd_max_length;
2655 if (arg->has_iops_wr_max_length) {
2656 cfg.buckets[THROTTLE_OPS_WRITE].burst_length = arg->iops_wr_max_length;
2659 if (arg->has_iops_size) {
2660 cfg.op_size = arg->iops_size;
2663 if (!throttle_is_valid(&cfg, errp)) {
2664 goto out;
2667 if (throttle_enabled(&cfg)) {
2668 /* Enable I/O limits if they're not enabled yet, otherwise
2669 * just update the throttling group. */
2670 if (!blk_get_public(blk)->throttle_state) {
2671 blk_io_limits_enable(blk,
2672 arg->has_group ? arg->group :
2673 arg->has_device ? arg->device :
2674 arg->id);
2675 } else if (arg->has_group) {
2676 blk_io_limits_update_group(blk, arg->group);
2678 /* Set the new throttling configuration */
2679 blk_set_io_limits(blk, &cfg);
2680 } else if (blk_get_public(blk)->throttle_state) {
2681 /* If all throttling settings are set to 0, disable I/O limits */
2682 blk_io_limits_disable(blk);
2685 out:
2686 aio_context_release(aio_context);
2689 void qmp_block_dirty_bitmap_add(const char *node, const char *name,
2690 bool has_granularity, uint32_t granularity,
2691 Error **errp)
2693 AioContext *aio_context;
2694 BlockDriverState *bs;
2696 if (!name || name[0] == '\0') {
2697 error_setg(errp, "Bitmap name cannot be empty");
2698 return;
2701 bs = bdrv_lookup_bs(node, node, errp);
2702 if (!bs) {
2703 return;
2706 aio_context = bdrv_get_aio_context(bs);
2707 aio_context_acquire(aio_context);
2709 if (has_granularity) {
2710 if (granularity < 512 || !is_power_of_2(granularity)) {
2711 error_setg(errp, "Granularity must be power of 2 "
2712 "and at least 512");
2713 goto out;
2715 } else {
2716 /* Default to cluster size, if available: */
2717 granularity = bdrv_get_default_bitmap_granularity(bs);
2720 bdrv_create_dirty_bitmap(bs, granularity, name, errp);
2722 out:
2723 aio_context_release(aio_context);
2726 void qmp_block_dirty_bitmap_remove(const char *node, const char *name,
2727 Error **errp)
2729 AioContext *aio_context;
2730 BlockDriverState *bs;
2731 BdrvDirtyBitmap *bitmap;
2733 bitmap = block_dirty_bitmap_lookup(node, name, &bs, &aio_context, errp);
2734 if (!bitmap || !bs) {
2735 return;
2738 if (bdrv_dirty_bitmap_frozen(bitmap)) {
2739 error_setg(errp,
2740 "Bitmap '%s' is currently frozen and cannot be removed",
2741 name);
2742 goto out;
2744 bdrv_dirty_bitmap_make_anon(bitmap);
2745 bdrv_release_dirty_bitmap(bs, bitmap);
2747 out:
2748 aio_context_release(aio_context);
2752 * Completely clear a bitmap, for the purposes of synchronizing a bitmap
2753 * immediately after a full backup operation.
2755 void qmp_block_dirty_bitmap_clear(const char *node, const char *name,
2756 Error **errp)
2758 AioContext *aio_context;
2759 BdrvDirtyBitmap *bitmap;
2760 BlockDriverState *bs;
2762 bitmap = block_dirty_bitmap_lookup(node, name, &bs, &aio_context, errp);
2763 if (!bitmap || !bs) {
2764 return;
2767 if (bdrv_dirty_bitmap_frozen(bitmap)) {
2768 error_setg(errp,
2769 "Bitmap '%s' is currently frozen and cannot be modified",
2770 name);
2771 goto out;
2772 } else if (!bdrv_dirty_bitmap_enabled(bitmap)) {
2773 error_setg(errp,
2774 "Bitmap '%s' is currently disabled and cannot be cleared",
2775 name);
2776 goto out;
2779 bdrv_clear_dirty_bitmap(bitmap, NULL);
2781 out:
2782 aio_context_release(aio_context);
2785 void hmp_drive_del(Monitor *mon, const QDict *qdict)
2787 const char *id = qdict_get_str(qdict, "id");
2788 BlockBackend *blk;
2789 BlockDriverState *bs;
2790 AioContext *aio_context;
2791 Error *local_err = NULL;
2793 bs = bdrv_find_node(id);
2794 if (bs) {
2795 qmp_x_blockdev_del(id, &local_err);
2796 if (local_err) {
2797 error_report_err(local_err);
2799 return;
2802 blk = blk_by_name(id);
2803 if (!blk) {
2804 error_report("Device '%s' not found", id);
2805 return;
2808 if (!blk_legacy_dinfo(blk)) {
2809 error_report("Deleting device added with blockdev-add"
2810 " is not supported");
2811 return;
2814 aio_context = blk_get_aio_context(blk);
2815 aio_context_acquire(aio_context);
2817 bs = blk_bs(blk);
2818 if (bs) {
2819 if (bdrv_op_is_blocked(bs, BLOCK_OP_TYPE_DRIVE_DEL, &local_err)) {
2820 error_report_err(local_err);
2821 aio_context_release(aio_context);
2822 return;
2825 blk_remove_bs(blk);
2828 /* Make the BlockBackend and the attached BlockDriverState anonymous */
2829 monitor_remove_blk(blk);
2831 /* If this BlockBackend has a device attached to it, its refcount will be
2832 * decremented when the device is removed; otherwise we have to do so here.
2834 if (blk_get_attached_dev(blk)) {
2835 /* Further I/O must not pause the guest */
2836 blk_set_on_error(blk, BLOCKDEV_ON_ERROR_REPORT,
2837 BLOCKDEV_ON_ERROR_REPORT);
2838 } else {
2839 blk_unref(blk);
2842 aio_context_release(aio_context);
2845 void qmp_block_resize(bool has_device, const char *device,
2846 bool has_node_name, const char *node_name,
2847 int64_t size, Error **errp)
2849 Error *local_err = NULL;
2850 BlockDriverState *bs;
2851 AioContext *aio_context;
2852 int ret;
2854 bs = bdrv_lookup_bs(has_device ? device : NULL,
2855 has_node_name ? node_name : NULL,
2856 &local_err);
2857 if (local_err) {
2858 error_propagate(errp, local_err);
2859 return;
2862 aio_context = bdrv_get_aio_context(bs);
2863 aio_context_acquire(aio_context);
2865 if (!bdrv_is_first_non_filter(bs)) {
2866 error_setg(errp, QERR_FEATURE_DISABLED, "resize");
2867 goto out;
2870 if (size < 0) {
2871 error_setg(errp, QERR_INVALID_PARAMETER_VALUE, "size", "a >0 size");
2872 goto out;
2875 if (bdrv_op_is_blocked(bs, BLOCK_OP_TYPE_RESIZE, NULL)) {
2876 error_setg(errp, QERR_DEVICE_IN_USE, device);
2877 goto out;
2880 /* complete all in-flight operations before resizing the device */
2881 bdrv_drain_all();
2883 ret = bdrv_truncate(bs, size);
2884 switch (ret) {
2885 case 0:
2886 break;
2887 case -ENOMEDIUM:
2888 error_setg(errp, QERR_DEVICE_HAS_NO_MEDIUM, device);
2889 break;
2890 case -ENOTSUP:
2891 error_setg(errp, QERR_UNSUPPORTED);
2892 break;
2893 case -EACCES:
2894 error_setg(errp, "Device '%s' is read only", device);
2895 break;
2896 case -EBUSY:
2897 error_setg(errp, QERR_DEVICE_IN_USE, device);
2898 break;
2899 default:
2900 error_setg_errno(errp, -ret, "Could not resize");
2901 break;
2904 out:
2905 aio_context_release(aio_context);
2908 void qmp_block_stream(bool has_job_id, const char *job_id, const char *device,
2909 bool has_base, const char *base,
2910 bool has_base_node, const char *base_node,
2911 bool has_backing_file, const char *backing_file,
2912 bool has_speed, int64_t speed,
2913 bool has_on_error, BlockdevOnError on_error,
2914 Error **errp)
2916 BlockDriverState *bs, *iter;
2917 BlockDriverState *base_bs = NULL;
2918 AioContext *aio_context;
2919 Error *local_err = NULL;
2920 const char *base_name = NULL;
2922 if (!has_on_error) {
2923 on_error = BLOCKDEV_ON_ERROR_REPORT;
2926 bs = bdrv_lookup_bs(device, device, errp);
2927 if (!bs) {
2928 return;
2931 aio_context = bdrv_get_aio_context(bs);
2932 aio_context_acquire(aio_context);
2934 if (has_base && has_base_node) {
2935 error_setg(errp, "'base' and 'base-node' cannot be specified "
2936 "at the same time");
2937 goto out;
2940 if (has_base) {
2941 base_bs = bdrv_find_backing_image(bs, base);
2942 if (base_bs == NULL) {
2943 error_setg(errp, QERR_BASE_NOT_FOUND, base);
2944 goto out;
2946 assert(bdrv_get_aio_context(base_bs) == aio_context);
2947 base_name = base;
2950 if (has_base_node) {
2951 base_bs = bdrv_lookup_bs(NULL, base_node, errp);
2952 if (!base_bs) {
2953 goto out;
2955 if (bs == base_bs || !bdrv_chain_contains(bs, base_bs)) {
2956 error_setg(errp, "Node '%s' is not a backing image of '%s'",
2957 base_node, device);
2958 goto out;
2960 assert(bdrv_get_aio_context(base_bs) == aio_context);
2961 base_name = base_bs->filename;
2964 /* Check for op blockers in the whole chain between bs and base */
2965 for (iter = bs; iter && iter != base_bs; iter = backing_bs(iter)) {
2966 if (bdrv_op_is_blocked(iter, BLOCK_OP_TYPE_STREAM, errp)) {
2967 goto out;
2971 /* if we are streaming the entire chain, the result will have no backing
2972 * file, and specifying one is therefore an error */
2973 if (base_bs == NULL && has_backing_file) {
2974 error_setg(errp, "backing file specified, but streaming the "
2975 "entire chain");
2976 goto out;
2979 /* backing_file string overrides base bs filename */
2980 base_name = has_backing_file ? backing_file : base_name;
2982 stream_start(has_job_id ? job_id : NULL, bs, base_bs, base_name,
2983 has_speed ? speed : 0, on_error, &local_err);
2984 if (local_err) {
2985 error_propagate(errp, local_err);
2986 goto out;
2989 trace_qmp_block_stream(bs, bs->job);
2991 out:
2992 aio_context_release(aio_context);
2995 void qmp_block_commit(bool has_job_id, const char *job_id, const char *device,
2996 bool has_base, const char *base,
2997 bool has_top, const char *top,
2998 bool has_backing_file, const char *backing_file,
2999 bool has_speed, int64_t speed,
3000 Error **errp)
3002 BlockDriverState *bs;
3003 BlockDriverState *iter;
3004 BlockDriverState *base_bs, *top_bs;
3005 AioContext *aio_context;
3006 Error *local_err = NULL;
3007 /* This will be part of the QMP command, if/when the
3008 * BlockdevOnError change for blkmirror makes it in
3010 BlockdevOnError on_error = BLOCKDEV_ON_ERROR_REPORT;
3012 if (!has_speed) {
3013 speed = 0;
3016 /* Important Note:
3017 * libvirt relies on the DeviceNotFound error class in order to probe for
3018 * live commit feature versions; for this to work, we must make sure to
3019 * perform the device lookup before any generic errors that may occur in a
3020 * scenario in which all optional arguments are omitted. */
3021 bs = qmp_get_root_bs(device, &local_err);
3022 if (!bs) {
3023 bs = bdrv_lookup_bs(device, device, NULL);
3024 if (!bs) {
3025 error_free(local_err);
3026 error_set(errp, ERROR_CLASS_DEVICE_NOT_FOUND,
3027 "Device '%s' not found", device);
3028 } else {
3029 error_propagate(errp, local_err);
3031 return;
3034 aio_context = bdrv_get_aio_context(bs);
3035 aio_context_acquire(aio_context);
3037 if (bdrv_op_is_blocked(bs, BLOCK_OP_TYPE_COMMIT_SOURCE, errp)) {
3038 goto out;
3041 /* default top_bs is the active layer */
3042 top_bs = bs;
3044 if (has_top && top) {
3045 if (strcmp(bs->filename, top) != 0) {
3046 top_bs = bdrv_find_backing_image(bs, top);
3050 if (top_bs == NULL) {
3051 error_setg(errp, "Top image file %s not found", top ? top : "NULL");
3052 goto out;
3055 assert(bdrv_get_aio_context(top_bs) == aio_context);
3057 if (has_base && base) {
3058 base_bs = bdrv_find_backing_image(top_bs, base);
3059 } else {
3060 base_bs = bdrv_find_base(top_bs);
3063 if (base_bs == NULL) {
3064 error_setg(errp, QERR_BASE_NOT_FOUND, base ? base : "NULL");
3065 goto out;
3068 assert(bdrv_get_aio_context(base_bs) == aio_context);
3070 for (iter = top_bs; iter != backing_bs(base_bs); iter = backing_bs(iter)) {
3071 if (bdrv_op_is_blocked(iter, BLOCK_OP_TYPE_COMMIT_TARGET, errp)) {
3072 goto out;
3076 /* Do not allow attempts to commit an image into itself */
3077 if (top_bs == base_bs) {
3078 error_setg(errp, "cannot commit an image into itself");
3079 goto out;
3082 if (top_bs == bs) {
3083 if (has_backing_file) {
3084 error_setg(errp, "'backing-file' specified,"
3085 " but 'top' is the active layer");
3086 goto out;
3088 commit_active_start(has_job_id ? job_id : NULL, bs, base_bs,
3089 BLOCK_JOB_DEFAULT, speed, on_error, NULL, NULL,
3090 &local_err, false);
3091 } else {
3092 BlockDriverState *overlay_bs = bdrv_find_overlay(bs, top_bs);
3093 if (bdrv_op_is_blocked(overlay_bs, BLOCK_OP_TYPE_COMMIT_TARGET, errp)) {
3094 goto out;
3096 commit_start(has_job_id ? job_id : NULL, bs, base_bs, top_bs, speed,
3097 on_error, has_backing_file ? backing_file : NULL,
3098 &local_err);
3100 if (local_err != NULL) {
3101 error_propagate(errp, local_err);
3102 goto out;
3105 out:
3106 aio_context_release(aio_context);
3109 static void do_drive_backup(DriveBackup *backup, BlockJobTxn *txn, Error **errp)
3111 BlockDriverState *bs;
3112 BlockDriverState *target_bs;
3113 BlockDriverState *source = NULL;
3114 BdrvDirtyBitmap *bmap = NULL;
3115 AioContext *aio_context;
3116 QDict *options = NULL;
3117 Error *local_err = NULL;
3118 int flags;
3119 int64_t size;
3121 if (!backup->has_speed) {
3122 backup->speed = 0;
3124 if (!backup->has_on_source_error) {
3125 backup->on_source_error = BLOCKDEV_ON_ERROR_REPORT;
3127 if (!backup->has_on_target_error) {
3128 backup->on_target_error = BLOCKDEV_ON_ERROR_REPORT;
3130 if (!backup->has_mode) {
3131 backup->mode = NEW_IMAGE_MODE_ABSOLUTE_PATHS;
3133 if (!backup->has_job_id) {
3134 backup->job_id = NULL;
3136 if (!backup->has_compress) {
3137 backup->compress = false;
3140 bs = qmp_get_root_bs(backup->device, errp);
3141 if (!bs) {
3142 return;
3145 aio_context = bdrv_get_aio_context(bs);
3146 aio_context_acquire(aio_context);
3148 if (!backup->has_format) {
3149 backup->format = backup->mode == NEW_IMAGE_MODE_EXISTING ?
3150 NULL : (char*) bs->drv->format_name;
3153 /* Early check to avoid creating target */
3154 if (bdrv_op_is_blocked(bs, BLOCK_OP_TYPE_BACKUP_SOURCE, errp)) {
3155 goto out;
3158 flags = bs->open_flags | BDRV_O_RDWR;
3160 /* See if we have a backing HD we can use to create our new image
3161 * on top of. */
3162 if (backup->sync == MIRROR_SYNC_MODE_TOP) {
3163 source = backing_bs(bs);
3164 if (!source) {
3165 backup->sync = MIRROR_SYNC_MODE_FULL;
3168 if (backup->sync == MIRROR_SYNC_MODE_NONE) {
3169 source = bs;
3172 size = bdrv_getlength(bs);
3173 if (size < 0) {
3174 error_setg_errno(errp, -size, "bdrv_getlength failed");
3175 goto out;
3178 if (backup->mode != NEW_IMAGE_MODE_EXISTING) {
3179 assert(backup->format);
3180 if (source) {
3181 bdrv_img_create(backup->target, backup->format, source->filename,
3182 source->drv->format_name, NULL,
3183 size, flags, &local_err, false);
3184 } else {
3185 bdrv_img_create(backup->target, backup->format, NULL, NULL, NULL,
3186 size, flags, &local_err, false);
3190 if (local_err) {
3191 error_propagate(errp, local_err);
3192 goto out;
3195 if (backup->format) {
3196 options = qdict_new();
3197 qdict_put(options, "driver", qstring_from_str(backup->format));
3200 target_bs = bdrv_open(backup->target, NULL, options, flags, errp);
3201 if (!target_bs) {
3202 goto out;
3205 bdrv_set_aio_context(target_bs, aio_context);
3207 if (backup->has_bitmap) {
3208 bmap = bdrv_find_dirty_bitmap(bs, backup->bitmap);
3209 if (!bmap) {
3210 error_setg(errp, "Bitmap '%s' could not be found", backup->bitmap);
3211 bdrv_unref(target_bs);
3212 goto out;
3216 backup_start(backup->job_id, bs, target_bs, backup->speed, backup->sync,
3217 bmap, backup->compress, backup->on_source_error,
3218 backup->on_target_error, BLOCK_JOB_DEFAULT,
3219 NULL, NULL, txn, &local_err);
3220 bdrv_unref(target_bs);
3221 if (local_err != NULL) {
3222 error_propagate(errp, local_err);
3223 goto out;
3226 out:
3227 aio_context_release(aio_context);
3230 void qmp_drive_backup(DriveBackup *arg, Error **errp)
3232 return do_drive_backup(arg, NULL, errp);
3235 BlockDeviceInfoList *qmp_query_named_block_nodes(Error **errp)
3237 return bdrv_named_nodes_list(errp);
3240 void do_blockdev_backup(BlockdevBackup *backup, BlockJobTxn *txn, Error **errp)
3242 BlockDriverState *bs;
3243 BlockDriverState *target_bs;
3244 Error *local_err = NULL;
3245 AioContext *aio_context;
3247 if (!backup->has_speed) {
3248 backup->speed = 0;
3250 if (!backup->has_on_source_error) {
3251 backup->on_source_error = BLOCKDEV_ON_ERROR_REPORT;
3253 if (!backup->has_on_target_error) {
3254 backup->on_target_error = BLOCKDEV_ON_ERROR_REPORT;
3256 if (!backup->has_job_id) {
3257 backup->job_id = NULL;
3259 if (!backup->has_compress) {
3260 backup->compress = false;
3263 bs = qmp_get_root_bs(backup->device, errp);
3264 if (!bs) {
3265 return;
3268 aio_context = bdrv_get_aio_context(bs);
3269 aio_context_acquire(aio_context);
3271 target_bs = bdrv_lookup_bs(backup->target, backup->target, errp);
3272 if (!target_bs) {
3273 goto out;
3276 if (bdrv_get_aio_context(target_bs) != aio_context) {
3277 if (!bdrv_has_blk(target_bs)) {
3278 /* The target BDS is not attached, we can safely move it to another
3279 * AioContext. */
3280 bdrv_set_aio_context(target_bs, aio_context);
3281 } else {
3282 error_setg(errp, "Target is attached to a different thread from "
3283 "source.");
3284 goto out;
3287 backup_start(backup->job_id, bs, target_bs, backup->speed, backup->sync,
3288 NULL, backup->compress, backup->on_source_error,
3289 backup->on_target_error, BLOCK_JOB_DEFAULT,
3290 NULL, NULL, txn, &local_err);
3291 if (local_err != NULL) {
3292 error_propagate(errp, local_err);
3294 out:
3295 aio_context_release(aio_context);
3298 void qmp_blockdev_backup(BlockdevBackup *arg, Error **errp)
3300 do_blockdev_backup(arg, NULL, errp);
3303 /* Parameter check and block job starting for drive mirroring.
3304 * Caller should hold @device and @target's aio context (must be the same).
3306 static void blockdev_mirror_common(const char *job_id, BlockDriverState *bs,
3307 BlockDriverState *target,
3308 bool has_replaces, const char *replaces,
3309 enum MirrorSyncMode sync,
3310 BlockMirrorBackingMode backing_mode,
3311 bool has_speed, int64_t speed,
3312 bool has_granularity, uint32_t granularity,
3313 bool has_buf_size, int64_t buf_size,
3314 bool has_on_source_error,
3315 BlockdevOnError on_source_error,
3316 bool has_on_target_error,
3317 BlockdevOnError on_target_error,
3318 bool has_unmap, bool unmap,
3319 Error **errp)
3322 if (!has_speed) {
3323 speed = 0;
3325 if (!has_on_source_error) {
3326 on_source_error = BLOCKDEV_ON_ERROR_REPORT;
3328 if (!has_on_target_error) {
3329 on_target_error = BLOCKDEV_ON_ERROR_REPORT;
3331 if (!has_granularity) {
3332 granularity = 0;
3334 if (!has_buf_size) {
3335 buf_size = 0;
3337 if (!has_unmap) {
3338 unmap = true;
3341 if (granularity != 0 && (granularity < 512 || granularity > 1048576 * 64)) {
3342 error_setg(errp, QERR_INVALID_PARAMETER_VALUE, "granularity",
3343 "a value in range [512B, 64MB]");
3344 return;
3346 if (granularity & (granularity - 1)) {
3347 error_setg(errp, QERR_INVALID_PARAMETER_VALUE, "granularity",
3348 "power of 2");
3349 return;
3352 if (bdrv_op_is_blocked(bs, BLOCK_OP_TYPE_MIRROR_SOURCE, errp)) {
3353 return;
3355 if (bdrv_op_is_blocked(target, BLOCK_OP_TYPE_MIRROR_TARGET, errp)) {
3356 return;
3359 if (!bs->backing && sync == MIRROR_SYNC_MODE_TOP) {
3360 sync = MIRROR_SYNC_MODE_FULL;
3363 /* pass the node name to replace to mirror start since it's loose coupling
3364 * and will allow to check whether the node still exist at mirror completion
3366 mirror_start(job_id, bs, target,
3367 has_replaces ? replaces : NULL,
3368 speed, granularity, buf_size, sync, backing_mode,
3369 on_source_error, on_target_error, unmap, errp);
3372 void qmp_drive_mirror(DriveMirror *arg, Error **errp)
3374 BlockDriverState *bs;
3375 BlockDriverState *source, *target_bs;
3376 AioContext *aio_context;
3377 BlockMirrorBackingMode backing_mode;
3378 Error *local_err = NULL;
3379 QDict *options = NULL;
3380 int flags;
3381 int64_t size;
3382 const char *format = arg->format;
3384 bs = qmp_get_root_bs(arg->device, errp);
3385 if (!bs) {
3386 return;
3389 aio_context = bdrv_get_aio_context(bs);
3390 aio_context_acquire(aio_context);
3392 if (!arg->has_mode) {
3393 arg->mode = NEW_IMAGE_MODE_ABSOLUTE_PATHS;
3396 if (!arg->has_format) {
3397 format = (arg->mode == NEW_IMAGE_MODE_EXISTING
3398 ? NULL : bs->drv->format_name);
3401 flags = bs->open_flags | BDRV_O_RDWR;
3402 source = backing_bs(bs);
3403 if (!source && arg->sync == MIRROR_SYNC_MODE_TOP) {
3404 arg->sync = MIRROR_SYNC_MODE_FULL;
3406 if (arg->sync == MIRROR_SYNC_MODE_NONE) {
3407 source = bs;
3410 size = bdrv_getlength(bs);
3411 if (size < 0) {
3412 error_setg_errno(errp, -size, "bdrv_getlength failed");
3413 goto out;
3416 if (arg->has_replaces) {
3417 BlockDriverState *to_replace_bs;
3418 AioContext *replace_aio_context;
3419 int64_t replace_size;
3421 if (!arg->has_node_name) {
3422 error_setg(errp, "a node-name must be provided when replacing a"
3423 " named node of the graph");
3424 goto out;
3427 to_replace_bs = check_to_replace_node(bs, arg->replaces, &local_err);
3429 if (!to_replace_bs) {
3430 error_propagate(errp, local_err);
3431 goto out;
3434 replace_aio_context = bdrv_get_aio_context(to_replace_bs);
3435 aio_context_acquire(replace_aio_context);
3436 replace_size = bdrv_getlength(to_replace_bs);
3437 aio_context_release(replace_aio_context);
3439 if (size != replace_size) {
3440 error_setg(errp, "cannot replace image with a mirror image of "
3441 "different size");
3442 goto out;
3446 if (arg->mode == NEW_IMAGE_MODE_ABSOLUTE_PATHS) {
3447 backing_mode = MIRROR_SOURCE_BACKING_CHAIN;
3448 } else {
3449 backing_mode = MIRROR_OPEN_BACKING_CHAIN;
3452 if ((arg->sync == MIRROR_SYNC_MODE_FULL || !source)
3453 && arg->mode != NEW_IMAGE_MODE_EXISTING)
3455 /* create new image w/o backing file */
3456 assert(format);
3457 bdrv_img_create(arg->target, format,
3458 NULL, NULL, NULL, size, flags, &local_err, false);
3459 } else {
3460 switch (arg->mode) {
3461 case NEW_IMAGE_MODE_EXISTING:
3462 break;
3463 case NEW_IMAGE_MODE_ABSOLUTE_PATHS:
3464 /* create new image with backing file */
3465 bdrv_img_create(arg->target, format,
3466 source->filename,
3467 source->drv->format_name,
3468 NULL, size, flags, &local_err, false);
3469 break;
3470 default:
3471 abort();
3475 if (local_err) {
3476 error_propagate(errp, local_err);
3477 goto out;
3480 options = qdict_new();
3481 if (arg->has_node_name) {
3482 qdict_put(options, "node-name", qstring_from_str(arg->node_name));
3484 if (format) {
3485 qdict_put(options, "driver", qstring_from_str(format));
3488 /* Mirroring takes care of copy-on-write using the source's backing
3489 * file.
3491 target_bs = bdrv_open(arg->target, NULL, options,
3492 flags | BDRV_O_NO_BACKING, errp);
3493 if (!target_bs) {
3494 goto out;
3497 bdrv_set_aio_context(target_bs, aio_context);
3499 blockdev_mirror_common(arg->has_job_id ? arg->job_id : NULL, bs, target_bs,
3500 arg->has_replaces, arg->replaces, arg->sync,
3501 backing_mode, arg->has_speed, arg->speed,
3502 arg->has_granularity, arg->granularity,
3503 arg->has_buf_size, arg->buf_size,
3504 arg->has_on_source_error, arg->on_source_error,
3505 arg->has_on_target_error, arg->on_target_error,
3506 arg->has_unmap, arg->unmap,
3507 &local_err);
3508 bdrv_unref(target_bs);
3509 error_propagate(errp, local_err);
3510 out:
3511 aio_context_release(aio_context);
3514 void qmp_blockdev_mirror(bool has_job_id, const char *job_id,
3515 const char *device, const char *target,
3516 bool has_replaces, const char *replaces,
3517 MirrorSyncMode sync,
3518 bool has_speed, int64_t speed,
3519 bool has_granularity, uint32_t granularity,
3520 bool has_buf_size, int64_t buf_size,
3521 bool has_on_source_error,
3522 BlockdevOnError on_source_error,
3523 bool has_on_target_error,
3524 BlockdevOnError on_target_error,
3525 Error **errp)
3527 BlockDriverState *bs;
3528 BlockDriverState *target_bs;
3529 AioContext *aio_context;
3530 BlockMirrorBackingMode backing_mode = MIRROR_LEAVE_BACKING_CHAIN;
3531 Error *local_err = NULL;
3533 bs = qmp_get_root_bs(device, errp);
3534 if (!bs) {
3535 return;
3538 target_bs = bdrv_lookup_bs(target, target, errp);
3539 if (!target_bs) {
3540 return;
3543 aio_context = bdrv_get_aio_context(bs);
3544 aio_context_acquire(aio_context);
3546 bdrv_set_aio_context(target_bs, aio_context);
3548 blockdev_mirror_common(has_job_id ? job_id : NULL, bs, target_bs,
3549 has_replaces, replaces, sync, backing_mode,
3550 has_speed, speed,
3551 has_granularity, granularity,
3552 has_buf_size, buf_size,
3553 has_on_source_error, on_source_error,
3554 has_on_target_error, on_target_error,
3555 true, true,
3556 &local_err);
3557 error_propagate(errp, local_err);
3559 aio_context_release(aio_context);
3562 /* Get a block job using its ID and acquire its AioContext */
3563 static BlockJob *find_block_job(const char *id, AioContext **aio_context,
3564 Error **errp)
3566 BlockJob *job;
3568 assert(id != NULL);
3570 *aio_context = NULL;
3572 job = block_job_get(id);
3574 if (!job) {
3575 error_set(errp, ERROR_CLASS_DEVICE_NOT_ACTIVE,
3576 "Block job '%s' not found", id);
3577 return NULL;
3580 *aio_context = blk_get_aio_context(job->blk);
3581 aio_context_acquire(*aio_context);
3583 return job;
3586 void qmp_block_job_set_speed(const char *device, int64_t speed, Error **errp)
3588 AioContext *aio_context;
3589 BlockJob *job = find_block_job(device, &aio_context, errp);
3591 if (!job) {
3592 return;
3595 block_job_set_speed(job, speed, errp);
3596 aio_context_release(aio_context);
3599 void qmp_block_job_cancel(const char *device,
3600 bool has_force, bool force, Error **errp)
3602 AioContext *aio_context;
3603 BlockJob *job = find_block_job(device, &aio_context, errp);
3605 if (!job) {
3606 return;
3609 if (!has_force) {
3610 force = false;
3613 if (block_job_user_paused(job) && !force) {
3614 error_setg(errp, "The block job for device '%s' is currently paused",
3615 device);
3616 goto out;
3619 trace_qmp_block_job_cancel(job);
3620 block_job_cancel(job);
3621 out:
3622 aio_context_release(aio_context);
3625 void qmp_block_job_pause(const char *device, Error **errp)
3627 AioContext *aio_context;
3628 BlockJob *job = find_block_job(device, &aio_context, errp);
3630 if (!job || block_job_user_paused(job)) {
3631 return;
3634 trace_qmp_block_job_pause(job);
3635 block_job_user_pause(job);
3636 aio_context_release(aio_context);
3639 void qmp_block_job_resume(const char *device, Error **errp)
3641 AioContext *aio_context;
3642 BlockJob *job = find_block_job(device, &aio_context, errp);
3644 if (!job || !block_job_user_paused(job)) {
3645 return;
3648 trace_qmp_block_job_resume(job);
3649 block_job_iostatus_reset(job);
3650 block_job_user_resume(job);
3651 aio_context_release(aio_context);
3654 void qmp_block_job_complete(const char *device, Error **errp)
3656 AioContext *aio_context;
3657 BlockJob *job = find_block_job(device, &aio_context, errp);
3659 if (!job) {
3660 return;
3663 trace_qmp_block_job_complete(job);
3664 block_job_complete(job, errp);
3665 aio_context_release(aio_context);
3668 void qmp_change_backing_file(const char *device,
3669 const char *image_node_name,
3670 const char *backing_file,
3671 Error **errp)
3673 BlockDriverState *bs = NULL;
3674 AioContext *aio_context;
3675 BlockDriverState *image_bs = NULL;
3676 Error *local_err = NULL;
3677 bool ro;
3678 int open_flags;
3679 int ret;
3681 bs = qmp_get_root_bs(device, errp);
3682 if (!bs) {
3683 return;
3686 aio_context = bdrv_get_aio_context(bs);
3687 aio_context_acquire(aio_context);
3689 image_bs = bdrv_lookup_bs(NULL, image_node_name, &local_err);
3690 if (local_err) {
3691 error_propagate(errp, local_err);
3692 goto out;
3695 if (!image_bs) {
3696 error_setg(errp, "image file not found");
3697 goto out;
3700 if (bdrv_find_base(image_bs) == image_bs) {
3701 error_setg(errp, "not allowing backing file change on an image "
3702 "without a backing file");
3703 goto out;
3706 /* even though we are not necessarily operating on bs, we need it to
3707 * determine if block ops are currently prohibited on the chain */
3708 if (bdrv_op_is_blocked(bs, BLOCK_OP_TYPE_CHANGE, errp)) {
3709 goto out;
3712 /* final sanity check */
3713 if (!bdrv_chain_contains(bs, image_bs)) {
3714 error_setg(errp, "'%s' and image file are not in the same chain",
3715 device);
3716 goto out;
3719 /* if not r/w, reopen to make r/w */
3720 open_flags = image_bs->open_flags;
3721 ro = bdrv_is_read_only(image_bs);
3723 if (ro) {
3724 bdrv_reopen(image_bs, open_flags | BDRV_O_RDWR, &local_err);
3725 if (local_err) {
3726 error_propagate(errp, local_err);
3727 goto out;
3731 ret = bdrv_change_backing_file(image_bs, backing_file,
3732 image_bs->drv ? image_bs->drv->format_name : "");
3734 if (ret < 0) {
3735 error_setg_errno(errp, -ret, "Could not change backing file to '%s'",
3736 backing_file);
3737 /* don't exit here, so we can try to restore open flags if
3738 * appropriate */
3741 if (ro) {
3742 bdrv_reopen(image_bs, open_flags, &local_err);
3743 error_propagate(errp, local_err);
3746 out:
3747 aio_context_release(aio_context);
3750 void hmp_drive_add_node(Monitor *mon, const char *optstr)
3752 QemuOpts *opts;
3753 QDict *qdict;
3754 Error *local_err = NULL;
3756 opts = qemu_opts_parse_noisily(&qemu_drive_opts, optstr, false);
3757 if (!opts) {
3758 return;
3761 qdict = qemu_opts_to_qdict(opts, NULL);
3763 if (!qdict_get_try_str(qdict, "node-name")) {
3764 QDECREF(qdict);
3765 error_report("'node-name' needs to be specified");
3766 goto out;
3769 BlockDriverState *bs = bds_tree_init(qdict, &local_err);
3770 if (!bs) {
3771 error_report_err(local_err);
3772 goto out;
3775 QTAILQ_INSERT_TAIL(&monitor_bdrv_states, bs, monitor_list);
3777 out:
3778 qemu_opts_del(opts);
3781 void qmp_blockdev_add(BlockdevOptions *options, Error **errp)
3783 BlockDriverState *bs;
3784 QObject *obj;
3785 Visitor *v = qobject_output_visitor_new(&obj);
3786 QDict *qdict;
3787 Error *local_err = NULL;
3789 visit_type_BlockdevOptions(v, NULL, &options, &local_err);
3790 if (local_err) {
3791 error_propagate(errp, local_err);
3792 goto fail;
3795 visit_complete(v, &obj);
3796 qdict = qobject_to_qdict(obj);
3798 qdict_flatten(qdict);
3800 if (!qdict_get_try_str(qdict, "node-name")) {
3801 error_setg(errp, "'node-name' must be specified for the root node");
3802 goto fail;
3805 bs = bds_tree_init(qdict, errp);
3806 if (!bs) {
3807 goto fail;
3810 QTAILQ_INSERT_TAIL(&monitor_bdrv_states, bs, monitor_list);
3812 if (bs && bdrv_key_required(bs)) {
3813 QTAILQ_REMOVE(&monitor_bdrv_states, bs, monitor_list);
3814 bdrv_unref(bs);
3815 error_setg(errp, "blockdev-add doesn't support encrypted devices");
3816 goto fail;
3819 fail:
3820 visit_free(v);
3823 void qmp_x_blockdev_del(const char *node_name, Error **errp)
3825 AioContext *aio_context;
3826 BlockDriverState *bs;
3828 bs = bdrv_find_node(node_name);
3829 if (!bs) {
3830 error_setg(errp, "Cannot find node %s", node_name);
3831 return;
3833 if (bdrv_has_blk(bs)) {
3834 error_setg(errp, "Node %s is in use", node_name);
3835 return;
3837 aio_context = bdrv_get_aio_context(bs);
3838 aio_context_acquire(aio_context);
3840 if (bdrv_op_is_blocked(bs, BLOCK_OP_TYPE_DRIVE_DEL, errp)) {
3841 goto out;
3844 if (!bs->monitor_list.tqe_prev) {
3845 error_setg(errp, "Node %s is not owned by the monitor",
3846 bs->node_name);
3847 goto out;
3850 if (bs->refcnt > 1) {
3851 error_setg(errp, "Block device %s is in use",
3852 bdrv_get_device_or_node_name(bs));
3853 goto out;
3856 QTAILQ_REMOVE(&monitor_bdrv_states, bs, monitor_list);
3857 bdrv_unref(bs);
3859 out:
3860 aio_context_release(aio_context);
3863 static BdrvChild *bdrv_find_child(BlockDriverState *parent_bs,
3864 const char *child_name)
3866 BdrvChild *child;
3868 QLIST_FOREACH(child, &parent_bs->children, next) {
3869 if (strcmp(child->name, child_name) == 0) {
3870 return child;
3874 return NULL;
3877 void qmp_x_blockdev_change(const char *parent, bool has_child,
3878 const char *child, bool has_node,
3879 const char *node, Error **errp)
3881 BlockDriverState *parent_bs, *new_bs = NULL;
3882 BdrvChild *p_child;
3884 parent_bs = bdrv_lookup_bs(parent, parent, errp);
3885 if (!parent_bs) {
3886 return;
3889 if (has_child == has_node) {
3890 if (has_child) {
3891 error_setg(errp, "The parameters child and node are in conflict");
3892 } else {
3893 error_setg(errp, "Either child or node must be specified");
3895 return;
3898 if (has_child) {
3899 p_child = bdrv_find_child(parent_bs, child);
3900 if (!p_child) {
3901 error_setg(errp, "Node '%s' does not have child '%s'",
3902 parent, child);
3903 return;
3905 bdrv_del_child(parent_bs, p_child, errp);
3908 if (has_node) {
3909 new_bs = bdrv_find_node(node);
3910 if (!new_bs) {
3911 error_setg(errp, "Node '%s' not found", node);
3912 return;
3914 bdrv_add_child(parent_bs, new_bs, errp);
3918 BlockJobInfoList *qmp_query_block_jobs(Error **errp)
3920 BlockJobInfoList *head = NULL, **p_next = &head;
3921 BlockJob *job;
3923 for (job = block_job_next(NULL); job; job = block_job_next(job)) {
3924 BlockJobInfoList *elem;
3925 AioContext *aio_context;
3927 if (block_job_is_internal(job)) {
3928 continue;
3930 elem = g_new0(BlockJobInfoList, 1);
3931 aio_context = blk_get_aio_context(job->blk);
3932 aio_context_acquire(aio_context);
3933 elem->value = block_job_query(job, errp);
3934 aio_context_release(aio_context);
3935 if (!elem->value) {
3936 g_free(elem);
3937 qapi_free_BlockJobInfoList(head);
3938 return NULL;
3940 *p_next = elem;
3941 p_next = &elem->next;
3944 return head;
3947 QemuOptsList qemu_common_drive_opts = {
3948 .name = "drive",
3949 .head = QTAILQ_HEAD_INITIALIZER(qemu_common_drive_opts.head),
3950 .desc = {
3952 .name = "snapshot",
3953 .type = QEMU_OPT_BOOL,
3954 .help = "enable/disable snapshot mode",
3956 .name = "aio",
3957 .type = QEMU_OPT_STRING,
3958 .help = "host AIO implementation (threads, native)",
3960 .name = BDRV_OPT_CACHE_WB,
3961 .type = QEMU_OPT_BOOL,
3962 .help = "Enable writeback mode",
3964 .name = "format",
3965 .type = QEMU_OPT_STRING,
3966 .help = "disk format (raw, qcow2, ...)",
3968 .name = "rerror",
3969 .type = QEMU_OPT_STRING,
3970 .help = "read error action",
3972 .name = "werror",
3973 .type = QEMU_OPT_STRING,
3974 .help = "write error action",
3976 .name = BDRV_OPT_READ_ONLY,
3977 .type = QEMU_OPT_BOOL,
3978 .help = "open drive file as read-only",
3980 .name = "throttling.iops-total",
3981 .type = QEMU_OPT_NUMBER,
3982 .help = "limit total I/O operations per second",
3984 .name = "throttling.iops-read",
3985 .type = QEMU_OPT_NUMBER,
3986 .help = "limit read operations per second",
3988 .name = "throttling.iops-write",
3989 .type = QEMU_OPT_NUMBER,
3990 .help = "limit write operations per second",
3992 .name = "throttling.bps-total",
3993 .type = QEMU_OPT_NUMBER,
3994 .help = "limit total bytes per second",
3996 .name = "throttling.bps-read",
3997 .type = QEMU_OPT_NUMBER,
3998 .help = "limit read bytes per second",
4000 .name = "throttling.bps-write",
4001 .type = QEMU_OPT_NUMBER,
4002 .help = "limit write bytes per second",
4004 .name = "throttling.iops-total-max",
4005 .type = QEMU_OPT_NUMBER,
4006 .help = "I/O operations burst",
4008 .name = "throttling.iops-read-max",
4009 .type = QEMU_OPT_NUMBER,
4010 .help = "I/O operations read burst",
4012 .name = "throttling.iops-write-max",
4013 .type = QEMU_OPT_NUMBER,
4014 .help = "I/O operations write burst",
4016 .name = "throttling.bps-total-max",
4017 .type = QEMU_OPT_NUMBER,
4018 .help = "total bytes burst",
4020 .name = "throttling.bps-read-max",
4021 .type = QEMU_OPT_NUMBER,
4022 .help = "total bytes read burst",
4024 .name = "throttling.bps-write-max",
4025 .type = QEMU_OPT_NUMBER,
4026 .help = "total bytes write burst",
4028 .name = "throttling.iops-total-max-length",
4029 .type = QEMU_OPT_NUMBER,
4030 .help = "length of the iops-total-max burst period, in seconds",
4032 .name = "throttling.iops-read-max-length",
4033 .type = QEMU_OPT_NUMBER,
4034 .help = "length of the iops-read-max burst period, in seconds",
4036 .name = "throttling.iops-write-max-length",
4037 .type = QEMU_OPT_NUMBER,
4038 .help = "length of the iops-write-max burst period, in seconds",
4040 .name = "throttling.bps-total-max-length",
4041 .type = QEMU_OPT_NUMBER,
4042 .help = "length of the bps-total-max burst period, in seconds",
4044 .name = "throttling.bps-read-max-length",
4045 .type = QEMU_OPT_NUMBER,
4046 .help = "length of the bps-read-max burst period, in seconds",
4048 .name = "throttling.bps-write-max-length",
4049 .type = QEMU_OPT_NUMBER,
4050 .help = "length of the bps-write-max burst period, in seconds",
4052 .name = "throttling.iops-size",
4053 .type = QEMU_OPT_NUMBER,
4054 .help = "when limiting by iops max size of an I/O in bytes",
4056 .name = "throttling.group",
4057 .type = QEMU_OPT_STRING,
4058 .help = "name of the block throttling group",
4060 .name = "copy-on-read",
4061 .type = QEMU_OPT_BOOL,
4062 .help = "copy read data from backing file into image file",
4064 .name = "detect-zeroes",
4065 .type = QEMU_OPT_STRING,
4066 .help = "try to optimize zero writes (off, on, unmap)",
4068 .name = "stats-account-invalid",
4069 .type = QEMU_OPT_BOOL,
4070 .help = "whether to account for invalid I/O operations "
4071 "in the statistics",
4073 .name = "stats-account-failed",
4074 .type = QEMU_OPT_BOOL,
4075 .help = "whether to account for failed I/O operations "
4076 "in the statistics",
4078 { /* end of list */ }
4082 QemuOptsList qemu_drive_opts = {
4083 .name = "drive",
4084 .head = QTAILQ_HEAD_INITIALIZER(qemu_drive_opts.head),
4085 .desc = {
4087 * no elements => accept any params
4088 * validation will happen later
4090 { /* end of list */ }