kvm_stat: Add powerpc support
[qemu/ar7.git] / blockdev.c
blobeb743a956cf68cd7b40edb28138aeb1647b3a4c1
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(BlockBackend *blk)
116 DriveInfo *dinfo = blk_legacy_dinfo(blk);
117 BlockDriverState *bs = blk_bs(blk);
119 if (!dinfo) {
120 return;
123 if (bs->job) {
124 block_job_cancel(bs->job);
126 dinfo->auto_del = 1;
129 void blockdev_auto_del(BlockBackend *blk)
131 DriveInfo *dinfo = blk_legacy_dinfo(blk);
133 if (dinfo && dinfo->auto_del) {
134 blk_unref(blk);
139 * Returns the current mapping of how many units per bus
140 * a particular interface can support.
142 * A positive integer indicates n units per bus.
143 * 0 implies the mapping has not been established.
144 * -1 indicates an invalid BlockInterfaceType was given.
146 int drive_get_max_devs(BlockInterfaceType type)
148 if (type >= IF_IDE && type < IF_COUNT) {
149 return if_max_devs[type];
152 return -1;
155 static int drive_index_to_bus_id(BlockInterfaceType type, int index)
157 int max_devs = if_max_devs[type];
158 return max_devs ? index / max_devs : 0;
161 static int drive_index_to_unit_id(BlockInterfaceType type, int index)
163 int max_devs = if_max_devs[type];
164 return max_devs ? index % max_devs : index;
167 QemuOpts *drive_def(const char *optstr)
169 return qemu_opts_parse(qemu_find_opts("drive"), optstr, 0);
172 QemuOpts *drive_add(BlockInterfaceType type, int index, const char *file,
173 const char *optstr)
175 QemuOpts *opts;
176 char buf[32];
178 opts = drive_def(optstr);
179 if (!opts) {
180 return NULL;
182 if (type != IF_DEFAULT) {
183 qemu_opt_set(opts, "if", if_name[type]);
185 if (index >= 0) {
186 snprintf(buf, sizeof(buf), "%d", index);
187 qemu_opt_set(opts, "index", buf);
189 if (file)
190 qemu_opt_set(opts, "file", file);
191 return opts;
194 DriveInfo *drive_get(BlockInterfaceType type, int bus, int unit)
196 BlockBackend *blk;
197 DriveInfo *dinfo;
199 for (blk = blk_next(NULL); blk; blk = blk_next(blk)) {
200 dinfo = blk_legacy_dinfo(blk);
201 if (dinfo && dinfo->type == type
202 && dinfo->bus == bus && dinfo->unit == unit) {
203 return dinfo;
207 return NULL;
210 bool drive_check_orphaned(void)
212 BlockBackend *blk;
213 DriveInfo *dinfo;
214 bool rs = false;
216 for (blk = blk_next(NULL); blk; blk = blk_next(blk)) {
217 dinfo = blk_legacy_dinfo(blk);
218 /* If dinfo->bdrv->dev is NULL, it has no device attached. */
219 /* Unless this is a default drive, this may be an oversight. */
220 if (!blk_get_attached_dev(blk) && !dinfo->is_default &&
221 dinfo->type != IF_NONE) {
222 fprintf(stderr, "Warning: Orphaned drive without device: "
223 "id=%s,file=%s,if=%s,bus=%d,unit=%d\n",
224 blk_name(blk), blk_bs(blk)->filename, if_name[dinfo->type],
225 dinfo->bus, dinfo->unit);
226 rs = true;
230 return rs;
233 DriveInfo *drive_get_by_index(BlockInterfaceType type, int index)
235 return drive_get(type,
236 drive_index_to_bus_id(type, index),
237 drive_index_to_unit_id(type, index));
240 int drive_get_max_bus(BlockInterfaceType type)
242 int max_bus;
243 BlockBackend *blk;
244 DriveInfo *dinfo;
246 max_bus = -1;
247 for (blk = blk_next(NULL); blk; blk = blk_next(blk)) {
248 dinfo = blk_legacy_dinfo(blk);
249 if (dinfo && dinfo->type == type && dinfo->bus > max_bus) {
250 max_bus = dinfo->bus;
253 return max_bus;
256 /* Get a block device. This should only be used for single-drive devices
257 (e.g. SD/Floppy/MTD). Multi-disk devices (scsi/ide) should use the
258 appropriate bus. */
259 DriveInfo *drive_get_next(BlockInterfaceType type)
261 static int next_block_unit[IF_COUNT];
263 return drive_get(type, 0, next_block_unit[type]++);
266 static void bdrv_format_print(void *opaque, const char *name)
268 error_printf(" %s", name);
271 typedef struct {
272 QEMUBH *bh;
273 BlockDriverState *bs;
274 } BDRVPutRefBH;
276 static void bdrv_put_ref_bh(void *opaque)
278 BDRVPutRefBH *s = opaque;
280 bdrv_unref(s->bs);
281 qemu_bh_delete(s->bh);
282 g_free(s);
286 * Release a BDS reference in a BH
288 * It is not safe to use bdrv_unref() from a callback function when the callers
289 * still need the BlockDriverState. In such cases we schedule a BH to release
290 * the reference.
292 static void bdrv_put_ref_bh_schedule(BlockDriverState *bs)
294 BDRVPutRefBH *s;
296 s = g_new(BDRVPutRefBH, 1);
297 s->bh = qemu_bh_new(bdrv_put_ref_bh, s);
298 s->bs = bs;
299 qemu_bh_schedule(s->bh);
302 static int parse_block_error_action(const char *buf, bool is_read, Error **errp)
304 if (!strcmp(buf, "ignore")) {
305 return BLOCKDEV_ON_ERROR_IGNORE;
306 } else if (!is_read && !strcmp(buf, "enospc")) {
307 return BLOCKDEV_ON_ERROR_ENOSPC;
308 } else if (!strcmp(buf, "stop")) {
309 return BLOCKDEV_ON_ERROR_STOP;
310 } else if (!strcmp(buf, "report")) {
311 return BLOCKDEV_ON_ERROR_REPORT;
312 } else {
313 error_setg(errp, "'%s' invalid %s error action",
314 buf, is_read ? "read" : "write");
315 return -1;
319 static bool check_throttle_config(ThrottleConfig *cfg, Error **errp)
321 if (throttle_conflicting(cfg)) {
322 error_setg(errp, "bps/iops/max total values and read/write values"
323 " cannot be used at the same time");
324 return false;
327 if (!throttle_is_valid(cfg)) {
328 error_setg(errp, "bps/iops/maxs values must be 0 or greater");
329 return false;
332 return true;
335 typedef enum { MEDIA_DISK, MEDIA_CDROM } DriveMediaType;
337 /* Takes the ownership of bs_opts */
338 static BlockBackend *blockdev_init(const char *file, QDict *bs_opts,
339 Error **errp)
341 const char *buf;
342 int ro = 0;
343 int bdrv_flags = 0;
344 int on_read_error, on_write_error;
345 BlockBackend *blk;
346 BlockDriverState *bs;
347 ThrottleConfig cfg;
348 int snapshot = 0;
349 bool copy_on_read;
350 int ret;
351 Error *error = NULL;
352 QemuOpts *opts;
353 const char *id;
354 bool has_driver_specific_opts;
355 BlockdevDetectZeroesOptions detect_zeroes;
356 BlockDriver *drv = NULL;
358 /* Check common options by copying from bs_opts to opts, all other options
359 * stay in bs_opts for processing by bdrv_open(). */
360 id = qdict_get_try_str(bs_opts, "id");
361 opts = qemu_opts_create(&qemu_common_drive_opts, id, 1, &error);
362 if (error) {
363 error_propagate(errp, error);
364 goto err_no_opts;
367 qemu_opts_absorb_qdict(opts, bs_opts, &error);
368 if (error) {
369 error_propagate(errp, error);
370 goto early_err;
373 if (id) {
374 qdict_del(bs_opts, "id");
377 has_driver_specific_opts = !!qdict_size(bs_opts);
379 /* extract parameters */
380 snapshot = qemu_opt_get_bool(opts, "snapshot", 0);
381 ro = qemu_opt_get_bool(opts, "read-only", 0);
382 copy_on_read = qemu_opt_get_bool(opts, "copy-on-read", false);
384 if ((buf = qemu_opt_get(opts, "discard")) != NULL) {
385 if (bdrv_parse_discard_flags(buf, &bdrv_flags) != 0) {
386 error_setg(errp, "invalid discard option");
387 goto early_err;
391 if (qemu_opt_get_bool(opts, "cache.writeback", true)) {
392 bdrv_flags |= BDRV_O_CACHE_WB;
394 if (qemu_opt_get_bool(opts, "cache.direct", false)) {
395 bdrv_flags |= BDRV_O_NOCACHE;
397 if (qemu_opt_get_bool(opts, "cache.no-flush", false)) {
398 bdrv_flags |= BDRV_O_NO_FLUSH;
401 #ifdef CONFIG_LINUX_AIO
402 if ((buf = qemu_opt_get(opts, "aio")) != NULL) {
403 if (!strcmp(buf, "native")) {
404 bdrv_flags |= BDRV_O_NATIVE_AIO;
405 } else if (!strcmp(buf, "threads")) {
406 /* this is the default */
407 } else {
408 error_setg(errp, "invalid aio option");
409 goto early_err;
412 #endif
414 if ((buf = qemu_opt_get(opts, "format")) != NULL) {
415 if (is_help_option(buf)) {
416 error_printf("Supported formats:");
417 bdrv_iterate_format(bdrv_format_print, NULL);
418 error_printf("\n");
419 goto early_err;
422 drv = bdrv_find_format(buf);
423 if (!drv) {
424 error_setg(errp, "'%s' invalid format", buf);
425 goto early_err;
429 /* disk I/O throttling */
430 memset(&cfg, 0, sizeof(cfg));
431 cfg.buckets[THROTTLE_BPS_TOTAL].avg =
432 qemu_opt_get_number(opts, "throttling.bps-total", 0);
433 cfg.buckets[THROTTLE_BPS_READ].avg =
434 qemu_opt_get_number(opts, "throttling.bps-read", 0);
435 cfg.buckets[THROTTLE_BPS_WRITE].avg =
436 qemu_opt_get_number(opts, "throttling.bps-write", 0);
437 cfg.buckets[THROTTLE_OPS_TOTAL].avg =
438 qemu_opt_get_number(opts, "throttling.iops-total", 0);
439 cfg.buckets[THROTTLE_OPS_READ].avg =
440 qemu_opt_get_number(opts, "throttling.iops-read", 0);
441 cfg.buckets[THROTTLE_OPS_WRITE].avg =
442 qemu_opt_get_number(opts, "throttling.iops-write", 0);
444 cfg.buckets[THROTTLE_BPS_TOTAL].max =
445 qemu_opt_get_number(opts, "throttling.bps-total-max", 0);
446 cfg.buckets[THROTTLE_BPS_READ].max =
447 qemu_opt_get_number(opts, "throttling.bps-read-max", 0);
448 cfg.buckets[THROTTLE_BPS_WRITE].max =
449 qemu_opt_get_number(opts, "throttling.bps-write-max", 0);
450 cfg.buckets[THROTTLE_OPS_TOTAL].max =
451 qemu_opt_get_number(opts, "throttling.iops-total-max", 0);
452 cfg.buckets[THROTTLE_OPS_READ].max =
453 qemu_opt_get_number(opts, "throttling.iops-read-max", 0);
454 cfg.buckets[THROTTLE_OPS_WRITE].max =
455 qemu_opt_get_number(opts, "throttling.iops-write-max", 0);
457 cfg.op_size = qemu_opt_get_number(opts, "throttling.iops-size", 0);
459 if (!check_throttle_config(&cfg, &error)) {
460 error_propagate(errp, error);
461 goto early_err;
464 on_write_error = BLOCKDEV_ON_ERROR_ENOSPC;
465 if ((buf = qemu_opt_get(opts, "werror")) != NULL) {
466 on_write_error = parse_block_error_action(buf, 0, &error);
467 if (error) {
468 error_propagate(errp, error);
469 goto early_err;
473 on_read_error = BLOCKDEV_ON_ERROR_REPORT;
474 if ((buf = qemu_opt_get(opts, "rerror")) != NULL) {
475 on_read_error = parse_block_error_action(buf, 1, &error);
476 if (error) {
477 error_propagate(errp, error);
478 goto early_err;
482 detect_zeroes =
483 qapi_enum_parse(BlockdevDetectZeroesOptions_lookup,
484 qemu_opt_get(opts, "detect-zeroes"),
485 BLOCKDEV_DETECT_ZEROES_OPTIONS_MAX,
486 BLOCKDEV_DETECT_ZEROES_OPTIONS_OFF,
487 &error);
488 if (error) {
489 error_propagate(errp, error);
490 goto early_err;
493 if (detect_zeroes == BLOCKDEV_DETECT_ZEROES_OPTIONS_UNMAP &&
494 !(bdrv_flags & BDRV_O_UNMAP)) {
495 error_setg(errp, "setting detect-zeroes to unmap is not allowed "
496 "without setting discard operation to unmap");
497 goto early_err;
500 /* init */
501 blk = blk_new_with_bs(qemu_opts_id(opts), errp);
502 if (!blk) {
503 goto early_err;
505 bs = blk_bs(blk);
506 bs->open_flags = snapshot ? BDRV_O_SNAPSHOT : 0;
507 bs->read_only = ro;
508 bs->detect_zeroes = detect_zeroes;
510 bdrv_set_on_error(bs, on_read_error, on_write_error);
512 /* disk I/O throttling */
513 if (throttle_enabled(&cfg)) {
514 bdrv_io_limits_enable(bs);
515 bdrv_set_io_limits(bs, &cfg);
518 if (!file || !*file) {
519 if (has_driver_specific_opts) {
520 file = NULL;
521 } else {
522 QDECREF(bs_opts);
523 qemu_opts_del(opts);
524 return blk;
527 if (snapshot) {
528 /* always use cache=unsafe with snapshot */
529 bdrv_flags &= ~BDRV_O_CACHE_MASK;
530 bdrv_flags |= (BDRV_O_SNAPSHOT|BDRV_O_CACHE_WB|BDRV_O_NO_FLUSH);
533 if (copy_on_read) {
534 bdrv_flags |= BDRV_O_COPY_ON_READ;
537 if (runstate_check(RUN_STATE_INMIGRATE)) {
538 bdrv_flags |= BDRV_O_INCOMING;
541 bdrv_flags |= ro ? 0 : BDRV_O_RDWR;
543 QINCREF(bs_opts);
544 ret = bdrv_open(&bs, file, NULL, bs_opts, bdrv_flags, drv, &error);
545 assert(bs == blk_bs(blk));
547 if (ret < 0) {
548 error_setg(errp, "could not open disk image %s: %s",
549 file ?: blk_name(blk), error_get_pretty(error));
550 error_free(error);
551 goto err;
554 if (bdrv_key_required(bs)) {
555 autostart = 0;
558 QDECREF(bs_opts);
559 qemu_opts_del(opts);
561 return blk;
563 err:
564 blk_unref(blk);
565 early_err:
566 qemu_opts_del(opts);
567 err_no_opts:
568 QDECREF(bs_opts);
569 return NULL;
572 static void qemu_opt_rename(QemuOpts *opts, const char *from, const char *to,
573 Error **errp)
575 const char *value;
577 value = qemu_opt_get(opts, from);
578 if (value) {
579 if (qemu_opt_find(opts, to)) {
580 error_setg(errp, "'%s' and its alias '%s' can't be used at the "
581 "same time", to, from);
582 return;
586 /* rename all items in opts */
587 while ((value = qemu_opt_get(opts, from))) {
588 qemu_opt_set(opts, to, value);
589 qemu_opt_unset(opts, from);
593 QemuOptsList qemu_legacy_drive_opts = {
594 .name = "drive",
595 .head = QTAILQ_HEAD_INITIALIZER(qemu_legacy_drive_opts.head),
596 .desc = {
598 .name = "bus",
599 .type = QEMU_OPT_NUMBER,
600 .help = "bus number",
602 .name = "unit",
603 .type = QEMU_OPT_NUMBER,
604 .help = "unit number (i.e. lun for scsi)",
606 .name = "index",
607 .type = QEMU_OPT_NUMBER,
608 .help = "index number",
610 .name = "media",
611 .type = QEMU_OPT_STRING,
612 .help = "media type (disk, cdrom)",
614 .name = "if",
615 .type = QEMU_OPT_STRING,
616 .help = "interface (ide, scsi, sd, mtd, floppy, pflash, virtio)",
618 .name = "cyls",
619 .type = QEMU_OPT_NUMBER,
620 .help = "number of cylinders (ide disk geometry)",
622 .name = "heads",
623 .type = QEMU_OPT_NUMBER,
624 .help = "number of heads (ide disk geometry)",
626 .name = "secs",
627 .type = QEMU_OPT_NUMBER,
628 .help = "number of sectors (ide disk geometry)",
630 .name = "trans",
631 .type = QEMU_OPT_STRING,
632 .help = "chs translation (auto, lba, none)",
634 .name = "boot",
635 .type = QEMU_OPT_BOOL,
636 .help = "(deprecated, ignored)",
638 .name = "addr",
639 .type = QEMU_OPT_STRING,
640 .help = "pci address (virtio only)",
642 .name = "serial",
643 .type = QEMU_OPT_STRING,
644 .help = "disk serial number",
646 .name = "file",
647 .type = QEMU_OPT_STRING,
648 .help = "file name",
651 /* Options that are passed on, but have special semantics with -drive */
653 .name = "read-only",
654 .type = QEMU_OPT_BOOL,
655 .help = "open drive file as read-only",
657 .name = "rerror",
658 .type = QEMU_OPT_STRING,
659 .help = "read error action",
661 .name = "werror",
662 .type = QEMU_OPT_STRING,
663 .help = "write error action",
665 .name = "copy-on-read",
666 .type = QEMU_OPT_BOOL,
667 .help = "copy read data from backing file into image file",
670 { /* end of list */ }
674 DriveInfo *drive_new(QemuOpts *all_opts, BlockInterfaceType block_default_type)
676 const char *value;
677 BlockBackend *blk;
678 DriveInfo *dinfo = NULL;
679 QDict *bs_opts;
680 QemuOpts *legacy_opts;
681 DriveMediaType media = MEDIA_DISK;
682 BlockInterfaceType type;
683 int cyls, heads, secs, translation;
684 int max_devs, bus_id, unit_id, index;
685 const char *devaddr;
686 const char *werror, *rerror;
687 bool read_only = false;
688 bool copy_on_read;
689 const char *serial;
690 const char *filename;
691 Error *local_err = NULL;
692 int i;
694 /* Change legacy command line options into QMP ones */
695 static const struct {
696 const char *from;
697 const char *to;
698 } opt_renames[] = {
699 { "iops", "throttling.iops-total" },
700 { "iops_rd", "throttling.iops-read" },
701 { "iops_wr", "throttling.iops-write" },
703 { "bps", "throttling.bps-total" },
704 { "bps_rd", "throttling.bps-read" },
705 { "bps_wr", "throttling.bps-write" },
707 { "iops_max", "throttling.iops-total-max" },
708 { "iops_rd_max", "throttling.iops-read-max" },
709 { "iops_wr_max", "throttling.iops-write-max" },
711 { "bps_max", "throttling.bps-total-max" },
712 { "bps_rd_max", "throttling.bps-read-max" },
713 { "bps_wr_max", "throttling.bps-write-max" },
715 { "iops_size", "throttling.iops-size" },
717 { "readonly", "read-only" },
720 for (i = 0; i < ARRAY_SIZE(opt_renames); i++) {
721 qemu_opt_rename(all_opts, opt_renames[i].from, opt_renames[i].to,
722 &local_err);
723 if (local_err) {
724 error_report("%s", error_get_pretty(local_err));
725 error_free(local_err);
726 return NULL;
730 value = qemu_opt_get(all_opts, "cache");
731 if (value) {
732 int flags = 0;
734 if (bdrv_parse_cache_flags(value, &flags) != 0) {
735 error_report("invalid cache option");
736 return NULL;
739 /* Specific options take precedence */
740 if (!qemu_opt_get(all_opts, "cache.writeback")) {
741 qemu_opt_set_bool(all_opts, "cache.writeback",
742 !!(flags & BDRV_O_CACHE_WB));
744 if (!qemu_opt_get(all_opts, "cache.direct")) {
745 qemu_opt_set_bool(all_opts, "cache.direct",
746 !!(flags & BDRV_O_NOCACHE));
748 if (!qemu_opt_get(all_opts, "cache.no-flush")) {
749 qemu_opt_set_bool(all_opts, "cache.no-flush",
750 !!(flags & BDRV_O_NO_FLUSH));
752 qemu_opt_unset(all_opts, "cache");
755 /* Get a QDict for processing the options */
756 bs_opts = qdict_new();
757 qemu_opts_to_qdict(all_opts, bs_opts);
759 legacy_opts = qemu_opts_create(&qemu_legacy_drive_opts, NULL, 0,
760 &error_abort);
761 qemu_opts_absorb_qdict(legacy_opts, bs_opts, &local_err);
762 if (local_err) {
763 error_report("%s", error_get_pretty(local_err));
764 error_free(local_err);
765 goto fail;
768 /* Deprecated option boot=[on|off] */
769 if (qemu_opt_get(legacy_opts, "boot") != NULL) {
770 fprintf(stderr, "qemu-kvm: boot=on|off is deprecated and will be "
771 "ignored. Future versions will reject this parameter. Please "
772 "update your scripts.\n");
775 /* Media type */
776 value = qemu_opt_get(legacy_opts, "media");
777 if (value) {
778 if (!strcmp(value, "disk")) {
779 media = MEDIA_DISK;
780 } else if (!strcmp(value, "cdrom")) {
781 media = MEDIA_CDROM;
782 read_only = true;
783 } else {
784 error_report("'%s' invalid media", value);
785 goto fail;
789 /* copy-on-read is disabled with a warning for read-only devices */
790 read_only |= qemu_opt_get_bool(legacy_opts, "read-only", false);
791 copy_on_read = qemu_opt_get_bool(legacy_opts, "copy-on-read", false);
793 if (read_only && copy_on_read) {
794 error_report("warning: disabling copy-on-read on read-only drive");
795 copy_on_read = false;
798 qdict_put(bs_opts, "read-only",
799 qstring_from_str(read_only ? "on" : "off"));
800 qdict_put(bs_opts, "copy-on-read",
801 qstring_from_str(copy_on_read ? "on" :"off"));
803 /* Controller type */
804 value = qemu_opt_get(legacy_opts, "if");
805 if (value) {
806 for (type = 0;
807 type < IF_COUNT && strcmp(value, if_name[type]);
808 type++) {
810 if (type == IF_COUNT) {
811 error_report("unsupported bus type '%s'", value);
812 goto fail;
814 } else {
815 type = block_default_type;
818 /* Geometry */
819 cyls = qemu_opt_get_number(legacy_opts, "cyls", 0);
820 heads = qemu_opt_get_number(legacy_opts, "heads", 0);
821 secs = qemu_opt_get_number(legacy_opts, "secs", 0);
823 if (cyls || heads || secs) {
824 if (cyls < 1) {
825 error_report("invalid physical cyls number");
826 goto fail;
828 if (heads < 1) {
829 error_report("invalid physical heads number");
830 goto fail;
832 if (secs < 1) {
833 error_report("invalid physical secs number");
834 goto fail;
838 translation = BIOS_ATA_TRANSLATION_AUTO;
839 value = qemu_opt_get(legacy_opts, "trans");
840 if (value != NULL) {
841 if (!cyls) {
842 error_report("'%s' trans must be used with cyls, heads and secs",
843 value);
844 goto fail;
846 if (!strcmp(value, "none")) {
847 translation = BIOS_ATA_TRANSLATION_NONE;
848 } else if (!strcmp(value, "lba")) {
849 translation = BIOS_ATA_TRANSLATION_LBA;
850 } else if (!strcmp(value, "large")) {
851 translation = BIOS_ATA_TRANSLATION_LARGE;
852 } else if (!strcmp(value, "rechs")) {
853 translation = BIOS_ATA_TRANSLATION_RECHS;
854 } else if (!strcmp(value, "auto")) {
855 translation = BIOS_ATA_TRANSLATION_AUTO;
856 } else {
857 error_report("'%s' invalid translation type", value);
858 goto fail;
862 if (media == MEDIA_CDROM) {
863 if (cyls || secs || heads) {
864 error_report("CHS can't be set with media=cdrom");
865 goto fail;
869 /* Device address specified by bus/unit or index.
870 * If none was specified, try to find the first free one. */
871 bus_id = qemu_opt_get_number(legacy_opts, "bus", 0);
872 unit_id = qemu_opt_get_number(legacy_opts, "unit", -1);
873 index = qemu_opt_get_number(legacy_opts, "index", -1);
875 max_devs = if_max_devs[type];
877 if (index != -1) {
878 if (bus_id != 0 || unit_id != -1) {
879 error_report("index cannot be used with bus and unit");
880 goto fail;
882 bus_id = drive_index_to_bus_id(type, index);
883 unit_id = drive_index_to_unit_id(type, index);
886 if (unit_id == -1) {
887 unit_id = 0;
888 while (drive_get(type, bus_id, unit_id) != NULL) {
889 unit_id++;
890 if (max_devs && unit_id >= max_devs) {
891 unit_id -= max_devs;
892 bus_id++;
897 if (max_devs && unit_id >= max_devs) {
898 error_report("unit %d too big (max is %d)", unit_id, max_devs - 1);
899 goto fail;
902 if (drive_get(type, bus_id, unit_id) != NULL) {
903 error_report("drive with bus=%d, unit=%d (index=%d) exists",
904 bus_id, unit_id, index);
905 goto fail;
908 /* Serial number */
909 serial = qemu_opt_get(legacy_opts, "serial");
911 /* no id supplied -> create one */
912 if (qemu_opts_id(all_opts) == NULL) {
913 char *new_id;
914 const char *mediastr = "";
915 if (type == IF_IDE || type == IF_SCSI) {
916 mediastr = (media == MEDIA_CDROM) ? "-cd" : "-hd";
918 if (max_devs) {
919 new_id = g_strdup_printf("%s%i%s%i", if_name[type], bus_id,
920 mediastr, unit_id);
921 } else {
922 new_id = g_strdup_printf("%s%s%i", if_name[type],
923 mediastr, unit_id);
925 qdict_put(bs_opts, "id", qstring_from_str(new_id));
926 g_free(new_id);
929 /* Add virtio block device */
930 devaddr = qemu_opt_get(legacy_opts, "addr");
931 if (devaddr && type != IF_VIRTIO) {
932 error_report("addr is not supported by this bus type");
933 goto fail;
936 if (type == IF_VIRTIO) {
937 QemuOpts *devopts;
938 devopts = qemu_opts_create(qemu_find_opts("device"), NULL, 0,
939 &error_abort);
940 if (arch_type == QEMU_ARCH_S390X) {
941 qemu_opt_set(devopts, "driver", "virtio-blk-s390");
942 } else {
943 qemu_opt_set(devopts, "driver", "virtio-blk-pci");
945 qemu_opt_set(devopts, "drive", qdict_get_str(bs_opts, "id"));
946 if (devaddr) {
947 qemu_opt_set(devopts, "addr", devaddr);
951 filename = qemu_opt_get(legacy_opts, "file");
953 /* Check werror/rerror compatibility with if=... */
954 werror = qemu_opt_get(legacy_opts, "werror");
955 if (werror != NULL) {
956 if (type != IF_IDE && type != IF_SCSI && type != IF_VIRTIO &&
957 type != IF_NONE) {
958 error_report("werror is not supported by this bus type");
959 goto fail;
961 qdict_put(bs_opts, "werror", qstring_from_str(werror));
964 rerror = qemu_opt_get(legacy_opts, "rerror");
965 if (rerror != NULL) {
966 if (type != IF_IDE && type != IF_VIRTIO && type != IF_SCSI &&
967 type != IF_NONE) {
968 error_report("rerror is not supported by this bus type");
969 goto fail;
971 qdict_put(bs_opts, "rerror", qstring_from_str(rerror));
974 /* Actual block device init: Functionality shared with blockdev-add */
975 blk = blockdev_init(filename, bs_opts, &local_err);
976 bs_opts = NULL;
977 if (!blk) {
978 if (local_err) {
979 error_report("%s", error_get_pretty(local_err));
980 error_free(local_err);
982 goto fail;
983 } else {
984 assert(!local_err);
987 /* Create legacy DriveInfo */
988 dinfo = g_malloc0(sizeof(*dinfo));
989 dinfo->opts = all_opts;
991 dinfo->cyls = cyls;
992 dinfo->heads = heads;
993 dinfo->secs = secs;
994 dinfo->trans = translation;
996 dinfo->type = type;
997 dinfo->bus = bus_id;
998 dinfo->unit = unit_id;
999 dinfo->devaddr = devaddr;
1000 dinfo->serial = g_strdup(serial);
1002 blk_set_legacy_dinfo(blk, dinfo);
1004 switch(type) {
1005 case IF_IDE:
1006 case IF_SCSI:
1007 case IF_XEN:
1008 case IF_NONE:
1009 dinfo->media_cd = media == MEDIA_CDROM;
1010 break;
1011 default:
1012 break;
1015 fail:
1016 qemu_opts_del(legacy_opts);
1017 QDECREF(bs_opts);
1018 return dinfo;
1021 void do_commit(Monitor *mon, const QDict *qdict)
1023 const char *device = qdict_get_str(qdict, "device");
1024 BlockDriverState *bs;
1025 int ret;
1027 if (!strcmp(device, "all")) {
1028 ret = bdrv_commit_all();
1029 } else {
1030 bs = bdrv_find(device);
1031 if (!bs) {
1032 monitor_printf(mon, "Device '%s' not found\n", device);
1033 return;
1035 ret = bdrv_commit(bs);
1037 if (ret < 0) {
1038 monitor_printf(mon, "'commit' error for '%s': %s\n", device,
1039 strerror(-ret));
1043 static void blockdev_do_action(int kind, void *data, Error **errp)
1045 TransactionAction action;
1046 TransactionActionList list;
1048 action.kind = kind;
1049 action.data = data;
1050 list.value = &action;
1051 list.next = NULL;
1052 qmp_transaction(&list, errp);
1055 void qmp_blockdev_snapshot_sync(bool has_device, const char *device,
1056 bool has_node_name, const char *node_name,
1057 const char *snapshot_file,
1058 bool has_snapshot_node_name,
1059 const char *snapshot_node_name,
1060 bool has_format, const char *format,
1061 bool has_mode, NewImageMode mode, Error **errp)
1063 BlockdevSnapshot snapshot = {
1064 .has_device = has_device,
1065 .device = (char *) device,
1066 .has_node_name = has_node_name,
1067 .node_name = (char *) node_name,
1068 .snapshot_file = (char *) snapshot_file,
1069 .has_snapshot_node_name = has_snapshot_node_name,
1070 .snapshot_node_name = (char *) snapshot_node_name,
1071 .has_format = has_format,
1072 .format = (char *) format,
1073 .has_mode = has_mode,
1074 .mode = mode,
1076 blockdev_do_action(TRANSACTION_ACTION_KIND_BLOCKDEV_SNAPSHOT_SYNC,
1077 &snapshot, errp);
1080 void qmp_blockdev_snapshot_internal_sync(const char *device,
1081 const char *name,
1082 Error **errp)
1084 BlockdevSnapshotInternal snapshot = {
1085 .device = (char *) device,
1086 .name = (char *) name
1089 blockdev_do_action(TRANSACTION_ACTION_KIND_BLOCKDEV_SNAPSHOT_INTERNAL_SYNC,
1090 &snapshot, errp);
1093 SnapshotInfo *qmp_blockdev_snapshot_delete_internal_sync(const char *device,
1094 bool has_id,
1095 const char *id,
1096 bool has_name,
1097 const char *name,
1098 Error **errp)
1100 BlockDriverState *bs = bdrv_find(device);
1101 QEMUSnapshotInfo sn;
1102 Error *local_err = NULL;
1103 SnapshotInfo *info = NULL;
1104 int ret;
1106 if (!bs) {
1107 error_set(errp, QERR_DEVICE_NOT_FOUND, device);
1108 return NULL;
1111 if (!has_id) {
1112 id = NULL;
1115 if (!has_name) {
1116 name = NULL;
1119 if (!id && !name) {
1120 error_setg(errp, "Name or id must be provided");
1121 return NULL;
1124 ret = bdrv_snapshot_find_by_id_and_name(bs, id, name, &sn, &local_err);
1125 if (local_err) {
1126 error_propagate(errp, local_err);
1127 return NULL;
1129 if (!ret) {
1130 error_setg(errp,
1131 "Snapshot with id '%s' and name '%s' does not exist on "
1132 "device '%s'",
1133 STR_OR_NULL(id), STR_OR_NULL(name), device);
1134 return NULL;
1137 bdrv_snapshot_delete(bs, id, name, &local_err);
1138 if (local_err) {
1139 error_propagate(errp, local_err);
1140 return NULL;
1143 info = g_new0(SnapshotInfo, 1);
1144 info->id = g_strdup(sn.id_str);
1145 info->name = g_strdup(sn.name);
1146 info->date_nsec = sn.date_nsec;
1147 info->date_sec = sn.date_sec;
1148 info->vm_state_size = sn.vm_state_size;
1149 info->vm_clock_nsec = sn.vm_clock_nsec % 1000000000;
1150 info->vm_clock_sec = sn.vm_clock_nsec / 1000000000;
1152 return info;
1155 /* New and old BlockDriverState structs for group snapshots */
1157 typedef struct BlkTransactionState BlkTransactionState;
1159 /* Only prepare() may fail. In a single transaction, only one of commit() or
1160 abort() will be called, clean() will always be called if it present. */
1161 typedef struct BdrvActionOps {
1162 /* Size of state struct, in bytes. */
1163 size_t instance_size;
1164 /* Prepare the work, must NOT be NULL. */
1165 void (*prepare)(BlkTransactionState *common, Error **errp);
1166 /* Commit the changes, can be NULL. */
1167 void (*commit)(BlkTransactionState *common);
1168 /* Abort the changes on fail, can be NULL. */
1169 void (*abort)(BlkTransactionState *common);
1170 /* Clean up resource in the end, can be NULL. */
1171 void (*clean)(BlkTransactionState *common);
1172 } BdrvActionOps;
1175 * This structure must be arranged as first member in child type, assuming
1176 * that compiler will also arrange it to the same address with parent instance.
1177 * Later it will be used in free().
1179 struct BlkTransactionState {
1180 TransactionAction *action;
1181 const BdrvActionOps *ops;
1182 QSIMPLEQ_ENTRY(BlkTransactionState) entry;
1185 /* internal snapshot private data */
1186 typedef struct InternalSnapshotState {
1187 BlkTransactionState common;
1188 BlockDriverState *bs;
1189 QEMUSnapshotInfo sn;
1190 } InternalSnapshotState;
1192 static void internal_snapshot_prepare(BlkTransactionState *common,
1193 Error **errp)
1195 Error *local_err = NULL;
1196 const char *device;
1197 const char *name;
1198 BlockDriverState *bs;
1199 QEMUSnapshotInfo old_sn, *sn;
1200 bool ret;
1201 qemu_timeval tv;
1202 BlockdevSnapshotInternal *internal;
1203 InternalSnapshotState *state;
1204 int ret1;
1206 g_assert(common->action->kind ==
1207 TRANSACTION_ACTION_KIND_BLOCKDEV_SNAPSHOT_INTERNAL_SYNC);
1208 internal = common->action->blockdev_snapshot_internal_sync;
1209 state = DO_UPCAST(InternalSnapshotState, common, common);
1211 /* 1. parse input */
1212 device = internal->device;
1213 name = internal->name;
1215 /* 2. check for validation */
1216 bs = bdrv_find(device);
1217 if (!bs) {
1218 error_set(errp, QERR_DEVICE_NOT_FOUND, device);
1219 return;
1222 if (!bdrv_is_inserted(bs)) {
1223 error_set(errp, QERR_DEVICE_HAS_NO_MEDIUM, device);
1224 return;
1227 if (bdrv_is_read_only(bs)) {
1228 error_set(errp, QERR_DEVICE_IS_READ_ONLY, device);
1229 return;
1232 if (!bdrv_can_snapshot(bs)) {
1233 error_set(errp, QERR_BLOCK_FORMAT_FEATURE_NOT_SUPPORTED,
1234 bs->drv->format_name, device, "internal snapshot");
1235 return;
1238 if (!strlen(name)) {
1239 error_setg(errp, "Name is empty");
1240 return;
1243 /* check whether a snapshot with name exist */
1244 ret = bdrv_snapshot_find_by_id_and_name(bs, NULL, name, &old_sn,
1245 &local_err);
1246 if (local_err) {
1247 error_propagate(errp, local_err);
1248 return;
1249 } else if (ret) {
1250 error_setg(errp,
1251 "Snapshot with name '%s' already exists on device '%s'",
1252 name, device);
1253 return;
1256 /* 3. take the snapshot */
1257 sn = &state->sn;
1258 pstrcpy(sn->name, sizeof(sn->name), name);
1259 qemu_gettimeofday(&tv);
1260 sn->date_sec = tv.tv_sec;
1261 sn->date_nsec = tv.tv_usec * 1000;
1262 sn->vm_clock_nsec = qemu_clock_get_ns(QEMU_CLOCK_VIRTUAL);
1264 ret1 = bdrv_snapshot_create(bs, sn);
1265 if (ret1 < 0) {
1266 error_setg_errno(errp, -ret1,
1267 "Failed to create snapshot '%s' on device '%s'",
1268 name, device);
1269 return;
1272 /* 4. succeed, mark a snapshot is created */
1273 state->bs = bs;
1276 static void internal_snapshot_abort(BlkTransactionState *common)
1278 InternalSnapshotState *state =
1279 DO_UPCAST(InternalSnapshotState, common, common);
1280 BlockDriverState *bs = state->bs;
1281 QEMUSnapshotInfo *sn = &state->sn;
1282 Error *local_error = NULL;
1284 if (!bs) {
1285 return;
1288 if (bdrv_snapshot_delete(bs, sn->id_str, sn->name, &local_error) < 0) {
1289 error_report("Failed to delete snapshot with id '%s' and name '%s' on "
1290 "device '%s' in abort: %s",
1291 sn->id_str,
1292 sn->name,
1293 bdrv_get_device_name(bs),
1294 error_get_pretty(local_error));
1295 error_free(local_error);
1299 /* external snapshot private data */
1300 typedef struct ExternalSnapshotState {
1301 BlkTransactionState common;
1302 BlockDriverState *old_bs;
1303 BlockDriverState *new_bs;
1304 } ExternalSnapshotState;
1306 static void external_snapshot_prepare(BlkTransactionState *common,
1307 Error **errp)
1309 BlockDriver *drv;
1310 int flags, ret;
1311 QDict *options = NULL;
1312 Error *local_err = NULL;
1313 bool has_device = false;
1314 const char *device;
1315 bool has_node_name = false;
1316 const char *node_name;
1317 bool has_snapshot_node_name = false;
1318 const char *snapshot_node_name;
1319 const char *new_image_file;
1320 const char *format = "qcow2";
1321 enum NewImageMode mode = NEW_IMAGE_MODE_ABSOLUTE_PATHS;
1322 ExternalSnapshotState *state =
1323 DO_UPCAST(ExternalSnapshotState, common, common);
1324 TransactionAction *action = common->action;
1326 /* get parameters */
1327 g_assert(action->kind == TRANSACTION_ACTION_KIND_BLOCKDEV_SNAPSHOT_SYNC);
1329 has_device = action->blockdev_snapshot_sync->has_device;
1330 device = action->blockdev_snapshot_sync->device;
1331 has_node_name = action->blockdev_snapshot_sync->has_node_name;
1332 node_name = action->blockdev_snapshot_sync->node_name;
1333 has_snapshot_node_name =
1334 action->blockdev_snapshot_sync->has_snapshot_node_name;
1335 snapshot_node_name = action->blockdev_snapshot_sync->snapshot_node_name;
1337 new_image_file = action->blockdev_snapshot_sync->snapshot_file;
1338 if (action->blockdev_snapshot_sync->has_format) {
1339 format = action->blockdev_snapshot_sync->format;
1341 if (action->blockdev_snapshot_sync->has_mode) {
1342 mode = action->blockdev_snapshot_sync->mode;
1345 /* start processing */
1346 drv = bdrv_find_format(format);
1347 if (!drv) {
1348 error_set(errp, QERR_INVALID_BLOCK_FORMAT, format);
1349 return;
1352 state->old_bs = bdrv_lookup_bs(has_device ? device : NULL,
1353 has_node_name ? node_name : NULL,
1354 &local_err);
1355 if (local_err) {
1356 error_propagate(errp, local_err);
1357 return;
1360 if (has_node_name && !has_snapshot_node_name) {
1361 error_setg(errp, "New snapshot node name missing");
1362 return;
1365 if (has_snapshot_node_name && bdrv_find_node(snapshot_node_name)) {
1366 error_setg(errp, "New snapshot node name already existing");
1367 return;
1370 if (!bdrv_is_inserted(state->old_bs)) {
1371 error_set(errp, QERR_DEVICE_HAS_NO_MEDIUM, device);
1372 return;
1375 if (bdrv_op_is_blocked(state->old_bs,
1376 BLOCK_OP_TYPE_EXTERNAL_SNAPSHOT, errp)) {
1377 return;
1380 if (!bdrv_is_read_only(state->old_bs)) {
1381 if (bdrv_flush(state->old_bs)) {
1382 error_set(errp, QERR_IO_ERROR);
1383 return;
1387 if (!bdrv_is_first_non_filter(state->old_bs)) {
1388 error_set(errp, QERR_FEATURE_DISABLED, "snapshot");
1389 return;
1392 flags = state->old_bs->open_flags;
1394 /* create new image w/backing file */
1395 if (mode != NEW_IMAGE_MODE_EXISTING) {
1396 bdrv_img_create(new_image_file, format,
1397 state->old_bs->filename,
1398 state->old_bs->drv->format_name,
1399 NULL, -1, flags, &local_err, false);
1400 if (local_err) {
1401 error_propagate(errp, local_err);
1402 return;
1406 if (has_snapshot_node_name) {
1407 options = qdict_new();
1408 qdict_put(options, "node-name",
1409 qstring_from_str(snapshot_node_name));
1412 /* TODO Inherit bs->options or only take explicit options with an
1413 * extended QMP command? */
1414 assert(state->new_bs == NULL);
1415 ret = bdrv_open(&state->new_bs, new_image_file, NULL, options,
1416 flags | BDRV_O_NO_BACKING, drv, &local_err);
1417 /* We will manually add the backing_hd field to the bs later */
1418 if (ret != 0) {
1419 error_propagate(errp, local_err);
1423 static void external_snapshot_commit(BlkTransactionState *common)
1425 ExternalSnapshotState *state =
1426 DO_UPCAST(ExternalSnapshotState, common, common);
1428 /* This removes our old bs and adds the new bs */
1429 bdrv_append(state->new_bs, state->old_bs);
1430 /* We don't need (or want) to use the transactional
1431 * bdrv_reopen_multiple() across all the entries at once, because we
1432 * don't want to abort all of them if one of them fails the reopen */
1433 bdrv_reopen(state->new_bs, state->new_bs->open_flags & ~BDRV_O_RDWR,
1434 NULL);
1437 static void external_snapshot_abort(BlkTransactionState *common)
1439 ExternalSnapshotState *state =
1440 DO_UPCAST(ExternalSnapshotState, common, common);
1441 if (state->new_bs) {
1442 bdrv_unref(state->new_bs);
1446 typedef struct DriveBackupState {
1447 BlkTransactionState common;
1448 BlockDriverState *bs;
1449 BlockJob *job;
1450 } DriveBackupState;
1452 static void drive_backup_prepare(BlkTransactionState *common, Error **errp)
1454 DriveBackupState *state = DO_UPCAST(DriveBackupState, common, common);
1455 DriveBackup *backup;
1456 Error *local_err = NULL;
1458 assert(common->action->kind == TRANSACTION_ACTION_KIND_DRIVE_BACKUP);
1459 backup = common->action->drive_backup;
1461 qmp_drive_backup(backup->device, backup->target,
1462 backup->has_format, backup->format,
1463 backup->sync,
1464 backup->has_mode, backup->mode,
1465 backup->has_speed, backup->speed,
1466 backup->has_on_source_error, backup->on_source_error,
1467 backup->has_on_target_error, backup->on_target_error,
1468 &local_err);
1469 if (local_err) {
1470 error_propagate(errp, local_err);
1471 state->bs = NULL;
1472 state->job = NULL;
1473 return;
1476 state->bs = bdrv_find(backup->device);
1477 state->job = state->bs->job;
1480 static void drive_backup_abort(BlkTransactionState *common)
1482 DriveBackupState *state = DO_UPCAST(DriveBackupState, common, common);
1483 BlockDriverState *bs = state->bs;
1485 /* Only cancel if it's the job we started */
1486 if (bs && bs->job && bs->job == state->job) {
1487 block_job_cancel_sync(bs->job);
1491 static void abort_prepare(BlkTransactionState *common, Error **errp)
1493 error_setg(errp, "Transaction aborted using Abort action");
1496 static void abort_commit(BlkTransactionState *common)
1498 g_assert_not_reached(); /* this action never succeeds */
1501 static const BdrvActionOps actions[] = {
1502 [TRANSACTION_ACTION_KIND_BLOCKDEV_SNAPSHOT_SYNC] = {
1503 .instance_size = sizeof(ExternalSnapshotState),
1504 .prepare = external_snapshot_prepare,
1505 .commit = external_snapshot_commit,
1506 .abort = external_snapshot_abort,
1508 [TRANSACTION_ACTION_KIND_DRIVE_BACKUP] = {
1509 .instance_size = sizeof(DriveBackupState),
1510 .prepare = drive_backup_prepare,
1511 .abort = drive_backup_abort,
1513 [TRANSACTION_ACTION_KIND_ABORT] = {
1514 .instance_size = sizeof(BlkTransactionState),
1515 .prepare = abort_prepare,
1516 .commit = abort_commit,
1518 [TRANSACTION_ACTION_KIND_BLOCKDEV_SNAPSHOT_INTERNAL_SYNC] = {
1519 .instance_size = sizeof(InternalSnapshotState),
1520 .prepare = internal_snapshot_prepare,
1521 .abort = internal_snapshot_abort,
1526 * 'Atomic' group snapshots. The snapshots are taken as a set, and if any fail
1527 * then we do not pivot any of the devices in the group, and abandon the
1528 * snapshots
1530 void qmp_transaction(TransactionActionList *dev_list, Error **errp)
1532 TransactionActionList *dev_entry = dev_list;
1533 BlkTransactionState *state, *next;
1534 Error *local_err = NULL;
1536 QSIMPLEQ_HEAD(snap_bdrv_states, BlkTransactionState) snap_bdrv_states;
1537 QSIMPLEQ_INIT(&snap_bdrv_states);
1539 /* drain all i/o before any snapshots */
1540 bdrv_drain_all();
1542 /* We don't do anything in this loop that commits us to the snapshot */
1543 while (NULL != dev_entry) {
1544 TransactionAction *dev_info = NULL;
1545 const BdrvActionOps *ops;
1547 dev_info = dev_entry->value;
1548 dev_entry = dev_entry->next;
1550 assert(dev_info->kind < ARRAY_SIZE(actions));
1552 ops = &actions[dev_info->kind];
1553 assert(ops->instance_size > 0);
1555 state = g_malloc0(ops->instance_size);
1556 state->ops = ops;
1557 state->action = dev_info;
1558 QSIMPLEQ_INSERT_TAIL(&snap_bdrv_states, state, entry);
1560 state->ops->prepare(state, &local_err);
1561 if (local_err) {
1562 error_propagate(errp, local_err);
1563 goto delete_and_fail;
1567 QSIMPLEQ_FOREACH(state, &snap_bdrv_states, entry) {
1568 if (state->ops->commit) {
1569 state->ops->commit(state);
1573 /* success */
1574 goto exit;
1576 delete_and_fail:
1578 * failure, and it is all-or-none; abandon each new bs, and keep using
1579 * the original bs for all images
1581 QSIMPLEQ_FOREACH(state, &snap_bdrv_states, entry) {
1582 if (state->ops->abort) {
1583 state->ops->abort(state);
1586 exit:
1587 QSIMPLEQ_FOREACH_SAFE(state, &snap_bdrv_states, entry, next) {
1588 if (state->ops->clean) {
1589 state->ops->clean(state);
1591 g_free(state);
1596 static void eject_device(BlockBackend *blk, int force, Error **errp)
1598 BlockDriverState *bs = blk_bs(blk);
1600 if (bdrv_op_is_blocked(bs, BLOCK_OP_TYPE_EJECT, errp)) {
1601 return;
1603 if (!blk_dev_has_removable_media(blk)) {
1604 error_setg(errp, "Device '%s' is not removable",
1605 bdrv_get_device_name(bs));
1606 return;
1609 if (blk_dev_is_medium_locked(blk) && !blk_dev_is_tray_open(blk)) {
1610 blk_dev_eject_request(blk, force);
1611 if (!force) {
1612 error_setg(errp, "Device '%s' is locked",
1613 bdrv_get_device_name(bs));
1614 return;
1618 bdrv_close(bs);
1621 void qmp_eject(const char *device, bool has_force, bool force, Error **errp)
1623 BlockBackend *blk;
1625 blk = blk_by_name(device);
1626 if (!blk) {
1627 error_set(errp, QERR_DEVICE_NOT_FOUND, device);
1628 return;
1631 eject_device(blk, force, errp);
1634 void qmp_block_passwd(bool has_device, const char *device,
1635 bool has_node_name, const char *node_name,
1636 const char *password, Error **errp)
1638 Error *local_err = NULL;
1639 BlockDriverState *bs;
1640 int err;
1642 bs = bdrv_lookup_bs(has_device ? device : NULL,
1643 has_node_name ? node_name : NULL,
1644 &local_err);
1645 if (local_err) {
1646 error_propagate(errp, local_err);
1647 return;
1650 err = bdrv_set_key(bs, password);
1651 if (err == -EINVAL) {
1652 error_set(errp, QERR_DEVICE_NOT_ENCRYPTED, bdrv_get_device_name(bs));
1653 return;
1654 } else if (err < 0) {
1655 error_set(errp, QERR_INVALID_PASSWORD);
1656 return;
1660 static void qmp_bdrv_open_encrypted(BlockDriverState *bs, const char *filename,
1661 int bdrv_flags, BlockDriver *drv,
1662 const char *password, Error **errp)
1664 Error *local_err = NULL;
1665 int ret;
1667 ret = bdrv_open(&bs, filename, NULL, NULL, bdrv_flags, drv, &local_err);
1668 if (ret < 0) {
1669 error_propagate(errp, local_err);
1670 return;
1673 if (bdrv_key_required(bs)) {
1674 if (password) {
1675 if (bdrv_set_key(bs, password) < 0) {
1676 error_set(errp, QERR_INVALID_PASSWORD);
1678 } else {
1679 error_set(errp, QERR_DEVICE_ENCRYPTED, bdrv_get_device_name(bs),
1680 bdrv_get_encrypted_filename(bs));
1682 } else if (password) {
1683 error_set(errp, QERR_DEVICE_NOT_ENCRYPTED, bdrv_get_device_name(bs));
1687 void qmp_change_blockdev(const char *device, const char *filename,
1688 const char *format, Error **errp)
1690 BlockBackend *blk;
1691 BlockDriverState *bs;
1692 BlockDriver *drv = NULL;
1693 int bdrv_flags;
1694 Error *err = NULL;
1696 blk = blk_by_name(device);
1697 if (!blk) {
1698 error_set(errp, QERR_DEVICE_NOT_FOUND, device);
1699 return;
1701 bs = blk_bs(blk);
1703 if (format) {
1704 drv = bdrv_find_whitelisted_format(format, bs->read_only);
1705 if (!drv) {
1706 error_set(errp, QERR_INVALID_BLOCK_FORMAT, format);
1707 return;
1711 eject_device(blk, 0, &err);
1712 if (err) {
1713 error_propagate(errp, err);
1714 return;
1717 bdrv_flags = bdrv_is_read_only(bs) ? 0 : BDRV_O_RDWR;
1718 bdrv_flags |= bdrv_is_snapshot(bs) ? BDRV_O_SNAPSHOT : 0;
1720 qmp_bdrv_open_encrypted(bs, filename, bdrv_flags, drv, NULL, errp);
1723 /* throttling disk I/O limits */
1724 void qmp_block_set_io_throttle(const char *device, int64_t bps, int64_t bps_rd,
1725 int64_t bps_wr,
1726 int64_t iops,
1727 int64_t iops_rd,
1728 int64_t iops_wr,
1729 bool has_bps_max,
1730 int64_t bps_max,
1731 bool has_bps_rd_max,
1732 int64_t bps_rd_max,
1733 bool has_bps_wr_max,
1734 int64_t bps_wr_max,
1735 bool has_iops_max,
1736 int64_t iops_max,
1737 bool has_iops_rd_max,
1738 int64_t iops_rd_max,
1739 bool has_iops_wr_max,
1740 int64_t iops_wr_max,
1741 bool has_iops_size,
1742 int64_t iops_size, Error **errp)
1744 ThrottleConfig cfg;
1745 BlockDriverState *bs;
1746 AioContext *aio_context;
1748 bs = bdrv_find(device);
1749 if (!bs) {
1750 error_set(errp, QERR_DEVICE_NOT_FOUND, device);
1751 return;
1754 memset(&cfg, 0, sizeof(cfg));
1755 cfg.buckets[THROTTLE_BPS_TOTAL].avg = bps;
1756 cfg.buckets[THROTTLE_BPS_READ].avg = bps_rd;
1757 cfg.buckets[THROTTLE_BPS_WRITE].avg = bps_wr;
1759 cfg.buckets[THROTTLE_OPS_TOTAL].avg = iops;
1760 cfg.buckets[THROTTLE_OPS_READ].avg = iops_rd;
1761 cfg.buckets[THROTTLE_OPS_WRITE].avg = iops_wr;
1763 if (has_bps_max) {
1764 cfg.buckets[THROTTLE_BPS_TOTAL].max = bps_max;
1766 if (has_bps_rd_max) {
1767 cfg.buckets[THROTTLE_BPS_READ].max = bps_rd_max;
1769 if (has_bps_wr_max) {
1770 cfg.buckets[THROTTLE_BPS_WRITE].max = bps_wr_max;
1772 if (has_iops_max) {
1773 cfg.buckets[THROTTLE_OPS_TOTAL].max = iops_max;
1775 if (has_iops_rd_max) {
1776 cfg.buckets[THROTTLE_OPS_READ].max = iops_rd_max;
1778 if (has_iops_wr_max) {
1779 cfg.buckets[THROTTLE_OPS_WRITE].max = iops_wr_max;
1782 if (has_iops_size) {
1783 cfg.op_size = iops_size;
1786 if (!check_throttle_config(&cfg, errp)) {
1787 return;
1790 aio_context = bdrv_get_aio_context(bs);
1791 aio_context_acquire(aio_context);
1793 if (!bs->io_limits_enabled && throttle_enabled(&cfg)) {
1794 bdrv_io_limits_enable(bs);
1795 } else if (bs->io_limits_enabled && !throttle_enabled(&cfg)) {
1796 bdrv_io_limits_disable(bs);
1799 if (bs->io_limits_enabled) {
1800 bdrv_set_io_limits(bs, &cfg);
1803 aio_context_release(aio_context);
1806 int do_drive_del(Monitor *mon, const QDict *qdict, QObject **ret_data)
1808 const char *id = qdict_get_str(qdict, "id");
1809 BlockBackend *blk;
1810 BlockDriverState *bs;
1811 AioContext *aio_context;
1812 Error *local_err = NULL;
1814 blk = blk_by_name(id);
1815 if (!blk) {
1816 error_report("Device '%s' not found", id);
1817 return -1;
1819 bs = blk_bs(blk);
1821 if (!blk_legacy_dinfo(blk)) {
1822 error_report("Deleting device added with blockdev-add"
1823 " is not supported");
1824 return -1;
1827 aio_context = bdrv_get_aio_context(bs);
1828 aio_context_acquire(aio_context);
1830 if (bdrv_op_is_blocked(bs, BLOCK_OP_TYPE_DRIVE_DEL, &local_err)) {
1831 error_report("%s", error_get_pretty(local_err));
1832 error_free(local_err);
1833 aio_context_release(aio_context);
1834 return -1;
1837 /* quiesce block driver; prevent further io */
1838 bdrv_drain_all();
1839 bdrv_flush(bs);
1840 bdrv_close(bs);
1842 /* if we have a device attached to this BlockDriverState
1843 * then we need to make the drive anonymous until the device
1844 * can be removed. If this is a drive with no device backing
1845 * then we can just get rid of the block driver state right here.
1847 if (blk_get_attached_dev(blk)) {
1848 blk_hide_on_behalf_of_do_drive_del(blk);
1849 /* Further I/O must not pause the guest */
1850 bdrv_set_on_error(bs, BLOCKDEV_ON_ERROR_REPORT,
1851 BLOCKDEV_ON_ERROR_REPORT);
1852 } else {
1853 blk_unref(blk);
1856 aio_context_release(aio_context);
1857 return 0;
1860 void qmp_block_resize(bool has_device, const char *device,
1861 bool has_node_name, const char *node_name,
1862 int64_t size, Error **errp)
1864 Error *local_err = NULL;
1865 BlockDriverState *bs;
1866 AioContext *aio_context;
1867 int ret;
1869 bs = bdrv_lookup_bs(has_device ? device : NULL,
1870 has_node_name ? node_name : NULL,
1871 &local_err);
1872 if (local_err) {
1873 error_propagate(errp, local_err);
1874 return;
1877 aio_context = bdrv_get_aio_context(bs);
1878 aio_context_acquire(aio_context);
1880 if (!bdrv_is_first_non_filter(bs)) {
1881 error_set(errp, QERR_FEATURE_DISABLED, "resize");
1882 goto out;
1885 if (size < 0) {
1886 error_set(errp, QERR_INVALID_PARAMETER_VALUE, "size", "a >0 size");
1887 goto out;
1890 if (bdrv_op_is_blocked(bs, BLOCK_OP_TYPE_RESIZE, NULL)) {
1891 error_set(errp, QERR_DEVICE_IN_USE, device);
1892 goto out;
1895 /* complete all in-flight operations before resizing the device */
1896 bdrv_drain_all();
1898 ret = bdrv_truncate(bs, size);
1899 switch (ret) {
1900 case 0:
1901 break;
1902 case -ENOMEDIUM:
1903 error_set(errp, QERR_DEVICE_HAS_NO_MEDIUM, device);
1904 break;
1905 case -ENOTSUP:
1906 error_set(errp, QERR_UNSUPPORTED);
1907 break;
1908 case -EACCES:
1909 error_set(errp, QERR_DEVICE_IS_READ_ONLY, device);
1910 break;
1911 case -EBUSY:
1912 error_set(errp, QERR_DEVICE_IN_USE, device);
1913 break;
1914 default:
1915 error_setg_errno(errp, -ret, "Could not resize");
1916 break;
1919 out:
1920 aio_context_release(aio_context);
1923 static void block_job_cb(void *opaque, int ret)
1925 BlockDriverState *bs = opaque;
1926 const char *msg = NULL;
1928 trace_block_job_cb(bs, bs->job, ret);
1930 assert(bs->job);
1932 if (ret < 0) {
1933 msg = strerror(-ret);
1936 if (block_job_is_cancelled(bs->job)) {
1937 block_job_event_cancelled(bs->job);
1938 } else {
1939 block_job_event_completed(bs->job, msg);
1942 bdrv_put_ref_bh_schedule(bs);
1945 void qmp_block_stream(const char *device,
1946 bool has_base, const char *base,
1947 bool has_backing_file, const char *backing_file,
1948 bool has_speed, int64_t speed,
1949 bool has_on_error, BlockdevOnError on_error,
1950 Error **errp)
1952 BlockDriverState *bs;
1953 BlockDriverState *base_bs = NULL;
1954 Error *local_err = NULL;
1955 const char *base_name = NULL;
1957 if (!has_on_error) {
1958 on_error = BLOCKDEV_ON_ERROR_REPORT;
1961 bs = bdrv_find(device);
1962 if (!bs) {
1963 error_set(errp, QERR_DEVICE_NOT_FOUND, device);
1964 return;
1967 if (bdrv_op_is_blocked(bs, BLOCK_OP_TYPE_STREAM, errp)) {
1968 return;
1971 if (has_base) {
1972 base_bs = bdrv_find_backing_image(bs, base);
1973 if (base_bs == NULL) {
1974 error_set(errp, QERR_BASE_NOT_FOUND, base);
1975 return;
1977 base_name = base;
1980 /* if we are streaming the entire chain, the result will have no backing
1981 * file, and specifying one is therefore an error */
1982 if (base_bs == NULL && has_backing_file) {
1983 error_setg(errp, "backing file specified, but streaming the "
1984 "entire chain");
1985 return;
1988 /* backing_file string overrides base bs filename */
1989 base_name = has_backing_file ? backing_file : base_name;
1991 stream_start(bs, base_bs, base_name, has_speed ? speed : 0,
1992 on_error, block_job_cb, bs, &local_err);
1993 if (local_err) {
1994 error_propagate(errp, local_err);
1995 return;
1998 trace_qmp_block_stream(bs, bs->job);
2001 void qmp_block_commit(const char *device,
2002 bool has_base, const char *base,
2003 bool has_top, const char *top,
2004 bool has_backing_file, const char *backing_file,
2005 bool has_speed, int64_t speed,
2006 Error **errp)
2008 BlockDriverState *bs;
2009 BlockDriverState *base_bs, *top_bs;
2010 Error *local_err = NULL;
2011 /* This will be part of the QMP command, if/when the
2012 * BlockdevOnError change for blkmirror makes it in
2014 BlockdevOnError on_error = BLOCKDEV_ON_ERROR_REPORT;
2016 if (!has_speed) {
2017 speed = 0;
2020 /* drain all i/o before commits */
2021 bdrv_drain_all();
2023 /* Important Note:
2024 * libvirt relies on the DeviceNotFound error class in order to probe for
2025 * live commit feature versions; for this to work, we must make sure to
2026 * perform the device lookup before any generic errors that may occur in a
2027 * scenario in which all optional arguments are omitted. */
2028 bs = bdrv_find(device);
2029 if (!bs) {
2030 error_set(errp, QERR_DEVICE_NOT_FOUND, device);
2031 return;
2034 if (bdrv_op_is_blocked(bs, BLOCK_OP_TYPE_COMMIT, errp)) {
2035 return;
2038 /* default top_bs is the active layer */
2039 top_bs = bs;
2041 if (has_top && top) {
2042 if (strcmp(bs->filename, top) != 0) {
2043 top_bs = bdrv_find_backing_image(bs, top);
2047 if (top_bs == NULL) {
2048 error_setg(errp, "Top image file %s not found", top ? top : "NULL");
2049 return;
2052 if (has_base && base) {
2053 base_bs = bdrv_find_backing_image(top_bs, base);
2054 } else {
2055 base_bs = bdrv_find_base(top_bs);
2058 if (base_bs == NULL) {
2059 error_set(errp, QERR_BASE_NOT_FOUND, base ? base : "NULL");
2060 return;
2063 /* Do not allow attempts to commit an image into itself */
2064 if (top_bs == base_bs) {
2065 error_setg(errp, "cannot commit an image into itself");
2066 return;
2069 if (top_bs == bs) {
2070 if (has_backing_file) {
2071 error_setg(errp, "'backing-file' specified,"
2072 " but 'top' is the active layer");
2073 return;
2075 commit_active_start(bs, base_bs, speed, on_error, block_job_cb,
2076 bs, &local_err);
2077 } else {
2078 commit_start(bs, base_bs, top_bs, speed, on_error, block_job_cb, bs,
2079 has_backing_file ? backing_file : NULL, &local_err);
2081 if (local_err != NULL) {
2082 error_propagate(errp, local_err);
2083 return;
2087 void qmp_drive_backup(const char *device, const char *target,
2088 bool has_format, const char *format,
2089 enum MirrorSyncMode sync,
2090 bool has_mode, enum NewImageMode mode,
2091 bool has_speed, int64_t speed,
2092 bool has_on_source_error, BlockdevOnError on_source_error,
2093 bool has_on_target_error, BlockdevOnError on_target_error,
2094 Error **errp)
2096 BlockDriverState *bs;
2097 BlockDriverState *target_bs;
2098 BlockDriverState *source = NULL;
2099 BlockDriver *drv = NULL;
2100 Error *local_err = NULL;
2101 int flags;
2102 int64_t size;
2103 int ret;
2105 if (!has_speed) {
2106 speed = 0;
2108 if (!has_on_source_error) {
2109 on_source_error = BLOCKDEV_ON_ERROR_REPORT;
2111 if (!has_on_target_error) {
2112 on_target_error = BLOCKDEV_ON_ERROR_REPORT;
2114 if (!has_mode) {
2115 mode = NEW_IMAGE_MODE_ABSOLUTE_PATHS;
2118 bs = bdrv_find(device);
2119 if (!bs) {
2120 error_set(errp, QERR_DEVICE_NOT_FOUND, device);
2121 return;
2124 if (!bdrv_is_inserted(bs)) {
2125 error_set(errp, QERR_DEVICE_HAS_NO_MEDIUM, device);
2126 return;
2129 if (!has_format) {
2130 format = mode == NEW_IMAGE_MODE_EXISTING ? NULL : bs->drv->format_name;
2132 if (format) {
2133 drv = bdrv_find_format(format);
2134 if (!drv) {
2135 error_set(errp, QERR_INVALID_BLOCK_FORMAT, format);
2136 return;
2140 if (bdrv_op_is_blocked(bs, BLOCK_OP_TYPE_BACKUP_SOURCE, errp)) {
2141 return;
2144 flags = bs->open_flags | BDRV_O_RDWR;
2146 /* See if we have a backing HD we can use to create our new image
2147 * on top of. */
2148 if (sync == MIRROR_SYNC_MODE_TOP) {
2149 source = bs->backing_hd;
2150 if (!source) {
2151 sync = MIRROR_SYNC_MODE_FULL;
2154 if (sync == MIRROR_SYNC_MODE_NONE) {
2155 source = bs;
2158 size = bdrv_getlength(bs);
2159 if (size < 0) {
2160 error_setg_errno(errp, -size, "bdrv_getlength failed");
2161 return;
2164 if (mode != NEW_IMAGE_MODE_EXISTING) {
2165 assert(format && drv);
2166 if (source) {
2167 bdrv_img_create(target, format, source->filename,
2168 source->drv->format_name, NULL,
2169 size, flags, &local_err, false);
2170 } else {
2171 bdrv_img_create(target, format, NULL, NULL, NULL,
2172 size, flags, &local_err, false);
2176 if (local_err) {
2177 error_propagate(errp, local_err);
2178 return;
2181 target_bs = NULL;
2182 ret = bdrv_open(&target_bs, target, NULL, NULL, flags, drv, &local_err);
2183 if (ret < 0) {
2184 error_propagate(errp, local_err);
2185 return;
2188 backup_start(bs, target_bs, speed, sync, on_source_error, on_target_error,
2189 block_job_cb, bs, &local_err);
2190 if (local_err != NULL) {
2191 bdrv_unref(target_bs);
2192 error_propagate(errp, local_err);
2193 return;
2197 BlockDeviceInfoList *qmp_query_named_block_nodes(Error **errp)
2199 return bdrv_named_nodes_list();
2202 #define DEFAULT_MIRROR_BUF_SIZE (10 << 20)
2204 void qmp_drive_mirror(const char *device, const char *target,
2205 bool has_format, const char *format,
2206 bool has_node_name, const char *node_name,
2207 bool has_replaces, const char *replaces,
2208 enum MirrorSyncMode sync,
2209 bool has_mode, enum NewImageMode mode,
2210 bool has_speed, int64_t speed,
2211 bool has_granularity, uint32_t granularity,
2212 bool has_buf_size, int64_t buf_size,
2213 bool has_on_source_error, BlockdevOnError on_source_error,
2214 bool has_on_target_error, BlockdevOnError on_target_error,
2215 Error **errp)
2217 BlockDriverState *bs;
2218 BlockDriverState *source, *target_bs;
2219 BlockDriver *drv = NULL;
2220 Error *local_err = NULL;
2221 QDict *options = NULL;
2222 int flags;
2223 int64_t size;
2224 int ret;
2226 if (!has_speed) {
2227 speed = 0;
2229 if (!has_on_source_error) {
2230 on_source_error = BLOCKDEV_ON_ERROR_REPORT;
2232 if (!has_on_target_error) {
2233 on_target_error = BLOCKDEV_ON_ERROR_REPORT;
2235 if (!has_mode) {
2236 mode = NEW_IMAGE_MODE_ABSOLUTE_PATHS;
2238 if (!has_granularity) {
2239 granularity = 0;
2241 if (!has_buf_size) {
2242 buf_size = DEFAULT_MIRROR_BUF_SIZE;
2245 if (granularity != 0 && (granularity < 512 || granularity > 1048576 * 64)) {
2246 error_set(errp, QERR_INVALID_PARAMETER_VALUE, "granularity",
2247 "a value in range [512B, 64MB]");
2248 return;
2250 if (granularity & (granularity - 1)) {
2251 error_set(errp, QERR_INVALID_PARAMETER_VALUE, "granularity", "power of 2");
2252 return;
2255 bs = bdrv_find(device);
2256 if (!bs) {
2257 error_set(errp, QERR_DEVICE_NOT_FOUND, device);
2258 return;
2261 if (!bdrv_is_inserted(bs)) {
2262 error_set(errp, QERR_DEVICE_HAS_NO_MEDIUM, device);
2263 return;
2266 if (!has_format) {
2267 format = mode == NEW_IMAGE_MODE_EXISTING ? NULL : bs->drv->format_name;
2269 if (format) {
2270 drv = bdrv_find_format(format);
2271 if (!drv) {
2272 error_set(errp, QERR_INVALID_BLOCK_FORMAT, format);
2273 return;
2277 if (bdrv_op_is_blocked(bs, BLOCK_OP_TYPE_MIRROR, errp)) {
2278 return;
2281 flags = bs->open_flags | BDRV_O_RDWR;
2282 source = bs->backing_hd;
2283 if (!source && sync == MIRROR_SYNC_MODE_TOP) {
2284 sync = MIRROR_SYNC_MODE_FULL;
2286 if (sync == MIRROR_SYNC_MODE_NONE) {
2287 source = bs;
2290 size = bdrv_getlength(bs);
2291 if (size < 0) {
2292 error_setg_errno(errp, -size, "bdrv_getlength failed");
2293 return;
2296 if (has_replaces) {
2297 BlockDriverState *to_replace_bs;
2299 if (!has_node_name) {
2300 error_setg(errp, "a node-name must be provided when replacing a"
2301 " named node of the graph");
2302 return;
2305 to_replace_bs = check_to_replace_node(replaces, &local_err);
2307 if (!to_replace_bs) {
2308 error_propagate(errp, local_err);
2309 return;
2312 if (size != bdrv_getlength(to_replace_bs)) {
2313 error_setg(errp, "cannot replace image with a mirror image of "
2314 "different size");
2315 return;
2319 if ((sync == MIRROR_SYNC_MODE_FULL || !source)
2320 && mode != NEW_IMAGE_MODE_EXISTING)
2322 /* create new image w/o backing file */
2323 assert(format && drv);
2324 bdrv_img_create(target, format,
2325 NULL, NULL, NULL, size, flags, &local_err, false);
2326 } else {
2327 switch (mode) {
2328 case NEW_IMAGE_MODE_EXISTING:
2329 break;
2330 case NEW_IMAGE_MODE_ABSOLUTE_PATHS:
2331 /* create new image with backing file */
2332 bdrv_img_create(target, format,
2333 source->filename,
2334 source->drv->format_name,
2335 NULL, size, flags, &local_err, false);
2336 break;
2337 default:
2338 abort();
2342 if (local_err) {
2343 error_propagate(errp, local_err);
2344 return;
2347 if (has_node_name) {
2348 options = qdict_new();
2349 qdict_put(options, "node-name", qstring_from_str(node_name));
2352 /* Mirroring takes care of copy-on-write using the source's backing
2353 * file.
2355 target_bs = NULL;
2356 ret = bdrv_open(&target_bs, target, NULL, options,
2357 flags | BDRV_O_NO_BACKING, drv, &local_err);
2358 if (ret < 0) {
2359 error_propagate(errp, local_err);
2360 return;
2363 /* pass the node name to replace to mirror start since it's loose coupling
2364 * and will allow to check whether the node still exist at mirror completion
2366 mirror_start(bs, target_bs,
2367 has_replaces ? replaces : NULL,
2368 speed, granularity, buf_size, sync,
2369 on_source_error, on_target_error,
2370 block_job_cb, bs, &local_err);
2371 if (local_err != NULL) {
2372 bdrv_unref(target_bs);
2373 error_propagate(errp, local_err);
2374 return;
2378 static BlockJob *find_block_job(const char *device)
2380 BlockDriverState *bs;
2382 bs = bdrv_find(device);
2383 if (!bs || !bs->job) {
2384 return NULL;
2386 return bs->job;
2389 void qmp_block_job_set_speed(const char *device, int64_t speed, Error **errp)
2391 BlockJob *job = find_block_job(device);
2393 if (!job) {
2394 error_set(errp, QERR_BLOCK_JOB_NOT_ACTIVE, device);
2395 return;
2398 block_job_set_speed(job, speed, errp);
2401 void qmp_block_job_cancel(const char *device,
2402 bool has_force, bool force, Error **errp)
2404 BlockJob *job = find_block_job(device);
2406 if (!has_force) {
2407 force = false;
2410 if (!job) {
2411 error_set(errp, QERR_BLOCK_JOB_NOT_ACTIVE, device);
2412 return;
2414 if (job->paused && !force) {
2415 error_setg(errp, "The block job for device '%s' is currently paused",
2416 device);
2417 return;
2420 trace_qmp_block_job_cancel(job);
2421 block_job_cancel(job);
2424 void qmp_block_job_pause(const char *device, Error **errp)
2426 BlockJob *job = find_block_job(device);
2428 if (!job) {
2429 error_set(errp, QERR_BLOCK_JOB_NOT_ACTIVE, device);
2430 return;
2433 trace_qmp_block_job_pause(job);
2434 block_job_pause(job);
2437 void qmp_block_job_resume(const char *device, Error **errp)
2439 BlockJob *job = find_block_job(device);
2441 if (!job) {
2442 error_set(errp, QERR_BLOCK_JOB_NOT_ACTIVE, device);
2443 return;
2446 trace_qmp_block_job_resume(job);
2447 block_job_resume(job);
2450 void qmp_block_job_complete(const char *device, Error **errp)
2452 BlockJob *job = find_block_job(device);
2454 if (!job) {
2455 error_set(errp, QERR_BLOCK_JOB_NOT_ACTIVE, device);
2456 return;
2459 trace_qmp_block_job_complete(job);
2460 block_job_complete(job, errp);
2463 void qmp_change_backing_file(const char *device,
2464 const char *image_node_name,
2465 const char *backing_file,
2466 Error **errp)
2468 BlockDriverState *bs = NULL;
2469 BlockDriverState *image_bs = NULL;
2470 Error *local_err = NULL;
2471 bool ro;
2472 int open_flags;
2473 int ret;
2475 /* find the top layer BDS of the chain */
2476 bs = bdrv_find(device);
2477 if (!bs) {
2478 error_set(errp, QERR_DEVICE_NOT_FOUND, device);
2479 return;
2482 image_bs = bdrv_lookup_bs(NULL, image_node_name, &local_err);
2483 if (local_err) {
2484 error_propagate(errp, local_err);
2485 return;
2488 if (!image_bs) {
2489 error_setg(errp, "image file not found");
2490 return;
2493 if (bdrv_find_base(image_bs) == image_bs) {
2494 error_setg(errp, "not allowing backing file change on an image "
2495 "without a backing file");
2496 return;
2499 /* even though we are not necessarily operating on bs, we need it to
2500 * determine if block ops are currently prohibited on the chain */
2501 if (bdrv_op_is_blocked(bs, BLOCK_OP_TYPE_CHANGE, errp)) {
2502 return;
2505 /* final sanity check */
2506 if (!bdrv_chain_contains(bs, image_bs)) {
2507 error_setg(errp, "'%s' and image file are not in the same chain",
2508 device);
2509 return;
2512 /* if not r/w, reopen to make r/w */
2513 open_flags = image_bs->open_flags;
2514 ro = bdrv_is_read_only(image_bs);
2516 if (ro) {
2517 bdrv_reopen(image_bs, open_flags | BDRV_O_RDWR, &local_err);
2518 if (local_err) {
2519 error_propagate(errp, local_err);
2520 return;
2524 ret = bdrv_change_backing_file(image_bs, backing_file,
2525 image_bs->drv ? image_bs->drv->format_name : "");
2527 if (ret < 0) {
2528 error_setg_errno(errp, -ret, "Could not change backing file to '%s'",
2529 backing_file);
2530 /* don't exit here, so we can try to restore open flags if
2531 * appropriate */
2534 if (ro) {
2535 bdrv_reopen(image_bs, open_flags, &local_err);
2536 if (local_err) {
2537 error_propagate(errp, local_err); /* will preserve prior errp */
2542 void qmp_blockdev_add(BlockdevOptions *options, Error **errp)
2544 QmpOutputVisitor *ov = qmp_output_visitor_new();
2545 BlockBackend *blk;
2546 QObject *obj;
2547 QDict *qdict;
2548 Error *local_err = NULL;
2550 /* Require an ID in the top level */
2551 if (!options->has_id) {
2552 error_setg(errp, "Block device needs an ID");
2553 goto fail;
2556 /* TODO Sort it out in raw-posix and drive_new(): Reject aio=native with
2557 * cache.direct=false instead of silently switching to aio=threads, except
2558 * when called from drive_new().
2560 * For now, simply forbidding the combination for all drivers will do. */
2561 if (options->has_aio && options->aio == BLOCKDEV_AIO_OPTIONS_NATIVE) {
2562 bool direct = options->has_cache &&
2563 options->cache->has_direct &&
2564 options->cache->direct;
2565 if (!direct) {
2566 error_setg(errp, "aio=native requires cache.direct=true");
2567 goto fail;
2571 visit_type_BlockdevOptions(qmp_output_get_visitor(ov),
2572 &options, NULL, &local_err);
2573 if (local_err) {
2574 error_propagate(errp, local_err);
2575 goto fail;
2578 obj = qmp_output_get_qobject(ov);
2579 qdict = qobject_to_qdict(obj);
2581 qdict_flatten(qdict);
2583 blk = blockdev_init(NULL, qdict, &local_err);
2584 if (local_err) {
2585 error_propagate(errp, local_err);
2586 goto fail;
2589 if (bdrv_key_required(blk_bs(blk))) {
2590 blk_unref(blk);
2591 error_setg(errp, "blockdev-add doesn't support encrypted devices");
2592 goto fail;
2595 fail:
2596 qmp_output_visitor_cleanup(ov);
2599 BlockJobInfoList *qmp_query_block_jobs(Error **errp)
2601 BlockJobInfoList *head = NULL, **p_next = &head;
2602 BlockDriverState *bs;
2604 for (bs = bdrv_next(NULL); bs; bs = bdrv_next(bs)) {
2605 if (bs->job) {
2606 BlockJobInfoList *elem = g_new0(BlockJobInfoList, 1);
2607 elem->value = block_job_query(bs->job);
2608 *p_next = elem;
2609 p_next = &elem->next;
2613 return head;
2616 QemuOptsList qemu_common_drive_opts = {
2617 .name = "drive",
2618 .head = QTAILQ_HEAD_INITIALIZER(qemu_common_drive_opts.head),
2619 .desc = {
2621 .name = "snapshot",
2622 .type = QEMU_OPT_BOOL,
2623 .help = "enable/disable snapshot mode",
2625 .name = "discard",
2626 .type = QEMU_OPT_STRING,
2627 .help = "discard operation (ignore/off, unmap/on)",
2629 .name = "cache.writeback",
2630 .type = QEMU_OPT_BOOL,
2631 .help = "enables writeback mode for any caches",
2633 .name = "cache.direct",
2634 .type = QEMU_OPT_BOOL,
2635 .help = "enables use of O_DIRECT (bypass the host page cache)",
2637 .name = "cache.no-flush",
2638 .type = QEMU_OPT_BOOL,
2639 .help = "ignore any flush requests for the device",
2641 .name = "aio",
2642 .type = QEMU_OPT_STRING,
2643 .help = "host AIO implementation (threads, native)",
2645 .name = "format",
2646 .type = QEMU_OPT_STRING,
2647 .help = "disk format (raw, qcow2, ...)",
2649 .name = "rerror",
2650 .type = QEMU_OPT_STRING,
2651 .help = "read error action",
2653 .name = "werror",
2654 .type = QEMU_OPT_STRING,
2655 .help = "write error action",
2657 .name = "read-only",
2658 .type = QEMU_OPT_BOOL,
2659 .help = "open drive file as read-only",
2661 .name = "throttling.iops-total",
2662 .type = QEMU_OPT_NUMBER,
2663 .help = "limit total I/O operations per second",
2665 .name = "throttling.iops-read",
2666 .type = QEMU_OPT_NUMBER,
2667 .help = "limit read operations per second",
2669 .name = "throttling.iops-write",
2670 .type = QEMU_OPT_NUMBER,
2671 .help = "limit write operations per second",
2673 .name = "throttling.bps-total",
2674 .type = QEMU_OPT_NUMBER,
2675 .help = "limit total bytes per second",
2677 .name = "throttling.bps-read",
2678 .type = QEMU_OPT_NUMBER,
2679 .help = "limit read bytes per second",
2681 .name = "throttling.bps-write",
2682 .type = QEMU_OPT_NUMBER,
2683 .help = "limit write bytes per second",
2685 .name = "throttling.iops-total-max",
2686 .type = QEMU_OPT_NUMBER,
2687 .help = "I/O operations burst",
2689 .name = "throttling.iops-read-max",
2690 .type = QEMU_OPT_NUMBER,
2691 .help = "I/O operations read burst",
2693 .name = "throttling.iops-write-max",
2694 .type = QEMU_OPT_NUMBER,
2695 .help = "I/O operations write burst",
2697 .name = "throttling.bps-total-max",
2698 .type = QEMU_OPT_NUMBER,
2699 .help = "total bytes burst",
2701 .name = "throttling.bps-read-max",
2702 .type = QEMU_OPT_NUMBER,
2703 .help = "total bytes read burst",
2705 .name = "throttling.bps-write-max",
2706 .type = QEMU_OPT_NUMBER,
2707 .help = "total bytes write burst",
2709 .name = "throttling.iops-size",
2710 .type = QEMU_OPT_NUMBER,
2711 .help = "when limiting by iops max size of an I/O in bytes",
2713 .name = "copy-on-read",
2714 .type = QEMU_OPT_BOOL,
2715 .help = "copy read data from backing file into image file",
2717 .name = "detect-zeroes",
2718 .type = QEMU_OPT_STRING,
2719 .help = "try to optimize zero writes (off, on, unmap)",
2721 { /* end of list */ }
2725 QemuOptsList qemu_drive_opts = {
2726 .name = "drive",
2727 .head = QTAILQ_HEAD_INITIALIZER(qemu_drive_opts.head),
2728 .desc = {
2730 * no elements => accept any params
2731 * validation will happen later
2733 { /* end of list */ }