vhost_net: Add missing 'static' attribute
[qemu.git] / blockdev.c
blobb9c1c0cc1aaa17ee526f4dd6499181ce9b38c1b6
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;
184 opts = drive_def(optstr);
185 if (!opts) {
186 return NULL;
188 if (type != IF_DEFAULT) {
189 qemu_opt_set(opts, "if", if_name[type], &error_abort);
191 if (index >= 0) {
192 qemu_opt_set_number(opts, "index", index, &error_abort);
194 if (file)
195 qemu_opt_set(opts, "file", file, &error_abort);
196 return opts;
199 DriveInfo *drive_get(BlockInterfaceType type, int bus, int unit)
201 BlockBackend *blk;
202 DriveInfo *dinfo;
204 for (blk = blk_next(NULL); blk; blk = blk_next(blk)) {
205 dinfo = blk_legacy_dinfo(blk);
206 if (dinfo && dinfo->type == type
207 && dinfo->bus == bus && dinfo->unit == unit) {
208 return dinfo;
212 return NULL;
215 bool drive_check_orphaned(void)
217 BlockBackend *blk;
218 DriveInfo *dinfo;
219 bool rs = false;
221 for (blk = blk_next(NULL); blk; blk = blk_next(blk)) {
222 dinfo = blk_legacy_dinfo(blk);
223 /* If dinfo->bdrv->dev is NULL, it has no device attached. */
224 /* Unless this is a default drive, this may be an oversight. */
225 if (!blk_get_attached_dev(blk) && !dinfo->is_default &&
226 dinfo->type != IF_NONE) {
227 fprintf(stderr, "Warning: Orphaned drive without device: "
228 "id=%s,file=%s,if=%s,bus=%d,unit=%d\n",
229 blk_name(blk), blk_bs(blk)->filename, if_name[dinfo->type],
230 dinfo->bus, dinfo->unit);
231 rs = true;
235 return rs;
238 DriveInfo *drive_get_by_index(BlockInterfaceType type, int index)
240 return drive_get(type,
241 drive_index_to_bus_id(type, index),
242 drive_index_to_unit_id(type, index));
245 int drive_get_max_bus(BlockInterfaceType type)
247 int max_bus;
248 BlockBackend *blk;
249 DriveInfo *dinfo;
251 max_bus = -1;
252 for (blk = blk_next(NULL); blk; blk = blk_next(blk)) {
253 dinfo = blk_legacy_dinfo(blk);
254 if (dinfo && dinfo->type == type && dinfo->bus > max_bus) {
255 max_bus = dinfo->bus;
258 return max_bus;
261 /* Get a block device. This should only be used for single-drive devices
262 (e.g. SD/Floppy/MTD). Multi-disk devices (scsi/ide) should use the
263 appropriate bus. */
264 DriveInfo *drive_get_next(BlockInterfaceType type)
266 static int next_block_unit[IF_COUNT];
268 return drive_get(type, 0, next_block_unit[type]++);
271 static void bdrv_format_print(void *opaque, const char *name)
273 error_printf(" %s", name);
276 typedef struct {
277 QEMUBH *bh;
278 BlockDriverState *bs;
279 } BDRVPutRefBH;
281 static void bdrv_put_ref_bh(void *opaque)
283 BDRVPutRefBH *s = opaque;
285 bdrv_unref(s->bs);
286 qemu_bh_delete(s->bh);
287 g_free(s);
291 * Release a BDS reference in a BH
293 * It is not safe to use bdrv_unref() from a callback function when the callers
294 * still need the BlockDriverState. In such cases we schedule a BH to release
295 * the reference.
297 static void bdrv_put_ref_bh_schedule(BlockDriverState *bs)
299 BDRVPutRefBH *s;
301 s = g_new(BDRVPutRefBH, 1);
302 s->bh = qemu_bh_new(bdrv_put_ref_bh, s);
303 s->bs = bs;
304 qemu_bh_schedule(s->bh);
307 static int parse_block_error_action(const char *buf, bool is_read, Error **errp)
309 if (!strcmp(buf, "ignore")) {
310 return BLOCKDEV_ON_ERROR_IGNORE;
311 } else if (!is_read && !strcmp(buf, "enospc")) {
312 return BLOCKDEV_ON_ERROR_ENOSPC;
313 } else if (!strcmp(buf, "stop")) {
314 return BLOCKDEV_ON_ERROR_STOP;
315 } else if (!strcmp(buf, "report")) {
316 return BLOCKDEV_ON_ERROR_REPORT;
317 } else {
318 error_setg(errp, "'%s' invalid %s error action",
319 buf, is_read ? "read" : "write");
320 return -1;
324 static bool check_throttle_config(ThrottleConfig *cfg, Error **errp)
326 if (throttle_conflicting(cfg)) {
327 error_setg(errp, "bps/iops/max total values and read/write values"
328 " cannot be used at the same time");
329 return false;
332 if (!throttle_is_valid(cfg)) {
333 error_setg(errp, "bps/iops/maxs values must be 0 or greater");
334 return false;
337 return true;
340 typedef enum { MEDIA_DISK, MEDIA_CDROM } DriveMediaType;
342 /* Takes the ownership of bs_opts */
343 static BlockBackend *blockdev_init(const char *file, QDict *bs_opts,
344 Error **errp)
346 const char *buf;
347 int ro = 0;
348 int bdrv_flags = 0;
349 int on_read_error, on_write_error;
350 BlockBackend *blk;
351 BlockDriverState *bs;
352 ThrottleConfig cfg;
353 int snapshot = 0;
354 bool copy_on_read;
355 Error *error = NULL;
356 QemuOpts *opts;
357 const char *id;
358 bool has_driver_specific_opts;
359 BlockdevDetectZeroesOptions detect_zeroes;
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 if (qdict_haskey(bs_opts, "driver")) {
426 error_setg(errp, "Cannot specify both 'driver' and 'format'");
427 goto early_err;
429 qdict_put(bs_opts, "driver", qstring_from_str(buf));
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 if ((!file || !*file) && !has_driver_specific_opts) {
505 blk = blk_new_with_bs(qemu_opts_id(opts), errp);
506 if (!blk) {
507 goto early_err;
510 bs = blk_bs(blk);
511 bs->open_flags = snapshot ? BDRV_O_SNAPSHOT : 0;
512 bs->read_only = ro;
514 QDECREF(bs_opts);
515 } else {
516 if (file && !*file) {
517 file = NULL;
520 if (snapshot) {
521 /* always use cache=unsafe with snapshot */
522 bdrv_flags &= ~BDRV_O_CACHE_MASK;
523 bdrv_flags |= (BDRV_O_SNAPSHOT|BDRV_O_CACHE_WB|BDRV_O_NO_FLUSH);
526 if (copy_on_read) {
527 bdrv_flags |= BDRV_O_COPY_ON_READ;
530 if (runstate_check(RUN_STATE_INMIGRATE)) {
531 bdrv_flags |= BDRV_O_INCOMING;
534 bdrv_flags |= ro ? 0 : BDRV_O_RDWR;
536 blk = blk_new_open(qemu_opts_id(opts), file, NULL, bs_opts, bdrv_flags,
537 errp);
538 if (!blk) {
539 goto err_no_bs_opts;
541 bs = blk_bs(blk);
544 bs->detect_zeroes = detect_zeroes;
546 bdrv_set_on_error(bs, on_read_error, on_write_error);
548 /* disk I/O throttling */
549 if (throttle_enabled(&cfg)) {
550 bdrv_io_limits_enable(bs);
551 bdrv_set_io_limits(bs, &cfg);
554 if (bdrv_key_required(bs)) {
555 autostart = 0;
558 err_no_bs_opts:
559 qemu_opts_del(opts);
560 return blk;
562 early_err:
563 qemu_opts_del(opts);
564 err_no_opts:
565 QDECREF(bs_opts);
566 return NULL;
569 static void qemu_opt_rename(QemuOpts *opts, const char *from, const char *to,
570 Error **errp)
572 const char *value;
574 value = qemu_opt_get(opts, from);
575 if (value) {
576 if (qemu_opt_find(opts, to)) {
577 error_setg(errp, "'%s' and its alias '%s' can't be used at the "
578 "same time", to, from);
579 return;
583 /* rename all items in opts */
584 while ((value = qemu_opt_get(opts, from))) {
585 qemu_opt_set(opts, to, value, &error_abort);
586 qemu_opt_unset(opts, from);
590 QemuOptsList qemu_legacy_drive_opts = {
591 .name = "drive",
592 .head = QTAILQ_HEAD_INITIALIZER(qemu_legacy_drive_opts.head),
593 .desc = {
595 .name = "bus",
596 .type = QEMU_OPT_NUMBER,
597 .help = "bus number",
599 .name = "unit",
600 .type = QEMU_OPT_NUMBER,
601 .help = "unit number (i.e. lun for scsi)",
603 .name = "index",
604 .type = QEMU_OPT_NUMBER,
605 .help = "index number",
607 .name = "media",
608 .type = QEMU_OPT_STRING,
609 .help = "media type (disk, cdrom)",
611 .name = "if",
612 .type = QEMU_OPT_STRING,
613 .help = "interface (ide, scsi, sd, mtd, floppy, pflash, virtio)",
615 .name = "cyls",
616 .type = QEMU_OPT_NUMBER,
617 .help = "number of cylinders (ide disk geometry)",
619 .name = "heads",
620 .type = QEMU_OPT_NUMBER,
621 .help = "number of heads (ide disk geometry)",
623 .name = "secs",
624 .type = QEMU_OPT_NUMBER,
625 .help = "number of sectors (ide disk geometry)",
627 .name = "trans",
628 .type = QEMU_OPT_STRING,
629 .help = "chs translation (auto, lba, none)",
631 .name = "boot",
632 .type = QEMU_OPT_BOOL,
633 .help = "(deprecated, ignored)",
635 .name = "addr",
636 .type = QEMU_OPT_STRING,
637 .help = "pci address (virtio only)",
639 .name = "serial",
640 .type = QEMU_OPT_STRING,
641 .help = "disk serial number",
643 .name = "file",
644 .type = QEMU_OPT_STRING,
645 .help = "file name",
648 /* Options that are passed on, but have special semantics with -drive */
650 .name = "read-only",
651 .type = QEMU_OPT_BOOL,
652 .help = "open drive file as read-only",
654 .name = "rerror",
655 .type = QEMU_OPT_STRING,
656 .help = "read error action",
658 .name = "werror",
659 .type = QEMU_OPT_STRING,
660 .help = "write error action",
662 .name = "copy-on-read",
663 .type = QEMU_OPT_BOOL,
664 .help = "copy read data from backing file into image file",
667 { /* end of list */ }
671 DriveInfo *drive_new(QemuOpts *all_opts, BlockInterfaceType block_default_type)
673 const char *value;
674 BlockBackend *blk;
675 DriveInfo *dinfo = NULL;
676 QDict *bs_opts;
677 QemuOpts *legacy_opts;
678 DriveMediaType media = MEDIA_DISK;
679 BlockInterfaceType type;
680 int cyls, heads, secs, translation;
681 int max_devs, bus_id, unit_id, index;
682 const char *devaddr;
683 const char *werror, *rerror;
684 bool read_only = false;
685 bool copy_on_read;
686 const char *serial;
687 const char *filename;
688 Error *local_err = NULL;
689 int i;
691 /* Change legacy command line options into QMP ones */
692 static const struct {
693 const char *from;
694 const char *to;
695 } opt_renames[] = {
696 { "iops", "throttling.iops-total" },
697 { "iops_rd", "throttling.iops-read" },
698 { "iops_wr", "throttling.iops-write" },
700 { "bps", "throttling.bps-total" },
701 { "bps_rd", "throttling.bps-read" },
702 { "bps_wr", "throttling.bps-write" },
704 { "iops_max", "throttling.iops-total-max" },
705 { "iops_rd_max", "throttling.iops-read-max" },
706 { "iops_wr_max", "throttling.iops-write-max" },
708 { "bps_max", "throttling.bps-total-max" },
709 { "bps_rd_max", "throttling.bps-read-max" },
710 { "bps_wr_max", "throttling.bps-write-max" },
712 { "iops_size", "throttling.iops-size" },
714 { "readonly", "read-only" },
717 for (i = 0; i < ARRAY_SIZE(opt_renames); i++) {
718 qemu_opt_rename(all_opts, opt_renames[i].from, opt_renames[i].to,
719 &local_err);
720 if (local_err) {
721 error_report_err(local_err);
722 return NULL;
726 value = qemu_opt_get(all_opts, "cache");
727 if (value) {
728 int flags = 0;
730 if (bdrv_parse_cache_flags(value, &flags) != 0) {
731 error_report("invalid cache option");
732 return NULL;
735 /* Specific options take precedence */
736 if (!qemu_opt_get(all_opts, "cache.writeback")) {
737 qemu_opt_set_bool(all_opts, "cache.writeback",
738 !!(flags & BDRV_O_CACHE_WB), &error_abort);
740 if (!qemu_opt_get(all_opts, "cache.direct")) {
741 qemu_opt_set_bool(all_opts, "cache.direct",
742 !!(flags & BDRV_O_NOCACHE), &error_abort);
744 if (!qemu_opt_get(all_opts, "cache.no-flush")) {
745 qemu_opt_set_bool(all_opts, "cache.no-flush",
746 !!(flags & BDRV_O_NO_FLUSH), &error_abort);
748 qemu_opt_unset(all_opts, "cache");
751 /* Get a QDict for processing the options */
752 bs_opts = qdict_new();
753 qemu_opts_to_qdict(all_opts, bs_opts);
755 legacy_opts = qemu_opts_create(&qemu_legacy_drive_opts, NULL, 0,
756 &error_abort);
757 qemu_opts_absorb_qdict(legacy_opts, bs_opts, &local_err);
758 if (local_err) {
759 error_report_err(local_err);
760 goto fail;
763 /* Deprecated option boot=[on|off] */
764 if (qemu_opt_get(legacy_opts, "boot") != NULL) {
765 fprintf(stderr, "qemu-kvm: boot=on|off is deprecated and will be "
766 "ignored. Future versions will reject this parameter. Please "
767 "update your scripts.\n");
770 /* Media type */
771 value = qemu_opt_get(legacy_opts, "media");
772 if (value) {
773 if (!strcmp(value, "disk")) {
774 media = MEDIA_DISK;
775 } else if (!strcmp(value, "cdrom")) {
776 media = MEDIA_CDROM;
777 read_only = true;
778 } else {
779 error_report("'%s' invalid media", value);
780 goto fail;
784 /* copy-on-read is disabled with a warning for read-only devices */
785 read_only |= qemu_opt_get_bool(legacy_opts, "read-only", false);
786 copy_on_read = qemu_opt_get_bool(legacy_opts, "copy-on-read", false);
788 if (read_only && copy_on_read) {
789 error_report("warning: disabling copy-on-read on read-only drive");
790 copy_on_read = false;
793 qdict_put(bs_opts, "read-only",
794 qstring_from_str(read_only ? "on" : "off"));
795 qdict_put(bs_opts, "copy-on-read",
796 qstring_from_str(copy_on_read ? "on" :"off"));
798 /* Controller type */
799 value = qemu_opt_get(legacy_opts, "if");
800 if (value) {
801 for (type = 0;
802 type < IF_COUNT && strcmp(value, if_name[type]);
803 type++) {
805 if (type == IF_COUNT) {
806 error_report("unsupported bus type '%s'", value);
807 goto fail;
809 } else {
810 type = block_default_type;
813 /* Geometry */
814 cyls = qemu_opt_get_number(legacy_opts, "cyls", 0);
815 heads = qemu_opt_get_number(legacy_opts, "heads", 0);
816 secs = qemu_opt_get_number(legacy_opts, "secs", 0);
818 if (cyls || heads || secs) {
819 if (cyls < 1) {
820 error_report("invalid physical cyls number");
821 goto fail;
823 if (heads < 1) {
824 error_report("invalid physical heads number");
825 goto fail;
827 if (secs < 1) {
828 error_report("invalid physical secs number");
829 goto fail;
833 translation = BIOS_ATA_TRANSLATION_AUTO;
834 value = qemu_opt_get(legacy_opts, "trans");
835 if (value != NULL) {
836 if (!cyls) {
837 error_report("'%s' trans must be used with cyls, heads and secs",
838 value);
839 goto fail;
841 if (!strcmp(value, "none")) {
842 translation = BIOS_ATA_TRANSLATION_NONE;
843 } else if (!strcmp(value, "lba")) {
844 translation = BIOS_ATA_TRANSLATION_LBA;
845 } else if (!strcmp(value, "large")) {
846 translation = BIOS_ATA_TRANSLATION_LARGE;
847 } else if (!strcmp(value, "rechs")) {
848 translation = BIOS_ATA_TRANSLATION_RECHS;
849 } else if (!strcmp(value, "auto")) {
850 translation = BIOS_ATA_TRANSLATION_AUTO;
851 } else {
852 error_report("'%s' invalid translation type", value);
853 goto fail;
857 if (media == MEDIA_CDROM) {
858 if (cyls || secs || heads) {
859 error_report("CHS can't be set with media=cdrom");
860 goto fail;
864 /* Device address specified by bus/unit or index.
865 * If none was specified, try to find the first free one. */
866 bus_id = qemu_opt_get_number(legacy_opts, "bus", 0);
867 unit_id = qemu_opt_get_number(legacy_opts, "unit", -1);
868 index = qemu_opt_get_number(legacy_opts, "index", -1);
870 max_devs = if_max_devs[type];
872 if (index != -1) {
873 if (bus_id != 0 || unit_id != -1) {
874 error_report("index cannot be used with bus and unit");
875 goto fail;
877 bus_id = drive_index_to_bus_id(type, index);
878 unit_id = drive_index_to_unit_id(type, index);
881 if (unit_id == -1) {
882 unit_id = 0;
883 while (drive_get(type, bus_id, unit_id) != NULL) {
884 unit_id++;
885 if (max_devs && unit_id >= max_devs) {
886 unit_id -= max_devs;
887 bus_id++;
892 if (max_devs && unit_id >= max_devs) {
893 error_report("unit %d too big (max is %d)", unit_id, max_devs - 1);
894 goto fail;
897 if (drive_get(type, bus_id, unit_id) != NULL) {
898 error_report("drive with bus=%d, unit=%d (index=%d) exists",
899 bus_id, unit_id, index);
900 goto fail;
903 /* Serial number */
904 serial = qemu_opt_get(legacy_opts, "serial");
906 /* no id supplied -> create one */
907 if (qemu_opts_id(all_opts) == NULL) {
908 char *new_id;
909 const char *mediastr = "";
910 if (type == IF_IDE || type == IF_SCSI) {
911 mediastr = (media == MEDIA_CDROM) ? "-cd" : "-hd";
913 if (max_devs) {
914 new_id = g_strdup_printf("%s%i%s%i", if_name[type], bus_id,
915 mediastr, unit_id);
916 } else {
917 new_id = g_strdup_printf("%s%s%i", if_name[type],
918 mediastr, unit_id);
920 qdict_put(bs_opts, "id", qstring_from_str(new_id));
921 g_free(new_id);
924 /* Add virtio block device */
925 devaddr = qemu_opt_get(legacy_opts, "addr");
926 if (devaddr && type != IF_VIRTIO) {
927 error_report("addr is not supported by this bus type");
928 goto fail;
931 if (type == IF_VIRTIO) {
932 QemuOpts *devopts;
933 devopts = qemu_opts_create(qemu_find_opts("device"), NULL, 0,
934 &error_abort);
935 if (arch_type == QEMU_ARCH_S390X) {
936 qemu_opt_set(devopts, "driver", "virtio-blk-s390", &error_abort);
937 } else {
938 qemu_opt_set(devopts, "driver", "virtio-blk-pci", &error_abort);
940 qemu_opt_set(devopts, "drive", qdict_get_str(bs_opts, "id"),
941 &error_abort);
942 if (devaddr) {
943 qemu_opt_set(devopts, "addr", devaddr, &error_abort);
947 filename = qemu_opt_get(legacy_opts, "file");
949 /* Check werror/rerror compatibility with if=... */
950 werror = qemu_opt_get(legacy_opts, "werror");
951 if (werror != NULL) {
952 if (type != IF_IDE && type != IF_SCSI && type != IF_VIRTIO &&
953 type != IF_NONE) {
954 error_report("werror is not supported by this bus type");
955 goto fail;
957 qdict_put(bs_opts, "werror", qstring_from_str(werror));
960 rerror = qemu_opt_get(legacy_opts, "rerror");
961 if (rerror != NULL) {
962 if (type != IF_IDE && type != IF_VIRTIO && type != IF_SCSI &&
963 type != IF_NONE) {
964 error_report("rerror is not supported by this bus type");
965 goto fail;
967 qdict_put(bs_opts, "rerror", qstring_from_str(rerror));
970 /* Actual block device init: Functionality shared with blockdev-add */
971 blk = blockdev_init(filename, bs_opts, &local_err);
972 bs_opts = NULL;
973 if (!blk) {
974 if (local_err) {
975 error_report_err(local_err);
977 goto fail;
978 } else {
979 assert(!local_err);
982 /* Create legacy DriveInfo */
983 dinfo = g_malloc0(sizeof(*dinfo));
984 dinfo->opts = all_opts;
986 dinfo->cyls = cyls;
987 dinfo->heads = heads;
988 dinfo->secs = secs;
989 dinfo->trans = translation;
991 dinfo->type = type;
992 dinfo->bus = bus_id;
993 dinfo->unit = unit_id;
994 dinfo->devaddr = devaddr;
995 dinfo->serial = g_strdup(serial);
997 blk_set_legacy_dinfo(blk, dinfo);
999 switch(type) {
1000 case IF_IDE:
1001 case IF_SCSI:
1002 case IF_XEN:
1003 case IF_NONE:
1004 dinfo->media_cd = media == MEDIA_CDROM;
1005 break;
1006 default:
1007 break;
1010 fail:
1011 qemu_opts_del(legacy_opts);
1012 QDECREF(bs_opts);
1013 return dinfo;
1016 void hmp_commit(Monitor *mon, const QDict *qdict)
1018 const char *device = qdict_get_str(qdict, "device");
1019 BlockDriverState *bs;
1020 int ret;
1022 if (!strcmp(device, "all")) {
1023 ret = bdrv_commit_all();
1024 } else {
1025 bs = bdrv_find(device);
1026 if (!bs) {
1027 monitor_printf(mon, "Device '%s' not found\n", device);
1028 return;
1030 ret = bdrv_commit(bs);
1032 if (ret < 0) {
1033 monitor_printf(mon, "'commit' error for '%s': %s\n", device,
1034 strerror(-ret));
1038 static void blockdev_do_action(int kind, void *data, Error **errp)
1040 TransactionAction action;
1041 TransactionActionList list;
1043 action.kind = kind;
1044 action.data = data;
1045 list.value = &action;
1046 list.next = NULL;
1047 qmp_transaction(&list, errp);
1050 void qmp_blockdev_snapshot_sync(bool has_device, const char *device,
1051 bool has_node_name, const char *node_name,
1052 const char *snapshot_file,
1053 bool has_snapshot_node_name,
1054 const char *snapshot_node_name,
1055 bool has_format, const char *format,
1056 bool has_mode, NewImageMode mode, Error **errp)
1058 BlockdevSnapshot snapshot = {
1059 .has_device = has_device,
1060 .device = (char *) device,
1061 .has_node_name = has_node_name,
1062 .node_name = (char *) node_name,
1063 .snapshot_file = (char *) snapshot_file,
1064 .has_snapshot_node_name = has_snapshot_node_name,
1065 .snapshot_node_name = (char *) snapshot_node_name,
1066 .has_format = has_format,
1067 .format = (char *) format,
1068 .has_mode = has_mode,
1069 .mode = mode,
1071 blockdev_do_action(TRANSACTION_ACTION_KIND_BLOCKDEV_SNAPSHOT_SYNC,
1072 &snapshot, errp);
1075 void qmp_blockdev_snapshot_internal_sync(const char *device,
1076 const char *name,
1077 Error **errp)
1079 BlockdevSnapshotInternal snapshot = {
1080 .device = (char *) device,
1081 .name = (char *) name
1084 blockdev_do_action(TRANSACTION_ACTION_KIND_BLOCKDEV_SNAPSHOT_INTERNAL_SYNC,
1085 &snapshot, errp);
1088 SnapshotInfo *qmp_blockdev_snapshot_delete_internal_sync(const char *device,
1089 bool has_id,
1090 const char *id,
1091 bool has_name,
1092 const char *name,
1093 Error **errp)
1095 BlockDriverState *bs = bdrv_find(device);
1096 AioContext *aio_context;
1097 QEMUSnapshotInfo sn;
1098 Error *local_err = NULL;
1099 SnapshotInfo *info = NULL;
1100 int ret;
1102 if (!bs) {
1103 error_set(errp, QERR_DEVICE_NOT_FOUND, device);
1104 return NULL;
1107 if (!has_id) {
1108 id = NULL;
1111 if (!has_name) {
1112 name = NULL;
1115 if (!id && !name) {
1116 error_setg(errp, "Name or id must be provided");
1117 return NULL;
1120 aio_context = bdrv_get_aio_context(bs);
1121 aio_context_acquire(aio_context);
1123 if (bdrv_op_is_blocked(bs, BLOCK_OP_TYPE_INTERNAL_SNAPSHOT_DELETE, errp)) {
1124 goto out_aio_context;
1127 ret = bdrv_snapshot_find_by_id_and_name(bs, id, name, &sn, &local_err);
1128 if (local_err) {
1129 error_propagate(errp, local_err);
1130 goto out_aio_context;
1132 if (!ret) {
1133 error_setg(errp,
1134 "Snapshot with id '%s' and name '%s' does not exist on "
1135 "device '%s'",
1136 STR_OR_NULL(id), STR_OR_NULL(name), device);
1137 goto out_aio_context;
1140 bdrv_snapshot_delete(bs, id, name, &local_err);
1141 if (local_err) {
1142 error_propagate(errp, local_err);
1143 goto out_aio_context;
1146 aio_context_release(aio_context);
1148 info = g_new0(SnapshotInfo, 1);
1149 info->id = g_strdup(sn.id_str);
1150 info->name = g_strdup(sn.name);
1151 info->date_nsec = sn.date_nsec;
1152 info->date_sec = sn.date_sec;
1153 info->vm_state_size = sn.vm_state_size;
1154 info->vm_clock_nsec = sn.vm_clock_nsec % 1000000000;
1155 info->vm_clock_sec = sn.vm_clock_nsec / 1000000000;
1157 return info;
1159 out_aio_context:
1160 aio_context_release(aio_context);
1161 return NULL;
1164 /* New and old BlockDriverState structs for atomic group operations */
1166 typedef struct BlkTransactionState BlkTransactionState;
1168 /* Only prepare() may fail. In a single transaction, only one of commit() or
1169 abort() will be called, clean() will always be called if it present. */
1170 typedef struct BdrvActionOps {
1171 /* Size of state struct, in bytes. */
1172 size_t instance_size;
1173 /* Prepare the work, must NOT be NULL. */
1174 void (*prepare)(BlkTransactionState *common, Error **errp);
1175 /* Commit the changes, can be NULL. */
1176 void (*commit)(BlkTransactionState *common);
1177 /* Abort the changes on fail, can be NULL. */
1178 void (*abort)(BlkTransactionState *common);
1179 /* Clean up resource in the end, can be NULL. */
1180 void (*clean)(BlkTransactionState *common);
1181 } BdrvActionOps;
1184 * This structure must be arranged as first member in child type, assuming
1185 * that compiler will also arrange it to the same address with parent instance.
1186 * Later it will be used in free().
1188 struct BlkTransactionState {
1189 TransactionAction *action;
1190 const BdrvActionOps *ops;
1191 QSIMPLEQ_ENTRY(BlkTransactionState) entry;
1194 /* internal snapshot private data */
1195 typedef struct InternalSnapshotState {
1196 BlkTransactionState common;
1197 BlockDriverState *bs;
1198 AioContext *aio_context;
1199 QEMUSnapshotInfo sn;
1200 } InternalSnapshotState;
1202 static void internal_snapshot_prepare(BlkTransactionState *common,
1203 Error **errp)
1205 Error *local_err = NULL;
1206 const char *device;
1207 const char *name;
1208 BlockDriverState *bs;
1209 QEMUSnapshotInfo old_sn, *sn;
1210 bool ret;
1211 qemu_timeval tv;
1212 BlockdevSnapshotInternal *internal;
1213 InternalSnapshotState *state;
1214 int ret1;
1216 g_assert(common->action->kind ==
1217 TRANSACTION_ACTION_KIND_BLOCKDEV_SNAPSHOT_INTERNAL_SYNC);
1218 internal = common->action->blockdev_snapshot_internal_sync;
1219 state = DO_UPCAST(InternalSnapshotState, common, common);
1221 /* 1. parse input */
1222 device = internal->device;
1223 name = internal->name;
1225 /* 2. check for validation */
1226 bs = bdrv_find(device);
1227 if (!bs) {
1228 error_set(errp, QERR_DEVICE_NOT_FOUND, device);
1229 return;
1232 /* AioContext is released in .clean() */
1233 state->aio_context = bdrv_get_aio_context(bs);
1234 aio_context_acquire(state->aio_context);
1236 if (!bdrv_is_inserted(bs)) {
1237 error_set(errp, QERR_DEVICE_HAS_NO_MEDIUM, device);
1238 return;
1241 if (bdrv_op_is_blocked(bs, BLOCK_OP_TYPE_INTERNAL_SNAPSHOT, errp)) {
1242 return;
1245 if (bdrv_is_read_only(bs)) {
1246 error_set(errp, QERR_DEVICE_IS_READ_ONLY, device);
1247 return;
1250 if (!bdrv_can_snapshot(bs)) {
1251 error_set(errp, QERR_BLOCK_FORMAT_FEATURE_NOT_SUPPORTED,
1252 bs->drv->format_name, device, "internal snapshot");
1253 return;
1256 if (!strlen(name)) {
1257 error_setg(errp, "Name is empty");
1258 return;
1261 /* check whether a snapshot with name exist */
1262 ret = bdrv_snapshot_find_by_id_and_name(bs, NULL, name, &old_sn,
1263 &local_err);
1264 if (local_err) {
1265 error_propagate(errp, local_err);
1266 return;
1267 } else if (ret) {
1268 error_setg(errp,
1269 "Snapshot with name '%s' already exists on device '%s'",
1270 name, device);
1271 return;
1274 /* 3. take the snapshot */
1275 sn = &state->sn;
1276 pstrcpy(sn->name, sizeof(sn->name), name);
1277 qemu_gettimeofday(&tv);
1278 sn->date_sec = tv.tv_sec;
1279 sn->date_nsec = tv.tv_usec * 1000;
1280 sn->vm_clock_nsec = qemu_clock_get_ns(QEMU_CLOCK_VIRTUAL);
1282 ret1 = bdrv_snapshot_create(bs, sn);
1283 if (ret1 < 0) {
1284 error_setg_errno(errp, -ret1,
1285 "Failed to create snapshot '%s' on device '%s'",
1286 name, device);
1287 return;
1290 /* 4. succeed, mark a snapshot is created */
1291 state->bs = bs;
1294 static void internal_snapshot_abort(BlkTransactionState *common)
1296 InternalSnapshotState *state =
1297 DO_UPCAST(InternalSnapshotState, common, common);
1298 BlockDriverState *bs = state->bs;
1299 QEMUSnapshotInfo *sn = &state->sn;
1300 Error *local_error = NULL;
1302 if (!bs) {
1303 return;
1306 if (bdrv_snapshot_delete(bs, sn->id_str, sn->name, &local_error) < 0) {
1307 error_report("Failed to delete snapshot with id '%s' and name '%s' on "
1308 "device '%s' in abort: %s",
1309 sn->id_str,
1310 sn->name,
1311 bdrv_get_device_name(bs),
1312 error_get_pretty(local_error));
1313 error_free(local_error);
1317 static void internal_snapshot_clean(BlkTransactionState *common)
1319 InternalSnapshotState *state = DO_UPCAST(InternalSnapshotState,
1320 common, common);
1322 if (state->aio_context) {
1323 aio_context_release(state->aio_context);
1327 /* external snapshot private data */
1328 typedef struct ExternalSnapshotState {
1329 BlkTransactionState common;
1330 BlockDriverState *old_bs;
1331 BlockDriverState *new_bs;
1332 AioContext *aio_context;
1333 } ExternalSnapshotState;
1335 static void external_snapshot_prepare(BlkTransactionState *common,
1336 Error **errp)
1338 BlockDriver *drv;
1339 int flags, ret;
1340 QDict *options = NULL;
1341 Error *local_err = NULL;
1342 bool has_device = false;
1343 const char *device;
1344 bool has_node_name = false;
1345 const char *node_name;
1346 bool has_snapshot_node_name = false;
1347 const char *snapshot_node_name;
1348 const char *new_image_file;
1349 const char *format = "qcow2";
1350 enum NewImageMode mode = NEW_IMAGE_MODE_ABSOLUTE_PATHS;
1351 ExternalSnapshotState *state =
1352 DO_UPCAST(ExternalSnapshotState, common, common);
1353 TransactionAction *action = common->action;
1355 /* get parameters */
1356 g_assert(action->kind == TRANSACTION_ACTION_KIND_BLOCKDEV_SNAPSHOT_SYNC);
1358 has_device = action->blockdev_snapshot_sync->has_device;
1359 device = action->blockdev_snapshot_sync->device;
1360 has_node_name = action->blockdev_snapshot_sync->has_node_name;
1361 node_name = action->blockdev_snapshot_sync->node_name;
1362 has_snapshot_node_name =
1363 action->blockdev_snapshot_sync->has_snapshot_node_name;
1364 snapshot_node_name = action->blockdev_snapshot_sync->snapshot_node_name;
1366 new_image_file = action->blockdev_snapshot_sync->snapshot_file;
1367 if (action->blockdev_snapshot_sync->has_format) {
1368 format = action->blockdev_snapshot_sync->format;
1370 if (action->blockdev_snapshot_sync->has_mode) {
1371 mode = action->blockdev_snapshot_sync->mode;
1374 /* start processing */
1375 drv = bdrv_find_format(format);
1376 if (!drv) {
1377 error_set(errp, QERR_INVALID_BLOCK_FORMAT, format);
1378 return;
1381 state->old_bs = bdrv_lookup_bs(has_device ? device : NULL,
1382 has_node_name ? node_name : NULL,
1383 &local_err);
1384 if (local_err) {
1385 error_propagate(errp, local_err);
1386 return;
1389 if (has_node_name && !has_snapshot_node_name) {
1390 error_setg(errp, "New snapshot node name missing");
1391 return;
1394 if (has_snapshot_node_name && bdrv_find_node(snapshot_node_name)) {
1395 error_setg(errp, "New snapshot node name already existing");
1396 return;
1399 /* Acquire AioContext now so any threads operating on old_bs stop */
1400 state->aio_context = bdrv_get_aio_context(state->old_bs);
1401 aio_context_acquire(state->aio_context);
1403 if (!bdrv_is_inserted(state->old_bs)) {
1404 error_set(errp, QERR_DEVICE_HAS_NO_MEDIUM, device);
1405 return;
1408 if (bdrv_op_is_blocked(state->old_bs,
1409 BLOCK_OP_TYPE_EXTERNAL_SNAPSHOT, errp)) {
1410 return;
1413 if (!bdrv_is_read_only(state->old_bs)) {
1414 if (bdrv_flush(state->old_bs)) {
1415 error_set(errp, QERR_IO_ERROR);
1416 return;
1420 if (!bdrv_is_first_non_filter(state->old_bs)) {
1421 error_set(errp, QERR_FEATURE_DISABLED, "snapshot");
1422 return;
1425 flags = state->old_bs->open_flags;
1427 /* create new image w/backing file */
1428 if (mode != NEW_IMAGE_MODE_EXISTING) {
1429 bdrv_img_create(new_image_file, format,
1430 state->old_bs->filename,
1431 state->old_bs->drv->format_name,
1432 NULL, -1, flags, &local_err, false);
1433 if (local_err) {
1434 error_propagate(errp, local_err);
1435 return;
1439 if (has_snapshot_node_name) {
1440 options = qdict_new();
1441 qdict_put(options, "node-name",
1442 qstring_from_str(snapshot_node_name));
1445 /* TODO Inherit bs->options or only take explicit options with an
1446 * extended QMP command? */
1447 assert(state->new_bs == NULL);
1448 ret = bdrv_open(&state->new_bs, new_image_file, NULL, options,
1449 flags | BDRV_O_NO_BACKING, drv, &local_err);
1450 /* We will manually add the backing_hd field to the bs later */
1451 if (ret != 0) {
1452 error_propagate(errp, local_err);
1456 static void external_snapshot_commit(BlkTransactionState *common)
1458 ExternalSnapshotState *state =
1459 DO_UPCAST(ExternalSnapshotState, common, common);
1461 bdrv_set_aio_context(state->new_bs, state->aio_context);
1463 /* This removes our old bs and adds the new bs */
1464 bdrv_append(state->new_bs, state->old_bs);
1465 /* We don't need (or want) to use the transactional
1466 * bdrv_reopen_multiple() across all the entries at once, because we
1467 * don't want to abort all of them if one of them fails the reopen */
1468 bdrv_reopen(state->new_bs, state->new_bs->open_flags & ~BDRV_O_RDWR,
1469 NULL);
1471 aio_context_release(state->aio_context);
1474 static void external_snapshot_abort(BlkTransactionState *common)
1476 ExternalSnapshotState *state =
1477 DO_UPCAST(ExternalSnapshotState, common, common);
1478 if (state->new_bs) {
1479 bdrv_unref(state->new_bs);
1481 if (state->aio_context) {
1482 aio_context_release(state->aio_context);
1486 typedef struct DriveBackupState {
1487 BlkTransactionState common;
1488 BlockDriverState *bs;
1489 AioContext *aio_context;
1490 BlockJob *job;
1491 } DriveBackupState;
1493 static void drive_backup_prepare(BlkTransactionState *common, Error **errp)
1495 DriveBackupState *state = DO_UPCAST(DriveBackupState, common, common);
1496 BlockDriverState *bs;
1497 DriveBackup *backup;
1498 Error *local_err = NULL;
1500 assert(common->action->kind == TRANSACTION_ACTION_KIND_DRIVE_BACKUP);
1501 backup = common->action->drive_backup;
1503 bs = bdrv_find(backup->device);
1504 if (!bs) {
1505 error_set(errp, QERR_DEVICE_NOT_FOUND, backup->device);
1506 return;
1509 /* AioContext is released in .clean() */
1510 state->aio_context = bdrv_get_aio_context(bs);
1511 aio_context_acquire(state->aio_context);
1513 qmp_drive_backup(backup->device, backup->target,
1514 backup->has_format, backup->format,
1515 backup->sync,
1516 backup->has_mode, backup->mode,
1517 backup->has_speed, backup->speed,
1518 backup->has_on_source_error, backup->on_source_error,
1519 backup->has_on_target_error, backup->on_target_error,
1520 &local_err);
1521 if (local_err) {
1522 error_propagate(errp, local_err);
1523 return;
1526 state->bs = bs;
1527 state->job = state->bs->job;
1530 static void drive_backup_abort(BlkTransactionState *common)
1532 DriveBackupState *state = DO_UPCAST(DriveBackupState, common, common);
1533 BlockDriverState *bs = state->bs;
1535 /* Only cancel if it's the job we started */
1536 if (bs && bs->job && bs->job == state->job) {
1537 block_job_cancel_sync(bs->job);
1541 static void drive_backup_clean(BlkTransactionState *common)
1543 DriveBackupState *state = DO_UPCAST(DriveBackupState, common, common);
1545 if (state->aio_context) {
1546 aio_context_release(state->aio_context);
1550 typedef struct BlockdevBackupState {
1551 BlkTransactionState common;
1552 BlockDriverState *bs;
1553 BlockJob *job;
1554 AioContext *aio_context;
1555 } BlockdevBackupState;
1557 static void blockdev_backup_prepare(BlkTransactionState *common, Error **errp)
1559 BlockdevBackupState *state = DO_UPCAST(BlockdevBackupState, common, common);
1560 BlockdevBackup *backup;
1561 BlockDriverState *bs, *target;
1562 Error *local_err = NULL;
1564 assert(common->action->kind == TRANSACTION_ACTION_KIND_BLOCKDEV_BACKUP);
1565 backup = common->action->blockdev_backup;
1567 bs = bdrv_find(backup->device);
1568 if (!bs) {
1569 error_set(errp, QERR_DEVICE_NOT_FOUND, backup->device);
1570 return;
1573 target = bdrv_find(backup->target);
1574 if (!target) {
1575 error_set(errp, QERR_DEVICE_NOT_FOUND, backup->target);
1576 return;
1579 /* AioContext is released in .clean() */
1580 state->aio_context = bdrv_get_aio_context(bs);
1581 if (state->aio_context != bdrv_get_aio_context(target)) {
1582 state->aio_context = NULL;
1583 error_setg(errp, "Backup between two IO threads is not implemented");
1584 return;
1586 aio_context_acquire(state->aio_context);
1588 qmp_blockdev_backup(backup->device, backup->target,
1589 backup->sync,
1590 backup->has_speed, backup->speed,
1591 backup->has_on_source_error, backup->on_source_error,
1592 backup->has_on_target_error, backup->on_target_error,
1593 &local_err);
1594 if (local_err) {
1595 error_propagate(errp, local_err);
1596 return;
1599 state->bs = bs;
1600 state->job = state->bs->job;
1603 static void blockdev_backup_abort(BlkTransactionState *common)
1605 BlockdevBackupState *state = DO_UPCAST(BlockdevBackupState, common, common);
1606 BlockDriverState *bs = state->bs;
1608 /* Only cancel if it's the job we started */
1609 if (bs && bs->job && bs->job == state->job) {
1610 block_job_cancel_sync(bs->job);
1614 static void blockdev_backup_clean(BlkTransactionState *common)
1616 BlockdevBackupState *state = DO_UPCAST(BlockdevBackupState, common, common);
1618 if (state->aio_context) {
1619 aio_context_release(state->aio_context);
1623 static void abort_prepare(BlkTransactionState *common, Error **errp)
1625 error_setg(errp, "Transaction aborted using Abort action");
1628 static void abort_commit(BlkTransactionState *common)
1630 g_assert_not_reached(); /* this action never succeeds */
1633 static const BdrvActionOps actions[] = {
1634 [TRANSACTION_ACTION_KIND_BLOCKDEV_SNAPSHOT_SYNC] = {
1635 .instance_size = sizeof(ExternalSnapshotState),
1636 .prepare = external_snapshot_prepare,
1637 .commit = external_snapshot_commit,
1638 .abort = external_snapshot_abort,
1640 [TRANSACTION_ACTION_KIND_DRIVE_BACKUP] = {
1641 .instance_size = sizeof(DriveBackupState),
1642 .prepare = drive_backup_prepare,
1643 .abort = drive_backup_abort,
1644 .clean = drive_backup_clean,
1646 [TRANSACTION_ACTION_KIND_BLOCKDEV_BACKUP] = {
1647 .instance_size = sizeof(BlockdevBackupState),
1648 .prepare = blockdev_backup_prepare,
1649 .abort = blockdev_backup_abort,
1650 .clean = blockdev_backup_clean,
1652 [TRANSACTION_ACTION_KIND_ABORT] = {
1653 .instance_size = sizeof(BlkTransactionState),
1654 .prepare = abort_prepare,
1655 .commit = abort_commit,
1657 [TRANSACTION_ACTION_KIND_BLOCKDEV_SNAPSHOT_INTERNAL_SYNC] = {
1658 .instance_size = sizeof(InternalSnapshotState),
1659 .prepare = internal_snapshot_prepare,
1660 .abort = internal_snapshot_abort,
1661 .clean = internal_snapshot_clean,
1666 * 'Atomic' group operations. The operations are performed as a set, and if
1667 * any fail then we roll back all operations in the group.
1669 void qmp_transaction(TransactionActionList *dev_list, Error **errp)
1671 TransactionActionList *dev_entry = dev_list;
1672 BlkTransactionState *state, *next;
1673 Error *local_err = NULL;
1675 QSIMPLEQ_HEAD(snap_bdrv_states, BlkTransactionState) snap_bdrv_states;
1676 QSIMPLEQ_INIT(&snap_bdrv_states);
1678 /* drain all i/o before any operations */
1679 bdrv_drain_all();
1681 /* We don't do anything in this loop that commits us to the operations */
1682 while (NULL != dev_entry) {
1683 TransactionAction *dev_info = NULL;
1684 const BdrvActionOps *ops;
1686 dev_info = dev_entry->value;
1687 dev_entry = dev_entry->next;
1689 assert(dev_info->kind < ARRAY_SIZE(actions));
1691 ops = &actions[dev_info->kind];
1692 assert(ops->instance_size > 0);
1694 state = g_malloc0(ops->instance_size);
1695 state->ops = ops;
1696 state->action = dev_info;
1697 QSIMPLEQ_INSERT_TAIL(&snap_bdrv_states, state, entry);
1699 state->ops->prepare(state, &local_err);
1700 if (local_err) {
1701 error_propagate(errp, local_err);
1702 goto delete_and_fail;
1706 QSIMPLEQ_FOREACH(state, &snap_bdrv_states, entry) {
1707 if (state->ops->commit) {
1708 state->ops->commit(state);
1712 /* success */
1713 goto exit;
1715 delete_and_fail:
1716 /* failure, and it is all-or-none; roll back all operations */
1717 QSIMPLEQ_FOREACH(state, &snap_bdrv_states, entry) {
1718 if (state->ops->abort) {
1719 state->ops->abort(state);
1722 exit:
1723 QSIMPLEQ_FOREACH_SAFE(state, &snap_bdrv_states, entry, next) {
1724 if (state->ops->clean) {
1725 state->ops->clean(state);
1727 g_free(state);
1732 static void eject_device(BlockBackend *blk, int force, Error **errp)
1734 BlockDriverState *bs = blk_bs(blk);
1735 AioContext *aio_context;
1737 aio_context = bdrv_get_aio_context(bs);
1738 aio_context_acquire(aio_context);
1740 if (bdrv_op_is_blocked(bs, BLOCK_OP_TYPE_EJECT, errp)) {
1741 goto out;
1743 if (!blk_dev_has_removable_media(blk)) {
1744 error_setg(errp, "Device '%s' is not removable",
1745 bdrv_get_device_name(bs));
1746 goto out;
1749 if (blk_dev_is_medium_locked(blk) && !blk_dev_is_tray_open(blk)) {
1750 blk_dev_eject_request(blk, force);
1751 if (!force) {
1752 error_setg(errp, "Device '%s' is locked",
1753 bdrv_get_device_name(bs));
1754 goto out;
1758 bdrv_close(bs);
1760 out:
1761 aio_context_release(aio_context);
1764 void qmp_eject(const char *device, bool has_force, bool force, Error **errp)
1766 BlockBackend *blk;
1768 blk = blk_by_name(device);
1769 if (!blk) {
1770 error_set(errp, QERR_DEVICE_NOT_FOUND, device);
1771 return;
1774 eject_device(blk, force, errp);
1777 void qmp_block_passwd(bool has_device, const char *device,
1778 bool has_node_name, const char *node_name,
1779 const char *password, Error **errp)
1781 Error *local_err = NULL;
1782 BlockDriverState *bs;
1783 AioContext *aio_context;
1785 bs = bdrv_lookup_bs(has_device ? device : NULL,
1786 has_node_name ? node_name : NULL,
1787 &local_err);
1788 if (local_err) {
1789 error_propagate(errp, local_err);
1790 return;
1793 aio_context = bdrv_get_aio_context(bs);
1794 aio_context_acquire(aio_context);
1796 bdrv_add_key(bs, password, errp);
1798 aio_context_release(aio_context);
1801 /* Assumes AioContext is held */
1802 static void qmp_bdrv_open_encrypted(BlockDriverState *bs, const char *filename,
1803 int bdrv_flags, BlockDriver *drv,
1804 const char *password, Error **errp)
1806 Error *local_err = NULL;
1807 int ret;
1809 ret = bdrv_open(&bs, filename, NULL, NULL, bdrv_flags, drv, &local_err);
1810 if (ret < 0) {
1811 error_propagate(errp, local_err);
1812 return;
1815 bdrv_add_key(bs, password, errp);
1818 void qmp_change_blockdev(const char *device, const char *filename,
1819 const char *format, Error **errp)
1821 BlockBackend *blk;
1822 BlockDriverState *bs;
1823 AioContext *aio_context;
1824 BlockDriver *drv = NULL;
1825 int bdrv_flags;
1826 Error *err = NULL;
1828 blk = blk_by_name(device);
1829 if (!blk) {
1830 error_set(errp, QERR_DEVICE_NOT_FOUND, device);
1831 return;
1833 bs = blk_bs(blk);
1835 aio_context = bdrv_get_aio_context(bs);
1836 aio_context_acquire(aio_context);
1838 if (format) {
1839 drv = bdrv_find_whitelisted_format(format, bs->read_only);
1840 if (!drv) {
1841 error_set(errp, QERR_INVALID_BLOCK_FORMAT, format);
1842 goto out;
1846 eject_device(blk, 0, &err);
1847 if (err) {
1848 error_propagate(errp, err);
1849 goto out;
1852 bdrv_flags = bdrv_is_read_only(bs) ? 0 : BDRV_O_RDWR;
1853 bdrv_flags |= bdrv_is_snapshot(bs) ? BDRV_O_SNAPSHOT : 0;
1855 qmp_bdrv_open_encrypted(bs, filename, bdrv_flags, drv, NULL, errp);
1857 out:
1858 aio_context_release(aio_context);
1861 /* throttling disk I/O limits */
1862 void qmp_block_set_io_throttle(const char *device, int64_t bps, int64_t bps_rd,
1863 int64_t bps_wr,
1864 int64_t iops,
1865 int64_t iops_rd,
1866 int64_t iops_wr,
1867 bool has_bps_max,
1868 int64_t bps_max,
1869 bool has_bps_rd_max,
1870 int64_t bps_rd_max,
1871 bool has_bps_wr_max,
1872 int64_t bps_wr_max,
1873 bool has_iops_max,
1874 int64_t iops_max,
1875 bool has_iops_rd_max,
1876 int64_t iops_rd_max,
1877 bool has_iops_wr_max,
1878 int64_t iops_wr_max,
1879 bool has_iops_size,
1880 int64_t iops_size, Error **errp)
1882 ThrottleConfig cfg;
1883 BlockDriverState *bs;
1884 AioContext *aio_context;
1886 bs = bdrv_find(device);
1887 if (!bs) {
1888 error_set(errp, QERR_DEVICE_NOT_FOUND, device);
1889 return;
1892 memset(&cfg, 0, sizeof(cfg));
1893 cfg.buckets[THROTTLE_BPS_TOTAL].avg = bps;
1894 cfg.buckets[THROTTLE_BPS_READ].avg = bps_rd;
1895 cfg.buckets[THROTTLE_BPS_WRITE].avg = bps_wr;
1897 cfg.buckets[THROTTLE_OPS_TOTAL].avg = iops;
1898 cfg.buckets[THROTTLE_OPS_READ].avg = iops_rd;
1899 cfg.buckets[THROTTLE_OPS_WRITE].avg = iops_wr;
1901 if (has_bps_max) {
1902 cfg.buckets[THROTTLE_BPS_TOTAL].max = bps_max;
1904 if (has_bps_rd_max) {
1905 cfg.buckets[THROTTLE_BPS_READ].max = bps_rd_max;
1907 if (has_bps_wr_max) {
1908 cfg.buckets[THROTTLE_BPS_WRITE].max = bps_wr_max;
1910 if (has_iops_max) {
1911 cfg.buckets[THROTTLE_OPS_TOTAL].max = iops_max;
1913 if (has_iops_rd_max) {
1914 cfg.buckets[THROTTLE_OPS_READ].max = iops_rd_max;
1916 if (has_iops_wr_max) {
1917 cfg.buckets[THROTTLE_OPS_WRITE].max = iops_wr_max;
1920 if (has_iops_size) {
1921 cfg.op_size = iops_size;
1924 if (!check_throttle_config(&cfg, errp)) {
1925 return;
1928 aio_context = bdrv_get_aio_context(bs);
1929 aio_context_acquire(aio_context);
1931 if (!bs->io_limits_enabled && throttle_enabled(&cfg)) {
1932 bdrv_io_limits_enable(bs);
1933 } else if (bs->io_limits_enabled && !throttle_enabled(&cfg)) {
1934 bdrv_io_limits_disable(bs);
1937 if (bs->io_limits_enabled) {
1938 bdrv_set_io_limits(bs, &cfg);
1941 aio_context_release(aio_context);
1944 int hmp_drive_del(Monitor *mon, const QDict *qdict, QObject **ret_data)
1946 const char *id = qdict_get_str(qdict, "id");
1947 BlockBackend *blk;
1948 BlockDriverState *bs;
1949 AioContext *aio_context;
1950 Error *local_err = NULL;
1952 blk = blk_by_name(id);
1953 if (!blk) {
1954 error_report("Device '%s' not found", id);
1955 return -1;
1957 bs = blk_bs(blk);
1959 if (!blk_legacy_dinfo(blk)) {
1960 error_report("Deleting device added with blockdev-add"
1961 " is not supported");
1962 return -1;
1965 aio_context = bdrv_get_aio_context(bs);
1966 aio_context_acquire(aio_context);
1968 if (bdrv_op_is_blocked(bs, BLOCK_OP_TYPE_DRIVE_DEL, &local_err)) {
1969 error_report_err(local_err);
1970 aio_context_release(aio_context);
1971 return -1;
1974 /* quiesce block driver; prevent further io */
1975 bdrv_drain_all();
1976 bdrv_flush(bs);
1977 bdrv_close(bs);
1979 /* if we have a device attached to this BlockDriverState
1980 * then we need to make the drive anonymous until the device
1981 * can be removed. If this is a drive with no device backing
1982 * then we can just get rid of the block driver state right here.
1984 if (blk_get_attached_dev(blk)) {
1985 blk_hide_on_behalf_of_hmp_drive_del(blk);
1986 /* Further I/O must not pause the guest */
1987 bdrv_set_on_error(bs, BLOCKDEV_ON_ERROR_REPORT,
1988 BLOCKDEV_ON_ERROR_REPORT);
1989 } else {
1990 blk_unref(blk);
1993 aio_context_release(aio_context);
1994 return 0;
1997 void qmp_block_resize(bool has_device, const char *device,
1998 bool has_node_name, const char *node_name,
1999 int64_t size, Error **errp)
2001 Error *local_err = NULL;
2002 BlockDriverState *bs;
2003 AioContext *aio_context;
2004 int ret;
2006 bs = bdrv_lookup_bs(has_device ? device : NULL,
2007 has_node_name ? node_name : NULL,
2008 &local_err);
2009 if (local_err) {
2010 error_propagate(errp, local_err);
2011 return;
2014 aio_context = bdrv_get_aio_context(bs);
2015 aio_context_acquire(aio_context);
2017 if (!bdrv_is_first_non_filter(bs)) {
2018 error_set(errp, QERR_FEATURE_DISABLED, "resize");
2019 goto out;
2022 if (size < 0) {
2023 error_set(errp, QERR_INVALID_PARAMETER_VALUE, "size", "a >0 size");
2024 goto out;
2027 if (bdrv_op_is_blocked(bs, BLOCK_OP_TYPE_RESIZE, NULL)) {
2028 error_set(errp, QERR_DEVICE_IN_USE, device);
2029 goto out;
2032 /* complete all in-flight operations before resizing the device */
2033 bdrv_drain_all();
2035 ret = bdrv_truncate(bs, size);
2036 switch (ret) {
2037 case 0:
2038 break;
2039 case -ENOMEDIUM:
2040 error_set(errp, QERR_DEVICE_HAS_NO_MEDIUM, device);
2041 break;
2042 case -ENOTSUP:
2043 error_set(errp, QERR_UNSUPPORTED);
2044 break;
2045 case -EACCES:
2046 error_set(errp, QERR_DEVICE_IS_READ_ONLY, device);
2047 break;
2048 case -EBUSY:
2049 error_set(errp, QERR_DEVICE_IN_USE, device);
2050 break;
2051 default:
2052 error_setg_errno(errp, -ret, "Could not resize");
2053 break;
2056 out:
2057 aio_context_release(aio_context);
2060 static void block_job_cb(void *opaque, int ret)
2062 /* Note that this function may be executed from another AioContext besides
2063 * the QEMU main loop. If you need to access anything that assumes the
2064 * QEMU global mutex, use a BH or introduce a mutex.
2067 BlockDriverState *bs = opaque;
2068 const char *msg = NULL;
2070 trace_block_job_cb(bs, bs->job, ret);
2072 assert(bs->job);
2074 if (ret < 0) {
2075 msg = strerror(-ret);
2078 if (block_job_is_cancelled(bs->job)) {
2079 block_job_event_cancelled(bs->job);
2080 } else {
2081 block_job_event_completed(bs->job, msg);
2084 bdrv_put_ref_bh_schedule(bs);
2087 void qmp_block_stream(const char *device,
2088 bool has_base, const char *base,
2089 bool has_backing_file, const char *backing_file,
2090 bool has_speed, int64_t speed,
2091 bool has_on_error, BlockdevOnError on_error,
2092 Error **errp)
2094 BlockDriverState *bs;
2095 BlockDriverState *base_bs = NULL;
2096 AioContext *aio_context;
2097 Error *local_err = NULL;
2098 const char *base_name = NULL;
2100 if (!has_on_error) {
2101 on_error = BLOCKDEV_ON_ERROR_REPORT;
2104 bs = bdrv_find(device);
2105 if (!bs) {
2106 error_set(errp, QERR_DEVICE_NOT_FOUND, device);
2107 return;
2110 aio_context = bdrv_get_aio_context(bs);
2111 aio_context_acquire(aio_context);
2113 if (bdrv_op_is_blocked(bs, BLOCK_OP_TYPE_STREAM, errp)) {
2114 goto out;
2117 if (has_base) {
2118 base_bs = bdrv_find_backing_image(bs, base);
2119 if (base_bs == NULL) {
2120 error_set(errp, QERR_BASE_NOT_FOUND, base);
2121 goto out;
2123 assert(bdrv_get_aio_context(base_bs) == aio_context);
2124 base_name = base;
2127 /* if we are streaming the entire chain, the result will have no backing
2128 * file, and specifying one is therefore an error */
2129 if (base_bs == NULL && has_backing_file) {
2130 error_setg(errp, "backing file specified, but streaming the "
2131 "entire chain");
2132 goto out;
2135 /* backing_file string overrides base bs filename */
2136 base_name = has_backing_file ? backing_file : base_name;
2138 stream_start(bs, base_bs, base_name, has_speed ? speed : 0,
2139 on_error, block_job_cb, bs, &local_err);
2140 if (local_err) {
2141 error_propagate(errp, local_err);
2142 goto out;
2145 trace_qmp_block_stream(bs, bs->job);
2147 out:
2148 aio_context_release(aio_context);
2151 void qmp_block_commit(const char *device,
2152 bool has_base, const char *base,
2153 bool has_top, const char *top,
2154 bool has_backing_file, const char *backing_file,
2155 bool has_speed, int64_t speed,
2156 Error **errp)
2158 BlockDriverState *bs;
2159 BlockDriverState *base_bs, *top_bs;
2160 AioContext *aio_context;
2161 Error *local_err = NULL;
2162 /* This will be part of the QMP command, if/when the
2163 * BlockdevOnError change for blkmirror makes it in
2165 BlockdevOnError on_error = BLOCKDEV_ON_ERROR_REPORT;
2167 if (!has_speed) {
2168 speed = 0;
2171 /* Important Note:
2172 * libvirt relies on the DeviceNotFound error class in order to probe for
2173 * live commit feature versions; for this to work, we must make sure to
2174 * perform the device lookup before any generic errors that may occur in a
2175 * scenario in which all optional arguments are omitted. */
2176 bs = bdrv_find(device);
2177 if (!bs) {
2178 error_set(errp, QERR_DEVICE_NOT_FOUND, device);
2179 return;
2182 aio_context = bdrv_get_aio_context(bs);
2183 aio_context_acquire(aio_context);
2185 /* drain all i/o before commits */
2186 bdrv_drain_all();
2188 if (bdrv_op_is_blocked(bs, BLOCK_OP_TYPE_COMMIT_SOURCE, errp)) {
2189 goto out;
2192 /* default top_bs is the active layer */
2193 top_bs = bs;
2195 if (has_top && top) {
2196 if (strcmp(bs->filename, top) != 0) {
2197 top_bs = bdrv_find_backing_image(bs, top);
2201 if (top_bs == NULL) {
2202 error_setg(errp, "Top image file %s not found", top ? top : "NULL");
2203 goto out;
2206 assert(bdrv_get_aio_context(top_bs) == aio_context);
2208 if (has_base && base) {
2209 base_bs = bdrv_find_backing_image(top_bs, base);
2210 } else {
2211 base_bs = bdrv_find_base(top_bs);
2214 if (base_bs == NULL) {
2215 error_set(errp, QERR_BASE_NOT_FOUND, base ? base : "NULL");
2216 goto out;
2219 assert(bdrv_get_aio_context(base_bs) == aio_context);
2221 if (bdrv_op_is_blocked(base_bs, BLOCK_OP_TYPE_COMMIT_TARGET, errp)) {
2222 goto out;
2225 /* Do not allow attempts to commit an image into itself */
2226 if (top_bs == base_bs) {
2227 error_setg(errp, "cannot commit an image into itself");
2228 goto out;
2231 if (top_bs == bs) {
2232 if (has_backing_file) {
2233 error_setg(errp, "'backing-file' specified,"
2234 " but 'top' is the active layer");
2235 goto out;
2237 commit_active_start(bs, base_bs, speed, on_error, block_job_cb,
2238 bs, &local_err);
2239 } else {
2240 commit_start(bs, base_bs, top_bs, speed, on_error, block_job_cb, bs,
2241 has_backing_file ? backing_file : NULL, &local_err);
2243 if (local_err != NULL) {
2244 error_propagate(errp, local_err);
2245 goto out;
2248 out:
2249 aio_context_release(aio_context);
2252 void qmp_drive_backup(const char *device, const char *target,
2253 bool has_format, const char *format,
2254 enum MirrorSyncMode sync,
2255 bool has_mode, enum NewImageMode mode,
2256 bool has_speed, int64_t speed,
2257 bool has_on_source_error, BlockdevOnError on_source_error,
2258 bool has_on_target_error, BlockdevOnError on_target_error,
2259 Error **errp)
2261 BlockDriverState *bs;
2262 BlockDriverState *target_bs;
2263 BlockDriverState *source = NULL;
2264 AioContext *aio_context;
2265 BlockDriver *drv = NULL;
2266 Error *local_err = NULL;
2267 int flags;
2268 int64_t size;
2269 int ret;
2271 if (!has_speed) {
2272 speed = 0;
2274 if (!has_on_source_error) {
2275 on_source_error = BLOCKDEV_ON_ERROR_REPORT;
2277 if (!has_on_target_error) {
2278 on_target_error = BLOCKDEV_ON_ERROR_REPORT;
2280 if (!has_mode) {
2281 mode = NEW_IMAGE_MODE_ABSOLUTE_PATHS;
2284 bs = bdrv_find(device);
2285 if (!bs) {
2286 error_set(errp, QERR_DEVICE_NOT_FOUND, device);
2287 return;
2290 aio_context = bdrv_get_aio_context(bs);
2291 aio_context_acquire(aio_context);
2293 /* Although backup_run has this check too, we need to use bs->drv below, so
2294 * do an early check redundantly. */
2295 if (!bdrv_is_inserted(bs)) {
2296 error_set(errp, QERR_DEVICE_HAS_NO_MEDIUM, device);
2297 goto out;
2300 if (!has_format) {
2301 format = mode == NEW_IMAGE_MODE_EXISTING ? NULL : bs->drv->format_name;
2303 if (format) {
2304 drv = bdrv_find_format(format);
2305 if (!drv) {
2306 error_set(errp, QERR_INVALID_BLOCK_FORMAT, format);
2307 goto out;
2311 /* Early check to avoid creating target */
2312 if (bdrv_op_is_blocked(bs, BLOCK_OP_TYPE_BACKUP_SOURCE, errp)) {
2313 goto out;
2316 flags = bs->open_flags | BDRV_O_RDWR;
2318 /* See if we have a backing HD we can use to create our new image
2319 * on top of. */
2320 if (sync == MIRROR_SYNC_MODE_TOP) {
2321 source = bs->backing_hd;
2322 if (!source) {
2323 sync = MIRROR_SYNC_MODE_FULL;
2326 if (sync == MIRROR_SYNC_MODE_NONE) {
2327 source = bs;
2330 size = bdrv_getlength(bs);
2331 if (size < 0) {
2332 error_setg_errno(errp, -size, "bdrv_getlength failed");
2333 goto out;
2336 if (mode != NEW_IMAGE_MODE_EXISTING) {
2337 assert(format && drv);
2338 if (source) {
2339 bdrv_img_create(target, format, source->filename,
2340 source->drv->format_name, NULL,
2341 size, flags, &local_err, false);
2342 } else {
2343 bdrv_img_create(target, format, NULL, NULL, NULL,
2344 size, flags, &local_err, false);
2348 if (local_err) {
2349 error_propagate(errp, local_err);
2350 goto out;
2353 target_bs = NULL;
2354 ret = bdrv_open(&target_bs, target, NULL, NULL, flags, drv, &local_err);
2355 if (ret < 0) {
2356 error_propagate(errp, local_err);
2357 goto out;
2360 bdrv_set_aio_context(target_bs, aio_context);
2362 backup_start(bs, target_bs, speed, sync, on_source_error, on_target_error,
2363 block_job_cb, bs, &local_err);
2364 if (local_err != NULL) {
2365 bdrv_unref(target_bs);
2366 error_propagate(errp, local_err);
2367 goto out;
2370 out:
2371 aio_context_release(aio_context);
2374 BlockDeviceInfoList *qmp_query_named_block_nodes(Error **errp)
2376 return bdrv_named_nodes_list();
2379 void qmp_blockdev_backup(const char *device, const char *target,
2380 enum MirrorSyncMode sync,
2381 bool has_speed, int64_t speed,
2382 bool has_on_source_error,
2383 BlockdevOnError on_source_error,
2384 bool has_on_target_error,
2385 BlockdevOnError on_target_error,
2386 Error **errp)
2388 BlockDriverState *bs;
2389 BlockDriverState *target_bs;
2390 Error *local_err = NULL;
2391 AioContext *aio_context;
2393 if (!has_speed) {
2394 speed = 0;
2396 if (!has_on_source_error) {
2397 on_source_error = BLOCKDEV_ON_ERROR_REPORT;
2399 if (!has_on_target_error) {
2400 on_target_error = BLOCKDEV_ON_ERROR_REPORT;
2403 bs = bdrv_find(device);
2404 if (!bs) {
2405 error_set(errp, QERR_DEVICE_NOT_FOUND, device);
2406 return;
2409 aio_context = bdrv_get_aio_context(bs);
2410 aio_context_acquire(aio_context);
2412 target_bs = bdrv_find(target);
2413 if (!target_bs) {
2414 error_set(errp, QERR_DEVICE_NOT_FOUND, target);
2415 goto out;
2418 bdrv_ref(target_bs);
2419 bdrv_set_aio_context(target_bs, aio_context);
2420 backup_start(bs, target_bs, speed, sync, on_source_error, on_target_error,
2421 block_job_cb, bs, &local_err);
2422 if (local_err != NULL) {
2423 bdrv_unref(target_bs);
2424 error_propagate(errp, local_err);
2426 out:
2427 aio_context_release(aio_context);
2430 #define DEFAULT_MIRROR_BUF_SIZE (10 << 20)
2432 void qmp_drive_mirror(const char *device, const char *target,
2433 bool has_format, const char *format,
2434 bool has_node_name, const char *node_name,
2435 bool has_replaces, const char *replaces,
2436 enum MirrorSyncMode sync,
2437 bool has_mode, enum NewImageMode mode,
2438 bool has_speed, int64_t speed,
2439 bool has_granularity, uint32_t granularity,
2440 bool has_buf_size, int64_t buf_size,
2441 bool has_on_source_error, BlockdevOnError on_source_error,
2442 bool has_on_target_error, BlockdevOnError on_target_error,
2443 Error **errp)
2445 BlockDriverState *bs;
2446 BlockDriverState *source, *target_bs;
2447 AioContext *aio_context;
2448 BlockDriver *drv = NULL;
2449 Error *local_err = NULL;
2450 QDict *options = NULL;
2451 int flags;
2452 int64_t size;
2453 int ret;
2455 if (!has_speed) {
2456 speed = 0;
2458 if (!has_on_source_error) {
2459 on_source_error = BLOCKDEV_ON_ERROR_REPORT;
2461 if (!has_on_target_error) {
2462 on_target_error = BLOCKDEV_ON_ERROR_REPORT;
2464 if (!has_mode) {
2465 mode = NEW_IMAGE_MODE_ABSOLUTE_PATHS;
2467 if (!has_granularity) {
2468 granularity = 0;
2470 if (!has_buf_size) {
2471 buf_size = DEFAULT_MIRROR_BUF_SIZE;
2474 if (granularity != 0 && (granularity < 512 || granularity > 1048576 * 64)) {
2475 error_set(errp, QERR_INVALID_PARAMETER_VALUE, "granularity",
2476 "a value in range [512B, 64MB]");
2477 return;
2479 if (granularity & (granularity - 1)) {
2480 error_set(errp, QERR_INVALID_PARAMETER_VALUE, "granularity", "power of 2");
2481 return;
2484 bs = bdrv_find(device);
2485 if (!bs) {
2486 error_set(errp, QERR_DEVICE_NOT_FOUND, device);
2487 return;
2490 aio_context = bdrv_get_aio_context(bs);
2491 aio_context_acquire(aio_context);
2493 if (!bdrv_is_inserted(bs)) {
2494 error_set(errp, QERR_DEVICE_HAS_NO_MEDIUM, device);
2495 goto out;
2498 if (!has_format) {
2499 format = mode == NEW_IMAGE_MODE_EXISTING ? NULL : bs->drv->format_name;
2501 if (format) {
2502 drv = bdrv_find_format(format);
2503 if (!drv) {
2504 error_set(errp, QERR_INVALID_BLOCK_FORMAT, format);
2505 goto out;
2509 if (bdrv_op_is_blocked(bs, BLOCK_OP_TYPE_MIRROR, errp)) {
2510 goto out;
2513 flags = bs->open_flags | BDRV_O_RDWR;
2514 source = bs->backing_hd;
2515 if (!source && sync == MIRROR_SYNC_MODE_TOP) {
2516 sync = MIRROR_SYNC_MODE_FULL;
2518 if (sync == MIRROR_SYNC_MODE_NONE) {
2519 source = bs;
2522 size = bdrv_getlength(bs);
2523 if (size < 0) {
2524 error_setg_errno(errp, -size, "bdrv_getlength failed");
2525 goto out;
2528 if (has_replaces) {
2529 BlockDriverState *to_replace_bs;
2530 AioContext *replace_aio_context;
2531 int64_t replace_size;
2533 if (!has_node_name) {
2534 error_setg(errp, "a node-name must be provided when replacing a"
2535 " named node of the graph");
2536 goto out;
2539 to_replace_bs = check_to_replace_node(replaces, &local_err);
2541 if (!to_replace_bs) {
2542 error_propagate(errp, local_err);
2543 goto out;
2546 replace_aio_context = bdrv_get_aio_context(to_replace_bs);
2547 aio_context_acquire(replace_aio_context);
2548 replace_size = bdrv_getlength(to_replace_bs);
2549 aio_context_release(replace_aio_context);
2551 if (size != replace_size) {
2552 error_setg(errp, "cannot replace image with a mirror image of "
2553 "different size");
2554 goto out;
2558 if ((sync == MIRROR_SYNC_MODE_FULL || !source)
2559 && mode != NEW_IMAGE_MODE_EXISTING)
2561 /* create new image w/o backing file */
2562 assert(format && drv);
2563 bdrv_img_create(target, format,
2564 NULL, NULL, NULL, size, flags, &local_err, false);
2565 } else {
2566 switch (mode) {
2567 case NEW_IMAGE_MODE_EXISTING:
2568 break;
2569 case NEW_IMAGE_MODE_ABSOLUTE_PATHS:
2570 /* create new image with backing file */
2571 bdrv_img_create(target, format,
2572 source->filename,
2573 source->drv->format_name,
2574 NULL, size, flags, &local_err, false);
2575 break;
2576 default:
2577 abort();
2581 if (local_err) {
2582 error_propagate(errp, local_err);
2583 goto out;
2586 if (has_node_name) {
2587 options = qdict_new();
2588 qdict_put(options, "node-name", qstring_from_str(node_name));
2591 /* Mirroring takes care of copy-on-write using the source's backing
2592 * file.
2594 target_bs = NULL;
2595 ret = bdrv_open(&target_bs, target, NULL, options,
2596 flags | BDRV_O_NO_BACKING, drv, &local_err);
2597 if (ret < 0) {
2598 error_propagate(errp, local_err);
2599 goto out;
2602 bdrv_set_aio_context(target_bs, aio_context);
2604 /* pass the node name to replace to mirror start since it's loose coupling
2605 * and will allow to check whether the node still exist at mirror completion
2607 mirror_start(bs, target_bs,
2608 has_replaces ? replaces : NULL,
2609 speed, granularity, buf_size, sync,
2610 on_source_error, on_target_error,
2611 block_job_cb, bs, &local_err);
2612 if (local_err != NULL) {
2613 bdrv_unref(target_bs);
2614 error_propagate(errp, local_err);
2615 goto out;
2618 out:
2619 aio_context_release(aio_context);
2622 /* Get the block job for a given device name and acquire its AioContext */
2623 static BlockJob *find_block_job(const char *device, AioContext **aio_context,
2624 Error **errp)
2626 BlockDriverState *bs;
2628 bs = bdrv_find(device);
2629 if (!bs) {
2630 goto notfound;
2633 *aio_context = bdrv_get_aio_context(bs);
2634 aio_context_acquire(*aio_context);
2636 if (!bs->job) {
2637 aio_context_release(*aio_context);
2638 goto notfound;
2641 return bs->job;
2643 notfound:
2644 error_set(errp, ERROR_CLASS_DEVICE_NOT_ACTIVE,
2645 "No active block job on device '%s'", device);
2646 *aio_context = NULL;
2647 return NULL;
2650 void qmp_block_job_set_speed(const char *device, int64_t speed, Error **errp)
2652 AioContext *aio_context;
2653 BlockJob *job = find_block_job(device, &aio_context, errp);
2655 if (!job) {
2656 return;
2659 block_job_set_speed(job, speed, errp);
2660 aio_context_release(aio_context);
2663 void qmp_block_job_cancel(const char *device,
2664 bool has_force, bool force, Error **errp)
2666 AioContext *aio_context;
2667 BlockJob *job = find_block_job(device, &aio_context, errp);
2669 if (!job) {
2670 return;
2673 if (!has_force) {
2674 force = false;
2677 if (job->paused && !force) {
2678 error_setg(errp, "The block job for device '%s' is currently paused",
2679 device);
2680 goto out;
2683 trace_qmp_block_job_cancel(job);
2684 block_job_cancel(job);
2685 out:
2686 aio_context_release(aio_context);
2689 void qmp_block_job_pause(const char *device, Error **errp)
2691 AioContext *aio_context;
2692 BlockJob *job = find_block_job(device, &aio_context, errp);
2694 if (!job) {
2695 return;
2698 trace_qmp_block_job_pause(job);
2699 block_job_pause(job);
2700 aio_context_release(aio_context);
2703 void qmp_block_job_resume(const char *device, Error **errp)
2705 AioContext *aio_context;
2706 BlockJob *job = find_block_job(device, &aio_context, errp);
2708 if (!job) {
2709 return;
2712 trace_qmp_block_job_resume(job);
2713 block_job_resume(job);
2714 aio_context_release(aio_context);
2717 void qmp_block_job_complete(const char *device, Error **errp)
2719 AioContext *aio_context;
2720 BlockJob *job = find_block_job(device, &aio_context, errp);
2722 if (!job) {
2723 return;
2726 trace_qmp_block_job_complete(job);
2727 block_job_complete(job, errp);
2728 aio_context_release(aio_context);
2731 void qmp_change_backing_file(const char *device,
2732 const char *image_node_name,
2733 const char *backing_file,
2734 Error **errp)
2736 BlockDriverState *bs = NULL;
2737 AioContext *aio_context;
2738 BlockDriverState *image_bs = NULL;
2739 Error *local_err = NULL;
2740 bool ro;
2741 int open_flags;
2742 int ret;
2744 /* find the top layer BDS of the chain */
2745 bs = bdrv_find(device);
2746 if (!bs) {
2747 error_set(errp, QERR_DEVICE_NOT_FOUND, device);
2748 return;
2751 aio_context = bdrv_get_aio_context(bs);
2752 aio_context_acquire(aio_context);
2754 image_bs = bdrv_lookup_bs(NULL, image_node_name, &local_err);
2755 if (local_err) {
2756 error_propagate(errp, local_err);
2757 goto out;
2760 if (!image_bs) {
2761 error_setg(errp, "image file not found");
2762 goto out;
2765 if (bdrv_find_base(image_bs) == image_bs) {
2766 error_setg(errp, "not allowing backing file change on an image "
2767 "without a backing file");
2768 goto out;
2771 /* even though we are not necessarily operating on bs, we need it to
2772 * determine if block ops are currently prohibited on the chain */
2773 if (bdrv_op_is_blocked(bs, BLOCK_OP_TYPE_CHANGE, errp)) {
2774 goto out;
2777 /* final sanity check */
2778 if (!bdrv_chain_contains(bs, image_bs)) {
2779 error_setg(errp, "'%s' and image file are not in the same chain",
2780 device);
2781 goto out;
2784 /* if not r/w, reopen to make r/w */
2785 open_flags = image_bs->open_flags;
2786 ro = bdrv_is_read_only(image_bs);
2788 if (ro) {
2789 bdrv_reopen(image_bs, open_flags | BDRV_O_RDWR, &local_err);
2790 if (local_err) {
2791 error_propagate(errp, local_err);
2792 goto out;
2796 ret = bdrv_change_backing_file(image_bs, backing_file,
2797 image_bs->drv ? image_bs->drv->format_name : "");
2799 if (ret < 0) {
2800 error_setg_errno(errp, -ret, "Could not change backing file to '%s'",
2801 backing_file);
2802 /* don't exit here, so we can try to restore open flags if
2803 * appropriate */
2806 if (ro) {
2807 bdrv_reopen(image_bs, open_flags, &local_err);
2808 if (local_err) {
2809 error_propagate(errp, local_err); /* will preserve prior errp */
2813 out:
2814 aio_context_release(aio_context);
2817 void qmp_blockdev_add(BlockdevOptions *options, Error **errp)
2819 QmpOutputVisitor *ov = qmp_output_visitor_new();
2820 BlockBackend *blk;
2821 QObject *obj;
2822 QDict *qdict;
2823 Error *local_err = NULL;
2825 /* Require an ID in the top level */
2826 if (!options->has_id) {
2827 error_setg(errp, "Block device needs an ID");
2828 goto fail;
2831 /* TODO Sort it out in raw-posix and drive_new(): Reject aio=native with
2832 * cache.direct=false instead of silently switching to aio=threads, except
2833 * when called from drive_new().
2835 * For now, simply forbidding the combination for all drivers will do. */
2836 if (options->has_aio && options->aio == BLOCKDEV_AIO_OPTIONS_NATIVE) {
2837 bool direct = options->has_cache &&
2838 options->cache->has_direct &&
2839 options->cache->direct;
2840 if (!direct) {
2841 error_setg(errp, "aio=native requires cache.direct=true");
2842 goto fail;
2846 visit_type_BlockdevOptions(qmp_output_get_visitor(ov),
2847 &options, NULL, &local_err);
2848 if (local_err) {
2849 error_propagate(errp, local_err);
2850 goto fail;
2853 obj = qmp_output_get_qobject(ov);
2854 qdict = qobject_to_qdict(obj);
2856 qdict_flatten(qdict);
2858 blk = blockdev_init(NULL, qdict, &local_err);
2859 if (local_err) {
2860 error_propagate(errp, local_err);
2861 goto fail;
2864 if (bdrv_key_required(blk_bs(blk))) {
2865 blk_unref(blk);
2866 error_setg(errp, "blockdev-add doesn't support encrypted devices");
2867 goto fail;
2870 fail:
2871 qmp_output_visitor_cleanup(ov);
2874 BlockJobInfoList *qmp_query_block_jobs(Error **errp)
2876 BlockJobInfoList *head = NULL, **p_next = &head;
2877 BlockDriverState *bs;
2879 for (bs = bdrv_next(NULL); bs; bs = bdrv_next(bs)) {
2880 AioContext *aio_context = bdrv_get_aio_context(bs);
2882 aio_context_acquire(aio_context);
2884 if (bs->job) {
2885 BlockJobInfoList *elem = g_new0(BlockJobInfoList, 1);
2886 elem->value = block_job_query(bs->job);
2887 *p_next = elem;
2888 p_next = &elem->next;
2891 aio_context_release(aio_context);
2894 return head;
2897 QemuOptsList qemu_common_drive_opts = {
2898 .name = "drive",
2899 .head = QTAILQ_HEAD_INITIALIZER(qemu_common_drive_opts.head),
2900 .desc = {
2902 .name = "snapshot",
2903 .type = QEMU_OPT_BOOL,
2904 .help = "enable/disable snapshot mode",
2906 .name = "discard",
2907 .type = QEMU_OPT_STRING,
2908 .help = "discard operation (ignore/off, unmap/on)",
2910 .name = "cache.writeback",
2911 .type = QEMU_OPT_BOOL,
2912 .help = "enables writeback mode for any caches",
2914 .name = "cache.direct",
2915 .type = QEMU_OPT_BOOL,
2916 .help = "enables use of O_DIRECT (bypass the host page cache)",
2918 .name = "cache.no-flush",
2919 .type = QEMU_OPT_BOOL,
2920 .help = "ignore any flush requests for the device",
2922 .name = "aio",
2923 .type = QEMU_OPT_STRING,
2924 .help = "host AIO implementation (threads, native)",
2926 .name = "format",
2927 .type = QEMU_OPT_STRING,
2928 .help = "disk format (raw, qcow2, ...)",
2930 .name = "rerror",
2931 .type = QEMU_OPT_STRING,
2932 .help = "read error action",
2934 .name = "werror",
2935 .type = QEMU_OPT_STRING,
2936 .help = "write error action",
2938 .name = "read-only",
2939 .type = QEMU_OPT_BOOL,
2940 .help = "open drive file as read-only",
2942 .name = "throttling.iops-total",
2943 .type = QEMU_OPT_NUMBER,
2944 .help = "limit total I/O operations per second",
2946 .name = "throttling.iops-read",
2947 .type = QEMU_OPT_NUMBER,
2948 .help = "limit read operations per second",
2950 .name = "throttling.iops-write",
2951 .type = QEMU_OPT_NUMBER,
2952 .help = "limit write operations per second",
2954 .name = "throttling.bps-total",
2955 .type = QEMU_OPT_NUMBER,
2956 .help = "limit total bytes per second",
2958 .name = "throttling.bps-read",
2959 .type = QEMU_OPT_NUMBER,
2960 .help = "limit read bytes per second",
2962 .name = "throttling.bps-write",
2963 .type = QEMU_OPT_NUMBER,
2964 .help = "limit write bytes per second",
2966 .name = "throttling.iops-total-max",
2967 .type = QEMU_OPT_NUMBER,
2968 .help = "I/O operations burst",
2970 .name = "throttling.iops-read-max",
2971 .type = QEMU_OPT_NUMBER,
2972 .help = "I/O operations read burst",
2974 .name = "throttling.iops-write-max",
2975 .type = QEMU_OPT_NUMBER,
2976 .help = "I/O operations write burst",
2978 .name = "throttling.bps-total-max",
2979 .type = QEMU_OPT_NUMBER,
2980 .help = "total bytes burst",
2982 .name = "throttling.bps-read-max",
2983 .type = QEMU_OPT_NUMBER,
2984 .help = "total bytes read burst",
2986 .name = "throttling.bps-write-max",
2987 .type = QEMU_OPT_NUMBER,
2988 .help = "total bytes write burst",
2990 .name = "throttling.iops-size",
2991 .type = QEMU_OPT_NUMBER,
2992 .help = "when limiting by iops max size of an I/O in bytes",
2994 .name = "copy-on-read",
2995 .type = QEMU_OPT_BOOL,
2996 .help = "copy read data from backing file into image file",
2998 .name = "detect-zeroes",
2999 .type = QEMU_OPT_STRING,
3000 .help = "try to optimize zero writes (off, on, unmap)",
3002 { /* end of list */ }
3006 QemuOptsList qemu_drive_opts = {
3007 .name = "drive",
3008 .head = QTAILQ_HEAD_INITIALIZER(qemu_drive_opts.head),
3009 .desc = {
3011 * no elements => accept any params
3012 * validation will happen later
3014 { /* end of list */ }