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 * GRAPH_RDLOCK
375 bdrv_make_absolute_filename(BlockDriverState
*relative_to
,
376 const char *filename
, Error
**errp
)
378 char *dir
, *full_name
;
380 if (!filename
|| filename
[0] == '\0') {
382 } else if (path_has_protocol(filename
) || path_is_absolute(filename
)) {
383 return g_strdup(filename
);
386 dir
= bdrv_dirname(relative_to
, errp
);
391 full_name
= g_strconcat(dir
, filename
, NULL
);
396 char *bdrv_get_full_backing_filename(BlockDriverState
*bs
, Error
**errp
)
399 return bdrv_make_absolute_filename(bs
, bs
->backing_file
, errp
);
402 void bdrv_register(BlockDriver
*bdrv
)
404 assert(bdrv
->format_name
);
406 QLIST_INSERT_HEAD(&bdrv_drivers
, bdrv
, list
);
409 BlockDriverState
*bdrv_new(void)
411 BlockDriverState
*bs
;
416 bs
= g_new0(BlockDriverState
, 1);
417 QLIST_INIT(&bs
->dirty_bitmaps
);
418 for (i
= 0; i
< BLOCK_OP_TYPE_MAX
; i
++) {
419 QLIST_INIT(&bs
->op_blockers
[i
]);
421 qemu_mutex_init(&bs
->reqs_lock
);
422 qemu_mutex_init(&bs
->dirty_bitmap_mutex
);
424 bs
->aio_context
= qemu_get_aio_context();
426 qemu_co_queue_init(&bs
->flush_queue
);
428 qemu_co_mutex_init(&bs
->bsc_modify_lock
);
429 bs
->block_status_cache
= g_new0(BdrvBlockStatusCache
, 1);
431 for (i
= 0; i
< bdrv_drain_all_count
; i
++) {
432 bdrv_drained_begin(bs
);
435 QTAILQ_INSERT_TAIL(&all_bdrv_states
, bs
, bs_list
);
440 static BlockDriver
*bdrv_do_find_format(const char *format_name
)
445 QLIST_FOREACH(drv1
, &bdrv_drivers
, list
) {
446 if (!strcmp(drv1
->format_name
, format_name
)) {
454 BlockDriver
*bdrv_find_format(const char *format_name
)
461 drv1
= bdrv_do_find_format(format_name
);
466 /* The driver isn't registered, maybe we need to load a module */
467 for (i
= 0; i
< (int)ARRAY_SIZE(block_driver_modules
); ++i
) {
468 if (!strcmp(block_driver_modules
[i
].format_name
, format_name
)) {
469 Error
*local_err
= NULL
;
470 int rv
= block_module_load(block_driver_modules
[i
].library_name
,
473 return bdrv_do_find_format(format_name
);
475 error_report_err(local_err
);
483 static int bdrv_format_is_whitelisted(const char *format_name
, bool read_only
)
485 static const char *whitelist_rw
[] = {
486 CONFIG_BDRV_RW_WHITELIST
489 static const char *whitelist_ro
[] = {
490 CONFIG_BDRV_RO_WHITELIST
495 if (!whitelist_rw
[0] && !whitelist_ro
[0]) {
496 return 1; /* no whitelist, anything goes */
499 for (p
= whitelist_rw
; *p
; p
++) {
500 if (!strcmp(format_name
, *p
)) {
505 for (p
= whitelist_ro
; *p
; p
++) {
506 if (!strcmp(format_name
, *p
)) {
514 int bdrv_is_whitelisted(BlockDriver
*drv
, bool read_only
)
517 return bdrv_format_is_whitelisted(drv
->format_name
, read_only
);
520 bool bdrv_uses_whitelist(void)
522 return use_bdrv_whitelist
;
525 typedef struct CreateCo
{
533 int coroutine_fn
bdrv_co_create(BlockDriver
*drv
, const char *filename
,
534 QemuOpts
*opts
, Error
**errp
)
540 if (!drv
->bdrv_co_create_opts
) {
541 error_setg(errp
, "Driver '%s' does not support image creation",
546 ret
= drv
->bdrv_co_create_opts(drv
, filename
, opts
, errp
);
547 if (ret
< 0 && !*errp
) {
548 error_setg_errno(errp
, -ret
, "Could not create image");
555 * Helper function for bdrv_create_file_fallback(): Resize @blk to at
556 * least the given @minimum_size.
558 * On success, return @blk's actual length.
559 * Otherwise, return -errno.
561 static int64_t coroutine_fn GRAPH_UNLOCKED
562 create_file_fallback_truncate(BlockBackend
*blk
, int64_t minimum_size
,
565 Error
*local_err
= NULL
;
571 ret
= blk_co_truncate(blk
, minimum_size
, false, PREALLOC_MODE_OFF
, 0,
573 if (ret
< 0 && ret
!= -ENOTSUP
) {
574 error_propagate(errp
, local_err
);
578 size
= blk_co_getlength(blk
);
580 error_free(local_err
);
581 error_setg_errno(errp
, -size
,
582 "Failed to inquire the new image file's length");
586 if (size
< minimum_size
) {
587 /* Need to grow the image, but we failed to do that */
588 error_propagate(errp
, local_err
);
592 error_free(local_err
);
599 * Helper function for bdrv_create_file_fallback(): Zero the first
600 * sector to remove any potentially pre-existing image header.
602 static int coroutine_fn
603 create_file_fallback_zero_first_sector(BlockBackend
*blk
,
604 int64_t current_size
,
607 int64_t bytes_to_clear
;
612 bytes_to_clear
= MIN(current_size
, BDRV_SECTOR_SIZE
);
613 if (bytes_to_clear
) {
614 ret
= blk_co_pwrite_zeroes(blk
, 0, bytes_to_clear
, BDRV_REQ_MAY_UNMAP
);
616 error_setg_errno(errp
, -ret
,
617 "Failed to clear the new image's first sector");
626 * Simple implementation of bdrv_co_create_opts for protocol drivers
627 * which only support creation via opening a file
628 * (usually existing raw storage device)
630 int coroutine_fn
bdrv_co_create_opts_simple(BlockDriver
*drv
,
631 const char *filename
,
639 PreallocMode prealloc
;
640 Error
*local_err
= NULL
;
645 size
= qemu_opt_get_size_del(opts
, BLOCK_OPT_SIZE
, 0);
646 buf
= qemu_opt_get_del(opts
, BLOCK_OPT_PREALLOC
);
647 prealloc
= qapi_enum_parse(&PreallocMode_lookup
, buf
,
648 PREALLOC_MODE_OFF
, &local_err
);
651 error_propagate(errp
, local_err
);
655 if (prealloc
!= PREALLOC_MODE_OFF
) {
656 error_setg(errp
, "Unsupported preallocation mode '%s'",
657 PreallocMode_str(prealloc
));
661 options
= qdict_new();
662 qdict_put_str(options
, "driver", drv
->format_name
);
664 blk
= blk_co_new_open(filename
, NULL
, options
,
665 BDRV_O_RDWR
| BDRV_O_RESIZE
, errp
);
667 error_prepend(errp
, "Protocol driver '%s' does not support creating "
668 "new images, so an existing image must be selected as "
669 "the target; however, opening the given target as an "
670 "existing image failed: ",
675 size
= create_file_fallback_truncate(blk
, size
, errp
);
681 ret
= create_file_fallback_zero_first_sector(blk
, size
, errp
);
692 int coroutine_fn
bdrv_co_create_file(const char *filename
, QemuOpts
*opts
,
695 QemuOpts
*protocol_opts
;
702 drv
= bdrv_find_protocol(filename
, true, errp
);
707 if (!drv
->create_opts
) {
708 error_setg(errp
, "Driver '%s' does not support image creation",
714 * 'opts' contains a QemuOptsList with a combination of format and protocol
717 * The format properly removes its options, but the default values remain
718 * in 'opts->list'. So if the protocol has options with the same name
719 * (e.g. rbd has 'cluster_size' as qcow2), it will see the default values
720 * of the format, since for overlapping options, the format wins.
722 * To avoid this issue, lets convert QemuOpts to QDict, in this way we take
723 * only the set options, and then convert it back to QemuOpts, using the
724 * create_opts of the protocol. So the new QemuOpts, will contain only the
727 qdict
= qemu_opts_to_qdict(opts
, NULL
);
728 protocol_opts
= qemu_opts_from_qdict(drv
->create_opts
, qdict
, errp
);
729 if (protocol_opts
== NULL
) {
734 ret
= bdrv_co_create(drv
, filename
, protocol_opts
, errp
);
736 qemu_opts_del(protocol_opts
);
737 qobject_unref(qdict
);
741 int coroutine_fn
bdrv_co_delete_file(BlockDriverState
*bs
, Error
**errp
)
743 Error
*local_err
= NULL
;
748 assert_bdrv_graph_readable();
751 error_setg(errp
, "Block node '%s' is not opened", bs
->filename
);
755 if (!bs
->drv
->bdrv_co_delete_file
) {
756 error_setg(errp
, "Driver '%s' does not support image deletion",
757 bs
->drv
->format_name
);
761 ret
= bs
->drv
->bdrv_co_delete_file(bs
, &local_err
);
763 error_propagate(errp
, local_err
);
769 void coroutine_fn
bdrv_co_delete_file_noerr(BlockDriverState
*bs
)
771 Error
*local_err
= NULL
;
779 ret
= bdrv_co_delete_file(bs
, &local_err
);
781 * ENOTSUP will happen if the block driver doesn't support
782 * the 'bdrv_co_delete_file' interface. This is a predictable
783 * scenario and shouldn't be reported back to the user.
785 if (ret
== -ENOTSUP
) {
786 error_free(local_err
);
787 } else if (ret
< 0) {
788 error_report_err(local_err
);
793 * Try to get @bs's logical and physical block size.
794 * On success, store them in @bsz struct and return 0.
795 * On failure return -errno.
796 * @bs must not be empty.
798 int bdrv_probe_blocksizes(BlockDriverState
*bs
, BlockSizes
*bsz
)
800 BlockDriver
*drv
= bs
->drv
;
801 BlockDriverState
*filtered
= bdrv_filter_bs(bs
);
804 if (drv
&& drv
->bdrv_probe_blocksizes
) {
805 return drv
->bdrv_probe_blocksizes(bs
, bsz
);
806 } else if (filtered
) {
807 return bdrv_probe_blocksizes(filtered
, bsz
);
814 * Try to get @bs's geometry (cyls, heads, sectors).
815 * On success, store them in @geo struct and return 0.
816 * On failure return -errno.
817 * @bs must not be empty.
819 int bdrv_probe_geometry(BlockDriverState
*bs
, HDGeometry
*geo
)
821 BlockDriver
*drv
= bs
->drv
;
822 BlockDriverState
*filtered
= bdrv_filter_bs(bs
);
825 if (drv
&& drv
->bdrv_probe_geometry
) {
826 return drv
->bdrv_probe_geometry(bs
, geo
);
827 } else if (filtered
) {
828 return bdrv_probe_geometry(filtered
, geo
);
835 * Create a uniquely-named empty temporary file.
836 * Return the actual file name used upon success, otherwise NULL.
837 * This string should be freed with g_free() when not needed any longer.
839 * Note: creating a temporary file for the caller to (re)open is
840 * inherently racy. Use g_file_open_tmp() instead whenever practical.
842 char *create_tmp_file(Error
**errp
)
846 g_autofree
char *filename
= NULL
;
848 tmpdir
= g_get_tmp_dir();
851 * See commit 69bef79 ("block: use /var/tmp instead of /tmp for -snapshot")
853 * This function is used to create temporary disk images (like -snapshot),
854 * so the files can become very large. /tmp is often a tmpfs where as
855 * /var/tmp is usually on a disk, so more appropriate for disk images.
857 if (!g_strcmp0(tmpdir
, "/tmp")) {
862 filename
= g_strdup_printf("%s/vl.XXXXXX", tmpdir
);
863 fd
= g_mkstemp(filename
);
865 error_setg_errno(errp
, errno
, "Could not open temporary file '%s'",
871 return g_steal_pointer(&filename
);
875 * Detect host devices. By convention, /dev/cdrom[N] is always
876 * recognized as a host CDROM.
878 static BlockDriver
*find_hdev_driver(const char *filename
)
880 int score_max
= 0, score
;
881 BlockDriver
*drv
= NULL
, *d
;
884 QLIST_FOREACH(d
, &bdrv_drivers
, list
) {
885 if (d
->bdrv_probe_device
) {
886 score
= d
->bdrv_probe_device(filename
);
887 if (score
> score_max
) {
897 static BlockDriver
*bdrv_do_find_protocol(const char *protocol
)
902 QLIST_FOREACH(drv1
, &bdrv_drivers
, list
) {
903 if (drv1
->protocol_name
&& !strcmp(drv1
->protocol_name
, protocol
)) {
911 BlockDriver
*bdrv_find_protocol(const char *filename
,
912 bool allow_protocol_prefix
,
922 /* TODO Drivers without bdrv_file_open must be specified explicitly */
925 * XXX(hch): we really should not let host device detection
926 * override an explicit protocol specification, but moving this
927 * later breaks access to device names with colons in them.
928 * Thanks to the brain-dead persistent naming schemes on udev-
929 * based Linux systems those actually are quite common.
931 drv1
= find_hdev_driver(filename
);
936 if (!path_has_protocol(filename
) || !allow_protocol_prefix
) {
940 p
= strchr(filename
, ':');
943 if (len
> sizeof(protocol
) - 1)
944 len
= sizeof(protocol
) - 1;
945 memcpy(protocol
, filename
, len
);
946 protocol
[len
] = '\0';
948 drv1
= bdrv_do_find_protocol(protocol
);
953 for (i
= 0; i
< (int)ARRAY_SIZE(block_driver_modules
); ++i
) {
954 if (block_driver_modules
[i
].protocol_name
&&
955 !strcmp(block_driver_modules
[i
].protocol_name
, protocol
)) {
956 int rv
= block_module_load(block_driver_modules
[i
].library_name
, errp
);
958 drv1
= bdrv_do_find_protocol(protocol
);
967 error_setg(errp
, "Unknown protocol '%s'", protocol
);
973 * Guess image format by probing its contents.
974 * This is not a good idea when your image is raw (CVE-2008-2004), but
975 * we do it anyway for backward compatibility.
977 * @buf contains the image's first @buf_size bytes.
978 * @buf_size is the buffer size in bytes (generally BLOCK_PROBE_BUF_SIZE,
979 * but can be smaller if the image file is smaller)
980 * @filename is its filename.
982 * For all block drivers, call the bdrv_probe() method to get its
984 * Return the first block driver with the highest probing score.
986 BlockDriver
*bdrv_probe_all(const uint8_t *buf
, int buf_size
,
987 const char *filename
)
989 int score_max
= 0, score
;
990 BlockDriver
*drv
= NULL
, *d
;
993 QLIST_FOREACH(d
, &bdrv_drivers
, list
) {
995 score
= d
->bdrv_probe(buf
, buf_size
, filename
);
996 if (score
> score_max
) {
1006 static int find_image_format(BlockBackend
*file
, const char *filename
,
1007 BlockDriver
**pdrv
, Error
**errp
)
1010 uint8_t buf
[BLOCK_PROBE_BUF_SIZE
];
1013 GLOBAL_STATE_CODE();
1015 /* Return the raw BlockDriver * to scsi-generic devices or empty drives */
1016 if (blk_is_sg(file
) || !blk_is_inserted(file
) || blk_getlength(file
) == 0) {
1021 ret
= blk_pread(file
, 0, sizeof(buf
), buf
, 0);
1023 error_setg_errno(errp
, -ret
, "Could not read image for determining its "
1029 drv
= bdrv_probe_all(buf
, sizeof(buf
), filename
);
1031 error_setg(errp
, "Could not determine image format: No compatible "
1042 * Set the current 'total_sectors' value
1043 * Return 0 on success, -errno on error.
1045 int coroutine_fn
bdrv_co_refresh_total_sectors(BlockDriverState
*bs
,
1048 BlockDriver
*drv
= bs
->drv
;
1050 assert_bdrv_graph_readable();
1056 /* Do not attempt drv->bdrv_co_getlength() on scsi-generic devices */
1060 /* query actual device if possible, otherwise just trust the hint */
1061 if (drv
->bdrv_co_getlength
) {
1062 int64_t length
= drv
->bdrv_co_getlength(bs
);
1066 hint
= DIV_ROUND_UP(length
, BDRV_SECTOR_SIZE
);
1069 bs
->total_sectors
= hint
;
1071 if (bs
->total_sectors
* BDRV_SECTOR_SIZE
> BDRV_MAX_LENGTH
) {
1079 * Combines a QDict of new block driver @options with any missing options taken
1080 * from @old_options, so that leaving out an option defaults to its old value.
1082 static void bdrv_join_options(BlockDriverState
*bs
, QDict
*options
,
1085 GLOBAL_STATE_CODE();
1086 if (bs
->drv
&& bs
->drv
->bdrv_join_options
) {
1087 bs
->drv
->bdrv_join_options(options
, old_options
);
1089 qdict_join(options
, old_options
, false);
1093 static BlockdevDetectZeroesOptions
bdrv_parse_detect_zeroes(QemuOpts
*opts
,
1097 Error
*local_err
= NULL
;
1098 char *value
= qemu_opt_get_del(opts
, "detect-zeroes");
1099 BlockdevDetectZeroesOptions detect_zeroes
=
1100 qapi_enum_parse(&BlockdevDetectZeroesOptions_lookup
, value
,
1101 BLOCKDEV_DETECT_ZEROES_OPTIONS_OFF
, &local_err
);
1102 GLOBAL_STATE_CODE();
1105 error_propagate(errp
, local_err
);
1106 return detect_zeroes
;
1109 if (detect_zeroes
== BLOCKDEV_DETECT_ZEROES_OPTIONS_UNMAP
&&
1110 !(open_flags
& BDRV_O_UNMAP
))
1112 error_setg(errp
, "setting detect-zeroes to unmap is not allowed "
1113 "without setting discard operation to unmap");
1116 return detect_zeroes
;
1120 * Set open flags for aio engine
1122 * Return 0 on success, -1 if the engine specified is invalid
1124 int bdrv_parse_aio(const char *mode
, int *flags
)
1126 if (!strcmp(mode
, "threads")) {
1127 /* do nothing, default */
1128 } else if (!strcmp(mode
, "native")) {
1129 *flags
|= BDRV_O_NATIVE_AIO
;
1130 #ifdef CONFIG_LINUX_IO_URING
1131 } else if (!strcmp(mode
, "io_uring")) {
1132 *flags
|= BDRV_O_IO_URING
;
1142 * Set open flags for a given discard mode
1144 * Return 0 on success, -1 if the discard mode was invalid.
1146 int bdrv_parse_discard_flags(const char *mode
, int *flags
)
1148 *flags
&= ~BDRV_O_UNMAP
;
1150 if (!strcmp(mode
, "off") || !strcmp(mode
, "ignore")) {
1152 } else if (!strcmp(mode
, "on") || !strcmp(mode
, "unmap")) {
1153 *flags
|= BDRV_O_UNMAP
;
1162 * Set open flags for a given cache mode
1164 * Return 0 on success, -1 if the cache mode was invalid.
1166 int bdrv_parse_cache_mode(const char *mode
, int *flags
, bool *writethrough
)
1168 *flags
&= ~BDRV_O_CACHE_MASK
;
1170 if (!strcmp(mode
, "off") || !strcmp(mode
, "none")) {
1171 *writethrough
= false;
1172 *flags
|= BDRV_O_NOCACHE
;
1173 } else if (!strcmp(mode
, "directsync")) {
1174 *writethrough
= true;
1175 *flags
|= BDRV_O_NOCACHE
;
1176 } else if (!strcmp(mode
, "writeback")) {
1177 *writethrough
= false;
1178 } else if (!strcmp(mode
, "unsafe")) {
1179 *writethrough
= false;
1180 *flags
|= BDRV_O_NO_FLUSH
;
1181 } else if (!strcmp(mode
, "writethrough")) {
1182 *writethrough
= true;
1190 static char *bdrv_child_get_parent_desc(BdrvChild
*c
)
1192 BlockDriverState
*parent
= c
->opaque
;
1193 return g_strdup_printf("node '%s'", bdrv_get_node_name(parent
));
1196 static void GRAPH_RDLOCK
bdrv_child_cb_drained_begin(BdrvChild
*child
)
1198 BlockDriverState
*bs
= child
->opaque
;
1199 bdrv_do_drained_begin_quiesce(bs
, NULL
);
1202 static bool GRAPH_RDLOCK
bdrv_child_cb_drained_poll(BdrvChild
*child
)
1204 BlockDriverState
*bs
= child
->opaque
;
1205 return bdrv_drain_poll(bs
, NULL
, false);
1208 static void GRAPH_RDLOCK
bdrv_child_cb_drained_end(BdrvChild
*child
)
1210 BlockDriverState
*bs
= child
->opaque
;
1211 bdrv_drained_end(bs
);
1214 static int bdrv_child_cb_inactivate(BdrvChild
*child
)
1216 BlockDriverState
*bs
= child
->opaque
;
1217 GLOBAL_STATE_CODE();
1218 assert(bs
->open_flags
& BDRV_O_INACTIVE
);
1222 static bool bdrv_child_cb_change_aio_ctx(BdrvChild
*child
, AioContext
*ctx
,
1223 GHashTable
*visited
, Transaction
*tran
,
1226 BlockDriverState
*bs
= child
->opaque
;
1227 return bdrv_change_aio_context(bs
, ctx
, visited
, tran
, errp
);
1231 * Returns the options and flags that a temporary snapshot should get, based on
1232 * the originally requested flags (the originally requested image will have
1233 * flags like a backing file)
1235 static void bdrv_temp_snapshot_options(int *child_flags
, QDict
*child_options
,
1236 int parent_flags
, QDict
*parent_options
)
1238 GLOBAL_STATE_CODE();
1239 *child_flags
= (parent_flags
& ~BDRV_O_SNAPSHOT
) | BDRV_O_TEMPORARY
;
1241 /* For temporary files, unconditional cache=unsafe is fine */
1242 qdict_set_default_str(child_options
, BDRV_OPT_CACHE_DIRECT
, "off");
1243 qdict_set_default_str(child_options
, BDRV_OPT_CACHE_NO_FLUSH
, "on");
1245 /* Copy the read-only and discard options from the parent */
1246 qdict_copy_default(child_options
, parent_options
, BDRV_OPT_READ_ONLY
);
1247 qdict_copy_default(child_options
, parent_options
, BDRV_OPT_DISCARD
);
1249 /* aio=native doesn't work for cache.direct=off, so disable it for the
1250 * temporary snapshot */
1251 *child_flags
&= ~BDRV_O_NATIVE_AIO
;
1254 static void GRAPH_WRLOCK
bdrv_backing_attach(BdrvChild
*c
)
1256 BlockDriverState
*parent
= c
->opaque
;
1257 BlockDriverState
*backing_hd
= c
->bs
;
1259 GLOBAL_STATE_CODE();
1260 assert(!parent
->backing_blocker
);
1261 error_setg(&parent
->backing_blocker
,
1262 "node is used as backing hd of '%s'",
1263 bdrv_get_device_or_node_name(parent
));
1265 bdrv_refresh_filename(backing_hd
);
1267 parent
->open_flags
&= ~BDRV_O_NO_BACKING
;
1269 bdrv_op_block_all(backing_hd
, parent
->backing_blocker
);
1270 /* Otherwise we won't be able to commit or stream */
1271 bdrv_op_unblock(backing_hd
, BLOCK_OP_TYPE_COMMIT_TARGET
,
1272 parent
->backing_blocker
);
1273 bdrv_op_unblock(backing_hd
, BLOCK_OP_TYPE_STREAM
,
1274 parent
->backing_blocker
);
1276 * We do backup in 3 ways:
1278 * The target bs is new opened, and the source is top BDS
1279 * 2. blockdev backup
1280 * Both the source and the target are top BDSes.
1281 * 3. internal backup(used for block replication)
1282 * Both the source and the target are backing file
1284 * In case 1 and 2, neither the source nor the target is the backing file.
1285 * In case 3, we will block the top BDS, so there is only one block job
1286 * for the top BDS and its backing chain.
1288 bdrv_op_unblock(backing_hd
, BLOCK_OP_TYPE_BACKUP_SOURCE
,
1289 parent
->backing_blocker
);
1290 bdrv_op_unblock(backing_hd
, BLOCK_OP_TYPE_BACKUP_TARGET
,
1291 parent
->backing_blocker
);
1294 static void bdrv_backing_detach(BdrvChild
*c
)
1296 BlockDriverState
*parent
= c
->opaque
;
1298 GLOBAL_STATE_CODE();
1299 assert(parent
->backing_blocker
);
1300 bdrv_op_unblock_all(c
->bs
, parent
->backing_blocker
);
1301 error_free(parent
->backing_blocker
);
1302 parent
->backing_blocker
= NULL
;
1305 static int bdrv_backing_update_filename(BdrvChild
*c
, BlockDriverState
*base
,
1306 const char *filename
, Error
**errp
)
1308 BlockDriverState
*parent
= c
->opaque
;
1309 bool read_only
= bdrv_is_read_only(parent
);
1311 GLOBAL_STATE_CODE();
1314 ret
= bdrv_reopen_set_read_only(parent
, false, errp
);
1320 ret
= bdrv_change_backing_file(parent
, filename
,
1321 base
->drv
? base
->drv
->format_name
: "",
1324 error_setg_errno(errp
, -ret
, "Could not update backing file link");
1328 bdrv_reopen_set_read_only(parent
, true, NULL
);
1335 * Returns the options and flags that a generic child of a BDS should
1336 * get, based on the given options and flags for the parent BDS.
1338 static void bdrv_inherited_options(BdrvChildRole role
, bool parent_is_format
,
1339 int *child_flags
, QDict
*child_options
,
1340 int parent_flags
, QDict
*parent_options
)
1342 int flags
= parent_flags
;
1343 GLOBAL_STATE_CODE();
1346 * First, decide whether to set, clear, or leave BDRV_O_PROTOCOL.
1347 * Generally, the question to answer is: Should this child be
1348 * format-probed by default?
1352 * Pure and non-filtered data children of non-format nodes should
1353 * be probed by default (even when the node itself has BDRV_O_PROTOCOL
1354 * set). This only affects a very limited set of drivers (namely
1355 * quorum and blkverify when this comment was written).
1356 * Force-clear BDRV_O_PROTOCOL then.
1358 if (!parent_is_format
&&
1359 (role
& BDRV_CHILD_DATA
) &&
1360 !(role
& (BDRV_CHILD_METADATA
| BDRV_CHILD_FILTERED
)))
1362 flags
&= ~BDRV_O_PROTOCOL
;
1366 * All children of format nodes (except for COW children) and all
1367 * metadata children in general should never be format-probed.
1368 * Force-set BDRV_O_PROTOCOL then.
1370 if ((parent_is_format
&& !(role
& BDRV_CHILD_COW
)) ||
1371 (role
& BDRV_CHILD_METADATA
))
1373 flags
|= BDRV_O_PROTOCOL
;
1377 * If the cache mode isn't explicitly set, inherit direct and no-flush from
1380 qdict_copy_default(child_options
, parent_options
, BDRV_OPT_CACHE_DIRECT
);
1381 qdict_copy_default(child_options
, parent_options
, BDRV_OPT_CACHE_NO_FLUSH
);
1382 qdict_copy_default(child_options
, parent_options
, BDRV_OPT_FORCE_SHARE
);
1384 if (role
& BDRV_CHILD_COW
) {
1385 /* backing files are opened read-only by default */
1386 qdict_set_default_str(child_options
, BDRV_OPT_READ_ONLY
, "on");
1387 qdict_set_default_str(child_options
, BDRV_OPT_AUTO_READ_ONLY
, "off");
1389 /* Inherit the read-only option from the parent if it's not set */
1390 qdict_copy_default(child_options
, parent_options
, BDRV_OPT_READ_ONLY
);
1391 qdict_copy_default(child_options
, parent_options
,
1392 BDRV_OPT_AUTO_READ_ONLY
);
1396 * bdrv_co_pdiscard() respects unmap policy for the parent, so we
1397 * can default to enable it on lower layers regardless of the
1400 qdict_set_default_str(child_options
, BDRV_OPT_DISCARD
, "unmap");
1402 /* Clear flags that only apply to the top layer */
1403 flags
&= ~(BDRV_O_SNAPSHOT
| BDRV_O_NO_BACKING
| BDRV_O_COPY_ON_READ
);
1405 if (role
& BDRV_CHILD_METADATA
) {
1406 flags
&= ~BDRV_O_NO_IO
;
1408 if (role
& BDRV_CHILD_COW
) {
1409 flags
&= ~BDRV_O_TEMPORARY
;
1412 *child_flags
= flags
;
1415 static void GRAPH_WRLOCK
bdrv_child_cb_attach(BdrvChild
*child
)
1417 BlockDriverState
*bs
= child
->opaque
;
1419 assert_bdrv_graph_writable();
1420 QLIST_INSERT_HEAD(&bs
->children
, child
, next
);
1421 if (bs
->drv
->is_filter
|| (child
->role
& BDRV_CHILD_FILTERED
)) {
1423 * Here we handle filters and block/raw-format.c when it behave like
1424 * filter. They generally have a single PRIMARY child, which is also the
1425 * FILTERED child, and that they may have multiple more children, which
1426 * are neither PRIMARY nor FILTERED. And never we have a COW child here.
1427 * So bs->file will be the PRIMARY child, unless the PRIMARY child goes
1428 * into bs->backing on exceptional cases; and bs->backing will be
1431 assert(!(child
->role
& BDRV_CHILD_COW
));
1432 if (child
->role
& BDRV_CHILD_PRIMARY
) {
1433 assert(child
->role
& BDRV_CHILD_FILTERED
);
1434 assert(!bs
->backing
);
1437 if (bs
->drv
->filtered_child_is_backing
) {
1438 bs
->backing
= child
;
1443 assert(!(child
->role
& BDRV_CHILD_FILTERED
));
1445 } else if (child
->role
& BDRV_CHILD_COW
) {
1446 assert(bs
->drv
->supports_backing
);
1447 assert(!(child
->role
& BDRV_CHILD_PRIMARY
));
1448 assert(!bs
->backing
);
1449 bs
->backing
= child
;
1450 bdrv_backing_attach(child
);
1451 } else if (child
->role
& BDRV_CHILD_PRIMARY
) {
1457 static void GRAPH_WRLOCK
bdrv_child_cb_detach(BdrvChild
*child
)
1459 BlockDriverState
*bs
= child
->opaque
;
1461 if (child
->role
& BDRV_CHILD_COW
) {
1462 bdrv_backing_detach(child
);
1465 assert_bdrv_graph_writable();
1466 QLIST_REMOVE(child
, next
);
1467 if (child
== bs
->backing
) {
1468 assert(child
!= bs
->file
);
1470 } else if (child
== bs
->file
) {
1475 static int bdrv_child_cb_update_filename(BdrvChild
*c
, BlockDriverState
*base
,
1476 const char *filename
, Error
**errp
)
1478 if (c
->role
& BDRV_CHILD_COW
) {
1479 return bdrv_backing_update_filename(c
, base
, filename
, errp
);
1484 AioContext
*child_of_bds_get_parent_aio_context(BdrvChild
*c
)
1486 BlockDriverState
*bs
= c
->opaque
;
1489 return bdrv_get_aio_context(bs
);
1492 const BdrvChildClass child_of_bds
= {
1493 .parent_is_bds
= true,
1494 .get_parent_desc
= bdrv_child_get_parent_desc
,
1495 .inherit_options
= bdrv_inherited_options
,
1496 .drained_begin
= bdrv_child_cb_drained_begin
,
1497 .drained_poll
= bdrv_child_cb_drained_poll
,
1498 .drained_end
= bdrv_child_cb_drained_end
,
1499 .attach
= bdrv_child_cb_attach
,
1500 .detach
= bdrv_child_cb_detach
,
1501 .inactivate
= bdrv_child_cb_inactivate
,
1502 .change_aio_ctx
= bdrv_child_cb_change_aio_ctx
,
1503 .update_filename
= bdrv_child_cb_update_filename
,
1504 .get_parent_aio_context
= child_of_bds_get_parent_aio_context
,
1507 AioContext
*bdrv_child_get_parent_aio_context(BdrvChild
*c
)
1510 return c
->klass
->get_parent_aio_context(c
);
1513 static int bdrv_open_flags(BlockDriverState
*bs
, int flags
)
1515 int open_flags
= flags
;
1516 GLOBAL_STATE_CODE();
1519 * Clear flags that are internal to the block layer before opening the
1522 open_flags
&= ~(BDRV_O_SNAPSHOT
| BDRV_O_NO_BACKING
| BDRV_O_PROTOCOL
);
1527 static void update_flags_from_options(int *flags
, QemuOpts
*opts
)
1529 GLOBAL_STATE_CODE();
1531 *flags
&= ~(BDRV_O_CACHE_MASK
| BDRV_O_RDWR
| BDRV_O_AUTO_RDONLY
);
1533 if (qemu_opt_get_bool_del(opts
, BDRV_OPT_CACHE_NO_FLUSH
, false)) {
1534 *flags
|= BDRV_O_NO_FLUSH
;
1537 if (qemu_opt_get_bool_del(opts
, BDRV_OPT_CACHE_DIRECT
, false)) {
1538 *flags
|= BDRV_O_NOCACHE
;
1541 if (!qemu_opt_get_bool_del(opts
, BDRV_OPT_READ_ONLY
, false)) {
1542 *flags
|= BDRV_O_RDWR
;
1545 if (qemu_opt_get_bool_del(opts
, BDRV_OPT_AUTO_READ_ONLY
, false)) {
1546 *flags
|= BDRV_O_AUTO_RDONLY
;
1550 static void update_options_from_flags(QDict
*options
, int flags
)
1552 GLOBAL_STATE_CODE();
1553 if (!qdict_haskey(options
, BDRV_OPT_CACHE_DIRECT
)) {
1554 qdict_put_bool(options
, BDRV_OPT_CACHE_DIRECT
, flags
& BDRV_O_NOCACHE
);
1556 if (!qdict_haskey(options
, BDRV_OPT_CACHE_NO_FLUSH
)) {
1557 qdict_put_bool(options
, BDRV_OPT_CACHE_NO_FLUSH
,
1558 flags
& BDRV_O_NO_FLUSH
);
1560 if (!qdict_haskey(options
, BDRV_OPT_READ_ONLY
)) {
1561 qdict_put_bool(options
, BDRV_OPT_READ_ONLY
, !(flags
& BDRV_O_RDWR
));
1563 if (!qdict_haskey(options
, BDRV_OPT_AUTO_READ_ONLY
)) {
1564 qdict_put_bool(options
, BDRV_OPT_AUTO_READ_ONLY
,
1565 flags
& BDRV_O_AUTO_RDONLY
);
1569 static void bdrv_assign_node_name(BlockDriverState
*bs
,
1570 const char *node_name
,
1573 char *gen_node_name
= NULL
;
1574 GLOBAL_STATE_CODE();
1577 node_name
= gen_node_name
= id_generate(ID_BLOCK
);
1578 } else if (!id_wellformed(node_name
)) {
1580 * Check for empty string or invalid characters, but not if it is
1581 * generated (generated names use characters not available to the user)
1583 error_setg(errp
, "Invalid node-name: '%s'", node_name
);
1587 /* takes care of avoiding namespaces collisions */
1588 if (blk_by_name(node_name
)) {
1589 error_setg(errp
, "node-name=%s is conflicting with a device id",
1594 /* takes care of avoiding duplicates node names */
1595 if (bdrv_find_node(node_name
)) {
1596 error_setg(errp
, "Duplicate nodes with node-name='%s'", node_name
);
1600 /* Make sure that the node name isn't truncated */
1601 if (strlen(node_name
) >= sizeof(bs
->node_name
)) {
1602 error_setg(errp
, "Node name too long");
1606 /* copy node name into the bs and insert it into the graph list */
1607 pstrcpy(bs
->node_name
, sizeof(bs
->node_name
), node_name
);
1608 QTAILQ_INSERT_TAIL(&graph_bdrv_states
, bs
, node_list
);
1610 g_free(gen_node_name
);
1614 * The caller must always hold @bs AioContext lock, because this function calls
1615 * bdrv_refresh_total_sectors() which polls when called from non-coroutine
1618 static int no_coroutine_fn GRAPH_UNLOCKED
1619 bdrv_open_driver(BlockDriverState
*bs
, BlockDriver
*drv
, const char *node_name
,
1620 QDict
*options
, int open_flags
, Error
**errp
)
1623 Error
*local_err
= NULL
;
1625 GLOBAL_STATE_CODE();
1627 bdrv_assign_node_name(bs
, node_name
, &local_err
);
1629 error_propagate(errp
, local_err
);
1634 bs
->opaque
= g_malloc0(drv
->instance_size
);
1636 if (drv
->bdrv_file_open
) {
1637 assert(!drv
->bdrv_needs_filename
|| bs
->filename
[0]);
1638 ret
= drv
->bdrv_file_open(bs
, options
, open_flags
, &local_err
);
1639 } else if (drv
->bdrv_open
) {
1640 ret
= drv
->bdrv_open(bs
, options
, open_flags
, &local_err
);
1647 error_propagate(errp
, local_err
);
1648 } else if (bs
->filename
[0]) {
1649 error_setg_errno(errp
, -ret
, "Could not open '%s'", bs
->filename
);
1651 error_setg_errno(errp
, -ret
, "Could not open image");
1656 assert(!(bs
->supported_read_flags
& ~BDRV_REQ_MASK
));
1657 assert(!(bs
->supported_write_flags
& ~BDRV_REQ_MASK
));
1660 * Always allow the BDRV_REQ_REGISTERED_BUF optimization hint. This saves
1661 * drivers that pass read/write requests through to a child the trouble of
1662 * declaring support explicitly.
1664 * Drivers must not propagate this flag accidentally when they initiate I/O
1665 * to a bounce buffer. That case should be rare though.
1667 bs
->supported_read_flags
|= BDRV_REQ_REGISTERED_BUF
;
1668 bs
->supported_write_flags
|= BDRV_REQ_REGISTERED_BUF
;
1670 /* Get the context after .bdrv_open, it can change the context */
1671 ctx
= bdrv_get_aio_context(bs
);
1672 aio_context_acquire(ctx
);
1674 ret
= bdrv_refresh_total_sectors(bs
, bs
->total_sectors
);
1676 error_setg_errno(errp
, -ret
, "Could not refresh total sector count");
1677 aio_context_release(ctx
);
1681 bdrv_graph_rdlock_main_loop();
1682 bdrv_refresh_limits(bs
, NULL
, &local_err
);
1683 bdrv_graph_rdunlock_main_loop();
1684 aio_context_release(ctx
);
1687 error_propagate(errp
, local_err
);
1691 assert(bdrv_opt_mem_align(bs
) != 0);
1692 assert(bdrv_min_mem_align(bs
) != 0);
1693 assert(is_power_of_2(bs
->bl
.request_alignment
));
1695 for (i
= 0; i
< bs
->quiesce_counter
; i
++) {
1696 if (drv
->bdrv_drain_begin
) {
1697 drv
->bdrv_drain_begin(bs
);
1704 if (bs
->file
!= NULL
) {
1705 bdrv_graph_wrlock(NULL
);
1706 bdrv_unref_child(bs
, bs
->file
);
1707 bdrv_graph_wrunlock();
1716 * Create and open a block node.
1718 * @options is a QDict of options to pass to the block drivers, or NULL for an
1719 * empty set of options. The reference to the QDict belongs to the block layer
1720 * after the call (even on failure), so if the caller intends to reuse the
1721 * dictionary, it needs to use qobject_ref() before calling bdrv_open.
1723 BlockDriverState
*bdrv_new_open_driver_opts(BlockDriver
*drv
,
1724 const char *node_name
,
1725 QDict
*options
, int flags
,
1728 BlockDriverState
*bs
;
1731 GLOBAL_STATE_CODE();
1734 bs
->open_flags
= flags
;
1735 bs
->options
= options
?: qdict_new();
1736 bs
->explicit_options
= qdict_clone_shallow(bs
->options
);
1739 update_options_from_flags(bs
->options
, flags
);
1741 ret
= bdrv_open_driver(bs
, drv
, node_name
, bs
->options
, flags
, errp
);
1743 qobject_unref(bs
->explicit_options
);
1744 bs
->explicit_options
= NULL
;
1745 qobject_unref(bs
->options
);
1754 /* Create and open a block node. */
1755 BlockDriverState
*bdrv_new_open_driver(BlockDriver
*drv
, const char *node_name
,
1756 int flags
, Error
**errp
)
1758 GLOBAL_STATE_CODE();
1759 return bdrv_new_open_driver_opts(drv
, node_name
, NULL
, flags
, errp
);
1762 QemuOptsList bdrv_runtime_opts
= {
1763 .name
= "bdrv_common",
1764 .head
= QTAILQ_HEAD_INITIALIZER(bdrv_runtime_opts
.head
),
1767 .name
= "node-name",
1768 .type
= QEMU_OPT_STRING
,
1769 .help
= "Node name of the block device node",
1773 .type
= QEMU_OPT_STRING
,
1774 .help
= "Block driver to use for the node",
1777 .name
= BDRV_OPT_CACHE_DIRECT
,
1778 .type
= QEMU_OPT_BOOL
,
1779 .help
= "Bypass software writeback cache on the host",
1782 .name
= BDRV_OPT_CACHE_NO_FLUSH
,
1783 .type
= QEMU_OPT_BOOL
,
1784 .help
= "Ignore flush requests",
1787 .name
= BDRV_OPT_READ_ONLY
,
1788 .type
= QEMU_OPT_BOOL
,
1789 .help
= "Node is opened in read-only mode",
1792 .name
= BDRV_OPT_AUTO_READ_ONLY
,
1793 .type
= QEMU_OPT_BOOL
,
1794 .help
= "Node can become read-only if opening read-write fails",
1797 .name
= "detect-zeroes",
1798 .type
= QEMU_OPT_STRING
,
1799 .help
= "try to optimize zero writes (off, on, unmap)",
1802 .name
= BDRV_OPT_DISCARD
,
1803 .type
= QEMU_OPT_STRING
,
1804 .help
= "discard operation (ignore/off, unmap/on)",
1807 .name
= BDRV_OPT_FORCE_SHARE
,
1808 .type
= QEMU_OPT_BOOL
,
1809 .help
= "always accept other writers (default: off)",
1811 { /* end of list */ }
1815 QemuOptsList bdrv_create_opts_simple
= {
1816 .name
= "simple-create-opts",
1817 .head
= QTAILQ_HEAD_INITIALIZER(bdrv_create_opts_simple
.head
),
1820 .name
= BLOCK_OPT_SIZE
,
1821 .type
= QEMU_OPT_SIZE
,
1822 .help
= "Virtual disk size"
1825 .name
= BLOCK_OPT_PREALLOC
,
1826 .type
= QEMU_OPT_STRING
,
1827 .help
= "Preallocation mode (allowed values: off)"
1829 { /* end of list */ }
1834 * Common part for opening disk images and files
1836 * Removes all processed options from *options.
1838 static int bdrv_open_common(BlockDriverState
*bs
, BlockBackend
*file
,
1839 QDict
*options
, Error
**errp
)
1841 int ret
, open_flags
;
1842 const char *filename
;
1843 const char *driver_name
= NULL
;
1844 const char *node_name
= NULL
;
1845 const char *discard
;
1848 Error
*local_err
= NULL
;
1851 assert(bs
->file
== NULL
);
1852 assert(options
!= NULL
&& bs
->options
!= options
);
1853 GLOBAL_STATE_CODE();
1855 opts
= qemu_opts_create(&bdrv_runtime_opts
, NULL
, 0, &error_abort
);
1856 if (!qemu_opts_absorb_qdict(opts
, options
, errp
)) {
1861 update_flags_from_options(&bs
->open_flags
, opts
);
1863 driver_name
= qemu_opt_get(opts
, "driver");
1864 drv
= bdrv_find_format(driver_name
);
1865 assert(drv
!= NULL
);
1867 bs
->force_share
= qemu_opt_get_bool(opts
, BDRV_OPT_FORCE_SHARE
, false);
1869 if (bs
->force_share
&& (bs
->open_flags
& BDRV_O_RDWR
)) {
1871 BDRV_OPT_FORCE_SHARE
1872 "=on can only be used with read-only images");
1878 bdrv_graph_rdlock_main_loop();
1879 bdrv_refresh_filename(blk_bs(file
));
1880 bdrv_graph_rdunlock_main_loop();
1882 filename
= blk_bs(file
)->filename
;
1885 * Caution: while qdict_get_try_str() is fine, getting
1886 * non-string types would require more care. When @options
1887 * come from -blockdev or blockdev_add, its members are typed
1888 * according to the QAPI schema, but when they come from
1889 * -drive, they're all QString.
1891 filename
= qdict_get_try_str(options
, "filename");
1894 if (drv
->bdrv_needs_filename
&& (!filename
|| !filename
[0])) {
1895 error_setg(errp
, "The '%s' block driver requires a file name",
1901 trace_bdrv_open_common(bs
, filename
?: "", bs
->open_flags
,
1904 ro
= bdrv_is_read_only(bs
);
1906 if (use_bdrv_whitelist
&& !bdrv_is_whitelisted(drv
, ro
)) {
1907 if (!ro
&& bdrv_is_whitelisted(drv
, true)) {
1908 ret
= bdrv_apply_auto_read_only(bs
, NULL
, NULL
);
1914 !ro
&& bdrv_is_whitelisted(drv
, true)
1915 ? "Driver '%s' can only be used for read-only devices"
1916 : "Driver '%s' is not whitelisted",
1922 /* bdrv_new() and bdrv_close() make it so */
1923 assert(qatomic_read(&bs
->copy_on_read
) == 0);
1925 if (bs
->open_flags
& BDRV_O_COPY_ON_READ
) {
1927 bdrv_enable_copy_on_read(bs
);
1929 error_setg(errp
, "Can't use copy-on-read on read-only device");
1935 discard
= qemu_opt_get(opts
, BDRV_OPT_DISCARD
);
1936 if (discard
!= NULL
) {
1937 if (bdrv_parse_discard_flags(discard
, &bs
->open_flags
) != 0) {
1938 error_setg(errp
, "Invalid discard option");
1945 bdrv_parse_detect_zeroes(opts
, bs
->open_flags
, &local_err
);
1947 error_propagate(errp
, local_err
);
1952 if (filename
!= NULL
) {
1953 pstrcpy(bs
->filename
, sizeof(bs
->filename
), filename
);
1955 bs
->filename
[0] = '\0';
1957 pstrcpy(bs
->exact_filename
, sizeof(bs
->exact_filename
), bs
->filename
);
1959 /* Open the image, either directly or using a protocol */
1960 open_flags
= bdrv_open_flags(bs
, bs
->open_flags
);
1961 node_name
= qemu_opt_get(opts
, "node-name");
1963 assert(!drv
->bdrv_file_open
|| file
== NULL
);
1964 ret
= bdrv_open_driver(bs
, drv
, node_name
, options
, open_flags
, errp
);
1969 qemu_opts_del(opts
);
1973 qemu_opts_del(opts
);
1977 static QDict
*parse_json_filename(const char *filename
, Error
**errp
)
1979 QObject
*options_obj
;
1982 GLOBAL_STATE_CODE();
1984 ret
= strstart(filename
, "json:", &filename
);
1987 options_obj
= qobject_from_json(filename
, errp
);
1989 error_prepend(errp
, "Could not parse the JSON options: ");
1993 options
= qobject_to(QDict
, options_obj
);
1995 qobject_unref(options_obj
);
1996 error_setg(errp
, "Invalid JSON object given");
2000 qdict_flatten(options
);
2005 static void parse_json_protocol(QDict
*options
, const char **pfilename
,
2008 QDict
*json_options
;
2009 Error
*local_err
= NULL
;
2010 GLOBAL_STATE_CODE();
2012 /* Parse json: pseudo-protocol */
2013 if (!*pfilename
|| !g_str_has_prefix(*pfilename
, "json:")) {
2017 json_options
= parse_json_filename(*pfilename
, &local_err
);
2019 error_propagate(errp
, local_err
);
2023 /* Options given in the filename have lower priority than options
2024 * specified directly */
2025 qdict_join(options
, json_options
, false);
2026 qobject_unref(json_options
);
2031 * Fills in default options for opening images and converts the legacy
2032 * filename/flags pair to option QDict entries.
2033 * The BDRV_O_PROTOCOL flag in *flags will be set or cleared accordingly if a
2034 * block driver has been specified explicitly.
2036 static int bdrv_fill_options(QDict
**options
, const char *filename
,
2037 int *flags
, Error
**errp
)
2039 const char *drvname
;
2040 bool protocol
= *flags
& BDRV_O_PROTOCOL
;
2041 bool parse_filename
= false;
2042 BlockDriver
*drv
= NULL
;
2043 Error
*local_err
= NULL
;
2045 GLOBAL_STATE_CODE();
2048 * Caution: while qdict_get_try_str() is fine, getting non-string
2049 * types would require more care. When @options come from
2050 * -blockdev or blockdev_add, its members are typed according to
2051 * the QAPI schema, but when they come from -drive, they're all
2054 drvname
= qdict_get_try_str(*options
, "driver");
2056 drv
= bdrv_find_format(drvname
);
2058 error_setg(errp
, "Unknown driver '%s'", drvname
);
2061 /* If the user has explicitly specified the driver, this choice should
2062 * override the BDRV_O_PROTOCOL flag */
2063 protocol
= drv
->bdrv_file_open
;
2067 *flags
|= BDRV_O_PROTOCOL
;
2069 *flags
&= ~BDRV_O_PROTOCOL
;
2072 /* Translate cache options from flags into options */
2073 update_options_from_flags(*options
, *flags
);
2075 /* Fetch the file name from the options QDict if necessary */
2076 if (protocol
&& filename
) {
2077 if (!qdict_haskey(*options
, "filename")) {
2078 qdict_put_str(*options
, "filename", filename
);
2079 parse_filename
= true;
2081 error_setg(errp
, "Can't specify 'file' and 'filename' options at "
2087 /* Find the right block driver */
2088 /* See cautionary note on accessing @options above */
2089 filename
= qdict_get_try_str(*options
, "filename");
2091 if (!drvname
&& protocol
) {
2093 drv
= bdrv_find_protocol(filename
, parse_filename
, errp
);
2098 drvname
= drv
->format_name
;
2099 qdict_put_str(*options
, "driver", drvname
);
2101 error_setg(errp
, "Must specify either driver or file");
2106 assert(drv
|| !protocol
);
2108 /* Driver-specific filename parsing */
2109 if (drv
&& drv
->bdrv_parse_filename
&& parse_filename
) {
2110 drv
->bdrv_parse_filename(filename
, *options
, &local_err
);
2112 error_propagate(errp
, local_err
);
2116 if (!drv
->bdrv_needs_filename
) {
2117 qdict_del(*options
, "filename");
2124 typedef struct BlockReopenQueueEntry
{
2126 BDRVReopenState state
;
2127 QTAILQ_ENTRY(BlockReopenQueueEntry
) entry
;
2128 } BlockReopenQueueEntry
;
2131 * Return the flags that @bs will have after the reopens in @q have
2132 * successfully completed. If @q is NULL (or @bs is not contained in @q),
2133 * return the current flags.
2135 static int bdrv_reopen_get_flags(BlockReopenQueue
*q
, BlockDriverState
*bs
)
2137 BlockReopenQueueEntry
*entry
;
2140 QTAILQ_FOREACH(entry
, q
, entry
) {
2141 if (entry
->state
.bs
== bs
) {
2142 return entry
->state
.flags
;
2147 return bs
->open_flags
;
2150 /* Returns whether the image file can be written to after the reopen queue @q
2151 * has been successfully applied, or right now if @q is NULL. */
2152 static bool bdrv_is_writable_after_reopen(BlockDriverState
*bs
,
2153 BlockReopenQueue
*q
)
2155 int flags
= bdrv_reopen_get_flags(q
, bs
);
2157 return (flags
& (BDRV_O_RDWR
| BDRV_O_INACTIVE
)) == BDRV_O_RDWR
;
2161 * Return whether the BDS can be written to. This is not necessarily
2162 * the same as !bdrv_is_read_only(bs), as inactivated images may not
2163 * be written to but do not count as read-only images.
2165 bool bdrv_is_writable(BlockDriverState
*bs
)
2168 return bdrv_is_writable_after_reopen(bs
, NULL
);
2171 static char *bdrv_child_user_desc(BdrvChild
*c
)
2173 GLOBAL_STATE_CODE();
2174 return c
->klass
->get_parent_desc(c
);
2178 * Check that @a allows everything that @b needs. @a and @b must reference same
2181 static bool bdrv_a_allow_b(BdrvChild
*a
, BdrvChild
*b
, Error
**errp
)
2183 const char *child_bs_name
;
2184 g_autofree
char *a_user
= NULL
;
2185 g_autofree
char *b_user
= NULL
;
2186 g_autofree
char *perms
= NULL
;
2189 assert(a
->bs
== b
->bs
);
2190 GLOBAL_STATE_CODE();
2192 if ((b
->perm
& a
->shared_perm
) == b
->perm
) {
2196 child_bs_name
= bdrv_get_node_name(b
->bs
);
2197 a_user
= bdrv_child_user_desc(a
);
2198 b_user
= bdrv_child_user_desc(b
);
2199 perms
= bdrv_perm_names(b
->perm
& ~a
->shared_perm
);
2201 error_setg(errp
, "Permission conflict on node '%s': permissions '%s' are "
2202 "both required by %s (uses node '%s' as '%s' child) and "
2203 "unshared by %s (uses node '%s' as '%s' child).",
2204 child_bs_name
, perms
,
2205 b_user
, child_bs_name
, b
->name
,
2206 a_user
, child_bs_name
, a
->name
);
2211 static bool GRAPH_RDLOCK
2212 bdrv_parent_perms_conflict(BlockDriverState
*bs
, Error
**errp
)
2215 GLOBAL_STATE_CODE();
2218 * During the loop we'll look at each pair twice. That's correct because
2219 * bdrv_a_allow_b() is asymmetric and we should check each pair in both
2222 QLIST_FOREACH(a
, &bs
->parents
, next_parent
) {
2223 QLIST_FOREACH(b
, &bs
->parents
, next_parent
) {
2228 if (!bdrv_a_allow_b(a
, b
, errp
)) {
2237 static void GRAPH_RDLOCK
2238 bdrv_child_perm(BlockDriverState
*bs
, BlockDriverState
*child_bs
,
2239 BdrvChild
*c
, BdrvChildRole role
,
2240 BlockReopenQueue
*reopen_queue
,
2241 uint64_t parent_perm
, uint64_t parent_shared
,
2242 uint64_t *nperm
, uint64_t *nshared
)
2244 assert(bs
->drv
&& bs
->drv
->bdrv_child_perm
);
2245 GLOBAL_STATE_CODE();
2246 bs
->drv
->bdrv_child_perm(bs
, c
, role
, reopen_queue
,
2247 parent_perm
, parent_shared
,
2249 /* TODO Take force_share from reopen_queue */
2250 if (child_bs
&& child_bs
->force_share
) {
2251 *nshared
= BLK_PERM_ALL
;
2256 * Adds the whole subtree of @bs (including @bs itself) to the @list (except for
2257 * nodes that are already in the @list, of course) so that final list is
2258 * topologically sorted. Return the result (GSList @list object is updated, so
2259 * don't use old reference after function call).
2261 * On function start @list must be already topologically sorted and for any node
2262 * in the @list the whole subtree of the node must be in the @list as well. The
2263 * simplest way to satisfy this criteria: use only result of
2264 * bdrv_topological_dfs() or NULL as @list parameter.
2266 static GSList
* GRAPH_RDLOCK
2267 bdrv_topological_dfs(GSList
*list
, GHashTable
*found
, BlockDriverState
*bs
)
2270 g_autoptr(GHashTable
) local_found
= NULL
;
2272 GLOBAL_STATE_CODE();
2276 found
= local_found
= g_hash_table_new(NULL
, NULL
);
2279 if (g_hash_table_contains(found
, bs
)) {
2282 g_hash_table_add(found
, bs
);
2284 QLIST_FOREACH(child
, &bs
->children
, next
) {
2285 list
= bdrv_topological_dfs(list
, found
, child
->bs
);
2288 return g_slist_prepend(list
, bs
);
2291 typedef struct BdrvChildSetPermState
{
2294 uint64_t old_shared_perm
;
2295 } BdrvChildSetPermState
;
2297 static void bdrv_child_set_perm_abort(void *opaque
)
2299 BdrvChildSetPermState
*s
= opaque
;
2301 GLOBAL_STATE_CODE();
2303 s
->child
->perm
= s
->old_perm
;
2304 s
->child
->shared_perm
= s
->old_shared_perm
;
2307 static TransactionActionDrv bdrv_child_set_pem_drv
= {
2308 .abort
= bdrv_child_set_perm_abort
,
2312 static void bdrv_child_set_perm(BdrvChild
*c
, uint64_t perm
,
2313 uint64_t shared
, Transaction
*tran
)
2315 BdrvChildSetPermState
*s
= g_new(BdrvChildSetPermState
, 1);
2316 GLOBAL_STATE_CODE();
2318 *s
= (BdrvChildSetPermState
) {
2320 .old_perm
= c
->perm
,
2321 .old_shared_perm
= c
->shared_perm
,
2325 c
->shared_perm
= shared
;
2327 tran_add(tran
, &bdrv_child_set_pem_drv
, s
);
2330 static void GRAPH_RDLOCK
bdrv_drv_set_perm_commit(void *opaque
)
2332 BlockDriverState
*bs
= opaque
;
2333 uint64_t cumulative_perms
, cumulative_shared_perms
;
2334 GLOBAL_STATE_CODE();
2336 if (bs
->drv
->bdrv_set_perm
) {
2337 bdrv_get_cumulative_perm(bs
, &cumulative_perms
,
2338 &cumulative_shared_perms
);
2339 bs
->drv
->bdrv_set_perm(bs
, cumulative_perms
, cumulative_shared_perms
);
2343 static void GRAPH_RDLOCK
bdrv_drv_set_perm_abort(void *opaque
)
2345 BlockDriverState
*bs
= opaque
;
2346 GLOBAL_STATE_CODE();
2348 if (bs
->drv
->bdrv_abort_perm_update
) {
2349 bs
->drv
->bdrv_abort_perm_update(bs
);
2353 TransactionActionDrv bdrv_drv_set_perm_drv
= {
2354 .abort
= bdrv_drv_set_perm_abort
,
2355 .commit
= bdrv_drv_set_perm_commit
,
2359 * After calling this function, the transaction @tran may only be completed
2360 * while holding a reader lock for the graph.
2362 static int GRAPH_RDLOCK
2363 bdrv_drv_set_perm(BlockDriverState
*bs
, uint64_t perm
, uint64_t shared_perm
,
2364 Transaction
*tran
, Error
**errp
)
2366 GLOBAL_STATE_CODE();
2371 if (bs
->drv
->bdrv_check_perm
) {
2372 int ret
= bs
->drv
->bdrv_check_perm(bs
, perm
, shared_perm
, errp
);
2379 tran_add(tran
, &bdrv_drv_set_perm_drv
, bs
);
2385 typedef struct BdrvReplaceChildState
{
2387 BlockDriverState
*old_bs
;
2388 } BdrvReplaceChildState
;
2390 static void GRAPH_WRLOCK
bdrv_replace_child_commit(void *opaque
)
2392 BdrvReplaceChildState
*s
= opaque
;
2393 GLOBAL_STATE_CODE();
2395 bdrv_schedule_unref(s
->old_bs
);
2398 static void GRAPH_WRLOCK
bdrv_replace_child_abort(void *opaque
)
2400 BdrvReplaceChildState
*s
= opaque
;
2401 BlockDriverState
*new_bs
= s
->child
->bs
;
2403 GLOBAL_STATE_CODE();
2404 assert_bdrv_graph_writable();
2406 /* old_bs reference is transparently moved from @s to @s->child */
2407 if (!s
->child
->bs
) {
2409 * The parents were undrained when removing old_bs from the child. New
2410 * requests can't have been made, though, because the child was empty.
2412 * TODO Make bdrv_replace_child_noperm() transactionable to avoid
2413 * undraining the parent in the first place. Once this is done, having
2414 * new_bs drained when calling bdrv_replace_child_tran() is not a
2415 * requirement any more.
2417 bdrv_parent_drained_begin_single(s
->child
);
2418 assert(!bdrv_parent_drained_poll_single(s
->child
));
2420 assert(s
->child
->quiesced_parent
);
2421 bdrv_replace_child_noperm(s
->child
, s
->old_bs
);
2426 static TransactionActionDrv bdrv_replace_child_drv
= {
2427 .commit
= bdrv_replace_child_commit
,
2428 .abort
= bdrv_replace_child_abort
,
2433 * bdrv_replace_child_tran
2435 * Note: real unref of old_bs is done only on commit.
2437 * Both @child->bs and @new_bs (if non-NULL) must be drained. @new_bs must be
2438 * kept drained until the transaction is completed.
2440 * After calling this function, the transaction @tran may only be completed
2441 * while holding a writer lock for the graph.
2443 * The function doesn't update permissions, caller is responsible for this.
2445 static void GRAPH_WRLOCK
2446 bdrv_replace_child_tran(BdrvChild
*child
, BlockDriverState
*new_bs
,
2449 BdrvReplaceChildState
*s
= g_new(BdrvReplaceChildState
, 1);
2451 assert(child
->quiesced_parent
);
2452 assert(!new_bs
|| new_bs
->quiesce_counter
);
2454 *s
= (BdrvReplaceChildState
) {
2456 .old_bs
= child
->bs
,
2458 tran_add(tran
, &bdrv_replace_child_drv
, s
);
2464 bdrv_replace_child_noperm(child
, new_bs
);
2465 /* old_bs reference is transparently moved from @child to @s */
2469 * Refresh permissions in @bs subtree. The function is intended to be called
2470 * after some graph modification that was done without permission update.
2472 * After calling this function, the transaction @tran may only be completed
2473 * while holding a reader lock for the graph.
2475 static int GRAPH_RDLOCK
2476 bdrv_node_refresh_perm(BlockDriverState
*bs
, BlockReopenQueue
*q
,
2477 Transaction
*tran
, Error
**errp
)
2479 BlockDriver
*drv
= bs
->drv
;
2482 uint64_t cumulative_perms
, cumulative_shared_perms
;
2483 GLOBAL_STATE_CODE();
2485 bdrv_get_cumulative_perm(bs
, &cumulative_perms
, &cumulative_shared_perms
);
2487 /* Write permissions never work with read-only images */
2488 if ((cumulative_perms
& (BLK_PERM_WRITE
| BLK_PERM_WRITE_UNCHANGED
)) &&
2489 !bdrv_is_writable_after_reopen(bs
, q
))
2491 if (!bdrv_is_writable_after_reopen(bs
, NULL
)) {
2492 error_setg(errp
, "Block node is read-only");
2494 error_setg(errp
, "Read-only block node '%s' cannot support "
2495 "read-write users", bdrv_get_node_name(bs
));
2502 * Unaligned requests will automatically be aligned to bl.request_alignment
2503 * and without RESIZE we can't extend requests to write to space beyond the
2504 * end of the image, so it's required that the image size is aligned.
2506 if ((cumulative_perms
& (BLK_PERM_WRITE
| BLK_PERM_WRITE_UNCHANGED
)) &&
2507 !(cumulative_perms
& BLK_PERM_RESIZE
))
2509 if ((bs
->total_sectors
* BDRV_SECTOR_SIZE
) % bs
->bl
.request_alignment
) {
2510 error_setg(errp
, "Cannot get 'write' permission without 'resize': "
2511 "Image size is not a multiple of request "
2517 /* Check this node */
2522 ret
= bdrv_drv_set_perm(bs
, cumulative_perms
, cumulative_shared_perms
, tran
,
2528 /* Drivers that never have children can omit .bdrv_child_perm() */
2529 if (!drv
->bdrv_child_perm
) {
2530 assert(QLIST_EMPTY(&bs
->children
));
2534 /* Check all children */
2535 QLIST_FOREACH(c
, &bs
->children
, next
) {
2536 uint64_t cur_perm
, cur_shared
;
2538 bdrv_child_perm(bs
, c
->bs
, c
, c
->role
, q
,
2539 cumulative_perms
, cumulative_shared_perms
,
2540 &cur_perm
, &cur_shared
);
2541 bdrv_child_set_perm(c
, cur_perm
, cur_shared
, tran
);
2548 * @list is a product of bdrv_topological_dfs() (may be called several times) -
2549 * a topologically sorted subgraph.
2551 * After calling this function, the transaction @tran may only be completed
2552 * while holding a reader lock for the graph.
2554 static int GRAPH_RDLOCK
2555 bdrv_do_refresh_perms(GSList
*list
, BlockReopenQueue
*q
, Transaction
*tran
,
2559 BlockDriverState
*bs
;
2560 GLOBAL_STATE_CODE();
2562 for ( ; list
; list
= list
->next
) {
2565 if (bdrv_parent_perms_conflict(bs
, errp
)) {
2569 ret
= bdrv_node_refresh_perm(bs
, q
, tran
, errp
);
2579 * @list is any list of nodes. List is completed by all subtrees and
2580 * topologically sorted. It's not a problem if some node occurs in the @list
2583 * After calling this function, the transaction @tran may only be completed
2584 * while holding a reader lock for the graph.
2586 static int GRAPH_RDLOCK
2587 bdrv_list_refresh_perms(GSList
*list
, BlockReopenQueue
*q
, Transaction
*tran
,
2590 g_autoptr(GHashTable
) found
= g_hash_table_new(NULL
, NULL
);
2591 g_autoptr(GSList
) refresh_list
= NULL
;
2593 for ( ; list
; list
= list
->next
) {
2594 refresh_list
= bdrv_topological_dfs(refresh_list
, found
, list
->data
);
2597 return bdrv_do_refresh_perms(refresh_list
, q
, tran
, errp
);
2600 void bdrv_get_cumulative_perm(BlockDriverState
*bs
, uint64_t *perm
,
2601 uint64_t *shared_perm
)
2604 uint64_t cumulative_perms
= 0;
2605 uint64_t cumulative_shared_perms
= BLK_PERM_ALL
;
2607 GLOBAL_STATE_CODE();
2609 QLIST_FOREACH(c
, &bs
->parents
, next_parent
) {
2610 cumulative_perms
|= c
->perm
;
2611 cumulative_shared_perms
&= c
->shared_perm
;
2614 *perm
= cumulative_perms
;
2615 *shared_perm
= cumulative_shared_perms
;
2618 char *bdrv_perm_names(uint64_t perm
)
2624 { BLK_PERM_CONSISTENT_READ
, "consistent read" },
2625 { BLK_PERM_WRITE
, "write" },
2626 { BLK_PERM_WRITE_UNCHANGED
, "write unchanged" },
2627 { BLK_PERM_RESIZE
, "resize" },
2631 GString
*result
= g_string_sized_new(30);
2632 struct perm_name
*p
;
2634 for (p
= permissions
; p
->name
; p
++) {
2635 if (perm
& p
->perm
) {
2636 if (result
->len
> 0) {
2637 g_string_append(result
, ", ");
2639 g_string_append(result
, p
->name
);
2643 return g_string_free(result
, FALSE
);
2648 * @tran is allowed to be NULL. In this case no rollback is possible.
2650 * After calling this function, the transaction @tran may only be completed
2651 * while holding a reader lock for the graph.
2653 static int GRAPH_RDLOCK
2654 bdrv_refresh_perms(BlockDriverState
*bs
, Transaction
*tran
, Error
**errp
)
2657 Transaction
*local_tran
= NULL
;
2658 g_autoptr(GSList
) list
= bdrv_topological_dfs(NULL
, NULL
, bs
);
2659 GLOBAL_STATE_CODE();
2662 tran
= local_tran
= tran_new();
2665 ret
= bdrv_do_refresh_perms(list
, NULL
, tran
, errp
);
2668 tran_finalize(local_tran
, ret
);
2674 int bdrv_child_try_set_perm(BdrvChild
*c
, uint64_t perm
, uint64_t shared
,
2677 Error
*local_err
= NULL
;
2678 Transaction
*tran
= tran_new();
2681 GLOBAL_STATE_CODE();
2683 bdrv_child_set_perm(c
, perm
, shared
, tran
);
2685 ret
= bdrv_refresh_perms(c
->bs
, tran
, &local_err
);
2687 tran_finalize(tran
, ret
);
2690 if ((perm
& ~c
->perm
) || (c
->shared_perm
& ~shared
)) {
2691 /* tighten permissions */
2692 error_propagate(errp
, local_err
);
2695 * Our caller may intend to only loosen restrictions and
2696 * does not expect this function to fail. Errors are not
2697 * fatal in such a case, so we can just hide them from our
2700 error_free(local_err
);
2708 int bdrv_child_refresh_perms(BlockDriverState
*bs
, BdrvChild
*c
, Error
**errp
)
2710 uint64_t parent_perms
, parent_shared
;
2711 uint64_t perms
, shared
;
2713 GLOBAL_STATE_CODE();
2715 bdrv_get_cumulative_perm(bs
, &parent_perms
, &parent_shared
);
2716 bdrv_child_perm(bs
, c
->bs
, c
, c
->role
, NULL
,
2717 parent_perms
, parent_shared
, &perms
, &shared
);
2719 return bdrv_child_try_set_perm(c
, perms
, shared
, errp
);
2723 * Default implementation for .bdrv_child_perm() for block filters:
2724 * Forward CONSISTENT_READ, WRITE, WRITE_UNCHANGED, and RESIZE to the
2727 static void bdrv_filter_default_perms(BlockDriverState
*bs
, BdrvChild
*c
,
2729 BlockReopenQueue
*reopen_queue
,
2730 uint64_t perm
, uint64_t shared
,
2731 uint64_t *nperm
, uint64_t *nshared
)
2733 GLOBAL_STATE_CODE();
2734 *nperm
= perm
& DEFAULT_PERM_PASSTHROUGH
;
2735 *nshared
= (shared
& DEFAULT_PERM_PASSTHROUGH
) | DEFAULT_PERM_UNCHANGED
;
2738 static void bdrv_default_perms_for_cow(BlockDriverState
*bs
, BdrvChild
*c
,
2740 BlockReopenQueue
*reopen_queue
,
2741 uint64_t perm
, uint64_t shared
,
2742 uint64_t *nperm
, uint64_t *nshared
)
2744 assert(role
& BDRV_CHILD_COW
);
2745 GLOBAL_STATE_CODE();
2748 * We want consistent read from backing files if the parent needs it.
2749 * No other operations are performed on backing files.
2751 perm
&= BLK_PERM_CONSISTENT_READ
;
2754 * If the parent can deal with changing data, we're okay with a
2755 * writable and resizable backing file.
2756 * TODO Require !(perm & BLK_PERM_CONSISTENT_READ), too?
2758 if (shared
& BLK_PERM_WRITE
) {
2759 shared
= BLK_PERM_WRITE
| BLK_PERM_RESIZE
;
2764 shared
|= BLK_PERM_CONSISTENT_READ
| BLK_PERM_WRITE_UNCHANGED
;
2766 if (bs
->open_flags
& BDRV_O_INACTIVE
) {
2767 shared
|= BLK_PERM_WRITE
| BLK_PERM_RESIZE
;
2774 static void bdrv_default_perms_for_storage(BlockDriverState
*bs
, BdrvChild
*c
,
2776 BlockReopenQueue
*reopen_queue
,
2777 uint64_t perm
, uint64_t shared
,
2778 uint64_t *nperm
, uint64_t *nshared
)
2782 GLOBAL_STATE_CODE();
2783 assert(role
& (BDRV_CHILD_METADATA
| BDRV_CHILD_DATA
));
2785 flags
= bdrv_reopen_get_flags(reopen_queue
, bs
);
2788 * Apart from the modifications below, the same permissions are
2789 * forwarded and left alone as for filters
2791 bdrv_filter_default_perms(bs
, c
, role
, reopen_queue
,
2792 perm
, shared
, &perm
, &shared
);
2794 if (role
& BDRV_CHILD_METADATA
) {
2795 /* Format drivers may touch metadata even if the guest doesn't write */
2796 if (bdrv_is_writable_after_reopen(bs
, reopen_queue
)) {
2797 perm
|= BLK_PERM_WRITE
| BLK_PERM_RESIZE
;
2801 * bs->file always needs to be consistent because of the
2802 * metadata. We can never allow other users to resize or write
2805 if (!(flags
& BDRV_O_NO_IO
)) {
2806 perm
|= BLK_PERM_CONSISTENT_READ
;
2808 shared
&= ~(BLK_PERM_WRITE
| BLK_PERM_RESIZE
);
2811 if (role
& BDRV_CHILD_DATA
) {
2813 * Technically, everything in this block is a subset of the
2814 * BDRV_CHILD_METADATA path taken above, and so this could
2815 * be an "else if" branch. However, that is not obvious, and
2816 * this function is not performance critical, therefore we let
2817 * this be an independent "if".
2821 * We cannot allow other users to resize the file because the
2822 * format driver might have some assumptions about the size
2823 * (e.g. because it is stored in metadata, or because the file
2824 * is split into fixed-size data files).
2826 shared
&= ~BLK_PERM_RESIZE
;
2829 * WRITE_UNCHANGED often cannot be performed as such on the
2830 * data file. For example, the qcow2 driver may still need to
2831 * write copied clusters on copy-on-read.
2833 if (perm
& BLK_PERM_WRITE_UNCHANGED
) {
2834 perm
|= BLK_PERM_WRITE
;
2838 * If the data file is written to, the format driver may
2839 * expect to be able to resize it by writing beyond the EOF.
2841 if (perm
& BLK_PERM_WRITE
) {
2842 perm
|= BLK_PERM_RESIZE
;
2846 if (bs
->open_flags
& BDRV_O_INACTIVE
) {
2847 shared
|= BLK_PERM_WRITE
| BLK_PERM_RESIZE
;
2854 void bdrv_default_perms(BlockDriverState
*bs
, BdrvChild
*c
,
2855 BdrvChildRole role
, BlockReopenQueue
*reopen_queue
,
2856 uint64_t perm
, uint64_t shared
,
2857 uint64_t *nperm
, uint64_t *nshared
)
2859 GLOBAL_STATE_CODE();
2860 if (role
& BDRV_CHILD_FILTERED
) {
2861 assert(!(role
& (BDRV_CHILD_DATA
| BDRV_CHILD_METADATA
|
2863 bdrv_filter_default_perms(bs
, c
, role
, reopen_queue
,
2864 perm
, shared
, nperm
, nshared
);
2865 } else if (role
& BDRV_CHILD_COW
) {
2866 assert(!(role
& (BDRV_CHILD_DATA
| BDRV_CHILD_METADATA
)));
2867 bdrv_default_perms_for_cow(bs
, c
, role
, reopen_queue
,
2868 perm
, shared
, nperm
, nshared
);
2869 } else if (role
& (BDRV_CHILD_METADATA
| BDRV_CHILD_DATA
)) {
2870 bdrv_default_perms_for_storage(bs
, c
, role
, reopen_queue
,
2871 perm
, shared
, nperm
, nshared
);
2873 g_assert_not_reached();
2877 uint64_t bdrv_qapi_perm_to_blk_perm(BlockPermission qapi_perm
)
2879 static const uint64_t permissions
[] = {
2880 [BLOCK_PERMISSION_CONSISTENT_READ
] = BLK_PERM_CONSISTENT_READ
,
2881 [BLOCK_PERMISSION_WRITE
] = BLK_PERM_WRITE
,
2882 [BLOCK_PERMISSION_WRITE_UNCHANGED
] = BLK_PERM_WRITE_UNCHANGED
,
2883 [BLOCK_PERMISSION_RESIZE
] = BLK_PERM_RESIZE
,
2886 QEMU_BUILD_BUG_ON(ARRAY_SIZE(permissions
) != BLOCK_PERMISSION__MAX
);
2887 QEMU_BUILD_BUG_ON(1UL << ARRAY_SIZE(permissions
) != BLK_PERM_ALL
+ 1);
2889 assert(qapi_perm
< BLOCK_PERMISSION__MAX
);
2891 return permissions
[qapi_perm
];
2895 * Replaces the node that a BdrvChild points to without updating permissions.
2897 * If @new_bs is non-NULL, the parent of @child must already be drained through
2898 * @child and the caller must hold the AioContext lock for @new_bs.
2900 static void GRAPH_WRLOCK
2901 bdrv_replace_child_noperm(BdrvChild
*child
, BlockDriverState
*new_bs
)
2903 BlockDriverState
*old_bs
= child
->bs
;
2904 int new_bs_quiesce_counter
;
2906 assert(!child
->frozen
);
2909 * If we want to change the BdrvChild to point to a drained node as its new
2910 * child->bs, we need to make sure that its new parent is drained, too. In
2911 * other words, either child->quiesce_parent must already be true or we must
2912 * be able to set it and keep the parent's quiesce_counter consistent with
2913 * that, but without polling or starting new requests (this function
2914 * guarantees that it doesn't poll, and starting new requests would be
2915 * against the invariants of drain sections).
2917 * To keep things simple, we pick the first option (child->quiesce_parent
2918 * must already be true). We also generalise the rule a bit to make it
2919 * easier to verify in callers and more likely to be covered in test cases:
2920 * The parent must be quiesced through this child even if new_bs isn't
2921 * currently drained.
2923 * The only exception is for callers that always pass new_bs == NULL. In
2924 * this case, we obviously never need to consider the case of a drained
2925 * new_bs, so we can keep the callers simpler by allowing them not to drain
2928 assert(!new_bs
|| child
->quiesced_parent
);
2929 assert(old_bs
!= new_bs
);
2930 GLOBAL_STATE_CODE();
2932 if (old_bs
&& new_bs
) {
2933 assert(bdrv_get_aio_context(old_bs
) == bdrv_get_aio_context(new_bs
));
2937 if (child
->klass
->detach
) {
2938 child
->klass
->detach(child
);
2940 QLIST_REMOVE(child
, next_parent
);
2946 QLIST_INSERT_HEAD(&new_bs
->parents
, child
, next_parent
);
2947 if (child
->klass
->attach
) {
2948 child
->klass
->attach(child
);
2953 * If the parent was drained through this BdrvChild previously, but new_bs
2954 * is not drained, allow requests to come in only after the new node has
2957 new_bs_quiesce_counter
= (new_bs
? new_bs
->quiesce_counter
: 0);
2958 if (!new_bs_quiesce_counter
&& child
->quiesced_parent
) {
2959 bdrv_parent_drained_end_single(child
);
2964 * Free the given @child.
2966 * The child must be empty (i.e. `child->bs == NULL`) and it must be
2967 * unused (i.e. not in a children list).
2969 static void bdrv_child_free(BdrvChild
*child
)
2972 GLOBAL_STATE_CODE();
2973 assert(!child
->next
.le_prev
); /* not in children list */
2975 g_free(child
->name
);
2979 typedef struct BdrvAttachChildCommonState
{
2981 AioContext
*old_parent_ctx
;
2982 AioContext
*old_child_ctx
;
2983 } BdrvAttachChildCommonState
;
2985 static void GRAPH_WRLOCK
bdrv_attach_child_common_abort(void *opaque
)
2987 BdrvAttachChildCommonState
*s
= opaque
;
2988 BlockDriverState
*bs
= s
->child
->bs
;
2990 GLOBAL_STATE_CODE();
2991 assert_bdrv_graph_writable();
2993 bdrv_replace_child_noperm(s
->child
, NULL
);
2995 if (bdrv_get_aio_context(bs
) != s
->old_child_ctx
) {
2996 bdrv_try_change_aio_context(bs
, s
->old_child_ctx
, NULL
, &error_abort
);
2999 if (bdrv_child_get_parent_aio_context(s
->child
) != s
->old_parent_ctx
) {
3001 GHashTable
*visited
;
3006 /* No need to visit `child`, because it has been detached already */
3007 visited
= g_hash_table_new(NULL
, NULL
);
3008 ret
= s
->child
->klass
->change_aio_ctx(s
->child
, s
->old_parent_ctx
,
3009 visited
, tran
, &error_abort
);
3010 g_hash_table_destroy(visited
);
3012 /* transaction is supposed to always succeed */
3013 assert(ret
== true);
3017 bdrv_schedule_unref(bs
);
3018 bdrv_child_free(s
->child
);
3021 static TransactionActionDrv bdrv_attach_child_common_drv
= {
3022 .abort
= bdrv_attach_child_common_abort
,
3027 * Common part of attaching bdrv child to bs or to blk or to job
3029 * Function doesn't update permissions, caller is responsible for this.
3031 * After calling this function, the transaction @tran may only be completed
3032 * while holding a writer lock for the graph.
3034 * Returns new created child.
3036 * The caller must hold the AioContext lock for @child_bs. Both @parent_bs and
3037 * @child_bs can move to a different AioContext in this function. Callers must
3038 * make sure that their AioContext locking is still correct after this.
3040 static BdrvChild
* GRAPH_WRLOCK
3041 bdrv_attach_child_common(BlockDriverState
*child_bs
,
3042 const char *child_name
,
3043 const BdrvChildClass
*child_class
,
3044 BdrvChildRole child_role
,
3045 uint64_t perm
, uint64_t shared_perm
,
3047 Transaction
*tran
, Error
**errp
)
3049 BdrvChild
*new_child
;
3050 AioContext
*parent_ctx
, *new_child_ctx
;
3051 AioContext
*child_ctx
= bdrv_get_aio_context(child_bs
);
3053 assert(child_class
->get_parent_desc
);
3054 GLOBAL_STATE_CODE();
3056 new_child
= g_new(BdrvChild
, 1);
3057 *new_child
= (BdrvChild
) {
3059 .name
= g_strdup(child_name
),
3060 .klass
= child_class
,
3063 .shared_perm
= shared_perm
,
3068 * If the AioContexts don't match, first try to move the subtree of
3069 * child_bs into the AioContext of the new parent. If this doesn't work,
3070 * try moving the parent into the AioContext of child_bs instead.
3072 parent_ctx
= bdrv_child_get_parent_aio_context(new_child
);
3073 if (child_ctx
!= parent_ctx
) {
3074 Error
*local_err
= NULL
;
3075 int ret
= bdrv_try_change_aio_context(child_bs
, parent_ctx
, NULL
,
3078 if (ret
< 0 && child_class
->change_aio_ctx
) {
3079 Transaction
*aio_ctx_tran
= tran_new();
3080 GHashTable
*visited
= g_hash_table_new(NULL
, NULL
);
3083 g_hash_table_add(visited
, new_child
);
3084 ret_child
= child_class
->change_aio_ctx(new_child
, child_ctx
,
3085 visited
, aio_ctx_tran
,
3087 if (ret_child
== true) {
3088 error_free(local_err
);
3091 tran_finalize(aio_ctx_tran
, ret_child
== true ? 0 : -1);
3092 g_hash_table_destroy(visited
);
3096 error_propagate(errp
, local_err
);
3097 bdrv_child_free(new_child
);
3102 new_child_ctx
= bdrv_get_aio_context(child_bs
);
3103 if (new_child_ctx
!= child_ctx
) {
3104 aio_context_release(child_ctx
);
3105 aio_context_acquire(new_child_ctx
);
3110 * Let every new BdrvChild start with a drained parent. Inserting the child
3111 * in the graph with bdrv_replace_child_noperm() will undrain it if
3112 * @child_bs is not drained.
3114 * The child was only just created and is not yet visible in global state
3115 * until bdrv_replace_child_noperm() inserts it into the graph, so nobody
3116 * could have sent requests and polling is not necessary.
3118 * Note that this means that the parent isn't fully drained yet, we only
3119 * stop new requests from coming in. This is fine, we don't care about the
3120 * old requests here, they are not for this child. If another place enters a
3121 * drain section for the same parent, but wants it to be fully quiesced, it
3122 * will not run most of the the code in .drained_begin() again (which is not
3123 * a problem, we already did this), but it will still poll until the parent
3124 * is fully quiesced, so it will not be negatively affected either.
3126 bdrv_parent_drained_begin_single(new_child
);
3127 bdrv_replace_child_noperm(new_child
, child_bs
);
3129 BdrvAttachChildCommonState
*s
= g_new(BdrvAttachChildCommonState
, 1);
3130 *s
= (BdrvAttachChildCommonState
) {
3132 .old_parent_ctx
= parent_ctx
,
3133 .old_child_ctx
= child_ctx
,
3135 tran_add(tran
, &bdrv_attach_child_common_drv
, s
);
3137 if (new_child_ctx
!= child_ctx
) {
3138 aio_context_release(new_child_ctx
);
3139 aio_context_acquire(child_ctx
);
3146 * Function doesn't update permissions, caller is responsible for this.
3148 * The caller must hold the AioContext lock for @child_bs. Both @parent_bs and
3149 * @child_bs can move to a different AioContext in this function. Callers must
3150 * make sure that their AioContext locking is still correct after this.
3152 * After calling this function, the transaction @tran may only be completed
3153 * while holding a writer lock for the graph.
3155 static BdrvChild
* GRAPH_WRLOCK
3156 bdrv_attach_child_noperm(BlockDriverState
*parent_bs
,
3157 BlockDriverState
*child_bs
,
3158 const char *child_name
,
3159 const BdrvChildClass
*child_class
,
3160 BdrvChildRole child_role
,
3164 uint64_t perm
, shared_perm
;
3166 assert(parent_bs
->drv
);
3167 GLOBAL_STATE_CODE();
3169 if (bdrv_recurse_has_child(child_bs
, parent_bs
)) {
3170 error_setg(errp
, "Making '%s' a %s child of '%s' would create a cycle",
3171 child_bs
->node_name
, child_name
, parent_bs
->node_name
);
3175 bdrv_get_cumulative_perm(parent_bs
, &perm
, &shared_perm
);
3176 bdrv_child_perm(parent_bs
, child_bs
, NULL
, child_role
, NULL
,
3177 perm
, shared_perm
, &perm
, &shared_perm
);
3179 return bdrv_attach_child_common(child_bs
, child_name
, child_class
,
3180 child_role
, perm
, shared_perm
, parent_bs
,
3185 * This function steals the reference to child_bs from the caller.
3186 * That reference is later dropped by bdrv_root_unref_child().
3188 * On failure NULL is returned, errp is set and the reference to
3189 * child_bs is also dropped.
3191 * The caller must hold the AioContext lock @child_bs, but not that of @ctx
3192 * (unless @child_bs is already in @ctx).
3194 BdrvChild
*bdrv_root_attach_child(BlockDriverState
*child_bs
,
3195 const char *child_name
,
3196 const BdrvChildClass
*child_class
,
3197 BdrvChildRole child_role
,
3198 uint64_t perm
, uint64_t shared_perm
,
3199 void *opaque
, Error
**errp
)
3203 Transaction
*tran
= tran_new();
3205 GLOBAL_STATE_CODE();
3207 bdrv_graph_wrlock(child_bs
);
3209 child
= bdrv_attach_child_common(child_bs
, child_name
, child_class
,
3210 child_role
, perm
, shared_perm
, opaque
,
3217 ret
= bdrv_refresh_perms(child_bs
, tran
, errp
);
3220 tran_finalize(tran
, ret
);
3221 bdrv_graph_wrunlock();
3223 bdrv_unref(child_bs
);
3225 return ret
< 0 ? NULL
: child
;
3229 * This function transfers the reference to child_bs from the caller
3230 * to parent_bs. That reference is later dropped by parent_bs on
3231 * bdrv_close() or if someone calls bdrv_unref_child().
3233 * On failure NULL is returned, errp is set and the reference to
3234 * child_bs is also dropped.
3236 * If @parent_bs and @child_bs are in different AioContexts, the caller must
3237 * hold the AioContext lock for @child_bs, but not for @parent_bs.
3239 BdrvChild
*bdrv_attach_child(BlockDriverState
*parent_bs
,
3240 BlockDriverState
*child_bs
,
3241 const char *child_name
,
3242 const BdrvChildClass
*child_class
,
3243 BdrvChildRole child_role
,
3248 Transaction
*tran
= tran_new();
3250 GLOBAL_STATE_CODE();
3252 child
= bdrv_attach_child_noperm(parent_bs
, child_bs
, child_name
,
3253 child_class
, child_role
, tran
, errp
);
3259 ret
= bdrv_refresh_perms(parent_bs
, tran
, errp
);
3265 tran_finalize(tran
, ret
);
3267 bdrv_schedule_unref(child_bs
);
3269 return ret
< 0 ? NULL
: child
;
3272 /* Callers must ensure that child->frozen is false. */
3273 void bdrv_root_unref_child(BdrvChild
*child
)
3275 BlockDriverState
*child_bs
= child
->bs
;
3277 GLOBAL_STATE_CODE();
3278 bdrv_replace_child_noperm(child
, NULL
);
3279 bdrv_child_free(child
);
3283 * Update permissions for old node. We're just taking a parent away, so
3284 * we're loosening restrictions. Errors of permission update are not
3285 * fatal in this case, ignore them.
3287 bdrv_refresh_perms(child_bs
, NULL
, NULL
);
3290 * When the parent requiring a non-default AioContext is removed, the
3291 * node moves back to the main AioContext
3293 bdrv_try_change_aio_context(child_bs
, qemu_get_aio_context(), NULL
,
3297 bdrv_schedule_unref(child_bs
);
3300 typedef struct BdrvSetInheritsFrom
{
3301 BlockDriverState
*bs
;
3302 BlockDriverState
*old_inherits_from
;
3303 } BdrvSetInheritsFrom
;
3305 static void bdrv_set_inherits_from_abort(void *opaque
)
3307 BdrvSetInheritsFrom
*s
= opaque
;
3309 s
->bs
->inherits_from
= s
->old_inherits_from
;
3312 static TransactionActionDrv bdrv_set_inherits_from_drv
= {
3313 .abort
= bdrv_set_inherits_from_abort
,
3317 /* @tran is allowed to be NULL. In this case no rollback is possible */
3318 static void bdrv_set_inherits_from(BlockDriverState
*bs
,
3319 BlockDriverState
*new_inherits_from
,
3323 BdrvSetInheritsFrom
*s
= g_new(BdrvSetInheritsFrom
, 1);
3325 *s
= (BdrvSetInheritsFrom
) {
3327 .old_inherits_from
= bs
->inherits_from
,
3330 tran_add(tran
, &bdrv_set_inherits_from_drv
, s
);
3333 bs
->inherits_from
= new_inherits_from
;
3337 * Clear all inherits_from pointers from children and grandchildren of
3338 * @root that point to @root, where necessary.
3339 * @tran is allowed to be NULL. In this case no rollback is possible
3341 static void GRAPH_WRLOCK
3342 bdrv_unset_inherits_from(BlockDriverState
*root
, BdrvChild
*child
,
3347 if (child
->bs
->inherits_from
== root
) {
3349 * Remove inherits_from only when the last reference between root and
3350 * child->bs goes away.
3352 QLIST_FOREACH(c
, &root
->children
, next
) {
3353 if (c
!= child
&& c
->bs
== child
->bs
) {
3358 bdrv_set_inherits_from(child
->bs
, NULL
, tran
);
3362 QLIST_FOREACH(c
, &child
->bs
->children
, next
) {
3363 bdrv_unset_inherits_from(root
, c
, tran
);
3367 /* Callers must ensure that child->frozen is false. */
3368 void bdrv_unref_child(BlockDriverState
*parent
, BdrvChild
*child
)
3370 GLOBAL_STATE_CODE();
3371 if (child
== NULL
) {
3375 bdrv_unset_inherits_from(parent
, child
, NULL
);
3376 bdrv_root_unref_child(child
);
3380 static void GRAPH_RDLOCK
3381 bdrv_parent_cb_change_media(BlockDriverState
*bs
, bool load
)
3384 GLOBAL_STATE_CODE();
3385 QLIST_FOREACH(c
, &bs
->parents
, next_parent
) {
3386 if (c
->klass
->change_media
) {
3387 c
->klass
->change_media(c
, load
);
3392 /* Return true if you can reach parent going through child->inherits_from
3393 * recursively. If parent or child are NULL, return false */
3394 static bool bdrv_inherits_from_recursive(BlockDriverState
*child
,
3395 BlockDriverState
*parent
)
3397 while (child
&& child
!= parent
) {
3398 child
= child
->inherits_from
;
3401 return child
!= NULL
;
3405 * Return the BdrvChildRole for @bs's backing child. bs->backing is
3406 * mostly used for COW backing children (role = COW), but also for
3407 * filtered children (role = FILTERED | PRIMARY).
3409 static BdrvChildRole
bdrv_backing_role(BlockDriverState
*bs
)
3411 if (bs
->drv
&& bs
->drv
->is_filter
) {
3412 return BDRV_CHILD_FILTERED
| BDRV_CHILD_PRIMARY
;
3414 return BDRV_CHILD_COW
;
3419 * Sets the bs->backing or bs->file link of a BDS. A new reference is created;
3420 * callers which don't need their own reference any more must call bdrv_unref().
3422 * If the respective child is already present (i.e. we're detaching a node),
3423 * that child node must be drained.
3425 * Function doesn't update permissions, caller is responsible for this.
3427 * The caller must hold the AioContext lock for @child_bs. Both @parent_bs and
3428 * @child_bs can move to a different AioContext in this function. Callers must
3429 * make sure that their AioContext locking is still correct after this.
3431 * After calling this function, the transaction @tran may only be completed
3432 * while holding a writer lock for the graph.
3434 static int GRAPH_WRLOCK
3435 bdrv_set_file_or_backing_noperm(BlockDriverState
*parent_bs
,
3436 BlockDriverState
*child_bs
,
3438 Transaction
*tran
, Error
**errp
)
3440 bool update_inherits_from
=
3441 bdrv_inherits_from_recursive(child_bs
, parent_bs
);
3442 BdrvChild
*child
= is_backing
? parent_bs
->backing
: parent_bs
->file
;
3445 GLOBAL_STATE_CODE();
3447 if (!parent_bs
->drv
) {
3449 * Node without drv is an object without a class :/. TODO: finally fix
3450 * qcow2 driver to never clear bs->drv and implement format corruption
3451 * handling in other way.
3453 error_setg(errp
, "Node corrupted");
3457 if (child
&& child
->frozen
) {
3458 error_setg(errp
, "Cannot change frozen '%s' link from '%s' to '%s'",
3459 child
->name
, parent_bs
->node_name
, child
->bs
->node_name
);
3463 if (is_backing
&& !parent_bs
->drv
->is_filter
&&
3464 !parent_bs
->drv
->supports_backing
)
3466 error_setg(errp
, "Driver '%s' of node '%s' does not support backing "
3467 "files", parent_bs
->drv
->format_name
, parent_bs
->node_name
);
3471 if (parent_bs
->drv
->is_filter
) {
3472 role
= BDRV_CHILD_FILTERED
| BDRV_CHILD_PRIMARY
;
3473 } else if (is_backing
) {
3474 role
= BDRV_CHILD_COW
;
3477 * We only can use same role as it is in existing child. We don't have
3478 * infrastructure to determine role of file child in generic way
3481 error_setg(errp
, "Cannot set file child to format node without "
3489 assert(child
->bs
->quiesce_counter
);
3490 bdrv_unset_inherits_from(parent_bs
, child
, tran
);
3491 bdrv_remove_child(child
, tran
);
3498 child
= bdrv_attach_child_noperm(parent_bs
, child_bs
,
3499 is_backing
? "backing" : "file",
3500 &child_of_bds
, role
,
3508 * If inherits_from pointed recursively to bs then let's update it to
3509 * point directly to bs (else it will become NULL).
3511 if (update_inherits_from
) {
3512 bdrv_set_inherits_from(child_bs
, parent_bs
, tran
);
3516 bdrv_refresh_limits(parent_bs
, tran
, NULL
);
3522 * The caller must hold the AioContext lock for @backing_hd. Both @bs and
3523 * @backing_hd can move to a different AioContext in this function. Callers must
3524 * make sure that their AioContext locking is still correct after this.
3526 * If a backing child is already present (i.e. we're detaching a node), that
3527 * child node must be drained.
3529 * After calling this function, the transaction @tran may only be completed
3530 * while holding a writer lock for the graph.
3532 static int GRAPH_WRLOCK
3533 bdrv_set_backing_noperm(BlockDriverState
*bs
,
3534 BlockDriverState
*backing_hd
,
3535 Transaction
*tran
, Error
**errp
)
3537 GLOBAL_STATE_CODE();
3538 return bdrv_set_file_or_backing_noperm(bs
, backing_hd
, true, tran
, errp
);
3541 int bdrv_set_backing_hd_drained(BlockDriverState
*bs
,
3542 BlockDriverState
*backing_hd
,
3546 Transaction
*tran
= tran_new();
3548 GLOBAL_STATE_CODE();
3549 assert(bs
->quiesce_counter
> 0);
3551 assert(bs
->backing
->bs
->quiesce_counter
> 0);
3553 bdrv_graph_wrlock(backing_hd
);
3555 ret
= bdrv_set_backing_noperm(bs
, backing_hd
, tran
, errp
);
3560 ret
= bdrv_refresh_perms(bs
, tran
, errp
);
3562 tran_finalize(tran
, ret
);
3563 bdrv_graph_wrunlock();
3567 int bdrv_set_backing_hd(BlockDriverState
*bs
, BlockDriverState
*backing_hd
,
3570 BlockDriverState
*drain_bs
= bs
->backing
? bs
->backing
->bs
: bs
;
3572 GLOBAL_STATE_CODE();
3575 bdrv_drained_begin(drain_bs
);
3576 ret
= bdrv_set_backing_hd_drained(bs
, backing_hd
, errp
);
3577 bdrv_drained_end(drain_bs
);
3578 bdrv_unref(drain_bs
);
3584 * Opens the backing file for a BlockDriverState if not yet open
3586 * bdref_key specifies the key for the image's BlockdevRef in the options QDict.
3587 * That QDict has to be flattened; therefore, if the BlockdevRef is a QDict
3588 * itself, all options starting with "${bdref_key}." are considered part of the
3591 * The caller must hold the main AioContext lock.
3593 * TODO Can this be unified with bdrv_open_image()?
3595 int bdrv_open_backing_file(BlockDriverState
*bs
, QDict
*parent_options
,
3596 const char *bdref_key
, Error
**errp
)
3598 char *backing_filename
= NULL
;
3599 char *bdref_key_dot
;
3600 const char *reference
= NULL
;
3602 bool implicit_backing
= false;
3603 BlockDriverState
*backing_hd
;
3604 AioContext
*backing_hd_ctx
;
3606 QDict
*tmp_parent_options
= NULL
;
3607 Error
*local_err
= NULL
;
3609 GLOBAL_STATE_CODE();
3611 if (bs
->backing
!= NULL
) {
3615 /* NULL means an empty set of options */
3616 if (parent_options
== NULL
) {
3617 tmp_parent_options
= qdict_new();
3618 parent_options
= tmp_parent_options
;
3621 bs
->open_flags
&= ~BDRV_O_NO_BACKING
;
3623 bdref_key_dot
= g_strdup_printf("%s.", bdref_key
);
3624 qdict_extract_subqdict(parent_options
, &options
, bdref_key_dot
);
3625 g_free(bdref_key_dot
);
3628 * Caution: while qdict_get_try_str() is fine, getting non-string
3629 * types would require more care. When @parent_options come from
3630 * -blockdev or blockdev_add, its members are typed according to
3631 * the QAPI schema, but when they come from -drive, they're all
3634 reference
= qdict_get_try_str(parent_options
, bdref_key
);
3635 if (reference
|| qdict_haskey(options
, "file.filename")) {
3636 /* keep backing_filename NULL */
3637 } else if (bs
->backing_file
[0] == '\0' && qdict_size(options
) == 0) {
3638 qobject_unref(options
);
3641 if (qdict_size(options
) == 0) {
3642 /* If the user specifies options that do not modify the
3643 * backing file's behavior, we might still consider it the
3644 * implicit backing file. But it's easier this way, and
3645 * just specifying some of the backing BDS's options is
3646 * only possible with -drive anyway (otherwise the QAPI
3647 * schema forces the user to specify everything). */
3648 implicit_backing
= !strcmp(bs
->auto_backing_file
, bs
->backing_file
);
3651 bdrv_graph_rdlock_main_loop();
3652 backing_filename
= bdrv_get_full_backing_filename(bs
, &local_err
);
3653 bdrv_graph_rdunlock_main_loop();
3657 error_propagate(errp
, local_err
);
3658 qobject_unref(options
);
3663 if (!bs
->drv
|| !bs
->drv
->supports_backing
) {
3665 error_setg(errp
, "Driver doesn't support backing files");
3666 qobject_unref(options
);
3671 bs
->backing_format
[0] != '\0' && !qdict_haskey(options
, "driver")) {
3672 qdict_put_str(options
, "driver", bs
->backing_format
);
3675 backing_hd
= bdrv_open_inherit(backing_filename
, reference
, options
, 0, bs
,
3676 &child_of_bds
, bdrv_backing_role(bs
), errp
);
3678 bs
->open_flags
|= BDRV_O_NO_BACKING
;
3679 error_prepend(errp
, "Could not open backing file: ");
3684 if (implicit_backing
) {
3685 bdrv_graph_rdlock_main_loop();
3686 bdrv_refresh_filename(backing_hd
);
3687 bdrv_graph_rdunlock_main_loop();
3688 pstrcpy(bs
->auto_backing_file
, sizeof(bs
->auto_backing_file
),
3689 backing_hd
->filename
);
3692 /* Hook up the backing file link; drop our reference, bs owns the
3693 * backing_hd reference now */
3694 backing_hd_ctx
= bdrv_get_aio_context(backing_hd
);
3695 aio_context_acquire(backing_hd_ctx
);
3696 ret
= bdrv_set_backing_hd(bs
, backing_hd
, errp
);
3697 bdrv_unref(backing_hd
);
3698 aio_context_release(backing_hd_ctx
);
3704 qdict_del(parent_options
, bdref_key
);
3707 g_free(backing_filename
);
3708 qobject_unref(tmp_parent_options
);
3712 static BlockDriverState
*
3713 bdrv_open_child_bs(const char *filename
, QDict
*options
, const char *bdref_key
,
3714 BlockDriverState
*parent
, const BdrvChildClass
*child_class
,
3715 BdrvChildRole child_role
, bool allow_none
, Error
**errp
)
3717 BlockDriverState
*bs
= NULL
;
3718 QDict
*image_options
;
3719 char *bdref_key_dot
;
3720 const char *reference
;
3722 assert(child_class
!= NULL
);
3724 bdref_key_dot
= g_strdup_printf("%s.", bdref_key
);
3725 qdict_extract_subqdict(options
, &image_options
, bdref_key_dot
);
3726 g_free(bdref_key_dot
);
3729 * Caution: while qdict_get_try_str() is fine, getting non-string
3730 * types would require more care. When @options come from
3731 * -blockdev or blockdev_add, its members are typed according to
3732 * the QAPI schema, but when they come from -drive, they're all
3735 reference
= qdict_get_try_str(options
, bdref_key
);
3736 if (!filename
&& !reference
&& !qdict_size(image_options
)) {
3738 error_setg(errp
, "A block device must be specified for \"%s\"",
3741 qobject_unref(image_options
);
3745 bs
= bdrv_open_inherit(filename
, reference
, image_options
, 0,
3746 parent
, child_class
, child_role
, errp
);
3752 qdict_del(options
, bdref_key
);
3757 * Opens a disk image whose options are given as BlockdevRef in another block
3760 * If allow_none is true, no image will be opened if filename is false and no
3761 * BlockdevRef is given. NULL will be returned, but errp remains unset.
3763 * bdrev_key specifies the key for the image's BlockdevRef in the options QDict.
3764 * That QDict has to be flattened; therefore, if the BlockdevRef is a QDict
3765 * itself, all options starting with "${bdref_key}." are considered part of the
3768 * The BlockdevRef will be removed from the options QDict.
3770 * The caller must hold the lock of the main AioContext and no other AioContext.
3771 * @parent can move to a different AioContext in this function. Callers must
3772 * make sure that their AioContext locking is still correct after this.
3774 BdrvChild
*bdrv_open_child(const char *filename
,
3775 QDict
*options
, const char *bdref_key
,
3776 BlockDriverState
*parent
,
3777 const BdrvChildClass
*child_class
,
3778 BdrvChildRole child_role
,
3779 bool allow_none
, Error
**errp
)
3781 BlockDriverState
*bs
;
3785 GLOBAL_STATE_CODE();
3787 bs
= bdrv_open_child_bs(filename
, options
, bdref_key
, parent
, child_class
,
3788 child_role
, allow_none
, errp
);
3793 bdrv_graph_wrlock(NULL
);
3794 ctx
= bdrv_get_aio_context(bs
);
3795 aio_context_acquire(ctx
);
3796 child
= bdrv_attach_child(parent
, bs
, bdref_key
, child_class
, child_role
,
3798 aio_context_release(ctx
);
3799 bdrv_graph_wrunlock();
3805 * Wrapper on bdrv_open_child() for most popular case: open primary child of bs.
3807 * The caller must hold the lock of the main AioContext and no other AioContext.
3808 * @parent can move to a different AioContext in this function. Callers must
3809 * make sure that their AioContext locking is still correct after this.
3811 int bdrv_open_file_child(const char *filename
,
3812 QDict
*options
, const char *bdref_key
,
3813 BlockDriverState
*parent
, Error
**errp
)
3817 /* commit_top and mirror_top don't use this function */
3818 assert(!parent
->drv
->filtered_child_is_backing
);
3819 role
= parent
->drv
->is_filter
?
3820 (BDRV_CHILD_FILTERED
| BDRV_CHILD_PRIMARY
) : BDRV_CHILD_IMAGE
;
3822 if (!bdrv_open_child(filename
, options
, bdref_key
, parent
,
3823 &child_of_bds
, role
, false, errp
))
3832 * TODO Future callers may need to specify parent/child_class in order for
3833 * option inheritance to work. Existing callers use it for the root node.
3835 BlockDriverState
*bdrv_open_blockdev_ref(BlockdevRef
*ref
, Error
**errp
)
3837 BlockDriverState
*bs
= NULL
;
3838 QObject
*obj
= NULL
;
3839 QDict
*qdict
= NULL
;
3840 const char *reference
= NULL
;
3843 GLOBAL_STATE_CODE();
3845 if (ref
->type
== QTYPE_QSTRING
) {
3846 reference
= ref
->u
.reference
;
3848 BlockdevOptions
*options
= &ref
->u
.definition
;
3849 assert(ref
->type
== QTYPE_QDICT
);
3851 v
= qobject_output_visitor_new(&obj
);
3852 visit_type_BlockdevOptions(v
, NULL
, &options
, &error_abort
);
3853 visit_complete(v
, &obj
);
3855 qdict
= qobject_to(QDict
, obj
);
3856 qdict_flatten(qdict
);
3858 /* bdrv_open_inherit() defaults to the values in bdrv_flags (for
3859 * compatibility with other callers) rather than what we want as the
3860 * real defaults. Apply the defaults here instead. */
3861 qdict_set_default_str(qdict
, BDRV_OPT_CACHE_DIRECT
, "off");
3862 qdict_set_default_str(qdict
, BDRV_OPT_CACHE_NO_FLUSH
, "off");
3863 qdict_set_default_str(qdict
, BDRV_OPT_READ_ONLY
, "off");
3864 qdict_set_default_str(qdict
, BDRV_OPT_AUTO_READ_ONLY
, "off");
3868 bs
= bdrv_open_inherit(NULL
, reference
, qdict
, 0, NULL
, NULL
, 0, errp
);
3875 static BlockDriverState
*bdrv_append_temp_snapshot(BlockDriverState
*bs
,
3877 QDict
*snapshot_options
,
3880 g_autofree
char *tmp_filename
= NULL
;
3882 QemuOpts
*opts
= NULL
;
3883 BlockDriverState
*bs_snapshot
= NULL
;
3884 AioContext
*ctx
= bdrv_get_aio_context(bs
);
3887 GLOBAL_STATE_CODE();
3889 /* if snapshot, we create a temporary backing file and open it
3890 instead of opening 'filename' directly */
3892 /* Get the required size from the image */
3893 aio_context_acquire(ctx
);
3894 total_size
= bdrv_getlength(bs
);
3895 aio_context_release(ctx
);
3897 if (total_size
< 0) {
3898 error_setg_errno(errp
, -total_size
, "Could not get image size");
3902 /* Create the temporary image */
3903 tmp_filename
= create_tmp_file(errp
);
3904 if (!tmp_filename
) {
3908 opts
= qemu_opts_create(bdrv_qcow2
.create_opts
, NULL
, 0,
3910 qemu_opt_set_number(opts
, BLOCK_OPT_SIZE
, total_size
, &error_abort
);
3911 ret
= bdrv_create(&bdrv_qcow2
, tmp_filename
, opts
, errp
);
3912 qemu_opts_del(opts
);
3914 error_prepend(errp
, "Could not create temporary overlay '%s': ",
3919 /* Prepare options QDict for the temporary file */
3920 qdict_put_str(snapshot_options
, "file.driver", "file");
3921 qdict_put_str(snapshot_options
, "file.filename", tmp_filename
);
3922 qdict_put_str(snapshot_options
, "driver", "qcow2");
3924 bs_snapshot
= bdrv_open(NULL
, NULL
, snapshot_options
, flags
, errp
);
3925 snapshot_options
= NULL
;
3930 aio_context_acquire(ctx
);
3931 ret
= bdrv_append(bs_snapshot
, bs
, errp
);
3932 aio_context_release(ctx
);
3940 qobject_unref(snapshot_options
);
3945 * Opens a disk image (raw, qcow2, vmdk, ...)
3947 * options is a QDict of options to pass to the block drivers, or NULL for an
3948 * empty set of options. The reference to the QDict belongs to the block layer
3949 * after the call (even on failure), so if the caller intends to reuse the
3950 * dictionary, it needs to use qobject_ref() before calling bdrv_open.
3952 * If *pbs is NULL, a new BDS will be created with a pointer to it stored there.
3953 * If it is not NULL, the referenced BDS will be reused.
3955 * The reference parameter may be used to specify an existing block device which
3956 * should be opened. If specified, neither options nor a filename may be given,
3957 * nor can an existing BDS be reused (that is, *pbs has to be NULL).
3959 * The caller must always hold the main AioContext lock.
3961 static BlockDriverState
* no_coroutine_fn
3962 bdrv_open_inherit(const char *filename
, const char *reference
, QDict
*options
,
3963 int flags
, BlockDriverState
*parent
,
3964 const BdrvChildClass
*child_class
, BdrvChildRole child_role
,
3968 BlockBackend
*file
= NULL
;
3969 BlockDriverState
*bs
;
3970 BlockDriver
*drv
= NULL
;
3972 const char *drvname
;
3973 const char *backing
;
3974 Error
*local_err
= NULL
;
3975 QDict
*snapshot_options
= NULL
;
3976 int snapshot_flags
= 0;
3977 AioContext
*ctx
= qemu_get_aio_context();
3979 assert(!child_class
|| !flags
);
3980 assert(!child_class
== !parent
);
3981 GLOBAL_STATE_CODE();
3982 assert(!qemu_in_coroutine());
3984 /* TODO We'll eventually have to take a writer lock in this function */
3985 GRAPH_RDLOCK_GUARD_MAINLOOP();
3988 bool options_non_empty
= options
? qdict_size(options
) : false;
3989 qobject_unref(options
);
3991 if (filename
|| options_non_empty
) {
3992 error_setg(errp
, "Cannot reference an existing block device with "
3993 "additional options or a new filename");
3997 bs
= bdrv_lookup_bs(reference
, reference
, errp
);
4008 /* NULL means an empty set of options */
4009 if (options
== NULL
) {
4010 options
= qdict_new();
4013 /* json: syntax counts as explicit options, as if in the QDict */
4014 parse_json_protocol(options
, &filename
, &local_err
);
4019 bs
->explicit_options
= qdict_clone_shallow(options
);
4022 bool parent_is_format
;
4025 parent_is_format
= parent
->drv
->is_format
;
4028 * parent->drv is not set yet because this node is opened for
4029 * (potential) format probing. That means that @parent is going
4030 * to be a format node.
4032 parent_is_format
= true;
4035 bs
->inherits_from
= parent
;
4036 child_class
->inherit_options(child_role
, parent_is_format
,
4038 parent
->open_flags
, parent
->options
);
4041 ret
= bdrv_fill_options(&options
, filename
, &flags
, &local_err
);
4047 * Set the BDRV_O_RDWR and BDRV_O_ALLOW_RDWR flags.
4048 * Caution: getting a boolean member of @options requires care.
4049 * When @options come from -blockdev or blockdev_add, members are
4050 * typed according to the QAPI schema, but when they come from
4051 * -drive, they're all QString.
4053 if (g_strcmp0(qdict_get_try_str(options
, BDRV_OPT_READ_ONLY
), "on") &&
4054 !qdict_get_try_bool(options
, BDRV_OPT_READ_ONLY
, false)) {
4055 flags
|= (BDRV_O_RDWR
| BDRV_O_ALLOW_RDWR
);
4057 flags
&= ~BDRV_O_RDWR
;
4060 if (flags
& BDRV_O_SNAPSHOT
) {
4061 snapshot_options
= qdict_new();
4062 bdrv_temp_snapshot_options(&snapshot_flags
, snapshot_options
,
4064 /* Let bdrv_backing_options() override "read-only" */
4065 qdict_del(options
, BDRV_OPT_READ_ONLY
);
4066 bdrv_inherited_options(BDRV_CHILD_COW
, true,
4067 &flags
, options
, flags
, options
);
4070 bs
->open_flags
= flags
;
4071 bs
->options
= options
;
4072 options
= qdict_clone_shallow(options
);
4074 /* Find the right image format driver */
4075 /* See cautionary note on accessing @options above */
4076 drvname
= qdict_get_try_str(options
, "driver");
4078 drv
= bdrv_find_format(drvname
);
4080 error_setg(errp
, "Unknown driver: '%s'", drvname
);
4085 assert(drvname
|| !(flags
& BDRV_O_PROTOCOL
));
4087 /* See cautionary note on accessing @options above */
4088 backing
= qdict_get_try_str(options
, "backing");
4089 if (qobject_to(QNull
, qdict_get(options
, "backing")) != NULL
||
4090 (backing
&& *backing
== '\0'))
4093 warn_report("Use of \"backing\": \"\" is deprecated; "
4094 "use \"backing\": null instead");
4096 flags
|= BDRV_O_NO_BACKING
;
4097 qdict_del(bs
->explicit_options
, "backing");
4098 qdict_del(bs
->options
, "backing");
4099 qdict_del(options
, "backing");
4102 /* Open image file without format layer. This BlockBackend is only used for
4103 * probing, the block drivers will do their own bdrv_open_child() for the
4104 * same BDS, which is why we put the node name back into options. */
4105 if ((flags
& BDRV_O_PROTOCOL
) == 0) {
4106 BlockDriverState
*file_bs
;
4108 file_bs
= bdrv_open_child_bs(filename
, options
, "file", bs
,
4109 &child_of_bds
, BDRV_CHILD_IMAGE
,
4114 if (file_bs
!= NULL
) {
4115 /* Not requesting BLK_PERM_CONSISTENT_READ because we're only
4116 * looking at the header to guess the image format. This works even
4117 * in cases where a guest would not see a consistent state. */
4118 ctx
= bdrv_get_aio_context(file_bs
);
4119 aio_context_acquire(ctx
);
4120 file
= blk_new(ctx
, 0, BLK_PERM_ALL
);
4121 blk_insert_bs(file
, file_bs
, &local_err
);
4122 bdrv_unref(file_bs
);
4123 aio_context_release(ctx
);
4129 qdict_put_str(options
, "file", bdrv_get_node_name(file_bs
));
4133 /* Image format probing */
4136 ret
= find_image_format(file
, filename
, &drv
, &local_err
);
4141 * This option update would logically belong in bdrv_fill_options(),
4142 * but we first need to open bs->file for the probing to work, while
4143 * opening bs->file already requires the (mostly) final set of options
4144 * so that cache mode etc. can be inherited.
4146 * Adding the driver later is somewhat ugly, but it's not an option
4147 * that would ever be inherited, so it's correct. We just need to make
4148 * sure to update both bs->options (which has the full effective
4149 * options for bs) and options (which has file.* already removed).
4151 qdict_put_str(bs
->options
, "driver", drv
->format_name
);
4152 qdict_put_str(options
, "driver", drv
->format_name
);
4154 error_setg(errp
, "Must specify either driver or file");
4158 /* BDRV_O_PROTOCOL must be set iff a protocol BDS is about to be created */
4159 assert(!!(flags
& BDRV_O_PROTOCOL
) == !!drv
->bdrv_file_open
);
4160 /* file must be NULL if a protocol BDS is about to be created
4161 * (the inverse results in an error message from bdrv_open_common()) */
4162 assert(!(flags
& BDRV_O_PROTOCOL
) || !file
);
4164 /* Open the image */
4165 ret
= bdrv_open_common(bs
, file
, options
, &local_err
);
4170 /* The AioContext could have changed during bdrv_open_common() */
4171 ctx
= bdrv_get_aio_context(bs
);
4174 aio_context_acquire(ctx
);
4176 aio_context_release(ctx
);
4180 /* If there is a backing file, use it */
4181 if ((flags
& BDRV_O_NO_BACKING
) == 0) {
4182 ret
= bdrv_open_backing_file(bs
, options
, "backing", &local_err
);
4184 goto close_and_fail
;
4188 /* Remove all children options and references
4189 * from bs->options and bs->explicit_options */
4190 QLIST_FOREACH(child
, &bs
->children
, next
) {
4191 char *child_key_dot
;
4192 child_key_dot
= g_strdup_printf("%s.", child
->name
);
4193 qdict_extract_subqdict(bs
->explicit_options
, NULL
, child_key_dot
);
4194 qdict_extract_subqdict(bs
->options
, NULL
, child_key_dot
);
4195 qdict_del(bs
->explicit_options
, child
->name
);
4196 qdict_del(bs
->options
, child
->name
);
4197 g_free(child_key_dot
);
4200 /* Check if any unknown options were used */
4201 if (qdict_size(options
) != 0) {
4202 const QDictEntry
*entry
= qdict_first(options
);
4203 if (flags
& BDRV_O_PROTOCOL
) {
4204 error_setg(errp
, "Block protocol '%s' doesn't support the option "
4205 "'%s'", drv
->format_name
, entry
->key
);
4208 "Block format '%s' does not support the option '%s'",
4209 drv
->format_name
, entry
->key
);
4212 goto close_and_fail
;
4215 bdrv_parent_cb_change_media(bs
, true);
4217 qobject_unref(options
);
4220 /* For snapshot=on, create a temporary qcow2 overlay. bs points to the
4221 * temporary snapshot afterwards. */
4222 if (snapshot_flags
) {
4223 BlockDriverState
*snapshot_bs
;
4224 snapshot_bs
= bdrv_append_temp_snapshot(bs
, snapshot_flags
,
4225 snapshot_options
, &local_err
);
4226 snapshot_options
= NULL
;
4228 goto close_and_fail
;
4230 /* We are not going to return bs but the overlay on top of it
4231 * (snapshot_bs); thus, we have to drop the strong reference to bs
4232 * (which we obtained by calling bdrv_new()). bs will not be deleted,
4233 * though, because the overlay still has a reference to it. */
4234 aio_context_acquire(ctx
);
4236 aio_context_release(ctx
);
4243 aio_context_acquire(ctx
);
4245 qobject_unref(snapshot_options
);
4246 qobject_unref(bs
->explicit_options
);
4247 qobject_unref(bs
->options
);
4248 qobject_unref(options
);
4250 bs
->explicit_options
= NULL
;
4252 aio_context_release(ctx
);
4253 error_propagate(errp
, local_err
);
4257 aio_context_acquire(ctx
);
4259 aio_context_release(ctx
);
4260 qobject_unref(snapshot_options
);
4261 qobject_unref(options
);
4262 error_propagate(errp
, local_err
);
4266 /* The caller must always hold the main AioContext lock. */
4267 BlockDriverState
*bdrv_open(const char *filename
, const char *reference
,
4268 QDict
*options
, int flags
, Error
**errp
)
4270 GLOBAL_STATE_CODE();
4272 return bdrv_open_inherit(filename
, reference
, options
, flags
, NULL
,
4276 /* Return true if the NULL-terminated @list contains @str */
4277 static bool is_str_in_list(const char *str
, const char *const *list
)
4281 for (i
= 0; list
[i
] != NULL
; i
++) {
4282 if (!strcmp(str
, list
[i
])) {
4291 * Check that every option set in @bs->options is also set in
4294 * Options listed in the common_options list and in
4295 * @bs->drv->mutable_opts are skipped.
4297 * Return 0 on success, otherwise return -EINVAL and set @errp.
4299 static int bdrv_reset_options_allowed(BlockDriverState
*bs
,
4300 const QDict
*new_opts
, Error
**errp
)
4302 const QDictEntry
*e
;
4303 /* These options are common to all block drivers and are handled
4304 * in bdrv_reopen_prepare() so they can be left out of @new_opts */
4305 const char *const common_options
[] = {
4306 "node-name", "discard", "cache.direct", "cache.no-flush",
4307 "read-only", "auto-read-only", "detect-zeroes", NULL
4310 for (e
= qdict_first(bs
->options
); e
; e
= qdict_next(bs
->options
, e
)) {
4311 if (!qdict_haskey(new_opts
, e
->key
) &&
4312 !is_str_in_list(e
->key
, common_options
) &&
4313 !is_str_in_list(e
->key
, bs
->drv
->mutable_opts
)) {
4314 error_setg(errp
, "Option '%s' cannot be reset "
4315 "to its default value", e
->key
);
4324 * Returns true if @child can be reached recursively from @bs
4326 static bool GRAPH_RDLOCK
4327 bdrv_recurse_has_child(BlockDriverState
*bs
, BlockDriverState
*child
)
4335 QLIST_FOREACH(c
, &bs
->children
, next
) {
4336 if (bdrv_recurse_has_child(c
->bs
, child
)) {
4345 * Adds a BlockDriverState to a simple queue for an atomic, transactional
4346 * reopen of multiple devices.
4348 * bs_queue can either be an existing BlockReopenQueue that has had QTAILQ_INIT
4349 * already performed, or alternatively may be NULL a new BlockReopenQueue will
4350 * be created and initialized. This newly created BlockReopenQueue should be
4351 * passed back in for subsequent calls that are intended to be of the same
4354 * bs is the BlockDriverState to add to the reopen queue.
4356 * options contains the changed options for the associated bs
4357 * (the BlockReopenQueue takes ownership)
4359 * flags contains the open flags for the associated bs
4361 * returns a pointer to bs_queue, which is either the newly allocated
4362 * bs_queue, or the existing bs_queue being used.
4364 * bs is drained here and undrained by bdrv_reopen_queue_free().
4366 * To be called with bs->aio_context locked.
4368 static BlockReopenQueue
* GRAPH_RDLOCK
4369 bdrv_reopen_queue_child(BlockReopenQueue
*bs_queue
, BlockDriverState
*bs
,
4370 QDict
*options
, const BdrvChildClass
*klass
,
4371 BdrvChildRole role
, bool parent_is_format
,
4372 QDict
*parent_options
, int parent_flags
,
4377 BlockReopenQueueEntry
*bs_entry
;
4379 QDict
*old_options
, *explicit_options
, *options_copy
;
4383 GLOBAL_STATE_CODE();
4386 * Strictly speaking, draining is illegal under GRAPH_RDLOCK. We know that
4387 * we've been called with bdrv_graph_rdlock_main_loop(), though, so it's ok
4390 bdrv_drained_begin(bs
);
4392 if (bs_queue
== NULL
) {
4393 bs_queue
= g_new0(BlockReopenQueue
, 1);
4394 QTAILQ_INIT(bs_queue
);
4398 options
= qdict_new();
4401 /* Check if this BlockDriverState is already in the queue */
4402 QTAILQ_FOREACH(bs_entry
, bs_queue
, entry
) {
4403 if (bs
== bs_entry
->state
.bs
) {
4409 * Precedence of options:
4410 * 1. Explicitly passed in options (highest)
4411 * 2. Retained from explicitly set options of bs
4412 * 3. Inherited from parent node
4413 * 4. Retained from effective options of bs
4416 /* Old explicitly set values (don't overwrite by inherited value) */
4417 if (bs_entry
|| keep_old_opts
) {
4418 old_options
= qdict_clone_shallow(bs_entry
?
4419 bs_entry
->state
.explicit_options
:
4420 bs
->explicit_options
);
4421 bdrv_join_options(bs
, options
, old_options
);
4422 qobject_unref(old_options
);
4425 explicit_options
= qdict_clone_shallow(options
);
4427 /* Inherit from parent node */
4428 if (parent_options
) {
4430 klass
->inherit_options(role
, parent_is_format
, &flags
, options
,
4431 parent_flags
, parent_options
);
4433 flags
= bdrv_get_flags(bs
);
4436 if (keep_old_opts
) {
4437 /* Old values are used for options that aren't set yet */
4438 old_options
= qdict_clone_shallow(bs
->options
);
4439 bdrv_join_options(bs
, options
, old_options
);
4440 qobject_unref(old_options
);
4443 /* We have the final set of options so let's update the flags */
4444 options_copy
= qdict_clone_shallow(options
);
4445 opts
= qemu_opts_create(&bdrv_runtime_opts
, NULL
, 0, &error_abort
);
4446 qemu_opts_absorb_qdict(opts
, options_copy
, NULL
);
4447 update_flags_from_options(&flags
, opts
);
4448 qemu_opts_del(opts
);
4449 qobject_unref(options_copy
);
4451 /* bdrv_open_inherit() sets and clears some additional flags internally */
4452 flags
&= ~BDRV_O_PROTOCOL
;
4453 if (flags
& BDRV_O_RDWR
) {
4454 flags
|= BDRV_O_ALLOW_RDWR
;
4458 bs_entry
= g_new0(BlockReopenQueueEntry
, 1);
4459 QTAILQ_INSERT_TAIL(bs_queue
, bs_entry
, entry
);
4461 qobject_unref(bs_entry
->state
.options
);
4462 qobject_unref(bs_entry
->state
.explicit_options
);
4465 bs_entry
->state
.bs
= bs
;
4466 bs_entry
->state
.options
= options
;
4467 bs_entry
->state
.explicit_options
= explicit_options
;
4468 bs_entry
->state
.flags
= flags
;
4471 * If keep_old_opts is false then it means that unspecified
4472 * options must be reset to their original value. We don't allow
4473 * resetting 'backing' but we need to know if the option is
4474 * missing in order to decide if we have to return an error.
4476 if (!keep_old_opts
) {
4477 bs_entry
->state
.backing_missing
=
4478 !qdict_haskey(options
, "backing") &&
4479 !qdict_haskey(options
, "backing.driver");
4482 QLIST_FOREACH(child
, &bs
->children
, next
) {
4483 QDict
*new_child_options
= NULL
;
4484 bool child_keep_old
= keep_old_opts
;
4486 /* reopen can only change the options of block devices that were
4487 * implicitly created and inherited options. For other (referenced)
4488 * block devices, a syntax like "backing.foo" results in an error. */
4489 if (child
->bs
->inherits_from
!= bs
) {
4493 /* Check if the options contain a child reference */
4494 if (qdict_haskey(options
, child
->name
)) {
4495 const char *childref
= qdict_get_try_str(options
, child
->name
);
4497 * The current child must not be reopened if the child
4498 * reference is null or points to a different node.
4500 if (g_strcmp0(childref
, child
->bs
->node_name
)) {
4504 * If the child reference points to the current child then
4505 * reopen it with its existing set of options (note that
4506 * it can still inherit new options from the parent).
4508 child_keep_old
= true;
4510 /* Extract child options ("child-name.*") */
4511 char *child_key_dot
= g_strdup_printf("%s.", child
->name
);
4512 qdict_extract_subqdict(explicit_options
, NULL
, child_key_dot
);
4513 qdict_extract_subqdict(options
, &new_child_options
, child_key_dot
);
4514 g_free(child_key_dot
);
4517 bdrv_reopen_queue_child(bs_queue
, child
->bs
, new_child_options
,
4518 child
->klass
, child
->role
, bs
->drv
->is_format
,
4519 options
, flags
, child_keep_old
);
4525 /* To be called with bs->aio_context locked */
4526 BlockReopenQueue
*bdrv_reopen_queue(BlockReopenQueue
*bs_queue
,
4527 BlockDriverState
*bs
,
4528 QDict
*options
, bool keep_old_opts
)
4530 GLOBAL_STATE_CODE();
4531 GRAPH_RDLOCK_GUARD_MAINLOOP();
4533 return bdrv_reopen_queue_child(bs_queue
, bs
, options
, NULL
, 0, false,
4534 NULL
, 0, keep_old_opts
);
4537 void bdrv_reopen_queue_free(BlockReopenQueue
*bs_queue
)
4539 GLOBAL_STATE_CODE();
4541 BlockReopenQueueEntry
*bs_entry
, *next
;
4542 QTAILQ_FOREACH_SAFE(bs_entry
, bs_queue
, entry
, next
) {
4543 AioContext
*ctx
= bdrv_get_aio_context(bs_entry
->state
.bs
);
4545 aio_context_acquire(ctx
);
4546 bdrv_drained_end(bs_entry
->state
.bs
);
4547 aio_context_release(ctx
);
4549 qobject_unref(bs_entry
->state
.explicit_options
);
4550 qobject_unref(bs_entry
->state
.options
);
4558 * Reopen multiple BlockDriverStates atomically & transactionally.
4560 * The queue passed in (bs_queue) must have been built up previous
4561 * via bdrv_reopen_queue().
4563 * Reopens all BDS specified in the queue, with the appropriate
4564 * flags. All devices are prepared for reopen, and failure of any
4565 * device will cause all device changes to be abandoned, and intermediate
4568 * If all devices prepare successfully, then the changes are committed
4571 * All affected nodes must be drained between bdrv_reopen_queue() and
4572 * bdrv_reopen_multiple().
4574 * To be called from the main thread, with all other AioContexts unlocked.
4576 int bdrv_reopen_multiple(BlockReopenQueue
*bs_queue
, Error
**errp
)
4579 BlockReopenQueueEntry
*bs_entry
, *next
;
4581 Transaction
*tran
= tran_new();
4582 g_autoptr(GSList
) refresh_list
= NULL
;
4584 assert(qemu_get_current_aio_context() == qemu_get_aio_context());
4585 assert(bs_queue
!= NULL
);
4586 GLOBAL_STATE_CODE();
4588 QTAILQ_FOREACH(bs_entry
, bs_queue
, entry
) {
4589 ctx
= bdrv_get_aio_context(bs_entry
->state
.bs
);
4590 aio_context_acquire(ctx
);
4591 ret
= bdrv_flush(bs_entry
->state
.bs
);
4592 aio_context_release(ctx
);
4594 error_setg_errno(errp
, -ret
, "Error flushing drive");
4599 QTAILQ_FOREACH(bs_entry
, bs_queue
, entry
) {
4600 assert(bs_entry
->state
.bs
->quiesce_counter
> 0);
4601 ctx
= bdrv_get_aio_context(bs_entry
->state
.bs
);
4602 aio_context_acquire(ctx
);
4603 ret
= bdrv_reopen_prepare(&bs_entry
->state
, bs_queue
, tran
, errp
);
4604 aio_context_release(ctx
);
4608 bs_entry
->prepared
= true;
4611 QTAILQ_FOREACH(bs_entry
, bs_queue
, entry
) {
4612 BDRVReopenState
*state
= &bs_entry
->state
;
4614 refresh_list
= g_slist_prepend(refresh_list
, state
->bs
);
4615 if (state
->old_backing_bs
) {
4616 refresh_list
= g_slist_prepend(refresh_list
, state
->old_backing_bs
);
4618 if (state
->old_file_bs
) {
4619 refresh_list
= g_slist_prepend(refresh_list
, state
->old_file_bs
);
4624 * Note that file-posix driver rely on permission update done during reopen
4625 * (even if no permission changed), because it wants "new" permissions for
4626 * reconfiguring the fd and that's why it does it in raw_check_perm(), not
4627 * in raw_reopen_prepare() which is called with "old" permissions.
4629 bdrv_graph_rdlock_main_loop();
4630 ret
= bdrv_list_refresh_perms(refresh_list
, bs_queue
, tran
, errp
);
4631 bdrv_graph_rdunlock_main_loop();
4638 * If we reach this point, we have success and just need to apply the
4641 * Reverse order is used to comfort qcow2 driver: on commit it need to write
4642 * IN_USE flag to the image, to mark bitmaps in the image as invalid. But
4643 * children are usually goes after parents in reopen-queue, so go from last
4646 QTAILQ_FOREACH_REVERSE(bs_entry
, bs_queue
, entry
) {
4647 ctx
= bdrv_get_aio_context(bs_entry
->state
.bs
);
4648 aio_context_acquire(ctx
);
4649 bdrv_reopen_commit(&bs_entry
->state
);
4650 aio_context_release(ctx
);
4653 bdrv_graph_wrlock(NULL
);
4655 bdrv_graph_wrunlock();
4657 QTAILQ_FOREACH_REVERSE(bs_entry
, bs_queue
, entry
) {
4658 BlockDriverState
*bs
= bs_entry
->state
.bs
;
4660 if (bs
->drv
->bdrv_reopen_commit_post
) {
4661 ctx
= bdrv_get_aio_context(bs
);
4662 aio_context_acquire(ctx
);
4663 bs
->drv
->bdrv_reopen_commit_post(&bs_entry
->state
);
4664 aio_context_release(ctx
);
4672 bdrv_graph_wrlock(NULL
);
4674 bdrv_graph_wrunlock();
4676 QTAILQ_FOREACH_SAFE(bs_entry
, bs_queue
, entry
, next
) {
4677 if (bs_entry
->prepared
) {
4678 ctx
= bdrv_get_aio_context(bs_entry
->state
.bs
);
4679 aio_context_acquire(ctx
);
4680 bdrv_reopen_abort(&bs_entry
->state
);
4681 aio_context_release(ctx
);
4686 bdrv_reopen_queue_free(bs_queue
);
4691 int bdrv_reopen(BlockDriverState
*bs
, QDict
*opts
, bool keep_old_opts
,
4694 AioContext
*ctx
= bdrv_get_aio_context(bs
);
4695 BlockReopenQueue
*queue
;
4698 GLOBAL_STATE_CODE();
4700 queue
= bdrv_reopen_queue(NULL
, bs
, opts
, keep_old_opts
);
4702 if (ctx
!= qemu_get_aio_context()) {
4703 aio_context_release(ctx
);
4705 ret
= bdrv_reopen_multiple(queue
, errp
);
4707 if (ctx
!= qemu_get_aio_context()) {
4708 aio_context_acquire(ctx
);
4714 int bdrv_reopen_set_read_only(BlockDriverState
*bs
, bool read_only
,
4717 QDict
*opts
= qdict_new();
4719 GLOBAL_STATE_CODE();
4721 qdict_put_bool(opts
, BDRV_OPT_READ_ONLY
, read_only
);
4723 return bdrv_reopen(bs
, opts
, true, errp
);
4727 * Take a BDRVReopenState and check if the value of 'backing' in the
4728 * reopen_state->options QDict is valid or not.
4730 * If 'backing' is missing from the QDict then return 0.
4732 * If 'backing' contains the node name of the backing file of
4733 * reopen_state->bs then return 0.
4735 * If 'backing' contains a different node name (or is null) then check
4736 * whether the current backing file can be replaced with the new one.
4737 * If that's the case then reopen_state->replace_backing_bs is set to
4738 * true and reopen_state->new_backing_bs contains a pointer to the new
4739 * backing BlockDriverState (or NULL).
4741 * After calling this function, the transaction @tran may only be completed
4742 * while holding a writer lock for the graph.
4744 * Return 0 on success, otherwise return < 0 and set @errp.
4746 * The caller must hold the AioContext lock of @reopen_state->bs.
4747 * @reopen_state->bs can move to a different AioContext in this function.
4748 * Callers must make sure that their AioContext locking is still correct after
4751 static int GRAPH_UNLOCKED
4752 bdrv_reopen_parse_file_or_backing(BDRVReopenState
*reopen_state
,
4753 bool is_backing
, Transaction
*tran
,
4756 BlockDriverState
*bs
= reopen_state
->bs
;
4757 BlockDriverState
*new_child_bs
;
4758 BlockDriverState
*old_child_bs
= is_backing
? child_bs(bs
->backing
) :
4760 const char *child_name
= is_backing
? "backing" : "file";
4763 AioContext
*ctx
, *old_ctx
;
4767 GLOBAL_STATE_CODE();
4769 value
= qdict_get(reopen_state
->options
, child_name
);
4770 if (value
== NULL
) {
4774 switch (qobject_type(value
)) {
4776 assert(is_backing
); /* The 'file' option does not allow a null value */
4777 new_child_bs
= NULL
;
4780 str
= qstring_get_str(qobject_to(QString
, value
));
4781 new_child_bs
= bdrv_lookup_bs(NULL
, str
, errp
);
4782 if (new_child_bs
== NULL
) {
4786 bdrv_graph_rdlock_main_loop();
4787 has_child
= bdrv_recurse_has_child(new_child_bs
, bs
);
4788 bdrv_graph_rdunlock_main_loop();
4791 error_setg(errp
, "Making '%s' a %s child of '%s' would create a "
4792 "cycle", str
, child_name
, bs
->node_name
);
4798 * The options QDict has been flattened, so 'backing' and 'file'
4799 * do not allow any other data type here.
4801 g_assert_not_reached();
4804 if (old_child_bs
== new_child_bs
) {
4809 if (bdrv_skip_implicit_filters(old_child_bs
) == new_child_bs
) {
4813 if (old_child_bs
->implicit
) {
4814 error_setg(errp
, "Cannot replace implicit %s child of %s",
4815 child_name
, bs
->node_name
);
4820 if (bs
->drv
->is_filter
&& !old_child_bs
) {
4822 * Filters always have a file or a backing child, so we are trying to
4823 * change wrong child
4825 error_setg(errp
, "'%s' is a %s filter node that does not support a "
4826 "%s child", bs
->node_name
, bs
->drv
->format_name
, child_name
);
4831 reopen_state
->old_backing_bs
= old_child_bs
;
4833 reopen_state
->old_file_bs
= old_child_bs
;
4837 bdrv_ref(old_child_bs
);
4838 bdrv_drained_begin(old_child_bs
);
4841 old_ctx
= bdrv_get_aio_context(bs
);
4842 ctx
= bdrv_get_aio_context(new_child_bs
);
4843 if (old_ctx
!= ctx
) {
4844 aio_context_release(old_ctx
);
4845 aio_context_acquire(ctx
);
4848 bdrv_graph_wrlock(new_child_bs
);
4850 ret
= bdrv_set_file_or_backing_noperm(bs
, new_child_bs
, is_backing
,
4853 bdrv_graph_wrunlock();
4855 if (old_ctx
!= ctx
) {
4856 aio_context_release(ctx
);
4857 aio_context_acquire(old_ctx
);
4861 bdrv_drained_end(old_child_bs
);
4862 bdrv_unref(old_child_bs
);
4869 * Prepares a BlockDriverState for reopen. All changes are staged in the
4870 * 'opaque' field of the BDRVReopenState, which is used and allocated by
4871 * the block driver layer .bdrv_reopen_prepare()
4873 * bs is the BlockDriverState to reopen
4874 * flags are the new open flags
4875 * queue is the reopen queue
4877 * Returns 0 on success, non-zero on error. On error errp will be set
4880 * On failure, bdrv_reopen_abort() will be called to clean up any data.
4881 * It is the responsibility of the caller to then call the abort() or
4882 * commit() for any other BDS that have been left in a prepare() state
4884 * The caller must hold the AioContext lock of @reopen_state->bs.
4886 * After calling this function, the transaction @change_child_tran may only be
4887 * completed while holding a writer lock for the graph.
4889 static int GRAPH_UNLOCKED
4890 bdrv_reopen_prepare(BDRVReopenState
*reopen_state
, BlockReopenQueue
*queue
,
4891 Transaction
*change_child_tran
, Error
**errp
)
4895 Error
*local_err
= NULL
;
4898 QDict
*orig_reopen_opts
;
4899 char *discard
= NULL
;
4901 bool drv_prepared
= false;
4903 assert(reopen_state
!= NULL
);
4904 assert(reopen_state
->bs
->drv
!= NULL
);
4905 GLOBAL_STATE_CODE();
4906 drv
= reopen_state
->bs
->drv
;
4908 /* This function and each driver's bdrv_reopen_prepare() remove
4909 * entries from reopen_state->options as they are processed, so
4910 * we need to make a copy of the original QDict. */
4911 orig_reopen_opts
= qdict_clone_shallow(reopen_state
->options
);
4913 /* Process generic block layer options */
4914 opts
= qemu_opts_create(&bdrv_runtime_opts
, NULL
, 0, &error_abort
);
4915 if (!qemu_opts_absorb_qdict(opts
, reopen_state
->options
, errp
)) {
4920 /* This was already called in bdrv_reopen_queue_child() so the flags
4921 * are up-to-date. This time we simply want to remove the options from
4922 * QemuOpts in order to indicate that they have been processed. */
4923 old_flags
= reopen_state
->flags
;
4924 update_flags_from_options(&reopen_state
->flags
, opts
);
4925 assert(old_flags
== reopen_state
->flags
);
4927 discard
= qemu_opt_get_del(opts
, BDRV_OPT_DISCARD
);
4928 if (discard
!= NULL
) {
4929 if (bdrv_parse_discard_flags(discard
, &reopen_state
->flags
) != 0) {
4930 error_setg(errp
, "Invalid discard option");
4936 reopen_state
->detect_zeroes
=
4937 bdrv_parse_detect_zeroes(opts
, reopen_state
->flags
, &local_err
);
4939 error_propagate(errp
, local_err
);
4944 /* All other options (including node-name and driver) must be unchanged.
4945 * Put them back into the QDict, so that they are checked at the end
4946 * of this function. */
4947 qemu_opts_to_qdict(opts
, reopen_state
->options
);
4949 /* If we are to stay read-only, do not allow permission change
4950 * to r/w. Attempting to set to r/w may fail if either BDRV_O_ALLOW_RDWR is
4951 * not set, or if the BDS still has copy_on_read enabled */
4952 read_only
= !(reopen_state
->flags
& BDRV_O_RDWR
);
4953 ret
= bdrv_can_set_read_only(reopen_state
->bs
, read_only
, true, &local_err
);
4955 error_propagate(errp
, local_err
);
4959 if (drv
->bdrv_reopen_prepare
) {
4961 * If a driver-specific option is missing, it means that we
4962 * should reset it to its default value.
4963 * But not all options allow that, so we need to check it first.
4965 ret
= bdrv_reset_options_allowed(reopen_state
->bs
,
4966 reopen_state
->options
, errp
);
4971 ret
= drv
->bdrv_reopen_prepare(reopen_state
, queue
, &local_err
);
4973 if (local_err
!= NULL
) {
4974 error_propagate(errp
, local_err
);
4976 bdrv_graph_rdlock_main_loop();
4977 bdrv_refresh_filename(reopen_state
->bs
);
4978 bdrv_graph_rdunlock_main_loop();
4979 error_setg(errp
, "failed while preparing to reopen image '%s'",
4980 reopen_state
->bs
->filename
);
4985 /* It is currently mandatory to have a bdrv_reopen_prepare()
4986 * handler for each supported drv. */
4987 error_setg(errp
, "Block format '%s' used by node '%s' "
4988 "does not support reopening files", drv
->format_name
,
4989 bdrv_get_device_or_node_name(reopen_state
->bs
));
4994 drv_prepared
= true;
4997 * We must provide the 'backing' option if the BDS has a backing
4998 * file or if the image file has a backing file name as part of
4999 * its metadata. Otherwise the 'backing' option can be omitted.
5001 if (drv
->supports_backing
&& reopen_state
->backing_missing
&&
5002 (reopen_state
->bs
->backing
|| reopen_state
->bs
->backing_file
[0])) {
5003 error_setg(errp
, "backing is missing for '%s'",
5004 reopen_state
->bs
->node_name
);
5010 * Allow changing the 'backing' option. The new value can be
5011 * either a reference to an existing node (using its node name)
5012 * or NULL to simply detach the current backing file.
5014 ret
= bdrv_reopen_parse_file_or_backing(reopen_state
, true,
5015 change_child_tran
, errp
);
5019 qdict_del(reopen_state
->options
, "backing");
5021 /* Allow changing the 'file' option. In this case NULL is not allowed */
5022 ret
= bdrv_reopen_parse_file_or_backing(reopen_state
, false,
5023 change_child_tran
, errp
);
5027 qdict_del(reopen_state
->options
, "file");
5029 /* Options that are not handled are only okay if they are unchanged
5030 * compared to the old state. It is expected that some options are only
5031 * used for the initial open, but not reopen (e.g. filename) */
5032 if (qdict_size(reopen_state
->options
)) {
5033 const QDictEntry
*entry
= qdict_first(reopen_state
->options
);
5035 GRAPH_RDLOCK_GUARD_MAINLOOP();
5038 QObject
*new = entry
->value
;
5039 QObject
*old
= qdict_get(reopen_state
->bs
->options
, entry
->key
);
5041 /* Allow child references (child_name=node_name) as long as they
5042 * point to the current child (i.e. everything stays the same). */
5043 if (qobject_type(new) == QTYPE_QSTRING
) {
5045 QLIST_FOREACH(child
, &reopen_state
->bs
->children
, next
) {
5046 if (!strcmp(child
->name
, entry
->key
)) {
5052 if (!strcmp(child
->bs
->node_name
,
5053 qstring_get_str(qobject_to(QString
, new)))) {
5054 continue; /* Found child with this name, skip option */
5060 * TODO: When using -drive to specify blockdev options, all values
5061 * will be strings; however, when using -blockdev, blockdev-add or
5062 * filenames using the json:{} pseudo-protocol, they will be
5064 * In contrast, reopening options are (currently) always strings
5065 * (because you can only specify them through qemu-io; all other
5066 * callers do not specify any options).
5067 * Therefore, when using anything other than -drive to create a BDS,
5068 * this cannot detect non-string options as unchanged, because
5069 * qobject_is_equal() always returns false for objects of different
5070 * type. In the future, this should be remedied by correctly typing
5071 * all options. For now, this is not too big of an issue because
5072 * the user can simply omit options which cannot be changed anyway,
5073 * so they will stay unchanged.
5075 if (!qobject_is_equal(new, old
)) {
5076 error_setg(errp
, "Cannot change the option '%s'", entry
->key
);
5080 } while ((entry
= qdict_next(reopen_state
->options
, entry
)));
5085 /* Restore the original reopen_state->options QDict */
5086 qobject_unref(reopen_state
->options
);
5087 reopen_state
->options
= qobject_ref(orig_reopen_opts
);
5090 if (ret
< 0 && drv_prepared
) {
5091 /* drv->bdrv_reopen_prepare() has succeeded, so we need to
5092 * call drv->bdrv_reopen_abort() before signaling an error
5093 * (bdrv_reopen_multiple() will not call bdrv_reopen_abort()
5094 * when the respective bdrv_reopen_prepare() has failed) */
5095 if (drv
->bdrv_reopen_abort
) {
5096 drv
->bdrv_reopen_abort(reopen_state
);
5099 qemu_opts_del(opts
);
5100 qobject_unref(orig_reopen_opts
);
5106 * Takes the staged changes for the reopen from bdrv_reopen_prepare(), and
5107 * makes them final by swapping the staging BlockDriverState contents into
5108 * the active BlockDriverState contents.
5110 static void GRAPH_UNLOCKED
bdrv_reopen_commit(BDRVReopenState
*reopen_state
)
5113 BlockDriverState
*bs
;
5116 assert(reopen_state
!= NULL
);
5117 bs
= reopen_state
->bs
;
5119 assert(drv
!= NULL
);
5120 GLOBAL_STATE_CODE();
5122 /* If there are any driver level actions to take */
5123 if (drv
->bdrv_reopen_commit
) {
5124 drv
->bdrv_reopen_commit(reopen_state
);
5127 GRAPH_RDLOCK_GUARD_MAINLOOP();
5129 /* set BDS specific flags now */
5130 qobject_unref(bs
->explicit_options
);
5131 qobject_unref(bs
->options
);
5132 qobject_ref(reopen_state
->explicit_options
);
5133 qobject_ref(reopen_state
->options
);
5135 bs
->explicit_options
= reopen_state
->explicit_options
;
5136 bs
->options
= reopen_state
->options
;
5137 bs
->open_flags
= reopen_state
->flags
;
5138 bs
->detect_zeroes
= reopen_state
->detect_zeroes
;
5140 /* Remove child references from bs->options and bs->explicit_options.
5141 * Child options were already removed in bdrv_reopen_queue_child() */
5142 QLIST_FOREACH(child
, &bs
->children
, next
) {
5143 qdict_del(bs
->explicit_options
, child
->name
);
5144 qdict_del(bs
->options
, child
->name
);
5146 /* backing is probably removed, so it's not handled by previous loop */
5147 qdict_del(bs
->explicit_options
, "backing");
5148 qdict_del(bs
->options
, "backing");
5150 bdrv_refresh_limits(bs
, NULL
, NULL
);
5151 bdrv_refresh_total_sectors(bs
, bs
->total_sectors
);
5155 * Abort the reopen, and delete and free the staged changes in
5158 static void GRAPH_UNLOCKED
bdrv_reopen_abort(BDRVReopenState
*reopen_state
)
5162 assert(reopen_state
!= NULL
);
5163 drv
= reopen_state
->bs
->drv
;
5164 assert(drv
!= NULL
);
5165 GLOBAL_STATE_CODE();
5167 if (drv
->bdrv_reopen_abort
) {
5168 drv
->bdrv_reopen_abort(reopen_state
);
5173 static void bdrv_close(BlockDriverState
*bs
)
5175 BdrvAioNotifier
*ban
, *ban_next
;
5176 BdrvChild
*child
, *next
;
5178 GLOBAL_STATE_CODE();
5179 assert(!bs
->refcnt
);
5181 bdrv_drained_begin(bs
); /* complete I/O */
5183 bdrv_drain(bs
); /* in case flush left pending I/O */
5186 if (bs
->drv
->bdrv_close
) {
5187 /* Must unfreeze all children, so bdrv_unref_child() works */
5188 bs
->drv
->bdrv_close(bs
);
5193 bdrv_graph_wrlock(NULL
);
5194 QLIST_FOREACH_SAFE(child
, &bs
->children
, next
, next
) {
5195 bdrv_unref_child(bs
, child
);
5197 bdrv_graph_wrunlock();
5199 assert(!bs
->backing
);
5203 qatomic_set(&bs
->copy_on_read
, 0);
5204 bs
->backing_file
[0] = '\0';
5205 bs
->backing_format
[0] = '\0';
5206 bs
->total_sectors
= 0;
5207 bs
->encrypted
= false;
5209 qobject_unref(bs
->options
);
5210 qobject_unref(bs
->explicit_options
);
5212 bs
->explicit_options
= NULL
;
5213 qobject_unref(bs
->full_open_options
);
5214 bs
->full_open_options
= NULL
;
5215 g_free(bs
->block_status_cache
);
5216 bs
->block_status_cache
= NULL
;
5218 bdrv_release_named_dirty_bitmaps(bs
);
5219 assert(QLIST_EMPTY(&bs
->dirty_bitmaps
));
5221 QLIST_FOREACH_SAFE(ban
, &bs
->aio_notifiers
, list
, ban_next
) {
5224 QLIST_INIT(&bs
->aio_notifiers
);
5225 bdrv_drained_end(bs
);
5228 * If we're still inside some bdrv_drain_all_begin()/end() sections, end
5229 * them now since this BDS won't exist anymore when bdrv_drain_all_end()
5232 if (bs
->quiesce_counter
) {
5233 bdrv_drain_all_end_quiesce(bs
);
5237 void bdrv_close_all(void)
5239 GLOBAL_STATE_CODE();
5240 assert(job_next(NULL
) == NULL
);
5242 /* Drop references from requests still in flight, such as canceled block
5243 * jobs whose AIO context has not been polled yet */
5246 blk_remove_all_bs();
5247 blockdev_close_all_bdrv_states();
5249 assert(QTAILQ_EMPTY(&all_bdrv_states
));
5252 static bool GRAPH_RDLOCK
should_update_child(BdrvChild
*c
, BlockDriverState
*to
)
5258 if (c
->klass
->stay_at_node
) {
5262 /* If the child @c belongs to the BDS @to, replacing the current
5263 * c->bs by @to would mean to create a loop.
5265 * Such a case occurs when appending a BDS to a backing chain.
5266 * For instance, imagine the following chain:
5268 * guest device -> node A -> further backing chain...
5270 * Now we create a new BDS B which we want to put on top of this
5271 * chain, so we first attach A as its backing node:
5276 * guest device -> node A -> further backing chain...
5278 * Finally we want to replace A by B. When doing that, we want to
5279 * replace all pointers to A by pointers to B -- except for the
5280 * pointer from B because (1) that would create a loop, and (2)
5281 * that pointer should simply stay intact:
5283 * guest device -> node B
5286 * node A -> further backing chain...
5288 * In general, when replacing a node A (c->bs) by a node B (@to),
5289 * if A is a child of B, that means we cannot replace A by B there
5290 * because that would create a loop. Silently detaching A from B
5291 * is also not really an option. So overall just leaving A in
5292 * place there is the most sensible choice.
5294 * We would also create a loop in any cases where @c is only
5295 * indirectly referenced by @to. Prevent this by returning false
5296 * if @c is found (by breadth-first search) anywhere in the whole
5301 found
= g_hash_table_new(NULL
, NULL
);
5302 g_hash_table_add(found
, to
);
5303 queue
= g_queue_new();
5304 g_queue_push_tail(queue
, to
);
5306 while (!g_queue_is_empty(queue
)) {
5307 BlockDriverState
*v
= g_queue_pop_head(queue
);
5310 QLIST_FOREACH(c2
, &v
->children
, next
) {
5316 if (g_hash_table_contains(found
, c2
->bs
)) {
5320 g_queue_push_tail(queue
, c2
->bs
);
5321 g_hash_table_add(found
, c2
->bs
);
5325 g_queue_free(queue
);
5326 g_hash_table_destroy(found
);
5331 static void bdrv_remove_child_commit(void *opaque
)
5333 GLOBAL_STATE_CODE();
5334 bdrv_child_free(opaque
);
5337 static TransactionActionDrv bdrv_remove_child_drv
= {
5338 .commit
= bdrv_remove_child_commit
,
5342 * Function doesn't update permissions, caller is responsible for this.
5344 * @child->bs (if non-NULL) must be drained.
5346 * After calling this function, the transaction @tran may only be completed
5347 * while holding a writer lock for the graph.
5349 static void GRAPH_WRLOCK
bdrv_remove_child(BdrvChild
*child
, Transaction
*tran
)
5356 assert(child
->quiesced_parent
);
5357 bdrv_replace_child_tran(child
, NULL
, tran
);
5360 tran_add(tran
, &bdrv_remove_child_drv
, child
);
5364 * Both @from and @to (if non-NULL) must be drained. @to must be kept drained
5365 * until the transaction is completed.
5367 * After calling this function, the transaction @tran may only be completed
5368 * while holding a writer lock for the graph.
5370 static int GRAPH_WRLOCK
5371 bdrv_replace_node_noperm(BlockDriverState
*from
,
5372 BlockDriverState
*to
,
5373 bool auto_skip
, Transaction
*tran
,
5376 BdrvChild
*c
, *next
;
5378 GLOBAL_STATE_CODE();
5380 assert(from
->quiesce_counter
);
5381 assert(to
->quiesce_counter
);
5383 QLIST_FOREACH_SAFE(c
, &from
->parents
, next_parent
, next
) {
5384 assert(c
->bs
== from
);
5385 if (!should_update_child(c
, to
)) {
5389 error_setg(errp
, "Should not change '%s' link to '%s'",
5390 c
->name
, from
->node_name
);
5394 error_setg(errp
, "Cannot change '%s' link to '%s'",
5395 c
->name
, from
->node_name
);
5398 bdrv_replace_child_tran(c
, to
, tran
);
5405 * With auto_skip=true bdrv_replace_node_common skips updating from parents
5406 * if it creates a parent-child relation loop or if parent is block-job.
5408 * With auto_skip=false the error is returned if from has a parent which should
5411 * With @detach_subchain=true @to must be in a backing chain of @from. In this
5412 * case backing link of the cow-parent of @to is removed.
5414 static int bdrv_replace_node_common(BlockDriverState
*from
,
5415 BlockDriverState
*to
,
5416 bool auto_skip
, bool detach_subchain
,
5419 Transaction
*tran
= tran_new();
5420 g_autoptr(GSList
) refresh_list
= NULL
;
5421 BlockDriverState
*to_cow_parent
= NULL
;
5424 GLOBAL_STATE_CODE();
5426 if (detach_subchain
) {
5427 assert(bdrv_chain_contains(from
, to
));
5429 for (to_cow_parent
= from
;
5430 bdrv_filter_or_cow_bs(to_cow_parent
) != to
;
5431 to_cow_parent
= bdrv_filter_or_cow_bs(to_cow_parent
))
5437 /* Make sure that @from doesn't go away until we have successfully attached
5438 * all of its parents to @to. */
5441 assert(qemu_get_current_aio_context() == qemu_get_aio_context());
5442 assert(bdrv_get_aio_context(from
) == bdrv_get_aio_context(to
));
5443 bdrv_drained_begin(from
);
5444 bdrv_drained_begin(to
);
5446 bdrv_graph_wrlock(to
);
5449 * Do the replacement without permission update.
5450 * Replacement may influence the permissions, we should calculate new
5451 * permissions based on new graph. If we fail, we'll roll-back the
5454 ret
= bdrv_replace_node_noperm(from
, to
, auto_skip
, tran
, errp
);
5459 if (detach_subchain
) {
5460 /* to_cow_parent is already drained because from is drained */
5461 bdrv_remove_child(bdrv_filter_or_cow_child(to_cow_parent
), tran
);
5464 refresh_list
= g_slist_prepend(refresh_list
, to
);
5465 refresh_list
= g_slist_prepend(refresh_list
, from
);
5467 ret
= bdrv_list_refresh_perms(refresh_list
, NULL
, tran
, errp
);
5475 tran_finalize(tran
, ret
);
5476 bdrv_graph_wrunlock();
5478 bdrv_drained_end(to
);
5479 bdrv_drained_end(from
);
5485 int bdrv_replace_node(BlockDriverState
*from
, BlockDriverState
*to
,
5488 GLOBAL_STATE_CODE();
5490 return bdrv_replace_node_common(from
, to
, true, false, errp
);
5493 int bdrv_drop_filter(BlockDriverState
*bs
, Error
**errp
)
5495 GLOBAL_STATE_CODE();
5497 return bdrv_replace_node_common(bs
, bdrv_filter_or_cow_bs(bs
), true, true,
5502 * Add new bs contents at the top of an image chain while the chain is
5503 * live, while keeping required fields on the top layer.
5505 * This will modify the BlockDriverState fields, and swap contents
5506 * between bs_new and bs_top. Both bs_new and bs_top are modified.
5508 * bs_new must not be attached to a BlockBackend and must not have backing
5511 * This function does not create any image files.
5513 * The caller must hold the AioContext lock for @bs_top.
5515 int bdrv_append(BlockDriverState
*bs_new
, BlockDriverState
*bs_top
,
5520 Transaction
*tran
= tran_new();
5521 AioContext
*old_context
, *new_context
= NULL
;
5523 GLOBAL_STATE_CODE();
5525 assert(!bs_new
->backing
);
5527 old_context
= bdrv_get_aio_context(bs_top
);
5528 bdrv_drained_begin(bs_top
);
5531 * bdrv_drained_begin() requires that only the AioContext of the drained
5532 * node is locked, and at this point it can still differ from the AioContext
5535 new_context
= bdrv_get_aio_context(bs_new
);
5536 aio_context_release(old_context
);
5537 aio_context_acquire(new_context
);
5538 bdrv_drained_begin(bs_new
);
5539 aio_context_release(new_context
);
5540 aio_context_acquire(old_context
);
5543 bdrv_graph_wrlock(bs_top
);
5545 child
= bdrv_attach_child_noperm(bs_new
, bs_top
, "backing",
5546 &child_of_bds
, bdrv_backing_role(bs_new
),
5554 * bdrv_attach_child_noperm could change the AioContext of bs_top and
5555 * bs_new, but at least they are in the same AioContext now. This is the
5556 * AioContext that we need to lock for the rest of the function.
5558 new_context
= bdrv_get_aio_context(bs_top
);
5560 if (old_context
!= new_context
) {
5561 aio_context_release(old_context
);
5562 aio_context_acquire(new_context
);
5565 ret
= bdrv_replace_node_noperm(bs_top
, bs_new
, true, tran
, errp
);
5570 ret
= bdrv_refresh_perms(bs_new
, tran
, errp
);
5572 tran_finalize(tran
, ret
);
5574 bdrv_refresh_limits(bs_top
, NULL
, NULL
);
5575 bdrv_graph_wrunlock();
5577 bdrv_drained_end(bs_top
);
5578 bdrv_drained_end(bs_new
);
5580 if (new_context
&& old_context
!= new_context
) {
5581 aio_context_release(new_context
);
5582 aio_context_acquire(old_context
);
5588 /* Not for empty child */
5589 int bdrv_replace_child_bs(BdrvChild
*child
, BlockDriverState
*new_bs
,
5593 Transaction
*tran
= tran_new();
5594 g_autoptr(GSList
) refresh_list
= NULL
;
5595 BlockDriverState
*old_bs
= child
->bs
;
5597 GLOBAL_STATE_CODE();
5600 bdrv_drained_begin(old_bs
);
5601 bdrv_drained_begin(new_bs
);
5602 bdrv_graph_wrlock(new_bs
);
5604 bdrv_replace_child_tran(child
, new_bs
, tran
);
5606 refresh_list
= g_slist_prepend(refresh_list
, old_bs
);
5607 refresh_list
= g_slist_prepend(refresh_list
, new_bs
);
5609 ret
= bdrv_list_refresh_perms(refresh_list
, NULL
, tran
, errp
);
5611 tran_finalize(tran
, ret
);
5613 bdrv_graph_wrunlock();
5614 bdrv_drained_end(old_bs
);
5615 bdrv_drained_end(new_bs
);
5621 static void bdrv_delete(BlockDriverState
*bs
)
5623 assert(bdrv_op_blocker_is_empty(bs
));
5624 assert(!bs
->refcnt
);
5625 GLOBAL_STATE_CODE();
5627 /* remove from list, if necessary */
5628 if (bs
->node_name
[0] != '\0') {
5629 QTAILQ_REMOVE(&graph_bdrv_states
, bs
, node_list
);
5631 QTAILQ_REMOVE(&all_bdrv_states
, bs
, bs_list
);
5635 qemu_mutex_destroy(&bs
->reqs_lock
);
5642 * Replace @bs by newly created block node.
5644 * @options is a QDict of options to pass to the block drivers, or NULL for an
5645 * empty set of options. The reference to the QDict belongs to the block layer
5646 * after the call (even on failure), so if the caller intends to reuse the
5647 * dictionary, it needs to use qobject_ref() before calling bdrv_open.
5649 * The caller holds the AioContext lock for @bs. It must make sure that @bs
5650 * stays in the same AioContext, i.e. @options must not refer to nodes in a
5651 * different AioContext.
5653 BlockDriverState
*bdrv_insert_node(BlockDriverState
*bs
, QDict
*options
,
5654 int flags
, Error
**errp
)
5658 AioContext
*ctx
= bdrv_get_aio_context(bs
);
5659 BlockDriverState
*new_node_bs
= NULL
;
5660 const char *drvname
, *node_name
;
5663 drvname
= qdict_get_try_str(options
, "driver");
5665 error_setg(errp
, "driver is not specified");
5669 drv
= bdrv_find_format(drvname
);
5671 error_setg(errp
, "Unknown driver: '%s'", drvname
);
5675 node_name
= qdict_get_try_str(options
, "node-name");
5677 GLOBAL_STATE_CODE();
5679 aio_context_release(ctx
);
5680 aio_context_acquire(qemu_get_aio_context());
5681 new_node_bs
= bdrv_new_open_driver_opts(drv
, node_name
, options
, flags
,
5683 aio_context_release(qemu_get_aio_context());
5684 aio_context_acquire(ctx
);
5685 assert(bdrv_get_aio_context(bs
) == ctx
);
5687 options
= NULL
; /* bdrv_new_open_driver() eats options */
5689 error_prepend(errp
, "Could not create node: ");
5693 bdrv_drained_begin(bs
);
5694 ret
= bdrv_replace_node(bs
, new_node_bs
, errp
);
5695 bdrv_drained_end(bs
);
5698 error_prepend(errp
, "Could not replace node: ");
5705 qobject_unref(options
);
5706 bdrv_unref(new_node_bs
);
5711 * Run consistency checks on an image
5713 * Returns 0 if the check could be completed (it doesn't mean that the image is
5714 * free of errors) or -errno when an internal error occurred. The results of the
5715 * check are stored in res.
5717 int coroutine_fn
bdrv_co_check(BlockDriverState
*bs
,
5718 BdrvCheckResult
*res
, BdrvCheckMode fix
)
5721 assert_bdrv_graph_readable();
5722 if (bs
->drv
== NULL
) {
5725 if (bs
->drv
->bdrv_co_check
== NULL
) {
5729 memset(res
, 0, sizeof(*res
));
5730 return bs
->drv
->bdrv_co_check(bs
, res
, fix
);
5736 * -EINVAL - backing format specified, but no file
5737 * -ENOSPC - can't update the backing file because no space is left in the
5739 * -ENOTSUP - format driver doesn't support changing the backing file
5741 int bdrv_change_backing_file(BlockDriverState
*bs
, const char *backing_file
,
5742 const char *backing_fmt
, bool require
)
5744 BlockDriver
*drv
= bs
->drv
;
5747 GLOBAL_STATE_CODE();
5753 /* Backing file format doesn't make sense without a backing file */
5754 if (backing_fmt
&& !backing_file
) {
5758 if (require
&& backing_file
&& !backing_fmt
) {
5762 if (drv
->bdrv_change_backing_file
!= NULL
) {
5763 ret
= drv
->bdrv_change_backing_file(bs
, backing_file
, backing_fmt
);
5769 pstrcpy(bs
->backing_file
, sizeof(bs
->backing_file
), backing_file
?: "");
5770 pstrcpy(bs
->backing_format
, sizeof(bs
->backing_format
), backing_fmt
?: "");
5771 pstrcpy(bs
->auto_backing_file
, sizeof(bs
->auto_backing_file
),
5772 backing_file
?: "");
5778 * Finds the first non-filter node above bs in the chain between
5779 * active and bs. The returned node is either an immediate parent of
5780 * bs, or there are only filter nodes between the two.
5782 * Returns NULL if bs is not found in active's image chain,
5783 * or if active == bs.
5785 * Returns the bottommost base image if bs == NULL.
5787 BlockDriverState
*bdrv_find_overlay(BlockDriverState
*active
,
5788 BlockDriverState
*bs
)
5791 GLOBAL_STATE_CODE();
5793 bs
= bdrv_skip_filters(bs
);
5794 active
= bdrv_skip_filters(active
);
5797 BlockDriverState
*next
= bdrv_backing_chain_next(active
);
5807 /* Given a BDS, searches for the base layer. */
5808 BlockDriverState
*bdrv_find_base(BlockDriverState
*bs
)
5810 GLOBAL_STATE_CODE();
5812 return bdrv_find_overlay(bs
, NULL
);
5816 * Return true if at least one of the COW (backing) and filter links
5817 * between @bs and @base is frozen. @errp is set if that's the case.
5818 * @base must be reachable from @bs, or NULL.
5820 bool bdrv_is_backing_chain_frozen(BlockDriverState
*bs
, BlockDriverState
*base
,
5823 BlockDriverState
*i
;
5826 GLOBAL_STATE_CODE();
5828 for (i
= bs
; i
!= base
; i
= child_bs(child
)) {
5829 child
= bdrv_filter_or_cow_child(i
);
5831 if (child
&& child
->frozen
) {
5832 error_setg(errp
, "Cannot change '%s' link from '%s' to '%s'",
5833 child
->name
, i
->node_name
, child
->bs
->node_name
);
5842 * Freeze all COW (backing) and filter links between @bs and @base.
5843 * If any of the links is already frozen the operation is aborted and
5844 * none of the links are modified.
5845 * @base must be reachable from @bs, or NULL.
5846 * Returns 0 on success. On failure returns < 0 and sets @errp.
5848 int bdrv_freeze_backing_chain(BlockDriverState
*bs
, BlockDriverState
*base
,
5851 BlockDriverState
*i
;
5854 GLOBAL_STATE_CODE();
5856 if (bdrv_is_backing_chain_frozen(bs
, base
, errp
)) {
5860 for (i
= bs
; i
!= base
; i
= child_bs(child
)) {
5861 child
= bdrv_filter_or_cow_child(i
);
5862 if (child
&& child
->bs
->never_freeze
) {
5863 error_setg(errp
, "Cannot freeze '%s' link to '%s'",
5864 child
->name
, child
->bs
->node_name
);
5869 for (i
= bs
; i
!= base
; i
= child_bs(child
)) {
5870 child
= bdrv_filter_or_cow_child(i
);
5872 child
->frozen
= true;
5880 * Unfreeze all COW (backing) and filter links between @bs and @base.
5881 * The caller must ensure that all links are frozen before using this
5883 * @base must be reachable from @bs, or NULL.
5885 void bdrv_unfreeze_backing_chain(BlockDriverState
*bs
, BlockDriverState
*base
)
5887 BlockDriverState
*i
;
5890 GLOBAL_STATE_CODE();
5892 for (i
= bs
; i
!= base
; i
= child_bs(child
)) {
5893 child
= bdrv_filter_or_cow_child(i
);
5895 assert(child
->frozen
);
5896 child
->frozen
= false;
5902 * Drops images above 'base' up to and including 'top', and sets the image
5903 * above 'top' to have base as its backing file.
5905 * Requires that the overlay to 'top' is opened r/w, so that the backing file
5906 * information in 'bs' can be properly updated.
5908 * E.g., this will convert the following chain:
5909 * bottom <- base <- intermediate <- top <- active
5913 * bottom <- base <- active
5915 * It is allowed for bottom==base, in which case it converts:
5917 * base <- intermediate <- top <- active
5923 * If backing_file_str is non-NULL, it will be used when modifying top's
5924 * overlay image metadata.
5927 * if active == top, that is considered an error
5930 int bdrv_drop_intermediate(BlockDriverState
*top
, BlockDriverState
*base
,
5931 const char *backing_file_str
)
5933 BlockDriverState
*explicit_top
= top
;
5934 bool update_inherits_from
;
5936 Error
*local_err
= NULL
;
5938 g_autoptr(GSList
) updated_children
= NULL
;
5941 GLOBAL_STATE_CODE();
5944 bdrv_drained_begin(base
);
5945 bdrv_graph_rdlock_main_loop();
5947 if (!top
->drv
|| !base
->drv
) {
5951 /* Make sure that base is in the backing chain of top */
5952 if (!bdrv_chain_contains(top
, base
)) {
5956 /* If 'base' recursively inherits from 'top' then we should set
5957 * base->inherits_from to top->inherits_from after 'top' and all
5958 * other intermediate nodes have been dropped.
5959 * If 'top' is an implicit node (e.g. "commit_top") we should skip
5960 * it because no one inherits from it. We use explicit_top for that. */
5961 explicit_top
= bdrv_skip_implicit_filters(explicit_top
);
5962 update_inherits_from
= bdrv_inherits_from_recursive(base
, explicit_top
);
5964 /* success - we can delete the intermediate states, and link top->base */
5965 if (!backing_file_str
) {
5966 bdrv_refresh_filename(base
);
5967 backing_file_str
= base
->filename
;
5970 QLIST_FOREACH(c
, &top
->parents
, next_parent
) {
5971 updated_children
= g_slist_prepend(updated_children
, c
);
5975 * It seems correct to pass detach_subchain=true here, but it triggers
5976 * one more yet not fixed bug, when due to nested aio_poll loop we switch to
5977 * another drained section, which modify the graph (for example, removing
5978 * the child, which we keep in updated_children list). So, it's a TODO.
5980 * Note, bug triggered if pass detach_subchain=true here and run
5981 * test-bdrv-drain. test_drop_intermediate_poll() test-case will crash.
5984 bdrv_replace_node_common(top
, base
, false, false, &local_err
);
5986 error_report_err(local_err
);
5990 for (p
= updated_children
; p
; p
= p
->next
) {
5993 if (c
->klass
->update_filename
) {
5994 ret
= c
->klass
->update_filename(c
, base
, backing_file_str
,
5998 * TODO: Actually, we want to rollback all previous iterations
5999 * of this loop, and (which is almost impossible) previous
6000 * bdrv_replace_node()...
6002 * Note, that c->klass->update_filename may lead to permission
6003 * update, so it's a bad idea to call it inside permission
6004 * update transaction of bdrv_replace_node.
6006 error_report_err(local_err
);
6012 if (update_inherits_from
) {
6013 base
->inherits_from
= explicit_top
->inherits_from
;
6018 bdrv_graph_rdunlock_main_loop();
6019 bdrv_drained_end(base
);
6025 * Implementation of BlockDriver.bdrv_co_get_allocated_file_size() that
6026 * sums the size of all data-bearing children. (This excludes backing
6029 static int64_t coroutine_fn GRAPH_RDLOCK
6030 bdrv_sum_allocated_file_size(BlockDriverState
*bs
)
6033 int64_t child_size
, sum
= 0;
6035 QLIST_FOREACH(child
, &bs
->children
, next
) {
6036 if (child
->role
& (BDRV_CHILD_DATA
| BDRV_CHILD_METADATA
|
6037 BDRV_CHILD_FILTERED
))
6039 child_size
= bdrv_co_get_allocated_file_size(child
->bs
);
6040 if (child_size
< 0) {
6051 * Length of a allocated file in bytes. Sparse files are counted by actual
6052 * allocated space. Return < 0 if error or unknown.
6054 int64_t coroutine_fn
bdrv_co_get_allocated_file_size(BlockDriverState
*bs
)
6056 BlockDriver
*drv
= bs
->drv
;
6058 assert_bdrv_graph_readable();
6063 if (drv
->bdrv_co_get_allocated_file_size
) {
6064 return drv
->bdrv_co_get_allocated_file_size(bs
);
6067 if (drv
->bdrv_file_open
) {
6069 * Protocol drivers default to -ENOTSUP (most of their data is
6070 * not stored in any of their children (if they even have any),
6071 * so there is no generic way to figure it out).
6074 } else if (drv
->is_filter
) {
6075 /* Filter drivers default to the size of their filtered child */
6076 return bdrv_co_get_allocated_file_size(bdrv_filter_bs(bs
));
6078 /* Other drivers default to summing their children's sizes */
6079 return bdrv_sum_allocated_file_size(bs
);
6085 * @drv: Format driver
6086 * @opts: Creation options for new image
6087 * @in_bs: Existing image containing data for new image (may be NULL)
6088 * @errp: Error object
6089 * Returns: A #BlockMeasureInfo (free using qapi_free_BlockMeasureInfo())
6092 * Calculate file size required to create a new image.
6094 * If @in_bs is given then space for allocated clusters and zero clusters
6095 * from that image are included in the calculation. If @opts contains a
6096 * backing file that is shared by @in_bs then backing clusters may be omitted
6097 * from the calculation.
6099 * If @in_bs is NULL then the calculation includes no allocated clusters
6100 * unless a preallocation option is given in @opts.
6102 * Note that @in_bs may use a different BlockDriver from @drv.
6104 * If an error occurs the @errp pointer is set.
6106 BlockMeasureInfo
*bdrv_measure(BlockDriver
*drv
, QemuOpts
*opts
,
6107 BlockDriverState
*in_bs
, Error
**errp
)
6110 if (!drv
->bdrv_measure
) {
6111 error_setg(errp
, "Block driver '%s' does not support size measurement",
6116 return drv
->bdrv_measure(opts
, in_bs
, errp
);
6120 * Return number of sectors on success, -errno on error.
6122 int64_t coroutine_fn
bdrv_co_nb_sectors(BlockDriverState
*bs
)
6124 BlockDriver
*drv
= bs
->drv
;
6126 assert_bdrv_graph_readable();
6131 if (bs
->bl
.has_variable_length
) {
6132 int ret
= bdrv_co_refresh_total_sectors(bs
, bs
->total_sectors
);
6137 return bs
->total_sectors
;
6141 * This wrapper is written by hand because this function is in the hot I/O path,
6142 * via blk_get_geometry.
6144 int64_t coroutine_mixed_fn
bdrv_nb_sectors(BlockDriverState
*bs
)
6146 BlockDriver
*drv
= bs
->drv
;
6152 if (bs
->bl
.has_variable_length
) {
6153 int ret
= bdrv_refresh_total_sectors(bs
, bs
->total_sectors
);
6159 return bs
->total_sectors
;
6163 * Return length in bytes on success, -errno on error.
6164 * The length is always a multiple of BDRV_SECTOR_SIZE.
6166 int64_t coroutine_fn
bdrv_co_getlength(BlockDriverState
*bs
)
6170 assert_bdrv_graph_readable();
6172 ret
= bdrv_co_nb_sectors(bs
);
6176 if (ret
> INT64_MAX
/ BDRV_SECTOR_SIZE
) {
6179 return ret
* BDRV_SECTOR_SIZE
;
6182 bool bdrv_is_sg(BlockDriverState
*bs
)
6189 * Return whether the given node supports compressed writes.
6191 bool bdrv_supports_compressed_writes(BlockDriverState
*bs
)
6193 BlockDriverState
*filtered
;
6196 if (!bs
->drv
|| !block_driver_can_compress(bs
->drv
)) {
6200 filtered
= bdrv_filter_bs(bs
);
6203 * Filters can only forward compressed writes, so we have to
6206 return bdrv_supports_compressed_writes(filtered
);
6212 const char *bdrv_get_format_name(BlockDriverState
*bs
)
6215 return bs
->drv
? bs
->drv
->format_name
: NULL
;
6218 static int qsort_strcmp(const void *a
, const void *b
)
6220 return strcmp(*(char *const *)a
, *(char *const *)b
);
6223 void bdrv_iterate_format(void (*it
)(void *opaque
, const char *name
),
6224 void *opaque
, bool read_only
)
6229 const char **formats
= NULL
;
6231 GLOBAL_STATE_CODE();
6233 QLIST_FOREACH(drv
, &bdrv_drivers
, list
) {
6234 if (drv
->format_name
) {
6237 if (use_bdrv_whitelist
&& !bdrv_is_whitelisted(drv
, read_only
)) {
6242 while (formats
&& i
&& !found
) {
6243 found
= !strcmp(formats
[--i
], drv
->format_name
);
6247 formats
= g_renew(const char *, formats
, count
+ 1);
6248 formats
[count
++] = drv
->format_name
;
6253 for (i
= 0; i
< (int)ARRAY_SIZE(block_driver_modules
); i
++) {
6254 const char *format_name
= block_driver_modules
[i
].format_name
;
6260 if (use_bdrv_whitelist
&&
6261 !bdrv_format_is_whitelisted(format_name
, read_only
)) {
6265 while (formats
&& j
&& !found
) {
6266 found
= !strcmp(formats
[--j
], format_name
);
6270 formats
= g_renew(const char *, formats
, count
+ 1);
6271 formats
[count
++] = format_name
;
6276 qsort(formats
, count
, sizeof(formats
[0]), qsort_strcmp
);
6278 for (i
= 0; i
< count
; i
++) {
6279 it(opaque
, formats
[i
]);
6285 /* This function is to find a node in the bs graph */
6286 BlockDriverState
*bdrv_find_node(const char *node_name
)
6288 BlockDriverState
*bs
;
6291 GLOBAL_STATE_CODE();
6293 QTAILQ_FOREACH(bs
, &graph_bdrv_states
, node_list
) {
6294 if (!strcmp(node_name
, bs
->node_name
)) {
6301 /* Put this QMP function here so it can access the static graph_bdrv_states. */
6302 BlockDeviceInfoList
*bdrv_named_nodes_list(bool flat
,
6305 BlockDeviceInfoList
*list
;
6306 BlockDriverState
*bs
;
6308 GLOBAL_STATE_CODE();
6309 GRAPH_RDLOCK_GUARD_MAINLOOP();
6312 QTAILQ_FOREACH(bs
, &graph_bdrv_states
, node_list
) {
6313 BlockDeviceInfo
*info
= bdrv_block_device_info(NULL
, bs
, flat
, errp
);
6315 qapi_free_BlockDeviceInfoList(list
);
6318 QAPI_LIST_PREPEND(list
, info
);
6324 typedef struct XDbgBlockGraphConstructor
{
6325 XDbgBlockGraph
*graph
;
6326 GHashTable
*graph_nodes
;
6327 } XDbgBlockGraphConstructor
;
6329 static XDbgBlockGraphConstructor
*xdbg_graph_new(void)
6331 XDbgBlockGraphConstructor
*gr
= g_new(XDbgBlockGraphConstructor
, 1);
6333 gr
->graph
= g_new0(XDbgBlockGraph
, 1);
6334 gr
->graph_nodes
= g_hash_table_new(NULL
, NULL
);
6339 static XDbgBlockGraph
*xdbg_graph_finalize(XDbgBlockGraphConstructor
*gr
)
6341 XDbgBlockGraph
*graph
= gr
->graph
;
6343 g_hash_table_destroy(gr
->graph_nodes
);
6349 static uintptr_t xdbg_graph_node_num(XDbgBlockGraphConstructor
*gr
, void *node
)
6351 uintptr_t ret
= (uintptr_t)g_hash_table_lookup(gr
->graph_nodes
, node
);
6358 * Start counting from 1, not 0, because 0 interferes with not-found (NULL)
6359 * answer of g_hash_table_lookup.
6361 ret
= g_hash_table_size(gr
->graph_nodes
) + 1;
6362 g_hash_table_insert(gr
->graph_nodes
, node
, (void *)ret
);
6367 static void xdbg_graph_add_node(XDbgBlockGraphConstructor
*gr
, void *node
,
6368 XDbgBlockGraphNodeType type
, const char *name
)
6370 XDbgBlockGraphNode
*n
;
6372 n
= g_new0(XDbgBlockGraphNode
, 1);
6374 n
->id
= xdbg_graph_node_num(gr
, node
);
6376 n
->name
= g_strdup(name
);
6378 QAPI_LIST_PREPEND(gr
->graph
->nodes
, n
);
6381 static void xdbg_graph_add_edge(XDbgBlockGraphConstructor
*gr
, void *parent
,
6382 const BdrvChild
*child
)
6384 BlockPermission qapi_perm
;
6385 XDbgBlockGraphEdge
*edge
;
6386 GLOBAL_STATE_CODE();
6388 edge
= g_new0(XDbgBlockGraphEdge
, 1);
6390 edge
->parent
= xdbg_graph_node_num(gr
, parent
);
6391 edge
->child
= xdbg_graph_node_num(gr
, child
->bs
);
6392 edge
->name
= g_strdup(child
->name
);
6394 for (qapi_perm
= 0; qapi_perm
< BLOCK_PERMISSION__MAX
; qapi_perm
++) {
6395 uint64_t flag
= bdrv_qapi_perm_to_blk_perm(qapi_perm
);
6397 if (flag
& child
->perm
) {
6398 QAPI_LIST_PREPEND(edge
->perm
, qapi_perm
);
6400 if (flag
& child
->shared_perm
) {
6401 QAPI_LIST_PREPEND(edge
->shared_perm
, qapi_perm
);
6405 QAPI_LIST_PREPEND(gr
->graph
->edges
, edge
);
6409 XDbgBlockGraph
*bdrv_get_xdbg_block_graph(Error
**errp
)
6413 BlockDriverState
*bs
;
6415 XDbgBlockGraphConstructor
*gr
= xdbg_graph_new();
6417 GLOBAL_STATE_CODE();
6419 for (blk
= blk_all_next(NULL
); blk
; blk
= blk_all_next(blk
)) {
6420 char *allocated_name
= NULL
;
6421 const char *name
= blk_name(blk
);
6424 name
= allocated_name
= blk_get_attached_dev_id(blk
);
6426 xdbg_graph_add_node(gr
, blk
, X_DBG_BLOCK_GRAPH_NODE_TYPE_BLOCK_BACKEND
,
6428 g_free(allocated_name
);
6429 if (blk_root(blk
)) {
6430 xdbg_graph_add_edge(gr
, blk
, blk_root(blk
));
6434 WITH_JOB_LOCK_GUARD() {
6435 for (job
= block_job_next_locked(NULL
); job
;
6436 job
= block_job_next_locked(job
)) {
6439 xdbg_graph_add_node(gr
, job
, X_DBG_BLOCK_GRAPH_NODE_TYPE_BLOCK_JOB
,
6441 for (el
= job
->nodes
; el
; el
= el
->next
) {
6442 xdbg_graph_add_edge(gr
, job
, (BdrvChild
*)el
->data
);
6447 QTAILQ_FOREACH(bs
, &graph_bdrv_states
, node_list
) {
6448 xdbg_graph_add_node(gr
, bs
, X_DBG_BLOCK_GRAPH_NODE_TYPE_BLOCK_DRIVER
,
6450 QLIST_FOREACH(child
, &bs
->children
, next
) {
6451 xdbg_graph_add_edge(gr
, bs
, child
);
6455 return xdbg_graph_finalize(gr
);
6458 BlockDriverState
*bdrv_lookup_bs(const char *device
,
6459 const char *node_name
,
6463 BlockDriverState
*bs
;
6465 GLOBAL_STATE_CODE();
6468 blk
= blk_by_name(device
);
6473 error_setg(errp
, "Device '%s' has no medium", device
);
6481 bs
= bdrv_find_node(node_name
);
6488 error_setg(errp
, "Cannot find device=\'%s\' nor node-name=\'%s\'",
6489 device
? device
: "",
6490 node_name
? node_name
: "");
6494 /* If 'base' is in the same chain as 'top', return true. Otherwise,
6495 * return false. If either argument is NULL, return false. */
6496 bool bdrv_chain_contains(BlockDriverState
*top
, BlockDriverState
*base
)
6499 GLOBAL_STATE_CODE();
6501 while (top
&& top
!= base
) {
6502 top
= bdrv_filter_or_cow_bs(top
);
6508 BlockDriverState
*bdrv_next_node(BlockDriverState
*bs
)
6510 GLOBAL_STATE_CODE();
6512 return QTAILQ_FIRST(&graph_bdrv_states
);
6514 return QTAILQ_NEXT(bs
, node_list
);
6517 BlockDriverState
*bdrv_next_all_states(BlockDriverState
*bs
)
6519 GLOBAL_STATE_CODE();
6521 return QTAILQ_FIRST(&all_bdrv_states
);
6523 return QTAILQ_NEXT(bs
, bs_list
);
6526 const char *bdrv_get_node_name(const BlockDriverState
*bs
)
6529 return bs
->node_name
;
6532 const char *bdrv_get_parent_name(const BlockDriverState
*bs
)
6538 /* If multiple parents have a name, just pick the first one. */
6539 QLIST_FOREACH(c
, &bs
->parents
, next_parent
) {
6540 if (c
->klass
->get_name
) {
6541 name
= c
->klass
->get_name(c
);
6542 if (name
&& *name
) {
6551 /* TODO check what callers really want: bs->node_name or blk_name() */
6552 const char *bdrv_get_device_name(const BlockDriverState
*bs
)
6555 return bdrv_get_parent_name(bs
) ?: "";
6558 /* This can be used to identify nodes that might not have a device
6559 * name associated. Since node and device names live in the same
6560 * namespace, the result is unambiguous. The exception is if both are
6561 * absent, then this returns an empty (non-null) string. */
6562 const char *bdrv_get_device_or_node_name(const BlockDriverState
*bs
)
6565 return bdrv_get_parent_name(bs
) ?: bs
->node_name
;
6568 int bdrv_get_flags(BlockDriverState
*bs
)
6571 return bs
->open_flags
;
6574 int bdrv_has_zero_init_1(BlockDriverState
*bs
)
6576 GLOBAL_STATE_CODE();
6580 int bdrv_has_zero_init(BlockDriverState
*bs
)
6582 BlockDriverState
*filtered
;
6583 GLOBAL_STATE_CODE();
6589 /* If BS is a copy on write image, it is initialized to
6590 the contents of the base image, which may not be zeroes. */
6591 if (bdrv_cow_child(bs
)) {
6594 if (bs
->drv
->bdrv_has_zero_init
) {
6595 return bs
->drv
->bdrv_has_zero_init(bs
);
6598 filtered
= bdrv_filter_bs(bs
);
6600 return bdrv_has_zero_init(filtered
);
6607 bool bdrv_can_write_zeroes_with_unmap(BlockDriverState
*bs
)
6610 if (!(bs
->open_flags
& BDRV_O_UNMAP
)) {
6614 return bs
->supported_zero_flags
& BDRV_REQ_MAY_UNMAP
;
6617 void bdrv_get_backing_filename(BlockDriverState
*bs
,
6618 char *filename
, int filename_size
)
6621 pstrcpy(filename
, filename_size
, bs
->backing_file
);
6624 int coroutine_fn
bdrv_co_get_info(BlockDriverState
*bs
, BlockDriverInfo
*bdi
)
6627 BlockDriver
*drv
= bs
->drv
;
6629 assert_bdrv_graph_readable();
6631 /* if bs->drv == NULL, bs is closed, so there's nothing to do here */
6635 if (!drv
->bdrv_co_get_info
) {
6636 BlockDriverState
*filtered
= bdrv_filter_bs(bs
);
6638 return bdrv_co_get_info(filtered
, bdi
);
6642 memset(bdi
, 0, sizeof(*bdi
));
6643 ret
= drv
->bdrv_co_get_info(bs
, bdi
);
6644 if (bdi
->subcluster_size
== 0) {
6646 * If the driver left this unset, subclusters are not supported.
6647 * Then it is safe to treat each cluster as having only one subcluster.
6649 bdi
->subcluster_size
= bdi
->cluster_size
;
6655 if (bdi
->cluster_size
> BDRV_MAX_ALIGNMENT
) {
6662 ImageInfoSpecific
*bdrv_get_specific_info(BlockDriverState
*bs
,
6665 BlockDriver
*drv
= bs
->drv
;
6667 if (drv
&& drv
->bdrv_get_specific_info
) {
6668 return drv
->bdrv_get_specific_info(bs
, errp
);
6673 BlockStatsSpecific
*bdrv_get_specific_stats(BlockDriverState
*bs
)
6675 BlockDriver
*drv
= bs
->drv
;
6677 if (!drv
|| !drv
->bdrv_get_specific_stats
) {
6680 return drv
->bdrv_get_specific_stats(bs
);
6683 void coroutine_fn
bdrv_co_debug_event(BlockDriverState
*bs
, BlkdebugEvent event
)
6686 assert_bdrv_graph_readable();
6688 if (!bs
|| !bs
->drv
|| !bs
->drv
->bdrv_co_debug_event
) {
6692 bs
->drv
->bdrv_co_debug_event(bs
, event
);
6695 static BlockDriverState
*bdrv_find_debug_node(BlockDriverState
*bs
)
6697 GLOBAL_STATE_CODE();
6698 while (bs
&& bs
->drv
&& !bs
->drv
->bdrv_debug_breakpoint
) {
6699 bs
= bdrv_primary_bs(bs
);
6702 if (bs
&& bs
->drv
&& bs
->drv
->bdrv_debug_breakpoint
) {
6703 assert(bs
->drv
->bdrv_debug_remove_breakpoint
);
6710 int bdrv_debug_breakpoint(BlockDriverState
*bs
, const char *event
,
6713 GLOBAL_STATE_CODE();
6714 bs
= bdrv_find_debug_node(bs
);
6716 return bs
->drv
->bdrv_debug_breakpoint(bs
, event
, tag
);
6722 int bdrv_debug_remove_breakpoint(BlockDriverState
*bs
, const char *tag
)
6724 GLOBAL_STATE_CODE();
6725 bs
= bdrv_find_debug_node(bs
);
6727 return bs
->drv
->bdrv_debug_remove_breakpoint(bs
, tag
);
6733 int bdrv_debug_resume(BlockDriverState
*bs
, const char *tag
)
6735 GLOBAL_STATE_CODE();
6736 while (bs
&& (!bs
->drv
|| !bs
->drv
->bdrv_debug_resume
)) {
6737 bs
= bdrv_primary_bs(bs
);
6740 if (bs
&& bs
->drv
&& bs
->drv
->bdrv_debug_resume
) {
6741 return bs
->drv
->bdrv_debug_resume(bs
, tag
);
6747 bool bdrv_debug_is_suspended(BlockDriverState
*bs
, const char *tag
)
6749 GLOBAL_STATE_CODE();
6750 while (bs
&& bs
->drv
&& !bs
->drv
->bdrv_debug_is_suspended
) {
6751 bs
= bdrv_primary_bs(bs
);
6754 if (bs
&& bs
->drv
&& bs
->drv
->bdrv_debug_is_suspended
) {
6755 return bs
->drv
->bdrv_debug_is_suspended(bs
, tag
);
6761 /* backing_file can either be relative, or absolute, or a protocol. If it is
6762 * relative, it must be relative to the chain. So, passing in bs->filename
6763 * from a BDS as backing_file should not be done, as that may be relative to
6764 * the CWD rather than the chain. */
6765 BlockDriverState
*bdrv_find_backing_image(BlockDriverState
*bs
,
6766 const char *backing_file
)
6768 char *filename_full
= NULL
;
6769 char *backing_file_full
= NULL
;
6770 char *filename_tmp
= NULL
;
6771 int is_protocol
= 0;
6772 bool filenames_refreshed
= false;
6773 BlockDriverState
*curr_bs
= NULL
;
6774 BlockDriverState
*retval
= NULL
;
6775 BlockDriverState
*bs_below
;
6777 GLOBAL_STATE_CODE();
6778 GRAPH_RDLOCK_GUARD_MAINLOOP();
6780 if (!bs
|| !bs
->drv
|| !backing_file
) {
6784 filename_full
= g_malloc(PATH_MAX
);
6785 backing_file_full
= g_malloc(PATH_MAX
);
6787 is_protocol
= path_has_protocol(backing_file
);
6790 * Being largely a legacy function, skip any filters here
6791 * (because filters do not have normal filenames, so they cannot
6792 * match anyway; and allowing json:{} filenames is a bit out of
6795 for (curr_bs
= bdrv_skip_filters(bs
);
6796 bdrv_cow_child(curr_bs
) != NULL
;
6799 bs_below
= bdrv_backing_chain_next(curr_bs
);
6801 if (bdrv_backing_overridden(curr_bs
)) {
6803 * If the backing file was overridden, we can only compare
6804 * directly against the backing node's filename.
6807 if (!filenames_refreshed
) {
6809 * This will automatically refresh all of the
6810 * filenames in the rest of the backing chain, so we
6811 * only need to do this once.
6813 bdrv_refresh_filename(bs_below
);
6814 filenames_refreshed
= true;
6817 if (strcmp(backing_file
, bs_below
->filename
) == 0) {
6821 } else if (is_protocol
|| path_has_protocol(curr_bs
->backing_file
)) {
6823 * If either of the filename paths is actually a protocol, then
6824 * compare unmodified paths; otherwise make paths relative.
6826 char *backing_file_full_ret
;
6828 if (strcmp(backing_file
, curr_bs
->backing_file
) == 0) {
6832 /* Also check against the full backing filename for the image */
6833 backing_file_full_ret
= bdrv_get_full_backing_filename(curr_bs
,
6835 if (backing_file_full_ret
) {
6836 bool equal
= strcmp(backing_file
, backing_file_full_ret
) == 0;
6837 g_free(backing_file_full_ret
);
6844 /* If not an absolute filename path, make it relative to the current
6845 * image's filename path */
6846 filename_tmp
= bdrv_make_absolute_filename(curr_bs
, backing_file
,
6848 /* We are going to compare canonicalized absolute pathnames */
6849 if (!filename_tmp
|| !realpath(filename_tmp
, filename_full
)) {
6850 g_free(filename_tmp
);
6853 g_free(filename_tmp
);
6855 /* We need to make sure the backing filename we are comparing against
6856 * is relative to the current image filename (or absolute) */
6857 filename_tmp
= bdrv_get_full_backing_filename(curr_bs
, NULL
);
6858 if (!filename_tmp
|| !realpath(filename_tmp
, backing_file_full
)) {
6859 g_free(filename_tmp
);
6862 g_free(filename_tmp
);
6864 if (strcmp(backing_file_full
, filename_full
) == 0) {
6871 g_free(filename_full
);
6872 g_free(backing_file_full
);
6876 void bdrv_init(void)
6878 #ifdef CONFIG_BDRV_WHITELIST_TOOLS
6879 use_bdrv_whitelist
= 1;
6881 module_call_init(MODULE_INIT_BLOCK
);
6884 void bdrv_init_with_whitelist(void)
6886 use_bdrv_whitelist
= 1;
6890 int bdrv_activate(BlockDriverState
*bs
, Error
**errp
)
6892 BdrvChild
*child
, *parent
;
6893 Error
*local_err
= NULL
;
6895 BdrvDirtyBitmap
*bm
;
6897 GLOBAL_STATE_CODE();
6898 GRAPH_RDLOCK_GUARD_MAINLOOP();
6904 QLIST_FOREACH(child
, &bs
->children
, next
) {
6905 bdrv_activate(child
->bs
, &local_err
);
6907 error_propagate(errp
, local_err
);
6913 * Update permissions, they may differ for inactive nodes.
6915 * Note that the required permissions of inactive images are always a
6916 * subset of the permissions required after activating the image. This
6917 * allows us to just get the permissions upfront without restricting
6918 * bdrv_co_invalidate_cache().
6920 * It also means that in error cases, we don't have to try and revert to
6921 * the old permissions (which is an operation that could fail, too). We can
6922 * just keep the extended permissions for the next time that an activation
6923 * of the image is tried.
6925 if (bs
->open_flags
& BDRV_O_INACTIVE
) {
6926 bs
->open_flags
&= ~BDRV_O_INACTIVE
;
6927 ret
= bdrv_refresh_perms(bs
, NULL
, errp
);
6929 bs
->open_flags
|= BDRV_O_INACTIVE
;
6933 ret
= bdrv_invalidate_cache(bs
, errp
);
6935 bs
->open_flags
|= BDRV_O_INACTIVE
;
6939 FOR_EACH_DIRTY_BITMAP(bs
, bm
) {
6940 bdrv_dirty_bitmap_skip_store(bm
, false);
6943 ret
= bdrv_refresh_total_sectors(bs
, bs
->total_sectors
);
6945 bs
->open_flags
|= BDRV_O_INACTIVE
;
6946 error_setg_errno(errp
, -ret
, "Could not refresh total sector count");
6951 QLIST_FOREACH(parent
, &bs
->parents
, next_parent
) {
6952 if (parent
->klass
->activate
) {
6953 parent
->klass
->activate(parent
, &local_err
);
6955 bs
->open_flags
|= BDRV_O_INACTIVE
;
6956 error_propagate(errp
, local_err
);
6965 int coroutine_fn
bdrv_co_invalidate_cache(BlockDriverState
*bs
, Error
**errp
)
6967 Error
*local_err
= NULL
;
6970 assert(!(bs
->open_flags
& BDRV_O_INACTIVE
));
6971 assert_bdrv_graph_readable();
6973 if (bs
->drv
->bdrv_co_invalidate_cache
) {
6974 bs
->drv
->bdrv_co_invalidate_cache(bs
, &local_err
);
6976 error_propagate(errp
, local_err
);
6984 void bdrv_activate_all(Error
**errp
)
6986 BlockDriverState
*bs
;
6987 BdrvNextIterator it
;
6989 GLOBAL_STATE_CODE();
6990 GRAPH_RDLOCK_GUARD_MAINLOOP();
6992 for (bs
= bdrv_first(&it
); bs
; bs
= bdrv_next(&it
)) {
6993 AioContext
*aio_context
= bdrv_get_aio_context(bs
);
6996 aio_context_acquire(aio_context
);
6997 ret
= bdrv_activate(bs
, errp
);
6998 aio_context_release(aio_context
);
7000 bdrv_next_cleanup(&it
);
7006 static bool GRAPH_RDLOCK
7007 bdrv_has_bds_parent(BlockDriverState
*bs
, bool only_active
)
7010 GLOBAL_STATE_CODE();
7012 QLIST_FOREACH(parent
, &bs
->parents
, next_parent
) {
7013 if (parent
->klass
->parent_is_bds
) {
7014 BlockDriverState
*parent_bs
= parent
->opaque
;
7015 if (!only_active
|| !(parent_bs
->open_flags
& BDRV_O_INACTIVE
)) {
7024 static int GRAPH_RDLOCK
bdrv_inactivate_recurse(BlockDriverState
*bs
)
7026 BdrvChild
*child
, *parent
;
7028 uint64_t cumulative_perms
, cumulative_shared_perms
;
7030 GLOBAL_STATE_CODE();
7036 /* Make sure that we don't inactivate a child before its parent.
7037 * It will be covered by recursion from the yet active parent. */
7038 if (bdrv_has_bds_parent(bs
, true)) {
7042 assert(!(bs
->open_flags
& BDRV_O_INACTIVE
));
7044 /* Inactivate this node */
7045 if (bs
->drv
->bdrv_inactivate
) {
7046 ret
= bs
->drv
->bdrv_inactivate(bs
);
7052 QLIST_FOREACH(parent
, &bs
->parents
, next_parent
) {
7053 if (parent
->klass
->inactivate
) {
7054 ret
= parent
->klass
->inactivate(parent
);
7061 bdrv_get_cumulative_perm(bs
, &cumulative_perms
,
7062 &cumulative_shared_perms
);
7063 if (cumulative_perms
& (BLK_PERM_WRITE
| BLK_PERM_WRITE_UNCHANGED
)) {
7064 /* Our inactive parents still need write access. Inactivation failed. */
7068 bs
->open_flags
|= BDRV_O_INACTIVE
;
7071 * Update permissions, they may differ for inactive nodes.
7072 * We only tried to loosen restrictions, so errors are not fatal, ignore
7075 bdrv_refresh_perms(bs
, NULL
, NULL
);
7077 /* Recursively inactivate children */
7078 QLIST_FOREACH(child
, &bs
->children
, next
) {
7079 ret
= bdrv_inactivate_recurse(child
->bs
);
7088 int bdrv_inactivate_all(void)
7090 BlockDriverState
*bs
= NULL
;
7091 BdrvNextIterator it
;
7093 GSList
*aio_ctxs
= NULL
, *ctx
;
7095 GLOBAL_STATE_CODE();
7096 GRAPH_RDLOCK_GUARD_MAINLOOP();
7098 for (bs
= bdrv_first(&it
); bs
; bs
= bdrv_next(&it
)) {
7099 AioContext
*aio_context
= bdrv_get_aio_context(bs
);
7101 if (!g_slist_find(aio_ctxs
, aio_context
)) {
7102 aio_ctxs
= g_slist_prepend(aio_ctxs
, aio_context
);
7103 aio_context_acquire(aio_context
);
7107 for (bs
= bdrv_first(&it
); bs
; bs
= bdrv_next(&it
)) {
7108 /* Nodes with BDS parents are covered by recursion from the last
7109 * parent that gets inactivated. Don't inactivate them a second
7110 * time if that has already happened. */
7111 if (bdrv_has_bds_parent(bs
, false)) {
7114 ret
= bdrv_inactivate_recurse(bs
);
7116 bdrv_next_cleanup(&it
);
7122 for (ctx
= aio_ctxs
; ctx
!= NULL
; ctx
= ctx
->next
) {
7123 AioContext
*aio_context
= ctx
->data
;
7124 aio_context_release(aio_context
);
7126 g_slist_free(aio_ctxs
);
7131 /**************************************************************/
7132 /* removable device support */
7135 * Return TRUE if the media is present
7137 bool coroutine_fn
bdrv_co_is_inserted(BlockDriverState
*bs
)
7139 BlockDriver
*drv
= bs
->drv
;
7142 assert_bdrv_graph_readable();
7147 if (drv
->bdrv_co_is_inserted
) {
7148 return drv
->bdrv_co_is_inserted(bs
);
7150 QLIST_FOREACH(child
, &bs
->children
, next
) {
7151 if (!bdrv_co_is_inserted(child
->bs
)) {
7159 * If eject_flag is TRUE, eject the media. Otherwise, close the tray
7161 void coroutine_fn
bdrv_co_eject(BlockDriverState
*bs
, bool eject_flag
)
7163 BlockDriver
*drv
= bs
->drv
;
7165 assert_bdrv_graph_readable();
7167 if (drv
&& drv
->bdrv_co_eject
) {
7168 drv
->bdrv_co_eject(bs
, eject_flag
);
7173 * Lock or unlock the media (if it is locked, the user won't be able
7174 * to eject it manually).
7176 void coroutine_fn
bdrv_co_lock_medium(BlockDriverState
*bs
, bool locked
)
7178 BlockDriver
*drv
= bs
->drv
;
7180 assert_bdrv_graph_readable();
7181 trace_bdrv_lock_medium(bs
, locked
);
7183 if (drv
&& drv
->bdrv_co_lock_medium
) {
7184 drv
->bdrv_co_lock_medium(bs
, locked
);
7188 /* Get a reference to bs */
7189 void bdrv_ref(BlockDriverState
*bs
)
7191 GLOBAL_STATE_CODE();
7195 /* Release a previously grabbed reference to bs.
7196 * If after releasing, reference count is zero, the BlockDriverState is
7198 void bdrv_unref(BlockDriverState
*bs
)
7200 GLOBAL_STATE_CODE();
7204 assert(bs
->refcnt
> 0);
7205 if (--bs
->refcnt
== 0) {
7211 * Release a BlockDriverState reference while holding the graph write lock.
7213 * Calling bdrv_unref() directly is forbidden while holding the graph lock
7214 * because bdrv_close() both involves polling and taking the graph lock
7215 * internally. bdrv_schedule_unref() instead delays decreasing the refcount and
7216 * possibly closing @bs until the graph lock is released.
7218 void bdrv_schedule_unref(BlockDriverState
*bs
)
7223 aio_bh_schedule_oneshot(qemu_get_aio_context(),
7224 (QEMUBHFunc
*) bdrv_unref
, bs
);
7227 struct BdrvOpBlocker
{
7229 QLIST_ENTRY(BdrvOpBlocker
) list
;
7232 bool bdrv_op_is_blocked(BlockDriverState
*bs
, BlockOpType op
, Error
**errp
)
7234 BdrvOpBlocker
*blocker
;
7235 GLOBAL_STATE_CODE();
7236 assert((int) op
>= 0 && op
< BLOCK_OP_TYPE_MAX
);
7237 if (!QLIST_EMPTY(&bs
->op_blockers
[op
])) {
7238 blocker
= QLIST_FIRST(&bs
->op_blockers
[op
]);
7239 error_propagate_prepend(errp
, error_copy(blocker
->reason
),
7240 "Node '%s' is busy: ",
7241 bdrv_get_device_or_node_name(bs
));
7247 void bdrv_op_block(BlockDriverState
*bs
, BlockOpType op
, Error
*reason
)
7249 BdrvOpBlocker
*blocker
;
7250 GLOBAL_STATE_CODE();
7251 assert((int) op
>= 0 && op
< BLOCK_OP_TYPE_MAX
);
7253 blocker
= g_new0(BdrvOpBlocker
, 1);
7254 blocker
->reason
= reason
;
7255 QLIST_INSERT_HEAD(&bs
->op_blockers
[op
], blocker
, list
);
7258 void bdrv_op_unblock(BlockDriverState
*bs
, BlockOpType op
, Error
*reason
)
7260 BdrvOpBlocker
*blocker
, *next
;
7261 GLOBAL_STATE_CODE();
7262 assert((int) op
>= 0 && op
< BLOCK_OP_TYPE_MAX
);
7263 QLIST_FOREACH_SAFE(blocker
, &bs
->op_blockers
[op
], list
, next
) {
7264 if (blocker
->reason
== reason
) {
7265 QLIST_REMOVE(blocker
, list
);
7271 void bdrv_op_block_all(BlockDriverState
*bs
, Error
*reason
)
7274 GLOBAL_STATE_CODE();
7275 for (i
= 0; i
< BLOCK_OP_TYPE_MAX
; i
++) {
7276 bdrv_op_block(bs
, i
, reason
);
7280 void bdrv_op_unblock_all(BlockDriverState
*bs
, Error
*reason
)
7283 GLOBAL_STATE_CODE();
7284 for (i
= 0; i
< BLOCK_OP_TYPE_MAX
; i
++) {
7285 bdrv_op_unblock(bs
, i
, reason
);
7289 bool bdrv_op_blocker_is_empty(BlockDriverState
*bs
)
7292 GLOBAL_STATE_CODE();
7293 for (i
= 0; i
< BLOCK_OP_TYPE_MAX
; i
++) {
7294 if (!QLIST_EMPTY(&bs
->op_blockers
[i
])) {
7302 * Must not be called while holding the lock of an AioContext other than the
7305 void bdrv_img_create(const char *filename
, const char *fmt
,
7306 const char *base_filename
, const char *base_fmt
,
7307 char *options
, uint64_t img_size
, int flags
, bool quiet
,
7310 QemuOptsList
*create_opts
= NULL
;
7311 QemuOpts
*opts
= NULL
;
7312 const char *backing_fmt
, *backing_file
;
7314 BlockDriver
*drv
, *proto_drv
;
7315 Error
*local_err
= NULL
;
7318 GLOBAL_STATE_CODE();
7320 /* Find driver and parse its options */
7321 drv
= bdrv_find_format(fmt
);
7323 error_setg(errp
, "Unknown file format '%s'", fmt
);
7327 proto_drv
= bdrv_find_protocol(filename
, true, errp
);
7332 if (!drv
->create_opts
) {
7333 error_setg(errp
, "Format driver '%s' does not support image creation",
7338 if (!proto_drv
->create_opts
) {
7339 error_setg(errp
, "Protocol driver '%s' does not support image creation",
7340 proto_drv
->format_name
);
7344 aio_context_acquire(qemu_get_aio_context());
7346 /* Create parameter list */
7347 create_opts
= qemu_opts_append(create_opts
, drv
->create_opts
);
7348 create_opts
= qemu_opts_append(create_opts
, proto_drv
->create_opts
);
7350 opts
= qemu_opts_create(create_opts
, NULL
, 0, &error_abort
);
7352 /* Parse -o options */
7354 if (!qemu_opts_do_parse(opts
, options
, NULL
, errp
)) {
7359 if (!qemu_opt_get(opts
, BLOCK_OPT_SIZE
)) {
7360 qemu_opt_set_number(opts
, BLOCK_OPT_SIZE
, img_size
, &error_abort
);
7361 } else if (img_size
!= UINT64_C(-1)) {
7362 error_setg(errp
, "The image size must be specified only once");
7366 if (base_filename
) {
7367 if (!qemu_opt_set(opts
, BLOCK_OPT_BACKING_FILE
, base_filename
,
7369 error_setg(errp
, "Backing file not supported for file format '%s'",
7376 if (!qemu_opt_set(opts
, BLOCK_OPT_BACKING_FMT
, base_fmt
, NULL
)) {
7377 error_setg(errp
, "Backing file format not supported for file "
7378 "format '%s'", fmt
);
7383 backing_file
= qemu_opt_get(opts
, BLOCK_OPT_BACKING_FILE
);
7385 if (!strcmp(filename
, backing_file
)) {
7386 error_setg(errp
, "Error: Trying to create an image with the "
7387 "same filename as the backing file");
7390 if (backing_file
[0] == '\0') {
7391 error_setg(errp
, "Expected backing file name, got empty string");
7396 backing_fmt
= qemu_opt_get(opts
, BLOCK_OPT_BACKING_FMT
);
7398 /* The size for the image must always be specified, unless we have a backing
7399 * file and we have not been forbidden from opening it. */
7400 size
= qemu_opt_get_size(opts
, BLOCK_OPT_SIZE
, img_size
);
7401 if (backing_file
&& !(flags
& BDRV_O_NO_BACKING
)) {
7402 BlockDriverState
*bs
;
7405 QDict
*backing_options
= NULL
;
7408 bdrv_get_full_backing_filename_from_filename(filename
, backing_file
,
7413 assert(full_backing
);
7416 * No need to do I/O here, which allows us to open encrypted
7417 * backing images without needing the secret
7420 back_flags
&= ~(BDRV_O_RDWR
| BDRV_O_SNAPSHOT
| BDRV_O_NO_BACKING
);
7421 back_flags
|= BDRV_O_NO_IO
;
7423 backing_options
= qdict_new();
7425 qdict_put_str(backing_options
, "driver", backing_fmt
);
7427 qdict_put_bool(backing_options
, BDRV_OPT_FORCE_SHARE
, true);
7429 bs
= bdrv_open(full_backing
, NULL
, backing_options
, back_flags
,
7431 g_free(full_backing
);
7433 error_append_hint(&local_err
, "Could not open backing image.\n");
7437 error_setg(&local_err
,
7438 "Backing file specified without backing format");
7439 error_append_hint(&local_err
, "Detected format of %s.\n",
7440 bs
->drv
->format_name
);
7444 /* Opened BS, have no size */
7445 size
= bdrv_getlength(bs
);
7447 error_setg_errno(errp
, -size
, "Could not get size of '%s'",
7452 qemu_opt_set_number(opts
, BLOCK_OPT_SIZE
, size
, &error_abort
);
7456 /* (backing_file && !(flags & BDRV_O_NO_BACKING)) */
7457 } else if (backing_file
&& !backing_fmt
) {
7458 error_setg(&local_err
,
7459 "Backing file specified without backing format");
7464 error_setg(errp
, "Image creation needs a size parameter");
7469 printf("Formatting '%s', fmt=%s ", filename
, fmt
);
7470 qemu_opts_print(opts
, " ");
7475 ret
= bdrv_create(drv
, filename
, opts
, &local_err
);
7477 if (ret
== -EFBIG
) {
7478 /* This is generally a better message than whatever the driver would
7479 * deliver (especially because of the cluster_size_hint), since that
7480 * is most probably not much different from "image too large". */
7481 const char *cluster_size_hint
= "";
7482 if (qemu_opt_get_size(opts
, BLOCK_OPT_CLUSTER_SIZE
, 0)) {
7483 cluster_size_hint
= " (try using a larger cluster size)";
7485 error_setg(errp
, "The image size is too large for file format '%s'"
7486 "%s", fmt
, cluster_size_hint
);
7487 error_free(local_err
);
7492 qemu_opts_del(opts
);
7493 qemu_opts_free(create_opts
);
7494 error_propagate(errp
, local_err
);
7495 aio_context_release(qemu_get_aio_context());
7498 AioContext
*bdrv_get_aio_context(BlockDriverState
*bs
)
7501 return bs
? bs
->aio_context
: qemu_get_aio_context();
7504 AioContext
*coroutine_fn
bdrv_co_enter(BlockDriverState
*bs
)
7506 Coroutine
*self
= qemu_coroutine_self();
7507 AioContext
*old_ctx
= qemu_coroutine_get_aio_context(self
);
7508 AioContext
*new_ctx
;
7512 * Increase bs->in_flight to ensure that this operation is completed before
7513 * moving the node to a different AioContext. Read new_ctx only afterwards.
7515 bdrv_inc_in_flight(bs
);
7517 new_ctx
= bdrv_get_aio_context(bs
);
7518 aio_co_reschedule_self(new_ctx
);
7522 void coroutine_fn
bdrv_co_leave(BlockDriverState
*bs
, AioContext
*old_ctx
)
7525 aio_co_reschedule_self(old_ctx
);
7526 bdrv_dec_in_flight(bs
);
7529 void coroutine_fn
bdrv_co_lock(BlockDriverState
*bs
)
7531 AioContext
*ctx
= bdrv_get_aio_context(bs
);
7533 /* In the main thread, bs->aio_context won't change concurrently */
7534 assert(qemu_get_current_aio_context() == qemu_get_aio_context());
7537 * We're in coroutine context, so we already hold the lock of the main
7538 * loop AioContext. Don't lock it twice to avoid deadlocks.
7540 assert(qemu_in_coroutine());
7541 if (ctx
!= qemu_get_aio_context()) {
7542 aio_context_acquire(ctx
);
7546 void coroutine_fn
bdrv_co_unlock(BlockDriverState
*bs
)
7548 AioContext
*ctx
= bdrv_get_aio_context(bs
);
7550 assert(qemu_in_coroutine());
7551 if (ctx
!= qemu_get_aio_context()) {
7552 aio_context_release(ctx
);
7556 static void bdrv_do_remove_aio_context_notifier(BdrvAioNotifier
*ban
)
7558 GLOBAL_STATE_CODE();
7559 QLIST_REMOVE(ban
, list
);
7563 static void bdrv_detach_aio_context(BlockDriverState
*bs
)
7565 BdrvAioNotifier
*baf
, *baf_tmp
;
7567 assert(!bs
->walking_aio_notifiers
);
7568 GLOBAL_STATE_CODE();
7569 bs
->walking_aio_notifiers
= true;
7570 QLIST_FOREACH_SAFE(baf
, &bs
->aio_notifiers
, list
, baf_tmp
) {
7572 bdrv_do_remove_aio_context_notifier(baf
);
7574 baf
->detach_aio_context(baf
->opaque
);
7577 /* Never mind iterating again to check for ->deleted. bdrv_close() will
7578 * remove remaining aio notifiers if we aren't called again.
7580 bs
->walking_aio_notifiers
= false;
7582 if (bs
->drv
&& bs
->drv
->bdrv_detach_aio_context
) {
7583 bs
->drv
->bdrv_detach_aio_context(bs
);
7586 bs
->aio_context
= NULL
;
7589 static void bdrv_attach_aio_context(BlockDriverState
*bs
,
7590 AioContext
*new_context
)
7592 BdrvAioNotifier
*ban
, *ban_tmp
;
7593 GLOBAL_STATE_CODE();
7595 bs
->aio_context
= new_context
;
7597 if (bs
->drv
&& bs
->drv
->bdrv_attach_aio_context
) {
7598 bs
->drv
->bdrv_attach_aio_context(bs
, new_context
);
7601 assert(!bs
->walking_aio_notifiers
);
7602 bs
->walking_aio_notifiers
= true;
7603 QLIST_FOREACH_SAFE(ban
, &bs
->aio_notifiers
, list
, ban_tmp
) {
7605 bdrv_do_remove_aio_context_notifier(ban
);
7607 ban
->attached_aio_context(new_context
, ban
->opaque
);
7610 bs
->walking_aio_notifiers
= false;
7613 typedef struct BdrvStateSetAioContext
{
7614 AioContext
*new_ctx
;
7615 BlockDriverState
*bs
;
7616 } BdrvStateSetAioContext
;
7618 static bool bdrv_parent_change_aio_context(BdrvChild
*c
, AioContext
*ctx
,
7619 GHashTable
*visited
,
7623 GLOBAL_STATE_CODE();
7624 if (g_hash_table_contains(visited
, c
)) {
7627 g_hash_table_add(visited
, c
);
7630 * A BdrvChildClass that doesn't handle AioContext changes cannot
7631 * tolerate any AioContext changes
7633 if (!c
->klass
->change_aio_ctx
) {
7634 char *user
= bdrv_child_user_desc(c
);
7635 error_setg(errp
, "Changing iothreads is not supported by %s", user
);
7639 if (!c
->klass
->change_aio_ctx(c
, ctx
, visited
, tran
, errp
)) {
7640 assert(!errp
|| *errp
);
7646 bool bdrv_child_change_aio_context(BdrvChild
*c
, AioContext
*ctx
,
7647 GHashTable
*visited
, Transaction
*tran
,
7650 GLOBAL_STATE_CODE();
7651 if (g_hash_table_contains(visited
, c
)) {
7654 g_hash_table_add(visited
, c
);
7655 return bdrv_change_aio_context(c
->bs
, ctx
, visited
, tran
, errp
);
7658 static void bdrv_set_aio_context_clean(void *opaque
)
7660 BdrvStateSetAioContext
*state
= (BdrvStateSetAioContext
*) opaque
;
7661 BlockDriverState
*bs
= (BlockDriverState
*) state
->bs
;
7663 /* Paired with bdrv_drained_begin in bdrv_change_aio_context() */
7664 bdrv_drained_end(bs
);
7669 static void bdrv_set_aio_context_commit(void *opaque
)
7671 BdrvStateSetAioContext
*state
= (BdrvStateSetAioContext
*) opaque
;
7672 BlockDriverState
*bs
= (BlockDriverState
*) state
->bs
;
7673 AioContext
*new_context
= state
->new_ctx
;
7674 AioContext
*old_context
= bdrv_get_aio_context(bs
);
7677 * Take the old AioContex when detaching it from bs.
7678 * At this point, new_context lock is already acquired, and we are now
7679 * also taking old_context. This is safe as long as bdrv_detach_aio_context
7680 * does not call AIO_POLL_WHILE().
7682 if (old_context
!= qemu_get_aio_context()) {
7683 aio_context_acquire(old_context
);
7685 bdrv_detach_aio_context(bs
);
7686 if (old_context
!= qemu_get_aio_context()) {
7687 aio_context_release(old_context
);
7689 bdrv_attach_aio_context(bs
, new_context
);
7692 static TransactionActionDrv set_aio_context
= {
7693 .commit
= bdrv_set_aio_context_commit
,
7694 .clean
= bdrv_set_aio_context_clean
,
7698 * Changes the AioContext used for fd handlers, timers, and BHs by this
7699 * BlockDriverState and all its children and parents.
7701 * Must be called from the main AioContext.
7703 * The caller must own the AioContext lock for the old AioContext of bs, but it
7704 * must not own the AioContext lock for new_context (unless new_context is the
7705 * same as the current context of bs).
7707 * @visited will accumulate all visited BdrvChild objects. The caller is
7708 * responsible for freeing the list afterwards.
7710 static bool bdrv_change_aio_context(BlockDriverState
*bs
, AioContext
*ctx
,
7711 GHashTable
*visited
, Transaction
*tran
,
7715 BdrvStateSetAioContext
*state
;
7717 GLOBAL_STATE_CODE();
7719 if (bdrv_get_aio_context(bs
) == ctx
) {
7723 bdrv_graph_rdlock_main_loop();
7724 QLIST_FOREACH(c
, &bs
->parents
, next_parent
) {
7725 if (!bdrv_parent_change_aio_context(c
, ctx
, visited
, tran
, errp
)) {
7726 bdrv_graph_rdunlock_main_loop();
7731 QLIST_FOREACH(c
, &bs
->children
, next
) {
7732 if (!bdrv_child_change_aio_context(c
, ctx
, visited
, tran
, errp
)) {
7733 bdrv_graph_rdunlock_main_loop();
7737 bdrv_graph_rdunlock_main_loop();
7739 state
= g_new(BdrvStateSetAioContext
, 1);
7740 *state
= (BdrvStateSetAioContext
) {
7745 /* Paired with bdrv_drained_end in bdrv_set_aio_context_clean() */
7746 bdrv_drained_begin(bs
);
7748 tran_add(tran
, &set_aio_context
, state
);
7754 * Change bs's and recursively all of its parents' and children's AioContext
7755 * to the given new context, returning an error if that isn't possible.
7757 * If ignore_child is not NULL, that child (and its subgraph) will not
7760 * This function still requires the caller to take the bs current
7761 * AioContext lock, otherwise draining will fail since AIO_WAIT_WHILE
7762 * assumes the lock is always held if bs is in another AioContext.
7763 * For the same reason, it temporarily also holds the new AioContext, since
7764 * bdrv_drained_end calls BDRV_POLL_WHILE that assumes the lock is taken too.
7765 * Therefore the new AioContext lock must not be taken by the caller.
7767 int bdrv_try_change_aio_context(BlockDriverState
*bs
, AioContext
*ctx
,
7768 BdrvChild
*ignore_child
, Error
**errp
)
7771 GHashTable
*visited
;
7773 AioContext
*old_context
= bdrv_get_aio_context(bs
);
7774 GLOBAL_STATE_CODE();
7777 * Recursion phase: go through all nodes of the graph.
7778 * Take care of checking that all nodes support changing AioContext
7779 * and drain them, building a linear list of callbacks to run if everything
7780 * is successful (the transaction itself).
7783 visited
= g_hash_table_new(NULL
, NULL
);
7785 g_hash_table_add(visited
, ignore_child
);
7787 ret
= bdrv_change_aio_context(bs
, ctx
, visited
, tran
, errp
);
7788 g_hash_table_destroy(visited
);
7791 * Linear phase: go through all callbacks collected in the transaction.
7792 * Run all callbacks collected in the recursion to switch all nodes
7793 * AioContext lock (transaction commit), or undo all changes done in the
7794 * recursion (transaction abort).
7798 /* Just run clean() callbacks. No AioContext changed. */
7804 * Release old AioContext, it won't be needed anymore, as all
7805 * bdrv_drained_begin() have been called already.
7807 if (qemu_get_aio_context() != old_context
) {
7808 aio_context_release(old_context
);
7812 * Acquire new AioContext since bdrv_drained_end() is going to be called
7813 * after we switched all nodes in the new AioContext, and the function
7814 * assumes that the lock of the bs is always taken.
7816 if (qemu_get_aio_context() != ctx
) {
7817 aio_context_acquire(ctx
);
7822 if (qemu_get_aio_context() != ctx
) {
7823 aio_context_release(ctx
);
7826 /* Re-acquire the old AioContext, since the caller takes and releases it. */
7827 if (qemu_get_aio_context() != old_context
) {
7828 aio_context_acquire(old_context
);
7834 void bdrv_add_aio_context_notifier(BlockDriverState
*bs
,
7835 void (*attached_aio_context
)(AioContext
*new_context
, void *opaque
),
7836 void (*detach_aio_context
)(void *opaque
), void *opaque
)
7838 BdrvAioNotifier
*ban
= g_new(BdrvAioNotifier
, 1);
7839 *ban
= (BdrvAioNotifier
){
7840 .attached_aio_context
= attached_aio_context
,
7841 .detach_aio_context
= detach_aio_context
,
7844 GLOBAL_STATE_CODE();
7846 QLIST_INSERT_HEAD(&bs
->aio_notifiers
, ban
, list
);
7849 void bdrv_remove_aio_context_notifier(BlockDriverState
*bs
,
7850 void (*attached_aio_context
)(AioContext
*,
7852 void (*detach_aio_context
)(void *),
7855 BdrvAioNotifier
*ban
, *ban_next
;
7856 GLOBAL_STATE_CODE();
7858 QLIST_FOREACH_SAFE(ban
, &bs
->aio_notifiers
, list
, ban_next
) {
7859 if (ban
->attached_aio_context
== attached_aio_context
&&
7860 ban
->detach_aio_context
== detach_aio_context
&&
7861 ban
->opaque
== opaque
&&
7862 ban
->deleted
== false)
7864 if (bs
->walking_aio_notifiers
) {
7865 ban
->deleted
= true;
7867 bdrv_do_remove_aio_context_notifier(ban
);
7876 int bdrv_amend_options(BlockDriverState
*bs
, QemuOpts
*opts
,
7877 BlockDriverAmendStatusCB
*status_cb
, void *cb_opaque
,
7881 GLOBAL_STATE_CODE();
7883 error_setg(errp
, "Node is ejected");
7886 if (!bs
->drv
->bdrv_amend_options
) {
7887 error_setg(errp
, "Block driver '%s' does not support option amendment",
7888 bs
->drv
->format_name
);
7891 return bs
->drv
->bdrv_amend_options(bs
, opts
, status_cb
,
7892 cb_opaque
, force
, errp
);
7896 * This function checks whether the given @to_replace is allowed to be
7897 * replaced by a node that always shows the same data as @bs. This is
7898 * used for example to verify whether the mirror job can replace
7899 * @to_replace by the target mirrored from @bs.
7900 * To be replaceable, @bs and @to_replace may either be guaranteed to
7901 * always show the same data (because they are only connected through
7902 * filters), or some driver may allow replacing one of its children
7903 * because it can guarantee that this child's data is not visible at
7904 * all (for example, for dissenting quorum children that have no other
7907 bool bdrv_recurse_can_replace(BlockDriverState
*bs
,
7908 BlockDriverState
*to_replace
)
7910 BlockDriverState
*filtered
;
7912 GLOBAL_STATE_CODE();
7914 if (!bs
|| !bs
->drv
) {
7918 if (bs
== to_replace
) {
7922 /* See what the driver can do */
7923 if (bs
->drv
->bdrv_recurse_can_replace
) {
7924 return bs
->drv
->bdrv_recurse_can_replace(bs
, to_replace
);
7927 /* For filters without an own implementation, we can recurse on our own */
7928 filtered
= bdrv_filter_bs(bs
);
7930 return bdrv_recurse_can_replace(filtered
, to_replace
);
7938 * Check whether the given @node_name can be replaced by a node that
7939 * has the same data as @parent_bs. If so, return @node_name's BDS;
7942 * @node_name must be a (recursive) *child of @parent_bs (or this
7943 * function will return NULL).
7945 * The result (whether the node can be replaced or not) is only valid
7946 * for as long as no graph or permission changes occur.
7948 BlockDriverState
*check_to_replace_node(BlockDriverState
*parent_bs
,
7949 const char *node_name
, Error
**errp
)
7951 BlockDriverState
*to_replace_bs
= bdrv_find_node(node_name
);
7952 AioContext
*aio_context
;
7954 GLOBAL_STATE_CODE();
7956 if (!to_replace_bs
) {
7957 error_setg(errp
, "Failed to find node with node-name='%s'", node_name
);
7961 aio_context
= bdrv_get_aio_context(to_replace_bs
);
7962 aio_context_acquire(aio_context
);
7964 if (bdrv_op_is_blocked(to_replace_bs
, BLOCK_OP_TYPE_REPLACE
, errp
)) {
7965 to_replace_bs
= NULL
;
7969 /* We don't want arbitrary node of the BDS chain to be replaced only the top
7970 * most non filter in order to prevent data corruption.
7971 * Another benefit is that this tests exclude backing files which are
7972 * blocked by the backing blockers.
7974 if (!bdrv_recurse_can_replace(parent_bs
, to_replace_bs
)) {
7975 error_setg(errp
, "Cannot replace '%s' by a node mirrored from '%s', "
7976 "because it cannot be guaranteed that doing so would not "
7977 "lead to an abrupt change of visible data",
7978 node_name
, parent_bs
->node_name
);
7979 to_replace_bs
= NULL
;
7984 aio_context_release(aio_context
);
7985 return to_replace_bs
;
7989 * Iterates through the list of runtime option keys that are said to
7990 * be "strong" for a BDS. An option is called "strong" if it changes
7991 * a BDS's data. For example, the null block driver's "size" and
7992 * "read-zeroes" options are strong, but its "latency-ns" option is
7995 * If a key returned by this function ends with a dot, all options
7996 * starting with that prefix are strong.
7998 static const char *const *strong_options(BlockDriverState
*bs
,
7999 const char *const *curopt
)
8001 static const char *const global_options
[] = {
8002 "driver", "filename", NULL
8006 return &global_options
[0];
8010 if (curopt
== &global_options
[ARRAY_SIZE(global_options
) - 1] && bs
->drv
) {
8011 curopt
= bs
->drv
->strong_runtime_opts
;
8014 return (curopt
&& *curopt
) ? curopt
: NULL
;
8018 * Copies all strong runtime options from bs->options to the given
8019 * QDict. The set of strong option keys is determined by invoking
8022 * Returns true iff any strong option was present in bs->options (and
8023 * thus copied to the target QDict) with the exception of "filename"
8024 * and "driver". The caller is expected to use this value to decide
8025 * whether the existence of strong options prevents the generation of
8028 static bool append_strong_runtime_options(QDict
*d
, BlockDriverState
*bs
)
8030 bool found_any
= false;
8031 const char *const *option_name
= NULL
;
8037 while ((option_name
= strong_options(bs
, option_name
))) {
8038 bool option_given
= false;
8040 assert(strlen(*option_name
) > 0);
8041 if ((*option_name
)[strlen(*option_name
) - 1] != '.') {
8042 QObject
*entry
= qdict_get(bs
->options
, *option_name
);
8047 qdict_put_obj(d
, *option_name
, qobject_ref(entry
));
8048 option_given
= true;
8050 const QDictEntry
*entry
;
8051 for (entry
= qdict_first(bs
->options
); entry
;
8052 entry
= qdict_next(bs
->options
, entry
))
8054 if (strstart(qdict_entry_key(entry
), *option_name
, NULL
)) {
8055 qdict_put_obj(d
, qdict_entry_key(entry
),
8056 qobject_ref(qdict_entry_value(entry
)));
8057 option_given
= true;
8062 /* While "driver" and "filename" need to be included in a JSON filename,
8063 * their existence does not prohibit generation of a plain filename. */
8064 if (!found_any
&& option_given
&&
8065 strcmp(*option_name
, "driver") && strcmp(*option_name
, "filename"))
8071 if (!qdict_haskey(d
, "driver")) {
8072 /* Drivers created with bdrv_new_open_driver() may not have a
8073 * @driver option. Add it here. */
8074 qdict_put_str(d
, "driver", bs
->drv
->format_name
);
8080 /* Note: This function may return false positives; it may return true
8081 * even if opening the backing file specified by bs's image header
8082 * would result in exactly bs->backing. */
8083 static bool bdrv_backing_overridden(BlockDriverState
*bs
)
8085 GLOBAL_STATE_CODE();
8087 return strcmp(bs
->auto_backing_file
,
8088 bs
->backing
->bs
->filename
);
8090 /* No backing BDS, so if the image header reports any backing
8091 * file, it must have been suppressed */
8092 return bs
->auto_backing_file
[0] != '\0';
8096 /* Updates the following BDS fields:
8097 * - exact_filename: A filename which may be used for opening a block device
8098 * which (mostly) equals the given BDS (even without any
8099 * other options; so reading and writing must return the same
8100 * results, but caching etc. may be different)
8101 * - full_open_options: Options which, when given when opening a block device
8102 * (without a filename), result in a BDS (mostly)
8103 * equalling the given one
8104 * - filename: If exact_filename is set, it is copied here. Otherwise,
8105 * full_open_options is converted to a JSON object, prefixed with
8106 * "json:" (for use through the JSON pseudo protocol) and put here.
8108 void bdrv_refresh_filename(BlockDriverState
*bs
)
8110 BlockDriver
*drv
= bs
->drv
;
8112 BlockDriverState
*primary_child_bs
;
8114 bool backing_overridden
;
8115 bool generate_json_filename
; /* Whether our default implementation should
8116 fill exact_filename (false) or not (true) */
8118 GLOBAL_STATE_CODE();
8124 /* This BDS's file name may depend on any of its children's file names, so
8125 * refresh those first */
8126 QLIST_FOREACH(child
, &bs
->children
, next
) {
8127 bdrv_refresh_filename(child
->bs
);
8131 /* For implicit nodes, just copy everything from the single child */
8132 child
= QLIST_FIRST(&bs
->children
);
8133 assert(QLIST_NEXT(child
, next
) == NULL
);
8135 pstrcpy(bs
->exact_filename
, sizeof(bs
->exact_filename
),
8136 child
->bs
->exact_filename
);
8137 pstrcpy(bs
->filename
, sizeof(bs
->filename
), child
->bs
->filename
);
8139 qobject_unref(bs
->full_open_options
);
8140 bs
->full_open_options
= qobject_ref(child
->bs
->full_open_options
);
8145 backing_overridden
= bdrv_backing_overridden(bs
);
8147 if (bs
->open_flags
& BDRV_O_NO_IO
) {
8148 /* Without I/O, the backing file does not change anything.
8149 * Therefore, in such a case (primarily qemu-img), we can
8150 * pretend the backing file has not been overridden even if
8151 * it technically has been. */
8152 backing_overridden
= false;
8155 /* Gather the options QDict */
8157 generate_json_filename
= append_strong_runtime_options(opts
, bs
);
8158 generate_json_filename
|= backing_overridden
;
8160 if (drv
->bdrv_gather_child_options
) {
8161 /* Some block drivers may not want to present all of their children's
8162 * options, or name them differently from BdrvChild.name */
8163 drv
->bdrv_gather_child_options(bs
, opts
, backing_overridden
);
8165 QLIST_FOREACH(child
, &bs
->children
, next
) {
8166 if (child
== bs
->backing
&& !backing_overridden
) {
8167 /* We can skip the backing BDS if it has not been overridden */
8171 qdict_put(opts
, child
->name
,
8172 qobject_ref(child
->bs
->full_open_options
));
8175 if (backing_overridden
&& !bs
->backing
) {
8176 /* Force no backing file */
8177 qdict_put_null(opts
, "backing");
8181 qobject_unref(bs
->full_open_options
);
8182 bs
->full_open_options
= opts
;
8184 primary_child_bs
= bdrv_primary_bs(bs
);
8186 if (drv
->bdrv_refresh_filename
) {
8187 /* Obsolete information is of no use here, so drop the old file name
8188 * information before refreshing it */
8189 bs
->exact_filename
[0] = '\0';
8191 drv
->bdrv_refresh_filename(bs
);
8192 } else if (primary_child_bs
) {
8194 * Try to reconstruct valid information from the underlying
8195 * file -- this only works for format nodes (filter nodes
8196 * cannot be probed and as such must be selected by the user
8197 * either through an options dict, or through a special
8198 * filename which the filter driver must construct in its
8199 * .bdrv_refresh_filename() implementation).
8202 bs
->exact_filename
[0] = '\0';
8205 * We can use the underlying file's filename if:
8206 * - it has a filename,
8207 * - the current BDS is not a filter,
8208 * - the file is a protocol BDS, and
8209 * - opening that file (as this BDS's format) will automatically create
8210 * the BDS tree we have right now, that is:
8211 * - the user did not significantly change this BDS's behavior with
8212 * some explicit (strong) options
8213 * - no non-file child of this BDS has been overridden by the user
8214 * Both of these conditions are represented by generate_json_filename.
8216 if (primary_child_bs
->exact_filename
[0] &&
8217 primary_child_bs
->drv
->bdrv_file_open
&&
8218 !drv
->is_filter
&& !generate_json_filename
)
8220 strcpy(bs
->exact_filename
, primary_child_bs
->exact_filename
);
8224 if (bs
->exact_filename
[0]) {
8225 pstrcpy(bs
->filename
, sizeof(bs
->filename
), bs
->exact_filename
);
8227 GString
*json
= qobject_to_json(QOBJECT(bs
->full_open_options
));
8228 if (snprintf(bs
->filename
, sizeof(bs
->filename
), "json:%s",
8229 json
->str
) >= sizeof(bs
->filename
)) {
8230 /* Give user a hint if we truncated things. */
8231 strcpy(bs
->filename
+ sizeof(bs
->filename
) - 4, "...");
8233 g_string_free(json
, true);
8237 char *bdrv_dirname(BlockDriverState
*bs
, Error
**errp
)
8239 BlockDriver
*drv
= bs
->drv
;
8240 BlockDriverState
*child_bs
;
8242 GLOBAL_STATE_CODE();
8245 error_setg(errp
, "Node '%s' is ejected", bs
->node_name
);
8249 if (drv
->bdrv_dirname
) {
8250 return drv
->bdrv_dirname(bs
, errp
);
8253 child_bs
= bdrv_primary_bs(bs
);
8255 return bdrv_dirname(child_bs
, errp
);
8258 bdrv_refresh_filename(bs
);
8259 if (bs
->exact_filename
[0] != '\0') {
8260 return path_combine(bs
->exact_filename
, "");
8263 error_setg(errp
, "Cannot generate a base directory for %s nodes",
8269 * Hot add/remove a BDS's child. So the user can take a child offline when
8270 * it is broken and take a new child online
8272 void bdrv_add_child(BlockDriverState
*parent_bs
, BlockDriverState
*child_bs
,
8275 GLOBAL_STATE_CODE();
8276 if (!parent_bs
->drv
|| !parent_bs
->drv
->bdrv_add_child
) {
8277 error_setg(errp
, "The node %s does not support adding a child",
8278 bdrv_get_device_or_node_name(parent_bs
));
8283 * Non-zoned block drivers do not follow zoned storage constraints
8284 * (i.e. sequential writes to zones). Refuse mixing zoned and non-zoned
8285 * drivers in a graph.
8287 if (!parent_bs
->drv
->supports_zoned_children
&&
8288 child_bs
->bl
.zoned
== BLK_Z_HM
) {
8290 * The host-aware model allows zoned storage constraints and random
8291 * write. Allow mixing host-aware and non-zoned drivers. Using
8292 * host-aware device as a regular device.
8294 error_setg(errp
, "Cannot add a %s child to a %s parent",
8295 child_bs
->bl
.zoned
== BLK_Z_HM
? "zoned" : "non-zoned",
8296 parent_bs
->drv
->supports_zoned_children
?
8297 "support zoned children" : "not support zoned children");
8301 if (!QLIST_EMPTY(&child_bs
->parents
)) {
8302 error_setg(errp
, "The node %s already has a parent",
8303 child_bs
->node_name
);
8307 parent_bs
->drv
->bdrv_add_child(parent_bs
, child_bs
, errp
);
8310 void bdrv_del_child(BlockDriverState
*parent_bs
, BdrvChild
*child
, Error
**errp
)
8314 GLOBAL_STATE_CODE();
8315 if (!parent_bs
->drv
|| !parent_bs
->drv
->bdrv_del_child
) {
8316 error_setg(errp
, "The node %s does not support removing a child",
8317 bdrv_get_device_or_node_name(parent_bs
));
8321 QLIST_FOREACH(tmp
, &parent_bs
->children
, next
) {
8328 error_setg(errp
, "The node %s does not have a child named %s",
8329 bdrv_get_device_or_node_name(parent_bs
),
8330 bdrv_get_device_or_node_name(child
->bs
));
8334 parent_bs
->drv
->bdrv_del_child(parent_bs
, child
, errp
);
8337 int bdrv_make_empty(BdrvChild
*c
, Error
**errp
)
8339 BlockDriver
*drv
= c
->bs
->drv
;
8342 GLOBAL_STATE_CODE();
8343 assert(c
->perm
& (BLK_PERM_WRITE
| BLK_PERM_WRITE_UNCHANGED
));
8345 if (!drv
->bdrv_make_empty
) {
8346 error_setg(errp
, "%s does not support emptying nodes",
8351 ret
= drv
->bdrv_make_empty(c
->bs
);
8353 error_setg_errno(errp
, -ret
, "Failed to empty %s",
8362 * Return the child that @bs acts as an overlay for, and from which data may be
8363 * copied in COW or COR operations. Usually this is the backing file.
8365 BdrvChild
*bdrv_cow_child(BlockDriverState
*bs
)
8369 if (!bs
|| !bs
->drv
) {
8373 if (bs
->drv
->is_filter
) {
8381 assert(bs
->backing
->role
& BDRV_CHILD_COW
);
8386 * If @bs acts as a filter for exactly one of its children, return
8389 BdrvChild
*bdrv_filter_child(BlockDriverState
*bs
)
8394 if (!bs
|| !bs
->drv
) {
8398 if (!bs
->drv
->is_filter
) {
8402 /* Only one of @backing or @file may be used */
8403 assert(!(bs
->backing
&& bs
->file
));
8405 c
= bs
->backing
?: bs
->file
;
8410 assert(c
->role
& BDRV_CHILD_FILTERED
);
8415 * Return either the result of bdrv_cow_child() or bdrv_filter_child(),
8416 * whichever is non-NULL.
8418 * Return NULL if both are NULL.
8420 BdrvChild
*bdrv_filter_or_cow_child(BlockDriverState
*bs
)
8422 BdrvChild
*cow_child
= bdrv_cow_child(bs
);
8423 BdrvChild
*filter_child
= bdrv_filter_child(bs
);
8426 /* Filter nodes cannot have COW backing files */
8427 assert(!(cow_child
&& filter_child
));
8429 return cow_child
?: filter_child
;
8433 * Return the primary child of this node: For filters, that is the
8434 * filtered child. For other nodes, that is usually the child storing
8436 * (A generally more helpful description is that this is (usually) the
8437 * child that has the same filename as @bs.)
8439 * Drivers do not necessarily have a primary child; for example quorum
8442 BdrvChild
*bdrv_primary_child(BlockDriverState
*bs
)
8444 BdrvChild
*c
, *found
= NULL
;
8447 QLIST_FOREACH(c
, &bs
->children
, next
) {
8448 if (c
->role
& BDRV_CHILD_PRIMARY
) {
8457 static BlockDriverState
*bdrv_do_skip_filters(BlockDriverState
*bs
,
8458 bool stop_on_explicit_filter
)
8466 while (!(stop_on_explicit_filter
&& !bs
->implicit
)) {
8467 c
= bdrv_filter_child(bs
);
8470 * A filter that is embedded in a working block graph must
8471 * have a child. Assert this here so this function does
8472 * not return a filter node that is not expected by the
8475 assert(!bs
->drv
|| !bs
->drv
->is_filter
);
8481 * Note that this treats nodes with bs->drv == NULL as not being
8482 * filters (bs->drv == NULL should be replaced by something else
8484 * The advantage of this behavior is that this function will thus
8485 * always return a non-NULL value (given a non-NULL @bs).
8492 * Return the first BDS that has not been added implicitly or that
8493 * does not have a filtered child down the chain starting from @bs
8494 * (including @bs itself).
8496 BlockDriverState
*bdrv_skip_implicit_filters(BlockDriverState
*bs
)
8498 GLOBAL_STATE_CODE();
8499 return bdrv_do_skip_filters(bs
, true);
8503 * Return the first BDS that does not have a filtered child down the
8504 * chain starting from @bs (including @bs itself).
8506 BlockDriverState
*bdrv_skip_filters(BlockDriverState
*bs
)
8509 return bdrv_do_skip_filters(bs
, false);
8513 * For a backing chain, return the first non-filter backing image of
8514 * the first non-filter image.
8516 BlockDriverState
*bdrv_backing_chain_next(BlockDriverState
*bs
)
8519 return bdrv_skip_filters(bdrv_cow_bs(bdrv_skip_filters(bs
)));
8523 * Check whether [offset, offset + bytes) overlaps with the cached
8524 * block-status data region.
8526 * If so, and @pnum is not NULL, set *pnum to `bsc.data_end - offset`,
8527 * which is what bdrv_bsc_is_data()'s interface needs.
8528 * Otherwise, *pnum is not touched.
8530 static bool bdrv_bsc_range_overlaps_locked(BlockDriverState
*bs
,
8531 int64_t offset
, int64_t bytes
,
8534 BdrvBlockStatusCache
*bsc
= qatomic_rcu_read(&bs
->block_status_cache
);
8538 qatomic_read(&bsc
->valid
) &&
8539 ranges_overlap(offset
, bytes
, bsc
->data_start
,
8540 bsc
->data_end
- bsc
->data_start
);
8542 if (overlaps
&& pnum
) {
8543 *pnum
= bsc
->data_end
- offset
;
8550 * See block_int.h for this function's documentation.
8552 bool bdrv_bsc_is_data(BlockDriverState
*bs
, int64_t offset
, int64_t *pnum
)
8555 RCU_READ_LOCK_GUARD();
8556 return bdrv_bsc_range_overlaps_locked(bs
, offset
, 1, pnum
);
8560 * See block_int.h for this function's documentation.
8562 void bdrv_bsc_invalidate_range(BlockDriverState
*bs
,
8563 int64_t offset
, int64_t bytes
)
8566 RCU_READ_LOCK_GUARD();
8568 if (bdrv_bsc_range_overlaps_locked(bs
, offset
, bytes
, NULL
)) {
8569 qatomic_set(&bs
->block_status_cache
->valid
, false);
8574 * See block_int.h for this function's documentation.
8576 void bdrv_bsc_fill(BlockDriverState
*bs
, int64_t offset
, int64_t bytes
)
8578 BdrvBlockStatusCache
*new_bsc
= g_new(BdrvBlockStatusCache
, 1);
8579 BdrvBlockStatusCache
*old_bsc
;
8582 *new_bsc
= (BdrvBlockStatusCache
) {
8584 .data_start
= offset
,
8585 .data_end
= offset
+ bytes
,
8588 QEMU_LOCK_GUARD(&bs
->bsc_modify_lock
);
8590 old_bsc
= qatomic_rcu_read(&bs
->block_status_cache
);
8591 qatomic_rcu_set(&bs
->block_status_cache
, new_bsc
);
8593 g_free_rcu(old_bsc
, rcu
);