2 * QEMU System Emulator block driver
4 * Copyright (c) 2003 Fabrice Bellard
5 * Copyright (c) 2020 Virtuozzo International GmbH.
7 * Permission is hereby granted, free of charge, to any person obtaining a copy
8 * of this software and associated documentation files (the "Software"), to deal
9 * in the Software without restriction, including without limitation the rights
10 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
11 * copies of the Software, and to permit persons to whom the Software is
12 * furnished to do so, subject to the following conditions:
14 * The above copyright notice and this permission notice shall be included in
15 * all copies or substantial portions of the Software.
17 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
18 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
19 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
20 * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
21 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
22 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
26 #include "qemu/osdep.h"
27 #include "block/trace.h"
28 #include "block/block_int.h"
29 #include "block/blockjob.h"
30 #include "block/dirty-bitmap.h"
31 #include "block/fuse.h"
32 #include "block/nbd.h"
33 #include "block/qdict.h"
34 #include "qemu/error-report.h"
35 #include "block/module_block.h"
36 #include "qemu/main-loop.h"
37 #include "qemu/module.h"
38 #include "qapi/error.h"
39 #include "qapi/qmp/qdict.h"
40 #include "qapi/qmp/qjson.h"
41 #include "qapi/qmp/qnull.h"
42 #include "qapi/qmp/qstring.h"
43 #include "qapi/qobject-output-visitor.h"
44 #include "qapi/qapi-visit-block-core.h"
45 #include "sysemu/block-backend.h"
46 #include "qemu/notify.h"
47 #include "qemu/option.h"
48 #include "qemu/coroutine.h"
49 #include "block/qapi.h"
50 #include "qemu/timer.h"
51 #include "qemu/cutils.h"
53 #include "qemu/range.h"
55 #include "block/coroutines.h"
58 #include <sys/ioctl.h>
59 #include <sys/queue.h>
60 #if defined(HAVE_SYS_DISK_H)
69 #define NOT_DONE 0x7fffffff /* used while emulated sync operation in progress */
71 /* Protected by BQL */
72 static QTAILQ_HEAD(, BlockDriverState) graph_bdrv_states =
73 QTAILQ_HEAD_INITIALIZER(graph_bdrv_states);
75 /* Protected by BQL */
76 static QTAILQ_HEAD(, BlockDriverState) all_bdrv_states =
77 QTAILQ_HEAD_INITIALIZER(all_bdrv_states);
79 /* Protected by BQL */
80 static QLIST_HEAD(, BlockDriver) bdrv_drivers =
81 QLIST_HEAD_INITIALIZER(bdrv_drivers);
83 static BlockDriverState *bdrv_open_inherit(const char *filename,
84 const char *reference,
85 QDict *options, int flags,
86 BlockDriverState *parent,
87 const BdrvChildClass *child_class,
88 BdrvChildRole child_role,
91 static bool bdrv_recurse_has_child(BlockDriverState *bs,
92 BlockDriverState *child);
94 static void GRAPH_WRLOCK
95 bdrv_replace_child_noperm(BdrvChild *child, BlockDriverState *new_bs);
97 static void GRAPH_WRLOCK
98 bdrv_remove_child(BdrvChild *child, Transaction *tran);
100 static int bdrv_reopen_prepare(BDRVReopenState *reopen_state,
101 BlockReopenQueue *queue,
102 Transaction *change_child_tran, Error **errp);
103 static void bdrv_reopen_commit(BDRVReopenState *reopen_state);
104 static void bdrv_reopen_abort(BDRVReopenState *reopen_state);
106 static bool bdrv_backing_overridden(BlockDriverState *bs);
108 static bool bdrv_change_aio_context(BlockDriverState *bs, AioContext *ctx,
109 GHashTable *visited, Transaction *tran,
112 /* If non-zero, use only whitelisted block drivers */
113 static int use_bdrv_whitelist;
116 static int is_windows_drive_prefix(const char *filename)
118 return (((filename[0] >= 'a' && filename[0] <= 'z') ||
119 (filename[0] >= 'A' && filename[0] <= 'Z')) &&
123 int is_windows_drive(const char *filename)
125 if (is_windows_drive_prefix(filename) &&
128 if (strstart(filename, "\\\\.\\", NULL) ||
129 strstart(filename, "//./", NULL))
135 size_t bdrv_opt_mem_align(BlockDriverState *bs)
137 if (!bs || !bs->drv) {
138 /* page size or 4k (hdd sector size) should be on the safe side */
139 return MAX(4096, qemu_real_host_page_size());
143 return bs->bl.opt_mem_alignment;
146 size_t bdrv_min_mem_align(BlockDriverState *bs)
148 if (!bs || !bs->drv) {
149 /* page size or 4k (hdd sector size) should be on the safe side */
150 return MAX(4096, qemu_real_host_page_size());
154 return bs->bl.min_mem_alignment;
157 /* check if the path starts with "<protocol>:" */
158 int path_has_protocol(const char *path)
163 if (is_windows_drive(path) ||
164 is_windows_drive_prefix(path)) {
167 p = path + strcspn(path, ":/\\");
169 p = path + strcspn(path, ":/");
175 int path_is_absolute(const char *path)
178 /* specific case for names like: "\\.\d:" */
179 if (is_windows_drive(path) || is_windows_drive_prefix(path)) {
182 return (*path == '/' || *path == '\\');
184 return (*path == '/');
188 /* if filename is absolute, just return its duplicate. Otherwise, build a
189 path to it by considering it is relative to base_path. URL are
191 char *path_combine(const char *base_path, const char *filename)
193 const char *protocol_stripped = NULL;
198 if (path_is_absolute(filename)) {
199 return g_strdup(filename);
202 if (path_has_protocol(base_path)) {
203 protocol_stripped = strchr(base_path, ':');
204 if (protocol_stripped) {
208 p = protocol_stripped ?: base_path;
210 p1 = strrchr(base_path, '/');
214 p2 = strrchr(base_path, '\\');
215 if (!p1 || p2 > p1) {
230 result = g_malloc(len + strlen(filename) + 1);
231 memcpy(result, base_path, len);
232 strcpy(result + len, filename);
238 * Helper function for bdrv_parse_filename() implementations to remove optional
239 * protocol prefixes (especially "file:") from a filename and for putting the
240 * stripped filename into the options QDict if there is such a prefix.
242 void bdrv_parse_filename_strip_prefix(const char *filename, const char *prefix,
245 if (strstart(filename, prefix, &filename)) {
246 /* Stripping the explicit protocol prefix may result in a protocol
247 * prefix being (wrongly) detected (if the filename contains a colon) */
248 if (path_has_protocol(filename)) {
249 GString *fat_filename;
251 /* This means there is some colon before the first slash; therefore,
252 * this cannot be an absolute path */
253 assert(!path_is_absolute(filename));
255 /* And we can thus fix the protocol detection issue by prefixing it
257 fat_filename = g_string_new("./");
258 g_string_append(fat_filename, filename);
260 assert(!path_has_protocol(fat_filename->str));
262 qdict_put(options, "filename",
263 qstring_from_gstring(fat_filename));
265 /* If no protocol prefix was detected, we can use the shortened
267 qdict_put_str(options, "filename", filename);
273 /* Returns whether the image file is opened as read-only. Note that this can
274 * return false and writing to the image file is still not possible because the
275 * image is inactivated. */
276 bool bdrv_is_read_only(BlockDriverState *bs)
279 return !(bs->open_flags & BDRV_O_RDWR);
282 static int bdrv_can_set_read_only(BlockDriverState *bs, bool read_only,
283 bool ignore_allow_rdw, Error **errp)
287 /* Do not set read_only if copy_on_read is enabled */
288 if (bs->copy_on_read && read_only) {
289 error_setg(errp, "Can't set node '%s' to r/o with copy-on-read enabled",
290 bdrv_get_device_or_node_name(bs));
294 /* Do not clear read_only if it is prohibited */
295 if (!read_only && !(bs->open_flags & BDRV_O_ALLOW_RDWR) &&
298 error_setg(errp, "Node '%s' is read only",
299 bdrv_get_device_or_node_name(bs));
307 * Called by a driver that can only provide a read-only image.
309 * Returns 0 if the node is already read-only or it could switch the node to
310 * read-only because BDRV_O_AUTO_RDONLY is set.
312 * Returns -EACCES if the node is read-write and BDRV_O_AUTO_RDONLY is not set
313 * or bdrv_can_set_read_only() forbids making the node read-only. If @errmsg
314 * is not NULL, it is used as the error message for the Error object.
316 int bdrv_apply_auto_read_only(BlockDriverState *bs, const char *errmsg,
322 if (!(bs->open_flags & BDRV_O_RDWR)) {
325 if (!(bs->open_flags & BDRV_O_AUTO_RDONLY)) {
329 ret = bdrv_can_set_read_only(bs, true, false, NULL);
334 bs->open_flags &= ~BDRV_O_RDWR;
339 error_setg(errp, "%s", errmsg ?: "Image is read-only");
344 * If @backing is empty, this function returns NULL without setting
345 * @errp. In all other cases, NULL will only be returned with @errp
348 * Therefore, a return value of NULL without @errp set means that
349 * there is no backing file; if @errp is set, there is one but its
350 * absolute filename cannot be generated.
352 char *bdrv_get_full_backing_filename_from_filename(const char *backed,
356 if (backing[0] == '\0') {
358 } else if (path_has_protocol(backing) || path_is_absolute(backing)) {
359 return g_strdup(backing);
360 } else if (backed[0] == '\0' || strstart(backed, "json:", NULL)) {
361 error_setg(errp, "Cannot use relative backing file names for '%s'",
365 return path_combine(backed, backing);
370 * If @filename is empty or NULL, this function returns NULL without
371 * setting @errp. In all other cases, NULL will only be returned with
374 static char *bdrv_make_absolute_filename(BlockDriverState *relative_to,
375 const char *filename, Error **errp)
377 char *dir, *full_name;
379 if (!filename || filename[0] == '\0') {
381 } else if (path_has_protocol(filename) || path_is_absolute(filename)) {
382 return g_strdup(filename);
385 dir = bdrv_dirname(relative_to, errp);
390 full_name = g_strconcat(dir, filename, NULL);
395 char *bdrv_get_full_backing_filename(BlockDriverState *bs, Error **errp)
398 return bdrv_make_absolute_filename(bs, bs->backing_file, errp);
401 void bdrv_register(BlockDriver *bdrv)
403 assert(bdrv->format_name);
405 QLIST_INSERT_HEAD(&bdrv_drivers, bdrv, list);
408 BlockDriverState *bdrv_new(void)
410 BlockDriverState *bs;
415 bs = g_new0(BlockDriverState, 1);
416 QLIST_INIT(&bs->dirty_bitmaps);
417 for (i = 0; i < BLOCK_OP_TYPE_MAX; i++) {
418 QLIST_INIT(&bs->op_blockers[i]);
420 qemu_mutex_init(&bs->reqs_lock);
421 qemu_mutex_init(&bs->dirty_bitmap_mutex);
423 bs->aio_context = qemu_get_aio_context();
425 qemu_co_queue_init(&bs->flush_queue);
427 qemu_co_mutex_init(&bs->bsc_modify_lock);
428 bs->block_status_cache = g_new0(BdrvBlockStatusCache, 1);
430 for (i = 0; i < bdrv_drain_all_count; i++) {
431 bdrv_drained_begin(bs);
434 QTAILQ_INSERT_TAIL(&all_bdrv_states, bs, bs_list);
439 static BlockDriver *bdrv_do_find_format(const char *format_name)
444 QLIST_FOREACH(drv1, &bdrv_drivers, list) {
445 if (!strcmp(drv1->format_name, format_name)) {
453 BlockDriver *bdrv_find_format(const char *format_name)
460 drv1 = bdrv_do_find_format(format_name);
465 /* The driver isn't registered, maybe we need to load a module */
466 for (i = 0; i < (int)ARRAY_SIZE(block_driver_modules); ++i) {
467 if (!strcmp(block_driver_modules[i].format_name, format_name)) {
468 Error *local_err = NULL;
469 int rv = block_module_load(block_driver_modules[i].library_name,
472 return bdrv_do_find_format(format_name);
474 error_report_err(local_err);
482 static int bdrv_format_is_whitelisted(const char *format_name, bool read_only)
484 static const char *whitelist_rw[] = {
485 CONFIG_BDRV_RW_WHITELIST
488 static const char *whitelist_ro[] = {
489 CONFIG_BDRV_RO_WHITELIST
494 if (!whitelist_rw[0] && !whitelist_ro[0]) {
495 return 1; /* no whitelist, anything goes */
498 for (p = whitelist_rw; *p; p++) {
499 if (!strcmp(format_name, *p)) {
504 for (p = whitelist_ro; *p; p++) {
505 if (!strcmp(format_name, *p)) {
513 int bdrv_is_whitelisted(BlockDriver *drv, bool read_only)
516 return bdrv_format_is_whitelisted(drv->format_name, read_only);
519 bool bdrv_uses_whitelist(void)
521 return use_bdrv_whitelist;
524 typedef struct CreateCo {
532 int coroutine_fn bdrv_co_create(BlockDriver *drv, const char *filename,
533 QemuOpts *opts, Error **errp)
539 if (!drv->bdrv_co_create_opts) {
540 error_setg(errp, "Driver '%s' does not support image creation",
545 ret = drv->bdrv_co_create_opts(drv, filename, opts, errp);
546 if (ret < 0 && !*errp) {
547 error_setg_errno(errp, -ret, "Could not create image");
554 * Helper function for bdrv_create_file_fallback(): Resize @blk to at
555 * least the given @minimum_size.
557 * On success, return @blk's actual length.
558 * Otherwise, return -errno.
560 static int64_t coroutine_fn GRAPH_UNLOCKED
561 create_file_fallback_truncate(BlockBackend *blk, int64_t minimum_size,
564 Error *local_err = NULL;
570 ret = blk_co_truncate(blk, minimum_size, false, PREALLOC_MODE_OFF, 0,
572 if (ret < 0 && ret != -ENOTSUP) {
573 error_propagate(errp, local_err);
577 size = blk_co_getlength(blk);
579 error_free(local_err);
580 error_setg_errno(errp, -size,
581 "Failed to inquire the new image file's length");
585 if (size < minimum_size) {
586 /* Need to grow the image, but we failed to do that */
587 error_propagate(errp, local_err);
591 error_free(local_err);
598 * Helper function for bdrv_create_file_fallback(): Zero the first
599 * sector to remove any potentially pre-existing image header.
601 static int coroutine_fn
602 create_file_fallback_zero_first_sector(BlockBackend *blk,
603 int64_t current_size,
606 int64_t bytes_to_clear;
611 bytes_to_clear = MIN(current_size, BDRV_SECTOR_SIZE);
612 if (bytes_to_clear) {
613 ret = blk_co_pwrite_zeroes(blk, 0, bytes_to_clear, BDRV_REQ_MAY_UNMAP);
615 error_setg_errno(errp, -ret,
616 "Failed to clear the new image's first sector");
625 * Simple implementation of bdrv_co_create_opts for protocol drivers
626 * which only support creation via opening a file
627 * (usually existing raw storage device)
629 int coroutine_fn bdrv_co_create_opts_simple(BlockDriver *drv,
630 const char *filename,
638 PreallocMode prealloc;
639 Error *local_err = NULL;
644 size = qemu_opt_get_size_del(opts, BLOCK_OPT_SIZE, 0);
645 buf = qemu_opt_get_del(opts, BLOCK_OPT_PREALLOC);
646 prealloc = qapi_enum_parse(&PreallocMode_lookup, buf,
647 PREALLOC_MODE_OFF, &local_err);
650 error_propagate(errp, local_err);
654 if (prealloc != PREALLOC_MODE_OFF) {
655 error_setg(errp, "Unsupported preallocation mode '%s'",
656 PreallocMode_str(prealloc));
660 options = qdict_new();
661 qdict_put_str(options, "driver", drv->format_name);
663 blk = blk_co_new_open(filename, NULL, options,
664 BDRV_O_RDWR | BDRV_O_RESIZE, errp);
666 error_prepend(errp, "Protocol driver '%s' does not support creating "
667 "new images, so an existing image must be selected as "
668 "the target; however, opening the given target as an "
669 "existing image failed: ",
674 size = create_file_fallback_truncate(blk, size, errp);
680 ret = create_file_fallback_zero_first_sector(blk, size, errp);
691 int coroutine_fn bdrv_co_create_file(const char *filename, QemuOpts *opts,
694 QemuOpts *protocol_opts;
701 drv = bdrv_find_protocol(filename, true, errp);
706 if (!drv->create_opts) {
707 error_setg(errp, "Driver '%s' does not support image creation",
713 * 'opts' contains a QemuOptsList with a combination of format and protocol
716 * The format properly removes its options, but the default values remain
717 * in 'opts->list'. So if the protocol has options with the same name
718 * (e.g. rbd has 'cluster_size' as qcow2), it will see the default values
719 * of the format, since for overlapping options, the format wins.
721 * To avoid this issue, lets convert QemuOpts to QDict, in this way we take
722 * only the set options, and then convert it back to QemuOpts, using the
723 * create_opts of the protocol. So the new QemuOpts, will contain only the
726 qdict = qemu_opts_to_qdict(opts, NULL);
727 protocol_opts = qemu_opts_from_qdict(drv->create_opts, qdict, errp);
728 if (protocol_opts == NULL) {
733 ret = bdrv_co_create(drv, filename, protocol_opts, errp);
735 qemu_opts_del(protocol_opts);
736 qobject_unref(qdict);
740 int coroutine_fn bdrv_co_delete_file(BlockDriverState *bs, Error **errp)
742 Error *local_err = NULL;
747 assert_bdrv_graph_readable();
750 error_setg(errp, "Block node '%s' is not opened", bs->filename);
754 if (!bs->drv->bdrv_co_delete_file) {
755 error_setg(errp, "Driver '%s' does not support image deletion",
756 bs->drv->format_name);
760 ret = bs->drv->bdrv_co_delete_file(bs, &local_err);
762 error_propagate(errp, local_err);
768 void coroutine_fn bdrv_co_delete_file_noerr(BlockDriverState *bs)
770 Error *local_err = NULL;
778 ret = bdrv_co_delete_file(bs, &local_err);
780 * ENOTSUP will happen if the block driver doesn't support
781 * the 'bdrv_co_delete_file' interface. This is a predictable
782 * scenario and shouldn't be reported back to the user.
784 if (ret == -ENOTSUP) {
785 error_free(local_err);
786 } else if (ret < 0) {
787 error_report_err(local_err);
792 * Try to get @bs's logical and physical block size.
793 * On success, store them in @bsz struct and return 0.
794 * On failure return -errno.
795 * @bs must not be empty.
797 int bdrv_probe_blocksizes(BlockDriverState *bs, BlockSizes *bsz)
799 BlockDriver *drv = bs->drv;
800 BlockDriverState *filtered = bdrv_filter_bs(bs);
803 if (drv && drv->bdrv_probe_blocksizes) {
804 return drv->bdrv_probe_blocksizes(bs, bsz);
805 } else if (filtered) {
806 return bdrv_probe_blocksizes(filtered, bsz);
813 * Try to get @bs's geometry (cyls, heads, sectors).
814 * On success, store them in @geo struct and return 0.
815 * On failure return -errno.
816 * @bs must not be empty.
818 int bdrv_probe_geometry(BlockDriverState *bs, HDGeometry *geo)
820 BlockDriver *drv = bs->drv;
821 BlockDriverState *filtered = bdrv_filter_bs(bs);
824 if (drv && drv->bdrv_probe_geometry) {
825 return drv->bdrv_probe_geometry(bs, geo);
826 } else if (filtered) {
827 return bdrv_probe_geometry(filtered, geo);
834 * Create a uniquely-named empty temporary file.
835 * Return the actual file name used upon success, otherwise NULL.
836 * This string should be freed with g_free() when not needed any longer.
838 * Note: creating a temporary file for the caller to (re)open is
839 * inherently racy. Use g_file_open_tmp() instead whenever practical.
841 char *create_tmp_file(Error **errp)
845 g_autofree char *filename = NULL;
847 tmpdir = g_get_tmp_dir();
850 * See commit 69bef79 ("block: use /var/tmp instead of /tmp for -snapshot")
852 * This function is used to create temporary disk images (like -snapshot),
853 * so the files can become very large. /tmp is often a tmpfs where as
854 * /var/tmp is usually on a disk, so more appropriate for disk images.
856 if (!g_strcmp0(tmpdir, "/tmp")) {
861 filename = g_strdup_printf("%s/vl.XXXXXX", tmpdir);
862 fd = g_mkstemp(filename);
864 error_setg_errno(errp, errno, "Could not open temporary file '%s'",
870 return g_steal_pointer(&filename);
874 * Detect host devices. By convention, /dev/cdrom[N] is always
875 * recognized as a host CDROM.
877 static BlockDriver *find_hdev_driver(const char *filename)
879 int score_max = 0, score;
880 BlockDriver *drv = NULL, *d;
883 QLIST_FOREACH(d, &bdrv_drivers, list) {
884 if (d->bdrv_probe_device) {
885 score = d->bdrv_probe_device(filename);
886 if (score > score_max) {
896 static BlockDriver *bdrv_do_find_protocol(const char *protocol)
901 QLIST_FOREACH(drv1, &bdrv_drivers, list) {
902 if (drv1->protocol_name && !strcmp(drv1->protocol_name, protocol)) {
910 BlockDriver *bdrv_find_protocol(const char *filename,
911 bool allow_protocol_prefix,
921 /* TODO Drivers without bdrv_file_open must be specified explicitly */
924 * XXX(hch): we really should not let host device detection
925 * override an explicit protocol specification, but moving this
926 * later breaks access to device names with colons in them.
927 * Thanks to the brain-dead persistent naming schemes on udev-
928 * based Linux systems those actually are quite common.
930 drv1 = find_hdev_driver(filename);
935 if (!path_has_protocol(filename) || !allow_protocol_prefix) {
939 p = strchr(filename, ':');
942 if (len > sizeof(protocol) - 1)
943 len = sizeof(protocol) - 1;
944 memcpy(protocol, filename, len);
945 protocol[len] = '\0';
947 drv1 = bdrv_do_find_protocol(protocol);
952 for (i = 0; i < (int)ARRAY_SIZE(block_driver_modules); ++i) {
953 if (block_driver_modules[i].protocol_name &&
954 !strcmp(block_driver_modules[i].protocol_name, protocol)) {
955 int rv = block_module_load(block_driver_modules[i].library_name, errp);
957 drv1 = bdrv_do_find_protocol(protocol);
966 error_setg(errp, "Unknown protocol '%s'", protocol);
972 * Guess image format by probing its contents.
973 * This is not a good idea when your image is raw (CVE-2008-2004), but
974 * we do it anyway for backward compatibility.
976 * @buf contains the image's first @buf_size bytes.
977 * @buf_size is the buffer size in bytes (generally BLOCK_PROBE_BUF_SIZE,
978 * but can be smaller if the image file is smaller)
979 * @filename is its filename.
981 * For all block drivers, call the bdrv_probe() method to get its
983 * Return the first block driver with the highest probing score.
985 BlockDriver *bdrv_probe_all(const uint8_t *buf, int buf_size,
986 const char *filename)
988 int score_max = 0, score;
989 BlockDriver *drv = NULL, *d;
992 QLIST_FOREACH(d, &bdrv_drivers, list) {
994 score = d->bdrv_probe(buf, buf_size, filename);
995 if (score > score_max) {
1005 static int find_image_format(BlockBackend *file, const char *filename,
1006 BlockDriver **pdrv, Error **errp)
1009 uint8_t buf[BLOCK_PROBE_BUF_SIZE];
1012 GLOBAL_STATE_CODE();
1014 /* Return the raw BlockDriver * to scsi-generic devices or empty drives */
1015 if (blk_is_sg(file) || !blk_is_inserted(file) || blk_getlength(file) == 0) {
1020 ret = blk_pread(file, 0, sizeof(buf), buf, 0);
1022 error_setg_errno(errp, -ret, "Could not read image for determining its "
1028 drv = bdrv_probe_all(buf, sizeof(buf), filename);
1030 error_setg(errp, "Could not determine image format: No compatible "
1041 * Set the current 'total_sectors' value
1042 * Return 0 on success, -errno on error.
1044 int coroutine_fn bdrv_co_refresh_total_sectors(BlockDriverState *bs,
1047 BlockDriver *drv = bs->drv;
1049 assert_bdrv_graph_readable();
1055 /* Do not attempt drv->bdrv_co_getlength() on scsi-generic devices */
1059 /* query actual device if possible, otherwise just trust the hint */
1060 if (drv->bdrv_co_getlength) {
1061 int64_t length = drv->bdrv_co_getlength(bs);
1065 hint = DIV_ROUND_UP(length, BDRV_SECTOR_SIZE);
1068 bs->total_sectors = hint;
1070 if (bs->total_sectors * BDRV_SECTOR_SIZE > BDRV_MAX_LENGTH) {
1078 * Combines a QDict of new block driver @options with any missing options taken
1079 * from @old_options, so that leaving out an option defaults to its old value.
1081 static void bdrv_join_options(BlockDriverState *bs, QDict *options,
1084 GLOBAL_STATE_CODE();
1085 if (bs->drv && bs->drv->bdrv_join_options) {
1086 bs->drv->bdrv_join_options(options, old_options);
1088 qdict_join(options, old_options, false);
1092 static BlockdevDetectZeroesOptions bdrv_parse_detect_zeroes(QemuOpts *opts,
1096 Error *local_err = NULL;
1097 char *value = qemu_opt_get_del(opts, "detect-zeroes");
1098 BlockdevDetectZeroesOptions detect_zeroes =
1099 qapi_enum_parse(&BlockdevDetectZeroesOptions_lookup, value,
1100 BLOCKDEV_DETECT_ZEROES_OPTIONS_OFF, &local_err);
1101 GLOBAL_STATE_CODE();
1104 error_propagate(errp, local_err);
1105 return detect_zeroes;
1108 if (detect_zeroes == BLOCKDEV_DETECT_ZEROES_OPTIONS_UNMAP &&
1109 !(open_flags & BDRV_O_UNMAP))
1111 error_setg(errp, "setting detect-zeroes to unmap is not allowed "
1112 "without setting discard operation to unmap");
1115 return detect_zeroes;
1119 * Set open flags for aio engine
1121 * Return 0 on success, -1 if the engine specified is invalid
1123 int bdrv_parse_aio(const char *mode, int *flags)
1125 if (!strcmp(mode, "threads")) {
1126 /* do nothing, default */
1127 } else if (!strcmp(mode, "native")) {
1128 *flags |= BDRV_O_NATIVE_AIO;
1129 #ifdef CONFIG_LINUX_IO_URING
1130 } else if (!strcmp(mode, "io_uring")) {
1131 *flags |= BDRV_O_IO_URING;
1141 * Set open flags for a given discard mode
1143 * Return 0 on success, -1 if the discard mode was invalid.
1145 int bdrv_parse_discard_flags(const char *mode, int *flags)
1147 *flags &= ~BDRV_O_UNMAP;
1149 if (!strcmp(mode, "off") || !strcmp(mode, "ignore")) {
1151 } else if (!strcmp(mode, "on") || !strcmp(mode, "unmap")) {
1152 *flags |= BDRV_O_UNMAP;
1161 * Set open flags for a given cache mode
1163 * Return 0 on success, -1 if the cache mode was invalid.
1165 int bdrv_parse_cache_mode(const char *mode, int *flags, bool *writethrough)
1167 *flags &= ~BDRV_O_CACHE_MASK;
1169 if (!strcmp(mode, "off") || !strcmp(mode, "none")) {
1170 *writethrough = false;
1171 *flags |= BDRV_O_NOCACHE;
1172 } else if (!strcmp(mode, "directsync")) {
1173 *writethrough = true;
1174 *flags |= BDRV_O_NOCACHE;
1175 } else if (!strcmp(mode, "writeback")) {
1176 *writethrough = false;
1177 } else if (!strcmp(mode, "unsafe")) {
1178 *writethrough = false;
1179 *flags |= BDRV_O_NO_FLUSH;
1180 } else if (!strcmp(mode, "writethrough")) {
1181 *writethrough = true;
1189 static char *bdrv_child_get_parent_desc(BdrvChild *c)
1191 BlockDriverState *parent = c->opaque;
1192 return g_strdup_printf("node '%s'", bdrv_get_node_name(parent));
1195 static void bdrv_child_cb_drained_begin(BdrvChild *child)
1197 BlockDriverState *bs = child->opaque;
1198 bdrv_do_drained_begin_quiesce(bs, NULL);
1201 static bool bdrv_child_cb_drained_poll(BdrvChild *child)
1203 BlockDriverState *bs = child->opaque;
1204 return bdrv_drain_poll(bs, NULL, false);
1207 static void bdrv_child_cb_drained_end(BdrvChild *child)
1209 BlockDriverState *bs = child->opaque;
1210 bdrv_drained_end(bs);
1213 static int bdrv_child_cb_inactivate(BdrvChild *child)
1215 BlockDriverState *bs = child->opaque;
1216 GLOBAL_STATE_CODE();
1217 assert(bs->open_flags & BDRV_O_INACTIVE);
1221 static bool bdrv_child_cb_change_aio_ctx(BdrvChild *child, AioContext *ctx,
1222 GHashTable *visited, Transaction *tran,
1225 BlockDriverState *bs = child->opaque;
1226 return bdrv_change_aio_context(bs, ctx, visited, tran, errp);
1230 * Returns the options and flags that a temporary snapshot should get, based on
1231 * the originally requested flags (the originally requested image will have
1232 * flags like a backing file)
1234 static void bdrv_temp_snapshot_options(int *child_flags, QDict *child_options,
1235 int parent_flags, QDict *parent_options)
1237 GLOBAL_STATE_CODE();
1238 *child_flags = (parent_flags & ~BDRV_O_SNAPSHOT) | BDRV_O_TEMPORARY;
1240 /* For temporary files, unconditional cache=unsafe is fine */
1241 qdict_set_default_str(child_options, BDRV_OPT_CACHE_DIRECT, "off");
1242 qdict_set_default_str(child_options, BDRV_OPT_CACHE_NO_FLUSH, "on");
1244 /* Copy the read-only and discard options from the parent */
1245 qdict_copy_default(child_options, parent_options, BDRV_OPT_READ_ONLY);
1246 qdict_copy_default(child_options, parent_options, BDRV_OPT_DISCARD);
1248 /* aio=native doesn't work for cache.direct=off, so disable it for the
1249 * temporary snapshot */
1250 *child_flags &= ~BDRV_O_NATIVE_AIO;
1253 static void bdrv_backing_attach(BdrvChild *c)
1255 BlockDriverState *parent = c->opaque;
1256 BlockDriverState *backing_hd = c->bs;
1258 GLOBAL_STATE_CODE();
1259 assert(!parent->backing_blocker);
1260 error_setg(&parent->backing_blocker,
1261 "node is used as backing hd of '%s'",
1262 bdrv_get_device_or_node_name(parent));
1264 bdrv_refresh_filename(backing_hd);
1266 parent->open_flags &= ~BDRV_O_NO_BACKING;
1268 bdrv_op_block_all(backing_hd, parent->backing_blocker);
1269 /* Otherwise we won't be able to commit or stream */
1270 bdrv_op_unblock(backing_hd, BLOCK_OP_TYPE_COMMIT_TARGET,
1271 parent->backing_blocker);
1272 bdrv_op_unblock(backing_hd, BLOCK_OP_TYPE_STREAM,
1273 parent->backing_blocker);
1275 * We do backup in 3 ways:
1277 * The target bs is new opened, and the source is top BDS
1278 * 2. blockdev backup
1279 * Both the source and the target are top BDSes.
1280 * 3. internal backup(used for block replication)
1281 * Both the source and the target are backing file
1283 * In case 1 and 2, neither the source nor the target is the backing file.
1284 * In case 3, we will block the top BDS, so there is only one block job
1285 * for the top BDS and its backing chain.
1287 bdrv_op_unblock(backing_hd, BLOCK_OP_TYPE_BACKUP_SOURCE,
1288 parent->backing_blocker);
1289 bdrv_op_unblock(backing_hd, BLOCK_OP_TYPE_BACKUP_TARGET,
1290 parent->backing_blocker);
1293 static void bdrv_backing_detach(BdrvChild *c)
1295 BlockDriverState *parent = c->opaque;
1297 GLOBAL_STATE_CODE();
1298 assert(parent->backing_blocker);
1299 bdrv_op_unblock_all(c->bs, parent->backing_blocker);
1300 error_free(parent->backing_blocker);
1301 parent->backing_blocker = NULL;
1304 static int bdrv_backing_update_filename(BdrvChild *c, BlockDriverState *base,
1305 const char *filename, Error **errp)
1307 BlockDriverState *parent = c->opaque;
1308 bool read_only = bdrv_is_read_only(parent);
1310 GLOBAL_STATE_CODE();
1313 ret = bdrv_reopen_set_read_only(parent, false, errp);
1319 ret = bdrv_change_backing_file(parent, filename,
1320 base->drv ? base->drv->format_name : "",
1323 error_setg_errno(errp, -ret, "Could not update backing file link");
1327 bdrv_reopen_set_read_only(parent, true, NULL);
1334 * Returns the options and flags that a generic child of a BDS should
1335 * get, based on the given options and flags for the parent BDS.
1337 static void bdrv_inherited_options(BdrvChildRole role, bool parent_is_format,
1338 int *child_flags, QDict *child_options,
1339 int parent_flags, QDict *parent_options)
1341 int flags = parent_flags;
1342 GLOBAL_STATE_CODE();
1345 * First, decide whether to set, clear, or leave BDRV_O_PROTOCOL.
1346 * Generally, the question to answer is: Should this child be
1347 * format-probed by default?
1351 * Pure and non-filtered data children of non-format nodes should
1352 * be probed by default (even when the node itself has BDRV_O_PROTOCOL
1353 * set). This only affects a very limited set of drivers (namely
1354 * quorum and blkverify when this comment was written).
1355 * Force-clear BDRV_O_PROTOCOL then.
1357 if (!parent_is_format &&
1358 (role & BDRV_CHILD_DATA) &&
1359 !(role & (BDRV_CHILD_METADATA | BDRV_CHILD_FILTERED)))
1361 flags &= ~BDRV_O_PROTOCOL;
1365 * All children of format nodes (except for COW children) and all
1366 * metadata children in general should never be format-probed.
1367 * Force-set BDRV_O_PROTOCOL then.
1369 if ((parent_is_format && !(role & BDRV_CHILD_COW)) ||
1370 (role & BDRV_CHILD_METADATA))
1372 flags |= BDRV_O_PROTOCOL;
1376 * If the cache mode isn't explicitly set, inherit direct and no-flush from
1379 qdict_copy_default(child_options, parent_options, BDRV_OPT_CACHE_DIRECT);
1380 qdict_copy_default(child_options, parent_options, BDRV_OPT_CACHE_NO_FLUSH);
1381 qdict_copy_default(child_options, parent_options, BDRV_OPT_FORCE_SHARE);
1383 if (role & BDRV_CHILD_COW) {
1384 /* backing files are opened read-only by default */
1385 qdict_set_default_str(child_options, BDRV_OPT_READ_ONLY, "on");
1386 qdict_set_default_str(child_options, BDRV_OPT_AUTO_READ_ONLY, "off");
1388 /* Inherit the read-only option from the parent if it's not set */
1389 qdict_copy_default(child_options, parent_options, BDRV_OPT_READ_ONLY);
1390 qdict_copy_default(child_options, parent_options,
1391 BDRV_OPT_AUTO_READ_ONLY);
1395 * bdrv_co_pdiscard() respects unmap policy for the parent, so we
1396 * can default to enable it on lower layers regardless of the
1399 qdict_set_default_str(child_options, BDRV_OPT_DISCARD, "unmap");
1401 /* Clear flags that only apply to the top layer */
1402 flags &= ~(BDRV_O_SNAPSHOT | BDRV_O_NO_BACKING | BDRV_O_COPY_ON_READ);
1404 if (role & BDRV_CHILD_METADATA) {
1405 flags &= ~BDRV_O_NO_IO;
1407 if (role & BDRV_CHILD_COW) {
1408 flags &= ~BDRV_O_TEMPORARY;
1411 *child_flags = flags;
1414 static void GRAPH_WRLOCK bdrv_child_cb_attach(BdrvChild *child)
1416 BlockDriverState *bs = child->opaque;
1418 assert_bdrv_graph_writable();
1419 QLIST_INSERT_HEAD(&bs->children, child, next);
1420 if (bs->drv->is_filter || (child->role & BDRV_CHILD_FILTERED)) {
1422 * Here we handle filters and block/raw-format.c when it behave like
1423 * filter. They generally have a single PRIMARY child, which is also the
1424 * FILTERED child, and that they may have multiple more children, which
1425 * are neither PRIMARY nor FILTERED. And never we have a COW child here.
1426 * So bs->file will be the PRIMARY child, unless the PRIMARY child goes
1427 * into bs->backing on exceptional cases; and bs->backing will be
1430 assert(!(child->role & BDRV_CHILD_COW));
1431 if (child->role & BDRV_CHILD_PRIMARY) {
1432 assert(child->role & BDRV_CHILD_FILTERED);
1433 assert(!bs->backing);
1436 if (bs->drv->filtered_child_is_backing) {
1437 bs->backing = child;
1442 assert(!(child->role & BDRV_CHILD_FILTERED));
1444 } else if (child->role & BDRV_CHILD_COW) {
1445 assert(bs->drv->supports_backing);
1446 assert(!(child->role & BDRV_CHILD_PRIMARY));
1447 assert(!bs->backing);
1448 bs->backing = child;
1449 bdrv_backing_attach(child);
1450 } else if (child->role & BDRV_CHILD_PRIMARY) {
1456 static void GRAPH_WRLOCK bdrv_child_cb_detach(BdrvChild *child)
1458 BlockDriverState *bs = child->opaque;
1460 if (child->role & BDRV_CHILD_COW) {
1461 bdrv_backing_detach(child);
1464 assert_bdrv_graph_writable();
1465 QLIST_REMOVE(child, next);
1466 if (child == bs->backing) {
1467 assert(child != bs->file);
1469 } else if (child == bs->file) {
1474 static int bdrv_child_cb_update_filename(BdrvChild *c, BlockDriverState *base,
1475 const char *filename, Error **errp)
1477 if (c->role & BDRV_CHILD_COW) {
1478 return bdrv_backing_update_filename(c, base, filename, errp);
1483 AioContext *child_of_bds_get_parent_aio_context(BdrvChild *c)
1485 BlockDriverState *bs = c->opaque;
1488 return bdrv_get_aio_context(bs);
1491 const BdrvChildClass child_of_bds = {
1492 .parent_is_bds = true,
1493 .get_parent_desc = bdrv_child_get_parent_desc,
1494 .inherit_options = bdrv_inherited_options,
1495 .drained_begin = bdrv_child_cb_drained_begin,
1496 .drained_poll = bdrv_child_cb_drained_poll,
1497 .drained_end = bdrv_child_cb_drained_end,
1498 .attach = bdrv_child_cb_attach,
1499 .detach = bdrv_child_cb_detach,
1500 .inactivate = bdrv_child_cb_inactivate,
1501 .change_aio_ctx = bdrv_child_cb_change_aio_ctx,
1502 .update_filename = bdrv_child_cb_update_filename,
1503 .get_parent_aio_context = child_of_bds_get_parent_aio_context,
1506 AioContext *bdrv_child_get_parent_aio_context(BdrvChild *c)
1509 return c->klass->get_parent_aio_context(c);
1512 static int bdrv_open_flags(BlockDriverState *bs, int flags)
1514 int open_flags = flags;
1515 GLOBAL_STATE_CODE();
1518 * Clear flags that are internal to the block layer before opening the
1521 open_flags &= ~(BDRV_O_SNAPSHOT | BDRV_O_NO_BACKING | BDRV_O_PROTOCOL);
1526 static void update_flags_from_options(int *flags, QemuOpts *opts)
1528 GLOBAL_STATE_CODE();
1530 *flags &= ~(BDRV_O_CACHE_MASK | BDRV_O_RDWR | BDRV_O_AUTO_RDONLY);
1532 if (qemu_opt_get_bool_del(opts, BDRV_OPT_CACHE_NO_FLUSH, false)) {
1533 *flags |= BDRV_O_NO_FLUSH;
1536 if (qemu_opt_get_bool_del(opts, BDRV_OPT_CACHE_DIRECT, false)) {
1537 *flags |= BDRV_O_NOCACHE;
1540 if (!qemu_opt_get_bool_del(opts, BDRV_OPT_READ_ONLY, false)) {
1541 *flags |= BDRV_O_RDWR;
1544 if (qemu_opt_get_bool_del(opts, BDRV_OPT_AUTO_READ_ONLY, false)) {
1545 *flags |= BDRV_O_AUTO_RDONLY;
1549 static void update_options_from_flags(QDict *options, int flags)
1551 GLOBAL_STATE_CODE();
1552 if (!qdict_haskey(options, BDRV_OPT_CACHE_DIRECT)) {
1553 qdict_put_bool(options, BDRV_OPT_CACHE_DIRECT, flags & BDRV_O_NOCACHE);
1555 if (!qdict_haskey(options, BDRV_OPT_CACHE_NO_FLUSH)) {
1556 qdict_put_bool(options, BDRV_OPT_CACHE_NO_FLUSH,
1557 flags & BDRV_O_NO_FLUSH);
1559 if (!qdict_haskey(options, BDRV_OPT_READ_ONLY)) {
1560 qdict_put_bool(options, BDRV_OPT_READ_ONLY, !(flags & BDRV_O_RDWR));
1562 if (!qdict_haskey(options, BDRV_OPT_AUTO_READ_ONLY)) {
1563 qdict_put_bool(options, BDRV_OPT_AUTO_READ_ONLY,
1564 flags & BDRV_O_AUTO_RDONLY);
1568 static void bdrv_assign_node_name(BlockDriverState *bs,
1569 const char *node_name,
1572 char *gen_node_name = NULL;
1573 GLOBAL_STATE_CODE();
1576 node_name = gen_node_name = id_generate(ID_BLOCK);
1577 } else if (!id_wellformed(node_name)) {
1579 * Check for empty string or invalid characters, but not if it is
1580 * generated (generated names use characters not available to the user)
1582 error_setg(errp, "Invalid node-name: '%s'", node_name);
1586 /* takes care of avoiding namespaces collisions */
1587 if (blk_by_name(node_name)) {
1588 error_setg(errp, "node-name=%s is conflicting with a device id",
1593 /* takes care of avoiding duplicates node names */
1594 if (bdrv_find_node(node_name)) {
1595 error_setg(errp, "Duplicate nodes with node-name='%s'", node_name);
1599 /* Make sure that the node name isn't truncated */
1600 if (strlen(node_name) >= sizeof(bs->node_name)) {
1601 error_setg(errp, "Node name too long");
1605 /* copy node name into the bs and insert it into the graph list */
1606 pstrcpy(bs->node_name, sizeof(bs->node_name), node_name);
1607 QTAILQ_INSERT_TAIL(&graph_bdrv_states, bs, node_list);
1609 g_free(gen_node_name);
1613 * The caller must always hold @bs AioContext lock, because this function calls
1614 * bdrv_refresh_total_sectors() which polls when called from non-coroutine
1617 static int no_coroutine_fn GRAPH_UNLOCKED
1618 bdrv_open_driver(BlockDriverState *bs, BlockDriver *drv, const char *node_name,
1619 QDict *options, int open_flags, Error **errp)
1622 Error *local_err = NULL;
1624 GLOBAL_STATE_CODE();
1626 bdrv_assign_node_name(bs, node_name, &local_err);
1628 error_propagate(errp, local_err);
1633 bs->opaque = g_malloc0(drv->instance_size);
1635 if (drv->bdrv_file_open) {
1636 assert(!drv->bdrv_needs_filename || bs->filename[0]);
1637 ret = drv->bdrv_file_open(bs, options, open_flags, &local_err);
1638 } else if (drv->bdrv_open) {
1639 ret = drv->bdrv_open(bs, options, open_flags, &local_err);
1646 error_propagate(errp, local_err);
1647 } else if (bs->filename[0]) {
1648 error_setg_errno(errp, -ret, "Could not open '%s'", bs->filename);
1650 error_setg_errno(errp, -ret, "Could not open image");
1655 assert(!(bs->supported_read_flags & ~BDRV_REQ_MASK));
1656 assert(!(bs->supported_write_flags & ~BDRV_REQ_MASK));
1659 * Always allow the BDRV_REQ_REGISTERED_BUF optimization hint. This saves
1660 * drivers that pass read/write requests through to a child the trouble of
1661 * declaring support explicitly.
1663 * Drivers must not propagate this flag accidentally when they initiate I/O
1664 * to a bounce buffer. That case should be rare though.
1666 bs->supported_read_flags |= BDRV_REQ_REGISTERED_BUF;
1667 bs->supported_write_flags |= BDRV_REQ_REGISTERED_BUF;
1669 /* Get the context after .bdrv_open, it can change the context */
1670 ctx = bdrv_get_aio_context(bs);
1671 aio_context_acquire(ctx);
1673 ret = bdrv_refresh_total_sectors(bs, bs->total_sectors);
1675 error_setg_errno(errp, -ret, "Could not refresh total sector count");
1676 aio_context_release(ctx);
1680 bdrv_graph_rdlock_main_loop();
1681 bdrv_refresh_limits(bs, NULL, &local_err);
1682 bdrv_graph_rdunlock_main_loop();
1683 aio_context_release(ctx);
1686 error_propagate(errp, local_err);
1690 assert(bdrv_opt_mem_align(bs) != 0);
1691 assert(bdrv_min_mem_align(bs) != 0);
1692 assert(is_power_of_2(bs->bl.request_alignment));
1694 for (i = 0; i < bs->quiesce_counter; i++) {
1695 if (drv->bdrv_drain_begin) {
1696 drv->bdrv_drain_begin(bs);
1703 if (bs->file != NULL) {
1704 bdrv_unref_child(bs, bs->file);
1713 * Create and open a block node.
1715 * @options is a QDict of options to pass to the block drivers, or NULL for an
1716 * empty set of options. The reference to the QDict belongs to the block layer
1717 * after the call (even on failure), so if the caller intends to reuse the
1718 * dictionary, it needs to use qobject_ref() before calling bdrv_open.
1720 BlockDriverState *bdrv_new_open_driver_opts(BlockDriver *drv,
1721 const char *node_name,
1722 QDict *options, int flags,
1725 BlockDriverState *bs;
1728 GLOBAL_STATE_CODE();
1731 bs->open_flags = flags;
1732 bs->options = options ?: qdict_new();
1733 bs->explicit_options = qdict_clone_shallow(bs->options);
1736 update_options_from_flags(bs->options, flags);
1738 ret = bdrv_open_driver(bs, drv, node_name, bs->options, flags, errp);
1740 qobject_unref(bs->explicit_options);
1741 bs->explicit_options = NULL;
1742 qobject_unref(bs->options);
1751 /* Create and open a block node. */
1752 BlockDriverState *bdrv_new_open_driver(BlockDriver *drv, const char *node_name,
1753 int flags, Error **errp)
1755 GLOBAL_STATE_CODE();
1756 return bdrv_new_open_driver_opts(drv, node_name, NULL, flags, errp);
1759 QemuOptsList bdrv_runtime_opts = {
1760 .name = "bdrv_common",
1761 .head = QTAILQ_HEAD_INITIALIZER(bdrv_runtime_opts.head),
1764 .name = "node-name",
1765 .type = QEMU_OPT_STRING,
1766 .help = "Node name of the block device node",
1770 .type = QEMU_OPT_STRING,
1771 .help = "Block driver to use for the node",
1774 .name = BDRV_OPT_CACHE_DIRECT,
1775 .type = QEMU_OPT_BOOL,
1776 .help = "Bypass software writeback cache on the host",
1779 .name = BDRV_OPT_CACHE_NO_FLUSH,
1780 .type = QEMU_OPT_BOOL,
1781 .help = "Ignore flush requests",
1784 .name = BDRV_OPT_READ_ONLY,
1785 .type = QEMU_OPT_BOOL,
1786 .help = "Node is opened in read-only mode",
1789 .name = BDRV_OPT_AUTO_READ_ONLY,
1790 .type = QEMU_OPT_BOOL,
1791 .help = "Node can become read-only if opening read-write fails",
1794 .name = "detect-zeroes",
1795 .type = QEMU_OPT_STRING,
1796 .help = "try to optimize zero writes (off, on, unmap)",
1799 .name = BDRV_OPT_DISCARD,
1800 .type = QEMU_OPT_STRING,
1801 .help = "discard operation (ignore/off, unmap/on)",
1804 .name = BDRV_OPT_FORCE_SHARE,
1805 .type = QEMU_OPT_BOOL,
1806 .help = "always accept other writers (default: off)",
1808 { /* end of list */ }
1812 QemuOptsList bdrv_create_opts_simple = {
1813 .name = "simple-create-opts",
1814 .head = QTAILQ_HEAD_INITIALIZER(bdrv_create_opts_simple.head),
1817 .name = BLOCK_OPT_SIZE,
1818 .type = QEMU_OPT_SIZE,
1819 .help = "Virtual disk size"
1822 .name = BLOCK_OPT_PREALLOC,
1823 .type = QEMU_OPT_STRING,
1824 .help = "Preallocation mode (allowed values: off)"
1826 { /* end of list */ }
1831 * Common part for opening disk images and files
1833 * Removes all processed options from *options.
1835 static int bdrv_open_common(BlockDriverState *bs, BlockBackend *file,
1836 QDict *options, Error **errp)
1838 int ret, open_flags;
1839 const char *filename;
1840 const char *driver_name = NULL;
1841 const char *node_name = NULL;
1842 const char *discard;
1845 Error *local_err = NULL;
1848 assert(bs->file == NULL);
1849 assert(options != NULL && bs->options != options);
1850 GLOBAL_STATE_CODE();
1852 opts = qemu_opts_create(&bdrv_runtime_opts, NULL, 0, &error_abort);
1853 if (!qemu_opts_absorb_qdict(opts, options, errp)) {
1858 update_flags_from_options(&bs->open_flags, opts);
1860 driver_name = qemu_opt_get(opts, "driver");
1861 drv = bdrv_find_format(driver_name);
1862 assert(drv != NULL);
1864 bs->force_share = qemu_opt_get_bool(opts, BDRV_OPT_FORCE_SHARE, false);
1866 if (bs->force_share && (bs->open_flags & BDRV_O_RDWR)) {
1868 BDRV_OPT_FORCE_SHARE
1869 "=on can only be used with read-only images");
1875 bdrv_refresh_filename(blk_bs(file));
1876 filename = blk_bs(file)->filename;
1879 * Caution: while qdict_get_try_str() is fine, getting
1880 * non-string types would require more care. When @options
1881 * come from -blockdev or blockdev_add, its members are typed
1882 * according to the QAPI schema, but when they come from
1883 * -drive, they're all QString.
1885 filename = qdict_get_try_str(options, "filename");
1888 if (drv->bdrv_needs_filename && (!filename || !filename[0])) {
1889 error_setg(errp, "The '%s' block driver requires a file name",
1895 trace_bdrv_open_common(bs, filename ?: "", bs->open_flags,
1898 ro = bdrv_is_read_only(bs);
1900 if (use_bdrv_whitelist && !bdrv_is_whitelisted(drv, ro)) {
1901 if (!ro && bdrv_is_whitelisted(drv, true)) {
1902 ret = bdrv_apply_auto_read_only(bs, NULL, NULL);
1908 !ro && bdrv_is_whitelisted(drv, true)
1909 ? "Driver '%s' can only be used for read-only devices"
1910 : "Driver '%s' is not whitelisted",
1916 /* bdrv_new() and bdrv_close() make it so */
1917 assert(qatomic_read(&bs->copy_on_read) == 0);
1919 if (bs->open_flags & BDRV_O_COPY_ON_READ) {
1921 bdrv_enable_copy_on_read(bs);
1923 error_setg(errp, "Can't use copy-on-read on read-only device");
1929 discard = qemu_opt_get(opts, BDRV_OPT_DISCARD);
1930 if (discard != NULL) {
1931 if (bdrv_parse_discard_flags(discard, &bs->open_flags) != 0) {
1932 error_setg(errp, "Invalid discard option");
1939 bdrv_parse_detect_zeroes(opts, bs->open_flags, &local_err);
1941 error_propagate(errp, local_err);
1946 if (filename != NULL) {
1947 pstrcpy(bs->filename, sizeof(bs->filename), filename);
1949 bs->filename[0] = '\0';
1951 pstrcpy(bs->exact_filename, sizeof(bs->exact_filename), bs->filename);
1953 /* Open the image, either directly or using a protocol */
1954 open_flags = bdrv_open_flags(bs, bs->open_flags);
1955 node_name = qemu_opt_get(opts, "node-name");
1957 assert(!drv->bdrv_file_open || file == NULL);
1958 ret = bdrv_open_driver(bs, drv, node_name, options, open_flags, errp);
1963 qemu_opts_del(opts);
1967 qemu_opts_del(opts);
1971 static QDict *parse_json_filename(const char *filename, Error **errp)
1973 QObject *options_obj;
1976 GLOBAL_STATE_CODE();
1978 ret = strstart(filename, "json:", &filename);
1981 options_obj = qobject_from_json(filename, errp);
1983 error_prepend(errp, "Could not parse the JSON options: ");
1987 options = qobject_to(QDict, options_obj);
1989 qobject_unref(options_obj);
1990 error_setg(errp, "Invalid JSON object given");
1994 qdict_flatten(options);
1999 static void parse_json_protocol(QDict *options, const char **pfilename,
2002 QDict *json_options;
2003 Error *local_err = NULL;
2004 GLOBAL_STATE_CODE();
2006 /* Parse json: pseudo-protocol */
2007 if (!*pfilename || !g_str_has_prefix(*pfilename, "json:")) {
2011 json_options = parse_json_filename(*pfilename, &local_err);
2013 error_propagate(errp, local_err);
2017 /* Options given in the filename have lower priority than options
2018 * specified directly */
2019 qdict_join(options, json_options, false);
2020 qobject_unref(json_options);
2025 * Fills in default options for opening images and converts the legacy
2026 * filename/flags pair to option QDict entries.
2027 * The BDRV_O_PROTOCOL flag in *flags will be set or cleared accordingly if a
2028 * block driver has been specified explicitly.
2030 static int bdrv_fill_options(QDict **options, const char *filename,
2031 int *flags, Error **errp)
2033 const char *drvname;
2034 bool protocol = *flags & BDRV_O_PROTOCOL;
2035 bool parse_filename = false;
2036 BlockDriver *drv = NULL;
2037 Error *local_err = NULL;
2039 GLOBAL_STATE_CODE();
2042 * Caution: while qdict_get_try_str() is fine, getting non-string
2043 * types would require more care. When @options come from
2044 * -blockdev or blockdev_add, its members are typed according to
2045 * the QAPI schema, but when they come from -drive, they're all
2048 drvname = qdict_get_try_str(*options, "driver");
2050 drv = bdrv_find_format(drvname);
2052 error_setg(errp, "Unknown driver '%s'", drvname);
2055 /* If the user has explicitly specified the driver, this choice should
2056 * override the BDRV_O_PROTOCOL flag */
2057 protocol = drv->bdrv_file_open;
2061 *flags |= BDRV_O_PROTOCOL;
2063 *flags &= ~BDRV_O_PROTOCOL;
2066 /* Translate cache options from flags into options */
2067 update_options_from_flags(*options, *flags);
2069 /* Fetch the file name from the options QDict if necessary */
2070 if (protocol && filename) {
2071 if (!qdict_haskey(*options, "filename")) {
2072 qdict_put_str(*options, "filename", filename);
2073 parse_filename = true;
2075 error_setg(errp, "Can't specify 'file' and 'filename' options at "
2081 /* Find the right block driver */
2082 /* See cautionary note on accessing @options above */
2083 filename = qdict_get_try_str(*options, "filename");
2085 if (!drvname && protocol) {
2087 drv = bdrv_find_protocol(filename, parse_filename, errp);
2092 drvname = drv->format_name;
2093 qdict_put_str(*options, "driver", drvname);
2095 error_setg(errp, "Must specify either driver or file");
2100 assert(drv || !protocol);
2102 /* Driver-specific filename parsing */
2103 if (drv && drv->bdrv_parse_filename && parse_filename) {
2104 drv->bdrv_parse_filename(filename, *options, &local_err);
2106 error_propagate(errp, local_err);
2110 if (!drv->bdrv_needs_filename) {
2111 qdict_del(*options, "filename");
2118 typedef struct BlockReopenQueueEntry {
2120 BDRVReopenState state;
2121 QTAILQ_ENTRY(BlockReopenQueueEntry) entry;
2122 } BlockReopenQueueEntry;
2125 * Return the flags that @bs will have after the reopens in @q have
2126 * successfully completed. If @q is NULL (or @bs is not contained in @q),
2127 * return the current flags.
2129 static int bdrv_reopen_get_flags(BlockReopenQueue *q, BlockDriverState *bs)
2131 BlockReopenQueueEntry *entry;
2134 QTAILQ_FOREACH(entry, q, entry) {
2135 if (entry->state.bs == bs) {
2136 return entry->state.flags;
2141 return bs->open_flags;
2144 /* Returns whether the image file can be written to after the reopen queue @q
2145 * has been successfully applied, or right now if @q is NULL. */
2146 static bool bdrv_is_writable_after_reopen(BlockDriverState *bs,
2147 BlockReopenQueue *q)
2149 int flags = bdrv_reopen_get_flags(q, bs);
2151 return (flags & (BDRV_O_RDWR | BDRV_O_INACTIVE)) == BDRV_O_RDWR;
2155 * Return whether the BDS can be written to. This is not necessarily
2156 * the same as !bdrv_is_read_only(bs), as inactivated images may not
2157 * be written to but do not count as read-only images.
2159 bool bdrv_is_writable(BlockDriverState *bs)
2162 return bdrv_is_writable_after_reopen(bs, NULL);
2165 static char *bdrv_child_user_desc(BdrvChild *c)
2167 GLOBAL_STATE_CODE();
2168 return c->klass->get_parent_desc(c);
2172 * Check that @a allows everything that @b needs. @a and @b must reference same
2175 static bool bdrv_a_allow_b(BdrvChild *a, BdrvChild *b, Error **errp)
2177 const char *child_bs_name;
2178 g_autofree char *a_user = NULL;
2179 g_autofree char *b_user = NULL;
2180 g_autofree char *perms = NULL;
2183 assert(a->bs == b->bs);
2184 GLOBAL_STATE_CODE();
2186 if ((b->perm & a->shared_perm) == b->perm) {
2190 child_bs_name = bdrv_get_node_name(b->bs);
2191 a_user = bdrv_child_user_desc(a);
2192 b_user = bdrv_child_user_desc(b);
2193 perms = bdrv_perm_names(b->perm & ~a->shared_perm);
2195 error_setg(errp, "Permission conflict on node '%s': permissions '%s' are "
2196 "both required by %s (uses node '%s' as '%s' child) and "
2197 "unshared by %s (uses node '%s' as '%s' child).",
2198 child_bs_name, perms,
2199 b_user, child_bs_name, b->name,
2200 a_user, child_bs_name, a->name);
2205 static bool bdrv_parent_perms_conflict(BlockDriverState *bs, Error **errp)
2208 GLOBAL_STATE_CODE();
2211 * During the loop we'll look at each pair twice. That's correct because
2212 * bdrv_a_allow_b() is asymmetric and we should check each pair in both
2215 QLIST_FOREACH(a, &bs->parents, next_parent) {
2216 QLIST_FOREACH(b, &bs->parents, next_parent) {
2221 if (!bdrv_a_allow_b(a, b, errp)) {
2230 static void bdrv_child_perm(BlockDriverState *bs, BlockDriverState *child_bs,
2231 BdrvChild *c, BdrvChildRole role,
2232 BlockReopenQueue *reopen_queue,
2233 uint64_t parent_perm, uint64_t parent_shared,
2234 uint64_t *nperm, uint64_t *nshared)
2236 assert(bs->drv && bs->drv->bdrv_child_perm);
2237 GLOBAL_STATE_CODE();
2238 bs->drv->bdrv_child_perm(bs, c, role, reopen_queue,
2239 parent_perm, parent_shared,
2241 /* TODO Take force_share from reopen_queue */
2242 if (child_bs && child_bs->force_share) {
2243 *nshared = BLK_PERM_ALL;
2248 * Adds the whole subtree of @bs (including @bs itself) to the @list (except for
2249 * nodes that are already in the @list, of course) so that final list is
2250 * topologically sorted. Return the result (GSList @list object is updated, so
2251 * don't use old reference after function call).
2253 * On function start @list must be already topologically sorted and for any node
2254 * in the @list the whole subtree of the node must be in the @list as well. The
2255 * simplest way to satisfy this criteria: use only result of
2256 * bdrv_topological_dfs() or NULL as @list parameter.
2258 static GSList *bdrv_topological_dfs(GSList *list, GHashTable *found,
2259 BlockDriverState *bs)
2262 g_autoptr(GHashTable) local_found = NULL;
2264 GLOBAL_STATE_CODE();
2268 found = local_found = g_hash_table_new(NULL, NULL);
2271 if (g_hash_table_contains(found, bs)) {
2274 g_hash_table_add(found, bs);
2276 QLIST_FOREACH(child, &bs->children, next) {
2277 list = bdrv_topological_dfs(list, found, child->bs);
2280 return g_slist_prepend(list, bs);
2283 typedef struct BdrvChildSetPermState {
2286 uint64_t old_shared_perm;
2287 } BdrvChildSetPermState;
2289 static void bdrv_child_set_perm_abort(void *opaque)
2291 BdrvChildSetPermState *s = opaque;
2293 GLOBAL_STATE_CODE();
2295 s->child->perm = s->old_perm;
2296 s->child->shared_perm = s->old_shared_perm;
2299 static TransactionActionDrv bdrv_child_set_pem_drv = {
2300 .abort = bdrv_child_set_perm_abort,
2304 static void bdrv_child_set_perm(BdrvChild *c, uint64_t perm,
2305 uint64_t shared, Transaction *tran)
2307 BdrvChildSetPermState *s = g_new(BdrvChildSetPermState, 1);
2308 GLOBAL_STATE_CODE();
2310 *s = (BdrvChildSetPermState) {
2312 .old_perm = c->perm,
2313 .old_shared_perm = c->shared_perm,
2317 c->shared_perm = shared;
2319 tran_add(tran, &bdrv_child_set_pem_drv, s);
2322 static void bdrv_drv_set_perm_commit(void *opaque)
2324 BlockDriverState *bs = opaque;
2325 uint64_t cumulative_perms, cumulative_shared_perms;
2326 GLOBAL_STATE_CODE();
2328 if (bs->drv->bdrv_set_perm) {
2329 bdrv_get_cumulative_perm(bs, &cumulative_perms,
2330 &cumulative_shared_perms);
2331 bs->drv->bdrv_set_perm(bs, cumulative_perms, cumulative_shared_perms);
2335 static void bdrv_drv_set_perm_abort(void *opaque)
2337 BlockDriverState *bs = opaque;
2338 GLOBAL_STATE_CODE();
2340 if (bs->drv->bdrv_abort_perm_update) {
2341 bs->drv->bdrv_abort_perm_update(bs);
2345 TransactionActionDrv bdrv_drv_set_perm_drv = {
2346 .abort = bdrv_drv_set_perm_abort,
2347 .commit = bdrv_drv_set_perm_commit,
2350 static int bdrv_drv_set_perm(BlockDriverState *bs, uint64_t perm,
2351 uint64_t shared_perm, Transaction *tran,
2354 GLOBAL_STATE_CODE();
2359 if (bs->drv->bdrv_check_perm) {
2360 int ret = bs->drv->bdrv_check_perm(bs, perm, shared_perm, errp);
2367 tran_add(tran, &bdrv_drv_set_perm_drv, bs);
2373 typedef struct BdrvReplaceChildState {
2375 BlockDriverState *old_bs;
2376 } BdrvReplaceChildState;
2378 static void GRAPH_WRLOCK bdrv_replace_child_commit(void *opaque)
2380 BdrvReplaceChildState *s = opaque;
2381 GLOBAL_STATE_CODE();
2383 bdrv_schedule_unref(s->old_bs);
2386 static void GRAPH_WRLOCK bdrv_replace_child_abort(void *opaque)
2388 BdrvReplaceChildState *s = opaque;
2389 BlockDriverState *new_bs = s->child->bs;
2391 GLOBAL_STATE_CODE();
2392 assert_bdrv_graph_writable();
2394 /* old_bs reference is transparently moved from @s to @s->child */
2395 if (!s->child->bs) {
2397 * The parents were undrained when removing old_bs from the child. New
2398 * requests can't have been made, though, because the child was empty.
2400 * TODO Make bdrv_replace_child_noperm() transactionable to avoid
2401 * undraining the parent in the first place. Once this is done, having
2402 * new_bs drained when calling bdrv_replace_child_tran() is not a
2403 * requirement any more.
2405 bdrv_parent_drained_begin_single(s->child);
2406 assert(!bdrv_parent_drained_poll_single(s->child));
2408 assert(s->child->quiesced_parent);
2409 bdrv_replace_child_noperm(s->child, s->old_bs);
2414 static TransactionActionDrv bdrv_replace_child_drv = {
2415 .commit = bdrv_replace_child_commit,
2416 .abort = bdrv_replace_child_abort,
2421 * bdrv_replace_child_tran
2423 * Note: real unref of old_bs is done only on commit.
2425 * Both @child->bs and @new_bs (if non-NULL) must be drained. @new_bs must be
2426 * kept drained until the transaction is completed.
2428 * After calling this function, the transaction @tran may only be completed
2429 * while holding a writer lock for the graph.
2431 * The function doesn't update permissions, caller is responsible for this.
2433 static void GRAPH_WRLOCK
2434 bdrv_replace_child_tran(BdrvChild *child, BlockDriverState *new_bs,
2437 BdrvReplaceChildState *s = g_new(BdrvReplaceChildState, 1);
2439 assert(child->quiesced_parent);
2440 assert(!new_bs || new_bs->quiesce_counter);
2442 *s = (BdrvReplaceChildState) {
2444 .old_bs = child->bs,
2446 tran_add(tran, &bdrv_replace_child_drv, s);
2452 bdrv_replace_child_noperm(child, new_bs);
2453 /* old_bs reference is transparently moved from @child to @s */
2457 * Refresh permissions in @bs subtree. The function is intended to be called
2458 * after some graph modification that was done without permission update.
2460 static int bdrv_node_refresh_perm(BlockDriverState *bs, BlockReopenQueue *q,
2461 Transaction *tran, Error **errp)
2463 BlockDriver *drv = bs->drv;
2466 uint64_t cumulative_perms, cumulative_shared_perms;
2467 GLOBAL_STATE_CODE();
2469 bdrv_get_cumulative_perm(bs, &cumulative_perms, &cumulative_shared_perms);
2471 /* Write permissions never work with read-only images */
2472 if ((cumulative_perms & (BLK_PERM_WRITE | BLK_PERM_WRITE_UNCHANGED)) &&
2473 !bdrv_is_writable_after_reopen(bs, q))
2475 if (!bdrv_is_writable_after_reopen(bs, NULL)) {
2476 error_setg(errp, "Block node is read-only");
2478 error_setg(errp, "Read-only block node '%s' cannot support "
2479 "read-write users", bdrv_get_node_name(bs));
2486 * Unaligned requests will automatically be aligned to bl.request_alignment
2487 * and without RESIZE we can't extend requests to write to space beyond the
2488 * end of the image, so it's required that the image size is aligned.
2490 if ((cumulative_perms & (BLK_PERM_WRITE | BLK_PERM_WRITE_UNCHANGED)) &&
2491 !(cumulative_perms & BLK_PERM_RESIZE))
2493 if ((bs->total_sectors * BDRV_SECTOR_SIZE) % bs->bl.request_alignment) {
2494 error_setg(errp, "Cannot get 'write' permission without 'resize': "
2495 "Image size is not a multiple of request "
2501 /* Check this node */
2506 ret = bdrv_drv_set_perm(bs, cumulative_perms, cumulative_shared_perms, tran,
2512 /* Drivers that never have children can omit .bdrv_child_perm() */
2513 if (!drv->bdrv_child_perm) {
2514 assert(QLIST_EMPTY(&bs->children));
2518 /* Check all children */
2519 QLIST_FOREACH(c, &bs->children, next) {
2520 uint64_t cur_perm, cur_shared;
2522 bdrv_child_perm(bs, c->bs, c, c->role, q,
2523 cumulative_perms, cumulative_shared_perms,
2524 &cur_perm, &cur_shared);
2525 bdrv_child_set_perm(c, cur_perm, cur_shared, tran);
2532 * @list is a product of bdrv_topological_dfs() (may be called several times) -
2533 * a topologically sorted subgraph.
2535 static int bdrv_do_refresh_perms(GSList *list, BlockReopenQueue *q,
2536 Transaction *tran, Error **errp)
2539 BlockDriverState *bs;
2540 GLOBAL_STATE_CODE();
2542 for ( ; list; list = list->next) {
2545 if (bdrv_parent_perms_conflict(bs, errp)) {
2549 ret = bdrv_node_refresh_perm(bs, q, tran, errp);
2559 * @list is any list of nodes. List is completed by all subtrees and
2560 * topologically sorted. It's not a problem if some node occurs in the @list
2563 static int bdrv_list_refresh_perms(GSList *list, BlockReopenQueue *q,
2564 Transaction *tran, Error **errp)
2566 g_autoptr(GHashTable) found = g_hash_table_new(NULL, NULL);
2567 g_autoptr(GSList) refresh_list = NULL;
2569 for ( ; list; list = list->next) {
2570 refresh_list = bdrv_topological_dfs(refresh_list, found, list->data);
2573 return bdrv_do_refresh_perms(refresh_list, q, tran, errp);
2576 void bdrv_get_cumulative_perm(BlockDriverState *bs, uint64_t *perm,
2577 uint64_t *shared_perm)
2580 uint64_t cumulative_perms = 0;
2581 uint64_t cumulative_shared_perms = BLK_PERM_ALL;
2583 GLOBAL_STATE_CODE();
2585 QLIST_FOREACH(c, &bs->parents, next_parent) {
2586 cumulative_perms |= c->perm;
2587 cumulative_shared_perms &= c->shared_perm;
2590 *perm = cumulative_perms;
2591 *shared_perm = cumulative_shared_perms;
2594 char *bdrv_perm_names(uint64_t perm)
2600 { BLK_PERM_CONSISTENT_READ, "consistent read" },
2601 { BLK_PERM_WRITE, "write" },
2602 { BLK_PERM_WRITE_UNCHANGED, "write unchanged" },
2603 { BLK_PERM_RESIZE, "resize" },
2607 GString *result = g_string_sized_new(30);
2608 struct perm_name *p;
2610 for (p = permissions; p->name; p++) {
2611 if (perm & p->perm) {
2612 if (result->len > 0) {
2613 g_string_append(result, ", ");
2615 g_string_append(result, p->name);
2619 return g_string_free(result, FALSE);
2623 /* @tran is allowed to be NULL. In this case no rollback is possible */
2624 static int bdrv_refresh_perms(BlockDriverState *bs, Transaction *tran,
2628 Transaction *local_tran = NULL;
2629 g_autoptr(GSList) list = bdrv_topological_dfs(NULL, NULL, bs);
2630 GLOBAL_STATE_CODE();
2633 tran = local_tran = tran_new();
2636 ret = bdrv_do_refresh_perms(list, NULL, tran, errp);
2639 tran_finalize(local_tran, ret);
2645 int bdrv_child_try_set_perm(BdrvChild *c, uint64_t perm, uint64_t shared,
2648 Error *local_err = NULL;
2649 Transaction *tran = tran_new();
2652 GLOBAL_STATE_CODE();
2654 bdrv_child_set_perm(c, perm, shared, tran);
2656 ret = bdrv_refresh_perms(c->bs, tran, &local_err);
2658 tran_finalize(tran, ret);
2661 if ((perm & ~c->perm) || (c->shared_perm & ~shared)) {
2662 /* tighten permissions */
2663 error_propagate(errp, local_err);
2666 * Our caller may intend to only loosen restrictions and
2667 * does not expect this function to fail. Errors are not
2668 * fatal in such a case, so we can just hide them from our
2671 error_free(local_err);
2679 int bdrv_child_refresh_perms(BlockDriverState *bs, BdrvChild *c, Error **errp)
2681 uint64_t parent_perms, parent_shared;
2682 uint64_t perms, shared;
2684 GLOBAL_STATE_CODE();
2686 bdrv_get_cumulative_perm(bs, &parent_perms, &parent_shared);
2687 bdrv_child_perm(bs, c->bs, c, c->role, NULL,
2688 parent_perms, parent_shared, &perms, &shared);
2690 return bdrv_child_try_set_perm(c, perms, shared, errp);
2694 * Default implementation for .bdrv_child_perm() for block filters:
2695 * Forward CONSISTENT_READ, WRITE, WRITE_UNCHANGED, and RESIZE to the
2698 static void bdrv_filter_default_perms(BlockDriverState *bs, BdrvChild *c,
2700 BlockReopenQueue *reopen_queue,
2701 uint64_t perm, uint64_t shared,
2702 uint64_t *nperm, uint64_t *nshared)
2704 GLOBAL_STATE_CODE();
2705 *nperm = perm & DEFAULT_PERM_PASSTHROUGH;
2706 *nshared = (shared & DEFAULT_PERM_PASSTHROUGH) | DEFAULT_PERM_UNCHANGED;
2709 static void bdrv_default_perms_for_cow(BlockDriverState *bs, BdrvChild *c,
2711 BlockReopenQueue *reopen_queue,
2712 uint64_t perm, uint64_t shared,
2713 uint64_t *nperm, uint64_t *nshared)
2715 assert(role & BDRV_CHILD_COW);
2716 GLOBAL_STATE_CODE();
2719 * We want consistent read from backing files if the parent needs it.
2720 * No other operations are performed on backing files.
2722 perm &= BLK_PERM_CONSISTENT_READ;
2725 * If the parent can deal with changing data, we're okay with a
2726 * writable and resizable backing file.
2727 * TODO Require !(perm & BLK_PERM_CONSISTENT_READ), too?
2729 if (shared & BLK_PERM_WRITE) {
2730 shared = BLK_PERM_WRITE | BLK_PERM_RESIZE;
2735 shared |= BLK_PERM_CONSISTENT_READ | BLK_PERM_WRITE_UNCHANGED;
2737 if (bs->open_flags & BDRV_O_INACTIVE) {
2738 shared |= BLK_PERM_WRITE | BLK_PERM_RESIZE;
2745 static void bdrv_default_perms_for_storage(BlockDriverState *bs, BdrvChild *c,
2747 BlockReopenQueue *reopen_queue,
2748 uint64_t perm, uint64_t shared,
2749 uint64_t *nperm, uint64_t *nshared)
2753 GLOBAL_STATE_CODE();
2754 assert(role & (BDRV_CHILD_METADATA | BDRV_CHILD_DATA));
2756 flags = bdrv_reopen_get_flags(reopen_queue, bs);
2759 * Apart from the modifications below, the same permissions are
2760 * forwarded and left alone as for filters
2762 bdrv_filter_default_perms(bs, c, role, reopen_queue,
2763 perm, shared, &perm, &shared);
2765 if (role & BDRV_CHILD_METADATA) {
2766 /* Format drivers may touch metadata even if the guest doesn't write */
2767 if (bdrv_is_writable_after_reopen(bs, reopen_queue)) {
2768 perm |= BLK_PERM_WRITE | BLK_PERM_RESIZE;
2772 * bs->file always needs to be consistent because of the
2773 * metadata. We can never allow other users to resize or write
2776 if (!(flags & BDRV_O_NO_IO)) {
2777 perm |= BLK_PERM_CONSISTENT_READ;
2779 shared &= ~(BLK_PERM_WRITE | BLK_PERM_RESIZE);
2782 if (role & BDRV_CHILD_DATA) {
2784 * Technically, everything in this block is a subset of the
2785 * BDRV_CHILD_METADATA path taken above, and so this could
2786 * be an "else if" branch. However, that is not obvious, and
2787 * this function is not performance critical, therefore we let
2788 * this be an independent "if".
2792 * We cannot allow other users to resize the file because the
2793 * format driver might have some assumptions about the size
2794 * (e.g. because it is stored in metadata, or because the file
2795 * is split into fixed-size data files).
2797 shared &= ~BLK_PERM_RESIZE;
2800 * WRITE_UNCHANGED often cannot be performed as such on the
2801 * data file. For example, the qcow2 driver may still need to
2802 * write copied clusters on copy-on-read.
2804 if (perm & BLK_PERM_WRITE_UNCHANGED) {
2805 perm |= BLK_PERM_WRITE;
2809 * If the data file is written to, the format driver may
2810 * expect to be able to resize it by writing beyond the EOF.
2812 if (perm & BLK_PERM_WRITE) {
2813 perm |= BLK_PERM_RESIZE;
2817 if (bs->open_flags & BDRV_O_INACTIVE) {
2818 shared |= BLK_PERM_WRITE | BLK_PERM_RESIZE;
2825 void bdrv_default_perms(BlockDriverState *bs, BdrvChild *c,
2826 BdrvChildRole role, BlockReopenQueue *reopen_queue,
2827 uint64_t perm, uint64_t shared,
2828 uint64_t *nperm, uint64_t *nshared)
2830 GLOBAL_STATE_CODE();
2831 if (role & BDRV_CHILD_FILTERED) {
2832 assert(!(role & (BDRV_CHILD_DATA | BDRV_CHILD_METADATA |
2834 bdrv_filter_default_perms(bs, c, role, reopen_queue,
2835 perm, shared, nperm, nshared);
2836 } else if (role & BDRV_CHILD_COW) {
2837 assert(!(role & (BDRV_CHILD_DATA | BDRV_CHILD_METADATA)));
2838 bdrv_default_perms_for_cow(bs, c, role, reopen_queue,
2839 perm, shared, nperm, nshared);
2840 } else if (role & (BDRV_CHILD_METADATA | BDRV_CHILD_DATA)) {
2841 bdrv_default_perms_for_storage(bs, c, role, reopen_queue,
2842 perm, shared, nperm, nshared);
2844 g_assert_not_reached();
2848 uint64_t bdrv_qapi_perm_to_blk_perm(BlockPermission qapi_perm)
2850 static const uint64_t permissions[] = {
2851 [BLOCK_PERMISSION_CONSISTENT_READ] = BLK_PERM_CONSISTENT_READ,
2852 [BLOCK_PERMISSION_WRITE] = BLK_PERM_WRITE,
2853 [BLOCK_PERMISSION_WRITE_UNCHANGED] = BLK_PERM_WRITE_UNCHANGED,
2854 [BLOCK_PERMISSION_RESIZE] = BLK_PERM_RESIZE,
2857 QEMU_BUILD_BUG_ON(ARRAY_SIZE(permissions) != BLOCK_PERMISSION__MAX);
2858 QEMU_BUILD_BUG_ON(1UL << ARRAY_SIZE(permissions) != BLK_PERM_ALL + 1);
2860 assert(qapi_perm < BLOCK_PERMISSION__MAX);
2862 return permissions[qapi_perm];
2866 * Replaces the node that a BdrvChild points to without updating permissions.
2868 * If @new_bs is non-NULL, the parent of @child must already be drained through
2869 * @child and the caller must hold the AioContext lock for @new_bs.
2871 static void GRAPH_WRLOCK
2872 bdrv_replace_child_noperm(BdrvChild *child, BlockDriverState *new_bs)
2874 BlockDriverState *old_bs = child->bs;
2875 int new_bs_quiesce_counter;
2877 assert(!child->frozen);
2880 * If we want to change the BdrvChild to point to a drained node as its new
2881 * child->bs, we need to make sure that its new parent is drained, too. In
2882 * other words, either child->quiesce_parent must already be true or we must
2883 * be able to set it and keep the parent's quiesce_counter consistent with
2884 * that, but without polling or starting new requests (this function
2885 * guarantees that it doesn't poll, and starting new requests would be
2886 * against the invariants of drain sections).
2888 * To keep things simple, we pick the first option (child->quiesce_parent
2889 * must already be true). We also generalise the rule a bit to make it
2890 * easier to verify in callers and more likely to be covered in test cases:
2891 * The parent must be quiesced through this child even if new_bs isn't
2892 * currently drained.
2894 * The only exception is for callers that always pass new_bs == NULL. In
2895 * this case, we obviously never need to consider the case of a drained
2896 * new_bs, so we can keep the callers simpler by allowing them not to drain
2899 assert(!new_bs || child->quiesced_parent);
2900 assert(old_bs != new_bs);
2901 GLOBAL_STATE_CODE();
2903 if (old_bs && new_bs) {
2904 assert(bdrv_get_aio_context(old_bs) == bdrv_get_aio_context(new_bs));
2908 if (child->klass->detach) {
2909 child->klass->detach(child);
2911 QLIST_REMOVE(child, next_parent);
2917 QLIST_INSERT_HEAD(&new_bs->parents, child, next_parent);
2918 if (child->klass->attach) {
2919 child->klass->attach(child);
2924 * If the parent was drained through this BdrvChild previously, but new_bs
2925 * is not drained, allow requests to come in only after the new node has
2928 new_bs_quiesce_counter = (new_bs ? new_bs->quiesce_counter : 0);
2929 if (!new_bs_quiesce_counter && child->quiesced_parent) {
2930 bdrv_parent_drained_end_single(child);
2935 * Free the given @child.
2937 * The child must be empty (i.e. `child->bs == NULL`) and it must be
2938 * unused (i.e. not in a children list).
2940 static void bdrv_child_free(BdrvChild *child)
2943 GLOBAL_STATE_CODE();
2944 assert(!child->next.le_prev); /* not in children list */
2946 g_free(child->name);
2950 typedef struct BdrvAttachChildCommonState {
2952 AioContext *old_parent_ctx;
2953 AioContext *old_child_ctx;
2954 } BdrvAttachChildCommonState;
2956 static void GRAPH_WRLOCK bdrv_attach_child_common_abort(void *opaque)
2958 BdrvAttachChildCommonState *s = opaque;
2959 BlockDriverState *bs = s->child->bs;
2961 GLOBAL_STATE_CODE();
2962 assert_bdrv_graph_writable();
2964 bdrv_replace_child_noperm(s->child, NULL);
2966 if (bdrv_get_aio_context(bs) != s->old_child_ctx) {
2967 bdrv_try_change_aio_context(bs, s->old_child_ctx, NULL, &error_abort);
2970 if (bdrv_child_get_parent_aio_context(s->child) != s->old_parent_ctx) {
2972 GHashTable *visited;
2977 /* No need to visit `child`, because it has been detached already */
2978 visited = g_hash_table_new(NULL, NULL);
2979 ret = s->child->klass->change_aio_ctx(s->child, s->old_parent_ctx,
2980 visited, tran, &error_abort);
2981 g_hash_table_destroy(visited);
2983 /* transaction is supposed to always succeed */
2984 assert(ret == true);
2988 bdrv_schedule_unref(bs);
2989 bdrv_child_free(s->child);
2992 static TransactionActionDrv bdrv_attach_child_common_drv = {
2993 .abort = bdrv_attach_child_common_abort,
2998 * Common part of attaching bdrv child to bs or to blk or to job
3000 * Function doesn't update permissions, caller is responsible for this.
3002 * After calling this function, the transaction @tran may only be completed
3003 * while holding a writer lock for the graph.
3005 * Returns new created child.
3007 * The caller must hold the AioContext lock for @child_bs. Both @parent_bs and
3008 * @child_bs can move to a different AioContext in this function. Callers must
3009 * make sure that their AioContext locking is still correct after this.
3011 static BdrvChild * GRAPH_WRLOCK
3012 bdrv_attach_child_common(BlockDriverState *child_bs,
3013 const char *child_name,
3014 const BdrvChildClass *child_class,
3015 BdrvChildRole child_role,
3016 uint64_t perm, uint64_t shared_perm,
3018 Transaction *tran, Error **errp)
3020 BdrvChild *new_child;
3021 AioContext *parent_ctx, *new_child_ctx;
3022 AioContext *child_ctx = bdrv_get_aio_context(child_bs);
3024 assert(child_class->get_parent_desc);
3025 GLOBAL_STATE_CODE();
3027 new_child = g_new(BdrvChild, 1);
3028 *new_child = (BdrvChild) {
3030 .name = g_strdup(child_name),
3031 .klass = child_class,
3034 .shared_perm = shared_perm,
3039 * If the AioContexts don't match, first try to move the subtree of
3040 * child_bs into the AioContext of the new parent. If this doesn't work,
3041 * try moving the parent into the AioContext of child_bs instead.
3043 parent_ctx = bdrv_child_get_parent_aio_context(new_child);
3044 if (child_ctx != parent_ctx) {
3045 Error *local_err = NULL;
3046 int ret = bdrv_try_change_aio_context(child_bs, parent_ctx, NULL,
3049 if (ret < 0 && child_class->change_aio_ctx) {
3050 Transaction *tran = tran_new();
3051 GHashTable *visited = g_hash_table_new(NULL, NULL);
3054 g_hash_table_add(visited, new_child);
3055 ret_child = child_class->change_aio_ctx(new_child, child_ctx,
3056 visited, tran, NULL);
3057 if (ret_child == true) {
3058 error_free(local_err);
3061 tran_finalize(tran, ret_child == true ? 0 : -1);
3062 g_hash_table_destroy(visited);
3066 error_propagate(errp, local_err);
3067 bdrv_child_free(new_child);
3072 new_child_ctx = bdrv_get_aio_context(child_bs);
3073 if (new_child_ctx != child_ctx) {
3074 aio_context_release(child_ctx);
3075 aio_context_acquire(new_child_ctx);
3080 * Let every new BdrvChild start with a drained parent. Inserting the child
3081 * in the graph with bdrv_replace_child_noperm() will undrain it if
3082 * @child_bs is not drained.
3084 * The child was only just created and is not yet visible in global state
3085 * until bdrv_replace_child_noperm() inserts it into the graph, so nobody
3086 * could have sent requests and polling is not necessary.
3088 * Note that this means that the parent isn't fully drained yet, we only
3089 * stop new requests from coming in. This is fine, we don't care about the
3090 * old requests here, they are not for this child. If another place enters a
3091 * drain section for the same parent, but wants it to be fully quiesced, it
3092 * will not run most of the the code in .drained_begin() again (which is not
3093 * a problem, we already did this), but it will still poll until the parent
3094 * is fully quiesced, so it will not be negatively affected either.
3096 bdrv_parent_drained_begin_single(new_child);
3097 bdrv_replace_child_noperm(new_child, child_bs);
3099 BdrvAttachChildCommonState *s = g_new(BdrvAttachChildCommonState, 1);
3100 *s = (BdrvAttachChildCommonState) {
3102 .old_parent_ctx = parent_ctx,
3103 .old_child_ctx = child_ctx,
3105 tran_add(tran, &bdrv_attach_child_common_drv, s);
3107 if (new_child_ctx != child_ctx) {
3108 aio_context_release(new_child_ctx);
3109 aio_context_acquire(child_ctx);
3116 * Function doesn't update permissions, caller is responsible for this.
3118 * The caller must hold the AioContext lock for @child_bs. Both @parent_bs and
3119 * @child_bs can move to a different AioContext in this function. Callers must
3120 * make sure that their AioContext locking is still correct after this.
3122 * After calling this function, the transaction @tran may only be completed
3123 * while holding a writer lock for the graph.
3125 static BdrvChild * GRAPH_WRLOCK
3126 bdrv_attach_child_noperm(BlockDriverState *parent_bs,
3127 BlockDriverState *child_bs,
3128 const char *child_name,
3129 const BdrvChildClass *child_class,
3130 BdrvChildRole child_role,
3134 uint64_t perm, shared_perm;
3136 assert(parent_bs->drv);
3137 GLOBAL_STATE_CODE();
3139 if (bdrv_recurse_has_child(child_bs, parent_bs)) {
3140 error_setg(errp, "Making '%s' a %s child of '%s' would create a cycle",
3141 child_bs->node_name, child_name, parent_bs->node_name);
3145 bdrv_get_cumulative_perm(parent_bs, &perm, &shared_perm);
3146 bdrv_child_perm(parent_bs, child_bs, NULL, child_role, NULL,
3147 perm, shared_perm, &perm, &shared_perm);
3149 return bdrv_attach_child_common(child_bs, child_name, child_class,
3150 child_role, perm, shared_perm, parent_bs,
3155 * This function steals the reference to child_bs from the caller.
3156 * That reference is later dropped by bdrv_root_unref_child().
3158 * On failure NULL is returned, errp is set and the reference to
3159 * child_bs is also dropped.
3161 * The caller must hold the AioContext lock @child_bs, but not that of @ctx
3162 * (unless @child_bs is already in @ctx).
3164 BdrvChild *bdrv_root_attach_child(BlockDriverState *child_bs,
3165 const char *child_name,
3166 const BdrvChildClass *child_class,
3167 BdrvChildRole child_role,
3168 uint64_t perm, uint64_t shared_perm,
3169 void *opaque, Error **errp)
3173 Transaction *tran = tran_new();
3175 GLOBAL_STATE_CODE();
3177 bdrv_graph_wrlock(child_bs);
3179 child = bdrv_attach_child_common(child_bs, child_name, child_class,
3180 child_role, perm, shared_perm, opaque,
3187 ret = bdrv_refresh_perms(child_bs, tran, errp);
3190 tran_finalize(tran, ret);
3191 bdrv_graph_wrunlock();
3193 bdrv_unref(child_bs);
3195 return ret < 0 ? NULL : child;
3199 * This function transfers the reference to child_bs from the caller
3200 * to parent_bs. That reference is later dropped by parent_bs on
3201 * bdrv_close() or if someone calls bdrv_unref_child().
3203 * On failure NULL is returned, errp is set and the reference to
3204 * child_bs is also dropped.
3206 * If @parent_bs and @child_bs are in different AioContexts, the caller must
3207 * hold the AioContext lock for @child_bs, but not for @parent_bs.
3209 BdrvChild *bdrv_attach_child(BlockDriverState *parent_bs,
3210 BlockDriverState *child_bs,
3211 const char *child_name,
3212 const BdrvChildClass *child_class,
3213 BdrvChildRole child_role,
3218 Transaction *tran = tran_new();
3220 GLOBAL_STATE_CODE();
3222 bdrv_graph_wrlock(child_bs);
3224 child = bdrv_attach_child_noperm(parent_bs, child_bs, child_name,
3225 child_class, child_role, tran, errp);
3231 ret = bdrv_refresh_perms(parent_bs, tran, errp);
3237 tran_finalize(tran, ret);
3238 bdrv_graph_wrunlock();
3240 bdrv_unref(child_bs);
3242 return ret < 0 ? NULL : child;
3245 /* Callers must ensure that child->frozen is false. */
3246 void bdrv_root_unref_child(BdrvChild *child)
3248 BlockDriverState *child_bs = child->bs;
3250 GLOBAL_STATE_CODE();
3251 bdrv_graph_wrlock(NULL);
3252 bdrv_replace_child_noperm(child, NULL);
3253 bdrv_graph_wrunlock();
3254 bdrv_child_free(child);
3258 * Update permissions for old node. We're just taking a parent away, so
3259 * we're loosening restrictions. Errors of permission update are not
3260 * fatal in this case, ignore them.
3262 bdrv_refresh_perms(child_bs, NULL, NULL);
3265 * When the parent requiring a non-default AioContext is removed, the
3266 * node moves back to the main AioContext
3268 bdrv_try_change_aio_context(child_bs, qemu_get_aio_context(), NULL,
3272 bdrv_unref(child_bs);
3275 typedef struct BdrvSetInheritsFrom {
3276 BlockDriverState *bs;
3277 BlockDriverState *old_inherits_from;
3278 } BdrvSetInheritsFrom;
3280 static void bdrv_set_inherits_from_abort(void *opaque)
3282 BdrvSetInheritsFrom *s = opaque;
3284 s->bs->inherits_from = s->old_inherits_from;
3287 static TransactionActionDrv bdrv_set_inherits_from_drv = {
3288 .abort = bdrv_set_inherits_from_abort,
3292 /* @tran is allowed to be NULL. In this case no rollback is possible */
3293 static void bdrv_set_inherits_from(BlockDriverState *bs,
3294 BlockDriverState *new_inherits_from,
3298 BdrvSetInheritsFrom *s = g_new(BdrvSetInheritsFrom, 1);
3300 *s = (BdrvSetInheritsFrom) {
3302 .old_inherits_from = bs->inherits_from,
3305 tran_add(tran, &bdrv_set_inherits_from_drv, s);
3308 bs->inherits_from = new_inherits_from;
3312 * Clear all inherits_from pointers from children and grandchildren of
3313 * @root that point to @root, where necessary.
3314 * @tran is allowed to be NULL. In this case no rollback is possible
3316 static void bdrv_unset_inherits_from(BlockDriverState *root, BdrvChild *child,
3321 if (child->bs->inherits_from == root) {
3323 * Remove inherits_from only when the last reference between root and
3324 * child->bs goes away.
3326 QLIST_FOREACH(c, &root->children, next) {
3327 if (c != child && c->bs == child->bs) {
3332 bdrv_set_inherits_from(child->bs, NULL, tran);
3336 QLIST_FOREACH(c, &child->bs->children, next) {
3337 bdrv_unset_inherits_from(root, c, tran);
3341 /* Callers must ensure that child->frozen is false. */
3342 void bdrv_unref_child(BlockDriverState *parent, BdrvChild *child)
3344 GLOBAL_STATE_CODE();
3345 if (child == NULL) {
3349 bdrv_unset_inherits_from(parent, child, NULL);
3350 bdrv_root_unref_child(child);
3354 static void bdrv_parent_cb_change_media(BlockDriverState *bs, bool load)
3357 GLOBAL_STATE_CODE();
3358 QLIST_FOREACH(c, &bs->parents, next_parent) {
3359 if (c->klass->change_media) {
3360 c->klass->change_media(c, load);
3365 /* Return true if you can reach parent going through child->inherits_from
3366 * recursively. If parent or child are NULL, return false */
3367 static bool bdrv_inherits_from_recursive(BlockDriverState *child,
3368 BlockDriverState *parent)
3370 while (child && child != parent) {
3371 child = child->inherits_from;
3374 return child != NULL;
3378 * Return the BdrvChildRole for @bs's backing child. bs->backing is
3379 * mostly used for COW backing children (role = COW), but also for
3380 * filtered children (role = FILTERED | PRIMARY).
3382 static BdrvChildRole bdrv_backing_role(BlockDriverState *bs)
3384 if (bs->drv && bs->drv->is_filter) {
3385 return BDRV_CHILD_FILTERED | BDRV_CHILD_PRIMARY;
3387 return BDRV_CHILD_COW;
3392 * Sets the bs->backing or bs->file link of a BDS. A new reference is created;
3393 * callers which don't need their own reference any more must call bdrv_unref().
3395 * If the respective child is already present (i.e. we're detaching a node),
3396 * that child node must be drained.
3398 * Function doesn't update permissions, caller is responsible for this.
3400 * The caller must hold the AioContext lock for @child_bs. Both @parent_bs and
3401 * @child_bs can move to a different AioContext in this function. Callers must
3402 * make sure that their AioContext locking is still correct after this.
3404 * After calling this function, the transaction @tran may only be completed
3405 * while holding a writer lock for the graph.
3407 static int GRAPH_WRLOCK
3408 bdrv_set_file_or_backing_noperm(BlockDriverState *parent_bs,
3409 BlockDriverState *child_bs,
3411 Transaction *tran, Error **errp)
3413 bool update_inherits_from =
3414 bdrv_inherits_from_recursive(child_bs, parent_bs);
3415 BdrvChild *child = is_backing ? parent_bs->backing : parent_bs->file;
3418 GLOBAL_STATE_CODE();
3420 if (!parent_bs->drv) {
3422 * Node without drv is an object without a class :/. TODO: finally fix
3423 * qcow2 driver to never clear bs->drv and implement format corruption
3424 * handling in other way.
3426 error_setg(errp, "Node corrupted");
3430 if (child && child->frozen) {
3431 error_setg(errp, "Cannot change frozen '%s' link from '%s' to '%s'",
3432 child->name, parent_bs->node_name, child->bs->node_name);
3436 if (is_backing && !parent_bs->drv->is_filter &&
3437 !parent_bs->drv->supports_backing)
3439 error_setg(errp, "Driver '%s' of node '%s' does not support backing "
3440 "files", parent_bs->drv->format_name, parent_bs->node_name);
3444 if (parent_bs->drv->is_filter) {
3445 role = BDRV_CHILD_FILTERED | BDRV_CHILD_PRIMARY;
3446 } else if (is_backing) {
3447 role = BDRV_CHILD_COW;
3450 * We only can use same role as it is in existing child. We don't have
3451 * infrastructure to determine role of file child in generic way
3454 error_setg(errp, "Cannot set file child to format node without "
3462 assert(child->bs->quiesce_counter);
3463 bdrv_unset_inherits_from(parent_bs, child, tran);
3464 bdrv_remove_child(child, tran);
3471 child = bdrv_attach_child_noperm(parent_bs, child_bs,
3472 is_backing ? "backing" : "file",
3473 &child_of_bds, role,
3481 * If inherits_from pointed recursively to bs then let's update it to
3482 * point directly to bs (else it will become NULL).
3484 if (update_inherits_from) {
3485 bdrv_set_inherits_from(child_bs, parent_bs, tran);
3489 bdrv_refresh_limits(parent_bs, tran, NULL);
3495 * The caller must hold the AioContext lock for @backing_hd. Both @bs and
3496 * @backing_hd can move to a different AioContext in this function. Callers must
3497 * make sure that their AioContext locking is still correct after this.
3499 * If a backing child is already present (i.e. we're detaching a node), that
3500 * child node must be drained.
3502 * After calling this function, the transaction @tran may only be completed
3503 * while holding a writer lock for the graph.
3505 static int GRAPH_WRLOCK
3506 bdrv_set_backing_noperm(BlockDriverState *bs,
3507 BlockDriverState *backing_hd,
3508 Transaction *tran, Error **errp)
3510 GLOBAL_STATE_CODE();
3511 return bdrv_set_file_or_backing_noperm(bs, backing_hd, true, tran, errp);
3514 int bdrv_set_backing_hd_drained(BlockDriverState *bs,
3515 BlockDriverState *backing_hd,
3519 Transaction *tran = tran_new();
3521 GLOBAL_STATE_CODE();
3522 assert(bs->quiesce_counter > 0);
3524 assert(bs->backing->bs->quiesce_counter > 0);
3526 bdrv_graph_wrlock(backing_hd);
3528 ret = bdrv_set_backing_noperm(bs, backing_hd, tran, errp);
3533 ret = bdrv_refresh_perms(bs, tran, errp);
3535 tran_finalize(tran, ret);
3536 bdrv_graph_wrunlock();
3540 int bdrv_set_backing_hd(BlockDriverState *bs, BlockDriverState *backing_hd,
3543 BlockDriverState *drain_bs = bs->backing ? bs->backing->bs : bs;
3545 GLOBAL_STATE_CODE();
3548 bdrv_drained_begin(drain_bs);
3549 ret = bdrv_set_backing_hd_drained(bs, backing_hd, errp);
3550 bdrv_drained_end(drain_bs);
3551 bdrv_unref(drain_bs);
3557 * Opens the backing file for a BlockDriverState if not yet open
3559 * bdref_key specifies the key for the image's BlockdevRef in the options QDict.
3560 * That QDict has to be flattened; therefore, if the BlockdevRef is a QDict
3561 * itself, all options starting with "${bdref_key}." are considered part of the
3564 * The caller must hold the main AioContext lock.
3566 * TODO Can this be unified with bdrv_open_image()?
3568 int bdrv_open_backing_file(BlockDriverState *bs, QDict *parent_options,
3569 const char *bdref_key, Error **errp)
3571 char *backing_filename = NULL;
3572 char *bdref_key_dot;
3573 const char *reference = NULL;
3575 bool implicit_backing = false;
3576 BlockDriverState *backing_hd;
3577 AioContext *backing_hd_ctx;
3579 QDict *tmp_parent_options = NULL;
3580 Error *local_err = NULL;
3582 GLOBAL_STATE_CODE();
3584 if (bs->backing != NULL) {
3588 /* NULL means an empty set of options */
3589 if (parent_options == NULL) {
3590 tmp_parent_options = qdict_new();
3591 parent_options = tmp_parent_options;
3594 bs->open_flags &= ~BDRV_O_NO_BACKING;
3596 bdref_key_dot = g_strdup_printf("%s.", bdref_key);
3597 qdict_extract_subqdict(parent_options, &options, bdref_key_dot);
3598 g_free(bdref_key_dot);
3601 * Caution: while qdict_get_try_str() is fine, getting non-string
3602 * types would require more care. When @parent_options come from
3603 * -blockdev or blockdev_add, its members are typed according to
3604 * the QAPI schema, but when they come from -drive, they're all
3607 reference = qdict_get_try_str(parent_options, bdref_key);
3608 if (reference || qdict_haskey(options, "file.filename")) {
3609 /* keep backing_filename NULL */
3610 } else if (bs->backing_file[0] == '\0' && qdict_size(options) == 0) {
3611 qobject_unref(options);
3614 if (qdict_size(options) == 0) {
3615 /* If the user specifies options that do not modify the
3616 * backing file's behavior, we might still consider it the
3617 * implicit backing file. But it's easier this way, and
3618 * just specifying some of the backing BDS's options is
3619 * only possible with -drive anyway (otherwise the QAPI
3620 * schema forces the user to specify everything). */
3621 implicit_backing = !strcmp(bs->auto_backing_file, bs->backing_file);
3624 backing_filename = bdrv_get_full_backing_filename(bs, &local_err);
3627 error_propagate(errp, local_err);
3628 qobject_unref(options);
3633 if (!bs->drv || !bs->drv->supports_backing) {
3635 error_setg(errp, "Driver doesn't support backing files");
3636 qobject_unref(options);
3641 bs->backing_format[0] != '\0' && !qdict_haskey(options, "driver")) {
3642 qdict_put_str(options, "driver", bs->backing_format);
3645 backing_hd = bdrv_open_inherit(backing_filename, reference, options, 0, bs,
3646 &child_of_bds, bdrv_backing_role(bs), errp);
3648 bs->open_flags |= BDRV_O_NO_BACKING;
3649 error_prepend(errp, "Could not open backing file: ");
3654 if (implicit_backing) {
3655 bdrv_refresh_filename(backing_hd);
3656 pstrcpy(bs->auto_backing_file, sizeof(bs->auto_backing_file),
3657 backing_hd->filename);
3660 /* Hook up the backing file link; drop our reference, bs owns the
3661 * backing_hd reference now */
3662 backing_hd_ctx = bdrv_get_aio_context(backing_hd);
3663 aio_context_acquire(backing_hd_ctx);
3664 ret = bdrv_set_backing_hd(bs, backing_hd, errp);
3665 bdrv_unref(backing_hd);
3666 aio_context_release(backing_hd_ctx);
3672 qdict_del(parent_options, bdref_key);
3675 g_free(backing_filename);
3676 qobject_unref(tmp_parent_options);
3680 static BlockDriverState *
3681 bdrv_open_child_bs(const char *filename, QDict *options, const char *bdref_key,
3682 BlockDriverState *parent, const BdrvChildClass *child_class,
3683 BdrvChildRole child_role, bool allow_none, Error **errp)
3685 BlockDriverState *bs = NULL;
3686 QDict *image_options;
3687 char *bdref_key_dot;
3688 const char *reference;
3690 assert(child_class != NULL);
3692 bdref_key_dot = g_strdup_printf("%s.", bdref_key);
3693 qdict_extract_subqdict(options, &image_options, bdref_key_dot);
3694 g_free(bdref_key_dot);
3697 * Caution: while qdict_get_try_str() is fine, getting non-string
3698 * types would require more care. When @options come from
3699 * -blockdev or blockdev_add, its members are typed according to
3700 * the QAPI schema, but when they come from -drive, they're all
3703 reference = qdict_get_try_str(options, bdref_key);
3704 if (!filename && !reference && !qdict_size(image_options)) {
3706 error_setg(errp, "A block device must be specified for \"%s\"",
3709 qobject_unref(image_options);
3713 bs = bdrv_open_inherit(filename, reference, image_options, 0,
3714 parent, child_class, child_role, errp);
3720 qdict_del(options, bdref_key);
3725 * Opens a disk image whose options are given as BlockdevRef in another block
3728 * If allow_none is true, no image will be opened if filename is false and no
3729 * BlockdevRef is given. NULL will be returned, but errp remains unset.
3731 * bdrev_key specifies the key for the image's BlockdevRef in the options QDict.
3732 * That QDict has to be flattened; therefore, if the BlockdevRef is a QDict
3733 * itself, all options starting with "${bdref_key}." are considered part of the
3736 * The BlockdevRef will be removed from the options QDict.
3738 * The caller must hold the lock of the main AioContext and no other AioContext.
3739 * @parent can move to a different AioContext in this function. Callers must
3740 * make sure that their AioContext locking is still correct after this.
3742 BdrvChild *bdrv_open_child(const char *filename,
3743 QDict *options, const char *bdref_key,
3744 BlockDriverState *parent,
3745 const BdrvChildClass *child_class,
3746 BdrvChildRole child_role,
3747 bool allow_none, Error **errp)
3749 BlockDriverState *bs;
3753 GLOBAL_STATE_CODE();
3755 bs = bdrv_open_child_bs(filename, options, bdref_key, parent, child_class,
3756 child_role, allow_none, errp);
3761 ctx = bdrv_get_aio_context(bs);
3762 aio_context_acquire(ctx);
3763 child = bdrv_attach_child(parent, bs, bdref_key, child_class, child_role,
3765 aio_context_release(ctx);
3771 * Wrapper on bdrv_open_child() for most popular case: open primary child of bs.
3773 * The caller must hold the lock of the main AioContext and no other AioContext.
3774 * @parent can move to a different AioContext in this function. Callers must
3775 * make sure that their AioContext locking is still correct after this.
3777 int bdrv_open_file_child(const char *filename,
3778 QDict *options, const char *bdref_key,
3779 BlockDriverState *parent, Error **errp)
3783 /* commit_top and mirror_top don't use this function */
3784 assert(!parent->drv->filtered_child_is_backing);
3785 role = parent->drv->is_filter ?
3786 (BDRV_CHILD_FILTERED | BDRV_CHILD_PRIMARY) : BDRV_CHILD_IMAGE;
3788 if (!bdrv_open_child(filename, options, bdref_key, parent,
3789 &child_of_bds, role, false, errp))
3798 * TODO Future callers may need to specify parent/child_class in order for
3799 * option inheritance to work. Existing callers use it for the root node.
3801 BlockDriverState *bdrv_open_blockdev_ref(BlockdevRef *ref, Error **errp)
3803 BlockDriverState *bs = NULL;
3804 QObject *obj = NULL;
3805 QDict *qdict = NULL;
3806 const char *reference = NULL;
3809 GLOBAL_STATE_CODE();
3811 if (ref->type == QTYPE_QSTRING) {
3812 reference = ref->u.reference;
3814 BlockdevOptions *options = &ref->u.definition;
3815 assert(ref->type == QTYPE_QDICT);
3817 v = qobject_output_visitor_new(&obj);
3818 visit_type_BlockdevOptions(v, NULL, &options, &error_abort);
3819 visit_complete(v, &obj);
3821 qdict = qobject_to(QDict, obj);
3822 qdict_flatten(qdict);
3824 /* bdrv_open_inherit() defaults to the values in bdrv_flags (for
3825 * compatibility with other callers) rather than what we want as the
3826 * real defaults. Apply the defaults here instead. */
3827 qdict_set_default_str(qdict, BDRV_OPT_CACHE_DIRECT, "off");
3828 qdict_set_default_str(qdict, BDRV_OPT_CACHE_NO_FLUSH, "off");
3829 qdict_set_default_str(qdict, BDRV_OPT_READ_ONLY, "off");
3830 qdict_set_default_str(qdict, BDRV_OPT_AUTO_READ_ONLY, "off");
3834 bs = bdrv_open_inherit(NULL, reference, qdict, 0, NULL, NULL, 0, errp);
3841 static BlockDriverState *bdrv_append_temp_snapshot(BlockDriverState *bs,
3843 QDict *snapshot_options,
3846 g_autofree char *tmp_filename = NULL;
3848 QemuOpts *opts = NULL;
3849 BlockDriverState *bs_snapshot = NULL;
3850 AioContext *ctx = bdrv_get_aio_context(bs);
3853 GLOBAL_STATE_CODE();
3855 /* if snapshot, we create a temporary backing file and open it
3856 instead of opening 'filename' directly */
3858 /* Get the required size from the image */
3859 aio_context_acquire(ctx);
3860 total_size = bdrv_getlength(bs);
3861 aio_context_release(ctx);
3863 if (total_size < 0) {
3864 error_setg_errno(errp, -total_size, "Could not get image size");
3868 /* Create the temporary image */
3869 tmp_filename = create_tmp_file(errp);
3870 if (!tmp_filename) {
3874 opts = qemu_opts_create(bdrv_qcow2.create_opts, NULL, 0,
3876 qemu_opt_set_number(opts, BLOCK_OPT_SIZE, total_size, &error_abort);
3877 ret = bdrv_create(&bdrv_qcow2, tmp_filename, opts, errp);
3878 qemu_opts_del(opts);
3880 error_prepend(errp, "Could not create temporary overlay '%s': ",
3885 /* Prepare options QDict for the temporary file */
3886 qdict_put_str(snapshot_options, "file.driver", "file");
3887 qdict_put_str(snapshot_options, "file.filename", tmp_filename);
3888 qdict_put_str(snapshot_options, "driver", "qcow2");
3890 bs_snapshot = bdrv_open(NULL, NULL, snapshot_options, flags, errp);
3891 snapshot_options = NULL;
3896 aio_context_acquire(ctx);
3897 ret = bdrv_append(bs_snapshot, bs, errp);
3898 aio_context_release(ctx);
3906 qobject_unref(snapshot_options);
3911 * Opens a disk image (raw, qcow2, vmdk, ...)
3913 * options is a QDict of options to pass to the block drivers, or NULL for an
3914 * empty set of options. The reference to the QDict belongs to the block layer
3915 * after the call (even on failure), so if the caller intends to reuse the
3916 * dictionary, it needs to use qobject_ref() before calling bdrv_open.
3918 * If *pbs is NULL, a new BDS will be created with a pointer to it stored there.
3919 * If it is not NULL, the referenced BDS will be reused.
3921 * The reference parameter may be used to specify an existing block device which
3922 * should be opened. If specified, neither options nor a filename may be given,
3923 * nor can an existing BDS be reused (that is, *pbs has to be NULL).
3925 * The caller must always hold the main AioContext lock.
3927 static BlockDriverState * no_coroutine_fn
3928 bdrv_open_inherit(const char *filename, const char *reference, QDict *options,
3929 int flags, BlockDriverState *parent,
3930 const BdrvChildClass *child_class, BdrvChildRole child_role,
3934 BlockBackend *file = NULL;
3935 BlockDriverState *bs;
3936 BlockDriver *drv = NULL;
3938 const char *drvname;
3939 const char *backing;
3940 Error *local_err = NULL;
3941 QDict *snapshot_options = NULL;
3942 int snapshot_flags = 0;
3943 AioContext *ctx = qemu_get_aio_context();
3945 assert(!child_class || !flags);
3946 assert(!child_class == !parent);
3947 GLOBAL_STATE_CODE();
3948 assert(!qemu_in_coroutine());
3951 bool options_non_empty = options ? qdict_size(options) : false;
3952 qobject_unref(options);
3954 if (filename || options_non_empty) {
3955 error_setg(errp, "Cannot reference an existing block device with "
3956 "additional options or a new filename");
3960 bs = bdrv_lookup_bs(reference, reference, errp);
3971 /* NULL means an empty set of options */
3972 if (options == NULL) {
3973 options = qdict_new();
3976 /* json: syntax counts as explicit options, as if in the QDict */
3977 parse_json_protocol(options, &filename, &local_err);
3982 bs->explicit_options = qdict_clone_shallow(options);
3985 bool parent_is_format;
3988 parent_is_format = parent->drv->is_format;
3991 * parent->drv is not set yet because this node is opened for
3992 * (potential) format probing. That means that @parent is going
3993 * to be a format node.
3995 parent_is_format = true;
3998 bs->inherits_from = parent;
3999 child_class->inherit_options(child_role, parent_is_format,
4001 parent->open_flags, parent->options);
4004 ret = bdrv_fill_options(&options, filename, &flags, &local_err);
4010 * Set the BDRV_O_RDWR and BDRV_O_ALLOW_RDWR flags.
4011 * Caution: getting a boolean member of @options requires care.
4012 * When @options come from -blockdev or blockdev_add, members are
4013 * typed according to the QAPI schema, but when they come from
4014 * -drive, they're all QString.
4016 if (g_strcmp0(qdict_get_try_str(options, BDRV_OPT_READ_ONLY), "on") &&
4017 !qdict_get_try_bool(options, BDRV_OPT_READ_ONLY, false)) {
4018 flags |= (BDRV_O_RDWR | BDRV_O_ALLOW_RDWR);
4020 flags &= ~BDRV_O_RDWR;
4023 if (flags & BDRV_O_SNAPSHOT) {
4024 snapshot_options = qdict_new();
4025 bdrv_temp_snapshot_options(&snapshot_flags, snapshot_options,
4027 /* Let bdrv_backing_options() override "read-only" */
4028 qdict_del(options, BDRV_OPT_READ_ONLY);
4029 bdrv_inherited_options(BDRV_CHILD_COW, true,
4030 &flags, options, flags, options);
4033 bs->open_flags = flags;
4034 bs->options = options;
4035 options = qdict_clone_shallow(options);
4037 /* Find the right image format driver */
4038 /* See cautionary note on accessing @options above */
4039 drvname = qdict_get_try_str(options, "driver");
4041 drv = bdrv_find_format(drvname);
4043 error_setg(errp, "Unknown driver: '%s'", drvname);
4048 assert(drvname || !(flags & BDRV_O_PROTOCOL));
4050 /* See cautionary note on accessing @options above */
4051 backing = qdict_get_try_str(options, "backing");
4052 if (qobject_to(QNull, qdict_get(options, "backing")) != NULL ||
4053 (backing && *backing == '\0'))
4056 warn_report("Use of \"backing\": \"\" is deprecated; "
4057 "use \"backing\": null instead");
4059 flags |= BDRV_O_NO_BACKING;
4060 qdict_del(bs->explicit_options, "backing");
4061 qdict_del(bs->options, "backing");
4062 qdict_del(options, "backing");
4065 /* Open image file without format layer. This BlockBackend is only used for
4066 * probing, the block drivers will do their own bdrv_open_child() for the
4067 * same BDS, which is why we put the node name back into options. */
4068 if ((flags & BDRV_O_PROTOCOL) == 0) {
4069 BlockDriverState *file_bs;
4071 file_bs = bdrv_open_child_bs(filename, options, "file", bs,
4072 &child_of_bds, BDRV_CHILD_IMAGE,
4077 if (file_bs != NULL) {
4078 /* Not requesting BLK_PERM_CONSISTENT_READ because we're only
4079 * looking at the header to guess the image format. This works even
4080 * in cases where a guest would not see a consistent state. */
4081 ctx = bdrv_get_aio_context(file_bs);
4082 aio_context_acquire(ctx);
4083 file = blk_new(ctx, 0, BLK_PERM_ALL);
4084 blk_insert_bs(file, file_bs, &local_err);
4085 bdrv_unref(file_bs);
4086 aio_context_release(ctx);
4092 qdict_put_str(options, "file", bdrv_get_node_name(file_bs));
4096 /* Image format probing */
4099 ret = find_image_format(file, filename, &drv, &local_err);
4104 * This option update would logically belong in bdrv_fill_options(),
4105 * but we first need to open bs->file for the probing to work, while
4106 * opening bs->file already requires the (mostly) final set of options
4107 * so that cache mode etc. can be inherited.
4109 * Adding the driver later is somewhat ugly, but it's not an option
4110 * that would ever be inherited, so it's correct. We just need to make
4111 * sure to update both bs->options (which has the full effective
4112 * options for bs) and options (which has file.* already removed).
4114 qdict_put_str(bs->options, "driver", drv->format_name);
4115 qdict_put_str(options, "driver", drv->format_name);
4117 error_setg(errp, "Must specify either driver or file");
4121 /* BDRV_O_PROTOCOL must be set iff a protocol BDS is about to be created */
4122 assert(!!(flags & BDRV_O_PROTOCOL) == !!drv->bdrv_file_open);
4123 /* file must be NULL if a protocol BDS is about to be created
4124 * (the inverse results in an error message from bdrv_open_common()) */
4125 assert(!(flags & BDRV_O_PROTOCOL) || !file);
4127 /* Open the image */
4128 ret = bdrv_open_common(bs, file, options, &local_err);
4133 /* The AioContext could have changed during bdrv_open_common() */
4134 ctx = bdrv_get_aio_context(bs);
4137 aio_context_acquire(ctx);
4139 aio_context_release(ctx);
4143 /* If there is a backing file, use it */
4144 if ((flags & BDRV_O_NO_BACKING) == 0) {
4145 ret = bdrv_open_backing_file(bs, options, "backing", &local_err);
4147 goto close_and_fail;
4151 /* Remove all children options and references
4152 * from bs->options and bs->explicit_options */
4153 QLIST_FOREACH(child, &bs->children, next) {
4154 char *child_key_dot;
4155 child_key_dot = g_strdup_printf("%s.", child->name);
4156 qdict_extract_subqdict(bs->explicit_options, NULL, child_key_dot);
4157 qdict_extract_subqdict(bs->options, NULL, child_key_dot);
4158 qdict_del(bs->explicit_options, child->name);
4159 qdict_del(bs->options, child->name);
4160 g_free(child_key_dot);
4163 /* Check if any unknown options were used */
4164 if (qdict_size(options) != 0) {
4165 const QDictEntry *entry = qdict_first(options);
4166 if (flags & BDRV_O_PROTOCOL) {
4167 error_setg(errp, "Block protocol '%s' doesn't support the option "
4168 "'%s'", drv->format_name, entry->key);
4171 "Block format '%s' does not support the option '%s'",
4172 drv->format_name, entry->key);
4175 goto close_and_fail;
4178 bdrv_parent_cb_change_media(bs, true);
4180 qobject_unref(options);
4183 /* For snapshot=on, create a temporary qcow2 overlay. bs points to the
4184 * temporary snapshot afterwards. */
4185 if (snapshot_flags) {
4186 BlockDriverState *snapshot_bs;
4187 snapshot_bs = bdrv_append_temp_snapshot(bs, snapshot_flags,
4188 snapshot_options, &local_err);
4189 snapshot_options = NULL;
4191 goto close_and_fail;
4193 /* We are not going to return bs but the overlay on top of it
4194 * (snapshot_bs); thus, we have to drop the strong reference to bs
4195 * (which we obtained by calling bdrv_new()). bs will not be deleted,
4196 * though, because the overlay still has a reference to it. */
4197 aio_context_acquire(ctx);
4199 aio_context_release(ctx);
4206 aio_context_acquire(ctx);
4208 qobject_unref(snapshot_options);
4209 qobject_unref(bs->explicit_options);
4210 qobject_unref(bs->options);
4211 qobject_unref(options);
4213 bs->explicit_options = NULL;
4215 aio_context_release(ctx);
4216 error_propagate(errp, local_err);
4220 aio_context_acquire(ctx);
4222 aio_context_release(ctx);
4223 qobject_unref(snapshot_options);
4224 qobject_unref(options);
4225 error_propagate(errp, local_err);
4229 /* The caller must always hold the main AioContext lock. */
4230 BlockDriverState *bdrv_open(const char *filename, const char *reference,
4231 QDict *options, int flags, Error **errp)
4233 GLOBAL_STATE_CODE();
4235 return bdrv_open_inherit(filename, reference, options, flags, NULL,
4239 /* Return true if the NULL-terminated @list contains @str */
4240 static bool is_str_in_list(const char *str, const char *const *list)
4244 for (i = 0; list[i] != NULL; i++) {
4245 if (!strcmp(str, list[i])) {
4254 * Check that every option set in @bs->options is also set in
4257 * Options listed in the common_options list and in
4258 * @bs->drv->mutable_opts are skipped.
4260 * Return 0 on success, otherwise return -EINVAL and set @errp.
4262 static int bdrv_reset_options_allowed(BlockDriverState *bs,
4263 const QDict *new_opts, Error **errp)
4265 const QDictEntry *e;
4266 /* These options are common to all block drivers and are handled
4267 * in bdrv_reopen_prepare() so they can be left out of @new_opts */
4268 const char *const common_options[] = {
4269 "node-name", "discard", "cache.direct", "cache.no-flush",
4270 "read-only", "auto-read-only", "detect-zeroes", NULL
4273 for (e = qdict_first(bs->options); e; e = qdict_next(bs->options, e)) {
4274 if (!qdict_haskey(new_opts, e->key) &&
4275 !is_str_in_list(e->key, common_options) &&
4276 !is_str_in_list(e->key, bs->drv->mutable_opts)) {
4277 error_setg(errp, "Option '%s' cannot be reset "
4278 "to its default value", e->key);
4287 * Returns true if @child can be reached recursively from @bs
4289 static bool bdrv_recurse_has_child(BlockDriverState *bs,
4290 BlockDriverState *child)
4298 QLIST_FOREACH(c, &bs->children, next) {
4299 if (bdrv_recurse_has_child(c->bs, child)) {
4308 * Adds a BlockDriverState to a simple queue for an atomic, transactional
4309 * reopen of multiple devices.
4311 * bs_queue can either be an existing BlockReopenQueue that has had QTAILQ_INIT
4312 * already performed, or alternatively may be NULL a new BlockReopenQueue will
4313 * be created and initialized. This newly created BlockReopenQueue should be
4314 * passed back in for subsequent calls that are intended to be of the same
4317 * bs is the BlockDriverState to add to the reopen queue.
4319 * options contains the changed options for the associated bs
4320 * (the BlockReopenQueue takes ownership)
4322 * flags contains the open flags for the associated bs
4324 * returns a pointer to bs_queue, which is either the newly allocated
4325 * bs_queue, or the existing bs_queue being used.
4327 * bs is drained here and undrained by bdrv_reopen_queue_free().
4329 * To be called with bs->aio_context locked.
4331 static BlockReopenQueue *bdrv_reopen_queue_child(BlockReopenQueue *bs_queue,
4332 BlockDriverState *bs,
4334 const BdrvChildClass *klass,
4336 bool parent_is_format,
4337 QDict *parent_options,
4343 BlockReopenQueueEntry *bs_entry;
4345 QDict *old_options, *explicit_options, *options_copy;
4349 GLOBAL_STATE_CODE();
4351 bdrv_drained_begin(bs);
4353 if (bs_queue == NULL) {
4354 bs_queue = g_new0(BlockReopenQueue, 1);
4355 QTAILQ_INIT(bs_queue);
4359 options = qdict_new();
4362 /* Check if this BlockDriverState is already in the queue */
4363 QTAILQ_FOREACH(bs_entry, bs_queue, entry) {
4364 if (bs == bs_entry->state.bs) {
4370 * Precedence of options:
4371 * 1. Explicitly passed in options (highest)
4372 * 2. Retained from explicitly set options of bs
4373 * 3. Inherited from parent node
4374 * 4. Retained from effective options of bs
4377 /* Old explicitly set values (don't overwrite by inherited value) */
4378 if (bs_entry || keep_old_opts) {
4379 old_options = qdict_clone_shallow(bs_entry ?
4380 bs_entry->state.explicit_options :
4381 bs->explicit_options);
4382 bdrv_join_options(bs, options, old_options);
4383 qobject_unref(old_options);
4386 explicit_options = qdict_clone_shallow(options);
4388 /* Inherit from parent node */
4389 if (parent_options) {
4391 klass->inherit_options(role, parent_is_format, &flags, options,
4392 parent_flags, parent_options);
4394 flags = bdrv_get_flags(bs);
4397 if (keep_old_opts) {
4398 /* Old values are used for options that aren't set yet */
4399 old_options = qdict_clone_shallow(bs->options);
4400 bdrv_join_options(bs, options, old_options);
4401 qobject_unref(old_options);
4404 /* We have the final set of options so let's update the flags */
4405 options_copy = qdict_clone_shallow(options);
4406 opts = qemu_opts_create(&bdrv_runtime_opts, NULL, 0, &error_abort);
4407 qemu_opts_absorb_qdict(opts, options_copy, NULL);
4408 update_flags_from_options(&flags, opts);
4409 qemu_opts_del(opts);
4410 qobject_unref(options_copy);
4412 /* bdrv_open_inherit() sets and clears some additional flags internally */
4413 flags &= ~BDRV_O_PROTOCOL;
4414 if (flags & BDRV_O_RDWR) {
4415 flags |= BDRV_O_ALLOW_RDWR;
4419 bs_entry = g_new0(BlockReopenQueueEntry, 1);
4420 QTAILQ_INSERT_TAIL(bs_queue, bs_entry, entry);
4422 qobject_unref(bs_entry->state.options);
4423 qobject_unref(bs_entry->state.explicit_options);
4426 bs_entry->state.bs = bs;
4427 bs_entry->state.options = options;
4428 bs_entry->state.explicit_options = explicit_options;
4429 bs_entry->state.flags = flags;
4432 * If keep_old_opts is false then it means that unspecified
4433 * options must be reset to their original value. We don't allow
4434 * resetting 'backing' but we need to know if the option is
4435 * missing in order to decide if we have to return an error.
4437 if (!keep_old_opts) {
4438 bs_entry->state.backing_missing =
4439 !qdict_haskey(options, "backing") &&
4440 !qdict_haskey(options, "backing.driver");
4443 QLIST_FOREACH(child, &bs->children, next) {
4444 QDict *new_child_options = NULL;
4445 bool child_keep_old = keep_old_opts;
4447 /* reopen can only change the options of block devices that were
4448 * implicitly created and inherited options. For other (referenced)
4449 * block devices, a syntax like "backing.foo" results in an error. */
4450 if (child->bs->inherits_from != bs) {
4454 /* Check if the options contain a child reference */
4455 if (qdict_haskey(options, child->name)) {
4456 const char *childref = qdict_get_try_str(options, child->name);
4458 * The current child must not be reopened if the child
4459 * reference is null or points to a different node.
4461 if (g_strcmp0(childref, child->bs->node_name)) {
4465 * If the child reference points to the current child then
4466 * reopen it with its existing set of options (note that
4467 * it can still inherit new options from the parent).
4469 child_keep_old = true;
4471 /* Extract child options ("child-name.*") */
4472 char *child_key_dot = g_strdup_printf("%s.", child->name);
4473 qdict_extract_subqdict(explicit_options, NULL, child_key_dot);
4474 qdict_extract_subqdict(options, &new_child_options, child_key_dot);
4475 g_free(child_key_dot);
4478 bdrv_reopen_queue_child(bs_queue, child->bs, new_child_options,
4479 child->klass, child->role, bs->drv->is_format,
4480 options, flags, child_keep_old);
4486 /* To be called with bs->aio_context locked */
4487 BlockReopenQueue *bdrv_reopen_queue(BlockReopenQueue *bs_queue,
4488 BlockDriverState *bs,
4489 QDict *options, bool keep_old_opts)
4491 GLOBAL_STATE_CODE();
4493 return bdrv_reopen_queue_child(bs_queue, bs, options, NULL, 0, false,
4494 NULL, 0, keep_old_opts);
4497 void bdrv_reopen_queue_free(BlockReopenQueue *bs_queue)
4499 GLOBAL_STATE_CODE();
4501 BlockReopenQueueEntry *bs_entry, *next;
4502 QTAILQ_FOREACH_SAFE(bs_entry, bs_queue, entry, next) {
4503 AioContext *ctx = bdrv_get_aio_context(bs_entry->state.bs);
4505 aio_context_acquire(ctx);
4506 bdrv_drained_end(bs_entry->state.bs);
4507 aio_context_release(ctx);
4509 qobject_unref(bs_entry->state.explicit_options);
4510 qobject_unref(bs_entry->state.options);
4518 * Reopen multiple BlockDriverStates atomically & transactionally.
4520 * The queue passed in (bs_queue) must have been built up previous
4521 * via bdrv_reopen_queue().
4523 * Reopens all BDS specified in the queue, with the appropriate
4524 * flags. All devices are prepared for reopen, and failure of any
4525 * device will cause all device changes to be abandoned, and intermediate
4528 * If all devices prepare successfully, then the changes are committed
4531 * All affected nodes must be drained between bdrv_reopen_queue() and
4532 * bdrv_reopen_multiple().
4534 * To be called from the main thread, with all other AioContexts unlocked.
4536 int bdrv_reopen_multiple(BlockReopenQueue *bs_queue, Error **errp)
4539 BlockReopenQueueEntry *bs_entry, *next;
4541 Transaction *tran = tran_new();
4542 g_autoptr(GSList) refresh_list = NULL;
4544 assert(qemu_get_current_aio_context() == qemu_get_aio_context());
4545 assert(bs_queue != NULL);
4546 GLOBAL_STATE_CODE();
4548 QTAILQ_FOREACH(bs_entry, bs_queue, entry) {
4549 ctx = bdrv_get_aio_context(bs_entry->state.bs);
4550 aio_context_acquire(ctx);
4551 ret = bdrv_flush(bs_entry->state.bs);
4552 aio_context_release(ctx);
4554 error_setg_errno(errp, -ret, "Error flushing drive");
4559 QTAILQ_FOREACH(bs_entry, bs_queue, entry) {
4560 assert(bs_entry->state.bs->quiesce_counter > 0);
4561 ctx = bdrv_get_aio_context(bs_entry->state.bs);
4562 aio_context_acquire(ctx);
4563 ret = bdrv_reopen_prepare(&bs_entry->state, bs_queue, tran, errp);
4564 aio_context_release(ctx);
4568 bs_entry->prepared = true;
4571 QTAILQ_FOREACH(bs_entry, bs_queue, entry) {
4572 BDRVReopenState *state = &bs_entry->state;
4574 refresh_list = g_slist_prepend(refresh_list, state->bs);
4575 if (state->old_backing_bs) {
4576 refresh_list = g_slist_prepend(refresh_list, state->old_backing_bs);
4578 if (state->old_file_bs) {
4579 refresh_list = g_slist_prepend(refresh_list, state->old_file_bs);
4584 * Note that file-posix driver rely on permission update done during reopen
4585 * (even if no permission changed), because it wants "new" permissions for
4586 * reconfiguring the fd and that's why it does it in raw_check_perm(), not
4587 * in raw_reopen_prepare() which is called with "old" permissions.
4589 ret = bdrv_list_refresh_perms(refresh_list, bs_queue, tran, errp);
4595 * If we reach this point, we have success and just need to apply the
4598 * Reverse order is used to comfort qcow2 driver: on commit it need to write
4599 * IN_USE flag to the image, to mark bitmaps in the image as invalid. But
4600 * children are usually goes after parents in reopen-queue, so go from last
4603 QTAILQ_FOREACH_REVERSE(bs_entry, bs_queue, entry) {
4604 ctx = bdrv_get_aio_context(bs_entry->state.bs);
4605 aio_context_acquire(ctx);
4606 bdrv_reopen_commit(&bs_entry->state);
4607 aio_context_release(ctx);
4610 bdrv_graph_wrlock(NULL);
4612 bdrv_graph_wrunlock();
4614 QTAILQ_FOREACH_REVERSE(bs_entry, bs_queue, entry) {
4615 BlockDriverState *bs = bs_entry->state.bs;
4617 if (bs->drv->bdrv_reopen_commit_post) {
4618 ctx = bdrv_get_aio_context(bs);
4619 aio_context_acquire(ctx);
4620 bs->drv->bdrv_reopen_commit_post(&bs_entry->state);
4621 aio_context_release(ctx);
4629 bdrv_graph_wrlock(NULL);
4631 bdrv_graph_wrunlock();
4633 QTAILQ_FOREACH_SAFE(bs_entry, bs_queue, entry, next) {
4634 if (bs_entry->prepared) {
4635 ctx = bdrv_get_aio_context(bs_entry->state.bs);
4636 aio_context_acquire(ctx);
4637 bdrv_reopen_abort(&bs_entry->state);
4638 aio_context_release(ctx);
4643 bdrv_reopen_queue_free(bs_queue);
4648 int bdrv_reopen(BlockDriverState *bs, QDict *opts, bool keep_old_opts,
4651 AioContext *ctx = bdrv_get_aio_context(bs);
4652 BlockReopenQueue *queue;
4655 GLOBAL_STATE_CODE();
4657 queue = bdrv_reopen_queue(NULL, bs, opts, keep_old_opts);
4659 if (ctx != qemu_get_aio_context()) {
4660 aio_context_release(ctx);
4662 ret = bdrv_reopen_multiple(queue, errp);
4664 if (ctx != qemu_get_aio_context()) {
4665 aio_context_acquire(ctx);
4671 int bdrv_reopen_set_read_only(BlockDriverState *bs, bool read_only,
4674 QDict *opts = qdict_new();
4676 GLOBAL_STATE_CODE();
4678 qdict_put_bool(opts, BDRV_OPT_READ_ONLY, read_only);
4680 return bdrv_reopen(bs, opts, true, errp);
4684 * Take a BDRVReopenState and check if the value of 'backing' in the
4685 * reopen_state->options QDict is valid or not.
4687 * If 'backing' is missing from the QDict then return 0.
4689 * If 'backing' contains the node name of the backing file of
4690 * reopen_state->bs then return 0.
4692 * If 'backing' contains a different node name (or is null) then check
4693 * whether the current backing file can be replaced with the new one.
4694 * If that's the case then reopen_state->replace_backing_bs is set to
4695 * true and reopen_state->new_backing_bs contains a pointer to the new
4696 * backing BlockDriverState (or NULL).
4698 * After calling this function, the transaction @tran may only be completed
4699 * while holding a writer lock for the graph.
4701 * Return 0 on success, otherwise return < 0 and set @errp.
4703 * The caller must hold the AioContext lock of @reopen_state->bs.
4704 * @reopen_state->bs can move to a different AioContext in this function.
4705 * Callers must make sure that their AioContext locking is still correct after
4708 static int bdrv_reopen_parse_file_or_backing(BDRVReopenState *reopen_state,
4709 bool is_backing, Transaction *tran,
4712 BlockDriverState *bs = reopen_state->bs;
4713 BlockDriverState *new_child_bs;
4714 BlockDriverState *old_child_bs = is_backing ? child_bs(bs->backing) :
4716 const char *child_name = is_backing ? "backing" : "file";
4719 AioContext *ctx, *old_ctx;
4722 GLOBAL_STATE_CODE();
4724 value = qdict_get(reopen_state->options, child_name);
4725 if (value == NULL) {
4729 switch (qobject_type(value)) {
4731 assert(is_backing); /* The 'file' option does not allow a null value */
4732 new_child_bs = NULL;
4735 str = qstring_get_str(qobject_to(QString, value));
4736 new_child_bs = bdrv_lookup_bs(NULL, str, errp);
4737 if (new_child_bs == NULL) {
4739 } else if (bdrv_recurse_has_child(new_child_bs, bs)) {
4740 error_setg(errp, "Making '%s' a %s child of '%s' would create a "
4741 "cycle", str, child_name, bs->node_name);
4747 * The options QDict has been flattened, so 'backing' and 'file'
4748 * do not allow any other data type here.
4750 g_assert_not_reached();
4753 if (old_child_bs == new_child_bs) {
4758 if (bdrv_skip_implicit_filters(old_child_bs) == new_child_bs) {
4762 if (old_child_bs->implicit) {
4763 error_setg(errp, "Cannot replace implicit %s child of %s",
4764 child_name, bs->node_name);
4769 if (bs->drv->is_filter && !old_child_bs) {
4771 * Filters always have a file or a backing child, so we are trying to
4772 * change wrong child
4774 error_setg(errp, "'%s' is a %s filter node that does not support a "
4775 "%s child", bs->node_name, bs->drv->format_name, child_name);
4780 reopen_state->old_backing_bs = old_child_bs;
4782 reopen_state->old_file_bs = old_child_bs;
4786 bdrv_ref(old_child_bs);
4787 bdrv_drained_begin(old_child_bs);
4790 old_ctx = bdrv_get_aio_context(bs);
4791 ctx = bdrv_get_aio_context(new_child_bs);
4792 if (old_ctx != ctx) {
4793 aio_context_release(old_ctx);
4794 aio_context_acquire(ctx);
4797 bdrv_graph_wrlock(new_child_bs);
4799 ret = bdrv_set_file_or_backing_noperm(bs, new_child_bs, is_backing,
4802 bdrv_graph_wrunlock();
4804 if (old_ctx != ctx) {
4805 aio_context_release(ctx);
4806 aio_context_acquire(old_ctx);
4810 bdrv_drained_end(old_child_bs);
4811 bdrv_unref(old_child_bs);
4818 * Prepares a BlockDriverState for reopen. All changes are staged in the
4819 * 'opaque' field of the BDRVReopenState, which is used and allocated by
4820 * the block driver layer .bdrv_reopen_prepare()
4822 * bs is the BlockDriverState to reopen
4823 * flags are the new open flags
4824 * queue is the reopen queue
4826 * Returns 0 on success, non-zero on error. On error errp will be set
4829 * On failure, bdrv_reopen_abort() will be called to clean up any data.
4830 * It is the responsibility of the caller to then call the abort() or
4831 * commit() for any other BDS that have been left in a prepare() state
4833 * The caller must hold the AioContext lock of @reopen_state->bs.
4835 * After calling this function, the transaction @change_child_tran may only be
4836 * completed while holding a writer lock for the graph.
4838 static int bdrv_reopen_prepare(BDRVReopenState *reopen_state,
4839 BlockReopenQueue *queue,
4840 Transaction *change_child_tran, Error **errp)
4844 Error *local_err = NULL;
4847 QDict *orig_reopen_opts;
4848 char *discard = NULL;
4850 bool drv_prepared = false;
4852 assert(reopen_state != NULL);
4853 assert(reopen_state->bs->drv != NULL);
4854 GLOBAL_STATE_CODE();
4855 drv = reopen_state->bs->drv;
4857 /* This function and each driver's bdrv_reopen_prepare() remove
4858 * entries from reopen_state->options as they are processed, so
4859 * we need to make a copy of the original QDict. */
4860 orig_reopen_opts = qdict_clone_shallow(reopen_state->options);
4862 /* Process generic block layer options */
4863 opts = qemu_opts_create(&bdrv_runtime_opts, NULL, 0, &error_abort);
4864 if (!qemu_opts_absorb_qdict(opts, reopen_state->options, errp)) {
4869 /* This was already called in bdrv_reopen_queue_child() so the flags
4870 * are up-to-date. This time we simply want to remove the options from
4871 * QemuOpts in order to indicate that they have been processed. */
4872 old_flags = reopen_state->flags;
4873 update_flags_from_options(&reopen_state->flags, opts);
4874 assert(old_flags == reopen_state->flags);
4876 discard = qemu_opt_get_del(opts, BDRV_OPT_DISCARD);
4877 if (discard != NULL) {
4878 if (bdrv_parse_discard_flags(discard, &reopen_state->flags) != 0) {
4879 error_setg(errp, "Invalid discard option");
4885 reopen_state->detect_zeroes =
4886 bdrv_parse_detect_zeroes(opts, reopen_state->flags, &local_err);
4888 error_propagate(errp, local_err);
4893 /* All other options (including node-name and driver) must be unchanged.
4894 * Put them back into the QDict, so that they are checked at the end
4895 * of this function. */
4896 qemu_opts_to_qdict(opts, reopen_state->options);
4898 /* If we are to stay read-only, do not allow permission change
4899 * to r/w. Attempting to set to r/w may fail if either BDRV_O_ALLOW_RDWR is
4900 * not set, or if the BDS still has copy_on_read enabled */
4901 read_only = !(reopen_state->flags & BDRV_O_RDWR);
4902 ret = bdrv_can_set_read_only(reopen_state->bs, read_only, true, &local_err);
4904 error_propagate(errp, local_err);
4908 if (drv->bdrv_reopen_prepare) {
4910 * If a driver-specific option is missing, it means that we
4911 * should reset it to its default value.
4912 * But not all options allow that, so we need to check it first.
4914 ret = bdrv_reset_options_allowed(reopen_state->bs,
4915 reopen_state->options, errp);
4920 ret = drv->bdrv_reopen_prepare(reopen_state, queue, &local_err);
4922 if (local_err != NULL) {
4923 error_propagate(errp, local_err);
4925 bdrv_refresh_filename(reopen_state->bs);
4926 error_setg(errp, "failed while preparing to reopen image '%s'",
4927 reopen_state->bs->filename);
4932 /* It is currently mandatory to have a bdrv_reopen_prepare()
4933 * handler for each supported drv. */
4934 error_setg(errp, "Block format '%s' used by node '%s' "
4935 "does not support reopening files", drv->format_name,
4936 bdrv_get_device_or_node_name(reopen_state->bs));
4941 drv_prepared = true;
4944 * We must provide the 'backing' option if the BDS has a backing
4945 * file or if the image file has a backing file name as part of
4946 * its metadata. Otherwise the 'backing' option can be omitted.
4948 if (drv->supports_backing && reopen_state->backing_missing &&
4949 (reopen_state->bs->backing || reopen_state->bs->backing_file[0])) {
4950 error_setg(errp, "backing is missing for '%s'",
4951 reopen_state->bs->node_name);
4957 * Allow changing the 'backing' option. The new value can be
4958 * either a reference to an existing node (using its node name)
4959 * or NULL to simply detach the current backing file.
4961 ret = bdrv_reopen_parse_file_or_backing(reopen_state, true,
4962 change_child_tran, errp);
4966 qdict_del(reopen_state->options, "backing");
4968 /* Allow changing the 'file' option. In this case NULL is not allowed */
4969 ret = bdrv_reopen_parse_file_or_backing(reopen_state, false,
4970 change_child_tran, errp);
4974 qdict_del(reopen_state->options, "file");
4976 /* Options that are not handled are only okay if they are unchanged
4977 * compared to the old state. It is expected that some options are only
4978 * used for the initial open, but not reopen (e.g. filename) */
4979 if (qdict_size(reopen_state->options)) {
4980 const QDictEntry *entry = qdict_first(reopen_state->options);
4983 QObject *new = entry->value;
4984 QObject *old = qdict_get(reopen_state->bs->options, entry->key);
4986 /* Allow child references (child_name=node_name) as long as they
4987 * point to the current child (i.e. everything stays the same). */
4988 if (qobject_type(new) == QTYPE_QSTRING) {
4990 QLIST_FOREACH(child, &reopen_state->bs->children, next) {
4991 if (!strcmp(child->name, entry->key)) {
4997 if (!strcmp(child->bs->node_name,
4998 qstring_get_str(qobject_to(QString, new)))) {
4999 continue; /* Found child with this name, skip option */
5005 * TODO: When using -drive to specify blockdev options, all values
5006 * will be strings; however, when using -blockdev, blockdev-add or
5007 * filenames using the json:{} pseudo-protocol, they will be
5009 * In contrast, reopening options are (currently) always strings
5010 * (because you can only specify them through qemu-io; all other
5011 * callers do not specify any options).
5012 * Therefore, when using anything other than -drive to create a BDS,
5013 * this cannot detect non-string options as unchanged, because
5014 * qobject_is_equal() always returns false for objects of different
5015 * type. In the future, this should be remedied by correctly typing
5016 * all options. For now, this is not too big of an issue because
5017 * the user can simply omit options which cannot be changed anyway,
5018 * so they will stay unchanged.
5020 if (!qobject_is_equal(new, old)) {
5021 error_setg(errp, "Cannot change the option '%s'", entry->key);
5025 } while ((entry = qdict_next(reopen_state->options, entry)));
5030 /* Restore the original reopen_state->options QDict */
5031 qobject_unref(reopen_state->options);
5032 reopen_state->options = qobject_ref(orig_reopen_opts);
5035 if (ret < 0 && drv_prepared) {
5036 /* drv->bdrv_reopen_prepare() has succeeded, so we need to
5037 * call drv->bdrv_reopen_abort() before signaling an error
5038 * (bdrv_reopen_multiple() will not call bdrv_reopen_abort()
5039 * when the respective bdrv_reopen_prepare() has failed) */
5040 if (drv->bdrv_reopen_abort) {
5041 drv->bdrv_reopen_abort(reopen_state);
5044 qemu_opts_del(opts);
5045 qobject_unref(orig_reopen_opts);
5051 * Takes the staged changes for the reopen from bdrv_reopen_prepare(), and
5052 * makes them final by swapping the staging BlockDriverState contents into
5053 * the active BlockDriverState contents.
5055 static void bdrv_reopen_commit(BDRVReopenState *reopen_state)
5058 BlockDriverState *bs;
5061 assert(reopen_state != NULL);
5062 bs = reopen_state->bs;
5064 assert(drv != NULL);
5065 GLOBAL_STATE_CODE();
5067 /* If there are any driver level actions to take */
5068 if (drv->bdrv_reopen_commit) {
5069 drv->bdrv_reopen_commit(reopen_state);
5072 /* set BDS specific flags now */
5073 qobject_unref(bs->explicit_options);
5074 qobject_unref(bs->options);
5075 qobject_ref(reopen_state->explicit_options);
5076 qobject_ref(reopen_state->options);
5078 bs->explicit_options = reopen_state->explicit_options;
5079 bs->options = reopen_state->options;
5080 bs->open_flags = reopen_state->flags;
5081 bs->detect_zeroes = reopen_state->detect_zeroes;
5083 /* Remove child references from bs->options and bs->explicit_options.
5084 * Child options were already removed in bdrv_reopen_queue_child() */
5085 QLIST_FOREACH(child, &bs->children, next) {
5086 qdict_del(bs->explicit_options, child->name);
5087 qdict_del(bs->options, child->name);
5089 /* backing is probably removed, so it's not handled by previous loop */
5090 qdict_del(bs->explicit_options, "backing");
5091 qdict_del(bs->options, "backing");
5093 bdrv_graph_rdlock_main_loop();
5094 bdrv_refresh_limits(bs, NULL, NULL);
5095 bdrv_graph_rdunlock_main_loop();
5096 bdrv_refresh_total_sectors(bs, bs->total_sectors);
5100 * Abort the reopen, and delete and free the staged changes in
5103 static void bdrv_reopen_abort(BDRVReopenState *reopen_state)
5107 assert(reopen_state != NULL);
5108 drv = reopen_state->bs->drv;
5109 assert(drv != NULL);
5110 GLOBAL_STATE_CODE();
5112 if (drv->bdrv_reopen_abort) {
5113 drv->bdrv_reopen_abort(reopen_state);
5118 static void bdrv_close(BlockDriverState *bs)
5120 BdrvAioNotifier *ban, *ban_next;
5121 BdrvChild *child, *next;
5123 GLOBAL_STATE_CODE();
5124 assert(!bs->refcnt);
5126 bdrv_drained_begin(bs); /* complete I/O */
5128 bdrv_drain(bs); /* in case flush left pending I/O */
5131 if (bs->drv->bdrv_close) {
5132 /* Must unfreeze all children, so bdrv_unref_child() works */
5133 bs->drv->bdrv_close(bs);
5138 QLIST_FOREACH_SAFE(child, &bs->children, next, next) {
5139 bdrv_unref_child(bs, child);
5142 assert(!bs->backing);
5146 qatomic_set(&bs->copy_on_read, 0);
5147 bs->backing_file[0] = '\0';
5148 bs->backing_format[0] = '\0';
5149 bs->total_sectors = 0;
5150 bs->encrypted = false;
5152 qobject_unref(bs->options);
5153 qobject_unref(bs->explicit_options);
5155 bs->explicit_options = NULL;
5156 qobject_unref(bs->full_open_options);
5157 bs->full_open_options = NULL;
5158 g_free(bs->block_status_cache);
5159 bs->block_status_cache = NULL;
5161 bdrv_release_named_dirty_bitmaps(bs);
5162 assert(QLIST_EMPTY(&bs->dirty_bitmaps));
5164 QLIST_FOREACH_SAFE(ban, &bs->aio_notifiers, list, ban_next) {
5167 QLIST_INIT(&bs->aio_notifiers);
5168 bdrv_drained_end(bs);
5171 * If we're still inside some bdrv_drain_all_begin()/end() sections, end
5172 * them now since this BDS won't exist anymore when bdrv_drain_all_end()
5175 if (bs->quiesce_counter) {
5176 bdrv_drain_all_end_quiesce(bs);
5180 void bdrv_close_all(void)
5182 GLOBAL_STATE_CODE();
5183 assert(job_next(NULL) == NULL);
5185 /* Drop references from requests still in flight, such as canceled block
5186 * jobs whose AIO context has not been polled yet */
5189 blk_remove_all_bs();
5190 blockdev_close_all_bdrv_states();
5192 assert(QTAILQ_EMPTY(&all_bdrv_states));
5195 static bool GRAPH_RDLOCK should_update_child(BdrvChild *c, BlockDriverState *to)
5201 if (c->klass->stay_at_node) {
5205 /* If the child @c belongs to the BDS @to, replacing the current
5206 * c->bs by @to would mean to create a loop.
5208 * Such a case occurs when appending a BDS to a backing chain.
5209 * For instance, imagine the following chain:
5211 * guest device -> node A -> further backing chain...
5213 * Now we create a new BDS B which we want to put on top of this
5214 * chain, so we first attach A as its backing node:
5219 * guest device -> node A -> further backing chain...
5221 * Finally we want to replace A by B. When doing that, we want to
5222 * replace all pointers to A by pointers to B -- except for the
5223 * pointer from B because (1) that would create a loop, and (2)
5224 * that pointer should simply stay intact:
5226 * guest device -> node B
5229 * node A -> further backing chain...
5231 * In general, when replacing a node A (c->bs) by a node B (@to),
5232 * if A is a child of B, that means we cannot replace A by B there
5233 * because that would create a loop. Silently detaching A from B
5234 * is also not really an option. So overall just leaving A in
5235 * place there is the most sensible choice.
5237 * We would also create a loop in any cases where @c is only
5238 * indirectly referenced by @to. Prevent this by returning false
5239 * if @c is found (by breadth-first search) anywhere in the whole
5244 found = g_hash_table_new(NULL, NULL);
5245 g_hash_table_add(found, to);
5246 queue = g_queue_new();
5247 g_queue_push_tail(queue, to);
5249 while (!g_queue_is_empty(queue)) {
5250 BlockDriverState *v = g_queue_pop_head(queue);
5253 QLIST_FOREACH(c2, &v->children, next) {
5259 if (g_hash_table_contains(found, c2->bs)) {
5263 g_queue_push_tail(queue, c2->bs);
5264 g_hash_table_add(found, c2->bs);
5268 g_queue_free(queue);
5269 g_hash_table_destroy(found);
5274 static void bdrv_remove_child_commit(void *opaque)
5276 GLOBAL_STATE_CODE();
5277 bdrv_child_free(opaque);
5280 static TransactionActionDrv bdrv_remove_child_drv = {
5281 .commit = bdrv_remove_child_commit,
5285 * Function doesn't update permissions, caller is responsible for this.
5287 * @child->bs (if non-NULL) must be drained.
5289 * After calling this function, the transaction @tran may only be completed
5290 * while holding a writer lock for the graph.
5292 static void GRAPH_WRLOCK bdrv_remove_child(BdrvChild *child, Transaction *tran)
5299 assert(child->quiesced_parent);
5300 bdrv_replace_child_tran(child, NULL, tran);
5303 tran_add(tran, &bdrv_remove_child_drv, child);
5307 * Both @from and @to (if non-NULL) must be drained. @to must be kept drained
5308 * until the transaction is completed.
5310 * After calling this function, the transaction @tran may only be completed
5311 * while holding a writer lock for the graph.
5313 static int GRAPH_WRLOCK
5314 bdrv_replace_node_noperm(BlockDriverState *from,
5315 BlockDriverState *to,
5316 bool auto_skip, Transaction *tran,
5319 BdrvChild *c, *next;
5321 GLOBAL_STATE_CODE();
5323 assert(from->quiesce_counter);
5324 assert(to->quiesce_counter);
5326 QLIST_FOREACH_SAFE(c, &from->parents, next_parent, next) {
5327 assert(c->bs == from);
5328 if (!should_update_child(c, to)) {
5332 error_setg(errp, "Should not change '%s' link to '%s'",
5333 c->name, from->node_name);
5337 error_setg(errp, "Cannot change '%s' link to '%s'",
5338 c->name, from->node_name);
5341 bdrv_replace_child_tran(c, to, tran);
5348 * With auto_skip=true bdrv_replace_node_common skips updating from parents
5349 * if it creates a parent-child relation loop or if parent is block-job.
5351 * With auto_skip=false the error is returned if from has a parent which should
5354 * With @detach_subchain=true @to must be in a backing chain of @from. In this
5355 * case backing link of the cow-parent of @to is removed.
5357 static int bdrv_replace_node_common(BlockDriverState *from,
5358 BlockDriverState *to,
5359 bool auto_skip, bool detach_subchain,
5362 Transaction *tran = tran_new();
5363 g_autoptr(GSList) refresh_list = NULL;
5364 BlockDriverState *to_cow_parent = NULL;
5367 GLOBAL_STATE_CODE();
5369 if (detach_subchain) {
5370 assert(bdrv_chain_contains(from, to));
5372 for (to_cow_parent = from;
5373 bdrv_filter_or_cow_bs(to_cow_parent) != to;
5374 to_cow_parent = bdrv_filter_or_cow_bs(to_cow_parent))
5380 /* Make sure that @from doesn't go away until we have successfully attached
5381 * all of its parents to @to. */
5384 assert(qemu_get_current_aio_context() == qemu_get_aio_context());
5385 assert(bdrv_get_aio_context(from) == bdrv_get_aio_context(to));
5386 bdrv_drained_begin(from);
5387 bdrv_drained_begin(to);
5389 bdrv_graph_wrlock(to);
5392 * Do the replacement without permission update.
5393 * Replacement may influence the permissions, we should calculate new
5394 * permissions based on new graph. If we fail, we'll roll-back the
5397 ret = bdrv_replace_node_noperm(from, to, auto_skip, tran, errp);
5402 if (detach_subchain) {
5403 /* to_cow_parent is already drained because from is drained */
5404 bdrv_remove_child(bdrv_filter_or_cow_child(to_cow_parent), tran);
5407 refresh_list = g_slist_prepend(refresh_list, to);
5408 refresh_list = g_slist_prepend(refresh_list, from);
5410 ret = bdrv_list_refresh_perms(refresh_list, NULL, tran, errp);
5418 tran_finalize(tran, ret);
5419 bdrv_graph_wrunlock();
5421 bdrv_drained_end(to);
5422 bdrv_drained_end(from);
5428 int bdrv_replace_node(BlockDriverState *from, BlockDriverState *to,
5431 GLOBAL_STATE_CODE();
5433 return bdrv_replace_node_common(from, to, true, false, errp);
5436 int bdrv_drop_filter(BlockDriverState *bs, Error **errp)
5438 GLOBAL_STATE_CODE();
5440 return bdrv_replace_node_common(bs, bdrv_filter_or_cow_bs(bs), true, true,
5445 * Add new bs contents at the top of an image chain while the chain is
5446 * live, while keeping required fields on the top layer.
5448 * This will modify the BlockDriverState fields, and swap contents
5449 * between bs_new and bs_top. Both bs_new and bs_top are modified.
5451 * bs_new must not be attached to a BlockBackend and must not have backing
5454 * This function does not create any image files.
5456 * The caller must hold the AioContext lock for @bs_top.
5458 int bdrv_append(BlockDriverState *bs_new, BlockDriverState *bs_top,
5463 Transaction *tran = tran_new();
5464 AioContext *old_context, *new_context = NULL;
5466 GLOBAL_STATE_CODE();
5468 assert(!bs_new->backing);
5470 old_context = bdrv_get_aio_context(bs_top);
5471 bdrv_drained_begin(bs_top);
5474 * bdrv_drained_begin() requires that only the AioContext of the drained
5475 * node is locked, and at this point it can still differ from the AioContext
5478 new_context = bdrv_get_aio_context(bs_new);
5479 aio_context_release(old_context);
5480 aio_context_acquire(new_context);
5481 bdrv_drained_begin(bs_new);
5482 aio_context_release(new_context);
5483 aio_context_acquire(old_context);
5486 bdrv_graph_wrlock(bs_top);
5488 child = bdrv_attach_child_noperm(bs_new, bs_top, "backing",
5489 &child_of_bds, bdrv_backing_role(bs_new),
5497 * bdrv_attach_child_noperm could change the AioContext of bs_top and
5498 * bs_new, but at least they are in the same AioContext now. This is the
5499 * AioContext that we need to lock for the rest of the function.
5501 new_context = bdrv_get_aio_context(bs_top);
5503 if (old_context != new_context) {
5504 aio_context_release(old_context);
5505 aio_context_acquire(new_context);
5508 ret = bdrv_replace_node_noperm(bs_top, bs_new, true, tran, errp);
5513 ret = bdrv_refresh_perms(bs_new, tran, errp);
5515 tran_finalize(tran, ret);
5517 bdrv_refresh_limits(bs_top, NULL, NULL);
5518 bdrv_graph_wrunlock();
5520 bdrv_drained_end(bs_top);
5521 bdrv_drained_end(bs_new);
5523 if (new_context && old_context != new_context) {
5524 aio_context_release(new_context);
5525 aio_context_acquire(old_context);
5531 /* Not for empty child */
5532 int bdrv_replace_child_bs(BdrvChild *child, BlockDriverState *new_bs,
5536 Transaction *tran = tran_new();
5537 g_autoptr(GSList) refresh_list = NULL;
5538 BlockDriverState *old_bs = child->bs;
5540 GLOBAL_STATE_CODE();
5543 bdrv_drained_begin(old_bs);
5544 bdrv_drained_begin(new_bs);
5545 bdrv_graph_wrlock(new_bs);
5547 bdrv_replace_child_tran(child, new_bs, tran);
5549 refresh_list = g_slist_prepend(refresh_list, old_bs);
5550 refresh_list = g_slist_prepend(refresh_list, new_bs);
5552 ret = bdrv_list_refresh_perms(refresh_list, NULL, tran, errp);
5554 tran_finalize(tran, ret);
5556 bdrv_graph_wrunlock();
5557 bdrv_drained_end(old_bs);
5558 bdrv_drained_end(new_bs);
5564 static void bdrv_delete(BlockDriverState *bs)
5566 assert(bdrv_op_blocker_is_empty(bs));
5567 assert(!bs->refcnt);
5568 GLOBAL_STATE_CODE();
5570 /* remove from list, if necessary */
5571 if (bs->node_name[0] != '\0') {
5572 QTAILQ_REMOVE(&graph_bdrv_states, bs, node_list);
5574 QTAILQ_REMOVE(&all_bdrv_states, bs, bs_list);
5578 qemu_mutex_destroy(&bs->reqs_lock);
5585 * Replace @bs by newly created block node.
5587 * @options is a QDict of options to pass to the block drivers, or NULL for an
5588 * empty set of options. The reference to the QDict belongs to the block layer
5589 * after the call (even on failure), so if the caller intends to reuse the
5590 * dictionary, it needs to use qobject_ref() before calling bdrv_open.
5592 * The caller holds the AioContext lock for @bs. It must make sure that @bs
5593 * stays in the same AioContext, i.e. @options must not refer to nodes in a
5594 * different AioContext.
5596 BlockDriverState *bdrv_insert_node(BlockDriverState *bs, QDict *options,
5597 int flags, Error **errp)
5601 AioContext *ctx = bdrv_get_aio_context(bs);
5602 BlockDriverState *new_node_bs = NULL;
5603 const char *drvname, *node_name;
5606 drvname = qdict_get_try_str(options, "driver");
5608 error_setg(errp, "driver is not specified");
5612 drv = bdrv_find_format(drvname);
5614 error_setg(errp, "Unknown driver: '%s'", drvname);
5618 node_name = qdict_get_try_str(options, "node-name");
5620 GLOBAL_STATE_CODE();
5622 aio_context_release(ctx);
5623 aio_context_acquire(qemu_get_aio_context());
5624 new_node_bs = bdrv_new_open_driver_opts(drv, node_name, options, flags,
5626 aio_context_release(qemu_get_aio_context());
5627 aio_context_acquire(ctx);
5628 assert(bdrv_get_aio_context(bs) == ctx);
5630 options = NULL; /* bdrv_new_open_driver() eats options */
5632 error_prepend(errp, "Could not create node: ");
5636 bdrv_drained_begin(bs);
5637 ret = bdrv_replace_node(bs, new_node_bs, errp);
5638 bdrv_drained_end(bs);
5641 error_prepend(errp, "Could not replace node: ");
5648 qobject_unref(options);
5649 bdrv_unref(new_node_bs);
5654 * Run consistency checks on an image
5656 * Returns 0 if the check could be completed (it doesn't mean that the image is
5657 * free of errors) or -errno when an internal error occurred. The results of the
5658 * check are stored in res.
5660 int coroutine_fn bdrv_co_check(BlockDriverState *bs,
5661 BdrvCheckResult *res, BdrvCheckMode fix)
5664 assert_bdrv_graph_readable();
5665 if (bs->drv == NULL) {
5668 if (bs->drv->bdrv_co_check == NULL) {
5672 memset(res, 0, sizeof(*res));
5673 return bs->drv->bdrv_co_check(bs, res, fix);
5679 * -EINVAL - backing format specified, but no file
5680 * -ENOSPC - can't update the backing file because no space is left in the
5682 * -ENOTSUP - format driver doesn't support changing the backing file
5684 int bdrv_change_backing_file(BlockDriverState *bs, const char *backing_file,
5685 const char *backing_fmt, bool require)
5687 BlockDriver *drv = bs->drv;
5690 GLOBAL_STATE_CODE();
5696 /* Backing file format doesn't make sense without a backing file */
5697 if (backing_fmt && !backing_file) {
5701 if (require && backing_file && !backing_fmt) {
5705 if (drv->bdrv_change_backing_file != NULL) {
5706 ret = drv->bdrv_change_backing_file(bs, backing_file, backing_fmt);
5712 pstrcpy(bs->backing_file, sizeof(bs->backing_file), backing_file ?: "");
5713 pstrcpy(bs->backing_format, sizeof(bs->backing_format), backing_fmt ?: "");
5714 pstrcpy(bs->auto_backing_file, sizeof(bs->auto_backing_file),
5715 backing_file ?: "");
5721 * Finds the first non-filter node above bs in the chain between
5722 * active and bs. The returned node is either an immediate parent of
5723 * bs, or there are only filter nodes between the two.
5725 * Returns NULL if bs is not found in active's image chain,
5726 * or if active == bs.
5728 * Returns the bottommost base image if bs == NULL.
5730 BlockDriverState *bdrv_find_overlay(BlockDriverState *active,
5731 BlockDriverState *bs)
5734 GLOBAL_STATE_CODE();
5736 bs = bdrv_skip_filters(bs);
5737 active = bdrv_skip_filters(active);
5740 BlockDriverState *next = bdrv_backing_chain_next(active);
5750 /* Given a BDS, searches for the base layer. */
5751 BlockDriverState *bdrv_find_base(BlockDriverState *bs)
5753 GLOBAL_STATE_CODE();
5755 return bdrv_find_overlay(bs, NULL);
5759 * Return true if at least one of the COW (backing) and filter links
5760 * between @bs and @base is frozen. @errp is set if that's the case.
5761 * @base must be reachable from @bs, or NULL.
5763 bool bdrv_is_backing_chain_frozen(BlockDriverState *bs, BlockDriverState *base,
5766 BlockDriverState *i;
5769 GLOBAL_STATE_CODE();
5771 for (i = bs; i != base; i = child_bs(child)) {
5772 child = bdrv_filter_or_cow_child(i);
5774 if (child && child->frozen) {
5775 error_setg(errp, "Cannot change '%s' link from '%s' to '%s'",
5776 child->name, i->node_name, child->bs->node_name);
5785 * Freeze all COW (backing) and filter links between @bs and @base.
5786 * If any of the links is already frozen the operation is aborted and
5787 * none of the links are modified.
5788 * @base must be reachable from @bs, or NULL.
5789 * Returns 0 on success. On failure returns < 0 and sets @errp.
5791 int bdrv_freeze_backing_chain(BlockDriverState *bs, BlockDriverState *base,
5794 BlockDriverState *i;
5797 GLOBAL_STATE_CODE();
5799 if (bdrv_is_backing_chain_frozen(bs, base, errp)) {
5803 for (i = bs; i != base; i = child_bs(child)) {
5804 child = bdrv_filter_or_cow_child(i);
5805 if (child && child->bs->never_freeze) {
5806 error_setg(errp, "Cannot freeze '%s' link to '%s'",
5807 child->name, child->bs->node_name);
5812 for (i = bs; i != base; i = child_bs(child)) {
5813 child = bdrv_filter_or_cow_child(i);
5815 child->frozen = true;
5823 * Unfreeze all COW (backing) and filter links between @bs and @base.
5824 * The caller must ensure that all links are frozen before using this
5826 * @base must be reachable from @bs, or NULL.
5828 void bdrv_unfreeze_backing_chain(BlockDriverState *bs, BlockDriverState *base)
5830 BlockDriverState *i;
5833 GLOBAL_STATE_CODE();
5835 for (i = bs; i != base; i = child_bs(child)) {
5836 child = bdrv_filter_or_cow_child(i);
5838 assert(child->frozen);
5839 child->frozen = false;
5845 * Drops images above 'base' up to and including 'top', and sets the image
5846 * above 'top' to have base as its backing file.
5848 * Requires that the overlay to 'top' is opened r/w, so that the backing file
5849 * information in 'bs' can be properly updated.
5851 * E.g., this will convert the following chain:
5852 * bottom <- base <- intermediate <- top <- active
5856 * bottom <- base <- active
5858 * It is allowed for bottom==base, in which case it converts:
5860 * base <- intermediate <- top <- active
5866 * If backing_file_str is non-NULL, it will be used when modifying top's
5867 * overlay image metadata.
5870 * if active == top, that is considered an error
5873 int bdrv_drop_intermediate(BlockDriverState *top, BlockDriverState *base,
5874 const char *backing_file_str)
5876 BlockDriverState *explicit_top = top;
5877 bool update_inherits_from;
5879 Error *local_err = NULL;
5881 g_autoptr(GSList) updated_children = NULL;
5884 GLOBAL_STATE_CODE();
5887 bdrv_drained_begin(base);
5889 if (!top->drv || !base->drv) {
5893 /* Make sure that base is in the backing chain of top */
5894 if (!bdrv_chain_contains(top, base)) {
5898 /* If 'base' recursively inherits from 'top' then we should set
5899 * base->inherits_from to top->inherits_from after 'top' and all
5900 * other intermediate nodes have been dropped.
5901 * If 'top' is an implicit node (e.g. "commit_top") we should skip
5902 * it because no one inherits from it. We use explicit_top for that. */
5903 explicit_top = bdrv_skip_implicit_filters(explicit_top);
5904 update_inherits_from = bdrv_inherits_from_recursive(base, explicit_top);
5906 /* success - we can delete the intermediate states, and link top->base */
5907 if (!backing_file_str) {
5908 bdrv_refresh_filename(base);
5909 backing_file_str = base->filename;
5912 QLIST_FOREACH(c, &top->parents, next_parent) {
5913 updated_children = g_slist_prepend(updated_children, c);
5917 * It seems correct to pass detach_subchain=true here, but it triggers
5918 * one more yet not fixed bug, when due to nested aio_poll loop we switch to
5919 * another drained section, which modify the graph (for example, removing
5920 * the child, which we keep in updated_children list). So, it's a TODO.
5922 * Note, bug triggered if pass detach_subchain=true here and run
5923 * test-bdrv-drain. test_drop_intermediate_poll() test-case will crash.
5926 bdrv_replace_node_common(top, base, false, false, &local_err);
5928 error_report_err(local_err);
5932 for (p = updated_children; p; p = p->next) {
5935 if (c->klass->update_filename) {
5936 ret = c->klass->update_filename(c, base, backing_file_str,
5940 * TODO: Actually, we want to rollback all previous iterations
5941 * of this loop, and (which is almost impossible) previous
5942 * bdrv_replace_node()...
5944 * Note, that c->klass->update_filename may lead to permission
5945 * update, so it's a bad idea to call it inside permission
5946 * update transaction of bdrv_replace_node.
5948 error_report_err(local_err);
5954 if (update_inherits_from) {
5955 base->inherits_from = explicit_top->inherits_from;
5960 bdrv_drained_end(base);
5966 * Implementation of BlockDriver.bdrv_co_get_allocated_file_size() that
5967 * sums the size of all data-bearing children. (This excludes backing
5970 static int64_t coroutine_fn GRAPH_RDLOCK
5971 bdrv_sum_allocated_file_size(BlockDriverState *bs)
5974 int64_t child_size, sum = 0;
5976 QLIST_FOREACH(child, &bs->children, next) {
5977 if (child->role & (BDRV_CHILD_DATA | BDRV_CHILD_METADATA |
5978 BDRV_CHILD_FILTERED))
5980 child_size = bdrv_co_get_allocated_file_size(child->bs);
5981 if (child_size < 0) {
5992 * Length of a allocated file in bytes. Sparse files are counted by actual
5993 * allocated space. Return < 0 if error or unknown.
5995 int64_t coroutine_fn bdrv_co_get_allocated_file_size(BlockDriverState *bs)
5997 BlockDriver *drv = bs->drv;
5999 assert_bdrv_graph_readable();
6004 if (drv->bdrv_co_get_allocated_file_size) {
6005 return drv->bdrv_co_get_allocated_file_size(bs);
6008 if (drv->bdrv_file_open) {
6010 * Protocol drivers default to -ENOTSUP (most of their data is
6011 * not stored in any of their children (if they even have any),
6012 * so there is no generic way to figure it out).
6015 } else if (drv->is_filter) {
6016 /* Filter drivers default to the size of their filtered child */
6017 return bdrv_co_get_allocated_file_size(bdrv_filter_bs(bs));
6019 /* Other drivers default to summing their children's sizes */
6020 return bdrv_sum_allocated_file_size(bs);
6026 * @drv: Format driver
6027 * @opts: Creation options for new image
6028 * @in_bs: Existing image containing data for new image (may be NULL)
6029 * @errp: Error object
6030 * Returns: A #BlockMeasureInfo (free using qapi_free_BlockMeasureInfo())
6033 * Calculate file size required to create a new image.
6035 * If @in_bs is given then space for allocated clusters and zero clusters
6036 * from that image are included in the calculation. If @opts contains a
6037 * backing file that is shared by @in_bs then backing clusters may be omitted
6038 * from the calculation.
6040 * If @in_bs is NULL then the calculation includes no allocated clusters
6041 * unless a preallocation option is given in @opts.
6043 * Note that @in_bs may use a different BlockDriver from @drv.
6045 * If an error occurs the @errp pointer is set.
6047 BlockMeasureInfo *bdrv_measure(BlockDriver *drv, QemuOpts *opts,
6048 BlockDriverState *in_bs, Error **errp)
6051 if (!drv->bdrv_measure) {
6052 error_setg(errp, "Block driver '%s' does not support size measurement",
6057 return drv->bdrv_measure(opts, in_bs, errp);
6061 * Return number of sectors on success, -errno on error.
6063 int64_t coroutine_fn bdrv_co_nb_sectors(BlockDriverState *bs)
6065 BlockDriver *drv = bs->drv;
6067 assert_bdrv_graph_readable();
6072 if (bs->bl.has_variable_length) {
6073 int ret = bdrv_co_refresh_total_sectors(bs, bs->total_sectors);
6078 return bs->total_sectors;
6082 * This wrapper is written by hand because this function is in the hot I/O path,
6083 * via blk_get_geometry.
6085 int64_t coroutine_mixed_fn bdrv_nb_sectors(BlockDriverState *bs)
6087 BlockDriver *drv = bs->drv;
6093 if (bs->bl.has_variable_length) {
6094 int ret = bdrv_refresh_total_sectors(bs, bs->total_sectors);
6100 return bs->total_sectors;
6104 * Return length in bytes on success, -errno on error.
6105 * The length is always a multiple of BDRV_SECTOR_SIZE.
6107 int64_t coroutine_fn bdrv_co_getlength(BlockDriverState *bs)
6111 assert_bdrv_graph_readable();
6113 ret = bdrv_co_nb_sectors(bs);
6117 if (ret > INT64_MAX / BDRV_SECTOR_SIZE) {
6120 return ret * BDRV_SECTOR_SIZE;
6123 bool bdrv_is_sg(BlockDriverState *bs)
6130 * Return whether the given node supports compressed writes.
6132 bool bdrv_supports_compressed_writes(BlockDriverState *bs)
6134 BlockDriverState *filtered;
6137 if (!bs->drv || !block_driver_can_compress(bs->drv)) {
6141 filtered = bdrv_filter_bs(bs);
6144 * Filters can only forward compressed writes, so we have to
6147 return bdrv_supports_compressed_writes(filtered);
6153 const char *bdrv_get_format_name(BlockDriverState *bs)
6156 return bs->drv ? bs->drv->format_name : NULL;
6159 static int qsort_strcmp(const void *a, const void *b)
6161 return strcmp(*(char *const *)a, *(char *const *)b);
6164 void bdrv_iterate_format(void (*it)(void *opaque, const char *name),
6165 void *opaque, bool read_only)
6170 const char **formats = NULL;
6172 GLOBAL_STATE_CODE();
6174 QLIST_FOREACH(drv, &bdrv_drivers, list) {
6175 if (drv->format_name) {
6179 if (use_bdrv_whitelist && !bdrv_is_whitelisted(drv, read_only)) {
6183 while (formats && i && !found) {
6184 found = !strcmp(formats[--i], drv->format_name);
6188 formats = g_renew(const char *, formats, count + 1);
6189 formats[count++] = drv->format_name;
6194 for (i = 0; i < (int)ARRAY_SIZE(block_driver_modules); i++) {
6195 const char *format_name = block_driver_modules[i].format_name;
6201 if (use_bdrv_whitelist &&
6202 !bdrv_format_is_whitelisted(format_name, read_only)) {
6206 while (formats && j && !found) {
6207 found = !strcmp(formats[--j], format_name);
6211 formats = g_renew(const char *, formats, count + 1);
6212 formats[count++] = format_name;
6217 qsort(formats, count, sizeof(formats[0]), qsort_strcmp);
6219 for (i = 0; i < count; i++) {
6220 it(opaque, formats[i]);
6226 /* This function is to find a node in the bs graph */
6227 BlockDriverState *bdrv_find_node(const char *node_name)
6229 BlockDriverState *bs;
6232 GLOBAL_STATE_CODE();
6234 QTAILQ_FOREACH(bs, &graph_bdrv_states, node_list) {
6235 if (!strcmp(node_name, bs->node_name)) {
6242 /* Put this QMP function here so it can access the static graph_bdrv_states. */
6243 BlockDeviceInfoList *bdrv_named_nodes_list(bool flat,
6246 BlockDeviceInfoList *list;
6247 BlockDriverState *bs;
6249 GLOBAL_STATE_CODE();
6252 QTAILQ_FOREACH(bs, &graph_bdrv_states, node_list) {
6253 BlockDeviceInfo *info = bdrv_block_device_info(NULL, bs, flat, errp);
6255 qapi_free_BlockDeviceInfoList(list);
6258 QAPI_LIST_PREPEND(list, info);
6264 typedef struct XDbgBlockGraphConstructor {
6265 XDbgBlockGraph *graph;
6266 GHashTable *graph_nodes;
6267 } XDbgBlockGraphConstructor;
6269 static XDbgBlockGraphConstructor *xdbg_graph_new(void)
6271 XDbgBlockGraphConstructor *gr = g_new(XDbgBlockGraphConstructor, 1);
6273 gr->graph = g_new0(XDbgBlockGraph, 1);
6274 gr->graph_nodes = g_hash_table_new(NULL, NULL);
6279 static XDbgBlockGraph *xdbg_graph_finalize(XDbgBlockGraphConstructor *gr)
6281 XDbgBlockGraph *graph = gr->graph;
6283 g_hash_table_destroy(gr->graph_nodes);
6289 static uintptr_t xdbg_graph_node_num(XDbgBlockGraphConstructor *gr, void *node)
6291 uintptr_t ret = (uintptr_t)g_hash_table_lookup(gr->graph_nodes, node);
6298 * Start counting from 1, not 0, because 0 interferes with not-found (NULL)
6299 * answer of g_hash_table_lookup.
6301 ret = g_hash_table_size(gr->graph_nodes) + 1;
6302 g_hash_table_insert(gr->graph_nodes, node, (void *)ret);
6307 static void xdbg_graph_add_node(XDbgBlockGraphConstructor *gr, void *node,
6308 XDbgBlockGraphNodeType type, const char *name)
6310 XDbgBlockGraphNode *n;
6312 n = g_new0(XDbgBlockGraphNode, 1);
6314 n->id = xdbg_graph_node_num(gr, node);
6316 n->name = g_strdup(name);
6318 QAPI_LIST_PREPEND(gr->graph->nodes, n);
6321 static void xdbg_graph_add_edge(XDbgBlockGraphConstructor *gr, void *parent,
6322 const BdrvChild *child)
6324 BlockPermission qapi_perm;
6325 XDbgBlockGraphEdge *edge;
6326 GLOBAL_STATE_CODE();
6328 edge = g_new0(XDbgBlockGraphEdge, 1);
6330 edge->parent = xdbg_graph_node_num(gr, parent);
6331 edge->child = xdbg_graph_node_num(gr, child->bs);
6332 edge->name = g_strdup(child->name);
6334 for (qapi_perm = 0; qapi_perm < BLOCK_PERMISSION__MAX; qapi_perm++) {
6335 uint64_t flag = bdrv_qapi_perm_to_blk_perm(qapi_perm);
6337 if (flag & child->perm) {
6338 QAPI_LIST_PREPEND(edge->perm, qapi_perm);
6340 if (flag & child->shared_perm) {
6341 QAPI_LIST_PREPEND(edge->shared_perm, qapi_perm);
6345 QAPI_LIST_PREPEND(gr->graph->edges, edge);
6349 XDbgBlockGraph *bdrv_get_xdbg_block_graph(Error **errp)
6353 BlockDriverState *bs;
6355 XDbgBlockGraphConstructor *gr = xdbg_graph_new();
6357 GLOBAL_STATE_CODE();
6359 for (blk = blk_all_next(NULL); blk; blk = blk_all_next(blk)) {
6360 char *allocated_name = NULL;
6361 const char *name = blk_name(blk);
6364 name = allocated_name = blk_get_attached_dev_id(blk);
6366 xdbg_graph_add_node(gr, blk, X_DBG_BLOCK_GRAPH_NODE_TYPE_BLOCK_BACKEND,
6368 g_free(allocated_name);
6369 if (blk_root(blk)) {
6370 xdbg_graph_add_edge(gr, blk, blk_root(blk));
6374 WITH_JOB_LOCK_GUARD() {
6375 for (job = block_job_next_locked(NULL); job;
6376 job = block_job_next_locked(job)) {
6379 xdbg_graph_add_node(gr, job, X_DBG_BLOCK_GRAPH_NODE_TYPE_BLOCK_JOB,
6381 for (el = job->nodes; el; el = el->next) {
6382 xdbg_graph_add_edge(gr, job, (BdrvChild *)el->data);
6387 QTAILQ_FOREACH(bs, &graph_bdrv_states, node_list) {
6388 xdbg_graph_add_node(gr, bs, X_DBG_BLOCK_GRAPH_NODE_TYPE_BLOCK_DRIVER,
6390 QLIST_FOREACH(child, &bs->children, next) {
6391 xdbg_graph_add_edge(gr, bs, child);
6395 return xdbg_graph_finalize(gr);
6398 BlockDriverState *bdrv_lookup_bs(const char *device,
6399 const char *node_name,
6403 BlockDriverState *bs;
6405 GLOBAL_STATE_CODE();
6408 blk = blk_by_name(device);
6413 error_setg(errp, "Device '%s' has no medium", device);
6421 bs = bdrv_find_node(node_name);
6428 error_setg(errp, "Cannot find device=\'%s\' nor node-name=\'%s\'",
6429 device ? device : "",
6430 node_name ? node_name : "");
6434 /* If 'base' is in the same chain as 'top', return true. Otherwise,
6435 * return false. If either argument is NULL, return false. */
6436 bool bdrv_chain_contains(BlockDriverState *top, BlockDriverState *base)
6439 GLOBAL_STATE_CODE();
6441 while (top && top != base) {
6442 top = bdrv_filter_or_cow_bs(top);
6448 BlockDriverState *bdrv_next_node(BlockDriverState *bs)
6450 GLOBAL_STATE_CODE();
6452 return QTAILQ_FIRST(&graph_bdrv_states);
6454 return QTAILQ_NEXT(bs, node_list);
6457 BlockDriverState *bdrv_next_all_states(BlockDriverState *bs)
6459 GLOBAL_STATE_CODE();
6461 return QTAILQ_FIRST(&all_bdrv_states);
6463 return QTAILQ_NEXT(bs, bs_list);
6466 const char *bdrv_get_node_name(const BlockDriverState *bs)
6469 return bs->node_name;
6472 const char *bdrv_get_parent_name(const BlockDriverState *bs)
6478 /* If multiple parents have a name, just pick the first one. */
6479 QLIST_FOREACH(c, &bs->parents, next_parent) {
6480 if (c->klass->get_name) {
6481 name = c->klass->get_name(c);
6482 if (name && *name) {
6491 /* TODO check what callers really want: bs->node_name or blk_name() */
6492 const char *bdrv_get_device_name(const BlockDriverState *bs)
6495 return bdrv_get_parent_name(bs) ?: "";
6498 /* This can be used to identify nodes that might not have a device
6499 * name associated. Since node and device names live in the same
6500 * namespace, the result is unambiguous. The exception is if both are
6501 * absent, then this returns an empty (non-null) string. */
6502 const char *bdrv_get_device_or_node_name(const BlockDriverState *bs)
6505 return bdrv_get_parent_name(bs) ?: bs->node_name;
6508 int bdrv_get_flags(BlockDriverState *bs)
6511 return bs->open_flags;
6514 int bdrv_has_zero_init_1(BlockDriverState *bs)
6516 GLOBAL_STATE_CODE();
6520 int bdrv_has_zero_init(BlockDriverState *bs)
6522 BlockDriverState *filtered;
6523 GLOBAL_STATE_CODE();
6529 /* If BS is a copy on write image, it is initialized to
6530 the contents of the base image, which may not be zeroes. */
6531 if (bdrv_cow_child(bs)) {
6534 if (bs->drv->bdrv_has_zero_init) {
6535 return bs->drv->bdrv_has_zero_init(bs);
6538 filtered = bdrv_filter_bs(bs);
6540 return bdrv_has_zero_init(filtered);
6547 bool bdrv_can_write_zeroes_with_unmap(BlockDriverState *bs)
6550 if (!(bs->open_flags & BDRV_O_UNMAP)) {
6554 return bs->supported_zero_flags & BDRV_REQ_MAY_UNMAP;
6557 void bdrv_get_backing_filename(BlockDriverState *bs,
6558 char *filename, int filename_size)
6561 pstrcpy(filename, filename_size, bs->backing_file);
6564 int coroutine_fn bdrv_co_get_info(BlockDriverState *bs, BlockDriverInfo *bdi)
6567 BlockDriver *drv = bs->drv;
6569 assert_bdrv_graph_readable();
6571 /* if bs->drv == NULL, bs is closed, so there's nothing to do here */
6575 if (!drv->bdrv_co_get_info) {
6576 BlockDriverState *filtered = bdrv_filter_bs(bs);
6578 return bdrv_co_get_info(filtered, bdi);
6582 memset(bdi, 0, sizeof(*bdi));
6583 ret = drv->bdrv_co_get_info(bs, bdi);
6584 if (bdi->subcluster_size == 0) {
6586 * If the driver left this unset, subclusters are not supported.
6587 * Then it is safe to treat each cluster as having only one subcluster.
6589 bdi->subcluster_size = bdi->cluster_size;
6595 if (bdi->cluster_size > BDRV_MAX_ALIGNMENT) {
6602 ImageInfoSpecific *bdrv_get_specific_info(BlockDriverState *bs,
6605 BlockDriver *drv = bs->drv;
6607 if (drv && drv->bdrv_get_specific_info) {
6608 return drv->bdrv_get_specific_info(bs, errp);
6613 BlockStatsSpecific *bdrv_get_specific_stats(BlockDriverState *bs)
6615 BlockDriver *drv = bs->drv;
6617 if (!drv || !drv->bdrv_get_specific_stats) {
6620 return drv->bdrv_get_specific_stats(bs);
6623 void coroutine_fn bdrv_co_debug_event(BlockDriverState *bs, BlkdebugEvent event)
6626 assert_bdrv_graph_readable();
6628 if (!bs || !bs->drv || !bs->drv->bdrv_co_debug_event) {
6632 bs->drv->bdrv_co_debug_event(bs, event);
6635 static BlockDriverState *bdrv_find_debug_node(BlockDriverState *bs)
6637 GLOBAL_STATE_CODE();
6638 while (bs && bs->drv && !bs->drv->bdrv_debug_breakpoint) {
6639 bs = bdrv_primary_bs(bs);
6642 if (bs && bs->drv && bs->drv->bdrv_debug_breakpoint) {
6643 assert(bs->drv->bdrv_debug_remove_breakpoint);
6650 int bdrv_debug_breakpoint(BlockDriverState *bs, const char *event,
6653 GLOBAL_STATE_CODE();
6654 bs = bdrv_find_debug_node(bs);
6656 return bs->drv->bdrv_debug_breakpoint(bs, event, tag);
6662 int bdrv_debug_remove_breakpoint(BlockDriverState *bs, const char *tag)
6664 GLOBAL_STATE_CODE();
6665 bs = bdrv_find_debug_node(bs);
6667 return bs->drv->bdrv_debug_remove_breakpoint(bs, tag);
6673 int bdrv_debug_resume(BlockDriverState *bs, const char *tag)
6675 GLOBAL_STATE_CODE();
6676 while (bs && (!bs->drv || !bs->drv->bdrv_debug_resume)) {
6677 bs = bdrv_primary_bs(bs);
6680 if (bs && bs->drv && bs->drv->bdrv_debug_resume) {
6681 return bs->drv->bdrv_debug_resume(bs, tag);
6687 bool bdrv_debug_is_suspended(BlockDriverState *bs, const char *tag)
6689 GLOBAL_STATE_CODE();
6690 while (bs && bs->drv && !bs->drv->bdrv_debug_is_suspended) {
6691 bs = bdrv_primary_bs(bs);
6694 if (bs && bs->drv && bs->drv->bdrv_debug_is_suspended) {
6695 return bs->drv->bdrv_debug_is_suspended(bs, tag);
6701 /* backing_file can either be relative, or absolute, or a protocol. If it is
6702 * relative, it must be relative to the chain. So, passing in bs->filename
6703 * from a BDS as backing_file should not be done, as that may be relative to
6704 * the CWD rather than the chain. */
6705 BlockDriverState *bdrv_find_backing_image(BlockDriverState *bs,
6706 const char *backing_file)
6708 char *filename_full = NULL;
6709 char *backing_file_full = NULL;
6710 char *filename_tmp = NULL;
6711 int is_protocol = 0;
6712 bool filenames_refreshed = false;
6713 BlockDriverState *curr_bs = NULL;
6714 BlockDriverState *retval = NULL;
6715 BlockDriverState *bs_below;
6717 GLOBAL_STATE_CODE();
6719 if (!bs || !bs->drv || !backing_file) {
6723 filename_full = g_malloc(PATH_MAX);
6724 backing_file_full = g_malloc(PATH_MAX);
6726 is_protocol = path_has_protocol(backing_file);
6729 * Being largely a legacy function, skip any filters here
6730 * (because filters do not have normal filenames, so they cannot
6731 * match anyway; and allowing json:{} filenames is a bit out of
6734 for (curr_bs = bdrv_skip_filters(bs);
6735 bdrv_cow_child(curr_bs) != NULL;
6738 bs_below = bdrv_backing_chain_next(curr_bs);
6740 if (bdrv_backing_overridden(curr_bs)) {
6742 * If the backing file was overridden, we can only compare
6743 * directly against the backing node's filename.
6746 if (!filenames_refreshed) {
6748 * This will automatically refresh all of the
6749 * filenames in the rest of the backing chain, so we
6750 * only need to do this once.
6752 bdrv_refresh_filename(bs_below);
6753 filenames_refreshed = true;
6756 if (strcmp(backing_file, bs_below->filename) == 0) {
6760 } else if (is_protocol || path_has_protocol(curr_bs->backing_file)) {
6762 * If either of the filename paths is actually a protocol, then
6763 * compare unmodified paths; otherwise make paths relative.
6765 char *backing_file_full_ret;
6767 if (strcmp(backing_file, curr_bs->backing_file) == 0) {
6771 /* Also check against the full backing filename for the image */
6772 backing_file_full_ret = bdrv_get_full_backing_filename(curr_bs,
6774 if (backing_file_full_ret) {
6775 bool equal = strcmp(backing_file, backing_file_full_ret) == 0;
6776 g_free(backing_file_full_ret);
6783 /* If not an absolute filename path, make it relative to the current
6784 * image's filename path */
6785 filename_tmp = bdrv_make_absolute_filename(curr_bs, backing_file,
6787 /* We are going to compare canonicalized absolute pathnames */
6788 if (!filename_tmp || !realpath(filename_tmp, filename_full)) {
6789 g_free(filename_tmp);
6792 g_free(filename_tmp);
6794 /* We need to make sure the backing filename we are comparing against
6795 * is relative to the current image filename (or absolute) */
6796 filename_tmp = bdrv_get_full_backing_filename(curr_bs, NULL);
6797 if (!filename_tmp || !realpath(filename_tmp, backing_file_full)) {
6798 g_free(filename_tmp);
6801 g_free(filename_tmp);
6803 if (strcmp(backing_file_full, filename_full) == 0) {
6810 g_free(filename_full);
6811 g_free(backing_file_full);
6815 void bdrv_init(void)
6817 #ifdef CONFIG_BDRV_WHITELIST_TOOLS
6818 use_bdrv_whitelist = 1;
6820 module_call_init(MODULE_INIT_BLOCK);
6823 void bdrv_init_with_whitelist(void)
6825 use_bdrv_whitelist = 1;
6829 int bdrv_activate(BlockDriverState *bs, Error **errp)
6831 BdrvChild *child, *parent;
6832 Error *local_err = NULL;
6834 BdrvDirtyBitmap *bm;
6836 GLOBAL_STATE_CODE();
6842 QLIST_FOREACH(child, &bs->children, next) {
6843 bdrv_activate(child->bs, &local_err);
6845 error_propagate(errp, local_err);
6851 * Update permissions, they may differ for inactive nodes.
6853 * Note that the required permissions of inactive images are always a
6854 * subset of the permissions required after activating the image. This
6855 * allows us to just get the permissions upfront without restricting
6856 * bdrv_co_invalidate_cache().
6858 * It also means that in error cases, we don't have to try and revert to
6859 * the old permissions (which is an operation that could fail, too). We can
6860 * just keep the extended permissions for the next time that an activation
6861 * of the image is tried.
6863 if (bs->open_flags & BDRV_O_INACTIVE) {
6864 bs->open_flags &= ~BDRV_O_INACTIVE;
6865 ret = bdrv_refresh_perms(bs, NULL, errp);
6867 bs->open_flags |= BDRV_O_INACTIVE;
6871 ret = bdrv_invalidate_cache(bs, errp);
6873 bs->open_flags |= BDRV_O_INACTIVE;
6877 FOR_EACH_DIRTY_BITMAP(bs, bm) {
6878 bdrv_dirty_bitmap_skip_store(bm, false);
6881 ret = bdrv_refresh_total_sectors(bs, bs->total_sectors);
6883 bs->open_flags |= BDRV_O_INACTIVE;
6884 error_setg_errno(errp, -ret, "Could not refresh total sector count");
6889 QLIST_FOREACH(parent, &bs->parents, next_parent) {
6890 if (parent->klass->activate) {
6891 parent->klass->activate(parent, &local_err);
6893 bs->open_flags |= BDRV_O_INACTIVE;
6894 error_propagate(errp, local_err);
6903 int coroutine_fn bdrv_co_invalidate_cache(BlockDriverState *bs, Error **errp)
6905 Error *local_err = NULL;
6908 assert(!(bs->open_flags & BDRV_O_INACTIVE));
6909 assert_bdrv_graph_readable();
6911 if (bs->drv->bdrv_co_invalidate_cache) {
6912 bs->drv->bdrv_co_invalidate_cache(bs, &local_err);
6914 error_propagate(errp, local_err);
6922 void bdrv_activate_all(Error **errp)
6924 BlockDriverState *bs;
6925 BdrvNextIterator it;
6927 GLOBAL_STATE_CODE();
6929 for (bs = bdrv_first(&it); bs; bs = bdrv_next(&it)) {
6930 AioContext *aio_context = bdrv_get_aio_context(bs);
6933 aio_context_acquire(aio_context);
6934 ret = bdrv_activate(bs, errp);
6935 aio_context_release(aio_context);
6937 bdrv_next_cleanup(&it);
6943 static bool bdrv_has_bds_parent(BlockDriverState *bs, bool only_active)
6946 GLOBAL_STATE_CODE();
6948 QLIST_FOREACH(parent, &bs->parents, next_parent) {
6949 if (parent->klass->parent_is_bds) {
6950 BlockDriverState *parent_bs = parent->opaque;
6951 if (!only_active || !(parent_bs->open_flags & BDRV_O_INACTIVE)) {
6960 static int bdrv_inactivate_recurse(BlockDriverState *bs)
6962 BdrvChild *child, *parent;
6964 uint64_t cumulative_perms, cumulative_shared_perms;
6966 GLOBAL_STATE_CODE();
6972 /* Make sure that we don't inactivate a child before its parent.
6973 * It will be covered by recursion from the yet active parent. */
6974 if (bdrv_has_bds_parent(bs, true)) {
6978 assert(!(bs->open_flags & BDRV_O_INACTIVE));
6980 /* Inactivate this node */
6981 if (bs->drv->bdrv_inactivate) {
6982 ret = bs->drv->bdrv_inactivate(bs);
6988 QLIST_FOREACH(parent, &bs->parents, next_parent) {
6989 if (parent->klass->inactivate) {
6990 ret = parent->klass->inactivate(parent);
6997 bdrv_get_cumulative_perm(bs, &cumulative_perms,
6998 &cumulative_shared_perms);
6999 if (cumulative_perms & (BLK_PERM_WRITE | BLK_PERM_WRITE_UNCHANGED)) {
7000 /* Our inactive parents still need write access. Inactivation failed. */
7004 bs->open_flags |= BDRV_O_INACTIVE;
7007 * Update permissions, they may differ for inactive nodes.
7008 * We only tried to loosen restrictions, so errors are not fatal, ignore
7011 bdrv_refresh_perms(bs, NULL, NULL);
7013 /* Recursively inactivate children */
7014 QLIST_FOREACH(child, &bs->children, next) {
7015 ret = bdrv_inactivate_recurse(child->bs);
7024 int bdrv_inactivate_all(void)
7026 BlockDriverState *bs = NULL;
7027 BdrvNextIterator it;
7029 GSList *aio_ctxs = NULL, *ctx;
7031 GLOBAL_STATE_CODE();
7033 for (bs = bdrv_first(&it); bs; bs = bdrv_next(&it)) {
7034 AioContext *aio_context = bdrv_get_aio_context(bs);
7036 if (!g_slist_find(aio_ctxs, aio_context)) {
7037 aio_ctxs = g_slist_prepend(aio_ctxs, aio_context);
7038 aio_context_acquire(aio_context);
7042 for (bs = bdrv_first(&it); bs; bs = bdrv_next(&it)) {
7043 /* Nodes with BDS parents are covered by recursion from the last
7044 * parent that gets inactivated. Don't inactivate them a second
7045 * time if that has already happened. */
7046 if (bdrv_has_bds_parent(bs, false)) {
7049 ret = bdrv_inactivate_recurse(bs);
7051 bdrv_next_cleanup(&it);
7057 for (ctx = aio_ctxs; ctx != NULL; ctx = ctx->next) {
7058 AioContext *aio_context = ctx->data;
7059 aio_context_release(aio_context);
7061 g_slist_free(aio_ctxs);
7066 /**************************************************************/
7067 /* removable device support */
7070 * Return TRUE if the media is present
7072 bool coroutine_fn bdrv_co_is_inserted(BlockDriverState *bs)
7074 BlockDriver *drv = bs->drv;
7077 assert_bdrv_graph_readable();
7082 if (drv->bdrv_co_is_inserted) {
7083 return drv->bdrv_co_is_inserted(bs);
7085 QLIST_FOREACH(child, &bs->children, next) {
7086 if (!bdrv_co_is_inserted(child->bs)) {
7094 * If eject_flag is TRUE, eject the media. Otherwise, close the tray
7096 void coroutine_fn bdrv_co_eject(BlockDriverState *bs, bool eject_flag)
7098 BlockDriver *drv = bs->drv;
7100 assert_bdrv_graph_readable();
7102 if (drv && drv->bdrv_co_eject) {
7103 drv->bdrv_co_eject(bs, eject_flag);
7108 * Lock or unlock the media (if it is locked, the user won't be able
7109 * to eject it manually).
7111 void coroutine_fn bdrv_co_lock_medium(BlockDriverState *bs, bool locked)
7113 BlockDriver *drv = bs->drv;
7115 assert_bdrv_graph_readable();
7116 trace_bdrv_lock_medium(bs, locked);
7118 if (drv && drv->bdrv_co_lock_medium) {
7119 drv->bdrv_co_lock_medium(bs, locked);
7123 /* Get a reference to bs */
7124 void bdrv_ref(BlockDriverState *bs)
7126 GLOBAL_STATE_CODE();
7130 /* Release a previously grabbed reference to bs.
7131 * If after releasing, reference count is zero, the BlockDriverState is
7133 void bdrv_unref(BlockDriverState *bs)
7135 GLOBAL_STATE_CODE();
7139 assert(bs->refcnt > 0);
7140 if (--bs->refcnt == 0) {
7146 * Release a BlockDriverState reference while holding the graph write lock.
7148 * Calling bdrv_unref() directly is forbidden while holding the graph lock
7149 * because bdrv_close() both involves polling and taking the graph lock
7150 * internally. bdrv_schedule_unref() instead delays decreasing the refcount and
7151 * possibly closing @bs until the graph lock is released.
7153 void bdrv_schedule_unref(BlockDriverState *bs)
7158 aio_bh_schedule_oneshot(qemu_get_aio_context(),
7159 (QEMUBHFunc *) bdrv_unref, bs);
7162 struct BdrvOpBlocker {
7164 QLIST_ENTRY(BdrvOpBlocker) list;
7167 bool bdrv_op_is_blocked(BlockDriverState *bs, BlockOpType op, Error **errp)
7169 BdrvOpBlocker *blocker;
7170 GLOBAL_STATE_CODE();
7171 assert((int) op >= 0 && op < BLOCK_OP_TYPE_MAX);
7172 if (!QLIST_EMPTY(&bs->op_blockers[op])) {
7173 blocker = QLIST_FIRST(&bs->op_blockers[op]);
7174 error_propagate_prepend(errp, error_copy(blocker->reason),
7175 "Node '%s' is busy: ",
7176 bdrv_get_device_or_node_name(bs));
7182 void bdrv_op_block(BlockDriverState *bs, BlockOpType op, Error *reason)
7184 BdrvOpBlocker *blocker;
7185 GLOBAL_STATE_CODE();
7186 assert((int) op >= 0 && op < BLOCK_OP_TYPE_MAX);
7188 blocker = g_new0(BdrvOpBlocker, 1);
7189 blocker->reason = reason;
7190 QLIST_INSERT_HEAD(&bs->op_blockers[op], blocker, list);
7193 void bdrv_op_unblock(BlockDriverState *bs, BlockOpType op, Error *reason)
7195 BdrvOpBlocker *blocker, *next;
7196 GLOBAL_STATE_CODE();
7197 assert((int) op >= 0 && op < BLOCK_OP_TYPE_MAX);
7198 QLIST_FOREACH_SAFE(blocker, &bs->op_blockers[op], list, next) {
7199 if (blocker->reason == reason) {
7200 QLIST_REMOVE(blocker, list);
7206 void bdrv_op_block_all(BlockDriverState *bs, Error *reason)
7209 GLOBAL_STATE_CODE();
7210 for (i = 0; i < BLOCK_OP_TYPE_MAX; i++) {
7211 bdrv_op_block(bs, i, reason);
7215 void bdrv_op_unblock_all(BlockDriverState *bs, Error *reason)
7218 GLOBAL_STATE_CODE();
7219 for (i = 0; i < BLOCK_OP_TYPE_MAX; i++) {
7220 bdrv_op_unblock(bs, i, reason);
7224 bool bdrv_op_blocker_is_empty(BlockDriverState *bs)
7227 GLOBAL_STATE_CODE();
7228 for (i = 0; i < BLOCK_OP_TYPE_MAX; i++) {
7229 if (!QLIST_EMPTY(&bs->op_blockers[i])) {
7237 * Must not be called while holding the lock of an AioContext other than the
7240 void bdrv_img_create(const char *filename, const char *fmt,
7241 const char *base_filename, const char *base_fmt,
7242 char *options, uint64_t img_size, int flags, bool quiet,
7245 QemuOptsList *create_opts = NULL;
7246 QemuOpts *opts = NULL;
7247 const char *backing_fmt, *backing_file;
7249 BlockDriver *drv, *proto_drv;
7250 Error *local_err = NULL;
7253 GLOBAL_STATE_CODE();
7255 /* Find driver and parse its options */
7256 drv = bdrv_find_format(fmt);
7258 error_setg(errp, "Unknown file format '%s'", fmt);
7262 proto_drv = bdrv_find_protocol(filename, true, errp);
7267 if (!drv->create_opts) {
7268 error_setg(errp, "Format driver '%s' does not support image creation",
7273 if (!proto_drv->create_opts) {
7274 error_setg(errp, "Protocol driver '%s' does not support image creation",
7275 proto_drv->format_name);
7279 aio_context_acquire(qemu_get_aio_context());
7281 /* Create parameter list */
7282 create_opts = qemu_opts_append(create_opts, drv->create_opts);
7283 create_opts = qemu_opts_append(create_opts, proto_drv->create_opts);
7285 opts = qemu_opts_create(create_opts, NULL, 0, &error_abort);
7287 /* Parse -o options */
7289 if (!qemu_opts_do_parse(opts, options, NULL, errp)) {
7294 if (!qemu_opt_get(opts, BLOCK_OPT_SIZE)) {
7295 qemu_opt_set_number(opts, BLOCK_OPT_SIZE, img_size, &error_abort);
7296 } else if (img_size != UINT64_C(-1)) {
7297 error_setg(errp, "The image size must be specified only once");
7301 if (base_filename) {
7302 if (!qemu_opt_set(opts, BLOCK_OPT_BACKING_FILE, base_filename,
7304 error_setg(errp, "Backing file not supported for file format '%s'",
7311 if (!qemu_opt_set(opts, BLOCK_OPT_BACKING_FMT, base_fmt, NULL)) {
7312 error_setg(errp, "Backing file format not supported for file "
7313 "format '%s'", fmt);
7318 backing_file = qemu_opt_get(opts, BLOCK_OPT_BACKING_FILE);
7320 if (!strcmp(filename, backing_file)) {
7321 error_setg(errp, "Error: Trying to create an image with the "
7322 "same filename as the backing file");
7325 if (backing_file[0] == '\0') {
7326 error_setg(errp, "Expected backing file name, got empty string");
7331 backing_fmt = qemu_opt_get(opts, BLOCK_OPT_BACKING_FMT);
7333 /* The size for the image must always be specified, unless we have a backing
7334 * file and we have not been forbidden from opening it. */
7335 size = qemu_opt_get_size(opts, BLOCK_OPT_SIZE, img_size);
7336 if (backing_file && !(flags & BDRV_O_NO_BACKING)) {
7337 BlockDriverState *bs;
7340 QDict *backing_options = NULL;
7343 bdrv_get_full_backing_filename_from_filename(filename, backing_file,
7348 assert(full_backing);
7351 * No need to do I/O here, which allows us to open encrypted
7352 * backing images without needing the secret
7355 back_flags &= ~(BDRV_O_RDWR | BDRV_O_SNAPSHOT | BDRV_O_NO_BACKING);
7356 back_flags |= BDRV_O_NO_IO;
7358 backing_options = qdict_new();
7360 qdict_put_str(backing_options, "driver", backing_fmt);
7362 qdict_put_bool(backing_options, BDRV_OPT_FORCE_SHARE, true);
7364 bs = bdrv_open(full_backing, NULL, backing_options, back_flags,
7366 g_free(full_backing);
7368 error_append_hint(&local_err, "Could not open backing image.\n");
7372 error_setg(&local_err,
7373 "Backing file specified without backing format");
7374 error_append_hint(&local_err, "Detected format of %s.\n",
7375 bs->drv->format_name);
7379 /* Opened BS, have no size */
7380 size = bdrv_getlength(bs);
7382 error_setg_errno(errp, -size, "Could not get size of '%s'",
7387 qemu_opt_set_number(opts, BLOCK_OPT_SIZE, size, &error_abort);
7391 /* (backing_file && !(flags & BDRV_O_NO_BACKING)) */
7392 } else if (backing_file && !backing_fmt) {
7393 error_setg(&local_err,
7394 "Backing file specified without backing format");
7399 error_setg(errp, "Image creation needs a size parameter");
7404 printf("Formatting '%s', fmt=%s ", filename, fmt);
7405 qemu_opts_print(opts, " ");
7410 ret = bdrv_create(drv, filename, opts, &local_err);
7412 if (ret == -EFBIG) {
7413 /* This is generally a better message than whatever the driver would
7414 * deliver (especially because of the cluster_size_hint), since that
7415 * is most probably not much different from "image too large". */
7416 const char *cluster_size_hint = "";
7417 if (qemu_opt_get_size(opts, BLOCK_OPT_CLUSTER_SIZE, 0)) {
7418 cluster_size_hint = " (try using a larger cluster size)";
7420 error_setg(errp, "The image size is too large for file format '%s'"
7421 "%s", fmt, cluster_size_hint);
7422 error_free(local_err);
7427 qemu_opts_del(opts);
7428 qemu_opts_free(create_opts);
7429 error_propagate(errp, local_err);
7430 aio_context_release(qemu_get_aio_context());
7433 AioContext *bdrv_get_aio_context(BlockDriverState *bs)
7436 return bs ? bs->aio_context : qemu_get_aio_context();
7439 AioContext *coroutine_fn bdrv_co_enter(BlockDriverState *bs)
7441 Coroutine *self = qemu_coroutine_self();
7442 AioContext *old_ctx = qemu_coroutine_get_aio_context(self);
7443 AioContext *new_ctx;
7447 * Increase bs->in_flight to ensure that this operation is completed before
7448 * moving the node to a different AioContext. Read new_ctx only afterwards.
7450 bdrv_inc_in_flight(bs);
7452 new_ctx = bdrv_get_aio_context(bs);
7453 aio_co_reschedule_self(new_ctx);
7457 void coroutine_fn bdrv_co_leave(BlockDriverState *bs, AioContext *old_ctx)
7460 aio_co_reschedule_self(old_ctx);
7461 bdrv_dec_in_flight(bs);
7464 void coroutine_fn bdrv_co_lock(BlockDriverState *bs)
7466 AioContext *ctx = bdrv_get_aio_context(bs);
7468 /* In the main thread, bs->aio_context won't change concurrently */
7469 assert(qemu_get_current_aio_context() == qemu_get_aio_context());
7472 * We're in coroutine context, so we already hold the lock of the main
7473 * loop AioContext. Don't lock it twice to avoid deadlocks.
7475 assert(qemu_in_coroutine());
7476 if (ctx != qemu_get_aio_context()) {
7477 aio_context_acquire(ctx);
7481 void coroutine_fn bdrv_co_unlock(BlockDriverState *bs)
7483 AioContext *ctx = bdrv_get_aio_context(bs);
7485 assert(qemu_in_coroutine());
7486 if (ctx != qemu_get_aio_context()) {
7487 aio_context_release(ctx);
7491 static void bdrv_do_remove_aio_context_notifier(BdrvAioNotifier *ban)
7493 GLOBAL_STATE_CODE();
7494 QLIST_REMOVE(ban, list);
7498 static void bdrv_detach_aio_context(BlockDriverState *bs)
7500 BdrvAioNotifier *baf, *baf_tmp;
7502 assert(!bs->walking_aio_notifiers);
7503 GLOBAL_STATE_CODE();
7504 bs->walking_aio_notifiers = true;
7505 QLIST_FOREACH_SAFE(baf, &bs->aio_notifiers, list, baf_tmp) {
7507 bdrv_do_remove_aio_context_notifier(baf);
7509 baf->detach_aio_context(baf->opaque);
7512 /* Never mind iterating again to check for ->deleted. bdrv_close() will
7513 * remove remaining aio notifiers if we aren't called again.
7515 bs->walking_aio_notifiers = false;
7517 if (bs->drv && bs->drv->bdrv_detach_aio_context) {
7518 bs->drv->bdrv_detach_aio_context(bs);
7521 bs->aio_context = NULL;
7524 static void bdrv_attach_aio_context(BlockDriverState *bs,
7525 AioContext *new_context)
7527 BdrvAioNotifier *ban, *ban_tmp;
7528 GLOBAL_STATE_CODE();
7530 bs->aio_context = new_context;
7532 if (bs->drv && bs->drv->bdrv_attach_aio_context) {
7533 bs->drv->bdrv_attach_aio_context(bs, new_context);
7536 assert(!bs->walking_aio_notifiers);
7537 bs->walking_aio_notifiers = true;
7538 QLIST_FOREACH_SAFE(ban, &bs->aio_notifiers, list, ban_tmp) {
7540 bdrv_do_remove_aio_context_notifier(ban);
7542 ban->attached_aio_context(new_context, ban->opaque);
7545 bs->walking_aio_notifiers = false;
7548 typedef struct BdrvStateSetAioContext {
7549 AioContext *new_ctx;
7550 BlockDriverState *bs;
7551 } BdrvStateSetAioContext;
7553 static bool bdrv_parent_change_aio_context(BdrvChild *c, AioContext *ctx,
7554 GHashTable *visited,
7558 GLOBAL_STATE_CODE();
7559 if (g_hash_table_contains(visited, c)) {
7562 g_hash_table_add(visited, c);
7565 * A BdrvChildClass that doesn't handle AioContext changes cannot
7566 * tolerate any AioContext changes
7568 if (!c->klass->change_aio_ctx) {
7569 char *user = bdrv_child_user_desc(c);
7570 error_setg(errp, "Changing iothreads is not supported by %s", user);
7574 if (!c->klass->change_aio_ctx(c, ctx, visited, tran, errp)) {
7575 assert(!errp || *errp);
7581 bool bdrv_child_change_aio_context(BdrvChild *c, AioContext *ctx,
7582 GHashTable *visited, Transaction *tran,
7585 GLOBAL_STATE_CODE();
7586 if (g_hash_table_contains(visited, c)) {
7589 g_hash_table_add(visited, c);
7590 return bdrv_change_aio_context(c->bs, ctx, visited, tran, errp);
7593 static void bdrv_set_aio_context_clean(void *opaque)
7595 BdrvStateSetAioContext *state = (BdrvStateSetAioContext *) opaque;
7596 BlockDriverState *bs = (BlockDriverState *) state->bs;
7598 /* Paired with bdrv_drained_begin in bdrv_change_aio_context() */
7599 bdrv_drained_end(bs);
7604 static void bdrv_set_aio_context_commit(void *opaque)
7606 BdrvStateSetAioContext *state = (BdrvStateSetAioContext *) opaque;
7607 BlockDriverState *bs = (BlockDriverState *) state->bs;
7608 AioContext *new_context = state->new_ctx;
7609 AioContext *old_context = bdrv_get_aio_context(bs);
7612 * Take the old AioContex when detaching it from bs.
7613 * At this point, new_context lock is already acquired, and we are now
7614 * also taking old_context. This is safe as long as bdrv_detach_aio_context
7615 * does not call AIO_POLL_WHILE().
7617 if (old_context != qemu_get_aio_context()) {
7618 aio_context_acquire(old_context);
7620 bdrv_detach_aio_context(bs);
7621 if (old_context != qemu_get_aio_context()) {
7622 aio_context_release(old_context);
7624 bdrv_attach_aio_context(bs, new_context);
7627 static TransactionActionDrv set_aio_context = {
7628 .commit = bdrv_set_aio_context_commit,
7629 .clean = bdrv_set_aio_context_clean,
7633 * Changes the AioContext used for fd handlers, timers, and BHs by this
7634 * BlockDriverState and all its children and parents.
7636 * Must be called from the main AioContext.
7638 * The caller must own the AioContext lock for the old AioContext of bs, but it
7639 * must not own the AioContext lock for new_context (unless new_context is the
7640 * same as the current context of bs).
7642 * @visited will accumulate all visited BdrvChild objects. The caller is
7643 * responsible for freeing the list afterwards.
7645 static bool bdrv_change_aio_context(BlockDriverState *bs, AioContext *ctx,
7646 GHashTable *visited, Transaction *tran,
7650 BdrvStateSetAioContext *state;
7652 GLOBAL_STATE_CODE();
7654 if (bdrv_get_aio_context(bs) == ctx) {
7658 QLIST_FOREACH(c, &bs->parents, next_parent) {
7659 if (!bdrv_parent_change_aio_context(c, ctx, visited, tran, errp)) {
7664 QLIST_FOREACH(c, &bs->children, next) {
7665 if (!bdrv_child_change_aio_context(c, ctx, visited, tran, errp)) {
7670 state = g_new(BdrvStateSetAioContext, 1);
7671 *state = (BdrvStateSetAioContext) {
7676 /* Paired with bdrv_drained_end in bdrv_set_aio_context_clean() */
7677 bdrv_drained_begin(bs);
7679 tran_add(tran, &set_aio_context, state);
7685 * Change bs's and recursively all of its parents' and children's AioContext
7686 * to the given new context, returning an error if that isn't possible.
7688 * If ignore_child is not NULL, that child (and its subgraph) will not
7691 * This function still requires the caller to take the bs current
7692 * AioContext lock, otherwise draining will fail since AIO_WAIT_WHILE
7693 * assumes the lock is always held if bs is in another AioContext.
7694 * For the same reason, it temporarily also holds the new AioContext, since
7695 * bdrv_drained_end calls BDRV_POLL_WHILE that assumes the lock is taken too.
7696 * Therefore the new AioContext lock must not be taken by the caller.
7698 int bdrv_try_change_aio_context(BlockDriverState *bs, AioContext *ctx,
7699 BdrvChild *ignore_child, Error **errp)
7702 GHashTable *visited;
7704 AioContext *old_context = bdrv_get_aio_context(bs);
7705 GLOBAL_STATE_CODE();
7708 * Recursion phase: go through all nodes of the graph.
7709 * Take care of checking that all nodes support changing AioContext
7710 * and drain them, building a linear list of callbacks to run if everything
7711 * is successful (the transaction itself).
7714 visited = g_hash_table_new(NULL, NULL);
7716 g_hash_table_add(visited, ignore_child);
7718 ret = bdrv_change_aio_context(bs, ctx, visited, tran, errp);
7719 g_hash_table_destroy(visited);
7722 * Linear phase: go through all callbacks collected in the transaction.
7723 * Run all callbacks collected in the recursion to switch all nodes
7724 * AioContext lock (transaction commit), or undo all changes done in the
7725 * recursion (transaction abort).
7729 /* Just run clean() callbacks. No AioContext changed. */
7735 * Release old AioContext, it won't be needed anymore, as all
7736 * bdrv_drained_begin() have been called already.
7738 if (qemu_get_aio_context() != old_context) {
7739 aio_context_release(old_context);
7743 * Acquire new AioContext since bdrv_drained_end() is going to be called
7744 * after we switched all nodes in the new AioContext, and the function
7745 * assumes that the lock of the bs is always taken.
7747 if (qemu_get_aio_context() != ctx) {
7748 aio_context_acquire(ctx);
7753 if (qemu_get_aio_context() != ctx) {
7754 aio_context_release(ctx);
7757 /* Re-acquire the old AioContext, since the caller takes and releases it. */
7758 if (qemu_get_aio_context() != old_context) {
7759 aio_context_acquire(old_context);
7765 void bdrv_add_aio_context_notifier(BlockDriverState *bs,
7766 void (*attached_aio_context)(AioContext *new_context, void *opaque),
7767 void (*detach_aio_context)(void *opaque), void *opaque)
7769 BdrvAioNotifier *ban = g_new(BdrvAioNotifier, 1);
7770 *ban = (BdrvAioNotifier){
7771 .attached_aio_context = attached_aio_context,
7772 .detach_aio_context = detach_aio_context,
7775 GLOBAL_STATE_CODE();
7777 QLIST_INSERT_HEAD(&bs->aio_notifiers, ban, list);
7780 void bdrv_remove_aio_context_notifier(BlockDriverState *bs,
7781 void (*attached_aio_context)(AioContext *,
7783 void (*detach_aio_context)(void *),
7786 BdrvAioNotifier *ban, *ban_next;
7787 GLOBAL_STATE_CODE();
7789 QLIST_FOREACH_SAFE(ban, &bs->aio_notifiers, list, ban_next) {
7790 if (ban->attached_aio_context == attached_aio_context &&
7791 ban->detach_aio_context == detach_aio_context &&
7792 ban->opaque == opaque &&
7793 ban->deleted == false)
7795 if (bs->walking_aio_notifiers) {
7796 ban->deleted = true;
7798 bdrv_do_remove_aio_context_notifier(ban);
7807 int bdrv_amend_options(BlockDriverState *bs, QemuOpts *opts,
7808 BlockDriverAmendStatusCB *status_cb, void *cb_opaque,
7812 GLOBAL_STATE_CODE();
7814 error_setg(errp, "Node is ejected");
7817 if (!bs->drv->bdrv_amend_options) {
7818 error_setg(errp, "Block driver '%s' does not support option amendment",
7819 bs->drv->format_name);
7822 return bs->drv->bdrv_amend_options(bs, opts, status_cb,
7823 cb_opaque, force, errp);
7827 * This function checks whether the given @to_replace is allowed to be
7828 * replaced by a node that always shows the same data as @bs. This is
7829 * used for example to verify whether the mirror job can replace
7830 * @to_replace by the target mirrored from @bs.
7831 * To be replaceable, @bs and @to_replace may either be guaranteed to
7832 * always show the same data (because they are only connected through
7833 * filters), or some driver may allow replacing one of its children
7834 * because it can guarantee that this child's data is not visible at
7835 * all (for example, for dissenting quorum children that have no other
7838 bool bdrv_recurse_can_replace(BlockDriverState *bs,
7839 BlockDriverState *to_replace)
7841 BlockDriverState *filtered;
7843 GLOBAL_STATE_CODE();
7845 if (!bs || !bs->drv) {
7849 if (bs == to_replace) {
7853 /* See what the driver can do */
7854 if (bs->drv->bdrv_recurse_can_replace) {
7855 return bs->drv->bdrv_recurse_can_replace(bs, to_replace);
7858 /* For filters without an own implementation, we can recurse on our own */
7859 filtered = bdrv_filter_bs(bs);
7861 return bdrv_recurse_can_replace(filtered, to_replace);
7869 * Check whether the given @node_name can be replaced by a node that
7870 * has the same data as @parent_bs. If so, return @node_name's BDS;
7873 * @node_name must be a (recursive) *child of @parent_bs (or this
7874 * function will return NULL).
7876 * The result (whether the node can be replaced or not) is only valid
7877 * for as long as no graph or permission changes occur.
7879 BlockDriverState *check_to_replace_node(BlockDriverState *parent_bs,
7880 const char *node_name, Error **errp)
7882 BlockDriverState *to_replace_bs = bdrv_find_node(node_name);
7883 AioContext *aio_context;
7885 GLOBAL_STATE_CODE();
7887 if (!to_replace_bs) {
7888 error_setg(errp, "Failed to find node with node-name='%s'", node_name);
7892 aio_context = bdrv_get_aio_context(to_replace_bs);
7893 aio_context_acquire(aio_context);
7895 if (bdrv_op_is_blocked(to_replace_bs, BLOCK_OP_TYPE_REPLACE, errp)) {
7896 to_replace_bs = NULL;
7900 /* We don't want arbitrary node of the BDS chain to be replaced only the top
7901 * most non filter in order to prevent data corruption.
7902 * Another benefit is that this tests exclude backing files which are
7903 * blocked by the backing blockers.
7905 if (!bdrv_recurse_can_replace(parent_bs, to_replace_bs)) {
7906 error_setg(errp, "Cannot replace '%s' by a node mirrored from '%s', "
7907 "because it cannot be guaranteed that doing so would not "
7908 "lead to an abrupt change of visible data",
7909 node_name, parent_bs->node_name);
7910 to_replace_bs = NULL;
7915 aio_context_release(aio_context);
7916 return to_replace_bs;
7920 * Iterates through the list of runtime option keys that are said to
7921 * be "strong" for a BDS. An option is called "strong" if it changes
7922 * a BDS's data. For example, the null block driver's "size" and
7923 * "read-zeroes" options are strong, but its "latency-ns" option is
7926 * If a key returned by this function ends with a dot, all options
7927 * starting with that prefix are strong.
7929 static const char *const *strong_options(BlockDriverState *bs,
7930 const char *const *curopt)
7932 static const char *const global_options[] = {
7933 "driver", "filename", NULL
7937 return &global_options[0];
7941 if (curopt == &global_options[ARRAY_SIZE(global_options) - 1] && bs->drv) {
7942 curopt = bs->drv->strong_runtime_opts;
7945 return (curopt && *curopt) ? curopt : NULL;
7949 * Copies all strong runtime options from bs->options to the given
7950 * QDict. The set of strong option keys is determined by invoking
7953 * Returns true iff any strong option was present in bs->options (and
7954 * thus copied to the target QDict) with the exception of "filename"
7955 * and "driver". The caller is expected to use this value to decide
7956 * whether the existence of strong options prevents the generation of
7959 static bool append_strong_runtime_options(QDict *d, BlockDriverState *bs)
7961 bool found_any = false;
7962 const char *const *option_name = NULL;
7968 while ((option_name = strong_options(bs, option_name))) {
7969 bool option_given = false;
7971 assert(strlen(*option_name) > 0);
7972 if ((*option_name)[strlen(*option_name) - 1] != '.') {
7973 QObject *entry = qdict_get(bs->options, *option_name);
7978 qdict_put_obj(d, *option_name, qobject_ref(entry));
7979 option_given = true;
7981 const QDictEntry *entry;
7982 for (entry = qdict_first(bs->options); entry;
7983 entry = qdict_next(bs->options, entry))
7985 if (strstart(qdict_entry_key(entry), *option_name, NULL)) {
7986 qdict_put_obj(d, qdict_entry_key(entry),
7987 qobject_ref(qdict_entry_value(entry)));
7988 option_given = true;
7993 /* While "driver" and "filename" need to be included in a JSON filename,
7994 * their existence does not prohibit generation of a plain filename. */
7995 if (!found_any && option_given &&
7996 strcmp(*option_name, "driver") && strcmp(*option_name, "filename"))
8002 if (!qdict_haskey(d, "driver")) {
8003 /* Drivers created with bdrv_new_open_driver() may not have a
8004 * @driver option. Add it here. */
8005 qdict_put_str(d, "driver", bs->drv->format_name);
8011 /* Note: This function may return false positives; it may return true
8012 * even if opening the backing file specified by bs's image header
8013 * would result in exactly bs->backing. */
8014 static bool bdrv_backing_overridden(BlockDriverState *bs)
8016 GLOBAL_STATE_CODE();
8018 return strcmp(bs->auto_backing_file,
8019 bs->backing->bs->filename);
8021 /* No backing BDS, so if the image header reports any backing
8022 * file, it must have been suppressed */
8023 return bs->auto_backing_file[0] != '\0';
8027 /* Updates the following BDS fields:
8028 * - exact_filename: A filename which may be used for opening a block device
8029 * which (mostly) equals the given BDS (even without any
8030 * other options; so reading and writing must return the same
8031 * results, but caching etc. may be different)
8032 * - full_open_options: Options which, when given when opening a block device
8033 * (without a filename), result in a BDS (mostly)
8034 * equalling the given one
8035 * - filename: If exact_filename is set, it is copied here. Otherwise,
8036 * full_open_options is converted to a JSON object, prefixed with
8037 * "json:" (for use through the JSON pseudo protocol) and put here.
8039 void bdrv_refresh_filename(BlockDriverState *bs)
8041 BlockDriver *drv = bs->drv;
8043 BlockDriverState *primary_child_bs;
8045 bool backing_overridden;
8046 bool generate_json_filename; /* Whether our default implementation should
8047 fill exact_filename (false) or not (true) */
8049 GLOBAL_STATE_CODE();
8055 /* This BDS's file name may depend on any of its children's file names, so
8056 * refresh those first */
8057 QLIST_FOREACH(child, &bs->children, next) {
8058 bdrv_refresh_filename(child->bs);
8062 /* For implicit nodes, just copy everything from the single child */
8063 child = QLIST_FIRST(&bs->children);
8064 assert(QLIST_NEXT(child, next) == NULL);
8066 pstrcpy(bs->exact_filename, sizeof(bs->exact_filename),
8067 child->bs->exact_filename);
8068 pstrcpy(bs->filename, sizeof(bs->filename), child->bs->filename);
8070 qobject_unref(bs->full_open_options);
8071 bs->full_open_options = qobject_ref(child->bs->full_open_options);
8076 backing_overridden = bdrv_backing_overridden(bs);
8078 if (bs->open_flags & BDRV_O_NO_IO) {
8079 /* Without I/O, the backing file does not change anything.
8080 * Therefore, in such a case (primarily qemu-img), we can
8081 * pretend the backing file has not been overridden even if
8082 * it technically has been. */
8083 backing_overridden = false;
8086 /* Gather the options QDict */
8088 generate_json_filename = append_strong_runtime_options(opts, bs);
8089 generate_json_filename |= backing_overridden;
8091 if (drv->bdrv_gather_child_options) {
8092 /* Some block drivers may not want to present all of their children's
8093 * options, or name them differently from BdrvChild.name */
8094 drv->bdrv_gather_child_options(bs, opts, backing_overridden);
8096 QLIST_FOREACH(child, &bs->children, next) {
8097 if (child == bs->backing && !backing_overridden) {
8098 /* We can skip the backing BDS if it has not been overridden */
8102 qdict_put(opts, child->name,
8103 qobject_ref(child->bs->full_open_options));
8106 if (backing_overridden && !bs->backing) {
8107 /* Force no backing file */
8108 qdict_put_null(opts, "backing");
8112 qobject_unref(bs->full_open_options);
8113 bs->full_open_options = opts;
8115 primary_child_bs = bdrv_primary_bs(bs);
8117 if (drv->bdrv_refresh_filename) {
8118 /* Obsolete information is of no use here, so drop the old file name
8119 * information before refreshing it */
8120 bs->exact_filename[0] = '\0';
8122 drv->bdrv_refresh_filename(bs);
8123 } else if (primary_child_bs) {
8125 * Try to reconstruct valid information from the underlying
8126 * file -- this only works for format nodes (filter nodes
8127 * cannot be probed and as such must be selected by the user
8128 * either through an options dict, or through a special
8129 * filename which the filter driver must construct in its
8130 * .bdrv_refresh_filename() implementation).
8133 bs->exact_filename[0] = '\0';
8136 * We can use the underlying file's filename if:
8137 * - it has a filename,
8138 * - the current BDS is not a filter,
8139 * - the file is a protocol BDS, and
8140 * - opening that file (as this BDS's format) will automatically create
8141 * the BDS tree we have right now, that is:
8142 * - the user did not significantly change this BDS's behavior with
8143 * some explicit (strong) options
8144 * - no non-file child of this BDS has been overridden by the user
8145 * Both of these conditions are represented by generate_json_filename.
8147 if (primary_child_bs->exact_filename[0] &&
8148 primary_child_bs->drv->bdrv_file_open &&
8149 !drv->is_filter && !generate_json_filename)
8151 strcpy(bs->exact_filename, primary_child_bs->exact_filename);
8155 if (bs->exact_filename[0]) {
8156 pstrcpy(bs->filename, sizeof(bs->filename), bs->exact_filename);
8158 GString *json = qobject_to_json(QOBJECT(bs->full_open_options));
8159 if (snprintf(bs->filename, sizeof(bs->filename), "json:%s",
8160 json->str) >= sizeof(bs->filename)) {
8161 /* Give user a hint if we truncated things. */
8162 strcpy(bs->filename + sizeof(bs->filename) - 4, "...");
8164 g_string_free(json, true);
8168 char *bdrv_dirname(BlockDriverState *bs, Error **errp)
8170 BlockDriver *drv = bs->drv;
8171 BlockDriverState *child_bs;
8173 GLOBAL_STATE_CODE();
8176 error_setg(errp, "Node '%s' is ejected", bs->node_name);
8180 if (drv->bdrv_dirname) {
8181 return drv->bdrv_dirname(bs, errp);
8184 child_bs = bdrv_primary_bs(bs);
8186 return bdrv_dirname(child_bs, errp);
8189 bdrv_refresh_filename(bs);
8190 if (bs->exact_filename[0] != '\0') {
8191 return path_combine(bs->exact_filename, "");
8194 error_setg(errp, "Cannot generate a base directory for %s nodes",
8200 * Hot add/remove a BDS's child. So the user can take a child offline when
8201 * it is broken and take a new child online
8203 void bdrv_add_child(BlockDriverState *parent_bs, BlockDriverState *child_bs,
8206 GLOBAL_STATE_CODE();
8207 if (!parent_bs->drv || !parent_bs->drv->bdrv_add_child) {
8208 error_setg(errp, "The node %s does not support adding a child",
8209 bdrv_get_device_or_node_name(parent_bs));
8214 * Non-zoned block drivers do not follow zoned storage constraints
8215 * (i.e. sequential writes to zones). Refuse mixing zoned and non-zoned
8216 * drivers in a graph.
8218 if (!parent_bs->drv->supports_zoned_children &&
8219 child_bs->bl.zoned == BLK_Z_HM) {
8221 * The host-aware model allows zoned storage constraints and random
8222 * write. Allow mixing host-aware and non-zoned drivers. Using
8223 * host-aware device as a regular device.
8225 error_setg(errp, "Cannot add a %s child to a %s parent",
8226 child_bs->bl.zoned == BLK_Z_HM ? "zoned" : "non-zoned",
8227 parent_bs->drv->supports_zoned_children ?
8228 "support zoned children" : "not support zoned children");
8232 if (!QLIST_EMPTY(&child_bs->parents)) {
8233 error_setg(errp, "The node %s already has a parent",
8234 child_bs->node_name);
8238 parent_bs->drv->bdrv_add_child(parent_bs, child_bs, errp);
8241 void bdrv_del_child(BlockDriverState *parent_bs, BdrvChild *child, Error **errp)
8245 GLOBAL_STATE_CODE();
8246 if (!parent_bs->drv || !parent_bs->drv->bdrv_del_child) {
8247 error_setg(errp, "The node %s does not support removing a child",
8248 bdrv_get_device_or_node_name(parent_bs));
8252 QLIST_FOREACH(tmp, &parent_bs->children, next) {
8259 error_setg(errp, "The node %s does not have a child named %s",
8260 bdrv_get_device_or_node_name(parent_bs),
8261 bdrv_get_device_or_node_name(child->bs));
8265 parent_bs->drv->bdrv_del_child(parent_bs, child, errp);
8268 int bdrv_make_empty(BdrvChild *c, Error **errp)
8270 BlockDriver *drv = c->bs->drv;
8273 GLOBAL_STATE_CODE();
8274 assert(c->perm & (BLK_PERM_WRITE | BLK_PERM_WRITE_UNCHANGED));
8276 if (!drv->bdrv_make_empty) {
8277 error_setg(errp, "%s does not support emptying nodes",
8282 ret = drv->bdrv_make_empty(c->bs);
8284 error_setg_errno(errp, -ret, "Failed to empty %s",
8293 * Return the child that @bs acts as an overlay for, and from which data may be
8294 * copied in COW or COR operations. Usually this is the backing file.
8296 BdrvChild *bdrv_cow_child(BlockDriverState *bs)
8300 if (!bs || !bs->drv) {
8304 if (bs->drv->is_filter) {
8312 assert(bs->backing->role & BDRV_CHILD_COW);
8317 * If @bs acts as a filter for exactly one of its children, return
8320 BdrvChild *bdrv_filter_child(BlockDriverState *bs)
8325 if (!bs || !bs->drv) {
8329 if (!bs->drv->is_filter) {
8333 /* Only one of @backing or @file may be used */
8334 assert(!(bs->backing && bs->file));
8336 c = bs->backing ?: bs->file;
8341 assert(c->role & BDRV_CHILD_FILTERED);
8346 * Return either the result of bdrv_cow_child() or bdrv_filter_child(),
8347 * whichever is non-NULL.
8349 * Return NULL if both are NULL.
8351 BdrvChild *bdrv_filter_or_cow_child(BlockDriverState *bs)
8353 BdrvChild *cow_child = bdrv_cow_child(bs);
8354 BdrvChild *filter_child = bdrv_filter_child(bs);
8357 /* Filter nodes cannot have COW backing files */
8358 assert(!(cow_child && filter_child));
8360 return cow_child ?: filter_child;
8364 * Return the primary child of this node: For filters, that is the
8365 * filtered child. For other nodes, that is usually the child storing
8367 * (A generally more helpful description is that this is (usually) the
8368 * child that has the same filename as @bs.)
8370 * Drivers do not necessarily have a primary child; for example quorum
8373 BdrvChild *bdrv_primary_child(BlockDriverState *bs)
8375 BdrvChild *c, *found = NULL;
8378 QLIST_FOREACH(c, &bs->children, next) {
8379 if (c->role & BDRV_CHILD_PRIMARY) {
8388 static BlockDriverState *bdrv_do_skip_filters(BlockDriverState *bs,
8389 bool stop_on_explicit_filter)
8397 while (!(stop_on_explicit_filter && !bs->implicit)) {
8398 c = bdrv_filter_child(bs);
8401 * A filter that is embedded in a working block graph must
8402 * have a child. Assert this here so this function does
8403 * not return a filter node that is not expected by the
8406 assert(!bs->drv || !bs->drv->is_filter);
8412 * Note that this treats nodes with bs->drv == NULL as not being
8413 * filters (bs->drv == NULL should be replaced by something else
8415 * The advantage of this behavior is that this function will thus
8416 * always return a non-NULL value (given a non-NULL @bs).
8423 * Return the first BDS that has not been added implicitly or that
8424 * does not have a filtered child down the chain starting from @bs
8425 * (including @bs itself).
8427 BlockDriverState *bdrv_skip_implicit_filters(BlockDriverState *bs)
8429 GLOBAL_STATE_CODE();
8430 return bdrv_do_skip_filters(bs, true);
8434 * Return the first BDS that does not have a filtered child down the
8435 * chain starting from @bs (including @bs itself).
8437 BlockDriverState *bdrv_skip_filters(BlockDriverState *bs)
8440 return bdrv_do_skip_filters(bs, false);
8444 * For a backing chain, return the first non-filter backing image of
8445 * the first non-filter image.
8447 BlockDriverState *bdrv_backing_chain_next(BlockDriverState *bs)
8450 return bdrv_skip_filters(bdrv_cow_bs(bdrv_skip_filters(bs)));
8454 * Check whether [offset, offset + bytes) overlaps with the cached
8455 * block-status data region.
8457 * If so, and @pnum is not NULL, set *pnum to `bsc.data_end - offset`,
8458 * which is what bdrv_bsc_is_data()'s interface needs.
8459 * Otherwise, *pnum is not touched.
8461 static bool bdrv_bsc_range_overlaps_locked(BlockDriverState *bs,
8462 int64_t offset, int64_t bytes,
8465 BdrvBlockStatusCache *bsc = qatomic_rcu_read(&bs->block_status_cache);
8469 qatomic_read(&bsc->valid) &&
8470 ranges_overlap(offset, bytes, bsc->data_start,
8471 bsc->data_end - bsc->data_start);
8473 if (overlaps && pnum) {
8474 *pnum = bsc->data_end - offset;
8481 * See block_int.h for this function's documentation.
8483 bool bdrv_bsc_is_data(BlockDriverState *bs, int64_t offset, int64_t *pnum)
8486 RCU_READ_LOCK_GUARD();
8487 return bdrv_bsc_range_overlaps_locked(bs, offset, 1, pnum);
8491 * See block_int.h for this function's documentation.
8493 void bdrv_bsc_invalidate_range(BlockDriverState *bs,
8494 int64_t offset, int64_t bytes)
8497 RCU_READ_LOCK_GUARD();
8499 if (bdrv_bsc_range_overlaps_locked(bs, offset, bytes, NULL)) {
8500 qatomic_set(&bs->block_status_cache->valid, false);
8505 * See block_int.h for this function's documentation.
8507 void bdrv_bsc_fill(BlockDriverState *bs, int64_t offset, int64_t bytes)
8509 BdrvBlockStatusCache *new_bsc = g_new(BdrvBlockStatusCache, 1);
8510 BdrvBlockStatusCache *old_bsc;
8513 *new_bsc = (BdrvBlockStatusCache) {
8515 .data_start = offset,
8516 .data_end = offset + bytes,
8519 QEMU_LOCK_GUARD(&bs->bsc_modify_lock);
8521 old_bsc = qatomic_rcu_read(&bs->block_status_cache);
8522 qatomic_rcu_set(&bs->block_status_cache, new_bsc);
8524 g_free_rcu(old_bsc, rcu);