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 static QTAILQ_HEAD(, BlockDriverState
) graph_bdrv_states
=
71 QTAILQ_HEAD_INITIALIZER(graph_bdrv_states
);
73 static QTAILQ_HEAD(, BlockDriverState
) all_bdrv_states
=
74 QTAILQ_HEAD_INITIALIZER(all_bdrv_states
);
76 static QLIST_HEAD(, BlockDriver
) bdrv_drivers
=
77 QLIST_HEAD_INITIALIZER(bdrv_drivers
);
79 static BlockDriverState
*bdrv_open_inherit(const char *filename
,
80 const char *reference
,
81 QDict
*options
, int flags
,
82 BlockDriverState
*parent
,
83 const BdrvChildClass
*child_class
,
84 BdrvChildRole child_role
,
87 static bool bdrv_recurse_has_child(BlockDriverState
*bs
,
88 BlockDriverState
*child
);
90 static void bdrv_child_free(BdrvChild
*child
);
91 static void bdrv_replace_child_noperm(BdrvChild
**child
,
92 BlockDriverState
*new_bs
,
93 bool free_empty_child
);
94 static void bdrv_remove_file_or_backing_child(BlockDriverState
*bs
,
97 static void bdrv_remove_filter_or_cow_child(BlockDriverState
*bs
,
100 static int bdrv_reopen_prepare(BDRVReopenState
*reopen_state
,
101 BlockReopenQueue
*queue
,
102 Transaction
*change_child_tran
, Error
**errp
);
103 static void bdrv_reopen_commit(BDRVReopenState
*reopen_state
);
104 static void bdrv_reopen_abort(BDRVReopenState
*reopen_state
);
106 /* If non-zero, use only whitelisted block drivers */
107 static int use_bdrv_whitelist
;
110 static int is_windows_drive_prefix(const char *filename
)
112 return (((filename
[0] >= 'a' && filename
[0] <= 'z') ||
113 (filename
[0] >= 'A' && filename
[0] <= 'Z')) &&
117 int is_windows_drive(const char *filename
)
119 if (is_windows_drive_prefix(filename
) &&
122 if (strstart(filename
, "\\\\.\\", NULL
) ||
123 strstart(filename
, "//./", NULL
))
129 size_t bdrv_opt_mem_align(BlockDriverState
*bs
)
131 if (!bs
|| !bs
->drv
) {
132 /* page size or 4k (hdd sector size) should be on the safe side */
133 return MAX(4096, qemu_real_host_page_size
);
136 return bs
->bl
.opt_mem_alignment
;
139 size_t bdrv_min_mem_align(BlockDriverState
*bs
)
141 if (!bs
|| !bs
->drv
) {
142 /* page size or 4k (hdd sector size) should be on the safe side */
143 return MAX(4096, qemu_real_host_page_size
);
146 return bs
->bl
.min_mem_alignment
;
149 /* check if the path starts with "<protocol>:" */
150 int path_has_protocol(const char *path
)
155 if (is_windows_drive(path
) ||
156 is_windows_drive_prefix(path
)) {
159 p
= path
+ strcspn(path
, ":/\\");
161 p
= path
+ strcspn(path
, ":/");
167 int path_is_absolute(const char *path
)
170 /* specific case for names like: "\\.\d:" */
171 if (is_windows_drive(path
) || is_windows_drive_prefix(path
)) {
174 return (*path
== '/' || *path
== '\\');
176 return (*path
== '/');
180 /* if filename is absolute, just return its duplicate. Otherwise, build a
181 path to it by considering it is relative to base_path. URL are
183 char *path_combine(const char *base_path
, const char *filename
)
185 const char *protocol_stripped
= NULL
;
190 if (path_is_absolute(filename
)) {
191 return g_strdup(filename
);
194 if (path_has_protocol(base_path
)) {
195 protocol_stripped
= strchr(base_path
, ':');
196 if (protocol_stripped
) {
200 p
= protocol_stripped
?: base_path
;
202 p1
= strrchr(base_path
, '/');
206 p2
= strrchr(base_path
, '\\');
207 if (!p1
|| p2
> p1
) {
222 result
= g_malloc(len
+ strlen(filename
) + 1);
223 memcpy(result
, base_path
, len
);
224 strcpy(result
+ len
, filename
);
230 * Helper function for bdrv_parse_filename() implementations to remove optional
231 * protocol prefixes (especially "file:") from a filename and for putting the
232 * stripped filename into the options QDict if there is such a prefix.
234 void bdrv_parse_filename_strip_prefix(const char *filename
, const char *prefix
,
237 if (strstart(filename
, prefix
, &filename
)) {
238 /* Stripping the explicit protocol prefix may result in a protocol
239 * prefix being (wrongly) detected (if the filename contains a colon) */
240 if (path_has_protocol(filename
)) {
241 GString
*fat_filename
;
243 /* This means there is some colon before the first slash; therefore,
244 * this cannot be an absolute path */
245 assert(!path_is_absolute(filename
));
247 /* And we can thus fix the protocol detection issue by prefixing it
249 fat_filename
= g_string_new("./");
250 g_string_append(fat_filename
, filename
);
252 assert(!path_has_protocol(fat_filename
->str
));
254 qdict_put(options
, "filename",
255 qstring_from_gstring(fat_filename
));
257 /* If no protocol prefix was detected, we can use the shortened
259 qdict_put_str(options
, "filename", filename
);
265 /* Returns whether the image file is opened as read-only. Note that this can
266 * return false and writing to the image file is still not possible because the
267 * image is inactivated. */
268 bool bdrv_is_read_only(BlockDriverState
*bs
)
270 return !(bs
->open_flags
& BDRV_O_RDWR
);
273 int bdrv_can_set_read_only(BlockDriverState
*bs
, bool read_only
,
274 bool ignore_allow_rdw
, Error
**errp
)
276 /* Do not set read_only if copy_on_read is enabled */
277 if (bs
->copy_on_read
&& read_only
) {
278 error_setg(errp
, "Can't set node '%s' to r/o with copy-on-read enabled",
279 bdrv_get_device_or_node_name(bs
));
283 /* Do not clear read_only if it is prohibited */
284 if (!read_only
&& !(bs
->open_flags
& BDRV_O_ALLOW_RDWR
) &&
287 error_setg(errp
, "Node '%s' is read only",
288 bdrv_get_device_or_node_name(bs
));
296 * Called by a driver that can only provide a read-only image.
298 * Returns 0 if the node is already read-only or it could switch the node to
299 * read-only because BDRV_O_AUTO_RDONLY is set.
301 * Returns -EACCES if the node is read-write and BDRV_O_AUTO_RDONLY is not set
302 * or bdrv_can_set_read_only() forbids making the node read-only. If @errmsg
303 * is not NULL, it is used as the error message for the Error object.
305 int bdrv_apply_auto_read_only(BlockDriverState
*bs
, const char *errmsg
,
310 if (!(bs
->open_flags
& BDRV_O_RDWR
)) {
313 if (!(bs
->open_flags
& BDRV_O_AUTO_RDONLY
)) {
317 ret
= bdrv_can_set_read_only(bs
, true, false, NULL
);
322 bs
->open_flags
&= ~BDRV_O_RDWR
;
327 error_setg(errp
, "%s", errmsg
?: "Image is read-only");
332 * If @backing is empty, this function returns NULL without setting
333 * @errp. In all other cases, NULL will only be returned with @errp
336 * Therefore, a return value of NULL without @errp set means that
337 * there is no backing file; if @errp is set, there is one but its
338 * absolute filename cannot be generated.
340 char *bdrv_get_full_backing_filename_from_filename(const char *backed
,
344 if (backing
[0] == '\0') {
346 } else if (path_has_protocol(backing
) || path_is_absolute(backing
)) {
347 return g_strdup(backing
);
348 } else if (backed
[0] == '\0' || strstart(backed
, "json:", NULL
)) {
349 error_setg(errp
, "Cannot use relative backing file names for '%s'",
353 return path_combine(backed
, backing
);
358 * If @filename is empty or NULL, this function returns NULL without
359 * setting @errp. In all other cases, NULL will only be returned with
362 static char *bdrv_make_absolute_filename(BlockDriverState
*relative_to
,
363 const char *filename
, Error
**errp
)
365 char *dir
, *full_name
;
367 if (!filename
|| filename
[0] == '\0') {
369 } else if (path_has_protocol(filename
) || path_is_absolute(filename
)) {
370 return g_strdup(filename
);
373 dir
= bdrv_dirname(relative_to
, errp
);
378 full_name
= g_strconcat(dir
, filename
, NULL
);
383 char *bdrv_get_full_backing_filename(BlockDriverState
*bs
, Error
**errp
)
385 return bdrv_make_absolute_filename(bs
, bs
->backing_file
, errp
);
388 void bdrv_register(BlockDriver
*bdrv
)
390 assert(bdrv
->format_name
);
391 QLIST_INSERT_HEAD(&bdrv_drivers
, bdrv
, list
);
394 BlockDriverState
*bdrv_new(void)
396 BlockDriverState
*bs
;
399 bs
= g_new0(BlockDriverState
, 1);
400 QLIST_INIT(&bs
->dirty_bitmaps
);
401 for (i
= 0; i
< BLOCK_OP_TYPE_MAX
; i
++) {
402 QLIST_INIT(&bs
->op_blockers
[i
]);
404 qemu_co_mutex_init(&bs
->reqs_lock
);
405 qemu_mutex_init(&bs
->dirty_bitmap_mutex
);
407 bs
->aio_context
= qemu_get_aio_context();
409 qemu_co_queue_init(&bs
->flush_queue
);
411 qemu_co_mutex_init(&bs
->bsc_modify_lock
);
412 bs
->block_status_cache
= g_new0(BdrvBlockStatusCache
, 1);
414 for (i
= 0; i
< bdrv_drain_all_count
; i
++) {
415 bdrv_drained_begin(bs
);
418 QTAILQ_INSERT_TAIL(&all_bdrv_states
, bs
, bs_list
);
423 static BlockDriver
*bdrv_do_find_format(const char *format_name
)
427 QLIST_FOREACH(drv1
, &bdrv_drivers
, list
) {
428 if (!strcmp(drv1
->format_name
, format_name
)) {
436 BlockDriver
*bdrv_find_format(const char *format_name
)
441 drv1
= bdrv_do_find_format(format_name
);
446 /* The driver isn't registered, maybe we need to load a module */
447 for (i
= 0; i
< (int)ARRAY_SIZE(block_driver_modules
); ++i
) {
448 if (!strcmp(block_driver_modules
[i
].format_name
, format_name
)) {
449 block_module_load_one(block_driver_modules
[i
].library_name
);
454 return bdrv_do_find_format(format_name
);
457 static int bdrv_format_is_whitelisted(const char *format_name
, bool read_only
)
459 static const char *whitelist_rw
[] = {
460 CONFIG_BDRV_RW_WHITELIST
463 static const char *whitelist_ro
[] = {
464 CONFIG_BDRV_RO_WHITELIST
469 if (!whitelist_rw
[0] && !whitelist_ro
[0]) {
470 return 1; /* no whitelist, anything goes */
473 for (p
= whitelist_rw
; *p
; p
++) {
474 if (!strcmp(format_name
, *p
)) {
479 for (p
= whitelist_ro
; *p
; p
++) {
480 if (!strcmp(format_name
, *p
)) {
488 int bdrv_is_whitelisted(BlockDriver
*drv
, bool read_only
)
490 return bdrv_format_is_whitelisted(drv
->format_name
, read_only
);
493 bool bdrv_uses_whitelist(void)
495 return use_bdrv_whitelist
;
498 typedef struct CreateCo
{
506 static void coroutine_fn
bdrv_create_co_entry(void *opaque
)
508 Error
*local_err
= NULL
;
511 CreateCo
*cco
= opaque
;
514 ret
= cco
->drv
->bdrv_co_create_opts(cco
->drv
,
515 cco
->filename
, cco
->opts
, &local_err
);
516 error_propagate(&cco
->err
, local_err
);
520 int bdrv_create(BlockDriver
*drv
, const char* filename
,
521 QemuOpts
*opts
, Error
**errp
)
528 .filename
= g_strdup(filename
),
534 if (!drv
->bdrv_co_create_opts
) {
535 error_setg(errp
, "Driver '%s' does not support image creation", drv
->format_name
);
540 if (qemu_in_coroutine()) {
541 /* Fast-path if already in coroutine context */
542 bdrv_create_co_entry(&cco
);
544 co
= qemu_coroutine_create(bdrv_create_co_entry
, &cco
);
545 qemu_coroutine_enter(co
);
546 while (cco
.ret
== NOT_DONE
) {
547 aio_poll(qemu_get_aio_context(), true);
554 error_propagate(errp
, cco
.err
);
556 error_setg_errno(errp
, -ret
, "Could not create image");
561 g_free(cco
.filename
);
566 * Helper function for bdrv_create_file_fallback(): Resize @blk to at
567 * least the given @minimum_size.
569 * On success, return @blk's actual length.
570 * Otherwise, return -errno.
572 static int64_t create_file_fallback_truncate(BlockBackend
*blk
,
573 int64_t minimum_size
, Error
**errp
)
575 Error
*local_err
= NULL
;
579 ret
= blk_truncate(blk
, minimum_size
, false, PREALLOC_MODE_OFF
, 0,
581 if (ret
< 0 && ret
!= -ENOTSUP
) {
582 error_propagate(errp
, local_err
);
586 size
= blk_getlength(blk
);
588 error_free(local_err
);
589 error_setg_errno(errp
, -size
,
590 "Failed to inquire the new image file's length");
594 if (size
< minimum_size
) {
595 /* Need to grow the image, but we failed to do that */
596 error_propagate(errp
, local_err
);
600 error_free(local_err
);
607 * Helper function for bdrv_create_file_fallback(): Zero the first
608 * sector to remove any potentially pre-existing image header.
610 static int create_file_fallback_zero_first_sector(BlockBackend
*blk
,
611 int64_t current_size
,
614 int64_t bytes_to_clear
;
617 bytes_to_clear
= MIN(current_size
, BDRV_SECTOR_SIZE
);
618 if (bytes_to_clear
) {
619 ret
= blk_pwrite_zeroes(blk
, 0, bytes_to_clear
, BDRV_REQ_MAY_UNMAP
);
621 error_setg_errno(errp
, -ret
,
622 "Failed to clear the new image's first sector");
631 * Simple implementation of bdrv_co_create_opts for protocol drivers
632 * which only support creation via opening a file
633 * (usually existing raw storage device)
635 int coroutine_fn
bdrv_co_create_opts_simple(BlockDriver
*drv
,
636 const char *filename
,
644 PreallocMode prealloc
;
645 Error
*local_err
= NULL
;
648 size
= qemu_opt_get_size_del(opts
, BLOCK_OPT_SIZE
, 0);
649 buf
= qemu_opt_get_del(opts
, BLOCK_OPT_PREALLOC
);
650 prealloc
= qapi_enum_parse(&PreallocMode_lookup
, buf
,
651 PREALLOC_MODE_OFF
, &local_err
);
654 error_propagate(errp
, local_err
);
658 if (prealloc
!= PREALLOC_MODE_OFF
) {
659 error_setg(errp
, "Unsupported preallocation mode '%s'",
660 PreallocMode_str(prealloc
));
664 options
= qdict_new();
665 qdict_put_str(options
, "driver", drv
->format_name
);
667 blk
= blk_new_open(filename
, NULL
, options
,
668 BDRV_O_RDWR
| BDRV_O_RESIZE
, errp
);
670 error_prepend(errp
, "Protocol driver '%s' does not support image "
671 "creation, and opening the image failed: ",
676 size
= create_file_fallback_truncate(blk
, size
, errp
);
682 ret
= create_file_fallback_zero_first_sector(blk
, size
, errp
);
693 int bdrv_create_file(const char *filename
, QemuOpts
*opts
, Error
**errp
)
695 QemuOpts
*protocol_opts
;
700 drv
= bdrv_find_protocol(filename
, true, errp
);
705 if (!drv
->create_opts
) {
706 error_setg(errp
, "Driver '%s' does not support image creation",
712 * 'opts' contains a QemuOptsList with a combination of format and protocol
715 * The format properly removes its options, but the default values remain
716 * in 'opts->list'. So if the protocol has options with the same name
717 * (e.g. rbd has 'cluster_size' as qcow2), it will see the default values
718 * of the format, since for overlapping options, the format wins.
720 * To avoid this issue, lets convert QemuOpts to QDict, in this way we take
721 * only the set options, and then convert it back to QemuOpts, using the
722 * create_opts of the protocol. So the new QemuOpts, will contain only the
725 qdict
= qemu_opts_to_qdict(opts
, NULL
);
726 protocol_opts
= qemu_opts_from_qdict(drv
->create_opts
, qdict
, errp
);
727 if (protocol_opts
== NULL
) {
732 ret
= bdrv_create(drv
, filename
, protocol_opts
, errp
);
734 qemu_opts_del(protocol_opts
);
735 qobject_unref(qdict
);
739 int coroutine_fn
bdrv_co_delete_file(BlockDriverState
*bs
, Error
**errp
)
741 Error
*local_err
= NULL
;
747 error_setg(errp
, "Block node '%s' is not opened", bs
->filename
);
751 if (!bs
->drv
->bdrv_co_delete_file
) {
752 error_setg(errp
, "Driver '%s' does not support image deletion",
753 bs
->drv
->format_name
);
757 ret
= bs
->drv
->bdrv_co_delete_file(bs
, &local_err
);
759 error_propagate(errp
, local_err
);
765 void coroutine_fn
bdrv_co_delete_file_noerr(BlockDriverState
*bs
)
767 Error
*local_err
= NULL
;
774 ret
= bdrv_co_delete_file(bs
, &local_err
);
776 * ENOTSUP will happen if the block driver doesn't support
777 * the 'bdrv_co_delete_file' interface. This is a predictable
778 * scenario and shouldn't be reported back to the user.
780 if (ret
== -ENOTSUP
) {
781 error_free(local_err
);
782 } else if (ret
< 0) {
783 error_report_err(local_err
);
788 * Try to get @bs's logical and physical block size.
789 * On success, store them in @bsz struct and return 0.
790 * On failure return -errno.
791 * @bs must not be empty.
793 int bdrv_probe_blocksizes(BlockDriverState
*bs
, BlockSizes
*bsz
)
795 BlockDriver
*drv
= bs
->drv
;
796 BlockDriverState
*filtered
= bdrv_filter_bs(bs
);
798 if (drv
&& drv
->bdrv_probe_blocksizes
) {
799 return drv
->bdrv_probe_blocksizes(bs
, bsz
);
800 } else if (filtered
) {
801 return bdrv_probe_blocksizes(filtered
, bsz
);
808 * Try to get @bs's geometry (cyls, heads, sectors).
809 * On success, store them in @geo struct and return 0.
810 * On failure return -errno.
811 * @bs must not be empty.
813 int bdrv_probe_geometry(BlockDriverState
*bs
, HDGeometry
*geo
)
815 BlockDriver
*drv
= bs
->drv
;
816 BlockDriverState
*filtered
= bdrv_filter_bs(bs
);
818 if (drv
&& drv
->bdrv_probe_geometry
) {
819 return drv
->bdrv_probe_geometry(bs
, geo
);
820 } else if (filtered
) {
821 return bdrv_probe_geometry(filtered
, geo
);
828 * Create a uniquely-named empty temporary file.
829 * Return 0 upon success, otherwise a negative errno value.
831 int get_tmp_filename(char *filename
, int size
)
834 char temp_dir
[MAX_PATH
];
835 /* GetTempFileName requires that its output buffer (4th param)
836 have length MAX_PATH or greater. */
837 assert(size
>= MAX_PATH
);
838 return (GetTempPath(MAX_PATH
, temp_dir
)
839 && GetTempFileName(temp_dir
, "qem", 0, filename
)
840 ? 0 : -GetLastError());
844 tmpdir
= getenv("TMPDIR");
848 if (snprintf(filename
, size
, "%s/vl.XXXXXX", tmpdir
) >= size
) {
851 fd
= mkstemp(filename
);
855 if (close(fd
) != 0) {
864 * Detect host devices. By convention, /dev/cdrom[N] is always
865 * recognized as a host CDROM.
867 static BlockDriver
*find_hdev_driver(const char *filename
)
869 int score_max
= 0, score
;
870 BlockDriver
*drv
= NULL
, *d
;
872 QLIST_FOREACH(d
, &bdrv_drivers
, list
) {
873 if (d
->bdrv_probe_device
) {
874 score
= d
->bdrv_probe_device(filename
);
875 if (score
> score_max
) {
885 static BlockDriver
*bdrv_do_find_protocol(const char *protocol
)
889 QLIST_FOREACH(drv1
, &bdrv_drivers
, list
) {
890 if (drv1
->protocol_name
&& !strcmp(drv1
->protocol_name
, protocol
)) {
898 BlockDriver
*bdrv_find_protocol(const char *filename
,
899 bool allow_protocol_prefix
,
908 /* TODO Drivers without bdrv_file_open must be specified explicitly */
911 * XXX(hch): we really should not let host device detection
912 * override an explicit protocol specification, but moving this
913 * later breaks access to device names with colons in them.
914 * Thanks to the brain-dead persistent naming schemes on udev-
915 * based Linux systems those actually are quite common.
917 drv1
= find_hdev_driver(filename
);
922 if (!path_has_protocol(filename
) || !allow_protocol_prefix
) {
926 p
= strchr(filename
, ':');
929 if (len
> sizeof(protocol
) - 1)
930 len
= sizeof(protocol
) - 1;
931 memcpy(protocol
, filename
, len
);
932 protocol
[len
] = '\0';
934 drv1
= bdrv_do_find_protocol(protocol
);
939 for (i
= 0; i
< (int)ARRAY_SIZE(block_driver_modules
); ++i
) {
940 if (block_driver_modules
[i
].protocol_name
&&
941 !strcmp(block_driver_modules
[i
].protocol_name
, protocol
)) {
942 block_module_load_one(block_driver_modules
[i
].library_name
);
947 drv1
= bdrv_do_find_protocol(protocol
);
949 error_setg(errp
, "Unknown protocol '%s'", protocol
);
955 * Guess image format by probing its contents.
956 * This is not a good idea when your image is raw (CVE-2008-2004), but
957 * we do it anyway for backward compatibility.
959 * @buf contains the image's first @buf_size bytes.
960 * @buf_size is the buffer size in bytes (generally BLOCK_PROBE_BUF_SIZE,
961 * but can be smaller if the image file is smaller)
962 * @filename is its filename.
964 * For all block drivers, call the bdrv_probe() method to get its
966 * Return the first block driver with the highest probing score.
968 BlockDriver
*bdrv_probe_all(const uint8_t *buf
, int buf_size
,
969 const char *filename
)
971 int score_max
= 0, score
;
972 BlockDriver
*drv
= NULL
, *d
;
974 QLIST_FOREACH(d
, &bdrv_drivers
, list
) {
976 score
= d
->bdrv_probe(buf
, buf_size
, filename
);
977 if (score
> score_max
) {
987 static int find_image_format(BlockBackend
*file
, const char *filename
,
988 BlockDriver
**pdrv
, Error
**errp
)
991 uint8_t buf
[BLOCK_PROBE_BUF_SIZE
];
994 /* Return the raw BlockDriver * to scsi-generic devices or empty drives */
995 if (blk_is_sg(file
) || !blk_is_inserted(file
) || blk_getlength(file
) == 0) {
1000 ret
= blk_pread(file
, 0, buf
, sizeof(buf
));
1002 error_setg_errno(errp
, -ret
, "Could not read image for determining its "
1008 drv
= bdrv_probe_all(buf
, ret
, filename
);
1010 error_setg(errp
, "Could not determine image format: No compatible "
1019 * Set the current 'total_sectors' value
1020 * Return 0 on success, -errno on error.
1022 int refresh_total_sectors(BlockDriverState
*bs
, int64_t hint
)
1024 BlockDriver
*drv
= bs
->drv
;
1030 /* Do not attempt drv->bdrv_getlength() on scsi-generic devices */
1034 /* query actual device if possible, otherwise just trust the hint */
1035 if (drv
->bdrv_getlength
) {
1036 int64_t length
= drv
->bdrv_getlength(bs
);
1040 hint
= DIV_ROUND_UP(length
, BDRV_SECTOR_SIZE
);
1043 bs
->total_sectors
= hint
;
1045 if (bs
->total_sectors
* BDRV_SECTOR_SIZE
> BDRV_MAX_LENGTH
) {
1053 * Combines a QDict of new block driver @options with any missing options taken
1054 * from @old_options, so that leaving out an option defaults to its old value.
1056 static void bdrv_join_options(BlockDriverState
*bs
, QDict
*options
,
1059 if (bs
->drv
&& bs
->drv
->bdrv_join_options
) {
1060 bs
->drv
->bdrv_join_options(options
, old_options
);
1062 qdict_join(options
, old_options
, false);
1066 static BlockdevDetectZeroesOptions
bdrv_parse_detect_zeroes(QemuOpts
*opts
,
1070 Error
*local_err
= NULL
;
1071 char *value
= qemu_opt_get_del(opts
, "detect-zeroes");
1072 BlockdevDetectZeroesOptions detect_zeroes
=
1073 qapi_enum_parse(&BlockdevDetectZeroesOptions_lookup
, value
,
1074 BLOCKDEV_DETECT_ZEROES_OPTIONS_OFF
, &local_err
);
1077 error_propagate(errp
, local_err
);
1078 return detect_zeroes
;
1081 if (detect_zeroes
== BLOCKDEV_DETECT_ZEROES_OPTIONS_UNMAP
&&
1082 !(open_flags
& BDRV_O_UNMAP
))
1084 error_setg(errp
, "setting detect-zeroes to unmap is not allowed "
1085 "without setting discard operation to unmap");
1088 return detect_zeroes
;
1092 * Set open flags for aio engine
1094 * Return 0 on success, -1 if the engine specified is invalid
1096 int bdrv_parse_aio(const char *mode
, int *flags
)
1098 if (!strcmp(mode
, "threads")) {
1099 /* do nothing, default */
1100 } else if (!strcmp(mode
, "native")) {
1101 *flags
|= BDRV_O_NATIVE_AIO
;
1102 #ifdef CONFIG_LINUX_IO_URING
1103 } else if (!strcmp(mode
, "io_uring")) {
1104 *flags
|= BDRV_O_IO_URING
;
1114 * Set open flags for a given discard mode
1116 * Return 0 on success, -1 if the discard mode was invalid.
1118 int bdrv_parse_discard_flags(const char *mode
, int *flags
)
1120 *flags
&= ~BDRV_O_UNMAP
;
1122 if (!strcmp(mode
, "off") || !strcmp(mode
, "ignore")) {
1124 } else if (!strcmp(mode
, "on") || !strcmp(mode
, "unmap")) {
1125 *flags
|= BDRV_O_UNMAP
;
1134 * Set open flags for a given cache mode
1136 * Return 0 on success, -1 if the cache mode was invalid.
1138 int bdrv_parse_cache_mode(const char *mode
, int *flags
, bool *writethrough
)
1140 *flags
&= ~BDRV_O_CACHE_MASK
;
1142 if (!strcmp(mode
, "off") || !strcmp(mode
, "none")) {
1143 *writethrough
= false;
1144 *flags
|= BDRV_O_NOCACHE
;
1145 } else if (!strcmp(mode
, "directsync")) {
1146 *writethrough
= true;
1147 *flags
|= BDRV_O_NOCACHE
;
1148 } else if (!strcmp(mode
, "writeback")) {
1149 *writethrough
= false;
1150 } else if (!strcmp(mode
, "unsafe")) {
1151 *writethrough
= false;
1152 *flags
|= BDRV_O_NO_FLUSH
;
1153 } else if (!strcmp(mode
, "writethrough")) {
1154 *writethrough
= true;
1162 static char *bdrv_child_get_parent_desc(BdrvChild
*c
)
1164 BlockDriverState
*parent
= c
->opaque
;
1165 return g_strdup_printf("node '%s'", bdrv_get_node_name(parent
));
1168 static void bdrv_child_cb_drained_begin(BdrvChild
*child
)
1170 BlockDriverState
*bs
= child
->opaque
;
1171 bdrv_do_drained_begin_quiesce(bs
, NULL
, false);
1174 static bool bdrv_child_cb_drained_poll(BdrvChild
*child
)
1176 BlockDriverState
*bs
= child
->opaque
;
1177 return bdrv_drain_poll(bs
, false, NULL
, false);
1180 static void bdrv_child_cb_drained_end(BdrvChild
*child
,
1181 int *drained_end_counter
)
1183 BlockDriverState
*bs
= child
->opaque
;
1184 bdrv_drained_end_no_poll(bs
, drained_end_counter
);
1187 static int bdrv_child_cb_inactivate(BdrvChild
*child
)
1189 BlockDriverState
*bs
= child
->opaque
;
1190 assert(bs
->open_flags
& BDRV_O_INACTIVE
);
1194 static bool bdrv_child_cb_can_set_aio_ctx(BdrvChild
*child
, AioContext
*ctx
,
1195 GSList
**ignore
, Error
**errp
)
1197 BlockDriverState
*bs
= child
->opaque
;
1198 return bdrv_can_set_aio_context(bs
, ctx
, ignore
, errp
);
1201 static void bdrv_child_cb_set_aio_ctx(BdrvChild
*child
, AioContext
*ctx
,
1204 BlockDriverState
*bs
= child
->opaque
;
1205 return bdrv_set_aio_context_ignore(bs
, ctx
, ignore
);
1209 * Returns the options and flags that a temporary snapshot should get, based on
1210 * the originally requested flags (the originally requested image will have
1211 * flags like a backing file)
1213 static void bdrv_temp_snapshot_options(int *child_flags
, QDict
*child_options
,
1214 int parent_flags
, QDict
*parent_options
)
1216 *child_flags
= (parent_flags
& ~BDRV_O_SNAPSHOT
) | BDRV_O_TEMPORARY
;
1218 /* For temporary files, unconditional cache=unsafe is fine */
1219 qdict_set_default_str(child_options
, BDRV_OPT_CACHE_DIRECT
, "off");
1220 qdict_set_default_str(child_options
, BDRV_OPT_CACHE_NO_FLUSH
, "on");
1222 /* Copy the read-only and discard options from the parent */
1223 qdict_copy_default(child_options
, parent_options
, BDRV_OPT_READ_ONLY
);
1224 qdict_copy_default(child_options
, parent_options
, BDRV_OPT_DISCARD
);
1226 /* aio=native doesn't work for cache.direct=off, so disable it for the
1227 * temporary snapshot */
1228 *child_flags
&= ~BDRV_O_NATIVE_AIO
;
1231 static void bdrv_backing_attach(BdrvChild
*c
)
1233 BlockDriverState
*parent
= c
->opaque
;
1234 BlockDriverState
*backing_hd
= c
->bs
;
1236 assert(!parent
->backing_blocker
);
1237 error_setg(&parent
->backing_blocker
,
1238 "node is used as backing hd of '%s'",
1239 bdrv_get_device_or_node_name(parent
));
1241 bdrv_refresh_filename(backing_hd
);
1243 parent
->open_flags
&= ~BDRV_O_NO_BACKING
;
1245 bdrv_op_block_all(backing_hd
, parent
->backing_blocker
);
1246 /* Otherwise we won't be able to commit or stream */
1247 bdrv_op_unblock(backing_hd
, BLOCK_OP_TYPE_COMMIT_TARGET
,
1248 parent
->backing_blocker
);
1249 bdrv_op_unblock(backing_hd
, BLOCK_OP_TYPE_STREAM
,
1250 parent
->backing_blocker
);
1252 * We do backup in 3 ways:
1254 * The target bs is new opened, and the source is top BDS
1255 * 2. blockdev backup
1256 * Both the source and the target are top BDSes.
1257 * 3. internal backup(used for block replication)
1258 * Both the source and the target are backing file
1260 * In case 1 and 2, neither the source nor the target is the backing file.
1261 * In case 3, we will block the top BDS, so there is only one block job
1262 * for the top BDS and its backing chain.
1264 bdrv_op_unblock(backing_hd
, BLOCK_OP_TYPE_BACKUP_SOURCE
,
1265 parent
->backing_blocker
);
1266 bdrv_op_unblock(backing_hd
, BLOCK_OP_TYPE_BACKUP_TARGET
,
1267 parent
->backing_blocker
);
1270 static void bdrv_backing_detach(BdrvChild
*c
)
1272 BlockDriverState
*parent
= c
->opaque
;
1274 assert(parent
->backing_blocker
);
1275 bdrv_op_unblock_all(c
->bs
, parent
->backing_blocker
);
1276 error_free(parent
->backing_blocker
);
1277 parent
->backing_blocker
= NULL
;
1280 static int bdrv_backing_update_filename(BdrvChild
*c
, BlockDriverState
*base
,
1281 const char *filename
, Error
**errp
)
1283 BlockDriverState
*parent
= c
->opaque
;
1284 bool read_only
= bdrv_is_read_only(parent
);
1288 ret
= bdrv_reopen_set_read_only(parent
, false, errp
);
1294 ret
= bdrv_change_backing_file(parent
, filename
,
1295 base
->drv
? base
->drv
->format_name
: "",
1298 error_setg_errno(errp
, -ret
, "Could not update backing file link");
1302 bdrv_reopen_set_read_only(parent
, true, NULL
);
1309 * Returns the options and flags that a generic child of a BDS should
1310 * get, based on the given options and flags for the parent BDS.
1312 static void bdrv_inherited_options(BdrvChildRole role
, bool parent_is_format
,
1313 int *child_flags
, QDict
*child_options
,
1314 int parent_flags
, QDict
*parent_options
)
1316 int flags
= parent_flags
;
1319 * First, decide whether to set, clear, or leave BDRV_O_PROTOCOL.
1320 * Generally, the question to answer is: Should this child be
1321 * format-probed by default?
1325 * Pure and non-filtered data children of non-format nodes should
1326 * be probed by default (even when the node itself has BDRV_O_PROTOCOL
1327 * set). This only affects a very limited set of drivers (namely
1328 * quorum and blkverify when this comment was written).
1329 * Force-clear BDRV_O_PROTOCOL then.
1331 if (!parent_is_format
&&
1332 (role
& BDRV_CHILD_DATA
) &&
1333 !(role
& (BDRV_CHILD_METADATA
| BDRV_CHILD_FILTERED
)))
1335 flags
&= ~BDRV_O_PROTOCOL
;
1339 * All children of format nodes (except for COW children) and all
1340 * metadata children in general should never be format-probed.
1341 * Force-set BDRV_O_PROTOCOL then.
1343 if ((parent_is_format
&& !(role
& BDRV_CHILD_COW
)) ||
1344 (role
& BDRV_CHILD_METADATA
))
1346 flags
|= BDRV_O_PROTOCOL
;
1350 * If the cache mode isn't explicitly set, inherit direct and no-flush from
1353 qdict_copy_default(child_options
, parent_options
, BDRV_OPT_CACHE_DIRECT
);
1354 qdict_copy_default(child_options
, parent_options
, BDRV_OPT_CACHE_NO_FLUSH
);
1355 qdict_copy_default(child_options
, parent_options
, BDRV_OPT_FORCE_SHARE
);
1357 if (role
& BDRV_CHILD_COW
) {
1358 /* backing files are opened read-only by default */
1359 qdict_set_default_str(child_options
, BDRV_OPT_READ_ONLY
, "on");
1360 qdict_set_default_str(child_options
, BDRV_OPT_AUTO_READ_ONLY
, "off");
1362 /* Inherit the read-only option from the parent if it's not set */
1363 qdict_copy_default(child_options
, parent_options
, BDRV_OPT_READ_ONLY
);
1364 qdict_copy_default(child_options
, parent_options
,
1365 BDRV_OPT_AUTO_READ_ONLY
);
1369 * bdrv_co_pdiscard() respects unmap policy for the parent, so we
1370 * can default to enable it on lower layers regardless of the
1373 qdict_set_default_str(child_options
, BDRV_OPT_DISCARD
, "unmap");
1375 /* Clear flags that only apply to the top layer */
1376 flags
&= ~(BDRV_O_SNAPSHOT
| BDRV_O_NO_BACKING
| BDRV_O_COPY_ON_READ
);
1378 if (role
& BDRV_CHILD_METADATA
) {
1379 flags
&= ~BDRV_O_NO_IO
;
1381 if (role
& BDRV_CHILD_COW
) {
1382 flags
&= ~BDRV_O_TEMPORARY
;
1385 *child_flags
= flags
;
1388 static void bdrv_child_cb_attach(BdrvChild
*child
)
1390 BlockDriverState
*bs
= child
->opaque
;
1392 QLIST_INSERT_HEAD(&bs
->children
, child
, next
);
1394 if (child
->role
& BDRV_CHILD_COW
) {
1395 bdrv_backing_attach(child
);
1398 bdrv_apply_subtree_drain(child
, bs
);
1401 static void bdrv_child_cb_detach(BdrvChild
*child
)
1403 BlockDriverState
*bs
= child
->opaque
;
1405 if (child
->role
& BDRV_CHILD_COW
) {
1406 bdrv_backing_detach(child
);
1409 bdrv_unapply_subtree_drain(child
, bs
);
1411 QLIST_REMOVE(child
, next
);
1414 static int bdrv_child_cb_update_filename(BdrvChild
*c
, BlockDriverState
*base
,
1415 const char *filename
, Error
**errp
)
1417 if (c
->role
& BDRV_CHILD_COW
) {
1418 return bdrv_backing_update_filename(c
, base
, filename
, errp
);
1423 AioContext
*child_of_bds_get_parent_aio_context(BdrvChild
*c
)
1425 BlockDriverState
*bs
= c
->opaque
;
1427 return bdrv_get_aio_context(bs
);
1430 const BdrvChildClass child_of_bds
= {
1431 .parent_is_bds
= true,
1432 .get_parent_desc
= bdrv_child_get_parent_desc
,
1433 .inherit_options
= bdrv_inherited_options
,
1434 .drained_begin
= bdrv_child_cb_drained_begin
,
1435 .drained_poll
= bdrv_child_cb_drained_poll
,
1436 .drained_end
= bdrv_child_cb_drained_end
,
1437 .attach
= bdrv_child_cb_attach
,
1438 .detach
= bdrv_child_cb_detach
,
1439 .inactivate
= bdrv_child_cb_inactivate
,
1440 .can_set_aio_ctx
= bdrv_child_cb_can_set_aio_ctx
,
1441 .set_aio_ctx
= bdrv_child_cb_set_aio_ctx
,
1442 .update_filename
= bdrv_child_cb_update_filename
,
1443 .get_parent_aio_context
= child_of_bds_get_parent_aio_context
,
1446 AioContext
*bdrv_child_get_parent_aio_context(BdrvChild
*c
)
1448 return c
->klass
->get_parent_aio_context(c
);
1451 static int bdrv_open_flags(BlockDriverState
*bs
, int flags
)
1453 int open_flags
= flags
;
1456 * Clear flags that are internal to the block layer before opening the
1459 open_flags
&= ~(BDRV_O_SNAPSHOT
| BDRV_O_NO_BACKING
| BDRV_O_PROTOCOL
);
1464 static void update_flags_from_options(int *flags
, QemuOpts
*opts
)
1466 *flags
&= ~(BDRV_O_CACHE_MASK
| BDRV_O_RDWR
| BDRV_O_AUTO_RDONLY
);
1468 if (qemu_opt_get_bool_del(opts
, BDRV_OPT_CACHE_NO_FLUSH
, false)) {
1469 *flags
|= BDRV_O_NO_FLUSH
;
1472 if (qemu_opt_get_bool_del(opts
, BDRV_OPT_CACHE_DIRECT
, false)) {
1473 *flags
|= BDRV_O_NOCACHE
;
1476 if (!qemu_opt_get_bool_del(opts
, BDRV_OPT_READ_ONLY
, false)) {
1477 *flags
|= BDRV_O_RDWR
;
1480 if (qemu_opt_get_bool_del(opts
, BDRV_OPT_AUTO_READ_ONLY
, false)) {
1481 *flags
|= BDRV_O_AUTO_RDONLY
;
1485 static void update_options_from_flags(QDict
*options
, int flags
)
1487 if (!qdict_haskey(options
, BDRV_OPT_CACHE_DIRECT
)) {
1488 qdict_put_bool(options
, BDRV_OPT_CACHE_DIRECT
, flags
& BDRV_O_NOCACHE
);
1490 if (!qdict_haskey(options
, BDRV_OPT_CACHE_NO_FLUSH
)) {
1491 qdict_put_bool(options
, BDRV_OPT_CACHE_NO_FLUSH
,
1492 flags
& BDRV_O_NO_FLUSH
);
1494 if (!qdict_haskey(options
, BDRV_OPT_READ_ONLY
)) {
1495 qdict_put_bool(options
, BDRV_OPT_READ_ONLY
, !(flags
& BDRV_O_RDWR
));
1497 if (!qdict_haskey(options
, BDRV_OPT_AUTO_READ_ONLY
)) {
1498 qdict_put_bool(options
, BDRV_OPT_AUTO_READ_ONLY
,
1499 flags
& BDRV_O_AUTO_RDONLY
);
1503 static void bdrv_assign_node_name(BlockDriverState
*bs
,
1504 const char *node_name
,
1507 char *gen_node_name
= NULL
;
1510 node_name
= gen_node_name
= id_generate(ID_BLOCK
);
1511 } else if (!id_wellformed(node_name
)) {
1513 * Check for empty string or invalid characters, but not if it is
1514 * generated (generated names use characters not available to the user)
1516 error_setg(errp
, "Invalid node-name: '%s'", node_name
);
1520 /* takes care of avoiding namespaces collisions */
1521 if (blk_by_name(node_name
)) {
1522 error_setg(errp
, "node-name=%s is conflicting with a device id",
1527 /* takes care of avoiding duplicates node names */
1528 if (bdrv_find_node(node_name
)) {
1529 error_setg(errp
, "Duplicate nodes with node-name='%s'", node_name
);
1533 /* Make sure that the node name isn't truncated */
1534 if (strlen(node_name
) >= sizeof(bs
->node_name
)) {
1535 error_setg(errp
, "Node name too long");
1539 /* copy node name into the bs and insert it into the graph list */
1540 pstrcpy(bs
->node_name
, sizeof(bs
->node_name
), node_name
);
1541 QTAILQ_INSERT_TAIL(&graph_bdrv_states
, bs
, node_list
);
1543 g_free(gen_node_name
);
1546 static int bdrv_open_driver(BlockDriverState
*bs
, BlockDriver
*drv
,
1547 const char *node_name
, QDict
*options
,
1548 int open_flags
, Error
**errp
)
1550 Error
*local_err
= NULL
;
1553 bdrv_assign_node_name(bs
, node_name
, &local_err
);
1555 error_propagate(errp
, local_err
);
1560 bs
->opaque
= g_malloc0(drv
->instance_size
);
1562 if (drv
->bdrv_file_open
) {
1563 assert(!drv
->bdrv_needs_filename
|| bs
->filename
[0]);
1564 ret
= drv
->bdrv_file_open(bs
, options
, open_flags
, &local_err
);
1565 } else if (drv
->bdrv_open
) {
1566 ret
= drv
->bdrv_open(bs
, options
, open_flags
, &local_err
);
1573 error_propagate(errp
, local_err
);
1574 } else if (bs
->filename
[0]) {
1575 error_setg_errno(errp
, -ret
, "Could not open '%s'", bs
->filename
);
1577 error_setg_errno(errp
, -ret
, "Could not open image");
1582 ret
= refresh_total_sectors(bs
, bs
->total_sectors
);
1584 error_setg_errno(errp
, -ret
, "Could not refresh total sector count");
1588 bdrv_refresh_limits(bs
, NULL
, &local_err
);
1590 error_propagate(errp
, local_err
);
1594 assert(bdrv_opt_mem_align(bs
) != 0);
1595 assert(bdrv_min_mem_align(bs
) != 0);
1596 assert(is_power_of_2(bs
->bl
.request_alignment
));
1598 for (i
= 0; i
< bs
->quiesce_counter
; i
++) {
1599 if (drv
->bdrv_co_drain_begin
) {
1600 drv
->bdrv_co_drain_begin(bs
);
1607 if (bs
->file
!= NULL
) {
1608 bdrv_unref_child(bs
, bs
->file
);
1617 * Create and open a block node.
1619 * @options is a QDict of options to pass to the block drivers, or NULL for an
1620 * empty set of options. The reference to the QDict belongs to the block layer
1621 * after the call (even on failure), so if the caller intends to reuse the
1622 * dictionary, it needs to use qobject_ref() before calling bdrv_open.
1624 BlockDriverState
*bdrv_new_open_driver_opts(BlockDriver
*drv
,
1625 const char *node_name
,
1626 QDict
*options
, int flags
,
1629 BlockDriverState
*bs
;
1633 bs
->open_flags
= flags
;
1634 bs
->options
= options
?: qdict_new();
1635 bs
->explicit_options
= qdict_clone_shallow(bs
->options
);
1638 update_options_from_flags(bs
->options
, flags
);
1640 ret
= bdrv_open_driver(bs
, drv
, node_name
, bs
->options
, flags
, errp
);
1642 qobject_unref(bs
->explicit_options
);
1643 bs
->explicit_options
= NULL
;
1644 qobject_unref(bs
->options
);
1653 /* Create and open a block node. */
1654 BlockDriverState
*bdrv_new_open_driver(BlockDriver
*drv
, const char *node_name
,
1655 int flags
, Error
**errp
)
1657 return bdrv_new_open_driver_opts(drv
, node_name
, NULL
, flags
, errp
);
1660 QemuOptsList bdrv_runtime_opts
= {
1661 .name
= "bdrv_common",
1662 .head
= QTAILQ_HEAD_INITIALIZER(bdrv_runtime_opts
.head
),
1665 .name
= "node-name",
1666 .type
= QEMU_OPT_STRING
,
1667 .help
= "Node name of the block device node",
1671 .type
= QEMU_OPT_STRING
,
1672 .help
= "Block driver to use for the node",
1675 .name
= BDRV_OPT_CACHE_DIRECT
,
1676 .type
= QEMU_OPT_BOOL
,
1677 .help
= "Bypass software writeback cache on the host",
1680 .name
= BDRV_OPT_CACHE_NO_FLUSH
,
1681 .type
= QEMU_OPT_BOOL
,
1682 .help
= "Ignore flush requests",
1685 .name
= BDRV_OPT_READ_ONLY
,
1686 .type
= QEMU_OPT_BOOL
,
1687 .help
= "Node is opened in read-only mode",
1690 .name
= BDRV_OPT_AUTO_READ_ONLY
,
1691 .type
= QEMU_OPT_BOOL
,
1692 .help
= "Node can become read-only if opening read-write fails",
1695 .name
= "detect-zeroes",
1696 .type
= QEMU_OPT_STRING
,
1697 .help
= "try to optimize zero writes (off, on, unmap)",
1700 .name
= BDRV_OPT_DISCARD
,
1701 .type
= QEMU_OPT_STRING
,
1702 .help
= "discard operation (ignore/off, unmap/on)",
1705 .name
= BDRV_OPT_FORCE_SHARE
,
1706 .type
= QEMU_OPT_BOOL
,
1707 .help
= "always accept other writers (default: off)",
1709 { /* end of list */ }
1713 QemuOptsList bdrv_create_opts_simple
= {
1714 .name
= "simple-create-opts",
1715 .head
= QTAILQ_HEAD_INITIALIZER(bdrv_create_opts_simple
.head
),
1718 .name
= BLOCK_OPT_SIZE
,
1719 .type
= QEMU_OPT_SIZE
,
1720 .help
= "Virtual disk size"
1723 .name
= BLOCK_OPT_PREALLOC
,
1724 .type
= QEMU_OPT_STRING
,
1725 .help
= "Preallocation mode (allowed values: off)"
1727 { /* end of list */ }
1732 * Common part for opening disk images and files
1734 * Removes all processed options from *options.
1736 static int bdrv_open_common(BlockDriverState
*bs
, BlockBackend
*file
,
1737 QDict
*options
, Error
**errp
)
1739 int ret
, open_flags
;
1740 const char *filename
;
1741 const char *driver_name
= NULL
;
1742 const char *node_name
= NULL
;
1743 const char *discard
;
1746 Error
*local_err
= NULL
;
1749 assert(bs
->file
== NULL
);
1750 assert(options
!= NULL
&& bs
->options
!= options
);
1752 opts
= qemu_opts_create(&bdrv_runtime_opts
, NULL
, 0, &error_abort
);
1753 if (!qemu_opts_absorb_qdict(opts
, options
, errp
)) {
1758 update_flags_from_options(&bs
->open_flags
, opts
);
1760 driver_name
= qemu_opt_get(opts
, "driver");
1761 drv
= bdrv_find_format(driver_name
);
1762 assert(drv
!= NULL
);
1764 bs
->force_share
= qemu_opt_get_bool(opts
, BDRV_OPT_FORCE_SHARE
, false);
1766 if (bs
->force_share
&& (bs
->open_flags
& BDRV_O_RDWR
)) {
1768 BDRV_OPT_FORCE_SHARE
1769 "=on can only be used with read-only images");
1775 bdrv_refresh_filename(blk_bs(file
));
1776 filename
= blk_bs(file
)->filename
;
1779 * Caution: while qdict_get_try_str() is fine, getting
1780 * non-string types would require more care. When @options
1781 * come from -blockdev or blockdev_add, its members are typed
1782 * according to the QAPI schema, but when they come from
1783 * -drive, they're all QString.
1785 filename
= qdict_get_try_str(options
, "filename");
1788 if (drv
->bdrv_needs_filename
&& (!filename
|| !filename
[0])) {
1789 error_setg(errp
, "The '%s' block driver requires a file name",
1795 trace_bdrv_open_common(bs
, filename
?: "", bs
->open_flags
,
1798 ro
= bdrv_is_read_only(bs
);
1800 if (use_bdrv_whitelist
&& !bdrv_is_whitelisted(drv
, ro
)) {
1801 if (!ro
&& bdrv_is_whitelisted(drv
, true)) {
1802 ret
= bdrv_apply_auto_read_only(bs
, NULL
, NULL
);
1808 !ro
&& bdrv_is_whitelisted(drv
, true)
1809 ? "Driver '%s' can only be used for read-only devices"
1810 : "Driver '%s' is not whitelisted",
1816 /* bdrv_new() and bdrv_close() make it so */
1817 assert(qatomic_read(&bs
->copy_on_read
) == 0);
1819 if (bs
->open_flags
& BDRV_O_COPY_ON_READ
) {
1821 bdrv_enable_copy_on_read(bs
);
1823 error_setg(errp
, "Can't use copy-on-read on read-only device");
1829 discard
= qemu_opt_get(opts
, BDRV_OPT_DISCARD
);
1830 if (discard
!= NULL
) {
1831 if (bdrv_parse_discard_flags(discard
, &bs
->open_flags
) != 0) {
1832 error_setg(errp
, "Invalid discard option");
1839 bdrv_parse_detect_zeroes(opts
, bs
->open_flags
, &local_err
);
1841 error_propagate(errp
, local_err
);
1846 if (filename
!= NULL
) {
1847 pstrcpy(bs
->filename
, sizeof(bs
->filename
), filename
);
1849 bs
->filename
[0] = '\0';
1851 pstrcpy(bs
->exact_filename
, sizeof(bs
->exact_filename
), bs
->filename
);
1853 /* Open the image, either directly or using a protocol */
1854 open_flags
= bdrv_open_flags(bs
, bs
->open_flags
);
1855 node_name
= qemu_opt_get(opts
, "node-name");
1857 assert(!drv
->bdrv_file_open
|| file
== NULL
);
1858 ret
= bdrv_open_driver(bs
, drv
, node_name
, options
, open_flags
, errp
);
1863 qemu_opts_del(opts
);
1867 qemu_opts_del(opts
);
1871 static QDict
*parse_json_filename(const char *filename
, Error
**errp
)
1873 QObject
*options_obj
;
1877 ret
= strstart(filename
, "json:", &filename
);
1880 options_obj
= qobject_from_json(filename
, errp
);
1882 error_prepend(errp
, "Could not parse the JSON options: ");
1886 options
= qobject_to(QDict
, options_obj
);
1888 qobject_unref(options_obj
);
1889 error_setg(errp
, "Invalid JSON object given");
1893 qdict_flatten(options
);
1898 static void parse_json_protocol(QDict
*options
, const char **pfilename
,
1901 QDict
*json_options
;
1902 Error
*local_err
= NULL
;
1904 /* Parse json: pseudo-protocol */
1905 if (!*pfilename
|| !g_str_has_prefix(*pfilename
, "json:")) {
1909 json_options
= parse_json_filename(*pfilename
, &local_err
);
1911 error_propagate(errp
, local_err
);
1915 /* Options given in the filename have lower priority than options
1916 * specified directly */
1917 qdict_join(options
, json_options
, false);
1918 qobject_unref(json_options
);
1923 * Fills in default options for opening images and converts the legacy
1924 * filename/flags pair to option QDict entries.
1925 * The BDRV_O_PROTOCOL flag in *flags will be set or cleared accordingly if a
1926 * block driver has been specified explicitly.
1928 static int bdrv_fill_options(QDict
**options
, const char *filename
,
1929 int *flags
, Error
**errp
)
1931 const char *drvname
;
1932 bool protocol
= *flags
& BDRV_O_PROTOCOL
;
1933 bool parse_filename
= false;
1934 BlockDriver
*drv
= NULL
;
1935 Error
*local_err
= NULL
;
1938 * Caution: while qdict_get_try_str() is fine, getting non-string
1939 * types would require more care. When @options come from
1940 * -blockdev or blockdev_add, its members are typed according to
1941 * the QAPI schema, but when they come from -drive, they're all
1944 drvname
= qdict_get_try_str(*options
, "driver");
1946 drv
= bdrv_find_format(drvname
);
1948 error_setg(errp
, "Unknown driver '%s'", drvname
);
1951 /* If the user has explicitly specified the driver, this choice should
1952 * override the BDRV_O_PROTOCOL flag */
1953 protocol
= drv
->bdrv_file_open
;
1957 *flags
|= BDRV_O_PROTOCOL
;
1959 *flags
&= ~BDRV_O_PROTOCOL
;
1962 /* Translate cache options from flags into options */
1963 update_options_from_flags(*options
, *flags
);
1965 /* Fetch the file name from the options QDict if necessary */
1966 if (protocol
&& filename
) {
1967 if (!qdict_haskey(*options
, "filename")) {
1968 qdict_put_str(*options
, "filename", filename
);
1969 parse_filename
= true;
1971 error_setg(errp
, "Can't specify 'file' and 'filename' options at "
1977 /* Find the right block driver */
1978 /* See cautionary note on accessing @options above */
1979 filename
= qdict_get_try_str(*options
, "filename");
1981 if (!drvname
&& protocol
) {
1983 drv
= bdrv_find_protocol(filename
, parse_filename
, errp
);
1988 drvname
= drv
->format_name
;
1989 qdict_put_str(*options
, "driver", drvname
);
1991 error_setg(errp
, "Must specify either driver or file");
1996 assert(drv
|| !protocol
);
1998 /* Driver-specific filename parsing */
1999 if (drv
&& drv
->bdrv_parse_filename
&& parse_filename
) {
2000 drv
->bdrv_parse_filename(filename
, *options
, &local_err
);
2002 error_propagate(errp
, local_err
);
2006 if (!drv
->bdrv_needs_filename
) {
2007 qdict_del(*options
, "filename");
2014 typedef struct BlockReopenQueueEntry
{
2017 BDRVReopenState state
;
2018 QTAILQ_ENTRY(BlockReopenQueueEntry
) entry
;
2019 } BlockReopenQueueEntry
;
2022 * Return the flags that @bs will have after the reopens in @q have
2023 * successfully completed. If @q is NULL (or @bs is not contained in @q),
2024 * return the current flags.
2026 static int bdrv_reopen_get_flags(BlockReopenQueue
*q
, BlockDriverState
*bs
)
2028 BlockReopenQueueEntry
*entry
;
2031 QTAILQ_FOREACH(entry
, q
, entry
) {
2032 if (entry
->state
.bs
== bs
) {
2033 return entry
->state
.flags
;
2038 return bs
->open_flags
;
2041 /* Returns whether the image file can be written to after the reopen queue @q
2042 * has been successfully applied, or right now if @q is NULL. */
2043 static bool bdrv_is_writable_after_reopen(BlockDriverState
*bs
,
2044 BlockReopenQueue
*q
)
2046 int flags
= bdrv_reopen_get_flags(q
, bs
);
2048 return (flags
& (BDRV_O_RDWR
| BDRV_O_INACTIVE
)) == BDRV_O_RDWR
;
2052 * Return whether the BDS can be written to. This is not necessarily
2053 * the same as !bdrv_is_read_only(bs), as inactivated images may not
2054 * be written to but do not count as read-only images.
2056 bool bdrv_is_writable(BlockDriverState
*bs
)
2058 return bdrv_is_writable_after_reopen(bs
, NULL
);
2061 static char *bdrv_child_user_desc(BdrvChild
*c
)
2063 return c
->klass
->get_parent_desc(c
);
2067 * Check that @a allows everything that @b needs. @a and @b must reference same
2070 static bool bdrv_a_allow_b(BdrvChild
*a
, BdrvChild
*b
, Error
**errp
)
2072 const char *child_bs_name
;
2073 g_autofree
char *a_user
= NULL
;
2074 g_autofree
char *b_user
= NULL
;
2075 g_autofree
char *perms
= NULL
;
2078 assert(a
->bs
== b
->bs
);
2080 if ((b
->perm
& a
->shared_perm
) == b
->perm
) {
2084 child_bs_name
= bdrv_get_node_name(b
->bs
);
2085 a_user
= bdrv_child_user_desc(a
);
2086 b_user
= bdrv_child_user_desc(b
);
2087 perms
= bdrv_perm_names(b
->perm
& ~a
->shared_perm
);
2089 error_setg(errp
, "Permission conflict on node '%s': permissions '%s' are "
2090 "both required by %s (uses node '%s' as '%s' child) and "
2091 "unshared by %s (uses node '%s' as '%s' child).",
2092 child_bs_name
, perms
,
2093 b_user
, child_bs_name
, b
->name
,
2094 a_user
, child_bs_name
, a
->name
);
2099 static bool bdrv_parent_perms_conflict(BlockDriverState
*bs
, Error
**errp
)
2104 * During the loop we'll look at each pair twice. That's correct because
2105 * bdrv_a_allow_b() is asymmetric and we should check each pair in both
2108 QLIST_FOREACH(a
, &bs
->parents
, next_parent
) {
2109 QLIST_FOREACH(b
, &bs
->parents
, next_parent
) {
2114 if (!bdrv_a_allow_b(a
, b
, errp
)) {
2123 static void bdrv_child_perm(BlockDriverState
*bs
, BlockDriverState
*child_bs
,
2124 BdrvChild
*c
, BdrvChildRole role
,
2125 BlockReopenQueue
*reopen_queue
,
2126 uint64_t parent_perm
, uint64_t parent_shared
,
2127 uint64_t *nperm
, uint64_t *nshared
)
2129 assert(bs
->drv
&& bs
->drv
->bdrv_child_perm
);
2130 bs
->drv
->bdrv_child_perm(bs
, c
, role
, reopen_queue
,
2131 parent_perm
, parent_shared
,
2133 /* TODO Take force_share from reopen_queue */
2134 if (child_bs
&& child_bs
->force_share
) {
2135 *nshared
= BLK_PERM_ALL
;
2140 * Adds the whole subtree of @bs (including @bs itself) to the @list (except for
2141 * nodes that are already in the @list, of course) so that final list is
2142 * topologically sorted. Return the result (GSList @list object is updated, so
2143 * don't use old reference after function call).
2145 * On function start @list must be already topologically sorted and for any node
2146 * in the @list the whole subtree of the node must be in the @list as well. The
2147 * simplest way to satisfy this criteria: use only result of
2148 * bdrv_topological_dfs() or NULL as @list parameter.
2150 static GSList
*bdrv_topological_dfs(GSList
*list
, GHashTable
*found
,
2151 BlockDriverState
*bs
)
2154 g_autoptr(GHashTable
) local_found
= NULL
;
2158 found
= local_found
= g_hash_table_new(NULL
, NULL
);
2161 if (g_hash_table_contains(found
, bs
)) {
2164 g_hash_table_add(found
, bs
);
2166 QLIST_FOREACH(child
, &bs
->children
, next
) {
2167 list
= bdrv_topological_dfs(list
, found
, child
->bs
);
2170 return g_slist_prepend(list
, bs
);
2173 typedef struct BdrvChildSetPermState
{
2176 uint64_t old_shared_perm
;
2177 } BdrvChildSetPermState
;
2179 static void bdrv_child_set_perm_abort(void *opaque
)
2181 BdrvChildSetPermState
*s
= opaque
;
2183 s
->child
->perm
= s
->old_perm
;
2184 s
->child
->shared_perm
= s
->old_shared_perm
;
2187 static TransactionActionDrv bdrv_child_set_pem_drv
= {
2188 .abort
= bdrv_child_set_perm_abort
,
2192 static void bdrv_child_set_perm(BdrvChild
*c
, uint64_t perm
,
2193 uint64_t shared
, Transaction
*tran
)
2195 BdrvChildSetPermState
*s
= g_new(BdrvChildSetPermState
, 1);
2197 *s
= (BdrvChildSetPermState
) {
2199 .old_perm
= c
->perm
,
2200 .old_shared_perm
= c
->shared_perm
,
2204 c
->shared_perm
= shared
;
2206 tran_add(tran
, &bdrv_child_set_pem_drv
, s
);
2209 static void bdrv_drv_set_perm_commit(void *opaque
)
2211 BlockDriverState
*bs
= opaque
;
2212 uint64_t cumulative_perms
, cumulative_shared_perms
;
2214 if (bs
->drv
->bdrv_set_perm
) {
2215 bdrv_get_cumulative_perm(bs
, &cumulative_perms
,
2216 &cumulative_shared_perms
);
2217 bs
->drv
->bdrv_set_perm(bs
, cumulative_perms
, cumulative_shared_perms
);
2221 static void bdrv_drv_set_perm_abort(void *opaque
)
2223 BlockDriverState
*bs
= opaque
;
2225 if (bs
->drv
->bdrv_abort_perm_update
) {
2226 bs
->drv
->bdrv_abort_perm_update(bs
);
2230 TransactionActionDrv bdrv_drv_set_perm_drv
= {
2231 .abort
= bdrv_drv_set_perm_abort
,
2232 .commit
= bdrv_drv_set_perm_commit
,
2235 static int bdrv_drv_set_perm(BlockDriverState
*bs
, uint64_t perm
,
2236 uint64_t shared_perm
, Transaction
*tran
,
2243 if (bs
->drv
->bdrv_check_perm
) {
2244 int ret
= bs
->drv
->bdrv_check_perm(bs
, perm
, shared_perm
, errp
);
2251 tran_add(tran
, &bdrv_drv_set_perm_drv
, bs
);
2257 typedef struct BdrvReplaceChildState
{
2260 BlockDriverState
*old_bs
;
2261 bool free_empty_child
;
2262 } BdrvReplaceChildState
;
2264 static void bdrv_replace_child_commit(void *opaque
)
2266 BdrvReplaceChildState
*s
= opaque
;
2268 if (s
->free_empty_child
&& !s
->child
->bs
) {
2269 bdrv_child_free(s
->child
);
2271 bdrv_unref(s
->old_bs
);
2274 static void bdrv_replace_child_abort(void *opaque
)
2276 BdrvReplaceChildState
*s
= opaque
;
2277 BlockDriverState
*new_bs
= s
->child
->bs
;
2280 * old_bs reference is transparently moved from @s to s->child.
2282 * Pass &s->child here instead of s->childp, because:
2283 * (1) s->old_bs must be non-NULL, so bdrv_replace_child_noperm() will not
2284 * modify the BdrvChild * pointer we indirectly pass to it, i.e. it
2285 * will not modify s->child. From that perspective, it does not matter
2286 * whether we pass s->childp or &s->child.
2287 * (2) If new_bs is not NULL, s->childp will be NULL. We then cannot use
2289 * (3) If new_bs is NULL, *s->childp will have been NULLed by
2290 * bdrv_replace_child_tran()'s bdrv_replace_child_noperm() call, and we
2291 * must not pass a NULL *s->childp here.
2293 * So whether new_bs was NULL or not, we cannot pass s->childp here; and in
2294 * any case, there is no reason to pass it anyway.
2296 bdrv_replace_child_noperm(&s
->child
, s
->old_bs
, true);
2298 * The child was pre-existing, so s->old_bs must be non-NULL, and
2299 * s->child thus must not have been freed
2301 assert(s
->child
!= NULL
);
2303 /* As described above, *s->childp was cleared, so restore it */
2304 assert(s
->childp
!= NULL
);
2305 *s
->childp
= s
->child
;
2310 static TransactionActionDrv bdrv_replace_child_drv
= {
2311 .commit
= bdrv_replace_child_commit
,
2312 .abort
= bdrv_replace_child_abort
,
2317 * bdrv_replace_child_tran
2319 * Note: real unref of old_bs is done only on commit.
2321 * The function doesn't update permissions, caller is responsible for this.
2323 * (*childp)->bs must not be NULL.
2325 * Note that if new_bs == NULL, @childp is stored in a state object attached
2326 * to @tran, so that the old child can be reinstated in the abort handler.
2327 * Therefore, if @new_bs can be NULL, @childp must stay valid until the
2328 * transaction is committed or aborted.
2330 * If @free_empty_child is true and @new_bs is NULL, the BdrvChild is
2331 * freed (on commit). @free_empty_child should only be false if the
2332 * caller will free the BDrvChild themselves (which may be important
2333 * if this is in turn called in another transactional context).
2335 static void bdrv_replace_child_tran(BdrvChild
**childp
,
2336 BlockDriverState
*new_bs
,
2338 bool free_empty_child
)
2340 BdrvReplaceChildState
*s
= g_new(BdrvReplaceChildState
, 1);
2341 *s
= (BdrvReplaceChildState
) {
2343 .childp
= new_bs
== NULL
? childp
: NULL
,
2344 .old_bs
= (*childp
)->bs
,
2345 .free_empty_child
= free_empty_child
,
2347 tran_add(tran
, &bdrv_replace_child_drv
, s
);
2349 /* The abort handler relies on this */
2350 assert(s
->old_bs
!= NULL
);
2356 * Pass free_empty_child=false, we will free the child (if
2357 * necessary) in bdrv_replace_child_commit() (if our
2358 * @free_empty_child parameter was true).
2360 bdrv_replace_child_noperm(childp
, new_bs
, false);
2361 /* old_bs reference is transparently moved from *childp to @s */
2365 * Refresh permissions in @bs subtree. The function is intended to be called
2366 * after some graph modification that was done without permission update.
2368 static int bdrv_node_refresh_perm(BlockDriverState
*bs
, BlockReopenQueue
*q
,
2369 Transaction
*tran
, Error
**errp
)
2371 BlockDriver
*drv
= bs
->drv
;
2374 uint64_t cumulative_perms
, cumulative_shared_perms
;
2376 bdrv_get_cumulative_perm(bs
, &cumulative_perms
, &cumulative_shared_perms
);
2378 /* Write permissions never work with read-only images */
2379 if ((cumulative_perms
& (BLK_PERM_WRITE
| BLK_PERM_WRITE_UNCHANGED
)) &&
2380 !bdrv_is_writable_after_reopen(bs
, q
))
2382 if (!bdrv_is_writable_after_reopen(bs
, NULL
)) {
2383 error_setg(errp
, "Block node is read-only");
2385 error_setg(errp
, "Read-only block node '%s' cannot support "
2386 "read-write users", bdrv_get_node_name(bs
));
2393 * Unaligned requests will automatically be aligned to bl.request_alignment
2394 * and without RESIZE we can't extend requests to write to space beyond the
2395 * end of the image, so it's required that the image size is aligned.
2397 if ((cumulative_perms
& (BLK_PERM_WRITE
| BLK_PERM_WRITE_UNCHANGED
)) &&
2398 !(cumulative_perms
& BLK_PERM_RESIZE
))
2400 if ((bs
->total_sectors
* BDRV_SECTOR_SIZE
) % bs
->bl
.request_alignment
) {
2401 error_setg(errp
, "Cannot get 'write' permission without 'resize': "
2402 "Image size is not a multiple of request "
2408 /* Check this node */
2413 ret
= bdrv_drv_set_perm(bs
, cumulative_perms
, cumulative_shared_perms
, tran
,
2419 /* Drivers that never have children can omit .bdrv_child_perm() */
2420 if (!drv
->bdrv_child_perm
) {
2421 assert(QLIST_EMPTY(&bs
->children
));
2425 /* Check all children */
2426 QLIST_FOREACH(c
, &bs
->children
, next
) {
2427 uint64_t cur_perm
, cur_shared
;
2429 bdrv_child_perm(bs
, c
->bs
, c
, c
->role
, q
,
2430 cumulative_perms
, cumulative_shared_perms
,
2431 &cur_perm
, &cur_shared
);
2432 bdrv_child_set_perm(c
, cur_perm
, cur_shared
, tran
);
2438 static int bdrv_list_refresh_perms(GSList
*list
, BlockReopenQueue
*q
,
2439 Transaction
*tran
, Error
**errp
)
2442 BlockDriverState
*bs
;
2444 for ( ; list
; list
= list
->next
) {
2447 if (bdrv_parent_perms_conflict(bs
, errp
)) {
2451 ret
= bdrv_node_refresh_perm(bs
, q
, tran
, errp
);
2460 void bdrv_get_cumulative_perm(BlockDriverState
*bs
, uint64_t *perm
,
2461 uint64_t *shared_perm
)
2464 uint64_t cumulative_perms
= 0;
2465 uint64_t cumulative_shared_perms
= BLK_PERM_ALL
;
2467 QLIST_FOREACH(c
, &bs
->parents
, next_parent
) {
2468 cumulative_perms
|= c
->perm
;
2469 cumulative_shared_perms
&= c
->shared_perm
;
2472 *perm
= cumulative_perms
;
2473 *shared_perm
= cumulative_shared_perms
;
2476 char *bdrv_perm_names(uint64_t perm
)
2482 { BLK_PERM_CONSISTENT_READ
, "consistent read" },
2483 { BLK_PERM_WRITE
, "write" },
2484 { BLK_PERM_WRITE_UNCHANGED
, "write unchanged" },
2485 { BLK_PERM_RESIZE
, "resize" },
2486 { BLK_PERM_GRAPH_MOD
, "change children" },
2490 GString
*result
= g_string_sized_new(30);
2491 struct perm_name
*p
;
2493 for (p
= permissions
; p
->name
; p
++) {
2494 if (perm
& p
->perm
) {
2495 if (result
->len
> 0) {
2496 g_string_append(result
, ", ");
2498 g_string_append(result
, p
->name
);
2502 return g_string_free(result
, FALSE
);
2506 static int bdrv_refresh_perms(BlockDriverState
*bs
, Error
**errp
)
2509 Transaction
*tran
= tran_new();
2510 g_autoptr(GSList
) list
= bdrv_topological_dfs(NULL
, NULL
, bs
);
2512 ret
= bdrv_list_refresh_perms(list
, NULL
, tran
, errp
);
2513 tran_finalize(tran
, ret
);
2518 int bdrv_child_try_set_perm(BdrvChild
*c
, uint64_t perm
, uint64_t shared
,
2521 Error
*local_err
= NULL
;
2522 Transaction
*tran
= tran_new();
2525 bdrv_child_set_perm(c
, perm
, shared
, tran
);
2527 ret
= bdrv_refresh_perms(c
->bs
, &local_err
);
2529 tran_finalize(tran
, ret
);
2532 if ((perm
& ~c
->perm
) || (c
->shared_perm
& ~shared
)) {
2533 /* tighten permissions */
2534 error_propagate(errp
, local_err
);
2537 * Our caller may intend to only loosen restrictions and
2538 * does not expect this function to fail. Errors are not
2539 * fatal in such a case, so we can just hide them from our
2542 error_free(local_err
);
2550 int bdrv_child_refresh_perms(BlockDriverState
*bs
, BdrvChild
*c
, Error
**errp
)
2552 uint64_t parent_perms
, parent_shared
;
2553 uint64_t perms
, shared
;
2555 bdrv_get_cumulative_perm(bs
, &parent_perms
, &parent_shared
);
2556 bdrv_child_perm(bs
, c
->bs
, c
, c
->role
, NULL
,
2557 parent_perms
, parent_shared
, &perms
, &shared
);
2559 return bdrv_child_try_set_perm(c
, perms
, shared
, errp
);
2563 * Default implementation for .bdrv_child_perm() for block filters:
2564 * Forward CONSISTENT_READ, WRITE, WRITE_UNCHANGED, and RESIZE to the
2567 static void bdrv_filter_default_perms(BlockDriverState
*bs
, BdrvChild
*c
,
2569 BlockReopenQueue
*reopen_queue
,
2570 uint64_t perm
, uint64_t shared
,
2571 uint64_t *nperm
, uint64_t *nshared
)
2573 *nperm
= perm
& DEFAULT_PERM_PASSTHROUGH
;
2574 *nshared
= (shared
& DEFAULT_PERM_PASSTHROUGH
) | DEFAULT_PERM_UNCHANGED
;
2577 static void bdrv_default_perms_for_cow(BlockDriverState
*bs
, BdrvChild
*c
,
2579 BlockReopenQueue
*reopen_queue
,
2580 uint64_t perm
, uint64_t shared
,
2581 uint64_t *nperm
, uint64_t *nshared
)
2583 assert(role
& BDRV_CHILD_COW
);
2586 * We want consistent read from backing files if the parent needs it.
2587 * No other operations are performed on backing files.
2589 perm
&= BLK_PERM_CONSISTENT_READ
;
2592 * If the parent can deal with changing data, we're okay with a
2593 * writable and resizable backing file.
2594 * TODO Require !(perm & BLK_PERM_CONSISTENT_READ), too?
2596 if (shared
& BLK_PERM_WRITE
) {
2597 shared
= BLK_PERM_WRITE
| BLK_PERM_RESIZE
;
2602 shared
|= BLK_PERM_CONSISTENT_READ
| BLK_PERM_GRAPH_MOD
|
2603 BLK_PERM_WRITE_UNCHANGED
;
2605 if (bs
->open_flags
& BDRV_O_INACTIVE
) {
2606 shared
|= BLK_PERM_WRITE
| BLK_PERM_RESIZE
;
2613 static void bdrv_default_perms_for_storage(BlockDriverState
*bs
, BdrvChild
*c
,
2615 BlockReopenQueue
*reopen_queue
,
2616 uint64_t perm
, uint64_t shared
,
2617 uint64_t *nperm
, uint64_t *nshared
)
2621 assert(role
& (BDRV_CHILD_METADATA
| BDRV_CHILD_DATA
));
2623 flags
= bdrv_reopen_get_flags(reopen_queue
, bs
);
2626 * Apart from the modifications below, the same permissions are
2627 * forwarded and left alone as for filters
2629 bdrv_filter_default_perms(bs
, c
, role
, reopen_queue
,
2630 perm
, shared
, &perm
, &shared
);
2632 if (role
& BDRV_CHILD_METADATA
) {
2633 /* Format drivers may touch metadata even if the guest doesn't write */
2634 if (bdrv_is_writable_after_reopen(bs
, reopen_queue
)) {
2635 perm
|= BLK_PERM_WRITE
| BLK_PERM_RESIZE
;
2639 * bs->file always needs to be consistent because of the
2640 * metadata. We can never allow other users to resize or write
2643 if (!(flags
& BDRV_O_NO_IO
)) {
2644 perm
|= BLK_PERM_CONSISTENT_READ
;
2646 shared
&= ~(BLK_PERM_WRITE
| BLK_PERM_RESIZE
);
2649 if (role
& BDRV_CHILD_DATA
) {
2651 * Technically, everything in this block is a subset of the
2652 * BDRV_CHILD_METADATA path taken above, and so this could
2653 * be an "else if" branch. However, that is not obvious, and
2654 * this function is not performance critical, therefore we let
2655 * this be an independent "if".
2659 * We cannot allow other users to resize the file because the
2660 * format driver might have some assumptions about the size
2661 * (e.g. because it is stored in metadata, or because the file
2662 * is split into fixed-size data files).
2664 shared
&= ~BLK_PERM_RESIZE
;
2667 * WRITE_UNCHANGED often cannot be performed as such on the
2668 * data file. For example, the qcow2 driver may still need to
2669 * write copied clusters on copy-on-read.
2671 if (perm
& BLK_PERM_WRITE_UNCHANGED
) {
2672 perm
|= BLK_PERM_WRITE
;
2676 * If the data file is written to, the format driver may
2677 * expect to be able to resize it by writing beyond the EOF.
2679 if (perm
& BLK_PERM_WRITE
) {
2680 perm
|= BLK_PERM_RESIZE
;
2684 if (bs
->open_flags
& BDRV_O_INACTIVE
) {
2685 shared
|= BLK_PERM_WRITE
| BLK_PERM_RESIZE
;
2692 void bdrv_default_perms(BlockDriverState
*bs
, BdrvChild
*c
,
2693 BdrvChildRole role
, BlockReopenQueue
*reopen_queue
,
2694 uint64_t perm
, uint64_t shared
,
2695 uint64_t *nperm
, uint64_t *nshared
)
2697 if (role
& BDRV_CHILD_FILTERED
) {
2698 assert(!(role
& (BDRV_CHILD_DATA
| BDRV_CHILD_METADATA
|
2700 bdrv_filter_default_perms(bs
, c
, role
, reopen_queue
,
2701 perm
, shared
, nperm
, nshared
);
2702 } else if (role
& BDRV_CHILD_COW
) {
2703 assert(!(role
& (BDRV_CHILD_DATA
| BDRV_CHILD_METADATA
)));
2704 bdrv_default_perms_for_cow(bs
, c
, role
, reopen_queue
,
2705 perm
, shared
, nperm
, nshared
);
2706 } else if (role
& (BDRV_CHILD_METADATA
| BDRV_CHILD_DATA
)) {
2707 bdrv_default_perms_for_storage(bs
, c
, role
, reopen_queue
,
2708 perm
, shared
, nperm
, nshared
);
2710 g_assert_not_reached();
2714 uint64_t bdrv_qapi_perm_to_blk_perm(BlockPermission qapi_perm
)
2716 static const uint64_t permissions
[] = {
2717 [BLOCK_PERMISSION_CONSISTENT_READ
] = BLK_PERM_CONSISTENT_READ
,
2718 [BLOCK_PERMISSION_WRITE
] = BLK_PERM_WRITE
,
2719 [BLOCK_PERMISSION_WRITE_UNCHANGED
] = BLK_PERM_WRITE_UNCHANGED
,
2720 [BLOCK_PERMISSION_RESIZE
] = BLK_PERM_RESIZE
,
2721 [BLOCK_PERMISSION_GRAPH_MOD
] = BLK_PERM_GRAPH_MOD
,
2724 QEMU_BUILD_BUG_ON(ARRAY_SIZE(permissions
) != BLOCK_PERMISSION__MAX
);
2725 QEMU_BUILD_BUG_ON(1UL << ARRAY_SIZE(permissions
) != BLK_PERM_ALL
+ 1);
2727 assert(qapi_perm
< BLOCK_PERMISSION__MAX
);
2729 return permissions
[qapi_perm
];
2733 * Replace (*childp)->bs by @new_bs.
2735 * If @new_bs is NULL, *childp will be set to NULL, too: BDS parents
2736 * generally cannot handle a BdrvChild with .bs == NULL, so clearing
2737 * BdrvChild.bs should generally immediately be followed by the
2738 * BdrvChild pointer being cleared as well.
2740 * If @free_empty_child is true and @new_bs is NULL, the BdrvChild is
2741 * freed. @free_empty_child should only be false if the caller will
2742 * free the BdrvChild themselves (this may be important in a
2743 * transactional context, where it may only be freed on commit).
2745 static void bdrv_replace_child_noperm(BdrvChild
**childp
,
2746 BlockDriverState
*new_bs
,
2747 bool free_empty_child
)
2749 BdrvChild
*child
= *childp
;
2750 BlockDriverState
*old_bs
= child
->bs
;
2751 int new_bs_quiesce_counter
;
2754 assert(!child
->frozen
);
2755 assert(old_bs
!= new_bs
);
2757 if (old_bs
&& new_bs
) {
2758 assert(bdrv_get_aio_context(old_bs
) == bdrv_get_aio_context(new_bs
));
2761 new_bs_quiesce_counter
= (new_bs
? new_bs
->quiesce_counter
: 0);
2762 drain_saldo
= new_bs_quiesce_counter
- child
->parent_quiesce_counter
;
2765 * If the new child node is drained but the old one was not, flush
2766 * all outstanding requests to the old child node.
2768 while (drain_saldo
> 0 && child
->klass
->drained_begin
) {
2769 bdrv_parent_drained_begin_single(child
, true);
2774 /* Detach first so that the recursive drain sections coming from @child
2775 * are already gone and we only end the drain sections that came from
2777 if (child
->klass
->detach
) {
2778 child
->klass
->detach(child
);
2780 QLIST_REMOVE(child
, next_parent
);
2789 QLIST_INSERT_HEAD(&new_bs
->parents
, child
, next_parent
);
2792 * Detaching the old node may have led to the new node's
2793 * quiesce_counter having been decreased. Not a problem, we
2794 * just need to recognize this here and then invoke
2795 * drained_end appropriately more often.
2797 assert(new_bs
->quiesce_counter
<= new_bs_quiesce_counter
);
2798 drain_saldo
+= new_bs
->quiesce_counter
- new_bs_quiesce_counter
;
2800 /* Attach only after starting new drained sections, so that recursive
2801 * drain sections coming from @child don't get an extra .drained_begin
2803 if (child
->klass
->attach
) {
2804 child
->klass
->attach(child
);
2809 * If the old child node was drained but the new one is not, allow
2810 * requests to come in only after the new node has been attached.
2812 while (drain_saldo
< 0 && child
->klass
->drained_end
) {
2813 bdrv_parent_drained_end_single(child
);
2817 if (free_empty_child
&& !child
->bs
) {
2818 bdrv_child_free(child
);
2823 * Free the given @child.
2825 * The child must be empty (i.e. `child->bs == NULL`) and it must be
2826 * unused (i.e. not in a children list).
2828 static void bdrv_child_free(BdrvChild
*child
)
2831 assert(!child
->next
.le_prev
); /* not in children list */
2833 g_free(child
->name
);
2837 typedef struct BdrvAttachChildCommonState
{
2839 AioContext
*old_parent_ctx
;
2840 AioContext
*old_child_ctx
;
2841 } BdrvAttachChildCommonState
;
2843 static void bdrv_attach_child_common_abort(void *opaque
)
2845 BdrvAttachChildCommonState
*s
= opaque
;
2846 BdrvChild
*child
= *s
->child
;
2847 BlockDriverState
*bs
= child
->bs
;
2850 * Pass free_empty_child=false, because we still need the child
2851 * for the AioContext operations on the parent below; those
2852 * BdrvChildClass methods all work on a BdrvChild object, so we
2853 * need to keep it as an empty shell (after this function, it will
2854 * not be attached to any parent, and it will not have a .bs).
2856 bdrv_replace_child_noperm(s
->child
, NULL
, false);
2858 if (bdrv_get_aio_context(bs
) != s
->old_child_ctx
) {
2859 bdrv_try_set_aio_context(bs
, s
->old_child_ctx
, &error_abort
);
2862 if (bdrv_child_get_parent_aio_context(child
) != s
->old_parent_ctx
) {
2865 /* No need to ignore `child`, because it has been detached already */
2867 child
->klass
->can_set_aio_ctx(child
, s
->old_parent_ctx
, &ignore
,
2869 g_slist_free(ignore
);
2872 child
->klass
->set_aio_ctx(child
, s
->old_parent_ctx
, &ignore
);
2873 g_slist_free(ignore
);
2877 bdrv_child_free(child
);
2880 static TransactionActionDrv bdrv_attach_child_common_drv
= {
2881 .abort
= bdrv_attach_child_common_abort
,
2886 * Common part of attaching bdrv child to bs or to blk or to job
2888 * Resulting new child is returned through @child.
2889 * At start *@child must be NULL.
2890 * @child is saved to a new entry of @tran, so that *@child could be reverted to
2891 * NULL on abort(). So referenced variable must live at least until transaction
2894 * Function doesn't update permissions, caller is responsible for this.
2896 static int bdrv_attach_child_common(BlockDriverState
*child_bs
,
2897 const char *child_name
,
2898 const BdrvChildClass
*child_class
,
2899 BdrvChildRole child_role
,
2900 uint64_t perm
, uint64_t shared_perm
,
2901 void *opaque
, BdrvChild
**child
,
2902 Transaction
*tran
, Error
**errp
)
2904 BdrvChild
*new_child
;
2905 AioContext
*parent_ctx
;
2906 AioContext
*child_ctx
= bdrv_get_aio_context(child_bs
);
2909 assert(*child
== NULL
);
2910 assert(child_class
->get_parent_desc
);
2912 new_child
= g_new(BdrvChild
, 1);
2913 *new_child
= (BdrvChild
) {
2915 .name
= g_strdup(child_name
),
2916 .klass
= child_class
,
2919 .shared_perm
= shared_perm
,
2924 * If the AioContexts don't match, first try to move the subtree of
2925 * child_bs into the AioContext of the new parent. If this doesn't work,
2926 * try moving the parent into the AioContext of child_bs instead.
2928 parent_ctx
= bdrv_child_get_parent_aio_context(new_child
);
2929 if (child_ctx
!= parent_ctx
) {
2930 Error
*local_err
= NULL
;
2931 int ret
= bdrv_try_set_aio_context(child_bs
, parent_ctx
, &local_err
);
2933 if (ret
< 0 && child_class
->can_set_aio_ctx
) {
2934 GSList
*ignore
= g_slist_prepend(NULL
, new_child
);
2935 if (child_class
->can_set_aio_ctx(new_child
, child_ctx
, &ignore
,
2938 error_free(local_err
);
2940 g_slist_free(ignore
);
2941 ignore
= g_slist_prepend(NULL
, new_child
);
2942 child_class
->set_aio_ctx(new_child
, child_ctx
, &ignore
);
2944 g_slist_free(ignore
);
2948 error_propagate(errp
, local_err
);
2949 bdrv_child_free(new_child
);
2955 bdrv_replace_child_noperm(&new_child
, child_bs
, true);
2956 /* child_bs was non-NULL, so new_child must not have been freed */
2957 assert(new_child
!= NULL
);
2961 BdrvAttachChildCommonState
*s
= g_new(BdrvAttachChildCommonState
, 1);
2962 *s
= (BdrvAttachChildCommonState
) {
2964 .old_parent_ctx
= parent_ctx
,
2965 .old_child_ctx
= child_ctx
,
2967 tran_add(tran
, &bdrv_attach_child_common_drv
, s
);
2973 * Variable referenced by @child must live at least until transaction end.
2974 * (see bdrv_attach_child_common() doc for details)
2976 * Function doesn't update permissions, caller is responsible for this.
2978 static int bdrv_attach_child_noperm(BlockDriverState
*parent_bs
,
2979 BlockDriverState
*child_bs
,
2980 const char *child_name
,
2981 const BdrvChildClass
*child_class
,
2982 BdrvChildRole child_role
,
2988 uint64_t perm
, shared_perm
;
2990 assert(parent_bs
->drv
);
2992 if (bdrv_recurse_has_child(child_bs
, parent_bs
)) {
2993 error_setg(errp
, "Making '%s' a %s child of '%s' would create a cycle",
2994 child_bs
->node_name
, child_name
, parent_bs
->node_name
);
2998 bdrv_get_cumulative_perm(parent_bs
, &perm
, &shared_perm
);
2999 bdrv_child_perm(parent_bs
, child_bs
, NULL
, child_role
, NULL
,
3000 perm
, shared_perm
, &perm
, &shared_perm
);
3002 ret
= bdrv_attach_child_common(child_bs
, child_name
, child_class
,
3003 child_role
, perm
, shared_perm
, parent_bs
,
3012 static void bdrv_detach_child(BdrvChild
**childp
)
3014 BlockDriverState
*old_bs
= (*childp
)->bs
;
3016 bdrv_replace_child_noperm(childp
, NULL
, true);
3020 * Update permissions for old node. We're just taking a parent away, so
3021 * we're loosening restrictions. Errors of permission update are not
3022 * fatal in this case, ignore them.
3024 bdrv_refresh_perms(old_bs
, NULL
);
3027 * When the parent requiring a non-default AioContext is removed, the
3028 * node moves back to the main AioContext
3030 bdrv_try_set_aio_context(old_bs
, qemu_get_aio_context(), NULL
);
3035 * This function steals the reference to child_bs from the caller.
3036 * That reference is later dropped by bdrv_root_unref_child().
3038 * On failure NULL is returned, errp is set and the reference to
3039 * child_bs is also dropped.
3041 * The caller must hold the AioContext lock @child_bs, but not that of @ctx
3042 * (unless @child_bs is already in @ctx).
3044 BdrvChild
*bdrv_root_attach_child(BlockDriverState
*child_bs
,
3045 const char *child_name
,
3046 const BdrvChildClass
*child_class
,
3047 BdrvChildRole child_role
,
3048 uint64_t perm
, uint64_t shared_perm
,
3049 void *opaque
, Error
**errp
)
3052 BdrvChild
*child
= NULL
;
3053 Transaction
*tran
= tran_new();
3055 ret
= bdrv_attach_child_common(child_bs
, child_name
, child_class
,
3056 child_role
, perm
, shared_perm
, opaque
,
3057 &child
, tran
, errp
);
3062 ret
= bdrv_refresh_perms(child_bs
, errp
);
3065 tran_finalize(tran
, ret
);
3066 /* child is unset on failure by bdrv_attach_child_common_abort() */
3067 assert((ret
< 0) == !child
);
3069 bdrv_unref(child_bs
);
3074 * This function transfers the reference to child_bs from the caller
3075 * to parent_bs. That reference is later dropped by parent_bs on
3076 * bdrv_close() or if someone calls bdrv_unref_child().
3078 * On failure NULL is returned, errp is set and the reference to
3079 * child_bs is also dropped.
3081 * If @parent_bs and @child_bs are in different AioContexts, the caller must
3082 * hold the AioContext lock for @child_bs, but not for @parent_bs.
3084 BdrvChild
*bdrv_attach_child(BlockDriverState
*parent_bs
,
3085 BlockDriverState
*child_bs
,
3086 const char *child_name
,
3087 const BdrvChildClass
*child_class
,
3088 BdrvChildRole child_role
,
3092 BdrvChild
*child
= NULL
;
3093 Transaction
*tran
= tran_new();
3095 ret
= bdrv_attach_child_noperm(parent_bs
, child_bs
, child_name
, child_class
,
3096 child_role
, &child
, tran
, errp
);
3101 ret
= bdrv_refresh_perms(parent_bs
, errp
);
3107 tran_finalize(tran
, ret
);
3108 /* child is unset on failure by bdrv_attach_child_common_abort() */
3109 assert((ret
< 0) == !child
);
3111 bdrv_unref(child_bs
);
3116 /* Callers must ensure that child->frozen is false. */
3117 void bdrv_root_unref_child(BdrvChild
*child
)
3119 BlockDriverState
*child_bs
;
3121 child_bs
= child
->bs
;
3122 bdrv_detach_child(&child
);
3123 bdrv_unref(child_bs
);
3126 typedef struct BdrvSetInheritsFrom
{
3127 BlockDriverState
*bs
;
3128 BlockDriverState
*old_inherits_from
;
3129 } BdrvSetInheritsFrom
;
3131 static void bdrv_set_inherits_from_abort(void *opaque
)
3133 BdrvSetInheritsFrom
*s
= opaque
;
3135 s
->bs
->inherits_from
= s
->old_inherits_from
;
3138 static TransactionActionDrv bdrv_set_inherits_from_drv
= {
3139 .abort
= bdrv_set_inherits_from_abort
,
3143 /* @tran is allowed to be NULL. In this case no rollback is possible */
3144 static void bdrv_set_inherits_from(BlockDriverState
*bs
,
3145 BlockDriverState
*new_inherits_from
,
3149 BdrvSetInheritsFrom
*s
= g_new(BdrvSetInheritsFrom
, 1);
3151 *s
= (BdrvSetInheritsFrom
) {
3153 .old_inherits_from
= bs
->inherits_from
,
3156 tran_add(tran
, &bdrv_set_inherits_from_drv
, s
);
3159 bs
->inherits_from
= new_inherits_from
;
3163 * Clear all inherits_from pointers from children and grandchildren of
3164 * @root that point to @root, where necessary.
3165 * @tran is allowed to be NULL. In this case no rollback is possible
3167 static void bdrv_unset_inherits_from(BlockDriverState
*root
, BdrvChild
*child
,
3172 if (child
->bs
->inherits_from
== root
) {
3174 * Remove inherits_from only when the last reference between root and
3175 * child->bs goes away.
3177 QLIST_FOREACH(c
, &root
->children
, next
) {
3178 if (c
!= child
&& c
->bs
== child
->bs
) {
3183 bdrv_set_inherits_from(child
->bs
, NULL
, tran
);
3187 QLIST_FOREACH(c
, &child
->bs
->children
, next
) {
3188 bdrv_unset_inherits_from(root
, c
, tran
);
3192 /* Callers must ensure that child->frozen is false. */
3193 void bdrv_unref_child(BlockDriverState
*parent
, BdrvChild
*child
)
3195 if (child
== NULL
) {
3199 bdrv_unset_inherits_from(parent
, child
, NULL
);
3200 bdrv_root_unref_child(child
);
3204 static void bdrv_parent_cb_change_media(BlockDriverState
*bs
, bool load
)
3207 QLIST_FOREACH(c
, &bs
->parents
, next_parent
) {
3208 if (c
->klass
->change_media
) {
3209 c
->klass
->change_media(c
, load
);
3214 /* Return true if you can reach parent going through child->inherits_from
3215 * recursively. If parent or child are NULL, return false */
3216 static bool bdrv_inherits_from_recursive(BlockDriverState
*child
,
3217 BlockDriverState
*parent
)
3219 while (child
&& child
!= parent
) {
3220 child
= child
->inherits_from
;
3223 return child
!= NULL
;
3227 * Return the BdrvChildRole for @bs's backing child. bs->backing is
3228 * mostly used for COW backing children (role = COW), but also for
3229 * filtered children (role = FILTERED | PRIMARY).
3231 static BdrvChildRole
bdrv_backing_role(BlockDriverState
*bs
)
3233 if (bs
->drv
&& bs
->drv
->is_filter
) {
3234 return BDRV_CHILD_FILTERED
| BDRV_CHILD_PRIMARY
;
3236 return BDRV_CHILD_COW
;
3241 * Sets the bs->backing or bs->file link of a BDS. A new reference is created;
3242 * callers which don't need their own reference any more must call bdrv_unref().
3244 * Function doesn't update permissions, caller is responsible for this.
3246 static int bdrv_set_file_or_backing_noperm(BlockDriverState
*parent_bs
,
3247 BlockDriverState
*child_bs
,
3249 Transaction
*tran
, Error
**errp
)
3252 bool update_inherits_from
=
3253 bdrv_inherits_from_recursive(child_bs
, parent_bs
);
3254 BdrvChild
*child
= is_backing
? parent_bs
->backing
: parent_bs
->file
;
3257 if (!parent_bs
->drv
) {
3259 * Node without drv is an object without a class :/. TODO: finally fix
3260 * qcow2 driver to never clear bs->drv and implement format corruption
3261 * handling in other way.
3263 error_setg(errp
, "Node corrupted");
3267 if (child
&& child
->frozen
) {
3268 error_setg(errp
, "Cannot change frozen '%s' link from '%s' to '%s'",
3269 child
->name
, parent_bs
->node_name
, child
->bs
->node_name
);
3273 if (is_backing
&& !parent_bs
->drv
->is_filter
&&
3274 !parent_bs
->drv
->supports_backing
)
3276 error_setg(errp
, "Driver '%s' of node '%s' does not support backing "
3277 "files", parent_bs
->drv
->format_name
, parent_bs
->node_name
);
3281 if (parent_bs
->drv
->is_filter
) {
3282 role
= BDRV_CHILD_FILTERED
| BDRV_CHILD_PRIMARY
;
3283 } else if (is_backing
) {
3284 role
= BDRV_CHILD_COW
;
3287 * We only can use same role as it is in existing child. We don't have
3288 * infrastructure to determine role of file child in generic way
3291 error_setg(errp
, "Cannot set file child to format node without "
3299 bdrv_unset_inherits_from(parent_bs
, child
, tran
);
3300 bdrv_remove_file_or_backing_child(parent_bs
, child
, tran
);
3307 ret
= bdrv_attach_child_noperm(parent_bs
, child_bs
,
3308 is_backing
? "backing" : "file",
3309 &child_of_bds
, role
,
3310 is_backing
? &parent_bs
->backing
:
3319 * If inherits_from pointed recursively to bs then let's update it to
3320 * point directly to bs (else it will become NULL).
3322 if (update_inherits_from
) {
3323 bdrv_set_inherits_from(child_bs
, parent_bs
, tran
);
3327 bdrv_refresh_limits(parent_bs
, tran
, NULL
);
3332 static int bdrv_set_backing_noperm(BlockDriverState
*bs
,
3333 BlockDriverState
*backing_hd
,
3334 Transaction
*tran
, Error
**errp
)
3336 return bdrv_set_file_or_backing_noperm(bs
, backing_hd
, true, tran
, errp
);
3339 int bdrv_set_backing_hd(BlockDriverState
*bs
, BlockDriverState
*backing_hd
,
3343 Transaction
*tran
= tran_new();
3345 ret
= bdrv_set_backing_noperm(bs
, backing_hd
, tran
, errp
);
3350 ret
= bdrv_refresh_perms(bs
, errp
);
3352 tran_finalize(tran
, ret
);
3358 * Opens the backing file for a BlockDriverState if not yet open
3360 * bdref_key specifies the key for the image's BlockdevRef in the options QDict.
3361 * That QDict has to be flattened; therefore, if the BlockdevRef is a QDict
3362 * itself, all options starting with "${bdref_key}." are considered part of the
3365 * TODO Can this be unified with bdrv_open_image()?
3367 int bdrv_open_backing_file(BlockDriverState
*bs
, QDict
*parent_options
,
3368 const char *bdref_key
, Error
**errp
)
3370 char *backing_filename
= NULL
;
3371 char *bdref_key_dot
;
3372 const char *reference
= NULL
;
3374 bool implicit_backing
= false;
3375 BlockDriverState
*backing_hd
;
3377 QDict
*tmp_parent_options
= NULL
;
3378 Error
*local_err
= NULL
;
3380 if (bs
->backing
!= NULL
) {
3384 /* NULL means an empty set of options */
3385 if (parent_options
== NULL
) {
3386 tmp_parent_options
= qdict_new();
3387 parent_options
= tmp_parent_options
;
3390 bs
->open_flags
&= ~BDRV_O_NO_BACKING
;
3392 bdref_key_dot
= g_strdup_printf("%s.", bdref_key
);
3393 qdict_extract_subqdict(parent_options
, &options
, bdref_key_dot
);
3394 g_free(bdref_key_dot
);
3397 * Caution: while qdict_get_try_str() is fine, getting non-string
3398 * types would require more care. When @parent_options come from
3399 * -blockdev or blockdev_add, its members are typed according to
3400 * the QAPI schema, but when they come from -drive, they're all
3403 reference
= qdict_get_try_str(parent_options
, bdref_key
);
3404 if (reference
|| qdict_haskey(options
, "file.filename")) {
3405 /* keep backing_filename NULL */
3406 } else if (bs
->backing_file
[0] == '\0' && qdict_size(options
) == 0) {
3407 qobject_unref(options
);
3410 if (qdict_size(options
) == 0) {
3411 /* If the user specifies options that do not modify the
3412 * backing file's behavior, we might still consider it the
3413 * implicit backing file. But it's easier this way, and
3414 * just specifying some of the backing BDS's options is
3415 * only possible with -drive anyway (otherwise the QAPI
3416 * schema forces the user to specify everything). */
3417 implicit_backing
= !strcmp(bs
->auto_backing_file
, bs
->backing_file
);
3420 backing_filename
= bdrv_get_full_backing_filename(bs
, &local_err
);
3423 error_propagate(errp
, local_err
);
3424 qobject_unref(options
);
3429 if (!bs
->drv
|| !bs
->drv
->supports_backing
) {
3431 error_setg(errp
, "Driver doesn't support backing files");
3432 qobject_unref(options
);
3437 bs
->backing_format
[0] != '\0' && !qdict_haskey(options
, "driver")) {
3438 qdict_put_str(options
, "driver", bs
->backing_format
);
3441 backing_hd
= bdrv_open_inherit(backing_filename
, reference
, options
, 0, bs
,
3442 &child_of_bds
, bdrv_backing_role(bs
), errp
);
3444 bs
->open_flags
|= BDRV_O_NO_BACKING
;
3445 error_prepend(errp
, "Could not open backing file: ");
3450 if (implicit_backing
) {
3451 bdrv_refresh_filename(backing_hd
);
3452 pstrcpy(bs
->auto_backing_file
, sizeof(bs
->auto_backing_file
),
3453 backing_hd
->filename
);
3456 /* Hook up the backing file link; drop our reference, bs owns the
3457 * backing_hd reference now */
3458 ret
= bdrv_set_backing_hd(bs
, backing_hd
, errp
);
3459 bdrv_unref(backing_hd
);
3464 qdict_del(parent_options
, bdref_key
);
3467 g_free(backing_filename
);
3468 qobject_unref(tmp_parent_options
);
3472 static BlockDriverState
*
3473 bdrv_open_child_bs(const char *filename
, QDict
*options
, const char *bdref_key
,
3474 BlockDriverState
*parent
, const BdrvChildClass
*child_class
,
3475 BdrvChildRole child_role
, bool allow_none
, Error
**errp
)
3477 BlockDriverState
*bs
= NULL
;
3478 QDict
*image_options
;
3479 char *bdref_key_dot
;
3480 const char *reference
;
3482 assert(child_class
!= NULL
);
3484 bdref_key_dot
= g_strdup_printf("%s.", bdref_key
);
3485 qdict_extract_subqdict(options
, &image_options
, bdref_key_dot
);
3486 g_free(bdref_key_dot
);
3489 * Caution: while qdict_get_try_str() is fine, getting non-string
3490 * types would require more care. When @options come from
3491 * -blockdev or blockdev_add, its members are typed according to
3492 * the QAPI schema, but when they come from -drive, they're all
3495 reference
= qdict_get_try_str(options
, bdref_key
);
3496 if (!filename
&& !reference
&& !qdict_size(image_options
)) {
3498 error_setg(errp
, "A block device must be specified for \"%s\"",
3501 qobject_unref(image_options
);
3505 bs
= bdrv_open_inherit(filename
, reference
, image_options
, 0,
3506 parent
, child_class
, child_role
, errp
);
3512 qdict_del(options
, bdref_key
);
3517 * Opens a disk image whose options are given as BlockdevRef in another block
3520 * If allow_none is true, no image will be opened if filename is false and no
3521 * BlockdevRef is given. NULL will be returned, but errp remains unset.
3523 * bdrev_key specifies the key for the image's BlockdevRef in the options QDict.
3524 * That QDict has to be flattened; therefore, if the BlockdevRef is a QDict
3525 * itself, all options starting with "${bdref_key}." are considered part of the
3528 * The BlockdevRef will be removed from the options QDict.
3530 BdrvChild
*bdrv_open_child(const char *filename
,
3531 QDict
*options
, const char *bdref_key
,
3532 BlockDriverState
*parent
,
3533 const BdrvChildClass
*child_class
,
3534 BdrvChildRole child_role
,
3535 bool allow_none
, Error
**errp
)
3537 BlockDriverState
*bs
;
3539 bs
= bdrv_open_child_bs(filename
, options
, bdref_key
, parent
, child_class
,
3540 child_role
, allow_none
, errp
);
3545 return bdrv_attach_child(parent
, bs
, bdref_key
, child_class
, child_role
,
3550 * TODO Future callers may need to specify parent/child_class in order for
3551 * option inheritance to work. Existing callers use it for the root node.
3553 BlockDriverState
*bdrv_open_blockdev_ref(BlockdevRef
*ref
, Error
**errp
)
3555 BlockDriverState
*bs
= NULL
;
3556 QObject
*obj
= NULL
;
3557 QDict
*qdict
= NULL
;
3558 const char *reference
= NULL
;
3561 if (ref
->type
== QTYPE_QSTRING
) {
3562 reference
= ref
->u
.reference
;
3564 BlockdevOptions
*options
= &ref
->u
.definition
;
3565 assert(ref
->type
== QTYPE_QDICT
);
3567 v
= qobject_output_visitor_new(&obj
);
3568 visit_type_BlockdevOptions(v
, NULL
, &options
, &error_abort
);
3569 visit_complete(v
, &obj
);
3571 qdict
= qobject_to(QDict
, obj
);
3572 qdict_flatten(qdict
);
3574 /* bdrv_open_inherit() defaults to the values in bdrv_flags (for
3575 * compatibility with other callers) rather than what we want as the
3576 * real defaults. Apply the defaults here instead. */
3577 qdict_set_default_str(qdict
, BDRV_OPT_CACHE_DIRECT
, "off");
3578 qdict_set_default_str(qdict
, BDRV_OPT_CACHE_NO_FLUSH
, "off");
3579 qdict_set_default_str(qdict
, BDRV_OPT_READ_ONLY
, "off");
3580 qdict_set_default_str(qdict
, BDRV_OPT_AUTO_READ_ONLY
, "off");
3584 bs
= bdrv_open_inherit(NULL
, reference
, qdict
, 0, NULL
, NULL
, 0, errp
);
3591 static BlockDriverState
*bdrv_append_temp_snapshot(BlockDriverState
*bs
,
3593 QDict
*snapshot_options
,
3596 /* TODO: extra byte is a hack to ensure MAX_PATH space on Windows. */
3597 char *tmp_filename
= g_malloc0(PATH_MAX
+ 1);
3599 QemuOpts
*opts
= NULL
;
3600 BlockDriverState
*bs_snapshot
= NULL
;
3603 /* if snapshot, we create a temporary backing file and open it
3604 instead of opening 'filename' directly */
3606 /* Get the required size from the image */
3607 total_size
= bdrv_getlength(bs
);
3608 if (total_size
< 0) {
3609 error_setg_errno(errp
, -total_size
, "Could not get image size");
3613 /* Create the temporary image */
3614 ret
= get_tmp_filename(tmp_filename
, PATH_MAX
+ 1);
3616 error_setg_errno(errp
, -ret
, "Could not get temporary filename");
3620 opts
= qemu_opts_create(bdrv_qcow2
.create_opts
, NULL
, 0,
3622 qemu_opt_set_number(opts
, BLOCK_OPT_SIZE
, total_size
, &error_abort
);
3623 ret
= bdrv_create(&bdrv_qcow2
, tmp_filename
, opts
, errp
);
3624 qemu_opts_del(opts
);
3626 error_prepend(errp
, "Could not create temporary overlay '%s': ",
3631 /* Prepare options QDict for the temporary file */
3632 qdict_put_str(snapshot_options
, "file.driver", "file");
3633 qdict_put_str(snapshot_options
, "file.filename", tmp_filename
);
3634 qdict_put_str(snapshot_options
, "driver", "qcow2");
3636 bs_snapshot
= bdrv_open(NULL
, NULL
, snapshot_options
, flags
, errp
);
3637 snapshot_options
= NULL
;
3642 ret
= bdrv_append(bs_snapshot
, bs
, errp
);
3649 qobject_unref(snapshot_options
);
3650 g_free(tmp_filename
);
3655 * Opens a disk image (raw, qcow2, vmdk, ...)
3657 * options is a QDict of options to pass to the block drivers, or NULL for an
3658 * empty set of options. The reference to the QDict belongs to the block layer
3659 * after the call (even on failure), so if the caller intends to reuse the
3660 * dictionary, it needs to use qobject_ref() before calling bdrv_open.
3662 * If *pbs is NULL, a new BDS will be created with a pointer to it stored there.
3663 * If it is not NULL, the referenced BDS will be reused.
3665 * The reference parameter may be used to specify an existing block device which
3666 * should be opened. If specified, neither options nor a filename may be given,
3667 * nor can an existing BDS be reused (that is, *pbs has to be NULL).
3669 static BlockDriverState
*bdrv_open_inherit(const char *filename
,
3670 const char *reference
,
3671 QDict
*options
, int flags
,
3672 BlockDriverState
*parent
,
3673 const BdrvChildClass
*child_class
,
3674 BdrvChildRole child_role
,
3678 BlockBackend
*file
= NULL
;
3679 BlockDriverState
*bs
;
3680 BlockDriver
*drv
= NULL
;
3682 const char *drvname
;
3683 const char *backing
;
3684 Error
*local_err
= NULL
;
3685 QDict
*snapshot_options
= NULL
;
3686 int snapshot_flags
= 0;
3688 assert(!child_class
|| !flags
);
3689 assert(!child_class
== !parent
);
3692 bool options_non_empty
= options
? qdict_size(options
) : false;
3693 qobject_unref(options
);
3695 if (filename
|| options_non_empty
) {
3696 error_setg(errp
, "Cannot reference an existing block device with "
3697 "additional options or a new filename");
3701 bs
= bdrv_lookup_bs(reference
, reference
, errp
);
3712 /* NULL means an empty set of options */
3713 if (options
== NULL
) {
3714 options
= qdict_new();
3717 /* json: syntax counts as explicit options, as if in the QDict */
3718 parse_json_protocol(options
, &filename
, &local_err
);
3723 bs
->explicit_options
= qdict_clone_shallow(options
);
3726 bool parent_is_format
;
3729 parent_is_format
= parent
->drv
->is_format
;
3732 * parent->drv is not set yet because this node is opened for
3733 * (potential) format probing. That means that @parent is going
3734 * to be a format node.
3736 parent_is_format
= true;
3739 bs
->inherits_from
= parent
;
3740 child_class
->inherit_options(child_role
, parent_is_format
,
3742 parent
->open_flags
, parent
->options
);
3745 ret
= bdrv_fill_options(&options
, filename
, &flags
, &local_err
);
3751 * Set the BDRV_O_RDWR and BDRV_O_ALLOW_RDWR flags.
3752 * Caution: getting a boolean member of @options requires care.
3753 * When @options come from -blockdev or blockdev_add, members are
3754 * typed according to the QAPI schema, but when they come from
3755 * -drive, they're all QString.
3757 if (g_strcmp0(qdict_get_try_str(options
, BDRV_OPT_READ_ONLY
), "on") &&
3758 !qdict_get_try_bool(options
, BDRV_OPT_READ_ONLY
, false)) {
3759 flags
|= (BDRV_O_RDWR
| BDRV_O_ALLOW_RDWR
);
3761 flags
&= ~BDRV_O_RDWR
;
3764 if (flags
& BDRV_O_SNAPSHOT
) {
3765 snapshot_options
= qdict_new();
3766 bdrv_temp_snapshot_options(&snapshot_flags
, snapshot_options
,
3768 /* Let bdrv_backing_options() override "read-only" */
3769 qdict_del(options
, BDRV_OPT_READ_ONLY
);
3770 bdrv_inherited_options(BDRV_CHILD_COW
, true,
3771 &flags
, options
, flags
, options
);
3774 bs
->open_flags
= flags
;
3775 bs
->options
= options
;
3776 options
= qdict_clone_shallow(options
);
3778 /* Find the right image format driver */
3779 /* See cautionary note on accessing @options above */
3780 drvname
= qdict_get_try_str(options
, "driver");
3782 drv
= bdrv_find_format(drvname
);
3784 error_setg(errp
, "Unknown driver: '%s'", drvname
);
3789 assert(drvname
|| !(flags
& BDRV_O_PROTOCOL
));
3791 /* See cautionary note on accessing @options above */
3792 backing
= qdict_get_try_str(options
, "backing");
3793 if (qobject_to(QNull
, qdict_get(options
, "backing")) != NULL
||
3794 (backing
&& *backing
== '\0'))
3797 warn_report("Use of \"backing\": \"\" is deprecated; "
3798 "use \"backing\": null instead");
3800 flags
|= BDRV_O_NO_BACKING
;
3801 qdict_del(bs
->explicit_options
, "backing");
3802 qdict_del(bs
->options
, "backing");
3803 qdict_del(options
, "backing");
3806 /* Open image file without format layer. This BlockBackend is only used for
3807 * probing, the block drivers will do their own bdrv_open_child() for the
3808 * same BDS, which is why we put the node name back into options. */
3809 if ((flags
& BDRV_O_PROTOCOL
) == 0) {
3810 BlockDriverState
*file_bs
;
3812 file_bs
= bdrv_open_child_bs(filename
, options
, "file", bs
,
3813 &child_of_bds
, BDRV_CHILD_IMAGE
,
3818 if (file_bs
!= NULL
) {
3819 /* Not requesting BLK_PERM_CONSISTENT_READ because we're only
3820 * looking at the header to guess the image format. This works even
3821 * in cases where a guest would not see a consistent state. */
3822 file
= blk_new(bdrv_get_aio_context(file_bs
), 0, BLK_PERM_ALL
);
3823 blk_insert_bs(file
, file_bs
, &local_err
);
3824 bdrv_unref(file_bs
);
3829 qdict_put_str(options
, "file", bdrv_get_node_name(file_bs
));
3833 /* Image format probing */
3836 ret
= find_image_format(file
, filename
, &drv
, &local_err
);
3841 * This option update would logically belong in bdrv_fill_options(),
3842 * but we first need to open bs->file for the probing to work, while
3843 * opening bs->file already requires the (mostly) final set of options
3844 * so that cache mode etc. can be inherited.
3846 * Adding the driver later is somewhat ugly, but it's not an option
3847 * that would ever be inherited, so it's correct. We just need to make
3848 * sure to update both bs->options (which has the full effective
3849 * options for bs) and options (which has file.* already removed).
3851 qdict_put_str(bs
->options
, "driver", drv
->format_name
);
3852 qdict_put_str(options
, "driver", drv
->format_name
);
3854 error_setg(errp
, "Must specify either driver or file");
3858 /* BDRV_O_PROTOCOL must be set iff a protocol BDS is about to be created */
3859 assert(!!(flags
& BDRV_O_PROTOCOL
) == !!drv
->bdrv_file_open
);
3860 /* file must be NULL if a protocol BDS is about to be created
3861 * (the inverse results in an error message from bdrv_open_common()) */
3862 assert(!(flags
& BDRV_O_PROTOCOL
) || !file
);
3864 /* Open the image */
3865 ret
= bdrv_open_common(bs
, file
, options
, &local_err
);
3875 /* If there is a backing file, use it */
3876 if ((flags
& BDRV_O_NO_BACKING
) == 0) {
3877 ret
= bdrv_open_backing_file(bs
, options
, "backing", &local_err
);
3879 goto close_and_fail
;
3883 /* Remove all children options and references
3884 * from bs->options and bs->explicit_options */
3885 QLIST_FOREACH(child
, &bs
->children
, next
) {
3886 char *child_key_dot
;
3887 child_key_dot
= g_strdup_printf("%s.", child
->name
);
3888 qdict_extract_subqdict(bs
->explicit_options
, NULL
, child_key_dot
);
3889 qdict_extract_subqdict(bs
->options
, NULL
, child_key_dot
);
3890 qdict_del(bs
->explicit_options
, child
->name
);
3891 qdict_del(bs
->options
, child
->name
);
3892 g_free(child_key_dot
);
3895 /* Check if any unknown options were used */
3896 if (qdict_size(options
) != 0) {
3897 const QDictEntry
*entry
= qdict_first(options
);
3898 if (flags
& BDRV_O_PROTOCOL
) {
3899 error_setg(errp
, "Block protocol '%s' doesn't support the option "
3900 "'%s'", drv
->format_name
, entry
->key
);
3903 "Block format '%s' does not support the option '%s'",
3904 drv
->format_name
, entry
->key
);
3907 goto close_and_fail
;
3910 bdrv_parent_cb_change_media(bs
, true);
3912 qobject_unref(options
);
3915 /* For snapshot=on, create a temporary qcow2 overlay. bs points to the
3916 * temporary snapshot afterwards. */
3917 if (snapshot_flags
) {
3918 BlockDriverState
*snapshot_bs
;
3919 snapshot_bs
= bdrv_append_temp_snapshot(bs
, snapshot_flags
,
3920 snapshot_options
, &local_err
);
3921 snapshot_options
= NULL
;
3923 goto close_and_fail
;
3925 /* We are not going to return bs but the overlay on top of it
3926 * (snapshot_bs); thus, we have to drop the strong reference to bs
3927 * (which we obtained by calling bdrv_new()). bs will not be deleted,
3928 * though, because the overlay still has a reference to it. */
3937 qobject_unref(snapshot_options
);
3938 qobject_unref(bs
->explicit_options
);
3939 qobject_unref(bs
->options
);
3940 qobject_unref(options
);
3942 bs
->explicit_options
= NULL
;
3944 error_propagate(errp
, local_err
);
3949 qobject_unref(snapshot_options
);
3950 qobject_unref(options
);
3951 error_propagate(errp
, local_err
);
3955 BlockDriverState
*bdrv_open(const char *filename
, const char *reference
,
3956 QDict
*options
, int flags
, Error
**errp
)
3958 return bdrv_open_inherit(filename
, reference
, options
, flags
, NULL
,
3962 /* Return true if the NULL-terminated @list contains @str */
3963 static bool is_str_in_list(const char *str
, const char *const *list
)
3967 for (i
= 0; list
[i
] != NULL
; i
++) {
3968 if (!strcmp(str
, list
[i
])) {
3977 * Check that every option set in @bs->options is also set in
3980 * Options listed in the common_options list and in
3981 * @bs->drv->mutable_opts are skipped.
3983 * Return 0 on success, otherwise return -EINVAL and set @errp.
3985 static int bdrv_reset_options_allowed(BlockDriverState
*bs
,
3986 const QDict
*new_opts
, Error
**errp
)
3988 const QDictEntry
*e
;
3989 /* These options are common to all block drivers and are handled
3990 * in bdrv_reopen_prepare() so they can be left out of @new_opts */
3991 const char *const common_options
[] = {
3992 "node-name", "discard", "cache.direct", "cache.no-flush",
3993 "read-only", "auto-read-only", "detect-zeroes", NULL
3996 for (e
= qdict_first(bs
->options
); e
; e
= qdict_next(bs
->options
, e
)) {
3997 if (!qdict_haskey(new_opts
, e
->key
) &&
3998 !is_str_in_list(e
->key
, common_options
) &&
3999 !is_str_in_list(e
->key
, bs
->drv
->mutable_opts
)) {
4000 error_setg(errp
, "Option '%s' cannot be reset "
4001 "to its default value", e
->key
);
4010 * Returns true if @child can be reached recursively from @bs
4012 static bool bdrv_recurse_has_child(BlockDriverState
*bs
,
4013 BlockDriverState
*child
)
4021 QLIST_FOREACH(c
, &bs
->children
, next
) {
4022 if (bdrv_recurse_has_child(c
->bs
, child
)) {
4031 * Adds a BlockDriverState to a simple queue for an atomic, transactional
4032 * reopen of multiple devices.
4034 * bs_queue can either be an existing BlockReopenQueue that has had QTAILQ_INIT
4035 * already performed, or alternatively may be NULL a new BlockReopenQueue will
4036 * be created and initialized. This newly created BlockReopenQueue should be
4037 * passed back in for subsequent calls that are intended to be of the same
4040 * bs is the BlockDriverState to add to the reopen queue.
4042 * options contains the changed options for the associated bs
4043 * (the BlockReopenQueue takes ownership)
4045 * flags contains the open flags for the associated bs
4047 * returns a pointer to bs_queue, which is either the newly allocated
4048 * bs_queue, or the existing bs_queue being used.
4050 * bs must be drained between bdrv_reopen_queue() and bdrv_reopen_multiple().
4052 static BlockReopenQueue
*bdrv_reopen_queue_child(BlockReopenQueue
*bs_queue
,
4053 BlockDriverState
*bs
,
4055 const BdrvChildClass
*klass
,
4057 bool parent_is_format
,
4058 QDict
*parent_options
,
4064 BlockReopenQueueEntry
*bs_entry
;
4066 QDict
*old_options
, *explicit_options
, *options_copy
;
4070 /* Make sure that the caller remembered to use a drained section. This is
4071 * important to avoid graph changes between the recursive queuing here and
4072 * bdrv_reopen_multiple(). */
4073 assert(bs
->quiesce_counter
> 0);
4075 if (bs_queue
== NULL
) {
4076 bs_queue
= g_new0(BlockReopenQueue
, 1);
4077 QTAILQ_INIT(bs_queue
);
4081 options
= qdict_new();
4084 /* Check if this BlockDriverState is already in the queue */
4085 QTAILQ_FOREACH(bs_entry
, bs_queue
, entry
) {
4086 if (bs
== bs_entry
->state
.bs
) {
4092 * Precedence of options:
4093 * 1. Explicitly passed in options (highest)
4094 * 2. Retained from explicitly set options of bs
4095 * 3. Inherited from parent node
4096 * 4. Retained from effective options of bs
4099 /* Old explicitly set values (don't overwrite by inherited value) */
4100 if (bs_entry
|| keep_old_opts
) {
4101 old_options
= qdict_clone_shallow(bs_entry
?
4102 bs_entry
->state
.explicit_options
:
4103 bs
->explicit_options
);
4104 bdrv_join_options(bs
, options
, old_options
);
4105 qobject_unref(old_options
);
4108 explicit_options
= qdict_clone_shallow(options
);
4110 /* Inherit from parent node */
4111 if (parent_options
) {
4113 klass
->inherit_options(role
, parent_is_format
, &flags
, options
,
4114 parent_flags
, parent_options
);
4116 flags
= bdrv_get_flags(bs
);
4119 if (keep_old_opts
) {
4120 /* Old values are used for options that aren't set yet */
4121 old_options
= qdict_clone_shallow(bs
->options
);
4122 bdrv_join_options(bs
, options
, old_options
);
4123 qobject_unref(old_options
);
4126 /* We have the final set of options so let's update the flags */
4127 options_copy
= qdict_clone_shallow(options
);
4128 opts
= qemu_opts_create(&bdrv_runtime_opts
, NULL
, 0, &error_abort
);
4129 qemu_opts_absorb_qdict(opts
, options_copy
, NULL
);
4130 update_flags_from_options(&flags
, opts
);
4131 qemu_opts_del(opts
);
4132 qobject_unref(options_copy
);
4134 /* bdrv_open_inherit() sets and clears some additional flags internally */
4135 flags
&= ~BDRV_O_PROTOCOL
;
4136 if (flags
& BDRV_O_RDWR
) {
4137 flags
|= BDRV_O_ALLOW_RDWR
;
4141 bs_entry
= g_new0(BlockReopenQueueEntry
, 1);
4142 QTAILQ_INSERT_TAIL(bs_queue
, bs_entry
, entry
);
4144 qobject_unref(bs_entry
->state
.options
);
4145 qobject_unref(bs_entry
->state
.explicit_options
);
4148 bs_entry
->state
.bs
= bs
;
4149 bs_entry
->state
.options
= options
;
4150 bs_entry
->state
.explicit_options
= explicit_options
;
4151 bs_entry
->state
.flags
= flags
;
4154 * If keep_old_opts is false then it means that unspecified
4155 * options must be reset to their original value. We don't allow
4156 * resetting 'backing' but we need to know if the option is
4157 * missing in order to decide if we have to return an error.
4159 if (!keep_old_opts
) {
4160 bs_entry
->state
.backing_missing
=
4161 !qdict_haskey(options
, "backing") &&
4162 !qdict_haskey(options
, "backing.driver");
4165 QLIST_FOREACH(child
, &bs
->children
, next
) {
4166 QDict
*new_child_options
= NULL
;
4167 bool child_keep_old
= keep_old_opts
;
4169 /* reopen can only change the options of block devices that were
4170 * implicitly created and inherited options. For other (referenced)
4171 * block devices, a syntax like "backing.foo" results in an error. */
4172 if (child
->bs
->inherits_from
!= bs
) {
4176 /* Check if the options contain a child reference */
4177 if (qdict_haskey(options
, child
->name
)) {
4178 const char *childref
= qdict_get_try_str(options
, child
->name
);
4180 * The current child must not be reopened if the child
4181 * reference is null or points to a different node.
4183 if (g_strcmp0(childref
, child
->bs
->node_name
)) {
4187 * If the child reference points to the current child then
4188 * reopen it with its existing set of options (note that
4189 * it can still inherit new options from the parent).
4191 child_keep_old
= true;
4193 /* Extract child options ("child-name.*") */
4194 char *child_key_dot
= g_strdup_printf("%s.", child
->name
);
4195 qdict_extract_subqdict(explicit_options
, NULL
, child_key_dot
);
4196 qdict_extract_subqdict(options
, &new_child_options
, child_key_dot
);
4197 g_free(child_key_dot
);
4200 bdrv_reopen_queue_child(bs_queue
, child
->bs
, new_child_options
,
4201 child
->klass
, child
->role
, bs
->drv
->is_format
,
4202 options
, flags
, child_keep_old
);
4208 BlockReopenQueue
*bdrv_reopen_queue(BlockReopenQueue
*bs_queue
,
4209 BlockDriverState
*bs
,
4210 QDict
*options
, bool keep_old_opts
)
4212 return bdrv_reopen_queue_child(bs_queue
, bs
, options
, NULL
, 0, false,
4213 NULL
, 0, keep_old_opts
);
4216 void bdrv_reopen_queue_free(BlockReopenQueue
*bs_queue
)
4219 BlockReopenQueueEntry
*bs_entry
, *next
;
4220 QTAILQ_FOREACH_SAFE(bs_entry
, bs_queue
, entry
, next
) {
4221 qobject_unref(bs_entry
->state
.explicit_options
);
4222 qobject_unref(bs_entry
->state
.options
);
4230 * Reopen multiple BlockDriverStates atomically & transactionally.
4232 * The queue passed in (bs_queue) must have been built up previous
4233 * via bdrv_reopen_queue().
4235 * Reopens all BDS specified in the queue, with the appropriate
4236 * flags. All devices are prepared for reopen, and failure of any
4237 * device will cause all device changes to be abandoned, and intermediate
4240 * If all devices prepare successfully, then the changes are committed
4243 * All affected nodes must be drained between bdrv_reopen_queue() and
4244 * bdrv_reopen_multiple().
4246 * To be called from the main thread, with all other AioContexts unlocked.
4248 int bdrv_reopen_multiple(BlockReopenQueue
*bs_queue
, Error
**errp
)
4251 BlockReopenQueueEntry
*bs_entry
, *next
;
4253 Transaction
*tran
= tran_new();
4254 g_autoptr(GHashTable
) found
= NULL
;
4255 g_autoptr(GSList
) refresh_list
= NULL
;
4257 assert(qemu_get_current_aio_context() == qemu_get_aio_context());
4258 assert(bs_queue
!= NULL
);
4260 QTAILQ_FOREACH(bs_entry
, bs_queue
, entry
) {
4261 ctx
= bdrv_get_aio_context(bs_entry
->state
.bs
);
4262 aio_context_acquire(ctx
);
4263 ret
= bdrv_flush(bs_entry
->state
.bs
);
4264 aio_context_release(ctx
);
4266 error_setg_errno(errp
, -ret
, "Error flushing drive");
4271 QTAILQ_FOREACH(bs_entry
, bs_queue
, entry
) {
4272 assert(bs_entry
->state
.bs
->quiesce_counter
> 0);
4273 ctx
= bdrv_get_aio_context(bs_entry
->state
.bs
);
4274 aio_context_acquire(ctx
);
4275 ret
= bdrv_reopen_prepare(&bs_entry
->state
, bs_queue
, tran
, errp
);
4276 aio_context_release(ctx
);
4280 bs_entry
->prepared
= true;
4283 found
= g_hash_table_new(NULL
, NULL
);
4284 QTAILQ_FOREACH(bs_entry
, bs_queue
, entry
) {
4285 BDRVReopenState
*state
= &bs_entry
->state
;
4287 refresh_list
= bdrv_topological_dfs(refresh_list
, found
, state
->bs
);
4288 if (state
->old_backing_bs
) {
4289 refresh_list
= bdrv_topological_dfs(refresh_list
, found
,
4290 state
->old_backing_bs
);
4292 if (state
->old_file_bs
) {
4293 refresh_list
= bdrv_topological_dfs(refresh_list
, found
,
4294 state
->old_file_bs
);
4299 * Note that file-posix driver rely on permission update done during reopen
4300 * (even if no permission changed), because it wants "new" permissions for
4301 * reconfiguring the fd and that's why it does it in raw_check_perm(), not
4302 * in raw_reopen_prepare() which is called with "old" permissions.
4304 ret
= bdrv_list_refresh_perms(refresh_list
, bs_queue
, tran
, errp
);
4310 * If we reach this point, we have success and just need to apply the
4313 * Reverse order is used to comfort qcow2 driver: on commit it need to write
4314 * IN_USE flag to the image, to mark bitmaps in the image as invalid. But
4315 * children are usually goes after parents in reopen-queue, so go from last
4318 QTAILQ_FOREACH_REVERSE(bs_entry
, bs_queue
, entry
) {
4319 ctx
= bdrv_get_aio_context(bs_entry
->state
.bs
);
4320 aio_context_acquire(ctx
);
4321 bdrv_reopen_commit(&bs_entry
->state
);
4322 aio_context_release(ctx
);
4327 QTAILQ_FOREACH_REVERSE(bs_entry
, bs_queue
, entry
) {
4328 BlockDriverState
*bs
= bs_entry
->state
.bs
;
4330 if (bs
->drv
->bdrv_reopen_commit_post
) {
4331 ctx
= bdrv_get_aio_context(bs
);
4332 aio_context_acquire(ctx
);
4333 bs
->drv
->bdrv_reopen_commit_post(&bs_entry
->state
);
4334 aio_context_release(ctx
);
4343 QTAILQ_FOREACH_SAFE(bs_entry
, bs_queue
, entry
, next
) {
4344 if (bs_entry
->prepared
) {
4345 ctx
= bdrv_get_aio_context(bs_entry
->state
.bs
);
4346 aio_context_acquire(ctx
);
4347 bdrv_reopen_abort(&bs_entry
->state
);
4348 aio_context_release(ctx
);
4353 bdrv_reopen_queue_free(bs_queue
);
4358 int bdrv_reopen(BlockDriverState
*bs
, QDict
*opts
, bool keep_old_opts
,
4361 AioContext
*ctx
= bdrv_get_aio_context(bs
);
4362 BlockReopenQueue
*queue
;
4365 bdrv_subtree_drained_begin(bs
);
4366 if (ctx
!= qemu_get_aio_context()) {
4367 aio_context_release(ctx
);
4370 queue
= bdrv_reopen_queue(NULL
, bs
, opts
, keep_old_opts
);
4371 ret
= bdrv_reopen_multiple(queue
, errp
);
4373 if (ctx
!= qemu_get_aio_context()) {
4374 aio_context_acquire(ctx
);
4376 bdrv_subtree_drained_end(bs
);
4381 int bdrv_reopen_set_read_only(BlockDriverState
*bs
, bool read_only
,
4384 QDict
*opts
= qdict_new();
4386 qdict_put_bool(opts
, BDRV_OPT_READ_ONLY
, read_only
);
4388 return bdrv_reopen(bs
, opts
, true, errp
);
4392 * Take a BDRVReopenState and check if the value of 'backing' in the
4393 * reopen_state->options QDict is valid or not.
4395 * If 'backing' is missing from the QDict then return 0.
4397 * If 'backing' contains the node name of the backing file of
4398 * reopen_state->bs then return 0.
4400 * If 'backing' contains a different node name (or is null) then check
4401 * whether the current backing file can be replaced with the new one.
4402 * If that's the case then reopen_state->replace_backing_bs is set to
4403 * true and reopen_state->new_backing_bs contains a pointer to the new
4404 * backing BlockDriverState (or NULL).
4406 * Return 0 on success, otherwise return < 0 and set @errp.
4408 static int bdrv_reopen_parse_file_or_backing(BDRVReopenState
*reopen_state
,
4409 bool is_backing
, Transaction
*tran
,
4412 BlockDriverState
*bs
= reopen_state
->bs
;
4413 BlockDriverState
*new_child_bs
;
4414 BlockDriverState
*old_child_bs
= is_backing
? child_bs(bs
->backing
) :
4416 const char *child_name
= is_backing
? "backing" : "file";
4420 value
= qdict_get(reopen_state
->options
, child_name
);
4421 if (value
== NULL
) {
4425 switch (qobject_type(value
)) {
4427 assert(is_backing
); /* The 'file' option does not allow a null value */
4428 new_child_bs
= NULL
;
4431 str
= qstring_get_str(qobject_to(QString
, value
));
4432 new_child_bs
= bdrv_lookup_bs(NULL
, str
, errp
);
4433 if (new_child_bs
== NULL
) {
4435 } else if (bdrv_recurse_has_child(new_child_bs
, bs
)) {
4436 error_setg(errp
, "Making '%s' a %s child of '%s' would create a "
4437 "cycle", str
, child_name
, bs
->node_name
);
4443 * The options QDict has been flattened, so 'backing' and 'file'
4444 * do not allow any other data type here.
4446 g_assert_not_reached();
4449 if (old_child_bs
== new_child_bs
) {
4454 if (bdrv_skip_implicit_filters(old_child_bs
) == new_child_bs
) {
4458 if (old_child_bs
->implicit
) {
4459 error_setg(errp
, "Cannot replace implicit %s child of %s",
4460 child_name
, bs
->node_name
);
4465 if (bs
->drv
->is_filter
&& !old_child_bs
) {
4467 * Filters always have a file or a backing child, so we are trying to
4468 * change wrong child
4470 error_setg(errp
, "'%s' is a %s filter node that does not support a "
4471 "%s child", bs
->node_name
, bs
->drv
->format_name
, child_name
);
4476 reopen_state
->old_backing_bs
= old_child_bs
;
4478 reopen_state
->old_file_bs
= old_child_bs
;
4481 return bdrv_set_file_or_backing_noperm(bs
, new_child_bs
, is_backing
,
4486 * Prepares a BlockDriverState for reopen. All changes are staged in the
4487 * 'opaque' field of the BDRVReopenState, which is used and allocated by
4488 * the block driver layer .bdrv_reopen_prepare()
4490 * bs is the BlockDriverState to reopen
4491 * flags are the new open flags
4492 * queue is the reopen queue
4494 * Returns 0 on success, non-zero on error. On error errp will be set
4497 * On failure, bdrv_reopen_abort() will be called to clean up any data.
4498 * It is the responsibility of the caller to then call the abort() or
4499 * commit() for any other BDS that have been left in a prepare() state
4502 static int bdrv_reopen_prepare(BDRVReopenState
*reopen_state
,
4503 BlockReopenQueue
*queue
,
4504 Transaction
*change_child_tran
, Error
**errp
)
4508 Error
*local_err
= NULL
;
4511 QDict
*orig_reopen_opts
;
4512 char *discard
= NULL
;
4514 bool drv_prepared
= false;
4516 assert(reopen_state
!= NULL
);
4517 assert(reopen_state
->bs
->drv
!= NULL
);
4518 drv
= reopen_state
->bs
->drv
;
4520 /* This function and each driver's bdrv_reopen_prepare() remove
4521 * entries from reopen_state->options as they are processed, so
4522 * we need to make a copy of the original QDict. */
4523 orig_reopen_opts
= qdict_clone_shallow(reopen_state
->options
);
4525 /* Process generic block layer options */
4526 opts
= qemu_opts_create(&bdrv_runtime_opts
, NULL
, 0, &error_abort
);
4527 if (!qemu_opts_absorb_qdict(opts
, reopen_state
->options
, errp
)) {
4532 /* This was already called in bdrv_reopen_queue_child() so the flags
4533 * are up-to-date. This time we simply want to remove the options from
4534 * QemuOpts in order to indicate that they have been processed. */
4535 old_flags
= reopen_state
->flags
;
4536 update_flags_from_options(&reopen_state
->flags
, opts
);
4537 assert(old_flags
== reopen_state
->flags
);
4539 discard
= qemu_opt_get_del(opts
, BDRV_OPT_DISCARD
);
4540 if (discard
!= NULL
) {
4541 if (bdrv_parse_discard_flags(discard
, &reopen_state
->flags
) != 0) {
4542 error_setg(errp
, "Invalid discard option");
4548 reopen_state
->detect_zeroes
=
4549 bdrv_parse_detect_zeroes(opts
, reopen_state
->flags
, &local_err
);
4551 error_propagate(errp
, local_err
);
4556 /* All other options (including node-name and driver) must be unchanged.
4557 * Put them back into the QDict, so that they are checked at the end
4558 * of this function. */
4559 qemu_opts_to_qdict(opts
, reopen_state
->options
);
4561 /* If we are to stay read-only, do not allow permission change
4562 * to r/w. Attempting to set to r/w may fail if either BDRV_O_ALLOW_RDWR is
4563 * not set, or if the BDS still has copy_on_read enabled */
4564 read_only
= !(reopen_state
->flags
& BDRV_O_RDWR
);
4565 ret
= bdrv_can_set_read_only(reopen_state
->bs
, read_only
, true, &local_err
);
4567 error_propagate(errp
, local_err
);
4571 if (drv
->bdrv_reopen_prepare
) {
4573 * If a driver-specific option is missing, it means that we
4574 * should reset it to its default value.
4575 * But not all options allow that, so we need to check it first.
4577 ret
= bdrv_reset_options_allowed(reopen_state
->bs
,
4578 reopen_state
->options
, errp
);
4583 ret
= drv
->bdrv_reopen_prepare(reopen_state
, queue
, &local_err
);
4585 if (local_err
!= NULL
) {
4586 error_propagate(errp
, local_err
);
4588 bdrv_refresh_filename(reopen_state
->bs
);
4589 error_setg(errp
, "failed while preparing to reopen image '%s'",
4590 reopen_state
->bs
->filename
);
4595 /* It is currently mandatory to have a bdrv_reopen_prepare()
4596 * handler for each supported drv. */
4597 error_setg(errp
, "Block format '%s' used by node '%s' "
4598 "does not support reopening files", drv
->format_name
,
4599 bdrv_get_device_or_node_name(reopen_state
->bs
));
4604 drv_prepared
= true;
4607 * We must provide the 'backing' option if the BDS has a backing
4608 * file or if the image file has a backing file name as part of
4609 * its metadata. Otherwise the 'backing' option can be omitted.
4611 if (drv
->supports_backing
&& reopen_state
->backing_missing
&&
4612 (reopen_state
->bs
->backing
|| reopen_state
->bs
->backing_file
[0])) {
4613 error_setg(errp
, "backing is missing for '%s'",
4614 reopen_state
->bs
->node_name
);
4620 * Allow changing the 'backing' option. The new value can be
4621 * either a reference to an existing node (using its node name)
4622 * or NULL to simply detach the current backing file.
4624 ret
= bdrv_reopen_parse_file_or_backing(reopen_state
, true,
4625 change_child_tran
, errp
);
4629 qdict_del(reopen_state
->options
, "backing");
4631 /* Allow changing the 'file' option. In this case NULL is not allowed */
4632 ret
= bdrv_reopen_parse_file_or_backing(reopen_state
, false,
4633 change_child_tran
, errp
);
4637 qdict_del(reopen_state
->options
, "file");
4639 /* Options that are not handled are only okay if they are unchanged
4640 * compared to the old state. It is expected that some options are only
4641 * used for the initial open, but not reopen (e.g. filename) */
4642 if (qdict_size(reopen_state
->options
)) {
4643 const QDictEntry
*entry
= qdict_first(reopen_state
->options
);
4646 QObject
*new = entry
->value
;
4647 QObject
*old
= qdict_get(reopen_state
->bs
->options
, entry
->key
);
4649 /* Allow child references (child_name=node_name) as long as they
4650 * point to the current child (i.e. everything stays the same). */
4651 if (qobject_type(new) == QTYPE_QSTRING
) {
4653 QLIST_FOREACH(child
, &reopen_state
->bs
->children
, next
) {
4654 if (!strcmp(child
->name
, entry
->key
)) {
4660 if (!strcmp(child
->bs
->node_name
,
4661 qstring_get_str(qobject_to(QString
, new)))) {
4662 continue; /* Found child with this name, skip option */
4668 * TODO: When using -drive to specify blockdev options, all values
4669 * will be strings; however, when using -blockdev, blockdev-add or
4670 * filenames using the json:{} pseudo-protocol, they will be
4672 * In contrast, reopening options are (currently) always strings
4673 * (because you can only specify them through qemu-io; all other
4674 * callers do not specify any options).
4675 * Therefore, when using anything other than -drive to create a BDS,
4676 * this cannot detect non-string options as unchanged, because
4677 * qobject_is_equal() always returns false for objects of different
4678 * type. In the future, this should be remedied by correctly typing
4679 * all options. For now, this is not too big of an issue because
4680 * the user can simply omit options which cannot be changed anyway,
4681 * so they will stay unchanged.
4683 if (!qobject_is_equal(new, old
)) {
4684 error_setg(errp
, "Cannot change the option '%s'", entry
->key
);
4688 } while ((entry
= qdict_next(reopen_state
->options
, entry
)));
4693 /* Restore the original reopen_state->options QDict */
4694 qobject_unref(reopen_state
->options
);
4695 reopen_state
->options
= qobject_ref(orig_reopen_opts
);
4698 if (ret
< 0 && drv_prepared
) {
4699 /* drv->bdrv_reopen_prepare() has succeeded, so we need to
4700 * call drv->bdrv_reopen_abort() before signaling an error
4701 * (bdrv_reopen_multiple() will not call bdrv_reopen_abort()
4702 * when the respective bdrv_reopen_prepare() has failed) */
4703 if (drv
->bdrv_reopen_abort
) {
4704 drv
->bdrv_reopen_abort(reopen_state
);
4707 qemu_opts_del(opts
);
4708 qobject_unref(orig_reopen_opts
);
4714 * Takes the staged changes for the reopen from bdrv_reopen_prepare(), and
4715 * makes them final by swapping the staging BlockDriverState contents into
4716 * the active BlockDriverState contents.
4718 static void bdrv_reopen_commit(BDRVReopenState
*reopen_state
)
4721 BlockDriverState
*bs
;
4724 assert(reopen_state
!= NULL
);
4725 bs
= reopen_state
->bs
;
4727 assert(drv
!= NULL
);
4729 /* If there are any driver level actions to take */
4730 if (drv
->bdrv_reopen_commit
) {
4731 drv
->bdrv_reopen_commit(reopen_state
);
4734 /* set BDS specific flags now */
4735 qobject_unref(bs
->explicit_options
);
4736 qobject_unref(bs
->options
);
4737 qobject_ref(reopen_state
->explicit_options
);
4738 qobject_ref(reopen_state
->options
);
4740 bs
->explicit_options
= reopen_state
->explicit_options
;
4741 bs
->options
= reopen_state
->options
;
4742 bs
->open_flags
= reopen_state
->flags
;
4743 bs
->detect_zeroes
= reopen_state
->detect_zeroes
;
4745 /* Remove child references from bs->options and bs->explicit_options.
4746 * Child options were already removed in bdrv_reopen_queue_child() */
4747 QLIST_FOREACH(child
, &bs
->children
, next
) {
4748 qdict_del(bs
->explicit_options
, child
->name
);
4749 qdict_del(bs
->options
, child
->name
);
4751 /* backing is probably removed, so it's not handled by previous loop */
4752 qdict_del(bs
->explicit_options
, "backing");
4753 qdict_del(bs
->options
, "backing");
4755 bdrv_refresh_limits(bs
, NULL
, NULL
);
4759 * Abort the reopen, and delete and free the staged changes in
4762 static void bdrv_reopen_abort(BDRVReopenState
*reopen_state
)
4766 assert(reopen_state
!= NULL
);
4767 drv
= reopen_state
->bs
->drv
;
4768 assert(drv
!= NULL
);
4770 if (drv
->bdrv_reopen_abort
) {
4771 drv
->bdrv_reopen_abort(reopen_state
);
4776 static void bdrv_close(BlockDriverState
*bs
)
4778 BdrvAioNotifier
*ban
, *ban_next
;
4779 BdrvChild
*child
, *next
;
4781 assert(!bs
->refcnt
);
4783 bdrv_drained_begin(bs
); /* complete I/O */
4785 bdrv_drain(bs
); /* in case flush left pending I/O */
4788 if (bs
->drv
->bdrv_close
) {
4789 /* Must unfreeze all children, so bdrv_unref_child() works */
4790 bs
->drv
->bdrv_close(bs
);
4795 QLIST_FOREACH_SAFE(child
, &bs
->children
, next
, next
) {
4796 bdrv_unref_child(bs
, child
);
4803 qatomic_set(&bs
->copy_on_read
, 0);
4804 bs
->backing_file
[0] = '\0';
4805 bs
->backing_format
[0] = '\0';
4806 bs
->total_sectors
= 0;
4807 bs
->encrypted
= false;
4809 qobject_unref(bs
->options
);
4810 qobject_unref(bs
->explicit_options
);
4812 bs
->explicit_options
= NULL
;
4813 qobject_unref(bs
->full_open_options
);
4814 bs
->full_open_options
= NULL
;
4815 g_free(bs
->block_status_cache
);
4816 bs
->block_status_cache
= NULL
;
4818 bdrv_release_named_dirty_bitmaps(bs
);
4819 assert(QLIST_EMPTY(&bs
->dirty_bitmaps
));
4821 QLIST_FOREACH_SAFE(ban
, &bs
->aio_notifiers
, list
, ban_next
) {
4824 QLIST_INIT(&bs
->aio_notifiers
);
4825 bdrv_drained_end(bs
);
4828 * If we're still inside some bdrv_drain_all_begin()/end() sections, end
4829 * them now since this BDS won't exist anymore when bdrv_drain_all_end()
4832 if (bs
->quiesce_counter
) {
4833 bdrv_drain_all_end_quiesce(bs
);
4837 void bdrv_close_all(void)
4839 assert(job_next(NULL
) == NULL
);
4841 /* Drop references from requests still in flight, such as canceled block
4842 * jobs whose AIO context has not been polled yet */
4845 blk_remove_all_bs();
4846 blockdev_close_all_bdrv_states();
4848 assert(QTAILQ_EMPTY(&all_bdrv_states
));
4851 static bool should_update_child(BdrvChild
*c
, BlockDriverState
*to
)
4857 if (c
->klass
->stay_at_node
) {
4861 /* If the child @c belongs to the BDS @to, replacing the current
4862 * c->bs by @to would mean to create a loop.
4864 * Such a case occurs when appending a BDS to a backing chain.
4865 * For instance, imagine the following chain:
4867 * guest device -> node A -> further backing chain...
4869 * Now we create a new BDS B which we want to put on top of this
4870 * chain, so we first attach A as its backing node:
4875 * guest device -> node A -> further backing chain...
4877 * Finally we want to replace A by B. When doing that, we want to
4878 * replace all pointers to A by pointers to B -- except for the
4879 * pointer from B because (1) that would create a loop, and (2)
4880 * that pointer should simply stay intact:
4882 * guest device -> node B
4885 * node A -> further backing chain...
4887 * In general, when replacing a node A (c->bs) by a node B (@to),
4888 * if A is a child of B, that means we cannot replace A by B there
4889 * because that would create a loop. Silently detaching A from B
4890 * is also not really an option. So overall just leaving A in
4891 * place there is the most sensible choice.
4893 * We would also create a loop in any cases where @c is only
4894 * indirectly referenced by @to. Prevent this by returning false
4895 * if @c is found (by breadth-first search) anywhere in the whole
4900 found
= g_hash_table_new(NULL
, NULL
);
4901 g_hash_table_add(found
, to
);
4902 queue
= g_queue_new();
4903 g_queue_push_tail(queue
, to
);
4905 while (!g_queue_is_empty(queue
)) {
4906 BlockDriverState
*v
= g_queue_pop_head(queue
);
4909 QLIST_FOREACH(c2
, &v
->children
, next
) {
4915 if (g_hash_table_contains(found
, c2
->bs
)) {
4919 g_queue_push_tail(queue
, c2
->bs
);
4920 g_hash_table_add(found
, c2
->bs
);
4924 g_queue_free(queue
);
4925 g_hash_table_destroy(found
);
4930 typedef struct BdrvRemoveFilterOrCowChild
{
4932 BlockDriverState
*bs
;
4934 } BdrvRemoveFilterOrCowChild
;
4936 static void bdrv_remove_filter_or_cow_child_abort(void *opaque
)
4938 BdrvRemoveFilterOrCowChild
*s
= opaque
;
4939 BlockDriverState
*parent_bs
= s
->child
->opaque
;
4941 if (s
->is_backing
) {
4942 parent_bs
->backing
= s
->child
;
4944 parent_bs
->file
= s
->child
;
4948 * We don't have to restore child->bs here to undo bdrv_replace_child_tran()
4949 * because that function is transactionable and it registered own completion
4950 * entries in @tran, so .abort() for bdrv_replace_child_safe() will be
4951 * called automatically.
4955 static void bdrv_remove_filter_or_cow_child_commit(void *opaque
)
4957 BdrvRemoveFilterOrCowChild
*s
= opaque
;
4959 bdrv_child_free(s
->child
);
4962 static void bdrv_remove_filter_or_cow_child_clean(void *opaque
)
4964 BdrvRemoveFilterOrCowChild
*s
= opaque
;
4966 /* Drop the bs reference after the transaction is done */
4971 static TransactionActionDrv bdrv_remove_filter_or_cow_child_drv
= {
4972 .abort
= bdrv_remove_filter_or_cow_child_abort
,
4973 .commit
= bdrv_remove_filter_or_cow_child_commit
,
4974 .clean
= bdrv_remove_filter_or_cow_child_clean
,
4978 * A function to remove backing or file child of @bs.
4979 * Function doesn't update permissions, caller is responsible for this.
4981 static void bdrv_remove_file_or_backing_child(BlockDriverState
*bs
,
4986 BdrvRemoveFilterOrCowChild
*s
;
4993 * Keep a reference to @bs so @childp will stay valid throughout the
4994 * transaction (required by bdrv_replace_child_tran())
4997 if (child
== bs
->backing
) {
4998 childp
= &bs
->backing
;
4999 } else if (child
== bs
->file
) {
5002 g_assert_not_reached();
5007 * Pass free_empty_child=false, we will free the child in
5008 * bdrv_remove_filter_or_cow_child_commit()
5010 bdrv_replace_child_tran(childp
, NULL
, tran
, false);
5013 s
= g_new(BdrvRemoveFilterOrCowChild
, 1);
5014 *s
= (BdrvRemoveFilterOrCowChild
) {
5017 .is_backing
= (childp
== &bs
->backing
),
5019 tran_add(tran
, &bdrv_remove_filter_or_cow_child_drv
, s
);
5023 * A function to remove backing-chain child of @bs if exists: cow child for
5024 * format nodes (always .backing) and filter child for filters (may be .file or
5027 static void bdrv_remove_filter_or_cow_child(BlockDriverState
*bs
,
5030 bdrv_remove_file_or_backing_child(bs
, bdrv_filter_or_cow_child(bs
), tran
);
5033 static int bdrv_replace_node_noperm(BlockDriverState
*from
,
5034 BlockDriverState
*to
,
5035 bool auto_skip
, Transaction
*tran
,
5038 BdrvChild
*c
, *next
;
5042 QLIST_FOREACH_SAFE(c
, &from
->parents
, next_parent
, next
) {
5043 assert(c
->bs
== from
);
5044 if (!should_update_child(c
, to
)) {
5048 error_setg(errp
, "Should not change '%s' link to '%s'",
5049 c
->name
, from
->node_name
);
5053 error_setg(errp
, "Cannot change '%s' link to '%s'",
5054 c
->name
, from
->node_name
);
5059 * Passing a pointer to the local variable @c is fine here, because
5060 * @to is not NULL, and so &c will not be attached to the transaction.
5062 bdrv_replace_child_tran(&c
, to
, tran
, true);
5069 * With auto_skip=true bdrv_replace_node_common skips updating from parents
5070 * if it creates a parent-child relation loop or if parent is block-job.
5072 * With auto_skip=false the error is returned if from has a parent which should
5075 * With @detach_subchain=true @to must be in a backing chain of @from. In this
5076 * case backing link of the cow-parent of @to is removed.
5078 * @to must not be NULL.
5080 static int bdrv_replace_node_common(BlockDriverState
*from
,
5081 BlockDriverState
*to
,
5082 bool auto_skip
, bool detach_subchain
,
5085 Transaction
*tran
= tran_new();
5086 g_autoptr(GHashTable
) found
= NULL
;
5087 g_autoptr(GSList
) refresh_list
= NULL
;
5088 BlockDriverState
*to_cow_parent
= NULL
;
5093 if (detach_subchain
) {
5094 assert(bdrv_chain_contains(from
, to
));
5096 for (to_cow_parent
= from
;
5097 bdrv_filter_or_cow_bs(to_cow_parent
) != to
;
5098 to_cow_parent
= bdrv_filter_or_cow_bs(to_cow_parent
))
5104 /* Make sure that @from doesn't go away until we have successfully attached
5105 * all of its parents to @to. */
5108 assert(qemu_get_current_aio_context() == qemu_get_aio_context());
5109 assert(bdrv_get_aio_context(from
) == bdrv_get_aio_context(to
));
5110 bdrv_drained_begin(from
);
5113 * Do the replacement without permission update.
5114 * Replacement may influence the permissions, we should calculate new
5115 * permissions based on new graph. If we fail, we'll roll-back the
5118 ret
= bdrv_replace_node_noperm(from
, to
, auto_skip
, tran
, errp
);
5123 if (detach_subchain
) {
5124 bdrv_remove_filter_or_cow_child(to_cow_parent
, tran
);
5127 found
= g_hash_table_new(NULL
, NULL
);
5129 refresh_list
= bdrv_topological_dfs(refresh_list
, found
, to
);
5130 refresh_list
= bdrv_topological_dfs(refresh_list
, found
, from
);
5132 ret
= bdrv_list_refresh_perms(refresh_list
, NULL
, tran
, errp
);
5140 tran_finalize(tran
, ret
);
5142 bdrv_drained_end(from
);
5149 * Replace node @from by @to (where neither may be NULL).
5151 int bdrv_replace_node(BlockDriverState
*from
, BlockDriverState
*to
,
5154 return bdrv_replace_node_common(from
, to
, true, false, errp
);
5157 int bdrv_drop_filter(BlockDriverState
*bs
, Error
**errp
)
5159 return bdrv_replace_node_common(bs
, bdrv_filter_or_cow_bs(bs
), true, true,
5164 * Add new bs contents at the top of an image chain while the chain is
5165 * live, while keeping required fields on the top layer.
5167 * This will modify the BlockDriverState fields, and swap contents
5168 * between bs_new and bs_top. Both bs_new and bs_top are modified.
5170 * bs_new must not be attached to a BlockBackend and must not have backing
5173 * This function does not create any image files.
5175 int bdrv_append(BlockDriverState
*bs_new
, BlockDriverState
*bs_top
,
5179 Transaction
*tran
= tran_new();
5181 assert(!bs_new
->backing
);
5183 ret
= bdrv_attach_child_noperm(bs_new
, bs_top
, "backing",
5184 &child_of_bds
, bdrv_backing_role(bs_new
),
5185 &bs_new
->backing
, tran
, errp
);
5190 ret
= bdrv_replace_node_noperm(bs_top
, bs_new
, true, tran
, errp
);
5195 ret
= bdrv_refresh_perms(bs_new
, errp
);
5197 tran_finalize(tran
, ret
);
5199 bdrv_refresh_limits(bs_top
, NULL
, NULL
);
5204 /* Not for empty child */
5205 int bdrv_replace_child_bs(BdrvChild
*child
, BlockDriverState
*new_bs
,
5209 Transaction
*tran
= tran_new();
5210 g_autoptr(GHashTable
) found
= NULL
;
5211 g_autoptr(GSList
) refresh_list
= NULL
;
5212 BlockDriverState
*old_bs
= child
->bs
;
5215 bdrv_drained_begin(old_bs
);
5216 bdrv_drained_begin(new_bs
);
5218 bdrv_replace_child_tran(&child
, new_bs
, tran
, true);
5219 /* @new_bs must have been non-NULL, so @child must not have been freed */
5220 assert(child
!= NULL
);
5222 found
= g_hash_table_new(NULL
, NULL
);
5223 refresh_list
= bdrv_topological_dfs(refresh_list
, found
, old_bs
);
5224 refresh_list
= bdrv_topological_dfs(refresh_list
, found
, new_bs
);
5226 ret
= bdrv_list_refresh_perms(refresh_list
, NULL
, tran
, errp
);
5228 tran_finalize(tran
, ret
);
5230 bdrv_drained_end(old_bs
);
5231 bdrv_drained_end(new_bs
);
5237 static void bdrv_delete(BlockDriverState
*bs
)
5239 assert(bdrv_op_blocker_is_empty(bs
));
5240 assert(!bs
->refcnt
);
5242 /* remove from list, if necessary */
5243 if (bs
->node_name
[0] != '\0') {
5244 QTAILQ_REMOVE(&graph_bdrv_states
, bs
, node_list
);
5246 QTAILQ_REMOVE(&all_bdrv_states
, bs
, bs_list
);
5255 * Replace @bs by newly created block node.
5257 * @options is a QDict of options to pass to the block drivers, or NULL for an
5258 * empty set of options. The reference to the QDict belongs to the block layer
5259 * after the call (even on failure), so if the caller intends to reuse the
5260 * dictionary, it needs to use qobject_ref() before calling bdrv_open.
5262 BlockDriverState
*bdrv_insert_node(BlockDriverState
*bs
, QDict
*options
,
5263 int flags
, Error
**errp
)
5267 BlockDriverState
*new_node_bs
= NULL
;
5268 const char *drvname
, *node_name
;
5271 drvname
= qdict_get_try_str(options
, "driver");
5273 error_setg(errp
, "driver is not specified");
5277 drv
= bdrv_find_format(drvname
);
5279 error_setg(errp
, "Unknown driver: '%s'", drvname
);
5283 node_name
= qdict_get_try_str(options
, "node-name");
5285 new_node_bs
= bdrv_new_open_driver_opts(drv
, node_name
, options
, flags
,
5287 options
= NULL
; /* bdrv_new_open_driver() eats options */
5289 error_prepend(errp
, "Could not create node: ");
5293 bdrv_drained_begin(bs
);
5294 ret
= bdrv_replace_node(bs
, new_node_bs
, errp
);
5295 bdrv_drained_end(bs
);
5298 error_prepend(errp
, "Could not replace node: ");
5305 qobject_unref(options
);
5306 bdrv_unref(new_node_bs
);
5311 * Run consistency checks on an image
5313 * Returns 0 if the check could be completed (it doesn't mean that the image is
5314 * free of errors) or -errno when an internal error occurred. The results of the
5315 * check are stored in res.
5317 int coroutine_fn
bdrv_co_check(BlockDriverState
*bs
,
5318 BdrvCheckResult
*res
, BdrvCheckMode fix
)
5320 if (bs
->drv
== NULL
) {
5323 if (bs
->drv
->bdrv_co_check
== NULL
) {
5327 memset(res
, 0, sizeof(*res
));
5328 return bs
->drv
->bdrv_co_check(bs
, res
, fix
);
5334 * -EINVAL - backing format specified, but no file
5335 * -ENOSPC - can't update the backing file because no space is left in the
5337 * -ENOTSUP - format driver doesn't support changing the backing file
5339 int bdrv_change_backing_file(BlockDriverState
*bs
, const char *backing_file
,
5340 const char *backing_fmt
, bool require
)
5342 BlockDriver
*drv
= bs
->drv
;
5349 /* Backing file format doesn't make sense without a backing file */
5350 if (backing_fmt
&& !backing_file
) {
5354 if (require
&& backing_file
&& !backing_fmt
) {
5358 if (drv
->bdrv_change_backing_file
!= NULL
) {
5359 ret
= drv
->bdrv_change_backing_file(bs
, backing_file
, backing_fmt
);
5365 pstrcpy(bs
->backing_file
, sizeof(bs
->backing_file
), backing_file
?: "");
5366 pstrcpy(bs
->backing_format
, sizeof(bs
->backing_format
), backing_fmt
?: "");
5367 pstrcpy(bs
->auto_backing_file
, sizeof(bs
->auto_backing_file
),
5368 backing_file
?: "");
5374 * Finds the first non-filter node above bs in the chain between
5375 * active and bs. The returned node is either an immediate parent of
5376 * bs, or there are only filter nodes between the two.
5378 * Returns NULL if bs is not found in active's image chain,
5379 * or if active == bs.
5381 * Returns the bottommost base image if bs == NULL.
5383 BlockDriverState
*bdrv_find_overlay(BlockDriverState
*active
,
5384 BlockDriverState
*bs
)
5386 bs
= bdrv_skip_filters(bs
);
5387 active
= bdrv_skip_filters(active
);
5390 BlockDriverState
*next
= bdrv_backing_chain_next(active
);
5400 /* Given a BDS, searches for the base layer. */
5401 BlockDriverState
*bdrv_find_base(BlockDriverState
*bs
)
5403 return bdrv_find_overlay(bs
, NULL
);
5407 * Return true if at least one of the COW (backing) and filter links
5408 * between @bs and @base is frozen. @errp is set if that's the case.
5409 * @base must be reachable from @bs, or NULL.
5411 bool bdrv_is_backing_chain_frozen(BlockDriverState
*bs
, BlockDriverState
*base
,
5414 BlockDriverState
*i
;
5417 for (i
= bs
; i
!= base
; i
= child_bs(child
)) {
5418 child
= bdrv_filter_or_cow_child(i
);
5420 if (child
&& child
->frozen
) {
5421 error_setg(errp
, "Cannot change '%s' link from '%s' to '%s'",
5422 child
->name
, i
->node_name
, child
->bs
->node_name
);
5431 * Freeze all COW (backing) and filter links between @bs and @base.
5432 * If any of the links is already frozen the operation is aborted and
5433 * none of the links are modified.
5434 * @base must be reachable from @bs, or NULL.
5435 * Returns 0 on success. On failure returns < 0 and sets @errp.
5437 int bdrv_freeze_backing_chain(BlockDriverState
*bs
, BlockDriverState
*base
,
5440 BlockDriverState
*i
;
5443 if (bdrv_is_backing_chain_frozen(bs
, base
, errp
)) {
5447 for (i
= bs
; i
!= base
; i
= child_bs(child
)) {
5448 child
= bdrv_filter_or_cow_child(i
);
5449 if (child
&& child
->bs
->never_freeze
) {
5450 error_setg(errp
, "Cannot freeze '%s' link to '%s'",
5451 child
->name
, child
->bs
->node_name
);
5456 for (i
= bs
; i
!= base
; i
= child_bs(child
)) {
5457 child
= bdrv_filter_or_cow_child(i
);
5459 child
->frozen
= true;
5467 * Unfreeze all COW (backing) and filter links between @bs and @base.
5468 * The caller must ensure that all links are frozen before using this
5470 * @base must be reachable from @bs, or NULL.
5472 void bdrv_unfreeze_backing_chain(BlockDriverState
*bs
, BlockDriverState
*base
)
5474 BlockDriverState
*i
;
5477 for (i
= bs
; i
!= base
; i
= child_bs(child
)) {
5478 child
= bdrv_filter_or_cow_child(i
);
5480 assert(child
->frozen
);
5481 child
->frozen
= false;
5487 * Drops images above 'base' up to and including 'top', and sets the image
5488 * above 'top' to have base as its backing file.
5490 * Requires that the overlay to 'top' is opened r/w, so that the backing file
5491 * information in 'bs' can be properly updated.
5493 * E.g., this will convert the following chain:
5494 * bottom <- base <- intermediate <- top <- active
5498 * bottom <- base <- active
5500 * It is allowed for bottom==base, in which case it converts:
5502 * base <- intermediate <- top <- active
5508 * If backing_file_str is non-NULL, it will be used when modifying top's
5509 * overlay image metadata.
5512 * if active == top, that is considered an error
5515 int bdrv_drop_intermediate(BlockDriverState
*top
, BlockDriverState
*base
,
5516 const char *backing_file_str
)
5518 BlockDriverState
*explicit_top
= top
;
5519 bool update_inherits_from
;
5521 Error
*local_err
= NULL
;
5523 g_autoptr(GSList
) updated_children
= NULL
;
5527 bdrv_subtree_drained_begin(top
);
5529 if (!top
->drv
|| !base
->drv
) {
5533 /* Make sure that base is in the backing chain of top */
5534 if (!bdrv_chain_contains(top
, base
)) {
5538 /* If 'base' recursively inherits from 'top' then we should set
5539 * base->inherits_from to top->inherits_from after 'top' and all
5540 * other intermediate nodes have been dropped.
5541 * If 'top' is an implicit node (e.g. "commit_top") we should skip
5542 * it because no one inherits from it. We use explicit_top for that. */
5543 explicit_top
= bdrv_skip_implicit_filters(explicit_top
);
5544 update_inherits_from
= bdrv_inherits_from_recursive(base
, explicit_top
);
5546 /* success - we can delete the intermediate states, and link top->base */
5547 /* TODO Check graph modification op blockers (BLK_PERM_GRAPH_MOD) once
5548 * we've figured out how they should work. */
5549 if (!backing_file_str
) {
5550 bdrv_refresh_filename(base
);
5551 backing_file_str
= base
->filename
;
5554 QLIST_FOREACH(c
, &top
->parents
, next_parent
) {
5555 updated_children
= g_slist_prepend(updated_children
, c
);
5559 * It seems correct to pass detach_subchain=true here, but it triggers
5560 * one more yet not fixed bug, when due to nested aio_poll loop we switch to
5561 * another drained section, which modify the graph (for example, removing
5562 * the child, which we keep in updated_children list). So, it's a TODO.
5564 * Note, bug triggered if pass detach_subchain=true here and run
5565 * test-bdrv-drain. test_drop_intermediate_poll() test-case will crash.
5568 bdrv_replace_node_common(top
, base
, false, false, &local_err
);
5570 error_report_err(local_err
);
5574 for (p
= updated_children
; p
; p
= p
->next
) {
5577 if (c
->klass
->update_filename
) {
5578 ret
= c
->klass
->update_filename(c
, base
, backing_file_str
,
5582 * TODO: Actually, we want to rollback all previous iterations
5583 * of this loop, and (which is almost impossible) previous
5584 * bdrv_replace_node()...
5586 * Note, that c->klass->update_filename may lead to permission
5587 * update, so it's a bad idea to call it inside permission
5588 * update transaction of bdrv_replace_node.
5590 error_report_err(local_err
);
5596 if (update_inherits_from
) {
5597 base
->inherits_from
= explicit_top
->inherits_from
;
5602 bdrv_subtree_drained_end(top
);
5608 * Implementation of BlockDriver.bdrv_get_allocated_file_size() that
5609 * sums the size of all data-bearing children. (This excludes backing
5612 static int64_t bdrv_sum_allocated_file_size(BlockDriverState
*bs
)
5615 int64_t child_size
, sum
= 0;
5617 QLIST_FOREACH(child
, &bs
->children
, next
) {
5618 if (child
->role
& (BDRV_CHILD_DATA
| BDRV_CHILD_METADATA
|
5619 BDRV_CHILD_FILTERED
))
5621 child_size
= bdrv_get_allocated_file_size(child
->bs
);
5622 if (child_size
< 0) {
5633 * Length of a allocated file in bytes. Sparse files are counted by actual
5634 * allocated space. Return < 0 if error or unknown.
5636 int64_t bdrv_get_allocated_file_size(BlockDriverState
*bs
)
5638 BlockDriver
*drv
= bs
->drv
;
5642 if (drv
->bdrv_get_allocated_file_size
) {
5643 return drv
->bdrv_get_allocated_file_size(bs
);
5646 if (drv
->bdrv_file_open
) {
5648 * Protocol drivers default to -ENOTSUP (most of their data is
5649 * not stored in any of their children (if they even have any),
5650 * so there is no generic way to figure it out).
5653 } else if (drv
->is_filter
) {
5654 /* Filter drivers default to the size of their filtered child */
5655 return bdrv_get_allocated_file_size(bdrv_filter_bs(bs
));
5657 /* Other drivers default to summing their children's sizes */
5658 return bdrv_sum_allocated_file_size(bs
);
5664 * @drv: Format driver
5665 * @opts: Creation options for new image
5666 * @in_bs: Existing image containing data for new image (may be NULL)
5667 * @errp: Error object
5668 * Returns: A #BlockMeasureInfo (free using qapi_free_BlockMeasureInfo())
5671 * Calculate file size required to create a new image.
5673 * If @in_bs is given then space for allocated clusters and zero clusters
5674 * from that image are included in the calculation. If @opts contains a
5675 * backing file that is shared by @in_bs then backing clusters may be omitted
5676 * from the calculation.
5678 * If @in_bs is NULL then the calculation includes no allocated clusters
5679 * unless a preallocation option is given in @opts.
5681 * Note that @in_bs may use a different BlockDriver from @drv.
5683 * If an error occurs the @errp pointer is set.
5685 BlockMeasureInfo
*bdrv_measure(BlockDriver
*drv
, QemuOpts
*opts
,
5686 BlockDriverState
*in_bs
, Error
**errp
)
5688 if (!drv
->bdrv_measure
) {
5689 error_setg(errp
, "Block driver '%s' does not support size measurement",
5694 return drv
->bdrv_measure(opts
, in_bs
, errp
);
5698 * Return number of sectors on success, -errno on error.
5700 int64_t bdrv_nb_sectors(BlockDriverState
*bs
)
5702 BlockDriver
*drv
= bs
->drv
;
5707 if (drv
->has_variable_length
) {
5708 int ret
= refresh_total_sectors(bs
, bs
->total_sectors
);
5713 return bs
->total_sectors
;
5717 * Return length in bytes on success, -errno on error.
5718 * The length is always a multiple of BDRV_SECTOR_SIZE.
5720 int64_t bdrv_getlength(BlockDriverState
*bs
)
5722 int64_t ret
= bdrv_nb_sectors(bs
);
5727 if (ret
> INT64_MAX
/ BDRV_SECTOR_SIZE
) {
5730 return ret
* BDRV_SECTOR_SIZE
;
5733 /* return 0 as number of sectors if no device present or error */
5734 void bdrv_get_geometry(BlockDriverState
*bs
, uint64_t *nb_sectors_ptr
)
5736 int64_t nb_sectors
= bdrv_nb_sectors(bs
);
5738 *nb_sectors_ptr
= nb_sectors
< 0 ? 0 : nb_sectors
;
5741 bool bdrv_is_sg(BlockDriverState
*bs
)
5747 * Return whether the given node supports compressed writes.
5749 bool bdrv_supports_compressed_writes(BlockDriverState
*bs
)
5751 BlockDriverState
*filtered
;
5753 if (!bs
->drv
|| !block_driver_can_compress(bs
->drv
)) {
5757 filtered
= bdrv_filter_bs(bs
);
5760 * Filters can only forward compressed writes, so we have to
5763 return bdrv_supports_compressed_writes(filtered
);
5769 const char *bdrv_get_format_name(BlockDriverState
*bs
)
5771 return bs
->drv
? bs
->drv
->format_name
: NULL
;
5774 static int qsort_strcmp(const void *a
, const void *b
)
5776 return strcmp(*(char *const *)a
, *(char *const *)b
);
5779 void bdrv_iterate_format(void (*it
)(void *opaque
, const char *name
),
5780 void *opaque
, bool read_only
)
5785 const char **formats
= NULL
;
5787 QLIST_FOREACH(drv
, &bdrv_drivers
, list
) {
5788 if (drv
->format_name
) {
5792 if (use_bdrv_whitelist
&& !bdrv_is_whitelisted(drv
, read_only
)) {
5796 while (formats
&& i
&& !found
) {
5797 found
= !strcmp(formats
[--i
], drv
->format_name
);
5801 formats
= g_renew(const char *, formats
, count
+ 1);
5802 formats
[count
++] = drv
->format_name
;
5807 for (i
= 0; i
< (int)ARRAY_SIZE(block_driver_modules
); i
++) {
5808 const char *format_name
= block_driver_modules
[i
].format_name
;
5814 if (use_bdrv_whitelist
&&
5815 !bdrv_format_is_whitelisted(format_name
, read_only
)) {
5819 while (formats
&& j
&& !found
) {
5820 found
= !strcmp(formats
[--j
], format_name
);
5824 formats
= g_renew(const char *, formats
, count
+ 1);
5825 formats
[count
++] = format_name
;
5830 qsort(formats
, count
, sizeof(formats
[0]), qsort_strcmp
);
5832 for (i
= 0; i
< count
; i
++) {
5833 it(opaque
, formats
[i
]);
5839 /* This function is to find a node in the bs graph */
5840 BlockDriverState
*bdrv_find_node(const char *node_name
)
5842 BlockDriverState
*bs
;
5846 QTAILQ_FOREACH(bs
, &graph_bdrv_states
, node_list
) {
5847 if (!strcmp(node_name
, bs
->node_name
)) {
5854 /* Put this QMP function here so it can access the static graph_bdrv_states. */
5855 BlockDeviceInfoList
*bdrv_named_nodes_list(bool flat
,
5858 BlockDeviceInfoList
*list
;
5859 BlockDriverState
*bs
;
5862 QTAILQ_FOREACH(bs
, &graph_bdrv_states
, node_list
) {
5863 BlockDeviceInfo
*info
= bdrv_block_device_info(NULL
, bs
, flat
, errp
);
5865 qapi_free_BlockDeviceInfoList(list
);
5868 QAPI_LIST_PREPEND(list
, info
);
5874 typedef struct XDbgBlockGraphConstructor
{
5875 XDbgBlockGraph
*graph
;
5876 GHashTable
*graph_nodes
;
5877 } XDbgBlockGraphConstructor
;
5879 static XDbgBlockGraphConstructor
*xdbg_graph_new(void)
5881 XDbgBlockGraphConstructor
*gr
= g_new(XDbgBlockGraphConstructor
, 1);
5883 gr
->graph
= g_new0(XDbgBlockGraph
, 1);
5884 gr
->graph_nodes
= g_hash_table_new(NULL
, NULL
);
5889 static XDbgBlockGraph
*xdbg_graph_finalize(XDbgBlockGraphConstructor
*gr
)
5891 XDbgBlockGraph
*graph
= gr
->graph
;
5893 g_hash_table_destroy(gr
->graph_nodes
);
5899 static uintptr_t xdbg_graph_node_num(XDbgBlockGraphConstructor
*gr
, void *node
)
5901 uintptr_t ret
= (uintptr_t)g_hash_table_lookup(gr
->graph_nodes
, node
);
5908 * Start counting from 1, not 0, because 0 interferes with not-found (NULL)
5909 * answer of g_hash_table_lookup.
5911 ret
= g_hash_table_size(gr
->graph_nodes
) + 1;
5912 g_hash_table_insert(gr
->graph_nodes
, node
, (void *)ret
);
5917 static void xdbg_graph_add_node(XDbgBlockGraphConstructor
*gr
, void *node
,
5918 XDbgBlockGraphNodeType type
, const char *name
)
5920 XDbgBlockGraphNode
*n
;
5922 n
= g_new0(XDbgBlockGraphNode
, 1);
5924 n
->id
= xdbg_graph_node_num(gr
, node
);
5926 n
->name
= g_strdup(name
);
5928 QAPI_LIST_PREPEND(gr
->graph
->nodes
, n
);
5931 static void xdbg_graph_add_edge(XDbgBlockGraphConstructor
*gr
, void *parent
,
5932 const BdrvChild
*child
)
5934 BlockPermission qapi_perm
;
5935 XDbgBlockGraphEdge
*edge
;
5937 edge
= g_new0(XDbgBlockGraphEdge
, 1);
5939 edge
->parent
= xdbg_graph_node_num(gr
, parent
);
5940 edge
->child
= xdbg_graph_node_num(gr
, child
->bs
);
5941 edge
->name
= g_strdup(child
->name
);
5943 for (qapi_perm
= 0; qapi_perm
< BLOCK_PERMISSION__MAX
; qapi_perm
++) {
5944 uint64_t flag
= bdrv_qapi_perm_to_blk_perm(qapi_perm
);
5946 if (flag
& child
->perm
) {
5947 QAPI_LIST_PREPEND(edge
->perm
, qapi_perm
);
5949 if (flag
& child
->shared_perm
) {
5950 QAPI_LIST_PREPEND(edge
->shared_perm
, qapi_perm
);
5954 QAPI_LIST_PREPEND(gr
->graph
->edges
, edge
);
5958 XDbgBlockGraph
*bdrv_get_xdbg_block_graph(Error
**errp
)
5962 BlockDriverState
*bs
;
5964 XDbgBlockGraphConstructor
*gr
= xdbg_graph_new();
5966 for (blk
= blk_all_next(NULL
); blk
; blk
= blk_all_next(blk
)) {
5967 char *allocated_name
= NULL
;
5968 const char *name
= blk_name(blk
);
5971 name
= allocated_name
= blk_get_attached_dev_id(blk
);
5973 xdbg_graph_add_node(gr
, blk
, X_DBG_BLOCK_GRAPH_NODE_TYPE_BLOCK_BACKEND
,
5975 g_free(allocated_name
);
5976 if (blk_root(blk
)) {
5977 xdbg_graph_add_edge(gr
, blk
, blk_root(blk
));
5981 for (job
= block_job_next(NULL
); job
; job
= block_job_next(job
)) {
5984 xdbg_graph_add_node(gr
, job
, X_DBG_BLOCK_GRAPH_NODE_TYPE_BLOCK_JOB
,
5986 for (el
= job
->nodes
; el
; el
= el
->next
) {
5987 xdbg_graph_add_edge(gr
, job
, (BdrvChild
*)el
->data
);
5991 QTAILQ_FOREACH(bs
, &graph_bdrv_states
, node_list
) {
5992 xdbg_graph_add_node(gr
, bs
, X_DBG_BLOCK_GRAPH_NODE_TYPE_BLOCK_DRIVER
,
5994 QLIST_FOREACH(child
, &bs
->children
, next
) {
5995 xdbg_graph_add_edge(gr
, bs
, child
);
5999 return xdbg_graph_finalize(gr
);
6002 BlockDriverState
*bdrv_lookup_bs(const char *device
,
6003 const char *node_name
,
6007 BlockDriverState
*bs
;
6010 blk
= blk_by_name(device
);
6015 error_setg(errp
, "Device '%s' has no medium", device
);
6023 bs
= bdrv_find_node(node_name
);
6030 error_setg(errp
, "Cannot find device=\'%s\' nor node-name=\'%s\'",
6031 device
? device
: "",
6032 node_name
? node_name
: "");
6036 /* If 'base' is in the same chain as 'top', return true. Otherwise,
6037 * return false. If either argument is NULL, return false. */
6038 bool bdrv_chain_contains(BlockDriverState
*top
, BlockDriverState
*base
)
6040 while (top
&& top
!= base
) {
6041 top
= bdrv_filter_or_cow_bs(top
);
6047 BlockDriverState
*bdrv_next_node(BlockDriverState
*bs
)
6050 return QTAILQ_FIRST(&graph_bdrv_states
);
6052 return QTAILQ_NEXT(bs
, node_list
);
6055 BlockDriverState
*bdrv_next_all_states(BlockDriverState
*bs
)
6058 return QTAILQ_FIRST(&all_bdrv_states
);
6060 return QTAILQ_NEXT(bs
, bs_list
);
6063 const char *bdrv_get_node_name(const BlockDriverState
*bs
)
6065 return bs
->node_name
;
6068 const char *bdrv_get_parent_name(const BlockDriverState
*bs
)
6073 /* If multiple parents have a name, just pick the first one. */
6074 QLIST_FOREACH(c
, &bs
->parents
, next_parent
) {
6075 if (c
->klass
->get_name
) {
6076 name
= c
->klass
->get_name(c
);
6077 if (name
&& *name
) {
6086 /* TODO check what callers really want: bs->node_name or blk_name() */
6087 const char *bdrv_get_device_name(const BlockDriverState
*bs
)
6089 return bdrv_get_parent_name(bs
) ?: "";
6092 /* This can be used to identify nodes that might not have a device
6093 * name associated. Since node and device names live in the same
6094 * namespace, the result is unambiguous. The exception is if both are
6095 * absent, then this returns an empty (non-null) string. */
6096 const char *bdrv_get_device_or_node_name(const BlockDriverState
*bs
)
6098 return bdrv_get_parent_name(bs
) ?: bs
->node_name
;
6101 int bdrv_get_flags(BlockDriverState
*bs
)
6103 return bs
->open_flags
;
6106 int bdrv_has_zero_init_1(BlockDriverState
*bs
)
6111 int bdrv_has_zero_init(BlockDriverState
*bs
)
6113 BlockDriverState
*filtered
;
6119 /* If BS is a copy on write image, it is initialized to
6120 the contents of the base image, which may not be zeroes. */
6121 if (bdrv_cow_child(bs
)) {
6124 if (bs
->drv
->bdrv_has_zero_init
) {
6125 return bs
->drv
->bdrv_has_zero_init(bs
);
6128 filtered
= bdrv_filter_bs(bs
);
6130 return bdrv_has_zero_init(filtered
);
6137 bool bdrv_can_write_zeroes_with_unmap(BlockDriverState
*bs
)
6139 if (!(bs
->open_flags
& BDRV_O_UNMAP
)) {
6143 return bs
->supported_zero_flags
& BDRV_REQ_MAY_UNMAP
;
6146 void bdrv_get_backing_filename(BlockDriverState
*bs
,
6147 char *filename
, int filename_size
)
6149 pstrcpy(filename
, filename_size
, bs
->backing_file
);
6152 int bdrv_get_info(BlockDriverState
*bs
, BlockDriverInfo
*bdi
)
6155 BlockDriver
*drv
= bs
->drv
;
6156 /* if bs->drv == NULL, bs is closed, so there's nothing to do here */
6160 if (!drv
->bdrv_get_info
) {
6161 BlockDriverState
*filtered
= bdrv_filter_bs(bs
);
6163 return bdrv_get_info(filtered
, bdi
);
6167 memset(bdi
, 0, sizeof(*bdi
));
6168 ret
= drv
->bdrv_get_info(bs
, bdi
);
6173 if (bdi
->cluster_size
> BDRV_MAX_ALIGNMENT
) {
6180 ImageInfoSpecific
*bdrv_get_specific_info(BlockDriverState
*bs
,
6183 BlockDriver
*drv
= bs
->drv
;
6184 if (drv
&& drv
->bdrv_get_specific_info
) {
6185 return drv
->bdrv_get_specific_info(bs
, errp
);
6190 BlockStatsSpecific
*bdrv_get_specific_stats(BlockDriverState
*bs
)
6192 BlockDriver
*drv
= bs
->drv
;
6193 if (!drv
|| !drv
->bdrv_get_specific_stats
) {
6196 return drv
->bdrv_get_specific_stats(bs
);
6199 void bdrv_debug_event(BlockDriverState
*bs
, BlkdebugEvent event
)
6201 if (!bs
|| !bs
->drv
|| !bs
->drv
->bdrv_debug_event
) {
6205 bs
->drv
->bdrv_debug_event(bs
, event
);
6208 static BlockDriverState
*bdrv_find_debug_node(BlockDriverState
*bs
)
6210 while (bs
&& bs
->drv
&& !bs
->drv
->bdrv_debug_breakpoint
) {
6211 bs
= bdrv_primary_bs(bs
);
6214 if (bs
&& bs
->drv
&& bs
->drv
->bdrv_debug_breakpoint
) {
6215 assert(bs
->drv
->bdrv_debug_remove_breakpoint
);
6222 int bdrv_debug_breakpoint(BlockDriverState
*bs
, const char *event
,
6225 bs
= bdrv_find_debug_node(bs
);
6227 return bs
->drv
->bdrv_debug_breakpoint(bs
, event
, tag
);
6233 int bdrv_debug_remove_breakpoint(BlockDriverState
*bs
, const char *tag
)
6235 bs
= bdrv_find_debug_node(bs
);
6237 return bs
->drv
->bdrv_debug_remove_breakpoint(bs
, tag
);
6243 int bdrv_debug_resume(BlockDriverState
*bs
, const char *tag
)
6245 while (bs
&& (!bs
->drv
|| !bs
->drv
->bdrv_debug_resume
)) {
6246 bs
= bdrv_primary_bs(bs
);
6249 if (bs
&& bs
->drv
&& bs
->drv
->bdrv_debug_resume
) {
6250 return bs
->drv
->bdrv_debug_resume(bs
, tag
);
6256 bool bdrv_debug_is_suspended(BlockDriverState
*bs
, const char *tag
)
6258 while (bs
&& bs
->drv
&& !bs
->drv
->bdrv_debug_is_suspended
) {
6259 bs
= bdrv_primary_bs(bs
);
6262 if (bs
&& bs
->drv
&& bs
->drv
->bdrv_debug_is_suspended
) {
6263 return bs
->drv
->bdrv_debug_is_suspended(bs
, tag
);
6269 /* backing_file can either be relative, or absolute, or a protocol. If it is
6270 * relative, it must be relative to the chain. So, passing in bs->filename
6271 * from a BDS as backing_file should not be done, as that may be relative to
6272 * the CWD rather than the chain. */
6273 BlockDriverState
*bdrv_find_backing_image(BlockDriverState
*bs
,
6274 const char *backing_file
)
6276 char *filename_full
= NULL
;
6277 char *backing_file_full
= NULL
;
6278 char *filename_tmp
= NULL
;
6279 int is_protocol
= 0;
6280 bool filenames_refreshed
= false;
6281 BlockDriverState
*curr_bs
= NULL
;
6282 BlockDriverState
*retval
= NULL
;
6283 BlockDriverState
*bs_below
;
6285 if (!bs
|| !bs
->drv
|| !backing_file
) {
6289 filename_full
= g_malloc(PATH_MAX
);
6290 backing_file_full
= g_malloc(PATH_MAX
);
6292 is_protocol
= path_has_protocol(backing_file
);
6295 * Being largely a legacy function, skip any filters here
6296 * (because filters do not have normal filenames, so they cannot
6297 * match anyway; and allowing json:{} filenames is a bit out of
6300 for (curr_bs
= bdrv_skip_filters(bs
);
6301 bdrv_cow_child(curr_bs
) != NULL
;
6304 bs_below
= bdrv_backing_chain_next(curr_bs
);
6306 if (bdrv_backing_overridden(curr_bs
)) {
6308 * If the backing file was overridden, we can only compare
6309 * directly against the backing node's filename.
6312 if (!filenames_refreshed
) {
6314 * This will automatically refresh all of the
6315 * filenames in the rest of the backing chain, so we
6316 * only need to do this once.
6318 bdrv_refresh_filename(bs_below
);
6319 filenames_refreshed
= true;
6322 if (strcmp(backing_file
, bs_below
->filename
) == 0) {
6326 } else if (is_protocol
|| path_has_protocol(curr_bs
->backing_file
)) {
6328 * If either of the filename paths is actually a protocol, then
6329 * compare unmodified paths; otherwise make paths relative.
6331 char *backing_file_full_ret
;
6333 if (strcmp(backing_file
, curr_bs
->backing_file
) == 0) {
6337 /* Also check against the full backing filename for the image */
6338 backing_file_full_ret
= bdrv_get_full_backing_filename(curr_bs
,
6340 if (backing_file_full_ret
) {
6341 bool equal
= strcmp(backing_file
, backing_file_full_ret
) == 0;
6342 g_free(backing_file_full_ret
);
6349 /* If not an absolute filename path, make it relative to the current
6350 * image's filename path */
6351 filename_tmp
= bdrv_make_absolute_filename(curr_bs
, backing_file
,
6353 /* We are going to compare canonicalized absolute pathnames */
6354 if (!filename_tmp
|| !realpath(filename_tmp
, filename_full
)) {
6355 g_free(filename_tmp
);
6358 g_free(filename_tmp
);
6360 /* We need to make sure the backing filename we are comparing against
6361 * is relative to the current image filename (or absolute) */
6362 filename_tmp
= bdrv_get_full_backing_filename(curr_bs
, NULL
);
6363 if (!filename_tmp
|| !realpath(filename_tmp
, backing_file_full
)) {
6364 g_free(filename_tmp
);
6367 g_free(filename_tmp
);
6369 if (strcmp(backing_file_full
, filename_full
) == 0) {
6376 g_free(filename_full
);
6377 g_free(backing_file_full
);
6381 void bdrv_init(void)
6383 #ifdef CONFIG_BDRV_WHITELIST_TOOLS
6384 use_bdrv_whitelist
= 1;
6386 module_call_init(MODULE_INIT_BLOCK
);
6389 void bdrv_init_with_whitelist(void)
6391 use_bdrv_whitelist
= 1;
6395 int coroutine_fn
bdrv_co_invalidate_cache(BlockDriverState
*bs
, Error
**errp
)
6397 BdrvChild
*child
, *parent
;
6398 Error
*local_err
= NULL
;
6400 BdrvDirtyBitmap
*bm
;
6406 QLIST_FOREACH(child
, &bs
->children
, next
) {
6407 bdrv_co_invalidate_cache(child
->bs
, &local_err
);
6409 error_propagate(errp
, local_err
);
6415 * Update permissions, they may differ for inactive nodes.
6417 * Note that the required permissions of inactive images are always a
6418 * subset of the permissions required after activating the image. This
6419 * allows us to just get the permissions upfront without restricting
6420 * drv->bdrv_invalidate_cache().
6422 * It also means that in error cases, we don't have to try and revert to
6423 * the old permissions (which is an operation that could fail, too). We can
6424 * just keep the extended permissions for the next time that an activation
6425 * of the image is tried.
6427 if (bs
->open_flags
& BDRV_O_INACTIVE
) {
6428 bs
->open_flags
&= ~BDRV_O_INACTIVE
;
6429 ret
= bdrv_refresh_perms(bs
, errp
);
6431 bs
->open_flags
|= BDRV_O_INACTIVE
;
6435 if (bs
->drv
->bdrv_co_invalidate_cache
) {
6436 bs
->drv
->bdrv_co_invalidate_cache(bs
, &local_err
);
6438 bs
->open_flags
|= BDRV_O_INACTIVE
;
6439 error_propagate(errp
, local_err
);
6444 FOR_EACH_DIRTY_BITMAP(bs
, bm
) {
6445 bdrv_dirty_bitmap_skip_store(bm
, false);
6448 ret
= refresh_total_sectors(bs
, bs
->total_sectors
);
6450 bs
->open_flags
|= BDRV_O_INACTIVE
;
6451 error_setg_errno(errp
, -ret
, "Could not refresh total sector count");
6456 QLIST_FOREACH(parent
, &bs
->parents
, next_parent
) {
6457 if (parent
->klass
->activate
) {
6458 parent
->klass
->activate(parent
, &local_err
);
6460 bs
->open_flags
|= BDRV_O_INACTIVE
;
6461 error_propagate(errp
, local_err
);
6470 void bdrv_invalidate_cache_all(Error
**errp
)
6472 BlockDriverState
*bs
;
6473 BdrvNextIterator it
;
6475 for (bs
= bdrv_first(&it
); bs
; bs
= bdrv_next(&it
)) {
6476 AioContext
*aio_context
= bdrv_get_aio_context(bs
);
6479 aio_context_acquire(aio_context
);
6480 ret
= bdrv_invalidate_cache(bs
, errp
);
6481 aio_context_release(aio_context
);
6483 bdrv_next_cleanup(&it
);
6489 static bool bdrv_has_bds_parent(BlockDriverState
*bs
, bool only_active
)
6493 QLIST_FOREACH(parent
, &bs
->parents
, next_parent
) {
6494 if (parent
->klass
->parent_is_bds
) {
6495 BlockDriverState
*parent_bs
= parent
->opaque
;
6496 if (!only_active
|| !(parent_bs
->open_flags
& BDRV_O_INACTIVE
)) {
6505 static int bdrv_inactivate_recurse(BlockDriverState
*bs
)
6507 BdrvChild
*child
, *parent
;
6509 uint64_t cumulative_perms
, cumulative_shared_perms
;
6515 /* Make sure that we don't inactivate a child before its parent.
6516 * It will be covered by recursion from the yet active parent. */
6517 if (bdrv_has_bds_parent(bs
, true)) {
6521 assert(!(bs
->open_flags
& BDRV_O_INACTIVE
));
6523 /* Inactivate this node */
6524 if (bs
->drv
->bdrv_inactivate
) {
6525 ret
= bs
->drv
->bdrv_inactivate(bs
);
6531 QLIST_FOREACH(parent
, &bs
->parents
, next_parent
) {
6532 if (parent
->klass
->inactivate
) {
6533 ret
= parent
->klass
->inactivate(parent
);
6540 bdrv_get_cumulative_perm(bs
, &cumulative_perms
,
6541 &cumulative_shared_perms
);
6542 if (cumulative_perms
& (BLK_PERM_WRITE
| BLK_PERM_WRITE_UNCHANGED
)) {
6543 /* Our inactive parents still need write access. Inactivation failed. */
6547 bs
->open_flags
|= BDRV_O_INACTIVE
;
6550 * Update permissions, they may differ for inactive nodes.
6551 * We only tried to loosen restrictions, so errors are not fatal, ignore
6554 bdrv_refresh_perms(bs
, NULL
);
6556 /* Recursively inactivate children */
6557 QLIST_FOREACH(child
, &bs
->children
, next
) {
6558 ret
= bdrv_inactivate_recurse(child
->bs
);
6567 int bdrv_inactivate_all(void)
6569 BlockDriverState
*bs
= NULL
;
6570 BdrvNextIterator it
;
6572 GSList
*aio_ctxs
= NULL
, *ctx
;
6574 for (bs
= bdrv_first(&it
); bs
; bs
= bdrv_next(&it
)) {
6575 AioContext
*aio_context
= bdrv_get_aio_context(bs
);
6577 if (!g_slist_find(aio_ctxs
, aio_context
)) {
6578 aio_ctxs
= g_slist_prepend(aio_ctxs
, aio_context
);
6579 aio_context_acquire(aio_context
);
6583 for (bs
= bdrv_first(&it
); bs
; bs
= bdrv_next(&it
)) {
6584 /* Nodes with BDS parents are covered by recursion from the last
6585 * parent that gets inactivated. Don't inactivate them a second
6586 * time if that has already happened. */
6587 if (bdrv_has_bds_parent(bs
, false)) {
6590 ret
= bdrv_inactivate_recurse(bs
);
6592 bdrv_next_cleanup(&it
);
6598 for (ctx
= aio_ctxs
; ctx
!= NULL
; ctx
= ctx
->next
) {
6599 AioContext
*aio_context
= ctx
->data
;
6600 aio_context_release(aio_context
);
6602 g_slist_free(aio_ctxs
);
6607 /**************************************************************/
6608 /* removable device support */
6611 * Return TRUE if the media is present
6613 bool bdrv_is_inserted(BlockDriverState
*bs
)
6615 BlockDriver
*drv
= bs
->drv
;
6621 if (drv
->bdrv_is_inserted
) {
6622 return drv
->bdrv_is_inserted(bs
);
6624 QLIST_FOREACH(child
, &bs
->children
, next
) {
6625 if (!bdrv_is_inserted(child
->bs
)) {
6633 * If eject_flag is TRUE, eject the media. Otherwise, close the tray
6635 void bdrv_eject(BlockDriverState
*bs
, bool eject_flag
)
6637 BlockDriver
*drv
= bs
->drv
;
6639 if (drv
&& drv
->bdrv_eject
) {
6640 drv
->bdrv_eject(bs
, eject_flag
);
6645 * Lock or unlock the media (if it is locked, the user won't be able
6646 * to eject it manually).
6648 void bdrv_lock_medium(BlockDriverState
*bs
, bool locked
)
6650 BlockDriver
*drv
= bs
->drv
;
6652 trace_bdrv_lock_medium(bs
, locked
);
6654 if (drv
&& drv
->bdrv_lock_medium
) {
6655 drv
->bdrv_lock_medium(bs
, locked
);
6659 /* Get a reference to bs */
6660 void bdrv_ref(BlockDriverState
*bs
)
6665 /* Release a previously grabbed reference to bs.
6666 * If after releasing, reference count is zero, the BlockDriverState is
6668 void bdrv_unref(BlockDriverState
*bs
)
6673 assert(bs
->refcnt
> 0);
6674 if (--bs
->refcnt
== 0) {
6679 struct BdrvOpBlocker
{
6681 QLIST_ENTRY(BdrvOpBlocker
) list
;
6684 bool bdrv_op_is_blocked(BlockDriverState
*bs
, BlockOpType op
, Error
**errp
)
6686 BdrvOpBlocker
*blocker
;
6687 assert((int) op
>= 0 && op
< BLOCK_OP_TYPE_MAX
);
6688 if (!QLIST_EMPTY(&bs
->op_blockers
[op
])) {
6689 blocker
= QLIST_FIRST(&bs
->op_blockers
[op
]);
6690 error_propagate_prepend(errp
, error_copy(blocker
->reason
),
6691 "Node '%s' is busy: ",
6692 bdrv_get_device_or_node_name(bs
));
6698 void bdrv_op_block(BlockDriverState
*bs
, BlockOpType op
, Error
*reason
)
6700 BdrvOpBlocker
*blocker
;
6701 assert((int) op
>= 0 && op
< BLOCK_OP_TYPE_MAX
);
6703 blocker
= g_new0(BdrvOpBlocker
, 1);
6704 blocker
->reason
= reason
;
6705 QLIST_INSERT_HEAD(&bs
->op_blockers
[op
], blocker
, list
);
6708 void bdrv_op_unblock(BlockDriverState
*bs
, BlockOpType op
, Error
*reason
)
6710 BdrvOpBlocker
*blocker
, *next
;
6711 assert((int) op
>= 0 && op
< BLOCK_OP_TYPE_MAX
);
6712 QLIST_FOREACH_SAFE(blocker
, &bs
->op_blockers
[op
], list
, next
) {
6713 if (blocker
->reason
== reason
) {
6714 QLIST_REMOVE(blocker
, list
);
6720 void bdrv_op_block_all(BlockDriverState
*bs
, Error
*reason
)
6723 for (i
= 0; i
< BLOCK_OP_TYPE_MAX
; i
++) {
6724 bdrv_op_block(bs
, i
, reason
);
6728 void bdrv_op_unblock_all(BlockDriverState
*bs
, Error
*reason
)
6731 for (i
= 0; i
< BLOCK_OP_TYPE_MAX
; i
++) {
6732 bdrv_op_unblock(bs
, i
, reason
);
6736 bool bdrv_op_blocker_is_empty(BlockDriverState
*bs
)
6740 for (i
= 0; i
< BLOCK_OP_TYPE_MAX
; i
++) {
6741 if (!QLIST_EMPTY(&bs
->op_blockers
[i
])) {
6748 void bdrv_img_create(const char *filename
, const char *fmt
,
6749 const char *base_filename
, const char *base_fmt
,
6750 char *options
, uint64_t img_size
, int flags
, bool quiet
,
6753 QemuOptsList
*create_opts
= NULL
;
6754 QemuOpts
*opts
= NULL
;
6755 const char *backing_fmt
, *backing_file
;
6757 BlockDriver
*drv
, *proto_drv
;
6758 Error
*local_err
= NULL
;
6761 /* Find driver and parse its options */
6762 drv
= bdrv_find_format(fmt
);
6764 error_setg(errp
, "Unknown file format '%s'", fmt
);
6768 proto_drv
= bdrv_find_protocol(filename
, true, errp
);
6773 if (!drv
->create_opts
) {
6774 error_setg(errp
, "Format driver '%s' does not support image creation",
6779 if (!proto_drv
->create_opts
) {
6780 error_setg(errp
, "Protocol driver '%s' does not support image creation",
6781 proto_drv
->format_name
);
6785 /* Create parameter list */
6786 create_opts
= qemu_opts_append(create_opts
, drv
->create_opts
);
6787 create_opts
= qemu_opts_append(create_opts
, proto_drv
->create_opts
);
6789 opts
= qemu_opts_create(create_opts
, NULL
, 0, &error_abort
);
6791 /* Parse -o options */
6793 if (!qemu_opts_do_parse(opts
, options
, NULL
, errp
)) {
6798 if (!qemu_opt_get(opts
, BLOCK_OPT_SIZE
)) {
6799 qemu_opt_set_number(opts
, BLOCK_OPT_SIZE
, img_size
, &error_abort
);
6800 } else if (img_size
!= UINT64_C(-1)) {
6801 error_setg(errp
, "The image size must be specified only once");
6805 if (base_filename
) {
6806 if (!qemu_opt_set(opts
, BLOCK_OPT_BACKING_FILE
, base_filename
,
6808 error_setg(errp
, "Backing file not supported for file format '%s'",
6815 if (!qemu_opt_set(opts
, BLOCK_OPT_BACKING_FMT
, base_fmt
, NULL
)) {
6816 error_setg(errp
, "Backing file format not supported for file "
6817 "format '%s'", fmt
);
6822 backing_file
= qemu_opt_get(opts
, BLOCK_OPT_BACKING_FILE
);
6824 if (!strcmp(filename
, backing_file
)) {
6825 error_setg(errp
, "Error: Trying to create an image with the "
6826 "same filename as the backing file");
6829 if (backing_file
[0] == '\0') {
6830 error_setg(errp
, "Expected backing file name, got empty string");
6835 backing_fmt
= qemu_opt_get(opts
, BLOCK_OPT_BACKING_FMT
);
6837 /* The size for the image must always be specified, unless we have a backing
6838 * file and we have not been forbidden from opening it. */
6839 size
= qemu_opt_get_size(opts
, BLOCK_OPT_SIZE
, img_size
);
6840 if (backing_file
&& !(flags
& BDRV_O_NO_BACKING
)) {
6841 BlockDriverState
*bs
;
6844 QDict
*backing_options
= NULL
;
6847 bdrv_get_full_backing_filename_from_filename(filename
, backing_file
,
6852 assert(full_backing
);
6855 * No need to do I/O here, which allows us to open encrypted
6856 * backing images without needing the secret
6859 back_flags
&= ~(BDRV_O_RDWR
| BDRV_O_SNAPSHOT
| BDRV_O_NO_BACKING
);
6860 back_flags
|= BDRV_O_NO_IO
;
6862 backing_options
= qdict_new();
6864 qdict_put_str(backing_options
, "driver", backing_fmt
);
6866 qdict_put_bool(backing_options
, BDRV_OPT_FORCE_SHARE
, true);
6868 bs
= bdrv_open(full_backing
, NULL
, backing_options
, back_flags
,
6870 g_free(full_backing
);
6872 error_append_hint(&local_err
, "Could not open backing image.\n");
6876 error_setg(&local_err
,
6877 "Backing file specified without backing format");
6878 error_append_hint(&local_err
, "Detected format of %s.",
6879 bs
->drv
->format_name
);
6883 /* Opened BS, have no size */
6884 size
= bdrv_getlength(bs
);
6886 error_setg_errno(errp
, -size
, "Could not get size of '%s'",
6891 qemu_opt_set_number(opts
, BLOCK_OPT_SIZE
, size
, &error_abort
);
6895 /* (backing_file && !(flags & BDRV_O_NO_BACKING)) */
6896 } else if (backing_file
&& !backing_fmt
) {
6897 error_setg(&local_err
,
6898 "Backing file specified without backing format");
6903 error_setg(errp
, "Image creation needs a size parameter");
6908 printf("Formatting '%s', fmt=%s ", filename
, fmt
);
6909 qemu_opts_print(opts
, " ");
6914 ret
= bdrv_create(drv
, filename
, opts
, &local_err
);
6916 if (ret
== -EFBIG
) {
6917 /* This is generally a better message than whatever the driver would
6918 * deliver (especially because of the cluster_size_hint), since that
6919 * is most probably not much different from "image too large". */
6920 const char *cluster_size_hint
= "";
6921 if (qemu_opt_get_size(opts
, BLOCK_OPT_CLUSTER_SIZE
, 0)) {
6922 cluster_size_hint
= " (try using a larger cluster size)";
6924 error_setg(errp
, "The image size is too large for file format '%s'"
6925 "%s", fmt
, cluster_size_hint
);
6926 error_free(local_err
);
6931 qemu_opts_del(opts
);
6932 qemu_opts_free(create_opts
);
6933 error_propagate(errp
, local_err
);
6936 AioContext
*bdrv_get_aio_context(BlockDriverState
*bs
)
6938 return bs
? bs
->aio_context
: qemu_get_aio_context();
6941 AioContext
*coroutine_fn
bdrv_co_enter(BlockDriverState
*bs
)
6943 Coroutine
*self
= qemu_coroutine_self();
6944 AioContext
*old_ctx
= qemu_coroutine_get_aio_context(self
);
6945 AioContext
*new_ctx
;
6948 * Increase bs->in_flight to ensure that this operation is completed before
6949 * moving the node to a different AioContext. Read new_ctx only afterwards.
6951 bdrv_inc_in_flight(bs
);
6953 new_ctx
= bdrv_get_aio_context(bs
);
6954 aio_co_reschedule_self(new_ctx
);
6958 void coroutine_fn
bdrv_co_leave(BlockDriverState
*bs
, AioContext
*old_ctx
)
6960 aio_co_reschedule_self(old_ctx
);
6961 bdrv_dec_in_flight(bs
);
6964 void coroutine_fn
bdrv_co_lock(BlockDriverState
*bs
)
6966 AioContext
*ctx
= bdrv_get_aio_context(bs
);
6968 /* In the main thread, bs->aio_context won't change concurrently */
6969 assert(qemu_get_current_aio_context() == qemu_get_aio_context());
6972 * We're in coroutine context, so we already hold the lock of the main
6973 * loop AioContext. Don't lock it twice to avoid deadlocks.
6975 assert(qemu_in_coroutine());
6976 if (ctx
!= qemu_get_aio_context()) {
6977 aio_context_acquire(ctx
);
6981 void coroutine_fn
bdrv_co_unlock(BlockDriverState
*bs
)
6983 AioContext
*ctx
= bdrv_get_aio_context(bs
);
6985 assert(qemu_in_coroutine());
6986 if (ctx
!= qemu_get_aio_context()) {
6987 aio_context_release(ctx
);
6991 void bdrv_coroutine_enter(BlockDriverState
*bs
, Coroutine
*co
)
6993 aio_co_enter(bdrv_get_aio_context(bs
), co
);
6996 static void bdrv_do_remove_aio_context_notifier(BdrvAioNotifier
*ban
)
6998 QLIST_REMOVE(ban
, list
);
7002 static void bdrv_detach_aio_context(BlockDriverState
*bs
)
7004 BdrvAioNotifier
*baf
, *baf_tmp
;
7006 assert(!bs
->walking_aio_notifiers
);
7007 bs
->walking_aio_notifiers
= true;
7008 QLIST_FOREACH_SAFE(baf
, &bs
->aio_notifiers
, list
, baf_tmp
) {
7010 bdrv_do_remove_aio_context_notifier(baf
);
7012 baf
->detach_aio_context(baf
->opaque
);
7015 /* Never mind iterating again to check for ->deleted. bdrv_close() will
7016 * remove remaining aio notifiers if we aren't called again.
7018 bs
->walking_aio_notifiers
= false;
7020 if (bs
->drv
&& bs
->drv
->bdrv_detach_aio_context
) {
7021 bs
->drv
->bdrv_detach_aio_context(bs
);
7024 if (bs
->quiesce_counter
) {
7025 aio_enable_external(bs
->aio_context
);
7027 bs
->aio_context
= NULL
;
7030 static void bdrv_attach_aio_context(BlockDriverState
*bs
,
7031 AioContext
*new_context
)
7033 BdrvAioNotifier
*ban
, *ban_tmp
;
7035 if (bs
->quiesce_counter
) {
7036 aio_disable_external(new_context
);
7039 bs
->aio_context
= new_context
;
7041 if (bs
->drv
&& bs
->drv
->bdrv_attach_aio_context
) {
7042 bs
->drv
->bdrv_attach_aio_context(bs
, new_context
);
7045 assert(!bs
->walking_aio_notifiers
);
7046 bs
->walking_aio_notifiers
= true;
7047 QLIST_FOREACH_SAFE(ban
, &bs
->aio_notifiers
, list
, ban_tmp
) {
7049 bdrv_do_remove_aio_context_notifier(ban
);
7051 ban
->attached_aio_context(new_context
, ban
->opaque
);
7054 bs
->walking_aio_notifiers
= false;
7058 * Changes the AioContext used for fd handlers, timers, and BHs by this
7059 * BlockDriverState and all its children and parents.
7061 * Must be called from the main AioContext.
7063 * The caller must own the AioContext lock for the old AioContext of bs, but it
7064 * must not own the AioContext lock for new_context (unless new_context is the
7065 * same as the current context of bs).
7067 * @ignore will accumulate all visited BdrvChild object. The caller is
7068 * responsible for freeing the list afterwards.
7070 void bdrv_set_aio_context_ignore(BlockDriverState
*bs
,
7071 AioContext
*new_context
, GSList
**ignore
)
7073 AioContext
*old_context
= bdrv_get_aio_context(bs
);
7074 GSList
*children_to_process
= NULL
;
7075 GSList
*parents_to_process
= NULL
;
7077 BdrvChild
*child
, *parent
;
7079 g_assert(qemu_get_current_aio_context() == qemu_get_aio_context());
7081 if (old_context
== new_context
) {
7085 bdrv_drained_begin(bs
);
7087 QLIST_FOREACH(child
, &bs
->children
, next
) {
7088 if (g_slist_find(*ignore
, child
)) {
7091 *ignore
= g_slist_prepend(*ignore
, child
);
7092 children_to_process
= g_slist_prepend(children_to_process
, child
);
7095 QLIST_FOREACH(parent
, &bs
->parents
, next_parent
) {
7096 if (g_slist_find(*ignore
, parent
)) {
7099 *ignore
= g_slist_prepend(*ignore
, parent
);
7100 parents_to_process
= g_slist_prepend(parents_to_process
, parent
);
7103 for (entry
= children_to_process
;
7105 entry
= g_slist_next(entry
)) {
7106 child
= entry
->data
;
7107 bdrv_set_aio_context_ignore(child
->bs
, new_context
, ignore
);
7109 g_slist_free(children_to_process
);
7111 for (entry
= parents_to_process
;
7113 entry
= g_slist_next(entry
)) {
7114 parent
= entry
->data
;
7115 assert(parent
->klass
->set_aio_ctx
);
7116 parent
->klass
->set_aio_ctx(parent
, new_context
, ignore
);
7118 g_slist_free(parents_to_process
);
7120 bdrv_detach_aio_context(bs
);
7122 /* Acquire the new context, if necessary */
7123 if (qemu_get_aio_context() != new_context
) {
7124 aio_context_acquire(new_context
);
7127 bdrv_attach_aio_context(bs
, new_context
);
7130 * If this function was recursively called from
7131 * bdrv_set_aio_context_ignore(), there may be nodes in the
7132 * subtree that have not yet been moved to the new AioContext.
7133 * Release the old one so bdrv_drained_end() can poll them.
7135 if (qemu_get_aio_context() != old_context
) {
7136 aio_context_release(old_context
);
7139 bdrv_drained_end(bs
);
7141 if (qemu_get_aio_context() != old_context
) {
7142 aio_context_acquire(old_context
);
7144 if (qemu_get_aio_context() != new_context
) {
7145 aio_context_release(new_context
);
7149 static bool bdrv_parent_can_set_aio_context(BdrvChild
*c
, AioContext
*ctx
,
7150 GSList
**ignore
, Error
**errp
)
7152 if (g_slist_find(*ignore
, c
)) {
7155 *ignore
= g_slist_prepend(*ignore
, c
);
7158 * A BdrvChildClass that doesn't handle AioContext changes cannot
7159 * tolerate any AioContext changes
7161 if (!c
->klass
->can_set_aio_ctx
) {
7162 char *user
= bdrv_child_user_desc(c
);
7163 error_setg(errp
, "Changing iothreads is not supported by %s", user
);
7167 if (!c
->klass
->can_set_aio_ctx(c
, ctx
, ignore
, errp
)) {
7168 assert(!errp
|| *errp
);
7174 bool bdrv_child_can_set_aio_context(BdrvChild
*c
, AioContext
*ctx
,
7175 GSList
**ignore
, Error
**errp
)
7177 if (g_slist_find(*ignore
, c
)) {
7180 *ignore
= g_slist_prepend(*ignore
, c
);
7181 return bdrv_can_set_aio_context(c
->bs
, ctx
, ignore
, errp
);
7184 /* @ignore will accumulate all visited BdrvChild object. The caller is
7185 * responsible for freeing the list afterwards. */
7186 bool bdrv_can_set_aio_context(BlockDriverState
*bs
, AioContext
*ctx
,
7187 GSList
**ignore
, Error
**errp
)
7191 if (bdrv_get_aio_context(bs
) == ctx
) {
7195 QLIST_FOREACH(c
, &bs
->parents
, next_parent
) {
7196 if (!bdrv_parent_can_set_aio_context(c
, ctx
, ignore
, errp
)) {
7200 QLIST_FOREACH(c
, &bs
->children
, next
) {
7201 if (!bdrv_child_can_set_aio_context(c
, ctx
, ignore
, errp
)) {
7209 int bdrv_child_try_set_aio_context(BlockDriverState
*bs
, AioContext
*ctx
,
7210 BdrvChild
*ignore_child
, Error
**errp
)
7215 ignore
= ignore_child
? g_slist_prepend(NULL
, ignore_child
) : NULL
;
7216 ret
= bdrv_can_set_aio_context(bs
, ctx
, &ignore
, errp
);
7217 g_slist_free(ignore
);
7223 ignore
= ignore_child
? g_slist_prepend(NULL
, ignore_child
) : NULL
;
7224 bdrv_set_aio_context_ignore(bs
, ctx
, &ignore
);
7225 g_slist_free(ignore
);
7230 int bdrv_try_set_aio_context(BlockDriverState
*bs
, AioContext
*ctx
,
7233 return bdrv_child_try_set_aio_context(bs
, ctx
, NULL
, errp
);
7236 void bdrv_add_aio_context_notifier(BlockDriverState
*bs
,
7237 void (*attached_aio_context
)(AioContext
*new_context
, void *opaque
),
7238 void (*detach_aio_context
)(void *opaque
), void *opaque
)
7240 BdrvAioNotifier
*ban
= g_new(BdrvAioNotifier
, 1);
7241 *ban
= (BdrvAioNotifier
){
7242 .attached_aio_context
= attached_aio_context
,
7243 .detach_aio_context
= detach_aio_context
,
7247 QLIST_INSERT_HEAD(&bs
->aio_notifiers
, ban
, list
);
7250 void bdrv_remove_aio_context_notifier(BlockDriverState
*bs
,
7251 void (*attached_aio_context
)(AioContext
*,
7253 void (*detach_aio_context
)(void *),
7256 BdrvAioNotifier
*ban
, *ban_next
;
7258 QLIST_FOREACH_SAFE(ban
, &bs
->aio_notifiers
, list
, ban_next
) {
7259 if (ban
->attached_aio_context
== attached_aio_context
&&
7260 ban
->detach_aio_context
== detach_aio_context
&&
7261 ban
->opaque
== opaque
&&
7262 ban
->deleted
== false)
7264 if (bs
->walking_aio_notifiers
) {
7265 ban
->deleted
= true;
7267 bdrv_do_remove_aio_context_notifier(ban
);
7276 int bdrv_amend_options(BlockDriverState
*bs
, QemuOpts
*opts
,
7277 BlockDriverAmendStatusCB
*status_cb
, void *cb_opaque
,
7282 error_setg(errp
, "Node is ejected");
7285 if (!bs
->drv
->bdrv_amend_options
) {
7286 error_setg(errp
, "Block driver '%s' does not support option amendment",
7287 bs
->drv
->format_name
);
7290 return bs
->drv
->bdrv_amend_options(bs
, opts
, status_cb
,
7291 cb_opaque
, force
, errp
);
7295 * This function checks whether the given @to_replace is allowed to be
7296 * replaced by a node that always shows the same data as @bs. This is
7297 * used for example to verify whether the mirror job can replace
7298 * @to_replace by the target mirrored from @bs.
7299 * To be replaceable, @bs and @to_replace may either be guaranteed to
7300 * always show the same data (because they are only connected through
7301 * filters), or some driver may allow replacing one of its children
7302 * because it can guarantee that this child's data is not visible at
7303 * all (for example, for dissenting quorum children that have no other
7306 bool bdrv_recurse_can_replace(BlockDriverState
*bs
,
7307 BlockDriverState
*to_replace
)
7309 BlockDriverState
*filtered
;
7311 if (!bs
|| !bs
->drv
) {
7315 if (bs
== to_replace
) {
7319 /* See what the driver can do */
7320 if (bs
->drv
->bdrv_recurse_can_replace
) {
7321 return bs
->drv
->bdrv_recurse_can_replace(bs
, to_replace
);
7324 /* For filters without an own implementation, we can recurse on our own */
7325 filtered
= bdrv_filter_bs(bs
);
7327 return bdrv_recurse_can_replace(filtered
, to_replace
);
7335 * Check whether the given @node_name can be replaced by a node that
7336 * has the same data as @parent_bs. If so, return @node_name's BDS;
7339 * @node_name must be a (recursive) *child of @parent_bs (or this
7340 * function will return NULL).
7342 * The result (whether the node can be replaced or not) is only valid
7343 * for as long as no graph or permission changes occur.
7345 BlockDriverState
*check_to_replace_node(BlockDriverState
*parent_bs
,
7346 const char *node_name
, Error
**errp
)
7348 BlockDriverState
*to_replace_bs
= bdrv_find_node(node_name
);
7349 AioContext
*aio_context
;
7351 if (!to_replace_bs
) {
7352 error_setg(errp
, "Failed to find node with node-name='%s'", node_name
);
7356 aio_context
= bdrv_get_aio_context(to_replace_bs
);
7357 aio_context_acquire(aio_context
);
7359 if (bdrv_op_is_blocked(to_replace_bs
, BLOCK_OP_TYPE_REPLACE
, errp
)) {
7360 to_replace_bs
= NULL
;
7364 /* We don't want arbitrary node of the BDS chain to be replaced only the top
7365 * most non filter in order to prevent data corruption.
7366 * Another benefit is that this tests exclude backing files which are
7367 * blocked by the backing blockers.
7369 if (!bdrv_recurse_can_replace(parent_bs
, to_replace_bs
)) {
7370 error_setg(errp
, "Cannot replace '%s' by a node mirrored from '%s', "
7371 "because it cannot be guaranteed that doing so would not "
7372 "lead to an abrupt change of visible data",
7373 node_name
, parent_bs
->node_name
);
7374 to_replace_bs
= NULL
;
7379 aio_context_release(aio_context
);
7380 return to_replace_bs
;
7384 * Iterates through the list of runtime option keys that are said to
7385 * be "strong" for a BDS. An option is called "strong" if it changes
7386 * a BDS's data. For example, the null block driver's "size" and
7387 * "read-zeroes" options are strong, but its "latency-ns" option is
7390 * If a key returned by this function ends with a dot, all options
7391 * starting with that prefix are strong.
7393 static const char *const *strong_options(BlockDriverState
*bs
,
7394 const char *const *curopt
)
7396 static const char *const global_options
[] = {
7397 "driver", "filename", NULL
7401 return &global_options
[0];
7405 if (curopt
== &global_options
[ARRAY_SIZE(global_options
) - 1] && bs
->drv
) {
7406 curopt
= bs
->drv
->strong_runtime_opts
;
7409 return (curopt
&& *curopt
) ? curopt
: NULL
;
7413 * Copies all strong runtime options from bs->options to the given
7414 * QDict. The set of strong option keys is determined by invoking
7417 * Returns true iff any strong option was present in bs->options (and
7418 * thus copied to the target QDict) with the exception of "filename"
7419 * and "driver". The caller is expected to use this value to decide
7420 * whether the existence of strong options prevents the generation of
7423 static bool append_strong_runtime_options(QDict
*d
, BlockDriverState
*bs
)
7425 bool found_any
= false;
7426 const char *const *option_name
= NULL
;
7432 while ((option_name
= strong_options(bs
, option_name
))) {
7433 bool option_given
= false;
7435 assert(strlen(*option_name
) > 0);
7436 if ((*option_name
)[strlen(*option_name
) - 1] != '.') {
7437 QObject
*entry
= qdict_get(bs
->options
, *option_name
);
7442 qdict_put_obj(d
, *option_name
, qobject_ref(entry
));
7443 option_given
= true;
7445 const QDictEntry
*entry
;
7446 for (entry
= qdict_first(bs
->options
); entry
;
7447 entry
= qdict_next(bs
->options
, entry
))
7449 if (strstart(qdict_entry_key(entry
), *option_name
, NULL
)) {
7450 qdict_put_obj(d
, qdict_entry_key(entry
),
7451 qobject_ref(qdict_entry_value(entry
)));
7452 option_given
= true;
7457 /* While "driver" and "filename" need to be included in a JSON filename,
7458 * their existence does not prohibit generation of a plain filename. */
7459 if (!found_any
&& option_given
&&
7460 strcmp(*option_name
, "driver") && strcmp(*option_name
, "filename"))
7466 if (!qdict_haskey(d
, "driver")) {
7467 /* Drivers created with bdrv_new_open_driver() may not have a
7468 * @driver option. Add it here. */
7469 qdict_put_str(d
, "driver", bs
->drv
->format_name
);
7475 /* Note: This function may return false positives; it may return true
7476 * even if opening the backing file specified by bs's image header
7477 * would result in exactly bs->backing. */
7478 bool bdrv_backing_overridden(BlockDriverState
*bs
)
7481 return strcmp(bs
->auto_backing_file
,
7482 bs
->backing
->bs
->filename
);
7484 /* No backing BDS, so if the image header reports any backing
7485 * file, it must have been suppressed */
7486 return bs
->auto_backing_file
[0] != '\0';
7490 /* Updates the following BDS fields:
7491 * - exact_filename: A filename which may be used for opening a block device
7492 * which (mostly) equals the given BDS (even without any
7493 * other options; so reading and writing must return the same
7494 * results, but caching etc. may be different)
7495 * - full_open_options: Options which, when given when opening a block device
7496 * (without a filename), result in a BDS (mostly)
7497 * equalling the given one
7498 * - filename: If exact_filename is set, it is copied here. Otherwise,
7499 * full_open_options is converted to a JSON object, prefixed with
7500 * "json:" (for use through the JSON pseudo protocol) and put here.
7502 void bdrv_refresh_filename(BlockDriverState
*bs
)
7504 BlockDriver
*drv
= bs
->drv
;
7506 BlockDriverState
*primary_child_bs
;
7508 bool backing_overridden
;
7509 bool generate_json_filename
; /* Whether our default implementation should
7510 fill exact_filename (false) or not (true) */
7516 /* This BDS's file name may depend on any of its children's file names, so
7517 * refresh those first */
7518 QLIST_FOREACH(child
, &bs
->children
, next
) {
7519 bdrv_refresh_filename(child
->bs
);
7523 /* For implicit nodes, just copy everything from the single child */
7524 child
= QLIST_FIRST(&bs
->children
);
7525 assert(QLIST_NEXT(child
, next
) == NULL
);
7527 pstrcpy(bs
->exact_filename
, sizeof(bs
->exact_filename
),
7528 child
->bs
->exact_filename
);
7529 pstrcpy(bs
->filename
, sizeof(bs
->filename
), child
->bs
->filename
);
7531 qobject_unref(bs
->full_open_options
);
7532 bs
->full_open_options
= qobject_ref(child
->bs
->full_open_options
);
7537 backing_overridden
= bdrv_backing_overridden(bs
);
7539 if (bs
->open_flags
& BDRV_O_NO_IO
) {
7540 /* Without I/O, the backing file does not change anything.
7541 * Therefore, in such a case (primarily qemu-img), we can
7542 * pretend the backing file has not been overridden even if
7543 * it technically has been. */
7544 backing_overridden
= false;
7547 /* Gather the options QDict */
7549 generate_json_filename
= append_strong_runtime_options(opts
, bs
);
7550 generate_json_filename
|= backing_overridden
;
7552 if (drv
->bdrv_gather_child_options
) {
7553 /* Some block drivers may not want to present all of their children's
7554 * options, or name them differently from BdrvChild.name */
7555 drv
->bdrv_gather_child_options(bs
, opts
, backing_overridden
);
7557 QLIST_FOREACH(child
, &bs
->children
, next
) {
7558 if (child
== bs
->backing
&& !backing_overridden
) {
7559 /* We can skip the backing BDS if it has not been overridden */
7563 qdict_put(opts
, child
->name
,
7564 qobject_ref(child
->bs
->full_open_options
));
7567 if (backing_overridden
&& !bs
->backing
) {
7568 /* Force no backing file */
7569 qdict_put_null(opts
, "backing");
7573 qobject_unref(bs
->full_open_options
);
7574 bs
->full_open_options
= opts
;
7576 primary_child_bs
= bdrv_primary_bs(bs
);
7578 if (drv
->bdrv_refresh_filename
) {
7579 /* Obsolete information is of no use here, so drop the old file name
7580 * information before refreshing it */
7581 bs
->exact_filename
[0] = '\0';
7583 drv
->bdrv_refresh_filename(bs
);
7584 } else if (primary_child_bs
) {
7586 * Try to reconstruct valid information from the underlying
7587 * file -- this only works for format nodes (filter nodes
7588 * cannot be probed and as such must be selected by the user
7589 * either through an options dict, or through a special
7590 * filename which the filter driver must construct in its
7591 * .bdrv_refresh_filename() implementation).
7594 bs
->exact_filename
[0] = '\0';
7597 * We can use the underlying file's filename if:
7598 * - it has a filename,
7599 * - the current BDS is not a filter,
7600 * - the file is a protocol BDS, and
7601 * - opening that file (as this BDS's format) will automatically create
7602 * the BDS tree we have right now, that is:
7603 * - the user did not significantly change this BDS's behavior with
7604 * some explicit (strong) options
7605 * - no non-file child of this BDS has been overridden by the user
7606 * Both of these conditions are represented by generate_json_filename.
7608 if (primary_child_bs
->exact_filename
[0] &&
7609 primary_child_bs
->drv
->bdrv_file_open
&&
7610 !drv
->is_filter
&& !generate_json_filename
)
7612 strcpy(bs
->exact_filename
, primary_child_bs
->exact_filename
);
7616 if (bs
->exact_filename
[0]) {
7617 pstrcpy(bs
->filename
, sizeof(bs
->filename
), bs
->exact_filename
);
7619 GString
*json
= qobject_to_json(QOBJECT(bs
->full_open_options
));
7620 if (snprintf(bs
->filename
, sizeof(bs
->filename
), "json:%s",
7621 json
->str
) >= sizeof(bs
->filename
)) {
7622 /* Give user a hint if we truncated things. */
7623 strcpy(bs
->filename
+ sizeof(bs
->filename
) - 4, "...");
7625 g_string_free(json
, true);
7629 char *bdrv_dirname(BlockDriverState
*bs
, Error
**errp
)
7631 BlockDriver
*drv
= bs
->drv
;
7632 BlockDriverState
*child_bs
;
7635 error_setg(errp
, "Node '%s' is ejected", bs
->node_name
);
7639 if (drv
->bdrv_dirname
) {
7640 return drv
->bdrv_dirname(bs
, errp
);
7643 child_bs
= bdrv_primary_bs(bs
);
7645 return bdrv_dirname(child_bs
, errp
);
7648 bdrv_refresh_filename(bs
);
7649 if (bs
->exact_filename
[0] != '\0') {
7650 return path_combine(bs
->exact_filename
, "");
7653 error_setg(errp
, "Cannot generate a base directory for %s nodes",
7659 * Hot add/remove a BDS's child. So the user can take a child offline when
7660 * it is broken and take a new child online
7662 void bdrv_add_child(BlockDriverState
*parent_bs
, BlockDriverState
*child_bs
,
7666 if (!parent_bs
->drv
|| !parent_bs
->drv
->bdrv_add_child
) {
7667 error_setg(errp
, "The node %s does not support adding a child",
7668 bdrv_get_device_or_node_name(parent_bs
));
7672 if (!QLIST_EMPTY(&child_bs
->parents
)) {
7673 error_setg(errp
, "The node %s already has a parent",
7674 child_bs
->node_name
);
7678 parent_bs
->drv
->bdrv_add_child(parent_bs
, child_bs
, errp
);
7681 void bdrv_del_child(BlockDriverState
*parent_bs
, BdrvChild
*child
, Error
**errp
)
7685 if (!parent_bs
->drv
|| !parent_bs
->drv
->bdrv_del_child
) {
7686 error_setg(errp
, "The node %s does not support removing a child",
7687 bdrv_get_device_or_node_name(parent_bs
));
7691 QLIST_FOREACH(tmp
, &parent_bs
->children
, next
) {
7698 error_setg(errp
, "The node %s does not have a child named %s",
7699 bdrv_get_device_or_node_name(parent_bs
),
7700 bdrv_get_device_or_node_name(child
->bs
));
7704 parent_bs
->drv
->bdrv_del_child(parent_bs
, child
, errp
);
7707 int bdrv_make_empty(BdrvChild
*c
, Error
**errp
)
7709 BlockDriver
*drv
= c
->bs
->drv
;
7712 assert(c
->perm
& (BLK_PERM_WRITE
| BLK_PERM_WRITE_UNCHANGED
));
7714 if (!drv
->bdrv_make_empty
) {
7715 error_setg(errp
, "%s does not support emptying nodes",
7720 ret
= drv
->bdrv_make_empty(c
->bs
);
7722 error_setg_errno(errp
, -ret
, "Failed to empty %s",
7731 * Return the child that @bs acts as an overlay for, and from which data may be
7732 * copied in COW or COR operations. Usually this is the backing file.
7734 BdrvChild
*bdrv_cow_child(BlockDriverState
*bs
)
7736 if (!bs
|| !bs
->drv
) {
7740 if (bs
->drv
->is_filter
) {
7748 assert(bs
->backing
->role
& BDRV_CHILD_COW
);
7753 * If @bs acts as a filter for exactly one of its children, return
7756 BdrvChild
*bdrv_filter_child(BlockDriverState
*bs
)
7760 if (!bs
|| !bs
->drv
) {
7764 if (!bs
->drv
->is_filter
) {
7768 /* Only one of @backing or @file may be used */
7769 assert(!(bs
->backing
&& bs
->file
));
7771 c
= bs
->backing
?: bs
->file
;
7776 assert(c
->role
& BDRV_CHILD_FILTERED
);
7781 * Return either the result of bdrv_cow_child() or bdrv_filter_child(),
7782 * whichever is non-NULL.
7784 * Return NULL if both are NULL.
7786 BdrvChild
*bdrv_filter_or_cow_child(BlockDriverState
*bs
)
7788 BdrvChild
*cow_child
= bdrv_cow_child(bs
);
7789 BdrvChild
*filter_child
= bdrv_filter_child(bs
);
7791 /* Filter nodes cannot have COW backing files */
7792 assert(!(cow_child
&& filter_child
));
7794 return cow_child
?: filter_child
;
7798 * Return the primary child of this node: For filters, that is the
7799 * filtered child. For other nodes, that is usually the child storing
7801 * (A generally more helpful description is that this is (usually) the
7802 * child that has the same filename as @bs.)
7804 * Drivers do not necessarily have a primary child; for example quorum
7807 BdrvChild
*bdrv_primary_child(BlockDriverState
*bs
)
7809 BdrvChild
*c
, *found
= NULL
;
7811 QLIST_FOREACH(c
, &bs
->children
, next
) {
7812 if (c
->role
& BDRV_CHILD_PRIMARY
) {
7821 static BlockDriverState
*bdrv_do_skip_filters(BlockDriverState
*bs
,
7822 bool stop_on_explicit_filter
)
7830 while (!(stop_on_explicit_filter
&& !bs
->implicit
)) {
7831 c
= bdrv_filter_child(bs
);
7834 * A filter that is embedded in a working block graph must
7835 * have a child. Assert this here so this function does
7836 * not return a filter node that is not expected by the
7839 assert(!bs
->drv
|| !bs
->drv
->is_filter
);
7845 * Note that this treats nodes with bs->drv == NULL as not being
7846 * filters (bs->drv == NULL should be replaced by something else
7848 * The advantage of this behavior is that this function will thus
7849 * always return a non-NULL value (given a non-NULL @bs).
7856 * Return the first BDS that has not been added implicitly or that
7857 * does not have a filtered child down the chain starting from @bs
7858 * (including @bs itself).
7860 BlockDriverState
*bdrv_skip_implicit_filters(BlockDriverState
*bs
)
7862 return bdrv_do_skip_filters(bs
, true);
7866 * Return the first BDS that does not have a filtered child down the
7867 * chain starting from @bs (including @bs itself).
7869 BlockDriverState
*bdrv_skip_filters(BlockDriverState
*bs
)
7871 return bdrv_do_skip_filters(bs
, false);
7875 * For a backing chain, return the first non-filter backing image of
7876 * the first non-filter image.
7878 BlockDriverState
*bdrv_backing_chain_next(BlockDriverState
*bs
)
7880 return bdrv_skip_filters(bdrv_cow_bs(bdrv_skip_filters(bs
)));
7884 * Check whether [offset, offset + bytes) overlaps with the cached
7885 * block-status data region.
7887 * If so, and @pnum is not NULL, set *pnum to `bsc.data_end - offset`,
7888 * which is what bdrv_bsc_is_data()'s interface needs.
7889 * Otherwise, *pnum is not touched.
7891 static bool bdrv_bsc_range_overlaps_locked(BlockDriverState
*bs
,
7892 int64_t offset
, int64_t bytes
,
7895 BdrvBlockStatusCache
*bsc
= qatomic_rcu_read(&bs
->block_status_cache
);
7899 qatomic_read(&bsc
->valid
) &&
7900 ranges_overlap(offset
, bytes
, bsc
->data_start
,
7901 bsc
->data_end
- bsc
->data_start
);
7903 if (overlaps
&& pnum
) {
7904 *pnum
= bsc
->data_end
- offset
;
7911 * See block_int.h for this function's documentation.
7913 bool bdrv_bsc_is_data(BlockDriverState
*bs
, int64_t offset
, int64_t *pnum
)
7915 RCU_READ_LOCK_GUARD();
7917 return bdrv_bsc_range_overlaps_locked(bs
, offset
, 1, pnum
);
7921 * See block_int.h for this function's documentation.
7923 void bdrv_bsc_invalidate_range(BlockDriverState
*bs
,
7924 int64_t offset
, int64_t bytes
)
7926 RCU_READ_LOCK_GUARD();
7928 if (bdrv_bsc_range_overlaps_locked(bs
, offset
, bytes
, NULL
)) {
7929 qatomic_set(&bs
->block_status_cache
->valid
, false);
7934 * See block_int.h for this function's documentation.
7936 void bdrv_bsc_fill(BlockDriverState
*bs
, int64_t offset
, int64_t bytes
)
7938 BdrvBlockStatusCache
*new_bsc
= g_new(BdrvBlockStatusCache
, 1);
7939 BdrvBlockStatusCache
*old_bsc
;
7941 *new_bsc
= (BdrvBlockStatusCache
) {
7943 .data_start
= offset
,
7944 .data_end
= offset
+ bytes
,
7947 QEMU_LOCK_GUARD(&bs
->bsc_modify_lock
);
7949 old_bsc
= qatomic_rcu_read(&bs
->block_status_cache
);
7950 qatomic_rcu_set(&bs
->block_status_cache
, new_bsc
);
7952 g_free_rcu(old_bsc
, rcu
);