block: Merge BlockBackend and BlockDriverState name spaces
[qemu-kvm.git] / blockdev.c
blobc99df8f3f19ebdbc35260673c27b5134312e1c2c
1 /*
2 * QEMU host block devices
4 * Copyright (c) 2003-2008 Fabrice Bellard
6 * This work is licensed under the terms of the GNU GPL, version 2 or
7 * later. See the COPYING file in the top-level directory.
9 * This file incorporates work covered by the following copyright and
10 * permission notice:
12 * Copyright (c) 2003-2008 Fabrice Bellard
14 * Permission is hereby granted, free of charge, to any person obtaining a copy
15 * of this software and associated documentation files (the "Software"), to deal
16 * in the Software without restriction, including without limitation the rights
17 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
18 * copies of the Software, and to permit persons to whom the Software is
19 * furnished to do so, subject to the following conditions:
21 * The above copyright notice and this permission notice shall be included in
22 * all copies or substantial portions of the Software.
24 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
25 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
26 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
27 * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
28 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
29 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
30 * THE SOFTWARE.
33 #include "sysemu/block-backend.h"
34 #include "sysemu/blockdev.h"
35 #include "hw/block/block.h"
36 #include "block/blockjob.h"
37 #include "monitor/monitor.h"
38 #include "qemu/option.h"
39 #include "qemu/config-file.h"
40 #include "qapi/qmp/types.h"
41 #include "qapi-visit.h"
42 #include "qapi/qmp-output-visitor.h"
43 #include "qapi/util.h"
44 #include "sysemu/sysemu.h"
45 #include "block/block_int.h"
46 #include "qmp-commands.h"
47 #include "trace.h"
48 #include "sysemu/arch_init.h"
50 static const char *const if_name[IF_COUNT] = {
51 [IF_NONE] = "none",
52 [IF_IDE] = "ide",
53 [IF_SCSI] = "scsi",
54 [IF_FLOPPY] = "floppy",
55 [IF_PFLASH] = "pflash",
56 [IF_MTD] = "mtd",
57 [IF_SD] = "sd",
58 [IF_VIRTIO] = "virtio",
59 [IF_XEN] = "xen",
62 static int if_max_devs[IF_COUNT] = {
64 * Do not change these numbers! They govern how drive option
65 * index maps to unit and bus. That mapping is ABI.
67 * All controllers used to imlement if=T drives need to support
68 * if_max_devs[T] units, for any T with if_max_devs[T] != 0.
69 * Otherwise, some index values map to "impossible" bus, unit
70 * values.
72 * For instance, if you change [IF_SCSI] to 255, -drive
73 * if=scsi,index=12 no longer means bus=1,unit=5, but
74 * bus=0,unit=12. With an lsi53c895a controller (7 units max),
75 * the drive can't be set up. Regression.
77 [IF_IDE] = 2,
78 [IF_SCSI] = 7,
81 /**
82 * Boards may call this to offer board-by-board overrides
83 * of the default, global values.
85 void override_max_devs(BlockInterfaceType type, int max_devs)
87 BlockBackend *blk;
88 DriveInfo *dinfo;
90 if (max_devs <= 0) {
91 return;
94 for (blk = blk_next(NULL); blk; blk = blk_next(blk)) {
95 dinfo = blk_legacy_dinfo(blk);
96 if (dinfo->type == type) {
97 fprintf(stderr, "Cannot override units-per-bus property of"
98 " the %s interface, because a drive of that type has"
99 " already been added.\n", if_name[type]);
100 g_assert_not_reached();
104 if_max_devs[type] = max_devs;
108 * We automatically delete the drive when a device using it gets
109 * unplugged. Questionable feature, but we can't just drop it.
110 * Device models call blockdev_mark_auto_del() to schedule the
111 * automatic deletion, and generic qdev code calls blockdev_auto_del()
112 * when deletion is actually safe.
114 void blockdev_mark_auto_del(BlockDriverState *bs)
116 BlockBackend *blk = bs->blk;
117 DriveInfo *dinfo = blk_legacy_dinfo(blk);
119 if (dinfo && !dinfo->enable_auto_del) {
120 return;
123 if (bs->job) {
124 block_job_cancel(bs->job);
126 if (dinfo) {
127 dinfo->auto_del = 1;
131 void blockdev_auto_del(BlockDriverState *bs)
133 BlockBackend *blk = bs->blk;
134 DriveInfo *dinfo = blk_legacy_dinfo(blk);
136 if (dinfo && dinfo->auto_del) {
137 blk_unref(blk);
142 * Returns the current mapping of how many units per bus
143 * a particular interface can support.
145 * A positive integer indicates n units per bus.
146 * 0 implies the mapping has not been established.
147 * -1 indicates an invalid BlockInterfaceType was given.
149 int drive_get_max_devs(BlockInterfaceType type)
151 if (type >= IF_IDE && type < IF_COUNT) {
152 return if_max_devs[type];
155 return -1;
158 static int drive_index_to_bus_id(BlockInterfaceType type, int index)
160 int max_devs = if_max_devs[type];
161 return max_devs ? index / max_devs : 0;
164 static int drive_index_to_unit_id(BlockInterfaceType type, int index)
166 int max_devs = if_max_devs[type];
167 return max_devs ? index % max_devs : index;
170 QemuOpts *drive_def(const char *optstr)
172 return qemu_opts_parse(qemu_find_opts("drive"), optstr, 0);
175 QemuOpts *drive_add(BlockInterfaceType type, int index, const char *file,
176 const char *optstr)
178 QemuOpts *opts;
179 char buf[32];
181 opts = drive_def(optstr);
182 if (!opts) {
183 return NULL;
185 if (type != IF_DEFAULT) {
186 qemu_opt_set(opts, "if", if_name[type]);
188 if (index >= 0) {
189 snprintf(buf, sizeof(buf), "%d", index);
190 qemu_opt_set(opts, "index", buf);
192 if (file)
193 qemu_opt_set(opts, "file", file);
194 return opts;
197 DriveInfo *drive_get(BlockInterfaceType type, int bus, int unit)
199 BlockBackend *blk;
200 DriveInfo *dinfo;
202 for (blk = blk_next(NULL); blk; blk = blk_next(blk)) {
203 dinfo = blk_legacy_dinfo(blk);
204 if (dinfo && dinfo->type == type
205 && dinfo->bus == bus && dinfo->unit == unit) {
206 return dinfo;
210 return NULL;
213 bool drive_check_orphaned(void)
215 BlockBackend *blk;
216 DriveInfo *dinfo;
217 bool rs = false;
219 for (blk = blk_next(NULL); blk; blk = blk_next(blk)) {
220 dinfo = blk_legacy_dinfo(blk);
221 /* If dinfo->bdrv->dev is NULL, it has no device attached. */
222 /* Unless this is a default drive, this may be an oversight. */
223 if (!dinfo->bdrv->dev && !dinfo->is_default &&
224 dinfo->type != IF_NONE) {
225 fprintf(stderr, "Warning: Orphaned drive without device: "
226 "id=%s,file=%s,if=%s,bus=%d,unit=%d\n",
227 dinfo->id, dinfo->bdrv->filename, if_name[dinfo->type],
228 dinfo->bus, dinfo->unit);
229 rs = true;
233 return rs;
236 DriveInfo *drive_get_by_index(BlockInterfaceType type, int index)
238 return drive_get(type,
239 drive_index_to_bus_id(type, index),
240 drive_index_to_unit_id(type, index));
243 int drive_get_max_bus(BlockInterfaceType type)
245 int max_bus;
246 BlockBackend *blk;
247 DriveInfo *dinfo;
249 max_bus = -1;
250 for (blk = blk_next(NULL); blk; blk = blk_next(blk)) {
251 dinfo = blk_legacy_dinfo(blk);
252 if (dinfo && dinfo->type == type && dinfo->bus > max_bus) {
253 max_bus = dinfo->bus;
256 return max_bus;
259 /* Get a block device. This should only be used for single-drive devices
260 (e.g. SD/Floppy/MTD). Multi-disk devices (scsi/ide) should use the
261 appropriate bus. */
262 DriveInfo *drive_get_next(BlockInterfaceType type)
264 static int next_block_unit[IF_COUNT];
266 return drive_get(type, 0, next_block_unit[type]++);
269 DriveInfo *drive_get_by_blockdev(BlockDriverState *bs)
271 return bs->blk ? blk_legacy_dinfo(bs->blk) : NULL;
274 static void bdrv_format_print(void *opaque, const char *name)
276 error_printf(" %s", name);
279 typedef struct {
280 QEMUBH *bh;
281 BlockDriverState *bs;
282 } BDRVPutRefBH;
284 static void bdrv_put_ref_bh(void *opaque)
286 BDRVPutRefBH *s = opaque;
288 bdrv_unref(s->bs);
289 qemu_bh_delete(s->bh);
290 g_free(s);
294 * Release a BDS reference in a BH
296 * It is not safe to use bdrv_unref() from a callback function when the callers
297 * still need the BlockDriverState. In such cases we schedule a BH to release
298 * the reference.
300 static void bdrv_put_ref_bh_schedule(BlockDriverState *bs)
302 BDRVPutRefBH *s;
304 s = g_new(BDRVPutRefBH, 1);
305 s->bh = qemu_bh_new(bdrv_put_ref_bh, s);
306 s->bs = bs;
307 qemu_bh_schedule(s->bh);
310 static int parse_block_error_action(const char *buf, bool is_read, Error **errp)
312 if (!strcmp(buf, "ignore")) {
313 return BLOCKDEV_ON_ERROR_IGNORE;
314 } else if (!is_read && !strcmp(buf, "enospc")) {
315 return BLOCKDEV_ON_ERROR_ENOSPC;
316 } else if (!strcmp(buf, "stop")) {
317 return BLOCKDEV_ON_ERROR_STOP;
318 } else if (!strcmp(buf, "report")) {
319 return BLOCKDEV_ON_ERROR_REPORT;
320 } else {
321 error_setg(errp, "'%s' invalid %s error action",
322 buf, is_read ? "read" : "write");
323 return -1;
327 static bool check_throttle_config(ThrottleConfig *cfg, Error **errp)
329 if (throttle_conflicting(cfg)) {
330 error_setg(errp, "bps/iops/max total values and read/write values"
331 " cannot be used at the same time");
332 return false;
335 if (!throttle_is_valid(cfg)) {
336 error_setg(errp, "bps/iops/maxs values must be 0 or greater");
337 return false;
340 return true;
343 typedef enum { MEDIA_DISK, MEDIA_CDROM } DriveMediaType;
345 /* Takes the ownership of bs_opts */
346 static BlockBackend *blockdev_init(const char *file, QDict *bs_opts,
347 Error **errp)
349 const char *buf;
350 int ro = 0;
351 int bdrv_flags = 0;
352 int on_read_error, on_write_error;
353 BlockBackend *blk;
354 BlockDriverState *bs;
355 DriveInfo *dinfo;
356 ThrottleConfig cfg;
357 int snapshot = 0;
358 bool copy_on_read;
359 int ret;
360 Error *error = NULL;
361 QemuOpts *opts;
362 const char *id;
363 bool has_driver_specific_opts;
364 BlockdevDetectZeroesOptions detect_zeroes;
365 BlockDriver *drv = NULL;
367 /* Check common options by copying from bs_opts to opts, all other options
368 * stay in bs_opts for processing by bdrv_open(). */
369 id = qdict_get_try_str(bs_opts, "id");
370 opts = qemu_opts_create(&qemu_common_drive_opts, id, 1, &error);
371 if (error) {
372 error_propagate(errp, error);
373 goto err_no_opts;
376 qemu_opts_absorb_qdict(opts, bs_opts, &error);
377 if (error) {
378 error_propagate(errp, error);
379 goto early_err;
382 if (id) {
383 qdict_del(bs_opts, "id");
386 has_driver_specific_opts = !!qdict_size(bs_opts);
388 /* extract parameters */
389 snapshot = qemu_opt_get_bool(opts, "snapshot", 0);
390 ro = qemu_opt_get_bool(opts, "read-only", 0);
391 copy_on_read = qemu_opt_get_bool(opts, "copy-on-read", false);
393 if ((buf = qemu_opt_get(opts, "discard")) != NULL) {
394 if (bdrv_parse_discard_flags(buf, &bdrv_flags) != 0) {
395 error_setg(errp, "invalid discard option");
396 goto early_err;
400 if (qemu_opt_get_bool(opts, "cache.writeback", true)) {
401 bdrv_flags |= BDRV_O_CACHE_WB;
403 if (qemu_opt_get_bool(opts, "cache.direct", false)) {
404 bdrv_flags |= BDRV_O_NOCACHE;
406 if (qemu_opt_get_bool(opts, "cache.no-flush", false)) {
407 bdrv_flags |= BDRV_O_NO_FLUSH;
410 #ifdef CONFIG_LINUX_AIO
411 if ((buf = qemu_opt_get(opts, "aio")) != NULL) {
412 if (!strcmp(buf, "native")) {
413 bdrv_flags |= BDRV_O_NATIVE_AIO;
414 } else if (!strcmp(buf, "threads")) {
415 /* this is the default */
416 } else {
417 error_setg(errp, "invalid aio option");
418 goto early_err;
421 #endif
423 if ((buf = qemu_opt_get(opts, "format")) != NULL) {
424 if (is_help_option(buf)) {
425 error_printf("Supported formats:");
426 bdrv_iterate_format(bdrv_format_print, NULL);
427 error_printf("\n");
428 goto early_err;
431 drv = bdrv_find_format(buf);
432 if (!drv) {
433 error_setg(errp, "'%s' invalid format", buf);
434 goto early_err;
438 /* disk I/O throttling */
439 memset(&cfg, 0, sizeof(cfg));
440 cfg.buckets[THROTTLE_BPS_TOTAL].avg =
441 qemu_opt_get_number(opts, "throttling.bps-total", 0);
442 cfg.buckets[THROTTLE_BPS_READ].avg =
443 qemu_opt_get_number(opts, "throttling.bps-read", 0);
444 cfg.buckets[THROTTLE_BPS_WRITE].avg =
445 qemu_opt_get_number(opts, "throttling.bps-write", 0);
446 cfg.buckets[THROTTLE_OPS_TOTAL].avg =
447 qemu_opt_get_number(opts, "throttling.iops-total", 0);
448 cfg.buckets[THROTTLE_OPS_READ].avg =
449 qemu_opt_get_number(opts, "throttling.iops-read", 0);
450 cfg.buckets[THROTTLE_OPS_WRITE].avg =
451 qemu_opt_get_number(opts, "throttling.iops-write", 0);
453 cfg.buckets[THROTTLE_BPS_TOTAL].max =
454 qemu_opt_get_number(opts, "throttling.bps-total-max", 0);
455 cfg.buckets[THROTTLE_BPS_READ].max =
456 qemu_opt_get_number(opts, "throttling.bps-read-max", 0);
457 cfg.buckets[THROTTLE_BPS_WRITE].max =
458 qemu_opt_get_number(opts, "throttling.bps-write-max", 0);
459 cfg.buckets[THROTTLE_OPS_TOTAL].max =
460 qemu_opt_get_number(opts, "throttling.iops-total-max", 0);
461 cfg.buckets[THROTTLE_OPS_READ].max =
462 qemu_opt_get_number(opts, "throttling.iops-read-max", 0);
463 cfg.buckets[THROTTLE_OPS_WRITE].max =
464 qemu_opt_get_number(opts, "throttling.iops-write-max", 0);
466 cfg.op_size = qemu_opt_get_number(opts, "throttling.iops-size", 0);
468 if (!check_throttle_config(&cfg, &error)) {
469 error_propagate(errp, error);
470 goto early_err;
473 on_write_error = BLOCKDEV_ON_ERROR_ENOSPC;
474 if ((buf = qemu_opt_get(opts, "werror")) != NULL) {
475 on_write_error = parse_block_error_action(buf, 0, &error);
476 if (error) {
477 error_propagate(errp, error);
478 goto early_err;
482 on_read_error = BLOCKDEV_ON_ERROR_REPORT;
483 if ((buf = qemu_opt_get(opts, "rerror")) != NULL) {
484 on_read_error = parse_block_error_action(buf, 1, &error);
485 if (error) {
486 error_propagate(errp, error);
487 goto early_err;
491 detect_zeroes =
492 qapi_enum_parse(BlockdevDetectZeroesOptions_lookup,
493 qemu_opt_get(opts, "detect-zeroes"),
494 BLOCKDEV_DETECT_ZEROES_OPTIONS_MAX,
495 BLOCKDEV_DETECT_ZEROES_OPTIONS_OFF,
496 &error);
497 if (error) {
498 error_propagate(errp, error);
499 goto early_err;
502 if (detect_zeroes == BLOCKDEV_DETECT_ZEROES_OPTIONS_UNMAP &&
503 !(bdrv_flags & BDRV_O_UNMAP)) {
504 error_setg(errp, "setting detect-zeroes to unmap is not allowed "
505 "without setting discard operation to unmap");
506 goto early_err;
509 /* init */
510 blk = blk_new_with_bs(qemu_opts_id(opts), errp);
511 if (!blk) {
512 goto early_err;
514 bs = blk_bs(blk);
515 bs->open_flags = snapshot ? BDRV_O_SNAPSHOT : 0;
516 bs->read_only = ro;
517 bs->detect_zeroes = detect_zeroes;
519 bdrv_set_on_error(bs, on_read_error, on_write_error);
521 /* disk I/O throttling */
522 if (throttle_enabled(&cfg)) {
523 bdrv_io_limits_enable(bs);
524 bdrv_set_io_limits(bs, &cfg);
527 dinfo = g_malloc0(sizeof(*dinfo));
528 dinfo->id = g_strdup(qemu_opts_id(opts));
529 dinfo->bdrv = bs;
530 blk_set_legacy_dinfo(blk, dinfo);
532 if (!file || !*file) {
533 if (has_driver_specific_opts) {
534 file = NULL;
535 } else {
536 QDECREF(bs_opts);
537 qemu_opts_del(opts);
538 return blk;
541 if (snapshot) {
542 /* always use cache=unsafe with snapshot */
543 bdrv_flags &= ~BDRV_O_CACHE_MASK;
544 bdrv_flags |= (BDRV_O_SNAPSHOT|BDRV_O_CACHE_WB|BDRV_O_NO_FLUSH);
547 if (copy_on_read) {
548 bdrv_flags |= BDRV_O_COPY_ON_READ;
551 if (runstate_check(RUN_STATE_INMIGRATE)) {
552 bdrv_flags |= BDRV_O_INCOMING;
555 bdrv_flags |= ro ? 0 : BDRV_O_RDWR;
557 QINCREF(bs_opts);
558 ret = bdrv_open(&bs, file, NULL, bs_opts, bdrv_flags, drv, &error);
559 assert(bs == dinfo->bdrv);
561 if (ret < 0) {
562 error_setg(errp, "could not open disk image %s: %s",
563 file ?: dinfo->id, error_get_pretty(error));
564 error_free(error);
565 goto err;
568 if (bdrv_key_required(bs)) {
569 autostart = 0;
572 QDECREF(bs_opts);
573 qemu_opts_del(opts);
575 return blk;
577 err:
578 blk_unref(blk);
579 early_err:
580 qemu_opts_del(opts);
581 err_no_opts:
582 QDECREF(bs_opts);
583 return NULL;
586 static void qemu_opt_rename(QemuOpts *opts, const char *from, const char *to,
587 Error **errp)
589 const char *value;
591 value = qemu_opt_get(opts, from);
592 if (value) {
593 if (qemu_opt_find(opts, to)) {
594 error_setg(errp, "'%s' and its alias '%s' can't be used at the "
595 "same time", to, from);
596 return;
600 /* rename all items in opts */
601 while ((value = qemu_opt_get(opts, from))) {
602 qemu_opt_set(opts, to, value);
603 qemu_opt_unset(opts, from);
607 QemuOptsList qemu_legacy_drive_opts = {
608 .name = "drive",
609 .head = QTAILQ_HEAD_INITIALIZER(qemu_legacy_drive_opts.head),
610 .desc = {
612 .name = "bus",
613 .type = QEMU_OPT_NUMBER,
614 .help = "bus number",
616 .name = "unit",
617 .type = QEMU_OPT_NUMBER,
618 .help = "unit number (i.e. lun for scsi)",
620 .name = "index",
621 .type = QEMU_OPT_NUMBER,
622 .help = "index number",
624 .name = "media",
625 .type = QEMU_OPT_STRING,
626 .help = "media type (disk, cdrom)",
628 .name = "if",
629 .type = QEMU_OPT_STRING,
630 .help = "interface (ide, scsi, sd, mtd, floppy, pflash, virtio)",
632 .name = "cyls",
633 .type = QEMU_OPT_NUMBER,
634 .help = "number of cylinders (ide disk geometry)",
636 .name = "heads",
637 .type = QEMU_OPT_NUMBER,
638 .help = "number of heads (ide disk geometry)",
640 .name = "secs",
641 .type = QEMU_OPT_NUMBER,
642 .help = "number of sectors (ide disk geometry)",
644 .name = "trans",
645 .type = QEMU_OPT_STRING,
646 .help = "chs translation (auto, lba, none)",
648 .name = "boot",
649 .type = QEMU_OPT_BOOL,
650 .help = "(deprecated, ignored)",
652 .name = "addr",
653 .type = QEMU_OPT_STRING,
654 .help = "pci address (virtio only)",
656 .name = "serial",
657 .type = QEMU_OPT_STRING,
658 .help = "disk serial number",
660 .name = "file",
661 .type = QEMU_OPT_STRING,
662 .help = "file name",
665 /* Options that are passed on, but have special semantics with -drive */
667 .name = "read-only",
668 .type = QEMU_OPT_BOOL,
669 .help = "open drive file as read-only",
671 .name = "rerror",
672 .type = QEMU_OPT_STRING,
673 .help = "read error action",
675 .name = "werror",
676 .type = QEMU_OPT_STRING,
677 .help = "write error action",
679 .name = "copy-on-read",
680 .type = QEMU_OPT_BOOL,
681 .help = "copy read data from backing file into image file",
684 { /* end of list */ }
688 DriveInfo *drive_new(QemuOpts *all_opts, BlockInterfaceType block_default_type)
690 const char *value;
691 BlockBackend *blk;
692 DriveInfo *dinfo = NULL;
693 QDict *bs_opts;
694 QemuOpts *legacy_opts;
695 DriveMediaType media = MEDIA_DISK;
696 BlockInterfaceType type;
697 int cyls, heads, secs, translation;
698 int max_devs, bus_id, unit_id, index;
699 const char *devaddr;
700 const char *werror, *rerror;
701 bool read_only = false;
702 bool copy_on_read;
703 const char *serial;
704 const char *filename;
705 Error *local_err = NULL;
706 int i;
708 /* Change legacy command line options into QMP ones */
709 static const struct {
710 const char *from;
711 const char *to;
712 } opt_renames[] = {
713 { "iops", "throttling.iops-total" },
714 { "iops_rd", "throttling.iops-read" },
715 { "iops_wr", "throttling.iops-write" },
717 { "bps", "throttling.bps-total" },
718 { "bps_rd", "throttling.bps-read" },
719 { "bps_wr", "throttling.bps-write" },
721 { "iops_max", "throttling.iops-total-max" },
722 { "iops_rd_max", "throttling.iops-read-max" },
723 { "iops_wr_max", "throttling.iops-write-max" },
725 { "bps_max", "throttling.bps-total-max" },
726 { "bps_rd_max", "throttling.bps-read-max" },
727 { "bps_wr_max", "throttling.bps-write-max" },
729 { "iops_size", "throttling.iops-size" },
731 { "readonly", "read-only" },
734 for (i = 0; i < ARRAY_SIZE(opt_renames); i++) {
735 qemu_opt_rename(all_opts, opt_renames[i].from, opt_renames[i].to,
736 &local_err);
737 if (local_err) {
738 error_report("%s", error_get_pretty(local_err));
739 error_free(local_err);
740 return NULL;
744 value = qemu_opt_get(all_opts, "cache");
745 if (value) {
746 int flags = 0;
748 if (bdrv_parse_cache_flags(value, &flags) != 0) {
749 error_report("invalid cache option");
750 return NULL;
753 /* Specific options take precedence */
754 if (!qemu_opt_get(all_opts, "cache.writeback")) {
755 qemu_opt_set_bool(all_opts, "cache.writeback",
756 !!(flags & BDRV_O_CACHE_WB));
758 if (!qemu_opt_get(all_opts, "cache.direct")) {
759 qemu_opt_set_bool(all_opts, "cache.direct",
760 !!(flags & BDRV_O_NOCACHE));
762 if (!qemu_opt_get(all_opts, "cache.no-flush")) {
763 qemu_opt_set_bool(all_opts, "cache.no-flush",
764 !!(flags & BDRV_O_NO_FLUSH));
766 qemu_opt_unset(all_opts, "cache");
769 /* Get a QDict for processing the options */
770 bs_opts = qdict_new();
771 qemu_opts_to_qdict(all_opts, bs_opts);
773 legacy_opts = qemu_opts_create(&qemu_legacy_drive_opts, NULL, 0,
774 &error_abort);
775 qemu_opts_absorb_qdict(legacy_opts, bs_opts, &local_err);
776 if (local_err) {
777 error_report("%s", error_get_pretty(local_err));
778 error_free(local_err);
779 goto fail;
782 /* Deprecated option boot=[on|off] */
783 if (qemu_opt_get(legacy_opts, "boot") != NULL) {
784 fprintf(stderr, "qemu-kvm: boot=on|off is deprecated and will be "
785 "ignored. Future versions will reject this parameter. Please "
786 "update your scripts.\n");
789 /* Media type */
790 value = qemu_opt_get(legacy_opts, "media");
791 if (value) {
792 if (!strcmp(value, "disk")) {
793 media = MEDIA_DISK;
794 } else if (!strcmp(value, "cdrom")) {
795 media = MEDIA_CDROM;
796 read_only = true;
797 } else {
798 error_report("'%s' invalid media", value);
799 goto fail;
803 /* copy-on-read is disabled with a warning for read-only devices */
804 read_only |= qemu_opt_get_bool(legacy_opts, "read-only", false);
805 copy_on_read = qemu_opt_get_bool(legacy_opts, "copy-on-read", false);
807 if (read_only && copy_on_read) {
808 error_report("warning: disabling copy-on-read on read-only drive");
809 copy_on_read = false;
812 qdict_put(bs_opts, "read-only",
813 qstring_from_str(read_only ? "on" : "off"));
814 qdict_put(bs_opts, "copy-on-read",
815 qstring_from_str(copy_on_read ? "on" :"off"));
817 /* Controller type */
818 value = qemu_opt_get(legacy_opts, "if");
819 if (value) {
820 for (type = 0;
821 type < IF_COUNT && strcmp(value, if_name[type]);
822 type++) {
824 if (type == IF_COUNT) {
825 error_report("unsupported bus type '%s'", value);
826 goto fail;
828 } else {
829 type = block_default_type;
832 /* Geometry */
833 cyls = qemu_opt_get_number(legacy_opts, "cyls", 0);
834 heads = qemu_opt_get_number(legacy_opts, "heads", 0);
835 secs = qemu_opt_get_number(legacy_opts, "secs", 0);
837 if (cyls || heads || secs) {
838 if (cyls < 1) {
839 error_report("invalid physical cyls number");
840 goto fail;
842 if (heads < 1) {
843 error_report("invalid physical heads number");
844 goto fail;
846 if (secs < 1) {
847 error_report("invalid physical secs number");
848 goto fail;
852 translation = BIOS_ATA_TRANSLATION_AUTO;
853 value = qemu_opt_get(legacy_opts, "trans");
854 if (value != NULL) {
855 if (!cyls) {
856 error_report("'%s' trans must be used with cyls, heads and secs",
857 value);
858 goto fail;
860 if (!strcmp(value, "none")) {
861 translation = BIOS_ATA_TRANSLATION_NONE;
862 } else if (!strcmp(value, "lba")) {
863 translation = BIOS_ATA_TRANSLATION_LBA;
864 } else if (!strcmp(value, "large")) {
865 translation = BIOS_ATA_TRANSLATION_LARGE;
866 } else if (!strcmp(value, "rechs")) {
867 translation = BIOS_ATA_TRANSLATION_RECHS;
868 } else if (!strcmp(value, "auto")) {
869 translation = BIOS_ATA_TRANSLATION_AUTO;
870 } else {
871 error_report("'%s' invalid translation type", value);
872 goto fail;
876 if (media == MEDIA_CDROM) {
877 if (cyls || secs || heads) {
878 error_report("CHS can't be set with media=cdrom");
879 goto fail;
883 /* Device address specified by bus/unit or index.
884 * If none was specified, try to find the first free one. */
885 bus_id = qemu_opt_get_number(legacy_opts, "bus", 0);
886 unit_id = qemu_opt_get_number(legacy_opts, "unit", -1);
887 index = qemu_opt_get_number(legacy_opts, "index", -1);
889 max_devs = if_max_devs[type];
891 if (index != -1) {
892 if (bus_id != 0 || unit_id != -1) {
893 error_report("index cannot be used with bus and unit");
894 goto fail;
896 bus_id = drive_index_to_bus_id(type, index);
897 unit_id = drive_index_to_unit_id(type, index);
900 if (unit_id == -1) {
901 unit_id = 0;
902 while (drive_get(type, bus_id, unit_id) != NULL) {
903 unit_id++;
904 if (max_devs && unit_id >= max_devs) {
905 unit_id -= max_devs;
906 bus_id++;
911 if (max_devs && unit_id >= max_devs) {
912 error_report("unit %d too big (max is %d)", unit_id, max_devs - 1);
913 goto fail;
916 if (drive_get(type, bus_id, unit_id) != NULL) {
917 error_report("drive with bus=%d, unit=%d (index=%d) exists",
918 bus_id, unit_id, index);
919 goto fail;
922 /* Serial number */
923 serial = qemu_opt_get(legacy_opts, "serial");
925 /* no id supplied -> create one */
926 if (qemu_opts_id(all_opts) == NULL) {
927 char *new_id;
928 const char *mediastr = "";
929 if (type == IF_IDE || type == IF_SCSI) {
930 mediastr = (media == MEDIA_CDROM) ? "-cd" : "-hd";
932 if (max_devs) {
933 new_id = g_strdup_printf("%s%i%s%i", if_name[type], bus_id,
934 mediastr, unit_id);
935 } else {
936 new_id = g_strdup_printf("%s%s%i", if_name[type],
937 mediastr, unit_id);
939 qdict_put(bs_opts, "id", qstring_from_str(new_id));
940 g_free(new_id);
943 /* Add virtio block device */
944 devaddr = qemu_opt_get(legacy_opts, "addr");
945 if (devaddr && type != IF_VIRTIO) {
946 error_report("addr is not supported by this bus type");
947 goto fail;
950 if (type == IF_VIRTIO) {
951 QemuOpts *devopts;
952 devopts = qemu_opts_create(qemu_find_opts("device"), NULL, 0,
953 &error_abort);
954 if (arch_type == QEMU_ARCH_S390X) {
955 qemu_opt_set(devopts, "driver", "virtio-blk-s390");
956 } else {
957 qemu_opt_set(devopts, "driver", "virtio-blk-pci");
959 qemu_opt_set(devopts, "drive", qdict_get_str(bs_opts, "id"));
960 if (devaddr) {
961 qemu_opt_set(devopts, "addr", devaddr);
965 filename = qemu_opt_get(legacy_opts, "file");
967 /* Check werror/rerror compatibility with if=... */
968 werror = qemu_opt_get(legacy_opts, "werror");
969 if (werror != NULL) {
970 if (type != IF_IDE && type != IF_SCSI && type != IF_VIRTIO &&
971 type != IF_NONE) {
972 error_report("werror is not supported by this bus type");
973 goto fail;
975 qdict_put(bs_opts, "werror", qstring_from_str(werror));
978 rerror = qemu_opt_get(legacy_opts, "rerror");
979 if (rerror != NULL) {
980 if (type != IF_IDE && type != IF_VIRTIO && type != IF_SCSI &&
981 type != IF_NONE) {
982 error_report("rerror is not supported by this bus type");
983 goto fail;
985 qdict_put(bs_opts, "rerror", qstring_from_str(rerror));
988 /* Actual block device init: Functionality shared with blockdev-add */
989 blk = blockdev_init(filename, bs_opts, &local_err);
990 bs_opts = NULL;
991 if (!blk) {
992 if (local_err) {
993 error_report("%s", error_get_pretty(local_err));
994 error_free(local_err);
996 goto fail;
997 } else {
998 assert(!local_err);
1001 /* Set legacy DriveInfo fields */
1002 dinfo = blk_legacy_dinfo(blk);
1003 dinfo->enable_auto_del = true;
1004 dinfo->opts = all_opts;
1006 dinfo->cyls = cyls;
1007 dinfo->heads = heads;
1008 dinfo->secs = secs;
1009 dinfo->trans = translation;
1011 dinfo->type = type;
1012 dinfo->bus = bus_id;
1013 dinfo->unit = unit_id;
1014 dinfo->devaddr = devaddr;
1016 dinfo->serial = g_strdup(serial);
1018 switch(type) {
1019 case IF_IDE:
1020 case IF_SCSI:
1021 case IF_XEN:
1022 case IF_NONE:
1023 dinfo->media_cd = media == MEDIA_CDROM;
1024 break;
1025 default:
1026 break;
1029 fail:
1030 qemu_opts_del(legacy_opts);
1031 QDECREF(bs_opts);
1032 return dinfo;
1035 void do_commit(Monitor *mon, const QDict *qdict)
1037 const char *device = qdict_get_str(qdict, "device");
1038 BlockDriverState *bs;
1039 int ret;
1041 if (!strcmp(device, "all")) {
1042 ret = bdrv_commit_all();
1043 } else {
1044 bs = bdrv_find(device);
1045 if (!bs) {
1046 monitor_printf(mon, "Device '%s' not found\n", device);
1047 return;
1049 ret = bdrv_commit(bs);
1051 if (ret < 0) {
1052 monitor_printf(mon, "'commit' error for '%s': %s\n", device,
1053 strerror(-ret));
1057 static void blockdev_do_action(int kind, void *data, Error **errp)
1059 TransactionAction action;
1060 TransactionActionList list;
1062 action.kind = kind;
1063 action.data = data;
1064 list.value = &action;
1065 list.next = NULL;
1066 qmp_transaction(&list, errp);
1069 void qmp_blockdev_snapshot_sync(bool has_device, const char *device,
1070 bool has_node_name, const char *node_name,
1071 const char *snapshot_file,
1072 bool has_snapshot_node_name,
1073 const char *snapshot_node_name,
1074 bool has_format, const char *format,
1075 bool has_mode, NewImageMode mode, Error **errp)
1077 BlockdevSnapshot snapshot = {
1078 .has_device = has_device,
1079 .device = (char *) device,
1080 .has_node_name = has_node_name,
1081 .node_name = (char *) node_name,
1082 .snapshot_file = (char *) snapshot_file,
1083 .has_snapshot_node_name = has_snapshot_node_name,
1084 .snapshot_node_name = (char *) snapshot_node_name,
1085 .has_format = has_format,
1086 .format = (char *) format,
1087 .has_mode = has_mode,
1088 .mode = mode,
1090 blockdev_do_action(TRANSACTION_ACTION_KIND_BLOCKDEV_SNAPSHOT_SYNC,
1091 &snapshot, errp);
1094 void qmp_blockdev_snapshot_internal_sync(const char *device,
1095 const char *name,
1096 Error **errp)
1098 BlockdevSnapshotInternal snapshot = {
1099 .device = (char *) device,
1100 .name = (char *) name
1103 blockdev_do_action(TRANSACTION_ACTION_KIND_BLOCKDEV_SNAPSHOT_INTERNAL_SYNC,
1104 &snapshot, errp);
1107 SnapshotInfo *qmp_blockdev_snapshot_delete_internal_sync(const char *device,
1108 bool has_id,
1109 const char *id,
1110 bool has_name,
1111 const char *name,
1112 Error **errp)
1114 BlockDriverState *bs = bdrv_find(device);
1115 QEMUSnapshotInfo sn;
1116 Error *local_err = NULL;
1117 SnapshotInfo *info = NULL;
1118 int ret;
1120 if (!bs) {
1121 error_set(errp, QERR_DEVICE_NOT_FOUND, device);
1122 return NULL;
1125 if (!has_id) {
1126 id = NULL;
1129 if (!has_name) {
1130 name = NULL;
1133 if (!id && !name) {
1134 error_setg(errp, "Name or id must be provided");
1135 return NULL;
1138 ret = bdrv_snapshot_find_by_id_and_name(bs, id, name, &sn, &local_err);
1139 if (local_err) {
1140 error_propagate(errp, local_err);
1141 return NULL;
1143 if (!ret) {
1144 error_setg(errp,
1145 "Snapshot with id '%s' and name '%s' does not exist on "
1146 "device '%s'",
1147 STR_OR_NULL(id), STR_OR_NULL(name), device);
1148 return NULL;
1151 bdrv_snapshot_delete(bs, id, name, &local_err);
1152 if (local_err) {
1153 error_propagate(errp, local_err);
1154 return NULL;
1157 info = g_new0(SnapshotInfo, 1);
1158 info->id = g_strdup(sn.id_str);
1159 info->name = g_strdup(sn.name);
1160 info->date_nsec = sn.date_nsec;
1161 info->date_sec = sn.date_sec;
1162 info->vm_state_size = sn.vm_state_size;
1163 info->vm_clock_nsec = sn.vm_clock_nsec % 1000000000;
1164 info->vm_clock_sec = sn.vm_clock_nsec / 1000000000;
1166 return info;
1169 /* New and old BlockDriverState structs for group snapshots */
1171 typedef struct BlkTransactionState BlkTransactionState;
1173 /* Only prepare() may fail. In a single transaction, only one of commit() or
1174 abort() will be called, clean() will always be called if it present. */
1175 typedef struct BdrvActionOps {
1176 /* Size of state struct, in bytes. */
1177 size_t instance_size;
1178 /* Prepare the work, must NOT be NULL. */
1179 void (*prepare)(BlkTransactionState *common, Error **errp);
1180 /* Commit the changes, can be NULL. */
1181 void (*commit)(BlkTransactionState *common);
1182 /* Abort the changes on fail, can be NULL. */
1183 void (*abort)(BlkTransactionState *common);
1184 /* Clean up resource in the end, can be NULL. */
1185 void (*clean)(BlkTransactionState *common);
1186 } BdrvActionOps;
1189 * This structure must be arranged as first member in child type, assuming
1190 * that compiler will also arrange it to the same address with parent instance.
1191 * Later it will be used in free().
1193 struct BlkTransactionState {
1194 TransactionAction *action;
1195 const BdrvActionOps *ops;
1196 QSIMPLEQ_ENTRY(BlkTransactionState) entry;
1199 /* internal snapshot private data */
1200 typedef struct InternalSnapshotState {
1201 BlkTransactionState common;
1202 BlockDriverState *bs;
1203 QEMUSnapshotInfo sn;
1204 } InternalSnapshotState;
1206 static void internal_snapshot_prepare(BlkTransactionState *common,
1207 Error **errp)
1209 Error *local_err = NULL;
1210 const char *device;
1211 const char *name;
1212 BlockDriverState *bs;
1213 QEMUSnapshotInfo old_sn, *sn;
1214 bool ret;
1215 qemu_timeval tv;
1216 BlockdevSnapshotInternal *internal;
1217 InternalSnapshotState *state;
1218 int ret1;
1220 g_assert(common->action->kind ==
1221 TRANSACTION_ACTION_KIND_BLOCKDEV_SNAPSHOT_INTERNAL_SYNC);
1222 internal = common->action->blockdev_snapshot_internal_sync;
1223 state = DO_UPCAST(InternalSnapshotState, common, common);
1225 /* 1. parse input */
1226 device = internal->device;
1227 name = internal->name;
1229 /* 2. check for validation */
1230 bs = bdrv_find(device);
1231 if (!bs) {
1232 error_set(errp, QERR_DEVICE_NOT_FOUND, device);
1233 return;
1236 if (!bdrv_is_inserted(bs)) {
1237 error_set(errp, QERR_DEVICE_HAS_NO_MEDIUM, device);
1238 return;
1241 if (bdrv_is_read_only(bs)) {
1242 error_set(errp, QERR_DEVICE_IS_READ_ONLY, device);
1243 return;
1246 if (!bdrv_can_snapshot(bs)) {
1247 error_set(errp, QERR_BLOCK_FORMAT_FEATURE_NOT_SUPPORTED,
1248 bs->drv->format_name, device, "internal snapshot");
1249 return;
1252 if (!strlen(name)) {
1253 error_setg(errp, "Name is empty");
1254 return;
1257 /* check whether a snapshot with name exist */
1258 ret = bdrv_snapshot_find_by_id_and_name(bs, NULL, name, &old_sn,
1259 &local_err);
1260 if (local_err) {
1261 error_propagate(errp, local_err);
1262 return;
1263 } else if (ret) {
1264 error_setg(errp,
1265 "Snapshot with name '%s' already exists on device '%s'",
1266 name, device);
1267 return;
1270 /* 3. take the snapshot */
1271 sn = &state->sn;
1272 pstrcpy(sn->name, sizeof(sn->name), name);
1273 qemu_gettimeofday(&tv);
1274 sn->date_sec = tv.tv_sec;
1275 sn->date_nsec = tv.tv_usec * 1000;
1276 sn->vm_clock_nsec = qemu_clock_get_ns(QEMU_CLOCK_VIRTUAL);
1278 ret1 = bdrv_snapshot_create(bs, sn);
1279 if (ret1 < 0) {
1280 error_setg_errno(errp, -ret1,
1281 "Failed to create snapshot '%s' on device '%s'",
1282 name, device);
1283 return;
1286 /* 4. succeed, mark a snapshot is created */
1287 state->bs = bs;
1290 static void internal_snapshot_abort(BlkTransactionState *common)
1292 InternalSnapshotState *state =
1293 DO_UPCAST(InternalSnapshotState, common, common);
1294 BlockDriverState *bs = state->bs;
1295 QEMUSnapshotInfo *sn = &state->sn;
1296 Error *local_error = NULL;
1298 if (!bs) {
1299 return;
1302 if (bdrv_snapshot_delete(bs, sn->id_str, sn->name, &local_error) < 0) {
1303 error_report("Failed to delete snapshot with id '%s' and name '%s' on "
1304 "device '%s' in abort: %s",
1305 sn->id_str,
1306 sn->name,
1307 bdrv_get_device_name(bs),
1308 error_get_pretty(local_error));
1309 error_free(local_error);
1313 /* external snapshot private data */
1314 typedef struct ExternalSnapshotState {
1315 BlkTransactionState common;
1316 BlockDriverState *old_bs;
1317 BlockDriverState *new_bs;
1318 } ExternalSnapshotState;
1320 static void external_snapshot_prepare(BlkTransactionState *common,
1321 Error **errp)
1323 BlockDriver *drv;
1324 int flags, ret;
1325 QDict *options = NULL;
1326 Error *local_err = NULL;
1327 bool has_device = false;
1328 const char *device;
1329 bool has_node_name = false;
1330 const char *node_name;
1331 bool has_snapshot_node_name = false;
1332 const char *snapshot_node_name;
1333 const char *new_image_file;
1334 const char *format = "qcow2";
1335 enum NewImageMode mode = NEW_IMAGE_MODE_ABSOLUTE_PATHS;
1336 ExternalSnapshotState *state =
1337 DO_UPCAST(ExternalSnapshotState, common, common);
1338 TransactionAction *action = common->action;
1340 /* get parameters */
1341 g_assert(action->kind == TRANSACTION_ACTION_KIND_BLOCKDEV_SNAPSHOT_SYNC);
1343 has_device = action->blockdev_snapshot_sync->has_device;
1344 device = action->blockdev_snapshot_sync->device;
1345 has_node_name = action->blockdev_snapshot_sync->has_node_name;
1346 node_name = action->blockdev_snapshot_sync->node_name;
1347 has_snapshot_node_name =
1348 action->blockdev_snapshot_sync->has_snapshot_node_name;
1349 snapshot_node_name = action->blockdev_snapshot_sync->snapshot_node_name;
1351 new_image_file = action->blockdev_snapshot_sync->snapshot_file;
1352 if (action->blockdev_snapshot_sync->has_format) {
1353 format = action->blockdev_snapshot_sync->format;
1355 if (action->blockdev_snapshot_sync->has_mode) {
1356 mode = action->blockdev_snapshot_sync->mode;
1359 /* start processing */
1360 drv = bdrv_find_format(format);
1361 if (!drv) {
1362 error_set(errp, QERR_INVALID_BLOCK_FORMAT, format);
1363 return;
1366 state->old_bs = bdrv_lookup_bs(has_device ? device : NULL,
1367 has_node_name ? node_name : NULL,
1368 &local_err);
1369 if (local_err) {
1370 error_propagate(errp, local_err);
1371 return;
1374 if (has_node_name && !has_snapshot_node_name) {
1375 error_setg(errp, "New snapshot node name missing");
1376 return;
1379 if (has_snapshot_node_name && bdrv_find_node(snapshot_node_name)) {
1380 error_setg(errp, "New snapshot node name already existing");
1381 return;
1384 if (!bdrv_is_inserted(state->old_bs)) {
1385 error_set(errp, QERR_DEVICE_HAS_NO_MEDIUM, device);
1386 return;
1389 if (bdrv_op_is_blocked(state->old_bs,
1390 BLOCK_OP_TYPE_EXTERNAL_SNAPSHOT, errp)) {
1391 return;
1394 if (!bdrv_is_read_only(state->old_bs)) {
1395 if (bdrv_flush(state->old_bs)) {
1396 error_set(errp, QERR_IO_ERROR);
1397 return;
1401 if (!bdrv_is_first_non_filter(state->old_bs)) {
1402 error_set(errp, QERR_FEATURE_DISABLED, "snapshot");
1403 return;
1406 flags = state->old_bs->open_flags;
1408 /* create new image w/backing file */
1409 if (mode != NEW_IMAGE_MODE_EXISTING) {
1410 bdrv_img_create(new_image_file, format,
1411 state->old_bs->filename,
1412 state->old_bs->drv->format_name,
1413 NULL, -1, flags, &local_err, false);
1414 if (local_err) {
1415 error_propagate(errp, local_err);
1416 return;
1420 if (has_snapshot_node_name) {
1421 options = qdict_new();
1422 qdict_put(options, "node-name",
1423 qstring_from_str(snapshot_node_name));
1426 /* TODO Inherit bs->options or only take explicit options with an
1427 * extended QMP command? */
1428 assert(state->new_bs == NULL);
1429 ret = bdrv_open(&state->new_bs, new_image_file, NULL, options,
1430 flags | BDRV_O_NO_BACKING, drv, &local_err);
1431 /* We will manually add the backing_hd field to the bs later */
1432 if (ret != 0) {
1433 error_propagate(errp, local_err);
1437 static void external_snapshot_commit(BlkTransactionState *common)
1439 ExternalSnapshotState *state =
1440 DO_UPCAST(ExternalSnapshotState, common, common);
1442 /* This removes our old bs and adds the new bs */
1443 bdrv_append(state->new_bs, state->old_bs);
1444 /* We don't need (or want) to use the transactional
1445 * bdrv_reopen_multiple() across all the entries at once, because we
1446 * don't want to abort all of them if one of them fails the reopen */
1447 bdrv_reopen(state->new_bs, state->new_bs->open_flags & ~BDRV_O_RDWR,
1448 NULL);
1451 static void external_snapshot_abort(BlkTransactionState *common)
1453 ExternalSnapshotState *state =
1454 DO_UPCAST(ExternalSnapshotState, common, common);
1455 if (state->new_bs) {
1456 bdrv_unref(state->new_bs);
1460 typedef struct DriveBackupState {
1461 BlkTransactionState common;
1462 BlockDriverState *bs;
1463 BlockJob *job;
1464 } DriveBackupState;
1466 static void drive_backup_prepare(BlkTransactionState *common, Error **errp)
1468 DriveBackupState *state = DO_UPCAST(DriveBackupState, common, common);
1469 DriveBackup *backup;
1470 Error *local_err = NULL;
1472 assert(common->action->kind == TRANSACTION_ACTION_KIND_DRIVE_BACKUP);
1473 backup = common->action->drive_backup;
1475 qmp_drive_backup(backup->device, backup->target,
1476 backup->has_format, backup->format,
1477 backup->sync,
1478 backup->has_mode, backup->mode,
1479 backup->has_speed, backup->speed,
1480 backup->has_on_source_error, backup->on_source_error,
1481 backup->has_on_target_error, backup->on_target_error,
1482 &local_err);
1483 if (local_err) {
1484 error_propagate(errp, local_err);
1485 state->bs = NULL;
1486 state->job = NULL;
1487 return;
1490 state->bs = bdrv_find(backup->device);
1491 state->job = state->bs->job;
1494 static void drive_backup_abort(BlkTransactionState *common)
1496 DriveBackupState *state = DO_UPCAST(DriveBackupState, common, common);
1497 BlockDriverState *bs = state->bs;
1499 /* Only cancel if it's the job we started */
1500 if (bs && bs->job && bs->job == state->job) {
1501 block_job_cancel_sync(bs->job);
1505 static void abort_prepare(BlkTransactionState *common, Error **errp)
1507 error_setg(errp, "Transaction aborted using Abort action");
1510 static void abort_commit(BlkTransactionState *common)
1512 g_assert_not_reached(); /* this action never succeeds */
1515 static const BdrvActionOps actions[] = {
1516 [TRANSACTION_ACTION_KIND_BLOCKDEV_SNAPSHOT_SYNC] = {
1517 .instance_size = sizeof(ExternalSnapshotState),
1518 .prepare = external_snapshot_prepare,
1519 .commit = external_snapshot_commit,
1520 .abort = external_snapshot_abort,
1522 [TRANSACTION_ACTION_KIND_DRIVE_BACKUP] = {
1523 .instance_size = sizeof(DriveBackupState),
1524 .prepare = drive_backup_prepare,
1525 .abort = drive_backup_abort,
1527 [TRANSACTION_ACTION_KIND_ABORT] = {
1528 .instance_size = sizeof(BlkTransactionState),
1529 .prepare = abort_prepare,
1530 .commit = abort_commit,
1532 [TRANSACTION_ACTION_KIND_BLOCKDEV_SNAPSHOT_INTERNAL_SYNC] = {
1533 .instance_size = sizeof(InternalSnapshotState),
1534 .prepare = internal_snapshot_prepare,
1535 .abort = internal_snapshot_abort,
1540 * 'Atomic' group snapshots. The snapshots are taken as a set, and if any fail
1541 * then we do not pivot any of the devices in the group, and abandon the
1542 * snapshots
1544 void qmp_transaction(TransactionActionList *dev_list, Error **errp)
1546 TransactionActionList *dev_entry = dev_list;
1547 BlkTransactionState *state, *next;
1548 Error *local_err = NULL;
1550 QSIMPLEQ_HEAD(snap_bdrv_states, BlkTransactionState) snap_bdrv_states;
1551 QSIMPLEQ_INIT(&snap_bdrv_states);
1553 /* drain all i/o before any snapshots */
1554 bdrv_drain_all();
1556 /* We don't do anything in this loop that commits us to the snapshot */
1557 while (NULL != dev_entry) {
1558 TransactionAction *dev_info = NULL;
1559 const BdrvActionOps *ops;
1561 dev_info = dev_entry->value;
1562 dev_entry = dev_entry->next;
1564 assert(dev_info->kind < ARRAY_SIZE(actions));
1566 ops = &actions[dev_info->kind];
1567 assert(ops->instance_size > 0);
1569 state = g_malloc0(ops->instance_size);
1570 state->ops = ops;
1571 state->action = dev_info;
1572 QSIMPLEQ_INSERT_TAIL(&snap_bdrv_states, state, entry);
1574 state->ops->prepare(state, &local_err);
1575 if (local_err) {
1576 error_propagate(errp, local_err);
1577 goto delete_and_fail;
1581 QSIMPLEQ_FOREACH(state, &snap_bdrv_states, entry) {
1582 if (state->ops->commit) {
1583 state->ops->commit(state);
1587 /* success */
1588 goto exit;
1590 delete_and_fail:
1592 * failure, and it is all-or-none; abandon each new bs, and keep using
1593 * the original bs for all images
1595 QSIMPLEQ_FOREACH(state, &snap_bdrv_states, entry) {
1596 if (state->ops->abort) {
1597 state->ops->abort(state);
1600 exit:
1601 QSIMPLEQ_FOREACH_SAFE(state, &snap_bdrv_states, entry, next) {
1602 if (state->ops->clean) {
1603 state->ops->clean(state);
1605 g_free(state);
1610 static void eject_device(BlockDriverState *bs, int force, Error **errp)
1612 if (bdrv_op_is_blocked(bs, BLOCK_OP_TYPE_EJECT, errp)) {
1613 return;
1615 if (!bdrv_dev_has_removable_media(bs)) {
1616 error_setg(errp, "Device '%s' is not removable",
1617 bdrv_get_device_name(bs));
1618 return;
1621 if (bdrv_dev_is_medium_locked(bs) && !bdrv_dev_is_tray_open(bs)) {
1622 bdrv_dev_eject_request(bs, force);
1623 if (!force) {
1624 error_setg(errp, "Device '%s' is locked",
1625 bdrv_get_device_name(bs));
1626 return;
1630 bdrv_close(bs);
1633 void qmp_eject(const char *device, bool has_force, bool force, Error **errp)
1635 BlockDriverState *bs;
1637 bs = bdrv_find(device);
1638 if (!bs) {
1639 error_set(errp, QERR_DEVICE_NOT_FOUND, device);
1640 return;
1643 eject_device(bs, force, errp);
1646 void qmp_block_passwd(bool has_device, const char *device,
1647 bool has_node_name, const char *node_name,
1648 const char *password, Error **errp)
1650 Error *local_err = NULL;
1651 BlockDriverState *bs;
1652 int err;
1654 bs = bdrv_lookup_bs(has_device ? device : NULL,
1655 has_node_name ? node_name : NULL,
1656 &local_err);
1657 if (local_err) {
1658 error_propagate(errp, local_err);
1659 return;
1662 err = bdrv_set_key(bs, password);
1663 if (err == -EINVAL) {
1664 error_set(errp, QERR_DEVICE_NOT_ENCRYPTED, bdrv_get_device_name(bs));
1665 return;
1666 } else if (err < 0) {
1667 error_set(errp, QERR_INVALID_PASSWORD);
1668 return;
1672 static void qmp_bdrv_open_encrypted(BlockDriverState *bs, const char *filename,
1673 int bdrv_flags, BlockDriver *drv,
1674 const char *password, Error **errp)
1676 Error *local_err = NULL;
1677 int ret;
1679 ret = bdrv_open(&bs, filename, NULL, NULL, bdrv_flags, drv, &local_err);
1680 if (ret < 0) {
1681 error_propagate(errp, local_err);
1682 return;
1685 if (bdrv_key_required(bs)) {
1686 if (password) {
1687 if (bdrv_set_key(bs, password) < 0) {
1688 error_set(errp, QERR_INVALID_PASSWORD);
1690 } else {
1691 error_set(errp, QERR_DEVICE_ENCRYPTED, bdrv_get_device_name(bs),
1692 bdrv_get_encrypted_filename(bs));
1694 } else if (password) {
1695 error_set(errp, QERR_DEVICE_NOT_ENCRYPTED, bdrv_get_device_name(bs));
1699 void qmp_change_blockdev(const char *device, const char *filename,
1700 const char *format, Error **errp)
1702 BlockDriverState *bs;
1703 BlockDriver *drv = NULL;
1704 int bdrv_flags;
1705 Error *err = NULL;
1707 bs = bdrv_find(device);
1708 if (!bs) {
1709 error_set(errp, QERR_DEVICE_NOT_FOUND, device);
1710 return;
1713 if (format) {
1714 drv = bdrv_find_whitelisted_format(format, bs->read_only);
1715 if (!drv) {
1716 error_set(errp, QERR_INVALID_BLOCK_FORMAT, format);
1717 return;
1721 eject_device(bs, 0, &err);
1722 if (err) {
1723 error_propagate(errp, err);
1724 return;
1727 bdrv_flags = bdrv_is_read_only(bs) ? 0 : BDRV_O_RDWR;
1728 bdrv_flags |= bdrv_is_snapshot(bs) ? BDRV_O_SNAPSHOT : 0;
1730 qmp_bdrv_open_encrypted(bs, filename, bdrv_flags, drv, NULL, errp);
1733 /* throttling disk I/O limits */
1734 void qmp_block_set_io_throttle(const char *device, int64_t bps, int64_t bps_rd,
1735 int64_t bps_wr,
1736 int64_t iops,
1737 int64_t iops_rd,
1738 int64_t iops_wr,
1739 bool has_bps_max,
1740 int64_t bps_max,
1741 bool has_bps_rd_max,
1742 int64_t bps_rd_max,
1743 bool has_bps_wr_max,
1744 int64_t bps_wr_max,
1745 bool has_iops_max,
1746 int64_t iops_max,
1747 bool has_iops_rd_max,
1748 int64_t iops_rd_max,
1749 bool has_iops_wr_max,
1750 int64_t iops_wr_max,
1751 bool has_iops_size,
1752 int64_t iops_size, Error **errp)
1754 ThrottleConfig cfg;
1755 BlockDriverState *bs;
1756 AioContext *aio_context;
1758 bs = bdrv_find(device);
1759 if (!bs) {
1760 error_set(errp, QERR_DEVICE_NOT_FOUND, device);
1761 return;
1764 memset(&cfg, 0, sizeof(cfg));
1765 cfg.buckets[THROTTLE_BPS_TOTAL].avg = bps;
1766 cfg.buckets[THROTTLE_BPS_READ].avg = bps_rd;
1767 cfg.buckets[THROTTLE_BPS_WRITE].avg = bps_wr;
1769 cfg.buckets[THROTTLE_OPS_TOTAL].avg = iops;
1770 cfg.buckets[THROTTLE_OPS_READ].avg = iops_rd;
1771 cfg.buckets[THROTTLE_OPS_WRITE].avg = iops_wr;
1773 if (has_bps_max) {
1774 cfg.buckets[THROTTLE_BPS_TOTAL].max = bps_max;
1776 if (has_bps_rd_max) {
1777 cfg.buckets[THROTTLE_BPS_READ].max = bps_rd_max;
1779 if (has_bps_wr_max) {
1780 cfg.buckets[THROTTLE_BPS_WRITE].max = bps_wr_max;
1782 if (has_iops_max) {
1783 cfg.buckets[THROTTLE_OPS_TOTAL].max = iops_max;
1785 if (has_iops_rd_max) {
1786 cfg.buckets[THROTTLE_OPS_READ].max = iops_rd_max;
1788 if (has_iops_wr_max) {
1789 cfg.buckets[THROTTLE_OPS_WRITE].max = iops_wr_max;
1792 if (has_iops_size) {
1793 cfg.op_size = iops_size;
1796 if (!check_throttle_config(&cfg, errp)) {
1797 return;
1800 aio_context = bdrv_get_aio_context(bs);
1801 aio_context_acquire(aio_context);
1803 if (!bs->io_limits_enabled && throttle_enabled(&cfg)) {
1804 bdrv_io_limits_enable(bs);
1805 } else if (bs->io_limits_enabled && !throttle_enabled(&cfg)) {
1806 bdrv_io_limits_disable(bs);
1809 if (bs->io_limits_enabled) {
1810 bdrv_set_io_limits(bs, &cfg);
1813 aio_context_release(aio_context);
1816 int do_drive_del(Monitor *mon, const QDict *qdict, QObject **ret_data)
1818 const char *id = qdict_get_str(qdict, "id");
1819 BlockBackend *blk;
1820 BlockDriverState *bs;
1821 DriveInfo *dinfo;
1822 AioContext *aio_context;
1823 Error *local_err = NULL;
1825 blk = blk_by_name(id);
1826 if (!blk) {
1827 error_report("Device '%s' not found", id);
1828 return -1;
1830 bs = blk_bs(blk);
1832 dinfo = blk_legacy_dinfo(blk);
1833 if (dinfo && !dinfo->enable_auto_del) {
1834 error_report("Deleting device added with blockdev-add"
1835 " is not supported");
1836 return -1;
1839 aio_context = bdrv_get_aio_context(bs);
1840 aio_context_acquire(aio_context);
1842 if (bdrv_op_is_blocked(bs, BLOCK_OP_TYPE_DRIVE_DEL, &local_err)) {
1843 error_report("%s", error_get_pretty(local_err));
1844 error_free(local_err);
1845 aio_context_release(aio_context);
1846 return -1;
1849 /* quiesce block driver; prevent further io */
1850 bdrv_drain_all();
1851 bdrv_flush(bs);
1852 bdrv_close(bs);
1854 /* if we have a device attached to this BlockDriverState
1855 * then we need to make the drive anonymous until the device
1856 * can be removed. If this is a drive with no device backing
1857 * then we can just get rid of the block driver state right here.
1859 if (bdrv_get_attached_dev(bs)) {
1860 blk_hide_on_behalf_of_do_drive_del(blk);
1861 /* Further I/O must not pause the guest */
1862 bdrv_set_on_error(bs, BLOCKDEV_ON_ERROR_REPORT,
1863 BLOCKDEV_ON_ERROR_REPORT);
1864 } else {
1865 blk_unref(blk);
1868 aio_context_release(aio_context);
1869 return 0;
1872 void qmp_block_resize(bool has_device, const char *device,
1873 bool has_node_name, const char *node_name,
1874 int64_t size, Error **errp)
1876 Error *local_err = NULL;
1877 BlockDriverState *bs;
1878 AioContext *aio_context;
1879 int ret;
1881 bs = bdrv_lookup_bs(has_device ? device : NULL,
1882 has_node_name ? node_name : NULL,
1883 &local_err);
1884 if (local_err) {
1885 error_propagate(errp, local_err);
1886 return;
1889 aio_context = bdrv_get_aio_context(bs);
1890 aio_context_acquire(aio_context);
1892 if (!bdrv_is_first_non_filter(bs)) {
1893 error_set(errp, QERR_FEATURE_DISABLED, "resize");
1894 goto out;
1897 if (size < 0) {
1898 error_set(errp, QERR_INVALID_PARAMETER_VALUE, "size", "a >0 size");
1899 goto out;
1902 if (bdrv_op_is_blocked(bs, BLOCK_OP_TYPE_RESIZE, NULL)) {
1903 error_set(errp, QERR_DEVICE_IN_USE, device);
1904 goto out;
1907 /* complete all in-flight operations before resizing the device */
1908 bdrv_drain_all();
1910 ret = bdrv_truncate(bs, size);
1911 switch (ret) {
1912 case 0:
1913 break;
1914 case -ENOMEDIUM:
1915 error_set(errp, QERR_DEVICE_HAS_NO_MEDIUM, device);
1916 break;
1917 case -ENOTSUP:
1918 error_set(errp, QERR_UNSUPPORTED);
1919 break;
1920 case -EACCES:
1921 error_set(errp, QERR_DEVICE_IS_READ_ONLY, device);
1922 break;
1923 case -EBUSY:
1924 error_set(errp, QERR_DEVICE_IN_USE, device);
1925 break;
1926 default:
1927 error_setg_errno(errp, -ret, "Could not resize");
1928 break;
1931 out:
1932 aio_context_release(aio_context);
1935 static void block_job_cb(void *opaque, int ret)
1937 BlockDriverState *bs = opaque;
1938 const char *msg = NULL;
1940 trace_block_job_cb(bs, bs->job, ret);
1942 assert(bs->job);
1944 if (ret < 0) {
1945 msg = strerror(-ret);
1948 if (block_job_is_cancelled(bs->job)) {
1949 block_job_event_cancelled(bs->job);
1950 } else {
1951 block_job_event_completed(bs->job, msg);
1954 bdrv_put_ref_bh_schedule(bs);
1957 void qmp_block_stream(const char *device,
1958 bool has_base, const char *base,
1959 bool has_backing_file, const char *backing_file,
1960 bool has_speed, int64_t speed,
1961 bool has_on_error, BlockdevOnError on_error,
1962 Error **errp)
1964 BlockDriverState *bs;
1965 BlockDriverState *base_bs = NULL;
1966 Error *local_err = NULL;
1967 const char *base_name = NULL;
1969 if (!has_on_error) {
1970 on_error = BLOCKDEV_ON_ERROR_REPORT;
1973 bs = bdrv_find(device);
1974 if (!bs) {
1975 error_set(errp, QERR_DEVICE_NOT_FOUND, device);
1976 return;
1979 if (bdrv_op_is_blocked(bs, BLOCK_OP_TYPE_STREAM, errp)) {
1980 return;
1983 if (has_base) {
1984 base_bs = bdrv_find_backing_image(bs, base);
1985 if (base_bs == NULL) {
1986 error_set(errp, QERR_BASE_NOT_FOUND, base);
1987 return;
1989 base_name = base;
1992 /* if we are streaming the entire chain, the result will have no backing
1993 * file, and specifying one is therefore an error */
1994 if (base_bs == NULL && has_backing_file) {
1995 error_setg(errp, "backing file specified, but streaming the "
1996 "entire chain");
1997 return;
2000 /* backing_file string overrides base bs filename */
2001 base_name = has_backing_file ? backing_file : base_name;
2003 stream_start(bs, base_bs, base_name, has_speed ? speed : 0,
2004 on_error, block_job_cb, bs, &local_err);
2005 if (local_err) {
2006 error_propagate(errp, local_err);
2007 return;
2010 trace_qmp_block_stream(bs, bs->job);
2013 void qmp_block_commit(const char *device,
2014 bool has_base, const char *base,
2015 bool has_top, const char *top,
2016 bool has_backing_file, const char *backing_file,
2017 bool has_speed, int64_t speed,
2018 Error **errp)
2020 BlockDriverState *bs;
2021 BlockDriverState *base_bs, *top_bs;
2022 Error *local_err = NULL;
2023 /* This will be part of the QMP command, if/when the
2024 * BlockdevOnError change for blkmirror makes it in
2026 BlockdevOnError on_error = BLOCKDEV_ON_ERROR_REPORT;
2028 if (!has_speed) {
2029 speed = 0;
2032 /* drain all i/o before commits */
2033 bdrv_drain_all();
2035 /* Important Note:
2036 * libvirt relies on the DeviceNotFound error class in order to probe for
2037 * live commit feature versions; for this to work, we must make sure to
2038 * perform the device lookup before any generic errors that may occur in a
2039 * scenario in which all optional arguments are omitted. */
2040 bs = bdrv_find(device);
2041 if (!bs) {
2042 error_set(errp, QERR_DEVICE_NOT_FOUND, device);
2043 return;
2046 if (bdrv_op_is_blocked(bs, BLOCK_OP_TYPE_COMMIT, errp)) {
2047 return;
2050 /* default top_bs is the active layer */
2051 top_bs = bs;
2053 if (has_top && top) {
2054 if (strcmp(bs->filename, top) != 0) {
2055 top_bs = bdrv_find_backing_image(bs, top);
2059 if (top_bs == NULL) {
2060 error_setg(errp, "Top image file %s not found", top ? top : "NULL");
2061 return;
2064 if (has_base && base) {
2065 base_bs = bdrv_find_backing_image(top_bs, base);
2066 } else {
2067 base_bs = bdrv_find_base(top_bs);
2070 if (base_bs == NULL) {
2071 error_set(errp, QERR_BASE_NOT_FOUND, base ? base : "NULL");
2072 return;
2075 /* Do not allow attempts to commit an image into itself */
2076 if (top_bs == base_bs) {
2077 error_setg(errp, "cannot commit an image into itself");
2078 return;
2081 if (top_bs == bs) {
2082 if (has_backing_file) {
2083 error_setg(errp, "'backing-file' specified,"
2084 " but 'top' is the active layer");
2085 return;
2087 commit_active_start(bs, base_bs, speed, on_error, block_job_cb,
2088 bs, &local_err);
2089 } else {
2090 commit_start(bs, base_bs, top_bs, speed, on_error, block_job_cb, bs,
2091 has_backing_file ? backing_file : NULL, &local_err);
2093 if (local_err != NULL) {
2094 error_propagate(errp, local_err);
2095 return;
2099 void qmp_drive_backup(const char *device, const char *target,
2100 bool has_format, const char *format,
2101 enum MirrorSyncMode sync,
2102 bool has_mode, enum NewImageMode mode,
2103 bool has_speed, int64_t speed,
2104 bool has_on_source_error, BlockdevOnError on_source_error,
2105 bool has_on_target_error, BlockdevOnError on_target_error,
2106 Error **errp)
2108 BlockDriverState *bs;
2109 BlockDriverState *target_bs;
2110 BlockDriverState *source = NULL;
2111 BlockDriver *drv = NULL;
2112 Error *local_err = NULL;
2113 int flags;
2114 int64_t size;
2115 int ret;
2117 if (!has_speed) {
2118 speed = 0;
2120 if (!has_on_source_error) {
2121 on_source_error = BLOCKDEV_ON_ERROR_REPORT;
2123 if (!has_on_target_error) {
2124 on_target_error = BLOCKDEV_ON_ERROR_REPORT;
2126 if (!has_mode) {
2127 mode = NEW_IMAGE_MODE_ABSOLUTE_PATHS;
2130 bs = bdrv_find(device);
2131 if (!bs) {
2132 error_set(errp, QERR_DEVICE_NOT_FOUND, device);
2133 return;
2136 if (!bdrv_is_inserted(bs)) {
2137 error_set(errp, QERR_DEVICE_HAS_NO_MEDIUM, device);
2138 return;
2141 if (!has_format) {
2142 format = mode == NEW_IMAGE_MODE_EXISTING ? NULL : bs->drv->format_name;
2144 if (format) {
2145 drv = bdrv_find_format(format);
2146 if (!drv) {
2147 error_set(errp, QERR_INVALID_BLOCK_FORMAT, format);
2148 return;
2152 if (bdrv_op_is_blocked(bs, BLOCK_OP_TYPE_BACKUP_SOURCE, errp)) {
2153 return;
2156 flags = bs->open_flags | BDRV_O_RDWR;
2158 /* See if we have a backing HD we can use to create our new image
2159 * on top of. */
2160 if (sync == MIRROR_SYNC_MODE_TOP) {
2161 source = bs->backing_hd;
2162 if (!source) {
2163 sync = MIRROR_SYNC_MODE_FULL;
2166 if (sync == MIRROR_SYNC_MODE_NONE) {
2167 source = bs;
2170 size = bdrv_getlength(bs);
2171 if (size < 0) {
2172 error_setg_errno(errp, -size, "bdrv_getlength failed");
2173 return;
2176 if (mode != NEW_IMAGE_MODE_EXISTING) {
2177 assert(format && drv);
2178 if (source) {
2179 bdrv_img_create(target, format, source->filename,
2180 source->drv->format_name, NULL,
2181 size, flags, &local_err, false);
2182 } else {
2183 bdrv_img_create(target, format, NULL, NULL, NULL,
2184 size, flags, &local_err, false);
2188 if (local_err) {
2189 error_propagate(errp, local_err);
2190 return;
2193 target_bs = NULL;
2194 ret = bdrv_open(&target_bs, target, NULL, NULL, flags, drv, &local_err);
2195 if (ret < 0) {
2196 error_propagate(errp, local_err);
2197 return;
2200 backup_start(bs, target_bs, speed, sync, on_source_error, on_target_error,
2201 block_job_cb, bs, &local_err);
2202 if (local_err != NULL) {
2203 bdrv_unref(target_bs);
2204 error_propagate(errp, local_err);
2205 return;
2209 BlockDeviceInfoList *qmp_query_named_block_nodes(Error **errp)
2211 return bdrv_named_nodes_list();
2214 #define DEFAULT_MIRROR_BUF_SIZE (10 << 20)
2216 void qmp_drive_mirror(const char *device, const char *target,
2217 bool has_format, const char *format,
2218 bool has_node_name, const char *node_name,
2219 bool has_replaces, const char *replaces,
2220 enum MirrorSyncMode sync,
2221 bool has_mode, enum NewImageMode mode,
2222 bool has_speed, int64_t speed,
2223 bool has_granularity, uint32_t granularity,
2224 bool has_buf_size, int64_t buf_size,
2225 bool has_on_source_error, BlockdevOnError on_source_error,
2226 bool has_on_target_error, BlockdevOnError on_target_error,
2227 Error **errp)
2229 BlockDriverState *bs;
2230 BlockDriverState *source, *target_bs;
2231 BlockDriver *drv = NULL;
2232 Error *local_err = NULL;
2233 QDict *options = NULL;
2234 int flags;
2235 int64_t size;
2236 int ret;
2238 if (!has_speed) {
2239 speed = 0;
2241 if (!has_on_source_error) {
2242 on_source_error = BLOCKDEV_ON_ERROR_REPORT;
2244 if (!has_on_target_error) {
2245 on_target_error = BLOCKDEV_ON_ERROR_REPORT;
2247 if (!has_mode) {
2248 mode = NEW_IMAGE_MODE_ABSOLUTE_PATHS;
2250 if (!has_granularity) {
2251 granularity = 0;
2253 if (!has_buf_size) {
2254 buf_size = DEFAULT_MIRROR_BUF_SIZE;
2257 if (granularity != 0 && (granularity < 512 || granularity > 1048576 * 64)) {
2258 error_set(errp, QERR_INVALID_PARAMETER_VALUE, "granularity",
2259 "a value in range [512B, 64MB]");
2260 return;
2262 if (granularity & (granularity - 1)) {
2263 error_set(errp, QERR_INVALID_PARAMETER_VALUE, "granularity", "power of 2");
2264 return;
2267 bs = bdrv_find(device);
2268 if (!bs) {
2269 error_set(errp, QERR_DEVICE_NOT_FOUND, device);
2270 return;
2273 if (!bdrv_is_inserted(bs)) {
2274 error_set(errp, QERR_DEVICE_HAS_NO_MEDIUM, device);
2275 return;
2278 if (!has_format) {
2279 format = mode == NEW_IMAGE_MODE_EXISTING ? NULL : bs->drv->format_name;
2281 if (format) {
2282 drv = bdrv_find_format(format);
2283 if (!drv) {
2284 error_set(errp, QERR_INVALID_BLOCK_FORMAT, format);
2285 return;
2289 if (bdrv_op_is_blocked(bs, BLOCK_OP_TYPE_MIRROR, errp)) {
2290 return;
2293 flags = bs->open_flags | BDRV_O_RDWR;
2294 source = bs->backing_hd;
2295 if (!source && sync == MIRROR_SYNC_MODE_TOP) {
2296 sync = MIRROR_SYNC_MODE_FULL;
2298 if (sync == MIRROR_SYNC_MODE_NONE) {
2299 source = bs;
2302 size = bdrv_getlength(bs);
2303 if (size < 0) {
2304 error_setg_errno(errp, -size, "bdrv_getlength failed");
2305 return;
2308 if (has_replaces) {
2309 BlockDriverState *to_replace_bs;
2311 if (!has_node_name) {
2312 error_setg(errp, "a node-name must be provided when replacing a"
2313 " named node of the graph");
2314 return;
2317 to_replace_bs = check_to_replace_node(replaces, &local_err);
2319 if (!to_replace_bs) {
2320 error_propagate(errp, local_err);
2321 return;
2324 if (size != bdrv_getlength(to_replace_bs)) {
2325 error_setg(errp, "cannot replace image with a mirror image of "
2326 "different size");
2327 return;
2331 if ((sync == MIRROR_SYNC_MODE_FULL || !source)
2332 && mode != NEW_IMAGE_MODE_EXISTING)
2334 /* create new image w/o backing file */
2335 assert(format && drv);
2336 bdrv_img_create(target, format,
2337 NULL, NULL, NULL, size, flags, &local_err, false);
2338 } else {
2339 switch (mode) {
2340 case NEW_IMAGE_MODE_EXISTING:
2341 break;
2342 case NEW_IMAGE_MODE_ABSOLUTE_PATHS:
2343 /* create new image with backing file */
2344 bdrv_img_create(target, format,
2345 source->filename,
2346 source->drv->format_name,
2347 NULL, size, flags, &local_err, false);
2348 break;
2349 default:
2350 abort();
2354 if (local_err) {
2355 error_propagate(errp, local_err);
2356 return;
2359 if (has_node_name) {
2360 options = qdict_new();
2361 qdict_put(options, "node-name", qstring_from_str(node_name));
2364 /* Mirroring takes care of copy-on-write using the source's backing
2365 * file.
2367 target_bs = NULL;
2368 ret = bdrv_open(&target_bs, target, NULL, options,
2369 flags | BDRV_O_NO_BACKING, drv, &local_err);
2370 if (ret < 0) {
2371 error_propagate(errp, local_err);
2372 return;
2375 /* pass the node name to replace to mirror start since it's loose coupling
2376 * and will allow to check whether the node still exist at mirror completion
2378 mirror_start(bs, target_bs,
2379 has_replaces ? replaces : NULL,
2380 speed, granularity, buf_size, sync,
2381 on_source_error, on_target_error,
2382 block_job_cb, bs, &local_err);
2383 if (local_err != NULL) {
2384 bdrv_unref(target_bs);
2385 error_propagate(errp, local_err);
2386 return;
2390 static BlockJob *find_block_job(const char *device)
2392 BlockDriverState *bs;
2394 bs = bdrv_find(device);
2395 if (!bs || !bs->job) {
2396 return NULL;
2398 return bs->job;
2401 void qmp_block_job_set_speed(const char *device, int64_t speed, Error **errp)
2403 BlockJob *job = find_block_job(device);
2405 if (!job) {
2406 error_set(errp, QERR_BLOCK_JOB_NOT_ACTIVE, device);
2407 return;
2410 block_job_set_speed(job, speed, errp);
2413 void qmp_block_job_cancel(const char *device,
2414 bool has_force, bool force, Error **errp)
2416 BlockJob *job = find_block_job(device);
2418 if (!has_force) {
2419 force = false;
2422 if (!job) {
2423 error_set(errp, QERR_BLOCK_JOB_NOT_ACTIVE, device);
2424 return;
2426 if (job->paused && !force) {
2427 error_setg(errp, "The block job for device '%s' is currently paused",
2428 device);
2429 return;
2432 trace_qmp_block_job_cancel(job);
2433 block_job_cancel(job);
2436 void qmp_block_job_pause(const char *device, Error **errp)
2438 BlockJob *job = find_block_job(device);
2440 if (!job) {
2441 error_set(errp, QERR_BLOCK_JOB_NOT_ACTIVE, device);
2442 return;
2445 trace_qmp_block_job_pause(job);
2446 block_job_pause(job);
2449 void qmp_block_job_resume(const char *device, Error **errp)
2451 BlockJob *job = find_block_job(device);
2453 if (!job) {
2454 error_set(errp, QERR_BLOCK_JOB_NOT_ACTIVE, device);
2455 return;
2458 trace_qmp_block_job_resume(job);
2459 block_job_resume(job);
2462 void qmp_block_job_complete(const char *device, Error **errp)
2464 BlockJob *job = find_block_job(device);
2466 if (!job) {
2467 error_set(errp, QERR_BLOCK_JOB_NOT_ACTIVE, device);
2468 return;
2471 trace_qmp_block_job_complete(job);
2472 block_job_complete(job, errp);
2475 void qmp_change_backing_file(const char *device,
2476 const char *image_node_name,
2477 const char *backing_file,
2478 Error **errp)
2480 BlockDriverState *bs = NULL;
2481 BlockDriverState *image_bs = NULL;
2482 Error *local_err = NULL;
2483 bool ro;
2484 int open_flags;
2485 int ret;
2487 /* find the top layer BDS of the chain */
2488 bs = bdrv_find(device);
2489 if (!bs) {
2490 error_set(errp, QERR_DEVICE_NOT_FOUND, device);
2491 return;
2494 image_bs = bdrv_lookup_bs(NULL, image_node_name, &local_err);
2495 if (local_err) {
2496 error_propagate(errp, local_err);
2497 return;
2500 if (!image_bs) {
2501 error_setg(errp, "image file not found");
2502 return;
2505 if (bdrv_find_base(image_bs) == image_bs) {
2506 error_setg(errp, "not allowing backing file change on an image "
2507 "without a backing file");
2508 return;
2511 /* even though we are not necessarily operating on bs, we need it to
2512 * determine if block ops are currently prohibited on the chain */
2513 if (bdrv_op_is_blocked(bs, BLOCK_OP_TYPE_CHANGE, errp)) {
2514 return;
2517 /* final sanity check */
2518 if (!bdrv_chain_contains(bs, image_bs)) {
2519 error_setg(errp, "'%s' and image file are not in the same chain",
2520 device);
2521 return;
2524 /* if not r/w, reopen to make r/w */
2525 open_flags = image_bs->open_flags;
2526 ro = bdrv_is_read_only(image_bs);
2528 if (ro) {
2529 bdrv_reopen(image_bs, open_flags | BDRV_O_RDWR, &local_err);
2530 if (local_err) {
2531 error_propagate(errp, local_err);
2532 return;
2536 ret = bdrv_change_backing_file(image_bs, backing_file,
2537 image_bs->drv ? image_bs->drv->format_name : "");
2539 if (ret < 0) {
2540 error_setg_errno(errp, -ret, "Could not change backing file to '%s'",
2541 backing_file);
2542 /* don't exit here, so we can try to restore open flags if
2543 * appropriate */
2546 if (ro) {
2547 bdrv_reopen(image_bs, open_flags, &local_err);
2548 if (local_err) {
2549 error_propagate(errp, local_err); /* will preserve prior errp */
2554 void qmp_blockdev_add(BlockdevOptions *options, Error **errp)
2556 QmpOutputVisitor *ov = qmp_output_visitor_new();
2557 BlockBackend *blk;
2558 QObject *obj;
2559 QDict *qdict;
2560 Error *local_err = NULL;
2562 /* Require an ID in the top level */
2563 if (!options->has_id) {
2564 error_setg(errp, "Block device needs an ID");
2565 goto fail;
2568 /* TODO Sort it out in raw-posix and drive_new(): Reject aio=native with
2569 * cache.direct=false instead of silently switching to aio=threads, except
2570 * when called from drive_new().
2572 * For now, simply forbidding the combination for all drivers will do. */
2573 if (options->has_aio && options->aio == BLOCKDEV_AIO_OPTIONS_NATIVE) {
2574 bool direct = options->has_cache &&
2575 options->cache->has_direct &&
2576 options->cache->direct;
2577 if (!direct) {
2578 error_setg(errp, "aio=native requires cache.direct=true");
2579 goto fail;
2583 visit_type_BlockdevOptions(qmp_output_get_visitor(ov),
2584 &options, NULL, &local_err);
2585 if (local_err) {
2586 error_propagate(errp, local_err);
2587 goto fail;
2590 obj = qmp_output_get_qobject(ov);
2591 qdict = qobject_to_qdict(obj);
2593 qdict_flatten(qdict);
2595 blk = blockdev_init(NULL, qdict, &local_err);
2596 if (local_err) {
2597 error_propagate(errp, local_err);
2598 goto fail;
2601 if (bdrv_key_required(blk_bs(blk))) {
2602 blk_unref(blk);
2603 error_setg(errp, "blockdev-add doesn't support encrypted devices");
2604 goto fail;
2607 fail:
2608 qmp_output_visitor_cleanup(ov);
2611 BlockJobInfoList *qmp_query_block_jobs(Error **errp)
2613 BlockJobInfoList *head = NULL, **p_next = &head;
2614 BlockDriverState *bs;
2616 for (bs = bdrv_next(NULL); bs; bs = bdrv_next(bs)) {
2617 if (bs->job) {
2618 BlockJobInfoList *elem = g_new0(BlockJobInfoList, 1);
2619 elem->value = block_job_query(bs->job);
2620 *p_next = elem;
2621 p_next = &elem->next;
2625 return head;
2628 QemuOptsList qemu_common_drive_opts = {
2629 .name = "drive",
2630 .head = QTAILQ_HEAD_INITIALIZER(qemu_common_drive_opts.head),
2631 .desc = {
2633 .name = "snapshot",
2634 .type = QEMU_OPT_BOOL,
2635 .help = "enable/disable snapshot mode",
2637 .name = "discard",
2638 .type = QEMU_OPT_STRING,
2639 .help = "discard operation (ignore/off, unmap/on)",
2641 .name = "cache.writeback",
2642 .type = QEMU_OPT_BOOL,
2643 .help = "enables writeback mode for any caches",
2645 .name = "cache.direct",
2646 .type = QEMU_OPT_BOOL,
2647 .help = "enables use of O_DIRECT (bypass the host page cache)",
2649 .name = "cache.no-flush",
2650 .type = QEMU_OPT_BOOL,
2651 .help = "ignore any flush requests for the device",
2653 .name = "aio",
2654 .type = QEMU_OPT_STRING,
2655 .help = "host AIO implementation (threads, native)",
2657 .name = "format",
2658 .type = QEMU_OPT_STRING,
2659 .help = "disk format (raw, qcow2, ...)",
2661 .name = "rerror",
2662 .type = QEMU_OPT_STRING,
2663 .help = "read error action",
2665 .name = "werror",
2666 .type = QEMU_OPT_STRING,
2667 .help = "write error action",
2669 .name = "read-only",
2670 .type = QEMU_OPT_BOOL,
2671 .help = "open drive file as read-only",
2673 .name = "throttling.iops-total",
2674 .type = QEMU_OPT_NUMBER,
2675 .help = "limit total I/O operations per second",
2677 .name = "throttling.iops-read",
2678 .type = QEMU_OPT_NUMBER,
2679 .help = "limit read operations per second",
2681 .name = "throttling.iops-write",
2682 .type = QEMU_OPT_NUMBER,
2683 .help = "limit write operations per second",
2685 .name = "throttling.bps-total",
2686 .type = QEMU_OPT_NUMBER,
2687 .help = "limit total bytes per second",
2689 .name = "throttling.bps-read",
2690 .type = QEMU_OPT_NUMBER,
2691 .help = "limit read bytes per second",
2693 .name = "throttling.bps-write",
2694 .type = QEMU_OPT_NUMBER,
2695 .help = "limit write bytes per second",
2697 .name = "throttling.iops-total-max",
2698 .type = QEMU_OPT_NUMBER,
2699 .help = "I/O operations burst",
2701 .name = "throttling.iops-read-max",
2702 .type = QEMU_OPT_NUMBER,
2703 .help = "I/O operations read burst",
2705 .name = "throttling.iops-write-max",
2706 .type = QEMU_OPT_NUMBER,
2707 .help = "I/O operations write burst",
2709 .name = "throttling.bps-total-max",
2710 .type = QEMU_OPT_NUMBER,
2711 .help = "total bytes burst",
2713 .name = "throttling.bps-read-max",
2714 .type = QEMU_OPT_NUMBER,
2715 .help = "total bytes read burst",
2717 .name = "throttling.bps-write-max",
2718 .type = QEMU_OPT_NUMBER,
2719 .help = "total bytes write burst",
2721 .name = "throttling.iops-size",
2722 .type = QEMU_OPT_NUMBER,
2723 .help = "when limiting by iops max size of an I/O in bytes",
2725 .name = "copy-on-read",
2726 .type = QEMU_OPT_BOOL,
2727 .help = "copy read data from backing file into image file",
2729 .name = "detect-zeroes",
2730 .type = QEMU_OPT_STRING,
2731 .help = "try to optimize zero writes (off, on, unmap)",
2733 { /* end of list */ }
2737 QemuOptsList qemu_drive_opts = {
2738 .name = "drive",
2739 .head = QTAILQ_HEAD_INITIALIZER(qemu_drive_opts.head),
2740 .desc = {
2742 * no elements => accept any params
2743 * validation will happen later
2745 { /* end of list */ }