backup: Extract dirty bitmap handling as a separate function
[qemu.git] / blockdev.c
blob209dbd51cacc466c63b67e7d7520700b77cb7639
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 void bdrv_put_ref_bh(void *opaque)
288 BDRVPutRefBH *s = opaque;
290 bdrv_unref(s->bs);
291 qemu_bh_delete(s->bh);
292 g_free(s);
296 * Release a BDS reference in a BH
298 * It is not safe to use bdrv_unref() from a callback function when the callers
299 * still need the BlockDriverState. In such cases we schedule a BH to release
300 * the reference.
302 static void bdrv_put_ref_bh_schedule(BlockDriverState *bs)
304 BDRVPutRefBH *s;
306 s = g_new(BDRVPutRefBH, 1);
307 s->bh = qemu_bh_new(bdrv_put_ref_bh, s);
308 s->bs = bs;
309 qemu_bh_schedule(s->bh);
312 static int parse_block_error_action(const char *buf, bool is_read, Error **errp)
314 if (!strcmp(buf, "ignore")) {
315 return BLOCKDEV_ON_ERROR_IGNORE;
316 } else if (!is_read && !strcmp(buf, "enospc")) {
317 return BLOCKDEV_ON_ERROR_ENOSPC;
318 } else if (!strcmp(buf, "stop")) {
319 return BLOCKDEV_ON_ERROR_STOP;
320 } else if (!strcmp(buf, "report")) {
321 return BLOCKDEV_ON_ERROR_REPORT;
322 } else {
323 error_setg(errp, "'%s' invalid %s error action",
324 buf, is_read ? "read" : "write");
325 return -1;
329 static bool check_throttle_config(ThrottleConfig *cfg, Error **errp)
331 if (throttle_conflicting(cfg)) {
332 error_setg(errp, "bps/iops/max total values and read/write values"
333 " cannot be used at the same time");
334 return false;
337 if (!throttle_is_valid(cfg)) {
338 error_setg(errp, "bps/iops/maxs values must be 0 or greater");
339 return false;
342 if (throttle_max_is_missing_limit(cfg)) {
343 error_setg(errp, "bps_max/iops_max require corresponding"
344 " bps/iops values");
345 return false;
348 return true;
351 typedef enum { MEDIA_DISK, MEDIA_CDROM } DriveMediaType;
353 /* All parameters but @opts are optional and may be set to NULL. */
354 static void extract_common_blockdev_options(QemuOpts *opts, int *bdrv_flags,
355 const char **throttling_group, ThrottleConfig *throttle_cfg,
356 BlockdevDetectZeroesOptions *detect_zeroes, Error **errp)
358 const char *discard;
359 Error *local_error = NULL;
360 const char *aio;
362 if (bdrv_flags) {
363 if (!qemu_opt_get_bool(opts, "read-only", false)) {
364 *bdrv_flags |= BDRV_O_RDWR;
366 if (qemu_opt_get_bool(opts, "copy-on-read", false)) {
367 *bdrv_flags |= BDRV_O_COPY_ON_READ;
370 if ((discard = qemu_opt_get(opts, "discard")) != NULL) {
371 if (bdrv_parse_discard_flags(discard, bdrv_flags) != 0) {
372 error_setg(errp, "Invalid discard option");
373 return;
377 if (qemu_opt_get_bool(opts, BDRV_OPT_CACHE_WB, true)) {
378 *bdrv_flags |= BDRV_O_CACHE_WB;
380 if (qemu_opt_get_bool(opts, BDRV_OPT_CACHE_DIRECT, false)) {
381 *bdrv_flags |= BDRV_O_NOCACHE;
383 if (qemu_opt_get_bool(opts, BDRV_OPT_CACHE_NO_FLUSH, false)) {
384 *bdrv_flags |= BDRV_O_NO_FLUSH;
387 if ((aio = qemu_opt_get(opts, "aio")) != NULL) {
388 if (!strcmp(aio, "native")) {
389 *bdrv_flags |= BDRV_O_NATIVE_AIO;
390 } else if (!strcmp(aio, "threads")) {
391 /* this is the default */
392 } else {
393 error_setg(errp, "invalid aio option");
394 return;
399 /* disk I/O throttling */
400 if (throttling_group) {
401 *throttling_group = qemu_opt_get(opts, "throttling.group");
404 if (throttle_cfg) {
405 memset(throttle_cfg, 0, sizeof(*throttle_cfg));
406 throttle_cfg->buckets[THROTTLE_BPS_TOTAL].avg =
407 qemu_opt_get_number(opts, "throttling.bps-total", 0);
408 throttle_cfg->buckets[THROTTLE_BPS_READ].avg =
409 qemu_opt_get_number(opts, "throttling.bps-read", 0);
410 throttle_cfg->buckets[THROTTLE_BPS_WRITE].avg =
411 qemu_opt_get_number(opts, "throttling.bps-write", 0);
412 throttle_cfg->buckets[THROTTLE_OPS_TOTAL].avg =
413 qemu_opt_get_number(opts, "throttling.iops-total", 0);
414 throttle_cfg->buckets[THROTTLE_OPS_READ].avg =
415 qemu_opt_get_number(opts, "throttling.iops-read", 0);
416 throttle_cfg->buckets[THROTTLE_OPS_WRITE].avg =
417 qemu_opt_get_number(opts, "throttling.iops-write", 0);
419 throttle_cfg->buckets[THROTTLE_BPS_TOTAL].max =
420 qemu_opt_get_number(opts, "throttling.bps-total-max", 0);
421 throttle_cfg->buckets[THROTTLE_BPS_READ].max =
422 qemu_opt_get_number(opts, "throttling.bps-read-max", 0);
423 throttle_cfg->buckets[THROTTLE_BPS_WRITE].max =
424 qemu_opt_get_number(opts, "throttling.bps-write-max", 0);
425 throttle_cfg->buckets[THROTTLE_OPS_TOTAL].max =
426 qemu_opt_get_number(opts, "throttling.iops-total-max", 0);
427 throttle_cfg->buckets[THROTTLE_OPS_READ].max =
428 qemu_opt_get_number(opts, "throttling.iops-read-max", 0);
429 throttle_cfg->buckets[THROTTLE_OPS_WRITE].max =
430 qemu_opt_get_number(opts, "throttling.iops-write-max", 0);
432 throttle_cfg->op_size =
433 qemu_opt_get_number(opts, "throttling.iops-size", 0);
435 if (!check_throttle_config(throttle_cfg, errp)) {
436 return;
440 if (detect_zeroes) {
441 *detect_zeroes =
442 qapi_enum_parse(BlockdevDetectZeroesOptions_lookup,
443 qemu_opt_get(opts, "detect-zeroes"),
444 BLOCKDEV_DETECT_ZEROES_OPTIONS_MAX,
445 BLOCKDEV_DETECT_ZEROES_OPTIONS_OFF,
446 &local_error);
447 if (local_error) {
448 error_propagate(errp, local_error);
449 return;
452 if (bdrv_flags &&
453 *detect_zeroes == BLOCKDEV_DETECT_ZEROES_OPTIONS_UNMAP &&
454 !(*bdrv_flags & BDRV_O_UNMAP))
456 error_setg(errp, "setting detect-zeroes to unmap is not allowed "
457 "without setting discard operation to unmap");
458 return;
463 /* Takes the ownership of bs_opts */
464 static BlockBackend *blockdev_init(const char *file, QDict *bs_opts,
465 Error **errp)
467 const char *buf;
468 int bdrv_flags = 0;
469 int on_read_error, on_write_error;
470 BlockBackend *blk;
471 BlockDriverState *bs;
472 ThrottleConfig cfg;
473 int snapshot = 0;
474 Error *error = NULL;
475 QemuOpts *opts;
476 const char *id;
477 bool has_driver_specific_opts;
478 BlockdevDetectZeroesOptions detect_zeroes =
479 BLOCKDEV_DETECT_ZEROES_OPTIONS_OFF;
480 const char *throttling_group = NULL;
482 /* Check common options by copying from bs_opts to opts, all other options
483 * stay in bs_opts for processing by bdrv_open(). */
484 id = qdict_get_try_str(bs_opts, "id");
485 opts = qemu_opts_create(&qemu_common_drive_opts, id, 1, &error);
486 if (error) {
487 error_propagate(errp, error);
488 goto err_no_opts;
491 qemu_opts_absorb_qdict(opts, bs_opts, &error);
492 if (error) {
493 error_propagate(errp, error);
494 goto early_err;
497 if (id) {
498 qdict_del(bs_opts, "id");
501 has_driver_specific_opts = !!qdict_size(bs_opts);
503 /* extract parameters */
504 snapshot = qemu_opt_get_bool(opts, "snapshot", 0);
506 extract_common_blockdev_options(opts, &bdrv_flags, &throttling_group, &cfg,
507 &detect_zeroes, &error);
508 if (error) {
509 error_propagate(errp, error);
510 goto early_err;
513 if ((buf = qemu_opt_get(opts, "format")) != NULL) {
514 if (is_help_option(buf)) {
515 error_printf("Supported formats:");
516 bdrv_iterate_format(bdrv_format_print, NULL);
517 error_printf("\n");
518 goto early_err;
521 if (qdict_haskey(bs_opts, "driver")) {
522 error_setg(errp, "Cannot specify both 'driver' and 'format'");
523 goto early_err;
525 qdict_put(bs_opts, "driver", qstring_from_str(buf));
528 on_write_error = BLOCKDEV_ON_ERROR_ENOSPC;
529 if ((buf = qemu_opt_get(opts, "werror")) != NULL) {
530 on_write_error = parse_block_error_action(buf, 0, &error);
531 if (error) {
532 error_propagate(errp, error);
533 goto early_err;
537 on_read_error = BLOCKDEV_ON_ERROR_REPORT;
538 if ((buf = qemu_opt_get(opts, "rerror")) != NULL) {
539 on_read_error = parse_block_error_action(buf, 1, &error);
540 if (error) {
541 error_propagate(errp, error);
542 goto early_err;
546 if (snapshot) {
547 /* always use cache=unsafe with snapshot */
548 bdrv_flags &= ~BDRV_O_CACHE_MASK;
549 bdrv_flags |= (BDRV_O_SNAPSHOT|BDRV_O_CACHE_WB|BDRV_O_NO_FLUSH);
552 /* init */
553 if ((!file || !*file) && !has_driver_specific_opts) {
554 BlockBackendRootState *blk_rs;
556 blk = blk_new(qemu_opts_id(opts), errp);
557 if (!blk) {
558 goto early_err;
561 blk_rs = blk_get_root_state(blk);
562 blk_rs->open_flags = bdrv_flags;
563 blk_rs->read_only = !(bdrv_flags & BDRV_O_RDWR);
564 blk_rs->detect_zeroes = detect_zeroes;
566 if (throttle_enabled(&cfg)) {
567 if (!throttling_group) {
568 throttling_group = blk_name(blk);
570 blk_rs->throttle_group = g_strdup(throttling_group);
571 blk_rs->throttle_state = throttle_group_incref(throttling_group);
572 blk_rs->throttle_state->cfg = cfg;
575 QDECREF(bs_opts);
576 } else {
577 if (file && !*file) {
578 file = NULL;
581 blk = blk_new_open(qemu_opts_id(opts), file, NULL, bs_opts, bdrv_flags,
582 errp);
583 if (!blk) {
584 goto err_no_bs_opts;
586 bs = blk_bs(blk);
588 bs->detect_zeroes = detect_zeroes;
590 /* disk I/O throttling */
591 if (throttle_enabled(&cfg)) {
592 if (!throttling_group) {
593 throttling_group = blk_name(blk);
595 bdrv_io_limits_enable(bs, throttling_group);
596 bdrv_set_io_limits(bs, &cfg);
599 if (bdrv_key_required(bs)) {
600 autostart = 0;
604 blk_set_on_error(blk, on_read_error, on_write_error);
606 err_no_bs_opts:
607 qemu_opts_del(opts);
608 return blk;
610 early_err:
611 qemu_opts_del(opts);
612 err_no_opts:
613 QDECREF(bs_opts);
614 return NULL;
617 static QemuOptsList qemu_root_bds_opts;
619 /* Takes the ownership of bs_opts */
620 static BlockDriverState *bds_tree_init(QDict *bs_opts, Error **errp)
622 BlockDriverState *bs;
623 QemuOpts *opts;
624 Error *local_error = NULL;
625 BlockdevDetectZeroesOptions detect_zeroes;
626 int ret;
627 int bdrv_flags = 0;
629 opts = qemu_opts_create(&qemu_root_bds_opts, NULL, 1, errp);
630 if (!opts) {
631 goto fail;
634 qemu_opts_absorb_qdict(opts, bs_opts, &local_error);
635 if (local_error) {
636 error_propagate(errp, local_error);
637 goto fail;
640 extract_common_blockdev_options(opts, &bdrv_flags, NULL, NULL,
641 &detect_zeroes, &local_error);
642 if (local_error) {
643 error_propagate(errp, local_error);
644 goto fail;
647 bs = NULL;
648 ret = bdrv_open(&bs, NULL, NULL, bs_opts, bdrv_flags, errp);
649 if (ret < 0) {
650 goto fail_no_bs_opts;
653 bs->detect_zeroes = detect_zeroes;
655 fail_no_bs_opts:
656 qemu_opts_del(opts);
657 return bs;
659 fail:
660 qemu_opts_del(opts);
661 QDECREF(bs_opts);
662 return NULL;
665 static void qemu_opt_rename(QemuOpts *opts, const char *from, const char *to,
666 Error **errp)
668 const char *value;
670 value = qemu_opt_get(opts, from);
671 if (value) {
672 if (qemu_opt_find(opts, to)) {
673 error_setg(errp, "'%s' and its alias '%s' can't be used at the "
674 "same time", to, from);
675 return;
679 /* rename all items in opts */
680 while ((value = qemu_opt_get(opts, from))) {
681 qemu_opt_set(opts, to, value, &error_abort);
682 qemu_opt_unset(opts, from);
686 QemuOptsList qemu_legacy_drive_opts = {
687 .name = "drive",
688 .head = QTAILQ_HEAD_INITIALIZER(qemu_legacy_drive_opts.head),
689 .desc = {
691 .name = "bus",
692 .type = QEMU_OPT_NUMBER,
693 .help = "bus number",
695 .name = "unit",
696 .type = QEMU_OPT_NUMBER,
697 .help = "unit number (i.e. lun for scsi)",
699 .name = "index",
700 .type = QEMU_OPT_NUMBER,
701 .help = "index number",
703 .name = "media",
704 .type = QEMU_OPT_STRING,
705 .help = "media type (disk, cdrom)",
707 .name = "if",
708 .type = QEMU_OPT_STRING,
709 .help = "interface (ide, scsi, sd, mtd, floppy, pflash, virtio)",
711 .name = "cyls",
712 .type = QEMU_OPT_NUMBER,
713 .help = "number of cylinders (ide disk geometry)",
715 .name = "heads",
716 .type = QEMU_OPT_NUMBER,
717 .help = "number of heads (ide disk geometry)",
719 .name = "secs",
720 .type = QEMU_OPT_NUMBER,
721 .help = "number of sectors (ide disk geometry)",
723 .name = "trans",
724 .type = QEMU_OPT_STRING,
725 .help = "chs translation (auto, lba, none)",
727 .name = "boot",
728 .type = QEMU_OPT_BOOL,
729 .help = "(deprecated, ignored)",
731 .name = "addr",
732 .type = QEMU_OPT_STRING,
733 .help = "pci address (virtio only)",
735 .name = "serial",
736 .type = QEMU_OPT_STRING,
737 .help = "disk serial number",
739 .name = "file",
740 .type = QEMU_OPT_STRING,
741 .help = "file name",
744 /* Options that are passed on, but have special semantics with -drive */
746 .name = "read-only",
747 .type = QEMU_OPT_BOOL,
748 .help = "open drive file as read-only",
750 .name = "rerror",
751 .type = QEMU_OPT_STRING,
752 .help = "read error action",
754 .name = "werror",
755 .type = QEMU_OPT_STRING,
756 .help = "write error action",
758 .name = "copy-on-read",
759 .type = QEMU_OPT_BOOL,
760 .help = "copy read data from backing file into image file",
763 { /* end of list */ }
767 DriveInfo *drive_new(QemuOpts *all_opts, BlockInterfaceType block_default_type)
769 const char *value;
770 BlockBackend *blk;
771 DriveInfo *dinfo = NULL;
772 QDict *bs_opts;
773 QemuOpts *legacy_opts;
774 DriveMediaType media = MEDIA_DISK;
775 BlockInterfaceType type;
776 int cyls, heads, secs, translation;
777 int max_devs, bus_id, unit_id, index;
778 const char *devaddr;
779 const char *werror, *rerror;
780 bool read_only = false;
781 bool copy_on_read;
782 const char *serial;
783 const char *filename;
784 Error *local_err = NULL;
785 int i;
787 /* Change legacy command line options into QMP ones */
788 static const struct {
789 const char *from;
790 const char *to;
791 } opt_renames[] = {
792 { "iops", "throttling.iops-total" },
793 { "iops_rd", "throttling.iops-read" },
794 { "iops_wr", "throttling.iops-write" },
796 { "bps", "throttling.bps-total" },
797 { "bps_rd", "throttling.bps-read" },
798 { "bps_wr", "throttling.bps-write" },
800 { "iops_max", "throttling.iops-total-max" },
801 { "iops_rd_max", "throttling.iops-read-max" },
802 { "iops_wr_max", "throttling.iops-write-max" },
804 { "bps_max", "throttling.bps-total-max" },
805 { "bps_rd_max", "throttling.bps-read-max" },
806 { "bps_wr_max", "throttling.bps-write-max" },
808 { "iops_size", "throttling.iops-size" },
810 { "group", "throttling.group" },
812 { "readonly", "read-only" },
815 for (i = 0; i < ARRAY_SIZE(opt_renames); i++) {
816 qemu_opt_rename(all_opts, opt_renames[i].from, opt_renames[i].to,
817 &local_err);
818 if (local_err) {
819 error_report_err(local_err);
820 return NULL;
824 value = qemu_opt_get(all_opts, "cache");
825 if (value) {
826 int flags = 0;
828 if (bdrv_parse_cache_flags(value, &flags) != 0) {
829 error_report("invalid cache option");
830 return NULL;
833 /* Specific options take precedence */
834 if (!qemu_opt_get(all_opts, BDRV_OPT_CACHE_WB)) {
835 qemu_opt_set_bool(all_opts, BDRV_OPT_CACHE_WB,
836 !!(flags & BDRV_O_CACHE_WB), &error_abort);
838 if (!qemu_opt_get(all_opts, BDRV_OPT_CACHE_DIRECT)) {
839 qemu_opt_set_bool(all_opts, BDRV_OPT_CACHE_DIRECT,
840 !!(flags & BDRV_O_NOCACHE), &error_abort);
842 if (!qemu_opt_get(all_opts, BDRV_OPT_CACHE_NO_FLUSH)) {
843 qemu_opt_set_bool(all_opts, BDRV_OPT_CACHE_NO_FLUSH,
844 !!(flags & BDRV_O_NO_FLUSH), &error_abort);
846 qemu_opt_unset(all_opts, "cache");
849 /* Get a QDict for processing the options */
850 bs_opts = qdict_new();
851 qemu_opts_to_qdict(all_opts, bs_opts);
853 legacy_opts = qemu_opts_create(&qemu_legacy_drive_opts, NULL, 0,
854 &error_abort);
855 qemu_opts_absorb_qdict(legacy_opts, bs_opts, &local_err);
856 if (local_err) {
857 error_report_err(local_err);
858 goto fail;
861 /* Deprecated option boot=[on|off] */
862 if (qemu_opt_get(legacy_opts, "boot") != NULL) {
863 fprintf(stderr, "qemu-kvm: boot=on|off is deprecated and will be "
864 "ignored. Future versions will reject this parameter. Please "
865 "update your scripts.\n");
868 /* Media type */
869 value = qemu_opt_get(legacy_opts, "media");
870 if (value) {
871 if (!strcmp(value, "disk")) {
872 media = MEDIA_DISK;
873 } else if (!strcmp(value, "cdrom")) {
874 media = MEDIA_CDROM;
875 read_only = true;
876 } else {
877 error_report("'%s' invalid media", value);
878 goto fail;
882 /* copy-on-read is disabled with a warning for read-only devices */
883 read_only |= qemu_opt_get_bool(legacy_opts, "read-only", false);
884 copy_on_read = qemu_opt_get_bool(legacy_opts, "copy-on-read", false);
886 if (read_only && copy_on_read) {
887 error_report("warning: disabling copy-on-read on read-only drive");
888 copy_on_read = false;
891 qdict_put(bs_opts, "read-only",
892 qstring_from_str(read_only ? "on" : "off"));
893 qdict_put(bs_opts, "copy-on-read",
894 qstring_from_str(copy_on_read ? "on" :"off"));
896 /* Controller type */
897 value = qemu_opt_get(legacy_opts, "if");
898 if (value) {
899 for (type = 0;
900 type < IF_COUNT && strcmp(value, if_name[type]);
901 type++) {
903 if (type == IF_COUNT) {
904 error_report("unsupported bus type '%s'", value);
905 goto fail;
907 } else {
908 type = block_default_type;
911 /* Geometry */
912 cyls = qemu_opt_get_number(legacy_opts, "cyls", 0);
913 heads = qemu_opt_get_number(legacy_opts, "heads", 0);
914 secs = qemu_opt_get_number(legacy_opts, "secs", 0);
916 if (cyls || heads || secs) {
917 if (cyls < 1) {
918 error_report("invalid physical cyls number");
919 goto fail;
921 if (heads < 1) {
922 error_report("invalid physical heads number");
923 goto fail;
925 if (secs < 1) {
926 error_report("invalid physical secs number");
927 goto fail;
931 translation = BIOS_ATA_TRANSLATION_AUTO;
932 value = qemu_opt_get(legacy_opts, "trans");
933 if (value != NULL) {
934 if (!cyls) {
935 error_report("'%s' trans must be used with cyls, heads and secs",
936 value);
937 goto fail;
939 if (!strcmp(value, "none")) {
940 translation = BIOS_ATA_TRANSLATION_NONE;
941 } else if (!strcmp(value, "lba")) {
942 translation = BIOS_ATA_TRANSLATION_LBA;
943 } else if (!strcmp(value, "large")) {
944 translation = BIOS_ATA_TRANSLATION_LARGE;
945 } else if (!strcmp(value, "rechs")) {
946 translation = BIOS_ATA_TRANSLATION_RECHS;
947 } else if (!strcmp(value, "auto")) {
948 translation = BIOS_ATA_TRANSLATION_AUTO;
949 } else {
950 error_report("'%s' invalid translation type", value);
951 goto fail;
955 if (media == MEDIA_CDROM) {
956 if (cyls || secs || heads) {
957 error_report("CHS can't be set with media=cdrom");
958 goto fail;
962 /* Device address specified by bus/unit or index.
963 * If none was specified, try to find the first free one. */
964 bus_id = qemu_opt_get_number(legacy_opts, "bus", 0);
965 unit_id = qemu_opt_get_number(legacy_opts, "unit", -1);
966 index = qemu_opt_get_number(legacy_opts, "index", -1);
968 max_devs = if_max_devs[type];
970 if (index != -1) {
971 if (bus_id != 0 || unit_id != -1) {
972 error_report("index cannot be used with bus and unit");
973 goto fail;
975 bus_id = drive_index_to_bus_id(type, index);
976 unit_id = drive_index_to_unit_id(type, index);
979 if (unit_id == -1) {
980 unit_id = 0;
981 while (drive_get(type, bus_id, unit_id) != NULL) {
982 unit_id++;
983 if (max_devs && unit_id >= max_devs) {
984 unit_id -= max_devs;
985 bus_id++;
990 if (max_devs && unit_id >= max_devs) {
991 error_report("unit %d too big (max is %d)", unit_id, max_devs - 1);
992 goto fail;
995 if (drive_get(type, bus_id, unit_id) != NULL) {
996 error_report("drive with bus=%d, unit=%d (index=%d) exists",
997 bus_id, unit_id, index);
998 goto fail;
1001 /* Serial number */
1002 serial = qemu_opt_get(legacy_opts, "serial");
1004 /* no id supplied -> create one */
1005 if (qemu_opts_id(all_opts) == NULL) {
1006 char *new_id;
1007 const char *mediastr = "";
1008 if (type == IF_IDE || type == IF_SCSI) {
1009 mediastr = (media == MEDIA_CDROM) ? "-cd" : "-hd";
1011 if (max_devs) {
1012 new_id = g_strdup_printf("%s%i%s%i", if_name[type], bus_id,
1013 mediastr, unit_id);
1014 } else {
1015 new_id = g_strdup_printf("%s%s%i", if_name[type],
1016 mediastr, unit_id);
1018 qdict_put(bs_opts, "id", qstring_from_str(new_id));
1019 g_free(new_id);
1022 /* Add virtio block device */
1023 devaddr = qemu_opt_get(legacy_opts, "addr");
1024 if (devaddr && type != IF_VIRTIO) {
1025 error_report("addr is not supported by this bus type");
1026 goto fail;
1029 if (type == IF_VIRTIO) {
1030 QemuOpts *devopts;
1031 devopts = qemu_opts_create(qemu_find_opts("device"), NULL, 0,
1032 &error_abort);
1033 if (arch_type == QEMU_ARCH_S390X) {
1034 qemu_opt_set(devopts, "driver", "virtio-blk-ccw", &error_abort);
1035 } else {
1036 qemu_opt_set(devopts, "driver", "virtio-blk-pci", &error_abort);
1038 qemu_opt_set(devopts, "drive", qdict_get_str(bs_opts, "id"),
1039 &error_abort);
1040 if (devaddr) {
1041 qemu_opt_set(devopts, "addr", devaddr, &error_abort);
1045 filename = qemu_opt_get(legacy_opts, "file");
1047 /* Check werror/rerror compatibility with if=... */
1048 werror = qemu_opt_get(legacy_opts, "werror");
1049 if (werror != NULL) {
1050 if (type != IF_IDE && type != IF_SCSI && type != IF_VIRTIO &&
1051 type != IF_NONE) {
1052 error_report("werror is not supported by this bus type");
1053 goto fail;
1055 qdict_put(bs_opts, "werror", qstring_from_str(werror));
1058 rerror = qemu_opt_get(legacy_opts, "rerror");
1059 if (rerror != NULL) {
1060 if (type != IF_IDE && type != IF_VIRTIO && type != IF_SCSI &&
1061 type != IF_NONE) {
1062 error_report("rerror is not supported by this bus type");
1063 goto fail;
1065 qdict_put(bs_opts, "rerror", qstring_from_str(rerror));
1068 /* Actual block device init: Functionality shared with blockdev-add */
1069 blk = blockdev_init(filename, bs_opts, &local_err);
1070 bs_opts = NULL;
1071 if (!blk) {
1072 if (local_err) {
1073 error_report_err(local_err);
1075 goto fail;
1076 } else {
1077 assert(!local_err);
1080 /* Create legacy DriveInfo */
1081 dinfo = g_malloc0(sizeof(*dinfo));
1082 dinfo->opts = all_opts;
1084 dinfo->cyls = cyls;
1085 dinfo->heads = heads;
1086 dinfo->secs = secs;
1087 dinfo->trans = translation;
1089 dinfo->type = type;
1090 dinfo->bus = bus_id;
1091 dinfo->unit = unit_id;
1092 dinfo->devaddr = devaddr;
1093 dinfo->serial = g_strdup(serial);
1095 blk_set_legacy_dinfo(blk, dinfo);
1097 switch(type) {
1098 case IF_IDE:
1099 case IF_SCSI:
1100 case IF_XEN:
1101 case IF_NONE:
1102 dinfo->media_cd = media == MEDIA_CDROM;
1103 break;
1104 default:
1105 break;
1108 fail:
1109 qemu_opts_del(legacy_opts);
1110 QDECREF(bs_opts);
1111 return dinfo;
1114 void hmp_commit(Monitor *mon, const QDict *qdict)
1116 const char *device = qdict_get_str(qdict, "device");
1117 BlockBackend *blk;
1118 int ret;
1120 if (!strcmp(device, "all")) {
1121 ret = bdrv_commit_all();
1122 } else {
1123 BlockDriverState *bs;
1124 AioContext *aio_context;
1126 blk = blk_by_name(device);
1127 if (!blk) {
1128 monitor_printf(mon, "Device '%s' not found\n", device);
1129 return;
1131 if (!blk_is_available(blk)) {
1132 monitor_printf(mon, "Device '%s' has no medium\n", device);
1133 return;
1136 bs = blk_bs(blk);
1137 aio_context = bdrv_get_aio_context(bs);
1138 aio_context_acquire(aio_context);
1140 ret = bdrv_commit(bs);
1142 aio_context_release(aio_context);
1144 if (ret < 0) {
1145 monitor_printf(mon, "'commit' error for '%s': %s\n", device,
1146 strerror(-ret));
1150 static void blockdev_do_action(TransactionActionKind type, void *data,
1151 Error **errp)
1153 TransactionAction action;
1154 TransactionActionList list;
1156 action.type = type;
1157 action.u.data = data;
1158 list.value = &action;
1159 list.next = NULL;
1160 qmp_transaction(&list, errp);
1163 void qmp_blockdev_snapshot_sync(bool has_device, const char *device,
1164 bool has_node_name, const char *node_name,
1165 const char *snapshot_file,
1166 bool has_snapshot_node_name,
1167 const char *snapshot_node_name,
1168 bool has_format, const char *format,
1169 bool has_mode, NewImageMode mode, Error **errp)
1171 BlockdevSnapshotSync snapshot = {
1172 .has_device = has_device,
1173 .device = (char *) device,
1174 .has_node_name = has_node_name,
1175 .node_name = (char *) node_name,
1176 .snapshot_file = (char *) snapshot_file,
1177 .has_snapshot_node_name = has_snapshot_node_name,
1178 .snapshot_node_name = (char *) snapshot_node_name,
1179 .has_format = has_format,
1180 .format = (char *) format,
1181 .has_mode = has_mode,
1182 .mode = mode,
1184 blockdev_do_action(TRANSACTION_ACTION_KIND_BLOCKDEV_SNAPSHOT_SYNC,
1185 &snapshot, errp);
1188 void qmp_blockdev_snapshot(const char *node, const char *overlay,
1189 Error **errp)
1191 BlockdevSnapshot snapshot_data = {
1192 .node = (char *) node,
1193 .overlay = (char *) overlay
1196 blockdev_do_action(TRANSACTION_ACTION_KIND_BLOCKDEV_SNAPSHOT,
1197 &snapshot_data, errp);
1200 void qmp_blockdev_snapshot_internal_sync(const char *device,
1201 const char *name,
1202 Error **errp)
1204 BlockdevSnapshotInternal snapshot = {
1205 .device = (char *) device,
1206 .name = (char *) name
1209 blockdev_do_action(TRANSACTION_ACTION_KIND_BLOCKDEV_SNAPSHOT_INTERNAL_SYNC,
1210 &snapshot, errp);
1213 SnapshotInfo *qmp_blockdev_snapshot_delete_internal_sync(const char *device,
1214 bool has_id,
1215 const char *id,
1216 bool has_name,
1217 const char *name,
1218 Error **errp)
1220 BlockDriverState *bs;
1221 BlockBackend *blk;
1222 AioContext *aio_context;
1223 QEMUSnapshotInfo sn;
1224 Error *local_err = NULL;
1225 SnapshotInfo *info = NULL;
1226 int ret;
1228 blk = blk_by_name(device);
1229 if (!blk) {
1230 error_set(errp, ERROR_CLASS_DEVICE_NOT_FOUND,
1231 "Device '%s' not found", device);
1232 return NULL;
1235 aio_context = blk_get_aio_context(blk);
1236 aio_context_acquire(aio_context);
1238 if (!has_id) {
1239 id = NULL;
1242 if (!has_name) {
1243 name = NULL;
1246 if (!id && !name) {
1247 error_setg(errp, "Name or id must be provided");
1248 goto out_aio_context;
1251 if (!blk_is_available(blk)) {
1252 error_setg(errp, "Device '%s' has no medium", device);
1253 goto out_aio_context;
1255 bs = blk_bs(blk);
1257 if (bdrv_op_is_blocked(bs, BLOCK_OP_TYPE_INTERNAL_SNAPSHOT_DELETE, errp)) {
1258 goto out_aio_context;
1261 ret = bdrv_snapshot_find_by_id_and_name(bs, id, name, &sn, &local_err);
1262 if (local_err) {
1263 error_propagate(errp, local_err);
1264 goto out_aio_context;
1266 if (!ret) {
1267 error_setg(errp,
1268 "Snapshot with id '%s' and name '%s' does not exist on "
1269 "device '%s'",
1270 STR_OR_NULL(id), STR_OR_NULL(name), device);
1271 goto out_aio_context;
1274 bdrv_snapshot_delete(bs, id, name, &local_err);
1275 if (local_err) {
1276 error_propagate(errp, local_err);
1277 goto out_aio_context;
1280 aio_context_release(aio_context);
1282 info = g_new0(SnapshotInfo, 1);
1283 info->id = g_strdup(sn.id_str);
1284 info->name = g_strdup(sn.name);
1285 info->date_nsec = sn.date_nsec;
1286 info->date_sec = sn.date_sec;
1287 info->vm_state_size = sn.vm_state_size;
1288 info->vm_clock_nsec = sn.vm_clock_nsec % 1000000000;
1289 info->vm_clock_sec = sn.vm_clock_nsec / 1000000000;
1291 return info;
1293 out_aio_context:
1294 aio_context_release(aio_context);
1295 return NULL;
1299 * block_dirty_bitmap_lookup:
1300 * Return a dirty bitmap (if present), after validating
1301 * the node reference and bitmap names.
1303 * @node: The name of the BDS node to search for bitmaps
1304 * @name: The name of the bitmap to search for
1305 * @pbs: Output pointer for BDS lookup, if desired. Can be NULL.
1306 * @paio: Output pointer for aio_context acquisition, if desired. Can be NULL.
1307 * @errp: Output pointer for error information. Can be NULL.
1309 * @return: A bitmap object on success, or NULL on failure.
1311 static BdrvDirtyBitmap *block_dirty_bitmap_lookup(const char *node,
1312 const char *name,
1313 BlockDriverState **pbs,
1314 AioContext **paio,
1315 Error **errp)
1317 BlockDriverState *bs;
1318 BdrvDirtyBitmap *bitmap;
1319 AioContext *aio_context;
1321 if (!node) {
1322 error_setg(errp, "Node cannot be NULL");
1323 return NULL;
1325 if (!name) {
1326 error_setg(errp, "Bitmap name cannot be NULL");
1327 return NULL;
1329 bs = bdrv_lookup_bs(node, node, NULL);
1330 if (!bs) {
1331 error_setg(errp, "Node '%s' not found", node);
1332 return NULL;
1335 aio_context = bdrv_get_aio_context(bs);
1336 aio_context_acquire(aio_context);
1338 bitmap = bdrv_find_dirty_bitmap(bs, name);
1339 if (!bitmap) {
1340 error_setg(errp, "Dirty bitmap '%s' not found", name);
1341 goto fail;
1344 if (pbs) {
1345 *pbs = bs;
1347 if (paio) {
1348 *paio = aio_context;
1349 } else {
1350 aio_context_release(aio_context);
1353 return bitmap;
1355 fail:
1356 aio_context_release(aio_context);
1357 return NULL;
1360 /* New and old BlockDriverState structs for atomic group operations */
1362 typedef struct BlkActionState BlkActionState;
1365 * BlkActionOps:
1366 * Table of operations that define an Action.
1368 * @instance_size: Size of state struct, in bytes.
1369 * @prepare: Prepare the work, must NOT be NULL.
1370 * @commit: Commit the changes, can be NULL.
1371 * @abort: Abort the changes on fail, can be NULL.
1372 * @clean: Clean up resources after all transaction actions have called
1373 * commit() or abort(). Can be NULL.
1375 * Only prepare() may fail. In a single transaction, only one of commit() or
1376 * abort() will be called. clean() will always be called if it is present.
1378 typedef struct BlkActionOps {
1379 size_t instance_size;
1380 void (*prepare)(BlkActionState *common, Error **errp);
1381 void (*commit)(BlkActionState *common);
1382 void (*abort)(BlkActionState *common);
1383 void (*clean)(BlkActionState *common);
1384 } BlkActionOps;
1387 * BlkActionState:
1388 * Describes one Action's state within a Transaction.
1390 * @action: QAPI-defined enum identifying which Action to perform.
1391 * @ops: Table of ActionOps this Action can perform.
1392 * @entry: List membership for all Actions in this Transaction.
1394 * This structure must be arranged as first member in a subclassed type,
1395 * assuming that the compiler will also arrange it to the same offsets as the
1396 * base class.
1398 struct BlkActionState {
1399 TransactionAction *action;
1400 const BlkActionOps *ops;
1401 QSIMPLEQ_ENTRY(BlkActionState) entry;
1404 /* internal snapshot private data */
1405 typedef struct InternalSnapshotState {
1406 BlkActionState common;
1407 BlockDriverState *bs;
1408 AioContext *aio_context;
1409 QEMUSnapshotInfo sn;
1410 bool created;
1411 } InternalSnapshotState;
1413 static void internal_snapshot_prepare(BlkActionState *common,
1414 Error **errp)
1416 Error *local_err = NULL;
1417 const char *device;
1418 const char *name;
1419 BlockBackend *blk;
1420 BlockDriverState *bs;
1421 QEMUSnapshotInfo old_sn, *sn;
1422 bool ret;
1423 qemu_timeval tv;
1424 BlockdevSnapshotInternal *internal;
1425 InternalSnapshotState *state;
1426 int ret1;
1428 g_assert(common->action->type ==
1429 TRANSACTION_ACTION_KIND_BLOCKDEV_SNAPSHOT_INTERNAL_SYNC);
1430 internal = common->action->u.blockdev_snapshot_internal_sync;
1431 state = DO_UPCAST(InternalSnapshotState, common, common);
1433 /* 1. parse input */
1434 device = internal->device;
1435 name = internal->name;
1437 /* 2. check for validation */
1438 blk = blk_by_name(device);
1439 if (!blk) {
1440 error_set(errp, ERROR_CLASS_DEVICE_NOT_FOUND,
1441 "Device '%s' not found", device);
1442 return;
1445 /* AioContext is released in .clean() */
1446 state->aio_context = blk_get_aio_context(blk);
1447 aio_context_acquire(state->aio_context);
1449 if (!blk_is_available(blk)) {
1450 error_setg(errp, QERR_DEVICE_HAS_NO_MEDIUM, device);
1451 return;
1453 bs = blk_bs(blk);
1455 state->bs = bs;
1456 bdrv_drained_begin(bs);
1458 if (bdrv_op_is_blocked(bs, BLOCK_OP_TYPE_INTERNAL_SNAPSHOT, errp)) {
1459 return;
1462 if (bdrv_is_read_only(bs)) {
1463 error_setg(errp, "Device '%s' is read only", device);
1464 return;
1467 if (!bdrv_can_snapshot(bs)) {
1468 error_setg(errp, "Block format '%s' used by device '%s' "
1469 "does not support internal snapshots",
1470 bs->drv->format_name, device);
1471 return;
1474 if (!strlen(name)) {
1475 error_setg(errp, "Name is empty");
1476 return;
1479 /* check whether a snapshot with name exist */
1480 ret = bdrv_snapshot_find_by_id_and_name(bs, NULL, name, &old_sn,
1481 &local_err);
1482 if (local_err) {
1483 error_propagate(errp, local_err);
1484 return;
1485 } else if (ret) {
1486 error_setg(errp,
1487 "Snapshot with name '%s' already exists on device '%s'",
1488 name, device);
1489 return;
1492 /* 3. take the snapshot */
1493 sn = &state->sn;
1494 pstrcpy(sn->name, sizeof(sn->name), name);
1495 qemu_gettimeofday(&tv);
1496 sn->date_sec = tv.tv_sec;
1497 sn->date_nsec = tv.tv_usec * 1000;
1498 sn->vm_clock_nsec = qemu_clock_get_ns(QEMU_CLOCK_VIRTUAL);
1500 ret1 = bdrv_snapshot_create(bs, sn);
1501 if (ret1 < 0) {
1502 error_setg_errno(errp, -ret1,
1503 "Failed to create snapshot '%s' on device '%s'",
1504 name, device);
1505 return;
1508 /* 4. succeed, mark a snapshot is created */
1509 state->created = true;
1512 static void internal_snapshot_abort(BlkActionState *common)
1514 InternalSnapshotState *state =
1515 DO_UPCAST(InternalSnapshotState, common, common);
1516 BlockDriverState *bs = state->bs;
1517 QEMUSnapshotInfo *sn = &state->sn;
1518 Error *local_error = NULL;
1520 if (!state->created) {
1521 return;
1524 if (bdrv_snapshot_delete(bs, sn->id_str, sn->name, &local_error) < 0) {
1525 error_report("Failed to delete snapshot with id '%s' and name '%s' on "
1526 "device '%s' in abort: %s",
1527 sn->id_str,
1528 sn->name,
1529 bdrv_get_device_name(bs),
1530 error_get_pretty(local_error));
1531 error_free(local_error);
1535 static void internal_snapshot_clean(BlkActionState *common)
1537 InternalSnapshotState *state = DO_UPCAST(InternalSnapshotState,
1538 common, common);
1540 if (state->aio_context) {
1541 if (state->bs) {
1542 bdrv_drained_end(state->bs);
1544 aio_context_release(state->aio_context);
1548 /* external snapshot private data */
1549 typedef struct ExternalSnapshotState {
1550 BlkActionState common;
1551 BlockDriverState *old_bs;
1552 BlockDriverState *new_bs;
1553 AioContext *aio_context;
1554 } ExternalSnapshotState;
1556 static void external_snapshot_prepare(BlkActionState *common,
1557 Error **errp)
1559 int flags = 0, ret;
1560 QDict *options = NULL;
1561 Error *local_err = NULL;
1562 /* Device and node name of the image to generate the snapshot from */
1563 const char *device;
1564 const char *node_name;
1565 /* Reference to the new image (for 'blockdev-snapshot') */
1566 const char *snapshot_ref;
1567 /* File name of the new image (for 'blockdev-snapshot-sync') */
1568 const char *new_image_file;
1569 ExternalSnapshotState *state =
1570 DO_UPCAST(ExternalSnapshotState, common, common);
1571 TransactionAction *action = common->action;
1573 /* 'blockdev-snapshot' and 'blockdev-snapshot-sync' have similar
1574 * purpose but a different set of parameters */
1575 switch (action->type) {
1576 case TRANSACTION_ACTION_KIND_BLOCKDEV_SNAPSHOT:
1578 BlockdevSnapshot *s = action->u.blockdev_snapshot;
1579 device = s->node;
1580 node_name = s->node;
1581 new_image_file = NULL;
1582 snapshot_ref = s->overlay;
1584 break;
1585 case TRANSACTION_ACTION_KIND_BLOCKDEV_SNAPSHOT_SYNC:
1587 BlockdevSnapshotSync *s = action->u.blockdev_snapshot_sync;
1588 device = s->has_device ? s->device : NULL;
1589 node_name = s->has_node_name ? s->node_name : NULL;
1590 new_image_file = s->snapshot_file;
1591 snapshot_ref = NULL;
1593 break;
1594 default:
1595 g_assert_not_reached();
1598 /* start processing */
1599 state->old_bs = bdrv_lookup_bs(device, node_name, errp);
1600 if (!state->old_bs) {
1601 return;
1604 /* Acquire AioContext now so any threads operating on old_bs stop */
1605 state->aio_context = bdrv_get_aio_context(state->old_bs);
1606 aio_context_acquire(state->aio_context);
1607 bdrv_drained_begin(state->old_bs);
1609 if (!bdrv_is_inserted(state->old_bs)) {
1610 error_setg(errp, QERR_DEVICE_HAS_NO_MEDIUM, device);
1611 return;
1614 if (bdrv_op_is_blocked(state->old_bs,
1615 BLOCK_OP_TYPE_EXTERNAL_SNAPSHOT, errp)) {
1616 return;
1619 if (!bdrv_is_read_only(state->old_bs)) {
1620 if (bdrv_flush(state->old_bs)) {
1621 error_setg(errp, QERR_IO_ERROR);
1622 return;
1626 if (!bdrv_is_first_non_filter(state->old_bs)) {
1627 error_setg(errp, QERR_FEATURE_DISABLED, "snapshot");
1628 return;
1631 if (action->type == TRANSACTION_ACTION_KIND_BLOCKDEV_SNAPSHOT_SYNC) {
1632 BlockdevSnapshotSync *s = action->u.blockdev_snapshot_sync;
1633 const char *format = s->has_format ? s->format : "qcow2";
1634 enum NewImageMode mode;
1635 const char *snapshot_node_name =
1636 s->has_snapshot_node_name ? s->snapshot_node_name : NULL;
1638 if (node_name && !snapshot_node_name) {
1639 error_setg(errp, "New snapshot node name missing");
1640 return;
1643 if (snapshot_node_name &&
1644 bdrv_lookup_bs(snapshot_node_name, snapshot_node_name, NULL)) {
1645 error_setg(errp, "New snapshot node name already in use");
1646 return;
1649 flags = state->old_bs->open_flags;
1651 /* create new image w/backing file */
1652 mode = s->has_mode ? s->mode : NEW_IMAGE_MODE_ABSOLUTE_PATHS;
1653 if (mode != NEW_IMAGE_MODE_EXISTING) {
1654 bdrv_img_create(new_image_file, format,
1655 state->old_bs->filename,
1656 state->old_bs->drv->format_name,
1657 NULL, -1, flags, &local_err, false);
1658 if (local_err) {
1659 error_propagate(errp, local_err);
1660 return;
1664 options = qdict_new();
1665 if (s->has_snapshot_node_name) {
1666 qdict_put(options, "node-name",
1667 qstring_from_str(snapshot_node_name));
1669 qdict_put(options, "driver", qstring_from_str(format));
1671 flags |= BDRV_O_NO_BACKING;
1674 assert(state->new_bs == NULL);
1675 ret = bdrv_open(&state->new_bs, new_image_file, snapshot_ref, options,
1676 flags, errp);
1677 /* We will manually add the backing_hd field to the bs later */
1678 if (ret != 0) {
1679 return;
1682 if (state->new_bs->blk != NULL) {
1683 error_setg(errp, "The snapshot is already in use by %s",
1684 blk_name(state->new_bs->blk));
1685 return;
1688 if (bdrv_op_is_blocked(state->new_bs, BLOCK_OP_TYPE_EXTERNAL_SNAPSHOT,
1689 errp)) {
1690 return;
1693 if (state->new_bs->backing != NULL) {
1694 error_setg(errp, "The snapshot already has a backing image");
1695 return;
1698 if (!state->new_bs->drv->supports_backing) {
1699 error_setg(errp, "The snapshot does not support backing images");
1703 static void external_snapshot_commit(BlkActionState *common)
1705 ExternalSnapshotState *state =
1706 DO_UPCAST(ExternalSnapshotState, common, common);
1708 bdrv_set_aio_context(state->new_bs, state->aio_context);
1710 /* This removes our old bs and adds the new bs */
1711 bdrv_append(state->new_bs, state->old_bs);
1712 /* We don't need (or want) to use the transactional
1713 * bdrv_reopen_multiple() across all the entries at once, because we
1714 * don't want to abort all of them if one of them fails the reopen */
1715 bdrv_reopen(state->old_bs, state->old_bs->open_flags & ~BDRV_O_RDWR,
1716 NULL);
1719 static void external_snapshot_abort(BlkActionState *common)
1721 ExternalSnapshotState *state =
1722 DO_UPCAST(ExternalSnapshotState, common, common);
1723 if (state->new_bs) {
1724 bdrv_unref(state->new_bs);
1728 static void external_snapshot_clean(BlkActionState *common)
1730 ExternalSnapshotState *state =
1731 DO_UPCAST(ExternalSnapshotState, common, common);
1732 if (state->aio_context) {
1733 bdrv_drained_end(state->old_bs);
1734 aio_context_release(state->aio_context);
1738 typedef struct DriveBackupState {
1739 BlkActionState common;
1740 BlockDriverState *bs;
1741 AioContext *aio_context;
1742 BlockJob *job;
1743 } DriveBackupState;
1745 static void drive_backup_prepare(BlkActionState *common, Error **errp)
1747 DriveBackupState *state = DO_UPCAST(DriveBackupState, common, common);
1748 BlockBackend *blk;
1749 DriveBackup *backup;
1750 Error *local_err = NULL;
1752 assert(common->action->type == TRANSACTION_ACTION_KIND_DRIVE_BACKUP);
1753 backup = common->action->u.drive_backup;
1755 blk = blk_by_name(backup->device);
1756 if (!blk) {
1757 error_set(errp, ERROR_CLASS_DEVICE_NOT_FOUND,
1758 "Device '%s' not found", backup->device);
1759 return;
1762 if (!blk_is_available(blk)) {
1763 error_setg(errp, QERR_DEVICE_HAS_NO_MEDIUM, backup->device);
1764 return;
1767 /* AioContext is released in .clean() */
1768 state->aio_context = blk_get_aio_context(blk);
1769 aio_context_acquire(state->aio_context);
1770 bdrv_drained_begin(blk_bs(blk));
1771 state->bs = blk_bs(blk);
1773 qmp_drive_backup(backup->device, backup->target,
1774 backup->has_format, backup->format,
1775 backup->sync,
1776 backup->has_mode, backup->mode,
1777 backup->has_speed, backup->speed,
1778 backup->has_bitmap, backup->bitmap,
1779 backup->has_on_source_error, backup->on_source_error,
1780 backup->has_on_target_error, backup->on_target_error,
1781 &local_err);
1782 if (local_err) {
1783 error_propagate(errp, local_err);
1784 return;
1787 state->job = state->bs->job;
1790 static void drive_backup_abort(BlkActionState *common)
1792 DriveBackupState *state = DO_UPCAST(DriveBackupState, common, common);
1793 BlockDriverState *bs = state->bs;
1795 /* Only cancel if it's the job we started */
1796 if (bs && bs->job && bs->job == state->job) {
1797 block_job_cancel_sync(bs->job);
1801 static void drive_backup_clean(BlkActionState *common)
1803 DriveBackupState *state = DO_UPCAST(DriveBackupState, common, common);
1805 if (state->aio_context) {
1806 bdrv_drained_end(state->bs);
1807 aio_context_release(state->aio_context);
1811 typedef struct BlockdevBackupState {
1812 BlkActionState common;
1813 BlockDriverState *bs;
1814 BlockJob *job;
1815 AioContext *aio_context;
1816 } BlockdevBackupState;
1818 static void blockdev_backup_prepare(BlkActionState *common, Error **errp)
1820 BlockdevBackupState *state = DO_UPCAST(BlockdevBackupState, common, common);
1821 BlockdevBackup *backup;
1822 BlockBackend *blk, *target;
1823 Error *local_err = NULL;
1825 assert(common->action->type == TRANSACTION_ACTION_KIND_BLOCKDEV_BACKUP);
1826 backup = common->action->u.blockdev_backup;
1828 blk = blk_by_name(backup->device);
1829 if (!blk) {
1830 error_setg(errp, "Device '%s' not found", backup->device);
1831 return;
1834 if (!blk_is_available(blk)) {
1835 error_setg(errp, QERR_DEVICE_HAS_NO_MEDIUM, backup->device);
1836 return;
1839 target = blk_by_name(backup->target);
1840 if (!target) {
1841 error_setg(errp, "Device '%s' not found", backup->target);
1842 return;
1845 /* AioContext is released in .clean() */
1846 state->aio_context = blk_get_aio_context(blk);
1847 if (state->aio_context != blk_get_aio_context(target)) {
1848 state->aio_context = NULL;
1849 error_setg(errp, "Backup between two IO threads is not implemented");
1850 return;
1852 aio_context_acquire(state->aio_context);
1853 state->bs = blk_bs(blk);
1854 bdrv_drained_begin(state->bs);
1856 qmp_blockdev_backup(backup->device, backup->target,
1857 backup->sync,
1858 backup->has_speed, backup->speed,
1859 backup->has_on_source_error, backup->on_source_error,
1860 backup->has_on_target_error, backup->on_target_error,
1861 &local_err);
1862 if (local_err) {
1863 error_propagate(errp, local_err);
1864 return;
1867 state->job = state->bs->job;
1870 static void blockdev_backup_abort(BlkActionState *common)
1872 BlockdevBackupState *state = DO_UPCAST(BlockdevBackupState, common, common);
1873 BlockDriverState *bs = state->bs;
1875 /* Only cancel if it's the job we started */
1876 if (bs && bs->job && bs->job == state->job) {
1877 block_job_cancel_sync(bs->job);
1881 static void blockdev_backup_clean(BlkActionState *common)
1883 BlockdevBackupState *state = DO_UPCAST(BlockdevBackupState, common, common);
1885 if (state->aio_context) {
1886 bdrv_drained_end(state->bs);
1887 aio_context_release(state->aio_context);
1891 typedef struct BlockDirtyBitmapState {
1892 BlkActionState common;
1893 BdrvDirtyBitmap *bitmap;
1894 BlockDriverState *bs;
1895 AioContext *aio_context;
1896 HBitmap *backup;
1897 bool prepared;
1898 } BlockDirtyBitmapState;
1900 static void block_dirty_bitmap_add_prepare(BlkActionState *common,
1901 Error **errp)
1903 Error *local_err = NULL;
1904 BlockDirtyBitmapAdd *action;
1905 BlockDirtyBitmapState *state = DO_UPCAST(BlockDirtyBitmapState,
1906 common, common);
1908 action = common->action->u.block_dirty_bitmap_add;
1909 /* AIO context taken and released within qmp_block_dirty_bitmap_add */
1910 qmp_block_dirty_bitmap_add(action->node, action->name,
1911 action->has_granularity, action->granularity,
1912 &local_err);
1914 if (!local_err) {
1915 state->prepared = true;
1916 } else {
1917 error_propagate(errp, local_err);
1921 static void block_dirty_bitmap_add_abort(BlkActionState *common)
1923 BlockDirtyBitmapAdd *action;
1924 BlockDirtyBitmapState *state = DO_UPCAST(BlockDirtyBitmapState,
1925 common, common);
1927 action = common->action->u.block_dirty_bitmap_add;
1928 /* Should not be able to fail: IF the bitmap was added via .prepare(),
1929 * then the node reference and bitmap name must have been valid.
1931 if (state->prepared) {
1932 qmp_block_dirty_bitmap_remove(action->node, action->name, &error_abort);
1936 static void block_dirty_bitmap_clear_prepare(BlkActionState *common,
1937 Error **errp)
1939 BlockDirtyBitmapState *state = DO_UPCAST(BlockDirtyBitmapState,
1940 common, common);
1941 BlockDirtyBitmap *action;
1943 action = common->action->u.block_dirty_bitmap_clear;
1944 state->bitmap = block_dirty_bitmap_lookup(action->node,
1945 action->name,
1946 &state->bs,
1947 &state->aio_context,
1948 errp);
1949 if (!state->bitmap) {
1950 return;
1953 if (bdrv_dirty_bitmap_frozen(state->bitmap)) {
1954 error_setg(errp, "Cannot modify a frozen bitmap");
1955 return;
1956 } else if (!bdrv_dirty_bitmap_enabled(state->bitmap)) {
1957 error_setg(errp, "Cannot clear a disabled bitmap");
1958 return;
1961 bdrv_clear_dirty_bitmap(state->bitmap, &state->backup);
1962 /* AioContext is released in .clean() */
1965 static void block_dirty_bitmap_clear_abort(BlkActionState *common)
1967 BlockDirtyBitmapState *state = DO_UPCAST(BlockDirtyBitmapState,
1968 common, common);
1970 bdrv_undo_clear_dirty_bitmap(state->bitmap, state->backup);
1973 static void block_dirty_bitmap_clear_commit(BlkActionState *common)
1975 BlockDirtyBitmapState *state = DO_UPCAST(BlockDirtyBitmapState,
1976 common, common);
1978 hbitmap_free(state->backup);
1981 static void block_dirty_bitmap_clear_clean(BlkActionState *common)
1983 BlockDirtyBitmapState *state = DO_UPCAST(BlockDirtyBitmapState,
1984 common, common);
1986 if (state->aio_context) {
1987 aio_context_release(state->aio_context);
1991 static void abort_prepare(BlkActionState *common, Error **errp)
1993 error_setg(errp, "Transaction aborted using Abort action");
1996 static void abort_commit(BlkActionState *common)
1998 g_assert_not_reached(); /* this action never succeeds */
2001 static const BlkActionOps actions[] = {
2002 [TRANSACTION_ACTION_KIND_BLOCKDEV_SNAPSHOT] = {
2003 .instance_size = sizeof(ExternalSnapshotState),
2004 .prepare = external_snapshot_prepare,
2005 .commit = external_snapshot_commit,
2006 .abort = external_snapshot_abort,
2008 [TRANSACTION_ACTION_KIND_BLOCKDEV_SNAPSHOT_SYNC] = {
2009 .instance_size = sizeof(ExternalSnapshotState),
2010 .prepare = external_snapshot_prepare,
2011 .commit = external_snapshot_commit,
2012 .abort = external_snapshot_abort,
2013 .clean = external_snapshot_clean,
2015 [TRANSACTION_ACTION_KIND_DRIVE_BACKUP] = {
2016 .instance_size = sizeof(DriveBackupState),
2017 .prepare = drive_backup_prepare,
2018 .abort = drive_backup_abort,
2019 .clean = drive_backup_clean,
2021 [TRANSACTION_ACTION_KIND_BLOCKDEV_BACKUP] = {
2022 .instance_size = sizeof(BlockdevBackupState),
2023 .prepare = blockdev_backup_prepare,
2024 .abort = blockdev_backup_abort,
2025 .clean = blockdev_backup_clean,
2027 [TRANSACTION_ACTION_KIND_ABORT] = {
2028 .instance_size = sizeof(BlkActionState),
2029 .prepare = abort_prepare,
2030 .commit = abort_commit,
2032 [TRANSACTION_ACTION_KIND_BLOCKDEV_SNAPSHOT_INTERNAL_SYNC] = {
2033 .instance_size = sizeof(InternalSnapshotState),
2034 .prepare = internal_snapshot_prepare,
2035 .abort = internal_snapshot_abort,
2036 .clean = internal_snapshot_clean,
2038 [TRANSACTION_ACTION_KIND_BLOCK_DIRTY_BITMAP_ADD] = {
2039 .instance_size = sizeof(BlockDirtyBitmapState),
2040 .prepare = block_dirty_bitmap_add_prepare,
2041 .abort = block_dirty_bitmap_add_abort,
2043 [TRANSACTION_ACTION_KIND_BLOCK_DIRTY_BITMAP_CLEAR] = {
2044 .instance_size = sizeof(BlockDirtyBitmapState),
2045 .prepare = block_dirty_bitmap_clear_prepare,
2046 .commit = block_dirty_bitmap_clear_commit,
2047 .abort = block_dirty_bitmap_clear_abort,
2048 .clean = block_dirty_bitmap_clear_clean,
2053 * 'Atomic' group operations. The operations are performed as a set, and if
2054 * any fail then we roll back all operations in the group.
2056 void qmp_transaction(TransactionActionList *dev_list, Error **errp)
2058 TransactionActionList *dev_entry = dev_list;
2059 BlkActionState *state, *next;
2060 Error *local_err = NULL;
2062 QSIMPLEQ_HEAD(snap_bdrv_states, BlkActionState) snap_bdrv_states;
2063 QSIMPLEQ_INIT(&snap_bdrv_states);
2065 /* drain all i/o before any operations */
2066 bdrv_drain_all();
2068 /* We don't do anything in this loop that commits us to the operations */
2069 while (NULL != dev_entry) {
2070 TransactionAction *dev_info = NULL;
2071 const BlkActionOps *ops;
2073 dev_info = dev_entry->value;
2074 dev_entry = dev_entry->next;
2076 assert(dev_info->type < ARRAY_SIZE(actions));
2078 ops = &actions[dev_info->type];
2079 assert(ops->instance_size > 0);
2081 state = g_malloc0(ops->instance_size);
2082 state->ops = ops;
2083 state->action = dev_info;
2084 QSIMPLEQ_INSERT_TAIL(&snap_bdrv_states, state, entry);
2086 state->ops->prepare(state, &local_err);
2087 if (local_err) {
2088 error_propagate(errp, local_err);
2089 goto delete_and_fail;
2093 QSIMPLEQ_FOREACH(state, &snap_bdrv_states, entry) {
2094 if (state->ops->commit) {
2095 state->ops->commit(state);
2099 /* success */
2100 goto exit;
2102 delete_and_fail:
2103 /* failure, and it is all-or-none; roll back all operations */
2104 QSIMPLEQ_FOREACH(state, &snap_bdrv_states, entry) {
2105 if (state->ops->abort) {
2106 state->ops->abort(state);
2109 exit:
2110 QSIMPLEQ_FOREACH_SAFE(state, &snap_bdrv_states, entry, next) {
2111 if (state->ops->clean) {
2112 state->ops->clean(state);
2114 g_free(state);
2118 void qmp_eject(const char *device, bool has_force, bool force, Error **errp)
2120 Error *local_err = NULL;
2122 qmp_blockdev_open_tray(device, has_force, force, &local_err);
2123 if (local_err) {
2124 error_propagate(errp, local_err);
2125 return;
2128 qmp_blockdev_remove_medium(device, errp);
2131 void qmp_block_passwd(bool has_device, const char *device,
2132 bool has_node_name, const char *node_name,
2133 const char *password, Error **errp)
2135 Error *local_err = NULL;
2136 BlockDriverState *bs;
2137 AioContext *aio_context;
2139 bs = bdrv_lookup_bs(has_device ? device : NULL,
2140 has_node_name ? node_name : NULL,
2141 &local_err);
2142 if (local_err) {
2143 error_propagate(errp, local_err);
2144 return;
2147 aio_context = bdrv_get_aio_context(bs);
2148 aio_context_acquire(aio_context);
2150 bdrv_add_key(bs, password, errp);
2152 aio_context_release(aio_context);
2155 void qmp_blockdev_open_tray(const char *device, bool has_force, bool force,
2156 Error **errp)
2158 BlockBackend *blk;
2159 bool locked;
2161 if (!has_force) {
2162 force = false;
2165 blk = blk_by_name(device);
2166 if (!blk) {
2167 error_set(errp, ERROR_CLASS_DEVICE_NOT_FOUND,
2168 "Device '%s' not found", device);
2169 return;
2172 if (!blk_dev_has_removable_media(blk)) {
2173 error_setg(errp, "Device '%s' is not removable", device);
2174 return;
2177 if (blk_dev_is_tray_open(blk)) {
2178 return;
2181 locked = blk_dev_is_medium_locked(blk);
2182 if (locked) {
2183 blk_dev_eject_request(blk, force);
2186 if (!locked || force) {
2187 blk_dev_change_media_cb(blk, false);
2191 void qmp_blockdev_close_tray(const char *device, Error **errp)
2193 BlockBackend *blk;
2195 blk = blk_by_name(device);
2196 if (!blk) {
2197 error_set(errp, ERROR_CLASS_DEVICE_NOT_FOUND,
2198 "Device '%s' not found", device);
2199 return;
2202 if (!blk_dev_has_removable_media(blk)) {
2203 error_setg(errp, "Device '%s' is not removable", device);
2204 return;
2207 if (!blk_dev_is_tray_open(blk)) {
2208 return;
2211 blk_dev_change_media_cb(blk, true);
2214 void qmp_blockdev_remove_medium(const char *device, Error **errp)
2216 BlockBackend *blk;
2217 BlockDriverState *bs;
2218 AioContext *aio_context;
2219 bool has_device;
2221 blk = blk_by_name(device);
2222 if (!blk) {
2223 error_set(errp, ERROR_CLASS_DEVICE_NOT_FOUND,
2224 "Device '%s' not found", device);
2225 return;
2228 /* For BBs without a device, we can exchange the BDS tree at will */
2229 has_device = blk_get_attached_dev(blk);
2231 if (has_device && !blk_dev_has_removable_media(blk)) {
2232 error_setg(errp, "Device '%s' is not removable", device);
2233 return;
2236 if (has_device && !blk_dev_is_tray_open(blk)) {
2237 error_setg(errp, "Tray of device '%s' is not open", device);
2238 return;
2241 bs = blk_bs(blk);
2242 if (!bs) {
2243 return;
2246 aio_context = bdrv_get_aio_context(bs);
2247 aio_context_acquire(aio_context);
2249 if (bdrv_op_is_blocked(bs, BLOCK_OP_TYPE_EJECT, errp)) {
2250 goto out;
2253 /* This follows the convention established by bdrv_make_anon() */
2254 if (bs->device_list.tqe_prev) {
2255 QTAILQ_REMOVE(&bdrv_states, bs, device_list);
2256 bs->device_list.tqe_prev = NULL;
2259 blk_remove_bs(blk);
2261 out:
2262 aio_context_release(aio_context);
2265 static void qmp_blockdev_insert_anon_medium(const char *device,
2266 BlockDriverState *bs, Error **errp)
2268 BlockBackend *blk;
2269 bool has_device;
2271 blk = blk_by_name(device);
2272 if (!blk) {
2273 error_set(errp, ERROR_CLASS_DEVICE_NOT_FOUND,
2274 "Device '%s' not found", device);
2275 return;
2278 /* For BBs without a device, we can exchange the BDS tree at will */
2279 has_device = blk_get_attached_dev(blk);
2281 if (has_device && !blk_dev_has_removable_media(blk)) {
2282 error_setg(errp, "Device '%s' is not removable", device);
2283 return;
2286 if (has_device && !blk_dev_is_tray_open(blk)) {
2287 error_setg(errp, "Tray of device '%s' is not open", device);
2288 return;
2291 if (blk_bs(blk)) {
2292 error_setg(errp, "There already is a medium in device '%s'", device);
2293 return;
2296 blk_insert_bs(blk, bs);
2298 QTAILQ_INSERT_TAIL(&bdrv_states, bs, device_list);
2301 void qmp_blockdev_insert_medium(const char *device, const char *node_name,
2302 Error **errp)
2304 BlockDriverState *bs;
2306 bs = bdrv_find_node(node_name);
2307 if (!bs) {
2308 error_setg(errp, "Node '%s' not found", node_name);
2309 return;
2312 if (bs->blk) {
2313 error_setg(errp, "Node '%s' is already in use by '%s'", node_name,
2314 blk_name(bs->blk));
2315 return;
2318 qmp_blockdev_insert_anon_medium(device, bs, errp);
2321 void qmp_blockdev_change_medium(const char *device, const char *filename,
2322 bool has_format, const char *format,
2323 bool has_read_only,
2324 BlockdevChangeReadOnlyMode read_only,
2325 Error **errp)
2327 BlockBackend *blk;
2328 BlockDriverState *medium_bs = NULL;
2329 int bdrv_flags, ret;
2330 QDict *options = NULL;
2331 Error *err = NULL;
2333 blk = blk_by_name(device);
2334 if (!blk) {
2335 error_set(errp, ERROR_CLASS_DEVICE_NOT_FOUND,
2336 "Device '%s' not found", device);
2337 goto fail;
2340 if (blk_bs(blk)) {
2341 blk_update_root_state(blk);
2344 bdrv_flags = blk_get_open_flags_from_root_state(blk);
2346 if (!has_read_only) {
2347 read_only = BLOCKDEV_CHANGE_READ_ONLY_MODE_RETAIN;
2350 switch (read_only) {
2351 case BLOCKDEV_CHANGE_READ_ONLY_MODE_RETAIN:
2352 break;
2354 case BLOCKDEV_CHANGE_READ_ONLY_MODE_READ_ONLY:
2355 bdrv_flags &= ~BDRV_O_RDWR;
2356 break;
2358 case BLOCKDEV_CHANGE_READ_ONLY_MODE_READ_WRITE:
2359 bdrv_flags |= BDRV_O_RDWR;
2360 break;
2362 default:
2363 abort();
2366 if (has_format) {
2367 options = qdict_new();
2368 qdict_put(options, "driver", qstring_from_str(format));
2371 assert(!medium_bs);
2372 ret = bdrv_open(&medium_bs, filename, NULL, options, bdrv_flags, errp);
2373 if (ret < 0) {
2374 goto fail;
2377 blk_apply_root_state(blk, medium_bs);
2379 bdrv_add_key(medium_bs, NULL, &err);
2380 if (err) {
2381 error_propagate(errp, err);
2382 goto fail;
2385 qmp_blockdev_open_tray(device, false, false, &err);
2386 if (err) {
2387 error_propagate(errp, err);
2388 goto fail;
2391 qmp_blockdev_remove_medium(device, &err);
2392 if (err) {
2393 error_propagate(errp, err);
2394 goto fail;
2397 qmp_blockdev_insert_anon_medium(device, medium_bs, &err);
2398 if (err) {
2399 error_propagate(errp, err);
2400 goto fail;
2403 qmp_blockdev_close_tray(device, errp);
2405 fail:
2406 /* If the medium has been inserted, the device has its own reference, so
2407 * ours must be relinquished; and if it has not been inserted successfully,
2408 * the reference must be relinquished anyway */
2409 bdrv_unref(medium_bs);
2412 /* throttling disk I/O limits */
2413 void qmp_block_set_io_throttle(const char *device, int64_t bps, int64_t bps_rd,
2414 int64_t bps_wr,
2415 int64_t iops,
2416 int64_t iops_rd,
2417 int64_t iops_wr,
2418 bool has_bps_max,
2419 int64_t bps_max,
2420 bool has_bps_rd_max,
2421 int64_t bps_rd_max,
2422 bool has_bps_wr_max,
2423 int64_t bps_wr_max,
2424 bool has_iops_max,
2425 int64_t iops_max,
2426 bool has_iops_rd_max,
2427 int64_t iops_rd_max,
2428 bool has_iops_wr_max,
2429 int64_t iops_wr_max,
2430 bool has_iops_size,
2431 int64_t iops_size,
2432 bool has_group,
2433 const char *group, Error **errp)
2435 ThrottleConfig cfg;
2436 BlockDriverState *bs;
2437 BlockBackend *blk;
2438 AioContext *aio_context;
2440 blk = blk_by_name(device);
2441 if (!blk) {
2442 error_set(errp, ERROR_CLASS_DEVICE_NOT_FOUND,
2443 "Device '%s' not found", device);
2444 return;
2447 aio_context = blk_get_aio_context(blk);
2448 aio_context_acquire(aio_context);
2450 bs = blk_bs(blk);
2451 if (!bs) {
2452 error_setg(errp, "Device '%s' has no medium", device);
2453 goto out;
2456 memset(&cfg, 0, sizeof(cfg));
2457 cfg.buckets[THROTTLE_BPS_TOTAL].avg = bps;
2458 cfg.buckets[THROTTLE_BPS_READ].avg = bps_rd;
2459 cfg.buckets[THROTTLE_BPS_WRITE].avg = bps_wr;
2461 cfg.buckets[THROTTLE_OPS_TOTAL].avg = iops;
2462 cfg.buckets[THROTTLE_OPS_READ].avg = iops_rd;
2463 cfg.buckets[THROTTLE_OPS_WRITE].avg = iops_wr;
2465 if (has_bps_max) {
2466 cfg.buckets[THROTTLE_BPS_TOTAL].max = bps_max;
2468 if (has_bps_rd_max) {
2469 cfg.buckets[THROTTLE_BPS_READ].max = bps_rd_max;
2471 if (has_bps_wr_max) {
2472 cfg.buckets[THROTTLE_BPS_WRITE].max = bps_wr_max;
2474 if (has_iops_max) {
2475 cfg.buckets[THROTTLE_OPS_TOTAL].max = iops_max;
2477 if (has_iops_rd_max) {
2478 cfg.buckets[THROTTLE_OPS_READ].max = iops_rd_max;
2480 if (has_iops_wr_max) {
2481 cfg.buckets[THROTTLE_OPS_WRITE].max = iops_wr_max;
2484 if (has_iops_size) {
2485 cfg.op_size = iops_size;
2488 if (!check_throttle_config(&cfg, errp)) {
2489 goto out;
2492 if (throttle_enabled(&cfg)) {
2493 /* Enable I/O limits if they're not enabled yet, otherwise
2494 * just update the throttling group. */
2495 if (!bs->throttle_state) {
2496 bdrv_io_limits_enable(bs, has_group ? group : device);
2497 } else if (has_group) {
2498 bdrv_io_limits_update_group(bs, group);
2500 /* Set the new throttling configuration */
2501 bdrv_set_io_limits(bs, &cfg);
2502 } else if (bs->throttle_state) {
2503 /* If all throttling settings are set to 0, disable I/O limits */
2504 bdrv_io_limits_disable(bs);
2507 out:
2508 aio_context_release(aio_context);
2511 void qmp_block_dirty_bitmap_add(const char *node, const char *name,
2512 bool has_granularity, uint32_t granularity,
2513 Error **errp)
2515 AioContext *aio_context;
2516 BlockDriverState *bs;
2518 if (!name || name[0] == '\0') {
2519 error_setg(errp, "Bitmap name cannot be empty");
2520 return;
2523 bs = bdrv_lookup_bs(node, node, errp);
2524 if (!bs) {
2525 return;
2528 aio_context = bdrv_get_aio_context(bs);
2529 aio_context_acquire(aio_context);
2531 if (has_granularity) {
2532 if (granularity < 512 || !is_power_of_2(granularity)) {
2533 error_setg(errp, "Granularity must be power of 2 "
2534 "and at least 512");
2535 goto out;
2537 } else {
2538 /* Default to cluster size, if available: */
2539 granularity = bdrv_get_default_bitmap_granularity(bs);
2542 bdrv_create_dirty_bitmap(bs, granularity, name, errp);
2544 out:
2545 aio_context_release(aio_context);
2548 void qmp_block_dirty_bitmap_remove(const char *node, const char *name,
2549 Error **errp)
2551 AioContext *aio_context;
2552 BlockDriverState *bs;
2553 BdrvDirtyBitmap *bitmap;
2555 bitmap = block_dirty_bitmap_lookup(node, name, &bs, &aio_context, errp);
2556 if (!bitmap || !bs) {
2557 return;
2560 if (bdrv_dirty_bitmap_frozen(bitmap)) {
2561 error_setg(errp,
2562 "Bitmap '%s' is currently frozen and cannot be removed",
2563 name);
2564 goto out;
2566 bdrv_dirty_bitmap_make_anon(bitmap);
2567 bdrv_release_dirty_bitmap(bs, bitmap);
2569 out:
2570 aio_context_release(aio_context);
2574 * Completely clear a bitmap, for the purposes of synchronizing a bitmap
2575 * immediately after a full backup operation.
2577 void qmp_block_dirty_bitmap_clear(const char *node, const char *name,
2578 Error **errp)
2580 AioContext *aio_context;
2581 BdrvDirtyBitmap *bitmap;
2582 BlockDriverState *bs;
2584 bitmap = block_dirty_bitmap_lookup(node, name, &bs, &aio_context, errp);
2585 if (!bitmap || !bs) {
2586 return;
2589 if (bdrv_dirty_bitmap_frozen(bitmap)) {
2590 error_setg(errp,
2591 "Bitmap '%s' is currently frozen and cannot be modified",
2592 name);
2593 goto out;
2594 } else if (!bdrv_dirty_bitmap_enabled(bitmap)) {
2595 error_setg(errp,
2596 "Bitmap '%s' is currently disabled and cannot be cleared",
2597 name);
2598 goto out;
2601 bdrv_clear_dirty_bitmap(bitmap, NULL);
2603 out:
2604 aio_context_release(aio_context);
2607 void hmp_drive_del(Monitor *mon, const QDict *qdict)
2609 const char *id = qdict_get_str(qdict, "id");
2610 BlockBackend *blk;
2611 BlockDriverState *bs;
2612 AioContext *aio_context;
2613 Error *local_err = NULL;
2615 blk = blk_by_name(id);
2616 if (!blk) {
2617 error_report("Device '%s' not found", id);
2618 return;
2621 if (!blk_legacy_dinfo(blk)) {
2622 error_report("Deleting device added with blockdev-add"
2623 " is not supported");
2624 return;
2627 aio_context = blk_get_aio_context(blk);
2628 aio_context_acquire(aio_context);
2630 bs = blk_bs(blk);
2631 if (bs) {
2632 if (bdrv_op_is_blocked(bs, BLOCK_OP_TYPE_DRIVE_DEL, &local_err)) {
2633 error_report_err(local_err);
2634 aio_context_release(aio_context);
2635 return;
2638 bdrv_close(bs);
2641 /* if we have a device attached to this BlockDriverState
2642 * then we need to make the drive anonymous until the device
2643 * can be removed. If this is a drive with no device backing
2644 * then we can just get rid of the block driver state right here.
2646 if (blk_get_attached_dev(blk)) {
2647 blk_hide_on_behalf_of_hmp_drive_del(blk);
2648 /* Further I/O must not pause the guest */
2649 blk_set_on_error(blk, BLOCKDEV_ON_ERROR_REPORT,
2650 BLOCKDEV_ON_ERROR_REPORT);
2651 } else {
2652 blk_unref(blk);
2655 aio_context_release(aio_context);
2658 void qmp_block_resize(bool has_device, const char *device,
2659 bool has_node_name, const char *node_name,
2660 int64_t size, Error **errp)
2662 Error *local_err = NULL;
2663 BlockDriverState *bs;
2664 AioContext *aio_context;
2665 int ret;
2667 bs = bdrv_lookup_bs(has_device ? device : NULL,
2668 has_node_name ? node_name : NULL,
2669 &local_err);
2670 if (local_err) {
2671 error_propagate(errp, local_err);
2672 return;
2675 aio_context = bdrv_get_aio_context(bs);
2676 aio_context_acquire(aio_context);
2678 if (!bdrv_is_first_non_filter(bs)) {
2679 error_setg(errp, QERR_FEATURE_DISABLED, "resize");
2680 goto out;
2683 if (size < 0) {
2684 error_setg(errp, QERR_INVALID_PARAMETER_VALUE, "size", "a >0 size");
2685 goto out;
2688 if (bdrv_op_is_blocked(bs, BLOCK_OP_TYPE_RESIZE, NULL)) {
2689 error_setg(errp, QERR_DEVICE_IN_USE, device);
2690 goto out;
2693 /* complete all in-flight operations before resizing the device */
2694 bdrv_drain_all();
2696 ret = bdrv_truncate(bs, size);
2697 switch (ret) {
2698 case 0:
2699 break;
2700 case -ENOMEDIUM:
2701 error_setg(errp, QERR_DEVICE_HAS_NO_MEDIUM, device);
2702 break;
2703 case -ENOTSUP:
2704 error_setg(errp, QERR_UNSUPPORTED);
2705 break;
2706 case -EACCES:
2707 error_setg(errp, "Device '%s' is read only", device);
2708 break;
2709 case -EBUSY:
2710 error_setg(errp, QERR_DEVICE_IN_USE, device);
2711 break;
2712 default:
2713 error_setg_errno(errp, -ret, "Could not resize");
2714 break;
2717 out:
2718 aio_context_release(aio_context);
2721 static void block_job_cb(void *opaque, int ret)
2723 /* Note that this function may be executed from another AioContext besides
2724 * the QEMU main loop. If you need to access anything that assumes the
2725 * QEMU global mutex, use a BH or introduce a mutex.
2728 BlockDriverState *bs = opaque;
2729 const char *msg = NULL;
2731 trace_block_job_cb(bs, bs->job, ret);
2733 assert(bs->job);
2735 if (ret < 0) {
2736 msg = strerror(-ret);
2739 if (block_job_is_cancelled(bs->job)) {
2740 block_job_event_cancelled(bs->job);
2741 } else {
2742 block_job_event_completed(bs->job, msg);
2745 bdrv_put_ref_bh_schedule(bs);
2748 void qmp_block_stream(const char *device,
2749 bool has_base, const char *base,
2750 bool has_backing_file, const char *backing_file,
2751 bool has_speed, int64_t speed,
2752 bool has_on_error, BlockdevOnError on_error,
2753 Error **errp)
2755 BlockBackend *blk;
2756 BlockDriverState *bs;
2757 BlockDriverState *base_bs = NULL;
2758 AioContext *aio_context;
2759 Error *local_err = NULL;
2760 const char *base_name = NULL;
2762 if (!has_on_error) {
2763 on_error = BLOCKDEV_ON_ERROR_REPORT;
2766 blk = blk_by_name(device);
2767 if (!blk) {
2768 error_set(errp, ERROR_CLASS_DEVICE_NOT_FOUND,
2769 "Device '%s' not found", device);
2770 return;
2773 aio_context = blk_get_aio_context(blk);
2774 aio_context_acquire(aio_context);
2776 if (!blk_is_available(blk)) {
2777 error_setg(errp, "Device '%s' has no medium", device);
2778 goto out;
2780 bs = blk_bs(blk);
2782 if (bdrv_op_is_blocked(bs, BLOCK_OP_TYPE_STREAM, errp)) {
2783 goto out;
2786 if (has_base) {
2787 base_bs = bdrv_find_backing_image(bs, base);
2788 if (base_bs == NULL) {
2789 error_setg(errp, QERR_BASE_NOT_FOUND, base);
2790 goto out;
2792 assert(bdrv_get_aio_context(base_bs) == aio_context);
2793 base_name = base;
2796 /* if we are streaming the entire chain, the result will have no backing
2797 * file, and specifying one is therefore an error */
2798 if (base_bs == NULL && has_backing_file) {
2799 error_setg(errp, "backing file specified, but streaming the "
2800 "entire chain");
2801 goto out;
2804 /* backing_file string overrides base bs filename */
2805 base_name = has_backing_file ? backing_file : base_name;
2807 stream_start(bs, base_bs, base_name, has_speed ? speed : 0,
2808 on_error, block_job_cb, bs, &local_err);
2809 if (local_err) {
2810 error_propagate(errp, local_err);
2811 goto out;
2814 trace_qmp_block_stream(bs, bs->job);
2816 out:
2817 aio_context_release(aio_context);
2820 void qmp_block_commit(const char *device,
2821 bool has_base, const char *base,
2822 bool has_top, const char *top,
2823 bool has_backing_file, const char *backing_file,
2824 bool has_speed, int64_t speed,
2825 Error **errp)
2827 BlockBackend *blk;
2828 BlockDriverState *bs;
2829 BlockDriverState *base_bs, *top_bs;
2830 AioContext *aio_context;
2831 Error *local_err = NULL;
2832 /* This will be part of the QMP command, if/when the
2833 * BlockdevOnError change for blkmirror makes it in
2835 BlockdevOnError on_error = BLOCKDEV_ON_ERROR_REPORT;
2837 if (!has_speed) {
2838 speed = 0;
2841 /* Important Note:
2842 * libvirt relies on the DeviceNotFound error class in order to probe for
2843 * live commit feature versions; for this to work, we must make sure to
2844 * perform the device lookup before any generic errors that may occur in a
2845 * scenario in which all optional arguments are omitted. */
2846 blk = blk_by_name(device);
2847 if (!blk) {
2848 error_set(errp, ERROR_CLASS_DEVICE_NOT_FOUND,
2849 "Device '%s' not found", device);
2850 return;
2853 aio_context = blk_get_aio_context(blk);
2854 aio_context_acquire(aio_context);
2856 if (!blk_is_available(blk)) {
2857 error_setg(errp, "Device '%s' has no medium", device);
2858 goto out;
2860 bs = blk_bs(blk);
2862 if (bdrv_op_is_blocked(bs, BLOCK_OP_TYPE_COMMIT_SOURCE, errp)) {
2863 goto out;
2866 /* default top_bs is the active layer */
2867 top_bs = bs;
2869 if (has_top && top) {
2870 if (strcmp(bs->filename, top) != 0) {
2871 top_bs = bdrv_find_backing_image(bs, top);
2875 if (top_bs == NULL) {
2876 error_setg(errp, "Top image file %s not found", top ? top : "NULL");
2877 goto out;
2880 assert(bdrv_get_aio_context(top_bs) == aio_context);
2882 if (has_base && base) {
2883 base_bs = bdrv_find_backing_image(top_bs, base);
2884 } else {
2885 base_bs = bdrv_find_base(top_bs);
2888 if (base_bs == NULL) {
2889 error_setg(errp, QERR_BASE_NOT_FOUND, base ? base : "NULL");
2890 goto out;
2893 assert(bdrv_get_aio_context(base_bs) == aio_context);
2895 if (bdrv_op_is_blocked(base_bs, BLOCK_OP_TYPE_COMMIT_TARGET, errp)) {
2896 goto out;
2899 /* Do not allow attempts to commit an image into itself */
2900 if (top_bs == base_bs) {
2901 error_setg(errp, "cannot commit an image into itself");
2902 goto out;
2905 if (top_bs == bs) {
2906 if (has_backing_file) {
2907 error_setg(errp, "'backing-file' specified,"
2908 " but 'top' is the active layer");
2909 goto out;
2911 commit_active_start(bs, base_bs, speed, on_error, block_job_cb,
2912 bs, &local_err);
2913 } else {
2914 commit_start(bs, base_bs, top_bs, speed, on_error, block_job_cb, bs,
2915 has_backing_file ? backing_file : NULL, &local_err);
2917 if (local_err != NULL) {
2918 error_propagate(errp, local_err);
2919 goto out;
2922 out:
2923 aio_context_release(aio_context);
2926 void qmp_drive_backup(const char *device, const char *target,
2927 bool has_format, const char *format,
2928 enum MirrorSyncMode sync,
2929 bool has_mode, enum NewImageMode mode,
2930 bool has_speed, int64_t speed,
2931 bool has_bitmap, const char *bitmap,
2932 bool has_on_source_error, BlockdevOnError on_source_error,
2933 bool has_on_target_error, BlockdevOnError on_target_error,
2934 Error **errp)
2936 BlockBackend *blk;
2937 BlockDriverState *bs;
2938 BlockDriverState *target_bs;
2939 BlockDriverState *source = NULL;
2940 BdrvDirtyBitmap *bmap = NULL;
2941 AioContext *aio_context;
2942 QDict *options = NULL;
2943 Error *local_err = NULL;
2944 int flags;
2945 int64_t size;
2946 int ret;
2948 if (!has_speed) {
2949 speed = 0;
2951 if (!has_on_source_error) {
2952 on_source_error = BLOCKDEV_ON_ERROR_REPORT;
2954 if (!has_on_target_error) {
2955 on_target_error = BLOCKDEV_ON_ERROR_REPORT;
2957 if (!has_mode) {
2958 mode = NEW_IMAGE_MODE_ABSOLUTE_PATHS;
2961 blk = blk_by_name(device);
2962 if (!blk) {
2963 error_set(errp, ERROR_CLASS_DEVICE_NOT_FOUND,
2964 "Device '%s' not found", device);
2965 return;
2968 aio_context = blk_get_aio_context(blk);
2969 aio_context_acquire(aio_context);
2971 /* Although backup_run has this check too, we need to use bs->drv below, so
2972 * do an early check redundantly. */
2973 if (!blk_is_available(blk)) {
2974 error_setg(errp, QERR_DEVICE_HAS_NO_MEDIUM, device);
2975 goto out;
2977 bs = blk_bs(blk);
2979 if (!has_format) {
2980 format = mode == NEW_IMAGE_MODE_EXISTING ? NULL : bs->drv->format_name;
2983 /* Early check to avoid creating target */
2984 if (bdrv_op_is_blocked(bs, BLOCK_OP_TYPE_BACKUP_SOURCE, errp)) {
2985 goto out;
2988 flags = bs->open_flags | BDRV_O_RDWR;
2990 /* See if we have a backing HD we can use to create our new image
2991 * on top of. */
2992 if (sync == MIRROR_SYNC_MODE_TOP) {
2993 source = backing_bs(bs);
2994 if (!source) {
2995 sync = MIRROR_SYNC_MODE_FULL;
2998 if (sync == MIRROR_SYNC_MODE_NONE) {
2999 source = bs;
3002 size = bdrv_getlength(bs);
3003 if (size < 0) {
3004 error_setg_errno(errp, -size, "bdrv_getlength failed");
3005 goto out;
3008 if (mode != NEW_IMAGE_MODE_EXISTING) {
3009 assert(format);
3010 if (source) {
3011 bdrv_img_create(target, format, source->filename,
3012 source->drv->format_name, NULL,
3013 size, flags, &local_err, false);
3014 } else {
3015 bdrv_img_create(target, format, NULL, NULL, NULL,
3016 size, flags, &local_err, false);
3020 if (local_err) {
3021 error_propagate(errp, local_err);
3022 goto out;
3025 if (format) {
3026 options = qdict_new();
3027 qdict_put(options, "driver", qstring_from_str(format));
3030 target_bs = NULL;
3031 ret = bdrv_open(&target_bs, target, NULL, options, flags, &local_err);
3032 if (ret < 0) {
3033 error_propagate(errp, local_err);
3034 goto out;
3037 bdrv_set_aio_context(target_bs, aio_context);
3039 if (has_bitmap) {
3040 bmap = bdrv_find_dirty_bitmap(bs, bitmap);
3041 if (!bmap) {
3042 error_setg(errp, "Bitmap '%s' could not be found", bitmap);
3043 goto out;
3047 backup_start(bs, target_bs, speed, sync, bmap,
3048 on_source_error, on_target_error,
3049 block_job_cb, bs, &local_err);
3050 if (local_err != NULL) {
3051 bdrv_unref(target_bs);
3052 error_propagate(errp, local_err);
3053 goto out;
3056 out:
3057 aio_context_release(aio_context);
3060 BlockDeviceInfoList *qmp_query_named_block_nodes(Error **errp)
3062 return bdrv_named_nodes_list(errp);
3065 void qmp_blockdev_backup(const char *device, const char *target,
3066 enum MirrorSyncMode sync,
3067 bool has_speed, int64_t speed,
3068 bool has_on_source_error,
3069 BlockdevOnError on_source_error,
3070 bool has_on_target_error,
3071 BlockdevOnError on_target_error,
3072 Error **errp)
3074 BlockBackend *blk, *target_blk;
3075 BlockDriverState *bs;
3076 BlockDriverState *target_bs;
3077 Error *local_err = NULL;
3078 AioContext *aio_context;
3080 if (!has_speed) {
3081 speed = 0;
3083 if (!has_on_source_error) {
3084 on_source_error = BLOCKDEV_ON_ERROR_REPORT;
3086 if (!has_on_target_error) {
3087 on_target_error = BLOCKDEV_ON_ERROR_REPORT;
3090 blk = blk_by_name(device);
3091 if (!blk) {
3092 error_setg(errp, "Device '%s' not found", device);
3093 return;
3096 aio_context = blk_get_aio_context(blk);
3097 aio_context_acquire(aio_context);
3099 if (!blk_is_available(blk)) {
3100 error_setg(errp, "Device '%s' has no medium", device);
3101 goto out;
3103 bs = blk_bs(blk);
3105 target_blk = blk_by_name(target);
3106 if (!target_blk) {
3107 error_setg(errp, "Device '%s' not found", target);
3108 goto out;
3111 if (!blk_is_available(target_blk)) {
3112 error_setg(errp, "Device '%s' has no medium", target);
3113 goto out;
3115 target_bs = blk_bs(target_blk);
3117 bdrv_ref(target_bs);
3118 bdrv_set_aio_context(target_bs, aio_context);
3119 backup_start(bs, target_bs, speed, sync, NULL, on_source_error,
3120 on_target_error, block_job_cb, bs, &local_err);
3121 if (local_err != NULL) {
3122 bdrv_unref(target_bs);
3123 error_propagate(errp, local_err);
3125 out:
3126 aio_context_release(aio_context);
3129 void qmp_drive_mirror(const char *device, const char *target,
3130 bool has_format, const char *format,
3131 bool has_node_name, const char *node_name,
3132 bool has_replaces, const char *replaces,
3133 enum MirrorSyncMode sync,
3134 bool has_mode, enum NewImageMode mode,
3135 bool has_speed, int64_t speed,
3136 bool has_granularity, uint32_t granularity,
3137 bool has_buf_size, int64_t buf_size,
3138 bool has_on_source_error, BlockdevOnError on_source_error,
3139 bool has_on_target_error, BlockdevOnError on_target_error,
3140 bool has_unmap, bool unmap,
3141 Error **errp)
3143 BlockBackend *blk;
3144 BlockDriverState *bs;
3145 BlockDriverState *source, *target_bs;
3146 AioContext *aio_context;
3147 Error *local_err = NULL;
3148 QDict *options;
3149 int flags;
3150 int64_t size;
3151 int ret;
3153 if (!has_speed) {
3154 speed = 0;
3156 if (!has_on_source_error) {
3157 on_source_error = BLOCKDEV_ON_ERROR_REPORT;
3159 if (!has_on_target_error) {
3160 on_target_error = BLOCKDEV_ON_ERROR_REPORT;
3162 if (!has_mode) {
3163 mode = NEW_IMAGE_MODE_ABSOLUTE_PATHS;
3165 if (!has_granularity) {
3166 granularity = 0;
3168 if (!has_buf_size) {
3169 buf_size = 0;
3171 if (!has_unmap) {
3172 unmap = true;
3175 if (granularity != 0 && (granularity < 512 || granularity > 1048576 * 64)) {
3176 error_setg(errp, QERR_INVALID_PARAMETER_VALUE, "granularity",
3177 "a value in range [512B, 64MB]");
3178 return;
3180 if (granularity & (granularity - 1)) {
3181 error_setg(errp, QERR_INVALID_PARAMETER_VALUE, "granularity",
3182 "power of 2");
3183 return;
3186 blk = blk_by_name(device);
3187 if (!blk) {
3188 error_set(errp, ERROR_CLASS_DEVICE_NOT_FOUND,
3189 "Device '%s' not found", device);
3190 return;
3193 aio_context = blk_get_aio_context(blk);
3194 aio_context_acquire(aio_context);
3196 if (!blk_is_available(blk)) {
3197 error_setg(errp, QERR_DEVICE_HAS_NO_MEDIUM, device);
3198 goto out;
3200 bs = blk_bs(blk);
3202 if (!has_format) {
3203 format = mode == NEW_IMAGE_MODE_EXISTING ? NULL : bs->drv->format_name;
3206 if (bdrv_op_is_blocked(bs, BLOCK_OP_TYPE_MIRROR, errp)) {
3207 goto out;
3210 flags = bs->open_flags | BDRV_O_RDWR;
3211 source = backing_bs(bs);
3212 if (!source && sync == MIRROR_SYNC_MODE_TOP) {
3213 sync = MIRROR_SYNC_MODE_FULL;
3215 if (sync == MIRROR_SYNC_MODE_NONE) {
3216 source = bs;
3219 size = bdrv_getlength(bs);
3220 if (size < 0) {
3221 error_setg_errno(errp, -size, "bdrv_getlength failed");
3222 goto out;
3225 if (has_replaces) {
3226 BlockDriverState *to_replace_bs;
3227 AioContext *replace_aio_context;
3228 int64_t replace_size;
3230 if (!has_node_name) {
3231 error_setg(errp, "a node-name must be provided when replacing a"
3232 " named node of the graph");
3233 goto out;
3236 to_replace_bs = check_to_replace_node(bs, replaces, &local_err);
3238 if (!to_replace_bs) {
3239 error_propagate(errp, local_err);
3240 goto out;
3243 replace_aio_context = bdrv_get_aio_context(to_replace_bs);
3244 aio_context_acquire(replace_aio_context);
3245 replace_size = bdrv_getlength(to_replace_bs);
3246 aio_context_release(replace_aio_context);
3248 if (size != replace_size) {
3249 error_setg(errp, "cannot replace image with a mirror image of "
3250 "different size");
3251 goto out;
3255 if ((sync == MIRROR_SYNC_MODE_FULL || !source)
3256 && mode != NEW_IMAGE_MODE_EXISTING)
3258 /* create new image w/o backing file */
3259 assert(format);
3260 bdrv_img_create(target, format,
3261 NULL, NULL, NULL, size, flags, &local_err, false);
3262 } else {
3263 switch (mode) {
3264 case NEW_IMAGE_MODE_EXISTING:
3265 break;
3266 case NEW_IMAGE_MODE_ABSOLUTE_PATHS:
3267 /* create new image with backing file */
3268 bdrv_img_create(target, format,
3269 source->filename,
3270 source->drv->format_name,
3271 NULL, size, flags, &local_err, false);
3272 break;
3273 default:
3274 abort();
3278 if (local_err) {
3279 error_propagate(errp, local_err);
3280 goto out;
3283 options = qdict_new();
3284 if (has_node_name) {
3285 qdict_put(options, "node-name", qstring_from_str(node_name));
3287 if (format) {
3288 qdict_put(options, "driver", qstring_from_str(format));
3291 /* Mirroring takes care of copy-on-write using the source's backing
3292 * file.
3294 target_bs = NULL;
3295 ret = bdrv_open(&target_bs, target, NULL, options,
3296 flags | BDRV_O_NO_BACKING, &local_err);
3297 if (ret < 0) {
3298 error_propagate(errp, local_err);
3299 goto out;
3302 bdrv_set_aio_context(target_bs, aio_context);
3304 /* pass the node name to replace to mirror start since it's loose coupling
3305 * and will allow to check whether the node still exist at mirror completion
3307 mirror_start(bs, target_bs,
3308 has_replaces ? replaces : NULL,
3309 speed, granularity, buf_size, sync,
3310 on_source_error, on_target_error,
3311 unmap,
3312 block_job_cb, bs, &local_err);
3313 if (local_err != NULL) {
3314 bdrv_unref(target_bs);
3315 error_propagate(errp, local_err);
3316 goto out;
3319 out:
3320 aio_context_release(aio_context);
3323 /* Get the block job for a given device name and acquire its AioContext */
3324 static BlockJob *find_block_job(const char *device, AioContext **aio_context,
3325 Error **errp)
3327 BlockBackend *blk;
3328 BlockDriverState *bs;
3330 *aio_context = NULL;
3332 blk = blk_by_name(device);
3333 if (!blk) {
3334 goto notfound;
3337 *aio_context = blk_get_aio_context(blk);
3338 aio_context_acquire(*aio_context);
3340 if (!blk_is_available(blk)) {
3341 goto notfound;
3343 bs = blk_bs(blk);
3345 if (!bs->job) {
3346 goto notfound;
3349 return bs->job;
3351 notfound:
3352 error_set(errp, ERROR_CLASS_DEVICE_NOT_ACTIVE,
3353 "No active block job on device '%s'", device);
3354 if (*aio_context) {
3355 aio_context_release(*aio_context);
3356 *aio_context = NULL;
3358 return NULL;
3361 void qmp_block_job_set_speed(const char *device, int64_t speed, Error **errp)
3363 AioContext *aio_context;
3364 BlockJob *job = find_block_job(device, &aio_context, errp);
3366 if (!job) {
3367 return;
3370 block_job_set_speed(job, speed, errp);
3371 aio_context_release(aio_context);
3374 void qmp_block_job_cancel(const char *device,
3375 bool has_force, bool force, Error **errp)
3377 AioContext *aio_context;
3378 BlockJob *job = find_block_job(device, &aio_context, errp);
3380 if (!job) {
3381 return;
3384 if (!has_force) {
3385 force = false;
3388 if (job->user_paused && !force) {
3389 error_setg(errp, "The block job for device '%s' is currently paused",
3390 device);
3391 goto out;
3394 trace_qmp_block_job_cancel(job);
3395 block_job_cancel(job);
3396 out:
3397 aio_context_release(aio_context);
3400 void qmp_block_job_pause(const char *device, Error **errp)
3402 AioContext *aio_context;
3403 BlockJob *job = find_block_job(device, &aio_context, errp);
3405 if (!job || job->user_paused) {
3406 return;
3409 job->user_paused = true;
3410 trace_qmp_block_job_pause(job);
3411 block_job_pause(job);
3412 aio_context_release(aio_context);
3415 void qmp_block_job_resume(const char *device, Error **errp)
3417 AioContext *aio_context;
3418 BlockJob *job = find_block_job(device, &aio_context, errp);
3420 if (!job || !job->user_paused) {
3421 return;
3424 job->user_paused = false;
3425 trace_qmp_block_job_resume(job);
3426 block_job_resume(job);
3427 aio_context_release(aio_context);
3430 void qmp_block_job_complete(const char *device, Error **errp)
3432 AioContext *aio_context;
3433 BlockJob *job = find_block_job(device, &aio_context, errp);
3435 if (!job) {
3436 return;
3439 trace_qmp_block_job_complete(job);
3440 block_job_complete(job, errp);
3441 aio_context_release(aio_context);
3444 void qmp_change_backing_file(const char *device,
3445 const char *image_node_name,
3446 const char *backing_file,
3447 Error **errp)
3449 BlockBackend *blk;
3450 BlockDriverState *bs = NULL;
3451 AioContext *aio_context;
3452 BlockDriverState *image_bs = NULL;
3453 Error *local_err = NULL;
3454 bool ro;
3455 int open_flags;
3456 int ret;
3458 blk = blk_by_name(device);
3459 if (!blk) {
3460 error_set(errp, ERROR_CLASS_DEVICE_NOT_FOUND,
3461 "Device '%s' not found", device);
3462 return;
3465 aio_context = blk_get_aio_context(blk);
3466 aio_context_acquire(aio_context);
3468 if (!blk_is_available(blk)) {
3469 error_setg(errp, "Device '%s' has no medium", device);
3470 goto out;
3472 bs = blk_bs(blk);
3474 image_bs = bdrv_lookup_bs(NULL, image_node_name, &local_err);
3475 if (local_err) {
3476 error_propagate(errp, local_err);
3477 goto out;
3480 if (!image_bs) {
3481 error_setg(errp, "image file not found");
3482 goto out;
3485 if (bdrv_find_base(image_bs) == image_bs) {
3486 error_setg(errp, "not allowing backing file change on an image "
3487 "without a backing file");
3488 goto out;
3491 /* even though we are not necessarily operating on bs, we need it to
3492 * determine if block ops are currently prohibited on the chain */
3493 if (bdrv_op_is_blocked(bs, BLOCK_OP_TYPE_CHANGE, errp)) {
3494 goto out;
3497 /* final sanity check */
3498 if (!bdrv_chain_contains(bs, image_bs)) {
3499 error_setg(errp, "'%s' and image file are not in the same chain",
3500 device);
3501 goto out;
3504 /* if not r/w, reopen to make r/w */
3505 open_flags = image_bs->open_flags;
3506 ro = bdrv_is_read_only(image_bs);
3508 if (ro) {
3509 bdrv_reopen(image_bs, open_flags | BDRV_O_RDWR, &local_err);
3510 if (local_err) {
3511 error_propagate(errp, local_err);
3512 goto out;
3516 ret = bdrv_change_backing_file(image_bs, backing_file,
3517 image_bs->drv ? image_bs->drv->format_name : "");
3519 if (ret < 0) {
3520 error_setg_errno(errp, -ret, "Could not change backing file to '%s'",
3521 backing_file);
3522 /* don't exit here, so we can try to restore open flags if
3523 * appropriate */
3526 if (ro) {
3527 bdrv_reopen(image_bs, open_flags, &local_err);
3528 if (local_err) {
3529 error_propagate(errp, local_err); /* will preserve prior errp */
3533 out:
3534 aio_context_release(aio_context);
3537 void qmp_blockdev_add(BlockdevOptions *options, Error **errp)
3539 QmpOutputVisitor *ov = qmp_output_visitor_new();
3540 BlockDriverState *bs;
3541 BlockBackend *blk = NULL;
3542 QObject *obj;
3543 QDict *qdict;
3544 Error *local_err = NULL;
3546 /* TODO Sort it out in raw-posix and drive_new(): Reject aio=native with
3547 * cache.direct=false instead of silently switching to aio=threads, except
3548 * when called from drive_new().
3550 * For now, simply forbidding the combination for all drivers will do. */
3551 if (options->has_aio && options->aio == BLOCKDEV_AIO_OPTIONS_NATIVE) {
3552 bool direct = options->has_cache &&
3553 options->cache->has_direct &&
3554 options->cache->direct;
3555 if (!direct) {
3556 error_setg(errp, "aio=native requires cache.direct=true");
3557 goto fail;
3561 visit_type_BlockdevOptions(qmp_output_get_visitor(ov),
3562 &options, NULL, &local_err);
3563 if (local_err) {
3564 error_propagate(errp, local_err);
3565 goto fail;
3568 obj = qmp_output_get_qobject(ov);
3569 qdict = qobject_to_qdict(obj);
3571 qdict_flatten(qdict);
3573 if (options->has_id) {
3574 blk = blockdev_init(NULL, qdict, &local_err);
3575 if (local_err) {
3576 error_propagate(errp, local_err);
3577 goto fail;
3580 bs = blk_bs(blk);
3581 } else {
3582 if (!qdict_get_try_str(qdict, "node-name")) {
3583 error_setg(errp, "'id' and/or 'node-name' need to be specified for "
3584 "the root node");
3585 goto fail;
3588 bs = bds_tree_init(qdict, errp);
3589 if (!bs) {
3590 goto fail;
3594 if (bs && bdrv_key_required(bs)) {
3595 if (blk) {
3596 blk_unref(blk);
3597 } else {
3598 bdrv_unref(bs);
3600 error_setg(errp, "blockdev-add doesn't support encrypted devices");
3601 goto fail;
3604 fail:
3605 qmp_output_visitor_cleanup(ov);
3608 void qmp_x_blockdev_del(bool has_id, const char *id,
3609 bool has_node_name, const char *node_name, Error **errp)
3611 AioContext *aio_context;
3612 BlockBackend *blk;
3613 BlockDriverState *bs;
3615 if (has_id && has_node_name) {
3616 error_setg(errp, "Only one of id and node-name must be specified");
3617 return;
3618 } else if (!has_id && !has_node_name) {
3619 error_setg(errp, "No block device specified");
3620 return;
3623 if (has_id) {
3624 blk = blk_by_name(id);
3625 if (!blk) {
3626 error_setg(errp, "Cannot find block backend %s", id);
3627 return;
3629 if (blk_get_refcnt(blk) > 1) {
3630 error_setg(errp, "Block backend %s is in use", id);
3631 return;
3633 bs = blk_bs(blk);
3634 aio_context = blk_get_aio_context(blk);
3635 } else {
3636 bs = bdrv_find_node(node_name);
3637 if (!bs) {
3638 error_setg(errp, "Cannot find node %s", node_name);
3639 return;
3641 blk = bs->blk;
3642 if (blk) {
3643 error_setg(errp, "Node %s is in use by %s",
3644 node_name, blk_name(blk));
3645 return;
3647 aio_context = bdrv_get_aio_context(bs);
3650 aio_context_acquire(aio_context);
3652 if (bs) {
3653 if (bdrv_op_is_blocked(bs, BLOCK_OP_TYPE_DRIVE_DEL, errp)) {
3654 goto out;
3657 if (bs->refcnt > 1 || !QLIST_EMPTY(&bs->parents)) {
3658 error_setg(errp, "Block device %s is in use",
3659 bdrv_get_device_or_node_name(bs));
3660 goto out;
3664 if (blk) {
3665 blk_unref(blk);
3666 } else {
3667 bdrv_unref(bs);
3670 out:
3671 aio_context_release(aio_context);
3674 BlockJobInfoList *qmp_query_block_jobs(Error **errp)
3676 BlockJobInfoList *head = NULL, **p_next = &head;
3677 BlockDriverState *bs;
3679 for (bs = bdrv_next(NULL); bs; bs = bdrv_next(bs)) {
3680 AioContext *aio_context = bdrv_get_aio_context(bs);
3682 aio_context_acquire(aio_context);
3684 if (bs->job) {
3685 BlockJobInfoList *elem = g_new0(BlockJobInfoList, 1);
3686 elem->value = block_job_query(bs->job);
3687 *p_next = elem;
3688 p_next = &elem->next;
3691 aio_context_release(aio_context);
3694 return head;
3697 QemuOptsList qemu_common_drive_opts = {
3698 .name = "drive",
3699 .head = QTAILQ_HEAD_INITIALIZER(qemu_common_drive_opts.head),
3700 .desc = {
3702 .name = "snapshot",
3703 .type = QEMU_OPT_BOOL,
3704 .help = "enable/disable snapshot mode",
3706 .name = "discard",
3707 .type = QEMU_OPT_STRING,
3708 .help = "discard operation (ignore/off, unmap/on)",
3710 .name = BDRV_OPT_CACHE_WB,
3711 .type = QEMU_OPT_BOOL,
3712 .help = "enables writeback mode for any caches",
3714 .name = BDRV_OPT_CACHE_DIRECT,
3715 .type = QEMU_OPT_BOOL,
3716 .help = "enables use of O_DIRECT (bypass the host page cache)",
3718 .name = BDRV_OPT_CACHE_NO_FLUSH,
3719 .type = QEMU_OPT_BOOL,
3720 .help = "ignore any flush requests for the device",
3722 .name = "aio",
3723 .type = QEMU_OPT_STRING,
3724 .help = "host AIO implementation (threads, native)",
3726 .name = "format",
3727 .type = QEMU_OPT_STRING,
3728 .help = "disk format (raw, qcow2, ...)",
3730 .name = "rerror",
3731 .type = QEMU_OPT_STRING,
3732 .help = "read error action",
3734 .name = "werror",
3735 .type = QEMU_OPT_STRING,
3736 .help = "write error action",
3738 .name = "read-only",
3739 .type = QEMU_OPT_BOOL,
3740 .help = "open drive file as read-only",
3742 .name = "throttling.iops-total",
3743 .type = QEMU_OPT_NUMBER,
3744 .help = "limit total I/O operations per second",
3746 .name = "throttling.iops-read",
3747 .type = QEMU_OPT_NUMBER,
3748 .help = "limit read operations per second",
3750 .name = "throttling.iops-write",
3751 .type = QEMU_OPT_NUMBER,
3752 .help = "limit write operations per second",
3754 .name = "throttling.bps-total",
3755 .type = QEMU_OPT_NUMBER,
3756 .help = "limit total bytes per second",
3758 .name = "throttling.bps-read",
3759 .type = QEMU_OPT_NUMBER,
3760 .help = "limit read bytes per second",
3762 .name = "throttling.bps-write",
3763 .type = QEMU_OPT_NUMBER,
3764 .help = "limit write bytes per second",
3766 .name = "throttling.iops-total-max",
3767 .type = QEMU_OPT_NUMBER,
3768 .help = "I/O operations burst",
3770 .name = "throttling.iops-read-max",
3771 .type = QEMU_OPT_NUMBER,
3772 .help = "I/O operations read burst",
3774 .name = "throttling.iops-write-max",
3775 .type = QEMU_OPT_NUMBER,
3776 .help = "I/O operations write burst",
3778 .name = "throttling.bps-total-max",
3779 .type = QEMU_OPT_NUMBER,
3780 .help = "total bytes burst",
3782 .name = "throttling.bps-read-max",
3783 .type = QEMU_OPT_NUMBER,
3784 .help = "total bytes read burst",
3786 .name = "throttling.bps-write-max",
3787 .type = QEMU_OPT_NUMBER,
3788 .help = "total bytes write burst",
3790 .name = "throttling.iops-size",
3791 .type = QEMU_OPT_NUMBER,
3792 .help = "when limiting by iops max size of an I/O in bytes",
3794 .name = "throttling.group",
3795 .type = QEMU_OPT_STRING,
3796 .help = "name of the block throttling group",
3798 .name = "copy-on-read",
3799 .type = QEMU_OPT_BOOL,
3800 .help = "copy read data from backing file into image file",
3802 .name = "detect-zeroes",
3803 .type = QEMU_OPT_STRING,
3804 .help = "try to optimize zero writes (off, on, unmap)",
3806 { /* end of list */ }
3810 static QemuOptsList qemu_root_bds_opts = {
3811 .name = "root-bds",
3812 .head = QTAILQ_HEAD_INITIALIZER(qemu_common_drive_opts.head),
3813 .desc = {
3815 .name = "discard",
3816 .type = QEMU_OPT_STRING,
3817 .help = "discard operation (ignore/off, unmap/on)",
3819 .name = "cache.writeback",
3820 .type = QEMU_OPT_BOOL,
3821 .help = "enables writeback mode for any caches",
3823 .name = "cache.direct",
3824 .type = QEMU_OPT_BOOL,
3825 .help = "enables use of O_DIRECT (bypass the host page cache)",
3827 .name = "cache.no-flush",
3828 .type = QEMU_OPT_BOOL,
3829 .help = "ignore any flush requests for the device",
3831 .name = "aio",
3832 .type = QEMU_OPT_STRING,
3833 .help = "host AIO implementation (threads, native)",
3835 .name = "read-only",
3836 .type = QEMU_OPT_BOOL,
3837 .help = "open drive file as read-only",
3839 .name = "copy-on-read",
3840 .type = QEMU_OPT_BOOL,
3841 .help = "copy read data from backing file into image file",
3843 .name = "detect-zeroes",
3844 .type = QEMU_OPT_STRING,
3845 .help = "try to optimize zero writes (off, on, unmap)",
3847 { /* end of list */ }
3851 QemuOptsList qemu_drive_opts = {
3852 .name = "drive",
3853 .head = QTAILQ_HEAD_INITIALIZER(qemu_drive_opts.head),
3854 .desc = {
3856 * no elements => accept any params
3857 * validation will happen later
3859 { /* end of list */ }