2 * QEMU System Emulator block driver
4 * Copyright (c) 2003 Fabrice Bellard
5 * Copyright (c) 2020 Virtuozzo International GmbH.
7 * Permission is hereby granted, free of charge, to any person obtaining a copy
8 * of this software and associated documentation files (the "Software"), to deal
9 * in the Software without restriction, including without limitation the rights
10 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
11 * copies of the Software, and to permit persons to whom the Software is
12 * furnished to do so, subject to the following conditions:
14 * The above copyright notice and this permission notice shall be included in
15 * all copies or substantial portions of the Software.
17 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
18 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
19 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
20 * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
21 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
22 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
26 #include "qemu/osdep.h"
27 #include "block/trace.h"
28 #include "block/block_int.h"
29 #include "block/blockjob.h"
30 #include "block/fuse.h"
31 #include "block/nbd.h"
32 #include "block/qdict.h"
33 #include "qemu/error-report.h"
34 #include "block/module_block.h"
35 #include "qemu/main-loop.h"
36 #include "qemu/module.h"
37 #include "qapi/error.h"
38 #include "qapi/qmp/qdict.h"
39 #include "qapi/qmp/qjson.h"
40 #include "qapi/qmp/qnull.h"
41 #include "qapi/qmp/qstring.h"
42 #include "qapi/qobject-output-visitor.h"
43 #include "qapi/qapi-visit-block-core.h"
44 #include "sysemu/block-backend.h"
45 #include "qemu/notify.h"
46 #include "qemu/option.h"
47 #include "qemu/coroutine.h"
48 #include "block/qapi.h"
49 #include "qemu/timer.h"
50 #include "qemu/cutils.h"
52 #include "qemu/range.h"
54 #include "block/coroutines.h"
57 #include <sys/ioctl.h>
58 #include <sys/queue.h>
59 #if defined(HAVE_SYS_DISK_H)
68 #define NOT_DONE 0x7fffffff /* used while emulated sync operation in progress */
70 /* Protected by BQL */
71 static QTAILQ_HEAD(, BlockDriverState
) graph_bdrv_states
=
72 QTAILQ_HEAD_INITIALIZER(graph_bdrv_states
);
74 /* Protected by BQL */
75 static QTAILQ_HEAD(, BlockDriverState
) all_bdrv_states
=
76 QTAILQ_HEAD_INITIALIZER(all_bdrv_states
);
78 /* Protected by BQL */
79 static QLIST_HEAD(, BlockDriver
) bdrv_drivers
=
80 QLIST_HEAD_INITIALIZER(bdrv_drivers
);
82 static BlockDriverState
*bdrv_open_inherit(const char *filename
,
83 const char *reference
,
84 QDict
*options
, int flags
,
85 BlockDriverState
*parent
,
86 const BdrvChildClass
*child_class
,
87 BdrvChildRole child_role
,
90 static bool bdrv_recurse_has_child(BlockDriverState
*bs
,
91 BlockDriverState
*child
);
93 static void bdrv_child_free(BdrvChild
*child
);
94 static void bdrv_replace_child_noperm(BdrvChild
**child
,
95 BlockDriverState
*new_bs
,
96 bool free_empty_child
);
97 static void bdrv_remove_file_or_backing_child(BlockDriverState
*bs
,
100 static void bdrv_remove_filter_or_cow_child(BlockDriverState
*bs
,
103 static int bdrv_reopen_prepare(BDRVReopenState
*reopen_state
,
104 BlockReopenQueue
*queue
,
105 Transaction
*change_child_tran
, Error
**errp
);
106 static void bdrv_reopen_commit(BDRVReopenState
*reopen_state
);
107 static void bdrv_reopen_abort(BDRVReopenState
*reopen_state
);
109 static bool bdrv_backing_overridden(BlockDriverState
*bs
);
111 /* If non-zero, use only whitelisted block drivers */
112 static int use_bdrv_whitelist
;
115 static int is_windows_drive_prefix(const char *filename
)
117 return (((filename
[0] >= 'a' && filename
[0] <= 'z') ||
118 (filename
[0] >= 'A' && filename
[0] <= 'Z')) &&
122 int is_windows_drive(const char *filename
)
124 if (is_windows_drive_prefix(filename
) &&
127 if (strstart(filename
, "\\\\.\\", NULL
) ||
128 strstart(filename
, "//./", NULL
))
134 size_t bdrv_opt_mem_align(BlockDriverState
*bs
)
136 if (!bs
|| !bs
->drv
) {
137 /* page size or 4k (hdd sector size) should be on the safe side */
138 return MAX(4096, qemu_real_host_page_size
);
142 return bs
->bl
.opt_mem_alignment
;
145 size_t bdrv_min_mem_align(BlockDriverState
*bs
)
147 if (!bs
|| !bs
->drv
) {
148 /* page size or 4k (hdd sector size) should be on the safe side */
149 return MAX(4096, qemu_real_host_page_size
);
153 return bs
->bl
.min_mem_alignment
;
156 /* check if the path starts with "<protocol>:" */
157 int path_has_protocol(const char *path
)
162 if (is_windows_drive(path
) ||
163 is_windows_drive_prefix(path
)) {
166 p
= path
+ strcspn(path
, ":/\\");
168 p
= path
+ strcspn(path
, ":/");
174 int path_is_absolute(const char *path
)
177 /* specific case for names like: "\\.\d:" */
178 if (is_windows_drive(path
) || is_windows_drive_prefix(path
)) {
181 return (*path
== '/' || *path
== '\\');
183 return (*path
== '/');
187 /* if filename is absolute, just return its duplicate. Otherwise, build a
188 path to it by considering it is relative to base_path. URL are
190 char *path_combine(const char *base_path
, const char *filename
)
192 const char *protocol_stripped
= NULL
;
197 if (path_is_absolute(filename
)) {
198 return g_strdup(filename
);
201 if (path_has_protocol(base_path
)) {
202 protocol_stripped
= strchr(base_path
, ':');
203 if (protocol_stripped
) {
207 p
= protocol_stripped
?: base_path
;
209 p1
= strrchr(base_path
, '/');
213 p2
= strrchr(base_path
, '\\');
214 if (!p1
|| p2
> p1
) {
229 result
= g_malloc(len
+ strlen(filename
) + 1);
230 memcpy(result
, base_path
, len
);
231 strcpy(result
+ len
, filename
);
237 * Helper function for bdrv_parse_filename() implementations to remove optional
238 * protocol prefixes (especially "file:") from a filename and for putting the
239 * stripped filename into the options QDict if there is such a prefix.
241 void bdrv_parse_filename_strip_prefix(const char *filename
, const char *prefix
,
244 if (strstart(filename
, prefix
, &filename
)) {
245 /* Stripping the explicit protocol prefix may result in a protocol
246 * prefix being (wrongly) detected (if the filename contains a colon) */
247 if (path_has_protocol(filename
)) {
248 GString
*fat_filename
;
250 /* This means there is some colon before the first slash; therefore,
251 * this cannot be an absolute path */
252 assert(!path_is_absolute(filename
));
254 /* And we can thus fix the protocol detection issue by prefixing it
256 fat_filename
= g_string_new("./");
257 g_string_append(fat_filename
, filename
);
259 assert(!path_has_protocol(fat_filename
->str
));
261 qdict_put(options
, "filename",
262 qstring_from_gstring(fat_filename
));
264 /* If no protocol prefix was detected, we can use the shortened
266 qdict_put_str(options
, "filename", filename
);
272 /* Returns whether the image file is opened as read-only. Note that this can
273 * return false and writing to the image file is still not possible because the
274 * image is inactivated. */
275 bool bdrv_is_read_only(BlockDriverState
*bs
)
278 return !(bs
->open_flags
& BDRV_O_RDWR
);
281 int bdrv_can_set_read_only(BlockDriverState
*bs
, bool read_only
,
282 bool ignore_allow_rdw
, Error
**errp
)
286 /* Do not set read_only if copy_on_read is enabled */
287 if (bs
->copy_on_read
&& read_only
) {
288 error_setg(errp
, "Can't set node '%s' to r/o with copy-on-read enabled",
289 bdrv_get_device_or_node_name(bs
));
293 /* Do not clear read_only if it is prohibited */
294 if (!read_only
&& !(bs
->open_flags
& BDRV_O_ALLOW_RDWR
) &&
297 error_setg(errp
, "Node '%s' is read only",
298 bdrv_get_device_or_node_name(bs
));
306 * Called by a driver that can only provide a read-only image.
308 * Returns 0 if the node is already read-only or it could switch the node to
309 * read-only because BDRV_O_AUTO_RDONLY is set.
311 * Returns -EACCES if the node is read-write and BDRV_O_AUTO_RDONLY is not set
312 * or bdrv_can_set_read_only() forbids making the node read-only. If @errmsg
313 * is not NULL, it is used as the error message for the Error object.
315 int bdrv_apply_auto_read_only(BlockDriverState
*bs
, const char *errmsg
,
321 if (!(bs
->open_flags
& BDRV_O_RDWR
)) {
324 if (!(bs
->open_flags
& BDRV_O_AUTO_RDONLY
)) {
328 ret
= bdrv_can_set_read_only(bs
, true, false, NULL
);
333 bs
->open_flags
&= ~BDRV_O_RDWR
;
338 error_setg(errp
, "%s", errmsg
?: "Image is read-only");
343 * If @backing is empty, this function returns NULL without setting
344 * @errp. In all other cases, NULL will only be returned with @errp
347 * Therefore, a return value of NULL without @errp set means that
348 * there is no backing file; if @errp is set, there is one but its
349 * absolute filename cannot be generated.
351 char *bdrv_get_full_backing_filename_from_filename(const char *backed
,
355 if (backing
[0] == '\0') {
357 } else if (path_has_protocol(backing
) || path_is_absolute(backing
)) {
358 return g_strdup(backing
);
359 } else if (backed
[0] == '\0' || strstart(backed
, "json:", NULL
)) {
360 error_setg(errp
, "Cannot use relative backing file names for '%s'",
364 return path_combine(backed
, backing
);
369 * If @filename is empty or NULL, this function returns NULL without
370 * setting @errp. In all other cases, NULL will only be returned with
373 static char *bdrv_make_absolute_filename(BlockDriverState
*relative_to
,
374 const char *filename
, Error
**errp
)
376 char *dir
, *full_name
;
378 if (!filename
|| filename
[0] == '\0') {
380 } else if (path_has_protocol(filename
) || path_is_absolute(filename
)) {
381 return g_strdup(filename
);
384 dir
= bdrv_dirname(relative_to
, errp
);
389 full_name
= g_strconcat(dir
, filename
, NULL
);
394 char *bdrv_get_full_backing_filename(BlockDriverState
*bs
, Error
**errp
)
397 return bdrv_make_absolute_filename(bs
, bs
->backing_file
, errp
);
400 void bdrv_register(BlockDriver
*bdrv
)
402 assert(bdrv
->format_name
);
404 QLIST_INSERT_HEAD(&bdrv_drivers
, bdrv
, list
);
407 BlockDriverState
*bdrv_new(void)
409 BlockDriverState
*bs
;
414 bs
= g_new0(BlockDriverState
, 1);
415 QLIST_INIT(&bs
->dirty_bitmaps
);
416 for (i
= 0; i
< BLOCK_OP_TYPE_MAX
; i
++) {
417 QLIST_INIT(&bs
->op_blockers
[i
]);
419 qemu_co_mutex_init(&bs
->reqs_lock
);
420 qemu_mutex_init(&bs
->dirty_bitmap_mutex
);
422 bs
->aio_context
= qemu_get_aio_context();
424 qemu_co_queue_init(&bs
->flush_queue
);
426 qemu_co_mutex_init(&bs
->bsc_modify_lock
);
427 bs
->block_status_cache
= g_new0(BdrvBlockStatusCache
, 1);
429 for (i
= 0; i
< bdrv_drain_all_count
; i
++) {
430 bdrv_drained_begin(bs
);
433 QTAILQ_INSERT_TAIL(&all_bdrv_states
, bs
, bs_list
);
438 static BlockDriver
*bdrv_do_find_format(const char *format_name
)
442 QLIST_FOREACH(drv1
, &bdrv_drivers
, list
) {
443 if (!strcmp(drv1
->format_name
, format_name
)) {
451 BlockDriver
*bdrv_find_format(const char *format_name
)
458 drv1
= bdrv_do_find_format(format_name
);
463 /* The driver isn't registered, maybe we need to load a module */
464 for (i
= 0; i
< (int)ARRAY_SIZE(block_driver_modules
); ++i
) {
465 if (!strcmp(block_driver_modules
[i
].format_name
, format_name
)) {
466 block_module_load_one(block_driver_modules
[i
].library_name
);
471 return bdrv_do_find_format(format_name
);
474 static int bdrv_format_is_whitelisted(const char *format_name
, bool read_only
)
476 static const char *whitelist_rw
[] = {
477 CONFIG_BDRV_RW_WHITELIST
480 static const char *whitelist_ro
[] = {
481 CONFIG_BDRV_RO_WHITELIST
486 if (!whitelist_rw
[0] && !whitelist_ro
[0]) {
487 return 1; /* no whitelist, anything goes */
490 for (p
= whitelist_rw
; *p
; p
++) {
491 if (!strcmp(format_name
, *p
)) {
496 for (p
= whitelist_ro
; *p
; p
++) {
497 if (!strcmp(format_name
, *p
)) {
505 int bdrv_is_whitelisted(BlockDriver
*drv
, bool read_only
)
508 return bdrv_format_is_whitelisted(drv
->format_name
, read_only
);
511 bool bdrv_uses_whitelist(void)
513 return use_bdrv_whitelist
;
516 typedef struct CreateCo
{
524 static void coroutine_fn
bdrv_create_co_entry(void *opaque
)
526 Error
*local_err
= NULL
;
529 CreateCo
*cco
= opaque
;
532 ret
= cco
->drv
->bdrv_co_create_opts(cco
->drv
,
533 cco
->filename
, cco
->opts
, &local_err
);
534 error_propagate(&cco
->err
, local_err
);
538 int bdrv_create(BlockDriver
*drv
, const char* filename
,
539 QemuOpts
*opts
, Error
**errp
)
548 .filename
= g_strdup(filename
),
554 if (!drv
->bdrv_co_create_opts
) {
555 error_setg(errp
, "Driver '%s' does not support image creation", drv
->format_name
);
560 if (qemu_in_coroutine()) {
561 /* Fast-path if already in coroutine context */
562 bdrv_create_co_entry(&cco
);
564 co
= qemu_coroutine_create(bdrv_create_co_entry
, &cco
);
565 qemu_coroutine_enter(co
);
566 while (cco
.ret
== NOT_DONE
) {
567 aio_poll(qemu_get_aio_context(), true);
574 error_propagate(errp
, cco
.err
);
576 error_setg_errno(errp
, -ret
, "Could not create image");
581 g_free(cco
.filename
);
586 * Helper function for bdrv_create_file_fallback(): Resize @blk to at
587 * least the given @minimum_size.
589 * On success, return @blk's actual length.
590 * Otherwise, return -errno.
592 static int64_t create_file_fallback_truncate(BlockBackend
*blk
,
593 int64_t minimum_size
, Error
**errp
)
595 Error
*local_err
= NULL
;
599 ret
= blk_truncate(blk
, minimum_size
, false, PREALLOC_MODE_OFF
, 0,
601 if (ret
< 0 && ret
!= -ENOTSUP
) {
602 error_propagate(errp
, local_err
);
606 size
= blk_getlength(blk
);
608 error_free(local_err
);
609 error_setg_errno(errp
, -size
,
610 "Failed to inquire the new image file's length");
614 if (size
< minimum_size
) {
615 /* Need to grow the image, but we failed to do that */
616 error_propagate(errp
, local_err
);
620 error_free(local_err
);
627 * Helper function for bdrv_create_file_fallback(): Zero the first
628 * sector to remove any potentially pre-existing image header.
630 static int create_file_fallback_zero_first_sector(BlockBackend
*blk
,
631 int64_t current_size
,
634 int64_t bytes_to_clear
;
637 bytes_to_clear
= MIN(current_size
, BDRV_SECTOR_SIZE
);
638 if (bytes_to_clear
) {
639 ret
= blk_pwrite_zeroes(blk
, 0, bytes_to_clear
, BDRV_REQ_MAY_UNMAP
);
641 error_setg_errno(errp
, -ret
,
642 "Failed to clear the new image's first sector");
651 * Simple implementation of bdrv_co_create_opts for protocol drivers
652 * which only support creation via opening a file
653 * (usually existing raw storage device)
655 int coroutine_fn
bdrv_co_create_opts_simple(BlockDriver
*drv
,
656 const char *filename
,
664 PreallocMode prealloc
;
665 Error
*local_err
= NULL
;
668 size
= qemu_opt_get_size_del(opts
, BLOCK_OPT_SIZE
, 0);
669 buf
= qemu_opt_get_del(opts
, BLOCK_OPT_PREALLOC
);
670 prealloc
= qapi_enum_parse(&PreallocMode_lookup
, buf
,
671 PREALLOC_MODE_OFF
, &local_err
);
674 error_propagate(errp
, local_err
);
678 if (prealloc
!= PREALLOC_MODE_OFF
) {
679 error_setg(errp
, "Unsupported preallocation mode '%s'",
680 PreallocMode_str(prealloc
));
684 options
= qdict_new();
685 qdict_put_str(options
, "driver", drv
->format_name
);
687 blk
= blk_new_open(filename
, NULL
, options
,
688 BDRV_O_RDWR
| BDRV_O_RESIZE
, errp
);
690 error_prepend(errp
, "Protocol driver '%s' does not support image "
691 "creation, and opening the image failed: ",
696 size
= create_file_fallback_truncate(blk
, size
, errp
);
702 ret
= create_file_fallback_zero_first_sector(blk
, size
, errp
);
713 int bdrv_create_file(const char *filename
, QemuOpts
*opts
, Error
**errp
)
715 QemuOpts
*protocol_opts
;
722 drv
= bdrv_find_protocol(filename
, true, errp
);
727 if (!drv
->create_opts
) {
728 error_setg(errp
, "Driver '%s' does not support image creation",
734 * 'opts' contains a QemuOptsList with a combination of format and protocol
737 * The format properly removes its options, but the default values remain
738 * in 'opts->list'. So if the protocol has options with the same name
739 * (e.g. rbd has 'cluster_size' as qcow2), it will see the default values
740 * of the format, since for overlapping options, the format wins.
742 * To avoid this issue, lets convert QemuOpts to QDict, in this way we take
743 * only the set options, and then convert it back to QemuOpts, using the
744 * create_opts of the protocol. So the new QemuOpts, will contain only the
747 qdict
= qemu_opts_to_qdict(opts
, NULL
);
748 protocol_opts
= qemu_opts_from_qdict(drv
->create_opts
, qdict
, errp
);
749 if (protocol_opts
== NULL
) {
754 ret
= bdrv_create(drv
, filename
, protocol_opts
, errp
);
756 qemu_opts_del(protocol_opts
);
757 qobject_unref(qdict
);
761 int coroutine_fn
bdrv_co_delete_file(BlockDriverState
*bs
, Error
**errp
)
763 Error
*local_err
= NULL
;
770 error_setg(errp
, "Block node '%s' is not opened", bs
->filename
);
774 if (!bs
->drv
->bdrv_co_delete_file
) {
775 error_setg(errp
, "Driver '%s' does not support image deletion",
776 bs
->drv
->format_name
);
780 ret
= bs
->drv
->bdrv_co_delete_file(bs
, &local_err
);
782 error_propagate(errp
, local_err
);
788 void coroutine_fn
bdrv_co_delete_file_noerr(BlockDriverState
*bs
)
790 Error
*local_err
= NULL
;
798 ret
= bdrv_co_delete_file(bs
, &local_err
);
800 * ENOTSUP will happen if the block driver doesn't support
801 * the 'bdrv_co_delete_file' interface. This is a predictable
802 * scenario and shouldn't be reported back to the user.
804 if (ret
== -ENOTSUP
) {
805 error_free(local_err
);
806 } else if (ret
< 0) {
807 error_report_err(local_err
);
812 * Try to get @bs's logical and physical block size.
813 * On success, store them in @bsz struct and return 0.
814 * On failure return -errno.
815 * @bs must not be empty.
817 int bdrv_probe_blocksizes(BlockDriverState
*bs
, BlockSizes
*bsz
)
819 BlockDriver
*drv
= bs
->drv
;
820 BlockDriverState
*filtered
= bdrv_filter_bs(bs
);
823 if (drv
&& drv
->bdrv_probe_blocksizes
) {
824 return drv
->bdrv_probe_blocksizes(bs
, bsz
);
825 } else if (filtered
) {
826 return bdrv_probe_blocksizes(filtered
, bsz
);
833 * Try to get @bs's geometry (cyls, heads, sectors).
834 * On success, store them in @geo struct and return 0.
835 * On failure return -errno.
836 * @bs must not be empty.
838 int bdrv_probe_geometry(BlockDriverState
*bs
, HDGeometry
*geo
)
840 BlockDriver
*drv
= bs
->drv
;
841 BlockDriverState
*filtered
= bdrv_filter_bs(bs
);
844 if (drv
&& drv
->bdrv_probe_geometry
) {
845 return drv
->bdrv_probe_geometry(bs
, geo
);
846 } else if (filtered
) {
847 return bdrv_probe_geometry(filtered
, geo
);
854 * Create a uniquely-named empty temporary file.
855 * Return 0 upon success, otherwise a negative errno value.
857 int get_tmp_filename(char *filename
, int size
)
860 char temp_dir
[MAX_PATH
];
861 /* GetTempFileName requires that its output buffer (4th param)
862 have length MAX_PATH or greater. */
863 assert(size
>= MAX_PATH
);
864 return (GetTempPath(MAX_PATH
, temp_dir
)
865 && GetTempFileName(temp_dir
, "qem", 0, filename
)
866 ? 0 : -GetLastError());
870 tmpdir
= getenv("TMPDIR");
874 if (snprintf(filename
, size
, "%s/vl.XXXXXX", tmpdir
) >= size
) {
877 fd
= mkstemp(filename
);
881 if (close(fd
) != 0) {
890 * Detect host devices. By convention, /dev/cdrom[N] is always
891 * recognized as a host CDROM.
893 static BlockDriver
*find_hdev_driver(const char *filename
)
895 int score_max
= 0, score
;
896 BlockDriver
*drv
= NULL
, *d
;
898 QLIST_FOREACH(d
, &bdrv_drivers
, list
) {
899 if (d
->bdrv_probe_device
) {
900 score
= d
->bdrv_probe_device(filename
);
901 if (score
> score_max
) {
911 static BlockDriver
*bdrv_do_find_protocol(const char *protocol
)
915 QLIST_FOREACH(drv1
, &bdrv_drivers
, list
) {
916 if (drv1
->protocol_name
&& !strcmp(drv1
->protocol_name
, protocol
)) {
924 BlockDriver
*bdrv_find_protocol(const char *filename
,
925 bool allow_protocol_prefix
,
935 /* TODO Drivers without bdrv_file_open must be specified explicitly */
938 * XXX(hch): we really should not let host device detection
939 * override an explicit protocol specification, but moving this
940 * later breaks access to device names with colons in them.
941 * Thanks to the brain-dead persistent naming schemes on udev-
942 * based Linux systems those actually are quite common.
944 drv1
= find_hdev_driver(filename
);
949 if (!path_has_protocol(filename
) || !allow_protocol_prefix
) {
953 p
= strchr(filename
, ':');
956 if (len
> sizeof(protocol
) - 1)
957 len
= sizeof(protocol
) - 1;
958 memcpy(protocol
, filename
, len
);
959 protocol
[len
] = '\0';
961 drv1
= bdrv_do_find_protocol(protocol
);
966 for (i
= 0; i
< (int)ARRAY_SIZE(block_driver_modules
); ++i
) {
967 if (block_driver_modules
[i
].protocol_name
&&
968 !strcmp(block_driver_modules
[i
].protocol_name
, protocol
)) {
969 block_module_load_one(block_driver_modules
[i
].library_name
);
974 drv1
= bdrv_do_find_protocol(protocol
);
976 error_setg(errp
, "Unknown protocol '%s'", protocol
);
982 * Guess image format by probing its contents.
983 * This is not a good idea when your image is raw (CVE-2008-2004), but
984 * we do it anyway for backward compatibility.
986 * @buf contains the image's first @buf_size bytes.
987 * @buf_size is the buffer size in bytes (generally BLOCK_PROBE_BUF_SIZE,
988 * but can be smaller if the image file is smaller)
989 * @filename is its filename.
991 * For all block drivers, call the bdrv_probe() method to get its
993 * Return the first block driver with the highest probing score.
995 BlockDriver
*bdrv_probe_all(const uint8_t *buf
, int buf_size
,
996 const char *filename
)
998 int score_max
= 0, score
;
999 BlockDriver
*drv
= NULL
, *d
;
1001 QLIST_FOREACH(d
, &bdrv_drivers
, list
) {
1002 if (d
->bdrv_probe
) {
1003 score
= d
->bdrv_probe(buf
, buf_size
, filename
);
1004 if (score
> score_max
) {
1014 static int find_image_format(BlockBackend
*file
, const char *filename
,
1015 BlockDriver
**pdrv
, Error
**errp
)
1018 uint8_t buf
[BLOCK_PROBE_BUF_SIZE
];
1021 /* Return the raw BlockDriver * to scsi-generic devices or empty drives */
1022 if (blk_is_sg(file
) || !blk_is_inserted(file
) || blk_getlength(file
) == 0) {
1027 ret
= blk_pread(file
, 0, buf
, sizeof(buf
));
1029 error_setg_errno(errp
, -ret
, "Could not read image for determining its "
1035 drv
= bdrv_probe_all(buf
, ret
, filename
);
1037 error_setg(errp
, "Could not determine image format: No compatible "
1046 * Set the current 'total_sectors' value
1047 * Return 0 on success, -errno on error.
1049 int refresh_total_sectors(BlockDriverState
*bs
, int64_t hint
)
1051 BlockDriver
*drv
= bs
->drv
;
1057 /* Do not attempt drv->bdrv_getlength() on scsi-generic devices */
1061 /* query actual device if possible, otherwise just trust the hint */
1062 if (drv
->bdrv_getlength
) {
1063 int64_t length
= drv
->bdrv_getlength(bs
);
1067 hint
= DIV_ROUND_UP(length
, BDRV_SECTOR_SIZE
);
1070 bs
->total_sectors
= hint
;
1072 if (bs
->total_sectors
* BDRV_SECTOR_SIZE
> BDRV_MAX_LENGTH
) {
1080 * Combines a QDict of new block driver @options with any missing options taken
1081 * from @old_options, so that leaving out an option defaults to its old value.
1083 static void bdrv_join_options(BlockDriverState
*bs
, QDict
*options
,
1086 if (bs
->drv
&& bs
->drv
->bdrv_join_options
) {
1087 bs
->drv
->bdrv_join_options(options
, old_options
);
1089 qdict_join(options
, old_options
, false);
1093 static BlockdevDetectZeroesOptions
bdrv_parse_detect_zeroes(QemuOpts
*opts
,
1097 Error
*local_err
= NULL
;
1098 char *value
= qemu_opt_get_del(opts
, "detect-zeroes");
1099 BlockdevDetectZeroesOptions detect_zeroes
=
1100 qapi_enum_parse(&BlockdevDetectZeroesOptions_lookup
, value
,
1101 BLOCKDEV_DETECT_ZEROES_OPTIONS_OFF
, &local_err
);
1104 error_propagate(errp
, local_err
);
1105 return detect_zeroes
;
1108 if (detect_zeroes
== BLOCKDEV_DETECT_ZEROES_OPTIONS_UNMAP
&&
1109 !(open_flags
& BDRV_O_UNMAP
))
1111 error_setg(errp
, "setting detect-zeroes to unmap is not allowed "
1112 "without setting discard operation to unmap");
1115 return detect_zeroes
;
1119 * Set open flags for aio engine
1121 * Return 0 on success, -1 if the engine specified is invalid
1123 int bdrv_parse_aio(const char *mode
, int *flags
)
1125 if (!strcmp(mode
, "threads")) {
1126 /* do nothing, default */
1127 } else if (!strcmp(mode
, "native")) {
1128 *flags
|= BDRV_O_NATIVE_AIO
;
1129 #ifdef CONFIG_LINUX_IO_URING
1130 } else if (!strcmp(mode
, "io_uring")) {
1131 *flags
|= BDRV_O_IO_URING
;
1141 * Set open flags for a given discard mode
1143 * Return 0 on success, -1 if the discard mode was invalid.
1145 int bdrv_parse_discard_flags(const char *mode
, int *flags
)
1147 *flags
&= ~BDRV_O_UNMAP
;
1149 if (!strcmp(mode
, "off") || !strcmp(mode
, "ignore")) {
1151 } else if (!strcmp(mode
, "on") || !strcmp(mode
, "unmap")) {
1152 *flags
|= BDRV_O_UNMAP
;
1161 * Set open flags for a given cache mode
1163 * Return 0 on success, -1 if the cache mode was invalid.
1165 int bdrv_parse_cache_mode(const char *mode
, int *flags
, bool *writethrough
)
1167 *flags
&= ~BDRV_O_CACHE_MASK
;
1169 if (!strcmp(mode
, "off") || !strcmp(mode
, "none")) {
1170 *writethrough
= false;
1171 *flags
|= BDRV_O_NOCACHE
;
1172 } else if (!strcmp(mode
, "directsync")) {
1173 *writethrough
= true;
1174 *flags
|= BDRV_O_NOCACHE
;
1175 } else if (!strcmp(mode
, "writeback")) {
1176 *writethrough
= false;
1177 } else if (!strcmp(mode
, "unsafe")) {
1178 *writethrough
= false;
1179 *flags
|= BDRV_O_NO_FLUSH
;
1180 } else if (!strcmp(mode
, "writethrough")) {
1181 *writethrough
= true;
1189 static char *bdrv_child_get_parent_desc(BdrvChild
*c
)
1191 BlockDriverState
*parent
= c
->opaque
;
1192 return g_strdup_printf("node '%s'", bdrv_get_node_name(parent
));
1195 static void bdrv_child_cb_drained_begin(BdrvChild
*child
)
1197 BlockDriverState
*bs
= child
->opaque
;
1198 bdrv_do_drained_begin_quiesce(bs
, NULL
, false);
1201 static bool bdrv_child_cb_drained_poll(BdrvChild
*child
)
1203 BlockDriverState
*bs
= child
->opaque
;
1204 return bdrv_drain_poll(bs
, false, NULL
, false);
1207 static void bdrv_child_cb_drained_end(BdrvChild
*child
,
1208 int *drained_end_counter
)
1210 BlockDriverState
*bs
= child
->opaque
;
1211 bdrv_drained_end_no_poll(bs
, drained_end_counter
);
1214 static int bdrv_child_cb_inactivate(BdrvChild
*child
)
1216 BlockDriverState
*bs
= child
->opaque
;
1217 assert(bs
->open_flags
& BDRV_O_INACTIVE
);
1221 static bool bdrv_child_cb_can_set_aio_ctx(BdrvChild
*child
, AioContext
*ctx
,
1222 GSList
**ignore
, Error
**errp
)
1224 BlockDriverState
*bs
= child
->opaque
;
1225 return bdrv_can_set_aio_context(bs
, ctx
, ignore
, errp
);
1228 static void bdrv_child_cb_set_aio_ctx(BdrvChild
*child
, AioContext
*ctx
,
1231 BlockDriverState
*bs
= child
->opaque
;
1232 return bdrv_set_aio_context_ignore(bs
, ctx
, ignore
);
1236 * Returns the options and flags that a temporary snapshot should get, based on
1237 * the originally requested flags (the originally requested image will have
1238 * flags like a backing file)
1240 static void bdrv_temp_snapshot_options(int *child_flags
, QDict
*child_options
,
1241 int parent_flags
, QDict
*parent_options
)
1243 *child_flags
= (parent_flags
& ~BDRV_O_SNAPSHOT
) | BDRV_O_TEMPORARY
;
1245 /* For temporary files, unconditional cache=unsafe is fine */
1246 qdict_set_default_str(child_options
, BDRV_OPT_CACHE_DIRECT
, "off");
1247 qdict_set_default_str(child_options
, BDRV_OPT_CACHE_NO_FLUSH
, "on");
1249 /* Copy the read-only and discard options from the parent */
1250 qdict_copy_default(child_options
, parent_options
, BDRV_OPT_READ_ONLY
);
1251 qdict_copy_default(child_options
, parent_options
, BDRV_OPT_DISCARD
);
1253 /* aio=native doesn't work for cache.direct=off, so disable it for the
1254 * temporary snapshot */
1255 *child_flags
&= ~BDRV_O_NATIVE_AIO
;
1258 static void bdrv_backing_attach(BdrvChild
*c
)
1260 BlockDriverState
*parent
= c
->opaque
;
1261 BlockDriverState
*backing_hd
= c
->bs
;
1263 assert(!parent
->backing_blocker
);
1264 error_setg(&parent
->backing_blocker
,
1265 "node is used as backing hd of '%s'",
1266 bdrv_get_device_or_node_name(parent
));
1268 bdrv_refresh_filename(backing_hd
);
1270 parent
->open_flags
&= ~BDRV_O_NO_BACKING
;
1272 bdrv_op_block_all(backing_hd
, parent
->backing_blocker
);
1273 /* Otherwise we won't be able to commit or stream */
1274 bdrv_op_unblock(backing_hd
, BLOCK_OP_TYPE_COMMIT_TARGET
,
1275 parent
->backing_blocker
);
1276 bdrv_op_unblock(backing_hd
, BLOCK_OP_TYPE_STREAM
,
1277 parent
->backing_blocker
);
1279 * We do backup in 3 ways:
1281 * The target bs is new opened, and the source is top BDS
1282 * 2. blockdev backup
1283 * Both the source and the target are top BDSes.
1284 * 3. internal backup(used for block replication)
1285 * Both the source and the target are backing file
1287 * In case 1 and 2, neither the source nor the target is the backing file.
1288 * In case 3, we will block the top BDS, so there is only one block job
1289 * for the top BDS and its backing chain.
1291 bdrv_op_unblock(backing_hd
, BLOCK_OP_TYPE_BACKUP_SOURCE
,
1292 parent
->backing_blocker
);
1293 bdrv_op_unblock(backing_hd
, BLOCK_OP_TYPE_BACKUP_TARGET
,
1294 parent
->backing_blocker
);
1297 static void bdrv_backing_detach(BdrvChild
*c
)
1299 BlockDriverState
*parent
= c
->opaque
;
1301 assert(parent
->backing_blocker
);
1302 bdrv_op_unblock_all(c
->bs
, parent
->backing_blocker
);
1303 error_free(parent
->backing_blocker
);
1304 parent
->backing_blocker
= NULL
;
1307 static int bdrv_backing_update_filename(BdrvChild
*c
, BlockDriverState
*base
,
1308 const char *filename
, Error
**errp
)
1310 BlockDriverState
*parent
= c
->opaque
;
1311 bool read_only
= bdrv_is_read_only(parent
);
1315 ret
= bdrv_reopen_set_read_only(parent
, false, errp
);
1321 ret
= bdrv_change_backing_file(parent
, filename
,
1322 base
->drv
? base
->drv
->format_name
: "",
1325 error_setg_errno(errp
, -ret
, "Could not update backing file link");
1329 bdrv_reopen_set_read_only(parent
, true, NULL
);
1336 * Returns the options and flags that a generic child of a BDS should
1337 * get, based on the given options and flags for the parent BDS.
1339 static void bdrv_inherited_options(BdrvChildRole role
, bool parent_is_format
,
1340 int *child_flags
, QDict
*child_options
,
1341 int parent_flags
, QDict
*parent_options
)
1343 int flags
= parent_flags
;
1346 * First, decide whether to set, clear, or leave BDRV_O_PROTOCOL.
1347 * Generally, the question to answer is: Should this child be
1348 * format-probed by default?
1352 * Pure and non-filtered data children of non-format nodes should
1353 * be probed by default (even when the node itself has BDRV_O_PROTOCOL
1354 * set). This only affects a very limited set of drivers (namely
1355 * quorum and blkverify when this comment was written).
1356 * Force-clear BDRV_O_PROTOCOL then.
1358 if (!parent_is_format
&&
1359 (role
& BDRV_CHILD_DATA
) &&
1360 !(role
& (BDRV_CHILD_METADATA
| BDRV_CHILD_FILTERED
)))
1362 flags
&= ~BDRV_O_PROTOCOL
;
1366 * All children of format nodes (except for COW children) and all
1367 * metadata children in general should never be format-probed.
1368 * Force-set BDRV_O_PROTOCOL then.
1370 if ((parent_is_format
&& !(role
& BDRV_CHILD_COW
)) ||
1371 (role
& BDRV_CHILD_METADATA
))
1373 flags
|= BDRV_O_PROTOCOL
;
1377 * If the cache mode isn't explicitly set, inherit direct and no-flush from
1380 qdict_copy_default(child_options
, parent_options
, BDRV_OPT_CACHE_DIRECT
);
1381 qdict_copy_default(child_options
, parent_options
, BDRV_OPT_CACHE_NO_FLUSH
);
1382 qdict_copy_default(child_options
, parent_options
, BDRV_OPT_FORCE_SHARE
);
1384 if (role
& BDRV_CHILD_COW
) {
1385 /* backing files are opened read-only by default */
1386 qdict_set_default_str(child_options
, BDRV_OPT_READ_ONLY
, "on");
1387 qdict_set_default_str(child_options
, BDRV_OPT_AUTO_READ_ONLY
, "off");
1389 /* Inherit the read-only option from the parent if it's not set */
1390 qdict_copy_default(child_options
, parent_options
, BDRV_OPT_READ_ONLY
);
1391 qdict_copy_default(child_options
, parent_options
,
1392 BDRV_OPT_AUTO_READ_ONLY
);
1396 * bdrv_co_pdiscard() respects unmap policy for the parent, so we
1397 * can default to enable it on lower layers regardless of the
1400 qdict_set_default_str(child_options
, BDRV_OPT_DISCARD
, "unmap");
1402 /* Clear flags that only apply to the top layer */
1403 flags
&= ~(BDRV_O_SNAPSHOT
| BDRV_O_NO_BACKING
| BDRV_O_COPY_ON_READ
);
1405 if (role
& BDRV_CHILD_METADATA
) {
1406 flags
&= ~BDRV_O_NO_IO
;
1408 if (role
& BDRV_CHILD_COW
) {
1409 flags
&= ~BDRV_O_TEMPORARY
;
1412 *child_flags
= flags
;
1415 static void bdrv_child_cb_attach(BdrvChild
*child
)
1417 BlockDriverState
*bs
= child
->opaque
;
1419 QLIST_INSERT_HEAD(&bs
->children
, child
, next
);
1421 if (child
->role
& BDRV_CHILD_COW
) {
1422 bdrv_backing_attach(child
);
1425 bdrv_apply_subtree_drain(child
, bs
);
1428 static void bdrv_child_cb_detach(BdrvChild
*child
)
1430 BlockDriverState
*bs
= child
->opaque
;
1432 if (child
->role
& BDRV_CHILD_COW
) {
1433 bdrv_backing_detach(child
);
1436 bdrv_unapply_subtree_drain(child
, bs
);
1438 QLIST_REMOVE(child
, next
);
1441 static int bdrv_child_cb_update_filename(BdrvChild
*c
, BlockDriverState
*base
,
1442 const char *filename
, Error
**errp
)
1444 if (c
->role
& BDRV_CHILD_COW
) {
1445 return bdrv_backing_update_filename(c
, base
, filename
, errp
);
1450 AioContext
*child_of_bds_get_parent_aio_context(BdrvChild
*c
)
1452 BlockDriverState
*bs
= c
->opaque
;
1455 return bdrv_get_aio_context(bs
);
1458 const BdrvChildClass child_of_bds
= {
1459 .parent_is_bds
= true,
1460 .get_parent_desc
= bdrv_child_get_parent_desc
,
1461 .inherit_options
= bdrv_inherited_options
,
1462 .drained_begin
= bdrv_child_cb_drained_begin
,
1463 .drained_poll
= bdrv_child_cb_drained_poll
,
1464 .drained_end
= bdrv_child_cb_drained_end
,
1465 .attach
= bdrv_child_cb_attach
,
1466 .detach
= bdrv_child_cb_detach
,
1467 .inactivate
= bdrv_child_cb_inactivate
,
1468 .can_set_aio_ctx
= bdrv_child_cb_can_set_aio_ctx
,
1469 .set_aio_ctx
= bdrv_child_cb_set_aio_ctx
,
1470 .update_filename
= bdrv_child_cb_update_filename
,
1471 .get_parent_aio_context
= child_of_bds_get_parent_aio_context
,
1474 AioContext
*bdrv_child_get_parent_aio_context(BdrvChild
*c
)
1477 return c
->klass
->get_parent_aio_context(c
);
1480 static int bdrv_open_flags(BlockDriverState
*bs
, int flags
)
1482 int open_flags
= flags
;
1485 * Clear flags that are internal to the block layer before opening the
1488 open_flags
&= ~(BDRV_O_SNAPSHOT
| BDRV_O_NO_BACKING
| BDRV_O_PROTOCOL
);
1493 static void update_flags_from_options(int *flags
, QemuOpts
*opts
)
1495 *flags
&= ~(BDRV_O_CACHE_MASK
| BDRV_O_RDWR
| BDRV_O_AUTO_RDONLY
);
1497 if (qemu_opt_get_bool_del(opts
, BDRV_OPT_CACHE_NO_FLUSH
, false)) {
1498 *flags
|= BDRV_O_NO_FLUSH
;
1501 if (qemu_opt_get_bool_del(opts
, BDRV_OPT_CACHE_DIRECT
, false)) {
1502 *flags
|= BDRV_O_NOCACHE
;
1505 if (!qemu_opt_get_bool_del(opts
, BDRV_OPT_READ_ONLY
, false)) {
1506 *flags
|= BDRV_O_RDWR
;
1509 if (qemu_opt_get_bool_del(opts
, BDRV_OPT_AUTO_READ_ONLY
, false)) {
1510 *flags
|= BDRV_O_AUTO_RDONLY
;
1514 static void update_options_from_flags(QDict
*options
, int flags
)
1516 if (!qdict_haskey(options
, BDRV_OPT_CACHE_DIRECT
)) {
1517 qdict_put_bool(options
, BDRV_OPT_CACHE_DIRECT
, flags
& BDRV_O_NOCACHE
);
1519 if (!qdict_haskey(options
, BDRV_OPT_CACHE_NO_FLUSH
)) {
1520 qdict_put_bool(options
, BDRV_OPT_CACHE_NO_FLUSH
,
1521 flags
& BDRV_O_NO_FLUSH
);
1523 if (!qdict_haskey(options
, BDRV_OPT_READ_ONLY
)) {
1524 qdict_put_bool(options
, BDRV_OPT_READ_ONLY
, !(flags
& BDRV_O_RDWR
));
1526 if (!qdict_haskey(options
, BDRV_OPT_AUTO_READ_ONLY
)) {
1527 qdict_put_bool(options
, BDRV_OPT_AUTO_READ_ONLY
,
1528 flags
& BDRV_O_AUTO_RDONLY
);
1532 static void bdrv_assign_node_name(BlockDriverState
*bs
,
1533 const char *node_name
,
1536 char *gen_node_name
= NULL
;
1539 node_name
= gen_node_name
= id_generate(ID_BLOCK
);
1540 } else if (!id_wellformed(node_name
)) {
1542 * Check for empty string or invalid characters, but not if it is
1543 * generated (generated names use characters not available to the user)
1545 error_setg(errp
, "Invalid node-name: '%s'", node_name
);
1549 /* takes care of avoiding namespaces collisions */
1550 if (blk_by_name(node_name
)) {
1551 error_setg(errp
, "node-name=%s is conflicting with a device id",
1556 /* takes care of avoiding duplicates node names */
1557 if (bdrv_find_node(node_name
)) {
1558 error_setg(errp
, "Duplicate nodes with node-name='%s'", node_name
);
1562 /* Make sure that the node name isn't truncated */
1563 if (strlen(node_name
) >= sizeof(bs
->node_name
)) {
1564 error_setg(errp
, "Node name too long");
1568 /* copy node name into the bs and insert it into the graph list */
1569 pstrcpy(bs
->node_name
, sizeof(bs
->node_name
), node_name
);
1570 QTAILQ_INSERT_TAIL(&graph_bdrv_states
, bs
, node_list
);
1572 g_free(gen_node_name
);
1575 static int bdrv_open_driver(BlockDriverState
*bs
, BlockDriver
*drv
,
1576 const char *node_name
, QDict
*options
,
1577 int open_flags
, Error
**errp
)
1579 Error
*local_err
= NULL
;
1582 bdrv_assign_node_name(bs
, node_name
, &local_err
);
1584 error_propagate(errp
, local_err
);
1589 bs
->opaque
= g_malloc0(drv
->instance_size
);
1591 if (drv
->bdrv_file_open
) {
1592 assert(!drv
->bdrv_needs_filename
|| bs
->filename
[0]);
1593 ret
= drv
->bdrv_file_open(bs
, options
, open_flags
, &local_err
);
1594 } else if (drv
->bdrv_open
) {
1595 ret
= drv
->bdrv_open(bs
, options
, open_flags
, &local_err
);
1602 error_propagate(errp
, local_err
);
1603 } else if (bs
->filename
[0]) {
1604 error_setg_errno(errp
, -ret
, "Could not open '%s'", bs
->filename
);
1606 error_setg_errno(errp
, -ret
, "Could not open image");
1611 ret
= refresh_total_sectors(bs
, bs
->total_sectors
);
1613 error_setg_errno(errp
, -ret
, "Could not refresh total sector count");
1617 bdrv_refresh_limits(bs
, NULL
, &local_err
);
1619 error_propagate(errp
, local_err
);
1623 assert(bdrv_opt_mem_align(bs
) != 0);
1624 assert(bdrv_min_mem_align(bs
) != 0);
1625 assert(is_power_of_2(bs
->bl
.request_alignment
));
1627 for (i
= 0; i
< bs
->quiesce_counter
; i
++) {
1628 if (drv
->bdrv_co_drain_begin
) {
1629 drv
->bdrv_co_drain_begin(bs
);
1636 if (bs
->file
!= NULL
) {
1637 bdrv_unref_child(bs
, bs
->file
);
1646 * Create and open a block node.
1648 * @options is a QDict of options to pass to the block drivers, or NULL for an
1649 * empty set of options. The reference to the QDict belongs to the block layer
1650 * after the call (even on failure), so if the caller intends to reuse the
1651 * dictionary, it needs to use qobject_ref() before calling bdrv_open.
1653 BlockDriverState
*bdrv_new_open_driver_opts(BlockDriver
*drv
,
1654 const char *node_name
,
1655 QDict
*options
, int flags
,
1658 BlockDriverState
*bs
;
1661 GLOBAL_STATE_CODE();
1664 bs
->open_flags
= flags
;
1665 bs
->options
= options
?: qdict_new();
1666 bs
->explicit_options
= qdict_clone_shallow(bs
->options
);
1669 update_options_from_flags(bs
->options
, flags
);
1671 ret
= bdrv_open_driver(bs
, drv
, node_name
, bs
->options
, flags
, errp
);
1673 qobject_unref(bs
->explicit_options
);
1674 bs
->explicit_options
= NULL
;
1675 qobject_unref(bs
->options
);
1684 /* Create and open a block node. */
1685 BlockDriverState
*bdrv_new_open_driver(BlockDriver
*drv
, const char *node_name
,
1686 int flags
, Error
**errp
)
1688 GLOBAL_STATE_CODE();
1689 return bdrv_new_open_driver_opts(drv
, node_name
, NULL
, flags
, errp
);
1692 QemuOptsList bdrv_runtime_opts
= {
1693 .name
= "bdrv_common",
1694 .head
= QTAILQ_HEAD_INITIALIZER(bdrv_runtime_opts
.head
),
1697 .name
= "node-name",
1698 .type
= QEMU_OPT_STRING
,
1699 .help
= "Node name of the block device node",
1703 .type
= QEMU_OPT_STRING
,
1704 .help
= "Block driver to use for the node",
1707 .name
= BDRV_OPT_CACHE_DIRECT
,
1708 .type
= QEMU_OPT_BOOL
,
1709 .help
= "Bypass software writeback cache on the host",
1712 .name
= BDRV_OPT_CACHE_NO_FLUSH
,
1713 .type
= QEMU_OPT_BOOL
,
1714 .help
= "Ignore flush requests",
1717 .name
= BDRV_OPT_READ_ONLY
,
1718 .type
= QEMU_OPT_BOOL
,
1719 .help
= "Node is opened in read-only mode",
1722 .name
= BDRV_OPT_AUTO_READ_ONLY
,
1723 .type
= QEMU_OPT_BOOL
,
1724 .help
= "Node can become read-only if opening read-write fails",
1727 .name
= "detect-zeroes",
1728 .type
= QEMU_OPT_STRING
,
1729 .help
= "try to optimize zero writes (off, on, unmap)",
1732 .name
= BDRV_OPT_DISCARD
,
1733 .type
= QEMU_OPT_STRING
,
1734 .help
= "discard operation (ignore/off, unmap/on)",
1737 .name
= BDRV_OPT_FORCE_SHARE
,
1738 .type
= QEMU_OPT_BOOL
,
1739 .help
= "always accept other writers (default: off)",
1741 { /* end of list */ }
1745 QemuOptsList bdrv_create_opts_simple
= {
1746 .name
= "simple-create-opts",
1747 .head
= QTAILQ_HEAD_INITIALIZER(bdrv_create_opts_simple
.head
),
1750 .name
= BLOCK_OPT_SIZE
,
1751 .type
= QEMU_OPT_SIZE
,
1752 .help
= "Virtual disk size"
1755 .name
= BLOCK_OPT_PREALLOC
,
1756 .type
= QEMU_OPT_STRING
,
1757 .help
= "Preallocation mode (allowed values: off)"
1759 { /* end of list */ }
1764 * Common part for opening disk images and files
1766 * Removes all processed options from *options.
1768 static int bdrv_open_common(BlockDriverState
*bs
, BlockBackend
*file
,
1769 QDict
*options
, Error
**errp
)
1771 int ret
, open_flags
;
1772 const char *filename
;
1773 const char *driver_name
= NULL
;
1774 const char *node_name
= NULL
;
1775 const char *discard
;
1778 Error
*local_err
= NULL
;
1781 assert(bs
->file
== NULL
);
1782 assert(options
!= NULL
&& bs
->options
!= options
);
1784 opts
= qemu_opts_create(&bdrv_runtime_opts
, NULL
, 0, &error_abort
);
1785 if (!qemu_opts_absorb_qdict(opts
, options
, errp
)) {
1790 update_flags_from_options(&bs
->open_flags
, opts
);
1792 driver_name
= qemu_opt_get(opts
, "driver");
1793 drv
= bdrv_find_format(driver_name
);
1794 assert(drv
!= NULL
);
1796 bs
->force_share
= qemu_opt_get_bool(opts
, BDRV_OPT_FORCE_SHARE
, false);
1798 if (bs
->force_share
&& (bs
->open_flags
& BDRV_O_RDWR
)) {
1800 BDRV_OPT_FORCE_SHARE
1801 "=on can only be used with read-only images");
1807 bdrv_refresh_filename(blk_bs(file
));
1808 filename
= blk_bs(file
)->filename
;
1811 * Caution: while qdict_get_try_str() is fine, getting
1812 * non-string types would require more care. When @options
1813 * come from -blockdev or blockdev_add, its members are typed
1814 * according to the QAPI schema, but when they come from
1815 * -drive, they're all QString.
1817 filename
= qdict_get_try_str(options
, "filename");
1820 if (drv
->bdrv_needs_filename
&& (!filename
|| !filename
[0])) {
1821 error_setg(errp
, "The '%s' block driver requires a file name",
1827 trace_bdrv_open_common(bs
, filename
?: "", bs
->open_flags
,
1830 ro
= bdrv_is_read_only(bs
);
1832 if (use_bdrv_whitelist
&& !bdrv_is_whitelisted(drv
, ro
)) {
1833 if (!ro
&& bdrv_is_whitelisted(drv
, true)) {
1834 ret
= bdrv_apply_auto_read_only(bs
, NULL
, NULL
);
1840 !ro
&& bdrv_is_whitelisted(drv
, true)
1841 ? "Driver '%s' can only be used for read-only devices"
1842 : "Driver '%s' is not whitelisted",
1848 /* bdrv_new() and bdrv_close() make it so */
1849 assert(qatomic_read(&bs
->copy_on_read
) == 0);
1851 if (bs
->open_flags
& BDRV_O_COPY_ON_READ
) {
1853 bdrv_enable_copy_on_read(bs
);
1855 error_setg(errp
, "Can't use copy-on-read on read-only device");
1861 discard
= qemu_opt_get(opts
, BDRV_OPT_DISCARD
);
1862 if (discard
!= NULL
) {
1863 if (bdrv_parse_discard_flags(discard
, &bs
->open_flags
) != 0) {
1864 error_setg(errp
, "Invalid discard option");
1871 bdrv_parse_detect_zeroes(opts
, bs
->open_flags
, &local_err
);
1873 error_propagate(errp
, local_err
);
1878 if (filename
!= NULL
) {
1879 pstrcpy(bs
->filename
, sizeof(bs
->filename
), filename
);
1881 bs
->filename
[0] = '\0';
1883 pstrcpy(bs
->exact_filename
, sizeof(bs
->exact_filename
), bs
->filename
);
1885 /* Open the image, either directly or using a protocol */
1886 open_flags
= bdrv_open_flags(bs
, bs
->open_flags
);
1887 node_name
= qemu_opt_get(opts
, "node-name");
1889 assert(!drv
->bdrv_file_open
|| file
== NULL
);
1890 ret
= bdrv_open_driver(bs
, drv
, node_name
, options
, open_flags
, errp
);
1895 qemu_opts_del(opts
);
1899 qemu_opts_del(opts
);
1903 static QDict
*parse_json_filename(const char *filename
, Error
**errp
)
1905 QObject
*options_obj
;
1909 ret
= strstart(filename
, "json:", &filename
);
1912 options_obj
= qobject_from_json(filename
, errp
);
1914 error_prepend(errp
, "Could not parse the JSON options: ");
1918 options
= qobject_to(QDict
, options_obj
);
1920 qobject_unref(options_obj
);
1921 error_setg(errp
, "Invalid JSON object given");
1925 qdict_flatten(options
);
1930 static void parse_json_protocol(QDict
*options
, const char **pfilename
,
1933 QDict
*json_options
;
1934 Error
*local_err
= NULL
;
1936 /* Parse json: pseudo-protocol */
1937 if (!*pfilename
|| !g_str_has_prefix(*pfilename
, "json:")) {
1941 json_options
= parse_json_filename(*pfilename
, &local_err
);
1943 error_propagate(errp
, local_err
);
1947 /* Options given in the filename have lower priority than options
1948 * specified directly */
1949 qdict_join(options
, json_options
, false);
1950 qobject_unref(json_options
);
1955 * Fills in default options for opening images and converts the legacy
1956 * filename/flags pair to option QDict entries.
1957 * The BDRV_O_PROTOCOL flag in *flags will be set or cleared accordingly if a
1958 * block driver has been specified explicitly.
1960 static int bdrv_fill_options(QDict
**options
, const char *filename
,
1961 int *flags
, Error
**errp
)
1963 const char *drvname
;
1964 bool protocol
= *flags
& BDRV_O_PROTOCOL
;
1965 bool parse_filename
= false;
1966 BlockDriver
*drv
= NULL
;
1967 Error
*local_err
= NULL
;
1970 * Caution: while qdict_get_try_str() is fine, getting non-string
1971 * types would require more care. When @options come from
1972 * -blockdev or blockdev_add, its members are typed according to
1973 * the QAPI schema, but when they come from -drive, they're all
1976 drvname
= qdict_get_try_str(*options
, "driver");
1978 drv
= bdrv_find_format(drvname
);
1980 error_setg(errp
, "Unknown driver '%s'", drvname
);
1983 /* If the user has explicitly specified the driver, this choice should
1984 * override the BDRV_O_PROTOCOL flag */
1985 protocol
= drv
->bdrv_file_open
;
1989 *flags
|= BDRV_O_PROTOCOL
;
1991 *flags
&= ~BDRV_O_PROTOCOL
;
1994 /* Translate cache options from flags into options */
1995 update_options_from_flags(*options
, *flags
);
1997 /* Fetch the file name from the options QDict if necessary */
1998 if (protocol
&& filename
) {
1999 if (!qdict_haskey(*options
, "filename")) {
2000 qdict_put_str(*options
, "filename", filename
);
2001 parse_filename
= true;
2003 error_setg(errp
, "Can't specify 'file' and 'filename' options at "
2009 /* Find the right block driver */
2010 /* See cautionary note on accessing @options above */
2011 filename
= qdict_get_try_str(*options
, "filename");
2013 if (!drvname
&& protocol
) {
2015 drv
= bdrv_find_protocol(filename
, parse_filename
, errp
);
2020 drvname
= drv
->format_name
;
2021 qdict_put_str(*options
, "driver", drvname
);
2023 error_setg(errp
, "Must specify either driver or file");
2028 assert(drv
|| !protocol
);
2030 /* Driver-specific filename parsing */
2031 if (drv
&& drv
->bdrv_parse_filename
&& parse_filename
) {
2032 drv
->bdrv_parse_filename(filename
, *options
, &local_err
);
2034 error_propagate(errp
, local_err
);
2038 if (!drv
->bdrv_needs_filename
) {
2039 qdict_del(*options
, "filename");
2046 typedef struct BlockReopenQueueEntry
{
2049 BDRVReopenState state
;
2050 QTAILQ_ENTRY(BlockReopenQueueEntry
) entry
;
2051 } BlockReopenQueueEntry
;
2054 * Return the flags that @bs will have after the reopens in @q have
2055 * successfully completed. If @q is NULL (or @bs is not contained in @q),
2056 * return the current flags.
2058 static int bdrv_reopen_get_flags(BlockReopenQueue
*q
, BlockDriverState
*bs
)
2060 BlockReopenQueueEntry
*entry
;
2063 QTAILQ_FOREACH(entry
, q
, entry
) {
2064 if (entry
->state
.bs
== bs
) {
2065 return entry
->state
.flags
;
2070 return bs
->open_flags
;
2073 /* Returns whether the image file can be written to after the reopen queue @q
2074 * has been successfully applied, or right now if @q is NULL. */
2075 static bool bdrv_is_writable_after_reopen(BlockDriverState
*bs
,
2076 BlockReopenQueue
*q
)
2078 int flags
= bdrv_reopen_get_flags(q
, bs
);
2080 return (flags
& (BDRV_O_RDWR
| BDRV_O_INACTIVE
)) == BDRV_O_RDWR
;
2084 * Return whether the BDS can be written to. This is not necessarily
2085 * the same as !bdrv_is_read_only(bs), as inactivated images may not
2086 * be written to but do not count as read-only images.
2088 bool bdrv_is_writable(BlockDriverState
*bs
)
2091 return bdrv_is_writable_after_reopen(bs
, NULL
);
2094 static char *bdrv_child_user_desc(BdrvChild
*c
)
2096 return c
->klass
->get_parent_desc(c
);
2100 * Check that @a allows everything that @b needs. @a and @b must reference same
2103 static bool bdrv_a_allow_b(BdrvChild
*a
, BdrvChild
*b
, Error
**errp
)
2105 const char *child_bs_name
;
2106 g_autofree
char *a_user
= NULL
;
2107 g_autofree
char *b_user
= NULL
;
2108 g_autofree
char *perms
= NULL
;
2111 assert(a
->bs
== b
->bs
);
2112 GLOBAL_STATE_CODE();
2114 if ((b
->perm
& a
->shared_perm
) == b
->perm
) {
2118 child_bs_name
= bdrv_get_node_name(b
->bs
);
2119 a_user
= bdrv_child_user_desc(a
);
2120 b_user
= bdrv_child_user_desc(b
);
2121 perms
= bdrv_perm_names(b
->perm
& ~a
->shared_perm
);
2123 error_setg(errp
, "Permission conflict on node '%s': permissions '%s' are "
2124 "both required by %s (uses node '%s' as '%s' child) and "
2125 "unshared by %s (uses node '%s' as '%s' child).",
2126 child_bs_name
, perms
,
2127 b_user
, child_bs_name
, b
->name
,
2128 a_user
, child_bs_name
, a
->name
);
2133 static bool bdrv_parent_perms_conflict(BlockDriverState
*bs
, Error
**errp
)
2136 GLOBAL_STATE_CODE();
2139 * During the loop we'll look at each pair twice. That's correct because
2140 * bdrv_a_allow_b() is asymmetric and we should check each pair in both
2143 QLIST_FOREACH(a
, &bs
->parents
, next_parent
) {
2144 QLIST_FOREACH(b
, &bs
->parents
, next_parent
) {
2149 if (!bdrv_a_allow_b(a
, b
, errp
)) {
2158 static void bdrv_child_perm(BlockDriverState
*bs
, BlockDriverState
*child_bs
,
2159 BdrvChild
*c
, BdrvChildRole role
,
2160 BlockReopenQueue
*reopen_queue
,
2161 uint64_t parent_perm
, uint64_t parent_shared
,
2162 uint64_t *nperm
, uint64_t *nshared
)
2164 assert(bs
->drv
&& bs
->drv
->bdrv_child_perm
);
2165 bs
->drv
->bdrv_child_perm(bs
, c
, role
, reopen_queue
,
2166 parent_perm
, parent_shared
,
2168 /* TODO Take force_share from reopen_queue */
2169 if (child_bs
&& child_bs
->force_share
) {
2170 *nshared
= BLK_PERM_ALL
;
2175 * Adds the whole subtree of @bs (including @bs itself) to the @list (except for
2176 * nodes that are already in the @list, of course) so that final list is
2177 * topologically sorted. Return the result (GSList @list object is updated, so
2178 * don't use old reference after function call).
2180 * On function start @list must be already topologically sorted and for any node
2181 * in the @list the whole subtree of the node must be in the @list as well. The
2182 * simplest way to satisfy this criteria: use only result of
2183 * bdrv_topological_dfs() or NULL as @list parameter.
2185 static GSList
*bdrv_topological_dfs(GSList
*list
, GHashTable
*found
,
2186 BlockDriverState
*bs
)
2189 g_autoptr(GHashTable
) local_found
= NULL
;
2193 found
= local_found
= g_hash_table_new(NULL
, NULL
);
2196 if (g_hash_table_contains(found
, bs
)) {
2199 g_hash_table_add(found
, bs
);
2201 QLIST_FOREACH(child
, &bs
->children
, next
) {
2202 list
= bdrv_topological_dfs(list
, found
, child
->bs
);
2205 return g_slist_prepend(list
, bs
);
2208 typedef struct BdrvChildSetPermState
{
2211 uint64_t old_shared_perm
;
2212 } BdrvChildSetPermState
;
2214 static void bdrv_child_set_perm_abort(void *opaque
)
2216 BdrvChildSetPermState
*s
= opaque
;
2218 GLOBAL_STATE_CODE();
2220 s
->child
->perm
= s
->old_perm
;
2221 s
->child
->shared_perm
= s
->old_shared_perm
;
2224 static TransactionActionDrv bdrv_child_set_pem_drv
= {
2225 .abort
= bdrv_child_set_perm_abort
,
2229 static void bdrv_child_set_perm(BdrvChild
*c
, uint64_t perm
,
2230 uint64_t shared
, Transaction
*tran
)
2232 BdrvChildSetPermState
*s
= g_new(BdrvChildSetPermState
, 1);
2233 GLOBAL_STATE_CODE();
2235 *s
= (BdrvChildSetPermState
) {
2237 .old_perm
= c
->perm
,
2238 .old_shared_perm
= c
->shared_perm
,
2242 c
->shared_perm
= shared
;
2244 tran_add(tran
, &bdrv_child_set_pem_drv
, s
);
2247 static void bdrv_drv_set_perm_commit(void *opaque
)
2249 BlockDriverState
*bs
= opaque
;
2250 uint64_t cumulative_perms
, cumulative_shared_perms
;
2252 if (bs
->drv
->bdrv_set_perm
) {
2253 bdrv_get_cumulative_perm(bs
, &cumulative_perms
,
2254 &cumulative_shared_perms
);
2255 bs
->drv
->bdrv_set_perm(bs
, cumulative_perms
, cumulative_shared_perms
);
2259 static void bdrv_drv_set_perm_abort(void *opaque
)
2261 BlockDriverState
*bs
= opaque
;
2263 if (bs
->drv
->bdrv_abort_perm_update
) {
2264 bs
->drv
->bdrv_abort_perm_update(bs
);
2268 TransactionActionDrv bdrv_drv_set_perm_drv
= {
2269 .abort
= bdrv_drv_set_perm_abort
,
2270 .commit
= bdrv_drv_set_perm_commit
,
2273 static int bdrv_drv_set_perm(BlockDriverState
*bs
, uint64_t perm
,
2274 uint64_t shared_perm
, Transaction
*tran
,
2281 if (bs
->drv
->bdrv_check_perm
) {
2282 int ret
= bs
->drv
->bdrv_check_perm(bs
, perm
, shared_perm
, errp
);
2289 tran_add(tran
, &bdrv_drv_set_perm_drv
, bs
);
2295 typedef struct BdrvReplaceChildState
{
2298 BlockDriverState
*old_bs
;
2299 bool free_empty_child
;
2300 } BdrvReplaceChildState
;
2302 static void bdrv_replace_child_commit(void *opaque
)
2304 BdrvReplaceChildState
*s
= opaque
;
2306 if (s
->free_empty_child
&& !s
->child
->bs
) {
2307 bdrv_child_free(s
->child
);
2309 bdrv_unref(s
->old_bs
);
2312 static void bdrv_replace_child_abort(void *opaque
)
2314 BdrvReplaceChildState
*s
= opaque
;
2315 BlockDriverState
*new_bs
= s
->child
->bs
;
2318 * old_bs reference is transparently moved from @s to s->child.
2320 * Pass &s->child here instead of s->childp, because:
2321 * (1) s->old_bs must be non-NULL, so bdrv_replace_child_noperm() will not
2322 * modify the BdrvChild * pointer we indirectly pass to it, i.e. it
2323 * will not modify s->child. From that perspective, it does not matter
2324 * whether we pass s->childp or &s->child.
2325 * (2) If new_bs is not NULL, s->childp will be NULL. We then cannot use
2327 * (3) If new_bs is NULL, *s->childp will have been NULLed by
2328 * bdrv_replace_child_tran()'s bdrv_replace_child_noperm() call, and we
2329 * must not pass a NULL *s->childp here.
2331 * So whether new_bs was NULL or not, we cannot pass s->childp here; and in
2332 * any case, there is no reason to pass it anyway.
2334 bdrv_replace_child_noperm(&s
->child
, s
->old_bs
, true);
2336 * The child was pre-existing, so s->old_bs must be non-NULL, and
2337 * s->child thus must not have been freed
2339 assert(s
->child
!= NULL
);
2341 /* As described above, *s->childp was cleared, so restore it */
2342 assert(s
->childp
!= NULL
);
2343 *s
->childp
= s
->child
;
2348 static TransactionActionDrv bdrv_replace_child_drv
= {
2349 .commit
= bdrv_replace_child_commit
,
2350 .abort
= bdrv_replace_child_abort
,
2355 * bdrv_replace_child_tran
2357 * Note: real unref of old_bs is done only on commit.
2359 * The function doesn't update permissions, caller is responsible for this.
2361 * (*childp)->bs must not be NULL.
2363 * Note that if new_bs == NULL, @childp is stored in a state object attached
2364 * to @tran, so that the old child can be reinstated in the abort handler.
2365 * Therefore, if @new_bs can be NULL, @childp must stay valid until the
2366 * transaction is committed or aborted.
2368 * If @free_empty_child is true and @new_bs is NULL, the BdrvChild is
2369 * freed (on commit). @free_empty_child should only be false if the
2370 * caller will free the BDrvChild themselves (which may be important
2371 * if this is in turn called in another transactional context).
2373 static void bdrv_replace_child_tran(BdrvChild
**childp
,
2374 BlockDriverState
*new_bs
,
2376 bool free_empty_child
)
2378 BdrvReplaceChildState
*s
= g_new(BdrvReplaceChildState
, 1);
2379 *s
= (BdrvReplaceChildState
) {
2381 .childp
= new_bs
== NULL
? childp
: NULL
,
2382 .old_bs
= (*childp
)->bs
,
2383 .free_empty_child
= free_empty_child
,
2385 tran_add(tran
, &bdrv_replace_child_drv
, s
);
2387 /* The abort handler relies on this */
2388 assert(s
->old_bs
!= NULL
);
2394 * Pass free_empty_child=false, we will free the child (if
2395 * necessary) in bdrv_replace_child_commit() (if our
2396 * @free_empty_child parameter was true).
2398 bdrv_replace_child_noperm(childp
, new_bs
, false);
2399 /* old_bs reference is transparently moved from *childp to @s */
2403 * Refresh permissions in @bs subtree. The function is intended to be called
2404 * after some graph modification that was done without permission update.
2406 static int bdrv_node_refresh_perm(BlockDriverState
*bs
, BlockReopenQueue
*q
,
2407 Transaction
*tran
, Error
**errp
)
2409 BlockDriver
*drv
= bs
->drv
;
2412 uint64_t cumulative_perms
, cumulative_shared_perms
;
2413 GLOBAL_STATE_CODE();
2415 bdrv_get_cumulative_perm(bs
, &cumulative_perms
, &cumulative_shared_perms
);
2417 /* Write permissions never work with read-only images */
2418 if ((cumulative_perms
& (BLK_PERM_WRITE
| BLK_PERM_WRITE_UNCHANGED
)) &&
2419 !bdrv_is_writable_after_reopen(bs
, q
))
2421 if (!bdrv_is_writable_after_reopen(bs
, NULL
)) {
2422 error_setg(errp
, "Block node is read-only");
2424 error_setg(errp
, "Read-only block node '%s' cannot support "
2425 "read-write users", bdrv_get_node_name(bs
));
2432 * Unaligned requests will automatically be aligned to bl.request_alignment
2433 * and without RESIZE we can't extend requests to write to space beyond the
2434 * end of the image, so it's required that the image size is aligned.
2436 if ((cumulative_perms
& (BLK_PERM_WRITE
| BLK_PERM_WRITE_UNCHANGED
)) &&
2437 !(cumulative_perms
& BLK_PERM_RESIZE
))
2439 if ((bs
->total_sectors
* BDRV_SECTOR_SIZE
) % bs
->bl
.request_alignment
) {
2440 error_setg(errp
, "Cannot get 'write' permission without 'resize': "
2441 "Image size is not a multiple of request "
2447 /* Check this node */
2452 ret
= bdrv_drv_set_perm(bs
, cumulative_perms
, cumulative_shared_perms
, tran
,
2458 /* Drivers that never have children can omit .bdrv_child_perm() */
2459 if (!drv
->bdrv_child_perm
) {
2460 assert(QLIST_EMPTY(&bs
->children
));
2464 /* Check all children */
2465 QLIST_FOREACH(c
, &bs
->children
, next
) {
2466 uint64_t cur_perm
, cur_shared
;
2468 bdrv_child_perm(bs
, c
->bs
, c
, c
->role
, q
,
2469 cumulative_perms
, cumulative_shared_perms
,
2470 &cur_perm
, &cur_shared
);
2471 bdrv_child_set_perm(c
, cur_perm
, cur_shared
, tran
);
2477 static int bdrv_list_refresh_perms(GSList
*list
, BlockReopenQueue
*q
,
2478 Transaction
*tran
, Error
**errp
)
2481 BlockDriverState
*bs
;
2482 GLOBAL_STATE_CODE();
2484 for ( ; list
; list
= list
->next
) {
2487 if (bdrv_parent_perms_conflict(bs
, errp
)) {
2491 ret
= bdrv_node_refresh_perm(bs
, q
, tran
, errp
);
2500 void bdrv_get_cumulative_perm(BlockDriverState
*bs
, uint64_t *perm
,
2501 uint64_t *shared_perm
)
2504 uint64_t cumulative_perms
= 0;
2505 uint64_t cumulative_shared_perms
= BLK_PERM_ALL
;
2507 QLIST_FOREACH(c
, &bs
->parents
, next_parent
) {
2508 cumulative_perms
|= c
->perm
;
2509 cumulative_shared_perms
&= c
->shared_perm
;
2512 *perm
= cumulative_perms
;
2513 *shared_perm
= cumulative_shared_perms
;
2516 char *bdrv_perm_names(uint64_t perm
)
2522 { BLK_PERM_CONSISTENT_READ
, "consistent read" },
2523 { BLK_PERM_WRITE
, "write" },
2524 { BLK_PERM_WRITE_UNCHANGED
, "write unchanged" },
2525 { BLK_PERM_RESIZE
, "resize" },
2529 GString
*result
= g_string_sized_new(30);
2530 struct perm_name
*p
;
2532 for (p
= permissions
; p
->name
; p
++) {
2533 if (perm
& p
->perm
) {
2534 if (result
->len
> 0) {
2535 g_string_append(result
, ", ");
2537 g_string_append(result
, p
->name
);
2541 return g_string_free(result
, FALSE
);
2545 static int bdrv_refresh_perms(BlockDriverState
*bs
, Error
**errp
)
2548 Transaction
*tran
= tran_new();
2549 g_autoptr(GSList
) list
= bdrv_topological_dfs(NULL
, NULL
, bs
);
2550 GLOBAL_STATE_CODE();
2552 ret
= bdrv_list_refresh_perms(list
, NULL
, tran
, errp
);
2553 tran_finalize(tran
, ret
);
2558 int bdrv_child_try_set_perm(BdrvChild
*c
, uint64_t perm
, uint64_t shared
,
2561 Error
*local_err
= NULL
;
2562 Transaction
*tran
= tran_new();
2565 bdrv_child_set_perm(c
, perm
, shared
, tran
);
2567 ret
= bdrv_refresh_perms(c
->bs
, &local_err
);
2569 tran_finalize(tran
, ret
);
2572 if ((perm
& ~c
->perm
) || (c
->shared_perm
& ~shared
)) {
2573 /* tighten permissions */
2574 error_propagate(errp
, local_err
);
2577 * Our caller may intend to only loosen restrictions and
2578 * does not expect this function to fail. Errors are not
2579 * fatal in such a case, so we can just hide them from our
2582 error_free(local_err
);
2590 int bdrv_child_refresh_perms(BlockDriverState
*bs
, BdrvChild
*c
, Error
**errp
)
2592 uint64_t parent_perms
, parent_shared
;
2593 uint64_t perms
, shared
;
2595 bdrv_get_cumulative_perm(bs
, &parent_perms
, &parent_shared
);
2596 bdrv_child_perm(bs
, c
->bs
, c
, c
->role
, NULL
,
2597 parent_perms
, parent_shared
, &perms
, &shared
);
2599 return bdrv_child_try_set_perm(c
, perms
, shared
, errp
);
2603 * Default implementation for .bdrv_child_perm() for block filters:
2604 * Forward CONSISTENT_READ, WRITE, WRITE_UNCHANGED, and RESIZE to the
2607 static void bdrv_filter_default_perms(BlockDriverState
*bs
, BdrvChild
*c
,
2609 BlockReopenQueue
*reopen_queue
,
2610 uint64_t perm
, uint64_t shared
,
2611 uint64_t *nperm
, uint64_t *nshared
)
2613 GLOBAL_STATE_CODE();
2614 *nperm
= perm
& DEFAULT_PERM_PASSTHROUGH
;
2615 *nshared
= (shared
& DEFAULT_PERM_PASSTHROUGH
) | DEFAULT_PERM_UNCHANGED
;
2618 static void bdrv_default_perms_for_cow(BlockDriverState
*bs
, BdrvChild
*c
,
2620 BlockReopenQueue
*reopen_queue
,
2621 uint64_t perm
, uint64_t shared
,
2622 uint64_t *nperm
, uint64_t *nshared
)
2624 assert(role
& BDRV_CHILD_COW
);
2625 GLOBAL_STATE_CODE();
2628 * We want consistent read from backing files if the parent needs it.
2629 * No other operations are performed on backing files.
2631 perm
&= BLK_PERM_CONSISTENT_READ
;
2634 * If the parent can deal with changing data, we're okay with a
2635 * writable and resizable backing file.
2636 * TODO Require !(perm & BLK_PERM_CONSISTENT_READ), too?
2638 if (shared
& BLK_PERM_WRITE
) {
2639 shared
= BLK_PERM_WRITE
| BLK_PERM_RESIZE
;
2644 shared
|= BLK_PERM_CONSISTENT_READ
| BLK_PERM_WRITE_UNCHANGED
;
2646 if (bs
->open_flags
& BDRV_O_INACTIVE
) {
2647 shared
|= BLK_PERM_WRITE
| BLK_PERM_RESIZE
;
2654 static void bdrv_default_perms_for_storage(BlockDriverState
*bs
, BdrvChild
*c
,
2656 BlockReopenQueue
*reopen_queue
,
2657 uint64_t perm
, uint64_t shared
,
2658 uint64_t *nperm
, uint64_t *nshared
)
2662 GLOBAL_STATE_CODE();
2663 assert(role
& (BDRV_CHILD_METADATA
| BDRV_CHILD_DATA
));
2665 flags
= bdrv_reopen_get_flags(reopen_queue
, bs
);
2668 * Apart from the modifications below, the same permissions are
2669 * forwarded and left alone as for filters
2671 bdrv_filter_default_perms(bs
, c
, role
, reopen_queue
,
2672 perm
, shared
, &perm
, &shared
);
2674 if (role
& BDRV_CHILD_METADATA
) {
2675 /* Format drivers may touch metadata even if the guest doesn't write */
2676 if (bdrv_is_writable_after_reopen(bs
, reopen_queue
)) {
2677 perm
|= BLK_PERM_WRITE
| BLK_PERM_RESIZE
;
2681 * bs->file always needs to be consistent because of the
2682 * metadata. We can never allow other users to resize or write
2685 if (!(flags
& BDRV_O_NO_IO
)) {
2686 perm
|= BLK_PERM_CONSISTENT_READ
;
2688 shared
&= ~(BLK_PERM_WRITE
| BLK_PERM_RESIZE
);
2691 if (role
& BDRV_CHILD_DATA
) {
2693 * Technically, everything in this block is a subset of the
2694 * BDRV_CHILD_METADATA path taken above, and so this could
2695 * be an "else if" branch. However, that is not obvious, and
2696 * this function is not performance critical, therefore we let
2697 * this be an independent "if".
2701 * We cannot allow other users to resize the file because the
2702 * format driver might have some assumptions about the size
2703 * (e.g. because it is stored in metadata, or because the file
2704 * is split into fixed-size data files).
2706 shared
&= ~BLK_PERM_RESIZE
;
2709 * WRITE_UNCHANGED often cannot be performed as such on the
2710 * data file. For example, the qcow2 driver may still need to
2711 * write copied clusters on copy-on-read.
2713 if (perm
& BLK_PERM_WRITE_UNCHANGED
) {
2714 perm
|= BLK_PERM_WRITE
;
2718 * If the data file is written to, the format driver may
2719 * expect to be able to resize it by writing beyond the EOF.
2721 if (perm
& BLK_PERM_WRITE
) {
2722 perm
|= BLK_PERM_RESIZE
;
2726 if (bs
->open_flags
& BDRV_O_INACTIVE
) {
2727 shared
|= BLK_PERM_WRITE
| BLK_PERM_RESIZE
;
2734 void bdrv_default_perms(BlockDriverState
*bs
, BdrvChild
*c
,
2735 BdrvChildRole role
, BlockReopenQueue
*reopen_queue
,
2736 uint64_t perm
, uint64_t shared
,
2737 uint64_t *nperm
, uint64_t *nshared
)
2739 if (role
& BDRV_CHILD_FILTERED
) {
2740 assert(!(role
& (BDRV_CHILD_DATA
| BDRV_CHILD_METADATA
|
2742 bdrv_filter_default_perms(bs
, c
, role
, reopen_queue
,
2743 perm
, shared
, nperm
, nshared
);
2744 } else if (role
& BDRV_CHILD_COW
) {
2745 assert(!(role
& (BDRV_CHILD_DATA
| BDRV_CHILD_METADATA
)));
2746 bdrv_default_perms_for_cow(bs
, c
, role
, reopen_queue
,
2747 perm
, shared
, nperm
, nshared
);
2748 } else if (role
& (BDRV_CHILD_METADATA
| BDRV_CHILD_DATA
)) {
2749 bdrv_default_perms_for_storage(bs
, c
, role
, reopen_queue
,
2750 perm
, shared
, nperm
, nshared
);
2752 g_assert_not_reached();
2756 uint64_t bdrv_qapi_perm_to_blk_perm(BlockPermission qapi_perm
)
2758 static const uint64_t permissions
[] = {
2759 [BLOCK_PERMISSION_CONSISTENT_READ
] = BLK_PERM_CONSISTENT_READ
,
2760 [BLOCK_PERMISSION_WRITE
] = BLK_PERM_WRITE
,
2761 [BLOCK_PERMISSION_WRITE_UNCHANGED
] = BLK_PERM_WRITE_UNCHANGED
,
2762 [BLOCK_PERMISSION_RESIZE
] = BLK_PERM_RESIZE
,
2765 QEMU_BUILD_BUG_ON(ARRAY_SIZE(permissions
) != BLOCK_PERMISSION__MAX
);
2766 QEMU_BUILD_BUG_ON(1UL << ARRAY_SIZE(permissions
) != BLK_PERM_ALL
+ 1);
2768 assert(qapi_perm
< BLOCK_PERMISSION__MAX
);
2770 return permissions
[qapi_perm
];
2774 * Replace (*childp)->bs by @new_bs.
2776 * If @new_bs is NULL, *childp will be set to NULL, too: BDS parents
2777 * generally cannot handle a BdrvChild with .bs == NULL, so clearing
2778 * BdrvChild.bs should generally immediately be followed by the
2779 * BdrvChild pointer being cleared as well.
2781 * If @free_empty_child is true and @new_bs is NULL, the BdrvChild is
2782 * freed. @free_empty_child should only be false if the caller will
2783 * free the BdrvChild themselves (this may be important in a
2784 * transactional context, where it may only be freed on commit).
2786 static void bdrv_replace_child_noperm(BdrvChild
**childp
,
2787 BlockDriverState
*new_bs
,
2788 bool free_empty_child
)
2790 BdrvChild
*child
= *childp
;
2791 BlockDriverState
*old_bs
= child
->bs
;
2792 int new_bs_quiesce_counter
;
2795 assert(!child
->frozen
);
2796 assert(old_bs
!= new_bs
);
2798 if (old_bs
&& new_bs
) {
2799 assert(bdrv_get_aio_context(old_bs
) == bdrv_get_aio_context(new_bs
));
2802 new_bs_quiesce_counter
= (new_bs
? new_bs
->quiesce_counter
: 0);
2803 drain_saldo
= new_bs_quiesce_counter
- child
->parent_quiesce_counter
;
2806 * If the new child node is drained but the old one was not, flush
2807 * all outstanding requests to the old child node.
2809 while (drain_saldo
> 0 && child
->klass
->drained_begin
) {
2810 bdrv_parent_drained_begin_single(child
, true);
2815 /* Detach first so that the recursive drain sections coming from @child
2816 * are already gone and we only end the drain sections that came from
2818 if (child
->klass
->detach
) {
2819 child
->klass
->detach(child
);
2821 QLIST_REMOVE(child
, next_parent
);
2830 QLIST_INSERT_HEAD(&new_bs
->parents
, child
, next_parent
);
2833 * Detaching the old node may have led to the new node's
2834 * quiesce_counter having been decreased. Not a problem, we
2835 * just need to recognize this here and then invoke
2836 * drained_end appropriately more often.
2838 assert(new_bs
->quiesce_counter
<= new_bs_quiesce_counter
);
2839 drain_saldo
+= new_bs
->quiesce_counter
- new_bs_quiesce_counter
;
2841 /* Attach only after starting new drained sections, so that recursive
2842 * drain sections coming from @child don't get an extra .drained_begin
2844 if (child
->klass
->attach
) {
2845 child
->klass
->attach(child
);
2850 * If the old child node was drained but the new one is not, allow
2851 * requests to come in only after the new node has been attached.
2853 while (drain_saldo
< 0 && child
->klass
->drained_end
) {
2854 bdrv_parent_drained_end_single(child
);
2858 if (free_empty_child
&& !child
->bs
) {
2859 bdrv_child_free(child
);
2864 * Free the given @child.
2866 * The child must be empty (i.e. `child->bs == NULL`) and it must be
2867 * unused (i.e. not in a children list).
2869 static void bdrv_child_free(BdrvChild
*child
)
2872 assert(!child
->next
.le_prev
); /* not in children list */
2874 g_free(child
->name
);
2878 typedef struct BdrvAttachChildCommonState
{
2880 AioContext
*old_parent_ctx
;
2881 AioContext
*old_child_ctx
;
2882 } BdrvAttachChildCommonState
;
2884 static void bdrv_attach_child_common_abort(void *opaque
)
2886 BdrvAttachChildCommonState
*s
= opaque
;
2887 BdrvChild
*child
= *s
->child
;
2888 BlockDriverState
*bs
= child
->bs
;
2891 * Pass free_empty_child=false, because we still need the child
2892 * for the AioContext operations on the parent below; those
2893 * BdrvChildClass methods all work on a BdrvChild object, so we
2894 * need to keep it as an empty shell (after this function, it will
2895 * not be attached to any parent, and it will not have a .bs).
2897 bdrv_replace_child_noperm(s
->child
, NULL
, false);
2899 if (bdrv_get_aio_context(bs
) != s
->old_child_ctx
) {
2900 bdrv_try_set_aio_context(bs
, s
->old_child_ctx
, &error_abort
);
2903 if (bdrv_child_get_parent_aio_context(child
) != s
->old_parent_ctx
) {
2906 /* No need to ignore `child`, because it has been detached already */
2908 child
->klass
->can_set_aio_ctx(child
, s
->old_parent_ctx
, &ignore
,
2910 g_slist_free(ignore
);
2913 child
->klass
->set_aio_ctx(child
, s
->old_parent_ctx
, &ignore
);
2914 g_slist_free(ignore
);
2918 bdrv_child_free(child
);
2921 static TransactionActionDrv bdrv_attach_child_common_drv
= {
2922 .abort
= bdrv_attach_child_common_abort
,
2927 * Common part of attaching bdrv child to bs or to blk or to job
2929 * Resulting new child is returned through @child.
2930 * At start *@child must be NULL.
2931 * @child is saved to a new entry of @tran, so that *@child could be reverted to
2932 * NULL on abort(). So referenced variable must live at least until transaction
2935 * Function doesn't update permissions, caller is responsible for this.
2937 static int bdrv_attach_child_common(BlockDriverState
*child_bs
,
2938 const char *child_name
,
2939 const BdrvChildClass
*child_class
,
2940 BdrvChildRole child_role
,
2941 uint64_t perm
, uint64_t shared_perm
,
2942 void *opaque
, BdrvChild
**child
,
2943 Transaction
*tran
, Error
**errp
)
2945 BdrvChild
*new_child
;
2946 AioContext
*parent_ctx
;
2947 AioContext
*child_ctx
= bdrv_get_aio_context(child_bs
);
2950 assert(*child
== NULL
);
2951 assert(child_class
->get_parent_desc
);
2953 new_child
= g_new(BdrvChild
, 1);
2954 *new_child
= (BdrvChild
) {
2956 .name
= g_strdup(child_name
),
2957 .klass
= child_class
,
2960 .shared_perm
= shared_perm
,
2965 * If the AioContexts don't match, first try to move the subtree of
2966 * child_bs into the AioContext of the new parent. If this doesn't work,
2967 * try moving the parent into the AioContext of child_bs instead.
2969 parent_ctx
= bdrv_child_get_parent_aio_context(new_child
);
2970 if (child_ctx
!= parent_ctx
) {
2971 Error
*local_err
= NULL
;
2972 int ret
= bdrv_try_set_aio_context(child_bs
, parent_ctx
, &local_err
);
2974 if (ret
< 0 && child_class
->can_set_aio_ctx
) {
2975 GSList
*ignore
= g_slist_prepend(NULL
, new_child
);
2976 if (child_class
->can_set_aio_ctx(new_child
, child_ctx
, &ignore
,
2979 error_free(local_err
);
2981 g_slist_free(ignore
);
2982 ignore
= g_slist_prepend(NULL
, new_child
);
2983 child_class
->set_aio_ctx(new_child
, child_ctx
, &ignore
);
2985 g_slist_free(ignore
);
2989 error_propagate(errp
, local_err
);
2990 bdrv_child_free(new_child
);
2996 bdrv_replace_child_noperm(&new_child
, child_bs
, true);
2997 /* child_bs was non-NULL, so new_child must not have been freed */
2998 assert(new_child
!= NULL
);
3002 BdrvAttachChildCommonState
*s
= g_new(BdrvAttachChildCommonState
, 1);
3003 *s
= (BdrvAttachChildCommonState
) {
3005 .old_parent_ctx
= parent_ctx
,
3006 .old_child_ctx
= child_ctx
,
3008 tran_add(tran
, &bdrv_attach_child_common_drv
, s
);
3014 * Variable referenced by @child must live at least until transaction end.
3015 * (see bdrv_attach_child_common() doc for details)
3017 * Function doesn't update permissions, caller is responsible for this.
3019 static int bdrv_attach_child_noperm(BlockDriverState
*parent_bs
,
3020 BlockDriverState
*child_bs
,
3021 const char *child_name
,
3022 const BdrvChildClass
*child_class
,
3023 BdrvChildRole child_role
,
3029 uint64_t perm
, shared_perm
;
3031 assert(parent_bs
->drv
);
3033 if (bdrv_recurse_has_child(child_bs
, parent_bs
)) {
3034 error_setg(errp
, "Making '%s' a %s child of '%s' would create a cycle",
3035 child_bs
->node_name
, child_name
, parent_bs
->node_name
);
3039 bdrv_get_cumulative_perm(parent_bs
, &perm
, &shared_perm
);
3040 bdrv_child_perm(parent_bs
, child_bs
, NULL
, child_role
, NULL
,
3041 perm
, shared_perm
, &perm
, &shared_perm
);
3043 ret
= bdrv_attach_child_common(child_bs
, child_name
, child_class
,
3044 child_role
, perm
, shared_perm
, parent_bs
,
3053 static void bdrv_detach_child(BdrvChild
**childp
)
3055 BlockDriverState
*old_bs
= (*childp
)->bs
;
3057 bdrv_replace_child_noperm(childp
, NULL
, true);
3061 * Update permissions for old node. We're just taking a parent away, so
3062 * we're loosening restrictions. Errors of permission update are not
3063 * fatal in this case, ignore them.
3065 bdrv_refresh_perms(old_bs
, NULL
);
3068 * When the parent requiring a non-default AioContext is removed, the
3069 * node moves back to the main AioContext
3071 bdrv_try_set_aio_context(old_bs
, qemu_get_aio_context(), NULL
);
3076 * This function steals the reference to child_bs from the caller.
3077 * That reference is later dropped by bdrv_root_unref_child().
3079 * On failure NULL is returned, errp is set and the reference to
3080 * child_bs is also dropped.
3082 * The caller must hold the AioContext lock @child_bs, but not that of @ctx
3083 * (unless @child_bs is already in @ctx).
3085 BdrvChild
*bdrv_root_attach_child(BlockDriverState
*child_bs
,
3086 const char *child_name
,
3087 const BdrvChildClass
*child_class
,
3088 BdrvChildRole child_role
,
3089 uint64_t perm
, uint64_t shared_perm
,
3090 void *opaque
, Error
**errp
)
3093 BdrvChild
*child
= NULL
;
3094 Transaction
*tran
= tran_new();
3096 ret
= bdrv_attach_child_common(child_bs
, child_name
, child_class
,
3097 child_role
, perm
, shared_perm
, opaque
,
3098 &child
, tran
, errp
);
3103 ret
= bdrv_refresh_perms(child_bs
, errp
);
3106 tran_finalize(tran
, ret
);
3107 /* child is unset on failure by bdrv_attach_child_common_abort() */
3108 assert((ret
< 0) == !child
);
3110 bdrv_unref(child_bs
);
3115 * This function transfers the reference to child_bs from the caller
3116 * to parent_bs. That reference is later dropped by parent_bs on
3117 * bdrv_close() or if someone calls bdrv_unref_child().
3119 * On failure NULL is returned, errp is set and the reference to
3120 * child_bs is also dropped.
3122 * If @parent_bs and @child_bs are in different AioContexts, the caller must
3123 * hold the AioContext lock for @child_bs, but not for @parent_bs.
3125 BdrvChild
*bdrv_attach_child(BlockDriverState
*parent_bs
,
3126 BlockDriverState
*child_bs
,
3127 const char *child_name
,
3128 const BdrvChildClass
*child_class
,
3129 BdrvChildRole child_role
,
3133 BdrvChild
*child
= NULL
;
3134 Transaction
*tran
= tran_new();
3136 GLOBAL_STATE_CODE();
3138 ret
= bdrv_attach_child_noperm(parent_bs
, child_bs
, child_name
, child_class
,
3139 child_role
, &child
, tran
, errp
);
3144 ret
= bdrv_refresh_perms(parent_bs
, errp
);
3150 tran_finalize(tran
, ret
);
3151 /* child is unset on failure by bdrv_attach_child_common_abort() */
3152 assert((ret
< 0) == !child
);
3154 bdrv_unref(child_bs
);
3159 /* Callers must ensure that child->frozen is false. */
3160 void bdrv_root_unref_child(BdrvChild
*child
)
3162 BlockDriverState
*child_bs
;
3164 GLOBAL_STATE_CODE();
3166 child_bs
= child
->bs
;
3167 bdrv_detach_child(&child
);
3168 bdrv_unref(child_bs
);
3171 typedef struct BdrvSetInheritsFrom
{
3172 BlockDriverState
*bs
;
3173 BlockDriverState
*old_inherits_from
;
3174 } BdrvSetInheritsFrom
;
3176 static void bdrv_set_inherits_from_abort(void *opaque
)
3178 BdrvSetInheritsFrom
*s
= opaque
;
3180 s
->bs
->inherits_from
= s
->old_inherits_from
;
3183 static TransactionActionDrv bdrv_set_inherits_from_drv
= {
3184 .abort
= bdrv_set_inherits_from_abort
,
3188 /* @tran is allowed to be NULL. In this case no rollback is possible */
3189 static void bdrv_set_inherits_from(BlockDriverState
*bs
,
3190 BlockDriverState
*new_inherits_from
,
3194 BdrvSetInheritsFrom
*s
= g_new(BdrvSetInheritsFrom
, 1);
3196 *s
= (BdrvSetInheritsFrom
) {
3198 .old_inherits_from
= bs
->inherits_from
,
3201 tran_add(tran
, &bdrv_set_inherits_from_drv
, s
);
3204 bs
->inherits_from
= new_inherits_from
;
3208 * Clear all inherits_from pointers from children and grandchildren of
3209 * @root that point to @root, where necessary.
3210 * @tran is allowed to be NULL. In this case no rollback is possible
3212 static void bdrv_unset_inherits_from(BlockDriverState
*root
, BdrvChild
*child
,
3217 if (child
->bs
->inherits_from
== root
) {
3219 * Remove inherits_from only when the last reference between root and
3220 * child->bs goes away.
3222 QLIST_FOREACH(c
, &root
->children
, next
) {
3223 if (c
!= child
&& c
->bs
== child
->bs
) {
3228 bdrv_set_inherits_from(child
->bs
, NULL
, tran
);
3232 QLIST_FOREACH(c
, &child
->bs
->children
, next
) {
3233 bdrv_unset_inherits_from(root
, c
, tran
);
3237 /* Callers must ensure that child->frozen is false. */
3238 void bdrv_unref_child(BlockDriverState
*parent
, BdrvChild
*child
)
3240 GLOBAL_STATE_CODE();
3241 if (child
== NULL
) {
3245 bdrv_unset_inherits_from(parent
, child
, NULL
);
3246 bdrv_root_unref_child(child
);
3250 static void bdrv_parent_cb_change_media(BlockDriverState
*bs
, bool load
)
3253 QLIST_FOREACH(c
, &bs
->parents
, next_parent
) {
3254 if (c
->klass
->change_media
) {
3255 c
->klass
->change_media(c
, load
);
3260 /* Return true if you can reach parent going through child->inherits_from
3261 * recursively. If parent or child are NULL, return false */
3262 static bool bdrv_inherits_from_recursive(BlockDriverState
*child
,
3263 BlockDriverState
*parent
)
3265 while (child
&& child
!= parent
) {
3266 child
= child
->inherits_from
;
3269 return child
!= NULL
;
3273 * Return the BdrvChildRole for @bs's backing child. bs->backing is
3274 * mostly used for COW backing children (role = COW), but also for
3275 * filtered children (role = FILTERED | PRIMARY).
3277 static BdrvChildRole
bdrv_backing_role(BlockDriverState
*bs
)
3279 if (bs
->drv
&& bs
->drv
->is_filter
) {
3280 return BDRV_CHILD_FILTERED
| BDRV_CHILD_PRIMARY
;
3282 return BDRV_CHILD_COW
;
3287 * Sets the bs->backing or bs->file link of a BDS. A new reference is created;
3288 * callers which don't need their own reference any more must call bdrv_unref().
3290 * Function doesn't update permissions, caller is responsible for this.
3292 static int bdrv_set_file_or_backing_noperm(BlockDriverState
*parent_bs
,
3293 BlockDriverState
*child_bs
,
3295 Transaction
*tran
, Error
**errp
)
3298 bool update_inherits_from
=
3299 bdrv_inherits_from_recursive(child_bs
, parent_bs
);
3300 BdrvChild
*child
= is_backing
? parent_bs
->backing
: parent_bs
->file
;
3303 if (!parent_bs
->drv
) {
3305 * Node without drv is an object without a class :/. TODO: finally fix
3306 * qcow2 driver to never clear bs->drv and implement format corruption
3307 * handling in other way.
3309 error_setg(errp
, "Node corrupted");
3313 if (child
&& child
->frozen
) {
3314 error_setg(errp
, "Cannot change frozen '%s' link from '%s' to '%s'",
3315 child
->name
, parent_bs
->node_name
, child
->bs
->node_name
);
3319 if (is_backing
&& !parent_bs
->drv
->is_filter
&&
3320 !parent_bs
->drv
->supports_backing
)
3322 error_setg(errp
, "Driver '%s' of node '%s' does not support backing "
3323 "files", parent_bs
->drv
->format_name
, parent_bs
->node_name
);
3327 if (parent_bs
->drv
->is_filter
) {
3328 role
= BDRV_CHILD_FILTERED
| BDRV_CHILD_PRIMARY
;
3329 } else if (is_backing
) {
3330 role
= BDRV_CHILD_COW
;
3333 * We only can use same role as it is in existing child. We don't have
3334 * infrastructure to determine role of file child in generic way
3337 error_setg(errp
, "Cannot set file child to format node without "
3345 bdrv_unset_inherits_from(parent_bs
, child
, tran
);
3346 bdrv_remove_file_or_backing_child(parent_bs
, child
, tran
);
3353 ret
= bdrv_attach_child_noperm(parent_bs
, child_bs
,
3354 is_backing
? "backing" : "file",
3355 &child_of_bds
, role
,
3356 is_backing
? &parent_bs
->backing
:
3365 * If inherits_from pointed recursively to bs then let's update it to
3366 * point directly to bs (else it will become NULL).
3368 if (update_inherits_from
) {
3369 bdrv_set_inherits_from(child_bs
, parent_bs
, tran
);
3373 bdrv_refresh_limits(parent_bs
, tran
, NULL
);
3378 static int bdrv_set_backing_noperm(BlockDriverState
*bs
,
3379 BlockDriverState
*backing_hd
,
3380 Transaction
*tran
, Error
**errp
)
3382 return bdrv_set_file_or_backing_noperm(bs
, backing_hd
, true, tran
, errp
);
3385 int bdrv_set_backing_hd(BlockDriverState
*bs
, BlockDriverState
*backing_hd
,
3389 Transaction
*tran
= tran_new();
3391 GLOBAL_STATE_CODE();
3392 bdrv_drained_begin(bs
);
3394 ret
= bdrv_set_backing_noperm(bs
, backing_hd
, tran
, errp
);
3399 ret
= bdrv_refresh_perms(bs
, errp
);
3401 tran_finalize(tran
, ret
);
3403 bdrv_drained_end(bs
);
3409 * Opens the backing file for a BlockDriverState if not yet open
3411 * bdref_key specifies the key for the image's BlockdevRef in the options QDict.
3412 * That QDict has to be flattened; therefore, if the BlockdevRef is a QDict
3413 * itself, all options starting with "${bdref_key}." are considered part of the
3416 * TODO Can this be unified with bdrv_open_image()?
3418 int bdrv_open_backing_file(BlockDriverState
*bs
, QDict
*parent_options
,
3419 const char *bdref_key
, Error
**errp
)
3421 char *backing_filename
= NULL
;
3422 char *bdref_key_dot
;
3423 const char *reference
= NULL
;
3425 bool implicit_backing
= false;
3426 BlockDriverState
*backing_hd
;
3428 QDict
*tmp_parent_options
= NULL
;
3429 Error
*local_err
= NULL
;
3431 GLOBAL_STATE_CODE();
3433 if (bs
->backing
!= NULL
) {
3437 /* NULL means an empty set of options */
3438 if (parent_options
== NULL
) {
3439 tmp_parent_options
= qdict_new();
3440 parent_options
= tmp_parent_options
;
3443 bs
->open_flags
&= ~BDRV_O_NO_BACKING
;
3445 bdref_key_dot
= g_strdup_printf("%s.", bdref_key
);
3446 qdict_extract_subqdict(parent_options
, &options
, bdref_key_dot
);
3447 g_free(bdref_key_dot
);
3450 * Caution: while qdict_get_try_str() is fine, getting non-string
3451 * types would require more care. When @parent_options come from
3452 * -blockdev or blockdev_add, its members are typed according to
3453 * the QAPI schema, but when they come from -drive, they're all
3456 reference
= qdict_get_try_str(parent_options
, bdref_key
);
3457 if (reference
|| qdict_haskey(options
, "file.filename")) {
3458 /* keep backing_filename NULL */
3459 } else if (bs
->backing_file
[0] == '\0' && qdict_size(options
) == 0) {
3460 qobject_unref(options
);
3463 if (qdict_size(options
) == 0) {
3464 /* If the user specifies options that do not modify the
3465 * backing file's behavior, we might still consider it the
3466 * implicit backing file. But it's easier this way, and
3467 * just specifying some of the backing BDS's options is
3468 * only possible with -drive anyway (otherwise the QAPI
3469 * schema forces the user to specify everything). */
3470 implicit_backing
= !strcmp(bs
->auto_backing_file
, bs
->backing_file
);
3473 backing_filename
= bdrv_get_full_backing_filename(bs
, &local_err
);
3476 error_propagate(errp
, local_err
);
3477 qobject_unref(options
);
3482 if (!bs
->drv
|| !bs
->drv
->supports_backing
) {
3484 error_setg(errp
, "Driver doesn't support backing files");
3485 qobject_unref(options
);
3490 bs
->backing_format
[0] != '\0' && !qdict_haskey(options
, "driver")) {
3491 qdict_put_str(options
, "driver", bs
->backing_format
);
3494 backing_hd
= bdrv_open_inherit(backing_filename
, reference
, options
, 0, bs
,
3495 &child_of_bds
, bdrv_backing_role(bs
), errp
);
3497 bs
->open_flags
|= BDRV_O_NO_BACKING
;
3498 error_prepend(errp
, "Could not open backing file: ");
3503 if (implicit_backing
) {
3504 bdrv_refresh_filename(backing_hd
);
3505 pstrcpy(bs
->auto_backing_file
, sizeof(bs
->auto_backing_file
),
3506 backing_hd
->filename
);
3509 /* Hook up the backing file link; drop our reference, bs owns the
3510 * backing_hd reference now */
3511 ret
= bdrv_set_backing_hd(bs
, backing_hd
, errp
);
3512 bdrv_unref(backing_hd
);
3517 qdict_del(parent_options
, bdref_key
);
3520 g_free(backing_filename
);
3521 qobject_unref(tmp_parent_options
);
3525 static BlockDriverState
*
3526 bdrv_open_child_bs(const char *filename
, QDict
*options
, const char *bdref_key
,
3527 BlockDriverState
*parent
, const BdrvChildClass
*child_class
,
3528 BdrvChildRole child_role
, bool allow_none
, Error
**errp
)
3530 BlockDriverState
*bs
= NULL
;
3531 QDict
*image_options
;
3532 char *bdref_key_dot
;
3533 const char *reference
;
3535 assert(child_class
!= NULL
);
3537 bdref_key_dot
= g_strdup_printf("%s.", bdref_key
);
3538 qdict_extract_subqdict(options
, &image_options
, bdref_key_dot
);
3539 g_free(bdref_key_dot
);
3542 * Caution: while qdict_get_try_str() is fine, getting non-string
3543 * types would require more care. When @options come from
3544 * -blockdev or blockdev_add, its members are typed according to
3545 * the QAPI schema, but when they come from -drive, they're all
3548 reference
= qdict_get_try_str(options
, bdref_key
);
3549 if (!filename
&& !reference
&& !qdict_size(image_options
)) {
3551 error_setg(errp
, "A block device must be specified for \"%s\"",
3554 qobject_unref(image_options
);
3558 bs
= bdrv_open_inherit(filename
, reference
, image_options
, 0,
3559 parent
, child_class
, child_role
, errp
);
3565 qdict_del(options
, bdref_key
);
3570 * Opens a disk image whose options are given as BlockdevRef in another block
3573 * If allow_none is true, no image will be opened if filename is false and no
3574 * BlockdevRef is given. NULL will be returned, but errp remains unset.
3576 * bdrev_key specifies the key for the image's BlockdevRef in the options QDict.
3577 * That QDict has to be flattened; therefore, if the BlockdevRef is a QDict
3578 * itself, all options starting with "${bdref_key}." are considered part of the
3581 * The BlockdevRef will be removed from the options QDict.
3583 BdrvChild
*bdrv_open_child(const char *filename
,
3584 QDict
*options
, const char *bdref_key
,
3585 BlockDriverState
*parent
,
3586 const BdrvChildClass
*child_class
,
3587 BdrvChildRole child_role
,
3588 bool allow_none
, Error
**errp
)
3590 BlockDriverState
*bs
;
3592 GLOBAL_STATE_CODE();
3594 bs
= bdrv_open_child_bs(filename
, options
, bdref_key
, parent
, child_class
,
3595 child_role
, allow_none
, errp
);
3600 return bdrv_attach_child(parent
, bs
, bdref_key
, child_class
, child_role
,
3605 * TODO Future callers may need to specify parent/child_class in order for
3606 * option inheritance to work. Existing callers use it for the root node.
3608 BlockDriverState
*bdrv_open_blockdev_ref(BlockdevRef
*ref
, Error
**errp
)
3610 BlockDriverState
*bs
= NULL
;
3611 QObject
*obj
= NULL
;
3612 QDict
*qdict
= NULL
;
3613 const char *reference
= NULL
;
3616 GLOBAL_STATE_CODE();
3618 if (ref
->type
== QTYPE_QSTRING
) {
3619 reference
= ref
->u
.reference
;
3621 BlockdevOptions
*options
= &ref
->u
.definition
;
3622 assert(ref
->type
== QTYPE_QDICT
);
3624 v
= qobject_output_visitor_new(&obj
);
3625 visit_type_BlockdevOptions(v
, NULL
, &options
, &error_abort
);
3626 visit_complete(v
, &obj
);
3628 qdict
= qobject_to(QDict
, obj
);
3629 qdict_flatten(qdict
);
3631 /* bdrv_open_inherit() defaults to the values in bdrv_flags (for
3632 * compatibility with other callers) rather than what we want as the
3633 * real defaults. Apply the defaults here instead. */
3634 qdict_set_default_str(qdict
, BDRV_OPT_CACHE_DIRECT
, "off");
3635 qdict_set_default_str(qdict
, BDRV_OPT_CACHE_NO_FLUSH
, "off");
3636 qdict_set_default_str(qdict
, BDRV_OPT_READ_ONLY
, "off");
3637 qdict_set_default_str(qdict
, BDRV_OPT_AUTO_READ_ONLY
, "off");
3641 bs
= bdrv_open_inherit(NULL
, reference
, qdict
, 0, NULL
, NULL
, 0, errp
);
3648 static BlockDriverState
*bdrv_append_temp_snapshot(BlockDriverState
*bs
,
3650 QDict
*snapshot_options
,
3653 /* TODO: extra byte is a hack to ensure MAX_PATH space on Windows. */
3654 char *tmp_filename
= g_malloc0(PATH_MAX
+ 1);
3656 QemuOpts
*opts
= NULL
;
3657 BlockDriverState
*bs_snapshot
= NULL
;
3660 /* if snapshot, we create a temporary backing file and open it
3661 instead of opening 'filename' directly */
3663 /* Get the required size from the image */
3664 total_size
= bdrv_getlength(bs
);
3665 if (total_size
< 0) {
3666 error_setg_errno(errp
, -total_size
, "Could not get image size");
3670 /* Create the temporary image */
3671 ret
= get_tmp_filename(tmp_filename
, PATH_MAX
+ 1);
3673 error_setg_errno(errp
, -ret
, "Could not get temporary filename");
3677 opts
= qemu_opts_create(bdrv_qcow2
.create_opts
, NULL
, 0,
3679 qemu_opt_set_number(opts
, BLOCK_OPT_SIZE
, total_size
, &error_abort
);
3680 ret
= bdrv_create(&bdrv_qcow2
, tmp_filename
, opts
, errp
);
3681 qemu_opts_del(opts
);
3683 error_prepend(errp
, "Could not create temporary overlay '%s': ",
3688 /* Prepare options QDict for the temporary file */
3689 qdict_put_str(snapshot_options
, "file.driver", "file");
3690 qdict_put_str(snapshot_options
, "file.filename", tmp_filename
);
3691 qdict_put_str(snapshot_options
, "driver", "qcow2");
3693 bs_snapshot
= bdrv_open(NULL
, NULL
, snapshot_options
, flags
, errp
);
3694 snapshot_options
= NULL
;
3699 ret
= bdrv_append(bs_snapshot
, bs
, errp
);
3706 qobject_unref(snapshot_options
);
3707 g_free(tmp_filename
);
3712 * Opens a disk image (raw, qcow2, vmdk, ...)
3714 * options is a QDict of options to pass to the block drivers, or NULL for an
3715 * empty set of options. The reference to the QDict belongs to the block layer
3716 * after the call (even on failure), so if the caller intends to reuse the
3717 * dictionary, it needs to use qobject_ref() before calling bdrv_open.
3719 * If *pbs is NULL, a new BDS will be created with a pointer to it stored there.
3720 * If it is not NULL, the referenced BDS will be reused.
3722 * The reference parameter may be used to specify an existing block device which
3723 * should be opened. If specified, neither options nor a filename may be given,
3724 * nor can an existing BDS be reused (that is, *pbs has to be NULL).
3726 static BlockDriverState
*bdrv_open_inherit(const char *filename
,
3727 const char *reference
,
3728 QDict
*options
, int flags
,
3729 BlockDriverState
*parent
,
3730 const BdrvChildClass
*child_class
,
3731 BdrvChildRole child_role
,
3735 BlockBackend
*file
= NULL
;
3736 BlockDriverState
*bs
;
3737 BlockDriver
*drv
= NULL
;
3739 const char *drvname
;
3740 const char *backing
;
3741 Error
*local_err
= NULL
;
3742 QDict
*snapshot_options
= NULL
;
3743 int snapshot_flags
= 0;
3745 assert(!child_class
|| !flags
);
3746 assert(!child_class
== !parent
);
3749 bool options_non_empty
= options
? qdict_size(options
) : false;
3750 qobject_unref(options
);
3752 if (filename
|| options_non_empty
) {
3753 error_setg(errp
, "Cannot reference an existing block device with "
3754 "additional options or a new filename");
3758 bs
= bdrv_lookup_bs(reference
, reference
, errp
);
3769 /* NULL means an empty set of options */
3770 if (options
== NULL
) {
3771 options
= qdict_new();
3774 /* json: syntax counts as explicit options, as if in the QDict */
3775 parse_json_protocol(options
, &filename
, &local_err
);
3780 bs
->explicit_options
= qdict_clone_shallow(options
);
3783 bool parent_is_format
;
3786 parent_is_format
= parent
->drv
->is_format
;
3789 * parent->drv is not set yet because this node is opened for
3790 * (potential) format probing. That means that @parent is going
3791 * to be a format node.
3793 parent_is_format
= true;
3796 bs
->inherits_from
= parent
;
3797 child_class
->inherit_options(child_role
, parent_is_format
,
3799 parent
->open_flags
, parent
->options
);
3802 ret
= bdrv_fill_options(&options
, filename
, &flags
, &local_err
);
3808 * Set the BDRV_O_RDWR and BDRV_O_ALLOW_RDWR flags.
3809 * Caution: getting a boolean member of @options requires care.
3810 * When @options come from -blockdev or blockdev_add, members are
3811 * typed according to the QAPI schema, but when they come from
3812 * -drive, they're all QString.
3814 if (g_strcmp0(qdict_get_try_str(options
, BDRV_OPT_READ_ONLY
), "on") &&
3815 !qdict_get_try_bool(options
, BDRV_OPT_READ_ONLY
, false)) {
3816 flags
|= (BDRV_O_RDWR
| BDRV_O_ALLOW_RDWR
);
3818 flags
&= ~BDRV_O_RDWR
;
3821 if (flags
& BDRV_O_SNAPSHOT
) {
3822 snapshot_options
= qdict_new();
3823 bdrv_temp_snapshot_options(&snapshot_flags
, snapshot_options
,
3825 /* Let bdrv_backing_options() override "read-only" */
3826 qdict_del(options
, BDRV_OPT_READ_ONLY
);
3827 bdrv_inherited_options(BDRV_CHILD_COW
, true,
3828 &flags
, options
, flags
, options
);
3831 bs
->open_flags
= flags
;
3832 bs
->options
= options
;
3833 options
= qdict_clone_shallow(options
);
3835 /* Find the right image format driver */
3836 /* See cautionary note on accessing @options above */
3837 drvname
= qdict_get_try_str(options
, "driver");
3839 drv
= bdrv_find_format(drvname
);
3841 error_setg(errp
, "Unknown driver: '%s'", drvname
);
3846 assert(drvname
|| !(flags
& BDRV_O_PROTOCOL
));
3848 /* See cautionary note on accessing @options above */
3849 backing
= qdict_get_try_str(options
, "backing");
3850 if (qobject_to(QNull
, qdict_get(options
, "backing")) != NULL
||
3851 (backing
&& *backing
== '\0'))
3854 warn_report("Use of \"backing\": \"\" is deprecated; "
3855 "use \"backing\": null instead");
3857 flags
|= BDRV_O_NO_BACKING
;
3858 qdict_del(bs
->explicit_options
, "backing");
3859 qdict_del(bs
->options
, "backing");
3860 qdict_del(options
, "backing");
3863 /* Open image file without format layer. This BlockBackend is only used for
3864 * probing, the block drivers will do their own bdrv_open_child() for the
3865 * same BDS, which is why we put the node name back into options. */
3866 if ((flags
& BDRV_O_PROTOCOL
) == 0) {
3867 BlockDriverState
*file_bs
;
3869 file_bs
= bdrv_open_child_bs(filename
, options
, "file", bs
,
3870 &child_of_bds
, BDRV_CHILD_IMAGE
,
3875 if (file_bs
!= NULL
) {
3876 /* Not requesting BLK_PERM_CONSISTENT_READ because we're only
3877 * looking at the header to guess the image format. This works even
3878 * in cases where a guest would not see a consistent state. */
3879 file
= blk_new(bdrv_get_aio_context(file_bs
), 0, BLK_PERM_ALL
);
3880 blk_insert_bs(file
, file_bs
, &local_err
);
3881 bdrv_unref(file_bs
);
3886 qdict_put_str(options
, "file", bdrv_get_node_name(file_bs
));
3890 /* Image format probing */
3893 ret
= find_image_format(file
, filename
, &drv
, &local_err
);
3898 * This option update would logically belong in bdrv_fill_options(),
3899 * but we first need to open bs->file for the probing to work, while
3900 * opening bs->file already requires the (mostly) final set of options
3901 * so that cache mode etc. can be inherited.
3903 * Adding the driver later is somewhat ugly, but it's not an option
3904 * that would ever be inherited, so it's correct. We just need to make
3905 * sure to update both bs->options (which has the full effective
3906 * options for bs) and options (which has file.* already removed).
3908 qdict_put_str(bs
->options
, "driver", drv
->format_name
);
3909 qdict_put_str(options
, "driver", drv
->format_name
);
3911 error_setg(errp
, "Must specify either driver or file");
3915 /* BDRV_O_PROTOCOL must be set iff a protocol BDS is about to be created */
3916 assert(!!(flags
& BDRV_O_PROTOCOL
) == !!drv
->bdrv_file_open
);
3917 /* file must be NULL if a protocol BDS is about to be created
3918 * (the inverse results in an error message from bdrv_open_common()) */
3919 assert(!(flags
& BDRV_O_PROTOCOL
) || !file
);
3921 /* Open the image */
3922 ret
= bdrv_open_common(bs
, file
, options
, &local_err
);
3932 /* If there is a backing file, use it */
3933 if ((flags
& BDRV_O_NO_BACKING
) == 0) {
3934 ret
= bdrv_open_backing_file(bs
, options
, "backing", &local_err
);
3936 goto close_and_fail
;
3940 /* Remove all children options and references
3941 * from bs->options and bs->explicit_options */
3942 QLIST_FOREACH(child
, &bs
->children
, next
) {
3943 char *child_key_dot
;
3944 child_key_dot
= g_strdup_printf("%s.", child
->name
);
3945 qdict_extract_subqdict(bs
->explicit_options
, NULL
, child_key_dot
);
3946 qdict_extract_subqdict(bs
->options
, NULL
, child_key_dot
);
3947 qdict_del(bs
->explicit_options
, child
->name
);
3948 qdict_del(bs
->options
, child
->name
);
3949 g_free(child_key_dot
);
3952 /* Check if any unknown options were used */
3953 if (qdict_size(options
) != 0) {
3954 const QDictEntry
*entry
= qdict_first(options
);
3955 if (flags
& BDRV_O_PROTOCOL
) {
3956 error_setg(errp
, "Block protocol '%s' doesn't support the option "
3957 "'%s'", drv
->format_name
, entry
->key
);
3960 "Block format '%s' does not support the option '%s'",
3961 drv
->format_name
, entry
->key
);
3964 goto close_and_fail
;
3967 bdrv_parent_cb_change_media(bs
, true);
3969 qobject_unref(options
);
3972 /* For snapshot=on, create a temporary qcow2 overlay. bs points to the
3973 * temporary snapshot afterwards. */
3974 if (snapshot_flags
) {
3975 BlockDriverState
*snapshot_bs
;
3976 snapshot_bs
= bdrv_append_temp_snapshot(bs
, snapshot_flags
,
3977 snapshot_options
, &local_err
);
3978 snapshot_options
= NULL
;
3980 goto close_and_fail
;
3982 /* We are not going to return bs but the overlay on top of it
3983 * (snapshot_bs); thus, we have to drop the strong reference to bs
3984 * (which we obtained by calling bdrv_new()). bs will not be deleted,
3985 * though, because the overlay still has a reference to it. */
3994 qobject_unref(snapshot_options
);
3995 qobject_unref(bs
->explicit_options
);
3996 qobject_unref(bs
->options
);
3997 qobject_unref(options
);
3999 bs
->explicit_options
= NULL
;
4001 error_propagate(errp
, local_err
);
4006 qobject_unref(snapshot_options
);
4007 qobject_unref(options
);
4008 error_propagate(errp
, local_err
);
4012 BlockDriverState
*bdrv_open(const char *filename
, const char *reference
,
4013 QDict
*options
, int flags
, Error
**errp
)
4015 GLOBAL_STATE_CODE();
4017 return bdrv_open_inherit(filename
, reference
, options
, flags
, NULL
,
4021 /* Return true if the NULL-terminated @list contains @str */
4022 static bool is_str_in_list(const char *str
, const char *const *list
)
4026 for (i
= 0; list
[i
] != NULL
; i
++) {
4027 if (!strcmp(str
, list
[i
])) {
4036 * Check that every option set in @bs->options is also set in
4039 * Options listed in the common_options list and in
4040 * @bs->drv->mutable_opts are skipped.
4042 * Return 0 on success, otherwise return -EINVAL and set @errp.
4044 static int bdrv_reset_options_allowed(BlockDriverState
*bs
,
4045 const QDict
*new_opts
, Error
**errp
)
4047 const QDictEntry
*e
;
4048 /* These options are common to all block drivers and are handled
4049 * in bdrv_reopen_prepare() so they can be left out of @new_opts */
4050 const char *const common_options
[] = {
4051 "node-name", "discard", "cache.direct", "cache.no-flush",
4052 "read-only", "auto-read-only", "detect-zeroes", NULL
4055 for (e
= qdict_first(bs
->options
); e
; e
= qdict_next(bs
->options
, e
)) {
4056 if (!qdict_haskey(new_opts
, e
->key
) &&
4057 !is_str_in_list(e
->key
, common_options
) &&
4058 !is_str_in_list(e
->key
, bs
->drv
->mutable_opts
)) {
4059 error_setg(errp
, "Option '%s' cannot be reset "
4060 "to its default value", e
->key
);
4069 * Returns true if @child can be reached recursively from @bs
4071 static bool bdrv_recurse_has_child(BlockDriverState
*bs
,
4072 BlockDriverState
*child
)
4080 QLIST_FOREACH(c
, &bs
->children
, next
) {
4081 if (bdrv_recurse_has_child(c
->bs
, child
)) {
4090 * Adds a BlockDriverState to a simple queue for an atomic, transactional
4091 * reopen of multiple devices.
4093 * bs_queue can either be an existing BlockReopenQueue that has had QTAILQ_INIT
4094 * already performed, or alternatively may be NULL a new BlockReopenQueue will
4095 * be created and initialized. This newly created BlockReopenQueue should be
4096 * passed back in for subsequent calls that are intended to be of the same
4099 * bs is the BlockDriverState to add to the reopen queue.
4101 * options contains the changed options for the associated bs
4102 * (the BlockReopenQueue takes ownership)
4104 * flags contains the open flags for the associated bs
4106 * returns a pointer to bs_queue, which is either the newly allocated
4107 * bs_queue, or the existing bs_queue being used.
4109 * bs must be drained between bdrv_reopen_queue() and bdrv_reopen_multiple().
4111 static BlockReopenQueue
*bdrv_reopen_queue_child(BlockReopenQueue
*bs_queue
,
4112 BlockDriverState
*bs
,
4114 const BdrvChildClass
*klass
,
4116 bool parent_is_format
,
4117 QDict
*parent_options
,
4123 BlockReopenQueueEntry
*bs_entry
;
4125 QDict
*old_options
, *explicit_options
, *options_copy
;
4129 /* Make sure that the caller remembered to use a drained section. This is
4130 * important to avoid graph changes between the recursive queuing here and
4131 * bdrv_reopen_multiple(). */
4132 assert(bs
->quiesce_counter
> 0);
4134 if (bs_queue
== NULL
) {
4135 bs_queue
= g_new0(BlockReopenQueue
, 1);
4136 QTAILQ_INIT(bs_queue
);
4140 options
= qdict_new();
4143 /* Check if this BlockDriverState is already in the queue */
4144 QTAILQ_FOREACH(bs_entry
, bs_queue
, entry
) {
4145 if (bs
== bs_entry
->state
.bs
) {
4151 * Precedence of options:
4152 * 1. Explicitly passed in options (highest)
4153 * 2. Retained from explicitly set options of bs
4154 * 3. Inherited from parent node
4155 * 4. Retained from effective options of bs
4158 /* Old explicitly set values (don't overwrite by inherited value) */
4159 if (bs_entry
|| keep_old_opts
) {
4160 old_options
= qdict_clone_shallow(bs_entry
?
4161 bs_entry
->state
.explicit_options
:
4162 bs
->explicit_options
);
4163 bdrv_join_options(bs
, options
, old_options
);
4164 qobject_unref(old_options
);
4167 explicit_options
= qdict_clone_shallow(options
);
4169 /* Inherit from parent node */
4170 if (parent_options
) {
4172 klass
->inherit_options(role
, parent_is_format
, &flags
, options
,
4173 parent_flags
, parent_options
);
4175 flags
= bdrv_get_flags(bs
);
4178 if (keep_old_opts
) {
4179 /* Old values are used for options that aren't set yet */
4180 old_options
= qdict_clone_shallow(bs
->options
);
4181 bdrv_join_options(bs
, options
, old_options
);
4182 qobject_unref(old_options
);
4185 /* We have the final set of options so let's update the flags */
4186 options_copy
= qdict_clone_shallow(options
);
4187 opts
= qemu_opts_create(&bdrv_runtime_opts
, NULL
, 0, &error_abort
);
4188 qemu_opts_absorb_qdict(opts
, options_copy
, NULL
);
4189 update_flags_from_options(&flags
, opts
);
4190 qemu_opts_del(opts
);
4191 qobject_unref(options_copy
);
4193 /* bdrv_open_inherit() sets and clears some additional flags internally */
4194 flags
&= ~BDRV_O_PROTOCOL
;
4195 if (flags
& BDRV_O_RDWR
) {
4196 flags
|= BDRV_O_ALLOW_RDWR
;
4200 bs_entry
= g_new0(BlockReopenQueueEntry
, 1);
4201 QTAILQ_INSERT_TAIL(bs_queue
, bs_entry
, entry
);
4203 qobject_unref(bs_entry
->state
.options
);
4204 qobject_unref(bs_entry
->state
.explicit_options
);
4207 bs_entry
->state
.bs
= bs
;
4208 bs_entry
->state
.options
= options
;
4209 bs_entry
->state
.explicit_options
= explicit_options
;
4210 bs_entry
->state
.flags
= flags
;
4213 * If keep_old_opts is false then it means that unspecified
4214 * options must be reset to their original value. We don't allow
4215 * resetting 'backing' but we need to know if the option is
4216 * missing in order to decide if we have to return an error.
4218 if (!keep_old_opts
) {
4219 bs_entry
->state
.backing_missing
=
4220 !qdict_haskey(options
, "backing") &&
4221 !qdict_haskey(options
, "backing.driver");
4224 QLIST_FOREACH(child
, &bs
->children
, next
) {
4225 QDict
*new_child_options
= NULL
;
4226 bool child_keep_old
= keep_old_opts
;
4228 /* reopen can only change the options of block devices that were
4229 * implicitly created and inherited options. For other (referenced)
4230 * block devices, a syntax like "backing.foo" results in an error. */
4231 if (child
->bs
->inherits_from
!= bs
) {
4235 /* Check if the options contain a child reference */
4236 if (qdict_haskey(options
, child
->name
)) {
4237 const char *childref
= qdict_get_try_str(options
, child
->name
);
4239 * The current child must not be reopened if the child
4240 * reference is null or points to a different node.
4242 if (g_strcmp0(childref
, child
->bs
->node_name
)) {
4246 * If the child reference points to the current child then
4247 * reopen it with its existing set of options (note that
4248 * it can still inherit new options from the parent).
4250 child_keep_old
= true;
4252 /* Extract child options ("child-name.*") */
4253 char *child_key_dot
= g_strdup_printf("%s.", child
->name
);
4254 qdict_extract_subqdict(explicit_options
, NULL
, child_key_dot
);
4255 qdict_extract_subqdict(options
, &new_child_options
, child_key_dot
);
4256 g_free(child_key_dot
);
4259 bdrv_reopen_queue_child(bs_queue
, child
->bs
, new_child_options
,
4260 child
->klass
, child
->role
, bs
->drv
->is_format
,
4261 options
, flags
, child_keep_old
);
4267 BlockReopenQueue
*bdrv_reopen_queue(BlockReopenQueue
*bs_queue
,
4268 BlockDriverState
*bs
,
4269 QDict
*options
, bool keep_old_opts
)
4271 GLOBAL_STATE_CODE();
4273 return bdrv_reopen_queue_child(bs_queue
, bs
, options
, NULL
, 0, false,
4274 NULL
, 0, keep_old_opts
);
4277 void bdrv_reopen_queue_free(BlockReopenQueue
*bs_queue
)
4279 GLOBAL_STATE_CODE();
4281 BlockReopenQueueEntry
*bs_entry
, *next
;
4282 QTAILQ_FOREACH_SAFE(bs_entry
, bs_queue
, entry
, next
) {
4283 qobject_unref(bs_entry
->state
.explicit_options
);
4284 qobject_unref(bs_entry
->state
.options
);
4292 * Reopen multiple BlockDriverStates atomically & transactionally.
4294 * The queue passed in (bs_queue) must have been built up previous
4295 * via bdrv_reopen_queue().
4297 * Reopens all BDS specified in the queue, with the appropriate
4298 * flags. All devices are prepared for reopen, and failure of any
4299 * device will cause all device changes to be abandoned, and intermediate
4302 * If all devices prepare successfully, then the changes are committed
4305 * All affected nodes must be drained between bdrv_reopen_queue() and
4306 * bdrv_reopen_multiple().
4308 * To be called from the main thread, with all other AioContexts unlocked.
4310 int bdrv_reopen_multiple(BlockReopenQueue
*bs_queue
, Error
**errp
)
4313 BlockReopenQueueEntry
*bs_entry
, *next
;
4315 Transaction
*tran
= tran_new();
4316 g_autoptr(GHashTable
) found
= NULL
;
4317 g_autoptr(GSList
) refresh_list
= NULL
;
4319 assert(qemu_get_current_aio_context() == qemu_get_aio_context());
4320 assert(bs_queue
!= NULL
);
4322 QTAILQ_FOREACH(bs_entry
, bs_queue
, entry
) {
4323 ctx
= bdrv_get_aio_context(bs_entry
->state
.bs
);
4324 aio_context_acquire(ctx
);
4325 ret
= bdrv_flush(bs_entry
->state
.bs
);
4326 aio_context_release(ctx
);
4328 error_setg_errno(errp
, -ret
, "Error flushing drive");
4333 QTAILQ_FOREACH(bs_entry
, bs_queue
, entry
) {
4334 assert(bs_entry
->state
.bs
->quiesce_counter
> 0);
4335 ctx
= bdrv_get_aio_context(bs_entry
->state
.bs
);
4336 aio_context_acquire(ctx
);
4337 ret
= bdrv_reopen_prepare(&bs_entry
->state
, bs_queue
, tran
, errp
);
4338 aio_context_release(ctx
);
4342 bs_entry
->prepared
= true;
4345 found
= g_hash_table_new(NULL
, NULL
);
4346 QTAILQ_FOREACH(bs_entry
, bs_queue
, entry
) {
4347 BDRVReopenState
*state
= &bs_entry
->state
;
4349 refresh_list
= bdrv_topological_dfs(refresh_list
, found
, state
->bs
);
4350 if (state
->old_backing_bs
) {
4351 refresh_list
= bdrv_topological_dfs(refresh_list
, found
,
4352 state
->old_backing_bs
);
4354 if (state
->old_file_bs
) {
4355 refresh_list
= bdrv_topological_dfs(refresh_list
, found
,
4356 state
->old_file_bs
);
4361 * Note that file-posix driver rely on permission update done during reopen
4362 * (even if no permission changed), because it wants "new" permissions for
4363 * reconfiguring the fd and that's why it does it in raw_check_perm(), not
4364 * in raw_reopen_prepare() which is called with "old" permissions.
4366 ret
= bdrv_list_refresh_perms(refresh_list
, bs_queue
, tran
, errp
);
4372 * If we reach this point, we have success and just need to apply the
4375 * Reverse order is used to comfort qcow2 driver: on commit it need to write
4376 * IN_USE flag to the image, to mark bitmaps in the image as invalid. But
4377 * children are usually goes after parents in reopen-queue, so go from last
4380 QTAILQ_FOREACH_REVERSE(bs_entry
, bs_queue
, entry
) {
4381 ctx
= bdrv_get_aio_context(bs_entry
->state
.bs
);
4382 aio_context_acquire(ctx
);
4383 bdrv_reopen_commit(&bs_entry
->state
);
4384 aio_context_release(ctx
);
4389 QTAILQ_FOREACH_REVERSE(bs_entry
, bs_queue
, entry
) {
4390 BlockDriverState
*bs
= bs_entry
->state
.bs
;
4392 if (bs
->drv
->bdrv_reopen_commit_post
) {
4393 ctx
= bdrv_get_aio_context(bs
);
4394 aio_context_acquire(ctx
);
4395 bs
->drv
->bdrv_reopen_commit_post(&bs_entry
->state
);
4396 aio_context_release(ctx
);
4405 QTAILQ_FOREACH_SAFE(bs_entry
, bs_queue
, entry
, next
) {
4406 if (bs_entry
->prepared
) {
4407 ctx
= bdrv_get_aio_context(bs_entry
->state
.bs
);
4408 aio_context_acquire(ctx
);
4409 bdrv_reopen_abort(&bs_entry
->state
);
4410 aio_context_release(ctx
);
4415 bdrv_reopen_queue_free(bs_queue
);
4420 int bdrv_reopen(BlockDriverState
*bs
, QDict
*opts
, bool keep_old_opts
,
4423 AioContext
*ctx
= bdrv_get_aio_context(bs
);
4424 BlockReopenQueue
*queue
;
4427 GLOBAL_STATE_CODE();
4429 bdrv_subtree_drained_begin(bs
);
4430 if (ctx
!= qemu_get_aio_context()) {
4431 aio_context_release(ctx
);
4434 queue
= bdrv_reopen_queue(NULL
, bs
, opts
, keep_old_opts
);
4435 ret
= bdrv_reopen_multiple(queue
, errp
);
4437 if (ctx
!= qemu_get_aio_context()) {
4438 aio_context_acquire(ctx
);
4440 bdrv_subtree_drained_end(bs
);
4445 int bdrv_reopen_set_read_only(BlockDriverState
*bs
, bool read_only
,
4448 QDict
*opts
= qdict_new();
4450 GLOBAL_STATE_CODE();
4452 qdict_put_bool(opts
, BDRV_OPT_READ_ONLY
, read_only
);
4454 return bdrv_reopen(bs
, opts
, true, errp
);
4458 * Take a BDRVReopenState and check if the value of 'backing' in the
4459 * reopen_state->options QDict is valid or not.
4461 * If 'backing' is missing from the QDict then return 0.
4463 * If 'backing' contains the node name of the backing file of
4464 * reopen_state->bs then return 0.
4466 * If 'backing' contains a different node name (or is null) then check
4467 * whether the current backing file can be replaced with the new one.
4468 * If that's the case then reopen_state->replace_backing_bs is set to
4469 * true and reopen_state->new_backing_bs contains a pointer to the new
4470 * backing BlockDriverState (or NULL).
4472 * Return 0 on success, otherwise return < 0 and set @errp.
4474 static int bdrv_reopen_parse_file_or_backing(BDRVReopenState
*reopen_state
,
4475 bool is_backing
, Transaction
*tran
,
4478 BlockDriverState
*bs
= reopen_state
->bs
;
4479 BlockDriverState
*new_child_bs
;
4480 BlockDriverState
*old_child_bs
= is_backing
? child_bs(bs
->backing
) :
4482 const char *child_name
= is_backing
? "backing" : "file";
4486 value
= qdict_get(reopen_state
->options
, child_name
);
4487 if (value
== NULL
) {
4491 switch (qobject_type(value
)) {
4493 assert(is_backing
); /* The 'file' option does not allow a null value */
4494 new_child_bs
= NULL
;
4497 str
= qstring_get_str(qobject_to(QString
, value
));
4498 new_child_bs
= bdrv_lookup_bs(NULL
, str
, errp
);
4499 if (new_child_bs
== NULL
) {
4501 } else if (bdrv_recurse_has_child(new_child_bs
, bs
)) {
4502 error_setg(errp
, "Making '%s' a %s child of '%s' would create a "
4503 "cycle", str
, child_name
, bs
->node_name
);
4509 * The options QDict has been flattened, so 'backing' and 'file'
4510 * do not allow any other data type here.
4512 g_assert_not_reached();
4515 if (old_child_bs
== new_child_bs
) {
4520 if (bdrv_skip_implicit_filters(old_child_bs
) == new_child_bs
) {
4524 if (old_child_bs
->implicit
) {
4525 error_setg(errp
, "Cannot replace implicit %s child of %s",
4526 child_name
, bs
->node_name
);
4531 if (bs
->drv
->is_filter
&& !old_child_bs
) {
4533 * Filters always have a file or a backing child, so we are trying to
4534 * change wrong child
4536 error_setg(errp
, "'%s' is a %s filter node that does not support a "
4537 "%s child", bs
->node_name
, bs
->drv
->format_name
, child_name
);
4542 reopen_state
->old_backing_bs
= old_child_bs
;
4544 reopen_state
->old_file_bs
= old_child_bs
;
4547 return bdrv_set_file_or_backing_noperm(bs
, new_child_bs
, is_backing
,
4552 * Prepares a BlockDriverState for reopen. All changes are staged in the
4553 * 'opaque' field of the BDRVReopenState, which is used and allocated by
4554 * the block driver layer .bdrv_reopen_prepare()
4556 * bs is the BlockDriverState to reopen
4557 * flags are the new open flags
4558 * queue is the reopen queue
4560 * Returns 0 on success, non-zero on error. On error errp will be set
4563 * On failure, bdrv_reopen_abort() will be called to clean up any data.
4564 * It is the responsibility of the caller to then call the abort() or
4565 * commit() for any other BDS that have been left in a prepare() state
4568 static int bdrv_reopen_prepare(BDRVReopenState
*reopen_state
,
4569 BlockReopenQueue
*queue
,
4570 Transaction
*change_child_tran
, Error
**errp
)
4574 Error
*local_err
= NULL
;
4577 QDict
*orig_reopen_opts
;
4578 char *discard
= NULL
;
4580 bool drv_prepared
= false;
4582 assert(reopen_state
!= NULL
);
4583 assert(reopen_state
->bs
->drv
!= NULL
);
4584 drv
= reopen_state
->bs
->drv
;
4586 /* This function and each driver's bdrv_reopen_prepare() remove
4587 * entries from reopen_state->options as they are processed, so
4588 * we need to make a copy of the original QDict. */
4589 orig_reopen_opts
= qdict_clone_shallow(reopen_state
->options
);
4591 /* Process generic block layer options */
4592 opts
= qemu_opts_create(&bdrv_runtime_opts
, NULL
, 0, &error_abort
);
4593 if (!qemu_opts_absorb_qdict(opts
, reopen_state
->options
, errp
)) {
4598 /* This was already called in bdrv_reopen_queue_child() so the flags
4599 * are up-to-date. This time we simply want to remove the options from
4600 * QemuOpts in order to indicate that they have been processed. */
4601 old_flags
= reopen_state
->flags
;
4602 update_flags_from_options(&reopen_state
->flags
, opts
);
4603 assert(old_flags
== reopen_state
->flags
);
4605 discard
= qemu_opt_get_del(opts
, BDRV_OPT_DISCARD
);
4606 if (discard
!= NULL
) {
4607 if (bdrv_parse_discard_flags(discard
, &reopen_state
->flags
) != 0) {
4608 error_setg(errp
, "Invalid discard option");
4614 reopen_state
->detect_zeroes
=
4615 bdrv_parse_detect_zeroes(opts
, reopen_state
->flags
, &local_err
);
4617 error_propagate(errp
, local_err
);
4622 /* All other options (including node-name and driver) must be unchanged.
4623 * Put them back into the QDict, so that they are checked at the end
4624 * of this function. */
4625 qemu_opts_to_qdict(opts
, reopen_state
->options
);
4627 /* If we are to stay read-only, do not allow permission change
4628 * to r/w. Attempting to set to r/w may fail if either BDRV_O_ALLOW_RDWR is
4629 * not set, or if the BDS still has copy_on_read enabled */
4630 read_only
= !(reopen_state
->flags
& BDRV_O_RDWR
);
4631 ret
= bdrv_can_set_read_only(reopen_state
->bs
, read_only
, true, &local_err
);
4633 error_propagate(errp
, local_err
);
4637 if (drv
->bdrv_reopen_prepare
) {
4639 * If a driver-specific option is missing, it means that we
4640 * should reset it to its default value.
4641 * But not all options allow that, so we need to check it first.
4643 ret
= bdrv_reset_options_allowed(reopen_state
->bs
,
4644 reopen_state
->options
, errp
);
4649 ret
= drv
->bdrv_reopen_prepare(reopen_state
, queue
, &local_err
);
4651 if (local_err
!= NULL
) {
4652 error_propagate(errp
, local_err
);
4654 bdrv_refresh_filename(reopen_state
->bs
);
4655 error_setg(errp
, "failed while preparing to reopen image '%s'",
4656 reopen_state
->bs
->filename
);
4661 /* It is currently mandatory to have a bdrv_reopen_prepare()
4662 * handler for each supported drv. */
4663 error_setg(errp
, "Block format '%s' used by node '%s' "
4664 "does not support reopening files", drv
->format_name
,
4665 bdrv_get_device_or_node_name(reopen_state
->bs
));
4670 drv_prepared
= true;
4673 * We must provide the 'backing' option if the BDS has a backing
4674 * file or if the image file has a backing file name as part of
4675 * its metadata. Otherwise the 'backing' option can be omitted.
4677 if (drv
->supports_backing
&& reopen_state
->backing_missing
&&
4678 (reopen_state
->bs
->backing
|| reopen_state
->bs
->backing_file
[0])) {
4679 error_setg(errp
, "backing is missing for '%s'",
4680 reopen_state
->bs
->node_name
);
4686 * Allow changing the 'backing' option. The new value can be
4687 * either a reference to an existing node (using its node name)
4688 * or NULL to simply detach the current backing file.
4690 ret
= bdrv_reopen_parse_file_or_backing(reopen_state
, true,
4691 change_child_tran
, errp
);
4695 qdict_del(reopen_state
->options
, "backing");
4697 /* Allow changing the 'file' option. In this case NULL is not allowed */
4698 ret
= bdrv_reopen_parse_file_or_backing(reopen_state
, false,
4699 change_child_tran
, errp
);
4703 qdict_del(reopen_state
->options
, "file");
4705 /* Options that are not handled are only okay if they are unchanged
4706 * compared to the old state. It is expected that some options are only
4707 * used for the initial open, but not reopen (e.g. filename) */
4708 if (qdict_size(reopen_state
->options
)) {
4709 const QDictEntry
*entry
= qdict_first(reopen_state
->options
);
4712 QObject
*new = entry
->value
;
4713 QObject
*old
= qdict_get(reopen_state
->bs
->options
, entry
->key
);
4715 /* Allow child references (child_name=node_name) as long as they
4716 * point to the current child (i.e. everything stays the same). */
4717 if (qobject_type(new) == QTYPE_QSTRING
) {
4719 QLIST_FOREACH(child
, &reopen_state
->bs
->children
, next
) {
4720 if (!strcmp(child
->name
, entry
->key
)) {
4726 if (!strcmp(child
->bs
->node_name
,
4727 qstring_get_str(qobject_to(QString
, new)))) {
4728 continue; /* Found child with this name, skip option */
4734 * TODO: When using -drive to specify blockdev options, all values
4735 * will be strings; however, when using -blockdev, blockdev-add or
4736 * filenames using the json:{} pseudo-protocol, they will be
4738 * In contrast, reopening options are (currently) always strings
4739 * (because you can only specify them through qemu-io; all other
4740 * callers do not specify any options).
4741 * Therefore, when using anything other than -drive to create a BDS,
4742 * this cannot detect non-string options as unchanged, because
4743 * qobject_is_equal() always returns false for objects of different
4744 * type. In the future, this should be remedied by correctly typing
4745 * all options. For now, this is not too big of an issue because
4746 * the user can simply omit options which cannot be changed anyway,
4747 * so they will stay unchanged.
4749 if (!qobject_is_equal(new, old
)) {
4750 error_setg(errp
, "Cannot change the option '%s'", entry
->key
);
4754 } while ((entry
= qdict_next(reopen_state
->options
, entry
)));
4759 /* Restore the original reopen_state->options QDict */
4760 qobject_unref(reopen_state
->options
);
4761 reopen_state
->options
= qobject_ref(orig_reopen_opts
);
4764 if (ret
< 0 && drv_prepared
) {
4765 /* drv->bdrv_reopen_prepare() has succeeded, so we need to
4766 * call drv->bdrv_reopen_abort() before signaling an error
4767 * (bdrv_reopen_multiple() will not call bdrv_reopen_abort()
4768 * when the respective bdrv_reopen_prepare() has failed) */
4769 if (drv
->bdrv_reopen_abort
) {
4770 drv
->bdrv_reopen_abort(reopen_state
);
4773 qemu_opts_del(opts
);
4774 qobject_unref(orig_reopen_opts
);
4780 * Takes the staged changes for the reopen from bdrv_reopen_prepare(), and
4781 * makes them final by swapping the staging BlockDriverState contents into
4782 * the active BlockDriverState contents.
4784 static void bdrv_reopen_commit(BDRVReopenState
*reopen_state
)
4787 BlockDriverState
*bs
;
4790 assert(reopen_state
!= NULL
);
4791 bs
= reopen_state
->bs
;
4793 assert(drv
!= NULL
);
4795 /* If there are any driver level actions to take */
4796 if (drv
->bdrv_reopen_commit
) {
4797 drv
->bdrv_reopen_commit(reopen_state
);
4800 /* set BDS specific flags now */
4801 qobject_unref(bs
->explicit_options
);
4802 qobject_unref(bs
->options
);
4803 qobject_ref(reopen_state
->explicit_options
);
4804 qobject_ref(reopen_state
->options
);
4806 bs
->explicit_options
= reopen_state
->explicit_options
;
4807 bs
->options
= reopen_state
->options
;
4808 bs
->open_flags
= reopen_state
->flags
;
4809 bs
->detect_zeroes
= reopen_state
->detect_zeroes
;
4811 /* Remove child references from bs->options and bs->explicit_options.
4812 * Child options were already removed in bdrv_reopen_queue_child() */
4813 QLIST_FOREACH(child
, &bs
->children
, next
) {
4814 qdict_del(bs
->explicit_options
, child
->name
);
4815 qdict_del(bs
->options
, child
->name
);
4817 /* backing is probably removed, so it's not handled by previous loop */
4818 qdict_del(bs
->explicit_options
, "backing");
4819 qdict_del(bs
->options
, "backing");
4821 bdrv_refresh_limits(bs
, NULL
, NULL
);
4825 * Abort the reopen, and delete and free the staged changes in
4828 static void bdrv_reopen_abort(BDRVReopenState
*reopen_state
)
4832 assert(reopen_state
!= NULL
);
4833 drv
= reopen_state
->bs
->drv
;
4834 assert(drv
!= NULL
);
4836 if (drv
->bdrv_reopen_abort
) {
4837 drv
->bdrv_reopen_abort(reopen_state
);
4842 static void bdrv_close(BlockDriverState
*bs
)
4844 BdrvAioNotifier
*ban
, *ban_next
;
4845 BdrvChild
*child
, *next
;
4847 GLOBAL_STATE_CODE();
4848 assert(!bs
->refcnt
);
4850 bdrv_drained_begin(bs
); /* complete I/O */
4852 bdrv_drain(bs
); /* in case flush left pending I/O */
4855 if (bs
->drv
->bdrv_close
) {
4856 /* Must unfreeze all children, so bdrv_unref_child() works */
4857 bs
->drv
->bdrv_close(bs
);
4862 QLIST_FOREACH_SAFE(child
, &bs
->children
, next
, next
) {
4863 bdrv_unref_child(bs
, child
);
4870 qatomic_set(&bs
->copy_on_read
, 0);
4871 bs
->backing_file
[0] = '\0';
4872 bs
->backing_format
[0] = '\0';
4873 bs
->total_sectors
= 0;
4874 bs
->encrypted
= false;
4876 qobject_unref(bs
->options
);
4877 qobject_unref(bs
->explicit_options
);
4879 bs
->explicit_options
= NULL
;
4880 qobject_unref(bs
->full_open_options
);
4881 bs
->full_open_options
= NULL
;
4882 g_free(bs
->block_status_cache
);
4883 bs
->block_status_cache
= NULL
;
4885 bdrv_release_named_dirty_bitmaps(bs
);
4886 assert(QLIST_EMPTY(&bs
->dirty_bitmaps
));
4888 QLIST_FOREACH_SAFE(ban
, &bs
->aio_notifiers
, list
, ban_next
) {
4891 QLIST_INIT(&bs
->aio_notifiers
);
4892 bdrv_drained_end(bs
);
4895 * If we're still inside some bdrv_drain_all_begin()/end() sections, end
4896 * them now since this BDS won't exist anymore when bdrv_drain_all_end()
4899 if (bs
->quiesce_counter
) {
4900 bdrv_drain_all_end_quiesce(bs
);
4904 void bdrv_close_all(void)
4906 assert(job_next(NULL
) == NULL
);
4907 GLOBAL_STATE_CODE();
4909 /* Drop references from requests still in flight, such as canceled block
4910 * jobs whose AIO context has not been polled yet */
4913 blk_remove_all_bs();
4914 blockdev_close_all_bdrv_states();
4916 assert(QTAILQ_EMPTY(&all_bdrv_states
));
4919 static bool should_update_child(BdrvChild
*c
, BlockDriverState
*to
)
4925 if (c
->klass
->stay_at_node
) {
4929 /* If the child @c belongs to the BDS @to, replacing the current
4930 * c->bs by @to would mean to create a loop.
4932 * Such a case occurs when appending a BDS to a backing chain.
4933 * For instance, imagine the following chain:
4935 * guest device -> node A -> further backing chain...
4937 * Now we create a new BDS B which we want to put on top of this
4938 * chain, so we first attach A as its backing node:
4943 * guest device -> node A -> further backing chain...
4945 * Finally we want to replace A by B. When doing that, we want to
4946 * replace all pointers to A by pointers to B -- except for the
4947 * pointer from B because (1) that would create a loop, and (2)
4948 * that pointer should simply stay intact:
4950 * guest device -> node B
4953 * node A -> further backing chain...
4955 * In general, when replacing a node A (c->bs) by a node B (@to),
4956 * if A is a child of B, that means we cannot replace A by B there
4957 * because that would create a loop. Silently detaching A from B
4958 * is also not really an option. So overall just leaving A in
4959 * place there is the most sensible choice.
4961 * We would also create a loop in any cases where @c is only
4962 * indirectly referenced by @to. Prevent this by returning false
4963 * if @c is found (by breadth-first search) anywhere in the whole
4968 found
= g_hash_table_new(NULL
, NULL
);
4969 g_hash_table_add(found
, to
);
4970 queue
= g_queue_new();
4971 g_queue_push_tail(queue
, to
);
4973 while (!g_queue_is_empty(queue
)) {
4974 BlockDriverState
*v
= g_queue_pop_head(queue
);
4977 QLIST_FOREACH(c2
, &v
->children
, next
) {
4983 if (g_hash_table_contains(found
, c2
->bs
)) {
4987 g_queue_push_tail(queue
, c2
->bs
);
4988 g_hash_table_add(found
, c2
->bs
);
4992 g_queue_free(queue
);
4993 g_hash_table_destroy(found
);
4998 typedef struct BdrvRemoveFilterOrCowChild
{
5000 BlockDriverState
*bs
;
5002 } BdrvRemoveFilterOrCowChild
;
5004 static void bdrv_remove_filter_or_cow_child_abort(void *opaque
)
5006 BdrvRemoveFilterOrCowChild
*s
= opaque
;
5007 BlockDriverState
*parent_bs
= s
->child
->opaque
;
5009 if (s
->is_backing
) {
5010 parent_bs
->backing
= s
->child
;
5012 parent_bs
->file
= s
->child
;
5016 * We don't have to restore child->bs here to undo bdrv_replace_child_tran()
5017 * because that function is transactionable and it registered own completion
5018 * entries in @tran, so .abort() for bdrv_replace_child_safe() will be
5019 * called automatically.
5023 static void bdrv_remove_filter_or_cow_child_commit(void *opaque
)
5025 BdrvRemoveFilterOrCowChild
*s
= opaque
;
5027 bdrv_child_free(s
->child
);
5030 static void bdrv_remove_filter_or_cow_child_clean(void *opaque
)
5032 BdrvRemoveFilterOrCowChild
*s
= opaque
;
5034 /* Drop the bs reference after the transaction is done */
5039 static TransactionActionDrv bdrv_remove_filter_or_cow_child_drv
= {
5040 .abort
= bdrv_remove_filter_or_cow_child_abort
,
5041 .commit
= bdrv_remove_filter_or_cow_child_commit
,
5042 .clean
= bdrv_remove_filter_or_cow_child_clean
,
5046 * A function to remove backing or file child of @bs.
5047 * Function doesn't update permissions, caller is responsible for this.
5049 static void bdrv_remove_file_or_backing_child(BlockDriverState
*bs
,
5054 BdrvRemoveFilterOrCowChild
*s
;
5061 * Keep a reference to @bs so @childp will stay valid throughout the
5062 * transaction (required by bdrv_replace_child_tran())
5065 if (child
== bs
->backing
) {
5066 childp
= &bs
->backing
;
5067 } else if (child
== bs
->file
) {
5070 g_assert_not_reached();
5075 * Pass free_empty_child=false, we will free the child in
5076 * bdrv_remove_filter_or_cow_child_commit()
5078 bdrv_replace_child_tran(childp
, NULL
, tran
, false);
5081 s
= g_new(BdrvRemoveFilterOrCowChild
, 1);
5082 *s
= (BdrvRemoveFilterOrCowChild
) {
5085 .is_backing
= (childp
== &bs
->backing
),
5087 tran_add(tran
, &bdrv_remove_filter_or_cow_child_drv
, s
);
5091 * A function to remove backing-chain child of @bs if exists: cow child for
5092 * format nodes (always .backing) and filter child for filters (may be .file or
5095 static void bdrv_remove_filter_or_cow_child(BlockDriverState
*bs
,
5098 bdrv_remove_file_or_backing_child(bs
, bdrv_filter_or_cow_child(bs
), tran
);
5101 static int bdrv_replace_node_noperm(BlockDriverState
*from
,
5102 BlockDriverState
*to
,
5103 bool auto_skip
, Transaction
*tran
,
5106 BdrvChild
*c
, *next
;
5110 QLIST_FOREACH_SAFE(c
, &from
->parents
, next_parent
, next
) {
5111 assert(c
->bs
== from
);
5112 if (!should_update_child(c
, to
)) {
5116 error_setg(errp
, "Should not change '%s' link to '%s'",
5117 c
->name
, from
->node_name
);
5121 error_setg(errp
, "Cannot change '%s' link to '%s'",
5122 c
->name
, from
->node_name
);
5127 * Passing a pointer to the local variable @c is fine here, because
5128 * @to is not NULL, and so &c will not be attached to the transaction.
5130 bdrv_replace_child_tran(&c
, to
, tran
, true);
5137 * With auto_skip=true bdrv_replace_node_common skips updating from parents
5138 * if it creates a parent-child relation loop or if parent is block-job.
5140 * With auto_skip=false the error is returned if from has a parent which should
5143 * With @detach_subchain=true @to must be in a backing chain of @from. In this
5144 * case backing link of the cow-parent of @to is removed.
5146 * @to must not be NULL.
5148 static int bdrv_replace_node_common(BlockDriverState
*from
,
5149 BlockDriverState
*to
,
5150 bool auto_skip
, bool detach_subchain
,
5153 Transaction
*tran
= tran_new();
5154 g_autoptr(GHashTable
) found
= NULL
;
5155 g_autoptr(GSList
) refresh_list
= NULL
;
5156 BlockDriverState
*to_cow_parent
= NULL
;
5161 if (detach_subchain
) {
5162 assert(bdrv_chain_contains(from
, to
));
5164 for (to_cow_parent
= from
;
5165 bdrv_filter_or_cow_bs(to_cow_parent
) != to
;
5166 to_cow_parent
= bdrv_filter_or_cow_bs(to_cow_parent
))
5172 /* Make sure that @from doesn't go away until we have successfully attached
5173 * all of its parents to @to. */
5176 assert(qemu_get_current_aio_context() == qemu_get_aio_context());
5177 assert(bdrv_get_aio_context(from
) == bdrv_get_aio_context(to
));
5178 bdrv_drained_begin(from
);
5181 * Do the replacement without permission update.
5182 * Replacement may influence the permissions, we should calculate new
5183 * permissions based on new graph. If we fail, we'll roll-back the
5186 ret
= bdrv_replace_node_noperm(from
, to
, auto_skip
, tran
, errp
);
5191 if (detach_subchain
) {
5192 bdrv_remove_filter_or_cow_child(to_cow_parent
, tran
);
5195 found
= g_hash_table_new(NULL
, NULL
);
5197 refresh_list
= bdrv_topological_dfs(refresh_list
, found
, to
);
5198 refresh_list
= bdrv_topological_dfs(refresh_list
, found
, from
);
5200 ret
= bdrv_list_refresh_perms(refresh_list
, NULL
, tran
, errp
);
5208 tran_finalize(tran
, ret
);
5210 bdrv_drained_end(from
);
5217 * Replace node @from by @to (where neither may be NULL).
5219 int bdrv_replace_node(BlockDriverState
*from
, BlockDriverState
*to
,
5222 GLOBAL_STATE_CODE();
5224 return bdrv_replace_node_common(from
, to
, true, false, errp
);
5227 int bdrv_drop_filter(BlockDriverState
*bs
, Error
**errp
)
5229 GLOBAL_STATE_CODE();
5231 return bdrv_replace_node_common(bs
, bdrv_filter_or_cow_bs(bs
), true, true,
5236 * Add new bs contents at the top of an image chain while the chain is
5237 * live, while keeping required fields on the top layer.
5239 * This will modify the BlockDriverState fields, and swap contents
5240 * between bs_new and bs_top. Both bs_new and bs_top are modified.
5242 * bs_new must not be attached to a BlockBackend and must not have backing
5245 * This function does not create any image files.
5247 int bdrv_append(BlockDriverState
*bs_new
, BlockDriverState
*bs_top
,
5251 Transaction
*tran
= tran_new();
5253 GLOBAL_STATE_CODE();
5255 assert(!bs_new
->backing
);
5257 ret
= bdrv_attach_child_noperm(bs_new
, bs_top
, "backing",
5258 &child_of_bds
, bdrv_backing_role(bs_new
),
5259 &bs_new
->backing
, tran
, errp
);
5264 ret
= bdrv_replace_node_noperm(bs_top
, bs_new
, true, tran
, errp
);
5269 ret
= bdrv_refresh_perms(bs_new
, errp
);
5271 tran_finalize(tran
, ret
);
5273 bdrv_refresh_limits(bs_top
, NULL
, NULL
);
5278 /* Not for empty child */
5279 int bdrv_replace_child_bs(BdrvChild
*child
, BlockDriverState
*new_bs
,
5283 Transaction
*tran
= tran_new();
5284 g_autoptr(GHashTable
) found
= NULL
;
5285 g_autoptr(GSList
) refresh_list
= NULL
;
5286 BlockDriverState
*old_bs
= child
->bs
;
5288 GLOBAL_STATE_CODE();
5291 bdrv_drained_begin(old_bs
);
5292 bdrv_drained_begin(new_bs
);
5294 bdrv_replace_child_tran(&child
, new_bs
, tran
, true);
5295 /* @new_bs must have been non-NULL, so @child must not have been freed */
5296 assert(child
!= NULL
);
5298 found
= g_hash_table_new(NULL
, NULL
);
5299 refresh_list
= bdrv_topological_dfs(refresh_list
, found
, old_bs
);
5300 refresh_list
= bdrv_topological_dfs(refresh_list
, found
, new_bs
);
5302 ret
= bdrv_list_refresh_perms(refresh_list
, NULL
, tran
, errp
);
5304 tran_finalize(tran
, ret
);
5306 bdrv_drained_end(old_bs
);
5307 bdrv_drained_end(new_bs
);
5313 static void bdrv_delete(BlockDriverState
*bs
)
5315 assert(bdrv_op_blocker_is_empty(bs
));
5316 assert(!bs
->refcnt
);
5317 GLOBAL_STATE_CODE();
5319 /* remove from list, if necessary */
5320 if (bs
->node_name
[0] != '\0') {
5321 QTAILQ_REMOVE(&graph_bdrv_states
, bs
, node_list
);
5323 QTAILQ_REMOVE(&all_bdrv_states
, bs
, bs_list
);
5332 * Replace @bs by newly created block node.
5334 * @options is a QDict of options to pass to the block drivers, or NULL for an
5335 * empty set of options. The reference to the QDict belongs to the block layer
5336 * after the call (even on failure), so if the caller intends to reuse the
5337 * dictionary, it needs to use qobject_ref() before calling bdrv_open.
5339 BlockDriverState
*bdrv_insert_node(BlockDriverState
*bs
, QDict
*options
,
5340 int flags
, Error
**errp
)
5344 BlockDriverState
*new_node_bs
= NULL
;
5345 const char *drvname
, *node_name
;
5348 drvname
= qdict_get_try_str(options
, "driver");
5350 error_setg(errp
, "driver is not specified");
5354 drv
= bdrv_find_format(drvname
);
5356 error_setg(errp
, "Unknown driver: '%s'", drvname
);
5360 node_name
= qdict_get_try_str(options
, "node-name");
5362 GLOBAL_STATE_CODE();
5364 new_node_bs
= bdrv_new_open_driver_opts(drv
, node_name
, options
, flags
,
5366 options
= NULL
; /* bdrv_new_open_driver() eats options */
5368 error_prepend(errp
, "Could not create node: ");
5372 bdrv_drained_begin(bs
);
5373 ret
= bdrv_replace_node(bs
, new_node_bs
, errp
);
5374 bdrv_drained_end(bs
);
5377 error_prepend(errp
, "Could not replace node: ");
5384 qobject_unref(options
);
5385 bdrv_unref(new_node_bs
);
5390 * Run consistency checks on an image
5392 * Returns 0 if the check could be completed (it doesn't mean that the image is
5393 * free of errors) or -errno when an internal error occurred. The results of the
5394 * check are stored in res.
5396 int coroutine_fn
bdrv_co_check(BlockDriverState
*bs
,
5397 BdrvCheckResult
*res
, BdrvCheckMode fix
)
5399 if (bs
->drv
== NULL
) {
5402 if (bs
->drv
->bdrv_co_check
== NULL
) {
5406 memset(res
, 0, sizeof(*res
));
5407 return bs
->drv
->bdrv_co_check(bs
, res
, fix
);
5413 * -EINVAL - backing format specified, but no file
5414 * -ENOSPC - can't update the backing file because no space is left in the
5416 * -ENOTSUP - format driver doesn't support changing the backing file
5418 int bdrv_change_backing_file(BlockDriverState
*bs
, const char *backing_file
,
5419 const char *backing_fmt
, bool require
)
5421 BlockDriver
*drv
= bs
->drv
;
5424 GLOBAL_STATE_CODE();
5430 /* Backing file format doesn't make sense without a backing file */
5431 if (backing_fmt
&& !backing_file
) {
5435 if (require
&& backing_file
&& !backing_fmt
) {
5439 if (drv
->bdrv_change_backing_file
!= NULL
) {
5440 ret
= drv
->bdrv_change_backing_file(bs
, backing_file
, backing_fmt
);
5446 pstrcpy(bs
->backing_file
, sizeof(bs
->backing_file
), backing_file
?: "");
5447 pstrcpy(bs
->backing_format
, sizeof(bs
->backing_format
), backing_fmt
?: "");
5448 pstrcpy(bs
->auto_backing_file
, sizeof(bs
->auto_backing_file
),
5449 backing_file
?: "");
5455 * Finds the first non-filter node above bs in the chain between
5456 * active and bs. The returned node is either an immediate parent of
5457 * bs, or there are only filter nodes between the two.
5459 * Returns NULL if bs is not found in active's image chain,
5460 * or if active == bs.
5462 * Returns the bottommost base image if bs == NULL.
5464 BlockDriverState
*bdrv_find_overlay(BlockDriverState
*active
,
5465 BlockDriverState
*bs
)
5468 GLOBAL_STATE_CODE();
5470 bs
= bdrv_skip_filters(bs
);
5471 active
= bdrv_skip_filters(active
);
5474 BlockDriverState
*next
= bdrv_backing_chain_next(active
);
5484 /* Given a BDS, searches for the base layer. */
5485 BlockDriverState
*bdrv_find_base(BlockDriverState
*bs
)
5487 GLOBAL_STATE_CODE();
5489 return bdrv_find_overlay(bs
, NULL
);
5493 * Return true if at least one of the COW (backing) and filter links
5494 * between @bs and @base is frozen. @errp is set if that's the case.
5495 * @base must be reachable from @bs, or NULL.
5497 bool bdrv_is_backing_chain_frozen(BlockDriverState
*bs
, BlockDriverState
*base
,
5500 BlockDriverState
*i
;
5503 GLOBAL_STATE_CODE();
5505 for (i
= bs
; i
!= base
; i
= child_bs(child
)) {
5506 child
= bdrv_filter_or_cow_child(i
);
5508 if (child
&& child
->frozen
) {
5509 error_setg(errp
, "Cannot change '%s' link from '%s' to '%s'",
5510 child
->name
, i
->node_name
, child
->bs
->node_name
);
5519 * Freeze all COW (backing) and filter links between @bs and @base.
5520 * If any of the links is already frozen the operation is aborted and
5521 * none of the links are modified.
5522 * @base must be reachable from @bs, or NULL.
5523 * Returns 0 on success. On failure returns < 0 and sets @errp.
5525 int bdrv_freeze_backing_chain(BlockDriverState
*bs
, BlockDriverState
*base
,
5528 BlockDriverState
*i
;
5531 GLOBAL_STATE_CODE();
5533 if (bdrv_is_backing_chain_frozen(bs
, base
, errp
)) {
5537 for (i
= bs
; i
!= base
; i
= child_bs(child
)) {
5538 child
= bdrv_filter_or_cow_child(i
);
5539 if (child
&& child
->bs
->never_freeze
) {
5540 error_setg(errp
, "Cannot freeze '%s' link to '%s'",
5541 child
->name
, child
->bs
->node_name
);
5546 for (i
= bs
; i
!= base
; i
= child_bs(child
)) {
5547 child
= bdrv_filter_or_cow_child(i
);
5549 child
->frozen
= true;
5557 * Unfreeze all COW (backing) and filter links between @bs and @base.
5558 * The caller must ensure that all links are frozen before using this
5560 * @base must be reachable from @bs, or NULL.
5562 void bdrv_unfreeze_backing_chain(BlockDriverState
*bs
, BlockDriverState
*base
)
5564 BlockDriverState
*i
;
5567 GLOBAL_STATE_CODE();
5569 for (i
= bs
; i
!= base
; i
= child_bs(child
)) {
5570 child
= bdrv_filter_or_cow_child(i
);
5572 assert(child
->frozen
);
5573 child
->frozen
= false;
5579 * Drops images above 'base' up to and including 'top', and sets the image
5580 * above 'top' to have base as its backing file.
5582 * Requires that the overlay to 'top' is opened r/w, so that the backing file
5583 * information in 'bs' can be properly updated.
5585 * E.g., this will convert the following chain:
5586 * bottom <- base <- intermediate <- top <- active
5590 * bottom <- base <- active
5592 * It is allowed for bottom==base, in which case it converts:
5594 * base <- intermediate <- top <- active
5600 * If backing_file_str is non-NULL, it will be used when modifying top's
5601 * overlay image metadata.
5604 * if active == top, that is considered an error
5607 int bdrv_drop_intermediate(BlockDriverState
*top
, BlockDriverState
*base
,
5608 const char *backing_file_str
)
5610 BlockDriverState
*explicit_top
= top
;
5611 bool update_inherits_from
;
5613 Error
*local_err
= NULL
;
5615 g_autoptr(GSList
) updated_children
= NULL
;
5618 GLOBAL_STATE_CODE();
5621 bdrv_subtree_drained_begin(top
);
5623 if (!top
->drv
|| !base
->drv
) {
5627 /* Make sure that base is in the backing chain of top */
5628 if (!bdrv_chain_contains(top
, base
)) {
5632 /* If 'base' recursively inherits from 'top' then we should set
5633 * base->inherits_from to top->inherits_from after 'top' and all
5634 * other intermediate nodes have been dropped.
5635 * If 'top' is an implicit node (e.g. "commit_top") we should skip
5636 * it because no one inherits from it. We use explicit_top for that. */
5637 explicit_top
= bdrv_skip_implicit_filters(explicit_top
);
5638 update_inherits_from
= bdrv_inherits_from_recursive(base
, explicit_top
);
5640 /* success - we can delete the intermediate states, and link top->base */
5641 if (!backing_file_str
) {
5642 bdrv_refresh_filename(base
);
5643 backing_file_str
= base
->filename
;
5646 QLIST_FOREACH(c
, &top
->parents
, next_parent
) {
5647 updated_children
= g_slist_prepend(updated_children
, c
);
5651 * It seems correct to pass detach_subchain=true here, but it triggers
5652 * one more yet not fixed bug, when due to nested aio_poll loop we switch to
5653 * another drained section, which modify the graph (for example, removing
5654 * the child, which we keep in updated_children list). So, it's a TODO.
5656 * Note, bug triggered if pass detach_subchain=true here and run
5657 * test-bdrv-drain. test_drop_intermediate_poll() test-case will crash.
5660 bdrv_replace_node_common(top
, base
, false, false, &local_err
);
5662 error_report_err(local_err
);
5666 for (p
= updated_children
; p
; p
= p
->next
) {
5669 if (c
->klass
->update_filename
) {
5670 ret
= c
->klass
->update_filename(c
, base
, backing_file_str
,
5674 * TODO: Actually, we want to rollback all previous iterations
5675 * of this loop, and (which is almost impossible) previous
5676 * bdrv_replace_node()...
5678 * Note, that c->klass->update_filename may lead to permission
5679 * update, so it's a bad idea to call it inside permission
5680 * update transaction of bdrv_replace_node.
5682 error_report_err(local_err
);
5688 if (update_inherits_from
) {
5689 base
->inherits_from
= explicit_top
->inherits_from
;
5694 bdrv_subtree_drained_end(top
);
5700 * Implementation of BlockDriver.bdrv_get_allocated_file_size() that
5701 * sums the size of all data-bearing children. (This excludes backing
5704 static int64_t bdrv_sum_allocated_file_size(BlockDriverState
*bs
)
5707 int64_t child_size
, sum
= 0;
5709 QLIST_FOREACH(child
, &bs
->children
, next
) {
5710 if (child
->role
& (BDRV_CHILD_DATA
| BDRV_CHILD_METADATA
|
5711 BDRV_CHILD_FILTERED
))
5713 child_size
= bdrv_get_allocated_file_size(child
->bs
);
5714 if (child_size
< 0) {
5725 * Length of a allocated file in bytes. Sparse files are counted by actual
5726 * allocated space. Return < 0 if error or unknown.
5728 int64_t bdrv_get_allocated_file_size(BlockDriverState
*bs
)
5730 BlockDriver
*drv
= bs
->drv
;
5736 if (drv
->bdrv_get_allocated_file_size
) {
5737 return drv
->bdrv_get_allocated_file_size(bs
);
5740 if (drv
->bdrv_file_open
) {
5742 * Protocol drivers default to -ENOTSUP (most of their data is
5743 * not stored in any of their children (if they even have any),
5744 * so there is no generic way to figure it out).
5747 } else if (drv
->is_filter
) {
5748 /* Filter drivers default to the size of their filtered child */
5749 return bdrv_get_allocated_file_size(bdrv_filter_bs(bs
));
5751 /* Other drivers default to summing their children's sizes */
5752 return bdrv_sum_allocated_file_size(bs
);
5758 * @drv: Format driver
5759 * @opts: Creation options for new image
5760 * @in_bs: Existing image containing data for new image (may be NULL)
5761 * @errp: Error object
5762 * Returns: A #BlockMeasureInfo (free using qapi_free_BlockMeasureInfo())
5765 * Calculate file size required to create a new image.
5767 * If @in_bs is given then space for allocated clusters and zero clusters
5768 * from that image are included in the calculation. If @opts contains a
5769 * backing file that is shared by @in_bs then backing clusters may be omitted
5770 * from the calculation.
5772 * If @in_bs is NULL then the calculation includes no allocated clusters
5773 * unless a preallocation option is given in @opts.
5775 * Note that @in_bs may use a different BlockDriver from @drv.
5777 * If an error occurs the @errp pointer is set.
5779 BlockMeasureInfo
*bdrv_measure(BlockDriver
*drv
, QemuOpts
*opts
,
5780 BlockDriverState
*in_bs
, Error
**errp
)
5783 if (!drv
->bdrv_measure
) {
5784 error_setg(errp
, "Block driver '%s' does not support size measurement",
5789 return drv
->bdrv_measure(opts
, in_bs
, errp
);
5793 * Return number of sectors on success, -errno on error.
5795 int64_t bdrv_nb_sectors(BlockDriverState
*bs
)
5797 BlockDriver
*drv
= bs
->drv
;
5803 if (drv
->has_variable_length
) {
5804 int ret
= refresh_total_sectors(bs
, bs
->total_sectors
);
5809 return bs
->total_sectors
;
5813 * Return length in bytes on success, -errno on error.
5814 * The length is always a multiple of BDRV_SECTOR_SIZE.
5816 int64_t bdrv_getlength(BlockDriverState
*bs
)
5818 int64_t ret
= bdrv_nb_sectors(bs
);
5824 if (ret
> INT64_MAX
/ BDRV_SECTOR_SIZE
) {
5827 return ret
* BDRV_SECTOR_SIZE
;
5830 /* return 0 as number of sectors if no device present or error */
5831 void bdrv_get_geometry(BlockDriverState
*bs
, uint64_t *nb_sectors_ptr
)
5833 int64_t nb_sectors
= bdrv_nb_sectors(bs
);
5836 *nb_sectors_ptr
= nb_sectors
< 0 ? 0 : nb_sectors
;
5839 bool bdrv_is_sg(BlockDriverState
*bs
)
5846 * Return whether the given node supports compressed writes.
5848 bool bdrv_supports_compressed_writes(BlockDriverState
*bs
)
5850 BlockDriverState
*filtered
;
5853 if (!bs
->drv
|| !block_driver_can_compress(bs
->drv
)) {
5857 filtered
= bdrv_filter_bs(bs
);
5860 * Filters can only forward compressed writes, so we have to
5863 return bdrv_supports_compressed_writes(filtered
);
5869 const char *bdrv_get_format_name(BlockDriverState
*bs
)
5872 return bs
->drv
? bs
->drv
->format_name
: NULL
;
5875 static int qsort_strcmp(const void *a
, const void *b
)
5877 return strcmp(*(char *const *)a
, *(char *const *)b
);
5880 void bdrv_iterate_format(void (*it
)(void *opaque
, const char *name
),
5881 void *opaque
, bool read_only
)
5886 const char **formats
= NULL
;
5888 GLOBAL_STATE_CODE();
5890 QLIST_FOREACH(drv
, &bdrv_drivers
, list
) {
5891 if (drv
->format_name
) {
5895 if (use_bdrv_whitelist
&& !bdrv_is_whitelisted(drv
, read_only
)) {
5899 while (formats
&& i
&& !found
) {
5900 found
= !strcmp(formats
[--i
], drv
->format_name
);
5904 formats
= g_renew(const char *, formats
, count
+ 1);
5905 formats
[count
++] = drv
->format_name
;
5910 for (i
= 0; i
< (int)ARRAY_SIZE(block_driver_modules
); i
++) {
5911 const char *format_name
= block_driver_modules
[i
].format_name
;
5917 if (use_bdrv_whitelist
&&
5918 !bdrv_format_is_whitelisted(format_name
, read_only
)) {
5922 while (formats
&& j
&& !found
) {
5923 found
= !strcmp(formats
[--j
], format_name
);
5927 formats
= g_renew(const char *, formats
, count
+ 1);
5928 formats
[count
++] = format_name
;
5933 qsort(formats
, count
, sizeof(formats
[0]), qsort_strcmp
);
5935 for (i
= 0; i
< count
; i
++) {
5936 it(opaque
, formats
[i
]);
5942 /* This function is to find a node in the bs graph */
5943 BlockDriverState
*bdrv_find_node(const char *node_name
)
5945 BlockDriverState
*bs
;
5948 GLOBAL_STATE_CODE();
5950 QTAILQ_FOREACH(bs
, &graph_bdrv_states
, node_list
) {
5951 if (!strcmp(node_name
, bs
->node_name
)) {
5958 /* Put this QMP function here so it can access the static graph_bdrv_states. */
5959 BlockDeviceInfoList
*bdrv_named_nodes_list(bool flat
,
5962 BlockDeviceInfoList
*list
;
5963 BlockDriverState
*bs
;
5965 GLOBAL_STATE_CODE();
5968 QTAILQ_FOREACH(bs
, &graph_bdrv_states
, node_list
) {
5969 BlockDeviceInfo
*info
= bdrv_block_device_info(NULL
, bs
, flat
, errp
);
5971 qapi_free_BlockDeviceInfoList(list
);
5974 QAPI_LIST_PREPEND(list
, info
);
5980 typedef struct XDbgBlockGraphConstructor
{
5981 XDbgBlockGraph
*graph
;
5982 GHashTable
*graph_nodes
;
5983 } XDbgBlockGraphConstructor
;
5985 static XDbgBlockGraphConstructor
*xdbg_graph_new(void)
5987 XDbgBlockGraphConstructor
*gr
= g_new(XDbgBlockGraphConstructor
, 1);
5989 gr
->graph
= g_new0(XDbgBlockGraph
, 1);
5990 gr
->graph_nodes
= g_hash_table_new(NULL
, NULL
);
5995 static XDbgBlockGraph
*xdbg_graph_finalize(XDbgBlockGraphConstructor
*gr
)
5997 XDbgBlockGraph
*graph
= gr
->graph
;
5999 g_hash_table_destroy(gr
->graph_nodes
);
6005 static uintptr_t xdbg_graph_node_num(XDbgBlockGraphConstructor
*gr
, void *node
)
6007 uintptr_t ret
= (uintptr_t)g_hash_table_lookup(gr
->graph_nodes
, node
);
6014 * Start counting from 1, not 0, because 0 interferes with not-found (NULL)
6015 * answer of g_hash_table_lookup.
6017 ret
= g_hash_table_size(gr
->graph_nodes
) + 1;
6018 g_hash_table_insert(gr
->graph_nodes
, node
, (void *)ret
);
6023 static void xdbg_graph_add_node(XDbgBlockGraphConstructor
*gr
, void *node
,
6024 XDbgBlockGraphNodeType type
, const char *name
)
6026 XDbgBlockGraphNode
*n
;
6028 n
= g_new0(XDbgBlockGraphNode
, 1);
6030 n
->id
= xdbg_graph_node_num(gr
, node
);
6032 n
->name
= g_strdup(name
);
6034 QAPI_LIST_PREPEND(gr
->graph
->nodes
, n
);
6037 static void xdbg_graph_add_edge(XDbgBlockGraphConstructor
*gr
, void *parent
,
6038 const BdrvChild
*child
)
6040 BlockPermission qapi_perm
;
6041 XDbgBlockGraphEdge
*edge
;
6042 GLOBAL_STATE_CODE();
6044 edge
= g_new0(XDbgBlockGraphEdge
, 1);
6046 edge
->parent
= xdbg_graph_node_num(gr
, parent
);
6047 edge
->child
= xdbg_graph_node_num(gr
, child
->bs
);
6048 edge
->name
= g_strdup(child
->name
);
6050 for (qapi_perm
= 0; qapi_perm
< BLOCK_PERMISSION__MAX
; qapi_perm
++) {
6051 uint64_t flag
= bdrv_qapi_perm_to_blk_perm(qapi_perm
);
6053 if (flag
& child
->perm
) {
6054 QAPI_LIST_PREPEND(edge
->perm
, qapi_perm
);
6056 if (flag
& child
->shared_perm
) {
6057 QAPI_LIST_PREPEND(edge
->shared_perm
, qapi_perm
);
6061 QAPI_LIST_PREPEND(gr
->graph
->edges
, edge
);
6065 XDbgBlockGraph
*bdrv_get_xdbg_block_graph(Error
**errp
)
6069 BlockDriverState
*bs
;
6071 XDbgBlockGraphConstructor
*gr
= xdbg_graph_new();
6073 GLOBAL_STATE_CODE();
6075 for (blk
= blk_all_next(NULL
); blk
; blk
= blk_all_next(blk
)) {
6076 char *allocated_name
= NULL
;
6077 const char *name
= blk_name(blk
);
6080 name
= allocated_name
= blk_get_attached_dev_id(blk
);
6082 xdbg_graph_add_node(gr
, blk
, X_DBG_BLOCK_GRAPH_NODE_TYPE_BLOCK_BACKEND
,
6084 g_free(allocated_name
);
6085 if (blk_root(blk
)) {
6086 xdbg_graph_add_edge(gr
, blk
, blk_root(blk
));
6090 for (job
= block_job_next(NULL
); job
; job
= block_job_next(job
)) {
6093 xdbg_graph_add_node(gr
, job
, X_DBG_BLOCK_GRAPH_NODE_TYPE_BLOCK_JOB
,
6095 for (el
= job
->nodes
; el
; el
= el
->next
) {
6096 xdbg_graph_add_edge(gr
, job
, (BdrvChild
*)el
->data
);
6100 QTAILQ_FOREACH(bs
, &graph_bdrv_states
, node_list
) {
6101 xdbg_graph_add_node(gr
, bs
, X_DBG_BLOCK_GRAPH_NODE_TYPE_BLOCK_DRIVER
,
6103 QLIST_FOREACH(child
, &bs
->children
, next
) {
6104 xdbg_graph_add_edge(gr
, bs
, child
);
6108 return xdbg_graph_finalize(gr
);
6111 BlockDriverState
*bdrv_lookup_bs(const char *device
,
6112 const char *node_name
,
6116 BlockDriverState
*bs
;
6118 GLOBAL_STATE_CODE();
6121 blk
= blk_by_name(device
);
6126 error_setg(errp
, "Device '%s' has no medium", device
);
6134 bs
= bdrv_find_node(node_name
);
6141 error_setg(errp
, "Cannot find device=\'%s\' nor node-name=\'%s\'",
6142 device
? device
: "",
6143 node_name
? node_name
: "");
6147 /* If 'base' is in the same chain as 'top', return true. Otherwise,
6148 * return false. If either argument is NULL, return false. */
6149 bool bdrv_chain_contains(BlockDriverState
*top
, BlockDriverState
*base
)
6152 GLOBAL_STATE_CODE();
6154 while (top
&& top
!= base
) {
6155 top
= bdrv_filter_or_cow_bs(top
);
6161 BlockDriverState
*bdrv_next_node(BlockDriverState
*bs
)
6163 GLOBAL_STATE_CODE();
6165 return QTAILQ_FIRST(&graph_bdrv_states
);
6167 return QTAILQ_NEXT(bs
, node_list
);
6170 BlockDriverState
*bdrv_next_all_states(BlockDriverState
*bs
)
6172 GLOBAL_STATE_CODE();
6174 return QTAILQ_FIRST(&all_bdrv_states
);
6176 return QTAILQ_NEXT(bs
, bs_list
);
6179 const char *bdrv_get_node_name(const BlockDriverState
*bs
)
6182 return bs
->node_name
;
6185 const char *bdrv_get_parent_name(const BlockDriverState
*bs
)
6190 /* If multiple parents have a name, just pick the first one. */
6191 QLIST_FOREACH(c
, &bs
->parents
, next_parent
) {
6192 if (c
->klass
->get_name
) {
6193 name
= c
->klass
->get_name(c
);
6194 if (name
&& *name
) {
6203 /* TODO check what callers really want: bs->node_name or blk_name() */
6204 const char *bdrv_get_device_name(const BlockDriverState
*bs
)
6207 return bdrv_get_parent_name(bs
) ?: "";
6210 /* This can be used to identify nodes that might not have a device
6211 * name associated. Since node and device names live in the same
6212 * namespace, the result is unambiguous. The exception is if both are
6213 * absent, then this returns an empty (non-null) string. */
6214 const char *bdrv_get_device_or_node_name(const BlockDriverState
*bs
)
6217 return bdrv_get_parent_name(bs
) ?: bs
->node_name
;
6220 int bdrv_get_flags(BlockDriverState
*bs
)
6222 GLOBAL_STATE_CODE();
6223 return bs
->open_flags
;
6226 int bdrv_has_zero_init_1(BlockDriverState
*bs
)
6228 GLOBAL_STATE_CODE();
6232 int bdrv_has_zero_init(BlockDriverState
*bs
)
6234 BlockDriverState
*filtered
;
6235 GLOBAL_STATE_CODE();
6241 /* If BS is a copy on write image, it is initialized to
6242 the contents of the base image, which may not be zeroes. */
6243 if (bdrv_cow_child(bs
)) {
6246 if (bs
->drv
->bdrv_has_zero_init
) {
6247 return bs
->drv
->bdrv_has_zero_init(bs
);
6250 filtered
= bdrv_filter_bs(bs
);
6252 return bdrv_has_zero_init(filtered
);
6259 bool bdrv_can_write_zeroes_with_unmap(BlockDriverState
*bs
)
6262 if (!(bs
->open_flags
& BDRV_O_UNMAP
)) {
6266 return bs
->supported_zero_flags
& BDRV_REQ_MAY_UNMAP
;
6269 void bdrv_get_backing_filename(BlockDriverState
*bs
,
6270 char *filename
, int filename_size
)
6273 pstrcpy(filename
, filename_size
, bs
->backing_file
);
6276 int bdrv_get_info(BlockDriverState
*bs
, BlockDriverInfo
*bdi
)
6279 BlockDriver
*drv
= bs
->drv
;
6281 /* if bs->drv == NULL, bs is closed, so there's nothing to do here */
6285 if (!drv
->bdrv_get_info
) {
6286 BlockDriverState
*filtered
= bdrv_filter_bs(bs
);
6288 return bdrv_get_info(filtered
, bdi
);
6292 memset(bdi
, 0, sizeof(*bdi
));
6293 ret
= drv
->bdrv_get_info(bs
, bdi
);
6298 if (bdi
->cluster_size
> BDRV_MAX_ALIGNMENT
) {
6305 ImageInfoSpecific
*bdrv_get_specific_info(BlockDriverState
*bs
,
6308 BlockDriver
*drv
= bs
->drv
;
6310 if (drv
&& drv
->bdrv_get_specific_info
) {
6311 return drv
->bdrv_get_specific_info(bs
, errp
);
6316 BlockStatsSpecific
*bdrv_get_specific_stats(BlockDriverState
*bs
)
6318 BlockDriver
*drv
= bs
->drv
;
6320 if (!drv
|| !drv
->bdrv_get_specific_stats
) {
6323 return drv
->bdrv_get_specific_stats(bs
);
6326 void bdrv_debug_event(BlockDriverState
*bs
, BlkdebugEvent event
)
6329 if (!bs
|| !bs
->drv
|| !bs
->drv
->bdrv_debug_event
) {
6333 bs
->drv
->bdrv_debug_event(bs
, event
);
6336 static BlockDriverState
*bdrv_find_debug_node(BlockDriverState
*bs
)
6338 while (bs
&& bs
->drv
&& !bs
->drv
->bdrv_debug_breakpoint
) {
6339 bs
= bdrv_primary_bs(bs
);
6342 if (bs
&& bs
->drv
&& bs
->drv
->bdrv_debug_breakpoint
) {
6343 assert(bs
->drv
->bdrv_debug_remove_breakpoint
);
6350 int bdrv_debug_breakpoint(BlockDriverState
*bs
, const char *event
,
6353 GLOBAL_STATE_CODE();
6354 bs
= bdrv_find_debug_node(bs
);
6356 return bs
->drv
->bdrv_debug_breakpoint(bs
, event
, tag
);
6362 int bdrv_debug_remove_breakpoint(BlockDriverState
*bs
, const char *tag
)
6364 GLOBAL_STATE_CODE();
6365 bs
= bdrv_find_debug_node(bs
);
6367 return bs
->drv
->bdrv_debug_remove_breakpoint(bs
, tag
);
6373 int bdrv_debug_resume(BlockDriverState
*bs
, const char *tag
)
6375 GLOBAL_STATE_CODE();
6376 while (bs
&& (!bs
->drv
|| !bs
->drv
->bdrv_debug_resume
)) {
6377 bs
= bdrv_primary_bs(bs
);
6380 if (bs
&& bs
->drv
&& bs
->drv
->bdrv_debug_resume
) {
6381 return bs
->drv
->bdrv_debug_resume(bs
, tag
);
6387 bool bdrv_debug_is_suspended(BlockDriverState
*bs
, const char *tag
)
6389 GLOBAL_STATE_CODE();
6390 while (bs
&& bs
->drv
&& !bs
->drv
->bdrv_debug_is_suspended
) {
6391 bs
= bdrv_primary_bs(bs
);
6394 if (bs
&& bs
->drv
&& bs
->drv
->bdrv_debug_is_suspended
) {
6395 return bs
->drv
->bdrv_debug_is_suspended(bs
, tag
);
6401 /* backing_file can either be relative, or absolute, or a protocol. If it is
6402 * relative, it must be relative to the chain. So, passing in bs->filename
6403 * from a BDS as backing_file should not be done, as that may be relative to
6404 * the CWD rather than the chain. */
6405 BlockDriverState
*bdrv_find_backing_image(BlockDriverState
*bs
,
6406 const char *backing_file
)
6408 char *filename_full
= NULL
;
6409 char *backing_file_full
= NULL
;
6410 char *filename_tmp
= NULL
;
6411 int is_protocol
= 0;
6412 bool filenames_refreshed
= false;
6413 BlockDriverState
*curr_bs
= NULL
;
6414 BlockDriverState
*retval
= NULL
;
6415 BlockDriverState
*bs_below
;
6417 GLOBAL_STATE_CODE();
6419 if (!bs
|| !bs
->drv
|| !backing_file
) {
6423 filename_full
= g_malloc(PATH_MAX
);
6424 backing_file_full
= g_malloc(PATH_MAX
);
6426 is_protocol
= path_has_protocol(backing_file
);
6429 * Being largely a legacy function, skip any filters here
6430 * (because filters do not have normal filenames, so they cannot
6431 * match anyway; and allowing json:{} filenames is a bit out of
6434 for (curr_bs
= bdrv_skip_filters(bs
);
6435 bdrv_cow_child(curr_bs
) != NULL
;
6438 bs_below
= bdrv_backing_chain_next(curr_bs
);
6440 if (bdrv_backing_overridden(curr_bs
)) {
6442 * If the backing file was overridden, we can only compare
6443 * directly against the backing node's filename.
6446 if (!filenames_refreshed
) {
6448 * This will automatically refresh all of the
6449 * filenames in the rest of the backing chain, so we
6450 * only need to do this once.
6452 bdrv_refresh_filename(bs_below
);
6453 filenames_refreshed
= true;
6456 if (strcmp(backing_file
, bs_below
->filename
) == 0) {
6460 } else if (is_protocol
|| path_has_protocol(curr_bs
->backing_file
)) {
6462 * If either of the filename paths is actually a protocol, then
6463 * compare unmodified paths; otherwise make paths relative.
6465 char *backing_file_full_ret
;
6467 if (strcmp(backing_file
, curr_bs
->backing_file
) == 0) {
6471 /* Also check against the full backing filename for the image */
6472 backing_file_full_ret
= bdrv_get_full_backing_filename(curr_bs
,
6474 if (backing_file_full_ret
) {
6475 bool equal
= strcmp(backing_file
, backing_file_full_ret
) == 0;
6476 g_free(backing_file_full_ret
);
6483 /* If not an absolute filename path, make it relative to the current
6484 * image's filename path */
6485 filename_tmp
= bdrv_make_absolute_filename(curr_bs
, backing_file
,
6487 /* We are going to compare canonicalized absolute pathnames */
6488 if (!filename_tmp
|| !realpath(filename_tmp
, filename_full
)) {
6489 g_free(filename_tmp
);
6492 g_free(filename_tmp
);
6494 /* We need to make sure the backing filename we are comparing against
6495 * is relative to the current image filename (or absolute) */
6496 filename_tmp
= bdrv_get_full_backing_filename(curr_bs
, NULL
);
6497 if (!filename_tmp
|| !realpath(filename_tmp
, backing_file_full
)) {
6498 g_free(filename_tmp
);
6501 g_free(filename_tmp
);
6503 if (strcmp(backing_file_full
, filename_full
) == 0) {
6510 g_free(filename_full
);
6511 g_free(backing_file_full
);
6515 void bdrv_init(void)
6517 #ifdef CONFIG_BDRV_WHITELIST_TOOLS
6518 use_bdrv_whitelist
= 1;
6520 module_call_init(MODULE_INIT_BLOCK
);
6523 void bdrv_init_with_whitelist(void)
6525 use_bdrv_whitelist
= 1;
6529 int bdrv_activate(BlockDriverState
*bs
, Error
**errp
)
6531 BdrvChild
*child
, *parent
;
6532 Error
*local_err
= NULL
;
6534 BdrvDirtyBitmap
*bm
;
6536 GLOBAL_STATE_CODE();
6542 QLIST_FOREACH(child
, &bs
->children
, next
) {
6543 bdrv_activate(child
->bs
, &local_err
);
6545 error_propagate(errp
, local_err
);
6551 * Update permissions, they may differ for inactive nodes.
6553 * Note that the required permissions of inactive images are always a
6554 * subset of the permissions required after activating the image. This
6555 * allows us to just get the permissions upfront without restricting
6556 * bdrv_co_invalidate_cache().
6558 * It also means that in error cases, we don't have to try and revert to
6559 * the old permissions (which is an operation that could fail, too). We can
6560 * just keep the extended permissions for the next time that an activation
6561 * of the image is tried.
6563 if (bs
->open_flags
& BDRV_O_INACTIVE
) {
6564 bs
->open_flags
&= ~BDRV_O_INACTIVE
;
6565 ret
= bdrv_refresh_perms(bs
, errp
);
6567 bs
->open_flags
|= BDRV_O_INACTIVE
;
6571 ret
= bdrv_invalidate_cache(bs
, errp
);
6573 bs
->open_flags
|= BDRV_O_INACTIVE
;
6577 FOR_EACH_DIRTY_BITMAP(bs
, bm
) {
6578 bdrv_dirty_bitmap_skip_store(bm
, false);
6581 ret
= refresh_total_sectors(bs
, bs
->total_sectors
);
6583 bs
->open_flags
|= BDRV_O_INACTIVE
;
6584 error_setg_errno(errp
, -ret
, "Could not refresh total sector count");
6589 QLIST_FOREACH(parent
, &bs
->parents
, next_parent
) {
6590 if (parent
->klass
->activate
) {
6591 parent
->klass
->activate(parent
, &local_err
);
6593 bs
->open_flags
|= BDRV_O_INACTIVE
;
6594 error_propagate(errp
, local_err
);
6603 int coroutine_fn
bdrv_co_invalidate_cache(BlockDriverState
*bs
, Error
**errp
)
6605 Error
*local_err
= NULL
;
6607 assert(!(bs
->open_flags
& BDRV_O_INACTIVE
));
6609 if (bs
->drv
->bdrv_co_invalidate_cache
) {
6610 bs
->drv
->bdrv_co_invalidate_cache(bs
, &local_err
);
6612 error_propagate(errp
, local_err
);
6620 void bdrv_activate_all(Error
**errp
)
6622 BlockDriverState
*bs
;
6623 BdrvNextIterator it
;
6625 GLOBAL_STATE_CODE();
6627 for (bs
= bdrv_first(&it
); bs
; bs
= bdrv_next(&it
)) {
6628 AioContext
*aio_context
= bdrv_get_aio_context(bs
);
6631 aio_context_acquire(aio_context
);
6632 ret
= bdrv_activate(bs
, errp
);
6633 aio_context_release(aio_context
);
6635 bdrv_next_cleanup(&it
);
6641 static bool bdrv_has_bds_parent(BlockDriverState
*bs
, bool only_active
)
6645 QLIST_FOREACH(parent
, &bs
->parents
, next_parent
) {
6646 if (parent
->klass
->parent_is_bds
) {
6647 BlockDriverState
*parent_bs
= parent
->opaque
;
6648 if (!only_active
|| !(parent_bs
->open_flags
& BDRV_O_INACTIVE
)) {
6657 static int bdrv_inactivate_recurse(BlockDriverState
*bs
)
6659 BdrvChild
*child
, *parent
;
6661 uint64_t cumulative_perms
, cumulative_shared_perms
;
6667 /* Make sure that we don't inactivate a child before its parent.
6668 * It will be covered by recursion from the yet active parent. */
6669 if (bdrv_has_bds_parent(bs
, true)) {
6673 assert(!(bs
->open_flags
& BDRV_O_INACTIVE
));
6675 /* Inactivate this node */
6676 if (bs
->drv
->bdrv_inactivate
) {
6677 ret
= bs
->drv
->bdrv_inactivate(bs
);
6683 QLIST_FOREACH(parent
, &bs
->parents
, next_parent
) {
6684 if (parent
->klass
->inactivate
) {
6685 ret
= parent
->klass
->inactivate(parent
);
6692 bdrv_get_cumulative_perm(bs
, &cumulative_perms
,
6693 &cumulative_shared_perms
);
6694 if (cumulative_perms
& (BLK_PERM_WRITE
| BLK_PERM_WRITE_UNCHANGED
)) {
6695 /* Our inactive parents still need write access. Inactivation failed. */
6699 bs
->open_flags
|= BDRV_O_INACTIVE
;
6702 * Update permissions, they may differ for inactive nodes.
6703 * We only tried to loosen restrictions, so errors are not fatal, ignore
6706 bdrv_refresh_perms(bs
, NULL
);
6708 /* Recursively inactivate children */
6709 QLIST_FOREACH(child
, &bs
->children
, next
) {
6710 ret
= bdrv_inactivate_recurse(child
->bs
);
6719 int bdrv_inactivate_all(void)
6721 BlockDriverState
*bs
= NULL
;
6722 BdrvNextIterator it
;
6724 GSList
*aio_ctxs
= NULL
, *ctx
;
6726 GLOBAL_STATE_CODE();
6728 for (bs
= bdrv_first(&it
); bs
; bs
= bdrv_next(&it
)) {
6729 AioContext
*aio_context
= bdrv_get_aio_context(bs
);
6731 if (!g_slist_find(aio_ctxs
, aio_context
)) {
6732 aio_ctxs
= g_slist_prepend(aio_ctxs
, aio_context
);
6733 aio_context_acquire(aio_context
);
6737 for (bs
= bdrv_first(&it
); bs
; bs
= bdrv_next(&it
)) {
6738 /* Nodes with BDS parents are covered by recursion from the last
6739 * parent that gets inactivated. Don't inactivate them a second
6740 * time if that has already happened. */
6741 if (bdrv_has_bds_parent(bs
, false)) {
6744 ret
= bdrv_inactivate_recurse(bs
);
6746 bdrv_next_cleanup(&it
);
6752 for (ctx
= aio_ctxs
; ctx
!= NULL
; ctx
= ctx
->next
) {
6753 AioContext
*aio_context
= ctx
->data
;
6754 aio_context_release(aio_context
);
6756 g_slist_free(aio_ctxs
);
6761 /**************************************************************/
6762 /* removable device support */
6765 * Return TRUE if the media is present
6767 bool bdrv_is_inserted(BlockDriverState
*bs
)
6769 BlockDriver
*drv
= bs
->drv
;
6776 if (drv
->bdrv_is_inserted
) {
6777 return drv
->bdrv_is_inserted(bs
);
6779 QLIST_FOREACH(child
, &bs
->children
, next
) {
6780 if (!bdrv_is_inserted(child
->bs
)) {
6788 * If eject_flag is TRUE, eject the media. Otherwise, close the tray
6790 void bdrv_eject(BlockDriverState
*bs
, bool eject_flag
)
6792 BlockDriver
*drv
= bs
->drv
;
6795 if (drv
&& drv
->bdrv_eject
) {
6796 drv
->bdrv_eject(bs
, eject_flag
);
6801 * Lock or unlock the media (if it is locked, the user won't be able
6802 * to eject it manually).
6804 void bdrv_lock_medium(BlockDriverState
*bs
, bool locked
)
6806 BlockDriver
*drv
= bs
->drv
;
6808 trace_bdrv_lock_medium(bs
, locked
);
6810 if (drv
&& drv
->bdrv_lock_medium
) {
6811 drv
->bdrv_lock_medium(bs
, locked
);
6815 /* Get a reference to bs */
6816 void bdrv_ref(BlockDriverState
*bs
)
6818 GLOBAL_STATE_CODE();
6822 /* Release a previously grabbed reference to bs.
6823 * If after releasing, reference count is zero, the BlockDriverState is
6825 void bdrv_unref(BlockDriverState
*bs
)
6827 GLOBAL_STATE_CODE();
6831 assert(bs
->refcnt
> 0);
6832 if (--bs
->refcnt
== 0) {
6837 struct BdrvOpBlocker
{
6839 QLIST_ENTRY(BdrvOpBlocker
) list
;
6842 bool bdrv_op_is_blocked(BlockDriverState
*bs
, BlockOpType op
, Error
**errp
)
6844 BdrvOpBlocker
*blocker
;
6845 GLOBAL_STATE_CODE();
6846 assert((int) op
>= 0 && op
< BLOCK_OP_TYPE_MAX
);
6847 if (!QLIST_EMPTY(&bs
->op_blockers
[op
])) {
6848 blocker
= QLIST_FIRST(&bs
->op_blockers
[op
]);
6849 error_propagate_prepend(errp
, error_copy(blocker
->reason
),
6850 "Node '%s' is busy: ",
6851 bdrv_get_device_or_node_name(bs
));
6857 void bdrv_op_block(BlockDriverState
*bs
, BlockOpType op
, Error
*reason
)
6859 BdrvOpBlocker
*blocker
;
6860 GLOBAL_STATE_CODE();
6861 assert((int) op
>= 0 && op
< BLOCK_OP_TYPE_MAX
);
6863 blocker
= g_new0(BdrvOpBlocker
, 1);
6864 blocker
->reason
= reason
;
6865 QLIST_INSERT_HEAD(&bs
->op_blockers
[op
], blocker
, list
);
6868 void bdrv_op_unblock(BlockDriverState
*bs
, BlockOpType op
, Error
*reason
)
6870 BdrvOpBlocker
*blocker
, *next
;
6871 GLOBAL_STATE_CODE();
6872 assert((int) op
>= 0 && op
< BLOCK_OP_TYPE_MAX
);
6873 QLIST_FOREACH_SAFE(blocker
, &bs
->op_blockers
[op
], list
, next
) {
6874 if (blocker
->reason
== reason
) {
6875 QLIST_REMOVE(blocker
, list
);
6881 void bdrv_op_block_all(BlockDriverState
*bs
, Error
*reason
)
6884 GLOBAL_STATE_CODE();
6885 for (i
= 0; i
< BLOCK_OP_TYPE_MAX
; i
++) {
6886 bdrv_op_block(bs
, i
, reason
);
6890 void bdrv_op_unblock_all(BlockDriverState
*bs
, Error
*reason
)
6893 GLOBAL_STATE_CODE();
6894 for (i
= 0; i
< BLOCK_OP_TYPE_MAX
; i
++) {
6895 bdrv_op_unblock(bs
, i
, reason
);
6899 bool bdrv_op_blocker_is_empty(BlockDriverState
*bs
)
6902 GLOBAL_STATE_CODE();
6903 for (i
= 0; i
< BLOCK_OP_TYPE_MAX
; i
++) {
6904 if (!QLIST_EMPTY(&bs
->op_blockers
[i
])) {
6911 void bdrv_img_create(const char *filename
, const char *fmt
,
6912 const char *base_filename
, const char *base_fmt
,
6913 char *options
, uint64_t img_size
, int flags
, bool quiet
,
6916 QemuOptsList
*create_opts
= NULL
;
6917 QemuOpts
*opts
= NULL
;
6918 const char *backing_fmt
, *backing_file
;
6920 BlockDriver
*drv
, *proto_drv
;
6921 Error
*local_err
= NULL
;
6924 GLOBAL_STATE_CODE();
6926 /* Find driver and parse its options */
6927 drv
= bdrv_find_format(fmt
);
6929 error_setg(errp
, "Unknown file format '%s'", fmt
);
6933 proto_drv
= bdrv_find_protocol(filename
, true, errp
);
6938 if (!drv
->create_opts
) {
6939 error_setg(errp
, "Format driver '%s' does not support image creation",
6944 if (!proto_drv
->create_opts
) {
6945 error_setg(errp
, "Protocol driver '%s' does not support image creation",
6946 proto_drv
->format_name
);
6950 /* Create parameter list */
6951 create_opts
= qemu_opts_append(create_opts
, drv
->create_opts
);
6952 create_opts
= qemu_opts_append(create_opts
, proto_drv
->create_opts
);
6954 opts
= qemu_opts_create(create_opts
, NULL
, 0, &error_abort
);
6956 /* Parse -o options */
6958 if (!qemu_opts_do_parse(opts
, options
, NULL
, errp
)) {
6963 if (!qemu_opt_get(opts
, BLOCK_OPT_SIZE
)) {
6964 qemu_opt_set_number(opts
, BLOCK_OPT_SIZE
, img_size
, &error_abort
);
6965 } else if (img_size
!= UINT64_C(-1)) {
6966 error_setg(errp
, "The image size must be specified only once");
6970 if (base_filename
) {
6971 if (!qemu_opt_set(opts
, BLOCK_OPT_BACKING_FILE
, base_filename
,
6973 error_setg(errp
, "Backing file not supported for file format '%s'",
6980 if (!qemu_opt_set(opts
, BLOCK_OPT_BACKING_FMT
, base_fmt
, NULL
)) {
6981 error_setg(errp
, "Backing file format not supported for file "
6982 "format '%s'", fmt
);
6987 backing_file
= qemu_opt_get(opts
, BLOCK_OPT_BACKING_FILE
);
6989 if (!strcmp(filename
, backing_file
)) {
6990 error_setg(errp
, "Error: Trying to create an image with the "
6991 "same filename as the backing file");
6994 if (backing_file
[0] == '\0') {
6995 error_setg(errp
, "Expected backing file name, got empty string");
7000 backing_fmt
= qemu_opt_get(opts
, BLOCK_OPT_BACKING_FMT
);
7002 /* The size for the image must always be specified, unless we have a backing
7003 * file and we have not been forbidden from opening it. */
7004 size
= qemu_opt_get_size(opts
, BLOCK_OPT_SIZE
, img_size
);
7005 if (backing_file
&& !(flags
& BDRV_O_NO_BACKING
)) {
7006 BlockDriverState
*bs
;
7009 QDict
*backing_options
= NULL
;
7012 bdrv_get_full_backing_filename_from_filename(filename
, backing_file
,
7017 assert(full_backing
);
7020 * No need to do I/O here, which allows us to open encrypted
7021 * backing images without needing the secret
7024 back_flags
&= ~(BDRV_O_RDWR
| BDRV_O_SNAPSHOT
| BDRV_O_NO_BACKING
);
7025 back_flags
|= BDRV_O_NO_IO
;
7027 backing_options
= qdict_new();
7029 qdict_put_str(backing_options
, "driver", backing_fmt
);
7031 qdict_put_bool(backing_options
, BDRV_OPT_FORCE_SHARE
, true);
7033 bs
= bdrv_open(full_backing
, NULL
, backing_options
, back_flags
,
7035 g_free(full_backing
);
7037 error_append_hint(&local_err
, "Could not open backing image.\n");
7041 error_setg(&local_err
,
7042 "Backing file specified without backing format");
7043 error_append_hint(&local_err
, "Detected format of %s.",
7044 bs
->drv
->format_name
);
7048 /* Opened BS, have no size */
7049 size
= bdrv_getlength(bs
);
7051 error_setg_errno(errp
, -size
, "Could not get size of '%s'",
7056 qemu_opt_set_number(opts
, BLOCK_OPT_SIZE
, size
, &error_abort
);
7060 /* (backing_file && !(flags & BDRV_O_NO_BACKING)) */
7061 } else if (backing_file
&& !backing_fmt
) {
7062 error_setg(&local_err
,
7063 "Backing file specified without backing format");
7068 error_setg(errp
, "Image creation needs a size parameter");
7073 printf("Formatting '%s', fmt=%s ", filename
, fmt
);
7074 qemu_opts_print(opts
, " ");
7079 ret
= bdrv_create(drv
, filename
, opts
, &local_err
);
7081 if (ret
== -EFBIG
) {
7082 /* This is generally a better message than whatever the driver would
7083 * deliver (especially because of the cluster_size_hint), since that
7084 * is most probably not much different from "image too large". */
7085 const char *cluster_size_hint
= "";
7086 if (qemu_opt_get_size(opts
, BLOCK_OPT_CLUSTER_SIZE
, 0)) {
7087 cluster_size_hint
= " (try using a larger cluster size)";
7089 error_setg(errp
, "The image size is too large for file format '%s'"
7090 "%s", fmt
, cluster_size_hint
);
7091 error_free(local_err
);
7096 qemu_opts_del(opts
);
7097 qemu_opts_free(create_opts
);
7098 error_propagate(errp
, local_err
);
7101 AioContext
*bdrv_get_aio_context(BlockDriverState
*bs
)
7104 return bs
? bs
->aio_context
: qemu_get_aio_context();
7107 AioContext
*coroutine_fn
bdrv_co_enter(BlockDriverState
*bs
)
7109 Coroutine
*self
= qemu_coroutine_self();
7110 AioContext
*old_ctx
= qemu_coroutine_get_aio_context(self
);
7111 AioContext
*new_ctx
;
7115 * Increase bs->in_flight to ensure that this operation is completed before
7116 * moving the node to a different AioContext. Read new_ctx only afterwards.
7118 bdrv_inc_in_flight(bs
);
7120 new_ctx
= bdrv_get_aio_context(bs
);
7121 aio_co_reschedule_self(new_ctx
);
7125 void coroutine_fn
bdrv_co_leave(BlockDriverState
*bs
, AioContext
*old_ctx
)
7128 aio_co_reschedule_self(old_ctx
);
7129 bdrv_dec_in_flight(bs
);
7132 void coroutine_fn
bdrv_co_lock(BlockDriverState
*bs
)
7134 AioContext
*ctx
= bdrv_get_aio_context(bs
);
7136 /* In the main thread, bs->aio_context won't change concurrently */
7137 assert(qemu_get_current_aio_context() == qemu_get_aio_context());
7140 * We're in coroutine context, so we already hold the lock of the main
7141 * loop AioContext. Don't lock it twice to avoid deadlocks.
7143 assert(qemu_in_coroutine());
7144 if (ctx
!= qemu_get_aio_context()) {
7145 aio_context_acquire(ctx
);
7149 void coroutine_fn
bdrv_co_unlock(BlockDriverState
*bs
)
7151 AioContext
*ctx
= bdrv_get_aio_context(bs
);
7153 assert(qemu_in_coroutine());
7154 if (ctx
!= qemu_get_aio_context()) {
7155 aio_context_release(ctx
);
7159 void bdrv_coroutine_enter(BlockDriverState
*bs
, Coroutine
*co
)
7162 aio_co_enter(bdrv_get_aio_context(bs
), co
);
7165 static void bdrv_do_remove_aio_context_notifier(BdrvAioNotifier
*ban
)
7167 QLIST_REMOVE(ban
, list
);
7171 static void bdrv_detach_aio_context(BlockDriverState
*bs
)
7173 BdrvAioNotifier
*baf
, *baf_tmp
;
7175 assert(!bs
->walking_aio_notifiers
);
7176 bs
->walking_aio_notifiers
= true;
7177 QLIST_FOREACH_SAFE(baf
, &bs
->aio_notifiers
, list
, baf_tmp
) {
7179 bdrv_do_remove_aio_context_notifier(baf
);
7181 baf
->detach_aio_context(baf
->opaque
);
7184 /* Never mind iterating again to check for ->deleted. bdrv_close() will
7185 * remove remaining aio notifiers if we aren't called again.
7187 bs
->walking_aio_notifiers
= false;
7189 if (bs
->drv
&& bs
->drv
->bdrv_detach_aio_context
) {
7190 bs
->drv
->bdrv_detach_aio_context(bs
);
7193 if (bs
->quiesce_counter
) {
7194 aio_enable_external(bs
->aio_context
);
7196 bs
->aio_context
= NULL
;
7199 static void bdrv_attach_aio_context(BlockDriverState
*bs
,
7200 AioContext
*new_context
)
7202 BdrvAioNotifier
*ban
, *ban_tmp
;
7204 if (bs
->quiesce_counter
) {
7205 aio_disable_external(new_context
);
7208 bs
->aio_context
= new_context
;
7210 if (bs
->drv
&& bs
->drv
->bdrv_attach_aio_context
) {
7211 bs
->drv
->bdrv_attach_aio_context(bs
, new_context
);
7214 assert(!bs
->walking_aio_notifiers
);
7215 bs
->walking_aio_notifiers
= true;
7216 QLIST_FOREACH_SAFE(ban
, &bs
->aio_notifiers
, list
, ban_tmp
) {
7218 bdrv_do_remove_aio_context_notifier(ban
);
7220 ban
->attached_aio_context(new_context
, ban
->opaque
);
7223 bs
->walking_aio_notifiers
= false;
7227 * Changes the AioContext used for fd handlers, timers, and BHs by this
7228 * BlockDriverState and all its children and parents.
7230 * Must be called from the main AioContext.
7232 * The caller must own the AioContext lock for the old AioContext of bs, but it
7233 * must not own the AioContext lock for new_context (unless new_context is the
7234 * same as the current context of bs).
7236 * @ignore will accumulate all visited BdrvChild object. The caller is
7237 * responsible for freeing the list afterwards.
7239 void bdrv_set_aio_context_ignore(BlockDriverState
*bs
,
7240 AioContext
*new_context
, GSList
**ignore
)
7242 AioContext
*old_context
= bdrv_get_aio_context(bs
);
7243 GSList
*children_to_process
= NULL
;
7244 GSList
*parents_to_process
= NULL
;
7246 BdrvChild
*child
, *parent
;
7248 g_assert(qemu_get_current_aio_context() == qemu_get_aio_context());
7250 if (old_context
== new_context
) {
7254 bdrv_drained_begin(bs
);
7256 QLIST_FOREACH(child
, &bs
->children
, next
) {
7257 if (g_slist_find(*ignore
, child
)) {
7260 *ignore
= g_slist_prepend(*ignore
, child
);
7261 children_to_process
= g_slist_prepend(children_to_process
, child
);
7264 QLIST_FOREACH(parent
, &bs
->parents
, next_parent
) {
7265 if (g_slist_find(*ignore
, parent
)) {
7268 *ignore
= g_slist_prepend(*ignore
, parent
);
7269 parents_to_process
= g_slist_prepend(parents_to_process
, parent
);
7272 for (entry
= children_to_process
;
7274 entry
= g_slist_next(entry
)) {
7275 child
= entry
->data
;
7276 bdrv_set_aio_context_ignore(child
->bs
, new_context
, ignore
);
7278 g_slist_free(children_to_process
);
7280 for (entry
= parents_to_process
;
7282 entry
= g_slist_next(entry
)) {
7283 parent
= entry
->data
;
7284 assert(parent
->klass
->set_aio_ctx
);
7285 parent
->klass
->set_aio_ctx(parent
, new_context
, ignore
);
7287 g_slist_free(parents_to_process
);
7289 bdrv_detach_aio_context(bs
);
7291 /* Acquire the new context, if necessary */
7292 if (qemu_get_aio_context() != new_context
) {
7293 aio_context_acquire(new_context
);
7296 bdrv_attach_aio_context(bs
, new_context
);
7299 * If this function was recursively called from
7300 * bdrv_set_aio_context_ignore(), there may be nodes in the
7301 * subtree that have not yet been moved to the new AioContext.
7302 * Release the old one so bdrv_drained_end() can poll them.
7304 if (qemu_get_aio_context() != old_context
) {
7305 aio_context_release(old_context
);
7308 bdrv_drained_end(bs
);
7310 if (qemu_get_aio_context() != old_context
) {
7311 aio_context_acquire(old_context
);
7313 if (qemu_get_aio_context() != new_context
) {
7314 aio_context_release(new_context
);
7318 static bool bdrv_parent_can_set_aio_context(BdrvChild
*c
, AioContext
*ctx
,
7319 GSList
**ignore
, Error
**errp
)
7321 if (g_slist_find(*ignore
, c
)) {
7324 *ignore
= g_slist_prepend(*ignore
, c
);
7327 * A BdrvChildClass that doesn't handle AioContext changes cannot
7328 * tolerate any AioContext changes
7330 if (!c
->klass
->can_set_aio_ctx
) {
7331 char *user
= bdrv_child_user_desc(c
);
7332 error_setg(errp
, "Changing iothreads is not supported by %s", user
);
7336 if (!c
->klass
->can_set_aio_ctx(c
, ctx
, ignore
, errp
)) {
7337 assert(!errp
|| *errp
);
7343 bool bdrv_child_can_set_aio_context(BdrvChild
*c
, AioContext
*ctx
,
7344 GSList
**ignore
, Error
**errp
)
7346 GLOBAL_STATE_CODE();
7347 if (g_slist_find(*ignore
, c
)) {
7350 *ignore
= g_slist_prepend(*ignore
, c
);
7351 return bdrv_can_set_aio_context(c
->bs
, ctx
, ignore
, errp
);
7354 /* @ignore will accumulate all visited BdrvChild object. The caller is
7355 * responsible for freeing the list afterwards. */
7356 bool bdrv_can_set_aio_context(BlockDriverState
*bs
, AioContext
*ctx
,
7357 GSList
**ignore
, Error
**errp
)
7361 if (bdrv_get_aio_context(bs
) == ctx
) {
7365 GLOBAL_STATE_CODE();
7367 QLIST_FOREACH(c
, &bs
->parents
, next_parent
) {
7368 if (!bdrv_parent_can_set_aio_context(c
, ctx
, ignore
, errp
)) {
7372 QLIST_FOREACH(c
, &bs
->children
, next
) {
7373 if (!bdrv_child_can_set_aio_context(c
, ctx
, ignore
, errp
)) {
7381 int bdrv_child_try_set_aio_context(BlockDriverState
*bs
, AioContext
*ctx
,
7382 BdrvChild
*ignore_child
, Error
**errp
)
7387 GLOBAL_STATE_CODE();
7389 ignore
= ignore_child
? g_slist_prepend(NULL
, ignore_child
) : NULL
;
7390 ret
= bdrv_can_set_aio_context(bs
, ctx
, &ignore
, errp
);
7391 g_slist_free(ignore
);
7397 ignore
= ignore_child
? g_slist_prepend(NULL
, ignore_child
) : NULL
;
7398 bdrv_set_aio_context_ignore(bs
, ctx
, &ignore
);
7399 g_slist_free(ignore
);
7404 int bdrv_try_set_aio_context(BlockDriverState
*bs
, AioContext
*ctx
,
7407 GLOBAL_STATE_CODE();
7408 return bdrv_child_try_set_aio_context(bs
, ctx
, NULL
, errp
);
7411 void bdrv_add_aio_context_notifier(BlockDriverState
*bs
,
7412 void (*attached_aio_context
)(AioContext
*new_context
, void *opaque
),
7413 void (*detach_aio_context
)(void *opaque
), void *opaque
)
7415 BdrvAioNotifier
*ban
= g_new(BdrvAioNotifier
, 1);
7416 *ban
= (BdrvAioNotifier
){
7417 .attached_aio_context
= attached_aio_context
,
7418 .detach_aio_context
= detach_aio_context
,
7421 GLOBAL_STATE_CODE();
7423 QLIST_INSERT_HEAD(&bs
->aio_notifiers
, ban
, list
);
7426 void bdrv_remove_aio_context_notifier(BlockDriverState
*bs
,
7427 void (*attached_aio_context
)(AioContext
*,
7429 void (*detach_aio_context
)(void *),
7432 BdrvAioNotifier
*ban
, *ban_next
;
7433 GLOBAL_STATE_CODE();
7435 QLIST_FOREACH_SAFE(ban
, &bs
->aio_notifiers
, list
, ban_next
) {
7436 if (ban
->attached_aio_context
== attached_aio_context
&&
7437 ban
->detach_aio_context
== detach_aio_context
&&
7438 ban
->opaque
== opaque
&&
7439 ban
->deleted
== false)
7441 if (bs
->walking_aio_notifiers
) {
7442 ban
->deleted
= true;
7444 bdrv_do_remove_aio_context_notifier(ban
);
7453 int bdrv_amend_options(BlockDriverState
*bs
, QemuOpts
*opts
,
7454 BlockDriverAmendStatusCB
*status_cb
, void *cb_opaque
,
7458 GLOBAL_STATE_CODE();
7460 error_setg(errp
, "Node is ejected");
7463 if (!bs
->drv
->bdrv_amend_options
) {
7464 error_setg(errp
, "Block driver '%s' does not support option amendment",
7465 bs
->drv
->format_name
);
7468 return bs
->drv
->bdrv_amend_options(bs
, opts
, status_cb
,
7469 cb_opaque
, force
, errp
);
7473 * This function checks whether the given @to_replace is allowed to be
7474 * replaced by a node that always shows the same data as @bs. This is
7475 * used for example to verify whether the mirror job can replace
7476 * @to_replace by the target mirrored from @bs.
7477 * To be replaceable, @bs and @to_replace may either be guaranteed to
7478 * always show the same data (because they are only connected through
7479 * filters), or some driver may allow replacing one of its children
7480 * because it can guarantee that this child's data is not visible at
7481 * all (for example, for dissenting quorum children that have no other
7484 bool bdrv_recurse_can_replace(BlockDriverState
*bs
,
7485 BlockDriverState
*to_replace
)
7487 BlockDriverState
*filtered
;
7489 if (!bs
|| !bs
->drv
) {
7493 if (bs
== to_replace
) {
7497 /* See what the driver can do */
7498 if (bs
->drv
->bdrv_recurse_can_replace
) {
7499 return bs
->drv
->bdrv_recurse_can_replace(bs
, to_replace
);
7502 /* For filters without an own implementation, we can recurse on our own */
7503 filtered
= bdrv_filter_bs(bs
);
7505 return bdrv_recurse_can_replace(filtered
, to_replace
);
7513 * Check whether the given @node_name can be replaced by a node that
7514 * has the same data as @parent_bs. If so, return @node_name's BDS;
7517 * @node_name must be a (recursive) *child of @parent_bs (or this
7518 * function will return NULL).
7520 * The result (whether the node can be replaced or not) is only valid
7521 * for as long as no graph or permission changes occur.
7523 BlockDriverState
*check_to_replace_node(BlockDriverState
*parent_bs
,
7524 const char *node_name
, Error
**errp
)
7526 BlockDriverState
*to_replace_bs
= bdrv_find_node(node_name
);
7527 AioContext
*aio_context
;
7529 GLOBAL_STATE_CODE();
7531 if (!to_replace_bs
) {
7532 error_setg(errp
, "Failed to find node with node-name='%s'", node_name
);
7536 aio_context
= bdrv_get_aio_context(to_replace_bs
);
7537 aio_context_acquire(aio_context
);
7539 if (bdrv_op_is_blocked(to_replace_bs
, BLOCK_OP_TYPE_REPLACE
, errp
)) {
7540 to_replace_bs
= NULL
;
7544 /* We don't want arbitrary node of the BDS chain to be replaced only the top
7545 * most non filter in order to prevent data corruption.
7546 * Another benefit is that this tests exclude backing files which are
7547 * blocked by the backing blockers.
7549 if (!bdrv_recurse_can_replace(parent_bs
, to_replace_bs
)) {
7550 error_setg(errp
, "Cannot replace '%s' by a node mirrored from '%s', "
7551 "because it cannot be guaranteed that doing so would not "
7552 "lead to an abrupt change of visible data",
7553 node_name
, parent_bs
->node_name
);
7554 to_replace_bs
= NULL
;
7559 aio_context_release(aio_context
);
7560 return to_replace_bs
;
7564 * Iterates through the list of runtime option keys that are said to
7565 * be "strong" for a BDS. An option is called "strong" if it changes
7566 * a BDS's data. For example, the null block driver's "size" and
7567 * "read-zeroes" options are strong, but its "latency-ns" option is
7570 * If a key returned by this function ends with a dot, all options
7571 * starting with that prefix are strong.
7573 static const char *const *strong_options(BlockDriverState
*bs
,
7574 const char *const *curopt
)
7576 static const char *const global_options
[] = {
7577 "driver", "filename", NULL
7581 return &global_options
[0];
7585 if (curopt
== &global_options
[ARRAY_SIZE(global_options
) - 1] && bs
->drv
) {
7586 curopt
= bs
->drv
->strong_runtime_opts
;
7589 return (curopt
&& *curopt
) ? curopt
: NULL
;
7593 * Copies all strong runtime options from bs->options to the given
7594 * QDict. The set of strong option keys is determined by invoking
7597 * Returns true iff any strong option was present in bs->options (and
7598 * thus copied to the target QDict) with the exception of "filename"
7599 * and "driver". The caller is expected to use this value to decide
7600 * whether the existence of strong options prevents the generation of
7603 static bool append_strong_runtime_options(QDict
*d
, BlockDriverState
*bs
)
7605 bool found_any
= false;
7606 const char *const *option_name
= NULL
;
7612 while ((option_name
= strong_options(bs
, option_name
))) {
7613 bool option_given
= false;
7615 assert(strlen(*option_name
) > 0);
7616 if ((*option_name
)[strlen(*option_name
) - 1] != '.') {
7617 QObject
*entry
= qdict_get(bs
->options
, *option_name
);
7622 qdict_put_obj(d
, *option_name
, qobject_ref(entry
));
7623 option_given
= true;
7625 const QDictEntry
*entry
;
7626 for (entry
= qdict_first(bs
->options
); entry
;
7627 entry
= qdict_next(bs
->options
, entry
))
7629 if (strstart(qdict_entry_key(entry
), *option_name
, NULL
)) {
7630 qdict_put_obj(d
, qdict_entry_key(entry
),
7631 qobject_ref(qdict_entry_value(entry
)));
7632 option_given
= true;
7637 /* While "driver" and "filename" need to be included in a JSON filename,
7638 * their existence does not prohibit generation of a plain filename. */
7639 if (!found_any
&& option_given
&&
7640 strcmp(*option_name
, "driver") && strcmp(*option_name
, "filename"))
7646 if (!qdict_haskey(d
, "driver")) {
7647 /* Drivers created with bdrv_new_open_driver() may not have a
7648 * @driver option. Add it here. */
7649 qdict_put_str(d
, "driver", bs
->drv
->format_name
);
7655 /* Note: This function may return false positives; it may return true
7656 * even if opening the backing file specified by bs's image header
7657 * would result in exactly bs->backing. */
7658 static bool bdrv_backing_overridden(BlockDriverState
*bs
)
7661 return strcmp(bs
->auto_backing_file
,
7662 bs
->backing
->bs
->filename
);
7664 /* No backing BDS, so if the image header reports any backing
7665 * file, it must have been suppressed */
7666 return bs
->auto_backing_file
[0] != '\0';
7670 /* Updates the following BDS fields:
7671 * - exact_filename: A filename which may be used for opening a block device
7672 * which (mostly) equals the given BDS (even without any
7673 * other options; so reading and writing must return the same
7674 * results, but caching etc. may be different)
7675 * - full_open_options: Options which, when given when opening a block device
7676 * (without a filename), result in a BDS (mostly)
7677 * equalling the given one
7678 * - filename: If exact_filename is set, it is copied here. Otherwise,
7679 * full_open_options is converted to a JSON object, prefixed with
7680 * "json:" (for use through the JSON pseudo protocol) and put here.
7682 void bdrv_refresh_filename(BlockDriverState
*bs
)
7684 BlockDriver
*drv
= bs
->drv
;
7686 BlockDriverState
*primary_child_bs
;
7688 bool backing_overridden
;
7689 bool generate_json_filename
; /* Whether our default implementation should
7690 fill exact_filename (false) or not (true) */
7692 GLOBAL_STATE_CODE();
7698 /* This BDS's file name may depend on any of its children's file names, so
7699 * refresh those first */
7700 QLIST_FOREACH(child
, &bs
->children
, next
) {
7701 bdrv_refresh_filename(child
->bs
);
7705 /* For implicit nodes, just copy everything from the single child */
7706 child
= QLIST_FIRST(&bs
->children
);
7707 assert(QLIST_NEXT(child
, next
) == NULL
);
7709 pstrcpy(bs
->exact_filename
, sizeof(bs
->exact_filename
),
7710 child
->bs
->exact_filename
);
7711 pstrcpy(bs
->filename
, sizeof(bs
->filename
), child
->bs
->filename
);
7713 qobject_unref(bs
->full_open_options
);
7714 bs
->full_open_options
= qobject_ref(child
->bs
->full_open_options
);
7719 backing_overridden
= bdrv_backing_overridden(bs
);
7721 if (bs
->open_flags
& BDRV_O_NO_IO
) {
7722 /* Without I/O, the backing file does not change anything.
7723 * Therefore, in such a case (primarily qemu-img), we can
7724 * pretend the backing file has not been overridden even if
7725 * it technically has been. */
7726 backing_overridden
= false;
7729 /* Gather the options QDict */
7731 generate_json_filename
= append_strong_runtime_options(opts
, bs
);
7732 generate_json_filename
|= backing_overridden
;
7734 if (drv
->bdrv_gather_child_options
) {
7735 /* Some block drivers may not want to present all of their children's
7736 * options, or name them differently from BdrvChild.name */
7737 drv
->bdrv_gather_child_options(bs
, opts
, backing_overridden
);
7739 QLIST_FOREACH(child
, &bs
->children
, next
) {
7740 if (child
== bs
->backing
&& !backing_overridden
) {
7741 /* We can skip the backing BDS if it has not been overridden */
7745 qdict_put(opts
, child
->name
,
7746 qobject_ref(child
->bs
->full_open_options
));
7749 if (backing_overridden
&& !bs
->backing
) {
7750 /* Force no backing file */
7751 qdict_put_null(opts
, "backing");
7755 qobject_unref(bs
->full_open_options
);
7756 bs
->full_open_options
= opts
;
7758 primary_child_bs
= bdrv_primary_bs(bs
);
7760 if (drv
->bdrv_refresh_filename
) {
7761 /* Obsolete information is of no use here, so drop the old file name
7762 * information before refreshing it */
7763 bs
->exact_filename
[0] = '\0';
7765 drv
->bdrv_refresh_filename(bs
);
7766 } else if (primary_child_bs
) {
7768 * Try to reconstruct valid information from the underlying
7769 * file -- this only works for format nodes (filter nodes
7770 * cannot be probed and as such must be selected by the user
7771 * either through an options dict, or through a special
7772 * filename which the filter driver must construct in its
7773 * .bdrv_refresh_filename() implementation).
7776 bs
->exact_filename
[0] = '\0';
7779 * We can use the underlying file's filename if:
7780 * - it has a filename,
7781 * - the current BDS is not a filter,
7782 * - the file is a protocol BDS, and
7783 * - opening that file (as this BDS's format) will automatically create
7784 * the BDS tree we have right now, that is:
7785 * - the user did not significantly change this BDS's behavior with
7786 * some explicit (strong) options
7787 * - no non-file child of this BDS has been overridden by the user
7788 * Both of these conditions are represented by generate_json_filename.
7790 if (primary_child_bs
->exact_filename
[0] &&
7791 primary_child_bs
->drv
->bdrv_file_open
&&
7792 !drv
->is_filter
&& !generate_json_filename
)
7794 strcpy(bs
->exact_filename
, primary_child_bs
->exact_filename
);
7798 if (bs
->exact_filename
[0]) {
7799 pstrcpy(bs
->filename
, sizeof(bs
->filename
), bs
->exact_filename
);
7801 GString
*json
= qobject_to_json(QOBJECT(bs
->full_open_options
));
7802 if (snprintf(bs
->filename
, sizeof(bs
->filename
), "json:%s",
7803 json
->str
) >= sizeof(bs
->filename
)) {
7804 /* Give user a hint if we truncated things. */
7805 strcpy(bs
->filename
+ sizeof(bs
->filename
) - 4, "...");
7807 g_string_free(json
, true);
7811 char *bdrv_dirname(BlockDriverState
*bs
, Error
**errp
)
7813 BlockDriver
*drv
= bs
->drv
;
7814 BlockDriverState
*child_bs
;
7816 GLOBAL_STATE_CODE();
7819 error_setg(errp
, "Node '%s' is ejected", bs
->node_name
);
7823 if (drv
->bdrv_dirname
) {
7824 return drv
->bdrv_dirname(bs
, errp
);
7827 child_bs
= bdrv_primary_bs(bs
);
7829 return bdrv_dirname(child_bs
, errp
);
7832 bdrv_refresh_filename(bs
);
7833 if (bs
->exact_filename
[0] != '\0') {
7834 return path_combine(bs
->exact_filename
, "");
7837 error_setg(errp
, "Cannot generate a base directory for %s nodes",
7843 * Hot add/remove a BDS's child. So the user can take a child offline when
7844 * it is broken and take a new child online
7846 void bdrv_add_child(BlockDriverState
*parent_bs
, BlockDriverState
*child_bs
,
7849 GLOBAL_STATE_CODE();
7850 if (!parent_bs
->drv
|| !parent_bs
->drv
->bdrv_add_child
) {
7851 error_setg(errp
, "The node %s does not support adding a child",
7852 bdrv_get_device_or_node_name(parent_bs
));
7856 if (!QLIST_EMPTY(&child_bs
->parents
)) {
7857 error_setg(errp
, "The node %s already has a parent",
7858 child_bs
->node_name
);
7862 parent_bs
->drv
->bdrv_add_child(parent_bs
, child_bs
, errp
);
7865 void bdrv_del_child(BlockDriverState
*parent_bs
, BdrvChild
*child
, Error
**errp
)
7869 GLOBAL_STATE_CODE();
7870 if (!parent_bs
->drv
|| !parent_bs
->drv
->bdrv_del_child
) {
7871 error_setg(errp
, "The node %s does not support removing a child",
7872 bdrv_get_device_or_node_name(parent_bs
));
7876 QLIST_FOREACH(tmp
, &parent_bs
->children
, next
) {
7883 error_setg(errp
, "The node %s does not have a child named %s",
7884 bdrv_get_device_or_node_name(parent_bs
),
7885 bdrv_get_device_or_node_name(child
->bs
));
7889 parent_bs
->drv
->bdrv_del_child(parent_bs
, child
, errp
);
7892 int bdrv_make_empty(BdrvChild
*c
, Error
**errp
)
7894 BlockDriver
*drv
= c
->bs
->drv
;
7897 GLOBAL_STATE_CODE();
7898 assert(c
->perm
& (BLK_PERM_WRITE
| BLK_PERM_WRITE_UNCHANGED
));
7900 if (!drv
->bdrv_make_empty
) {
7901 error_setg(errp
, "%s does not support emptying nodes",
7906 ret
= drv
->bdrv_make_empty(c
->bs
);
7908 error_setg_errno(errp
, -ret
, "Failed to empty %s",
7917 * Return the child that @bs acts as an overlay for, and from which data may be
7918 * copied in COW or COR operations. Usually this is the backing file.
7920 BdrvChild
*bdrv_cow_child(BlockDriverState
*bs
)
7922 if (!bs
|| !bs
->drv
) {
7926 if (bs
->drv
->is_filter
) {
7934 assert(bs
->backing
->role
& BDRV_CHILD_COW
);
7939 * If @bs acts as a filter for exactly one of its children, return
7942 BdrvChild
*bdrv_filter_child(BlockDriverState
*bs
)
7946 if (!bs
|| !bs
->drv
) {
7950 if (!bs
->drv
->is_filter
) {
7954 /* Only one of @backing or @file may be used */
7955 assert(!(bs
->backing
&& bs
->file
));
7957 c
= bs
->backing
?: bs
->file
;
7962 assert(c
->role
& BDRV_CHILD_FILTERED
);
7967 * Return either the result of bdrv_cow_child() or bdrv_filter_child(),
7968 * whichever is non-NULL.
7970 * Return NULL if both are NULL.
7972 BdrvChild
*bdrv_filter_or_cow_child(BlockDriverState
*bs
)
7974 BdrvChild
*cow_child
= bdrv_cow_child(bs
);
7975 BdrvChild
*filter_child
= bdrv_filter_child(bs
);
7977 /* Filter nodes cannot have COW backing files */
7978 assert(!(cow_child
&& filter_child
));
7980 return cow_child
?: filter_child
;
7984 * Return the primary child of this node: For filters, that is the
7985 * filtered child. For other nodes, that is usually the child storing
7987 * (A generally more helpful description is that this is (usually) the
7988 * child that has the same filename as @bs.)
7990 * Drivers do not necessarily have a primary child; for example quorum
7993 BdrvChild
*bdrv_primary_child(BlockDriverState
*bs
)
7995 BdrvChild
*c
, *found
= NULL
;
7997 QLIST_FOREACH(c
, &bs
->children
, next
) {
7998 if (c
->role
& BDRV_CHILD_PRIMARY
) {
8007 static BlockDriverState
*bdrv_do_skip_filters(BlockDriverState
*bs
,
8008 bool stop_on_explicit_filter
)
8016 while (!(stop_on_explicit_filter
&& !bs
->implicit
)) {
8017 c
= bdrv_filter_child(bs
);
8020 * A filter that is embedded in a working block graph must
8021 * have a child. Assert this here so this function does
8022 * not return a filter node that is not expected by the
8025 assert(!bs
->drv
|| !bs
->drv
->is_filter
);
8031 * Note that this treats nodes with bs->drv == NULL as not being
8032 * filters (bs->drv == NULL should be replaced by something else
8034 * The advantage of this behavior is that this function will thus
8035 * always return a non-NULL value (given a non-NULL @bs).
8042 * Return the first BDS that has not been added implicitly or that
8043 * does not have a filtered child down the chain starting from @bs
8044 * (including @bs itself).
8046 BlockDriverState
*bdrv_skip_implicit_filters(BlockDriverState
*bs
)
8048 return bdrv_do_skip_filters(bs
, true);
8052 * Return the first BDS that does not have a filtered child down the
8053 * chain starting from @bs (including @bs itself).
8055 BlockDriverState
*bdrv_skip_filters(BlockDriverState
*bs
)
8057 return bdrv_do_skip_filters(bs
, false);
8061 * For a backing chain, return the first non-filter backing image of
8062 * the first non-filter image.
8064 BlockDriverState
*bdrv_backing_chain_next(BlockDriverState
*bs
)
8066 return bdrv_skip_filters(bdrv_cow_bs(bdrv_skip_filters(bs
)));
8070 * Check whether [offset, offset + bytes) overlaps with the cached
8071 * block-status data region.
8073 * If so, and @pnum is not NULL, set *pnum to `bsc.data_end - offset`,
8074 * which is what bdrv_bsc_is_data()'s interface needs.
8075 * Otherwise, *pnum is not touched.
8077 static bool bdrv_bsc_range_overlaps_locked(BlockDriverState
*bs
,
8078 int64_t offset
, int64_t bytes
,
8081 BdrvBlockStatusCache
*bsc
= qatomic_rcu_read(&bs
->block_status_cache
);
8085 qatomic_read(&bsc
->valid
) &&
8086 ranges_overlap(offset
, bytes
, bsc
->data_start
,
8087 bsc
->data_end
- bsc
->data_start
);
8089 if (overlaps
&& pnum
) {
8090 *pnum
= bsc
->data_end
- offset
;
8097 * See block_int.h for this function's documentation.
8099 bool bdrv_bsc_is_data(BlockDriverState
*bs
, int64_t offset
, int64_t *pnum
)
8101 RCU_READ_LOCK_GUARD();
8103 return bdrv_bsc_range_overlaps_locked(bs
, offset
, 1, pnum
);
8107 * See block_int.h for this function's documentation.
8109 void bdrv_bsc_invalidate_range(BlockDriverState
*bs
,
8110 int64_t offset
, int64_t bytes
)
8112 RCU_READ_LOCK_GUARD();
8114 if (bdrv_bsc_range_overlaps_locked(bs
, offset
, bytes
, NULL
)) {
8115 qatomic_set(&bs
->block_status_cache
->valid
, false);
8120 * See block_int.h for this function's documentation.
8122 void bdrv_bsc_fill(BlockDriverState
*bs
, int64_t offset
, int64_t bytes
)
8124 BdrvBlockStatusCache
*new_bsc
= g_new(BdrvBlockStatusCache
, 1);
8125 BdrvBlockStatusCache
*old_bsc
;
8127 *new_bsc
= (BdrvBlockStatusCache
) {
8129 .data_start
= offset
,
8130 .data_end
= offset
+ bytes
,
8133 QEMU_LOCK_GUARD(&bs
->bsc_modify_lock
);
8135 old_bsc
= qatomic_rcu_read(&bs
->block_status_cache
);
8136 qatomic_rcu_set(&bs
->block_status_cache
, new_bsc
);
8138 g_free_rcu(old_bsc
, rcu
);