Host page!=target page: Cleanup bitmaps
[qemu/cris-port.git] / blockdev.c
blob97be42f6cd43ee4d8c43628d30976207e0b72b8a
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 BlockdevSnapshot 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_internal_sync(const char *device,
1189 const char *name,
1190 Error **errp)
1192 BlockdevSnapshotInternal snapshot = {
1193 .device = (char *) device,
1194 .name = (char *) name
1197 blockdev_do_action(TRANSACTION_ACTION_KIND_BLOCKDEV_SNAPSHOT_INTERNAL_SYNC,
1198 &snapshot, errp);
1201 SnapshotInfo *qmp_blockdev_snapshot_delete_internal_sync(const char *device,
1202 bool has_id,
1203 const char *id,
1204 bool has_name,
1205 const char *name,
1206 Error **errp)
1208 BlockDriverState *bs;
1209 BlockBackend *blk;
1210 AioContext *aio_context;
1211 QEMUSnapshotInfo sn;
1212 Error *local_err = NULL;
1213 SnapshotInfo *info = NULL;
1214 int ret;
1216 blk = blk_by_name(device);
1217 if (!blk) {
1218 error_set(errp, ERROR_CLASS_DEVICE_NOT_FOUND,
1219 "Device '%s' not found", device);
1220 return NULL;
1223 aio_context = blk_get_aio_context(blk);
1224 aio_context_acquire(aio_context);
1226 if (!has_id) {
1227 id = NULL;
1230 if (!has_name) {
1231 name = NULL;
1234 if (!id && !name) {
1235 error_setg(errp, "Name or id must be provided");
1236 goto out_aio_context;
1239 if (!blk_is_available(blk)) {
1240 error_setg(errp, "Device '%s' has no medium", device);
1241 goto out_aio_context;
1243 bs = blk_bs(blk);
1245 if (bdrv_op_is_blocked(bs, BLOCK_OP_TYPE_INTERNAL_SNAPSHOT_DELETE, errp)) {
1246 goto out_aio_context;
1249 ret = bdrv_snapshot_find_by_id_and_name(bs, id, name, &sn, &local_err);
1250 if (local_err) {
1251 error_propagate(errp, local_err);
1252 goto out_aio_context;
1254 if (!ret) {
1255 error_setg(errp,
1256 "Snapshot with id '%s' and name '%s' does not exist on "
1257 "device '%s'",
1258 STR_OR_NULL(id), STR_OR_NULL(name), device);
1259 goto out_aio_context;
1262 bdrv_snapshot_delete(bs, id, name, &local_err);
1263 if (local_err) {
1264 error_propagate(errp, local_err);
1265 goto out_aio_context;
1268 aio_context_release(aio_context);
1270 info = g_new0(SnapshotInfo, 1);
1271 info->id = g_strdup(sn.id_str);
1272 info->name = g_strdup(sn.name);
1273 info->date_nsec = sn.date_nsec;
1274 info->date_sec = sn.date_sec;
1275 info->vm_state_size = sn.vm_state_size;
1276 info->vm_clock_nsec = sn.vm_clock_nsec % 1000000000;
1277 info->vm_clock_sec = sn.vm_clock_nsec / 1000000000;
1279 return info;
1281 out_aio_context:
1282 aio_context_release(aio_context);
1283 return NULL;
1287 * block_dirty_bitmap_lookup:
1288 * Return a dirty bitmap (if present), after validating
1289 * the node reference and bitmap names.
1291 * @node: The name of the BDS node to search for bitmaps
1292 * @name: The name of the bitmap to search for
1293 * @pbs: Output pointer for BDS lookup, if desired. Can be NULL.
1294 * @paio: Output pointer for aio_context acquisition, if desired. Can be NULL.
1295 * @errp: Output pointer for error information. Can be NULL.
1297 * @return: A bitmap object on success, or NULL on failure.
1299 static BdrvDirtyBitmap *block_dirty_bitmap_lookup(const char *node,
1300 const char *name,
1301 BlockDriverState **pbs,
1302 AioContext **paio,
1303 Error **errp)
1305 BlockDriverState *bs;
1306 BdrvDirtyBitmap *bitmap;
1307 AioContext *aio_context;
1309 if (!node) {
1310 error_setg(errp, "Node cannot be NULL");
1311 return NULL;
1313 if (!name) {
1314 error_setg(errp, "Bitmap name cannot be NULL");
1315 return NULL;
1317 bs = bdrv_lookup_bs(node, node, NULL);
1318 if (!bs) {
1319 error_setg(errp, "Node '%s' not found", node);
1320 return NULL;
1323 aio_context = bdrv_get_aio_context(bs);
1324 aio_context_acquire(aio_context);
1326 bitmap = bdrv_find_dirty_bitmap(bs, name);
1327 if (!bitmap) {
1328 error_setg(errp, "Dirty bitmap '%s' not found", name);
1329 goto fail;
1332 if (pbs) {
1333 *pbs = bs;
1335 if (paio) {
1336 *paio = aio_context;
1337 } else {
1338 aio_context_release(aio_context);
1341 return bitmap;
1343 fail:
1344 aio_context_release(aio_context);
1345 return NULL;
1348 /* New and old BlockDriverState structs for atomic group operations */
1350 typedef struct BlkTransactionState BlkTransactionState;
1352 /* Only prepare() may fail. In a single transaction, only one of commit() or
1353 abort() will be called, clean() will always be called if it present. */
1354 typedef struct BdrvActionOps {
1355 /* Size of state struct, in bytes. */
1356 size_t instance_size;
1357 /* Prepare the work, must NOT be NULL. */
1358 void (*prepare)(BlkTransactionState *common, Error **errp);
1359 /* Commit the changes, can be NULL. */
1360 void (*commit)(BlkTransactionState *common);
1361 /* Abort the changes on fail, can be NULL. */
1362 void (*abort)(BlkTransactionState *common);
1363 /* Clean up resource in the end, can be NULL. */
1364 void (*clean)(BlkTransactionState *common);
1365 } BdrvActionOps;
1368 * This structure must be arranged as first member in child type, assuming
1369 * that compiler will also arrange it to the same address with parent instance.
1370 * Later it will be used in free().
1372 struct BlkTransactionState {
1373 TransactionAction *action;
1374 const BdrvActionOps *ops;
1375 QSIMPLEQ_ENTRY(BlkTransactionState) entry;
1378 /* internal snapshot private data */
1379 typedef struct InternalSnapshotState {
1380 BlkTransactionState common;
1381 BlockDriverState *bs;
1382 AioContext *aio_context;
1383 QEMUSnapshotInfo sn;
1384 bool created;
1385 } InternalSnapshotState;
1387 static void internal_snapshot_prepare(BlkTransactionState *common,
1388 Error **errp)
1390 Error *local_err = NULL;
1391 const char *device;
1392 const char *name;
1393 BlockBackend *blk;
1394 BlockDriverState *bs;
1395 QEMUSnapshotInfo old_sn, *sn;
1396 bool ret;
1397 qemu_timeval tv;
1398 BlockdevSnapshotInternal *internal;
1399 InternalSnapshotState *state;
1400 int ret1;
1402 g_assert(common->action->type ==
1403 TRANSACTION_ACTION_KIND_BLOCKDEV_SNAPSHOT_INTERNAL_SYNC);
1404 internal = common->action->u.blockdev_snapshot_internal_sync;
1405 state = DO_UPCAST(InternalSnapshotState, common, common);
1407 /* 1. parse input */
1408 device = internal->device;
1409 name = internal->name;
1411 /* 2. check for validation */
1412 blk = blk_by_name(device);
1413 if (!blk) {
1414 error_set(errp, ERROR_CLASS_DEVICE_NOT_FOUND,
1415 "Device '%s' not found", device);
1416 return;
1419 /* AioContext is released in .clean() */
1420 state->aio_context = blk_get_aio_context(blk);
1421 aio_context_acquire(state->aio_context);
1423 if (!blk_is_available(blk)) {
1424 error_setg(errp, QERR_DEVICE_HAS_NO_MEDIUM, device);
1425 return;
1427 bs = blk_bs(blk);
1429 state->bs = bs;
1430 bdrv_drained_begin(bs);
1432 if (bdrv_op_is_blocked(bs, BLOCK_OP_TYPE_INTERNAL_SNAPSHOT, errp)) {
1433 return;
1436 if (bdrv_is_read_only(bs)) {
1437 error_setg(errp, "Device '%s' is read only", device);
1438 return;
1441 if (!bdrv_can_snapshot(bs)) {
1442 error_setg(errp, "Block format '%s' used by device '%s' "
1443 "does not support internal snapshots",
1444 bs->drv->format_name, device);
1445 return;
1448 if (!strlen(name)) {
1449 error_setg(errp, "Name is empty");
1450 return;
1453 /* check whether a snapshot with name exist */
1454 ret = bdrv_snapshot_find_by_id_and_name(bs, NULL, name, &old_sn,
1455 &local_err);
1456 if (local_err) {
1457 error_propagate(errp, local_err);
1458 return;
1459 } else if (ret) {
1460 error_setg(errp,
1461 "Snapshot with name '%s' already exists on device '%s'",
1462 name, device);
1463 return;
1466 /* 3. take the snapshot */
1467 sn = &state->sn;
1468 pstrcpy(sn->name, sizeof(sn->name), name);
1469 qemu_gettimeofday(&tv);
1470 sn->date_sec = tv.tv_sec;
1471 sn->date_nsec = tv.tv_usec * 1000;
1472 sn->vm_clock_nsec = qemu_clock_get_ns(QEMU_CLOCK_VIRTUAL);
1474 ret1 = bdrv_snapshot_create(bs, sn);
1475 if (ret1 < 0) {
1476 error_setg_errno(errp, -ret1,
1477 "Failed to create snapshot '%s' on device '%s'",
1478 name, device);
1479 return;
1482 /* 4. succeed, mark a snapshot is created */
1483 state->created = true;
1486 static void internal_snapshot_abort(BlkTransactionState *common)
1488 InternalSnapshotState *state =
1489 DO_UPCAST(InternalSnapshotState, common, common);
1490 BlockDriverState *bs = state->bs;
1491 QEMUSnapshotInfo *sn = &state->sn;
1492 Error *local_error = NULL;
1494 if (!state->created) {
1495 return;
1498 if (bdrv_snapshot_delete(bs, sn->id_str, sn->name, &local_error) < 0) {
1499 error_report("Failed to delete snapshot with id '%s' and name '%s' on "
1500 "device '%s' in abort: %s",
1501 sn->id_str,
1502 sn->name,
1503 bdrv_get_device_name(bs),
1504 error_get_pretty(local_error));
1505 error_free(local_error);
1509 static void internal_snapshot_clean(BlkTransactionState *common)
1511 InternalSnapshotState *state = DO_UPCAST(InternalSnapshotState,
1512 common, common);
1514 if (state->aio_context) {
1515 if (state->bs) {
1516 bdrv_drained_end(state->bs);
1518 aio_context_release(state->aio_context);
1522 /* external snapshot private data */
1523 typedef struct ExternalSnapshotState {
1524 BlkTransactionState common;
1525 BlockDriverState *old_bs;
1526 BlockDriverState *new_bs;
1527 AioContext *aio_context;
1528 } ExternalSnapshotState;
1530 static void external_snapshot_prepare(BlkTransactionState *common,
1531 Error **errp)
1533 int flags, ret;
1534 QDict *options;
1535 Error *local_err = NULL;
1536 bool has_device = false;
1537 const char *device;
1538 bool has_node_name = false;
1539 const char *node_name;
1540 bool has_snapshot_node_name = false;
1541 const char *snapshot_node_name;
1542 const char *new_image_file;
1543 const char *format = "qcow2";
1544 enum NewImageMode mode = NEW_IMAGE_MODE_ABSOLUTE_PATHS;
1545 ExternalSnapshotState *state =
1546 DO_UPCAST(ExternalSnapshotState, common, common);
1547 TransactionAction *action = common->action;
1549 /* get parameters */
1550 g_assert(action->type == TRANSACTION_ACTION_KIND_BLOCKDEV_SNAPSHOT_SYNC);
1552 has_device = action->u.blockdev_snapshot_sync->has_device;
1553 device = action->u.blockdev_snapshot_sync->device;
1554 has_node_name = action->u.blockdev_snapshot_sync->has_node_name;
1555 node_name = action->u.blockdev_snapshot_sync->node_name;
1556 has_snapshot_node_name =
1557 action->u.blockdev_snapshot_sync->has_snapshot_node_name;
1558 snapshot_node_name = action->u.blockdev_snapshot_sync->snapshot_node_name;
1560 new_image_file = action->u.blockdev_snapshot_sync->snapshot_file;
1561 if (action->u.blockdev_snapshot_sync->has_format) {
1562 format = action->u.blockdev_snapshot_sync->format;
1564 if (action->u.blockdev_snapshot_sync->has_mode) {
1565 mode = action->u.blockdev_snapshot_sync->mode;
1568 /* start processing */
1569 state->old_bs = bdrv_lookup_bs(has_device ? device : NULL,
1570 has_node_name ? node_name : NULL,
1571 &local_err);
1572 if (local_err) {
1573 error_propagate(errp, local_err);
1574 return;
1577 if (has_node_name && !has_snapshot_node_name) {
1578 error_setg(errp, "New snapshot node name missing");
1579 return;
1582 if (has_snapshot_node_name && bdrv_find_node(snapshot_node_name)) {
1583 error_setg(errp, "New snapshot node name already existing");
1584 return;
1587 /* Acquire AioContext now so any threads operating on old_bs stop */
1588 state->aio_context = bdrv_get_aio_context(state->old_bs);
1589 aio_context_acquire(state->aio_context);
1590 bdrv_drained_begin(state->old_bs);
1592 if (!bdrv_is_inserted(state->old_bs)) {
1593 error_setg(errp, QERR_DEVICE_HAS_NO_MEDIUM, device);
1594 return;
1597 if (bdrv_op_is_blocked(state->old_bs,
1598 BLOCK_OP_TYPE_EXTERNAL_SNAPSHOT, errp)) {
1599 return;
1602 if (!bdrv_is_read_only(state->old_bs)) {
1603 if (bdrv_flush(state->old_bs)) {
1604 error_setg(errp, QERR_IO_ERROR);
1605 return;
1609 if (!bdrv_is_first_non_filter(state->old_bs)) {
1610 error_setg(errp, QERR_FEATURE_DISABLED, "snapshot");
1611 return;
1614 flags = state->old_bs->open_flags;
1616 /* create new image w/backing file */
1617 if (mode != NEW_IMAGE_MODE_EXISTING) {
1618 bdrv_img_create(new_image_file, format,
1619 state->old_bs->filename,
1620 state->old_bs->drv->format_name,
1621 NULL, -1, flags, &local_err, false);
1622 if (local_err) {
1623 error_propagate(errp, local_err);
1624 return;
1628 options = qdict_new();
1629 if (has_snapshot_node_name) {
1630 qdict_put(options, "node-name",
1631 qstring_from_str(snapshot_node_name));
1633 qdict_put(options, "driver", qstring_from_str(format));
1635 /* TODO Inherit bs->options or only take explicit options with an
1636 * extended QMP command? */
1637 assert(state->new_bs == NULL);
1638 ret = bdrv_open(&state->new_bs, new_image_file, NULL, options,
1639 flags | BDRV_O_NO_BACKING, &local_err);
1640 /* We will manually add the backing_hd field to the bs later */
1641 if (ret != 0) {
1642 error_propagate(errp, local_err);
1646 static void external_snapshot_commit(BlkTransactionState *common)
1648 ExternalSnapshotState *state =
1649 DO_UPCAST(ExternalSnapshotState, common, common);
1651 bdrv_set_aio_context(state->new_bs, state->aio_context);
1653 /* This removes our old bs and adds the new bs */
1654 bdrv_append(state->new_bs, state->old_bs);
1655 /* We don't need (or want) to use the transactional
1656 * bdrv_reopen_multiple() across all the entries at once, because we
1657 * don't want to abort all of them if one of them fails the reopen */
1658 bdrv_reopen(state->old_bs, state->old_bs->open_flags & ~BDRV_O_RDWR,
1659 NULL);
1662 static void external_snapshot_abort(BlkTransactionState *common)
1664 ExternalSnapshotState *state =
1665 DO_UPCAST(ExternalSnapshotState, common, common);
1666 if (state->new_bs) {
1667 bdrv_unref(state->new_bs);
1671 static void external_snapshot_clean(BlkTransactionState *common)
1673 ExternalSnapshotState *state =
1674 DO_UPCAST(ExternalSnapshotState, common, common);
1675 if (state->aio_context) {
1676 bdrv_drained_end(state->old_bs);
1677 aio_context_release(state->aio_context);
1681 typedef struct DriveBackupState {
1682 BlkTransactionState common;
1683 BlockDriverState *bs;
1684 AioContext *aio_context;
1685 BlockJob *job;
1686 } DriveBackupState;
1688 static void drive_backup_prepare(BlkTransactionState *common, Error **errp)
1690 DriveBackupState *state = DO_UPCAST(DriveBackupState, common, common);
1691 BlockBackend *blk;
1692 DriveBackup *backup;
1693 Error *local_err = NULL;
1695 assert(common->action->type == TRANSACTION_ACTION_KIND_DRIVE_BACKUP);
1696 backup = common->action->u.drive_backup;
1698 blk = blk_by_name(backup->device);
1699 if (!blk) {
1700 error_set(errp, ERROR_CLASS_DEVICE_NOT_FOUND,
1701 "Device '%s' not found", backup->device);
1702 return;
1705 if (!blk_is_available(blk)) {
1706 error_setg(errp, QERR_DEVICE_HAS_NO_MEDIUM, backup->device);
1707 return;
1710 /* AioContext is released in .clean() */
1711 state->aio_context = blk_get_aio_context(blk);
1712 aio_context_acquire(state->aio_context);
1713 bdrv_drained_begin(blk_bs(blk));
1714 state->bs = blk_bs(blk);
1716 qmp_drive_backup(backup->device, backup->target,
1717 backup->has_format, backup->format,
1718 backup->sync,
1719 backup->has_mode, backup->mode,
1720 backup->has_speed, backup->speed,
1721 backup->has_bitmap, backup->bitmap,
1722 backup->has_on_source_error, backup->on_source_error,
1723 backup->has_on_target_error, backup->on_target_error,
1724 &local_err);
1725 if (local_err) {
1726 error_propagate(errp, local_err);
1727 return;
1730 state->job = state->bs->job;
1733 static void drive_backup_abort(BlkTransactionState *common)
1735 DriveBackupState *state = DO_UPCAST(DriveBackupState, common, common);
1736 BlockDriverState *bs = state->bs;
1738 /* Only cancel if it's the job we started */
1739 if (bs && bs->job && bs->job == state->job) {
1740 block_job_cancel_sync(bs->job);
1744 static void drive_backup_clean(BlkTransactionState *common)
1746 DriveBackupState *state = DO_UPCAST(DriveBackupState, common, common);
1748 if (state->aio_context) {
1749 bdrv_drained_end(state->bs);
1750 aio_context_release(state->aio_context);
1754 typedef struct BlockdevBackupState {
1755 BlkTransactionState common;
1756 BlockDriverState *bs;
1757 BlockJob *job;
1758 AioContext *aio_context;
1759 } BlockdevBackupState;
1761 static void blockdev_backup_prepare(BlkTransactionState *common, Error **errp)
1763 BlockdevBackupState *state = DO_UPCAST(BlockdevBackupState, common, common);
1764 BlockdevBackup *backup;
1765 BlockBackend *blk, *target;
1766 Error *local_err = NULL;
1768 assert(common->action->type == TRANSACTION_ACTION_KIND_BLOCKDEV_BACKUP);
1769 backup = common->action->u.blockdev_backup;
1771 blk = blk_by_name(backup->device);
1772 if (!blk) {
1773 error_setg(errp, "Device '%s' not found", backup->device);
1774 return;
1777 if (!blk_is_available(blk)) {
1778 error_setg(errp, QERR_DEVICE_HAS_NO_MEDIUM, backup->device);
1779 return;
1782 target = blk_by_name(backup->target);
1783 if (!target) {
1784 error_setg(errp, "Device '%s' not found", backup->target);
1785 return;
1788 /* AioContext is released in .clean() */
1789 state->aio_context = blk_get_aio_context(blk);
1790 if (state->aio_context != blk_get_aio_context(target)) {
1791 state->aio_context = NULL;
1792 error_setg(errp, "Backup between two IO threads is not implemented");
1793 return;
1795 aio_context_acquire(state->aio_context);
1796 state->bs = blk_bs(blk);
1797 bdrv_drained_begin(state->bs);
1799 qmp_blockdev_backup(backup->device, backup->target,
1800 backup->sync,
1801 backup->has_speed, backup->speed,
1802 backup->has_on_source_error, backup->on_source_error,
1803 backup->has_on_target_error, backup->on_target_error,
1804 &local_err);
1805 if (local_err) {
1806 error_propagate(errp, local_err);
1807 return;
1810 state->job = state->bs->job;
1813 static void blockdev_backup_abort(BlkTransactionState *common)
1815 BlockdevBackupState *state = DO_UPCAST(BlockdevBackupState, common, common);
1816 BlockDriverState *bs = state->bs;
1818 /* Only cancel if it's the job we started */
1819 if (bs && bs->job && bs->job == state->job) {
1820 block_job_cancel_sync(bs->job);
1824 static void blockdev_backup_clean(BlkTransactionState *common)
1826 BlockdevBackupState *state = DO_UPCAST(BlockdevBackupState, common, common);
1828 if (state->aio_context) {
1829 bdrv_drained_end(state->bs);
1830 aio_context_release(state->aio_context);
1834 static void abort_prepare(BlkTransactionState *common, Error **errp)
1836 error_setg(errp, "Transaction aborted using Abort action");
1839 static void abort_commit(BlkTransactionState *common)
1841 g_assert_not_reached(); /* this action never succeeds */
1844 static const BdrvActionOps actions[] = {
1845 [TRANSACTION_ACTION_KIND_BLOCKDEV_SNAPSHOT_SYNC] = {
1846 .instance_size = sizeof(ExternalSnapshotState),
1847 .prepare = external_snapshot_prepare,
1848 .commit = external_snapshot_commit,
1849 .abort = external_snapshot_abort,
1850 .clean = external_snapshot_clean,
1852 [TRANSACTION_ACTION_KIND_DRIVE_BACKUP] = {
1853 .instance_size = sizeof(DriveBackupState),
1854 .prepare = drive_backup_prepare,
1855 .abort = drive_backup_abort,
1856 .clean = drive_backup_clean,
1858 [TRANSACTION_ACTION_KIND_BLOCKDEV_BACKUP] = {
1859 .instance_size = sizeof(BlockdevBackupState),
1860 .prepare = blockdev_backup_prepare,
1861 .abort = blockdev_backup_abort,
1862 .clean = blockdev_backup_clean,
1864 [TRANSACTION_ACTION_KIND_ABORT] = {
1865 .instance_size = sizeof(BlkTransactionState),
1866 .prepare = abort_prepare,
1867 .commit = abort_commit,
1869 [TRANSACTION_ACTION_KIND_BLOCKDEV_SNAPSHOT_INTERNAL_SYNC] = {
1870 .instance_size = sizeof(InternalSnapshotState),
1871 .prepare = internal_snapshot_prepare,
1872 .abort = internal_snapshot_abort,
1873 .clean = internal_snapshot_clean,
1878 * 'Atomic' group operations. The operations are performed as a set, and if
1879 * any fail then we roll back all operations in the group.
1881 void qmp_transaction(TransactionActionList *dev_list, Error **errp)
1883 TransactionActionList *dev_entry = dev_list;
1884 BlkTransactionState *state, *next;
1885 Error *local_err = NULL;
1887 QSIMPLEQ_HEAD(snap_bdrv_states, BlkTransactionState) snap_bdrv_states;
1888 QSIMPLEQ_INIT(&snap_bdrv_states);
1890 /* drain all i/o before any operations */
1891 bdrv_drain_all();
1893 /* We don't do anything in this loop that commits us to the operations */
1894 while (NULL != dev_entry) {
1895 TransactionAction *dev_info = NULL;
1896 const BdrvActionOps *ops;
1898 dev_info = dev_entry->value;
1899 dev_entry = dev_entry->next;
1901 assert(dev_info->type < ARRAY_SIZE(actions));
1903 ops = &actions[dev_info->type];
1904 assert(ops->instance_size > 0);
1906 state = g_malloc0(ops->instance_size);
1907 state->ops = ops;
1908 state->action = dev_info;
1909 QSIMPLEQ_INSERT_TAIL(&snap_bdrv_states, state, entry);
1911 state->ops->prepare(state, &local_err);
1912 if (local_err) {
1913 error_propagate(errp, local_err);
1914 goto delete_and_fail;
1918 QSIMPLEQ_FOREACH(state, &snap_bdrv_states, entry) {
1919 if (state->ops->commit) {
1920 state->ops->commit(state);
1924 /* success */
1925 goto exit;
1927 delete_and_fail:
1928 /* failure, and it is all-or-none; roll back all operations */
1929 QSIMPLEQ_FOREACH(state, &snap_bdrv_states, entry) {
1930 if (state->ops->abort) {
1931 state->ops->abort(state);
1934 exit:
1935 QSIMPLEQ_FOREACH_SAFE(state, &snap_bdrv_states, entry, next) {
1936 if (state->ops->clean) {
1937 state->ops->clean(state);
1939 g_free(state);
1944 static void eject_device(BlockBackend *blk, int force, Error **errp)
1946 BlockDriverState *bs = blk_bs(blk);
1947 AioContext *aio_context;
1949 if (!bs) {
1950 /* No medium inserted, so there is nothing to do */
1951 return;
1954 aio_context = bdrv_get_aio_context(bs);
1955 aio_context_acquire(aio_context);
1957 if (bdrv_op_is_blocked(bs, BLOCK_OP_TYPE_EJECT, errp)) {
1958 goto out;
1960 if (!blk_dev_has_removable_media(blk)) {
1961 error_setg(errp, "Device '%s' is not removable",
1962 bdrv_get_device_name(bs));
1963 goto out;
1966 if (blk_dev_is_medium_locked(blk) && !blk_dev_is_tray_open(blk)) {
1967 blk_dev_eject_request(blk, force);
1968 if (!force) {
1969 error_setg(errp, "Device '%s' is locked",
1970 bdrv_get_device_name(bs));
1971 goto out;
1975 bdrv_close(bs);
1977 out:
1978 aio_context_release(aio_context);
1981 void qmp_eject(const char *device, bool has_force, bool force, Error **errp)
1983 BlockBackend *blk;
1985 blk = blk_by_name(device);
1986 if (!blk) {
1987 error_set(errp, ERROR_CLASS_DEVICE_NOT_FOUND,
1988 "Device '%s' not found", device);
1989 return;
1992 eject_device(blk, force, errp);
1995 void qmp_block_passwd(bool has_device, const char *device,
1996 bool has_node_name, const char *node_name,
1997 const char *password, Error **errp)
1999 Error *local_err = NULL;
2000 BlockDriverState *bs;
2001 AioContext *aio_context;
2003 bs = bdrv_lookup_bs(has_device ? device : NULL,
2004 has_node_name ? node_name : NULL,
2005 &local_err);
2006 if (local_err) {
2007 error_propagate(errp, local_err);
2008 return;
2011 aio_context = bdrv_get_aio_context(bs);
2012 aio_context_acquire(aio_context);
2014 bdrv_add_key(bs, password, errp);
2016 aio_context_release(aio_context);
2019 /* Assumes AioContext is held */
2020 static void qmp_bdrv_open_encrypted(BlockDriverState **pbs,
2021 const char *filename,
2022 int bdrv_flags, const char *format,
2023 const char *password, Error **errp)
2025 Error *local_err = NULL;
2026 QDict *options = NULL;
2027 int ret;
2029 if (format) {
2030 options = qdict_new();
2031 qdict_put(options, "driver", qstring_from_str(format));
2034 ret = bdrv_open(pbs, filename, NULL, options, bdrv_flags, &local_err);
2035 if (ret < 0) {
2036 error_propagate(errp, local_err);
2037 return;
2040 bdrv_add_key(*pbs, password, errp);
2043 void qmp_change_blockdev(const char *device, const char *filename,
2044 const char *format, Error **errp)
2046 BlockBackend *blk;
2047 BlockDriverState *bs;
2048 AioContext *aio_context;
2049 int bdrv_flags;
2050 bool new_bs;
2051 Error *err = NULL;
2053 blk = blk_by_name(device);
2054 if (!blk) {
2055 error_set(errp, ERROR_CLASS_DEVICE_NOT_FOUND,
2056 "Device '%s' not found", device);
2057 return;
2059 bs = blk_bs(blk);
2060 new_bs = !bs;
2062 aio_context = blk_get_aio_context(blk);
2063 aio_context_acquire(aio_context);
2065 eject_device(blk, 0, &err);
2066 if (err) {
2067 error_propagate(errp, err);
2068 goto out;
2071 bdrv_flags = blk_is_read_only(blk) ? 0 : BDRV_O_RDWR;
2072 bdrv_flags |= blk_get_root_state(blk)->open_flags & ~BDRV_O_RDWR;
2074 qmp_bdrv_open_encrypted(&bs, filename, bdrv_flags, format, NULL, &err);
2075 if (err) {
2076 error_propagate(errp, err);
2077 goto out;
2080 if (new_bs) {
2081 blk_insert_bs(blk, bs);
2082 /* Has been sent automatically by bdrv_open() if blk_bs(blk) was not
2083 * NULL */
2084 blk_dev_change_media_cb(blk, true);
2087 out:
2088 aio_context_release(aio_context);
2091 /* throttling disk I/O limits */
2092 void qmp_block_set_io_throttle(const char *device, int64_t bps, int64_t bps_rd,
2093 int64_t bps_wr,
2094 int64_t iops,
2095 int64_t iops_rd,
2096 int64_t iops_wr,
2097 bool has_bps_max,
2098 int64_t bps_max,
2099 bool has_bps_rd_max,
2100 int64_t bps_rd_max,
2101 bool has_bps_wr_max,
2102 int64_t bps_wr_max,
2103 bool has_iops_max,
2104 int64_t iops_max,
2105 bool has_iops_rd_max,
2106 int64_t iops_rd_max,
2107 bool has_iops_wr_max,
2108 int64_t iops_wr_max,
2109 bool has_iops_size,
2110 int64_t iops_size,
2111 bool has_group,
2112 const char *group, Error **errp)
2114 ThrottleConfig cfg;
2115 BlockDriverState *bs;
2116 BlockBackend *blk;
2117 AioContext *aio_context;
2119 blk = blk_by_name(device);
2120 if (!blk) {
2121 error_set(errp, ERROR_CLASS_DEVICE_NOT_FOUND,
2122 "Device '%s' not found", device);
2123 return;
2126 aio_context = blk_get_aio_context(blk);
2127 aio_context_acquire(aio_context);
2129 bs = blk_bs(blk);
2130 if (!bs) {
2131 error_setg(errp, "Device '%s' has no medium", device);
2132 goto out;
2135 memset(&cfg, 0, sizeof(cfg));
2136 cfg.buckets[THROTTLE_BPS_TOTAL].avg = bps;
2137 cfg.buckets[THROTTLE_BPS_READ].avg = bps_rd;
2138 cfg.buckets[THROTTLE_BPS_WRITE].avg = bps_wr;
2140 cfg.buckets[THROTTLE_OPS_TOTAL].avg = iops;
2141 cfg.buckets[THROTTLE_OPS_READ].avg = iops_rd;
2142 cfg.buckets[THROTTLE_OPS_WRITE].avg = iops_wr;
2144 if (has_bps_max) {
2145 cfg.buckets[THROTTLE_BPS_TOTAL].max = bps_max;
2147 if (has_bps_rd_max) {
2148 cfg.buckets[THROTTLE_BPS_READ].max = bps_rd_max;
2150 if (has_bps_wr_max) {
2151 cfg.buckets[THROTTLE_BPS_WRITE].max = bps_wr_max;
2153 if (has_iops_max) {
2154 cfg.buckets[THROTTLE_OPS_TOTAL].max = iops_max;
2156 if (has_iops_rd_max) {
2157 cfg.buckets[THROTTLE_OPS_READ].max = iops_rd_max;
2159 if (has_iops_wr_max) {
2160 cfg.buckets[THROTTLE_OPS_WRITE].max = iops_wr_max;
2163 if (has_iops_size) {
2164 cfg.op_size = iops_size;
2167 if (!check_throttle_config(&cfg, errp)) {
2168 goto out;
2171 if (throttle_enabled(&cfg)) {
2172 /* Enable I/O limits if they're not enabled yet, otherwise
2173 * just update the throttling group. */
2174 if (!bs->io_limits_enabled) {
2175 bdrv_io_limits_enable(bs, has_group ? group : device);
2176 } else if (has_group) {
2177 bdrv_io_limits_update_group(bs, group);
2179 /* Set the new throttling configuration */
2180 bdrv_set_io_limits(bs, &cfg);
2181 } else if (bs->io_limits_enabled) {
2182 /* If all throttling settings are set to 0, disable I/O limits */
2183 bdrv_io_limits_disable(bs);
2186 out:
2187 aio_context_release(aio_context);
2190 void qmp_block_dirty_bitmap_add(const char *node, const char *name,
2191 bool has_granularity, uint32_t granularity,
2192 Error **errp)
2194 AioContext *aio_context;
2195 BlockDriverState *bs;
2197 if (!name || name[0] == '\0') {
2198 error_setg(errp, "Bitmap name cannot be empty");
2199 return;
2202 bs = bdrv_lookup_bs(node, node, errp);
2203 if (!bs) {
2204 return;
2207 aio_context = bdrv_get_aio_context(bs);
2208 aio_context_acquire(aio_context);
2210 if (has_granularity) {
2211 if (granularity < 512 || !is_power_of_2(granularity)) {
2212 error_setg(errp, "Granularity must be power of 2 "
2213 "and at least 512");
2214 goto out;
2216 } else {
2217 /* Default to cluster size, if available: */
2218 granularity = bdrv_get_default_bitmap_granularity(bs);
2221 bdrv_create_dirty_bitmap(bs, granularity, name, errp);
2223 out:
2224 aio_context_release(aio_context);
2227 void qmp_block_dirty_bitmap_remove(const char *node, const char *name,
2228 Error **errp)
2230 AioContext *aio_context;
2231 BlockDriverState *bs;
2232 BdrvDirtyBitmap *bitmap;
2234 bitmap = block_dirty_bitmap_lookup(node, name, &bs, &aio_context, errp);
2235 if (!bitmap || !bs) {
2236 return;
2239 if (bdrv_dirty_bitmap_frozen(bitmap)) {
2240 error_setg(errp,
2241 "Bitmap '%s' is currently frozen and cannot be removed",
2242 name);
2243 goto out;
2245 bdrv_dirty_bitmap_make_anon(bitmap);
2246 bdrv_release_dirty_bitmap(bs, bitmap);
2248 out:
2249 aio_context_release(aio_context);
2253 * Completely clear a bitmap, for the purposes of synchronizing a bitmap
2254 * immediately after a full backup operation.
2256 void qmp_block_dirty_bitmap_clear(const char *node, const char *name,
2257 Error **errp)
2259 AioContext *aio_context;
2260 BdrvDirtyBitmap *bitmap;
2261 BlockDriverState *bs;
2263 bitmap = block_dirty_bitmap_lookup(node, name, &bs, &aio_context, errp);
2264 if (!bitmap || !bs) {
2265 return;
2268 if (bdrv_dirty_bitmap_frozen(bitmap)) {
2269 error_setg(errp,
2270 "Bitmap '%s' is currently frozen and cannot be modified",
2271 name);
2272 goto out;
2273 } else if (!bdrv_dirty_bitmap_enabled(bitmap)) {
2274 error_setg(errp,
2275 "Bitmap '%s' is currently disabled and cannot be cleared",
2276 name);
2277 goto out;
2280 bdrv_clear_dirty_bitmap(bitmap);
2282 out:
2283 aio_context_release(aio_context);
2286 void hmp_drive_del(Monitor *mon, const QDict *qdict)
2288 const char *id = qdict_get_str(qdict, "id");
2289 BlockBackend *blk;
2290 BlockDriverState *bs;
2291 AioContext *aio_context;
2292 Error *local_err = NULL;
2294 blk = blk_by_name(id);
2295 if (!blk) {
2296 error_report("Device '%s' not found", id);
2297 return;
2300 if (!blk_legacy_dinfo(blk)) {
2301 error_report("Deleting device added with blockdev-add"
2302 " is not supported");
2303 return;
2306 aio_context = blk_get_aio_context(blk);
2307 aio_context_acquire(aio_context);
2309 bs = blk_bs(blk);
2310 if (bs) {
2311 if (bdrv_op_is_blocked(bs, BLOCK_OP_TYPE_DRIVE_DEL, &local_err)) {
2312 error_report_err(local_err);
2313 aio_context_release(aio_context);
2314 return;
2317 bdrv_close(bs);
2320 /* if we have a device attached to this BlockDriverState
2321 * then we need to make the drive anonymous until the device
2322 * can be removed. If this is a drive with no device backing
2323 * then we can just get rid of the block driver state right here.
2325 if (blk_get_attached_dev(blk)) {
2326 blk_hide_on_behalf_of_hmp_drive_del(blk);
2327 /* Further I/O must not pause the guest */
2328 blk_set_on_error(blk, BLOCKDEV_ON_ERROR_REPORT,
2329 BLOCKDEV_ON_ERROR_REPORT);
2330 } else {
2331 blk_unref(blk);
2334 aio_context_release(aio_context);
2337 void qmp_block_resize(bool has_device, const char *device,
2338 bool has_node_name, const char *node_name,
2339 int64_t size, Error **errp)
2341 Error *local_err = NULL;
2342 BlockDriverState *bs;
2343 AioContext *aio_context;
2344 int ret;
2346 bs = bdrv_lookup_bs(has_device ? device : NULL,
2347 has_node_name ? node_name : NULL,
2348 &local_err);
2349 if (local_err) {
2350 error_propagate(errp, local_err);
2351 return;
2354 aio_context = bdrv_get_aio_context(bs);
2355 aio_context_acquire(aio_context);
2357 if (!bdrv_is_first_non_filter(bs)) {
2358 error_setg(errp, QERR_FEATURE_DISABLED, "resize");
2359 goto out;
2362 if (size < 0) {
2363 error_setg(errp, QERR_INVALID_PARAMETER_VALUE, "size", "a >0 size");
2364 goto out;
2367 if (bdrv_op_is_blocked(bs, BLOCK_OP_TYPE_RESIZE, NULL)) {
2368 error_setg(errp, QERR_DEVICE_IN_USE, device);
2369 goto out;
2372 /* complete all in-flight operations before resizing the device */
2373 bdrv_drain_all();
2375 ret = bdrv_truncate(bs, size);
2376 switch (ret) {
2377 case 0:
2378 break;
2379 case -ENOMEDIUM:
2380 error_setg(errp, QERR_DEVICE_HAS_NO_MEDIUM, device);
2381 break;
2382 case -ENOTSUP:
2383 error_setg(errp, QERR_UNSUPPORTED);
2384 break;
2385 case -EACCES:
2386 error_setg(errp, "Device '%s' is read only", device);
2387 break;
2388 case -EBUSY:
2389 error_setg(errp, QERR_DEVICE_IN_USE, device);
2390 break;
2391 default:
2392 error_setg_errno(errp, -ret, "Could not resize");
2393 break;
2396 out:
2397 aio_context_release(aio_context);
2400 static void block_job_cb(void *opaque, int ret)
2402 /* Note that this function may be executed from another AioContext besides
2403 * the QEMU main loop. If you need to access anything that assumes the
2404 * QEMU global mutex, use a BH or introduce a mutex.
2407 BlockDriverState *bs = opaque;
2408 const char *msg = NULL;
2410 trace_block_job_cb(bs, bs->job, ret);
2412 assert(bs->job);
2414 if (ret < 0) {
2415 msg = strerror(-ret);
2418 if (block_job_is_cancelled(bs->job)) {
2419 block_job_event_cancelled(bs->job);
2420 } else {
2421 block_job_event_completed(bs->job, msg);
2424 bdrv_put_ref_bh_schedule(bs);
2427 void qmp_block_stream(const char *device,
2428 bool has_base, const char *base,
2429 bool has_backing_file, const char *backing_file,
2430 bool has_speed, int64_t speed,
2431 bool has_on_error, BlockdevOnError on_error,
2432 Error **errp)
2434 BlockBackend *blk;
2435 BlockDriverState *bs;
2436 BlockDriverState *base_bs = NULL;
2437 AioContext *aio_context;
2438 Error *local_err = NULL;
2439 const char *base_name = NULL;
2441 if (!has_on_error) {
2442 on_error = BLOCKDEV_ON_ERROR_REPORT;
2445 blk = blk_by_name(device);
2446 if (!blk) {
2447 error_set(errp, ERROR_CLASS_DEVICE_NOT_FOUND,
2448 "Device '%s' not found", device);
2449 return;
2452 aio_context = blk_get_aio_context(blk);
2453 aio_context_acquire(aio_context);
2455 if (!blk_is_available(blk)) {
2456 error_setg(errp, "Device '%s' has no medium", device);
2457 goto out;
2459 bs = blk_bs(blk);
2461 if (bdrv_op_is_blocked(bs, BLOCK_OP_TYPE_STREAM, errp)) {
2462 goto out;
2465 if (has_base) {
2466 base_bs = bdrv_find_backing_image(bs, base);
2467 if (base_bs == NULL) {
2468 error_setg(errp, QERR_BASE_NOT_FOUND, base);
2469 goto out;
2471 assert(bdrv_get_aio_context(base_bs) == aio_context);
2472 base_name = base;
2475 /* if we are streaming the entire chain, the result will have no backing
2476 * file, and specifying one is therefore an error */
2477 if (base_bs == NULL && has_backing_file) {
2478 error_setg(errp, "backing file specified, but streaming the "
2479 "entire chain");
2480 goto out;
2483 /* backing_file string overrides base bs filename */
2484 base_name = has_backing_file ? backing_file : base_name;
2486 stream_start(bs, base_bs, base_name, has_speed ? speed : 0,
2487 on_error, block_job_cb, bs, &local_err);
2488 if (local_err) {
2489 error_propagate(errp, local_err);
2490 goto out;
2493 trace_qmp_block_stream(bs, bs->job);
2495 out:
2496 aio_context_release(aio_context);
2499 void qmp_block_commit(const char *device,
2500 bool has_base, const char *base,
2501 bool has_top, const char *top,
2502 bool has_backing_file, const char *backing_file,
2503 bool has_speed, int64_t speed,
2504 Error **errp)
2506 BlockBackend *blk;
2507 BlockDriverState *bs;
2508 BlockDriverState *base_bs, *top_bs;
2509 AioContext *aio_context;
2510 Error *local_err = NULL;
2511 /* This will be part of the QMP command, if/when the
2512 * BlockdevOnError change for blkmirror makes it in
2514 BlockdevOnError on_error = BLOCKDEV_ON_ERROR_REPORT;
2516 if (!has_speed) {
2517 speed = 0;
2520 /* Important Note:
2521 * libvirt relies on the DeviceNotFound error class in order to probe for
2522 * live commit feature versions; for this to work, we must make sure to
2523 * perform the device lookup before any generic errors that may occur in a
2524 * scenario in which all optional arguments are omitted. */
2525 blk = blk_by_name(device);
2526 if (!blk) {
2527 error_set(errp, ERROR_CLASS_DEVICE_NOT_FOUND,
2528 "Device '%s' not found", device);
2529 return;
2532 aio_context = blk_get_aio_context(blk);
2533 aio_context_acquire(aio_context);
2535 if (!blk_is_available(blk)) {
2536 error_setg(errp, "Device '%s' has no medium", device);
2537 goto out;
2539 bs = blk_bs(blk);
2541 if (bdrv_op_is_blocked(bs, BLOCK_OP_TYPE_COMMIT_SOURCE, errp)) {
2542 goto out;
2545 /* default top_bs is the active layer */
2546 top_bs = bs;
2548 if (has_top && top) {
2549 if (strcmp(bs->filename, top) != 0) {
2550 top_bs = bdrv_find_backing_image(bs, top);
2554 if (top_bs == NULL) {
2555 error_setg(errp, "Top image file %s not found", top ? top : "NULL");
2556 goto out;
2559 assert(bdrv_get_aio_context(top_bs) == aio_context);
2561 if (has_base && base) {
2562 base_bs = bdrv_find_backing_image(top_bs, base);
2563 } else {
2564 base_bs = bdrv_find_base(top_bs);
2567 if (base_bs == NULL) {
2568 error_setg(errp, QERR_BASE_NOT_FOUND, base ? base : "NULL");
2569 goto out;
2572 assert(bdrv_get_aio_context(base_bs) == aio_context);
2574 if (bdrv_op_is_blocked(base_bs, BLOCK_OP_TYPE_COMMIT_TARGET, errp)) {
2575 goto out;
2578 /* Do not allow attempts to commit an image into itself */
2579 if (top_bs == base_bs) {
2580 error_setg(errp, "cannot commit an image into itself");
2581 goto out;
2584 if (top_bs == bs) {
2585 if (has_backing_file) {
2586 error_setg(errp, "'backing-file' specified,"
2587 " but 'top' is the active layer");
2588 goto out;
2590 commit_active_start(bs, base_bs, speed, on_error, block_job_cb,
2591 bs, &local_err);
2592 } else {
2593 commit_start(bs, base_bs, top_bs, speed, on_error, block_job_cb, bs,
2594 has_backing_file ? backing_file : NULL, &local_err);
2596 if (local_err != NULL) {
2597 error_propagate(errp, local_err);
2598 goto out;
2601 out:
2602 aio_context_release(aio_context);
2605 void qmp_drive_backup(const char *device, const char *target,
2606 bool has_format, const char *format,
2607 enum MirrorSyncMode sync,
2608 bool has_mode, enum NewImageMode mode,
2609 bool has_speed, int64_t speed,
2610 bool has_bitmap, const char *bitmap,
2611 bool has_on_source_error, BlockdevOnError on_source_error,
2612 bool has_on_target_error, BlockdevOnError on_target_error,
2613 Error **errp)
2615 BlockBackend *blk;
2616 BlockDriverState *bs;
2617 BlockDriverState *target_bs;
2618 BlockDriverState *source = NULL;
2619 BdrvDirtyBitmap *bmap = NULL;
2620 AioContext *aio_context;
2621 QDict *options = NULL;
2622 Error *local_err = NULL;
2623 int flags;
2624 int64_t size;
2625 int ret;
2627 if (!has_speed) {
2628 speed = 0;
2630 if (!has_on_source_error) {
2631 on_source_error = BLOCKDEV_ON_ERROR_REPORT;
2633 if (!has_on_target_error) {
2634 on_target_error = BLOCKDEV_ON_ERROR_REPORT;
2636 if (!has_mode) {
2637 mode = NEW_IMAGE_MODE_ABSOLUTE_PATHS;
2640 blk = blk_by_name(device);
2641 if (!blk) {
2642 error_set(errp, ERROR_CLASS_DEVICE_NOT_FOUND,
2643 "Device '%s' not found", device);
2644 return;
2647 aio_context = blk_get_aio_context(blk);
2648 aio_context_acquire(aio_context);
2650 /* Although backup_run has this check too, we need to use bs->drv below, so
2651 * do an early check redundantly. */
2652 if (!blk_is_available(blk)) {
2653 error_setg(errp, QERR_DEVICE_HAS_NO_MEDIUM, device);
2654 goto out;
2656 bs = blk_bs(blk);
2658 if (!has_format) {
2659 format = mode == NEW_IMAGE_MODE_EXISTING ? NULL : bs->drv->format_name;
2662 /* Early check to avoid creating target */
2663 if (bdrv_op_is_blocked(bs, BLOCK_OP_TYPE_BACKUP_SOURCE, errp)) {
2664 goto out;
2667 flags = bs->open_flags | BDRV_O_RDWR;
2669 /* See if we have a backing HD we can use to create our new image
2670 * on top of. */
2671 if (sync == MIRROR_SYNC_MODE_TOP) {
2672 source = backing_bs(bs);
2673 if (!source) {
2674 sync = MIRROR_SYNC_MODE_FULL;
2677 if (sync == MIRROR_SYNC_MODE_NONE) {
2678 source = bs;
2681 size = bdrv_getlength(bs);
2682 if (size < 0) {
2683 error_setg_errno(errp, -size, "bdrv_getlength failed");
2684 goto out;
2687 if (mode != NEW_IMAGE_MODE_EXISTING) {
2688 assert(format);
2689 if (source) {
2690 bdrv_img_create(target, format, source->filename,
2691 source->drv->format_name, NULL,
2692 size, flags, &local_err, false);
2693 } else {
2694 bdrv_img_create(target, format, NULL, NULL, NULL,
2695 size, flags, &local_err, false);
2699 if (local_err) {
2700 error_propagate(errp, local_err);
2701 goto out;
2704 if (format) {
2705 options = qdict_new();
2706 qdict_put(options, "driver", qstring_from_str(format));
2709 target_bs = NULL;
2710 ret = bdrv_open(&target_bs, target, NULL, options, flags, &local_err);
2711 if (ret < 0) {
2712 error_propagate(errp, local_err);
2713 goto out;
2716 bdrv_set_aio_context(target_bs, aio_context);
2718 if (has_bitmap) {
2719 bmap = bdrv_find_dirty_bitmap(bs, bitmap);
2720 if (!bmap) {
2721 error_setg(errp, "Bitmap '%s' could not be found", bitmap);
2722 goto out;
2726 backup_start(bs, target_bs, speed, sync, bmap,
2727 on_source_error, on_target_error,
2728 block_job_cb, bs, &local_err);
2729 if (local_err != NULL) {
2730 bdrv_unref(target_bs);
2731 error_propagate(errp, local_err);
2732 goto out;
2735 out:
2736 aio_context_release(aio_context);
2739 BlockDeviceInfoList *qmp_query_named_block_nodes(Error **errp)
2741 return bdrv_named_nodes_list(errp);
2744 void qmp_blockdev_backup(const char *device, const char *target,
2745 enum MirrorSyncMode sync,
2746 bool has_speed, int64_t speed,
2747 bool has_on_source_error,
2748 BlockdevOnError on_source_error,
2749 bool has_on_target_error,
2750 BlockdevOnError on_target_error,
2751 Error **errp)
2753 BlockBackend *blk, *target_blk;
2754 BlockDriverState *bs;
2755 BlockDriverState *target_bs;
2756 Error *local_err = NULL;
2757 AioContext *aio_context;
2759 if (!has_speed) {
2760 speed = 0;
2762 if (!has_on_source_error) {
2763 on_source_error = BLOCKDEV_ON_ERROR_REPORT;
2765 if (!has_on_target_error) {
2766 on_target_error = BLOCKDEV_ON_ERROR_REPORT;
2769 blk = blk_by_name(device);
2770 if (!blk) {
2771 error_setg(errp, "Device '%s' not found", device);
2772 return;
2775 aio_context = blk_get_aio_context(blk);
2776 aio_context_acquire(aio_context);
2778 if (!blk_is_available(blk)) {
2779 error_setg(errp, "Device '%s' has no medium", device);
2780 goto out;
2782 bs = blk_bs(blk);
2784 target_blk = blk_by_name(target);
2785 if (!target_blk) {
2786 error_setg(errp, "Device '%s' not found", target);
2787 goto out;
2790 if (!blk_is_available(target_blk)) {
2791 error_setg(errp, "Device '%s' has no medium", target);
2792 goto out;
2794 target_bs = blk_bs(target_blk);
2796 bdrv_ref(target_bs);
2797 bdrv_set_aio_context(target_bs, aio_context);
2798 backup_start(bs, target_bs, speed, sync, NULL, on_source_error,
2799 on_target_error, block_job_cb, bs, &local_err);
2800 if (local_err != NULL) {
2801 bdrv_unref(target_bs);
2802 error_propagate(errp, local_err);
2804 out:
2805 aio_context_release(aio_context);
2808 void qmp_drive_mirror(const char *device, const char *target,
2809 bool has_format, const char *format,
2810 bool has_node_name, const char *node_name,
2811 bool has_replaces, const char *replaces,
2812 enum MirrorSyncMode sync,
2813 bool has_mode, enum NewImageMode mode,
2814 bool has_speed, int64_t speed,
2815 bool has_granularity, uint32_t granularity,
2816 bool has_buf_size, int64_t buf_size,
2817 bool has_on_source_error, BlockdevOnError on_source_error,
2818 bool has_on_target_error, BlockdevOnError on_target_error,
2819 bool has_unmap, bool unmap,
2820 Error **errp)
2822 BlockBackend *blk;
2823 BlockDriverState *bs;
2824 BlockDriverState *source, *target_bs;
2825 AioContext *aio_context;
2826 Error *local_err = NULL;
2827 QDict *options;
2828 int flags;
2829 int64_t size;
2830 int ret;
2832 if (!has_speed) {
2833 speed = 0;
2835 if (!has_on_source_error) {
2836 on_source_error = BLOCKDEV_ON_ERROR_REPORT;
2838 if (!has_on_target_error) {
2839 on_target_error = BLOCKDEV_ON_ERROR_REPORT;
2841 if (!has_mode) {
2842 mode = NEW_IMAGE_MODE_ABSOLUTE_PATHS;
2844 if (!has_granularity) {
2845 granularity = 0;
2847 if (!has_buf_size) {
2848 buf_size = 0;
2850 if (!has_unmap) {
2851 unmap = true;
2854 if (granularity != 0 && (granularity < 512 || granularity > 1048576 * 64)) {
2855 error_setg(errp, QERR_INVALID_PARAMETER_VALUE, "granularity",
2856 "a value in range [512B, 64MB]");
2857 return;
2859 if (granularity & (granularity - 1)) {
2860 error_setg(errp, QERR_INVALID_PARAMETER_VALUE, "granularity",
2861 "power of 2");
2862 return;
2865 blk = blk_by_name(device);
2866 if (!blk) {
2867 error_set(errp, ERROR_CLASS_DEVICE_NOT_FOUND,
2868 "Device '%s' not found", device);
2869 return;
2872 aio_context = blk_get_aio_context(blk);
2873 aio_context_acquire(aio_context);
2875 if (!blk_is_available(blk)) {
2876 error_setg(errp, QERR_DEVICE_HAS_NO_MEDIUM, device);
2877 goto out;
2879 bs = blk_bs(blk);
2881 if (!has_format) {
2882 format = mode == NEW_IMAGE_MODE_EXISTING ? NULL : bs->drv->format_name;
2885 if (bdrv_op_is_blocked(bs, BLOCK_OP_TYPE_MIRROR, errp)) {
2886 goto out;
2889 flags = bs->open_flags | BDRV_O_RDWR;
2890 source = backing_bs(bs);
2891 if (!source && sync == MIRROR_SYNC_MODE_TOP) {
2892 sync = MIRROR_SYNC_MODE_FULL;
2894 if (sync == MIRROR_SYNC_MODE_NONE) {
2895 source = bs;
2898 size = bdrv_getlength(bs);
2899 if (size < 0) {
2900 error_setg_errno(errp, -size, "bdrv_getlength failed");
2901 goto out;
2904 if (has_replaces) {
2905 BlockDriverState *to_replace_bs;
2906 AioContext *replace_aio_context;
2907 int64_t replace_size;
2909 if (!has_node_name) {
2910 error_setg(errp, "a node-name must be provided when replacing a"
2911 " named node of the graph");
2912 goto out;
2915 to_replace_bs = check_to_replace_node(bs, replaces, &local_err);
2917 if (!to_replace_bs) {
2918 error_propagate(errp, local_err);
2919 goto out;
2922 replace_aio_context = bdrv_get_aio_context(to_replace_bs);
2923 aio_context_acquire(replace_aio_context);
2924 replace_size = bdrv_getlength(to_replace_bs);
2925 aio_context_release(replace_aio_context);
2927 if (size != replace_size) {
2928 error_setg(errp, "cannot replace image with a mirror image of "
2929 "different size");
2930 goto out;
2934 if ((sync == MIRROR_SYNC_MODE_FULL || !source)
2935 && mode != NEW_IMAGE_MODE_EXISTING)
2937 /* create new image w/o backing file */
2938 assert(format);
2939 bdrv_img_create(target, format,
2940 NULL, NULL, NULL, size, flags, &local_err, false);
2941 } else {
2942 switch (mode) {
2943 case NEW_IMAGE_MODE_EXISTING:
2944 break;
2945 case NEW_IMAGE_MODE_ABSOLUTE_PATHS:
2946 /* create new image with backing file */
2947 bdrv_img_create(target, format,
2948 source->filename,
2949 source->drv->format_name,
2950 NULL, size, flags, &local_err, false);
2951 break;
2952 default:
2953 abort();
2957 if (local_err) {
2958 error_propagate(errp, local_err);
2959 goto out;
2962 options = qdict_new();
2963 if (has_node_name) {
2964 qdict_put(options, "node-name", qstring_from_str(node_name));
2966 if (format) {
2967 qdict_put(options, "driver", qstring_from_str(format));
2970 /* Mirroring takes care of copy-on-write using the source's backing
2971 * file.
2973 target_bs = NULL;
2974 ret = bdrv_open(&target_bs, target, NULL, options,
2975 flags | BDRV_O_NO_BACKING, &local_err);
2976 if (ret < 0) {
2977 error_propagate(errp, local_err);
2978 goto out;
2981 bdrv_set_aio_context(target_bs, aio_context);
2983 /* pass the node name to replace to mirror start since it's loose coupling
2984 * and will allow to check whether the node still exist at mirror completion
2986 mirror_start(bs, target_bs,
2987 has_replaces ? replaces : NULL,
2988 speed, granularity, buf_size, sync,
2989 on_source_error, on_target_error,
2990 unmap,
2991 block_job_cb, bs, &local_err);
2992 if (local_err != NULL) {
2993 bdrv_unref(target_bs);
2994 error_propagate(errp, local_err);
2995 goto out;
2998 out:
2999 aio_context_release(aio_context);
3002 /* Get the block job for a given device name and acquire its AioContext */
3003 static BlockJob *find_block_job(const char *device, AioContext **aio_context,
3004 Error **errp)
3006 BlockBackend *blk;
3007 BlockDriverState *bs;
3009 *aio_context = NULL;
3011 blk = blk_by_name(device);
3012 if (!blk) {
3013 goto notfound;
3016 *aio_context = blk_get_aio_context(blk);
3017 aio_context_acquire(*aio_context);
3019 if (!blk_is_available(blk)) {
3020 goto notfound;
3022 bs = blk_bs(blk);
3024 if (!bs->job) {
3025 goto notfound;
3028 return bs->job;
3030 notfound:
3031 error_set(errp, ERROR_CLASS_DEVICE_NOT_ACTIVE,
3032 "No active block job on device '%s'", device);
3033 if (*aio_context) {
3034 aio_context_release(*aio_context);
3035 *aio_context = NULL;
3037 return NULL;
3040 void qmp_block_job_set_speed(const char *device, int64_t speed, Error **errp)
3042 AioContext *aio_context;
3043 BlockJob *job = find_block_job(device, &aio_context, errp);
3045 if (!job) {
3046 return;
3049 block_job_set_speed(job, speed, errp);
3050 aio_context_release(aio_context);
3053 void qmp_block_job_cancel(const char *device,
3054 bool has_force, bool force, Error **errp)
3056 AioContext *aio_context;
3057 BlockJob *job = find_block_job(device, &aio_context, errp);
3059 if (!job) {
3060 return;
3063 if (!has_force) {
3064 force = false;
3067 if (job->user_paused && !force) {
3068 error_setg(errp, "The block job for device '%s' is currently paused",
3069 device);
3070 goto out;
3073 trace_qmp_block_job_cancel(job);
3074 block_job_cancel(job);
3075 out:
3076 aio_context_release(aio_context);
3079 void qmp_block_job_pause(const char *device, Error **errp)
3081 AioContext *aio_context;
3082 BlockJob *job = find_block_job(device, &aio_context, errp);
3084 if (!job || job->user_paused) {
3085 return;
3088 job->user_paused = true;
3089 trace_qmp_block_job_pause(job);
3090 block_job_pause(job);
3091 aio_context_release(aio_context);
3094 void qmp_block_job_resume(const char *device, Error **errp)
3096 AioContext *aio_context;
3097 BlockJob *job = find_block_job(device, &aio_context, errp);
3099 if (!job || !job->user_paused) {
3100 return;
3103 job->user_paused = false;
3104 trace_qmp_block_job_resume(job);
3105 block_job_resume(job);
3106 aio_context_release(aio_context);
3109 void qmp_block_job_complete(const char *device, Error **errp)
3111 AioContext *aio_context;
3112 BlockJob *job = find_block_job(device, &aio_context, errp);
3114 if (!job) {
3115 return;
3118 trace_qmp_block_job_complete(job);
3119 block_job_complete(job, errp);
3120 aio_context_release(aio_context);
3123 void qmp_change_backing_file(const char *device,
3124 const char *image_node_name,
3125 const char *backing_file,
3126 Error **errp)
3128 BlockBackend *blk;
3129 BlockDriverState *bs = NULL;
3130 AioContext *aio_context;
3131 BlockDriverState *image_bs = NULL;
3132 Error *local_err = NULL;
3133 bool ro;
3134 int open_flags;
3135 int ret;
3137 blk = blk_by_name(device);
3138 if (!blk) {
3139 error_set(errp, ERROR_CLASS_DEVICE_NOT_FOUND,
3140 "Device '%s' not found", device);
3141 return;
3144 aio_context = blk_get_aio_context(blk);
3145 aio_context_acquire(aio_context);
3147 if (!blk_is_available(blk)) {
3148 error_setg(errp, "Device '%s' has no medium", device);
3149 goto out;
3151 bs = blk_bs(blk);
3153 image_bs = bdrv_lookup_bs(NULL, image_node_name, &local_err);
3154 if (local_err) {
3155 error_propagate(errp, local_err);
3156 goto out;
3159 if (!image_bs) {
3160 error_setg(errp, "image file not found");
3161 goto out;
3164 if (bdrv_find_base(image_bs) == image_bs) {
3165 error_setg(errp, "not allowing backing file change on an image "
3166 "without a backing file");
3167 goto out;
3170 /* even though we are not necessarily operating on bs, we need it to
3171 * determine if block ops are currently prohibited on the chain */
3172 if (bdrv_op_is_blocked(bs, BLOCK_OP_TYPE_CHANGE, errp)) {
3173 goto out;
3176 /* final sanity check */
3177 if (!bdrv_chain_contains(bs, image_bs)) {
3178 error_setg(errp, "'%s' and image file are not in the same chain",
3179 device);
3180 goto out;
3183 /* if not r/w, reopen to make r/w */
3184 open_flags = image_bs->open_flags;
3185 ro = bdrv_is_read_only(image_bs);
3187 if (ro) {
3188 bdrv_reopen(image_bs, open_flags | BDRV_O_RDWR, &local_err);
3189 if (local_err) {
3190 error_propagate(errp, local_err);
3191 goto out;
3195 ret = bdrv_change_backing_file(image_bs, backing_file,
3196 image_bs->drv ? image_bs->drv->format_name : "");
3198 if (ret < 0) {
3199 error_setg_errno(errp, -ret, "Could not change backing file to '%s'",
3200 backing_file);
3201 /* don't exit here, so we can try to restore open flags if
3202 * appropriate */
3205 if (ro) {
3206 bdrv_reopen(image_bs, open_flags, &local_err);
3207 if (local_err) {
3208 error_propagate(errp, local_err); /* will preserve prior errp */
3212 out:
3213 aio_context_release(aio_context);
3216 void qmp_blockdev_add(BlockdevOptions *options, Error **errp)
3218 QmpOutputVisitor *ov = qmp_output_visitor_new();
3219 BlockDriverState *bs;
3220 BlockBackend *blk = NULL;
3221 QObject *obj;
3222 QDict *qdict;
3223 Error *local_err = NULL;
3225 /* TODO Sort it out in raw-posix and drive_new(): Reject aio=native with
3226 * cache.direct=false instead of silently switching to aio=threads, except
3227 * when called from drive_new().
3229 * For now, simply forbidding the combination for all drivers will do. */
3230 if (options->has_aio && options->aio == BLOCKDEV_AIO_OPTIONS_NATIVE) {
3231 bool direct = options->has_cache &&
3232 options->cache->has_direct &&
3233 options->cache->direct;
3234 if (!direct) {
3235 error_setg(errp, "aio=native requires cache.direct=true");
3236 goto fail;
3240 visit_type_BlockdevOptions(qmp_output_get_visitor(ov),
3241 &options, NULL, &local_err);
3242 if (local_err) {
3243 error_propagate(errp, local_err);
3244 goto fail;
3247 obj = qmp_output_get_qobject(ov);
3248 qdict = qobject_to_qdict(obj);
3250 qdict_flatten(qdict);
3252 if (options->has_id) {
3253 blk = blockdev_init(NULL, qdict, &local_err);
3254 if (local_err) {
3255 error_propagate(errp, local_err);
3256 goto fail;
3259 bs = blk_bs(blk);
3260 } else {
3261 if (!qdict_get_try_str(qdict, "node-name")) {
3262 error_setg(errp, "'id' and/or 'node-name' need to be specified for "
3263 "the root node");
3264 goto fail;
3267 bs = bds_tree_init(qdict, errp);
3268 if (!bs) {
3269 goto fail;
3273 if (bs && bdrv_key_required(bs)) {
3274 if (blk) {
3275 blk_unref(blk);
3276 } else {
3277 bdrv_unref(bs);
3279 error_setg(errp, "blockdev-add doesn't support encrypted devices");
3280 goto fail;
3283 fail:
3284 qmp_output_visitor_cleanup(ov);
3287 BlockJobInfoList *qmp_query_block_jobs(Error **errp)
3289 BlockJobInfoList *head = NULL, **p_next = &head;
3290 BlockDriverState *bs;
3292 for (bs = bdrv_next(NULL); bs; bs = bdrv_next(bs)) {
3293 AioContext *aio_context = bdrv_get_aio_context(bs);
3295 aio_context_acquire(aio_context);
3297 if (bs->job) {
3298 BlockJobInfoList *elem = g_new0(BlockJobInfoList, 1);
3299 elem->value = block_job_query(bs->job);
3300 *p_next = elem;
3301 p_next = &elem->next;
3304 aio_context_release(aio_context);
3307 return head;
3310 QemuOptsList qemu_common_drive_opts = {
3311 .name = "drive",
3312 .head = QTAILQ_HEAD_INITIALIZER(qemu_common_drive_opts.head),
3313 .desc = {
3315 .name = "snapshot",
3316 .type = QEMU_OPT_BOOL,
3317 .help = "enable/disable snapshot mode",
3319 .name = "discard",
3320 .type = QEMU_OPT_STRING,
3321 .help = "discard operation (ignore/off, unmap/on)",
3323 .name = BDRV_OPT_CACHE_WB,
3324 .type = QEMU_OPT_BOOL,
3325 .help = "enables writeback mode for any caches",
3327 .name = BDRV_OPT_CACHE_DIRECT,
3328 .type = QEMU_OPT_BOOL,
3329 .help = "enables use of O_DIRECT (bypass the host page cache)",
3331 .name = BDRV_OPT_CACHE_NO_FLUSH,
3332 .type = QEMU_OPT_BOOL,
3333 .help = "ignore any flush requests for the device",
3335 .name = "aio",
3336 .type = QEMU_OPT_STRING,
3337 .help = "host AIO implementation (threads, native)",
3339 .name = "format",
3340 .type = QEMU_OPT_STRING,
3341 .help = "disk format (raw, qcow2, ...)",
3343 .name = "rerror",
3344 .type = QEMU_OPT_STRING,
3345 .help = "read error action",
3347 .name = "werror",
3348 .type = QEMU_OPT_STRING,
3349 .help = "write error action",
3351 .name = "read-only",
3352 .type = QEMU_OPT_BOOL,
3353 .help = "open drive file as read-only",
3355 .name = "throttling.iops-total",
3356 .type = QEMU_OPT_NUMBER,
3357 .help = "limit total I/O operations per second",
3359 .name = "throttling.iops-read",
3360 .type = QEMU_OPT_NUMBER,
3361 .help = "limit read operations per second",
3363 .name = "throttling.iops-write",
3364 .type = QEMU_OPT_NUMBER,
3365 .help = "limit write operations per second",
3367 .name = "throttling.bps-total",
3368 .type = QEMU_OPT_NUMBER,
3369 .help = "limit total bytes per second",
3371 .name = "throttling.bps-read",
3372 .type = QEMU_OPT_NUMBER,
3373 .help = "limit read bytes per second",
3375 .name = "throttling.bps-write",
3376 .type = QEMU_OPT_NUMBER,
3377 .help = "limit write bytes per second",
3379 .name = "throttling.iops-total-max",
3380 .type = QEMU_OPT_NUMBER,
3381 .help = "I/O operations burst",
3383 .name = "throttling.iops-read-max",
3384 .type = QEMU_OPT_NUMBER,
3385 .help = "I/O operations read burst",
3387 .name = "throttling.iops-write-max",
3388 .type = QEMU_OPT_NUMBER,
3389 .help = "I/O operations write burst",
3391 .name = "throttling.bps-total-max",
3392 .type = QEMU_OPT_NUMBER,
3393 .help = "total bytes burst",
3395 .name = "throttling.bps-read-max",
3396 .type = QEMU_OPT_NUMBER,
3397 .help = "total bytes read burst",
3399 .name = "throttling.bps-write-max",
3400 .type = QEMU_OPT_NUMBER,
3401 .help = "total bytes write burst",
3403 .name = "throttling.iops-size",
3404 .type = QEMU_OPT_NUMBER,
3405 .help = "when limiting by iops max size of an I/O in bytes",
3407 .name = "throttling.group",
3408 .type = QEMU_OPT_STRING,
3409 .help = "name of the block throttling group",
3411 .name = "copy-on-read",
3412 .type = QEMU_OPT_BOOL,
3413 .help = "copy read data from backing file into image file",
3415 .name = "detect-zeroes",
3416 .type = QEMU_OPT_STRING,
3417 .help = "try to optimize zero writes (off, on, unmap)",
3419 { /* end of list */ }
3423 static QemuOptsList qemu_root_bds_opts = {
3424 .name = "root-bds",
3425 .head = QTAILQ_HEAD_INITIALIZER(qemu_common_drive_opts.head),
3426 .desc = {
3428 .name = "discard",
3429 .type = QEMU_OPT_STRING,
3430 .help = "discard operation (ignore/off, unmap/on)",
3432 .name = "cache.writeback",
3433 .type = QEMU_OPT_BOOL,
3434 .help = "enables writeback mode for any caches",
3436 .name = "cache.direct",
3437 .type = QEMU_OPT_BOOL,
3438 .help = "enables use of O_DIRECT (bypass the host page cache)",
3440 .name = "cache.no-flush",
3441 .type = QEMU_OPT_BOOL,
3442 .help = "ignore any flush requests for the device",
3444 .name = "aio",
3445 .type = QEMU_OPT_STRING,
3446 .help = "host AIO implementation (threads, native)",
3448 .name = "read-only",
3449 .type = QEMU_OPT_BOOL,
3450 .help = "open drive file as read-only",
3452 .name = "copy-on-read",
3453 .type = QEMU_OPT_BOOL,
3454 .help = "copy read data from backing file into image file",
3456 .name = "detect-zeroes",
3457 .type = QEMU_OPT_STRING,
3458 .help = "try to optimize zero writes (off, on, unmap)",
3460 { /* end of list */ }
3464 QemuOptsList qemu_drive_opts = {
3465 .name = "drive",
3466 .head = QTAILQ_HEAD_INITIALIZER(qemu_drive_opts.head),
3467 .desc = {
3469 * no elements => accept any params
3470 * validation will happen later
3472 { /* end of list */ }