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
);
96 static void bdrv_remove_filter_or_cow_child(BlockDriverState
*bs
,
99 static int bdrv_reopen_prepare(BDRVReopenState
*reopen_state
,
100 BlockReopenQueue
*queue
,
101 Transaction
*change_child_tran
, Error
**errp
);
102 static void bdrv_reopen_commit(BDRVReopenState
*reopen_state
);
103 static void bdrv_reopen_abort(BDRVReopenState
*reopen_state
);
105 static bool bdrv_backing_overridden(BlockDriverState
*bs
);
107 static bool bdrv_change_aio_context(BlockDriverState
*bs
, AioContext
*ctx
,
108 GHashTable
*visited
, Transaction
*tran
,
111 /* If non-zero, use only whitelisted block drivers */
112 static int use_bdrv_whitelist
;
115 static int is_windows_drive_prefix(const char *filename
)
117 return (((filename
[0] >= 'a' && filename
[0] <= 'z') ||
118 (filename
[0] >= 'A' && filename
[0] <= 'Z')) &&
122 int is_windows_drive(const char *filename
)
124 if (is_windows_drive_prefix(filename
) &&
127 if (strstart(filename
, "\\\\.\\", NULL
) ||
128 strstart(filename
, "//./", NULL
))
134 size_t bdrv_opt_mem_align(BlockDriverState
*bs
)
136 if (!bs
|| !bs
->drv
) {
137 /* page size or 4k (hdd sector size) should be on the safe side */
138 return MAX(4096, qemu_real_host_page_size());
142 return bs
->bl
.opt_mem_alignment
;
145 size_t bdrv_min_mem_align(BlockDriverState
*bs
)
147 if (!bs
|| !bs
->drv
) {
148 /* page size or 4k (hdd sector size) should be on the safe side */
149 return MAX(4096, qemu_real_host_page_size());
153 return bs
->bl
.min_mem_alignment
;
156 /* check if the path starts with "<protocol>:" */
157 int path_has_protocol(const char *path
)
162 if (is_windows_drive(path
) ||
163 is_windows_drive_prefix(path
)) {
166 p
= path
+ strcspn(path
, ":/\\");
168 p
= path
+ strcspn(path
, ":/");
174 int path_is_absolute(const char *path
)
177 /* specific case for names like: "\\.\d:" */
178 if (is_windows_drive(path
) || is_windows_drive_prefix(path
)) {
181 return (*path
== '/' || *path
== '\\');
183 return (*path
== '/');
187 /* if filename is absolute, just return its duplicate. Otherwise, build a
188 path to it by considering it is relative to base_path. URL are
190 char *path_combine(const char *base_path
, const char *filename
)
192 const char *protocol_stripped
= NULL
;
197 if (path_is_absolute(filename
)) {
198 return g_strdup(filename
);
201 if (path_has_protocol(base_path
)) {
202 protocol_stripped
= strchr(base_path
, ':');
203 if (protocol_stripped
) {
207 p
= protocol_stripped
?: base_path
;
209 p1
= strrchr(base_path
, '/');
213 p2
= strrchr(base_path
, '\\');
214 if (!p1
|| p2
> p1
) {
229 result
= g_malloc(len
+ strlen(filename
) + 1);
230 memcpy(result
, base_path
, len
);
231 strcpy(result
+ len
, filename
);
237 * Helper function for bdrv_parse_filename() implementations to remove optional
238 * protocol prefixes (especially "file:") from a filename and for putting the
239 * stripped filename into the options QDict if there is such a prefix.
241 void bdrv_parse_filename_strip_prefix(const char *filename
, const char *prefix
,
244 if (strstart(filename
, prefix
, &filename
)) {
245 /* Stripping the explicit protocol prefix may result in a protocol
246 * prefix being (wrongly) detected (if the filename contains a colon) */
247 if (path_has_protocol(filename
)) {
248 GString
*fat_filename
;
250 /* This means there is some colon before the first slash; therefore,
251 * this cannot be an absolute path */
252 assert(!path_is_absolute(filename
));
254 /* And we can thus fix the protocol detection issue by prefixing it
256 fat_filename
= g_string_new("./");
257 g_string_append(fat_filename
, filename
);
259 assert(!path_has_protocol(fat_filename
->str
));
261 qdict_put(options
, "filename",
262 qstring_from_gstring(fat_filename
));
264 /* If no protocol prefix was detected, we can use the shortened
266 qdict_put_str(options
, "filename", filename
);
272 /* Returns whether the image file is opened as read-only. Note that this can
273 * return false and writing to the image file is still not possible because the
274 * image is inactivated. */
275 bool bdrv_is_read_only(BlockDriverState
*bs
)
278 return !(bs
->open_flags
& BDRV_O_RDWR
);
281 int bdrv_can_set_read_only(BlockDriverState
*bs
, bool read_only
,
282 bool ignore_allow_rdw
, Error
**errp
)
286 /* Do not set read_only if copy_on_read is enabled */
287 if (bs
->copy_on_read
&& read_only
) {
288 error_setg(errp
, "Can't set node '%s' to r/o with copy-on-read enabled",
289 bdrv_get_device_or_node_name(bs
));
293 /* Do not clear read_only if it is prohibited */
294 if (!read_only
&& !(bs
->open_flags
& BDRV_O_ALLOW_RDWR
) &&
297 error_setg(errp
, "Node '%s' is read only",
298 bdrv_get_device_or_node_name(bs
));
306 * Called by a driver that can only provide a read-only image.
308 * Returns 0 if the node is already read-only or it could switch the node to
309 * read-only because BDRV_O_AUTO_RDONLY is set.
311 * Returns -EACCES if the node is read-write and BDRV_O_AUTO_RDONLY is not set
312 * or bdrv_can_set_read_only() forbids making the node read-only. If @errmsg
313 * is not NULL, it is used as the error message for the Error object.
315 int bdrv_apply_auto_read_only(BlockDriverState
*bs
, const char *errmsg
,
321 if (!(bs
->open_flags
& BDRV_O_RDWR
)) {
324 if (!(bs
->open_flags
& BDRV_O_AUTO_RDONLY
)) {
328 ret
= bdrv_can_set_read_only(bs
, true, false, NULL
);
333 bs
->open_flags
&= ~BDRV_O_RDWR
;
338 error_setg(errp
, "%s", errmsg
?: "Image is read-only");
343 * If @backing is empty, this function returns NULL without setting
344 * @errp. In all other cases, NULL will only be returned with @errp
347 * Therefore, a return value of NULL without @errp set means that
348 * there is no backing file; if @errp is set, there is one but its
349 * absolute filename cannot be generated.
351 char *bdrv_get_full_backing_filename_from_filename(const char *backed
,
355 if (backing
[0] == '\0') {
357 } else if (path_has_protocol(backing
) || path_is_absolute(backing
)) {
358 return g_strdup(backing
);
359 } else if (backed
[0] == '\0' || strstart(backed
, "json:", NULL
)) {
360 error_setg(errp
, "Cannot use relative backing file names for '%s'",
364 return path_combine(backed
, backing
);
369 * If @filename is empty or NULL, this function returns NULL without
370 * setting @errp. In all other cases, NULL will only be returned with
373 static char *bdrv_make_absolute_filename(BlockDriverState
*relative_to
,
374 const char *filename
, Error
**errp
)
376 char *dir
, *full_name
;
378 if (!filename
|| filename
[0] == '\0') {
380 } else if (path_has_protocol(filename
) || path_is_absolute(filename
)) {
381 return g_strdup(filename
);
384 dir
= bdrv_dirname(relative_to
, errp
);
389 full_name
= g_strconcat(dir
, filename
, NULL
);
394 char *bdrv_get_full_backing_filename(BlockDriverState
*bs
, Error
**errp
)
397 return bdrv_make_absolute_filename(bs
, bs
->backing_file
, errp
);
400 void bdrv_register(BlockDriver
*bdrv
)
402 assert(bdrv
->format_name
);
404 QLIST_INSERT_HEAD(&bdrv_drivers
, bdrv
, list
);
407 BlockDriverState
*bdrv_new(void)
409 BlockDriverState
*bs
;
414 bs
= g_new0(BlockDriverState
, 1);
415 QLIST_INIT(&bs
->dirty_bitmaps
);
416 for (i
= 0; i
< BLOCK_OP_TYPE_MAX
; i
++) {
417 QLIST_INIT(&bs
->op_blockers
[i
]);
419 qemu_co_mutex_init(&bs
->reqs_lock
);
420 qemu_mutex_init(&bs
->dirty_bitmap_mutex
);
422 bs
->aio_context
= qemu_get_aio_context();
424 qemu_co_queue_init(&bs
->flush_queue
);
426 qemu_co_mutex_init(&bs
->bsc_modify_lock
);
427 bs
->block_status_cache
= g_new0(BdrvBlockStatusCache
, 1);
429 for (i
= 0; i
< bdrv_drain_all_count
; i
++) {
430 bdrv_drained_begin(bs
);
433 QTAILQ_INSERT_TAIL(&all_bdrv_states
, bs
, bs_list
);
438 static BlockDriver
*bdrv_do_find_format(const char *format_name
)
443 QLIST_FOREACH(drv1
, &bdrv_drivers
, list
) {
444 if (!strcmp(drv1
->format_name
, format_name
)) {
452 BlockDriver
*bdrv_find_format(const char *format_name
)
459 drv1
= bdrv_do_find_format(format_name
);
464 /* The driver isn't registered, maybe we need to load a module */
465 for (i
= 0; i
< (int)ARRAY_SIZE(block_driver_modules
); ++i
) {
466 if (!strcmp(block_driver_modules
[i
].format_name
, format_name
)) {
467 block_module_load_one(block_driver_modules
[i
].library_name
);
472 return bdrv_do_find_format(format_name
);
475 static int bdrv_format_is_whitelisted(const char *format_name
, bool read_only
)
477 static const char *whitelist_rw
[] = {
478 CONFIG_BDRV_RW_WHITELIST
481 static const char *whitelist_ro
[] = {
482 CONFIG_BDRV_RO_WHITELIST
487 if (!whitelist_rw
[0] && !whitelist_ro
[0]) {
488 return 1; /* no whitelist, anything goes */
491 for (p
= whitelist_rw
; *p
; p
++) {
492 if (!strcmp(format_name
, *p
)) {
497 for (p
= whitelist_ro
; *p
; p
++) {
498 if (!strcmp(format_name
, *p
)) {
506 int bdrv_is_whitelisted(BlockDriver
*drv
, bool read_only
)
509 return bdrv_format_is_whitelisted(drv
->format_name
, read_only
);
512 bool bdrv_uses_whitelist(void)
514 return use_bdrv_whitelist
;
517 typedef struct CreateCo
{
525 static void coroutine_fn
bdrv_create_co_entry(void *opaque
)
527 Error
*local_err
= NULL
;
530 CreateCo
*cco
= opaque
;
534 ret
= cco
->drv
->bdrv_co_create_opts(cco
->drv
,
535 cco
->filename
, cco
->opts
, &local_err
);
536 error_propagate(&cco
->err
, local_err
);
540 int bdrv_create(BlockDriver
*drv
, const char* filename
,
541 QemuOpts
*opts
, Error
**errp
)
550 .filename
= g_strdup(filename
),
556 if (!drv
->bdrv_co_create_opts
) {
557 error_setg(errp
, "Driver '%s' does not support image creation", drv
->format_name
);
562 if (qemu_in_coroutine()) {
563 /* Fast-path if already in coroutine context */
564 bdrv_create_co_entry(&cco
);
566 co
= qemu_coroutine_create(bdrv_create_co_entry
, &cco
);
567 qemu_coroutine_enter(co
);
568 while (cco
.ret
== NOT_DONE
) {
569 aio_poll(qemu_get_aio_context(), true);
576 error_propagate(errp
, cco
.err
);
578 error_setg_errno(errp
, -ret
, "Could not create image");
583 g_free(cco
.filename
);
588 * Helper function for bdrv_create_file_fallback(): Resize @blk to at
589 * least the given @minimum_size.
591 * On success, return @blk's actual length.
592 * Otherwise, return -errno.
594 static int64_t create_file_fallback_truncate(BlockBackend
*blk
,
595 int64_t minimum_size
, Error
**errp
)
597 Error
*local_err
= NULL
;
603 ret
= blk_truncate(blk
, minimum_size
, false, PREALLOC_MODE_OFF
, 0,
605 if (ret
< 0 && ret
!= -ENOTSUP
) {
606 error_propagate(errp
, local_err
);
610 size
= blk_getlength(blk
);
612 error_free(local_err
);
613 error_setg_errno(errp
, -size
,
614 "Failed to inquire the new image file's length");
618 if (size
< minimum_size
) {
619 /* Need to grow the image, but we failed to do that */
620 error_propagate(errp
, local_err
);
624 error_free(local_err
);
631 * Helper function for bdrv_create_file_fallback(): Zero the first
632 * sector to remove any potentially pre-existing image header.
634 static int coroutine_fn
635 create_file_fallback_zero_first_sector(BlockBackend
*blk
,
636 int64_t current_size
,
639 int64_t bytes_to_clear
;
644 bytes_to_clear
= MIN(current_size
, BDRV_SECTOR_SIZE
);
645 if (bytes_to_clear
) {
646 ret
= blk_co_pwrite_zeroes(blk
, 0, bytes_to_clear
, BDRV_REQ_MAY_UNMAP
);
648 error_setg_errno(errp
, -ret
,
649 "Failed to clear the new image's first sector");
658 * Simple implementation of bdrv_co_create_opts for protocol drivers
659 * which only support creation via opening a file
660 * (usually existing raw storage device)
662 int coroutine_fn
bdrv_co_create_opts_simple(BlockDriver
*drv
,
663 const char *filename
,
671 PreallocMode prealloc
;
672 Error
*local_err
= NULL
;
677 size
= qemu_opt_get_size_del(opts
, BLOCK_OPT_SIZE
, 0);
678 buf
= qemu_opt_get_del(opts
, BLOCK_OPT_PREALLOC
);
679 prealloc
= qapi_enum_parse(&PreallocMode_lookup
, buf
,
680 PREALLOC_MODE_OFF
, &local_err
);
683 error_propagate(errp
, local_err
);
687 if (prealloc
!= PREALLOC_MODE_OFF
) {
688 error_setg(errp
, "Unsupported preallocation mode '%s'",
689 PreallocMode_str(prealloc
));
693 options
= qdict_new();
694 qdict_put_str(options
, "driver", drv
->format_name
);
696 blk
= blk_new_open(filename
, NULL
, options
,
697 BDRV_O_RDWR
| BDRV_O_RESIZE
, errp
);
699 error_prepend(errp
, "Protocol driver '%s' does not support image "
700 "creation, and opening the image failed: ",
705 size
= create_file_fallback_truncate(blk
, size
, errp
);
711 ret
= create_file_fallback_zero_first_sector(blk
, size
, errp
);
722 int bdrv_create_file(const char *filename
, QemuOpts
*opts
, Error
**errp
)
724 QemuOpts
*protocol_opts
;
731 drv
= bdrv_find_protocol(filename
, true, errp
);
736 if (!drv
->create_opts
) {
737 error_setg(errp
, "Driver '%s' does not support image creation",
743 * 'opts' contains a QemuOptsList with a combination of format and protocol
746 * The format properly removes its options, but the default values remain
747 * in 'opts->list'. So if the protocol has options with the same name
748 * (e.g. rbd has 'cluster_size' as qcow2), it will see the default values
749 * of the format, since for overlapping options, the format wins.
751 * To avoid this issue, lets convert QemuOpts to QDict, in this way we take
752 * only the set options, and then convert it back to QemuOpts, using the
753 * create_opts of the protocol. So the new QemuOpts, will contain only the
756 qdict
= qemu_opts_to_qdict(opts
, NULL
);
757 protocol_opts
= qemu_opts_from_qdict(drv
->create_opts
, qdict
, errp
);
758 if (protocol_opts
== NULL
) {
763 ret
= bdrv_create(drv
, filename
, protocol_opts
, errp
);
765 qemu_opts_del(protocol_opts
);
766 qobject_unref(qdict
);
770 int coroutine_fn
bdrv_co_delete_file(BlockDriverState
*bs
, Error
**errp
)
772 Error
*local_err
= NULL
;
779 error_setg(errp
, "Block node '%s' is not opened", bs
->filename
);
783 if (!bs
->drv
->bdrv_co_delete_file
) {
784 error_setg(errp
, "Driver '%s' does not support image deletion",
785 bs
->drv
->format_name
);
789 ret
= bs
->drv
->bdrv_co_delete_file(bs
, &local_err
);
791 error_propagate(errp
, local_err
);
797 void coroutine_fn
bdrv_co_delete_file_noerr(BlockDriverState
*bs
)
799 Error
*local_err
= NULL
;
807 ret
= bdrv_co_delete_file(bs
, &local_err
);
809 * ENOTSUP will happen if the block driver doesn't support
810 * the 'bdrv_co_delete_file' interface. This is a predictable
811 * scenario and shouldn't be reported back to the user.
813 if (ret
== -ENOTSUP
) {
814 error_free(local_err
);
815 } else if (ret
< 0) {
816 error_report_err(local_err
);
821 * Try to get @bs's logical and physical block size.
822 * On success, store them in @bsz struct and return 0.
823 * On failure return -errno.
824 * @bs must not be empty.
826 int bdrv_probe_blocksizes(BlockDriverState
*bs
, BlockSizes
*bsz
)
828 BlockDriver
*drv
= bs
->drv
;
829 BlockDriverState
*filtered
= bdrv_filter_bs(bs
);
832 if (drv
&& drv
->bdrv_probe_blocksizes
) {
833 return drv
->bdrv_probe_blocksizes(bs
, bsz
);
834 } else if (filtered
) {
835 return bdrv_probe_blocksizes(filtered
, bsz
);
842 * Try to get @bs's geometry (cyls, heads, sectors).
843 * On success, store them in @geo struct and return 0.
844 * On failure return -errno.
845 * @bs must not be empty.
847 int bdrv_probe_geometry(BlockDriverState
*bs
, HDGeometry
*geo
)
849 BlockDriver
*drv
= bs
->drv
;
850 BlockDriverState
*filtered
= bdrv_filter_bs(bs
);
853 if (drv
&& drv
->bdrv_probe_geometry
) {
854 return drv
->bdrv_probe_geometry(bs
, geo
);
855 } else if (filtered
) {
856 return bdrv_probe_geometry(filtered
, geo
);
863 * Create a uniquely-named empty temporary file.
864 * Return the actual file name used upon success, otherwise NULL.
865 * This string should be freed with g_free() when not needed any longer.
867 * Note: creating a temporary file for the caller to (re)open is
868 * inherently racy. Use g_file_open_tmp() instead whenever practical.
870 char *create_tmp_file(Error
**errp
)
874 g_autofree
char *filename
= NULL
;
876 tmpdir
= g_get_tmp_dir();
879 * See commit 69bef79 ("block: use /var/tmp instead of /tmp for -snapshot")
881 * This function is used to create temporary disk images (like -snapshot),
882 * so the files can become very large. /tmp is often a tmpfs where as
883 * /var/tmp is usually on a disk, so more appropriate for disk images.
885 if (!g_strcmp0(tmpdir
, "/tmp")) {
890 filename
= g_strdup_printf("%s/vl.XXXXXX", tmpdir
);
891 fd
= g_mkstemp(filename
);
893 error_setg_errno(errp
, errno
, "Could not open temporary file '%s'",
899 return g_steal_pointer(&filename
);
903 * Detect host devices. By convention, /dev/cdrom[N] is always
904 * recognized as a host CDROM.
906 static BlockDriver
*find_hdev_driver(const char *filename
)
908 int score_max
= 0, score
;
909 BlockDriver
*drv
= NULL
, *d
;
912 QLIST_FOREACH(d
, &bdrv_drivers
, list
) {
913 if (d
->bdrv_probe_device
) {
914 score
= d
->bdrv_probe_device(filename
);
915 if (score
> score_max
) {
925 static BlockDriver
*bdrv_do_find_protocol(const char *protocol
)
930 QLIST_FOREACH(drv1
, &bdrv_drivers
, list
) {
931 if (drv1
->protocol_name
&& !strcmp(drv1
->protocol_name
, protocol
)) {
939 BlockDriver
*bdrv_find_protocol(const char *filename
,
940 bool allow_protocol_prefix
,
950 /* TODO Drivers without bdrv_file_open must be specified explicitly */
953 * XXX(hch): we really should not let host device detection
954 * override an explicit protocol specification, but moving this
955 * later breaks access to device names with colons in them.
956 * Thanks to the brain-dead persistent naming schemes on udev-
957 * based Linux systems those actually are quite common.
959 drv1
= find_hdev_driver(filename
);
964 if (!path_has_protocol(filename
) || !allow_protocol_prefix
) {
968 p
= strchr(filename
, ':');
971 if (len
> sizeof(protocol
) - 1)
972 len
= sizeof(protocol
) - 1;
973 memcpy(protocol
, filename
, len
);
974 protocol
[len
] = '\0';
976 drv1
= bdrv_do_find_protocol(protocol
);
981 for (i
= 0; i
< (int)ARRAY_SIZE(block_driver_modules
); ++i
) {
982 if (block_driver_modules
[i
].protocol_name
&&
983 !strcmp(block_driver_modules
[i
].protocol_name
, protocol
)) {
984 block_module_load_one(block_driver_modules
[i
].library_name
);
989 drv1
= bdrv_do_find_protocol(protocol
);
991 error_setg(errp
, "Unknown protocol '%s'", protocol
);
997 * Guess image format by probing its contents.
998 * This is not a good idea when your image is raw (CVE-2008-2004), but
999 * we do it anyway for backward compatibility.
1001 * @buf contains the image's first @buf_size bytes.
1002 * @buf_size is the buffer size in bytes (generally BLOCK_PROBE_BUF_SIZE,
1003 * but can be smaller if the image file is smaller)
1004 * @filename is its filename.
1006 * For all block drivers, call the bdrv_probe() method to get its
1008 * Return the first block driver with the highest probing score.
1010 BlockDriver
*bdrv_probe_all(const uint8_t *buf
, int buf_size
,
1011 const char *filename
)
1013 int score_max
= 0, score
;
1014 BlockDriver
*drv
= NULL
, *d
;
1017 QLIST_FOREACH(d
, &bdrv_drivers
, list
) {
1018 if (d
->bdrv_probe
) {
1019 score
= d
->bdrv_probe(buf
, buf_size
, filename
);
1020 if (score
> score_max
) {
1030 static int find_image_format(BlockBackend
*file
, const char *filename
,
1031 BlockDriver
**pdrv
, Error
**errp
)
1034 uint8_t buf
[BLOCK_PROBE_BUF_SIZE
];
1037 GLOBAL_STATE_CODE();
1039 /* Return the raw BlockDriver * to scsi-generic devices or empty drives */
1040 if (blk_is_sg(file
) || !blk_is_inserted(file
) || blk_getlength(file
) == 0) {
1045 ret
= blk_pread(file
, 0, sizeof(buf
), buf
, 0);
1047 error_setg_errno(errp
, -ret
, "Could not read image for determining its "
1053 drv
= bdrv_probe_all(buf
, sizeof(buf
), filename
);
1055 error_setg(errp
, "Could not determine image format: No compatible "
1066 * Set the current 'total_sectors' value
1067 * Return 0 on success, -errno on error.
1069 int refresh_total_sectors(BlockDriverState
*bs
, int64_t hint
)
1071 BlockDriver
*drv
= bs
->drv
;
1078 /* Do not attempt drv->bdrv_getlength() on scsi-generic devices */
1082 /* query actual device if possible, otherwise just trust the hint */
1083 if (drv
->bdrv_getlength
) {
1084 int64_t length
= drv
->bdrv_getlength(bs
);
1088 hint
= DIV_ROUND_UP(length
, BDRV_SECTOR_SIZE
);
1091 bs
->total_sectors
= hint
;
1093 if (bs
->total_sectors
* BDRV_SECTOR_SIZE
> BDRV_MAX_LENGTH
) {
1101 * Combines a QDict of new block driver @options with any missing options taken
1102 * from @old_options, so that leaving out an option defaults to its old value.
1104 static void bdrv_join_options(BlockDriverState
*bs
, QDict
*options
,
1107 GLOBAL_STATE_CODE();
1108 if (bs
->drv
&& bs
->drv
->bdrv_join_options
) {
1109 bs
->drv
->bdrv_join_options(options
, old_options
);
1111 qdict_join(options
, old_options
, false);
1115 static BlockdevDetectZeroesOptions
bdrv_parse_detect_zeroes(QemuOpts
*opts
,
1119 Error
*local_err
= NULL
;
1120 char *value
= qemu_opt_get_del(opts
, "detect-zeroes");
1121 BlockdevDetectZeroesOptions detect_zeroes
=
1122 qapi_enum_parse(&BlockdevDetectZeroesOptions_lookup
, value
,
1123 BLOCKDEV_DETECT_ZEROES_OPTIONS_OFF
, &local_err
);
1124 GLOBAL_STATE_CODE();
1127 error_propagate(errp
, local_err
);
1128 return detect_zeroes
;
1131 if (detect_zeroes
== BLOCKDEV_DETECT_ZEROES_OPTIONS_UNMAP
&&
1132 !(open_flags
& BDRV_O_UNMAP
))
1134 error_setg(errp
, "setting detect-zeroes to unmap is not allowed "
1135 "without setting discard operation to unmap");
1138 return detect_zeroes
;
1142 * Set open flags for aio engine
1144 * Return 0 on success, -1 if the engine specified is invalid
1146 int bdrv_parse_aio(const char *mode
, int *flags
)
1148 if (!strcmp(mode
, "threads")) {
1149 /* do nothing, default */
1150 } else if (!strcmp(mode
, "native")) {
1151 *flags
|= BDRV_O_NATIVE_AIO
;
1152 #ifdef CONFIG_LINUX_IO_URING
1153 } else if (!strcmp(mode
, "io_uring")) {
1154 *flags
|= BDRV_O_IO_URING
;
1164 * Set open flags for a given discard mode
1166 * Return 0 on success, -1 if the discard mode was invalid.
1168 int bdrv_parse_discard_flags(const char *mode
, int *flags
)
1170 *flags
&= ~BDRV_O_UNMAP
;
1172 if (!strcmp(mode
, "off") || !strcmp(mode
, "ignore")) {
1174 } else if (!strcmp(mode
, "on") || !strcmp(mode
, "unmap")) {
1175 *flags
|= BDRV_O_UNMAP
;
1184 * Set open flags for a given cache mode
1186 * Return 0 on success, -1 if the cache mode was invalid.
1188 int bdrv_parse_cache_mode(const char *mode
, int *flags
, bool *writethrough
)
1190 *flags
&= ~BDRV_O_CACHE_MASK
;
1192 if (!strcmp(mode
, "off") || !strcmp(mode
, "none")) {
1193 *writethrough
= false;
1194 *flags
|= BDRV_O_NOCACHE
;
1195 } else if (!strcmp(mode
, "directsync")) {
1196 *writethrough
= true;
1197 *flags
|= BDRV_O_NOCACHE
;
1198 } else if (!strcmp(mode
, "writeback")) {
1199 *writethrough
= false;
1200 } else if (!strcmp(mode
, "unsafe")) {
1201 *writethrough
= false;
1202 *flags
|= BDRV_O_NO_FLUSH
;
1203 } else if (!strcmp(mode
, "writethrough")) {
1204 *writethrough
= true;
1212 static char *bdrv_child_get_parent_desc(BdrvChild
*c
)
1214 BlockDriverState
*parent
= c
->opaque
;
1215 return g_strdup_printf("node '%s'", bdrv_get_node_name(parent
));
1218 static void bdrv_child_cb_drained_begin(BdrvChild
*child
)
1220 BlockDriverState
*bs
= child
->opaque
;
1221 bdrv_do_drained_begin_quiesce(bs
, NULL
, false);
1224 static bool bdrv_child_cb_drained_poll(BdrvChild
*child
)
1226 BlockDriverState
*bs
= child
->opaque
;
1227 return bdrv_drain_poll(bs
, false, NULL
, false);
1230 static void bdrv_child_cb_drained_end(BdrvChild
*child
,
1231 int *drained_end_counter
)
1233 BlockDriverState
*bs
= child
->opaque
;
1234 bdrv_drained_end_no_poll(bs
, drained_end_counter
);
1237 static int bdrv_child_cb_inactivate(BdrvChild
*child
)
1239 BlockDriverState
*bs
= child
->opaque
;
1240 GLOBAL_STATE_CODE();
1241 assert(bs
->open_flags
& BDRV_O_INACTIVE
);
1245 static bool bdrv_child_cb_change_aio_ctx(BdrvChild
*child
, AioContext
*ctx
,
1246 GHashTable
*visited
, Transaction
*tran
,
1249 BlockDriverState
*bs
= child
->opaque
;
1250 return bdrv_change_aio_context(bs
, ctx
, visited
, tran
, errp
);
1254 * Returns the options and flags that a temporary snapshot should get, based on
1255 * the originally requested flags (the originally requested image will have
1256 * flags like a backing file)
1258 static void bdrv_temp_snapshot_options(int *child_flags
, QDict
*child_options
,
1259 int parent_flags
, QDict
*parent_options
)
1261 GLOBAL_STATE_CODE();
1262 *child_flags
= (parent_flags
& ~BDRV_O_SNAPSHOT
) | BDRV_O_TEMPORARY
;
1264 /* For temporary files, unconditional cache=unsafe is fine */
1265 qdict_set_default_str(child_options
, BDRV_OPT_CACHE_DIRECT
, "off");
1266 qdict_set_default_str(child_options
, BDRV_OPT_CACHE_NO_FLUSH
, "on");
1268 /* Copy the read-only and discard options from the parent */
1269 qdict_copy_default(child_options
, parent_options
, BDRV_OPT_READ_ONLY
);
1270 qdict_copy_default(child_options
, parent_options
, BDRV_OPT_DISCARD
);
1272 /* aio=native doesn't work for cache.direct=off, so disable it for the
1273 * temporary snapshot */
1274 *child_flags
&= ~BDRV_O_NATIVE_AIO
;
1277 static void bdrv_backing_attach(BdrvChild
*c
)
1279 BlockDriverState
*parent
= c
->opaque
;
1280 BlockDriverState
*backing_hd
= c
->bs
;
1282 GLOBAL_STATE_CODE();
1283 assert(!parent
->backing_blocker
);
1284 error_setg(&parent
->backing_blocker
,
1285 "node is used as backing hd of '%s'",
1286 bdrv_get_device_or_node_name(parent
));
1288 bdrv_refresh_filename(backing_hd
);
1290 parent
->open_flags
&= ~BDRV_O_NO_BACKING
;
1292 bdrv_op_block_all(backing_hd
, parent
->backing_blocker
);
1293 /* Otherwise we won't be able to commit or stream */
1294 bdrv_op_unblock(backing_hd
, BLOCK_OP_TYPE_COMMIT_TARGET
,
1295 parent
->backing_blocker
);
1296 bdrv_op_unblock(backing_hd
, BLOCK_OP_TYPE_STREAM
,
1297 parent
->backing_blocker
);
1299 * We do backup in 3 ways:
1301 * The target bs is new opened, and the source is top BDS
1302 * 2. blockdev backup
1303 * Both the source and the target are top BDSes.
1304 * 3. internal backup(used for block replication)
1305 * Both the source and the target are backing file
1307 * In case 1 and 2, neither the source nor the target is the backing file.
1308 * In case 3, we will block the top BDS, so there is only one block job
1309 * for the top BDS and its backing chain.
1311 bdrv_op_unblock(backing_hd
, BLOCK_OP_TYPE_BACKUP_SOURCE
,
1312 parent
->backing_blocker
);
1313 bdrv_op_unblock(backing_hd
, BLOCK_OP_TYPE_BACKUP_TARGET
,
1314 parent
->backing_blocker
);
1317 static void bdrv_backing_detach(BdrvChild
*c
)
1319 BlockDriverState
*parent
= c
->opaque
;
1321 GLOBAL_STATE_CODE();
1322 assert(parent
->backing_blocker
);
1323 bdrv_op_unblock_all(c
->bs
, parent
->backing_blocker
);
1324 error_free(parent
->backing_blocker
);
1325 parent
->backing_blocker
= NULL
;
1328 static int bdrv_backing_update_filename(BdrvChild
*c
, BlockDriverState
*base
,
1329 const char *filename
, Error
**errp
)
1331 BlockDriverState
*parent
= c
->opaque
;
1332 bool read_only
= bdrv_is_read_only(parent
);
1334 GLOBAL_STATE_CODE();
1337 ret
= bdrv_reopen_set_read_only(parent
, false, errp
);
1343 ret
= bdrv_change_backing_file(parent
, filename
,
1344 base
->drv
? base
->drv
->format_name
: "",
1347 error_setg_errno(errp
, -ret
, "Could not update backing file link");
1351 bdrv_reopen_set_read_only(parent
, true, NULL
);
1358 * Returns the options and flags that a generic child of a BDS should
1359 * get, based on the given options and flags for the parent BDS.
1361 static void bdrv_inherited_options(BdrvChildRole role
, bool parent_is_format
,
1362 int *child_flags
, QDict
*child_options
,
1363 int parent_flags
, QDict
*parent_options
)
1365 int flags
= parent_flags
;
1366 GLOBAL_STATE_CODE();
1369 * First, decide whether to set, clear, or leave BDRV_O_PROTOCOL.
1370 * Generally, the question to answer is: Should this child be
1371 * format-probed by default?
1375 * Pure and non-filtered data children of non-format nodes should
1376 * be probed by default (even when the node itself has BDRV_O_PROTOCOL
1377 * set). This only affects a very limited set of drivers (namely
1378 * quorum and blkverify when this comment was written).
1379 * Force-clear BDRV_O_PROTOCOL then.
1381 if (!parent_is_format
&&
1382 (role
& BDRV_CHILD_DATA
) &&
1383 !(role
& (BDRV_CHILD_METADATA
| BDRV_CHILD_FILTERED
)))
1385 flags
&= ~BDRV_O_PROTOCOL
;
1389 * All children of format nodes (except for COW children) and all
1390 * metadata children in general should never be format-probed.
1391 * Force-set BDRV_O_PROTOCOL then.
1393 if ((parent_is_format
&& !(role
& BDRV_CHILD_COW
)) ||
1394 (role
& BDRV_CHILD_METADATA
))
1396 flags
|= BDRV_O_PROTOCOL
;
1400 * If the cache mode isn't explicitly set, inherit direct and no-flush from
1403 qdict_copy_default(child_options
, parent_options
, BDRV_OPT_CACHE_DIRECT
);
1404 qdict_copy_default(child_options
, parent_options
, BDRV_OPT_CACHE_NO_FLUSH
);
1405 qdict_copy_default(child_options
, parent_options
, BDRV_OPT_FORCE_SHARE
);
1407 if (role
& BDRV_CHILD_COW
) {
1408 /* backing files are opened read-only by default */
1409 qdict_set_default_str(child_options
, BDRV_OPT_READ_ONLY
, "on");
1410 qdict_set_default_str(child_options
, BDRV_OPT_AUTO_READ_ONLY
, "off");
1412 /* Inherit the read-only option from the parent if it's not set */
1413 qdict_copy_default(child_options
, parent_options
, BDRV_OPT_READ_ONLY
);
1414 qdict_copy_default(child_options
, parent_options
,
1415 BDRV_OPT_AUTO_READ_ONLY
);
1419 * bdrv_co_pdiscard() respects unmap policy for the parent, so we
1420 * can default to enable it on lower layers regardless of the
1423 qdict_set_default_str(child_options
, BDRV_OPT_DISCARD
, "unmap");
1425 /* Clear flags that only apply to the top layer */
1426 flags
&= ~(BDRV_O_SNAPSHOT
| BDRV_O_NO_BACKING
| BDRV_O_COPY_ON_READ
);
1428 if (role
& BDRV_CHILD_METADATA
) {
1429 flags
&= ~BDRV_O_NO_IO
;
1431 if (role
& BDRV_CHILD_COW
) {
1432 flags
&= ~BDRV_O_TEMPORARY
;
1435 *child_flags
= flags
;
1438 static void bdrv_child_cb_attach(BdrvChild
*child
)
1440 BlockDriverState
*bs
= child
->opaque
;
1442 assert_bdrv_graph_writable(bs
);
1443 QLIST_INSERT_HEAD(&bs
->children
, child
, next
);
1444 if (bs
->drv
->is_filter
|| (child
->role
& BDRV_CHILD_FILTERED
)) {
1446 * Here we handle filters and block/raw-format.c when it behave like
1447 * filter. They generally have a single PRIMARY child, which is also the
1448 * FILTERED child, and that they may have multiple more children, which
1449 * are neither PRIMARY nor FILTERED. And never we have a COW child here.
1450 * So bs->file will be the PRIMARY child, unless the PRIMARY child goes
1451 * into bs->backing on exceptional cases; and bs->backing will be
1454 assert(!(child
->role
& BDRV_CHILD_COW
));
1455 if (child
->role
& BDRV_CHILD_PRIMARY
) {
1456 assert(child
->role
& BDRV_CHILD_FILTERED
);
1457 assert(!bs
->backing
);
1460 if (bs
->drv
->filtered_child_is_backing
) {
1461 bs
->backing
= child
;
1466 assert(!(child
->role
& BDRV_CHILD_FILTERED
));
1468 } else if (child
->role
& BDRV_CHILD_COW
) {
1469 assert(bs
->drv
->supports_backing
);
1470 assert(!(child
->role
& BDRV_CHILD_PRIMARY
));
1471 assert(!bs
->backing
);
1472 bs
->backing
= child
;
1473 bdrv_backing_attach(child
);
1474 } else if (child
->role
& BDRV_CHILD_PRIMARY
) {
1479 bdrv_apply_subtree_drain(child
, bs
);
1482 static void bdrv_child_cb_detach(BdrvChild
*child
)
1484 BlockDriverState
*bs
= child
->opaque
;
1486 if (child
->role
& BDRV_CHILD_COW
) {
1487 bdrv_backing_detach(child
);
1490 bdrv_unapply_subtree_drain(child
, bs
);
1492 assert_bdrv_graph_writable(bs
);
1493 QLIST_REMOVE(child
, next
);
1494 if (child
== bs
->backing
) {
1495 assert(child
!= bs
->file
);
1497 } else if (child
== bs
->file
) {
1502 static int bdrv_child_cb_update_filename(BdrvChild
*c
, BlockDriverState
*base
,
1503 const char *filename
, Error
**errp
)
1505 if (c
->role
& BDRV_CHILD_COW
) {
1506 return bdrv_backing_update_filename(c
, base
, filename
, errp
);
1511 AioContext
*child_of_bds_get_parent_aio_context(BdrvChild
*c
)
1513 BlockDriverState
*bs
= c
->opaque
;
1516 return bdrv_get_aio_context(bs
);
1519 const BdrvChildClass child_of_bds
= {
1520 .parent_is_bds
= true,
1521 .get_parent_desc
= bdrv_child_get_parent_desc
,
1522 .inherit_options
= bdrv_inherited_options
,
1523 .drained_begin
= bdrv_child_cb_drained_begin
,
1524 .drained_poll
= bdrv_child_cb_drained_poll
,
1525 .drained_end
= bdrv_child_cb_drained_end
,
1526 .attach
= bdrv_child_cb_attach
,
1527 .detach
= bdrv_child_cb_detach
,
1528 .inactivate
= bdrv_child_cb_inactivate
,
1529 .change_aio_ctx
= bdrv_child_cb_change_aio_ctx
,
1530 .update_filename
= bdrv_child_cb_update_filename
,
1531 .get_parent_aio_context
= child_of_bds_get_parent_aio_context
,
1534 AioContext
*bdrv_child_get_parent_aio_context(BdrvChild
*c
)
1536 GLOBAL_STATE_CODE();
1537 return c
->klass
->get_parent_aio_context(c
);
1540 static int bdrv_open_flags(BlockDriverState
*bs
, int flags
)
1542 int open_flags
= flags
;
1543 GLOBAL_STATE_CODE();
1546 * Clear flags that are internal to the block layer before opening the
1549 open_flags
&= ~(BDRV_O_SNAPSHOT
| BDRV_O_NO_BACKING
| BDRV_O_PROTOCOL
);
1554 static void update_flags_from_options(int *flags
, QemuOpts
*opts
)
1556 GLOBAL_STATE_CODE();
1558 *flags
&= ~(BDRV_O_CACHE_MASK
| BDRV_O_RDWR
| BDRV_O_AUTO_RDONLY
);
1560 if (qemu_opt_get_bool_del(opts
, BDRV_OPT_CACHE_NO_FLUSH
, false)) {
1561 *flags
|= BDRV_O_NO_FLUSH
;
1564 if (qemu_opt_get_bool_del(opts
, BDRV_OPT_CACHE_DIRECT
, false)) {
1565 *flags
|= BDRV_O_NOCACHE
;
1568 if (!qemu_opt_get_bool_del(opts
, BDRV_OPT_READ_ONLY
, false)) {
1569 *flags
|= BDRV_O_RDWR
;
1572 if (qemu_opt_get_bool_del(opts
, BDRV_OPT_AUTO_READ_ONLY
, false)) {
1573 *flags
|= BDRV_O_AUTO_RDONLY
;
1577 static void update_options_from_flags(QDict
*options
, int flags
)
1579 GLOBAL_STATE_CODE();
1580 if (!qdict_haskey(options
, BDRV_OPT_CACHE_DIRECT
)) {
1581 qdict_put_bool(options
, BDRV_OPT_CACHE_DIRECT
, flags
& BDRV_O_NOCACHE
);
1583 if (!qdict_haskey(options
, BDRV_OPT_CACHE_NO_FLUSH
)) {
1584 qdict_put_bool(options
, BDRV_OPT_CACHE_NO_FLUSH
,
1585 flags
& BDRV_O_NO_FLUSH
);
1587 if (!qdict_haskey(options
, BDRV_OPT_READ_ONLY
)) {
1588 qdict_put_bool(options
, BDRV_OPT_READ_ONLY
, !(flags
& BDRV_O_RDWR
));
1590 if (!qdict_haskey(options
, BDRV_OPT_AUTO_READ_ONLY
)) {
1591 qdict_put_bool(options
, BDRV_OPT_AUTO_READ_ONLY
,
1592 flags
& BDRV_O_AUTO_RDONLY
);
1596 static void bdrv_assign_node_name(BlockDriverState
*bs
,
1597 const char *node_name
,
1600 char *gen_node_name
= NULL
;
1601 GLOBAL_STATE_CODE();
1604 node_name
= gen_node_name
= id_generate(ID_BLOCK
);
1605 } else if (!id_wellformed(node_name
)) {
1607 * Check for empty string or invalid characters, but not if it is
1608 * generated (generated names use characters not available to the user)
1610 error_setg(errp
, "Invalid node-name: '%s'", node_name
);
1614 /* takes care of avoiding namespaces collisions */
1615 if (blk_by_name(node_name
)) {
1616 error_setg(errp
, "node-name=%s is conflicting with a device id",
1621 /* takes care of avoiding duplicates node names */
1622 if (bdrv_find_node(node_name
)) {
1623 error_setg(errp
, "Duplicate nodes with node-name='%s'", node_name
);
1627 /* Make sure that the node name isn't truncated */
1628 if (strlen(node_name
) >= sizeof(bs
->node_name
)) {
1629 error_setg(errp
, "Node name too long");
1633 /* copy node name into the bs and insert it into the graph list */
1634 pstrcpy(bs
->node_name
, sizeof(bs
->node_name
), node_name
);
1635 QTAILQ_INSERT_TAIL(&graph_bdrv_states
, bs
, node_list
);
1637 g_free(gen_node_name
);
1640 static int bdrv_open_driver(BlockDriverState
*bs
, BlockDriver
*drv
,
1641 const char *node_name
, QDict
*options
,
1642 int open_flags
, Error
**errp
)
1644 Error
*local_err
= NULL
;
1646 GLOBAL_STATE_CODE();
1648 bdrv_assign_node_name(bs
, node_name
, &local_err
);
1650 error_propagate(errp
, local_err
);
1655 bs
->opaque
= g_malloc0(drv
->instance_size
);
1657 if (drv
->bdrv_file_open
) {
1658 assert(!drv
->bdrv_needs_filename
|| bs
->filename
[0]);
1659 ret
= drv
->bdrv_file_open(bs
, options
, open_flags
, &local_err
);
1660 } else if (drv
->bdrv_open
) {
1661 ret
= drv
->bdrv_open(bs
, options
, open_flags
, &local_err
);
1668 error_propagate(errp
, local_err
);
1669 } else if (bs
->filename
[0]) {
1670 error_setg_errno(errp
, -ret
, "Could not open '%s'", bs
->filename
);
1672 error_setg_errno(errp
, -ret
, "Could not open image");
1677 assert(!(bs
->supported_read_flags
& ~BDRV_REQ_MASK
));
1678 assert(!(bs
->supported_write_flags
& ~BDRV_REQ_MASK
));
1681 * Always allow the BDRV_REQ_REGISTERED_BUF optimization hint. This saves
1682 * drivers that pass read/write requests through to a child the trouble of
1683 * declaring support explicitly.
1685 * Drivers must not propagate this flag accidentally when they initiate I/O
1686 * to a bounce buffer. That case should be rare though.
1688 bs
->supported_read_flags
|= BDRV_REQ_REGISTERED_BUF
;
1689 bs
->supported_write_flags
|= BDRV_REQ_REGISTERED_BUF
;
1691 ret
= refresh_total_sectors(bs
, bs
->total_sectors
);
1693 error_setg_errno(errp
, -ret
, "Could not refresh total sector count");
1697 bdrv_refresh_limits(bs
, NULL
, &local_err
);
1699 error_propagate(errp
, local_err
);
1703 assert(bdrv_opt_mem_align(bs
) != 0);
1704 assert(bdrv_min_mem_align(bs
) != 0);
1705 assert(is_power_of_2(bs
->bl
.request_alignment
));
1707 for (i
= 0; i
< bs
->quiesce_counter
; i
++) {
1708 if (drv
->bdrv_co_drain_begin
) {
1709 drv
->bdrv_co_drain_begin(bs
);
1716 if (bs
->file
!= NULL
) {
1717 bdrv_unref_child(bs
, bs
->file
);
1726 * Create and open a block node.
1728 * @options is a QDict of options to pass to the block drivers, or NULL for an
1729 * empty set of options. The reference to the QDict belongs to the block layer
1730 * after the call (even on failure), so if the caller intends to reuse the
1731 * dictionary, it needs to use qobject_ref() before calling bdrv_open.
1733 BlockDriverState
*bdrv_new_open_driver_opts(BlockDriver
*drv
,
1734 const char *node_name
,
1735 QDict
*options
, int flags
,
1738 BlockDriverState
*bs
;
1741 GLOBAL_STATE_CODE();
1744 bs
->open_flags
= flags
;
1745 bs
->options
= options
?: qdict_new();
1746 bs
->explicit_options
= qdict_clone_shallow(bs
->options
);
1749 update_options_from_flags(bs
->options
, flags
);
1751 ret
= bdrv_open_driver(bs
, drv
, node_name
, bs
->options
, flags
, errp
);
1753 qobject_unref(bs
->explicit_options
);
1754 bs
->explicit_options
= NULL
;
1755 qobject_unref(bs
->options
);
1764 /* Create and open a block node. */
1765 BlockDriverState
*bdrv_new_open_driver(BlockDriver
*drv
, const char *node_name
,
1766 int flags
, Error
**errp
)
1768 GLOBAL_STATE_CODE();
1769 return bdrv_new_open_driver_opts(drv
, node_name
, NULL
, flags
, errp
);
1772 QemuOptsList bdrv_runtime_opts
= {
1773 .name
= "bdrv_common",
1774 .head
= QTAILQ_HEAD_INITIALIZER(bdrv_runtime_opts
.head
),
1777 .name
= "node-name",
1778 .type
= QEMU_OPT_STRING
,
1779 .help
= "Node name of the block device node",
1783 .type
= QEMU_OPT_STRING
,
1784 .help
= "Block driver to use for the node",
1787 .name
= BDRV_OPT_CACHE_DIRECT
,
1788 .type
= QEMU_OPT_BOOL
,
1789 .help
= "Bypass software writeback cache on the host",
1792 .name
= BDRV_OPT_CACHE_NO_FLUSH
,
1793 .type
= QEMU_OPT_BOOL
,
1794 .help
= "Ignore flush requests",
1797 .name
= BDRV_OPT_READ_ONLY
,
1798 .type
= QEMU_OPT_BOOL
,
1799 .help
= "Node is opened in read-only mode",
1802 .name
= BDRV_OPT_AUTO_READ_ONLY
,
1803 .type
= QEMU_OPT_BOOL
,
1804 .help
= "Node can become read-only if opening read-write fails",
1807 .name
= "detect-zeroes",
1808 .type
= QEMU_OPT_STRING
,
1809 .help
= "try to optimize zero writes (off, on, unmap)",
1812 .name
= BDRV_OPT_DISCARD
,
1813 .type
= QEMU_OPT_STRING
,
1814 .help
= "discard operation (ignore/off, unmap/on)",
1817 .name
= BDRV_OPT_FORCE_SHARE
,
1818 .type
= QEMU_OPT_BOOL
,
1819 .help
= "always accept other writers (default: off)",
1821 { /* end of list */ }
1825 QemuOptsList bdrv_create_opts_simple
= {
1826 .name
= "simple-create-opts",
1827 .head
= QTAILQ_HEAD_INITIALIZER(bdrv_create_opts_simple
.head
),
1830 .name
= BLOCK_OPT_SIZE
,
1831 .type
= QEMU_OPT_SIZE
,
1832 .help
= "Virtual disk size"
1835 .name
= BLOCK_OPT_PREALLOC
,
1836 .type
= QEMU_OPT_STRING
,
1837 .help
= "Preallocation mode (allowed values: off)"
1839 { /* end of list */ }
1844 * Common part for opening disk images and files
1846 * Removes all processed options from *options.
1848 static int bdrv_open_common(BlockDriverState
*bs
, BlockBackend
*file
,
1849 QDict
*options
, Error
**errp
)
1851 int ret
, open_flags
;
1852 const char *filename
;
1853 const char *driver_name
= NULL
;
1854 const char *node_name
= NULL
;
1855 const char *discard
;
1858 Error
*local_err
= NULL
;
1861 assert(bs
->file
== NULL
);
1862 assert(options
!= NULL
&& bs
->options
!= options
);
1863 GLOBAL_STATE_CODE();
1865 opts
= qemu_opts_create(&bdrv_runtime_opts
, NULL
, 0, &error_abort
);
1866 if (!qemu_opts_absorb_qdict(opts
, options
, errp
)) {
1871 update_flags_from_options(&bs
->open_flags
, opts
);
1873 driver_name
= qemu_opt_get(opts
, "driver");
1874 drv
= bdrv_find_format(driver_name
);
1875 assert(drv
!= NULL
);
1877 bs
->force_share
= qemu_opt_get_bool(opts
, BDRV_OPT_FORCE_SHARE
, false);
1879 if (bs
->force_share
&& (bs
->open_flags
& BDRV_O_RDWR
)) {
1881 BDRV_OPT_FORCE_SHARE
1882 "=on can only be used with read-only images");
1888 bdrv_refresh_filename(blk_bs(file
));
1889 filename
= blk_bs(file
)->filename
;
1892 * Caution: while qdict_get_try_str() is fine, getting
1893 * non-string types would require more care. When @options
1894 * come from -blockdev or blockdev_add, its members are typed
1895 * according to the QAPI schema, but when they come from
1896 * -drive, they're all QString.
1898 filename
= qdict_get_try_str(options
, "filename");
1901 if (drv
->bdrv_needs_filename
&& (!filename
|| !filename
[0])) {
1902 error_setg(errp
, "The '%s' block driver requires a file name",
1908 trace_bdrv_open_common(bs
, filename
?: "", bs
->open_flags
,
1911 ro
= bdrv_is_read_only(bs
);
1913 if (use_bdrv_whitelist
&& !bdrv_is_whitelisted(drv
, ro
)) {
1914 if (!ro
&& bdrv_is_whitelisted(drv
, true)) {
1915 ret
= bdrv_apply_auto_read_only(bs
, NULL
, NULL
);
1921 !ro
&& bdrv_is_whitelisted(drv
, true)
1922 ? "Driver '%s' can only be used for read-only devices"
1923 : "Driver '%s' is not whitelisted",
1929 /* bdrv_new() and bdrv_close() make it so */
1930 assert(qatomic_read(&bs
->copy_on_read
) == 0);
1932 if (bs
->open_flags
& BDRV_O_COPY_ON_READ
) {
1934 bdrv_enable_copy_on_read(bs
);
1936 error_setg(errp
, "Can't use copy-on-read on read-only device");
1942 discard
= qemu_opt_get(opts
, BDRV_OPT_DISCARD
);
1943 if (discard
!= NULL
) {
1944 if (bdrv_parse_discard_flags(discard
, &bs
->open_flags
) != 0) {
1945 error_setg(errp
, "Invalid discard option");
1952 bdrv_parse_detect_zeroes(opts
, bs
->open_flags
, &local_err
);
1954 error_propagate(errp
, local_err
);
1959 if (filename
!= NULL
) {
1960 pstrcpy(bs
->filename
, sizeof(bs
->filename
), filename
);
1962 bs
->filename
[0] = '\0';
1964 pstrcpy(bs
->exact_filename
, sizeof(bs
->exact_filename
), bs
->filename
);
1966 /* Open the image, either directly or using a protocol */
1967 open_flags
= bdrv_open_flags(bs
, bs
->open_flags
);
1968 node_name
= qemu_opt_get(opts
, "node-name");
1970 assert(!drv
->bdrv_file_open
|| file
== NULL
);
1971 ret
= bdrv_open_driver(bs
, drv
, node_name
, options
, open_flags
, errp
);
1976 qemu_opts_del(opts
);
1980 qemu_opts_del(opts
);
1984 static QDict
*parse_json_filename(const char *filename
, Error
**errp
)
1986 QObject
*options_obj
;
1989 GLOBAL_STATE_CODE();
1991 ret
= strstart(filename
, "json:", &filename
);
1994 options_obj
= qobject_from_json(filename
, errp
);
1996 error_prepend(errp
, "Could not parse the JSON options: ");
2000 options
= qobject_to(QDict
, options_obj
);
2002 qobject_unref(options_obj
);
2003 error_setg(errp
, "Invalid JSON object given");
2007 qdict_flatten(options
);
2012 static void parse_json_protocol(QDict
*options
, const char **pfilename
,
2015 QDict
*json_options
;
2016 Error
*local_err
= NULL
;
2017 GLOBAL_STATE_CODE();
2019 /* Parse json: pseudo-protocol */
2020 if (!*pfilename
|| !g_str_has_prefix(*pfilename
, "json:")) {
2024 json_options
= parse_json_filename(*pfilename
, &local_err
);
2026 error_propagate(errp
, local_err
);
2030 /* Options given in the filename have lower priority than options
2031 * specified directly */
2032 qdict_join(options
, json_options
, false);
2033 qobject_unref(json_options
);
2038 * Fills in default options for opening images and converts the legacy
2039 * filename/flags pair to option QDict entries.
2040 * The BDRV_O_PROTOCOL flag in *flags will be set or cleared accordingly if a
2041 * block driver has been specified explicitly.
2043 static int bdrv_fill_options(QDict
**options
, const char *filename
,
2044 int *flags
, Error
**errp
)
2046 const char *drvname
;
2047 bool protocol
= *flags
& BDRV_O_PROTOCOL
;
2048 bool parse_filename
= false;
2049 BlockDriver
*drv
= NULL
;
2050 Error
*local_err
= NULL
;
2052 GLOBAL_STATE_CODE();
2055 * Caution: while qdict_get_try_str() is fine, getting non-string
2056 * types would require more care. When @options come from
2057 * -blockdev or blockdev_add, its members are typed according to
2058 * the QAPI schema, but when they come from -drive, they're all
2061 drvname
= qdict_get_try_str(*options
, "driver");
2063 drv
= bdrv_find_format(drvname
);
2065 error_setg(errp
, "Unknown driver '%s'", drvname
);
2068 /* If the user has explicitly specified the driver, this choice should
2069 * override the BDRV_O_PROTOCOL flag */
2070 protocol
= drv
->bdrv_file_open
;
2074 *flags
|= BDRV_O_PROTOCOL
;
2076 *flags
&= ~BDRV_O_PROTOCOL
;
2079 /* Translate cache options from flags into options */
2080 update_options_from_flags(*options
, *flags
);
2082 /* Fetch the file name from the options QDict if necessary */
2083 if (protocol
&& filename
) {
2084 if (!qdict_haskey(*options
, "filename")) {
2085 qdict_put_str(*options
, "filename", filename
);
2086 parse_filename
= true;
2088 error_setg(errp
, "Can't specify 'file' and 'filename' options at "
2094 /* Find the right block driver */
2095 /* See cautionary note on accessing @options above */
2096 filename
= qdict_get_try_str(*options
, "filename");
2098 if (!drvname
&& protocol
) {
2100 drv
= bdrv_find_protocol(filename
, parse_filename
, errp
);
2105 drvname
= drv
->format_name
;
2106 qdict_put_str(*options
, "driver", drvname
);
2108 error_setg(errp
, "Must specify either driver or file");
2113 assert(drv
|| !protocol
);
2115 /* Driver-specific filename parsing */
2116 if (drv
&& drv
->bdrv_parse_filename
&& parse_filename
) {
2117 drv
->bdrv_parse_filename(filename
, *options
, &local_err
);
2119 error_propagate(errp
, local_err
);
2123 if (!drv
->bdrv_needs_filename
) {
2124 qdict_del(*options
, "filename");
2131 typedef struct BlockReopenQueueEntry
{
2134 BDRVReopenState state
;
2135 QTAILQ_ENTRY(BlockReopenQueueEntry
) entry
;
2136 } BlockReopenQueueEntry
;
2139 * Return the flags that @bs will have after the reopens in @q have
2140 * successfully completed. If @q is NULL (or @bs is not contained in @q),
2141 * return the current flags.
2143 static int bdrv_reopen_get_flags(BlockReopenQueue
*q
, BlockDriverState
*bs
)
2145 BlockReopenQueueEntry
*entry
;
2148 QTAILQ_FOREACH(entry
, q
, entry
) {
2149 if (entry
->state
.bs
== bs
) {
2150 return entry
->state
.flags
;
2155 return bs
->open_flags
;
2158 /* Returns whether the image file can be written to after the reopen queue @q
2159 * has been successfully applied, or right now if @q is NULL. */
2160 static bool bdrv_is_writable_after_reopen(BlockDriverState
*bs
,
2161 BlockReopenQueue
*q
)
2163 int flags
= bdrv_reopen_get_flags(q
, bs
);
2165 return (flags
& (BDRV_O_RDWR
| BDRV_O_INACTIVE
)) == BDRV_O_RDWR
;
2169 * Return whether the BDS can be written to. This is not necessarily
2170 * the same as !bdrv_is_read_only(bs), as inactivated images may not
2171 * be written to but do not count as read-only images.
2173 bool bdrv_is_writable(BlockDriverState
*bs
)
2176 return bdrv_is_writable_after_reopen(bs
, NULL
);
2179 static char *bdrv_child_user_desc(BdrvChild
*c
)
2181 GLOBAL_STATE_CODE();
2182 return c
->klass
->get_parent_desc(c
);
2186 * Check that @a allows everything that @b needs. @a and @b must reference same
2189 static bool bdrv_a_allow_b(BdrvChild
*a
, BdrvChild
*b
, Error
**errp
)
2191 const char *child_bs_name
;
2192 g_autofree
char *a_user
= NULL
;
2193 g_autofree
char *b_user
= NULL
;
2194 g_autofree
char *perms
= NULL
;
2197 assert(a
->bs
== b
->bs
);
2198 GLOBAL_STATE_CODE();
2200 if ((b
->perm
& a
->shared_perm
) == b
->perm
) {
2204 child_bs_name
= bdrv_get_node_name(b
->bs
);
2205 a_user
= bdrv_child_user_desc(a
);
2206 b_user
= bdrv_child_user_desc(b
);
2207 perms
= bdrv_perm_names(b
->perm
& ~a
->shared_perm
);
2209 error_setg(errp
, "Permission conflict on node '%s': permissions '%s' are "
2210 "both required by %s (uses node '%s' as '%s' child) and "
2211 "unshared by %s (uses node '%s' as '%s' child).",
2212 child_bs_name
, perms
,
2213 b_user
, child_bs_name
, b
->name
,
2214 a_user
, child_bs_name
, a
->name
);
2219 static bool bdrv_parent_perms_conflict(BlockDriverState
*bs
, Error
**errp
)
2222 GLOBAL_STATE_CODE();
2225 * During the loop we'll look at each pair twice. That's correct because
2226 * bdrv_a_allow_b() is asymmetric and we should check each pair in both
2229 QLIST_FOREACH(a
, &bs
->parents
, next_parent
) {
2230 QLIST_FOREACH(b
, &bs
->parents
, next_parent
) {
2235 if (!bdrv_a_allow_b(a
, b
, errp
)) {
2244 static void bdrv_child_perm(BlockDriverState
*bs
, BlockDriverState
*child_bs
,
2245 BdrvChild
*c
, BdrvChildRole role
,
2246 BlockReopenQueue
*reopen_queue
,
2247 uint64_t parent_perm
, uint64_t parent_shared
,
2248 uint64_t *nperm
, uint64_t *nshared
)
2250 assert(bs
->drv
&& bs
->drv
->bdrv_child_perm
);
2251 GLOBAL_STATE_CODE();
2252 bs
->drv
->bdrv_child_perm(bs
, c
, role
, reopen_queue
,
2253 parent_perm
, parent_shared
,
2255 /* TODO Take force_share from reopen_queue */
2256 if (child_bs
&& child_bs
->force_share
) {
2257 *nshared
= BLK_PERM_ALL
;
2262 * Adds the whole subtree of @bs (including @bs itself) to the @list (except for
2263 * nodes that are already in the @list, of course) so that final list is
2264 * topologically sorted. Return the result (GSList @list object is updated, so
2265 * don't use old reference after function call).
2267 * On function start @list must be already topologically sorted and for any node
2268 * in the @list the whole subtree of the node must be in the @list as well. The
2269 * simplest way to satisfy this criteria: use only result of
2270 * bdrv_topological_dfs() or NULL as @list parameter.
2272 static GSList
*bdrv_topological_dfs(GSList
*list
, GHashTable
*found
,
2273 BlockDriverState
*bs
)
2276 g_autoptr(GHashTable
) local_found
= NULL
;
2278 GLOBAL_STATE_CODE();
2282 found
= local_found
= g_hash_table_new(NULL
, NULL
);
2285 if (g_hash_table_contains(found
, bs
)) {
2288 g_hash_table_add(found
, bs
);
2290 QLIST_FOREACH(child
, &bs
->children
, next
) {
2291 list
= bdrv_topological_dfs(list
, found
, child
->bs
);
2294 return g_slist_prepend(list
, bs
);
2297 typedef struct BdrvChildSetPermState
{
2300 uint64_t old_shared_perm
;
2301 } BdrvChildSetPermState
;
2303 static void bdrv_child_set_perm_abort(void *opaque
)
2305 BdrvChildSetPermState
*s
= opaque
;
2307 GLOBAL_STATE_CODE();
2309 s
->child
->perm
= s
->old_perm
;
2310 s
->child
->shared_perm
= s
->old_shared_perm
;
2313 static TransactionActionDrv bdrv_child_set_pem_drv
= {
2314 .abort
= bdrv_child_set_perm_abort
,
2318 static void bdrv_child_set_perm(BdrvChild
*c
, uint64_t perm
,
2319 uint64_t shared
, Transaction
*tran
)
2321 BdrvChildSetPermState
*s
= g_new(BdrvChildSetPermState
, 1);
2322 GLOBAL_STATE_CODE();
2324 *s
= (BdrvChildSetPermState
) {
2326 .old_perm
= c
->perm
,
2327 .old_shared_perm
= c
->shared_perm
,
2331 c
->shared_perm
= shared
;
2333 tran_add(tran
, &bdrv_child_set_pem_drv
, s
);
2336 static void bdrv_drv_set_perm_commit(void *opaque
)
2338 BlockDriverState
*bs
= opaque
;
2339 uint64_t cumulative_perms
, cumulative_shared_perms
;
2340 GLOBAL_STATE_CODE();
2342 if (bs
->drv
->bdrv_set_perm
) {
2343 bdrv_get_cumulative_perm(bs
, &cumulative_perms
,
2344 &cumulative_shared_perms
);
2345 bs
->drv
->bdrv_set_perm(bs
, cumulative_perms
, cumulative_shared_perms
);
2349 static void bdrv_drv_set_perm_abort(void *opaque
)
2351 BlockDriverState
*bs
= opaque
;
2352 GLOBAL_STATE_CODE();
2354 if (bs
->drv
->bdrv_abort_perm_update
) {
2355 bs
->drv
->bdrv_abort_perm_update(bs
);
2359 TransactionActionDrv bdrv_drv_set_perm_drv
= {
2360 .abort
= bdrv_drv_set_perm_abort
,
2361 .commit
= bdrv_drv_set_perm_commit
,
2364 static int bdrv_drv_set_perm(BlockDriverState
*bs
, uint64_t perm
,
2365 uint64_t shared_perm
, Transaction
*tran
,
2368 GLOBAL_STATE_CODE();
2373 if (bs
->drv
->bdrv_check_perm
) {
2374 int ret
= bs
->drv
->bdrv_check_perm(bs
, perm
, shared_perm
, errp
);
2381 tran_add(tran
, &bdrv_drv_set_perm_drv
, bs
);
2387 typedef struct BdrvReplaceChildState
{
2389 BlockDriverState
*old_bs
;
2390 } BdrvReplaceChildState
;
2392 static void bdrv_replace_child_commit(void *opaque
)
2394 BdrvReplaceChildState
*s
= opaque
;
2395 GLOBAL_STATE_CODE();
2397 bdrv_unref(s
->old_bs
);
2400 static void bdrv_replace_child_abort(void *opaque
)
2402 BdrvReplaceChildState
*s
= opaque
;
2403 BlockDriverState
*new_bs
= s
->child
->bs
;
2405 GLOBAL_STATE_CODE();
2406 /* old_bs reference is transparently moved from @s to @s->child */
2407 bdrv_replace_child_noperm(s
->child
, s
->old_bs
);
2411 static TransactionActionDrv bdrv_replace_child_drv
= {
2412 .commit
= bdrv_replace_child_commit
,
2413 .abort
= bdrv_replace_child_abort
,
2418 * bdrv_replace_child_tran
2420 * Note: real unref of old_bs is done only on commit.
2422 * The function doesn't update permissions, caller is responsible for this.
2424 static void bdrv_replace_child_tran(BdrvChild
*child
, BlockDriverState
*new_bs
,
2427 BdrvReplaceChildState
*s
= g_new(BdrvReplaceChildState
, 1);
2428 *s
= (BdrvReplaceChildState
) {
2430 .old_bs
= child
->bs
,
2432 tran_add(tran
, &bdrv_replace_child_drv
, s
);
2437 bdrv_replace_child_noperm(child
, new_bs
);
2438 /* old_bs reference is transparently moved from @child to @s */
2442 * Refresh permissions in @bs subtree. The function is intended to be called
2443 * after some graph modification that was done without permission update.
2445 static int bdrv_node_refresh_perm(BlockDriverState
*bs
, BlockReopenQueue
*q
,
2446 Transaction
*tran
, Error
**errp
)
2448 BlockDriver
*drv
= bs
->drv
;
2451 uint64_t cumulative_perms
, cumulative_shared_perms
;
2452 GLOBAL_STATE_CODE();
2454 bdrv_get_cumulative_perm(bs
, &cumulative_perms
, &cumulative_shared_perms
);
2456 /* Write permissions never work with read-only images */
2457 if ((cumulative_perms
& (BLK_PERM_WRITE
| BLK_PERM_WRITE_UNCHANGED
)) &&
2458 !bdrv_is_writable_after_reopen(bs
, q
))
2460 if (!bdrv_is_writable_after_reopen(bs
, NULL
)) {
2461 error_setg(errp
, "Block node is read-only");
2463 error_setg(errp
, "Read-only block node '%s' cannot support "
2464 "read-write users", bdrv_get_node_name(bs
));
2471 * Unaligned requests will automatically be aligned to bl.request_alignment
2472 * and without RESIZE we can't extend requests to write to space beyond the
2473 * end of the image, so it's required that the image size is aligned.
2475 if ((cumulative_perms
& (BLK_PERM_WRITE
| BLK_PERM_WRITE_UNCHANGED
)) &&
2476 !(cumulative_perms
& BLK_PERM_RESIZE
))
2478 if ((bs
->total_sectors
* BDRV_SECTOR_SIZE
) % bs
->bl
.request_alignment
) {
2479 error_setg(errp
, "Cannot get 'write' permission without 'resize': "
2480 "Image size is not a multiple of request "
2486 /* Check this node */
2491 ret
= bdrv_drv_set_perm(bs
, cumulative_perms
, cumulative_shared_perms
, tran
,
2497 /* Drivers that never have children can omit .bdrv_child_perm() */
2498 if (!drv
->bdrv_child_perm
) {
2499 assert(QLIST_EMPTY(&bs
->children
));
2503 /* Check all children */
2504 QLIST_FOREACH(c
, &bs
->children
, next
) {
2505 uint64_t cur_perm
, cur_shared
;
2507 bdrv_child_perm(bs
, c
->bs
, c
, c
->role
, q
,
2508 cumulative_perms
, cumulative_shared_perms
,
2509 &cur_perm
, &cur_shared
);
2510 bdrv_child_set_perm(c
, cur_perm
, cur_shared
, tran
);
2516 static int bdrv_list_refresh_perms(GSList
*list
, BlockReopenQueue
*q
,
2517 Transaction
*tran
, Error
**errp
)
2520 BlockDriverState
*bs
;
2521 GLOBAL_STATE_CODE();
2523 for ( ; list
; list
= list
->next
) {
2526 if (bdrv_parent_perms_conflict(bs
, errp
)) {
2530 ret
= bdrv_node_refresh_perm(bs
, q
, tran
, errp
);
2539 void bdrv_get_cumulative_perm(BlockDriverState
*bs
, uint64_t *perm
,
2540 uint64_t *shared_perm
)
2543 uint64_t cumulative_perms
= 0;
2544 uint64_t cumulative_shared_perms
= BLK_PERM_ALL
;
2546 GLOBAL_STATE_CODE();
2548 QLIST_FOREACH(c
, &bs
->parents
, next_parent
) {
2549 cumulative_perms
|= c
->perm
;
2550 cumulative_shared_perms
&= c
->shared_perm
;
2553 *perm
= cumulative_perms
;
2554 *shared_perm
= cumulative_shared_perms
;
2557 char *bdrv_perm_names(uint64_t perm
)
2563 { BLK_PERM_CONSISTENT_READ
, "consistent read" },
2564 { BLK_PERM_WRITE
, "write" },
2565 { BLK_PERM_WRITE_UNCHANGED
, "write unchanged" },
2566 { BLK_PERM_RESIZE
, "resize" },
2570 GString
*result
= g_string_sized_new(30);
2571 struct perm_name
*p
;
2573 for (p
= permissions
; p
->name
; p
++) {
2574 if (perm
& p
->perm
) {
2575 if (result
->len
> 0) {
2576 g_string_append(result
, ", ");
2578 g_string_append(result
, p
->name
);
2582 return g_string_free(result
, FALSE
);
2586 static int bdrv_refresh_perms(BlockDriverState
*bs
, Error
**errp
)
2589 Transaction
*tran
= tran_new();
2590 g_autoptr(GSList
) list
= bdrv_topological_dfs(NULL
, NULL
, bs
);
2591 GLOBAL_STATE_CODE();
2593 ret
= bdrv_list_refresh_perms(list
, NULL
, tran
, errp
);
2594 tran_finalize(tran
, ret
);
2599 int bdrv_child_try_set_perm(BdrvChild
*c
, uint64_t perm
, uint64_t shared
,
2602 Error
*local_err
= NULL
;
2603 Transaction
*tran
= tran_new();
2606 GLOBAL_STATE_CODE();
2608 bdrv_child_set_perm(c
, perm
, shared
, tran
);
2610 ret
= bdrv_refresh_perms(c
->bs
, &local_err
);
2612 tran_finalize(tran
, ret
);
2615 if ((perm
& ~c
->perm
) || (c
->shared_perm
& ~shared
)) {
2616 /* tighten permissions */
2617 error_propagate(errp
, local_err
);
2620 * Our caller may intend to only loosen restrictions and
2621 * does not expect this function to fail. Errors are not
2622 * fatal in such a case, so we can just hide them from our
2625 error_free(local_err
);
2633 int bdrv_child_refresh_perms(BlockDriverState
*bs
, BdrvChild
*c
, Error
**errp
)
2635 uint64_t parent_perms
, parent_shared
;
2636 uint64_t perms
, shared
;
2638 GLOBAL_STATE_CODE();
2640 bdrv_get_cumulative_perm(bs
, &parent_perms
, &parent_shared
);
2641 bdrv_child_perm(bs
, c
->bs
, c
, c
->role
, NULL
,
2642 parent_perms
, parent_shared
, &perms
, &shared
);
2644 return bdrv_child_try_set_perm(c
, perms
, shared
, errp
);
2648 * Default implementation for .bdrv_child_perm() for block filters:
2649 * Forward CONSISTENT_READ, WRITE, WRITE_UNCHANGED, and RESIZE to the
2652 static void bdrv_filter_default_perms(BlockDriverState
*bs
, BdrvChild
*c
,
2654 BlockReopenQueue
*reopen_queue
,
2655 uint64_t perm
, uint64_t shared
,
2656 uint64_t *nperm
, uint64_t *nshared
)
2658 GLOBAL_STATE_CODE();
2659 *nperm
= perm
& DEFAULT_PERM_PASSTHROUGH
;
2660 *nshared
= (shared
& DEFAULT_PERM_PASSTHROUGH
) | DEFAULT_PERM_UNCHANGED
;
2663 static void bdrv_default_perms_for_cow(BlockDriverState
*bs
, BdrvChild
*c
,
2665 BlockReopenQueue
*reopen_queue
,
2666 uint64_t perm
, uint64_t shared
,
2667 uint64_t *nperm
, uint64_t *nshared
)
2669 assert(role
& BDRV_CHILD_COW
);
2670 GLOBAL_STATE_CODE();
2673 * We want consistent read from backing files if the parent needs it.
2674 * No other operations are performed on backing files.
2676 perm
&= BLK_PERM_CONSISTENT_READ
;
2679 * If the parent can deal with changing data, we're okay with a
2680 * writable and resizable backing file.
2681 * TODO Require !(perm & BLK_PERM_CONSISTENT_READ), too?
2683 if (shared
& BLK_PERM_WRITE
) {
2684 shared
= BLK_PERM_WRITE
| BLK_PERM_RESIZE
;
2689 shared
|= BLK_PERM_CONSISTENT_READ
| BLK_PERM_WRITE_UNCHANGED
;
2691 if (bs
->open_flags
& BDRV_O_INACTIVE
) {
2692 shared
|= BLK_PERM_WRITE
| BLK_PERM_RESIZE
;
2699 static void bdrv_default_perms_for_storage(BlockDriverState
*bs
, BdrvChild
*c
,
2701 BlockReopenQueue
*reopen_queue
,
2702 uint64_t perm
, uint64_t shared
,
2703 uint64_t *nperm
, uint64_t *nshared
)
2707 GLOBAL_STATE_CODE();
2708 assert(role
& (BDRV_CHILD_METADATA
| BDRV_CHILD_DATA
));
2710 flags
= bdrv_reopen_get_flags(reopen_queue
, bs
);
2713 * Apart from the modifications below, the same permissions are
2714 * forwarded and left alone as for filters
2716 bdrv_filter_default_perms(bs
, c
, role
, reopen_queue
,
2717 perm
, shared
, &perm
, &shared
);
2719 if (role
& BDRV_CHILD_METADATA
) {
2720 /* Format drivers may touch metadata even if the guest doesn't write */
2721 if (bdrv_is_writable_after_reopen(bs
, reopen_queue
)) {
2722 perm
|= BLK_PERM_WRITE
| BLK_PERM_RESIZE
;
2726 * bs->file always needs to be consistent because of the
2727 * metadata. We can never allow other users to resize or write
2730 if (!(flags
& BDRV_O_NO_IO
)) {
2731 perm
|= BLK_PERM_CONSISTENT_READ
;
2733 shared
&= ~(BLK_PERM_WRITE
| BLK_PERM_RESIZE
);
2736 if (role
& BDRV_CHILD_DATA
) {
2738 * Technically, everything in this block is a subset of the
2739 * BDRV_CHILD_METADATA path taken above, and so this could
2740 * be an "else if" branch. However, that is not obvious, and
2741 * this function is not performance critical, therefore we let
2742 * this be an independent "if".
2746 * We cannot allow other users to resize the file because the
2747 * format driver might have some assumptions about the size
2748 * (e.g. because it is stored in metadata, or because the file
2749 * is split into fixed-size data files).
2751 shared
&= ~BLK_PERM_RESIZE
;
2754 * WRITE_UNCHANGED often cannot be performed as such on the
2755 * data file. For example, the qcow2 driver may still need to
2756 * write copied clusters on copy-on-read.
2758 if (perm
& BLK_PERM_WRITE_UNCHANGED
) {
2759 perm
|= BLK_PERM_WRITE
;
2763 * If the data file is written to, the format driver may
2764 * expect to be able to resize it by writing beyond the EOF.
2766 if (perm
& BLK_PERM_WRITE
) {
2767 perm
|= BLK_PERM_RESIZE
;
2771 if (bs
->open_flags
& BDRV_O_INACTIVE
) {
2772 shared
|= BLK_PERM_WRITE
| BLK_PERM_RESIZE
;
2779 void bdrv_default_perms(BlockDriverState
*bs
, BdrvChild
*c
,
2780 BdrvChildRole role
, BlockReopenQueue
*reopen_queue
,
2781 uint64_t perm
, uint64_t shared
,
2782 uint64_t *nperm
, uint64_t *nshared
)
2784 GLOBAL_STATE_CODE();
2785 if (role
& BDRV_CHILD_FILTERED
) {
2786 assert(!(role
& (BDRV_CHILD_DATA
| BDRV_CHILD_METADATA
|
2788 bdrv_filter_default_perms(bs
, c
, role
, reopen_queue
,
2789 perm
, shared
, nperm
, nshared
);
2790 } else if (role
& BDRV_CHILD_COW
) {
2791 assert(!(role
& (BDRV_CHILD_DATA
| BDRV_CHILD_METADATA
)));
2792 bdrv_default_perms_for_cow(bs
, c
, role
, reopen_queue
,
2793 perm
, shared
, nperm
, nshared
);
2794 } else if (role
& (BDRV_CHILD_METADATA
| BDRV_CHILD_DATA
)) {
2795 bdrv_default_perms_for_storage(bs
, c
, role
, reopen_queue
,
2796 perm
, shared
, nperm
, nshared
);
2798 g_assert_not_reached();
2802 uint64_t bdrv_qapi_perm_to_blk_perm(BlockPermission qapi_perm
)
2804 static const uint64_t permissions
[] = {
2805 [BLOCK_PERMISSION_CONSISTENT_READ
] = BLK_PERM_CONSISTENT_READ
,
2806 [BLOCK_PERMISSION_WRITE
] = BLK_PERM_WRITE
,
2807 [BLOCK_PERMISSION_WRITE_UNCHANGED
] = BLK_PERM_WRITE_UNCHANGED
,
2808 [BLOCK_PERMISSION_RESIZE
] = BLK_PERM_RESIZE
,
2811 QEMU_BUILD_BUG_ON(ARRAY_SIZE(permissions
) != BLOCK_PERMISSION__MAX
);
2812 QEMU_BUILD_BUG_ON(1UL << ARRAY_SIZE(permissions
) != BLK_PERM_ALL
+ 1);
2814 assert(qapi_perm
< BLOCK_PERMISSION__MAX
);
2816 return permissions
[qapi_perm
];
2819 static void bdrv_replace_child_noperm(BdrvChild
*child
,
2820 BlockDriverState
*new_bs
)
2822 BlockDriverState
*old_bs
= child
->bs
;
2823 int new_bs_quiesce_counter
;
2826 assert(!child
->frozen
);
2827 assert(old_bs
!= new_bs
);
2828 GLOBAL_STATE_CODE();
2830 if (old_bs
&& new_bs
) {
2831 assert(bdrv_get_aio_context(old_bs
) == bdrv_get_aio_context(new_bs
));
2834 new_bs_quiesce_counter
= (new_bs
? new_bs
->quiesce_counter
: 0);
2835 drain_saldo
= new_bs_quiesce_counter
- child
->parent_quiesce_counter
;
2838 * If the new child node is drained but the old one was not, flush
2839 * all outstanding requests to the old child node.
2841 while (drain_saldo
> 0 && child
->klass
->drained_begin
) {
2842 bdrv_parent_drained_begin_single(child
, true);
2847 /* Detach first so that the recursive drain sections coming from @child
2848 * are already gone and we only end the drain sections that came from
2850 if (child
->klass
->detach
) {
2851 child
->klass
->detach(child
);
2853 assert_bdrv_graph_writable(old_bs
);
2854 QLIST_REMOVE(child
, next_parent
);
2860 assert_bdrv_graph_writable(new_bs
);
2861 QLIST_INSERT_HEAD(&new_bs
->parents
, child
, next_parent
);
2864 * Detaching the old node may have led to the new node's
2865 * quiesce_counter having been decreased. Not a problem, we
2866 * just need to recognize this here and then invoke
2867 * drained_end appropriately more often.
2869 assert(new_bs
->quiesce_counter
<= new_bs_quiesce_counter
);
2870 drain_saldo
+= new_bs
->quiesce_counter
- new_bs_quiesce_counter
;
2872 /* Attach only after starting new drained sections, so that recursive
2873 * drain sections coming from @child don't get an extra .drained_begin
2875 if (child
->klass
->attach
) {
2876 child
->klass
->attach(child
);
2881 * If the old child node was drained but the new one is not, allow
2882 * requests to come in only after the new node has been attached.
2884 while (drain_saldo
< 0 && child
->klass
->drained_end
) {
2885 bdrv_parent_drained_end_single(child
);
2891 * Free the given @child.
2893 * The child must be empty (i.e. `child->bs == NULL`) and it must be
2894 * unused (i.e. not in a children list).
2896 static void bdrv_child_free(BdrvChild
*child
)
2899 GLOBAL_STATE_CODE();
2900 assert(!child
->next
.le_prev
); /* not in children list */
2902 g_free(child
->name
);
2906 typedef struct BdrvAttachChildCommonState
{
2908 AioContext
*old_parent_ctx
;
2909 AioContext
*old_child_ctx
;
2910 } BdrvAttachChildCommonState
;
2912 static void bdrv_attach_child_common_abort(void *opaque
)
2914 BdrvAttachChildCommonState
*s
= opaque
;
2915 BlockDriverState
*bs
= s
->child
->bs
;
2917 GLOBAL_STATE_CODE();
2918 bdrv_replace_child_noperm(s
->child
, NULL
);
2920 if (bdrv_get_aio_context(bs
) != s
->old_child_ctx
) {
2921 bdrv_try_change_aio_context(bs
, s
->old_child_ctx
, NULL
, &error_abort
);
2924 if (bdrv_child_get_parent_aio_context(s
->child
) != s
->old_parent_ctx
) {
2926 GHashTable
*visited
;
2931 /* No need to visit `child`, because it has been detached already */
2932 visited
= g_hash_table_new(NULL
, NULL
);
2933 ret
= s
->child
->klass
->change_aio_ctx(s
->child
, s
->old_parent_ctx
,
2934 visited
, tran
, &error_abort
);
2935 g_hash_table_destroy(visited
);
2937 /* transaction is supposed to always succeed */
2938 assert(ret
== true);
2943 bdrv_child_free(s
->child
);
2946 static TransactionActionDrv bdrv_attach_child_common_drv
= {
2947 .abort
= bdrv_attach_child_common_abort
,
2952 * Common part of attaching bdrv child to bs or to blk or to job
2954 * Function doesn't update permissions, caller is responsible for this.
2956 * Returns new created child.
2958 static BdrvChild
*bdrv_attach_child_common(BlockDriverState
*child_bs
,
2959 const char *child_name
,
2960 const BdrvChildClass
*child_class
,
2961 BdrvChildRole child_role
,
2962 uint64_t perm
, uint64_t shared_perm
,
2964 Transaction
*tran
, Error
**errp
)
2966 BdrvChild
*new_child
;
2967 AioContext
*parent_ctx
;
2968 AioContext
*child_ctx
= bdrv_get_aio_context(child_bs
);
2970 assert(child_class
->get_parent_desc
);
2971 GLOBAL_STATE_CODE();
2973 new_child
= g_new(BdrvChild
, 1);
2974 *new_child
= (BdrvChild
) {
2976 .name
= g_strdup(child_name
),
2977 .klass
= child_class
,
2980 .shared_perm
= shared_perm
,
2985 * If the AioContexts don't match, first try to move the subtree of
2986 * child_bs into the AioContext of the new parent. If this doesn't work,
2987 * try moving the parent into the AioContext of child_bs instead.
2989 parent_ctx
= bdrv_child_get_parent_aio_context(new_child
);
2990 if (child_ctx
!= parent_ctx
) {
2991 Error
*local_err
= NULL
;
2992 int ret
= bdrv_try_change_aio_context(child_bs
, parent_ctx
, NULL
,
2995 if (ret
< 0 && child_class
->change_aio_ctx
) {
2996 Transaction
*tran
= tran_new();
2997 GHashTable
*visited
= g_hash_table_new(NULL
, NULL
);
3000 g_hash_table_add(visited
, new_child
);
3001 ret_child
= child_class
->change_aio_ctx(new_child
, child_ctx
,
3002 visited
, tran
, NULL
);
3003 if (ret_child
== true) {
3004 error_free(local_err
);
3007 tran_finalize(tran
, ret_child
== true ? 0 : -1);
3008 g_hash_table_destroy(visited
);
3012 error_propagate(errp
, local_err
);
3013 bdrv_child_free(new_child
);
3019 bdrv_replace_child_noperm(new_child
, child_bs
);
3021 BdrvAttachChildCommonState
*s
= g_new(BdrvAttachChildCommonState
, 1);
3022 *s
= (BdrvAttachChildCommonState
) {
3024 .old_parent_ctx
= parent_ctx
,
3025 .old_child_ctx
= child_ctx
,
3027 tran_add(tran
, &bdrv_attach_child_common_drv
, s
);
3033 * Function doesn't update permissions, caller is responsible for this.
3035 static BdrvChild
*bdrv_attach_child_noperm(BlockDriverState
*parent_bs
,
3036 BlockDriverState
*child_bs
,
3037 const char *child_name
,
3038 const BdrvChildClass
*child_class
,
3039 BdrvChildRole child_role
,
3043 uint64_t perm
, shared_perm
;
3045 assert(parent_bs
->drv
);
3046 GLOBAL_STATE_CODE();
3048 if (bdrv_recurse_has_child(child_bs
, parent_bs
)) {
3049 error_setg(errp
, "Making '%s' a %s child of '%s' would create a cycle",
3050 child_bs
->node_name
, child_name
, parent_bs
->node_name
);
3054 bdrv_get_cumulative_perm(parent_bs
, &perm
, &shared_perm
);
3055 bdrv_child_perm(parent_bs
, child_bs
, NULL
, child_role
, NULL
,
3056 perm
, shared_perm
, &perm
, &shared_perm
);
3058 return bdrv_attach_child_common(child_bs
, child_name
, child_class
,
3059 child_role
, perm
, shared_perm
, parent_bs
,
3063 static void bdrv_detach_child(BdrvChild
*child
)
3065 BlockDriverState
*old_bs
= child
->bs
;
3067 GLOBAL_STATE_CODE();
3068 bdrv_replace_child_noperm(child
, NULL
);
3069 bdrv_child_free(child
);
3073 * Update permissions for old node. We're just taking a parent away, so
3074 * we're loosening restrictions. Errors of permission update are not
3075 * fatal in this case, ignore them.
3077 bdrv_refresh_perms(old_bs
, NULL
);
3080 * When the parent requiring a non-default AioContext is removed, the
3081 * node moves back to the main AioContext
3083 bdrv_try_change_aio_context(old_bs
, qemu_get_aio_context(), NULL
, NULL
);
3088 * This function steals the reference to child_bs from the caller.
3089 * That reference is later dropped by bdrv_root_unref_child().
3091 * On failure NULL is returned, errp is set and the reference to
3092 * child_bs is also dropped.
3094 * The caller must hold the AioContext lock @child_bs, but not that of @ctx
3095 * (unless @child_bs is already in @ctx).
3097 BdrvChild
*bdrv_root_attach_child(BlockDriverState
*child_bs
,
3098 const char *child_name
,
3099 const BdrvChildClass
*child_class
,
3100 BdrvChildRole child_role
,
3101 uint64_t perm
, uint64_t shared_perm
,
3102 void *opaque
, Error
**errp
)
3106 Transaction
*tran
= tran_new();
3108 GLOBAL_STATE_CODE();
3110 child
= bdrv_attach_child_common(child_bs
, child_name
, child_class
,
3111 child_role
, perm
, shared_perm
, opaque
,
3118 ret
= bdrv_refresh_perms(child_bs
, errp
);
3121 tran_finalize(tran
, ret
);
3123 bdrv_unref(child_bs
);
3125 return ret
< 0 ? NULL
: child
;
3129 * This function transfers the reference to child_bs from the caller
3130 * to parent_bs. That reference is later dropped by parent_bs on
3131 * bdrv_close() or if someone calls bdrv_unref_child().
3133 * On failure NULL is returned, errp is set and the reference to
3134 * child_bs is also dropped.
3136 * If @parent_bs and @child_bs are in different AioContexts, the caller must
3137 * hold the AioContext lock for @child_bs, but not for @parent_bs.
3139 BdrvChild
*bdrv_attach_child(BlockDriverState
*parent_bs
,
3140 BlockDriverState
*child_bs
,
3141 const char *child_name
,
3142 const BdrvChildClass
*child_class
,
3143 BdrvChildRole child_role
,
3148 Transaction
*tran
= tran_new();
3150 GLOBAL_STATE_CODE();
3152 child
= bdrv_attach_child_noperm(parent_bs
, child_bs
, child_name
,
3153 child_class
, child_role
, tran
, errp
);
3159 ret
= bdrv_refresh_perms(parent_bs
, errp
);
3165 tran_finalize(tran
, ret
);
3167 bdrv_unref(child_bs
);
3169 return ret
< 0 ? NULL
: child
;
3172 /* Callers must ensure that child->frozen is false. */
3173 void bdrv_root_unref_child(BdrvChild
*child
)
3175 BlockDriverState
*child_bs
;
3177 GLOBAL_STATE_CODE();
3179 child_bs
= child
->bs
;
3180 bdrv_detach_child(child
);
3181 bdrv_unref(child_bs
);
3184 typedef struct BdrvSetInheritsFrom
{
3185 BlockDriverState
*bs
;
3186 BlockDriverState
*old_inherits_from
;
3187 } BdrvSetInheritsFrom
;
3189 static void bdrv_set_inherits_from_abort(void *opaque
)
3191 BdrvSetInheritsFrom
*s
= opaque
;
3193 s
->bs
->inherits_from
= s
->old_inherits_from
;
3196 static TransactionActionDrv bdrv_set_inherits_from_drv
= {
3197 .abort
= bdrv_set_inherits_from_abort
,
3201 /* @tran is allowed to be NULL. In this case no rollback is possible */
3202 static void bdrv_set_inherits_from(BlockDriverState
*bs
,
3203 BlockDriverState
*new_inherits_from
,
3207 BdrvSetInheritsFrom
*s
= g_new(BdrvSetInheritsFrom
, 1);
3209 *s
= (BdrvSetInheritsFrom
) {
3211 .old_inherits_from
= bs
->inherits_from
,
3214 tran_add(tran
, &bdrv_set_inherits_from_drv
, s
);
3217 bs
->inherits_from
= new_inherits_from
;
3221 * Clear all inherits_from pointers from children and grandchildren of
3222 * @root that point to @root, where necessary.
3223 * @tran is allowed to be NULL. In this case no rollback is possible
3225 static void bdrv_unset_inherits_from(BlockDriverState
*root
, BdrvChild
*child
,
3230 if (child
->bs
->inherits_from
== root
) {
3232 * Remove inherits_from only when the last reference between root and
3233 * child->bs goes away.
3235 QLIST_FOREACH(c
, &root
->children
, next
) {
3236 if (c
!= child
&& c
->bs
== child
->bs
) {
3241 bdrv_set_inherits_from(child
->bs
, NULL
, tran
);
3245 QLIST_FOREACH(c
, &child
->bs
->children
, next
) {
3246 bdrv_unset_inherits_from(root
, c
, tran
);
3250 /* Callers must ensure that child->frozen is false. */
3251 void bdrv_unref_child(BlockDriverState
*parent
, BdrvChild
*child
)
3253 GLOBAL_STATE_CODE();
3254 if (child
== NULL
) {
3258 bdrv_unset_inherits_from(parent
, child
, NULL
);
3259 bdrv_root_unref_child(child
);
3263 static void bdrv_parent_cb_change_media(BlockDriverState
*bs
, bool load
)
3266 GLOBAL_STATE_CODE();
3267 QLIST_FOREACH(c
, &bs
->parents
, next_parent
) {
3268 if (c
->klass
->change_media
) {
3269 c
->klass
->change_media(c
, load
);
3274 /* Return true if you can reach parent going through child->inherits_from
3275 * recursively. If parent or child are NULL, return false */
3276 static bool bdrv_inherits_from_recursive(BlockDriverState
*child
,
3277 BlockDriverState
*parent
)
3279 while (child
&& child
!= parent
) {
3280 child
= child
->inherits_from
;
3283 return child
!= NULL
;
3287 * Return the BdrvChildRole for @bs's backing child. bs->backing is
3288 * mostly used for COW backing children (role = COW), but also for
3289 * filtered children (role = FILTERED | PRIMARY).
3291 static BdrvChildRole
bdrv_backing_role(BlockDriverState
*bs
)
3293 if (bs
->drv
&& bs
->drv
->is_filter
) {
3294 return BDRV_CHILD_FILTERED
| BDRV_CHILD_PRIMARY
;
3296 return BDRV_CHILD_COW
;
3301 * Sets the bs->backing or bs->file link of a BDS. A new reference is created;
3302 * callers which don't need their own reference any more must call bdrv_unref().
3304 * Function doesn't update permissions, caller is responsible for this.
3306 static int bdrv_set_file_or_backing_noperm(BlockDriverState
*parent_bs
,
3307 BlockDriverState
*child_bs
,
3309 Transaction
*tran
, Error
**errp
)
3311 bool update_inherits_from
=
3312 bdrv_inherits_from_recursive(child_bs
, parent_bs
);
3313 BdrvChild
*child
= is_backing
? parent_bs
->backing
: parent_bs
->file
;
3316 GLOBAL_STATE_CODE();
3318 if (!parent_bs
->drv
) {
3320 * Node without drv is an object without a class :/. TODO: finally fix
3321 * qcow2 driver to never clear bs->drv and implement format corruption
3322 * handling in other way.
3324 error_setg(errp
, "Node corrupted");
3328 if (child
&& child
->frozen
) {
3329 error_setg(errp
, "Cannot change frozen '%s' link from '%s' to '%s'",
3330 child
->name
, parent_bs
->node_name
, child
->bs
->node_name
);
3334 if (is_backing
&& !parent_bs
->drv
->is_filter
&&
3335 !parent_bs
->drv
->supports_backing
)
3337 error_setg(errp
, "Driver '%s' of node '%s' does not support backing "
3338 "files", parent_bs
->drv
->format_name
, parent_bs
->node_name
);
3342 if (parent_bs
->drv
->is_filter
) {
3343 role
= BDRV_CHILD_FILTERED
| BDRV_CHILD_PRIMARY
;
3344 } else if (is_backing
) {
3345 role
= BDRV_CHILD_COW
;
3348 * We only can use same role as it is in existing child. We don't have
3349 * infrastructure to determine role of file child in generic way
3352 error_setg(errp
, "Cannot set file child to format node without "
3360 bdrv_unset_inherits_from(parent_bs
, child
, tran
);
3361 bdrv_remove_child(child
, tran
);
3368 child
= bdrv_attach_child_noperm(parent_bs
, child_bs
,
3369 is_backing
? "backing" : "file",
3370 &child_of_bds
, role
,
3378 * If inherits_from pointed recursively to bs then let's update it to
3379 * point directly to bs (else it will become NULL).
3381 if (update_inherits_from
) {
3382 bdrv_set_inherits_from(child_bs
, parent_bs
, tran
);
3386 bdrv_refresh_limits(parent_bs
, tran
, NULL
);
3391 static int bdrv_set_backing_noperm(BlockDriverState
*bs
,
3392 BlockDriverState
*backing_hd
,
3393 Transaction
*tran
, Error
**errp
)
3395 GLOBAL_STATE_CODE();
3396 return bdrv_set_file_or_backing_noperm(bs
, backing_hd
, true, tran
, errp
);
3399 int bdrv_set_backing_hd(BlockDriverState
*bs
, BlockDriverState
*backing_hd
,
3403 Transaction
*tran
= tran_new();
3405 GLOBAL_STATE_CODE();
3406 bdrv_drained_begin(bs
);
3408 ret
= bdrv_set_backing_noperm(bs
, backing_hd
, tran
, errp
);
3413 ret
= bdrv_refresh_perms(bs
, errp
);
3415 tran_finalize(tran
, ret
);
3417 bdrv_drained_end(bs
);
3423 * Opens the backing file for a BlockDriverState if not yet open
3425 * bdref_key specifies the key for the image's BlockdevRef in the options QDict.
3426 * That QDict has to be flattened; therefore, if the BlockdevRef is a QDict
3427 * itself, all options starting with "${bdref_key}." are considered part of the
3430 * TODO Can this be unified with bdrv_open_image()?
3432 int bdrv_open_backing_file(BlockDriverState
*bs
, QDict
*parent_options
,
3433 const char *bdref_key
, Error
**errp
)
3435 char *backing_filename
= NULL
;
3436 char *bdref_key_dot
;
3437 const char *reference
= NULL
;
3439 bool implicit_backing
= false;
3440 BlockDriverState
*backing_hd
;
3442 QDict
*tmp_parent_options
= NULL
;
3443 Error
*local_err
= NULL
;
3445 GLOBAL_STATE_CODE();
3447 if (bs
->backing
!= NULL
) {
3451 /* NULL means an empty set of options */
3452 if (parent_options
== NULL
) {
3453 tmp_parent_options
= qdict_new();
3454 parent_options
= tmp_parent_options
;
3457 bs
->open_flags
&= ~BDRV_O_NO_BACKING
;
3459 bdref_key_dot
= g_strdup_printf("%s.", bdref_key
);
3460 qdict_extract_subqdict(parent_options
, &options
, bdref_key_dot
);
3461 g_free(bdref_key_dot
);
3464 * Caution: while qdict_get_try_str() is fine, getting non-string
3465 * types would require more care. When @parent_options come from
3466 * -blockdev or blockdev_add, its members are typed according to
3467 * the QAPI schema, but when they come from -drive, they're all
3470 reference
= qdict_get_try_str(parent_options
, bdref_key
);
3471 if (reference
|| qdict_haskey(options
, "file.filename")) {
3472 /* keep backing_filename NULL */
3473 } else if (bs
->backing_file
[0] == '\0' && qdict_size(options
) == 0) {
3474 qobject_unref(options
);
3477 if (qdict_size(options
) == 0) {
3478 /* If the user specifies options that do not modify the
3479 * backing file's behavior, we might still consider it the
3480 * implicit backing file. But it's easier this way, and
3481 * just specifying some of the backing BDS's options is
3482 * only possible with -drive anyway (otherwise the QAPI
3483 * schema forces the user to specify everything). */
3484 implicit_backing
= !strcmp(bs
->auto_backing_file
, bs
->backing_file
);
3487 backing_filename
= bdrv_get_full_backing_filename(bs
, &local_err
);
3490 error_propagate(errp
, local_err
);
3491 qobject_unref(options
);
3496 if (!bs
->drv
|| !bs
->drv
->supports_backing
) {
3498 error_setg(errp
, "Driver doesn't support backing files");
3499 qobject_unref(options
);
3504 bs
->backing_format
[0] != '\0' && !qdict_haskey(options
, "driver")) {
3505 qdict_put_str(options
, "driver", bs
->backing_format
);
3508 backing_hd
= bdrv_open_inherit(backing_filename
, reference
, options
, 0, bs
,
3509 &child_of_bds
, bdrv_backing_role(bs
), errp
);
3511 bs
->open_flags
|= BDRV_O_NO_BACKING
;
3512 error_prepend(errp
, "Could not open backing file: ");
3517 if (implicit_backing
) {
3518 bdrv_refresh_filename(backing_hd
);
3519 pstrcpy(bs
->auto_backing_file
, sizeof(bs
->auto_backing_file
),
3520 backing_hd
->filename
);
3523 /* Hook up the backing file link; drop our reference, bs owns the
3524 * backing_hd reference now */
3525 ret
= bdrv_set_backing_hd(bs
, backing_hd
, errp
);
3526 bdrv_unref(backing_hd
);
3531 qdict_del(parent_options
, bdref_key
);
3534 g_free(backing_filename
);
3535 qobject_unref(tmp_parent_options
);
3539 static BlockDriverState
*
3540 bdrv_open_child_bs(const char *filename
, QDict
*options
, const char *bdref_key
,
3541 BlockDriverState
*parent
, const BdrvChildClass
*child_class
,
3542 BdrvChildRole child_role
, bool allow_none
, Error
**errp
)
3544 BlockDriverState
*bs
= NULL
;
3545 QDict
*image_options
;
3546 char *bdref_key_dot
;
3547 const char *reference
;
3549 assert(child_class
!= NULL
);
3551 bdref_key_dot
= g_strdup_printf("%s.", bdref_key
);
3552 qdict_extract_subqdict(options
, &image_options
, bdref_key_dot
);
3553 g_free(bdref_key_dot
);
3556 * Caution: while qdict_get_try_str() is fine, getting non-string
3557 * types would require more care. When @options come from
3558 * -blockdev or blockdev_add, its members are typed according to
3559 * the QAPI schema, but when they come from -drive, they're all
3562 reference
= qdict_get_try_str(options
, bdref_key
);
3563 if (!filename
&& !reference
&& !qdict_size(image_options
)) {
3565 error_setg(errp
, "A block device must be specified for \"%s\"",
3568 qobject_unref(image_options
);
3572 bs
= bdrv_open_inherit(filename
, reference
, image_options
, 0,
3573 parent
, child_class
, child_role
, errp
);
3579 qdict_del(options
, bdref_key
);
3584 * Opens a disk image whose options are given as BlockdevRef in another block
3587 * If allow_none is true, no image will be opened if filename is false and no
3588 * BlockdevRef is given. NULL will be returned, but errp remains unset.
3590 * bdrev_key specifies the key for the image's BlockdevRef in the options QDict.
3591 * That QDict has to be flattened; therefore, if the BlockdevRef is a QDict
3592 * itself, all options starting with "${bdref_key}." are considered part of the
3595 * The BlockdevRef will be removed from the options QDict.
3597 BdrvChild
*bdrv_open_child(const char *filename
,
3598 QDict
*options
, const char *bdref_key
,
3599 BlockDriverState
*parent
,
3600 const BdrvChildClass
*child_class
,
3601 BdrvChildRole child_role
,
3602 bool allow_none
, Error
**errp
)
3604 BlockDriverState
*bs
;
3606 GLOBAL_STATE_CODE();
3608 bs
= bdrv_open_child_bs(filename
, options
, bdref_key
, parent
, child_class
,
3609 child_role
, allow_none
, errp
);
3614 return bdrv_attach_child(parent
, bs
, bdref_key
, child_class
, child_role
,
3619 * Wrapper on bdrv_open_child() for most popular case: open primary child of bs.
3621 int bdrv_open_file_child(const char *filename
,
3622 QDict
*options
, const char *bdref_key
,
3623 BlockDriverState
*parent
, Error
**errp
)
3627 /* commit_top and mirror_top don't use this function */
3628 assert(!parent
->drv
->filtered_child_is_backing
);
3629 role
= parent
->drv
->is_filter
?
3630 (BDRV_CHILD_FILTERED
| BDRV_CHILD_PRIMARY
) : BDRV_CHILD_IMAGE
;
3632 if (!bdrv_open_child(filename
, options
, bdref_key
, parent
,
3633 &child_of_bds
, role
, false, errp
))
3642 * TODO Future callers may need to specify parent/child_class in order for
3643 * option inheritance to work. Existing callers use it for the root node.
3645 BlockDriverState
*bdrv_open_blockdev_ref(BlockdevRef
*ref
, Error
**errp
)
3647 BlockDriverState
*bs
= NULL
;
3648 QObject
*obj
= NULL
;
3649 QDict
*qdict
= NULL
;
3650 const char *reference
= NULL
;
3653 GLOBAL_STATE_CODE();
3655 if (ref
->type
== QTYPE_QSTRING
) {
3656 reference
= ref
->u
.reference
;
3658 BlockdevOptions
*options
= &ref
->u
.definition
;
3659 assert(ref
->type
== QTYPE_QDICT
);
3661 v
= qobject_output_visitor_new(&obj
);
3662 visit_type_BlockdevOptions(v
, NULL
, &options
, &error_abort
);
3663 visit_complete(v
, &obj
);
3665 qdict
= qobject_to(QDict
, obj
);
3666 qdict_flatten(qdict
);
3668 /* bdrv_open_inherit() defaults to the values in bdrv_flags (for
3669 * compatibility with other callers) rather than what we want as the
3670 * real defaults. Apply the defaults here instead. */
3671 qdict_set_default_str(qdict
, BDRV_OPT_CACHE_DIRECT
, "off");
3672 qdict_set_default_str(qdict
, BDRV_OPT_CACHE_NO_FLUSH
, "off");
3673 qdict_set_default_str(qdict
, BDRV_OPT_READ_ONLY
, "off");
3674 qdict_set_default_str(qdict
, BDRV_OPT_AUTO_READ_ONLY
, "off");
3678 bs
= bdrv_open_inherit(NULL
, reference
, qdict
, 0, NULL
, NULL
, 0, errp
);
3685 static BlockDriverState
*bdrv_append_temp_snapshot(BlockDriverState
*bs
,
3687 QDict
*snapshot_options
,
3690 g_autofree
char *tmp_filename
= NULL
;
3692 QemuOpts
*opts
= NULL
;
3693 BlockDriverState
*bs_snapshot
= NULL
;
3696 GLOBAL_STATE_CODE();
3698 /* if snapshot, we create a temporary backing file and open it
3699 instead of opening 'filename' directly */
3701 /* Get the required size from the image */
3702 total_size
= bdrv_getlength(bs
);
3703 if (total_size
< 0) {
3704 error_setg_errno(errp
, -total_size
, "Could not get image size");
3708 /* Create the temporary image */
3709 tmp_filename
= create_tmp_file(errp
);
3710 if (!tmp_filename
) {
3714 opts
= qemu_opts_create(bdrv_qcow2
.create_opts
, NULL
, 0,
3716 qemu_opt_set_number(opts
, BLOCK_OPT_SIZE
, total_size
, &error_abort
);
3717 ret
= bdrv_create(&bdrv_qcow2
, tmp_filename
, opts
, errp
);
3718 qemu_opts_del(opts
);
3720 error_prepend(errp
, "Could not create temporary overlay '%s': ",
3725 /* Prepare options QDict for the temporary file */
3726 qdict_put_str(snapshot_options
, "file.driver", "file");
3727 qdict_put_str(snapshot_options
, "file.filename", tmp_filename
);
3728 qdict_put_str(snapshot_options
, "driver", "qcow2");
3730 bs_snapshot
= bdrv_open(NULL
, NULL
, snapshot_options
, flags
, errp
);
3731 snapshot_options
= NULL
;
3736 ret
= bdrv_append(bs_snapshot
, bs
, errp
);
3743 qobject_unref(snapshot_options
);
3748 * Opens a disk image (raw, qcow2, vmdk, ...)
3750 * options is a QDict of options to pass to the block drivers, or NULL for an
3751 * empty set of options. The reference to the QDict belongs to the block layer
3752 * after the call (even on failure), so if the caller intends to reuse the
3753 * dictionary, it needs to use qobject_ref() before calling bdrv_open.
3755 * If *pbs is NULL, a new BDS will be created with a pointer to it stored there.
3756 * If it is not NULL, the referenced BDS will be reused.
3758 * The reference parameter may be used to specify an existing block device which
3759 * should be opened. If specified, neither options nor a filename may be given,
3760 * nor can an existing BDS be reused (that is, *pbs has to be NULL).
3762 static BlockDriverState
*bdrv_open_inherit(const char *filename
,
3763 const char *reference
,
3764 QDict
*options
, int flags
,
3765 BlockDriverState
*parent
,
3766 const BdrvChildClass
*child_class
,
3767 BdrvChildRole child_role
,
3771 BlockBackend
*file
= NULL
;
3772 BlockDriverState
*bs
;
3773 BlockDriver
*drv
= NULL
;
3775 const char *drvname
;
3776 const char *backing
;
3777 Error
*local_err
= NULL
;
3778 QDict
*snapshot_options
= NULL
;
3779 int snapshot_flags
= 0;
3781 assert(!child_class
|| !flags
);
3782 assert(!child_class
== !parent
);
3783 GLOBAL_STATE_CODE();
3786 bool options_non_empty
= options
? qdict_size(options
) : false;
3787 qobject_unref(options
);
3789 if (filename
|| options_non_empty
) {
3790 error_setg(errp
, "Cannot reference an existing block device with "
3791 "additional options or a new filename");
3795 bs
= bdrv_lookup_bs(reference
, reference
, errp
);
3806 /* NULL means an empty set of options */
3807 if (options
== NULL
) {
3808 options
= qdict_new();
3811 /* json: syntax counts as explicit options, as if in the QDict */
3812 parse_json_protocol(options
, &filename
, &local_err
);
3817 bs
->explicit_options
= qdict_clone_shallow(options
);
3820 bool parent_is_format
;
3823 parent_is_format
= parent
->drv
->is_format
;
3826 * parent->drv is not set yet because this node is opened for
3827 * (potential) format probing. That means that @parent is going
3828 * to be a format node.
3830 parent_is_format
= true;
3833 bs
->inherits_from
= parent
;
3834 child_class
->inherit_options(child_role
, parent_is_format
,
3836 parent
->open_flags
, parent
->options
);
3839 ret
= bdrv_fill_options(&options
, filename
, &flags
, &local_err
);
3845 * Set the BDRV_O_RDWR and BDRV_O_ALLOW_RDWR flags.
3846 * Caution: getting a boolean member of @options requires care.
3847 * When @options come from -blockdev or blockdev_add, members are
3848 * typed according to the QAPI schema, but when they come from
3849 * -drive, they're all QString.
3851 if (g_strcmp0(qdict_get_try_str(options
, BDRV_OPT_READ_ONLY
), "on") &&
3852 !qdict_get_try_bool(options
, BDRV_OPT_READ_ONLY
, false)) {
3853 flags
|= (BDRV_O_RDWR
| BDRV_O_ALLOW_RDWR
);
3855 flags
&= ~BDRV_O_RDWR
;
3858 if (flags
& BDRV_O_SNAPSHOT
) {
3859 snapshot_options
= qdict_new();
3860 bdrv_temp_snapshot_options(&snapshot_flags
, snapshot_options
,
3862 /* Let bdrv_backing_options() override "read-only" */
3863 qdict_del(options
, BDRV_OPT_READ_ONLY
);
3864 bdrv_inherited_options(BDRV_CHILD_COW
, true,
3865 &flags
, options
, flags
, options
);
3868 bs
->open_flags
= flags
;
3869 bs
->options
= options
;
3870 options
= qdict_clone_shallow(options
);
3872 /* Find the right image format driver */
3873 /* See cautionary note on accessing @options above */
3874 drvname
= qdict_get_try_str(options
, "driver");
3876 drv
= bdrv_find_format(drvname
);
3878 error_setg(errp
, "Unknown driver: '%s'", drvname
);
3883 assert(drvname
|| !(flags
& BDRV_O_PROTOCOL
));
3885 /* See cautionary note on accessing @options above */
3886 backing
= qdict_get_try_str(options
, "backing");
3887 if (qobject_to(QNull
, qdict_get(options
, "backing")) != NULL
||
3888 (backing
&& *backing
== '\0'))
3891 warn_report("Use of \"backing\": \"\" is deprecated; "
3892 "use \"backing\": null instead");
3894 flags
|= BDRV_O_NO_BACKING
;
3895 qdict_del(bs
->explicit_options
, "backing");
3896 qdict_del(bs
->options
, "backing");
3897 qdict_del(options
, "backing");
3900 /* Open image file without format layer. This BlockBackend is only used for
3901 * probing, the block drivers will do their own bdrv_open_child() for the
3902 * same BDS, which is why we put the node name back into options. */
3903 if ((flags
& BDRV_O_PROTOCOL
) == 0) {
3904 BlockDriverState
*file_bs
;
3906 file_bs
= bdrv_open_child_bs(filename
, options
, "file", bs
,
3907 &child_of_bds
, BDRV_CHILD_IMAGE
,
3912 if (file_bs
!= NULL
) {
3913 /* Not requesting BLK_PERM_CONSISTENT_READ because we're only
3914 * looking at the header to guess the image format. This works even
3915 * in cases where a guest would not see a consistent state. */
3916 file
= blk_new(bdrv_get_aio_context(file_bs
), 0, BLK_PERM_ALL
);
3917 blk_insert_bs(file
, file_bs
, &local_err
);
3918 bdrv_unref(file_bs
);
3923 qdict_put_str(options
, "file", bdrv_get_node_name(file_bs
));
3927 /* Image format probing */
3930 ret
= find_image_format(file
, filename
, &drv
, &local_err
);
3935 * This option update would logically belong in bdrv_fill_options(),
3936 * but we first need to open bs->file for the probing to work, while
3937 * opening bs->file already requires the (mostly) final set of options
3938 * so that cache mode etc. can be inherited.
3940 * Adding the driver later is somewhat ugly, but it's not an option
3941 * that would ever be inherited, so it's correct. We just need to make
3942 * sure to update both bs->options (which has the full effective
3943 * options for bs) and options (which has file.* already removed).
3945 qdict_put_str(bs
->options
, "driver", drv
->format_name
);
3946 qdict_put_str(options
, "driver", drv
->format_name
);
3948 error_setg(errp
, "Must specify either driver or file");
3952 /* BDRV_O_PROTOCOL must be set iff a protocol BDS is about to be created */
3953 assert(!!(flags
& BDRV_O_PROTOCOL
) == !!drv
->bdrv_file_open
);
3954 /* file must be NULL if a protocol BDS is about to be created
3955 * (the inverse results in an error message from bdrv_open_common()) */
3956 assert(!(flags
& BDRV_O_PROTOCOL
) || !file
);
3958 /* Open the image */
3959 ret
= bdrv_open_common(bs
, file
, options
, &local_err
);
3969 /* If there is a backing file, use it */
3970 if ((flags
& BDRV_O_NO_BACKING
) == 0) {
3971 ret
= bdrv_open_backing_file(bs
, options
, "backing", &local_err
);
3973 goto close_and_fail
;
3977 /* Remove all children options and references
3978 * from bs->options and bs->explicit_options */
3979 QLIST_FOREACH(child
, &bs
->children
, next
) {
3980 char *child_key_dot
;
3981 child_key_dot
= g_strdup_printf("%s.", child
->name
);
3982 qdict_extract_subqdict(bs
->explicit_options
, NULL
, child_key_dot
);
3983 qdict_extract_subqdict(bs
->options
, NULL
, child_key_dot
);
3984 qdict_del(bs
->explicit_options
, child
->name
);
3985 qdict_del(bs
->options
, child
->name
);
3986 g_free(child_key_dot
);
3989 /* Check if any unknown options were used */
3990 if (qdict_size(options
) != 0) {
3991 const QDictEntry
*entry
= qdict_first(options
);
3992 if (flags
& BDRV_O_PROTOCOL
) {
3993 error_setg(errp
, "Block protocol '%s' doesn't support the option "
3994 "'%s'", drv
->format_name
, entry
->key
);
3997 "Block format '%s' does not support the option '%s'",
3998 drv
->format_name
, entry
->key
);
4001 goto close_and_fail
;
4004 bdrv_parent_cb_change_media(bs
, true);
4006 qobject_unref(options
);
4009 /* For snapshot=on, create a temporary qcow2 overlay. bs points to the
4010 * temporary snapshot afterwards. */
4011 if (snapshot_flags
) {
4012 BlockDriverState
*snapshot_bs
;
4013 snapshot_bs
= bdrv_append_temp_snapshot(bs
, snapshot_flags
,
4014 snapshot_options
, &local_err
);
4015 snapshot_options
= NULL
;
4017 goto close_and_fail
;
4019 /* We are not going to return bs but the overlay on top of it
4020 * (snapshot_bs); thus, we have to drop the strong reference to bs
4021 * (which we obtained by calling bdrv_new()). bs will not be deleted,
4022 * though, because the overlay still has a reference to it. */
4031 qobject_unref(snapshot_options
);
4032 qobject_unref(bs
->explicit_options
);
4033 qobject_unref(bs
->options
);
4034 qobject_unref(options
);
4036 bs
->explicit_options
= NULL
;
4038 error_propagate(errp
, local_err
);
4043 qobject_unref(snapshot_options
);
4044 qobject_unref(options
);
4045 error_propagate(errp
, local_err
);
4049 BlockDriverState
*bdrv_open(const char *filename
, const char *reference
,
4050 QDict
*options
, int flags
, Error
**errp
)
4052 GLOBAL_STATE_CODE();
4054 return bdrv_open_inherit(filename
, reference
, options
, flags
, NULL
,
4058 /* Return true if the NULL-terminated @list contains @str */
4059 static bool is_str_in_list(const char *str
, const char *const *list
)
4063 for (i
= 0; list
[i
] != NULL
; i
++) {
4064 if (!strcmp(str
, list
[i
])) {
4073 * Check that every option set in @bs->options is also set in
4076 * Options listed in the common_options list and in
4077 * @bs->drv->mutable_opts are skipped.
4079 * Return 0 on success, otherwise return -EINVAL and set @errp.
4081 static int bdrv_reset_options_allowed(BlockDriverState
*bs
,
4082 const QDict
*new_opts
, Error
**errp
)
4084 const QDictEntry
*e
;
4085 /* These options are common to all block drivers and are handled
4086 * in bdrv_reopen_prepare() so they can be left out of @new_opts */
4087 const char *const common_options
[] = {
4088 "node-name", "discard", "cache.direct", "cache.no-flush",
4089 "read-only", "auto-read-only", "detect-zeroes", NULL
4092 for (e
= qdict_first(bs
->options
); e
; e
= qdict_next(bs
->options
, e
)) {
4093 if (!qdict_haskey(new_opts
, e
->key
) &&
4094 !is_str_in_list(e
->key
, common_options
) &&
4095 !is_str_in_list(e
->key
, bs
->drv
->mutable_opts
)) {
4096 error_setg(errp
, "Option '%s' cannot be reset "
4097 "to its default value", e
->key
);
4106 * Returns true if @child can be reached recursively from @bs
4108 static bool bdrv_recurse_has_child(BlockDriverState
*bs
,
4109 BlockDriverState
*child
)
4117 QLIST_FOREACH(c
, &bs
->children
, next
) {
4118 if (bdrv_recurse_has_child(c
->bs
, child
)) {
4127 * Adds a BlockDriverState to a simple queue for an atomic, transactional
4128 * reopen of multiple devices.
4130 * bs_queue can either be an existing BlockReopenQueue that has had QTAILQ_INIT
4131 * already performed, or alternatively may be NULL a new BlockReopenQueue will
4132 * be created and initialized. This newly created BlockReopenQueue should be
4133 * passed back in for subsequent calls that are intended to be of the same
4136 * bs is the BlockDriverState to add to the reopen queue.
4138 * options contains the changed options for the associated bs
4139 * (the BlockReopenQueue takes ownership)
4141 * flags contains the open flags for the associated bs
4143 * returns a pointer to bs_queue, which is either the newly allocated
4144 * bs_queue, or the existing bs_queue being used.
4146 * bs must be drained between bdrv_reopen_queue() and bdrv_reopen_multiple().
4148 static BlockReopenQueue
*bdrv_reopen_queue_child(BlockReopenQueue
*bs_queue
,
4149 BlockDriverState
*bs
,
4151 const BdrvChildClass
*klass
,
4153 bool parent_is_format
,
4154 QDict
*parent_options
,
4160 BlockReopenQueueEntry
*bs_entry
;
4162 QDict
*old_options
, *explicit_options
, *options_copy
;
4166 /* Make sure that the caller remembered to use a drained section. This is
4167 * important to avoid graph changes between the recursive queuing here and
4168 * bdrv_reopen_multiple(). */
4169 assert(bs
->quiesce_counter
> 0);
4170 GLOBAL_STATE_CODE();
4172 if (bs_queue
== NULL
) {
4173 bs_queue
= g_new0(BlockReopenQueue
, 1);
4174 QTAILQ_INIT(bs_queue
);
4178 options
= qdict_new();
4181 /* Check if this BlockDriverState is already in the queue */
4182 QTAILQ_FOREACH(bs_entry
, bs_queue
, entry
) {
4183 if (bs
== bs_entry
->state
.bs
) {
4189 * Precedence of options:
4190 * 1. Explicitly passed in options (highest)
4191 * 2. Retained from explicitly set options of bs
4192 * 3. Inherited from parent node
4193 * 4. Retained from effective options of bs
4196 /* Old explicitly set values (don't overwrite by inherited value) */
4197 if (bs_entry
|| keep_old_opts
) {
4198 old_options
= qdict_clone_shallow(bs_entry
?
4199 bs_entry
->state
.explicit_options
:
4200 bs
->explicit_options
);
4201 bdrv_join_options(bs
, options
, old_options
);
4202 qobject_unref(old_options
);
4205 explicit_options
= qdict_clone_shallow(options
);
4207 /* Inherit from parent node */
4208 if (parent_options
) {
4210 klass
->inherit_options(role
, parent_is_format
, &flags
, options
,
4211 parent_flags
, parent_options
);
4213 flags
= bdrv_get_flags(bs
);
4216 if (keep_old_opts
) {
4217 /* Old values are used for options that aren't set yet */
4218 old_options
= qdict_clone_shallow(bs
->options
);
4219 bdrv_join_options(bs
, options
, old_options
);
4220 qobject_unref(old_options
);
4223 /* We have the final set of options so let's update the flags */
4224 options_copy
= qdict_clone_shallow(options
);
4225 opts
= qemu_opts_create(&bdrv_runtime_opts
, NULL
, 0, &error_abort
);
4226 qemu_opts_absorb_qdict(opts
, options_copy
, NULL
);
4227 update_flags_from_options(&flags
, opts
);
4228 qemu_opts_del(opts
);
4229 qobject_unref(options_copy
);
4231 /* bdrv_open_inherit() sets and clears some additional flags internally */
4232 flags
&= ~BDRV_O_PROTOCOL
;
4233 if (flags
& BDRV_O_RDWR
) {
4234 flags
|= BDRV_O_ALLOW_RDWR
;
4238 bs_entry
= g_new0(BlockReopenQueueEntry
, 1);
4239 QTAILQ_INSERT_TAIL(bs_queue
, bs_entry
, entry
);
4241 qobject_unref(bs_entry
->state
.options
);
4242 qobject_unref(bs_entry
->state
.explicit_options
);
4245 bs_entry
->state
.bs
= bs
;
4246 bs_entry
->state
.options
= options
;
4247 bs_entry
->state
.explicit_options
= explicit_options
;
4248 bs_entry
->state
.flags
= flags
;
4251 * If keep_old_opts is false then it means that unspecified
4252 * options must be reset to their original value. We don't allow
4253 * resetting 'backing' but we need to know if the option is
4254 * missing in order to decide if we have to return an error.
4256 if (!keep_old_opts
) {
4257 bs_entry
->state
.backing_missing
=
4258 !qdict_haskey(options
, "backing") &&
4259 !qdict_haskey(options
, "backing.driver");
4262 QLIST_FOREACH(child
, &bs
->children
, next
) {
4263 QDict
*new_child_options
= NULL
;
4264 bool child_keep_old
= keep_old_opts
;
4266 /* reopen can only change the options of block devices that were
4267 * implicitly created and inherited options. For other (referenced)
4268 * block devices, a syntax like "backing.foo" results in an error. */
4269 if (child
->bs
->inherits_from
!= bs
) {
4273 /* Check if the options contain a child reference */
4274 if (qdict_haskey(options
, child
->name
)) {
4275 const char *childref
= qdict_get_try_str(options
, child
->name
);
4277 * The current child must not be reopened if the child
4278 * reference is null or points to a different node.
4280 if (g_strcmp0(childref
, child
->bs
->node_name
)) {
4284 * If the child reference points to the current child then
4285 * reopen it with its existing set of options (note that
4286 * it can still inherit new options from the parent).
4288 child_keep_old
= true;
4290 /* Extract child options ("child-name.*") */
4291 char *child_key_dot
= g_strdup_printf("%s.", child
->name
);
4292 qdict_extract_subqdict(explicit_options
, NULL
, child_key_dot
);
4293 qdict_extract_subqdict(options
, &new_child_options
, child_key_dot
);
4294 g_free(child_key_dot
);
4297 bdrv_reopen_queue_child(bs_queue
, child
->bs
, new_child_options
,
4298 child
->klass
, child
->role
, bs
->drv
->is_format
,
4299 options
, flags
, child_keep_old
);
4305 BlockReopenQueue
*bdrv_reopen_queue(BlockReopenQueue
*bs_queue
,
4306 BlockDriverState
*bs
,
4307 QDict
*options
, bool keep_old_opts
)
4309 GLOBAL_STATE_CODE();
4311 return bdrv_reopen_queue_child(bs_queue
, bs
, options
, NULL
, 0, false,
4312 NULL
, 0, keep_old_opts
);
4315 void bdrv_reopen_queue_free(BlockReopenQueue
*bs_queue
)
4317 GLOBAL_STATE_CODE();
4319 BlockReopenQueueEntry
*bs_entry
, *next
;
4320 QTAILQ_FOREACH_SAFE(bs_entry
, bs_queue
, entry
, next
) {
4321 qobject_unref(bs_entry
->state
.explicit_options
);
4322 qobject_unref(bs_entry
->state
.options
);
4330 * Reopen multiple BlockDriverStates atomically & transactionally.
4332 * The queue passed in (bs_queue) must have been built up previous
4333 * via bdrv_reopen_queue().
4335 * Reopens all BDS specified in the queue, with the appropriate
4336 * flags. All devices are prepared for reopen, and failure of any
4337 * device will cause all device changes to be abandoned, and intermediate
4340 * If all devices prepare successfully, then the changes are committed
4343 * All affected nodes must be drained between bdrv_reopen_queue() and
4344 * bdrv_reopen_multiple().
4346 * To be called from the main thread, with all other AioContexts unlocked.
4348 int bdrv_reopen_multiple(BlockReopenQueue
*bs_queue
, Error
**errp
)
4351 BlockReopenQueueEntry
*bs_entry
, *next
;
4353 Transaction
*tran
= tran_new();
4354 g_autoptr(GHashTable
) found
= NULL
;
4355 g_autoptr(GSList
) refresh_list
= NULL
;
4357 assert(qemu_get_current_aio_context() == qemu_get_aio_context());
4358 assert(bs_queue
!= NULL
);
4359 GLOBAL_STATE_CODE();
4361 QTAILQ_FOREACH(bs_entry
, bs_queue
, entry
) {
4362 ctx
= bdrv_get_aio_context(bs_entry
->state
.bs
);
4363 aio_context_acquire(ctx
);
4364 ret
= bdrv_flush(bs_entry
->state
.bs
);
4365 aio_context_release(ctx
);
4367 error_setg_errno(errp
, -ret
, "Error flushing drive");
4372 QTAILQ_FOREACH(bs_entry
, bs_queue
, entry
) {
4373 assert(bs_entry
->state
.bs
->quiesce_counter
> 0);
4374 ctx
= bdrv_get_aio_context(bs_entry
->state
.bs
);
4375 aio_context_acquire(ctx
);
4376 ret
= bdrv_reopen_prepare(&bs_entry
->state
, bs_queue
, tran
, errp
);
4377 aio_context_release(ctx
);
4381 bs_entry
->prepared
= true;
4384 found
= g_hash_table_new(NULL
, NULL
);
4385 QTAILQ_FOREACH(bs_entry
, bs_queue
, entry
) {
4386 BDRVReopenState
*state
= &bs_entry
->state
;
4388 refresh_list
= bdrv_topological_dfs(refresh_list
, found
, state
->bs
);
4389 if (state
->old_backing_bs
) {
4390 refresh_list
= bdrv_topological_dfs(refresh_list
, found
,
4391 state
->old_backing_bs
);
4393 if (state
->old_file_bs
) {
4394 refresh_list
= bdrv_topological_dfs(refresh_list
, found
,
4395 state
->old_file_bs
);
4400 * Note that file-posix driver rely on permission update done during reopen
4401 * (even if no permission changed), because it wants "new" permissions for
4402 * reconfiguring the fd and that's why it does it in raw_check_perm(), not
4403 * in raw_reopen_prepare() which is called with "old" permissions.
4405 ret
= bdrv_list_refresh_perms(refresh_list
, bs_queue
, tran
, errp
);
4411 * If we reach this point, we have success and just need to apply the
4414 * Reverse order is used to comfort qcow2 driver: on commit it need to write
4415 * IN_USE flag to the image, to mark bitmaps in the image as invalid. But
4416 * children are usually goes after parents in reopen-queue, so go from last
4419 QTAILQ_FOREACH_REVERSE(bs_entry
, bs_queue
, entry
) {
4420 ctx
= bdrv_get_aio_context(bs_entry
->state
.bs
);
4421 aio_context_acquire(ctx
);
4422 bdrv_reopen_commit(&bs_entry
->state
);
4423 aio_context_release(ctx
);
4428 QTAILQ_FOREACH_REVERSE(bs_entry
, bs_queue
, entry
) {
4429 BlockDriverState
*bs
= bs_entry
->state
.bs
;
4431 if (bs
->drv
->bdrv_reopen_commit_post
) {
4432 ctx
= bdrv_get_aio_context(bs
);
4433 aio_context_acquire(ctx
);
4434 bs
->drv
->bdrv_reopen_commit_post(&bs_entry
->state
);
4435 aio_context_release(ctx
);
4444 QTAILQ_FOREACH_SAFE(bs_entry
, bs_queue
, entry
, next
) {
4445 if (bs_entry
->prepared
) {
4446 ctx
= bdrv_get_aio_context(bs_entry
->state
.bs
);
4447 aio_context_acquire(ctx
);
4448 bdrv_reopen_abort(&bs_entry
->state
);
4449 aio_context_release(ctx
);
4454 bdrv_reopen_queue_free(bs_queue
);
4459 int bdrv_reopen(BlockDriverState
*bs
, QDict
*opts
, bool keep_old_opts
,
4462 AioContext
*ctx
= bdrv_get_aio_context(bs
);
4463 BlockReopenQueue
*queue
;
4466 GLOBAL_STATE_CODE();
4468 bdrv_subtree_drained_begin(bs
);
4469 if (ctx
!= qemu_get_aio_context()) {
4470 aio_context_release(ctx
);
4473 queue
= bdrv_reopen_queue(NULL
, bs
, opts
, keep_old_opts
);
4474 ret
= bdrv_reopen_multiple(queue
, errp
);
4476 if (ctx
!= qemu_get_aio_context()) {
4477 aio_context_acquire(ctx
);
4479 bdrv_subtree_drained_end(bs
);
4484 int bdrv_reopen_set_read_only(BlockDriverState
*bs
, bool read_only
,
4487 QDict
*opts
= qdict_new();
4489 GLOBAL_STATE_CODE();
4491 qdict_put_bool(opts
, BDRV_OPT_READ_ONLY
, read_only
);
4493 return bdrv_reopen(bs
, opts
, true, errp
);
4497 * Take a BDRVReopenState and check if the value of 'backing' in the
4498 * reopen_state->options QDict is valid or not.
4500 * If 'backing' is missing from the QDict then return 0.
4502 * If 'backing' contains the node name of the backing file of
4503 * reopen_state->bs then return 0.
4505 * If 'backing' contains a different node name (or is null) then check
4506 * whether the current backing file can be replaced with the new one.
4507 * If that's the case then reopen_state->replace_backing_bs is set to
4508 * true and reopen_state->new_backing_bs contains a pointer to the new
4509 * backing BlockDriverState (or NULL).
4511 * Return 0 on success, otherwise return < 0 and set @errp.
4513 static int bdrv_reopen_parse_file_or_backing(BDRVReopenState
*reopen_state
,
4514 bool is_backing
, Transaction
*tran
,
4517 BlockDriverState
*bs
= reopen_state
->bs
;
4518 BlockDriverState
*new_child_bs
;
4519 BlockDriverState
*old_child_bs
= is_backing
? child_bs(bs
->backing
) :
4521 const char *child_name
= is_backing
? "backing" : "file";
4525 GLOBAL_STATE_CODE();
4527 value
= qdict_get(reopen_state
->options
, child_name
);
4528 if (value
== NULL
) {
4532 switch (qobject_type(value
)) {
4534 assert(is_backing
); /* The 'file' option does not allow a null value */
4535 new_child_bs
= NULL
;
4538 str
= qstring_get_str(qobject_to(QString
, value
));
4539 new_child_bs
= bdrv_lookup_bs(NULL
, str
, errp
);
4540 if (new_child_bs
== NULL
) {
4542 } else if (bdrv_recurse_has_child(new_child_bs
, bs
)) {
4543 error_setg(errp
, "Making '%s' a %s child of '%s' would create a "
4544 "cycle", str
, child_name
, bs
->node_name
);
4550 * The options QDict has been flattened, so 'backing' and 'file'
4551 * do not allow any other data type here.
4553 g_assert_not_reached();
4556 if (old_child_bs
== new_child_bs
) {
4561 if (bdrv_skip_implicit_filters(old_child_bs
) == new_child_bs
) {
4565 if (old_child_bs
->implicit
) {
4566 error_setg(errp
, "Cannot replace implicit %s child of %s",
4567 child_name
, bs
->node_name
);
4572 if (bs
->drv
->is_filter
&& !old_child_bs
) {
4574 * Filters always have a file or a backing child, so we are trying to
4575 * change wrong child
4577 error_setg(errp
, "'%s' is a %s filter node that does not support a "
4578 "%s child", bs
->node_name
, bs
->drv
->format_name
, child_name
);
4583 reopen_state
->old_backing_bs
= old_child_bs
;
4585 reopen_state
->old_file_bs
= old_child_bs
;
4588 return bdrv_set_file_or_backing_noperm(bs
, new_child_bs
, is_backing
,
4593 * Prepares a BlockDriverState for reopen. All changes are staged in the
4594 * 'opaque' field of the BDRVReopenState, which is used and allocated by
4595 * the block driver layer .bdrv_reopen_prepare()
4597 * bs is the BlockDriverState to reopen
4598 * flags are the new open flags
4599 * queue is the reopen queue
4601 * Returns 0 on success, non-zero on error. On error errp will be set
4604 * On failure, bdrv_reopen_abort() will be called to clean up any data.
4605 * It is the responsibility of the caller to then call the abort() or
4606 * commit() for any other BDS that have been left in a prepare() state
4609 static int bdrv_reopen_prepare(BDRVReopenState
*reopen_state
,
4610 BlockReopenQueue
*queue
,
4611 Transaction
*change_child_tran
, Error
**errp
)
4615 Error
*local_err
= NULL
;
4618 QDict
*orig_reopen_opts
;
4619 char *discard
= NULL
;
4621 bool drv_prepared
= false;
4623 assert(reopen_state
!= NULL
);
4624 assert(reopen_state
->bs
->drv
!= NULL
);
4625 GLOBAL_STATE_CODE();
4626 drv
= reopen_state
->bs
->drv
;
4628 /* This function and each driver's bdrv_reopen_prepare() remove
4629 * entries from reopen_state->options as they are processed, so
4630 * we need to make a copy of the original QDict. */
4631 orig_reopen_opts
= qdict_clone_shallow(reopen_state
->options
);
4633 /* Process generic block layer options */
4634 opts
= qemu_opts_create(&bdrv_runtime_opts
, NULL
, 0, &error_abort
);
4635 if (!qemu_opts_absorb_qdict(opts
, reopen_state
->options
, errp
)) {
4640 /* This was already called in bdrv_reopen_queue_child() so the flags
4641 * are up-to-date. This time we simply want to remove the options from
4642 * QemuOpts in order to indicate that they have been processed. */
4643 old_flags
= reopen_state
->flags
;
4644 update_flags_from_options(&reopen_state
->flags
, opts
);
4645 assert(old_flags
== reopen_state
->flags
);
4647 discard
= qemu_opt_get_del(opts
, BDRV_OPT_DISCARD
);
4648 if (discard
!= NULL
) {
4649 if (bdrv_parse_discard_flags(discard
, &reopen_state
->flags
) != 0) {
4650 error_setg(errp
, "Invalid discard option");
4656 reopen_state
->detect_zeroes
=
4657 bdrv_parse_detect_zeroes(opts
, reopen_state
->flags
, &local_err
);
4659 error_propagate(errp
, local_err
);
4664 /* All other options (including node-name and driver) must be unchanged.
4665 * Put them back into the QDict, so that they are checked at the end
4666 * of this function. */
4667 qemu_opts_to_qdict(opts
, reopen_state
->options
);
4669 /* If we are to stay read-only, do not allow permission change
4670 * to r/w. Attempting to set to r/w may fail if either BDRV_O_ALLOW_RDWR is
4671 * not set, or if the BDS still has copy_on_read enabled */
4672 read_only
= !(reopen_state
->flags
& BDRV_O_RDWR
);
4673 ret
= bdrv_can_set_read_only(reopen_state
->bs
, read_only
, true, &local_err
);
4675 error_propagate(errp
, local_err
);
4679 if (drv
->bdrv_reopen_prepare
) {
4681 * If a driver-specific option is missing, it means that we
4682 * should reset it to its default value.
4683 * But not all options allow that, so we need to check it first.
4685 ret
= bdrv_reset_options_allowed(reopen_state
->bs
,
4686 reopen_state
->options
, errp
);
4691 ret
= drv
->bdrv_reopen_prepare(reopen_state
, queue
, &local_err
);
4693 if (local_err
!= NULL
) {
4694 error_propagate(errp
, local_err
);
4696 bdrv_refresh_filename(reopen_state
->bs
);
4697 error_setg(errp
, "failed while preparing to reopen image '%s'",
4698 reopen_state
->bs
->filename
);
4703 /* It is currently mandatory to have a bdrv_reopen_prepare()
4704 * handler for each supported drv. */
4705 error_setg(errp
, "Block format '%s' used by node '%s' "
4706 "does not support reopening files", drv
->format_name
,
4707 bdrv_get_device_or_node_name(reopen_state
->bs
));
4712 drv_prepared
= true;
4715 * We must provide the 'backing' option if the BDS has a backing
4716 * file or if the image file has a backing file name as part of
4717 * its metadata. Otherwise the 'backing' option can be omitted.
4719 if (drv
->supports_backing
&& reopen_state
->backing_missing
&&
4720 (reopen_state
->bs
->backing
|| reopen_state
->bs
->backing_file
[0])) {
4721 error_setg(errp
, "backing is missing for '%s'",
4722 reopen_state
->bs
->node_name
);
4728 * Allow changing the 'backing' option. The new value can be
4729 * either a reference to an existing node (using its node name)
4730 * or NULL to simply detach the current backing file.
4732 ret
= bdrv_reopen_parse_file_or_backing(reopen_state
, true,
4733 change_child_tran
, errp
);
4737 qdict_del(reopen_state
->options
, "backing");
4739 /* Allow changing the 'file' option. In this case NULL is not allowed */
4740 ret
= bdrv_reopen_parse_file_or_backing(reopen_state
, false,
4741 change_child_tran
, errp
);
4745 qdict_del(reopen_state
->options
, "file");
4747 /* Options that are not handled are only okay if they are unchanged
4748 * compared to the old state. It is expected that some options are only
4749 * used for the initial open, but not reopen (e.g. filename) */
4750 if (qdict_size(reopen_state
->options
)) {
4751 const QDictEntry
*entry
= qdict_first(reopen_state
->options
);
4754 QObject
*new = entry
->value
;
4755 QObject
*old
= qdict_get(reopen_state
->bs
->options
, entry
->key
);
4757 /* Allow child references (child_name=node_name) as long as they
4758 * point to the current child (i.e. everything stays the same). */
4759 if (qobject_type(new) == QTYPE_QSTRING
) {
4761 QLIST_FOREACH(child
, &reopen_state
->bs
->children
, next
) {
4762 if (!strcmp(child
->name
, entry
->key
)) {
4768 if (!strcmp(child
->bs
->node_name
,
4769 qstring_get_str(qobject_to(QString
, new)))) {
4770 continue; /* Found child with this name, skip option */
4776 * TODO: When using -drive to specify blockdev options, all values
4777 * will be strings; however, when using -blockdev, blockdev-add or
4778 * filenames using the json:{} pseudo-protocol, they will be
4780 * In contrast, reopening options are (currently) always strings
4781 * (because you can only specify them through qemu-io; all other
4782 * callers do not specify any options).
4783 * Therefore, when using anything other than -drive to create a BDS,
4784 * this cannot detect non-string options as unchanged, because
4785 * qobject_is_equal() always returns false for objects of different
4786 * type. In the future, this should be remedied by correctly typing
4787 * all options. For now, this is not too big of an issue because
4788 * the user can simply omit options which cannot be changed anyway,
4789 * so they will stay unchanged.
4791 if (!qobject_is_equal(new, old
)) {
4792 error_setg(errp
, "Cannot change the option '%s'", entry
->key
);
4796 } while ((entry
= qdict_next(reopen_state
->options
, entry
)));
4801 /* Restore the original reopen_state->options QDict */
4802 qobject_unref(reopen_state
->options
);
4803 reopen_state
->options
= qobject_ref(orig_reopen_opts
);
4806 if (ret
< 0 && drv_prepared
) {
4807 /* drv->bdrv_reopen_prepare() has succeeded, so we need to
4808 * call drv->bdrv_reopen_abort() before signaling an error
4809 * (bdrv_reopen_multiple() will not call bdrv_reopen_abort()
4810 * when the respective bdrv_reopen_prepare() has failed) */
4811 if (drv
->bdrv_reopen_abort
) {
4812 drv
->bdrv_reopen_abort(reopen_state
);
4815 qemu_opts_del(opts
);
4816 qobject_unref(orig_reopen_opts
);
4822 * Takes the staged changes for the reopen from bdrv_reopen_prepare(), and
4823 * makes them final by swapping the staging BlockDriverState contents into
4824 * the active BlockDriverState contents.
4826 static void bdrv_reopen_commit(BDRVReopenState
*reopen_state
)
4829 BlockDriverState
*bs
;
4832 assert(reopen_state
!= NULL
);
4833 bs
= reopen_state
->bs
;
4835 assert(drv
!= NULL
);
4836 GLOBAL_STATE_CODE();
4838 /* If there are any driver level actions to take */
4839 if (drv
->bdrv_reopen_commit
) {
4840 drv
->bdrv_reopen_commit(reopen_state
);
4843 /* set BDS specific flags now */
4844 qobject_unref(bs
->explicit_options
);
4845 qobject_unref(bs
->options
);
4846 qobject_ref(reopen_state
->explicit_options
);
4847 qobject_ref(reopen_state
->options
);
4849 bs
->explicit_options
= reopen_state
->explicit_options
;
4850 bs
->options
= reopen_state
->options
;
4851 bs
->open_flags
= reopen_state
->flags
;
4852 bs
->detect_zeroes
= reopen_state
->detect_zeroes
;
4854 /* Remove child references from bs->options and bs->explicit_options.
4855 * Child options were already removed in bdrv_reopen_queue_child() */
4856 QLIST_FOREACH(child
, &bs
->children
, next
) {
4857 qdict_del(bs
->explicit_options
, child
->name
);
4858 qdict_del(bs
->options
, child
->name
);
4860 /* backing is probably removed, so it's not handled by previous loop */
4861 qdict_del(bs
->explicit_options
, "backing");
4862 qdict_del(bs
->options
, "backing");
4864 bdrv_refresh_limits(bs
, NULL
, NULL
);
4868 * Abort the reopen, and delete and free the staged changes in
4871 static void bdrv_reopen_abort(BDRVReopenState
*reopen_state
)
4875 assert(reopen_state
!= NULL
);
4876 drv
= reopen_state
->bs
->drv
;
4877 assert(drv
!= NULL
);
4878 GLOBAL_STATE_CODE();
4880 if (drv
->bdrv_reopen_abort
) {
4881 drv
->bdrv_reopen_abort(reopen_state
);
4886 static void bdrv_close(BlockDriverState
*bs
)
4888 BdrvAioNotifier
*ban
, *ban_next
;
4889 BdrvChild
*child
, *next
;
4891 GLOBAL_STATE_CODE();
4892 assert(!bs
->refcnt
);
4894 bdrv_drained_begin(bs
); /* complete I/O */
4896 bdrv_drain(bs
); /* in case flush left pending I/O */
4899 if (bs
->drv
->bdrv_close
) {
4900 /* Must unfreeze all children, so bdrv_unref_child() works */
4901 bs
->drv
->bdrv_close(bs
);
4906 QLIST_FOREACH_SAFE(child
, &bs
->children
, next
, next
) {
4907 bdrv_unref_child(bs
, child
);
4910 assert(!bs
->backing
);
4914 qatomic_set(&bs
->copy_on_read
, 0);
4915 bs
->backing_file
[0] = '\0';
4916 bs
->backing_format
[0] = '\0';
4917 bs
->total_sectors
= 0;
4918 bs
->encrypted
= false;
4920 qobject_unref(bs
->options
);
4921 qobject_unref(bs
->explicit_options
);
4923 bs
->explicit_options
= NULL
;
4924 qobject_unref(bs
->full_open_options
);
4925 bs
->full_open_options
= NULL
;
4926 g_free(bs
->block_status_cache
);
4927 bs
->block_status_cache
= NULL
;
4929 bdrv_release_named_dirty_bitmaps(bs
);
4930 assert(QLIST_EMPTY(&bs
->dirty_bitmaps
));
4932 QLIST_FOREACH_SAFE(ban
, &bs
->aio_notifiers
, list
, ban_next
) {
4935 QLIST_INIT(&bs
->aio_notifiers
);
4936 bdrv_drained_end(bs
);
4939 * If we're still inside some bdrv_drain_all_begin()/end() sections, end
4940 * them now since this BDS won't exist anymore when bdrv_drain_all_end()
4943 if (bs
->quiesce_counter
) {
4944 bdrv_drain_all_end_quiesce(bs
);
4948 void bdrv_close_all(void)
4950 GLOBAL_STATE_CODE();
4951 assert(job_next(NULL
) == NULL
);
4953 /* Drop references from requests still in flight, such as canceled block
4954 * jobs whose AIO context has not been polled yet */
4957 blk_remove_all_bs();
4958 blockdev_close_all_bdrv_states();
4960 assert(QTAILQ_EMPTY(&all_bdrv_states
));
4963 static bool should_update_child(BdrvChild
*c
, BlockDriverState
*to
)
4969 if (c
->klass
->stay_at_node
) {
4973 /* If the child @c belongs to the BDS @to, replacing the current
4974 * c->bs by @to would mean to create a loop.
4976 * Such a case occurs when appending a BDS to a backing chain.
4977 * For instance, imagine the following chain:
4979 * guest device -> node A -> further backing chain...
4981 * Now we create a new BDS B which we want to put on top of this
4982 * chain, so we first attach A as its backing node:
4987 * guest device -> node A -> further backing chain...
4989 * Finally we want to replace A by B. When doing that, we want to
4990 * replace all pointers to A by pointers to B -- except for the
4991 * pointer from B because (1) that would create a loop, and (2)
4992 * that pointer should simply stay intact:
4994 * guest device -> node B
4997 * node A -> further backing chain...
4999 * In general, when replacing a node A (c->bs) by a node B (@to),
5000 * if A is a child of B, that means we cannot replace A by B there
5001 * because that would create a loop. Silently detaching A from B
5002 * is also not really an option. So overall just leaving A in
5003 * place there is the most sensible choice.
5005 * We would also create a loop in any cases where @c is only
5006 * indirectly referenced by @to. Prevent this by returning false
5007 * if @c is found (by breadth-first search) anywhere in the whole
5012 found
= g_hash_table_new(NULL
, NULL
);
5013 g_hash_table_add(found
, to
);
5014 queue
= g_queue_new();
5015 g_queue_push_tail(queue
, to
);
5017 while (!g_queue_is_empty(queue
)) {
5018 BlockDriverState
*v
= g_queue_pop_head(queue
);
5021 QLIST_FOREACH(c2
, &v
->children
, next
) {
5027 if (g_hash_table_contains(found
, c2
->bs
)) {
5031 g_queue_push_tail(queue
, c2
->bs
);
5032 g_hash_table_add(found
, c2
->bs
);
5036 g_queue_free(queue
);
5037 g_hash_table_destroy(found
);
5042 static void bdrv_remove_child_commit(void *opaque
)
5044 GLOBAL_STATE_CODE();
5045 bdrv_child_free(opaque
);
5048 static TransactionActionDrv bdrv_remove_child_drv
= {
5049 .commit
= bdrv_remove_child_commit
,
5052 /* Function doesn't update permissions, caller is responsible for this. */
5053 static void bdrv_remove_child(BdrvChild
*child
, Transaction
*tran
)
5060 bdrv_replace_child_tran(child
, NULL
, tran
);
5063 tran_add(tran
, &bdrv_remove_child_drv
, child
);
5067 * A function to remove backing-chain child of @bs if exists: cow child for
5068 * format nodes (always .backing) and filter child for filters (may be .file or
5071 static void bdrv_remove_filter_or_cow_child(BlockDriverState
*bs
,
5074 bdrv_remove_child(bdrv_filter_or_cow_child(bs
), tran
);
5077 static int bdrv_replace_node_noperm(BlockDriverState
*from
,
5078 BlockDriverState
*to
,
5079 bool auto_skip
, Transaction
*tran
,
5082 BdrvChild
*c
, *next
;
5084 GLOBAL_STATE_CODE();
5086 QLIST_FOREACH_SAFE(c
, &from
->parents
, next_parent
, next
) {
5087 assert(c
->bs
== from
);
5088 if (!should_update_child(c
, to
)) {
5092 error_setg(errp
, "Should not change '%s' link to '%s'",
5093 c
->name
, from
->node_name
);
5097 error_setg(errp
, "Cannot change '%s' link to '%s'",
5098 c
->name
, from
->node_name
);
5101 bdrv_replace_child_tran(c
, to
, tran
);
5108 * With auto_skip=true bdrv_replace_node_common skips updating from parents
5109 * if it creates a parent-child relation loop or if parent is block-job.
5111 * With auto_skip=false the error is returned if from has a parent which should
5114 * With @detach_subchain=true @to must be in a backing chain of @from. In this
5115 * case backing link of the cow-parent of @to is removed.
5117 static int bdrv_replace_node_common(BlockDriverState
*from
,
5118 BlockDriverState
*to
,
5119 bool auto_skip
, bool detach_subchain
,
5122 Transaction
*tran
= tran_new();
5123 g_autoptr(GHashTable
) found
= NULL
;
5124 g_autoptr(GSList
) refresh_list
= NULL
;
5125 BlockDriverState
*to_cow_parent
= NULL
;
5128 GLOBAL_STATE_CODE();
5130 if (detach_subchain
) {
5131 assert(bdrv_chain_contains(from
, to
));
5133 for (to_cow_parent
= from
;
5134 bdrv_filter_or_cow_bs(to_cow_parent
) != to
;
5135 to_cow_parent
= bdrv_filter_or_cow_bs(to_cow_parent
))
5141 /* Make sure that @from doesn't go away until we have successfully attached
5142 * all of its parents to @to. */
5145 assert(qemu_get_current_aio_context() == qemu_get_aio_context());
5146 assert(bdrv_get_aio_context(from
) == bdrv_get_aio_context(to
));
5147 bdrv_drained_begin(from
);
5150 * Do the replacement without permission update.
5151 * Replacement may influence the permissions, we should calculate new
5152 * permissions based on new graph. If we fail, we'll roll-back the
5155 ret
= bdrv_replace_node_noperm(from
, to
, auto_skip
, tran
, errp
);
5160 if (detach_subchain
) {
5161 bdrv_remove_filter_or_cow_child(to_cow_parent
, tran
);
5164 found
= g_hash_table_new(NULL
, NULL
);
5166 refresh_list
= bdrv_topological_dfs(refresh_list
, found
, to
);
5167 refresh_list
= bdrv_topological_dfs(refresh_list
, found
, from
);
5169 ret
= bdrv_list_refresh_perms(refresh_list
, NULL
, tran
, errp
);
5177 tran_finalize(tran
, ret
);
5179 bdrv_drained_end(from
);
5185 int bdrv_replace_node(BlockDriverState
*from
, BlockDriverState
*to
,
5188 GLOBAL_STATE_CODE();
5190 return bdrv_replace_node_common(from
, to
, true, false, errp
);
5193 int bdrv_drop_filter(BlockDriverState
*bs
, Error
**errp
)
5195 GLOBAL_STATE_CODE();
5197 return bdrv_replace_node_common(bs
, bdrv_filter_or_cow_bs(bs
), true, true,
5202 * Add new bs contents at the top of an image chain while the chain is
5203 * live, while keeping required fields on the top layer.
5205 * This will modify the BlockDriverState fields, and swap contents
5206 * between bs_new and bs_top. Both bs_new and bs_top are modified.
5208 * bs_new must not be attached to a BlockBackend and must not have backing
5211 * This function does not create any image files.
5213 int bdrv_append(BlockDriverState
*bs_new
, BlockDriverState
*bs_top
,
5218 Transaction
*tran
= tran_new();
5220 GLOBAL_STATE_CODE();
5222 assert(!bs_new
->backing
);
5224 child
= bdrv_attach_child_noperm(bs_new
, bs_top
, "backing",
5225 &child_of_bds
, bdrv_backing_role(bs_new
),
5232 ret
= bdrv_replace_node_noperm(bs_top
, bs_new
, true, tran
, errp
);
5237 ret
= bdrv_refresh_perms(bs_new
, errp
);
5239 tran_finalize(tran
, ret
);
5241 bdrv_refresh_limits(bs_top
, NULL
, NULL
);
5246 /* Not for empty child */
5247 int bdrv_replace_child_bs(BdrvChild
*child
, BlockDriverState
*new_bs
,
5251 Transaction
*tran
= tran_new();
5252 g_autoptr(GHashTable
) found
= NULL
;
5253 g_autoptr(GSList
) refresh_list
= NULL
;
5254 BlockDriverState
*old_bs
= child
->bs
;
5256 GLOBAL_STATE_CODE();
5259 bdrv_drained_begin(old_bs
);
5260 bdrv_drained_begin(new_bs
);
5262 bdrv_replace_child_tran(child
, new_bs
, tran
);
5264 found
= g_hash_table_new(NULL
, NULL
);
5265 refresh_list
= bdrv_topological_dfs(refresh_list
, found
, old_bs
);
5266 refresh_list
= bdrv_topological_dfs(refresh_list
, found
, new_bs
);
5268 ret
= bdrv_list_refresh_perms(refresh_list
, NULL
, tran
, errp
);
5270 tran_finalize(tran
, ret
);
5272 bdrv_drained_end(old_bs
);
5273 bdrv_drained_end(new_bs
);
5279 static void bdrv_delete(BlockDriverState
*bs
)
5281 assert(bdrv_op_blocker_is_empty(bs
));
5282 assert(!bs
->refcnt
);
5283 GLOBAL_STATE_CODE();
5285 /* remove from list, if necessary */
5286 if (bs
->node_name
[0] != '\0') {
5287 QTAILQ_REMOVE(&graph_bdrv_states
, bs
, node_list
);
5289 QTAILQ_REMOVE(&all_bdrv_states
, bs
, bs_list
);
5298 * Replace @bs by newly created block node.
5300 * @options is a QDict of options to pass to the block drivers, or NULL for an
5301 * empty set of options. The reference to the QDict belongs to the block layer
5302 * after the call (even on failure), so if the caller intends to reuse the
5303 * dictionary, it needs to use qobject_ref() before calling bdrv_open.
5305 BlockDriverState
*bdrv_insert_node(BlockDriverState
*bs
, QDict
*options
,
5306 int flags
, Error
**errp
)
5310 BlockDriverState
*new_node_bs
= NULL
;
5311 const char *drvname
, *node_name
;
5314 drvname
= qdict_get_try_str(options
, "driver");
5316 error_setg(errp
, "driver is not specified");
5320 drv
= bdrv_find_format(drvname
);
5322 error_setg(errp
, "Unknown driver: '%s'", drvname
);
5326 node_name
= qdict_get_try_str(options
, "node-name");
5328 GLOBAL_STATE_CODE();
5330 new_node_bs
= bdrv_new_open_driver_opts(drv
, node_name
, options
, flags
,
5332 options
= NULL
; /* bdrv_new_open_driver() eats options */
5334 error_prepend(errp
, "Could not create node: ");
5338 bdrv_drained_begin(bs
);
5339 ret
= bdrv_replace_node(bs
, new_node_bs
, errp
);
5340 bdrv_drained_end(bs
);
5343 error_prepend(errp
, "Could not replace node: ");
5350 qobject_unref(options
);
5351 bdrv_unref(new_node_bs
);
5356 * Run consistency checks on an image
5358 * Returns 0 if the check could be completed (it doesn't mean that the image is
5359 * free of errors) or -errno when an internal error occurred. The results of the
5360 * check are stored in res.
5362 int coroutine_fn
bdrv_co_check(BlockDriverState
*bs
,
5363 BdrvCheckResult
*res
, BdrvCheckMode fix
)
5366 if (bs
->drv
== NULL
) {
5369 if (bs
->drv
->bdrv_co_check
== NULL
) {
5373 memset(res
, 0, sizeof(*res
));
5374 return bs
->drv
->bdrv_co_check(bs
, res
, fix
);
5380 * -EINVAL - backing format specified, but no file
5381 * -ENOSPC - can't update the backing file because no space is left in the
5383 * -ENOTSUP - format driver doesn't support changing the backing file
5385 int bdrv_change_backing_file(BlockDriverState
*bs
, const char *backing_file
,
5386 const char *backing_fmt
, bool require
)
5388 BlockDriver
*drv
= bs
->drv
;
5391 GLOBAL_STATE_CODE();
5397 /* Backing file format doesn't make sense without a backing file */
5398 if (backing_fmt
&& !backing_file
) {
5402 if (require
&& backing_file
&& !backing_fmt
) {
5406 if (drv
->bdrv_change_backing_file
!= NULL
) {
5407 ret
= drv
->bdrv_change_backing_file(bs
, backing_file
, backing_fmt
);
5413 pstrcpy(bs
->backing_file
, sizeof(bs
->backing_file
), backing_file
?: "");
5414 pstrcpy(bs
->backing_format
, sizeof(bs
->backing_format
), backing_fmt
?: "");
5415 pstrcpy(bs
->auto_backing_file
, sizeof(bs
->auto_backing_file
),
5416 backing_file
?: "");
5422 * Finds the first non-filter node above bs in the chain between
5423 * active and bs. The returned node is either an immediate parent of
5424 * bs, or there are only filter nodes between the two.
5426 * Returns NULL if bs is not found in active's image chain,
5427 * or if active == bs.
5429 * Returns the bottommost base image if bs == NULL.
5431 BlockDriverState
*bdrv_find_overlay(BlockDriverState
*active
,
5432 BlockDriverState
*bs
)
5435 GLOBAL_STATE_CODE();
5437 bs
= bdrv_skip_filters(bs
);
5438 active
= bdrv_skip_filters(active
);
5441 BlockDriverState
*next
= bdrv_backing_chain_next(active
);
5451 /* Given a BDS, searches for the base layer. */
5452 BlockDriverState
*bdrv_find_base(BlockDriverState
*bs
)
5454 GLOBAL_STATE_CODE();
5456 return bdrv_find_overlay(bs
, NULL
);
5460 * Return true if at least one of the COW (backing) and filter links
5461 * between @bs and @base is frozen. @errp is set if that's the case.
5462 * @base must be reachable from @bs, or NULL.
5464 bool bdrv_is_backing_chain_frozen(BlockDriverState
*bs
, BlockDriverState
*base
,
5467 BlockDriverState
*i
;
5470 GLOBAL_STATE_CODE();
5472 for (i
= bs
; i
!= base
; i
= child_bs(child
)) {
5473 child
= bdrv_filter_or_cow_child(i
);
5475 if (child
&& child
->frozen
) {
5476 error_setg(errp
, "Cannot change '%s' link from '%s' to '%s'",
5477 child
->name
, i
->node_name
, child
->bs
->node_name
);
5486 * Freeze all COW (backing) and filter links between @bs and @base.
5487 * If any of the links is already frozen the operation is aborted and
5488 * none of the links are modified.
5489 * @base must be reachable from @bs, or NULL.
5490 * Returns 0 on success. On failure returns < 0 and sets @errp.
5492 int bdrv_freeze_backing_chain(BlockDriverState
*bs
, BlockDriverState
*base
,
5495 BlockDriverState
*i
;
5498 GLOBAL_STATE_CODE();
5500 if (bdrv_is_backing_chain_frozen(bs
, base
, errp
)) {
5504 for (i
= bs
; i
!= base
; i
= child_bs(child
)) {
5505 child
= bdrv_filter_or_cow_child(i
);
5506 if (child
&& child
->bs
->never_freeze
) {
5507 error_setg(errp
, "Cannot freeze '%s' link to '%s'",
5508 child
->name
, child
->bs
->node_name
);
5513 for (i
= bs
; i
!= base
; i
= child_bs(child
)) {
5514 child
= bdrv_filter_or_cow_child(i
);
5516 child
->frozen
= true;
5524 * Unfreeze all COW (backing) and filter links between @bs and @base.
5525 * The caller must ensure that all links are frozen before using this
5527 * @base must be reachable from @bs, or NULL.
5529 void bdrv_unfreeze_backing_chain(BlockDriverState
*bs
, BlockDriverState
*base
)
5531 BlockDriverState
*i
;
5534 GLOBAL_STATE_CODE();
5536 for (i
= bs
; i
!= base
; i
= child_bs(child
)) {
5537 child
= bdrv_filter_or_cow_child(i
);
5539 assert(child
->frozen
);
5540 child
->frozen
= false;
5546 * Drops images above 'base' up to and including 'top', and sets the image
5547 * above 'top' to have base as its backing file.
5549 * Requires that the overlay to 'top' is opened r/w, so that the backing file
5550 * information in 'bs' can be properly updated.
5552 * E.g., this will convert the following chain:
5553 * bottom <- base <- intermediate <- top <- active
5557 * bottom <- base <- active
5559 * It is allowed for bottom==base, in which case it converts:
5561 * base <- intermediate <- top <- active
5567 * If backing_file_str is non-NULL, it will be used when modifying top's
5568 * overlay image metadata.
5571 * if active == top, that is considered an error
5574 int bdrv_drop_intermediate(BlockDriverState
*top
, BlockDriverState
*base
,
5575 const char *backing_file_str
)
5577 BlockDriverState
*explicit_top
= top
;
5578 bool update_inherits_from
;
5580 Error
*local_err
= NULL
;
5582 g_autoptr(GSList
) updated_children
= NULL
;
5585 GLOBAL_STATE_CODE();
5588 bdrv_subtree_drained_begin(top
);
5590 if (!top
->drv
|| !base
->drv
) {
5594 /* Make sure that base is in the backing chain of top */
5595 if (!bdrv_chain_contains(top
, base
)) {
5599 /* If 'base' recursively inherits from 'top' then we should set
5600 * base->inherits_from to top->inherits_from after 'top' and all
5601 * other intermediate nodes have been dropped.
5602 * If 'top' is an implicit node (e.g. "commit_top") we should skip
5603 * it because no one inherits from it. We use explicit_top for that. */
5604 explicit_top
= bdrv_skip_implicit_filters(explicit_top
);
5605 update_inherits_from
= bdrv_inherits_from_recursive(base
, explicit_top
);
5607 /* success - we can delete the intermediate states, and link top->base */
5608 if (!backing_file_str
) {
5609 bdrv_refresh_filename(base
);
5610 backing_file_str
= base
->filename
;
5613 QLIST_FOREACH(c
, &top
->parents
, next_parent
) {
5614 updated_children
= g_slist_prepend(updated_children
, c
);
5618 * It seems correct to pass detach_subchain=true here, but it triggers
5619 * one more yet not fixed bug, when due to nested aio_poll loop we switch to
5620 * another drained section, which modify the graph (for example, removing
5621 * the child, which we keep in updated_children list). So, it's a TODO.
5623 * Note, bug triggered if pass detach_subchain=true here and run
5624 * test-bdrv-drain. test_drop_intermediate_poll() test-case will crash.
5627 bdrv_replace_node_common(top
, base
, false, false, &local_err
);
5629 error_report_err(local_err
);
5633 for (p
= updated_children
; p
; p
= p
->next
) {
5636 if (c
->klass
->update_filename
) {
5637 ret
= c
->klass
->update_filename(c
, base
, backing_file_str
,
5641 * TODO: Actually, we want to rollback all previous iterations
5642 * of this loop, and (which is almost impossible) previous
5643 * bdrv_replace_node()...
5645 * Note, that c->klass->update_filename may lead to permission
5646 * update, so it's a bad idea to call it inside permission
5647 * update transaction of bdrv_replace_node.
5649 error_report_err(local_err
);
5655 if (update_inherits_from
) {
5656 base
->inherits_from
= explicit_top
->inherits_from
;
5661 bdrv_subtree_drained_end(top
);
5667 * Implementation of BlockDriver.bdrv_get_allocated_file_size() that
5668 * sums the size of all data-bearing children. (This excludes backing
5671 static int64_t bdrv_sum_allocated_file_size(BlockDriverState
*bs
)
5674 int64_t child_size
, sum
= 0;
5676 QLIST_FOREACH(child
, &bs
->children
, next
) {
5677 if (child
->role
& (BDRV_CHILD_DATA
| BDRV_CHILD_METADATA
|
5678 BDRV_CHILD_FILTERED
))
5680 child_size
= bdrv_get_allocated_file_size(child
->bs
);
5681 if (child_size
< 0) {
5692 * Length of a allocated file in bytes. Sparse files are counted by actual
5693 * allocated space. Return < 0 if error or unknown.
5695 int64_t bdrv_get_allocated_file_size(BlockDriverState
*bs
)
5697 BlockDriver
*drv
= bs
->drv
;
5703 if (drv
->bdrv_get_allocated_file_size
) {
5704 return drv
->bdrv_get_allocated_file_size(bs
);
5707 if (drv
->bdrv_file_open
) {
5709 * Protocol drivers default to -ENOTSUP (most of their data is
5710 * not stored in any of their children (if they even have any),
5711 * so there is no generic way to figure it out).
5714 } else if (drv
->is_filter
) {
5715 /* Filter drivers default to the size of their filtered child */
5716 return bdrv_get_allocated_file_size(bdrv_filter_bs(bs
));
5718 /* Other drivers default to summing their children's sizes */
5719 return bdrv_sum_allocated_file_size(bs
);
5725 * @drv: Format driver
5726 * @opts: Creation options for new image
5727 * @in_bs: Existing image containing data for new image (may be NULL)
5728 * @errp: Error object
5729 * Returns: A #BlockMeasureInfo (free using qapi_free_BlockMeasureInfo())
5732 * Calculate file size required to create a new image.
5734 * If @in_bs is given then space for allocated clusters and zero clusters
5735 * from that image are included in the calculation. If @opts contains a
5736 * backing file that is shared by @in_bs then backing clusters may be omitted
5737 * from the calculation.
5739 * If @in_bs is NULL then the calculation includes no allocated clusters
5740 * unless a preallocation option is given in @opts.
5742 * Note that @in_bs may use a different BlockDriver from @drv.
5744 * If an error occurs the @errp pointer is set.
5746 BlockMeasureInfo
*bdrv_measure(BlockDriver
*drv
, QemuOpts
*opts
,
5747 BlockDriverState
*in_bs
, Error
**errp
)
5750 if (!drv
->bdrv_measure
) {
5751 error_setg(errp
, "Block driver '%s' does not support size measurement",
5756 return drv
->bdrv_measure(opts
, in_bs
, errp
);
5760 * Return number of sectors on success, -errno on error.
5762 int64_t bdrv_nb_sectors(BlockDriverState
*bs
)
5764 BlockDriver
*drv
= bs
->drv
;
5770 if (drv
->has_variable_length
) {
5771 int ret
= refresh_total_sectors(bs
, bs
->total_sectors
);
5776 return bs
->total_sectors
;
5780 * Return length in bytes on success, -errno on error.
5781 * The length is always a multiple of BDRV_SECTOR_SIZE.
5783 int64_t bdrv_getlength(BlockDriverState
*bs
)
5785 int64_t ret
= bdrv_nb_sectors(bs
);
5791 if (ret
> INT64_MAX
/ BDRV_SECTOR_SIZE
) {
5794 return ret
* BDRV_SECTOR_SIZE
;
5797 /* return 0 as number of sectors if no device present or error */
5798 void bdrv_get_geometry(BlockDriverState
*bs
, uint64_t *nb_sectors_ptr
)
5800 int64_t nb_sectors
= bdrv_nb_sectors(bs
);
5803 *nb_sectors_ptr
= nb_sectors
< 0 ? 0 : nb_sectors
;
5806 bool bdrv_is_sg(BlockDriverState
*bs
)
5813 * Return whether the given node supports compressed writes.
5815 bool bdrv_supports_compressed_writes(BlockDriverState
*bs
)
5817 BlockDriverState
*filtered
;
5820 if (!bs
->drv
|| !block_driver_can_compress(bs
->drv
)) {
5824 filtered
= bdrv_filter_bs(bs
);
5827 * Filters can only forward compressed writes, so we have to
5830 return bdrv_supports_compressed_writes(filtered
);
5836 const char *bdrv_get_format_name(BlockDriverState
*bs
)
5839 return bs
->drv
? bs
->drv
->format_name
: NULL
;
5842 static int qsort_strcmp(const void *a
, const void *b
)
5844 return strcmp(*(char *const *)a
, *(char *const *)b
);
5847 void bdrv_iterate_format(void (*it
)(void *opaque
, const char *name
),
5848 void *opaque
, bool read_only
)
5853 const char **formats
= NULL
;
5855 GLOBAL_STATE_CODE();
5857 QLIST_FOREACH(drv
, &bdrv_drivers
, list
) {
5858 if (drv
->format_name
) {
5862 if (use_bdrv_whitelist
&& !bdrv_is_whitelisted(drv
, read_only
)) {
5866 while (formats
&& i
&& !found
) {
5867 found
= !strcmp(formats
[--i
], drv
->format_name
);
5871 formats
= g_renew(const char *, formats
, count
+ 1);
5872 formats
[count
++] = drv
->format_name
;
5877 for (i
= 0; i
< (int)ARRAY_SIZE(block_driver_modules
); i
++) {
5878 const char *format_name
= block_driver_modules
[i
].format_name
;
5884 if (use_bdrv_whitelist
&&
5885 !bdrv_format_is_whitelisted(format_name
, read_only
)) {
5889 while (formats
&& j
&& !found
) {
5890 found
= !strcmp(formats
[--j
], format_name
);
5894 formats
= g_renew(const char *, formats
, count
+ 1);
5895 formats
[count
++] = format_name
;
5900 qsort(formats
, count
, sizeof(formats
[0]), qsort_strcmp
);
5902 for (i
= 0; i
< count
; i
++) {
5903 it(opaque
, formats
[i
]);
5909 /* This function is to find a node in the bs graph */
5910 BlockDriverState
*bdrv_find_node(const char *node_name
)
5912 BlockDriverState
*bs
;
5915 GLOBAL_STATE_CODE();
5917 QTAILQ_FOREACH(bs
, &graph_bdrv_states
, node_list
) {
5918 if (!strcmp(node_name
, bs
->node_name
)) {
5925 /* Put this QMP function here so it can access the static graph_bdrv_states. */
5926 BlockDeviceInfoList
*bdrv_named_nodes_list(bool flat
,
5929 BlockDeviceInfoList
*list
;
5930 BlockDriverState
*bs
;
5932 GLOBAL_STATE_CODE();
5935 QTAILQ_FOREACH(bs
, &graph_bdrv_states
, node_list
) {
5936 BlockDeviceInfo
*info
= bdrv_block_device_info(NULL
, bs
, flat
, errp
);
5938 qapi_free_BlockDeviceInfoList(list
);
5941 QAPI_LIST_PREPEND(list
, info
);
5947 typedef struct XDbgBlockGraphConstructor
{
5948 XDbgBlockGraph
*graph
;
5949 GHashTable
*graph_nodes
;
5950 } XDbgBlockGraphConstructor
;
5952 static XDbgBlockGraphConstructor
*xdbg_graph_new(void)
5954 XDbgBlockGraphConstructor
*gr
= g_new(XDbgBlockGraphConstructor
, 1);
5956 gr
->graph
= g_new0(XDbgBlockGraph
, 1);
5957 gr
->graph_nodes
= g_hash_table_new(NULL
, NULL
);
5962 static XDbgBlockGraph
*xdbg_graph_finalize(XDbgBlockGraphConstructor
*gr
)
5964 XDbgBlockGraph
*graph
= gr
->graph
;
5966 g_hash_table_destroy(gr
->graph_nodes
);
5972 static uintptr_t xdbg_graph_node_num(XDbgBlockGraphConstructor
*gr
, void *node
)
5974 uintptr_t ret
= (uintptr_t)g_hash_table_lookup(gr
->graph_nodes
, node
);
5981 * Start counting from 1, not 0, because 0 interferes with not-found (NULL)
5982 * answer of g_hash_table_lookup.
5984 ret
= g_hash_table_size(gr
->graph_nodes
) + 1;
5985 g_hash_table_insert(gr
->graph_nodes
, node
, (void *)ret
);
5990 static void xdbg_graph_add_node(XDbgBlockGraphConstructor
*gr
, void *node
,
5991 XDbgBlockGraphNodeType type
, const char *name
)
5993 XDbgBlockGraphNode
*n
;
5995 n
= g_new0(XDbgBlockGraphNode
, 1);
5997 n
->id
= xdbg_graph_node_num(gr
, node
);
5999 n
->name
= g_strdup(name
);
6001 QAPI_LIST_PREPEND(gr
->graph
->nodes
, n
);
6004 static void xdbg_graph_add_edge(XDbgBlockGraphConstructor
*gr
, void *parent
,
6005 const BdrvChild
*child
)
6007 BlockPermission qapi_perm
;
6008 XDbgBlockGraphEdge
*edge
;
6009 GLOBAL_STATE_CODE();
6011 edge
= g_new0(XDbgBlockGraphEdge
, 1);
6013 edge
->parent
= xdbg_graph_node_num(gr
, parent
);
6014 edge
->child
= xdbg_graph_node_num(gr
, child
->bs
);
6015 edge
->name
= g_strdup(child
->name
);
6017 for (qapi_perm
= 0; qapi_perm
< BLOCK_PERMISSION__MAX
; qapi_perm
++) {
6018 uint64_t flag
= bdrv_qapi_perm_to_blk_perm(qapi_perm
);
6020 if (flag
& child
->perm
) {
6021 QAPI_LIST_PREPEND(edge
->perm
, qapi_perm
);
6023 if (flag
& child
->shared_perm
) {
6024 QAPI_LIST_PREPEND(edge
->shared_perm
, qapi_perm
);
6028 QAPI_LIST_PREPEND(gr
->graph
->edges
, edge
);
6032 XDbgBlockGraph
*bdrv_get_xdbg_block_graph(Error
**errp
)
6036 BlockDriverState
*bs
;
6038 XDbgBlockGraphConstructor
*gr
= xdbg_graph_new();
6040 GLOBAL_STATE_CODE();
6042 for (blk
= blk_all_next(NULL
); blk
; blk
= blk_all_next(blk
)) {
6043 char *allocated_name
= NULL
;
6044 const char *name
= blk_name(blk
);
6047 name
= allocated_name
= blk_get_attached_dev_id(blk
);
6049 xdbg_graph_add_node(gr
, blk
, X_DBG_BLOCK_GRAPH_NODE_TYPE_BLOCK_BACKEND
,
6051 g_free(allocated_name
);
6052 if (blk_root(blk
)) {
6053 xdbg_graph_add_edge(gr
, blk
, blk_root(blk
));
6057 WITH_JOB_LOCK_GUARD() {
6058 for (job
= block_job_next_locked(NULL
); job
;
6059 job
= block_job_next_locked(job
)) {
6062 xdbg_graph_add_node(gr
, job
, X_DBG_BLOCK_GRAPH_NODE_TYPE_BLOCK_JOB
,
6064 for (el
= job
->nodes
; el
; el
= el
->next
) {
6065 xdbg_graph_add_edge(gr
, job
, (BdrvChild
*)el
->data
);
6070 QTAILQ_FOREACH(bs
, &graph_bdrv_states
, node_list
) {
6071 xdbg_graph_add_node(gr
, bs
, X_DBG_BLOCK_GRAPH_NODE_TYPE_BLOCK_DRIVER
,
6073 QLIST_FOREACH(child
, &bs
->children
, next
) {
6074 xdbg_graph_add_edge(gr
, bs
, child
);
6078 return xdbg_graph_finalize(gr
);
6081 BlockDriverState
*bdrv_lookup_bs(const char *device
,
6082 const char *node_name
,
6086 BlockDriverState
*bs
;
6088 GLOBAL_STATE_CODE();
6091 blk
= blk_by_name(device
);
6096 error_setg(errp
, "Device '%s' has no medium", device
);
6104 bs
= bdrv_find_node(node_name
);
6111 error_setg(errp
, "Cannot find device=\'%s\' nor node-name=\'%s\'",
6112 device
? device
: "",
6113 node_name
? node_name
: "");
6117 /* If 'base' is in the same chain as 'top', return true. Otherwise,
6118 * return false. If either argument is NULL, return false. */
6119 bool bdrv_chain_contains(BlockDriverState
*top
, BlockDriverState
*base
)
6122 GLOBAL_STATE_CODE();
6124 while (top
&& top
!= base
) {
6125 top
= bdrv_filter_or_cow_bs(top
);
6131 BlockDriverState
*bdrv_next_node(BlockDriverState
*bs
)
6133 GLOBAL_STATE_CODE();
6135 return QTAILQ_FIRST(&graph_bdrv_states
);
6137 return QTAILQ_NEXT(bs
, node_list
);
6140 BlockDriverState
*bdrv_next_all_states(BlockDriverState
*bs
)
6142 GLOBAL_STATE_CODE();
6144 return QTAILQ_FIRST(&all_bdrv_states
);
6146 return QTAILQ_NEXT(bs
, bs_list
);
6149 const char *bdrv_get_node_name(const BlockDriverState
*bs
)
6152 return bs
->node_name
;
6155 const char *bdrv_get_parent_name(const BlockDriverState
*bs
)
6161 /* If multiple parents have a name, just pick the first one. */
6162 QLIST_FOREACH(c
, &bs
->parents
, next_parent
) {
6163 if (c
->klass
->get_name
) {
6164 name
= c
->klass
->get_name(c
);
6165 if (name
&& *name
) {
6174 /* TODO check what callers really want: bs->node_name or blk_name() */
6175 const char *bdrv_get_device_name(const BlockDriverState
*bs
)
6178 return bdrv_get_parent_name(bs
) ?: "";
6181 /* This can be used to identify nodes that might not have a device
6182 * name associated. Since node and device names live in the same
6183 * namespace, the result is unambiguous. The exception is if both are
6184 * absent, then this returns an empty (non-null) string. */
6185 const char *bdrv_get_device_or_node_name(const BlockDriverState
*bs
)
6188 return bdrv_get_parent_name(bs
) ?: bs
->node_name
;
6191 int bdrv_get_flags(BlockDriverState
*bs
)
6194 return bs
->open_flags
;
6197 int bdrv_has_zero_init_1(BlockDriverState
*bs
)
6199 GLOBAL_STATE_CODE();
6203 int bdrv_has_zero_init(BlockDriverState
*bs
)
6205 BlockDriverState
*filtered
;
6206 GLOBAL_STATE_CODE();
6212 /* If BS is a copy on write image, it is initialized to
6213 the contents of the base image, which may not be zeroes. */
6214 if (bdrv_cow_child(bs
)) {
6217 if (bs
->drv
->bdrv_has_zero_init
) {
6218 return bs
->drv
->bdrv_has_zero_init(bs
);
6221 filtered
= bdrv_filter_bs(bs
);
6223 return bdrv_has_zero_init(filtered
);
6230 bool bdrv_can_write_zeroes_with_unmap(BlockDriverState
*bs
)
6233 if (!(bs
->open_flags
& BDRV_O_UNMAP
)) {
6237 return bs
->supported_zero_flags
& BDRV_REQ_MAY_UNMAP
;
6240 void bdrv_get_backing_filename(BlockDriverState
*bs
,
6241 char *filename
, int filename_size
)
6244 pstrcpy(filename
, filename_size
, bs
->backing_file
);
6247 int bdrv_get_info(BlockDriverState
*bs
, BlockDriverInfo
*bdi
)
6250 BlockDriver
*drv
= bs
->drv
;
6252 /* if bs->drv == NULL, bs is closed, so there's nothing to do here */
6256 if (!drv
->bdrv_get_info
) {
6257 BlockDriverState
*filtered
= bdrv_filter_bs(bs
);
6259 return bdrv_get_info(filtered
, bdi
);
6263 memset(bdi
, 0, sizeof(*bdi
));
6264 ret
= drv
->bdrv_get_info(bs
, bdi
);
6269 if (bdi
->cluster_size
> BDRV_MAX_ALIGNMENT
) {
6276 ImageInfoSpecific
*bdrv_get_specific_info(BlockDriverState
*bs
,
6279 BlockDriver
*drv
= bs
->drv
;
6281 if (drv
&& drv
->bdrv_get_specific_info
) {
6282 return drv
->bdrv_get_specific_info(bs
, errp
);
6287 BlockStatsSpecific
*bdrv_get_specific_stats(BlockDriverState
*bs
)
6289 BlockDriver
*drv
= bs
->drv
;
6291 if (!drv
|| !drv
->bdrv_get_specific_stats
) {
6294 return drv
->bdrv_get_specific_stats(bs
);
6297 void bdrv_debug_event(BlockDriverState
*bs
, BlkdebugEvent event
)
6300 if (!bs
|| !bs
->drv
|| !bs
->drv
->bdrv_debug_event
) {
6304 bs
->drv
->bdrv_debug_event(bs
, event
);
6307 static BlockDriverState
*bdrv_find_debug_node(BlockDriverState
*bs
)
6309 GLOBAL_STATE_CODE();
6310 while (bs
&& bs
->drv
&& !bs
->drv
->bdrv_debug_breakpoint
) {
6311 bs
= bdrv_primary_bs(bs
);
6314 if (bs
&& bs
->drv
&& bs
->drv
->bdrv_debug_breakpoint
) {
6315 assert(bs
->drv
->bdrv_debug_remove_breakpoint
);
6322 int bdrv_debug_breakpoint(BlockDriverState
*bs
, const char *event
,
6325 GLOBAL_STATE_CODE();
6326 bs
= bdrv_find_debug_node(bs
);
6328 return bs
->drv
->bdrv_debug_breakpoint(bs
, event
, tag
);
6334 int bdrv_debug_remove_breakpoint(BlockDriverState
*bs
, const char *tag
)
6336 GLOBAL_STATE_CODE();
6337 bs
= bdrv_find_debug_node(bs
);
6339 return bs
->drv
->bdrv_debug_remove_breakpoint(bs
, tag
);
6345 int bdrv_debug_resume(BlockDriverState
*bs
, const char *tag
)
6347 GLOBAL_STATE_CODE();
6348 while (bs
&& (!bs
->drv
|| !bs
->drv
->bdrv_debug_resume
)) {
6349 bs
= bdrv_primary_bs(bs
);
6352 if (bs
&& bs
->drv
&& bs
->drv
->bdrv_debug_resume
) {
6353 return bs
->drv
->bdrv_debug_resume(bs
, tag
);
6359 bool bdrv_debug_is_suspended(BlockDriverState
*bs
, const char *tag
)
6361 GLOBAL_STATE_CODE();
6362 while (bs
&& bs
->drv
&& !bs
->drv
->bdrv_debug_is_suspended
) {
6363 bs
= bdrv_primary_bs(bs
);
6366 if (bs
&& bs
->drv
&& bs
->drv
->bdrv_debug_is_suspended
) {
6367 return bs
->drv
->bdrv_debug_is_suspended(bs
, tag
);
6373 /* backing_file can either be relative, or absolute, or a protocol. If it is
6374 * relative, it must be relative to the chain. So, passing in bs->filename
6375 * from a BDS as backing_file should not be done, as that may be relative to
6376 * the CWD rather than the chain. */
6377 BlockDriverState
*bdrv_find_backing_image(BlockDriverState
*bs
,
6378 const char *backing_file
)
6380 char *filename_full
= NULL
;
6381 char *backing_file_full
= NULL
;
6382 char *filename_tmp
= NULL
;
6383 int is_protocol
= 0;
6384 bool filenames_refreshed
= false;
6385 BlockDriverState
*curr_bs
= NULL
;
6386 BlockDriverState
*retval
= NULL
;
6387 BlockDriverState
*bs_below
;
6389 GLOBAL_STATE_CODE();
6391 if (!bs
|| !bs
->drv
|| !backing_file
) {
6395 filename_full
= g_malloc(PATH_MAX
);
6396 backing_file_full
= g_malloc(PATH_MAX
);
6398 is_protocol
= path_has_protocol(backing_file
);
6401 * Being largely a legacy function, skip any filters here
6402 * (because filters do not have normal filenames, so they cannot
6403 * match anyway; and allowing json:{} filenames is a bit out of
6406 for (curr_bs
= bdrv_skip_filters(bs
);
6407 bdrv_cow_child(curr_bs
) != NULL
;
6410 bs_below
= bdrv_backing_chain_next(curr_bs
);
6412 if (bdrv_backing_overridden(curr_bs
)) {
6414 * If the backing file was overridden, we can only compare
6415 * directly against the backing node's filename.
6418 if (!filenames_refreshed
) {
6420 * This will automatically refresh all of the
6421 * filenames in the rest of the backing chain, so we
6422 * only need to do this once.
6424 bdrv_refresh_filename(bs_below
);
6425 filenames_refreshed
= true;
6428 if (strcmp(backing_file
, bs_below
->filename
) == 0) {
6432 } else if (is_protocol
|| path_has_protocol(curr_bs
->backing_file
)) {
6434 * If either of the filename paths is actually a protocol, then
6435 * compare unmodified paths; otherwise make paths relative.
6437 char *backing_file_full_ret
;
6439 if (strcmp(backing_file
, curr_bs
->backing_file
) == 0) {
6443 /* Also check against the full backing filename for the image */
6444 backing_file_full_ret
= bdrv_get_full_backing_filename(curr_bs
,
6446 if (backing_file_full_ret
) {
6447 bool equal
= strcmp(backing_file
, backing_file_full_ret
) == 0;
6448 g_free(backing_file_full_ret
);
6455 /* If not an absolute filename path, make it relative to the current
6456 * image's filename path */
6457 filename_tmp
= bdrv_make_absolute_filename(curr_bs
, backing_file
,
6459 /* We are going to compare canonicalized absolute pathnames */
6460 if (!filename_tmp
|| !realpath(filename_tmp
, filename_full
)) {
6461 g_free(filename_tmp
);
6464 g_free(filename_tmp
);
6466 /* We need to make sure the backing filename we are comparing against
6467 * is relative to the current image filename (or absolute) */
6468 filename_tmp
= bdrv_get_full_backing_filename(curr_bs
, NULL
);
6469 if (!filename_tmp
|| !realpath(filename_tmp
, backing_file_full
)) {
6470 g_free(filename_tmp
);
6473 g_free(filename_tmp
);
6475 if (strcmp(backing_file_full
, filename_full
) == 0) {
6482 g_free(filename_full
);
6483 g_free(backing_file_full
);
6487 void bdrv_init(void)
6489 #ifdef CONFIG_BDRV_WHITELIST_TOOLS
6490 use_bdrv_whitelist
= 1;
6492 module_call_init(MODULE_INIT_BLOCK
);
6495 void bdrv_init_with_whitelist(void)
6497 use_bdrv_whitelist
= 1;
6501 int bdrv_activate(BlockDriverState
*bs
, Error
**errp
)
6503 BdrvChild
*child
, *parent
;
6504 Error
*local_err
= NULL
;
6506 BdrvDirtyBitmap
*bm
;
6508 GLOBAL_STATE_CODE();
6514 QLIST_FOREACH(child
, &bs
->children
, next
) {
6515 bdrv_activate(child
->bs
, &local_err
);
6517 error_propagate(errp
, local_err
);
6523 * Update permissions, they may differ for inactive nodes.
6525 * Note that the required permissions of inactive images are always a
6526 * subset of the permissions required after activating the image. This
6527 * allows us to just get the permissions upfront without restricting
6528 * bdrv_co_invalidate_cache().
6530 * It also means that in error cases, we don't have to try and revert to
6531 * the old permissions (which is an operation that could fail, too). We can
6532 * just keep the extended permissions for the next time that an activation
6533 * of the image is tried.
6535 if (bs
->open_flags
& BDRV_O_INACTIVE
) {
6536 bs
->open_flags
&= ~BDRV_O_INACTIVE
;
6537 ret
= bdrv_refresh_perms(bs
, errp
);
6539 bs
->open_flags
|= BDRV_O_INACTIVE
;
6543 ret
= bdrv_invalidate_cache(bs
, errp
);
6545 bs
->open_flags
|= BDRV_O_INACTIVE
;
6549 FOR_EACH_DIRTY_BITMAP(bs
, bm
) {
6550 bdrv_dirty_bitmap_skip_store(bm
, false);
6553 ret
= refresh_total_sectors(bs
, bs
->total_sectors
);
6555 bs
->open_flags
|= BDRV_O_INACTIVE
;
6556 error_setg_errno(errp
, -ret
, "Could not refresh total sector count");
6561 QLIST_FOREACH(parent
, &bs
->parents
, next_parent
) {
6562 if (parent
->klass
->activate
) {
6563 parent
->klass
->activate(parent
, &local_err
);
6565 bs
->open_flags
|= BDRV_O_INACTIVE
;
6566 error_propagate(errp
, local_err
);
6575 int coroutine_fn
bdrv_co_invalidate_cache(BlockDriverState
*bs
, Error
**errp
)
6577 Error
*local_err
= NULL
;
6580 assert(!(bs
->open_flags
& BDRV_O_INACTIVE
));
6582 if (bs
->drv
->bdrv_co_invalidate_cache
) {
6583 bs
->drv
->bdrv_co_invalidate_cache(bs
, &local_err
);
6585 error_propagate(errp
, local_err
);
6593 void bdrv_activate_all(Error
**errp
)
6595 BlockDriverState
*bs
;
6596 BdrvNextIterator it
;
6598 GLOBAL_STATE_CODE();
6600 for (bs
= bdrv_first(&it
); bs
; bs
= bdrv_next(&it
)) {
6601 AioContext
*aio_context
= bdrv_get_aio_context(bs
);
6604 aio_context_acquire(aio_context
);
6605 ret
= bdrv_activate(bs
, errp
);
6606 aio_context_release(aio_context
);
6608 bdrv_next_cleanup(&it
);
6614 static bool bdrv_has_bds_parent(BlockDriverState
*bs
, bool only_active
)
6617 GLOBAL_STATE_CODE();
6619 QLIST_FOREACH(parent
, &bs
->parents
, next_parent
) {
6620 if (parent
->klass
->parent_is_bds
) {
6621 BlockDriverState
*parent_bs
= parent
->opaque
;
6622 if (!only_active
|| !(parent_bs
->open_flags
& BDRV_O_INACTIVE
)) {
6631 static int bdrv_inactivate_recurse(BlockDriverState
*bs
)
6633 BdrvChild
*child
, *parent
;
6635 uint64_t cumulative_perms
, cumulative_shared_perms
;
6637 GLOBAL_STATE_CODE();
6643 /* Make sure that we don't inactivate a child before its parent.
6644 * It will be covered by recursion from the yet active parent. */
6645 if (bdrv_has_bds_parent(bs
, true)) {
6649 assert(!(bs
->open_flags
& BDRV_O_INACTIVE
));
6651 /* Inactivate this node */
6652 if (bs
->drv
->bdrv_inactivate
) {
6653 ret
= bs
->drv
->bdrv_inactivate(bs
);
6659 QLIST_FOREACH(parent
, &bs
->parents
, next_parent
) {
6660 if (parent
->klass
->inactivate
) {
6661 ret
= parent
->klass
->inactivate(parent
);
6668 bdrv_get_cumulative_perm(bs
, &cumulative_perms
,
6669 &cumulative_shared_perms
);
6670 if (cumulative_perms
& (BLK_PERM_WRITE
| BLK_PERM_WRITE_UNCHANGED
)) {
6671 /* Our inactive parents still need write access. Inactivation failed. */
6675 bs
->open_flags
|= BDRV_O_INACTIVE
;
6678 * Update permissions, they may differ for inactive nodes.
6679 * We only tried to loosen restrictions, so errors are not fatal, ignore
6682 bdrv_refresh_perms(bs
, NULL
);
6684 /* Recursively inactivate children */
6685 QLIST_FOREACH(child
, &bs
->children
, next
) {
6686 ret
= bdrv_inactivate_recurse(child
->bs
);
6695 int bdrv_inactivate_all(void)
6697 BlockDriverState
*bs
= NULL
;
6698 BdrvNextIterator it
;
6700 GSList
*aio_ctxs
= NULL
, *ctx
;
6702 GLOBAL_STATE_CODE();
6704 for (bs
= bdrv_first(&it
); bs
; bs
= bdrv_next(&it
)) {
6705 AioContext
*aio_context
= bdrv_get_aio_context(bs
);
6707 if (!g_slist_find(aio_ctxs
, aio_context
)) {
6708 aio_ctxs
= g_slist_prepend(aio_ctxs
, aio_context
);
6709 aio_context_acquire(aio_context
);
6713 for (bs
= bdrv_first(&it
); bs
; bs
= bdrv_next(&it
)) {
6714 /* Nodes with BDS parents are covered by recursion from the last
6715 * parent that gets inactivated. Don't inactivate them a second
6716 * time if that has already happened. */
6717 if (bdrv_has_bds_parent(bs
, false)) {
6720 ret
= bdrv_inactivate_recurse(bs
);
6722 bdrv_next_cleanup(&it
);
6728 for (ctx
= aio_ctxs
; ctx
!= NULL
; ctx
= ctx
->next
) {
6729 AioContext
*aio_context
= ctx
->data
;
6730 aio_context_release(aio_context
);
6732 g_slist_free(aio_ctxs
);
6737 /**************************************************************/
6738 /* removable device support */
6741 * Return TRUE if the media is present
6743 bool bdrv_is_inserted(BlockDriverState
*bs
)
6745 BlockDriver
*drv
= bs
->drv
;
6752 if (drv
->bdrv_is_inserted
) {
6753 return drv
->bdrv_is_inserted(bs
);
6755 QLIST_FOREACH(child
, &bs
->children
, next
) {
6756 if (!bdrv_is_inserted(child
->bs
)) {
6764 * If eject_flag is TRUE, eject the media. Otherwise, close the tray
6766 void bdrv_eject(BlockDriverState
*bs
, bool eject_flag
)
6768 BlockDriver
*drv
= bs
->drv
;
6771 if (drv
&& drv
->bdrv_eject
) {
6772 drv
->bdrv_eject(bs
, eject_flag
);
6777 * Lock or unlock the media (if it is locked, the user won't be able
6778 * to eject it manually).
6780 void bdrv_lock_medium(BlockDriverState
*bs
, bool locked
)
6782 BlockDriver
*drv
= bs
->drv
;
6784 trace_bdrv_lock_medium(bs
, locked
);
6786 if (drv
&& drv
->bdrv_lock_medium
) {
6787 drv
->bdrv_lock_medium(bs
, locked
);
6791 /* Get a reference to bs */
6792 void bdrv_ref(BlockDriverState
*bs
)
6794 GLOBAL_STATE_CODE();
6798 /* Release a previously grabbed reference to bs.
6799 * If after releasing, reference count is zero, the BlockDriverState is
6801 void bdrv_unref(BlockDriverState
*bs
)
6803 GLOBAL_STATE_CODE();
6807 assert(bs
->refcnt
> 0);
6808 if (--bs
->refcnt
== 0) {
6813 struct BdrvOpBlocker
{
6815 QLIST_ENTRY(BdrvOpBlocker
) list
;
6818 bool bdrv_op_is_blocked(BlockDriverState
*bs
, BlockOpType op
, Error
**errp
)
6820 BdrvOpBlocker
*blocker
;
6821 GLOBAL_STATE_CODE();
6822 assert((int) op
>= 0 && op
< BLOCK_OP_TYPE_MAX
);
6823 if (!QLIST_EMPTY(&bs
->op_blockers
[op
])) {
6824 blocker
= QLIST_FIRST(&bs
->op_blockers
[op
]);
6825 error_propagate_prepend(errp
, error_copy(blocker
->reason
),
6826 "Node '%s' is busy: ",
6827 bdrv_get_device_or_node_name(bs
));
6833 void bdrv_op_block(BlockDriverState
*bs
, BlockOpType op
, Error
*reason
)
6835 BdrvOpBlocker
*blocker
;
6836 GLOBAL_STATE_CODE();
6837 assert((int) op
>= 0 && op
< BLOCK_OP_TYPE_MAX
);
6839 blocker
= g_new0(BdrvOpBlocker
, 1);
6840 blocker
->reason
= reason
;
6841 QLIST_INSERT_HEAD(&bs
->op_blockers
[op
], blocker
, list
);
6844 void bdrv_op_unblock(BlockDriverState
*bs
, BlockOpType op
, Error
*reason
)
6846 BdrvOpBlocker
*blocker
, *next
;
6847 GLOBAL_STATE_CODE();
6848 assert((int) op
>= 0 && op
< BLOCK_OP_TYPE_MAX
);
6849 QLIST_FOREACH_SAFE(blocker
, &bs
->op_blockers
[op
], list
, next
) {
6850 if (blocker
->reason
== reason
) {
6851 QLIST_REMOVE(blocker
, list
);
6857 void bdrv_op_block_all(BlockDriverState
*bs
, Error
*reason
)
6860 GLOBAL_STATE_CODE();
6861 for (i
= 0; i
< BLOCK_OP_TYPE_MAX
; i
++) {
6862 bdrv_op_block(bs
, i
, reason
);
6866 void bdrv_op_unblock_all(BlockDriverState
*bs
, Error
*reason
)
6869 GLOBAL_STATE_CODE();
6870 for (i
= 0; i
< BLOCK_OP_TYPE_MAX
; i
++) {
6871 bdrv_op_unblock(bs
, i
, reason
);
6875 bool bdrv_op_blocker_is_empty(BlockDriverState
*bs
)
6878 GLOBAL_STATE_CODE();
6879 for (i
= 0; i
< BLOCK_OP_TYPE_MAX
; i
++) {
6880 if (!QLIST_EMPTY(&bs
->op_blockers
[i
])) {
6887 void bdrv_img_create(const char *filename
, const char *fmt
,
6888 const char *base_filename
, const char *base_fmt
,
6889 char *options
, uint64_t img_size
, int flags
, bool quiet
,
6892 QemuOptsList
*create_opts
= NULL
;
6893 QemuOpts
*opts
= NULL
;
6894 const char *backing_fmt
, *backing_file
;
6896 BlockDriver
*drv
, *proto_drv
;
6897 Error
*local_err
= NULL
;
6900 GLOBAL_STATE_CODE();
6902 /* Find driver and parse its options */
6903 drv
= bdrv_find_format(fmt
);
6905 error_setg(errp
, "Unknown file format '%s'", fmt
);
6909 proto_drv
= bdrv_find_protocol(filename
, true, errp
);
6914 if (!drv
->create_opts
) {
6915 error_setg(errp
, "Format driver '%s' does not support image creation",
6920 if (!proto_drv
->create_opts
) {
6921 error_setg(errp
, "Protocol driver '%s' does not support image creation",
6922 proto_drv
->format_name
);
6926 /* Create parameter list */
6927 create_opts
= qemu_opts_append(create_opts
, drv
->create_opts
);
6928 create_opts
= qemu_opts_append(create_opts
, proto_drv
->create_opts
);
6930 opts
= qemu_opts_create(create_opts
, NULL
, 0, &error_abort
);
6932 /* Parse -o options */
6934 if (!qemu_opts_do_parse(opts
, options
, NULL
, errp
)) {
6939 if (!qemu_opt_get(opts
, BLOCK_OPT_SIZE
)) {
6940 qemu_opt_set_number(opts
, BLOCK_OPT_SIZE
, img_size
, &error_abort
);
6941 } else if (img_size
!= UINT64_C(-1)) {
6942 error_setg(errp
, "The image size must be specified only once");
6946 if (base_filename
) {
6947 if (!qemu_opt_set(opts
, BLOCK_OPT_BACKING_FILE
, base_filename
,
6949 error_setg(errp
, "Backing file not supported for file format '%s'",
6956 if (!qemu_opt_set(opts
, BLOCK_OPT_BACKING_FMT
, base_fmt
, NULL
)) {
6957 error_setg(errp
, "Backing file format not supported for file "
6958 "format '%s'", fmt
);
6963 backing_file
= qemu_opt_get(opts
, BLOCK_OPT_BACKING_FILE
);
6965 if (!strcmp(filename
, backing_file
)) {
6966 error_setg(errp
, "Error: Trying to create an image with the "
6967 "same filename as the backing file");
6970 if (backing_file
[0] == '\0') {
6971 error_setg(errp
, "Expected backing file name, got empty string");
6976 backing_fmt
= qemu_opt_get(opts
, BLOCK_OPT_BACKING_FMT
);
6978 /* The size for the image must always be specified, unless we have a backing
6979 * file and we have not been forbidden from opening it. */
6980 size
= qemu_opt_get_size(opts
, BLOCK_OPT_SIZE
, img_size
);
6981 if (backing_file
&& !(flags
& BDRV_O_NO_BACKING
)) {
6982 BlockDriverState
*bs
;
6985 QDict
*backing_options
= NULL
;
6988 bdrv_get_full_backing_filename_from_filename(filename
, backing_file
,
6993 assert(full_backing
);
6996 * No need to do I/O here, which allows us to open encrypted
6997 * backing images without needing the secret
7000 back_flags
&= ~(BDRV_O_RDWR
| BDRV_O_SNAPSHOT
| BDRV_O_NO_BACKING
);
7001 back_flags
|= BDRV_O_NO_IO
;
7003 backing_options
= qdict_new();
7005 qdict_put_str(backing_options
, "driver", backing_fmt
);
7007 qdict_put_bool(backing_options
, BDRV_OPT_FORCE_SHARE
, true);
7009 bs
= bdrv_open(full_backing
, NULL
, backing_options
, back_flags
,
7011 g_free(full_backing
);
7013 error_append_hint(&local_err
, "Could not open backing image.\n");
7017 error_setg(&local_err
,
7018 "Backing file specified without backing format");
7019 error_append_hint(&local_err
, "Detected format of %s.",
7020 bs
->drv
->format_name
);
7024 /* Opened BS, have no size */
7025 size
= bdrv_getlength(bs
);
7027 error_setg_errno(errp
, -size
, "Could not get size of '%s'",
7032 qemu_opt_set_number(opts
, BLOCK_OPT_SIZE
, size
, &error_abort
);
7036 /* (backing_file && !(flags & BDRV_O_NO_BACKING)) */
7037 } else if (backing_file
&& !backing_fmt
) {
7038 error_setg(&local_err
,
7039 "Backing file specified without backing format");
7044 error_setg(errp
, "Image creation needs a size parameter");
7049 printf("Formatting '%s', fmt=%s ", filename
, fmt
);
7050 qemu_opts_print(opts
, " ");
7055 ret
= bdrv_create(drv
, filename
, opts
, &local_err
);
7057 if (ret
== -EFBIG
) {
7058 /* This is generally a better message than whatever the driver would
7059 * deliver (especially because of the cluster_size_hint), since that
7060 * is most probably not much different from "image too large". */
7061 const char *cluster_size_hint
= "";
7062 if (qemu_opt_get_size(opts
, BLOCK_OPT_CLUSTER_SIZE
, 0)) {
7063 cluster_size_hint
= " (try using a larger cluster size)";
7065 error_setg(errp
, "The image size is too large for file format '%s'"
7066 "%s", fmt
, cluster_size_hint
);
7067 error_free(local_err
);
7072 qemu_opts_del(opts
);
7073 qemu_opts_free(create_opts
);
7074 error_propagate(errp
, local_err
);
7077 AioContext
*bdrv_get_aio_context(BlockDriverState
*bs
)
7080 return bs
? bs
->aio_context
: qemu_get_aio_context();
7083 AioContext
*coroutine_fn
bdrv_co_enter(BlockDriverState
*bs
)
7085 Coroutine
*self
= qemu_coroutine_self();
7086 AioContext
*old_ctx
= qemu_coroutine_get_aio_context(self
);
7087 AioContext
*new_ctx
;
7091 * Increase bs->in_flight to ensure that this operation is completed before
7092 * moving the node to a different AioContext. Read new_ctx only afterwards.
7094 bdrv_inc_in_flight(bs
);
7096 new_ctx
= bdrv_get_aio_context(bs
);
7097 aio_co_reschedule_self(new_ctx
);
7101 void coroutine_fn
bdrv_co_leave(BlockDriverState
*bs
, AioContext
*old_ctx
)
7104 aio_co_reschedule_self(old_ctx
);
7105 bdrv_dec_in_flight(bs
);
7108 void coroutine_fn
bdrv_co_lock(BlockDriverState
*bs
)
7110 AioContext
*ctx
= bdrv_get_aio_context(bs
);
7112 /* In the main thread, bs->aio_context won't change concurrently */
7113 assert(qemu_get_current_aio_context() == qemu_get_aio_context());
7116 * We're in coroutine context, so we already hold the lock of the main
7117 * loop AioContext. Don't lock it twice to avoid deadlocks.
7119 assert(qemu_in_coroutine());
7120 if (ctx
!= qemu_get_aio_context()) {
7121 aio_context_acquire(ctx
);
7125 void coroutine_fn
bdrv_co_unlock(BlockDriverState
*bs
)
7127 AioContext
*ctx
= bdrv_get_aio_context(bs
);
7129 assert(qemu_in_coroutine());
7130 if (ctx
!= qemu_get_aio_context()) {
7131 aio_context_release(ctx
);
7135 void bdrv_coroutine_enter(BlockDriverState
*bs
, Coroutine
*co
)
7138 aio_co_enter(bdrv_get_aio_context(bs
), co
);
7141 static void bdrv_do_remove_aio_context_notifier(BdrvAioNotifier
*ban
)
7143 GLOBAL_STATE_CODE();
7144 QLIST_REMOVE(ban
, list
);
7148 static void bdrv_detach_aio_context(BlockDriverState
*bs
)
7150 BdrvAioNotifier
*baf
, *baf_tmp
;
7152 assert(!bs
->walking_aio_notifiers
);
7153 GLOBAL_STATE_CODE();
7154 bs
->walking_aio_notifiers
= true;
7155 QLIST_FOREACH_SAFE(baf
, &bs
->aio_notifiers
, list
, baf_tmp
) {
7157 bdrv_do_remove_aio_context_notifier(baf
);
7159 baf
->detach_aio_context(baf
->opaque
);
7162 /* Never mind iterating again to check for ->deleted. bdrv_close() will
7163 * remove remaining aio notifiers if we aren't called again.
7165 bs
->walking_aio_notifiers
= false;
7167 if (bs
->drv
&& bs
->drv
->bdrv_detach_aio_context
) {
7168 bs
->drv
->bdrv_detach_aio_context(bs
);
7171 if (bs
->quiesce_counter
) {
7172 aio_enable_external(bs
->aio_context
);
7174 assert_bdrv_graph_writable(bs
);
7175 bs
->aio_context
= NULL
;
7178 static void bdrv_attach_aio_context(BlockDriverState
*bs
,
7179 AioContext
*new_context
)
7181 BdrvAioNotifier
*ban
, *ban_tmp
;
7182 GLOBAL_STATE_CODE();
7184 if (bs
->quiesce_counter
) {
7185 aio_disable_external(new_context
);
7188 assert_bdrv_graph_writable(bs
);
7189 bs
->aio_context
= new_context
;
7191 if (bs
->drv
&& bs
->drv
->bdrv_attach_aio_context
) {
7192 bs
->drv
->bdrv_attach_aio_context(bs
, new_context
);
7195 assert(!bs
->walking_aio_notifiers
);
7196 bs
->walking_aio_notifiers
= true;
7197 QLIST_FOREACH_SAFE(ban
, &bs
->aio_notifiers
, list
, ban_tmp
) {
7199 bdrv_do_remove_aio_context_notifier(ban
);
7201 ban
->attached_aio_context(new_context
, ban
->opaque
);
7204 bs
->walking_aio_notifiers
= false;
7207 typedef struct BdrvStateSetAioContext
{
7208 AioContext
*new_ctx
;
7209 BlockDriverState
*bs
;
7210 } BdrvStateSetAioContext
;
7212 static bool bdrv_parent_change_aio_context(BdrvChild
*c
, AioContext
*ctx
,
7213 GHashTable
*visited
,
7217 GLOBAL_STATE_CODE();
7218 if (g_hash_table_contains(visited
, c
)) {
7221 g_hash_table_add(visited
, c
);
7224 * A BdrvChildClass that doesn't handle AioContext changes cannot
7225 * tolerate any AioContext changes
7227 if (!c
->klass
->change_aio_ctx
) {
7228 char *user
= bdrv_child_user_desc(c
);
7229 error_setg(errp
, "Changing iothreads is not supported by %s", user
);
7233 if (!c
->klass
->change_aio_ctx(c
, ctx
, visited
, tran
, errp
)) {
7234 assert(!errp
|| *errp
);
7240 bool bdrv_child_change_aio_context(BdrvChild
*c
, AioContext
*ctx
,
7241 GHashTable
*visited
, Transaction
*tran
,
7244 GLOBAL_STATE_CODE();
7245 if (g_hash_table_contains(visited
, c
)) {
7248 g_hash_table_add(visited
, c
);
7249 return bdrv_change_aio_context(c
->bs
, ctx
, visited
, tran
, errp
);
7252 static void bdrv_set_aio_context_clean(void *opaque
)
7254 BdrvStateSetAioContext
*state
= (BdrvStateSetAioContext
*) opaque
;
7255 BlockDriverState
*bs
= (BlockDriverState
*) state
->bs
;
7257 /* Paired with bdrv_drained_begin in bdrv_change_aio_context() */
7258 bdrv_drained_end(bs
);
7263 static void bdrv_set_aio_context_commit(void *opaque
)
7265 BdrvStateSetAioContext
*state
= (BdrvStateSetAioContext
*) opaque
;
7266 BlockDriverState
*bs
= (BlockDriverState
*) state
->bs
;
7267 AioContext
*new_context
= state
->new_ctx
;
7268 AioContext
*old_context
= bdrv_get_aio_context(bs
);
7269 assert_bdrv_graph_writable(bs
);
7272 * Take the old AioContex when detaching it from bs.
7273 * At this point, new_context lock is already acquired, and we are now
7274 * also taking old_context. This is safe as long as bdrv_detach_aio_context
7275 * does not call AIO_POLL_WHILE().
7277 if (old_context
!= qemu_get_aio_context()) {
7278 aio_context_acquire(old_context
);
7280 bdrv_detach_aio_context(bs
);
7281 if (old_context
!= qemu_get_aio_context()) {
7282 aio_context_release(old_context
);
7284 bdrv_attach_aio_context(bs
, new_context
);
7287 static TransactionActionDrv set_aio_context
= {
7288 .commit
= bdrv_set_aio_context_commit
,
7289 .clean
= bdrv_set_aio_context_clean
,
7293 * Changes the AioContext used for fd handlers, timers, and BHs by this
7294 * BlockDriverState and all its children and parents.
7296 * Must be called from the main AioContext.
7298 * The caller must own the AioContext lock for the old AioContext of bs, but it
7299 * must not own the AioContext lock for new_context (unless new_context is the
7300 * same as the current context of bs).
7302 * @visited will accumulate all visited BdrvChild objects. The caller is
7303 * responsible for freeing the list afterwards.
7305 static bool bdrv_change_aio_context(BlockDriverState
*bs
, AioContext
*ctx
,
7306 GHashTable
*visited
, Transaction
*tran
,
7310 BdrvStateSetAioContext
*state
;
7312 GLOBAL_STATE_CODE();
7314 if (bdrv_get_aio_context(bs
) == ctx
) {
7318 QLIST_FOREACH(c
, &bs
->parents
, next_parent
) {
7319 if (!bdrv_parent_change_aio_context(c
, ctx
, visited
, tran
, errp
)) {
7324 QLIST_FOREACH(c
, &bs
->children
, next
) {
7325 if (!bdrv_child_change_aio_context(c
, ctx
, visited
, tran
, errp
)) {
7330 state
= g_new(BdrvStateSetAioContext
, 1);
7331 *state
= (BdrvStateSetAioContext
) {
7336 /* Paired with bdrv_drained_end in bdrv_set_aio_context_clean() */
7337 bdrv_drained_begin(bs
);
7339 tran_add(tran
, &set_aio_context
, state
);
7345 * Change bs's and recursively all of its parents' and children's AioContext
7346 * to the given new context, returning an error if that isn't possible.
7348 * If ignore_child is not NULL, that child (and its subgraph) will not
7351 * This function still requires the caller to take the bs current
7352 * AioContext lock, otherwise draining will fail since AIO_WAIT_WHILE
7353 * assumes the lock is always held if bs is in another AioContext.
7354 * For the same reason, it temporarily also holds the new AioContext, since
7355 * bdrv_drained_end calls BDRV_POLL_WHILE that assumes the lock is taken too.
7356 * Therefore the new AioContext lock must not be taken by the caller.
7358 int bdrv_try_change_aio_context(BlockDriverState
*bs
, AioContext
*ctx
,
7359 BdrvChild
*ignore_child
, Error
**errp
)
7362 GHashTable
*visited
;
7364 AioContext
*old_context
= bdrv_get_aio_context(bs
);
7365 GLOBAL_STATE_CODE();
7368 * Recursion phase: go through all nodes of the graph.
7369 * Take care of checking that all nodes support changing AioContext
7370 * and drain them, builing a linear list of callbacks to run if everything
7371 * is successful (the transaction itself).
7374 visited
= g_hash_table_new(NULL
, NULL
);
7376 g_hash_table_add(visited
, ignore_child
);
7378 ret
= bdrv_change_aio_context(bs
, ctx
, visited
, tran
, errp
);
7379 g_hash_table_destroy(visited
);
7382 * Linear phase: go through all callbacks collected in the transaction.
7383 * Run all callbacks collected in the recursion to switch all nodes
7384 * AioContext lock (transaction commit), or undo all changes done in the
7385 * recursion (transaction abort).
7389 /* Just run clean() callbacks. No AioContext changed. */
7395 * Release old AioContext, it won't be needed anymore, as all
7396 * bdrv_drained_begin() have been called already.
7398 if (qemu_get_aio_context() != old_context
) {
7399 aio_context_release(old_context
);
7403 * Acquire new AioContext since bdrv_drained_end() is going to be called
7404 * after we switched all nodes in the new AioContext, and the function
7405 * assumes that the lock of the bs is always taken.
7407 if (qemu_get_aio_context() != ctx
) {
7408 aio_context_acquire(ctx
);
7413 if (qemu_get_aio_context() != ctx
) {
7414 aio_context_release(ctx
);
7417 /* Re-acquire the old AioContext, since the caller takes and releases it. */
7418 if (qemu_get_aio_context() != old_context
) {
7419 aio_context_acquire(old_context
);
7425 void bdrv_add_aio_context_notifier(BlockDriverState
*bs
,
7426 void (*attached_aio_context
)(AioContext
*new_context
, void *opaque
),
7427 void (*detach_aio_context
)(void *opaque
), void *opaque
)
7429 BdrvAioNotifier
*ban
= g_new(BdrvAioNotifier
, 1);
7430 *ban
= (BdrvAioNotifier
){
7431 .attached_aio_context
= attached_aio_context
,
7432 .detach_aio_context
= detach_aio_context
,
7435 GLOBAL_STATE_CODE();
7437 QLIST_INSERT_HEAD(&bs
->aio_notifiers
, ban
, list
);
7440 void bdrv_remove_aio_context_notifier(BlockDriverState
*bs
,
7441 void (*attached_aio_context
)(AioContext
*,
7443 void (*detach_aio_context
)(void *),
7446 BdrvAioNotifier
*ban
, *ban_next
;
7447 GLOBAL_STATE_CODE();
7449 QLIST_FOREACH_SAFE(ban
, &bs
->aio_notifiers
, list
, ban_next
) {
7450 if (ban
->attached_aio_context
== attached_aio_context
&&
7451 ban
->detach_aio_context
== detach_aio_context
&&
7452 ban
->opaque
== opaque
&&
7453 ban
->deleted
== false)
7455 if (bs
->walking_aio_notifiers
) {
7456 ban
->deleted
= true;
7458 bdrv_do_remove_aio_context_notifier(ban
);
7467 int bdrv_amend_options(BlockDriverState
*bs
, QemuOpts
*opts
,
7468 BlockDriverAmendStatusCB
*status_cb
, void *cb_opaque
,
7472 GLOBAL_STATE_CODE();
7474 error_setg(errp
, "Node is ejected");
7477 if (!bs
->drv
->bdrv_amend_options
) {
7478 error_setg(errp
, "Block driver '%s' does not support option amendment",
7479 bs
->drv
->format_name
);
7482 return bs
->drv
->bdrv_amend_options(bs
, opts
, status_cb
,
7483 cb_opaque
, force
, errp
);
7487 * This function checks whether the given @to_replace is allowed to be
7488 * replaced by a node that always shows the same data as @bs. This is
7489 * used for example to verify whether the mirror job can replace
7490 * @to_replace by the target mirrored from @bs.
7491 * To be replaceable, @bs and @to_replace may either be guaranteed to
7492 * always show the same data (because they are only connected through
7493 * filters), or some driver may allow replacing one of its children
7494 * because it can guarantee that this child's data is not visible at
7495 * all (for example, for dissenting quorum children that have no other
7498 bool bdrv_recurse_can_replace(BlockDriverState
*bs
,
7499 BlockDriverState
*to_replace
)
7501 BlockDriverState
*filtered
;
7503 GLOBAL_STATE_CODE();
7505 if (!bs
|| !bs
->drv
) {
7509 if (bs
== to_replace
) {
7513 /* See what the driver can do */
7514 if (bs
->drv
->bdrv_recurse_can_replace
) {
7515 return bs
->drv
->bdrv_recurse_can_replace(bs
, to_replace
);
7518 /* For filters without an own implementation, we can recurse on our own */
7519 filtered
= bdrv_filter_bs(bs
);
7521 return bdrv_recurse_can_replace(filtered
, to_replace
);
7529 * Check whether the given @node_name can be replaced by a node that
7530 * has the same data as @parent_bs. If so, return @node_name's BDS;
7533 * @node_name must be a (recursive) *child of @parent_bs (or this
7534 * function will return NULL).
7536 * The result (whether the node can be replaced or not) is only valid
7537 * for as long as no graph or permission changes occur.
7539 BlockDriverState
*check_to_replace_node(BlockDriverState
*parent_bs
,
7540 const char *node_name
, Error
**errp
)
7542 BlockDriverState
*to_replace_bs
= bdrv_find_node(node_name
);
7543 AioContext
*aio_context
;
7545 GLOBAL_STATE_CODE();
7547 if (!to_replace_bs
) {
7548 error_setg(errp
, "Failed to find node with node-name='%s'", node_name
);
7552 aio_context
= bdrv_get_aio_context(to_replace_bs
);
7553 aio_context_acquire(aio_context
);
7555 if (bdrv_op_is_blocked(to_replace_bs
, BLOCK_OP_TYPE_REPLACE
, errp
)) {
7556 to_replace_bs
= NULL
;
7560 /* We don't want arbitrary node of the BDS chain to be replaced only the top
7561 * most non filter in order to prevent data corruption.
7562 * Another benefit is that this tests exclude backing files which are
7563 * blocked by the backing blockers.
7565 if (!bdrv_recurse_can_replace(parent_bs
, to_replace_bs
)) {
7566 error_setg(errp
, "Cannot replace '%s' by a node mirrored from '%s', "
7567 "because it cannot be guaranteed that doing so would not "
7568 "lead to an abrupt change of visible data",
7569 node_name
, parent_bs
->node_name
);
7570 to_replace_bs
= NULL
;
7575 aio_context_release(aio_context
);
7576 return to_replace_bs
;
7580 * Iterates through the list of runtime option keys that are said to
7581 * be "strong" for a BDS. An option is called "strong" if it changes
7582 * a BDS's data. For example, the null block driver's "size" and
7583 * "read-zeroes" options are strong, but its "latency-ns" option is
7586 * If a key returned by this function ends with a dot, all options
7587 * starting with that prefix are strong.
7589 static const char *const *strong_options(BlockDriverState
*bs
,
7590 const char *const *curopt
)
7592 static const char *const global_options
[] = {
7593 "driver", "filename", NULL
7597 return &global_options
[0];
7601 if (curopt
== &global_options
[ARRAY_SIZE(global_options
) - 1] && bs
->drv
) {
7602 curopt
= bs
->drv
->strong_runtime_opts
;
7605 return (curopt
&& *curopt
) ? curopt
: NULL
;
7609 * Copies all strong runtime options from bs->options to the given
7610 * QDict. The set of strong option keys is determined by invoking
7613 * Returns true iff any strong option was present in bs->options (and
7614 * thus copied to the target QDict) with the exception of "filename"
7615 * and "driver". The caller is expected to use this value to decide
7616 * whether the existence of strong options prevents the generation of
7619 static bool append_strong_runtime_options(QDict
*d
, BlockDriverState
*bs
)
7621 bool found_any
= false;
7622 const char *const *option_name
= NULL
;
7628 while ((option_name
= strong_options(bs
, option_name
))) {
7629 bool option_given
= false;
7631 assert(strlen(*option_name
) > 0);
7632 if ((*option_name
)[strlen(*option_name
) - 1] != '.') {
7633 QObject
*entry
= qdict_get(bs
->options
, *option_name
);
7638 qdict_put_obj(d
, *option_name
, qobject_ref(entry
));
7639 option_given
= true;
7641 const QDictEntry
*entry
;
7642 for (entry
= qdict_first(bs
->options
); entry
;
7643 entry
= qdict_next(bs
->options
, entry
))
7645 if (strstart(qdict_entry_key(entry
), *option_name
, NULL
)) {
7646 qdict_put_obj(d
, qdict_entry_key(entry
),
7647 qobject_ref(qdict_entry_value(entry
)));
7648 option_given
= true;
7653 /* While "driver" and "filename" need to be included in a JSON filename,
7654 * their existence does not prohibit generation of a plain filename. */
7655 if (!found_any
&& option_given
&&
7656 strcmp(*option_name
, "driver") && strcmp(*option_name
, "filename"))
7662 if (!qdict_haskey(d
, "driver")) {
7663 /* Drivers created with bdrv_new_open_driver() may not have a
7664 * @driver option. Add it here. */
7665 qdict_put_str(d
, "driver", bs
->drv
->format_name
);
7671 /* Note: This function may return false positives; it may return true
7672 * even if opening the backing file specified by bs's image header
7673 * would result in exactly bs->backing. */
7674 static bool bdrv_backing_overridden(BlockDriverState
*bs
)
7676 GLOBAL_STATE_CODE();
7678 return strcmp(bs
->auto_backing_file
,
7679 bs
->backing
->bs
->filename
);
7681 /* No backing BDS, so if the image header reports any backing
7682 * file, it must have been suppressed */
7683 return bs
->auto_backing_file
[0] != '\0';
7687 /* Updates the following BDS fields:
7688 * - exact_filename: A filename which may be used for opening a block device
7689 * which (mostly) equals the given BDS (even without any
7690 * other options; so reading and writing must return the same
7691 * results, but caching etc. may be different)
7692 * - full_open_options: Options which, when given when opening a block device
7693 * (without a filename), result in a BDS (mostly)
7694 * equalling the given one
7695 * - filename: If exact_filename is set, it is copied here. Otherwise,
7696 * full_open_options is converted to a JSON object, prefixed with
7697 * "json:" (for use through the JSON pseudo protocol) and put here.
7699 void bdrv_refresh_filename(BlockDriverState
*bs
)
7701 BlockDriver
*drv
= bs
->drv
;
7703 BlockDriverState
*primary_child_bs
;
7705 bool backing_overridden
;
7706 bool generate_json_filename
; /* Whether our default implementation should
7707 fill exact_filename (false) or not (true) */
7709 GLOBAL_STATE_CODE();
7715 /* This BDS's file name may depend on any of its children's file names, so
7716 * refresh those first */
7717 QLIST_FOREACH(child
, &bs
->children
, next
) {
7718 bdrv_refresh_filename(child
->bs
);
7722 /* For implicit nodes, just copy everything from the single child */
7723 child
= QLIST_FIRST(&bs
->children
);
7724 assert(QLIST_NEXT(child
, next
) == NULL
);
7726 pstrcpy(bs
->exact_filename
, sizeof(bs
->exact_filename
),
7727 child
->bs
->exact_filename
);
7728 pstrcpy(bs
->filename
, sizeof(bs
->filename
), child
->bs
->filename
);
7730 qobject_unref(bs
->full_open_options
);
7731 bs
->full_open_options
= qobject_ref(child
->bs
->full_open_options
);
7736 backing_overridden
= bdrv_backing_overridden(bs
);
7738 if (bs
->open_flags
& BDRV_O_NO_IO
) {
7739 /* Without I/O, the backing file does not change anything.
7740 * Therefore, in such a case (primarily qemu-img), we can
7741 * pretend the backing file has not been overridden even if
7742 * it technically has been. */
7743 backing_overridden
= false;
7746 /* Gather the options QDict */
7748 generate_json_filename
= append_strong_runtime_options(opts
, bs
);
7749 generate_json_filename
|= backing_overridden
;
7751 if (drv
->bdrv_gather_child_options
) {
7752 /* Some block drivers may not want to present all of their children's
7753 * options, or name them differently from BdrvChild.name */
7754 drv
->bdrv_gather_child_options(bs
, opts
, backing_overridden
);
7756 QLIST_FOREACH(child
, &bs
->children
, next
) {
7757 if (child
== bs
->backing
&& !backing_overridden
) {
7758 /* We can skip the backing BDS if it has not been overridden */
7762 qdict_put(opts
, child
->name
,
7763 qobject_ref(child
->bs
->full_open_options
));
7766 if (backing_overridden
&& !bs
->backing
) {
7767 /* Force no backing file */
7768 qdict_put_null(opts
, "backing");
7772 qobject_unref(bs
->full_open_options
);
7773 bs
->full_open_options
= opts
;
7775 primary_child_bs
= bdrv_primary_bs(bs
);
7777 if (drv
->bdrv_refresh_filename
) {
7778 /* Obsolete information is of no use here, so drop the old file name
7779 * information before refreshing it */
7780 bs
->exact_filename
[0] = '\0';
7782 drv
->bdrv_refresh_filename(bs
);
7783 } else if (primary_child_bs
) {
7785 * Try to reconstruct valid information from the underlying
7786 * file -- this only works for format nodes (filter nodes
7787 * cannot be probed and as such must be selected by the user
7788 * either through an options dict, or through a special
7789 * filename which the filter driver must construct in its
7790 * .bdrv_refresh_filename() implementation).
7793 bs
->exact_filename
[0] = '\0';
7796 * We can use the underlying file's filename if:
7797 * - it has a filename,
7798 * - the current BDS is not a filter,
7799 * - the file is a protocol BDS, and
7800 * - opening that file (as this BDS's format) will automatically create
7801 * the BDS tree we have right now, that is:
7802 * - the user did not significantly change this BDS's behavior with
7803 * some explicit (strong) options
7804 * - no non-file child of this BDS has been overridden by the user
7805 * Both of these conditions are represented by generate_json_filename.
7807 if (primary_child_bs
->exact_filename
[0] &&
7808 primary_child_bs
->drv
->bdrv_file_open
&&
7809 !drv
->is_filter
&& !generate_json_filename
)
7811 strcpy(bs
->exact_filename
, primary_child_bs
->exact_filename
);
7815 if (bs
->exact_filename
[0]) {
7816 pstrcpy(bs
->filename
, sizeof(bs
->filename
), bs
->exact_filename
);
7818 GString
*json
= qobject_to_json(QOBJECT(bs
->full_open_options
));
7819 if (snprintf(bs
->filename
, sizeof(bs
->filename
), "json:%s",
7820 json
->str
) >= sizeof(bs
->filename
)) {
7821 /* Give user a hint if we truncated things. */
7822 strcpy(bs
->filename
+ sizeof(bs
->filename
) - 4, "...");
7824 g_string_free(json
, true);
7828 char *bdrv_dirname(BlockDriverState
*bs
, Error
**errp
)
7830 BlockDriver
*drv
= bs
->drv
;
7831 BlockDriverState
*child_bs
;
7833 GLOBAL_STATE_CODE();
7836 error_setg(errp
, "Node '%s' is ejected", bs
->node_name
);
7840 if (drv
->bdrv_dirname
) {
7841 return drv
->bdrv_dirname(bs
, errp
);
7844 child_bs
= bdrv_primary_bs(bs
);
7846 return bdrv_dirname(child_bs
, errp
);
7849 bdrv_refresh_filename(bs
);
7850 if (bs
->exact_filename
[0] != '\0') {
7851 return path_combine(bs
->exact_filename
, "");
7854 error_setg(errp
, "Cannot generate a base directory for %s nodes",
7860 * Hot add/remove a BDS's child. So the user can take a child offline when
7861 * it is broken and take a new child online
7863 void bdrv_add_child(BlockDriverState
*parent_bs
, BlockDriverState
*child_bs
,
7866 GLOBAL_STATE_CODE();
7867 if (!parent_bs
->drv
|| !parent_bs
->drv
->bdrv_add_child
) {
7868 error_setg(errp
, "The node %s does not support adding a child",
7869 bdrv_get_device_or_node_name(parent_bs
));
7873 if (!QLIST_EMPTY(&child_bs
->parents
)) {
7874 error_setg(errp
, "The node %s already has a parent",
7875 child_bs
->node_name
);
7879 parent_bs
->drv
->bdrv_add_child(parent_bs
, child_bs
, errp
);
7882 void bdrv_del_child(BlockDriverState
*parent_bs
, BdrvChild
*child
, Error
**errp
)
7886 GLOBAL_STATE_CODE();
7887 if (!parent_bs
->drv
|| !parent_bs
->drv
->bdrv_del_child
) {
7888 error_setg(errp
, "The node %s does not support removing a child",
7889 bdrv_get_device_or_node_name(parent_bs
));
7893 QLIST_FOREACH(tmp
, &parent_bs
->children
, next
) {
7900 error_setg(errp
, "The node %s does not have a child named %s",
7901 bdrv_get_device_or_node_name(parent_bs
),
7902 bdrv_get_device_or_node_name(child
->bs
));
7906 parent_bs
->drv
->bdrv_del_child(parent_bs
, child
, errp
);
7909 int bdrv_make_empty(BdrvChild
*c
, Error
**errp
)
7911 BlockDriver
*drv
= c
->bs
->drv
;
7914 GLOBAL_STATE_CODE();
7915 assert(c
->perm
& (BLK_PERM_WRITE
| BLK_PERM_WRITE_UNCHANGED
));
7917 if (!drv
->bdrv_make_empty
) {
7918 error_setg(errp
, "%s does not support emptying nodes",
7923 ret
= drv
->bdrv_make_empty(c
->bs
);
7925 error_setg_errno(errp
, -ret
, "Failed to empty %s",
7934 * Return the child that @bs acts as an overlay for, and from which data may be
7935 * copied in COW or COR operations. Usually this is the backing file.
7937 BdrvChild
*bdrv_cow_child(BlockDriverState
*bs
)
7941 if (!bs
|| !bs
->drv
) {
7945 if (bs
->drv
->is_filter
) {
7953 assert(bs
->backing
->role
& BDRV_CHILD_COW
);
7958 * If @bs acts as a filter for exactly one of its children, return
7961 BdrvChild
*bdrv_filter_child(BlockDriverState
*bs
)
7966 if (!bs
|| !bs
->drv
) {
7970 if (!bs
->drv
->is_filter
) {
7974 /* Only one of @backing or @file may be used */
7975 assert(!(bs
->backing
&& bs
->file
));
7977 c
= bs
->backing
?: bs
->file
;
7982 assert(c
->role
& BDRV_CHILD_FILTERED
);
7987 * Return either the result of bdrv_cow_child() or bdrv_filter_child(),
7988 * whichever is non-NULL.
7990 * Return NULL if both are NULL.
7992 BdrvChild
*bdrv_filter_or_cow_child(BlockDriverState
*bs
)
7994 BdrvChild
*cow_child
= bdrv_cow_child(bs
);
7995 BdrvChild
*filter_child
= bdrv_filter_child(bs
);
7998 /* Filter nodes cannot have COW backing files */
7999 assert(!(cow_child
&& filter_child
));
8001 return cow_child
?: filter_child
;
8005 * Return the primary child of this node: For filters, that is the
8006 * filtered child. For other nodes, that is usually the child storing
8008 * (A generally more helpful description is that this is (usually) the
8009 * child that has the same filename as @bs.)
8011 * Drivers do not necessarily have a primary child; for example quorum
8014 BdrvChild
*bdrv_primary_child(BlockDriverState
*bs
)
8016 BdrvChild
*c
, *found
= NULL
;
8019 QLIST_FOREACH(c
, &bs
->children
, next
) {
8020 if (c
->role
& BDRV_CHILD_PRIMARY
) {
8029 static BlockDriverState
*bdrv_do_skip_filters(BlockDriverState
*bs
,
8030 bool stop_on_explicit_filter
)
8038 while (!(stop_on_explicit_filter
&& !bs
->implicit
)) {
8039 c
= bdrv_filter_child(bs
);
8042 * A filter that is embedded in a working block graph must
8043 * have a child. Assert this here so this function does
8044 * not return a filter node that is not expected by the
8047 assert(!bs
->drv
|| !bs
->drv
->is_filter
);
8053 * Note that this treats nodes with bs->drv == NULL as not being
8054 * filters (bs->drv == NULL should be replaced by something else
8056 * The advantage of this behavior is that this function will thus
8057 * always return a non-NULL value (given a non-NULL @bs).
8064 * Return the first BDS that has not been added implicitly or that
8065 * does not have a filtered child down the chain starting from @bs
8066 * (including @bs itself).
8068 BlockDriverState
*bdrv_skip_implicit_filters(BlockDriverState
*bs
)
8070 GLOBAL_STATE_CODE();
8071 return bdrv_do_skip_filters(bs
, true);
8075 * Return the first BDS that does not have a filtered child down the
8076 * chain starting from @bs (including @bs itself).
8078 BlockDriverState
*bdrv_skip_filters(BlockDriverState
*bs
)
8081 return bdrv_do_skip_filters(bs
, false);
8085 * For a backing chain, return the first non-filter backing image of
8086 * the first non-filter image.
8088 BlockDriverState
*bdrv_backing_chain_next(BlockDriverState
*bs
)
8091 return bdrv_skip_filters(bdrv_cow_bs(bdrv_skip_filters(bs
)));
8095 * Check whether [offset, offset + bytes) overlaps with the cached
8096 * block-status data region.
8098 * If so, and @pnum is not NULL, set *pnum to `bsc.data_end - offset`,
8099 * which is what bdrv_bsc_is_data()'s interface needs.
8100 * Otherwise, *pnum is not touched.
8102 static bool bdrv_bsc_range_overlaps_locked(BlockDriverState
*bs
,
8103 int64_t offset
, int64_t bytes
,
8106 BdrvBlockStatusCache
*bsc
= qatomic_rcu_read(&bs
->block_status_cache
);
8110 qatomic_read(&bsc
->valid
) &&
8111 ranges_overlap(offset
, bytes
, bsc
->data_start
,
8112 bsc
->data_end
- bsc
->data_start
);
8114 if (overlaps
&& pnum
) {
8115 *pnum
= bsc
->data_end
- offset
;
8122 * See block_int.h for this function's documentation.
8124 bool bdrv_bsc_is_data(BlockDriverState
*bs
, int64_t offset
, int64_t *pnum
)
8127 RCU_READ_LOCK_GUARD();
8128 return bdrv_bsc_range_overlaps_locked(bs
, offset
, 1, pnum
);
8132 * See block_int.h for this function's documentation.
8134 void bdrv_bsc_invalidate_range(BlockDriverState
*bs
,
8135 int64_t offset
, int64_t bytes
)
8138 RCU_READ_LOCK_GUARD();
8140 if (bdrv_bsc_range_overlaps_locked(bs
, offset
, bytes
, NULL
)) {
8141 qatomic_set(&bs
->block_status_cache
->valid
, false);
8146 * See block_int.h for this function's documentation.
8148 void bdrv_bsc_fill(BlockDriverState
*bs
, int64_t offset
, int64_t bytes
)
8150 BdrvBlockStatusCache
*new_bsc
= g_new(BdrvBlockStatusCache
, 1);
8151 BdrvBlockStatusCache
*old_bsc
;
8154 *new_bsc
= (BdrvBlockStatusCache
) {
8156 .data_start
= offset
,
8157 .data_end
= offset
+ bytes
,
8160 QEMU_LOCK_GUARD(&bs
->bsc_modify_lock
);
8162 old_bsc
= qatomic_rcu_read(&bs
->block_status_cache
);
8163 qatomic_rcu_set(&bs
->block_status_cache
, new_bsc
);
8165 g_free_rcu(old_bsc
, rcu
);