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 ret
= refresh_total_sectors(bs
, bs
->total_sectors
);
1679 error_setg_errno(errp
, -ret
, "Could not refresh total sector count");
1683 bdrv_refresh_limits(bs
, NULL
, &local_err
);
1685 error_propagate(errp
, local_err
);
1689 assert(bdrv_opt_mem_align(bs
) != 0);
1690 assert(bdrv_min_mem_align(bs
) != 0);
1691 assert(is_power_of_2(bs
->bl
.request_alignment
));
1693 for (i
= 0; i
< bs
->quiesce_counter
; i
++) {
1694 if (drv
->bdrv_co_drain_begin
) {
1695 drv
->bdrv_co_drain_begin(bs
);
1702 if (bs
->file
!= NULL
) {
1703 bdrv_unref_child(bs
, bs
->file
);
1712 * Create and open a block node.
1714 * @options is a QDict of options to pass to the block drivers, or NULL for an
1715 * empty set of options. The reference to the QDict belongs to the block layer
1716 * after the call (even on failure), so if the caller intends to reuse the
1717 * dictionary, it needs to use qobject_ref() before calling bdrv_open.
1719 BlockDriverState
*bdrv_new_open_driver_opts(BlockDriver
*drv
,
1720 const char *node_name
,
1721 QDict
*options
, int flags
,
1724 BlockDriverState
*bs
;
1727 GLOBAL_STATE_CODE();
1730 bs
->open_flags
= flags
;
1731 bs
->options
= options
?: qdict_new();
1732 bs
->explicit_options
= qdict_clone_shallow(bs
->options
);
1735 update_options_from_flags(bs
->options
, flags
);
1737 ret
= bdrv_open_driver(bs
, drv
, node_name
, bs
->options
, flags
, errp
);
1739 qobject_unref(bs
->explicit_options
);
1740 bs
->explicit_options
= NULL
;
1741 qobject_unref(bs
->options
);
1750 /* Create and open a block node. */
1751 BlockDriverState
*bdrv_new_open_driver(BlockDriver
*drv
, const char *node_name
,
1752 int flags
, Error
**errp
)
1754 GLOBAL_STATE_CODE();
1755 return bdrv_new_open_driver_opts(drv
, node_name
, NULL
, flags
, errp
);
1758 QemuOptsList bdrv_runtime_opts
= {
1759 .name
= "bdrv_common",
1760 .head
= QTAILQ_HEAD_INITIALIZER(bdrv_runtime_opts
.head
),
1763 .name
= "node-name",
1764 .type
= QEMU_OPT_STRING
,
1765 .help
= "Node name of the block device node",
1769 .type
= QEMU_OPT_STRING
,
1770 .help
= "Block driver to use for the node",
1773 .name
= BDRV_OPT_CACHE_DIRECT
,
1774 .type
= QEMU_OPT_BOOL
,
1775 .help
= "Bypass software writeback cache on the host",
1778 .name
= BDRV_OPT_CACHE_NO_FLUSH
,
1779 .type
= QEMU_OPT_BOOL
,
1780 .help
= "Ignore flush requests",
1783 .name
= BDRV_OPT_READ_ONLY
,
1784 .type
= QEMU_OPT_BOOL
,
1785 .help
= "Node is opened in read-only mode",
1788 .name
= BDRV_OPT_AUTO_READ_ONLY
,
1789 .type
= QEMU_OPT_BOOL
,
1790 .help
= "Node can become read-only if opening read-write fails",
1793 .name
= "detect-zeroes",
1794 .type
= QEMU_OPT_STRING
,
1795 .help
= "try to optimize zero writes (off, on, unmap)",
1798 .name
= BDRV_OPT_DISCARD
,
1799 .type
= QEMU_OPT_STRING
,
1800 .help
= "discard operation (ignore/off, unmap/on)",
1803 .name
= BDRV_OPT_FORCE_SHARE
,
1804 .type
= QEMU_OPT_BOOL
,
1805 .help
= "always accept other writers (default: off)",
1807 { /* end of list */ }
1811 QemuOptsList bdrv_create_opts_simple
= {
1812 .name
= "simple-create-opts",
1813 .head
= QTAILQ_HEAD_INITIALIZER(bdrv_create_opts_simple
.head
),
1816 .name
= BLOCK_OPT_SIZE
,
1817 .type
= QEMU_OPT_SIZE
,
1818 .help
= "Virtual disk size"
1821 .name
= BLOCK_OPT_PREALLOC
,
1822 .type
= QEMU_OPT_STRING
,
1823 .help
= "Preallocation mode (allowed values: off)"
1825 { /* end of list */ }
1830 * Common part for opening disk images and files
1832 * Removes all processed options from *options.
1834 static int bdrv_open_common(BlockDriverState
*bs
, BlockBackend
*file
,
1835 QDict
*options
, Error
**errp
)
1837 int ret
, open_flags
;
1838 const char *filename
;
1839 const char *driver_name
= NULL
;
1840 const char *node_name
= NULL
;
1841 const char *discard
;
1844 Error
*local_err
= NULL
;
1847 assert(bs
->file
== NULL
);
1848 assert(options
!= NULL
&& bs
->options
!= options
);
1849 GLOBAL_STATE_CODE();
1851 opts
= qemu_opts_create(&bdrv_runtime_opts
, NULL
, 0, &error_abort
);
1852 if (!qemu_opts_absorb_qdict(opts
, options
, errp
)) {
1857 update_flags_from_options(&bs
->open_flags
, opts
);
1859 driver_name
= qemu_opt_get(opts
, "driver");
1860 drv
= bdrv_find_format(driver_name
);
1861 assert(drv
!= NULL
);
1863 bs
->force_share
= qemu_opt_get_bool(opts
, BDRV_OPT_FORCE_SHARE
, false);
1865 if (bs
->force_share
&& (bs
->open_flags
& BDRV_O_RDWR
)) {
1867 BDRV_OPT_FORCE_SHARE
1868 "=on can only be used with read-only images");
1874 bdrv_refresh_filename(blk_bs(file
));
1875 filename
= blk_bs(file
)->filename
;
1878 * Caution: while qdict_get_try_str() is fine, getting
1879 * non-string types would require more care. When @options
1880 * come from -blockdev or blockdev_add, its members are typed
1881 * according to the QAPI schema, but when they come from
1882 * -drive, they're all QString.
1884 filename
= qdict_get_try_str(options
, "filename");
1887 if (drv
->bdrv_needs_filename
&& (!filename
|| !filename
[0])) {
1888 error_setg(errp
, "The '%s' block driver requires a file name",
1894 trace_bdrv_open_common(bs
, filename
?: "", bs
->open_flags
,
1897 ro
= bdrv_is_read_only(bs
);
1899 if (use_bdrv_whitelist
&& !bdrv_is_whitelisted(drv
, ro
)) {
1900 if (!ro
&& bdrv_is_whitelisted(drv
, true)) {
1901 ret
= bdrv_apply_auto_read_only(bs
, NULL
, NULL
);
1907 !ro
&& bdrv_is_whitelisted(drv
, true)
1908 ? "Driver '%s' can only be used for read-only devices"
1909 : "Driver '%s' is not whitelisted",
1915 /* bdrv_new() and bdrv_close() make it so */
1916 assert(qatomic_read(&bs
->copy_on_read
) == 0);
1918 if (bs
->open_flags
& BDRV_O_COPY_ON_READ
) {
1920 bdrv_enable_copy_on_read(bs
);
1922 error_setg(errp
, "Can't use copy-on-read on read-only device");
1928 discard
= qemu_opt_get(opts
, BDRV_OPT_DISCARD
);
1929 if (discard
!= NULL
) {
1930 if (bdrv_parse_discard_flags(discard
, &bs
->open_flags
) != 0) {
1931 error_setg(errp
, "Invalid discard option");
1938 bdrv_parse_detect_zeroes(opts
, bs
->open_flags
, &local_err
);
1940 error_propagate(errp
, local_err
);
1945 if (filename
!= NULL
) {
1946 pstrcpy(bs
->filename
, sizeof(bs
->filename
), filename
);
1948 bs
->filename
[0] = '\0';
1950 pstrcpy(bs
->exact_filename
, sizeof(bs
->exact_filename
), bs
->filename
);
1952 /* Open the image, either directly or using a protocol */
1953 open_flags
= bdrv_open_flags(bs
, bs
->open_flags
);
1954 node_name
= qemu_opt_get(opts
, "node-name");
1956 assert(!drv
->bdrv_file_open
|| file
== NULL
);
1957 ret
= bdrv_open_driver(bs
, drv
, node_name
, options
, open_flags
, errp
);
1962 qemu_opts_del(opts
);
1966 qemu_opts_del(opts
);
1970 static QDict
*parse_json_filename(const char *filename
, Error
**errp
)
1972 QObject
*options_obj
;
1975 GLOBAL_STATE_CODE();
1977 ret
= strstart(filename
, "json:", &filename
);
1980 options_obj
= qobject_from_json(filename
, errp
);
1982 error_prepend(errp
, "Could not parse the JSON options: ");
1986 options
= qobject_to(QDict
, options_obj
);
1988 qobject_unref(options_obj
);
1989 error_setg(errp
, "Invalid JSON object given");
1993 qdict_flatten(options
);
1998 static void parse_json_protocol(QDict
*options
, const char **pfilename
,
2001 QDict
*json_options
;
2002 Error
*local_err
= NULL
;
2003 GLOBAL_STATE_CODE();
2005 /* Parse json: pseudo-protocol */
2006 if (!*pfilename
|| !g_str_has_prefix(*pfilename
, "json:")) {
2010 json_options
= parse_json_filename(*pfilename
, &local_err
);
2012 error_propagate(errp
, local_err
);
2016 /* Options given in the filename have lower priority than options
2017 * specified directly */
2018 qdict_join(options
, json_options
, false);
2019 qobject_unref(json_options
);
2024 * Fills in default options for opening images and converts the legacy
2025 * filename/flags pair to option QDict entries.
2026 * The BDRV_O_PROTOCOL flag in *flags will be set or cleared accordingly if a
2027 * block driver has been specified explicitly.
2029 static int bdrv_fill_options(QDict
**options
, const char *filename
,
2030 int *flags
, Error
**errp
)
2032 const char *drvname
;
2033 bool protocol
= *flags
& BDRV_O_PROTOCOL
;
2034 bool parse_filename
= false;
2035 BlockDriver
*drv
= NULL
;
2036 Error
*local_err
= NULL
;
2038 GLOBAL_STATE_CODE();
2041 * Caution: while qdict_get_try_str() is fine, getting non-string
2042 * types would require more care. When @options come from
2043 * -blockdev or blockdev_add, its members are typed according to
2044 * the QAPI schema, but when they come from -drive, they're all
2047 drvname
= qdict_get_try_str(*options
, "driver");
2049 drv
= bdrv_find_format(drvname
);
2051 error_setg(errp
, "Unknown driver '%s'", drvname
);
2054 /* If the user has explicitly specified the driver, this choice should
2055 * override the BDRV_O_PROTOCOL flag */
2056 protocol
= drv
->bdrv_file_open
;
2060 *flags
|= BDRV_O_PROTOCOL
;
2062 *flags
&= ~BDRV_O_PROTOCOL
;
2065 /* Translate cache options from flags into options */
2066 update_options_from_flags(*options
, *flags
);
2068 /* Fetch the file name from the options QDict if necessary */
2069 if (protocol
&& filename
) {
2070 if (!qdict_haskey(*options
, "filename")) {
2071 qdict_put_str(*options
, "filename", filename
);
2072 parse_filename
= true;
2074 error_setg(errp
, "Can't specify 'file' and 'filename' options at "
2080 /* Find the right block driver */
2081 /* See cautionary note on accessing @options above */
2082 filename
= qdict_get_try_str(*options
, "filename");
2084 if (!drvname
&& protocol
) {
2086 drv
= bdrv_find_protocol(filename
, parse_filename
, errp
);
2091 drvname
= drv
->format_name
;
2092 qdict_put_str(*options
, "driver", drvname
);
2094 error_setg(errp
, "Must specify either driver or file");
2099 assert(drv
|| !protocol
);
2101 /* Driver-specific filename parsing */
2102 if (drv
&& drv
->bdrv_parse_filename
&& parse_filename
) {
2103 drv
->bdrv_parse_filename(filename
, *options
, &local_err
);
2105 error_propagate(errp
, local_err
);
2109 if (!drv
->bdrv_needs_filename
) {
2110 qdict_del(*options
, "filename");
2117 typedef struct BlockReopenQueueEntry
{
2120 BDRVReopenState state
;
2121 QTAILQ_ENTRY(BlockReopenQueueEntry
) entry
;
2122 } BlockReopenQueueEntry
;
2125 * Return the flags that @bs will have after the reopens in @q have
2126 * successfully completed. If @q is NULL (or @bs is not contained in @q),
2127 * return the current flags.
2129 static int bdrv_reopen_get_flags(BlockReopenQueue
*q
, BlockDriverState
*bs
)
2131 BlockReopenQueueEntry
*entry
;
2134 QTAILQ_FOREACH(entry
, q
, entry
) {
2135 if (entry
->state
.bs
== bs
) {
2136 return entry
->state
.flags
;
2141 return bs
->open_flags
;
2144 /* Returns whether the image file can be written to after the reopen queue @q
2145 * has been successfully applied, or right now if @q is NULL. */
2146 static bool bdrv_is_writable_after_reopen(BlockDriverState
*bs
,
2147 BlockReopenQueue
*q
)
2149 int flags
= bdrv_reopen_get_flags(q
, bs
);
2151 return (flags
& (BDRV_O_RDWR
| BDRV_O_INACTIVE
)) == BDRV_O_RDWR
;
2155 * Return whether the BDS can be written to. This is not necessarily
2156 * the same as !bdrv_is_read_only(bs), as inactivated images may not
2157 * be written to but do not count as read-only images.
2159 bool bdrv_is_writable(BlockDriverState
*bs
)
2162 return bdrv_is_writable_after_reopen(bs
, NULL
);
2165 static char *bdrv_child_user_desc(BdrvChild
*c
)
2167 GLOBAL_STATE_CODE();
2168 return c
->klass
->get_parent_desc(c
);
2172 * Check that @a allows everything that @b needs. @a and @b must reference same
2175 static bool bdrv_a_allow_b(BdrvChild
*a
, BdrvChild
*b
, Error
**errp
)
2177 const char *child_bs_name
;
2178 g_autofree
char *a_user
= NULL
;
2179 g_autofree
char *b_user
= NULL
;
2180 g_autofree
char *perms
= NULL
;
2183 assert(a
->bs
== b
->bs
);
2184 GLOBAL_STATE_CODE();
2186 if ((b
->perm
& a
->shared_perm
) == b
->perm
) {
2190 child_bs_name
= bdrv_get_node_name(b
->bs
);
2191 a_user
= bdrv_child_user_desc(a
);
2192 b_user
= bdrv_child_user_desc(b
);
2193 perms
= bdrv_perm_names(b
->perm
& ~a
->shared_perm
);
2195 error_setg(errp
, "Permission conflict on node '%s': permissions '%s' are "
2196 "both required by %s (uses node '%s' as '%s' child) and "
2197 "unshared by %s (uses node '%s' as '%s' child).",
2198 child_bs_name
, perms
,
2199 b_user
, child_bs_name
, b
->name
,
2200 a_user
, child_bs_name
, a
->name
);
2205 static bool bdrv_parent_perms_conflict(BlockDriverState
*bs
, Error
**errp
)
2208 GLOBAL_STATE_CODE();
2211 * During the loop we'll look at each pair twice. That's correct because
2212 * bdrv_a_allow_b() is asymmetric and we should check each pair in both
2215 QLIST_FOREACH(a
, &bs
->parents
, next_parent
) {
2216 QLIST_FOREACH(b
, &bs
->parents
, next_parent
) {
2221 if (!bdrv_a_allow_b(a
, b
, errp
)) {
2230 static void bdrv_child_perm(BlockDriverState
*bs
, BlockDriverState
*child_bs
,
2231 BdrvChild
*c
, BdrvChildRole role
,
2232 BlockReopenQueue
*reopen_queue
,
2233 uint64_t parent_perm
, uint64_t parent_shared
,
2234 uint64_t *nperm
, uint64_t *nshared
)
2236 assert(bs
->drv
&& bs
->drv
->bdrv_child_perm
);
2237 GLOBAL_STATE_CODE();
2238 bs
->drv
->bdrv_child_perm(bs
, c
, role
, reopen_queue
,
2239 parent_perm
, parent_shared
,
2241 /* TODO Take force_share from reopen_queue */
2242 if (child_bs
&& child_bs
->force_share
) {
2243 *nshared
= BLK_PERM_ALL
;
2248 * Adds the whole subtree of @bs (including @bs itself) to the @list (except for
2249 * nodes that are already in the @list, of course) so that final list is
2250 * topologically sorted. Return the result (GSList @list object is updated, so
2251 * don't use old reference after function call).
2253 * On function start @list must be already topologically sorted and for any node
2254 * in the @list the whole subtree of the node must be in the @list as well. The
2255 * simplest way to satisfy this criteria: use only result of
2256 * bdrv_topological_dfs() or NULL as @list parameter.
2258 static GSList
*bdrv_topological_dfs(GSList
*list
, GHashTable
*found
,
2259 BlockDriverState
*bs
)
2262 g_autoptr(GHashTable
) local_found
= NULL
;
2264 GLOBAL_STATE_CODE();
2268 found
= local_found
= g_hash_table_new(NULL
, NULL
);
2271 if (g_hash_table_contains(found
, bs
)) {
2274 g_hash_table_add(found
, bs
);
2276 QLIST_FOREACH(child
, &bs
->children
, next
) {
2277 list
= bdrv_topological_dfs(list
, found
, child
->bs
);
2280 return g_slist_prepend(list
, bs
);
2283 typedef struct BdrvChildSetPermState
{
2286 uint64_t old_shared_perm
;
2287 } BdrvChildSetPermState
;
2289 static void bdrv_child_set_perm_abort(void *opaque
)
2291 BdrvChildSetPermState
*s
= opaque
;
2293 GLOBAL_STATE_CODE();
2295 s
->child
->perm
= s
->old_perm
;
2296 s
->child
->shared_perm
= s
->old_shared_perm
;
2299 static TransactionActionDrv bdrv_child_set_pem_drv
= {
2300 .abort
= bdrv_child_set_perm_abort
,
2304 static void bdrv_child_set_perm(BdrvChild
*c
, uint64_t perm
,
2305 uint64_t shared
, Transaction
*tran
)
2307 BdrvChildSetPermState
*s
= g_new(BdrvChildSetPermState
, 1);
2308 GLOBAL_STATE_CODE();
2310 *s
= (BdrvChildSetPermState
) {
2312 .old_perm
= c
->perm
,
2313 .old_shared_perm
= c
->shared_perm
,
2317 c
->shared_perm
= shared
;
2319 tran_add(tran
, &bdrv_child_set_pem_drv
, s
);
2322 static void bdrv_drv_set_perm_commit(void *opaque
)
2324 BlockDriverState
*bs
= opaque
;
2325 uint64_t cumulative_perms
, cumulative_shared_perms
;
2326 GLOBAL_STATE_CODE();
2328 if (bs
->drv
->bdrv_set_perm
) {
2329 bdrv_get_cumulative_perm(bs
, &cumulative_perms
,
2330 &cumulative_shared_perms
);
2331 bs
->drv
->bdrv_set_perm(bs
, cumulative_perms
, cumulative_shared_perms
);
2335 static void bdrv_drv_set_perm_abort(void *opaque
)
2337 BlockDriverState
*bs
= opaque
;
2338 GLOBAL_STATE_CODE();
2340 if (bs
->drv
->bdrv_abort_perm_update
) {
2341 bs
->drv
->bdrv_abort_perm_update(bs
);
2345 TransactionActionDrv bdrv_drv_set_perm_drv
= {
2346 .abort
= bdrv_drv_set_perm_abort
,
2347 .commit
= bdrv_drv_set_perm_commit
,
2350 static int bdrv_drv_set_perm(BlockDriverState
*bs
, uint64_t perm
,
2351 uint64_t shared_perm
, Transaction
*tran
,
2354 GLOBAL_STATE_CODE();
2359 if (bs
->drv
->bdrv_check_perm
) {
2360 int ret
= bs
->drv
->bdrv_check_perm(bs
, perm
, shared_perm
, errp
);
2367 tran_add(tran
, &bdrv_drv_set_perm_drv
, bs
);
2373 typedef struct BdrvReplaceChildState
{
2375 BlockDriverState
*old_bs
;
2376 } BdrvReplaceChildState
;
2378 static void bdrv_replace_child_commit(void *opaque
)
2380 BdrvReplaceChildState
*s
= opaque
;
2381 GLOBAL_STATE_CODE();
2383 bdrv_unref(s
->old_bs
);
2386 static void bdrv_replace_child_abort(void *opaque
)
2388 BdrvReplaceChildState
*s
= opaque
;
2389 BlockDriverState
*new_bs
= s
->child
->bs
;
2391 GLOBAL_STATE_CODE();
2392 /* old_bs reference is transparently moved from @s to @s->child */
2393 bdrv_replace_child_noperm(s
->child
, s
->old_bs
);
2397 static TransactionActionDrv bdrv_replace_child_drv
= {
2398 .commit
= bdrv_replace_child_commit
,
2399 .abort
= bdrv_replace_child_abort
,
2404 * bdrv_replace_child_tran
2406 * Note: real unref of old_bs is done only on commit.
2408 * The function doesn't update permissions, caller is responsible for this.
2410 static void bdrv_replace_child_tran(BdrvChild
*child
, BlockDriverState
*new_bs
,
2413 BdrvReplaceChildState
*s
= g_new(BdrvReplaceChildState
, 1);
2414 *s
= (BdrvReplaceChildState
) {
2416 .old_bs
= child
->bs
,
2418 tran_add(tran
, &bdrv_replace_child_drv
, s
);
2423 bdrv_replace_child_noperm(child
, new_bs
);
2424 /* old_bs reference is transparently moved from @child to @s */
2428 * Refresh permissions in @bs subtree. The function is intended to be called
2429 * after some graph modification that was done without permission update.
2431 static int bdrv_node_refresh_perm(BlockDriverState
*bs
, BlockReopenQueue
*q
,
2432 Transaction
*tran
, Error
**errp
)
2434 BlockDriver
*drv
= bs
->drv
;
2437 uint64_t cumulative_perms
, cumulative_shared_perms
;
2438 GLOBAL_STATE_CODE();
2440 bdrv_get_cumulative_perm(bs
, &cumulative_perms
, &cumulative_shared_perms
);
2442 /* Write permissions never work with read-only images */
2443 if ((cumulative_perms
& (BLK_PERM_WRITE
| BLK_PERM_WRITE_UNCHANGED
)) &&
2444 !bdrv_is_writable_after_reopen(bs
, q
))
2446 if (!bdrv_is_writable_after_reopen(bs
, NULL
)) {
2447 error_setg(errp
, "Block node is read-only");
2449 error_setg(errp
, "Read-only block node '%s' cannot support "
2450 "read-write users", bdrv_get_node_name(bs
));
2457 * Unaligned requests will automatically be aligned to bl.request_alignment
2458 * and without RESIZE we can't extend requests to write to space beyond the
2459 * end of the image, so it's required that the image size is aligned.
2461 if ((cumulative_perms
& (BLK_PERM_WRITE
| BLK_PERM_WRITE_UNCHANGED
)) &&
2462 !(cumulative_perms
& BLK_PERM_RESIZE
))
2464 if ((bs
->total_sectors
* BDRV_SECTOR_SIZE
) % bs
->bl
.request_alignment
) {
2465 error_setg(errp
, "Cannot get 'write' permission without 'resize': "
2466 "Image size is not a multiple of request "
2472 /* Check this node */
2477 ret
= bdrv_drv_set_perm(bs
, cumulative_perms
, cumulative_shared_perms
, tran
,
2483 /* Drivers that never have children can omit .bdrv_child_perm() */
2484 if (!drv
->bdrv_child_perm
) {
2485 assert(QLIST_EMPTY(&bs
->children
));
2489 /* Check all children */
2490 QLIST_FOREACH(c
, &bs
->children
, next
) {
2491 uint64_t cur_perm
, cur_shared
;
2493 bdrv_child_perm(bs
, c
->bs
, c
, c
->role
, q
,
2494 cumulative_perms
, cumulative_shared_perms
,
2495 &cur_perm
, &cur_shared
);
2496 bdrv_child_set_perm(c
, cur_perm
, cur_shared
, tran
);
2502 static int bdrv_list_refresh_perms(GSList
*list
, BlockReopenQueue
*q
,
2503 Transaction
*tran
, Error
**errp
)
2506 BlockDriverState
*bs
;
2507 GLOBAL_STATE_CODE();
2509 for ( ; list
; list
= list
->next
) {
2512 if (bdrv_parent_perms_conflict(bs
, errp
)) {
2516 ret
= bdrv_node_refresh_perm(bs
, q
, tran
, errp
);
2525 void bdrv_get_cumulative_perm(BlockDriverState
*bs
, uint64_t *perm
,
2526 uint64_t *shared_perm
)
2529 uint64_t cumulative_perms
= 0;
2530 uint64_t cumulative_shared_perms
= BLK_PERM_ALL
;
2532 GLOBAL_STATE_CODE();
2534 QLIST_FOREACH(c
, &bs
->parents
, next_parent
) {
2535 cumulative_perms
|= c
->perm
;
2536 cumulative_shared_perms
&= c
->shared_perm
;
2539 *perm
= cumulative_perms
;
2540 *shared_perm
= cumulative_shared_perms
;
2543 char *bdrv_perm_names(uint64_t perm
)
2549 { BLK_PERM_CONSISTENT_READ
, "consistent read" },
2550 { BLK_PERM_WRITE
, "write" },
2551 { BLK_PERM_WRITE_UNCHANGED
, "write unchanged" },
2552 { BLK_PERM_RESIZE
, "resize" },
2556 GString
*result
= g_string_sized_new(30);
2557 struct perm_name
*p
;
2559 for (p
= permissions
; p
->name
; p
++) {
2560 if (perm
& p
->perm
) {
2561 if (result
->len
> 0) {
2562 g_string_append(result
, ", ");
2564 g_string_append(result
, p
->name
);
2568 return g_string_free(result
, FALSE
);
2572 static int bdrv_refresh_perms(BlockDriverState
*bs
, Error
**errp
)
2575 Transaction
*tran
= tran_new();
2576 g_autoptr(GSList
) list
= bdrv_topological_dfs(NULL
, NULL
, bs
);
2577 GLOBAL_STATE_CODE();
2579 ret
= bdrv_list_refresh_perms(list
, NULL
, tran
, errp
);
2580 tran_finalize(tran
, ret
);
2585 int bdrv_child_try_set_perm(BdrvChild
*c
, uint64_t perm
, uint64_t shared
,
2588 Error
*local_err
= NULL
;
2589 Transaction
*tran
= tran_new();
2592 GLOBAL_STATE_CODE();
2594 bdrv_child_set_perm(c
, perm
, shared
, tran
);
2596 ret
= bdrv_refresh_perms(c
->bs
, &local_err
);
2598 tran_finalize(tran
, ret
);
2601 if ((perm
& ~c
->perm
) || (c
->shared_perm
& ~shared
)) {
2602 /* tighten permissions */
2603 error_propagate(errp
, local_err
);
2606 * Our caller may intend to only loosen restrictions and
2607 * does not expect this function to fail. Errors are not
2608 * fatal in such a case, so we can just hide them from our
2611 error_free(local_err
);
2619 int bdrv_child_refresh_perms(BlockDriverState
*bs
, BdrvChild
*c
, Error
**errp
)
2621 uint64_t parent_perms
, parent_shared
;
2622 uint64_t perms
, shared
;
2624 GLOBAL_STATE_CODE();
2626 bdrv_get_cumulative_perm(bs
, &parent_perms
, &parent_shared
);
2627 bdrv_child_perm(bs
, c
->bs
, c
, c
->role
, NULL
,
2628 parent_perms
, parent_shared
, &perms
, &shared
);
2630 return bdrv_child_try_set_perm(c
, perms
, shared
, errp
);
2634 * Default implementation for .bdrv_child_perm() for block filters:
2635 * Forward CONSISTENT_READ, WRITE, WRITE_UNCHANGED, and RESIZE to the
2638 static void bdrv_filter_default_perms(BlockDriverState
*bs
, BdrvChild
*c
,
2640 BlockReopenQueue
*reopen_queue
,
2641 uint64_t perm
, uint64_t shared
,
2642 uint64_t *nperm
, uint64_t *nshared
)
2644 GLOBAL_STATE_CODE();
2645 *nperm
= perm
& DEFAULT_PERM_PASSTHROUGH
;
2646 *nshared
= (shared
& DEFAULT_PERM_PASSTHROUGH
) | DEFAULT_PERM_UNCHANGED
;
2649 static void bdrv_default_perms_for_cow(BlockDriverState
*bs
, BdrvChild
*c
,
2651 BlockReopenQueue
*reopen_queue
,
2652 uint64_t perm
, uint64_t shared
,
2653 uint64_t *nperm
, uint64_t *nshared
)
2655 assert(role
& BDRV_CHILD_COW
);
2656 GLOBAL_STATE_CODE();
2659 * We want consistent read from backing files if the parent needs it.
2660 * No other operations are performed on backing files.
2662 perm
&= BLK_PERM_CONSISTENT_READ
;
2665 * If the parent can deal with changing data, we're okay with a
2666 * writable and resizable backing file.
2667 * TODO Require !(perm & BLK_PERM_CONSISTENT_READ), too?
2669 if (shared
& BLK_PERM_WRITE
) {
2670 shared
= BLK_PERM_WRITE
| BLK_PERM_RESIZE
;
2675 shared
|= BLK_PERM_CONSISTENT_READ
| BLK_PERM_WRITE_UNCHANGED
;
2677 if (bs
->open_flags
& BDRV_O_INACTIVE
) {
2678 shared
|= BLK_PERM_WRITE
| BLK_PERM_RESIZE
;
2685 static void bdrv_default_perms_for_storage(BlockDriverState
*bs
, BdrvChild
*c
,
2687 BlockReopenQueue
*reopen_queue
,
2688 uint64_t perm
, uint64_t shared
,
2689 uint64_t *nperm
, uint64_t *nshared
)
2693 GLOBAL_STATE_CODE();
2694 assert(role
& (BDRV_CHILD_METADATA
| BDRV_CHILD_DATA
));
2696 flags
= bdrv_reopen_get_flags(reopen_queue
, bs
);
2699 * Apart from the modifications below, the same permissions are
2700 * forwarded and left alone as for filters
2702 bdrv_filter_default_perms(bs
, c
, role
, reopen_queue
,
2703 perm
, shared
, &perm
, &shared
);
2705 if (role
& BDRV_CHILD_METADATA
) {
2706 /* Format drivers may touch metadata even if the guest doesn't write */
2707 if (bdrv_is_writable_after_reopen(bs
, reopen_queue
)) {
2708 perm
|= BLK_PERM_WRITE
| BLK_PERM_RESIZE
;
2712 * bs->file always needs to be consistent because of the
2713 * metadata. We can never allow other users to resize or write
2716 if (!(flags
& BDRV_O_NO_IO
)) {
2717 perm
|= BLK_PERM_CONSISTENT_READ
;
2719 shared
&= ~(BLK_PERM_WRITE
| BLK_PERM_RESIZE
);
2722 if (role
& BDRV_CHILD_DATA
) {
2724 * Technically, everything in this block is a subset of the
2725 * BDRV_CHILD_METADATA path taken above, and so this could
2726 * be an "else if" branch. However, that is not obvious, and
2727 * this function is not performance critical, therefore we let
2728 * this be an independent "if".
2732 * We cannot allow other users to resize the file because the
2733 * format driver might have some assumptions about the size
2734 * (e.g. because it is stored in metadata, or because the file
2735 * is split into fixed-size data files).
2737 shared
&= ~BLK_PERM_RESIZE
;
2740 * WRITE_UNCHANGED often cannot be performed as such on the
2741 * data file. For example, the qcow2 driver may still need to
2742 * write copied clusters on copy-on-read.
2744 if (perm
& BLK_PERM_WRITE_UNCHANGED
) {
2745 perm
|= BLK_PERM_WRITE
;
2749 * If the data file is written to, the format driver may
2750 * expect to be able to resize it by writing beyond the EOF.
2752 if (perm
& BLK_PERM_WRITE
) {
2753 perm
|= BLK_PERM_RESIZE
;
2757 if (bs
->open_flags
& BDRV_O_INACTIVE
) {
2758 shared
|= BLK_PERM_WRITE
| BLK_PERM_RESIZE
;
2765 void bdrv_default_perms(BlockDriverState
*bs
, BdrvChild
*c
,
2766 BdrvChildRole role
, BlockReopenQueue
*reopen_queue
,
2767 uint64_t perm
, uint64_t shared
,
2768 uint64_t *nperm
, uint64_t *nshared
)
2770 GLOBAL_STATE_CODE();
2771 if (role
& BDRV_CHILD_FILTERED
) {
2772 assert(!(role
& (BDRV_CHILD_DATA
| BDRV_CHILD_METADATA
|
2774 bdrv_filter_default_perms(bs
, c
, role
, reopen_queue
,
2775 perm
, shared
, nperm
, nshared
);
2776 } else if (role
& BDRV_CHILD_COW
) {
2777 assert(!(role
& (BDRV_CHILD_DATA
| BDRV_CHILD_METADATA
)));
2778 bdrv_default_perms_for_cow(bs
, c
, role
, reopen_queue
,
2779 perm
, shared
, nperm
, nshared
);
2780 } else if (role
& (BDRV_CHILD_METADATA
| BDRV_CHILD_DATA
)) {
2781 bdrv_default_perms_for_storage(bs
, c
, role
, reopen_queue
,
2782 perm
, shared
, nperm
, nshared
);
2784 g_assert_not_reached();
2788 uint64_t bdrv_qapi_perm_to_blk_perm(BlockPermission qapi_perm
)
2790 static const uint64_t permissions
[] = {
2791 [BLOCK_PERMISSION_CONSISTENT_READ
] = BLK_PERM_CONSISTENT_READ
,
2792 [BLOCK_PERMISSION_WRITE
] = BLK_PERM_WRITE
,
2793 [BLOCK_PERMISSION_WRITE_UNCHANGED
] = BLK_PERM_WRITE_UNCHANGED
,
2794 [BLOCK_PERMISSION_RESIZE
] = BLK_PERM_RESIZE
,
2797 QEMU_BUILD_BUG_ON(ARRAY_SIZE(permissions
) != BLOCK_PERMISSION__MAX
);
2798 QEMU_BUILD_BUG_ON(1UL << ARRAY_SIZE(permissions
) != BLK_PERM_ALL
+ 1);
2800 assert(qapi_perm
< BLOCK_PERMISSION__MAX
);
2802 return permissions
[qapi_perm
];
2805 static void bdrv_replace_child_noperm(BdrvChild
*child
,
2806 BlockDriverState
*new_bs
)
2808 BlockDriverState
*old_bs
= child
->bs
;
2809 int new_bs_quiesce_counter
;
2812 assert(!child
->frozen
);
2813 assert(old_bs
!= new_bs
);
2814 GLOBAL_STATE_CODE();
2816 if (old_bs
&& new_bs
) {
2817 assert(bdrv_get_aio_context(old_bs
) == bdrv_get_aio_context(new_bs
));
2820 new_bs_quiesce_counter
= (new_bs
? new_bs
->quiesce_counter
: 0);
2821 drain_saldo
= new_bs_quiesce_counter
- child
->parent_quiesce_counter
;
2824 * If the new child node is drained but the old one was not, flush
2825 * all outstanding requests to the old child node.
2827 while (drain_saldo
> 0 && child
->klass
->drained_begin
) {
2828 bdrv_parent_drained_begin_single(child
, true);
2833 /* Detach first so that the recursive drain sections coming from @child
2834 * are already gone and we only end the drain sections that came from
2836 if (child
->klass
->detach
) {
2837 child
->klass
->detach(child
);
2839 assert_bdrv_graph_writable(old_bs
);
2840 QLIST_REMOVE(child
, next_parent
);
2846 assert_bdrv_graph_writable(new_bs
);
2847 QLIST_INSERT_HEAD(&new_bs
->parents
, child
, next_parent
);
2850 * Detaching the old node may have led to the new node's
2851 * quiesce_counter having been decreased. Not a problem, we
2852 * just need to recognize this here and then invoke
2853 * drained_end appropriately more often.
2855 assert(new_bs
->quiesce_counter
<= new_bs_quiesce_counter
);
2856 drain_saldo
+= new_bs
->quiesce_counter
- new_bs_quiesce_counter
;
2858 /* Attach only after starting new drained sections, so that recursive
2859 * drain sections coming from @child don't get an extra .drained_begin
2861 if (child
->klass
->attach
) {
2862 child
->klass
->attach(child
);
2867 * If the old child node was drained but the new one is not, allow
2868 * requests to come in only after the new node has been attached.
2870 while (drain_saldo
< 0 && child
->klass
->drained_end
) {
2871 bdrv_parent_drained_end_single(child
);
2877 * Free the given @child.
2879 * The child must be empty (i.e. `child->bs == NULL`) and it must be
2880 * unused (i.e. not in a children list).
2882 static void bdrv_child_free(BdrvChild
*child
)
2885 GLOBAL_STATE_CODE();
2886 assert(!child
->next
.le_prev
); /* not in children list */
2888 g_free(child
->name
);
2892 typedef struct BdrvAttachChildCommonState
{
2894 AioContext
*old_parent_ctx
;
2895 AioContext
*old_child_ctx
;
2896 } BdrvAttachChildCommonState
;
2898 static void bdrv_attach_child_common_abort(void *opaque
)
2900 BdrvAttachChildCommonState
*s
= opaque
;
2901 BlockDriverState
*bs
= s
->child
->bs
;
2903 GLOBAL_STATE_CODE();
2904 bdrv_replace_child_noperm(s
->child
, NULL
);
2906 if (bdrv_get_aio_context(bs
) != s
->old_child_ctx
) {
2907 bdrv_try_change_aio_context(bs
, s
->old_child_ctx
, NULL
, &error_abort
);
2910 if (bdrv_child_get_parent_aio_context(s
->child
) != s
->old_parent_ctx
) {
2912 GHashTable
*visited
;
2917 /* No need to visit `child`, because it has been detached already */
2918 visited
= g_hash_table_new(NULL
, NULL
);
2919 ret
= s
->child
->klass
->change_aio_ctx(s
->child
, s
->old_parent_ctx
,
2920 visited
, tran
, &error_abort
);
2921 g_hash_table_destroy(visited
);
2923 /* transaction is supposed to always succeed */
2924 assert(ret
== true);
2929 bdrv_child_free(s
->child
);
2932 static TransactionActionDrv bdrv_attach_child_common_drv
= {
2933 .abort
= bdrv_attach_child_common_abort
,
2938 * Common part of attaching bdrv child to bs or to blk or to job
2940 * Function doesn't update permissions, caller is responsible for this.
2942 * Returns new created child.
2944 static BdrvChild
*bdrv_attach_child_common(BlockDriverState
*child_bs
,
2945 const char *child_name
,
2946 const BdrvChildClass
*child_class
,
2947 BdrvChildRole child_role
,
2948 uint64_t perm
, uint64_t shared_perm
,
2950 Transaction
*tran
, Error
**errp
)
2952 BdrvChild
*new_child
;
2953 AioContext
*parent_ctx
;
2954 AioContext
*child_ctx
= bdrv_get_aio_context(child_bs
);
2956 assert(child_class
->get_parent_desc
);
2957 GLOBAL_STATE_CODE();
2959 new_child
= g_new(BdrvChild
, 1);
2960 *new_child
= (BdrvChild
) {
2962 .name
= g_strdup(child_name
),
2963 .klass
= child_class
,
2966 .shared_perm
= shared_perm
,
2971 * If the AioContexts don't match, first try to move the subtree of
2972 * child_bs into the AioContext of the new parent. If this doesn't work,
2973 * try moving the parent into the AioContext of child_bs instead.
2975 parent_ctx
= bdrv_child_get_parent_aio_context(new_child
);
2976 if (child_ctx
!= parent_ctx
) {
2977 Error
*local_err
= NULL
;
2978 int ret
= bdrv_try_change_aio_context(child_bs
, parent_ctx
, NULL
,
2981 if (ret
< 0 && child_class
->change_aio_ctx
) {
2982 Transaction
*tran
= tran_new();
2983 GHashTable
*visited
= g_hash_table_new(NULL
, NULL
);
2986 g_hash_table_add(visited
, new_child
);
2987 ret_child
= child_class
->change_aio_ctx(new_child
, child_ctx
,
2988 visited
, tran
, NULL
);
2989 if (ret_child
== true) {
2990 error_free(local_err
);
2993 tran_finalize(tran
, ret_child
== true ? 0 : -1);
2994 g_hash_table_destroy(visited
);
2998 error_propagate(errp
, local_err
);
2999 bdrv_child_free(new_child
);
3005 bdrv_replace_child_noperm(new_child
, child_bs
);
3007 BdrvAttachChildCommonState
*s
= g_new(BdrvAttachChildCommonState
, 1);
3008 *s
= (BdrvAttachChildCommonState
) {
3010 .old_parent_ctx
= parent_ctx
,
3011 .old_child_ctx
= child_ctx
,
3013 tran_add(tran
, &bdrv_attach_child_common_drv
, s
);
3019 * Function doesn't update permissions, caller is responsible for this.
3021 static BdrvChild
*bdrv_attach_child_noperm(BlockDriverState
*parent_bs
,
3022 BlockDriverState
*child_bs
,
3023 const char *child_name
,
3024 const BdrvChildClass
*child_class
,
3025 BdrvChildRole child_role
,
3029 uint64_t perm
, shared_perm
;
3031 assert(parent_bs
->drv
);
3032 GLOBAL_STATE_CODE();
3034 if (bdrv_recurse_has_child(child_bs
, parent_bs
)) {
3035 error_setg(errp
, "Making '%s' a %s child of '%s' would create a cycle",
3036 child_bs
->node_name
, child_name
, parent_bs
->node_name
);
3040 bdrv_get_cumulative_perm(parent_bs
, &perm
, &shared_perm
);
3041 bdrv_child_perm(parent_bs
, child_bs
, NULL
, child_role
, NULL
,
3042 perm
, shared_perm
, &perm
, &shared_perm
);
3044 return bdrv_attach_child_common(child_bs
, child_name
, child_class
,
3045 child_role
, perm
, shared_perm
, parent_bs
,
3049 static void bdrv_detach_child(BdrvChild
*child
)
3051 BlockDriverState
*old_bs
= child
->bs
;
3053 GLOBAL_STATE_CODE();
3054 bdrv_replace_child_noperm(child
, NULL
);
3055 bdrv_child_free(child
);
3059 * Update permissions for old node. We're just taking a parent away, so
3060 * we're loosening restrictions. Errors of permission update are not
3061 * fatal in this case, ignore them.
3063 bdrv_refresh_perms(old_bs
, NULL
);
3066 * When the parent requiring a non-default AioContext is removed, the
3067 * node moves back to the main AioContext
3069 bdrv_try_change_aio_context(old_bs
, qemu_get_aio_context(), NULL
, NULL
);
3074 * This function steals the reference to child_bs from the caller.
3075 * That reference is later dropped by bdrv_root_unref_child().
3077 * On failure NULL is returned, errp is set and the reference to
3078 * child_bs is also dropped.
3080 * The caller must hold the AioContext lock @child_bs, but not that of @ctx
3081 * (unless @child_bs is already in @ctx).
3083 BdrvChild
*bdrv_root_attach_child(BlockDriverState
*child_bs
,
3084 const char *child_name
,
3085 const BdrvChildClass
*child_class
,
3086 BdrvChildRole child_role
,
3087 uint64_t perm
, uint64_t shared_perm
,
3088 void *opaque
, Error
**errp
)
3092 Transaction
*tran
= tran_new();
3094 GLOBAL_STATE_CODE();
3096 child
= bdrv_attach_child_common(child_bs
, child_name
, child_class
,
3097 child_role
, perm
, shared_perm
, opaque
,
3104 ret
= bdrv_refresh_perms(child_bs
, errp
);
3107 tran_finalize(tran
, ret
);
3109 bdrv_unref(child_bs
);
3111 return ret
< 0 ? NULL
: child
;
3115 * This function transfers the reference to child_bs from the caller
3116 * to parent_bs. That reference is later dropped by parent_bs on
3117 * bdrv_close() or if someone calls bdrv_unref_child().
3119 * On failure NULL is returned, errp is set and the reference to
3120 * child_bs is also dropped.
3122 * If @parent_bs and @child_bs are in different AioContexts, the caller must
3123 * hold the AioContext lock for @child_bs, but not for @parent_bs.
3125 BdrvChild
*bdrv_attach_child(BlockDriverState
*parent_bs
,
3126 BlockDriverState
*child_bs
,
3127 const char *child_name
,
3128 const BdrvChildClass
*child_class
,
3129 BdrvChildRole child_role
,
3134 Transaction
*tran
= tran_new();
3136 GLOBAL_STATE_CODE();
3138 child
= bdrv_attach_child_noperm(parent_bs
, child_bs
, child_name
,
3139 child_class
, child_role
, tran
, errp
);
3145 ret
= bdrv_refresh_perms(parent_bs
, errp
);
3151 tran_finalize(tran
, ret
);
3153 bdrv_unref(child_bs
);
3155 return ret
< 0 ? NULL
: child
;
3158 /* Callers must ensure that child->frozen is false. */
3159 void bdrv_root_unref_child(BdrvChild
*child
)
3161 BlockDriverState
*child_bs
;
3163 GLOBAL_STATE_CODE();
3165 child_bs
= child
->bs
;
3166 bdrv_detach_child(child
);
3167 bdrv_unref(child_bs
);
3170 typedef struct BdrvSetInheritsFrom
{
3171 BlockDriverState
*bs
;
3172 BlockDriverState
*old_inherits_from
;
3173 } BdrvSetInheritsFrom
;
3175 static void bdrv_set_inherits_from_abort(void *opaque
)
3177 BdrvSetInheritsFrom
*s
= opaque
;
3179 s
->bs
->inherits_from
= s
->old_inherits_from
;
3182 static TransactionActionDrv bdrv_set_inherits_from_drv
= {
3183 .abort
= bdrv_set_inherits_from_abort
,
3187 /* @tran is allowed to be NULL. In this case no rollback is possible */
3188 static void bdrv_set_inherits_from(BlockDriverState
*bs
,
3189 BlockDriverState
*new_inherits_from
,
3193 BdrvSetInheritsFrom
*s
= g_new(BdrvSetInheritsFrom
, 1);
3195 *s
= (BdrvSetInheritsFrom
) {
3197 .old_inherits_from
= bs
->inherits_from
,
3200 tran_add(tran
, &bdrv_set_inherits_from_drv
, s
);
3203 bs
->inherits_from
= new_inherits_from
;
3207 * Clear all inherits_from pointers from children and grandchildren of
3208 * @root that point to @root, where necessary.
3209 * @tran is allowed to be NULL. In this case no rollback is possible
3211 static void bdrv_unset_inherits_from(BlockDriverState
*root
, BdrvChild
*child
,
3216 if (child
->bs
->inherits_from
== root
) {
3218 * Remove inherits_from only when the last reference between root and
3219 * child->bs goes away.
3221 QLIST_FOREACH(c
, &root
->children
, next
) {
3222 if (c
!= child
&& c
->bs
== child
->bs
) {
3227 bdrv_set_inherits_from(child
->bs
, NULL
, tran
);
3231 QLIST_FOREACH(c
, &child
->bs
->children
, next
) {
3232 bdrv_unset_inherits_from(root
, c
, tran
);
3236 /* Callers must ensure that child->frozen is false. */
3237 void bdrv_unref_child(BlockDriverState
*parent
, BdrvChild
*child
)
3239 GLOBAL_STATE_CODE();
3240 if (child
== NULL
) {
3244 bdrv_unset_inherits_from(parent
, child
, NULL
);
3245 bdrv_root_unref_child(child
);
3249 static void bdrv_parent_cb_change_media(BlockDriverState
*bs
, bool load
)
3252 GLOBAL_STATE_CODE();
3253 QLIST_FOREACH(c
, &bs
->parents
, next_parent
) {
3254 if (c
->klass
->change_media
) {
3255 c
->klass
->change_media(c
, load
);
3260 /* Return true if you can reach parent going through child->inherits_from
3261 * recursively. If parent or child are NULL, return false */
3262 static bool bdrv_inherits_from_recursive(BlockDriverState
*child
,
3263 BlockDriverState
*parent
)
3265 while (child
&& child
!= parent
) {
3266 child
= child
->inherits_from
;
3269 return child
!= NULL
;
3273 * Return the BdrvChildRole for @bs's backing child. bs->backing is
3274 * mostly used for COW backing children (role = COW), but also for
3275 * filtered children (role = FILTERED | PRIMARY).
3277 static BdrvChildRole
bdrv_backing_role(BlockDriverState
*bs
)
3279 if (bs
->drv
&& bs
->drv
->is_filter
) {
3280 return BDRV_CHILD_FILTERED
| BDRV_CHILD_PRIMARY
;
3282 return BDRV_CHILD_COW
;
3287 * Sets the bs->backing or bs->file link of a BDS. A new reference is created;
3288 * callers which don't need their own reference any more must call bdrv_unref().
3290 * Function doesn't update permissions, caller is responsible for this.
3292 static int bdrv_set_file_or_backing_noperm(BlockDriverState
*parent_bs
,
3293 BlockDriverState
*child_bs
,
3295 Transaction
*tran
, Error
**errp
)
3297 bool update_inherits_from
=
3298 bdrv_inherits_from_recursive(child_bs
, parent_bs
);
3299 BdrvChild
*child
= is_backing
? parent_bs
->backing
: parent_bs
->file
;
3302 GLOBAL_STATE_CODE();
3304 if (!parent_bs
->drv
) {
3306 * Node without drv is an object without a class :/. TODO: finally fix
3307 * qcow2 driver to never clear bs->drv and implement format corruption
3308 * handling in other way.
3310 error_setg(errp
, "Node corrupted");
3314 if (child
&& child
->frozen
) {
3315 error_setg(errp
, "Cannot change frozen '%s' link from '%s' to '%s'",
3316 child
->name
, parent_bs
->node_name
, child
->bs
->node_name
);
3320 if (is_backing
&& !parent_bs
->drv
->is_filter
&&
3321 !parent_bs
->drv
->supports_backing
)
3323 error_setg(errp
, "Driver '%s' of node '%s' does not support backing "
3324 "files", parent_bs
->drv
->format_name
, parent_bs
->node_name
);
3328 if (parent_bs
->drv
->is_filter
) {
3329 role
= BDRV_CHILD_FILTERED
| BDRV_CHILD_PRIMARY
;
3330 } else if (is_backing
) {
3331 role
= BDRV_CHILD_COW
;
3334 * We only can use same role as it is in existing child. We don't have
3335 * infrastructure to determine role of file child in generic way
3338 error_setg(errp
, "Cannot set file child to format node without "
3346 bdrv_unset_inherits_from(parent_bs
, child
, tran
);
3347 bdrv_remove_child(child
, tran
);
3354 child
= bdrv_attach_child_noperm(parent_bs
, child_bs
,
3355 is_backing
? "backing" : "file",
3356 &child_of_bds
, role
,
3364 * If inherits_from pointed recursively to bs then let's update it to
3365 * point directly to bs (else it will become NULL).
3367 if (update_inherits_from
) {
3368 bdrv_set_inherits_from(child_bs
, parent_bs
, tran
);
3372 bdrv_refresh_limits(parent_bs
, tran
, NULL
);
3377 static int bdrv_set_backing_noperm(BlockDriverState
*bs
,
3378 BlockDriverState
*backing_hd
,
3379 Transaction
*tran
, Error
**errp
)
3381 GLOBAL_STATE_CODE();
3382 return bdrv_set_file_or_backing_noperm(bs
, backing_hd
, true, tran
, errp
);
3385 int bdrv_set_backing_hd(BlockDriverState
*bs
, BlockDriverState
*backing_hd
,
3389 Transaction
*tran
= tran_new();
3391 GLOBAL_STATE_CODE();
3392 bdrv_drained_begin(bs
);
3394 ret
= bdrv_set_backing_noperm(bs
, backing_hd
, tran
, errp
);
3399 ret
= bdrv_refresh_perms(bs
, errp
);
3401 tran_finalize(tran
, ret
);
3403 bdrv_drained_end(bs
);
3409 * Opens the backing file for a BlockDriverState if not yet open
3411 * bdref_key specifies the key for the image's BlockdevRef in the options QDict.
3412 * That QDict has to be flattened; therefore, if the BlockdevRef is a QDict
3413 * itself, all options starting with "${bdref_key}." are considered part of the
3416 * TODO Can this be unified with bdrv_open_image()?
3418 int bdrv_open_backing_file(BlockDriverState
*bs
, QDict
*parent_options
,
3419 const char *bdref_key
, Error
**errp
)
3421 char *backing_filename
= NULL
;
3422 char *bdref_key_dot
;
3423 const char *reference
= NULL
;
3425 bool implicit_backing
= false;
3426 BlockDriverState
*backing_hd
;
3428 QDict
*tmp_parent_options
= NULL
;
3429 Error
*local_err
= NULL
;
3431 GLOBAL_STATE_CODE();
3433 if (bs
->backing
!= NULL
) {
3437 /* NULL means an empty set of options */
3438 if (parent_options
== NULL
) {
3439 tmp_parent_options
= qdict_new();
3440 parent_options
= tmp_parent_options
;
3443 bs
->open_flags
&= ~BDRV_O_NO_BACKING
;
3445 bdref_key_dot
= g_strdup_printf("%s.", bdref_key
);
3446 qdict_extract_subqdict(parent_options
, &options
, bdref_key_dot
);
3447 g_free(bdref_key_dot
);
3450 * Caution: while qdict_get_try_str() is fine, getting non-string
3451 * types would require more care. When @parent_options come from
3452 * -blockdev or blockdev_add, its members are typed according to
3453 * the QAPI schema, but when they come from -drive, they're all
3456 reference
= qdict_get_try_str(parent_options
, bdref_key
);
3457 if (reference
|| qdict_haskey(options
, "file.filename")) {
3458 /* keep backing_filename NULL */
3459 } else if (bs
->backing_file
[0] == '\0' && qdict_size(options
) == 0) {
3460 qobject_unref(options
);
3463 if (qdict_size(options
) == 0) {
3464 /* If the user specifies options that do not modify the
3465 * backing file's behavior, we might still consider it the
3466 * implicit backing file. But it's easier this way, and
3467 * just specifying some of the backing BDS's options is
3468 * only possible with -drive anyway (otherwise the QAPI
3469 * schema forces the user to specify everything). */
3470 implicit_backing
= !strcmp(bs
->auto_backing_file
, bs
->backing_file
);
3473 backing_filename
= bdrv_get_full_backing_filename(bs
, &local_err
);
3476 error_propagate(errp
, local_err
);
3477 qobject_unref(options
);
3482 if (!bs
->drv
|| !bs
->drv
->supports_backing
) {
3484 error_setg(errp
, "Driver doesn't support backing files");
3485 qobject_unref(options
);
3490 bs
->backing_format
[0] != '\0' && !qdict_haskey(options
, "driver")) {
3491 qdict_put_str(options
, "driver", bs
->backing_format
);
3494 backing_hd
= bdrv_open_inherit(backing_filename
, reference
, options
, 0, bs
,
3495 &child_of_bds
, bdrv_backing_role(bs
), errp
);
3497 bs
->open_flags
|= BDRV_O_NO_BACKING
;
3498 error_prepend(errp
, "Could not open backing file: ");
3503 if (implicit_backing
) {
3504 bdrv_refresh_filename(backing_hd
);
3505 pstrcpy(bs
->auto_backing_file
, sizeof(bs
->auto_backing_file
),
3506 backing_hd
->filename
);
3509 /* Hook up the backing file link; drop our reference, bs owns the
3510 * backing_hd reference now */
3511 ret
= bdrv_set_backing_hd(bs
, backing_hd
, errp
);
3512 bdrv_unref(backing_hd
);
3517 qdict_del(parent_options
, bdref_key
);
3520 g_free(backing_filename
);
3521 qobject_unref(tmp_parent_options
);
3525 static BlockDriverState
*
3526 bdrv_open_child_bs(const char *filename
, QDict
*options
, const char *bdref_key
,
3527 BlockDriverState
*parent
, const BdrvChildClass
*child_class
,
3528 BdrvChildRole child_role
, bool allow_none
, Error
**errp
)
3530 BlockDriverState
*bs
= NULL
;
3531 QDict
*image_options
;
3532 char *bdref_key_dot
;
3533 const char *reference
;
3535 assert(child_class
!= NULL
);
3537 bdref_key_dot
= g_strdup_printf("%s.", bdref_key
);
3538 qdict_extract_subqdict(options
, &image_options
, bdref_key_dot
);
3539 g_free(bdref_key_dot
);
3542 * Caution: while qdict_get_try_str() is fine, getting non-string
3543 * types would require more care. When @options come from
3544 * -blockdev or blockdev_add, its members are typed according to
3545 * the QAPI schema, but when they come from -drive, they're all
3548 reference
= qdict_get_try_str(options
, bdref_key
);
3549 if (!filename
&& !reference
&& !qdict_size(image_options
)) {
3551 error_setg(errp
, "A block device must be specified for \"%s\"",
3554 qobject_unref(image_options
);
3558 bs
= bdrv_open_inherit(filename
, reference
, image_options
, 0,
3559 parent
, child_class
, child_role
, errp
);
3565 qdict_del(options
, bdref_key
);
3570 * Opens a disk image whose options are given as BlockdevRef in another block
3573 * If allow_none is true, no image will be opened if filename is false and no
3574 * BlockdevRef is given. NULL will be returned, but errp remains unset.
3576 * bdrev_key specifies the key for the image's BlockdevRef in the options QDict.
3577 * That QDict has to be flattened; therefore, if the BlockdevRef is a QDict
3578 * itself, all options starting with "${bdref_key}." are considered part of the
3581 * The BlockdevRef will be removed from the options QDict.
3583 BdrvChild
*bdrv_open_child(const char *filename
,
3584 QDict
*options
, const char *bdref_key
,
3585 BlockDriverState
*parent
,
3586 const BdrvChildClass
*child_class
,
3587 BdrvChildRole child_role
,
3588 bool allow_none
, Error
**errp
)
3590 BlockDriverState
*bs
;
3592 GLOBAL_STATE_CODE();
3594 bs
= bdrv_open_child_bs(filename
, options
, bdref_key
, parent
, child_class
,
3595 child_role
, allow_none
, errp
);
3600 return bdrv_attach_child(parent
, bs
, bdref_key
, child_class
, child_role
,
3605 * Wrapper on bdrv_open_child() for most popular case: open primary child of bs.
3607 int bdrv_open_file_child(const char *filename
,
3608 QDict
*options
, const char *bdref_key
,
3609 BlockDriverState
*parent
, Error
**errp
)
3613 /* commit_top and mirror_top don't use this function */
3614 assert(!parent
->drv
->filtered_child_is_backing
);
3615 role
= parent
->drv
->is_filter
?
3616 (BDRV_CHILD_FILTERED
| BDRV_CHILD_PRIMARY
) : BDRV_CHILD_IMAGE
;
3618 if (!bdrv_open_child(filename
, options
, bdref_key
, parent
,
3619 &child_of_bds
, role
, false, errp
))
3628 * TODO Future callers may need to specify parent/child_class in order for
3629 * option inheritance to work. Existing callers use it for the root node.
3631 BlockDriverState
*bdrv_open_blockdev_ref(BlockdevRef
*ref
, Error
**errp
)
3633 BlockDriverState
*bs
= NULL
;
3634 QObject
*obj
= NULL
;
3635 QDict
*qdict
= NULL
;
3636 const char *reference
= NULL
;
3639 GLOBAL_STATE_CODE();
3641 if (ref
->type
== QTYPE_QSTRING
) {
3642 reference
= ref
->u
.reference
;
3644 BlockdevOptions
*options
= &ref
->u
.definition
;
3645 assert(ref
->type
== QTYPE_QDICT
);
3647 v
= qobject_output_visitor_new(&obj
);
3648 visit_type_BlockdevOptions(v
, NULL
, &options
, &error_abort
);
3649 visit_complete(v
, &obj
);
3651 qdict
= qobject_to(QDict
, obj
);
3652 qdict_flatten(qdict
);
3654 /* bdrv_open_inherit() defaults to the values in bdrv_flags (for
3655 * compatibility with other callers) rather than what we want as the
3656 * real defaults. Apply the defaults here instead. */
3657 qdict_set_default_str(qdict
, BDRV_OPT_CACHE_DIRECT
, "off");
3658 qdict_set_default_str(qdict
, BDRV_OPT_CACHE_NO_FLUSH
, "off");
3659 qdict_set_default_str(qdict
, BDRV_OPT_READ_ONLY
, "off");
3660 qdict_set_default_str(qdict
, BDRV_OPT_AUTO_READ_ONLY
, "off");
3664 bs
= bdrv_open_inherit(NULL
, reference
, qdict
, 0, NULL
, NULL
, 0, errp
);
3671 static BlockDriverState
*bdrv_append_temp_snapshot(BlockDriverState
*bs
,
3673 QDict
*snapshot_options
,
3676 g_autofree
char *tmp_filename
= NULL
;
3678 QemuOpts
*opts
= NULL
;
3679 BlockDriverState
*bs_snapshot
= NULL
;
3682 GLOBAL_STATE_CODE();
3684 /* if snapshot, we create a temporary backing file and open it
3685 instead of opening 'filename' directly */
3687 /* Get the required size from the image */
3688 total_size
= bdrv_getlength(bs
);
3689 if (total_size
< 0) {
3690 error_setg_errno(errp
, -total_size
, "Could not get image size");
3694 /* Create the temporary image */
3695 tmp_filename
= create_tmp_file(errp
);
3696 if (!tmp_filename
) {
3700 opts
= qemu_opts_create(bdrv_qcow2
.create_opts
, NULL
, 0,
3702 qemu_opt_set_number(opts
, BLOCK_OPT_SIZE
, total_size
, &error_abort
);
3703 ret
= bdrv_create(&bdrv_qcow2
, tmp_filename
, opts
, errp
);
3704 qemu_opts_del(opts
);
3706 error_prepend(errp
, "Could not create temporary overlay '%s': ",
3711 /* Prepare options QDict for the temporary file */
3712 qdict_put_str(snapshot_options
, "file.driver", "file");
3713 qdict_put_str(snapshot_options
, "file.filename", tmp_filename
);
3714 qdict_put_str(snapshot_options
, "driver", "qcow2");
3716 bs_snapshot
= bdrv_open(NULL
, NULL
, snapshot_options
, flags
, errp
);
3717 snapshot_options
= NULL
;
3722 ret
= bdrv_append(bs_snapshot
, bs
, errp
);
3729 qobject_unref(snapshot_options
);
3734 * Opens a disk image (raw, qcow2, vmdk, ...)
3736 * options is a QDict of options to pass to the block drivers, or NULL for an
3737 * empty set of options. The reference to the QDict belongs to the block layer
3738 * after the call (even on failure), so if the caller intends to reuse the
3739 * dictionary, it needs to use qobject_ref() before calling bdrv_open.
3741 * If *pbs is NULL, a new BDS will be created with a pointer to it stored there.
3742 * If it is not NULL, the referenced BDS will be reused.
3744 * The reference parameter may be used to specify an existing block device which
3745 * should be opened. If specified, neither options nor a filename may be given,
3746 * nor can an existing BDS be reused (that is, *pbs has to be NULL).
3748 static BlockDriverState
*bdrv_open_inherit(const char *filename
,
3749 const char *reference
,
3750 QDict
*options
, int flags
,
3751 BlockDriverState
*parent
,
3752 const BdrvChildClass
*child_class
,
3753 BdrvChildRole child_role
,
3757 BlockBackend
*file
= NULL
;
3758 BlockDriverState
*bs
;
3759 BlockDriver
*drv
= NULL
;
3761 const char *drvname
;
3762 const char *backing
;
3763 Error
*local_err
= NULL
;
3764 QDict
*snapshot_options
= NULL
;
3765 int snapshot_flags
= 0;
3767 assert(!child_class
|| !flags
);
3768 assert(!child_class
== !parent
);
3769 GLOBAL_STATE_CODE();
3772 bool options_non_empty
= options
? qdict_size(options
) : false;
3773 qobject_unref(options
);
3775 if (filename
|| options_non_empty
) {
3776 error_setg(errp
, "Cannot reference an existing block device with "
3777 "additional options or a new filename");
3781 bs
= bdrv_lookup_bs(reference
, reference
, errp
);
3792 /* NULL means an empty set of options */
3793 if (options
== NULL
) {
3794 options
= qdict_new();
3797 /* json: syntax counts as explicit options, as if in the QDict */
3798 parse_json_protocol(options
, &filename
, &local_err
);
3803 bs
->explicit_options
= qdict_clone_shallow(options
);
3806 bool parent_is_format
;
3809 parent_is_format
= parent
->drv
->is_format
;
3812 * parent->drv is not set yet because this node is opened for
3813 * (potential) format probing. That means that @parent is going
3814 * to be a format node.
3816 parent_is_format
= true;
3819 bs
->inherits_from
= parent
;
3820 child_class
->inherit_options(child_role
, parent_is_format
,
3822 parent
->open_flags
, parent
->options
);
3825 ret
= bdrv_fill_options(&options
, filename
, &flags
, &local_err
);
3831 * Set the BDRV_O_RDWR and BDRV_O_ALLOW_RDWR flags.
3832 * Caution: getting a boolean member of @options requires care.
3833 * When @options come from -blockdev or blockdev_add, members are
3834 * typed according to the QAPI schema, but when they come from
3835 * -drive, they're all QString.
3837 if (g_strcmp0(qdict_get_try_str(options
, BDRV_OPT_READ_ONLY
), "on") &&
3838 !qdict_get_try_bool(options
, BDRV_OPT_READ_ONLY
, false)) {
3839 flags
|= (BDRV_O_RDWR
| BDRV_O_ALLOW_RDWR
);
3841 flags
&= ~BDRV_O_RDWR
;
3844 if (flags
& BDRV_O_SNAPSHOT
) {
3845 snapshot_options
= qdict_new();
3846 bdrv_temp_snapshot_options(&snapshot_flags
, snapshot_options
,
3848 /* Let bdrv_backing_options() override "read-only" */
3849 qdict_del(options
, BDRV_OPT_READ_ONLY
);
3850 bdrv_inherited_options(BDRV_CHILD_COW
, true,
3851 &flags
, options
, flags
, options
);
3854 bs
->open_flags
= flags
;
3855 bs
->options
= options
;
3856 options
= qdict_clone_shallow(options
);
3858 /* Find the right image format driver */
3859 /* See cautionary note on accessing @options above */
3860 drvname
= qdict_get_try_str(options
, "driver");
3862 drv
= bdrv_find_format(drvname
);
3864 error_setg(errp
, "Unknown driver: '%s'", drvname
);
3869 assert(drvname
|| !(flags
& BDRV_O_PROTOCOL
));
3871 /* See cautionary note on accessing @options above */
3872 backing
= qdict_get_try_str(options
, "backing");
3873 if (qobject_to(QNull
, qdict_get(options
, "backing")) != NULL
||
3874 (backing
&& *backing
== '\0'))
3877 warn_report("Use of \"backing\": \"\" is deprecated; "
3878 "use \"backing\": null instead");
3880 flags
|= BDRV_O_NO_BACKING
;
3881 qdict_del(bs
->explicit_options
, "backing");
3882 qdict_del(bs
->options
, "backing");
3883 qdict_del(options
, "backing");
3886 /* Open image file without format layer. This BlockBackend is only used for
3887 * probing, the block drivers will do their own bdrv_open_child() for the
3888 * same BDS, which is why we put the node name back into options. */
3889 if ((flags
& BDRV_O_PROTOCOL
) == 0) {
3890 BlockDriverState
*file_bs
;
3892 file_bs
= bdrv_open_child_bs(filename
, options
, "file", bs
,
3893 &child_of_bds
, BDRV_CHILD_IMAGE
,
3898 if (file_bs
!= NULL
) {
3899 /* Not requesting BLK_PERM_CONSISTENT_READ because we're only
3900 * looking at the header to guess the image format. This works even
3901 * in cases where a guest would not see a consistent state. */
3902 file
= blk_new(bdrv_get_aio_context(file_bs
), 0, BLK_PERM_ALL
);
3903 blk_insert_bs(file
, file_bs
, &local_err
);
3904 bdrv_unref(file_bs
);
3909 qdict_put_str(options
, "file", bdrv_get_node_name(file_bs
));
3913 /* Image format probing */
3916 ret
= find_image_format(file
, filename
, &drv
, &local_err
);
3921 * This option update would logically belong in bdrv_fill_options(),
3922 * but we first need to open bs->file for the probing to work, while
3923 * opening bs->file already requires the (mostly) final set of options
3924 * so that cache mode etc. can be inherited.
3926 * Adding the driver later is somewhat ugly, but it's not an option
3927 * that would ever be inherited, so it's correct. We just need to make
3928 * sure to update both bs->options (which has the full effective
3929 * options for bs) and options (which has file.* already removed).
3931 qdict_put_str(bs
->options
, "driver", drv
->format_name
);
3932 qdict_put_str(options
, "driver", drv
->format_name
);
3934 error_setg(errp
, "Must specify either driver or file");
3938 /* BDRV_O_PROTOCOL must be set iff a protocol BDS is about to be created */
3939 assert(!!(flags
& BDRV_O_PROTOCOL
) == !!drv
->bdrv_file_open
);
3940 /* file must be NULL if a protocol BDS is about to be created
3941 * (the inverse results in an error message from bdrv_open_common()) */
3942 assert(!(flags
& BDRV_O_PROTOCOL
) || !file
);
3944 /* Open the image */
3945 ret
= bdrv_open_common(bs
, file
, options
, &local_err
);
3955 /* If there is a backing file, use it */
3956 if ((flags
& BDRV_O_NO_BACKING
) == 0) {
3957 ret
= bdrv_open_backing_file(bs
, options
, "backing", &local_err
);
3959 goto close_and_fail
;
3963 /* Remove all children options and references
3964 * from bs->options and bs->explicit_options */
3965 QLIST_FOREACH(child
, &bs
->children
, next
) {
3966 char *child_key_dot
;
3967 child_key_dot
= g_strdup_printf("%s.", child
->name
);
3968 qdict_extract_subqdict(bs
->explicit_options
, NULL
, child_key_dot
);
3969 qdict_extract_subqdict(bs
->options
, NULL
, child_key_dot
);
3970 qdict_del(bs
->explicit_options
, child
->name
);
3971 qdict_del(bs
->options
, child
->name
);
3972 g_free(child_key_dot
);
3975 /* Check if any unknown options were used */
3976 if (qdict_size(options
) != 0) {
3977 const QDictEntry
*entry
= qdict_first(options
);
3978 if (flags
& BDRV_O_PROTOCOL
) {
3979 error_setg(errp
, "Block protocol '%s' doesn't support the option "
3980 "'%s'", drv
->format_name
, entry
->key
);
3983 "Block format '%s' does not support the option '%s'",
3984 drv
->format_name
, entry
->key
);
3987 goto close_and_fail
;
3990 bdrv_parent_cb_change_media(bs
, true);
3992 qobject_unref(options
);
3995 /* For snapshot=on, create a temporary qcow2 overlay. bs points to the
3996 * temporary snapshot afterwards. */
3997 if (snapshot_flags
) {
3998 BlockDriverState
*snapshot_bs
;
3999 snapshot_bs
= bdrv_append_temp_snapshot(bs
, snapshot_flags
,
4000 snapshot_options
, &local_err
);
4001 snapshot_options
= NULL
;
4003 goto close_and_fail
;
4005 /* We are not going to return bs but the overlay on top of it
4006 * (snapshot_bs); thus, we have to drop the strong reference to bs
4007 * (which we obtained by calling bdrv_new()). bs will not be deleted,
4008 * though, because the overlay still has a reference to it. */
4017 qobject_unref(snapshot_options
);
4018 qobject_unref(bs
->explicit_options
);
4019 qobject_unref(bs
->options
);
4020 qobject_unref(options
);
4022 bs
->explicit_options
= NULL
;
4024 error_propagate(errp
, local_err
);
4029 qobject_unref(snapshot_options
);
4030 qobject_unref(options
);
4031 error_propagate(errp
, local_err
);
4035 BlockDriverState
*bdrv_open(const char *filename
, const char *reference
,
4036 QDict
*options
, int flags
, Error
**errp
)
4038 GLOBAL_STATE_CODE();
4040 return bdrv_open_inherit(filename
, reference
, options
, flags
, NULL
,
4044 /* Return true if the NULL-terminated @list contains @str */
4045 static bool is_str_in_list(const char *str
, const char *const *list
)
4049 for (i
= 0; list
[i
] != NULL
; i
++) {
4050 if (!strcmp(str
, list
[i
])) {
4059 * Check that every option set in @bs->options is also set in
4062 * Options listed in the common_options list and in
4063 * @bs->drv->mutable_opts are skipped.
4065 * Return 0 on success, otherwise return -EINVAL and set @errp.
4067 static int bdrv_reset_options_allowed(BlockDriverState
*bs
,
4068 const QDict
*new_opts
, Error
**errp
)
4070 const QDictEntry
*e
;
4071 /* These options are common to all block drivers and are handled
4072 * in bdrv_reopen_prepare() so they can be left out of @new_opts */
4073 const char *const common_options
[] = {
4074 "node-name", "discard", "cache.direct", "cache.no-flush",
4075 "read-only", "auto-read-only", "detect-zeroes", NULL
4078 for (e
= qdict_first(bs
->options
); e
; e
= qdict_next(bs
->options
, e
)) {
4079 if (!qdict_haskey(new_opts
, e
->key
) &&
4080 !is_str_in_list(e
->key
, common_options
) &&
4081 !is_str_in_list(e
->key
, bs
->drv
->mutable_opts
)) {
4082 error_setg(errp
, "Option '%s' cannot be reset "
4083 "to its default value", e
->key
);
4092 * Returns true if @child can be reached recursively from @bs
4094 static bool bdrv_recurse_has_child(BlockDriverState
*bs
,
4095 BlockDriverState
*child
)
4103 QLIST_FOREACH(c
, &bs
->children
, next
) {
4104 if (bdrv_recurse_has_child(c
->bs
, child
)) {
4113 * Adds a BlockDriverState to a simple queue for an atomic, transactional
4114 * reopen of multiple devices.
4116 * bs_queue can either be an existing BlockReopenQueue that has had QTAILQ_INIT
4117 * already performed, or alternatively may be NULL a new BlockReopenQueue will
4118 * be created and initialized. This newly created BlockReopenQueue should be
4119 * passed back in for subsequent calls that are intended to be of the same
4122 * bs is the BlockDriverState to add to the reopen queue.
4124 * options contains the changed options for the associated bs
4125 * (the BlockReopenQueue takes ownership)
4127 * flags contains the open flags for the associated bs
4129 * returns a pointer to bs_queue, which is either the newly allocated
4130 * bs_queue, or the existing bs_queue being used.
4132 * bs must be drained between bdrv_reopen_queue() and bdrv_reopen_multiple().
4134 static BlockReopenQueue
*bdrv_reopen_queue_child(BlockReopenQueue
*bs_queue
,
4135 BlockDriverState
*bs
,
4137 const BdrvChildClass
*klass
,
4139 bool parent_is_format
,
4140 QDict
*parent_options
,
4146 BlockReopenQueueEntry
*bs_entry
;
4148 QDict
*old_options
, *explicit_options
, *options_copy
;
4152 /* Make sure that the caller remembered to use a drained section. This is
4153 * important to avoid graph changes between the recursive queuing here and
4154 * bdrv_reopen_multiple(). */
4155 assert(bs
->quiesce_counter
> 0);
4156 GLOBAL_STATE_CODE();
4158 if (bs_queue
== NULL
) {
4159 bs_queue
= g_new0(BlockReopenQueue
, 1);
4160 QTAILQ_INIT(bs_queue
);
4164 options
= qdict_new();
4167 /* Check if this BlockDriverState is already in the queue */
4168 QTAILQ_FOREACH(bs_entry
, bs_queue
, entry
) {
4169 if (bs
== bs_entry
->state
.bs
) {
4175 * Precedence of options:
4176 * 1. Explicitly passed in options (highest)
4177 * 2. Retained from explicitly set options of bs
4178 * 3. Inherited from parent node
4179 * 4. Retained from effective options of bs
4182 /* Old explicitly set values (don't overwrite by inherited value) */
4183 if (bs_entry
|| keep_old_opts
) {
4184 old_options
= qdict_clone_shallow(bs_entry
?
4185 bs_entry
->state
.explicit_options
:
4186 bs
->explicit_options
);
4187 bdrv_join_options(bs
, options
, old_options
);
4188 qobject_unref(old_options
);
4191 explicit_options
= qdict_clone_shallow(options
);
4193 /* Inherit from parent node */
4194 if (parent_options
) {
4196 klass
->inherit_options(role
, parent_is_format
, &flags
, options
,
4197 parent_flags
, parent_options
);
4199 flags
= bdrv_get_flags(bs
);
4202 if (keep_old_opts
) {
4203 /* Old values are used for options that aren't set yet */
4204 old_options
= qdict_clone_shallow(bs
->options
);
4205 bdrv_join_options(bs
, options
, old_options
);
4206 qobject_unref(old_options
);
4209 /* We have the final set of options so let's update the flags */
4210 options_copy
= qdict_clone_shallow(options
);
4211 opts
= qemu_opts_create(&bdrv_runtime_opts
, NULL
, 0, &error_abort
);
4212 qemu_opts_absorb_qdict(opts
, options_copy
, NULL
);
4213 update_flags_from_options(&flags
, opts
);
4214 qemu_opts_del(opts
);
4215 qobject_unref(options_copy
);
4217 /* bdrv_open_inherit() sets and clears some additional flags internally */
4218 flags
&= ~BDRV_O_PROTOCOL
;
4219 if (flags
& BDRV_O_RDWR
) {
4220 flags
|= BDRV_O_ALLOW_RDWR
;
4224 bs_entry
= g_new0(BlockReopenQueueEntry
, 1);
4225 QTAILQ_INSERT_TAIL(bs_queue
, bs_entry
, entry
);
4227 qobject_unref(bs_entry
->state
.options
);
4228 qobject_unref(bs_entry
->state
.explicit_options
);
4231 bs_entry
->state
.bs
= bs
;
4232 bs_entry
->state
.options
= options
;
4233 bs_entry
->state
.explicit_options
= explicit_options
;
4234 bs_entry
->state
.flags
= flags
;
4237 * If keep_old_opts is false then it means that unspecified
4238 * options must be reset to their original value. We don't allow
4239 * resetting 'backing' but we need to know if the option is
4240 * missing in order to decide if we have to return an error.
4242 if (!keep_old_opts
) {
4243 bs_entry
->state
.backing_missing
=
4244 !qdict_haskey(options
, "backing") &&
4245 !qdict_haskey(options
, "backing.driver");
4248 QLIST_FOREACH(child
, &bs
->children
, next
) {
4249 QDict
*new_child_options
= NULL
;
4250 bool child_keep_old
= keep_old_opts
;
4252 /* reopen can only change the options of block devices that were
4253 * implicitly created and inherited options. For other (referenced)
4254 * block devices, a syntax like "backing.foo" results in an error. */
4255 if (child
->bs
->inherits_from
!= bs
) {
4259 /* Check if the options contain a child reference */
4260 if (qdict_haskey(options
, child
->name
)) {
4261 const char *childref
= qdict_get_try_str(options
, child
->name
);
4263 * The current child must not be reopened if the child
4264 * reference is null or points to a different node.
4266 if (g_strcmp0(childref
, child
->bs
->node_name
)) {
4270 * If the child reference points to the current child then
4271 * reopen it with its existing set of options (note that
4272 * it can still inherit new options from the parent).
4274 child_keep_old
= true;
4276 /* Extract child options ("child-name.*") */
4277 char *child_key_dot
= g_strdup_printf("%s.", child
->name
);
4278 qdict_extract_subqdict(explicit_options
, NULL
, child_key_dot
);
4279 qdict_extract_subqdict(options
, &new_child_options
, child_key_dot
);
4280 g_free(child_key_dot
);
4283 bdrv_reopen_queue_child(bs_queue
, child
->bs
, new_child_options
,
4284 child
->klass
, child
->role
, bs
->drv
->is_format
,
4285 options
, flags
, child_keep_old
);
4291 BlockReopenQueue
*bdrv_reopen_queue(BlockReopenQueue
*bs_queue
,
4292 BlockDriverState
*bs
,
4293 QDict
*options
, bool keep_old_opts
)
4295 GLOBAL_STATE_CODE();
4297 return bdrv_reopen_queue_child(bs_queue
, bs
, options
, NULL
, 0, false,
4298 NULL
, 0, keep_old_opts
);
4301 void bdrv_reopen_queue_free(BlockReopenQueue
*bs_queue
)
4303 GLOBAL_STATE_CODE();
4305 BlockReopenQueueEntry
*bs_entry
, *next
;
4306 QTAILQ_FOREACH_SAFE(bs_entry
, bs_queue
, entry
, next
) {
4307 qobject_unref(bs_entry
->state
.explicit_options
);
4308 qobject_unref(bs_entry
->state
.options
);
4316 * Reopen multiple BlockDriverStates atomically & transactionally.
4318 * The queue passed in (bs_queue) must have been built up previous
4319 * via bdrv_reopen_queue().
4321 * Reopens all BDS specified in the queue, with the appropriate
4322 * flags. All devices are prepared for reopen, and failure of any
4323 * device will cause all device changes to be abandoned, and intermediate
4326 * If all devices prepare successfully, then the changes are committed
4329 * All affected nodes must be drained between bdrv_reopen_queue() and
4330 * bdrv_reopen_multiple().
4332 * To be called from the main thread, with all other AioContexts unlocked.
4334 int bdrv_reopen_multiple(BlockReopenQueue
*bs_queue
, Error
**errp
)
4337 BlockReopenQueueEntry
*bs_entry
, *next
;
4339 Transaction
*tran
= tran_new();
4340 g_autoptr(GHashTable
) found
= NULL
;
4341 g_autoptr(GSList
) refresh_list
= NULL
;
4343 assert(qemu_get_current_aio_context() == qemu_get_aio_context());
4344 assert(bs_queue
!= NULL
);
4345 GLOBAL_STATE_CODE();
4347 QTAILQ_FOREACH(bs_entry
, bs_queue
, entry
) {
4348 ctx
= bdrv_get_aio_context(bs_entry
->state
.bs
);
4349 aio_context_acquire(ctx
);
4350 ret
= bdrv_flush(bs_entry
->state
.bs
);
4351 aio_context_release(ctx
);
4353 error_setg_errno(errp
, -ret
, "Error flushing drive");
4358 QTAILQ_FOREACH(bs_entry
, bs_queue
, entry
) {
4359 assert(bs_entry
->state
.bs
->quiesce_counter
> 0);
4360 ctx
= bdrv_get_aio_context(bs_entry
->state
.bs
);
4361 aio_context_acquire(ctx
);
4362 ret
= bdrv_reopen_prepare(&bs_entry
->state
, bs_queue
, tran
, errp
);
4363 aio_context_release(ctx
);
4367 bs_entry
->prepared
= true;
4370 found
= g_hash_table_new(NULL
, NULL
);
4371 QTAILQ_FOREACH(bs_entry
, bs_queue
, entry
) {
4372 BDRVReopenState
*state
= &bs_entry
->state
;
4374 refresh_list
= bdrv_topological_dfs(refresh_list
, found
, state
->bs
);
4375 if (state
->old_backing_bs
) {
4376 refresh_list
= bdrv_topological_dfs(refresh_list
, found
,
4377 state
->old_backing_bs
);
4379 if (state
->old_file_bs
) {
4380 refresh_list
= bdrv_topological_dfs(refresh_list
, found
,
4381 state
->old_file_bs
);
4386 * Note that file-posix driver rely on permission update done during reopen
4387 * (even if no permission changed), because it wants "new" permissions for
4388 * reconfiguring the fd and that's why it does it in raw_check_perm(), not
4389 * in raw_reopen_prepare() which is called with "old" permissions.
4391 ret
= bdrv_list_refresh_perms(refresh_list
, bs_queue
, tran
, errp
);
4397 * If we reach this point, we have success and just need to apply the
4400 * Reverse order is used to comfort qcow2 driver: on commit it need to write
4401 * IN_USE flag to the image, to mark bitmaps in the image as invalid. But
4402 * children are usually goes after parents in reopen-queue, so go from last
4405 QTAILQ_FOREACH_REVERSE(bs_entry
, bs_queue
, entry
) {
4406 ctx
= bdrv_get_aio_context(bs_entry
->state
.bs
);
4407 aio_context_acquire(ctx
);
4408 bdrv_reopen_commit(&bs_entry
->state
);
4409 aio_context_release(ctx
);
4414 QTAILQ_FOREACH_REVERSE(bs_entry
, bs_queue
, entry
) {
4415 BlockDriverState
*bs
= bs_entry
->state
.bs
;
4417 if (bs
->drv
->bdrv_reopen_commit_post
) {
4418 ctx
= bdrv_get_aio_context(bs
);
4419 aio_context_acquire(ctx
);
4420 bs
->drv
->bdrv_reopen_commit_post(&bs_entry
->state
);
4421 aio_context_release(ctx
);
4430 QTAILQ_FOREACH_SAFE(bs_entry
, bs_queue
, entry
, next
) {
4431 if (bs_entry
->prepared
) {
4432 ctx
= bdrv_get_aio_context(bs_entry
->state
.bs
);
4433 aio_context_acquire(ctx
);
4434 bdrv_reopen_abort(&bs_entry
->state
);
4435 aio_context_release(ctx
);
4440 bdrv_reopen_queue_free(bs_queue
);
4445 int bdrv_reopen(BlockDriverState
*bs
, QDict
*opts
, bool keep_old_opts
,
4448 AioContext
*ctx
= bdrv_get_aio_context(bs
);
4449 BlockReopenQueue
*queue
;
4452 GLOBAL_STATE_CODE();
4454 bdrv_subtree_drained_begin(bs
);
4455 if (ctx
!= qemu_get_aio_context()) {
4456 aio_context_release(ctx
);
4459 queue
= bdrv_reopen_queue(NULL
, bs
, opts
, keep_old_opts
);
4460 ret
= bdrv_reopen_multiple(queue
, errp
);
4462 if (ctx
!= qemu_get_aio_context()) {
4463 aio_context_acquire(ctx
);
4465 bdrv_subtree_drained_end(bs
);
4470 int bdrv_reopen_set_read_only(BlockDriverState
*bs
, bool read_only
,
4473 QDict
*opts
= qdict_new();
4475 GLOBAL_STATE_CODE();
4477 qdict_put_bool(opts
, BDRV_OPT_READ_ONLY
, read_only
);
4479 return bdrv_reopen(bs
, opts
, true, errp
);
4483 * Take a BDRVReopenState and check if the value of 'backing' in the
4484 * reopen_state->options QDict is valid or not.
4486 * If 'backing' is missing from the QDict then return 0.
4488 * If 'backing' contains the node name of the backing file of
4489 * reopen_state->bs then return 0.
4491 * If 'backing' contains a different node name (or is null) then check
4492 * whether the current backing file can be replaced with the new one.
4493 * If that's the case then reopen_state->replace_backing_bs is set to
4494 * true and reopen_state->new_backing_bs contains a pointer to the new
4495 * backing BlockDriverState (or NULL).
4497 * Return 0 on success, otherwise return < 0 and set @errp.
4499 static int bdrv_reopen_parse_file_or_backing(BDRVReopenState
*reopen_state
,
4500 bool is_backing
, Transaction
*tran
,
4503 BlockDriverState
*bs
= reopen_state
->bs
;
4504 BlockDriverState
*new_child_bs
;
4505 BlockDriverState
*old_child_bs
= is_backing
? child_bs(bs
->backing
) :
4507 const char *child_name
= is_backing
? "backing" : "file";
4511 GLOBAL_STATE_CODE();
4513 value
= qdict_get(reopen_state
->options
, child_name
);
4514 if (value
== NULL
) {
4518 switch (qobject_type(value
)) {
4520 assert(is_backing
); /* The 'file' option does not allow a null value */
4521 new_child_bs
= NULL
;
4524 str
= qstring_get_str(qobject_to(QString
, value
));
4525 new_child_bs
= bdrv_lookup_bs(NULL
, str
, errp
);
4526 if (new_child_bs
== NULL
) {
4528 } else if (bdrv_recurse_has_child(new_child_bs
, bs
)) {
4529 error_setg(errp
, "Making '%s' a %s child of '%s' would create a "
4530 "cycle", str
, child_name
, bs
->node_name
);
4536 * The options QDict has been flattened, so 'backing' and 'file'
4537 * do not allow any other data type here.
4539 g_assert_not_reached();
4542 if (old_child_bs
== new_child_bs
) {
4547 if (bdrv_skip_implicit_filters(old_child_bs
) == new_child_bs
) {
4551 if (old_child_bs
->implicit
) {
4552 error_setg(errp
, "Cannot replace implicit %s child of %s",
4553 child_name
, bs
->node_name
);
4558 if (bs
->drv
->is_filter
&& !old_child_bs
) {
4560 * Filters always have a file or a backing child, so we are trying to
4561 * change wrong child
4563 error_setg(errp
, "'%s' is a %s filter node that does not support a "
4564 "%s child", bs
->node_name
, bs
->drv
->format_name
, child_name
);
4569 reopen_state
->old_backing_bs
= old_child_bs
;
4571 reopen_state
->old_file_bs
= old_child_bs
;
4574 return bdrv_set_file_or_backing_noperm(bs
, new_child_bs
, is_backing
,
4579 * Prepares a BlockDriverState for reopen. All changes are staged in the
4580 * 'opaque' field of the BDRVReopenState, which is used and allocated by
4581 * the block driver layer .bdrv_reopen_prepare()
4583 * bs is the BlockDriverState to reopen
4584 * flags are the new open flags
4585 * queue is the reopen queue
4587 * Returns 0 on success, non-zero on error. On error errp will be set
4590 * On failure, bdrv_reopen_abort() will be called to clean up any data.
4591 * It is the responsibility of the caller to then call the abort() or
4592 * commit() for any other BDS that have been left in a prepare() state
4595 static int bdrv_reopen_prepare(BDRVReopenState
*reopen_state
,
4596 BlockReopenQueue
*queue
,
4597 Transaction
*change_child_tran
, Error
**errp
)
4601 Error
*local_err
= NULL
;
4604 QDict
*orig_reopen_opts
;
4605 char *discard
= NULL
;
4607 bool drv_prepared
= false;
4609 assert(reopen_state
!= NULL
);
4610 assert(reopen_state
->bs
->drv
!= NULL
);
4611 GLOBAL_STATE_CODE();
4612 drv
= reopen_state
->bs
->drv
;
4614 /* This function and each driver's bdrv_reopen_prepare() remove
4615 * entries from reopen_state->options as they are processed, so
4616 * we need to make a copy of the original QDict. */
4617 orig_reopen_opts
= qdict_clone_shallow(reopen_state
->options
);
4619 /* Process generic block layer options */
4620 opts
= qemu_opts_create(&bdrv_runtime_opts
, NULL
, 0, &error_abort
);
4621 if (!qemu_opts_absorb_qdict(opts
, reopen_state
->options
, errp
)) {
4626 /* This was already called in bdrv_reopen_queue_child() so the flags
4627 * are up-to-date. This time we simply want to remove the options from
4628 * QemuOpts in order to indicate that they have been processed. */
4629 old_flags
= reopen_state
->flags
;
4630 update_flags_from_options(&reopen_state
->flags
, opts
);
4631 assert(old_flags
== reopen_state
->flags
);
4633 discard
= qemu_opt_get_del(opts
, BDRV_OPT_DISCARD
);
4634 if (discard
!= NULL
) {
4635 if (bdrv_parse_discard_flags(discard
, &reopen_state
->flags
) != 0) {
4636 error_setg(errp
, "Invalid discard option");
4642 reopen_state
->detect_zeroes
=
4643 bdrv_parse_detect_zeroes(opts
, reopen_state
->flags
, &local_err
);
4645 error_propagate(errp
, local_err
);
4650 /* All other options (including node-name and driver) must be unchanged.
4651 * Put them back into the QDict, so that they are checked at the end
4652 * of this function. */
4653 qemu_opts_to_qdict(opts
, reopen_state
->options
);
4655 /* If we are to stay read-only, do not allow permission change
4656 * to r/w. Attempting to set to r/w may fail if either BDRV_O_ALLOW_RDWR is
4657 * not set, or if the BDS still has copy_on_read enabled */
4658 read_only
= !(reopen_state
->flags
& BDRV_O_RDWR
);
4659 ret
= bdrv_can_set_read_only(reopen_state
->bs
, read_only
, true, &local_err
);
4661 error_propagate(errp
, local_err
);
4665 if (drv
->bdrv_reopen_prepare
) {
4667 * If a driver-specific option is missing, it means that we
4668 * should reset it to its default value.
4669 * But not all options allow that, so we need to check it first.
4671 ret
= bdrv_reset_options_allowed(reopen_state
->bs
,
4672 reopen_state
->options
, errp
);
4677 ret
= drv
->bdrv_reopen_prepare(reopen_state
, queue
, &local_err
);
4679 if (local_err
!= NULL
) {
4680 error_propagate(errp
, local_err
);
4682 bdrv_refresh_filename(reopen_state
->bs
);
4683 error_setg(errp
, "failed while preparing to reopen image '%s'",
4684 reopen_state
->bs
->filename
);
4689 /* It is currently mandatory to have a bdrv_reopen_prepare()
4690 * handler for each supported drv. */
4691 error_setg(errp
, "Block format '%s' used by node '%s' "
4692 "does not support reopening files", drv
->format_name
,
4693 bdrv_get_device_or_node_name(reopen_state
->bs
));
4698 drv_prepared
= true;
4701 * We must provide the 'backing' option if the BDS has a backing
4702 * file or if the image file has a backing file name as part of
4703 * its metadata. Otherwise the 'backing' option can be omitted.
4705 if (drv
->supports_backing
&& reopen_state
->backing_missing
&&
4706 (reopen_state
->bs
->backing
|| reopen_state
->bs
->backing_file
[0])) {
4707 error_setg(errp
, "backing is missing for '%s'",
4708 reopen_state
->bs
->node_name
);
4714 * Allow changing the 'backing' option. The new value can be
4715 * either a reference to an existing node (using its node name)
4716 * or NULL to simply detach the current backing file.
4718 ret
= bdrv_reopen_parse_file_or_backing(reopen_state
, true,
4719 change_child_tran
, errp
);
4723 qdict_del(reopen_state
->options
, "backing");
4725 /* Allow changing the 'file' option. In this case NULL is not allowed */
4726 ret
= bdrv_reopen_parse_file_or_backing(reopen_state
, false,
4727 change_child_tran
, errp
);
4731 qdict_del(reopen_state
->options
, "file");
4733 /* Options that are not handled are only okay if they are unchanged
4734 * compared to the old state. It is expected that some options are only
4735 * used for the initial open, but not reopen (e.g. filename) */
4736 if (qdict_size(reopen_state
->options
)) {
4737 const QDictEntry
*entry
= qdict_first(reopen_state
->options
);
4740 QObject
*new = entry
->value
;
4741 QObject
*old
= qdict_get(reopen_state
->bs
->options
, entry
->key
);
4743 /* Allow child references (child_name=node_name) as long as they
4744 * point to the current child (i.e. everything stays the same). */
4745 if (qobject_type(new) == QTYPE_QSTRING
) {
4747 QLIST_FOREACH(child
, &reopen_state
->bs
->children
, next
) {
4748 if (!strcmp(child
->name
, entry
->key
)) {
4754 if (!strcmp(child
->bs
->node_name
,
4755 qstring_get_str(qobject_to(QString
, new)))) {
4756 continue; /* Found child with this name, skip option */
4762 * TODO: When using -drive to specify blockdev options, all values
4763 * will be strings; however, when using -blockdev, blockdev-add or
4764 * filenames using the json:{} pseudo-protocol, they will be
4766 * In contrast, reopening options are (currently) always strings
4767 * (because you can only specify them through qemu-io; all other
4768 * callers do not specify any options).
4769 * Therefore, when using anything other than -drive to create a BDS,
4770 * this cannot detect non-string options as unchanged, because
4771 * qobject_is_equal() always returns false for objects of different
4772 * type. In the future, this should be remedied by correctly typing
4773 * all options. For now, this is not too big of an issue because
4774 * the user can simply omit options which cannot be changed anyway,
4775 * so they will stay unchanged.
4777 if (!qobject_is_equal(new, old
)) {
4778 error_setg(errp
, "Cannot change the option '%s'", entry
->key
);
4782 } while ((entry
= qdict_next(reopen_state
->options
, entry
)));
4787 /* Restore the original reopen_state->options QDict */
4788 qobject_unref(reopen_state
->options
);
4789 reopen_state
->options
= qobject_ref(orig_reopen_opts
);
4792 if (ret
< 0 && drv_prepared
) {
4793 /* drv->bdrv_reopen_prepare() has succeeded, so we need to
4794 * call drv->bdrv_reopen_abort() before signaling an error
4795 * (bdrv_reopen_multiple() will not call bdrv_reopen_abort()
4796 * when the respective bdrv_reopen_prepare() has failed) */
4797 if (drv
->bdrv_reopen_abort
) {
4798 drv
->bdrv_reopen_abort(reopen_state
);
4801 qemu_opts_del(opts
);
4802 qobject_unref(orig_reopen_opts
);
4808 * Takes the staged changes for the reopen from bdrv_reopen_prepare(), and
4809 * makes them final by swapping the staging BlockDriverState contents into
4810 * the active BlockDriverState contents.
4812 static void bdrv_reopen_commit(BDRVReopenState
*reopen_state
)
4815 BlockDriverState
*bs
;
4818 assert(reopen_state
!= NULL
);
4819 bs
= reopen_state
->bs
;
4821 assert(drv
!= NULL
);
4822 GLOBAL_STATE_CODE();
4824 /* If there are any driver level actions to take */
4825 if (drv
->bdrv_reopen_commit
) {
4826 drv
->bdrv_reopen_commit(reopen_state
);
4829 /* set BDS specific flags now */
4830 qobject_unref(bs
->explicit_options
);
4831 qobject_unref(bs
->options
);
4832 qobject_ref(reopen_state
->explicit_options
);
4833 qobject_ref(reopen_state
->options
);
4835 bs
->explicit_options
= reopen_state
->explicit_options
;
4836 bs
->options
= reopen_state
->options
;
4837 bs
->open_flags
= reopen_state
->flags
;
4838 bs
->detect_zeroes
= reopen_state
->detect_zeroes
;
4840 /* Remove child references from bs->options and bs->explicit_options.
4841 * Child options were already removed in bdrv_reopen_queue_child() */
4842 QLIST_FOREACH(child
, &bs
->children
, next
) {
4843 qdict_del(bs
->explicit_options
, child
->name
);
4844 qdict_del(bs
->options
, child
->name
);
4846 /* backing is probably removed, so it's not handled by previous loop */
4847 qdict_del(bs
->explicit_options
, "backing");
4848 qdict_del(bs
->options
, "backing");
4850 bdrv_refresh_limits(bs
, NULL
, NULL
);
4854 * Abort the reopen, and delete and free the staged changes in
4857 static void bdrv_reopen_abort(BDRVReopenState
*reopen_state
)
4861 assert(reopen_state
!= NULL
);
4862 drv
= reopen_state
->bs
->drv
;
4863 assert(drv
!= NULL
);
4864 GLOBAL_STATE_CODE();
4866 if (drv
->bdrv_reopen_abort
) {
4867 drv
->bdrv_reopen_abort(reopen_state
);
4872 static void bdrv_close(BlockDriverState
*bs
)
4874 BdrvAioNotifier
*ban
, *ban_next
;
4875 BdrvChild
*child
, *next
;
4877 GLOBAL_STATE_CODE();
4878 assert(!bs
->refcnt
);
4880 bdrv_drained_begin(bs
); /* complete I/O */
4882 bdrv_drain(bs
); /* in case flush left pending I/O */
4885 if (bs
->drv
->bdrv_close
) {
4886 /* Must unfreeze all children, so bdrv_unref_child() works */
4887 bs
->drv
->bdrv_close(bs
);
4892 QLIST_FOREACH_SAFE(child
, &bs
->children
, next
, next
) {
4893 bdrv_unref_child(bs
, child
);
4896 assert(!bs
->backing
);
4900 qatomic_set(&bs
->copy_on_read
, 0);
4901 bs
->backing_file
[0] = '\0';
4902 bs
->backing_format
[0] = '\0';
4903 bs
->total_sectors
= 0;
4904 bs
->encrypted
= false;
4906 qobject_unref(bs
->options
);
4907 qobject_unref(bs
->explicit_options
);
4909 bs
->explicit_options
= NULL
;
4910 qobject_unref(bs
->full_open_options
);
4911 bs
->full_open_options
= NULL
;
4912 g_free(bs
->block_status_cache
);
4913 bs
->block_status_cache
= NULL
;
4915 bdrv_release_named_dirty_bitmaps(bs
);
4916 assert(QLIST_EMPTY(&bs
->dirty_bitmaps
));
4918 QLIST_FOREACH_SAFE(ban
, &bs
->aio_notifiers
, list
, ban_next
) {
4921 QLIST_INIT(&bs
->aio_notifiers
);
4922 bdrv_drained_end(bs
);
4925 * If we're still inside some bdrv_drain_all_begin()/end() sections, end
4926 * them now since this BDS won't exist anymore when bdrv_drain_all_end()
4929 if (bs
->quiesce_counter
) {
4930 bdrv_drain_all_end_quiesce(bs
);
4934 void bdrv_close_all(void)
4936 GLOBAL_STATE_CODE();
4937 assert(job_next(NULL
) == NULL
);
4939 /* Drop references from requests still in flight, such as canceled block
4940 * jobs whose AIO context has not been polled yet */
4943 blk_remove_all_bs();
4944 blockdev_close_all_bdrv_states();
4946 assert(QTAILQ_EMPTY(&all_bdrv_states
));
4949 static bool should_update_child(BdrvChild
*c
, BlockDriverState
*to
)
4955 if (c
->klass
->stay_at_node
) {
4959 /* If the child @c belongs to the BDS @to, replacing the current
4960 * c->bs by @to would mean to create a loop.
4962 * Such a case occurs when appending a BDS to a backing chain.
4963 * For instance, imagine the following chain:
4965 * guest device -> node A -> further backing chain...
4967 * Now we create a new BDS B which we want to put on top of this
4968 * chain, so we first attach A as its backing node:
4973 * guest device -> node A -> further backing chain...
4975 * Finally we want to replace A by B. When doing that, we want to
4976 * replace all pointers to A by pointers to B -- except for the
4977 * pointer from B because (1) that would create a loop, and (2)
4978 * that pointer should simply stay intact:
4980 * guest device -> node B
4983 * node A -> further backing chain...
4985 * In general, when replacing a node A (c->bs) by a node B (@to),
4986 * if A is a child of B, that means we cannot replace A by B there
4987 * because that would create a loop. Silently detaching A from B
4988 * is also not really an option. So overall just leaving A in
4989 * place there is the most sensible choice.
4991 * We would also create a loop in any cases where @c is only
4992 * indirectly referenced by @to. Prevent this by returning false
4993 * if @c is found (by breadth-first search) anywhere in the whole
4998 found
= g_hash_table_new(NULL
, NULL
);
4999 g_hash_table_add(found
, to
);
5000 queue
= g_queue_new();
5001 g_queue_push_tail(queue
, to
);
5003 while (!g_queue_is_empty(queue
)) {
5004 BlockDriverState
*v
= g_queue_pop_head(queue
);
5007 QLIST_FOREACH(c2
, &v
->children
, next
) {
5013 if (g_hash_table_contains(found
, c2
->bs
)) {
5017 g_queue_push_tail(queue
, c2
->bs
);
5018 g_hash_table_add(found
, c2
->bs
);
5022 g_queue_free(queue
);
5023 g_hash_table_destroy(found
);
5028 static void bdrv_remove_child_commit(void *opaque
)
5030 GLOBAL_STATE_CODE();
5031 bdrv_child_free(opaque
);
5034 static TransactionActionDrv bdrv_remove_child_drv
= {
5035 .commit
= bdrv_remove_child_commit
,
5038 /* Function doesn't update permissions, caller is responsible for this. */
5039 static void bdrv_remove_child(BdrvChild
*child
, Transaction
*tran
)
5046 bdrv_replace_child_tran(child
, NULL
, tran
);
5049 tran_add(tran
, &bdrv_remove_child_drv
, child
);
5053 * A function to remove backing-chain child of @bs if exists: cow child for
5054 * format nodes (always .backing) and filter child for filters (may be .file or
5057 static void bdrv_remove_filter_or_cow_child(BlockDriverState
*bs
,
5060 bdrv_remove_child(bdrv_filter_or_cow_child(bs
), tran
);
5063 static int bdrv_replace_node_noperm(BlockDriverState
*from
,
5064 BlockDriverState
*to
,
5065 bool auto_skip
, Transaction
*tran
,
5068 BdrvChild
*c
, *next
;
5070 GLOBAL_STATE_CODE();
5072 QLIST_FOREACH_SAFE(c
, &from
->parents
, next_parent
, next
) {
5073 assert(c
->bs
== from
);
5074 if (!should_update_child(c
, to
)) {
5078 error_setg(errp
, "Should not change '%s' link to '%s'",
5079 c
->name
, from
->node_name
);
5083 error_setg(errp
, "Cannot change '%s' link to '%s'",
5084 c
->name
, from
->node_name
);
5087 bdrv_replace_child_tran(c
, to
, tran
);
5094 * With auto_skip=true bdrv_replace_node_common skips updating from parents
5095 * if it creates a parent-child relation loop or if parent is block-job.
5097 * With auto_skip=false the error is returned if from has a parent which should
5100 * With @detach_subchain=true @to must be in a backing chain of @from. In this
5101 * case backing link of the cow-parent of @to is removed.
5103 static int bdrv_replace_node_common(BlockDriverState
*from
,
5104 BlockDriverState
*to
,
5105 bool auto_skip
, bool detach_subchain
,
5108 Transaction
*tran
= tran_new();
5109 g_autoptr(GHashTable
) found
= NULL
;
5110 g_autoptr(GSList
) refresh_list
= NULL
;
5111 BlockDriverState
*to_cow_parent
= NULL
;
5114 GLOBAL_STATE_CODE();
5116 if (detach_subchain
) {
5117 assert(bdrv_chain_contains(from
, to
));
5119 for (to_cow_parent
= from
;
5120 bdrv_filter_or_cow_bs(to_cow_parent
) != to
;
5121 to_cow_parent
= bdrv_filter_or_cow_bs(to_cow_parent
))
5127 /* Make sure that @from doesn't go away until we have successfully attached
5128 * all of its parents to @to. */
5131 assert(qemu_get_current_aio_context() == qemu_get_aio_context());
5132 assert(bdrv_get_aio_context(from
) == bdrv_get_aio_context(to
));
5133 bdrv_drained_begin(from
);
5136 * Do the replacement without permission update.
5137 * Replacement may influence the permissions, we should calculate new
5138 * permissions based on new graph. If we fail, we'll roll-back the
5141 ret
= bdrv_replace_node_noperm(from
, to
, auto_skip
, tran
, errp
);
5146 if (detach_subchain
) {
5147 bdrv_remove_filter_or_cow_child(to_cow_parent
, tran
);
5150 found
= g_hash_table_new(NULL
, NULL
);
5152 refresh_list
= bdrv_topological_dfs(refresh_list
, found
, to
);
5153 refresh_list
= bdrv_topological_dfs(refresh_list
, found
, from
);
5155 ret
= bdrv_list_refresh_perms(refresh_list
, NULL
, tran
, errp
);
5163 tran_finalize(tran
, ret
);
5165 bdrv_drained_end(from
);
5171 int bdrv_replace_node(BlockDriverState
*from
, BlockDriverState
*to
,
5174 GLOBAL_STATE_CODE();
5176 return bdrv_replace_node_common(from
, to
, true, false, errp
);
5179 int bdrv_drop_filter(BlockDriverState
*bs
, Error
**errp
)
5181 GLOBAL_STATE_CODE();
5183 return bdrv_replace_node_common(bs
, bdrv_filter_or_cow_bs(bs
), true, true,
5188 * Add new bs contents at the top of an image chain while the chain is
5189 * live, while keeping required fields on the top layer.
5191 * This will modify the BlockDriverState fields, and swap contents
5192 * between bs_new and bs_top. Both bs_new and bs_top are modified.
5194 * bs_new must not be attached to a BlockBackend and must not have backing
5197 * This function does not create any image files.
5199 int bdrv_append(BlockDriverState
*bs_new
, BlockDriverState
*bs_top
,
5204 Transaction
*tran
= tran_new();
5206 GLOBAL_STATE_CODE();
5208 assert(!bs_new
->backing
);
5210 child
= bdrv_attach_child_noperm(bs_new
, bs_top
, "backing",
5211 &child_of_bds
, bdrv_backing_role(bs_new
),
5218 ret
= bdrv_replace_node_noperm(bs_top
, bs_new
, true, tran
, errp
);
5223 ret
= bdrv_refresh_perms(bs_new
, errp
);
5225 tran_finalize(tran
, ret
);
5227 bdrv_refresh_limits(bs_top
, NULL
, NULL
);
5232 /* Not for empty child */
5233 int bdrv_replace_child_bs(BdrvChild
*child
, BlockDriverState
*new_bs
,
5237 Transaction
*tran
= tran_new();
5238 g_autoptr(GHashTable
) found
= NULL
;
5239 g_autoptr(GSList
) refresh_list
= NULL
;
5240 BlockDriverState
*old_bs
= child
->bs
;
5242 GLOBAL_STATE_CODE();
5245 bdrv_drained_begin(old_bs
);
5246 bdrv_drained_begin(new_bs
);
5248 bdrv_replace_child_tran(child
, new_bs
, tran
);
5250 found
= g_hash_table_new(NULL
, NULL
);
5251 refresh_list
= bdrv_topological_dfs(refresh_list
, found
, old_bs
);
5252 refresh_list
= bdrv_topological_dfs(refresh_list
, found
, new_bs
);
5254 ret
= bdrv_list_refresh_perms(refresh_list
, NULL
, tran
, errp
);
5256 tran_finalize(tran
, ret
);
5258 bdrv_drained_end(old_bs
);
5259 bdrv_drained_end(new_bs
);
5265 static void bdrv_delete(BlockDriverState
*bs
)
5267 assert(bdrv_op_blocker_is_empty(bs
));
5268 assert(!bs
->refcnt
);
5269 GLOBAL_STATE_CODE();
5271 /* remove from list, if necessary */
5272 if (bs
->node_name
[0] != '\0') {
5273 QTAILQ_REMOVE(&graph_bdrv_states
, bs
, node_list
);
5275 QTAILQ_REMOVE(&all_bdrv_states
, bs
, bs_list
);
5284 * Replace @bs by newly created block node.
5286 * @options is a QDict of options to pass to the block drivers, or NULL for an
5287 * empty set of options. The reference to the QDict belongs to the block layer
5288 * after the call (even on failure), so if the caller intends to reuse the
5289 * dictionary, it needs to use qobject_ref() before calling bdrv_open.
5291 BlockDriverState
*bdrv_insert_node(BlockDriverState
*bs
, QDict
*options
,
5292 int flags
, Error
**errp
)
5296 BlockDriverState
*new_node_bs
= NULL
;
5297 const char *drvname
, *node_name
;
5300 drvname
= qdict_get_try_str(options
, "driver");
5302 error_setg(errp
, "driver is not specified");
5306 drv
= bdrv_find_format(drvname
);
5308 error_setg(errp
, "Unknown driver: '%s'", drvname
);
5312 node_name
= qdict_get_try_str(options
, "node-name");
5314 GLOBAL_STATE_CODE();
5316 new_node_bs
= bdrv_new_open_driver_opts(drv
, node_name
, options
, flags
,
5318 options
= NULL
; /* bdrv_new_open_driver() eats options */
5320 error_prepend(errp
, "Could not create node: ");
5324 bdrv_drained_begin(bs
);
5325 ret
= bdrv_replace_node(bs
, new_node_bs
, errp
);
5326 bdrv_drained_end(bs
);
5329 error_prepend(errp
, "Could not replace node: ");
5336 qobject_unref(options
);
5337 bdrv_unref(new_node_bs
);
5342 * Run consistency checks on an image
5344 * Returns 0 if the check could be completed (it doesn't mean that the image is
5345 * free of errors) or -errno when an internal error occurred. The results of the
5346 * check are stored in res.
5348 int coroutine_fn
bdrv_co_check(BlockDriverState
*bs
,
5349 BdrvCheckResult
*res
, BdrvCheckMode fix
)
5352 if (bs
->drv
== NULL
) {
5355 if (bs
->drv
->bdrv_co_check
== NULL
) {
5359 memset(res
, 0, sizeof(*res
));
5360 return bs
->drv
->bdrv_co_check(bs
, res
, fix
);
5366 * -EINVAL - backing format specified, but no file
5367 * -ENOSPC - can't update the backing file because no space is left in the
5369 * -ENOTSUP - format driver doesn't support changing the backing file
5371 int bdrv_change_backing_file(BlockDriverState
*bs
, const char *backing_file
,
5372 const char *backing_fmt
, bool require
)
5374 BlockDriver
*drv
= bs
->drv
;
5377 GLOBAL_STATE_CODE();
5383 /* Backing file format doesn't make sense without a backing file */
5384 if (backing_fmt
&& !backing_file
) {
5388 if (require
&& backing_file
&& !backing_fmt
) {
5392 if (drv
->bdrv_change_backing_file
!= NULL
) {
5393 ret
= drv
->bdrv_change_backing_file(bs
, backing_file
, backing_fmt
);
5399 pstrcpy(bs
->backing_file
, sizeof(bs
->backing_file
), backing_file
?: "");
5400 pstrcpy(bs
->backing_format
, sizeof(bs
->backing_format
), backing_fmt
?: "");
5401 pstrcpy(bs
->auto_backing_file
, sizeof(bs
->auto_backing_file
),
5402 backing_file
?: "");
5408 * Finds the first non-filter node above bs in the chain between
5409 * active and bs. The returned node is either an immediate parent of
5410 * bs, or there are only filter nodes between the two.
5412 * Returns NULL if bs is not found in active's image chain,
5413 * or if active == bs.
5415 * Returns the bottommost base image if bs == NULL.
5417 BlockDriverState
*bdrv_find_overlay(BlockDriverState
*active
,
5418 BlockDriverState
*bs
)
5421 GLOBAL_STATE_CODE();
5423 bs
= bdrv_skip_filters(bs
);
5424 active
= bdrv_skip_filters(active
);
5427 BlockDriverState
*next
= bdrv_backing_chain_next(active
);
5437 /* Given a BDS, searches for the base layer. */
5438 BlockDriverState
*bdrv_find_base(BlockDriverState
*bs
)
5440 GLOBAL_STATE_CODE();
5442 return bdrv_find_overlay(bs
, NULL
);
5446 * Return true if at least one of the COW (backing) and filter links
5447 * between @bs and @base is frozen. @errp is set if that's the case.
5448 * @base must be reachable from @bs, or NULL.
5450 bool bdrv_is_backing_chain_frozen(BlockDriverState
*bs
, BlockDriverState
*base
,
5453 BlockDriverState
*i
;
5456 GLOBAL_STATE_CODE();
5458 for (i
= bs
; i
!= base
; i
= child_bs(child
)) {
5459 child
= bdrv_filter_or_cow_child(i
);
5461 if (child
&& child
->frozen
) {
5462 error_setg(errp
, "Cannot change '%s' link from '%s' to '%s'",
5463 child
->name
, i
->node_name
, child
->bs
->node_name
);
5472 * Freeze all COW (backing) and filter links between @bs and @base.
5473 * If any of the links is already frozen the operation is aborted and
5474 * none of the links are modified.
5475 * @base must be reachable from @bs, or NULL.
5476 * Returns 0 on success. On failure returns < 0 and sets @errp.
5478 int bdrv_freeze_backing_chain(BlockDriverState
*bs
, BlockDriverState
*base
,
5481 BlockDriverState
*i
;
5484 GLOBAL_STATE_CODE();
5486 if (bdrv_is_backing_chain_frozen(bs
, base
, errp
)) {
5490 for (i
= bs
; i
!= base
; i
= child_bs(child
)) {
5491 child
= bdrv_filter_or_cow_child(i
);
5492 if (child
&& child
->bs
->never_freeze
) {
5493 error_setg(errp
, "Cannot freeze '%s' link to '%s'",
5494 child
->name
, child
->bs
->node_name
);
5499 for (i
= bs
; i
!= base
; i
= child_bs(child
)) {
5500 child
= bdrv_filter_or_cow_child(i
);
5502 child
->frozen
= true;
5510 * Unfreeze all COW (backing) and filter links between @bs and @base.
5511 * The caller must ensure that all links are frozen before using this
5513 * @base must be reachable from @bs, or NULL.
5515 void bdrv_unfreeze_backing_chain(BlockDriverState
*bs
, BlockDriverState
*base
)
5517 BlockDriverState
*i
;
5520 GLOBAL_STATE_CODE();
5522 for (i
= bs
; i
!= base
; i
= child_bs(child
)) {
5523 child
= bdrv_filter_or_cow_child(i
);
5525 assert(child
->frozen
);
5526 child
->frozen
= false;
5532 * Drops images above 'base' up to and including 'top', and sets the image
5533 * above 'top' to have base as its backing file.
5535 * Requires that the overlay to 'top' is opened r/w, so that the backing file
5536 * information in 'bs' can be properly updated.
5538 * E.g., this will convert the following chain:
5539 * bottom <- base <- intermediate <- top <- active
5543 * bottom <- base <- active
5545 * It is allowed for bottom==base, in which case it converts:
5547 * base <- intermediate <- top <- active
5553 * If backing_file_str is non-NULL, it will be used when modifying top's
5554 * overlay image metadata.
5557 * if active == top, that is considered an error
5560 int bdrv_drop_intermediate(BlockDriverState
*top
, BlockDriverState
*base
,
5561 const char *backing_file_str
)
5563 BlockDriverState
*explicit_top
= top
;
5564 bool update_inherits_from
;
5566 Error
*local_err
= NULL
;
5568 g_autoptr(GSList
) updated_children
= NULL
;
5571 GLOBAL_STATE_CODE();
5574 bdrv_subtree_drained_begin(top
);
5576 if (!top
->drv
|| !base
->drv
) {
5580 /* Make sure that base is in the backing chain of top */
5581 if (!bdrv_chain_contains(top
, base
)) {
5585 /* If 'base' recursively inherits from 'top' then we should set
5586 * base->inherits_from to top->inherits_from after 'top' and all
5587 * other intermediate nodes have been dropped.
5588 * If 'top' is an implicit node (e.g. "commit_top") we should skip
5589 * it because no one inherits from it. We use explicit_top for that. */
5590 explicit_top
= bdrv_skip_implicit_filters(explicit_top
);
5591 update_inherits_from
= bdrv_inherits_from_recursive(base
, explicit_top
);
5593 /* success - we can delete the intermediate states, and link top->base */
5594 if (!backing_file_str
) {
5595 bdrv_refresh_filename(base
);
5596 backing_file_str
= base
->filename
;
5599 QLIST_FOREACH(c
, &top
->parents
, next_parent
) {
5600 updated_children
= g_slist_prepend(updated_children
, c
);
5604 * It seems correct to pass detach_subchain=true here, but it triggers
5605 * one more yet not fixed bug, when due to nested aio_poll loop we switch to
5606 * another drained section, which modify the graph (for example, removing
5607 * the child, which we keep in updated_children list). So, it's a TODO.
5609 * Note, bug triggered if pass detach_subchain=true here and run
5610 * test-bdrv-drain. test_drop_intermediate_poll() test-case will crash.
5613 bdrv_replace_node_common(top
, base
, false, false, &local_err
);
5615 error_report_err(local_err
);
5619 for (p
= updated_children
; p
; p
= p
->next
) {
5622 if (c
->klass
->update_filename
) {
5623 ret
= c
->klass
->update_filename(c
, base
, backing_file_str
,
5627 * TODO: Actually, we want to rollback all previous iterations
5628 * of this loop, and (which is almost impossible) previous
5629 * bdrv_replace_node()...
5631 * Note, that c->klass->update_filename may lead to permission
5632 * update, so it's a bad idea to call it inside permission
5633 * update transaction of bdrv_replace_node.
5635 error_report_err(local_err
);
5641 if (update_inherits_from
) {
5642 base
->inherits_from
= explicit_top
->inherits_from
;
5647 bdrv_subtree_drained_end(top
);
5653 * Implementation of BlockDriver.bdrv_get_allocated_file_size() that
5654 * sums the size of all data-bearing children. (This excludes backing
5657 static int64_t bdrv_sum_allocated_file_size(BlockDriverState
*bs
)
5660 int64_t child_size
, sum
= 0;
5662 QLIST_FOREACH(child
, &bs
->children
, next
) {
5663 if (child
->role
& (BDRV_CHILD_DATA
| BDRV_CHILD_METADATA
|
5664 BDRV_CHILD_FILTERED
))
5666 child_size
= bdrv_get_allocated_file_size(child
->bs
);
5667 if (child_size
< 0) {
5678 * Length of a allocated file in bytes. Sparse files are counted by actual
5679 * allocated space. Return < 0 if error or unknown.
5681 int64_t bdrv_get_allocated_file_size(BlockDriverState
*bs
)
5683 BlockDriver
*drv
= bs
->drv
;
5689 if (drv
->bdrv_get_allocated_file_size
) {
5690 return drv
->bdrv_get_allocated_file_size(bs
);
5693 if (drv
->bdrv_file_open
) {
5695 * Protocol drivers default to -ENOTSUP (most of their data is
5696 * not stored in any of their children (if they even have any),
5697 * so there is no generic way to figure it out).
5700 } else if (drv
->is_filter
) {
5701 /* Filter drivers default to the size of their filtered child */
5702 return bdrv_get_allocated_file_size(bdrv_filter_bs(bs
));
5704 /* Other drivers default to summing their children's sizes */
5705 return bdrv_sum_allocated_file_size(bs
);
5711 * @drv: Format driver
5712 * @opts: Creation options for new image
5713 * @in_bs: Existing image containing data for new image (may be NULL)
5714 * @errp: Error object
5715 * Returns: A #BlockMeasureInfo (free using qapi_free_BlockMeasureInfo())
5718 * Calculate file size required to create a new image.
5720 * If @in_bs is given then space for allocated clusters and zero clusters
5721 * from that image are included in the calculation. If @opts contains a
5722 * backing file that is shared by @in_bs then backing clusters may be omitted
5723 * from the calculation.
5725 * If @in_bs is NULL then the calculation includes no allocated clusters
5726 * unless a preallocation option is given in @opts.
5728 * Note that @in_bs may use a different BlockDriver from @drv.
5730 * If an error occurs the @errp pointer is set.
5732 BlockMeasureInfo
*bdrv_measure(BlockDriver
*drv
, QemuOpts
*opts
,
5733 BlockDriverState
*in_bs
, Error
**errp
)
5736 if (!drv
->bdrv_measure
) {
5737 error_setg(errp
, "Block driver '%s' does not support size measurement",
5742 return drv
->bdrv_measure(opts
, in_bs
, errp
);
5746 * Return number of sectors on success, -errno on error.
5748 int64_t bdrv_nb_sectors(BlockDriverState
*bs
)
5750 BlockDriver
*drv
= bs
->drv
;
5756 if (drv
->has_variable_length
) {
5757 int ret
= refresh_total_sectors(bs
, bs
->total_sectors
);
5762 return bs
->total_sectors
;
5766 * Return length in bytes on success, -errno on error.
5767 * The length is always a multiple of BDRV_SECTOR_SIZE.
5769 int64_t bdrv_getlength(BlockDriverState
*bs
)
5771 int64_t ret
= bdrv_nb_sectors(bs
);
5777 if (ret
> INT64_MAX
/ BDRV_SECTOR_SIZE
) {
5780 return ret
* BDRV_SECTOR_SIZE
;
5783 /* return 0 as number of sectors if no device present or error */
5784 void bdrv_get_geometry(BlockDriverState
*bs
, uint64_t *nb_sectors_ptr
)
5786 int64_t nb_sectors
= bdrv_nb_sectors(bs
);
5789 *nb_sectors_ptr
= nb_sectors
< 0 ? 0 : nb_sectors
;
5792 bool bdrv_is_sg(BlockDriverState
*bs
)
5799 * Return whether the given node supports compressed writes.
5801 bool bdrv_supports_compressed_writes(BlockDriverState
*bs
)
5803 BlockDriverState
*filtered
;
5806 if (!bs
->drv
|| !block_driver_can_compress(bs
->drv
)) {
5810 filtered
= bdrv_filter_bs(bs
);
5813 * Filters can only forward compressed writes, so we have to
5816 return bdrv_supports_compressed_writes(filtered
);
5822 const char *bdrv_get_format_name(BlockDriverState
*bs
)
5825 return bs
->drv
? bs
->drv
->format_name
: NULL
;
5828 static int qsort_strcmp(const void *a
, const void *b
)
5830 return strcmp(*(char *const *)a
, *(char *const *)b
);
5833 void bdrv_iterate_format(void (*it
)(void *opaque
, const char *name
),
5834 void *opaque
, bool read_only
)
5839 const char **formats
= NULL
;
5841 GLOBAL_STATE_CODE();
5843 QLIST_FOREACH(drv
, &bdrv_drivers
, list
) {
5844 if (drv
->format_name
) {
5848 if (use_bdrv_whitelist
&& !bdrv_is_whitelisted(drv
, read_only
)) {
5852 while (formats
&& i
&& !found
) {
5853 found
= !strcmp(formats
[--i
], drv
->format_name
);
5857 formats
= g_renew(const char *, formats
, count
+ 1);
5858 formats
[count
++] = drv
->format_name
;
5863 for (i
= 0; i
< (int)ARRAY_SIZE(block_driver_modules
); i
++) {
5864 const char *format_name
= block_driver_modules
[i
].format_name
;
5870 if (use_bdrv_whitelist
&&
5871 !bdrv_format_is_whitelisted(format_name
, read_only
)) {
5875 while (formats
&& j
&& !found
) {
5876 found
= !strcmp(formats
[--j
], format_name
);
5880 formats
= g_renew(const char *, formats
, count
+ 1);
5881 formats
[count
++] = format_name
;
5886 qsort(formats
, count
, sizeof(formats
[0]), qsort_strcmp
);
5888 for (i
= 0; i
< count
; i
++) {
5889 it(opaque
, formats
[i
]);
5895 /* This function is to find a node in the bs graph */
5896 BlockDriverState
*bdrv_find_node(const char *node_name
)
5898 BlockDriverState
*bs
;
5901 GLOBAL_STATE_CODE();
5903 QTAILQ_FOREACH(bs
, &graph_bdrv_states
, node_list
) {
5904 if (!strcmp(node_name
, bs
->node_name
)) {
5911 /* Put this QMP function here so it can access the static graph_bdrv_states. */
5912 BlockDeviceInfoList
*bdrv_named_nodes_list(bool flat
,
5915 BlockDeviceInfoList
*list
;
5916 BlockDriverState
*bs
;
5918 GLOBAL_STATE_CODE();
5921 QTAILQ_FOREACH(bs
, &graph_bdrv_states
, node_list
) {
5922 BlockDeviceInfo
*info
= bdrv_block_device_info(NULL
, bs
, flat
, errp
);
5924 qapi_free_BlockDeviceInfoList(list
);
5927 QAPI_LIST_PREPEND(list
, info
);
5933 typedef struct XDbgBlockGraphConstructor
{
5934 XDbgBlockGraph
*graph
;
5935 GHashTable
*graph_nodes
;
5936 } XDbgBlockGraphConstructor
;
5938 static XDbgBlockGraphConstructor
*xdbg_graph_new(void)
5940 XDbgBlockGraphConstructor
*gr
= g_new(XDbgBlockGraphConstructor
, 1);
5942 gr
->graph
= g_new0(XDbgBlockGraph
, 1);
5943 gr
->graph_nodes
= g_hash_table_new(NULL
, NULL
);
5948 static XDbgBlockGraph
*xdbg_graph_finalize(XDbgBlockGraphConstructor
*gr
)
5950 XDbgBlockGraph
*graph
= gr
->graph
;
5952 g_hash_table_destroy(gr
->graph_nodes
);
5958 static uintptr_t xdbg_graph_node_num(XDbgBlockGraphConstructor
*gr
, void *node
)
5960 uintptr_t ret
= (uintptr_t)g_hash_table_lookup(gr
->graph_nodes
, node
);
5967 * Start counting from 1, not 0, because 0 interferes with not-found (NULL)
5968 * answer of g_hash_table_lookup.
5970 ret
= g_hash_table_size(gr
->graph_nodes
) + 1;
5971 g_hash_table_insert(gr
->graph_nodes
, node
, (void *)ret
);
5976 static void xdbg_graph_add_node(XDbgBlockGraphConstructor
*gr
, void *node
,
5977 XDbgBlockGraphNodeType type
, const char *name
)
5979 XDbgBlockGraphNode
*n
;
5981 n
= g_new0(XDbgBlockGraphNode
, 1);
5983 n
->id
= xdbg_graph_node_num(gr
, node
);
5985 n
->name
= g_strdup(name
);
5987 QAPI_LIST_PREPEND(gr
->graph
->nodes
, n
);
5990 static void xdbg_graph_add_edge(XDbgBlockGraphConstructor
*gr
, void *parent
,
5991 const BdrvChild
*child
)
5993 BlockPermission qapi_perm
;
5994 XDbgBlockGraphEdge
*edge
;
5995 GLOBAL_STATE_CODE();
5997 edge
= g_new0(XDbgBlockGraphEdge
, 1);
5999 edge
->parent
= xdbg_graph_node_num(gr
, parent
);
6000 edge
->child
= xdbg_graph_node_num(gr
, child
->bs
);
6001 edge
->name
= g_strdup(child
->name
);
6003 for (qapi_perm
= 0; qapi_perm
< BLOCK_PERMISSION__MAX
; qapi_perm
++) {
6004 uint64_t flag
= bdrv_qapi_perm_to_blk_perm(qapi_perm
);
6006 if (flag
& child
->perm
) {
6007 QAPI_LIST_PREPEND(edge
->perm
, qapi_perm
);
6009 if (flag
& child
->shared_perm
) {
6010 QAPI_LIST_PREPEND(edge
->shared_perm
, qapi_perm
);
6014 QAPI_LIST_PREPEND(gr
->graph
->edges
, edge
);
6018 XDbgBlockGraph
*bdrv_get_xdbg_block_graph(Error
**errp
)
6022 BlockDriverState
*bs
;
6024 XDbgBlockGraphConstructor
*gr
= xdbg_graph_new();
6026 GLOBAL_STATE_CODE();
6028 for (blk
= blk_all_next(NULL
); blk
; blk
= blk_all_next(blk
)) {
6029 char *allocated_name
= NULL
;
6030 const char *name
= blk_name(blk
);
6033 name
= allocated_name
= blk_get_attached_dev_id(blk
);
6035 xdbg_graph_add_node(gr
, blk
, X_DBG_BLOCK_GRAPH_NODE_TYPE_BLOCK_BACKEND
,
6037 g_free(allocated_name
);
6038 if (blk_root(blk
)) {
6039 xdbg_graph_add_edge(gr
, blk
, blk_root(blk
));
6043 WITH_JOB_LOCK_GUARD() {
6044 for (job
= block_job_next_locked(NULL
); job
;
6045 job
= block_job_next_locked(job
)) {
6048 xdbg_graph_add_node(gr
, job
, X_DBG_BLOCK_GRAPH_NODE_TYPE_BLOCK_JOB
,
6050 for (el
= job
->nodes
; el
; el
= el
->next
) {
6051 xdbg_graph_add_edge(gr
, job
, (BdrvChild
*)el
->data
);
6056 QTAILQ_FOREACH(bs
, &graph_bdrv_states
, node_list
) {
6057 xdbg_graph_add_node(gr
, bs
, X_DBG_BLOCK_GRAPH_NODE_TYPE_BLOCK_DRIVER
,
6059 QLIST_FOREACH(child
, &bs
->children
, next
) {
6060 xdbg_graph_add_edge(gr
, bs
, child
);
6064 return xdbg_graph_finalize(gr
);
6067 BlockDriverState
*bdrv_lookup_bs(const char *device
,
6068 const char *node_name
,
6072 BlockDriverState
*bs
;
6074 GLOBAL_STATE_CODE();
6077 blk
= blk_by_name(device
);
6082 error_setg(errp
, "Device '%s' has no medium", device
);
6090 bs
= bdrv_find_node(node_name
);
6097 error_setg(errp
, "Cannot find device=\'%s\' nor node-name=\'%s\'",
6098 device
? device
: "",
6099 node_name
? node_name
: "");
6103 /* If 'base' is in the same chain as 'top', return true. Otherwise,
6104 * return false. If either argument is NULL, return false. */
6105 bool bdrv_chain_contains(BlockDriverState
*top
, BlockDriverState
*base
)
6108 GLOBAL_STATE_CODE();
6110 while (top
&& top
!= base
) {
6111 top
= bdrv_filter_or_cow_bs(top
);
6117 BlockDriverState
*bdrv_next_node(BlockDriverState
*bs
)
6119 GLOBAL_STATE_CODE();
6121 return QTAILQ_FIRST(&graph_bdrv_states
);
6123 return QTAILQ_NEXT(bs
, node_list
);
6126 BlockDriverState
*bdrv_next_all_states(BlockDriverState
*bs
)
6128 GLOBAL_STATE_CODE();
6130 return QTAILQ_FIRST(&all_bdrv_states
);
6132 return QTAILQ_NEXT(bs
, bs_list
);
6135 const char *bdrv_get_node_name(const BlockDriverState
*bs
)
6138 return bs
->node_name
;
6141 const char *bdrv_get_parent_name(const BlockDriverState
*bs
)
6147 /* If multiple parents have a name, just pick the first one. */
6148 QLIST_FOREACH(c
, &bs
->parents
, next_parent
) {
6149 if (c
->klass
->get_name
) {
6150 name
= c
->klass
->get_name(c
);
6151 if (name
&& *name
) {
6160 /* TODO check what callers really want: bs->node_name or blk_name() */
6161 const char *bdrv_get_device_name(const BlockDriverState
*bs
)
6164 return bdrv_get_parent_name(bs
) ?: "";
6167 /* This can be used to identify nodes that might not have a device
6168 * name associated. Since node and device names live in the same
6169 * namespace, the result is unambiguous. The exception is if both are
6170 * absent, then this returns an empty (non-null) string. */
6171 const char *bdrv_get_device_or_node_name(const BlockDriverState
*bs
)
6174 return bdrv_get_parent_name(bs
) ?: bs
->node_name
;
6177 int bdrv_get_flags(BlockDriverState
*bs
)
6180 return bs
->open_flags
;
6183 int bdrv_has_zero_init_1(BlockDriverState
*bs
)
6185 GLOBAL_STATE_CODE();
6189 int bdrv_has_zero_init(BlockDriverState
*bs
)
6191 BlockDriverState
*filtered
;
6192 GLOBAL_STATE_CODE();
6198 /* If BS is a copy on write image, it is initialized to
6199 the contents of the base image, which may not be zeroes. */
6200 if (bdrv_cow_child(bs
)) {
6203 if (bs
->drv
->bdrv_has_zero_init
) {
6204 return bs
->drv
->bdrv_has_zero_init(bs
);
6207 filtered
= bdrv_filter_bs(bs
);
6209 return bdrv_has_zero_init(filtered
);
6216 bool bdrv_can_write_zeroes_with_unmap(BlockDriverState
*bs
)
6219 if (!(bs
->open_flags
& BDRV_O_UNMAP
)) {
6223 return bs
->supported_zero_flags
& BDRV_REQ_MAY_UNMAP
;
6226 void bdrv_get_backing_filename(BlockDriverState
*bs
,
6227 char *filename
, int filename_size
)
6230 pstrcpy(filename
, filename_size
, bs
->backing_file
);
6233 int bdrv_get_info(BlockDriverState
*bs
, BlockDriverInfo
*bdi
)
6236 BlockDriver
*drv
= bs
->drv
;
6238 /* if bs->drv == NULL, bs is closed, so there's nothing to do here */
6242 if (!drv
->bdrv_get_info
) {
6243 BlockDriverState
*filtered
= bdrv_filter_bs(bs
);
6245 return bdrv_get_info(filtered
, bdi
);
6249 memset(bdi
, 0, sizeof(*bdi
));
6250 ret
= drv
->bdrv_get_info(bs
, bdi
);
6255 if (bdi
->cluster_size
> BDRV_MAX_ALIGNMENT
) {
6262 ImageInfoSpecific
*bdrv_get_specific_info(BlockDriverState
*bs
,
6265 BlockDriver
*drv
= bs
->drv
;
6267 if (drv
&& drv
->bdrv_get_specific_info
) {
6268 return drv
->bdrv_get_specific_info(bs
, errp
);
6273 BlockStatsSpecific
*bdrv_get_specific_stats(BlockDriverState
*bs
)
6275 BlockDriver
*drv
= bs
->drv
;
6277 if (!drv
|| !drv
->bdrv_get_specific_stats
) {
6280 return drv
->bdrv_get_specific_stats(bs
);
6283 void bdrv_debug_event(BlockDriverState
*bs
, BlkdebugEvent event
)
6286 if (!bs
|| !bs
->drv
|| !bs
->drv
->bdrv_debug_event
) {
6290 bs
->drv
->bdrv_debug_event(bs
, event
);
6293 static BlockDriverState
*bdrv_find_debug_node(BlockDriverState
*bs
)
6295 GLOBAL_STATE_CODE();
6296 while (bs
&& bs
->drv
&& !bs
->drv
->bdrv_debug_breakpoint
) {
6297 bs
= bdrv_primary_bs(bs
);
6300 if (bs
&& bs
->drv
&& bs
->drv
->bdrv_debug_breakpoint
) {
6301 assert(bs
->drv
->bdrv_debug_remove_breakpoint
);
6308 int bdrv_debug_breakpoint(BlockDriverState
*bs
, const char *event
,
6311 GLOBAL_STATE_CODE();
6312 bs
= bdrv_find_debug_node(bs
);
6314 return bs
->drv
->bdrv_debug_breakpoint(bs
, event
, tag
);
6320 int bdrv_debug_remove_breakpoint(BlockDriverState
*bs
, const char *tag
)
6322 GLOBAL_STATE_CODE();
6323 bs
= bdrv_find_debug_node(bs
);
6325 return bs
->drv
->bdrv_debug_remove_breakpoint(bs
, tag
);
6331 int bdrv_debug_resume(BlockDriverState
*bs
, const char *tag
)
6333 GLOBAL_STATE_CODE();
6334 while (bs
&& (!bs
->drv
|| !bs
->drv
->bdrv_debug_resume
)) {
6335 bs
= bdrv_primary_bs(bs
);
6338 if (bs
&& bs
->drv
&& bs
->drv
->bdrv_debug_resume
) {
6339 return bs
->drv
->bdrv_debug_resume(bs
, tag
);
6345 bool bdrv_debug_is_suspended(BlockDriverState
*bs
, const char *tag
)
6347 GLOBAL_STATE_CODE();
6348 while (bs
&& bs
->drv
&& !bs
->drv
->bdrv_debug_is_suspended
) {
6349 bs
= bdrv_primary_bs(bs
);
6352 if (bs
&& bs
->drv
&& bs
->drv
->bdrv_debug_is_suspended
) {
6353 return bs
->drv
->bdrv_debug_is_suspended(bs
, tag
);
6359 /* backing_file can either be relative, or absolute, or a protocol. If it is
6360 * relative, it must be relative to the chain. So, passing in bs->filename
6361 * from a BDS as backing_file should not be done, as that may be relative to
6362 * the CWD rather than the chain. */
6363 BlockDriverState
*bdrv_find_backing_image(BlockDriverState
*bs
,
6364 const char *backing_file
)
6366 char *filename_full
= NULL
;
6367 char *backing_file_full
= NULL
;
6368 char *filename_tmp
= NULL
;
6369 int is_protocol
= 0;
6370 bool filenames_refreshed
= false;
6371 BlockDriverState
*curr_bs
= NULL
;
6372 BlockDriverState
*retval
= NULL
;
6373 BlockDriverState
*bs_below
;
6375 GLOBAL_STATE_CODE();
6377 if (!bs
|| !bs
->drv
|| !backing_file
) {
6381 filename_full
= g_malloc(PATH_MAX
);
6382 backing_file_full
= g_malloc(PATH_MAX
);
6384 is_protocol
= path_has_protocol(backing_file
);
6387 * Being largely a legacy function, skip any filters here
6388 * (because filters do not have normal filenames, so they cannot
6389 * match anyway; and allowing json:{} filenames is a bit out of
6392 for (curr_bs
= bdrv_skip_filters(bs
);
6393 bdrv_cow_child(curr_bs
) != NULL
;
6396 bs_below
= bdrv_backing_chain_next(curr_bs
);
6398 if (bdrv_backing_overridden(curr_bs
)) {
6400 * If the backing file was overridden, we can only compare
6401 * directly against the backing node's filename.
6404 if (!filenames_refreshed
) {
6406 * This will automatically refresh all of the
6407 * filenames in the rest of the backing chain, so we
6408 * only need to do this once.
6410 bdrv_refresh_filename(bs_below
);
6411 filenames_refreshed
= true;
6414 if (strcmp(backing_file
, bs_below
->filename
) == 0) {
6418 } else if (is_protocol
|| path_has_protocol(curr_bs
->backing_file
)) {
6420 * If either of the filename paths is actually a protocol, then
6421 * compare unmodified paths; otherwise make paths relative.
6423 char *backing_file_full_ret
;
6425 if (strcmp(backing_file
, curr_bs
->backing_file
) == 0) {
6429 /* Also check against the full backing filename for the image */
6430 backing_file_full_ret
= bdrv_get_full_backing_filename(curr_bs
,
6432 if (backing_file_full_ret
) {
6433 bool equal
= strcmp(backing_file
, backing_file_full_ret
) == 0;
6434 g_free(backing_file_full_ret
);
6441 /* If not an absolute filename path, make it relative to the current
6442 * image's filename path */
6443 filename_tmp
= bdrv_make_absolute_filename(curr_bs
, backing_file
,
6445 /* We are going to compare canonicalized absolute pathnames */
6446 if (!filename_tmp
|| !realpath(filename_tmp
, filename_full
)) {
6447 g_free(filename_tmp
);
6450 g_free(filename_tmp
);
6452 /* We need to make sure the backing filename we are comparing against
6453 * is relative to the current image filename (or absolute) */
6454 filename_tmp
= bdrv_get_full_backing_filename(curr_bs
, NULL
);
6455 if (!filename_tmp
|| !realpath(filename_tmp
, backing_file_full
)) {
6456 g_free(filename_tmp
);
6459 g_free(filename_tmp
);
6461 if (strcmp(backing_file_full
, filename_full
) == 0) {
6468 g_free(filename_full
);
6469 g_free(backing_file_full
);
6473 void bdrv_init(void)
6475 #ifdef CONFIG_BDRV_WHITELIST_TOOLS
6476 use_bdrv_whitelist
= 1;
6478 module_call_init(MODULE_INIT_BLOCK
);
6481 void bdrv_init_with_whitelist(void)
6483 use_bdrv_whitelist
= 1;
6487 int bdrv_activate(BlockDriverState
*bs
, Error
**errp
)
6489 BdrvChild
*child
, *parent
;
6490 Error
*local_err
= NULL
;
6492 BdrvDirtyBitmap
*bm
;
6494 GLOBAL_STATE_CODE();
6500 QLIST_FOREACH(child
, &bs
->children
, next
) {
6501 bdrv_activate(child
->bs
, &local_err
);
6503 error_propagate(errp
, local_err
);
6509 * Update permissions, they may differ for inactive nodes.
6511 * Note that the required permissions of inactive images are always a
6512 * subset of the permissions required after activating the image. This
6513 * allows us to just get the permissions upfront without restricting
6514 * bdrv_co_invalidate_cache().
6516 * It also means that in error cases, we don't have to try and revert to
6517 * the old permissions (which is an operation that could fail, too). We can
6518 * just keep the extended permissions for the next time that an activation
6519 * of the image is tried.
6521 if (bs
->open_flags
& BDRV_O_INACTIVE
) {
6522 bs
->open_flags
&= ~BDRV_O_INACTIVE
;
6523 ret
= bdrv_refresh_perms(bs
, errp
);
6525 bs
->open_flags
|= BDRV_O_INACTIVE
;
6529 ret
= bdrv_invalidate_cache(bs
, errp
);
6531 bs
->open_flags
|= BDRV_O_INACTIVE
;
6535 FOR_EACH_DIRTY_BITMAP(bs
, bm
) {
6536 bdrv_dirty_bitmap_skip_store(bm
, false);
6539 ret
= refresh_total_sectors(bs
, bs
->total_sectors
);
6541 bs
->open_flags
|= BDRV_O_INACTIVE
;
6542 error_setg_errno(errp
, -ret
, "Could not refresh total sector count");
6547 QLIST_FOREACH(parent
, &bs
->parents
, next_parent
) {
6548 if (parent
->klass
->activate
) {
6549 parent
->klass
->activate(parent
, &local_err
);
6551 bs
->open_flags
|= BDRV_O_INACTIVE
;
6552 error_propagate(errp
, local_err
);
6561 int coroutine_fn
bdrv_co_invalidate_cache(BlockDriverState
*bs
, Error
**errp
)
6563 Error
*local_err
= NULL
;
6566 assert(!(bs
->open_flags
& BDRV_O_INACTIVE
));
6568 if (bs
->drv
->bdrv_co_invalidate_cache
) {
6569 bs
->drv
->bdrv_co_invalidate_cache(bs
, &local_err
);
6571 error_propagate(errp
, local_err
);
6579 void bdrv_activate_all(Error
**errp
)
6581 BlockDriverState
*bs
;
6582 BdrvNextIterator it
;
6584 GLOBAL_STATE_CODE();
6586 for (bs
= bdrv_first(&it
); bs
; bs
= bdrv_next(&it
)) {
6587 AioContext
*aio_context
= bdrv_get_aio_context(bs
);
6590 aio_context_acquire(aio_context
);
6591 ret
= bdrv_activate(bs
, errp
);
6592 aio_context_release(aio_context
);
6594 bdrv_next_cleanup(&it
);
6600 static bool bdrv_has_bds_parent(BlockDriverState
*bs
, bool only_active
)
6603 GLOBAL_STATE_CODE();
6605 QLIST_FOREACH(parent
, &bs
->parents
, next_parent
) {
6606 if (parent
->klass
->parent_is_bds
) {
6607 BlockDriverState
*parent_bs
= parent
->opaque
;
6608 if (!only_active
|| !(parent_bs
->open_flags
& BDRV_O_INACTIVE
)) {
6617 static int bdrv_inactivate_recurse(BlockDriverState
*bs
)
6619 BdrvChild
*child
, *parent
;
6621 uint64_t cumulative_perms
, cumulative_shared_perms
;
6623 GLOBAL_STATE_CODE();
6629 /* Make sure that we don't inactivate a child before its parent.
6630 * It will be covered by recursion from the yet active parent. */
6631 if (bdrv_has_bds_parent(bs
, true)) {
6635 assert(!(bs
->open_flags
& BDRV_O_INACTIVE
));
6637 /* Inactivate this node */
6638 if (bs
->drv
->bdrv_inactivate
) {
6639 ret
= bs
->drv
->bdrv_inactivate(bs
);
6645 QLIST_FOREACH(parent
, &bs
->parents
, next_parent
) {
6646 if (parent
->klass
->inactivate
) {
6647 ret
= parent
->klass
->inactivate(parent
);
6654 bdrv_get_cumulative_perm(bs
, &cumulative_perms
,
6655 &cumulative_shared_perms
);
6656 if (cumulative_perms
& (BLK_PERM_WRITE
| BLK_PERM_WRITE_UNCHANGED
)) {
6657 /* Our inactive parents still need write access. Inactivation failed. */
6661 bs
->open_flags
|= BDRV_O_INACTIVE
;
6664 * Update permissions, they may differ for inactive nodes.
6665 * We only tried to loosen restrictions, so errors are not fatal, ignore
6668 bdrv_refresh_perms(bs
, NULL
);
6670 /* Recursively inactivate children */
6671 QLIST_FOREACH(child
, &bs
->children
, next
) {
6672 ret
= bdrv_inactivate_recurse(child
->bs
);
6681 int bdrv_inactivate_all(void)
6683 BlockDriverState
*bs
= NULL
;
6684 BdrvNextIterator it
;
6686 GSList
*aio_ctxs
= NULL
, *ctx
;
6688 GLOBAL_STATE_CODE();
6690 for (bs
= bdrv_first(&it
); bs
; bs
= bdrv_next(&it
)) {
6691 AioContext
*aio_context
= bdrv_get_aio_context(bs
);
6693 if (!g_slist_find(aio_ctxs
, aio_context
)) {
6694 aio_ctxs
= g_slist_prepend(aio_ctxs
, aio_context
);
6695 aio_context_acquire(aio_context
);
6699 for (bs
= bdrv_first(&it
); bs
; bs
= bdrv_next(&it
)) {
6700 /* Nodes with BDS parents are covered by recursion from the last
6701 * parent that gets inactivated. Don't inactivate them a second
6702 * time if that has already happened. */
6703 if (bdrv_has_bds_parent(bs
, false)) {
6706 ret
= bdrv_inactivate_recurse(bs
);
6708 bdrv_next_cleanup(&it
);
6714 for (ctx
= aio_ctxs
; ctx
!= NULL
; ctx
= ctx
->next
) {
6715 AioContext
*aio_context
= ctx
->data
;
6716 aio_context_release(aio_context
);
6718 g_slist_free(aio_ctxs
);
6723 /**************************************************************/
6724 /* removable device support */
6727 * Return TRUE if the media is present
6729 bool bdrv_is_inserted(BlockDriverState
*bs
)
6731 BlockDriver
*drv
= bs
->drv
;
6738 if (drv
->bdrv_is_inserted
) {
6739 return drv
->bdrv_is_inserted(bs
);
6741 QLIST_FOREACH(child
, &bs
->children
, next
) {
6742 if (!bdrv_is_inserted(child
->bs
)) {
6750 * If eject_flag is TRUE, eject the media. Otherwise, close the tray
6752 void bdrv_eject(BlockDriverState
*bs
, bool eject_flag
)
6754 BlockDriver
*drv
= bs
->drv
;
6757 if (drv
&& drv
->bdrv_eject
) {
6758 drv
->bdrv_eject(bs
, eject_flag
);
6763 * Lock or unlock the media (if it is locked, the user won't be able
6764 * to eject it manually).
6766 void bdrv_lock_medium(BlockDriverState
*bs
, bool locked
)
6768 BlockDriver
*drv
= bs
->drv
;
6770 trace_bdrv_lock_medium(bs
, locked
);
6772 if (drv
&& drv
->bdrv_lock_medium
) {
6773 drv
->bdrv_lock_medium(bs
, locked
);
6777 /* Get a reference to bs */
6778 void bdrv_ref(BlockDriverState
*bs
)
6780 GLOBAL_STATE_CODE();
6784 /* Release a previously grabbed reference to bs.
6785 * If after releasing, reference count is zero, the BlockDriverState is
6787 void bdrv_unref(BlockDriverState
*bs
)
6789 GLOBAL_STATE_CODE();
6793 assert(bs
->refcnt
> 0);
6794 if (--bs
->refcnt
== 0) {
6799 struct BdrvOpBlocker
{
6801 QLIST_ENTRY(BdrvOpBlocker
) list
;
6804 bool bdrv_op_is_blocked(BlockDriverState
*bs
, BlockOpType op
, Error
**errp
)
6806 BdrvOpBlocker
*blocker
;
6807 GLOBAL_STATE_CODE();
6808 assert((int) op
>= 0 && op
< BLOCK_OP_TYPE_MAX
);
6809 if (!QLIST_EMPTY(&bs
->op_blockers
[op
])) {
6810 blocker
= QLIST_FIRST(&bs
->op_blockers
[op
]);
6811 error_propagate_prepend(errp
, error_copy(blocker
->reason
),
6812 "Node '%s' is busy: ",
6813 bdrv_get_device_or_node_name(bs
));
6819 void bdrv_op_block(BlockDriverState
*bs
, BlockOpType op
, Error
*reason
)
6821 BdrvOpBlocker
*blocker
;
6822 GLOBAL_STATE_CODE();
6823 assert((int) op
>= 0 && op
< BLOCK_OP_TYPE_MAX
);
6825 blocker
= g_new0(BdrvOpBlocker
, 1);
6826 blocker
->reason
= reason
;
6827 QLIST_INSERT_HEAD(&bs
->op_blockers
[op
], blocker
, list
);
6830 void bdrv_op_unblock(BlockDriverState
*bs
, BlockOpType op
, Error
*reason
)
6832 BdrvOpBlocker
*blocker
, *next
;
6833 GLOBAL_STATE_CODE();
6834 assert((int) op
>= 0 && op
< BLOCK_OP_TYPE_MAX
);
6835 QLIST_FOREACH_SAFE(blocker
, &bs
->op_blockers
[op
], list
, next
) {
6836 if (blocker
->reason
== reason
) {
6837 QLIST_REMOVE(blocker
, list
);
6843 void bdrv_op_block_all(BlockDriverState
*bs
, Error
*reason
)
6846 GLOBAL_STATE_CODE();
6847 for (i
= 0; i
< BLOCK_OP_TYPE_MAX
; i
++) {
6848 bdrv_op_block(bs
, i
, reason
);
6852 void bdrv_op_unblock_all(BlockDriverState
*bs
, Error
*reason
)
6855 GLOBAL_STATE_CODE();
6856 for (i
= 0; i
< BLOCK_OP_TYPE_MAX
; i
++) {
6857 bdrv_op_unblock(bs
, i
, reason
);
6861 bool bdrv_op_blocker_is_empty(BlockDriverState
*bs
)
6864 GLOBAL_STATE_CODE();
6865 for (i
= 0; i
< BLOCK_OP_TYPE_MAX
; i
++) {
6866 if (!QLIST_EMPTY(&bs
->op_blockers
[i
])) {
6873 void bdrv_img_create(const char *filename
, const char *fmt
,
6874 const char *base_filename
, const char *base_fmt
,
6875 char *options
, uint64_t img_size
, int flags
, bool quiet
,
6878 QemuOptsList
*create_opts
= NULL
;
6879 QemuOpts
*opts
= NULL
;
6880 const char *backing_fmt
, *backing_file
;
6882 BlockDriver
*drv
, *proto_drv
;
6883 Error
*local_err
= NULL
;
6886 GLOBAL_STATE_CODE();
6888 /* Find driver and parse its options */
6889 drv
= bdrv_find_format(fmt
);
6891 error_setg(errp
, "Unknown file format '%s'", fmt
);
6895 proto_drv
= bdrv_find_protocol(filename
, true, errp
);
6900 if (!drv
->create_opts
) {
6901 error_setg(errp
, "Format driver '%s' does not support image creation",
6906 if (!proto_drv
->create_opts
) {
6907 error_setg(errp
, "Protocol driver '%s' does not support image creation",
6908 proto_drv
->format_name
);
6912 /* Create parameter list */
6913 create_opts
= qemu_opts_append(create_opts
, drv
->create_opts
);
6914 create_opts
= qemu_opts_append(create_opts
, proto_drv
->create_opts
);
6916 opts
= qemu_opts_create(create_opts
, NULL
, 0, &error_abort
);
6918 /* Parse -o options */
6920 if (!qemu_opts_do_parse(opts
, options
, NULL
, errp
)) {
6925 if (!qemu_opt_get(opts
, BLOCK_OPT_SIZE
)) {
6926 qemu_opt_set_number(opts
, BLOCK_OPT_SIZE
, img_size
, &error_abort
);
6927 } else if (img_size
!= UINT64_C(-1)) {
6928 error_setg(errp
, "The image size must be specified only once");
6932 if (base_filename
) {
6933 if (!qemu_opt_set(opts
, BLOCK_OPT_BACKING_FILE
, base_filename
,
6935 error_setg(errp
, "Backing file not supported for file format '%s'",
6942 if (!qemu_opt_set(opts
, BLOCK_OPT_BACKING_FMT
, base_fmt
, NULL
)) {
6943 error_setg(errp
, "Backing file format not supported for file "
6944 "format '%s'", fmt
);
6949 backing_file
= qemu_opt_get(opts
, BLOCK_OPT_BACKING_FILE
);
6951 if (!strcmp(filename
, backing_file
)) {
6952 error_setg(errp
, "Error: Trying to create an image with the "
6953 "same filename as the backing file");
6956 if (backing_file
[0] == '\0') {
6957 error_setg(errp
, "Expected backing file name, got empty string");
6962 backing_fmt
= qemu_opt_get(opts
, BLOCK_OPT_BACKING_FMT
);
6964 /* The size for the image must always be specified, unless we have a backing
6965 * file and we have not been forbidden from opening it. */
6966 size
= qemu_opt_get_size(opts
, BLOCK_OPT_SIZE
, img_size
);
6967 if (backing_file
&& !(flags
& BDRV_O_NO_BACKING
)) {
6968 BlockDriverState
*bs
;
6971 QDict
*backing_options
= NULL
;
6974 bdrv_get_full_backing_filename_from_filename(filename
, backing_file
,
6979 assert(full_backing
);
6982 * No need to do I/O here, which allows us to open encrypted
6983 * backing images without needing the secret
6986 back_flags
&= ~(BDRV_O_RDWR
| BDRV_O_SNAPSHOT
| BDRV_O_NO_BACKING
);
6987 back_flags
|= BDRV_O_NO_IO
;
6989 backing_options
= qdict_new();
6991 qdict_put_str(backing_options
, "driver", backing_fmt
);
6993 qdict_put_bool(backing_options
, BDRV_OPT_FORCE_SHARE
, true);
6995 bs
= bdrv_open(full_backing
, NULL
, backing_options
, back_flags
,
6997 g_free(full_backing
);
6999 error_append_hint(&local_err
, "Could not open backing image.\n");
7003 error_setg(&local_err
,
7004 "Backing file specified without backing format");
7005 error_append_hint(&local_err
, "Detected format of %s.",
7006 bs
->drv
->format_name
);
7010 /* Opened BS, have no size */
7011 size
= bdrv_getlength(bs
);
7013 error_setg_errno(errp
, -size
, "Could not get size of '%s'",
7018 qemu_opt_set_number(opts
, BLOCK_OPT_SIZE
, size
, &error_abort
);
7022 /* (backing_file && !(flags & BDRV_O_NO_BACKING)) */
7023 } else if (backing_file
&& !backing_fmt
) {
7024 error_setg(&local_err
,
7025 "Backing file specified without backing format");
7030 error_setg(errp
, "Image creation needs a size parameter");
7035 printf("Formatting '%s', fmt=%s ", filename
, fmt
);
7036 qemu_opts_print(opts
, " ");
7041 ret
= bdrv_create(drv
, filename
, opts
, &local_err
);
7043 if (ret
== -EFBIG
) {
7044 /* This is generally a better message than whatever the driver would
7045 * deliver (especially because of the cluster_size_hint), since that
7046 * is most probably not much different from "image too large". */
7047 const char *cluster_size_hint
= "";
7048 if (qemu_opt_get_size(opts
, BLOCK_OPT_CLUSTER_SIZE
, 0)) {
7049 cluster_size_hint
= " (try using a larger cluster size)";
7051 error_setg(errp
, "The image size is too large for file format '%s'"
7052 "%s", fmt
, cluster_size_hint
);
7053 error_free(local_err
);
7058 qemu_opts_del(opts
);
7059 qemu_opts_free(create_opts
);
7060 error_propagate(errp
, local_err
);
7063 AioContext
*bdrv_get_aio_context(BlockDriverState
*bs
)
7066 return bs
? bs
->aio_context
: qemu_get_aio_context();
7069 AioContext
*coroutine_fn
bdrv_co_enter(BlockDriverState
*bs
)
7071 Coroutine
*self
= qemu_coroutine_self();
7072 AioContext
*old_ctx
= qemu_coroutine_get_aio_context(self
);
7073 AioContext
*new_ctx
;
7077 * Increase bs->in_flight to ensure that this operation is completed before
7078 * moving the node to a different AioContext. Read new_ctx only afterwards.
7080 bdrv_inc_in_flight(bs
);
7082 new_ctx
= bdrv_get_aio_context(bs
);
7083 aio_co_reschedule_self(new_ctx
);
7087 void coroutine_fn
bdrv_co_leave(BlockDriverState
*bs
, AioContext
*old_ctx
)
7090 aio_co_reschedule_self(old_ctx
);
7091 bdrv_dec_in_flight(bs
);
7094 void coroutine_fn
bdrv_co_lock(BlockDriverState
*bs
)
7096 AioContext
*ctx
= bdrv_get_aio_context(bs
);
7098 /* In the main thread, bs->aio_context won't change concurrently */
7099 assert(qemu_get_current_aio_context() == qemu_get_aio_context());
7102 * We're in coroutine context, so we already hold the lock of the main
7103 * loop AioContext. Don't lock it twice to avoid deadlocks.
7105 assert(qemu_in_coroutine());
7106 if (ctx
!= qemu_get_aio_context()) {
7107 aio_context_acquire(ctx
);
7111 void coroutine_fn
bdrv_co_unlock(BlockDriverState
*bs
)
7113 AioContext
*ctx
= bdrv_get_aio_context(bs
);
7115 assert(qemu_in_coroutine());
7116 if (ctx
!= qemu_get_aio_context()) {
7117 aio_context_release(ctx
);
7121 void bdrv_coroutine_enter(BlockDriverState
*bs
, Coroutine
*co
)
7124 aio_co_enter(bdrv_get_aio_context(bs
), co
);
7127 static void bdrv_do_remove_aio_context_notifier(BdrvAioNotifier
*ban
)
7129 GLOBAL_STATE_CODE();
7130 QLIST_REMOVE(ban
, list
);
7134 static void bdrv_detach_aio_context(BlockDriverState
*bs
)
7136 BdrvAioNotifier
*baf
, *baf_tmp
;
7138 assert(!bs
->walking_aio_notifiers
);
7139 GLOBAL_STATE_CODE();
7140 bs
->walking_aio_notifiers
= true;
7141 QLIST_FOREACH_SAFE(baf
, &bs
->aio_notifiers
, list
, baf_tmp
) {
7143 bdrv_do_remove_aio_context_notifier(baf
);
7145 baf
->detach_aio_context(baf
->opaque
);
7148 /* Never mind iterating again to check for ->deleted. bdrv_close() will
7149 * remove remaining aio notifiers if we aren't called again.
7151 bs
->walking_aio_notifiers
= false;
7153 if (bs
->drv
&& bs
->drv
->bdrv_detach_aio_context
) {
7154 bs
->drv
->bdrv_detach_aio_context(bs
);
7157 if (bs
->quiesce_counter
) {
7158 aio_enable_external(bs
->aio_context
);
7160 assert_bdrv_graph_writable(bs
);
7161 bs
->aio_context
= NULL
;
7164 static void bdrv_attach_aio_context(BlockDriverState
*bs
,
7165 AioContext
*new_context
)
7167 BdrvAioNotifier
*ban
, *ban_tmp
;
7168 GLOBAL_STATE_CODE();
7170 if (bs
->quiesce_counter
) {
7171 aio_disable_external(new_context
);
7174 assert_bdrv_graph_writable(bs
);
7175 bs
->aio_context
= new_context
;
7177 if (bs
->drv
&& bs
->drv
->bdrv_attach_aio_context
) {
7178 bs
->drv
->bdrv_attach_aio_context(bs
, new_context
);
7181 assert(!bs
->walking_aio_notifiers
);
7182 bs
->walking_aio_notifiers
= true;
7183 QLIST_FOREACH_SAFE(ban
, &bs
->aio_notifiers
, list
, ban_tmp
) {
7185 bdrv_do_remove_aio_context_notifier(ban
);
7187 ban
->attached_aio_context(new_context
, ban
->opaque
);
7190 bs
->walking_aio_notifiers
= false;
7193 typedef struct BdrvStateSetAioContext
{
7194 AioContext
*new_ctx
;
7195 BlockDriverState
*bs
;
7196 } BdrvStateSetAioContext
;
7198 static bool bdrv_parent_change_aio_context(BdrvChild
*c
, AioContext
*ctx
,
7199 GHashTable
*visited
,
7203 GLOBAL_STATE_CODE();
7204 if (g_hash_table_contains(visited
, c
)) {
7207 g_hash_table_add(visited
, c
);
7210 * A BdrvChildClass that doesn't handle AioContext changes cannot
7211 * tolerate any AioContext changes
7213 if (!c
->klass
->change_aio_ctx
) {
7214 char *user
= bdrv_child_user_desc(c
);
7215 error_setg(errp
, "Changing iothreads is not supported by %s", user
);
7219 if (!c
->klass
->change_aio_ctx(c
, ctx
, visited
, tran
, errp
)) {
7220 assert(!errp
|| *errp
);
7226 bool bdrv_child_change_aio_context(BdrvChild
*c
, AioContext
*ctx
,
7227 GHashTable
*visited
, Transaction
*tran
,
7230 GLOBAL_STATE_CODE();
7231 if (g_hash_table_contains(visited
, c
)) {
7234 g_hash_table_add(visited
, c
);
7235 return bdrv_change_aio_context(c
->bs
, ctx
, visited
, tran
, errp
);
7238 static void bdrv_set_aio_context_clean(void *opaque
)
7240 BdrvStateSetAioContext
*state
= (BdrvStateSetAioContext
*) opaque
;
7241 BlockDriverState
*bs
= (BlockDriverState
*) state
->bs
;
7243 /* Paired with bdrv_drained_begin in bdrv_change_aio_context() */
7244 bdrv_drained_end(bs
);
7249 static void bdrv_set_aio_context_commit(void *opaque
)
7251 BdrvStateSetAioContext
*state
= (BdrvStateSetAioContext
*) opaque
;
7252 BlockDriverState
*bs
= (BlockDriverState
*) state
->bs
;
7253 AioContext
*new_context
= state
->new_ctx
;
7254 AioContext
*old_context
= bdrv_get_aio_context(bs
);
7255 assert_bdrv_graph_writable(bs
);
7258 * Take the old AioContex when detaching it from bs.
7259 * At this point, new_context lock is already acquired, and we are now
7260 * also taking old_context. This is safe as long as bdrv_detach_aio_context
7261 * does not call AIO_POLL_WHILE().
7263 if (old_context
!= qemu_get_aio_context()) {
7264 aio_context_acquire(old_context
);
7266 bdrv_detach_aio_context(bs
);
7267 if (old_context
!= qemu_get_aio_context()) {
7268 aio_context_release(old_context
);
7270 bdrv_attach_aio_context(bs
, new_context
);
7273 static TransactionActionDrv set_aio_context
= {
7274 .commit
= bdrv_set_aio_context_commit
,
7275 .clean
= bdrv_set_aio_context_clean
,
7279 * Changes the AioContext used for fd handlers, timers, and BHs by this
7280 * BlockDriverState and all its children and parents.
7282 * Must be called from the main AioContext.
7284 * The caller must own the AioContext lock for the old AioContext of bs, but it
7285 * must not own the AioContext lock for new_context (unless new_context is the
7286 * same as the current context of bs).
7288 * @visited will accumulate all visited BdrvChild objects. The caller is
7289 * responsible for freeing the list afterwards.
7291 static bool bdrv_change_aio_context(BlockDriverState
*bs
, AioContext
*ctx
,
7292 GHashTable
*visited
, Transaction
*tran
,
7296 BdrvStateSetAioContext
*state
;
7298 GLOBAL_STATE_CODE();
7300 if (bdrv_get_aio_context(bs
) == ctx
) {
7304 QLIST_FOREACH(c
, &bs
->parents
, next_parent
) {
7305 if (!bdrv_parent_change_aio_context(c
, ctx
, visited
, tran
, errp
)) {
7310 QLIST_FOREACH(c
, &bs
->children
, next
) {
7311 if (!bdrv_child_change_aio_context(c
, ctx
, visited
, tran
, errp
)) {
7316 state
= g_new(BdrvStateSetAioContext
, 1);
7317 *state
= (BdrvStateSetAioContext
) {
7322 /* Paired with bdrv_drained_end in bdrv_set_aio_context_clean() */
7323 bdrv_drained_begin(bs
);
7325 tran_add(tran
, &set_aio_context
, state
);
7331 * Change bs's and recursively all of its parents' and children's AioContext
7332 * to the given new context, returning an error if that isn't possible.
7334 * If ignore_child is not NULL, that child (and its subgraph) will not
7337 * This function still requires the caller to take the bs current
7338 * AioContext lock, otherwise draining will fail since AIO_WAIT_WHILE
7339 * assumes the lock is always held if bs is in another AioContext.
7340 * For the same reason, it temporarily also holds the new AioContext, since
7341 * bdrv_drained_end calls BDRV_POLL_WHILE that assumes the lock is taken too.
7342 * Therefore the new AioContext lock must not be taken by the caller.
7344 int bdrv_try_change_aio_context(BlockDriverState
*bs
, AioContext
*ctx
,
7345 BdrvChild
*ignore_child
, Error
**errp
)
7348 GHashTable
*visited
;
7350 AioContext
*old_context
= bdrv_get_aio_context(bs
);
7351 GLOBAL_STATE_CODE();
7354 * Recursion phase: go through all nodes of the graph.
7355 * Take care of checking that all nodes support changing AioContext
7356 * and drain them, builing a linear list of callbacks to run if everything
7357 * is successful (the transaction itself).
7360 visited
= g_hash_table_new(NULL
, NULL
);
7362 g_hash_table_add(visited
, ignore_child
);
7364 ret
= bdrv_change_aio_context(bs
, ctx
, visited
, tran
, errp
);
7365 g_hash_table_destroy(visited
);
7368 * Linear phase: go through all callbacks collected in the transaction.
7369 * Run all callbacks collected in the recursion to switch all nodes
7370 * AioContext lock (transaction commit), or undo all changes done in the
7371 * recursion (transaction abort).
7375 /* Just run clean() callbacks. No AioContext changed. */
7381 * Release old AioContext, it won't be needed anymore, as all
7382 * bdrv_drained_begin() have been called already.
7384 if (qemu_get_aio_context() != old_context
) {
7385 aio_context_release(old_context
);
7389 * Acquire new AioContext since bdrv_drained_end() is going to be called
7390 * after we switched all nodes in the new AioContext, and the function
7391 * assumes that the lock of the bs is always taken.
7393 if (qemu_get_aio_context() != ctx
) {
7394 aio_context_acquire(ctx
);
7399 if (qemu_get_aio_context() != ctx
) {
7400 aio_context_release(ctx
);
7403 /* Re-acquire the old AioContext, since the caller takes and releases it. */
7404 if (qemu_get_aio_context() != old_context
) {
7405 aio_context_acquire(old_context
);
7411 void bdrv_add_aio_context_notifier(BlockDriverState
*bs
,
7412 void (*attached_aio_context
)(AioContext
*new_context
, void *opaque
),
7413 void (*detach_aio_context
)(void *opaque
), void *opaque
)
7415 BdrvAioNotifier
*ban
= g_new(BdrvAioNotifier
, 1);
7416 *ban
= (BdrvAioNotifier
){
7417 .attached_aio_context
= attached_aio_context
,
7418 .detach_aio_context
= detach_aio_context
,
7421 GLOBAL_STATE_CODE();
7423 QLIST_INSERT_HEAD(&bs
->aio_notifiers
, ban
, list
);
7426 void bdrv_remove_aio_context_notifier(BlockDriverState
*bs
,
7427 void (*attached_aio_context
)(AioContext
*,
7429 void (*detach_aio_context
)(void *),
7432 BdrvAioNotifier
*ban
, *ban_next
;
7433 GLOBAL_STATE_CODE();
7435 QLIST_FOREACH_SAFE(ban
, &bs
->aio_notifiers
, list
, ban_next
) {
7436 if (ban
->attached_aio_context
== attached_aio_context
&&
7437 ban
->detach_aio_context
== detach_aio_context
&&
7438 ban
->opaque
== opaque
&&
7439 ban
->deleted
== false)
7441 if (bs
->walking_aio_notifiers
) {
7442 ban
->deleted
= true;
7444 bdrv_do_remove_aio_context_notifier(ban
);
7453 int bdrv_amend_options(BlockDriverState
*bs
, QemuOpts
*opts
,
7454 BlockDriverAmendStatusCB
*status_cb
, void *cb_opaque
,
7458 GLOBAL_STATE_CODE();
7460 error_setg(errp
, "Node is ejected");
7463 if (!bs
->drv
->bdrv_amend_options
) {
7464 error_setg(errp
, "Block driver '%s' does not support option amendment",
7465 bs
->drv
->format_name
);
7468 return bs
->drv
->bdrv_amend_options(bs
, opts
, status_cb
,
7469 cb_opaque
, force
, errp
);
7473 * This function checks whether the given @to_replace is allowed to be
7474 * replaced by a node that always shows the same data as @bs. This is
7475 * used for example to verify whether the mirror job can replace
7476 * @to_replace by the target mirrored from @bs.
7477 * To be replaceable, @bs and @to_replace may either be guaranteed to
7478 * always show the same data (because they are only connected through
7479 * filters), or some driver may allow replacing one of its children
7480 * because it can guarantee that this child's data is not visible at
7481 * all (for example, for dissenting quorum children that have no other
7484 bool bdrv_recurse_can_replace(BlockDriverState
*bs
,
7485 BlockDriverState
*to_replace
)
7487 BlockDriverState
*filtered
;
7489 GLOBAL_STATE_CODE();
7491 if (!bs
|| !bs
->drv
) {
7495 if (bs
== to_replace
) {
7499 /* See what the driver can do */
7500 if (bs
->drv
->bdrv_recurse_can_replace
) {
7501 return bs
->drv
->bdrv_recurse_can_replace(bs
, to_replace
);
7504 /* For filters without an own implementation, we can recurse on our own */
7505 filtered
= bdrv_filter_bs(bs
);
7507 return bdrv_recurse_can_replace(filtered
, to_replace
);
7515 * Check whether the given @node_name can be replaced by a node that
7516 * has the same data as @parent_bs. If so, return @node_name's BDS;
7519 * @node_name must be a (recursive) *child of @parent_bs (or this
7520 * function will return NULL).
7522 * The result (whether the node can be replaced or not) is only valid
7523 * for as long as no graph or permission changes occur.
7525 BlockDriverState
*check_to_replace_node(BlockDriverState
*parent_bs
,
7526 const char *node_name
, Error
**errp
)
7528 BlockDriverState
*to_replace_bs
= bdrv_find_node(node_name
);
7529 AioContext
*aio_context
;
7531 GLOBAL_STATE_CODE();
7533 if (!to_replace_bs
) {
7534 error_setg(errp
, "Failed to find node with node-name='%s'", node_name
);
7538 aio_context
= bdrv_get_aio_context(to_replace_bs
);
7539 aio_context_acquire(aio_context
);
7541 if (bdrv_op_is_blocked(to_replace_bs
, BLOCK_OP_TYPE_REPLACE
, errp
)) {
7542 to_replace_bs
= NULL
;
7546 /* We don't want arbitrary node of the BDS chain to be replaced only the top
7547 * most non filter in order to prevent data corruption.
7548 * Another benefit is that this tests exclude backing files which are
7549 * blocked by the backing blockers.
7551 if (!bdrv_recurse_can_replace(parent_bs
, to_replace_bs
)) {
7552 error_setg(errp
, "Cannot replace '%s' by a node mirrored from '%s', "
7553 "because it cannot be guaranteed that doing so would not "
7554 "lead to an abrupt change of visible data",
7555 node_name
, parent_bs
->node_name
);
7556 to_replace_bs
= NULL
;
7561 aio_context_release(aio_context
);
7562 return to_replace_bs
;
7566 * Iterates through the list of runtime option keys that are said to
7567 * be "strong" for a BDS. An option is called "strong" if it changes
7568 * a BDS's data. For example, the null block driver's "size" and
7569 * "read-zeroes" options are strong, but its "latency-ns" option is
7572 * If a key returned by this function ends with a dot, all options
7573 * starting with that prefix are strong.
7575 static const char *const *strong_options(BlockDriverState
*bs
,
7576 const char *const *curopt
)
7578 static const char *const global_options
[] = {
7579 "driver", "filename", NULL
7583 return &global_options
[0];
7587 if (curopt
== &global_options
[ARRAY_SIZE(global_options
) - 1] && bs
->drv
) {
7588 curopt
= bs
->drv
->strong_runtime_opts
;
7591 return (curopt
&& *curopt
) ? curopt
: NULL
;
7595 * Copies all strong runtime options from bs->options to the given
7596 * QDict. The set of strong option keys is determined by invoking
7599 * Returns true iff any strong option was present in bs->options (and
7600 * thus copied to the target QDict) with the exception of "filename"
7601 * and "driver". The caller is expected to use this value to decide
7602 * whether the existence of strong options prevents the generation of
7605 static bool append_strong_runtime_options(QDict
*d
, BlockDriverState
*bs
)
7607 bool found_any
= false;
7608 const char *const *option_name
= NULL
;
7614 while ((option_name
= strong_options(bs
, option_name
))) {
7615 bool option_given
= false;
7617 assert(strlen(*option_name
) > 0);
7618 if ((*option_name
)[strlen(*option_name
) - 1] != '.') {
7619 QObject
*entry
= qdict_get(bs
->options
, *option_name
);
7624 qdict_put_obj(d
, *option_name
, qobject_ref(entry
));
7625 option_given
= true;
7627 const QDictEntry
*entry
;
7628 for (entry
= qdict_first(bs
->options
); entry
;
7629 entry
= qdict_next(bs
->options
, entry
))
7631 if (strstart(qdict_entry_key(entry
), *option_name
, NULL
)) {
7632 qdict_put_obj(d
, qdict_entry_key(entry
),
7633 qobject_ref(qdict_entry_value(entry
)));
7634 option_given
= true;
7639 /* While "driver" and "filename" need to be included in a JSON filename,
7640 * their existence does not prohibit generation of a plain filename. */
7641 if (!found_any
&& option_given
&&
7642 strcmp(*option_name
, "driver") && strcmp(*option_name
, "filename"))
7648 if (!qdict_haskey(d
, "driver")) {
7649 /* Drivers created with bdrv_new_open_driver() may not have a
7650 * @driver option. Add it here. */
7651 qdict_put_str(d
, "driver", bs
->drv
->format_name
);
7657 /* Note: This function may return false positives; it may return true
7658 * even if opening the backing file specified by bs's image header
7659 * would result in exactly bs->backing. */
7660 static bool bdrv_backing_overridden(BlockDriverState
*bs
)
7662 GLOBAL_STATE_CODE();
7664 return strcmp(bs
->auto_backing_file
,
7665 bs
->backing
->bs
->filename
);
7667 /* No backing BDS, so if the image header reports any backing
7668 * file, it must have been suppressed */
7669 return bs
->auto_backing_file
[0] != '\0';
7673 /* Updates the following BDS fields:
7674 * - exact_filename: A filename which may be used for opening a block device
7675 * which (mostly) equals the given BDS (even without any
7676 * other options; so reading and writing must return the same
7677 * results, but caching etc. may be different)
7678 * - full_open_options: Options which, when given when opening a block device
7679 * (without a filename), result in a BDS (mostly)
7680 * equalling the given one
7681 * - filename: If exact_filename is set, it is copied here. Otherwise,
7682 * full_open_options is converted to a JSON object, prefixed with
7683 * "json:" (for use through the JSON pseudo protocol) and put here.
7685 void bdrv_refresh_filename(BlockDriverState
*bs
)
7687 BlockDriver
*drv
= bs
->drv
;
7689 BlockDriverState
*primary_child_bs
;
7691 bool backing_overridden
;
7692 bool generate_json_filename
; /* Whether our default implementation should
7693 fill exact_filename (false) or not (true) */
7695 GLOBAL_STATE_CODE();
7701 /* This BDS's file name may depend on any of its children's file names, so
7702 * refresh those first */
7703 QLIST_FOREACH(child
, &bs
->children
, next
) {
7704 bdrv_refresh_filename(child
->bs
);
7708 /* For implicit nodes, just copy everything from the single child */
7709 child
= QLIST_FIRST(&bs
->children
);
7710 assert(QLIST_NEXT(child
, next
) == NULL
);
7712 pstrcpy(bs
->exact_filename
, sizeof(bs
->exact_filename
),
7713 child
->bs
->exact_filename
);
7714 pstrcpy(bs
->filename
, sizeof(bs
->filename
), child
->bs
->filename
);
7716 qobject_unref(bs
->full_open_options
);
7717 bs
->full_open_options
= qobject_ref(child
->bs
->full_open_options
);
7722 backing_overridden
= bdrv_backing_overridden(bs
);
7724 if (bs
->open_flags
& BDRV_O_NO_IO
) {
7725 /* Without I/O, the backing file does not change anything.
7726 * Therefore, in such a case (primarily qemu-img), we can
7727 * pretend the backing file has not been overridden even if
7728 * it technically has been. */
7729 backing_overridden
= false;
7732 /* Gather the options QDict */
7734 generate_json_filename
= append_strong_runtime_options(opts
, bs
);
7735 generate_json_filename
|= backing_overridden
;
7737 if (drv
->bdrv_gather_child_options
) {
7738 /* Some block drivers may not want to present all of their children's
7739 * options, or name them differently from BdrvChild.name */
7740 drv
->bdrv_gather_child_options(bs
, opts
, backing_overridden
);
7742 QLIST_FOREACH(child
, &bs
->children
, next
) {
7743 if (child
== bs
->backing
&& !backing_overridden
) {
7744 /* We can skip the backing BDS if it has not been overridden */
7748 qdict_put(opts
, child
->name
,
7749 qobject_ref(child
->bs
->full_open_options
));
7752 if (backing_overridden
&& !bs
->backing
) {
7753 /* Force no backing file */
7754 qdict_put_null(opts
, "backing");
7758 qobject_unref(bs
->full_open_options
);
7759 bs
->full_open_options
= opts
;
7761 primary_child_bs
= bdrv_primary_bs(bs
);
7763 if (drv
->bdrv_refresh_filename
) {
7764 /* Obsolete information is of no use here, so drop the old file name
7765 * information before refreshing it */
7766 bs
->exact_filename
[0] = '\0';
7768 drv
->bdrv_refresh_filename(bs
);
7769 } else if (primary_child_bs
) {
7771 * Try to reconstruct valid information from the underlying
7772 * file -- this only works for format nodes (filter nodes
7773 * cannot be probed and as such must be selected by the user
7774 * either through an options dict, or through a special
7775 * filename which the filter driver must construct in its
7776 * .bdrv_refresh_filename() implementation).
7779 bs
->exact_filename
[0] = '\0';
7782 * We can use the underlying file's filename if:
7783 * - it has a filename,
7784 * - the current BDS is not a filter,
7785 * - the file is a protocol BDS, and
7786 * - opening that file (as this BDS's format) will automatically create
7787 * the BDS tree we have right now, that is:
7788 * - the user did not significantly change this BDS's behavior with
7789 * some explicit (strong) options
7790 * - no non-file child of this BDS has been overridden by the user
7791 * Both of these conditions are represented by generate_json_filename.
7793 if (primary_child_bs
->exact_filename
[0] &&
7794 primary_child_bs
->drv
->bdrv_file_open
&&
7795 !drv
->is_filter
&& !generate_json_filename
)
7797 strcpy(bs
->exact_filename
, primary_child_bs
->exact_filename
);
7801 if (bs
->exact_filename
[0]) {
7802 pstrcpy(bs
->filename
, sizeof(bs
->filename
), bs
->exact_filename
);
7804 GString
*json
= qobject_to_json(QOBJECT(bs
->full_open_options
));
7805 if (snprintf(bs
->filename
, sizeof(bs
->filename
), "json:%s",
7806 json
->str
) >= sizeof(bs
->filename
)) {
7807 /* Give user a hint if we truncated things. */
7808 strcpy(bs
->filename
+ sizeof(bs
->filename
) - 4, "...");
7810 g_string_free(json
, true);
7814 char *bdrv_dirname(BlockDriverState
*bs
, Error
**errp
)
7816 BlockDriver
*drv
= bs
->drv
;
7817 BlockDriverState
*child_bs
;
7819 GLOBAL_STATE_CODE();
7822 error_setg(errp
, "Node '%s' is ejected", bs
->node_name
);
7826 if (drv
->bdrv_dirname
) {
7827 return drv
->bdrv_dirname(bs
, errp
);
7830 child_bs
= bdrv_primary_bs(bs
);
7832 return bdrv_dirname(child_bs
, errp
);
7835 bdrv_refresh_filename(bs
);
7836 if (bs
->exact_filename
[0] != '\0') {
7837 return path_combine(bs
->exact_filename
, "");
7840 error_setg(errp
, "Cannot generate a base directory for %s nodes",
7846 * Hot add/remove a BDS's child. So the user can take a child offline when
7847 * it is broken and take a new child online
7849 void bdrv_add_child(BlockDriverState
*parent_bs
, BlockDriverState
*child_bs
,
7852 GLOBAL_STATE_CODE();
7853 if (!parent_bs
->drv
|| !parent_bs
->drv
->bdrv_add_child
) {
7854 error_setg(errp
, "The node %s does not support adding a child",
7855 bdrv_get_device_or_node_name(parent_bs
));
7859 if (!QLIST_EMPTY(&child_bs
->parents
)) {
7860 error_setg(errp
, "The node %s already has a parent",
7861 child_bs
->node_name
);
7865 parent_bs
->drv
->bdrv_add_child(parent_bs
, child_bs
, errp
);
7868 void bdrv_del_child(BlockDriverState
*parent_bs
, BdrvChild
*child
, Error
**errp
)
7872 GLOBAL_STATE_CODE();
7873 if (!parent_bs
->drv
|| !parent_bs
->drv
->bdrv_del_child
) {
7874 error_setg(errp
, "The node %s does not support removing a child",
7875 bdrv_get_device_or_node_name(parent_bs
));
7879 QLIST_FOREACH(tmp
, &parent_bs
->children
, next
) {
7886 error_setg(errp
, "The node %s does not have a child named %s",
7887 bdrv_get_device_or_node_name(parent_bs
),
7888 bdrv_get_device_or_node_name(child
->bs
));
7892 parent_bs
->drv
->bdrv_del_child(parent_bs
, child
, errp
);
7895 int bdrv_make_empty(BdrvChild
*c
, Error
**errp
)
7897 BlockDriver
*drv
= c
->bs
->drv
;
7900 GLOBAL_STATE_CODE();
7901 assert(c
->perm
& (BLK_PERM_WRITE
| BLK_PERM_WRITE_UNCHANGED
));
7903 if (!drv
->bdrv_make_empty
) {
7904 error_setg(errp
, "%s does not support emptying nodes",
7909 ret
= drv
->bdrv_make_empty(c
->bs
);
7911 error_setg_errno(errp
, -ret
, "Failed to empty %s",
7920 * Return the child that @bs acts as an overlay for, and from which data may be
7921 * copied in COW or COR operations. Usually this is the backing file.
7923 BdrvChild
*bdrv_cow_child(BlockDriverState
*bs
)
7927 if (!bs
|| !bs
->drv
) {
7931 if (bs
->drv
->is_filter
) {
7939 assert(bs
->backing
->role
& BDRV_CHILD_COW
);
7944 * If @bs acts as a filter for exactly one of its children, return
7947 BdrvChild
*bdrv_filter_child(BlockDriverState
*bs
)
7952 if (!bs
|| !bs
->drv
) {
7956 if (!bs
->drv
->is_filter
) {
7960 /* Only one of @backing or @file may be used */
7961 assert(!(bs
->backing
&& bs
->file
));
7963 c
= bs
->backing
?: bs
->file
;
7968 assert(c
->role
& BDRV_CHILD_FILTERED
);
7973 * Return either the result of bdrv_cow_child() or bdrv_filter_child(),
7974 * whichever is non-NULL.
7976 * Return NULL if both are NULL.
7978 BdrvChild
*bdrv_filter_or_cow_child(BlockDriverState
*bs
)
7980 BdrvChild
*cow_child
= bdrv_cow_child(bs
);
7981 BdrvChild
*filter_child
= bdrv_filter_child(bs
);
7984 /* Filter nodes cannot have COW backing files */
7985 assert(!(cow_child
&& filter_child
));
7987 return cow_child
?: filter_child
;
7991 * Return the primary child of this node: For filters, that is the
7992 * filtered child. For other nodes, that is usually the child storing
7994 * (A generally more helpful description is that this is (usually) the
7995 * child that has the same filename as @bs.)
7997 * Drivers do not necessarily have a primary child; for example quorum
8000 BdrvChild
*bdrv_primary_child(BlockDriverState
*bs
)
8002 BdrvChild
*c
, *found
= NULL
;
8005 QLIST_FOREACH(c
, &bs
->children
, next
) {
8006 if (c
->role
& BDRV_CHILD_PRIMARY
) {
8015 static BlockDriverState
*bdrv_do_skip_filters(BlockDriverState
*bs
,
8016 bool stop_on_explicit_filter
)
8024 while (!(stop_on_explicit_filter
&& !bs
->implicit
)) {
8025 c
= bdrv_filter_child(bs
);
8028 * A filter that is embedded in a working block graph must
8029 * have a child. Assert this here so this function does
8030 * not return a filter node that is not expected by the
8033 assert(!bs
->drv
|| !bs
->drv
->is_filter
);
8039 * Note that this treats nodes with bs->drv == NULL as not being
8040 * filters (bs->drv == NULL should be replaced by something else
8042 * The advantage of this behavior is that this function will thus
8043 * always return a non-NULL value (given a non-NULL @bs).
8050 * Return the first BDS that has not been added implicitly or that
8051 * does not have a filtered child down the chain starting from @bs
8052 * (including @bs itself).
8054 BlockDriverState
*bdrv_skip_implicit_filters(BlockDriverState
*bs
)
8056 GLOBAL_STATE_CODE();
8057 return bdrv_do_skip_filters(bs
, true);
8061 * Return the first BDS that does not have a filtered child down the
8062 * chain starting from @bs (including @bs itself).
8064 BlockDriverState
*bdrv_skip_filters(BlockDriverState
*bs
)
8067 return bdrv_do_skip_filters(bs
, false);
8071 * For a backing chain, return the first non-filter backing image of
8072 * the first non-filter image.
8074 BlockDriverState
*bdrv_backing_chain_next(BlockDriverState
*bs
)
8077 return bdrv_skip_filters(bdrv_cow_bs(bdrv_skip_filters(bs
)));
8081 * Check whether [offset, offset + bytes) overlaps with the cached
8082 * block-status data region.
8084 * If so, and @pnum is not NULL, set *pnum to `bsc.data_end - offset`,
8085 * which is what bdrv_bsc_is_data()'s interface needs.
8086 * Otherwise, *pnum is not touched.
8088 static bool bdrv_bsc_range_overlaps_locked(BlockDriverState
*bs
,
8089 int64_t offset
, int64_t bytes
,
8092 BdrvBlockStatusCache
*bsc
= qatomic_rcu_read(&bs
->block_status_cache
);
8096 qatomic_read(&bsc
->valid
) &&
8097 ranges_overlap(offset
, bytes
, bsc
->data_start
,
8098 bsc
->data_end
- bsc
->data_start
);
8100 if (overlaps
&& pnum
) {
8101 *pnum
= bsc
->data_end
- offset
;
8108 * See block_int.h for this function's documentation.
8110 bool bdrv_bsc_is_data(BlockDriverState
*bs
, int64_t offset
, int64_t *pnum
)
8113 RCU_READ_LOCK_GUARD();
8114 return bdrv_bsc_range_overlaps_locked(bs
, offset
, 1, pnum
);
8118 * See block_int.h for this function's documentation.
8120 void bdrv_bsc_invalidate_range(BlockDriverState
*bs
,
8121 int64_t offset
, int64_t bytes
)
8124 RCU_READ_LOCK_GUARD();
8126 if (bdrv_bsc_range_overlaps_locked(bs
, offset
, bytes
, NULL
)) {
8127 qatomic_set(&bs
->block_status_cache
->valid
, false);
8132 * See block_int.h for this function's documentation.
8134 void bdrv_bsc_fill(BlockDriverState
*bs
, int64_t offset
, int64_t bytes
)
8136 BdrvBlockStatusCache
*new_bsc
= g_new(BdrvBlockStatusCache
, 1);
8137 BdrvBlockStatusCache
*old_bsc
;
8140 *new_bsc
= (BdrvBlockStatusCache
) {
8142 .data_start
= offset
,
8143 .data_end
= offset
+ bytes
,
8146 QEMU_LOCK_GUARD(&bs
->bsc_modify_lock
);
8148 old_bsc
= qatomic_rcu_read(&bs
->block_status_cache
);
8149 qatomic_rcu_set(&bs
->block_status_cache
, new_bsc
);
8151 g_free_rcu(old_bsc
, rcu
);