qxl: refactor rounding up to a nearest power of 2
[qemu/cris-port.git] / blockdev.c
blobae735395512d4ce08c76aed269f9471fe01e800f
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);
118 AioContext *aio_context;
120 if (!dinfo) {
121 return;
124 aio_context = bdrv_get_aio_context(bs);
125 aio_context_acquire(aio_context);
127 if (bs->job) {
128 block_job_cancel(bs->job);
131 aio_context_release(aio_context);
133 dinfo->auto_del = 1;
136 void blockdev_auto_del(BlockBackend *blk)
138 DriveInfo *dinfo = blk_legacy_dinfo(blk);
140 if (dinfo && dinfo->auto_del) {
141 blk_unref(blk);
146 * Returns the current mapping of how many units per bus
147 * a particular interface can support.
149 * A positive integer indicates n units per bus.
150 * 0 implies the mapping has not been established.
151 * -1 indicates an invalid BlockInterfaceType was given.
153 int drive_get_max_devs(BlockInterfaceType type)
155 if (type >= IF_IDE && type < IF_COUNT) {
156 return if_max_devs[type];
159 return -1;
162 static int drive_index_to_bus_id(BlockInterfaceType type, int index)
164 int max_devs = if_max_devs[type];
165 return max_devs ? index / max_devs : 0;
168 static int drive_index_to_unit_id(BlockInterfaceType type, int index)
170 int max_devs = if_max_devs[type];
171 return max_devs ? index % max_devs : index;
174 QemuOpts *drive_def(const char *optstr)
176 return qemu_opts_parse(qemu_find_opts("drive"), optstr, 0);
179 QemuOpts *drive_add(BlockInterfaceType type, int index, const char *file,
180 const char *optstr)
182 QemuOpts *opts;
183 char buf[32];
185 opts = drive_def(optstr);
186 if (!opts) {
187 return NULL;
189 if (type != IF_DEFAULT) {
190 qemu_opt_set(opts, "if", if_name[type]);
192 if (index >= 0) {
193 snprintf(buf, sizeof(buf), "%d", index);
194 qemu_opt_set(opts, "index", buf);
196 if (file)
197 qemu_opt_set(opts, "file", file);
198 return opts;
201 DriveInfo *drive_get(BlockInterfaceType type, int bus, int unit)
203 BlockBackend *blk;
204 DriveInfo *dinfo;
206 for (blk = blk_next(NULL); blk; blk = blk_next(blk)) {
207 dinfo = blk_legacy_dinfo(blk);
208 if (dinfo && dinfo->type == type
209 && dinfo->bus == bus && dinfo->unit == unit) {
210 return dinfo;
214 return NULL;
217 bool drive_check_orphaned(void)
219 BlockBackend *blk;
220 DriveInfo *dinfo;
221 bool rs = false;
223 for (blk = blk_next(NULL); blk; blk = blk_next(blk)) {
224 dinfo = blk_legacy_dinfo(blk);
225 /* If dinfo->bdrv->dev is NULL, it has no device attached. */
226 /* Unless this is a default drive, this may be an oversight. */
227 if (!blk_get_attached_dev(blk) && !dinfo->is_default &&
228 dinfo->type != IF_NONE) {
229 fprintf(stderr, "Warning: Orphaned drive without device: "
230 "id=%s,file=%s,if=%s,bus=%d,unit=%d\n",
231 blk_name(blk), blk_bs(blk)->filename, if_name[dinfo->type],
232 dinfo->bus, dinfo->unit);
233 rs = true;
237 return rs;
240 DriveInfo *drive_get_by_index(BlockInterfaceType type, int index)
242 return drive_get(type,
243 drive_index_to_bus_id(type, index),
244 drive_index_to_unit_id(type, index));
247 int drive_get_max_bus(BlockInterfaceType type)
249 int max_bus;
250 BlockBackend *blk;
251 DriveInfo *dinfo;
253 max_bus = -1;
254 for (blk = blk_next(NULL); blk; blk = blk_next(blk)) {
255 dinfo = blk_legacy_dinfo(blk);
256 if (dinfo && dinfo->type == type && dinfo->bus > max_bus) {
257 max_bus = dinfo->bus;
260 return max_bus;
263 /* Get a block device. This should only be used for single-drive devices
264 (e.g. SD/Floppy/MTD). Multi-disk devices (scsi/ide) should use the
265 appropriate bus. */
266 DriveInfo *drive_get_next(BlockInterfaceType type)
268 static int next_block_unit[IF_COUNT];
270 return drive_get(type, 0, next_block_unit[type]++);
273 static void bdrv_format_print(void *opaque, const char *name)
275 error_printf(" %s", name);
278 typedef struct {
279 QEMUBH *bh;
280 BlockDriverState *bs;
281 } BDRVPutRefBH;
283 static void bdrv_put_ref_bh(void *opaque)
285 BDRVPutRefBH *s = opaque;
287 bdrv_unref(s->bs);
288 qemu_bh_delete(s->bh);
289 g_free(s);
293 * Release a BDS reference in a BH
295 * It is not safe to use bdrv_unref() from a callback function when the callers
296 * still need the BlockDriverState. In such cases we schedule a BH to release
297 * the reference.
299 static void bdrv_put_ref_bh_schedule(BlockDriverState *bs)
301 BDRVPutRefBH *s;
303 s = g_new(BDRVPutRefBH, 1);
304 s->bh = qemu_bh_new(bdrv_put_ref_bh, s);
305 s->bs = bs;
306 qemu_bh_schedule(s->bh);
309 static int parse_block_error_action(const char *buf, bool is_read, Error **errp)
311 if (!strcmp(buf, "ignore")) {
312 return BLOCKDEV_ON_ERROR_IGNORE;
313 } else if (!is_read && !strcmp(buf, "enospc")) {
314 return BLOCKDEV_ON_ERROR_ENOSPC;
315 } else if (!strcmp(buf, "stop")) {
316 return BLOCKDEV_ON_ERROR_STOP;
317 } else if (!strcmp(buf, "report")) {
318 return BLOCKDEV_ON_ERROR_REPORT;
319 } else {
320 error_setg(errp, "'%s' invalid %s error action",
321 buf, is_read ? "read" : "write");
322 return -1;
326 static bool check_throttle_config(ThrottleConfig *cfg, Error **errp)
328 if (throttle_conflicting(cfg)) {
329 error_setg(errp, "bps/iops/max total values and read/write values"
330 " cannot be used at the same time");
331 return false;
334 if (!throttle_is_valid(cfg)) {
335 error_setg(errp, "bps/iops/maxs values must be 0 or greater");
336 return false;
339 return true;
342 typedef enum { MEDIA_DISK, MEDIA_CDROM } DriveMediaType;
344 /* Takes the ownership of bs_opts */
345 static BlockBackend *blockdev_init(const char *file, QDict *bs_opts,
346 Error **errp)
348 const char *buf;
349 int ro = 0;
350 int bdrv_flags = 0;
351 int on_read_error, on_write_error;
352 BlockBackend *blk;
353 BlockDriverState *bs;
354 ThrottleConfig cfg;
355 int snapshot = 0;
356 bool copy_on_read;
357 Error *error = NULL;
358 QemuOpts *opts;
359 const char *id;
360 bool has_driver_specific_opts;
361 BlockdevDetectZeroesOptions detect_zeroes;
363 /* Check common options by copying from bs_opts to opts, all other options
364 * stay in bs_opts for processing by bdrv_open(). */
365 id = qdict_get_try_str(bs_opts, "id");
366 opts = qemu_opts_create(&qemu_common_drive_opts, id, 1, &error);
367 if (error) {
368 error_propagate(errp, error);
369 goto err_no_opts;
372 qemu_opts_absorb_qdict(opts, bs_opts, &error);
373 if (error) {
374 error_propagate(errp, error);
375 goto early_err;
378 if (id) {
379 qdict_del(bs_opts, "id");
382 has_driver_specific_opts = !!qdict_size(bs_opts);
384 /* extract parameters */
385 snapshot = qemu_opt_get_bool(opts, "snapshot", 0);
386 ro = qemu_opt_get_bool(opts, "read-only", 0);
387 copy_on_read = qemu_opt_get_bool(opts, "copy-on-read", false);
389 if ((buf = qemu_opt_get(opts, "discard")) != NULL) {
390 if (bdrv_parse_discard_flags(buf, &bdrv_flags) != 0) {
391 error_setg(errp, "invalid discard option");
392 goto early_err;
396 if (qemu_opt_get_bool(opts, "cache.writeback", true)) {
397 bdrv_flags |= BDRV_O_CACHE_WB;
399 if (qemu_opt_get_bool(opts, "cache.direct", false)) {
400 bdrv_flags |= BDRV_O_NOCACHE;
402 if (qemu_opt_get_bool(opts, "cache.no-flush", false)) {
403 bdrv_flags |= BDRV_O_NO_FLUSH;
406 #ifdef CONFIG_LINUX_AIO
407 if ((buf = qemu_opt_get(opts, "aio")) != NULL) {
408 if (!strcmp(buf, "native")) {
409 bdrv_flags |= BDRV_O_NATIVE_AIO;
410 } else if (!strcmp(buf, "threads")) {
411 /* this is the default */
412 } else {
413 error_setg(errp, "invalid aio option");
414 goto early_err;
417 #endif
419 if ((buf = qemu_opt_get(opts, "format")) != NULL) {
420 if (is_help_option(buf)) {
421 error_printf("Supported formats:");
422 bdrv_iterate_format(bdrv_format_print, NULL);
423 error_printf("\n");
424 goto early_err;
427 if (qdict_haskey(bs_opts, "driver")) {
428 error_setg(errp, "Cannot specify both 'driver' and 'format'");
429 goto early_err;
431 qdict_put(bs_opts, "driver", qstring_from_str(buf));
434 /* disk I/O throttling */
435 memset(&cfg, 0, sizeof(cfg));
436 cfg.buckets[THROTTLE_BPS_TOTAL].avg =
437 qemu_opt_get_number(opts, "throttling.bps-total", 0);
438 cfg.buckets[THROTTLE_BPS_READ].avg =
439 qemu_opt_get_number(opts, "throttling.bps-read", 0);
440 cfg.buckets[THROTTLE_BPS_WRITE].avg =
441 qemu_opt_get_number(opts, "throttling.bps-write", 0);
442 cfg.buckets[THROTTLE_OPS_TOTAL].avg =
443 qemu_opt_get_number(opts, "throttling.iops-total", 0);
444 cfg.buckets[THROTTLE_OPS_READ].avg =
445 qemu_opt_get_number(opts, "throttling.iops-read", 0);
446 cfg.buckets[THROTTLE_OPS_WRITE].avg =
447 qemu_opt_get_number(opts, "throttling.iops-write", 0);
449 cfg.buckets[THROTTLE_BPS_TOTAL].max =
450 qemu_opt_get_number(opts, "throttling.bps-total-max", 0);
451 cfg.buckets[THROTTLE_BPS_READ].max =
452 qemu_opt_get_number(opts, "throttling.bps-read-max", 0);
453 cfg.buckets[THROTTLE_BPS_WRITE].max =
454 qemu_opt_get_number(opts, "throttling.bps-write-max", 0);
455 cfg.buckets[THROTTLE_OPS_TOTAL].max =
456 qemu_opt_get_number(opts, "throttling.iops-total-max", 0);
457 cfg.buckets[THROTTLE_OPS_READ].max =
458 qemu_opt_get_number(opts, "throttling.iops-read-max", 0);
459 cfg.buckets[THROTTLE_OPS_WRITE].max =
460 qemu_opt_get_number(opts, "throttling.iops-write-max", 0);
462 cfg.op_size = qemu_opt_get_number(opts, "throttling.iops-size", 0);
464 if (!check_throttle_config(&cfg, &error)) {
465 error_propagate(errp, error);
466 goto early_err;
469 on_write_error = BLOCKDEV_ON_ERROR_ENOSPC;
470 if ((buf = qemu_opt_get(opts, "werror")) != NULL) {
471 on_write_error = parse_block_error_action(buf, 0, &error);
472 if (error) {
473 error_propagate(errp, error);
474 goto early_err;
478 on_read_error = BLOCKDEV_ON_ERROR_REPORT;
479 if ((buf = qemu_opt_get(opts, "rerror")) != NULL) {
480 on_read_error = parse_block_error_action(buf, 1, &error);
481 if (error) {
482 error_propagate(errp, error);
483 goto early_err;
487 detect_zeroes =
488 qapi_enum_parse(BlockdevDetectZeroesOptions_lookup,
489 qemu_opt_get(opts, "detect-zeroes"),
490 BLOCKDEV_DETECT_ZEROES_OPTIONS_MAX,
491 BLOCKDEV_DETECT_ZEROES_OPTIONS_OFF,
492 &error);
493 if (error) {
494 error_propagate(errp, error);
495 goto early_err;
498 if (detect_zeroes == BLOCKDEV_DETECT_ZEROES_OPTIONS_UNMAP &&
499 !(bdrv_flags & BDRV_O_UNMAP)) {
500 error_setg(errp, "setting detect-zeroes to unmap is not allowed "
501 "without setting discard operation to unmap");
502 goto early_err;
505 /* init */
506 if ((!file || !*file) && !has_driver_specific_opts) {
507 blk = blk_new_with_bs(qemu_opts_id(opts), errp);
508 if (!blk) {
509 goto early_err;
512 bs = blk_bs(blk);
513 bs->open_flags = snapshot ? BDRV_O_SNAPSHOT : 0;
514 bs->read_only = ro;
516 QDECREF(bs_opts);
517 } else {
518 if (file && !*file) {
519 file = NULL;
522 if (snapshot) {
523 /* always use cache=unsafe with snapshot */
524 bdrv_flags &= ~BDRV_O_CACHE_MASK;
525 bdrv_flags |= (BDRV_O_SNAPSHOT|BDRV_O_CACHE_WB|BDRV_O_NO_FLUSH);
528 if (copy_on_read) {
529 bdrv_flags |= BDRV_O_COPY_ON_READ;
532 if (runstate_check(RUN_STATE_INMIGRATE)) {
533 bdrv_flags |= BDRV_O_INCOMING;
536 bdrv_flags |= ro ? 0 : BDRV_O_RDWR;
538 blk = blk_new_open(qemu_opts_id(opts), file, NULL, bs_opts, bdrv_flags,
539 errp);
540 if (!blk) {
541 goto err_no_bs_opts;
543 bs = blk_bs(blk);
546 bs->detect_zeroes = detect_zeroes;
548 bdrv_set_on_error(bs, on_read_error, on_write_error);
550 /* disk I/O throttling */
551 if (throttle_enabled(&cfg)) {
552 bdrv_io_limits_enable(bs);
553 bdrv_set_io_limits(bs, &cfg);
556 if (bdrv_key_required(bs)) {
557 autostart = 0;
560 err_no_bs_opts:
561 qemu_opts_del(opts);
562 return blk;
564 early_err:
565 qemu_opts_del(opts);
566 err_no_opts:
567 QDECREF(bs_opts);
568 return NULL;
571 static void qemu_opt_rename(QemuOpts *opts, const char *from, const char *to,
572 Error **errp)
574 const char *value;
576 value = qemu_opt_get(opts, from);
577 if (value) {
578 if (qemu_opt_find(opts, to)) {
579 error_setg(errp, "'%s' and its alias '%s' can't be used at the "
580 "same time", to, from);
581 return;
585 /* rename all items in opts */
586 while ((value = qemu_opt_get(opts, from))) {
587 qemu_opt_set(opts, to, value);
588 qemu_opt_unset(opts, from);
592 QemuOptsList qemu_legacy_drive_opts = {
593 .name = "drive",
594 .head = QTAILQ_HEAD_INITIALIZER(qemu_legacy_drive_opts.head),
595 .desc = {
597 .name = "bus",
598 .type = QEMU_OPT_NUMBER,
599 .help = "bus number",
601 .name = "unit",
602 .type = QEMU_OPT_NUMBER,
603 .help = "unit number (i.e. lun for scsi)",
605 .name = "index",
606 .type = QEMU_OPT_NUMBER,
607 .help = "index number",
609 .name = "media",
610 .type = QEMU_OPT_STRING,
611 .help = "media type (disk, cdrom)",
613 .name = "if",
614 .type = QEMU_OPT_STRING,
615 .help = "interface (ide, scsi, sd, mtd, floppy, pflash, virtio)",
617 .name = "cyls",
618 .type = QEMU_OPT_NUMBER,
619 .help = "number of cylinders (ide disk geometry)",
621 .name = "heads",
622 .type = QEMU_OPT_NUMBER,
623 .help = "number of heads (ide disk geometry)",
625 .name = "secs",
626 .type = QEMU_OPT_NUMBER,
627 .help = "number of sectors (ide disk geometry)",
629 .name = "trans",
630 .type = QEMU_OPT_STRING,
631 .help = "chs translation (auto, lba, none)",
633 .name = "boot",
634 .type = QEMU_OPT_BOOL,
635 .help = "(deprecated, ignored)",
637 .name = "addr",
638 .type = QEMU_OPT_STRING,
639 .help = "pci address (virtio only)",
641 .name = "serial",
642 .type = QEMU_OPT_STRING,
643 .help = "disk serial number",
645 .name = "file",
646 .type = QEMU_OPT_STRING,
647 .help = "file name",
650 /* Options that are passed on, but have special semantics with -drive */
652 .name = "read-only",
653 .type = QEMU_OPT_BOOL,
654 .help = "open drive file as read-only",
656 .name = "rerror",
657 .type = QEMU_OPT_STRING,
658 .help = "read error action",
660 .name = "werror",
661 .type = QEMU_OPT_STRING,
662 .help = "write error action",
664 .name = "copy-on-read",
665 .type = QEMU_OPT_BOOL,
666 .help = "copy read data from backing file into image file",
669 { /* end of list */ }
673 DriveInfo *drive_new(QemuOpts *all_opts, BlockInterfaceType block_default_type)
675 const char *value;
676 BlockBackend *blk;
677 DriveInfo *dinfo = NULL;
678 QDict *bs_opts;
679 QemuOpts *legacy_opts;
680 DriveMediaType media = MEDIA_DISK;
681 BlockInterfaceType type;
682 int cyls, heads, secs, translation;
683 int max_devs, bus_id, unit_id, index;
684 const char *devaddr;
685 const char *werror, *rerror;
686 bool read_only = false;
687 bool copy_on_read;
688 const char *serial;
689 const char *filename;
690 Error *local_err = NULL;
691 int i;
693 /* Change legacy command line options into QMP ones */
694 static const struct {
695 const char *from;
696 const char *to;
697 } opt_renames[] = {
698 { "iops", "throttling.iops-total" },
699 { "iops_rd", "throttling.iops-read" },
700 { "iops_wr", "throttling.iops-write" },
702 { "bps", "throttling.bps-total" },
703 { "bps_rd", "throttling.bps-read" },
704 { "bps_wr", "throttling.bps-write" },
706 { "iops_max", "throttling.iops-total-max" },
707 { "iops_rd_max", "throttling.iops-read-max" },
708 { "iops_wr_max", "throttling.iops-write-max" },
710 { "bps_max", "throttling.bps-total-max" },
711 { "bps_rd_max", "throttling.bps-read-max" },
712 { "bps_wr_max", "throttling.bps-write-max" },
714 { "iops_size", "throttling.iops-size" },
716 { "readonly", "read-only" },
719 for (i = 0; i < ARRAY_SIZE(opt_renames); i++) {
720 qemu_opt_rename(all_opts, opt_renames[i].from, opt_renames[i].to,
721 &local_err);
722 if (local_err) {
723 error_report_err(local_err);
724 return NULL;
728 value = qemu_opt_get(all_opts, "cache");
729 if (value) {
730 int flags = 0;
732 if (bdrv_parse_cache_flags(value, &flags) != 0) {
733 error_report("invalid cache option");
734 return NULL;
737 /* Specific options take precedence */
738 if (!qemu_opt_get(all_opts, "cache.writeback")) {
739 qemu_opt_set_bool(all_opts, "cache.writeback",
740 !!(flags & BDRV_O_CACHE_WB));
742 if (!qemu_opt_get(all_opts, "cache.direct")) {
743 qemu_opt_set_bool(all_opts, "cache.direct",
744 !!(flags & BDRV_O_NOCACHE));
746 if (!qemu_opt_get(all_opts, "cache.no-flush")) {
747 qemu_opt_set_bool(all_opts, "cache.no-flush",
748 !!(flags & BDRV_O_NO_FLUSH));
750 qemu_opt_unset(all_opts, "cache");
753 /* Get a QDict for processing the options */
754 bs_opts = qdict_new();
755 qemu_opts_to_qdict(all_opts, bs_opts);
757 legacy_opts = qemu_opts_create(&qemu_legacy_drive_opts, NULL, 0,
758 &error_abort);
759 qemu_opts_absorb_qdict(legacy_opts, bs_opts, &local_err);
760 if (local_err) {
761 error_report_err(local_err);
762 goto fail;
765 /* Deprecated option boot=[on|off] */
766 if (qemu_opt_get(legacy_opts, "boot") != NULL) {
767 fprintf(stderr, "qemu-kvm: boot=on|off is deprecated and will be "
768 "ignored. Future versions will reject this parameter. Please "
769 "update your scripts.\n");
772 /* Media type */
773 value = qemu_opt_get(legacy_opts, "media");
774 if (value) {
775 if (!strcmp(value, "disk")) {
776 media = MEDIA_DISK;
777 } else if (!strcmp(value, "cdrom")) {
778 media = MEDIA_CDROM;
779 read_only = true;
780 } else {
781 error_report("'%s' invalid media", value);
782 goto fail;
786 /* copy-on-read is disabled with a warning for read-only devices */
787 read_only |= qemu_opt_get_bool(legacy_opts, "read-only", false);
788 copy_on_read = qemu_opt_get_bool(legacy_opts, "copy-on-read", false);
790 if (read_only && copy_on_read) {
791 error_report("warning: disabling copy-on-read on read-only drive");
792 copy_on_read = false;
795 qdict_put(bs_opts, "read-only",
796 qstring_from_str(read_only ? "on" : "off"));
797 qdict_put(bs_opts, "copy-on-read",
798 qstring_from_str(copy_on_read ? "on" :"off"));
800 /* Controller type */
801 value = qemu_opt_get(legacy_opts, "if");
802 if (value) {
803 for (type = 0;
804 type < IF_COUNT && strcmp(value, if_name[type]);
805 type++) {
807 if (type == IF_COUNT) {
808 error_report("unsupported bus type '%s'", value);
809 goto fail;
811 } else {
812 type = block_default_type;
815 /* Geometry */
816 cyls = qemu_opt_get_number(legacy_opts, "cyls", 0);
817 heads = qemu_opt_get_number(legacy_opts, "heads", 0);
818 secs = qemu_opt_get_number(legacy_opts, "secs", 0);
820 if (cyls || heads || secs) {
821 if (cyls < 1) {
822 error_report("invalid physical cyls number");
823 goto fail;
825 if (heads < 1) {
826 error_report("invalid physical heads number");
827 goto fail;
829 if (secs < 1) {
830 error_report("invalid physical secs number");
831 goto fail;
835 translation = BIOS_ATA_TRANSLATION_AUTO;
836 value = qemu_opt_get(legacy_opts, "trans");
837 if (value != NULL) {
838 if (!cyls) {
839 error_report("'%s' trans must be used with cyls, heads and secs",
840 value);
841 goto fail;
843 if (!strcmp(value, "none")) {
844 translation = BIOS_ATA_TRANSLATION_NONE;
845 } else if (!strcmp(value, "lba")) {
846 translation = BIOS_ATA_TRANSLATION_LBA;
847 } else if (!strcmp(value, "large")) {
848 translation = BIOS_ATA_TRANSLATION_LARGE;
849 } else if (!strcmp(value, "rechs")) {
850 translation = BIOS_ATA_TRANSLATION_RECHS;
851 } else if (!strcmp(value, "auto")) {
852 translation = BIOS_ATA_TRANSLATION_AUTO;
853 } else {
854 error_report("'%s' invalid translation type", value);
855 goto fail;
859 if (media == MEDIA_CDROM) {
860 if (cyls || secs || heads) {
861 error_report("CHS can't be set with media=cdrom");
862 goto fail;
866 /* Device address specified by bus/unit or index.
867 * If none was specified, try to find the first free one. */
868 bus_id = qemu_opt_get_number(legacy_opts, "bus", 0);
869 unit_id = qemu_opt_get_number(legacy_opts, "unit", -1);
870 index = qemu_opt_get_number(legacy_opts, "index", -1);
872 max_devs = if_max_devs[type];
874 if (index != -1) {
875 if (bus_id != 0 || unit_id != -1) {
876 error_report("index cannot be used with bus and unit");
877 goto fail;
879 bus_id = drive_index_to_bus_id(type, index);
880 unit_id = drive_index_to_unit_id(type, index);
883 if (unit_id == -1) {
884 unit_id = 0;
885 while (drive_get(type, bus_id, unit_id) != NULL) {
886 unit_id++;
887 if (max_devs && unit_id >= max_devs) {
888 unit_id -= max_devs;
889 bus_id++;
894 if (max_devs && unit_id >= max_devs) {
895 error_report("unit %d too big (max is %d)", unit_id, max_devs - 1);
896 goto fail;
899 if (drive_get(type, bus_id, unit_id) != NULL) {
900 error_report("drive with bus=%d, unit=%d (index=%d) exists",
901 bus_id, unit_id, index);
902 goto fail;
905 /* Serial number */
906 serial = qemu_opt_get(legacy_opts, "serial");
908 /* no id supplied -> create one */
909 if (qemu_opts_id(all_opts) == NULL) {
910 char *new_id;
911 const char *mediastr = "";
912 if (type == IF_IDE || type == IF_SCSI) {
913 mediastr = (media == MEDIA_CDROM) ? "-cd" : "-hd";
915 if (max_devs) {
916 new_id = g_strdup_printf("%s%i%s%i", if_name[type], bus_id,
917 mediastr, unit_id);
918 } else {
919 new_id = g_strdup_printf("%s%s%i", if_name[type],
920 mediastr, unit_id);
922 qdict_put(bs_opts, "id", qstring_from_str(new_id));
923 g_free(new_id);
926 /* Add virtio block device */
927 devaddr = qemu_opt_get(legacy_opts, "addr");
928 if (devaddr && type != IF_VIRTIO) {
929 error_report("addr is not supported by this bus type");
930 goto fail;
933 if (type == IF_VIRTIO) {
934 QemuOpts *devopts;
935 devopts = qemu_opts_create(qemu_find_opts("device"), NULL, 0,
936 &error_abort);
937 if (arch_type == QEMU_ARCH_S390X) {
938 qemu_opt_set(devopts, "driver", "virtio-blk-s390");
939 } else {
940 qemu_opt_set(devopts, "driver", "virtio-blk-pci");
942 qemu_opt_set(devopts, "drive", qdict_get_str(bs_opts, "id"));
943 if (devaddr) {
944 qemu_opt_set(devopts, "addr", devaddr);
948 filename = qemu_opt_get(legacy_opts, "file");
950 /* Check werror/rerror compatibility with if=... */
951 werror = qemu_opt_get(legacy_opts, "werror");
952 if (werror != NULL) {
953 if (type != IF_IDE && type != IF_SCSI && type != IF_VIRTIO &&
954 type != IF_NONE) {
955 error_report("werror is not supported by this bus type");
956 goto fail;
958 qdict_put(bs_opts, "werror", qstring_from_str(werror));
961 rerror = qemu_opt_get(legacy_opts, "rerror");
962 if (rerror != NULL) {
963 if (type != IF_IDE && type != IF_VIRTIO && type != IF_SCSI &&
964 type != IF_NONE) {
965 error_report("rerror is not supported by this bus type");
966 goto fail;
968 qdict_put(bs_opts, "rerror", qstring_from_str(rerror));
971 /* Actual block device init: Functionality shared with blockdev-add */
972 blk = blockdev_init(filename, bs_opts, &local_err);
973 bs_opts = NULL;
974 if (!blk) {
975 if (local_err) {
976 error_report_err(local_err);
978 goto fail;
979 } else {
980 assert(!local_err);
983 /* Create legacy DriveInfo */
984 dinfo = g_malloc0(sizeof(*dinfo));
985 dinfo->opts = all_opts;
987 dinfo->cyls = cyls;
988 dinfo->heads = heads;
989 dinfo->secs = secs;
990 dinfo->trans = translation;
992 dinfo->type = type;
993 dinfo->bus = bus_id;
994 dinfo->unit = unit_id;
995 dinfo->devaddr = devaddr;
996 dinfo->serial = g_strdup(serial);
998 blk_set_legacy_dinfo(blk, dinfo);
1000 switch(type) {
1001 case IF_IDE:
1002 case IF_SCSI:
1003 case IF_XEN:
1004 case IF_NONE:
1005 dinfo->media_cd = media == MEDIA_CDROM;
1006 break;
1007 default:
1008 break;
1011 fail:
1012 qemu_opts_del(legacy_opts);
1013 QDECREF(bs_opts);
1014 return dinfo;
1017 void hmp_commit(Monitor *mon, const QDict *qdict)
1019 const char *device = qdict_get_str(qdict, "device");
1020 BlockDriverState *bs;
1021 int ret;
1023 if (!strcmp(device, "all")) {
1024 ret = bdrv_commit_all();
1025 } else {
1026 bs = bdrv_find(device);
1027 if (!bs) {
1028 monitor_printf(mon, "Device '%s' not found\n", device);
1029 return;
1031 ret = bdrv_commit(bs);
1033 if (ret < 0) {
1034 monitor_printf(mon, "'commit' error for '%s': %s\n", device,
1035 strerror(-ret));
1039 static void blockdev_do_action(int kind, void *data, Error **errp)
1041 TransactionAction action;
1042 TransactionActionList list;
1044 action.kind = kind;
1045 action.data = data;
1046 list.value = &action;
1047 list.next = NULL;
1048 qmp_transaction(&list, errp);
1051 void qmp_blockdev_snapshot_sync(bool has_device, const char *device,
1052 bool has_node_name, const char *node_name,
1053 const char *snapshot_file,
1054 bool has_snapshot_node_name,
1055 const char *snapshot_node_name,
1056 bool has_format, const char *format,
1057 bool has_mode, NewImageMode mode, Error **errp)
1059 BlockdevSnapshot snapshot = {
1060 .has_device = has_device,
1061 .device = (char *) device,
1062 .has_node_name = has_node_name,
1063 .node_name = (char *) node_name,
1064 .snapshot_file = (char *) snapshot_file,
1065 .has_snapshot_node_name = has_snapshot_node_name,
1066 .snapshot_node_name = (char *) snapshot_node_name,
1067 .has_format = has_format,
1068 .format = (char *) format,
1069 .has_mode = has_mode,
1070 .mode = mode,
1072 blockdev_do_action(TRANSACTION_ACTION_KIND_BLOCKDEV_SNAPSHOT_SYNC,
1073 &snapshot, errp);
1076 void qmp_blockdev_snapshot_internal_sync(const char *device,
1077 const char *name,
1078 Error **errp)
1080 BlockdevSnapshotInternal snapshot = {
1081 .device = (char *) device,
1082 .name = (char *) name
1085 blockdev_do_action(TRANSACTION_ACTION_KIND_BLOCKDEV_SNAPSHOT_INTERNAL_SYNC,
1086 &snapshot, errp);
1089 SnapshotInfo *qmp_blockdev_snapshot_delete_internal_sync(const char *device,
1090 bool has_id,
1091 const char *id,
1092 bool has_name,
1093 const char *name,
1094 Error **errp)
1096 BlockDriverState *bs = bdrv_find(device);
1097 AioContext *aio_context;
1098 QEMUSnapshotInfo sn;
1099 Error *local_err = NULL;
1100 SnapshotInfo *info = NULL;
1101 int ret;
1103 if (!bs) {
1104 error_set(errp, QERR_DEVICE_NOT_FOUND, device);
1105 return NULL;
1108 if (!has_id) {
1109 id = NULL;
1112 if (!has_name) {
1113 name = NULL;
1116 if (!id && !name) {
1117 error_setg(errp, "Name or id must be provided");
1118 return NULL;
1121 aio_context = bdrv_get_aio_context(bs);
1122 aio_context_acquire(aio_context);
1124 if (bdrv_op_is_blocked(bs, BLOCK_OP_TYPE_INTERNAL_SNAPSHOT_DELETE, errp)) {
1125 goto out_aio_context;
1128 ret = bdrv_snapshot_find_by_id_and_name(bs, id, name, &sn, &local_err);
1129 if (local_err) {
1130 error_propagate(errp, local_err);
1131 goto out_aio_context;
1133 if (!ret) {
1134 error_setg(errp,
1135 "Snapshot with id '%s' and name '%s' does not exist on "
1136 "device '%s'",
1137 STR_OR_NULL(id), STR_OR_NULL(name), device);
1138 goto out_aio_context;
1141 bdrv_snapshot_delete(bs, id, name, &local_err);
1142 if (local_err) {
1143 error_propagate(errp, local_err);
1144 goto out_aio_context;
1147 aio_context_release(aio_context);
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;
1160 out_aio_context:
1161 aio_context_release(aio_context);
1162 return NULL;
1165 /* New and old BlockDriverState structs for atomic group operations */
1167 typedef struct BlkTransactionState BlkTransactionState;
1169 /* Only prepare() may fail. In a single transaction, only one of commit() or
1170 abort() will be called, clean() will always be called if it present. */
1171 typedef struct BdrvActionOps {
1172 /* Size of state struct, in bytes. */
1173 size_t instance_size;
1174 /* Prepare the work, must NOT be NULL. */
1175 void (*prepare)(BlkTransactionState *common, Error **errp);
1176 /* Commit the changes, can be NULL. */
1177 void (*commit)(BlkTransactionState *common);
1178 /* Abort the changes on fail, can be NULL. */
1179 void (*abort)(BlkTransactionState *common);
1180 /* Clean up resource in the end, can be NULL. */
1181 void (*clean)(BlkTransactionState *common);
1182 } BdrvActionOps;
1185 * This structure must be arranged as first member in child type, assuming
1186 * that compiler will also arrange it to the same address with parent instance.
1187 * Later it will be used in free().
1189 struct BlkTransactionState {
1190 TransactionAction *action;
1191 const BdrvActionOps *ops;
1192 QSIMPLEQ_ENTRY(BlkTransactionState) entry;
1195 /* internal snapshot private data */
1196 typedef struct InternalSnapshotState {
1197 BlkTransactionState common;
1198 BlockDriverState *bs;
1199 AioContext *aio_context;
1200 QEMUSnapshotInfo sn;
1201 } InternalSnapshotState;
1203 static void internal_snapshot_prepare(BlkTransactionState *common,
1204 Error **errp)
1206 Error *local_err = NULL;
1207 const char *device;
1208 const char *name;
1209 BlockDriverState *bs;
1210 QEMUSnapshotInfo old_sn, *sn;
1211 bool ret;
1212 qemu_timeval tv;
1213 BlockdevSnapshotInternal *internal;
1214 InternalSnapshotState *state;
1215 int ret1;
1217 g_assert(common->action->kind ==
1218 TRANSACTION_ACTION_KIND_BLOCKDEV_SNAPSHOT_INTERNAL_SYNC);
1219 internal = common->action->blockdev_snapshot_internal_sync;
1220 state = DO_UPCAST(InternalSnapshotState, common, common);
1222 /* 1. parse input */
1223 device = internal->device;
1224 name = internal->name;
1226 /* 2. check for validation */
1227 bs = bdrv_find(device);
1228 if (!bs) {
1229 error_set(errp, QERR_DEVICE_NOT_FOUND, device);
1230 return;
1233 /* AioContext is released in .clean() */
1234 state->aio_context = bdrv_get_aio_context(bs);
1235 aio_context_acquire(state->aio_context);
1237 if (!bdrv_is_inserted(bs)) {
1238 error_set(errp, QERR_DEVICE_HAS_NO_MEDIUM, device);
1239 return;
1242 if (bdrv_op_is_blocked(bs, BLOCK_OP_TYPE_INTERNAL_SNAPSHOT, errp)) {
1243 return;
1246 if (bdrv_is_read_only(bs)) {
1247 error_set(errp, QERR_DEVICE_IS_READ_ONLY, device);
1248 return;
1251 if (!bdrv_can_snapshot(bs)) {
1252 error_set(errp, QERR_BLOCK_FORMAT_FEATURE_NOT_SUPPORTED,
1253 bs->drv->format_name, device, "internal snapshot");
1254 return;
1257 if (!strlen(name)) {
1258 error_setg(errp, "Name is empty");
1259 return;
1262 /* check whether a snapshot with name exist */
1263 ret = bdrv_snapshot_find_by_id_and_name(bs, NULL, name, &old_sn,
1264 &local_err);
1265 if (local_err) {
1266 error_propagate(errp, local_err);
1267 return;
1268 } else if (ret) {
1269 error_setg(errp,
1270 "Snapshot with name '%s' already exists on device '%s'",
1271 name, device);
1272 return;
1275 /* 3. take the snapshot */
1276 sn = &state->sn;
1277 pstrcpy(sn->name, sizeof(sn->name), name);
1278 qemu_gettimeofday(&tv);
1279 sn->date_sec = tv.tv_sec;
1280 sn->date_nsec = tv.tv_usec * 1000;
1281 sn->vm_clock_nsec = qemu_clock_get_ns(QEMU_CLOCK_VIRTUAL);
1283 ret1 = bdrv_snapshot_create(bs, sn);
1284 if (ret1 < 0) {
1285 error_setg_errno(errp, -ret1,
1286 "Failed to create snapshot '%s' on device '%s'",
1287 name, device);
1288 return;
1291 /* 4. succeed, mark a snapshot is created */
1292 state->bs = bs;
1295 static void internal_snapshot_abort(BlkTransactionState *common)
1297 InternalSnapshotState *state =
1298 DO_UPCAST(InternalSnapshotState, common, common);
1299 BlockDriverState *bs = state->bs;
1300 QEMUSnapshotInfo *sn = &state->sn;
1301 Error *local_error = NULL;
1303 if (!bs) {
1304 return;
1307 if (bdrv_snapshot_delete(bs, sn->id_str, sn->name, &local_error) < 0) {
1308 error_report("Failed to delete snapshot with id '%s' and name '%s' on "
1309 "device '%s' in abort: %s",
1310 sn->id_str,
1311 sn->name,
1312 bdrv_get_device_name(bs),
1313 error_get_pretty(local_error));
1314 error_free(local_error);
1318 static void internal_snapshot_clean(BlkTransactionState *common)
1320 InternalSnapshotState *state = DO_UPCAST(InternalSnapshotState,
1321 common, common);
1323 if (state->aio_context) {
1324 aio_context_release(state->aio_context);
1328 /* external snapshot private data */
1329 typedef struct ExternalSnapshotState {
1330 BlkTransactionState common;
1331 BlockDriverState *old_bs;
1332 BlockDriverState *new_bs;
1333 AioContext *aio_context;
1334 } ExternalSnapshotState;
1336 static void external_snapshot_prepare(BlkTransactionState *common,
1337 Error **errp)
1339 BlockDriver *drv;
1340 int flags, ret;
1341 QDict *options = NULL;
1342 Error *local_err = NULL;
1343 bool has_device = false;
1344 const char *device;
1345 bool has_node_name = false;
1346 const char *node_name;
1347 bool has_snapshot_node_name = false;
1348 const char *snapshot_node_name;
1349 const char *new_image_file;
1350 const char *format = "qcow2";
1351 enum NewImageMode mode = NEW_IMAGE_MODE_ABSOLUTE_PATHS;
1352 ExternalSnapshotState *state =
1353 DO_UPCAST(ExternalSnapshotState, common, common);
1354 TransactionAction *action = common->action;
1356 /* get parameters */
1357 g_assert(action->kind == TRANSACTION_ACTION_KIND_BLOCKDEV_SNAPSHOT_SYNC);
1359 has_device = action->blockdev_snapshot_sync->has_device;
1360 device = action->blockdev_snapshot_sync->device;
1361 has_node_name = action->blockdev_snapshot_sync->has_node_name;
1362 node_name = action->blockdev_snapshot_sync->node_name;
1363 has_snapshot_node_name =
1364 action->blockdev_snapshot_sync->has_snapshot_node_name;
1365 snapshot_node_name = action->blockdev_snapshot_sync->snapshot_node_name;
1367 new_image_file = action->blockdev_snapshot_sync->snapshot_file;
1368 if (action->blockdev_snapshot_sync->has_format) {
1369 format = action->blockdev_snapshot_sync->format;
1371 if (action->blockdev_snapshot_sync->has_mode) {
1372 mode = action->blockdev_snapshot_sync->mode;
1375 /* start processing */
1376 drv = bdrv_find_format(format);
1377 if (!drv) {
1378 error_set(errp, QERR_INVALID_BLOCK_FORMAT, format);
1379 return;
1382 state->old_bs = bdrv_lookup_bs(has_device ? device : NULL,
1383 has_node_name ? node_name : NULL,
1384 &local_err);
1385 if (local_err) {
1386 error_propagate(errp, local_err);
1387 return;
1390 if (has_node_name && !has_snapshot_node_name) {
1391 error_setg(errp, "New snapshot node name missing");
1392 return;
1395 if (has_snapshot_node_name && bdrv_find_node(snapshot_node_name)) {
1396 error_setg(errp, "New snapshot node name already existing");
1397 return;
1400 /* Acquire AioContext now so any threads operating on old_bs stop */
1401 state->aio_context = bdrv_get_aio_context(state->old_bs);
1402 aio_context_acquire(state->aio_context);
1404 if (!bdrv_is_inserted(state->old_bs)) {
1405 error_set(errp, QERR_DEVICE_HAS_NO_MEDIUM, device);
1406 return;
1409 if (bdrv_op_is_blocked(state->old_bs,
1410 BLOCK_OP_TYPE_EXTERNAL_SNAPSHOT, errp)) {
1411 return;
1414 if (!bdrv_is_read_only(state->old_bs)) {
1415 if (bdrv_flush(state->old_bs)) {
1416 error_set(errp, QERR_IO_ERROR);
1417 return;
1421 if (!bdrv_is_first_non_filter(state->old_bs)) {
1422 error_set(errp, QERR_FEATURE_DISABLED, "snapshot");
1423 return;
1426 flags = state->old_bs->open_flags;
1428 /* create new image w/backing file */
1429 if (mode != NEW_IMAGE_MODE_EXISTING) {
1430 bdrv_img_create(new_image_file, format,
1431 state->old_bs->filename,
1432 state->old_bs->drv->format_name,
1433 NULL, -1, flags, &local_err, false);
1434 if (local_err) {
1435 error_propagate(errp, local_err);
1436 return;
1440 if (has_snapshot_node_name) {
1441 options = qdict_new();
1442 qdict_put(options, "node-name",
1443 qstring_from_str(snapshot_node_name));
1446 /* TODO Inherit bs->options or only take explicit options with an
1447 * extended QMP command? */
1448 assert(state->new_bs == NULL);
1449 ret = bdrv_open(&state->new_bs, new_image_file, NULL, options,
1450 flags | BDRV_O_NO_BACKING, drv, &local_err);
1451 /* We will manually add the backing_hd field to the bs later */
1452 if (ret != 0) {
1453 error_propagate(errp, local_err);
1457 static void external_snapshot_commit(BlkTransactionState *common)
1459 ExternalSnapshotState *state =
1460 DO_UPCAST(ExternalSnapshotState, common, common);
1462 bdrv_set_aio_context(state->new_bs, state->aio_context);
1464 /* This removes our old bs and adds the new bs */
1465 bdrv_append(state->new_bs, state->old_bs);
1466 /* We don't need (or want) to use the transactional
1467 * bdrv_reopen_multiple() across all the entries at once, because we
1468 * don't want to abort all of them if one of them fails the reopen */
1469 bdrv_reopen(state->new_bs, state->new_bs->open_flags & ~BDRV_O_RDWR,
1470 NULL);
1472 aio_context_release(state->aio_context);
1475 static void external_snapshot_abort(BlkTransactionState *common)
1477 ExternalSnapshotState *state =
1478 DO_UPCAST(ExternalSnapshotState, common, common);
1479 if (state->new_bs) {
1480 bdrv_unref(state->new_bs);
1482 if (state->aio_context) {
1483 aio_context_release(state->aio_context);
1487 typedef struct DriveBackupState {
1488 BlkTransactionState common;
1489 BlockDriverState *bs;
1490 AioContext *aio_context;
1491 BlockJob *job;
1492 } DriveBackupState;
1494 static void drive_backup_prepare(BlkTransactionState *common, Error **errp)
1496 DriveBackupState *state = DO_UPCAST(DriveBackupState, common, common);
1497 BlockDriverState *bs;
1498 DriveBackup *backup;
1499 Error *local_err = NULL;
1501 assert(common->action->kind == TRANSACTION_ACTION_KIND_DRIVE_BACKUP);
1502 backup = common->action->drive_backup;
1504 bs = bdrv_find(backup->device);
1505 if (!bs) {
1506 error_set(errp, QERR_DEVICE_NOT_FOUND, backup->device);
1507 return;
1510 /* AioContext is released in .clean() */
1511 state->aio_context = bdrv_get_aio_context(bs);
1512 aio_context_acquire(state->aio_context);
1514 qmp_drive_backup(backup->device, backup->target,
1515 backup->has_format, backup->format,
1516 backup->sync,
1517 backup->has_mode, backup->mode,
1518 backup->has_speed, backup->speed,
1519 backup->has_on_source_error, backup->on_source_error,
1520 backup->has_on_target_error, backup->on_target_error,
1521 &local_err);
1522 if (local_err) {
1523 error_propagate(errp, local_err);
1524 return;
1527 state->bs = bs;
1528 state->job = state->bs->job;
1531 static void drive_backup_abort(BlkTransactionState *common)
1533 DriveBackupState *state = DO_UPCAST(DriveBackupState, common, common);
1534 BlockDriverState *bs = state->bs;
1536 /* Only cancel if it's the job we started */
1537 if (bs && bs->job && bs->job == state->job) {
1538 block_job_cancel_sync(bs->job);
1542 static void drive_backup_clean(BlkTransactionState *common)
1544 DriveBackupState *state = DO_UPCAST(DriveBackupState, common, common);
1546 if (state->aio_context) {
1547 aio_context_release(state->aio_context);
1551 typedef struct BlockdevBackupState {
1552 BlkTransactionState common;
1553 BlockDriverState *bs;
1554 BlockJob *job;
1555 AioContext *aio_context;
1556 } BlockdevBackupState;
1558 static void blockdev_backup_prepare(BlkTransactionState *common, Error **errp)
1560 BlockdevBackupState *state = DO_UPCAST(BlockdevBackupState, common, common);
1561 BlockdevBackup *backup;
1562 BlockDriverState *bs, *target;
1563 Error *local_err = NULL;
1565 assert(common->action->kind == TRANSACTION_ACTION_KIND_BLOCKDEV_BACKUP);
1566 backup = common->action->blockdev_backup;
1568 bs = bdrv_find(backup->device);
1569 if (!bs) {
1570 error_set(errp, QERR_DEVICE_NOT_FOUND, backup->device);
1571 return;
1574 target = bdrv_find(backup->target);
1575 if (!target) {
1576 error_set(errp, QERR_DEVICE_NOT_FOUND, backup->target);
1577 return;
1580 /* AioContext is released in .clean() */
1581 state->aio_context = bdrv_get_aio_context(bs);
1582 if (state->aio_context != bdrv_get_aio_context(target)) {
1583 state->aio_context = NULL;
1584 error_setg(errp, "Backup between two IO threads is not implemented");
1585 return;
1587 aio_context_acquire(state->aio_context);
1589 qmp_blockdev_backup(backup->device, backup->target,
1590 backup->sync,
1591 backup->has_speed, backup->speed,
1592 backup->has_on_source_error, backup->on_source_error,
1593 backup->has_on_target_error, backup->on_target_error,
1594 &local_err);
1595 if (local_err) {
1596 error_propagate(errp, local_err);
1597 return;
1600 state->bs = bs;
1601 state->job = state->bs->job;
1604 static void blockdev_backup_abort(BlkTransactionState *common)
1606 BlockdevBackupState *state = DO_UPCAST(BlockdevBackupState, common, common);
1607 BlockDriverState *bs = state->bs;
1609 /* Only cancel if it's the job we started */
1610 if (bs && bs->job && bs->job == state->job) {
1611 block_job_cancel_sync(bs->job);
1615 static void blockdev_backup_clean(BlkTransactionState *common)
1617 BlockdevBackupState *state = DO_UPCAST(BlockdevBackupState, common, common);
1619 if (state->aio_context) {
1620 aio_context_release(state->aio_context);
1624 static void abort_prepare(BlkTransactionState *common, Error **errp)
1626 error_setg(errp, "Transaction aborted using Abort action");
1629 static void abort_commit(BlkTransactionState *common)
1631 g_assert_not_reached(); /* this action never succeeds */
1634 static const BdrvActionOps actions[] = {
1635 [TRANSACTION_ACTION_KIND_BLOCKDEV_SNAPSHOT_SYNC] = {
1636 .instance_size = sizeof(ExternalSnapshotState),
1637 .prepare = external_snapshot_prepare,
1638 .commit = external_snapshot_commit,
1639 .abort = external_snapshot_abort,
1641 [TRANSACTION_ACTION_KIND_DRIVE_BACKUP] = {
1642 .instance_size = sizeof(DriveBackupState),
1643 .prepare = drive_backup_prepare,
1644 .abort = drive_backup_abort,
1645 .clean = drive_backup_clean,
1647 [TRANSACTION_ACTION_KIND_BLOCKDEV_BACKUP] = {
1648 .instance_size = sizeof(BlockdevBackupState),
1649 .prepare = blockdev_backup_prepare,
1650 .abort = blockdev_backup_abort,
1651 .clean = blockdev_backup_clean,
1653 [TRANSACTION_ACTION_KIND_ABORT] = {
1654 .instance_size = sizeof(BlkTransactionState),
1655 .prepare = abort_prepare,
1656 .commit = abort_commit,
1658 [TRANSACTION_ACTION_KIND_BLOCKDEV_SNAPSHOT_INTERNAL_SYNC] = {
1659 .instance_size = sizeof(InternalSnapshotState),
1660 .prepare = internal_snapshot_prepare,
1661 .abort = internal_snapshot_abort,
1662 .clean = internal_snapshot_clean,
1667 * 'Atomic' group operations. The operations are performed as a set, and if
1668 * any fail then we roll back all operations in the group.
1670 void qmp_transaction(TransactionActionList *dev_list, Error **errp)
1672 TransactionActionList *dev_entry = dev_list;
1673 BlkTransactionState *state, *next;
1674 Error *local_err = NULL;
1676 QSIMPLEQ_HEAD(snap_bdrv_states, BlkTransactionState) snap_bdrv_states;
1677 QSIMPLEQ_INIT(&snap_bdrv_states);
1679 /* drain all i/o before any operations */
1680 bdrv_drain_all();
1682 /* We don't do anything in this loop that commits us to the operations */
1683 while (NULL != dev_entry) {
1684 TransactionAction *dev_info = NULL;
1685 const BdrvActionOps *ops;
1687 dev_info = dev_entry->value;
1688 dev_entry = dev_entry->next;
1690 assert(dev_info->kind < ARRAY_SIZE(actions));
1692 ops = &actions[dev_info->kind];
1693 assert(ops->instance_size > 0);
1695 state = g_malloc0(ops->instance_size);
1696 state->ops = ops;
1697 state->action = dev_info;
1698 QSIMPLEQ_INSERT_TAIL(&snap_bdrv_states, state, entry);
1700 state->ops->prepare(state, &local_err);
1701 if (local_err) {
1702 error_propagate(errp, local_err);
1703 goto delete_and_fail;
1707 QSIMPLEQ_FOREACH(state, &snap_bdrv_states, entry) {
1708 if (state->ops->commit) {
1709 state->ops->commit(state);
1713 /* success */
1714 goto exit;
1716 delete_and_fail:
1717 /* failure, and it is all-or-none; roll back all operations */
1718 QSIMPLEQ_FOREACH(state, &snap_bdrv_states, entry) {
1719 if (state->ops->abort) {
1720 state->ops->abort(state);
1723 exit:
1724 QSIMPLEQ_FOREACH_SAFE(state, &snap_bdrv_states, entry, next) {
1725 if (state->ops->clean) {
1726 state->ops->clean(state);
1728 g_free(state);
1733 static void eject_device(BlockBackend *blk, int force, Error **errp)
1735 BlockDriverState *bs = blk_bs(blk);
1736 AioContext *aio_context;
1738 aio_context = bdrv_get_aio_context(bs);
1739 aio_context_acquire(aio_context);
1741 if (bdrv_op_is_blocked(bs, BLOCK_OP_TYPE_EJECT, errp)) {
1742 goto out;
1744 if (!blk_dev_has_removable_media(blk)) {
1745 error_setg(errp, "Device '%s' is not removable",
1746 bdrv_get_device_name(bs));
1747 goto out;
1750 if (blk_dev_is_medium_locked(blk) && !blk_dev_is_tray_open(blk)) {
1751 blk_dev_eject_request(blk, force);
1752 if (!force) {
1753 error_setg(errp, "Device '%s' is locked",
1754 bdrv_get_device_name(bs));
1755 goto out;
1759 bdrv_close(bs);
1761 out:
1762 aio_context_release(aio_context);
1765 void qmp_eject(const char *device, bool has_force, bool force, Error **errp)
1767 BlockBackend *blk;
1769 blk = blk_by_name(device);
1770 if (!blk) {
1771 error_set(errp, QERR_DEVICE_NOT_FOUND, device);
1772 return;
1775 eject_device(blk, force, errp);
1778 void qmp_block_passwd(bool has_device, const char *device,
1779 bool has_node_name, const char *node_name,
1780 const char *password, Error **errp)
1782 Error *local_err = NULL;
1783 BlockDriverState *bs;
1784 AioContext *aio_context;
1786 bs = bdrv_lookup_bs(has_device ? device : NULL,
1787 has_node_name ? node_name : NULL,
1788 &local_err);
1789 if (local_err) {
1790 error_propagate(errp, local_err);
1791 return;
1794 aio_context = bdrv_get_aio_context(bs);
1795 aio_context_acquire(aio_context);
1797 bdrv_add_key(bs, password, errp);
1799 aio_context_release(aio_context);
1802 /* Assumes AioContext is held */
1803 static void qmp_bdrv_open_encrypted(BlockDriverState *bs, const char *filename,
1804 int bdrv_flags, BlockDriver *drv,
1805 const char *password, Error **errp)
1807 Error *local_err = NULL;
1808 int ret;
1810 ret = bdrv_open(&bs, filename, NULL, NULL, bdrv_flags, drv, &local_err);
1811 if (ret < 0) {
1812 error_propagate(errp, local_err);
1813 return;
1816 bdrv_add_key(bs, password, errp);
1819 void qmp_change_blockdev(const char *device, const char *filename,
1820 const char *format, Error **errp)
1822 BlockBackend *blk;
1823 BlockDriverState *bs;
1824 AioContext *aio_context;
1825 BlockDriver *drv = NULL;
1826 int bdrv_flags;
1827 Error *err = NULL;
1829 blk = blk_by_name(device);
1830 if (!blk) {
1831 error_set(errp, QERR_DEVICE_NOT_FOUND, device);
1832 return;
1834 bs = blk_bs(blk);
1836 aio_context = bdrv_get_aio_context(bs);
1837 aio_context_acquire(aio_context);
1839 if (format) {
1840 drv = bdrv_find_whitelisted_format(format, bs->read_only);
1841 if (!drv) {
1842 error_set(errp, QERR_INVALID_BLOCK_FORMAT, format);
1843 goto out;
1847 eject_device(blk, 0, &err);
1848 if (err) {
1849 error_propagate(errp, err);
1850 goto out;
1853 bdrv_flags = bdrv_is_read_only(bs) ? 0 : BDRV_O_RDWR;
1854 bdrv_flags |= bdrv_is_snapshot(bs) ? BDRV_O_SNAPSHOT : 0;
1856 qmp_bdrv_open_encrypted(bs, filename, bdrv_flags, drv, NULL, errp);
1858 out:
1859 aio_context_release(aio_context);
1862 /* throttling disk I/O limits */
1863 void qmp_block_set_io_throttle(const char *device, int64_t bps, int64_t bps_rd,
1864 int64_t bps_wr,
1865 int64_t iops,
1866 int64_t iops_rd,
1867 int64_t iops_wr,
1868 bool has_bps_max,
1869 int64_t bps_max,
1870 bool has_bps_rd_max,
1871 int64_t bps_rd_max,
1872 bool has_bps_wr_max,
1873 int64_t bps_wr_max,
1874 bool has_iops_max,
1875 int64_t iops_max,
1876 bool has_iops_rd_max,
1877 int64_t iops_rd_max,
1878 bool has_iops_wr_max,
1879 int64_t iops_wr_max,
1880 bool has_iops_size,
1881 int64_t iops_size, Error **errp)
1883 ThrottleConfig cfg;
1884 BlockDriverState *bs;
1885 AioContext *aio_context;
1887 bs = bdrv_find(device);
1888 if (!bs) {
1889 error_set(errp, QERR_DEVICE_NOT_FOUND, device);
1890 return;
1893 memset(&cfg, 0, sizeof(cfg));
1894 cfg.buckets[THROTTLE_BPS_TOTAL].avg = bps;
1895 cfg.buckets[THROTTLE_BPS_READ].avg = bps_rd;
1896 cfg.buckets[THROTTLE_BPS_WRITE].avg = bps_wr;
1898 cfg.buckets[THROTTLE_OPS_TOTAL].avg = iops;
1899 cfg.buckets[THROTTLE_OPS_READ].avg = iops_rd;
1900 cfg.buckets[THROTTLE_OPS_WRITE].avg = iops_wr;
1902 if (has_bps_max) {
1903 cfg.buckets[THROTTLE_BPS_TOTAL].max = bps_max;
1905 if (has_bps_rd_max) {
1906 cfg.buckets[THROTTLE_BPS_READ].max = bps_rd_max;
1908 if (has_bps_wr_max) {
1909 cfg.buckets[THROTTLE_BPS_WRITE].max = bps_wr_max;
1911 if (has_iops_max) {
1912 cfg.buckets[THROTTLE_OPS_TOTAL].max = iops_max;
1914 if (has_iops_rd_max) {
1915 cfg.buckets[THROTTLE_OPS_READ].max = iops_rd_max;
1917 if (has_iops_wr_max) {
1918 cfg.buckets[THROTTLE_OPS_WRITE].max = iops_wr_max;
1921 if (has_iops_size) {
1922 cfg.op_size = iops_size;
1925 if (!check_throttle_config(&cfg, errp)) {
1926 return;
1929 aio_context = bdrv_get_aio_context(bs);
1930 aio_context_acquire(aio_context);
1932 if (!bs->io_limits_enabled && throttle_enabled(&cfg)) {
1933 bdrv_io_limits_enable(bs);
1934 } else if (bs->io_limits_enabled && !throttle_enabled(&cfg)) {
1935 bdrv_io_limits_disable(bs);
1938 if (bs->io_limits_enabled) {
1939 bdrv_set_io_limits(bs, &cfg);
1942 aio_context_release(aio_context);
1945 int hmp_drive_del(Monitor *mon, const QDict *qdict, QObject **ret_data)
1947 const char *id = qdict_get_str(qdict, "id");
1948 BlockBackend *blk;
1949 BlockDriverState *bs;
1950 AioContext *aio_context;
1951 Error *local_err = NULL;
1953 blk = blk_by_name(id);
1954 if (!blk) {
1955 error_report("Device '%s' not found", id);
1956 return -1;
1958 bs = blk_bs(blk);
1960 if (!blk_legacy_dinfo(blk)) {
1961 error_report("Deleting device added with blockdev-add"
1962 " is not supported");
1963 return -1;
1966 aio_context = bdrv_get_aio_context(bs);
1967 aio_context_acquire(aio_context);
1969 if (bdrv_op_is_blocked(bs, BLOCK_OP_TYPE_DRIVE_DEL, &local_err)) {
1970 error_report_err(local_err);
1971 aio_context_release(aio_context);
1972 return -1;
1975 /* quiesce block driver; prevent further io */
1976 bdrv_drain_all();
1977 bdrv_flush(bs);
1978 bdrv_close(bs);
1980 /* if we have a device attached to this BlockDriverState
1981 * then we need to make the drive anonymous until the device
1982 * can be removed. If this is a drive with no device backing
1983 * then we can just get rid of the block driver state right here.
1985 if (blk_get_attached_dev(blk)) {
1986 blk_hide_on_behalf_of_hmp_drive_del(blk);
1987 /* Further I/O must not pause the guest */
1988 bdrv_set_on_error(bs, BLOCKDEV_ON_ERROR_REPORT,
1989 BLOCKDEV_ON_ERROR_REPORT);
1990 } else {
1991 blk_unref(blk);
1994 aio_context_release(aio_context);
1995 return 0;
1998 void qmp_block_resize(bool has_device, const char *device,
1999 bool has_node_name, const char *node_name,
2000 int64_t size, Error **errp)
2002 Error *local_err = NULL;
2003 BlockDriverState *bs;
2004 AioContext *aio_context;
2005 int ret;
2007 bs = bdrv_lookup_bs(has_device ? device : NULL,
2008 has_node_name ? node_name : NULL,
2009 &local_err);
2010 if (local_err) {
2011 error_propagate(errp, local_err);
2012 return;
2015 aio_context = bdrv_get_aio_context(bs);
2016 aio_context_acquire(aio_context);
2018 if (!bdrv_is_first_non_filter(bs)) {
2019 error_set(errp, QERR_FEATURE_DISABLED, "resize");
2020 goto out;
2023 if (size < 0) {
2024 error_set(errp, QERR_INVALID_PARAMETER_VALUE, "size", "a >0 size");
2025 goto out;
2028 if (bdrv_op_is_blocked(bs, BLOCK_OP_TYPE_RESIZE, NULL)) {
2029 error_set(errp, QERR_DEVICE_IN_USE, device);
2030 goto out;
2033 /* complete all in-flight operations before resizing the device */
2034 bdrv_drain_all();
2036 ret = bdrv_truncate(bs, size);
2037 switch (ret) {
2038 case 0:
2039 break;
2040 case -ENOMEDIUM:
2041 error_set(errp, QERR_DEVICE_HAS_NO_MEDIUM, device);
2042 break;
2043 case -ENOTSUP:
2044 error_set(errp, QERR_UNSUPPORTED);
2045 break;
2046 case -EACCES:
2047 error_set(errp, QERR_DEVICE_IS_READ_ONLY, device);
2048 break;
2049 case -EBUSY:
2050 error_set(errp, QERR_DEVICE_IN_USE, device);
2051 break;
2052 default:
2053 error_setg_errno(errp, -ret, "Could not resize");
2054 break;
2057 out:
2058 aio_context_release(aio_context);
2061 static void block_job_cb(void *opaque, int ret)
2063 /* Note that this function may be executed from another AioContext besides
2064 * the QEMU main loop. If you need to access anything that assumes the
2065 * QEMU global mutex, use a BH or introduce a mutex.
2068 BlockDriverState *bs = opaque;
2069 const char *msg = NULL;
2071 trace_block_job_cb(bs, bs->job, ret);
2073 assert(bs->job);
2075 if (ret < 0) {
2076 msg = strerror(-ret);
2079 if (block_job_is_cancelled(bs->job)) {
2080 block_job_event_cancelled(bs->job);
2081 } else {
2082 block_job_event_completed(bs->job, msg);
2085 bdrv_put_ref_bh_schedule(bs);
2088 void qmp_block_stream(const char *device,
2089 bool has_base, const char *base,
2090 bool has_backing_file, const char *backing_file,
2091 bool has_speed, int64_t speed,
2092 bool has_on_error, BlockdevOnError on_error,
2093 Error **errp)
2095 BlockDriverState *bs;
2096 BlockDriverState *base_bs = NULL;
2097 AioContext *aio_context;
2098 Error *local_err = NULL;
2099 const char *base_name = NULL;
2101 if (!has_on_error) {
2102 on_error = BLOCKDEV_ON_ERROR_REPORT;
2105 bs = bdrv_find(device);
2106 if (!bs) {
2107 error_set(errp, QERR_DEVICE_NOT_FOUND, device);
2108 return;
2111 aio_context = bdrv_get_aio_context(bs);
2112 aio_context_acquire(aio_context);
2114 if (bdrv_op_is_blocked(bs, BLOCK_OP_TYPE_STREAM, errp)) {
2115 goto out;
2118 if (has_base) {
2119 base_bs = bdrv_find_backing_image(bs, base);
2120 if (base_bs == NULL) {
2121 error_set(errp, QERR_BASE_NOT_FOUND, base);
2122 goto out;
2124 assert(bdrv_get_aio_context(base_bs) == aio_context);
2125 base_name = base;
2128 /* if we are streaming the entire chain, the result will have no backing
2129 * file, and specifying one is therefore an error */
2130 if (base_bs == NULL && has_backing_file) {
2131 error_setg(errp, "backing file specified, but streaming the "
2132 "entire chain");
2133 goto out;
2136 /* backing_file string overrides base bs filename */
2137 base_name = has_backing_file ? backing_file : base_name;
2139 stream_start(bs, base_bs, base_name, has_speed ? speed : 0,
2140 on_error, block_job_cb, bs, &local_err);
2141 if (local_err) {
2142 error_propagate(errp, local_err);
2143 goto out;
2146 trace_qmp_block_stream(bs, bs->job);
2148 out:
2149 aio_context_release(aio_context);
2152 void qmp_block_commit(const char *device,
2153 bool has_base, const char *base,
2154 bool has_top, const char *top,
2155 bool has_backing_file, const char *backing_file,
2156 bool has_speed, int64_t speed,
2157 Error **errp)
2159 BlockDriverState *bs;
2160 BlockDriverState *base_bs, *top_bs;
2161 AioContext *aio_context;
2162 Error *local_err = NULL;
2163 /* This will be part of the QMP command, if/when the
2164 * BlockdevOnError change for blkmirror makes it in
2166 BlockdevOnError on_error = BLOCKDEV_ON_ERROR_REPORT;
2168 if (!has_speed) {
2169 speed = 0;
2172 /* Important Note:
2173 * libvirt relies on the DeviceNotFound error class in order to probe for
2174 * live commit feature versions; for this to work, we must make sure to
2175 * perform the device lookup before any generic errors that may occur in a
2176 * scenario in which all optional arguments are omitted. */
2177 bs = bdrv_find(device);
2178 if (!bs) {
2179 error_set(errp, QERR_DEVICE_NOT_FOUND, device);
2180 return;
2183 aio_context = bdrv_get_aio_context(bs);
2184 aio_context_acquire(aio_context);
2186 /* drain all i/o before commits */
2187 bdrv_drain_all();
2189 if (bdrv_op_is_blocked(bs, BLOCK_OP_TYPE_COMMIT_SOURCE, errp)) {
2190 goto out;
2193 /* default top_bs is the active layer */
2194 top_bs = bs;
2196 if (has_top && top) {
2197 if (strcmp(bs->filename, top) != 0) {
2198 top_bs = bdrv_find_backing_image(bs, top);
2202 if (top_bs == NULL) {
2203 error_setg(errp, "Top image file %s not found", top ? top : "NULL");
2204 goto out;
2207 assert(bdrv_get_aio_context(top_bs) == aio_context);
2209 if (has_base && base) {
2210 base_bs = bdrv_find_backing_image(top_bs, base);
2211 } else {
2212 base_bs = bdrv_find_base(top_bs);
2215 if (base_bs == NULL) {
2216 error_set(errp, QERR_BASE_NOT_FOUND, base ? base : "NULL");
2217 goto out;
2220 assert(bdrv_get_aio_context(base_bs) == aio_context);
2222 if (bdrv_op_is_blocked(base_bs, BLOCK_OP_TYPE_COMMIT_TARGET, errp)) {
2223 goto out;
2226 /* Do not allow attempts to commit an image into itself */
2227 if (top_bs == base_bs) {
2228 error_setg(errp, "cannot commit an image into itself");
2229 goto out;
2232 if (top_bs == bs) {
2233 if (has_backing_file) {
2234 error_setg(errp, "'backing-file' specified,"
2235 " but 'top' is the active layer");
2236 goto out;
2238 commit_active_start(bs, base_bs, speed, on_error, block_job_cb,
2239 bs, &local_err);
2240 } else {
2241 commit_start(bs, base_bs, top_bs, speed, on_error, block_job_cb, bs,
2242 has_backing_file ? backing_file : NULL, &local_err);
2244 if (local_err != NULL) {
2245 error_propagate(errp, local_err);
2246 goto out;
2249 out:
2250 aio_context_release(aio_context);
2253 void qmp_drive_backup(const char *device, const char *target,
2254 bool has_format, const char *format,
2255 enum MirrorSyncMode sync,
2256 bool has_mode, enum NewImageMode mode,
2257 bool has_speed, int64_t speed,
2258 bool has_on_source_error, BlockdevOnError on_source_error,
2259 bool has_on_target_error, BlockdevOnError on_target_error,
2260 Error **errp)
2262 BlockDriverState *bs;
2263 BlockDriverState *target_bs;
2264 BlockDriverState *source = NULL;
2265 AioContext *aio_context;
2266 BlockDriver *drv = NULL;
2267 Error *local_err = NULL;
2268 int flags;
2269 int64_t size;
2270 int ret;
2272 if (!has_speed) {
2273 speed = 0;
2275 if (!has_on_source_error) {
2276 on_source_error = BLOCKDEV_ON_ERROR_REPORT;
2278 if (!has_on_target_error) {
2279 on_target_error = BLOCKDEV_ON_ERROR_REPORT;
2281 if (!has_mode) {
2282 mode = NEW_IMAGE_MODE_ABSOLUTE_PATHS;
2285 bs = bdrv_find(device);
2286 if (!bs) {
2287 error_set(errp, QERR_DEVICE_NOT_FOUND, device);
2288 return;
2291 aio_context = bdrv_get_aio_context(bs);
2292 aio_context_acquire(aio_context);
2294 /* Although backup_run has this check too, we need to use bs->drv below, so
2295 * do an early check redundantly. */
2296 if (!bdrv_is_inserted(bs)) {
2297 error_set(errp, QERR_DEVICE_HAS_NO_MEDIUM, device);
2298 goto out;
2301 if (!has_format) {
2302 format = mode == NEW_IMAGE_MODE_EXISTING ? NULL : bs->drv->format_name;
2304 if (format) {
2305 drv = bdrv_find_format(format);
2306 if (!drv) {
2307 error_set(errp, QERR_INVALID_BLOCK_FORMAT, format);
2308 goto out;
2312 /* Early check to avoid creating target */
2313 if (bdrv_op_is_blocked(bs, BLOCK_OP_TYPE_BACKUP_SOURCE, errp)) {
2314 goto out;
2317 flags = bs->open_flags | BDRV_O_RDWR;
2319 /* See if we have a backing HD we can use to create our new image
2320 * on top of. */
2321 if (sync == MIRROR_SYNC_MODE_TOP) {
2322 source = bs->backing_hd;
2323 if (!source) {
2324 sync = MIRROR_SYNC_MODE_FULL;
2327 if (sync == MIRROR_SYNC_MODE_NONE) {
2328 source = bs;
2331 size = bdrv_getlength(bs);
2332 if (size < 0) {
2333 error_setg_errno(errp, -size, "bdrv_getlength failed");
2334 goto out;
2337 if (mode != NEW_IMAGE_MODE_EXISTING) {
2338 assert(format && drv);
2339 if (source) {
2340 bdrv_img_create(target, format, source->filename,
2341 source->drv->format_name, NULL,
2342 size, flags, &local_err, false);
2343 } else {
2344 bdrv_img_create(target, format, NULL, NULL, NULL,
2345 size, flags, &local_err, false);
2349 if (local_err) {
2350 error_propagate(errp, local_err);
2351 goto out;
2354 target_bs = NULL;
2355 ret = bdrv_open(&target_bs, target, NULL, NULL, flags, drv, &local_err);
2356 if (ret < 0) {
2357 error_propagate(errp, local_err);
2358 goto out;
2361 bdrv_set_aio_context(target_bs, aio_context);
2363 backup_start(bs, target_bs, speed, sync, on_source_error, on_target_error,
2364 block_job_cb, bs, &local_err);
2365 if (local_err != NULL) {
2366 bdrv_unref(target_bs);
2367 error_propagate(errp, local_err);
2368 goto out;
2371 out:
2372 aio_context_release(aio_context);
2375 BlockDeviceInfoList *qmp_query_named_block_nodes(Error **errp)
2377 return bdrv_named_nodes_list();
2380 void qmp_blockdev_backup(const char *device, const char *target,
2381 enum MirrorSyncMode sync,
2382 bool has_speed, int64_t speed,
2383 bool has_on_source_error,
2384 BlockdevOnError on_source_error,
2385 bool has_on_target_error,
2386 BlockdevOnError on_target_error,
2387 Error **errp)
2389 BlockDriverState *bs;
2390 BlockDriverState *target_bs;
2391 Error *local_err = NULL;
2392 AioContext *aio_context;
2394 if (!has_speed) {
2395 speed = 0;
2397 if (!has_on_source_error) {
2398 on_source_error = BLOCKDEV_ON_ERROR_REPORT;
2400 if (!has_on_target_error) {
2401 on_target_error = BLOCKDEV_ON_ERROR_REPORT;
2404 bs = bdrv_find(device);
2405 if (!bs) {
2406 error_set(errp, QERR_DEVICE_NOT_FOUND, device);
2407 return;
2410 aio_context = bdrv_get_aio_context(bs);
2411 aio_context_acquire(aio_context);
2413 target_bs = bdrv_find(target);
2414 if (!target_bs) {
2415 error_set(errp, QERR_DEVICE_NOT_FOUND, target);
2416 goto out;
2419 bdrv_ref(target_bs);
2420 bdrv_set_aio_context(target_bs, aio_context);
2421 backup_start(bs, target_bs, speed, sync, on_source_error, on_target_error,
2422 block_job_cb, bs, &local_err);
2423 if (local_err != NULL) {
2424 bdrv_unref(target_bs);
2425 error_propagate(errp, local_err);
2427 out:
2428 aio_context_release(aio_context);
2431 #define DEFAULT_MIRROR_BUF_SIZE (10 << 20)
2433 void qmp_drive_mirror(const char *device, const char *target,
2434 bool has_format, const char *format,
2435 bool has_node_name, const char *node_name,
2436 bool has_replaces, const char *replaces,
2437 enum MirrorSyncMode sync,
2438 bool has_mode, enum NewImageMode mode,
2439 bool has_speed, int64_t speed,
2440 bool has_granularity, uint32_t granularity,
2441 bool has_buf_size, int64_t buf_size,
2442 bool has_on_source_error, BlockdevOnError on_source_error,
2443 bool has_on_target_error, BlockdevOnError on_target_error,
2444 Error **errp)
2446 BlockDriverState *bs;
2447 BlockDriverState *source, *target_bs;
2448 AioContext *aio_context;
2449 BlockDriver *drv = NULL;
2450 Error *local_err = NULL;
2451 QDict *options = NULL;
2452 int flags;
2453 int64_t size;
2454 int ret;
2456 if (!has_speed) {
2457 speed = 0;
2459 if (!has_on_source_error) {
2460 on_source_error = BLOCKDEV_ON_ERROR_REPORT;
2462 if (!has_on_target_error) {
2463 on_target_error = BLOCKDEV_ON_ERROR_REPORT;
2465 if (!has_mode) {
2466 mode = NEW_IMAGE_MODE_ABSOLUTE_PATHS;
2468 if (!has_granularity) {
2469 granularity = 0;
2471 if (!has_buf_size) {
2472 buf_size = DEFAULT_MIRROR_BUF_SIZE;
2475 if (granularity != 0 && (granularity < 512 || granularity > 1048576 * 64)) {
2476 error_set(errp, QERR_INVALID_PARAMETER_VALUE, "granularity",
2477 "a value in range [512B, 64MB]");
2478 return;
2480 if (granularity & (granularity - 1)) {
2481 error_set(errp, QERR_INVALID_PARAMETER_VALUE, "granularity", "power of 2");
2482 return;
2485 bs = bdrv_find(device);
2486 if (!bs) {
2487 error_set(errp, QERR_DEVICE_NOT_FOUND, device);
2488 return;
2491 aio_context = bdrv_get_aio_context(bs);
2492 aio_context_acquire(aio_context);
2494 if (!bdrv_is_inserted(bs)) {
2495 error_set(errp, QERR_DEVICE_HAS_NO_MEDIUM, device);
2496 goto out;
2499 if (!has_format) {
2500 format = mode == NEW_IMAGE_MODE_EXISTING ? NULL : bs->drv->format_name;
2502 if (format) {
2503 drv = bdrv_find_format(format);
2504 if (!drv) {
2505 error_set(errp, QERR_INVALID_BLOCK_FORMAT, format);
2506 goto out;
2510 if (bdrv_op_is_blocked(bs, BLOCK_OP_TYPE_MIRROR, errp)) {
2511 goto out;
2514 flags = bs->open_flags | BDRV_O_RDWR;
2515 source = bs->backing_hd;
2516 if (!source && sync == MIRROR_SYNC_MODE_TOP) {
2517 sync = MIRROR_SYNC_MODE_FULL;
2519 if (sync == MIRROR_SYNC_MODE_NONE) {
2520 source = bs;
2523 size = bdrv_getlength(bs);
2524 if (size < 0) {
2525 error_setg_errno(errp, -size, "bdrv_getlength failed");
2526 goto out;
2529 if (has_replaces) {
2530 BlockDriverState *to_replace_bs;
2531 AioContext *replace_aio_context;
2532 int64_t replace_size;
2534 if (!has_node_name) {
2535 error_setg(errp, "a node-name must be provided when replacing a"
2536 " named node of the graph");
2537 goto out;
2540 to_replace_bs = check_to_replace_node(replaces, &local_err);
2542 if (!to_replace_bs) {
2543 error_propagate(errp, local_err);
2544 goto out;
2547 replace_aio_context = bdrv_get_aio_context(to_replace_bs);
2548 aio_context_acquire(replace_aio_context);
2549 replace_size = bdrv_getlength(to_replace_bs);
2550 aio_context_release(replace_aio_context);
2552 if (size != replace_size) {
2553 error_setg(errp, "cannot replace image with a mirror image of "
2554 "different size");
2555 goto out;
2559 if ((sync == MIRROR_SYNC_MODE_FULL || !source)
2560 && mode != NEW_IMAGE_MODE_EXISTING)
2562 /* create new image w/o backing file */
2563 assert(format && drv);
2564 bdrv_img_create(target, format,
2565 NULL, NULL, NULL, size, flags, &local_err, false);
2566 } else {
2567 switch (mode) {
2568 case NEW_IMAGE_MODE_EXISTING:
2569 break;
2570 case NEW_IMAGE_MODE_ABSOLUTE_PATHS:
2571 /* create new image with backing file */
2572 bdrv_img_create(target, format,
2573 source->filename,
2574 source->drv->format_name,
2575 NULL, size, flags, &local_err, false);
2576 break;
2577 default:
2578 abort();
2582 if (local_err) {
2583 error_propagate(errp, local_err);
2584 goto out;
2587 if (has_node_name) {
2588 options = qdict_new();
2589 qdict_put(options, "node-name", qstring_from_str(node_name));
2592 /* Mirroring takes care of copy-on-write using the source's backing
2593 * file.
2595 target_bs = NULL;
2596 ret = bdrv_open(&target_bs, target, NULL, options,
2597 flags | BDRV_O_NO_BACKING, drv, &local_err);
2598 if (ret < 0) {
2599 error_propagate(errp, local_err);
2600 goto out;
2603 bdrv_set_aio_context(target_bs, aio_context);
2605 /* pass the node name to replace to mirror start since it's loose coupling
2606 * and will allow to check whether the node still exist at mirror completion
2608 mirror_start(bs, target_bs,
2609 has_replaces ? replaces : NULL,
2610 speed, granularity, buf_size, sync,
2611 on_source_error, on_target_error,
2612 block_job_cb, bs, &local_err);
2613 if (local_err != NULL) {
2614 bdrv_unref(target_bs);
2615 error_propagate(errp, local_err);
2616 goto out;
2619 out:
2620 aio_context_release(aio_context);
2623 /* Get the block job for a given device name and acquire its AioContext */
2624 static BlockJob *find_block_job(const char *device, AioContext **aio_context,
2625 Error **errp)
2627 BlockDriverState *bs;
2629 bs = bdrv_find(device);
2630 if (!bs) {
2631 goto notfound;
2634 *aio_context = bdrv_get_aio_context(bs);
2635 aio_context_acquire(*aio_context);
2637 if (!bs->job) {
2638 aio_context_release(*aio_context);
2639 goto notfound;
2642 return bs->job;
2644 notfound:
2645 error_set(errp, ERROR_CLASS_DEVICE_NOT_ACTIVE,
2646 "No active block job on device '%s'", device);
2647 *aio_context = NULL;
2648 return NULL;
2651 void qmp_block_job_set_speed(const char *device, int64_t speed, Error **errp)
2653 AioContext *aio_context;
2654 BlockJob *job = find_block_job(device, &aio_context, errp);
2656 if (!job) {
2657 return;
2660 block_job_set_speed(job, speed, errp);
2661 aio_context_release(aio_context);
2664 void qmp_block_job_cancel(const char *device,
2665 bool has_force, bool force, Error **errp)
2667 AioContext *aio_context;
2668 BlockJob *job = find_block_job(device, &aio_context, errp);
2670 if (!job) {
2671 return;
2674 if (!has_force) {
2675 force = false;
2678 if (job->paused && !force) {
2679 error_setg(errp, "The block job for device '%s' is currently paused",
2680 device);
2681 goto out;
2684 trace_qmp_block_job_cancel(job);
2685 block_job_cancel(job);
2686 out:
2687 aio_context_release(aio_context);
2690 void qmp_block_job_pause(const char *device, Error **errp)
2692 AioContext *aio_context;
2693 BlockJob *job = find_block_job(device, &aio_context, errp);
2695 if (!job) {
2696 return;
2699 trace_qmp_block_job_pause(job);
2700 block_job_pause(job);
2701 aio_context_release(aio_context);
2704 void qmp_block_job_resume(const char *device, Error **errp)
2706 AioContext *aio_context;
2707 BlockJob *job = find_block_job(device, &aio_context, errp);
2709 if (!job) {
2710 return;
2713 trace_qmp_block_job_resume(job);
2714 block_job_resume(job);
2715 aio_context_release(aio_context);
2718 void qmp_block_job_complete(const char *device, Error **errp)
2720 AioContext *aio_context;
2721 BlockJob *job = find_block_job(device, &aio_context, errp);
2723 if (!job) {
2724 return;
2727 trace_qmp_block_job_complete(job);
2728 block_job_complete(job, errp);
2729 aio_context_release(aio_context);
2732 void qmp_change_backing_file(const char *device,
2733 const char *image_node_name,
2734 const char *backing_file,
2735 Error **errp)
2737 BlockDriverState *bs = NULL;
2738 AioContext *aio_context;
2739 BlockDriverState *image_bs = NULL;
2740 Error *local_err = NULL;
2741 bool ro;
2742 int open_flags;
2743 int ret;
2745 /* find the top layer BDS of the chain */
2746 bs = bdrv_find(device);
2747 if (!bs) {
2748 error_set(errp, QERR_DEVICE_NOT_FOUND, device);
2749 return;
2752 aio_context = bdrv_get_aio_context(bs);
2753 aio_context_acquire(aio_context);
2755 image_bs = bdrv_lookup_bs(NULL, image_node_name, &local_err);
2756 if (local_err) {
2757 error_propagate(errp, local_err);
2758 goto out;
2761 if (!image_bs) {
2762 error_setg(errp, "image file not found");
2763 goto out;
2766 if (bdrv_find_base(image_bs) == image_bs) {
2767 error_setg(errp, "not allowing backing file change on an image "
2768 "without a backing file");
2769 goto out;
2772 /* even though we are not necessarily operating on bs, we need it to
2773 * determine if block ops are currently prohibited on the chain */
2774 if (bdrv_op_is_blocked(bs, BLOCK_OP_TYPE_CHANGE, errp)) {
2775 goto out;
2778 /* final sanity check */
2779 if (!bdrv_chain_contains(bs, image_bs)) {
2780 error_setg(errp, "'%s' and image file are not in the same chain",
2781 device);
2782 goto out;
2785 /* if not r/w, reopen to make r/w */
2786 open_flags = image_bs->open_flags;
2787 ro = bdrv_is_read_only(image_bs);
2789 if (ro) {
2790 bdrv_reopen(image_bs, open_flags | BDRV_O_RDWR, &local_err);
2791 if (local_err) {
2792 error_propagate(errp, local_err);
2793 goto out;
2797 ret = bdrv_change_backing_file(image_bs, backing_file,
2798 image_bs->drv ? image_bs->drv->format_name : "");
2800 if (ret < 0) {
2801 error_setg_errno(errp, -ret, "Could not change backing file to '%s'",
2802 backing_file);
2803 /* don't exit here, so we can try to restore open flags if
2804 * appropriate */
2807 if (ro) {
2808 bdrv_reopen(image_bs, open_flags, &local_err);
2809 if (local_err) {
2810 error_propagate(errp, local_err); /* will preserve prior errp */
2814 out:
2815 aio_context_release(aio_context);
2818 void qmp_blockdev_add(BlockdevOptions *options, Error **errp)
2820 QmpOutputVisitor *ov = qmp_output_visitor_new();
2821 BlockBackend *blk;
2822 QObject *obj;
2823 QDict *qdict;
2824 Error *local_err = NULL;
2826 /* Require an ID in the top level */
2827 if (!options->has_id) {
2828 error_setg(errp, "Block device needs an ID");
2829 goto fail;
2832 /* TODO Sort it out in raw-posix and drive_new(): Reject aio=native with
2833 * cache.direct=false instead of silently switching to aio=threads, except
2834 * when called from drive_new().
2836 * For now, simply forbidding the combination for all drivers will do. */
2837 if (options->has_aio && options->aio == BLOCKDEV_AIO_OPTIONS_NATIVE) {
2838 bool direct = options->has_cache &&
2839 options->cache->has_direct &&
2840 options->cache->direct;
2841 if (!direct) {
2842 error_setg(errp, "aio=native requires cache.direct=true");
2843 goto fail;
2847 visit_type_BlockdevOptions(qmp_output_get_visitor(ov),
2848 &options, NULL, &local_err);
2849 if (local_err) {
2850 error_propagate(errp, local_err);
2851 goto fail;
2854 obj = qmp_output_get_qobject(ov);
2855 qdict = qobject_to_qdict(obj);
2857 qdict_flatten(qdict);
2859 blk = blockdev_init(NULL, qdict, &local_err);
2860 if (local_err) {
2861 error_propagate(errp, local_err);
2862 goto fail;
2865 if (bdrv_key_required(blk_bs(blk))) {
2866 blk_unref(blk);
2867 error_setg(errp, "blockdev-add doesn't support encrypted devices");
2868 goto fail;
2871 fail:
2872 qmp_output_visitor_cleanup(ov);
2875 BlockJobInfoList *qmp_query_block_jobs(Error **errp)
2877 BlockJobInfoList *head = NULL, **p_next = &head;
2878 BlockDriverState *bs;
2880 for (bs = bdrv_next(NULL); bs; bs = bdrv_next(bs)) {
2881 AioContext *aio_context = bdrv_get_aio_context(bs);
2883 aio_context_acquire(aio_context);
2885 if (bs->job) {
2886 BlockJobInfoList *elem = g_new0(BlockJobInfoList, 1);
2887 elem->value = block_job_query(bs->job);
2888 *p_next = elem;
2889 p_next = &elem->next;
2892 aio_context_release(aio_context);
2895 return head;
2898 QemuOptsList qemu_common_drive_opts = {
2899 .name = "drive",
2900 .head = QTAILQ_HEAD_INITIALIZER(qemu_common_drive_opts.head),
2901 .desc = {
2903 .name = "snapshot",
2904 .type = QEMU_OPT_BOOL,
2905 .help = "enable/disable snapshot mode",
2907 .name = "discard",
2908 .type = QEMU_OPT_STRING,
2909 .help = "discard operation (ignore/off, unmap/on)",
2911 .name = "cache.writeback",
2912 .type = QEMU_OPT_BOOL,
2913 .help = "enables writeback mode for any caches",
2915 .name = "cache.direct",
2916 .type = QEMU_OPT_BOOL,
2917 .help = "enables use of O_DIRECT (bypass the host page cache)",
2919 .name = "cache.no-flush",
2920 .type = QEMU_OPT_BOOL,
2921 .help = "ignore any flush requests for the device",
2923 .name = "aio",
2924 .type = QEMU_OPT_STRING,
2925 .help = "host AIO implementation (threads, native)",
2927 .name = "format",
2928 .type = QEMU_OPT_STRING,
2929 .help = "disk format (raw, qcow2, ...)",
2931 .name = "rerror",
2932 .type = QEMU_OPT_STRING,
2933 .help = "read error action",
2935 .name = "werror",
2936 .type = QEMU_OPT_STRING,
2937 .help = "write error action",
2939 .name = "read-only",
2940 .type = QEMU_OPT_BOOL,
2941 .help = "open drive file as read-only",
2943 .name = "throttling.iops-total",
2944 .type = QEMU_OPT_NUMBER,
2945 .help = "limit total I/O operations per second",
2947 .name = "throttling.iops-read",
2948 .type = QEMU_OPT_NUMBER,
2949 .help = "limit read operations per second",
2951 .name = "throttling.iops-write",
2952 .type = QEMU_OPT_NUMBER,
2953 .help = "limit write operations per second",
2955 .name = "throttling.bps-total",
2956 .type = QEMU_OPT_NUMBER,
2957 .help = "limit total bytes per second",
2959 .name = "throttling.bps-read",
2960 .type = QEMU_OPT_NUMBER,
2961 .help = "limit read bytes per second",
2963 .name = "throttling.bps-write",
2964 .type = QEMU_OPT_NUMBER,
2965 .help = "limit write bytes per second",
2967 .name = "throttling.iops-total-max",
2968 .type = QEMU_OPT_NUMBER,
2969 .help = "I/O operations burst",
2971 .name = "throttling.iops-read-max",
2972 .type = QEMU_OPT_NUMBER,
2973 .help = "I/O operations read burst",
2975 .name = "throttling.iops-write-max",
2976 .type = QEMU_OPT_NUMBER,
2977 .help = "I/O operations write burst",
2979 .name = "throttling.bps-total-max",
2980 .type = QEMU_OPT_NUMBER,
2981 .help = "total bytes burst",
2983 .name = "throttling.bps-read-max",
2984 .type = QEMU_OPT_NUMBER,
2985 .help = "total bytes read burst",
2987 .name = "throttling.bps-write-max",
2988 .type = QEMU_OPT_NUMBER,
2989 .help = "total bytes write burst",
2991 .name = "throttling.iops-size",
2992 .type = QEMU_OPT_NUMBER,
2993 .help = "when limiting by iops max size of an I/O in bytes",
2995 .name = "copy-on-read",
2996 .type = QEMU_OPT_BOOL,
2997 .help = "copy read data from backing file into image file",
2999 .name = "detect-zeroes",
3000 .type = QEMU_OPT_STRING,
3001 .help = "try to optimize zero writes (off, on, unmap)",
3003 { /* end of list */ }
3007 QemuOptsList qemu_drive_opts = {
3008 .name = "drive",
3009 .head = QTAILQ_HEAD_INITIALIZER(qemu_drive_opts.head),
3010 .desc = {
3012 * no elements => accept any params
3013 * validation will happen later
3015 { /* end of list */ }