block: Drop superfluous conditionals around qemu_opts_del()
[qemu/ar7.git] / blockdev.c
blob2f441c53433370daa836400e942b2079d0416e84
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/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"
46 #include "trace.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] = {
52 [IF_NONE] = "none",
53 [IF_IDE] = "ide",
54 [IF_SCSI] = "scsi",
55 [IF_FLOPPY] = "floppy",
56 [IF_PFLASH] = "pflash",
57 [IF_MTD] = "mtd",
58 [IF_SD] = "sd",
59 [IF_VIRTIO] = "virtio",
60 [IF_XEN] = "xen",
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
71 * values.
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.
78 [IF_IDE] = 2,
79 [IF_SCSI] = 7,
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) {
94 return;
97 if (bs->job) {
98 block_job_cancel(bs->job);
100 if (dinfo) {
101 dinfo->auto_del = 1;
105 void blockdev_auto_del(BlockDriverState *bs)
107 DriveInfo *dinfo = drive_get_by_blockdev(bs);
109 if (dinfo && dinfo->auto_del) {
110 drive_del(dinfo);
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,
132 const char *optstr)
134 QemuOpts *opts;
135 char buf[32];
137 opts = drive_def(optstr);
138 if (!opts) {
139 return NULL;
141 if (type != IF_DEFAULT) {
142 qemu_opt_set(opts, "if", if_name[type]);
144 if (index >= 0) {
145 snprintf(buf, sizeof(buf), "%d", index);
146 qemu_opt_set(opts, "index", buf);
148 if (file)
149 qemu_opt_set(opts, "file", file);
150 return opts;
153 DriveInfo *drive_get(BlockInterfaceType type, int bus, int unit)
155 DriveInfo *dinfo;
157 /* seek interface, bus and unit */
159 QTAILQ_FOREACH(dinfo, &drives, next) {
160 if (dinfo->type == type &&
161 dinfo->bus == bus &&
162 dinfo->unit == unit)
163 return dinfo;
166 return NULL;
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)
178 int max_bus;
179 DriveInfo *dinfo;
181 max_bus = -1;
182 QTAILQ_FOREACH(dinfo, &drives, next) {
183 if(dinfo->type == type &&
184 dinfo->bus > max_bus)
185 max_bus = dinfo->bus;
187 return max_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
192 appropriate bus. */
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)
202 DriveInfo *dinfo;
204 QTAILQ_FOREACH(dinfo, &drives, next) {
205 if (dinfo->bdrv == bs) {
206 return dinfo;
209 return NULL;
212 static void bdrv_format_print(void *opaque, const char *name)
214 error_printf(" %s", name);
217 void drive_del(DriveInfo *dinfo)
219 bdrv_unref(dinfo->bdrv);
222 void drive_info_del(DriveInfo *dinfo)
224 if (!dinfo) {
225 return;
227 qemu_opts_del(dinfo->opts);
228 g_free(dinfo->id);
229 QTAILQ_REMOVE(&drives, dinfo, next);
230 g_free(dinfo->serial);
231 g_free(dinfo);
234 typedef struct {
235 QEMUBH *bh;
236 BlockDriverState *bs;
237 } BDRVPutRefBH;
239 static void bdrv_put_ref_bh(void *opaque)
241 BDRVPutRefBH *s = opaque;
243 bdrv_unref(s->bs);
244 qemu_bh_delete(s->bh);
245 g_free(s);
249 * Release a BDS reference in a BH
251 * It is not safe to use bdrv_unref() from a callback function when the callers
252 * still need the BlockDriverState. In such cases we schedule a BH to release
253 * the reference.
255 static void bdrv_put_ref_bh_schedule(BlockDriverState *bs)
257 BDRVPutRefBH *s;
259 s = g_new(BDRVPutRefBH, 1);
260 s->bh = qemu_bh_new(bdrv_put_ref_bh, s);
261 s->bs = bs;
262 qemu_bh_schedule(s->bh);
265 static int parse_block_error_action(const char *buf, bool is_read, Error **errp)
267 if (!strcmp(buf, "ignore")) {
268 return BLOCKDEV_ON_ERROR_IGNORE;
269 } else if (!is_read && !strcmp(buf, "enospc")) {
270 return BLOCKDEV_ON_ERROR_ENOSPC;
271 } else if (!strcmp(buf, "stop")) {
272 return BLOCKDEV_ON_ERROR_STOP;
273 } else if (!strcmp(buf, "report")) {
274 return BLOCKDEV_ON_ERROR_REPORT;
275 } else {
276 error_setg(errp, "'%s' invalid %s error action",
277 buf, is_read ? "read" : "write");
278 return -1;
282 static bool check_throttle_config(ThrottleConfig *cfg, Error **errp)
284 if (throttle_conflicting(cfg)) {
285 error_setg(errp, "bps/iops/max total values and read/write values"
286 " cannot be used at the same time");
287 return false;
290 if (!throttle_is_valid(cfg)) {
291 error_setg(errp, "bps/iops/maxs values must be 0 or greater");
292 return false;
295 return true;
298 typedef enum { MEDIA_DISK, MEDIA_CDROM } DriveMediaType;
300 /* Takes the ownership of bs_opts */
301 static DriveInfo *blockdev_init(const char *file, QDict *bs_opts,
302 Error **errp)
304 const char *buf;
305 int ro = 0;
306 int bdrv_flags = 0;
307 int on_read_error, on_write_error;
308 BlockDriverState *bs;
309 DriveInfo *dinfo;
310 ThrottleConfig cfg;
311 int snapshot = 0;
312 bool copy_on_read;
313 int ret;
314 Error *error = NULL;
315 QemuOpts *opts;
316 const char *id;
317 bool has_driver_specific_opts;
318 BlockdevDetectZeroesOptions detect_zeroes;
319 BlockDriver *drv = NULL;
321 /* Check common options by copying from bs_opts to opts, all other options
322 * stay in bs_opts for processing by bdrv_open(). */
323 id = qdict_get_try_str(bs_opts, "id");
324 opts = qemu_opts_create(&qemu_common_drive_opts, id, 1, &error);
325 if (error) {
326 error_propagate(errp, error);
327 goto err_no_opts;
330 qemu_opts_absorb_qdict(opts, bs_opts, &error);
331 if (error) {
332 error_propagate(errp, error);
333 goto early_err;
336 if (id) {
337 qdict_del(bs_opts, "id");
340 has_driver_specific_opts = !!qdict_size(bs_opts);
342 /* extract parameters */
343 snapshot = qemu_opt_get_bool(opts, "snapshot", 0);
344 ro = qemu_opt_get_bool(opts, "read-only", 0);
345 copy_on_read = qemu_opt_get_bool(opts, "copy-on-read", false);
347 if ((buf = qemu_opt_get(opts, "discard")) != NULL) {
348 if (bdrv_parse_discard_flags(buf, &bdrv_flags) != 0) {
349 error_setg(errp, "invalid discard option");
350 goto early_err;
354 if (qemu_opt_get_bool(opts, "cache.writeback", true)) {
355 bdrv_flags |= BDRV_O_CACHE_WB;
357 if (qemu_opt_get_bool(opts, "cache.direct", false)) {
358 bdrv_flags |= BDRV_O_NOCACHE;
360 if (qemu_opt_get_bool(opts, "cache.no-flush", false)) {
361 bdrv_flags |= BDRV_O_NO_FLUSH;
364 #ifdef CONFIG_LINUX_AIO
365 if ((buf = qemu_opt_get(opts, "aio")) != NULL) {
366 if (!strcmp(buf, "native")) {
367 bdrv_flags |= BDRV_O_NATIVE_AIO;
368 } else if (!strcmp(buf, "threads")) {
369 /* this is the default */
370 } else {
371 error_setg(errp, "invalid aio option");
372 goto early_err;
375 #endif
377 if ((buf = qemu_opt_get(opts, "format")) != NULL) {
378 if (is_help_option(buf)) {
379 error_printf("Supported formats:");
380 bdrv_iterate_format(bdrv_format_print, NULL);
381 error_printf("\n");
382 goto early_err;
385 drv = bdrv_find_format(buf);
386 if (!drv) {
387 error_setg(errp, "'%s' invalid format", buf);
388 goto early_err;
392 /* disk I/O throttling */
393 memset(&cfg, 0, sizeof(cfg));
394 cfg.buckets[THROTTLE_BPS_TOTAL].avg =
395 qemu_opt_get_number(opts, "throttling.bps-total", 0);
396 cfg.buckets[THROTTLE_BPS_READ].avg =
397 qemu_opt_get_number(opts, "throttling.bps-read", 0);
398 cfg.buckets[THROTTLE_BPS_WRITE].avg =
399 qemu_opt_get_number(opts, "throttling.bps-write", 0);
400 cfg.buckets[THROTTLE_OPS_TOTAL].avg =
401 qemu_opt_get_number(opts, "throttling.iops-total", 0);
402 cfg.buckets[THROTTLE_OPS_READ].avg =
403 qemu_opt_get_number(opts, "throttling.iops-read", 0);
404 cfg.buckets[THROTTLE_OPS_WRITE].avg =
405 qemu_opt_get_number(opts, "throttling.iops-write", 0);
407 cfg.buckets[THROTTLE_BPS_TOTAL].max =
408 qemu_opt_get_number(opts, "throttling.bps-total-max", 0);
409 cfg.buckets[THROTTLE_BPS_READ].max =
410 qemu_opt_get_number(opts, "throttling.bps-read-max", 0);
411 cfg.buckets[THROTTLE_BPS_WRITE].max =
412 qemu_opt_get_number(opts, "throttling.bps-write-max", 0);
413 cfg.buckets[THROTTLE_OPS_TOTAL].max =
414 qemu_opt_get_number(opts, "throttling.iops-total-max", 0);
415 cfg.buckets[THROTTLE_OPS_READ].max =
416 qemu_opt_get_number(opts, "throttling.iops-read-max", 0);
417 cfg.buckets[THROTTLE_OPS_WRITE].max =
418 qemu_opt_get_number(opts, "throttling.iops-write-max", 0);
420 cfg.op_size = qemu_opt_get_number(opts, "throttling.iops-size", 0);
422 if (!check_throttle_config(&cfg, &error)) {
423 error_propagate(errp, error);
424 goto early_err;
427 on_write_error = BLOCKDEV_ON_ERROR_ENOSPC;
428 if ((buf = qemu_opt_get(opts, "werror")) != NULL) {
429 on_write_error = parse_block_error_action(buf, 0, &error);
430 if (error) {
431 error_propagate(errp, error);
432 goto early_err;
436 on_read_error = BLOCKDEV_ON_ERROR_REPORT;
437 if ((buf = qemu_opt_get(opts, "rerror")) != NULL) {
438 on_read_error = parse_block_error_action(buf, 1, &error);
439 if (error) {
440 error_propagate(errp, error);
441 goto early_err;
445 detect_zeroes =
446 qapi_enum_parse(BlockdevDetectZeroesOptions_lookup,
447 qemu_opt_get(opts, "detect-zeroes"),
448 BLOCKDEV_DETECT_ZEROES_OPTIONS_MAX,
449 BLOCKDEV_DETECT_ZEROES_OPTIONS_OFF,
450 &error);
451 if (error) {
452 error_propagate(errp, error);
453 goto early_err;
456 if (detect_zeroes == BLOCKDEV_DETECT_ZEROES_OPTIONS_UNMAP &&
457 !(bdrv_flags & BDRV_O_UNMAP)) {
458 error_setg(errp, "setting detect-zeroes to unmap is not allowed "
459 "without setting discard operation to unmap");
460 goto early_err;
463 /* init */
464 bs = bdrv_new(qemu_opts_id(opts), errp);
465 if (!bs) {
466 goto early_err;
468 bs->open_flags = snapshot ? BDRV_O_SNAPSHOT : 0;
469 bs->read_only = ro;
470 bs->detect_zeroes = detect_zeroes;
472 bdrv_set_on_error(bs, on_read_error, on_write_error);
474 /* disk I/O throttling */
475 if (throttle_enabled(&cfg)) {
476 bdrv_io_limits_enable(bs);
477 bdrv_set_io_limits(bs, &cfg);
480 dinfo = g_malloc0(sizeof(*dinfo));
481 dinfo->id = g_strdup(qemu_opts_id(opts));
482 dinfo->bdrv = bs;
483 QTAILQ_INSERT_TAIL(&drives, dinfo, next);
485 if (!file || !*file) {
486 if (has_driver_specific_opts) {
487 file = NULL;
488 } else {
489 QDECREF(bs_opts);
490 qemu_opts_del(opts);
491 return dinfo;
494 if (snapshot) {
495 /* always use cache=unsafe with snapshot */
496 bdrv_flags &= ~BDRV_O_CACHE_MASK;
497 bdrv_flags |= (BDRV_O_SNAPSHOT|BDRV_O_CACHE_WB|BDRV_O_NO_FLUSH);
500 if (copy_on_read) {
501 bdrv_flags |= BDRV_O_COPY_ON_READ;
504 if (runstate_check(RUN_STATE_INMIGRATE)) {
505 bdrv_flags |= BDRV_O_INCOMING;
508 bdrv_flags |= ro ? 0 : BDRV_O_RDWR;
510 QINCREF(bs_opts);
511 ret = bdrv_open(&bs, file, NULL, bs_opts, bdrv_flags, drv, &error);
512 assert(bs == dinfo->bdrv);
514 if (ret < 0) {
515 error_setg(errp, "could not open disk image %s: %s",
516 file ?: dinfo->id, error_get_pretty(error));
517 error_free(error);
518 goto err;
521 if (bdrv_key_required(bs)) {
522 autostart = 0;
525 QDECREF(bs_opts);
526 qemu_opts_del(opts);
528 return dinfo;
530 err:
531 bdrv_unref(bs);
532 early_err:
533 qemu_opts_del(opts);
534 err_no_opts:
535 QDECREF(bs_opts);
536 return NULL;
539 static void qemu_opt_rename(QemuOpts *opts, const char *from, const char *to,
540 Error **errp)
542 const char *value;
544 value = qemu_opt_get(opts, from);
545 if (value) {
546 if (qemu_opt_find(opts, to)) {
547 error_setg(errp, "'%s' and its alias '%s' can't be used at the "
548 "same time", to, from);
549 return;
551 qemu_opt_set(opts, to, value);
552 qemu_opt_unset(opts, from);
556 QemuOptsList qemu_legacy_drive_opts = {
557 .name = "drive",
558 .head = QTAILQ_HEAD_INITIALIZER(qemu_legacy_drive_opts.head),
559 .desc = {
561 .name = "bus",
562 .type = QEMU_OPT_NUMBER,
563 .help = "bus number",
565 .name = "unit",
566 .type = QEMU_OPT_NUMBER,
567 .help = "unit number (i.e. lun for scsi)",
569 .name = "index",
570 .type = QEMU_OPT_NUMBER,
571 .help = "index number",
573 .name = "media",
574 .type = QEMU_OPT_STRING,
575 .help = "media type (disk, cdrom)",
577 .name = "if",
578 .type = QEMU_OPT_STRING,
579 .help = "interface (ide, scsi, sd, mtd, floppy, pflash, virtio)",
581 .name = "cyls",
582 .type = QEMU_OPT_NUMBER,
583 .help = "number of cylinders (ide disk geometry)",
585 .name = "heads",
586 .type = QEMU_OPT_NUMBER,
587 .help = "number of heads (ide disk geometry)",
589 .name = "secs",
590 .type = QEMU_OPT_NUMBER,
591 .help = "number of sectors (ide disk geometry)",
593 .name = "trans",
594 .type = QEMU_OPT_STRING,
595 .help = "chs translation (auto, lba, none)",
597 .name = "boot",
598 .type = QEMU_OPT_BOOL,
599 .help = "(deprecated, ignored)",
601 .name = "addr",
602 .type = QEMU_OPT_STRING,
603 .help = "pci address (virtio only)",
605 .name = "serial",
606 .type = QEMU_OPT_STRING,
607 .help = "disk serial number",
609 .name = "file",
610 .type = QEMU_OPT_STRING,
611 .help = "file name",
614 /* Options that are passed on, but have special semantics with -drive */
616 .name = "read-only",
617 .type = QEMU_OPT_BOOL,
618 .help = "open drive file as read-only",
620 .name = "rerror",
621 .type = QEMU_OPT_STRING,
622 .help = "read error action",
624 .name = "werror",
625 .type = QEMU_OPT_STRING,
626 .help = "write error action",
628 .name = "copy-on-read",
629 .type = QEMU_OPT_BOOL,
630 .help = "copy read data from backing file into image file",
633 { /* end of list */ }
637 DriveInfo *drive_new(QemuOpts *all_opts, BlockInterfaceType block_default_type)
639 const char *value;
640 DriveInfo *dinfo = NULL;
641 QDict *bs_opts;
642 QemuOpts *legacy_opts;
643 DriveMediaType media = MEDIA_DISK;
644 BlockInterfaceType type;
645 int cyls, heads, secs, translation;
646 int max_devs, bus_id, unit_id, index;
647 const char *devaddr;
648 const char *werror, *rerror;
649 bool read_only = false;
650 bool copy_on_read;
651 const char *serial;
652 const char *filename;
653 Error *local_err = NULL;
654 int i;
656 /* Change legacy command line options into QMP ones */
657 static const struct {
658 const char *from;
659 const char *to;
660 } opt_renames[] = {
661 { "iops", "throttling.iops-total" },
662 { "iops_rd", "throttling.iops-read" },
663 { "iops_wr", "throttling.iops-write" },
665 { "bps", "throttling.bps-total" },
666 { "bps_rd", "throttling.bps-read" },
667 { "bps_wr", "throttling.bps-write" },
669 { "iops_max", "throttling.iops-total-max" },
670 { "iops_rd_max", "throttling.iops-read-max" },
671 { "iops_wr_max", "throttling.iops-write-max" },
673 { "bps_max", "throttling.bps-total-max" },
674 { "bps_rd_max", "throttling.bps-read-max" },
675 { "bps_wr_max", "throttling.bps-write-max" },
677 { "iops_size", "throttling.iops-size" },
679 { "readonly", "read-only" },
682 for (i = 0; i < ARRAY_SIZE(opt_renames); i++) {
683 qemu_opt_rename(all_opts, opt_renames[i].from, opt_renames[i].to,
684 &local_err);
685 if (local_err) {
686 error_report("%s", error_get_pretty(local_err));
687 error_free(local_err);
688 return NULL;
692 value = qemu_opt_get(all_opts, "cache");
693 if (value) {
694 int flags = 0;
696 if (bdrv_parse_cache_flags(value, &flags) != 0) {
697 error_report("invalid cache option");
698 return NULL;
701 /* Specific options take precedence */
702 if (!qemu_opt_get(all_opts, "cache.writeback")) {
703 qemu_opt_set_bool(all_opts, "cache.writeback",
704 !!(flags & BDRV_O_CACHE_WB));
706 if (!qemu_opt_get(all_opts, "cache.direct")) {
707 qemu_opt_set_bool(all_opts, "cache.direct",
708 !!(flags & BDRV_O_NOCACHE));
710 if (!qemu_opt_get(all_opts, "cache.no-flush")) {
711 qemu_opt_set_bool(all_opts, "cache.no-flush",
712 !!(flags & BDRV_O_NO_FLUSH));
714 qemu_opt_unset(all_opts, "cache");
717 /* Get a QDict for processing the options */
718 bs_opts = qdict_new();
719 qemu_opts_to_qdict(all_opts, bs_opts);
721 legacy_opts = qemu_opts_create(&qemu_legacy_drive_opts, NULL, 0,
722 &error_abort);
723 qemu_opts_absorb_qdict(legacy_opts, bs_opts, &local_err);
724 if (local_err) {
725 error_report("%s", error_get_pretty(local_err));
726 error_free(local_err);
727 goto fail;
730 /* Deprecated option boot=[on|off] */
731 if (qemu_opt_get(legacy_opts, "boot") != NULL) {
732 fprintf(stderr, "qemu-kvm: boot=on|off is deprecated and will be "
733 "ignored. Future versions will reject this parameter. Please "
734 "update your scripts.\n");
737 /* Media type */
738 value = qemu_opt_get(legacy_opts, "media");
739 if (value) {
740 if (!strcmp(value, "disk")) {
741 media = MEDIA_DISK;
742 } else if (!strcmp(value, "cdrom")) {
743 media = MEDIA_CDROM;
744 read_only = true;
745 } else {
746 error_report("'%s' invalid media", value);
747 goto fail;
751 /* copy-on-read is disabled with a warning for read-only devices */
752 read_only |= qemu_opt_get_bool(legacy_opts, "read-only", false);
753 copy_on_read = qemu_opt_get_bool(legacy_opts, "copy-on-read", false);
755 if (read_only && copy_on_read) {
756 error_report("warning: disabling copy-on-read on read-only drive");
757 copy_on_read = false;
760 qdict_put(bs_opts, "read-only",
761 qstring_from_str(read_only ? "on" : "off"));
762 qdict_put(bs_opts, "copy-on-read",
763 qstring_from_str(copy_on_read ? "on" :"off"));
765 /* Controller type */
766 value = qemu_opt_get(legacy_opts, "if");
767 if (value) {
768 for (type = 0;
769 type < IF_COUNT && strcmp(value, if_name[type]);
770 type++) {
772 if (type == IF_COUNT) {
773 error_report("unsupported bus type '%s'", value);
774 goto fail;
776 } else {
777 type = block_default_type;
780 /* Geometry */
781 cyls = qemu_opt_get_number(legacy_opts, "cyls", 0);
782 heads = qemu_opt_get_number(legacy_opts, "heads", 0);
783 secs = qemu_opt_get_number(legacy_opts, "secs", 0);
785 if (cyls || heads || secs) {
786 if (cyls < 1) {
787 error_report("invalid physical cyls number");
788 goto fail;
790 if (heads < 1) {
791 error_report("invalid physical heads number");
792 goto fail;
794 if (secs < 1) {
795 error_report("invalid physical secs number");
796 goto fail;
800 translation = BIOS_ATA_TRANSLATION_AUTO;
801 value = qemu_opt_get(legacy_opts, "trans");
802 if (value != NULL) {
803 if (!cyls) {
804 error_report("'%s' trans must be used with cyls, heads and secs",
805 value);
806 goto fail;
808 if (!strcmp(value, "none")) {
809 translation = BIOS_ATA_TRANSLATION_NONE;
810 } else if (!strcmp(value, "lba")) {
811 translation = BIOS_ATA_TRANSLATION_LBA;
812 } else if (!strcmp(value, "large")) {
813 translation = BIOS_ATA_TRANSLATION_LARGE;
814 } else if (!strcmp(value, "rechs")) {
815 translation = BIOS_ATA_TRANSLATION_RECHS;
816 } else if (!strcmp(value, "auto")) {
817 translation = BIOS_ATA_TRANSLATION_AUTO;
818 } else {
819 error_report("'%s' invalid translation type", value);
820 goto fail;
824 if (media == MEDIA_CDROM) {
825 if (cyls || secs || heads) {
826 error_report("CHS can't be set with media=cdrom");
827 goto fail;
831 /* Device address specified by bus/unit or index.
832 * If none was specified, try to find the first free one. */
833 bus_id = qemu_opt_get_number(legacy_opts, "bus", 0);
834 unit_id = qemu_opt_get_number(legacy_opts, "unit", -1);
835 index = qemu_opt_get_number(legacy_opts, "index", -1);
837 max_devs = if_max_devs[type];
839 if (index != -1) {
840 if (bus_id != 0 || unit_id != -1) {
841 error_report("index cannot be used with bus and unit");
842 goto fail;
844 bus_id = drive_index_to_bus_id(type, index);
845 unit_id = drive_index_to_unit_id(type, index);
848 if (unit_id == -1) {
849 unit_id = 0;
850 while (drive_get(type, bus_id, unit_id) != NULL) {
851 unit_id++;
852 if (max_devs && unit_id >= max_devs) {
853 unit_id -= max_devs;
854 bus_id++;
859 if (max_devs && unit_id >= max_devs) {
860 error_report("unit %d too big (max is %d)", unit_id, max_devs - 1);
861 goto fail;
864 if (drive_get(type, bus_id, unit_id) != NULL) {
865 error_report("drive with bus=%d, unit=%d (index=%d) exists",
866 bus_id, unit_id, index);
867 goto fail;
870 /* Serial number */
871 serial = qemu_opt_get(legacy_opts, "serial");
873 /* no id supplied -> create one */
874 if (qemu_opts_id(all_opts) == NULL) {
875 char *new_id;
876 const char *mediastr = "";
877 if (type == IF_IDE || type == IF_SCSI) {
878 mediastr = (media == MEDIA_CDROM) ? "-cd" : "-hd";
880 if (max_devs) {
881 new_id = g_strdup_printf("%s%i%s%i", if_name[type], bus_id,
882 mediastr, unit_id);
883 } else {
884 new_id = g_strdup_printf("%s%s%i", if_name[type],
885 mediastr, unit_id);
887 qdict_put(bs_opts, "id", qstring_from_str(new_id));
888 g_free(new_id);
891 /* Add virtio block device */
892 devaddr = qemu_opt_get(legacy_opts, "addr");
893 if (devaddr && type != IF_VIRTIO) {
894 error_report("addr is not supported by this bus type");
895 goto fail;
898 if (type == IF_VIRTIO) {
899 QemuOpts *devopts;
900 devopts = qemu_opts_create(qemu_find_opts("device"), NULL, 0,
901 &error_abort);
902 if (arch_type == QEMU_ARCH_S390X) {
903 qemu_opt_set(devopts, "driver", "virtio-blk-s390");
904 } else {
905 qemu_opt_set(devopts, "driver", "virtio-blk-pci");
907 qemu_opt_set(devopts, "drive", qdict_get_str(bs_opts, "id"));
908 if (devaddr) {
909 qemu_opt_set(devopts, "addr", devaddr);
913 filename = qemu_opt_get(legacy_opts, "file");
915 /* Check werror/rerror compatibility with if=... */
916 werror = qemu_opt_get(legacy_opts, "werror");
917 if (werror != NULL) {
918 if (type != IF_IDE && type != IF_SCSI && type != IF_VIRTIO &&
919 type != IF_NONE) {
920 error_report("werror is not supported by this bus type");
921 goto fail;
923 qdict_put(bs_opts, "werror", qstring_from_str(werror));
926 rerror = qemu_opt_get(legacy_opts, "rerror");
927 if (rerror != NULL) {
928 if (type != IF_IDE && type != IF_VIRTIO && type != IF_SCSI &&
929 type != IF_NONE) {
930 error_report("rerror is not supported by this bus type");
931 goto fail;
933 qdict_put(bs_opts, "rerror", qstring_from_str(rerror));
936 /* Actual block device init: Functionality shared with blockdev-add */
937 dinfo = blockdev_init(filename, bs_opts, &local_err);
938 bs_opts = NULL;
939 if (dinfo == NULL) {
940 if (local_err) {
941 error_report("%s", error_get_pretty(local_err));
942 error_free(local_err);
944 goto fail;
945 } else {
946 assert(!local_err);
949 /* Set legacy DriveInfo fields */
950 dinfo->enable_auto_del = true;
951 dinfo->opts = all_opts;
953 dinfo->cyls = cyls;
954 dinfo->heads = heads;
955 dinfo->secs = secs;
956 dinfo->trans = translation;
958 dinfo->type = type;
959 dinfo->bus = bus_id;
960 dinfo->unit = unit_id;
961 dinfo->devaddr = devaddr;
963 dinfo->serial = g_strdup(serial);
965 switch(type) {
966 case IF_IDE:
967 case IF_SCSI:
968 case IF_XEN:
969 case IF_NONE:
970 dinfo->media_cd = media == MEDIA_CDROM;
971 break;
972 default:
973 break;
976 fail:
977 qemu_opts_del(legacy_opts);
978 QDECREF(bs_opts);
979 return dinfo;
982 void do_commit(Monitor *mon, const QDict *qdict)
984 const char *device = qdict_get_str(qdict, "device");
985 BlockDriverState *bs;
986 int ret;
988 if (!strcmp(device, "all")) {
989 ret = bdrv_commit_all();
990 } else {
991 bs = bdrv_find(device);
992 if (!bs) {
993 monitor_printf(mon, "Device '%s' not found\n", device);
994 return;
996 ret = bdrv_commit(bs);
998 if (ret < 0) {
999 monitor_printf(mon, "'commit' error for '%s': %s\n", device,
1000 strerror(-ret));
1004 static void blockdev_do_action(int kind, void *data, Error **errp)
1006 TransactionAction action;
1007 TransactionActionList list;
1009 action.kind = kind;
1010 action.data = data;
1011 list.value = &action;
1012 list.next = NULL;
1013 qmp_transaction(&list, errp);
1016 void qmp_blockdev_snapshot_sync(bool has_device, const char *device,
1017 bool has_node_name, const char *node_name,
1018 const char *snapshot_file,
1019 bool has_snapshot_node_name,
1020 const char *snapshot_node_name,
1021 bool has_format, const char *format,
1022 bool has_mode, NewImageMode mode, Error **errp)
1024 BlockdevSnapshot snapshot = {
1025 .has_device = has_device,
1026 .device = (char *) device,
1027 .has_node_name = has_node_name,
1028 .node_name = (char *) node_name,
1029 .snapshot_file = (char *) snapshot_file,
1030 .has_snapshot_node_name = has_snapshot_node_name,
1031 .snapshot_node_name = (char *) snapshot_node_name,
1032 .has_format = has_format,
1033 .format = (char *) format,
1034 .has_mode = has_mode,
1035 .mode = mode,
1037 blockdev_do_action(TRANSACTION_ACTION_KIND_BLOCKDEV_SNAPSHOT_SYNC,
1038 &snapshot, errp);
1041 void qmp_blockdev_snapshot_internal_sync(const char *device,
1042 const char *name,
1043 Error **errp)
1045 BlockdevSnapshotInternal snapshot = {
1046 .device = (char *) device,
1047 .name = (char *) name
1050 blockdev_do_action(TRANSACTION_ACTION_KIND_BLOCKDEV_SNAPSHOT_INTERNAL_SYNC,
1051 &snapshot, errp);
1054 SnapshotInfo *qmp_blockdev_snapshot_delete_internal_sync(const char *device,
1055 bool has_id,
1056 const char *id,
1057 bool has_name,
1058 const char *name,
1059 Error **errp)
1061 BlockDriverState *bs = bdrv_find(device);
1062 QEMUSnapshotInfo sn;
1063 Error *local_err = NULL;
1064 SnapshotInfo *info = NULL;
1065 int ret;
1067 if (!bs) {
1068 error_set(errp, QERR_DEVICE_NOT_FOUND, device);
1069 return NULL;
1072 if (!has_id) {
1073 id = NULL;
1076 if (!has_name) {
1077 name = NULL;
1080 if (!id && !name) {
1081 error_setg(errp, "Name or id must be provided");
1082 return NULL;
1085 ret = bdrv_snapshot_find_by_id_and_name(bs, id, name, &sn, &local_err);
1086 if (local_err) {
1087 error_propagate(errp, local_err);
1088 return NULL;
1090 if (!ret) {
1091 error_setg(errp,
1092 "Snapshot with id '%s' and name '%s' does not exist on "
1093 "device '%s'",
1094 STR_OR_NULL(id), STR_OR_NULL(name), device);
1095 return NULL;
1098 bdrv_snapshot_delete(bs, id, name, &local_err);
1099 if (local_err) {
1100 error_propagate(errp, local_err);
1101 return NULL;
1104 info = g_new0(SnapshotInfo, 1);
1105 info->id = g_strdup(sn.id_str);
1106 info->name = g_strdup(sn.name);
1107 info->date_nsec = sn.date_nsec;
1108 info->date_sec = sn.date_sec;
1109 info->vm_state_size = sn.vm_state_size;
1110 info->vm_clock_nsec = sn.vm_clock_nsec % 1000000000;
1111 info->vm_clock_sec = sn.vm_clock_nsec / 1000000000;
1113 return info;
1116 /* New and old BlockDriverState structs for group snapshots */
1118 typedef struct BlkTransactionState BlkTransactionState;
1120 /* Only prepare() may fail. In a single transaction, only one of commit() or
1121 abort() will be called, clean() will always be called if it present. */
1122 typedef struct BdrvActionOps {
1123 /* Size of state struct, in bytes. */
1124 size_t instance_size;
1125 /* Prepare the work, must NOT be NULL. */
1126 void (*prepare)(BlkTransactionState *common, Error **errp);
1127 /* Commit the changes, can be NULL. */
1128 void (*commit)(BlkTransactionState *common);
1129 /* Abort the changes on fail, can be NULL. */
1130 void (*abort)(BlkTransactionState *common);
1131 /* Clean up resource in the end, can be NULL. */
1132 void (*clean)(BlkTransactionState *common);
1133 } BdrvActionOps;
1136 * This structure must be arranged as first member in child type, assuming
1137 * that compiler will also arrange it to the same address with parent instance.
1138 * Later it will be used in free().
1140 struct BlkTransactionState {
1141 TransactionAction *action;
1142 const BdrvActionOps *ops;
1143 QSIMPLEQ_ENTRY(BlkTransactionState) entry;
1146 /* internal snapshot private data */
1147 typedef struct InternalSnapshotState {
1148 BlkTransactionState common;
1149 BlockDriverState *bs;
1150 QEMUSnapshotInfo sn;
1151 } InternalSnapshotState;
1153 static void internal_snapshot_prepare(BlkTransactionState *common,
1154 Error **errp)
1156 Error *local_err = NULL;
1157 const char *device;
1158 const char *name;
1159 BlockDriverState *bs;
1160 QEMUSnapshotInfo old_sn, *sn;
1161 bool ret;
1162 qemu_timeval tv;
1163 BlockdevSnapshotInternal *internal;
1164 InternalSnapshotState *state;
1165 int ret1;
1167 g_assert(common->action->kind ==
1168 TRANSACTION_ACTION_KIND_BLOCKDEV_SNAPSHOT_INTERNAL_SYNC);
1169 internal = common->action->blockdev_snapshot_internal_sync;
1170 state = DO_UPCAST(InternalSnapshotState, common, common);
1172 /* 1. parse input */
1173 device = internal->device;
1174 name = internal->name;
1176 /* 2. check for validation */
1177 bs = bdrv_find(device);
1178 if (!bs) {
1179 error_set(errp, QERR_DEVICE_NOT_FOUND, device);
1180 return;
1183 if (!bdrv_is_inserted(bs)) {
1184 error_set(errp, QERR_DEVICE_HAS_NO_MEDIUM, device);
1185 return;
1188 if (bdrv_is_read_only(bs)) {
1189 error_set(errp, QERR_DEVICE_IS_READ_ONLY, device);
1190 return;
1193 if (!bdrv_can_snapshot(bs)) {
1194 error_set(errp, QERR_BLOCK_FORMAT_FEATURE_NOT_SUPPORTED,
1195 bs->drv->format_name, device, "internal snapshot");
1196 return;
1199 if (!strlen(name)) {
1200 error_setg(errp, "Name is empty");
1201 return;
1204 /* check whether a snapshot with name exist */
1205 ret = bdrv_snapshot_find_by_id_and_name(bs, NULL, name, &old_sn,
1206 &local_err);
1207 if (local_err) {
1208 error_propagate(errp, local_err);
1209 return;
1210 } else if (ret) {
1211 error_setg(errp,
1212 "Snapshot with name '%s' already exists on device '%s'",
1213 name, device);
1214 return;
1217 /* 3. take the snapshot */
1218 sn = &state->sn;
1219 pstrcpy(sn->name, sizeof(sn->name), name);
1220 qemu_gettimeofday(&tv);
1221 sn->date_sec = tv.tv_sec;
1222 sn->date_nsec = tv.tv_usec * 1000;
1223 sn->vm_clock_nsec = qemu_clock_get_ns(QEMU_CLOCK_VIRTUAL);
1225 ret1 = bdrv_snapshot_create(bs, sn);
1226 if (ret1 < 0) {
1227 error_setg_errno(errp, -ret1,
1228 "Failed to create snapshot '%s' on device '%s'",
1229 name, device);
1230 return;
1233 /* 4. succeed, mark a snapshot is created */
1234 state->bs = bs;
1237 static void internal_snapshot_abort(BlkTransactionState *common)
1239 InternalSnapshotState *state =
1240 DO_UPCAST(InternalSnapshotState, common, common);
1241 BlockDriverState *bs = state->bs;
1242 QEMUSnapshotInfo *sn = &state->sn;
1243 Error *local_error = NULL;
1245 if (!bs) {
1246 return;
1249 if (bdrv_snapshot_delete(bs, sn->id_str, sn->name, &local_error) < 0) {
1250 error_report("Failed to delete snapshot with id '%s' and name '%s' on "
1251 "device '%s' in abort: %s",
1252 sn->id_str,
1253 sn->name,
1254 bdrv_get_device_name(bs),
1255 error_get_pretty(local_error));
1256 error_free(local_error);
1260 /* external snapshot private data */
1261 typedef struct ExternalSnapshotState {
1262 BlkTransactionState common;
1263 BlockDriverState *old_bs;
1264 BlockDriverState *new_bs;
1265 } ExternalSnapshotState;
1267 static void external_snapshot_prepare(BlkTransactionState *common,
1268 Error **errp)
1270 BlockDriver *drv;
1271 int flags, ret;
1272 QDict *options = NULL;
1273 Error *local_err = NULL;
1274 bool has_device = false;
1275 const char *device;
1276 bool has_node_name = false;
1277 const char *node_name;
1278 bool has_snapshot_node_name = false;
1279 const char *snapshot_node_name;
1280 const char *new_image_file;
1281 const char *format = "qcow2";
1282 enum NewImageMode mode = NEW_IMAGE_MODE_ABSOLUTE_PATHS;
1283 ExternalSnapshotState *state =
1284 DO_UPCAST(ExternalSnapshotState, common, common);
1285 TransactionAction *action = common->action;
1287 /* get parameters */
1288 g_assert(action->kind == TRANSACTION_ACTION_KIND_BLOCKDEV_SNAPSHOT_SYNC);
1290 has_device = action->blockdev_snapshot_sync->has_device;
1291 device = action->blockdev_snapshot_sync->device;
1292 has_node_name = action->blockdev_snapshot_sync->has_node_name;
1293 node_name = action->blockdev_snapshot_sync->node_name;
1294 has_snapshot_node_name =
1295 action->blockdev_snapshot_sync->has_snapshot_node_name;
1296 snapshot_node_name = action->blockdev_snapshot_sync->snapshot_node_name;
1298 new_image_file = action->blockdev_snapshot_sync->snapshot_file;
1299 if (action->blockdev_snapshot_sync->has_format) {
1300 format = action->blockdev_snapshot_sync->format;
1302 if (action->blockdev_snapshot_sync->has_mode) {
1303 mode = action->blockdev_snapshot_sync->mode;
1306 /* start processing */
1307 drv = bdrv_find_format(format);
1308 if (!drv) {
1309 error_set(errp, QERR_INVALID_BLOCK_FORMAT, format);
1310 return;
1313 state->old_bs = bdrv_lookup_bs(has_device ? device : NULL,
1314 has_node_name ? node_name : NULL,
1315 &local_err);
1316 if (local_err) {
1317 error_propagate(errp, local_err);
1318 return;
1321 if (has_node_name && !has_snapshot_node_name) {
1322 error_setg(errp, "New snapshot node name missing");
1323 return;
1326 if (has_snapshot_node_name && bdrv_find_node(snapshot_node_name)) {
1327 error_setg(errp, "New snapshot node name already existing");
1328 return;
1331 if (!bdrv_is_inserted(state->old_bs)) {
1332 error_set(errp, QERR_DEVICE_HAS_NO_MEDIUM, device);
1333 return;
1336 if (bdrv_op_is_blocked(state->old_bs,
1337 BLOCK_OP_TYPE_EXTERNAL_SNAPSHOT, errp)) {
1338 return;
1341 if (!bdrv_is_read_only(state->old_bs)) {
1342 if (bdrv_flush(state->old_bs)) {
1343 error_set(errp, QERR_IO_ERROR);
1344 return;
1348 if (!bdrv_is_first_non_filter(state->old_bs)) {
1349 error_set(errp, QERR_FEATURE_DISABLED, "snapshot");
1350 return;
1353 flags = state->old_bs->open_flags;
1355 /* create new image w/backing file */
1356 if (mode != NEW_IMAGE_MODE_EXISTING) {
1357 bdrv_img_create(new_image_file, format,
1358 state->old_bs->filename,
1359 state->old_bs->drv->format_name,
1360 NULL, -1, flags, &local_err, false);
1361 if (local_err) {
1362 error_propagate(errp, local_err);
1363 return;
1367 if (has_snapshot_node_name) {
1368 options = qdict_new();
1369 qdict_put(options, "node-name",
1370 qstring_from_str(snapshot_node_name));
1373 /* TODO Inherit bs->options or only take explicit options with an
1374 * extended QMP command? */
1375 assert(state->new_bs == NULL);
1376 ret = bdrv_open(&state->new_bs, new_image_file, NULL, options,
1377 flags | BDRV_O_NO_BACKING, drv, &local_err);
1378 /* We will manually add the backing_hd field to the bs later */
1379 if (ret != 0) {
1380 error_propagate(errp, local_err);
1384 static void external_snapshot_commit(BlkTransactionState *common)
1386 ExternalSnapshotState *state =
1387 DO_UPCAST(ExternalSnapshotState, common, common);
1389 /* This removes our old bs and adds the new bs */
1390 bdrv_append(state->new_bs, state->old_bs);
1391 /* We don't need (or want) to use the transactional
1392 * bdrv_reopen_multiple() across all the entries at once, because we
1393 * don't want to abort all of them if one of them fails the reopen */
1394 bdrv_reopen(state->new_bs, state->new_bs->open_flags & ~BDRV_O_RDWR,
1395 NULL);
1398 static void external_snapshot_abort(BlkTransactionState *common)
1400 ExternalSnapshotState *state =
1401 DO_UPCAST(ExternalSnapshotState, common, common);
1402 if (state->new_bs) {
1403 bdrv_unref(state->new_bs);
1407 typedef struct DriveBackupState {
1408 BlkTransactionState common;
1409 BlockDriverState *bs;
1410 BlockJob *job;
1411 } DriveBackupState;
1413 static void drive_backup_prepare(BlkTransactionState *common, Error **errp)
1415 DriveBackupState *state = DO_UPCAST(DriveBackupState, common, common);
1416 DriveBackup *backup;
1417 Error *local_err = NULL;
1419 assert(common->action->kind == TRANSACTION_ACTION_KIND_DRIVE_BACKUP);
1420 backup = common->action->drive_backup;
1422 qmp_drive_backup(backup->device, backup->target,
1423 backup->has_format, backup->format,
1424 backup->sync,
1425 backup->has_mode, backup->mode,
1426 backup->has_speed, backup->speed,
1427 backup->has_on_source_error, backup->on_source_error,
1428 backup->has_on_target_error, backup->on_target_error,
1429 &local_err);
1430 if (local_err) {
1431 error_propagate(errp, local_err);
1432 state->bs = NULL;
1433 state->job = NULL;
1434 return;
1437 state->bs = bdrv_find(backup->device);
1438 state->job = state->bs->job;
1441 static void drive_backup_abort(BlkTransactionState *common)
1443 DriveBackupState *state = DO_UPCAST(DriveBackupState, common, common);
1444 BlockDriverState *bs = state->bs;
1446 /* Only cancel if it's the job we started */
1447 if (bs && bs->job && bs->job == state->job) {
1448 block_job_cancel_sync(bs->job);
1452 static void abort_prepare(BlkTransactionState *common, Error **errp)
1454 error_setg(errp, "Transaction aborted using Abort action");
1457 static void abort_commit(BlkTransactionState *common)
1459 g_assert_not_reached(); /* this action never succeeds */
1462 static const BdrvActionOps actions[] = {
1463 [TRANSACTION_ACTION_KIND_BLOCKDEV_SNAPSHOT_SYNC] = {
1464 .instance_size = sizeof(ExternalSnapshotState),
1465 .prepare = external_snapshot_prepare,
1466 .commit = external_snapshot_commit,
1467 .abort = external_snapshot_abort,
1469 [TRANSACTION_ACTION_KIND_DRIVE_BACKUP] = {
1470 .instance_size = sizeof(DriveBackupState),
1471 .prepare = drive_backup_prepare,
1472 .abort = drive_backup_abort,
1474 [TRANSACTION_ACTION_KIND_ABORT] = {
1475 .instance_size = sizeof(BlkTransactionState),
1476 .prepare = abort_prepare,
1477 .commit = abort_commit,
1479 [TRANSACTION_ACTION_KIND_BLOCKDEV_SNAPSHOT_INTERNAL_SYNC] = {
1480 .instance_size = sizeof(InternalSnapshotState),
1481 .prepare = internal_snapshot_prepare,
1482 .abort = internal_snapshot_abort,
1487 * 'Atomic' group snapshots. The snapshots are taken as a set, and if any fail
1488 * then we do not pivot any of the devices in the group, and abandon the
1489 * snapshots
1491 void qmp_transaction(TransactionActionList *dev_list, Error **errp)
1493 TransactionActionList *dev_entry = dev_list;
1494 BlkTransactionState *state, *next;
1495 Error *local_err = NULL;
1497 QSIMPLEQ_HEAD(snap_bdrv_states, BlkTransactionState) snap_bdrv_states;
1498 QSIMPLEQ_INIT(&snap_bdrv_states);
1500 /* drain all i/o before any snapshots */
1501 bdrv_drain_all();
1503 /* We don't do anything in this loop that commits us to the snapshot */
1504 while (NULL != dev_entry) {
1505 TransactionAction *dev_info = NULL;
1506 const BdrvActionOps *ops;
1508 dev_info = dev_entry->value;
1509 dev_entry = dev_entry->next;
1511 assert(dev_info->kind < ARRAY_SIZE(actions));
1513 ops = &actions[dev_info->kind];
1514 assert(ops->instance_size > 0);
1516 state = g_malloc0(ops->instance_size);
1517 state->ops = ops;
1518 state->action = dev_info;
1519 QSIMPLEQ_INSERT_TAIL(&snap_bdrv_states, state, entry);
1521 state->ops->prepare(state, &local_err);
1522 if (local_err) {
1523 error_propagate(errp, local_err);
1524 goto delete_and_fail;
1528 QSIMPLEQ_FOREACH(state, &snap_bdrv_states, entry) {
1529 if (state->ops->commit) {
1530 state->ops->commit(state);
1534 /* success */
1535 goto exit;
1537 delete_and_fail:
1539 * failure, and it is all-or-none; abandon each new bs, and keep using
1540 * the original bs for all images
1542 QSIMPLEQ_FOREACH(state, &snap_bdrv_states, entry) {
1543 if (state->ops->abort) {
1544 state->ops->abort(state);
1547 exit:
1548 QSIMPLEQ_FOREACH_SAFE(state, &snap_bdrv_states, entry, next) {
1549 if (state->ops->clean) {
1550 state->ops->clean(state);
1552 g_free(state);
1557 static void eject_device(BlockDriverState *bs, int force, Error **errp)
1559 if (bdrv_op_is_blocked(bs, BLOCK_OP_TYPE_EJECT, errp)) {
1560 return;
1562 if (!bdrv_dev_has_removable_media(bs)) {
1563 error_setg(errp, "Device '%s' is not removable",
1564 bdrv_get_device_name(bs));
1565 return;
1568 if (bdrv_dev_is_medium_locked(bs) && !bdrv_dev_is_tray_open(bs)) {
1569 bdrv_dev_eject_request(bs, force);
1570 if (!force) {
1571 error_setg(errp, "Device '%s' is locked",
1572 bdrv_get_device_name(bs));
1573 return;
1577 bdrv_close(bs);
1580 void qmp_eject(const char *device, bool has_force, bool force, Error **errp)
1582 BlockDriverState *bs;
1584 bs = bdrv_find(device);
1585 if (!bs) {
1586 error_set(errp, QERR_DEVICE_NOT_FOUND, device);
1587 return;
1590 eject_device(bs, force, errp);
1593 void qmp_block_passwd(bool has_device, const char *device,
1594 bool has_node_name, const char *node_name,
1595 const char *password, Error **errp)
1597 Error *local_err = NULL;
1598 BlockDriverState *bs;
1599 int err;
1601 bs = bdrv_lookup_bs(has_device ? device : NULL,
1602 has_node_name ? node_name : NULL,
1603 &local_err);
1604 if (local_err) {
1605 error_propagate(errp, local_err);
1606 return;
1609 err = bdrv_set_key(bs, password);
1610 if (err == -EINVAL) {
1611 error_set(errp, QERR_DEVICE_NOT_ENCRYPTED, bdrv_get_device_name(bs));
1612 return;
1613 } else if (err < 0) {
1614 error_set(errp, QERR_INVALID_PASSWORD);
1615 return;
1619 static void qmp_bdrv_open_encrypted(BlockDriverState *bs, const char *filename,
1620 int bdrv_flags, BlockDriver *drv,
1621 const char *password, Error **errp)
1623 Error *local_err = NULL;
1624 int ret;
1626 ret = bdrv_open(&bs, filename, NULL, NULL, bdrv_flags, drv, &local_err);
1627 if (ret < 0) {
1628 error_propagate(errp, local_err);
1629 return;
1632 if (bdrv_key_required(bs)) {
1633 if (password) {
1634 if (bdrv_set_key(bs, password) < 0) {
1635 error_set(errp, QERR_INVALID_PASSWORD);
1637 } else {
1638 error_set(errp, QERR_DEVICE_ENCRYPTED, bdrv_get_device_name(bs),
1639 bdrv_get_encrypted_filename(bs));
1641 } else if (password) {
1642 error_set(errp, QERR_DEVICE_NOT_ENCRYPTED, bdrv_get_device_name(bs));
1646 void qmp_change_blockdev(const char *device, const char *filename,
1647 const char *format, Error **errp)
1649 BlockDriverState *bs;
1650 BlockDriver *drv = NULL;
1651 int bdrv_flags;
1652 Error *err = NULL;
1654 bs = bdrv_find(device);
1655 if (!bs) {
1656 error_set(errp, QERR_DEVICE_NOT_FOUND, device);
1657 return;
1660 if (format) {
1661 drv = bdrv_find_whitelisted_format(format, bs->read_only);
1662 if (!drv) {
1663 error_set(errp, QERR_INVALID_BLOCK_FORMAT, format);
1664 return;
1668 eject_device(bs, 0, &err);
1669 if (err) {
1670 error_propagate(errp, err);
1671 return;
1674 bdrv_flags = bdrv_is_read_only(bs) ? 0 : BDRV_O_RDWR;
1675 bdrv_flags |= bdrv_is_snapshot(bs) ? BDRV_O_SNAPSHOT : 0;
1677 qmp_bdrv_open_encrypted(bs, filename, bdrv_flags, drv, NULL, errp);
1680 /* throttling disk I/O limits */
1681 void qmp_block_set_io_throttle(const char *device, int64_t bps, int64_t bps_rd,
1682 int64_t bps_wr,
1683 int64_t iops,
1684 int64_t iops_rd,
1685 int64_t iops_wr,
1686 bool has_bps_max,
1687 int64_t bps_max,
1688 bool has_bps_rd_max,
1689 int64_t bps_rd_max,
1690 bool has_bps_wr_max,
1691 int64_t bps_wr_max,
1692 bool has_iops_max,
1693 int64_t iops_max,
1694 bool has_iops_rd_max,
1695 int64_t iops_rd_max,
1696 bool has_iops_wr_max,
1697 int64_t iops_wr_max,
1698 bool has_iops_size,
1699 int64_t iops_size, Error **errp)
1701 ThrottleConfig cfg;
1702 BlockDriverState *bs;
1703 AioContext *aio_context;
1705 bs = bdrv_find(device);
1706 if (!bs) {
1707 error_set(errp, QERR_DEVICE_NOT_FOUND, device);
1708 return;
1711 memset(&cfg, 0, sizeof(cfg));
1712 cfg.buckets[THROTTLE_BPS_TOTAL].avg = bps;
1713 cfg.buckets[THROTTLE_BPS_READ].avg = bps_rd;
1714 cfg.buckets[THROTTLE_BPS_WRITE].avg = bps_wr;
1716 cfg.buckets[THROTTLE_OPS_TOTAL].avg = iops;
1717 cfg.buckets[THROTTLE_OPS_READ].avg = iops_rd;
1718 cfg.buckets[THROTTLE_OPS_WRITE].avg = iops_wr;
1720 if (has_bps_max) {
1721 cfg.buckets[THROTTLE_BPS_TOTAL].max = bps_max;
1723 if (has_bps_rd_max) {
1724 cfg.buckets[THROTTLE_BPS_READ].max = bps_rd_max;
1726 if (has_bps_wr_max) {
1727 cfg.buckets[THROTTLE_BPS_WRITE].max = bps_wr_max;
1729 if (has_iops_max) {
1730 cfg.buckets[THROTTLE_OPS_TOTAL].max = iops_max;
1732 if (has_iops_rd_max) {
1733 cfg.buckets[THROTTLE_OPS_READ].max = iops_rd_max;
1735 if (has_iops_wr_max) {
1736 cfg.buckets[THROTTLE_OPS_WRITE].max = iops_wr_max;
1739 if (has_iops_size) {
1740 cfg.op_size = iops_size;
1743 if (!check_throttle_config(&cfg, errp)) {
1744 return;
1747 aio_context = bdrv_get_aio_context(bs);
1748 aio_context_acquire(aio_context);
1750 if (!bs->io_limits_enabled && throttle_enabled(&cfg)) {
1751 bdrv_io_limits_enable(bs);
1752 } else if (bs->io_limits_enabled && !throttle_enabled(&cfg)) {
1753 bdrv_io_limits_disable(bs);
1756 if (bs->io_limits_enabled) {
1757 bdrv_set_io_limits(bs, &cfg);
1760 aio_context_release(aio_context);
1763 int do_drive_del(Monitor *mon, const QDict *qdict, QObject **ret_data)
1765 const char *id = qdict_get_str(qdict, "id");
1766 BlockDriverState *bs;
1767 DriveInfo *dinfo;
1768 AioContext *aio_context;
1769 Error *local_err = NULL;
1771 bs = bdrv_find(id);
1772 if (!bs) {
1773 error_report("Device '%s' not found", id);
1774 return -1;
1777 dinfo = drive_get_by_blockdev(bs);
1778 if (dinfo && !dinfo->enable_auto_del) {
1779 error_report("Deleting device added with blockdev-add"
1780 " is not supported");
1781 return -1;
1784 aio_context = bdrv_get_aio_context(bs);
1785 aio_context_acquire(aio_context);
1787 if (bdrv_op_is_blocked(bs, BLOCK_OP_TYPE_DRIVE_DEL, &local_err)) {
1788 error_report("%s", error_get_pretty(local_err));
1789 error_free(local_err);
1790 aio_context_release(aio_context);
1791 return -1;
1794 /* quiesce block driver; prevent further io */
1795 bdrv_drain_all();
1796 bdrv_flush(bs);
1797 bdrv_close(bs);
1799 /* if we have a device attached to this BlockDriverState
1800 * then we need to make the drive anonymous until the device
1801 * can be removed. If this is a drive with no device backing
1802 * then we can just get rid of the block driver state right here.
1804 if (bdrv_get_attached_dev(bs)) {
1805 bdrv_make_anon(bs);
1807 /* Further I/O must not pause the guest */
1808 bdrv_set_on_error(bs, BLOCKDEV_ON_ERROR_REPORT,
1809 BLOCKDEV_ON_ERROR_REPORT);
1810 } else {
1811 drive_del(dinfo);
1814 aio_context_release(aio_context);
1815 return 0;
1818 void qmp_block_resize(bool has_device, const char *device,
1819 bool has_node_name, const char *node_name,
1820 int64_t size, Error **errp)
1822 Error *local_err = NULL;
1823 BlockDriverState *bs;
1824 AioContext *aio_context;
1825 int ret;
1827 bs = bdrv_lookup_bs(has_device ? device : NULL,
1828 has_node_name ? node_name : NULL,
1829 &local_err);
1830 if (local_err) {
1831 error_propagate(errp, local_err);
1832 return;
1835 aio_context = bdrv_get_aio_context(bs);
1836 aio_context_acquire(aio_context);
1838 if (!bdrv_is_first_non_filter(bs)) {
1839 error_set(errp, QERR_FEATURE_DISABLED, "resize");
1840 goto out;
1843 if (size < 0) {
1844 error_set(errp, QERR_INVALID_PARAMETER_VALUE, "size", "a >0 size");
1845 goto out;
1848 if (bdrv_op_is_blocked(bs, BLOCK_OP_TYPE_RESIZE, NULL)) {
1849 error_set(errp, QERR_DEVICE_IN_USE, device);
1850 goto out;
1853 /* complete all in-flight operations before resizing the device */
1854 bdrv_drain_all();
1856 ret = bdrv_truncate(bs, size);
1857 switch (ret) {
1858 case 0:
1859 break;
1860 case -ENOMEDIUM:
1861 error_set(errp, QERR_DEVICE_HAS_NO_MEDIUM, device);
1862 break;
1863 case -ENOTSUP:
1864 error_set(errp, QERR_UNSUPPORTED);
1865 break;
1866 case -EACCES:
1867 error_set(errp, QERR_DEVICE_IS_READ_ONLY, device);
1868 break;
1869 case -EBUSY:
1870 error_set(errp, QERR_DEVICE_IN_USE, device);
1871 break;
1872 default:
1873 error_setg_errno(errp, -ret, "Could not resize");
1874 break;
1877 out:
1878 aio_context_release(aio_context);
1881 static void block_job_cb(void *opaque, int ret)
1883 BlockDriverState *bs = opaque;
1884 const char *msg = NULL;
1886 trace_block_job_cb(bs, bs->job, ret);
1888 assert(bs->job);
1890 if (ret < 0) {
1891 msg = strerror(-ret);
1894 if (block_job_is_cancelled(bs->job)) {
1895 block_job_event_cancelled(bs->job);
1896 } else {
1897 block_job_event_completed(bs->job, msg);
1900 bdrv_put_ref_bh_schedule(bs);
1903 void qmp_block_stream(const char *device,
1904 bool has_base, const char *base,
1905 bool has_backing_file, const char *backing_file,
1906 bool has_speed, int64_t speed,
1907 bool has_on_error, BlockdevOnError on_error,
1908 Error **errp)
1910 BlockDriverState *bs;
1911 BlockDriverState *base_bs = NULL;
1912 Error *local_err = NULL;
1913 const char *base_name = NULL;
1915 if (!has_on_error) {
1916 on_error = BLOCKDEV_ON_ERROR_REPORT;
1919 bs = bdrv_find(device);
1920 if (!bs) {
1921 error_set(errp, QERR_DEVICE_NOT_FOUND, device);
1922 return;
1925 if (bdrv_op_is_blocked(bs, BLOCK_OP_TYPE_STREAM, errp)) {
1926 return;
1929 if (has_base) {
1930 base_bs = bdrv_find_backing_image(bs, base);
1931 if (base_bs == NULL) {
1932 error_set(errp, QERR_BASE_NOT_FOUND, base);
1933 return;
1935 base_name = base;
1938 /* if we are streaming the entire chain, the result will have no backing
1939 * file, and specifying one is therefore an error */
1940 if (base_bs == NULL && has_backing_file) {
1941 error_setg(errp, "backing file specified, but streaming the "
1942 "entire chain");
1943 return;
1946 /* backing_file string overrides base bs filename */
1947 base_name = has_backing_file ? backing_file : base_name;
1949 stream_start(bs, base_bs, base_name, has_speed ? speed : 0,
1950 on_error, block_job_cb, bs, &local_err);
1951 if (local_err) {
1952 error_propagate(errp, local_err);
1953 return;
1956 trace_qmp_block_stream(bs, bs->job);
1959 void qmp_block_commit(const char *device,
1960 bool has_base, const char *base,
1961 bool has_top, const char *top,
1962 bool has_backing_file, const char *backing_file,
1963 bool has_speed, int64_t speed,
1964 Error **errp)
1966 BlockDriverState *bs;
1967 BlockDriverState *base_bs, *top_bs;
1968 Error *local_err = NULL;
1969 /* This will be part of the QMP command, if/when the
1970 * BlockdevOnError change for blkmirror makes it in
1972 BlockdevOnError on_error = BLOCKDEV_ON_ERROR_REPORT;
1974 if (!has_speed) {
1975 speed = 0;
1978 /* drain all i/o before commits */
1979 bdrv_drain_all();
1981 /* Important Note:
1982 * libvirt relies on the DeviceNotFound error class in order to probe for
1983 * live commit feature versions; for this to work, we must make sure to
1984 * perform the device lookup before any generic errors that may occur in a
1985 * scenario in which all optional arguments are omitted. */
1986 bs = bdrv_find(device);
1987 if (!bs) {
1988 error_set(errp, QERR_DEVICE_NOT_FOUND, device);
1989 return;
1992 if (bdrv_op_is_blocked(bs, BLOCK_OP_TYPE_COMMIT, errp)) {
1993 return;
1996 /* default top_bs is the active layer */
1997 top_bs = bs;
1999 if (has_top && top) {
2000 if (strcmp(bs->filename, top) != 0) {
2001 top_bs = bdrv_find_backing_image(bs, top);
2005 if (top_bs == NULL) {
2006 error_setg(errp, "Top image file %s not found", top ? top : "NULL");
2007 return;
2010 if (has_base && base) {
2011 base_bs = bdrv_find_backing_image(top_bs, base);
2012 } else {
2013 base_bs = bdrv_find_base(top_bs);
2016 if (base_bs == NULL) {
2017 error_set(errp, QERR_BASE_NOT_FOUND, base ? base : "NULL");
2018 return;
2021 /* Do not allow attempts to commit an image into itself */
2022 if (top_bs == base_bs) {
2023 error_setg(errp, "cannot commit an image into itself");
2024 return;
2027 if (top_bs == bs) {
2028 if (has_backing_file) {
2029 error_setg(errp, "'backing-file' specified,"
2030 " but 'top' is the active layer");
2031 return;
2033 commit_active_start(bs, base_bs, speed, on_error, block_job_cb,
2034 bs, &local_err);
2035 } else {
2036 commit_start(bs, base_bs, top_bs, speed, on_error, block_job_cb, bs,
2037 has_backing_file ? backing_file : NULL, &local_err);
2039 if (local_err != NULL) {
2040 error_propagate(errp, local_err);
2041 return;
2045 void qmp_drive_backup(const char *device, const char *target,
2046 bool has_format, const char *format,
2047 enum MirrorSyncMode sync,
2048 bool has_mode, enum NewImageMode mode,
2049 bool has_speed, int64_t speed,
2050 bool has_on_source_error, BlockdevOnError on_source_error,
2051 bool has_on_target_error, BlockdevOnError on_target_error,
2052 Error **errp)
2054 BlockDriverState *bs;
2055 BlockDriverState *target_bs;
2056 BlockDriverState *source = NULL;
2057 BlockDriver *drv = NULL;
2058 Error *local_err = NULL;
2059 int flags;
2060 int64_t size;
2061 int ret;
2063 if (!has_speed) {
2064 speed = 0;
2066 if (!has_on_source_error) {
2067 on_source_error = BLOCKDEV_ON_ERROR_REPORT;
2069 if (!has_on_target_error) {
2070 on_target_error = BLOCKDEV_ON_ERROR_REPORT;
2072 if (!has_mode) {
2073 mode = NEW_IMAGE_MODE_ABSOLUTE_PATHS;
2076 bs = bdrv_find(device);
2077 if (!bs) {
2078 error_set(errp, QERR_DEVICE_NOT_FOUND, device);
2079 return;
2082 if (!bdrv_is_inserted(bs)) {
2083 error_set(errp, QERR_DEVICE_HAS_NO_MEDIUM, device);
2084 return;
2087 if (!has_format) {
2088 format = mode == NEW_IMAGE_MODE_EXISTING ? NULL : bs->drv->format_name;
2090 if (format) {
2091 drv = bdrv_find_format(format);
2092 if (!drv) {
2093 error_set(errp, QERR_INVALID_BLOCK_FORMAT, format);
2094 return;
2098 if (bdrv_op_is_blocked(bs, BLOCK_OP_TYPE_BACKUP_SOURCE, errp)) {
2099 return;
2102 flags = bs->open_flags | BDRV_O_RDWR;
2104 /* See if we have a backing HD we can use to create our new image
2105 * on top of. */
2106 if (sync == MIRROR_SYNC_MODE_TOP) {
2107 source = bs->backing_hd;
2108 if (!source) {
2109 sync = MIRROR_SYNC_MODE_FULL;
2112 if (sync == MIRROR_SYNC_MODE_NONE) {
2113 source = bs;
2116 size = bdrv_getlength(bs);
2117 if (size < 0) {
2118 error_setg_errno(errp, -size, "bdrv_getlength failed");
2119 return;
2122 if (mode != NEW_IMAGE_MODE_EXISTING) {
2123 assert(format && drv);
2124 if (source) {
2125 bdrv_img_create(target, format, source->filename,
2126 source->drv->format_name, NULL,
2127 size, flags, &local_err, false);
2128 } else {
2129 bdrv_img_create(target, format, NULL, NULL, NULL,
2130 size, flags, &local_err, false);
2134 if (local_err) {
2135 error_propagate(errp, local_err);
2136 return;
2139 target_bs = NULL;
2140 ret = bdrv_open(&target_bs, target, NULL, NULL, flags, drv, &local_err);
2141 if (ret < 0) {
2142 error_propagate(errp, local_err);
2143 return;
2146 backup_start(bs, target_bs, speed, sync, on_source_error, on_target_error,
2147 block_job_cb, bs, &local_err);
2148 if (local_err != NULL) {
2149 bdrv_unref(target_bs);
2150 error_propagate(errp, local_err);
2151 return;
2155 BlockDeviceInfoList *qmp_query_named_block_nodes(Error **errp)
2157 return bdrv_named_nodes_list();
2160 #define DEFAULT_MIRROR_BUF_SIZE (10 << 20)
2162 void qmp_drive_mirror(const char *device, const char *target,
2163 bool has_format, const char *format,
2164 bool has_node_name, const char *node_name,
2165 bool has_replaces, const char *replaces,
2166 enum MirrorSyncMode sync,
2167 bool has_mode, enum NewImageMode mode,
2168 bool has_speed, int64_t speed,
2169 bool has_granularity, uint32_t granularity,
2170 bool has_buf_size, int64_t buf_size,
2171 bool has_on_source_error, BlockdevOnError on_source_error,
2172 bool has_on_target_error, BlockdevOnError on_target_error,
2173 Error **errp)
2175 BlockDriverState *bs;
2176 BlockDriverState *source, *target_bs;
2177 BlockDriver *drv = NULL;
2178 Error *local_err = NULL;
2179 QDict *options = NULL;
2180 int flags;
2181 int64_t size;
2182 int ret;
2184 if (!has_speed) {
2185 speed = 0;
2187 if (!has_on_source_error) {
2188 on_source_error = BLOCKDEV_ON_ERROR_REPORT;
2190 if (!has_on_target_error) {
2191 on_target_error = BLOCKDEV_ON_ERROR_REPORT;
2193 if (!has_mode) {
2194 mode = NEW_IMAGE_MODE_ABSOLUTE_PATHS;
2196 if (!has_granularity) {
2197 granularity = 0;
2199 if (!has_buf_size) {
2200 buf_size = DEFAULT_MIRROR_BUF_SIZE;
2203 if (granularity != 0 && (granularity < 512 || granularity > 1048576 * 64)) {
2204 error_set(errp, QERR_INVALID_PARAMETER_VALUE, "granularity",
2205 "a value in range [512B, 64MB]");
2206 return;
2208 if (granularity & (granularity - 1)) {
2209 error_set(errp, QERR_INVALID_PARAMETER_VALUE, "granularity", "power of 2");
2210 return;
2213 bs = bdrv_find(device);
2214 if (!bs) {
2215 error_set(errp, QERR_DEVICE_NOT_FOUND, device);
2216 return;
2219 if (!bdrv_is_inserted(bs)) {
2220 error_set(errp, QERR_DEVICE_HAS_NO_MEDIUM, device);
2221 return;
2224 if (!has_format) {
2225 format = mode == NEW_IMAGE_MODE_EXISTING ? NULL : bs->drv->format_name;
2227 if (format) {
2228 drv = bdrv_find_format(format);
2229 if (!drv) {
2230 error_set(errp, QERR_INVALID_BLOCK_FORMAT, format);
2231 return;
2235 if (bdrv_op_is_blocked(bs, BLOCK_OP_TYPE_MIRROR, errp)) {
2236 return;
2239 flags = bs->open_flags | BDRV_O_RDWR;
2240 source = bs->backing_hd;
2241 if (!source && sync == MIRROR_SYNC_MODE_TOP) {
2242 sync = MIRROR_SYNC_MODE_FULL;
2244 if (sync == MIRROR_SYNC_MODE_NONE) {
2245 source = bs;
2248 size = bdrv_getlength(bs);
2249 if (size < 0) {
2250 error_setg_errno(errp, -size, "bdrv_getlength failed");
2251 return;
2254 if (has_replaces) {
2255 BlockDriverState *to_replace_bs;
2257 if (!has_node_name) {
2258 error_setg(errp, "a node-name must be provided when replacing a"
2259 " named node of the graph");
2260 return;
2263 to_replace_bs = check_to_replace_node(replaces, &local_err);
2265 if (!to_replace_bs) {
2266 error_propagate(errp, local_err);
2267 return;
2270 if (size != bdrv_getlength(to_replace_bs)) {
2271 error_setg(errp, "cannot replace image with a mirror image of "
2272 "different size");
2273 return;
2277 if ((sync == MIRROR_SYNC_MODE_FULL || !source)
2278 && mode != NEW_IMAGE_MODE_EXISTING)
2280 /* create new image w/o backing file */
2281 assert(format && drv);
2282 bdrv_img_create(target, format,
2283 NULL, NULL, NULL, size, flags, &local_err, false);
2284 } else {
2285 switch (mode) {
2286 case NEW_IMAGE_MODE_EXISTING:
2287 break;
2288 case NEW_IMAGE_MODE_ABSOLUTE_PATHS:
2289 /* create new image with backing file */
2290 bdrv_img_create(target, format,
2291 source->filename,
2292 source->drv->format_name,
2293 NULL, size, flags, &local_err, false);
2294 break;
2295 default:
2296 abort();
2300 if (local_err) {
2301 error_propagate(errp, local_err);
2302 return;
2305 if (has_node_name) {
2306 options = qdict_new();
2307 qdict_put(options, "node-name", qstring_from_str(node_name));
2310 /* Mirroring takes care of copy-on-write using the source's backing
2311 * file.
2313 target_bs = NULL;
2314 ret = bdrv_open(&target_bs, target, NULL, options,
2315 flags | BDRV_O_NO_BACKING, drv, &local_err);
2316 if (ret < 0) {
2317 error_propagate(errp, local_err);
2318 return;
2321 /* pass the node name to replace to mirror start since it's loose coupling
2322 * and will allow to check whether the node still exist at mirror completion
2324 mirror_start(bs, target_bs,
2325 has_replaces ? replaces : NULL,
2326 speed, granularity, buf_size, sync,
2327 on_source_error, on_target_error,
2328 block_job_cb, bs, &local_err);
2329 if (local_err != NULL) {
2330 bdrv_unref(target_bs);
2331 error_propagate(errp, local_err);
2332 return;
2336 static BlockJob *find_block_job(const char *device)
2338 BlockDriverState *bs;
2340 bs = bdrv_find(device);
2341 if (!bs || !bs->job) {
2342 return NULL;
2344 return bs->job;
2347 void qmp_block_job_set_speed(const char *device, int64_t speed, Error **errp)
2349 BlockJob *job = find_block_job(device);
2351 if (!job) {
2352 error_set(errp, QERR_BLOCK_JOB_NOT_ACTIVE, device);
2353 return;
2356 block_job_set_speed(job, speed, errp);
2359 void qmp_block_job_cancel(const char *device,
2360 bool has_force, bool force, Error **errp)
2362 BlockJob *job = find_block_job(device);
2364 if (!has_force) {
2365 force = false;
2368 if (!job) {
2369 error_set(errp, QERR_BLOCK_JOB_NOT_ACTIVE, device);
2370 return;
2372 if (job->paused && !force) {
2373 error_setg(errp, "The block job for device '%s' is currently paused",
2374 device);
2375 return;
2378 trace_qmp_block_job_cancel(job);
2379 block_job_cancel(job);
2382 void qmp_block_job_pause(const char *device, Error **errp)
2384 BlockJob *job = find_block_job(device);
2386 if (!job) {
2387 error_set(errp, QERR_BLOCK_JOB_NOT_ACTIVE, device);
2388 return;
2391 trace_qmp_block_job_pause(job);
2392 block_job_pause(job);
2395 void qmp_block_job_resume(const char *device, Error **errp)
2397 BlockJob *job = find_block_job(device);
2399 if (!job) {
2400 error_set(errp, QERR_BLOCK_JOB_NOT_ACTIVE, device);
2401 return;
2404 trace_qmp_block_job_resume(job);
2405 block_job_resume(job);
2408 void qmp_block_job_complete(const char *device, Error **errp)
2410 BlockJob *job = find_block_job(device);
2412 if (!job) {
2413 error_set(errp, QERR_BLOCK_JOB_NOT_ACTIVE, device);
2414 return;
2417 trace_qmp_block_job_complete(job);
2418 block_job_complete(job, errp);
2421 void qmp_change_backing_file(const char *device,
2422 const char *image_node_name,
2423 const char *backing_file,
2424 Error **errp)
2426 BlockDriverState *bs = NULL;
2427 BlockDriverState *image_bs = NULL;
2428 Error *local_err = NULL;
2429 bool ro;
2430 int open_flags;
2431 int ret;
2433 /* find the top layer BDS of the chain */
2434 bs = bdrv_find(device);
2435 if (!bs) {
2436 error_set(errp, QERR_DEVICE_NOT_FOUND, device);
2437 return;
2440 image_bs = bdrv_lookup_bs(NULL, image_node_name, &local_err);
2441 if (local_err) {
2442 error_propagate(errp, local_err);
2443 return;
2446 if (!image_bs) {
2447 error_setg(errp, "image file not found");
2448 return;
2451 if (bdrv_find_base(image_bs) == image_bs) {
2452 error_setg(errp, "not allowing backing file change on an image "
2453 "without a backing file");
2454 return;
2457 /* even though we are not necessarily operating on bs, we need it to
2458 * determine if block ops are currently prohibited on the chain */
2459 if (bdrv_op_is_blocked(bs, BLOCK_OP_TYPE_CHANGE, errp)) {
2460 return;
2463 /* final sanity check */
2464 if (!bdrv_chain_contains(bs, image_bs)) {
2465 error_setg(errp, "'%s' and image file are not in the same chain",
2466 device);
2467 return;
2470 /* if not r/w, reopen to make r/w */
2471 open_flags = image_bs->open_flags;
2472 ro = bdrv_is_read_only(image_bs);
2474 if (ro) {
2475 bdrv_reopen(image_bs, open_flags | BDRV_O_RDWR, &local_err);
2476 if (local_err) {
2477 error_propagate(errp, local_err);
2478 return;
2482 ret = bdrv_change_backing_file(image_bs, backing_file,
2483 image_bs->drv ? image_bs->drv->format_name : "");
2485 if (ret < 0) {
2486 error_setg_errno(errp, -ret, "Could not change backing file to '%s'",
2487 backing_file);
2488 /* don't exit here, so we can try to restore open flags if
2489 * appropriate */
2492 if (ro) {
2493 bdrv_reopen(image_bs, open_flags, &local_err);
2494 if (local_err) {
2495 error_propagate(errp, local_err); /* will preserve prior errp */
2500 void qmp_blockdev_add(BlockdevOptions *options, Error **errp)
2502 QmpOutputVisitor *ov = qmp_output_visitor_new();
2503 DriveInfo *dinfo;
2504 QObject *obj;
2505 QDict *qdict;
2506 Error *local_err = NULL;
2508 /* Require an ID in the top level */
2509 if (!options->has_id) {
2510 error_setg(errp, "Block device needs an ID");
2511 goto fail;
2514 /* TODO Sort it out in raw-posix and drive_new(): Reject aio=native with
2515 * cache.direct=false instead of silently switching to aio=threads, except
2516 * when called from drive_new().
2518 * For now, simply forbidding the combination for all drivers will do. */
2519 if (options->has_aio && options->aio == BLOCKDEV_AIO_OPTIONS_NATIVE) {
2520 bool direct = options->has_cache &&
2521 options->cache->has_direct &&
2522 options->cache->direct;
2523 if (!direct) {
2524 error_setg(errp, "aio=native requires cache.direct=true");
2525 goto fail;
2529 visit_type_BlockdevOptions(qmp_output_get_visitor(ov),
2530 &options, NULL, &local_err);
2531 if (local_err) {
2532 error_propagate(errp, local_err);
2533 goto fail;
2536 obj = qmp_output_get_qobject(ov);
2537 qdict = qobject_to_qdict(obj);
2539 qdict_flatten(qdict);
2541 dinfo = blockdev_init(NULL, qdict, &local_err);
2542 if (local_err) {
2543 error_propagate(errp, local_err);
2544 goto fail;
2547 if (bdrv_key_required(dinfo->bdrv)) {
2548 drive_del(dinfo);
2549 error_setg(errp, "blockdev-add doesn't support encrypted devices");
2550 goto fail;
2553 fail:
2554 qmp_output_visitor_cleanup(ov);
2557 static void do_qmp_query_block_jobs_one(void *opaque, BlockDriverState *bs)
2559 BlockJobInfoList **prev = opaque;
2560 BlockJob *job = bs->job;
2562 if (job) {
2563 BlockJobInfoList *elem = g_new0(BlockJobInfoList, 1);
2564 elem->value = block_job_query(bs->job);
2565 (*prev)->next = elem;
2566 *prev = elem;
2570 BlockJobInfoList *qmp_query_block_jobs(Error **errp)
2572 /* Dummy is a fake list element for holding the head pointer */
2573 BlockJobInfoList dummy = {};
2574 BlockJobInfoList *prev = &dummy;
2575 bdrv_iterate(do_qmp_query_block_jobs_one, &prev);
2576 return dummy.next;
2579 QemuOptsList qemu_common_drive_opts = {
2580 .name = "drive",
2581 .head = QTAILQ_HEAD_INITIALIZER(qemu_common_drive_opts.head),
2582 .desc = {
2584 .name = "snapshot",
2585 .type = QEMU_OPT_BOOL,
2586 .help = "enable/disable snapshot mode",
2588 .name = "discard",
2589 .type = QEMU_OPT_STRING,
2590 .help = "discard operation (ignore/off, unmap/on)",
2592 .name = "cache.writeback",
2593 .type = QEMU_OPT_BOOL,
2594 .help = "enables writeback mode for any caches",
2596 .name = "cache.direct",
2597 .type = QEMU_OPT_BOOL,
2598 .help = "enables use of O_DIRECT (bypass the host page cache)",
2600 .name = "cache.no-flush",
2601 .type = QEMU_OPT_BOOL,
2602 .help = "ignore any flush requests for the device",
2604 .name = "aio",
2605 .type = QEMU_OPT_STRING,
2606 .help = "host AIO implementation (threads, native)",
2608 .name = "format",
2609 .type = QEMU_OPT_STRING,
2610 .help = "disk format (raw, qcow2, ...)",
2612 .name = "rerror",
2613 .type = QEMU_OPT_STRING,
2614 .help = "read error action",
2616 .name = "werror",
2617 .type = QEMU_OPT_STRING,
2618 .help = "write error action",
2620 .name = "read-only",
2621 .type = QEMU_OPT_BOOL,
2622 .help = "open drive file as read-only",
2624 .name = "throttling.iops-total",
2625 .type = QEMU_OPT_NUMBER,
2626 .help = "limit total I/O operations per second",
2628 .name = "throttling.iops-read",
2629 .type = QEMU_OPT_NUMBER,
2630 .help = "limit read operations per second",
2632 .name = "throttling.iops-write",
2633 .type = QEMU_OPT_NUMBER,
2634 .help = "limit write operations per second",
2636 .name = "throttling.bps-total",
2637 .type = QEMU_OPT_NUMBER,
2638 .help = "limit total bytes per second",
2640 .name = "throttling.bps-read",
2641 .type = QEMU_OPT_NUMBER,
2642 .help = "limit read bytes per second",
2644 .name = "throttling.bps-write",
2645 .type = QEMU_OPT_NUMBER,
2646 .help = "limit write bytes per second",
2648 .name = "throttling.iops-total-max",
2649 .type = QEMU_OPT_NUMBER,
2650 .help = "I/O operations burst",
2652 .name = "throttling.iops-read-max",
2653 .type = QEMU_OPT_NUMBER,
2654 .help = "I/O operations read burst",
2656 .name = "throttling.iops-write-max",
2657 .type = QEMU_OPT_NUMBER,
2658 .help = "I/O operations write burst",
2660 .name = "throttling.bps-total-max",
2661 .type = QEMU_OPT_NUMBER,
2662 .help = "total bytes burst",
2664 .name = "throttling.bps-read-max",
2665 .type = QEMU_OPT_NUMBER,
2666 .help = "total bytes read burst",
2668 .name = "throttling.bps-write-max",
2669 .type = QEMU_OPT_NUMBER,
2670 .help = "total bytes write burst",
2672 .name = "throttling.iops-size",
2673 .type = QEMU_OPT_NUMBER,
2674 .help = "when limiting by iops max size of an I/O in bytes",
2676 .name = "copy-on-read",
2677 .type = QEMU_OPT_BOOL,
2678 .help = "copy read data from backing file into image file",
2680 .name = "detect-zeroes",
2681 .type = QEMU_OPT_STRING,
2682 .help = "try to optimize zero writes (off, on, unmap)",
2684 { /* end of list */ }
2688 QemuOptsList qemu_drive_opts = {
2689 .name = "drive",
2690 .head = QTAILQ_HEAD_INITIALIZER(qemu_drive_opts.head),
2691 .desc = {
2693 * no elements => accept any params
2694 * validation will happen later
2696 { /* end of list */ }