blockdev: Drop superfluous DriveInfo member id
[qemu.git] / blockdev.c
blobcdefbb001df7a0a09161035fb3a88675ccd9f087
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 && !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(BlockBackend *blk)
133 DriveInfo *dinfo = blk_legacy_dinfo(blk);
135 if (dinfo && dinfo->auto_del) {
136 blk_unref(blk);
141 * Returns the current mapping of how many units per bus
142 * a particular interface can support.
144 * A positive integer indicates n units per bus.
145 * 0 implies the mapping has not been established.
146 * -1 indicates an invalid BlockInterfaceType was given.
148 int drive_get_max_devs(BlockInterfaceType type)
150 if (type >= IF_IDE && type < IF_COUNT) {
151 return if_max_devs[type];
154 return -1;
157 static int drive_index_to_bus_id(BlockInterfaceType type, int index)
159 int max_devs = if_max_devs[type];
160 return max_devs ? index / max_devs : 0;
163 static int drive_index_to_unit_id(BlockInterfaceType type, int index)
165 int max_devs = if_max_devs[type];
166 return max_devs ? index % max_devs : index;
169 QemuOpts *drive_def(const char *optstr)
171 return qemu_opts_parse(qemu_find_opts("drive"), optstr, 0);
174 QemuOpts *drive_add(BlockInterfaceType type, int index, const char *file,
175 const char *optstr)
177 QemuOpts *opts;
178 char buf[32];
180 opts = drive_def(optstr);
181 if (!opts) {
182 return NULL;
184 if (type != IF_DEFAULT) {
185 qemu_opt_set(opts, "if", if_name[type]);
187 if (index >= 0) {
188 snprintf(buf, sizeof(buf), "%d", index);
189 qemu_opt_set(opts, "index", buf);
191 if (file)
192 qemu_opt_set(opts, "file", file);
193 return opts;
196 DriveInfo *drive_get(BlockInterfaceType type, int bus, int unit)
198 BlockBackend *blk;
199 DriveInfo *dinfo;
201 for (blk = blk_next(NULL); blk; blk = blk_next(blk)) {
202 dinfo = blk_legacy_dinfo(blk);
203 if (dinfo && dinfo->type == type
204 && dinfo->bus == bus && dinfo->unit == unit) {
205 return dinfo;
209 return NULL;
212 bool drive_check_orphaned(void)
214 BlockBackend *blk;
215 DriveInfo *dinfo;
216 bool rs = false;
218 for (blk = blk_next(NULL); blk; blk = blk_next(blk)) {
219 dinfo = blk_legacy_dinfo(blk);
220 /* If dinfo->bdrv->dev is NULL, it has no device attached. */
221 /* Unless this is a default drive, this may be an oversight. */
222 if (!blk_bs(blk)->dev && !dinfo->is_default &&
223 dinfo->type != IF_NONE) {
224 fprintf(stderr, "Warning: Orphaned drive without device: "
225 "id=%s,file=%s,if=%s,bus=%d,unit=%d\n",
226 blk_name(blk), blk_bs(blk)->filename, if_name[dinfo->type],
227 dinfo->bus, dinfo->unit);
228 rs = true;
232 return rs;
235 DriveInfo *drive_get_by_index(BlockInterfaceType type, int index)
237 return drive_get(type,
238 drive_index_to_bus_id(type, index),
239 drive_index_to_unit_id(type, index));
242 int drive_get_max_bus(BlockInterfaceType type)
244 int max_bus;
245 BlockBackend *blk;
246 DriveInfo *dinfo;
248 max_bus = -1;
249 for (blk = blk_next(NULL); blk; blk = blk_next(blk)) {
250 dinfo = blk_legacy_dinfo(blk);
251 if (dinfo && dinfo->type == type && dinfo->bus > max_bus) {
252 max_bus = dinfo->bus;
255 return max_bus;
258 /* Get a block device. This should only be used for single-drive devices
259 (e.g. SD/Floppy/MTD). Multi-disk devices (scsi/ide) should use the
260 appropriate bus. */
261 DriveInfo *drive_get_next(BlockInterfaceType type)
263 static int next_block_unit[IF_COUNT];
265 return drive_get(type, 0, next_block_unit[type]++);
268 static void bdrv_format_print(void *opaque, const char *name)
270 error_printf(" %s", name);
273 typedef struct {
274 QEMUBH *bh;
275 BlockDriverState *bs;
276 } BDRVPutRefBH;
278 static void bdrv_put_ref_bh(void *opaque)
280 BDRVPutRefBH *s = opaque;
282 bdrv_unref(s->bs);
283 qemu_bh_delete(s->bh);
284 g_free(s);
288 * Release a BDS reference in a BH
290 * It is not safe to use bdrv_unref() from a callback function when the callers
291 * still need the BlockDriverState. In such cases we schedule a BH to release
292 * the reference.
294 static void bdrv_put_ref_bh_schedule(BlockDriverState *bs)
296 BDRVPutRefBH *s;
298 s = g_new(BDRVPutRefBH, 1);
299 s->bh = qemu_bh_new(bdrv_put_ref_bh, s);
300 s->bs = bs;
301 qemu_bh_schedule(s->bh);
304 static int parse_block_error_action(const char *buf, bool is_read, Error **errp)
306 if (!strcmp(buf, "ignore")) {
307 return BLOCKDEV_ON_ERROR_IGNORE;
308 } else if (!is_read && !strcmp(buf, "enospc")) {
309 return BLOCKDEV_ON_ERROR_ENOSPC;
310 } else if (!strcmp(buf, "stop")) {
311 return BLOCKDEV_ON_ERROR_STOP;
312 } else if (!strcmp(buf, "report")) {
313 return BLOCKDEV_ON_ERROR_REPORT;
314 } else {
315 error_setg(errp, "'%s' invalid %s error action",
316 buf, is_read ? "read" : "write");
317 return -1;
321 static bool check_throttle_config(ThrottleConfig *cfg, Error **errp)
323 if (throttle_conflicting(cfg)) {
324 error_setg(errp, "bps/iops/max total values and read/write values"
325 " cannot be used at the same time");
326 return false;
329 if (!throttle_is_valid(cfg)) {
330 error_setg(errp, "bps/iops/maxs values must be 0 or greater");
331 return false;
334 return true;
337 typedef enum { MEDIA_DISK, MEDIA_CDROM } DriveMediaType;
339 /* Takes the ownership of bs_opts */
340 static BlockBackend *blockdev_init(const char *file, QDict *bs_opts,
341 Error **errp)
343 const char *buf;
344 int ro = 0;
345 int bdrv_flags = 0;
346 int on_read_error, on_write_error;
347 BlockBackend *blk;
348 BlockDriverState *bs;
349 DriveInfo *dinfo;
350 ThrottleConfig cfg;
351 int snapshot = 0;
352 bool copy_on_read;
353 int ret;
354 Error *error = NULL;
355 QemuOpts *opts;
356 const char *id;
357 bool has_driver_specific_opts;
358 BlockdevDetectZeroesOptions detect_zeroes;
359 BlockDriver *drv = NULL;
361 /* Check common options by copying from bs_opts to opts, all other options
362 * stay in bs_opts for processing by bdrv_open(). */
363 id = qdict_get_try_str(bs_opts, "id");
364 opts = qemu_opts_create(&qemu_common_drive_opts, id, 1, &error);
365 if (error) {
366 error_propagate(errp, error);
367 goto err_no_opts;
370 qemu_opts_absorb_qdict(opts, bs_opts, &error);
371 if (error) {
372 error_propagate(errp, error);
373 goto early_err;
376 if (id) {
377 qdict_del(bs_opts, "id");
380 has_driver_specific_opts = !!qdict_size(bs_opts);
382 /* extract parameters */
383 snapshot = qemu_opt_get_bool(opts, "snapshot", 0);
384 ro = qemu_opt_get_bool(opts, "read-only", 0);
385 copy_on_read = qemu_opt_get_bool(opts, "copy-on-read", false);
387 if ((buf = qemu_opt_get(opts, "discard")) != NULL) {
388 if (bdrv_parse_discard_flags(buf, &bdrv_flags) != 0) {
389 error_setg(errp, "invalid discard option");
390 goto early_err;
394 if (qemu_opt_get_bool(opts, "cache.writeback", true)) {
395 bdrv_flags |= BDRV_O_CACHE_WB;
397 if (qemu_opt_get_bool(opts, "cache.direct", false)) {
398 bdrv_flags |= BDRV_O_NOCACHE;
400 if (qemu_opt_get_bool(opts, "cache.no-flush", false)) {
401 bdrv_flags |= BDRV_O_NO_FLUSH;
404 #ifdef CONFIG_LINUX_AIO
405 if ((buf = qemu_opt_get(opts, "aio")) != NULL) {
406 if (!strcmp(buf, "native")) {
407 bdrv_flags |= BDRV_O_NATIVE_AIO;
408 } else if (!strcmp(buf, "threads")) {
409 /* this is the default */
410 } else {
411 error_setg(errp, "invalid aio option");
412 goto early_err;
415 #endif
417 if ((buf = qemu_opt_get(opts, "format")) != NULL) {
418 if (is_help_option(buf)) {
419 error_printf("Supported formats:");
420 bdrv_iterate_format(bdrv_format_print, NULL);
421 error_printf("\n");
422 goto early_err;
425 drv = bdrv_find_format(buf);
426 if (!drv) {
427 error_setg(errp, "'%s' invalid format", buf);
428 goto early_err;
432 /* disk I/O throttling */
433 memset(&cfg, 0, sizeof(cfg));
434 cfg.buckets[THROTTLE_BPS_TOTAL].avg =
435 qemu_opt_get_number(opts, "throttling.bps-total", 0);
436 cfg.buckets[THROTTLE_BPS_READ].avg =
437 qemu_opt_get_number(opts, "throttling.bps-read", 0);
438 cfg.buckets[THROTTLE_BPS_WRITE].avg =
439 qemu_opt_get_number(opts, "throttling.bps-write", 0);
440 cfg.buckets[THROTTLE_OPS_TOTAL].avg =
441 qemu_opt_get_number(opts, "throttling.iops-total", 0);
442 cfg.buckets[THROTTLE_OPS_READ].avg =
443 qemu_opt_get_number(opts, "throttling.iops-read", 0);
444 cfg.buckets[THROTTLE_OPS_WRITE].avg =
445 qemu_opt_get_number(opts, "throttling.iops-write", 0);
447 cfg.buckets[THROTTLE_BPS_TOTAL].max =
448 qemu_opt_get_number(opts, "throttling.bps-total-max", 0);
449 cfg.buckets[THROTTLE_BPS_READ].max =
450 qemu_opt_get_number(opts, "throttling.bps-read-max", 0);
451 cfg.buckets[THROTTLE_BPS_WRITE].max =
452 qemu_opt_get_number(opts, "throttling.bps-write-max", 0);
453 cfg.buckets[THROTTLE_OPS_TOTAL].max =
454 qemu_opt_get_number(opts, "throttling.iops-total-max", 0);
455 cfg.buckets[THROTTLE_OPS_READ].max =
456 qemu_opt_get_number(opts, "throttling.iops-read-max", 0);
457 cfg.buckets[THROTTLE_OPS_WRITE].max =
458 qemu_opt_get_number(opts, "throttling.iops-write-max", 0);
460 cfg.op_size = qemu_opt_get_number(opts, "throttling.iops-size", 0);
462 if (!check_throttle_config(&cfg, &error)) {
463 error_propagate(errp, error);
464 goto early_err;
467 on_write_error = BLOCKDEV_ON_ERROR_ENOSPC;
468 if ((buf = qemu_opt_get(opts, "werror")) != NULL) {
469 on_write_error = parse_block_error_action(buf, 0, &error);
470 if (error) {
471 error_propagate(errp, error);
472 goto early_err;
476 on_read_error = BLOCKDEV_ON_ERROR_REPORT;
477 if ((buf = qemu_opt_get(opts, "rerror")) != NULL) {
478 on_read_error = parse_block_error_action(buf, 1, &error);
479 if (error) {
480 error_propagate(errp, error);
481 goto early_err;
485 detect_zeroes =
486 qapi_enum_parse(BlockdevDetectZeroesOptions_lookup,
487 qemu_opt_get(opts, "detect-zeroes"),
488 BLOCKDEV_DETECT_ZEROES_OPTIONS_MAX,
489 BLOCKDEV_DETECT_ZEROES_OPTIONS_OFF,
490 &error);
491 if (error) {
492 error_propagate(errp, error);
493 goto early_err;
496 if (detect_zeroes == BLOCKDEV_DETECT_ZEROES_OPTIONS_UNMAP &&
497 !(bdrv_flags & BDRV_O_UNMAP)) {
498 error_setg(errp, "setting detect-zeroes to unmap is not allowed "
499 "without setting discard operation to unmap");
500 goto early_err;
503 /* init */
504 blk = blk_new_with_bs(qemu_opts_id(opts), errp);
505 if (!blk) {
506 goto early_err;
508 bs = blk_bs(blk);
509 bs->open_flags = snapshot ? BDRV_O_SNAPSHOT : 0;
510 bs->read_only = ro;
511 bs->detect_zeroes = detect_zeroes;
513 bdrv_set_on_error(bs, on_read_error, on_write_error);
515 /* disk I/O throttling */
516 if (throttle_enabled(&cfg)) {
517 bdrv_io_limits_enable(bs);
518 bdrv_set_io_limits(bs, &cfg);
521 dinfo = g_malloc0(sizeof(*dinfo));
522 blk_set_legacy_dinfo(blk, dinfo);
524 if (!file || !*file) {
525 if (has_driver_specific_opts) {
526 file = NULL;
527 } else {
528 QDECREF(bs_opts);
529 qemu_opts_del(opts);
530 return blk;
533 if (snapshot) {
534 /* always use cache=unsafe with snapshot */
535 bdrv_flags &= ~BDRV_O_CACHE_MASK;
536 bdrv_flags |= (BDRV_O_SNAPSHOT|BDRV_O_CACHE_WB|BDRV_O_NO_FLUSH);
539 if (copy_on_read) {
540 bdrv_flags |= BDRV_O_COPY_ON_READ;
543 if (runstate_check(RUN_STATE_INMIGRATE)) {
544 bdrv_flags |= BDRV_O_INCOMING;
547 bdrv_flags |= ro ? 0 : BDRV_O_RDWR;
549 QINCREF(bs_opts);
550 ret = bdrv_open(&bs, file, NULL, bs_opts, bdrv_flags, drv, &error);
551 assert(bs == blk_bs(blk));
553 if (ret < 0) {
554 error_setg(errp, "could not open disk image %s: %s",
555 file ?: blk_name(blk), error_get_pretty(error));
556 error_free(error);
557 goto err;
560 if (bdrv_key_required(bs)) {
561 autostart = 0;
564 QDECREF(bs_opts);
565 qemu_opts_del(opts);
567 return blk;
569 err:
570 blk_unref(blk);
571 early_err:
572 qemu_opts_del(opts);
573 err_no_opts:
574 QDECREF(bs_opts);
575 return NULL;
578 static void qemu_opt_rename(QemuOpts *opts, const char *from, const char *to,
579 Error **errp)
581 const char *value;
583 value = qemu_opt_get(opts, from);
584 if (value) {
585 if (qemu_opt_find(opts, to)) {
586 error_setg(errp, "'%s' and its alias '%s' can't be used at the "
587 "same time", to, from);
588 return;
592 /* rename all items in opts */
593 while ((value = qemu_opt_get(opts, from))) {
594 qemu_opt_set(opts, to, value);
595 qemu_opt_unset(opts, from);
599 QemuOptsList qemu_legacy_drive_opts = {
600 .name = "drive",
601 .head = QTAILQ_HEAD_INITIALIZER(qemu_legacy_drive_opts.head),
602 .desc = {
604 .name = "bus",
605 .type = QEMU_OPT_NUMBER,
606 .help = "bus number",
608 .name = "unit",
609 .type = QEMU_OPT_NUMBER,
610 .help = "unit number (i.e. lun for scsi)",
612 .name = "index",
613 .type = QEMU_OPT_NUMBER,
614 .help = "index number",
616 .name = "media",
617 .type = QEMU_OPT_STRING,
618 .help = "media type (disk, cdrom)",
620 .name = "if",
621 .type = QEMU_OPT_STRING,
622 .help = "interface (ide, scsi, sd, mtd, floppy, pflash, virtio)",
624 .name = "cyls",
625 .type = QEMU_OPT_NUMBER,
626 .help = "number of cylinders (ide disk geometry)",
628 .name = "heads",
629 .type = QEMU_OPT_NUMBER,
630 .help = "number of heads (ide disk geometry)",
632 .name = "secs",
633 .type = QEMU_OPT_NUMBER,
634 .help = "number of sectors (ide disk geometry)",
636 .name = "trans",
637 .type = QEMU_OPT_STRING,
638 .help = "chs translation (auto, lba, none)",
640 .name = "boot",
641 .type = QEMU_OPT_BOOL,
642 .help = "(deprecated, ignored)",
644 .name = "addr",
645 .type = QEMU_OPT_STRING,
646 .help = "pci address (virtio only)",
648 .name = "serial",
649 .type = QEMU_OPT_STRING,
650 .help = "disk serial number",
652 .name = "file",
653 .type = QEMU_OPT_STRING,
654 .help = "file name",
657 /* Options that are passed on, but have special semantics with -drive */
659 .name = "read-only",
660 .type = QEMU_OPT_BOOL,
661 .help = "open drive file as read-only",
663 .name = "rerror",
664 .type = QEMU_OPT_STRING,
665 .help = "read error action",
667 .name = "werror",
668 .type = QEMU_OPT_STRING,
669 .help = "write error action",
671 .name = "copy-on-read",
672 .type = QEMU_OPT_BOOL,
673 .help = "copy read data from backing file into image file",
676 { /* end of list */ }
680 DriveInfo *drive_new(QemuOpts *all_opts, BlockInterfaceType block_default_type)
682 const char *value;
683 BlockBackend *blk;
684 DriveInfo *dinfo = NULL;
685 QDict *bs_opts;
686 QemuOpts *legacy_opts;
687 DriveMediaType media = MEDIA_DISK;
688 BlockInterfaceType type;
689 int cyls, heads, secs, translation;
690 int max_devs, bus_id, unit_id, index;
691 const char *devaddr;
692 const char *werror, *rerror;
693 bool read_only = false;
694 bool copy_on_read;
695 const char *serial;
696 const char *filename;
697 Error *local_err = NULL;
698 int i;
700 /* Change legacy command line options into QMP ones */
701 static const struct {
702 const char *from;
703 const char *to;
704 } opt_renames[] = {
705 { "iops", "throttling.iops-total" },
706 { "iops_rd", "throttling.iops-read" },
707 { "iops_wr", "throttling.iops-write" },
709 { "bps", "throttling.bps-total" },
710 { "bps_rd", "throttling.bps-read" },
711 { "bps_wr", "throttling.bps-write" },
713 { "iops_max", "throttling.iops-total-max" },
714 { "iops_rd_max", "throttling.iops-read-max" },
715 { "iops_wr_max", "throttling.iops-write-max" },
717 { "bps_max", "throttling.bps-total-max" },
718 { "bps_rd_max", "throttling.bps-read-max" },
719 { "bps_wr_max", "throttling.bps-write-max" },
721 { "iops_size", "throttling.iops-size" },
723 { "readonly", "read-only" },
726 for (i = 0; i < ARRAY_SIZE(opt_renames); i++) {
727 qemu_opt_rename(all_opts, opt_renames[i].from, opt_renames[i].to,
728 &local_err);
729 if (local_err) {
730 error_report("%s", error_get_pretty(local_err));
731 error_free(local_err);
732 return NULL;
736 value = qemu_opt_get(all_opts, "cache");
737 if (value) {
738 int flags = 0;
740 if (bdrv_parse_cache_flags(value, &flags) != 0) {
741 error_report("invalid cache option");
742 return NULL;
745 /* Specific options take precedence */
746 if (!qemu_opt_get(all_opts, "cache.writeback")) {
747 qemu_opt_set_bool(all_opts, "cache.writeback",
748 !!(flags & BDRV_O_CACHE_WB));
750 if (!qemu_opt_get(all_opts, "cache.direct")) {
751 qemu_opt_set_bool(all_opts, "cache.direct",
752 !!(flags & BDRV_O_NOCACHE));
754 if (!qemu_opt_get(all_opts, "cache.no-flush")) {
755 qemu_opt_set_bool(all_opts, "cache.no-flush",
756 !!(flags & BDRV_O_NO_FLUSH));
758 qemu_opt_unset(all_opts, "cache");
761 /* Get a QDict for processing the options */
762 bs_opts = qdict_new();
763 qemu_opts_to_qdict(all_opts, bs_opts);
765 legacy_opts = qemu_opts_create(&qemu_legacy_drive_opts, NULL, 0,
766 &error_abort);
767 qemu_opts_absorb_qdict(legacy_opts, bs_opts, &local_err);
768 if (local_err) {
769 error_report("%s", error_get_pretty(local_err));
770 error_free(local_err);
771 goto fail;
774 /* Deprecated option boot=[on|off] */
775 if (qemu_opt_get(legacy_opts, "boot") != NULL) {
776 fprintf(stderr, "qemu-kvm: boot=on|off is deprecated and will be "
777 "ignored. Future versions will reject this parameter. Please "
778 "update your scripts.\n");
781 /* Media type */
782 value = qemu_opt_get(legacy_opts, "media");
783 if (value) {
784 if (!strcmp(value, "disk")) {
785 media = MEDIA_DISK;
786 } else if (!strcmp(value, "cdrom")) {
787 media = MEDIA_CDROM;
788 read_only = true;
789 } else {
790 error_report("'%s' invalid media", value);
791 goto fail;
795 /* copy-on-read is disabled with a warning for read-only devices */
796 read_only |= qemu_opt_get_bool(legacy_opts, "read-only", false);
797 copy_on_read = qemu_opt_get_bool(legacy_opts, "copy-on-read", false);
799 if (read_only && copy_on_read) {
800 error_report("warning: disabling copy-on-read on read-only drive");
801 copy_on_read = false;
804 qdict_put(bs_opts, "read-only",
805 qstring_from_str(read_only ? "on" : "off"));
806 qdict_put(bs_opts, "copy-on-read",
807 qstring_from_str(copy_on_read ? "on" :"off"));
809 /* Controller type */
810 value = qemu_opt_get(legacy_opts, "if");
811 if (value) {
812 for (type = 0;
813 type < IF_COUNT && strcmp(value, if_name[type]);
814 type++) {
816 if (type == IF_COUNT) {
817 error_report("unsupported bus type '%s'", value);
818 goto fail;
820 } else {
821 type = block_default_type;
824 /* Geometry */
825 cyls = qemu_opt_get_number(legacy_opts, "cyls", 0);
826 heads = qemu_opt_get_number(legacy_opts, "heads", 0);
827 secs = qemu_opt_get_number(legacy_opts, "secs", 0);
829 if (cyls || heads || secs) {
830 if (cyls < 1) {
831 error_report("invalid physical cyls number");
832 goto fail;
834 if (heads < 1) {
835 error_report("invalid physical heads number");
836 goto fail;
838 if (secs < 1) {
839 error_report("invalid physical secs number");
840 goto fail;
844 translation = BIOS_ATA_TRANSLATION_AUTO;
845 value = qemu_opt_get(legacy_opts, "trans");
846 if (value != NULL) {
847 if (!cyls) {
848 error_report("'%s' trans must be used with cyls, heads and secs",
849 value);
850 goto fail;
852 if (!strcmp(value, "none")) {
853 translation = BIOS_ATA_TRANSLATION_NONE;
854 } else if (!strcmp(value, "lba")) {
855 translation = BIOS_ATA_TRANSLATION_LBA;
856 } else if (!strcmp(value, "large")) {
857 translation = BIOS_ATA_TRANSLATION_LARGE;
858 } else if (!strcmp(value, "rechs")) {
859 translation = BIOS_ATA_TRANSLATION_RECHS;
860 } else if (!strcmp(value, "auto")) {
861 translation = BIOS_ATA_TRANSLATION_AUTO;
862 } else {
863 error_report("'%s' invalid translation type", value);
864 goto fail;
868 if (media == MEDIA_CDROM) {
869 if (cyls || secs || heads) {
870 error_report("CHS can't be set with media=cdrom");
871 goto fail;
875 /* Device address specified by bus/unit or index.
876 * If none was specified, try to find the first free one. */
877 bus_id = qemu_opt_get_number(legacy_opts, "bus", 0);
878 unit_id = qemu_opt_get_number(legacy_opts, "unit", -1);
879 index = qemu_opt_get_number(legacy_opts, "index", -1);
881 max_devs = if_max_devs[type];
883 if (index != -1) {
884 if (bus_id != 0 || unit_id != -1) {
885 error_report("index cannot be used with bus and unit");
886 goto fail;
888 bus_id = drive_index_to_bus_id(type, index);
889 unit_id = drive_index_to_unit_id(type, index);
892 if (unit_id == -1) {
893 unit_id = 0;
894 while (drive_get(type, bus_id, unit_id) != NULL) {
895 unit_id++;
896 if (max_devs && unit_id >= max_devs) {
897 unit_id -= max_devs;
898 bus_id++;
903 if (max_devs && unit_id >= max_devs) {
904 error_report("unit %d too big (max is %d)", unit_id, max_devs - 1);
905 goto fail;
908 if (drive_get(type, bus_id, unit_id) != NULL) {
909 error_report("drive with bus=%d, unit=%d (index=%d) exists",
910 bus_id, unit_id, index);
911 goto fail;
914 /* Serial number */
915 serial = qemu_opt_get(legacy_opts, "serial");
917 /* no id supplied -> create one */
918 if (qemu_opts_id(all_opts) == NULL) {
919 char *new_id;
920 const char *mediastr = "";
921 if (type == IF_IDE || type == IF_SCSI) {
922 mediastr = (media == MEDIA_CDROM) ? "-cd" : "-hd";
924 if (max_devs) {
925 new_id = g_strdup_printf("%s%i%s%i", if_name[type], bus_id,
926 mediastr, unit_id);
927 } else {
928 new_id = g_strdup_printf("%s%s%i", if_name[type],
929 mediastr, unit_id);
931 qdict_put(bs_opts, "id", qstring_from_str(new_id));
932 g_free(new_id);
935 /* Add virtio block device */
936 devaddr = qemu_opt_get(legacy_opts, "addr");
937 if (devaddr && type != IF_VIRTIO) {
938 error_report("addr is not supported by this bus type");
939 goto fail;
942 if (type == IF_VIRTIO) {
943 QemuOpts *devopts;
944 devopts = qemu_opts_create(qemu_find_opts("device"), NULL, 0,
945 &error_abort);
946 if (arch_type == QEMU_ARCH_S390X) {
947 qemu_opt_set(devopts, "driver", "virtio-blk-s390");
948 } else {
949 qemu_opt_set(devopts, "driver", "virtio-blk-pci");
951 qemu_opt_set(devopts, "drive", qdict_get_str(bs_opts, "id"));
952 if (devaddr) {
953 qemu_opt_set(devopts, "addr", devaddr);
957 filename = qemu_opt_get(legacy_opts, "file");
959 /* Check werror/rerror compatibility with if=... */
960 werror = qemu_opt_get(legacy_opts, "werror");
961 if (werror != NULL) {
962 if (type != IF_IDE && type != IF_SCSI && type != IF_VIRTIO &&
963 type != IF_NONE) {
964 error_report("werror is not supported by this bus type");
965 goto fail;
967 qdict_put(bs_opts, "werror", qstring_from_str(werror));
970 rerror = qemu_opt_get(legacy_opts, "rerror");
971 if (rerror != NULL) {
972 if (type != IF_IDE && type != IF_VIRTIO && type != IF_SCSI &&
973 type != IF_NONE) {
974 error_report("rerror is not supported by this bus type");
975 goto fail;
977 qdict_put(bs_opts, "rerror", qstring_from_str(rerror));
980 /* Actual block device init: Functionality shared with blockdev-add */
981 blk = blockdev_init(filename, bs_opts, &local_err);
982 bs_opts = NULL;
983 if (!blk) {
984 if (local_err) {
985 error_report("%s", error_get_pretty(local_err));
986 error_free(local_err);
988 goto fail;
989 } else {
990 assert(!local_err);
993 /* Set legacy DriveInfo fields */
994 dinfo = blk_legacy_dinfo(blk);
995 dinfo->enable_auto_del = true;
996 dinfo->opts = all_opts;
998 dinfo->cyls = cyls;
999 dinfo->heads = heads;
1000 dinfo->secs = secs;
1001 dinfo->trans = translation;
1003 dinfo->type = type;
1004 dinfo->bus = bus_id;
1005 dinfo->unit = unit_id;
1006 dinfo->devaddr = devaddr;
1008 dinfo->serial = g_strdup(serial);
1010 switch(type) {
1011 case IF_IDE:
1012 case IF_SCSI:
1013 case IF_XEN:
1014 case IF_NONE:
1015 dinfo->media_cd = media == MEDIA_CDROM;
1016 break;
1017 default:
1018 break;
1021 fail:
1022 qemu_opts_del(legacy_opts);
1023 QDECREF(bs_opts);
1024 return dinfo;
1027 void do_commit(Monitor *mon, const QDict *qdict)
1029 const char *device = qdict_get_str(qdict, "device");
1030 BlockDriverState *bs;
1031 int ret;
1033 if (!strcmp(device, "all")) {
1034 ret = bdrv_commit_all();
1035 } else {
1036 bs = bdrv_find(device);
1037 if (!bs) {
1038 monitor_printf(mon, "Device '%s' not found\n", device);
1039 return;
1041 ret = bdrv_commit(bs);
1043 if (ret < 0) {
1044 monitor_printf(mon, "'commit' error for '%s': %s\n", device,
1045 strerror(-ret));
1049 static void blockdev_do_action(int kind, void *data, Error **errp)
1051 TransactionAction action;
1052 TransactionActionList list;
1054 action.kind = kind;
1055 action.data = data;
1056 list.value = &action;
1057 list.next = NULL;
1058 qmp_transaction(&list, errp);
1061 void qmp_blockdev_snapshot_sync(bool has_device, const char *device,
1062 bool has_node_name, const char *node_name,
1063 const char *snapshot_file,
1064 bool has_snapshot_node_name,
1065 const char *snapshot_node_name,
1066 bool has_format, const char *format,
1067 bool has_mode, NewImageMode mode, Error **errp)
1069 BlockdevSnapshot snapshot = {
1070 .has_device = has_device,
1071 .device = (char *) device,
1072 .has_node_name = has_node_name,
1073 .node_name = (char *) node_name,
1074 .snapshot_file = (char *) snapshot_file,
1075 .has_snapshot_node_name = has_snapshot_node_name,
1076 .snapshot_node_name = (char *) snapshot_node_name,
1077 .has_format = has_format,
1078 .format = (char *) format,
1079 .has_mode = has_mode,
1080 .mode = mode,
1082 blockdev_do_action(TRANSACTION_ACTION_KIND_BLOCKDEV_SNAPSHOT_SYNC,
1083 &snapshot, errp);
1086 void qmp_blockdev_snapshot_internal_sync(const char *device,
1087 const char *name,
1088 Error **errp)
1090 BlockdevSnapshotInternal snapshot = {
1091 .device = (char *) device,
1092 .name = (char *) name
1095 blockdev_do_action(TRANSACTION_ACTION_KIND_BLOCKDEV_SNAPSHOT_INTERNAL_SYNC,
1096 &snapshot, errp);
1099 SnapshotInfo *qmp_blockdev_snapshot_delete_internal_sync(const char *device,
1100 bool has_id,
1101 const char *id,
1102 bool has_name,
1103 const char *name,
1104 Error **errp)
1106 BlockDriverState *bs = bdrv_find(device);
1107 QEMUSnapshotInfo sn;
1108 Error *local_err = NULL;
1109 SnapshotInfo *info = NULL;
1110 int ret;
1112 if (!bs) {
1113 error_set(errp, QERR_DEVICE_NOT_FOUND, device);
1114 return NULL;
1117 if (!has_id) {
1118 id = NULL;
1121 if (!has_name) {
1122 name = NULL;
1125 if (!id && !name) {
1126 error_setg(errp, "Name or id must be provided");
1127 return NULL;
1130 ret = bdrv_snapshot_find_by_id_and_name(bs, id, name, &sn, &local_err);
1131 if (local_err) {
1132 error_propagate(errp, local_err);
1133 return NULL;
1135 if (!ret) {
1136 error_setg(errp,
1137 "Snapshot with id '%s' and name '%s' does not exist on "
1138 "device '%s'",
1139 STR_OR_NULL(id), STR_OR_NULL(name), device);
1140 return NULL;
1143 bdrv_snapshot_delete(bs, id, name, &local_err);
1144 if (local_err) {
1145 error_propagate(errp, local_err);
1146 return NULL;
1149 info = g_new0(SnapshotInfo, 1);
1150 info->id = g_strdup(sn.id_str);
1151 info->name = g_strdup(sn.name);
1152 info->date_nsec = sn.date_nsec;
1153 info->date_sec = sn.date_sec;
1154 info->vm_state_size = sn.vm_state_size;
1155 info->vm_clock_nsec = sn.vm_clock_nsec % 1000000000;
1156 info->vm_clock_sec = sn.vm_clock_nsec / 1000000000;
1158 return info;
1161 /* New and old BlockDriverState structs for group snapshots */
1163 typedef struct BlkTransactionState BlkTransactionState;
1165 /* Only prepare() may fail. In a single transaction, only one of commit() or
1166 abort() will be called, clean() will always be called if it present. */
1167 typedef struct BdrvActionOps {
1168 /* Size of state struct, in bytes. */
1169 size_t instance_size;
1170 /* Prepare the work, must NOT be NULL. */
1171 void (*prepare)(BlkTransactionState *common, Error **errp);
1172 /* Commit the changes, can be NULL. */
1173 void (*commit)(BlkTransactionState *common);
1174 /* Abort the changes on fail, can be NULL. */
1175 void (*abort)(BlkTransactionState *common);
1176 /* Clean up resource in the end, can be NULL. */
1177 void (*clean)(BlkTransactionState *common);
1178 } BdrvActionOps;
1181 * This structure must be arranged as first member in child type, assuming
1182 * that compiler will also arrange it to the same address with parent instance.
1183 * Later it will be used in free().
1185 struct BlkTransactionState {
1186 TransactionAction *action;
1187 const BdrvActionOps *ops;
1188 QSIMPLEQ_ENTRY(BlkTransactionState) entry;
1191 /* internal snapshot private data */
1192 typedef struct InternalSnapshotState {
1193 BlkTransactionState common;
1194 BlockDriverState *bs;
1195 QEMUSnapshotInfo sn;
1196 } InternalSnapshotState;
1198 static void internal_snapshot_prepare(BlkTransactionState *common,
1199 Error **errp)
1201 Error *local_err = NULL;
1202 const char *device;
1203 const char *name;
1204 BlockDriverState *bs;
1205 QEMUSnapshotInfo old_sn, *sn;
1206 bool ret;
1207 qemu_timeval tv;
1208 BlockdevSnapshotInternal *internal;
1209 InternalSnapshotState *state;
1210 int ret1;
1212 g_assert(common->action->kind ==
1213 TRANSACTION_ACTION_KIND_BLOCKDEV_SNAPSHOT_INTERNAL_SYNC);
1214 internal = common->action->blockdev_snapshot_internal_sync;
1215 state = DO_UPCAST(InternalSnapshotState, common, common);
1217 /* 1. parse input */
1218 device = internal->device;
1219 name = internal->name;
1221 /* 2. check for validation */
1222 bs = bdrv_find(device);
1223 if (!bs) {
1224 error_set(errp, QERR_DEVICE_NOT_FOUND, device);
1225 return;
1228 if (!bdrv_is_inserted(bs)) {
1229 error_set(errp, QERR_DEVICE_HAS_NO_MEDIUM, device);
1230 return;
1233 if (bdrv_is_read_only(bs)) {
1234 error_set(errp, QERR_DEVICE_IS_READ_ONLY, device);
1235 return;
1238 if (!bdrv_can_snapshot(bs)) {
1239 error_set(errp, QERR_BLOCK_FORMAT_FEATURE_NOT_SUPPORTED,
1240 bs->drv->format_name, device, "internal snapshot");
1241 return;
1244 if (!strlen(name)) {
1245 error_setg(errp, "Name is empty");
1246 return;
1249 /* check whether a snapshot with name exist */
1250 ret = bdrv_snapshot_find_by_id_and_name(bs, NULL, name, &old_sn,
1251 &local_err);
1252 if (local_err) {
1253 error_propagate(errp, local_err);
1254 return;
1255 } else if (ret) {
1256 error_setg(errp,
1257 "Snapshot with name '%s' already exists on device '%s'",
1258 name, device);
1259 return;
1262 /* 3. take the snapshot */
1263 sn = &state->sn;
1264 pstrcpy(sn->name, sizeof(sn->name), name);
1265 qemu_gettimeofday(&tv);
1266 sn->date_sec = tv.tv_sec;
1267 sn->date_nsec = tv.tv_usec * 1000;
1268 sn->vm_clock_nsec = qemu_clock_get_ns(QEMU_CLOCK_VIRTUAL);
1270 ret1 = bdrv_snapshot_create(bs, sn);
1271 if (ret1 < 0) {
1272 error_setg_errno(errp, -ret1,
1273 "Failed to create snapshot '%s' on device '%s'",
1274 name, device);
1275 return;
1278 /* 4. succeed, mark a snapshot is created */
1279 state->bs = bs;
1282 static void internal_snapshot_abort(BlkTransactionState *common)
1284 InternalSnapshotState *state =
1285 DO_UPCAST(InternalSnapshotState, common, common);
1286 BlockDriverState *bs = state->bs;
1287 QEMUSnapshotInfo *sn = &state->sn;
1288 Error *local_error = NULL;
1290 if (!bs) {
1291 return;
1294 if (bdrv_snapshot_delete(bs, sn->id_str, sn->name, &local_error) < 0) {
1295 error_report("Failed to delete snapshot with id '%s' and name '%s' on "
1296 "device '%s' in abort: %s",
1297 sn->id_str,
1298 sn->name,
1299 bdrv_get_device_name(bs),
1300 error_get_pretty(local_error));
1301 error_free(local_error);
1305 /* external snapshot private data */
1306 typedef struct ExternalSnapshotState {
1307 BlkTransactionState common;
1308 BlockDriverState *old_bs;
1309 BlockDriverState *new_bs;
1310 } ExternalSnapshotState;
1312 static void external_snapshot_prepare(BlkTransactionState *common,
1313 Error **errp)
1315 BlockDriver *drv;
1316 int flags, ret;
1317 QDict *options = NULL;
1318 Error *local_err = NULL;
1319 bool has_device = false;
1320 const char *device;
1321 bool has_node_name = false;
1322 const char *node_name;
1323 bool has_snapshot_node_name = false;
1324 const char *snapshot_node_name;
1325 const char *new_image_file;
1326 const char *format = "qcow2";
1327 enum NewImageMode mode = NEW_IMAGE_MODE_ABSOLUTE_PATHS;
1328 ExternalSnapshotState *state =
1329 DO_UPCAST(ExternalSnapshotState, common, common);
1330 TransactionAction *action = common->action;
1332 /* get parameters */
1333 g_assert(action->kind == TRANSACTION_ACTION_KIND_BLOCKDEV_SNAPSHOT_SYNC);
1335 has_device = action->blockdev_snapshot_sync->has_device;
1336 device = action->blockdev_snapshot_sync->device;
1337 has_node_name = action->blockdev_snapshot_sync->has_node_name;
1338 node_name = action->blockdev_snapshot_sync->node_name;
1339 has_snapshot_node_name =
1340 action->blockdev_snapshot_sync->has_snapshot_node_name;
1341 snapshot_node_name = action->blockdev_snapshot_sync->snapshot_node_name;
1343 new_image_file = action->blockdev_snapshot_sync->snapshot_file;
1344 if (action->blockdev_snapshot_sync->has_format) {
1345 format = action->blockdev_snapshot_sync->format;
1347 if (action->blockdev_snapshot_sync->has_mode) {
1348 mode = action->blockdev_snapshot_sync->mode;
1351 /* start processing */
1352 drv = bdrv_find_format(format);
1353 if (!drv) {
1354 error_set(errp, QERR_INVALID_BLOCK_FORMAT, format);
1355 return;
1358 state->old_bs = bdrv_lookup_bs(has_device ? device : NULL,
1359 has_node_name ? node_name : NULL,
1360 &local_err);
1361 if (local_err) {
1362 error_propagate(errp, local_err);
1363 return;
1366 if (has_node_name && !has_snapshot_node_name) {
1367 error_setg(errp, "New snapshot node name missing");
1368 return;
1371 if (has_snapshot_node_name && bdrv_find_node(snapshot_node_name)) {
1372 error_setg(errp, "New snapshot node name already existing");
1373 return;
1376 if (!bdrv_is_inserted(state->old_bs)) {
1377 error_set(errp, QERR_DEVICE_HAS_NO_MEDIUM, device);
1378 return;
1381 if (bdrv_op_is_blocked(state->old_bs,
1382 BLOCK_OP_TYPE_EXTERNAL_SNAPSHOT, errp)) {
1383 return;
1386 if (!bdrv_is_read_only(state->old_bs)) {
1387 if (bdrv_flush(state->old_bs)) {
1388 error_set(errp, QERR_IO_ERROR);
1389 return;
1393 if (!bdrv_is_first_non_filter(state->old_bs)) {
1394 error_set(errp, QERR_FEATURE_DISABLED, "snapshot");
1395 return;
1398 flags = state->old_bs->open_flags;
1400 /* create new image w/backing file */
1401 if (mode != NEW_IMAGE_MODE_EXISTING) {
1402 bdrv_img_create(new_image_file, format,
1403 state->old_bs->filename,
1404 state->old_bs->drv->format_name,
1405 NULL, -1, flags, &local_err, false);
1406 if (local_err) {
1407 error_propagate(errp, local_err);
1408 return;
1412 if (has_snapshot_node_name) {
1413 options = qdict_new();
1414 qdict_put(options, "node-name",
1415 qstring_from_str(snapshot_node_name));
1418 /* TODO Inherit bs->options or only take explicit options with an
1419 * extended QMP command? */
1420 assert(state->new_bs == NULL);
1421 ret = bdrv_open(&state->new_bs, new_image_file, NULL, options,
1422 flags | BDRV_O_NO_BACKING, drv, &local_err);
1423 /* We will manually add the backing_hd field to the bs later */
1424 if (ret != 0) {
1425 error_propagate(errp, local_err);
1429 static void external_snapshot_commit(BlkTransactionState *common)
1431 ExternalSnapshotState *state =
1432 DO_UPCAST(ExternalSnapshotState, common, common);
1434 /* This removes our old bs and adds the new bs */
1435 bdrv_append(state->new_bs, state->old_bs);
1436 /* We don't need (or want) to use the transactional
1437 * bdrv_reopen_multiple() across all the entries at once, because we
1438 * don't want to abort all of them if one of them fails the reopen */
1439 bdrv_reopen(state->new_bs, state->new_bs->open_flags & ~BDRV_O_RDWR,
1440 NULL);
1443 static void external_snapshot_abort(BlkTransactionState *common)
1445 ExternalSnapshotState *state =
1446 DO_UPCAST(ExternalSnapshotState, common, common);
1447 if (state->new_bs) {
1448 bdrv_unref(state->new_bs);
1452 typedef struct DriveBackupState {
1453 BlkTransactionState common;
1454 BlockDriverState *bs;
1455 BlockJob *job;
1456 } DriveBackupState;
1458 static void drive_backup_prepare(BlkTransactionState *common, Error **errp)
1460 DriveBackupState *state = DO_UPCAST(DriveBackupState, common, common);
1461 DriveBackup *backup;
1462 Error *local_err = NULL;
1464 assert(common->action->kind == TRANSACTION_ACTION_KIND_DRIVE_BACKUP);
1465 backup = common->action->drive_backup;
1467 qmp_drive_backup(backup->device, backup->target,
1468 backup->has_format, backup->format,
1469 backup->sync,
1470 backup->has_mode, backup->mode,
1471 backup->has_speed, backup->speed,
1472 backup->has_on_source_error, backup->on_source_error,
1473 backup->has_on_target_error, backup->on_target_error,
1474 &local_err);
1475 if (local_err) {
1476 error_propagate(errp, local_err);
1477 state->bs = NULL;
1478 state->job = NULL;
1479 return;
1482 state->bs = bdrv_find(backup->device);
1483 state->job = state->bs->job;
1486 static void drive_backup_abort(BlkTransactionState *common)
1488 DriveBackupState *state = DO_UPCAST(DriveBackupState, common, common);
1489 BlockDriverState *bs = state->bs;
1491 /* Only cancel if it's the job we started */
1492 if (bs && bs->job && bs->job == state->job) {
1493 block_job_cancel_sync(bs->job);
1497 static void abort_prepare(BlkTransactionState *common, Error **errp)
1499 error_setg(errp, "Transaction aborted using Abort action");
1502 static void abort_commit(BlkTransactionState *common)
1504 g_assert_not_reached(); /* this action never succeeds */
1507 static const BdrvActionOps actions[] = {
1508 [TRANSACTION_ACTION_KIND_BLOCKDEV_SNAPSHOT_SYNC] = {
1509 .instance_size = sizeof(ExternalSnapshotState),
1510 .prepare = external_snapshot_prepare,
1511 .commit = external_snapshot_commit,
1512 .abort = external_snapshot_abort,
1514 [TRANSACTION_ACTION_KIND_DRIVE_BACKUP] = {
1515 .instance_size = sizeof(DriveBackupState),
1516 .prepare = drive_backup_prepare,
1517 .abort = drive_backup_abort,
1519 [TRANSACTION_ACTION_KIND_ABORT] = {
1520 .instance_size = sizeof(BlkTransactionState),
1521 .prepare = abort_prepare,
1522 .commit = abort_commit,
1524 [TRANSACTION_ACTION_KIND_BLOCKDEV_SNAPSHOT_INTERNAL_SYNC] = {
1525 .instance_size = sizeof(InternalSnapshotState),
1526 .prepare = internal_snapshot_prepare,
1527 .abort = internal_snapshot_abort,
1532 * 'Atomic' group snapshots. The snapshots are taken as a set, and if any fail
1533 * then we do not pivot any of the devices in the group, and abandon the
1534 * snapshots
1536 void qmp_transaction(TransactionActionList *dev_list, Error **errp)
1538 TransactionActionList *dev_entry = dev_list;
1539 BlkTransactionState *state, *next;
1540 Error *local_err = NULL;
1542 QSIMPLEQ_HEAD(snap_bdrv_states, BlkTransactionState) snap_bdrv_states;
1543 QSIMPLEQ_INIT(&snap_bdrv_states);
1545 /* drain all i/o before any snapshots */
1546 bdrv_drain_all();
1548 /* We don't do anything in this loop that commits us to the snapshot */
1549 while (NULL != dev_entry) {
1550 TransactionAction *dev_info = NULL;
1551 const BdrvActionOps *ops;
1553 dev_info = dev_entry->value;
1554 dev_entry = dev_entry->next;
1556 assert(dev_info->kind < ARRAY_SIZE(actions));
1558 ops = &actions[dev_info->kind];
1559 assert(ops->instance_size > 0);
1561 state = g_malloc0(ops->instance_size);
1562 state->ops = ops;
1563 state->action = dev_info;
1564 QSIMPLEQ_INSERT_TAIL(&snap_bdrv_states, state, entry);
1566 state->ops->prepare(state, &local_err);
1567 if (local_err) {
1568 error_propagate(errp, local_err);
1569 goto delete_and_fail;
1573 QSIMPLEQ_FOREACH(state, &snap_bdrv_states, entry) {
1574 if (state->ops->commit) {
1575 state->ops->commit(state);
1579 /* success */
1580 goto exit;
1582 delete_and_fail:
1584 * failure, and it is all-or-none; abandon each new bs, and keep using
1585 * the original bs for all images
1587 QSIMPLEQ_FOREACH(state, &snap_bdrv_states, entry) {
1588 if (state->ops->abort) {
1589 state->ops->abort(state);
1592 exit:
1593 QSIMPLEQ_FOREACH_SAFE(state, &snap_bdrv_states, entry, next) {
1594 if (state->ops->clean) {
1595 state->ops->clean(state);
1597 g_free(state);
1602 static void eject_device(BlockDriverState *bs, int force, Error **errp)
1604 if (bdrv_op_is_blocked(bs, BLOCK_OP_TYPE_EJECT, errp)) {
1605 return;
1607 if (!bdrv_dev_has_removable_media(bs)) {
1608 error_setg(errp, "Device '%s' is not removable",
1609 bdrv_get_device_name(bs));
1610 return;
1613 if (bdrv_dev_is_medium_locked(bs) && !bdrv_dev_is_tray_open(bs)) {
1614 bdrv_dev_eject_request(bs, force);
1615 if (!force) {
1616 error_setg(errp, "Device '%s' is locked",
1617 bdrv_get_device_name(bs));
1618 return;
1622 bdrv_close(bs);
1625 void qmp_eject(const char *device, bool has_force, bool force, Error **errp)
1627 BlockDriverState *bs;
1629 bs = bdrv_find(device);
1630 if (!bs) {
1631 error_set(errp, QERR_DEVICE_NOT_FOUND, device);
1632 return;
1635 eject_device(bs, force, errp);
1638 void qmp_block_passwd(bool has_device, const char *device,
1639 bool has_node_name, const char *node_name,
1640 const char *password, Error **errp)
1642 Error *local_err = NULL;
1643 BlockDriverState *bs;
1644 int err;
1646 bs = bdrv_lookup_bs(has_device ? device : NULL,
1647 has_node_name ? node_name : NULL,
1648 &local_err);
1649 if (local_err) {
1650 error_propagate(errp, local_err);
1651 return;
1654 err = bdrv_set_key(bs, password);
1655 if (err == -EINVAL) {
1656 error_set(errp, QERR_DEVICE_NOT_ENCRYPTED, bdrv_get_device_name(bs));
1657 return;
1658 } else if (err < 0) {
1659 error_set(errp, QERR_INVALID_PASSWORD);
1660 return;
1664 static void qmp_bdrv_open_encrypted(BlockDriverState *bs, const char *filename,
1665 int bdrv_flags, BlockDriver *drv,
1666 const char *password, Error **errp)
1668 Error *local_err = NULL;
1669 int ret;
1671 ret = bdrv_open(&bs, filename, NULL, NULL, bdrv_flags, drv, &local_err);
1672 if (ret < 0) {
1673 error_propagate(errp, local_err);
1674 return;
1677 if (bdrv_key_required(bs)) {
1678 if (password) {
1679 if (bdrv_set_key(bs, password) < 0) {
1680 error_set(errp, QERR_INVALID_PASSWORD);
1682 } else {
1683 error_set(errp, QERR_DEVICE_ENCRYPTED, bdrv_get_device_name(bs),
1684 bdrv_get_encrypted_filename(bs));
1686 } else if (password) {
1687 error_set(errp, QERR_DEVICE_NOT_ENCRYPTED, bdrv_get_device_name(bs));
1691 void qmp_change_blockdev(const char *device, const char *filename,
1692 const char *format, Error **errp)
1694 BlockDriverState *bs;
1695 BlockDriver *drv = NULL;
1696 int bdrv_flags;
1697 Error *err = NULL;
1699 bs = bdrv_find(device);
1700 if (!bs) {
1701 error_set(errp, QERR_DEVICE_NOT_FOUND, device);
1702 return;
1705 if (format) {
1706 drv = bdrv_find_whitelisted_format(format, bs->read_only);
1707 if (!drv) {
1708 error_set(errp, QERR_INVALID_BLOCK_FORMAT, format);
1709 return;
1713 eject_device(bs, 0, &err);
1714 if (err) {
1715 error_propagate(errp, err);
1716 return;
1719 bdrv_flags = bdrv_is_read_only(bs) ? 0 : BDRV_O_RDWR;
1720 bdrv_flags |= bdrv_is_snapshot(bs) ? BDRV_O_SNAPSHOT : 0;
1722 qmp_bdrv_open_encrypted(bs, filename, bdrv_flags, drv, NULL, errp);
1725 /* throttling disk I/O limits */
1726 void qmp_block_set_io_throttle(const char *device, int64_t bps, int64_t bps_rd,
1727 int64_t bps_wr,
1728 int64_t iops,
1729 int64_t iops_rd,
1730 int64_t iops_wr,
1731 bool has_bps_max,
1732 int64_t bps_max,
1733 bool has_bps_rd_max,
1734 int64_t bps_rd_max,
1735 bool has_bps_wr_max,
1736 int64_t bps_wr_max,
1737 bool has_iops_max,
1738 int64_t iops_max,
1739 bool has_iops_rd_max,
1740 int64_t iops_rd_max,
1741 bool has_iops_wr_max,
1742 int64_t iops_wr_max,
1743 bool has_iops_size,
1744 int64_t iops_size, Error **errp)
1746 ThrottleConfig cfg;
1747 BlockDriverState *bs;
1748 AioContext *aio_context;
1750 bs = bdrv_find(device);
1751 if (!bs) {
1752 error_set(errp, QERR_DEVICE_NOT_FOUND, device);
1753 return;
1756 memset(&cfg, 0, sizeof(cfg));
1757 cfg.buckets[THROTTLE_BPS_TOTAL].avg = bps;
1758 cfg.buckets[THROTTLE_BPS_READ].avg = bps_rd;
1759 cfg.buckets[THROTTLE_BPS_WRITE].avg = bps_wr;
1761 cfg.buckets[THROTTLE_OPS_TOTAL].avg = iops;
1762 cfg.buckets[THROTTLE_OPS_READ].avg = iops_rd;
1763 cfg.buckets[THROTTLE_OPS_WRITE].avg = iops_wr;
1765 if (has_bps_max) {
1766 cfg.buckets[THROTTLE_BPS_TOTAL].max = bps_max;
1768 if (has_bps_rd_max) {
1769 cfg.buckets[THROTTLE_BPS_READ].max = bps_rd_max;
1771 if (has_bps_wr_max) {
1772 cfg.buckets[THROTTLE_BPS_WRITE].max = bps_wr_max;
1774 if (has_iops_max) {
1775 cfg.buckets[THROTTLE_OPS_TOTAL].max = iops_max;
1777 if (has_iops_rd_max) {
1778 cfg.buckets[THROTTLE_OPS_READ].max = iops_rd_max;
1780 if (has_iops_wr_max) {
1781 cfg.buckets[THROTTLE_OPS_WRITE].max = iops_wr_max;
1784 if (has_iops_size) {
1785 cfg.op_size = iops_size;
1788 if (!check_throttle_config(&cfg, errp)) {
1789 return;
1792 aio_context = bdrv_get_aio_context(bs);
1793 aio_context_acquire(aio_context);
1795 if (!bs->io_limits_enabled && throttle_enabled(&cfg)) {
1796 bdrv_io_limits_enable(bs);
1797 } else if (bs->io_limits_enabled && !throttle_enabled(&cfg)) {
1798 bdrv_io_limits_disable(bs);
1801 if (bs->io_limits_enabled) {
1802 bdrv_set_io_limits(bs, &cfg);
1805 aio_context_release(aio_context);
1808 int do_drive_del(Monitor *mon, const QDict *qdict, QObject **ret_data)
1810 const char *id = qdict_get_str(qdict, "id");
1811 BlockBackend *blk;
1812 BlockDriverState *bs;
1813 DriveInfo *dinfo;
1814 AioContext *aio_context;
1815 Error *local_err = NULL;
1817 blk = blk_by_name(id);
1818 if (!blk) {
1819 error_report("Device '%s' not found", id);
1820 return -1;
1822 bs = blk_bs(blk);
1824 dinfo = blk_legacy_dinfo(blk);
1825 if (dinfo && !dinfo->enable_auto_del) {
1826 error_report("Deleting device added with blockdev-add"
1827 " is not supported");
1828 return -1;
1831 aio_context = bdrv_get_aio_context(bs);
1832 aio_context_acquire(aio_context);
1834 if (bdrv_op_is_blocked(bs, BLOCK_OP_TYPE_DRIVE_DEL, &local_err)) {
1835 error_report("%s", error_get_pretty(local_err));
1836 error_free(local_err);
1837 aio_context_release(aio_context);
1838 return -1;
1841 /* quiesce block driver; prevent further io */
1842 bdrv_drain_all();
1843 bdrv_flush(bs);
1844 bdrv_close(bs);
1846 /* if we have a device attached to this BlockDriverState
1847 * then we need to make the drive anonymous until the device
1848 * can be removed. If this is a drive with no device backing
1849 * then we can just get rid of the block driver state right here.
1851 if (bdrv_get_attached_dev(bs)) {
1852 blk_hide_on_behalf_of_do_drive_del(blk);
1853 /* Further I/O must not pause the guest */
1854 bdrv_set_on_error(bs, BLOCKDEV_ON_ERROR_REPORT,
1855 BLOCKDEV_ON_ERROR_REPORT);
1856 } else {
1857 blk_unref(blk);
1860 aio_context_release(aio_context);
1861 return 0;
1864 void qmp_block_resize(bool has_device, const char *device,
1865 bool has_node_name, const char *node_name,
1866 int64_t size, Error **errp)
1868 Error *local_err = NULL;
1869 BlockDriverState *bs;
1870 AioContext *aio_context;
1871 int ret;
1873 bs = bdrv_lookup_bs(has_device ? device : NULL,
1874 has_node_name ? node_name : NULL,
1875 &local_err);
1876 if (local_err) {
1877 error_propagate(errp, local_err);
1878 return;
1881 aio_context = bdrv_get_aio_context(bs);
1882 aio_context_acquire(aio_context);
1884 if (!bdrv_is_first_non_filter(bs)) {
1885 error_set(errp, QERR_FEATURE_DISABLED, "resize");
1886 goto out;
1889 if (size < 0) {
1890 error_set(errp, QERR_INVALID_PARAMETER_VALUE, "size", "a >0 size");
1891 goto out;
1894 if (bdrv_op_is_blocked(bs, BLOCK_OP_TYPE_RESIZE, NULL)) {
1895 error_set(errp, QERR_DEVICE_IN_USE, device);
1896 goto out;
1899 /* complete all in-flight operations before resizing the device */
1900 bdrv_drain_all();
1902 ret = bdrv_truncate(bs, size);
1903 switch (ret) {
1904 case 0:
1905 break;
1906 case -ENOMEDIUM:
1907 error_set(errp, QERR_DEVICE_HAS_NO_MEDIUM, device);
1908 break;
1909 case -ENOTSUP:
1910 error_set(errp, QERR_UNSUPPORTED);
1911 break;
1912 case -EACCES:
1913 error_set(errp, QERR_DEVICE_IS_READ_ONLY, device);
1914 break;
1915 case -EBUSY:
1916 error_set(errp, QERR_DEVICE_IN_USE, device);
1917 break;
1918 default:
1919 error_setg_errno(errp, -ret, "Could not resize");
1920 break;
1923 out:
1924 aio_context_release(aio_context);
1927 static void block_job_cb(void *opaque, int ret)
1929 BlockDriverState *bs = opaque;
1930 const char *msg = NULL;
1932 trace_block_job_cb(bs, bs->job, ret);
1934 assert(bs->job);
1936 if (ret < 0) {
1937 msg = strerror(-ret);
1940 if (block_job_is_cancelled(bs->job)) {
1941 block_job_event_cancelled(bs->job);
1942 } else {
1943 block_job_event_completed(bs->job, msg);
1946 bdrv_put_ref_bh_schedule(bs);
1949 void qmp_block_stream(const char *device,
1950 bool has_base, const char *base,
1951 bool has_backing_file, const char *backing_file,
1952 bool has_speed, int64_t speed,
1953 bool has_on_error, BlockdevOnError on_error,
1954 Error **errp)
1956 BlockDriverState *bs;
1957 BlockDriverState *base_bs = NULL;
1958 Error *local_err = NULL;
1959 const char *base_name = NULL;
1961 if (!has_on_error) {
1962 on_error = BLOCKDEV_ON_ERROR_REPORT;
1965 bs = bdrv_find(device);
1966 if (!bs) {
1967 error_set(errp, QERR_DEVICE_NOT_FOUND, device);
1968 return;
1971 if (bdrv_op_is_blocked(bs, BLOCK_OP_TYPE_STREAM, errp)) {
1972 return;
1975 if (has_base) {
1976 base_bs = bdrv_find_backing_image(bs, base);
1977 if (base_bs == NULL) {
1978 error_set(errp, QERR_BASE_NOT_FOUND, base);
1979 return;
1981 base_name = base;
1984 /* if we are streaming the entire chain, the result will have no backing
1985 * file, and specifying one is therefore an error */
1986 if (base_bs == NULL && has_backing_file) {
1987 error_setg(errp, "backing file specified, but streaming the "
1988 "entire chain");
1989 return;
1992 /* backing_file string overrides base bs filename */
1993 base_name = has_backing_file ? backing_file : base_name;
1995 stream_start(bs, base_bs, base_name, has_speed ? speed : 0,
1996 on_error, block_job_cb, bs, &local_err);
1997 if (local_err) {
1998 error_propagate(errp, local_err);
1999 return;
2002 trace_qmp_block_stream(bs, bs->job);
2005 void qmp_block_commit(const char *device,
2006 bool has_base, const char *base,
2007 bool has_top, const char *top,
2008 bool has_backing_file, const char *backing_file,
2009 bool has_speed, int64_t speed,
2010 Error **errp)
2012 BlockDriverState *bs;
2013 BlockDriverState *base_bs, *top_bs;
2014 Error *local_err = NULL;
2015 /* This will be part of the QMP command, if/when the
2016 * BlockdevOnError change for blkmirror makes it in
2018 BlockdevOnError on_error = BLOCKDEV_ON_ERROR_REPORT;
2020 if (!has_speed) {
2021 speed = 0;
2024 /* drain all i/o before commits */
2025 bdrv_drain_all();
2027 /* Important Note:
2028 * libvirt relies on the DeviceNotFound error class in order to probe for
2029 * live commit feature versions; for this to work, we must make sure to
2030 * perform the device lookup before any generic errors that may occur in a
2031 * scenario in which all optional arguments are omitted. */
2032 bs = bdrv_find(device);
2033 if (!bs) {
2034 error_set(errp, QERR_DEVICE_NOT_FOUND, device);
2035 return;
2038 if (bdrv_op_is_blocked(bs, BLOCK_OP_TYPE_COMMIT, errp)) {
2039 return;
2042 /* default top_bs is the active layer */
2043 top_bs = bs;
2045 if (has_top && top) {
2046 if (strcmp(bs->filename, top) != 0) {
2047 top_bs = bdrv_find_backing_image(bs, top);
2051 if (top_bs == NULL) {
2052 error_setg(errp, "Top image file %s not found", top ? top : "NULL");
2053 return;
2056 if (has_base && base) {
2057 base_bs = bdrv_find_backing_image(top_bs, base);
2058 } else {
2059 base_bs = bdrv_find_base(top_bs);
2062 if (base_bs == NULL) {
2063 error_set(errp, QERR_BASE_NOT_FOUND, base ? base : "NULL");
2064 return;
2067 /* Do not allow attempts to commit an image into itself */
2068 if (top_bs == base_bs) {
2069 error_setg(errp, "cannot commit an image into itself");
2070 return;
2073 if (top_bs == bs) {
2074 if (has_backing_file) {
2075 error_setg(errp, "'backing-file' specified,"
2076 " but 'top' is the active layer");
2077 return;
2079 commit_active_start(bs, base_bs, speed, on_error, block_job_cb,
2080 bs, &local_err);
2081 } else {
2082 commit_start(bs, base_bs, top_bs, speed, on_error, block_job_cb, bs,
2083 has_backing_file ? backing_file : NULL, &local_err);
2085 if (local_err != NULL) {
2086 error_propagate(errp, local_err);
2087 return;
2091 void qmp_drive_backup(const char *device, const char *target,
2092 bool has_format, const char *format,
2093 enum MirrorSyncMode sync,
2094 bool has_mode, enum NewImageMode mode,
2095 bool has_speed, int64_t speed,
2096 bool has_on_source_error, BlockdevOnError on_source_error,
2097 bool has_on_target_error, BlockdevOnError on_target_error,
2098 Error **errp)
2100 BlockDriverState *bs;
2101 BlockDriverState *target_bs;
2102 BlockDriverState *source = NULL;
2103 BlockDriver *drv = NULL;
2104 Error *local_err = NULL;
2105 int flags;
2106 int64_t size;
2107 int ret;
2109 if (!has_speed) {
2110 speed = 0;
2112 if (!has_on_source_error) {
2113 on_source_error = BLOCKDEV_ON_ERROR_REPORT;
2115 if (!has_on_target_error) {
2116 on_target_error = BLOCKDEV_ON_ERROR_REPORT;
2118 if (!has_mode) {
2119 mode = NEW_IMAGE_MODE_ABSOLUTE_PATHS;
2122 bs = bdrv_find(device);
2123 if (!bs) {
2124 error_set(errp, QERR_DEVICE_NOT_FOUND, device);
2125 return;
2128 if (!bdrv_is_inserted(bs)) {
2129 error_set(errp, QERR_DEVICE_HAS_NO_MEDIUM, device);
2130 return;
2133 if (!has_format) {
2134 format = mode == NEW_IMAGE_MODE_EXISTING ? NULL : bs->drv->format_name;
2136 if (format) {
2137 drv = bdrv_find_format(format);
2138 if (!drv) {
2139 error_set(errp, QERR_INVALID_BLOCK_FORMAT, format);
2140 return;
2144 if (bdrv_op_is_blocked(bs, BLOCK_OP_TYPE_BACKUP_SOURCE, errp)) {
2145 return;
2148 flags = bs->open_flags | BDRV_O_RDWR;
2150 /* See if we have a backing HD we can use to create our new image
2151 * on top of. */
2152 if (sync == MIRROR_SYNC_MODE_TOP) {
2153 source = bs->backing_hd;
2154 if (!source) {
2155 sync = MIRROR_SYNC_MODE_FULL;
2158 if (sync == MIRROR_SYNC_MODE_NONE) {
2159 source = bs;
2162 size = bdrv_getlength(bs);
2163 if (size < 0) {
2164 error_setg_errno(errp, -size, "bdrv_getlength failed");
2165 return;
2168 if (mode != NEW_IMAGE_MODE_EXISTING) {
2169 assert(format && drv);
2170 if (source) {
2171 bdrv_img_create(target, format, source->filename,
2172 source->drv->format_name, NULL,
2173 size, flags, &local_err, false);
2174 } else {
2175 bdrv_img_create(target, format, NULL, NULL, NULL,
2176 size, flags, &local_err, false);
2180 if (local_err) {
2181 error_propagate(errp, local_err);
2182 return;
2185 target_bs = NULL;
2186 ret = bdrv_open(&target_bs, target, NULL, NULL, flags, drv, &local_err);
2187 if (ret < 0) {
2188 error_propagate(errp, local_err);
2189 return;
2192 backup_start(bs, target_bs, speed, sync, on_source_error, on_target_error,
2193 block_job_cb, bs, &local_err);
2194 if (local_err != NULL) {
2195 bdrv_unref(target_bs);
2196 error_propagate(errp, local_err);
2197 return;
2201 BlockDeviceInfoList *qmp_query_named_block_nodes(Error **errp)
2203 return bdrv_named_nodes_list();
2206 #define DEFAULT_MIRROR_BUF_SIZE (10 << 20)
2208 void qmp_drive_mirror(const char *device, const char *target,
2209 bool has_format, const char *format,
2210 bool has_node_name, const char *node_name,
2211 bool has_replaces, const char *replaces,
2212 enum MirrorSyncMode sync,
2213 bool has_mode, enum NewImageMode mode,
2214 bool has_speed, int64_t speed,
2215 bool has_granularity, uint32_t granularity,
2216 bool has_buf_size, int64_t buf_size,
2217 bool has_on_source_error, BlockdevOnError on_source_error,
2218 bool has_on_target_error, BlockdevOnError on_target_error,
2219 Error **errp)
2221 BlockDriverState *bs;
2222 BlockDriverState *source, *target_bs;
2223 BlockDriver *drv = NULL;
2224 Error *local_err = NULL;
2225 QDict *options = NULL;
2226 int flags;
2227 int64_t size;
2228 int ret;
2230 if (!has_speed) {
2231 speed = 0;
2233 if (!has_on_source_error) {
2234 on_source_error = BLOCKDEV_ON_ERROR_REPORT;
2236 if (!has_on_target_error) {
2237 on_target_error = BLOCKDEV_ON_ERROR_REPORT;
2239 if (!has_mode) {
2240 mode = NEW_IMAGE_MODE_ABSOLUTE_PATHS;
2242 if (!has_granularity) {
2243 granularity = 0;
2245 if (!has_buf_size) {
2246 buf_size = DEFAULT_MIRROR_BUF_SIZE;
2249 if (granularity != 0 && (granularity < 512 || granularity > 1048576 * 64)) {
2250 error_set(errp, QERR_INVALID_PARAMETER_VALUE, "granularity",
2251 "a value in range [512B, 64MB]");
2252 return;
2254 if (granularity & (granularity - 1)) {
2255 error_set(errp, QERR_INVALID_PARAMETER_VALUE, "granularity", "power of 2");
2256 return;
2259 bs = bdrv_find(device);
2260 if (!bs) {
2261 error_set(errp, QERR_DEVICE_NOT_FOUND, device);
2262 return;
2265 if (!bdrv_is_inserted(bs)) {
2266 error_set(errp, QERR_DEVICE_HAS_NO_MEDIUM, device);
2267 return;
2270 if (!has_format) {
2271 format = mode == NEW_IMAGE_MODE_EXISTING ? NULL : bs->drv->format_name;
2273 if (format) {
2274 drv = bdrv_find_format(format);
2275 if (!drv) {
2276 error_set(errp, QERR_INVALID_BLOCK_FORMAT, format);
2277 return;
2281 if (bdrv_op_is_blocked(bs, BLOCK_OP_TYPE_MIRROR, errp)) {
2282 return;
2285 flags = bs->open_flags | BDRV_O_RDWR;
2286 source = bs->backing_hd;
2287 if (!source && sync == MIRROR_SYNC_MODE_TOP) {
2288 sync = MIRROR_SYNC_MODE_FULL;
2290 if (sync == MIRROR_SYNC_MODE_NONE) {
2291 source = bs;
2294 size = bdrv_getlength(bs);
2295 if (size < 0) {
2296 error_setg_errno(errp, -size, "bdrv_getlength failed");
2297 return;
2300 if (has_replaces) {
2301 BlockDriverState *to_replace_bs;
2303 if (!has_node_name) {
2304 error_setg(errp, "a node-name must be provided when replacing a"
2305 " named node of the graph");
2306 return;
2309 to_replace_bs = check_to_replace_node(replaces, &local_err);
2311 if (!to_replace_bs) {
2312 error_propagate(errp, local_err);
2313 return;
2316 if (size != bdrv_getlength(to_replace_bs)) {
2317 error_setg(errp, "cannot replace image with a mirror image of "
2318 "different size");
2319 return;
2323 if ((sync == MIRROR_SYNC_MODE_FULL || !source)
2324 && mode != NEW_IMAGE_MODE_EXISTING)
2326 /* create new image w/o backing file */
2327 assert(format && drv);
2328 bdrv_img_create(target, format,
2329 NULL, NULL, NULL, size, flags, &local_err, false);
2330 } else {
2331 switch (mode) {
2332 case NEW_IMAGE_MODE_EXISTING:
2333 break;
2334 case NEW_IMAGE_MODE_ABSOLUTE_PATHS:
2335 /* create new image with backing file */
2336 bdrv_img_create(target, format,
2337 source->filename,
2338 source->drv->format_name,
2339 NULL, size, flags, &local_err, false);
2340 break;
2341 default:
2342 abort();
2346 if (local_err) {
2347 error_propagate(errp, local_err);
2348 return;
2351 if (has_node_name) {
2352 options = qdict_new();
2353 qdict_put(options, "node-name", qstring_from_str(node_name));
2356 /* Mirroring takes care of copy-on-write using the source's backing
2357 * file.
2359 target_bs = NULL;
2360 ret = bdrv_open(&target_bs, target, NULL, options,
2361 flags | BDRV_O_NO_BACKING, drv, &local_err);
2362 if (ret < 0) {
2363 error_propagate(errp, local_err);
2364 return;
2367 /* pass the node name to replace to mirror start since it's loose coupling
2368 * and will allow to check whether the node still exist at mirror completion
2370 mirror_start(bs, target_bs,
2371 has_replaces ? replaces : NULL,
2372 speed, granularity, buf_size, sync,
2373 on_source_error, on_target_error,
2374 block_job_cb, bs, &local_err);
2375 if (local_err != NULL) {
2376 bdrv_unref(target_bs);
2377 error_propagate(errp, local_err);
2378 return;
2382 static BlockJob *find_block_job(const char *device)
2384 BlockDriverState *bs;
2386 bs = bdrv_find(device);
2387 if (!bs || !bs->job) {
2388 return NULL;
2390 return bs->job;
2393 void qmp_block_job_set_speed(const char *device, int64_t speed, Error **errp)
2395 BlockJob *job = find_block_job(device);
2397 if (!job) {
2398 error_set(errp, QERR_BLOCK_JOB_NOT_ACTIVE, device);
2399 return;
2402 block_job_set_speed(job, speed, errp);
2405 void qmp_block_job_cancel(const char *device,
2406 bool has_force, bool force, Error **errp)
2408 BlockJob *job = find_block_job(device);
2410 if (!has_force) {
2411 force = false;
2414 if (!job) {
2415 error_set(errp, QERR_BLOCK_JOB_NOT_ACTIVE, device);
2416 return;
2418 if (job->paused && !force) {
2419 error_setg(errp, "The block job for device '%s' is currently paused",
2420 device);
2421 return;
2424 trace_qmp_block_job_cancel(job);
2425 block_job_cancel(job);
2428 void qmp_block_job_pause(const char *device, Error **errp)
2430 BlockJob *job = find_block_job(device);
2432 if (!job) {
2433 error_set(errp, QERR_BLOCK_JOB_NOT_ACTIVE, device);
2434 return;
2437 trace_qmp_block_job_pause(job);
2438 block_job_pause(job);
2441 void qmp_block_job_resume(const char *device, Error **errp)
2443 BlockJob *job = find_block_job(device);
2445 if (!job) {
2446 error_set(errp, QERR_BLOCK_JOB_NOT_ACTIVE, device);
2447 return;
2450 trace_qmp_block_job_resume(job);
2451 block_job_resume(job);
2454 void qmp_block_job_complete(const char *device, Error **errp)
2456 BlockJob *job = find_block_job(device);
2458 if (!job) {
2459 error_set(errp, QERR_BLOCK_JOB_NOT_ACTIVE, device);
2460 return;
2463 trace_qmp_block_job_complete(job);
2464 block_job_complete(job, errp);
2467 void qmp_change_backing_file(const char *device,
2468 const char *image_node_name,
2469 const char *backing_file,
2470 Error **errp)
2472 BlockDriverState *bs = NULL;
2473 BlockDriverState *image_bs = NULL;
2474 Error *local_err = NULL;
2475 bool ro;
2476 int open_flags;
2477 int ret;
2479 /* find the top layer BDS of the chain */
2480 bs = bdrv_find(device);
2481 if (!bs) {
2482 error_set(errp, QERR_DEVICE_NOT_FOUND, device);
2483 return;
2486 image_bs = bdrv_lookup_bs(NULL, image_node_name, &local_err);
2487 if (local_err) {
2488 error_propagate(errp, local_err);
2489 return;
2492 if (!image_bs) {
2493 error_setg(errp, "image file not found");
2494 return;
2497 if (bdrv_find_base(image_bs) == image_bs) {
2498 error_setg(errp, "not allowing backing file change on an image "
2499 "without a backing file");
2500 return;
2503 /* even though we are not necessarily operating on bs, we need it to
2504 * determine if block ops are currently prohibited on the chain */
2505 if (bdrv_op_is_blocked(bs, BLOCK_OP_TYPE_CHANGE, errp)) {
2506 return;
2509 /* final sanity check */
2510 if (!bdrv_chain_contains(bs, image_bs)) {
2511 error_setg(errp, "'%s' and image file are not in the same chain",
2512 device);
2513 return;
2516 /* if not r/w, reopen to make r/w */
2517 open_flags = image_bs->open_flags;
2518 ro = bdrv_is_read_only(image_bs);
2520 if (ro) {
2521 bdrv_reopen(image_bs, open_flags | BDRV_O_RDWR, &local_err);
2522 if (local_err) {
2523 error_propagate(errp, local_err);
2524 return;
2528 ret = bdrv_change_backing_file(image_bs, backing_file,
2529 image_bs->drv ? image_bs->drv->format_name : "");
2531 if (ret < 0) {
2532 error_setg_errno(errp, -ret, "Could not change backing file to '%s'",
2533 backing_file);
2534 /* don't exit here, so we can try to restore open flags if
2535 * appropriate */
2538 if (ro) {
2539 bdrv_reopen(image_bs, open_flags, &local_err);
2540 if (local_err) {
2541 error_propagate(errp, local_err); /* will preserve prior errp */
2546 void qmp_blockdev_add(BlockdevOptions *options, Error **errp)
2548 QmpOutputVisitor *ov = qmp_output_visitor_new();
2549 BlockBackend *blk;
2550 QObject *obj;
2551 QDict *qdict;
2552 Error *local_err = NULL;
2554 /* Require an ID in the top level */
2555 if (!options->has_id) {
2556 error_setg(errp, "Block device needs an ID");
2557 goto fail;
2560 /* TODO Sort it out in raw-posix and drive_new(): Reject aio=native with
2561 * cache.direct=false instead of silently switching to aio=threads, except
2562 * when called from drive_new().
2564 * For now, simply forbidding the combination for all drivers will do. */
2565 if (options->has_aio && options->aio == BLOCKDEV_AIO_OPTIONS_NATIVE) {
2566 bool direct = options->has_cache &&
2567 options->cache->has_direct &&
2568 options->cache->direct;
2569 if (!direct) {
2570 error_setg(errp, "aio=native requires cache.direct=true");
2571 goto fail;
2575 visit_type_BlockdevOptions(qmp_output_get_visitor(ov),
2576 &options, NULL, &local_err);
2577 if (local_err) {
2578 error_propagate(errp, local_err);
2579 goto fail;
2582 obj = qmp_output_get_qobject(ov);
2583 qdict = qobject_to_qdict(obj);
2585 qdict_flatten(qdict);
2587 blk = blockdev_init(NULL, qdict, &local_err);
2588 if (local_err) {
2589 error_propagate(errp, local_err);
2590 goto fail;
2593 if (bdrv_key_required(blk_bs(blk))) {
2594 blk_unref(blk);
2595 error_setg(errp, "blockdev-add doesn't support encrypted devices");
2596 goto fail;
2599 fail:
2600 qmp_output_visitor_cleanup(ov);
2603 BlockJobInfoList *qmp_query_block_jobs(Error **errp)
2605 BlockJobInfoList *head = NULL, **p_next = &head;
2606 BlockDriverState *bs;
2608 for (bs = bdrv_next(NULL); bs; bs = bdrv_next(bs)) {
2609 if (bs->job) {
2610 BlockJobInfoList *elem = g_new0(BlockJobInfoList, 1);
2611 elem->value = block_job_query(bs->job);
2612 *p_next = elem;
2613 p_next = &elem->next;
2617 return head;
2620 QemuOptsList qemu_common_drive_opts = {
2621 .name = "drive",
2622 .head = QTAILQ_HEAD_INITIALIZER(qemu_common_drive_opts.head),
2623 .desc = {
2625 .name = "snapshot",
2626 .type = QEMU_OPT_BOOL,
2627 .help = "enable/disable snapshot mode",
2629 .name = "discard",
2630 .type = QEMU_OPT_STRING,
2631 .help = "discard operation (ignore/off, unmap/on)",
2633 .name = "cache.writeback",
2634 .type = QEMU_OPT_BOOL,
2635 .help = "enables writeback mode for any caches",
2637 .name = "cache.direct",
2638 .type = QEMU_OPT_BOOL,
2639 .help = "enables use of O_DIRECT (bypass the host page cache)",
2641 .name = "cache.no-flush",
2642 .type = QEMU_OPT_BOOL,
2643 .help = "ignore any flush requests for the device",
2645 .name = "aio",
2646 .type = QEMU_OPT_STRING,
2647 .help = "host AIO implementation (threads, native)",
2649 .name = "format",
2650 .type = QEMU_OPT_STRING,
2651 .help = "disk format (raw, qcow2, ...)",
2653 .name = "rerror",
2654 .type = QEMU_OPT_STRING,
2655 .help = "read error action",
2657 .name = "werror",
2658 .type = QEMU_OPT_STRING,
2659 .help = "write error action",
2661 .name = "read-only",
2662 .type = QEMU_OPT_BOOL,
2663 .help = "open drive file as read-only",
2665 .name = "throttling.iops-total",
2666 .type = QEMU_OPT_NUMBER,
2667 .help = "limit total I/O operations per second",
2669 .name = "throttling.iops-read",
2670 .type = QEMU_OPT_NUMBER,
2671 .help = "limit read operations per second",
2673 .name = "throttling.iops-write",
2674 .type = QEMU_OPT_NUMBER,
2675 .help = "limit write operations per second",
2677 .name = "throttling.bps-total",
2678 .type = QEMU_OPT_NUMBER,
2679 .help = "limit total bytes per second",
2681 .name = "throttling.bps-read",
2682 .type = QEMU_OPT_NUMBER,
2683 .help = "limit read bytes per second",
2685 .name = "throttling.bps-write",
2686 .type = QEMU_OPT_NUMBER,
2687 .help = "limit write bytes per second",
2689 .name = "throttling.iops-total-max",
2690 .type = QEMU_OPT_NUMBER,
2691 .help = "I/O operations burst",
2693 .name = "throttling.iops-read-max",
2694 .type = QEMU_OPT_NUMBER,
2695 .help = "I/O operations read burst",
2697 .name = "throttling.iops-write-max",
2698 .type = QEMU_OPT_NUMBER,
2699 .help = "I/O operations write burst",
2701 .name = "throttling.bps-total-max",
2702 .type = QEMU_OPT_NUMBER,
2703 .help = "total bytes burst",
2705 .name = "throttling.bps-read-max",
2706 .type = QEMU_OPT_NUMBER,
2707 .help = "total bytes read burst",
2709 .name = "throttling.bps-write-max",
2710 .type = QEMU_OPT_NUMBER,
2711 .help = "total bytes write burst",
2713 .name = "throttling.iops-size",
2714 .type = QEMU_OPT_NUMBER,
2715 .help = "when limiting by iops max size of an I/O in bytes",
2717 .name = "copy-on-read",
2718 .type = QEMU_OPT_BOOL,
2719 .help = "copy read data from backing file into image file",
2721 .name = "detect-zeroes",
2722 .type = QEMU_OPT_STRING,
2723 .help = "try to optimize zero writes (off, on, unmap)",
2725 { /* end of list */ }
2729 QemuOptsList qemu_drive_opts = {
2730 .name = "drive",
2731 .head = QTAILQ_HEAD_INITIALIZER(qemu_drive_opts.head),
2732 .desc = {
2734 * no elements => accept any params
2735 * validation will happen later
2737 { /* end of list */ }