block: Make BlockBackend own its BlockDriverState
[qemu-kvm.git] / blockdev.c
blob63f797b417095ef6a3846b68132ee7f1e74639cb
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 "monitor/monitor.h"
38 #include "qemu/option.h"
39 #include "qemu/config-file.h"
40 #include "qapi/qmp/types.h"
41 #include "qapi-visit.h"
42 #include "qapi/qmp-output-visitor.h"
43 #include "qapi/util.h"
44 #include "sysemu/sysemu.h"
45 #include "block/block_int.h"
46 #include "qmp-commands.h"
47 #include "trace.h"
48 #include "sysemu/arch_init.h"
50 static const char *const if_name[IF_COUNT] = {
51 [IF_NONE] = "none",
52 [IF_IDE] = "ide",
53 [IF_SCSI] = "scsi",
54 [IF_FLOPPY] = "floppy",
55 [IF_PFLASH] = "pflash",
56 [IF_MTD] = "mtd",
57 [IF_SD] = "sd",
58 [IF_VIRTIO] = "virtio",
59 [IF_XEN] = "xen",
62 static int if_max_devs[IF_COUNT] = {
64 * Do not change these numbers! They govern how drive option
65 * index maps to unit and bus. That mapping is ABI.
67 * All controllers used to imlement if=T drives need to support
68 * if_max_devs[T] units, for any T with if_max_devs[T] != 0.
69 * Otherwise, some index values map to "impossible" bus, unit
70 * values.
72 * For instance, if you change [IF_SCSI] to 255, -drive
73 * if=scsi,index=12 no longer means bus=1,unit=5, but
74 * bus=0,unit=12. With an lsi53c895a controller (7 units max),
75 * the drive can't be set up. Regression.
77 [IF_IDE] = 2,
78 [IF_SCSI] = 7,
81 /**
82 * Boards may call this to offer board-by-board overrides
83 * of the default, global values.
85 void override_max_devs(BlockInterfaceType type, int max_devs)
87 BlockBackend *blk;
88 DriveInfo *dinfo;
90 if (max_devs <= 0) {
91 return;
94 for (blk = blk_next(NULL); blk; blk = blk_next(blk)) {
95 dinfo = blk_legacy_dinfo(blk);
96 if (dinfo->type == type) {
97 fprintf(stderr, "Cannot override units-per-bus property of"
98 " the %s interface, because a drive of that type has"
99 " already been added.\n", if_name[type]);
100 g_assert_not_reached();
104 if_max_devs[type] = max_devs;
108 * We automatically delete the drive when a device using it gets
109 * unplugged. Questionable feature, but we can't just drop it.
110 * Device models call blockdev_mark_auto_del() to schedule the
111 * automatic deletion, and generic qdev code calls blockdev_auto_del()
112 * when deletion is actually safe.
114 void blockdev_mark_auto_del(BlockDriverState *bs)
116 BlockBackend *blk = bs->blk;
117 DriveInfo *dinfo = blk_legacy_dinfo(blk);
119 if (dinfo && !dinfo->enable_auto_del) {
120 return;
123 if (bs->job) {
124 block_job_cancel(bs->job);
126 if (dinfo) {
127 dinfo->auto_del = 1;
131 void blockdev_auto_del(BlockDriverState *bs)
133 BlockBackend *blk = bs->blk;
134 DriveInfo *dinfo = blk_legacy_dinfo(blk);
136 if (dinfo && dinfo->auto_del) {
137 drive_del(dinfo);
142 * Returns the current mapping of how many units per bus
143 * a particular interface can support.
145 * A positive integer indicates n units per bus.
146 * 0 implies the mapping has not been established.
147 * -1 indicates an invalid BlockInterfaceType was given.
149 int drive_get_max_devs(BlockInterfaceType type)
151 if (type >= IF_IDE && type < IF_COUNT) {
152 return if_max_devs[type];
155 return -1;
158 static int drive_index_to_bus_id(BlockInterfaceType type, int index)
160 int max_devs = if_max_devs[type];
161 return max_devs ? index / max_devs : 0;
164 static int drive_index_to_unit_id(BlockInterfaceType type, int index)
166 int max_devs = if_max_devs[type];
167 return max_devs ? index % max_devs : index;
170 QemuOpts *drive_def(const char *optstr)
172 return qemu_opts_parse(qemu_find_opts("drive"), optstr, 0);
175 QemuOpts *drive_add(BlockInterfaceType type, int index, const char *file,
176 const char *optstr)
178 QemuOpts *opts;
179 char buf[32];
181 opts = drive_def(optstr);
182 if (!opts) {
183 return NULL;
185 if (type != IF_DEFAULT) {
186 qemu_opt_set(opts, "if", if_name[type]);
188 if (index >= 0) {
189 snprintf(buf, sizeof(buf), "%d", index);
190 qemu_opt_set(opts, "index", buf);
192 if (file)
193 qemu_opt_set(opts, "file", file);
194 return opts;
197 DriveInfo *drive_get(BlockInterfaceType type, int bus, int unit)
199 BlockBackend *blk;
200 DriveInfo *dinfo;
202 for (blk = blk_next(NULL); blk; blk = blk_next(blk)) {
203 dinfo = blk_legacy_dinfo(blk);
204 if (dinfo && dinfo->type == type
205 && dinfo->bus == bus && dinfo->unit == unit) {
206 return dinfo;
210 return NULL;
213 bool drive_check_orphaned(void)
215 BlockBackend *blk;
216 DriveInfo *dinfo;
217 bool rs = false;
219 for (blk = blk_next(NULL); blk; blk = blk_next(blk)) {
220 dinfo = blk_legacy_dinfo(blk);
221 /* If dinfo->bdrv->dev is NULL, it has no device attached. */
222 /* Unless this is a default drive, this may be an oversight. */
223 if (!dinfo->bdrv->dev && !dinfo->is_default &&
224 dinfo->type != IF_NONE) {
225 fprintf(stderr, "Warning: Orphaned drive without device: "
226 "id=%s,file=%s,if=%s,bus=%d,unit=%d\n",
227 dinfo->id, dinfo->bdrv->filename, if_name[dinfo->type],
228 dinfo->bus, dinfo->unit);
229 rs = true;
233 return rs;
236 DriveInfo *drive_get_by_index(BlockInterfaceType type, int index)
238 return drive_get(type,
239 drive_index_to_bus_id(type, index),
240 drive_index_to_unit_id(type, index));
243 int drive_get_max_bus(BlockInterfaceType type)
245 int max_bus;
246 BlockBackend *blk;
247 DriveInfo *dinfo;
249 max_bus = -1;
250 for (blk = blk_next(NULL); blk; blk = blk_next(blk)) {
251 dinfo = blk_legacy_dinfo(blk);
252 if (dinfo && dinfo->type == type && dinfo->bus > max_bus) {
253 max_bus = dinfo->bus;
256 return max_bus;
259 /* Get a block device. This should only be used for single-drive devices
260 (e.g. SD/Floppy/MTD). Multi-disk devices (scsi/ide) should use the
261 appropriate bus. */
262 DriveInfo *drive_get_next(BlockInterfaceType type)
264 static int next_block_unit[IF_COUNT];
266 return drive_get(type, 0, next_block_unit[type]++);
269 DriveInfo *drive_get_by_blockdev(BlockDriverState *bs)
271 return bs->blk ? blk_legacy_dinfo(bs->blk) : NULL;
274 static void bdrv_format_print(void *opaque, const char *name)
276 error_printf(" %s", name);
279 void drive_del(DriveInfo *dinfo)
281 blk_unref(dinfo->bdrv->blk);
284 typedef struct {
285 QEMUBH *bh;
286 BlockDriverState *bs;
287 } BDRVPutRefBH;
289 static void bdrv_put_ref_bh(void *opaque)
291 BDRVPutRefBH *s = opaque;
293 bdrv_unref(s->bs);
294 qemu_bh_delete(s->bh);
295 g_free(s);
299 * Release a BDS reference in a BH
301 * It is not safe to use bdrv_unref() from a callback function when the callers
302 * still need the BlockDriverState. In such cases we schedule a BH to release
303 * the reference.
305 static void bdrv_put_ref_bh_schedule(BlockDriverState *bs)
307 BDRVPutRefBH *s;
309 s = g_new(BDRVPutRefBH, 1);
310 s->bh = qemu_bh_new(bdrv_put_ref_bh, s);
311 s->bs = bs;
312 qemu_bh_schedule(s->bh);
315 static int parse_block_error_action(const char *buf, bool is_read, Error **errp)
317 if (!strcmp(buf, "ignore")) {
318 return BLOCKDEV_ON_ERROR_IGNORE;
319 } else if (!is_read && !strcmp(buf, "enospc")) {
320 return BLOCKDEV_ON_ERROR_ENOSPC;
321 } else if (!strcmp(buf, "stop")) {
322 return BLOCKDEV_ON_ERROR_STOP;
323 } else if (!strcmp(buf, "report")) {
324 return BLOCKDEV_ON_ERROR_REPORT;
325 } else {
326 error_setg(errp, "'%s' invalid %s error action",
327 buf, is_read ? "read" : "write");
328 return -1;
332 static bool check_throttle_config(ThrottleConfig *cfg, Error **errp)
334 if (throttle_conflicting(cfg)) {
335 error_setg(errp, "bps/iops/max total values and read/write values"
336 " cannot be used at the same time");
337 return false;
340 if (!throttle_is_valid(cfg)) {
341 error_setg(errp, "bps/iops/maxs values must be 0 or greater");
342 return false;
345 return true;
348 typedef enum { MEDIA_DISK, MEDIA_CDROM } DriveMediaType;
350 /* Takes the ownership of bs_opts */
351 static BlockBackend *blockdev_init(const char *file, QDict *bs_opts,
352 Error **errp)
354 const char *buf;
355 int ro = 0;
356 int bdrv_flags = 0;
357 int on_read_error, on_write_error;
358 BlockBackend *blk;
359 BlockDriverState *bs;
360 DriveInfo *dinfo;
361 ThrottleConfig cfg;
362 int snapshot = 0;
363 bool copy_on_read;
364 int ret;
365 Error *error = NULL;
366 QemuOpts *opts;
367 const char *id;
368 bool has_driver_specific_opts;
369 BlockdevDetectZeroesOptions detect_zeroes;
370 BlockDriver *drv = NULL;
372 /* Check common options by copying from bs_opts to opts, all other options
373 * stay in bs_opts for processing by bdrv_open(). */
374 id = qdict_get_try_str(bs_opts, "id");
375 opts = qemu_opts_create(&qemu_common_drive_opts, id, 1, &error);
376 if (error) {
377 error_propagate(errp, error);
378 goto err_no_opts;
381 qemu_opts_absorb_qdict(opts, bs_opts, &error);
382 if (error) {
383 error_propagate(errp, error);
384 goto early_err;
387 if (id) {
388 qdict_del(bs_opts, "id");
391 has_driver_specific_opts = !!qdict_size(bs_opts);
393 /* extract parameters */
394 snapshot = qemu_opt_get_bool(opts, "snapshot", 0);
395 ro = qemu_opt_get_bool(opts, "read-only", 0);
396 copy_on_read = qemu_opt_get_bool(opts, "copy-on-read", false);
398 if ((buf = qemu_opt_get(opts, "discard")) != NULL) {
399 if (bdrv_parse_discard_flags(buf, &bdrv_flags) != 0) {
400 error_setg(errp, "invalid discard option");
401 goto early_err;
405 if (qemu_opt_get_bool(opts, "cache.writeback", true)) {
406 bdrv_flags |= BDRV_O_CACHE_WB;
408 if (qemu_opt_get_bool(opts, "cache.direct", false)) {
409 bdrv_flags |= BDRV_O_NOCACHE;
411 if (qemu_opt_get_bool(opts, "cache.no-flush", false)) {
412 bdrv_flags |= BDRV_O_NO_FLUSH;
415 #ifdef CONFIG_LINUX_AIO
416 if ((buf = qemu_opt_get(opts, "aio")) != NULL) {
417 if (!strcmp(buf, "native")) {
418 bdrv_flags |= BDRV_O_NATIVE_AIO;
419 } else if (!strcmp(buf, "threads")) {
420 /* this is the default */
421 } else {
422 error_setg(errp, "invalid aio option");
423 goto early_err;
426 #endif
428 if ((buf = qemu_opt_get(opts, "format")) != NULL) {
429 if (is_help_option(buf)) {
430 error_printf("Supported formats:");
431 bdrv_iterate_format(bdrv_format_print, NULL);
432 error_printf("\n");
433 goto early_err;
436 drv = bdrv_find_format(buf);
437 if (!drv) {
438 error_setg(errp, "'%s' invalid format", buf);
439 goto early_err;
443 /* disk I/O throttling */
444 memset(&cfg, 0, sizeof(cfg));
445 cfg.buckets[THROTTLE_BPS_TOTAL].avg =
446 qemu_opt_get_number(opts, "throttling.bps-total", 0);
447 cfg.buckets[THROTTLE_BPS_READ].avg =
448 qemu_opt_get_number(opts, "throttling.bps-read", 0);
449 cfg.buckets[THROTTLE_BPS_WRITE].avg =
450 qemu_opt_get_number(opts, "throttling.bps-write", 0);
451 cfg.buckets[THROTTLE_OPS_TOTAL].avg =
452 qemu_opt_get_number(opts, "throttling.iops-total", 0);
453 cfg.buckets[THROTTLE_OPS_READ].avg =
454 qemu_opt_get_number(opts, "throttling.iops-read", 0);
455 cfg.buckets[THROTTLE_OPS_WRITE].avg =
456 qemu_opt_get_number(opts, "throttling.iops-write", 0);
458 cfg.buckets[THROTTLE_BPS_TOTAL].max =
459 qemu_opt_get_number(opts, "throttling.bps-total-max", 0);
460 cfg.buckets[THROTTLE_BPS_READ].max =
461 qemu_opt_get_number(opts, "throttling.bps-read-max", 0);
462 cfg.buckets[THROTTLE_BPS_WRITE].max =
463 qemu_opt_get_number(opts, "throttling.bps-write-max", 0);
464 cfg.buckets[THROTTLE_OPS_TOTAL].max =
465 qemu_opt_get_number(opts, "throttling.iops-total-max", 0);
466 cfg.buckets[THROTTLE_OPS_READ].max =
467 qemu_opt_get_number(opts, "throttling.iops-read-max", 0);
468 cfg.buckets[THROTTLE_OPS_WRITE].max =
469 qemu_opt_get_number(opts, "throttling.iops-write-max", 0);
471 cfg.op_size = qemu_opt_get_number(opts, "throttling.iops-size", 0);
473 if (!check_throttle_config(&cfg, &error)) {
474 error_propagate(errp, error);
475 goto early_err;
478 on_write_error = BLOCKDEV_ON_ERROR_ENOSPC;
479 if ((buf = qemu_opt_get(opts, "werror")) != NULL) {
480 on_write_error = parse_block_error_action(buf, 0, &error);
481 if (error) {
482 error_propagate(errp, error);
483 goto early_err;
487 on_read_error = BLOCKDEV_ON_ERROR_REPORT;
488 if ((buf = qemu_opt_get(opts, "rerror")) != NULL) {
489 on_read_error = parse_block_error_action(buf, 1, &error);
490 if (error) {
491 error_propagate(errp, error);
492 goto early_err;
496 detect_zeroes =
497 qapi_enum_parse(BlockdevDetectZeroesOptions_lookup,
498 qemu_opt_get(opts, "detect-zeroes"),
499 BLOCKDEV_DETECT_ZEROES_OPTIONS_MAX,
500 BLOCKDEV_DETECT_ZEROES_OPTIONS_OFF,
501 &error);
502 if (error) {
503 error_propagate(errp, error);
504 goto early_err;
507 if (detect_zeroes == BLOCKDEV_DETECT_ZEROES_OPTIONS_UNMAP &&
508 !(bdrv_flags & BDRV_O_UNMAP)) {
509 error_setg(errp, "setting detect-zeroes to unmap is not allowed "
510 "without setting discard operation to unmap");
511 goto early_err;
514 /* init */
515 blk = blk_new_with_bs(qemu_opts_id(opts), errp);
516 if (!blk) {
517 goto early_err;
519 bs = blk_bs(blk);
520 bs->open_flags = snapshot ? BDRV_O_SNAPSHOT : 0;
521 bs->read_only = ro;
522 bs->detect_zeroes = detect_zeroes;
524 bdrv_set_on_error(bs, on_read_error, on_write_error);
526 /* disk I/O throttling */
527 if (throttle_enabled(&cfg)) {
528 bdrv_io_limits_enable(bs);
529 bdrv_set_io_limits(bs, &cfg);
532 dinfo = g_malloc0(sizeof(*dinfo));
533 dinfo->id = g_strdup(qemu_opts_id(opts));
534 dinfo->bdrv = bs;
535 blk_set_legacy_dinfo(blk, dinfo);
537 if (!file || !*file) {
538 if (has_driver_specific_opts) {
539 file = NULL;
540 } else {
541 QDECREF(bs_opts);
542 qemu_opts_del(opts);
543 return blk;
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 if (copy_on_read) {
553 bdrv_flags |= BDRV_O_COPY_ON_READ;
556 if (runstate_check(RUN_STATE_INMIGRATE)) {
557 bdrv_flags |= BDRV_O_INCOMING;
560 bdrv_flags |= ro ? 0 : BDRV_O_RDWR;
562 QINCREF(bs_opts);
563 ret = bdrv_open(&bs, file, NULL, bs_opts, bdrv_flags, drv, &error);
564 assert(bs == dinfo->bdrv);
566 if (ret < 0) {
567 error_setg(errp, "could not open disk image %s: %s",
568 file ?: dinfo->id, error_get_pretty(error));
569 error_free(error);
570 goto err;
573 if (bdrv_key_required(bs)) {
574 autostart = 0;
577 QDECREF(bs_opts);
578 qemu_opts_del(opts);
580 return blk;
582 err:
583 blk_unref(blk);
584 early_err:
585 qemu_opts_del(opts);
586 err_no_opts:
587 QDECREF(bs_opts);
588 return NULL;
591 static void qemu_opt_rename(QemuOpts *opts, const char *from, const char *to,
592 Error **errp)
594 const char *value;
596 value = qemu_opt_get(opts, from);
597 if (value) {
598 if (qemu_opt_find(opts, to)) {
599 error_setg(errp, "'%s' and its alias '%s' can't be used at the "
600 "same time", to, from);
601 return;
605 /* rename all items in opts */
606 while ((value = qemu_opt_get(opts, from))) {
607 qemu_opt_set(opts, to, value);
608 qemu_opt_unset(opts, from);
612 QemuOptsList qemu_legacy_drive_opts = {
613 .name = "drive",
614 .head = QTAILQ_HEAD_INITIALIZER(qemu_legacy_drive_opts.head),
615 .desc = {
617 .name = "bus",
618 .type = QEMU_OPT_NUMBER,
619 .help = "bus number",
621 .name = "unit",
622 .type = QEMU_OPT_NUMBER,
623 .help = "unit number (i.e. lun for scsi)",
625 .name = "index",
626 .type = QEMU_OPT_NUMBER,
627 .help = "index number",
629 .name = "media",
630 .type = QEMU_OPT_STRING,
631 .help = "media type (disk, cdrom)",
633 .name = "if",
634 .type = QEMU_OPT_STRING,
635 .help = "interface (ide, scsi, sd, mtd, floppy, pflash, virtio)",
637 .name = "cyls",
638 .type = QEMU_OPT_NUMBER,
639 .help = "number of cylinders (ide disk geometry)",
641 .name = "heads",
642 .type = QEMU_OPT_NUMBER,
643 .help = "number of heads (ide disk geometry)",
645 .name = "secs",
646 .type = QEMU_OPT_NUMBER,
647 .help = "number of sectors (ide disk geometry)",
649 .name = "trans",
650 .type = QEMU_OPT_STRING,
651 .help = "chs translation (auto, lba, none)",
653 .name = "boot",
654 .type = QEMU_OPT_BOOL,
655 .help = "(deprecated, ignored)",
657 .name = "addr",
658 .type = QEMU_OPT_STRING,
659 .help = "pci address (virtio only)",
661 .name = "serial",
662 .type = QEMU_OPT_STRING,
663 .help = "disk serial number",
665 .name = "file",
666 .type = QEMU_OPT_STRING,
667 .help = "file name",
670 /* Options that are passed on, but have special semantics with -drive */
672 .name = "read-only",
673 .type = QEMU_OPT_BOOL,
674 .help = "open drive file as read-only",
676 .name = "rerror",
677 .type = QEMU_OPT_STRING,
678 .help = "read error action",
680 .name = "werror",
681 .type = QEMU_OPT_STRING,
682 .help = "write error action",
684 .name = "copy-on-read",
685 .type = QEMU_OPT_BOOL,
686 .help = "copy read data from backing file into image file",
689 { /* end of list */ }
693 DriveInfo *drive_new(QemuOpts *all_opts, BlockInterfaceType block_default_type)
695 const char *value;
696 BlockBackend *blk;
697 DriveInfo *dinfo = NULL;
698 QDict *bs_opts;
699 QemuOpts *legacy_opts;
700 DriveMediaType media = MEDIA_DISK;
701 BlockInterfaceType type;
702 int cyls, heads, secs, translation;
703 int max_devs, bus_id, unit_id, index;
704 const char *devaddr;
705 const char *werror, *rerror;
706 bool read_only = false;
707 bool copy_on_read;
708 const char *serial;
709 const char *filename;
710 Error *local_err = NULL;
711 int i;
713 /* Change legacy command line options into QMP ones */
714 static const struct {
715 const char *from;
716 const char *to;
717 } opt_renames[] = {
718 { "iops", "throttling.iops-total" },
719 { "iops_rd", "throttling.iops-read" },
720 { "iops_wr", "throttling.iops-write" },
722 { "bps", "throttling.bps-total" },
723 { "bps_rd", "throttling.bps-read" },
724 { "bps_wr", "throttling.bps-write" },
726 { "iops_max", "throttling.iops-total-max" },
727 { "iops_rd_max", "throttling.iops-read-max" },
728 { "iops_wr_max", "throttling.iops-write-max" },
730 { "bps_max", "throttling.bps-total-max" },
731 { "bps_rd_max", "throttling.bps-read-max" },
732 { "bps_wr_max", "throttling.bps-write-max" },
734 { "iops_size", "throttling.iops-size" },
736 { "readonly", "read-only" },
739 for (i = 0; i < ARRAY_SIZE(opt_renames); i++) {
740 qemu_opt_rename(all_opts, opt_renames[i].from, opt_renames[i].to,
741 &local_err);
742 if (local_err) {
743 error_report("%s", error_get_pretty(local_err));
744 error_free(local_err);
745 return NULL;
749 value = qemu_opt_get(all_opts, "cache");
750 if (value) {
751 int flags = 0;
753 if (bdrv_parse_cache_flags(value, &flags) != 0) {
754 error_report("invalid cache option");
755 return NULL;
758 /* Specific options take precedence */
759 if (!qemu_opt_get(all_opts, "cache.writeback")) {
760 qemu_opt_set_bool(all_opts, "cache.writeback",
761 !!(flags & BDRV_O_CACHE_WB));
763 if (!qemu_opt_get(all_opts, "cache.direct")) {
764 qemu_opt_set_bool(all_opts, "cache.direct",
765 !!(flags & BDRV_O_NOCACHE));
767 if (!qemu_opt_get(all_opts, "cache.no-flush")) {
768 qemu_opt_set_bool(all_opts, "cache.no-flush",
769 !!(flags & BDRV_O_NO_FLUSH));
771 qemu_opt_unset(all_opts, "cache");
774 /* Get a QDict for processing the options */
775 bs_opts = qdict_new();
776 qemu_opts_to_qdict(all_opts, bs_opts);
778 legacy_opts = qemu_opts_create(&qemu_legacy_drive_opts, NULL, 0,
779 &error_abort);
780 qemu_opts_absorb_qdict(legacy_opts, bs_opts, &local_err);
781 if (local_err) {
782 error_report("%s", error_get_pretty(local_err));
783 error_free(local_err);
784 goto fail;
787 /* Deprecated option boot=[on|off] */
788 if (qemu_opt_get(legacy_opts, "boot") != NULL) {
789 fprintf(stderr, "qemu-kvm: boot=on|off is deprecated and will be "
790 "ignored. Future versions will reject this parameter. Please "
791 "update your scripts.\n");
794 /* Media type */
795 value = qemu_opt_get(legacy_opts, "media");
796 if (value) {
797 if (!strcmp(value, "disk")) {
798 media = MEDIA_DISK;
799 } else if (!strcmp(value, "cdrom")) {
800 media = MEDIA_CDROM;
801 read_only = true;
802 } else {
803 error_report("'%s' invalid media", value);
804 goto fail;
808 /* copy-on-read is disabled with a warning for read-only devices */
809 read_only |= qemu_opt_get_bool(legacy_opts, "read-only", false);
810 copy_on_read = qemu_opt_get_bool(legacy_opts, "copy-on-read", false);
812 if (read_only && copy_on_read) {
813 error_report("warning: disabling copy-on-read on read-only drive");
814 copy_on_read = false;
817 qdict_put(bs_opts, "read-only",
818 qstring_from_str(read_only ? "on" : "off"));
819 qdict_put(bs_opts, "copy-on-read",
820 qstring_from_str(copy_on_read ? "on" :"off"));
822 /* Controller type */
823 value = qemu_opt_get(legacy_opts, "if");
824 if (value) {
825 for (type = 0;
826 type < IF_COUNT && strcmp(value, if_name[type]);
827 type++) {
829 if (type == IF_COUNT) {
830 error_report("unsupported bus type '%s'", value);
831 goto fail;
833 } else {
834 type = block_default_type;
837 /* Geometry */
838 cyls = qemu_opt_get_number(legacy_opts, "cyls", 0);
839 heads = qemu_opt_get_number(legacy_opts, "heads", 0);
840 secs = qemu_opt_get_number(legacy_opts, "secs", 0);
842 if (cyls || heads || secs) {
843 if (cyls < 1) {
844 error_report("invalid physical cyls number");
845 goto fail;
847 if (heads < 1) {
848 error_report("invalid physical heads number");
849 goto fail;
851 if (secs < 1) {
852 error_report("invalid physical secs number");
853 goto fail;
857 translation = BIOS_ATA_TRANSLATION_AUTO;
858 value = qemu_opt_get(legacy_opts, "trans");
859 if (value != NULL) {
860 if (!cyls) {
861 error_report("'%s' trans must be used with cyls, heads and secs",
862 value);
863 goto fail;
865 if (!strcmp(value, "none")) {
866 translation = BIOS_ATA_TRANSLATION_NONE;
867 } else if (!strcmp(value, "lba")) {
868 translation = BIOS_ATA_TRANSLATION_LBA;
869 } else if (!strcmp(value, "large")) {
870 translation = BIOS_ATA_TRANSLATION_LARGE;
871 } else if (!strcmp(value, "rechs")) {
872 translation = BIOS_ATA_TRANSLATION_RECHS;
873 } else if (!strcmp(value, "auto")) {
874 translation = BIOS_ATA_TRANSLATION_AUTO;
875 } else {
876 error_report("'%s' invalid translation type", value);
877 goto fail;
881 if (media == MEDIA_CDROM) {
882 if (cyls || secs || heads) {
883 error_report("CHS can't be set with media=cdrom");
884 goto fail;
888 /* Device address specified by bus/unit or index.
889 * If none was specified, try to find the first free one. */
890 bus_id = qemu_opt_get_number(legacy_opts, "bus", 0);
891 unit_id = qemu_opt_get_number(legacy_opts, "unit", -1);
892 index = qemu_opt_get_number(legacy_opts, "index", -1);
894 max_devs = if_max_devs[type];
896 if (index != -1) {
897 if (bus_id != 0 || unit_id != -1) {
898 error_report("index cannot be used with bus and unit");
899 goto fail;
901 bus_id = drive_index_to_bus_id(type, index);
902 unit_id = drive_index_to_unit_id(type, index);
905 if (unit_id == -1) {
906 unit_id = 0;
907 while (drive_get(type, bus_id, unit_id) != NULL) {
908 unit_id++;
909 if (max_devs && unit_id >= max_devs) {
910 unit_id -= max_devs;
911 bus_id++;
916 if (max_devs && unit_id >= max_devs) {
917 error_report("unit %d too big (max is %d)", unit_id, max_devs - 1);
918 goto fail;
921 if (drive_get(type, bus_id, unit_id) != NULL) {
922 error_report("drive with bus=%d, unit=%d (index=%d) exists",
923 bus_id, unit_id, index);
924 goto fail;
927 /* Serial number */
928 serial = qemu_opt_get(legacy_opts, "serial");
930 /* no id supplied -> create one */
931 if (qemu_opts_id(all_opts) == NULL) {
932 char *new_id;
933 const char *mediastr = "";
934 if (type == IF_IDE || type == IF_SCSI) {
935 mediastr = (media == MEDIA_CDROM) ? "-cd" : "-hd";
937 if (max_devs) {
938 new_id = g_strdup_printf("%s%i%s%i", if_name[type], bus_id,
939 mediastr, unit_id);
940 } else {
941 new_id = g_strdup_printf("%s%s%i", if_name[type],
942 mediastr, unit_id);
944 qdict_put(bs_opts, "id", qstring_from_str(new_id));
945 g_free(new_id);
948 /* Add virtio block device */
949 devaddr = qemu_opt_get(legacy_opts, "addr");
950 if (devaddr && type != IF_VIRTIO) {
951 error_report("addr is not supported by this bus type");
952 goto fail;
955 if (type == IF_VIRTIO) {
956 QemuOpts *devopts;
957 devopts = qemu_opts_create(qemu_find_opts("device"), NULL, 0,
958 &error_abort);
959 if (arch_type == QEMU_ARCH_S390X) {
960 qemu_opt_set(devopts, "driver", "virtio-blk-s390");
961 } else {
962 qemu_opt_set(devopts, "driver", "virtio-blk-pci");
964 qemu_opt_set(devopts, "drive", qdict_get_str(bs_opts, "id"));
965 if (devaddr) {
966 qemu_opt_set(devopts, "addr", devaddr);
970 filename = qemu_opt_get(legacy_opts, "file");
972 /* Check werror/rerror compatibility with if=... */
973 werror = qemu_opt_get(legacy_opts, "werror");
974 if (werror != NULL) {
975 if (type != IF_IDE && type != IF_SCSI && type != IF_VIRTIO &&
976 type != IF_NONE) {
977 error_report("werror is not supported by this bus type");
978 goto fail;
980 qdict_put(bs_opts, "werror", qstring_from_str(werror));
983 rerror = qemu_opt_get(legacy_opts, "rerror");
984 if (rerror != NULL) {
985 if (type != IF_IDE && type != IF_VIRTIO && type != IF_SCSI &&
986 type != IF_NONE) {
987 error_report("rerror is not supported by this bus type");
988 goto fail;
990 qdict_put(bs_opts, "rerror", qstring_from_str(rerror));
993 /* Actual block device init: Functionality shared with blockdev-add */
994 blk = blockdev_init(filename, bs_opts, &local_err);
995 bs_opts = NULL;
996 if (!blk) {
997 if (local_err) {
998 error_report("%s", error_get_pretty(local_err));
999 error_free(local_err);
1001 goto fail;
1002 } else {
1003 assert(!local_err);
1006 /* Set legacy DriveInfo fields */
1007 dinfo = blk_legacy_dinfo(blk);
1008 dinfo->enable_auto_del = true;
1009 dinfo->opts = all_opts;
1011 dinfo->cyls = cyls;
1012 dinfo->heads = heads;
1013 dinfo->secs = secs;
1014 dinfo->trans = translation;
1016 dinfo->type = type;
1017 dinfo->bus = bus_id;
1018 dinfo->unit = unit_id;
1019 dinfo->devaddr = devaddr;
1021 dinfo->serial = g_strdup(serial);
1023 switch(type) {
1024 case IF_IDE:
1025 case IF_SCSI:
1026 case IF_XEN:
1027 case IF_NONE:
1028 dinfo->media_cd = media == MEDIA_CDROM;
1029 break;
1030 default:
1031 break;
1034 fail:
1035 qemu_opts_del(legacy_opts);
1036 QDECREF(bs_opts);
1037 return dinfo;
1040 void do_commit(Monitor *mon, const QDict *qdict)
1042 const char *device = qdict_get_str(qdict, "device");
1043 BlockDriverState *bs;
1044 int ret;
1046 if (!strcmp(device, "all")) {
1047 ret = bdrv_commit_all();
1048 } else {
1049 bs = bdrv_find(device);
1050 if (!bs) {
1051 monitor_printf(mon, "Device '%s' not found\n", device);
1052 return;
1054 ret = bdrv_commit(bs);
1056 if (ret < 0) {
1057 monitor_printf(mon, "'commit' error for '%s': %s\n", device,
1058 strerror(-ret));
1062 static void blockdev_do_action(int kind, void *data, Error **errp)
1064 TransactionAction action;
1065 TransactionActionList list;
1067 action.kind = kind;
1068 action.data = data;
1069 list.value = &action;
1070 list.next = NULL;
1071 qmp_transaction(&list, errp);
1074 void qmp_blockdev_snapshot_sync(bool has_device, const char *device,
1075 bool has_node_name, const char *node_name,
1076 const char *snapshot_file,
1077 bool has_snapshot_node_name,
1078 const char *snapshot_node_name,
1079 bool has_format, const char *format,
1080 bool has_mode, NewImageMode mode, Error **errp)
1082 BlockdevSnapshot snapshot = {
1083 .has_device = has_device,
1084 .device = (char *) device,
1085 .has_node_name = has_node_name,
1086 .node_name = (char *) node_name,
1087 .snapshot_file = (char *) snapshot_file,
1088 .has_snapshot_node_name = has_snapshot_node_name,
1089 .snapshot_node_name = (char *) snapshot_node_name,
1090 .has_format = has_format,
1091 .format = (char *) format,
1092 .has_mode = has_mode,
1093 .mode = mode,
1095 blockdev_do_action(TRANSACTION_ACTION_KIND_BLOCKDEV_SNAPSHOT_SYNC,
1096 &snapshot, errp);
1099 void qmp_blockdev_snapshot_internal_sync(const char *device,
1100 const char *name,
1101 Error **errp)
1103 BlockdevSnapshotInternal snapshot = {
1104 .device = (char *) device,
1105 .name = (char *) name
1108 blockdev_do_action(TRANSACTION_ACTION_KIND_BLOCKDEV_SNAPSHOT_INTERNAL_SYNC,
1109 &snapshot, errp);
1112 SnapshotInfo *qmp_blockdev_snapshot_delete_internal_sync(const char *device,
1113 bool has_id,
1114 const char *id,
1115 bool has_name,
1116 const char *name,
1117 Error **errp)
1119 BlockDriverState *bs = bdrv_find(device);
1120 QEMUSnapshotInfo sn;
1121 Error *local_err = NULL;
1122 SnapshotInfo *info = NULL;
1123 int ret;
1125 if (!bs) {
1126 error_set(errp, QERR_DEVICE_NOT_FOUND, device);
1127 return NULL;
1130 if (!has_id) {
1131 id = NULL;
1134 if (!has_name) {
1135 name = NULL;
1138 if (!id && !name) {
1139 error_setg(errp, "Name or id must be provided");
1140 return NULL;
1143 ret = bdrv_snapshot_find_by_id_and_name(bs, id, name, &sn, &local_err);
1144 if (local_err) {
1145 error_propagate(errp, local_err);
1146 return NULL;
1148 if (!ret) {
1149 error_setg(errp,
1150 "Snapshot with id '%s' and name '%s' does not exist on "
1151 "device '%s'",
1152 STR_OR_NULL(id), STR_OR_NULL(name), device);
1153 return NULL;
1156 bdrv_snapshot_delete(bs, id, name, &local_err);
1157 if (local_err) {
1158 error_propagate(errp, local_err);
1159 return NULL;
1162 info = g_new0(SnapshotInfo, 1);
1163 info->id = g_strdup(sn.id_str);
1164 info->name = g_strdup(sn.name);
1165 info->date_nsec = sn.date_nsec;
1166 info->date_sec = sn.date_sec;
1167 info->vm_state_size = sn.vm_state_size;
1168 info->vm_clock_nsec = sn.vm_clock_nsec % 1000000000;
1169 info->vm_clock_sec = sn.vm_clock_nsec / 1000000000;
1171 return info;
1174 /* New and old BlockDriverState structs for group snapshots */
1176 typedef struct BlkTransactionState BlkTransactionState;
1178 /* Only prepare() may fail. In a single transaction, only one of commit() or
1179 abort() will be called, clean() will always be called if it present. */
1180 typedef struct BdrvActionOps {
1181 /* Size of state struct, in bytes. */
1182 size_t instance_size;
1183 /* Prepare the work, must NOT be NULL. */
1184 void (*prepare)(BlkTransactionState *common, Error **errp);
1185 /* Commit the changes, can be NULL. */
1186 void (*commit)(BlkTransactionState *common);
1187 /* Abort the changes on fail, can be NULL. */
1188 void (*abort)(BlkTransactionState *common);
1189 /* Clean up resource in the end, can be NULL. */
1190 void (*clean)(BlkTransactionState *common);
1191 } BdrvActionOps;
1194 * This structure must be arranged as first member in child type, assuming
1195 * that compiler will also arrange it to the same address with parent instance.
1196 * Later it will be used in free().
1198 struct BlkTransactionState {
1199 TransactionAction *action;
1200 const BdrvActionOps *ops;
1201 QSIMPLEQ_ENTRY(BlkTransactionState) entry;
1204 /* internal snapshot private data */
1205 typedef struct InternalSnapshotState {
1206 BlkTransactionState common;
1207 BlockDriverState *bs;
1208 QEMUSnapshotInfo sn;
1209 } InternalSnapshotState;
1211 static void internal_snapshot_prepare(BlkTransactionState *common,
1212 Error **errp)
1214 Error *local_err = NULL;
1215 const char *device;
1216 const char *name;
1217 BlockDriverState *bs;
1218 QEMUSnapshotInfo old_sn, *sn;
1219 bool ret;
1220 qemu_timeval tv;
1221 BlockdevSnapshotInternal *internal;
1222 InternalSnapshotState *state;
1223 int ret1;
1225 g_assert(common->action->kind ==
1226 TRANSACTION_ACTION_KIND_BLOCKDEV_SNAPSHOT_INTERNAL_SYNC);
1227 internal = common->action->blockdev_snapshot_internal_sync;
1228 state = DO_UPCAST(InternalSnapshotState, common, common);
1230 /* 1. parse input */
1231 device = internal->device;
1232 name = internal->name;
1234 /* 2. check for validation */
1235 bs = bdrv_find(device);
1236 if (!bs) {
1237 error_set(errp, QERR_DEVICE_NOT_FOUND, device);
1238 return;
1241 if (!bdrv_is_inserted(bs)) {
1242 error_set(errp, QERR_DEVICE_HAS_NO_MEDIUM, device);
1243 return;
1246 if (bdrv_is_read_only(bs)) {
1247 error_set(errp, QERR_DEVICE_IS_READ_ONLY, device);
1248 return;
1251 if (!bdrv_can_snapshot(bs)) {
1252 error_set(errp, QERR_BLOCK_FORMAT_FEATURE_NOT_SUPPORTED,
1253 bs->drv->format_name, device, "internal snapshot");
1254 return;
1257 if (!strlen(name)) {
1258 error_setg(errp, "Name is empty");
1259 return;
1262 /* check whether a snapshot with name exist */
1263 ret = bdrv_snapshot_find_by_id_and_name(bs, NULL, name, &old_sn,
1264 &local_err);
1265 if (local_err) {
1266 error_propagate(errp, local_err);
1267 return;
1268 } else if (ret) {
1269 error_setg(errp,
1270 "Snapshot with name '%s' already exists on device '%s'",
1271 name, device);
1272 return;
1275 /* 3. take the snapshot */
1276 sn = &state->sn;
1277 pstrcpy(sn->name, sizeof(sn->name), name);
1278 qemu_gettimeofday(&tv);
1279 sn->date_sec = tv.tv_sec;
1280 sn->date_nsec = tv.tv_usec * 1000;
1281 sn->vm_clock_nsec = qemu_clock_get_ns(QEMU_CLOCK_VIRTUAL);
1283 ret1 = bdrv_snapshot_create(bs, sn);
1284 if (ret1 < 0) {
1285 error_setg_errno(errp, -ret1,
1286 "Failed to create snapshot '%s' on device '%s'",
1287 name, device);
1288 return;
1291 /* 4. succeed, mark a snapshot is created */
1292 state->bs = bs;
1295 static void internal_snapshot_abort(BlkTransactionState *common)
1297 InternalSnapshotState *state =
1298 DO_UPCAST(InternalSnapshotState, common, common);
1299 BlockDriverState *bs = state->bs;
1300 QEMUSnapshotInfo *sn = &state->sn;
1301 Error *local_error = NULL;
1303 if (!bs) {
1304 return;
1307 if (bdrv_snapshot_delete(bs, sn->id_str, sn->name, &local_error) < 0) {
1308 error_report("Failed to delete snapshot with id '%s' and name '%s' on "
1309 "device '%s' in abort: %s",
1310 sn->id_str,
1311 sn->name,
1312 bdrv_get_device_name(bs),
1313 error_get_pretty(local_error));
1314 error_free(local_error);
1318 /* external snapshot private data */
1319 typedef struct ExternalSnapshotState {
1320 BlkTransactionState common;
1321 BlockDriverState *old_bs;
1322 BlockDriverState *new_bs;
1323 } ExternalSnapshotState;
1325 static void external_snapshot_prepare(BlkTransactionState *common,
1326 Error **errp)
1328 BlockDriver *drv;
1329 int flags, ret;
1330 QDict *options = NULL;
1331 Error *local_err = NULL;
1332 bool has_device = false;
1333 const char *device;
1334 bool has_node_name = false;
1335 const char *node_name;
1336 bool has_snapshot_node_name = false;
1337 const char *snapshot_node_name;
1338 const char *new_image_file;
1339 const char *format = "qcow2";
1340 enum NewImageMode mode = NEW_IMAGE_MODE_ABSOLUTE_PATHS;
1341 ExternalSnapshotState *state =
1342 DO_UPCAST(ExternalSnapshotState, common, common);
1343 TransactionAction *action = common->action;
1345 /* get parameters */
1346 g_assert(action->kind == TRANSACTION_ACTION_KIND_BLOCKDEV_SNAPSHOT_SYNC);
1348 has_device = action->blockdev_snapshot_sync->has_device;
1349 device = action->blockdev_snapshot_sync->device;
1350 has_node_name = action->blockdev_snapshot_sync->has_node_name;
1351 node_name = action->blockdev_snapshot_sync->node_name;
1352 has_snapshot_node_name =
1353 action->blockdev_snapshot_sync->has_snapshot_node_name;
1354 snapshot_node_name = action->blockdev_snapshot_sync->snapshot_node_name;
1356 new_image_file = action->blockdev_snapshot_sync->snapshot_file;
1357 if (action->blockdev_snapshot_sync->has_format) {
1358 format = action->blockdev_snapshot_sync->format;
1360 if (action->blockdev_snapshot_sync->has_mode) {
1361 mode = action->blockdev_snapshot_sync->mode;
1364 /* start processing */
1365 drv = bdrv_find_format(format);
1366 if (!drv) {
1367 error_set(errp, QERR_INVALID_BLOCK_FORMAT, format);
1368 return;
1371 state->old_bs = bdrv_lookup_bs(has_device ? device : NULL,
1372 has_node_name ? node_name : NULL,
1373 &local_err);
1374 if (local_err) {
1375 error_propagate(errp, local_err);
1376 return;
1379 if (has_node_name && !has_snapshot_node_name) {
1380 error_setg(errp, "New snapshot node name missing");
1381 return;
1384 if (has_snapshot_node_name && bdrv_find_node(snapshot_node_name)) {
1385 error_setg(errp, "New snapshot node name already existing");
1386 return;
1389 if (!bdrv_is_inserted(state->old_bs)) {
1390 error_set(errp, QERR_DEVICE_HAS_NO_MEDIUM, device);
1391 return;
1394 if (bdrv_op_is_blocked(state->old_bs,
1395 BLOCK_OP_TYPE_EXTERNAL_SNAPSHOT, errp)) {
1396 return;
1399 if (!bdrv_is_read_only(state->old_bs)) {
1400 if (bdrv_flush(state->old_bs)) {
1401 error_set(errp, QERR_IO_ERROR);
1402 return;
1406 if (!bdrv_is_first_non_filter(state->old_bs)) {
1407 error_set(errp, QERR_FEATURE_DISABLED, "snapshot");
1408 return;
1411 flags = state->old_bs->open_flags;
1413 /* create new image w/backing file */
1414 if (mode != NEW_IMAGE_MODE_EXISTING) {
1415 bdrv_img_create(new_image_file, format,
1416 state->old_bs->filename,
1417 state->old_bs->drv->format_name,
1418 NULL, -1, flags, &local_err, false);
1419 if (local_err) {
1420 error_propagate(errp, local_err);
1421 return;
1425 if (has_snapshot_node_name) {
1426 options = qdict_new();
1427 qdict_put(options, "node-name",
1428 qstring_from_str(snapshot_node_name));
1431 /* TODO Inherit bs->options or only take explicit options with an
1432 * extended QMP command? */
1433 assert(state->new_bs == NULL);
1434 ret = bdrv_open(&state->new_bs, new_image_file, NULL, options,
1435 flags | BDRV_O_NO_BACKING, drv, &local_err);
1436 /* We will manually add the backing_hd field to the bs later */
1437 if (ret != 0) {
1438 error_propagate(errp, local_err);
1442 static void external_snapshot_commit(BlkTransactionState *common)
1444 ExternalSnapshotState *state =
1445 DO_UPCAST(ExternalSnapshotState, common, common);
1447 /* This removes our old bs and adds the new bs */
1448 bdrv_append(state->new_bs, state->old_bs);
1449 /* We don't need (or want) to use the transactional
1450 * bdrv_reopen_multiple() across all the entries at once, because we
1451 * don't want to abort all of them if one of them fails the reopen */
1452 bdrv_reopen(state->new_bs, state->new_bs->open_flags & ~BDRV_O_RDWR,
1453 NULL);
1456 static void external_snapshot_abort(BlkTransactionState *common)
1458 ExternalSnapshotState *state =
1459 DO_UPCAST(ExternalSnapshotState, common, common);
1460 if (state->new_bs) {
1461 bdrv_unref(state->new_bs);
1465 typedef struct DriveBackupState {
1466 BlkTransactionState common;
1467 BlockDriverState *bs;
1468 BlockJob *job;
1469 } DriveBackupState;
1471 static void drive_backup_prepare(BlkTransactionState *common, Error **errp)
1473 DriveBackupState *state = DO_UPCAST(DriveBackupState, common, common);
1474 DriveBackup *backup;
1475 Error *local_err = NULL;
1477 assert(common->action->kind == TRANSACTION_ACTION_KIND_DRIVE_BACKUP);
1478 backup = common->action->drive_backup;
1480 qmp_drive_backup(backup->device, backup->target,
1481 backup->has_format, backup->format,
1482 backup->sync,
1483 backup->has_mode, backup->mode,
1484 backup->has_speed, backup->speed,
1485 backup->has_on_source_error, backup->on_source_error,
1486 backup->has_on_target_error, backup->on_target_error,
1487 &local_err);
1488 if (local_err) {
1489 error_propagate(errp, local_err);
1490 state->bs = NULL;
1491 state->job = NULL;
1492 return;
1495 state->bs = bdrv_find(backup->device);
1496 state->job = state->bs->job;
1499 static void drive_backup_abort(BlkTransactionState *common)
1501 DriveBackupState *state = DO_UPCAST(DriveBackupState, common, common);
1502 BlockDriverState *bs = state->bs;
1504 /* Only cancel if it's the job we started */
1505 if (bs && bs->job && bs->job == state->job) {
1506 block_job_cancel_sync(bs->job);
1510 static void abort_prepare(BlkTransactionState *common, Error **errp)
1512 error_setg(errp, "Transaction aborted using Abort action");
1515 static void abort_commit(BlkTransactionState *common)
1517 g_assert_not_reached(); /* this action never succeeds */
1520 static const BdrvActionOps actions[] = {
1521 [TRANSACTION_ACTION_KIND_BLOCKDEV_SNAPSHOT_SYNC] = {
1522 .instance_size = sizeof(ExternalSnapshotState),
1523 .prepare = external_snapshot_prepare,
1524 .commit = external_snapshot_commit,
1525 .abort = external_snapshot_abort,
1527 [TRANSACTION_ACTION_KIND_DRIVE_BACKUP] = {
1528 .instance_size = sizeof(DriveBackupState),
1529 .prepare = drive_backup_prepare,
1530 .abort = drive_backup_abort,
1532 [TRANSACTION_ACTION_KIND_ABORT] = {
1533 .instance_size = sizeof(BlkTransactionState),
1534 .prepare = abort_prepare,
1535 .commit = abort_commit,
1537 [TRANSACTION_ACTION_KIND_BLOCKDEV_SNAPSHOT_INTERNAL_SYNC] = {
1538 .instance_size = sizeof(InternalSnapshotState),
1539 .prepare = internal_snapshot_prepare,
1540 .abort = internal_snapshot_abort,
1545 * 'Atomic' group snapshots. The snapshots are taken as a set, and if any fail
1546 * then we do not pivot any of the devices in the group, and abandon the
1547 * snapshots
1549 void qmp_transaction(TransactionActionList *dev_list, Error **errp)
1551 TransactionActionList *dev_entry = dev_list;
1552 BlkTransactionState *state, *next;
1553 Error *local_err = NULL;
1555 QSIMPLEQ_HEAD(snap_bdrv_states, BlkTransactionState) snap_bdrv_states;
1556 QSIMPLEQ_INIT(&snap_bdrv_states);
1558 /* drain all i/o before any snapshots */
1559 bdrv_drain_all();
1561 /* We don't do anything in this loop that commits us to the snapshot */
1562 while (NULL != dev_entry) {
1563 TransactionAction *dev_info = NULL;
1564 const BdrvActionOps *ops;
1566 dev_info = dev_entry->value;
1567 dev_entry = dev_entry->next;
1569 assert(dev_info->kind < ARRAY_SIZE(actions));
1571 ops = &actions[dev_info->kind];
1572 assert(ops->instance_size > 0);
1574 state = g_malloc0(ops->instance_size);
1575 state->ops = ops;
1576 state->action = dev_info;
1577 QSIMPLEQ_INSERT_TAIL(&snap_bdrv_states, state, entry);
1579 state->ops->prepare(state, &local_err);
1580 if (local_err) {
1581 error_propagate(errp, local_err);
1582 goto delete_and_fail;
1586 QSIMPLEQ_FOREACH(state, &snap_bdrv_states, entry) {
1587 if (state->ops->commit) {
1588 state->ops->commit(state);
1592 /* success */
1593 goto exit;
1595 delete_and_fail:
1597 * failure, and it is all-or-none; abandon each new bs, and keep using
1598 * the original bs for all images
1600 QSIMPLEQ_FOREACH(state, &snap_bdrv_states, entry) {
1601 if (state->ops->abort) {
1602 state->ops->abort(state);
1605 exit:
1606 QSIMPLEQ_FOREACH_SAFE(state, &snap_bdrv_states, entry, next) {
1607 if (state->ops->clean) {
1608 state->ops->clean(state);
1610 g_free(state);
1615 static void eject_device(BlockDriverState *bs, int force, Error **errp)
1617 if (bdrv_op_is_blocked(bs, BLOCK_OP_TYPE_EJECT, errp)) {
1618 return;
1620 if (!bdrv_dev_has_removable_media(bs)) {
1621 error_setg(errp, "Device '%s' is not removable",
1622 bdrv_get_device_name(bs));
1623 return;
1626 if (bdrv_dev_is_medium_locked(bs) && !bdrv_dev_is_tray_open(bs)) {
1627 bdrv_dev_eject_request(bs, force);
1628 if (!force) {
1629 error_setg(errp, "Device '%s' is locked",
1630 bdrv_get_device_name(bs));
1631 return;
1635 bdrv_close(bs);
1638 void qmp_eject(const char *device, bool has_force, bool force, Error **errp)
1640 BlockDriverState *bs;
1642 bs = bdrv_find(device);
1643 if (!bs) {
1644 error_set(errp, QERR_DEVICE_NOT_FOUND, device);
1645 return;
1648 eject_device(bs, force, errp);
1651 void qmp_block_passwd(bool has_device, const char *device,
1652 bool has_node_name, const char *node_name,
1653 const char *password, Error **errp)
1655 Error *local_err = NULL;
1656 BlockDriverState *bs;
1657 int err;
1659 bs = bdrv_lookup_bs(has_device ? device : NULL,
1660 has_node_name ? node_name : NULL,
1661 &local_err);
1662 if (local_err) {
1663 error_propagate(errp, local_err);
1664 return;
1667 err = bdrv_set_key(bs, password);
1668 if (err == -EINVAL) {
1669 error_set(errp, QERR_DEVICE_NOT_ENCRYPTED, bdrv_get_device_name(bs));
1670 return;
1671 } else if (err < 0) {
1672 error_set(errp, QERR_INVALID_PASSWORD);
1673 return;
1677 static void qmp_bdrv_open_encrypted(BlockDriverState *bs, const char *filename,
1678 int bdrv_flags, BlockDriver *drv,
1679 const char *password, Error **errp)
1681 Error *local_err = NULL;
1682 int ret;
1684 ret = bdrv_open(&bs, filename, NULL, NULL, bdrv_flags, drv, &local_err);
1685 if (ret < 0) {
1686 error_propagate(errp, local_err);
1687 return;
1690 if (bdrv_key_required(bs)) {
1691 if (password) {
1692 if (bdrv_set_key(bs, password) < 0) {
1693 error_set(errp, QERR_INVALID_PASSWORD);
1695 } else {
1696 error_set(errp, QERR_DEVICE_ENCRYPTED, bdrv_get_device_name(bs),
1697 bdrv_get_encrypted_filename(bs));
1699 } else if (password) {
1700 error_set(errp, QERR_DEVICE_NOT_ENCRYPTED, bdrv_get_device_name(bs));
1704 void qmp_change_blockdev(const char *device, const char *filename,
1705 const char *format, Error **errp)
1707 BlockDriverState *bs;
1708 BlockDriver *drv = NULL;
1709 int bdrv_flags;
1710 Error *err = NULL;
1712 bs = bdrv_find(device);
1713 if (!bs) {
1714 error_set(errp, QERR_DEVICE_NOT_FOUND, device);
1715 return;
1718 if (format) {
1719 drv = bdrv_find_whitelisted_format(format, bs->read_only);
1720 if (!drv) {
1721 error_set(errp, QERR_INVALID_BLOCK_FORMAT, format);
1722 return;
1726 eject_device(bs, 0, &err);
1727 if (err) {
1728 error_propagate(errp, err);
1729 return;
1732 bdrv_flags = bdrv_is_read_only(bs) ? 0 : BDRV_O_RDWR;
1733 bdrv_flags |= bdrv_is_snapshot(bs) ? BDRV_O_SNAPSHOT : 0;
1735 qmp_bdrv_open_encrypted(bs, filename, bdrv_flags, drv, NULL, errp);
1738 /* throttling disk I/O limits */
1739 void qmp_block_set_io_throttle(const char *device, int64_t bps, int64_t bps_rd,
1740 int64_t bps_wr,
1741 int64_t iops,
1742 int64_t iops_rd,
1743 int64_t iops_wr,
1744 bool has_bps_max,
1745 int64_t bps_max,
1746 bool has_bps_rd_max,
1747 int64_t bps_rd_max,
1748 bool has_bps_wr_max,
1749 int64_t bps_wr_max,
1750 bool has_iops_max,
1751 int64_t iops_max,
1752 bool has_iops_rd_max,
1753 int64_t iops_rd_max,
1754 bool has_iops_wr_max,
1755 int64_t iops_wr_max,
1756 bool has_iops_size,
1757 int64_t iops_size, Error **errp)
1759 ThrottleConfig cfg;
1760 BlockDriverState *bs;
1761 AioContext *aio_context;
1763 bs = bdrv_find(device);
1764 if (!bs) {
1765 error_set(errp, QERR_DEVICE_NOT_FOUND, device);
1766 return;
1769 memset(&cfg, 0, sizeof(cfg));
1770 cfg.buckets[THROTTLE_BPS_TOTAL].avg = bps;
1771 cfg.buckets[THROTTLE_BPS_READ].avg = bps_rd;
1772 cfg.buckets[THROTTLE_BPS_WRITE].avg = bps_wr;
1774 cfg.buckets[THROTTLE_OPS_TOTAL].avg = iops;
1775 cfg.buckets[THROTTLE_OPS_READ].avg = iops_rd;
1776 cfg.buckets[THROTTLE_OPS_WRITE].avg = iops_wr;
1778 if (has_bps_max) {
1779 cfg.buckets[THROTTLE_BPS_TOTAL].max = bps_max;
1781 if (has_bps_rd_max) {
1782 cfg.buckets[THROTTLE_BPS_READ].max = bps_rd_max;
1784 if (has_bps_wr_max) {
1785 cfg.buckets[THROTTLE_BPS_WRITE].max = bps_wr_max;
1787 if (has_iops_max) {
1788 cfg.buckets[THROTTLE_OPS_TOTAL].max = iops_max;
1790 if (has_iops_rd_max) {
1791 cfg.buckets[THROTTLE_OPS_READ].max = iops_rd_max;
1793 if (has_iops_wr_max) {
1794 cfg.buckets[THROTTLE_OPS_WRITE].max = iops_wr_max;
1797 if (has_iops_size) {
1798 cfg.op_size = iops_size;
1801 if (!check_throttle_config(&cfg, errp)) {
1802 return;
1805 aio_context = bdrv_get_aio_context(bs);
1806 aio_context_acquire(aio_context);
1808 if (!bs->io_limits_enabled && throttle_enabled(&cfg)) {
1809 bdrv_io_limits_enable(bs);
1810 } else if (bs->io_limits_enabled && !throttle_enabled(&cfg)) {
1811 bdrv_io_limits_disable(bs);
1814 if (bs->io_limits_enabled) {
1815 bdrv_set_io_limits(bs, &cfg);
1818 aio_context_release(aio_context);
1821 int do_drive_del(Monitor *mon, const QDict *qdict, QObject **ret_data)
1823 const char *id = qdict_get_str(qdict, "id");
1824 BlockBackend *blk;
1825 BlockDriverState *bs;
1826 DriveInfo *dinfo;
1827 AioContext *aio_context;
1828 Error *local_err = NULL;
1830 blk = blk_by_name(id);
1831 if (!blk) {
1832 error_report("Device '%s' not found", id);
1833 return -1;
1835 bs = blk_bs(blk);
1837 dinfo = blk_legacy_dinfo(blk);
1838 if (dinfo && !dinfo->enable_auto_del) {
1839 error_report("Deleting device added with blockdev-add"
1840 " is not supported");
1841 return -1;
1844 aio_context = bdrv_get_aio_context(bs);
1845 aio_context_acquire(aio_context);
1847 if (bdrv_op_is_blocked(bs, BLOCK_OP_TYPE_DRIVE_DEL, &local_err)) {
1848 error_report("%s", error_get_pretty(local_err));
1849 error_free(local_err);
1850 aio_context_release(aio_context);
1851 return -1;
1854 /* quiesce block driver; prevent further io */
1855 bdrv_drain_all();
1856 bdrv_flush(bs);
1857 bdrv_close(bs);
1859 /* if we have a device attached to this BlockDriverState
1860 * then we need to make the drive anonymous until the device
1861 * can be removed. If this is a drive with no device backing
1862 * then we can just get rid of the block driver state right here.
1864 if (bdrv_get_attached_dev(bs)) {
1865 blk_hide_on_behalf_of_do_drive_del(blk);
1866 /* Further I/O must not pause the guest */
1867 bdrv_set_on_error(bs, BLOCKDEV_ON_ERROR_REPORT,
1868 BLOCKDEV_ON_ERROR_REPORT);
1869 } else {
1870 drive_del(dinfo);
1873 aio_context_release(aio_context);
1874 return 0;
1877 void qmp_block_resize(bool has_device, const char *device,
1878 bool has_node_name, const char *node_name,
1879 int64_t size, Error **errp)
1881 Error *local_err = NULL;
1882 BlockDriverState *bs;
1883 AioContext *aio_context;
1884 int ret;
1886 bs = bdrv_lookup_bs(has_device ? device : NULL,
1887 has_node_name ? node_name : NULL,
1888 &local_err);
1889 if (local_err) {
1890 error_propagate(errp, local_err);
1891 return;
1894 aio_context = bdrv_get_aio_context(bs);
1895 aio_context_acquire(aio_context);
1897 if (!bdrv_is_first_non_filter(bs)) {
1898 error_set(errp, QERR_FEATURE_DISABLED, "resize");
1899 goto out;
1902 if (size < 0) {
1903 error_set(errp, QERR_INVALID_PARAMETER_VALUE, "size", "a >0 size");
1904 goto out;
1907 if (bdrv_op_is_blocked(bs, BLOCK_OP_TYPE_RESIZE, NULL)) {
1908 error_set(errp, QERR_DEVICE_IN_USE, device);
1909 goto out;
1912 /* complete all in-flight operations before resizing the device */
1913 bdrv_drain_all();
1915 ret = bdrv_truncate(bs, size);
1916 switch (ret) {
1917 case 0:
1918 break;
1919 case -ENOMEDIUM:
1920 error_set(errp, QERR_DEVICE_HAS_NO_MEDIUM, device);
1921 break;
1922 case -ENOTSUP:
1923 error_set(errp, QERR_UNSUPPORTED);
1924 break;
1925 case -EACCES:
1926 error_set(errp, QERR_DEVICE_IS_READ_ONLY, device);
1927 break;
1928 case -EBUSY:
1929 error_set(errp, QERR_DEVICE_IN_USE, device);
1930 break;
1931 default:
1932 error_setg_errno(errp, -ret, "Could not resize");
1933 break;
1936 out:
1937 aio_context_release(aio_context);
1940 static void block_job_cb(void *opaque, int ret)
1942 BlockDriverState *bs = opaque;
1943 const char *msg = NULL;
1945 trace_block_job_cb(bs, bs->job, ret);
1947 assert(bs->job);
1949 if (ret < 0) {
1950 msg = strerror(-ret);
1953 if (block_job_is_cancelled(bs->job)) {
1954 block_job_event_cancelled(bs->job);
1955 } else {
1956 block_job_event_completed(bs->job, msg);
1959 bdrv_put_ref_bh_schedule(bs);
1962 void qmp_block_stream(const char *device,
1963 bool has_base, const char *base,
1964 bool has_backing_file, const char *backing_file,
1965 bool has_speed, int64_t speed,
1966 bool has_on_error, BlockdevOnError on_error,
1967 Error **errp)
1969 BlockDriverState *bs;
1970 BlockDriverState *base_bs = NULL;
1971 Error *local_err = NULL;
1972 const char *base_name = NULL;
1974 if (!has_on_error) {
1975 on_error = BLOCKDEV_ON_ERROR_REPORT;
1978 bs = bdrv_find(device);
1979 if (!bs) {
1980 error_set(errp, QERR_DEVICE_NOT_FOUND, device);
1981 return;
1984 if (bdrv_op_is_blocked(bs, BLOCK_OP_TYPE_STREAM, errp)) {
1985 return;
1988 if (has_base) {
1989 base_bs = bdrv_find_backing_image(bs, base);
1990 if (base_bs == NULL) {
1991 error_set(errp, QERR_BASE_NOT_FOUND, base);
1992 return;
1994 base_name = base;
1997 /* if we are streaming the entire chain, the result will have no backing
1998 * file, and specifying one is therefore an error */
1999 if (base_bs == NULL && has_backing_file) {
2000 error_setg(errp, "backing file specified, but streaming the "
2001 "entire chain");
2002 return;
2005 /* backing_file string overrides base bs filename */
2006 base_name = has_backing_file ? backing_file : base_name;
2008 stream_start(bs, base_bs, base_name, has_speed ? speed : 0,
2009 on_error, block_job_cb, bs, &local_err);
2010 if (local_err) {
2011 error_propagate(errp, local_err);
2012 return;
2015 trace_qmp_block_stream(bs, bs->job);
2018 void qmp_block_commit(const char *device,
2019 bool has_base, const char *base,
2020 bool has_top, const char *top,
2021 bool has_backing_file, const char *backing_file,
2022 bool has_speed, int64_t speed,
2023 Error **errp)
2025 BlockDriverState *bs;
2026 BlockDriverState *base_bs, *top_bs;
2027 Error *local_err = NULL;
2028 /* This will be part of the QMP command, if/when the
2029 * BlockdevOnError change for blkmirror makes it in
2031 BlockdevOnError on_error = BLOCKDEV_ON_ERROR_REPORT;
2033 if (!has_speed) {
2034 speed = 0;
2037 /* drain all i/o before commits */
2038 bdrv_drain_all();
2040 /* Important Note:
2041 * libvirt relies on the DeviceNotFound error class in order to probe for
2042 * live commit feature versions; for this to work, we must make sure to
2043 * perform the device lookup before any generic errors that may occur in a
2044 * scenario in which all optional arguments are omitted. */
2045 bs = bdrv_find(device);
2046 if (!bs) {
2047 error_set(errp, QERR_DEVICE_NOT_FOUND, device);
2048 return;
2051 if (bdrv_op_is_blocked(bs, BLOCK_OP_TYPE_COMMIT, errp)) {
2052 return;
2055 /* default top_bs is the active layer */
2056 top_bs = bs;
2058 if (has_top && top) {
2059 if (strcmp(bs->filename, top) != 0) {
2060 top_bs = bdrv_find_backing_image(bs, top);
2064 if (top_bs == NULL) {
2065 error_setg(errp, "Top image file %s not found", top ? top : "NULL");
2066 return;
2069 if (has_base && base) {
2070 base_bs = bdrv_find_backing_image(top_bs, base);
2071 } else {
2072 base_bs = bdrv_find_base(top_bs);
2075 if (base_bs == NULL) {
2076 error_set(errp, QERR_BASE_NOT_FOUND, base ? base : "NULL");
2077 return;
2080 /* Do not allow attempts to commit an image into itself */
2081 if (top_bs == base_bs) {
2082 error_setg(errp, "cannot commit an image into itself");
2083 return;
2086 if (top_bs == bs) {
2087 if (has_backing_file) {
2088 error_setg(errp, "'backing-file' specified,"
2089 " but 'top' is the active layer");
2090 return;
2092 commit_active_start(bs, base_bs, speed, on_error, block_job_cb,
2093 bs, &local_err);
2094 } else {
2095 commit_start(bs, base_bs, top_bs, speed, on_error, block_job_cb, bs,
2096 has_backing_file ? backing_file : NULL, &local_err);
2098 if (local_err != NULL) {
2099 error_propagate(errp, local_err);
2100 return;
2104 void qmp_drive_backup(const char *device, const char *target,
2105 bool has_format, const char *format,
2106 enum MirrorSyncMode sync,
2107 bool has_mode, enum NewImageMode mode,
2108 bool has_speed, int64_t speed,
2109 bool has_on_source_error, BlockdevOnError on_source_error,
2110 bool has_on_target_error, BlockdevOnError on_target_error,
2111 Error **errp)
2113 BlockDriverState *bs;
2114 BlockDriverState *target_bs;
2115 BlockDriverState *source = NULL;
2116 BlockDriver *drv = NULL;
2117 Error *local_err = NULL;
2118 int flags;
2119 int64_t size;
2120 int ret;
2122 if (!has_speed) {
2123 speed = 0;
2125 if (!has_on_source_error) {
2126 on_source_error = BLOCKDEV_ON_ERROR_REPORT;
2128 if (!has_on_target_error) {
2129 on_target_error = BLOCKDEV_ON_ERROR_REPORT;
2131 if (!has_mode) {
2132 mode = NEW_IMAGE_MODE_ABSOLUTE_PATHS;
2135 bs = bdrv_find(device);
2136 if (!bs) {
2137 error_set(errp, QERR_DEVICE_NOT_FOUND, device);
2138 return;
2141 if (!bdrv_is_inserted(bs)) {
2142 error_set(errp, QERR_DEVICE_HAS_NO_MEDIUM, device);
2143 return;
2146 if (!has_format) {
2147 format = mode == NEW_IMAGE_MODE_EXISTING ? NULL : bs->drv->format_name;
2149 if (format) {
2150 drv = bdrv_find_format(format);
2151 if (!drv) {
2152 error_set(errp, QERR_INVALID_BLOCK_FORMAT, format);
2153 return;
2157 if (bdrv_op_is_blocked(bs, BLOCK_OP_TYPE_BACKUP_SOURCE, errp)) {
2158 return;
2161 flags = bs->open_flags | BDRV_O_RDWR;
2163 /* See if we have a backing HD we can use to create our new image
2164 * on top of. */
2165 if (sync == MIRROR_SYNC_MODE_TOP) {
2166 source = bs->backing_hd;
2167 if (!source) {
2168 sync = MIRROR_SYNC_MODE_FULL;
2171 if (sync == MIRROR_SYNC_MODE_NONE) {
2172 source = bs;
2175 size = bdrv_getlength(bs);
2176 if (size < 0) {
2177 error_setg_errno(errp, -size, "bdrv_getlength failed");
2178 return;
2181 if (mode != NEW_IMAGE_MODE_EXISTING) {
2182 assert(format && drv);
2183 if (source) {
2184 bdrv_img_create(target, format, source->filename,
2185 source->drv->format_name, NULL,
2186 size, flags, &local_err, false);
2187 } else {
2188 bdrv_img_create(target, format, NULL, NULL, NULL,
2189 size, flags, &local_err, false);
2193 if (local_err) {
2194 error_propagate(errp, local_err);
2195 return;
2198 target_bs = NULL;
2199 ret = bdrv_open(&target_bs, target, NULL, NULL, flags, drv, &local_err);
2200 if (ret < 0) {
2201 error_propagate(errp, local_err);
2202 return;
2205 backup_start(bs, target_bs, speed, sync, on_source_error, on_target_error,
2206 block_job_cb, bs, &local_err);
2207 if (local_err != NULL) {
2208 bdrv_unref(target_bs);
2209 error_propagate(errp, local_err);
2210 return;
2214 BlockDeviceInfoList *qmp_query_named_block_nodes(Error **errp)
2216 return bdrv_named_nodes_list();
2219 #define DEFAULT_MIRROR_BUF_SIZE (10 << 20)
2221 void qmp_drive_mirror(const char *device, const char *target,
2222 bool has_format, const char *format,
2223 bool has_node_name, const char *node_name,
2224 bool has_replaces, const char *replaces,
2225 enum MirrorSyncMode sync,
2226 bool has_mode, enum NewImageMode mode,
2227 bool has_speed, int64_t speed,
2228 bool has_granularity, uint32_t granularity,
2229 bool has_buf_size, int64_t buf_size,
2230 bool has_on_source_error, BlockdevOnError on_source_error,
2231 bool has_on_target_error, BlockdevOnError on_target_error,
2232 Error **errp)
2234 BlockDriverState *bs;
2235 BlockDriverState *source, *target_bs;
2236 BlockDriver *drv = NULL;
2237 Error *local_err = NULL;
2238 QDict *options = NULL;
2239 int flags;
2240 int64_t size;
2241 int ret;
2243 if (!has_speed) {
2244 speed = 0;
2246 if (!has_on_source_error) {
2247 on_source_error = BLOCKDEV_ON_ERROR_REPORT;
2249 if (!has_on_target_error) {
2250 on_target_error = BLOCKDEV_ON_ERROR_REPORT;
2252 if (!has_mode) {
2253 mode = NEW_IMAGE_MODE_ABSOLUTE_PATHS;
2255 if (!has_granularity) {
2256 granularity = 0;
2258 if (!has_buf_size) {
2259 buf_size = DEFAULT_MIRROR_BUF_SIZE;
2262 if (granularity != 0 && (granularity < 512 || granularity > 1048576 * 64)) {
2263 error_set(errp, QERR_INVALID_PARAMETER_VALUE, "granularity",
2264 "a value in range [512B, 64MB]");
2265 return;
2267 if (granularity & (granularity - 1)) {
2268 error_set(errp, QERR_INVALID_PARAMETER_VALUE, "granularity", "power of 2");
2269 return;
2272 bs = bdrv_find(device);
2273 if (!bs) {
2274 error_set(errp, QERR_DEVICE_NOT_FOUND, device);
2275 return;
2278 if (!bdrv_is_inserted(bs)) {
2279 error_set(errp, QERR_DEVICE_HAS_NO_MEDIUM, device);
2280 return;
2283 if (!has_format) {
2284 format = mode == NEW_IMAGE_MODE_EXISTING ? NULL : bs->drv->format_name;
2286 if (format) {
2287 drv = bdrv_find_format(format);
2288 if (!drv) {
2289 error_set(errp, QERR_INVALID_BLOCK_FORMAT, format);
2290 return;
2294 if (bdrv_op_is_blocked(bs, BLOCK_OP_TYPE_MIRROR, errp)) {
2295 return;
2298 flags = bs->open_flags | BDRV_O_RDWR;
2299 source = bs->backing_hd;
2300 if (!source && sync == MIRROR_SYNC_MODE_TOP) {
2301 sync = MIRROR_SYNC_MODE_FULL;
2303 if (sync == MIRROR_SYNC_MODE_NONE) {
2304 source = bs;
2307 size = bdrv_getlength(bs);
2308 if (size < 0) {
2309 error_setg_errno(errp, -size, "bdrv_getlength failed");
2310 return;
2313 if (has_replaces) {
2314 BlockDriverState *to_replace_bs;
2316 if (!has_node_name) {
2317 error_setg(errp, "a node-name must be provided when replacing a"
2318 " named node of the graph");
2319 return;
2322 to_replace_bs = check_to_replace_node(replaces, &local_err);
2324 if (!to_replace_bs) {
2325 error_propagate(errp, local_err);
2326 return;
2329 if (size != bdrv_getlength(to_replace_bs)) {
2330 error_setg(errp, "cannot replace image with a mirror image of "
2331 "different size");
2332 return;
2336 if ((sync == MIRROR_SYNC_MODE_FULL || !source)
2337 && mode != NEW_IMAGE_MODE_EXISTING)
2339 /* create new image w/o backing file */
2340 assert(format && drv);
2341 bdrv_img_create(target, format,
2342 NULL, NULL, NULL, size, flags, &local_err, false);
2343 } else {
2344 switch (mode) {
2345 case NEW_IMAGE_MODE_EXISTING:
2346 break;
2347 case NEW_IMAGE_MODE_ABSOLUTE_PATHS:
2348 /* create new image with backing file */
2349 bdrv_img_create(target, format,
2350 source->filename,
2351 source->drv->format_name,
2352 NULL, size, flags, &local_err, false);
2353 break;
2354 default:
2355 abort();
2359 if (local_err) {
2360 error_propagate(errp, local_err);
2361 return;
2364 if (has_node_name) {
2365 options = qdict_new();
2366 qdict_put(options, "node-name", qstring_from_str(node_name));
2369 /* Mirroring takes care of copy-on-write using the source's backing
2370 * file.
2372 target_bs = NULL;
2373 ret = bdrv_open(&target_bs, target, NULL, options,
2374 flags | BDRV_O_NO_BACKING, drv, &local_err);
2375 if (ret < 0) {
2376 error_propagate(errp, local_err);
2377 return;
2380 /* pass the node name to replace to mirror start since it's loose coupling
2381 * and will allow to check whether the node still exist at mirror completion
2383 mirror_start(bs, target_bs,
2384 has_replaces ? replaces : NULL,
2385 speed, granularity, buf_size, sync,
2386 on_source_error, on_target_error,
2387 block_job_cb, bs, &local_err);
2388 if (local_err != NULL) {
2389 bdrv_unref(target_bs);
2390 error_propagate(errp, local_err);
2391 return;
2395 static BlockJob *find_block_job(const char *device)
2397 BlockDriverState *bs;
2399 bs = bdrv_find(device);
2400 if (!bs || !bs->job) {
2401 return NULL;
2403 return bs->job;
2406 void qmp_block_job_set_speed(const char *device, int64_t speed, Error **errp)
2408 BlockJob *job = find_block_job(device);
2410 if (!job) {
2411 error_set(errp, QERR_BLOCK_JOB_NOT_ACTIVE, device);
2412 return;
2415 block_job_set_speed(job, speed, errp);
2418 void qmp_block_job_cancel(const char *device,
2419 bool has_force, bool force, Error **errp)
2421 BlockJob *job = find_block_job(device);
2423 if (!has_force) {
2424 force = false;
2427 if (!job) {
2428 error_set(errp, QERR_BLOCK_JOB_NOT_ACTIVE, device);
2429 return;
2431 if (job->paused && !force) {
2432 error_setg(errp, "The block job for device '%s' is currently paused",
2433 device);
2434 return;
2437 trace_qmp_block_job_cancel(job);
2438 block_job_cancel(job);
2441 void qmp_block_job_pause(const char *device, Error **errp)
2443 BlockJob *job = find_block_job(device);
2445 if (!job) {
2446 error_set(errp, QERR_BLOCK_JOB_NOT_ACTIVE, device);
2447 return;
2450 trace_qmp_block_job_pause(job);
2451 block_job_pause(job);
2454 void qmp_block_job_resume(const char *device, Error **errp)
2456 BlockJob *job = find_block_job(device);
2458 if (!job) {
2459 error_set(errp, QERR_BLOCK_JOB_NOT_ACTIVE, device);
2460 return;
2463 trace_qmp_block_job_resume(job);
2464 block_job_resume(job);
2467 void qmp_block_job_complete(const char *device, Error **errp)
2469 BlockJob *job = find_block_job(device);
2471 if (!job) {
2472 error_set(errp, QERR_BLOCK_JOB_NOT_ACTIVE, device);
2473 return;
2476 trace_qmp_block_job_complete(job);
2477 block_job_complete(job, errp);
2480 void qmp_change_backing_file(const char *device,
2481 const char *image_node_name,
2482 const char *backing_file,
2483 Error **errp)
2485 BlockDriverState *bs = NULL;
2486 BlockDriverState *image_bs = NULL;
2487 Error *local_err = NULL;
2488 bool ro;
2489 int open_flags;
2490 int ret;
2492 /* find the top layer BDS of the chain */
2493 bs = bdrv_find(device);
2494 if (!bs) {
2495 error_set(errp, QERR_DEVICE_NOT_FOUND, device);
2496 return;
2499 image_bs = bdrv_lookup_bs(NULL, image_node_name, &local_err);
2500 if (local_err) {
2501 error_propagate(errp, local_err);
2502 return;
2505 if (!image_bs) {
2506 error_setg(errp, "image file not found");
2507 return;
2510 if (bdrv_find_base(image_bs) == image_bs) {
2511 error_setg(errp, "not allowing backing file change on an image "
2512 "without a backing file");
2513 return;
2516 /* even though we are not necessarily operating on bs, we need it to
2517 * determine if block ops are currently prohibited on the chain */
2518 if (bdrv_op_is_blocked(bs, BLOCK_OP_TYPE_CHANGE, errp)) {
2519 return;
2522 /* final sanity check */
2523 if (!bdrv_chain_contains(bs, image_bs)) {
2524 error_setg(errp, "'%s' and image file are not in the same chain",
2525 device);
2526 return;
2529 /* if not r/w, reopen to make r/w */
2530 open_flags = image_bs->open_flags;
2531 ro = bdrv_is_read_only(image_bs);
2533 if (ro) {
2534 bdrv_reopen(image_bs, open_flags | BDRV_O_RDWR, &local_err);
2535 if (local_err) {
2536 error_propagate(errp, local_err);
2537 return;
2541 ret = bdrv_change_backing_file(image_bs, backing_file,
2542 image_bs->drv ? image_bs->drv->format_name : "");
2544 if (ret < 0) {
2545 error_setg_errno(errp, -ret, "Could not change backing file to '%s'",
2546 backing_file);
2547 /* don't exit here, so we can try to restore open flags if
2548 * appropriate */
2551 if (ro) {
2552 bdrv_reopen(image_bs, open_flags, &local_err);
2553 if (local_err) {
2554 error_propagate(errp, local_err); /* will preserve prior errp */
2559 void qmp_blockdev_add(BlockdevOptions *options, Error **errp)
2561 QmpOutputVisitor *ov = qmp_output_visitor_new();
2562 BlockBackend *blk;
2563 QObject *obj;
2564 QDict *qdict;
2565 Error *local_err = NULL;
2567 /* Require an ID in the top level */
2568 if (!options->has_id) {
2569 error_setg(errp, "Block device needs an ID");
2570 goto fail;
2573 /* TODO Sort it out in raw-posix and drive_new(): Reject aio=native with
2574 * cache.direct=false instead of silently switching to aio=threads, except
2575 * when called from drive_new().
2577 * For now, simply forbidding the combination for all drivers will do. */
2578 if (options->has_aio && options->aio == BLOCKDEV_AIO_OPTIONS_NATIVE) {
2579 bool direct = options->has_cache &&
2580 options->cache->has_direct &&
2581 options->cache->direct;
2582 if (!direct) {
2583 error_setg(errp, "aio=native requires cache.direct=true");
2584 goto fail;
2588 visit_type_BlockdevOptions(qmp_output_get_visitor(ov),
2589 &options, NULL, &local_err);
2590 if (local_err) {
2591 error_propagate(errp, local_err);
2592 goto fail;
2595 obj = qmp_output_get_qobject(ov);
2596 qdict = qobject_to_qdict(obj);
2598 qdict_flatten(qdict);
2600 blk = blockdev_init(NULL, qdict, &local_err);
2601 if (local_err) {
2602 error_propagate(errp, local_err);
2603 goto fail;
2606 if (bdrv_key_required(blk_bs(blk))) {
2607 blk_unref(blk);
2608 error_setg(errp, "blockdev-add doesn't support encrypted devices");
2609 goto fail;
2612 fail:
2613 qmp_output_visitor_cleanup(ov);
2616 static void do_qmp_query_block_jobs_one(void *opaque, BlockDriverState *bs)
2618 BlockJobInfoList **prev = opaque;
2619 BlockJob *job = bs->job;
2621 if (job) {
2622 BlockJobInfoList *elem = g_new0(BlockJobInfoList, 1);
2623 elem->value = block_job_query(bs->job);
2624 (*prev)->next = elem;
2625 *prev = elem;
2629 BlockJobInfoList *qmp_query_block_jobs(Error **errp)
2631 /* Dummy is a fake list element for holding the head pointer */
2632 BlockJobInfoList dummy = {};
2633 BlockJobInfoList *prev = &dummy;
2634 bdrv_iterate(do_qmp_query_block_jobs_one, &prev);
2635 return dummy.next;
2638 QemuOptsList qemu_common_drive_opts = {
2639 .name = "drive",
2640 .head = QTAILQ_HEAD_INITIALIZER(qemu_common_drive_opts.head),
2641 .desc = {
2643 .name = "snapshot",
2644 .type = QEMU_OPT_BOOL,
2645 .help = "enable/disable snapshot mode",
2647 .name = "discard",
2648 .type = QEMU_OPT_STRING,
2649 .help = "discard operation (ignore/off, unmap/on)",
2651 .name = "cache.writeback",
2652 .type = QEMU_OPT_BOOL,
2653 .help = "enables writeback mode for any caches",
2655 .name = "cache.direct",
2656 .type = QEMU_OPT_BOOL,
2657 .help = "enables use of O_DIRECT (bypass the host page cache)",
2659 .name = "cache.no-flush",
2660 .type = QEMU_OPT_BOOL,
2661 .help = "ignore any flush requests for the device",
2663 .name = "aio",
2664 .type = QEMU_OPT_STRING,
2665 .help = "host AIO implementation (threads, native)",
2667 .name = "format",
2668 .type = QEMU_OPT_STRING,
2669 .help = "disk format (raw, qcow2, ...)",
2671 .name = "rerror",
2672 .type = QEMU_OPT_STRING,
2673 .help = "read error action",
2675 .name = "werror",
2676 .type = QEMU_OPT_STRING,
2677 .help = "write error action",
2679 .name = "read-only",
2680 .type = QEMU_OPT_BOOL,
2681 .help = "open drive file as read-only",
2683 .name = "throttling.iops-total",
2684 .type = QEMU_OPT_NUMBER,
2685 .help = "limit total I/O operations per second",
2687 .name = "throttling.iops-read",
2688 .type = QEMU_OPT_NUMBER,
2689 .help = "limit read operations per second",
2691 .name = "throttling.iops-write",
2692 .type = QEMU_OPT_NUMBER,
2693 .help = "limit write operations per second",
2695 .name = "throttling.bps-total",
2696 .type = QEMU_OPT_NUMBER,
2697 .help = "limit total bytes per second",
2699 .name = "throttling.bps-read",
2700 .type = QEMU_OPT_NUMBER,
2701 .help = "limit read bytes per second",
2703 .name = "throttling.bps-write",
2704 .type = QEMU_OPT_NUMBER,
2705 .help = "limit write bytes per second",
2707 .name = "throttling.iops-total-max",
2708 .type = QEMU_OPT_NUMBER,
2709 .help = "I/O operations burst",
2711 .name = "throttling.iops-read-max",
2712 .type = QEMU_OPT_NUMBER,
2713 .help = "I/O operations read burst",
2715 .name = "throttling.iops-write-max",
2716 .type = QEMU_OPT_NUMBER,
2717 .help = "I/O operations write burst",
2719 .name = "throttling.bps-total-max",
2720 .type = QEMU_OPT_NUMBER,
2721 .help = "total bytes burst",
2723 .name = "throttling.bps-read-max",
2724 .type = QEMU_OPT_NUMBER,
2725 .help = "total bytes read burst",
2727 .name = "throttling.bps-write-max",
2728 .type = QEMU_OPT_NUMBER,
2729 .help = "total bytes write burst",
2731 .name = "throttling.iops-size",
2732 .type = QEMU_OPT_NUMBER,
2733 .help = "when limiting by iops max size of an I/O in bytes",
2735 .name = "copy-on-read",
2736 .type = QEMU_OPT_BOOL,
2737 .help = "copy read data from backing file into image file",
2739 .name = "detect-zeroes",
2740 .type = QEMU_OPT_STRING,
2741 .help = "try to optimize zero writes (off, on, unmap)",
2743 { /* end of list */ }
2747 QemuOptsList qemu_drive_opts = {
2748 .name = "drive",
2749 .head = QTAILQ_HEAD_INITIALIZER(qemu_drive_opts.head),
2750 .desc = {
2752 * no elements => accept any params
2753 * validation will happen later
2755 { /* end of list */ }