nbd: client_close on error in nbd_co_client_start
[qemu/ar7.git] / blockdev.c
blob1044a6acade6352e86d5281a2eab6c5f212241ce
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 "sysemu/block-backend.h"
34 #include "sysemu/blockdev.h"
35 #include "hw/block/block.h"
36 #include "block/blockjob.h"
37 #include "block/throttle-groups.h"
38 #include "monitor/monitor.h"
39 #include "qemu/error-report.h"
40 #include "qemu/option.h"
41 #include "qemu/config-file.h"
42 #include "qapi/qmp/types.h"
43 #include "qapi-visit.h"
44 #include "qapi/qmp/qerror.h"
45 #include "qapi/qmp-output-visitor.h"
46 #include "qapi/util.h"
47 #include "sysemu/sysemu.h"
48 #include "block/block_int.h"
49 #include "qmp-commands.h"
50 #include "trace.h"
51 #include "sysemu/arch_init.h"
53 static const char *const if_name[IF_COUNT] = {
54 [IF_NONE] = "none",
55 [IF_IDE] = "ide",
56 [IF_SCSI] = "scsi",
57 [IF_FLOPPY] = "floppy",
58 [IF_PFLASH] = "pflash",
59 [IF_MTD] = "mtd",
60 [IF_SD] = "sd",
61 [IF_VIRTIO] = "virtio",
62 [IF_XEN] = "xen",
65 static int if_max_devs[IF_COUNT] = {
67 * Do not change these numbers! They govern how drive option
68 * index maps to unit and bus. That mapping is ABI.
70 * All controllers used to imlement if=T drives need to support
71 * if_max_devs[T] units, for any T with if_max_devs[T] != 0.
72 * Otherwise, some index values map to "impossible" bus, unit
73 * values.
75 * For instance, if you change [IF_SCSI] to 255, -drive
76 * if=scsi,index=12 no longer means bus=1,unit=5, but
77 * bus=0,unit=12. With an lsi53c895a controller (7 units max),
78 * the drive can't be set up. Regression.
80 [IF_IDE] = 2,
81 [IF_SCSI] = 7,
84 /**
85 * Boards may call this to offer board-by-board overrides
86 * of the default, global values.
88 void override_max_devs(BlockInterfaceType type, int max_devs)
90 BlockBackend *blk;
91 DriveInfo *dinfo;
93 if (max_devs <= 0) {
94 return;
97 for (blk = blk_next(NULL); blk; blk = blk_next(blk)) {
98 dinfo = blk_legacy_dinfo(blk);
99 if (dinfo->type == type) {
100 fprintf(stderr, "Cannot override units-per-bus property of"
101 " the %s interface, because a drive of that type has"
102 " already been added.\n", if_name[type]);
103 g_assert_not_reached();
107 if_max_devs[type] = max_devs;
111 * We automatically delete the drive when a device using it gets
112 * unplugged. Questionable feature, but we can't just drop it.
113 * Device models call blockdev_mark_auto_del() to schedule the
114 * automatic deletion, and generic qdev code calls blockdev_auto_del()
115 * when deletion is actually safe.
117 void blockdev_mark_auto_del(BlockBackend *blk)
119 DriveInfo *dinfo = blk_legacy_dinfo(blk);
120 BlockDriverState *bs = blk_bs(blk);
121 AioContext *aio_context;
123 if (!dinfo) {
124 return;
127 if (bs) {
128 aio_context = bdrv_get_aio_context(bs);
129 aio_context_acquire(aio_context);
131 if (bs->job) {
132 block_job_cancel(bs->job);
135 aio_context_release(aio_context);
138 dinfo->auto_del = 1;
141 void blockdev_auto_del(BlockBackend *blk)
143 DriveInfo *dinfo = blk_legacy_dinfo(blk);
145 if (dinfo && dinfo->auto_del) {
146 blk_unref(blk);
151 * Returns the current mapping of how many units per bus
152 * a particular interface can support.
154 * A positive integer indicates n units per bus.
155 * 0 implies the mapping has not been established.
156 * -1 indicates an invalid BlockInterfaceType was given.
158 int drive_get_max_devs(BlockInterfaceType type)
160 if (type >= IF_IDE && type < IF_COUNT) {
161 return if_max_devs[type];
164 return -1;
167 static int drive_index_to_bus_id(BlockInterfaceType type, int index)
169 int max_devs = if_max_devs[type];
170 return max_devs ? index / max_devs : 0;
173 static int drive_index_to_unit_id(BlockInterfaceType type, int index)
175 int max_devs = if_max_devs[type];
176 return max_devs ? index % max_devs : index;
179 QemuOpts *drive_def(const char *optstr)
181 return qemu_opts_parse_noisily(qemu_find_opts("drive"), optstr, false);
184 QemuOpts *drive_add(BlockInterfaceType type, int index, const char *file,
185 const char *optstr)
187 QemuOpts *opts;
189 opts = drive_def(optstr);
190 if (!opts) {
191 return NULL;
193 if (type != IF_DEFAULT) {
194 qemu_opt_set(opts, "if", if_name[type], &error_abort);
196 if (index >= 0) {
197 qemu_opt_set_number(opts, "index", index, &error_abort);
199 if (file)
200 qemu_opt_set(opts, "file", file, &error_abort);
201 return opts;
204 DriveInfo *drive_get(BlockInterfaceType type, int bus, int unit)
206 BlockBackend *blk;
207 DriveInfo *dinfo;
209 for (blk = blk_next(NULL); blk; blk = blk_next(blk)) {
210 dinfo = blk_legacy_dinfo(blk);
211 if (dinfo && dinfo->type == type
212 && dinfo->bus == bus && dinfo->unit == unit) {
213 return dinfo;
217 return NULL;
220 bool drive_check_orphaned(void)
222 BlockBackend *blk;
223 DriveInfo *dinfo;
224 bool rs = false;
226 for (blk = blk_next(NULL); blk; blk = blk_next(blk)) {
227 dinfo = blk_legacy_dinfo(blk);
228 /* If dinfo->bdrv->dev is NULL, it has no device attached. */
229 /* Unless this is a default drive, this may be an oversight. */
230 if (!blk_get_attached_dev(blk) && !dinfo->is_default &&
231 dinfo->type != IF_NONE) {
232 fprintf(stderr, "Warning: Orphaned drive without device: "
233 "id=%s,file=%s,if=%s,bus=%d,unit=%d\n",
234 blk_name(blk), blk_bs(blk) ? blk_bs(blk)->filename : "",
235 if_name[dinfo->type], dinfo->bus, dinfo->unit);
236 rs = true;
240 return rs;
243 DriveInfo *drive_get_by_index(BlockInterfaceType type, int index)
245 return drive_get(type,
246 drive_index_to_bus_id(type, index),
247 drive_index_to_unit_id(type, index));
250 int drive_get_max_bus(BlockInterfaceType type)
252 int max_bus;
253 BlockBackend *blk;
254 DriveInfo *dinfo;
256 max_bus = -1;
257 for (blk = blk_next(NULL); blk; blk = blk_next(blk)) {
258 dinfo = blk_legacy_dinfo(blk);
259 if (dinfo && dinfo->type == type && dinfo->bus > max_bus) {
260 max_bus = dinfo->bus;
263 return max_bus;
266 /* Get a block device. This should only be used for single-drive devices
267 (e.g. SD/Floppy/MTD). Multi-disk devices (scsi/ide) should use the
268 appropriate bus. */
269 DriveInfo *drive_get_next(BlockInterfaceType type)
271 static int next_block_unit[IF_COUNT];
273 return drive_get(type, 0, next_block_unit[type]++);
276 static void bdrv_format_print(void *opaque, const char *name)
278 error_printf(" %s", name);
281 typedef struct {
282 QEMUBH *bh;
283 BlockDriverState *bs;
284 } BDRVPutRefBH;
286 static int parse_block_error_action(const char *buf, bool is_read, Error **errp)
288 if (!strcmp(buf, "ignore")) {
289 return BLOCKDEV_ON_ERROR_IGNORE;
290 } else if (!is_read && !strcmp(buf, "enospc")) {
291 return BLOCKDEV_ON_ERROR_ENOSPC;
292 } else if (!strcmp(buf, "stop")) {
293 return BLOCKDEV_ON_ERROR_STOP;
294 } else if (!strcmp(buf, "report")) {
295 return BLOCKDEV_ON_ERROR_REPORT;
296 } else {
297 error_setg(errp, "'%s' invalid %s error action",
298 buf, is_read ? "read" : "write");
299 return -1;
303 static bool parse_stats_intervals(BlockAcctStats *stats, QList *intervals,
304 Error **errp)
306 const QListEntry *entry;
307 for (entry = qlist_first(intervals); entry; entry = qlist_next(entry)) {
308 switch (qobject_type(entry->value)) {
310 case QTYPE_QSTRING: {
311 unsigned long long length;
312 const char *str = qstring_get_str(qobject_to_qstring(entry->value));
313 if (parse_uint_full(str, &length, 10) == 0 &&
314 length > 0 && length <= UINT_MAX) {
315 block_acct_add_interval(stats, (unsigned) length);
316 } else {
317 error_setg(errp, "Invalid interval length: %s", str);
318 return false;
320 break;
323 case QTYPE_QINT: {
324 int64_t length = qint_get_int(qobject_to_qint(entry->value));
325 if (length > 0 && length <= UINT_MAX) {
326 block_acct_add_interval(stats, (unsigned) length);
327 } else {
328 error_setg(errp, "Invalid interval length: %" PRId64, length);
329 return false;
331 break;
334 default:
335 error_setg(errp, "The specification of stats-intervals is invalid");
336 return false;
339 return true;
342 static bool check_throttle_config(ThrottleConfig *cfg, Error **errp)
344 if (throttle_conflicting(cfg)) {
345 error_setg(errp, "bps/iops/max total values and read/write values"
346 " cannot be used at the same time");
347 return false;
350 if (!throttle_is_valid(cfg)) {
351 error_setg(errp, "bps/iops/max values must be within [0, %lld]",
352 THROTTLE_VALUE_MAX);
353 return false;
356 if (throttle_max_is_missing_limit(cfg)) {
357 error_setg(errp, "bps_max/iops_max require corresponding"
358 " bps/iops values");
359 return false;
362 return true;
365 typedef enum { MEDIA_DISK, MEDIA_CDROM } DriveMediaType;
367 /* All parameters but @opts are optional and may be set to NULL. */
368 static void extract_common_blockdev_options(QemuOpts *opts, int *bdrv_flags,
369 const char **throttling_group, ThrottleConfig *throttle_cfg,
370 BlockdevDetectZeroesOptions *detect_zeroes, Error **errp)
372 const char *discard;
373 Error *local_error = NULL;
374 const char *aio;
376 if (bdrv_flags) {
377 if (!qemu_opt_get_bool(opts, "read-only", false)) {
378 *bdrv_flags |= BDRV_O_RDWR;
380 if (qemu_opt_get_bool(opts, "copy-on-read", false)) {
381 *bdrv_flags |= BDRV_O_COPY_ON_READ;
384 if ((discard = qemu_opt_get(opts, "discard")) != NULL) {
385 if (bdrv_parse_discard_flags(discard, bdrv_flags) != 0) {
386 error_setg(errp, "Invalid discard option");
387 return;
391 if ((aio = qemu_opt_get(opts, "aio")) != NULL) {
392 if (!strcmp(aio, "native")) {
393 *bdrv_flags |= BDRV_O_NATIVE_AIO;
394 } else if (!strcmp(aio, "threads")) {
395 /* this is the default */
396 } else {
397 error_setg(errp, "invalid aio option");
398 return;
403 /* disk I/O throttling */
404 if (throttling_group) {
405 *throttling_group = qemu_opt_get(opts, "throttling.group");
408 if (throttle_cfg) {
409 memset(throttle_cfg, 0, sizeof(*throttle_cfg));
410 throttle_cfg->buckets[THROTTLE_BPS_TOTAL].avg =
411 qemu_opt_get_number(opts, "throttling.bps-total", 0);
412 throttle_cfg->buckets[THROTTLE_BPS_READ].avg =
413 qemu_opt_get_number(opts, "throttling.bps-read", 0);
414 throttle_cfg->buckets[THROTTLE_BPS_WRITE].avg =
415 qemu_opt_get_number(opts, "throttling.bps-write", 0);
416 throttle_cfg->buckets[THROTTLE_OPS_TOTAL].avg =
417 qemu_opt_get_number(opts, "throttling.iops-total", 0);
418 throttle_cfg->buckets[THROTTLE_OPS_READ].avg =
419 qemu_opt_get_number(opts, "throttling.iops-read", 0);
420 throttle_cfg->buckets[THROTTLE_OPS_WRITE].avg =
421 qemu_opt_get_number(opts, "throttling.iops-write", 0);
423 throttle_cfg->buckets[THROTTLE_BPS_TOTAL].max =
424 qemu_opt_get_number(opts, "throttling.bps-total-max", 0);
425 throttle_cfg->buckets[THROTTLE_BPS_READ].max =
426 qemu_opt_get_number(opts, "throttling.bps-read-max", 0);
427 throttle_cfg->buckets[THROTTLE_BPS_WRITE].max =
428 qemu_opt_get_number(opts, "throttling.bps-write-max", 0);
429 throttle_cfg->buckets[THROTTLE_OPS_TOTAL].max =
430 qemu_opt_get_number(opts, "throttling.iops-total-max", 0);
431 throttle_cfg->buckets[THROTTLE_OPS_READ].max =
432 qemu_opt_get_number(opts, "throttling.iops-read-max", 0);
433 throttle_cfg->buckets[THROTTLE_OPS_WRITE].max =
434 qemu_opt_get_number(opts, "throttling.iops-write-max", 0);
436 throttle_cfg->op_size =
437 qemu_opt_get_number(opts, "throttling.iops-size", 0);
439 if (!check_throttle_config(throttle_cfg, errp)) {
440 return;
444 if (detect_zeroes) {
445 *detect_zeroes =
446 qapi_enum_parse(BlockdevDetectZeroesOptions_lookup,
447 qemu_opt_get(opts, "detect-zeroes"),
448 BLOCKDEV_DETECT_ZEROES_OPTIONS__MAX,
449 BLOCKDEV_DETECT_ZEROES_OPTIONS_OFF,
450 &local_error);
451 if (local_error) {
452 error_propagate(errp, local_error);
453 return;
456 if (bdrv_flags &&
457 *detect_zeroes == BLOCKDEV_DETECT_ZEROES_OPTIONS_UNMAP &&
458 !(*bdrv_flags & BDRV_O_UNMAP))
460 error_setg(errp, "setting detect-zeroes to unmap is not allowed "
461 "without setting discard operation to unmap");
462 return;
467 /* Takes the ownership of bs_opts */
468 static BlockBackend *blockdev_init(const char *file, QDict *bs_opts,
469 Error **errp)
471 const char *buf;
472 int bdrv_flags = 0;
473 int on_read_error, on_write_error;
474 bool account_invalid, account_failed;
475 BlockBackend *blk;
476 BlockDriverState *bs;
477 ThrottleConfig cfg;
478 int snapshot = 0;
479 Error *error = NULL;
480 QemuOpts *opts;
481 QDict *interval_dict = NULL;
482 QList *interval_list = NULL;
483 const char *id;
484 BlockdevDetectZeroesOptions detect_zeroes =
485 BLOCKDEV_DETECT_ZEROES_OPTIONS_OFF;
486 const char *throttling_group = NULL;
488 /* Check common options by copying from bs_opts to opts, all other options
489 * stay in bs_opts for processing by bdrv_open(). */
490 id = qdict_get_try_str(bs_opts, "id");
491 opts = qemu_opts_create(&qemu_common_drive_opts, id, 1, &error);
492 if (error) {
493 error_propagate(errp, error);
494 goto err_no_opts;
497 qemu_opts_absorb_qdict(opts, bs_opts, &error);
498 if (error) {
499 error_propagate(errp, error);
500 goto early_err;
503 if (id) {
504 qdict_del(bs_opts, "id");
507 /* extract parameters */
508 snapshot = qemu_opt_get_bool(opts, "snapshot", 0);
510 account_invalid = qemu_opt_get_bool(opts, "stats-account-invalid", true);
511 account_failed = qemu_opt_get_bool(opts, "stats-account-failed", true);
513 qdict_extract_subqdict(bs_opts, &interval_dict, "stats-intervals.");
514 qdict_array_split(interval_dict, &interval_list);
516 if (qdict_size(interval_dict) != 0) {
517 error_setg(errp, "Invalid option stats-intervals.%s",
518 qdict_first(interval_dict)->key);
519 goto early_err;
522 extract_common_blockdev_options(opts, &bdrv_flags, &throttling_group, &cfg,
523 &detect_zeroes, &error);
524 if (error) {
525 error_propagate(errp, error);
526 goto early_err;
529 if ((buf = qemu_opt_get(opts, "format")) != NULL) {
530 if (is_help_option(buf)) {
531 error_printf("Supported formats:");
532 bdrv_iterate_format(bdrv_format_print, NULL);
533 error_printf("\n");
534 goto early_err;
537 if (qdict_haskey(bs_opts, "driver")) {
538 error_setg(errp, "Cannot specify both 'driver' and 'format'");
539 goto early_err;
541 qdict_put(bs_opts, "driver", qstring_from_str(buf));
544 on_write_error = BLOCKDEV_ON_ERROR_ENOSPC;
545 if ((buf = qemu_opt_get(opts, "werror")) != NULL) {
546 on_write_error = parse_block_error_action(buf, 0, &error);
547 if (error) {
548 error_propagate(errp, error);
549 goto early_err;
553 on_read_error = BLOCKDEV_ON_ERROR_REPORT;
554 if ((buf = qemu_opt_get(opts, "rerror")) != NULL) {
555 on_read_error = parse_block_error_action(buf, 1, &error);
556 if (error) {
557 error_propagate(errp, error);
558 goto early_err;
562 if (snapshot) {
563 bdrv_flags |= BDRV_O_SNAPSHOT;
566 /* init */
567 if ((!file || !*file) && !qdict_size(bs_opts)) {
568 BlockBackendRootState *blk_rs;
570 blk = blk_new(qemu_opts_id(opts), errp);
571 if (!blk) {
572 goto early_err;
575 blk_rs = blk_get_root_state(blk);
576 blk_rs->open_flags = bdrv_flags;
577 blk_rs->read_only = !(bdrv_flags & BDRV_O_RDWR);
578 blk_rs->detect_zeroes = detect_zeroes;
580 if (throttle_enabled(&cfg)) {
581 if (!throttling_group) {
582 throttling_group = blk_name(blk);
584 blk_rs->throttle_group = g_strdup(throttling_group);
585 blk_rs->throttle_state = throttle_group_incref(throttling_group);
586 blk_rs->throttle_state->cfg = cfg;
589 QDECREF(bs_opts);
590 } else {
591 if (file && !*file) {
592 file = NULL;
595 /* bdrv_open() defaults to the values in bdrv_flags (for compatibility
596 * with other callers) rather than what we want as the real defaults.
597 * Apply the defaults here instead. */
598 qdict_set_default_str(bs_opts, BDRV_OPT_CACHE_WB, "on");
599 qdict_set_default_str(bs_opts, BDRV_OPT_CACHE_DIRECT, "off");
600 qdict_set_default_str(bs_opts, BDRV_OPT_CACHE_NO_FLUSH, "off");
602 if (snapshot) {
603 /* always use cache=unsafe with snapshot */
604 qdict_put(bs_opts, BDRV_OPT_CACHE_WB, qstring_from_str("on"));
605 qdict_put(bs_opts, BDRV_OPT_CACHE_DIRECT, qstring_from_str("off"));
606 qdict_put(bs_opts, BDRV_OPT_CACHE_NO_FLUSH, qstring_from_str("on"));
609 blk = blk_new_open(qemu_opts_id(opts), file, NULL, bs_opts, bdrv_flags,
610 errp);
611 if (!blk) {
612 goto err_no_bs_opts;
614 bs = blk_bs(blk);
616 bs->detect_zeroes = detect_zeroes;
618 /* disk I/O throttling */
619 if (throttle_enabled(&cfg)) {
620 if (!throttling_group) {
621 throttling_group = blk_name(blk);
623 bdrv_io_limits_enable(bs, throttling_group);
624 bdrv_set_io_limits(bs, &cfg);
627 if (bdrv_key_required(bs)) {
628 autostart = 0;
631 block_acct_init(blk_get_stats(blk), account_invalid, account_failed);
633 if (!parse_stats_intervals(blk_get_stats(blk), interval_list, errp)) {
634 blk_unref(blk);
635 blk = NULL;
636 goto err_no_bs_opts;
640 blk_set_on_error(blk, on_read_error, on_write_error);
642 err_no_bs_opts:
643 qemu_opts_del(opts);
644 QDECREF(interval_dict);
645 QDECREF(interval_list);
646 return blk;
648 early_err:
649 qemu_opts_del(opts);
650 QDECREF(interval_dict);
651 QDECREF(interval_list);
652 err_no_opts:
653 QDECREF(bs_opts);
654 return NULL;
657 static QemuOptsList qemu_root_bds_opts;
659 /* Takes the ownership of bs_opts */
660 static BlockDriverState *bds_tree_init(QDict *bs_opts, Error **errp)
662 BlockDriverState *bs;
663 QemuOpts *opts;
664 Error *local_error = NULL;
665 BlockdevDetectZeroesOptions detect_zeroes;
666 int ret;
667 int bdrv_flags = 0;
669 opts = qemu_opts_create(&qemu_root_bds_opts, NULL, 1, errp);
670 if (!opts) {
671 goto fail;
674 qemu_opts_absorb_qdict(opts, bs_opts, &local_error);
675 if (local_error) {
676 error_propagate(errp, local_error);
677 goto fail;
680 extract_common_blockdev_options(opts, &bdrv_flags, NULL, NULL,
681 &detect_zeroes, &local_error);
682 if (local_error) {
683 error_propagate(errp, local_error);
684 goto fail;
687 bs = NULL;
688 ret = bdrv_open(&bs, NULL, NULL, bs_opts, bdrv_flags, errp);
689 if (ret < 0) {
690 goto fail_no_bs_opts;
693 bs->detect_zeroes = detect_zeroes;
695 fail_no_bs_opts:
696 qemu_opts_del(opts);
697 return bs;
699 fail:
700 qemu_opts_del(opts);
701 QDECREF(bs_opts);
702 return NULL;
705 static void qemu_opt_rename(QemuOpts *opts, const char *from, const char *to,
706 Error **errp)
708 const char *value;
710 value = qemu_opt_get(opts, from);
711 if (value) {
712 if (qemu_opt_find(opts, to)) {
713 error_setg(errp, "'%s' and its alias '%s' can't be used at the "
714 "same time", to, from);
715 return;
719 /* rename all items in opts */
720 while ((value = qemu_opt_get(opts, from))) {
721 qemu_opt_set(opts, to, value, &error_abort);
722 qemu_opt_unset(opts, from);
726 QemuOptsList qemu_legacy_drive_opts = {
727 .name = "drive",
728 .head = QTAILQ_HEAD_INITIALIZER(qemu_legacy_drive_opts.head),
729 .desc = {
731 .name = "bus",
732 .type = QEMU_OPT_NUMBER,
733 .help = "bus number",
735 .name = "unit",
736 .type = QEMU_OPT_NUMBER,
737 .help = "unit number (i.e. lun for scsi)",
739 .name = "index",
740 .type = QEMU_OPT_NUMBER,
741 .help = "index number",
743 .name = "media",
744 .type = QEMU_OPT_STRING,
745 .help = "media type (disk, cdrom)",
747 .name = "if",
748 .type = QEMU_OPT_STRING,
749 .help = "interface (ide, scsi, sd, mtd, floppy, pflash, virtio)",
751 .name = "cyls",
752 .type = QEMU_OPT_NUMBER,
753 .help = "number of cylinders (ide disk geometry)",
755 .name = "heads",
756 .type = QEMU_OPT_NUMBER,
757 .help = "number of heads (ide disk geometry)",
759 .name = "secs",
760 .type = QEMU_OPT_NUMBER,
761 .help = "number of sectors (ide disk geometry)",
763 .name = "trans",
764 .type = QEMU_OPT_STRING,
765 .help = "chs translation (auto, lba, none)",
767 .name = "boot",
768 .type = QEMU_OPT_BOOL,
769 .help = "(deprecated, ignored)",
771 .name = "addr",
772 .type = QEMU_OPT_STRING,
773 .help = "pci address (virtio only)",
775 .name = "serial",
776 .type = QEMU_OPT_STRING,
777 .help = "disk serial number",
779 .name = "file",
780 .type = QEMU_OPT_STRING,
781 .help = "file name",
784 /* Options that are passed on, but have special semantics with -drive */
786 .name = "read-only",
787 .type = QEMU_OPT_BOOL,
788 .help = "open drive file as read-only",
790 .name = "rerror",
791 .type = QEMU_OPT_STRING,
792 .help = "read error action",
794 .name = "werror",
795 .type = QEMU_OPT_STRING,
796 .help = "write error action",
798 .name = "copy-on-read",
799 .type = QEMU_OPT_BOOL,
800 .help = "copy read data from backing file into image file",
803 { /* end of list */ }
807 DriveInfo *drive_new(QemuOpts *all_opts, BlockInterfaceType block_default_type)
809 const char *value;
810 BlockBackend *blk;
811 DriveInfo *dinfo = NULL;
812 QDict *bs_opts;
813 QemuOpts *legacy_opts;
814 DriveMediaType media = MEDIA_DISK;
815 BlockInterfaceType type;
816 int cyls, heads, secs, translation;
817 int max_devs, bus_id, unit_id, index;
818 const char *devaddr;
819 const char *werror, *rerror;
820 bool read_only = false;
821 bool copy_on_read;
822 const char *serial;
823 const char *filename;
824 Error *local_err = NULL;
825 int i;
827 /* Change legacy command line options into QMP ones */
828 static const struct {
829 const char *from;
830 const char *to;
831 } opt_renames[] = {
832 { "iops", "throttling.iops-total" },
833 { "iops_rd", "throttling.iops-read" },
834 { "iops_wr", "throttling.iops-write" },
836 { "bps", "throttling.bps-total" },
837 { "bps_rd", "throttling.bps-read" },
838 { "bps_wr", "throttling.bps-write" },
840 { "iops_max", "throttling.iops-total-max" },
841 { "iops_rd_max", "throttling.iops-read-max" },
842 { "iops_wr_max", "throttling.iops-write-max" },
844 { "bps_max", "throttling.bps-total-max" },
845 { "bps_rd_max", "throttling.bps-read-max" },
846 { "bps_wr_max", "throttling.bps-write-max" },
848 { "iops_size", "throttling.iops-size" },
850 { "group", "throttling.group" },
852 { "readonly", "read-only" },
855 for (i = 0; i < ARRAY_SIZE(opt_renames); i++) {
856 qemu_opt_rename(all_opts, opt_renames[i].from, opt_renames[i].to,
857 &local_err);
858 if (local_err) {
859 error_report_err(local_err);
860 return NULL;
864 value = qemu_opt_get(all_opts, "cache");
865 if (value) {
866 int flags = 0;
868 if (bdrv_parse_cache_flags(value, &flags) != 0) {
869 error_report("invalid cache option");
870 return NULL;
873 /* Specific options take precedence */
874 if (!qemu_opt_get(all_opts, BDRV_OPT_CACHE_WB)) {
875 qemu_opt_set_bool(all_opts, BDRV_OPT_CACHE_WB,
876 !!(flags & BDRV_O_CACHE_WB), &error_abort);
878 if (!qemu_opt_get(all_opts, BDRV_OPT_CACHE_DIRECT)) {
879 qemu_opt_set_bool(all_opts, BDRV_OPT_CACHE_DIRECT,
880 !!(flags & BDRV_O_NOCACHE), &error_abort);
882 if (!qemu_opt_get(all_opts, BDRV_OPT_CACHE_NO_FLUSH)) {
883 qemu_opt_set_bool(all_opts, BDRV_OPT_CACHE_NO_FLUSH,
884 !!(flags & BDRV_O_NO_FLUSH), &error_abort);
886 qemu_opt_unset(all_opts, "cache");
889 /* Get a QDict for processing the options */
890 bs_opts = qdict_new();
891 qemu_opts_to_qdict(all_opts, bs_opts);
893 legacy_opts = qemu_opts_create(&qemu_legacy_drive_opts, NULL, 0,
894 &error_abort);
895 qemu_opts_absorb_qdict(legacy_opts, bs_opts, &local_err);
896 if (local_err) {
897 error_report_err(local_err);
898 goto fail;
901 /* Deprecated option boot=[on|off] */
902 if (qemu_opt_get(legacy_opts, "boot") != NULL) {
903 fprintf(stderr, "qemu-kvm: boot=on|off is deprecated and will be "
904 "ignored. Future versions will reject this parameter. Please "
905 "update your scripts.\n");
908 /* Media type */
909 value = qemu_opt_get(legacy_opts, "media");
910 if (value) {
911 if (!strcmp(value, "disk")) {
912 media = MEDIA_DISK;
913 } else if (!strcmp(value, "cdrom")) {
914 media = MEDIA_CDROM;
915 read_only = true;
916 } else {
917 error_report("'%s' invalid media", value);
918 goto fail;
922 /* copy-on-read is disabled with a warning for read-only devices */
923 read_only |= qemu_opt_get_bool(legacy_opts, "read-only", false);
924 copy_on_read = qemu_opt_get_bool(legacy_opts, "copy-on-read", false);
926 if (read_only && copy_on_read) {
927 error_report("warning: disabling copy-on-read on read-only drive");
928 copy_on_read = false;
931 qdict_put(bs_opts, "read-only",
932 qstring_from_str(read_only ? "on" : "off"));
933 qdict_put(bs_opts, "copy-on-read",
934 qstring_from_str(copy_on_read ? "on" :"off"));
936 /* Controller type */
937 value = qemu_opt_get(legacy_opts, "if");
938 if (value) {
939 for (type = 0;
940 type < IF_COUNT && strcmp(value, if_name[type]);
941 type++) {
943 if (type == IF_COUNT) {
944 error_report("unsupported bus type '%s'", value);
945 goto fail;
947 } else {
948 type = block_default_type;
951 /* Geometry */
952 cyls = qemu_opt_get_number(legacy_opts, "cyls", 0);
953 heads = qemu_opt_get_number(legacy_opts, "heads", 0);
954 secs = qemu_opt_get_number(legacy_opts, "secs", 0);
956 if (cyls || heads || secs) {
957 if (cyls < 1) {
958 error_report("invalid physical cyls number");
959 goto fail;
961 if (heads < 1) {
962 error_report("invalid physical heads number");
963 goto fail;
965 if (secs < 1) {
966 error_report("invalid physical secs number");
967 goto fail;
971 translation = BIOS_ATA_TRANSLATION_AUTO;
972 value = qemu_opt_get(legacy_opts, "trans");
973 if (value != NULL) {
974 if (!cyls) {
975 error_report("'%s' trans must be used with cyls, heads and secs",
976 value);
977 goto fail;
979 if (!strcmp(value, "none")) {
980 translation = BIOS_ATA_TRANSLATION_NONE;
981 } else if (!strcmp(value, "lba")) {
982 translation = BIOS_ATA_TRANSLATION_LBA;
983 } else if (!strcmp(value, "large")) {
984 translation = BIOS_ATA_TRANSLATION_LARGE;
985 } else if (!strcmp(value, "rechs")) {
986 translation = BIOS_ATA_TRANSLATION_RECHS;
987 } else if (!strcmp(value, "auto")) {
988 translation = BIOS_ATA_TRANSLATION_AUTO;
989 } else {
990 error_report("'%s' invalid translation type", value);
991 goto fail;
995 if (media == MEDIA_CDROM) {
996 if (cyls || secs || heads) {
997 error_report("CHS can't be set with media=cdrom");
998 goto fail;
1002 /* Device address specified by bus/unit or index.
1003 * If none was specified, try to find the first free one. */
1004 bus_id = qemu_opt_get_number(legacy_opts, "bus", 0);
1005 unit_id = qemu_opt_get_number(legacy_opts, "unit", -1);
1006 index = qemu_opt_get_number(legacy_opts, "index", -1);
1008 max_devs = if_max_devs[type];
1010 if (index != -1) {
1011 if (bus_id != 0 || unit_id != -1) {
1012 error_report("index cannot be used with bus and unit");
1013 goto fail;
1015 bus_id = drive_index_to_bus_id(type, index);
1016 unit_id = drive_index_to_unit_id(type, index);
1019 if (unit_id == -1) {
1020 unit_id = 0;
1021 while (drive_get(type, bus_id, unit_id) != NULL) {
1022 unit_id++;
1023 if (max_devs && unit_id >= max_devs) {
1024 unit_id -= max_devs;
1025 bus_id++;
1030 if (max_devs && unit_id >= max_devs) {
1031 error_report("unit %d too big (max is %d)", unit_id, max_devs - 1);
1032 goto fail;
1035 if (drive_get(type, bus_id, unit_id) != NULL) {
1036 error_report("drive with bus=%d, unit=%d (index=%d) exists",
1037 bus_id, unit_id, index);
1038 goto fail;
1041 /* Serial number */
1042 serial = qemu_opt_get(legacy_opts, "serial");
1044 /* no id supplied -> create one */
1045 if (qemu_opts_id(all_opts) == NULL) {
1046 char *new_id;
1047 const char *mediastr = "";
1048 if (type == IF_IDE || type == IF_SCSI) {
1049 mediastr = (media == MEDIA_CDROM) ? "-cd" : "-hd";
1051 if (max_devs) {
1052 new_id = g_strdup_printf("%s%i%s%i", if_name[type], bus_id,
1053 mediastr, unit_id);
1054 } else {
1055 new_id = g_strdup_printf("%s%s%i", if_name[type],
1056 mediastr, unit_id);
1058 qdict_put(bs_opts, "id", qstring_from_str(new_id));
1059 g_free(new_id);
1062 /* Add virtio block device */
1063 devaddr = qemu_opt_get(legacy_opts, "addr");
1064 if (devaddr && type != IF_VIRTIO) {
1065 error_report("addr is not supported by this bus type");
1066 goto fail;
1069 if (type == IF_VIRTIO) {
1070 QemuOpts *devopts;
1071 devopts = qemu_opts_create(qemu_find_opts("device"), NULL, 0,
1072 &error_abort);
1073 if (arch_type == QEMU_ARCH_S390X) {
1074 qemu_opt_set(devopts, "driver", "virtio-blk-ccw", &error_abort);
1075 } else {
1076 qemu_opt_set(devopts, "driver", "virtio-blk-pci", &error_abort);
1078 qemu_opt_set(devopts, "drive", qdict_get_str(bs_opts, "id"),
1079 &error_abort);
1080 if (devaddr) {
1081 qemu_opt_set(devopts, "addr", devaddr, &error_abort);
1085 filename = qemu_opt_get(legacy_opts, "file");
1087 /* Check werror/rerror compatibility with if=... */
1088 werror = qemu_opt_get(legacy_opts, "werror");
1089 if (werror != NULL) {
1090 if (type != IF_IDE && type != IF_SCSI && type != IF_VIRTIO &&
1091 type != IF_NONE) {
1092 error_report("werror is not supported by this bus type");
1093 goto fail;
1095 qdict_put(bs_opts, "werror", qstring_from_str(werror));
1098 rerror = qemu_opt_get(legacy_opts, "rerror");
1099 if (rerror != NULL) {
1100 if (type != IF_IDE && type != IF_VIRTIO && type != IF_SCSI &&
1101 type != IF_NONE) {
1102 error_report("rerror is not supported by this bus type");
1103 goto fail;
1105 qdict_put(bs_opts, "rerror", qstring_from_str(rerror));
1108 /* Actual block device init: Functionality shared with blockdev-add */
1109 blk = blockdev_init(filename, bs_opts, &local_err);
1110 bs_opts = NULL;
1111 if (!blk) {
1112 if (local_err) {
1113 error_report_err(local_err);
1115 goto fail;
1116 } else {
1117 assert(!local_err);
1120 /* Create legacy DriveInfo */
1121 dinfo = g_malloc0(sizeof(*dinfo));
1122 dinfo->opts = all_opts;
1124 dinfo->cyls = cyls;
1125 dinfo->heads = heads;
1126 dinfo->secs = secs;
1127 dinfo->trans = translation;
1129 dinfo->type = type;
1130 dinfo->bus = bus_id;
1131 dinfo->unit = unit_id;
1132 dinfo->devaddr = devaddr;
1133 dinfo->serial = g_strdup(serial);
1135 blk_set_legacy_dinfo(blk, dinfo);
1137 switch(type) {
1138 case IF_IDE:
1139 case IF_SCSI:
1140 case IF_XEN:
1141 case IF_NONE:
1142 dinfo->media_cd = media == MEDIA_CDROM;
1143 break;
1144 default:
1145 break;
1148 fail:
1149 qemu_opts_del(legacy_opts);
1150 QDECREF(bs_opts);
1151 return dinfo;
1154 void hmp_commit(Monitor *mon, const QDict *qdict)
1156 const char *device = qdict_get_str(qdict, "device");
1157 BlockBackend *blk;
1158 int ret;
1160 if (!strcmp(device, "all")) {
1161 ret = bdrv_commit_all();
1162 } else {
1163 BlockDriverState *bs;
1164 AioContext *aio_context;
1166 blk = blk_by_name(device);
1167 if (!blk) {
1168 monitor_printf(mon, "Device '%s' not found\n", device);
1169 return;
1171 if (!blk_is_available(blk)) {
1172 monitor_printf(mon, "Device '%s' has no medium\n", device);
1173 return;
1176 bs = blk_bs(blk);
1177 aio_context = bdrv_get_aio_context(bs);
1178 aio_context_acquire(aio_context);
1180 ret = bdrv_commit(bs);
1182 aio_context_release(aio_context);
1184 if (ret < 0) {
1185 monitor_printf(mon, "'commit' error for '%s': %s\n", device,
1186 strerror(-ret));
1190 static void blockdev_do_action(TransactionActionKind type, void *data,
1191 Error **errp)
1193 TransactionAction action;
1194 TransactionActionList list;
1196 action.type = type;
1197 action.u.data = data;
1198 list.value = &action;
1199 list.next = NULL;
1200 qmp_transaction(&list, false, NULL, errp);
1203 void qmp_blockdev_snapshot_sync(bool has_device, const char *device,
1204 bool has_node_name, const char *node_name,
1205 const char *snapshot_file,
1206 bool has_snapshot_node_name,
1207 const char *snapshot_node_name,
1208 bool has_format, const char *format,
1209 bool has_mode, NewImageMode mode, Error **errp)
1211 BlockdevSnapshotSync snapshot = {
1212 .has_device = has_device,
1213 .device = (char *) device,
1214 .has_node_name = has_node_name,
1215 .node_name = (char *) node_name,
1216 .snapshot_file = (char *) snapshot_file,
1217 .has_snapshot_node_name = has_snapshot_node_name,
1218 .snapshot_node_name = (char *) snapshot_node_name,
1219 .has_format = has_format,
1220 .format = (char *) format,
1221 .has_mode = has_mode,
1222 .mode = mode,
1224 blockdev_do_action(TRANSACTION_ACTION_KIND_BLOCKDEV_SNAPSHOT_SYNC,
1225 &snapshot, errp);
1228 void qmp_blockdev_snapshot(const char *node, const char *overlay,
1229 Error **errp)
1231 BlockdevSnapshot snapshot_data = {
1232 .node = (char *) node,
1233 .overlay = (char *) overlay
1236 blockdev_do_action(TRANSACTION_ACTION_KIND_BLOCKDEV_SNAPSHOT,
1237 &snapshot_data, errp);
1240 void qmp_blockdev_snapshot_internal_sync(const char *device,
1241 const char *name,
1242 Error **errp)
1244 BlockdevSnapshotInternal snapshot = {
1245 .device = (char *) device,
1246 .name = (char *) name
1249 blockdev_do_action(TRANSACTION_ACTION_KIND_BLOCKDEV_SNAPSHOT_INTERNAL_SYNC,
1250 &snapshot, errp);
1253 SnapshotInfo *qmp_blockdev_snapshot_delete_internal_sync(const char *device,
1254 bool has_id,
1255 const char *id,
1256 bool has_name,
1257 const char *name,
1258 Error **errp)
1260 BlockDriverState *bs;
1261 BlockBackend *blk;
1262 AioContext *aio_context;
1263 QEMUSnapshotInfo sn;
1264 Error *local_err = NULL;
1265 SnapshotInfo *info = NULL;
1266 int ret;
1268 blk = blk_by_name(device);
1269 if (!blk) {
1270 error_set(errp, ERROR_CLASS_DEVICE_NOT_FOUND,
1271 "Device '%s' not found", device);
1272 return NULL;
1275 aio_context = blk_get_aio_context(blk);
1276 aio_context_acquire(aio_context);
1278 if (!has_id) {
1279 id = NULL;
1282 if (!has_name) {
1283 name = NULL;
1286 if (!id && !name) {
1287 error_setg(errp, "Name or id must be provided");
1288 goto out_aio_context;
1291 if (!blk_is_available(blk)) {
1292 error_setg(errp, "Device '%s' has no medium", device);
1293 goto out_aio_context;
1295 bs = blk_bs(blk);
1297 if (bdrv_op_is_blocked(bs, BLOCK_OP_TYPE_INTERNAL_SNAPSHOT_DELETE, errp)) {
1298 goto out_aio_context;
1301 ret = bdrv_snapshot_find_by_id_and_name(bs, id, name, &sn, &local_err);
1302 if (local_err) {
1303 error_propagate(errp, local_err);
1304 goto out_aio_context;
1306 if (!ret) {
1307 error_setg(errp,
1308 "Snapshot with id '%s' and name '%s' does not exist on "
1309 "device '%s'",
1310 STR_OR_NULL(id), STR_OR_NULL(name), device);
1311 goto out_aio_context;
1314 bdrv_snapshot_delete(bs, id, name, &local_err);
1315 if (local_err) {
1316 error_propagate(errp, local_err);
1317 goto out_aio_context;
1320 aio_context_release(aio_context);
1322 info = g_new0(SnapshotInfo, 1);
1323 info->id = g_strdup(sn.id_str);
1324 info->name = g_strdup(sn.name);
1325 info->date_nsec = sn.date_nsec;
1326 info->date_sec = sn.date_sec;
1327 info->vm_state_size = sn.vm_state_size;
1328 info->vm_clock_nsec = sn.vm_clock_nsec % 1000000000;
1329 info->vm_clock_sec = sn.vm_clock_nsec / 1000000000;
1331 return info;
1333 out_aio_context:
1334 aio_context_release(aio_context);
1335 return NULL;
1339 * block_dirty_bitmap_lookup:
1340 * Return a dirty bitmap (if present), after validating
1341 * the node reference and bitmap names.
1343 * @node: The name of the BDS node to search for bitmaps
1344 * @name: The name of the bitmap to search for
1345 * @pbs: Output pointer for BDS lookup, if desired. Can be NULL.
1346 * @paio: Output pointer for aio_context acquisition, if desired. Can be NULL.
1347 * @errp: Output pointer for error information. Can be NULL.
1349 * @return: A bitmap object on success, or NULL on failure.
1351 static BdrvDirtyBitmap *block_dirty_bitmap_lookup(const char *node,
1352 const char *name,
1353 BlockDriverState **pbs,
1354 AioContext **paio,
1355 Error **errp)
1357 BlockDriverState *bs;
1358 BdrvDirtyBitmap *bitmap;
1359 AioContext *aio_context;
1361 if (!node) {
1362 error_setg(errp, "Node cannot be NULL");
1363 return NULL;
1365 if (!name) {
1366 error_setg(errp, "Bitmap name cannot be NULL");
1367 return NULL;
1369 bs = bdrv_lookup_bs(node, node, NULL);
1370 if (!bs) {
1371 error_setg(errp, "Node '%s' not found", node);
1372 return NULL;
1375 aio_context = bdrv_get_aio_context(bs);
1376 aio_context_acquire(aio_context);
1378 bitmap = bdrv_find_dirty_bitmap(bs, name);
1379 if (!bitmap) {
1380 error_setg(errp, "Dirty bitmap '%s' not found", name);
1381 goto fail;
1384 if (pbs) {
1385 *pbs = bs;
1387 if (paio) {
1388 *paio = aio_context;
1389 } else {
1390 aio_context_release(aio_context);
1393 return bitmap;
1395 fail:
1396 aio_context_release(aio_context);
1397 return NULL;
1400 /* New and old BlockDriverState structs for atomic group operations */
1402 typedef struct BlkActionState BlkActionState;
1405 * BlkActionOps:
1406 * Table of operations that define an Action.
1408 * @instance_size: Size of state struct, in bytes.
1409 * @prepare: Prepare the work, must NOT be NULL.
1410 * @commit: Commit the changes, can be NULL.
1411 * @abort: Abort the changes on fail, can be NULL.
1412 * @clean: Clean up resources after all transaction actions have called
1413 * commit() or abort(). Can be NULL.
1415 * Only prepare() may fail. In a single transaction, only one of commit() or
1416 * abort() will be called. clean() will always be called if it is present.
1418 typedef struct BlkActionOps {
1419 size_t instance_size;
1420 void (*prepare)(BlkActionState *common, Error **errp);
1421 void (*commit)(BlkActionState *common);
1422 void (*abort)(BlkActionState *common);
1423 void (*clean)(BlkActionState *common);
1424 } BlkActionOps;
1427 * BlkActionState:
1428 * Describes one Action's state within a Transaction.
1430 * @action: QAPI-defined enum identifying which Action to perform.
1431 * @ops: Table of ActionOps this Action can perform.
1432 * @block_job_txn: Transaction which this action belongs to.
1433 * @entry: List membership for all Actions in this Transaction.
1435 * This structure must be arranged as first member in a subclassed type,
1436 * assuming that the compiler will also arrange it to the same offsets as the
1437 * base class.
1439 struct BlkActionState {
1440 TransactionAction *action;
1441 const BlkActionOps *ops;
1442 BlockJobTxn *block_job_txn;
1443 TransactionProperties *txn_props;
1444 QSIMPLEQ_ENTRY(BlkActionState) entry;
1447 /* internal snapshot private data */
1448 typedef struct InternalSnapshotState {
1449 BlkActionState common;
1450 BlockDriverState *bs;
1451 AioContext *aio_context;
1452 QEMUSnapshotInfo sn;
1453 bool created;
1454 } InternalSnapshotState;
1457 static int action_check_completion_mode(BlkActionState *s, Error **errp)
1459 if (s->txn_props->completion_mode != ACTION_COMPLETION_MODE_INDIVIDUAL) {
1460 error_setg(errp,
1461 "Action '%s' does not support Transaction property "
1462 "completion-mode = %s",
1463 TransactionActionKind_lookup[s->action->type],
1464 ActionCompletionMode_lookup[s->txn_props->completion_mode]);
1465 return -1;
1467 return 0;
1470 static void internal_snapshot_prepare(BlkActionState *common,
1471 Error **errp)
1473 Error *local_err = NULL;
1474 const char *device;
1475 const char *name;
1476 BlockBackend *blk;
1477 BlockDriverState *bs;
1478 QEMUSnapshotInfo old_sn, *sn;
1479 bool ret;
1480 qemu_timeval tv;
1481 BlockdevSnapshotInternal *internal;
1482 InternalSnapshotState *state;
1483 int ret1;
1485 g_assert(common->action->type ==
1486 TRANSACTION_ACTION_KIND_BLOCKDEV_SNAPSHOT_INTERNAL_SYNC);
1487 internal = common->action->u.blockdev_snapshot_internal_sync;
1488 state = DO_UPCAST(InternalSnapshotState, common, common);
1490 /* 1. parse input */
1491 device = internal->device;
1492 name = internal->name;
1494 /* 2. check for validation */
1495 if (action_check_completion_mode(common, errp) < 0) {
1496 return;
1499 blk = blk_by_name(device);
1500 if (!blk) {
1501 error_set(errp, ERROR_CLASS_DEVICE_NOT_FOUND,
1502 "Device '%s' not found", device);
1503 return;
1506 /* AioContext is released in .clean() */
1507 state->aio_context = blk_get_aio_context(blk);
1508 aio_context_acquire(state->aio_context);
1510 if (!blk_is_available(blk)) {
1511 error_setg(errp, QERR_DEVICE_HAS_NO_MEDIUM, device);
1512 return;
1514 bs = blk_bs(blk);
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, ret;
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;
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;
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;
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;
1714 /* create new image w/backing file */
1715 mode = s->has_mode ? s->mode : NEW_IMAGE_MODE_ABSOLUTE_PATHS;
1716 if (mode != NEW_IMAGE_MODE_EXISTING) {
1717 bdrv_img_create(new_image_file, format,
1718 state->old_bs->filename,
1719 state->old_bs->drv->format_name,
1720 NULL, -1, flags, &local_err, false);
1721 if (local_err) {
1722 error_propagate(errp, local_err);
1723 return;
1727 options = qdict_new();
1728 if (s->has_snapshot_node_name) {
1729 qdict_put(options, "node-name",
1730 qstring_from_str(snapshot_node_name));
1732 qdict_put(options, "driver", qstring_from_str(format));
1734 flags |= BDRV_O_NO_BACKING;
1737 assert(state->new_bs == NULL);
1738 ret = bdrv_open(&state->new_bs, new_image_file, snapshot_ref, options,
1739 flags, errp);
1740 /* We will manually add the backing_hd field to the bs later */
1741 if (ret != 0) {
1742 return;
1745 if (state->new_bs->blk != NULL) {
1746 error_setg(errp, "The snapshot is already in use by %s",
1747 blk_name(state->new_bs->blk));
1748 return;
1751 if (bdrv_op_is_blocked(state->new_bs, BLOCK_OP_TYPE_EXTERNAL_SNAPSHOT,
1752 errp)) {
1753 return;
1756 if (state->new_bs->backing != NULL) {
1757 error_setg(errp, "The snapshot already has a backing image");
1758 return;
1761 if (!state->new_bs->drv->supports_backing) {
1762 error_setg(errp, "The snapshot does not support backing images");
1766 static void external_snapshot_commit(BlkActionState *common)
1768 ExternalSnapshotState *state =
1769 DO_UPCAST(ExternalSnapshotState, common, common);
1771 bdrv_set_aio_context(state->new_bs, state->aio_context);
1773 /* This removes our old bs and adds the new bs */
1774 bdrv_append(state->new_bs, state->old_bs);
1775 /* We don't need (or want) to use the transactional
1776 * bdrv_reopen_multiple() across all the entries at once, because we
1777 * don't want to abort all of them if one of them fails the reopen */
1778 bdrv_reopen(state->old_bs, state->old_bs->open_flags & ~BDRV_O_RDWR,
1779 NULL);
1782 static void external_snapshot_abort(BlkActionState *common)
1784 ExternalSnapshotState *state =
1785 DO_UPCAST(ExternalSnapshotState, common, common);
1786 if (state->new_bs) {
1787 bdrv_unref(state->new_bs);
1791 static void external_snapshot_clean(BlkActionState *common)
1793 ExternalSnapshotState *state =
1794 DO_UPCAST(ExternalSnapshotState, common, common);
1795 if (state->aio_context) {
1796 bdrv_drained_end(state->old_bs);
1797 aio_context_release(state->aio_context);
1801 typedef struct DriveBackupState {
1802 BlkActionState common;
1803 BlockDriverState *bs;
1804 AioContext *aio_context;
1805 BlockJob *job;
1806 } DriveBackupState;
1808 static void do_drive_backup(const char *device, const char *target,
1809 bool has_format, const char *format,
1810 enum MirrorSyncMode sync,
1811 bool has_mode, enum NewImageMode mode,
1812 bool has_speed, int64_t speed,
1813 bool has_bitmap, const char *bitmap,
1814 bool has_on_source_error,
1815 BlockdevOnError on_source_error,
1816 bool has_on_target_error,
1817 BlockdevOnError on_target_error,
1818 BlockJobTxn *txn, Error **errp);
1820 static void drive_backup_prepare(BlkActionState *common, Error **errp)
1822 DriveBackupState *state = DO_UPCAST(DriveBackupState, common, common);
1823 BlockBackend *blk;
1824 DriveBackup *backup;
1825 Error *local_err = NULL;
1827 assert(common->action->type == TRANSACTION_ACTION_KIND_DRIVE_BACKUP);
1828 backup = common->action->u.drive_backup;
1830 blk = blk_by_name(backup->device);
1831 if (!blk) {
1832 error_set(errp, ERROR_CLASS_DEVICE_NOT_FOUND,
1833 "Device '%s' not found", backup->device);
1834 return;
1837 if (!blk_is_available(blk)) {
1838 error_setg(errp, QERR_DEVICE_HAS_NO_MEDIUM, backup->device);
1839 return;
1842 /* AioContext is released in .clean() */
1843 state->aio_context = blk_get_aio_context(blk);
1844 aio_context_acquire(state->aio_context);
1845 bdrv_drained_begin(blk_bs(blk));
1846 state->bs = blk_bs(blk);
1848 do_drive_backup(backup->device, backup->target,
1849 backup->has_format, backup->format,
1850 backup->sync,
1851 backup->has_mode, backup->mode,
1852 backup->has_speed, backup->speed,
1853 backup->has_bitmap, backup->bitmap,
1854 backup->has_on_source_error, backup->on_source_error,
1855 backup->has_on_target_error, backup->on_target_error,
1856 common->block_job_txn, &local_err);
1857 if (local_err) {
1858 error_propagate(errp, local_err);
1859 return;
1862 state->job = state->bs->job;
1865 static void drive_backup_abort(BlkActionState *common)
1867 DriveBackupState *state = DO_UPCAST(DriveBackupState, common, common);
1868 BlockDriverState *bs = state->bs;
1870 /* Only cancel if it's the job we started */
1871 if (bs && bs->job && bs->job == state->job) {
1872 block_job_cancel_sync(bs->job);
1876 static void drive_backup_clean(BlkActionState *common)
1878 DriveBackupState *state = DO_UPCAST(DriveBackupState, common, common);
1880 if (state->aio_context) {
1881 bdrv_drained_end(state->bs);
1882 aio_context_release(state->aio_context);
1886 typedef struct BlockdevBackupState {
1887 BlkActionState common;
1888 BlockDriverState *bs;
1889 BlockJob *job;
1890 AioContext *aio_context;
1891 } BlockdevBackupState;
1893 static void do_blockdev_backup(const char *device, const char *target,
1894 enum MirrorSyncMode sync,
1895 bool has_speed, int64_t speed,
1896 bool has_on_source_error,
1897 BlockdevOnError on_source_error,
1898 bool has_on_target_error,
1899 BlockdevOnError on_target_error,
1900 BlockJobTxn *txn, Error **errp);
1902 static void blockdev_backup_prepare(BlkActionState *common, Error **errp)
1904 BlockdevBackupState *state = DO_UPCAST(BlockdevBackupState, common, common);
1905 BlockdevBackup *backup;
1906 BlockBackend *blk, *target;
1907 Error *local_err = NULL;
1909 assert(common->action->type == TRANSACTION_ACTION_KIND_BLOCKDEV_BACKUP);
1910 backup = common->action->u.blockdev_backup;
1912 blk = blk_by_name(backup->device);
1913 if (!blk) {
1914 error_setg(errp, "Device '%s' not found", backup->device);
1915 return;
1918 if (!blk_is_available(blk)) {
1919 error_setg(errp, QERR_DEVICE_HAS_NO_MEDIUM, backup->device);
1920 return;
1923 target = blk_by_name(backup->target);
1924 if (!target) {
1925 error_setg(errp, "Device '%s' not found", backup->target);
1926 return;
1929 /* AioContext is released in .clean() */
1930 state->aio_context = blk_get_aio_context(blk);
1931 if (state->aio_context != blk_get_aio_context(target)) {
1932 state->aio_context = NULL;
1933 error_setg(errp, "Backup between two IO threads is not implemented");
1934 return;
1936 aio_context_acquire(state->aio_context);
1937 state->bs = blk_bs(blk);
1938 bdrv_drained_begin(state->bs);
1940 do_blockdev_backup(backup->device, backup->target,
1941 backup->sync,
1942 backup->has_speed, backup->speed,
1943 backup->has_on_source_error, backup->on_source_error,
1944 backup->has_on_target_error, backup->on_target_error,
1945 common->block_job_txn, &local_err);
1946 if (local_err) {
1947 error_propagate(errp, local_err);
1948 return;
1951 state->job = state->bs->job;
1954 static void blockdev_backup_abort(BlkActionState *common)
1956 BlockdevBackupState *state = DO_UPCAST(BlockdevBackupState, common, common);
1957 BlockDriverState *bs = state->bs;
1959 /* Only cancel if it's the job we started */
1960 if (bs && bs->job && bs->job == state->job) {
1961 block_job_cancel_sync(bs->job);
1965 static void blockdev_backup_clean(BlkActionState *common)
1967 BlockdevBackupState *state = DO_UPCAST(BlockdevBackupState, common, common);
1969 if (state->aio_context) {
1970 bdrv_drained_end(state->bs);
1971 aio_context_release(state->aio_context);
1975 typedef struct BlockDirtyBitmapState {
1976 BlkActionState common;
1977 BdrvDirtyBitmap *bitmap;
1978 BlockDriverState *bs;
1979 AioContext *aio_context;
1980 HBitmap *backup;
1981 bool prepared;
1982 } BlockDirtyBitmapState;
1984 static void block_dirty_bitmap_add_prepare(BlkActionState *common,
1985 Error **errp)
1987 Error *local_err = NULL;
1988 BlockDirtyBitmapAdd *action;
1989 BlockDirtyBitmapState *state = DO_UPCAST(BlockDirtyBitmapState,
1990 common, common);
1992 if (action_check_completion_mode(common, errp) < 0) {
1993 return;
1996 action = common->action->u.block_dirty_bitmap_add;
1997 /* AIO context taken and released within qmp_block_dirty_bitmap_add */
1998 qmp_block_dirty_bitmap_add(action->node, action->name,
1999 action->has_granularity, action->granularity,
2000 &local_err);
2002 if (!local_err) {
2003 state->prepared = true;
2004 } else {
2005 error_propagate(errp, local_err);
2009 static void block_dirty_bitmap_add_abort(BlkActionState *common)
2011 BlockDirtyBitmapAdd *action;
2012 BlockDirtyBitmapState *state = DO_UPCAST(BlockDirtyBitmapState,
2013 common, common);
2015 action = common->action->u.block_dirty_bitmap_add;
2016 /* Should not be able to fail: IF the bitmap was added via .prepare(),
2017 * then the node reference and bitmap name must have been valid.
2019 if (state->prepared) {
2020 qmp_block_dirty_bitmap_remove(action->node, action->name, &error_abort);
2024 static void block_dirty_bitmap_clear_prepare(BlkActionState *common,
2025 Error **errp)
2027 BlockDirtyBitmapState *state = DO_UPCAST(BlockDirtyBitmapState,
2028 common, common);
2029 BlockDirtyBitmap *action;
2031 if (action_check_completion_mode(common, errp) < 0) {
2032 return;
2035 action = common->action->u.block_dirty_bitmap_clear;
2036 state->bitmap = block_dirty_bitmap_lookup(action->node,
2037 action->name,
2038 &state->bs,
2039 &state->aio_context,
2040 errp);
2041 if (!state->bitmap) {
2042 return;
2045 if (bdrv_dirty_bitmap_frozen(state->bitmap)) {
2046 error_setg(errp, "Cannot modify a frozen bitmap");
2047 return;
2048 } else if (!bdrv_dirty_bitmap_enabled(state->bitmap)) {
2049 error_setg(errp, "Cannot clear a disabled bitmap");
2050 return;
2053 bdrv_clear_dirty_bitmap(state->bitmap, &state->backup);
2054 /* AioContext is released in .clean() */
2057 static void block_dirty_bitmap_clear_abort(BlkActionState *common)
2059 BlockDirtyBitmapState *state = DO_UPCAST(BlockDirtyBitmapState,
2060 common, common);
2062 bdrv_undo_clear_dirty_bitmap(state->bitmap, state->backup);
2065 static void block_dirty_bitmap_clear_commit(BlkActionState *common)
2067 BlockDirtyBitmapState *state = DO_UPCAST(BlockDirtyBitmapState,
2068 common, common);
2070 hbitmap_free(state->backup);
2073 static void block_dirty_bitmap_clear_clean(BlkActionState *common)
2075 BlockDirtyBitmapState *state = DO_UPCAST(BlockDirtyBitmapState,
2076 common, common);
2078 if (state->aio_context) {
2079 aio_context_release(state->aio_context);
2083 static void abort_prepare(BlkActionState *common, Error **errp)
2085 error_setg(errp, "Transaction aborted using Abort action");
2088 static void abort_commit(BlkActionState *common)
2090 g_assert_not_reached(); /* this action never succeeds */
2093 static const BlkActionOps actions[] = {
2094 [TRANSACTION_ACTION_KIND_BLOCKDEV_SNAPSHOT] = {
2095 .instance_size = sizeof(ExternalSnapshotState),
2096 .prepare = external_snapshot_prepare,
2097 .commit = external_snapshot_commit,
2098 .abort = external_snapshot_abort,
2099 .clean = external_snapshot_clean,
2101 [TRANSACTION_ACTION_KIND_BLOCKDEV_SNAPSHOT_SYNC] = {
2102 .instance_size = sizeof(ExternalSnapshotState),
2103 .prepare = external_snapshot_prepare,
2104 .commit = external_snapshot_commit,
2105 .abort = external_snapshot_abort,
2106 .clean = external_snapshot_clean,
2108 [TRANSACTION_ACTION_KIND_DRIVE_BACKUP] = {
2109 .instance_size = sizeof(DriveBackupState),
2110 .prepare = drive_backup_prepare,
2111 .abort = drive_backup_abort,
2112 .clean = drive_backup_clean,
2114 [TRANSACTION_ACTION_KIND_BLOCKDEV_BACKUP] = {
2115 .instance_size = sizeof(BlockdevBackupState),
2116 .prepare = blockdev_backup_prepare,
2117 .abort = blockdev_backup_abort,
2118 .clean = blockdev_backup_clean,
2120 [TRANSACTION_ACTION_KIND_ABORT] = {
2121 .instance_size = sizeof(BlkActionState),
2122 .prepare = abort_prepare,
2123 .commit = abort_commit,
2125 [TRANSACTION_ACTION_KIND_BLOCKDEV_SNAPSHOT_INTERNAL_SYNC] = {
2126 .instance_size = sizeof(InternalSnapshotState),
2127 .prepare = internal_snapshot_prepare,
2128 .abort = internal_snapshot_abort,
2129 .clean = internal_snapshot_clean,
2131 [TRANSACTION_ACTION_KIND_BLOCK_DIRTY_BITMAP_ADD] = {
2132 .instance_size = sizeof(BlockDirtyBitmapState),
2133 .prepare = block_dirty_bitmap_add_prepare,
2134 .abort = block_dirty_bitmap_add_abort,
2136 [TRANSACTION_ACTION_KIND_BLOCK_DIRTY_BITMAP_CLEAR] = {
2137 .instance_size = sizeof(BlockDirtyBitmapState),
2138 .prepare = block_dirty_bitmap_clear_prepare,
2139 .commit = block_dirty_bitmap_clear_commit,
2140 .abort = block_dirty_bitmap_clear_abort,
2141 .clean = block_dirty_bitmap_clear_clean,
2146 * Allocate a TransactionProperties structure if necessary, and fill
2147 * that structure with desired defaults if they are unset.
2149 static TransactionProperties *get_transaction_properties(
2150 TransactionProperties *props)
2152 if (!props) {
2153 props = g_new0(TransactionProperties, 1);
2156 if (!props->has_completion_mode) {
2157 props->has_completion_mode = true;
2158 props->completion_mode = ACTION_COMPLETION_MODE_INDIVIDUAL;
2161 return props;
2165 * 'Atomic' group operations. The operations are performed as a set, and if
2166 * any fail then we roll back all operations in the group.
2168 void qmp_transaction(TransactionActionList *dev_list,
2169 bool has_props,
2170 struct TransactionProperties *props,
2171 Error **errp)
2173 TransactionActionList *dev_entry = dev_list;
2174 BlockJobTxn *block_job_txn = NULL;
2175 BlkActionState *state, *next;
2176 Error *local_err = NULL;
2178 QSIMPLEQ_HEAD(snap_bdrv_states, BlkActionState) snap_bdrv_states;
2179 QSIMPLEQ_INIT(&snap_bdrv_states);
2181 /* Does this transaction get canceled as a group on failure?
2182 * If not, we don't really need to make a BlockJobTxn.
2184 props = get_transaction_properties(props);
2185 if (props->completion_mode != ACTION_COMPLETION_MODE_INDIVIDUAL) {
2186 block_job_txn = block_job_txn_new();
2189 /* drain all i/o before any operations */
2190 bdrv_drain_all();
2192 /* We don't do anything in this loop that commits us to the operations */
2193 while (NULL != dev_entry) {
2194 TransactionAction *dev_info = NULL;
2195 const BlkActionOps *ops;
2197 dev_info = dev_entry->value;
2198 dev_entry = dev_entry->next;
2200 assert(dev_info->type < ARRAY_SIZE(actions));
2202 ops = &actions[dev_info->type];
2203 assert(ops->instance_size > 0);
2205 state = g_malloc0(ops->instance_size);
2206 state->ops = ops;
2207 state->action = dev_info;
2208 state->block_job_txn = block_job_txn;
2209 state->txn_props = props;
2210 QSIMPLEQ_INSERT_TAIL(&snap_bdrv_states, state, entry);
2212 state->ops->prepare(state, &local_err);
2213 if (local_err) {
2214 error_propagate(errp, local_err);
2215 goto delete_and_fail;
2219 QSIMPLEQ_FOREACH(state, &snap_bdrv_states, entry) {
2220 if (state->ops->commit) {
2221 state->ops->commit(state);
2225 /* success */
2226 goto exit;
2228 delete_and_fail:
2229 /* failure, and it is all-or-none; roll back all operations */
2230 QSIMPLEQ_FOREACH(state, &snap_bdrv_states, entry) {
2231 if (state->ops->abort) {
2232 state->ops->abort(state);
2235 exit:
2236 QSIMPLEQ_FOREACH_SAFE(state, &snap_bdrv_states, entry, next) {
2237 if (state->ops->clean) {
2238 state->ops->clean(state);
2240 g_free(state);
2242 if (!has_props) {
2243 qapi_free_TransactionProperties(props);
2245 block_job_txn_unref(block_job_txn);
2248 void qmp_eject(const char *device, bool has_force, bool force, Error **errp)
2250 Error *local_err = NULL;
2252 qmp_blockdev_open_tray(device, has_force, force, &local_err);
2253 if (local_err) {
2254 error_propagate(errp, local_err);
2255 return;
2258 qmp_x_blockdev_remove_medium(device, errp);
2261 void qmp_block_passwd(bool has_device, const char *device,
2262 bool has_node_name, const char *node_name,
2263 const char *password, Error **errp)
2265 Error *local_err = NULL;
2266 BlockDriverState *bs;
2267 AioContext *aio_context;
2269 bs = bdrv_lookup_bs(has_device ? device : NULL,
2270 has_node_name ? node_name : NULL,
2271 &local_err);
2272 if (local_err) {
2273 error_propagate(errp, local_err);
2274 return;
2277 aio_context = bdrv_get_aio_context(bs);
2278 aio_context_acquire(aio_context);
2280 bdrv_add_key(bs, password, errp);
2282 aio_context_release(aio_context);
2285 void qmp_blockdev_open_tray(const char *device, bool has_force, bool force,
2286 Error **errp)
2288 BlockBackend *blk;
2289 bool locked;
2291 if (!has_force) {
2292 force = false;
2295 blk = blk_by_name(device);
2296 if (!blk) {
2297 error_set(errp, ERROR_CLASS_DEVICE_NOT_FOUND,
2298 "Device '%s' not found", device);
2299 return;
2302 if (!blk_dev_has_removable_media(blk)) {
2303 error_setg(errp, "Device '%s' is not removable", device);
2304 return;
2307 if (!blk_dev_has_tray(blk)) {
2308 /* Ignore this command on tray-less devices */
2309 return;
2312 if (blk_dev_is_tray_open(blk)) {
2313 return;
2316 locked = blk_dev_is_medium_locked(blk);
2317 if (locked) {
2318 blk_dev_eject_request(blk, force);
2321 if (!locked || force) {
2322 blk_dev_change_media_cb(blk, false);
2326 void qmp_blockdev_close_tray(const char *device, Error **errp)
2328 BlockBackend *blk;
2330 blk = blk_by_name(device);
2331 if (!blk) {
2332 error_set(errp, ERROR_CLASS_DEVICE_NOT_FOUND,
2333 "Device '%s' not found", device);
2334 return;
2337 if (!blk_dev_has_removable_media(blk)) {
2338 error_setg(errp, "Device '%s' is not removable", device);
2339 return;
2342 if (!blk_dev_has_tray(blk)) {
2343 /* Ignore this command on tray-less devices */
2344 return;
2347 if (!blk_dev_is_tray_open(blk)) {
2348 return;
2351 blk_dev_change_media_cb(blk, true);
2354 void qmp_x_blockdev_remove_medium(const char *device, Error **errp)
2356 BlockBackend *blk;
2357 BlockDriverState *bs;
2358 AioContext *aio_context;
2359 bool has_device;
2361 blk = blk_by_name(device);
2362 if (!blk) {
2363 error_set(errp, ERROR_CLASS_DEVICE_NOT_FOUND,
2364 "Device '%s' not found", device);
2365 return;
2368 /* For BBs without a device, we can exchange the BDS tree at will */
2369 has_device = blk_get_attached_dev(blk);
2371 if (has_device && !blk_dev_has_removable_media(blk)) {
2372 error_setg(errp, "Device '%s' is not removable", device);
2373 return;
2376 if (has_device && blk_dev_has_tray(blk) && !blk_dev_is_tray_open(blk)) {
2377 error_setg(errp, "Tray of device '%s' is not open", device);
2378 return;
2381 bs = blk_bs(blk);
2382 if (!bs) {
2383 return;
2386 aio_context = bdrv_get_aio_context(bs);
2387 aio_context_acquire(aio_context);
2389 if (bdrv_op_is_blocked(bs, BLOCK_OP_TYPE_EJECT, errp)) {
2390 goto out;
2393 /* This follows the convention established by bdrv_make_anon() */
2394 if (bs->device_list.tqe_prev) {
2395 QTAILQ_REMOVE(&bdrv_states, bs, device_list);
2396 bs->device_list.tqe_prev = NULL;
2399 blk_remove_bs(blk);
2401 if (!blk_dev_has_tray(blk)) {
2402 /* For tray-less devices, blockdev-open-tray is a no-op (or may not be
2403 * called at all); therefore, the medium needs to be ejected here.
2404 * Do it after blk_remove_bs() so blk_is_inserted(blk) returns the @load
2405 * value passed here (i.e. false). */
2406 blk_dev_change_media_cb(blk, false);
2409 out:
2410 aio_context_release(aio_context);
2413 static void qmp_blockdev_insert_anon_medium(const char *device,
2414 BlockDriverState *bs, Error **errp)
2416 BlockBackend *blk;
2417 bool has_device;
2419 blk = blk_by_name(device);
2420 if (!blk) {
2421 error_set(errp, ERROR_CLASS_DEVICE_NOT_FOUND,
2422 "Device '%s' not found", device);
2423 return;
2426 /* For BBs without a device, we can exchange the BDS tree at will */
2427 has_device = blk_get_attached_dev(blk);
2429 if (has_device && !blk_dev_has_removable_media(blk)) {
2430 error_setg(errp, "Device '%s' is not removable", device);
2431 return;
2434 if (has_device && blk_dev_has_tray(blk) && !blk_dev_is_tray_open(blk)) {
2435 error_setg(errp, "Tray of device '%s' is not open", device);
2436 return;
2439 if (blk_bs(blk)) {
2440 error_setg(errp, "There already is a medium in device '%s'", device);
2441 return;
2444 blk_insert_bs(blk, bs);
2446 QTAILQ_INSERT_TAIL(&bdrv_states, bs, device_list);
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(const char *device, const char *node_name,
2459 Error **errp)
2461 BlockDriverState *bs;
2463 bs = bdrv_find_node(node_name);
2464 if (!bs) {
2465 error_setg(errp, "Node '%s' not found", node_name);
2466 return;
2469 if (bs->blk) {
2470 error_setg(errp, "Node '%s' is already in use by '%s'", node_name,
2471 blk_name(bs->blk));
2472 return;
2475 qmp_blockdev_insert_anon_medium(device, bs, errp);
2478 void qmp_blockdev_change_medium(const char *device, const char *filename,
2479 bool has_format, const char *format,
2480 bool has_read_only,
2481 BlockdevChangeReadOnlyMode read_only,
2482 Error **errp)
2484 BlockBackend *blk;
2485 BlockDriverState *medium_bs = NULL;
2486 int bdrv_flags, ret;
2487 QDict *options = NULL;
2488 Error *err = NULL;
2490 blk = blk_by_name(device);
2491 if (!blk) {
2492 error_set(errp, ERROR_CLASS_DEVICE_NOT_FOUND,
2493 "Device '%s' not found", device);
2494 goto fail;
2497 if (blk_bs(blk)) {
2498 blk_update_root_state(blk);
2501 bdrv_flags = blk_get_open_flags_from_root_state(blk);
2503 if (!has_read_only) {
2504 read_only = BLOCKDEV_CHANGE_READ_ONLY_MODE_RETAIN;
2507 switch (read_only) {
2508 case BLOCKDEV_CHANGE_READ_ONLY_MODE_RETAIN:
2509 break;
2511 case BLOCKDEV_CHANGE_READ_ONLY_MODE_READ_ONLY:
2512 bdrv_flags &= ~BDRV_O_RDWR;
2513 break;
2515 case BLOCKDEV_CHANGE_READ_ONLY_MODE_READ_WRITE:
2516 bdrv_flags |= BDRV_O_RDWR;
2517 break;
2519 default:
2520 abort();
2523 if (has_format) {
2524 options = qdict_new();
2525 qdict_put(options, "driver", qstring_from_str(format));
2528 assert(!medium_bs);
2529 ret = bdrv_open(&medium_bs, filename, NULL, options, bdrv_flags, errp);
2530 if (ret < 0) {
2531 goto fail;
2534 blk_apply_root_state(blk, medium_bs);
2536 bdrv_add_key(medium_bs, NULL, &err);
2537 if (err) {
2538 error_propagate(errp, err);
2539 goto fail;
2542 qmp_blockdev_open_tray(device, false, false, &err);
2543 if (err) {
2544 error_propagate(errp, err);
2545 goto fail;
2548 qmp_x_blockdev_remove_medium(device, &err);
2549 if (err) {
2550 error_propagate(errp, err);
2551 goto fail;
2554 qmp_blockdev_insert_anon_medium(device, medium_bs, &err);
2555 if (err) {
2556 error_propagate(errp, err);
2557 goto fail;
2560 qmp_blockdev_close_tray(device, errp);
2562 fail:
2563 /* If the medium has been inserted, the device has its own reference, so
2564 * ours must be relinquished; and if it has not been inserted successfully,
2565 * the reference must be relinquished anyway */
2566 bdrv_unref(medium_bs);
2569 /* throttling disk I/O limits */
2570 void qmp_block_set_io_throttle(const char *device, int64_t bps, int64_t bps_rd,
2571 int64_t bps_wr,
2572 int64_t iops,
2573 int64_t iops_rd,
2574 int64_t iops_wr,
2575 bool has_bps_max,
2576 int64_t bps_max,
2577 bool has_bps_rd_max,
2578 int64_t bps_rd_max,
2579 bool has_bps_wr_max,
2580 int64_t bps_wr_max,
2581 bool has_iops_max,
2582 int64_t iops_max,
2583 bool has_iops_rd_max,
2584 int64_t iops_rd_max,
2585 bool has_iops_wr_max,
2586 int64_t iops_wr_max,
2587 bool has_iops_size,
2588 int64_t iops_size,
2589 bool has_group,
2590 const char *group, Error **errp)
2592 ThrottleConfig cfg;
2593 BlockDriverState *bs;
2594 BlockBackend *blk;
2595 AioContext *aio_context;
2597 blk = blk_by_name(device);
2598 if (!blk) {
2599 error_set(errp, ERROR_CLASS_DEVICE_NOT_FOUND,
2600 "Device '%s' not found", device);
2601 return;
2604 aio_context = blk_get_aio_context(blk);
2605 aio_context_acquire(aio_context);
2607 bs = blk_bs(blk);
2608 if (!bs) {
2609 error_setg(errp, "Device '%s' has no medium", device);
2610 goto out;
2613 memset(&cfg, 0, sizeof(cfg));
2614 cfg.buckets[THROTTLE_BPS_TOTAL].avg = bps;
2615 cfg.buckets[THROTTLE_BPS_READ].avg = bps_rd;
2616 cfg.buckets[THROTTLE_BPS_WRITE].avg = bps_wr;
2618 cfg.buckets[THROTTLE_OPS_TOTAL].avg = iops;
2619 cfg.buckets[THROTTLE_OPS_READ].avg = iops_rd;
2620 cfg.buckets[THROTTLE_OPS_WRITE].avg = iops_wr;
2622 if (has_bps_max) {
2623 cfg.buckets[THROTTLE_BPS_TOTAL].max = bps_max;
2625 if (has_bps_rd_max) {
2626 cfg.buckets[THROTTLE_BPS_READ].max = bps_rd_max;
2628 if (has_bps_wr_max) {
2629 cfg.buckets[THROTTLE_BPS_WRITE].max = bps_wr_max;
2631 if (has_iops_max) {
2632 cfg.buckets[THROTTLE_OPS_TOTAL].max = iops_max;
2634 if (has_iops_rd_max) {
2635 cfg.buckets[THROTTLE_OPS_READ].max = iops_rd_max;
2637 if (has_iops_wr_max) {
2638 cfg.buckets[THROTTLE_OPS_WRITE].max = iops_wr_max;
2641 if (has_iops_size) {
2642 cfg.op_size = iops_size;
2645 if (!check_throttle_config(&cfg, errp)) {
2646 goto out;
2649 if (throttle_enabled(&cfg)) {
2650 /* Enable I/O limits if they're not enabled yet, otherwise
2651 * just update the throttling group. */
2652 if (!bs->throttle_state) {
2653 bdrv_io_limits_enable(bs, has_group ? group : device);
2654 } else if (has_group) {
2655 bdrv_io_limits_update_group(bs, group);
2657 /* Set the new throttling configuration */
2658 bdrv_set_io_limits(bs, &cfg);
2659 } else if (bs->throttle_state) {
2660 /* If all throttling settings are set to 0, disable I/O limits */
2661 bdrv_io_limits_disable(bs);
2664 out:
2665 aio_context_release(aio_context);
2668 void qmp_block_dirty_bitmap_add(const char *node, const char *name,
2669 bool has_granularity, uint32_t granularity,
2670 Error **errp)
2672 AioContext *aio_context;
2673 BlockDriverState *bs;
2675 if (!name || name[0] == '\0') {
2676 error_setg(errp, "Bitmap name cannot be empty");
2677 return;
2680 bs = bdrv_lookup_bs(node, node, errp);
2681 if (!bs) {
2682 return;
2685 aio_context = bdrv_get_aio_context(bs);
2686 aio_context_acquire(aio_context);
2688 if (has_granularity) {
2689 if (granularity < 512 || !is_power_of_2(granularity)) {
2690 error_setg(errp, "Granularity must be power of 2 "
2691 "and at least 512");
2692 goto out;
2694 } else {
2695 /* Default to cluster size, if available: */
2696 granularity = bdrv_get_default_bitmap_granularity(bs);
2699 bdrv_create_dirty_bitmap(bs, granularity, name, errp);
2701 out:
2702 aio_context_release(aio_context);
2705 void qmp_block_dirty_bitmap_remove(const char *node, const char *name,
2706 Error **errp)
2708 AioContext *aio_context;
2709 BlockDriverState *bs;
2710 BdrvDirtyBitmap *bitmap;
2712 bitmap = block_dirty_bitmap_lookup(node, name, &bs, &aio_context, errp);
2713 if (!bitmap || !bs) {
2714 return;
2717 if (bdrv_dirty_bitmap_frozen(bitmap)) {
2718 error_setg(errp,
2719 "Bitmap '%s' is currently frozen and cannot be removed",
2720 name);
2721 goto out;
2723 bdrv_dirty_bitmap_make_anon(bitmap);
2724 bdrv_release_dirty_bitmap(bs, bitmap);
2726 out:
2727 aio_context_release(aio_context);
2731 * Completely clear a bitmap, for the purposes of synchronizing a bitmap
2732 * immediately after a full backup operation.
2734 void qmp_block_dirty_bitmap_clear(const char *node, const char *name,
2735 Error **errp)
2737 AioContext *aio_context;
2738 BdrvDirtyBitmap *bitmap;
2739 BlockDriverState *bs;
2741 bitmap = block_dirty_bitmap_lookup(node, name, &bs, &aio_context, errp);
2742 if (!bitmap || !bs) {
2743 return;
2746 if (bdrv_dirty_bitmap_frozen(bitmap)) {
2747 error_setg(errp,
2748 "Bitmap '%s' is currently frozen and cannot be modified",
2749 name);
2750 goto out;
2751 } else if (!bdrv_dirty_bitmap_enabled(bitmap)) {
2752 error_setg(errp,
2753 "Bitmap '%s' is currently disabled and cannot be cleared",
2754 name);
2755 goto out;
2758 bdrv_clear_dirty_bitmap(bitmap, NULL);
2760 out:
2761 aio_context_release(aio_context);
2764 void hmp_drive_del(Monitor *mon, const QDict *qdict)
2766 const char *id = qdict_get_str(qdict, "id");
2767 BlockBackend *blk;
2768 BlockDriverState *bs;
2769 AioContext *aio_context;
2770 Error *local_err = NULL;
2772 blk = blk_by_name(id);
2773 if (!blk) {
2774 error_report("Device '%s' not found", id);
2775 return;
2778 if (!blk_legacy_dinfo(blk)) {
2779 error_report("Deleting device added with blockdev-add"
2780 " is not supported");
2781 return;
2784 aio_context = blk_get_aio_context(blk);
2785 aio_context_acquire(aio_context);
2787 bs = blk_bs(blk);
2788 if (bs) {
2789 if (bdrv_op_is_blocked(bs, BLOCK_OP_TYPE_DRIVE_DEL, &local_err)) {
2790 error_report_err(local_err);
2791 aio_context_release(aio_context);
2792 return;
2795 bdrv_close(bs);
2798 /* if we have a device attached to this BlockDriverState
2799 * then we need to make the drive anonymous until the device
2800 * can be removed. If this is a drive with no device backing
2801 * then we can just get rid of the block driver state right here.
2803 if (blk_get_attached_dev(blk)) {
2804 blk_hide_on_behalf_of_hmp_drive_del(blk);
2805 /* Further I/O must not pause the guest */
2806 blk_set_on_error(blk, BLOCKDEV_ON_ERROR_REPORT,
2807 BLOCKDEV_ON_ERROR_REPORT);
2808 } else {
2809 blk_unref(blk);
2812 aio_context_release(aio_context);
2815 void qmp_block_resize(bool has_device, const char *device,
2816 bool has_node_name, const char *node_name,
2817 int64_t size, Error **errp)
2819 Error *local_err = NULL;
2820 BlockDriverState *bs;
2821 AioContext *aio_context;
2822 int ret;
2824 bs = bdrv_lookup_bs(has_device ? device : NULL,
2825 has_node_name ? node_name : NULL,
2826 &local_err);
2827 if (local_err) {
2828 error_propagate(errp, local_err);
2829 return;
2832 aio_context = bdrv_get_aio_context(bs);
2833 aio_context_acquire(aio_context);
2835 if (!bdrv_is_first_non_filter(bs)) {
2836 error_setg(errp, QERR_FEATURE_DISABLED, "resize");
2837 goto out;
2840 if (size < 0) {
2841 error_setg(errp, QERR_INVALID_PARAMETER_VALUE, "size", "a >0 size");
2842 goto out;
2845 if (bdrv_op_is_blocked(bs, BLOCK_OP_TYPE_RESIZE, NULL)) {
2846 error_setg(errp, QERR_DEVICE_IN_USE, device);
2847 goto out;
2850 /* complete all in-flight operations before resizing the device */
2851 bdrv_drain_all();
2853 ret = bdrv_truncate(bs, size);
2854 switch (ret) {
2855 case 0:
2856 break;
2857 case -ENOMEDIUM:
2858 error_setg(errp, QERR_DEVICE_HAS_NO_MEDIUM, device);
2859 break;
2860 case -ENOTSUP:
2861 error_setg(errp, QERR_UNSUPPORTED);
2862 break;
2863 case -EACCES:
2864 error_setg(errp, "Device '%s' is read only", device);
2865 break;
2866 case -EBUSY:
2867 error_setg(errp, QERR_DEVICE_IN_USE, device);
2868 break;
2869 default:
2870 error_setg_errno(errp, -ret, "Could not resize");
2871 break;
2874 out:
2875 aio_context_release(aio_context);
2878 static void block_job_cb(void *opaque, int ret)
2880 /* Note that this function may be executed from another AioContext besides
2881 * the QEMU main loop. If you need to access anything that assumes the
2882 * QEMU global mutex, use a BH or introduce a mutex.
2885 BlockDriverState *bs = opaque;
2886 const char *msg = NULL;
2888 trace_block_job_cb(bs, bs->job, ret);
2890 assert(bs->job);
2892 if (ret < 0) {
2893 msg = strerror(-ret);
2896 if (block_job_is_cancelled(bs->job)) {
2897 block_job_event_cancelled(bs->job);
2898 } else {
2899 block_job_event_completed(bs->job, msg);
2903 void qmp_block_stream(const char *device,
2904 bool has_base, const char *base,
2905 bool has_backing_file, const char *backing_file,
2906 bool has_speed, int64_t speed,
2907 bool has_on_error, BlockdevOnError on_error,
2908 Error **errp)
2910 BlockBackend *blk;
2911 BlockDriverState *bs;
2912 BlockDriverState *base_bs = NULL;
2913 AioContext *aio_context;
2914 Error *local_err = NULL;
2915 const char *base_name = NULL;
2917 if (!has_on_error) {
2918 on_error = BLOCKDEV_ON_ERROR_REPORT;
2921 blk = blk_by_name(device);
2922 if (!blk) {
2923 error_set(errp, ERROR_CLASS_DEVICE_NOT_FOUND,
2924 "Device '%s' not found", device);
2925 return;
2928 aio_context = blk_get_aio_context(blk);
2929 aio_context_acquire(aio_context);
2931 if (!blk_is_available(blk)) {
2932 error_setg(errp, "Device '%s' has no medium", device);
2933 goto out;
2935 bs = blk_bs(blk);
2937 if (bdrv_op_is_blocked(bs, BLOCK_OP_TYPE_STREAM, errp)) {
2938 goto out;
2941 if (has_base) {
2942 base_bs = bdrv_find_backing_image(bs, base);
2943 if (base_bs == NULL) {
2944 error_setg(errp, QERR_BASE_NOT_FOUND, base);
2945 goto out;
2947 assert(bdrv_get_aio_context(base_bs) == aio_context);
2948 base_name = base;
2951 /* if we are streaming the entire chain, the result will have no backing
2952 * file, and specifying one is therefore an error */
2953 if (base_bs == NULL && has_backing_file) {
2954 error_setg(errp, "backing file specified, but streaming the "
2955 "entire chain");
2956 goto out;
2959 /* backing_file string overrides base bs filename */
2960 base_name = has_backing_file ? backing_file : base_name;
2962 stream_start(bs, base_bs, base_name, has_speed ? speed : 0,
2963 on_error, block_job_cb, bs, &local_err);
2964 if (local_err) {
2965 error_propagate(errp, local_err);
2966 goto out;
2969 trace_qmp_block_stream(bs, bs->job);
2971 out:
2972 aio_context_release(aio_context);
2975 void qmp_block_commit(const char *device,
2976 bool has_base, const char *base,
2977 bool has_top, const char *top,
2978 bool has_backing_file, const char *backing_file,
2979 bool has_speed, int64_t speed,
2980 Error **errp)
2982 BlockBackend *blk;
2983 BlockDriverState *bs;
2984 BlockDriverState *base_bs, *top_bs;
2985 AioContext *aio_context;
2986 Error *local_err = NULL;
2987 /* This will be part of the QMP command, if/when the
2988 * BlockdevOnError change for blkmirror makes it in
2990 BlockdevOnError on_error = BLOCKDEV_ON_ERROR_REPORT;
2992 if (!has_speed) {
2993 speed = 0;
2996 /* Important Note:
2997 * libvirt relies on the DeviceNotFound error class in order to probe for
2998 * live commit feature versions; for this to work, we must make sure to
2999 * perform the device lookup before any generic errors that may occur in a
3000 * scenario in which all optional arguments are omitted. */
3001 blk = blk_by_name(device);
3002 if (!blk) {
3003 error_set(errp, ERROR_CLASS_DEVICE_NOT_FOUND,
3004 "Device '%s' not found", device);
3005 return;
3008 aio_context = blk_get_aio_context(blk);
3009 aio_context_acquire(aio_context);
3011 if (!blk_is_available(blk)) {
3012 error_setg(errp, "Device '%s' has no medium", device);
3013 goto out;
3015 bs = blk_bs(blk);
3017 if (bdrv_op_is_blocked(bs, BLOCK_OP_TYPE_COMMIT_SOURCE, errp)) {
3018 goto out;
3021 /* default top_bs is the active layer */
3022 top_bs = bs;
3024 if (has_top && top) {
3025 if (strcmp(bs->filename, top) != 0) {
3026 top_bs = bdrv_find_backing_image(bs, top);
3030 if (top_bs == NULL) {
3031 error_setg(errp, "Top image file %s not found", top ? top : "NULL");
3032 goto out;
3035 assert(bdrv_get_aio_context(top_bs) == aio_context);
3037 if (has_base && base) {
3038 base_bs = bdrv_find_backing_image(top_bs, base);
3039 } else {
3040 base_bs = bdrv_find_base(top_bs);
3043 if (base_bs == NULL) {
3044 error_setg(errp, QERR_BASE_NOT_FOUND, base ? base : "NULL");
3045 goto out;
3048 assert(bdrv_get_aio_context(base_bs) == aio_context);
3050 if (bdrv_op_is_blocked(base_bs, BLOCK_OP_TYPE_COMMIT_TARGET, errp)) {
3051 goto out;
3054 /* Do not allow attempts to commit an image into itself */
3055 if (top_bs == base_bs) {
3056 error_setg(errp, "cannot commit an image into itself");
3057 goto out;
3060 if (top_bs == bs) {
3061 if (has_backing_file) {
3062 error_setg(errp, "'backing-file' specified,"
3063 " but 'top' is the active layer");
3064 goto out;
3066 commit_active_start(bs, base_bs, speed, on_error, block_job_cb,
3067 bs, &local_err);
3068 } else {
3069 commit_start(bs, base_bs, top_bs, speed, on_error, block_job_cb, bs,
3070 has_backing_file ? backing_file : NULL, &local_err);
3072 if (local_err != NULL) {
3073 error_propagate(errp, local_err);
3074 goto out;
3077 out:
3078 aio_context_release(aio_context);
3081 static void do_drive_backup(const char *device, const char *target,
3082 bool has_format, const char *format,
3083 enum MirrorSyncMode sync,
3084 bool has_mode, enum NewImageMode mode,
3085 bool has_speed, int64_t speed,
3086 bool has_bitmap, const char *bitmap,
3087 bool has_on_source_error,
3088 BlockdevOnError on_source_error,
3089 bool has_on_target_error,
3090 BlockdevOnError on_target_error,
3091 BlockJobTxn *txn, Error **errp)
3093 BlockBackend *blk;
3094 BlockDriverState *bs;
3095 BlockDriverState *target_bs;
3096 BlockDriverState *source = NULL;
3097 BdrvDirtyBitmap *bmap = NULL;
3098 AioContext *aio_context;
3099 QDict *options = NULL;
3100 Error *local_err = NULL;
3101 int flags;
3102 int64_t size;
3103 int ret;
3105 if (!has_speed) {
3106 speed = 0;
3108 if (!has_on_source_error) {
3109 on_source_error = BLOCKDEV_ON_ERROR_REPORT;
3111 if (!has_on_target_error) {
3112 on_target_error = BLOCKDEV_ON_ERROR_REPORT;
3114 if (!has_mode) {
3115 mode = NEW_IMAGE_MODE_ABSOLUTE_PATHS;
3118 blk = blk_by_name(device);
3119 if (!blk) {
3120 error_set(errp, ERROR_CLASS_DEVICE_NOT_FOUND,
3121 "Device '%s' not found", device);
3122 return;
3125 aio_context = blk_get_aio_context(blk);
3126 aio_context_acquire(aio_context);
3128 /* Although backup_run has this check too, we need to use bs->drv below, so
3129 * do an early check redundantly. */
3130 if (!blk_is_available(blk)) {
3131 error_setg(errp, QERR_DEVICE_HAS_NO_MEDIUM, device);
3132 goto out;
3134 bs = blk_bs(blk);
3136 if (!has_format) {
3137 format = mode == NEW_IMAGE_MODE_EXISTING ? NULL : bs->drv->format_name;
3140 /* Early check to avoid creating target */
3141 if (bdrv_op_is_blocked(bs, BLOCK_OP_TYPE_BACKUP_SOURCE, errp)) {
3142 goto out;
3145 flags = bs->open_flags | BDRV_O_RDWR;
3147 /* See if we have a backing HD we can use to create our new image
3148 * on top of. */
3149 if (sync == MIRROR_SYNC_MODE_TOP) {
3150 source = backing_bs(bs);
3151 if (!source) {
3152 sync = MIRROR_SYNC_MODE_FULL;
3155 if (sync == MIRROR_SYNC_MODE_NONE) {
3156 source = bs;
3159 size = bdrv_getlength(bs);
3160 if (size < 0) {
3161 error_setg_errno(errp, -size, "bdrv_getlength failed");
3162 goto out;
3165 if (mode != NEW_IMAGE_MODE_EXISTING) {
3166 assert(format);
3167 if (source) {
3168 bdrv_img_create(target, format, source->filename,
3169 source->drv->format_name, NULL,
3170 size, flags, &local_err, false);
3171 } else {
3172 bdrv_img_create(target, format, NULL, NULL, NULL,
3173 size, flags, &local_err, false);
3177 if (local_err) {
3178 error_propagate(errp, local_err);
3179 goto out;
3182 if (format) {
3183 options = qdict_new();
3184 qdict_put(options, "driver", qstring_from_str(format));
3187 target_bs = NULL;
3188 ret = bdrv_open(&target_bs, target, NULL, options, flags, &local_err);
3189 if (ret < 0) {
3190 error_propagate(errp, local_err);
3191 goto out;
3194 bdrv_set_aio_context(target_bs, aio_context);
3196 if (has_bitmap) {
3197 bmap = bdrv_find_dirty_bitmap(bs, bitmap);
3198 if (!bmap) {
3199 error_setg(errp, "Bitmap '%s' could not be found", bitmap);
3200 bdrv_unref(target_bs);
3201 goto out;
3205 backup_start(bs, target_bs, speed, sync, bmap,
3206 on_source_error, on_target_error,
3207 block_job_cb, bs, txn, &local_err);
3208 if (local_err != NULL) {
3209 bdrv_unref(target_bs);
3210 error_propagate(errp, local_err);
3211 goto out;
3214 out:
3215 aio_context_release(aio_context);
3218 void qmp_drive_backup(const char *device, const char *target,
3219 bool has_format, const char *format,
3220 enum MirrorSyncMode sync,
3221 bool has_mode, enum NewImageMode mode,
3222 bool has_speed, int64_t speed,
3223 bool has_bitmap, const char *bitmap,
3224 bool has_on_source_error, BlockdevOnError on_source_error,
3225 bool has_on_target_error, BlockdevOnError on_target_error,
3226 Error **errp)
3228 return do_drive_backup(device, target, has_format, format, sync,
3229 has_mode, mode, has_speed, speed,
3230 has_bitmap, bitmap,
3231 has_on_source_error, on_source_error,
3232 has_on_target_error, on_target_error,
3233 NULL, errp);
3236 BlockDeviceInfoList *qmp_query_named_block_nodes(Error **errp)
3238 return bdrv_named_nodes_list(errp);
3241 void do_blockdev_backup(const char *device, const char *target,
3242 enum MirrorSyncMode sync,
3243 bool has_speed, int64_t speed,
3244 bool has_on_source_error,
3245 BlockdevOnError on_source_error,
3246 bool has_on_target_error,
3247 BlockdevOnError on_target_error,
3248 BlockJobTxn *txn, Error **errp)
3250 BlockBackend *blk, *target_blk;
3251 BlockDriverState *bs;
3252 BlockDriverState *target_bs;
3253 Error *local_err = NULL;
3254 AioContext *aio_context;
3256 if (!has_speed) {
3257 speed = 0;
3259 if (!has_on_source_error) {
3260 on_source_error = BLOCKDEV_ON_ERROR_REPORT;
3262 if (!has_on_target_error) {
3263 on_target_error = BLOCKDEV_ON_ERROR_REPORT;
3266 blk = blk_by_name(device);
3267 if (!blk) {
3268 error_setg(errp, "Device '%s' not found", device);
3269 return;
3272 aio_context = blk_get_aio_context(blk);
3273 aio_context_acquire(aio_context);
3275 if (!blk_is_available(blk)) {
3276 error_setg(errp, "Device '%s' has no medium", device);
3277 goto out;
3279 bs = blk_bs(blk);
3281 target_blk = blk_by_name(target);
3282 if (!target_blk) {
3283 error_setg(errp, "Device '%s' not found", target);
3284 goto out;
3287 if (!blk_is_available(target_blk)) {
3288 error_setg(errp, "Device '%s' has no medium", target);
3289 goto out;
3291 target_bs = blk_bs(target_blk);
3293 bdrv_ref(target_bs);
3294 bdrv_set_aio_context(target_bs, aio_context);
3295 backup_start(bs, target_bs, speed, sync, NULL, on_source_error,
3296 on_target_error, block_job_cb, bs, txn, &local_err);
3297 if (local_err != NULL) {
3298 bdrv_unref(target_bs);
3299 error_propagate(errp, local_err);
3301 out:
3302 aio_context_release(aio_context);
3305 void qmp_blockdev_backup(const char *device, const char *target,
3306 enum MirrorSyncMode sync,
3307 bool has_speed, int64_t speed,
3308 bool has_on_source_error,
3309 BlockdevOnError on_source_error,
3310 bool has_on_target_error,
3311 BlockdevOnError on_target_error,
3312 Error **errp)
3314 do_blockdev_backup(device, target, sync, has_speed, speed,
3315 has_on_source_error, on_source_error,
3316 has_on_target_error, on_target_error,
3317 NULL, errp);
3320 /* Parameter check and block job starting for drive mirroring.
3321 * Caller should hold @device and @target's aio context (must be the same).
3323 static void blockdev_mirror_common(BlockDriverState *bs,
3324 BlockDriverState *target,
3325 bool has_replaces, const char *replaces,
3326 enum MirrorSyncMode sync,
3327 bool has_speed, int64_t speed,
3328 bool has_granularity, uint32_t granularity,
3329 bool has_buf_size, int64_t buf_size,
3330 bool has_on_source_error,
3331 BlockdevOnError on_source_error,
3332 bool has_on_target_error,
3333 BlockdevOnError on_target_error,
3334 bool has_unmap, bool unmap,
3335 Error **errp)
3338 if (!has_speed) {
3339 speed = 0;
3341 if (!has_on_source_error) {
3342 on_source_error = BLOCKDEV_ON_ERROR_REPORT;
3344 if (!has_on_target_error) {
3345 on_target_error = BLOCKDEV_ON_ERROR_REPORT;
3347 if (!has_granularity) {
3348 granularity = 0;
3350 if (!has_buf_size) {
3351 buf_size = 0;
3353 if (!has_unmap) {
3354 unmap = true;
3357 if (granularity != 0 && (granularity < 512 || granularity > 1048576 * 64)) {
3358 error_setg(errp, QERR_INVALID_PARAMETER_VALUE, "granularity",
3359 "a value in range [512B, 64MB]");
3360 return;
3362 if (granularity & (granularity - 1)) {
3363 error_setg(errp, QERR_INVALID_PARAMETER_VALUE, "granularity",
3364 "power of 2");
3365 return;
3368 if (bdrv_op_is_blocked(bs, BLOCK_OP_TYPE_MIRROR_SOURCE, errp)) {
3369 return;
3371 if (bdrv_op_is_blocked(target, BLOCK_OP_TYPE_MIRROR_TARGET, errp)) {
3372 return;
3374 if (target->blk) {
3375 error_setg(errp, "Cannot mirror to an attached block device");
3376 return;
3379 if (!bs->backing && sync == MIRROR_SYNC_MODE_TOP) {
3380 sync = MIRROR_SYNC_MODE_FULL;
3383 /* pass the node name to replace to mirror start since it's loose coupling
3384 * and will allow to check whether the node still exist at mirror completion
3386 mirror_start(bs, target,
3387 has_replaces ? replaces : NULL,
3388 speed, granularity, buf_size, sync,
3389 on_source_error, on_target_error, unmap,
3390 block_job_cb, bs, errp);
3393 void qmp_drive_mirror(const char *device, const char *target,
3394 bool has_format, const char *format,
3395 bool has_node_name, const char *node_name,
3396 bool has_replaces, const char *replaces,
3397 enum MirrorSyncMode sync,
3398 bool has_mode, enum NewImageMode mode,
3399 bool has_speed, int64_t speed,
3400 bool has_granularity, uint32_t granularity,
3401 bool has_buf_size, int64_t buf_size,
3402 bool has_on_source_error, BlockdevOnError on_source_error,
3403 bool has_on_target_error, BlockdevOnError on_target_error,
3404 bool has_unmap, bool unmap,
3405 Error **errp)
3407 BlockDriverState *bs;
3408 BlockBackend *blk;
3409 BlockDriverState *source, *target_bs;
3410 AioContext *aio_context;
3411 Error *local_err = NULL;
3412 QDict *options = NULL;
3413 int flags;
3414 int64_t size;
3415 int ret;
3417 blk = blk_by_name(device);
3418 if (!blk) {
3419 error_set(errp, ERROR_CLASS_DEVICE_NOT_FOUND,
3420 "Device '%s' not found", device);
3421 return;
3424 aio_context = blk_get_aio_context(blk);
3425 aio_context_acquire(aio_context);
3427 if (!blk_is_available(blk)) {
3428 error_setg(errp, QERR_DEVICE_HAS_NO_MEDIUM, device);
3429 goto out;
3431 bs = blk_bs(blk);
3432 if (!has_mode) {
3433 mode = NEW_IMAGE_MODE_ABSOLUTE_PATHS;
3436 if (!has_format) {
3437 format = mode == NEW_IMAGE_MODE_EXISTING ? NULL : bs->drv->format_name;
3440 flags = bs->open_flags | BDRV_O_RDWR;
3441 source = backing_bs(bs);
3442 if (!source && sync == MIRROR_SYNC_MODE_TOP) {
3443 sync = MIRROR_SYNC_MODE_FULL;
3445 if (sync == MIRROR_SYNC_MODE_NONE) {
3446 source = bs;
3449 size = bdrv_getlength(bs);
3450 if (size < 0) {
3451 error_setg_errno(errp, -size, "bdrv_getlength failed");
3452 goto out;
3455 if (has_replaces) {
3456 BlockDriverState *to_replace_bs;
3457 AioContext *replace_aio_context;
3458 int64_t replace_size;
3460 if (!has_node_name) {
3461 error_setg(errp, "a node-name must be provided when replacing a"
3462 " named node of the graph");
3463 goto out;
3466 to_replace_bs = check_to_replace_node(bs, replaces, &local_err);
3468 if (!to_replace_bs) {
3469 error_propagate(errp, local_err);
3470 goto out;
3473 replace_aio_context = bdrv_get_aio_context(to_replace_bs);
3474 aio_context_acquire(replace_aio_context);
3475 replace_size = bdrv_getlength(to_replace_bs);
3476 aio_context_release(replace_aio_context);
3478 if (size != replace_size) {
3479 error_setg(errp, "cannot replace image with a mirror image of "
3480 "different size");
3481 goto out;
3485 if ((sync == MIRROR_SYNC_MODE_FULL || !source)
3486 && mode != NEW_IMAGE_MODE_EXISTING)
3488 /* create new image w/o backing file */
3489 assert(format);
3490 bdrv_img_create(target, format,
3491 NULL, NULL, NULL, size, flags, &local_err, false);
3492 } else {
3493 switch (mode) {
3494 case NEW_IMAGE_MODE_EXISTING:
3495 break;
3496 case NEW_IMAGE_MODE_ABSOLUTE_PATHS:
3497 /* create new image with backing file */
3498 bdrv_img_create(target, format,
3499 source->filename,
3500 source->drv->format_name,
3501 NULL, size, flags, &local_err, false);
3502 break;
3503 default:
3504 abort();
3508 if (local_err) {
3509 error_propagate(errp, local_err);
3510 goto out;
3513 options = qdict_new();
3514 if (has_node_name) {
3515 qdict_put(options, "node-name", qstring_from_str(node_name));
3517 if (format) {
3518 qdict_put(options, "driver", qstring_from_str(format));
3521 /* Mirroring takes care of copy-on-write using the source's backing
3522 * file.
3524 target_bs = NULL;
3525 ret = bdrv_open(&target_bs, target, NULL, options,
3526 flags | BDRV_O_NO_BACKING, &local_err);
3527 if (ret < 0) {
3528 error_propagate(errp, local_err);
3529 goto out;
3532 bdrv_set_aio_context(target_bs, aio_context);
3534 blockdev_mirror_common(bs, target_bs,
3535 has_replaces, replaces, sync,
3536 has_speed, speed,
3537 has_granularity, granularity,
3538 has_buf_size, buf_size,
3539 has_on_source_error, on_source_error,
3540 has_on_target_error, on_target_error,
3541 has_unmap, unmap,
3542 &local_err);
3543 if (local_err) {
3544 error_propagate(errp, local_err);
3545 bdrv_unref(target_bs);
3547 out:
3548 aio_context_release(aio_context);
3551 void qmp_blockdev_mirror(const char *device, const char *target,
3552 bool has_replaces, const char *replaces,
3553 MirrorSyncMode sync,
3554 bool has_speed, int64_t speed,
3555 bool has_granularity, uint32_t granularity,
3556 bool has_buf_size, int64_t buf_size,
3557 bool has_on_source_error,
3558 BlockdevOnError on_source_error,
3559 bool has_on_target_error,
3560 BlockdevOnError on_target_error,
3561 Error **errp)
3563 BlockDriverState *bs;
3564 BlockBackend *blk;
3565 BlockDriverState *target_bs;
3566 AioContext *aio_context;
3567 Error *local_err = NULL;
3569 blk = blk_by_name(device);
3570 if (!blk) {
3571 error_setg(errp, "Device '%s' not found", device);
3572 return;
3574 bs = blk_bs(blk);
3576 if (!bs) {
3577 error_setg(errp, "Device '%s' has no media", device);
3578 return;
3581 target_bs = bdrv_lookup_bs(target, target, errp);
3582 if (!target_bs) {
3583 return;
3586 aio_context = bdrv_get_aio_context(bs);
3587 aio_context_acquire(aio_context);
3589 bdrv_ref(target_bs);
3590 bdrv_set_aio_context(target_bs, aio_context);
3592 blockdev_mirror_common(bs, target_bs,
3593 has_replaces, replaces, sync,
3594 has_speed, speed,
3595 has_granularity, granularity,
3596 has_buf_size, buf_size,
3597 has_on_source_error, on_source_error,
3598 has_on_target_error, on_target_error,
3599 true, true,
3600 &local_err);
3601 if (local_err) {
3602 error_propagate(errp, local_err);
3603 bdrv_unref(target_bs);
3606 aio_context_release(aio_context);
3609 /* Get the block job for a given device name and acquire its AioContext */
3610 static BlockJob *find_block_job(const char *device, AioContext **aio_context,
3611 Error **errp)
3613 BlockBackend *blk;
3614 BlockDriverState *bs;
3616 *aio_context = NULL;
3618 blk = blk_by_name(device);
3619 if (!blk) {
3620 goto notfound;
3623 *aio_context = blk_get_aio_context(blk);
3624 aio_context_acquire(*aio_context);
3626 if (!blk_is_available(blk)) {
3627 goto notfound;
3629 bs = blk_bs(blk);
3631 if (!bs->job) {
3632 goto notfound;
3635 return bs->job;
3637 notfound:
3638 error_set(errp, ERROR_CLASS_DEVICE_NOT_ACTIVE,
3639 "No active block job on device '%s'", device);
3640 if (*aio_context) {
3641 aio_context_release(*aio_context);
3642 *aio_context = NULL;
3644 return NULL;
3647 void qmp_block_job_set_speed(const char *device, int64_t speed, Error **errp)
3649 AioContext *aio_context;
3650 BlockJob *job = find_block_job(device, &aio_context, errp);
3652 if (!job) {
3653 return;
3656 block_job_set_speed(job, speed, errp);
3657 aio_context_release(aio_context);
3660 void qmp_block_job_cancel(const char *device,
3661 bool has_force, bool force, Error **errp)
3663 AioContext *aio_context;
3664 BlockJob *job = find_block_job(device, &aio_context, errp);
3666 if (!job) {
3667 return;
3670 if (!has_force) {
3671 force = false;
3674 if (job->user_paused && !force) {
3675 error_setg(errp, "The block job for device '%s' is currently paused",
3676 device);
3677 goto out;
3680 trace_qmp_block_job_cancel(job);
3681 block_job_cancel(job);
3682 out:
3683 aio_context_release(aio_context);
3686 void qmp_block_job_pause(const char *device, Error **errp)
3688 AioContext *aio_context;
3689 BlockJob *job = find_block_job(device, &aio_context, errp);
3691 if (!job || job->user_paused) {
3692 return;
3695 job->user_paused = true;
3696 trace_qmp_block_job_pause(job);
3697 block_job_pause(job);
3698 aio_context_release(aio_context);
3701 void qmp_block_job_resume(const char *device, Error **errp)
3703 AioContext *aio_context;
3704 BlockJob *job = find_block_job(device, &aio_context, errp);
3706 if (!job || !job->user_paused) {
3707 return;
3710 job->user_paused = false;
3711 trace_qmp_block_job_resume(job);
3712 block_job_resume(job);
3713 aio_context_release(aio_context);
3716 void qmp_block_job_complete(const char *device, Error **errp)
3718 AioContext *aio_context;
3719 BlockJob *job = find_block_job(device, &aio_context, errp);
3721 if (!job) {
3722 return;
3725 trace_qmp_block_job_complete(job);
3726 block_job_complete(job, errp);
3727 aio_context_release(aio_context);
3730 void qmp_change_backing_file(const char *device,
3731 const char *image_node_name,
3732 const char *backing_file,
3733 Error **errp)
3735 BlockBackend *blk;
3736 BlockDriverState *bs = NULL;
3737 AioContext *aio_context;
3738 BlockDriverState *image_bs = NULL;
3739 Error *local_err = NULL;
3740 bool ro;
3741 int open_flags;
3742 int ret;
3744 blk = blk_by_name(device);
3745 if (!blk) {
3746 error_set(errp, ERROR_CLASS_DEVICE_NOT_FOUND,
3747 "Device '%s' not found", device);
3748 return;
3751 aio_context = blk_get_aio_context(blk);
3752 aio_context_acquire(aio_context);
3754 if (!blk_is_available(blk)) {
3755 error_setg(errp, "Device '%s' has no medium", device);
3756 goto out;
3758 bs = blk_bs(blk);
3760 image_bs = bdrv_lookup_bs(NULL, image_node_name, &local_err);
3761 if (local_err) {
3762 error_propagate(errp, local_err);
3763 goto out;
3766 if (!image_bs) {
3767 error_setg(errp, "image file not found");
3768 goto out;
3771 if (bdrv_find_base(image_bs) == image_bs) {
3772 error_setg(errp, "not allowing backing file change on an image "
3773 "without a backing file");
3774 goto out;
3777 /* even though we are not necessarily operating on bs, we need it to
3778 * determine if block ops are currently prohibited on the chain */
3779 if (bdrv_op_is_blocked(bs, BLOCK_OP_TYPE_CHANGE, errp)) {
3780 goto out;
3783 /* final sanity check */
3784 if (!bdrv_chain_contains(bs, image_bs)) {
3785 error_setg(errp, "'%s' and image file are not in the same chain",
3786 device);
3787 goto out;
3790 /* if not r/w, reopen to make r/w */
3791 open_flags = image_bs->open_flags;
3792 ro = bdrv_is_read_only(image_bs);
3794 if (ro) {
3795 bdrv_reopen(image_bs, open_flags | BDRV_O_RDWR, &local_err);
3796 if (local_err) {
3797 error_propagate(errp, local_err);
3798 goto out;
3802 ret = bdrv_change_backing_file(image_bs, backing_file,
3803 image_bs->drv ? image_bs->drv->format_name : "");
3805 if (ret < 0) {
3806 error_setg_errno(errp, -ret, "Could not change backing file to '%s'",
3807 backing_file);
3808 /* don't exit here, so we can try to restore open flags if
3809 * appropriate */
3812 if (ro) {
3813 bdrv_reopen(image_bs, open_flags, &local_err);
3814 if (local_err) {
3815 error_propagate(errp, local_err); /* will preserve prior errp */
3819 out:
3820 aio_context_release(aio_context);
3823 void qmp_blockdev_add(BlockdevOptions *options, Error **errp)
3825 QmpOutputVisitor *ov = qmp_output_visitor_new();
3826 BlockDriverState *bs;
3827 BlockBackend *blk = NULL;
3828 QObject *obj;
3829 QDict *qdict;
3830 Error *local_err = NULL;
3832 /* TODO Sort it out in raw-posix and drive_new(): Reject aio=native with
3833 * cache.direct=false instead of silently switching to aio=threads, except
3834 * when called from drive_new().
3836 * For now, simply forbidding the combination for all drivers will do. */
3837 if (options->has_aio && options->aio == BLOCKDEV_AIO_OPTIONS_NATIVE) {
3838 bool direct = options->has_cache &&
3839 options->cache->has_direct &&
3840 options->cache->direct;
3841 if (!direct) {
3842 error_setg(errp, "aio=native requires cache.direct=true");
3843 goto fail;
3847 visit_type_BlockdevOptions(qmp_output_get_visitor(ov),
3848 &options, NULL, &local_err);
3849 if (local_err) {
3850 error_propagate(errp, local_err);
3851 goto fail;
3854 obj = qmp_output_get_qobject(ov);
3855 qdict = qobject_to_qdict(obj);
3857 qdict_flatten(qdict);
3859 if (options->has_id) {
3860 blk = blockdev_init(NULL, qdict, &local_err);
3861 if (local_err) {
3862 error_propagate(errp, local_err);
3863 goto fail;
3866 bs = blk_bs(blk);
3867 } else {
3868 if (!qdict_get_try_str(qdict, "node-name")) {
3869 error_setg(errp, "'id' and/or 'node-name' need to be specified for "
3870 "the root node");
3871 goto fail;
3874 bs = bds_tree_init(qdict, errp);
3875 if (!bs) {
3876 goto fail;
3880 if (bs && bdrv_key_required(bs)) {
3881 if (blk) {
3882 blk_unref(blk);
3883 } else {
3884 bdrv_unref(bs);
3886 error_setg(errp, "blockdev-add doesn't support encrypted devices");
3887 goto fail;
3890 fail:
3891 qmp_output_visitor_cleanup(ov);
3894 void qmp_x_blockdev_del(bool has_id, const char *id,
3895 bool has_node_name, const char *node_name, Error **errp)
3897 AioContext *aio_context;
3898 BlockBackend *blk;
3899 BlockDriverState *bs;
3901 if (has_id && has_node_name) {
3902 error_setg(errp, "Only one of id and node-name must be specified");
3903 return;
3904 } else if (!has_id && !has_node_name) {
3905 error_setg(errp, "No block device specified");
3906 return;
3909 if (has_id) {
3910 blk = blk_by_name(id);
3911 if (!blk) {
3912 error_setg(errp, "Cannot find block backend %s", id);
3913 return;
3915 if (blk_get_refcnt(blk) > 1) {
3916 error_setg(errp, "Block backend %s is in use", id);
3917 return;
3919 bs = blk_bs(blk);
3920 aio_context = blk_get_aio_context(blk);
3921 } else {
3922 bs = bdrv_find_node(node_name);
3923 if (!bs) {
3924 error_setg(errp, "Cannot find node %s", node_name);
3925 return;
3927 blk = bs->blk;
3928 if (blk) {
3929 error_setg(errp, "Node %s is in use by %s",
3930 node_name, blk_name(blk));
3931 return;
3933 aio_context = bdrv_get_aio_context(bs);
3936 aio_context_acquire(aio_context);
3938 if (bs) {
3939 if (bdrv_op_is_blocked(bs, BLOCK_OP_TYPE_DRIVE_DEL, errp)) {
3940 goto out;
3943 if (bs->refcnt > 1 || !QLIST_EMPTY(&bs->parents)) {
3944 error_setg(errp, "Block device %s is in use",
3945 bdrv_get_device_or_node_name(bs));
3946 goto out;
3950 if (blk) {
3951 blk_unref(blk);
3952 } else {
3953 bdrv_unref(bs);
3956 out:
3957 aio_context_release(aio_context);
3960 BlockJobInfoList *qmp_query_block_jobs(Error **errp)
3962 BlockJobInfoList *head = NULL, **p_next = &head;
3963 BlockDriverState *bs;
3965 for (bs = bdrv_next(NULL); bs; bs = bdrv_next(bs)) {
3966 AioContext *aio_context = bdrv_get_aio_context(bs);
3968 aio_context_acquire(aio_context);
3970 if (bs->job) {
3971 BlockJobInfoList *elem = g_new0(BlockJobInfoList, 1);
3972 elem->value = block_job_query(bs->job);
3973 *p_next = elem;
3974 p_next = &elem->next;
3977 aio_context_release(aio_context);
3980 return head;
3983 QemuOptsList qemu_common_drive_opts = {
3984 .name = "drive",
3985 .head = QTAILQ_HEAD_INITIALIZER(qemu_common_drive_opts.head),
3986 .desc = {
3988 .name = "snapshot",
3989 .type = QEMU_OPT_BOOL,
3990 .help = "enable/disable snapshot mode",
3992 .name = "discard",
3993 .type = QEMU_OPT_STRING,
3994 .help = "discard operation (ignore/off, unmap/on)",
3996 .name = "aio",
3997 .type = QEMU_OPT_STRING,
3998 .help = "host AIO implementation (threads, native)",
4000 .name = "format",
4001 .type = QEMU_OPT_STRING,
4002 .help = "disk format (raw, qcow2, ...)",
4004 .name = "rerror",
4005 .type = QEMU_OPT_STRING,
4006 .help = "read error action",
4008 .name = "werror",
4009 .type = QEMU_OPT_STRING,
4010 .help = "write error action",
4012 .name = "read-only",
4013 .type = QEMU_OPT_BOOL,
4014 .help = "open drive file as read-only",
4016 .name = "throttling.iops-total",
4017 .type = QEMU_OPT_NUMBER,
4018 .help = "limit total I/O operations per second",
4020 .name = "throttling.iops-read",
4021 .type = QEMU_OPT_NUMBER,
4022 .help = "limit read operations per second",
4024 .name = "throttling.iops-write",
4025 .type = QEMU_OPT_NUMBER,
4026 .help = "limit write operations per second",
4028 .name = "throttling.bps-total",
4029 .type = QEMU_OPT_NUMBER,
4030 .help = "limit total bytes per second",
4032 .name = "throttling.bps-read",
4033 .type = QEMU_OPT_NUMBER,
4034 .help = "limit read bytes per second",
4036 .name = "throttling.bps-write",
4037 .type = QEMU_OPT_NUMBER,
4038 .help = "limit write bytes per second",
4040 .name = "throttling.iops-total-max",
4041 .type = QEMU_OPT_NUMBER,
4042 .help = "I/O operations burst",
4044 .name = "throttling.iops-read-max",
4045 .type = QEMU_OPT_NUMBER,
4046 .help = "I/O operations read burst",
4048 .name = "throttling.iops-write-max",
4049 .type = QEMU_OPT_NUMBER,
4050 .help = "I/O operations write burst",
4052 .name = "throttling.bps-total-max",
4053 .type = QEMU_OPT_NUMBER,
4054 .help = "total bytes burst",
4056 .name = "throttling.bps-read-max",
4057 .type = QEMU_OPT_NUMBER,
4058 .help = "total bytes read burst",
4060 .name = "throttling.bps-write-max",
4061 .type = QEMU_OPT_NUMBER,
4062 .help = "total bytes write burst",
4064 .name = "throttling.iops-size",
4065 .type = QEMU_OPT_NUMBER,
4066 .help = "when limiting by iops max size of an I/O in bytes",
4068 .name = "throttling.group",
4069 .type = QEMU_OPT_STRING,
4070 .help = "name of the block throttling group",
4072 .name = "copy-on-read",
4073 .type = QEMU_OPT_BOOL,
4074 .help = "copy read data from backing file into image file",
4076 .name = "detect-zeroes",
4077 .type = QEMU_OPT_STRING,
4078 .help = "try to optimize zero writes (off, on, unmap)",
4080 .name = "stats-account-invalid",
4081 .type = QEMU_OPT_BOOL,
4082 .help = "whether to account for invalid I/O operations "
4083 "in the statistics",
4085 .name = "stats-account-failed",
4086 .type = QEMU_OPT_BOOL,
4087 .help = "whether to account for failed I/O operations "
4088 "in the statistics",
4090 { /* end of list */ }
4094 static QemuOptsList qemu_root_bds_opts = {
4095 .name = "root-bds",
4096 .head = QTAILQ_HEAD_INITIALIZER(qemu_common_drive_opts.head),
4097 .desc = {
4099 .name = "discard",
4100 .type = QEMU_OPT_STRING,
4101 .help = "discard operation (ignore/off, unmap/on)",
4103 .name = "aio",
4104 .type = QEMU_OPT_STRING,
4105 .help = "host AIO implementation (threads, native)",
4107 .name = "read-only",
4108 .type = QEMU_OPT_BOOL,
4109 .help = "open drive file as read-only",
4111 .name = "copy-on-read",
4112 .type = QEMU_OPT_BOOL,
4113 .help = "copy read data from backing file into image file",
4115 .name = "detect-zeroes",
4116 .type = QEMU_OPT_STRING,
4117 .help = "try to optimize zero writes (off, on, unmap)",
4119 { /* end of list */ }
4123 QemuOptsList qemu_drive_opts = {
4124 .name = "drive",
4125 .head = QTAILQ_HEAD_INITIALIZER(qemu_drive_opts.head),
4126 .desc = {
4128 * no elements => accept any params
4129 * validation will happen later
4131 { /* end of list */ }