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/fuse.h"
31 #include "block/nbd.h"
32 #include "block/qdict.h"
33 #include "qemu/error-report.h"
34 #include "block/module_block.h"
35 #include "qemu/main-loop.h"
36 #include "qemu/module.h"
37 #include "qapi/error.h"
38 #include "qapi/qmp/qdict.h"
39 #include "qapi/qmp/qjson.h"
40 #include "qapi/qmp/qnull.h"
41 #include "qapi/qmp/qstring.h"
42 #include "qapi/qobject-output-visitor.h"
43 #include "qapi/qapi-visit-block-core.h"
44 #include "sysemu/block-backend.h"
45 #include "qemu/notify.h"
46 #include "qemu/option.h"
47 #include "qemu/coroutine.h"
48 #include "block/qapi.h"
49 #include "qemu/timer.h"
50 #include "qemu/cutils.h"
52 #include "qemu/range.h"
54 #include "block/coroutines.h"
57 #include <sys/ioctl.h>
58 #include <sys/queue.h>
59 #if defined(HAVE_SYS_DISK_H)
68 #define NOT_DONE 0x7fffffff /* used while emulated sync operation in progress */
70 /* Protected by BQL */
71 static QTAILQ_HEAD(, BlockDriverState
) graph_bdrv_states
=
72 QTAILQ_HEAD_INITIALIZER(graph_bdrv_states
);
74 /* Protected by BQL */
75 static QTAILQ_HEAD(, BlockDriverState
) all_bdrv_states
=
76 QTAILQ_HEAD_INITIALIZER(all_bdrv_states
);
78 /* Protected by BQL */
79 static QLIST_HEAD(, BlockDriver
) bdrv_drivers
=
80 QLIST_HEAD_INITIALIZER(bdrv_drivers
);
82 static BlockDriverState
*bdrv_open_inherit(const char *filename
,
83 const char *reference
,
84 QDict
*options
, int flags
,
85 BlockDriverState
*parent
,
86 const BdrvChildClass
*child_class
,
87 BdrvChildRole child_role
,
90 static bool bdrv_recurse_has_child(BlockDriverState
*bs
,
91 BlockDriverState
*child
);
93 static void bdrv_replace_child_noperm(BdrvChild
*child
,
94 BlockDriverState
*new_bs
);
95 static void bdrv_remove_child(BdrvChild
*child
, Transaction
*tran
);
97 static int bdrv_reopen_prepare(BDRVReopenState
*reopen_state
,
98 BlockReopenQueue
*queue
,
99 Transaction
*change_child_tran
, Error
**errp
);
100 static void bdrv_reopen_commit(BDRVReopenState
*reopen_state
);
101 static void bdrv_reopen_abort(BDRVReopenState
*reopen_state
);
103 static bool bdrv_backing_overridden(BlockDriverState
*bs
);
105 static bool bdrv_change_aio_context(BlockDriverState
*bs
, AioContext
*ctx
,
106 GHashTable
*visited
, Transaction
*tran
,
109 /* If non-zero, use only whitelisted block drivers */
110 static int use_bdrv_whitelist
;
113 static int is_windows_drive_prefix(const char *filename
)
115 return (((filename
[0] >= 'a' && filename
[0] <= 'z') ||
116 (filename
[0] >= 'A' && filename
[0] <= 'Z')) &&
120 int is_windows_drive(const char *filename
)
122 if (is_windows_drive_prefix(filename
) &&
125 if (strstart(filename
, "\\\\.\\", NULL
) ||
126 strstart(filename
, "//./", NULL
))
132 size_t bdrv_opt_mem_align(BlockDriverState
*bs
)
134 if (!bs
|| !bs
->drv
) {
135 /* page size or 4k (hdd sector size) should be on the safe side */
136 return MAX(4096, qemu_real_host_page_size());
140 return bs
->bl
.opt_mem_alignment
;
143 size_t bdrv_min_mem_align(BlockDriverState
*bs
)
145 if (!bs
|| !bs
->drv
) {
146 /* page size or 4k (hdd sector size) should be on the safe side */
147 return MAX(4096, qemu_real_host_page_size());
151 return bs
->bl
.min_mem_alignment
;
154 /* check if the path starts with "<protocol>:" */
155 int path_has_protocol(const char *path
)
160 if (is_windows_drive(path
) ||
161 is_windows_drive_prefix(path
)) {
164 p
= path
+ strcspn(path
, ":/\\");
166 p
= path
+ strcspn(path
, ":/");
172 int path_is_absolute(const char *path
)
175 /* specific case for names like: "\\.\d:" */
176 if (is_windows_drive(path
) || is_windows_drive_prefix(path
)) {
179 return (*path
== '/' || *path
== '\\');
181 return (*path
== '/');
185 /* if filename is absolute, just return its duplicate. Otherwise, build a
186 path to it by considering it is relative to base_path. URL are
188 char *path_combine(const char *base_path
, const char *filename
)
190 const char *protocol_stripped
= NULL
;
195 if (path_is_absolute(filename
)) {
196 return g_strdup(filename
);
199 if (path_has_protocol(base_path
)) {
200 protocol_stripped
= strchr(base_path
, ':');
201 if (protocol_stripped
) {
205 p
= protocol_stripped
?: base_path
;
207 p1
= strrchr(base_path
, '/');
211 p2
= strrchr(base_path
, '\\');
212 if (!p1
|| p2
> p1
) {
227 result
= g_malloc(len
+ strlen(filename
) + 1);
228 memcpy(result
, base_path
, len
);
229 strcpy(result
+ len
, filename
);
235 * Helper function for bdrv_parse_filename() implementations to remove optional
236 * protocol prefixes (especially "file:") from a filename and for putting the
237 * stripped filename into the options QDict if there is such a prefix.
239 void bdrv_parse_filename_strip_prefix(const char *filename
, const char *prefix
,
242 if (strstart(filename
, prefix
, &filename
)) {
243 /* Stripping the explicit protocol prefix may result in a protocol
244 * prefix being (wrongly) detected (if the filename contains a colon) */
245 if (path_has_protocol(filename
)) {
246 GString
*fat_filename
;
248 /* This means there is some colon before the first slash; therefore,
249 * this cannot be an absolute path */
250 assert(!path_is_absolute(filename
));
252 /* And we can thus fix the protocol detection issue by prefixing it
254 fat_filename
= g_string_new("./");
255 g_string_append(fat_filename
, filename
);
257 assert(!path_has_protocol(fat_filename
->str
));
259 qdict_put(options
, "filename",
260 qstring_from_gstring(fat_filename
));
262 /* If no protocol prefix was detected, we can use the shortened
264 qdict_put_str(options
, "filename", filename
);
270 /* Returns whether the image file is opened as read-only. Note that this can
271 * return false and writing to the image file is still not possible because the
272 * image is inactivated. */
273 bool bdrv_is_read_only(BlockDriverState
*bs
)
276 return !(bs
->open_flags
& BDRV_O_RDWR
);
279 int bdrv_can_set_read_only(BlockDriverState
*bs
, bool read_only
,
280 bool ignore_allow_rdw
, Error
**errp
)
284 /* Do not set read_only if copy_on_read is enabled */
285 if (bs
->copy_on_read
&& read_only
) {
286 error_setg(errp
, "Can't set node '%s' to r/o with copy-on-read enabled",
287 bdrv_get_device_or_node_name(bs
));
291 /* Do not clear read_only if it is prohibited */
292 if (!read_only
&& !(bs
->open_flags
& BDRV_O_ALLOW_RDWR
) &&
295 error_setg(errp
, "Node '%s' is read only",
296 bdrv_get_device_or_node_name(bs
));
304 * Called by a driver that can only provide a read-only image.
306 * Returns 0 if the node is already read-only or it could switch the node to
307 * read-only because BDRV_O_AUTO_RDONLY is set.
309 * Returns -EACCES if the node is read-write and BDRV_O_AUTO_RDONLY is not set
310 * or bdrv_can_set_read_only() forbids making the node read-only. If @errmsg
311 * is not NULL, it is used as the error message for the Error object.
313 int bdrv_apply_auto_read_only(BlockDriverState
*bs
, const char *errmsg
,
319 if (!(bs
->open_flags
& BDRV_O_RDWR
)) {
322 if (!(bs
->open_flags
& BDRV_O_AUTO_RDONLY
)) {
326 ret
= bdrv_can_set_read_only(bs
, true, false, NULL
);
331 bs
->open_flags
&= ~BDRV_O_RDWR
;
336 error_setg(errp
, "%s", errmsg
?: "Image is read-only");
341 * If @backing is empty, this function returns NULL without setting
342 * @errp. In all other cases, NULL will only be returned with @errp
345 * Therefore, a return value of NULL without @errp set means that
346 * there is no backing file; if @errp is set, there is one but its
347 * absolute filename cannot be generated.
349 char *bdrv_get_full_backing_filename_from_filename(const char *backed
,
353 if (backing
[0] == '\0') {
355 } else if (path_has_protocol(backing
) || path_is_absolute(backing
)) {
356 return g_strdup(backing
);
357 } else if (backed
[0] == '\0' || strstart(backed
, "json:", NULL
)) {
358 error_setg(errp
, "Cannot use relative backing file names for '%s'",
362 return path_combine(backed
, backing
);
367 * If @filename is empty or NULL, this function returns NULL without
368 * setting @errp. In all other cases, NULL will only be returned with
371 static char *bdrv_make_absolute_filename(BlockDriverState
*relative_to
,
372 const char *filename
, Error
**errp
)
374 char *dir
, *full_name
;
376 if (!filename
|| filename
[0] == '\0') {
378 } else if (path_has_protocol(filename
) || path_is_absolute(filename
)) {
379 return g_strdup(filename
);
382 dir
= bdrv_dirname(relative_to
, errp
);
387 full_name
= g_strconcat(dir
, filename
, NULL
);
392 char *bdrv_get_full_backing_filename(BlockDriverState
*bs
, Error
**errp
)
395 return bdrv_make_absolute_filename(bs
, bs
->backing_file
, errp
);
398 void bdrv_register(BlockDriver
*bdrv
)
400 assert(bdrv
->format_name
);
402 QLIST_INSERT_HEAD(&bdrv_drivers
, bdrv
, list
);
405 BlockDriverState
*bdrv_new(void)
407 BlockDriverState
*bs
;
412 bs
= g_new0(BlockDriverState
, 1);
413 QLIST_INIT(&bs
->dirty_bitmaps
);
414 for (i
= 0; i
< BLOCK_OP_TYPE_MAX
; i
++) {
415 QLIST_INIT(&bs
->op_blockers
[i
]);
417 qemu_co_mutex_init(&bs
->reqs_lock
);
418 qemu_mutex_init(&bs
->dirty_bitmap_mutex
);
420 bs
->aio_context
= qemu_get_aio_context();
422 qemu_co_queue_init(&bs
->flush_queue
);
424 qemu_co_mutex_init(&bs
->bsc_modify_lock
);
425 bs
->block_status_cache
= g_new0(BdrvBlockStatusCache
, 1);
427 for (i
= 0; i
< bdrv_drain_all_count
; i
++) {
428 bdrv_drained_begin(bs
);
431 QTAILQ_INSERT_TAIL(&all_bdrv_states
, bs
, bs_list
);
436 static BlockDriver
*bdrv_do_find_format(const char *format_name
)
441 QLIST_FOREACH(drv1
, &bdrv_drivers
, list
) {
442 if (!strcmp(drv1
->format_name
, format_name
)) {
450 BlockDriver
*bdrv_find_format(const char *format_name
)
457 drv1
= bdrv_do_find_format(format_name
);
462 /* The driver isn't registered, maybe we need to load a module */
463 for (i
= 0; i
< (int)ARRAY_SIZE(block_driver_modules
); ++i
) {
464 if (!strcmp(block_driver_modules
[i
].format_name
, format_name
)) {
465 Error
*local_err
= NULL
;
466 int rv
= block_module_load(block_driver_modules
[i
].library_name
,
469 return bdrv_do_find_format(format_name
);
471 error_report_err(local_err
);
479 static int bdrv_format_is_whitelisted(const char *format_name
, bool read_only
)
481 static const char *whitelist_rw
[] = {
482 CONFIG_BDRV_RW_WHITELIST
485 static const char *whitelist_ro
[] = {
486 CONFIG_BDRV_RO_WHITELIST
491 if (!whitelist_rw
[0] && !whitelist_ro
[0]) {
492 return 1; /* no whitelist, anything goes */
495 for (p
= whitelist_rw
; *p
; p
++) {
496 if (!strcmp(format_name
, *p
)) {
501 for (p
= whitelist_ro
; *p
; p
++) {
502 if (!strcmp(format_name
, *p
)) {
510 int bdrv_is_whitelisted(BlockDriver
*drv
, bool read_only
)
513 return bdrv_format_is_whitelisted(drv
->format_name
, read_only
);
516 bool bdrv_uses_whitelist(void)
518 return use_bdrv_whitelist
;
521 typedef struct CreateCo
{
529 static void coroutine_fn
bdrv_create_co_entry(void *opaque
)
531 Error
*local_err
= NULL
;
534 CreateCo
*cco
= opaque
;
538 ret
= cco
->drv
->bdrv_co_create_opts(cco
->drv
,
539 cco
->filename
, cco
->opts
, &local_err
);
540 error_propagate(&cco
->err
, local_err
);
544 int bdrv_create(BlockDriver
*drv
, const char* filename
,
545 QemuOpts
*opts
, Error
**errp
)
554 .filename
= g_strdup(filename
),
560 if (!drv
->bdrv_co_create_opts
) {
561 error_setg(errp
, "Driver '%s' does not support image creation", drv
->format_name
);
566 if (qemu_in_coroutine()) {
567 /* Fast-path if already in coroutine context */
568 bdrv_create_co_entry(&cco
);
570 co
= qemu_coroutine_create(bdrv_create_co_entry
, &cco
);
571 qemu_coroutine_enter(co
);
572 while (cco
.ret
== NOT_DONE
) {
573 aio_poll(qemu_get_aio_context(), true);
580 error_propagate(errp
, cco
.err
);
582 error_setg_errno(errp
, -ret
, "Could not create image");
587 g_free(cco
.filename
);
592 * Helper function for bdrv_create_file_fallback(): Resize @blk to at
593 * least the given @minimum_size.
595 * On success, return @blk's actual length.
596 * Otherwise, return -errno.
598 static int64_t create_file_fallback_truncate(BlockBackend
*blk
,
599 int64_t minimum_size
, Error
**errp
)
601 Error
*local_err
= NULL
;
607 ret
= blk_truncate(blk
, minimum_size
, false, PREALLOC_MODE_OFF
, 0,
609 if (ret
< 0 && ret
!= -ENOTSUP
) {
610 error_propagate(errp
, local_err
);
614 size
= blk_getlength(blk
);
616 error_free(local_err
);
617 error_setg_errno(errp
, -size
,
618 "Failed to inquire the new image file's length");
622 if (size
< minimum_size
) {
623 /* Need to grow the image, but we failed to do that */
624 error_propagate(errp
, local_err
);
628 error_free(local_err
);
635 * Helper function for bdrv_create_file_fallback(): Zero the first
636 * sector to remove any potentially pre-existing image header.
638 static int coroutine_fn
639 create_file_fallback_zero_first_sector(BlockBackend
*blk
,
640 int64_t current_size
,
643 int64_t bytes_to_clear
;
648 bytes_to_clear
= MIN(current_size
, BDRV_SECTOR_SIZE
);
649 if (bytes_to_clear
) {
650 ret
= blk_co_pwrite_zeroes(blk
, 0, bytes_to_clear
, BDRV_REQ_MAY_UNMAP
);
652 error_setg_errno(errp
, -ret
,
653 "Failed to clear the new image's first sector");
662 * Simple implementation of bdrv_co_create_opts for protocol drivers
663 * which only support creation via opening a file
664 * (usually existing raw storage device)
666 int coroutine_fn
bdrv_co_create_opts_simple(BlockDriver
*drv
,
667 const char *filename
,
675 PreallocMode prealloc
;
676 Error
*local_err
= NULL
;
681 size
= qemu_opt_get_size_del(opts
, BLOCK_OPT_SIZE
, 0);
682 buf
= qemu_opt_get_del(opts
, BLOCK_OPT_PREALLOC
);
683 prealloc
= qapi_enum_parse(&PreallocMode_lookup
, buf
,
684 PREALLOC_MODE_OFF
, &local_err
);
687 error_propagate(errp
, local_err
);
691 if (prealloc
!= PREALLOC_MODE_OFF
) {
692 error_setg(errp
, "Unsupported preallocation mode '%s'",
693 PreallocMode_str(prealloc
));
697 options
= qdict_new();
698 qdict_put_str(options
, "driver", drv
->format_name
);
700 blk
= blk_new_open(filename
, NULL
, options
,
701 BDRV_O_RDWR
| BDRV_O_RESIZE
, errp
);
703 error_prepend(errp
, "Protocol driver '%s' does not support image "
704 "creation, and opening the image failed: ",
709 size
= create_file_fallback_truncate(blk
, size
, errp
);
715 ret
= create_file_fallback_zero_first_sector(blk
, size
, errp
);
726 int bdrv_create_file(const char *filename
, QemuOpts
*opts
, Error
**errp
)
728 QemuOpts
*protocol_opts
;
735 drv
= bdrv_find_protocol(filename
, true, errp
);
740 if (!drv
->create_opts
) {
741 error_setg(errp
, "Driver '%s' does not support image creation",
747 * 'opts' contains a QemuOptsList with a combination of format and protocol
750 * The format properly removes its options, but the default values remain
751 * in 'opts->list'. So if the protocol has options with the same name
752 * (e.g. rbd has 'cluster_size' as qcow2), it will see the default values
753 * of the format, since for overlapping options, the format wins.
755 * To avoid this issue, lets convert QemuOpts to QDict, in this way we take
756 * only the set options, and then convert it back to QemuOpts, using the
757 * create_opts of the protocol. So the new QemuOpts, will contain only the
760 qdict
= qemu_opts_to_qdict(opts
, NULL
);
761 protocol_opts
= qemu_opts_from_qdict(drv
->create_opts
, qdict
, errp
);
762 if (protocol_opts
== NULL
) {
767 ret
= bdrv_create(drv
, filename
, protocol_opts
, errp
);
769 qemu_opts_del(protocol_opts
);
770 qobject_unref(qdict
);
774 int coroutine_fn
bdrv_co_delete_file(BlockDriverState
*bs
, Error
**errp
)
776 Error
*local_err
= NULL
;
783 error_setg(errp
, "Block node '%s' is not opened", bs
->filename
);
787 if (!bs
->drv
->bdrv_co_delete_file
) {
788 error_setg(errp
, "Driver '%s' does not support image deletion",
789 bs
->drv
->format_name
);
793 ret
= bs
->drv
->bdrv_co_delete_file(bs
, &local_err
);
795 error_propagate(errp
, local_err
);
801 void coroutine_fn
bdrv_co_delete_file_noerr(BlockDriverState
*bs
)
803 Error
*local_err
= NULL
;
811 ret
= bdrv_co_delete_file(bs
, &local_err
);
813 * ENOTSUP will happen if the block driver doesn't support
814 * the 'bdrv_co_delete_file' interface. This is a predictable
815 * scenario and shouldn't be reported back to the user.
817 if (ret
== -ENOTSUP
) {
818 error_free(local_err
);
819 } else if (ret
< 0) {
820 error_report_err(local_err
);
825 * Try to get @bs's logical and physical block size.
826 * On success, store them in @bsz struct and return 0.
827 * On failure return -errno.
828 * @bs must not be empty.
830 int bdrv_probe_blocksizes(BlockDriverState
*bs
, BlockSizes
*bsz
)
832 BlockDriver
*drv
= bs
->drv
;
833 BlockDriverState
*filtered
= bdrv_filter_bs(bs
);
836 if (drv
&& drv
->bdrv_probe_blocksizes
) {
837 return drv
->bdrv_probe_blocksizes(bs
, bsz
);
838 } else if (filtered
) {
839 return bdrv_probe_blocksizes(filtered
, bsz
);
846 * Try to get @bs's geometry (cyls, heads, sectors).
847 * On success, store them in @geo struct and return 0.
848 * On failure return -errno.
849 * @bs must not be empty.
851 int bdrv_probe_geometry(BlockDriverState
*bs
, HDGeometry
*geo
)
853 BlockDriver
*drv
= bs
->drv
;
854 BlockDriverState
*filtered
= bdrv_filter_bs(bs
);
857 if (drv
&& drv
->bdrv_probe_geometry
) {
858 return drv
->bdrv_probe_geometry(bs
, geo
);
859 } else if (filtered
) {
860 return bdrv_probe_geometry(filtered
, geo
);
867 * Create a uniquely-named empty temporary file.
868 * Return the actual file name used upon success, otherwise NULL.
869 * This string should be freed with g_free() when not needed any longer.
871 * Note: creating a temporary file for the caller to (re)open is
872 * inherently racy. Use g_file_open_tmp() instead whenever practical.
874 char *create_tmp_file(Error
**errp
)
878 g_autofree
char *filename
= NULL
;
880 tmpdir
= g_get_tmp_dir();
883 * See commit 69bef79 ("block: use /var/tmp instead of /tmp for -snapshot")
885 * This function is used to create temporary disk images (like -snapshot),
886 * so the files can become very large. /tmp is often a tmpfs where as
887 * /var/tmp is usually on a disk, so more appropriate for disk images.
889 if (!g_strcmp0(tmpdir
, "/tmp")) {
894 filename
= g_strdup_printf("%s/vl.XXXXXX", tmpdir
);
895 fd
= g_mkstemp(filename
);
897 error_setg_errno(errp
, errno
, "Could not open temporary file '%s'",
903 return g_steal_pointer(&filename
);
907 * Detect host devices. By convention, /dev/cdrom[N] is always
908 * recognized as a host CDROM.
910 static BlockDriver
*find_hdev_driver(const char *filename
)
912 int score_max
= 0, score
;
913 BlockDriver
*drv
= NULL
, *d
;
916 QLIST_FOREACH(d
, &bdrv_drivers
, list
) {
917 if (d
->bdrv_probe_device
) {
918 score
= d
->bdrv_probe_device(filename
);
919 if (score
> score_max
) {
929 static BlockDriver
*bdrv_do_find_protocol(const char *protocol
)
934 QLIST_FOREACH(drv1
, &bdrv_drivers
, list
) {
935 if (drv1
->protocol_name
&& !strcmp(drv1
->protocol_name
, protocol
)) {
943 BlockDriver
*bdrv_find_protocol(const char *filename
,
944 bool allow_protocol_prefix
,
954 /* TODO Drivers without bdrv_file_open must be specified explicitly */
957 * XXX(hch): we really should not let host device detection
958 * override an explicit protocol specification, but moving this
959 * later breaks access to device names with colons in them.
960 * Thanks to the brain-dead persistent naming schemes on udev-
961 * based Linux systems those actually are quite common.
963 drv1
= find_hdev_driver(filename
);
968 if (!path_has_protocol(filename
) || !allow_protocol_prefix
) {
972 p
= strchr(filename
, ':');
975 if (len
> sizeof(protocol
) - 1)
976 len
= sizeof(protocol
) - 1;
977 memcpy(protocol
, filename
, len
);
978 protocol
[len
] = '\0';
980 drv1
= bdrv_do_find_protocol(protocol
);
985 for (i
= 0; i
< (int)ARRAY_SIZE(block_driver_modules
); ++i
) {
986 if (block_driver_modules
[i
].protocol_name
&&
987 !strcmp(block_driver_modules
[i
].protocol_name
, protocol
)) {
988 int rv
= block_module_load(block_driver_modules
[i
].library_name
, errp
);
990 drv1
= bdrv_do_find_protocol(protocol
);
999 error_setg(errp
, "Unknown protocol '%s'", protocol
);
1005 * Guess image format by probing its contents.
1006 * This is not a good idea when your image is raw (CVE-2008-2004), but
1007 * we do it anyway for backward compatibility.
1009 * @buf contains the image's first @buf_size bytes.
1010 * @buf_size is the buffer size in bytes (generally BLOCK_PROBE_BUF_SIZE,
1011 * but can be smaller if the image file is smaller)
1012 * @filename is its filename.
1014 * For all block drivers, call the bdrv_probe() method to get its
1016 * Return the first block driver with the highest probing score.
1018 BlockDriver
*bdrv_probe_all(const uint8_t *buf
, int buf_size
,
1019 const char *filename
)
1021 int score_max
= 0, score
;
1022 BlockDriver
*drv
= NULL
, *d
;
1025 QLIST_FOREACH(d
, &bdrv_drivers
, list
) {
1026 if (d
->bdrv_probe
) {
1027 score
= d
->bdrv_probe(buf
, buf_size
, filename
);
1028 if (score
> score_max
) {
1038 static int find_image_format(BlockBackend
*file
, const char *filename
,
1039 BlockDriver
**pdrv
, Error
**errp
)
1042 uint8_t buf
[BLOCK_PROBE_BUF_SIZE
];
1045 GLOBAL_STATE_CODE();
1047 /* Return the raw BlockDriver * to scsi-generic devices or empty drives */
1048 if (blk_is_sg(file
) || !blk_is_inserted(file
) || blk_getlength(file
) == 0) {
1053 ret
= blk_pread(file
, 0, sizeof(buf
), buf
, 0);
1055 error_setg_errno(errp
, -ret
, "Could not read image for determining its "
1061 drv
= bdrv_probe_all(buf
, sizeof(buf
), filename
);
1063 error_setg(errp
, "Could not determine image format: No compatible "
1074 * Set the current 'total_sectors' value
1075 * Return 0 on success, -errno on error.
1077 int refresh_total_sectors(BlockDriverState
*bs
, int64_t hint
)
1079 BlockDriver
*drv
= bs
->drv
;
1086 /* Do not attempt drv->bdrv_getlength() on scsi-generic devices */
1090 /* query actual device if possible, otherwise just trust the hint */
1091 if (drv
->bdrv_getlength
) {
1092 int64_t length
= drv
->bdrv_getlength(bs
);
1096 hint
= DIV_ROUND_UP(length
, BDRV_SECTOR_SIZE
);
1099 bs
->total_sectors
= hint
;
1101 if (bs
->total_sectors
* BDRV_SECTOR_SIZE
> BDRV_MAX_LENGTH
) {
1109 * Combines a QDict of new block driver @options with any missing options taken
1110 * from @old_options, so that leaving out an option defaults to its old value.
1112 static void bdrv_join_options(BlockDriverState
*bs
, QDict
*options
,
1115 GLOBAL_STATE_CODE();
1116 if (bs
->drv
&& bs
->drv
->bdrv_join_options
) {
1117 bs
->drv
->bdrv_join_options(options
, old_options
);
1119 qdict_join(options
, old_options
, false);
1123 static BlockdevDetectZeroesOptions
bdrv_parse_detect_zeroes(QemuOpts
*opts
,
1127 Error
*local_err
= NULL
;
1128 char *value
= qemu_opt_get_del(opts
, "detect-zeroes");
1129 BlockdevDetectZeroesOptions detect_zeroes
=
1130 qapi_enum_parse(&BlockdevDetectZeroesOptions_lookup
, value
,
1131 BLOCKDEV_DETECT_ZEROES_OPTIONS_OFF
, &local_err
);
1132 GLOBAL_STATE_CODE();
1135 error_propagate(errp
, local_err
);
1136 return detect_zeroes
;
1139 if (detect_zeroes
== BLOCKDEV_DETECT_ZEROES_OPTIONS_UNMAP
&&
1140 !(open_flags
& BDRV_O_UNMAP
))
1142 error_setg(errp
, "setting detect-zeroes to unmap is not allowed "
1143 "without setting discard operation to unmap");
1146 return detect_zeroes
;
1150 * Set open flags for aio engine
1152 * Return 0 on success, -1 if the engine specified is invalid
1154 int bdrv_parse_aio(const char *mode
, int *flags
)
1156 if (!strcmp(mode
, "threads")) {
1157 /* do nothing, default */
1158 } else if (!strcmp(mode
, "native")) {
1159 *flags
|= BDRV_O_NATIVE_AIO
;
1160 #ifdef CONFIG_LINUX_IO_URING
1161 } else if (!strcmp(mode
, "io_uring")) {
1162 *flags
|= BDRV_O_IO_URING
;
1172 * Set open flags for a given discard mode
1174 * Return 0 on success, -1 if the discard mode was invalid.
1176 int bdrv_parse_discard_flags(const char *mode
, int *flags
)
1178 *flags
&= ~BDRV_O_UNMAP
;
1180 if (!strcmp(mode
, "off") || !strcmp(mode
, "ignore")) {
1182 } else if (!strcmp(mode
, "on") || !strcmp(mode
, "unmap")) {
1183 *flags
|= BDRV_O_UNMAP
;
1192 * Set open flags for a given cache mode
1194 * Return 0 on success, -1 if the cache mode was invalid.
1196 int bdrv_parse_cache_mode(const char *mode
, int *flags
, bool *writethrough
)
1198 *flags
&= ~BDRV_O_CACHE_MASK
;
1200 if (!strcmp(mode
, "off") || !strcmp(mode
, "none")) {
1201 *writethrough
= false;
1202 *flags
|= BDRV_O_NOCACHE
;
1203 } else if (!strcmp(mode
, "directsync")) {
1204 *writethrough
= true;
1205 *flags
|= BDRV_O_NOCACHE
;
1206 } else if (!strcmp(mode
, "writeback")) {
1207 *writethrough
= false;
1208 } else if (!strcmp(mode
, "unsafe")) {
1209 *writethrough
= false;
1210 *flags
|= BDRV_O_NO_FLUSH
;
1211 } else if (!strcmp(mode
, "writethrough")) {
1212 *writethrough
= true;
1220 static char *bdrv_child_get_parent_desc(BdrvChild
*c
)
1222 BlockDriverState
*parent
= c
->opaque
;
1223 return g_strdup_printf("node '%s'", bdrv_get_node_name(parent
));
1226 static void bdrv_child_cb_drained_begin(BdrvChild
*child
)
1228 BlockDriverState
*bs
= child
->opaque
;
1229 bdrv_do_drained_begin_quiesce(bs
, NULL
, false);
1232 static bool bdrv_child_cb_drained_poll(BdrvChild
*child
)
1234 BlockDriverState
*bs
= child
->opaque
;
1235 return bdrv_drain_poll(bs
, false, NULL
, false);
1238 static void bdrv_child_cb_drained_end(BdrvChild
*child
)
1240 BlockDriverState
*bs
= child
->opaque
;
1241 bdrv_drained_end(bs
);
1244 static int bdrv_child_cb_inactivate(BdrvChild
*child
)
1246 BlockDriverState
*bs
= child
->opaque
;
1247 GLOBAL_STATE_CODE();
1248 assert(bs
->open_flags
& BDRV_O_INACTIVE
);
1252 static bool bdrv_child_cb_change_aio_ctx(BdrvChild
*child
, AioContext
*ctx
,
1253 GHashTable
*visited
, Transaction
*tran
,
1256 BlockDriverState
*bs
= child
->opaque
;
1257 return bdrv_change_aio_context(bs
, ctx
, visited
, tran
, errp
);
1261 * Returns the options and flags that a temporary snapshot should get, based on
1262 * the originally requested flags (the originally requested image will have
1263 * flags like a backing file)
1265 static void bdrv_temp_snapshot_options(int *child_flags
, QDict
*child_options
,
1266 int parent_flags
, QDict
*parent_options
)
1268 GLOBAL_STATE_CODE();
1269 *child_flags
= (parent_flags
& ~BDRV_O_SNAPSHOT
) | BDRV_O_TEMPORARY
;
1271 /* For temporary files, unconditional cache=unsafe is fine */
1272 qdict_set_default_str(child_options
, BDRV_OPT_CACHE_DIRECT
, "off");
1273 qdict_set_default_str(child_options
, BDRV_OPT_CACHE_NO_FLUSH
, "on");
1275 /* Copy the read-only and discard options from the parent */
1276 qdict_copy_default(child_options
, parent_options
, BDRV_OPT_READ_ONLY
);
1277 qdict_copy_default(child_options
, parent_options
, BDRV_OPT_DISCARD
);
1279 /* aio=native doesn't work for cache.direct=off, so disable it for the
1280 * temporary snapshot */
1281 *child_flags
&= ~BDRV_O_NATIVE_AIO
;
1284 static void bdrv_backing_attach(BdrvChild
*c
)
1286 BlockDriverState
*parent
= c
->opaque
;
1287 BlockDriverState
*backing_hd
= c
->bs
;
1289 GLOBAL_STATE_CODE();
1290 assert(!parent
->backing_blocker
);
1291 error_setg(&parent
->backing_blocker
,
1292 "node is used as backing hd of '%s'",
1293 bdrv_get_device_or_node_name(parent
));
1295 bdrv_refresh_filename(backing_hd
);
1297 parent
->open_flags
&= ~BDRV_O_NO_BACKING
;
1299 bdrv_op_block_all(backing_hd
, parent
->backing_blocker
);
1300 /* Otherwise we won't be able to commit or stream */
1301 bdrv_op_unblock(backing_hd
, BLOCK_OP_TYPE_COMMIT_TARGET
,
1302 parent
->backing_blocker
);
1303 bdrv_op_unblock(backing_hd
, BLOCK_OP_TYPE_STREAM
,
1304 parent
->backing_blocker
);
1306 * We do backup in 3 ways:
1308 * The target bs is new opened, and the source is top BDS
1309 * 2. blockdev backup
1310 * Both the source and the target are top BDSes.
1311 * 3. internal backup(used for block replication)
1312 * Both the source and the target are backing file
1314 * In case 1 and 2, neither the source nor the target is the backing file.
1315 * In case 3, we will block the top BDS, so there is only one block job
1316 * for the top BDS and its backing chain.
1318 bdrv_op_unblock(backing_hd
, BLOCK_OP_TYPE_BACKUP_SOURCE
,
1319 parent
->backing_blocker
);
1320 bdrv_op_unblock(backing_hd
, BLOCK_OP_TYPE_BACKUP_TARGET
,
1321 parent
->backing_blocker
);
1324 static void bdrv_backing_detach(BdrvChild
*c
)
1326 BlockDriverState
*parent
= c
->opaque
;
1328 GLOBAL_STATE_CODE();
1329 assert(parent
->backing_blocker
);
1330 bdrv_op_unblock_all(c
->bs
, parent
->backing_blocker
);
1331 error_free(parent
->backing_blocker
);
1332 parent
->backing_blocker
= NULL
;
1335 static int bdrv_backing_update_filename(BdrvChild
*c
, BlockDriverState
*base
,
1336 const char *filename
, Error
**errp
)
1338 BlockDriverState
*parent
= c
->opaque
;
1339 bool read_only
= bdrv_is_read_only(parent
);
1341 GLOBAL_STATE_CODE();
1344 ret
= bdrv_reopen_set_read_only(parent
, false, errp
);
1350 ret
= bdrv_change_backing_file(parent
, filename
,
1351 base
->drv
? base
->drv
->format_name
: "",
1354 error_setg_errno(errp
, -ret
, "Could not update backing file link");
1358 bdrv_reopen_set_read_only(parent
, true, NULL
);
1365 * Returns the options and flags that a generic child of a BDS should
1366 * get, based on the given options and flags for the parent BDS.
1368 static void bdrv_inherited_options(BdrvChildRole role
, bool parent_is_format
,
1369 int *child_flags
, QDict
*child_options
,
1370 int parent_flags
, QDict
*parent_options
)
1372 int flags
= parent_flags
;
1373 GLOBAL_STATE_CODE();
1376 * First, decide whether to set, clear, or leave BDRV_O_PROTOCOL.
1377 * Generally, the question to answer is: Should this child be
1378 * format-probed by default?
1382 * Pure and non-filtered data children of non-format nodes should
1383 * be probed by default (even when the node itself has BDRV_O_PROTOCOL
1384 * set). This only affects a very limited set of drivers (namely
1385 * quorum and blkverify when this comment was written).
1386 * Force-clear BDRV_O_PROTOCOL then.
1388 if (!parent_is_format
&&
1389 (role
& BDRV_CHILD_DATA
) &&
1390 !(role
& (BDRV_CHILD_METADATA
| BDRV_CHILD_FILTERED
)))
1392 flags
&= ~BDRV_O_PROTOCOL
;
1396 * All children of format nodes (except for COW children) and all
1397 * metadata children in general should never be format-probed.
1398 * Force-set BDRV_O_PROTOCOL then.
1400 if ((parent_is_format
&& !(role
& BDRV_CHILD_COW
)) ||
1401 (role
& BDRV_CHILD_METADATA
))
1403 flags
|= BDRV_O_PROTOCOL
;
1407 * If the cache mode isn't explicitly set, inherit direct and no-flush from
1410 qdict_copy_default(child_options
, parent_options
, BDRV_OPT_CACHE_DIRECT
);
1411 qdict_copy_default(child_options
, parent_options
, BDRV_OPT_CACHE_NO_FLUSH
);
1412 qdict_copy_default(child_options
, parent_options
, BDRV_OPT_FORCE_SHARE
);
1414 if (role
& BDRV_CHILD_COW
) {
1415 /* backing files are opened read-only by default */
1416 qdict_set_default_str(child_options
, BDRV_OPT_READ_ONLY
, "on");
1417 qdict_set_default_str(child_options
, BDRV_OPT_AUTO_READ_ONLY
, "off");
1419 /* Inherit the read-only option from the parent if it's not set */
1420 qdict_copy_default(child_options
, parent_options
, BDRV_OPT_READ_ONLY
);
1421 qdict_copy_default(child_options
, parent_options
,
1422 BDRV_OPT_AUTO_READ_ONLY
);
1426 * bdrv_co_pdiscard() respects unmap policy for the parent, so we
1427 * can default to enable it on lower layers regardless of the
1430 qdict_set_default_str(child_options
, BDRV_OPT_DISCARD
, "unmap");
1432 /* Clear flags that only apply to the top layer */
1433 flags
&= ~(BDRV_O_SNAPSHOT
| BDRV_O_NO_BACKING
| BDRV_O_COPY_ON_READ
);
1435 if (role
& BDRV_CHILD_METADATA
) {
1436 flags
&= ~BDRV_O_NO_IO
;
1438 if (role
& BDRV_CHILD_COW
) {
1439 flags
&= ~BDRV_O_TEMPORARY
;
1442 *child_flags
= flags
;
1445 static void bdrv_child_cb_attach(BdrvChild
*child
)
1447 BlockDriverState
*bs
= child
->opaque
;
1449 assert_bdrv_graph_writable(bs
);
1450 QLIST_INSERT_HEAD(&bs
->children
, child
, next
);
1451 if (bs
->drv
->is_filter
|| (child
->role
& BDRV_CHILD_FILTERED
)) {
1453 * Here we handle filters and block/raw-format.c when it behave like
1454 * filter. They generally have a single PRIMARY child, which is also the
1455 * FILTERED child, and that they may have multiple more children, which
1456 * are neither PRIMARY nor FILTERED. And never we have a COW child here.
1457 * So bs->file will be the PRIMARY child, unless the PRIMARY child goes
1458 * into bs->backing on exceptional cases; and bs->backing will be
1461 assert(!(child
->role
& BDRV_CHILD_COW
));
1462 if (child
->role
& BDRV_CHILD_PRIMARY
) {
1463 assert(child
->role
& BDRV_CHILD_FILTERED
);
1464 assert(!bs
->backing
);
1467 if (bs
->drv
->filtered_child_is_backing
) {
1468 bs
->backing
= child
;
1473 assert(!(child
->role
& BDRV_CHILD_FILTERED
));
1475 } else if (child
->role
& BDRV_CHILD_COW
) {
1476 assert(bs
->drv
->supports_backing
);
1477 assert(!(child
->role
& BDRV_CHILD_PRIMARY
));
1478 assert(!bs
->backing
);
1479 bs
->backing
= child
;
1480 bdrv_backing_attach(child
);
1481 } else if (child
->role
& BDRV_CHILD_PRIMARY
) {
1486 bdrv_apply_subtree_drain(child
, bs
);
1489 static void bdrv_child_cb_detach(BdrvChild
*child
)
1491 BlockDriverState
*bs
= child
->opaque
;
1493 if (child
->role
& BDRV_CHILD_COW
) {
1494 bdrv_backing_detach(child
);
1497 bdrv_unapply_subtree_drain(child
, bs
);
1499 assert_bdrv_graph_writable(bs
);
1500 QLIST_REMOVE(child
, next
);
1501 if (child
== bs
->backing
) {
1502 assert(child
!= bs
->file
);
1504 } else if (child
== bs
->file
) {
1509 static int bdrv_child_cb_update_filename(BdrvChild
*c
, BlockDriverState
*base
,
1510 const char *filename
, Error
**errp
)
1512 if (c
->role
& BDRV_CHILD_COW
) {
1513 return bdrv_backing_update_filename(c
, base
, filename
, errp
);
1518 AioContext
*child_of_bds_get_parent_aio_context(BdrvChild
*c
)
1520 BlockDriverState
*bs
= c
->opaque
;
1523 return bdrv_get_aio_context(bs
);
1526 const BdrvChildClass child_of_bds
= {
1527 .parent_is_bds
= true,
1528 .get_parent_desc
= bdrv_child_get_parent_desc
,
1529 .inherit_options
= bdrv_inherited_options
,
1530 .drained_begin
= bdrv_child_cb_drained_begin
,
1531 .drained_poll
= bdrv_child_cb_drained_poll
,
1532 .drained_end
= bdrv_child_cb_drained_end
,
1533 .attach
= bdrv_child_cb_attach
,
1534 .detach
= bdrv_child_cb_detach
,
1535 .inactivate
= bdrv_child_cb_inactivate
,
1536 .change_aio_ctx
= bdrv_child_cb_change_aio_ctx
,
1537 .update_filename
= bdrv_child_cb_update_filename
,
1538 .get_parent_aio_context
= child_of_bds_get_parent_aio_context
,
1541 AioContext
*bdrv_child_get_parent_aio_context(BdrvChild
*c
)
1544 return c
->klass
->get_parent_aio_context(c
);
1547 static int bdrv_open_flags(BlockDriverState
*bs
, int flags
)
1549 int open_flags
= flags
;
1550 GLOBAL_STATE_CODE();
1553 * Clear flags that are internal to the block layer before opening the
1556 open_flags
&= ~(BDRV_O_SNAPSHOT
| BDRV_O_NO_BACKING
| BDRV_O_PROTOCOL
);
1561 static void update_flags_from_options(int *flags
, QemuOpts
*opts
)
1563 GLOBAL_STATE_CODE();
1565 *flags
&= ~(BDRV_O_CACHE_MASK
| BDRV_O_RDWR
| BDRV_O_AUTO_RDONLY
);
1567 if (qemu_opt_get_bool_del(opts
, BDRV_OPT_CACHE_NO_FLUSH
, false)) {
1568 *flags
|= BDRV_O_NO_FLUSH
;
1571 if (qemu_opt_get_bool_del(opts
, BDRV_OPT_CACHE_DIRECT
, false)) {
1572 *flags
|= BDRV_O_NOCACHE
;
1575 if (!qemu_opt_get_bool_del(opts
, BDRV_OPT_READ_ONLY
, false)) {
1576 *flags
|= BDRV_O_RDWR
;
1579 if (qemu_opt_get_bool_del(opts
, BDRV_OPT_AUTO_READ_ONLY
, false)) {
1580 *flags
|= BDRV_O_AUTO_RDONLY
;
1584 static void update_options_from_flags(QDict
*options
, int flags
)
1586 GLOBAL_STATE_CODE();
1587 if (!qdict_haskey(options
, BDRV_OPT_CACHE_DIRECT
)) {
1588 qdict_put_bool(options
, BDRV_OPT_CACHE_DIRECT
, flags
& BDRV_O_NOCACHE
);
1590 if (!qdict_haskey(options
, BDRV_OPT_CACHE_NO_FLUSH
)) {
1591 qdict_put_bool(options
, BDRV_OPT_CACHE_NO_FLUSH
,
1592 flags
& BDRV_O_NO_FLUSH
);
1594 if (!qdict_haskey(options
, BDRV_OPT_READ_ONLY
)) {
1595 qdict_put_bool(options
, BDRV_OPT_READ_ONLY
, !(flags
& BDRV_O_RDWR
));
1597 if (!qdict_haskey(options
, BDRV_OPT_AUTO_READ_ONLY
)) {
1598 qdict_put_bool(options
, BDRV_OPT_AUTO_READ_ONLY
,
1599 flags
& BDRV_O_AUTO_RDONLY
);
1603 static void bdrv_assign_node_name(BlockDriverState
*bs
,
1604 const char *node_name
,
1607 char *gen_node_name
= NULL
;
1608 GLOBAL_STATE_CODE();
1611 node_name
= gen_node_name
= id_generate(ID_BLOCK
);
1612 } else if (!id_wellformed(node_name
)) {
1614 * Check for empty string or invalid characters, but not if it is
1615 * generated (generated names use characters not available to the user)
1617 error_setg(errp
, "Invalid node-name: '%s'", node_name
);
1621 /* takes care of avoiding namespaces collisions */
1622 if (blk_by_name(node_name
)) {
1623 error_setg(errp
, "node-name=%s is conflicting with a device id",
1628 /* takes care of avoiding duplicates node names */
1629 if (bdrv_find_node(node_name
)) {
1630 error_setg(errp
, "Duplicate nodes with node-name='%s'", node_name
);
1634 /* Make sure that the node name isn't truncated */
1635 if (strlen(node_name
) >= sizeof(bs
->node_name
)) {
1636 error_setg(errp
, "Node name too long");
1640 /* copy node name into the bs and insert it into the graph list */
1641 pstrcpy(bs
->node_name
, sizeof(bs
->node_name
), node_name
);
1642 QTAILQ_INSERT_TAIL(&graph_bdrv_states
, bs
, node_list
);
1644 g_free(gen_node_name
);
1647 static int bdrv_open_driver(BlockDriverState
*bs
, BlockDriver
*drv
,
1648 const char *node_name
, QDict
*options
,
1649 int open_flags
, Error
**errp
)
1651 Error
*local_err
= NULL
;
1653 GLOBAL_STATE_CODE();
1655 bdrv_assign_node_name(bs
, node_name
, &local_err
);
1657 error_propagate(errp
, local_err
);
1662 bs
->opaque
= g_malloc0(drv
->instance_size
);
1664 if (drv
->bdrv_file_open
) {
1665 assert(!drv
->bdrv_needs_filename
|| bs
->filename
[0]);
1666 ret
= drv
->bdrv_file_open(bs
, options
, open_flags
, &local_err
);
1667 } else if (drv
->bdrv_open
) {
1668 ret
= drv
->bdrv_open(bs
, options
, open_flags
, &local_err
);
1675 error_propagate(errp
, local_err
);
1676 } else if (bs
->filename
[0]) {
1677 error_setg_errno(errp
, -ret
, "Could not open '%s'", bs
->filename
);
1679 error_setg_errno(errp
, -ret
, "Could not open image");
1684 assert(!(bs
->supported_read_flags
& ~BDRV_REQ_MASK
));
1685 assert(!(bs
->supported_write_flags
& ~BDRV_REQ_MASK
));
1688 * Always allow the BDRV_REQ_REGISTERED_BUF optimization hint. This saves
1689 * drivers that pass read/write requests through to a child the trouble of
1690 * declaring support explicitly.
1692 * Drivers must not propagate this flag accidentally when they initiate I/O
1693 * to a bounce buffer. That case should be rare though.
1695 bs
->supported_read_flags
|= BDRV_REQ_REGISTERED_BUF
;
1696 bs
->supported_write_flags
|= BDRV_REQ_REGISTERED_BUF
;
1698 ret
= refresh_total_sectors(bs
, bs
->total_sectors
);
1700 error_setg_errno(errp
, -ret
, "Could not refresh total sector count");
1704 bdrv_refresh_limits(bs
, NULL
, &local_err
);
1706 error_propagate(errp
, local_err
);
1710 assert(bdrv_opt_mem_align(bs
) != 0);
1711 assert(bdrv_min_mem_align(bs
) != 0);
1712 assert(is_power_of_2(bs
->bl
.request_alignment
));
1714 for (i
= 0; i
< bs
->quiesce_counter
; i
++) {
1715 if (drv
->bdrv_drain_begin
) {
1716 drv
->bdrv_drain_begin(bs
);
1723 if (bs
->file
!= NULL
) {
1724 bdrv_unref_child(bs
, bs
->file
);
1733 * Create and open a block node.
1735 * @options is a QDict of options to pass to the block drivers, or NULL for an
1736 * empty set of options. The reference to the QDict belongs to the block layer
1737 * after the call (even on failure), so if the caller intends to reuse the
1738 * dictionary, it needs to use qobject_ref() before calling bdrv_open.
1740 BlockDriverState
*bdrv_new_open_driver_opts(BlockDriver
*drv
,
1741 const char *node_name
,
1742 QDict
*options
, int flags
,
1745 BlockDriverState
*bs
;
1748 GLOBAL_STATE_CODE();
1751 bs
->open_flags
= flags
;
1752 bs
->options
= options
?: qdict_new();
1753 bs
->explicit_options
= qdict_clone_shallow(bs
->options
);
1756 update_options_from_flags(bs
->options
, flags
);
1758 ret
= bdrv_open_driver(bs
, drv
, node_name
, bs
->options
, flags
, errp
);
1760 qobject_unref(bs
->explicit_options
);
1761 bs
->explicit_options
= NULL
;
1762 qobject_unref(bs
->options
);
1771 /* Create and open a block node. */
1772 BlockDriverState
*bdrv_new_open_driver(BlockDriver
*drv
, const char *node_name
,
1773 int flags
, Error
**errp
)
1775 GLOBAL_STATE_CODE();
1776 return bdrv_new_open_driver_opts(drv
, node_name
, NULL
, flags
, errp
);
1779 QemuOptsList bdrv_runtime_opts
= {
1780 .name
= "bdrv_common",
1781 .head
= QTAILQ_HEAD_INITIALIZER(bdrv_runtime_opts
.head
),
1784 .name
= "node-name",
1785 .type
= QEMU_OPT_STRING
,
1786 .help
= "Node name of the block device node",
1790 .type
= QEMU_OPT_STRING
,
1791 .help
= "Block driver to use for the node",
1794 .name
= BDRV_OPT_CACHE_DIRECT
,
1795 .type
= QEMU_OPT_BOOL
,
1796 .help
= "Bypass software writeback cache on the host",
1799 .name
= BDRV_OPT_CACHE_NO_FLUSH
,
1800 .type
= QEMU_OPT_BOOL
,
1801 .help
= "Ignore flush requests",
1804 .name
= BDRV_OPT_READ_ONLY
,
1805 .type
= QEMU_OPT_BOOL
,
1806 .help
= "Node is opened in read-only mode",
1809 .name
= BDRV_OPT_AUTO_READ_ONLY
,
1810 .type
= QEMU_OPT_BOOL
,
1811 .help
= "Node can become read-only if opening read-write fails",
1814 .name
= "detect-zeroes",
1815 .type
= QEMU_OPT_STRING
,
1816 .help
= "try to optimize zero writes (off, on, unmap)",
1819 .name
= BDRV_OPT_DISCARD
,
1820 .type
= QEMU_OPT_STRING
,
1821 .help
= "discard operation (ignore/off, unmap/on)",
1824 .name
= BDRV_OPT_FORCE_SHARE
,
1825 .type
= QEMU_OPT_BOOL
,
1826 .help
= "always accept other writers (default: off)",
1828 { /* end of list */ }
1832 QemuOptsList bdrv_create_opts_simple
= {
1833 .name
= "simple-create-opts",
1834 .head
= QTAILQ_HEAD_INITIALIZER(bdrv_create_opts_simple
.head
),
1837 .name
= BLOCK_OPT_SIZE
,
1838 .type
= QEMU_OPT_SIZE
,
1839 .help
= "Virtual disk size"
1842 .name
= BLOCK_OPT_PREALLOC
,
1843 .type
= QEMU_OPT_STRING
,
1844 .help
= "Preallocation mode (allowed values: off)"
1846 { /* end of list */ }
1851 * Common part for opening disk images and files
1853 * Removes all processed options from *options.
1855 static int bdrv_open_common(BlockDriverState
*bs
, BlockBackend
*file
,
1856 QDict
*options
, Error
**errp
)
1858 int ret
, open_flags
;
1859 const char *filename
;
1860 const char *driver_name
= NULL
;
1861 const char *node_name
= NULL
;
1862 const char *discard
;
1865 Error
*local_err
= NULL
;
1868 assert(bs
->file
== NULL
);
1869 assert(options
!= NULL
&& bs
->options
!= options
);
1870 GLOBAL_STATE_CODE();
1872 opts
= qemu_opts_create(&bdrv_runtime_opts
, NULL
, 0, &error_abort
);
1873 if (!qemu_opts_absorb_qdict(opts
, options
, errp
)) {
1878 update_flags_from_options(&bs
->open_flags
, opts
);
1880 driver_name
= qemu_opt_get(opts
, "driver");
1881 drv
= bdrv_find_format(driver_name
);
1882 assert(drv
!= NULL
);
1884 bs
->force_share
= qemu_opt_get_bool(opts
, BDRV_OPT_FORCE_SHARE
, false);
1886 if (bs
->force_share
&& (bs
->open_flags
& BDRV_O_RDWR
)) {
1888 BDRV_OPT_FORCE_SHARE
1889 "=on can only be used with read-only images");
1895 bdrv_refresh_filename(blk_bs(file
));
1896 filename
= blk_bs(file
)->filename
;
1899 * Caution: while qdict_get_try_str() is fine, getting
1900 * non-string types would require more care. When @options
1901 * come from -blockdev or blockdev_add, its members are typed
1902 * according to the QAPI schema, but when they come from
1903 * -drive, they're all QString.
1905 filename
= qdict_get_try_str(options
, "filename");
1908 if (drv
->bdrv_needs_filename
&& (!filename
|| !filename
[0])) {
1909 error_setg(errp
, "The '%s' block driver requires a file name",
1915 trace_bdrv_open_common(bs
, filename
?: "", bs
->open_flags
,
1918 ro
= bdrv_is_read_only(bs
);
1920 if (use_bdrv_whitelist
&& !bdrv_is_whitelisted(drv
, ro
)) {
1921 if (!ro
&& bdrv_is_whitelisted(drv
, true)) {
1922 ret
= bdrv_apply_auto_read_only(bs
, NULL
, NULL
);
1928 !ro
&& bdrv_is_whitelisted(drv
, true)
1929 ? "Driver '%s' can only be used for read-only devices"
1930 : "Driver '%s' is not whitelisted",
1936 /* bdrv_new() and bdrv_close() make it so */
1937 assert(qatomic_read(&bs
->copy_on_read
) == 0);
1939 if (bs
->open_flags
& BDRV_O_COPY_ON_READ
) {
1941 bdrv_enable_copy_on_read(bs
);
1943 error_setg(errp
, "Can't use copy-on-read on read-only device");
1949 discard
= qemu_opt_get(opts
, BDRV_OPT_DISCARD
);
1950 if (discard
!= NULL
) {
1951 if (bdrv_parse_discard_flags(discard
, &bs
->open_flags
) != 0) {
1952 error_setg(errp
, "Invalid discard option");
1959 bdrv_parse_detect_zeroes(opts
, bs
->open_flags
, &local_err
);
1961 error_propagate(errp
, local_err
);
1966 if (filename
!= NULL
) {
1967 pstrcpy(bs
->filename
, sizeof(bs
->filename
), filename
);
1969 bs
->filename
[0] = '\0';
1971 pstrcpy(bs
->exact_filename
, sizeof(bs
->exact_filename
), bs
->filename
);
1973 /* Open the image, either directly or using a protocol */
1974 open_flags
= bdrv_open_flags(bs
, bs
->open_flags
);
1975 node_name
= qemu_opt_get(opts
, "node-name");
1977 assert(!drv
->bdrv_file_open
|| file
== NULL
);
1978 ret
= bdrv_open_driver(bs
, drv
, node_name
, options
, open_flags
, errp
);
1983 qemu_opts_del(opts
);
1987 qemu_opts_del(opts
);
1991 static QDict
*parse_json_filename(const char *filename
, Error
**errp
)
1993 QObject
*options_obj
;
1996 GLOBAL_STATE_CODE();
1998 ret
= strstart(filename
, "json:", &filename
);
2001 options_obj
= qobject_from_json(filename
, errp
);
2003 error_prepend(errp
, "Could not parse the JSON options: ");
2007 options
= qobject_to(QDict
, options_obj
);
2009 qobject_unref(options_obj
);
2010 error_setg(errp
, "Invalid JSON object given");
2014 qdict_flatten(options
);
2019 static void parse_json_protocol(QDict
*options
, const char **pfilename
,
2022 QDict
*json_options
;
2023 Error
*local_err
= NULL
;
2024 GLOBAL_STATE_CODE();
2026 /* Parse json: pseudo-protocol */
2027 if (!*pfilename
|| !g_str_has_prefix(*pfilename
, "json:")) {
2031 json_options
= parse_json_filename(*pfilename
, &local_err
);
2033 error_propagate(errp
, local_err
);
2037 /* Options given in the filename have lower priority than options
2038 * specified directly */
2039 qdict_join(options
, json_options
, false);
2040 qobject_unref(json_options
);
2045 * Fills in default options for opening images and converts the legacy
2046 * filename/flags pair to option QDict entries.
2047 * The BDRV_O_PROTOCOL flag in *flags will be set or cleared accordingly if a
2048 * block driver has been specified explicitly.
2050 static int bdrv_fill_options(QDict
**options
, const char *filename
,
2051 int *flags
, Error
**errp
)
2053 const char *drvname
;
2054 bool protocol
= *flags
& BDRV_O_PROTOCOL
;
2055 bool parse_filename
= false;
2056 BlockDriver
*drv
= NULL
;
2057 Error
*local_err
= NULL
;
2059 GLOBAL_STATE_CODE();
2062 * Caution: while qdict_get_try_str() is fine, getting non-string
2063 * types would require more care. When @options come from
2064 * -blockdev or blockdev_add, its members are typed according to
2065 * the QAPI schema, but when they come from -drive, they're all
2068 drvname
= qdict_get_try_str(*options
, "driver");
2070 drv
= bdrv_find_format(drvname
);
2072 error_setg(errp
, "Unknown driver '%s'", drvname
);
2075 /* If the user has explicitly specified the driver, this choice should
2076 * override the BDRV_O_PROTOCOL flag */
2077 protocol
= drv
->bdrv_file_open
;
2081 *flags
|= BDRV_O_PROTOCOL
;
2083 *flags
&= ~BDRV_O_PROTOCOL
;
2086 /* Translate cache options from flags into options */
2087 update_options_from_flags(*options
, *flags
);
2089 /* Fetch the file name from the options QDict if necessary */
2090 if (protocol
&& filename
) {
2091 if (!qdict_haskey(*options
, "filename")) {
2092 qdict_put_str(*options
, "filename", filename
);
2093 parse_filename
= true;
2095 error_setg(errp
, "Can't specify 'file' and 'filename' options at "
2101 /* Find the right block driver */
2102 /* See cautionary note on accessing @options above */
2103 filename
= qdict_get_try_str(*options
, "filename");
2105 if (!drvname
&& protocol
) {
2107 drv
= bdrv_find_protocol(filename
, parse_filename
, errp
);
2112 drvname
= drv
->format_name
;
2113 qdict_put_str(*options
, "driver", drvname
);
2115 error_setg(errp
, "Must specify either driver or file");
2120 assert(drv
|| !protocol
);
2122 /* Driver-specific filename parsing */
2123 if (drv
&& drv
->bdrv_parse_filename
&& parse_filename
) {
2124 drv
->bdrv_parse_filename(filename
, *options
, &local_err
);
2126 error_propagate(errp
, local_err
);
2130 if (!drv
->bdrv_needs_filename
) {
2131 qdict_del(*options
, "filename");
2138 typedef struct BlockReopenQueueEntry
{
2141 BDRVReopenState state
;
2142 QTAILQ_ENTRY(BlockReopenQueueEntry
) entry
;
2143 } BlockReopenQueueEntry
;
2146 * Return the flags that @bs will have after the reopens in @q have
2147 * successfully completed. If @q is NULL (or @bs is not contained in @q),
2148 * return the current flags.
2150 static int bdrv_reopen_get_flags(BlockReopenQueue
*q
, BlockDriverState
*bs
)
2152 BlockReopenQueueEntry
*entry
;
2155 QTAILQ_FOREACH(entry
, q
, entry
) {
2156 if (entry
->state
.bs
== bs
) {
2157 return entry
->state
.flags
;
2162 return bs
->open_flags
;
2165 /* Returns whether the image file can be written to after the reopen queue @q
2166 * has been successfully applied, or right now if @q is NULL. */
2167 static bool bdrv_is_writable_after_reopen(BlockDriverState
*bs
,
2168 BlockReopenQueue
*q
)
2170 int flags
= bdrv_reopen_get_flags(q
, bs
);
2172 return (flags
& (BDRV_O_RDWR
| BDRV_O_INACTIVE
)) == BDRV_O_RDWR
;
2176 * Return whether the BDS can be written to. This is not necessarily
2177 * the same as !bdrv_is_read_only(bs), as inactivated images may not
2178 * be written to but do not count as read-only images.
2180 bool bdrv_is_writable(BlockDriverState
*bs
)
2183 return bdrv_is_writable_after_reopen(bs
, NULL
);
2186 static char *bdrv_child_user_desc(BdrvChild
*c
)
2188 GLOBAL_STATE_CODE();
2189 return c
->klass
->get_parent_desc(c
);
2193 * Check that @a allows everything that @b needs. @a and @b must reference same
2196 static bool bdrv_a_allow_b(BdrvChild
*a
, BdrvChild
*b
, Error
**errp
)
2198 const char *child_bs_name
;
2199 g_autofree
char *a_user
= NULL
;
2200 g_autofree
char *b_user
= NULL
;
2201 g_autofree
char *perms
= NULL
;
2204 assert(a
->bs
== b
->bs
);
2205 GLOBAL_STATE_CODE();
2207 if ((b
->perm
& a
->shared_perm
) == b
->perm
) {
2211 child_bs_name
= bdrv_get_node_name(b
->bs
);
2212 a_user
= bdrv_child_user_desc(a
);
2213 b_user
= bdrv_child_user_desc(b
);
2214 perms
= bdrv_perm_names(b
->perm
& ~a
->shared_perm
);
2216 error_setg(errp
, "Permission conflict on node '%s': permissions '%s' are "
2217 "both required by %s (uses node '%s' as '%s' child) and "
2218 "unshared by %s (uses node '%s' as '%s' child).",
2219 child_bs_name
, perms
,
2220 b_user
, child_bs_name
, b
->name
,
2221 a_user
, child_bs_name
, a
->name
);
2226 static bool bdrv_parent_perms_conflict(BlockDriverState
*bs
, Error
**errp
)
2229 GLOBAL_STATE_CODE();
2232 * During the loop we'll look at each pair twice. That's correct because
2233 * bdrv_a_allow_b() is asymmetric and we should check each pair in both
2236 QLIST_FOREACH(a
, &bs
->parents
, next_parent
) {
2237 QLIST_FOREACH(b
, &bs
->parents
, next_parent
) {
2242 if (!bdrv_a_allow_b(a
, b
, errp
)) {
2251 static void bdrv_child_perm(BlockDriverState
*bs
, BlockDriverState
*child_bs
,
2252 BdrvChild
*c
, BdrvChildRole role
,
2253 BlockReopenQueue
*reopen_queue
,
2254 uint64_t parent_perm
, uint64_t parent_shared
,
2255 uint64_t *nperm
, uint64_t *nshared
)
2257 assert(bs
->drv
&& bs
->drv
->bdrv_child_perm
);
2258 GLOBAL_STATE_CODE();
2259 bs
->drv
->bdrv_child_perm(bs
, c
, role
, reopen_queue
,
2260 parent_perm
, parent_shared
,
2262 /* TODO Take force_share from reopen_queue */
2263 if (child_bs
&& child_bs
->force_share
) {
2264 *nshared
= BLK_PERM_ALL
;
2269 * Adds the whole subtree of @bs (including @bs itself) to the @list (except for
2270 * nodes that are already in the @list, of course) so that final list is
2271 * topologically sorted. Return the result (GSList @list object is updated, so
2272 * don't use old reference after function call).
2274 * On function start @list must be already topologically sorted and for any node
2275 * in the @list the whole subtree of the node must be in the @list as well. The
2276 * simplest way to satisfy this criteria: use only result of
2277 * bdrv_topological_dfs() or NULL as @list parameter.
2279 static GSList
*bdrv_topological_dfs(GSList
*list
, GHashTable
*found
,
2280 BlockDriverState
*bs
)
2283 g_autoptr(GHashTable
) local_found
= NULL
;
2285 GLOBAL_STATE_CODE();
2289 found
= local_found
= g_hash_table_new(NULL
, NULL
);
2292 if (g_hash_table_contains(found
, bs
)) {
2295 g_hash_table_add(found
, bs
);
2297 QLIST_FOREACH(child
, &bs
->children
, next
) {
2298 list
= bdrv_topological_dfs(list
, found
, child
->bs
);
2301 return g_slist_prepend(list
, bs
);
2304 typedef struct BdrvChildSetPermState
{
2307 uint64_t old_shared_perm
;
2308 } BdrvChildSetPermState
;
2310 static void bdrv_child_set_perm_abort(void *opaque
)
2312 BdrvChildSetPermState
*s
= opaque
;
2314 GLOBAL_STATE_CODE();
2316 s
->child
->perm
= s
->old_perm
;
2317 s
->child
->shared_perm
= s
->old_shared_perm
;
2320 static TransactionActionDrv bdrv_child_set_pem_drv
= {
2321 .abort
= bdrv_child_set_perm_abort
,
2325 static void bdrv_child_set_perm(BdrvChild
*c
, uint64_t perm
,
2326 uint64_t shared
, Transaction
*tran
)
2328 BdrvChildSetPermState
*s
= g_new(BdrvChildSetPermState
, 1);
2329 GLOBAL_STATE_CODE();
2331 *s
= (BdrvChildSetPermState
) {
2333 .old_perm
= c
->perm
,
2334 .old_shared_perm
= c
->shared_perm
,
2338 c
->shared_perm
= shared
;
2340 tran_add(tran
, &bdrv_child_set_pem_drv
, s
);
2343 static void bdrv_drv_set_perm_commit(void *opaque
)
2345 BlockDriverState
*bs
= opaque
;
2346 uint64_t cumulative_perms
, cumulative_shared_perms
;
2347 GLOBAL_STATE_CODE();
2349 if (bs
->drv
->bdrv_set_perm
) {
2350 bdrv_get_cumulative_perm(bs
, &cumulative_perms
,
2351 &cumulative_shared_perms
);
2352 bs
->drv
->bdrv_set_perm(bs
, cumulative_perms
, cumulative_shared_perms
);
2356 static void bdrv_drv_set_perm_abort(void *opaque
)
2358 BlockDriverState
*bs
= opaque
;
2359 GLOBAL_STATE_CODE();
2361 if (bs
->drv
->bdrv_abort_perm_update
) {
2362 bs
->drv
->bdrv_abort_perm_update(bs
);
2366 TransactionActionDrv bdrv_drv_set_perm_drv
= {
2367 .abort
= bdrv_drv_set_perm_abort
,
2368 .commit
= bdrv_drv_set_perm_commit
,
2371 static int bdrv_drv_set_perm(BlockDriverState
*bs
, uint64_t perm
,
2372 uint64_t shared_perm
, Transaction
*tran
,
2375 GLOBAL_STATE_CODE();
2380 if (bs
->drv
->bdrv_check_perm
) {
2381 int ret
= bs
->drv
->bdrv_check_perm(bs
, perm
, shared_perm
, errp
);
2388 tran_add(tran
, &bdrv_drv_set_perm_drv
, bs
);
2394 typedef struct BdrvReplaceChildState
{
2396 BlockDriverState
*old_bs
;
2397 } BdrvReplaceChildState
;
2399 static void bdrv_replace_child_commit(void *opaque
)
2401 BdrvReplaceChildState
*s
= opaque
;
2402 GLOBAL_STATE_CODE();
2404 bdrv_unref(s
->old_bs
);
2407 static void bdrv_replace_child_abort(void *opaque
)
2409 BdrvReplaceChildState
*s
= opaque
;
2410 BlockDriverState
*new_bs
= s
->child
->bs
;
2412 GLOBAL_STATE_CODE();
2413 /* old_bs reference is transparently moved from @s to @s->child */
2414 bdrv_replace_child_noperm(s
->child
, s
->old_bs
);
2418 static TransactionActionDrv bdrv_replace_child_drv
= {
2419 .commit
= bdrv_replace_child_commit
,
2420 .abort
= bdrv_replace_child_abort
,
2425 * bdrv_replace_child_tran
2427 * Note: real unref of old_bs is done only on commit.
2429 * The function doesn't update permissions, caller is responsible for this.
2431 static void bdrv_replace_child_tran(BdrvChild
*child
, BlockDriverState
*new_bs
,
2434 BdrvReplaceChildState
*s
= g_new(BdrvReplaceChildState
, 1);
2435 *s
= (BdrvReplaceChildState
) {
2437 .old_bs
= child
->bs
,
2439 tran_add(tran
, &bdrv_replace_child_drv
, s
);
2444 bdrv_replace_child_noperm(child
, new_bs
);
2445 /* old_bs reference is transparently moved from @child to @s */
2449 * Refresh permissions in @bs subtree. The function is intended to be called
2450 * after some graph modification that was done without permission update.
2452 static int bdrv_node_refresh_perm(BlockDriverState
*bs
, BlockReopenQueue
*q
,
2453 Transaction
*tran
, Error
**errp
)
2455 BlockDriver
*drv
= bs
->drv
;
2458 uint64_t cumulative_perms
, cumulative_shared_perms
;
2459 GLOBAL_STATE_CODE();
2461 bdrv_get_cumulative_perm(bs
, &cumulative_perms
, &cumulative_shared_perms
);
2463 /* Write permissions never work with read-only images */
2464 if ((cumulative_perms
& (BLK_PERM_WRITE
| BLK_PERM_WRITE_UNCHANGED
)) &&
2465 !bdrv_is_writable_after_reopen(bs
, q
))
2467 if (!bdrv_is_writable_after_reopen(bs
, NULL
)) {
2468 error_setg(errp
, "Block node is read-only");
2470 error_setg(errp
, "Read-only block node '%s' cannot support "
2471 "read-write users", bdrv_get_node_name(bs
));
2478 * Unaligned requests will automatically be aligned to bl.request_alignment
2479 * and without RESIZE we can't extend requests to write to space beyond the
2480 * end of the image, so it's required that the image size is aligned.
2482 if ((cumulative_perms
& (BLK_PERM_WRITE
| BLK_PERM_WRITE_UNCHANGED
)) &&
2483 !(cumulative_perms
& BLK_PERM_RESIZE
))
2485 if ((bs
->total_sectors
* BDRV_SECTOR_SIZE
) % bs
->bl
.request_alignment
) {
2486 error_setg(errp
, "Cannot get 'write' permission without 'resize': "
2487 "Image size is not a multiple of request "
2493 /* Check this node */
2498 ret
= bdrv_drv_set_perm(bs
, cumulative_perms
, cumulative_shared_perms
, tran
,
2504 /* Drivers that never have children can omit .bdrv_child_perm() */
2505 if (!drv
->bdrv_child_perm
) {
2506 assert(QLIST_EMPTY(&bs
->children
));
2510 /* Check all children */
2511 QLIST_FOREACH(c
, &bs
->children
, next
) {
2512 uint64_t cur_perm
, cur_shared
;
2514 bdrv_child_perm(bs
, c
->bs
, c
, c
->role
, q
,
2515 cumulative_perms
, cumulative_shared_perms
,
2516 &cur_perm
, &cur_shared
);
2517 bdrv_child_set_perm(c
, cur_perm
, cur_shared
, tran
);
2524 * @list is a product of bdrv_topological_dfs() (may be called several times) -
2525 * a topologically sorted subgraph.
2527 static int bdrv_do_refresh_perms(GSList
*list
, BlockReopenQueue
*q
,
2528 Transaction
*tran
, Error
**errp
)
2531 BlockDriverState
*bs
;
2532 GLOBAL_STATE_CODE();
2534 for ( ; list
; list
= list
->next
) {
2537 if (bdrv_parent_perms_conflict(bs
, errp
)) {
2541 ret
= bdrv_node_refresh_perm(bs
, q
, tran
, errp
);
2551 * @list is any list of nodes. List is completed by all subtrees and
2552 * topologically sorted. It's not a problem if some node occurs in the @list
2555 static int bdrv_list_refresh_perms(GSList
*list
, BlockReopenQueue
*q
,
2556 Transaction
*tran
, Error
**errp
)
2558 g_autoptr(GHashTable
) found
= g_hash_table_new(NULL
, NULL
);
2559 g_autoptr(GSList
) refresh_list
= NULL
;
2561 for ( ; list
; list
= list
->next
) {
2562 refresh_list
= bdrv_topological_dfs(refresh_list
, found
, list
->data
);
2565 return bdrv_do_refresh_perms(refresh_list
, q
, tran
, errp
);
2568 void bdrv_get_cumulative_perm(BlockDriverState
*bs
, uint64_t *perm
,
2569 uint64_t *shared_perm
)
2572 uint64_t cumulative_perms
= 0;
2573 uint64_t cumulative_shared_perms
= BLK_PERM_ALL
;
2575 GLOBAL_STATE_CODE();
2577 QLIST_FOREACH(c
, &bs
->parents
, next_parent
) {
2578 cumulative_perms
|= c
->perm
;
2579 cumulative_shared_perms
&= c
->shared_perm
;
2582 *perm
= cumulative_perms
;
2583 *shared_perm
= cumulative_shared_perms
;
2586 char *bdrv_perm_names(uint64_t perm
)
2592 { BLK_PERM_CONSISTENT_READ
, "consistent read" },
2593 { BLK_PERM_WRITE
, "write" },
2594 { BLK_PERM_WRITE_UNCHANGED
, "write unchanged" },
2595 { BLK_PERM_RESIZE
, "resize" },
2599 GString
*result
= g_string_sized_new(30);
2600 struct perm_name
*p
;
2602 for (p
= permissions
; p
->name
; p
++) {
2603 if (perm
& p
->perm
) {
2604 if (result
->len
> 0) {
2605 g_string_append(result
, ", ");
2607 g_string_append(result
, p
->name
);
2611 return g_string_free(result
, FALSE
);
2615 /* @tran is allowed to be NULL. In this case no rollback is possible */
2616 static int bdrv_refresh_perms(BlockDriverState
*bs
, Transaction
*tran
,
2620 Transaction
*local_tran
= NULL
;
2621 g_autoptr(GSList
) list
= bdrv_topological_dfs(NULL
, NULL
, bs
);
2622 GLOBAL_STATE_CODE();
2625 tran
= local_tran
= tran_new();
2628 ret
= bdrv_do_refresh_perms(list
, NULL
, tran
, errp
);
2631 tran_finalize(local_tran
, ret
);
2637 int bdrv_child_try_set_perm(BdrvChild
*c
, uint64_t perm
, uint64_t shared
,
2640 Error
*local_err
= NULL
;
2641 Transaction
*tran
= tran_new();
2644 GLOBAL_STATE_CODE();
2646 bdrv_child_set_perm(c
, perm
, shared
, tran
);
2648 ret
= bdrv_refresh_perms(c
->bs
, tran
, &local_err
);
2650 tran_finalize(tran
, ret
);
2653 if ((perm
& ~c
->perm
) || (c
->shared_perm
& ~shared
)) {
2654 /* tighten permissions */
2655 error_propagate(errp
, local_err
);
2658 * Our caller may intend to only loosen restrictions and
2659 * does not expect this function to fail. Errors are not
2660 * fatal in such a case, so we can just hide them from our
2663 error_free(local_err
);
2671 int bdrv_child_refresh_perms(BlockDriverState
*bs
, BdrvChild
*c
, Error
**errp
)
2673 uint64_t parent_perms
, parent_shared
;
2674 uint64_t perms
, shared
;
2676 GLOBAL_STATE_CODE();
2678 bdrv_get_cumulative_perm(bs
, &parent_perms
, &parent_shared
);
2679 bdrv_child_perm(bs
, c
->bs
, c
, c
->role
, NULL
,
2680 parent_perms
, parent_shared
, &perms
, &shared
);
2682 return bdrv_child_try_set_perm(c
, perms
, shared
, errp
);
2686 * Default implementation for .bdrv_child_perm() for block filters:
2687 * Forward CONSISTENT_READ, WRITE, WRITE_UNCHANGED, and RESIZE to the
2690 static void bdrv_filter_default_perms(BlockDriverState
*bs
, BdrvChild
*c
,
2692 BlockReopenQueue
*reopen_queue
,
2693 uint64_t perm
, uint64_t shared
,
2694 uint64_t *nperm
, uint64_t *nshared
)
2696 GLOBAL_STATE_CODE();
2697 *nperm
= perm
& DEFAULT_PERM_PASSTHROUGH
;
2698 *nshared
= (shared
& DEFAULT_PERM_PASSTHROUGH
) | DEFAULT_PERM_UNCHANGED
;
2701 static void bdrv_default_perms_for_cow(BlockDriverState
*bs
, BdrvChild
*c
,
2703 BlockReopenQueue
*reopen_queue
,
2704 uint64_t perm
, uint64_t shared
,
2705 uint64_t *nperm
, uint64_t *nshared
)
2707 assert(role
& BDRV_CHILD_COW
);
2708 GLOBAL_STATE_CODE();
2711 * We want consistent read from backing files if the parent needs it.
2712 * No other operations are performed on backing files.
2714 perm
&= BLK_PERM_CONSISTENT_READ
;
2717 * If the parent can deal with changing data, we're okay with a
2718 * writable and resizable backing file.
2719 * TODO Require !(perm & BLK_PERM_CONSISTENT_READ), too?
2721 if (shared
& BLK_PERM_WRITE
) {
2722 shared
= BLK_PERM_WRITE
| BLK_PERM_RESIZE
;
2727 shared
|= BLK_PERM_CONSISTENT_READ
| BLK_PERM_WRITE_UNCHANGED
;
2729 if (bs
->open_flags
& BDRV_O_INACTIVE
) {
2730 shared
|= BLK_PERM_WRITE
| BLK_PERM_RESIZE
;
2737 static void bdrv_default_perms_for_storage(BlockDriverState
*bs
, BdrvChild
*c
,
2739 BlockReopenQueue
*reopen_queue
,
2740 uint64_t perm
, uint64_t shared
,
2741 uint64_t *nperm
, uint64_t *nshared
)
2745 GLOBAL_STATE_CODE();
2746 assert(role
& (BDRV_CHILD_METADATA
| BDRV_CHILD_DATA
));
2748 flags
= bdrv_reopen_get_flags(reopen_queue
, bs
);
2751 * Apart from the modifications below, the same permissions are
2752 * forwarded and left alone as for filters
2754 bdrv_filter_default_perms(bs
, c
, role
, reopen_queue
,
2755 perm
, shared
, &perm
, &shared
);
2757 if (role
& BDRV_CHILD_METADATA
) {
2758 /* Format drivers may touch metadata even if the guest doesn't write */
2759 if (bdrv_is_writable_after_reopen(bs
, reopen_queue
)) {
2760 perm
|= BLK_PERM_WRITE
| BLK_PERM_RESIZE
;
2764 * bs->file always needs to be consistent because of the
2765 * metadata. We can never allow other users to resize or write
2768 if (!(flags
& BDRV_O_NO_IO
)) {
2769 perm
|= BLK_PERM_CONSISTENT_READ
;
2771 shared
&= ~(BLK_PERM_WRITE
| BLK_PERM_RESIZE
);
2774 if (role
& BDRV_CHILD_DATA
) {
2776 * Technically, everything in this block is a subset of the
2777 * BDRV_CHILD_METADATA path taken above, and so this could
2778 * be an "else if" branch. However, that is not obvious, and
2779 * this function is not performance critical, therefore we let
2780 * this be an independent "if".
2784 * We cannot allow other users to resize the file because the
2785 * format driver might have some assumptions about the size
2786 * (e.g. because it is stored in metadata, or because the file
2787 * is split into fixed-size data files).
2789 shared
&= ~BLK_PERM_RESIZE
;
2792 * WRITE_UNCHANGED often cannot be performed as such on the
2793 * data file. For example, the qcow2 driver may still need to
2794 * write copied clusters on copy-on-read.
2796 if (perm
& BLK_PERM_WRITE_UNCHANGED
) {
2797 perm
|= BLK_PERM_WRITE
;
2801 * If the data file is written to, the format driver may
2802 * expect to be able to resize it by writing beyond the EOF.
2804 if (perm
& BLK_PERM_WRITE
) {
2805 perm
|= BLK_PERM_RESIZE
;
2809 if (bs
->open_flags
& BDRV_O_INACTIVE
) {
2810 shared
|= BLK_PERM_WRITE
| BLK_PERM_RESIZE
;
2817 void bdrv_default_perms(BlockDriverState
*bs
, BdrvChild
*c
,
2818 BdrvChildRole role
, BlockReopenQueue
*reopen_queue
,
2819 uint64_t perm
, uint64_t shared
,
2820 uint64_t *nperm
, uint64_t *nshared
)
2822 GLOBAL_STATE_CODE();
2823 if (role
& BDRV_CHILD_FILTERED
) {
2824 assert(!(role
& (BDRV_CHILD_DATA
| BDRV_CHILD_METADATA
|
2826 bdrv_filter_default_perms(bs
, c
, role
, reopen_queue
,
2827 perm
, shared
, nperm
, nshared
);
2828 } else if (role
& BDRV_CHILD_COW
) {
2829 assert(!(role
& (BDRV_CHILD_DATA
| BDRV_CHILD_METADATA
)));
2830 bdrv_default_perms_for_cow(bs
, c
, role
, reopen_queue
,
2831 perm
, shared
, nperm
, nshared
);
2832 } else if (role
& (BDRV_CHILD_METADATA
| BDRV_CHILD_DATA
)) {
2833 bdrv_default_perms_for_storage(bs
, c
, role
, reopen_queue
,
2834 perm
, shared
, nperm
, nshared
);
2836 g_assert_not_reached();
2840 uint64_t bdrv_qapi_perm_to_blk_perm(BlockPermission qapi_perm
)
2842 static const uint64_t permissions
[] = {
2843 [BLOCK_PERMISSION_CONSISTENT_READ
] = BLK_PERM_CONSISTENT_READ
,
2844 [BLOCK_PERMISSION_WRITE
] = BLK_PERM_WRITE
,
2845 [BLOCK_PERMISSION_WRITE_UNCHANGED
] = BLK_PERM_WRITE_UNCHANGED
,
2846 [BLOCK_PERMISSION_RESIZE
] = BLK_PERM_RESIZE
,
2849 QEMU_BUILD_BUG_ON(ARRAY_SIZE(permissions
) != BLOCK_PERMISSION__MAX
);
2850 QEMU_BUILD_BUG_ON(1UL << ARRAY_SIZE(permissions
) != BLK_PERM_ALL
+ 1);
2852 assert(qapi_perm
< BLOCK_PERMISSION__MAX
);
2854 return permissions
[qapi_perm
];
2857 static void bdrv_replace_child_noperm(BdrvChild
*child
,
2858 BlockDriverState
*new_bs
)
2860 BlockDriverState
*old_bs
= child
->bs
;
2861 int new_bs_quiesce_counter
;
2864 assert(!child
->frozen
);
2865 assert(old_bs
!= new_bs
);
2866 GLOBAL_STATE_CODE();
2868 if (old_bs
&& new_bs
) {
2869 assert(bdrv_get_aio_context(old_bs
) == bdrv_get_aio_context(new_bs
));
2872 new_bs_quiesce_counter
= (new_bs
? new_bs
->quiesce_counter
: 0);
2873 drain_saldo
= new_bs_quiesce_counter
- child
->parent_quiesce_counter
;
2876 * If the new child node is drained but the old one was not, flush
2877 * all outstanding requests to the old child node.
2879 while (drain_saldo
> 0 && child
->klass
->drained_begin
) {
2880 bdrv_parent_drained_begin_single(child
, true);
2885 /* Detach first so that the recursive drain sections coming from @child
2886 * are already gone and we only end the drain sections that came from
2888 if (child
->klass
->detach
) {
2889 child
->klass
->detach(child
);
2891 assert_bdrv_graph_writable(old_bs
);
2892 QLIST_REMOVE(child
, next_parent
);
2898 assert_bdrv_graph_writable(new_bs
);
2899 QLIST_INSERT_HEAD(&new_bs
->parents
, child
, next_parent
);
2902 * Detaching the old node may have led to the new node's
2903 * quiesce_counter having been decreased. Not a problem, we
2904 * just need to recognize this here and then invoke
2905 * drained_end appropriately more often.
2907 assert(new_bs
->quiesce_counter
<= new_bs_quiesce_counter
);
2908 drain_saldo
+= new_bs
->quiesce_counter
- new_bs_quiesce_counter
;
2910 /* Attach only after starting new drained sections, so that recursive
2911 * drain sections coming from @child don't get an extra .drained_begin
2913 if (child
->klass
->attach
) {
2914 child
->klass
->attach(child
);
2919 * If the old child node was drained but the new one is not, allow
2920 * requests to come in only after the new node has been attached.
2922 while (drain_saldo
< 0 && child
->klass
->drained_end
) {
2923 bdrv_parent_drained_end_single(child
);
2929 * Free the given @child.
2931 * The child must be empty (i.e. `child->bs == NULL`) and it must be
2932 * unused (i.e. not in a children list).
2934 static void bdrv_child_free(BdrvChild
*child
)
2937 GLOBAL_STATE_CODE();
2938 assert(!child
->next
.le_prev
); /* not in children list */
2940 g_free(child
->name
);
2944 typedef struct BdrvAttachChildCommonState
{
2946 AioContext
*old_parent_ctx
;
2947 AioContext
*old_child_ctx
;
2948 } BdrvAttachChildCommonState
;
2950 static void bdrv_attach_child_common_abort(void *opaque
)
2952 BdrvAttachChildCommonState
*s
= opaque
;
2953 BlockDriverState
*bs
= s
->child
->bs
;
2955 GLOBAL_STATE_CODE();
2956 bdrv_replace_child_noperm(s
->child
, NULL
);
2958 if (bdrv_get_aio_context(bs
) != s
->old_child_ctx
) {
2959 bdrv_try_change_aio_context(bs
, s
->old_child_ctx
, NULL
, &error_abort
);
2962 if (bdrv_child_get_parent_aio_context(s
->child
) != s
->old_parent_ctx
) {
2964 GHashTable
*visited
;
2969 /* No need to visit `child`, because it has been detached already */
2970 visited
= g_hash_table_new(NULL
, NULL
);
2971 ret
= s
->child
->klass
->change_aio_ctx(s
->child
, s
->old_parent_ctx
,
2972 visited
, tran
, &error_abort
);
2973 g_hash_table_destroy(visited
);
2975 /* transaction is supposed to always succeed */
2976 assert(ret
== true);
2981 bdrv_child_free(s
->child
);
2984 static TransactionActionDrv bdrv_attach_child_common_drv
= {
2985 .abort
= bdrv_attach_child_common_abort
,
2990 * Common part of attaching bdrv child to bs or to blk or to job
2992 * Function doesn't update permissions, caller is responsible for this.
2994 * Returns new created child.
2996 static BdrvChild
*bdrv_attach_child_common(BlockDriverState
*child_bs
,
2997 const char *child_name
,
2998 const BdrvChildClass
*child_class
,
2999 BdrvChildRole child_role
,
3000 uint64_t perm
, uint64_t shared_perm
,
3002 Transaction
*tran
, Error
**errp
)
3004 BdrvChild
*new_child
;
3005 AioContext
*parent_ctx
;
3006 AioContext
*child_ctx
= bdrv_get_aio_context(child_bs
);
3008 assert(child_class
->get_parent_desc
);
3009 GLOBAL_STATE_CODE();
3011 new_child
= g_new(BdrvChild
, 1);
3012 *new_child
= (BdrvChild
) {
3014 .name
= g_strdup(child_name
),
3015 .klass
= child_class
,
3018 .shared_perm
= shared_perm
,
3023 * If the AioContexts don't match, first try to move the subtree of
3024 * child_bs into the AioContext of the new parent. If this doesn't work,
3025 * try moving the parent into the AioContext of child_bs instead.
3027 parent_ctx
= bdrv_child_get_parent_aio_context(new_child
);
3028 if (child_ctx
!= parent_ctx
) {
3029 Error
*local_err
= NULL
;
3030 int ret
= bdrv_try_change_aio_context(child_bs
, parent_ctx
, NULL
,
3033 if (ret
< 0 && child_class
->change_aio_ctx
) {
3034 Transaction
*tran
= tran_new();
3035 GHashTable
*visited
= g_hash_table_new(NULL
, NULL
);
3038 g_hash_table_add(visited
, new_child
);
3039 ret_child
= child_class
->change_aio_ctx(new_child
, child_ctx
,
3040 visited
, tran
, NULL
);
3041 if (ret_child
== true) {
3042 error_free(local_err
);
3045 tran_finalize(tran
, ret_child
== true ? 0 : -1);
3046 g_hash_table_destroy(visited
);
3050 error_propagate(errp
, local_err
);
3051 bdrv_child_free(new_child
);
3057 bdrv_replace_child_noperm(new_child
, child_bs
);
3059 BdrvAttachChildCommonState
*s
= g_new(BdrvAttachChildCommonState
, 1);
3060 *s
= (BdrvAttachChildCommonState
) {
3062 .old_parent_ctx
= parent_ctx
,
3063 .old_child_ctx
= child_ctx
,
3065 tran_add(tran
, &bdrv_attach_child_common_drv
, s
);
3071 * Function doesn't update permissions, caller is responsible for this.
3073 static BdrvChild
*bdrv_attach_child_noperm(BlockDriverState
*parent_bs
,
3074 BlockDriverState
*child_bs
,
3075 const char *child_name
,
3076 const BdrvChildClass
*child_class
,
3077 BdrvChildRole child_role
,
3081 uint64_t perm
, shared_perm
;
3083 assert(parent_bs
->drv
);
3084 GLOBAL_STATE_CODE();
3086 if (bdrv_recurse_has_child(child_bs
, parent_bs
)) {
3087 error_setg(errp
, "Making '%s' a %s child of '%s' would create a cycle",
3088 child_bs
->node_name
, child_name
, parent_bs
->node_name
);
3092 bdrv_get_cumulative_perm(parent_bs
, &perm
, &shared_perm
);
3093 bdrv_child_perm(parent_bs
, child_bs
, NULL
, child_role
, NULL
,
3094 perm
, shared_perm
, &perm
, &shared_perm
);
3096 return bdrv_attach_child_common(child_bs
, child_name
, child_class
,
3097 child_role
, perm
, shared_perm
, parent_bs
,
3102 * This function steals the reference to child_bs from the caller.
3103 * That reference is later dropped by bdrv_root_unref_child().
3105 * On failure NULL is returned, errp is set and the reference to
3106 * child_bs is also dropped.
3108 * The caller must hold the AioContext lock @child_bs, but not that of @ctx
3109 * (unless @child_bs is already in @ctx).
3111 BdrvChild
*bdrv_root_attach_child(BlockDriverState
*child_bs
,
3112 const char *child_name
,
3113 const BdrvChildClass
*child_class
,
3114 BdrvChildRole child_role
,
3115 uint64_t perm
, uint64_t shared_perm
,
3116 void *opaque
, Error
**errp
)
3120 Transaction
*tran
= tran_new();
3122 GLOBAL_STATE_CODE();
3124 child
= bdrv_attach_child_common(child_bs
, child_name
, child_class
,
3125 child_role
, perm
, shared_perm
, opaque
,
3132 ret
= bdrv_refresh_perms(child_bs
, tran
, errp
);
3135 tran_finalize(tran
, ret
);
3137 bdrv_unref(child_bs
);
3139 return ret
< 0 ? NULL
: child
;
3143 * This function transfers the reference to child_bs from the caller
3144 * to parent_bs. That reference is later dropped by parent_bs on
3145 * bdrv_close() or if someone calls bdrv_unref_child().
3147 * On failure NULL is returned, errp is set and the reference to
3148 * child_bs is also dropped.
3150 * If @parent_bs and @child_bs are in different AioContexts, the caller must
3151 * hold the AioContext lock for @child_bs, but not for @parent_bs.
3153 BdrvChild
*bdrv_attach_child(BlockDriverState
*parent_bs
,
3154 BlockDriverState
*child_bs
,
3155 const char *child_name
,
3156 const BdrvChildClass
*child_class
,
3157 BdrvChildRole child_role
,
3162 Transaction
*tran
= tran_new();
3164 GLOBAL_STATE_CODE();
3166 child
= bdrv_attach_child_noperm(parent_bs
, child_bs
, child_name
,
3167 child_class
, child_role
, tran
, errp
);
3173 ret
= bdrv_refresh_perms(parent_bs
, tran
, errp
);
3179 tran_finalize(tran
, ret
);
3181 bdrv_unref(child_bs
);
3183 return ret
< 0 ? NULL
: child
;
3186 /* Callers must ensure that child->frozen is false. */
3187 void bdrv_root_unref_child(BdrvChild
*child
)
3189 BlockDriverState
*child_bs
= child
->bs
;
3191 GLOBAL_STATE_CODE();
3192 bdrv_replace_child_noperm(child
, NULL
);
3193 bdrv_child_free(child
);
3197 * Update permissions for old node. We're just taking a parent away, so
3198 * we're loosening restrictions. Errors of permission update are not
3199 * fatal in this case, ignore them.
3201 bdrv_refresh_perms(child_bs
, NULL
, NULL
);
3204 * When the parent requiring a non-default AioContext is removed, the
3205 * node moves back to the main AioContext
3207 bdrv_try_change_aio_context(child_bs
, qemu_get_aio_context(), NULL
,
3211 bdrv_unref(child_bs
);
3214 typedef struct BdrvSetInheritsFrom
{
3215 BlockDriverState
*bs
;
3216 BlockDriverState
*old_inherits_from
;
3217 } BdrvSetInheritsFrom
;
3219 static void bdrv_set_inherits_from_abort(void *opaque
)
3221 BdrvSetInheritsFrom
*s
= opaque
;
3223 s
->bs
->inherits_from
= s
->old_inherits_from
;
3226 static TransactionActionDrv bdrv_set_inherits_from_drv
= {
3227 .abort
= bdrv_set_inherits_from_abort
,
3231 /* @tran is allowed to be NULL. In this case no rollback is possible */
3232 static void bdrv_set_inherits_from(BlockDriverState
*bs
,
3233 BlockDriverState
*new_inherits_from
,
3237 BdrvSetInheritsFrom
*s
= g_new(BdrvSetInheritsFrom
, 1);
3239 *s
= (BdrvSetInheritsFrom
) {
3241 .old_inherits_from
= bs
->inherits_from
,
3244 tran_add(tran
, &bdrv_set_inherits_from_drv
, s
);
3247 bs
->inherits_from
= new_inherits_from
;
3251 * Clear all inherits_from pointers from children and grandchildren of
3252 * @root that point to @root, where necessary.
3253 * @tran is allowed to be NULL. In this case no rollback is possible
3255 static void bdrv_unset_inherits_from(BlockDriverState
*root
, BdrvChild
*child
,
3260 if (child
->bs
->inherits_from
== root
) {
3262 * Remove inherits_from only when the last reference between root and
3263 * child->bs goes away.
3265 QLIST_FOREACH(c
, &root
->children
, next
) {
3266 if (c
!= child
&& c
->bs
== child
->bs
) {
3271 bdrv_set_inherits_from(child
->bs
, NULL
, tran
);
3275 QLIST_FOREACH(c
, &child
->bs
->children
, next
) {
3276 bdrv_unset_inherits_from(root
, c
, tran
);
3280 /* Callers must ensure that child->frozen is false. */
3281 void bdrv_unref_child(BlockDriverState
*parent
, BdrvChild
*child
)
3283 GLOBAL_STATE_CODE();
3284 if (child
== NULL
) {
3288 bdrv_unset_inherits_from(parent
, child
, NULL
);
3289 bdrv_root_unref_child(child
);
3293 static void bdrv_parent_cb_change_media(BlockDriverState
*bs
, bool load
)
3296 GLOBAL_STATE_CODE();
3297 QLIST_FOREACH(c
, &bs
->parents
, next_parent
) {
3298 if (c
->klass
->change_media
) {
3299 c
->klass
->change_media(c
, load
);
3304 /* Return true if you can reach parent going through child->inherits_from
3305 * recursively. If parent or child are NULL, return false */
3306 static bool bdrv_inherits_from_recursive(BlockDriverState
*child
,
3307 BlockDriverState
*parent
)
3309 while (child
&& child
!= parent
) {
3310 child
= child
->inherits_from
;
3313 return child
!= NULL
;
3317 * Return the BdrvChildRole for @bs's backing child. bs->backing is
3318 * mostly used for COW backing children (role = COW), but also for
3319 * filtered children (role = FILTERED | PRIMARY).
3321 static BdrvChildRole
bdrv_backing_role(BlockDriverState
*bs
)
3323 if (bs
->drv
&& bs
->drv
->is_filter
) {
3324 return BDRV_CHILD_FILTERED
| BDRV_CHILD_PRIMARY
;
3326 return BDRV_CHILD_COW
;
3331 * Sets the bs->backing or bs->file link of a BDS. A new reference is created;
3332 * callers which don't need their own reference any more must call bdrv_unref().
3334 * Function doesn't update permissions, caller is responsible for this.
3336 static int bdrv_set_file_or_backing_noperm(BlockDriverState
*parent_bs
,
3337 BlockDriverState
*child_bs
,
3339 Transaction
*tran
, Error
**errp
)
3341 bool update_inherits_from
=
3342 bdrv_inherits_from_recursive(child_bs
, parent_bs
);
3343 BdrvChild
*child
= is_backing
? parent_bs
->backing
: parent_bs
->file
;
3346 GLOBAL_STATE_CODE();
3348 if (!parent_bs
->drv
) {
3350 * Node without drv is an object without a class :/. TODO: finally fix
3351 * qcow2 driver to never clear bs->drv and implement format corruption
3352 * handling in other way.
3354 error_setg(errp
, "Node corrupted");
3358 if (child
&& child
->frozen
) {
3359 error_setg(errp
, "Cannot change frozen '%s' link from '%s' to '%s'",
3360 child
->name
, parent_bs
->node_name
, child
->bs
->node_name
);
3364 if (is_backing
&& !parent_bs
->drv
->is_filter
&&
3365 !parent_bs
->drv
->supports_backing
)
3367 error_setg(errp
, "Driver '%s' of node '%s' does not support backing "
3368 "files", parent_bs
->drv
->format_name
, parent_bs
->node_name
);
3372 if (parent_bs
->drv
->is_filter
) {
3373 role
= BDRV_CHILD_FILTERED
| BDRV_CHILD_PRIMARY
;
3374 } else if (is_backing
) {
3375 role
= BDRV_CHILD_COW
;
3378 * We only can use same role as it is in existing child. We don't have
3379 * infrastructure to determine role of file child in generic way
3382 error_setg(errp
, "Cannot set file child to format node without "
3390 bdrv_unset_inherits_from(parent_bs
, child
, tran
);
3391 bdrv_remove_child(child
, tran
);
3398 child
= bdrv_attach_child_noperm(parent_bs
, child_bs
,
3399 is_backing
? "backing" : "file",
3400 &child_of_bds
, role
,
3408 * If inherits_from pointed recursively to bs then let's update it to
3409 * point directly to bs (else it will become NULL).
3411 if (update_inherits_from
) {
3412 bdrv_set_inherits_from(child_bs
, parent_bs
, tran
);
3416 bdrv_refresh_limits(parent_bs
, tran
, NULL
);
3421 static int bdrv_set_backing_noperm(BlockDriverState
*bs
,
3422 BlockDriverState
*backing_hd
,
3423 Transaction
*tran
, Error
**errp
)
3425 GLOBAL_STATE_CODE();
3426 return bdrv_set_file_or_backing_noperm(bs
, backing_hd
, true, tran
, errp
);
3429 int bdrv_set_backing_hd(BlockDriverState
*bs
, BlockDriverState
*backing_hd
,
3433 Transaction
*tran
= tran_new();
3435 GLOBAL_STATE_CODE();
3436 bdrv_drained_begin(bs
);
3438 ret
= bdrv_set_backing_noperm(bs
, backing_hd
, tran
, errp
);
3443 ret
= bdrv_refresh_perms(bs
, tran
, errp
);
3445 tran_finalize(tran
, ret
);
3447 bdrv_drained_end(bs
);
3453 * Opens the backing file for a BlockDriverState if not yet open
3455 * bdref_key specifies the key for the image's BlockdevRef in the options QDict.
3456 * That QDict has to be flattened; therefore, if the BlockdevRef is a QDict
3457 * itself, all options starting with "${bdref_key}." are considered part of the
3460 * TODO Can this be unified with bdrv_open_image()?
3462 int bdrv_open_backing_file(BlockDriverState
*bs
, QDict
*parent_options
,
3463 const char *bdref_key
, Error
**errp
)
3465 char *backing_filename
= NULL
;
3466 char *bdref_key_dot
;
3467 const char *reference
= NULL
;
3469 bool implicit_backing
= false;
3470 BlockDriverState
*backing_hd
;
3472 QDict
*tmp_parent_options
= NULL
;
3473 Error
*local_err
= NULL
;
3475 GLOBAL_STATE_CODE();
3477 if (bs
->backing
!= NULL
) {
3481 /* NULL means an empty set of options */
3482 if (parent_options
== NULL
) {
3483 tmp_parent_options
= qdict_new();
3484 parent_options
= tmp_parent_options
;
3487 bs
->open_flags
&= ~BDRV_O_NO_BACKING
;
3489 bdref_key_dot
= g_strdup_printf("%s.", bdref_key
);
3490 qdict_extract_subqdict(parent_options
, &options
, bdref_key_dot
);
3491 g_free(bdref_key_dot
);
3494 * Caution: while qdict_get_try_str() is fine, getting non-string
3495 * types would require more care. When @parent_options come from
3496 * -blockdev or blockdev_add, its members are typed according to
3497 * the QAPI schema, but when they come from -drive, they're all
3500 reference
= qdict_get_try_str(parent_options
, bdref_key
);
3501 if (reference
|| qdict_haskey(options
, "file.filename")) {
3502 /* keep backing_filename NULL */
3503 } else if (bs
->backing_file
[0] == '\0' && qdict_size(options
) == 0) {
3504 qobject_unref(options
);
3507 if (qdict_size(options
) == 0) {
3508 /* If the user specifies options that do not modify the
3509 * backing file's behavior, we might still consider it the
3510 * implicit backing file. But it's easier this way, and
3511 * just specifying some of the backing BDS's options is
3512 * only possible with -drive anyway (otherwise the QAPI
3513 * schema forces the user to specify everything). */
3514 implicit_backing
= !strcmp(bs
->auto_backing_file
, bs
->backing_file
);
3517 backing_filename
= bdrv_get_full_backing_filename(bs
, &local_err
);
3520 error_propagate(errp
, local_err
);
3521 qobject_unref(options
);
3526 if (!bs
->drv
|| !bs
->drv
->supports_backing
) {
3528 error_setg(errp
, "Driver doesn't support backing files");
3529 qobject_unref(options
);
3534 bs
->backing_format
[0] != '\0' && !qdict_haskey(options
, "driver")) {
3535 qdict_put_str(options
, "driver", bs
->backing_format
);
3538 backing_hd
= bdrv_open_inherit(backing_filename
, reference
, options
, 0, bs
,
3539 &child_of_bds
, bdrv_backing_role(bs
), errp
);
3541 bs
->open_flags
|= BDRV_O_NO_BACKING
;
3542 error_prepend(errp
, "Could not open backing file: ");
3547 if (implicit_backing
) {
3548 bdrv_refresh_filename(backing_hd
);
3549 pstrcpy(bs
->auto_backing_file
, sizeof(bs
->auto_backing_file
),
3550 backing_hd
->filename
);
3553 /* Hook up the backing file link; drop our reference, bs owns the
3554 * backing_hd reference now */
3555 ret
= bdrv_set_backing_hd(bs
, backing_hd
, errp
);
3556 bdrv_unref(backing_hd
);
3561 qdict_del(parent_options
, bdref_key
);
3564 g_free(backing_filename
);
3565 qobject_unref(tmp_parent_options
);
3569 static BlockDriverState
*
3570 bdrv_open_child_bs(const char *filename
, QDict
*options
, const char *bdref_key
,
3571 BlockDriverState
*parent
, const BdrvChildClass
*child_class
,
3572 BdrvChildRole child_role
, bool allow_none
, Error
**errp
)
3574 BlockDriverState
*bs
= NULL
;
3575 QDict
*image_options
;
3576 char *bdref_key_dot
;
3577 const char *reference
;
3579 assert(child_class
!= NULL
);
3581 bdref_key_dot
= g_strdup_printf("%s.", bdref_key
);
3582 qdict_extract_subqdict(options
, &image_options
, bdref_key_dot
);
3583 g_free(bdref_key_dot
);
3586 * Caution: while qdict_get_try_str() is fine, getting non-string
3587 * types would require more care. When @options come from
3588 * -blockdev or blockdev_add, its members are typed according to
3589 * the QAPI schema, but when they come from -drive, they're all
3592 reference
= qdict_get_try_str(options
, bdref_key
);
3593 if (!filename
&& !reference
&& !qdict_size(image_options
)) {
3595 error_setg(errp
, "A block device must be specified for \"%s\"",
3598 qobject_unref(image_options
);
3602 bs
= bdrv_open_inherit(filename
, reference
, image_options
, 0,
3603 parent
, child_class
, child_role
, errp
);
3609 qdict_del(options
, bdref_key
);
3614 * Opens a disk image whose options are given as BlockdevRef in another block
3617 * If allow_none is true, no image will be opened if filename is false and no
3618 * BlockdevRef is given. NULL will be returned, but errp remains unset.
3620 * bdrev_key specifies the key for the image's BlockdevRef in the options QDict.
3621 * That QDict has to be flattened; therefore, if the BlockdevRef is a QDict
3622 * itself, all options starting with "${bdref_key}." are considered part of the
3625 * The BlockdevRef will be removed from the options QDict.
3627 BdrvChild
*bdrv_open_child(const char *filename
,
3628 QDict
*options
, const char *bdref_key
,
3629 BlockDriverState
*parent
,
3630 const BdrvChildClass
*child_class
,
3631 BdrvChildRole child_role
,
3632 bool allow_none
, Error
**errp
)
3634 BlockDriverState
*bs
;
3636 GLOBAL_STATE_CODE();
3638 bs
= bdrv_open_child_bs(filename
, options
, bdref_key
, parent
, child_class
,
3639 child_role
, allow_none
, errp
);
3644 return bdrv_attach_child(parent
, bs
, bdref_key
, child_class
, child_role
,
3649 * Wrapper on bdrv_open_child() for most popular case: open primary child of bs.
3651 int bdrv_open_file_child(const char *filename
,
3652 QDict
*options
, const char *bdref_key
,
3653 BlockDriverState
*parent
, Error
**errp
)
3657 /* commit_top and mirror_top don't use this function */
3658 assert(!parent
->drv
->filtered_child_is_backing
);
3659 role
= parent
->drv
->is_filter
?
3660 (BDRV_CHILD_FILTERED
| BDRV_CHILD_PRIMARY
) : BDRV_CHILD_IMAGE
;
3662 if (!bdrv_open_child(filename
, options
, bdref_key
, parent
,
3663 &child_of_bds
, role
, false, errp
))
3672 * TODO Future callers may need to specify parent/child_class in order for
3673 * option inheritance to work. Existing callers use it for the root node.
3675 BlockDriverState
*bdrv_open_blockdev_ref(BlockdevRef
*ref
, Error
**errp
)
3677 BlockDriverState
*bs
= NULL
;
3678 QObject
*obj
= NULL
;
3679 QDict
*qdict
= NULL
;
3680 const char *reference
= NULL
;
3683 GLOBAL_STATE_CODE();
3685 if (ref
->type
== QTYPE_QSTRING
) {
3686 reference
= ref
->u
.reference
;
3688 BlockdevOptions
*options
= &ref
->u
.definition
;
3689 assert(ref
->type
== QTYPE_QDICT
);
3691 v
= qobject_output_visitor_new(&obj
);
3692 visit_type_BlockdevOptions(v
, NULL
, &options
, &error_abort
);
3693 visit_complete(v
, &obj
);
3695 qdict
= qobject_to(QDict
, obj
);
3696 qdict_flatten(qdict
);
3698 /* bdrv_open_inherit() defaults to the values in bdrv_flags (for
3699 * compatibility with other callers) rather than what we want as the
3700 * real defaults. Apply the defaults here instead. */
3701 qdict_set_default_str(qdict
, BDRV_OPT_CACHE_DIRECT
, "off");
3702 qdict_set_default_str(qdict
, BDRV_OPT_CACHE_NO_FLUSH
, "off");
3703 qdict_set_default_str(qdict
, BDRV_OPT_READ_ONLY
, "off");
3704 qdict_set_default_str(qdict
, BDRV_OPT_AUTO_READ_ONLY
, "off");
3708 bs
= bdrv_open_inherit(NULL
, reference
, qdict
, 0, NULL
, NULL
, 0, errp
);
3715 static BlockDriverState
*bdrv_append_temp_snapshot(BlockDriverState
*bs
,
3717 QDict
*snapshot_options
,
3720 g_autofree
char *tmp_filename
= NULL
;
3722 QemuOpts
*opts
= NULL
;
3723 BlockDriverState
*bs_snapshot
= NULL
;
3726 GLOBAL_STATE_CODE();
3728 /* if snapshot, we create a temporary backing file and open it
3729 instead of opening 'filename' directly */
3731 /* Get the required size from the image */
3732 total_size
= bdrv_getlength(bs
);
3733 if (total_size
< 0) {
3734 error_setg_errno(errp
, -total_size
, "Could not get image size");
3738 /* Create the temporary image */
3739 tmp_filename
= create_tmp_file(errp
);
3740 if (!tmp_filename
) {
3744 opts
= qemu_opts_create(bdrv_qcow2
.create_opts
, NULL
, 0,
3746 qemu_opt_set_number(opts
, BLOCK_OPT_SIZE
, total_size
, &error_abort
);
3747 ret
= bdrv_create(&bdrv_qcow2
, tmp_filename
, opts
, errp
);
3748 qemu_opts_del(opts
);
3750 error_prepend(errp
, "Could not create temporary overlay '%s': ",
3755 /* Prepare options QDict for the temporary file */
3756 qdict_put_str(snapshot_options
, "file.driver", "file");
3757 qdict_put_str(snapshot_options
, "file.filename", tmp_filename
);
3758 qdict_put_str(snapshot_options
, "driver", "qcow2");
3760 bs_snapshot
= bdrv_open(NULL
, NULL
, snapshot_options
, flags
, errp
);
3761 snapshot_options
= NULL
;
3766 ret
= bdrv_append(bs_snapshot
, bs
, errp
);
3773 qobject_unref(snapshot_options
);
3778 * Opens a disk image (raw, qcow2, vmdk, ...)
3780 * options is a QDict of options to pass to the block drivers, or NULL for an
3781 * empty set of options. The reference to the QDict belongs to the block layer
3782 * after the call (even on failure), so if the caller intends to reuse the
3783 * dictionary, it needs to use qobject_ref() before calling bdrv_open.
3785 * If *pbs is NULL, a new BDS will be created with a pointer to it stored there.
3786 * If it is not NULL, the referenced BDS will be reused.
3788 * The reference parameter may be used to specify an existing block device which
3789 * should be opened. If specified, neither options nor a filename may be given,
3790 * nor can an existing BDS be reused (that is, *pbs has to be NULL).
3792 static BlockDriverState
*bdrv_open_inherit(const char *filename
,
3793 const char *reference
,
3794 QDict
*options
, int flags
,
3795 BlockDriverState
*parent
,
3796 const BdrvChildClass
*child_class
,
3797 BdrvChildRole child_role
,
3801 BlockBackend
*file
= NULL
;
3802 BlockDriverState
*bs
;
3803 BlockDriver
*drv
= NULL
;
3805 const char *drvname
;
3806 const char *backing
;
3807 Error
*local_err
= NULL
;
3808 QDict
*snapshot_options
= NULL
;
3809 int snapshot_flags
= 0;
3811 assert(!child_class
|| !flags
);
3812 assert(!child_class
== !parent
);
3813 GLOBAL_STATE_CODE();
3816 bool options_non_empty
= options
? qdict_size(options
) : false;
3817 qobject_unref(options
);
3819 if (filename
|| options_non_empty
) {
3820 error_setg(errp
, "Cannot reference an existing block device with "
3821 "additional options or a new filename");
3825 bs
= bdrv_lookup_bs(reference
, reference
, errp
);
3836 /* NULL means an empty set of options */
3837 if (options
== NULL
) {
3838 options
= qdict_new();
3841 /* json: syntax counts as explicit options, as if in the QDict */
3842 parse_json_protocol(options
, &filename
, &local_err
);
3847 bs
->explicit_options
= qdict_clone_shallow(options
);
3850 bool parent_is_format
;
3853 parent_is_format
= parent
->drv
->is_format
;
3856 * parent->drv is not set yet because this node is opened for
3857 * (potential) format probing. That means that @parent is going
3858 * to be a format node.
3860 parent_is_format
= true;
3863 bs
->inherits_from
= parent
;
3864 child_class
->inherit_options(child_role
, parent_is_format
,
3866 parent
->open_flags
, parent
->options
);
3869 ret
= bdrv_fill_options(&options
, filename
, &flags
, &local_err
);
3875 * Set the BDRV_O_RDWR and BDRV_O_ALLOW_RDWR flags.
3876 * Caution: getting a boolean member of @options requires care.
3877 * When @options come from -blockdev or blockdev_add, members are
3878 * typed according to the QAPI schema, but when they come from
3879 * -drive, they're all QString.
3881 if (g_strcmp0(qdict_get_try_str(options
, BDRV_OPT_READ_ONLY
), "on") &&
3882 !qdict_get_try_bool(options
, BDRV_OPT_READ_ONLY
, false)) {
3883 flags
|= (BDRV_O_RDWR
| BDRV_O_ALLOW_RDWR
);
3885 flags
&= ~BDRV_O_RDWR
;
3888 if (flags
& BDRV_O_SNAPSHOT
) {
3889 snapshot_options
= qdict_new();
3890 bdrv_temp_snapshot_options(&snapshot_flags
, snapshot_options
,
3892 /* Let bdrv_backing_options() override "read-only" */
3893 qdict_del(options
, BDRV_OPT_READ_ONLY
);
3894 bdrv_inherited_options(BDRV_CHILD_COW
, true,
3895 &flags
, options
, flags
, options
);
3898 bs
->open_flags
= flags
;
3899 bs
->options
= options
;
3900 options
= qdict_clone_shallow(options
);
3902 /* Find the right image format driver */
3903 /* See cautionary note on accessing @options above */
3904 drvname
= qdict_get_try_str(options
, "driver");
3906 drv
= bdrv_find_format(drvname
);
3908 error_setg(errp
, "Unknown driver: '%s'", drvname
);
3913 assert(drvname
|| !(flags
& BDRV_O_PROTOCOL
));
3915 /* See cautionary note on accessing @options above */
3916 backing
= qdict_get_try_str(options
, "backing");
3917 if (qobject_to(QNull
, qdict_get(options
, "backing")) != NULL
||
3918 (backing
&& *backing
== '\0'))
3921 warn_report("Use of \"backing\": \"\" is deprecated; "
3922 "use \"backing\": null instead");
3924 flags
|= BDRV_O_NO_BACKING
;
3925 qdict_del(bs
->explicit_options
, "backing");
3926 qdict_del(bs
->options
, "backing");
3927 qdict_del(options
, "backing");
3930 /* Open image file without format layer. This BlockBackend is only used for
3931 * probing, the block drivers will do their own bdrv_open_child() for the
3932 * same BDS, which is why we put the node name back into options. */
3933 if ((flags
& BDRV_O_PROTOCOL
) == 0) {
3934 BlockDriverState
*file_bs
;
3936 file_bs
= bdrv_open_child_bs(filename
, options
, "file", bs
,
3937 &child_of_bds
, BDRV_CHILD_IMAGE
,
3942 if (file_bs
!= NULL
) {
3943 /* Not requesting BLK_PERM_CONSISTENT_READ because we're only
3944 * looking at the header to guess the image format. This works even
3945 * in cases where a guest would not see a consistent state. */
3946 file
= blk_new(bdrv_get_aio_context(file_bs
), 0, BLK_PERM_ALL
);
3947 blk_insert_bs(file
, file_bs
, &local_err
);
3948 bdrv_unref(file_bs
);
3953 qdict_put_str(options
, "file", bdrv_get_node_name(file_bs
));
3957 /* Image format probing */
3960 ret
= find_image_format(file
, filename
, &drv
, &local_err
);
3965 * This option update would logically belong in bdrv_fill_options(),
3966 * but we first need to open bs->file for the probing to work, while
3967 * opening bs->file already requires the (mostly) final set of options
3968 * so that cache mode etc. can be inherited.
3970 * Adding the driver later is somewhat ugly, but it's not an option
3971 * that would ever be inherited, so it's correct. We just need to make
3972 * sure to update both bs->options (which has the full effective
3973 * options for bs) and options (which has file.* already removed).
3975 qdict_put_str(bs
->options
, "driver", drv
->format_name
);
3976 qdict_put_str(options
, "driver", drv
->format_name
);
3978 error_setg(errp
, "Must specify either driver or file");
3982 /* BDRV_O_PROTOCOL must be set iff a protocol BDS is about to be created */
3983 assert(!!(flags
& BDRV_O_PROTOCOL
) == !!drv
->bdrv_file_open
);
3984 /* file must be NULL if a protocol BDS is about to be created
3985 * (the inverse results in an error message from bdrv_open_common()) */
3986 assert(!(flags
& BDRV_O_PROTOCOL
) || !file
);
3988 /* Open the image */
3989 ret
= bdrv_open_common(bs
, file
, options
, &local_err
);
3999 /* If there is a backing file, use it */
4000 if ((flags
& BDRV_O_NO_BACKING
) == 0) {
4001 ret
= bdrv_open_backing_file(bs
, options
, "backing", &local_err
);
4003 goto close_and_fail
;
4007 /* Remove all children options and references
4008 * from bs->options and bs->explicit_options */
4009 QLIST_FOREACH(child
, &bs
->children
, next
) {
4010 char *child_key_dot
;
4011 child_key_dot
= g_strdup_printf("%s.", child
->name
);
4012 qdict_extract_subqdict(bs
->explicit_options
, NULL
, child_key_dot
);
4013 qdict_extract_subqdict(bs
->options
, NULL
, child_key_dot
);
4014 qdict_del(bs
->explicit_options
, child
->name
);
4015 qdict_del(bs
->options
, child
->name
);
4016 g_free(child_key_dot
);
4019 /* Check if any unknown options were used */
4020 if (qdict_size(options
) != 0) {
4021 const QDictEntry
*entry
= qdict_first(options
);
4022 if (flags
& BDRV_O_PROTOCOL
) {
4023 error_setg(errp
, "Block protocol '%s' doesn't support the option "
4024 "'%s'", drv
->format_name
, entry
->key
);
4027 "Block format '%s' does not support the option '%s'",
4028 drv
->format_name
, entry
->key
);
4031 goto close_and_fail
;
4034 bdrv_parent_cb_change_media(bs
, true);
4036 qobject_unref(options
);
4039 /* For snapshot=on, create a temporary qcow2 overlay. bs points to the
4040 * temporary snapshot afterwards. */
4041 if (snapshot_flags
) {
4042 BlockDriverState
*snapshot_bs
;
4043 snapshot_bs
= bdrv_append_temp_snapshot(bs
, snapshot_flags
,
4044 snapshot_options
, &local_err
);
4045 snapshot_options
= NULL
;
4047 goto close_and_fail
;
4049 /* We are not going to return bs but the overlay on top of it
4050 * (snapshot_bs); thus, we have to drop the strong reference to bs
4051 * (which we obtained by calling bdrv_new()). bs will not be deleted,
4052 * though, because the overlay still has a reference to it. */
4061 qobject_unref(snapshot_options
);
4062 qobject_unref(bs
->explicit_options
);
4063 qobject_unref(bs
->options
);
4064 qobject_unref(options
);
4066 bs
->explicit_options
= NULL
;
4068 error_propagate(errp
, local_err
);
4073 qobject_unref(snapshot_options
);
4074 qobject_unref(options
);
4075 error_propagate(errp
, local_err
);
4079 BlockDriverState
*bdrv_open(const char *filename
, const char *reference
,
4080 QDict
*options
, int flags
, Error
**errp
)
4082 GLOBAL_STATE_CODE();
4084 return bdrv_open_inherit(filename
, reference
, options
, flags
, NULL
,
4088 /* Return true if the NULL-terminated @list contains @str */
4089 static bool is_str_in_list(const char *str
, const char *const *list
)
4093 for (i
= 0; list
[i
] != NULL
; i
++) {
4094 if (!strcmp(str
, list
[i
])) {
4103 * Check that every option set in @bs->options is also set in
4106 * Options listed in the common_options list and in
4107 * @bs->drv->mutable_opts are skipped.
4109 * Return 0 on success, otherwise return -EINVAL and set @errp.
4111 static int bdrv_reset_options_allowed(BlockDriverState
*bs
,
4112 const QDict
*new_opts
, Error
**errp
)
4114 const QDictEntry
*e
;
4115 /* These options are common to all block drivers and are handled
4116 * in bdrv_reopen_prepare() so they can be left out of @new_opts */
4117 const char *const common_options
[] = {
4118 "node-name", "discard", "cache.direct", "cache.no-flush",
4119 "read-only", "auto-read-only", "detect-zeroes", NULL
4122 for (e
= qdict_first(bs
->options
); e
; e
= qdict_next(bs
->options
, e
)) {
4123 if (!qdict_haskey(new_opts
, e
->key
) &&
4124 !is_str_in_list(e
->key
, common_options
) &&
4125 !is_str_in_list(e
->key
, bs
->drv
->mutable_opts
)) {
4126 error_setg(errp
, "Option '%s' cannot be reset "
4127 "to its default value", e
->key
);
4136 * Returns true if @child can be reached recursively from @bs
4138 static bool bdrv_recurse_has_child(BlockDriverState
*bs
,
4139 BlockDriverState
*child
)
4147 QLIST_FOREACH(c
, &bs
->children
, next
) {
4148 if (bdrv_recurse_has_child(c
->bs
, child
)) {
4157 * Adds a BlockDriverState to a simple queue for an atomic, transactional
4158 * reopen of multiple devices.
4160 * bs_queue can either be an existing BlockReopenQueue that has had QTAILQ_INIT
4161 * already performed, or alternatively may be NULL a new BlockReopenQueue will
4162 * be created and initialized. This newly created BlockReopenQueue should be
4163 * passed back in for subsequent calls that are intended to be of the same
4166 * bs is the BlockDriverState to add to the reopen queue.
4168 * options contains the changed options for the associated bs
4169 * (the BlockReopenQueue takes ownership)
4171 * flags contains the open flags for the associated bs
4173 * returns a pointer to bs_queue, which is either the newly allocated
4174 * bs_queue, or the existing bs_queue being used.
4176 * bs must be drained between bdrv_reopen_queue() and bdrv_reopen_multiple().
4178 * To be called with bs->aio_context locked.
4180 static BlockReopenQueue
*bdrv_reopen_queue_child(BlockReopenQueue
*bs_queue
,
4181 BlockDriverState
*bs
,
4183 const BdrvChildClass
*klass
,
4185 bool parent_is_format
,
4186 QDict
*parent_options
,
4192 BlockReopenQueueEntry
*bs_entry
;
4194 QDict
*old_options
, *explicit_options
, *options_copy
;
4198 /* Make sure that the caller remembered to use a drained section. This is
4199 * important to avoid graph changes between the recursive queuing here and
4200 * bdrv_reopen_multiple(). */
4201 assert(bs
->quiesce_counter
> 0);
4202 GLOBAL_STATE_CODE();
4204 if (bs_queue
== NULL
) {
4205 bs_queue
= g_new0(BlockReopenQueue
, 1);
4206 QTAILQ_INIT(bs_queue
);
4210 options
= qdict_new();
4213 /* Check if this BlockDriverState is already in the queue */
4214 QTAILQ_FOREACH(bs_entry
, bs_queue
, entry
) {
4215 if (bs
== bs_entry
->state
.bs
) {
4221 * Precedence of options:
4222 * 1. Explicitly passed in options (highest)
4223 * 2. Retained from explicitly set options of bs
4224 * 3. Inherited from parent node
4225 * 4. Retained from effective options of bs
4228 /* Old explicitly set values (don't overwrite by inherited value) */
4229 if (bs_entry
|| keep_old_opts
) {
4230 old_options
= qdict_clone_shallow(bs_entry
?
4231 bs_entry
->state
.explicit_options
:
4232 bs
->explicit_options
);
4233 bdrv_join_options(bs
, options
, old_options
);
4234 qobject_unref(old_options
);
4237 explicit_options
= qdict_clone_shallow(options
);
4239 /* Inherit from parent node */
4240 if (parent_options
) {
4242 klass
->inherit_options(role
, parent_is_format
, &flags
, options
,
4243 parent_flags
, parent_options
);
4245 flags
= bdrv_get_flags(bs
);
4248 if (keep_old_opts
) {
4249 /* Old values are used for options that aren't set yet */
4250 old_options
= qdict_clone_shallow(bs
->options
);
4251 bdrv_join_options(bs
, options
, old_options
);
4252 qobject_unref(old_options
);
4255 /* We have the final set of options so let's update the flags */
4256 options_copy
= qdict_clone_shallow(options
);
4257 opts
= qemu_opts_create(&bdrv_runtime_opts
, NULL
, 0, &error_abort
);
4258 qemu_opts_absorb_qdict(opts
, options_copy
, NULL
);
4259 update_flags_from_options(&flags
, opts
);
4260 qemu_opts_del(opts
);
4261 qobject_unref(options_copy
);
4263 /* bdrv_open_inherit() sets and clears some additional flags internally */
4264 flags
&= ~BDRV_O_PROTOCOL
;
4265 if (flags
& BDRV_O_RDWR
) {
4266 flags
|= BDRV_O_ALLOW_RDWR
;
4270 bs_entry
= g_new0(BlockReopenQueueEntry
, 1);
4271 QTAILQ_INSERT_TAIL(bs_queue
, bs_entry
, entry
);
4273 qobject_unref(bs_entry
->state
.options
);
4274 qobject_unref(bs_entry
->state
.explicit_options
);
4277 bs_entry
->state
.bs
= bs
;
4278 bs_entry
->state
.options
= options
;
4279 bs_entry
->state
.explicit_options
= explicit_options
;
4280 bs_entry
->state
.flags
= flags
;
4283 * If keep_old_opts is false then it means that unspecified
4284 * options must be reset to their original value. We don't allow
4285 * resetting 'backing' but we need to know if the option is
4286 * missing in order to decide if we have to return an error.
4288 if (!keep_old_opts
) {
4289 bs_entry
->state
.backing_missing
=
4290 !qdict_haskey(options
, "backing") &&
4291 !qdict_haskey(options
, "backing.driver");
4294 QLIST_FOREACH(child
, &bs
->children
, next
) {
4295 QDict
*new_child_options
= NULL
;
4296 bool child_keep_old
= keep_old_opts
;
4298 /* reopen can only change the options of block devices that were
4299 * implicitly created and inherited options. For other (referenced)
4300 * block devices, a syntax like "backing.foo" results in an error. */
4301 if (child
->bs
->inherits_from
!= bs
) {
4305 /* Check if the options contain a child reference */
4306 if (qdict_haskey(options
, child
->name
)) {
4307 const char *childref
= qdict_get_try_str(options
, child
->name
);
4309 * The current child must not be reopened if the child
4310 * reference is null or points to a different node.
4312 if (g_strcmp0(childref
, child
->bs
->node_name
)) {
4316 * If the child reference points to the current child then
4317 * reopen it with its existing set of options (note that
4318 * it can still inherit new options from the parent).
4320 child_keep_old
= true;
4322 /* Extract child options ("child-name.*") */
4323 char *child_key_dot
= g_strdup_printf("%s.", child
->name
);
4324 qdict_extract_subqdict(explicit_options
, NULL
, child_key_dot
);
4325 qdict_extract_subqdict(options
, &new_child_options
, child_key_dot
);
4326 g_free(child_key_dot
);
4329 bdrv_reopen_queue_child(bs_queue
, child
->bs
, new_child_options
,
4330 child
->klass
, child
->role
, bs
->drv
->is_format
,
4331 options
, flags
, child_keep_old
);
4337 /* To be called with bs->aio_context locked */
4338 BlockReopenQueue
*bdrv_reopen_queue(BlockReopenQueue
*bs_queue
,
4339 BlockDriverState
*bs
,
4340 QDict
*options
, bool keep_old_opts
)
4342 GLOBAL_STATE_CODE();
4344 return bdrv_reopen_queue_child(bs_queue
, bs
, options
, NULL
, 0, false,
4345 NULL
, 0, keep_old_opts
);
4348 void bdrv_reopen_queue_free(BlockReopenQueue
*bs_queue
)
4350 GLOBAL_STATE_CODE();
4352 BlockReopenQueueEntry
*bs_entry
, *next
;
4353 QTAILQ_FOREACH_SAFE(bs_entry
, bs_queue
, entry
, next
) {
4354 qobject_unref(bs_entry
->state
.explicit_options
);
4355 qobject_unref(bs_entry
->state
.options
);
4363 * Reopen multiple BlockDriverStates atomically & transactionally.
4365 * The queue passed in (bs_queue) must have been built up previous
4366 * via bdrv_reopen_queue().
4368 * Reopens all BDS specified in the queue, with the appropriate
4369 * flags. All devices are prepared for reopen, and failure of any
4370 * device will cause all device changes to be abandoned, and intermediate
4373 * If all devices prepare successfully, then the changes are committed
4376 * All affected nodes must be drained between bdrv_reopen_queue() and
4377 * bdrv_reopen_multiple().
4379 * To be called from the main thread, with all other AioContexts unlocked.
4381 int bdrv_reopen_multiple(BlockReopenQueue
*bs_queue
, Error
**errp
)
4384 BlockReopenQueueEntry
*bs_entry
, *next
;
4386 Transaction
*tran
= tran_new();
4387 g_autoptr(GSList
) refresh_list
= NULL
;
4389 assert(qemu_get_current_aio_context() == qemu_get_aio_context());
4390 assert(bs_queue
!= NULL
);
4391 GLOBAL_STATE_CODE();
4393 QTAILQ_FOREACH(bs_entry
, bs_queue
, entry
) {
4394 ctx
= bdrv_get_aio_context(bs_entry
->state
.bs
);
4395 aio_context_acquire(ctx
);
4396 ret
= bdrv_flush(bs_entry
->state
.bs
);
4397 aio_context_release(ctx
);
4399 error_setg_errno(errp
, -ret
, "Error flushing drive");
4404 QTAILQ_FOREACH(bs_entry
, bs_queue
, entry
) {
4405 assert(bs_entry
->state
.bs
->quiesce_counter
> 0);
4406 ctx
= bdrv_get_aio_context(bs_entry
->state
.bs
);
4407 aio_context_acquire(ctx
);
4408 ret
= bdrv_reopen_prepare(&bs_entry
->state
, bs_queue
, tran
, errp
);
4409 aio_context_release(ctx
);
4413 bs_entry
->prepared
= true;
4416 QTAILQ_FOREACH(bs_entry
, bs_queue
, entry
) {
4417 BDRVReopenState
*state
= &bs_entry
->state
;
4419 refresh_list
= g_slist_prepend(refresh_list
, state
->bs
);
4420 if (state
->old_backing_bs
) {
4421 refresh_list
= g_slist_prepend(refresh_list
, state
->old_backing_bs
);
4423 if (state
->old_file_bs
) {
4424 refresh_list
= g_slist_prepend(refresh_list
, state
->old_file_bs
);
4429 * Note that file-posix driver rely on permission update done during reopen
4430 * (even if no permission changed), because it wants "new" permissions for
4431 * reconfiguring the fd and that's why it does it in raw_check_perm(), not
4432 * in raw_reopen_prepare() which is called with "old" permissions.
4434 ret
= bdrv_list_refresh_perms(refresh_list
, bs_queue
, tran
, errp
);
4440 * If we reach this point, we have success and just need to apply the
4443 * Reverse order is used to comfort qcow2 driver: on commit it need to write
4444 * IN_USE flag to the image, to mark bitmaps in the image as invalid. But
4445 * children are usually goes after parents in reopen-queue, so go from last
4448 QTAILQ_FOREACH_REVERSE(bs_entry
, bs_queue
, entry
) {
4449 ctx
= bdrv_get_aio_context(bs_entry
->state
.bs
);
4450 aio_context_acquire(ctx
);
4451 bdrv_reopen_commit(&bs_entry
->state
);
4452 aio_context_release(ctx
);
4457 QTAILQ_FOREACH_REVERSE(bs_entry
, bs_queue
, entry
) {
4458 BlockDriverState
*bs
= bs_entry
->state
.bs
;
4460 if (bs
->drv
->bdrv_reopen_commit_post
) {
4461 ctx
= bdrv_get_aio_context(bs
);
4462 aio_context_acquire(ctx
);
4463 bs
->drv
->bdrv_reopen_commit_post(&bs_entry
->state
);
4464 aio_context_release(ctx
);
4473 QTAILQ_FOREACH_SAFE(bs_entry
, bs_queue
, entry
, next
) {
4474 if (bs_entry
->prepared
) {
4475 ctx
= bdrv_get_aio_context(bs_entry
->state
.bs
);
4476 aio_context_acquire(ctx
);
4477 bdrv_reopen_abort(&bs_entry
->state
);
4478 aio_context_release(ctx
);
4483 bdrv_reopen_queue_free(bs_queue
);
4488 int bdrv_reopen(BlockDriverState
*bs
, QDict
*opts
, bool keep_old_opts
,
4491 AioContext
*ctx
= bdrv_get_aio_context(bs
);
4492 BlockReopenQueue
*queue
;
4495 GLOBAL_STATE_CODE();
4497 bdrv_subtree_drained_begin(bs
);
4498 queue
= bdrv_reopen_queue(NULL
, bs
, opts
, keep_old_opts
);
4500 if (ctx
!= qemu_get_aio_context()) {
4501 aio_context_release(ctx
);
4503 ret
= bdrv_reopen_multiple(queue
, errp
);
4505 if (ctx
!= qemu_get_aio_context()) {
4506 aio_context_acquire(ctx
);
4508 bdrv_subtree_drained_end(bs
);
4513 int bdrv_reopen_set_read_only(BlockDriverState
*bs
, bool read_only
,
4516 QDict
*opts
= qdict_new();
4518 GLOBAL_STATE_CODE();
4520 qdict_put_bool(opts
, BDRV_OPT_READ_ONLY
, read_only
);
4522 return bdrv_reopen(bs
, opts
, true, errp
);
4526 * Take a BDRVReopenState and check if the value of 'backing' in the
4527 * reopen_state->options QDict is valid or not.
4529 * If 'backing' is missing from the QDict then return 0.
4531 * If 'backing' contains the node name of the backing file of
4532 * reopen_state->bs then return 0.
4534 * If 'backing' contains a different node name (or is null) then check
4535 * whether the current backing file can be replaced with the new one.
4536 * If that's the case then reopen_state->replace_backing_bs is set to
4537 * true and reopen_state->new_backing_bs contains a pointer to the new
4538 * backing BlockDriverState (or NULL).
4540 * Return 0 on success, otherwise return < 0 and set @errp.
4542 static int bdrv_reopen_parse_file_or_backing(BDRVReopenState
*reopen_state
,
4543 bool is_backing
, Transaction
*tran
,
4546 BlockDriverState
*bs
= reopen_state
->bs
;
4547 BlockDriverState
*new_child_bs
;
4548 BlockDriverState
*old_child_bs
= is_backing
? child_bs(bs
->backing
) :
4550 const char *child_name
= is_backing
? "backing" : "file";
4554 GLOBAL_STATE_CODE();
4556 value
= qdict_get(reopen_state
->options
, child_name
);
4557 if (value
== NULL
) {
4561 switch (qobject_type(value
)) {
4563 assert(is_backing
); /* The 'file' option does not allow a null value */
4564 new_child_bs
= NULL
;
4567 str
= qstring_get_str(qobject_to(QString
, value
));
4568 new_child_bs
= bdrv_lookup_bs(NULL
, str
, errp
);
4569 if (new_child_bs
== NULL
) {
4571 } else if (bdrv_recurse_has_child(new_child_bs
, bs
)) {
4572 error_setg(errp
, "Making '%s' a %s child of '%s' would create a "
4573 "cycle", str
, child_name
, bs
->node_name
);
4579 * The options QDict has been flattened, so 'backing' and 'file'
4580 * do not allow any other data type here.
4582 g_assert_not_reached();
4585 if (old_child_bs
== new_child_bs
) {
4590 if (bdrv_skip_implicit_filters(old_child_bs
) == new_child_bs
) {
4594 if (old_child_bs
->implicit
) {
4595 error_setg(errp
, "Cannot replace implicit %s child of %s",
4596 child_name
, bs
->node_name
);
4601 if (bs
->drv
->is_filter
&& !old_child_bs
) {
4603 * Filters always have a file or a backing child, so we are trying to
4604 * change wrong child
4606 error_setg(errp
, "'%s' is a %s filter node that does not support a "
4607 "%s child", bs
->node_name
, bs
->drv
->format_name
, child_name
);
4612 reopen_state
->old_backing_bs
= old_child_bs
;
4614 reopen_state
->old_file_bs
= old_child_bs
;
4617 return bdrv_set_file_or_backing_noperm(bs
, new_child_bs
, is_backing
,
4622 * Prepares a BlockDriverState for reopen. All changes are staged in the
4623 * 'opaque' field of the BDRVReopenState, which is used and allocated by
4624 * the block driver layer .bdrv_reopen_prepare()
4626 * bs is the BlockDriverState to reopen
4627 * flags are the new open flags
4628 * queue is the reopen queue
4630 * Returns 0 on success, non-zero on error. On error errp will be set
4633 * On failure, bdrv_reopen_abort() will be called to clean up any data.
4634 * It is the responsibility of the caller to then call the abort() or
4635 * commit() for any other BDS that have been left in a prepare() state
4638 static int bdrv_reopen_prepare(BDRVReopenState
*reopen_state
,
4639 BlockReopenQueue
*queue
,
4640 Transaction
*change_child_tran
, Error
**errp
)
4644 Error
*local_err
= NULL
;
4647 QDict
*orig_reopen_opts
;
4648 char *discard
= NULL
;
4650 bool drv_prepared
= false;
4652 assert(reopen_state
!= NULL
);
4653 assert(reopen_state
->bs
->drv
!= NULL
);
4654 GLOBAL_STATE_CODE();
4655 drv
= reopen_state
->bs
->drv
;
4657 /* This function and each driver's bdrv_reopen_prepare() remove
4658 * entries from reopen_state->options as they are processed, so
4659 * we need to make a copy of the original QDict. */
4660 orig_reopen_opts
= qdict_clone_shallow(reopen_state
->options
);
4662 /* Process generic block layer options */
4663 opts
= qemu_opts_create(&bdrv_runtime_opts
, NULL
, 0, &error_abort
);
4664 if (!qemu_opts_absorb_qdict(opts
, reopen_state
->options
, errp
)) {
4669 /* This was already called in bdrv_reopen_queue_child() so the flags
4670 * are up-to-date. This time we simply want to remove the options from
4671 * QemuOpts in order to indicate that they have been processed. */
4672 old_flags
= reopen_state
->flags
;
4673 update_flags_from_options(&reopen_state
->flags
, opts
);
4674 assert(old_flags
== reopen_state
->flags
);
4676 discard
= qemu_opt_get_del(opts
, BDRV_OPT_DISCARD
);
4677 if (discard
!= NULL
) {
4678 if (bdrv_parse_discard_flags(discard
, &reopen_state
->flags
) != 0) {
4679 error_setg(errp
, "Invalid discard option");
4685 reopen_state
->detect_zeroes
=
4686 bdrv_parse_detect_zeroes(opts
, reopen_state
->flags
, &local_err
);
4688 error_propagate(errp
, local_err
);
4693 /* All other options (including node-name and driver) must be unchanged.
4694 * Put them back into the QDict, so that they are checked at the end
4695 * of this function. */
4696 qemu_opts_to_qdict(opts
, reopen_state
->options
);
4698 /* If we are to stay read-only, do not allow permission change
4699 * to r/w. Attempting to set to r/w may fail if either BDRV_O_ALLOW_RDWR is
4700 * not set, or if the BDS still has copy_on_read enabled */
4701 read_only
= !(reopen_state
->flags
& BDRV_O_RDWR
);
4702 ret
= bdrv_can_set_read_only(reopen_state
->bs
, read_only
, true, &local_err
);
4704 error_propagate(errp
, local_err
);
4708 if (drv
->bdrv_reopen_prepare
) {
4710 * If a driver-specific option is missing, it means that we
4711 * should reset it to its default value.
4712 * But not all options allow that, so we need to check it first.
4714 ret
= bdrv_reset_options_allowed(reopen_state
->bs
,
4715 reopen_state
->options
, errp
);
4720 ret
= drv
->bdrv_reopen_prepare(reopen_state
, queue
, &local_err
);
4722 if (local_err
!= NULL
) {
4723 error_propagate(errp
, local_err
);
4725 bdrv_refresh_filename(reopen_state
->bs
);
4726 error_setg(errp
, "failed while preparing to reopen image '%s'",
4727 reopen_state
->bs
->filename
);
4732 /* It is currently mandatory to have a bdrv_reopen_prepare()
4733 * handler for each supported drv. */
4734 error_setg(errp
, "Block format '%s' used by node '%s' "
4735 "does not support reopening files", drv
->format_name
,
4736 bdrv_get_device_or_node_name(reopen_state
->bs
));
4741 drv_prepared
= true;
4744 * We must provide the 'backing' option if the BDS has a backing
4745 * file or if the image file has a backing file name as part of
4746 * its metadata. Otherwise the 'backing' option can be omitted.
4748 if (drv
->supports_backing
&& reopen_state
->backing_missing
&&
4749 (reopen_state
->bs
->backing
|| reopen_state
->bs
->backing_file
[0])) {
4750 error_setg(errp
, "backing is missing for '%s'",
4751 reopen_state
->bs
->node_name
);
4757 * Allow changing the 'backing' option. The new value can be
4758 * either a reference to an existing node (using its node name)
4759 * or NULL to simply detach the current backing file.
4761 ret
= bdrv_reopen_parse_file_or_backing(reopen_state
, true,
4762 change_child_tran
, errp
);
4766 qdict_del(reopen_state
->options
, "backing");
4768 /* Allow changing the 'file' option. In this case NULL is not allowed */
4769 ret
= bdrv_reopen_parse_file_or_backing(reopen_state
, false,
4770 change_child_tran
, errp
);
4774 qdict_del(reopen_state
->options
, "file");
4776 /* Options that are not handled are only okay if they are unchanged
4777 * compared to the old state. It is expected that some options are only
4778 * used for the initial open, but not reopen (e.g. filename) */
4779 if (qdict_size(reopen_state
->options
)) {
4780 const QDictEntry
*entry
= qdict_first(reopen_state
->options
);
4783 QObject
*new = entry
->value
;
4784 QObject
*old
= qdict_get(reopen_state
->bs
->options
, entry
->key
);
4786 /* Allow child references (child_name=node_name) as long as they
4787 * point to the current child (i.e. everything stays the same). */
4788 if (qobject_type(new) == QTYPE_QSTRING
) {
4790 QLIST_FOREACH(child
, &reopen_state
->bs
->children
, next
) {
4791 if (!strcmp(child
->name
, entry
->key
)) {
4797 if (!strcmp(child
->bs
->node_name
,
4798 qstring_get_str(qobject_to(QString
, new)))) {
4799 continue; /* Found child with this name, skip option */
4805 * TODO: When using -drive to specify blockdev options, all values
4806 * will be strings; however, when using -blockdev, blockdev-add or
4807 * filenames using the json:{} pseudo-protocol, they will be
4809 * In contrast, reopening options are (currently) always strings
4810 * (because you can only specify them through qemu-io; all other
4811 * callers do not specify any options).
4812 * Therefore, when using anything other than -drive to create a BDS,
4813 * this cannot detect non-string options as unchanged, because
4814 * qobject_is_equal() always returns false for objects of different
4815 * type. In the future, this should be remedied by correctly typing
4816 * all options. For now, this is not too big of an issue because
4817 * the user can simply omit options which cannot be changed anyway,
4818 * so they will stay unchanged.
4820 if (!qobject_is_equal(new, old
)) {
4821 error_setg(errp
, "Cannot change the option '%s'", entry
->key
);
4825 } while ((entry
= qdict_next(reopen_state
->options
, entry
)));
4830 /* Restore the original reopen_state->options QDict */
4831 qobject_unref(reopen_state
->options
);
4832 reopen_state
->options
= qobject_ref(orig_reopen_opts
);
4835 if (ret
< 0 && drv_prepared
) {
4836 /* drv->bdrv_reopen_prepare() has succeeded, so we need to
4837 * call drv->bdrv_reopen_abort() before signaling an error
4838 * (bdrv_reopen_multiple() will not call bdrv_reopen_abort()
4839 * when the respective bdrv_reopen_prepare() has failed) */
4840 if (drv
->bdrv_reopen_abort
) {
4841 drv
->bdrv_reopen_abort(reopen_state
);
4844 qemu_opts_del(opts
);
4845 qobject_unref(orig_reopen_opts
);
4851 * Takes the staged changes for the reopen from bdrv_reopen_prepare(), and
4852 * makes them final by swapping the staging BlockDriverState contents into
4853 * the active BlockDriverState contents.
4855 static void bdrv_reopen_commit(BDRVReopenState
*reopen_state
)
4858 BlockDriverState
*bs
;
4861 assert(reopen_state
!= NULL
);
4862 bs
= reopen_state
->bs
;
4864 assert(drv
!= NULL
);
4865 GLOBAL_STATE_CODE();
4867 /* If there are any driver level actions to take */
4868 if (drv
->bdrv_reopen_commit
) {
4869 drv
->bdrv_reopen_commit(reopen_state
);
4872 /* set BDS specific flags now */
4873 qobject_unref(bs
->explicit_options
);
4874 qobject_unref(bs
->options
);
4875 qobject_ref(reopen_state
->explicit_options
);
4876 qobject_ref(reopen_state
->options
);
4878 bs
->explicit_options
= reopen_state
->explicit_options
;
4879 bs
->options
= reopen_state
->options
;
4880 bs
->open_flags
= reopen_state
->flags
;
4881 bs
->detect_zeroes
= reopen_state
->detect_zeroes
;
4883 /* Remove child references from bs->options and bs->explicit_options.
4884 * Child options were already removed in bdrv_reopen_queue_child() */
4885 QLIST_FOREACH(child
, &bs
->children
, next
) {
4886 qdict_del(bs
->explicit_options
, child
->name
);
4887 qdict_del(bs
->options
, child
->name
);
4889 /* backing is probably removed, so it's not handled by previous loop */
4890 qdict_del(bs
->explicit_options
, "backing");
4891 qdict_del(bs
->options
, "backing");
4893 bdrv_refresh_limits(bs
, NULL
, NULL
);
4897 * Abort the reopen, and delete and free the staged changes in
4900 static void bdrv_reopen_abort(BDRVReopenState
*reopen_state
)
4904 assert(reopen_state
!= NULL
);
4905 drv
= reopen_state
->bs
->drv
;
4906 assert(drv
!= NULL
);
4907 GLOBAL_STATE_CODE();
4909 if (drv
->bdrv_reopen_abort
) {
4910 drv
->bdrv_reopen_abort(reopen_state
);
4915 static void bdrv_close(BlockDriverState
*bs
)
4917 BdrvAioNotifier
*ban
, *ban_next
;
4918 BdrvChild
*child
, *next
;
4920 GLOBAL_STATE_CODE();
4921 assert(!bs
->refcnt
);
4923 bdrv_drained_begin(bs
); /* complete I/O */
4925 bdrv_drain(bs
); /* in case flush left pending I/O */
4928 if (bs
->drv
->bdrv_close
) {
4929 /* Must unfreeze all children, so bdrv_unref_child() works */
4930 bs
->drv
->bdrv_close(bs
);
4935 QLIST_FOREACH_SAFE(child
, &bs
->children
, next
, next
) {
4936 bdrv_unref_child(bs
, child
);
4939 assert(!bs
->backing
);
4943 qatomic_set(&bs
->copy_on_read
, 0);
4944 bs
->backing_file
[0] = '\0';
4945 bs
->backing_format
[0] = '\0';
4946 bs
->total_sectors
= 0;
4947 bs
->encrypted
= false;
4949 qobject_unref(bs
->options
);
4950 qobject_unref(bs
->explicit_options
);
4952 bs
->explicit_options
= NULL
;
4953 qobject_unref(bs
->full_open_options
);
4954 bs
->full_open_options
= NULL
;
4955 g_free(bs
->block_status_cache
);
4956 bs
->block_status_cache
= NULL
;
4958 bdrv_release_named_dirty_bitmaps(bs
);
4959 assert(QLIST_EMPTY(&bs
->dirty_bitmaps
));
4961 QLIST_FOREACH_SAFE(ban
, &bs
->aio_notifiers
, list
, ban_next
) {
4964 QLIST_INIT(&bs
->aio_notifiers
);
4965 bdrv_drained_end(bs
);
4968 * If we're still inside some bdrv_drain_all_begin()/end() sections, end
4969 * them now since this BDS won't exist anymore when bdrv_drain_all_end()
4972 if (bs
->quiesce_counter
) {
4973 bdrv_drain_all_end_quiesce(bs
);
4977 void bdrv_close_all(void)
4979 GLOBAL_STATE_CODE();
4980 assert(job_next(NULL
) == NULL
);
4982 /* Drop references from requests still in flight, such as canceled block
4983 * jobs whose AIO context has not been polled yet */
4986 blk_remove_all_bs();
4987 blockdev_close_all_bdrv_states();
4989 assert(QTAILQ_EMPTY(&all_bdrv_states
));
4992 static bool should_update_child(BdrvChild
*c
, BlockDriverState
*to
)
4998 if (c
->klass
->stay_at_node
) {
5002 /* If the child @c belongs to the BDS @to, replacing the current
5003 * c->bs by @to would mean to create a loop.
5005 * Such a case occurs when appending a BDS to a backing chain.
5006 * For instance, imagine the following chain:
5008 * guest device -> node A -> further backing chain...
5010 * Now we create a new BDS B which we want to put on top of this
5011 * chain, so we first attach A as its backing node:
5016 * guest device -> node A -> further backing chain...
5018 * Finally we want to replace A by B. When doing that, we want to
5019 * replace all pointers to A by pointers to B -- except for the
5020 * pointer from B because (1) that would create a loop, and (2)
5021 * that pointer should simply stay intact:
5023 * guest device -> node B
5026 * node A -> further backing chain...
5028 * In general, when replacing a node A (c->bs) by a node B (@to),
5029 * if A is a child of B, that means we cannot replace A by B there
5030 * because that would create a loop. Silently detaching A from B
5031 * is also not really an option. So overall just leaving A in
5032 * place there is the most sensible choice.
5034 * We would also create a loop in any cases where @c is only
5035 * indirectly referenced by @to. Prevent this by returning false
5036 * if @c is found (by breadth-first search) anywhere in the whole
5041 found
= g_hash_table_new(NULL
, NULL
);
5042 g_hash_table_add(found
, to
);
5043 queue
= g_queue_new();
5044 g_queue_push_tail(queue
, to
);
5046 while (!g_queue_is_empty(queue
)) {
5047 BlockDriverState
*v
= g_queue_pop_head(queue
);
5050 QLIST_FOREACH(c2
, &v
->children
, next
) {
5056 if (g_hash_table_contains(found
, c2
->bs
)) {
5060 g_queue_push_tail(queue
, c2
->bs
);
5061 g_hash_table_add(found
, c2
->bs
);
5065 g_queue_free(queue
);
5066 g_hash_table_destroy(found
);
5071 static void bdrv_remove_child_commit(void *opaque
)
5073 GLOBAL_STATE_CODE();
5074 bdrv_child_free(opaque
);
5077 static TransactionActionDrv bdrv_remove_child_drv
= {
5078 .commit
= bdrv_remove_child_commit
,
5081 /* Function doesn't update permissions, caller is responsible for this. */
5082 static void bdrv_remove_child(BdrvChild
*child
, Transaction
*tran
)
5089 bdrv_replace_child_tran(child
, NULL
, tran
);
5092 tran_add(tran
, &bdrv_remove_child_drv
, child
);
5095 static int bdrv_replace_node_noperm(BlockDriverState
*from
,
5096 BlockDriverState
*to
,
5097 bool auto_skip
, Transaction
*tran
,
5100 BdrvChild
*c
, *next
;
5102 GLOBAL_STATE_CODE();
5104 QLIST_FOREACH_SAFE(c
, &from
->parents
, next_parent
, next
) {
5105 assert(c
->bs
== from
);
5106 if (!should_update_child(c
, to
)) {
5110 error_setg(errp
, "Should not change '%s' link to '%s'",
5111 c
->name
, from
->node_name
);
5115 error_setg(errp
, "Cannot change '%s' link to '%s'",
5116 c
->name
, from
->node_name
);
5119 bdrv_replace_child_tran(c
, to
, tran
);
5126 * With auto_skip=true bdrv_replace_node_common skips updating from parents
5127 * if it creates a parent-child relation loop or if parent is block-job.
5129 * With auto_skip=false the error is returned if from has a parent which should
5132 * With @detach_subchain=true @to must be in a backing chain of @from. In this
5133 * case backing link of the cow-parent of @to is removed.
5135 static int bdrv_replace_node_common(BlockDriverState
*from
,
5136 BlockDriverState
*to
,
5137 bool auto_skip
, bool detach_subchain
,
5140 Transaction
*tran
= tran_new();
5141 g_autoptr(GSList
) refresh_list
= NULL
;
5142 BlockDriverState
*to_cow_parent
= NULL
;
5145 GLOBAL_STATE_CODE();
5147 if (detach_subchain
) {
5148 assert(bdrv_chain_contains(from
, to
));
5150 for (to_cow_parent
= from
;
5151 bdrv_filter_or_cow_bs(to_cow_parent
) != to
;
5152 to_cow_parent
= bdrv_filter_or_cow_bs(to_cow_parent
))
5158 /* Make sure that @from doesn't go away until we have successfully attached
5159 * all of its parents to @to. */
5162 assert(qemu_get_current_aio_context() == qemu_get_aio_context());
5163 assert(bdrv_get_aio_context(from
) == bdrv_get_aio_context(to
));
5164 bdrv_drained_begin(from
);
5167 * Do the replacement without permission update.
5168 * Replacement may influence the permissions, we should calculate new
5169 * permissions based on new graph. If we fail, we'll roll-back the
5172 ret
= bdrv_replace_node_noperm(from
, to
, auto_skip
, tran
, errp
);
5177 if (detach_subchain
) {
5178 bdrv_remove_child(bdrv_filter_or_cow_child(to_cow_parent
), tran
);
5181 refresh_list
= g_slist_prepend(refresh_list
, to
);
5182 refresh_list
= g_slist_prepend(refresh_list
, from
);
5184 ret
= bdrv_list_refresh_perms(refresh_list
, NULL
, tran
, errp
);
5192 tran_finalize(tran
, ret
);
5194 bdrv_drained_end(from
);
5200 int bdrv_replace_node(BlockDriverState
*from
, BlockDriverState
*to
,
5203 GLOBAL_STATE_CODE();
5205 return bdrv_replace_node_common(from
, to
, true, false, errp
);
5208 int bdrv_drop_filter(BlockDriverState
*bs
, Error
**errp
)
5210 GLOBAL_STATE_CODE();
5212 return bdrv_replace_node_common(bs
, bdrv_filter_or_cow_bs(bs
), true, true,
5217 * Add new bs contents at the top of an image chain while the chain is
5218 * live, while keeping required fields on the top layer.
5220 * This will modify the BlockDriverState fields, and swap contents
5221 * between bs_new and bs_top. Both bs_new and bs_top are modified.
5223 * bs_new must not be attached to a BlockBackend and must not have backing
5226 * This function does not create any image files.
5228 int bdrv_append(BlockDriverState
*bs_new
, BlockDriverState
*bs_top
,
5233 Transaction
*tran
= tran_new();
5235 GLOBAL_STATE_CODE();
5237 assert(!bs_new
->backing
);
5239 child
= bdrv_attach_child_noperm(bs_new
, bs_top
, "backing",
5240 &child_of_bds
, bdrv_backing_role(bs_new
),
5247 ret
= bdrv_replace_node_noperm(bs_top
, bs_new
, true, tran
, errp
);
5252 ret
= bdrv_refresh_perms(bs_new
, tran
, errp
);
5254 tran_finalize(tran
, ret
);
5256 bdrv_refresh_limits(bs_top
, NULL
, NULL
);
5261 /* Not for empty child */
5262 int bdrv_replace_child_bs(BdrvChild
*child
, BlockDriverState
*new_bs
,
5266 Transaction
*tran
= tran_new();
5267 g_autoptr(GSList
) refresh_list
= NULL
;
5268 BlockDriverState
*old_bs
= child
->bs
;
5270 GLOBAL_STATE_CODE();
5273 bdrv_drained_begin(old_bs
);
5274 bdrv_drained_begin(new_bs
);
5276 bdrv_replace_child_tran(child
, new_bs
, tran
);
5278 refresh_list
= g_slist_prepend(refresh_list
, old_bs
);
5279 refresh_list
= g_slist_prepend(refresh_list
, new_bs
);
5281 ret
= bdrv_list_refresh_perms(refresh_list
, NULL
, tran
, errp
);
5283 tran_finalize(tran
, ret
);
5285 bdrv_drained_end(old_bs
);
5286 bdrv_drained_end(new_bs
);
5292 static void bdrv_delete(BlockDriverState
*bs
)
5294 assert(bdrv_op_blocker_is_empty(bs
));
5295 assert(!bs
->refcnt
);
5296 GLOBAL_STATE_CODE();
5298 /* remove from list, if necessary */
5299 if (bs
->node_name
[0] != '\0') {
5300 QTAILQ_REMOVE(&graph_bdrv_states
, bs
, node_list
);
5302 QTAILQ_REMOVE(&all_bdrv_states
, bs
, bs_list
);
5311 * Replace @bs by newly created block node.
5313 * @options is a QDict of options to pass to the block drivers, or NULL for an
5314 * empty set of options. The reference to the QDict belongs to the block layer
5315 * after the call (even on failure), so if the caller intends to reuse the
5316 * dictionary, it needs to use qobject_ref() before calling bdrv_open.
5318 BlockDriverState
*bdrv_insert_node(BlockDriverState
*bs
, QDict
*options
,
5319 int flags
, Error
**errp
)
5323 BlockDriverState
*new_node_bs
= NULL
;
5324 const char *drvname
, *node_name
;
5327 drvname
= qdict_get_try_str(options
, "driver");
5329 error_setg(errp
, "driver is not specified");
5333 drv
= bdrv_find_format(drvname
);
5335 error_setg(errp
, "Unknown driver: '%s'", drvname
);
5339 node_name
= qdict_get_try_str(options
, "node-name");
5341 GLOBAL_STATE_CODE();
5343 new_node_bs
= bdrv_new_open_driver_opts(drv
, node_name
, options
, flags
,
5345 options
= NULL
; /* bdrv_new_open_driver() eats options */
5347 error_prepend(errp
, "Could not create node: ");
5351 bdrv_drained_begin(bs
);
5352 ret
= bdrv_replace_node(bs
, new_node_bs
, errp
);
5353 bdrv_drained_end(bs
);
5356 error_prepend(errp
, "Could not replace node: ");
5363 qobject_unref(options
);
5364 bdrv_unref(new_node_bs
);
5369 * Run consistency checks on an image
5371 * Returns 0 if the check could be completed (it doesn't mean that the image is
5372 * free of errors) or -errno when an internal error occurred. The results of the
5373 * check are stored in res.
5375 int coroutine_fn
bdrv_co_check(BlockDriverState
*bs
,
5376 BdrvCheckResult
*res
, BdrvCheckMode fix
)
5379 if (bs
->drv
== NULL
) {
5382 if (bs
->drv
->bdrv_co_check
== NULL
) {
5386 memset(res
, 0, sizeof(*res
));
5387 return bs
->drv
->bdrv_co_check(bs
, res
, fix
);
5393 * -EINVAL - backing format specified, but no file
5394 * -ENOSPC - can't update the backing file because no space is left in the
5396 * -ENOTSUP - format driver doesn't support changing the backing file
5398 int bdrv_change_backing_file(BlockDriverState
*bs
, const char *backing_file
,
5399 const char *backing_fmt
, bool require
)
5401 BlockDriver
*drv
= bs
->drv
;
5404 GLOBAL_STATE_CODE();
5410 /* Backing file format doesn't make sense without a backing file */
5411 if (backing_fmt
&& !backing_file
) {
5415 if (require
&& backing_file
&& !backing_fmt
) {
5419 if (drv
->bdrv_change_backing_file
!= NULL
) {
5420 ret
= drv
->bdrv_change_backing_file(bs
, backing_file
, backing_fmt
);
5426 pstrcpy(bs
->backing_file
, sizeof(bs
->backing_file
), backing_file
?: "");
5427 pstrcpy(bs
->backing_format
, sizeof(bs
->backing_format
), backing_fmt
?: "");
5428 pstrcpy(bs
->auto_backing_file
, sizeof(bs
->auto_backing_file
),
5429 backing_file
?: "");
5435 * Finds the first non-filter node above bs in the chain between
5436 * active and bs. The returned node is either an immediate parent of
5437 * bs, or there are only filter nodes between the two.
5439 * Returns NULL if bs is not found in active's image chain,
5440 * or if active == bs.
5442 * Returns the bottommost base image if bs == NULL.
5444 BlockDriverState
*bdrv_find_overlay(BlockDriverState
*active
,
5445 BlockDriverState
*bs
)
5448 GLOBAL_STATE_CODE();
5450 bs
= bdrv_skip_filters(bs
);
5451 active
= bdrv_skip_filters(active
);
5454 BlockDriverState
*next
= bdrv_backing_chain_next(active
);
5464 /* Given a BDS, searches for the base layer. */
5465 BlockDriverState
*bdrv_find_base(BlockDriverState
*bs
)
5467 GLOBAL_STATE_CODE();
5469 return bdrv_find_overlay(bs
, NULL
);
5473 * Return true if at least one of the COW (backing) and filter links
5474 * between @bs and @base is frozen. @errp is set if that's the case.
5475 * @base must be reachable from @bs, or NULL.
5477 bool bdrv_is_backing_chain_frozen(BlockDriverState
*bs
, BlockDriverState
*base
,
5480 BlockDriverState
*i
;
5483 GLOBAL_STATE_CODE();
5485 for (i
= bs
; i
!= base
; i
= child_bs(child
)) {
5486 child
= bdrv_filter_or_cow_child(i
);
5488 if (child
&& child
->frozen
) {
5489 error_setg(errp
, "Cannot change '%s' link from '%s' to '%s'",
5490 child
->name
, i
->node_name
, child
->bs
->node_name
);
5499 * Freeze all COW (backing) and filter links between @bs and @base.
5500 * If any of the links is already frozen the operation is aborted and
5501 * none of the links are modified.
5502 * @base must be reachable from @bs, or NULL.
5503 * Returns 0 on success. On failure returns < 0 and sets @errp.
5505 int bdrv_freeze_backing_chain(BlockDriverState
*bs
, BlockDriverState
*base
,
5508 BlockDriverState
*i
;
5511 GLOBAL_STATE_CODE();
5513 if (bdrv_is_backing_chain_frozen(bs
, base
, errp
)) {
5517 for (i
= bs
; i
!= base
; i
= child_bs(child
)) {
5518 child
= bdrv_filter_or_cow_child(i
);
5519 if (child
&& child
->bs
->never_freeze
) {
5520 error_setg(errp
, "Cannot freeze '%s' link to '%s'",
5521 child
->name
, child
->bs
->node_name
);
5526 for (i
= bs
; i
!= base
; i
= child_bs(child
)) {
5527 child
= bdrv_filter_or_cow_child(i
);
5529 child
->frozen
= true;
5537 * Unfreeze all COW (backing) and filter links between @bs and @base.
5538 * The caller must ensure that all links are frozen before using this
5540 * @base must be reachable from @bs, or NULL.
5542 void bdrv_unfreeze_backing_chain(BlockDriverState
*bs
, BlockDriverState
*base
)
5544 BlockDriverState
*i
;
5547 GLOBAL_STATE_CODE();
5549 for (i
= bs
; i
!= base
; i
= child_bs(child
)) {
5550 child
= bdrv_filter_or_cow_child(i
);
5552 assert(child
->frozen
);
5553 child
->frozen
= false;
5559 * Drops images above 'base' up to and including 'top', and sets the image
5560 * above 'top' to have base as its backing file.
5562 * Requires that the overlay to 'top' is opened r/w, so that the backing file
5563 * information in 'bs' can be properly updated.
5565 * E.g., this will convert the following chain:
5566 * bottom <- base <- intermediate <- top <- active
5570 * bottom <- base <- active
5572 * It is allowed for bottom==base, in which case it converts:
5574 * base <- intermediate <- top <- active
5580 * If backing_file_str is non-NULL, it will be used when modifying top's
5581 * overlay image metadata.
5584 * if active == top, that is considered an error
5587 int bdrv_drop_intermediate(BlockDriverState
*top
, BlockDriverState
*base
,
5588 const char *backing_file_str
)
5590 BlockDriverState
*explicit_top
= top
;
5591 bool update_inherits_from
;
5593 Error
*local_err
= NULL
;
5595 g_autoptr(GSList
) updated_children
= NULL
;
5598 GLOBAL_STATE_CODE();
5601 bdrv_subtree_drained_begin(top
);
5603 if (!top
->drv
|| !base
->drv
) {
5607 /* Make sure that base is in the backing chain of top */
5608 if (!bdrv_chain_contains(top
, base
)) {
5612 /* If 'base' recursively inherits from 'top' then we should set
5613 * base->inherits_from to top->inherits_from after 'top' and all
5614 * other intermediate nodes have been dropped.
5615 * If 'top' is an implicit node (e.g. "commit_top") we should skip
5616 * it because no one inherits from it. We use explicit_top for that. */
5617 explicit_top
= bdrv_skip_implicit_filters(explicit_top
);
5618 update_inherits_from
= bdrv_inherits_from_recursive(base
, explicit_top
);
5620 /* success - we can delete the intermediate states, and link top->base */
5621 if (!backing_file_str
) {
5622 bdrv_refresh_filename(base
);
5623 backing_file_str
= base
->filename
;
5626 QLIST_FOREACH(c
, &top
->parents
, next_parent
) {
5627 updated_children
= g_slist_prepend(updated_children
, c
);
5631 * It seems correct to pass detach_subchain=true here, but it triggers
5632 * one more yet not fixed bug, when due to nested aio_poll loop we switch to
5633 * another drained section, which modify the graph (for example, removing
5634 * the child, which we keep in updated_children list). So, it's a TODO.
5636 * Note, bug triggered if pass detach_subchain=true here and run
5637 * test-bdrv-drain. test_drop_intermediate_poll() test-case will crash.
5640 bdrv_replace_node_common(top
, base
, false, false, &local_err
);
5642 error_report_err(local_err
);
5646 for (p
= updated_children
; p
; p
= p
->next
) {
5649 if (c
->klass
->update_filename
) {
5650 ret
= c
->klass
->update_filename(c
, base
, backing_file_str
,
5654 * TODO: Actually, we want to rollback all previous iterations
5655 * of this loop, and (which is almost impossible) previous
5656 * bdrv_replace_node()...
5658 * Note, that c->klass->update_filename may lead to permission
5659 * update, so it's a bad idea to call it inside permission
5660 * update transaction of bdrv_replace_node.
5662 error_report_err(local_err
);
5668 if (update_inherits_from
) {
5669 base
->inherits_from
= explicit_top
->inherits_from
;
5674 bdrv_subtree_drained_end(top
);
5680 * Implementation of BlockDriver.bdrv_get_allocated_file_size() that
5681 * sums the size of all data-bearing children. (This excludes backing
5684 static int64_t bdrv_sum_allocated_file_size(BlockDriverState
*bs
)
5687 int64_t child_size
, sum
= 0;
5689 QLIST_FOREACH(child
, &bs
->children
, next
) {
5690 if (child
->role
& (BDRV_CHILD_DATA
| BDRV_CHILD_METADATA
|
5691 BDRV_CHILD_FILTERED
))
5693 child_size
= bdrv_get_allocated_file_size(child
->bs
);
5694 if (child_size
< 0) {
5705 * Length of a allocated file in bytes. Sparse files are counted by actual
5706 * allocated space. Return < 0 if error or unknown.
5708 int64_t bdrv_get_allocated_file_size(BlockDriverState
*bs
)
5710 BlockDriver
*drv
= bs
->drv
;
5716 if (drv
->bdrv_get_allocated_file_size
) {
5717 return drv
->bdrv_get_allocated_file_size(bs
);
5720 if (drv
->bdrv_file_open
) {
5722 * Protocol drivers default to -ENOTSUP (most of their data is
5723 * not stored in any of their children (if they even have any),
5724 * so there is no generic way to figure it out).
5727 } else if (drv
->is_filter
) {
5728 /* Filter drivers default to the size of their filtered child */
5729 return bdrv_get_allocated_file_size(bdrv_filter_bs(bs
));
5731 /* Other drivers default to summing their children's sizes */
5732 return bdrv_sum_allocated_file_size(bs
);
5738 * @drv: Format driver
5739 * @opts: Creation options for new image
5740 * @in_bs: Existing image containing data for new image (may be NULL)
5741 * @errp: Error object
5742 * Returns: A #BlockMeasureInfo (free using qapi_free_BlockMeasureInfo())
5745 * Calculate file size required to create a new image.
5747 * If @in_bs is given then space for allocated clusters and zero clusters
5748 * from that image are included in the calculation. If @opts contains a
5749 * backing file that is shared by @in_bs then backing clusters may be omitted
5750 * from the calculation.
5752 * If @in_bs is NULL then the calculation includes no allocated clusters
5753 * unless a preallocation option is given in @opts.
5755 * Note that @in_bs may use a different BlockDriver from @drv.
5757 * If an error occurs the @errp pointer is set.
5759 BlockMeasureInfo
*bdrv_measure(BlockDriver
*drv
, QemuOpts
*opts
,
5760 BlockDriverState
*in_bs
, Error
**errp
)
5763 if (!drv
->bdrv_measure
) {
5764 error_setg(errp
, "Block driver '%s' does not support size measurement",
5769 return drv
->bdrv_measure(opts
, in_bs
, errp
);
5773 * Return number of sectors on success, -errno on error.
5775 int64_t bdrv_nb_sectors(BlockDriverState
*bs
)
5777 BlockDriver
*drv
= bs
->drv
;
5783 if (drv
->has_variable_length
) {
5784 int ret
= refresh_total_sectors(bs
, bs
->total_sectors
);
5789 return bs
->total_sectors
;
5793 * Return length in bytes on success, -errno on error.
5794 * The length is always a multiple of BDRV_SECTOR_SIZE.
5796 int64_t bdrv_getlength(BlockDriverState
*bs
)
5798 int64_t ret
= bdrv_nb_sectors(bs
);
5804 if (ret
> INT64_MAX
/ BDRV_SECTOR_SIZE
) {
5807 return ret
* BDRV_SECTOR_SIZE
;
5810 /* return 0 as number of sectors if no device present or error */
5811 void bdrv_get_geometry(BlockDriverState
*bs
, uint64_t *nb_sectors_ptr
)
5813 int64_t nb_sectors
= bdrv_nb_sectors(bs
);
5816 *nb_sectors_ptr
= nb_sectors
< 0 ? 0 : nb_sectors
;
5819 bool bdrv_is_sg(BlockDriverState
*bs
)
5826 * Return whether the given node supports compressed writes.
5828 bool bdrv_supports_compressed_writes(BlockDriverState
*bs
)
5830 BlockDriverState
*filtered
;
5833 if (!bs
->drv
|| !block_driver_can_compress(bs
->drv
)) {
5837 filtered
= bdrv_filter_bs(bs
);
5840 * Filters can only forward compressed writes, so we have to
5843 return bdrv_supports_compressed_writes(filtered
);
5849 const char *bdrv_get_format_name(BlockDriverState
*bs
)
5852 return bs
->drv
? bs
->drv
->format_name
: NULL
;
5855 static int qsort_strcmp(const void *a
, const void *b
)
5857 return strcmp(*(char *const *)a
, *(char *const *)b
);
5860 void bdrv_iterate_format(void (*it
)(void *opaque
, const char *name
),
5861 void *opaque
, bool read_only
)
5866 const char **formats
= NULL
;
5868 GLOBAL_STATE_CODE();
5870 QLIST_FOREACH(drv
, &bdrv_drivers
, list
) {
5871 if (drv
->format_name
) {
5875 if (use_bdrv_whitelist
&& !bdrv_is_whitelisted(drv
, read_only
)) {
5879 while (formats
&& i
&& !found
) {
5880 found
= !strcmp(formats
[--i
], drv
->format_name
);
5884 formats
= g_renew(const char *, formats
, count
+ 1);
5885 formats
[count
++] = drv
->format_name
;
5890 for (i
= 0; i
< (int)ARRAY_SIZE(block_driver_modules
); i
++) {
5891 const char *format_name
= block_driver_modules
[i
].format_name
;
5897 if (use_bdrv_whitelist
&&
5898 !bdrv_format_is_whitelisted(format_name
, read_only
)) {
5902 while (formats
&& j
&& !found
) {
5903 found
= !strcmp(formats
[--j
], format_name
);
5907 formats
= g_renew(const char *, formats
, count
+ 1);
5908 formats
[count
++] = format_name
;
5913 qsort(formats
, count
, sizeof(formats
[0]), qsort_strcmp
);
5915 for (i
= 0; i
< count
; i
++) {
5916 it(opaque
, formats
[i
]);
5922 /* This function is to find a node in the bs graph */
5923 BlockDriverState
*bdrv_find_node(const char *node_name
)
5925 BlockDriverState
*bs
;
5928 GLOBAL_STATE_CODE();
5930 QTAILQ_FOREACH(bs
, &graph_bdrv_states
, node_list
) {
5931 if (!strcmp(node_name
, bs
->node_name
)) {
5938 /* Put this QMP function here so it can access the static graph_bdrv_states. */
5939 BlockDeviceInfoList
*bdrv_named_nodes_list(bool flat
,
5942 BlockDeviceInfoList
*list
;
5943 BlockDriverState
*bs
;
5945 GLOBAL_STATE_CODE();
5948 QTAILQ_FOREACH(bs
, &graph_bdrv_states
, node_list
) {
5949 BlockDeviceInfo
*info
= bdrv_block_device_info(NULL
, bs
, flat
, errp
);
5951 qapi_free_BlockDeviceInfoList(list
);
5954 QAPI_LIST_PREPEND(list
, info
);
5960 typedef struct XDbgBlockGraphConstructor
{
5961 XDbgBlockGraph
*graph
;
5962 GHashTable
*graph_nodes
;
5963 } XDbgBlockGraphConstructor
;
5965 static XDbgBlockGraphConstructor
*xdbg_graph_new(void)
5967 XDbgBlockGraphConstructor
*gr
= g_new(XDbgBlockGraphConstructor
, 1);
5969 gr
->graph
= g_new0(XDbgBlockGraph
, 1);
5970 gr
->graph_nodes
= g_hash_table_new(NULL
, NULL
);
5975 static XDbgBlockGraph
*xdbg_graph_finalize(XDbgBlockGraphConstructor
*gr
)
5977 XDbgBlockGraph
*graph
= gr
->graph
;
5979 g_hash_table_destroy(gr
->graph_nodes
);
5985 static uintptr_t xdbg_graph_node_num(XDbgBlockGraphConstructor
*gr
, void *node
)
5987 uintptr_t ret
= (uintptr_t)g_hash_table_lookup(gr
->graph_nodes
, node
);
5994 * Start counting from 1, not 0, because 0 interferes with not-found (NULL)
5995 * answer of g_hash_table_lookup.
5997 ret
= g_hash_table_size(gr
->graph_nodes
) + 1;
5998 g_hash_table_insert(gr
->graph_nodes
, node
, (void *)ret
);
6003 static void xdbg_graph_add_node(XDbgBlockGraphConstructor
*gr
, void *node
,
6004 XDbgBlockGraphNodeType type
, const char *name
)
6006 XDbgBlockGraphNode
*n
;
6008 n
= g_new0(XDbgBlockGraphNode
, 1);
6010 n
->id
= xdbg_graph_node_num(gr
, node
);
6012 n
->name
= g_strdup(name
);
6014 QAPI_LIST_PREPEND(gr
->graph
->nodes
, n
);
6017 static void xdbg_graph_add_edge(XDbgBlockGraphConstructor
*gr
, void *parent
,
6018 const BdrvChild
*child
)
6020 BlockPermission qapi_perm
;
6021 XDbgBlockGraphEdge
*edge
;
6022 GLOBAL_STATE_CODE();
6024 edge
= g_new0(XDbgBlockGraphEdge
, 1);
6026 edge
->parent
= xdbg_graph_node_num(gr
, parent
);
6027 edge
->child
= xdbg_graph_node_num(gr
, child
->bs
);
6028 edge
->name
= g_strdup(child
->name
);
6030 for (qapi_perm
= 0; qapi_perm
< BLOCK_PERMISSION__MAX
; qapi_perm
++) {
6031 uint64_t flag
= bdrv_qapi_perm_to_blk_perm(qapi_perm
);
6033 if (flag
& child
->perm
) {
6034 QAPI_LIST_PREPEND(edge
->perm
, qapi_perm
);
6036 if (flag
& child
->shared_perm
) {
6037 QAPI_LIST_PREPEND(edge
->shared_perm
, qapi_perm
);
6041 QAPI_LIST_PREPEND(gr
->graph
->edges
, edge
);
6045 XDbgBlockGraph
*bdrv_get_xdbg_block_graph(Error
**errp
)
6049 BlockDriverState
*bs
;
6051 XDbgBlockGraphConstructor
*gr
= xdbg_graph_new();
6053 GLOBAL_STATE_CODE();
6055 for (blk
= blk_all_next(NULL
); blk
; blk
= blk_all_next(blk
)) {
6056 char *allocated_name
= NULL
;
6057 const char *name
= blk_name(blk
);
6060 name
= allocated_name
= blk_get_attached_dev_id(blk
);
6062 xdbg_graph_add_node(gr
, blk
, X_DBG_BLOCK_GRAPH_NODE_TYPE_BLOCK_BACKEND
,
6064 g_free(allocated_name
);
6065 if (blk_root(blk
)) {
6066 xdbg_graph_add_edge(gr
, blk
, blk_root(blk
));
6070 WITH_JOB_LOCK_GUARD() {
6071 for (job
= block_job_next_locked(NULL
); job
;
6072 job
= block_job_next_locked(job
)) {
6075 xdbg_graph_add_node(gr
, job
, X_DBG_BLOCK_GRAPH_NODE_TYPE_BLOCK_JOB
,
6077 for (el
= job
->nodes
; el
; el
= el
->next
) {
6078 xdbg_graph_add_edge(gr
, job
, (BdrvChild
*)el
->data
);
6083 QTAILQ_FOREACH(bs
, &graph_bdrv_states
, node_list
) {
6084 xdbg_graph_add_node(gr
, bs
, X_DBG_BLOCK_GRAPH_NODE_TYPE_BLOCK_DRIVER
,
6086 QLIST_FOREACH(child
, &bs
->children
, next
) {
6087 xdbg_graph_add_edge(gr
, bs
, child
);
6091 return xdbg_graph_finalize(gr
);
6094 BlockDriverState
*bdrv_lookup_bs(const char *device
,
6095 const char *node_name
,
6099 BlockDriverState
*bs
;
6101 GLOBAL_STATE_CODE();
6104 blk
= blk_by_name(device
);
6109 error_setg(errp
, "Device '%s' has no medium", device
);
6117 bs
= bdrv_find_node(node_name
);
6124 error_setg(errp
, "Cannot find device=\'%s\' nor node-name=\'%s\'",
6125 device
? device
: "",
6126 node_name
? node_name
: "");
6130 /* If 'base' is in the same chain as 'top', return true. Otherwise,
6131 * return false. If either argument is NULL, return false. */
6132 bool bdrv_chain_contains(BlockDriverState
*top
, BlockDriverState
*base
)
6135 GLOBAL_STATE_CODE();
6137 while (top
&& top
!= base
) {
6138 top
= bdrv_filter_or_cow_bs(top
);
6144 BlockDriverState
*bdrv_next_node(BlockDriverState
*bs
)
6146 GLOBAL_STATE_CODE();
6148 return QTAILQ_FIRST(&graph_bdrv_states
);
6150 return QTAILQ_NEXT(bs
, node_list
);
6153 BlockDriverState
*bdrv_next_all_states(BlockDriverState
*bs
)
6155 GLOBAL_STATE_CODE();
6157 return QTAILQ_FIRST(&all_bdrv_states
);
6159 return QTAILQ_NEXT(bs
, bs_list
);
6162 const char *bdrv_get_node_name(const BlockDriverState
*bs
)
6165 return bs
->node_name
;
6168 const char *bdrv_get_parent_name(const BlockDriverState
*bs
)
6174 /* If multiple parents have a name, just pick the first one. */
6175 QLIST_FOREACH(c
, &bs
->parents
, next_parent
) {
6176 if (c
->klass
->get_name
) {
6177 name
= c
->klass
->get_name(c
);
6178 if (name
&& *name
) {
6187 /* TODO check what callers really want: bs->node_name or blk_name() */
6188 const char *bdrv_get_device_name(const BlockDriverState
*bs
)
6191 return bdrv_get_parent_name(bs
) ?: "";
6194 /* This can be used to identify nodes that might not have a device
6195 * name associated. Since node and device names live in the same
6196 * namespace, the result is unambiguous. The exception is if both are
6197 * absent, then this returns an empty (non-null) string. */
6198 const char *bdrv_get_device_or_node_name(const BlockDriverState
*bs
)
6201 return bdrv_get_parent_name(bs
) ?: bs
->node_name
;
6204 int bdrv_get_flags(BlockDriverState
*bs
)
6207 return bs
->open_flags
;
6210 int bdrv_has_zero_init_1(BlockDriverState
*bs
)
6212 GLOBAL_STATE_CODE();
6216 int bdrv_has_zero_init(BlockDriverState
*bs
)
6218 BlockDriverState
*filtered
;
6219 GLOBAL_STATE_CODE();
6225 /* If BS is a copy on write image, it is initialized to
6226 the contents of the base image, which may not be zeroes. */
6227 if (bdrv_cow_child(bs
)) {
6230 if (bs
->drv
->bdrv_has_zero_init
) {
6231 return bs
->drv
->bdrv_has_zero_init(bs
);
6234 filtered
= bdrv_filter_bs(bs
);
6236 return bdrv_has_zero_init(filtered
);
6243 bool bdrv_can_write_zeroes_with_unmap(BlockDriverState
*bs
)
6246 if (!(bs
->open_flags
& BDRV_O_UNMAP
)) {
6250 return bs
->supported_zero_flags
& BDRV_REQ_MAY_UNMAP
;
6253 void bdrv_get_backing_filename(BlockDriverState
*bs
,
6254 char *filename
, int filename_size
)
6257 pstrcpy(filename
, filename_size
, bs
->backing_file
);
6260 int bdrv_get_info(BlockDriverState
*bs
, BlockDriverInfo
*bdi
)
6263 BlockDriver
*drv
= bs
->drv
;
6265 /* if bs->drv == NULL, bs is closed, so there's nothing to do here */
6269 if (!drv
->bdrv_get_info
) {
6270 BlockDriverState
*filtered
= bdrv_filter_bs(bs
);
6272 return bdrv_get_info(filtered
, bdi
);
6276 memset(bdi
, 0, sizeof(*bdi
));
6277 ret
= drv
->bdrv_get_info(bs
, bdi
);
6282 if (bdi
->cluster_size
> BDRV_MAX_ALIGNMENT
) {
6289 ImageInfoSpecific
*bdrv_get_specific_info(BlockDriverState
*bs
,
6292 BlockDriver
*drv
= bs
->drv
;
6294 if (drv
&& drv
->bdrv_get_specific_info
) {
6295 return drv
->bdrv_get_specific_info(bs
, errp
);
6300 BlockStatsSpecific
*bdrv_get_specific_stats(BlockDriverState
*bs
)
6302 BlockDriver
*drv
= bs
->drv
;
6304 if (!drv
|| !drv
->bdrv_get_specific_stats
) {
6307 return drv
->bdrv_get_specific_stats(bs
);
6310 void bdrv_debug_event(BlockDriverState
*bs
, BlkdebugEvent event
)
6313 if (!bs
|| !bs
->drv
|| !bs
->drv
->bdrv_debug_event
) {
6317 bs
->drv
->bdrv_debug_event(bs
, event
);
6320 static BlockDriverState
*bdrv_find_debug_node(BlockDriverState
*bs
)
6322 GLOBAL_STATE_CODE();
6323 while (bs
&& bs
->drv
&& !bs
->drv
->bdrv_debug_breakpoint
) {
6324 bs
= bdrv_primary_bs(bs
);
6327 if (bs
&& bs
->drv
&& bs
->drv
->bdrv_debug_breakpoint
) {
6328 assert(bs
->drv
->bdrv_debug_remove_breakpoint
);
6335 int bdrv_debug_breakpoint(BlockDriverState
*bs
, const char *event
,
6338 GLOBAL_STATE_CODE();
6339 bs
= bdrv_find_debug_node(bs
);
6341 return bs
->drv
->bdrv_debug_breakpoint(bs
, event
, tag
);
6347 int bdrv_debug_remove_breakpoint(BlockDriverState
*bs
, const char *tag
)
6349 GLOBAL_STATE_CODE();
6350 bs
= bdrv_find_debug_node(bs
);
6352 return bs
->drv
->bdrv_debug_remove_breakpoint(bs
, tag
);
6358 int bdrv_debug_resume(BlockDriverState
*bs
, const char *tag
)
6360 GLOBAL_STATE_CODE();
6361 while (bs
&& (!bs
->drv
|| !bs
->drv
->bdrv_debug_resume
)) {
6362 bs
= bdrv_primary_bs(bs
);
6365 if (bs
&& bs
->drv
&& bs
->drv
->bdrv_debug_resume
) {
6366 return bs
->drv
->bdrv_debug_resume(bs
, tag
);
6372 bool bdrv_debug_is_suspended(BlockDriverState
*bs
, const char *tag
)
6374 GLOBAL_STATE_CODE();
6375 while (bs
&& bs
->drv
&& !bs
->drv
->bdrv_debug_is_suspended
) {
6376 bs
= bdrv_primary_bs(bs
);
6379 if (bs
&& bs
->drv
&& bs
->drv
->bdrv_debug_is_suspended
) {
6380 return bs
->drv
->bdrv_debug_is_suspended(bs
, tag
);
6386 /* backing_file can either be relative, or absolute, or a protocol. If it is
6387 * relative, it must be relative to the chain. So, passing in bs->filename
6388 * from a BDS as backing_file should not be done, as that may be relative to
6389 * the CWD rather than the chain. */
6390 BlockDriverState
*bdrv_find_backing_image(BlockDriverState
*bs
,
6391 const char *backing_file
)
6393 char *filename_full
= NULL
;
6394 char *backing_file_full
= NULL
;
6395 char *filename_tmp
= NULL
;
6396 int is_protocol
= 0;
6397 bool filenames_refreshed
= false;
6398 BlockDriverState
*curr_bs
= NULL
;
6399 BlockDriverState
*retval
= NULL
;
6400 BlockDriverState
*bs_below
;
6402 GLOBAL_STATE_CODE();
6404 if (!bs
|| !bs
->drv
|| !backing_file
) {
6408 filename_full
= g_malloc(PATH_MAX
);
6409 backing_file_full
= g_malloc(PATH_MAX
);
6411 is_protocol
= path_has_protocol(backing_file
);
6414 * Being largely a legacy function, skip any filters here
6415 * (because filters do not have normal filenames, so they cannot
6416 * match anyway; and allowing json:{} filenames is a bit out of
6419 for (curr_bs
= bdrv_skip_filters(bs
);
6420 bdrv_cow_child(curr_bs
) != NULL
;
6423 bs_below
= bdrv_backing_chain_next(curr_bs
);
6425 if (bdrv_backing_overridden(curr_bs
)) {
6427 * If the backing file was overridden, we can only compare
6428 * directly against the backing node's filename.
6431 if (!filenames_refreshed
) {
6433 * This will automatically refresh all of the
6434 * filenames in the rest of the backing chain, so we
6435 * only need to do this once.
6437 bdrv_refresh_filename(bs_below
);
6438 filenames_refreshed
= true;
6441 if (strcmp(backing_file
, bs_below
->filename
) == 0) {
6445 } else if (is_protocol
|| path_has_protocol(curr_bs
->backing_file
)) {
6447 * If either of the filename paths is actually a protocol, then
6448 * compare unmodified paths; otherwise make paths relative.
6450 char *backing_file_full_ret
;
6452 if (strcmp(backing_file
, curr_bs
->backing_file
) == 0) {
6456 /* Also check against the full backing filename for the image */
6457 backing_file_full_ret
= bdrv_get_full_backing_filename(curr_bs
,
6459 if (backing_file_full_ret
) {
6460 bool equal
= strcmp(backing_file
, backing_file_full_ret
) == 0;
6461 g_free(backing_file_full_ret
);
6468 /* If not an absolute filename path, make it relative to the current
6469 * image's filename path */
6470 filename_tmp
= bdrv_make_absolute_filename(curr_bs
, backing_file
,
6472 /* We are going to compare canonicalized absolute pathnames */
6473 if (!filename_tmp
|| !realpath(filename_tmp
, filename_full
)) {
6474 g_free(filename_tmp
);
6477 g_free(filename_tmp
);
6479 /* We need to make sure the backing filename we are comparing against
6480 * is relative to the current image filename (or absolute) */
6481 filename_tmp
= bdrv_get_full_backing_filename(curr_bs
, NULL
);
6482 if (!filename_tmp
|| !realpath(filename_tmp
, backing_file_full
)) {
6483 g_free(filename_tmp
);
6486 g_free(filename_tmp
);
6488 if (strcmp(backing_file_full
, filename_full
) == 0) {
6495 g_free(filename_full
);
6496 g_free(backing_file_full
);
6500 void bdrv_init(void)
6502 #ifdef CONFIG_BDRV_WHITELIST_TOOLS
6503 use_bdrv_whitelist
= 1;
6505 module_call_init(MODULE_INIT_BLOCK
);
6508 void bdrv_init_with_whitelist(void)
6510 use_bdrv_whitelist
= 1;
6514 int bdrv_activate(BlockDriverState
*bs
, Error
**errp
)
6516 BdrvChild
*child
, *parent
;
6517 Error
*local_err
= NULL
;
6519 BdrvDirtyBitmap
*bm
;
6521 GLOBAL_STATE_CODE();
6527 QLIST_FOREACH(child
, &bs
->children
, next
) {
6528 bdrv_activate(child
->bs
, &local_err
);
6530 error_propagate(errp
, local_err
);
6536 * Update permissions, they may differ for inactive nodes.
6538 * Note that the required permissions of inactive images are always a
6539 * subset of the permissions required after activating the image. This
6540 * allows us to just get the permissions upfront without restricting
6541 * bdrv_co_invalidate_cache().
6543 * It also means that in error cases, we don't have to try and revert to
6544 * the old permissions (which is an operation that could fail, too). We can
6545 * just keep the extended permissions for the next time that an activation
6546 * of the image is tried.
6548 if (bs
->open_flags
& BDRV_O_INACTIVE
) {
6549 bs
->open_flags
&= ~BDRV_O_INACTIVE
;
6550 ret
= bdrv_refresh_perms(bs
, NULL
, errp
);
6552 bs
->open_flags
|= BDRV_O_INACTIVE
;
6556 ret
= bdrv_invalidate_cache(bs
, errp
);
6558 bs
->open_flags
|= BDRV_O_INACTIVE
;
6562 FOR_EACH_DIRTY_BITMAP(bs
, bm
) {
6563 bdrv_dirty_bitmap_skip_store(bm
, false);
6566 ret
= refresh_total_sectors(bs
, bs
->total_sectors
);
6568 bs
->open_flags
|= BDRV_O_INACTIVE
;
6569 error_setg_errno(errp
, -ret
, "Could not refresh total sector count");
6574 QLIST_FOREACH(parent
, &bs
->parents
, next_parent
) {
6575 if (parent
->klass
->activate
) {
6576 parent
->klass
->activate(parent
, &local_err
);
6578 bs
->open_flags
|= BDRV_O_INACTIVE
;
6579 error_propagate(errp
, local_err
);
6588 int coroutine_fn
bdrv_co_invalidate_cache(BlockDriverState
*bs
, Error
**errp
)
6590 Error
*local_err
= NULL
;
6593 assert(!(bs
->open_flags
& BDRV_O_INACTIVE
));
6595 if (bs
->drv
->bdrv_co_invalidate_cache
) {
6596 bs
->drv
->bdrv_co_invalidate_cache(bs
, &local_err
);
6598 error_propagate(errp
, local_err
);
6606 void bdrv_activate_all(Error
**errp
)
6608 BlockDriverState
*bs
;
6609 BdrvNextIterator it
;
6611 GLOBAL_STATE_CODE();
6613 for (bs
= bdrv_first(&it
); bs
; bs
= bdrv_next(&it
)) {
6614 AioContext
*aio_context
= bdrv_get_aio_context(bs
);
6617 aio_context_acquire(aio_context
);
6618 ret
= bdrv_activate(bs
, errp
);
6619 aio_context_release(aio_context
);
6621 bdrv_next_cleanup(&it
);
6627 static bool bdrv_has_bds_parent(BlockDriverState
*bs
, bool only_active
)
6630 GLOBAL_STATE_CODE();
6632 QLIST_FOREACH(parent
, &bs
->parents
, next_parent
) {
6633 if (parent
->klass
->parent_is_bds
) {
6634 BlockDriverState
*parent_bs
= parent
->opaque
;
6635 if (!only_active
|| !(parent_bs
->open_flags
& BDRV_O_INACTIVE
)) {
6644 static int bdrv_inactivate_recurse(BlockDriverState
*bs
)
6646 BdrvChild
*child
, *parent
;
6648 uint64_t cumulative_perms
, cumulative_shared_perms
;
6650 GLOBAL_STATE_CODE();
6656 /* Make sure that we don't inactivate a child before its parent.
6657 * It will be covered by recursion from the yet active parent. */
6658 if (bdrv_has_bds_parent(bs
, true)) {
6662 assert(!(bs
->open_flags
& BDRV_O_INACTIVE
));
6664 /* Inactivate this node */
6665 if (bs
->drv
->bdrv_inactivate
) {
6666 ret
= bs
->drv
->bdrv_inactivate(bs
);
6672 QLIST_FOREACH(parent
, &bs
->parents
, next_parent
) {
6673 if (parent
->klass
->inactivate
) {
6674 ret
= parent
->klass
->inactivate(parent
);
6681 bdrv_get_cumulative_perm(bs
, &cumulative_perms
,
6682 &cumulative_shared_perms
);
6683 if (cumulative_perms
& (BLK_PERM_WRITE
| BLK_PERM_WRITE_UNCHANGED
)) {
6684 /* Our inactive parents still need write access. Inactivation failed. */
6688 bs
->open_flags
|= BDRV_O_INACTIVE
;
6691 * Update permissions, they may differ for inactive nodes.
6692 * We only tried to loosen restrictions, so errors are not fatal, ignore
6695 bdrv_refresh_perms(bs
, NULL
, NULL
);
6697 /* Recursively inactivate children */
6698 QLIST_FOREACH(child
, &bs
->children
, next
) {
6699 ret
= bdrv_inactivate_recurse(child
->bs
);
6708 int bdrv_inactivate_all(void)
6710 BlockDriverState
*bs
= NULL
;
6711 BdrvNextIterator it
;
6713 GSList
*aio_ctxs
= NULL
, *ctx
;
6715 GLOBAL_STATE_CODE();
6717 for (bs
= bdrv_first(&it
); bs
; bs
= bdrv_next(&it
)) {
6718 AioContext
*aio_context
= bdrv_get_aio_context(bs
);
6720 if (!g_slist_find(aio_ctxs
, aio_context
)) {
6721 aio_ctxs
= g_slist_prepend(aio_ctxs
, aio_context
);
6722 aio_context_acquire(aio_context
);
6726 for (bs
= bdrv_first(&it
); bs
; bs
= bdrv_next(&it
)) {
6727 /* Nodes with BDS parents are covered by recursion from the last
6728 * parent that gets inactivated. Don't inactivate them a second
6729 * time if that has already happened. */
6730 if (bdrv_has_bds_parent(bs
, false)) {
6733 ret
= bdrv_inactivate_recurse(bs
);
6735 bdrv_next_cleanup(&it
);
6741 for (ctx
= aio_ctxs
; ctx
!= NULL
; ctx
= ctx
->next
) {
6742 AioContext
*aio_context
= ctx
->data
;
6743 aio_context_release(aio_context
);
6745 g_slist_free(aio_ctxs
);
6750 /**************************************************************/
6751 /* removable device support */
6754 * Return TRUE if the media is present
6756 bool bdrv_is_inserted(BlockDriverState
*bs
)
6758 BlockDriver
*drv
= bs
->drv
;
6765 if (drv
->bdrv_is_inserted
) {
6766 return drv
->bdrv_is_inserted(bs
);
6768 QLIST_FOREACH(child
, &bs
->children
, next
) {
6769 if (!bdrv_is_inserted(child
->bs
)) {
6777 * If eject_flag is TRUE, eject the media. Otherwise, close the tray
6779 void bdrv_eject(BlockDriverState
*bs
, bool eject_flag
)
6781 BlockDriver
*drv
= bs
->drv
;
6784 if (drv
&& drv
->bdrv_eject
) {
6785 drv
->bdrv_eject(bs
, eject_flag
);
6790 * Lock or unlock the media (if it is locked, the user won't be able
6791 * to eject it manually).
6793 void bdrv_lock_medium(BlockDriverState
*bs
, bool locked
)
6795 BlockDriver
*drv
= bs
->drv
;
6797 trace_bdrv_lock_medium(bs
, locked
);
6799 if (drv
&& drv
->bdrv_lock_medium
) {
6800 drv
->bdrv_lock_medium(bs
, locked
);
6804 /* Get a reference to bs */
6805 void bdrv_ref(BlockDriverState
*bs
)
6807 GLOBAL_STATE_CODE();
6811 /* Release a previously grabbed reference to bs.
6812 * If after releasing, reference count is zero, the BlockDriverState is
6814 void bdrv_unref(BlockDriverState
*bs
)
6816 GLOBAL_STATE_CODE();
6820 assert(bs
->refcnt
> 0);
6821 if (--bs
->refcnt
== 0) {
6826 struct BdrvOpBlocker
{
6828 QLIST_ENTRY(BdrvOpBlocker
) list
;
6831 bool bdrv_op_is_blocked(BlockDriverState
*bs
, BlockOpType op
, Error
**errp
)
6833 BdrvOpBlocker
*blocker
;
6834 GLOBAL_STATE_CODE();
6835 assert((int) op
>= 0 && op
< BLOCK_OP_TYPE_MAX
);
6836 if (!QLIST_EMPTY(&bs
->op_blockers
[op
])) {
6837 blocker
= QLIST_FIRST(&bs
->op_blockers
[op
]);
6838 error_propagate_prepend(errp
, error_copy(blocker
->reason
),
6839 "Node '%s' is busy: ",
6840 bdrv_get_device_or_node_name(bs
));
6846 void bdrv_op_block(BlockDriverState
*bs
, BlockOpType op
, Error
*reason
)
6848 BdrvOpBlocker
*blocker
;
6849 GLOBAL_STATE_CODE();
6850 assert((int) op
>= 0 && op
< BLOCK_OP_TYPE_MAX
);
6852 blocker
= g_new0(BdrvOpBlocker
, 1);
6853 blocker
->reason
= reason
;
6854 QLIST_INSERT_HEAD(&bs
->op_blockers
[op
], blocker
, list
);
6857 void bdrv_op_unblock(BlockDriverState
*bs
, BlockOpType op
, Error
*reason
)
6859 BdrvOpBlocker
*blocker
, *next
;
6860 GLOBAL_STATE_CODE();
6861 assert((int) op
>= 0 && op
< BLOCK_OP_TYPE_MAX
);
6862 QLIST_FOREACH_SAFE(blocker
, &bs
->op_blockers
[op
], list
, next
) {
6863 if (blocker
->reason
== reason
) {
6864 QLIST_REMOVE(blocker
, list
);
6870 void bdrv_op_block_all(BlockDriverState
*bs
, Error
*reason
)
6873 GLOBAL_STATE_CODE();
6874 for (i
= 0; i
< BLOCK_OP_TYPE_MAX
; i
++) {
6875 bdrv_op_block(bs
, i
, reason
);
6879 void bdrv_op_unblock_all(BlockDriverState
*bs
, Error
*reason
)
6882 GLOBAL_STATE_CODE();
6883 for (i
= 0; i
< BLOCK_OP_TYPE_MAX
; i
++) {
6884 bdrv_op_unblock(bs
, i
, reason
);
6888 bool bdrv_op_blocker_is_empty(BlockDriverState
*bs
)
6891 GLOBAL_STATE_CODE();
6892 for (i
= 0; i
< BLOCK_OP_TYPE_MAX
; i
++) {
6893 if (!QLIST_EMPTY(&bs
->op_blockers
[i
])) {
6900 void bdrv_img_create(const char *filename
, const char *fmt
,
6901 const char *base_filename
, const char *base_fmt
,
6902 char *options
, uint64_t img_size
, int flags
, bool quiet
,
6905 QemuOptsList
*create_opts
= NULL
;
6906 QemuOpts
*opts
= NULL
;
6907 const char *backing_fmt
, *backing_file
;
6909 BlockDriver
*drv
, *proto_drv
;
6910 Error
*local_err
= NULL
;
6913 GLOBAL_STATE_CODE();
6915 /* Find driver and parse its options */
6916 drv
= bdrv_find_format(fmt
);
6918 error_setg(errp
, "Unknown file format '%s'", fmt
);
6922 proto_drv
= bdrv_find_protocol(filename
, true, errp
);
6927 if (!drv
->create_opts
) {
6928 error_setg(errp
, "Format driver '%s' does not support image creation",
6933 if (!proto_drv
->create_opts
) {
6934 error_setg(errp
, "Protocol driver '%s' does not support image creation",
6935 proto_drv
->format_name
);
6939 /* Create parameter list */
6940 create_opts
= qemu_opts_append(create_opts
, drv
->create_opts
);
6941 create_opts
= qemu_opts_append(create_opts
, proto_drv
->create_opts
);
6943 opts
= qemu_opts_create(create_opts
, NULL
, 0, &error_abort
);
6945 /* Parse -o options */
6947 if (!qemu_opts_do_parse(opts
, options
, NULL
, errp
)) {
6952 if (!qemu_opt_get(opts
, BLOCK_OPT_SIZE
)) {
6953 qemu_opt_set_number(opts
, BLOCK_OPT_SIZE
, img_size
, &error_abort
);
6954 } else if (img_size
!= UINT64_C(-1)) {
6955 error_setg(errp
, "The image size must be specified only once");
6959 if (base_filename
) {
6960 if (!qemu_opt_set(opts
, BLOCK_OPT_BACKING_FILE
, base_filename
,
6962 error_setg(errp
, "Backing file not supported for file format '%s'",
6969 if (!qemu_opt_set(opts
, BLOCK_OPT_BACKING_FMT
, base_fmt
, NULL
)) {
6970 error_setg(errp
, "Backing file format not supported for file "
6971 "format '%s'", fmt
);
6976 backing_file
= qemu_opt_get(opts
, BLOCK_OPT_BACKING_FILE
);
6978 if (!strcmp(filename
, backing_file
)) {
6979 error_setg(errp
, "Error: Trying to create an image with the "
6980 "same filename as the backing file");
6983 if (backing_file
[0] == '\0') {
6984 error_setg(errp
, "Expected backing file name, got empty string");
6989 backing_fmt
= qemu_opt_get(opts
, BLOCK_OPT_BACKING_FMT
);
6991 /* The size for the image must always be specified, unless we have a backing
6992 * file and we have not been forbidden from opening it. */
6993 size
= qemu_opt_get_size(opts
, BLOCK_OPT_SIZE
, img_size
);
6994 if (backing_file
&& !(flags
& BDRV_O_NO_BACKING
)) {
6995 BlockDriverState
*bs
;
6998 QDict
*backing_options
= NULL
;
7001 bdrv_get_full_backing_filename_from_filename(filename
, backing_file
,
7006 assert(full_backing
);
7009 * No need to do I/O here, which allows us to open encrypted
7010 * backing images without needing the secret
7013 back_flags
&= ~(BDRV_O_RDWR
| BDRV_O_SNAPSHOT
| BDRV_O_NO_BACKING
);
7014 back_flags
|= BDRV_O_NO_IO
;
7016 backing_options
= qdict_new();
7018 qdict_put_str(backing_options
, "driver", backing_fmt
);
7020 qdict_put_bool(backing_options
, BDRV_OPT_FORCE_SHARE
, true);
7022 bs
= bdrv_open(full_backing
, NULL
, backing_options
, back_flags
,
7024 g_free(full_backing
);
7026 error_append_hint(&local_err
, "Could not open backing image.\n");
7030 error_setg(&local_err
,
7031 "Backing file specified without backing format");
7032 error_append_hint(&local_err
, "Detected format of %s.",
7033 bs
->drv
->format_name
);
7037 /* Opened BS, have no size */
7038 size
= bdrv_getlength(bs
);
7040 error_setg_errno(errp
, -size
, "Could not get size of '%s'",
7045 qemu_opt_set_number(opts
, BLOCK_OPT_SIZE
, size
, &error_abort
);
7049 /* (backing_file && !(flags & BDRV_O_NO_BACKING)) */
7050 } else if (backing_file
&& !backing_fmt
) {
7051 error_setg(&local_err
,
7052 "Backing file specified without backing format");
7057 error_setg(errp
, "Image creation needs a size parameter");
7062 printf("Formatting '%s', fmt=%s ", filename
, fmt
);
7063 qemu_opts_print(opts
, " ");
7068 ret
= bdrv_create(drv
, filename
, opts
, &local_err
);
7070 if (ret
== -EFBIG
) {
7071 /* This is generally a better message than whatever the driver would
7072 * deliver (especially because of the cluster_size_hint), since that
7073 * is most probably not much different from "image too large". */
7074 const char *cluster_size_hint
= "";
7075 if (qemu_opt_get_size(opts
, BLOCK_OPT_CLUSTER_SIZE
, 0)) {
7076 cluster_size_hint
= " (try using a larger cluster size)";
7078 error_setg(errp
, "The image size is too large for file format '%s'"
7079 "%s", fmt
, cluster_size_hint
);
7080 error_free(local_err
);
7085 qemu_opts_del(opts
);
7086 qemu_opts_free(create_opts
);
7087 error_propagate(errp
, local_err
);
7090 AioContext
*bdrv_get_aio_context(BlockDriverState
*bs
)
7093 return bs
? bs
->aio_context
: qemu_get_aio_context();
7096 AioContext
*coroutine_fn
bdrv_co_enter(BlockDriverState
*bs
)
7098 Coroutine
*self
= qemu_coroutine_self();
7099 AioContext
*old_ctx
= qemu_coroutine_get_aio_context(self
);
7100 AioContext
*new_ctx
;
7104 * Increase bs->in_flight to ensure that this operation is completed before
7105 * moving the node to a different AioContext. Read new_ctx only afterwards.
7107 bdrv_inc_in_flight(bs
);
7109 new_ctx
= bdrv_get_aio_context(bs
);
7110 aio_co_reschedule_self(new_ctx
);
7114 void coroutine_fn
bdrv_co_leave(BlockDriverState
*bs
, AioContext
*old_ctx
)
7117 aio_co_reschedule_self(old_ctx
);
7118 bdrv_dec_in_flight(bs
);
7121 void coroutine_fn
bdrv_co_lock(BlockDriverState
*bs
)
7123 AioContext
*ctx
= bdrv_get_aio_context(bs
);
7125 /* In the main thread, bs->aio_context won't change concurrently */
7126 assert(qemu_get_current_aio_context() == qemu_get_aio_context());
7129 * We're in coroutine context, so we already hold the lock of the main
7130 * loop AioContext. Don't lock it twice to avoid deadlocks.
7132 assert(qemu_in_coroutine());
7133 if (ctx
!= qemu_get_aio_context()) {
7134 aio_context_acquire(ctx
);
7138 void coroutine_fn
bdrv_co_unlock(BlockDriverState
*bs
)
7140 AioContext
*ctx
= bdrv_get_aio_context(bs
);
7142 assert(qemu_in_coroutine());
7143 if (ctx
!= qemu_get_aio_context()) {
7144 aio_context_release(ctx
);
7148 void bdrv_coroutine_enter(BlockDriverState
*bs
, Coroutine
*co
)
7151 aio_co_enter(bdrv_get_aio_context(bs
), co
);
7154 static void bdrv_do_remove_aio_context_notifier(BdrvAioNotifier
*ban
)
7156 GLOBAL_STATE_CODE();
7157 QLIST_REMOVE(ban
, list
);
7161 static void bdrv_detach_aio_context(BlockDriverState
*bs
)
7163 BdrvAioNotifier
*baf
, *baf_tmp
;
7165 assert(!bs
->walking_aio_notifiers
);
7166 GLOBAL_STATE_CODE();
7167 bs
->walking_aio_notifiers
= true;
7168 QLIST_FOREACH_SAFE(baf
, &bs
->aio_notifiers
, list
, baf_tmp
) {
7170 bdrv_do_remove_aio_context_notifier(baf
);
7172 baf
->detach_aio_context(baf
->opaque
);
7175 /* Never mind iterating again to check for ->deleted. bdrv_close() will
7176 * remove remaining aio notifiers if we aren't called again.
7178 bs
->walking_aio_notifiers
= false;
7180 if (bs
->drv
&& bs
->drv
->bdrv_detach_aio_context
) {
7181 bs
->drv
->bdrv_detach_aio_context(bs
);
7184 if (bs
->quiesce_counter
) {
7185 aio_enable_external(bs
->aio_context
);
7187 assert_bdrv_graph_writable(bs
);
7188 bs
->aio_context
= NULL
;
7191 static void bdrv_attach_aio_context(BlockDriverState
*bs
,
7192 AioContext
*new_context
)
7194 BdrvAioNotifier
*ban
, *ban_tmp
;
7195 GLOBAL_STATE_CODE();
7197 if (bs
->quiesce_counter
) {
7198 aio_disable_external(new_context
);
7201 assert_bdrv_graph_writable(bs
);
7202 bs
->aio_context
= new_context
;
7204 if (bs
->drv
&& bs
->drv
->bdrv_attach_aio_context
) {
7205 bs
->drv
->bdrv_attach_aio_context(bs
, new_context
);
7208 assert(!bs
->walking_aio_notifiers
);
7209 bs
->walking_aio_notifiers
= true;
7210 QLIST_FOREACH_SAFE(ban
, &bs
->aio_notifiers
, list
, ban_tmp
) {
7212 bdrv_do_remove_aio_context_notifier(ban
);
7214 ban
->attached_aio_context(new_context
, ban
->opaque
);
7217 bs
->walking_aio_notifiers
= false;
7220 typedef struct BdrvStateSetAioContext
{
7221 AioContext
*new_ctx
;
7222 BlockDriverState
*bs
;
7223 } BdrvStateSetAioContext
;
7225 static bool bdrv_parent_change_aio_context(BdrvChild
*c
, AioContext
*ctx
,
7226 GHashTable
*visited
,
7230 GLOBAL_STATE_CODE();
7231 if (g_hash_table_contains(visited
, c
)) {
7234 g_hash_table_add(visited
, c
);
7237 * A BdrvChildClass that doesn't handle AioContext changes cannot
7238 * tolerate any AioContext changes
7240 if (!c
->klass
->change_aio_ctx
) {
7241 char *user
= bdrv_child_user_desc(c
);
7242 error_setg(errp
, "Changing iothreads is not supported by %s", user
);
7246 if (!c
->klass
->change_aio_ctx(c
, ctx
, visited
, tran
, errp
)) {
7247 assert(!errp
|| *errp
);
7253 bool bdrv_child_change_aio_context(BdrvChild
*c
, AioContext
*ctx
,
7254 GHashTable
*visited
, Transaction
*tran
,
7257 GLOBAL_STATE_CODE();
7258 if (g_hash_table_contains(visited
, c
)) {
7261 g_hash_table_add(visited
, c
);
7262 return bdrv_change_aio_context(c
->bs
, ctx
, visited
, tran
, errp
);
7265 static void bdrv_set_aio_context_clean(void *opaque
)
7267 BdrvStateSetAioContext
*state
= (BdrvStateSetAioContext
*) opaque
;
7268 BlockDriverState
*bs
= (BlockDriverState
*) state
->bs
;
7270 /* Paired with bdrv_drained_begin in bdrv_change_aio_context() */
7271 bdrv_drained_end(bs
);
7276 static void bdrv_set_aio_context_commit(void *opaque
)
7278 BdrvStateSetAioContext
*state
= (BdrvStateSetAioContext
*) opaque
;
7279 BlockDriverState
*bs
= (BlockDriverState
*) state
->bs
;
7280 AioContext
*new_context
= state
->new_ctx
;
7281 AioContext
*old_context
= bdrv_get_aio_context(bs
);
7282 assert_bdrv_graph_writable(bs
);
7285 * Take the old AioContex when detaching it from bs.
7286 * At this point, new_context lock is already acquired, and we are now
7287 * also taking old_context. This is safe as long as bdrv_detach_aio_context
7288 * does not call AIO_POLL_WHILE().
7290 if (old_context
!= qemu_get_aio_context()) {
7291 aio_context_acquire(old_context
);
7293 bdrv_detach_aio_context(bs
);
7294 if (old_context
!= qemu_get_aio_context()) {
7295 aio_context_release(old_context
);
7297 bdrv_attach_aio_context(bs
, new_context
);
7300 static TransactionActionDrv set_aio_context
= {
7301 .commit
= bdrv_set_aio_context_commit
,
7302 .clean
= bdrv_set_aio_context_clean
,
7306 * Changes the AioContext used for fd handlers, timers, and BHs by this
7307 * BlockDriverState and all its children and parents.
7309 * Must be called from the main AioContext.
7311 * The caller must own the AioContext lock for the old AioContext of bs, but it
7312 * must not own the AioContext lock for new_context (unless new_context is the
7313 * same as the current context of bs).
7315 * @visited will accumulate all visited BdrvChild objects. The caller is
7316 * responsible for freeing the list afterwards.
7318 static bool bdrv_change_aio_context(BlockDriverState
*bs
, AioContext
*ctx
,
7319 GHashTable
*visited
, Transaction
*tran
,
7323 BdrvStateSetAioContext
*state
;
7325 GLOBAL_STATE_CODE();
7327 if (bdrv_get_aio_context(bs
) == ctx
) {
7331 QLIST_FOREACH(c
, &bs
->parents
, next_parent
) {
7332 if (!bdrv_parent_change_aio_context(c
, ctx
, visited
, tran
, errp
)) {
7337 QLIST_FOREACH(c
, &bs
->children
, next
) {
7338 if (!bdrv_child_change_aio_context(c
, ctx
, visited
, tran
, errp
)) {
7343 state
= g_new(BdrvStateSetAioContext
, 1);
7344 *state
= (BdrvStateSetAioContext
) {
7349 /* Paired with bdrv_drained_end in bdrv_set_aio_context_clean() */
7350 bdrv_drained_begin(bs
);
7352 tran_add(tran
, &set_aio_context
, state
);
7358 * Change bs's and recursively all of its parents' and children's AioContext
7359 * to the given new context, returning an error if that isn't possible.
7361 * If ignore_child is not NULL, that child (and its subgraph) will not
7364 * This function still requires the caller to take the bs current
7365 * AioContext lock, otherwise draining will fail since AIO_WAIT_WHILE
7366 * assumes the lock is always held if bs is in another AioContext.
7367 * For the same reason, it temporarily also holds the new AioContext, since
7368 * bdrv_drained_end calls BDRV_POLL_WHILE that assumes the lock is taken too.
7369 * Therefore the new AioContext lock must not be taken by the caller.
7371 int bdrv_try_change_aio_context(BlockDriverState
*bs
, AioContext
*ctx
,
7372 BdrvChild
*ignore_child
, Error
**errp
)
7375 GHashTable
*visited
;
7377 AioContext
*old_context
= bdrv_get_aio_context(bs
);
7378 GLOBAL_STATE_CODE();
7381 * Recursion phase: go through all nodes of the graph.
7382 * Take care of checking that all nodes support changing AioContext
7383 * and drain them, builing a linear list of callbacks to run if everything
7384 * is successful (the transaction itself).
7387 visited
= g_hash_table_new(NULL
, NULL
);
7389 g_hash_table_add(visited
, ignore_child
);
7391 ret
= bdrv_change_aio_context(bs
, ctx
, visited
, tran
, errp
);
7392 g_hash_table_destroy(visited
);
7395 * Linear phase: go through all callbacks collected in the transaction.
7396 * Run all callbacks collected in the recursion to switch all nodes
7397 * AioContext lock (transaction commit), or undo all changes done in the
7398 * recursion (transaction abort).
7402 /* Just run clean() callbacks. No AioContext changed. */
7408 * Release old AioContext, it won't be needed anymore, as all
7409 * bdrv_drained_begin() have been called already.
7411 if (qemu_get_aio_context() != old_context
) {
7412 aio_context_release(old_context
);
7416 * Acquire new AioContext since bdrv_drained_end() is going to be called
7417 * after we switched all nodes in the new AioContext, and the function
7418 * assumes that the lock of the bs is always taken.
7420 if (qemu_get_aio_context() != ctx
) {
7421 aio_context_acquire(ctx
);
7426 if (qemu_get_aio_context() != ctx
) {
7427 aio_context_release(ctx
);
7430 /* Re-acquire the old AioContext, since the caller takes and releases it. */
7431 if (qemu_get_aio_context() != old_context
) {
7432 aio_context_acquire(old_context
);
7438 void bdrv_add_aio_context_notifier(BlockDriverState
*bs
,
7439 void (*attached_aio_context
)(AioContext
*new_context
, void *opaque
),
7440 void (*detach_aio_context
)(void *opaque
), void *opaque
)
7442 BdrvAioNotifier
*ban
= g_new(BdrvAioNotifier
, 1);
7443 *ban
= (BdrvAioNotifier
){
7444 .attached_aio_context
= attached_aio_context
,
7445 .detach_aio_context
= detach_aio_context
,
7448 GLOBAL_STATE_CODE();
7450 QLIST_INSERT_HEAD(&bs
->aio_notifiers
, ban
, list
);
7453 void bdrv_remove_aio_context_notifier(BlockDriverState
*bs
,
7454 void (*attached_aio_context
)(AioContext
*,
7456 void (*detach_aio_context
)(void *),
7459 BdrvAioNotifier
*ban
, *ban_next
;
7460 GLOBAL_STATE_CODE();
7462 QLIST_FOREACH_SAFE(ban
, &bs
->aio_notifiers
, list
, ban_next
) {
7463 if (ban
->attached_aio_context
== attached_aio_context
&&
7464 ban
->detach_aio_context
== detach_aio_context
&&
7465 ban
->opaque
== opaque
&&
7466 ban
->deleted
== false)
7468 if (bs
->walking_aio_notifiers
) {
7469 ban
->deleted
= true;
7471 bdrv_do_remove_aio_context_notifier(ban
);
7480 int bdrv_amend_options(BlockDriverState
*bs
, QemuOpts
*opts
,
7481 BlockDriverAmendStatusCB
*status_cb
, void *cb_opaque
,
7485 GLOBAL_STATE_CODE();
7487 error_setg(errp
, "Node is ejected");
7490 if (!bs
->drv
->bdrv_amend_options
) {
7491 error_setg(errp
, "Block driver '%s' does not support option amendment",
7492 bs
->drv
->format_name
);
7495 return bs
->drv
->bdrv_amend_options(bs
, opts
, status_cb
,
7496 cb_opaque
, force
, errp
);
7500 * This function checks whether the given @to_replace is allowed to be
7501 * replaced by a node that always shows the same data as @bs. This is
7502 * used for example to verify whether the mirror job can replace
7503 * @to_replace by the target mirrored from @bs.
7504 * To be replaceable, @bs and @to_replace may either be guaranteed to
7505 * always show the same data (because they are only connected through
7506 * filters), or some driver may allow replacing one of its children
7507 * because it can guarantee that this child's data is not visible at
7508 * all (for example, for dissenting quorum children that have no other
7511 bool bdrv_recurse_can_replace(BlockDriverState
*bs
,
7512 BlockDriverState
*to_replace
)
7514 BlockDriverState
*filtered
;
7516 GLOBAL_STATE_CODE();
7518 if (!bs
|| !bs
->drv
) {
7522 if (bs
== to_replace
) {
7526 /* See what the driver can do */
7527 if (bs
->drv
->bdrv_recurse_can_replace
) {
7528 return bs
->drv
->bdrv_recurse_can_replace(bs
, to_replace
);
7531 /* For filters without an own implementation, we can recurse on our own */
7532 filtered
= bdrv_filter_bs(bs
);
7534 return bdrv_recurse_can_replace(filtered
, to_replace
);
7542 * Check whether the given @node_name can be replaced by a node that
7543 * has the same data as @parent_bs. If so, return @node_name's BDS;
7546 * @node_name must be a (recursive) *child of @parent_bs (or this
7547 * function will return NULL).
7549 * The result (whether the node can be replaced or not) is only valid
7550 * for as long as no graph or permission changes occur.
7552 BlockDriverState
*check_to_replace_node(BlockDriverState
*parent_bs
,
7553 const char *node_name
, Error
**errp
)
7555 BlockDriverState
*to_replace_bs
= bdrv_find_node(node_name
);
7556 AioContext
*aio_context
;
7558 GLOBAL_STATE_CODE();
7560 if (!to_replace_bs
) {
7561 error_setg(errp
, "Failed to find node with node-name='%s'", node_name
);
7565 aio_context
= bdrv_get_aio_context(to_replace_bs
);
7566 aio_context_acquire(aio_context
);
7568 if (bdrv_op_is_blocked(to_replace_bs
, BLOCK_OP_TYPE_REPLACE
, errp
)) {
7569 to_replace_bs
= NULL
;
7573 /* We don't want arbitrary node of the BDS chain to be replaced only the top
7574 * most non filter in order to prevent data corruption.
7575 * Another benefit is that this tests exclude backing files which are
7576 * blocked by the backing blockers.
7578 if (!bdrv_recurse_can_replace(parent_bs
, to_replace_bs
)) {
7579 error_setg(errp
, "Cannot replace '%s' by a node mirrored from '%s', "
7580 "because it cannot be guaranteed that doing so would not "
7581 "lead to an abrupt change of visible data",
7582 node_name
, parent_bs
->node_name
);
7583 to_replace_bs
= NULL
;
7588 aio_context_release(aio_context
);
7589 return to_replace_bs
;
7593 * Iterates through the list of runtime option keys that are said to
7594 * be "strong" for a BDS. An option is called "strong" if it changes
7595 * a BDS's data. For example, the null block driver's "size" and
7596 * "read-zeroes" options are strong, but its "latency-ns" option is
7599 * If a key returned by this function ends with a dot, all options
7600 * starting with that prefix are strong.
7602 static const char *const *strong_options(BlockDriverState
*bs
,
7603 const char *const *curopt
)
7605 static const char *const global_options
[] = {
7606 "driver", "filename", NULL
7610 return &global_options
[0];
7614 if (curopt
== &global_options
[ARRAY_SIZE(global_options
) - 1] && bs
->drv
) {
7615 curopt
= bs
->drv
->strong_runtime_opts
;
7618 return (curopt
&& *curopt
) ? curopt
: NULL
;
7622 * Copies all strong runtime options from bs->options to the given
7623 * QDict. The set of strong option keys is determined by invoking
7626 * Returns true iff any strong option was present in bs->options (and
7627 * thus copied to the target QDict) with the exception of "filename"
7628 * and "driver". The caller is expected to use this value to decide
7629 * whether the existence of strong options prevents the generation of
7632 static bool append_strong_runtime_options(QDict
*d
, BlockDriverState
*bs
)
7634 bool found_any
= false;
7635 const char *const *option_name
= NULL
;
7641 while ((option_name
= strong_options(bs
, option_name
))) {
7642 bool option_given
= false;
7644 assert(strlen(*option_name
) > 0);
7645 if ((*option_name
)[strlen(*option_name
) - 1] != '.') {
7646 QObject
*entry
= qdict_get(bs
->options
, *option_name
);
7651 qdict_put_obj(d
, *option_name
, qobject_ref(entry
));
7652 option_given
= true;
7654 const QDictEntry
*entry
;
7655 for (entry
= qdict_first(bs
->options
); entry
;
7656 entry
= qdict_next(bs
->options
, entry
))
7658 if (strstart(qdict_entry_key(entry
), *option_name
, NULL
)) {
7659 qdict_put_obj(d
, qdict_entry_key(entry
),
7660 qobject_ref(qdict_entry_value(entry
)));
7661 option_given
= true;
7666 /* While "driver" and "filename" need to be included in a JSON filename,
7667 * their existence does not prohibit generation of a plain filename. */
7668 if (!found_any
&& option_given
&&
7669 strcmp(*option_name
, "driver") && strcmp(*option_name
, "filename"))
7675 if (!qdict_haskey(d
, "driver")) {
7676 /* Drivers created with bdrv_new_open_driver() may not have a
7677 * @driver option. Add it here. */
7678 qdict_put_str(d
, "driver", bs
->drv
->format_name
);
7684 /* Note: This function may return false positives; it may return true
7685 * even if opening the backing file specified by bs's image header
7686 * would result in exactly bs->backing. */
7687 static bool bdrv_backing_overridden(BlockDriverState
*bs
)
7689 GLOBAL_STATE_CODE();
7691 return strcmp(bs
->auto_backing_file
,
7692 bs
->backing
->bs
->filename
);
7694 /* No backing BDS, so if the image header reports any backing
7695 * file, it must have been suppressed */
7696 return bs
->auto_backing_file
[0] != '\0';
7700 /* Updates the following BDS fields:
7701 * - exact_filename: A filename which may be used for opening a block device
7702 * which (mostly) equals the given BDS (even without any
7703 * other options; so reading and writing must return the same
7704 * results, but caching etc. may be different)
7705 * - full_open_options: Options which, when given when opening a block device
7706 * (without a filename), result in a BDS (mostly)
7707 * equalling the given one
7708 * - filename: If exact_filename is set, it is copied here. Otherwise,
7709 * full_open_options is converted to a JSON object, prefixed with
7710 * "json:" (for use through the JSON pseudo protocol) and put here.
7712 void bdrv_refresh_filename(BlockDriverState
*bs
)
7714 BlockDriver
*drv
= bs
->drv
;
7716 BlockDriverState
*primary_child_bs
;
7718 bool backing_overridden
;
7719 bool generate_json_filename
; /* Whether our default implementation should
7720 fill exact_filename (false) or not (true) */
7722 GLOBAL_STATE_CODE();
7728 /* This BDS's file name may depend on any of its children's file names, so
7729 * refresh those first */
7730 QLIST_FOREACH(child
, &bs
->children
, next
) {
7731 bdrv_refresh_filename(child
->bs
);
7735 /* For implicit nodes, just copy everything from the single child */
7736 child
= QLIST_FIRST(&bs
->children
);
7737 assert(QLIST_NEXT(child
, next
) == NULL
);
7739 pstrcpy(bs
->exact_filename
, sizeof(bs
->exact_filename
),
7740 child
->bs
->exact_filename
);
7741 pstrcpy(bs
->filename
, sizeof(bs
->filename
), child
->bs
->filename
);
7743 qobject_unref(bs
->full_open_options
);
7744 bs
->full_open_options
= qobject_ref(child
->bs
->full_open_options
);
7749 backing_overridden
= bdrv_backing_overridden(bs
);
7751 if (bs
->open_flags
& BDRV_O_NO_IO
) {
7752 /* Without I/O, the backing file does not change anything.
7753 * Therefore, in such a case (primarily qemu-img), we can
7754 * pretend the backing file has not been overridden even if
7755 * it technically has been. */
7756 backing_overridden
= false;
7759 /* Gather the options QDict */
7761 generate_json_filename
= append_strong_runtime_options(opts
, bs
);
7762 generate_json_filename
|= backing_overridden
;
7764 if (drv
->bdrv_gather_child_options
) {
7765 /* Some block drivers may not want to present all of their children's
7766 * options, or name them differently from BdrvChild.name */
7767 drv
->bdrv_gather_child_options(bs
, opts
, backing_overridden
);
7769 QLIST_FOREACH(child
, &bs
->children
, next
) {
7770 if (child
== bs
->backing
&& !backing_overridden
) {
7771 /* We can skip the backing BDS if it has not been overridden */
7775 qdict_put(opts
, child
->name
,
7776 qobject_ref(child
->bs
->full_open_options
));
7779 if (backing_overridden
&& !bs
->backing
) {
7780 /* Force no backing file */
7781 qdict_put_null(opts
, "backing");
7785 qobject_unref(bs
->full_open_options
);
7786 bs
->full_open_options
= opts
;
7788 primary_child_bs
= bdrv_primary_bs(bs
);
7790 if (drv
->bdrv_refresh_filename
) {
7791 /* Obsolete information is of no use here, so drop the old file name
7792 * information before refreshing it */
7793 bs
->exact_filename
[0] = '\0';
7795 drv
->bdrv_refresh_filename(bs
);
7796 } else if (primary_child_bs
) {
7798 * Try to reconstruct valid information from the underlying
7799 * file -- this only works for format nodes (filter nodes
7800 * cannot be probed and as such must be selected by the user
7801 * either through an options dict, or through a special
7802 * filename which the filter driver must construct in its
7803 * .bdrv_refresh_filename() implementation).
7806 bs
->exact_filename
[0] = '\0';
7809 * We can use the underlying file's filename if:
7810 * - it has a filename,
7811 * - the current BDS is not a filter,
7812 * - the file is a protocol BDS, and
7813 * - opening that file (as this BDS's format) will automatically create
7814 * the BDS tree we have right now, that is:
7815 * - the user did not significantly change this BDS's behavior with
7816 * some explicit (strong) options
7817 * - no non-file child of this BDS has been overridden by the user
7818 * Both of these conditions are represented by generate_json_filename.
7820 if (primary_child_bs
->exact_filename
[0] &&
7821 primary_child_bs
->drv
->bdrv_file_open
&&
7822 !drv
->is_filter
&& !generate_json_filename
)
7824 strcpy(bs
->exact_filename
, primary_child_bs
->exact_filename
);
7828 if (bs
->exact_filename
[0]) {
7829 pstrcpy(bs
->filename
, sizeof(bs
->filename
), bs
->exact_filename
);
7831 GString
*json
= qobject_to_json(QOBJECT(bs
->full_open_options
));
7832 if (snprintf(bs
->filename
, sizeof(bs
->filename
), "json:%s",
7833 json
->str
) >= sizeof(bs
->filename
)) {
7834 /* Give user a hint if we truncated things. */
7835 strcpy(bs
->filename
+ sizeof(bs
->filename
) - 4, "...");
7837 g_string_free(json
, true);
7841 char *bdrv_dirname(BlockDriverState
*bs
, Error
**errp
)
7843 BlockDriver
*drv
= bs
->drv
;
7844 BlockDriverState
*child_bs
;
7846 GLOBAL_STATE_CODE();
7849 error_setg(errp
, "Node '%s' is ejected", bs
->node_name
);
7853 if (drv
->bdrv_dirname
) {
7854 return drv
->bdrv_dirname(bs
, errp
);
7857 child_bs
= bdrv_primary_bs(bs
);
7859 return bdrv_dirname(child_bs
, errp
);
7862 bdrv_refresh_filename(bs
);
7863 if (bs
->exact_filename
[0] != '\0') {
7864 return path_combine(bs
->exact_filename
, "");
7867 error_setg(errp
, "Cannot generate a base directory for %s nodes",
7873 * Hot add/remove a BDS's child. So the user can take a child offline when
7874 * it is broken and take a new child online
7876 void bdrv_add_child(BlockDriverState
*parent_bs
, BlockDriverState
*child_bs
,
7879 GLOBAL_STATE_CODE();
7880 if (!parent_bs
->drv
|| !parent_bs
->drv
->bdrv_add_child
) {
7881 error_setg(errp
, "The node %s does not support adding a child",
7882 bdrv_get_device_or_node_name(parent_bs
));
7886 if (!QLIST_EMPTY(&child_bs
->parents
)) {
7887 error_setg(errp
, "The node %s already has a parent",
7888 child_bs
->node_name
);
7892 parent_bs
->drv
->bdrv_add_child(parent_bs
, child_bs
, errp
);
7895 void bdrv_del_child(BlockDriverState
*parent_bs
, BdrvChild
*child
, Error
**errp
)
7899 GLOBAL_STATE_CODE();
7900 if (!parent_bs
->drv
|| !parent_bs
->drv
->bdrv_del_child
) {
7901 error_setg(errp
, "The node %s does not support removing a child",
7902 bdrv_get_device_or_node_name(parent_bs
));
7906 QLIST_FOREACH(tmp
, &parent_bs
->children
, next
) {
7913 error_setg(errp
, "The node %s does not have a child named %s",
7914 bdrv_get_device_or_node_name(parent_bs
),
7915 bdrv_get_device_or_node_name(child
->bs
));
7919 parent_bs
->drv
->bdrv_del_child(parent_bs
, child
, errp
);
7922 int bdrv_make_empty(BdrvChild
*c
, Error
**errp
)
7924 BlockDriver
*drv
= c
->bs
->drv
;
7927 GLOBAL_STATE_CODE();
7928 assert(c
->perm
& (BLK_PERM_WRITE
| BLK_PERM_WRITE_UNCHANGED
));
7930 if (!drv
->bdrv_make_empty
) {
7931 error_setg(errp
, "%s does not support emptying nodes",
7936 ret
= drv
->bdrv_make_empty(c
->bs
);
7938 error_setg_errno(errp
, -ret
, "Failed to empty %s",
7947 * Return the child that @bs acts as an overlay for, and from which data may be
7948 * copied in COW or COR operations. Usually this is the backing file.
7950 BdrvChild
*bdrv_cow_child(BlockDriverState
*bs
)
7954 if (!bs
|| !bs
->drv
) {
7958 if (bs
->drv
->is_filter
) {
7966 assert(bs
->backing
->role
& BDRV_CHILD_COW
);
7971 * If @bs acts as a filter for exactly one of its children, return
7974 BdrvChild
*bdrv_filter_child(BlockDriverState
*bs
)
7979 if (!bs
|| !bs
->drv
) {
7983 if (!bs
->drv
->is_filter
) {
7987 /* Only one of @backing or @file may be used */
7988 assert(!(bs
->backing
&& bs
->file
));
7990 c
= bs
->backing
?: bs
->file
;
7995 assert(c
->role
& BDRV_CHILD_FILTERED
);
8000 * Return either the result of bdrv_cow_child() or bdrv_filter_child(),
8001 * whichever is non-NULL.
8003 * Return NULL if both are NULL.
8005 BdrvChild
*bdrv_filter_or_cow_child(BlockDriverState
*bs
)
8007 BdrvChild
*cow_child
= bdrv_cow_child(bs
);
8008 BdrvChild
*filter_child
= bdrv_filter_child(bs
);
8011 /* Filter nodes cannot have COW backing files */
8012 assert(!(cow_child
&& filter_child
));
8014 return cow_child
?: filter_child
;
8018 * Return the primary child of this node: For filters, that is the
8019 * filtered child. For other nodes, that is usually the child storing
8021 * (A generally more helpful description is that this is (usually) the
8022 * child that has the same filename as @bs.)
8024 * Drivers do not necessarily have a primary child; for example quorum
8027 BdrvChild
*bdrv_primary_child(BlockDriverState
*bs
)
8029 BdrvChild
*c
, *found
= NULL
;
8032 QLIST_FOREACH(c
, &bs
->children
, next
) {
8033 if (c
->role
& BDRV_CHILD_PRIMARY
) {
8042 static BlockDriverState
*bdrv_do_skip_filters(BlockDriverState
*bs
,
8043 bool stop_on_explicit_filter
)
8051 while (!(stop_on_explicit_filter
&& !bs
->implicit
)) {
8052 c
= bdrv_filter_child(bs
);
8055 * A filter that is embedded in a working block graph must
8056 * have a child. Assert this here so this function does
8057 * not return a filter node that is not expected by the
8060 assert(!bs
->drv
|| !bs
->drv
->is_filter
);
8066 * Note that this treats nodes with bs->drv == NULL as not being
8067 * filters (bs->drv == NULL should be replaced by something else
8069 * The advantage of this behavior is that this function will thus
8070 * always return a non-NULL value (given a non-NULL @bs).
8077 * Return the first BDS that has not been added implicitly or that
8078 * does not have a filtered child down the chain starting from @bs
8079 * (including @bs itself).
8081 BlockDriverState
*bdrv_skip_implicit_filters(BlockDriverState
*bs
)
8083 GLOBAL_STATE_CODE();
8084 return bdrv_do_skip_filters(bs
, true);
8088 * Return the first BDS that does not have a filtered child down the
8089 * chain starting from @bs (including @bs itself).
8091 BlockDriverState
*bdrv_skip_filters(BlockDriverState
*bs
)
8094 return bdrv_do_skip_filters(bs
, false);
8098 * For a backing chain, return the first non-filter backing image of
8099 * the first non-filter image.
8101 BlockDriverState
*bdrv_backing_chain_next(BlockDriverState
*bs
)
8104 return bdrv_skip_filters(bdrv_cow_bs(bdrv_skip_filters(bs
)));
8108 * Check whether [offset, offset + bytes) overlaps with the cached
8109 * block-status data region.
8111 * If so, and @pnum is not NULL, set *pnum to `bsc.data_end - offset`,
8112 * which is what bdrv_bsc_is_data()'s interface needs.
8113 * Otherwise, *pnum is not touched.
8115 static bool bdrv_bsc_range_overlaps_locked(BlockDriverState
*bs
,
8116 int64_t offset
, int64_t bytes
,
8119 BdrvBlockStatusCache
*bsc
= qatomic_rcu_read(&bs
->block_status_cache
);
8123 qatomic_read(&bsc
->valid
) &&
8124 ranges_overlap(offset
, bytes
, bsc
->data_start
,
8125 bsc
->data_end
- bsc
->data_start
);
8127 if (overlaps
&& pnum
) {
8128 *pnum
= bsc
->data_end
- offset
;
8135 * See block_int.h for this function's documentation.
8137 bool bdrv_bsc_is_data(BlockDriverState
*bs
, int64_t offset
, int64_t *pnum
)
8140 RCU_READ_LOCK_GUARD();
8141 return bdrv_bsc_range_overlaps_locked(bs
, offset
, 1, pnum
);
8145 * See block_int.h for this function's documentation.
8147 void bdrv_bsc_invalidate_range(BlockDriverState
*bs
,
8148 int64_t offset
, int64_t bytes
)
8151 RCU_READ_LOCK_GUARD();
8153 if (bdrv_bsc_range_overlaps_locked(bs
, offset
, bytes
, NULL
)) {
8154 qatomic_set(&bs
->block_status_cache
->valid
, false);
8159 * See block_int.h for this function's documentation.
8161 void bdrv_bsc_fill(BlockDriverState
*bs
, int64_t offset
, int64_t bytes
)
8163 BdrvBlockStatusCache
*new_bsc
= g_new(BdrvBlockStatusCache
, 1);
8164 BdrvBlockStatusCache
*old_bsc
;
8167 *new_bsc
= (BdrvBlockStatusCache
) {
8169 .data_start
= offset
,
8170 .data_end
= offset
+ bytes
,
8173 QEMU_LOCK_GUARD(&bs
->bsc_modify_lock
);
8175 old_bsc
= qatomic_rcu_read(&bs
->block_status_cache
);
8176 qatomic_rcu_set(&bs
->block_status_cache
, new_bsc
);
8178 g_free_rcu(old_bsc
, rcu
);