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_child_free(BdrvChild
*child
);
94 static void bdrv_replace_child_noperm(BdrvChild
**child
,
95 BlockDriverState
*new_bs
,
96 bool free_empty_child
);
97 static void bdrv_remove_file_or_backing_child(BlockDriverState
*bs
,
100 static void bdrv_remove_filter_or_cow_child(BlockDriverState
*bs
,
103 static int bdrv_reopen_prepare(BDRVReopenState
*reopen_state
,
104 BlockReopenQueue
*queue
,
105 Transaction
*change_child_tran
, Error
**errp
);
106 static void bdrv_reopen_commit(BDRVReopenState
*reopen_state
);
107 static void bdrv_reopen_abort(BDRVReopenState
*reopen_state
);
109 static bool bdrv_backing_overridden(BlockDriverState
*bs
);
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
;
533 ret
= cco
->drv
->bdrv_co_create_opts(cco
->drv
,
534 cco
->filename
, cco
->opts
, &local_err
);
535 error_propagate(&cco
->err
, local_err
);
539 int bdrv_create(BlockDriver
*drv
, const char* filename
,
540 QemuOpts
*opts
, Error
**errp
)
549 .filename
= g_strdup(filename
),
555 if (!drv
->bdrv_co_create_opts
) {
556 error_setg(errp
, "Driver '%s' does not support image creation", drv
->format_name
);
561 if (qemu_in_coroutine()) {
562 /* Fast-path if already in coroutine context */
563 bdrv_create_co_entry(&cco
);
565 co
= qemu_coroutine_create(bdrv_create_co_entry
, &cco
);
566 qemu_coroutine_enter(co
);
567 while (cco
.ret
== NOT_DONE
) {
568 aio_poll(qemu_get_aio_context(), true);
575 error_propagate(errp
, cco
.err
);
577 error_setg_errno(errp
, -ret
, "Could not create image");
582 g_free(cco
.filename
);
587 * Helper function for bdrv_create_file_fallback(): Resize @blk to at
588 * least the given @minimum_size.
590 * On success, return @blk's actual length.
591 * Otherwise, return -errno.
593 static int64_t create_file_fallback_truncate(BlockBackend
*blk
,
594 int64_t minimum_size
, Error
**errp
)
596 Error
*local_err
= NULL
;
602 ret
= blk_truncate(blk
, minimum_size
, false, PREALLOC_MODE_OFF
, 0,
604 if (ret
< 0 && ret
!= -ENOTSUP
) {
605 error_propagate(errp
, local_err
);
609 size
= blk_getlength(blk
);
611 error_free(local_err
);
612 error_setg_errno(errp
, -size
,
613 "Failed to inquire the new image file's length");
617 if (size
< minimum_size
) {
618 /* Need to grow the image, but we failed to do that */
619 error_propagate(errp
, local_err
);
623 error_free(local_err
);
630 * Helper function for bdrv_create_file_fallback(): Zero the first
631 * sector to remove any potentially pre-existing image header.
633 static int create_file_fallback_zero_first_sector(BlockBackend
*blk
,
634 int64_t current_size
,
637 int64_t bytes_to_clear
;
642 bytes_to_clear
= MIN(current_size
, BDRV_SECTOR_SIZE
);
643 if (bytes_to_clear
) {
644 ret
= blk_pwrite_zeroes(blk
, 0, bytes_to_clear
, BDRV_REQ_MAY_UNMAP
);
646 error_setg_errno(errp
, -ret
,
647 "Failed to clear the new image's first sector");
656 * Simple implementation of bdrv_co_create_opts for protocol drivers
657 * which only support creation via opening a file
658 * (usually existing raw storage device)
660 int coroutine_fn
bdrv_co_create_opts_simple(BlockDriver
*drv
,
661 const char *filename
,
669 PreallocMode prealloc
;
670 Error
*local_err
= NULL
;
675 size
= qemu_opt_get_size_del(opts
, BLOCK_OPT_SIZE
, 0);
676 buf
= qemu_opt_get_del(opts
, BLOCK_OPT_PREALLOC
);
677 prealloc
= qapi_enum_parse(&PreallocMode_lookup
, buf
,
678 PREALLOC_MODE_OFF
, &local_err
);
681 error_propagate(errp
, local_err
);
685 if (prealloc
!= PREALLOC_MODE_OFF
) {
686 error_setg(errp
, "Unsupported preallocation mode '%s'",
687 PreallocMode_str(prealloc
));
691 options
= qdict_new();
692 qdict_put_str(options
, "driver", drv
->format_name
);
694 blk
= blk_new_open(filename
, NULL
, options
,
695 BDRV_O_RDWR
| BDRV_O_RESIZE
, errp
);
697 error_prepend(errp
, "Protocol driver '%s' does not support image "
698 "creation, and opening the image failed: ",
703 size
= create_file_fallback_truncate(blk
, size
, errp
);
709 ret
= create_file_fallback_zero_first_sector(blk
, size
, errp
);
720 int bdrv_create_file(const char *filename
, QemuOpts
*opts
, Error
**errp
)
722 QemuOpts
*protocol_opts
;
729 drv
= bdrv_find_protocol(filename
, true, errp
);
734 if (!drv
->create_opts
) {
735 error_setg(errp
, "Driver '%s' does not support image creation",
741 * 'opts' contains a QemuOptsList with a combination of format and protocol
744 * The format properly removes its options, but the default values remain
745 * in 'opts->list'. So if the protocol has options with the same name
746 * (e.g. rbd has 'cluster_size' as qcow2), it will see the default values
747 * of the format, since for overlapping options, the format wins.
749 * To avoid this issue, lets convert QemuOpts to QDict, in this way we take
750 * only the set options, and then convert it back to QemuOpts, using the
751 * create_opts of the protocol. So the new QemuOpts, will contain only the
754 qdict
= qemu_opts_to_qdict(opts
, NULL
);
755 protocol_opts
= qemu_opts_from_qdict(drv
->create_opts
, qdict
, errp
);
756 if (protocol_opts
== NULL
) {
761 ret
= bdrv_create(drv
, filename
, protocol_opts
, errp
);
763 qemu_opts_del(protocol_opts
);
764 qobject_unref(qdict
);
768 int coroutine_fn
bdrv_co_delete_file(BlockDriverState
*bs
, Error
**errp
)
770 Error
*local_err
= NULL
;
777 error_setg(errp
, "Block node '%s' is not opened", bs
->filename
);
781 if (!bs
->drv
->bdrv_co_delete_file
) {
782 error_setg(errp
, "Driver '%s' does not support image deletion",
783 bs
->drv
->format_name
);
787 ret
= bs
->drv
->bdrv_co_delete_file(bs
, &local_err
);
789 error_propagate(errp
, local_err
);
795 void coroutine_fn
bdrv_co_delete_file_noerr(BlockDriverState
*bs
)
797 Error
*local_err
= NULL
;
805 ret
= bdrv_co_delete_file(bs
, &local_err
);
807 * ENOTSUP will happen if the block driver doesn't support
808 * the 'bdrv_co_delete_file' interface. This is a predictable
809 * scenario and shouldn't be reported back to the user.
811 if (ret
== -ENOTSUP
) {
812 error_free(local_err
);
813 } else if (ret
< 0) {
814 error_report_err(local_err
);
819 * Try to get @bs's logical and physical block size.
820 * On success, store them in @bsz struct and return 0.
821 * On failure return -errno.
822 * @bs must not be empty.
824 int bdrv_probe_blocksizes(BlockDriverState
*bs
, BlockSizes
*bsz
)
826 BlockDriver
*drv
= bs
->drv
;
827 BlockDriverState
*filtered
= bdrv_filter_bs(bs
);
830 if (drv
&& drv
->bdrv_probe_blocksizes
) {
831 return drv
->bdrv_probe_blocksizes(bs
, bsz
);
832 } else if (filtered
) {
833 return bdrv_probe_blocksizes(filtered
, bsz
);
840 * Try to get @bs's geometry (cyls, heads, sectors).
841 * On success, store them in @geo struct and return 0.
842 * On failure return -errno.
843 * @bs must not be empty.
845 int bdrv_probe_geometry(BlockDriverState
*bs
, HDGeometry
*geo
)
847 BlockDriver
*drv
= bs
->drv
;
848 BlockDriverState
*filtered
= bdrv_filter_bs(bs
);
851 if (drv
&& drv
->bdrv_probe_geometry
) {
852 return drv
->bdrv_probe_geometry(bs
, geo
);
853 } else if (filtered
) {
854 return bdrv_probe_geometry(filtered
, geo
);
861 * Create a uniquely-named empty temporary file.
862 * Return 0 upon success, otherwise a negative errno value.
864 int get_tmp_filename(char *filename
, int size
)
867 char temp_dir
[MAX_PATH
];
868 /* GetTempFileName requires that its output buffer (4th param)
869 have length MAX_PATH or greater. */
870 assert(size
>= MAX_PATH
);
871 return (GetTempPath(MAX_PATH
, temp_dir
)
872 && GetTempFileName(temp_dir
, "qem", 0, filename
)
873 ? 0 : -GetLastError());
877 tmpdir
= getenv("TMPDIR");
881 if (snprintf(filename
, size
, "%s/vl.XXXXXX", tmpdir
) >= size
) {
884 fd
= mkstemp(filename
);
888 if (close(fd
) != 0) {
897 * Detect host devices. By convention, /dev/cdrom[N] is always
898 * recognized as a host CDROM.
900 static BlockDriver
*find_hdev_driver(const char *filename
)
902 int score_max
= 0, score
;
903 BlockDriver
*drv
= NULL
, *d
;
906 QLIST_FOREACH(d
, &bdrv_drivers
, list
) {
907 if (d
->bdrv_probe_device
) {
908 score
= d
->bdrv_probe_device(filename
);
909 if (score
> score_max
) {
919 static BlockDriver
*bdrv_do_find_protocol(const char *protocol
)
924 QLIST_FOREACH(drv1
, &bdrv_drivers
, list
) {
925 if (drv1
->protocol_name
&& !strcmp(drv1
->protocol_name
, protocol
)) {
933 BlockDriver
*bdrv_find_protocol(const char *filename
,
934 bool allow_protocol_prefix
,
944 /* TODO Drivers without bdrv_file_open must be specified explicitly */
947 * XXX(hch): we really should not let host device detection
948 * override an explicit protocol specification, but moving this
949 * later breaks access to device names with colons in them.
950 * Thanks to the brain-dead persistent naming schemes on udev-
951 * based Linux systems those actually are quite common.
953 drv1
= find_hdev_driver(filename
);
958 if (!path_has_protocol(filename
) || !allow_protocol_prefix
) {
962 p
= strchr(filename
, ':');
965 if (len
> sizeof(protocol
) - 1)
966 len
= sizeof(protocol
) - 1;
967 memcpy(protocol
, filename
, len
);
968 protocol
[len
] = '\0';
970 drv1
= bdrv_do_find_protocol(protocol
);
975 for (i
= 0; i
< (int)ARRAY_SIZE(block_driver_modules
); ++i
) {
976 if (block_driver_modules
[i
].protocol_name
&&
977 !strcmp(block_driver_modules
[i
].protocol_name
, protocol
)) {
978 block_module_load_one(block_driver_modules
[i
].library_name
);
983 drv1
= bdrv_do_find_protocol(protocol
);
985 error_setg(errp
, "Unknown protocol '%s'", protocol
);
991 * Guess image format by probing its contents.
992 * This is not a good idea when your image is raw (CVE-2008-2004), but
993 * we do it anyway for backward compatibility.
995 * @buf contains the image's first @buf_size bytes.
996 * @buf_size is the buffer size in bytes (generally BLOCK_PROBE_BUF_SIZE,
997 * but can be smaller if the image file is smaller)
998 * @filename is its filename.
1000 * For all block drivers, call the bdrv_probe() method to get its
1002 * Return the first block driver with the highest probing score.
1004 BlockDriver
*bdrv_probe_all(const uint8_t *buf
, int buf_size
,
1005 const char *filename
)
1007 int score_max
= 0, score
;
1008 BlockDriver
*drv
= NULL
, *d
;
1011 QLIST_FOREACH(d
, &bdrv_drivers
, list
) {
1012 if (d
->bdrv_probe
) {
1013 score
= d
->bdrv_probe(buf
, buf_size
, filename
);
1014 if (score
> score_max
) {
1024 static int find_image_format(BlockBackend
*file
, const char *filename
,
1025 BlockDriver
**pdrv
, Error
**errp
)
1028 uint8_t buf
[BLOCK_PROBE_BUF_SIZE
];
1031 GLOBAL_STATE_CODE();
1033 /* Return the raw BlockDriver * to scsi-generic devices or empty drives */
1034 if (blk_is_sg(file
) || !blk_is_inserted(file
) || blk_getlength(file
) == 0) {
1039 ret
= blk_pread(file
, 0, buf
, sizeof(buf
));
1041 error_setg_errno(errp
, -ret
, "Could not read image for determining its "
1047 drv
= bdrv_probe_all(buf
, ret
, filename
);
1049 error_setg(errp
, "Could not determine image format: No compatible "
1058 * Set the current 'total_sectors' value
1059 * Return 0 on success, -errno on error.
1061 int refresh_total_sectors(BlockDriverState
*bs
, int64_t hint
)
1063 BlockDriver
*drv
= bs
->drv
;
1070 /* Do not attempt drv->bdrv_getlength() on scsi-generic devices */
1074 /* query actual device if possible, otherwise just trust the hint */
1075 if (drv
->bdrv_getlength
) {
1076 int64_t length
= drv
->bdrv_getlength(bs
);
1080 hint
= DIV_ROUND_UP(length
, BDRV_SECTOR_SIZE
);
1083 bs
->total_sectors
= hint
;
1085 if (bs
->total_sectors
* BDRV_SECTOR_SIZE
> BDRV_MAX_LENGTH
) {
1093 * Combines a QDict of new block driver @options with any missing options taken
1094 * from @old_options, so that leaving out an option defaults to its old value.
1096 static void bdrv_join_options(BlockDriverState
*bs
, QDict
*options
,
1099 if (bs
->drv
&& bs
->drv
->bdrv_join_options
) {
1100 bs
->drv
->bdrv_join_options(options
, old_options
);
1102 qdict_join(options
, old_options
, false);
1106 static BlockdevDetectZeroesOptions
bdrv_parse_detect_zeroes(QemuOpts
*opts
,
1110 Error
*local_err
= NULL
;
1111 char *value
= qemu_opt_get_del(opts
, "detect-zeroes");
1112 BlockdevDetectZeroesOptions detect_zeroes
=
1113 qapi_enum_parse(&BlockdevDetectZeroesOptions_lookup
, value
,
1114 BLOCKDEV_DETECT_ZEROES_OPTIONS_OFF
, &local_err
);
1115 GLOBAL_STATE_CODE();
1118 error_propagate(errp
, local_err
);
1119 return detect_zeroes
;
1122 if (detect_zeroes
== BLOCKDEV_DETECT_ZEROES_OPTIONS_UNMAP
&&
1123 !(open_flags
& BDRV_O_UNMAP
))
1125 error_setg(errp
, "setting detect-zeroes to unmap is not allowed "
1126 "without setting discard operation to unmap");
1129 return detect_zeroes
;
1133 * Set open flags for aio engine
1135 * Return 0 on success, -1 if the engine specified is invalid
1137 int bdrv_parse_aio(const char *mode
, int *flags
)
1139 if (!strcmp(mode
, "threads")) {
1140 /* do nothing, default */
1141 } else if (!strcmp(mode
, "native")) {
1142 *flags
|= BDRV_O_NATIVE_AIO
;
1143 #ifdef CONFIG_LINUX_IO_URING
1144 } else if (!strcmp(mode
, "io_uring")) {
1145 *flags
|= BDRV_O_IO_URING
;
1155 * Set open flags for a given discard mode
1157 * Return 0 on success, -1 if the discard mode was invalid.
1159 int bdrv_parse_discard_flags(const char *mode
, int *flags
)
1161 *flags
&= ~BDRV_O_UNMAP
;
1163 if (!strcmp(mode
, "off") || !strcmp(mode
, "ignore")) {
1165 } else if (!strcmp(mode
, "on") || !strcmp(mode
, "unmap")) {
1166 *flags
|= BDRV_O_UNMAP
;
1175 * Set open flags for a given cache mode
1177 * Return 0 on success, -1 if the cache mode was invalid.
1179 int bdrv_parse_cache_mode(const char *mode
, int *flags
, bool *writethrough
)
1181 *flags
&= ~BDRV_O_CACHE_MASK
;
1183 if (!strcmp(mode
, "off") || !strcmp(mode
, "none")) {
1184 *writethrough
= false;
1185 *flags
|= BDRV_O_NOCACHE
;
1186 } else if (!strcmp(mode
, "directsync")) {
1187 *writethrough
= true;
1188 *flags
|= BDRV_O_NOCACHE
;
1189 } else if (!strcmp(mode
, "writeback")) {
1190 *writethrough
= false;
1191 } else if (!strcmp(mode
, "unsafe")) {
1192 *writethrough
= false;
1193 *flags
|= BDRV_O_NO_FLUSH
;
1194 } else if (!strcmp(mode
, "writethrough")) {
1195 *writethrough
= true;
1203 static char *bdrv_child_get_parent_desc(BdrvChild
*c
)
1205 BlockDriverState
*parent
= c
->opaque
;
1206 return g_strdup_printf("node '%s'", bdrv_get_node_name(parent
));
1209 static void bdrv_child_cb_drained_begin(BdrvChild
*child
)
1211 BlockDriverState
*bs
= child
->opaque
;
1212 bdrv_do_drained_begin_quiesce(bs
, NULL
, false);
1215 static bool bdrv_child_cb_drained_poll(BdrvChild
*child
)
1217 BlockDriverState
*bs
= child
->opaque
;
1218 return bdrv_drain_poll(bs
, false, NULL
, false);
1221 static void bdrv_child_cb_drained_end(BdrvChild
*child
,
1222 int *drained_end_counter
)
1224 BlockDriverState
*bs
= child
->opaque
;
1225 bdrv_drained_end_no_poll(bs
, drained_end_counter
);
1228 static int bdrv_child_cb_inactivate(BdrvChild
*child
)
1230 BlockDriverState
*bs
= child
->opaque
;
1231 GLOBAL_STATE_CODE();
1232 assert(bs
->open_flags
& BDRV_O_INACTIVE
);
1236 static bool bdrv_child_cb_can_set_aio_ctx(BdrvChild
*child
, AioContext
*ctx
,
1237 GSList
**ignore
, Error
**errp
)
1239 BlockDriverState
*bs
= child
->opaque
;
1240 return bdrv_can_set_aio_context(bs
, ctx
, ignore
, errp
);
1243 static void bdrv_child_cb_set_aio_ctx(BdrvChild
*child
, AioContext
*ctx
,
1246 BlockDriverState
*bs
= child
->opaque
;
1247 return bdrv_set_aio_context_ignore(bs
, ctx
, ignore
);
1251 * Returns the options and flags that a temporary snapshot should get, based on
1252 * the originally requested flags (the originally requested image will have
1253 * flags like a backing file)
1255 static void bdrv_temp_snapshot_options(int *child_flags
, QDict
*child_options
,
1256 int parent_flags
, QDict
*parent_options
)
1258 GLOBAL_STATE_CODE();
1259 *child_flags
= (parent_flags
& ~BDRV_O_SNAPSHOT
) | BDRV_O_TEMPORARY
;
1261 /* For temporary files, unconditional cache=unsafe is fine */
1262 qdict_set_default_str(child_options
, BDRV_OPT_CACHE_DIRECT
, "off");
1263 qdict_set_default_str(child_options
, BDRV_OPT_CACHE_NO_FLUSH
, "on");
1265 /* Copy the read-only and discard options from the parent */
1266 qdict_copy_default(child_options
, parent_options
, BDRV_OPT_READ_ONLY
);
1267 qdict_copy_default(child_options
, parent_options
, BDRV_OPT_DISCARD
);
1269 /* aio=native doesn't work for cache.direct=off, so disable it for the
1270 * temporary snapshot */
1271 *child_flags
&= ~BDRV_O_NATIVE_AIO
;
1274 static void bdrv_backing_attach(BdrvChild
*c
)
1276 BlockDriverState
*parent
= c
->opaque
;
1277 BlockDriverState
*backing_hd
= c
->bs
;
1279 GLOBAL_STATE_CODE();
1280 assert(!parent
->backing_blocker
);
1281 error_setg(&parent
->backing_blocker
,
1282 "node is used as backing hd of '%s'",
1283 bdrv_get_device_or_node_name(parent
));
1285 bdrv_refresh_filename(backing_hd
);
1287 parent
->open_flags
&= ~BDRV_O_NO_BACKING
;
1289 bdrv_op_block_all(backing_hd
, parent
->backing_blocker
);
1290 /* Otherwise we won't be able to commit or stream */
1291 bdrv_op_unblock(backing_hd
, BLOCK_OP_TYPE_COMMIT_TARGET
,
1292 parent
->backing_blocker
);
1293 bdrv_op_unblock(backing_hd
, BLOCK_OP_TYPE_STREAM
,
1294 parent
->backing_blocker
);
1296 * We do backup in 3 ways:
1298 * The target bs is new opened, and the source is top BDS
1299 * 2. blockdev backup
1300 * Both the source and the target are top BDSes.
1301 * 3. internal backup(used for block replication)
1302 * Both the source and the target are backing file
1304 * In case 1 and 2, neither the source nor the target is the backing file.
1305 * In case 3, we will block the top BDS, so there is only one block job
1306 * for the top BDS and its backing chain.
1308 bdrv_op_unblock(backing_hd
, BLOCK_OP_TYPE_BACKUP_SOURCE
,
1309 parent
->backing_blocker
);
1310 bdrv_op_unblock(backing_hd
, BLOCK_OP_TYPE_BACKUP_TARGET
,
1311 parent
->backing_blocker
);
1314 static void bdrv_backing_detach(BdrvChild
*c
)
1316 BlockDriverState
*parent
= c
->opaque
;
1318 GLOBAL_STATE_CODE();
1319 assert(parent
->backing_blocker
);
1320 bdrv_op_unblock_all(c
->bs
, parent
->backing_blocker
);
1321 error_free(parent
->backing_blocker
);
1322 parent
->backing_blocker
= NULL
;
1325 static int bdrv_backing_update_filename(BdrvChild
*c
, BlockDriverState
*base
,
1326 const char *filename
, Error
**errp
)
1328 BlockDriverState
*parent
= c
->opaque
;
1329 bool read_only
= bdrv_is_read_only(parent
);
1331 GLOBAL_STATE_CODE();
1334 ret
= bdrv_reopen_set_read_only(parent
, false, errp
);
1340 ret
= bdrv_change_backing_file(parent
, filename
,
1341 base
->drv
? base
->drv
->format_name
: "",
1344 error_setg_errno(errp
, -ret
, "Could not update backing file link");
1348 bdrv_reopen_set_read_only(parent
, true, NULL
);
1355 * Returns the options and flags that a generic child of a BDS should
1356 * get, based on the given options and flags for the parent BDS.
1358 static void bdrv_inherited_options(BdrvChildRole role
, bool parent_is_format
,
1359 int *child_flags
, QDict
*child_options
,
1360 int parent_flags
, QDict
*parent_options
)
1362 int flags
= parent_flags
;
1363 GLOBAL_STATE_CODE();
1366 * First, decide whether to set, clear, or leave BDRV_O_PROTOCOL.
1367 * Generally, the question to answer is: Should this child be
1368 * format-probed by default?
1372 * Pure and non-filtered data children of non-format nodes should
1373 * be probed by default (even when the node itself has BDRV_O_PROTOCOL
1374 * set). This only affects a very limited set of drivers (namely
1375 * quorum and blkverify when this comment was written).
1376 * Force-clear BDRV_O_PROTOCOL then.
1378 if (!parent_is_format
&&
1379 (role
& BDRV_CHILD_DATA
) &&
1380 !(role
& (BDRV_CHILD_METADATA
| BDRV_CHILD_FILTERED
)))
1382 flags
&= ~BDRV_O_PROTOCOL
;
1386 * All children of format nodes (except for COW children) and all
1387 * metadata children in general should never be format-probed.
1388 * Force-set BDRV_O_PROTOCOL then.
1390 if ((parent_is_format
&& !(role
& BDRV_CHILD_COW
)) ||
1391 (role
& BDRV_CHILD_METADATA
))
1393 flags
|= BDRV_O_PROTOCOL
;
1397 * If the cache mode isn't explicitly set, inherit direct and no-flush from
1400 qdict_copy_default(child_options
, parent_options
, BDRV_OPT_CACHE_DIRECT
);
1401 qdict_copy_default(child_options
, parent_options
, BDRV_OPT_CACHE_NO_FLUSH
);
1402 qdict_copy_default(child_options
, parent_options
, BDRV_OPT_FORCE_SHARE
);
1404 if (role
& BDRV_CHILD_COW
) {
1405 /* backing files are opened read-only by default */
1406 qdict_set_default_str(child_options
, BDRV_OPT_READ_ONLY
, "on");
1407 qdict_set_default_str(child_options
, BDRV_OPT_AUTO_READ_ONLY
, "off");
1409 /* Inherit the read-only option from the parent if it's not set */
1410 qdict_copy_default(child_options
, parent_options
, BDRV_OPT_READ_ONLY
);
1411 qdict_copy_default(child_options
, parent_options
,
1412 BDRV_OPT_AUTO_READ_ONLY
);
1416 * bdrv_co_pdiscard() respects unmap policy for the parent, so we
1417 * can default to enable it on lower layers regardless of the
1420 qdict_set_default_str(child_options
, BDRV_OPT_DISCARD
, "unmap");
1422 /* Clear flags that only apply to the top layer */
1423 flags
&= ~(BDRV_O_SNAPSHOT
| BDRV_O_NO_BACKING
| BDRV_O_COPY_ON_READ
);
1425 if (role
& BDRV_CHILD_METADATA
) {
1426 flags
&= ~BDRV_O_NO_IO
;
1428 if (role
& BDRV_CHILD_COW
) {
1429 flags
&= ~BDRV_O_TEMPORARY
;
1432 *child_flags
= flags
;
1435 static void bdrv_child_cb_attach(BdrvChild
*child
)
1437 BlockDriverState
*bs
= child
->opaque
;
1439 assert_bdrv_graph_writable(bs
);
1440 QLIST_INSERT_HEAD(&bs
->children
, child
, next
);
1442 if (child
->role
& BDRV_CHILD_COW
) {
1443 bdrv_backing_attach(child
);
1446 bdrv_apply_subtree_drain(child
, bs
);
1449 static void bdrv_child_cb_detach(BdrvChild
*child
)
1451 BlockDriverState
*bs
= child
->opaque
;
1453 if (child
->role
& BDRV_CHILD_COW
) {
1454 bdrv_backing_detach(child
);
1457 bdrv_unapply_subtree_drain(child
, bs
);
1459 assert_bdrv_graph_writable(bs
);
1460 QLIST_REMOVE(child
, next
);
1463 static int bdrv_child_cb_update_filename(BdrvChild
*c
, BlockDriverState
*base
,
1464 const char *filename
, Error
**errp
)
1466 if (c
->role
& BDRV_CHILD_COW
) {
1467 return bdrv_backing_update_filename(c
, base
, filename
, errp
);
1472 AioContext
*child_of_bds_get_parent_aio_context(BdrvChild
*c
)
1474 BlockDriverState
*bs
= c
->opaque
;
1477 return bdrv_get_aio_context(bs
);
1480 const BdrvChildClass child_of_bds
= {
1481 .parent_is_bds
= true,
1482 .get_parent_desc
= bdrv_child_get_parent_desc
,
1483 .inherit_options
= bdrv_inherited_options
,
1484 .drained_begin
= bdrv_child_cb_drained_begin
,
1485 .drained_poll
= bdrv_child_cb_drained_poll
,
1486 .drained_end
= bdrv_child_cb_drained_end
,
1487 .attach
= bdrv_child_cb_attach
,
1488 .detach
= bdrv_child_cb_detach
,
1489 .inactivate
= bdrv_child_cb_inactivate
,
1490 .can_set_aio_ctx
= bdrv_child_cb_can_set_aio_ctx
,
1491 .set_aio_ctx
= bdrv_child_cb_set_aio_ctx
,
1492 .update_filename
= bdrv_child_cb_update_filename
,
1493 .get_parent_aio_context
= child_of_bds_get_parent_aio_context
,
1496 AioContext
*bdrv_child_get_parent_aio_context(BdrvChild
*c
)
1499 return c
->klass
->get_parent_aio_context(c
);
1502 static int bdrv_open_flags(BlockDriverState
*bs
, int flags
)
1504 int open_flags
= flags
;
1505 GLOBAL_STATE_CODE();
1508 * Clear flags that are internal to the block layer before opening the
1511 open_flags
&= ~(BDRV_O_SNAPSHOT
| BDRV_O_NO_BACKING
| BDRV_O_PROTOCOL
);
1516 static void update_flags_from_options(int *flags
, QemuOpts
*opts
)
1518 GLOBAL_STATE_CODE();
1520 *flags
&= ~(BDRV_O_CACHE_MASK
| BDRV_O_RDWR
| BDRV_O_AUTO_RDONLY
);
1522 if (qemu_opt_get_bool_del(opts
, BDRV_OPT_CACHE_NO_FLUSH
, false)) {
1523 *flags
|= BDRV_O_NO_FLUSH
;
1526 if (qemu_opt_get_bool_del(opts
, BDRV_OPT_CACHE_DIRECT
, false)) {
1527 *flags
|= BDRV_O_NOCACHE
;
1530 if (!qemu_opt_get_bool_del(opts
, BDRV_OPT_READ_ONLY
, false)) {
1531 *flags
|= BDRV_O_RDWR
;
1534 if (qemu_opt_get_bool_del(opts
, BDRV_OPT_AUTO_READ_ONLY
, false)) {
1535 *flags
|= BDRV_O_AUTO_RDONLY
;
1539 static void update_options_from_flags(QDict
*options
, int flags
)
1541 GLOBAL_STATE_CODE();
1542 if (!qdict_haskey(options
, BDRV_OPT_CACHE_DIRECT
)) {
1543 qdict_put_bool(options
, BDRV_OPT_CACHE_DIRECT
, flags
& BDRV_O_NOCACHE
);
1545 if (!qdict_haskey(options
, BDRV_OPT_CACHE_NO_FLUSH
)) {
1546 qdict_put_bool(options
, BDRV_OPT_CACHE_NO_FLUSH
,
1547 flags
& BDRV_O_NO_FLUSH
);
1549 if (!qdict_haskey(options
, BDRV_OPT_READ_ONLY
)) {
1550 qdict_put_bool(options
, BDRV_OPT_READ_ONLY
, !(flags
& BDRV_O_RDWR
));
1552 if (!qdict_haskey(options
, BDRV_OPT_AUTO_READ_ONLY
)) {
1553 qdict_put_bool(options
, BDRV_OPT_AUTO_READ_ONLY
,
1554 flags
& BDRV_O_AUTO_RDONLY
);
1558 static void bdrv_assign_node_name(BlockDriverState
*bs
,
1559 const char *node_name
,
1562 char *gen_node_name
= NULL
;
1563 GLOBAL_STATE_CODE();
1566 node_name
= gen_node_name
= id_generate(ID_BLOCK
);
1567 } else if (!id_wellformed(node_name
)) {
1569 * Check for empty string or invalid characters, but not if it is
1570 * generated (generated names use characters not available to the user)
1572 error_setg(errp
, "Invalid node-name: '%s'", node_name
);
1576 /* takes care of avoiding namespaces collisions */
1577 if (blk_by_name(node_name
)) {
1578 error_setg(errp
, "node-name=%s is conflicting with a device id",
1583 /* takes care of avoiding duplicates node names */
1584 if (bdrv_find_node(node_name
)) {
1585 error_setg(errp
, "Duplicate nodes with node-name='%s'", node_name
);
1589 /* Make sure that the node name isn't truncated */
1590 if (strlen(node_name
) >= sizeof(bs
->node_name
)) {
1591 error_setg(errp
, "Node name too long");
1595 /* copy node name into the bs and insert it into the graph list */
1596 pstrcpy(bs
->node_name
, sizeof(bs
->node_name
), node_name
);
1597 QTAILQ_INSERT_TAIL(&graph_bdrv_states
, bs
, node_list
);
1599 g_free(gen_node_name
);
1602 static int bdrv_open_driver(BlockDriverState
*bs
, BlockDriver
*drv
,
1603 const char *node_name
, QDict
*options
,
1604 int open_flags
, Error
**errp
)
1606 Error
*local_err
= NULL
;
1609 bdrv_assign_node_name(bs
, node_name
, &local_err
);
1611 error_propagate(errp
, local_err
);
1616 bs
->opaque
= g_malloc0(drv
->instance_size
);
1618 if (drv
->bdrv_file_open
) {
1619 assert(!drv
->bdrv_needs_filename
|| bs
->filename
[0]);
1620 ret
= drv
->bdrv_file_open(bs
, options
, open_flags
, &local_err
);
1621 } else if (drv
->bdrv_open
) {
1622 ret
= drv
->bdrv_open(bs
, options
, open_flags
, &local_err
);
1629 error_propagate(errp
, local_err
);
1630 } else if (bs
->filename
[0]) {
1631 error_setg_errno(errp
, -ret
, "Could not open '%s'", bs
->filename
);
1633 error_setg_errno(errp
, -ret
, "Could not open image");
1638 ret
= refresh_total_sectors(bs
, bs
->total_sectors
);
1640 error_setg_errno(errp
, -ret
, "Could not refresh total sector count");
1644 bdrv_refresh_limits(bs
, NULL
, &local_err
);
1646 error_propagate(errp
, local_err
);
1650 assert(bdrv_opt_mem_align(bs
) != 0);
1651 assert(bdrv_min_mem_align(bs
) != 0);
1652 assert(is_power_of_2(bs
->bl
.request_alignment
));
1654 for (i
= 0; i
< bs
->quiesce_counter
; i
++) {
1655 if (drv
->bdrv_co_drain_begin
) {
1656 drv
->bdrv_co_drain_begin(bs
);
1663 if (bs
->file
!= NULL
) {
1664 bdrv_unref_child(bs
, bs
->file
);
1673 * Create and open a block node.
1675 * @options is a QDict of options to pass to the block drivers, or NULL for an
1676 * empty set of options. The reference to the QDict belongs to the block layer
1677 * after the call (even on failure), so if the caller intends to reuse the
1678 * dictionary, it needs to use qobject_ref() before calling bdrv_open.
1680 BlockDriverState
*bdrv_new_open_driver_opts(BlockDriver
*drv
,
1681 const char *node_name
,
1682 QDict
*options
, int flags
,
1685 BlockDriverState
*bs
;
1688 GLOBAL_STATE_CODE();
1691 bs
->open_flags
= flags
;
1692 bs
->options
= options
?: qdict_new();
1693 bs
->explicit_options
= qdict_clone_shallow(bs
->options
);
1696 update_options_from_flags(bs
->options
, flags
);
1698 ret
= bdrv_open_driver(bs
, drv
, node_name
, bs
->options
, flags
, errp
);
1700 qobject_unref(bs
->explicit_options
);
1701 bs
->explicit_options
= NULL
;
1702 qobject_unref(bs
->options
);
1711 /* Create and open a block node. */
1712 BlockDriverState
*bdrv_new_open_driver(BlockDriver
*drv
, const char *node_name
,
1713 int flags
, Error
**errp
)
1715 GLOBAL_STATE_CODE();
1716 return bdrv_new_open_driver_opts(drv
, node_name
, NULL
, flags
, errp
);
1719 QemuOptsList bdrv_runtime_opts
= {
1720 .name
= "bdrv_common",
1721 .head
= QTAILQ_HEAD_INITIALIZER(bdrv_runtime_opts
.head
),
1724 .name
= "node-name",
1725 .type
= QEMU_OPT_STRING
,
1726 .help
= "Node name of the block device node",
1730 .type
= QEMU_OPT_STRING
,
1731 .help
= "Block driver to use for the node",
1734 .name
= BDRV_OPT_CACHE_DIRECT
,
1735 .type
= QEMU_OPT_BOOL
,
1736 .help
= "Bypass software writeback cache on the host",
1739 .name
= BDRV_OPT_CACHE_NO_FLUSH
,
1740 .type
= QEMU_OPT_BOOL
,
1741 .help
= "Ignore flush requests",
1744 .name
= BDRV_OPT_READ_ONLY
,
1745 .type
= QEMU_OPT_BOOL
,
1746 .help
= "Node is opened in read-only mode",
1749 .name
= BDRV_OPT_AUTO_READ_ONLY
,
1750 .type
= QEMU_OPT_BOOL
,
1751 .help
= "Node can become read-only if opening read-write fails",
1754 .name
= "detect-zeroes",
1755 .type
= QEMU_OPT_STRING
,
1756 .help
= "try to optimize zero writes (off, on, unmap)",
1759 .name
= BDRV_OPT_DISCARD
,
1760 .type
= QEMU_OPT_STRING
,
1761 .help
= "discard operation (ignore/off, unmap/on)",
1764 .name
= BDRV_OPT_FORCE_SHARE
,
1765 .type
= QEMU_OPT_BOOL
,
1766 .help
= "always accept other writers (default: off)",
1768 { /* end of list */ }
1772 QemuOptsList bdrv_create_opts_simple
= {
1773 .name
= "simple-create-opts",
1774 .head
= QTAILQ_HEAD_INITIALIZER(bdrv_create_opts_simple
.head
),
1777 .name
= BLOCK_OPT_SIZE
,
1778 .type
= QEMU_OPT_SIZE
,
1779 .help
= "Virtual disk size"
1782 .name
= BLOCK_OPT_PREALLOC
,
1783 .type
= QEMU_OPT_STRING
,
1784 .help
= "Preallocation mode (allowed values: off)"
1786 { /* end of list */ }
1791 * Common part for opening disk images and files
1793 * Removes all processed options from *options.
1795 static int bdrv_open_common(BlockDriverState
*bs
, BlockBackend
*file
,
1796 QDict
*options
, Error
**errp
)
1798 int ret
, open_flags
;
1799 const char *filename
;
1800 const char *driver_name
= NULL
;
1801 const char *node_name
= NULL
;
1802 const char *discard
;
1805 Error
*local_err
= NULL
;
1808 assert(bs
->file
== NULL
);
1809 assert(options
!= NULL
&& bs
->options
!= options
);
1810 GLOBAL_STATE_CODE();
1812 opts
= qemu_opts_create(&bdrv_runtime_opts
, NULL
, 0, &error_abort
);
1813 if (!qemu_opts_absorb_qdict(opts
, options
, errp
)) {
1818 update_flags_from_options(&bs
->open_flags
, opts
);
1820 driver_name
= qemu_opt_get(opts
, "driver");
1821 drv
= bdrv_find_format(driver_name
);
1822 assert(drv
!= NULL
);
1824 bs
->force_share
= qemu_opt_get_bool(opts
, BDRV_OPT_FORCE_SHARE
, false);
1826 if (bs
->force_share
&& (bs
->open_flags
& BDRV_O_RDWR
)) {
1828 BDRV_OPT_FORCE_SHARE
1829 "=on can only be used with read-only images");
1835 bdrv_refresh_filename(blk_bs(file
));
1836 filename
= blk_bs(file
)->filename
;
1839 * Caution: while qdict_get_try_str() is fine, getting
1840 * non-string types would require more care. When @options
1841 * come from -blockdev or blockdev_add, its members are typed
1842 * according to the QAPI schema, but when they come from
1843 * -drive, they're all QString.
1845 filename
= qdict_get_try_str(options
, "filename");
1848 if (drv
->bdrv_needs_filename
&& (!filename
|| !filename
[0])) {
1849 error_setg(errp
, "The '%s' block driver requires a file name",
1855 trace_bdrv_open_common(bs
, filename
?: "", bs
->open_flags
,
1858 ro
= bdrv_is_read_only(bs
);
1860 if (use_bdrv_whitelist
&& !bdrv_is_whitelisted(drv
, ro
)) {
1861 if (!ro
&& bdrv_is_whitelisted(drv
, true)) {
1862 ret
= bdrv_apply_auto_read_only(bs
, NULL
, NULL
);
1868 !ro
&& bdrv_is_whitelisted(drv
, true)
1869 ? "Driver '%s' can only be used for read-only devices"
1870 : "Driver '%s' is not whitelisted",
1876 /* bdrv_new() and bdrv_close() make it so */
1877 assert(qatomic_read(&bs
->copy_on_read
) == 0);
1879 if (bs
->open_flags
& BDRV_O_COPY_ON_READ
) {
1881 bdrv_enable_copy_on_read(bs
);
1883 error_setg(errp
, "Can't use copy-on-read on read-only device");
1889 discard
= qemu_opt_get(opts
, BDRV_OPT_DISCARD
);
1890 if (discard
!= NULL
) {
1891 if (bdrv_parse_discard_flags(discard
, &bs
->open_flags
) != 0) {
1892 error_setg(errp
, "Invalid discard option");
1899 bdrv_parse_detect_zeroes(opts
, bs
->open_flags
, &local_err
);
1901 error_propagate(errp
, local_err
);
1906 if (filename
!= NULL
) {
1907 pstrcpy(bs
->filename
, sizeof(bs
->filename
), filename
);
1909 bs
->filename
[0] = '\0';
1911 pstrcpy(bs
->exact_filename
, sizeof(bs
->exact_filename
), bs
->filename
);
1913 /* Open the image, either directly or using a protocol */
1914 open_flags
= bdrv_open_flags(bs
, bs
->open_flags
);
1915 node_name
= qemu_opt_get(opts
, "node-name");
1917 assert(!drv
->bdrv_file_open
|| file
== NULL
);
1918 ret
= bdrv_open_driver(bs
, drv
, node_name
, options
, open_flags
, errp
);
1923 qemu_opts_del(opts
);
1927 qemu_opts_del(opts
);
1931 static QDict
*parse_json_filename(const char *filename
, Error
**errp
)
1933 QObject
*options_obj
;
1936 GLOBAL_STATE_CODE();
1938 ret
= strstart(filename
, "json:", &filename
);
1941 options_obj
= qobject_from_json(filename
, errp
);
1943 error_prepend(errp
, "Could not parse the JSON options: ");
1947 options
= qobject_to(QDict
, options_obj
);
1949 qobject_unref(options_obj
);
1950 error_setg(errp
, "Invalid JSON object given");
1954 qdict_flatten(options
);
1959 static void parse_json_protocol(QDict
*options
, const char **pfilename
,
1962 QDict
*json_options
;
1963 Error
*local_err
= NULL
;
1964 GLOBAL_STATE_CODE();
1966 /* Parse json: pseudo-protocol */
1967 if (!*pfilename
|| !g_str_has_prefix(*pfilename
, "json:")) {
1971 json_options
= parse_json_filename(*pfilename
, &local_err
);
1973 error_propagate(errp
, local_err
);
1977 /* Options given in the filename have lower priority than options
1978 * specified directly */
1979 qdict_join(options
, json_options
, false);
1980 qobject_unref(json_options
);
1985 * Fills in default options for opening images and converts the legacy
1986 * filename/flags pair to option QDict entries.
1987 * The BDRV_O_PROTOCOL flag in *flags will be set or cleared accordingly if a
1988 * block driver has been specified explicitly.
1990 static int bdrv_fill_options(QDict
**options
, const char *filename
,
1991 int *flags
, Error
**errp
)
1993 const char *drvname
;
1994 bool protocol
= *flags
& BDRV_O_PROTOCOL
;
1995 bool parse_filename
= false;
1996 BlockDriver
*drv
= NULL
;
1997 Error
*local_err
= NULL
;
2000 * Caution: while qdict_get_try_str() is fine, getting non-string
2001 * types would require more care. When @options come from
2002 * -blockdev or blockdev_add, its members are typed according to
2003 * the QAPI schema, but when they come from -drive, they're all
2006 drvname
= qdict_get_try_str(*options
, "driver");
2008 drv
= bdrv_find_format(drvname
);
2010 error_setg(errp
, "Unknown driver '%s'", drvname
);
2013 /* If the user has explicitly specified the driver, this choice should
2014 * override the BDRV_O_PROTOCOL flag */
2015 protocol
= drv
->bdrv_file_open
;
2019 *flags
|= BDRV_O_PROTOCOL
;
2021 *flags
&= ~BDRV_O_PROTOCOL
;
2024 /* Translate cache options from flags into options */
2025 update_options_from_flags(*options
, *flags
);
2027 /* Fetch the file name from the options QDict if necessary */
2028 if (protocol
&& filename
) {
2029 if (!qdict_haskey(*options
, "filename")) {
2030 qdict_put_str(*options
, "filename", filename
);
2031 parse_filename
= true;
2033 error_setg(errp
, "Can't specify 'file' and 'filename' options at "
2039 /* Find the right block driver */
2040 /* See cautionary note on accessing @options above */
2041 filename
= qdict_get_try_str(*options
, "filename");
2043 if (!drvname
&& protocol
) {
2045 drv
= bdrv_find_protocol(filename
, parse_filename
, errp
);
2050 drvname
= drv
->format_name
;
2051 qdict_put_str(*options
, "driver", drvname
);
2053 error_setg(errp
, "Must specify either driver or file");
2058 assert(drv
|| !protocol
);
2060 /* Driver-specific filename parsing */
2061 if (drv
&& drv
->bdrv_parse_filename
&& parse_filename
) {
2062 drv
->bdrv_parse_filename(filename
, *options
, &local_err
);
2064 error_propagate(errp
, local_err
);
2068 if (!drv
->bdrv_needs_filename
) {
2069 qdict_del(*options
, "filename");
2076 typedef struct BlockReopenQueueEntry
{
2079 BDRVReopenState state
;
2080 QTAILQ_ENTRY(BlockReopenQueueEntry
) entry
;
2081 } BlockReopenQueueEntry
;
2084 * Return the flags that @bs will have after the reopens in @q have
2085 * successfully completed. If @q is NULL (or @bs is not contained in @q),
2086 * return the current flags.
2088 static int bdrv_reopen_get_flags(BlockReopenQueue
*q
, BlockDriverState
*bs
)
2090 BlockReopenQueueEntry
*entry
;
2093 QTAILQ_FOREACH(entry
, q
, entry
) {
2094 if (entry
->state
.bs
== bs
) {
2095 return entry
->state
.flags
;
2100 return bs
->open_flags
;
2103 /* Returns whether the image file can be written to after the reopen queue @q
2104 * has been successfully applied, or right now if @q is NULL. */
2105 static bool bdrv_is_writable_after_reopen(BlockDriverState
*bs
,
2106 BlockReopenQueue
*q
)
2108 int flags
= bdrv_reopen_get_flags(q
, bs
);
2110 return (flags
& (BDRV_O_RDWR
| BDRV_O_INACTIVE
)) == BDRV_O_RDWR
;
2114 * Return whether the BDS can be written to. This is not necessarily
2115 * the same as !bdrv_is_read_only(bs), as inactivated images may not
2116 * be written to but do not count as read-only images.
2118 bool bdrv_is_writable(BlockDriverState
*bs
)
2121 return bdrv_is_writable_after_reopen(bs
, NULL
);
2124 static char *bdrv_child_user_desc(BdrvChild
*c
)
2126 return c
->klass
->get_parent_desc(c
);
2130 * Check that @a allows everything that @b needs. @a and @b must reference same
2133 static bool bdrv_a_allow_b(BdrvChild
*a
, BdrvChild
*b
, Error
**errp
)
2135 const char *child_bs_name
;
2136 g_autofree
char *a_user
= NULL
;
2137 g_autofree
char *b_user
= NULL
;
2138 g_autofree
char *perms
= NULL
;
2141 assert(a
->bs
== b
->bs
);
2142 GLOBAL_STATE_CODE();
2144 if ((b
->perm
& a
->shared_perm
) == b
->perm
) {
2148 child_bs_name
= bdrv_get_node_name(b
->bs
);
2149 a_user
= bdrv_child_user_desc(a
);
2150 b_user
= bdrv_child_user_desc(b
);
2151 perms
= bdrv_perm_names(b
->perm
& ~a
->shared_perm
);
2153 error_setg(errp
, "Permission conflict on node '%s': permissions '%s' are "
2154 "both required by %s (uses node '%s' as '%s' child) and "
2155 "unshared by %s (uses node '%s' as '%s' child).",
2156 child_bs_name
, perms
,
2157 b_user
, child_bs_name
, b
->name
,
2158 a_user
, child_bs_name
, a
->name
);
2163 static bool bdrv_parent_perms_conflict(BlockDriverState
*bs
, Error
**errp
)
2166 GLOBAL_STATE_CODE();
2169 * During the loop we'll look at each pair twice. That's correct because
2170 * bdrv_a_allow_b() is asymmetric and we should check each pair in both
2173 QLIST_FOREACH(a
, &bs
->parents
, next_parent
) {
2174 QLIST_FOREACH(b
, &bs
->parents
, next_parent
) {
2179 if (!bdrv_a_allow_b(a
, b
, errp
)) {
2188 static void bdrv_child_perm(BlockDriverState
*bs
, BlockDriverState
*child_bs
,
2189 BdrvChild
*c
, BdrvChildRole role
,
2190 BlockReopenQueue
*reopen_queue
,
2191 uint64_t parent_perm
, uint64_t parent_shared
,
2192 uint64_t *nperm
, uint64_t *nshared
)
2194 assert(bs
->drv
&& bs
->drv
->bdrv_child_perm
);
2195 bs
->drv
->bdrv_child_perm(bs
, c
, role
, reopen_queue
,
2196 parent_perm
, parent_shared
,
2198 /* TODO Take force_share from reopen_queue */
2199 if (child_bs
&& child_bs
->force_share
) {
2200 *nshared
= BLK_PERM_ALL
;
2205 * Adds the whole subtree of @bs (including @bs itself) to the @list (except for
2206 * nodes that are already in the @list, of course) so that final list is
2207 * topologically sorted. Return the result (GSList @list object is updated, so
2208 * don't use old reference after function call).
2210 * On function start @list must be already topologically sorted and for any node
2211 * in the @list the whole subtree of the node must be in the @list as well. The
2212 * simplest way to satisfy this criteria: use only result of
2213 * bdrv_topological_dfs() or NULL as @list parameter.
2215 static GSList
*bdrv_topological_dfs(GSList
*list
, GHashTable
*found
,
2216 BlockDriverState
*bs
)
2219 g_autoptr(GHashTable
) local_found
= NULL
;
2221 GLOBAL_STATE_CODE();
2225 found
= local_found
= g_hash_table_new(NULL
, NULL
);
2228 if (g_hash_table_contains(found
, bs
)) {
2231 g_hash_table_add(found
, bs
);
2233 QLIST_FOREACH(child
, &bs
->children
, next
) {
2234 list
= bdrv_topological_dfs(list
, found
, child
->bs
);
2237 return g_slist_prepend(list
, bs
);
2240 typedef struct BdrvChildSetPermState
{
2243 uint64_t old_shared_perm
;
2244 } BdrvChildSetPermState
;
2246 static void bdrv_child_set_perm_abort(void *opaque
)
2248 BdrvChildSetPermState
*s
= opaque
;
2250 GLOBAL_STATE_CODE();
2252 s
->child
->perm
= s
->old_perm
;
2253 s
->child
->shared_perm
= s
->old_shared_perm
;
2256 static TransactionActionDrv bdrv_child_set_pem_drv
= {
2257 .abort
= bdrv_child_set_perm_abort
,
2261 static void bdrv_child_set_perm(BdrvChild
*c
, uint64_t perm
,
2262 uint64_t shared
, Transaction
*tran
)
2264 BdrvChildSetPermState
*s
= g_new(BdrvChildSetPermState
, 1);
2265 GLOBAL_STATE_CODE();
2267 *s
= (BdrvChildSetPermState
) {
2269 .old_perm
= c
->perm
,
2270 .old_shared_perm
= c
->shared_perm
,
2274 c
->shared_perm
= shared
;
2276 tran_add(tran
, &bdrv_child_set_pem_drv
, s
);
2279 static void bdrv_drv_set_perm_commit(void *opaque
)
2281 BlockDriverState
*bs
= opaque
;
2282 uint64_t cumulative_perms
, cumulative_shared_perms
;
2284 if (bs
->drv
->bdrv_set_perm
) {
2285 bdrv_get_cumulative_perm(bs
, &cumulative_perms
,
2286 &cumulative_shared_perms
);
2287 bs
->drv
->bdrv_set_perm(bs
, cumulative_perms
, cumulative_shared_perms
);
2291 static void bdrv_drv_set_perm_abort(void *opaque
)
2293 BlockDriverState
*bs
= opaque
;
2295 if (bs
->drv
->bdrv_abort_perm_update
) {
2296 bs
->drv
->bdrv_abort_perm_update(bs
);
2300 TransactionActionDrv bdrv_drv_set_perm_drv
= {
2301 .abort
= bdrv_drv_set_perm_abort
,
2302 .commit
= bdrv_drv_set_perm_commit
,
2305 static int bdrv_drv_set_perm(BlockDriverState
*bs
, uint64_t perm
,
2306 uint64_t shared_perm
, Transaction
*tran
,
2313 if (bs
->drv
->bdrv_check_perm
) {
2314 int ret
= bs
->drv
->bdrv_check_perm(bs
, perm
, shared_perm
, errp
);
2321 tran_add(tran
, &bdrv_drv_set_perm_drv
, bs
);
2327 typedef struct BdrvReplaceChildState
{
2330 BlockDriverState
*old_bs
;
2331 bool free_empty_child
;
2332 } BdrvReplaceChildState
;
2334 static void bdrv_replace_child_commit(void *opaque
)
2336 BdrvReplaceChildState
*s
= opaque
;
2337 GLOBAL_STATE_CODE();
2339 if (s
->free_empty_child
&& !s
->child
->bs
) {
2340 bdrv_child_free(s
->child
);
2342 bdrv_unref(s
->old_bs
);
2345 static void bdrv_replace_child_abort(void *opaque
)
2347 BdrvReplaceChildState
*s
= opaque
;
2348 BlockDriverState
*new_bs
= s
->child
->bs
;
2350 GLOBAL_STATE_CODE();
2352 * old_bs reference is transparently moved from @s to s->child.
2354 * Pass &s->child here instead of s->childp, because:
2355 * (1) s->old_bs must be non-NULL, so bdrv_replace_child_noperm() will not
2356 * modify the BdrvChild * pointer we indirectly pass to it, i.e. it
2357 * will not modify s->child. From that perspective, it does not matter
2358 * whether we pass s->childp or &s->child.
2359 * (2) If new_bs is not NULL, s->childp will be NULL. We then cannot use
2361 * (3) If new_bs is NULL, *s->childp will have been NULLed by
2362 * bdrv_replace_child_tran()'s bdrv_replace_child_noperm() call, and we
2363 * must not pass a NULL *s->childp here.
2365 * So whether new_bs was NULL or not, we cannot pass s->childp here; and in
2366 * any case, there is no reason to pass it anyway.
2368 bdrv_replace_child_noperm(&s
->child
, s
->old_bs
, true);
2370 * The child was pre-existing, so s->old_bs must be non-NULL, and
2371 * s->child thus must not have been freed
2373 assert(s
->child
!= NULL
);
2375 /* As described above, *s->childp was cleared, so restore it */
2376 assert(s
->childp
!= NULL
);
2377 *s
->childp
= s
->child
;
2382 static TransactionActionDrv bdrv_replace_child_drv
= {
2383 .commit
= bdrv_replace_child_commit
,
2384 .abort
= bdrv_replace_child_abort
,
2389 * bdrv_replace_child_tran
2391 * Note: real unref of old_bs is done only on commit.
2393 * The function doesn't update permissions, caller is responsible for this.
2395 * (*childp)->bs must not be NULL.
2397 * Note that if new_bs == NULL, @childp is stored in a state object attached
2398 * to @tran, so that the old child can be reinstated in the abort handler.
2399 * Therefore, if @new_bs can be NULL, @childp must stay valid until the
2400 * transaction is committed or aborted.
2402 * If @free_empty_child is true and @new_bs is NULL, the BdrvChild is
2403 * freed (on commit). @free_empty_child should only be false if the
2404 * caller will free the BDrvChild themselves (which may be important
2405 * if this is in turn called in another transactional context).
2407 static void bdrv_replace_child_tran(BdrvChild
**childp
,
2408 BlockDriverState
*new_bs
,
2410 bool free_empty_child
)
2412 BdrvReplaceChildState
*s
= g_new(BdrvReplaceChildState
, 1);
2413 *s
= (BdrvReplaceChildState
) {
2415 .childp
= new_bs
== NULL
? childp
: NULL
,
2416 .old_bs
= (*childp
)->bs
,
2417 .free_empty_child
= free_empty_child
,
2419 tran_add(tran
, &bdrv_replace_child_drv
, s
);
2421 /* The abort handler relies on this */
2422 assert(s
->old_bs
!= NULL
);
2428 * Pass free_empty_child=false, we will free the child (if
2429 * necessary) in bdrv_replace_child_commit() (if our
2430 * @free_empty_child parameter was true).
2432 bdrv_replace_child_noperm(childp
, new_bs
, false);
2433 /* old_bs reference is transparently moved from *childp to @s */
2437 * Refresh permissions in @bs subtree. The function is intended to be called
2438 * after some graph modification that was done without permission update.
2440 static int bdrv_node_refresh_perm(BlockDriverState
*bs
, BlockReopenQueue
*q
,
2441 Transaction
*tran
, Error
**errp
)
2443 BlockDriver
*drv
= bs
->drv
;
2446 uint64_t cumulative_perms
, cumulative_shared_perms
;
2447 GLOBAL_STATE_CODE();
2449 bdrv_get_cumulative_perm(bs
, &cumulative_perms
, &cumulative_shared_perms
);
2451 /* Write permissions never work with read-only images */
2452 if ((cumulative_perms
& (BLK_PERM_WRITE
| BLK_PERM_WRITE_UNCHANGED
)) &&
2453 !bdrv_is_writable_after_reopen(bs
, q
))
2455 if (!bdrv_is_writable_after_reopen(bs
, NULL
)) {
2456 error_setg(errp
, "Block node is read-only");
2458 error_setg(errp
, "Read-only block node '%s' cannot support "
2459 "read-write users", bdrv_get_node_name(bs
));
2466 * Unaligned requests will automatically be aligned to bl.request_alignment
2467 * and without RESIZE we can't extend requests to write to space beyond the
2468 * end of the image, so it's required that the image size is aligned.
2470 if ((cumulative_perms
& (BLK_PERM_WRITE
| BLK_PERM_WRITE_UNCHANGED
)) &&
2471 !(cumulative_perms
& BLK_PERM_RESIZE
))
2473 if ((bs
->total_sectors
* BDRV_SECTOR_SIZE
) % bs
->bl
.request_alignment
) {
2474 error_setg(errp
, "Cannot get 'write' permission without 'resize': "
2475 "Image size is not a multiple of request "
2481 /* Check this node */
2486 ret
= bdrv_drv_set_perm(bs
, cumulative_perms
, cumulative_shared_perms
, tran
,
2492 /* Drivers that never have children can omit .bdrv_child_perm() */
2493 if (!drv
->bdrv_child_perm
) {
2494 assert(QLIST_EMPTY(&bs
->children
));
2498 /* Check all children */
2499 QLIST_FOREACH(c
, &bs
->children
, next
) {
2500 uint64_t cur_perm
, cur_shared
;
2502 bdrv_child_perm(bs
, c
->bs
, c
, c
->role
, q
,
2503 cumulative_perms
, cumulative_shared_perms
,
2504 &cur_perm
, &cur_shared
);
2505 bdrv_child_set_perm(c
, cur_perm
, cur_shared
, tran
);
2511 static int bdrv_list_refresh_perms(GSList
*list
, BlockReopenQueue
*q
,
2512 Transaction
*tran
, Error
**errp
)
2515 BlockDriverState
*bs
;
2516 GLOBAL_STATE_CODE();
2518 for ( ; list
; list
= list
->next
) {
2521 if (bdrv_parent_perms_conflict(bs
, errp
)) {
2525 ret
= bdrv_node_refresh_perm(bs
, q
, tran
, errp
);
2534 void bdrv_get_cumulative_perm(BlockDriverState
*bs
, uint64_t *perm
,
2535 uint64_t *shared_perm
)
2538 uint64_t cumulative_perms
= 0;
2539 uint64_t cumulative_shared_perms
= BLK_PERM_ALL
;
2541 GLOBAL_STATE_CODE();
2543 QLIST_FOREACH(c
, &bs
->parents
, next_parent
) {
2544 cumulative_perms
|= c
->perm
;
2545 cumulative_shared_perms
&= c
->shared_perm
;
2548 *perm
= cumulative_perms
;
2549 *shared_perm
= cumulative_shared_perms
;
2552 char *bdrv_perm_names(uint64_t perm
)
2558 { BLK_PERM_CONSISTENT_READ
, "consistent read" },
2559 { BLK_PERM_WRITE
, "write" },
2560 { BLK_PERM_WRITE_UNCHANGED
, "write unchanged" },
2561 { BLK_PERM_RESIZE
, "resize" },
2565 GString
*result
= g_string_sized_new(30);
2566 struct perm_name
*p
;
2568 for (p
= permissions
; p
->name
; p
++) {
2569 if (perm
& p
->perm
) {
2570 if (result
->len
> 0) {
2571 g_string_append(result
, ", ");
2573 g_string_append(result
, p
->name
);
2577 return g_string_free(result
, FALSE
);
2581 static int bdrv_refresh_perms(BlockDriverState
*bs
, Error
**errp
)
2584 Transaction
*tran
= tran_new();
2585 g_autoptr(GSList
) list
= bdrv_topological_dfs(NULL
, NULL
, bs
);
2586 GLOBAL_STATE_CODE();
2588 ret
= bdrv_list_refresh_perms(list
, NULL
, tran
, errp
);
2589 tran_finalize(tran
, ret
);
2594 int bdrv_child_try_set_perm(BdrvChild
*c
, uint64_t perm
, uint64_t shared
,
2597 Error
*local_err
= NULL
;
2598 Transaction
*tran
= tran_new();
2601 GLOBAL_STATE_CODE();
2603 bdrv_child_set_perm(c
, perm
, shared
, tran
);
2605 ret
= bdrv_refresh_perms(c
->bs
, &local_err
);
2607 tran_finalize(tran
, ret
);
2610 if ((perm
& ~c
->perm
) || (c
->shared_perm
& ~shared
)) {
2611 /* tighten permissions */
2612 error_propagate(errp
, local_err
);
2615 * Our caller may intend to only loosen restrictions and
2616 * does not expect this function to fail. Errors are not
2617 * fatal in such a case, so we can just hide them from our
2620 error_free(local_err
);
2628 int bdrv_child_refresh_perms(BlockDriverState
*bs
, BdrvChild
*c
, Error
**errp
)
2630 uint64_t parent_perms
, parent_shared
;
2631 uint64_t perms
, shared
;
2633 GLOBAL_STATE_CODE();
2635 bdrv_get_cumulative_perm(bs
, &parent_perms
, &parent_shared
);
2636 bdrv_child_perm(bs
, c
->bs
, c
, c
->role
, NULL
,
2637 parent_perms
, parent_shared
, &perms
, &shared
);
2639 return bdrv_child_try_set_perm(c
, perms
, shared
, errp
);
2643 * Default implementation for .bdrv_child_perm() for block filters:
2644 * Forward CONSISTENT_READ, WRITE, WRITE_UNCHANGED, and RESIZE to the
2647 static void bdrv_filter_default_perms(BlockDriverState
*bs
, BdrvChild
*c
,
2649 BlockReopenQueue
*reopen_queue
,
2650 uint64_t perm
, uint64_t shared
,
2651 uint64_t *nperm
, uint64_t *nshared
)
2653 GLOBAL_STATE_CODE();
2654 *nperm
= perm
& DEFAULT_PERM_PASSTHROUGH
;
2655 *nshared
= (shared
& DEFAULT_PERM_PASSTHROUGH
) | DEFAULT_PERM_UNCHANGED
;
2658 static void bdrv_default_perms_for_cow(BlockDriverState
*bs
, BdrvChild
*c
,
2660 BlockReopenQueue
*reopen_queue
,
2661 uint64_t perm
, uint64_t shared
,
2662 uint64_t *nperm
, uint64_t *nshared
)
2664 assert(role
& BDRV_CHILD_COW
);
2665 GLOBAL_STATE_CODE();
2668 * We want consistent read from backing files if the parent needs it.
2669 * No other operations are performed on backing files.
2671 perm
&= BLK_PERM_CONSISTENT_READ
;
2674 * If the parent can deal with changing data, we're okay with a
2675 * writable and resizable backing file.
2676 * TODO Require !(perm & BLK_PERM_CONSISTENT_READ), too?
2678 if (shared
& BLK_PERM_WRITE
) {
2679 shared
= BLK_PERM_WRITE
| BLK_PERM_RESIZE
;
2684 shared
|= BLK_PERM_CONSISTENT_READ
| BLK_PERM_WRITE_UNCHANGED
;
2686 if (bs
->open_flags
& BDRV_O_INACTIVE
) {
2687 shared
|= BLK_PERM_WRITE
| BLK_PERM_RESIZE
;
2694 static void bdrv_default_perms_for_storage(BlockDriverState
*bs
, BdrvChild
*c
,
2696 BlockReopenQueue
*reopen_queue
,
2697 uint64_t perm
, uint64_t shared
,
2698 uint64_t *nperm
, uint64_t *nshared
)
2702 GLOBAL_STATE_CODE();
2703 assert(role
& (BDRV_CHILD_METADATA
| BDRV_CHILD_DATA
));
2705 flags
= bdrv_reopen_get_flags(reopen_queue
, bs
);
2708 * Apart from the modifications below, the same permissions are
2709 * forwarded and left alone as for filters
2711 bdrv_filter_default_perms(bs
, c
, role
, reopen_queue
,
2712 perm
, shared
, &perm
, &shared
);
2714 if (role
& BDRV_CHILD_METADATA
) {
2715 /* Format drivers may touch metadata even if the guest doesn't write */
2716 if (bdrv_is_writable_after_reopen(bs
, reopen_queue
)) {
2717 perm
|= BLK_PERM_WRITE
| BLK_PERM_RESIZE
;
2721 * bs->file always needs to be consistent because of the
2722 * metadata. We can never allow other users to resize or write
2725 if (!(flags
& BDRV_O_NO_IO
)) {
2726 perm
|= BLK_PERM_CONSISTENT_READ
;
2728 shared
&= ~(BLK_PERM_WRITE
| BLK_PERM_RESIZE
);
2731 if (role
& BDRV_CHILD_DATA
) {
2733 * Technically, everything in this block is a subset of the
2734 * BDRV_CHILD_METADATA path taken above, and so this could
2735 * be an "else if" branch. However, that is not obvious, and
2736 * this function is not performance critical, therefore we let
2737 * this be an independent "if".
2741 * We cannot allow other users to resize the file because the
2742 * format driver might have some assumptions about the size
2743 * (e.g. because it is stored in metadata, or because the file
2744 * is split into fixed-size data files).
2746 shared
&= ~BLK_PERM_RESIZE
;
2749 * WRITE_UNCHANGED often cannot be performed as such on the
2750 * data file. For example, the qcow2 driver may still need to
2751 * write copied clusters on copy-on-read.
2753 if (perm
& BLK_PERM_WRITE_UNCHANGED
) {
2754 perm
|= BLK_PERM_WRITE
;
2758 * If the data file is written to, the format driver may
2759 * expect to be able to resize it by writing beyond the EOF.
2761 if (perm
& BLK_PERM_WRITE
) {
2762 perm
|= BLK_PERM_RESIZE
;
2766 if (bs
->open_flags
& BDRV_O_INACTIVE
) {
2767 shared
|= BLK_PERM_WRITE
| BLK_PERM_RESIZE
;
2774 void bdrv_default_perms(BlockDriverState
*bs
, BdrvChild
*c
,
2775 BdrvChildRole role
, BlockReopenQueue
*reopen_queue
,
2776 uint64_t perm
, uint64_t shared
,
2777 uint64_t *nperm
, uint64_t *nshared
)
2779 GLOBAL_STATE_CODE();
2780 if (role
& BDRV_CHILD_FILTERED
) {
2781 assert(!(role
& (BDRV_CHILD_DATA
| BDRV_CHILD_METADATA
|
2783 bdrv_filter_default_perms(bs
, c
, role
, reopen_queue
,
2784 perm
, shared
, nperm
, nshared
);
2785 } else if (role
& BDRV_CHILD_COW
) {
2786 assert(!(role
& (BDRV_CHILD_DATA
| BDRV_CHILD_METADATA
)));
2787 bdrv_default_perms_for_cow(bs
, c
, role
, reopen_queue
,
2788 perm
, shared
, nperm
, nshared
);
2789 } else if (role
& (BDRV_CHILD_METADATA
| BDRV_CHILD_DATA
)) {
2790 bdrv_default_perms_for_storage(bs
, c
, role
, reopen_queue
,
2791 perm
, shared
, nperm
, nshared
);
2793 g_assert_not_reached();
2797 uint64_t bdrv_qapi_perm_to_blk_perm(BlockPermission qapi_perm
)
2799 static const uint64_t permissions
[] = {
2800 [BLOCK_PERMISSION_CONSISTENT_READ
] = BLK_PERM_CONSISTENT_READ
,
2801 [BLOCK_PERMISSION_WRITE
] = BLK_PERM_WRITE
,
2802 [BLOCK_PERMISSION_WRITE_UNCHANGED
] = BLK_PERM_WRITE_UNCHANGED
,
2803 [BLOCK_PERMISSION_RESIZE
] = BLK_PERM_RESIZE
,
2806 QEMU_BUILD_BUG_ON(ARRAY_SIZE(permissions
) != BLOCK_PERMISSION__MAX
);
2807 QEMU_BUILD_BUG_ON(1UL << ARRAY_SIZE(permissions
) != BLK_PERM_ALL
+ 1);
2809 assert(qapi_perm
< BLOCK_PERMISSION__MAX
);
2811 return permissions
[qapi_perm
];
2815 * Replace (*childp)->bs by @new_bs.
2817 * If @new_bs is NULL, *childp will be set to NULL, too: BDS parents
2818 * generally cannot handle a BdrvChild with .bs == NULL, so clearing
2819 * BdrvChild.bs should generally immediately be followed by the
2820 * BdrvChild pointer being cleared as well.
2822 * If @free_empty_child is true and @new_bs is NULL, the BdrvChild is
2823 * freed. @free_empty_child should only be false if the caller will
2824 * free the BdrvChild themselves (this may be important in a
2825 * transactional context, where it may only be freed on commit).
2827 static void bdrv_replace_child_noperm(BdrvChild
**childp
,
2828 BlockDriverState
*new_bs
,
2829 bool free_empty_child
)
2831 BdrvChild
*child
= *childp
;
2832 BlockDriverState
*old_bs
= child
->bs
;
2833 int new_bs_quiesce_counter
;
2836 assert(!child
->frozen
);
2837 assert(old_bs
!= new_bs
);
2839 if (old_bs
&& new_bs
) {
2840 assert(bdrv_get_aio_context(old_bs
) == bdrv_get_aio_context(new_bs
));
2843 new_bs_quiesce_counter
= (new_bs
? new_bs
->quiesce_counter
: 0);
2844 drain_saldo
= new_bs_quiesce_counter
- child
->parent_quiesce_counter
;
2847 * If the new child node is drained but the old one was not, flush
2848 * all outstanding requests to the old child node.
2850 while (drain_saldo
> 0 && child
->klass
->drained_begin
) {
2851 bdrv_parent_drained_begin_single(child
, true);
2856 /* Detach first so that the recursive drain sections coming from @child
2857 * are already gone and we only end the drain sections that came from
2859 if (child
->klass
->detach
) {
2860 child
->klass
->detach(child
);
2862 assert_bdrv_graph_writable(old_bs
);
2863 QLIST_REMOVE(child
, next_parent
);
2872 assert_bdrv_graph_writable(new_bs
);
2873 QLIST_INSERT_HEAD(&new_bs
->parents
, child
, next_parent
);
2876 * Detaching the old node may have led to the new node's
2877 * quiesce_counter having been decreased. Not a problem, we
2878 * just need to recognize this here and then invoke
2879 * drained_end appropriately more often.
2881 assert(new_bs
->quiesce_counter
<= new_bs_quiesce_counter
);
2882 drain_saldo
+= new_bs
->quiesce_counter
- new_bs_quiesce_counter
;
2884 /* Attach only after starting new drained sections, so that recursive
2885 * drain sections coming from @child don't get an extra .drained_begin
2887 if (child
->klass
->attach
) {
2888 child
->klass
->attach(child
);
2893 * If the old child node was drained but the new one is not, allow
2894 * requests to come in only after the new node has been attached.
2896 while (drain_saldo
< 0 && child
->klass
->drained_end
) {
2897 bdrv_parent_drained_end_single(child
);
2901 if (free_empty_child
&& !child
->bs
) {
2902 bdrv_child_free(child
);
2907 * Free the given @child.
2909 * The child must be empty (i.e. `child->bs == NULL`) and it must be
2910 * unused (i.e. not in a children list).
2912 static void bdrv_child_free(BdrvChild
*child
)
2915 GLOBAL_STATE_CODE();
2916 assert(!child
->next
.le_prev
); /* not in children list */
2918 g_free(child
->name
);
2922 typedef struct BdrvAttachChildCommonState
{
2924 AioContext
*old_parent_ctx
;
2925 AioContext
*old_child_ctx
;
2926 } BdrvAttachChildCommonState
;
2928 static void bdrv_attach_child_common_abort(void *opaque
)
2930 BdrvAttachChildCommonState
*s
= opaque
;
2931 BdrvChild
*child
= *s
->child
;
2932 BlockDriverState
*bs
= child
->bs
;
2935 * Pass free_empty_child=false, because we still need the child
2936 * for the AioContext operations on the parent below; those
2937 * BdrvChildClass methods all work on a BdrvChild object, so we
2938 * need to keep it as an empty shell (after this function, it will
2939 * not be attached to any parent, and it will not have a .bs).
2941 bdrv_replace_child_noperm(s
->child
, NULL
, false);
2943 if (bdrv_get_aio_context(bs
) != s
->old_child_ctx
) {
2944 bdrv_try_set_aio_context(bs
, s
->old_child_ctx
, &error_abort
);
2947 if (bdrv_child_get_parent_aio_context(child
) != s
->old_parent_ctx
) {
2950 /* No need to ignore `child`, because it has been detached already */
2952 child
->klass
->can_set_aio_ctx(child
, s
->old_parent_ctx
, &ignore
,
2954 g_slist_free(ignore
);
2957 child
->klass
->set_aio_ctx(child
, s
->old_parent_ctx
, &ignore
);
2958 g_slist_free(ignore
);
2962 bdrv_child_free(child
);
2965 static TransactionActionDrv bdrv_attach_child_common_drv
= {
2966 .abort
= bdrv_attach_child_common_abort
,
2971 * Common part of attaching bdrv child to bs or to blk or to job
2973 * Resulting new child is returned through @child.
2974 * At start *@child must be NULL.
2975 * @child is saved to a new entry of @tran, so that *@child could be reverted to
2976 * NULL on abort(). So referenced variable must live at least until transaction
2979 * Function doesn't update permissions, caller is responsible for this.
2981 static int bdrv_attach_child_common(BlockDriverState
*child_bs
,
2982 const char *child_name
,
2983 const BdrvChildClass
*child_class
,
2984 BdrvChildRole child_role
,
2985 uint64_t perm
, uint64_t shared_perm
,
2986 void *opaque
, BdrvChild
**child
,
2987 Transaction
*tran
, Error
**errp
)
2989 BdrvChild
*new_child
;
2990 AioContext
*parent_ctx
;
2991 AioContext
*child_ctx
= bdrv_get_aio_context(child_bs
);
2994 assert(*child
== NULL
);
2995 assert(child_class
->get_parent_desc
);
2996 GLOBAL_STATE_CODE();
2998 new_child
= g_new(BdrvChild
, 1);
2999 *new_child
= (BdrvChild
) {
3001 .name
= g_strdup(child_name
),
3002 .klass
= child_class
,
3005 .shared_perm
= shared_perm
,
3010 * If the AioContexts don't match, first try to move the subtree of
3011 * child_bs into the AioContext of the new parent. If this doesn't work,
3012 * try moving the parent into the AioContext of child_bs instead.
3014 parent_ctx
= bdrv_child_get_parent_aio_context(new_child
);
3015 if (child_ctx
!= parent_ctx
) {
3016 Error
*local_err
= NULL
;
3017 int ret
= bdrv_try_set_aio_context(child_bs
, parent_ctx
, &local_err
);
3019 if (ret
< 0 && child_class
->can_set_aio_ctx
) {
3020 GSList
*ignore
= g_slist_prepend(NULL
, new_child
);
3021 if (child_class
->can_set_aio_ctx(new_child
, child_ctx
, &ignore
,
3024 error_free(local_err
);
3026 g_slist_free(ignore
);
3027 ignore
= g_slist_prepend(NULL
, new_child
);
3028 child_class
->set_aio_ctx(new_child
, child_ctx
, &ignore
);
3030 g_slist_free(ignore
);
3034 error_propagate(errp
, local_err
);
3035 bdrv_child_free(new_child
);
3041 bdrv_replace_child_noperm(&new_child
, child_bs
, true);
3042 /* child_bs was non-NULL, so new_child must not have been freed */
3043 assert(new_child
!= NULL
);
3047 BdrvAttachChildCommonState
*s
= g_new(BdrvAttachChildCommonState
, 1);
3048 *s
= (BdrvAttachChildCommonState
) {
3050 .old_parent_ctx
= parent_ctx
,
3051 .old_child_ctx
= child_ctx
,
3053 tran_add(tran
, &bdrv_attach_child_common_drv
, s
);
3059 * Variable referenced by @child must live at least until transaction end.
3060 * (see bdrv_attach_child_common() doc for details)
3062 * Function doesn't update permissions, caller is responsible for this.
3064 static int bdrv_attach_child_noperm(BlockDriverState
*parent_bs
,
3065 BlockDriverState
*child_bs
,
3066 const char *child_name
,
3067 const BdrvChildClass
*child_class
,
3068 BdrvChildRole child_role
,
3074 uint64_t perm
, shared_perm
;
3076 assert(parent_bs
->drv
);
3077 GLOBAL_STATE_CODE();
3079 if (bdrv_recurse_has_child(child_bs
, parent_bs
)) {
3080 error_setg(errp
, "Making '%s' a %s child of '%s' would create a cycle",
3081 child_bs
->node_name
, child_name
, parent_bs
->node_name
);
3085 bdrv_get_cumulative_perm(parent_bs
, &perm
, &shared_perm
);
3086 bdrv_child_perm(parent_bs
, child_bs
, NULL
, child_role
, NULL
,
3087 perm
, shared_perm
, &perm
, &shared_perm
);
3089 ret
= bdrv_attach_child_common(child_bs
, child_name
, child_class
,
3090 child_role
, perm
, shared_perm
, parent_bs
,
3099 static void bdrv_detach_child(BdrvChild
**childp
)
3101 BlockDriverState
*old_bs
= (*childp
)->bs
;
3103 GLOBAL_STATE_CODE();
3104 bdrv_replace_child_noperm(childp
, NULL
, true);
3108 * Update permissions for old node. We're just taking a parent away, so
3109 * we're loosening restrictions. Errors of permission update are not
3110 * fatal in this case, ignore them.
3112 bdrv_refresh_perms(old_bs
, NULL
);
3115 * When the parent requiring a non-default AioContext is removed, the
3116 * node moves back to the main AioContext
3118 bdrv_try_set_aio_context(old_bs
, qemu_get_aio_context(), NULL
);
3123 * This function steals the reference to child_bs from the caller.
3124 * That reference is later dropped by bdrv_root_unref_child().
3126 * On failure NULL is returned, errp is set and the reference to
3127 * child_bs is also dropped.
3129 * The caller must hold the AioContext lock @child_bs, but not that of @ctx
3130 * (unless @child_bs is already in @ctx).
3132 BdrvChild
*bdrv_root_attach_child(BlockDriverState
*child_bs
,
3133 const char *child_name
,
3134 const BdrvChildClass
*child_class
,
3135 BdrvChildRole child_role
,
3136 uint64_t perm
, uint64_t shared_perm
,
3137 void *opaque
, Error
**errp
)
3140 BdrvChild
*child
= NULL
;
3141 Transaction
*tran
= tran_new();
3143 GLOBAL_STATE_CODE();
3145 ret
= bdrv_attach_child_common(child_bs
, child_name
, child_class
,
3146 child_role
, perm
, shared_perm
, opaque
,
3147 &child
, tran
, errp
);
3152 ret
= bdrv_refresh_perms(child_bs
, errp
);
3155 tran_finalize(tran
, ret
);
3156 /* child is unset on failure by bdrv_attach_child_common_abort() */
3157 assert((ret
< 0) == !child
);
3159 bdrv_unref(child_bs
);
3164 * This function transfers the reference to child_bs from the caller
3165 * to parent_bs. That reference is later dropped by parent_bs on
3166 * bdrv_close() or if someone calls bdrv_unref_child().
3168 * On failure NULL is returned, errp is set and the reference to
3169 * child_bs is also dropped.
3171 * If @parent_bs and @child_bs are in different AioContexts, the caller must
3172 * hold the AioContext lock for @child_bs, but not for @parent_bs.
3174 BdrvChild
*bdrv_attach_child(BlockDriverState
*parent_bs
,
3175 BlockDriverState
*child_bs
,
3176 const char *child_name
,
3177 const BdrvChildClass
*child_class
,
3178 BdrvChildRole child_role
,
3182 BdrvChild
*child
= NULL
;
3183 Transaction
*tran
= tran_new();
3185 GLOBAL_STATE_CODE();
3187 ret
= bdrv_attach_child_noperm(parent_bs
, child_bs
, child_name
, child_class
,
3188 child_role
, &child
, tran
, errp
);
3193 ret
= bdrv_refresh_perms(parent_bs
, errp
);
3199 tran_finalize(tran
, ret
);
3200 /* child is unset on failure by bdrv_attach_child_common_abort() */
3201 assert((ret
< 0) == !child
);
3203 bdrv_unref(child_bs
);
3208 /* Callers must ensure that child->frozen is false. */
3209 void bdrv_root_unref_child(BdrvChild
*child
)
3211 BlockDriverState
*child_bs
;
3213 GLOBAL_STATE_CODE();
3215 child_bs
= child
->bs
;
3216 bdrv_detach_child(&child
);
3217 bdrv_unref(child_bs
);
3220 typedef struct BdrvSetInheritsFrom
{
3221 BlockDriverState
*bs
;
3222 BlockDriverState
*old_inherits_from
;
3223 } BdrvSetInheritsFrom
;
3225 static void bdrv_set_inherits_from_abort(void *opaque
)
3227 BdrvSetInheritsFrom
*s
= opaque
;
3229 s
->bs
->inherits_from
= s
->old_inherits_from
;
3232 static TransactionActionDrv bdrv_set_inherits_from_drv
= {
3233 .abort
= bdrv_set_inherits_from_abort
,
3237 /* @tran is allowed to be NULL. In this case no rollback is possible */
3238 static void bdrv_set_inherits_from(BlockDriverState
*bs
,
3239 BlockDriverState
*new_inherits_from
,
3243 BdrvSetInheritsFrom
*s
= g_new(BdrvSetInheritsFrom
, 1);
3245 *s
= (BdrvSetInheritsFrom
) {
3247 .old_inherits_from
= bs
->inherits_from
,
3250 tran_add(tran
, &bdrv_set_inherits_from_drv
, s
);
3253 bs
->inherits_from
= new_inherits_from
;
3257 * Clear all inherits_from pointers from children and grandchildren of
3258 * @root that point to @root, where necessary.
3259 * @tran is allowed to be NULL. In this case no rollback is possible
3261 static void bdrv_unset_inherits_from(BlockDriverState
*root
, BdrvChild
*child
,
3266 if (child
->bs
->inherits_from
== root
) {
3268 * Remove inherits_from only when the last reference between root and
3269 * child->bs goes away.
3271 QLIST_FOREACH(c
, &root
->children
, next
) {
3272 if (c
!= child
&& c
->bs
== child
->bs
) {
3277 bdrv_set_inherits_from(child
->bs
, NULL
, tran
);
3281 QLIST_FOREACH(c
, &child
->bs
->children
, next
) {
3282 bdrv_unset_inherits_from(root
, c
, tran
);
3286 /* Callers must ensure that child->frozen is false. */
3287 void bdrv_unref_child(BlockDriverState
*parent
, BdrvChild
*child
)
3289 GLOBAL_STATE_CODE();
3290 if (child
== NULL
) {
3294 bdrv_unset_inherits_from(parent
, child
, NULL
);
3295 bdrv_root_unref_child(child
);
3299 static void bdrv_parent_cb_change_media(BlockDriverState
*bs
, bool load
)
3302 QLIST_FOREACH(c
, &bs
->parents
, next_parent
) {
3303 if (c
->klass
->change_media
) {
3304 c
->klass
->change_media(c
, load
);
3309 /* Return true if you can reach parent going through child->inherits_from
3310 * recursively. If parent or child are NULL, return false */
3311 static bool bdrv_inherits_from_recursive(BlockDriverState
*child
,
3312 BlockDriverState
*parent
)
3314 while (child
&& child
!= parent
) {
3315 child
= child
->inherits_from
;
3318 return child
!= NULL
;
3322 * Return the BdrvChildRole for @bs's backing child. bs->backing is
3323 * mostly used for COW backing children (role = COW), but also for
3324 * filtered children (role = FILTERED | PRIMARY).
3326 static BdrvChildRole
bdrv_backing_role(BlockDriverState
*bs
)
3328 if (bs
->drv
&& bs
->drv
->is_filter
) {
3329 return BDRV_CHILD_FILTERED
| BDRV_CHILD_PRIMARY
;
3331 return BDRV_CHILD_COW
;
3336 * Sets the bs->backing or bs->file link of a BDS. A new reference is created;
3337 * callers which don't need their own reference any more must call bdrv_unref().
3339 * Function doesn't update permissions, caller is responsible for this.
3341 static int bdrv_set_file_or_backing_noperm(BlockDriverState
*parent_bs
,
3342 BlockDriverState
*child_bs
,
3344 Transaction
*tran
, Error
**errp
)
3347 bool update_inherits_from
=
3348 bdrv_inherits_from_recursive(child_bs
, parent_bs
);
3349 BdrvChild
*child
= is_backing
? parent_bs
->backing
: parent_bs
->file
;
3352 GLOBAL_STATE_CODE();
3354 if (!parent_bs
->drv
) {
3356 * Node without drv is an object without a class :/. TODO: finally fix
3357 * qcow2 driver to never clear bs->drv and implement format corruption
3358 * handling in other way.
3360 error_setg(errp
, "Node corrupted");
3364 if (child
&& child
->frozen
) {
3365 error_setg(errp
, "Cannot change frozen '%s' link from '%s' to '%s'",
3366 child
->name
, parent_bs
->node_name
, child
->bs
->node_name
);
3370 if (is_backing
&& !parent_bs
->drv
->is_filter
&&
3371 !parent_bs
->drv
->supports_backing
)
3373 error_setg(errp
, "Driver '%s' of node '%s' does not support backing "
3374 "files", parent_bs
->drv
->format_name
, parent_bs
->node_name
);
3378 if (parent_bs
->drv
->is_filter
) {
3379 role
= BDRV_CHILD_FILTERED
| BDRV_CHILD_PRIMARY
;
3380 } else if (is_backing
) {
3381 role
= BDRV_CHILD_COW
;
3384 * We only can use same role as it is in existing child. We don't have
3385 * infrastructure to determine role of file child in generic way
3388 error_setg(errp
, "Cannot set file child to format node without "
3396 bdrv_unset_inherits_from(parent_bs
, child
, tran
);
3397 bdrv_remove_file_or_backing_child(parent_bs
, child
, tran
);
3404 ret
= bdrv_attach_child_noperm(parent_bs
, child_bs
,
3405 is_backing
? "backing" : "file",
3406 &child_of_bds
, role
,
3407 is_backing
? &parent_bs
->backing
:
3416 * If inherits_from pointed recursively to bs then let's update it to
3417 * point directly to bs (else it will become NULL).
3419 if (update_inherits_from
) {
3420 bdrv_set_inherits_from(child_bs
, parent_bs
, tran
);
3424 bdrv_refresh_limits(parent_bs
, tran
, NULL
);
3429 static int bdrv_set_backing_noperm(BlockDriverState
*bs
,
3430 BlockDriverState
*backing_hd
,
3431 Transaction
*tran
, Error
**errp
)
3433 GLOBAL_STATE_CODE();
3434 return bdrv_set_file_or_backing_noperm(bs
, backing_hd
, true, tran
, errp
);
3437 int bdrv_set_backing_hd(BlockDriverState
*bs
, BlockDriverState
*backing_hd
,
3441 Transaction
*tran
= tran_new();
3443 GLOBAL_STATE_CODE();
3444 bdrv_drained_begin(bs
);
3446 ret
= bdrv_set_backing_noperm(bs
, backing_hd
, tran
, errp
);
3451 ret
= bdrv_refresh_perms(bs
, errp
);
3453 tran_finalize(tran
, ret
);
3455 bdrv_drained_end(bs
);
3461 * Opens the backing file for a BlockDriverState if not yet open
3463 * bdref_key specifies the key for the image's BlockdevRef in the options QDict.
3464 * That QDict has to be flattened; therefore, if the BlockdevRef is a QDict
3465 * itself, all options starting with "${bdref_key}." are considered part of the
3468 * TODO Can this be unified with bdrv_open_image()?
3470 int bdrv_open_backing_file(BlockDriverState
*bs
, QDict
*parent_options
,
3471 const char *bdref_key
, Error
**errp
)
3473 char *backing_filename
= NULL
;
3474 char *bdref_key_dot
;
3475 const char *reference
= NULL
;
3477 bool implicit_backing
= false;
3478 BlockDriverState
*backing_hd
;
3480 QDict
*tmp_parent_options
= NULL
;
3481 Error
*local_err
= NULL
;
3483 GLOBAL_STATE_CODE();
3485 if (bs
->backing
!= NULL
) {
3489 /* NULL means an empty set of options */
3490 if (parent_options
== NULL
) {
3491 tmp_parent_options
= qdict_new();
3492 parent_options
= tmp_parent_options
;
3495 bs
->open_flags
&= ~BDRV_O_NO_BACKING
;
3497 bdref_key_dot
= g_strdup_printf("%s.", bdref_key
);
3498 qdict_extract_subqdict(parent_options
, &options
, bdref_key_dot
);
3499 g_free(bdref_key_dot
);
3502 * Caution: while qdict_get_try_str() is fine, getting non-string
3503 * types would require more care. When @parent_options come from
3504 * -blockdev or blockdev_add, its members are typed according to
3505 * the QAPI schema, but when they come from -drive, they're all
3508 reference
= qdict_get_try_str(parent_options
, bdref_key
);
3509 if (reference
|| qdict_haskey(options
, "file.filename")) {
3510 /* keep backing_filename NULL */
3511 } else if (bs
->backing_file
[0] == '\0' && qdict_size(options
) == 0) {
3512 qobject_unref(options
);
3515 if (qdict_size(options
) == 0) {
3516 /* If the user specifies options that do not modify the
3517 * backing file's behavior, we might still consider it the
3518 * implicit backing file. But it's easier this way, and
3519 * just specifying some of the backing BDS's options is
3520 * only possible with -drive anyway (otherwise the QAPI
3521 * schema forces the user to specify everything). */
3522 implicit_backing
= !strcmp(bs
->auto_backing_file
, bs
->backing_file
);
3525 backing_filename
= bdrv_get_full_backing_filename(bs
, &local_err
);
3528 error_propagate(errp
, local_err
);
3529 qobject_unref(options
);
3534 if (!bs
->drv
|| !bs
->drv
->supports_backing
) {
3536 error_setg(errp
, "Driver doesn't support backing files");
3537 qobject_unref(options
);
3542 bs
->backing_format
[0] != '\0' && !qdict_haskey(options
, "driver")) {
3543 qdict_put_str(options
, "driver", bs
->backing_format
);
3546 backing_hd
= bdrv_open_inherit(backing_filename
, reference
, options
, 0, bs
,
3547 &child_of_bds
, bdrv_backing_role(bs
), errp
);
3549 bs
->open_flags
|= BDRV_O_NO_BACKING
;
3550 error_prepend(errp
, "Could not open backing file: ");
3555 if (implicit_backing
) {
3556 bdrv_refresh_filename(backing_hd
);
3557 pstrcpy(bs
->auto_backing_file
, sizeof(bs
->auto_backing_file
),
3558 backing_hd
->filename
);
3561 /* Hook up the backing file link; drop our reference, bs owns the
3562 * backing_hd reference now */
3563 ret
= bdrv_set_backing_hd(bs
, backing_hd
, errp
);
3564 bdrv_unref(backing_hd
);
3569 qdict_del(parent_options
, bdref_key
);
3572 g_free(backing_filename
);
3573 qobject_unref(tmp_parent_options
);
3577 static BlockDriverState
*
3578 bdrv_open_child_bs(const char *filename
, QDict
*options
, const char *bdref_key
,
3579 BlockDriverState
*parent
, const BdrvChildClass
*child_class
,
3580 BdrvChildRole child_role
, bool allow_none
, Error
**errp
)
3582 BlockDriverState
*bs
= NULL
;
3583 QDict
*image_options
;
3584 char *bdref_key_dot
;
3585 const char *reference
;
3587 assert(child_class
!= NULL
);
3589 bdref_key_dot
= g_strdup_printf("%s.", bdref_key
);
3590 qdict_extract_subqdict(options
, &image_options
, bdref_key_dot
);
3591 g_free(bdref_key_dot
);
3594 * Caution: while qdict_get_try_str() is fine, getting non-string
3595 * types would require more care. When @options come from
3596 * -blockdev or blockdev_add, its members are typed according to
3597 * the QAPI schema, but when they come from -drive, they're all
3600 reference
= qdict_get_try_str(options
, bdref_key
);
3601 if (!filename
&& !reference
&& !qdict_size(image_options
)) {
3603 error_setg(errp
, "A block device must be specified for \"%s\"",
3606 qobject_unref(image_options
);
3610 bs
= bdrv_open_inherit(filename
, reference
, image_options
, 0,
3611 parent
, child_class
, child_role
, errp
);
3617 qdict_del(options
, bdref_key
);
3622 * Opens a disk image whose options are given as BlockdevRef in another block
3625 * If allow_none is true, no image will be opened if filename is false and no
3626 * BlockdevRef is given. NULL will be returned, but errp remains unset.
3628 * bdrev_key specifies the key for the image's BlockdevRef in the options QDict.
3629 * That QDict has to be flattened; therefore, if the BlockdevRef is a QDict
3630 * itself, all options starting with "${bdref_key}." are considered part of the
3633 * The BlockdevRef will be removed from the options QDict.
3635 BdrvChild
*bdrv_open_child(const char *filename
,
3636 QDict
*options
, const char *bdref_key
,
3637 BlockDriverState
*parent
,
3638 const BdrvChildClass
*child_class
,
3639 BdrvChildRole child_role
,
3640 bool allow_none
, Error
**errp
)
3642 BlockDriverState
*bs
;
3644 GLOBAL_STATE_CODE();
3646 bs
= bdrv_open_child_bs(filename
, options
, bdref_key
, parent
, child_class
,
3647 child_role
, allow_none
, errp
);
3652 return bdrv_attach_child(parent
, bs
, bdref_key
, child_class
, child_role
,
3657 * TODO Future callers may need to specify parent/child_class in order for
3658 * option inheritance to work. Existing callers use it for the root node.
3660 BlockDriverState
*bdrv_open_blockdev_ref(BlockdevRef
*ref
, Error
**errp
)
3662 BlockDriverState
*bs
= NULL
;
3663 QObject
*obj
= NULL
;
3664 QDict
*qdict
= NULL
;
3665 const char *reference
= NULL
;
3668 GLOBAL_STATE_CODE();
3670 if (ref
->type
== QTYPE_QSTRING
) {
3671 reference
= ref
->u
.reference
;
3673 BlockdevOptions
*options
= &ref
->u
.definition
;
3674 assert(ref
->type
== QTYPE_QDICT
);
3676 v
= qobject_output_visitor_new(&obj
);
3677 visit_type_BlockdevOptions(v
, NULL
, &options
, &error_abort
);
3678 visit_complete(v
, &obj
);
3680 qdict
= qobject_to(QDict
, obj
);
3681 qdict_flatten(qdict
);
3683 /* bdrv_open_inherit() defaults to the values in bdrv_flags (for
3684 * compatibility with other callers) rather than what we want as the
3685 * real defaults. Apply the defaults here instead. */
3686 qdict_set_default_str(qdict
, BDRV_OPT_CACHE_DIRECT
, "off");
3687 qdict_set_default_str(qdict
, BDRV_OPT_CACHE_NO_FLUSH
, "off");
3688 qdict_set_default_str(qdict
, BDRV_OPT_READ_ONLY
, "off");
3689 qdict_set_default_str(qdict
, BDRV_OPT_AUTO_READ_ONLY
, "off");
3693 bs
= bdrv_open_inherit(NULL
, reference
, qdict
, 0, NULL
, NULL
, 0, errp
);
3700 static BlockDriverState
*bdrv_append_temp_snapshot(BlockDriverState
*bs
,
3702 QDict
*snapshot_options
,
3705 /* TODO: extra byte is a hack to ensure MAX_PATH space on Windows. */
3706 char *tmp_filename
= g_malloc0(PATH_MAX
+ 1);
3708 QemuOpts
*opts
= NULL
;
3709 BlockDriverState
*bs_snapshot
= NULL
;
3712 GLOBAL_STATE_CODE();
3714 /* if snapshot, we create a temporary backing file and open it
3715 instead of opening 'filename' directly */
3717 /* Get the required size from the image */
3718 total_size
= bdrv_getlength(bs
);
3719 if (total_size
< 0) {
3720 error_setg_errno(errp
, -total_size
, "Could not get image size");
3724 /* Create the temporary image */
3725 ret
= get_tmp_filename(tmp_filename
, PATH_MAX
+ 1);
3727 error_setg_errno(errp
, -ret
, "Could not get temporary filename");
3731 opts
= qemu_opts_create(bdrv_qcow2
.create_opts
, NULL
, 0,
3733 qemu_opt_set_number(opts
, BLOCK_OPT_SIZE
, total_size
, &error_abort
);
3734 ret
= bdrv_create(&bdrv_qcow2
, tmp_filename
, opts
, errp
);
3735 qemu_opts_del(opts
);
3737 error_prepend(errp
, "Could not create temporary overlay '%s': ",
3742 /* Prepare options QDict for the temporary file */
3743 qdict_put_str(snapshot_options
, "file.driver", "file");
3744 qdict_put_str(snapshot_options
, "file.filename", tmp_filename
);
3745 qdict_put_str(snapshot_options
, "driver", "qcow2");
3747 bs_snapshot
= bdrv_open(NULL
, NULL
, snapshot_options
, flags
, errp
);
3748 snapshot_options
= NULL
;
3753 ret
= bdrv_append(bs_snapshot
, bs
, errp
);
3760 qobject_unref(snapshot_options
);
3761 g_free(tmp_filename
);
3766 * Opens a disk image (raw, qcow2, vmdk, ...)
3768 * options is a QDict of options to pass to the block drivers, or NULL for an
3769 * empty set of options. The reference to the QDict belongs to the block layer
3770 * after the call (even on failure), so if the caller intends to reuse the
3771 * dictionary, it needs to use qobject_ref() before calling bdrv_open.
3773 * If *pbs is NULL, a new BDS will be created with a pointer to it stored there.
3774 * If it is not NULL, the referenced BDS will be reused.
3776 * The reference parameter may be used to specify an existing block device which
3777 * should be opened. If specified, neither options nor a filename may be given,
3778 * nor can an existing BDS be reused (that is, *pbs has to be NULL).
3780 static BlockDriverState
*bdrv_open_inherit(const char *filename
,
3781 const char *reference
,
3782 QDict
*options
, int flags
,
3783 BlockDriverState
*parent
,
3784 const BdrvChildClass
*child_class
,
3785 BdrvChildRole child_role
,
3789 BlockBackend
*file
= NULL
;
3790 BlockDriverState
*bs
;
3791 BlockDriver
*drv
= NULL
;
3793 const char *drvname
;
3794 const char *backing
;
3795 Error
*local_err
= NULL
;
3796 QDict
*snapshot_options
= NULL
;
3797 int snapshot_flags
= 0;
3799 assert(!child_class
|| !flags
);
3800 assert(!child_class
== !parent
);
3803 bool options_non_empty
= options
? qdict_size(options
) : false;
3804 qobject_unref(options
);
3806 if (filename
|| options_non_empty
) {
3807 error_setg(errp
, "Cannot reference an existing block device with "
3808 "additional options or a new filename");
3812 bs
= bdrv_lookup_bs(reference
, reference
, errp
);
3823 /* NULL means an empty set of options */
3824 if (options
== NULL
) {
3825 options
= qdict_new();
3828 /* json: syntax counts as explicit options, as if in the QDict */
3829 parse_json_protocol(options
, &filename
, &local_err
);
3834 bs
->explicit_options
= qdict_clone_shallow(options
);
3837 bool parent_is_format
;
3840 parent_is_format
= parent
->drv
->is_format
;
3843 * parent->drv is not set yet because this node is opened for
3844 * (potential) format probing. That means that @parent is going
3845 * to be a format node.
3847 parent_is_format
= true;
3850 bs
->inherits_from
= parent
;
3851 child_class
->inherit_options(child_role
, parent_is_format
,
3853 parent
->open_flags
, parent
->options
);
3856 ret
= bdrv_fill_options(&options
, filename
, &flags
, &local_err
);
3862 * Set the BDRV_O_RDWR and BDRV_O_ALLOW_RDWR flags.
3863 * Caution: getting a boolean member of @options requires care.
3864 * When @options come from -blockdev or blockdev_add, members are
3865 * typed according to the QAPI schema, but when they come from
3866 * -drive, they're all QString.
3868 if (g_strcmp0(qdict_get_try_str(options
, BDRV_OPT_READ_ONLY
), "on") &&
3869 !qdict_get_try_bool(options
, BDRV_OPT_READ_ONLY
, false)) {
3870 flags
|= (BDRV_O_RDWR
| BDRV_O_ALLOW_RDWR
);
3872 flags
&= ~BDRV_O_RDWR
;
3875 if (flags
& BDRV_O_SNAPSHOT
) {
3876 snapshot_options
= qdict_new();
3877 bdrv_temp_snapshot_options(&snapshot_flags
, snapshot_options
,
3879 /* Let bdrv_backing_options() override "read-only" */
3880 qdict_del(options
, BDRV_OPT_READ_ONLY
);
3881 bdrv_inherited_options(BDRV_CHILD_COW
, true,
3882 &flags
, options
, flags
, options
);
3885 bs
->open_flags
= flags
;
3886 bs
->options
= options
;
3887 options
= qdict_clone_shallow(options
);
3889 /* Find the right image format driver */
3890 /* See cautionary note on accessing @options above */
3891 drvname
= qdict_get_try_str(options
, "driver");
3893 drv
= bdrv_find_format(drvname
);
3895 error_setg(errp
, "Unknown driver: '%s'", drvname
);
3900 assert(drvname
|| !(flags
& BDRV_O_PROTOCOL
));
3902 /* See cautionary note on accessing @options above */
3903 backing
= qdict_get_try_str(options
, "backing");
3904 if (qobject_to(QNull
, qdict_get(options
, "backing")) != NULL
||
3905 (backing
&& *backing
== '\0'))
3908 warn_report("Use of \"backing\": \"\" is deprecated; "
3909 "use \"backing\": null instead");
3911 flags
|= BDRV_O_NO_BACKING
;
3912 qdict_del(bs
->explicit_options
, "backing");
3913 qdict_del(bs
->options
, "backing");
3914 qdict_del(options
, "backing");
3917 /* Open image file without format layer. This BlockBackend is only used for
3918 * probing, the block drivers will do their own bdrv_open_child() for the
3919 * same BDS, which is why we put the node name back into options. */
3920 if ((flags
& BDRV_O_PROTOCOL
) == 0) {
3921 BlockDriverState
*file_bs
;
3923 file_bs
= bdrv_open_child_bs(filename
, options
, "file", bs
,
3924 &child_of_bds
, BDRV_CHILD_IMAGE
,
3929 if (file_bs
!= NULL
) {
3930 /* Not requesting BLK_PERM_CONSISTENT_READ because we're only
3931 * looking at the header to guess the image format. This works even
3932 * in cases where a guest would not see a consistent state. */
3933 file
= blk_new(bdrv_get_aio_context(file_bs
), 0, BLK_PERM_ALL
);
3934 blk_insert_bs(file
, file_bs
, &local_err
);
3935 bdrv_unref(file_bs
);
3940 qdict_put_str(options
, "file", bdrv_get_node_name(file_bs
));
3944 /* Image format probing */
3947 ret
= find_image_format(file
, filename
, &drv
, &local_err
);
3952 * This option update would logically belong in bdrv_fill_options(),
3953 * but we first need to open bs->file for the probing to work, while
3954 * opening bs->file already requires the (mostly) final set of options
3955 * so that cache mode etc. can be inherited.
3957 * Adding the driver later is somewhat ugly, but it's not an option
3958 * that would ever be inherited, so it's correct. We just need to make
3959 * sure to update both bs->options (which has the full effective
3960 * options for bs) and options (which has file.* already removed).
3962 qdict_put_str(bs
->options
, "driver", drv
->format_name
);
3963 qdict_put_str(options
, "driver", drv
->format_name
);
3965 error_setg(errp
, "Must specify either driver or file");
3969 /* BDRV_O_PROTOCOL must be set iff a protocol BDS is about to be created */
3970 assert(!!(flags
& BDRV_O_PROTOCOL
) == !!drv
->bdrv_file_open
);
3971 /* file must be NULL if a protocol BDS is about to be created
3972 * (the inverse results in an error message from bdrv_open_common()) */
3973 assert(!(flags
& BDRV_O_PROTOCOL
) || !file
);
3975 /* Open the image */
3976 ret
= bdrv_open_common(bs
, file
, options
, &local_err
);
3986 /* If there is a backing file, use it */
3987 if ((flags
& BDRV_O_NO_BACKING
) == 0) {
3988 ret
= bdrv_open_backing_file(bs
, options
, "backing", &local_err
);
3990 goto close_and_fail
;
3994 /* Remove all children options and references
3995 * from bs->options and bs->explicit_options */
3996 QLIST_FOREACH(child
, &bs
->children
, next
) {
3997 char *child_key_dot
;
3998 child_key_dot
= g_strdup_printf("%s.", child
->name
);
3999 qdict_extract_subqdict(bs
->explicit_options
, NULL
, child_key_dot
);
4000 qdict_extract_subqdict(bs
->options
, NULL
, child_key_dot
);
4001 qdict_del(bs
->explicit_options
, child
->name
);
4002 qdict_del(bs
->options
, child
->name
);
4003 g_free(child_key_dot
);
4006 /* Check if any unknown options were used */
4007 if (qdict_size(options
) != 0) {
4008 const QDictEntry
*entry
= qdict_first(options
);
4009 if (flags
& BDRV_O_PROTOCOL
) {
4010 error_setg(errp
, "Block protocol '%s' doesn't support the option "
4011 "'%s'", drv
->format_name
, entry
->key
);
4014 "Block format '%s' does not support the option '%s'",
4015 drv
->format_name
, entry
->key
);
4018 goto close_and_fail
;
4021 bdrv_parent_cb_change_media(bs
, true);
4023 qobject_unref(options
);
4026 /* For snapshot=on, create a temporary qcow2 overlay. bs points to the
4027 * temporary snapshot afterwards. */
4028 if (snapshot_flags
) {
4029 BlockDriverState
*snapshot_bs
;
4030 snapshot_bs
= bdrv_append_temp_snapshot(bs
, snapshot_flags
,
4031 snapshot_options
, &local_err
);
4032 snapshot_options
= NULL
;
4034 goto close_and_fail
;
4036 /* We are not going to return bs but the overlay on top of it
4037 * (snapshot_bs); thus, we have to drop the strong reference to bs
4038 * (which we obtained by calling bdrv_new()). bs will not be deleted,
4039 * though, because the overlay still has a reference to it. */
4048 qobject_unref(snapshot_options
);
4049 qobject_unref(bs
->explicit_options
);
4050 qobject_unref(bs
->options
);
4051 qobject_unref(options
);
4053 bs
->explicit_options
= NULL
;
4055 error_propagate(errp
, local_err
);
4060 qobject_unref(snapshot_options
);
4061 qobject_unref(options
);
4062 error_propagate(errp
, local_err
);
4066 BlockDriverState
*bdrv_open(const char *filename
, const char *reference
,
4067 QDict
*options
, int flags
, Error
**errp
)
4069 GLOBAL_STATE_CODE();
4071 return bdrv_open_inherit(filename
, reference
, options
, flags
, NULL
,
4075 /* Return true if the NULL-terminated @list contains @str */
4076 static bool is_str_in_list(const char *str
, const char *const *list
)
4080 for (i
= 0; list
[i
] != NULL
; i
++) {
4081 if (!strcmp(str
, list
[i
])) {
4090 * Check that every option set in @bs->options is also set in
4093 * Options listed in the common_options list and in
4094 * @bs->drv->mutable_opts are skipped.
4096 * Return 0 on success, otherwise return -EINVAL and set @errp.
4098 static int bdrv_reset_options_allowed(BlockDriverState
*bs
,
4099 const QDict
*new_opts
, Error
**errp
)
4101 const QDictEntry
*e
;
4102 /* These options are common to all block drivers and are handled
4103 * in bdrv_reopen_prepare() so they can be left out of @new_opts */
4104 const char *const common_options
[] = {
4105 "node-name", "discard", "cache.direct", "cache.no-flush",
4106 "read-only", "auto-read-only", "detect-zeroes", NULL
4109 for (e
= qdict_first(bs
->options
); e
; e
= qdict_next(bs
->options
, e
)) {
4110 if (!qdict_haskey(new_opts
, e
->key
) &&
4111 !is_str_in_list(e
->key
, common_options
) &&
4112 !is_str_in_list(e
->key
, bs
->drv
->mutable_opts
)) {
4113 error_setg(errp
, "Option '%s' cannot be reset "
4114 "to its default value", e
->key
);
4123 * Returns true if @child can be reached recursively from @bs
4125 static bool bdrv_recurse_has_child(BlockDriverState
*bs
,
4126 BlockDriverState
*child
)
4134 QLIST_FOREACH(c
, &bs
->children
, next
) {
4135 if (bdrv_recurse_has_child(c
->bs
, child
)) {
4144 * Adds a BlockDriverState to a simple queue for an atomic, transactional
4145 * reopen of multiple devices.
4147 * bs_queue can either be an existing BlockReopenQueue that has had QTAILQ_INIT
4148 * already performed, or alternatively may be NULL a new BlockReopenQueue will
4149 * be created and initialized. This newly created BlockReopenQueue should be
4150 * passed back in for subsequent calls that are intended to be of the same
4153 * bs is the BlockDriverState to add to the reopen queue.
4155 * options contains the changed options for the associated bs
4156 * (the BlockReopenQueue takes ownership)
4158 * flags contains the open flags for the associated bs
4160 * returns a pointer to bs_queue, which is either the newly allocated
4161 * bs_queue, or the existing bs_queue being used.
4163 * bs must be drained between bdrv_reopen_queue() and bdrv_reopen_multiple().
4165 static BlockReopenQueue
*bdrv_reopen_queue_child(BlockReopenQueue
*bs_queue
,
4166 BlockDriverState
*bs
,
4168 const BdrvChildClass
*klass
,
4170 bool parent_is_format
,
4171 QDict
*parent_options
,
4177 BlockReopenQueueEntry
*bs_entry
;
4179 QDict
*old_options
, *explicit_options
, *options_copy
;
4183 /* Make sure that the caller remembered to use a drained section. This is
4184 * important to avoid graph changes between the recursive queuing here and
4185 * bdrv_reopen_multiple(). */
4186 assert(bs
->quiesce_counter
> 0);
4188 if (bs_queue
== NULL
) {
4189 bs_queue
= g_new0(BlockReopenQueue
, 1);
4190 QTAILQ_INIT(bs_queue
);
4194 options
= qdict_new();
4197 /* Check if this BlockDriverState is already in the queue */
4198 QTAILQ_FOREACH(bs_entry
, bs_queue
, entry
) {
4199 if (bs
== bs_entry
->state
.bs
) {
4205 * Precedence of options:
4206 * 1. Explicitly passed in options (highest)
4207 * 2. Retained from explicitly set options of bs
4208 * 3. Inherited from parent node
4209 * 4. Retained from effective options of bs
4212 /* Old explicitly set values (don't overwrite by inherited value) */
4213 if (bs_entry
|| keep_old_opts
) {
4214 old_options
= qdict_clone_shallow(bs_entry
?
4215 bs_entry
->state
.explicit_options
:
4216 bs
->explicit_options
);
4217 bdrv_join_options(bs
, options
, old_options
);
4218 qobject_unref(old_options
);
4221 explicit_options
= qdict_clone_shallow(options
);
4223 /* Inherit from parent node */
4224 if (parent_options
) {
4226 klass
->inherit_options(role
, parent_is_format
, &flags
, options
,
4227 parent_flags
, parent_options
);
4229 flags
= bdrv_get_flags(bs
);
4232 if (keep_old_opts
) {
4233 /* Old values are used for options that aren't set yet */
4234 old_options
= qdict_clone_shallow(bs
->options
);
4235 bdrv_join_options(bs
, options
, old_options
);
4236 qobject_unref(old_options
);
4239 /* We have the final set of options so let's update the flags */
4240 options_copy
= qdict_clone_shallow(options
);
4241 opts
= qemu_opts_create(&bdrv_runtime_opts
, NULL
, 0, &error_abort
);
4242 qemu_opts_absorb_qdict(opts
, options_copy
, NULL
);
4243 update_flags_from_options(&flags
, opts
);
4244 qemu_opts_del(opts
);
4245 qobject_unref(options_copy
);
4247 /* bdrv_open_inherit() sets and clears some additional flags internally */
4248 flags
&= ~BDRV_O_PROTOCOL
;
4249 if (flags
& BDRV_O_RDWR
) {
4250 flags
|= BDRV_O_ALLOW_RDWR
;
4254 bs_entry
= g_new0(BlockReopenQueueEntry
, 1);
4255 QTAILQ_INSERT_TAIL(bs_queue
, bs_entry
, entry
);
4257 qobject_unref(bs_entry
->state
.options
);
4258 qobject_unref(bs_entry
->state
.explicit_options
);
4261 bs_entry
->state
.bs
= bs
;
4262 bs_entry
->state
.options
= options
;
4263 bs_entry
->state
.explicit_options
= explicit_options
;
4264 bs_entry
->state
.flags
= flags
;
4267 * If keep_old_opts is false then it means that unspecified
4268 * options must be reset to their original value. We don't allow
4269 * resetting 'backing' but we need to know if the option is
4270 * missing in order to decide if we have to return an error.
4272 if (!keep_old_opts
) {
4273 bs_entry
->state
.backing_missing
=
4274 !qdict_haskey(options
, "backing") &&
4275 !qdict_haskey(options
, "backing.driver");
4278 QLIST_FOREACH(child
, &bs
->children
, next
) {
4279 QDict
*new_child_options
= NULL
;
4280 bool child_keep_old
= keep_old_opts
;
4282 /* reopen can only change the options of block devices that were
4283 * implicitly created and inherited options. For other (referenced)
4284 * block devices, a syntax like "backing.foo" results in an error. */
4285 if (child
->bs
->inherits_from
!= bs
) {
4289 /* Check if the options contain a child reference */
4290 if (qdict_haskey(options
, child
->name
)) {
4291 const char *childref
= qdict_get_try_str(options
, child
->name
);
4293 * The current child must not be reopened if the child
4294 * reference is null or points to a different node.
4296 if (g_strcmp0(childref
, child
->bs
->node_name
)) {
4300 * If the child reference points to the current child then
4301 * reopen it with its existing set of options (note that
4302 * it can still inherit new options from the parent).
4304 child_keep_old
= true;
4306 /* Extract child options ("child-name.*") */
4307 char *child_key_dot
= g_strdup_printf("%s.", child
->name
);
4308 qdict_extract_subqdict(explicit_options
, NULL
, child_key_dot
);
4309 qdict_extract_subqdict(options
, &new_child_options
, child_key_dot
);
4310 g_free(child_key_dot
);
4313 bdrv_reopen_queue_child(bs_queue
, child
->bs
, new_child_options
,
4314 child
->klass
, child
->role
, bs
->drv
->is_format
,
4315 options
, flags
, child_keep_old
);
4321 BlockReopenQueue
*bdrv_reopen_queue(BlockReopenQueue
*bs_queue
,
4322 BlockDriverState
*bs
,
4323 QDict
*options
, bool keep_old_opts
)
4325 GLOBAL_STATE_CODE();
4327 return bdrv_reopen_queue_child(bs_queue
, bs
, options
, NULL
, 0, false,
4328 NULL
, 0, keep_old_opts
);
4331 void bdrv_reopen_queue_free(BlockReopenQueue
*bs_queue
)
4333 GLOBAL_STATE_CODE();
4335 BlockReopenQueueEntry
*bs_entry
, *next
;
4336 QTAILQ_FOREACH_SAFE(bs_entry
, bs_queue
, entry
, next
) {
4337 qobject_unref(bs_entry
->state
.explicit_options
);
4338 qobject_unref(bs_entry
->state
.options
);
4346 * Reopen multiple BlockDriverStates atomically & transactionally.
4348 * The queue passed in (bs_queue) must have been built up previous
4349 * via bdrv_reopen_queue().
4351 * Reopens all BDS specified in the queue, with the appropriate
4352 * flags. All devices are prepared for reopen, and failure of any
4353 * device will cause all device changes to be abandoned, and intermediate
4356 * If all devices prepare successfully, then the changes are committed
4359 * All affected nodes must be drained between bdrv_reopen_queue() and
4360 * bdrv_reopen_multiple().
4362 * To be called from the main thread, with all other AioContexts unlocked.
4364 int bdrv_reopen_multiple(BlockReopenQueue
*bs_queue
, Error
**errp
)
4367 BlockReopenQueueEntry
*bs_entry
, *next
;
4369 Transaction
*tran
= tran_new();
4370 g_autoptr(GHashTable
) found
= NULL
;
4371 g_autoptr(GSList
) refresh_list
= NULL
;
4373 assert(qemu_get_current_aio_context() == qemu_get_aio_context());
4374 assert(bs_queue
!= NULL
);
4376 QTAILQ_FOREACH(bs_entry
, bs_queue
, entry
) {
4377 ctx
= bdrv_get_aio_context(bs_entry
->state
.bs
);
4378 aio_context_acquire(ctx
);
4379 ret
= bdrv_flush(bs_entry
->state
.bs
);
4380 aio_context_release(ctx
);
4382 error_setg_errno(errp
, -ret
, "Error flushing drive");
4387 QTAILQ_FOREACH(bs_entry
, bs_queue
, entry
) {
4388 assert(bs_entry
->state
.bs
->quiesce_counter
> 0);
4389 ctx
= bdrv_get_aio_context(bs_entry
->state
.bs
);
4390 aio_context_acquire(ctx
);
4391 ret
= bdrv_reopen_prepare(&bs_entry
->state
, bs_queue
, tran
, errp
);
4392 aio_context_release(ctx
);
4396 bs_entry
->prepared
= true;
4399 found
= g_hash_table_new(NULL
, NULL
);
4400 QTAILQ_FOREACH(bs_entry
, bs_queue
, entry
) {
4401 BDRVReopenState
*state
= &bs_entry
->state
;
4403 refresh_list
= bdrv_topological_dfs(refresh_list
, found
, state
->bs
);
4404 if (state
->old_backing_bs
) {
4405 refresh_list
= bdrv_topological_dfs(refresh_list
, found
,
4406 state
->old_backing_bs
);
4408 if (state
->old_file_bs
) {
4409 refresh_list
= bdrv_topological_dfs(refresh_list
, found
,
4410 state
->old_file_bs
);
4415 * Note that file-posix driver rely on permission update done during reopen
4416 * (even if no permission changed), because it wants "new" permissions for
4417 * reconfiguring the fd and that's why it does it in raw_check_perm(), not
4418 * in raw_reopen_prepare() which is called with "old" permissions.
4420 ret
= bdrv_list_refresh_perms(refresh_list
, bs_queue
, tran
, errp
);
4426 * If we reach this point, we have success and just need to apply the
4429 * Reverse order is used to comfort qcow2 driver: on commit it need to write
4430 * IN_USE flag to the image, to mark bitmaps in the image as invalid. But
4431 * children are usually goes after parents in reopen-queue, so go from last
4434 QTAILQ_FOREACH_REVERSE(bs_entry
, bs_queue
, entry
) {
4435 ctx
= bdrv_get_aio_context(bs_entry
->state
.bs
);
4436 aio_context_acquire(ctx
);
4437 bdrv_reopen_commit(&bs_entry
->state
);
4438 aio_context_release(ctx
);
4443 QTAILQ_FOREACH_REVERSE(bs_entry
, bs_queue
, entry
) {
4444 BlockDriverState
*bs
= bs_entry
->state
.bs
;
4446 if (bs
->drv
->bdrv_reopen_commit_post
) {
4447 ctx
= bdrv_get_aio_context(bs
);
4448 aio_context_acquire(ctx
);
4449 bs
->drv
->bdrv_reopen_commit_post(&bs_entry
->state
);
4450 aio_context_release(ctx
);
4459 QTAILQ_FOREACH_SAFE(bs_entry
, bs_queue
, entry
, next
) {
4460 if (bs_entry
->prepared
) {
4461 ctx
= bdrv_get_aio_context(bs_entry
->state
.bs
);
4462 aio_context_acquire(ctx
);
4463 bdrv_reopen_abort(&bs_entry
->state
);
4464 aio_context_release(ctx
);
4469 bdrv_reopen_queue_free(bs_queue
);
4474 int bdrv_reopen(BlockDriverState
*bs
, QDict
*opts
, bool keep_old_opts
,
4477 AioContext
*ctx
= bdrv_get_aio_context(bs
);
4478 BlockReopenQueue
*queue
;
4481 GLOBAL_STATE_CODE();
4483 bdrv_subtree_drained_begin(bs
);
4484 if (ctx
!= qemu_get_aio_context()) {
4485 aio_context_release(ctx
);
4488 queue
= bdrv_reopen_queue(NULL
, bs
, opts
, keep_old_opts
);
4489 ret
= bdrv_reopen_multiple(queue
, errp
);
4491 if (ctx
!= qemu_get_aio_context()) {
4492 aio_context_acquire(ctx
);
4494 bdrv_subtree_drained_end(bs
);
4499 int bdrv_reopen_set_read_only(BlockDriverState
*bs
, bool read_only
,
4502 QDict
*opts
= qdict_new();
4504 GLOBAL_STATE_CODE();
4506 qdict_put_bool(opts
, BDRV_OPT_READ_ONLY
, read_only
);
4508 return bdrv_reopen(bs
, opts
, true, errp
);
4512 * Take a BDRVReopenState and check if the value of 'backing' in the
4513 * reopen_state->options QDict is valid or not.
4515 * If 'backing' is missing from the QDict then return 0.
4517 * If 'backing' contains the node name of the backing file of
4518 * reopen_state->bs then return 0.
4520 * If 'backing' contains a different node name (or is null) then check
4521 * whether the current backing file can be replaced with the new one.
4522 * If that's the case then reopen_state->replace_backing_bs is set to
4523 * true and reopen_state->new_backing_bs contains a pointer to the new
4524 * backing BlockDriverState (or NULL).
4526 * Return 0 on success, otherwise return < 0 and set @errp.
4528 static int bdrv_reopen_parse_file_or_backing(BDRVReopenState
*reopen_state
,
4529 bool is_backing
, Transaction
*tran
,
4532 BlockDriverState
*bs
= reopen_state
->bs
;
4533 BlockDriverState
*new_child_bs
;
4534 BlockDriverState
*old_child_bs
= is_backing
? child_bs(bs
->backing
) :
4536 const char *child_name
= is_backing
? "backing" : "file";
4540 GLOBAL_STATE_CODE();
4542 value
= qdict_get(reopen_state
->options
, child_name
);
4543 if (value
== NULL
) {
4547 switch (qobject_type(value
)) {
4549 assert(is_backing
); /* The 'file' option does not allow a null value */
4550 new_child_bs
= NULL
;
4553 str
= qstring_get_str(qobject_to(QString
, value
));
4554 new_child_bs
= bdrv_lookup_bs(NULL
, str
, errp
);
4555 if (new_child_bs
== NULL
) {
4557 } else if (bdrv_recurse_has_child(new_child_bs
, bs
)) {
4558 error_setg(errp
, "Making '%s' a %s child of '%s' would create a "
4559 "cycle", str
, child_name
, bs
->node_name
);
4565 * The options QDict has been flattened, so 'backing' and 'file'
4566 * do not allow any other data type here.
4568 g_assert_not_reached();
4571 if (old_child_bs
== new_child_bs
) {
4576 if (bdrv_skip_implicit_filters(old_child_bs
) == new_child_bs
) {
4580 if (old_child_bs
->implicit
) {
4581 error_setg(errp
, "Cannot replace implicit %s child of %s",
4582 child_name
, bs
->node_name
);
4587 if (bs
->drv
->is_filter
&& !old_child_bs
) {
4589 * Filters always have a file or a backing child, so we are trying to
4590 * change wrong child
4592 error_setg(errp
, "'%s' is a %s filter node that does not support a "
4593 "%s child", bs
->node_name
, bs
->drv
->format_name
, child_name
);
4598 reopen_state
->old_backing_bs
= old_child_bs
;
4600 reopen_state
->old_file_bs
= old_child_bs
;
4603 return bdrv_set_file_or_backing_noperm(bs
, new_child_bs
, is_backing
,
4608 * Prepares a BlockDriverState for reopen. All changes are staged in the
4609 * 'opaque' field of the BDRVReopenState, which is used and allocated by
4610 * the block driver layer .bdrv_reopen_prepare()
4612 * bs is the BlockDriverState to reopen
4613 * flags are the new open flags
4614 * queue is the reopen queue
4616 * Returns 0 on success, non-zero on error. On error errp will be set
4619 * On failure, bdrv_reopen_abort() will be called to clean up any data.
4620 * It is the responsibility of the caller to then call the abort() or
4621 * commit() for any other BDS that have been left in a prepare() state
4624 static int bdrv_reopen_prepare(BDRVReopenState
*reopen_state
,
4625 BlockReopenQueue
*queue
,
4626 Transaction
*change_child_tran
, Error
**errp
)
4630 Error
*local_err
= NULL
;
4633 QDict
*orig_reopen_opts
;
4634 char *discard
= NULL
;
4636 bool drv_prepared
= false;
4638 assert(reopen_state
!= NULL
);
4639 assert(reopen_state
->bs
->drv
!= NULL
);
4640 drv
= reopen_state
->bs
->drv
;
4642 /* This function and each driver's bdrv_reopen_prepare() remove
4643 * entries from reopen_state->options as they are processed, so
4644 * we need to make a copy of the original QDict. */
4645 orig_reopen_opts
= qdict_clone_shallow(reopen_state
->options
);
4647 /* Process generic block layer options */
4648 opts
= qemu_opts_create(&bdrv_runtime_opts
, NULL
, 0, &error_abort
);
4649 if (!qemu_opts_absorb_qdict(opts
, reopen_state
->options
, errp
)) {
4654 /* This was already called in bdrv_reopen_queue_child() so the flags
4655 * are up-to-date. This time we simply want to remove the options from
4656 * QemuOpts in order to indicate that they have been processed. */
4657 old_flags
= reopen_state
->flags
;
4658 update_flags_from_options(&reopen_state
->flags
, opts
);
4659 assert(old_flags
== reopen_state
->flags
);
4661 discard
= qemu_opt_get_del(opts
, BDRV_OPT_DISCARD
);
4662 if (discard
!= NULL
) {
4663 if (bdrv_parse_discard_flags(discard
, &reopen_state
->flags
) != 0) {
4664 error_setg(errp
, "Invalid discard option");
4670 reopen_state
->detect_zeroes
=
4671 bdrv_parse_detect_zeroes(opts
, reopen_state
->flags
, &local_err
);
4673 error_propagate(errp
, local_err
);
4678 /* All other options (including node-name and driver) must be unchanged.
4679 * Put them back into the QDict, so that they are checked at the end
4680 * of this function. */
4681 qemu_opts_to_qdict(opts
, reopen_state
->options
);
4683 /* If we are to stay read-only, do not allow permission change
4684 * to r/w. Attempting to set to r/w may fail if either BDRV_O_ALLOW_RDWR is
4685 * not set, or if the BDS still has copy_on_read enabled */
4686 read_only
= !(reopen_state
->flags
& BDRV_O_RDWR
);
4687 ret
= bdrv_can_set_read_only(reopen_state
->bs
, read_only
, true, &local_err
);
4689 error_propagate(errp
, local_err
);
4693 if (drv
->bdrv_reopen_prepare
) {
4695 * If a driver-specific option is missing, it means that we
4696 * should reset it to its default value.
4697 * But not all options allow that, so we need to check it first.
4699 ret
= bdrv_reset_options_allowed(reopen_state
->bs
,
4700 reopen_state
->options
, errp
);
4705 ret
= drv
->bdrv_reopen_prepare(reopen_state
, queue
, &local_err
);
4707 if (local_err
!= NULL
) {
4708 error_propagate(errp
, local_err
);
4710 bdrv_refresh_filename(reopen_state
->bs
);
4711 error_setg(errp
, "failed while preparing to reopen image '%s'",
4712 reopen_state
->bs
->filename
);
4717 /* It is currently mandatory to have a bdrv_reopen_prepare()
4718 * handler for each supported drv. */
4719 error_setg(errp
, "Block format '%s' used by node '%s' "
4720 "does not support reopening files", drv
->format_name
,
4721 bdrv_get_device_or_node_name(reopen_state
->bs
));
4726 drv_prepared
= true;
4729 * We must provide the 'backing' option if the BDS has a backing
4730 * file or if the image file has a backing file name as part of
4731 * its metadata. Otherwise the 'backing' option can be omitted.
4733 if (drv
->supports_backing
&& reopen_state
->backing_missing
&&
4734 (reopen_state
->bs
->backing
|| reopen_state
->bs
->backing_file
[0])) {
4735 error_setg(errp
, "backing is missing for '%s'",
4736 reopen_state
->bs
->node_name
);
4742 * Allow changing the 'backing' option. The new value can be
4743 * either a reference to an existing node (using its node name)
4744 * or NULL to simply detach the current backing file.
4746 ret
= bdrv_reopen_parse_file_or_backing(reopen_state
, true,
4747 change_child_tran
, errp
);
4751 qdict_del(reopen_state
->options
, "backing");
4753 /* Allow changing the 'file' option. In this case NULL is not allowed */
4754 ret
= bdrv_reopen_parse_file_or_backing(reopen_state
, false,
4755 change_child_tran
, errp
);
4759 qdict_del(reopen_state
->options
, "file");
4761 /* Options that are not handled are only okay if they are unchanged
4762 * compared to the old state. It is expected that some options are only
4763 * used for the initial open, but not reopen (e.g. filename) */
4764 if (qdict_size(reopen_state
->options
)) {
4765 const QDictEntry
*entry
= qdict_first(reopen_state
->options
);
4768 QObject
*new = entry
->value
;
4769 QObject
*old
= qdict_get(reopen_state
->bs
->options
, entry
->key
);
4771 /* Allow child references (child_name=node_name) as long as they
4772 * point to the current child (i.e. everything stays the same). */
4773 if (qobject_type(new) == QTYPE_QSTRING
) {
4775 QLIST_FOREACH(child
, &reopen_state
->bs
->children
, next
) {
4776 if (!strcmp(child
->name
, entry
->key
)) {
4782 if (!strcmp(child
->bs
->node_name
,
4783 qstring_get_str(qobject_to(QString
, new)))) {
4784 continue; /* Found child with this name, skip option */
4790 * TODO: When using -drive to specify blockdev options, all values
4791 * will be strings; however, when using -blockdev, blockdev-add or
4792 * filenames using the json:{} pseudo-protocol, they will be
4794 * In contrast, reopening options are (currently) always strings
4795 * (because you can only specify them through qemu-io; all other
4796 * callers do not specify any options).
4797 * Therefore, when using anything other than -drive to create a BDS,
4798 * this cannot detect non-string options as unchanged, because
4799 * qobject_is_equal() always returns false for objects of different
4800 * type. In the future, this should be remedied by correctly typing
4801 * all options. For now, this is not too big of an issue because
4802 * the user can simply omit options which cannot be changed anyway,
4803 * so they will stay unchanged.
4805 if (!qobject_is_equal(new, old
)) {
4806 error_setg(errp
, "Cannot change the option '%s'", entry
->key
);
4810 } while ((entry
= qdict_next(reopen_state
->options
, entry
)));
4815 /* Restore the original reopen_state->options QDict */
4816 qobject_unref(reopen_state
->options
);
4817 reopen_state
->options
= qobject_ref(orig_reopen_opts
);
4820 if (ret
< 0 && drv_prepared
) {
4821 /* drv->bdrv_reopen_prepare() has succeeded, so we need to
4822 * call drv->bdrv_reopen_abort() before signaling an error
4823 * (bdrv_reopen_multiple() will not call bdrv_reopen_abort()
4824 * when the respective bdrv_reopen_prepare() has failed) */
4825 if (drv
->bdrv_reopen_abort
) {
4826 drv
->bdrv_reopen_abort(reopen_state
);
4829 qemu_opts_del(opts
);
4830 qobject_unref(orig_reopen_opts
);
4836 * Takes the staged changes for the reopen from bdrv_reopen_prepare(), and
4837 * makes them final by swapping the staging BlockDriverState contents into
4838 * the active BlockDriverState contents.
4840 static void bdrv_reopen_commit(BDRVReopenState
*reopen_state
)
4843 BlockDriverState
*bs
;
4846 assert(reopen_state
!= NULL
);
4847 bs
= reopen_state
->bs
;
4849 assert(drv
!= NULL
);
4851 /* If there are any driver level actions to take */
4852 if (drv
->bdrv_reopen_commit
) {
4853 drv
->bdrv_reopen_commit(reopen_state
);
4856 /* set BDS specific flags now */
4857 qobject_unref(bs
->explicit_options
);
4858 qobject_unref(bs
->options
);
4859 qobject_ref(reopen_state
->explicit_options
);
4860 qobject_ref(reopen_state
->options
);
4862 bs
->explicit_options
= reopen_state
->explicit_options
;
4863 bs
->options
= reopen_state
->options
;
4864 bs
->open_flags
= reopen_state
->flags
;
4865 bs
->detect_zeroes
= reopen_state
->detect_zeroes
;
4867 /* Remove child references from bs->options and bs->explicit_options.
4868 * Child options were already removed in bdrv_reopen_queue_child() */
4869 QLIST_FOREACH(child
, &bs
->children
, next
) {
4870 qdict_del(bs
->explicit_options
, child
->name
);
4871 qdict_del(bs
->options
, child
->name
);
4873 /* backing is probably removed, so it's not handled by previous loop */
4874 qdict_del(bs
->explicit_options
, "backing");
4875 qdict_del(bs
->options
, "backing");
4877 bdrv_refresh_limits(bs
, NULL
, NULL
);
4881 * Abort the reopen, and delete and free the staged changes in
4884 static void bdrv_reopen_abort(BDRVReopenState
*reopen_state
)
4888 assert(reopen_state
!= NULL
);
4889 drv
= reopen_state
->bs
->drv
;
4890 assert(drv
!= NULL
);
4892 if (drv
->bdrv_reopen_abort
) {
4893 drv
->bdrv_reopen_abort(reopen_state
);
4898 static void bdrv_close(BlockDriverState
*bs
)
4900 BdrvAioNotifier
*ban
, *ban_next
;
4901 BdrvChild
*child
, *next
;
4903 GLOBAL_STATE_CODE();
4904 assert(!bs
->refcnt
);
4906 bdrv_drained_begin(bs
); /* complete I/O */
4908 bdrv_drain(bs
); /* in case flush left pending I/O */
4911 if (bs
->drv
->bdrv_close
) {
4912 /* Must unfreeze all children, so bdrv_unref_child() works */
4913 bs
->drv
->bdrv_close(bs
);
4918 QLIST_FOREACH_SAFE(child
, &bs
->children
, next
, next
) {
4919 bdrv_unref_child(bs
, child
);
4926 qatomic_set(&bs
->copy_on_read
, 0);
4927 bs
->backing_file
[0] = '\0';
4928 bs
->backing_format
[0] = '\0';
4929 bs
->total_sectors
= 0;
4930 bs
->encrypted
= false;
4932 qobject_unref(bs
->options
);
4933 qobject_unref(bs
->explicit_options
);
4935 bs
->explicit_options
= NULL
;
4936 qobject_unref(bs
->full_open_options
);
4937 bs
->full_open_options
= NULL
;
4938 g_free(bs
->block_status_cache
);
4939 bs
->block_status_cache
= NULL
;
4941 bdrv_release_named_dirty_bitmaps(bs
);
4942 assert(QLIST_EMPTY(&bs
->dirty_bitmaps
));
4944 QLIST_FOREACH_SAFE(ban
, &bs
->aio_notifiers
, list
, ban_next
) {
4947 QLIST_INIT(&bs
->aio_notifiers
);
4948 bdrv_drained_end(bs
);
4951 * If we're still inside some bdrv_drain_all_begin()/end() sections, end
4952 * them now since this BDS won't exist anymore when bdrv_drain_all_end()
4955 if (bs
->quiesce_counter
) {
4956 bdrv_drain_all_end_quiesce(bs
);
4960 void bdrv_close_all(void)
4962 assert(job_next(NULL
) == NULL
);
4963 GLOBAL_STATE_CODE();
4965 /* Drop references from requests still in flight, such as canceled block
4966 * jobs whose AIO context has not been polled yet */
4969 blk_remove_all_bs();
4970 blockdev_close_all_bdrv_states();
4972 assert(QTAILQ_EMPTY(&all_bdrv_states
));
4975 static bool should_update_child(BdrvChild
*c
, BlockDriverState
*to
)
4981 if (c
->klass
->stay_at_node
) {
4985 /* If the child @c belongs to the BDS @to, replacing the current
4986 * c->bs by @to would mean to create a loop.
4988 * Such a case occurs when appending a BDS to a backing chain.
4989 * For instance, imagine the following chain:
4991 * guest device -> node A -> further backing chain...
4993 * Now we create a new BDS B which we want to put on top of this
4994 * chain, so we first attach A as its backing node:
4999 * guest device -> node A -> further backing chain...
5001 * Finally we want to replace A by B. When doing that, we want to
5002 * replace all pointers to A by pointers to B -- except for the
5003 * pointer from B because (1) that would create a loop, and (2)
5004 * that pointer should simply stay intact:
5006 * guest device -> node B
5009 * node A -> further backing chain...
5011 * In general, when replacing a node A (c->bs) by a node B (@to),
5012 * if A is a child of B, that means we cannot replace A by B there
5013 * because that would create a loop. Silently detaching A from B
5014 * is also not really an option. So overall just leaving A in
5015 * place there is the most sensible choice.
5017 * We would also create a loop in any cases where @c is only
5018 * indirectly referenced by @to. Prevent this by returning false
5019 * if @c is found (by breadth-first search) anywhere in the whole
5024 found
= g_hash_table_new(NULL
, NULL
);
5025 g_hash_table_add(found
, to
);
5026 queue
= g_queue_new();
5027 g_queue_push_tail(queue
, to
);
5029 while (!g_queue_is_empty(queue
)) {
5030 BlockDriverState
*v
= g_queue_pop_head(queue
);
5033 QLIST_FOREACH(c2
, &v
->children
, next
) {
5039 if (g_hash_table_contains(found
, c2
->bs
)) {
5043 g_queue_push_tail(queue
, c2
->bs
);
5044 g_hash_table_add(found
, c2
->bs
);
5048 g_queue_free(queue
);
5049 g_hash_table_destroy(found
);
5054 typedef struct BdrvRemoveFilterOrCowChild
{
5056 BlockDriverState
*bs
;
5058 } BdrvRemoveFilterOrCowChild
;
5060 static void bdrv_remove_filter_or_cow_child_abort(void *opaque
)
5062 BdrvRemoveFilterOrCowChild
*s
= opaque
;
5063 BlockDriverState
*parent_bs
= s
->child
->opaque
;
5065 if (s
->is_backing
) {
5066 parent_bs
->backing
= s
->child
;
5068 parent_bs
->file
= s
->child
;
5072 * We don't have to restore child->bs here to undo bdrv_replace_child_tran()
5073 * because that function is transactionable and it registered own completion
5074 * entries in @tran, so .abort() for bdrv_replace_child_safe() will be
5075 * called automatically.
5079 static void bdrv_remove_filter_or_cow_child_commit(void *opaque
)
5081 BdrvRemoveFilterOrCowChild
*s
= opaque
;
5082 GLOBAL_STATE_CODE();
5083 bdrv_child_free(s
->child
);
5086 static void bdrv_remove_filter_or_cow_child_clean(void *opaque
)
5088 BdrvRemoveFilterOrCowChild
*s
= opaque
;
5090 /* Drop the bs reference after the transaction is done */
5095 static TransactionActionDrv bdrv_remove_filter_or_cow_child_drv
= {
5096 .abort
= bdrv_remove_filter_or_cow_child_abort
,
5097 .commit
= bdrv_remove_filter_or_cow_child_commit
,
5098 .clean
= bdrv_remove_filter_or_cow_child_clean
,
5102 * A function to remove backing or file child of @bs.
5103 * Function doesn't update permissions, caller is responsible for this.
5105 static void bdrv_remove_file_or_backing_child(BlockDriverState
*bs
,
5110 BdrvRemoveFilterOrCowChild
*s
;
5117 * Keep a reference to @bs so @childp will stay valid throughout the
5118 * transaction (required by bdrv_replace_child_tran())
5121 if (child
== bs
->backing
) {
5122 childp
= &bs
->backing
;
5123 } else if (child
== bs
->file
) {
5126 g_assert_not_reached();
5131 * Pass free_empty_child=false, we will free the child in
5132 * bdrv_remove_filter_or_cow_child_commit()
5134 bdrv_replace_child_tran(childp
, NULL
, tran
, false);
5137 s
= g_new(BdrvRemoveFilterOrCowChild
, 1);
5138 *s
= (BdrvRemoveFilterOrCowChild
) {
5141 .is_backing
= (childp
== &bs
->backing
),
5143 tran_add(tran
, &bdrv_remove_filter_or_cow_child_drv
, s
);
5147 * A function to remove backing-chain child of @bs if exists: cow child for
5148 * format nodes (always .backing) and filter child for filters (may be .file or
5151 static void bdrv_remove_filter_or_cow_child(BlockDriverState
*bs
,
5154 bdrv_remove_file_or_backing_child(bs
, bdrv_filter_or_cow_child(bs
), tran
);
5157 static int bdrv_replace_node_noperm(BlockDriverState
*from
,
5158 BlockDriverState
*to
,
5159 bool auto_skip
, Transaction
*tran
,
5162 BdrvChild
*c
, *next
;
5165 GLOBAL_STATE_CODE();
5167 QLIST_FOREACH_SAFE(c
, &from
->parents
, next_parent
, next
) {
5168 assert(c
->bs
== from
);
5169 if (!should_update_child(c
, to
)) {
5173 error_setg(errp
, "Should not change '%s' link to '%s'",
5174 c
->name
, from
->node_name
);
5178 error_setg(errp
, "Cannot change '%s' link to '%s'",
5179 c
->name
, from
->node_name
);
5184 * Passing a pointer to the local variable @c is fine here, because
5185 * @to is not NULL, and so &c will not be attached to the transaction.
5187 bdrv_replace_child_tran(&c
, to
, tran
, true);
5194 * With auto_skip=true bdrv_replace_node_common skips updating from parents
5195 * if it creates a parent-child relation loop or if parent is block-job.
5197 * With auto_skip=false the error is returned if from has a parent which should
5200 * With @detach_subchain=true @to must be in a backing chain of @from. In this
5201 * case backing link of the cow-parent of @to is removed.
5203 * @to must not be NULL.
5205 static int bdrv_replace_node_common(BlockDriverState
*from
,
5206 BlockDriverState
*to
,
5207 bool auto_skip
, bool detach_subchain
,
5210 Transaction
*tran
= tran_new();
5211 g_autoptr(GHashTable
) found
= NULL
;
5212 g_autoptr(GSList
) refresh_list
= NULL
;
5213 BlockDriverState
*to_cow_parent
= NULL
;
5216 GLOBAL_STATE_CODE();
5219 if (detach_subchain
) {
5220 assert(bdrv_chain_contains(from
, to
));
5222 for (to_cow_parent
= from
;
5223 bdrv_filter_or_cow_bs(to_cow_parent
) != to
;
5224 to_cow_parent
= bdrv_filter_or_cow_bs(to_cow_parent
))
5230 /* Make sure that @from doesn't go away until we have successfully attached
5231 * all of its parents to @to. */
5234 assert(qemu_get_current_aio_context() == qemu_get_aio_context());
5235 assert(bdrv_get_aio_context(from
) == bdrv_get_aio_context(to
));
5236 bdrv_drained_begin(from
);
5239 * Do the replacement without permission update.
5240 * Replacement may influence the permissions, we should calculate new
5241 * permissions based on new graph. If we fail, we'll roll-back the
5244 ret
= bdrv_replace_node_noperm(from
, to
, auto_skip
, tran
, errp
);
5249 if (detach_subchain
) {
5250 bdrv_remove_filter_or_cow_child(to_cow_parent
, tran
);
5253 found
= g_hash_table_new(NULL
, NULL
);
5255 refresh_list
= bdrv_topological_dfs(refresh_list
, found
, to
);
5256 refresh_list
= bdrv_topological_dfs(refresh_list
, found
, from
);
5258 ret
= bdrv_list_refresh_perms(refresh_list
, NULL
, tran
, errp
);
5266 tran_finalize(tran
, ret
);
5268 bdrv_drained_end(from
);
5275 * Replace node @from by @to (where neither may be NULL).
5277 int bdrv_replace_node(BlockDriverState
*from
, BlockDriverState
*to
,
5280 GLOBAL_STATE_CODE();
5282 return bdrv_replace_node_common(from
, to
, true, false, errp
);
5285 int bdrv_drop_filter(BlockDriverState
*bs
, Error
**errp
)
5287 GLOBAL_STATE_CODE();
5289 return bdrv_replace_node_common(bs
, bdrv_filter_or_cow_bs(bs
), true, true,
5294 * Add new bs contents at the top of an image chain while the chain is
5295 * live, while keeping required fields on the top layer.
5297 * This will modify the BlockDriverState fields, and swap contents
5298 * between bs_new and bs_top. Both bs_new and bs_top are modified.
5300 * bs_new must not be attached to a BlockBackend and must not have backing
5303 * This function does not create any image files.
5305 int bdrv_append(BlockDriverState
*bs_new
, BlockDriverState
*bs_top
,
5309 Transaction
*tran
= tran_new();
5311 GLOBAL_STATE_CODE();
5313 assert(!bs_new
->backing
);
5315 ret
= bdrv_attach_child_noperm(bs_new
, bs_top
, "backing",
5316 &child_of_bds
, bdrv_backing_role(bs_new
),
5317 &bs_new
->backing
, tran
, errp
);
5322 ret
= bdrv_replace_node_noperm(bs_top
, bs_new
, true, tran
, errp
);
5327 ret
= bdrv_refresh_perms(bs_new
, errp
);
5329 tran_finalize(tran
, ret
);
5331 bdrv_refresh_limits(bs_top
, NULL
, NULL
);
5336 /* Not for empty child */
5337 int bdrv_replace_child_bs(BdrvChild
*child
, BlockDriverState
*new_bs
,
5341 Transaction
*tran
= tran_new();
5342 g_autoptr(GHashTable
) found
= NULL
;
5343 g_autoptr(GSList
) refresh_list
= NULL
;
5344 BlockDriverState
*old_bs
= child
->bs
;
5346 GLOBAL_STATE_CODE();
5349 bdrv_drained_begin(old_bs
);
5350 bdrv_drained_begin(new_bs
);
5352 bdrv_replace_child_tran(&child
, new_bs
, tran
, true);
5353 /* @new_bs must have been non-NULL, so @child must not have been freed */
5354 assert(child
!= NULL
);
5356 found
= g_hash_table_new(NULL
, NULL
);
5357 refresh_list
= bdrv_topological_dfs(refresh_list
, found
, old_bs
);
5358 refresh_list
= bdrv_topological_dfs(refresh_list
, found
, new_bs
);
5360 ret
= bdrv_list_refresh_perms(refresh_list
, NULL
, tran
, errp
);
5362 tran_finalize(tran
, ret
);
5364 bdrv_drained_end(old_bs
);
5365 bdrv_drained_end(new_bs
);
5371 static void bdrv_delete(BlockDriverState
*bs
)
5373 assert(bdrv_op_blocker_is_empty(bs
));
5374 assert(!bs
->refcnt
);
5375 GLOBAL_STATE_CODE();
5377 /* remove from list, if necessary */
5378 if (bs
->node_name
[0] != '\0') {
5379 QTAILQ_REMOVE(&graph_bdrv_states
, bs
, node_list
);
5381 QTAILQ_REMOVE(&all_bdrv_states
, bs
, bs_list
);
5390 * Replace @bs by newly created block node.
5392 * @options is a QDict of options to pass to the block drivers, or NULL for an
5393 * empty set of options. The reference to the QDict belongs to the block layer
5394 * after the call (even on failure), so if the caller intends to reuse the
5395 * dictionary, it needs to use qobject_ref() before calling bdrv_open.
5397 BlockDriverState
*bdrv_insert_node(BlockDriverState
*bs
, QDict
*options
,
5398 int flags
, Error
**errp
)
5402 BlockDriverState
*new_node_bs
= NULL
;
5403 const char *drvname
, *node_name
;
5406 drvname
= qdict_get_try_str(options
, "driver");
5408 error_setg(errp
, "driver is not specified");
5412 drv
= bdrv_find_format(drvname
);
5414 error_setg(errp
, "Unknown driver: '%s'", drvname
);
5418 node_name
= qdict_get_try_str(options
, "node-name");
5420 GLOBAL_STATE_CODE();
5422 new_node_bs
= bdrv_new_open_driver_opts(drv
, node_name
, options
, flags
,
5424 options
= NULL
; /* bdrv_new_open_driver() eats options */
5426 error_prepend(errp
, "Could not create node: ");
5430 bdrv_drained_begin(bs
);
5431 ret
= bdrv_replace_node(bs
, new_node_bs
, errp
);
5432 bdrv_drained_end(bs
);
5435 error_prepend(errp
, "Could not replace node: ");
5442 qobject_unref(options
);
5443 bdrv_unref(new_node_bs
);
5448 * Run consistency checks on an image
5450 * Returns 0 if the check could be completed (it doesn't mean that the image is
5451 * free of errors) or -errno when an internal error occurred. The results of the
5452 * check are stored in res.
5454 int coroutine_fn
bdrv_co_check(BlockDriverState
*bs
,
5455 BdrvCheckResult
*res
, BdrvCheckMode fix
)
5458 if (bs
->drv
== NULL
) {
5461 if (bs
->drv
->bdrv_co_check
== NULL
) {
5465 memset(res
, 0, sizeof(*res
));
5466 return bs
->drv
->bdrv_co_check(bs
, res
, fix
);
5472 * -EINVAL - backing format specified, but no file
5473 * -ENOSPC - can't update the backing file because no space is left in the
5475 * -ENOTSUP - format driver doesn't support changing the backing file
5477 int bdrv_change_backing_file(BlockDriverState
*bs
, const char *backing_file
,
5478 const char *backing_fmt
, bool require
)
5480 BlockDriver
*drv
= bs
->drv
;
5483 GLOBAL_STATE_CODE();
5489 /* Backing file format doesn't make sense without a backing file */
5490 if (backing_fmt
&& !backing_file
) {
5494 if (require
&& backing_file
&& !backing_fmt
) {
5498 if (drv
->bdrv_change_backing_file
!= NULL
) {
5499 ret
= drv
->bdrv_change_backing_file(bs
, backing_file
, backing_fmt
);
5505 pstrcpy(bs
->backing_file
, sizeof(bs
->backing_file
), backing_file
?: "");
5506 pstrcpy(bs
->backing_format
, sizeof(bs
->backing_format
), backing_fmt
?: "");
5507 pstrcpy(bs
->auto_backing_file
, sizeof(bs
->auto_backing_file
),
5508 backing_file
?: "");
5514 * Finds the first non-filter node above bs in the chain between
5515 * active and bs. The returned node is either an immediate parent of
5516 * bs, or there are only filter nodes between the two.
5518 * Returns NULL if bs is not found in active's image chain,
5519 * or if active == bs.
5521 * Returns the bottommost base image if bs == NULL.
5523 BlockDriverState
*bdrv_find_overlay(BlockDriverState
*active
,
5524 BlockDriverState
*bs
)
5527 GLOBAL_STATE_CODE();
5529 bs
= bdrv_skip_filters(bs
);
5530 active
= bdrv_skip_filters(active
);
5533 BlockDriverState
*next
= bdrv_backing_chain_next(active
);
5543 /* Given a BDS, searches for the base layer. */
5544 BlockDriverState
*bdrv_find_base(BlockDriverState
*bs
)
5546 GLOBAL_STATE_CODE();
5548 return bdrv_find_overlay(bs
, NULL
);
5552 * Return true if at least one of the COW (backing) and filter links
5553 * between @bs and @base is frozen. @errp is set if that's the case.
5554 * @base must be reachable from @bs, or NULL.
5556 bool bdrv_is_backing_chain_frozen(BlockDriverState
*bs
, BlockDriverState
*base
,
5559 BlockDriverState
*i
;
5562 GLOBAL_STATE_CODE();
5564 for (i
= bs
; i
!= base
; i
= child_bs(child
)) {
5565 child
= bdrv_filter_or_cow_child(i
);
5567 if (child
&& child
->frozen
) {
5568 error_setg(errp
, "Cannot change '%s' link from '%s' to '%s'",
5569 child
->name
, i
->node_name
, child
->bs
->node_name
);
5578 * Freeze all COW (backing) and filter links between @bs and @base.
5579 * If any of the links is already frozen the operation is aborted and
5580 * none of the links are modified.
5581 * @base must be reachable from @bs, or NULL.
5582 * Returns 0 on success. On failure returns < 0 and sets @errp.
5584 int bdrv_freeze_backing_chain(BlockDriverState
*bs
, BlockDriverState
*base
,
5587 BlockDriverState
*i
;
5590 GLOBAL_STATE_CODE();
5592 if (bdrv_is_backing_chain_frozen(bs
, base
, errp
)) {
5596 for (i
= bs
; i
!= base
; i
= child_bs(child
)) {
5597 child
= bdrv_filter_or_cow_child(i
);
5598 if (child
&& child
->bs
->never_freeze
) {
5599 error_setg(errp
, "Cannot freeze '%s' link to '%s'",
5600 child
->name
, child
->bs
->node_name
);
5605 for (i
= bs
; i
!= base
; i
= child_bs(child
)) {
5606 child
= bdrv_filter_or_cow_child(i
);
5608 child
->frozen
= true;
5616 * Unfreeze all COW (backing) and filter links between @bs and @base.
5617 * The caller must ensure that all links are frozen before using this
5619 * @base must be reachable from @bs, or NULL.
5621 void bdrv_unfreeze_backing_chain(BlockDriverState
*bs
, BlockDriverState
*base
)
5623 BlockDriverState
*i
;
5626 GLOBAL_STATE_CODE();
5628 for (i
= bs
; i
!= base
; i
= child_bs(child
)) {
5629 child
= bdrv_filter_or_cow_child(i
);
5631 assert(child
->frozen
);
5632 child
->frozen
= false;
5638 * Drops images above 'base' up to and including 'top', and sets the image
5639 * above 'top' to have base as its backing file.
5641 * Requires that the overlay to 'top' is opened r/w, so that the backing file
5642 * information in 'bs' can be properly updated.
5644 * E.g., this will convert the following chain:
5645 * bottom <- base <- intermediate <- top <- active
5649 * bottom <- base <- active
5651 * It is allowed for bottom==base, in which case it converts:
5653 * base <- intermediate <- top <- active
5659 * If backing_file_str is non-NULL, it will be used when modifying top's
5660 * overlay image metadata.
5663 * if active == top, that is considered an error
5666 int bdrv_drop_intermediate(BlockDriverState
*top
, BlockDriverState
*base
,
5667 const char *backing_file_str
)
5669 BlockDriverState
*explicit_top
= top
;
5670 bool update_inherits_from
;
5672 Error
*local_err
= NULL
;
5674 g_autoptr(GSList
) updated_children
= NULL
;
5677 GLOBAL_STATE_CODE();
5680 bdrv_subtree_drained_begin(top
);
5682 if (!top
->drv
|| !base
->drv
) {
5686 /* Make sure that base is in the backing chain of top */
5687 if (!bdrv_chain_contains(top
, base
)) {
5691 /* If 'base' recursively inherits from 'top' then we should set
5692 * base->inherits_from to top->inherits_from after 'top' and all
5693 * other intermediate nodes have been dropped.
5694 * If 'top' is an implicit node (e.g. "commit_top") we should skip
5695 * it because no one inherits from it. We use explicit_top for that. */
5696 explicit_top
= bdrv_skip_implicit_filters(explicit_top
);
5697 update_inherits_from
= bdrv_inherits_from_recursive(base
, explicit_top
);
5699 /* success - we can delete the intermediate states, and link top->base */
5700 if (!backing_file_str
) {
5701 bdrv_refresh_filename(base
);
5702 backing_file_str
= base
->filename
;
5705 QLIST_FOREACH(c
, &top
->parents
, next_parent
) {
5706 updated_children
= g_slist_prepend(updated_children
, c
);
5710 * It seems correct to pass detach_subchain=true here, but it triggers
5711 * one more yet not fixed bug, when due to nested aio_poll loop we switch to
5712 * another drained section, which modify the graph (for example, removing
5713 * the child, which we keep in updated_children list). So, it's a TODO.
5715 * Note, bug triggered if pass detach_subchain=true here and run
5716 * test-bdrv-drain. test_drop_intermediate_poll() test-case will crash.
5719 bdrv_replace_node_common(top
, base
, false, false, &local_err
);
5721 error_report_err(local_err
);
5725 for (p
= updated_children
; p
; p
= p
->next
) {
5728 if (c
->klass
->update_filename
) {
5729 ret
= c
->klass
->update_filename(c
, base
, backing_file_str
,
5733 * TODO: Actually, we want to rollback all previous iterations
5734 * of this loop, and (which is almost impossible) previous
5735 * bdrv_replace_node()...
5737 * Note, that c->klass->update_filename may lead to permission
5738 * update, so it's a bad idea to call it inside permission
5739 * update transaction of bdrv_replace_node.
5741 error_report_err(local_err
);
5747 if (update_inherits_from
) {
5748 base
->inherits_from
= explicit_top
->inherits_from
;
5753 bdrv_subtree_drained_end(top
);
5759 * Implementation of BlockDriver.bdrv_get_allocated_file_size() that
5760 * sums the size of all data-bearing children. (This excludes backing
5763 static int64_t bdrv_sum_allocated_file_size(BlockDriverState
*bs
)
5766 int64_t child_size
, sum
= 0;
5768 QLIST_FOREACH(child
, &bs
->children
, next
) {
5769 if (child
->role
& (BDRV_CHILD_DATA
| BDRV_CHILD_METADATA
|
5770 BDRV_CHILD_FILTERED
))
5772 child_size
= bdrv_get_allocated_file_size(child
->bs
);
5773 if (child_size
< 0) {
5784 * Length of a allocated file in bytes. Sparse files are counted by actual
5785 * allocated space. Return < 0 if error or unknown.
5787 int64_t bdrv_get_allocated_file_size(BlockDriverState
*bs
)
5789 BlockDriver
*drv
= bs
->drv
;
5795 if (drv
->bdrv_get_allocated_file_size
) {
5796 return drv
->bdrv_get_allocated_file_size(bs
);
5799 if (drv
->bdrv_file_open
) {
5801 * Protocol drivers default to -ENOTSUP (most of their data is
5802 * not stored in any of their children (if they even have any),
5803 * so there is no generic way to figure it out).
5806 } else if (drv
->is_filter
) {
5807 /* Filter drivers default to the size of their filtered child */
5808 return bdrv_get_allocated_file_size(bdrv_filter_bs(bs
));
5810 /* Other drivers default to summing their children's sizes */
5811 return bdrv_sum_allocated_file_size(bs
);
5817 * @drv: Format driver
5818 * @opts: Creation options for new image
5819 * @in_bs: Existing image containing data for new image (may be NULL)
5820 * @errp: Error object
5821 * Returns: A #BlockMeasureInfo (free using qapi_free_BlockMeasureInfo())
5824 * Calculate file size required to create a new image.
5826 * If @in_bs is given then space for allocated clusters and zero clusters
5827 * from that image are included in the calculation. If @opts contains a
5828 * backing file that is shared by @in_bs then backing clusters may be omitted
5829 * from the calculation.
5831 * If @in_bs is NULL then the calculation includes no allocated clusters
5832 * unless a preallocation option is given in @opts.
5834 * Note that @in_bs may use a different BlockDriver from @drv.
5836 * If an error occurs the @errp pointer is set.
5838 BlockMeasureInfo
*bdrv_measure(BlockDriver
*drv
, QemuOpts
*opts
,
5839 BlockDriverState
*in_bs
, Error
**errp
)
5842 if (!drv
->bdrv_measure
) {
5843 error_setg(errp
, "Block driver '%s' does not support size measurement",
5848 return drv
->bdrv_measure(opts
, in_bs
, errp
);
5852 * Return number of sectors on success, -errno on error.
5854 int64_t bdrv_nb_sectors(BlockDriverState
*bs
)
5856 BlockDriver
*drv
= bs
->drv
;
5862 if (drv
->has_variable_length
) {
5863 int ret
= refresh_total_sectors(bs
, bs
->total_sectors
);
5868 return bs
->total_sectors
;
5872 * Return length in bytes on success, -errno on error.
5873 * The length is always a multiple of BDRV_SECTOR_SIZE.
5875 int64_t bdrv_getlength(BlockDriverState
*bs
)
5877 int64_t ret
= bdrv_nb_sectors(bs
);
5883 if (ret
> INT64_MAX
/ BDRV_SECTOR_SIZE
) {
5886 return ret
* BDRV_SECTOR_SIZE
;
5889 /* return 0 as number of sectors if no device present or error */
5890 void bdrv_get_geometry(BlockDriverState
*bs
, uint64_t *nb_sectors_ptr
)
5892 int64_t nb_sectors
= bdrv_nb_sectors(bs
);
5895 *nb_sectors_ptr
= nb_sectors
< 0 ? 0 : nb_sectors
;
5898 bool bdrv_is_sg(BlockDriverState
*bs
)
5905 * Return whether the given node supports compressed writes.
5907 bool bdrv_supports_compressed_writes(BlockDriverState
*bs
)
5909 BlockDriverState
*filtered
;
5912 if (!bs
->drv
|| !block_driver_can_compress(bs
->drv
)) {
5916 filtered
= bdrv_filter_bs(bs
);
5919 * Filters can only forward compressed writes, so we have to
5922 return bdrv_supports_compressed_writes(filtered
);
5928 const char *bdrv_get_format_name(BlockDriverState
*bs
)
5931 return bs
->drv
? bs
->drv
->format_name
: NULL
;
5934 static int qsort_strcmp(const void *a
, const void *b
)
5936 return strcmp(*(char *const *)a
, *(char *const *)b
);
5939 void bdrv_iterate_format(void (*it
)(void *opaque
, const char *name
),
5940 void *opaque
, bool read_only
)
5945 const char **formats
= NULL
;
5947 GLOBAL_STATE_CODE();
5949 QLIST_FOREACH(drv
, &bdrv_drivers
, list
) {
5950 if (drv
->format_name
) {
5954 if (use_bdrv_whitelist
&& !bdrv_is_whitelisted(drv
, read_only
)) {
5958 while (formats
&& i
&& !found
) {
5959 found
= !strcmp(formats
[--i
], drv
->format_name
);
5963 formats
= g_renew(const char *, formats
, count
+ 1);
5964 formats
[count
++] = drv
->format_name
;
5969 for (i
= 0; i
< (int)ARRAY_SIZE(block_driver_modules
); i
++) {
5970 const char *format_name
= block_driver_modules
[i
].format_name
;
5976 if (use_bdrv_whitelist
&&
5977 !bdrv_format_is_whitelisted(format_name
, read_only
)) {
5981 while (formats
&& j
&& !found
) {
5982 found
= !strcmp(formats
[--j
], format_name
);
5986 formats
= g_renew(const char *, formats
, count
+ 1);
5987 formats
[count
++] = format_name
;
5992 qsort(formats
, count
, sizeof(formats
[0]), qsort_strcmp
);
5994 for (i
= 0; i
< count
; i
++) {
5995 it(opaque
, formats
[i
]);
6001 /* This function is to find a node in the bs graph */
6002 BlockDriverState
*bdrv_find_node(const char *node_name
)
6004 BlockDriverState
*bs
;
6007 GLOBAL_STATE_CODE();
6009 QTAILQ_FOREACH(bs
, &graph_bdrv_states
, node_list
) {
6010 if (!strcmp(node_name
, bs
->node_name
)) {
6017 /* Put this QMP function here so it can access the static graph_bdrv_states. */
6018 BlockDeviceInfoList
*bdrv_named_nodes_list(bool flat
,
6021 BlockDeviceInfoList
*list
;
6022 BlockDriverState
*bs
;
6024 GLOBAL_STATE_CODE();
6027 QTAILQ_FOREACH(bs
, &graph_bdrv_states
, node_list
) {
6028 BlockDeviceInfo
*info
= bdrv_block_device_info(NULL
, bs
, flat
, errp
);
6030 qapi_free_BlockDeviceInfoList(list
);
6033 QAPI_LIST_PREPEND(list
, info
);
6039 typedef struct XDbgBlockGraphConstructor
{
6040 XDbgBlockGraph
*graph
;
6041 GHashTable
*graph_nodes
;
6042 } XDbgBlockGraphConstructor
;
6044 static XDbgBlockGraphConstructor
*xdbg_graph_new(void)
6046 XDbgBlockGraphConstructor
*gr
= g_new(XDbgBlockGraphConstructor
, 1);
6048 gr
->graph
= g_new0(XDbgBlockGraph
, 1);
6049 gr
->graph_nodes
= g_hash_table_new(NULL
, NULL
);
6054 static XDbgBlockGraph
*xdbg_graph_finalize(XDbgBlockGraphConstructor
*gr
)
6056 XDbgBlockGraph
*graph
= gr
->graph
;
6058 g_hash_table_destroy(gr
->graph_nodes
);
6064 static uintptr_t xdbg_graph_node_num(XDbgBlockGraphConstructor
*gr
, void *node
)
6066 uintptr_t ret
= (uintptr_t)g_hash_table_lookup(gr
->graph_nodes
, node
);
6073 * Start counting from 1, not 0, because 0 interferes with not-found (NULL)
6074 * answer of g_hash_table_lookup.
6076 ret
= g_hash_table_size(gr
->graph_nodes
) + 1;
6077 g_hash_table_insert(gr
->graph_nodes
, node
, (void *)ret
);
6082 static void xdbg_graph_add_node(XDbgBlockGraphConstructor
*gr
, void *node
,
6083 XDbgBlockGraphNodeType type
, const char *name
)
6085 XDbgBlockGraphNode
*n
;
6087 n
= g_new0(XDbgBlockGraphNode
, 1);
6089 n
->id
= xdbg_graph_node_num(gr
, node
);
6091 n
->name
= g_strdup(name
);
6093 QAPI_LIST_PREPEND(gr
->graph
->nodes
, n
);
6096 static void xdbg_graph_add_edge(XDbgBlockGraphConstructor
*gr
, void *parent
,
6097 const BdrvChild
*child
)
6099 BlockPermission qapi_perm
;
6100 XDbgBlockGraphEdge
*edge
;
6101 GLOBAL_STATE_CODE();
6103 edge
= g_new0(XDbgBlockGraphEdge
, 1);
6105 edge
->parent
= xdbg_graph_node_num(gr
, parent
);
6106 edge
->child
= xdbg_graph_node_num(gr
, child
->bs
);
6107 edge
->name
= g_strdup(child
->name
);
6109 for (qapi_perm
= 0; qapi_perm
< BLOCK_PERMISSION__MAX
; qapi_perm
++) {
6110 uint64_t flag
= bdrv_qapi_perm_to_blk_perm(qapi_perm
);
6112 if (flag
& child
->perm
) {
6113 QAPI_LIST_PREPEND(edge
->perm
, qapi_perm
);
6115 if (flag
& child
->shared_perm
) {
6116 QAPI_LIST_PREPEND(edge
->shared_perm
, qapi_perm
);
6120 QAPI_LIST_PREPEND(gr
->graph
->edges
, edge
);
6124 XDbgBlockGraph
*bdrv_get_xdbg_block_graph(Error
**errp
)
6128 BlockDriverState
*bs
;
6130 XDbgBlockGraphConstructor
*gr
= xdbg_graph_new();
6132 GLOBAL_STATE_CODE();
6134 for (blk
= blk_all_next(NULL
); blk
; blk
= blk_all_next(blk
)) {
6135 char *allocated_name
= NULL
;
6136 const char *name
= blk_name(blk
);
6139 name
= allocated_name
= blk_get_attached_dev_id(blk
);
6141 xdbg_graph_add_node(gr
, blk
, X_DBG_BLOCK_GRAPH_NODE_TYPE_BLOCK_BACKEND
,
6143 g_free(allocated_name
);
6144 if (blk_root(blk
)) {
6145 xdbg_graph_add_edge(gr
, blk
, blk_root(blk
));
6149 for (job
= block_job_next(NULL
); job
; job
= block_job_next(job
)) {
6152 xdbg_graph_add_node(gr
, job
, X_DBG_BLOCK_GRAPH_NODE_TYPE_BLOCK_JOB
,
6154 for (el
= job
->nodes
; el
; el
= el
->next
) {
6155 xdbg_graph_add_edge(gr
, job
, (BdrvChild
*)el
->data
);
6159 QTAILQ_FOREACH(bs
, &graph_bdrv_states
, node_list
) {
6160 xdbg_graph_add_node(gr
, bs
, X_DBG_BLOCK_GRAPH_NODE_TYPE_BLOCK_DRIVER
,
6162 QLIST_FOREACH(child
, &bs
->children
, next
) {
6163 xdbg_graph_add_edge(gr
, bs
, child
);
6167 return xdbg_graph_finalize(gr
);
6170 BlockDriverState
*bdrv_lookup_bs(const char *device
,
6171 const char *node_name
,
6175 BlockDriverState
*bs
;
6177 GLOBAL_STATE_CODE();
6180 blk
= blk_by_name(device
);
6185 error_setg(errp
, "Device '%s' has no medium", device
);
6193 bs
= bdrv_find_node(node_name
);
6200 error_setg(errp
, "Cannot find device=\'%s\' nor node-name=\'%s\'",
6201 device
? device
: "",
6202 node_name
? node_name
: "");
6206 /* If 'base' is in the same chain as 'top', return true. Otherwise,
6207 * return false. If either argument is NULL, return false. */
6208 bool bdrv_chain_contains(BlockDriverState
*top
, BlockDriverState
*base
)
6211 GLOBAL_STATE_CODE();
6213 while (top
&& top
!= base
) {
6214 top
= bdrv_filter_or_cow_bs(top
);
6220 BlockDriverState
*bdrv_next_node(BlockDriverState
*bs
)
6222 GLOBAL_STATE_CODE();
6224 return QTAILQ_FIRST(&graph_bdrv_states
);
6226 return QTAILQ_NEXT(bs
, node_list
);
6229 BlockDriverState
*bdrv_next_all_states(BlockDriverState
*bs
)
6231 GLOBAL_STATE_CODE();
6233 return QTAILQ_FIRST(&all_bdrv_states
);
6235 return QTAILQ_NEXT(bs
, bs_list
);
6238 const char *bdrv_get_node_name(const BlockDriverState
*bs
)
6241 return bs
->node_name
;
6244 const char *bdrv_get_parent_name(const BlockDriverState
*bs
)
6250 /* If multiple parents have a name, just pick the first one. */
6251 QLIST_FOREACH(c
, &bs
->parents
, next_parent
) {
6252 if (c
->klass
->get_name
) {
6253 name
= c
->klass
->get_name(c
);
6254 if (name
&& *name
) {
6263 /* TODO check what callers really want: bs->node_name or blk_name() */
6264 const char *bdrv_get_device_name(const BlockDriverState
*bs
)
6267 return bdrv_get_parent_name(bs
) ?: "";
6270 /* This can be used to identify nodes that might not have a device
6271 * name associated. Since node and device names live in the same
6272 * namespace, the result is unambiguous. The exception is if both are
6273 * absent, then this returns an empty (non-null) string. */
6274 const char *bdrv_get_device_or_node_name(const BlockDriverState
*bs
)
6277 return bdrv_get_parent_name(bs
) ?: bs
->node_name
;
6280 int bdrv_get_flags(BlockDriverState
*bs
)
6282 GLOBAL_STATE_CODE();
6283 return bs
->open_flags
;
6286 int bdrv_has_zero_init_1(BlockDriverState
*bs
)
6288 GLOBAL_STATE_CODE();
6292 int bdrv_has_zero_init(BlockDriverState
*bs
)
6294 BlockDriverState
*filtered
;
6295 GLOBAL_STATE_CODE();
6301 /* If BS is a copy on write image, it is initialized to
6302 the contents of the base image, which may not be zeroes. */
6303 if (bdrv_cow_child(bs
)) {
6306 if (bs
->drv
->bdrv_has_zero_init
) {
6307 return bs
->drv
->bdrv_has_zero_init(bs
);
6310 filtered
= bdrv_filter_bs(bs
);
6312 return bdrv_has_zero_init(filtered
);
6319 bool bdrv_can_write_zeroes_with_unmap(BlockDriverState
*bs
)
6322 if (!(bs
->open_flags
& BDRV_O_UNMAP
)) {
6326 return bs
->supported_zero_flags
& BDRV_REQ_MAY_UNMAP
;
6329 void bdrv_get_backing_filename(BlockDriverState
*bs
,
6330 char *filename
, int filename_size
)
6333 pstrcpy(filename
, filename_size
, bs
->backing_file
);
6336 int bdrv_get_info(BlockDriverState
*bs
, BlockDriverInfo
*bdi
)
6339 BlockDriver
*drv
= bs
->drv
;
6341 /* if bs->drv == NULL, bs is closed, so there's nothing to do here */
6345 if (!drv
->bdrv_get_info
) {
6346 BlockDriverState
*filtered
= bdrv_filter_bs(bs
);
6348 return bdrv_get_info(filtered
, bdi
);
6352 memset(bdi
, 0, sizeof(*bdi
));
6353 ret
= drv
->bdrv_get_info(bs
, bdi
);
6358 if (bdi
->cluster_size
> BDRV_MAX_ALIGNMENT
) {
6365 ImageInfoSpecific
*bdrv_get_specific_info(BlockDriverState
*bs
,
6368 BlockDriver
*drv
= bs
->drv
;
6370 if (drv
&& drv
->bdrv_get_specific_info
) {
6371 return drv
->bdrv_get_specific_info(bs
, errp
);
6376 BlockStatsSpecific
*bdrv_get_specific_stats(BlockDriverState
*bs
)
6378 BlockDriver
*drv
= bs
->drv
;
6380 if (!drv
|| !drv
->bdrv_get_specific_stats
) {
6383 return drv
->bdrv_get_specific_stats(bs
);
6386 void bdrv_debug_event(BlockDriverState
*bs
, BlkdebugEvent event
)
6389 if (!bs
|| !bs
->drv
|| !bs
->drv
->bdrv_debug_event
) {
6393 bs
->drv
->bdrv_debug_event(bs
, event
);
6396 static BlockDriverState
*bdrv_find_debug_node(BlockDriverState
*bs
)
6398 GLOBAL_STATE_CODE();
6399 while (bs
&& bs
->drv
&& !bs
->drv
->bdrv_debug_breakpoint
) {
6400 bs
= bdrv_primary_bs(bs
);
6403 if (bs
&& bs
->drv
&& bs
->drv
->bdrv_debug_breakpoint
) {
6404 assert(bs
->drv
->bdrv_debug_remove_breakpoint
);
6411 int bdrv_debug_breakpoint(BlockDriverState
*bs
, const char *event
,
6414 GLOBAL_STATE_CODE();
6415 bs
= bdrv_find_debug_node(bs
);
6417 return bs
->drv
->bdrv_debug_breakpoint(bs
, event
, tag
);
6423 int bdrv_debug_remove_breakpoint(BlockDriverState
*bs
, const char *tag
)
6425 GLOBAL_STATE_CODE();
6426 bs
= bdrv_find_debug_node(bs
);
6428 return bs
->drv
->bdrv_debug_remove_breakpoint(bs
, tag
);
6434 int bdrv_debug_resume(BlockDriverState
*bs
, const char *tag
)
6436 GLOBAL_STATE_CODE();
6437 while (bs
&& (!bs
->drv
|| !bs
->drv
->bdrv_debug_resume
)) {
6438 bs
= bdrv_primary_bs(bs
);
6441 if (bs
&& bs
->drv
&& bs
->drv
->bdrv_debug_resume
) {
6442 return bs
->drv
->bdrv_debug_resume(bs
, tag
);
6448 bool bdrv_debug_is_suspended(BlockDriverState
*bs
, const char *tag
)
6450 GLOBAL_STATE_CODE();
6451 while (bs
&& bs
->drv
&& !bs
->drv
->bdrv_debug_is_suspended
) {
6452 bs
= bdrv_primary_bs(bs
);
6455 if (bs
&& bs
->drv
&& bs
->drv
->bdrv_debug_is_suspended
) {
6456 return bs
->drv
->bdrv_debug_is_suspended(bs
, tag
);
6462 /* backing_file can either be relative, or absolute, or a protocol. If it is
6463 * relative, it must be relative to the chain. So, passing in bs->filename
6464 * from a BDS as backing_file should not be done, as that may be relative to
6465 * the CWD rather than the chain. */
6466 BlockDriverState
*bdrv_find_backing_image(BlockDriverState
*bs
,
6467 const char *backing_file
)
6469 char *filename_full
= NULL
;
6470 char *backing_file_full
= NULL
;
6471 char *filename_tmp
= NULL
;
6472 int is_protocol
= 0;
6473 bool filenames_refreshed
= false;
6474 BlockDriverState
*curr_bs
= NULL
;
6475 BlockDriverState
*retval
= NULL
;
6476 BlockDriverState
*bs_below
;
6478 GLOBAL_STATE_CODE();
6480 if (!bs
|| !bs
->drv
|| !backing_file
) {
6484 filename_full
= g_malloc(PATH_MAX
);
6485 backing_file_full
= g_malloc(PATH_MAX
);
6487 is_protocol
= path_has_protocol(backing_file
);
6490 * Being largely a legacy function, skip any filters here
6491 * (because filters do not have normal filenames, so they cannot
6492 * match anyway; and allowing json:{} filenames is a bit out of
6495 for (curr_bs
= bdrv_skip_filters(bs
);
6496 bdrv_cow_child(curr_bs
) != NULL
;
6499 bs_below
= bdrv_backing_chain_next(curr_bs
);
6501 if (bdrv_backing_overridden(curr_bs
)) {
6503 * If the backing file was overridden, we can only compare
6504 * directly against the backing node's filename.
6507 if (!filenames_refreshed
) {
6509 * This will automatically refresh all of the
6510 * filenames in the rest of the backing chain, so we
6511 * only need to do this once.
6513 bdrv_refresh_filename(bs_below
);
6514 filenames_refreshed
= true;
6517 if (strcmp(backing_file
, bs_below
->filename
) == 0) {
6521 } else if (is_protocol
|| path_has_protocol(curr_bs
->backing_file
)) {
6523 * If either of the filename paths is actually a protocol, then
6524 * compare unmodified paths; otherwise make paths relative.
6526 char *backing_file_full_ret
;
6528 if (strcmp(backing_file
, curr_bs
->backing_file
) == 0) {
6532 /* Also check against the full backing filename for the image */
6533 backing_file_full_ret
= bdrv_get_full_backing_filename(curr_bs
,
6535 if (backing_file_full_ret
) {
6536 bool equal
= strcmp(backing_file
, backing_file_full_ret
) == 0;
6537 g_free(backing_file_full_ret
);
6544 /* If not an absolute filename path, make it relative to the current
6545 * image's filename path */
6546 filename_tmp
= bdrv_make_absolute_filename(curr_bs
, backing_file
,
6548 /* We are going to compare canonicalized absolute pathnames */
6549 if (!filename_tmp
|| !realpath(filename_tmp
, filename_full
)) {
6550 g_free(filename_tmp
);
6553 g_free(filename_tmp
);
6555 /* We need to make sure the backing filename we are comparing against
6556 * is relative to the current image filename (or absolute) */
6557 filename_tmp
= bdrv_get_full_backing_filename(curr_bs
, NULL
);
6558 if (!filename_tmp
|| !realpath(filename_tmp
, backing_file_full
)) {
6559 g_free(filename_tmp
);
6562 g_free(filename_tmp
);
6564 if (strcmp(backing_file_full
, filename_full
) == 0) {
6571 g_free(filename_full
);
6572 g_free(backing_file_full
);
6576 void bdrv_init(void)
6578 #ifdef CONFIG_BDRV_WHITELIST_TOOLS
6579 use_bdrv_whitelist
= 1;
6581 module_call_init(MODULE_INIT_BLOCK
);
6584 void bdrv_init_with_whitelist(void)
6586 use_bdrv_whitelist
= 1;
6590 int bdrv_activate(BlockDriverState
*bs
, Error
**errp
)
6592 BdrvChild
*child
, *parent
;
6593 Error
*local_err
= NULL
;
6595 BdrvDirtyBitmap
*bm
;
6597 GLOBAL_STATE_CODE();
6603 QLIST_FOREACH(child
, &bs
->children
, next
) {
6604 bdrv_activate(child
->bs
, &local_err
);
6606 error_propagate(errp
, local_err
);
6612 * Update permissions, they may differ for inactive nodes.
6614 * Note that the required permissions of inactive images are always a
6615 * subset of the permissions required after activating the image. This
6616 * allows us to just get the permissions upfront without restricting
6617 * bdrv_co_invalidate_cache().
6619 * It also means that in error cases, we don't have to try and revert to
6620 * the old permissions (which is an operation that could fail, too). We can
6621 * just keep the extended permissions for the next time that an activation
6622 * of the image is tried.
6624 if (bs
->open_flags
& BDRV_O_INACTIVE
) {
6625 bs
->open_flags
&= ~BDRV_O_INACTIVE
;
6626 ret
= bdrv_refresh_perms(bs
, errp
);
6628 bs
->open_flags
|= BDRV_O_INACTIVE
;
6632 ret
= bdrv_invalidate_cache(bs
, errp
);
6634 bs
->open_flags
|= BDRV_O_INACTIVE
;
6638 FOR_EACH_DIRTY_BITMAP(bs
, bm
) {
6639 bdrv_dirty_bitmap_skip_store(bm
, false);
6642 ret
= refresh_total_sectors(bs
, bs
->total_sectors
);
6644 bs
->open_flags
|= BDRV_O_INACTIVE
;
6645 error_setg_errno(errp
, -ret
, "Could not refresh total sector count");
6650 QLIST_FOREACH(parent
, &bs
->parents
, next_parent
) {
6651 if (parent
->klass
->activate
) {
6652 parent
->klass
->activate(parent
, &local_err
);
6654 bs
->open_flags
|= BDRV_O_INACTIVE
;
6655 error_propagate(errp
, local_err
);
6664 int coroutine_fn
bdrv_co_invalidate_cache(BlockDriverState
*bs
, Error
**errp
)
6666 Error
*local_err
= NULL
;
6669 assert(!(bs
->open_flags
& BDRV_O_INACTIVE
));
6671 if (bs
->drv
->bdrv_co_invalidate_cache
) {
6672 bs
->drv
->bdrv_co_invalidate_cache(bs
, &local_err
);
6674 error_propagate(errp
, local_err
);
6682 void bdrv_activate_all(Error
**errp
)
6684 BlockDriverState
*bs
;
6685 BdrvNextIterator it
;
6687 GLOBAL_STATE_CODE();
6689 for (bs
= bdrv_first(&it
); bs
; bs
= bdrv_next(&it
)) {
6690 AioContext
*aio_context
= bdrv_get_aio_context(bs
);
6693 aio_context_acquire(aio_context
);
6694 ret
= bdrv_activate(bs
, errp
);
6695 aio_context_release(aio_context
);
6697 bdrv_next_cleanup(&it
);
6703 static bool bdrv_has_bds_parent(BlockDriverState
*bs
, bool only_active
)
6706 GLOBAL_STATE_CODE();
6708 QLIST_FOREACH(parent
, &bs
->parents
, next_parent
) {
6709 if (parent
->klass
->parent_is_bds
) {
6710 BlockDriverState
*parent_bs
= parent
->opaque
;
6711 if (!only_active
|| !(parent_bs
->open_flags
& BDRV_O_INACTIVE
)) {
6720 static int bdrv_inactivate_recurse(BlockDriverState
*bs
)
6722 BdrvChild
*child
, *parent
;
6724 uint64_t cumulative_perms
, cumulative_shared_perms
;
6730 /* Make sure that we don't inactivate a child before its parent.
6731 * It will be covered by recursion from the yet active parent. */
6732 if (bdrv_has_bds_parent(bs
, true)) {
6736 assert(!(bs
->open_flags
& BDRV_O_INACTIVE
));
6738 /* Inactivate this node */
6739 if (bs
->drv
->bdrv_inactivate
) {
6740 ret
= bs
->drv
->bdrv_inactivate(bs
);
6746 QLIST_FOREACH(parent
, &bs
->parents
, next_parent
) {
6747 if (parent
->klass
->inactivate
) {
6748 ret
= parent
->klass
->inactivate(parent
);
6755 bdrv_get_cumulative_perm(bs
, &cumulative_perms
,
6756 &cumulative_shared_perms
);
6757 if (cumulative_perms
& (BLK_PERM_WRITE
| BLK_PERM_WRITE_UNCHANGED
)) {
6758 /* Our inactive parents still need write access. Inactivation failed. */
6762 bs
->open_flags
|= BDRV_O_INACTIVE
;
6765 * Update permissions, they may differ for inactive nodes.
6766 * We only tried to loosen restrictions, so errors are not fatal, ignore
6769 bdrv_refresh_perms(bs
, NULL
);
6771 /* Recursively inactivate children */
6772 QLIST_FOREACH(child
, &bs
->children
, next
) {
6773 ret
= bdrv_inactivate_recurse(child
->bs
);
6782 int bdrv_inactivate_all(void)
6784 BlockDriverState
*bs
= NULL
;
6785 BdrvNextIterator it
;
6787 GSList
*aio_ctxs
= NULL
, *ctx
;
6789 GLOBAL_STATE_CODE();
6791 for (bs
= bdrv_first(&it
); bs
; bs
= bdrv_next(&it
)) {
6792 AioContext
*aio_context
= bdrv_get_aio_context(bs
);
6794 if (!g_slist_find(aio_ctxs
, aio_context
)) {
6795 aio_ctxs
= g_slist_prepend(aio_ctxs
, aio_context
);
6796 aio_context_acquire(aio_context
);
6800 for (bs
= bdrv_first(&it
); bs
; bs
= bdrv_next(&it
)) {
6801 /* Nodes with BDS parents are covered by recursion from the last
6802 * parent that gets inactivated. Don't inactivate them a second
6803 * time if that has already happened. */
6804 if (bdrv_has_bds_parent(bs
, false)) {
6807 ret
= bdrv_inactivate_recurse(bs
);
6809 bdrv_next_cleanup(&it
);
6815 for (ctx
= aio_ctxs
; ctx
!= NULL
; ctx
= ctx
->next
) {
6816 AioContext
*aio_context
= ctx
->data
;
6817 aio_context_release(aio_context
);
6819 g_slist_free(aio_ctxs
);
6824 /**************************************************************/
6825 /* removable device support */
6828 * Return TRUE if the media is present
6830 bool bdrv_is_inserted(BlockDriverState
*bs
)
6832 BlockDriver
*drv
= bs
->drv
;
6839 if (drv
->bdrv_is_inserted
) {
6840 return drv
->bdrv_is_inserted(bs
);
6842 QLIST_FOREACH(child
, &bs
->children
, next
) {
6843 if (!bdrv_is_inserted(child
->bs
)) {
6851 * If eject_flag is TRUE, eject the media. Otherwise, close the tray
6853 void bdrv_eject(BlockDriverState
*bs
, bool eject_flag
)
6855 BlockDriver
*drv
= bs
->drv
;
6858 if (drv
&& drv
->bdrv_eject
) {
6859 drv
->bdrv_eject(bs
, eject_flag
);
6864 * Lock or unlock the media (if it is locked, the user won't be able
6865 * to eject it manually).
6867 void bdrv_lock_medium(BlockDriverState
*bs
, bool locked
)
6869 BlockDriver
*drv
= bs
->drv
;
6871 trace_bdrv_lock_medium(bs
, locked
);
6873 if (drv
&& drv
->bdrv_lock_medium
) {
6874 drv
->bdrv_lock_medium(bs
, locked
);
6878 /* Get a reference to bs */
6879 void bdrv_ref(BlockDriverState
*bs
)
6881 GLOBAL_STATE_CODE();
6885 /* Release a previously grabbed reference to bs.
6886 * If after releasing, reference count is zero, the BlockDriverState is
6888 void bdrv_unref(BlockDriverState
*bs
)
6890 GLOBAL_STATE_CODE();
6894 assert(bs
->refcnt
> 0);
6895 if (--bs
->refcnt
== 0) {
6900 struct BdrvOpBlocker
{
6902 QLIST_ENTRY(BdrvOpBlocker
) list
;
6905 bool bdrv_op_is_blocked(BlockDriverState
*bs
, BlockOpType op
, Error
**errp
)
6907 BdrvOpBlocker
*blocker
;
6908 GLOBAL_STATE_CODE();
6909 assert((int) op
>= 0 && op
< BLOCK_OP_TYPE_MAX
);
6910 if (!QLIST_EMPTY(&bs
->op_blockers
[op
])) {
6911 blocker
= QLIST_FIRST(&bs
->op_blockers
[op
]);
6912 error_propagate_prepend(errp
, error_copy(blocker
->reason
),
6913 "Node '%s' is busy: ",
6914 bdrv_get_device_or_node_name(bs
));
6920 void bdrv_op_block(BlockDriverState
*bs
, BlockOpType op
, Error
*reason
)
6922 BdrvOpBlocker
*blocker
;
6923 GLOBAL_STATE_CODE();
6924 assert((int) op
>= 0 && op
< BLOCK_OP_TYPE_MAX
);
6926 blocker
= g_new0(BdrvOpBlocker
, 1);
6927 blocker
->reason
= reason
;
6928 QLIST_INSERT_HEAD(&bs
->op_blockers
[op
], blocker
, list
);
6931 void bdrv_op_unblock(BlockDriverState
*bs
, BlockOpType op
, Error
*reason
)
6933 BdrvOpBlocker
*blocker
, *next
;
6934 GLOBAL_STATE_CODE();
6935 assert((int) op
>= 0 && op
< BLOCK_OP_TYPE_MAX
);
6936 QLIST_FOREACH_SAFE(blocker
, &bs
->op_blockers
[op
], list
, next
) {
6937 if (blocker
->reason
== reason
) {
6938 QLIST_REMOVE(blocker
, list
);
6944 void bdrv_op_block_all(BlockDriverState
*bs
, Error
*reason
)
6947 GLOBAL_STATE_CODE();
6948 for (i
= 0; i
< BLOCK_OP_TYPE_MAX
; i
++) {
6949 bdrv_op_block(bs
, i
, reason
);
6953 void bdrv_op_unblock_all(BlockDriverState
*bs
, Error
*reason
)
6956 GLOBAL_STATE_CODE();
6957 for (i
= 0; i
< BLOCK_OP_TYPE_MAX
; i
++) {
6958 bdrv_op_unblock(bs
, i
, reason
);
6962 bool bdrv_op_blocker_is_empty(BlockDriverState
*bs
)
6965 GLOBAL_STATE_CODE();
6966 for (i
= 0; i
< BLOCK_OP_TYPE_MAX
; i
++) {
6967 if (!QLIST_EMPTY(&bs
->op_blockers
[i
])) {
6974 void bdrv_img_create(const char *filename
, const char *fmt
,
6975 const char *base_filename
, const char *base_fmt
,
6976 char *options
, uint64_t img_size
, int flags
, bool quiet
,
6979 QemuOptsList
*create_opts
= NULL
;
6980 QemuOpts
*opts
= NULL
;
6981 const char *backing_fmt
, *backing_file
;
6983 BlockDriver
*drv
, *proto_drv
;
6984 Error
*local_err
= NULL
;
6987 GLOBAL_STATE_CODE();
6989 /* Find driver and parse its options */
6990 drv
= bdrv_find_format(fmt
);
6992 error_setg(errp
, "Unknown file format '%s'", fmt
);
6996 proto_drv
= bdrv_find_protocol(filename
, true, errp
);
7001 if (!drv
->create_opts
) {
7002 error_setg(errp
, "Format driver '%s' does not support image creation",
7007 if (!proto_drv
->create_opts
) {
7008 error_setg(errp
, "Protocol driver '%s' does not support image creation",
7009 proto_drv
->format_name
);
7013 /* Create parameter list */
7014 create_opts
= qemu_opts_append(create_opts
, drv
->create_opts
);
7015 create_opts
= qemu_opts_append(create_opts
, proto_drv
->create_opts
);
7017 opts
= qemu_opts_create(create_opts
, NULL
, 0, &error_abort
);
7019 /* Parse -o options */
7021 if (!qemu_opts_do_parse(opts
, options
, NULL
, errp
)) {
7026 if (!qemu_opt_get(opts
, BLOCK_OPT_SIZE
)) {
7027 qemu_opt_set_number(opts
, BLOCK_OPT_SIZE
, img_size
, &error_abort
);
7028 } else if (img_size
!= UINT64_C(-1)) {
7029 error_setg(errp
, "The image size must be specified only once");
7033 if (base_filename
) {
7034 if (!qemu_opt_set(opts
, BLOCK_OPT_BACKING_FILE
, base_filename
,
7036 error_setg(errp
, "Backing file not supported for file format '%s'",
7043 if (!qemu_opt_set(opts
, BLOCK_OPT_BACKING_FMT
, base_fmt
, NULL
)) {
7044 error_setg(errp
, "Backing file format not supported for file "
7045 "format '%s'", fmt
);
7050 backing_file
= qemu_opt_get(opts
, BLOCK_OPT_BACKING_FILE
);
7052 if (!strcmp(filename
, backing_file
)) {
7053 error_setg(errp
, "Error: Trying to create an image with the "
7054 "same filename as the backing file");
7057 if (backing_file
[0] == '\0') {
7058 error_setg(errp
, "Expected backing file name, got empty string");
7063 backing_fmt
= qemu_opt_get(opts
, BLOCK_OPT_BACKING_FMT
);
7065 /* The size for the image must always be specified, unless we have a backing
7066 * file and we have not been forbidden from opening it. */
7067 size
= qemu_opt_get_size(opts
, BLOCK_OPT_SIZE
, img_size
);
7068 if (backing_file
&& !(flags
& BDRV_O_NO_BACKING
)) {
7069 BlockDriverState
*bs
;
7072 QDict
*backing_options
= NULL
;
7075 bdrv_get_full_backing_filename_from_filename(filename
, backing_file
,
7080 assert(full_backing
);
7083 * No need to do I/O here, which allows us to open encrypted
7084 * backing images without needing the secret
7087 back_flags
&= ~(BDRV_O_RDWR
| BDRV_O_SNAPSHOT
| BDRV_O_NO_BACKING
);
7088 back_flags
|= BDRV_O_NO_IO
;
7090 backing_options
= qdict_new();
7092 qdict_put_str(backing_options
, "driver", backing_fmt
);
7094 qdict_put_bool(backing_options
, BDRV_OPT_FORCE_SHARE
, true);
7096 bs
= bdrv_open(full_backing
, NULL
, backing_options
, back_flags
,
7098 g_free(full_backing
);
7100 error_append_hint(&local_err
, "Could not open backing image.\n");
7104 error_setg(&local_err
,
7105 "Backing file specified without backing format");
7106 error_append_hint(&local_err
, "Detected format of %s.",
7107 bs
->drv
->format_name
);
7111 /* Opened BS, have no size */
7112 size
= bdrv_getlength(bs
);
7114 error_setg_errno(errp
, -size
, "Could not get size of '%s'",
7119 qemu_opt_set_number(opts
, BLOCK_OPT_SIZE
, size
, &error_abort
);
7123 /* (backing_file && !(flags & BDRV_O_NO_BACKING)) */
7124 } else if (backing_file
&& !backing_fmt
) {
7125 error_setg(&local_err
,
7126 "Backing file specified without backing format");
7131 error_setg(errp
, "Image creation needs a size parameter");
7136 printf("Formatting '%s', fmt=%s ", filename
, fmt
);
7137 qemu_opts_print(opts
, " ");
7142 ret
= bdrv_create(drv
, filename
, opts
, &local_err
);
7144 if (ret
== -EFBIG
) {
7145 /* This is generally a better message than whatever the driver would
7146 * deliver (especially because of the cluster_size_hint), since that
7147 * is most probably not much different from "image too large". */
7148 const char *cluster_size_hint
= "";
7149 if (qemu_opt_get_size(opts
, BLOCK_OPT_CLUSTER_SIZE
, 0)) {
7150 cluster_size_hint
= " (try using a larger cluster size)";
7152 error_setg(errp
, "The image size is too large for file format '%s'"
7153 "%s", fmt
, cluster_size_hint
);
7154 error_free(local_err
);
7159 qemu_opts_del(opts
);
7160 qemu_opts_free(create_opts
);
7161 error_propagate(errp
, local_err
);
7164 AioContext
*bdrv_get_aio_context(BlockDriverState
*bs
)
7167 return bs
? bs
->aio_context
: qemu_get_aio_context();
7170 AioContext
*coroutine_fn
bdrv_co_enter(BlockDriverState
*bs
)
7172 Coroutine
*self
= qemu_coroutine_self();
7173 AioContext
*old_ctx
= qemu_coroutine_get_aio_context(self
);
7174 AioContext
*new_ctx
;
7178 * Increase bs->in_flight to ensure that this operation is completed before
7179 * moving the node to a different AioContext. Read new_ctx only afterwards.
7181 bdrv_inc_in_flight(bs
);
7183 new_ctx
= bdrv_get_aio_context(bs
);
7184 aio_co_reschedule_self(new_ctx
);
7188 void coroutine_fn
bdrv_co_leave(BlockDriverState
*bs
, AioContext
*old_ctx
)
7191 aio_co_reschedule_self(old_ctx
);
7192 bdrv_dec_in_flight(bs
);
7195 void coroutine_fn
bdrv_co_lock(BlockDriverState
*bs
)
7197 AioContext
*ctx
= bdrv_get_aio_context(bs
);
7199 /* In the main thread, bs->aio_context won't change concurrently */
7200 assert(qemu_get_current_aio_context() == qemu_get_aio_context());
7203 * We're in coroutine context, so we already hold the lock of the main
7204 * loop AioContext. Don't lock it twice to avoid deadlocks.
7206 assert(qemu_in_coroutine());
7207 if (ctx
!= qemu_get_aio_context()) {
7208 aio_context_acquire(ctx
);
7212 void coroutine_fn
bdrv_co_unlock(BlockDriverState
*bs
)
7214 AioContext
*ctx
= bdrv_get_aio_context(bs
);
7216 assert(qemu_in_coroutine());
7217 if (ctx
!= qemu_get_aio_context()) {
7218 aio_context_release(ctx
);
7222 void bdrv_coroutine_enter(BlockDriverState
*bs
, Coroutine
*co
)
7225 aio_co_enter(bdrv_get_aio_context(bs
), co
);
7228 static void bdrv_do_remove_aio_context_notifier(BdrvAioNotifier
*ban
)
7230 GLOBAL_STATE_CODE();
7231 QLIST_REMOVE(ban
, list
);
7235 static void bdrv_detach_aio_context(BlockDriverState
*bs
)
7237 BdrvAioNotifier
*baf
, *baf_tmp
;
7239 assert(!bs
->walking_aio_notifiers
);
7240 bs
->walking_aio_notifiers
= true;
7241 QLIST_FOREACH_SAFE(baf
, &bs
->aio_notifiers
, list
, baf_tmp
) {
7243 bdrv_do_remove_aio_context_notifier(baf
);
7245 baf
->detach_aio_context(baf
->opaque
);
7248 /* Never mind iterating again to check for ->deleted. bdrv_close() will
7249 * remove remaining aio notifiers if we aren't called again.
7251 bs
->walking_aio_notifiers
= false;
7253 if (bs
->drv
&& bs
->drv
->bdrv_detach_aio_context
) {
7254 bs
->drv
->bdrv_detach_aio_context(bs
);
7257 if (bs
->quiesce_counter
) {
7258 aio_enable_external(bs
->aio_context
);
7260 bs
->aio_context
= NULL
;
7263 static void bdrv_attach_aio_context(BlockDriverState
*bs
,
7264 AioContext
*new_context
)
7266 BdrvAioNotifier
*ban
, *ban_tmp
;
7268 if (bs
->quiesce_counter
) {
7269 aio_disable_external(new_context
);
7272 bs
->aio_context
= new_context
;
7274 if (bs
->drv
&& bs
->drv
->bdrv_attach_aio_context
) {
7275 bs
->drv
->bdrv_attach_aio_context(bs
, new_context
);
7278 assert(!bs
->walking_aio_notifiers
);
7279 bs
->walking_aio_notifiers
= true;
7280 QLIST_FOREACH_SAFE(ban
, &bs
->aio_notifiers
, list
, ban_tmp
) {
7282 bdrv_do_remove_aio_context_notifier(ban
);
7284 ban
->attached_aio_context(new_context
, ban
->opaque
);
7287 bs
->walking_aio_notifiers
= false;
7291 * Changes the AioContext used for fd handlers, timers, and BHs by this
7292 * BlockDriverState and all its children and parents.
7294 * Must be called from the main AioContext.
7296 * The caller must own the AioContext lock for the old AioContext of bs, but it
7297 * must not own the AioContext lock for new_context (unless new_context is the
7298 * same as the current context of bs).
7300 * @ignore will accumulate all visited BdrvChild object. The caller is
7301 * responsible for freeing the list afterwards.
7303 void bdrv_set_aio_context_ignore(BlockDriverState
*bs
,
7304 AioContext
*new_context
, GSList
**ignore
)
7306 AioContext
*old_context
= bdrv_get_aio_context(bs
);
7307 GSList
*children_to_process
= NULL
;
7308 GSList
*parents_to_process
= NULL
;
7310 BdrvChild
*child
, *parent
;
7312 g_assert(qemu_get_current_aio_context() == qemu_get_aio_context());
7314 if (old_context
== new_context
) {
7318 bdrv_drained_begin(bs
);
7320 QLIST_FOREACH(child
, &bs
->children
, next
) {
7321 if (g_slist_find(*ignore
, child
)) {
7324 *ignore
= g_slist_prepend(*ignore
, child
);
7325 children_to_process
= g_slist_prepend(children_to_process
, child
);
7328 QLIST_FOREACH(parent
, &bs
->parents
, next_parent
) {
7329 if (g_slist_find(*ignore
, parent
)) {
7332 *ignore
= g_slist_prepend(*ignore
, parent
);
7333 parents_to_process
= g_slist_prepend(parents_to_process
, parent
);
7336 for (entry
= children_to_process
;
7338 entry
= g_slist_next(entry
)) {
7339 child
= entry
->data
;
7340 bdrv_set_aio_context_ignore(child
->bs
, new_context
, ignore
);
7342 g_slist_free(children_to_process
);
7344 for (entry
= parents_to_process
;
7346 entry
= g_slist_next(entry
)) {
7347 parent
= entry
->data
;
7348 assert(parent
->klass
->set_aio_ctx
);
7349 parent
->klass
->set_aio_ctx(parent
, new_context
, ignore
);
7351 g_slist_free(parents_to_process
);
7353 bdrv_detach_aio_context(bs
);
7355 /* Acquire the new context, if necessary */
7356 if (qemu_get_aio_context() != new_context
) {
7357 aio_context_acquire(new_context
);
7360 bdrv_attach_aio_context(bs
, new_context
);
7363 * If this function was recursively called from
7364 * bdrv_set_aio_context_ignore(), there may be nodes in the
7365 * subtree that have not yet been moved to the new AioContext.
7366 * Release the old one so bdrv_drained_end() can poll them.
7368 if (qemu_get_aio_context() != old_context
) {
7369 aio_context_release(old_context
);
7372 bdrv_drained_end(bs
);
7374 if (qemu_get_aio_context() != old_context
) {
7375 aio_context_acquire(old_context
);
7377 if (qemu_get_aio_context() != new_context
) {
7378 aio_context_release(new_context
);
7382 static bool bdrv_parent_can_set_aio_context(BdrvChild
*c
, AioContext
*ctx
,
7383 GSList
**ignore
, Error
**errp
)
7385 if (g_slist_find(*ignore
, c
)) {
7388 *ignore
= g_slist_prepend(*ignore
, c
);
7391 * A BdrvChildClass that doesn't handle AioContext changes cannot
7392 * tolerate any AioContext changes
7394 if (!c
->klass
->can_set_aio_ctx
) {
7395 char *user
= bdrv_child_user_desc(c
);
7396 error_setg(errp
, "Changing iothreads is not supported by %s", user
);
7400 if (!c
->klass
->can_set_aio_ctx(c
, ctx
, ignore
, errp
)) {
7401 assert(!errp
|| *errp
);
7407 bool bdrv_child_can_set_aio_context(BdrvChild
*c
, AioContext
*ctx
,
7408 GSList
**ignore
, Error
**errp
)
7410 GLOBAL_STATE_CODE();
7411 if (g_slist_find(*ignore
, c
)) {
7414 *ignore
= g_slist_prepend(*ignore
, c
);
7415 return bdrv_can_set_aio_context(c
->bs
, ctx
, ignore
, errp
);
7418 /* @ignore will accumulate all visited BdrvChild object. The caller is
7419 * responsible for freeing the list afterwards. */
7420 bool bdrv_can_set_aio_context(BlockDriverState
*bs
, AioContext
*ctx
,
7421 GSList
**ignore
, Error
**errp
)
7425 if (bdrv_get_aio_context(bs
) == ctx
) {
7429 GLOBAL_STATE_CODE();
7431 QLIST_FOREACH(c
, &bs
->parents
, next_parent
) {
7432 if (!bdrv_parent_can_set_aio_context(c
, ctx
, ignore
, errp
)) {
7436 QLIST_FOREACH(c
, &bs
->children
, next
) {
7437 if (!bdrv_child_can_set_aio_context(c
, ctx
, ignore
, errp
)) {
7445 int bdrv_child_try_set_aio_context(BlockDriverState
*bs
, AioContext
*ctx
,
7446 BdrvChild
*ignore_child
, Error
**errp
)
7451 GLOBAL_STATE_CODE();
7453 ignore
= ignore_child
? g_slist_prepend(NULL
, ignore_child
) : NULL
;
7454 ret
= bdrv_can_set_aio_context(bs
, ctx
, &ignore
, errp
);
7455 g_slist_free(ignore
);
7461 ignore
= ignore_child
? g_slist_prepend(NULL
, ignore_child
) : NULL
;
7462 bdrv_set_aio_context_ignore(bs
, ctx
, &ignore
);
7463 g_slist_free(ignore
);
7468 int bdrv_try_set_aio_context(BlockDriverState
*bs
, AioContext
*ctx
,
7471 GLOBAL_STATE_CODE();
7472 return bdrv_child_try_set_aio_context(bs
, ctx
, NULL
, errp
);
7475 void bdrv_add_aio_context_notifier(BlockDriverState
*bs
,
7476 void (*attached_aio_context
)(AioContext
*new_context
, void *opaque
),
7477 void (*detach_aio_context
)(void *opaque
), void *opaque
)
7479 BdrvAioNotifier
*ban
= g_new(BdrvAioNotifier
, 1);
7480 *ban
= (BdrvAioNotifier
){
7481 .attached_aio_context
= attached_aio_context
,
7482 .detach_aio_context
= detach_aio_context
,
7485 GLOBAL_STATE_CODE();
7487 QLIST_INSERT_HEAD(&bs
->aio_notifiers
, ban
, list
);
7490 void bdrv_remove_aio_context_notifier(BlockDriverState
*bs
,
7491 void (*attached_aio_context
)(AioContext
*,
7493 void (*detach_aio_context
)(void *),
7496 BdrvAioNotifier
*ban
, *ban_next
;
7497 GLOBAL_STATE_CODE();
7499 QLIST_FOREACH_SAFE(ban
, &bs
->aio_notifiers
, list
, ban_next
) {
7500 if (ban
->attached_aio_context
== attached_aio_context
&&
7501 ban
->detach_aio_context
== detach_aio_context
&&
7502 ban
->opaque
== opaque
&&
7503 ban
->deleted
== false)
7505 if (bs
->walking_aio_notifiers
) {
7506 ban
->deleted
= true;
7508 bdrv_do_remove_aio_context_notifier(ban
);
7517 int bdrv_amend_options(BlockDriverState
*bs
, QemuOpts
*opts
,
7518 BlockDriverAmendStatusCB
*status_cb
, void *cb_opaque
,
7522 GLOBAL_STATE_CODE();
7524 error_setg(errp
, "Node is ejected");
7527 if (!bs
->drv
->bdrv_amend_options
) {
7528 error_setg(errp
, "Block driver '%s' does not support option amendment",
7529 bs
->drv
->format_name
);
7532 return bs
->drv
->bdrv_amend_options(bs
, opts
, status_cb
,
7533 cb_opaque
, force
, errp
);
7537 * This function checks whether the given @to_replace is allowed to be
7538 * replaced by a node that always shows the same data as @bs. This is
7539 * used for example to verify whether the mirror job can replace
7540 * @to_replace by the target mirrored from @bs.
7541 * To be replaceable, @bs and @to_replace may either be guaranteed to
7542 * always show the same data (because they are only connected through
7543 * filters), or some driver may allow replacing one of its children
7544 * because it can guarantee that this child's data is not visible at
7545 * all (for example, for dissenting quorum children that have no other
7548 bool bdrv_recurse_can_replace(BlockDriverState
*bs
,
7549 BlockDriverState
*to_replace
)
7551 BlockDriverState
*filtered
;
7553 GLOBAL_STATE_CODE();
7555 if (!bs
|| !bs
->drv
) {
7559 if (bs
== to_replace
) {
7563 /* See what the driver can do */
7564 if (bs
->drv
->bdrv_recurse_can_replace
) {
7565 return bs
->drv
->bdrv_recurse_can_replace(bs
, to_replace
);
7568 /* For filters without an own implementation, we can recurse on our own */
7569 filtered
= bdrv_filter_bs(bs
);
7571 return bdrv_recurse_can_replace(filtered
, to_replace
);
7579 * Check whether the given @node_name can be replaced by a node that
7580 * has the same data as @parent_bs. If so, return @node_name's BDS;
7583 * @node_name must be a (recursive) *child of @parent_bs (or this
7584 * function will return NULL).
7586 * The result (whether the node can be replaced or not) is only valid
7587 * for as long as no graph or permission changes occur.
7589 BlockDriverState
*check_to_replace_node(BlockDriverState
*parent_bs
,
7590 const char *node_name
, Error
**errp
)
7592 BlockDriverState
*to_replace_bs
= bdrv_find_node(node_name
);
7593 AioContext
*aio_context
;
7595 GLOBAL_STATE_CODE();
7597 if (!to_replace_bs
) {
7598 error_setg(errp
, "Failed to find node with node-name='%s'", node_name
);
7602 aio_context
= bdrv_get_aio_context(to_replace_bs
);
7603 aio_context_acquire(aio_context
);
7605 if (bdrv_op_is_blocked(to_replace_bs
, BLOCK_OP_TYPE_REPLACE
, errp
)) {
7606 to_replace_bs
= NULL
;
7610 /* We don't want arbitrary node of the BDS chain to be replaced only the top
7611 * most non filter in order to prevent data corruption.
7612 * Another benefit is that this tests exclude backing files which are
7613 * blocked by the backing blockers.
7615 if (!bdrv_recurse_can_replace(parent_bs
, to_replace_bs
)) {
7616 error_setg(errp
, "Cannot replace '%s' by a node mirrored from '%s', "
7617 "because it cannot be guaranteed that doing so would not "
7618 "lead to an abrupt change of visible data",
7619 node_name
, parent_bs
->node_name
);
7620 to_replace_bs
= NULL
;
7625 aio_context_release(aio_context
);
7626 return to_replace_bs
;
7630 * Iterates through the list of runtime option keys that are said to
7631 * be "strong" for a BDS. An option is called "strong" if it changes
7632 * a BDS's data. For example, the null block driver's "size" and
7633 * "read-zeroes" options are strong, but its "latency-ns" option is
7636 * If a key returned by this function ends with a dot, all options
7637 * starting with that prefix are strong.
7639 static const char *const *strong_options(BlockDriverState
*bs
,
7640 const char *const *curopt
)
7642 static const char *const global_options
[] = {
7643 "driver", "filename", NULL
7647 return &global_options
[0];
7651 if (curopt
== &global_options
[ARRAY_SIZE(global_options
) - 1] && bs
->drv
) {
7652 curopt
= bs
->drv
->strong_runtime_opts
;
7655 return (curopt
&& *curopt
) ? curopt
: NULL
;
7659 * Copies all strong runtime options from bs->options to the given
7660 * QDict. The set of strong option keys is determined by invoking
7663 * Returns true iff any strong option was present in bs->options (and
7664 * thus copied to the target QDict) with the exception of "filename"
7665 * and "driver". The caller is expected to use this value to decide
7666 * whether the existence of strong options prevents the generation of
7669 static bool append_strong_runtime_options(QDict
*d
, BlockDriverState
*bs
)
7671 bool found_any
= false;
7672 const char *const *option_name
= NULL
;
7678 while ((option_name
= strong_options(bs
, option_name
))) {
7679 bool option_given
= false;
7681 assert(strlen(*option_name
) > 0);
7682 if ((*option_name
)[strlen(*option_name
) - 1] != '.') {
7683 QObject
*entry
= qdict_get(bs
->options
, *option_name
);
7688 qdict_put_obj(d
, *option_name
, qobject_ref(entry
));
7689 option_given
= true;
7691 const QDictEntry
*entry
;
7692 for (entry
= qdict_first(bs
->options
); entry
;
7693 entry
= qdict_next(bs
->options
, entry
))
7695 if (strstart(qdict_entry_key(entry
), *option_name
, NULL
)) {
7696 qdict_put_obj(d
, qdict_entry_key(entry
),
7697 qobject_ref(qdict_entry_value(entry
)));
7698 option_given
= true;
7703 /* While "driver" and "filename" need to be included in a JSON filename,
7704 * their existence does not prohibit generation of a plain filename. */
7705 if (!found_any
&& option_given
&&
7706 strcmp(*option_name
, "driver") && strcmp(*option_name
, "filename"))
7712 if (!qdict_haskey(d
, "driver")) {
7713 /* Drivers created with bdrv_new_open_driver() may not have a
7714 * @driver option. Add it here. */
7715 qdict_put_str(d
, "driver", bs
->drv
->format_name
);
7721 /* Note: This function may return false positives; it may return true
7722 * even if opening the backing file specified by bs's image header
7723 * would result in exactly bs->backing. */
7724 static bool bdrv_backing_overridden(BlockDriverState
*bs
)
7726 GLOBAL_STATE_CODE();
7728 return strcmp(bs
->auto_backing_file
,
7729 bs
->backing
->bs
->filename
);
7731 /* No backing BDS, so if the image header reports any backing
7732 * file, it must have been suppressed */
7733 return bs
->auto_backing_file
[0] != '\0';
7737 /* Updates the following BDS fields:
7738 * - exact_filename: A filename which may be used for opening a block device
7739 * which (mostly) equals the given BDS (even without any
7740 * other options; so reading and writing must return the same
7741 * results, but caching etc. may be different)
7742 * - full_open_options: Options which, when given when opening a block device
7743 * (without a filename), result in a BDS (mostly)
7744 * equalling the given one
7745 * - filename: If exact_filename is set, it is copied here. Otherwise,
7746 * full_open_options is converted to a JSON object, prefixed with
7747 * "json:" (for use through the JSON pseudo protocol) and put here.
7749 void bdrv_refresh_filename(BlockDriverState
*bs
)
7751 BlockDriver
*drv
= bs
->drv
;
7753 BlockDriverState
*primary_child_bs
;
7755 bool backing_overridden
;
7756 bool generate_json_filename
; /* Whether our default implementation should
7757 fill exact_filename (false) or not (true) */
7759 GLOBAL_STATE_CODE();
7765 /* This BDS's file name may depend on any of its children's file names, so
7766 * refresh those first */
7767 QLIST_FOREACH(child
, &bs
->children
, next
) {
7768 bdrv_refresh_filename(child
->bs
);
7772 /* For implicit nodes, just copy everything from the single child */
7773 child
= QLIST_FIRST(&bs
->children
);
7774 assert(QLIST_NEXT(child
, next
) == NULL
);
7776 pstrcpy(bs
->exact_filename
, sizeof(bs
->exact_filename
),
7777 child
->bs
->exact_filename
);
7778 pstrcpy(bs
->filename
, sizeof(bs
->filename
), child
->bs
->filename
);
7780 qobject_unref(bs
->full_open_options
);
7781 bs
->full_open_options
= qobject_ref(child
->bs
->full_open_options
);
7786 backing_overridden
= bdrv_backing_overridden(bs
);
7788 if (bs
->open_flags
& BDRV_O_NO_IO
) {
7789 /* Without I/O, the backing file does not change anything.
7790 * Therefore, in such a case (primarily qemu-img), we can
7791 * pretend the backing file has not been overridden even if
7792 * it technically has been. */
7793 backing_overridden
= false;
7796 /* Gather the options QDict */
7798 generate_json_filename
= append_strong_runtime_options(opts
, bs
);
7799 generate_json_filename
|= backing_overridden
;
7801 if (drv
->bdrv_gather_child_options
) {
7802 /* Some block drivers may not want to present all of their children's
7803 * options, or name them differently from BdrvChild.name */
7804 drv
->bdrv_gather_child_options(bs
, opts
, backing_overridden
);
7806 QLIST_FOREACH(child
, &bs
->children
, next
) {
7807 if (child
== bs
->backing
&& !backing_overridden
) {
7808 /* We can skip the backing BDS if it has not been overridden */
7812 qdict_put(opts
, child
->name
,
7813 qobject_ref(child
->bs
->full_open_options
));
7816 if (backing_overridden
&& !bs
->backing
) {
7817 /* Force no backing file */
7818 qdict_put_null(opts
, "backing");
7822 qobject_unref(bs
->full_open_options
);
7823 bs
->full_open_options
= opts
;
7825 primary_child_bs
= bdrv_primary_bs(bs
);
7827 if (drv
->bdrv_refresh_filename
) {
7828 /* Obsolete information is of no use here, so drop the old file name
7829 * information before refreshing it */
7830 bs
->exact_filename
[0] = '\0';
7832 drv
->bdrv_refresh_filename(bs
);
7833 } else if (primary_child_bs
) {
7835 * Try to reconstruct valid information from the underlying
7836 * file -- this only works for format nodes (filter nodes
7837 * cannot be probed and as such must be selected by the user
7838 * either through an options dict, or through a special
7839 * filename which the filter driver must construct in its
7840 * .bdrv_refresh_filename() implementation).
7843 bs
->exact_filename
[0] = '\0';
7846 * We can use the underlying file's filename if:
7847 * - it has a filename,
7848 * - the current BDS is not a filter,
7849 * - the file is a protocol BDS, and
7850 * - opening that file (as this BDS's format) will automatically create
7851 * the BDS tree we have right now, that is:
7852 * - the user did not significantly change this BDS's behavior with
7853 * some explicit (strong) options
7854 * - no non-file child of this BDS has been overridden by the user
7855 * Both of these conditions are represented by generate_json_filename.
7857 if (primary_child_bs
->exact_filename
[0] &&
7858 primary_child_bs
->drv
->bdrv_file_open
&&
7859 !drv
->is_filter
&& !generate_json_filename
)
7861 strcpy(bs
->exact_filename
, primary_child_bs
->exact_filename
);
7865 if (bs
->exact_filename
[0]) {
7866 pstrcpy(bs
->filename
, sizeof(bs
->filename
), bs
->exact_filename
);
7868 GString
*json
= qobject_to_json(QOBJECT(bs
->full_open_options
));
7869 if (snprintf(bs
->filename
, sizeof(bs
->filename
), "json:%s",
7870 json
->str
) >= sizeof(bs
->filename
)) {
7871 /* Give user a hint if we truncated things. */
7872 strcpy(bs
->filename
+ sizeof(bs
->filename
) - 4, "...");
7874 g_string_free(json
, true);
7878 char *bdrv_dirname(BlockDriverState
*bs
, Error
**errp
)
7880 BlockDriver
*drv
= bs
->drv
;
7881 BlockDriverState
*child_bs
;
7883 GLOBAL_STATE_CODE();
7886 error_setg(errp
, "Node '%s' is ejected", bs
->node_name
);
7890 if (drv
->bdrv_dirname
) {
7891 return drv
->bdrv_dirname(bs
, errp
);
7894 child_bs
= bdrv_primary_bs(bs
);
7896 return bdrv_dirname(child_bs
, errp
);
7899 bdrv_refresh_filename(bs
);
7900 if (bs
->exact_filename
[0] != '\0') {
7901 return path_combine(bs
->exact_filename
, "");
7904 error_setg(errp
, "Cannot generate a base directory for %s nodes",
7910 * Hot add/remove a BDS's child. So the user can take a child offline when
7911 * it is broken and take a new child online
7913 void bdrv_add_child(BlockDriverState
*parent_bs
, BlockDriverState
*child_bs
,
7916 GLOBAL_STATE_CODE();
7917 if (!parent_bs
->drv
|| !parent_bs
->drv
->bdrv_add_child
) {
7918 error_setg(errp
, "The node %s does not support adding a child",
7919 bdrv_get_device_or_node_name(parent_bs
));
7923 if (!QLIST_EMPTY(&child_bs
->parents
)) {
7924 error_setg(errp
, "The node %s already has a parent",
7925 child_bs
->node_name
);
7929 parent_bs
->drv
->bdrv_add_child(parent_bs
, child_bs
, errp
);
7932 void bdrv_del_child(BlockDriverState
*parent_bs
, BdrvChild
*child
, Error
**errp
)
7936 GLOBAL_STATE_CODE();
7937 if (!parent_bs
->drv
|| !parent_bs
->drv
->bdrv_del_child
) {
7938 error_setg(errp
, "The node %s does not support removing a child",
7939 bdrv_get_device_or_node_name(parent_bs
));
7943 QLIST_FOREACH(tmp
, &parent_bs
->children
, next
) {
7950 error_setg(errp
, "The node %s does not have a child named %s",
7951 bdrv_get_device_or_node_name(parent_bs
),
7952 bdrv_get_device_or_node_name(child
->bs
));
7956 parent_bs
->drv
->bdrv_del_child(parent_bs
, child
, errp
);
7959 int bdrv_make_empty(BdrvChild
*c
, Error
**errp
)
7961 BlockDriver
*drv
= c
->bs
->drv
;
7964 GLOBAL_STATE_CODE();
7965 assert(c
->perm
& (BLK_PERM_WRITE
| BLK_PERM_WRITE_UNCHANGED
));
7967 if (!drv
->bdrv_make_empty
) {
7968 error_setg(errp
, "%s does not support emptying nodes",
7973 ret
= drv
->bdrv_make_empty(c
->bs
);
7975 error_setg_errno(errp
, -ret
, "Failed to empty %s",
7984 * Return the child that @bs acts as an overlay for, and from which data may be
7985 * copied in COW or COR operations. Usually this is the backing file.
7987 BdrvChild
*bdrv_cow_child(BlockDriverState
*bs
)
7991 if (!bs
|| !bs
->drv
) {
7995 if (bs
->drv
->is_filter
) {
8003 assert(bs
->backing
->role
& BDRV_CHILD_COW
);
8008 * If @bs acts as a filter for exactly one of its children, return
8011 BdrvChild
*bdrv_filter_child(BlockDriverState
*bs
)
8016 if (!bs
|| !bs
->drv
) {
8020 if (!bs
->drv
->is_filter
) {
8024 /* Only one of @backing or @file may be used */
8025 assert(!(bs
->backing
&& bs
->file
));
8027 c
= bs
->backing
?: bs
->file
;
8032 assert(c
->role
& BDRV_CHILD_FILTERED
);
8037 * Return either the result of bdrv_cow_child() or bdrv_filter_child(),
8038 * whichever is non-NULL.
8040 * Return NULL if both are NULL.
8042 BdrvChild
*bdrv_filter_or_cow_child(BlockDriverState
*bs
)
8044 BdrvChild
*cow_child
= bdrv_cow_child(bs
);
8045 BdrvChild
*filter_child
= bdrv_filter_child(bs
);
8048 /* Filter nodes cannot have COW backing files */
8049 assert(!(cow_child
&& filter_child
));
8051 return cow_child
?: filter_child
;
8055 * Return the primary child of this node: For filters, that is the
8056 * filtered child. For other nodes, that is usually the child storing
8058 * (A generally more helpful description is that this is (usually) the
8059 * child that has the same filename as @bs.)
8061 * Drivers do not necessarily have a primary child; for example quorum
8064 BdrvChild
*bdrv_primary_child(BlockDriverState
*bs
)
8066 BdrvChild
*c
, *found
= NULL
;
8069 QLIST_FOREACH(c
, &bs
->children
, next
) {
8070 if (c
->role
& BDRV_CHILD_PRIMARY
) {
8079 static BlockDriverState
*bdrv_do_skip_filters(BlockDriverState
*bs
,
8080 bool stop_on_explicit_filter
)
8088 while (!(stop_on_explicit_filter
&& !bs
->implicit
)) {
8089 c
= bdrv_filter_child(bs
);
8092 * A filter that is embedded in a working block graph must
8093 * have a child. Assert this here so this function does
8094 * not return a filter node that is not expected by the
8097 assert(!bs
->drv
|| !bs
->drv
->is_filter
);
8103 * Note that this treats nodes with bs->drv == NULL as not being
8104 * filters (bs->drv == NULL should be replaced by something else
8106 * The advantage of this behavior is that this function will thus
8107 * always return a non-NULL value (given a non-NULL @bs).
8114 * Return the first BDS that has not been added implicitly or that
8115 * does not have a filtered child down the chain starting from @bs
8116 * (including @bs itself).
8118 BlockDriverState
*bdrv_skip_implicit_filters(BlockDriverState
*bs
)
8120 GLOBAL_STATE_CODE();
8121 return bdrv_do_skip_filters(bs
, true);
8125 * Return the first BDS that does not have a filtered child down the
8126 * chain starting from @bs (including @bs itself).
8128 BlockDriverState
*bdrv_skip_filters(BlockDriverState
*bs
)
8131 return bdrv_do_skip_filters(bs
, false);
8135 * For a backing chain, return the first non-filter backing image of
8136 * the first non-filter image.
8138 BlockDriverState
*bdrv_backing_chain_next(BlockDriverState
*bs
)
8141 return bdrv_skip_filters(bdrv_cow_bs(bdrv_skip_filters(bs
)));
8145 * Check whether [offset, offset + bytes) overlaps with the cached
8146 * block-status data region.
8148 * If so, and @pnum is not NULL, set *pnum to `bsc.data_end - offset`,
8149 * which is what bdrv_bsc_is_data()'s interface needs.
8150 * Otherwise, *pnum is not touched.
8152 static bool bdrv_bsc_range_overlaps_locked(BlockDriverState
*bs
,
8153 int64_t offset
, int64_t bytes
,
8156 BdrvBlockStatusCache
*bsc
= qatomic_rcu_read(&bs
->block_status_cache
);
8160 qatomic_read(&bsc
->valid
) &&
8161 ranges_overlap(offset
, bytes
, bsc
->data_start
,
8162 bsc
->data_end
- bsc
->data_start
);
8164 if (overlaps
&& pnum
) {
8165 *pnum
= bsc
->data_end
- offset
;
8172 * See block_int.h for this function's documentation.
8174 bool bdrv_bsc_is_data(BlockDriverState
*bs
, int64_t offset
, int64_t *pnum
)
8177 RCU_READ_LOCK_GUARD();
8178 return bdrv_bsc_range_overlaps_locked(bs
, offset
, 1, pnum
);
8182 * See block_int.h for this function's documentation.
8184 void bdrv_bsc_invalidate_range(BlockDriverState
*bs
,
8185 int64_t offset
, int64_t bytes
)
8188 RCU_READ_LOCK_GUARD();
8190 if (bdrv_bsc_range_overlaps_locked(bs
, offset
, bytes
, NULL
)) {
8191 qatomic_set(&bs
->block_status_cache
->valid
, false);
8196 * See block_int.h for this function's documentation.
8198 void bdrv_bsc_fill(BlockDriverState
*bs
, int64_t offset
, int64_t bytes
)
8200 BdrvBlockStatusCache
*new_bsc
= g_new(BdrvBlockStatusCache
, 1);
8201 BdrvBlockStatusCache
*old_bsc
;
8204 *new_bsc
= (BdrvBlockStatusCache
) {
8206 .data_start
= offset
,
8207 .data_end
= offset
+ bytes
,
8210 QEMU_LOCK_GUARD(&bs
->bsc_modify_lock
);
8212 old_bsc
= qatomic_rcu_read(&bs
->block_status_cache
);
8213 qatomic_rcu_set(&bs
->block_status_cache
, new_bsc
);
8215 g_free_rcu(old_bsc
, rcu
);