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
)
442 QLIST_FOREACH(drv1
, &bdrv_drivers
, list
) {
443 if (!strcmp(drv1
->format_name
, format_name
)) {
451 BlockDriver
*bdrv_find_format(const char *format_name
)
458 drv1
= bdrv_do_find_format(format_name
);
463 /* The driver isn't registered, maybe we need to load a module */
464 for (i
= 0; i
< (int)ARRAY_SIZE(block_driver_modules
); ++i
) {
465 if (!strcmp(block_driver_modules
[i
].format_name
, format_name
)) {
466 block_module_load_one(block_driver_modules
[i
].library_name
);
471 return bdrv_do_find_format(format_name
);
474 static int bdrv_format_is_whitelisted(const char *format_name
, bool read_only
)
476 static const char *whitelist_rw
[] = {
477 CONFIG_BDRV_RW_WHITELIST
480 static const char *whitelist_ro
[] = {
481 CONFIG_BDRV_RO_WHITELIST
486 if (!whitelist_rw
[0] && !whitelist_ro
[0]) {
487 return 1; /* no whitelist, anything goes */
490 for (p
= whitelist_rw
; *p
; p
++) {
491 if (!strcmp(format_name
, *p
)) {
496 for (p
= whitelist_ro
; *p
; p
++) {
497 if (!strcmp(format_name
, *p
)) {
505 int bdrv_is_whitelisted(BlockDriver
*drv
, bool read_only
)
508 return bdrv_format_is_whitelisted(drv
->format_name
, read_only
);
511 bool bdrv_uses_whitelist(void)
513 return use_bdrv_whitelist
;
516 typedef struct CreateCo
{
524 static void coroutine_fn
bdrv_create_co_entry(void *opaque
)
526 Error
*local_err
= NULL
;
529 CreateCo
*cco
= opaque
;
532 ret
= cco
->drv
->bdrv_co_create_opts(cco
->drv
,
533 cco
->filename
, cco
->opts
, &local_err
);
534 error_propagate(&cco
->err
, local_err
);
538 int bdrv_create(BlockDriver
*drv
, const char* filename
,
539 QemuOpts
*opts
, Error
**errp
)
548 .filename
= g_strdup(filename
),
554 if (!drv
->bdrv_co_create_opts
) {
555 error_setg(errp
, "Driver '%s' does not support image creation", drv
->format_name
);
560 if (qemu_in_coroutine()) {
561 /* Fast-path if already in coroutine context */
562 bdrv_create_co_entry(&cco
);
564 co
= qemu_coroutine_create(bdrv_create_co_entry
, &cco
);
565 qemu_coroutine_enter(co
);
566 while (cco
.ret
== NOT_DONE
) {
567 aio_poll(qemu_get_aio_context(), true);
574 error_propagate(errp
, cco
.err
);
576 error_setg_errno(errp
, -ret
, "Could not create image");
581 g_free(cco
.filename
);
586 * Helper function for bdrv_create_file_fallback(): Resize @blk to at
587 * least the given @minimum_size.
589 * On success, return @blk's actual length.
590 * Otherwise, return -errno.
592 static int64_t create_file_fallback_truncate(BlockBackend
*blk
,
593 int64_t minimum_size
, Error
**errp
)
595 Error
*local_err
= NULL
;
599 ret
= blk_truncate(blk
, minimum_size
, false, PREALLOC_MODE_OFF
, 0,
601 if (ret
< 0 && ret
!= -ENOTSUP
) {
602 error_propagate(errp
, local_err
);
606 size
= blk_getlength(blk
);
608 error_free(local_err
);
609 error_setg_errno(errp
, -size
,
610 "Failed to inquire the new image file's length");
614 if (size
< minimum_size
) {
615 /* Need to grow the image, but we failed to do that */
616 error_propagate(errp
, local_err
);
620 error_free(local_err
);
627 * Helper function for bdrv_create_file_fallback(): Zero the first
628 * sector to remove any potentially pre-existing image header.
630 static int create_file_fallback_zero_first_sector(BlockBackend
*blk
,
631 int64_t current_size
,
634 int64_t bytes_to_clear
;
637 bytes_to_clear
= MIN(current_size
, BDRV_SECTOR_SIZE
);
638 if (bytes_to_clear
) {
639 ret
= blk_pwrite_zeroes(blk
, 0, bytes_to_clear
, BDRV_REQ_MAY_UNMAP
);
641 error_setg_errno(errp
, -ret
,
642 "Failed to clear the new image's first sector");
651 * Simple implementation of bdrv_co_create_opts for protocol drivers
652 * which only support creation via opening a file
653 * (usually existing raw storage device)
655 int coroutine_fn
bdrv_co_create_opts_simple(BlockDriver
*drv
,
656 const char *filename
,
664 PreallocMode prealloc
;
665 Error
*local_err
= NULL
;
670 size
= qemu_opt_get_size_del(opts
, BLOCK_OPT_SIZE
, 0);
671 buf
= qemu_opt_get_del(opts
, BLOCK_OPT_PREALLOC
);
672 prealloc
= qapi_enum_parse(&PreallocMode_lookup
, buf
,
673 PREALLOC_MODE_OFF
, &local_err
);
676 error_propagate(errp
, local_err
);
680 if (prealloc
!= PREALLOC_MODE_OFF
) {
681 error_setg(errp
, "Unsupported preallocation mode '%s'",
682 PreallocMode_str(prealloc
));
686 options
= qdict_new();
687 qdict_put_str(options
, "driver", drv
->format_name
);
689 blk
= blk_new_open(filename
, NULL
, options
,
690 BDRV_O_RDWR
| BDRV_O_RESIZE
, errp
);
692 error_prepend(errp
, "Protocol driver '%s' does not support image "
693 "creation, and opening the image failed: ",
698 size
= create_file_fallback_truncate(blk
, size
, errp
);
704 ret
= create_file_fallback_zero_first_sector(blk
, size
, errp
);
715 int bdrv_create_file(const char *filename
, QemuOpts
*opts
, Error
**errp
)
717 QemuOpts
*protocol_opts
;
724 drv
= bdrv_find_protocol(filename
, true, errp
);
729 if (!drv
->create_opts
) {
730 error_setg(errp
, "Driver '%s' does not support image creation",
736 * 'opts' contains a QemuOptsList with a combination of format and protocol
739 * The format properly removes its options, but the default values remain
740 * in 'opts->list'. So if the protocol has options with the same name
741 * (e.g. rbd has 'cluster_size' as qcow2), it will see the default values
742 * of the format, since for overlapping options, the format wins.
744 * To avoid this issue, lets convert QemuOpts to QDict, in this way we take
745 * only the set options, and then convert it back to QemuOpts, using the
746 * create_opts of the protocol. So the new QemuOpts, will contain only the
749 qdict
= qemu_opts_to_qdict(opts
, NULL
);
750 protocol_opts
= qemu_opts_from_qdict(drv
->create_opts
, qdict
, errp
);
751 if (protocol_opts
== NULL
) {
756 ret
= bdrv_create(drv
, filename
, protocol_opts
, errp
);
758 qemu_opts_del(protocol_opts
);
759 qobject_unref(qdict
);
763 int coroutine_fn
bdrv_co_delete_file(BlockDriverState
*bs
, Error
**errp
)
765 Error
*local_err
= NULL
;
772 error_setg(errp
, "Block node '%s' is not opened", bs
->filename
);
776 if (!bs
->drv
->bdrv_co_delete_file
) {
777 error_setg(errp
, "Driver '%s' does not support image deletion",
778 bs
->drv
->format_name
);
782 ret
= bs
->drv
->bdrv_co_delete_file(bs
, &local_err
);
784 error_propagate(errp
, local_err
);
790 void coroutine_fn
bdrv_co_delete_file_noerr(BlockDriverState
*bs
)
792 Error
*local_err
= NULL
;
800 ret
= bdrv_co_delete_file(bs
, &local_err
);
802 * ENOTSUP will happen if the block driver doesn't support
803 * the 'bdrv_co_delete_file' interface. This is a predictable
804 * scenario and shouldn't be reported back to the user.
806 if (ret
== -ENOTSUP
) {
807 error_free(local_err
);
808 } else if (ret
< 0) {
809 error_report_err(local_err
);
814 * Try to get @bs's logical and physical block size.
815 * On success, store them in @bsz struct and return 0.
816 * On failure return -errno.
817 * @bs must not be empty.
819 int bdrv_probe_blocksizes(BlockDriverState
*bs
, BlockSizes
*bsz
)
821 BlockDriver
*drv
= bs
->drv
;
822 BlockDriverState
*filtered
= bdrv_filter_bs(bs
);
825 if (drv
&& drv
->bdrv_probe_blocksizes
) {
826 return drv
->bdrv_probe_blocksizes(bs
, bsz
);
827 } else if (filtered
) {
828 return bdrv_probe_blocksizes(filtered
, bsz
);
835 * Try to get @bs's geometry (cyls, heads, sectors).
836 * On success, store them in @geo struct and return 0.
837 * On failure return -errno.
838 * @bs must not be empty.
840 int bdrv_probe_geometry(BlockDriverState
*bs
, HDGeometry
*geo
)
842 BlockDriver
*drv
= bs
->drv
;
843 BlockDriverState
*filtered
= bdrv_filter_bs(bs
);
846 if (drv
&& drv
->bdrv_probe_geometry
) {
847 return drv
->bdrv_probe_geometry(bs
, geo
);
848 } else if (filtered
) {
849 return bdrv_probe_geometry(filtered
, geo
);
856 * Create a uniquely-named empty temporary file.
857 * Return 0 upon success, otherwise a negative errno value.
859 int get_tmp_filename(char *filename
, int size
)
862 char temp_dir
[MAX_PATH
];
863 /* GetTempFileName requires that its output buffer (4th param)
864 have length MAX_PATH or greater. */
865 assert(size
>= MAX_PATH
);
866 return (GetTempPath(MAX_PATH
, temp_dir
)
867 && GetTempFileName(temp_dir
, "qem", 0, filename
)
868 ? 0 : -GetLastError());
872 tmpdir
= getenv("TMPDIR");
876 if (snprintf(filename
, size
, "%s/vl.XXXXXX", tmpdir
) >= size
) {
879 fd
= mkstemp(filename
);
883 if (close(fd
) != 0) {
892 * Detect host devices. By convention, /dev/cdrom[N] is always
893 * recognized as a host CDROM.
895 static BlockDriver
*find_hdev_driver(const char *filename
)
897 int score_max
= 0, score
;
898 BlockDriver
*drv
= NULL
, *d
;
900 QLIST_FOREACH(d
, &bdrv_drivers
, list
) {
901 if (d
->bdrv_probe_device
) {
902 score
= d
->bdrv_probe_device(filename
);
903 if (score
> score_max
) {
913 static BlockDriver
*bdrv_do_find_protocol(const char *protocol
)
917 QLIST_FOREACH(drv1
, &bdrv_drivers
, list
) {
918 if (drv1
->protocol_name
&& !strcmp(drv1
->protocol_name
, protocol
)) {
926 BlockDriver
*bdrv_find_protocol(const char *filename
,
927 bool allow_protocol_prefix
,
937 /* TODO Drivers without bdrv_file_open must be specified explicitly */
940 * XXX(hch): we really should not let host device detection
941 * override an explicit protocol specification, but moving this
942 * later breaks access to device names with colons in them.
943 * Thanks to the brain-dead persistent naming schemes on udev-
944 * based Linux systems those actually are quite common.
946 drv1
= find_hdev_driver(filename
);
951 if (!path_has_protocol(filename
) || !allow_protocol_prefix
) {
955 p
= strchr(filename
, ':');
958 if (len
> sizeof(protocol
) - 1)
959 len
= sizeof(protocol
) - 1;
960 memcpy(protocol
, filename
, len
);
961 protocol
[len
] = '\0';
963 drv1
= bdrv_do_find_protocol(protocol
);
968 for (i
= 0; i
< (int)ARRAY_SIZE(block_driver_modules
); ++i
) {
969 if (block_driver_modules
[i
].protocol_name
&&
970 !strcmp(block_driver_modules
[i
].protocol_name
, protocol
)) {
971 block_module_load_one(block_driver_modules
[i
].library_name
);
976 drv1
= bdrv_do_find_protocol(protocol
);
978 error_setg(errp
, "Unknown protocol '%s'", protocol
);
984 * Guess image format by probing its contents.
985 * This is not a good idea when your image is raw (CVE-2008-2004), but
986 * we do it anyway for backward compatibility.
988 * @buf contains the image's first @buf_size bytes.
989 * @buf_size is the buffer size in bytes (generally BLOCK_PROBE_BUF_SIZE,
990 * but can be smaller if the image file is smaller)
991 * @filename is its filename.
993 * For all block drivers, call the bdrv_probe() method to get its
995 * Return the first block driver with the highest probing score.
997 BlockDriver
*bdrv_probe_all(const uint8_t *buf
, int buf_size
,
998 const char *filename
)
1000 int score_max
= 0, score
;
1001 BlockDriver
*drv
= NULL
, *d
;
1004 QLIST_FOREACH(d
, &bdrv_drivers
, list
) {
1005 if (d
->bdrv_probe
) {
1006 score
= d
->bdrv_probe(buf
, buf_size
, filename
);
1007 if (score
> score_max
) {
1017 static int find_image_format(BlockBackend
*file
, const char *filename
,
1018 BlockDriver
**pdrv
, Error
**errp
)
1021 uint8_t buf
[BLOCK_PROBE_BUF_SIZE
];
1024 /* Return the raw BlockDriver * to scsi-generic devices or empty drives */
1025 if (blk_is_sg(file
) || !blk_is_inserted(file
) || blk_getlength(file
) == 0) {
1030 ret
= blk_pread(file
, 0, buf
, sizeof(buf
));
1032 error_setg_errno(errp
, -ret
, "Could not read image for determining its "
1038 drv
= bdrv_probe_all(buf
, ret
, filename
);
1040 error_setg(errp
, "Could not determine image format: No compatible "
1049 * Set the current 'total_sectors' value
1050 * Return 0 on success, -errno on error.
1052 int refresh_total_sectors(BlockDriverState
*bs
, int64_t hint
)
1054 BlockDriver
*drv
= bs
->drv
;
1061 /* Do not attempt drv->bdrv_getlength() on scsi-generic devices */
1065 /* query actual device if possible, otherwise just trust the hint */
1066 if (drv
->bdrv_getlength
) {
1067 int64_t length
= drv
->bdrv_getlength(bs
);
1071 hint
= DIV_ROUND_UP(length
, BDRV_SECTOR_SIZE
);
1074 bs
->total_sectors
= hint
;
1076 if (bs
->total_sectors
* BDRV_SECTOR_SIZE
> BDRV_MAX_LENGTH
) {
1084 * Combines a QDict of new block driver @options with any missing options taken
1085 * from @old_options, so that leaving out an option defaults to its old value.
1087 static void bdrv_join_options(BlockDriverState
*bs
, QDict
*options
,
1090 if (bs
->drv
&& bs
->drv
->bdrv_join_options
) {
1091 bs
->drv
->bdrv_join_options(options
, old_options
);
1093 qdict_join(options
, old_options
, false);
1097 static BlockdevDetectZeroesOptions
bdrv_parse_detect_zeroes(QemuOpts
*opts
,
1101 Error
*local_err
= NULL
;
1102 char *value
= qemu_opt_get_del(opts
, "detect-zeroes");
1103 BlockdevDetectZeroesOptions detect_zeroes
=
1104 qapi_enum_parse(&BlockdevDetectZeroesOptions_lookup
, value
,
1105 BLOCKDEV_DETECT_ZEROES_OPTIONS_OFF
, &local_err
);
1108 error_propagate(errp
, local_err
);
1109 return detect_zeroes
;
1112 if (detect_zeroes
== BLOCKDEV_DETECT_ZEROES_OPTIONS_UNMAP
&&
1113 !(open_flags
& BDRV_O_UNMAP
))
1115 error_setg(errp
, "setting detect-zeroes to unmap is not allowed "
1116 "without setting discard operation to unmap");
1119 return detect_zeroes
;
1123 * Set open flags for aio engine
1125 * Return 0 on success, -1 if the engine specified is invalid
1127 int bdrv_parse_aio(const char *mode
, int *flags
)
1129 if (!strcmp(mode
, "threads")) {
1130 /* do nothing, default */
1131 } else if (!strcmp(mode
, "native")) {
1132 *flags
|= BDRV_O_NATIVE_AIO
;
1133 #ifdef CONFIG_LINUX_IO_URING
1134 } else if (!strcmp(mode
, "io_uring")) {
1135 *flags
|= BDRV_O_IO_URING
;
1145 * Set open flags for a given discard mode
1147 * Return 0 on success, -1 if the discard mode was invalid.
1149 int bdrv_parse_discard_flags(const char *mode
, int *flags
)
1151 *flags
&= ~BDRV_O_UNMAP
;
1153 if (!strcmp(mode
, "off") || !strcmp(mode
, "ignore")) {
1155 } else if (!strcmp(mode
, "on") || !strcmp(mode
, "unmap")) {
1156 *flags
|= BDRV_O_UNMAP
;
1165 * Set open flags for a given cache mode
1167 * Return 0 on success, -1 if the cache mode was invalid.
1169 int bdrv_parse_cache_mode(const char *mode
, int *flags
, bool *writethrough
)
1171 *flags
&= ~BDRV_O_CACHE_MASK
;
1173 if (!strcmp(mode
, "off") || !strcmp(mode
, "none")) {
1174 *writethrough
= false;
1175 *flags
|= BDRV_O_NOCACHE
;
1176 } else if (!strcmp(mode
, "directsync")) {
1177 *writethrough
= true;
1178 *flags
|= BDRV_O_NOCACHE
;
1179 } else if (!strcmp(mode
, "writeback")) {
1180 *writethrough
= false;
1181 } else if (!strcmp(mode
, "unsafe")) {
1182 *writethrough
= false;
1183 *flags
|= BDRV_O_NO_FLUSH
;
1184 } else if (!strcmp(mode
, "writethrough")) {
1185 *writethrough
= true;
1193 static char *bdrv_child_get_parent_desc(BdrvChild
*c
)
1195 BlockDriverState
*parent
= c
->opaque
;
1196 return g_strdup_printf("node '%s'", bdrv_get_node_name(parent
));
1199 static void bdrv_child_cb_drained_begin(BdrvChild
*child
)
1201 BlockDriverState
*bs
= child
->opaque
;
1202 bdrv_do_drained_begin_quiesce(bs
, NULL
, false);
1205 static bool bdrv_child_cb_drained_poll(BdrvChild
*child
)
1207 BlockDriverState
*bs
= child
->opaque
;
1208 return bdrv_drain_poll(bs
, false, NULL
, false);
1211 static void bdrv_child_cb_drained_end(BdrvChild
*child
,
1212 int *drained_end_counter
)
1214 BlockDriverState
*bs
= child
->opaque
;
1215 bdrv_drained_end_no_poll(bs
, drained_end_counter
);
1218 static int bdrv_child_cb_inactivate(BdrvChild
*child
)
1220 BlockDriverState
*bs
= child
->opaque
;
1221 assert(bs
->open_flags
& BDRV_O_INACTIVE
);
1225 static bool bdrv_child_cb_can_set_aio_ctx(BdrvChild
*child
, AioContext
*ctx
,
1226 GSList
**ignore
, Error
**errp
)
1228 BlockDriverState
*bs
= child
->opaque
;
1229 return bdrv_can_set_aio_context(bs
, ctx
, ignore
, errp
);
1232 static void bdrv_child_cb_set_aio_ctx(BdrvChild
*child
, AioContext
*ctx
,
1235 BlockDriverState
*bs
= child
->opaque
;
1236 return bdrv_set_aio_context_ignore(bs
, ctx
, ignore
);
1240 * Returns the options and flags that a temporary snapshot should get, based on
1241 * the originally requested flags (the originally requested image will have
1242 * flags like a backing file)
1244 static void bdrv_temp_snapshot_options(int *child_flags
, QDict
*child_options
,
1245 int parent_flags
, QDict
*parent_options
)
1247 *child_flags
= (parent_flags
& ~BDRV_O_SNAPSHOT
) | BDRV_O_TEMPORARY
;
1249 /* For temporary files, unconditional cache=unsafe is fine */
1250 qdict_set_default_str(child_options
, BDRV_OPT_CACHE_DIRECT
, "off");
1251 qdict_set_default_str(child_options
, BDRV_OPT_CACHE_NO_FLUSH
, "on");
1253 /* Copy the read-only and discard options from the parent */
1254 qdict_copy_default(child_options
, parent_options
, BDRV_OPT_READ_ONLY
);
1255 qdict_copy_default(child_options
, parent_options
, BDRV_OPT_DISCARD
);
1257 /* aio=native doesn't work for cache.direct=off, so disable it for the
1258 * temporary snapshot */
1259 *child_flags
&= ~BDRV_O_NATIVE_AIO
;
1262 static void bdrv_backing_attach(BdrvChild
*c
)
1264 BlockDriverState
*parent
= c
->opaque
;
1265 BlockDriverState
*backing_hd
= c
->bs
;
1267 assert(!parent
->backing_blocker
);
1268 error_setg(&parent
->backing_blocker
,
1269 "node is used as backing hd of '%s'",
1270 bdrv_get_device_or_node_name(parent
));
1272 bdrv_refresh_filename(backing_hd
);
1274 parent
->open_flags
&= ~BDRV_O_NO_BACKING
;
1276 bdrv_op_block_all(backing_hd
, parent
->backing_blocker
);
1277 /* Otherwise we won't be able to commit or stream */
1278 bdrv_op_unblock(backing_hd
, BLOCK_OP_TYPE_COMMIT_TARGET
,
1279 parent
->backing_blocker
);
1280 bdrv_op_unblock(backing_hd
, BLOCK_OP_TYPE_STREAM
,
1281 parent
->backing_blocker
);
1283 * We do backup in 3 ways:
1285 * The target bs is new opened, and the source is top BDS
1286 * 2. blockdev backup
1287 * Both the source and the target are top BDSes.
1288 * 3. internal backup(used for block replication)
1289 * Both the source and the target are backing file
1291 * In case 1 and 2, neither the source nor the target is the backing file.
1292 * In case 3, we will block the top BDS, so there is only one block job
1293 * for the top BDS and its backing chain.
1295 bdrv_op_unblock(backing_hd
, BLOCK_OP_TYPE_BACKUP_SOURCE
,
1296 parent
->backing_blocker
);
1297 bdrv_op_unblock(backing_hd
, BLOCK_OP_TYPE_BACKUP_TARGET
,
1298 parent
->backing_blocker
);
1301 static void bdrv_backing_detach(BdrvChild
*c
)
1303 BlockDriverState
*parent
= c
->opaque
;
1305 assert(parent
->backing_blocker
);
1306 bdrv_op_unblock_all(c
->bs
, parent
->backing_blocker
);
1307 error_free(parent
->backing_blocker
);
1308 parent
->backing_blocker
= NULL
;
1311 static int bdrv_backing_update_filename(BdrvChild
*c
, BlockDriverState
*base
,
1312 const char *filename
, Error
**errp
)
1314 BlockDriverState
*parent
= c
->opaque
;
1315 bool read_only
= bdrv_is_read_only(parent
);
1319 ret
= bdrv_reopen_set_read_only(parent
, false, errp
);
1325 ret
= bdrv_change_backing_file(parent
, filename
,
1326 base
->drv
? base
->drv
->format_name
: "",
1329 error_setg_errno(errp
, -ret
, "Could not update backing file link");
1333 bdrv_reopen_set_read_only(parent
, true, NULL
);
1340 * Returns the options and flags that a generic child of a BDS should
1341 * get, based on the given options and flags for the parent BDS.
1343 static void bdrv_inherited_options(BdrvChildRole role
, bool parent_is_format
,
1344 int *child_flags
, QDict
*child_options
,
1345 int parent_flags
, QDict
*parent_options
)
1347 int flags
= parent_flags
;
1350 * First, decide whether to set, clear, or leave BDRV_O_PROTOCOL.
1351 * Generally, the question to answer is: Should this child be
1352 * format-probed by default?
1356 * Pure and non-filtered data children of non-format nodes should
1357 * be probed by default (even when the node itself has BDRV_O_PROTOCOL
1358 * set). This only affects a very limited set of drivers (namely
1359 * quorum and blkverify when this comment was written).
1360 * Force-clear BDRV_O_PROTOCOL then.
1362 if (!parent_is_format
&&
1363 (role
& BDRV_CHILD_DATA
) &&
1364 !(role
& (BDRV_CHILD_METADATA
| BDRV_CHILD_FILTERED
)))
1366 flags
&= ~BDRV_O_PROTOCOL
;
1370 * All children of format nodes (except for COW children) and all
1371 * metadata children in general should never be format-probed.
1372 * Force-set BDRV_O_PROTOCOL then.
1374 if ((parent_is_format
&& !(role
& BDRV_CHILD_COW
)) ||
1375 (role
& BDRV_CHILD_METADATA
))
1377 flags
|= BDRV_O_PROTOCOL
;
1381 * If the cache mode isn't explicitly set, inherit direct and no-flush from
1384 qdict_copy_default(child_options
, parent_options
, BDRV_OPT_CACHE_DIRECT
);
1385 qdict_copy_default(child_options
, parent_options
, BDRV_OPT_CACHE_NO_FLUSH
);
1386 qdict_copy_default(child_options
, parent_options
, BDRV_OPT_FORCE_SHARE
);
1388 if (role
& BDRV_CHILD_COW
) {
1389 /* backing files are opened read-only by default */
1390 qdict_set_default_str(child_options
, BDRV_OPT_READ_ONLY
, "on");
1391 qdict_set_default_str(child_options
, BDRV_OPT_AUTO_READ_ONLY
, "off");
1393 /* Inherit the read-only option from the parent if it's not set */
1394 qdict_copy_default(child_options
, parent_options
, BDRV_OPT_READ_ONLY
);
1395 qdict_copy_default(child_options
, parent_options
,
1396 BDRV_OPT_AUTO_READ_ONLY
);
1400 * bdrv_co_pdiscard() respects unmap policy for the parent, so we
1401 * can default to enable it on lower layers regardless of the
1404 qdict_set_default_str(child_options
, BDRV_OPT_DISCARD
, "unmap");
1406 /* Clear flags that only apply to the top layer */
1407 flags
&= ~(BDRV_O_SNAPSHOT
| BDRV_O_NO_BACKING
| BDRV_O_COPY_ON_READ
);
1409 if (role
& BDRV_CHILD_METADATA
) {
1410 flags
&= ~BDRV_O_NO_IO
;
1412 if (role
& BDRV_CHILD_COW
) {
1413 flags
&= ~BDRV_O_TEMPORARY
;
1416 *child_flags
= flags
;
1419 static void bdrv_child_cb_attach(BdrvChild
*child
)
1421 BlockDriverState
*bs
= child
->opaque
;
1423 QLIST_INSERT_HEAD(&bs
->children
, child
, next
);
1425 if (child
->role
& BDRV_CHILD_COW
) {
1426 bdrv_backing_attach(child
);
1429 bdrv_apply_subtree_drain(child
, bs
);
1432 static void bdrv_child_cb_detach(BdrvChild
*child
)
1434 BlockDriverState
*bs
= child
->opaque
;
1436 if (child
->role
& BDRV_CHILD_COW
) {
1437 bdrv_backing_detach(child
);
1440 bdrv_unapply_subtree_drain(child
, bs
);
1442 QLIST_REMOVE(child
, next
);
1445 static int bdrv_child_cb_update_filename(BdrvChild
*c
, BlockDriverState
*base
,
1446 const char *filename
, Error
**errp
)
1448 if (c
->role
& BDRV_CHILD_COW
) {
1449 return bdrv_backing_update_filename(c
, base
, filename
, errp
);
1454 AioContext
*child_of_bds_get_parent_aio_context(BdrvChild
*c
)
1456 BlockDriverState
*bs
= c
->opaque
;
1459 return bdrv_get_aio_context(bs
);
1462 const BdrvChildClass child_of_bds
= {
1463 .parent_is_bds
= true,
1464 .get_parent_desc
= bdrv_child_get_parent_desc
,
1465 .inherit_options
= bdrv_inherited_options
,
1466 .drained_begin
= bdrv_child_cb_drained_begin
,
1467 .drained_poll
= bdrv_child_cb_drained_poll
,
1468 .drained_end
= bdrv_child_cb_drained_end
,
1469 .attach
= bdrv_child_cb_attach
,
1470 .detach
= bdrv_child_cb_detach
,
1471 .inactivate
= bdrv_child_cb_inactivate
,
1472 .can_set_aio_ctx
= bdrv_child_cb_can_set_aio_ctx
,
1473 .set_aio_ctx
= bdrv_child_cb_set_aio_ctx
,
1474 .update_filename
= bdrv_child_cb_update_filename
,
1475 .get_parent_aio_context
= child_of_bds_get_parent_aio_context
,
1478 AioContext
*bdrv_child_get_parent_aio_context(BdrvChild
*c
)
1481 return c
->klass
->get_parent_aio_context(c
);
1484 static int bdrv_open_flags(BlockDriverState
*bs
, int flags
)
1486 int open_flags
= flags
;
1489 * Clear flags that are internal to the block layer before opening the
1492 open_flags
&= ~(BDRV_O_SNAPSHOT
| BDRV_O_NO_BACKING
| BDRV_O_PROTOCOL
);
1497 static void update_flags_from_options(int *flags
, QemuOpts
*opts
)
1499 *flags
&= ~(BDRV_O_CACHE_MASK
| BDRV_O_RDWR
| BDRV_O_AUTO_RDONLY
);
1501 if (qemu_opt_get_bool_del(opts
, BDRV_OPT_CACHE_NO_FLUSH
, false)) {
1502 *flags
|= BDRV_O_NO_FLUSH
;
1505 if (qemu_opt_get_bool_del(opts
, BDRV_OPT_CACHE_DIRECT
, false)) {
1506 *flags
|= BDRV_O_NOCACHE
;
1509 if (!qemu_opt_get_bool_del(opts
, BDRV_OPT_READ_ONLY
, false)) {
1510 *flags
|= BDRV_O_RDWR
;
1513 if (qemu_opt_get_bool_del(opts
, BDRV_OPT_AUTO_READ_ONLY
, false)) {
1514 *flags
|= BDRV_O_AUTO_RDONLY
;
1518 static void update_options_from_flags(QDict
*options
, int flags
)
1520 if (!qdict_haskey(options
, BDRV_OPT_CACHE_DIRECT
)) {
1521 qdict_put_bool(options
, BDRV_OPT_CACHE_DIRECT
, flags
& BDRV_O_NOCACHE
);
1523 if (!qdict_haskey(options
, BDRV_OPT_CACHE_NO_FLUSH
)) {
1524 qdict_put_bool(options
, BDRV_OPT_CACHE_NO_FLUSH
,
1525 flags
& BDRV_O_NO_FLUSH
);
1527 if (!qdict_haskey(options
, BDRV_OPT_READ_ONLY
)) {
1528 qdict_put_bool(options
, BDRV_OPT_READ_ONLY
, !(flags
& BDRV_O_RDWR
));
1530 if (!qdict_haskey(options
, BDRV_OPT_AUTO_READ_ONLY
)) {
1531 qdict_put_bool(options
, BDRV_OPT_AUTO_READ_ONLY
,
1532 flags
& BDRV_O_AUTO_RDONLY
);
1536 static void bdrv_assign_node_name(BlockDriverState
*bs
,
1537 const char *node_name
,
1540 char *gen_node_name
= NULL
;
1543 node_name
= gen_node_name
= id_generate(ID_BLOCK
);
1544 } else if (!id_wellformed(node_name
)) {
1546 * Check for empty string or invalid characters, but not if it is
1547 * generated (generated names use characters not available to the user)
1549 error_setg(errp
, "Invalid node-name: '%s'", node_name
);
1553 /* takes care of avoiding namespaces collisions */
1554 if (blk_by_name(node_name
)) {
1555 error_setg(errp
, "node-name=%s is conflicting with a device id",
1560 /* takes care of avoiding duplicates node names */
1561 if (bdrv_find_node(node_name
)) {
1562 error_setg(errp
, "Duplicate nodes with node-name='%s'", node_name
);
1566 /* Make sure that the node name isn't truncated */
1567 if (strlen(node_name
) >= sizeof(bs
->node_name
)) {
1568 error_setg(errp
, "Node name too long");
1572 /* copy node name into the bs and insert it into the graph list */
1573 pstrcpy(bs
->node_name
, sizeof(bs
->node_name
), node_name
);
1574 QTAILQ_INSERT_TAIL(&graph_bdrv_states
, bs
, node_list
);
1576 g_free(gen_node_name
);
1579 static int bdrv_open_driver(BlockDriverState
*bs
, BlockDriver
*drv
,
1580 const char *node_name
, QDict
*options
,
1581 int open_flags
, Error
**errp
)
1583 Error
*local_err
= NULL
;
1586 bdrv_assign_node_name(bs
, node_name
, &local_err
);
1588 error_propagate(errp
, local_err
);
1593 bs
->opaque
= g_malloc0(drv
->instance_size
);
1595 if (drv
->bdrv_file_open
) {
1596 assert(!drv
->bdrv_needs_filename
|| bs
->filename
[0]);
1597 ret
= drv
->bdrv_file_open(bs
, options
, open_flags
, &local_err
);
1598 } else if (drv
->bdrv_open
) {
1599 ret
= drv
->bdrv_open(bs
, options
, open_flags
, &local_err
);
1606 error_propagate(errp
, local_err
);
1607 } else if (bs
->filename
[0]) {
1608 error_setg_errno(errp
, -ret
, "Could not open '%s'", bs
->filename
);
1610 error_setg_errno(errp
, -ret
, "Could not open image");
1615 ret
= refresh_total_sectors(bs
, bs
->total_sectors
);
1617 error_setg_errno(errp
, -ret
, "Could not refresh total sector count");
1621 bdrv_refresh_limits(bs
, NULL
, &local_err
);
1623 error_propagate(errp
, local_err
);
1627 assert(bdrv_opt_mem_align(bs
) != 0);
1628 assert(bdrv_min_mem_align(bs
) != 0);
1629 assert(is_power_of_2(bs
->bl
.request_alignment
));
1631 for (i
= 0; i
< bs
->quiesce_counter
; i
++) {
1632 if (drv
->bdrv_co_drain_begin
) {
1633 drv
->bdrv_co_drain_begin(bs
);
1640 if (bs
->file
!= NULL
) {
1641 bdrv_unref_child(bs
, bs
->file
);
1650 * Create and open a block node.
1652 * @options is a QDict of options to pass to the block drivers, or NULL for an
1653 * empty set of options. The reference to the QDict belongs to the block layer
1654 * after the call (even on failure), so if the caller intends to reuse the
1655 * dictionary, it needs to use qobject_ref() before calling bdrv_open.
1657 BlockDriverState
*bdrv_new_open_driver_opts(BlockDriver
*drv
,
1658 const char *node_name
,
1659 QDict
*options
, int flags
,
1662 BlockDriverState
*bs
;
1665 GLOBAL_STATE_CODE();
1668 bs
->open_flags
= flags
;
1669 bs
->options
= options
?: qdict_new();
1670 bs
->explicit_options
= qdict_clone_shallow(bs
->options
);
1673 update_options_from_flags(bs
->options
, flags
);
1675 ret
= bdrv_open_driver(bs
, drv
, node_name
, bs
->options
, flags
, errp
);
1677 qobject_unref(bs
->explicit_options
);
1678 bs
->explicit_options
= NULL
;
1679 qobject_unref(bs
->options
);
1688 /* Create and open a block node. */
1689 BlockDriverState
*bdrv_new_open_driver(BlockDriver
*drv
, const char *node_name
,
1690 int flags
, Error
**errp
)
1692 GLOBAL_STATE_CODE();
1693 return bdrv_new_open_driver_opts(drv
, node_name
, NULL
, flags
, errp
);
1696 QemuOptsList bdrv_runtime_opts
= {
1697 .name
= "bdrv_common",
1698 .head
= QTAILQ_HEAD_INITIALIZER(bdrv_runtime_opts
.head
),
1701 .name
= "node-name",
1702 .type
= QEMU_OPT_STRING
,
1703 .help
= "Node name of the block device node",
1707 .type
= QEMU_OPT_STRING
,
1708 .help
= "Block driver to use for the node",
1711 .name
= BDRV_OPT_CACHE_DIRECT
,
1712 .type
= QEMU_OPT_BOOL
,
1713 .help
= "Bypass software writeback cache on the host",
1716 .name
= BDRV_OPT_CACHE_NO_FLUSH
,
1717 .type
= QEMU_OPT_BOOL
,
1718 .help
= "Ignore flush requests",
1721 .name
= BDRV_OPT_READ_ONLY
,
1722 .type
= QEMU_OPT_BOOL
,
1723 .help
= "Node is opened in read-only mode",
1726 .name
= BDRV_OPT_AUTO_READ_ONLY
,
1727 .type
= QEMU_OPT_BOOL
,
1728 .help
= "Node can become read-only if opening read-write fails",
1731 .name
= "detect-zeroes",
1732 .type
= QEMU_OPT_STRING
,
1733 .help
= "try to optimize zero writes (off, on, unmap)",
1736 .name
= BDRV_OPT_DISCARD
,
1737 .type
= QEMU_OPT_STRING
,
1738 .help
= "discard operation (ignore/off, unmap/on)",
1741 .name
= BDRV_OPT_FORCE_SHARE
,
1742 .type
= QEMU_OPT_BOOL
,
1743 .help
= "always accept other writers (default: off)",
1745 { /* end of list */ }
1749 QemuOptsList bdrv_create_opts_simple
= {
1750 .name
= "simple-create-opts",
1751 .head
= QTAILQ_HEAD_INITIALIZER(bdrv_create_opts_simple
.head
),
1754 .name
= BLOCK_OPT_SIZE
,
1755 .type
= QEMU_OPT_SIZE
,
1756 .help
= "Virtual disk size"
1759 .name
= BLOCK_OPT_PREALLOC
,
1760 .type
= QEMU_OPT_STRING
,
1761 .help
= "Preallocation mode (allowed values: off)"
1763 { /* end of list */ }
1768 * Common part for opening disk images and files
1770 * Removes all processed options from *options.
1772 static int bdrv_open_common(BlockDriverState
*bs
, BlockBackend
*file
,
1773 QDict
*options
, Error
**errp
)
1775 int ret
, open_flags
;
1776 const char *filename
;
1777 const char *driver_name
= NULL
;
1778 const char *node_name
= NULL
;
1779 const char *discard
;
1782 Error
*local_err
= NULL
;
1785 assert(bs
->file
== NULL
);
1786 assert(options
!= NULL
&& bs
->options
!= options
);
1788 opts
= qemu_opts_create(&bdrv_runtime_opts
, NULL
, 0, &error_abort
);
1789 if (!qemu_opts_absorb_qdict(opts
, options
, errp
)) {
1794 update_flags_from_options(&bs
->open_flags
, opts
);
1796 driver_name
= qemu_opt_get(opts
, "driver");
1797 drv
= bdrv_find_format(driver_name
);
1798 assert(drv
!= NULL
);
1800 bs
->force_share
= qemu_opt_get_bool(opts
, BDRV_OPT_FORCE_SHARE
, false);
1802 if (bs
->force_share
&& (bs
->open_flags
& BDRV_O_RDWR
)) {
1804 BDRV_OPT_FORCE_SHARE
1805 "=on can only be used with read-only images");
1811 bdrv_refresh_filename(blk_bs(file
));
1812 filename
= blk_bs(file
)->filename
;
1815 * Caution: while qdict_get_try_str() is fine, getting
1816 * non-string types would require more care. When @options
1817 * come from -blockdev or blockdev_add, its members are typed
1818 * according to the QAPI schema, but when they come from
1819 * -drive, they're all QString.
1821 filename
= qdict_get_try_str(options
, "filename");
1824 if (drv
->bdrv_needs_filename
&& (!filename
|| !filename
[0])) {
1825 error_setg(errp
, "The '%s' block driver requires a file name",
1831 trace_bdrv_open_common(bs
, filename
?: "", bs
->open_flags
,
1834 ro
= bdrv_is_read_only(bs
);
1836 if (use_bdrv_whitelist
&& !bdrv_is_whitelisted(drv
, ro
)) {
1837 if (!ro
&& bdrv_is_whitelisted(drv
, true)) {
1838 ret
= bdrv_apply_auto_read_only(bs
, NULL
, NULL
);
1844 !ro
&& bdrv_is_whitelisted(drv
, true)
1845 ? "Driver '%s' can only be used for read-only devices"
1846 : "Driver '%s' is not whitelisted",
1852 /* bdrv_new() and bdrv_close() make it so */
1853 assert(qatomic_read(&bs
->copy_on_read
) == 0);
1855 if (bs
->open_flags
& BDRV_O_COPY_ON_READ
) {
1857 bdrv_enable_copy_on_read(bs
);
1859 error_setg(errp
, "Can't use copy-on-read on read-only device");
1865 discard
= qemu_opt_get(opts
, BDRV_OPT_DISCARD
);
1866 if (discard
!= NULL
) {
1867 if (bdrv_parse_discard_flags(discard
, &bs
->open_flags
) != 0) {
1868 error_setg(errp
, "Invalid discard option");
1875 bdrv_parse_detect_zeroes(opts
, bs
->open_flags
, &local_err
);
1877 error_propagate(errp
, local_err
);
1882 if (filename
!= NULL
) {
1883 pstrcpy(bs
->filename
, sizeof(bs
->filename
), filename
);
1885 bs
->filename
[0] = '\0';
1887 pstrcpy(bs
->exact_filename
, sizeof(bs
->exact_filename
), bs
->filename
);
1889 /* Open the image, either directly or using a protocol */
1890 open_flags
= bdrv_open_flags(bs
, bs
->open_flags
);
1891 node_name
= qemu_opt_get(opts
, "node-name");
1893 assert(!drv
->bdrv_file_open
|| file
== NULL
);
1894 ret
= bdrv_open_driver(bs
, drv
, node_name
, options
, open_flags
, errp
);
1899 qemu_opts_del(opts
);
1903 qemu_opts_del(opts
);
1907 static QDict
*parse_json_filename(const char *filename
, Error
**errp
)
1909 QObject
*options_obj
;
1913 ret
= strstart(filename
, "json:", &filename
);
1916 options_obj
= qobject_from_json(filename
, errp
);
1918 error_prepend(errp
, "Could not parse the JSON options: ");
1922 options
= qobject_to(QDict
, options_obj
);
1924 qobject_unref(options_obj
);
1925 error_setg(errp
, "Invalid JSON object given");
1929 qdict_flatten(options
);
1934 static void parse_json_protocol(QDict
*options
, const char **pfilename
,
1937 QDict
*json_options
;
1938 Error
*local_err
= NULL
;
1940 /* Parse json: pseudo-protocol */
1941 if (!*pfilename
|| !g_str_has_prefix(*pfilename
, "json:")) {
1945 json_options
= parse_json_filename(*pfilename
, &local_err
);
1947 error_propagate(errp
, local_err
);
1951 /* Options given in the filename have lower priority than options
1952 * specified directly */
1953 qdict_join(options
, json_options
, false);
1954 qobject_unref(json_options
);
1959 * Fills in default options for opening images and converts the legacy
1960 * filename/flags pair to option QDict entries.
1961 * The BDRV_O_PROTOCOL flag in *flags will be set or cleared accordingly if a
1962 * block driver has been specified explicitly.
1964 static int bdrv_fill_options(QDict
**options
, const char *filename
,
1965 int *flags
, Error
**errp
)
1967 const char *drvname
;
1968 bool protocol
= *flags
& BDRV_O_PROTOCOL
;
1969 bool parse_filename
= false;
1970 BlockDriver
*drv
= NULL
;
1971 Error
*local_err
= NULL
;
1974 * Caution: while qdict_get_try_str() is fine, getting non-string
1975 * types would require more care. When @options come from
1976 * -blockdev or blockdev_add, its members are typed according to
1977 * the QAPI schema, but when they come from -drive, they're all
1980 drvname
= qdict_get_try_str(*options
, "driver");
1982 drv
= bdrv_find_format(drvname
);
1984 error_setg(errp
, "Unknown driver '%s'", drvname
);
1987 /* If the user has explicitly specified the driver, this choice should
1988 * override the BDRV_O_PROTOCOL flag */
1989 protocol
= drv
->bdrv_file_open
;
1993 *flags
|= BDRV_O_PROTOCOL
;
1995 *flags
&= ~BDRV_O_PROTOCOL
;
1998 /* Translate cache options from flags into options */
1999 update_options_from_flags(*options
, *flags
);
2001 /* Fetch the file name from the options QDict if necessary */
2002 if (protocol
&& filename
) {
2003 if (!qdict_haskey(*options
, "filename")) {
2004 qdict_put_str(*options
, "filename", filename
);
2005 parse_filename
= true;
2007 error_setg(errp
, "Can't specify 'file' and 'filename' options at "
2013 /* Find the right block driver */
2014 /* See cautionary note on accessing @options above */
2015 filename
= qdict_get_try_str(*options
, "filename");
2017 if (!drvname
&& protocol
) {
2019 drv
= bdrv_find_protocol(filename
, parse_filename
, errp
);
2024 drvname
= drv
->format_name
;
2025 qdict_put_str(*options
, "driver", drvname
);
2027 error_setg(errp
, "Must specify either driver or file");
2032 assert(drv
|| !protocol
);
2034 /* Driver-specific filename parsing */
2035 if (drv
&& drv
->bdrv_parse_filename
&& parse_filename
) {
2036 drv
->bdrv_parse_filename(filename
, *options
, &local_err
);
2038 error_propagate(errp
, local_err
);
2042 if (!drv
->bdrv_needs_filename
) {
2043 qdict_del(*options
, "filename");
2050 typedef struct BlockReopenQueueEntry
{
2053 BDRVReopenState state
;
2054 QTAILQ_ENTRY(BlockReopenQueueEntry
) entry
;
2055 } BlockReopenQueueEntry
;
2058 * Return the flags that @bs will have after the reopens in @q have
2059 * successfully completed. If @q is NULL (or @bs is not contained in @q),
2060 * return the current flags.
2062 static int bdrv_reopen_get_flags(BlockReopenQueue
*q
, BlockDriverState
*bs
)
2064 BlockReopenQueueEntry
*entry
;
2067 QTAILQ_FOREACH(entry
, q
, entry
) {
2068 if (entry
->state
.bs
== bs
) {
2069 return entry
->state
.flags
;
2074 return bs
->open_flags
;
2077 /* Returns whether the image file can be written to after the reopen queue @q
2078 * has been successfully applied, or right now if @q is NULL. */
2079 static bool bdrv_is_writable_after_reopen(BlockDriverState
*bs
,
2080 BlockReopenQueue
*q
)
2082 int flags
= bdrv_reopen_get_flags(q
, bs
);
2084 return (flags
& (BDRV_O_RDWR
| BDRV_O_INACTIVE
)) == BDRV_O_RDWR
;
2088 * Return whether the BDS can be written to. This is not necessarily
2089 * the same as !bdrv_is_read_only(bs), as inactivated images may not
2090 * be written to but do not count as read-only images.
2092 bool bdrv_is_writable(BlockDriverState
*bs
)
2095 return bdrv_is_writable_after_reopen(bs
, NULL
);
2098 static char *bdrv_child_user_desc(BdrvChild
*c
)
2100 return c
->klass
->get_parent_desc(c
);
2104 * Check that @a allows everything that @b needs. @a and @b must reference same
2107 static bool bdrv_a_allow_b(BdrvChild
*a
, BdrvChild
*b
, Error
**errp
)
2109 const char *child_bs_name
;
2110 g_autofree
char *a_user
= NULL
;
2111 g_autofree
char *b_user
= NULL
;
2112 g_autofree
char *perms
= NULL
;
2115 assert(a
->bs
== b
->bs
);
2116 GLOBAL_STATE_CODE();
2118 if ((b
->perm
& a
->shared_perm
) == b
->perm
) {
2122 child_bs_name
= bdrv_get_node_name(b
->bs
);
2123 a_user
= bdrv_child_user_desc(a
);
2124 b_user
= bdrv_child_user_desc(b
);
2125 perms
= bdrv_perm_names(b
->perm
& ~a
->shared_perm
);
2127 error_setg(errp
, "Permission conflict on node '%s': permissions '%s' are "
2128 "both required by %s (uses node '%s' as '%s' child) and "
2129 "unshared by %s (uses node '%s' as '%s' child).",
2130 child_bs_name
, perms
,
2131 b_user
, child_bs_name
, b
->name
,
2132 a_user
, child_bs_name
, a
->name
);
2137 static bool bdrv_parent_perms_conflict(BlockDriverState
*bs
, Error
**errp
)
2140 GLOBAL_STATE_CODE();
2143 * During the loop we'll look at each pair twice. That's correct because
2144 * bdrv_a_allow_b() is asymmetric and we should check each pair in both
2147 QLIST_FOREACH(a
, &bs
->parents
, next_parent
) {
2148 QLIST_FOREACH(b
, &bs
->parents
, next_parent
) {
2153 if (!bdrv_a_allow_b(a
, b
, errp
)) {
2162 static void bdrv_child_perm(BlockDriverState
*bs
, BlockDriverState
*child_bs
,
2163 BdrvChild
*c
, BdrvChildRole role
,
2164 BlockReopenQueue
*reopen_queue
,
2165 uint64_t parent_perm
, uint64_t parent_shared
,
2166 uint64_t *nperm
, uint64_t *nshared
)
2168 assert(bs
->drv
&& bs
->drv
->bdrv_child_perm
);
2169 bs
->drv
->bdrv_child_perm(bs
, c
, role
, reopen_queue
,
2170 parent_perm
, parent_shared
,
2172 /* TODO Take force_share from reopen_queue */
2173 if (child_bs
&& child_bs
->force_share
) {
2174 *nshared
= BLK_PERM_ALL
;
2179 * Adds the whole subtree of @bs (including @bs itself) to the @list (except for
2180 * nodes that are already in the @list, of course) so that final list is
2181 * topologically sorted. Return the result (GSList @list object is updated, so
2182 * don't use old reference after function call).
2184 * On function start @list must be already topologically sorted and for any node
2185 * in the @list the whole subtree of the node must be in the @list as well. The
2186 * simplest way to satisfy this criteria: use only result of
2187 * bdrv_topological_dfs() or NULL as @list parameter.
2189 static GSList
*bdrv_topological_dfs(GSList
*list
, GHashTable
*found
,
2190 BlockDriverState
*bs
)
2193 g_autoptr(GHashTable
) local_found
= NULL
;
2197 found
= local_found
= g_hash_table_new(NULL
, NULL
);
2200 if (g_hash_table_contains(found
, bs
)) {
2203 g_hash_table_add(found
, bs
);
2205 QLIST_FOREACH(child
, &bs
->children
, next
) {
2206 list
= bdrv_topological_dfs(list
, found
, child
->bs
);
2209 return g_slist_prepend(list
, bs
);
2212 typedef struct BdrvChildSetPermState
{
2215 uint64_t old_shared_perm
;
2216 } BdrvChildSetPermState
;
2218 static void bdrv_child_set_perm_abort(void *opaque
)
2220 BdrvChildSetPermState
*s
= opaque
;
2222 GLOBAL_STATE_CODE();
2224 s
->child
->perm
= s
->old_perm
;
2225 s
->child
->shared_perm
= s
->old_shared_perm
;
2228 static TransactionActionDrv bdrv_child_set_pem_drv
= {
2229 .abort
= bdrv_child_set_perm_abort
,
2233 static void bdrv_child_set_perm(BdrvChild
*c
, uint64_t perm
,
2234 uint64_t shared
, Transaction
*tran
)
2236 BdrvChildSetPermState
*s
= g_new(BdrvChildSetPermState
, 1);
2237 GLOBAL_STATE_CODE();
2239 *s
= (BdrvChildSetPermState
) {
2241 .old_perm
= c
->perm
,
2242 .old_shared_perm
= c
->shared_perm
,
2246 c
->shared_perm
= shared
;
2248 tran_add(tran
, &bdrv_child_set_pem_drv
, s
);
2251 static void bdrv_drv_set_perm_commit(void *opaque
)
2253 BlockDriverState
*bs
= opaque
;
2254 uint64_t cumulative_perms
, cumulative_shared_perms
;
2256 if (bs
->drv
->bdrv_set_perm
) {
2257 bdrv_get_cumulative_perm(bs
, &cumulative_perms
,
2258 &cumulative_shared_perms
);
2259 bs
->drv
->bdrv_set_perm(bs
, cumulative_perms
, cumulative_shared_perms
);
2263 static void bdrv_drv_set_perm_abort(void *opaque
)
2265 BlockDriverState
*bs
= opaque
;
2267 if (bs
->drv
->bdrv_abort_perm_update
) {
2268 bs
->drv
->bdrv_abort_perm_update(bs
);
2272 TransactionActionDrv bdrv_drv_set_perm_drv
= {
2273 .abort
= bdrv_drv_set_perm_abort
,
2274 .commit
= bdrv_drv_set_perm_commit
,
2277 static int bdrv_drv_set_perm(BlockDriverState
*bs
, uint64_t perm
,
2278 uint64_t shared_perm
, Transaction
*tran
,
2285 if (bs
->drv
->bdrv_check_perm
) {
2286 int ret
= bs
->drv
->bdrv_check_perm(bs
, perm
, shared_perm
, errp
);
2293 tran_add(tran
, &bdrv_drv_set_perm_drv
, bs
);
2299 typedef struct BdrvReplaceChildState
{
2302 BlockDriverState
*old_bs
;
2303 bool free_empty_child
;
2304 } BdrvReplaceChildState
;
2306 static void bdrv_replace_child_commit(void *opaque
)
2308 BdrvReplaceChildState
*s
= opaque
;
2310 if (s
->free_empty_child
&& !s
->child
->bs
) {
2311 bdrv_child_free(s
->child
);
2313 bdrv_unref(s
->old_bs
);
2316 static void bdrv_replace_child_abort(void *opaque
)
2318 BdrvReplaceChildState
*s
= opaque
;
2319 BlockDriverState
*new_bs
= s
->child
->bs
;
2322 * old_bs reference is transparently moved from @s to s->child.
2324 * Pass &s->child here instead of s->childp, because:
2325 * (1) s->old_bs must be non-NULL, so bdrv_replace_child_noperm() will not
2326 * modify the BdrvChild * pointer we indirectly pass to it, i.e. it
2327 * will not modify s->child. From that perspective, it does not matter
2328 * whether we pass s->childp or &s->child.
2329 * (2) If new_bs is not NULL, s->childp will be NULL. We then cannot use
2331 * (3) If new_bs is NULL, *s->childp will have been NULLed by
2332 * bdrv_replace_child_tran()'s bdrv_replace_child_noperm() call, and we
2333 * must not pass a NULL *s->childp here.
2335 * So whether new_bs was NULL or not, we cannot pass s->childp here; and in
2336 * any case, there is no reason to pass it anyway.
2338 bdrv_replace_child_noperm(&s
->child
, s
->old_bs
, true);
2340 * The child was pre-existing, so s->old_bs must be non-NULL, and
2341 * s->child thus must not have been freed
2343 assert(s
->child
!= NULL
);
2345 /* As described above, *s->childp was cleared, so restore it */
2346 assert(s
->childp
!= NULL
);
2347 *s
->childp
= s
->child
;
2352 static TransactionActionDrv bdrv_replace_child_drv
= {
2353 .commit
= bdrv_replace_child_commit
,
2354 .abort
= bdrv_replace_child_abort
,
2359 * bdrv_replace_child_tran
2361 * Note: real unref of old_bs is done only on commit.
2363 * The function doesn't update permissions, caller is responsible for this.
2365 * (*childp)->bs must not be NULL.
2367 * Note that if new_bs == NULL, @childp is stored in a state object attached
2368 * to @tran, so that the old child can be reinstated in the abort handler.
2369 * Therefore, if @new_bs can be NULL, @childp must stay valid until the
2370 * transaction is committed or aborted.
2372 * If @free_empty_child is true and @new_bs is NULL, the BdrvChild is
2373 * freed (on commit). @free_empty_child should only be false if the
2374 * caller will free the BDrvChild themselves (which may be important
2375 * if this is in turn called in another transactional context).
2377 static void bdrv_replace_child_tran(BdrvChild
**childp
,
2378 BlockDriverState
*new_bs
,
2380 bool free_empty_child
)
2382 BdrvReplaceChildState
*s
= g_new(BdrvReplaceChildState
, 1);
2383 *s
= (BdrvReplaceChildState
) {
2385 .childp
= new_bs
== NULL
? childp
: NULL
,
2386 .old_bs
= (*childp
)->bs
,
2387 .free_empty_child
= free_empty_child
,
2389 tran_add(tran
, &bdrv_replace_child_drv
, s
);
2391 /* The abort handler relies on this */
2392 assert(s
->old_bs
!= NULL
);
2398 * Pass free_empty_child=false, we will free the child (if
2399 * necessary) in bdrv_replace_child_commit() (if our
2400 * @free_empty_child parameter was true).
2402 bdrv_replace_child_noperm(childp
, new_bs
, false);
2403 /* old_bs reference is transparently moved from *childp to @s */
2407 * Refresh permissions in @bs subtree. The function is intended to be called
2408 * after some graph modification that was done without permission update.
2410 static int bdrv_node_refresh_perm(BlockDriverState
*bs
, BlockReopenQueue
*q
,
2411 Transaction
*tran
, Error
**errp
)
2413 BlockDriver
*drv
= bs
->drv
;
2416 uint64_t cumulative_perms
, cumulative_shared_perms
;
2417 GLOBAL_STATE_CODE();
2419 bdrv_get_cumulative_perm(bs
, &cumulative_perms
, &cumulative_shared_perms
);
2421 /* Write permissions never work with read-only images */
2422 if ((cumulative_perms
& (BLK_PERM_WRITE
| BLK_PERM_WRITE_UNCHANGED
)) &&
2423 !bdrv_is_writable_after_reopen(bs
, q
))
2425 if (!bdrv_is_writable_after_reopen(bs
, NULL
)) {
2426 error_setg(errp
, "Block node is read-only");
2428 error_setg(errp
, "Read-only block node '%s' cannot support "
2429 "read-write users", bdrv_get_node_name(bs
));
2436 * Unaligned requests will automatically be aligned to bl.request_alignment
2437 * and without RESIZE we can't extend requests to write to space beyond the
2438 * end of the image, so it's required that the image size is aligned.
2440 if ((cumulative_perms
& (BLK_PERM_WRITE
| BLK_PERM_WRITE_UNCHANGED
)) &&
2441 !(cumulative_perms
& BLK_PERM_RESIZE
))
2443 if ((bs
->total_sectors
* BDRV_SECTOR_SIZE
) % bs
->bl
.request_alignment
) {
2444 error_setg(errp
, "Cannot get 'write' permission without 'resize': "
2445 "Image size is not a multiple of request "
2451 /* Check this node */
2456 ret
= bdrv_drv_set_perm(bs
, cumulative_perms
, cumulative_shared_perms
, tran
,
2462 /* Drivers that never have children can omit .bdrv_child_perm() */
2463 if (!drv
->bdrv_child_perm
) {
2464 assert(QLIST_EMPTY(&bs
->children
));
2468 /* Check all children */
2469 QLIST_FOREACH(c
, &bs
->children
, next
) {
2470 uint64_t cur_perm
, cur_shared
;
2472 bdrv_child_perm(bs
, c
->bs
, c
, c
->role
, q
,
2473 cumulative_perms
, cumulative_shared_perms
,
2474 &cur_perm
, &cur_shared
);
2475 bdrv_child_set_perm(c
, cur_perm
, cur_shared
, tran
);
2481 static int bdrv_list_refresh_perms(GSList
*list
, BlockReopenQueue
*q
,
2482 Transaction
*tran
, Error
**errp
)
2485 BlockDriverState
*bs
;
2486 GLOBAL_STATE_CODE();
2488 for ( ; list
; list
= list
->next
) {
2491 if (bdrv_parent_perms_conflict(bs
, errp
)) {
2495 ret
= bdrv_node_refresh_perm(bs
, q
, tran
, errp
);
2504 void bdrv_get_cumulative_perm(BlockDriverState
*bs
, uint64_t *perm
,
2505 uint64_t *shared_perm
)
2508 uint64_t cumulative_perms
= 0;
2509 uint64_t cumulative_shared_perms
= BLK_PERM_ALL
;
2511 GLOBAL_STATE_CODE();
2513 QLIST_FOREACH(c
, &bs
->parents
, next_parent
) {
2514 cumulative_perms
|= c
->perm
;
2515 cumulative_shared_perms
&= c
->shared_perm
;
2518 *perm
= cumulative_perms
;
2519 *shared_perm
= cumulative_shared_perms
;
2522 char *bdrv_perm_names(uint64_t perm
)
2528 { BLK_PERM_CONSISTENT_READ
, "consistent read" },
2529 { BLK_PERM_WRITE
, "write" },
2530 { BLK_PERM_WRITE_UNCHANGED
, "write unchanged" },
2531 { BLK_PERM_RESIZE
, "resize" },
2535 GString
*result
= g_string_sized_new(30);
2536 struct perm_name
*p
;
2538 for (p
= permissions
; p
->name
; p
++) {
2539 if (perm
& p
->perm
) {
2540 if (result
->len
> 0) {
2541 g_string_append(result
, ", ");
2543 g_string_append(result
, p
->name
);
2547 return g_string_free(result
, FALSE
);
2551 static int bdrv_refresh_perms(BlockDriverState
*bs
, Error
**errp
)
2554 Transaction
*tran
= tran_new();
2555 g_autoptr(GSList
) list
= bdrv_topological_dfs(NULL
, NULL
, bs
);
2556 GLOBAL_STATE_CODE();
2558 ret
= bdrv_list_refresh_perms(list
, NULL
, tran
, errp
);
2559 tran_finalize(tran
, ret
);
2564 int bdrv_child_try_set_perm(BdrvChild
*c
, uint64_t perm
, uint64_t shared
,
2567 Error
*local_err
= NULL
;
2568 Transaction
*tran
= tran_new();
2571 GLOBAL_STATE_CODE();
2573 bdrv_child_set_perm(c
, perm
, shared
, tran
);
2575 ret
= bdrv_refresh_perms(c
->bs
, &local_err
);
2577 tran_finalize(tran
, ret
);
2580 if ((perm
& ~c
->perm
) || (c
->shared_perm
& ~shared
)) {
2581 /* tighten permissions */
2582 error_propagate(errp
, local_err
);
2585 * Our caller may intend to only loosen restrictions and
2586 * does not expect this function to fail. Errors are not
2587 * fatal in such a case, so we can just hide them from our
2590 error_free(local_err
);
2598 int bdrv_child_refresh_perms(BlockDriverState
*bs
, BdrvChild
*c
, Error
**errp
)
2600 uint64_t parent_perms
, parent_shared
;
2601 uint64_t perms
, shared
;
2603 GLOBAL_STATE_CODE();
2605 bdrv_get_cumulative_perm(bs
, &parent_perms
, &parent_shared
);
2606 bdrv_child_perm(bs
, c
->bs
, c
, c
->role
, NULL
,
2607 parent_perms
, parent_shared
, &perms
, &shared
);
2609 return bdrv_child_try_set_perm(c
, perms
, shared
, errp
);
2613 * Default implementation for .bdrv_child_perm() for block filters:
2614 * Forward CONSISTENT_READ, WRITE, WRITE_UNCHANGED, and RESIZE to the
2617 static void bdrv_filter_default_perms(BlockDriverState
*bs
, BdrvChild
*c
,
2619 BlockReopenQueue
*reopen_queue
,
2620 uint64_t perm
, uint64_t shared
,
2621 uint64_t *nperm
, uint64_t *nshared
)
2623 GLOBAL_STATE_CODE();
2624 *nperm
= perm
& DEFAULT_PERM_PASSTHROUGH
;
2625 *nshared
= (shared
& DEFAULT_PERM_PASSTHROUGH
) | DEFAULT_PERM_UNCHANGED
;
2628 static void bdrv_default_perms_for_cow(BlockDriverState
*bs
, BdrvChild
*c
,
2630 BlockReopenQueue
*reopen_queue
,
2631 uint64_t perm
, uint64_t shared
,
2632 uint64_t *nperm
, uint64_t *nshared
)
2634 assert(role
& BDRV_CHILD_COW
);
2635 GLOBAL_STATE_CODE();
2638 * We want consistent read from backing files if the parent needs it.
2639 * No other operations are performed on backing files.
2641 perm
&= BLK_PERM_CONSISTENT_READ
;
2644 * If the parent can deal with changing data, we're okay with a
2645 * writable and resizable backing file.
2646 * TODO Require !(perm & BLK_PERM_CONSISTENT_READ), too?
2648 if (shared
& BLK_PERM_WRITE
) {
2649 shared
= BLK_PERM_WRITE
| BLK_PERM_RESIZE
;
2654 shared
|= BLK_PERM_CONSISTENT_READ
| BLK_PERM_WRITE_UNCHANGED
;
2656 if (bs
->open_flags
& BDRV_O_INACTIVE
) {
2657 shared
|= BLK_PERM_WRITE
| BLK_PERM_RESIZE
;
2664 static void bdrv_default_perms_for_storage(BlockDriverState
*bs
, BdrvChild
*c
,
2666 BlockReopenQueue
*reopen_queue
,
2667 uint64_t perm
, uint64_t shared
,
2668 uint64_t *nperm
, uint64_t *nshared
)
2672 GLOBAL_STATE_CODE();
2673 assert(role
& (BDRV_CHILD_METADATA
| BDRV_CHILD_DATA
));
2675 flags
= bdrv_reopen_get_flags(reopen_queue
, bs
);
2678 * Apart from the modifications below, the same permissions are
2679 * forwarded and left alone as for filters
2681 bdrv_filter_default_perms(bs
, c
, role
, reopen_queue
,
2682 perm
, shared
, &perm
, &shared
);
2684 if (role
& BDRV_CHILD_METADATA
) {
2685 /* Format drivers may touch metadata even if the guest doesn't write */
2686 if (bdrv_is_writable_after_reopen(bs
, reopen_queue
)) {
2687 perm
|= BLK_PERM_WRITE
| BLK_PERM_RESIZE
;
2691 * bs->file always needs to be consistent because of the
2692 * metadata. We can never allow other users to resize or write
2695 if (!(flags
& BDRV_O_NO_IO
)) {
2696 perm
|= BLK_PERM_CONSISTENT_READ
;
2698 shared
&= ~(BLK_PERM_WRITE
| BLK_PERM_RESIZE
);
2701 if (role
& BDRV_CHILD_DATA
) {
2703 * Technically, everything in this block is a subset of the
2704 * BDRV_CHILD_METADATA path taken above, and so this could
2705 * be an "else if" branch. However, that is not obvious, and
2706 * this function is not performance critical, therefore we let
2707 * this be an independent "if".
2711 * We cannot allow other users to resize the file because the
2712 * format driver might have some assumptions about the size
2713 * (e.g. because it is stored in metadata, or because the file
2714 * is split into fixed-size data files).
2716 shared
&= ~BLK_PERM_RESIZE
;
2719 * WRITE_UNCHANGED often cannot be performed as such on the
2720 * data file. For example, the qcow2 driver may still need to
2721 * write copied clusters on copy-on-read.
2723 if (perm
& BLK_PERM_WRITE_UNCHANGED
) {
2724 perm
|= BLK_PERM_WRITE
;
2728 * If the data file is written to, the format driver may
2729 * expect to be able to resize it by writing beyond the EOF.
2731 if (perm
& BLK_PERM_WRITE
) {
2732 perm
|= BLK_PERM_RESIZE
;
2736 if (bs
->open_flags
& BDRV_O_INACTIVE
) {
2737 shared
|= BLK_PERM_WRITE
| BLK_PERM_RESIZE
;
2744 void bdrv_default_perms(BlockDriverState
*bs
, BdrvChild
*c
,
2745 BdrvChildRole role
, BlockReopenQueue
*reopen_queue
,
2746 uint64_t perm
, uint64_t shared
,
2747 uint64_t *nperm
, uint64_t *nshared
)
2749 GLOBAL_STATE_CODE();
2750 if (role
& BDRV_CHILD_FILTERED
) {
2751 assert(!(role
& (BDRV_CHILD_DATA
| BDRV_CHILD_METADATA
|
2753 bdrv_filter_default_perms(bs
, c
, role
, reopen_queue
,
2754 perm
, shared
, nperm
, nshared
);
2755 } else if (role
& BDRV_CHILD_COW
) {
2756 assert(!(role
& (BDRV_CHILD_DATA
| BDRV_CHILD_METADATA
)));
2757 bdrv_default_perms_for_cow(bs
, c
, role
, reopen_queue
,
2758 perm
, shared
, nperm
, nshared
);
2759 } else if (role
& (BDRV_CHILD_METADATA
| BDRV_CHILD_DATA
)) {
2760 bdrv_default_perms_for_storage(bs
, c
, role
, reopen_queue
,
2761 perm
, shared
, nperm
, nshared
);
2763 g_assert_not_reached();
2767 uint64_t bdrv_qapi_perm_to_blk_perm(BlockPermission qapi_perm
)
2769 static const uint64_t permissions
[] = {
2770 [BLOCK_PERMISSION_CONSISTENT_READ
] = BLK_PERM_CONSISTENT_READ
,
2771 [BLOCK_PERMISSION_WRITE
] = BLK_PERM_WRITE
,
2772 [BLOCK_PERMISSION_WRITE_UNCHANGED
] = BLK_PERM_WRITE_UNCHANGED
,
2773 [BLOCK_PERMISSION_RESIZE
] = BLK_PERM_RESIZE
,
2776 QEMU_BUILD_BUG_ON(ARRAY_SIZE(permissions
) != BLOCK_PERMISSION__MAX
);
2777 QEMU_BUILD_BUG_ON(1UL << ARRAY_SIZE(permissions
) != BLK_PERM_ALL
+ 1);
2779 assert(qapi_perm
< BLOCK_PERMISSION__MAX
);
2781 return permissions
[qapi_perm
];
2785 * Replace (*childp)->bs by @new_bs.
2787 * If @new_bs is NULL, *childp will be set to NULL, too: BDS parents
2788 * generally cannot handle a BdrvChild with .bs == NULL, so clearing
2789 * BdrvChild.bs should generally immediately be followed by the
2790 * BdrvChild pointer being cleared as well.
2792 * If @free_empty_child is true and @new_bs is NULL, the BdrvChild is
2793 * freed. @free_empty_child should only be false if the caller will
2794 * free the BdrvChild themselves (this may be important in a
2795 * transactional context, where it may only be freed on commit).
2797 static void bdrv_replace_child_noperm(BdrvChild
**childp
,
2798 BlockDriverState
*new_bs
,
2799 bool free_empty_child
)
2801 BdrvChild
*child
= *childp
;
2802 BlockDriverState
*old_bs
= child
->bs
;
2803 int new_bs_quiesce_counter
;
2806 assert(!child
->frozen
);
2807 assert(old_bs
!= new_bs
);
2809 if (old_bs
&& new_bs
) {
2810 assert(bdrv_get_aio_context(old_bs
) == bdrv_get_aio_context(new_bs
));
2813 new_bs_quiesce_counter
= (new_bs
? new_bs
->quiesce_counter
: 0);
2814 drain_saldo
= new_bs_quiesce_counter
- child
->parent_quiesce_counter
;
2817 * If the new child node is drained but the old one was not, flush
2818 * all outstanding requests to the old child node.
2820 while (drain_saldo
> 0 && child
->klass
->drained_begin
) {
2821 bdrv_parent_drained_begin_single(child
, true);
2826 /* Detach first so that the recursive drain sections coming from @child
2827 * are already gone and we only end the drain sections that came from
2829 if (child
->klass
->detach
) {
2830 child
->klass
->detach(child
);
2832 QLIST_REMOVE(child
, next_parent
);
2841 QLIST_INSERT_HEAD(&new_bs
->parents
, child
, next_parent
);
2844 * Detaching the old node may have led to the new node's
2845 * quiesce_counter having been decreased. Not a problem, we
2846 * just need to recognize this here and then invoke
2847 * drained_end appropriately more often.
2849 assert(new_bs
->quiesce_counter
<= new_bs_quiesce_counter
);
2850 drain_saldo
+= new_bs
->quiesce_counter
- new_bs_quiesce_counter
;
2852 /* Attach only after starting new drained sections, so that recursive
2853 * drain sections coming from @child don't get an extra .drained_begin
2855 if (child
->klass
->attach
) {
2856 child
->klass
->attach(child
);
2861 * If the old child node was drained but the new one is not, allow
2862 * requests to come in only after the new node has been attached.
2864 while (drain_saldo
< 0 && child
->klass
->drained_end
) {
2865 bdrv_parent_drained_end_single(child
);
2869 if (free_empty_child
&& !child
->bs
) {
2870 bdrv_child_free(child
);
2875 * Free the given @child.
2877 * The child must be empty (i.e. `child->bs == NULL`) and it must be
2878 * unused (i.e. not in a children list).
2880 static void bdrv_child_free(BdrvChild
*child
)
2883 assert(!child
->next
.le_prev
); /* not in children list */
2885 g_free(child
->name
);
2889 typedef struct BdrvAttachChildCommonState
{
2891 AioContext
*old_parent_ctx
;
2892 AioContext
*old_child_ctx
;
2893 } BdrvAttachChildCommonState
;
2895 static void bdrv_attach_child_common_abort(void *opaque
)
2897 BdrvAttachChildCommonState
*s
= opaque
;
2898 BdrvChild
*child
= *s
->child
;
2899 BlockDriverState
*bs
= child
->bs
;
2902 * Pass free_empty_child=false, because we still need the child
2903 * for the AioContext operations on the parent below; those
2904 * BdrvChildClass methods all work on a BdrvChild object, so we
2905 * need to keep it as an empty shell (after this function, it will
2906 * not be attached to any parent, and it will not have a .bs).
2908 bdrv_replace_child_noperm(s
->child
, NULL
, false);
2910 if (bdrv_get_aio_context(bs
) != s
->old_child_ctx
) {
2911 bdrv_try_set_aio_context(bs
, s
->old_child_ctx
, &error_abort
);
2914 if (bdrv_child_get_parent_aio_context(child
) != s
->old_parent_ctx
) {
2917 /* No need to ignore `child`, because it has been detached already */
2919 child
->klass
->can_set_aio_ctx(child
, s
->old_parent_ctx
, &ignore
,
2921 g_slist_free(ignore
);
2924 child
->klass
->set_aio_ctx(child
, s
->old_parent_ctx
, &ignore
);
2925 g_slist_free(ignore
);
2929 bdrv_child_free(child
);
2932 static TransactionActionDrv bdrv_attach_child_common_drv
= {
2933 .abort
= bdrv_attach_child_common_abort
,
2938 * Common part of attaching bdrv child to bs or to blk or to job
2940 * Resulting new child is returned through @child.
2941 * At start *@child must be NULL.
2942 * @child is saved to a new entry of @tran, so that *@child could be reverted to
2943 * NULL on abort(). So referenced variable must live at least until transaction
2946 * Function doesn't update permissions, caller is responsible for this.
2948 static int bdrv_attach_child_common(BlockDriverState
*child_bs
,
2949 const char *child_name
,
2950 const BdrvChildClass
*child_class
,
2951 BdrvChildRole child_role
,
2952 uint64_t perm
, uint64_t shared_perm
,
2953 void *opaque
, BdrvChild
**child
,
2954 Transaction
*tran
, Error
**errp
)
2956 BdrvChild
*new_child
;
2957 AioContext
*parent_ctx
;
2958 AioContext
*child_ctx
= bdrv_get_aio_context(child_bs
);
2961 assert(*child
== NULL
);
2962 assert(child_class
->get_parent_desc
);
2964 new_child
= g_new(BdrvChild
, 1);
2965 *new_child
= (BdrvChild
) {
2967 .name
= g_strdup(child_name
),
2968 .klass
= child_class
,
2971 .shared_perm
= shared_perm
,
2976 * If the AioContexts don't match, first try to move the subtree of
2977 * child_bs into the AioContext of the new parent. If this doesn't work,
2978 * try moving the parent into the AioContext of child_bs instead.
2980 parent_ctx
= bdrv_child_get_parent_aio_context(new_child
);
2981 if (child_ctx
!= parent_ctx
) {
2982 Error
*local_err
= NULL
;
2983 int ret
= bdrv_try_set_aio_context(child_bs
, parent_ctx
, &local_err
);
2985 if (ret
< 0 && child_class
->can_set_aio_ctx
) {
2986 GSList
*ignore
= g_slist_prepend(NULL
, new_child
);
2987 if (child_class
->can_set_aio_ctx(new_child
, child_ctx
, &ignore
,
2990 error_free(local_err
);
2992 g_slist_free(ignore
);
2993 ignore
= g_slist_prepend(NULL
, new_child
);
2994 child_class
->set_aio_ctx(new_child
, child_ctx
, &ignore
);
2996 g_slist_free(ignore
);
3000 error_propagate(errp
, local_err
);
3001 bdrv_child_free(new_child
);
3007 bdrv_replace_child_noperm(&new_child
, child_bs
, true);
3008 /* child_bs was non-NULL, so new_child must not have been freed */
3009 assert(new_child
!= NULL
);
3013 BdrvAttachChildCommonState
*s
= g_new(BdrvAttachChildCommonState
, 1);
3014 *s
= (BdrvAttachChildCommonState
) {
3016 .old_parent_ctx
= parent_ctx
,
3017 .old_child_ctx
= child_ctx
,
3019 tran_add(tran
, &bdrv_attach_child_common_drv
, s
);
3025 * Variable referenced by @child must live at least until transaction end.
3026 * (see bdrv_attach_child_common() doc for details)
3028 * Function doesn't update permissions, caller is responsible for this.
3030 static int bdrv_attach_child_noperm(BlockDriverState
*parent_bs
,
3031 BlockDriverState
*child_bs
,
3032 const char *child_name
,
3033 const BdrvChildClass
*child_class
,
3034 BdrvChildRole child_role
,
3040 uint64_t perm
, shared_perm
;
3042 assert(parent_bs
->drv
);
3044 if (bdrv_recurse_has_child(child_bs
, parent_bs
)) {
3045 error_setg(errp
, "Making '%s' a %s child of '%s' would create a cycle",
3046 child_bs
->node_name
, child_name
, parent_bs
->node_name
);
3050 bdrv_get_cumulative_perm(parent_bs
, &perm
, &shared_perm
);
3051 bdrv_child_perm(parent_bs
, child_bs
, NULL
, child_role
, NULL
,
3052 perm
, shared_perm
, &perm
, &shared_perm
);
3054 ret
= bdrv_attach_child_common(child_bs
, child_name
, child_class
,
3055 child_role
, perm
, shared_perm
, parent_bs
,
3064 static void bdrv_detach_child(BdrvChild
**childp
)
3066 BlockDriverState
*old_bs
= (*childp
)->bs
;
3068 bdrv_replace_child_noperm(childp
, NULL
, true);
3072 * Update permissions for old node. We're just taking a parent away, so
3073 * we're loosening restrictions. Errors of permission update are not
3074 * fatal in this case, ignore them.
3076 bdrv_refresh_perms(old_bs
, NULL
);
3079 * When the parent requiring a non-default AioContext is removed, the
3080 * node moves back to the main AioContext
3082 bdrv_try_set_aio_context(old_bs
, qemu_get_aio_context(), NULL
);
3087 * This function steals the reference to child_bs from the caller.
3088 * That reference is later dropped by bdrv_root_unref_child().
3090 * On failure NULL is returned, errp is set and the reference to
3091 * child_bs is also dropped.
3093 * The caller must hold the AioContext lock @child_bs, but not that of @ctx
3094 * (unless @child_bs is already in @ctx).
3096 BdrvChild
*bdrv_root_attach_child(BlockDriverState
*child_bs
,
3097 const char *child_name
,
3098 const BdrvChildClass
*child_class
,
3099 BdrvChildRole child_role
,
3100 uint64_t perm
, uint64_t shared_perm
,
3101 void *opaque
, Error
**errp
)
3104 BdrvChild
*child
= NULL
;
3105 Transaction
*tran
= tran_new();
3107 GLOBAL_STATE_CODE();
3109 ret
= bdrv_attach_child_common(child_bs
, child_name
, child_class
,
3110 child_role
, perm
, shared_perm
, opaque
,
3111 &child
, tran
, errp
);
3116 ret
= bdrv_refresh_perms(child_bs
, errp
);
3119 tran_finalize(tran
, ret
);
3120 /* child is unset on failure by bdrv_attach_child_common_abort() */
3121 assert((ret
< 0) == !child
);
3123 bdrv_unref(child_bs
);
3128 * This function transfers the reference to child_bs from the caller
3129 * to parent_bs. That reference is later dropped by parent_bs on
3130 * bdrv_close() or if someone calls bdrv_unref_child().
3132 * On failure NULL is returned, errp is set and the reference to
3133 * child_bs is also dropped.
3135 * If @parent_bs and @child_bs are in different AioContexts, the caller must
3136 * hold the AioContext lock for @child_bs, but not for @parent_bs.
3138 BdrvChild
*bdrv_attach_child(BlockDriverState
*parent_bs
,
3139 BlockDriverState
*child_bs
,
3140 const char *child_name
,
3141 const BdrvChildClass
*child_class
,
3142 BdrvChildRole child_role
,
3146 BdrvChild
*child
= NULL
;
3147 Transaction
*tran
= tran_new();
3149 GLOBAL_STATE_CODE();
3151 ret
= bdrv_attach_child_noperm(parent_bs
, child_bs
, child_name
, child_class
,
3152 child_role
, &child
, tran
, errp
);
3157 ret
= bdrv_refresh_perms(parent_bs
, errp
);
3163 tran_finalize(tran
, ret
);
3164 /* child is unset on failure by bdrv_attach_child_common_abort() */
3165 assert((ret
< 0) == !child
);
3167 bdrv_unref(child_bs
);
3172 /* Callers must ensure that child->frozen is false. */
3173 void bdrv_root_unref_child(BdrvChild
*child
)
3175 BlockDriverState
*child_bs
;
3177 GLOBAL_STATE_CODE();
3179 child_bs
= child
->bs
;
3180 bdrv_detach_child(&child
);
3181 bdrv_unref(child_bs
);
3184 typedef struct BdrvSetInheritsFrom
{
3185 BlockDriverState
*bs
;
3186 BlockDriverState
*old_inherits_from
;
3187 } BdrvSetInheritsFrom
;
3189 static void bdrv_set_inherits_from_abort(void *opaque
)
3191 BdrvSetInheritsFrom
*s
= opaque
;
3193 s
->bs
->inherits_from
= s
->old_inherits_from
;
3196 static TransactionActionDrv bdrv_set_inherits_from_drv
= {
3197 .abort
= bdrv_set_inherits_from_abort
,
3201 /* @tran is allowed to be NULL. In this case no rollback is possible */
3202 static void bdrv_set_inherits_from(BlockDriverState
*bs
,
3203 BlockDriverState
*new_inherits_from
,
3207 BdrvSetInheritsFrom
*s
= g_new(BdrvSetInheritsFrom
, 1);
3209 *s
= (BdrvSetInheritsFrom
) {
3211 .old_inherits_from
= bs
->inherits_from
,
3214 tran_add(tran
, &bdrv_set_inherits_from_drv
, s
);
3217 bs
->inherits_from
= new_inherits_from
;
3221 * Clear all inherits_from pointers from children and grandchildren of
3222 * @root that point to @root, where necessary.
3223 * @tran is allowed to be NULL. In this case no rollback is possible
3225 static void bdrv_unset_inherits_from(BlockDriverState
*root
, BdrvChild
*child
,
3230 if (child
->bs
->inherits_from
== root
) {
3232 * Remove inherits_from only when the last reference between root and
3233 * child->bs goes away.
3235 QLIST_FOREACH(c
, &root
->children
, next
) {
3236 if (c
!= child
&& c
->bs
== child
->bs
) {
3241 bdrv_set_inherits_from(child
->bs
, NULL
, tran
);
3245 QLIST_FOREACH(c
, &child
->bs
->children
, next
) {
3246 bdrv_unset_inherits_from(root
, c
, tran
);
3250 /* Callers must ensure that child->frozen is false. */
3251 void bdrv_unref_child(BlockDriverState
*parent
, BdrvChild
*child
)
3253 GLOBAL_STATE_CODE();
3254 if (child
== NULL
) {
3258 bdrv_unset_inherits_from(parent
, child
, NULL
);
3259 bdrv_root_unref_child(child
);
3263 static void bdrv_parent_cb_change_media(BlockDriverState
*bs
, bool load
)
3266 QLIST_FOREACH(c
, &bs
->parents
, next_parent
) {
3267 if (c
->klass
->change_media
) {
3268 c
->klass
->change_media(c
, load
);
3273 /* Return true if you can reach parent going through child->inherits_from
3274 * recursively. If parent or child are NULL, return false */
3275 static bool bdrv_inherits_from_recursive(BlockDriverState
*child
,
3276 BlockDriverState
*parent
)
3278 while (child
&& child
!= parent
) {
3279 child
= child
->inherits_from
;
3282 return child
!= NULL
;
3286 * Return the BdrvChildRole for @bs's backing child. bs->backing is
3287 * mostly used for COW backing children (role = COW), but also for
3288 * filtered children (role = FILTERED | PRIMARY).
3290 static BdrvChildRole
bdrv_backing_role(BlockDriverState
*bs
)
3292 if (bs
->drv
&& bs
->drv
->is_filter
) {
3293 return BDRV_CHILD_FILTERED
| BDRV_CHILD_PRIMARY
;
3295 return BDRV_CHILD_COW
;
3300 * Sets the bs->backing or bs->file link of a BDS. A new reference is created;
3301 * callers which don't need their own reference any more must call bdrv_unref().
3303 * Function doesn't update permissions, caller is responsible for this.
3305 static int bdrv_set_file_or_backing_noperm(BlockDriverState
*parent_bs
,
3306 BlockDriverState
*child_bs
,
3308 Transaction
*tran
, Error
**errp
)
3311 bool update_inherits_from
=
3312 bdrv_inherits_from_recursive(child_bs
, parent_bs
);
3313 BdrvChild
*child
= is_backing
? parent_bs
->backing
: parent_bs
->file
;
3316 if (!parent_bs
->drv
) {
3318 * Node without drv is an object without a class :/. TODO: finally fix
3319 * qcow2 driver to never clear bs->drv and implement format corruption
3320 * handling in other way.
3322 error_setg(errp
, "Node corrupted");
3326 if (child
&& child
->frozen
) {
3327 error_setg(errp
, "Cannot change frozen '%s' link from '%s' to '%s'",
3328 child
->name
, parent_bs
->node_name
, child
->bs
->node_name
);
3332 if (is_backing
&& !parent_bs
->drv
->is_filter
&&
3333 !parent_bs
->drv
->supports_backing
)
3335 error_setg(errp
, "Driver '%s' of node '%s' does not support backing "
3336 "files", parent_bs
->drv
->format_name
, parent_bs
->node_name
);
3340 if (parent_bs
->drv
->is_filter
) {
3341 role
= BDRV_CHILD_FILTERED
| BDRV_CHILD_PRIMARY
;
3342 } else if (is_backing
) {
3343 role
= BDRV_CHILD_COW
;
3346 * We only can use same role as it is in existing child. We don't have
3347 * infrastructure to determine role of file child in generic way
3350 error_setg(errp
, "Cannot set file child to format node without "
3358 bdrv_unset_inherits_from(parent_bs
, child
, tran
);
3359 bdrv_remove_file_or_backing_child(parent_bs
, child
, tran
);
3366 ret
= bdrv_attach_child_noperm(parent_bs
, child_bs
,
3367 is_backing
? "backing" : "file",
3368 &child_of_bds
, role
,
3369 is_backing
? &parent_bs
->backing
:
3378 * If inherits_from pointed recursively to bs then let's update it to
3379 * point directly to bs (else it will become NULL).
3381 if (update_inherits_from
) {
3382 bdrv_set_inherits_from(child_bs
, parent_bs
, tran
);
3386 bdrv_refresh_limits(parent_bs
, tran
, NULL
);
3391 static int bdrv_set_backing_noperm(BlockDriverState
*bs
,
3392 BlockDriverState
*backing_hd
,
3393 Transaction
*tran
, Error
**errp
)
3395 return bdrv_set_file_or_backing_noperm(bs
, backing_hd
, true, tran
, errp
);
3398 int bdrv_set_backing_hd(BlockDriverState
*bs
, BlockDriverState
*backing_hd
,
3402 Transaction
*tran
= tran_new();
3404 GLOBAL_STATE_CODE();
3405 bdrv_drained_begin(bs
);
3407 ret
= bdrv_set_backing_noperm(bs
, backing_hd
, tran
, errp
);
3412 ret
= bdrv_refresh_perms(bs
, errp
);
3414 tran_finalize(tran
, ret
);
3416 bdrv_drained_end(bs
);
3422 * Opens the backing file for a BlockDriverState if not yet open
3424 * bdref_key specifies the key for the image's BlockdevRef in the options QDict.
3425 * That QDict has to be flattened; therefore, if the BlockdevRef is a QDict
3426 * itself, all options starting with "${bdref_key}." are considered part of the
3429 * TODO Can this be unified with bdrv_open_image()?
3431 int bdrv_open_backing_file(BlockDriverState
*bs
, QDict
*parent_options
,
3432 const char *bdref_key
, Error
**errp
)
3434 char *backing_filename
= NULL
;
3435 char *bdref_key_dot
;
3436 const char *reference
= NULL
;
3438 bool implicit_backing
= false;
3439 BlockDriverState
*backing_hd
;
3441 QDict
*tmp_parent_options
= NULL
;
3442 Error
*local_err
= NULL
;
3444 GLOBAL_STATE_CODE();
3446 if (bs
->backing
!= NULL
) {
3450 /* NULL means an empty set of options */
3451 if (parent_options
== NULL
) {
3452 tmp_parent_options
= qdict_new();
3453 parent_options
= tmp_parent_options
;
3456 bs
->open_flags
&= ~BDRV_O_NO_BACKING
;
3458 bdref_key_dot
= g_strdup_printf("%s.", bdref_key
);
3459 qdict_extract_subqdict(parent_options
, &options
, bdref_key_dot
);
3460 g_free(bdref_key_dot
);
3463 * Caution: while qdict_get_try_str() is fine, getting non-string
3464 * types would require more care. When @parent_options come from
3465 * -blockdev or blockdev_add, its members are typed according to
3466 * the QAPI schema, but when they come from -drive, they're all
3469 reference
= qdict_get_try_str(parent_options
, bdref_key
);
3470 if (reference
|| qdict_haskey(options
, "file.filename")) {
3471 /* keep backing_filename NULL */
3472 } else if (bs
->backing_file
[0] == '\0' && qdict_size(options
) == 0) {
3473 qobject_unref(options
);
3476 if (qdict_size(options
) == 0) {
3477 /* If the user specifies options that do not modify the
3478 * backing file's behavior, we might still consider it the
3479 * implicit backing file. But it's easier this way, and
3480 * just specifying some of the backing BDS's options is
3481 * only possible with -drive anyway (otherwise the QAPI
3482 * schema forces the user to specify everything). */
3483 implicit_backing
= !strcmp(bs
->auto_backing_file
, bs
->backing_file
);
3486 backing_filename
= bdrv_get_full_backing_filename(bs
, &local_err
);
3489 error_propagate(errp
, local_err
);
3490 qobject_unref(options
);
3495 if (!bs
->drv
|| !bs
->drv
->supports_backing
) {
3497 error_setg(errp
, "Driver doesn't support backing files");
3498 qobject_unref(options
);
3503 bs
->backing_format
[0] != '\0' && !qdict_haskey(options
, "driver")) {
3504 qdict_put_str(options
, "driver", bs
->backing_format
);
3507 backing_hd
= bdrv_open_inherit(backing_filename
, reference
, options
, 0, bs
,
3508 &child_of_bds
, bdrv_backing_role(bs
), errp
);
3510 bs
->open_flags
|= BDRV_O_NO_BACKING
;
3511 error_prepend(errp
, "Could not open backing file: ");
3516 if (implicit_backing
) {
3517 bdrv_refresh_filename(backing_hd
);
3518 pstrcpy(bs
->auto_backing_file
, sizeof(bs
->auto_backing_file
),
3519 backing_hd
->filename
);
3522 /* Hook up the backing file link; drop our reference, bs owns the
3523 * backing_hd reference now */
3524 ret
= bdrv_set_backing_hd(bs
, backing_hd
, errp
);
3525 bdrv_unref(backing_hd
);
3530 qdict_del(parent_options
, bdref_key
);
3533 g_free(backing_filename
);
3534 qobject_unref(tmp_parent_options
);
3538 static BlockDriverState
*
3539 bdrv_open_child_bs(const char *filename
, QDict
*options
, const char *bdref_key
,
3540 BlockDriverState
*parent
, const BdrvChildClass
*child_class
,
3541 BdrvChildRole child_role
, bool allow_none
, Error
**errp
)
3543 BlockDriverState
*bs
= NULL
;
3544 QDict
*image_options
;
3545 char *bdref_key_dot
;
3546 const char *reference
;
3548 assert(child_class
!= NULL
);
3550 bdref_key_dot
= g_strdup_printf("%s.", bdref_key
);
3551 qdict_extract_subqdict(options
, &image_options
, bdref_key_dot
);
3552 g_free(bdref_key_dot
);
3555 * Caution: while qdict_get_try_str() is fine, getting non-string
3556 * types would require more care. When @options come from
3557 * -blockdev or blockdev_add, its members are typed according to
3558 * the QAPI schema, but when they come from -drive, they're all
3561 reference
= qdict_get_try_str(options
, bdref_key
);
3562 if (!filename
&& !reference
&& !qdict_size(image_options
)) {
3564 error_setg(errp
, "A block device must be specified for \"%s\"",
3567 qobject_unref(image_options
);
3571 bs
= bdrv_open_inherit(filename
, reference
, image_options
, 0,
3572 parent
, child_class
, child_role
, errp
);
3578 qdict_del(options
, bdref_key
);
3583 * Opens a disk image whose options are given as BlockdevRef in another block
3586 * If allow_none is true, no image will be opened if filename is false and no
3587 * BlockdevRef is given. NULL will be returned, but errp remains unset.
3589 * bdrev_key specifies the key for the image's BlockdevRef in the options QDict.
3590 * That QDict has to be flattened; therefore, if the BlockdevRef is a QDict
3591 * itself, all options starting with "${bdref_key}." are considered part of the
3594 * The BlockdevRef will be removed from the options QDict.
3596 BdrvChild
*bdrv_open_child(const char *filename
,
3597 QDict
*options
, const char *bdref_key
,
3598 BlockDriverState
*parent
,
3599 const BdrvChildClass
*child_class
,
3600 BdrvChildRole child_role
,
3601 bool allow_none
, Error
**errp
)
3603 BlockDriverState
*bs
;
3605 GLOBAL_STATE_CODE();
3607 bs
= bdrv_open_child_bs(filename
, options
, bdref_key
, parent
, child_class
,
3608 child_role
, allow_none
, errp
);
3613 return bdrv_attach_child(parent
, bs
, bdref_key
, child_class
, child_role
,
3618 * TODO Future callers may need to specify parent/child_class in order for
3619 * option inheritance to work. Existing callers use it for the root node.
3621 BlockDriverState
*bdrv_open_blockdev_ref(BlockdevRef
*ref
, Error
**errp
)
3623 BlockDriverState
*bs
= NULL
;
3624 QObject
*obj
= NULL
;
3625 QDict
*qdict
= NULL
;
3626 const char *reference
= NULL
;
3629 GLOBAL_STATE_CODE();
3631 if (ref
->type
== QTYPE_QSTRING
) {
3632 reference
= ref
->u
.reference
;
3634 BlockdevOptions
*options
= &ref
->u
.definition
;
3635 assert(ref
->type
== QTYPE_QDICT
);
3637 v
= qobject_output_visitor_new(&obj
);
3638 visit_type_BlockdevOptions(v
, NULL
, &options
, &error_abort
);
3639 visit_complete(v
, &obj
);
3641 qdict
= qobject_to(QDict
, obj
);
3642 qdict_flatten(qdict
);
3644 /* bdrv_open_inherit() defaults to the values in bdrv_flags (for
3645 * compatibility with other callers) rather than what we want as the
3646 * real defaults. Apply the defaults here instead. */
3647 qdict_set_default_str(qdict
, BDRV_OPT_CACHE_DIRECT
, "off");
3648 qdict_set_default_str(qdict
, BDRV_OPT_CACHE_NO_FLUSH
, "off");
3649 qdict_set_default_str(qdict
, BDRV_OPT_READ_ONLY
, "off");
3650 qdict_set_default_str(qdict
, BDRV_OPT_AUTO_READ_ONLY
, "off");
3654 bs
= bdrv_open_inherit(NULL
, reference
, qdict
, 0, NULL
, NULL
, 0, errp
);
3661 static BlockDriverState
*bdrv_append_temp_snapshot(BlockDriverState
*bs
,
3663 QDict
*snapshot_options
,
3666 /* TODO: extra byte is a hack to ensure MAX_PATH space on Windows. */
3667 char *tmp_filename
= g_malloc0(PATH_MAX
+ 1);
3669 QemuOpts
*opts
= NULL
;
3670 BlockDriverState
*bs_snapshot
= NULL
;
3673 /* if snapshot, we create a temporary backing file and open it
3674 instead of opening 'filename' directly */
3676 /* Get the required size from the image */
3677 total_size
= bdrv_getlength(bs
);
3678 if (total_size
< 0) {
3679 error_setg_errno(errp
, -total_size
, "Could not get image size");
3683 /* Create the temporary image */
3684 ret
= get_tmp_filename(tmp_filename
, PATH_MAX
+ 1);
3686 error_setg_errno(errp
, -ret
, "Could not get temporary filename");
3690 opts
= qemu_opts_create(bdrv_qcow2
.create_opts
, NULL
, 0,
3692 qemu_opt_set_number(opts
, BLOCK_OPT_SIZE
, total_size
, &error_abort
);
3693 ret
= bdrv_create(&bdrv_qcow2
, tmp_filename
, opts
, errp
);
3694 qemu_opts_del(opts
);
3696 error_prepend(errp
, "Could not create temporary overlay '%s': ",
3701 /* Prepare options QDict for the temporary file */
3702 qdict_put_str(snapshot_options
, "file.driver", "file");
3703 qdict_put_str(snapshot_options
, "file.filename", tmp_filename
);
3704 qdict_put_str(snapshot_options
, "driver", "qcow2");
3706 bs_snapshot
= bdrv_open(NULL
, NULL
, snapshot_options
, flags
, errp
);
3707 snapshot_options
= NULL
;
3712 ret
= bdrv_append(bs_snapshot
, bs
, errp
);
3719 qobject_unref(snapshot_options
);
3720 g_free(tmp_filename
);
3725 * Opens a disk image (raw, qcow2, vmdk, ...)
3727 * options is a QDict of options to pass to the block drivers, or NULL for an
3728 * empty set of options. The reference to the QDict belongs to the block layer
3729 * after the call (even on failure), so if the caller intends to reuse the
3730 * dictionary, it needs to use qobject_ref() before calling bdrv_open.
3732 * If *pbs is NULL, a new BDS will be created with a pointer to it stored there.
3733 * If it is not NULL, the referenced BDS will be reused.
3735 * The reference parameter may be used to specify an existing block device which
3736 * should be opened. If specified, neither options nor a filename may be given,
3737 * nor can an existing BDS be reused (that is, *pbs has to be NULL).
3739 static BlockDriverState
*bdrv_open_inherit(const char *filename
,
3740 const char *reference
,
3741 QDict
*options
, int flags
,
3742 BlockDriverState
*parent
,
3743 const BdrvChildClass
*child_class
,
3744 BdrvChildRole child_role
,
3748 BlockBackend
*file
= NULL
;
3749 BlockDriverState
*bs
;
3750 BlockDriver
*drv
= NULL
;
3752 const char *drvname
;
3753 const char *backing
;
3754 Error
*local_err
= NULL
;
3755 QDict
*snapshot_options
= NULL
;
3756 int snapshot_flags
= 0;
3758 assert(!child_class
|| !flags
);
3759 assert(!child_class
== !parent
);
3762 bool options_non_empty
= options
? qdict_size(options
) : false;
3763 qobject_unref(options
);
3765 if (filename
|| options_non_empty
) {
3766 error_setg(errp
, "Cannot reference an existing block device with "
3767 "additional options or a new filename");
3771 bs
= bdrv_lookup_bs(reference
, reference
, errp
);
3782 /* NULL means an empty set of options */
3783 if (options
== NULL
) {
3784 options
= qdict_new();
3787 /* json: syntax counts as explicit options, as if in the QDict */
3788 parse_json_protocol(options
, &filename
, &local_err
);
3793 bs
->explicit_options
= qdict_clone_shallow(options
);
3796 bool parent_is_format
;
3799 parent_is_format
= parent
->drv
->is_format
;
3802 * parent->drv is not set yet because this node is opened for
3803 * (potential) format probing. That means that @parent is going
3804 * to be a format node.
3806 parent_is_format
= true;
3809 bs
->inherits_from
= parent
;
3810 child_class
->inherit_options(child_role
, parent_is_format
,
3812 parent
->open_flags
, parent
->options
);
3815 ret
= bdrv_fill_options(&options
, filename
, &flags
, &local_err
);
3821 * Set the BDRV_O_RDWR and BDRV_O_ALLOW_RDWR flags.
3822 * Caution: getting a boolean member of @options requires care.
3823 * When @options come from -blockdev or blockdev_add, members are
3824 * typed according to the QAPI schema, but when they come from
3825 * -drive, they're all QString.
3827 if (g_strcmp0(qdict_get_try_str(options
, BDRV_OPT_READ_ONLY
), "on") &&
3828 !qdict_get_try_bool(options
, BDRV_OPT_READ_ONLY
, false)) {
3829 flags
|= (BDRV_O_RDWR
| BDRV_O_ALLOW_RDWR
);
3831 flags
&= ~BDRV_O_RDWR
;
3834 if (flags
& BDRV_O_SNAPSHOT
) {
3835 snapshot_options
= qdict_new();
3836 bdrv_temp_snapshot_options(&snapshot_flags
, snapshot_options
,
3838 /* Let bdrv_backing_options() override "read-only" */
3839 qdict_del(options
, BDRV_OPT_READ_ONLY
);
3840 bdrv_inherited_options(BDRV_CHILD_COW
, true,
3841 &flags
, options
, flags
, options
);
3844 bs
->open_flags
= flags
;
3845 bs
->options
= options
;
3846 options
= qdict_clone_shallow(options
);
3848 /* Find the right image format driver */
3849 /* See cautionary note on accessing @options above */
3850 drvname
= qdict_get_try_str(options
, "driver");
3852 drv
= bdrv_find_format(drvname
);
3854 error_setg(errp
, "Unknown driver: '%s'", drvname
);
3859 assert(drvname
|| !(flags
& BDRV_O_PROTOCOL
));
3861 /* See cautionary note on accessing @options above */
3862 backing
= qdict_get_try_str(options
, "backing");
3863 if (qobject_to(QNull
, qdict_get(options
, "backing")) != NULL
||
3864 (backing
&& *backing
== '\0'))
3867 warn_report("Use of \"backing\": \"\" is deprecated; "
3868 "use \"backing\": null instead");
3870 flags
|= BDRV_O_NO_BACKING
;
3871 qdict_del(bs
->explicit_options
, "backing");
3872 qdict_del(bs
->options
, "backing");
3873 qdict_del(options
, "backing");
3876 /* Open image file without format layer. This BlockBackend is only used for
3877 * probing, the block drivers will do their own bdrv_open_child() for the
3878 * same BDS, which is why we put the node name back into options. */
3879 if ((flags
& BDRV_O_PROTOCOL
) == 0) {
3880 BlockDriverState
*file_bs
;
3882 file_bs
= bdrv_open_child_bs(filename
, options
, "file", bs
,
3883 &child_of_bds
, BDRV_CHILD_IMAGE
,
3888 if (file_bs
!= NULL
) {
3889 /* Not requesting BLK_PERM_CONSISTENT_READ because we're only
3890 * looking at the header to guess the image format. This works even
3891 * in cases where a guest would not see a consistent state. */
3892 file
= blk_new(bdrv_get_aio_context(file_bs
), 0, BLK_PERM_ALL
);
3893 blk_insert_bs(file
, file_bs
, &local_err
);
3894 bdrv_unref(file_bs
);
3899 qdict_put_str(options
, "file", bdrv_get_node_name(file_bs
));
3903 /* Image format probing */
3906 ret
= find_image_format(file
, filename
, &drv
, &local_err
);
3911 * This option update would logically belong in bdrv_fill_options(),
3912 * but we first need to open bs->file for the probing to work, while
3913 * opening bs->file already requires the (mostly) final set of options
3914 * so that cache mode etc. can be inherited.
3916 * Adding the driver later is somewhat ugly, but it's not an option
3917 * that would ever be inherited, so it's correct. We just need to make
3918 * sure to update both bs->options (which has the full effective
3919 * options for bs) and options (which has file.* already removed).
3921 qdict_put_str(bs
->options
, "driver", drv
->format_name
);
3922 qdict_put_str(options
, "driver", drv
->format_name
);
3924 error_setg(errp
, "Must specify either driver or file");
3928 /* BDRV_O_PROTOCOL must be set iff a protocol BDS is about to be created */
3929 assert(!!(flags
& BDRV_O_PROTOCOL
) == !!drv
->bdrv_file_open
);
3930 /* file must be NULL if a protocol BDS is about to be created
3931 * (the inverse results in an error message from bdrv_open_common()) */
3932 assert(!(flags
& BDRV_O_PROTOCOL
) || !file
);
3934 /* Open the image */
3935 ret
= bdrv_open_common(bs
, file
, options
, &local_err
);
3945 /* If there is a backing file, use it */
3946 if ((flags
& BDRV_O_NO_BACKING
) == 0) {
3947 ret
= bdrv_open_backing_file(bs
, options
, "backing", &local_err
);
3949 goto close_and_fail
;
3953 /* Remove all children options and references
3954 * from bs->options and bs->explicit_options */
3955 QLIST_FOREACH(child
, &bs
->children
, next
) {
3956 char *child_key_dot
;
3957 child_key_dot
= g_strdup_printf("%s.", child
->name
);
3958 qdict_extract_subqdict(bs
->explicit_options
, NULL
, child_key_dot
);
3959 qdict_extract_subqdict(bs
->options
, NULL
, child_key_dot
);
3960 qdict_del(bs
->explicit_options
, child
->name
);
3961 qdict_del(bs
->options
, child
->name
);
3962 g_free(child_key_dot
);
3965 /* Check if any unknown options were used */
3966 if (qdict_size(options
) != 0) {
3967 const QDictEntry
*entry
= qdict_first(options
);
3968 if (flags
& BDRV_O_PROTOCOL
) {
3969 error_setg(errp
, "Block protocol '%s' doesn't support the option "
3970 "'%s'", drv
->format_name
, entry
->key
);
3973 "Block format '%s' does not support the option '%s'",
3974 drv
->format_name
, entry
->key
);
3977 goto close_and_fail
;
3980 bdrv_parent_cb_change_media(bs
, true);
3982 qobject_unref(options
);
3985 /* For snapshot=on, create a temporary qcow2 overlay. bs points to the
3986 * temporary snapshot afterwards. */
3987 if (snapshot_flags
) {
3988 BlockDriverState
*snapshot_bs
;
3989 snapshot_bs
= bdrv_append_temp_snapshot(bs
, snapshot_flags
,
3990 snapshot_options
, &local_err
);
3991 snapshot_options
= NULL
;
3993 goto close_and_fail
;
3995 /* We are not going to return bs but the overlay on top of it
3996 * (snapshot_bs); thus, we have to drop the strong reference to bs
3997 * (which we obtained by calling bdrv_new()). bs will not be deleted,
3998 * though, because the overlay still has a reference to it. */
4007 qobject_unref(snapshot_options
);
4008 qobject_unref(bs
->explicit_options
);
4009 qobject_unref(bs
->options
);
4010 qobject_unref(options
);
4012 bs
->explicit_options
= NULL
;
4014 error_propagate(errp
, local_err
);
4019 qobject_unref(snapshot_options
);
4020 qobject_unref(options
);
4021 error_propagate(errp
, local_err
);
4025 BlockDriverState
*bdrv_open(const char *filename
, const char *reference
,
4026 QDict
*options
, int flags
, Error
**errp
)
4028 GLOBAL_STATE_CODE();
4030 return bdrv_open_inherit(filename
, reference
, options
, flags
, NULL
,
4034 /* Return true if the NULL-terminated @list contains @str */
4035 static bool is_str_in_list(const char *str
, const char *const *list
)
4039 for (i
= 0; list
[i
] != NULL
; i
++) {
4040 if (!strcmp(str
, list
[i
])) {
4049 * Check that every option set in @bs->options is also set in
4052 * Options listed in the common_options list and in
4053 * @bs->drv->mutable_opts are skipped.
4055 * Return 0 on success, otherwise return -EINVAL and set @errp.
4057 static int bdrv_reset_options_allowed(BlockDriverState
*bs
,
4058 const QDict
*new_opts
, Error
**errp
)
4060 const QDictEntry
*e
;
4061 /* These options are common to all block drivers and are handled
4062 * in bdrv_reopen_prepare() so they can be left out of @new_opts */
4063 const char *const common_options
[] = {
4064 "node-name", "discard", "cache.direct", "cache.no-flush",
4065 "read-only", "auto-read-only", "detect-zeroes", NULL
4068 for (e
= qdict_first(bs
->options
); e
; e
= qdict_next(bs
->options
, e
)) {
4069 if (!qdict_haskey(new_opts
, e
->key
) &&
4070 !is_str_in_list(e
->key
, common_options
) &&
4071 !is_str_in_list(e
->key
, bs
->drv
->mutable_opts
)) {
4072 error_setg(errp
, "Option '%s' cannot be reset "
4073 "to its default value", e
->key
);
4082 * Returns true if @child can be reached recursively from @bs
4084 static bool bdrv_recurse_has_child(BlockDriverState
*bs
,
4085 BlockDriverState
*child
)
4093 QLIST_FOREACH(c
, &bs
->children
, next
) {
4094 if (bdrv_recurse_has_child(c
->bs
, child
)) {
4103 * Adds a BlockDriverState to a simple queue for an atomic, transactional
4104 * reopen of multiple devices.
4106 * bs_queue can either be an existing BlockReopenQueue that has had QTAILQ_INIT
4107 * already performed, or alternatively may be NULL a new BlockReopenQueue will
4108 * be created and initialized. This newly created BlockReopenQueue should be
4109 * passed back in for subsequent calls that are intended to be of the same
4112 * bs is the BlockDriverState to add to the reopen queue.
4114 * options contains the changed options for the associated bs
4115 * (the BlockReopenQueue takes ownership)
4117 * flags contains the open flags for the associated bs
4119 * returns a pointer to bs_queue, which is either the newly allocated
4120 * bs_queue, or the existing bs_queue being used.
4122 * bs must be drained between bdrv_reopen_queue() and bdrv_reopen_multiple().
4124 static BlockReopenQueue
*bdrv_reopen_queue_child(BlockReopenQueue
*bs_queue
,
4125 BlockDriverState
*bs
,
4127 const BdrvChildClass
*klass
,
4129 bool parent_is_format
,
4130 QDict
*parent_options
,
4136 BlockReopenQueueEntry
*bs_entry
;
4138 QDict
*old_options
, *explicit_options
, *options_copy
;
4142 /* Make sure that the caller remembered to use a drained section. This is
4143 * important to avoid graph changes between the recursive queuing here and
4144 * bdrv_reopen_multiple(). */
4145 assert(bs
->quiesce_counter
> 0);
4147 if (bs_queue
== NULL
) {
4148 bs_queue
= g_new0(BlockReopenQueue
, 1);
4149 QTAILQ_INIT(bs_queue
);
4153 options
= qdict_new();
4156 /* Check if this BlockDriverState is already in the queue */
4157 QTAILQ_FOREACH(bs_entry
, bs_queue
, entry
) {
4158 if (bs
== bs_entry
->state
.bs
) {
4164 * Precedence of options:
4165 * 1. Explicitly passed in options (highest)
4166 * 2. Retained from explicitly set options of bs
4167 * 3. Inherited from parent node
4168 * 4. Retained from effective options of bs
4171 /* Old explicitly set values (don't overwrite by inherited value) */
4172 if (bs_entry
|| keep_old_opts
) {
4173 old_options
= qdict_clone_shallow(bs_entry
?
4174 bs_entry
->state
.explicit_options
:
4175 bs
->explicit_options
);
4176 bdrv_join_options(bs
, options
, old_options
);
4177 qobject_unref(old_options
);
4180 explicit_options
= qdict_clone_shallow(options
);
4182 /* Inherit from parent node */
4183 if (parent_options
) {
4185 klass
->inherit_options(role
, parent_is_format
, &flags
, options
,
4186 parent_flags
, parent_options
);
4188 flags
= bdrv_get_flags(bs
);
4191 if (keep_old_opts
) {
4192 /* Old values are used for options that aren't set yet */
4193 old_options
= qdict_clone_shallow(bs
->options
);
4194 bdrv_join_options(bs
, options
, old_options
);
4195 qobject_unref(old_options
);
4198 /* We have the final set of options so let's update the flags */
4199 options_copy
= qdict_clone_shallow(options
);
4200 opts
= qemu_opts_create(&bdrv_runtime_opts
, NULL
, 0, &error_abort
);
4201 qemu_opts_absorb_qdict(opts
, options_copy
, NULL
);
4202 update_flags_from_options(&flags
, opts
);
4203 qemu_opts_del(opts
);
4204 qobject_unref(options_copy
);
4206 /* bdrv_open_inherit() sets and clears some additional flags internally */
4207 flags
&= ~BDRV_O_PROTOCOL
;
4208 if (flags
& BDRV_O_RDWR
) {
4209 flags
|= BDRV_O_ALLOW_RDWR
;
4213 bs_entry
= g_new0(BlockReopenQueueEntry
, 1);
4214 QTAILQ_INSERT_TAIL(bs_queue
, bs_entry
, entry
);
4216 qobject_unref(bs_entry
->state
.options
);
4217 qobject_unref(bs_entry
->state
.explicit_options
);
4220 bs_entry
->state
.bs
= bs
;
4221 bs_entry
->state
.options
= options
;
4222 bs_entry
->state
.explicit_options
= explicit_options
;
4223 bs_entry
->state
.flags
= flags
;
4226 * If keep_old_opts is false then it means that unspecified
4227 * options must be reset to their original value. We don't allow
4228 * resetting 'backing' but we need to know if the option is
4229 * missing in order to decide if we have to return an error.
4231 if (!keep_old_opts
) {
4232 bs_entry
->state
.backing_missing
=
4233 !qdict_haskey(options
, "backing") &&
4234 !qdict_haskey(options
, "backing.driver");
4237 QLIST_FOREACH(child
, &bs
->children
, next
) {
4238 QDict
*new_child_options
= NULL
;
4239 bool child_keep_old
= keep_old_opts
;
4241 /* reopen can only change the options of block devices that were
4242 * implicitly created and inherited options. For other (referenced)
4243 * block devices, a syntax like "backing.foo" results in an error. */
4244 if (child
->bs
->inherits_from
!= bs
) {
4248 /* Check if the options contain a child reference */
4249 if (qdict_haskey(options
, child
->name
)) {
4250 const char *childref
= qdict_get_try_str(options
, child
->name
);
4252 * The current child must not be reopened if the child
4253 * reference is null or points to a different node.
4255 if (g_strcmp0(childref
, child
->bs
->node_name
)) {
4259 * If the child reference points to the current child then
4260 * reopen it with its existing set of options (note that
4261 * it can still inherit new options from the parent).
4263 child_keep_old
= true;
4265 /* Extract child options ("child-name.*") */
4266 char *child_key_dot
= g_strdup_printf("%s.", child
->name
);
4267 qdict_extract_subqdict(explicit_options
, NULL
, child_key_dot
);
4268 qdict_extract_subqdict(options
, &new_child_options
, child_key_dot
);
4269 g_free(child_key_dot
);
4272 bdrv_reopen_queue_child(bs_queue
, child
->bs
, new_child_options
,
4273 child
->klass
, child
->role
, bs
->drv
->is_format
,
4274 options
, flags
, child_keep_old
);
4280 BlockReopenQueue
*bdrv_reopen_queue(BlockReopenQueue
*bs_queue
,
4281 BlockDriverState
*bs
,
4282 QDict
*options
, bool keep_old_opts
)
4284 GLOBAL_STATE_CODE();
4286 return bdrv_reopen_queue_child(bs_queue
, bs
, options
, NULL
, 0, false,
4287 NULL
, 0, keep_old_opts
);
4290 void bdrv_reopen_queue_free(BlockReopenQueue
*bs_queue
)
4292 GLOBAL_STATE_CODE();
4294 BlockReopenQueueEntry
*bs_entry
, *next
;
4295 QTAILQ_FOREACH_SAFE(bs_entry
, bs_queue
, entry
, next
) {
4296 qobject_unref(bs_entry
->state
.explicit_options
);
4297 qobject_unref(bs_entry
->state
.options
);
4305 * Reopen multiple BlockDriverStates atomically & transactionally.
4307 * The queue passed in (bs_queue) must have been built up previous
4308 * via bdrv_reopen_queue().
4310 * Reopens all BDS specified in the queue, with the appropriate
4311 * flags. All devices are prepared for reopen, and failure of any
4312 * device will cause all device changes to be abandoned, and intermediate
4315 * If all devices prepare successfully, then the changes are committed
4318 * All affected nodes must be drained between bdrv_reopen_queue() and
4319 * bdrv_reopen_multiple().
4321 * To be called from the main thread, with all other AioContexts unlocked.
4323 int bdrv_reopen_multiple(BlockReopenQueue
*bs_queue
, Error
**errp
)
4326 BlockReopenQueueEntry
*bs_entry
, *next
;
4328 Transaction
*tran
= tran_new();
4329 g_autoptr(GHashTable
) found
= NULL
;
4330 g_autoptr(GSList
) refresh_list
= NULL
;
4332 assert(qemu_get_current_aio_context() == qemu_get_aio_context());
4333 assert(bs_queue
!= NULL
);
4335 QTAILQ_FOREACH(bs_entry
, bs_queue
, entry
) {
4336 ctx
= bdrv_get_aio_context(bs_entry
->state
.bs
);
4337 aio_context_acquire(ctx
);
4338 ret
= bdrv_flush(bs_entry
->state
.bs
);
4339 aio_context_release(ctx
);
4341 error_setg_errno(errp
, -ret
, "Error flushing drive");
4346 QTAILQ_FOREACH(bs_entry
, bs_queue
, entry
) {
4347 assert(bs_entry
->state
.bs
->quiesce_counter
> 0);
4348 ctx
= bdrv_get_aio_context(bs_entry
->state
.bs
);
4349 aio_context_acquire(ctx
);
4350 ret
= bdrv_reopen_prepare(&bs_entry
->state
, bs_queue
, tran
, errp
);
4351 aio_context_release(ctx
);
4355 bs_entry
->prepared
= true;
4358 found
= g_hash_table_new(NULL
, NULL
);
4359 QTAILQ_FOREACH(bs_entry
, bs_queue
, entry
) {
4360 BDRVReopenState
*state
= &bs_entry
->state
;
4362 refresh_list
= bdrv_topological_dfs(refresh_list
, found
, state
->bs
);
4363 if (state
->old_backing_bs
) {
4364 refresh_list
= bdrv_topological_dfs(refresh_list
, found
,
4365 state
->old_backing_bs
);
4367 if (state
->old_file_bs
) {
4368 refresh_list
= bdrv_topological_dfs(refresh_list
, found
,
4369 state
->old_file_bs
);
4374 * Note that file-posix driver rely on permission update done during reopen
4375 * (even if no permission changed), because it wants "new" permissions for
4376 * reconfiguring the fd and that's why it does it in raw_check_perm(), not
4377 * in raw_reopen_prepare() which is called with "old" permissions.
4379 ret
= bdrv_list_refresh_perms(refresh_list
, bs_queue
, tran
, errp
);
4385 * If we reach this point, we have success and just need to apply the
4388 * Reverse order is used to comfort qcow2 driver: on commit it need to write
4389 * IN_USE flag to the image, to mark bitmaps in the image as invalid. But
4390 * children are usually goes after parents in reopen-queue, so go from last
4393 QTAILQ_FOREACH_REVERSE(bs_entry
, bs_queue
, entry
) {
4394 ctx
= bdrv_get_aio_context(bs_entry
->state
.bs
);
4395 aio_context_acquire(ctx
);
4396 bdrv_reopen_commit(&bs_entry
->state
);
4397 aio_context_release(ctx
);
4402 QTAILQ_FOREACH_REVERSE(bs_entry
, bs_queue
, entry
) {
4403 BlockDriverState
*bs
= bs_entry
->state
.bs
;
4405 if (bs
->drv
->bdrv_reopen_commit_post
) {
4406 ctx
= bdrv_get_aio_context(bs
);
4407 aio_context_acquire(ctx
);
4408 bs
->drv
->bdrv_reopen_commit_post(&bs_entry
->state
);
4409 aio_context_release(ctx
);
4418 QTAILQ_FOREACH_SAFE(bs_entry
, bs_queue
, entry
, next
) {
4419 if (bs_entry
->prepared
) {
4420 ctx
= bdrv_get_aio_context(bs_entry
->state
.bs
);
4421 aio_context_acquire(ctx
);
4422 bdrv_reopen_abort(&bs_entry
->state
);
4423 aio_context_release(ctx
);
4428 bdrv_reopen_queue_free(bs_queue
);
4433 int bdrv_reopen(BlockDriverState
*bs
, QDict
*opts
, bool keep_old_opts
,
4436 AioContext
*ctx
= bdrv_get_aio_context(bs
);
4437 BlockReopenQueue
*queue
;
4440 GLOBAL_STATE_CODE();
4442 bdrv_subtree_drained_begin(bs
);
4443 if (ctx
!= qemu_get_aio_context()) {
4444 aio_context_release(ctx
);
4447 queue
= bdrv_reopen_queue(NULL
, bs
, opts
, keep_old_opts
);
4448 ret
= bdrv_reopen_multiple(queue
, errp
);
4450 if (ctx
!= qemu_get_aio_context()) {
4451 aio_context_acquire(ctx
);
4453 bdrv_subtree_drained_end(bs
);
4458 int bdrv_reopen_set_read_only(BlockDriverState
*bs
, bool read_only
,
4461 QDict
*opts
= qdict_new();
4463 GLOBAL_STATE_CODE();
4465 qdict_put_bool(opts
, BDRV_OPT_READ_ONLY
, read_only
);
4467 return bdrv_reopen(bs
, opts
, true, errp
);
4471 * Take a BDRVReopenState and check if the value of 'backing' in the
4472 * reopen_state->options QDict is valid or not.
4474 * If 'backing' is missing from the QDict then return 0.
4476 * If 'backing' contains the node name of the backing file of
4477 * reopen_state->bs then return 0.
4479 * If 'backing' contains a different node name (or is null) then check
4480 * whether the current backing file can be replaced with the new one.
4481 * If that's the case then reopen_state->replace_backing_bs is set to
4482 * true and reopen_state->new_backing_bs contains a pointer to the new
4483 * backing BlockDriverState (or NULL).
4485 * Return 0 on success, otherwise return < 0 and set @errp.
4487 static int bdrv_reopen_parse_file_or_backing(BDRVReopenState
*reopen_state
,
4488 bool is_backing
, Transaction
*tran
,
4491 BlockDriverState
*bs
= reopen_state
->bs
;
4492 BlockDriverState
*new_child_bs
;
4493 BlockDriverState
*old_child_bs
= is_backing
? child_bs(bs
->backing
) :
4495 const char *child_name
= is_backing
? "backing" : "file";
4499 value
= qdict_get(reopen_state
->options
, child_name
);
4500 if (value
== NULL
) {
4504 switch (qobject_type(value
)) {
4506 assert(is_backing
); /* The 'file' option does not allow a null value */
4507 new_child_bs
= NULL
;
4510 str
= qstring_get_str(qobject_to(QString
, value
));
4511 new_child_bs
= bdrv_lookup_bs(NULL
, str
, errp
);
4512 if (new_child_bs
== NULL
) {
4514 } else if (bdrv_recurse_has_child(new_child_bs
, bs
)) {
4515 error_setg(errp
, "Making '%s' a %s child of '%s' would create a "
4516 "cycle", str
, child_name
, bs
->node_name
);
4522 * The options QDict has been flattened, so 'backing' and 'file'
4523 * do not allow any other data type here.
4525 g_assert_not_reached();
4528 if (old_child_bs
== new_child_bs
) {
4533 if (bdrv_skip_implicit_filters(old_child_bs
) == new_child_bs
) {
4537 if (old_child_bs
->implicit
) {
4538 error_setg(errp
, "Cannot replace implicit %s child of %s",
4539 child_name
, bs
->node_name
);
4544 if (bs
->drv
->is_filter
&& !old_child_bs
) {
4546 * Filters always have a file or a backing child, so we are trying to
4547 * change wrong child
4549 error_setg(errp
, "'%s' is a %s filter node that does not support a "
4550 "%s child", bs
->node_name
, bs
->drv
->format_name
, child_name
);
4555 reopen_state
->old_backing_bs
= old_child_bs
;
4557 reopen_state
->old_file_bs
= old_child_bs
;
4560 return bdrv_set_file_or_backing_noperm(bs
, new_child_bs
, is_backing
,
4565 * Prepares a BlockDriverState for reopen. All changes are staged in the
4566 * 'opaque' field of the BDRVReopenState, which is used and allocated by
4567 * the block driver layer .bdrv_reopen_prepare()
4569 * bs is the BlockDriverState to reopen
4570 * flags are the new open flags
4571 * queue is the reopen queue
4573 * Returns 0 on success, non-zero on error. On error errp will be set
4576 * On failure, bdrv_reopen_abort() will be called to clean up any data.
4577 * It is the responsibility of the caller to then call the abort() or
4578 * commit() for any other BDS that have been left in a prepare() state
4581 static int bdrv_reopen_prepare(BDRVReopenState
*reopen_state
,
4582 BlockReopenQueue
*queue
,
4583 Transaction
*change_child_tran
, Error
**errp
)
4587 Error
*local_err
= NULL
;
4590 QDict
*orig_reopen_opts
;
4591 char *discard
= NULL
;
4593 bool drv_prepared
= false;
4595 assert(reopen_state
!= NULL
);
4596 assert(reopen_state
->bs
->drv
!= NULL
);
4597 drv
= reopen_state
->bs
->drv
;
4599 /* This function and each driver's bdrv_reopen_prepare() remove
4600 * entries from reopen_state->options as they are processed, so
4601 * we need to make a copy of the original QDict. */
4602 orig_reopen_opts
= qdict_clone_shallow(reopen_state
->options
);
4604 /* Process generic block layer options */
4605 opts
= qemu_opts_create(&bdrv_runtime_opts
, NULL
, 0, &error_abort
);
4606 if (!qemu_opts_absorb_qdict(opts
, reopen_state
->options
, errp
)) {
4611 /* This was already called in bdrv_reopen_queue_child() so the flags
4612 * are up-to-date. This time we simply want to remove the options from
4613 * QemuOpts in order to indicate that they have been processed. */
4614 old_flags
= reopen_state
->flags
;
4615 update_flags_from_options(&reopen_state
->flags
, opts
);
4616 assert(old_flags
== reopen_state
->flags
);
4618 discard
= qemu_opt_get_del(opts
, BDRV_OPT_DISCARD
);
4619 if (discard
!= NULL
) {
4620 if (bdrv_parse_discard_flags(discard
, &reopen_state
->flags
) != 0) {
4621 error_setg(errp
, "Invalid discard option");
4627 reopen_state
->detect_zeroes
=
4628 bdrv_parse_detect_zeroes(opts
, reopen_state
->flags
, &local_err
);
4630 error_propagate(errp
, local_err
);
4635 /* All other options (including node-name and driver) must be unchanged.
4636 * Put them back into the QDict, so that they are checked at the end
4637 * of this function. */
4638 qemu_opts_to_qdict(opts
, reopen_state
->options
);
4640 /* If we are to stay read-only, do not allow permission change
4641 * to r/w. Attempting to set to r/w may fail if either BDRV_O_ALLOW_RDWR is
4642 * not set, or if the BDS still has copy_on_read enabled */
4643 read_only
= !(reopen_state
->flags
& BDRV_O_RDWR
);
4644 ret
= bdrv_can_set_read_only(reopen_state
->bs
, read_only
, true, &local_err
);
4646 error_propagate(errp
, local_err
);
4650 if (drv
->bdrv_reopen_prepare
) {
4652 * If a driver-specific option is missing, it means that we
4653 * should reset it to its default value.
4654 * But not all options allow that, so we need to check it first.
4656 ret
= bdrv_reset_options_allowed(reopen_state
->bs
,
4657 reopen_state
->options
, errp
);
4662 ret
= drv
->bdrv_reopen_prepare(reopen_state
, queue
, &local_err
);
4664 if (local_err
!= NULL
) {
4665 error_propagate(errp
, local_err
);
4667 bdrv_refresh_filename(reopen_state
->bs
);
4668 error_setg(errp
, "failed while preparing to reopen image '%s'",
4669 reopen_state
->bs
->filename
);
4674 /* It is currently mandatory to have a bdrv_reopen_prepare()
4675 * handler for each supported drv. */
4676 error_setg(errp
, "Block format '%s' used by node '%s' "
4677 "does not support reopening files", drv
->format_name
,
4678 bdrv_get_device_or_node_name(reopen_state
->bs
));
4683 drv_prepared
= true;
4686 * We must provide the 'backing' option if the BDS has a backing
4687 * file or if the image file has a backing file name as part of
4688 * its metadata. Otherwise the 'backing' option can be omitted.
4690 if (drv
->supports_backing
&& reopen_state
->backing_missing
&&
4691 (reopen_state
->bs
->backing
|| reopen_state
->bs
->backing_file
[0])) {
4692 error_setg(errp
, "backing is missing for '%s'",
4693 reopen_state
->bs
->node_name
);
4699 * Allow changing the 'backing' option. The new value can be
4700 * either a reference to an existing node (using its node name)
4701 * or NULL to simply detach the current backing file.
4703 ret
= bdrv_reopen_parse_file_or_backing(reopen_state
, true,
4704 change_child_tran
, errp
);
4708 qdict_del(reopen_state
->options
, "backing");
4710 /* Allow changing the 'file' option. In this case NULL is not allowed */
4711 ret
= bdrv_reopen_parse_file_or_backing(reopen_state
, false,
4712 change_child_tran
, errp
);
4716 qdict_del(reopen_state
->options
, "file");
4718 /* Options that are not handled are only okay if they are unchanged
4719 * compared to the old state. It is expected that some options are only
4720 * used for the initial open, but not reopen (e.g. filename) */
4721 if (qdict_size(reopen_state
->options
)) {
4722 const QDictEntry
*entry
= qdict_first(reopen_state
->options
);
4725 QObject
*new = entry
->value
;
4726 QObject
*old
= qdict_get(reopen_state
->bs
->options
, entry
->key
);
4728 /* Allow child references (child_name=node_name) as long as they
4729 * point to the current child (i.e. everything stays the same). */
4730 if (qobject_type(new) == QTYPE_QSTRING
) {
4732 QLIST_FOREACH(child
, &reopen_state
->bs
->children
, next
) {
4733 if (!strcmp(child
->name
, entry
->key
)) {
4739 if (!strcmp(child
->bs
->node_name
,
4740 qstring_get_str(qobject_to(QString
, new)))) {
4741 continue; /* Found child with this name, skip option */
4747 * TODO: When using -drive to specify blockdev options, all values
4748 * will be strings; however, when using -blockdev, blockdev-add or
4749 * filenames using the json:{} pseudo-protocol, they will be
4751 * In contrast, reopening options are (currently) always strings
4752 * (because you can only specify them through qemu-io; all other
4753 * callers do not specify any options).
4754 * Therefore, when using anything other than -drive to create a BDS,
4755 * this cannot detect non-string options as unchanged, because
4756 * qobject_is_equal() always returns false for objects of different
4757 * type. In the future, this should be remedied by correctly typing
4758 * all options. For now, this is not too big of an issue because
4759 * the user can simply omit options which cannot be changed anyway,
4760 * so they will stay unchanged.
4762 if (!qobject_is_equal(new, old
)) {
4763 error_setg(errp
, "Cannot change the option '%s'", entry
->key
);
4767 } while ((entry
= qdict_next(reopen_state
->options
, entry
)));
4772 /* Restore the original reopen_state->options QDict */
4773 qobject_unref(reopen_state
->options
);
4774 reopen_state
->options
= qobject_ref(orig_reopen_opts
);
4777 if (ret
< 0 && drv_prepared
) {
4778 /* drv->bdrv_reopen_prepare() has succeeded, so we need to
4779 * call drv->bdrv_reopen_abort() before signaling an error
4780 * (bdrv_reopen_multiple() will not call bdrv_reopen_abort()
4781 * when the respective bdrv_reopen_prepare() has failed) */
4782 if (drv
->bdrv_reopen_abort
) {
4783 drv
->bdrv_reopen_abort(reopen_state
);
4786 qemu_opts_del(opts
);
4787 qobject_unref(orig_reopen_opts
);
4793 * Takes the staged changes for the reopen from bdrv_reopen_prepare(), and
4794 * makes them final by swapping the staging BlockDriverState contents into
4795 * the active BlockDriverState contents.
4797 static void bdrv_reopen_commit(BDRVReopenState
*reopen_state
)
4800 BlockDriverState
*bs
;
4803 assert(reopen_state
!= NULL
);
4804 bs
= reopen_state
->bs
;
4806 assert(drv
!= NULL
);
4808 /* If there are any driver level actions to take */
4809 if (drv
->bdrv_reopen_commit
) {
4810 drv
->bdrv_reopen_commit(reopen_state
);
4813 /* set BDS specific flags now */
4814 qobject_unref(bs
->explicit_options
);
4815 qobject_unref(bs
->options
);
4816 qobject_ref(reopen_state
->explicit_options
);
4817 qobject_ref(reopen_state
->options
);
4819 bs
->explicit_options
= reopen_state
->explicit_options
;
4820 bs
->options
= reopen_state
->options
;
4821 bs
->open_flags
= reopen_state
->flags
;
4822 bs
->detect_zeroes
= reopen_state
->detect_zeroes
;
4824 /* Remove child references from bs->options and bs->explicit_options.
4825 * Child options were already removed in bdrv_reopen_queue_child() */
4826 QLIST_FOREACH(child
, &bs
->children
, next
) {
4827 qdict_del(bs
->explicit_options
, child
->name
);
4828 qdict_del(bs
->options
, child
->name
);
4830 /* backing is probably removed, so it's not handled by previous loop */
4831 qdict_del(bs
->explicit_options
, "backing");
4832 qdict_del(bs
->options
, "backing");
4834 bdrv_refresh_limits(bs
, NULL
, NULL
);
4838 * Abort the reopen, and delete and free the staged changes in
4841 static void bdrv_reopen_abort(BDRVReopenState
*reopen_state
)
4845 assert(reopen_state
!= NULL
);
4846 drv
= reopen_state
->bs
->drv
;
4847 assert(drv
!= NULL
);
4849 if (drv
->bdrv_reopen_abort
) {
4850 drv
->bdrv_reopen_abort(reopen_state
);
4855 static void bdrv_close(BlockDriverState
*bs
)
4857 BdrvAioNotifier
*ban
, *ban_next
;
4858 BdrvChild
*child
, *next
;
4860 GLOBAL_STATE_CODE();
4861 assert(!bs
->refcnt
);
4863 bdrv_drained_begin(bs
); /* complete I/O */
4865 bdrv_drain(bs
); /* in case flush left pending I/O */
4868 if (bs
->drv
->bdrv_close
) {
4869 /* Must unfreeze all children, so bdrv_unref_child() works */
4870 bs
->drv
->bdrv_close(bs
);
4875 QLIST_FOREACH_SAFE(child
, &bs
->children
, next
, next
) {
4876 bdrv_unref_child(bs
, child
);
4883 qatomic_set(&bs
->copy_on_read
, 0);
4884 bs
->backing_file
[0] = '\0';
4885 bs
->backing_format
[0] = '\0';
4886 bs
->total_sectors
= 0;
4887 bs
->encrypted
= false;
4889 qobject_unref(bs
->options
);
4890 qobject_unref(bs
->explicit_options
);
4892 bs
->explicit_options
= NULL
;
4893 qobject_unref(bs
->full_open_options
);
4894 bs
->full_open_options
= NULL
;
4895 g_free(bs
->block_status_cache
);
4896 bs
->block_status_cache
= NULL
;
4898 bdrv_release_named_dirty_bitmaps(bs
);
4899 assert(QLIST_EMPTY(&bs
->dirty_bitmaps
));
4901 QLIST_FOREACH_SAFE(ban
, &bs
->aio_notifiers
, list
, ban_next
) {
4904 QLIST_INIT(&bs
->aio_notifiers
);
4905 bdrv_drained_end(bs
);
4908 * If we're still inside some bdrv_drain_all_begin()/end() sections, end
4909 * them now since this BDS won't exist anymore when bdrv_drain_all_end()
4912 if (bs
->quiesce_counter
) {
4913 bdrv_drain_all_end_quiesce(bs
);
4917 void bdrv_close_all(void)
4919 assert(job_next(NULL
) == NULL
);
4920 GLOBAL_STATE_CODE();
4922 /* Drop references from requests still in flight, such as canceled block
4923 * jobs whose AIO context has not been polled yet */
4926 blk_remove_all_bs();
4927 blockdev_close_all_bdrv_states();
4929 assert(QTAILQ_EMPTY(&all_bdrv_states
));
4932 static bool should_update_child(BdrvChild
*c
, BlockDriverState
*to
)
4938 if (c
->klass
->stay_at_node
) {
4942 /* If the child @c belongs to the BDS @to, replacing the current
4943 * c->bs by @to would mean to create a loop.
4945 * Such a case occurs when appending a BDS to a backing chain.
4946 * For instance, imagine the following chain:
4948 * guest device -> node A -> further backing chain...
4950 * Now we create a new BDS B which we want to put on top of this
4951 * chain, so we first attach A as its backing node:
4956 * guest device -> node A -> further backing chain...
4958 * Finally we want to replace A by B. When doing that, we want to
4959 * replace all pointers to A by pointers to B -- except for the
4960 * pointer from B because (1) that would create a loop, and (2)
4961 * that pointer should simply stay intact:
4963 * guest device -> node B
4966 * node A -> further backing chain...
4968 * In general, when replacing a node A (c->bs) by a node B (@to),
4969 * if A is a child of B, that means we cannot replace A by B there
4970 * because that would create a loop. Silently detaching A from B
4971 * is also not really an option. So overall just leaving A in
4972 * place there is the most sensible choice.
4974 * We would also create a loop in any cases where @c is only
4975 * indirectly referenced by @to. Prevent this by returning false
4976 * if @c is found (by breadth-first search) anywhere in the whole
4981 found
= g_hash_table_new(NULL
, NULL
);
4982 g_hash_table_add(found
, to
);
4983 queue
= g_queue_new();
4984 g_queue_push_tail(queue
, to
);
4986 while (!g_queue_is_empty(queue
)) {
4987 BlockDriverState
*v
= g_queue_pop_head(queue
);
4990 QLIST_FOREACH(c2
, &v
->children
, next
) {
4996 if (g_hash_table_contains(found
, c2
->bs
)) {
5000 g_queue_push_tail(queue
, c2
->bs
);
5001 g_hash_table_add(found
, c2
->bs
);
5005 g_queue_free(queue
);
5006 g_hash_table_destroy(found
);
5011 typedef struct BdrvRemoveFilterOrCowChild
{
5013 BlockDriverState
*bs
;
5015 } BdrvRemoveFilterOrCowChild
;
5017 static void bdrv_remove_filter_or_cow_child_abort(void *opaque
)
5019 BdrvRemoveFilterOrCowChild
*s
= opaque
;
5020 BlockDriverState
*parent_bs
= s
->child
->opaque
;
5022 if (s
->is_backing
) {
5023 parent_bs
->backing
= s
->child
;
5025 parent_bs
->file
= s
->child
;
5029 * We don't have to restore child->bs here to undo bdrv_replace_child_tran()
5030 * because that function is transactionable and it registered own completion
5031 * entries in @tran, so .abort() for bdrv_replace_child_safe() will be
5032 * called automatically.
5036 static void bdrv_remove_filter_or_cow_child_commit(void *opaque
)
5038 BdrvRemoveFilterOrCowChild
*s
= opaque
;
5040 bdrv_child_free(s
->child
);
5043 static void bdrv_remove_filter_or_cow_child_clean(void *opaque
)
5045 BdrvRemoveFilterOrCowChild
*s
= opaque
;
5047 /* Drop the bs reference after the transaction is done */
5052 static TransactionActionDrv bdrv_remove_filter_or_cow_child_drv
= {
5053 .abort
= bdrv_remove_filter_or_cow_child_abort
,
5054 .commit
= bdrv_remove_filter_or_cow_child_commit
,
5055 .clean
= bdrv_remove_filter_or_cow_child_clean
,
5059 * A function to remove backing or file child of @bs.
5060 * Function doesn't update permissions, caller is responsible for this.
5062 static void bdrv_remove_file_or_backing_child(BlockDriverState
*bs
,
5067 BdrvRemoveFilterOrCowChild
*s
;
5074 * Keep a reference to @bs so @childp will stay valid throughout the
5075 * transaction (required by bdrv_replace_child_tran())
5078 if (child
== bs
->backing
) {
5079 childp
= &bs
->backing
;
5080 } else if (child
== bs
->file
) {
5083 g_assert_not_reached();
5088 * Pass free_empty_child=false, we will free the child in
5089 * bdrv_remove_filter_or_cow_child_commit()
5091 bdrv_replace_child_tran(childp
, NULL
, tran
, false);
5094 s
= g_new(BdrvRemoveFilterOrCowChild
, 1);
5095 *s
= (BdrvRemoveFilterOrCowChild
) {
5098 .is_backing
= (childp
== &bs
->backing
),
5100 tran_add(tran
, &bdrv_remove_filter_or_cow_child_drv
, s
);
5104 * A function to remove backing-chain child of @bs if exists: cow child for
5105 * format nodes (always .backing) and filter child for filters (may be .file or
5108 static void bdrv_remove_filter_or_cow_child(BlockDriverState
*bs
,
5111 bdrv_remove_file_or_backing_child(bs
, bdrv_filter_or_cow_child(bs
), tran
);
5114 static int bdrv_replace_node_noperm(BlockDriverState
*from
,
5115 BlockDriverState
*to
,
5116 bool auto_skip
, Transaction
*tran
,
5119 BdrvChild
*c
, *next
;
5123 QLIST_FOREACH_SAFE(c
, &from
->parents
, next_parent
, next
) {
5124 assert(c
->bs
== from
);
5125 if (!should_update_child(c
, to
)) {
5129 error_setg(errp
, "Should not change '%s' link to '%s'",
5130 c
->name
, from
->node_name
);
5134 error_setg(errp
, "Cannot change '%s' link to '%s'",
5135 c
->name
, from
->node_name
);
5140 * Passing a pointer to the local variable @c is fine here, because
5141 * @to is not NULL, and so &c will not be attached to the transaction.
5143 bdrv_replace_child_tran(&c
, to
, tran
, true);
5150 * With auto_skip=true bdrv_replace_node_common skips updating from parents
5151 * if it creates a parent-child relation loop or if parent is block-job.
5153 * With auto_skip=false the error is returned if from has a parent which should
5156 * With @detach_subchain=true @to must be in a backing chain of @from. In this
5157 * case backing link of the cow-parent of @to is removed.
5159 * @to must not be NULL.
5161 static int bdrv_replace_node_common(BlockDriverState
*from
,
5162 BlockDriverState
*to
,
5163 bool auto_skip
, bool detach_subchain
,
5166 Transaction
*tran
= tran_new();
5167 g_autoptr(GHashTable
) found
= NULL
;
5168 g_autoptr(GSList
) refresh_list
= NULL
;
5169 BlockDriverState
*to_cow_parent
= NULL
;
5174 if (detach_subchain
) {
5175 assert(bdrv_chain_contains(from
, to
));
5177 for (to_cow_parent
= from
;
5178 bdrv_filter_or_cow_bs(to_cow_parent
) != to
;
5179 to_cow_parent
= bdrv_filter_or_cow_bs(to_cow_parent
))
5185 /* Make sure that @from doesn't go away until we have successfully attached
5186 * all of its parents to @to. */
5189 assert(qemu_get_current_aio_context() == qemu_get_aio_context());
5190 assert(bdrv_get_aio_context(from
) == bdrv_get_aio_context(to
));
5191 bdrv_drained_begin(from
);
5194 * Do the replacement without permission update.
5195 * Replacement may influence the permissions, we should calculate new
5196 * permissions based on new graph. If we fail, we'll roll-back the
5199 ret
= bdrv_replace_node_noperm(from
, to
, auto_skip
, tran
, errp
);
5204 if (detach_subchain
) {
5205 bdrv_remove_filter_or_cow_child(to_cow_parent
, tran
);
5208 found
= g_hash_table_new(NULL
, NULL
);
5210 refresh_list
= bdrv_topological_dfs(refresh_list
, found
, to
);
5211 refresh_list
= bdrv_topological_dfs(refresh_list
, found
, from
);
5213 ret
= bdrv_list_refresh_perms(refresh_list
, NULL
, tran
, errp
);
5221 tran_finalize(tran
, ret
);
5223 bdrv_drained_end(from
);
5230 * Replace node @from by @to (where neither may be NULL).
5232 int bdrv_replace_node(BlockDriverState
*from
, BlockDriverState
*to
,
5235 GLOBAL_STATE_CODE();
5237 return bdrv_replace_node_common(from
, to
, true, false, errp
);
5240 int bdrv_drop_filter(BlockDriverState
*bs
, Error
**errp
)
5242 GLOBAL_STATE_CODE();
5244 return bdrv_replace_node_common(bs
, bdrv_filter_or_cow_bs(bs
), true, true,
5249 * Add new bs contents at the top of an image chain while the chain is
5250 * live, while keeping required fields on the top layer.
5252 * This will modify the BlockDriverState fields, and swap contents
5253 * between bs_new and bs_top. Both bs_new and bs_top are modified.
5255 * bs_new must not be attached to a BlockBackend and must not have backing
5258 * This function does not create any image files.
5260 int bdrv_append(BlockDriverState
*bs_new
, BlockDriverState
*bs_top
,
5264 Transaction
*tran
= tran_new();
5266 GLOBAL_STATE_CODE();
5268 assert(!bs_new
->backing
);
5270 ret
= bdrv_attach_child_noperm(bs_new
, bs_top
, "backing",
5271 &child_of_bds
, bdrv_backing_role(bs_new
),
5272 &bs_new
->backing
, tran
, errp
);
5277 ret
= bdrv_replace_node_noperm(bs_top
, bs_new
, true, tran
, errp
);
5282 ret
= bdrv_refresh_perms(bs_new
, errp
);
5284 tran_finalize(tran
, ret
);
5286 bdrv_refresh_limits(bs_top
, NULL
, NULL
);
5291 /* Not for empty child */
5292 int bdrv_replace_child_bs(BdrvChild
*child
, BlockDriverState
*new_bs
,
5296 Transaction
*tran
= tran_new();
5297 g_autoptr(GHashTable
) found
= NULL
;
5298 g_autoptr(GSList
) refresh_list
= NULL
;
5299 BlockDriverState
*old_bs
= child
->bs
;
5301 GLOBAL_STATE_CODE();
5304 bdrv_drained_begin(old_bs
);
5305 bdrv_drained_begin(new_bs
);
5307 bdrv_replace_child_tran(&child
, new_bs
, tran
, true);
5308 /* @new_bs must have been non-NULL, so @child must not have been freed */
5309 assert(child
!= NULL
);
5311 found
= g_hash_table_new(NULL
, NULL
);
5312 refresh_list
= bdrv_topological_dfs(refresh_list
, found
, old_bs
);
5313 refresh_list
= bdrv_topological_dfs(refresh_list
, found
, new_bs
);
5315 ret
= bdrv_list_refresh_perms(refresh_list
, NULL
, tran
, errp
);
5317 tran_finalize(tran
, ret
);
5319 bdrv_drained_end(old_bs
);
5320 bdrv_drained_end(new_bs
);
5326 static void bdrv_delete(BlockDriverState
*bs
)
5328 assert(bdrv_op_blocker_is_empty(bs
));
5329 assert(!bs
->refcnt
);
5330 GLOBAL_STATE_CODE();
5332 /* remove from list, if necessary */
5333 if (bs
->node_name
[0] != '\0') {
5334 QTAILQ_REMOVE(&graph_bdrv_states
, bs
, node_list
);
5336 QTAILQ_REMOVE(&all_bdrv_states
, bs
, bs_list
);
5345 * Replace @bs by newly created block node.
5347 * @options is a QDict of options to pass to the block drivers, or NULL for an
5348 * empty set of options. The reference to the QDict belongs to the block layer
5349 * after the call (even on failure), so if the caller intends to reuse the
5350 * dictionary, it needs to use qobject_ref() before calling bdrv_open.
5352 BlockDriverState
*bdrv_insert_node(BlockDriverState
*bs
, QDict
*options
,
5353 int flags
, Error
**errp
)
5357 BlockDriverState
*new_node_bs
= NULL
;
5358 const char *drvname
, *node_name
;
5361 drvname
= qdict_get_try_str(options
, "driver");
5363 error_setg(errp
, "driver is not specified");
5367 drv
= bdrv_find_format(drvname
);
5369 error_setg(errp
, "Unknown driver: '%s'", drvname
);
5373 node_name
= qdict_get_try_str(options
, "node-name");
5375 GLOBAL_STATE_CODE();
5377 new_node_bs
= bdrv_new_open_driver_opts(drv
, node_name
, options
, flags
,
5379 options
= NULL
; /* bdrv_new_open_driver() eats options */
5381 error_prepend(errp
, "Could not create node: ");
5385 bdrv_drained_begin(bs
);
5386 ret
= bdrv_replace_node(bs
, new_node_bs
, errp
);
5387 bdrv_drained_end(bs
);
5390 error_prepend(errp
, "Could not replace node: ");
5397 qobject_unref(options
);
5398 bdrv_unref(new_node_bs
);
5403 * Run consistency checks on an image
5405 * Returns 0 if the check could be completed (it doesn't mean that the image is
5406 * free of errors) or -errno when an internal error occurred. The results of the
5407 * check are stored in res.
5409 int coroutine_fn
bdrv_co_check(BlockDriverState
*bs
,
5410 BdrvCheckResult
*res
, BdrvCheckMode fix
)
5412 if (bs
->drv
== NULL
) {
5415 if (bs
->drv
->bdrv_co_check
== NULL
) {
5419 memset(res
, 0, sizeof(*res
));
5420 return bs
->drv
->bdrv_co_check(bs
, res
, fix
);
5426 * -EINVAL - backing format specified, but no file
5427 * -ENOSPC - can't update the backing file because no space is left in the
5429 * -ENOTSUP - format driver doesn't support changing the backing file
5431 int bdrv_change_backing_file(BlockDriverState
*bs
, const char *backing_file
,
5432 const char *backing_fmt
, bool require
)
5434 BlockDriver
*drv
= bs
->drv
;
5437 GLOBAL_STATE_CODE();
5443 /* Backing file format doesn't make sense without a backing file */
5444 if (backing_fmt
&& !backing_file
) {
5448 if (require
&& backing_file
&& !backing_fmt
) {
5452 if (drv
->bdrv_change_backing_file
!= NULL
) {
5453 ret
= drv
->bdrv_change_backing_file(bs
, backing_file
, backing_fmt
);
5459 pstrcpy(bs
->backing_file
, sizeof(bs
->backing_file
), backing_file
?: "");
5460 pstrcpy(bs
->backing_format
, sizeof(bs
->backing_format
), backing_fmt
?: "");
5461 pstrcpy(bs
->auto_backing_file
, sizeof(bs
->auto_backing_file
),
5462 backing_file
?: "");
5468 * Finds the first non-filter node above bs in the chain between
5469 * active and bs. The returned node is either an immediate parent of
5470 * bs, or there are only filter nodes between the two.
5472 * Returns NULL if bs is not found in active's image chain,
5473 * or if active == bs.
5475 * Returns the bottommost base image if bs == NULL.
5477 BlockDriverState
*bdrv_find_overlay(BlockDriverState
*active
,
5478 BlockDriverState
*bs
)
5481 GLOBAL_STATE_CODE();
5483 bs
= bdrv_skip_filters(bs
);
5484 active
= bdrv_skip_filters(active
);
5487 BlockDriverState
*next
= bdrv_backing_chain_next(active
);
5497 /* Given a BDS, searches for the base layer. */
5498 BlockDriverState
*bdrv_find_base(BlockDriverState
*bs
)
5500 GLOBAL_STATE_CODE();
5502 return bdrv_find_overlay(bs
, NULL
);
5506 * Return true if at least one of the COW (backing) and filter links
5507 * between @bs and @base is frozen. @errp is set if that's the case.
5508 * @base must be reachable from @bs, or NULL.
5510 bool bdrv_is_backing_chain_frozen(BlockDriverState
*bs
, BlockDriverState
*base
,
5513 BlockDriverState
*i
;
5516 GLOBAL_STATE_CODE();
5518 for (i
= bs
; i
!= base
; i
= child_bs(child
)) {
5519 child
= bdrv_filter_or_cow_child(i
);
5521 if (child
&& child
->frozen
) {
5522 error_setg(errp
, "Cannot change '%s' link from '%s' to '%s'",
5523 child
->name
, i
->node_name
, child
->bs
->node_name
);
5532 * Freeze all COW (backing) and filter links between @bs and @base.
5533 * If any of the links is already frozen the operation is aborted and
5534 * none of the links are modified.
5535 * @base must be reachable from @bs, or NULL.
5536 * Returns 0 on success. On failure returns < 0 and sets @errp.
5538 int bdrv_freeze_backing_chain(BlockDriverState
*bs
, BlockDriverState
*base
,
5541 BlockDriverState
*i
;
5544 GLOBAL_STATE_CODE();
5546 if (bdrv_is_backing_chain_frozen(bs
, base
, errp
)) {
5550 for (i
= bs
; i
!= base
; i
= child_bs(child
)) {
5551 child
= bdrv_filter_or_cow_child(i
);
5552 if (child
&& child
->bs
->never_freeze
) {
5553 error_setg(errp
, "Cannot freeze '%s' link to '%s'",
5554 child
->name
, child
->bs
->node_name
);
5559 for (i
= bs
; i
!= base
; i
= child_bs(child
)) {
5560 child
= bdrv_filter_or_cow_child(i
);
5562 child
->frozen
= true;
5570 * Unfreeze all COW (backing) and filter links between @bs and @base.
5571 * The caller must ensure that all links are frozen before using this
5573 * @base must be reachable from @bs, or NULL.
5575 void bdrv_unfreeze_backing_chain(BlockDriverState
*bs
, BlockDriverState
*base
)
5577 BlockDriverState
*i
;
5580 GLOBAL_STATE_CODE();
5582 for (i
= bs
; i
!= base
; i
= child_bs(child
)) {
5583 child
= bdrv_filter_or_cow_child(i
);
5585 assert(child
->frozen
);
5586 child
->frozen
= false;
5592 * Drops images above 'base' up to and including 'top', and sets the image
5593 * above 'top' to have base as its backing file.
5595 * Requires that the overlay to 'top' is opened r/w, so that the backing file
5596 * information in 'bs' can be properly updated.
5598 * E.g., this will convert the following chain:
5599 * bottom <- base <- intermediate <- top <- active
5603 * bottom <- base <- active
5605 * It is allowed for bottom==base, in which case it converts:
5607 * base <- intermediate <- top <- active
5613 * If backing_file_str is non-NULL, it will be used when modifying top's
5614 * overlay image metadata.
5617 * if active == top, that is considered an error
5620 int bdrv_drop_intermediate(BlockDriverState
*top
, BlockDriverState
*base
,
5621 const char *backing_file_str
)
5623 BlockDriverState
*explicit_top
= top
;
5624 bool update_inherits_from
;
5626 Error
*local_err
= NULL
;
5628 g_autoptr(GSList
) updated_children
= NULL
;
5631 GLOBAL_STATE_CODE();
5634 bdrv_subtree_drained_begin(top
);
5636 if (!top
->drv
|| !base
->drv
) {
5640 /* Make sure that base is in the backing chain of top */
5641 if (!bdrv_chain_contains(top
, base
)) {
5645 /* If 'base' recursively inherits from 'top' then we should set
5646 * base->inherits_from to top->inherits_from after 'top' and all
5647 * other intermediate nodes have been dropped.
5648 * If 'top' is an implicit node (e.g. "commit_top") we should skip
5649 * it because no one inherits from it. We use explicit_top for that. */
5650 explicit_top
= bdrv_skip_implicit_filters(explicit_top
);
5651 update_inherits_from
= bdrv_inherits_from_recursive(base
, explicit_top
);
5653 /* success - we can delete the intermediate states, and link top->base */
5654 if (!backing_file_str
) {
5655 bdrv_refresh_filename(base
);
5656 backing_file_str
= base
->filename
;
5659 QLIST_FOREACH(c
, &top
->parents
, next_parent
) {
5660 updated_children
= g_slist_prepend(updated_children
, c
);
5664 * It seems correct to pass detach_subchain=true here, but it triggers
5665 * one more yet not fixed bug, when due to nested aio_poll loop we switch to
5666 * another drained section, which modify the graph (for example, removing
5667 * the child, which we keep in updated_children list). So, it's a TODO.
5669 * Note, bug triggered if pass detach_subchain=true here and run
5670 * test-bdrv-drain. test_drop_intermediate_poll() test-case will crash.
5673 bdrv_replace_node_common(top
, base
, false, false, &local_err
);
5675 error_report_err(local_err
);
5679 for (p
= updated_children
; p
; p
= p
->next
) {
5682 if (c
->klass
->update_filename
) {
5683 ret
= c
->klass
->update_filename(c
, base
, backing_file_str
,
5687 * TODO: Actually, we want to rollback all previous iterations
5688 * of this loop, and (which is almost impossible) previous
5689 * bdrv_replace_node()...
5691 * Note, that c->klass->update_filename may lead to permission
5692 * update, so it's a bad idea to call it inside permission
5693 * update transaction of bdrv_replace_node.
5695 error_report_err(local_err
);
5701 if (update_inherits_from
) {
5702 base
->inherits_from
= explicit_top
->inherits_from
;
5707 bdrv_subtree_drained_end(top
);
5713 * Implementation of BlockDriver.bdrv_get_allocated_file_size() that
5714 * sums the size of all data-bearing children. (This excludes backing
5717 static int64_t bdrv_sum_allocated_file_size(BlockDriverState
*bs
)
5720 int64_t child_size
, sum
= 0;
5722 QLIST_FOREACH(child
, &bs
->children
, next
) {
5723 if (child
->role
& (BDRV_CHILD_DATA
| BDRV_CHILD_METADATA
|
5724 BDRV_CHILD_FILTERED
))
5726 child_size
= bdrv_get_allocated_file_size(child
->bs
);
5727 if (child_size
< 0) {
5738 * Length of a allocated file in bytes. Sparse files are counted by actual
5739 * allocated space. Return < 0 if error or unknown.
5741 int64_t bdrv_get_allocated_file_size(BlockDriverState
*bs
)
5743 BlockDriver
*drv
= bs
->drv
;
5749 if (drv
->bdrv_get_allocated_file_size
) {
5750 return drv
->bdrv_get_allocated_file_size(bs
);
5753 if (drv
->bdrv_file_open
) {
5755 * Protocol drivers default to -ENOTSUP (most of their data is
5756 * not stored in any of their children (if they even have any),
5757 * so there is no generic way to figure it out).
5760 } else if (drv
->is_filter
) {
5761 /* Filter drivers default to the size of their filtered child */
5762 return bdrv_get_allocated_file_size(bdrv_filter_bs(bs
));
5764 /* Other drivers default to summing their children's sizes */
5765 return bdrv_sum_allocated_file_size(bs
);
5771 * @drv: Format driver
5772 * @opts: Creation options for new image
5773 * @in_bs: Existing image containing data for new image (may be NULL)
5774 * @errp: Error object
5775 * Returns: A #BlockMeasureInfo (free using qapi_free_BlockMeasureInfo())
5778 * Calculate file size required to create a new image.
5780 * If @in_bs is given then space for allocated clusters and zero clusters
5781 * from that image are included in the calculation. If @opts contains a
5782 * backing file that is shared by @in_bs then backing clusters may be omitted
5783 * from the calculation.
5785 * If @in_bs is NULL then the calculation includes no allocated clusters
5786 * unless a preallocation option is given in @opts.
5788 * Note that @in_bs may use a different BlockDriver from @drv.
5790 * If an error occurs the @errp pointer is set.
5792 BlockMeasureInfo
*bdrv_measure(BlockDriver
*drv
, QemuOpts
*opts
,
5793 BlockDriverState
*in_bs
, Error
**errp
)
5796 if (!drv
->bdrv_measure
) {
5797 error_setg(errp
, "Block driver '%s' does not support size measurement",
5802 return drv
->bdrv_measure(opts
, in_bs
, errp
);
5806 * Return number of sectors on success, -errno on error.
5808 int64_t bdrv_nb_sectors(BlockDriverState
*bs
)
5810 BlockDriver
*drv
= bs
->drv
;
5816 if (drv
->has_variable_length
) {
5817 int ret
= refresh_total_sectors(bs
, bs
->total_sectors
);
5822 return bs
->total_sectors
;
5826 * Return length in bytes on success, -errno on error.
5827 * The length is always a multiple of BDRV_SECTOR_SIZE.
5829 int64_t bdrv_getlength(BlockDriverState
*bs
)
5831 int64_t ret
= bdrv_nb_sectors(bs
);
5837 if (ret
> INT64_MAX
/ BDRV_SECTOR_SIZE
) {
5840 return ret
* BDRV_SECTOR_SIZE
;
5843 /* return 0 as number of sectors if no device present or error */
5844 void bdrv_get_geometry(BlockDriverState
*bs
, uint64_t *nb_sectors_ptr
)
5846 int64_t nb_sectors
= bdrv_nb_sectors(bs
);
5849 *nb_sectors_ptr
= nb_sectors
< 0 ? 0 : nb_sectors
;
5852 bool bdrv_is_sg(BlockDriverState
*bs
)
5859 * Return whether the given node supports compressed writes.
5861 bool bdrv_supports_compressed_writes(BlockDriverState
*bs
)
5863 BlockDriverState
*filtered
;
5866 if (!bs
->drv
|| !block_driver_can_compress(bs
->drv
)) {
5870 filtered
= bdrv_filter_bs(bs
);
5873 * Filters can only forward compressed writes, so we have to
5876 return bdrv_supports_compressed_writes(filtered
);
5882 const char *bdrv_get_format_name(BlockDriverState
*bs
)
5885 return bs
->drv
? bs
->drv
->format_name
: NULL
;
5888 static int qsort_strcmp(const void *a
, const void *b
)
5890 return strcmp(*(char *const *)a
, *(char *const *)b
);
5893 void bdrv_iterate_format(void (*it
)(void *opaque
, const char *name
),
5894 void *opaque
, bool read_only
)
5899 const char **formats
= NULL
;
5901 GLOBAL_STATE_CODE();
5903 QLIST_FOREACH(drv
, &bdrv_drivers
, list
) {
5904 if (drv
->format_name
) {
5908 if (use_bdrv_whitelist
&& !bdrv_is_whitelisted(drv
, read_only
)) {
5912 while (formats
&& i
&& !found
) {
5913 found
= !strcmp(formats
[--i
], drv
->format_name
);
5917 formats
= g_renew(const char *, formats
, count
+ 1);
5918 formats
[count
++] = drv
->format_name
;
5923 for (i
= 0; i
< (int)ARRAY_SIZE(block_driver_modules
); i
++) {
5924 const char *format_name
= block_driver_modules
[i
].format_name
;
5930 if (use_bdrv_whitelist
&&
5931 !bdrv_format_is_whitelisted(format_name
, read_only
)) {
5935 while (formats
&& j
&& !found
) {
5936 found
= !strcmp(formats
[--j
], format_name
);
5940 formats
= g_renew(const char *, formats
, count
+ 1);
5941 formats
[count
++] = format_name
;
5946 qsort(formats
, count
, sizeof(formats
[0]), qsort_strcmp
);
5948 for (i
= 0; i
< count
; i
++) {
5949 it(opaque
, formats
[i
]);
5955 /* This function is to find a node in the bs graph */
5956 BlockDriverState
*bdrv_find_node(const char *node_name
)
5958 BlockDriverState
*bs
;
5961 GLOBAL_STATE_CODE();
5963 QTAILQ_FOREACH(bs
, &graph_bdrv_states
, node_list
) {
5964 if (!strcmp(node_name
, bs
->node_name
)) {
5971 /* Put this QMP function here so it can access the static graph_bdrv_states. */
5972 BlockDeviceInfoList
*bdrv_named_nodes_list(bool flat
,
5975 BlockDeviceInfoList
*list
;
5976 BlockDriverState
*bs
;
5978 GLOBAL_STATE_CODE();
5981 QTAILQ_FOREACH(bs
, &graph_bdrv_states
, node_list
) {
5982 BlockDeviceInfo
*info
= bdrv_block_device_info(NULL
, bs
, flat
, errp
);
5984 qapi_free_BlockDeviceInfoList(list
);
5987 QAPI_LIST_PREPEND(list
, info
);
5993 typedef struct XDbgBlockGraphConstructor
{
5994 XDbgBlockGraph
*graph
;
5995 GHashTable
*graph_nodes
;
5996 } XDbgBlockGraphConstructor
;
5998 static XDbgBlockGraphConstructor
*xdbg_graph_new(void)
6000 XDbgBlockGraphConstructor
*gr
= g_new(XDbgBlockGraphConstructor
, 1);
6002 gr
->graph
= g_new0(XDbgBlockGraph
, 1);
6003 gr
->graph_nodes
= g_hash_table_new(NULL
, NULL
);
6008 static XDbgBlockGraph
*xdbg_graph_finalize(XDbgBlockGraphConstructor
*gr
)
6010 XDbgBlockGraph
*graph
= gr
->graph
;
6012 g_hash_table_destroy(gr
->graph_nodes
);
6018 static uintptr_t xdbg_graph_node_num(XDbgBlockGraphConstructor
*gr
, void *node
)
6020 uintptr_t ret
= (uintptr_t)g_hash_table_lookup(gr
->graph_nodes
, node
);
6027 * Start counting from 1, not 0, because 0 interferes with not-found (NULL)
6028 * answer of g_hash_table_lookup.
6030 ret
= g_hash_table_size(gr
->graph_nodes
) + 1;
6031 g_hash_table_insert(gr
->graph_nodes
, node
, (void *)ret
);
6036 static void xdbg_graph_add_node(XDbgBlockGraphConstructor
*gr
, void *node
,
6037 XDbgBlockGraphNodeType type
, const char *name
)
6039 XDbgBlockGraphNode
*n
;
6041 n
= g_new0(XDbgBlockGraphNode
, 1);
6043 n
->id
= xdbg_graph_node_num(gr
, node
);
6045 n
->name
= g_strdup(name
);
6047 QAPI_LIST_PREPEND(gr
->graph
->nodes
, n
);
6050 static void xdbg_graph_add_edge(XDbgBlockGraphConstructor
*gr
, void *parent
,
6051 const BdrvChild
*child
)
6053 BlockPermission qapi_perm
;
6054 XDbgBlockGraphEdge
*edge
;
6055 GLOBAL_STATE_CODE();
6057 edge
= g_new0(XDbgBlockGraphEdge
, 1);
6059 edge
->parent
= xdbg_graph_node_num(gr
, parent
);
6060 edge
->child
= xdbg_graph_node_num(gr
, child
->bs
);
6061 edge
->name
= g_strdup(child
->name
);
6063 for (qapi_perm
= 0; qapi_perm
< BLOCK_PERMISSION__MAX
; qapi_perm
++) {
6064 uint64_t flag
= bdrv_qapi_perm_to_blk_perm(qapi_perm
);
6066 if (flag
& child
->perm
) {
6067 QAPI_LIST_PREPEND(edge
->perm
, qapi_perm
);
6069 if (flag
& child
->shared_perm
) {
6070 QAPI_LIST_PREPEND(edge
->shared_perm
, qapi_perm
);
6074 QAPI_LIST_PREPEND(gr
->graph
->edges
, edge
);
6078 XDbgBlockGraph
*bdrv_get_xdbg_block_graph(Error
**errp
)
6082 BlockDriverState
*bs
;
6084 XDbgBlockGraphConstructor
*gr
= xdbg_graph_new();
6086 GLOBAL_STATE_CODE();
6088 for (blk
= blk_all_next(NULL
); blk
; blk
= blk_all_next(blk
)) {
6089 char *allocated_name
= NULL
;
6090 const char *name
= blk_name(blk
);
6093 name
= allocated_name
= blk_get_attached_dev_id(blk
);
6095 xdbg_graph_add_node(gr
, blk
, X_DBG_BLOCK_GRAPH_NODE_TYPE_BLOCK_BACKEND
,
6097 g_free(allocated_name
);
6098 if (blk_root(blk
)) {
6099 xdbg_graph_add_edge(gr
, blk
, blk_root(blk
));
6103 for (job
= block_job_next(NULL
); job
; job
= block_job_next(job
)) {
6106 xdbg_graph_add_node(gr
, job
, X_DBG_BLOCK_GRAPH_NODE_TYPE_BLOCK_JOB
,
6108 for (el
= job
->nodes
; el
; el
= el
->next
) {
6109 xdbg_graph_add_edge(gr
, job
, (BdrvChild
*)el
->data
);
6113 QTAILQ_FOREACH(bs
, &graph_bdrv_states
, node_list
) {
6114 xdbg_graph_add_node(gr
, bs
, X_DBG_BLOCK_GRAPH_NODE_TYPE_BLOCK_DRIVER
,
6116 QLIST_FOREACH(child
, &bs
->children
, next
) {
6117 xdbg_graph_add_edge(gr
, bs
, child
);
6121 return xdbg_graph_finalize(gr
);
6124 BlockDriverState
*bdrv_lookup_bs(const char *device
,
6125 const char *node_name
,
6129 BlockDriverState
*bs
;
6131 GLOBAL_STATE_CODE();
6134 blk
= blk_by_name(device
);
6139 error_setg(errp
, "Device '%s' has no medium", device
);
6147 bs
= bdrv_find_node(node_name
);
6154 error_setg(errp
, "Cannot find device=\'%s\' nor node-name=\'%s\'",
6155 device
? device
: "",
6156 node_name
? node_name
: "");
6160 /* If 'base' is in the same chain as 'top', return true. Otherwise,
6161 * return false. If either argument is NULL, return false. */
6162 bool bdrv_chain_contains(BlockDriverState
*top
, BlockDriverState
*base
)
6165 GLOBAL_STATE_CODE();
6167 while (top
&& top
!= base
) {
6168 top
= bdrv_filter_or_cow_bs(top
);
6174 BlockDriverState
*bdrv_next_node(BlockDriverState
*bs
)
6176 GLOBAL_STATE_CODE();
6178 return QTAILQ_FIRST(&graph_bdrv_states
);
6180 return QTAILQ_NEXT(bs
, node_list
);
6183 BlockDriverState
*bdrv_next_all_states(BlockDriverState
*bs
)
6185 GLOBAL_STATE_CODE();
6187 return QTAILQ_FIRST(&all_bdrv_states
);
6189 return QTAILQ_NEXT(bs
, bs_list
);
6192 const char *bdrv_get_node_name(const BlockDriverState
*bs
)
6195 return bs
->node_name
;
6198 const char *bdrv_get_parent_name(const BlockDriverState
*bs
)
6204 /* If multiple parents have a name, just pick the first one. */
6205 QLIST_FOREACH(c
, &bs
->parents
, next_parent
) {
6206 if (c
->klass
->get_name
) {
6207 name
= c
->klass
->get_name(c
);
6208 if (name
&& *name
) {
6217 /* TODO check what callers really want: bs->node_name or blk_name() */
6218 const char *bdrv_get_device_name(const BlockDriverState
*bs
)
6221 return bdrv_get_parent_name(bs
) ?: "";
6224 /* This can be used to identify nodes that might not have a device
6225 * name associated. Since node and device names live in the same
6226 * namespace, the result is unambiguous. The exception is if both are
6227 * absent, then this returns an empty (non-null) string. */
6228 const char *bdrv_get_device_or_node_name(const BlockDriverState
*bs
)
6231 return bdrv_get_parent_name(bs
) ?: bs
->node_name
;
6234 int bdrv_get_flags(BlockDriverState
*bs
)
6236 GLOBAL_STATE_CODE();
6237 return bs
->open_flags
;
6240 int bdrv_has_zero_init_1(BlockDriverState
*bs
)
6242 GLOBAL_STATE_CODE();
6246 int bdrv_has_zero_init(BlockDriverState
*bs
)
6248 BlockDriverState
*filtered
;
6249 GLOBAL_STATE_CODE();
6255 /* If BS is a copy on write image, it is initialized to
6256 the contents of the base image, which may not be zeroes. */
6257 if (bdrv_cow_child(bs
)) {
6260 if (bs
->drv
->bdrv_has_zero_init
) {
6261 return bs
->drv
->bdrv_has_zero_init(bs
);
6264 filtered
= bdrv_filter_bs(bs
);
6266 return bdrv_has_zero_init(filtered
);
6273 bool bdrv_can_write_zeroes_with_unmap(BlockDriverState
*bs
)
6276 if (!(bs
->open_flags
& BDRV_O_UNMAP
)) {
6280 return bs
->supported_zero_flags
& BDRV_REQ_MAY_UNMAP
;
6283 void bdrv_get_backing_filename(BlockDriverState
*bs
,
6284 char *filename
, int filename_size
)
6287 pstrcpy(filename
, filename_size
, bs
->backing_file
);
6290 int bdrv_get_info(BlockDriverState
*bs
, BlockDriverInfo
*bdi
)
6293 BlockDriver
*drv
= bs
->drv
;
6295 /* if bs->drv == NULL, bs is closed, so there's nothing to do here */
6299 if (!drv
->bdrv_get_info
) {
6300 BlockDriverState
*filtered
= bdrv_filter_bs(bs
);
6302 return bdrv_get_info(filtered
, bdi
);
6306 memset(bdi
, 0, sizeof(*bdi
));
6307 ret
= drv
->bdrv_get_info(bs
, bdi
);
6312 if (bdi
->cluster_size
> BDRV_MAX_ALIGNMENT
) {
6319 ImageInfoSpecific
*bdrv_get_specific_info(BlockDriverState
*bs
,
6322 BlockDriver
*drv
= bs
->drv
;
6324 if (drv
&& drv
->bdrv_get_specific_info
) {
6325 return drv
->bdrv_get_specific_info(bs
, errp
);
6330 BlockStatsSpecific
*bdrv_get_specific_stats(BlockDriverState
*bs
)
6332 BlockDriver
*drv
= bs
->drv
;
6334 if (!drv
|| !drv
->bdrv_get_specific_stats
) {
6337 return drv
->bdrv_get_specific_stats(bs
);
6340 void bdrv_debug_event(BlockDriverState
*bs
, BlkdebugEvent event
)
6343 if (!bs
|| !bs
->drv
|| !bs
->drv
->bdrv_debug_event
) {
6347 bs
->drv
->bdrv_debug_event(bs
, event
);
6350 static BlockDriverState
*bdrv_find_debug_node(BlockDriverState
*bs
)
6352 while (bs
&& bs
->drv
&& !bs
->drv
->bdrv_debug_breakpoint
) {
6353 bs
= bdrv_primary_bs(bs
);
6356 if (bs
&& bs
->drv
&& bs
->drv
->bdrv_debug_breakpoint
) {
6357 assert(bs
->drv
->bdrv_debug_remove_breakpoint
);
6364 int bdrv_debug_breakpoint(BlockDriverState
*bs
, const char *event
,
6367 GLOBAL_STATE_CODE();
6368 bs
= bdrv_find_debug_node(bs
);
6370 return bs
->drv
->bdrv_debug_breakpoint(bs
, event
, tag
);
6376 int bdrv_debug_remove_breakpoint(BlockDriverState
*bs
, const char *tag
)
6378 GLOBAL_STATE_CODE();
6379 bs
= bdrv_find_debug_node(bs
);
6381 return bs
->drv
->bdrv_debug_remove_breakpoint(bs
, tag
);
6387 int bdrv_debug_resume(BlockDriverState
*bs
, const char *tag
)
6389 GLOBAL_STATE_CODE();
6390 while (bs
&& (!bs
->drv
|| !bs
->drv
->bdrv_debug_resume
)) {
6391 bs
= bdrv_primary_bs(bs
);
6394 if (bs
&& bs
->drv
&& bs
->drv
->bdrv_debug_resume
) {
6395 return bs
->drv
->bdrv_debug_resume(bs
, tag
);
6401 bool bdrv_debug_is_suspended(BlockDriverState
*bs
, const char *tag
)
6403 GLOBAL_STATE_CODE();
6404 while (bs
&& bs
->drv
&& !bs
->drv
->bdrv_debug_is_suspended
) {
6405 bs
= bdrv_primary_bs(bs
);
6408 if (bs
&& bs
->drv
&& bs
->drv
->bdrv_debug_is_suspended
) {
6409 return bs
->drv
->bdrv_debug_is_suspended(bs
, tag
);
6415 /* backing_file can either be relative, or absolute, or a protocol. If it is
6416 * relative, it must be relative to the chain. So, passing in bs->filename
6417 * from a BDS as backing_file should not be done, as that may be relative to
6418 * the CWD rather than the chain. */
6419 BlockDriverState
*bdrv_find_backing_image(BlockDriverState
*bs
,
6420 const char *backing_file
)
6422 char *filename_full
= NULL
;
6423 char *backing_file_full
= NULL
;
6424 char *filename_tmp
= NULL
;
6425 int is_protocol
= 0;
6426 bool filenames_refreshed
= false;
6427 BlockDriverState
*curr_bs
= NULL
;
6428 BlockDriverState
*retval
= NULL
;
6429 BlockDriverState
*bs_below
;
6431 GLOBAL_STATE_CODE();
6433 if (!bs
|| !bs
->drv
|| !backing_file
) {
6437 filename_full
= g_malloc(PATH_MAX
);
6438 backing_file_full
= g_malloc(PATH_MAX
);
6440 is_protocol
= path_has_protocol(backing_file
);
6443 * Being largely a legacy function, skip any filters here
6444 * (because filters do not have normal filenames, so they cannot
6445 * match anyway; and allowing json:{} filenames is a bit out of
6448 for (curr_bs
= bdrv_skip_filters(bs
);
6449 bdrv_cow_child(curr_bs
) != NULL
;
6452 bs_below
= bdrv_backing_chain_next(curr_bs
);
6454 if (bdrv_backing_overridden(curr_bs
)) {
6456 * If the backing file was overridden, we can only compare
6457 * directly against the backing node's filename.
6460 if (!filenames_refreshed
) {
6462 * This will automatically refresh all of the
6463 * filenames in the rest of the backing chain, so we
6464 * only need to do this once.
6466 bdrv_refresh_filename(bs_below
);
6467 filenames_refreshed
= true;
6470 if (strcmp(backing_file
, bs_below
->filename
) == 0) {
6474 } else if (is_protocol
|| path_has_protocol(curr_bs
->backing_file
)) {
6476 * If either of the filename paths is actually a protocol, then
6477 * compare unmodified paths; otherwise make paths relative.
6479 char *backing_file_full_ret
;
6481 if (strcmp(backing_file
, curr_bs
->backing_file
) == 0) {
6485 /* Also check against the full backing filename for the image */
6486 backing_file_full_ret
= bdrv_get_full_backing_filename(curr_bs
,
6488 if (backing_file_full_ret
) {
6489 bool equal
= strcmp(backing_file
, backing_file_full_ret
) == 0;
6490 g_free(backing_file_full_ret
);
6497 /* If not an absolute filename path, make it relative to the current
6498 * image's filename path */
6499 filename_tmp
= bdrv_make_absolute_filename(curr_bs
, backing_file
,
6501 /* We are going to compare canonicalized absolute pathnames */
6502 if (!filename_tmp
|| !realpath(filename_tmp
, filename_full
)) {
6503 g_free(filename_tmp
);
6506 g_free(filename_tmp
);
6508 /* We need to make sure the backing filename we are comparing against
6509 * is relative to the current image filename (or absolute) */
6510 filename_tmp
= bdrv_get_full_backing_filename(curr_bs
, NULL
);
6511 if (!filename_tmp
|| !realpath(filename_tmp
, backing_file_full
)) {
6512 g_free(filename_tmp
);
6515 g_free(filename_tmp
);
6517 if (strcmp(backing_file_full
, filename_full
) == 0) {
6524 g_free(filename_full
);
6525 g_free(backing_file_full
);
6529 void bdrv_init(void)
6531 #ifdef CONFIG_BDRV_WHITELIST_TOOLS
6532 use_bdrv_whitelist
= 1;
6534 module_call_init(MODULE_INIT_BLOCK
);
6537 void bdrv_init_with_whitelist(void)
6539 use_bdrv_whitelist
= 1;
6543 int bdrv_activate(BlockDriverState
*bs
, Error
**errp
)
6545 BdrvChild
*child
, *parent
;
6546 Error
*local_err
= NULL
;
6548 BdrvDirtyBitmap
*bm
;
6550 GLOBAL_STATE_CODE();
6556 QLIST_FOREACH(child
, &bs
->children
, next
) {
6557 bdrv_activate(child
->bs
, &local_err
);
6559 error_propagate(errp
, local_err
);
6565 * Update permissions, they may differ for inactive nodes.
6567 * Note that the required permissions of inactive images are always a
6568 * subset of the permissions required after activating the image. This
6569 * allows us to just get the permissions upfront without restricting
6570 * bdrv_co_invalidate_cache().
6572 * It also means that in error cases, we don't have to try and revert to
6573 * the old permissions (which is an operation that could fail, too). We can
6574 * just keep the extended permissions for the next time that an activation
6575 * of the image is tried.
6577 if (bs
->open_flags
& BDRV_O_INACTIVE
) {
6578 bs
->open_flags
&= ~BDRV_O_INACTIVE
;
6579 ret
= bdrv_refresh_perms(bs
, errp
);
6581 bs
->open_flags
|= BDRV_O_INACTIVE
;
6585 ret
= bdrv_invalidate_cache(bs
, errp
);
6587 bs
->open_flags
|= BDRV_O_INACTIVE
;
6591 FOR_EACH_DIRTY_BITMAP(bs
, bm
) {
6592 bdrv_dirty_bitmap_skip_store(bm
, false);
6595 ret
= refresh_total_sectors(bs
, bs
->total_sectors
);
6597 bs
->open_flags
|= BDRV_O_INACTIVE
;
6598 error_setg_errno(errp
, -ret
, "Could not refresh total sector count");
6603 QLIST_FOREACH(parent
, &bs
->parents
, next_parent
) {
6604 if (parent
->klass
->activate
) {
6605 parent
->klass
->activate(parent
, &local_err
);
6607 bs
->open_flags
|= BDRV_O_INACTIVE
;
6608 error_propagate(errp
, local_err
);
6617 int coroutine_fn
bdrv_co_invalidate_cache(BlockDriverState
*bs
, Error
**errp
)
6619 Error
*local_err
= NULL
;
6621 assert(!(bs
->open_flags
& BDRV_O_INACTIVE
));
6623 if (bs
->drv
->bdrv_co_invalidate_cache
) {
6624 bs
->drv
->bdrv_co_invalidate_cache(bs
, &local_err
);
6626 error_propagate(errp
, local_err
);
6634 void bdrv_activate_all(Error
**errp
)
6636 BlockDriverState
*bs
;
6637 BdrvNextIterator it
;
6639 GLOBAL_STATE_CODE();
6641 for (bs
= bdrv_first(&it
); bs
; bs
= bdrv_next(&it
)) {
6642 AioContext
*aio_context
= bdrv_get_aio_context(bs
);
6645 aio_context_acquire(aio_context
);
6646 ret
= bdrv_activate(bs
, errp
);
6647 aio_context_release(aio_context
);
6649 bdrv_next_cleanup(&it
);
6655 static bool bdrv_has_bds_parent(BlockDriverState
*bs
, bool only_active
)
6659 QLIST_FOREACH(parent
, &bs
->parents
, next_parent
) {
6660 if (parent
->klass
->parent_is_bds
) {
6661 BlockDriverState
*parent_bs
= parent
->opaque
;
6662 if (!only_active
|| !(parent_bs
->open_flags
& BDRV_O_INACTIVE
)) {
6671 static int bdrv_inactivate_recurse(BlockDriverState
*bs
)
6673 BdrvChild
*child
, *parent
;
6675 uint64_t cumulative_perms
, cumulative_shared_perms
;
6681 /* Make sure that we don't inactivate a child before its parent.
6682 * It will be covered by recursion from the yet active parent. */
6683 if (bdrv_has_bds_parent(bs
, true)) {
6687 assert(!(bs
->open_flags
& BDRV_O_INACTIVE
));
6689 /* Inactivate this node */
6690 if (bs
->drv
->bdrv_inactivate
) {
6691 ret
= bs
->drv
->bdrv_inactivate(bs
);
6697 QLIST_FOREACH(parent
, &bs
->parents
, next_parent
) {
6698 if (parent
->klass
->inactivate
) {
6699 ret
= parent
->klass
->inactivate(parent
);
6706 bdrv_get_cumulative_perm(bs
, &cumulative_perms
,
6707 &cumulative_shared_perms
);
6708 if (cumulative_perms
& (BLK_PERM_WRITE
| BLK_PERM_WRITE_UNCHANGED
)) {
6709 /* Our inactive parents still need write access. Inactivation failed. */
6713 bs
->open_flags
|= BDRV_O_INACTIVE
;
6716 * Update permissions, they may differ for inactive nodes.
6717 * We only tried to loosen restrictions, so errors are not fatal, ignore
6720 bdrv_refresh_perms(bs
, NULL
);
6722 /* Recursively inactivate children */
6723 QLIST_FOREACH(child
, &bs
->children
, next
) {
6724 ret
= bdrv_inactivate_recurse(child
->bs
);
6733 int bdrv_inactivate_all(void)
6735 BlockDriverState
*bs
= NULL
;
6736 BdrvNextIterator it
;
6738 GSList
*aio_ctxs
= NULL
, *ctx
;
6740 GLOBAL_STATE_CODE();
6742 for (bs
= bdrv_first(&it
); bs
; bs
= bdrv_next(&it
)) {
6743 AioContext
*aio_context
= bdrv_get_aio_context(bs
);
6745 if (!g_slist_find(aio_ctxs
, aio_context
)) {
6746 aio_ctxs
= g_slist_prepend(aio_ctxs
, aio_context
);
6747 aio_context_acquire(aio_context
);
6751 for (bs
= bdrv_first(&it
); bs
; bs
= bdrv_next(&it
)) {
6752 /* Nodes with BDS parents are covered by recursion from the last
6753 * parent that gets inactivated. Don't inactivate them a second
6754 * time if that has already happened. */
6755 if (bdrv_has_bds_parent(bs
, false)) {
6758 ret
= bdrv_inactivate_recurse(bs
);
6760 bdrv_next_cleanup(&it
);
6766 for (ctx
= aio_ctxs
; ctx
!= NULL
; ctx
= ctx
->next
) {
6767 AioContext
*aio_context
= ctx
->data
;
6768 aio_context_release(aio_context
);
6770 g_slist_free(aio_ctxs
);
6775 /**************************************************************/
6776 /* removable device support */
6779 * Return TRUE if the media is present
6781 bool bdrv_is_inserted(BlockDriverState
*bs
)
6783 BlockDriver
*drv
= bs
->drv
;
6790 if (drv
->bdrv_is_inserted
) {
6791 return drv
->bdrv_is_inserted(bs
);
6793 QLIST_FOREACH(child
, &bs
->children
, next
) {
6794 if (!bdrv_is_inserted(child
->bs
)) {
6802 * If eject_flag is TRUE, eject the media. Otherwise, close the tray
6804 void bdrv_eject(BlockDriverState
*bs
, bool eject_flag
)
6806 BlockDriver
*drv
= bs
->drv
;
6809 if (drv
&& drv
->bdrv_eject
) {
6810 drv
->bdrv_eject(bs
, eject_flag
);
6815 * Lock or unlock the media (if it is locked, the user won't be able
6816 * to eject it manually).
6818 void bdrv_lock_medium(BlockDriverState
*bs
, bool locked
)
6820 BlockDriver
*drv
= bs
->drv
;
6822 trace_bdrv_lock_medium(bs
, locked
);
6824 if (drv
&& drv
->bdrv_lock_medium
) {
6825 drv
->bdrv_lock_medium(bs
, locked
);
6829 /* Get a reference to bs */
6830 void bdrv_ref(BlockDriverState
*bs
)
6832 GLOBAL_STATE_CODE();
6836 /* Release a previously grabbed reference to bs.
6837 * If after releasing, reference count is zero, the BlockDriverState is
6839 void bdrv_unref(BlockDriverState
*bs
)
6841 GLOBAL_STATE_CODE();
6845 assert(bs
->refcnt
> 0);
6846 if (--bs
->refcnt
== 0) {
6851 struct BdrvOpBlocker
{
6853 QLIST_ENTRY(BdrvOpBlocker
) list
;
6856 bool bdrv_op_is_blocked(BlockDriverState
*bs
, BlockOpType op
, Error
**errp
)
6858 BdrvOpBlocker
*blocker
;
6859 GLOBAL_STATE_CODE();
6860 assert((int) op
>= 0 && op
< BLOCK_OP_TYPE_MAX
);
6861 if (!QLIST_EMPTY(&bs
->op_blockers
[op
])) {
6862 blocker
= QLIST_FIRST(&bs
->op_blockers
[op
]);
6863 error_propagate_prepend(errp
, error_copy(blocker
->reason
),
6864 "Node '%s' is busy: ",
6865 bdrv_get_device_or_node_name(bs
));
6871 void bdrv_op_block(BlockDriverState
*bs
, BlockOpType op
, Error
*reason
)
6873 BdrvOpBlocker
*blocker
;
6874 GLOBAL_STATE_CODE();
6875 assert((int) op
>= 0 && op
< BLOCK_OP_TYPE_MAX
);
6877 blocker
= g_new0(BdrvOpBlocker
, 1);
6878 blocker
->reason
= reason
;
6879 QLIST_INSERT_HEAD(&bs
->op_blockers
[op
], blocker
, list
);
6882 void bdrv_op_unblock(BlockDriverState
*bs
, BlockOpType op
, Error
*reason
)
6884 BdrvOpBlocker
*blocker
, *next
;
6885 GLOBAL_STATE_CODE();
6886 assert((int) op
>= 0 && op
< BLOCK_OP_TYPE_MAX
);
6887 QLIST_FOREACH_SAFE(blocker
, &bs
->op_blockers
[op
], list
, next
) {
6888 if (blocker
->reason
== reason
) {
6889 QLIST_REMOVE(blocker
, list
);
6895 void bdrv_op_block_all(BlockDriverState
*bs
, Error
*reason
)
6898 GLOBAL_STATE_CODE();
6899 for (i
= 0; i
< BLOCK_OP_TYPE_MAX
; i
++) {
6900 bdrv_op_block(bs
, i
, reason
);
6904 void bdrv_op_unblock_all(BlockDriverState
*bs
, Error
*reason
)
6907 GLOBAL_STATE_CODE();
6908 for (i
= 0; i
< BLOCK_OP_TYPE_MAX
; i
++) {
6909 bdrv_op_unblock(bs
, i
, reason
);
6913 bool bdrv_op_blocker_is_empty(BlockDriverState
*bs
)
6916 GLOBAL_STATE_CODE();
6917 for (i
= 0; i
< BLOCK_OP_TYPE_MAX
; i
++) {
6918 if (!QLIST_EMPTY(&bs
->op_blockers
[i
])) {
6925 void bdrv_img_create(const char *filename
, const char *fmt
,
6926 const char *base_filename
, const char *base_fmt
,
6927 char *options
, uint64_t img_size
, int flags
, bool quiet
,
6930 QemuOptsList
*create_opts
= NULL
;
6931 QemuOpts
*opts
= NULL
;
6932 const char *backing_fmt
, *backing_file
;
6934 BlockDriver
*drv
, *proto_drv
;
6935 Error
*local_err
= NULL
;
6938 GLOBAL_STATE_CODE();
6940 /* Find driver and parse its options */
6941 drv
= bdrv_find_format(fmt
);
6943 error_setg(errp
, "Unknown file format '%s'", fmt
);
6947 proto_drv
= bdrv_find_protocol(filename
, true, errp
);
6952 if (!drv
->create_opts
) {
6953 error_setg(errp
, "Format driver '%s' does not support image creation",
6958 if (!proto_drv
->create_opts
) {
6959 error_setg(errp
, "Protocol driver '%s' does not support image creation",
6960 proto_drv
->format_name
);
6964 /* Create parameter list */
6965 create_opts
= qemu_opts_append(create_opts
, drv
->create_opts
);
6966 create_opts
= qemu_opts_append(create_opts
, proto_drv
->create_opts
);
6968 opts
= qemu_opts_create(create_opts
, NULL
, 0, &error_abort
);
6970 /* Parse -o options */
6972 if (!qemu_opts_do_parse(opts
, options
, NULL
, errp
)) {
6977 if (!qemu_opt_get(opts
, BLOCK_OPT_SIZE
)) {
6978 qemu_opt_set_number(opts
, BLOCK_OPT_SIZE
, img_size
, &error_abort
);
6979 } else if (img_size
!= UINT64_C(-1)) {
6980 error_setg(errp
, "The image size must be specified only once");
6984 if (base_filename
) {
6985 if (!qemu_opt_set(opts
, BLOCK_OPT_BACKING_FILE
, base_filename
,
6987 error_setg(errp
, "Backing file not supported for file format '%s'",
6994 if (!qemu_opt_set(opts
, BLOCK_OPT_BACKING_FMT
, base_fmt
, NULL
)) {
6995 error_setg(errp
, "Backing file format not supported for file "
6996 "format '%s'", fmt
);
7001 backing_file
= qemu_opt_get(opts
, BLOCK_OPT_BACKING_FILE
);
7003 if (!strcmp(filename
, backing_file
)) {
7004 error_setg(errp
, "Error: Trying to create an image with the "
7005 "same filename as the backing file");
7008 if (backing_file
[0] == '\0') {
7009 error_setg(errp
, "Expected backing file name, got empty string");
7014 backing_fmt
= qemu_opt_get(opts
, BLOCK_OPT_BACKING_FMT
);
7016 /* The size for the image must always be specified, unless we have a backing
7017 * file and we have not been forbidden from opening it. */
7018 size
= qemu_opt_get_size(opts
, BLOCK_OPT_SIZE
, img_size
);
7019 if (backing_file
&& !(flags
& BDRV_O_NO_BACKING
)) {
7020 BlockDriverState
*bs
;
7023 QDict
*backing_options
= NULL
;
7026 bdrv_get_full_backing_filename_from_filename(filename
, backing_file
,
7031 assert(full_backing
);
7034 * No need to do I/O here, which allows us to open encrypted
7035 * backing images without needing the secret
7038 back_flags
&= ~(BDRV_O_RDWR
| BDRV_O_SNAPSHOT
| BDRV_O_NO_BACKING
);
7039 back_flags
|= BDRV_O_NO_IO
;
7041 backing_options
= qdict_new();
7043 qdict_put_str(backing_options
, "driver", backing_fmt
);
7045 qdict_put_bool(backing_options
, BDRV_OPT_FORCE_SHARE
, true);
7047 bs
= bdrv_open(full_backing
, NULL
, backing_options
, back_flags
,
7049 g_free(full_backing
);
7051 error_append_hint(&local_err
, "Could not open backing image.\n");
7055 error_setg(&local_err
,
7056 "Backing file specified without backing format");
7057 error_append_hint(&local_err
, "Detected format of %s.",
7058 bs
->drv
->format_name
);
7062 /* Opened BS, have no size */
7063 size
= bdrv_getlength(bs
);
7065 error_setg_errno(errp
, -size
, "Could not get size of '%s'",
7070 qemu_opt_set_number(opts
, BLOCK_OPT_SIZE
, size
, &error_abort
);
7074 /* (backing_file && !(flags & BDRV_O_NO_BACKING)) */
7075 } else if (backing_file
&& !backing_fmt
) {
7076 error_setg(&local_err
,
7077 "Backing file specified without backing format");
7082 error_setg(errp
, "Image creation needs a size parameter");
7087 printf("Formatting '%s', fmt=%s ", filename
, fmt
);
7088 qemu_opts_print(opts
, " ");
7093 ret
= bdrv_create(drv
, filename
, opts
, &local_err
);
7095 if (ret
== -EFBIG
) {
7096 /* This is generally a better message than whatever the driver would
7097 * deliver (especially because of the cluster_size_hint), since that
7098 * is most probably not much different from "image too large". */
7099 const char *cluster_size_hint
= "";
7100 if (qemu_opt_get_size(opts
, BLOCK_OPT_CLUSTER_SIZE
, 0)) {
7101 cluster_size_hint
= " (try using a larger cluster size)";
7103 error_setg(errp
, "The image size is too large for file format '%s'"
7104 "%s", fmt
, cluster_size_hint
);
7105 error_free(local_err
);
7110 qemu_opts_del(opts
);
7111 qemu_opts_free(create_opts
);
7112 error_propagate(errp
, local_err
);
7115 AioContext
*bdrv_get_aio_context(BlockDriverState
*bs
)
7118 return bs
? bs
->aio_context
: qemu_get_aio_context();
7121 AioContext
*coroutine_fn
bdrv_co_enter(BlockDriverState
*bs
)
7123 Coroutine
*self
= qemu_coroutine_self();
7124 AioContext
*old_ctx
= qemu_coroutine_get_aio_context(self
);
7125 AioContext
*new_ctx
;
7129 * Increase bs->in_flight to ensure that this operation is completed before
7130 * moving the node to a different AioContext. Read new_ctx only afterwards.
7132 bdrv_inc_in_flight(bs
);
7134 new_ctx
= bdrv_get_aio_context(bs
);
7135 aio_co_reschedule_self(new_ctx
);
7139 void coroutine_fn
bdrv_co_leave(BlockDriverState
*bs
, AioContext
*old_ctx
)
7142 aio_co_reschedule_self(old_ctx
);
7143 bdrv_dec_in_flight(bs
);
7146 void coroutine_fn
bdrv_co_lock(BlockDriverState
*bs
)
7148 AioContext
*ctx
= bdrv_get_aio_context(bs
);
7150 /* In the main thread, bs->aio_context won't change concurrently */
7151 assert(qemu_get_current_aio_context() == qemu_get_aio_context());
7154 * We're in coroutine context, so we already hold the lock of the main
7155 * loop AioContext. Don't lock it twice to avoid deadlocks.
7157 assert(qemu_in_coroutine());
7158 if (ctx
!= qemu_get_aio_context()) {
7159 aio_context_acquire(ctx
);
7163 void coroutine_fn
bdrv_co_unlock(BlockDriverState
*bs
)
7165 AioContext
*ctx
= bdrv_get_aio_context(bs
);
7167 assert(qemu_in_coroutine());
7168 if (ctx
!= qemu_get_aio_context()) {
7169 aio_context_release(ctx
);
7173 void bdrv_coroutine_enter(BlockDriverState
*bs
, Coroutine
*co
)
7176 aio_co_enter(bdrv_get_aio_context(bs
), co
);
7179 static void bdrv_do_remove_aio_context_notifier(BdrvAioNotifier
*ban
)
7181 QLIST_REMOVE(ban
, list
);
7185 static void bdrv_detach_aio_context(BlockDriverState
*bs
)
7187 BdrvAioNotifier
*baf
, *baf_tmp
;
7189 assert(!bs
->walking_aio_notifiers
);
7190 bs
->walking_aio_notifiers
= true;
7191 QLIST_FOREACH_SAFE(baf
, &bs
->aio_notifiers
, list
, baf_tmp
) {
7193 bdrv_do_remove_aio_context_notifier(baf
);
7195 baf
->detach_aio_context(baf
->opaque
);
7198 /* Never mind iterating again to check for ->deleted. bdrv_close() will
7199 * remove remaining aio notifiers if we aren't called again.
7201 bs
->walking_aio_notifiers
= false;
7203 if (bs
->drv
&& bs
->drv
->bdrv_detach_aio_context
) {
7204 bs
->drv
->bdrv_detach_aio_context(bs
);
7207 if (bs
->quiesce_counter
) {
7208 aio_enable_external(bs
->aio_context
);
7210 bs
->aio_context
= NULL
;
7213 static void bdrv_attach_aio_context(BlockDriverState
*bs
,
7214 AioContext
*new_context
)
7216 BdrvAioNotifier
*ban
, *ban_tmp
;
7218 if (bs
->quiesce_counter
) {
7219 aio_disable_external(new_context
);
7222 bs
->aio_context
= new_context
;
7224 if (bs
->drv
&& bs
->drv
->bdrv_attach_aio_context
) {
7225 bs
->drv
->bdrv_attach_aio_context(bs
, new_context
);
7228 assert(!bs
->walking_aio_notifiers
);
7229 bs
->walking_aio_notifiers
= true;
7230 QLIST_FOREACH_SAFE(ban
, &bs
->aio_notifiers
, list
, ban_tmp
) {
7232 bdrv_do_remove_aio_context_notifier(ban
);
7234 ban
->attached_aio_context(new_context
, ban
->opaque
);
7237 bs
->walking_aio_notifiers
= false;
7241 * Changes the AioContext used for fd handlers, timers, and BHs by this
7242 * BlockDriverState and all its children and parents.
7244 * Must be called from the main AioContext.
7246 * The caller must own the AioContext lock for the old AioContext of bs, but it
7247 * must not own the AioContext lock for new_context (unless new_context is the
7248 * same as the current context of bs).
7250 * @ignore will accumulate all visited BdrvChild object. The caller is
7251 * responsible for freeing the list afterwards.
7253 void bdrv_set_aio_context_ignore(BlockDriverState
*bs
,
7254 AioContext
*new_context
, GSList
**ignore
)
7256 AioContext
*old_context
= bdrv_get_aio_context(bs
);
7257 GSList
*children_to_process
= NULL
;
7258 GSList
*parents_to_process
= NULL
;
7260 BdrvChild
*child
, *parent
;
7262 g_assert(qemu_get_current_aio_context() == qemu_get_aio_context());
7264 if (old_context
== new_context
) {
7268 bdrv_drained_begin(bs
);
7270 QLIST_FOREACH(child
, &bs
->children
, next
) {
7271 if (g_slist_find(*ignore
, child
)) {
7274 *ignore
= g_slist_prepend(*ignore
, child
);
7275 children_to_process
= g_slist_prepend(children_to_process
, child
);
7278 QLIST_FOREACH(parent
, &bs
->parents
, next_parent
) {
7279 if (g_slist_find(*ignore
, parent
)) {
7282 *ignore
= g_slist_prepend(*ignore
, parent
);
7283 parents_to_process
= g_slist_prepend(parents_to_process
, parent
);
7286 for (entry
= children_to_process
;
7288 entry
= g_slist_next(entry
)) {
7289 child
= entry
->data
;
7290 bdrv_set_aio_context_ignore(child
->bs
, new_context
, ignore
);
7292 g_slist_free(children_to_process
);
7294 for (entry
= parents_to_process
;
7296 entry
= g_slist_next(entry
)) {
7297 parent
= entry
->data
;
7298 assert(parent
->klass
->set_aio_ctx
);
7299 parent
->klass
->set_aio_ctx(parent
, new_context
, ignore
);
7301 g_slist_free(parents_to_process
);
7303 bdrv_detach_aio_context(bs
);
7305 /* Acquire the new context, if necessary */
7306 if (qemu_get_aio_context() != new_context
) {
7307 aio_context_acquire(new_context
);
7310 bdrv_attach_aio_context(bs
, new_context
);
7313 * If this function was recursively called from
7314 * bdrv_set_aio_context_ignore(), there may be nodes in the
7315 * subtree that have not yet been moved to the new AioContext.
7316 * Release the old one so bdrv_drained_end() can poll them.
7318 if (qemu_get_aio_context() != old_context
) {
7319 aio_context_release(old_context
);
7322 bdrv_drained_end(bs
);
7324 if (qemu_get_aio_context() != old_context
) {
7325 aio_context_acquire(old_context
);
7327 if (qemu_get_aio_context() != new_context
) {
7328 aio_context_release(new_context
);
7332 static bool bdrv_parent_can_set_aio_context(BdrvChild
*c
, AioContext
*ctx
,
7333 GSList
**ignore
, Error
**errp
)
7335 if (g_slist_find(*ignore
, c
)) {
7338 *ignore
= g_slist_prepend(*ignore
, c
);
7341 * A BdrvChildClass that doesn't handle AioContext changes cannot
7342 * tolerate any AioContext changes
7344 if (!c
->klass
->can_set_aio_ctx
) {
7345 char *user
= bdrv_child_user_desc(c
);
7346 error_setg(errp
, "Changing iothreads is not supported by %s", user
);
7350 if (!c
->klass
->can_set_aio_ctx(c
, ctx
, ignore
, errp
)) {
7351 assert(!errp
|| *errp
);
7357 bool bdrv_child_can_set_aio_context(BdrvChild
*c
, AioContext
*ctx
,
7358 GSList
**ignore
, Error
**errp
)
7360 GLOBAL_STATE_CODE();
7361 if (g_slist_find(*ignore
, c
)) {
7364 *ignore
= g_slist_prepend(*ignore
, c
);
7365 return bdrv_can_set_aio_context(c
->bs
, ctx
, ignore
, errp
);
7368 /* @ignore will accumulate all visited BdrvChild object. The caller is
7369 * responsible for freeing the list afterwards. */
7370 bool bdrv_can_set_aio_context(BlockDriverState
*bs
, AioContext
*ctx
,
7371 GSList
**ignore
, Error
**errp
)
7375 if (bdrv_get_aio_context(bs
) == ctx
) {
7379 GLOBAL_STATE_CODE();
7381 QLIST_FOREACH(c
, &bs
->parents
, next_parent
) {
7382 if (!bdrv_parent_can_set_aio_context(c
, ctx
, ignore
, errp
)) {
7386 QLIST_FOREACH(c
, &bs
->children
, next
) {
7387 if (!bdrv_child_can_set_aio_context(c
, ctx
, ignore
, errp
)) {
7395 int bdrv_child_try_set_aio_context(BlockDriverState
*bs
, AioContext
*ctx
,
7396 BdrvChild
*ignore_child
, Error
**errp
)
7401 GLOBAL_STATE_CODE();
7403 ignore
= ignore_child
? g_slist_prepend(NULL
, ignore_child
) : NULL
;
7404 ret
= bdrv_can_set_aio_context(bs
, ctx
, &ignore
, errp
);
7405 g_slist_free(ignore
);
7411 ignore
= ignore_child
? g_slist_prepend(NULL
, ignore_child
) : NULL
;
7412 bdrv_set_aio_context_ignore(bs
, ctx
, &ignore
);
7413 g_slist_free(ignore
);
7418 int bdrv_try_set_aio_context(BlockDriverState
*bs
, AioContext
*ctx
,
7421 GLOBAL_STATE_CODE();
7422 return bdrv_child_try_set_aio_context(bs
, ctx
, NULL
, errp
);
7425 void bdrv_add_aio_context_notifier(BlockDriverState
*bs
,
7426 void (*attached_aio_context
)(AioContext
*new_context
, void *opaque
),
7427 void (*detach_aio_context
)(void *opaque
), void *opaque
)
7429 BdrvAioNotifier
*ban
= g_new(BdrvAioNotifier
, 1);
7430 *ban
= (BdrvAioNotifier
){
7431 .attached_aio_context
= attached_aio_context
,
7432 .detach_aio_context
= detach_aio_context
,
7435 GLOBAL_STATE_CODE();
7437 QLIST_INSERT_HEAD(&bs
->aio_notifiers
, ban
, list
);
7440 void bdrv_remove_aio_context_notifier(BlockDriverState
*bs
,
7441 void (*attached_aio_context
)(AioContext
*,
7443 void (*detach_aio_context
)(void *),
7446 BdrvAioNotifier
*ban
, *ban_next
;
7447 GLOBAL_STATE_CODE();
7449 QLIST_FOREACH_SAFE(ban
, &bs
->aio_notifiers
, list
, ban_next
) {
7450 if (ban
->attached_aio_context
== attached_aio_context
&&
7451 ban
->detach_aio_context
== detach_aio_context
&&
7452 ban
->opaque
== opaque
&&
7453 ban
->deleted
== false)
7455 if (bs
->walking_aio_notifiers
) {
7456 ban
->deleted
= true;
7458 bdrv_do_remove_aio_context_notifier(ban
);
7467 int bdrv_amend_options(BlockDriverState
*bs
, QemuOpts
*opts
,
7468 BlockDriverAmendStatusCB
*status_cb
, void *cb_opaque
,
7472 GLOBAL_STATE_CODE();
7474 error_setg(errp
, "Node is ejected");
7477 if (!bs
->drv
->bdrv_amend_options
) {
7478 error_setg(errp
, "Block driver '%s' does not support option amendment",
7479 bs
->drv
->format_name
);
7482 return bs
->drv
->bdrv_amend_options(bs
, opts
, status_cb
,
7483 cb_opaque
, force
, errp
);
7487 * This function checks whether the given @to_replace is allowed to be
7488 * replaced by a node that always shows the same data as @bs. This is
7489 * used for example to verify whether the mirror job can replace
7490 * @to_replace by the target mirrored from @bs.
7491 * To be replaceable, @bs and @to_replace may either be guaranteed to
7492 * always show the same data (because they are only connected through
7493 * filters), or some driver may allow replacing one of its children
7494 * because it can guarantee that this child's data is not visible at
7495 * all (for example, for dissenting quorum children that have no other
7498 bool bdrv_recurse_can_replace(BlockDriverState
*bs
,
7499 BlockDriverState
*to_replace
)
7501 BlockDriverState
*filtered
;
7503 GLOBAL_STATE_CODE();
7505 if (!bs
|| !bs
->drv
) {
7509 if (bs
== to_replace
) {
7513 /* See what the driver can do */
7514 if (bs
->drv
->bdrv_recurse_can_replace
) {
7515 return bs
->drv
->bdrv_recurse_can_replace(bs
, to_replace
);
7518 /* For filters without an own implementation, we can recurse on our own */
7519 filtered
= bdrv_filter_bs(bs
);
7521 return bdrv_recurse_can_replace(filtered
, to_replace
);
7529 * Check whether the given @node_name can be replaced by a node that
7530 * has the same data as @parent_bs. If so, return @node_name's BDS;
7533 * @node_name must be a (recursive) *child of @parent_bs (or this
7534 * function will return NULL).
7536 * The result (whether the node can be replaced or not) is only valid
7537 * for as long as no graph or permission changes occur.
7539 BlockDriverState
*check_to_replace_node(BlockDriverState
*parent_bs
,
7540 const char *node_name
, Error
**errp
)
7542 BlockDriverState
*to_replace_bs
= bdrv_find_node(node_name
);
7543 AioContext
*aio_context
;
7545 GLOBAL_STATE_CODE();
7547 if (!to_replace_bs
) {
7548 error_setg(errp
, "Failed to find node with node-name='%s'", node_name
);
7552 aio_context
= bdrv_get_aio_context(to_replace_bs
);
7553 aio_context_acquire(aio_context
);
7555 if (bdrv_op_is_blocked(to_replace_bs
, BLOCK_OP_TYPE_REPLACE
, errp
)) {
7556 to_replace_bs
= NULL
;
7560 /* We don't want arbitrary node of the BDS chain to be replaced only the top
7561 * most non filter in order to prevent data corruption.
7562 * Another benefit is that this tests exclude backing files which are
7563 * blocked by the backing blockers.
7565 if (!bdrv_recurse_can_replace(parent_bs
, to_replace_bs
)) {
7566 error_setg(errp
, "Cannot replace '%s' by a node mirrored from '%s', "
7567 "because it cannot be guaranteed that doing so would not "
7568 "lead to an abrupt change of visible data",
7569 node_name
, parent_bs
->node_name
);
7570 to_replace_bs
= NULL
;
7575 aio_context_release(aio_context
);
7576 return to_replace_bs
;
7580 * Iterates through the list of runtime option keys that are said to
7581 * be "strong" for a BDS. An option is called "strong" if it changes
7582 * a BDS's data. For example, the null block driver's "size" and
7583 * "read-zeroes" options are strong, but its "latency-ns" option is
7586 * If a key returned by this function ends with a dot, all options
7587 * starting with that prefix are strong.
7589 static const char *const *strong_options(BlockDriverState
*bs
,
7590 const char *const *curopt
)
7592 static const char *const global_options
[] = {
7593 "driver", "filename", NULL
7597 return &global_options
[0];
7601 if (curopt
== &global_options
[ARRAY_SIZE(global_options
) - 1] && bs
->drv
) {
7602 curopt
= bs
->drv
->strong_runtime_opts
;
7605 return (curopt
&& *curopt
) ? curopt
: NULL
;
7609 * Copies all strong runtime options from bs->options to the given
7610 * QDict. The set of strong option keys is determined by invoking
7613 * Returns true iff any strong option was present in bs->options (and
7614 * thus copied to the target QDict) with the exception of "filename"
7615 * and "driver". The caller is expected to use this value to decide
7616 * whether the existence of strong options prevents the generation of
7619 static bool append_strong_runtime_options(QDict
*d
, BlockDriverState
*bs
)
7621 bool found_any
= false;
7622 const char *const *option_name
= NULL
;
7628 while ((option_name
= strong_options(bs
, option_name
))) {
7629 bool option_given
= false;
7631 assert(strlen(*option_name
) > 0);
7632 if ((*option_name
)[strlen(*option_name
) - 1] != '.') {
7633 QObject
*entry
= qdict_get(bs
->options
, *option_name
);
7638 qdict_put_obj(d
, *option_name
, qobject_ref(entry
));
7639 option_given
= true;
7641 const QDictEntry
*entry
;
7642 for (entry
= qdict_first(bs
->options
); entry
;
7643 entry
= qdict_next(bs
->options
, entry
))
7645 if (strstart(qdict_entry_key(entry
), *option_name
, NULL
)) {
7646 qdict_put_obj(d
, qdict_entry_key(entry
),
7647 qobject_ref(qdict_entry_value(entry
)));
7648 option_given
= true;
7653 /* While "driver" and "filename" need to be included in a JSON filename,
7654 * their existence does not prohibit generation of a plain filename. */
7655 if (!found_any
&& option_given
&&
7656 strcmp(*option_name
, "driver") && strcmp(*option_name
, "filename"))
7662 if (!qdict_haskey(d
, "driver")) {
7663 /* Drivers created with bdrv_new_open_driver() may not have a
7664 * @driver option. Add it here. */
7665 qdict_put_str(d
, "driver", bs
->drv
->format_name
);
7671 /* Note: This function may return false positives; it may return true
7672 * even if opening the backing file specified by bs's image header
7673 * would result in exactly bs->backing. */
7674 static bool bdrv_backing_overridden(BlockDriverState
*bs
)
7676 GLOBAL_STATE_CODE();
7678 return strcmp(bs
->auto_backing_file
,
7679 bs
->backing
->bs
->filename
);
7681 /* No backing BDS, so if the image header reports any backing
7682 * file, it must have been suppressed */
7683 return bs
->auto_backing_file
[0] != '\0';
7687 /* Updates the following BDS fields:
7688 * - exact_filename: A filename which may be used for opening a block device
7689 * which (mostly) equals the given BDS (even without any
7690 * other options; so reading and writing must return the same
7691 * results, but caching etc. may be different)
7692 * - full_open_options: Options which, when given when opening a block device
7693 * (without a filename), result in a BDS (mostly)
7694 * equalling the given one
7695 * - filename: If exact_filename is set, it is copied here. Otherwise,
7696 * full_open_options is converted to a JSON object, prefixed with
7697 * "json:" (for use through the JSON pseudo protocol) and put here.
7699 void bdrv_refresh_filename(BlockDriverState
*bs
)
7701 BlockDriver
*drv
= bs
->drv
;
7703 BlockDriverState
*primary_child_bs
;
7705 bool backing_overridden
;
7706 bool generate_json_filename
; /* Whether our default implementation should
7707 fill exact_filename (false) or not (true) */
7709 GLOBAL_STATE_CODE();
7715 /* This BDS's file name may depend on any of its children's file names, so
7716 * refresh those first */
7717 QLIST_FOREACH(child
, &bs
->children
, next
) {
7718 bdrv_refresh_filename(child
->bs
);
7722 /* For implicit nodes, just copy everything from the single child */
7723 child
= QLIST_FIRST(&bs
->children
);
7724 assert(QLIST_NEXT(child
, next
) == NULL
);
7726 pstrcpy(bs
->exact_filename
, sizeof(bs
->exact_filename
),
7727 child
->bs
->exact_filename
);
7728 pstrcpy(bs
->filename
, sizeof(bs
->filename
), child
->bs
->filename
);
7730 qobject_unref(bs
->full_open_options
);
7731 bs
->full_open_options
= qobject_ref(child
->bs
->full_open_options
);
7736 backing_overridden
= bdrv_backing_overridden(bs
);
7738 if (bs
->open_flags
& BDRV_O_NO_IO
) {
7739 /* Without I/O, the backing file does not change anything.
7740 * Therefore, in such a case (primarily qemu-img), we can
7741 * pretend the backing file has not been overridden even if
7742 * it technically has been. */
7743 backing_overridden
= false;
7746 /* Gather the options QDict */
7748 generate_json_filename
= append_strong_runtime_options(opts
, bs
);
7749 generate_json_filename
|= backing_overridden
;
7751 if (drv
->bdrv_gather_child_options
) {
7752 /* Some block drivers may not want to present all of their children's
7753 * options, or name them differently from BdrvChild.name */
7754 drv
->bdrv_gather_child_options(bs
, opts
, backing_overridden
);
7756 QLIST_FOREACH(child
, &bs
->children
, next
) {
7757 if (child
== bs
->backing
&& !backing_overridden
) {
7758 /* We can skip the backing BDS if it has not been overridden */
7762 qdict_put(opts
, child
->name
,
7763 qobject_ref(child
->bs
->full_open_options
));
7766 if (backing_overridden
&& !bs
->backing
) {
7767 /* Force no backing file */
7768 qdict_put_null(opts
, "backing");
7772 qobject_unref(bs
->full_open_options
);
7773 bs
->full_open_options
= opts
;
7775 primary_child_bs
= bdrv_primary_bs(bs
);
7777 if (drv
->bdrv_refresh_filename
) {
7778 /* Obsolete information is of no use here, so drop the old file name
7779 * information before refreshing it */
7780 bs
->exact_filename
[0] = '\0';
7782 drv
->bdrv_refresh_filename(bs
);
7783 } else if (primary_child_bs
) {
7785 * Try to reconstruct valid information from the underlying
7786 * file -- this only works for format nodes (filter nodes
7787 * cannot be probed and as such must be selected by the user
7788 * either through an options dict, or through a special
7789 * filename which the filter driver must construct in its
7790 * .bdrv_refresh_filename() implementation).
7793 bs
->exact_filename
[0] = '\0';
7796 * We can use the underlying file's filename if:
7797 * - it has a filename,
7798 * - the current BDS is not a filter,
7799 * - the file is a protocol BDS, and
7800 * - opening that file (as this BDS's format) will automatically create
7801 * the BDS tree we have right now, that is:
7802 * - the user did not significantly change this BDS's behavior with
7803 * some explicit (strong) options
7804 * - no non-file child of this BDS has been overridden by the user
7805 * Both of these conditions are represented by generate_json_filename.
7807 if (primary_child_bs
->exact_filename
[0] &&
7808 primary_child_bs
->drv
->bdrv_file_open
&&
7809 !drv
->is_filter
&& !generate_json_filename
)
7811 strcpy(bs
->exact_filename
, primary_child_bs
->exact_filename
);
7815 if (bs
->exact_filename
[0]) {
7816 pstrcpy(bs
->filename
, sizeof(bs
->filename
), bs
->exact_filename
);
7818 GString
*json
= qobject_to_json(QOBJECT(bs
->full_open_options
));
7819 if (snprintf(bs
->filename
, sizeof(bs
->filename
), "json:%s",
7820 json
->str
) >= sizeof(bs
->filename
)) {
7821 /* Give user a hint if we truncated things. */
7822 strcpy(bs
->filename
+ sizeof(bs
->filename
) - 4, "...");
7824 g_string_free(json
, true);
7828 char *bdrv_dirname(BlockDriverState
*bs
, Error
**errp
)
7830 BlockDriver
*drv
= bs
->drv
;
7831 BlockDriverState
*child_bs
;
7833 GLOBAL_STATE_CODE();
7836 error_setg(errp
, "Node '%s' is ejected", bs
->node_name
);
7840 if (drv
->bdrv_dirname
) {
7841 return drv
->bdrv_dirname(bs
, errp
);
7844 child_bs
= bdrv_primary_bs(bs
);
7846 return bdrv_dirname(child_bs
, errp
);
7849 bdrv_refresh_filename(bs
);
7850 if (bs
->exact_filename
[0] != '\0') {
7851 return path_combine(bs
->exact_filename
, "");
7854 error_setg(errp
, "Cannot generate a base directory for %s nodes",
7860 * Hot add/remove a BDS's child. So the user can take a child offline when
7861 * it is broken and take a new child online
7863 void bdrv_add_child(BlockDriverState
*parent_bs
, BlockDriverState
*child_bs
,
7866 GLOBAL_STATE_CODE();
7867 if (!parent_bs
->drv
|| !parent_bs
->drv
->bdrv_add_child
) {
7868 error_setg(errp
, "The node %s does not support adding a child",
7869 bdrv_get_device_or_node_name(parent_bs
));
7873 if (!QLIST_EMPTY(&child_bs
->parents
)) {
7874 error_setg(errp
, "The node %s already has a parent",
7875 child_bs
->node_name
);
7879 parent_bs
->drv
->bdrv_add_child(parent_bs
, child_bs
, errp
);
7882 void bdrv_del_child(BlockDriverState
*parent_bs
, BdrvChild
*child
, Error
**errp
)
7886 GLOBAL_STATE_CODE();
7887 if (!parent_bs
->drv
|| !parent_bs
->drv
->bdrv_del_child
) {
7888 error_setg(errp
, "The node %s does not support removing a child",
7889 bdrv_get_device_or_node_name(parent_bs
));
7893 QLIST_FOREACH(tmp
, &parent_bs
->children
, next
) {
7900 error_setg(errp
, "The node %s does not have a child named %s",
7901 bdrv_get_device_or_node_name(parent_bs
),
7902 bdrv_get_device_or_node_name(child
->bs
));
7906 parent_bs
->drv
->bdrv_del_child(parent_bs
, child
, errp
);
7909 int bdrv_make_empty(BdrvChild
*c
, Error
**errp
)
7911 BlockDriver
*drv
= c
->bs
->drv
;
7914 GLOBAL_STATE_CODE();
7915 assert(c
->perm
& (BLK_PERM_WRITE
| BLK_PERM_WRITE_UNCHANGED
));
7917 if (!drv
->bdrv_make_empty
) {
7918 error_setg(errp
, "%s does not support emptying nodes",
7923 ret
= drv
->bdrv_make_empty(c
->bs
);
7925 error_setg_errno(errp
, -ret
, "Failed to empty %s",
7934 * Return the child that @bs acts as an overlay for, and from which data may be
7935 * copied in COW or COR operations. Usually this is the backing file.
7937 BdrvChild
*bdrv_cow_child(BlockDriverState
*bs
)
7941 if (!bs
|| !bs
->drv
) {
7945 if (bs
->drv
->is_filter
) {
7953 assert(bs
->backing
->role
& BDRV_CHILD_COW
);
7958 * If @bs acts as a filter for exactly one of its children, return
7961 BdrvChild
*bdrv_filter_child(BlockDriverState
*bs
)
7966 if (!bs
|| !bs
->drv
) {
7970 if (!bs
->drv
->is_filter
) {
7974 /* Only one of @backing or @file may be used */
7975 assert(!(bs
->backing
&& bs
->file
));
7977 c
= bs
->backing
?: bs
->file
;
7982 assert(c
->role
& BDRV_CHILD_FILTERED
);
7987 * Return either the result of bdrv_cow_child() or bdrv_filter_child(),
7988 * whichever is non-NULL.
7990 * Return NULL if both are NULL.
7992 BdrvChild
*bdrv_filter_or_cow_child(BlockDriverState
*bs
)
7994 BdrvChild
*cow_child
= bdrv_cow_child(bs
);
7995 BdrvChild
*filter_child
= bdrv_filter_child(bs
);
7998 /* Filter nodes cannot have COW backing files */
7999 assert(!(cow_child
&& filter_child
));
8001 return cow_child
?: filter_child
;
8005 * Return the primary child of this node: For filters, that is the
8006 * filtered child. For other nodes, that is usually the child storing
8008 * (A generally more helpful description is that this is (usually) the
8009 * child that has the same filename as @bs.)
8011 * Drivers do not necessarily have a primary child; for example quorum
8014 BdrvChild
*bdrv_primary_child(BlockDriverState
*bs
)
8016 BdrvChild
*c
, *found
= NULL
;
8019 QLIST_FOREACH(c
, &bs
->children
, next
) {
8020 if (c
->role
& BDRV_CHILD_PRIMARY
) {
8029 static BlockDriverState
*bdrv_do_skip_filters(BlockDriverState
*bs
,
8030 bool stop_on_explicit_filter
)
8038 while (!(stop_on_explicit_filter
&& !bs
->implicit
)) {
8039 c
= bdrv_filter_child(bs
);
8042 * A filter that is embedded in a working block graph must
8043 * have a child. Assert this here so this function does
8044 * not return a filter node that is not expected by the
8047 assert(!bs
->drv
|| !bs
->drv
->is_filter
);
8053 * Note that this treats nodes with bs->drv == NULL as not being
8054 * filters (bs->drv == NULL should be replaced by something else
8056 * The advantage of this behavior is that this function will thus
8057 * always return a non-NULL value (given a non-NULL @bs).
8064 * Return the first BDS that has not been added implicitly or that
8065 * does not have a filtered child down the chain starting from @bs
8066 * (including @bs itself).
8068 BlockDriverState
*bdrv_skip_implicit_filters(BlockDriverState
*bs
)
8070 GLOBAL_STATE_CODE();
8071 return bdrv_do_skip_filters(bs
, true);
8075 * Return the first BDS that does not have a filtered child down the
8076 * chain starting from @bs (including @bs itself).
8078 BlockDriverState
*bdrv_skip_filters(BlockDriverState
*bs
)
8081 return bdrv_do_skip_filters(bs
, false);
8085 * For a backing chain, return the first non-filter backing image of
8086 * the first non-filter image.
8088 BlockDriverState
*bdrv_backing_chain_next(BlockDriverState
*bs
)
8091 return bdrv_skip_filters(bdrv_cow_bs(bdrv_skip_filters(bs
)));
8095 * Check whether [offset, offset + bytes) overlaps with the cached
8096 * block-status data region.
8098 * If so, and @pnum is not NULL, set *pnum to `bsc.data_end - offset`,
8099 * which is what bdrv_bsc_is_data()'s interface needs.
8100 * Otherwise, *pnum is not touched.
8102 static bool bdrv_bsc_range_overlaps_locked(BlockDriverState
*bs
,
8103 int64_t offset
, int64_t bytes
,
8106 BdrvBlockStatusCache
*bsc
= qatomic_rcu_read(&bs
->block_status_cache
);
8110 qatomic_read(&bsc
->valid
) &&
8111 ranges_overlap(offset
, bytes
, bsc
->data_start
,
8112 bsc
->data_end
- bsc
->data_start
);
8114 if (overlaps
&& pnum
) {
8115 *pnum
= bsc
->data_end
- offset
;
8122 * See block_int.h for this function's documentation.
8124 bool bdrv_bsc_is_data(BlockDriverState
*bs
, int64_t offset
, int64_t *pnum
)
8127 RCU_READ_LOCK_GUARD();
8128 return bdrv_bsc_range_overlaps_locked(bs
, offset
, 1, pnum
);
8132 * See block_int.h for this function's documentation.
8134 void bdrv_bsc_invalidate_range(BlockDriverState
*bs
,
8135 int64_t offset
, int64_t bytes
)
8138 RCU_READ_LOCK_GUARD();
8140 if (bdrv_bsc_range_overlaps_locked(bs
, offset
, bytes
, NULL
)) {
8141 qatomic_set(&bs
->block_status_cache
->valid
, false);
8146 * See block_int.h for this function's documentation.
8148 void bdrv_bsc_fill(BlockDriverState
*bs
, int64_t offset
, int64_t bytes
)
8150 BdrvBlockStatusCache
*new_bsc
= g_new(BdrvBlockStatusCache
, 1);
8151 BdrvBlockStatusCache
*old_bsc
;
8154 *new_bsc
= (BdrvBlockStatusCache
) {
8156 .data_start
= offset
,
8157 .data_end
= offset
+ bytes
,
8160 QEMU_LOCK_GUARD(&bs
->bsc_modify_lock
);
8162 old_bsc
= qatomic_rcu_read(&bs
->block_status_cache
);
8163 qatomic_rcu_set(&bs
->block_status_cache
, new_bsc
);
8165 g_free_rcu(old_bsc
, rcu
);