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
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
33 #include "sysemu/blockdev.h"
34 #include "hw/block/block.h"
35 #include "block/blockjob.h"
36 #include "monitor/monitor.h"
37 #include "qemu/option.h"
38 #include "qemu/config-file.h"
39 #include "qapi/qmp/types.h"
40 #include "qapi-visit.h"
41 #include "qapi/qmp-output-visitor.h"
42 #include "qapi/util.h"
43 #include "sysemu/sysemu.h"
44 #include "block/block_int.h"
45 #include "qmp-commands.h"
47 #include "sysemu/arch_init.h"
49 static QTAILQ_HEAD(drivelist, DriveInfo) drives = QTAILQ_HEAD_INITIALIZER(drives);
51 static const char *const if_name[IF_COUNT] = {
55 [IF_FLOPPY] = "floppy",
56 [IF_PFLASH] = "pflash",
59 [IF_VIRTIO] = "virtio",
63 static const int if_max_devs[IF_COUNT] = {
65 * Do not change these numbers! They govern how drive option
66 * index maps to unit and bus. That mapping is ABI.
68 * All controllers used to imlement if=T drives need to support
69 * if_max_devs[T] units, for any T with if_max_devs[T] != 0.
70 * Otherwise, some index values map to "impossible" bus, unit
73 * For instance, if you change [IF_SCSI] to 255, -drive
74 * if=scsi,index=12 no longer means bus=1,unit=5, but
75 * bus=0,unit=12. With an lsi53c895a controller (7 units max),
76 * the drive can't be set up. Regression.
83 * We automatically delete the drive when a device using it gets
84 * unplugged. Questionable feature, but we can't just drop it.
85 * Device models call blockdev_mark_auto_del() to schedule the
86 * automatic deletion, and generic qdev code calls blockdev_auto_del()
87 * when deletion is actually safe.
89 void blockdev_mark_auto_del(BlockDriverState *bs)
91 DriveInfo *dinfo = drive_get_by_blockdev(bs);
93 if (dinfo && !dinfo->enable_auto_del) {
98 block_job_cancel(bs->job);
105 void blockdev_auto_del(BlockDriverState *bs)
107 DriveInfo *dinfo = drive_get_by_blockdev(bs);
109 if (dinfo && dinfo->auto_del) {
114 static int drive_index_to_bus_id(BlockInterfaceType type, int index)
116 int max_devs = if_max_devs[type];
117 return max_devs ? index / max_devs : 0;
120 static int drive_index_to_unit_id(BlockInterfaceType type, int index)
122 int max_devs = if_max_devs[type];
123 return max_devs ? index % max_devs : index;
126 QemuOpts *drive_def(const char *optstr)
128 return qemu_opts_parse(qemu_find_opts("drive"), optstr, 0);
131 QemuOpts *drive_add(BlockInterfaceType type, int index, const char *file,
137 opts = drive_def(optstr);
141 if (type != IF_DEFAULT) {
142 qemu_opt_set(opts, "if", if_name[type]);
145 snprintf(buf, sizeof(buf), "%d", index);
146 qemu_opt_set(opts, "index", buf);
149 qemu_opt_set(opts, "file", file);
153 DriveInfo *drive_get(BlockInterfaceType type, int bus, int unit)
157 /* seek interface, bus and unit */
159 QTAILQ_FOREACH(dinfo, &drives, next) {
160 if (dinfo->type == type &&
169 DriveInfo *drive_get_by_index(BlockInterfaceType type, int index)
171 return drive_get(type,
172 drive_index_to_bus_id(type, index),
173 drive_index_to_unit_id(type, index));
176 int drive_get_max_bus(BlockInterfaceType type)
182 QTAILQ_FOREACH(dinfo, &drives, next) {
183 if(dinfo->type == type &&
184 dinfo->bus > max_bus)
185 max_bus = dinfo->bus;
190 /* Get a block device. This should only be used for single-drive devices
191 (e.g. SD/Floppy/MTD). Multi-disk devices (scsi/ide) should use the
193 DriveInfo *drive_get_next(BlockInterfaceType type)
195 static int next_block_unit[IF_COUNT];
197 return drive_get(type, 0, next_block_unit[type]++);
200 DriveInfo *drive_get_by_blockdev(BlockDriverState *bs)
204 QTAILQ_FOREACH(dinfo, &drives, next) {
205 if (dinfo->bdrv == bs) {
212 static void bdrv_format_print(void *opaque, const char *name)
214 error_printf(" %s", name);
217 void drive_del(DriveInfo *dinfo)
220 qemu_opts_del(dinfo->opts);
223 bdrv_unref(dinfo->bdrv);
225 QTAILQ_REMOVE(&drives, dinfo, next);
226 g_free(dinfo->serial);
232 BlockDriverState *bs;
235 static void bdrv_put_ref_bh(void *opaque)
237 BDRVPutRefBH *s = opaque;
240 qemu_bh_delete(s->bh);
245 * Release a BDS reference in a BH
247 * It is not safe to use bdrv_unref() from a callback function when the callers
248 * still need the BlockDriverState. In such cases we schedule a BH to release
251 static void bdrv_put_ref_bh_schedule(BlockDriverState *bs)
255 s = g_new(BDRVPutRefBH, 1);
256 s->bh = qemu_bh_new(bdrv_put_ref_bh, s);
258 qemu_bh_schedule(s->bh);
261 static int parse_block_error_action(const char *buf, bool is_read, Error **errp)
263 if (!strcmp(buf, "ignore")) {
264 return BLOCKDEV_ON_ERROR_IGNORE;
265 } else if (!is_read && !strcmp(buf, "enospc")) {
266 return BLOCKDEV_ON_ERROR_ENOSPC;
267 } else if (!strcmp(buf, "stop")) {
268 return BLOCKDEV_ON_ERROR_STOP;
269 } else if (!strcmp(buf, "report")) {
270 return BLOCKDEV_ON_ERROR_REPORT;
272 error_setg(errp, "'%s' invalid %s error action",
273 buf, is_read ? "read" : "write");
278 static bool check_throttle_config(ThrottleConfig *cfg, Error **errp)
280 if (throttle_conflicting(cfg)) {
281 error_setg(errp, "bps/iops/max total values and read/write values"
282 " cannot be used at the same time");
286 if (!throttle_is_valid(cfg)) {
287 error_setg(errp, "bps/iops/maxs values must be 0 or greater");
294 typedef enum { MEDIA_DISK, MEDIA_CDROM } DriveMediaType;
296 /* Takes the ownership of bs_opts */
297 static DriveInfo *blockdev_init(const char *file, QDict *bs_opts,
303 int on_read_error, on_write_error;
312 bool has_driver_specific_opts;
313 BlockdevDetectZeroesOptions detect_zeroes;
314 BlockDriver *drv = NULL;
316 /* Check common options by copying from bs_opts to opts, all other options
317 * stay in bs_opts for processing by bdrv_open(). */
318 id = qdict_get_try_str(bs_opts, "id");
319 opts = qemu_opts_create(&qemu_common_drive_opts, id, 1, &error);
321 error_propagate(errp, error);
325 qemu_opts_absorb_qdict(opts, bs_opts, &error);
327 error_propagate(errp, error);
332 qdict_del(bs_opts, "id");
335 has_driver_specific_opts = !!qdict_size(bs_opts);
337 /* extract parameters */
338 snapshot = qemu_opt_get_bool(opts, "snapshot", 0);
339 ro = qemu_opt_get_bool(opts, "read-only", 0);
340 copy_on_read = qemu_opt_get_bool(opts, "copy-on-read", false);
342 if ((buf = qemu_opt_get(opts, "discard")) != NULL) {
343 if (bdrv_parse_discard_flags(buf, &bdrv_flags) != 0) {
344 error_setg(errp, "invalid discard option");
349 if (qemu_opt_get_bool(opts, "cache.writeback", true)) {
350 bdrv_flags |= BDRV_O_CACHE_WB;
352 if (qemu_opt_get_bool(opts, "cache.direct", false)) {
353 bdrv_flags |= BDRV_O_NOCACHE;
355 if (qemu_opt_get_bool(opts, "cache.no-flush", false)) {
356 bdrv_flags |= BDRV_O_NO_FLUSH;
359 #ifdef CONFIG_LINUX_AIO
360 if ((buf = qemu_opt_get(opts, "aio")) != NULL) {
361 if (!strcmp(buf, "native")) {
362 bdrv_flags |= BDRV_O_NATIVE_AIO;
363 } else if (!strcmp(buf, "threads")) {
364 /* this is the default */
366 error_setg(errp, "invalid aio option");
372 if ((buf = qemu_opt_get(opts, "format")) != NULL) {
373 if (is_help_option(buf)) {
374 error_printf("Supported formats:");
375 bdrv_iterate_format(bdrv_format_print, NULL);
380 drv = bdrv_find_format(buf);
382 error_setg(errp, "'%s' invalid format", buf);
387 /* disk I/O throttling */
388 memset(&cfg, 0, sizeof(cfg));
389 cfg.buckets[THROTTLE_BPS_TOTAL].avg =
390 qemu_opt_get_number(opts, "throttling.bps-total", 0);
391 cfg.buckets[THROTTLE_BPS_READ].avg =
392 qemu_opt_get_number(opts, "throttling.bps-read", 0);
393 cfg.buckets[THROTTLE_BPS_WRITE].avg =
394 qemu_opt_get_number(opts, "throttling.bps-write", 0);
395 cfg.buckets[THROTTLE_OPS_TOTAL].avg =
396 qemu_opt_get_number(opts, "throttling.iops-total", 0);
397 cfg.buckets[THROTTLE_OPS_READ].avg =
398 qemu_opt_get_number(opts, "throttling.iops-read", 0);
399 cfg.buckets[THROTTLE_OPS_WRITE].avg =
400 qemu_opt_get_number(opts, "throttling.iops-write", 0);
402 cfg.buckets[THROTTLE_BPS_TOTAL].max =
403 qemu_opt_get_number(opts, "throttling.bps-total-max", 0);
404 cfg.buckets[THROTTLE_BPS_READ].max =
405 qemu_opt_get_number(opts, "throttling.bps-read-max", 0);
406 cfg.buckets[THROTTLE_BPS_WRITE].max =
407 qemu_opt_get_number(opts, "throttling.bps-write-max", 0);
408 cfg.buckets[THROTTLE_OPS_TOTAL].max =
409 qemu_opt_get_number(opts, "throttling.iops-total-max", 0);
410 cfg.buckets[THROTTLE_OPS_READ].max =
411 qemu_opt_get_number(opts, "throttling.iops-read-max", 0);
412 cfg.buckets[THROTTLE_OPS_WRITE].max =
413 qemu_opt_get_number(opts, "throttling.iops-write-max", 0);
415 cfg.op_size = qemu_opt_get_number(opts, "throttling.iops-size", 0);
417 if (!check_throttle_config(&cfg, &error)) {
418 error_propagate(errp, error);
422 on_write_error = BLOCKDEV_ON_ERROR_ENOSPC;
423 if ((buf = qemu_opt_get(opts, "werror")) != NULL) {
424 on_write_error = parse_block_error_action(buf, 0, &error);
426 error_propagate(errp, error);
431 on_read_error = BLOCKDEV_ON_ERROR_REPORT;
432 if ((buf = qemu_opt_get(opts, "rerror")) != NULL) {
433 on_read_error = parse_block_error_action(buf, 1, &error);
435 error_propagate(errp, error);
441 qapi_enum_parse(BlockdevDetectZeroesOptions_lookup,
442 qemu_opt_get(opts, "detect-zeroes"),
443 BLOCKDEV_DETECT_ZEROES_OPTIONS_MAX,
444 BLOCKDEV_DETECT_ZEROES_OPTIONS_OFF,
447 error_propagate(errp, error);
451 if (detect_zeroes == BLOCKDEV_DETECT_ZEROES_OPTIONS_UNMAP &&
452 !(bdrv_flags & BDRV_O_UNMAP)) {
453 error_setg(errp, "setting detect-zeroes to unmap is not allowed "
454 "without setting discard operation to unmap");
459 dinfo = g_malloc0(sizeof(*dinfo));
460 dinfo->id = g_strdup(qemu_opts_id(opts));
461 dinfo->bdrv = bdrv_new(dinfo->id, &error);
463 error_propagate(errp, error);
466 dinfo->bdrv->open_flags = snapshot ? BDRV_O_SNAPSHOT : 0;
467 dinfo->bdrv->read_only = ro;
468 dinfo->bdrv->detect_zeroes = detect_zeroes;
469 QTAILQ_INSERT_TAIL(&drives, dinfo, next);
471 bdrv_set_on_error(dinfo->bdrv, on_read_error, on_write_error);
473 /* disk I/O throttling */
474 if (throttle_enabled(&cfg)) {
475 bdrv_io_limits_enable(dinfo->bdrv);
476 bdrv_set_io_limits(dinfo->bdrv, &cfg);
479 if (!file || !*file) {
480 if (has_driver_specific_opts) {
489 /* always use cache=unsafe with snapshot */
490 bdrv_flags &= ~BDRV_O_CACHE_MASK;
491 bdrv_flags |= (BDRV_O_SNAPSHOT|BDRV_O_CACHE_WB|BDRV_O_NO_FLUSH);
495 bdrv_flags |= BDRV_O_COPY_ON_READ;
498 if (runstate_check(RUN_STATE_INMIGRATE)) {
499 bdrv_flags |= BDRV_O_INCOMING;
502 bdrv_flags |= ro ? 0 : BDRV_O_RDWR;
505 ret = bdrv_open(&dinfo->bdrv, file, NULL, bs_opts, bdrv_flags, drv, &error);
508 error_setg(errp, "could not open disk image %s: %s",
509 file ?: dinfo->id, error_get_pretty(error));
514 if (bdrv_key_required(dinfo->bdrv))
523 bdrv_unref(dinfo->bdrv);
524 QTAILQ_REMOVE(&drives, dinfo, next);
535 static void qemu_opt_rename(QemuOpts *opts, const char *from, const char *to)
539 value = qemu_opt_get(opts, from);
541 qemu_opt_set(opts, to, value);
542 qemu_opt_unset(opts, from);
546 QemuOptsList qemu_legacy_drive_opts = {
548 .head = QTAILQ_HEAD_INITIALIZER(qemu_legacy_drive_opts.head),
552 .type = QEMU_OPT_NUMBER,
553 .help = "bus number",
556 .type = QEMU_OPT_NUMBER,
557 .help = "unit number (i.e. lun for scsi)",
560 .type = QEMU_OPT_NUMBER,
561 .help = "index number",
564 .type = QEMU_OPT_STRING,
565 .help = "media type (disk, cdrom)",
568 .type = QEMU_OPT_STRING,
569 .help = "interface (ide, scsi, sd, mtd, floppy, pflash, virtio)",
572 .type = QEMU_OPT_NUMBER,
573 .help = "number of cylinders (ide disk geometry)",
576 .type = QEMU_OPT_NUMBER,
577 .help = "number of heads (ide disk geometry)",
580 .type = QEMU_OPT_NUMBER,
581 .help = "number of sectors (ide disk geometry)",
584 .type = QEMU_OPT_STRING,
585 .help = "chs translation (auto, lba, none)",
588 .type = QEMU_OPT_BOOL,
589 .help = "(deprecated, ignored)",
592 .type = QEMU_OPT_STRING,
593 .help = "pci address (virtio only)",
596 .type = QEMU_OPT_STRING,
597 .help = "disk serial number",
600 .type = QEMU_OPT_STRING,
604 /* Options that are passed on, but have special semantics with -drive */
607 .type = QEMU_OPT_BOOL,
608 .help = "open drive file as read-only",
611 .type = QEMU_OPT_STRING,
612 .help = "read error action",
615 .type = QEMU_OPT_STRING,
616 .help = "write error action",
618 .name = "copy-on-read",
619 .type = QEMU_OPT_BOOL,
620 .help = "copy read data from backing file into image file",
623 { /* end of list */ }
627 DriveInfo *drive_new(QemuOpts *all_opts, BlockInterfaceType block_default_type)
630 DriveInfo *dinfo = NULL;
632 QemuOpts *legacy_opts;
633 DriveMediaType media = MEDIA_DISK;
634 BlockInterfaceType type;
635 int cyls, heads, secs, translation;
636 int max_devs, bus_id, unit_id, index;
638 const char *werror, *rerror;
639 bool read_only = false;
642 const char *filename;
643 Error *local_err = NULL;
645 /* Change legacy command line options into QMP ones */
646 qemu_opt_rename(all_opts, "iops", "throttling.iops-total");
647 qemu_opt_rename(all_opts, "iops_rd", "throttling.iops-read");
648 qemu_opt_rename(all_opts, "iops_wr", "throttling.iops-write");
650 qemu_opt_rename(all_opts, "bps", "throttling.bps-total");
651 qemu_opt_rename(all_opts, "bps_rd", "throttling.bps-read");
652 qemu_opt_rename(all_opts, "bps_wr", "throttling.bps-write");
654 qemu_opt_rename(all_opts, "iops_max", "throttling.iops-total-max");
655 qemu_opt_rename(all_opts, "iops_rd_max", "throttling.iops-read-max");
656 qemu_opt_rename(all_opts, "iops_wr_max", "throttling.iops-write-max");
658 qemu_opt_rename(all_opts, "bps_max", "throttling.bps-total-max");
659 qemu_opt_rename(all_opts, "bps_rd_max", "throttling.bps-read-max");
660 qemu_opt_rename(all_opts, "bps_wr_max", "throttling.bps-write-max");
662 qemu_opt_rename(all_opts,
663 "iops_size", "throttling.iops-size");
665 qemu_opt_rename(all_opts, "readonly", "read-only");
667 value = qemu_opt_get(all_opts, "cache");
671 if (bdrv_parse_cache_flags(value, &flags) != 0) {
672 error_report("invalid cache option");
676 /* Specific options take precedence */
677 if (!qemu_opt_get(all_opts, "cache.writeback")) {
678 qemu_opt_set_bool(all_opts, "cache.writeback",
679 !!(flags & BDRV_O_CACHE_WB));
681 if (!qemu_opt_get(all_opts, "cache.direct")) {
682 qemu_opt_set_bool(all_opts, "cache.direct",
683 !!(flags & BDRV_O_NOCACHE));
685 if (!qemu_opt_get(all_opts, "cache.no-flush")) {
686 qemu_opt_set_bool(all_opts, "cache.no-flush",
687 !!(flags & BDRV_O_NO_FLUSH));
689 qemu_opt_unset(all_opts, "cache");
692 /* Get a QDict for processing the options */
693 bs_opts = qdict_new();
694 qemu_opts_to_qdict(all_opts, bs_opts);
696 legacy_opts = qemu_opts_create(&qemu_legacy_drive_opts, NULL, 0,
698 qemu_opts_absorb_qdict(legacy_opts, bs_opts, &local_err);
700 error_report("%s", error_get_pretty(local_err));
701 error_free(local_err);
705 /* Deprecated option boot=[on|off] */
706 if (qemu_opt_get(legacy_opts, "boot") != NULL) {
707 fprintf(stderr, "qemu-kvm: boot=on|off is deprecated and will be "
708 "ignored. Future versions will reject this parameter. Please "
709 "update your scripts.\n");
713 value = qemu_opt_get(legacy_opts, "media");
715 if (!strcmp(value, "disk")) {
717 } else if (!strcmp(value, "cdrom")) {
721 error_report("'%s' invalid media", value);
726 /* copy-on-read is disabled with a warning for read-only devices */
727 read_only |= qemu_opt_get_bool(legacy_opts, "read-only", false);
728 copy_on_read = qemu_opt_get_bool(legacy_opts, "copy-on-read", false);
730 if (read_only && copy_on_read) {
731 error_report("warning: disabling copy-on-read on read-only drive");
732 copy_on_read = false;
735 qdict_put(bs_opts, "read-only",
736 qstring_from_str(read_only ? "on" : "off"));
737 qdict_put(bs_opts, "copy-on-read",
738 qstring_from_str(copy_on_read ? "on" :"off"));
740 /* Controller type */
741 value = qemu_opt_get(legacy_opts, "if");
744 type < IF_COUNT && strcmp(value, if_name[type]);
747 if (type == IF_COUNT) {
748 error_report("unsupported bus type '%s'", value);
752 type = block_default_type;
756 cyls = qemu_opt_get_number(legacy_opts, "cyls", 0);
757 heads = qemu_opt_get_number(legacy_opts, "heads", 0);
758 secs = qemu_opt_get_number(legacy_opts, "secs", 0);
760 if (cyls || heads || secs) {
762 error_report("invalid physical cyls number");
766 error_report("invalid physical heads number");
770 error_report("invalid physical secs number");
775 translation = BIOS_ATA_TRANSLATION_AUTO;
776 value = qemu_opt_get(legacy_opts, "trans");
779 error_report("'%s' trans must be used with cyls, heads and secs",
783 if (!strcmp(value, "none")) {
784 translation = BIOS_ATA_TRANSLATION_NONE;
785 } else if (!strcmp(value, "lba")) {
786 translation = BIOS_ATA_TRANSLATION_LBA;
787 } else if (!strcmp(value, "large")) {
788 translation = BIOS_ATA_TRANSLATION_LARGE;
789 } else if (!strcmp(value, "rechs")) {
790 translation = BIOS_ATA_TRANSLATION_RECHS;
791 } else if (!strcmp(value, "auto")) {
792 translation = BIOS_ATA_TRANSLATION_AUTO;
794 error_report("'%s' invalid translation type", value);
799 if (media == MEDIA_CDROM) {
800 if (cyls || secs || heads) {
801 error_report("CHS can't be set with media=cdrom");
806 /* Device address specified by bus/unit or index.
807 * If none was specified, try to find the first free one. */
808 bus_id = qemu_opt_get_number(legacy_opts, "bus", 0);
809 unit_id = qemu_opt_get_number(legacy_opts, "unit", -1);
810 index = qemu_opt_get_number(legacy_opts, "index", -1);
812 max_devs = if_max_devs[type];
815 if (bus_id != 0 || unit_id != -1) {
816 error_report("index cannot be used with bus and unit");
819 bus_id = drive_index_to_bus_id(type, index);
820 unit_id = drive_index_to_unit_id(type, index);
825 while (drive_get(type, bus_id, unit_id) != NULL) {
827 if (max_devs && unit_id >= max_devs) {
834 if (max_devs && unit_id >= max_devs) {
835 error_report("unit %d too big (max is %d)", unit_id, max_devs - 1);
839 if (drive_get(type, bus_id, unit_id) != NULL) {
840 error_report("drive with bus=%d, unit=%d (index=%d) exists",
841 bus_id, unit_id, index);
846 serial = qemu_opt_get(legacy_opts, "serial");
848 /* no id supplied -> create one */
849 if (qemu_opts_id(all_opts) == NULL) {
851 const char *mediastr = "";
852 if (type == IF_IDE || type == IF_SCSI) {
853 mediastr = (media == MEDIA_CDROM) ? "-cd" : "-hd";
856 new_id = g_strdup_printf("%s%i%s%i", if_name[type], bus_id,
859 new_id = g_strdup_printf("%s%s%i", if_name[type],
862 qdict_put(bs_opts, "id", qstring_from_str(new_id));
866 /* Add virtio block device */
867 devaddr = qemu_opt_get(legacy_opts, "addr");
868 if (devaddr && type != IF_VIRTIO) {
869 error_report("addr is not supported by this bus type");
873 if (type == IF_VIRTIO) {
875 devopts = qemu_opts_create(qemu_find_opts("device"), NULL, 0,
877 if (arch_type == QEMU_ARCH_S390X) {
878 qemu_opt_set(devopts, "driver", "virtio-blk-s390");
880 qemu_opt_set(devopts, "driver", "virtio-blk-pci");
882 qemu_opt_set(devopts, "drive", qdict_get_str(bs_opts, "id"));
884 qemu_opt_set(devopts, "addr", devaddr);
888 filename = qemu_opt_get(legacy_opts, "file");
890 /* Check werror/rerror compatibility with if=... */
891 werror = qemu_opt_get(legacy_opts, "werror");
892 if (werror != NULL) {
893 if (type != IF_IDE && type != IF_SCSI && type != IF_VIRTIO &&
895 error_report("werror is not supported by this bus type");
898 qdict_put(bs_opts, "werror", qstring_from_str(werror));
901 rerror = qemu_opt_get(legacy_opts, "rerror");
902 if (rerror != NULL) {
903 if (type != IF_IDE && type != IF_VIRTIO && type != IF_SCSI &&
905 error_report("rerror is not supported by this bus type");
908 qdict_put(bs_opts, "rerror", qstring_from_str(rerror));
911 /* Actual block device init: Functionality shared with blockdev-add */
912 dinfo = blockdev_init(filename, bs_opts, &local_err);
916 error_report("%s", error_get_pretty(local_err));
917 error_free(local_err);
924 /* Set legacy DriveInfo fields */
925 dinfo->enable_auto_del = true;
926 dinfo->opts = all_opts;
929 dinfo->heads = heads;
931 dinfo->trans = translation;
935 dinfo->unit = unit_id;
936 dinfo->devaddr = devaddr;
938 dinfo->serial = g_strdup(serial);
945 dinfo->media_cd = media == MEDIA_CDROM;
952 qemu_opts_del(legacy_opts);
957 void do_commit(Monitor *mon, const QDict *qdict)
959 const char *device = qdict_get_str(qdict, "device");
960 BlockDriverState *bs;
963 if (!strcmp(device, "all")) {
964 ret = bdrv_commit_all();
966 bs = bdrv_find(device);
968 monitor_printf(mon, "Device '%s' not found\n", device);
971 ret = bdrv_commit(bs);
974 monitor_printf(mon, "'commit' error for '%s': %s\n", device,
979 static void blockdev_do_action(int kind, void *data, Error **errp)
981 TransactionAction action;
982 TransactionActionList list;
986 list.value = &action;
988 qmp_transaction(&list, errp);
991 void qmp_blockdev_snapshot_sync(bool has_device, const char *device,
992 bool has_node_name, const char *node_name,
993 const char *snapshot_file,
994 bool has_snapshot_node_name,
995 const char *snapshot_node_name,
996 bool has_format, const char *format,
997 bool has_mode, NewImageMode mode, Error **errp)
999 BlockdevSnapshot snapshot = {
1000 .has_device = has_device,
1001 .device = (char *) device,
1002 .has_node_name = has_node_name,
1003 .node_name = (char *) node_name,
1004 .snapshot_file = (char *) snapshot_file,
1005 .has_snapshot_node_name = has_snapshot_node_name,
1006 .snapshot_node_name = (char *) snapshot_node_name,
1007 .has_format = has_format,
1008 .format = (char *) format,
1009 .has_mode = has_mode,
1012 blockdev_do_action(TRANSACTION_ACTION_KIND_BLOCKDEV_SNAPSHOT_SYNC,
1016 void qmp_blockdev_snapshot_internal_sync(const char *device,
1020 BlockdevSnapshotInternal snapshot = {
1021 .device = (char *) device,
1022 .name = (char *) name
1025 blockdev_do_action(TRANSACTION_ACTION_KIND_BLOCKDEV_SNAPSHOT_INTERNAL_SYNC,
1029 SnapshotInfo *qmp_blockdev_snapshot_delete_internal_sync(const char *device,
1036 BlockDriverState *bs = bdrv_find(device);
1037 QEMUSnapshotInfo sn;
1038 Error *local_err = NULL;
1039 SnapshotInfo *info = NULL;
1043 error_set(errp, QERR_DEVICE_NOT_FOUND, device);
1056 error_setg(errp, "Name or id must be provided");
1060 ret = bdrv_snapshot_find_by_id_and_name(bs, id, name, &sn, &local_err);
1062 error_propagate(errp, local_err);
1067 "Snapshot with id '%s' and name '%s' does not exist on "
1069 STR_OR_NULL(id), STR_OR_NULL(name), device);
1073 bdrv_snapshot_delete(bs, id, name, &local_err);
1075 error_propagate(errp, local_err);
1079 info = g_new0(SnapshotInfo, 1);
1080 info->id = g_strdup(sn.id_str);
1081 info->name = g_strdup(sn.name);
1082 info->date_nsec = sn.date_nsec;
1083 info->date_sec = sn.date_sec;
1084 info->vm_state_size = sn.vm_state_size;
1085 info->vm_clock_nsec = sn.vm_clock_nsec % 1000000000;
1086 info->vm_clock_sec = sn.vm_clock_nsec / 1000000000;
1091 /* New and old BlockDriverState structs for group snapshots */
1093 typedef struct BlkTransactionState BlkTransactionState;
1095 /* Only prepare() may fail. In a single transaction, only one of commit() or
1096 abort() will be called, clean() will always be called if it present. */
1097 typedef struct BdrvActionOps {
1098 /* Size of state struct, in bytes. */
1099 size_t instance_size;
1100 /* Prepare the work, must NOT be NULL. */
1101 void (*prepare)(BlkTransactionState *common, Error **errp);
1102 /* Commit the changes, can be NULL. */
1103 void (*commit)(BlkTransactionState *common);
1104 /* Abort the changes on fail, can be NULL. */
1105 void (*abort)(BlkTransactionState *common);
1106 /* Clean up resource in the end, can be NULL. */
1107 void (*clean)(BlkTransactionState *common);
1111 * This structure must be arranged as first member in child type, assuming
1112 * that compiler will also arrange it to the same address with parent instance.
1113 * Later it will be used in free().
1115 struct BlkTransactionState {
1116 TransactionAction *action;
1117 const BdrvActionOps *ops;
1118 QSIMPLEQ_ENTRY(BlkTransactionState) entry;
1121 /* internal snapshot private data */
1122 typedef struct InternalSnapshotState {
1123 BlkTransactionState common;
1124 BlockDriverState *bs;
1125 QEMUSnapshotInfo sn;
1126 } InternalSnapshotState;
1128 static void internal_snapshot_prepare(BlkTransactionState *common,
1131 Error *local_err = NULL;
1134 BlockDriverState *bs;
1135 QEMUSnapshotInfo old_sn, *sn;
1138 BlockdevSnapshotInternal *internal;
1139 InternalSnapshotState *state;
1142 g_assert(common->action->kind ==
1143 TRANSACTION_ACTION_KIND_BLOCKDEV_SNAPSHOT_INTERNAL_SYNC);
1144 internal = common->action->blockdev_snapshot_internal_sync;
1145 state = DO_UPCAST(InternalSnapshotState, common, common);
1147 /* 1. parse input */
1148 device = internal->device;
1149 name = internal->name;
1151 /* 2. check for validation */
1152 bs = bdrv_find(device);
1154 error_set(errp, QERR_DEVICE_NOT_FOUND, device);
1158 if (!bdrv_is_inserted(bs)) {
1159 error_set(errp, QERR_DEVICE_HAS_NO_MEDIUM, device);
1163 if (bdrv_is_read_only(bs)) {
1164 error_set(errp, QERR_DEVICE_IS_READ_ONLY, device);
1168 if (!bdrv_can_snapshot(bs)) {
1169 error_set(errp, QERR_BLOCK_FORMAT_FEATURE_NOT_SUPPORTED,
1170 bs->drv->format_name, device, "internal snapshot");
1174 if (!strlen(name)) {
1175 error_setg(errp, "Name is empty");
1179 /* check whether a snapshot with name exist */
1180 ret = bdrv_snapshot_find_by_id_and_name(bs, NULL, name, &old_sn,
1183 error_propagate(errp, local_err);
1187 "Snapshot with name '%s' already exists on device '%s'",
1192 /* 3. take the snapshot */
1194 pstrcpy(sn->name, sizeof(sn->name), name);
1195 qemu_gettimeofday(&tv);
1196 sn->date_sec = tv.tv_sec;
1197 sn->date_nsec = tv.tv_usec * 1000;
1198 sn->vm_clock_nsec = qemu_clock_get_ns(QEMU_CLOCK_VIRTUAL);
1200 ret1 = bdrv_snapshot_create(bs, sn);
1202 error_setg_errno(errp, -ret1,
1203 "Failed to create snapshot '%s' on device '%s'",
1208 /* 4. succeed, mark a snapshot is created */
1212 static void internal_snapshot_abort(BlkTransactionState *common)
1214 InternalSnapshotState *state =
1215 DO_UPCAST(InternalSnapshotState, common, common);
1216 BlockDriverState *bs = state->bs;
1217 QEMUSnapshotInfo *sn = &state->sn;
1218 Error *local_error = NULL;
1224 if (bdrv_snapshot_delete(bs, sn->id_str, sn->name, &local_error) < 0) {
1225 error_report("Failed to delete snapshot with id '%s' and name '%s' on "
1226 "device '%s' in abort: %s",
1229 bdrv_get_device_name(bs),
1230 error_get_pretty(local_error));
1231 error_free(local_error);
1235 /* external snapshot private data */
1236 typedef struct ExternalSnapshotState {
1237 BlkTransactionState common;
1238 BlockDriverState *old_bs;
1239 BlockDriverState *new_bs;
1240 } ExternalSnapshotState;
1242 static void external_snapshot_prepare(BlkTransactionState *common,
1247 QDict *options = NULL;
1248 Error *local_err = NULL;
1249 bool has_device = false;
1251 bool has_node_name = false;
1252 const char *node_name;
1253 bool has_snapshot_node_name = false;
1254 const char *snapshot_node_name;
1255 const char *new_image_file;
1256 const char *format = "qcow2";
1257 enum NewImageMode mode = NEW_IMAGE_MODE_ABSOLUTE_PATHS;
1258 ExternalSnapshotState *state =
1259 DO_UPCAST(ExternalSnapshotState, common, common);
1260 TransactionAction *action = common->action;
1262 /* get parameters */
1263 g_assert(action->kind == TRANSACTION_ACTION_KIND_BLOCKDEV_SNAPSHOT_SYNC);
1265 has_device = action->blockdev_snapshot_sync->has_device;
1266 device = action->blockdev_snapshot_sync->device;
1267 has_node_name = action->blockdev_snapshot_sync->has_node_name;
1268 node_name = action->blockdev_snapshot_sync->node_name;
1269 has_snapshot_node_name =
1270 action->blockdev_snapshot_sync->has_snapshot_node_name;
1271 snapshot_node_name = action->blockdev_snapshot_sync->snapshot_node_name;
1273 new_image_file = action->blockdev_snapshot_sync->snapshot_file;
1274 if (action->blockdev_snapshot_sync->has_format) {
1275 format = action->blockdev_snapshot_sync->format;
1277 if (action->blockdev_snapshot_sync->has_mode) {
1278 mode = action->blockdev_snapshot_sync->mode;
1281 /* start processing */
1282 drv = bdrv_find_format(format);
1284 error_set(errp, QERR_INVALID_BLOCK_FORMAT, format);
1288 state->old_bs = bdrv_lookup_bs(has_device ? device : NULL,
1289 has_node_name ? node_name : NULL,
1292 error_propagate(errp, local_err);
1296 if (has_node_name && !has_snapshot_node_name) {
1297 error_setg(errp, "New snapshot node name missing");
1301 if (has_snapshot_node_name && bdrv_find_node(snapshot_node_name)) {
1302 error_setg(errp, "New snapshot node name already existing");
1306 if (!bdrv_is_inserted(state->old_bs)) {
1307 error_set(errp, QERR_DEVICE_HAS_NO_MEDIUM, device);
1311 if (bdrv_op_is_blocked(state->old_bs,
1312 BLOCK_OP_TYPE_EXTERNAL_SNAPSHOT, errp)) {
1316 if (!bdrv_is_read_only(state->old_bs)) {
1317 if (bdrv_flush(state->old_bs)) {
1318 error_set(errp, QERR_IO_ERROR);
1323 if (!bdrv_is_first_non_filter(state->old_bs)) {
1324 error_set(errp, QERR_FEATURE_DISABLED, "snapshot");
1328 flags = state->old_bs->open_flags;
1330 /* create new image w/backing file */
1331 if (mode != NEW_IMAGE_MODE_EXISTING) {
1332 bdrv_img_create(new_image_file, format,
1333 state->old_bs->filename,
1334 state->old_bs->drv->format_name,
1335 NULL, -1, flags, &local_err, false);
1337 error_propagate(errp, local_err);
1342 if (has_snapshot_node_name) {
1343 options = qdict_new();
1344 qdict_put(options, "node-name",
1345 qstring_from_str(snapshot_node_name));
1348 /* TODO Inherit bs->options or only take explicit options with an
1349 * extended QMP command? */
1350 assert(state->new_bs == NULL);
1351 ret = bdrv_open(&state->new_bs, new_image_file, NULL, options,
1352 flags | BDRV_O_NO_BACKING, drv, &local_err);
1353 /* We will manually add the backing_hd field to the bs later */
1355 error_propagate(errp, local_err);
1359 static void external_snapshot_commit(BlkTransactionState *common)
1361 ExternalSnapshotState *state =
1362 DO_UPCAST(ExternalSnapshotState, common, common);
1364 /* This removes our old bs and adds the new bs */
1365 bdrv_append(state->new_bs, state->old_bs);
1366 /* We don't need (or want) to use the transactional
1367 * bdrv_reopen_multiple() across all the entries at once, because we
1368 * don't want to abort all of them if one of them fails the reopen */
1369 bdrv_reopen(state->new_bs, state->new_bs->open_flags & ~BDRV_O_RDWR,
1373 static void external_snapshot_abort(BlkTransactionState *common)
1375 ExternalSnapshotState *state =
1376 DO_UPCAST(ExternalSnapshotState, common, common);
1377 if (state->new_bs) {
1378 bdrv_unref(state->new_bs);
1382 typedef struct DriveBackupState {
1383 BlkTransactionState common;
1384 BlockDriverState *bs;
1388 static void drive_backup_prepare(BlkTransactionState *common, Error **errp)
1390 DriveBackupState *state = DO_UPCAST(DriveBackupState, common, common);
1391 DriveBackup *backup;
1392 Error *local_err = NULL;
1394 assert(common->action->kind == TRANSACTION_ACTION_KIND_DRIVE_BACKUP);
1395 backup = common->action->drive_backup;
1397 qmp_drive_backup(backup->device, backup->target,
1398 backup->has_format, backup->format,
1400 backup->has_mode, backup->mode,
1401 backup->has_speed, backup->speed,
1402 backup->has_on_source_error, backup->on_source_error,
1403 backup->has_on_target_error, backup->on_target_error,
1406 error_propagate(errp, local_err);
1412 state->bs = bdrv_find(backup->device);
1413 state->job = state->bs->job;
1416 static void drive_backup_abort(BlkTransactionState *common)
1418 DriveBackupState *state = DO_UPCAST(DriveBackupState, common, common);
1419 BlockDriverState *bs = state->bs;
1421 /* Only cancel if it's the job we started */
1422 if (bs && bs->job && bs->job == state->job) {
1423 block_job_cancel_sync(bs->job);
1427 static void abort_prepare(BlkTransactionState *common, Error **errp)
1429 error_setg(errp, "Transaction aborted using Abort action");
1432 static void abort_commit(BlkTransactionState *common)
1434 g_assert_not_reached(); /* this action never succeeds */
1437 static const BdrvActionOps actions[] = {
1438 [TRANSACTION_ACTION_KIND_BLOCKDEV_SNAPSHOT_SYNC] = {
1439 .instance_size = sizeof(ExternalSnapshotState),
1440 .prepare = external_snapshot_prepare,
1441 .commit = external_snapshot_commit,
1442 .abort = external_snapshot_abort,
1444 [TRANSACTION_ACTION_KIND_DRIVE_BACKUP] = {
1445 .instance_size = sizeof(DriveBackupState),
1446 .prepare = drive_backup_prepare,
1447 .abort = drive_backup_abort,
1449 [TRANSACTION_ACTION_KIND_ABORT] = {
1450 .instance_size = sizeof(BlkTransactionState),
1451 .prepare = abort_prepare,
1452 .commit = abort_commit,
1454 [TRANSACTION_ACTION_KIND_BLOCKDEV_SNAPSHOT_INTERNAL_SYNC] = {
1455 .instance_size = sizeof(InternalSnapshotState),
1456 .prepare = internal_snapshot_prepare,
1457 .abort = internal_snapshot_abort,
1462 * 'Atomic' group snapshots. The snapshots are taken as a set, and if any fail
1463 * then we do not pivot any of the devices in the group, and abandon the
1466 void qmp_transaction(TransactionActionList *dev_list, Error **errp)
1468 TransactionActionList *dev_entry = dev_list;
1469 BlkTransactionState *state, *next;
1470 Error *local_err = NULL;
1472 QSIMPLEQ_HEAD(snap_bdrv_states, BlkTransactionState) snap_bdrv_states;
1473 QSIMPLEQ_INIT(&snap_bdrv_states);
1475 /* drain all i/o before any snapshots */
1478 /* We don't do anything in this loop that commits us to the snapshot */
1479 while (NULL != dev_entry) {
1480 TransactionAction *dev_info = NULL;
1481 const BdrvActionOps *ops;
1483 dev_info = dev_entry->value;
1484 dev_entry = dev_entry->next;
1486 assert(dev_info->kind < ARRAY_SIZE(actions));
1488 ops = &actions[dev_info->kind];
1489 assert(ops->instance_size > 0);
1491 state = g_malloc0(ops->instance_size);
1493 state->action = dev_info;
1494 QSIMPLEQ_INSERT_TAIL(&snap_bdrv_states, state, entry);
1496 state->ops->prepare(state, &local_err);
1498 error_propagate(errp, local_err);
1499 goto delete_and_fail;
1503 QSIMPLEQ_FOREACH(state, &snap_bdrv_states, entry) {
1504 if (state->ops->commit) {
1505 state->ops->commit(state);
1514 * failure, and it is all-or-none; abandon each new bs, and keep using
1515 * the original bs for all images
1517 QSIMPLEQ_FOREACH(state, &snap_bdrv_states, entry) {
1518 if (state->ops->abort) {
1519 state->ops->abort(state);
1523 QSIMPLEQ_FOREACH_SAFE(state, &snap_bdrv_states, entry, next) {
1524 if (state->ops->clean) {
1525 state->ops->clean(state);
1532 static void eject_device(BlockDriverState *bs, int force, Error **errp)
1534 if (bdrv_op_is_blocked(bs, BLOCK_OP_TYPE_EJECT, errp)) {
1537 if (!bdrv_dev_has_removable_media(bs)) {
1538 error_setg(errp, "Device '%s' is not removable",
1539 bdrv_get_device_name(bs));
1543 if (bdrv_dev_is_medium_locked(bs) && !bdrv_dev_is_tray_open(bs)) {
1544 bdrv_dev_eject_request(bs, force);
1546 error_setg(errp, "Device '%s' is locked",
1547 bdrv_get_device_name(bs));
1555 void qmp_eject(const char *device, bool has_force, bool force, Error **errp)
1557 BlockDriverState *bs;
1559 bs = bdrv_find(device);
1561 error_set(errp, QERR_DEVICE_NOT_FOUND, device);
1565 eject_device(bs, force, errp);
1568 void qmp_block_passwd(bool has_device, const char *device,
1569 bool has_node_name, const char *node_name,
1570 const char *password, Error **errp)
1572 Error *local_err = NULL;
1573 BlockDriverState *bs;
1576 bs = bdrv_lookup_bs(has_device ? device : NULL,
1577 has_node_name ? node_name : NULL,
1580 error_propagate(errp, local_err);
1584 err = bdrv_set_key(bs, password);
1585 if (err == -EINVAL) {
1586 error_set(errp, QERR_DEVICE_NOT_ENCRYPTED, bdrv_get_device_name(bs));
1588 } else if (err < 0) {
1589 error_set(errp, QERR_INVALID_PASSWORD);
1594 static void qmp_bdrv_open_encrypted(BlockDriverState *bs, const char *filename,
1595 int bdrv_flags, BlockDriver *drv,
1596 const char *password, Error **errp)
1598 Error *local_err = NULL;
1601 ret = bdrv_open(&bs, filename, NULL, NULL, bdrv_flags, drv, &local_err);
1603 error_propagate(errp, local_err);
1607 if (bdrv_key_required(bs)) {
1609 if (bdrv_set_key(bs, password) < 0) {
1610 error_set(errp, QERR_INVALID_PASSWORD);
1613 error_set(errp, QERR_DEVICE_ENCRYPTED, bdrv_get_device_name(bs),
1614 bdrv_get_encrypted_filename(bs));
1616 } else if (password) {
1617 error_set(errp, QERR_DEVICE_NOT_ENCRYPTED, bdrv_get_device_name(bs));
1621 void qmp_change_blockdev(const char *device, const char *filename,
1622 const char *format, Error **errp)
1624 BlockDriverState *bs;
1625 BlockDriver *drv = NULL;
1629 bs = bdrv_find(device);
1631 error_set(errp, QERR_DEVICE_NOT_FOUND, device);
1636 drv = bdrv_find_whitelisted_format(format, bs->read_only);
1638 error_set(errp, QERR_INVALID_BLOCK_FORMAT, format);
1643 eject_device(bs, 0, &err);
1645 error_propagate(errp, err);
1649 bdrv_flags = bdrv_is_read_only(bs) ? 0 : BDRV_O_RDWR;
1650 bdrv_flags |= bdrv_is_snapshot(bs) ? BDRV_O_SNAPSHOT : 0;
1652 qmp_bdrv_open_encrypted(bs, filename, bdrv_flags, drv, NULL, errp);
1655 /* throttling disk I/O limits */
1656 void qmp_block_set_io_throttle(const char *device, int64_t bps, int64_t bps_rd,
1663 bool has_bps_rd_max,
1665 bool has_bps_wr_max,
1669 bool has_iops_rd_max,
1670 int64_t iops_rd_max,
1671 bool has_iops_wr_max,
1672 int64_t iops_wr_max,
1674 int64_t iops_size, Error **errp)
1677 BlockDriverState *bs;
1678 AioContext *aio_context;
1680 bs = bdrv_find(device);
1682 error_set(errp, QERR_DEVICE_NOT_FOUND, device);
1686 memset(&cfg, 0, sizeof(cfg));
1687 cfg.buckets[THROTTLE_BPS_TOTAL].avg = bps;
1688 cfg.buckets[THROTTLE_BPS_READ].avg = bps_rd;
1689 cfg.buckets[THROTTLE_BPS_WRITE].avg = bps_wr;
1691 cfg.buckets[THROTTLE_OPS_TOTAL].avg = iops;
1692 cfg.buckets[THROTTLE_OPS_READ].avg = iops_rd;
1693 cfg.buckets[THROTTLE_OPS_WRITE].avg = iops_wr;
1696 cfg.buckets[THROTTLE_BPS_TOTAL].max = bps_max;
1698 if (has_bps_rd_max) {
1699 cfg.buckets[THROTTLE_BPS_READ].max = bps_rd_max;
1701 if (has_bps_wr_max) {
1702 cfg.buckets[THROTTLE_BPS_WRITE].max = bps_wr_max;
1705 cfg.buckets[THROTTLE_OPS_TOTAL].max = iops_max;
1707 if (has_iops_rd_max) {
1708 cfg.buckets[THROTTLE_OPS_READ].max = iops_rd_max;
1710 if (has_iops_wr_max) {
1711 cfg.buckets[THROTTLE_OPS_WRITE].max = iops_wr_max;
1714 if (has_iops_size) {
1715 cfg.op_size = iops_size;
1718 if (!check_throttle_config(&cfg, errp)) {
1722 aio_context = bdrv_get_aio_context(bs);
1723 aio_context_acquire(aio_context);
1725 if (!bs->io_limits_enabled && throttle_enabled(&cfg)) {
1726 bdrv_io_limits_enable(bs);
1727 } else if (bs->io_limits_enabled && !throttle_enabled(&cfg)) {
1728 bdrv_io_limits_disable(bs);
1731 if (bs->io_limits_enabled) {
1732 bdrv_set_io_limits(bs, &cfg);
1735 aio_context_release(aio_context);
1738 int do_drive_del(Monitor *mon, const QDict *qdict, QObject **ret_data)
1740 const char *id = qdict_get_str(qdict, "id");
1741 BlockDriverState *bs;
1742 AioContext *aio_context;
1743 Error *local_err = NULL;
1747 error_report("Device '%s' not found", id);
1751 aio_context = bdrv_get_aio_context(bs);
1752 aio_context_acquire(aio_context);
1754 if (bdrv_op_is_blocked(bs, BLOCK_OP_TYPE_DRIVE_DEL, &local_err)) {
1755 error_report("%s", error_get_pretty(local_err));
1756 error_free(local_err);
1757 aio_context_release(aio_context);
1761 /* quiesce block driver; prevent further io */
1766 /* if we have a device attached to this BlockDriverState
1767 * then we need to make the drive anonymous until the device
1768 * can be removed. If this is a drive with no device backing
1769 * then we can just get rid of the block driver state right here.
1771 if (bdrv_get_attached_dev(bs)) {
1774 /* Further I/O must not pause the guest */
1775 bdrv_set_on_error(bs, BLOCKDEV_ON_ERROR_REPORT,
1776 BLOCKDEV_ON_ERROR_REPORT);
1778 drive_del(drive_get_by_blockdev(bs));
1781 aio_context_release(aio_context);
1785 void qmp_block_resize(bool has_device, const char *device,
1786 bool has_node_name, const char *node_name,
1787 int64_t size, Error **errp)
1789 Error *local_err = NULL;
1790 BlockDriverState *bs;
1791 AioContext *aio_context;
1794 bs = bdrv_lookup_bs(has_device ? device : NULL,
1795 has_node_name ? node_name : NULL,
1798 error_propagate(errp, local_err);
1802 aio_context = bdrv_get_aio_context(bs);
1803 aio_context_acquire(aio_context);
1805 if (!bdrv_is_first_non_filter(bs)) {
1806 error_set(errp, QERR_FEATURE_DISABLED, "resize");
1811 error_set(errp, QERR_INVALID_PARAMETER_VALUE, "size", "a >0 size");
1815 if (bdrv_op_is_blocked(bs, BLOCK_OP_TYPE_RESIZE, NULL)) {
1816 error_set(errp, QERR_DEVICE_IN_USE, device);
1820 /* complete all in-flight operations before resizing the device */
1823 ret = bdrv_truncate(bs, size);
1828 error_set(errp, QERR_DEVICE_HAS_NO_MEDIUM, device);
1831 error_set(errp, QERR_UNSUPPORTED);
1834 error_set(errp, QERR_DEVICE_IS_READ_ONLY, device);
1837 error_set(errp, QERR_DEVICE_IN_USE, device);
1840 error_setg_errno(errp, -ret, "Could not resize");
1845 aio_context_release(aio_context);
1848 static void block_job_cb(void *opaque, int ret)
1850 BlockDriverState *bs = opaque;
1851 const char *msg = NULL;
1853 trace_block_job_cb(bs, bs->job, ret);
1858 msg = strerror(-ret);
1861 if (block_job_is_cancelled(bs->job)) {
1862 block_job_event_cancelled(bs->job);
1864 block_job_event_completed(bs->job, msg);
1867 bdrv_put_ref_bh_schedule(bs);
1870 void qmp_block_stream(const char *device,
1871 bool has_base, const char *base,
1872 bool has_backing_file, const char *backing_file,
1873 bool has_speed, int64_t speed,
1874 bool has_on_error, BlockdevOnError on_error,
1877 BlockDriverState *bs;
1878 BlockDriverState *base_bs = NULL;
1879 Error *local_err = NULL;
1880 const char *base_name = NULL;
1882 if (!has_on_error) {
1883 on_error = BLOCKDEV_ON_ERROR_REPORT;
1886 bs = bdrv_find(device);
1888 error_set(errp, QERR_DEVICE_NOT_FOUND, device);
1892 if (bdrv_op_is_blocked(bs, BLOCK_OP_TYPE_STREAM, errp)) {
1897 base_bs = bdrv_find_backing_image(bs, base);
1898 if (base_bs == NULL) {
1899 error_set(errp, QERR_BASE_NOT_FOUND, base);
1905 /* if we are streaming the entire chain, the result will have no backing
1906 * file, and specifying one is therefore an error */
1907 if (base_bs == NULL && has_backing_file) {
1908 error_setg(errp, "backing file specified, but streaming the "
1913 /* backing_file string overrides base bs filename */
1914 base_name = has_backing_file ? backing_file : base_name;
1916 stream_start(bs, base_bs, base_name, has_speed ? speed : 0,
1917 on_error, block_job_cb, bs, &local_err);
1919 error_propagate(errp, local_err);
1923 trace_qmp_block_stream(bs, bs->job);
1926 void qmp_block_commit(const char *device,
1927 bool has_base, const char *base,
1928 bool has_top, const char *top,
1929 bool has_backing_file, const char *backing_file,
1930 bool has_speed, int64_t speed,
1933 BlockDriverState *bs;
1934 BlockDriverState *base_bs, *top_bs;
1935 Error *local_err = NULL;
1936 /* This will be part of the QMP command, if/when the
1937 * BlockdevOnError change for blkmirror makes it in
1939 BlockdevOnError on_error = BLOCKDEV_ON_ERROR_REPORT;
1945 /* drain all i/o before commits */
1949 * libvirt relies on the DeviceNotFound error class in order to probe for
1950 * live commit feature versions; for this to work, we must make sure to
1951 * perform the device lookup before any generic errors that may occur in a
1952 * scenario in which all optional arguments are omitted. */
1953 bs = bdrv_find(device);
1955 error_set(errp, QERR_DEVICE_NOT_FOUND, device);
1959 if (bdrv_op_is_blocked(bs, BLOCK_OP_TYPE_COMMIT, errp)) {
1963 /* default top_bs is the active layer */
1966 if (has_top && top) {
1967 if (strcmp(bs->filename, top) != 0) {
1968 top_bs = bdrv_find_backing_image(bs, top);
1972 if (top_bs == NULL) {
1973 error_setg(errp, "Top image file %s not found", top ? top : "NULL");
1977 if (has_base && base) {
1978 base_bs = bdrv_find_backing_image(top_bs, base);
1980 base_bs = bdrv_find_base(top_bs);
1983 if (base_bs == NULL) {
1984 error_set(errp, QERR_BASE_NOT_FOUND, base ? base : "NULL");
1988 /* Do not allow attempts to commit an image into itself */
1989 if (top_bs == base_bs) {
1990 error_setg(errp, "cannot commit an image into itself");
1995 if (has_backing_file) {
1996 error_setg(errp, "'backing-file' specified,"
1997 " but 'top' is the active layer");
2000 commit_active_start(bs, base_bs, speed, on_error, block_job_cb,
2003 commit_start(bs, base_bs, top_bs, speed, on_error, block_job_cb, bs,
2004 has_backing_file ? backing_file : NULL, &local_err);
2006 if (local_err != NULL) {
2007 error_propagate(errp, local_err);
2012 void qmp_drive_backup(const char *device, const char *target,
2013 bool has_format, const char *format,
2014 enum MirrorSyncMode sync,
2015 bool has_mode, enum NewImageMode mode,
2016 bool has_speed, int64_t speed,
2017 bool has_on_source_error, BlockdevOnError on_source_error,
2018 bool has_on_target_error, BlockdevOnError on_target_error,
2021 BlockDriverState *bs;
2022 BlockDriverState *target_bs;
2023 BlockDriverState *source = NULL;
2024 BlockDriver *drv = NULL;
2025 Error *local_err = NULL;
2033 if (!has_on_source_error) {
2034 on_source_error = BLOCKDEV_ON_ERROR_REPORT;
2036 if (!has_on_target_error) {
2037 on_target_error = BLOCKDEV_ON_ERROR_REPORT;
2040 mode = NEW_IMAGE_MODE_ABSOLUTE_PATHS;
2043 bs = bdrv_find(device);
2045 error_set(errp, QERR_DEVICE_NOT_FOUND, device);
2049 if (!bdrv_is_inserted(bs)) {
2050 error_set(errp, QERR_DEVICE_HAS_NO_MEDIUM, device);
2055 format = mode == NEW_IMAGE_MODE_EXISTING ? NULL : bs->drv->format_name;
2058 drv = bdrv_find_format(format);
2060 error_set(errp, QERR_INVALID_BLOCK_FORMAT, format);
2065 if (bdrv_op_is_blocked(bs, BLOCK_OP_TYPE_BACKUP_SOURCE, errp)) {
2069 flags = bs->open_flags | BDRV_O_RDWR;
2071 /* See if we have a backing HD we can use to create our new image
2073 if (sync == MIRROR_SYNC_MODE_TOP) {
2074 source = bs->backing_hd;
2076 sync = MIRROR_SYNC_MODE_FULL;
2079 if (sync == MIRROR_SYNC_MODE_NONE) {
2083 size = bdrv_getlength(bs);
2085 error_setg_errno(errp, -size, "bdrv_getlength failed");
2089 if (mode != NEW_IMAGE_MODE_EXISTING) {
2090 assert(format && drv);
2092 bdrv_img_create(target, format, source->filename,
2093 source->drv->format_name, NULL,
2094 size, flags, &local_err, false);
2096 bdrv_img_create(target, format, NULL, NULL, NULL,
2097 size, flags, &local_err, false);
2102 error_propagate(errp, local_err);
2107 ret = bdrv_open(&target_bs, target, NULL, NULL, flags, drv, &local_err);
2109 error_propagate(errp, local_err);
2113 backup_start(bs, target_bs, speed, sync, on_source_error, on_target_error,
2114 block_job_cb, bs, &local_err);
2115 if (local_err != NULL) {
2116 bdrv_unref(target_bs);
2117 error_propagate(errp, local_err);
2122 BlockDeviceInfoList *qmp_query_named_block_nodes(Error **errp)
2124 return bdrv_named_nodes_list();
2127 #define DEFAULT_MIRROR_BUF_SIZE (10 << 20)
2129 void qmp_drive_mirror(const char *device, const char *target,
2130 bool has_format, const char *format,
2131 bool has_node_name, const char *node_name,
2132 bool has_replaces, const char *replaces,
2133 enum MirrorSyncMode sync,
2134 bool has_mode, enum NewImageMode mode,
2135 bool has_speed, int64_t speed,
2136 bool has_granularity, uint32_t granularity,
2137 bool has_buf_size, int64_t buf_size,
2138 bool has_on_source_error, BlockdevOnError on_source_error,
2139 bool has_on_target_error, BlockdevOnError on_target_error,
2142 BlockDriverState *bs;
2143 BlockDriverState *source, *target_bs;
2144 BlockDriver *drv = NULL;
2145 Error *local_err = NULL;
2146 QDict *options = NULL;
2154 if (!has_on_source_error) {
2155 on_source_error = BLOCKDEV_ON_ERROR_REPORT;
2157 if (!has_on_target_error) {
2158 on_target_error = BLOCKDEV_ON_ERROR_REPORT;
2161 mode = NEW_IMAGE_MODE_ABSOLUTE_PATHS;
2163 if (!has_granularity) {
2166 if (!has_buf_size) {
2167 buf_size = DEFAULT_MIRROR_BUF_SIZE;
2170 if (granularity != 0 && (granularity < 512 || granularity > 1048576 * 64)) {
2171 error_set(errp, QERR_INVALID_PARAMETER_VALUE, "granularity",
2172 "a value in range [512B, 64MB]");
2175 if (granularity & (granularity - 1)) {
2176 error_set(errp, QERR_INVALID_PARAMETER_VALUE, "granularity", "power of 2");
2180 bs = bdrv_find(device);
2182 error_set(errp, QERR_DEVICE_NOT_FOUND, device);
2186 if (!bdrv_is_inserted(bs)) {
2187 error_set(errp, QERR_DEVICE_HAS_NO_MEDIUM, device);
2192 format = mode == NEW_IMAGE_MODE_EXISTING ? NULL : bs->drv->format_name;
2195 drv = bdrv_find_format(format);
2197 error_set(errp, QERR_INVALID_BLOCK_FORMAT, format);
2202 if (bdrv_op_is_blocked(bs, BLOCK_OP_TYPE_MIRROR, errp)) {
2206 flags = bs->open_flags | BDRV_O_RDWR;
2207 source = bs->backing_hd;
2208 if (!source && sync == MIRROR_SYNC_MODE_TOP) {
2209 sync = MIRROR_SYNC_MODE_FULL;
2211 if (sync == MIRROR_SYNC_MODE_NONE) {
2215 size = bdrv_getlength(bs);
2217 error_setg_errno(errp, -size, "bdrv_getlength failed");
2222 BlockDriverState *to_replace_bs;
2224 if (!has_node_name) {
2225 error_setg(errp, "a node-name must be provided when replacing a"
2226 " named node of the graph");
2230 to_replace_bs = check_to_replace_node(replaces, &local_err);
2232 if (!to_replace_bs) {
2233 error_propagate(errp, local_err);
2237 if (size != bdrv_getlength(to_replace_bs)) {
2238 error_setg(errp, "cannot replace image with a mirror image of "
2244 if ((sync == MIRROR_SYNC_MODE_FULL || !source)
2245 && mode != NEW_IMAGE_MODE_EXISTING)
2247 /* create new image w/o backing file */
2248 assert(format && drv);
2249 bdrv_img_create(target, format,
2250 NULL, NULL, NULL, size, flags, &local_err, false);
2253 case NEW_IMAGE_MODE_EXISTING:
2255 case NEW_IMAGE_MODE_ABSOLUTE_PATHS:
2256 /* create new image with backing file */
2257 bdrv_img_create(target, format,
2259 source->drv->format_name,
2260 NULL, size, flags, &local_err, false);
2268 error_propagate(errp, local_err);
2272 if (has_node_name) {
2273 options = qdict_new();
2274 qdict_put(options, "node-name", qstring_from_str(node_name));
2277 /* Mirroring takes care of copy-on-write using the source's backing
2281 ret = bdrv_open(&target_bs, target, NULL, options,
2282 flags | BDRV_O_NO_BACKING, drv, &local_err);
2284 error_propagate(errp, local_err);
2288 /* pass the node name to replace to mirror start since it's loose coupling
2289 * and will allow to check whether the node still exist at mirror completion
2291 mirror_start(bs, target_bs,
2292 has_replaces ? replaces : NULL,
2293 speed, granularity, buf_size, sync,
2294 on_source_error, on_target_error,
2295 block_job_cb, bs, &local_err);
2296 if (local_err != NULL) {
2297 bdrv_unref(target_bs);
2298 error_propagate(errp, local_err);
2303 static BlockJob *find_block_job(const char *device)
2305 BlockDriverState *bs;
2307 bs = bdrv_find(device);
2308 if (!bs || !bs->job) {
2314 void qmp_block_job_set_speed(const char *device, int64_t speed, Error **errp)
2316 BlockJob *job = find_block_job(device);
2319 error_set(errp, QERR_BLOCK_JOB_NOT_ACTIVE, device);
2323 block_job_set_speed(job, speed, errp);
2326 void qmp_block_job_cancel(const char *device,
2327 bool has_force, bool force, Error **errp)
2329 BlockJob *job = find_block_job(device);
2336 error_set(errp, QERR_BLOCK_JOB_NOT_ACTIVE, device);
2339 if (job->paused && !force) {
2340 error_setg(errp, "The block job for device '%s' is currently paused",
2345 trace_qmp_block_job_cancel(job);
2346 block_job_cancel(job);
2349 void qmp_block_job_pause(const char *device, Error **errp)
2351 BlockJob *job = find_block_job(device);
2354 error_set(errp, QERR_BLOCK_JOB_NOT_ACTIVE, device);
2358 trace_qmp_block_job_pause(job);
2359 block_job_pause(job);
2362 void qmp_block_job_resume(const char *device, Error **errp)
2364 BlockJob *job = find_block_job(device);
2367 error_set(errp, QERR_BLOCK_JOB_NOT_ACTIVE, device);
2371 trace_qmp_block_job_resume(job);
2372 block_job_resume(job);
2375 void qmp_block_job_complete(const char *device, Error **errp)
2377 BlockJob *job = find_block_job(device);
2380 error_set(errp, QERR_BLOCK_JOB_NOT_ACTIVE, device);
2384 trace_qmp_block_job_complete(job);
2385 block_job_complete(job, errp);
2388 void qmp_change_backing_file(const char *device,
2389 const char *image_node_name,
2390 const char *backing_file,
2393 BlockDriverState *bs = NULL;
2394 BlockDriverState *image_bs = NULL;
2395 Error *local_err = NULL;
2400 /* find the top layer BDS of the chain */
2401 bs = bdrv_find(device);
2403 error_set(errp, QERR_DEVICE_NOT_FOUND, device);
2407 image_bs = bdrv_lookup_bs(NULL, image_node_name, &local_err);
2409 error_propagate(errp, local_err);
2414 error_setg(errp, "image file not found");
2418 if (bdrv_find_base(image_bs) == image_bs) {
2419 error_setg(errp, "not allowing backing file change on an image "
2420 "without a backing file");
2424 /* even though we are not necessarily operating on bs, we need it to
2425 * determine if block ops are currently prohibited on the chain */
2426 if (bdrv_op_is_blocked(bs, BLOCK_OP_TYPE_CHANGE, errp)) {
2430 /* final sanity check */
2431 if (!bdrv_chain_contains(bs, image_bs)) {
2432 error_setg(errp, "'%s' and image file are not in the same chain",
2437 /* if not r/w, reopen to make r/w */
2438 open_flags = image_bs->open_flags;
2439 ro = bdrv_is_read_only(image_bs);
2442 bdrv_reopen(image_bs, open_flags | BDRV_O_RDWR, &local_err);
2444 error_propagate(errp, local_err);
2449 ret = bdrv_change_backing_file(image_bs, backing_file,
2450 image_bs->drv ? image_bs->drv->format_name : "");
2453 error_setg_errno(errp, -ret, "Could not change backing file to '%s'",
2455 /* don't exit here, so we can try to restore open flags if
2460 bdrv_reopen(image_bs, open_flags, &local_err);
2462 error_propagate(errp, local_err); /* will preserve prior errp */
2467 void qmp_blockdev_add(BlockdevOptions *options, Error **errp)
2469 QmpOutputVisitor *ov = qmp_output_visitor_new();
2473 Error *local_err = NULL;
2475 /* Require an ID in the top level */
2476 if (!options->has_id) {
2477 error_setg(errp, "Block device needs an ID");
2481 /* TODO Sort it out in raw-posix and drive_new(): Reject aio=native with
2482 * cache.direct=false instead of silently switching to aio=threads, except
2483 * when called from drive_new().
2485 * For now, simply forbidding the combination for all drivers will do. */
2486 if (options->has_aio && options->aio == BLOCKDEV_AIO_OPTIONS_NATIVE) {
2487 bool direct = options->has_cache &&
2488 options->cache->has_direct &&
2489 options->cache->direct;
2491 error_setg(errp, "aio=native requires cache.direct=true");
2496 visit_type_BlockdevOptions(qmp_output_get_visitor(ov),
2497 &options, NULL, &local_err);
2499 error_propagate(errp, local_err);
2503 obj = qmp_output_get_qobject(ov);
2504 qdict = qobject_to_qdict(obj);
2506 qdict_flatten(qdict);
2508 dinfo = blockdev_init(NULL, qdict, &local_err);
2510 error_propagate(errp, local_err);
2514 if (bdrv_key_required(dinfo->bdrv)) {
2516 error_setg(errp, "blockdev-add doesn't support encrypted devices");
2521 qmp_output_visitor_cleanup(ov);
2524 static void do_qmp_query_block_jobs_one(void *opaque, BlockDriverState *bs)
2526 BlockJobInfoList **prev = opaque;
2527 BlockJob *job = bs->job;
2530 BlockJobInfoList *elem = g_new0(BlockJobInfoList, 1);
2531 elem->value = block_job_query(bs->job);
2532 (*prev)->next = elem;
2537 BlockJobInfoList *qmp_query_block_jobs(Error **errp)
2539 /* Dummy is a fake list element for holding the head pointer */
2540 BlockJobInfoList dummy = {};
2541 BlockJobInfoList *prev = &dummy;
2542 bdrv_iterate(do_qmp_query_block_jobs_one, &prev);
2546 QemuOptsList qemu_common_drive_opts = {
2548 .head = QTAILQ_HEAD_INITIALIZER(qemu_common_drive_opts.head),
2552 .type = QEMU_OPT_BOOL,
2553 .help = "enable/disable snapshot mode",
2556 .type = QEMU_OPT_STRING,
2557 .help = "discard operation (ignore/off, unmap/on)",
2559 .name = "cache.writeback",
2560 .type = QEMU_OPT_BOOL,
2561 .help = "enables writeback mode for any caches",
2563 .name = "cache.direct",
2564 .type = QEMU_OPT_BOOL,
2565 .help = "enables use of O_DIRECT (bypass the host page cache)",
2567 .name = "cache.no-flush",
2568 .type = QEMU_OPT_BOOL,
2569 .help = "ignore any flush requests for the device",
2572 .type = QEMU_OPT_STRING,
2573 .help = "host AIO implementation (threads, native)",
2576 .type = QEMU_OPT_STRING,
2577 .help = "disk format (raw, qcow2, ...)",
2580 .type = QEMU_OPT_STRING,
2581 .help = "read error action",
2584 .type = QEMU_OPT_STRING,
2585 .help = "write error action",
2587 .name = "read-only",
2588 .type = QEMU_OPT_BOOL,
2589 .help = "open drive file as read-only",
2591 .name = "throttling.iops-total",
2592 .type = QEMU_OPT_NUMBER,
2593 .help = "limit total I/O operations per second",
2595 .name = "throttling.iops-read",
2596 .type = QEMU_OPT_NUMBER,
2597 .help = "limit read operations per second",
2599 .name = "throttling.iops-write",
2600 .type = QEMU_OPT_NUMBER,
2601 .help = "limit write operations per second",
2603 .name = "throttling.bps-total",
2604 .type = QEMU_OPT_NUMBER,
2605 .help = "limit total bytes per second",
2607 .name = "throttling.bps-read",
2608 .type = QEMU_OPT_NUMBER,
2609 .help = "limit read bytes per second",
2611 .name = "throttling.bps-write",
2612 .type = QEMU_OPT_NUMBER,
2613 .help = "limit write bytes per second",
2615 .name = "throttling.iops-total-max",
2616 .type = QEMU_OPT_NUMBER,
2617 .help = "I/O operations burst",
2619 .name = "throttling.iops-read-max",
2620 .type = QEMU_OPT_NUMBER,
2621 .help = "I/O operations read burst",
2623 .name = "throttling.iops-write-max",
2624 .type = QEMU_OPT_NUMBER,
2625 .help = "I/O operations write burst",
2627 .name = "throttling.bps-total-max",
2628 .type = QEMU_OPT_NUMBER,
2629 .help = "total bytes burst",
2631 .name = "throttling.bps-read-max",
2632 .type = QEMU_OPT_NUMBER,
2633 .help = "total bytes read burst",
2635 .name = "throttling.bps-write-max",
2636 .type = QEMU_OPT_NUMBER,
2637 .help = "total bytes write burst",
2639 .name = "throttling.iops-size",
2640 .type = QEMU_OPT_NUMBER,
2641 .help = "when limiting by iops max size of an I/O in bytes",
2643 .name = "copy-on-read",
2644 .type = QEMU_OPT_BOOL,
2645 .help = "copy read data from backing file into image file",
2647 .name = "detect-zeroes",
2648 .type = QEMU_OPT_STRING,
2649 .help = "try to optimize zero writes (off, on, unmap)",
2651 { /* end of list */ }
2655 QemuOptsList qemu_drive_opts = {
2657 .head = QTAILQ_HEAD_INITIALIZER(qemu_drive_opts.head),
2660 * no elements => accept any params
2661 * validation will happen later
2663 { /* end of list */ }