2 * QEMU System Emulator block driver
4 * Copyright (c) 2003 Fabrice Bellard
6 * Permission is hereby granted, free of charge, to any person obtaining a copy
7 * of this software and associated documentation files (the "Software"), to deal
8 * in the Software without restriction, including without limitation the rights
9 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
10 * copies of the Software, and to permit persons to whom the Software is
11 * furnished to do so, subject to the following conditions:
13 * The above copyright notice and this permission notice shall be included in
14 * all copies or substantial portions of the Software.
16 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
19 * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
21 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
25 #include "qemu/osdep.h"
26 #include "block/trace.h"
27 #include "block/block_int.h"
28 #include "block/blockjob.h"
29 #include "block/fuse.h"
30 #include "block/nbd.h"
31 #include "block/qdict.h"
32 #include "qemu/error-report.h"
33 #include "block/module_block.h"
34 #include "qemu/main-loop.h"
35 #include "qemu/module.h"
36 #include "qapi/error.h"
37 #include "qapi/qmp/qdict.h"
38 #include "qapi/qmp/qjson.h"
39 #include "qapi/qmp/qnull.h"
40 #include "qapi/qmp/qstring.h"
41 #include "qapi/qobject-output-visitor.h"
42 #include "qapi/qapi-visit-block-core.h"
43 #include "sysemu/block-backend.h"
44 #include "sysemu/sysemu.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 "block/coroutines.h"
55 #include <sys/ioctl.h>
56 #include <sys/queue.h>
66 #define NOT_DONE 0x7fffffff /* used while emulated sync operation in progress */
68 static QTAILQ_HEAD(, BlockDriverState
) graph_bdrv_states
=
69 QTAILQ_HEAD_INITIALIZER(graph_bdrv_states
);
71 static QTAILQ_HEAD(, BlockDriverState
) all_bdrv_states
=
72 QTAILQ_HEAD_INITIALIZER(all_bdrv_states
);
74 static QLIST_HEAD(, BlockDriver
) bdrv_drivers
=
75 QLIST_HEAD_INITIALIZER(bdrv_drivers
);
77 static BlockDriverState
*bdrv_open_inherit(const char *filename
,
78 const char *reference
,
79 QDict
*options
, int flags
,
80 BlockDriverState
*parent
,
81 const BdrvChildClass
*child_class
,
82 BdrvChildRole child_role
,
85 /* If non-zero, use only whitelisted block drivers */
86 static int use_bdrv_whitelist
;
89 static int is_windows_drive_prefix(const char *filename
)
91 return (((filename
[0] >= 'a' && filename
[0] <= 'z') ||
92 (filename
[0] >= 'A' && filename
[0] <= 'Z')) &&
96 int is_windows_drive(const char *filename
)
98 if (is_windows_drive_prefix(filename
) &&
101 if (strstart(filename
, "\\\\.\\", NULL
) ||
102 strstart(filename
, "//./", NULL
))
108 size_t bdrv_opt_mem_align(BlockDriverState
*bs
)
110 if (!bs
|| !bs
->drv
) {
111 /* page size or 4k (hdd sector size) should be on the safe side */
112 return MAX(4096, qemu_real_host_page_size
);
115 return bs
->bl
.opt_mem_alignment
;
118 size_t bdrv_min_mem_align(BlockDriverState
*bs
)
120 if (!bs
|| !bs
->drv
) {
121 /* page size or 4k (hdd sector size) should be on the safe side */
122 return MAX(4096, qemu_real_host_page_size
);
125 return bs
->bl
.min_mem_alignment
;
128 /* check if the path starts with "<protocol>:" */
129 int path_has_protocol(const char *path
)
134 if (is_windows_drive(path
) ||
135 is_windows_drive_prefix(path
)) {
138 p
= path
+ strcspn(path
, ":/\\");
140 p
= path
+ strcspn(path
, ":/");
146 int path_is_absolute(const char *path
)
149 /* specific case for names like: "\\.\d:" */
150 if (is_windows_drive(path
) || is_windows_drive_prefix(path
)) {
153 return (*path
== '/' || *path
== '\\');
155 return (*path
== '/');
159 /* if filename is absolute, just return its duplicate. Otherwise, build a
160 path to it by considering it is relative to base_path. URL are
162 char *path_combine(const char *base_path
, const char *filename
)
164 const char *protocol_stripped
= NULL
;
169 if (path_is_absolute(filename
)) {
170 return g_strdup(filename
);
173 if (path_has_protocol(base_path
)) {
174 protocol_stripped
= strchr(base_path
, ':');
175 if (protocol_stripped
) {
179 p
= protocol_stripped
?: base_path
;
181 p1
= strrchr(base_path
, '/');
185 p2
= strrchr(base_path
, '\\');
186 if (!p1
|| p2
> p1
) {
201 result
= g_malloc(len
+ strlen(filename
) + 1);
202 memcpy(result
, base_path
, len
);
203 strcpy(result
+ len
, filename
);
209 * Helper function for bdrv_parse_filename() implementations to remove optional
210 * protocol prefixes (especially "file:") from a filename and for putting the
211 * stripped filename into the options QDict if there is such a prefix.
213 void bdrv_parse_filename_strip_prefix(const char *filename
, const char *prefix
,
216 if (strstart(filename
, prefix
, &filename
)) {
217 /* Stripping the explicit protocol prefix may result in a protocol
218 * prefix being (wrongly) detected (if the filename contains a colon) */
219 if (path_has_protocol(filename
)) {
220 GString
*fat_filename
;
222 /* This means there is some colon before the first slash; therefore,
223 * this cannot be an absolute path */
224 assert(!path_is_absolute(filename
));
226 /* And we can thus fix the protocol detection issue by prefixing it
228 fat_filename
= g_string_new("./");
229 g_string_append(fat_filename
, filename
);
231 assert(!path_has_protocol(fat_filename
->str
));
233 qdict_put(options
, "filename",
234 qstring_from_gstring(fat_filename
));
236 /* If no protocol prefix was detected, we can use the shortened
238 qdict_put_str(options
, "filename", filename
);
244 /* Returns whether the image file is opened as read-only. Note that this can
245 * return false and writing to the image file is still not possible because the
246 * image is inactivated. */
247 bool bdrv_is_read_only(BlockDriverState
*bs
)
249 return bs
->read_only
;
252 int bdrv_can_set_read_only(BlockDriverState
*bs
, bool read_only
,
253 bool ignore_allow_rdw
, Error
**errp
)
255 /* Do not set read_only if copy_on_read is enabled */
256 if (bs
->copy_on_read
&& read_only
) {
257 error_setg(errp
, "Can't set node '%s' to r/o with copy-on-read enabled",
258 bdrv_get_device_or_node_name(bs
));
262 /* Do not clear read_only if it is prohibited */
263 if (!read_only
&& !(bs
->open_flags
& BDRV_O_ALLOW_RDWR
) &&
266 error_setg(errp
, "Node '%s' is read only",
267 bdrv_get_device_or_node_name(bs
));
275 * Called by a driver that can only provide a read-only image.
277 * Returns 0 if the node is already read-only or it could switch the node to
278 * read-only because BDRV_O_AUTO_RDONLY is set.
280 * Returns -EACCES if the node is read-write and BDRV_O_AUTO_RDONLY is not set
281 * or bdrv_can_set_read_only() forbids making the node read-only. If @errmsg
282 * is not NULL, it is used as the error message for the Error object.
284 int bdrv_apply_auto_read_only(BlockDriverState
*bs
, const char *errmsg
,
289 if (!(bs
->open_flags
& BDRV_O_RDWR
)) {
292 if (!(bs
->open_flags
& BDRV_O_AUTO_RDONLY
)) {
296 ret
= bdrv_can_set_read_only(bs
, true, false, NULL
);
301 bs
->read_only
= true;
302 bs
->open_flags
&= ~BDRV_O_RDWR
;
307 error_setg(errp
, "%s", errmsg
?: "Image is read-only");
312 * If @backing is empty, this function returns NULL without setting
313 * @errp. In all other cases, NULL will only be returned with @errp
316 * Therefore, a return value of NULL without @errp set means that
317 * there is no backing file; if @errp is set, there is one but its
318 * absolute filename cannot be generated.
320 char *bdrv_get_full_backing_filename_from_filename(const char *backed
,
324 if (backing
[0] == '\0') {
326 } else if (path_has_protocol(backing
) || path_is_absolute(backing
)) {
327 return g_strdup(backing
);
328 } else if (backed
[0] == '\0' || strstart(backed
, "json:", NULL
)) {
329 error_setg(errp
, "Cannot use relative backing file names for '%s'",
333 return path_combine(backed
, backing
);
338 * If @filename is empty or NULL, this function returns NULL without
339 * setting @errp. In all other cases, NULL will only be returned with
342 static char *bdrv_make_absolute_filename(BlockDriverState
*relative_to
,
343 const char *filename
, Error
**errp
)
345 char *dir
, *full_name
;
347 if (!filename
|| filename
[0] == '\0') {
349 } else if (path_has_protocol(filename
) || path_is_absolute(filename
)) {
350 return g_strdup(filename
);
353 dir
= bdrv_dirname(relative_to
, errp
);
358 full_name
= g_strconcat(dir
, filename
, NULL
);
363 char *bdrv_get_full_backing_filename(BlockDriverState
*bs
, Error
**errp
)
365 return bdrv_make_absolute_filename(bs
, bs
->backing_file
, errp
);
368 void bdrv_register(BlockDriver
*bdrv
)
370 assert(bdrv
->format_name
);
371 QLIST_INSERT_HEAD(&bdrv_drivers
, bdrv
, list
);
374 BlockDriverState
*bdrv_new(void)
376 BlockDriverState
*bs
;
379 bs
= g_new0(BlockDriverState
, 1);
380 QLIST_INIT(&bs
->dirty_bitmaps
);
381 for (i
= 0; i
< BLOCK_OP_TYPE_MAX
; i
++) {
382 QLIST_INIT(&bs
->op_blockers
[i
]);
384 notifier_with_return_list_init(&bs
->before_write_notifiers
);
385 qemu_co_mutex_init(&bs
->reqs_lock
);
386 qemu_mutex_init(&bs
->dirty_bitmap_mutex
);
388 bs
->aio_context
= qemu_get_aio_context();
390 qemu_co_queue_init(&bs
->flush_queue
);
392 for (i
= 0; i
< bdrv_drain_all_count
; i
++) {
393 bdrv_drained_begin(bs
);
396 QTAILQ_INSERT_TAIL(&all_bdrv_states
, bs
, bs_list
);
401 static BlockDriver
*bdrv_do_find_format(const char *format_name
)
405 QLIST_FOREACH(drv1
, &bdrv_drivers
, list
) {
406 if (!strcmp(drv1
->format_name
, format_name
)) {
414 BlockDriver
*bdrv_find_format(const char *format_name
)
419 drv1
= bdrv_do_find_format(format_name
);
424 /* The driver isn't registered, maybe we need to load a module */
425 for (i
= 0; i
< (int)ARRAY_SIZE(block_driver_modules
); ++i
) {
426 if (!strcmp(block_driver_modules
[i
].format_name
, format_name
)) {
427 block_module_load_one(block_driver_modules
[i
].library_name
);
432 return bdrv_do_find_format(format_name
);
435 static int bdrv_format_is_whitelisted(const char *format_name
, bool read_only
)
437 static const char *whitelist_rw
[] = {
438 CONFIG_BDRV_RW_WHITELIST
441 static const char *whitelist_ro
[] = {
442 CONFIG_BDRV_RO_WHITELIST
447 if (!whitelist_rw
[0] && !whitelist_ro
[0]) {
448 return 1; /* no whitelist, anything goes */
451 for (p
= whitelist_rw
; *p
; p
++) {
452 if (!strcmp(format_name
, *p
)) {
457 for (p
= whitelist_ro
; *p
; p
++) {
458 if (!strcmp(format_name
, *p
)) {
466 int bdrv_is_whitelisted(BlockDriver
*drv
, bool read_only
)
468 return bdrv_format_is_whitelisted(drv
->format_name
, read_only
);
471 bool bdrv_uses_whitelist(void)
473 return use_bdrv_whitelist
;
476 typedef struct CreateCo
{
484 static void coroutine_fn
bdrv_create_co_entry(void *opaque
)
486 Error
*local_err
= NULL
;
489 CreateCo
*cco
= opaque
;
492 ret
= cco
->drv
->bdrv_co_create_opts(cco
->drv
,
493 cco
->filename
, cco
->opts
, &local_err
);
494 error_propagate(&cco
->err
, local_err
);
498 int bdrv_create(BlockDriver
*drv
, const char* filename
,
499 QemuOpts
*opts
, Error
**errp
)
506 .filename
= g_strdup(filename
),
512 if (!drv
->bdrv_co_create_opts
) {
513 error_setg(errp
, "Driver '%s' does not support image creation", drv
->format_name
);
518 if (qemu_in_coroutine()) {
519 /* Fast-path if already in coroutine context */
520 bdrv_create_co_entry(&cco
);
522 co
= qemu_coroutine_create(bdrv_create_co_entry
, &cco
);
523 qemu_coroutine_enter(co
);
524 while (cco
.ret
== NOT_DONE
) {
525 aio_poll(qemu_get_aio_context(), true);
532 error_propagate(errp
, cco
.err
);
534 error_setg_errno(errp
, -ret
, "Could not create image");
539 g_free(cco
.filename
);
544 * Helper function for bdrv_create_file_fallback(): Resize @blk to at
545 * least the given @minimum_size.
547 * On success, return @blk's actual length.
548 * Otherwise, return -errno.
550 static int64_t create_file_fallback_truncate(BlockBackend
*blk
,
551 int64_t minimum_size
, Error
**errp
)
553 Error
*local_err
= NULL
;
557 ret
= blk_truncate(blk
, minimum_size
, false, PREALLOC_MODE_OFF
, 0,
559 if (ret
< 0 && ret
!= -ENOTSUP
) {
560 error_propagate(errp
, local_err
);
564 size
= blk_getlength(blk
);
566 error_free(local_err
);
567 error_setg_errno(errp
, -size
,
568 "Failed to inquire the new image file's length");
572 if (size
< minimum_size
) {
573 /* Need to grow the image, but we failed to do that */
574 error_propagate(errp
, local_err
);
578 error_free(local_err
);
585 * Helper function for bdrv_create_file_fallback(): Zero the first
586 * sector to remove any potentially pre-existing image header.
588 static int create_file_fallback_zero_first_sector(BlockBackend
*blk
,
589 int64_t current_size
,
592 int64_t bytes_to_clear
;
595 bytes_to_clear
= MIN(current_size
, BDRV_SECTOR_SIZE
);
596 if (bytes_to_clear
) {
597 ret
= blk_pwrite_zeroes(blk
, 0, bytes_to_clear
, BDRV_REQ_MAY_UNMAP
);
599 error_setg_errno(errp
, -ret
,
600 "Failed to clear the new image's first sector");
609 * Simple implementation of bdrv_co_create_opts for protocol drivers
610 * which only support creation via opening a file
611 * (usually existing raw storage device)
613 int coroutine_fn
bdrv_co_create_opts_simple(BlockDriver
*drv
,
614 const char *filename
,
622 PreallocMode prealloc
;
623 Error
*local_err
= NULL
;
626 size
= qemu_opt_get_size_del(opts
, BLOCK_OPT_SIZE
, 0);
627 buf
= qemu_opt_get_del(opts
, BLOCK_OPT_PREALLOC
);
628 prealloc
= qapi_enum_parse(&PreallocMode_lookup
, buf
,
629 PREALLOC_MODE_OFF
, &local_err
);
632 error_propagate(errp
, local_err
);
636 if (prealloc
!= PREALLOC_MODE_OFF
) {
637 error_setg(errp
, "Unsupported preallocation mode '%s'",
638 PreallocMode_str(prealloc
));
642 options
= qdict_new();
643 qdict_put_str(options
, "driver", drv
->format_name
);
645 blk
= blk_new_open(filename
, NULL
, options
,
646 BDRV_O_RDWR
| BDRV_O_RESIZE
, errp
);
648 error_prepend(errp
, "Protocol driver '%s' does not support image "
649 "creation, and opening the image failed: ",
654 size
= create_file_fallback_truncate(blk
, size
, errp
);
660 ret
= create_file_fallback_zero_first_sector(blk
, size
, errp
);
671 int bdrv_create_file(const char *filename
, QemuOpts
*opts
, Error
**errp
)
673 QemuOpts
*protocol_opts
;
678 drv
= bdrv_find_protocol(filename
, true, errp
);
683 if (!drv
->create_opts
) {
684 error_setg(errp
, "Driver '%s' does not support image creation",
690 * 'opts' contains a QemuOptsList with a combination of format and protocol
693 * The format properly removes its options, but the default values remain
694 * in 'opts->list'. So if the protocol has options with the same name
695 * (e.g. rbd has 'cluster_size' as qcow2), it will see the default values
696 * of the format, since for overlapping options, the format wins.
698 * To avoid this issue, lets convert QemuOpts to QDict, in this way we take
699 * only the set options, and then convert it back to QemuOpts, using the
700 * create_opts of the protocol. So the new QemuOpts, will contain only the
703 qdict
= qemu_opts_to_qdict(opts
, NULL
);
704 protocol_opts
= qemu_opts_from_qdict(drv
->create_opts
, qdict
, errp
);
705 if (protocol_opts
== NULL
) {
710 ret
= bdrv_create(drv
, filename
, protocol_opts
, errp
);
712 qemu_opts_del(protocol_opts
);
713 qobject_unref(qdict
);
717 int coroutine_fn
bdrv_co_delete_file(BlockDriverState
*bs
, Error
**errp
)
719 Error
*local_err
= NULL
;
725 error_setg(errp
, "Block node '%s' is not opened", bs
->filename
);
729 if (!bs
->drv
->bdrv_co_delete_file
) {
730 error_setg(errp
, "Driver '%s' does not support image deletion",
731 bs
->drv
->format_name
);
735 ret
= bs
->drv
->bdrv_co_delete_file(bs
, &local_err
);
737 error_propagate(errp
, local_err
);
743 void coroutine_fn
bdrv_co_delete_file_noerr(BlockDriverState
*bs
)
745 Error
*local_err
= NULL
;
752 ret
= bdrv_co_delete_file(bs
, &local_err
);
754 * ENOTSUP will happen if the block driver doesn't support
755 * the 'bdrv_co_delete_file' interface. This is a predictable
756 * scenario and shouldn't be reported back to the user.
758 if (ret
== -ENOTSUP
) {
759 error_free(local_err
);
760 } else if (ret
< 0) {
761 error_report_err(local_err
);
766 * Try to get @bs's logical and physical block size.
767 * On success, store them in @bsz struct and return 0.
768 * On failure return -errno.
769 * @bs must not be empty.
771 int bdrv_probe_blocksizes(BlockDriverState
*bs
, BlockSizes
*bsz
)
773 BlockDriver
*drv
= bs
->drv
;
774 BlockDriverState
*filtered
= bdrv_filter_bs(bs
);
776 if (drv
&& drv
->bdrv_probe_blocksizes
) {
777 return drv
->bdrv_probe_blocksizes(bs
, bsz
);
778 } else if (filtered
) {
779 return bdrv_probe_blocksizes(filtered
, bsz
);
786 * Try to get @bs's geometry (cyls, heads, sectors).
787 * On success, store them in @geo struct and return 0.
788 * On failure return -errno.
789 * @bs must not be empty.
791 int bdrv_probe_geometry(BlockDriverState
*bs
, HDGeometry
*geo
)
793 BlockDriver
*drv
= bs
->drv
;
794 BlockDriverState
*filtered
= bdrv_filter_bs(bs
);
796 if (drv
&& drv
->bdrv_probe_geometry
) {
797 return drv
->bdrv_probe_geometry(bs
, geo
);
798 } else if (filtered
) {
799 return bdrv_probe_geometry(filtered
, geo
);
806 * Create a uniquely-named empty temporary file.
807 * Return 0 upon success, otherwise a negative errno value.
809 int get_tmp_filename(char *filename
, int size
)
812 char temp_dir
[MAX_PATH
];
813 /* GetTempFileName requires that its output buffer (4th param)
814 have length MAX_PATH or greater. */
815 assert(size
>= MAX_PATH
);
816 return (GetTempPath(MAX_PATH
, temp_dir
)
817 && GetTempFileName(temp_dir
, "qem", 0, filename
)
818 ? 0 : -GetLastError());
822 tmpdir
= getenv("TMPDIR");
826 if (snprintf(filename
, size
, "%s/vl.XXXXXX", tmpdir
) >= size
) {
829 fd
= mkstemp(filename
);
833 if (close(fd
) != 0) {
842 * Detect host devices. By convention, /dev/cdrom[N] is always
843 * recognized as a host CDROM.
845 static BlockDriver
*find_hdev_driver(const char *filename
)
847 int score_max
= 0, score
;
848 BlockDriver
*drv
= NULL
, *d
;
850 QLIST_FOREACH(d
, &bdrv_drivers
, list
) {
851 if (d
->bdrv_probe_device
) {
852 score
= d
->bdrv_probe_device(filename
);
853 if (score
> score_max
) {
863 static BlockDriver
*bdrv_do_find_protocol(const char *protocol
)
867 QLIST_FOREACH(drv1
, &bdrv_drivers
, list
) {
868 if (drv1
->protocol_name
&& !strcmp(drv1
->protocol_name
, protocol
)) {
876 BlockDriver
*bdrv_find_protocol(const char *filename
,
877 bool allow_protocol_prefix
,
886 /* TODO Drivers without bdrv_file_open must be specified explicitly */
889 * XXX(hch): we really should not let host device detection
890 * override an explicit protocol specification, but moving this
891 * later breaks access to device names with colons in them.
892 * Thanks to the brain-dead persistent naming schemes on udev-
893 * based Linux systems those actually are quite common.
895 drv1
= find_hdev_driver(filename
);
900 if (!path_has_protocol(filename
) || !allow_protocol_prefix
) {
904 p
= strchr(filename
, ':');
907 if (len
> sizeof(protocol
) - 1)
908 len
= sizeof(protocol
) - 1;
909 memcpy(protocol
, filename
, len
);
910 protocol
[len
] = '\0';
912 drv1
= bdrv_do_find_protocol(protocol
);
917 for (i
= 0; i
< (int)ARRAY_SIZE(block_driver_modules
); ++i
) {
918 if (block_driver_modules
[i
].protocol_name
&&
919 !strcmp(block_driver_modules
[i
].protocol_name
, protocol
)) {
920 block_module_load_one(block_driver_modules
[i
].library_name
);
925 drv1
= bdrv_do_find_protocol(protocol
);
927 error_setg(errp
, "Unknown protocol '%s'", protocol
);
933 * Guess image format by probing its contents.
934 * This is not a good idea when your image is raw (CVE-2008-2004), but
935 * we do it anyway for backward compatibility.
937 * @buf contains the image's first @buf_size bytes.
938 * @buf_size is the buffer size in bytes (generally BLOCK_PROBE_BUF_SIZE,
939 * but can be smaller if the image file is smaller)
940 * @filename is its filename.
942 * For all block drivers, call the bdrv_probe() method to get its
944 * Return the first block driver with the highest probing score.
946 BlockDriver
*bdrv_probe_all(const uint8_t *buf
, int buf_size
,
947 const char *filename
)
949 int score_max
= 0, score
;
950 BlockDriver
*drv
= NULL
, *d
;
952 QLIST_FOREACH(d
, &bdrv_drivers
, list
) {
954 score
= d
->bdrv_probe(buf
, buf_size
, filename
);
955 if (score
> score_max
) {
965 static int find_image_format(BlockBackend
*file
, const char *filename
,
966 BlockDriver
**pdrv
, Error
**errp
)
969 uint8_t buf
[BLOCK_PROBE_BUF_SIZE
];
972 /* Return the raw BlockDriver * to scsi-generic devices or empty drives */
973 if (blk_is_sg(file
) || !blk_is_inserted(file
) || blk_getlength(file
) == 0) {
978 ret
= blk_pread(file
, 0, buf
, sizeof(buf
));
980 error_setg_errno(errp
, -ret
, "Could not read image for determining its "
986 drv
= bdrv_probe_all(buf
, ret
, filename
);
988 error_setg(errp
, "Could not determine image format: No compatible "
997 * Set the current 'total_sectors' value
998 * Return 0 on success, -errno on error.
1000 int refresh_total_sectors(BlockDriverState
*bs
, int64_t hint
)
1002 BlockDriver
*drv
= bs
->drv
;
1008 /* Do not attempt drv->bdrv_getlength() on scsi-generic devices */
1012 /* query actual device if possible, otherwise just trust the hint */
1013 if (drv
->bdrv_getlength
) {
1014 int64_t length
= drv
->bdrv_getlength(bs
);
1018 hint
= DIV_ROUND_UP(length
, BDRV_SECTOR_SIZE
);
1021 bs
->total_sectors
= hint
;
1023 if (bs
->total_sectors
* BDRV_SECTOR_SIZE
> BDRV_MAX_LENGTH
) {
1031 * Combines a QDict of new block driver @options with any missing options taken
1032 * from @old_options, so that leaving out an option defaults to its old value.
1034 static void bdrv_join_options(BlockDriverState
*bs
, QDict
*options
,
1037 if (bs
->drv
&& bs
->drv
->bdrv_join_options
) {
1038 bs
->drv
->bdrv_join_options(options
, old_options
);
1040 qdict_join(options
, old_options
, false);
1044 static BlockdevDetectZeroesOptions
bdrv_parse_detect_zeroes(QemuOpts
*opts
,
1048 Error
*local_err
= NULL
;
1049 char *value
= qemu_opt_get_del(opts
, "detect-zeroes");
1050 BlockdevDetectZeroesOptions detect_zeroes
=
1051 qapi_enum_parse(&BlockdevDetectZeroesOptions_lookup
, value
,
1052 BLOCKDEV_DETECT_ZEROES_OPTIONS_OFF
, &local_err
);
1055 error_propagate(errp
, local_err
);
1056 return detect_zeroes
;
1059 if (detect_zeroes
== BLOCKDEV_DETECT_ZEROES_OPTIONS_UNMAP
&&
1060 !(open_flags
& BDRV_O_UNMAP
))
1062 error_setg(errp
, "setting detect-zeroes to unmap is not allowed "
1063 "without setting discard operation to unmap");
1066 return detect_zeroes
;
1070 * Set open flags for aio engine
1072 * Return 0 on success, -1 if the engine specified is invalid
1074 int bdrv_parse_aio(const char *mode
, int *flags
)
1076 if (!strcmp(mode
, "threads")) {
1077 /* do nothing, default */
1078 } else if (!strcmp(mode
, "native")) {
1079 *flags
|= BDRV_O_NATIVE_AIO
;
1080 #ifdef CONFIG_LINUX_IO_URING
1081 } else if (!strcmp(mode
, "io_uring")) {
1082 *flags
|= BDRV_O_IO_URING
;
1092 * Set open flags for a given discard mode
1094 * Return 0 on success, -1 if the discard mode was invalid.
1096 int bdrv_parse_discard_flags(const char *mode
, int *flags
)
1098 *flags
&= ~BDRV_O_UNMAP
;
1100 if (!strcmp(mode
, "off") || !strcmp(mode
, "ignore")) {
1102 } else if (!strcmp(mode
, "on") || !strcmp(mode
, "unmap")) {
1103 *flags
|= BDRV_O_UNMAP
;
1112 * Set open flags for a given cache mode
1114 * Return 0 on success, -1 if the cache mode was invalid.
1116 int bdrv_parse_cache_mode(const char *mode
, int *flags
, bool *writethrough
)
1118 *flags
&= ~BDRV_O_CACHE_MASK
;
1120 if (!strcmp(mode
, "off") || !strcmp(mode
, "none")) {
1121 *writethrough
= false;
1122 *flags
|= BDRV_O_NOCACHE
;
1123 } else if (!strcmp(mode
, "directsync")) {
1124 *writethrough
= true;
1125 *flags
|= BDRV_O_NOCACHE
;
1126 } else if (!strcmp(mode
, "writeback")) {
1127 *writethrough
= false;
1128 } else if (!strcmp(mode
, "unsafe")) {
1129 *writethrough
= false;
1130 *flags
|= BDRV_O_NO_FLUSH
;
1131 } else if (!strcmp(mode
, "writethrough")) {
1132 *writethrough
= true;
1140 static char *bdrv_child_get_parent_desc(BdrvChild
*c
)
1142 BlockDriverState
*parent
= c
->opaque
;
1143 return g_strdup(bdrv_get_device_or_node_name(parent
));
1146 static void bdrv_child_cb_drained_begin(BdrvChild
*child
)
1148 BlockDriverState
*bs
= child
->opaque
;
1149 bdrv_do_drained_begin_quiesce(bs
, NULL
, false);
1152 static bool bdrv_child_cb_drained_poll(BdrvChild
*child
)
1154 BlockDriverState
*bs
= child
->opaque
;
1155 return bdrv_drain_poll(bs
, false, NULL
, false);
1158 static void bdrv_child_cb_drained_end(BdrvChild
*child
,
1159 int *drained_end_counter
)
1161 BlockDriverState
*bs
= child
->opaque
;
1162 bdrv_drained_end_no_poll(bs
, drained_end_counter
);
1165 static int bdrv_child_cb_inactivate(BdrvChild
*child
)
1167 BlockDriverState
*bs
= child
->opaque
;
1168 assert(bs
->open_flags
& BDRV_O_INACTIVE
);
1172 static bool bdrv_child_cb_can_set_aio_ctx(BdrvChild
*child
, AioContext
*ctx
,
1173 GSList
**ignore
, Error
**errp
)
1175 BlockDriverState
*bs
= child
->opaque
;
1176 return bdrv_can_set_aio_context(bs
, ctx
, ignore
, errp
);
1179 static void bdrv_child_cb_set_aio_ctx(BdrvChild
*child
, AioContext
*ctx
,
1182 BlockDriverState
*bs
= child
->opaque
;
1183 return bdrv_set_aio_context_ignore(bs
, ctx
, ignore
);
1187 * Returns the options and flags that a temporary snapshot should get, based on
1188 * the originally requested flags (the originally requested image will have
1189 * flags like a backing file)
1191 static void bdrv_temp_snapshot_options(int *child_flags
, QDict
*child_options
,
1192 int parent_flags
, QDict
*parent_options
)
1194 *child_flags
= (parent_flags
& ~BDRV_O_SNAPSHOT
) | BDRV_O_TEMPORARY
;
1196 /* For temporary files, unconditional cache=unsafe is fine */
1197 qdict_set_default_str(child_options
, BDRV_OPT_CACHE_DIRECT
, "off");
1198 qdict_set_default_str(child_options
, BDRV_OPT_CACHE_NO_FLUSH
, "on");
1200 /* Copy the read-only and discard options from the parent */
1201 qdict_copy_default(child_options
, parent_options
, BDRV_OPT_READ_ONLY
);
1202 qdict_copy_default(child_options
, parent_options
, BDRV_OPT_DISCARD
);
1204 /* aio=native doesn't work for cache.direct=off, so disable it for the
1205 * temporary snapshot */
1206 *child_flags
&= ~BDRV_O_NATIVE_AIO
;
1209 static void bdrv_backing_attach(BdrvChild
*c
)
1211 BlockDriverState
*parent
= c
->opaque
;
1212 BlockDriverState
*backing_hd
= c
->bs
;
1214 assert(!parent
->backing_blocker
);
1215 error_setg(&parent
->backing_blocker
,
1216 "node is used as backing hd of '%s'",
1217 bdrv_get_device_or_node_name(parent
));
1219 bdrv_refresh_filename(backing_hd
);
1221 parent
->open_flags
&= ~BDRV_O_NO_BACKING
;
1223 bdrv_op_block_all(backing_hd
, parent
->backing_blocker
);
1224 /* Otherwise we won't be able to commit or stream */
1225 bdrv_op_unblock(backing_hd
, BLOCK_OP_TYPE_COMMIT_TARGET
,
1226 parent
->backing_blocker
);
1227 bdrv_op_unblock(backing_hd
, BLOCK_OP_TYPE_STREAM
,
1228 parent
->backing_blocker
);
1230 * We do backup in 3 ways:
1232 * The target bs is new opened, and the source is top BDS
1233 * 2. blockdev backup
1234 * Both the source and the target are top BDSes.
1235 * 3. internal backup(used for block replication)
1236 * Both the source and the target are backing file
1238 * In case 1 and 2, neither the source nor the target is the backing file.
1239 * In case 3, we will block the top BDS, so there is only one block job
1240 * for the top BDS and its backing chain.
1242 bdrv_op_unblock(backing_hd
, BLOCK_OP_TYPE_BACKUP_SOURCE
,
1243 parent
->backing_blocker
);
1244 bdrv_op_unblock(backing_hd
, BLOCK_OP_TYPE_BACKUP_TARGET
,
1245 parent
->backing_blocker
);
1248 static void bdrv_backing_detach(BdrvChild
*c
)
1250 BlockDriverState
*parent
= c
->opaque
;
1252 assert(parent
->backing_blocker
);
1253 bdrv_op_unblock_all(c
->bs
, parent
->backing_blocker
);
1254 error_free(parent
->backing_blocker
);
1255 parent
->backing_blocker
= NULL
;
1258 static int bdrv_backing_update_filename(BdrvChild
*c
, BlockDriverState
*base
,
1259 const char *filename
, Error
**errp
)
1261 BlockDriverState
*parent
= c
->opaque
;
1262 bool read_only
= bdrv_is_read_only(parent
);
1266 ret
= bdrv_reopen_set_read_only(parent
, false, errp
);
1272 ret
= bdrv_change_backing_file(parent
, filename
,
1273 base
->drv
? base
->drv
->format_name
: "",
1276 error_setg_errno(errp
, -ret
, "Could not update backing file link");
1280 bdrv_reopen_set_read_only(parent
, true, NULL
);
1287 * Returns the options and flags that a generic child of a BDS should
1288 * get, based on the given options and flags for the parent BDS.
1290 static void bdrv_inherited_options(BdrvChildRole role
, bool parent_is_format
,
1291 int *child_flags
, QDict
*child_options
,
1292 int parent_flags
, QDict
*parent_options
)
1294 int flags
= parent_flags
;
1297 * First, decide whether to set, clear, or leave BDRV_O_PROTOCOL.
1298 * Generally, the question to answer is: Should this child be
1299 * format-probed by default?
1303 * Pure and non-filtered data children of non-format nodes should
1304 * be probed by default (even when the node itself has BDRV_O_PROTOCOL
1305 * set). This only affects a very limited set of drivers (namely
1306 * quorum and blkverify when this comment was written).
1307 * Force-clear BDRV_O_PROTOCOL then.
1309 if (!parent_is_format
&&
1310 (role
& BDRV_CHILD_DATA
) &&
1311 !(role
& (BDRV_CHILD_METADATA
| BDRV_CHILD_FILTERED
)))
1313 flags
&= ~BDRV_O_PROTOCOL
;
1317 * All children of format nodes (except for COW children) and all
1318 * metadata children in general should never be format-probed.
1319 * Force-set BDRV_O_PROTOCOL then.
1321 if ((parent_is_format
&& !(role
& BDRV_CHILD_COW
)) ||
1322 (role
& BDRV_CHILD_METADATA
))
1324 flags
|= BDRV_O_PROTOCOL
;
1328 * If the cache mode isn't explicitly set, inherit direct and no-flush from
1331 qdict_copy_default(child_options
, parent_options
, BDRV_OPT_CACHE_DIRECT
);
1332 qdict_copy_default(child_options
, parent_options
, BDRV_OPT_CACHE_NO_FLUSH
);
1333 qdict_copy_default(child_options
, parent_options
, BDRV_OPT_FORCE_SHARE
);
1335 if (role
& BDRV_CHILD_COW
) {
1336 /* backing files are opened read-only by default */
1337 qdict_set_default_str(child_options
, BDRV_OPT_READ_ONLY
, "on");
1338 qdict_set_default_str(child_options
, BDRV_OPT_AUTO_READ_ONLY
, "off");
1340 /* Inherit the read-only option from the parent if it's not set */
1341 qdict_copy_default(child_options
, parent_options
, BDRV_OPT_READ_ONLY
);
1342 qdict_copy_default(child_options
, parent_options
,
1343 BDRV_OPT_AUTO_READ_ONLY
);
1347 * bdrv_co_pdiscard() respects unmap policy for the parent, so we
1348 * can default to enable it on lower layers regardless of the
1351 qdict_set_default_str(child_options
, BDRV_OPT_DISCARD
, "unmap");
1353 /* Clear flags that only apply to the top layer */
1354 flags
&= ~(BDRV_O_SNAPSHOT
| BDRV_O_NO_BACKING
| BDRV_O_COPY_ON_READ
);
1356 if (role
& BDRV_CHILD_METADATA
) {
1357 flags
&= ~BDRV_O_NO_IO
;
1359 if (role
& BDRV_CHILD_COW
) {
1360 flags
&= ~BDRV_O_TEMPORARY
;
1363 *child_flags
= flags
;
1366 static void bdrv_child_cb_attach(BdrvChild
*child
)
1368 BlockDriverState
*bs
= child
->opaque
;
1370 if (child
->role
& BDRV_CHILD_COW
) {
1371 bdrv_backing_attach(child
);
1374 bdrv_apply_subtree_drain(child
, bs
);
1377 static void bdrv_child_cb_detach(BdrvChild
*child
)
1379 BlockDriverState
*bs
= child
->opaque
;
1381 if (child
->role
& BDRV_CHILD_COW
) {
1382 bdrv_backing_detach(child
);
1385 bdrv_unapply_subtree_drain(child
, bs
);
1388 static int bdrv_child_cb_update_filename(BdrvChild
*c
, BlockDriverState
*base
,
1389 const char *filename
, Error
**errp
)
1391 if (c
->role
& BDRV_CHILD_COW
) {
1392 return bdrv_backing_update_filename(c
, base
, filename
, errp
);
1397 const BdrvChildClass child_of_bds
= {
1398 .parent_is_bds
= true,
1399 .get_parent_desc
= bdrv_child_get_parent_desc
,
1400 .inherit_options
= bdrv_inherited_options
,
1401 .drained_begin
= bdrv_child_cb_drained_begin
,
1402 .drained_poll
= bdrv_child_cb_drained_poll
,
1403 .drained_end
= bdrv_child_cb_drained_end
,
1404 .attach
= bdrv_child_cb_attach
,
1405 .detach
= bdrv_child_cb_detach
,
1406 .inactivate
= bdrv_child_cb_inactivate
,
1407 .can_set_aio_ctx
= bdrv_child_cb_can_set_aio_ctx
,
1408 .set_aio_ctx
= bdrv_child_cb_set_aio_ctx
,
1409 .update_filename
= bdrv_child_cb_update_filename
,
1412 static int bdrv_open_flags(BlockDriverState
*bs
, int flags
)
1414 int open_flags
= flags
;
1417 * Clear flags that are internal to the block layer before opening the
1420 open_flags
&= ~(BDRV_O_SNAPSHOT
| BDRV_O_NO_BACKING
| BDRV_O_PROTOCOL
);
1425 static void update_flags_from_options(int *flags
, QemuOpts
*opts
)
1427 *flags
&= ~(BDRV_O_CACHE_MASK
| BDRV_O_RDWR
| BDRV_O_AUTO_RDONLY
);
1429 if (qemu_opt_get_bool_del(opts
, BDRV_OPT_CACHE_NO_FLUSH
, false)) {
1430 *flags
|= BDRV_O_NO_FLUSH
;
1433 if (qemu_opt_get_bool_del(opts
, BDRV_OPT_CACHE_DIRECT
, false)) {
1434 *flags
|= BDRV_O_NOCACHE
;
1437 if (!qemu_opt_get_bool_del(opts
, BDRV_OPT_READ_ONLY
, false)) {
1438 *flags
|= BDRV_O_RDWR
;
1441 if (qemu_opt_get_bool_del(opts
, BDRV_OPT_AUTO_READ_ONLY
, false)) {
1442 *flags
|= BDRV_O_AUTO_RDONLY
;
1446 static void update_options_from_flags(QDict
*options
, int flags
)
1448 if (!qdict_haskey(options
, BDRV_OPT_CACHE_DIRECT
)) {
1449 qdict_put_bool(options
, BDRV_OPT_CACHE_DIRECT
, flags
& BDRV_O_NOCACHE
);
1451 if (!qdict_haskey(options
, BDRV_OPT_CACHE_NO_FLUSH
)) {
1452 qdict_put_bool(options
, BDRV_OPT_CACHE_NO_FLUSH
,
1453 flags
& BDRV_O_NO_FLUSH
);
1455 if (!qdict_haskey(options
, BDRV_OPT_READ_ONLY
)) {
1456 qdict_put_bool(options
, BDRV_OPT_READ_ONLY
, !(flags
& BDRV_O_RDWR
));
1458 if (!qdict_haskey(options
, BDRV_OPT_AUTO_READ_ONLY
)) {
1459 qdict_put_bool(options
, BDRV_OPT_AUTO_READ_ONLY
,
1460 flags
& BDRV_O_AUTO_RDONLY
);
1464 static void bdrv_assign_node_name(BlockDriverState
*bs
,
1465 const char *node_name
,
1468 char *gen_node_name
= NULL
;
1471 node_name
= gen_node_name
= id_generate(ID_BLOCK
);
1472 } else if (!id_wellformed(node_name
)) {
1474 * Check for empty string or invalid characters, but not if it is
1475 * generated (generated names use characters not available to the user)
1477 error_setg(errp
, "Invalid node-name: '%s'", node_name
);
1481 /* takes care of avoiding namespaces collisions */
1482 if (blk_by_name(node_name
)) {
1483 error_setg(errp
, "node-name=%s is conflicting with a device id",
1488 /* takes care of avoiding duplicates node names */
1489 if (bdrv_find_node(node_name
)) {
1490 error_setg(errp
, "Duplicate nodes with node-name='%s'", node_name
);
1494 /* Make sure that the node name isn't truncated */
1495 if (strlen(node_name
) >= sizeof(bs
->node_name
)) {
1496 error_setg(errp
, "Node name too long");
1500 /* copy node name into the bs and insert it into the graph list */
1501 pstrcpy(bs
->node_name
, sizeof(bs
->node_name
), node_name
);
1502 QTAILQ_INSERT_TAIL(&graph_bdrv_states
, bs
, node_list
);
1504 g_free(gen_node_name
);
1507 static int bdrv_open_driver(BlockDriverState
*bs
, BlockDriver
*drv
,
1508 const char *node_name
, QDict
*options
,
1509 int open_flags
, Error
**errp
)
1511 Error
*local_err
= NULL
;
1514 bdrv_assign_node_name(bs
, node_name
, &local_err
);
1516 error_propagate(errp
, local_err
);
1521 bs
->read_only
= !(bs
->open_flags
& BDRV_O_RDWR
);
1522 bs
->opaque
= g_malloc0(drv
->instance_size
);
1524 if (drv
->bdrv_file_open
) {
1525 assert(!drv
->bdrv_needs_filename
|| bs
->filename
[0]);
1526 ret
= drv
->bdrv_file_open(bs
, options
, open_flags
, &local_err
);
1527 } else if (drv
->bdrv_open
) {
1528 ret
= drv
->bdrv_open(bs
, options
, open_flags
, &local_err
);
1535 error_propagate(errp
, local_err
);
1536 } else if (bs
->filename
[0]) {
1537 error_setg_errno(errp
, -ret
, "Could not open '%s'", bs
->filename
);
1539 error_setg_errno(errp
, -ret
, "Could not open image");
1544 ret
= refresh_total_sectors(bs
, bs
->total_sectors
);
1546 error_setg_errno(errp
, -ret
, "Could not refresh total sector count");
1550 bdrv_refresh_limits(bs
, &local_err
);
1552 error_propagate(errp
, local_err
);
1556 assert(bdrv_opt_mem_align(bs
) != 0);
1557 assert(bdrv_min_mem_align(bs
) != 0);
1558 assert(is_power_of_2(bs
->bl
.request_alignment
));
1560 for (i
= 0; i
< bs
->quiesce_counter
; i
++) {
1561 if (drv
->bdrv_co_drain_begin
) {
1562 drv
->bdrv_co_drain_begin(bs
);
1569 if (bs
->file
!= NULL
) {
1570 bdrv_unref_child(bs
, bs
->file
);
1578 BlockDriverState
*bdrv_new_open_driver(BlockDriver
*drv
, const char *node_name
,
1579 int flags
, Error
**errp
)
1581 BlockDriverState
*bs
;
1585 bs
->open_flags
= flags
;
1586 bs
->explicit_options
= qdict_new();
1587 bs
->options
= qdict_new();
1590 update_options_from_flags(bs
->options
, flags
);
1592 ret
= bdrv_open_driver(bs
, drv
, node_name
, bs
->options
, flags
, errp
);
1594 qobject_unref(bs
->explicit_options
);
1595 bs
->explicit_options
= NULL
;
1596 qobject_unref(bs
->options
);
1605 QemuOptsList bdrv_runtime_opts
= {
1606 .name
= "bdrv_common",
1607 .head
= QTAILQ_HEAD_INITIALIZER(bdrv_runtime_opts
.head
),
1610 .name
= "node-name",
1611 .type
= QEMU_OPT_STRING
,
1612 .help
= "Node name of the block device node",
1616 .type
= QEMU_OPT_STRING
,
1617 .help
= "Block driver to use for the node",
1620 .name
= BDRV_OPT_CACHE_DIRECT
,
1621 .type
= QEMU_OPT_BOOL
,
1622 .help
= "Bypass software writeback cache on the host",
1625 .name
= BDRV_OPT_CACHE_NO_FLUSH
,
1626 .type
= QEMU_OPT_BOOL
,
1627 .help
= "Ignore flush requests",
1630 .name
= BDRV_OPT_READ_ONLY
,
1631 .type
= QEMU_OPT_BOOL
,
1632 .help
= "Node is opened in read-only mode",
1635 .name
= BDRV_OPT_AUTO_READ_ONLY
,
1636 .type
= QEMU_OPT_BOOL
,
1637 .help
= "Node can become read-only if opening read-write fails",
1640 .name
= "detect-zeroes",
1641 .type
= QEMU_OPT_STRING
,
1642 .help
= "try to optimize zero writes (off, on, unmap)",
1645 .name
= BDRV_OPT_DISCARD
,
1646 .type
= QEMU_OPT_STRING
,
1647 .help
= "discard operation (ignore/off, unmap/on)",
1650 .name
= BDRV_OPT_FORCE_SHARE
,
1651 .type
= QEMU_OPT_BOOL
,
1652 .help
= "always accept other writers (default: off)",
1654 { /* end of list */ }
1658 QemuOptsList bdrv_create_opts_simple
= {
1659 .name
= "simple-create-opts",
1660 .head
= QTAILQ_HEAD_INITIALIZER(bdrv_create_opts_simple
.head
),
1663 .name
= BLOCK_OPT_SIZE
,
1664 .type
= QEMU_OPT_SIZE
,
1665 .help
= "Virtual disk size"
1668 .name
= BLOCK_OPT_PREALLOC
,
1669 .type
= QEMU_OPT_STRING
,
1670 .help
= "Preallocation mode (allowed values: off)"
1672 { /* end of list */ }
1677 * Common part for opening disk images and files
1679 * Removes all processed options from *options.
1681 static int bdrv_open_common(BlockDriverState
*bs
, BlockBackend
*file
,
1682 QDict
*options
, Error
**errp
)
1684 int ret
, open_flags
;
1685 const char *filename
;
1686 const char *driver_name
= NULL
;
1687 const char *node_name
= NULL
;
1688 const char *discard
;
1691 Error
*local_err
= NULL
;
1693 assert(bs
->file
== NULL
);
1694 assert(options
!= NULL
&& bs
->options
!= options
);
1696 opts
= qemu_opts_create(&bdrv_runtime_opts
, NULL
, 0, &error_abort
);
1697 if (!qemu_opts_absorb_qdict(opts
, options
, errp
)) {
1702 update_flags_from_options(&bs
->open_flags
, opts
);
1704 driver_name
= qemu_opt_get(opts
, "driver");
1705 drv
= bdrv_find_format(driver_name
);
1706 assert(drv
!= NULL
);
1708 bs
->force_share
= qemu_opt_get_bool(opts
, BDRV_OPT_FORCE_SHARE
, false);
1710 if (bs
->force_share
&& (bs
->open_flags
& BDRV_O_RDWR
)) {
1712 BDRV_OPT_FORCE_SHARE
1713 "=on can only be used with read-only images");
1719 bdrv_refresh_filename(blk_bs(file
));
1720 filename
= blk_bs(file
)->filename
;
1723 * Caution: while qdict_get_try_str() is fine, getting
1724 * non-string types would require more care. When @options
1725 * come from -blockdev or blockdev_add, its members are typed
1726 * according to the QAPI schema, but when they come from
1727 * -drive, they're all QString.
1729 filename
= qdict_get_try_str(options
, "filename");
1732 if (drv
->bdrv_needs_filename
&& (!filename
|| !filename
[0])) {
1733 error_setg(errp
, "The '%s' block driver requires a file name",
1739 trace_bdrv_open_common(bs
, filename
?: "", bs
->open_flags
,
1742 bs
->read_only
= !(bs
->open_flags
& BDRV_O_RDWR
);
1744 if (use_bdrv_whitelist
&& !bdrv_is_whitelisted(drv
, bs
->read_only
)) {
1745 if (!bs
->read_only
&& bdrv_is_whitelisted(drv
, true)) {
1746 ret
= bdrv_apply_auto_read_only(bs
, NULL
, NULL
);
1752 !bs
->read_only
&& bdrv_is_whitelisted(drv
, true)
1753 ? "Driver '%s' can only be used for read-only devices"
1754 : "Driver '%s' is not whitelisted",
1760 /* bdrv_new() and bdrv_close() make it so */
1761 assert(qatomic_read(&bs
->copy_on_read
) == 0);
1763 if (bs
->open_flags
& BDRV_O_COPY_ON_READ
) {
1764 if (!bs
->read_only
) {
1765 bdrv_enable_copy_on_read(bs
);
1767 error_setg(errp
, "Can't use copy-on-read on read-only device");
1773 discard
= qemu_opt_get(opts
, BDRV_OPT_DISCARD
);
1774 if (discard
!= NULL
) {
1775 if (bdrv_parse_discard_flags(discard
, &bs
->open_flags
) != 0) {
1776 error_setg(errp
, "Invalid discard option");
1783 bdrv_parse_detect_zeroes(opts
, bs
->open_flags
, &local_err
);
1785 error_propagate(errp
, local_err
);
1790 if (filename
!= NULL
) {
1791 pstrcpy(bs
->filename
, sizeof(bs
->filename
), filename
);
1793 bs
->filename
[0] = '\0';
1795 pstrcpy(bs
->exact_filename
, sizeof(bs
->exact_filename
), bs
->filename
);
1797 /* Open the image, either directly or using a protocol */
1798 open_flags
= bdrv_open_flags(bs
, bs
->open_flags
);
1799 node_name
= qemu_opt_get(opts
, "node-name");
1801 assert(!drv
->bdrv_file_open
|| file
== NULL
);
1802 ret
= bdrv_open_driver(bs
, drv
, node_name
, options
, open_flags
, errp
);
1807 qemu_opts_del(opts
);
1811 qemu_opts_del(opts
);
1815 static GCC_FMT_ATTR(1, 0)
1816 QDict
*parse_json_filename(const char *filename
, Error
**errp
)
1818 QObject
*options_obj
;
1822 ret
= strstart(filename
, "json:", &filename
);
1825 options_obj
= qobject_from_json(filename
, errp
);
1827 error_prepend(errp
, "Could not parse the JSON options: ");
1831 options
= qobject_to(QDict
, options_obj
);
1833 qobject_unref(options_obj
);
1834 error_setg(errp
, "Invalid JSON object given");
1838 qdict_flatten(options
);
1843 static void parse_json_protocol(QDict
*options
, const char **pfilename
,
1846 QDict
*json_options
;
1847 Error
*local_err
= NULL
;
1849 /* Parse json: pseudo-protocol */
1850 if (!*pfilename
|| !g_str_has_prefix(*pfilename
, "json:")) {
1854 json_options
= parse_json_filename(*pfilename
, &local_err
);
1856 error_propagate(errp
, local_err
);
1860 /* Options given in the filename have lower priority than options
1861 * specified directly */
1862 qdict_join(options
, json_options
, false);
1863 qobject_unref(json_options
);
1868 * Fills in default options for opening images and converts the legacy
1869 * filename/flags pair to option QDict entries.
1870 * The BDRV_O_PROTOCOL flag in *flags will be set or cleared accordingly if a
1871 * block driver has been specified explicitly.
1873 static int bdrv_fill_options(QDict
**options
, const char *filename
,
1874 int *flags
, Error
**errp
)
1876 const char *drvname
;
1877 bool protocol
= *flags
& BDRV_O_PROTOCOL
;
1878 bool parse_filename
= false;
1879 BlockDriver
*drv
= NULL
;
1880 Error
*local_err
= NULL
;
1883 * Caution: while qdict_get_try_str() is fine, getting non-string
1884 * types would require more care. When @options come from
1885 * -blockdev or blockdev_add, its members are typed according to
1886 * the QAPI schema, but when they come from -drive, they're all
1889 drvname
= qdict_get_try_str(*options
, "driver");
1891 drv
= bdrv_find_format(drvname
);
1893 error_setg(errp
, "Unknown driver '%s'", drvname
);
1896 /* If the user has explicitly specified the driver, this choice should
1897 * override the BDRV_O_PROTOCOL flag */
1898 protocol
= drv
->bdrv_file_open
;
1902 *flags
|= BDRV_O_PROTOCOL
;
1904 *flags
&= ~BDRV_O_PROTOCOL
;
1907 /* Translate cache options from flags into options */
1908 update_options_from_flags(*options
, *flags
);
1910 /* Fetch the file name from the options QDict if necessary */
1911 if (protocol
&& filename
) {
1912 if (!qdict_haskey(*options
, "filename")) {
1913 qdict_put_str(*options
, "filename", filename
);
1914 parse_filename
= true;
1916 error_setg(errp
, "Can't specify 'file' and 'filename' options at "
1922 /* Find the right block driver */
1923 /* See cautionary note on accessing @options above */
1924 filename
= qdict_get_try_str(*options
, "filename");
1926 if (!drvname
&& protocol
) {
1928 drv
= bdrv_find_protocol(filename
, parse_filename
, errp
);
1933 drvname
= drv
->format_name
;
1934 qdict_put_str(*options
, "driver", drvname
);
1936 error_setg(errp
, "Must specify either driver or file");
1941 assert(drv
|| !protocol
);
1943 /* Driver-specific filename parsing */
1944 if (drv
&& drv
->bdrv_parse_filename
&& parse_filename
) {
1945 drv
->bdrv_parse_filename(filename
, *options
, &local_err
);
1947 error_propagate(errp
, local_err
);
1951 if (!drv
->bdrv_needs_filename
) {
1952 qdict_del(*options
, "filename");
1959 static int bdrv_child_check_perm(BdrvChild
*c
, BlockReopenQueue
*q
,
1960 uint64_t perm
, uint64_t shared
,
1961 GSList
*ignore_children
, Error
**errp
);
1962 static void bdrv_child_abort_perm_update(BdrvChild
*c
);
1963 static void bdrv_child_set_perm(BdrvChild
*c
);
1965 typedef struct BlockReopenQueueEntry
{
1968 BDRVReopenState state
;
1969 QTAILQ_ENTRY(BlockReopenQueueEntry
) entry
;
1970 } BlockReopenQueueEntry
;
1973 * Return the flags that @bs will have after the reopens in @q have
1974 * successfully completed. If @q is NULL (or @bs is not contained in @q),
1975 * return the current flags.
1977 static int bdrv_reopen_get_flags(BlockReopenQueue
*q
, BlockDriverState
*bs
)
1979 BlockReopenQueueEntry
*entry
;
1982 QTAILQ_FOREACH(entry
, q
, entry
) {
1983 if (entry
->state
.bs
== bs
) {
1984 return entry
->state
.flags
;
1989 return bs
->open_flags
;
1992 /* Returns whether the image file can be written to after the reopen queue @q
1993 * has been successfully applied, or right now if @q is NULL. */
1994 static bool bdrv_is_writable_after_reopen(BlockDriverState
*bs
,
1995 BlockReopenQueue
*q
)
1997 int flags
= bdrv_reopen_get_flags(q
, bs
);
1999 return (flags
& (BDRV_O_RDWR
| BDRV_O_INACTIVE
)) == BDRV_O_RDWR
;
2003 * Return whether the BDS can be written to. This is not necessarily
2004 * the same as !bdrv_is_read_only(bs), as inactivated images may not
2005 * be written to but do not count as read-only images.
2007 bool bdrv_is_writable(BlockDriverState
*bs
)
2009 return bdrv_is_writable_after_reopen(bs
, NULL
);
2012 static void bdrv_child_perm(BlockDriverState
*bs
, BlockDriverState
*child_bs
,
2013 BdrvChild
*c
, BdrvChildRole role
,
2014 BlockReopenQueue
*reopen_queue
,
2015 uint64_t parent_perm
, uint64_t parent_shared
,
2016 uint64_t *nperm
, uint64_t *nshared
)
2018 assert(bs
->drv
&& bs
->drv
->bdrv_child_perm
);
2019 bs
->drv
->bdrv_child_perm(bs
, c
, role
, reopen_queue
,
2020 parent_perm
, parent_shared
,
2022 /* TODO Take force_share from reopen_queue */
2023 if (child_bs
&& child_bs
->force_share
) {
2024 *nshared
= BLK_PERM_ALL
;
2029 * Check whether permissions on this node can be changed in a way that
2030 * @cumulative_perms and @cumulative_shared_perms are the new cumulative
2031 * permissions of all its parents. This involves checking whether all necessary
2032 * permission changes to child nodes can be performed.
2034 * A call to this function must always be followed by a call to bdrv_set_perm()
2035 * or bdrv_abort_perm_update().
2037 static int bdrv_check_perm(BlockDriverState
*bs
, BlockReopenQueue
*q
,
2038 uint64_t cumulative_perms
,
2039 uint64_t cumulative_shared_perms
,
2040 GSList
*ignore_children
, Error
**errp
)
2042 BlockDriver
*drv
= bs
->drv
;
2046 /* Write permissions never work with read-only images */
2047 if ((cumulative_perms
& (BLK_PERM_WRITE
| BLK_PERM_WRITE_UNCHANGED
)) &&
2048 !bdrv_is_writable_after_reopen(bs
, q
))
2050 if (!bdrv_is_writable_after_reopen(bs
, NULL
)) {
2051 error_setg(errp
, "Block node is read-only");
2053 uint64_t current_perms
, current_shared
;
2054 bdrv_get_cumulative_perm(bs
, ¤t_perms
, ¤t_shared
);
2055 if (current_perms
& (BLK_PERM_WRITE
| BLK_PERM_WRITE_UNCHANGED
)) {
2056 error_setg(errp
, "Cannot make block node read-only, there is "
2059 error_setg(errp
, "Cannot make block node read-only and create "
2068 * Unaligned requests will automatically be aligned to bl.request_alignment
2069 * and without RESIZE we can't extend requests to write to space beyond the
2070 * end of the image, so it's required that the image size is aligned.
2072 if ((cumulative_perms
& (BLK_PERM_WRITE
| BLK_PERM_WRITE_UNCHANGED
)) &&
2073 !(cumulative_perms
& BLK_PERM_RESIZE
))
2075 if ((bs
->total_sectors
* BDRV_SECTOR_SIZE
) % bs
->bl
.request_alignment
) {
2076 error_setg(errp
, "Cannot get 'write' permission without 'resize': "
2077 "Image size is not a multiple of request "
2083 /* Check this node */
2088 if (drv
->bdrv_check_perm
) {
2089 ret
= drv
->bdrv_check_perm(bs
, cumulative_perms
,
2090 cumulative_shared_perms
, errp
);
2096 /* Drivers that never have children can omit .bdrv_child_perm() */
2097 if (!drv
->bdrv_child_perm
) {
2098 assert(QLIST_EMPTY(&bs
->children
));
2102 /* Check all children */
2103 QLIST_FOREACH(c
, &bs
->children
, next
) {
2104 uint64_t cur_perm
, cur_shared
;
2106 bdrv_child_perm(bs
, c
->bs
, c
, c
->role
, q
,
2107 cumulative_perms
, cumulative_shared_perms
,
2108 &cur_perm
, &cur_shared
);
2109 ret
= bdrv_child_check_perm(c
, q
, cur_perm
, cur_shared
, ignore_children
,
2120 * Notifies drivers that after a previous bdrv_check_perm() call, the
2121 * permission update is not performed and any preparations made for it (e.g.
2122 * taken file locks) need to be undone.
2124 * This function recursively notifies all child nodes.
2126 static void bdrv_abort_perm_update(BlockDriverState
*bs
)
2128 BlockDriver
*drv
= bs
->drv
;
2135 if (drv
->bdrv_abort_perm_update
) {
2136 drv
->bdrv_abort_perm_update(bs
);
2139 QLIST_FOREACH(c
, &bs
->children
, next
) {
2140 bdrv_child_abort_perm_update(c
);
2144 static void bdrv_set_perm(BlockDriverState
*bs
)
2146 uint64_t cumulative_perms
, cumulative_shared_perms
;
2147 BlockDriver
*drv
= bs
->drv
;
2154 bdrv_get_cumulative_perm(bs
, &cumulative_perms
, &cumulative_shared_perms
);
2156 /* Update this node */
2157 if (drv
->bdrv_set_perm
) {
2158 drv
->bdrv_set_perm(bs
, cumulative_perms
, cumulative_shared_perms
);
2161 /* Drivers that never have children can omit .bdrv_child_perm() */
2162 if (!drv
->bdrv_child_perm
) {
2163 assert(QLIST_EMPTY(&bs
->children
));
2167 /* Update all children */
2168 QLIST_FOREACH(c
, &bs
->children
, next
) {
2169 bdrv_child_set_perm(c
);
2173 void bdrv_get_cumulative_perm(BlockDriverState
*bs
, uint64_t *perm
,
2174 uint64_t *shared_perm
)
2177 uint64_t cumulative_perms
= 0;
2178 uint64_t cumulative_shared_perms
= BLK_PERM_ALL
;
2180 QLIST_FOREACH(c
, &bs
->parents
, next_parent
) {
2181 cumulative_perms
|= c
->perm
;
2182 cumulative_shared_perms
&= c
->shared_perm
;
2185 *perm
= cumulative_perms
;
2186 *shared_perm
= cumulative_shared_perms
;
2189 static char *bdrv_child_user_desc(BdrvChild
*c
)
2191 if (c
->klass
->get_parent_desc
) {
2192 return c
->klass
->get_parent_desc(c
);
2195 return g_strdup("another user");
2198 char *bdrv_perm_names(uint64_t perm
)
2204 { BLK_PERM_CONSISTENT_READ
, "consistent read" },
2205 { BLK_PERM_WRITE
, "write" },
2206 { BLK_PERM_WRITE_UNCHANGED
, "write unchanged" },
2207 { BLK_PERM_RESIZE
, "resize" },
2208 { BLK_PERM_GRAPH_MOD
, "change children" },
2212 GString
*result
= g_string_sized_new(30);
2213 struct perm_name
*p
;
2215 for (p
= permissions
; p
->name
; p
++) {
2216 if (perm
& p
->perm
) {
2217 if (result
->len
> 0) {
2218 g_string_append(result
, ", ");
2220 g_string_append(result
, p
->name
);
2224 return g_string_free(result
, FALSE
);
2228 * Checks whether a new reference to @bs can be added if the new user requires
2229 * @new_used_perm/@new_shared_perm as its permissions. If @ignore_children is
2230 * set, the BdrvChild objects in this list are ignored in the calculations;
2231 * this allows checking permission updates for an existing reference.
2233 * Needs to be followed by a call to either bdrv_set_perm() or
2234 * bdrv_abort_perm_update(). */
2235 static int bdrv_check_update_perm(BlockDriverState
*bs
, BlockReopenQueue
*q
,
2236 uint64_t new_used_perm
,
2237 uint64_t new_shared_perm
,
2238 GSList
*ignore_children
,
2242 uint64_t cumulative_perms
= new_used_perm
;
2243 uint64_t cumulative_shared_perms
= new_shared_perm
;
2246 /* There is no reason why anyone couldn't tolerate write_unchanged */
2247 assert(new_shared_perm
& BLK_PERM_WRITE_UNCHANGED
);
2249 QLIST_FOREACH(c
, &bs
->parents
, next_parent
) {
2250 if (g_slist_find(ignore_children
, c
)) {
2254 if ((new_used_perm
& c
->shared_perm
) != new_used_perm
) {
2255 char *user
= bdrv_child_user_desc(c
);
2256 char *perm_names
= bdrv_perm_names(new_used_perm
& ~c
->shared_perm
);
2258 error_setg(errp
, "Conflicts with use by %s as '%s', which does not "
2260 user
, c
->name
, perm_names
, bdrv_get_node_name(c
->bs
));
2266 if ((c
->perm
& new_shared_perm
) != c
->perm
) {
2267 char *user
= bdrv_child_user_desc(c
);
2268 char *perm_names
= bdrv_perm_names(c
->perm
& ~new_shared_perm
);
2270 error_setg(errp
, "Conflicts with use by %s as '%s', which uses "
2272 user
, c
->name
, perm_names
, bdrv_get_node_name(c
->bs
));
2278 cumulative_perms
|= c
->perm
;
2279 cumulative_shared_perms
&= c
->shared_perm
;
2282 return bdrv_check_perm(bs
, q
, cumulative_perms
, cumulative_shared_perms
,
2283 ignore_children
, errp
);
2286 /* Needs to be followed by a call to either bdrv_child_set_perm() or
2287 * bdrv_child_abort_perm_update(). */
2288 static int bdrv_child_check_perm(BdrvChild
*c
, BlockReopenQueue
*q
,
2289 uint64_t perm
, uint64_t shared
,
2290 GSList
*ignore_children
, Error
**errp
)
2294 ignore_children
= g_slist_prepend(g_slist_copy(ignore_children
), c
);
2295 ret
= bdrv_check_update_perm(c
->bs
, q
, perm
, shared
, ignore_children
, errp
);
2296 g_slist_free(ignore_children
);
2302 if (!c
->has_backup_perm
) {
2303 c
->has_backup_perm
= true;
2304 c
->backup_perm
= c
->perm
;
2305 c
->backup_shared_perm
= c
->shared_perm
;
2308 * Note: it's OK if c->has_backup_perm was already set, as we can find the
2309 * same child twice during check_perm procedure
2313 c
->shared_perm
= shared
;
2318 static void bdrv_child_set_perm(BdrvChild
*c
)
2320 c
->has_backup_perm
= false;
2322 bdrv_set_perm(c
->bs
);
2325 static void bdrv_child_abort_perm_update(BdrvChild
*c
)
2327 if (c
->has_backup_perm
) {
2328 c
->perm
= c
->backup_perm
;
2329 c
->shared_perm
= c
->backup_shared_perm
;
2330 c
->has_backup_perm
= false;
2333 bdrv_abort_perm_update(c
->bs
);
2336 static int bdrv_refresh_perms(BlockDriverState
*bs
, Error
**errp
)
2339 uint64_t perm
, shared_perm
;
2341 bdrv_get_cumulative_perm(bs
, &perm
, &shared_perm
);
2342 ret
= bdrv_check_perm(bs
, NULL
, perm
, shared_perm
, NULL
, errp
);
2344 bdrv_abort_perm_update(bs
);
2352 int bdrv_child_try_set_perm(BdrvChild
*c
, uint64_t perm
, uint64_t shared
,
2355 Error
*local_err
= NULL
;
2358 ret
= bdrv_child_check_perm(c
, NULL
, perm
, shared
, NULL
, &local_err
);
2360 bdrv_child_abort_perm_update(c
);
2361 if ((perm
& ~c
->perm
) || (c
->shared_perm
& ~shared
)) {
2362 /* tighten permissions */
2363 error_propagate(errp
, local_err
);
2366 * Our caller may intend to only loosen restrictions and
2367 * does not expect this function to fail. Errors are not
2368 * fatal in such a case, so we can just hide them from our
2371 error_free(local_err
);
2377 bdrv_child_set_perm(c
);
2382 int bdrv_child_refresh_perms(BlockDriverState
*bs
, BdrvChild
*c
, Error
**errp
)
2384 uint64_t parent_perms
, parent_shared
;
2385 uint64_t perms
, shared
;
2387 bdrv_get_cumulative_perm(bs
, &parent_perms
, &parent_shared
);
2388 bdrv_child_perm(bs
, c
->bs
, c
, c
->role
, NULL
,
2389 parent_perms
, parent_shared
, &perms
, &shared
);
2391 return bdrv_child_try_set_perm(c
, perms
, shared
, errp
);
2395 * Default implementation for .bdrv_child_perm() for block filters:
2396 * Forward CONSISTENT_READ, WRITE, WRITE_UNCHANGED, and RESIZE to the
2399 static void bdrv_filter_default_perms(BlockDriverState
*bs
, BdrvChild
*c
,
2401 BlockReopenQueue
*reopen_queue
,
2402 uint64_t perm
, uint64_t shared
,
2403 uint64_t *nperm
, uint64_t *nshared
)
2405 *nperm
= perm
& DEFAULT_PERM_PASSTHROUGH
;
2406 *nshared
= (shared
& DEFAULT_PERM_PASSTHROUGH
) | DEFAULT_PERM_UNCHANGED
;
2409 static void bdrv_default_perms_for_cow(BlockDriverState
*bs
, BdrvChild
*c
,
2411 BlockReopenQueue
*reopen_queue
,
2412 uint64_t perm
, uint64_t shared
,
2413 uint64_t *nperm
, uint64_t *nshared
)
2415 assert(role
& BDRV_CHILD_COW
);
2418 * We want consistent read from backing files if the parent needs it.
2419 * No other operations are performed on backing files.
2421 perm
&= BLK_PERM_CONSISTENT_READ
;
2424 * If the parent can deal with changing data, we're okay with a
2425 * writable and resizable backing file.
2426 * TODO Require !(perm & BLK_PERM_CONSISTENT_READ), too?
2428 if (shared
& BLK_PERM_WRITE
) {
2429 shared
= BLK_PERM_WRITE
| BLK_PERM_RESIZE
;
2434 shared
|= BLK_PERM_CONSISTENT_READ
| BLK_PERM_GRAPH_MOD
|
2435 BLK_PERM_WRITE_UNCHANGED
;
2437 if (bs
->open_flags
& BDRV_O_INACTIVE
) {
2438 shared
|= BLK_PERM_WRITE
| BLK_PERM_RESIZE
;
2445 static void bdrv_default_perms_for_storage(BlockDriverState
*bs
, BdrvChild
*c
,
2447 BlockReopenQueue
*reopen_queue
,
2448 uint64_t perm
, uint64_t shared
,
2449 uint64_t *nperm
, uint64_t *nshared
)
2453 assert(role
& (BDRV_CHILD_METADATA
| BDRV_CHILD_DATA
));
2455 flags
= bdrv_reopen_get_flags(reopen_queue
, bs
);
2458 * Apart from the modifications below, the same permissions are
2459 * forwarded and left alone as for filters
2461 bdrv_filter_default_perms(bs
, c
, role
, reopen_queue
,
2462 perm
, shared
, &perm
, &shared
);
2464 if (role
& BDRV_CHILD_METADATA
) {
2465 /* Format drivers may touch metadata even if the guest doesn't write */
2466 if (bdrv_is_writable_after_reopen(bs
, reopen_queue
)) {
2467 perm
|= BLK_PERM_WRITE
| BLK_PERM_RESIZE
;
2471 * bs->file always needs to be consistent because of the
2472 * metadata. We can never allow other users to resize or write
2475 if (!(flags
& BDRV_O_NO_IO
)) {
2476 perm
|= BLK_PERM_CONSISTENT_READ
;
2478 shared
&= ~(BLK_PERM_WRITE
| BLK_PERM_RESIZE
);
2481 if (role
& BDRV_CHILD_DATA
) {
2483 * Technically, everything in this block is a subset of the
2484 * BDRV_CHILD_METADATA path taken above, and so this could
2485 * be an "else if" branch. However, that is not obvious, and
2486 * this function is not performance critical, therefore we let
2487 * this be an independent "if".
2491 * We cannot allow other users to resize the file because the
2492 * format driver might have some assumptions about the size
2493 * (e.g. because it is stored in metadata, or because the file
2494 * is split into fixed-size data files).
2496 shared
&= ~BLK_PERM_RESIZE
;
2499 * WRITE_UNCHANGED often cannot be performed as such on the
2500 * data file. For example, the qcow2 driver may still need to
2501 * write copied clusters on copy-on-read.
2503 if (perm
& BLK_PERM_WRITE_UNCHANGED
) {
2504 perm
|= BLK_PERM_WRITE
;
2508 * If the data file is written to, the format driver may
2509 * expect to be able to resize it by writing beyond the EOF.
2511 if (perm
& BLK_PERM_WRITE
) {
2512 perm
|= BLK_PERM_RESIZE
;
2516 if (bs
->open_flags
& BDRV_O_INACTIVE
) {
2517 shared
|= BLK_PERM_WRITE
| BLK_PERM_RESIZE
;
2524 void bdrv_default_perms(BlockDriverState
*bs
, BdrvChild
*c
,
2525 BdrvChildRole role
, BlockReopenQueue
*reopen_queue
,
2526 uint64_t perm
, uint64_t shared
,
2527 uint64_t *nperm
, uint64_t *nshared
)
2529 if (role
& BDRV_CHILD_FILTERED
) {
2530 assert(!(role
& (BDRV_CHILD_DATA
| BDRV_CHILD_METADATA
|
2532 bdrv_filter_default_perms(bs
, c
, role
, reopen_queue
,
2533 perm
, shared
, nperm
, nshared
);
2534 } else if (role
& BDRV_CHILD_COW
) {
2535 assert(!(role
& (BDRV_CHILD_DATA
| BDRV_CHILD_METADATA
)));
2536 bdrv_default_perms_for_cow(bs
, c
, role
, reopen_queue
,
2537 perm
, shared
, nperm
, nshared
);
2538 } else if (role
& (BDRV_CHILD_METADATA
| BDRV_CHILD_DATA
)) {
2539 bdrv_default_perms_for_storage(bs
, c
, role
, reopen_queue
,
2540 perm
, shared
, nperm
, nshared
);
2542 g_assert_not_reached();
2546 uint64_t bdrv_qapi_perm_to_blk_perm(BlockPermission qapi_perm
)
2548 static const uint64_t permissions
[] = {
2549 [BLOCK_PERMISSION_CONSISTENT_READ
] = BLK_PERM_CONSISTENT_READ
,
2550 [BLOCK_PERMISSION_WRITE
] = BLK_PERM_WRITE
,
2551 [BLOCK_PERMISSION_WRITE_UNCHANGED
] = BLK_PERM_WRITE_UNCHANGED
,
2552 [BLOCK_PERMISSION_RESIZE
] = BLK_PERM_RESIZE
,
2553 [BLOCK_PERMISSION_GRAPH_MOD
] = BLK_PERM_GRAPH_MOD
,
2556 QEMU_BUILD_BUG_ON(ARRAY_SIZE(permissions
) != BLOCK_PERMISSION__MAX
);
2557 QEMU_BUILD_BUG_ON(1UL << ARRAY_SIZE(permissions
) != BLK_PERM_ALL
+ 1);
2559 assert(qapi_perm
< BLOCK_PERMISSION__MAX
);
2561 return permissions
[qapi_perm
];
2564 static void bdrv_replace_child_noperm(BdrvChild
*child
,
2565 BlockDriverState
*new_bs
)
2567 BlockDriverState
*old_bs
= child
->bs
;
2568 int new_bs_quiesce_counter
;
2571 assert(!child
->frozen
);
2573 if (old_bs
&& new_bs
) {
2574 assert(bdrv_get_aio_context(old_bs
) == bdrv_get_aio_context(new_bs
));
2577 new_bs_quiesce_counter
= (new_bs
? new_bs
->quiesce_counter
: 0);
2578 drain_saldo
= new_bs_quiesce_counter
- child
->parent_quiesce_counter
;
2581 * If the new child node is drained but the old one was not, flush
2582 * all outstanding requests to the old child node.
2584 while (drain_saldo
> 0 && child
->klass
->drained_begin
) {
2585 bdrv_parent_drained_begin_single(child
, true);
2590 /* Detach first so that the recursive drain sections coming from @child
2591 * are already gone and we only end the drain sections that came from
2593 if (child
->klass
->detach
) {
2594 child
->klass
->detach(child
);
2596 QLIST_REMOVE(child
, next_parent
);
2602 QLIST_INSERT_HEAD(&new_bs
->parents
, child
, next_parent
);
2605 * Detaching the old node may have led to the new node's
2606 * quiesce_counter having been decreased. Not a problem, we
2607 * just need to recognize this here and then invoke
2608 * drained_end appropriately more often.
2610 assert(new_bs
->quiesce_counter
<= new_bs_quiesce_counter
);
2611 drain_saldo
+= new_bs
->quiesce_counter
- new_bs_quiesce_counter
;
2613 /* Attach only after starting new drained sections, so that recursive
2614 * drain sections coming from @child don't get an extra .drained_begin
2616 if (child
->klass
->attach
) {
2617 child
->klass
->attach(child
);
2622 * If the old child node was drained but the new one is not, allow
2623 * requests to come in only after the new node has been attached.
2625 while (drain_saldo
< 0 && child
->klass
->drained_end
) {
2626 bdrv_parent_drained_end_single(child
);
2632 * Updates @child to change its reference to point to @new_bs, including
2633 * checking and applying the necessary permission updates both to the old node
2636 * NULL is passed as @new_bs for removing the reference before freeing @child.
2638 * If @new_bs is not NULL, bdrv_check_perm() must be called beforehand, as this
2639 * function uses bdrv_set_perm() to update the permissions according to the new
2640 * reference that @new_bs gets.
2642 * Callers must ensure that child->frozen is false.
2644 static void bdrv_replace_child(BdrvChild
*child
, BlockDriverState
*new_bs
)
2646 BlockDriverState
*old_bs
= child
->bs
;
2648 /* Asserts that child->frozen == false */
2649 bdrv_replace_child_noperm(child
, new_bs
);
2652 * Start with the new node's permissions. If @new_bs is a (direct
2653 * or indirect) child of @old_bs, we must complete the permission
2654 * update on @new_bs before we loosen the restrictions on @old_bs.
2655 * Otherwise, bdrv_check_perm() on @old_bs would re-initiate
2656 * updating the permissions of @new_bs, and thus not purely loosen
2660 bdrv_set_perm(new_bs
);
2665 * Update permissions for old node. We're just taking a parent away, so
2666 * we're loosening restrictions. Errors of permission update are not
2667 * fatal in this case, ignore them.
2669 bdrv_refresh_perms(old_bs
, NULL
);
2671 /* When the parent requiring a non-default AioContext is removed, the
2672 * node moves back to the main AioContext */
2673 bdrv_try_set_aio_context(old_bs
, qemu_get_aio_context(), NULL
);
2678 * This function steals the reference to child_bs from the caller.
2679 * That reference is later dropped by bdrv_root_unref_child().
2681 * On failure NULL is returned, errp is set and the reference to
2682 * child_bs is also dropped.
2684 * The caller must hold the AioContext lock @child_bs, but not that of @ctx
2685 * (unless @child_bs is already in @ctx).
2687 BdrvChild
*bdrv_root_attach_child(BlockDriverState
*child_bs
,
2688 const char *child_name
,
2689 const BdrvChildClass
*child_class
,
2690 BdrvChildRole child_role
,
2692 uint64_t perm
, uint64_t shared_perm
,
2693 void *opaque
, Error
**errp
)
2696 Error
*local_err
= NULL
;
2699 ret
= bdrv_check_update_perm(child_bs
, NULL
, perm
, shared_perm
, NULL
, errp
);
2701 bdrv_abort_perm_update(child_bs
);
2702 bdrv_unref(child_bs
);
2706 child
= g_new(BdrvChild
, 1);
2707 *child
= (BdrvChild
) {
2709 .name
= g_strdup(child_name
),
2710 .klass
= child_class
,
2713 .shared_perm
= shared_perm
,
2717 /* If the AioContexts don't match, first try to move the subtree of
2718 * child_bs into the AioContext of the new parent. If this doesn't work,
2719 * try moving the parent into the AioContext of child_bs instead. */
2720 if (bdrv_get_aio_context(child_bs
) != ctx
) {
2721 ret
= bdrv_try_set_aio_context(child_bs
, ctx
, &local_err
);
2722 if (ret
< 0 && child_class
->can_set_aio_ctx
) {
2723 GSList
*ignore
= g_slist_prepend(NULL
, child
);
2724 ctx
= bdrv_get_aio_context(child_bs
);
2725 if (child_class
->can_set_aio_ctx(child
, ctx
, &ignore
, NULL
)) {
2726 error_free(local_err
);
2728 g_slist_free(ignore
);
2729 ignore
= g_slist_prepend(NULL
, child
);
2730 child_class
->set_aio_ctx(child
, ctx
, &ignore
);
2732 g_slist_free(ignore
);
2735 error_propagate(errp
, local_err
);
2737 bdrv_abort_perm_update(child_bs
);
2738 bdrv_unref(child_bs
);
2743 /* This performs the matching bdrv_set_perm() for the above check. */
2744 bdrv_replace_child(child
, child_bs
);
2750 * This function transfers the reference to child_bs from the caller
2751 * to parent_bs. That reference is later dropped by parent_bs on
2752 * bdrv_close() or if someone calls bdrv_unref_child().
2754 * On failure NULL is returned, errp is set and the reference to
2755 * child_bs is also dropped.
2757 * If @parent_bs and @child_bs are in different AioContexts, the caller must
2758 * hold the AioContext lock for @child_bs, but not for @parent_bs.
2760 BdrvChild
*bdrv_attach_child(BlockDriverState
*parent_bs
,
2761 BlockDriverState
*child_bs
,
2762 const char *child_name
,
2763 const BdrvChildClass
*child_class
,
2764 BdrvChildRole child_role
,
2768 uint64_t perm
, shared_perm
;
2770 bdrv_get_cumulative_perm(parent_bs
, &perm
, &shared_perm
);
2772 assert(parent_bs
->drv
);
2773 bdrv_child_perm(parent_bs
, child_bs
, NULL
, child_role
, NULL
,
2774 perm
, shared_perm
, &perm
, &shared_perm
);
2776 child
= bdrv_root_attach_child(child_bs
, child_name
, child_class
,
2777 child_role
, bdrv_get_aio_context(parent_bs
),
2778 perm
, shared_perm
, parent_bs
, errp
);
2779 if (child
== NULL
) {
2783 QLIST_INSERT_HEAD(&parent_bs
->children
, child
, next
);
2787 static void bdrv_detach_child(BdrvChild
*child
)
2789 QLIST_SAFE_REMOVE(child
, next
);
2791 bdrv_replace_child(child
, NULL
);
2793 g_free(child
->name
);
2797 /* Callers must ensure that child->frozen is false. */
2798 void bdrv_root_unref_child(BdrvChild
*child
)
2800 BlockDriverState
*child_bs
;
2802 child_bs
= child
->bs
;
2803 bdrv_detach_child(child
);
2804 bdrv_unref(child_bs
);
2808 * Clear all inherits_from pointers from children and grandchildren of
2809 * @root that point to @root, where necessary.
2811 static void bdrv_unset_inherits_from(BlockDriverState
*root
, BdrvChild
*child
)
2815 if (child
->bs
->inherits_from
== root
) {
2817 * Remove inherits_from only when the last reference between root and
2818 * child->bs goes away.
2820 QLIST_FOREACH(c
, &root
->children
, next
) {
2821 if (c
!= child
&& c
->bs
== child
->bs
) {
2826 child
->bs
->inherits_from
= NULL
;
2830 QLIST_FOREACH(c
, &child
->bs
->children
, next
) {
2831 bdrv_unset_inherits_from(root
, c
);
2835 /* Callers must ensure that child->frozen is false. */
2836 void bdrv_unref_child(BlockDriverState
*parent
, BdrvChild
*child
)
2838 if (child
== NULL
) {
2842 bdrv_unset_inherits_from(parent
, child
);
2843 bdrv_root_unref_child(child
);
2847 static void bdrv_parent_cb_change_media(BlockDriverState
*bs
, bool load
)
2850 QLIST_FOREACH(c
, &bs
->parents
, next_parent
) {
2851 if (c
->klass
->change_media
) {
2852 c
->klass
->change_media(c
, load
);
2857 /* Return true if you can reach parent going through child->inherits_from
2858 * recursively. If parent or child are NULL, return false */
2859 static bool bdrv_inherits_from_recursive(BlockDriverState
*child
,
2860 BlockDriverState
*parent
)
2862 while (child
&& child
!= parent
) {
2863 child
= child
->inherits_from
;
2866 return child
!= NULL
;
2870 * Return the BdrvChildRole for @bs's backing child. bs->backing is
2871 * mostly used for COW backing children (role = COW), but also for
2872 * filtered children (role = FILTERED | PRIMARY).
2874 static BdrvChildRole
bdrv_backing_role(BlockDriverState
*bs
)
2876 if (bs
->drv
&& bs
->drv
->is_filter
) {
2877 return BDRV_CHILD_FILTERED
| BDRV_CHILD_PRIMARY
;
2879 return BDRV_CHILD_COW
;
2884 * Sets the bs->backing link of a BDS. A new reference is created; callers
2885 * which don't need their own reference any more must call bdrv_unref().
2887 int bdrv_set_backing_hd(BlockDriverState
*bs
, BlockDriverState
*backing_hd
,
2891 bool update_inherits_from
= bdrv_chain_contains(bs
, backing_hd
) &&
2892 bdrv_inherits_from_recursive(backing_hd
, bs
);
2894 if (bdrv_is_backing_chain_frozen(bs
, child_bs(bs
->backing
), errp
)) {
2899 bdrv_ref(backing_hd
);
2903 /* Cannot be frozen, we checked that above */
2904 bdrv_unref_child(bs
, bs
->backing
);
2912 bs
->backing
= bdrv_attach_child(bs
, backing_hd
, "backing", &child_of_bds
,
2913 bdrv_backing_role(bs
), errp
);
2919 /* If backing_hd was already part of bs's backing chain, and
2920 * inherits_from pointed recursively to bs then let's update it to
2921 * point directly to bs (else it will become NULL). */
2922 if (update_inherits_from
) {
2923 backing_hd
->inherits_from
= bs
;
2927 bdrv_refresh_limits(bs
, NULL
);
2933 * Opens the backing file for a BlockDriverState if not yet open
2935 * bdref_key specifies the key for the image's BlockdevRef in the options QDict.
2936 * That QDict has to be flattened; therefore, if the BlockdevRef is a QDict
2937 * itself, all options starting with "${bdref_key}." are considered part of the
2940 * TODO Can this be unified with bdrv_open_image()?
2942 int bdrv_open_backing_file(BlockDriverState
*bs
, QDict
*parent_options
,
2943 const char *bdref_key
, Error
**errp
)
2945 char *backing_filename
= NULL
;
2946 char *bdref_key_dot
;
2947 const char *reference
= NULL
;
2949 bool implicit_backing
= false;
2950 BlockDriverState
*backing_hd
;
2952 QDict
*tmp_parent_options
= NULL
;
2953 Error
*local_err
= NULL
;
2955 if (bs
->backing
!= NULL
) {
2959 /* NULL means an empty set of options */
2960 if (parent_options
== NULL
) {
2961 tmp_parent_options
= qdict_new();
2962 parent_options
= tmp_parent_options
;
2965 bs
->open_flags
&= ~BDRV_O_NO_BACKING
;
2967 bdref_key_dot
= g_strdup_printf("%s.", bdref_key
);
2968 qdict_extract_subqdict(parent_options
, &options
, bdref_key_dot
);
2969 g_free(bdref_key_dot
);
2972 * Caution: while qdict_get_try_str() is fine, getting non-string
2973 * types would require more care. When @parent_options come from
2974 * -blockdev or blockdev_add, its members are typed according to
2975 * the QAPI schema, but when they come from -drive, they're all
2978 reference
= qdict_get_try_str(parent_options
, bdref_key
);
2979 if (reference
|| qdict_haskey(options
, "file.filename")) {
2980 /* keep backing_filename NULL */
2981 } else if (bs
->backing_file
[0] == '\0' && qdict_size(options
) == 0) {
2982 qobject_unref(options
);
2985 if (qdict_size(options
) == 0) {
2986 /* If the user specifies options that do not modify the
2987 * backing file's behavior, we might still consider it the
2988 * implicit backing file. But it's easier this way, and
2989 * just specifying some of the backing BDS's options is
2990 * only possible with -drive anyway (otherwise the QAPI
2991 * schema forces the user to specify everything). */
2992 implicit_backing
= !strcmp(bs
->auto_backing_file
, bs
->backing_file
);
2995 backing_filename
= bdrv_get_full_backing_filename(bs
, &local_err
);
2998 error_propagate(errp
, local_err
);
2999 qobject_unref(options
);
3004 if (!bs
->drv
|| !bs
->drv
->supports_backing
) {
3006 error_setg(errp
, "Driver doesn't support backing files");
3007 qobject_unref(options
);
3012 bs
->backing_format
[0] != '\0' && !qdict_haskey(options
, "driver")) {
3013 qdict_put_str(options
, "driver", bs
->backing_format
);
3016 backing_hd
= bdrv_open_inherit(backing_filename
, reference
, options
, 0, bs
,
3017 &child_of_bds
, bdrv_backing_role(bs
), errp
);
3019 bs
->open_flags
|= BDRV_O_NO_BACKING
;
3020 error_prepend(errp
, "Could not open backing file: ");
3025 if (implicit_backing
) {
3026 bdrv_refresh_filename(backing_hd
);
3027 pstrcpy(bs
->auto_backing_file
, sizeof(bs
->auto_backing_file
),
3028 backing_hd
->filename
);
3031 /* Hook up the backing file link; drop our reference, bs owns the
3032 * backing_hd reference now */
3033 ret
= bdrv_set_backing_hd(bs
, backing_hd
, errp
);
3034 bdrv_unref(backing_hd
);
3039 qdict_del(parent_options
, bdref_key
);
3042 g_free(backing_filename
);
3043 qobject_unref(tmp_parent_options
);
3047 static BlockDriverState
*
3048 bdrv_open_child_bs(const char *filename
, QDict
*options
, const char *bdref_key
,
3049 BlockDriverState
*parent
, const BdrvChildClass
*child_class
,
3050 BdrvChildRole child_role
, bool allow_none
, Error
**errp
)
3052 BlockDriverState
*bs
= NULL
;
3053 QDict
*image_options
;
3054 char *bdref_key_dot
;
3055 const char *reference
;
3057 assert(child_class
!= NULL
);
3059 bdref_key_dot
= g_strdup_printf("%s.", bdref_key
);
3060 qdict_extract_subqdict(options
, &image_options
, bdref_key_dot
);
3061 g_free(bdref_key_dot
);
3064 * Caution: while qdict_get_try_str() is fine, getting non-string
3065 * types would require more care. When @options come from
3066 * -blockdev or blockdev_add, its members are typed according to
3067 * the QAPI schema, but when they come from -drive, they're all
3070 reference
= qdict_get_try_str(options
, bdref_key
);
3071 if (!filename
&& !reference
&& !qdict_size(image_options
)) {
3073 error_setg(errp
, "A block device must be specified for \"%s\"",
3076 qobject_unref(image_options
);
3080 bs
= bdrv_open_inherit(filename
, reference
, image_options
, 0,
3081 parent
, child_class
, child_role
, errp
);
3087 qdict_del(options
, bdref_key
);
3092 * Opens a disk image whose options are given as BlockdevRef in another block
3095 * If allow_none is true, no image will be opened if filename is false and no
3096 * BlockdevRef is given. NULL will be returned, but errp remains unset.
3098 * bdrev_key specifies the key for the image's BlockdevRef in the options QDict.
3099 * That QDict has to be flattened; therefore, if the BlockdevRef is a QDict
3100 * itself, all options starting with "${bdref_key}." are considered part of the
3103 * The BlockdevRef will be removed from the options QDict.
3105 BdrvChild
*bdrv_open_child(const char *filename
,
3106 QDict
*options
, const char *bdref_key
,
3107 BlockDriverState
*parent
,
3108 const BdrvChildClass
*child_class
,
3109 BdrvChildRole child_role
,
3110 bool allow_none
, Error
**errp
)
3112 BlockDriverState
*bs
;
3114 bs
= bdrv_open_child_bs(filename
, options
, bdref_key
, parent
, child_class
,
3115 child_role
, allow_none
, errp
);
3120 return bdrv_attach_child(parent
, bs
, bdref_key
, child_class
, child_role
,
3125 * TODO Future callers may need to specify parent/child_class in order for
3126 * option inheritance to work. Existing callers use it for the root node.
3128 BlockDriverState
*bdrv_open_blockdev_ref(BlockdevRef
*ref
, Error
**errp
)
3130 BlockDriverState
*bs
= NULL
;
3131 QObject
*obj
= NULL
;
3132 QDict
*qdict
= NULL
;
3133 const char *reference
= NULL
;
3136 if (ref
->type
== QTYPE_QSTRING
) {
3137 reference
= ref
->u
.reference
;
3139 BlockdevOptions
*options
= &ref
->u
.definition
;
3140 assert(ref
->type
== QTYPE_QDICT
);
3142 v
= qobject_output_visitor_new(&obj
);
3143 visit_type_BlockdevOptions(v
, NULL
, &options
, &error_abort
);
3144 visit_complete(v
, &obj
);
3146 qdict
= qobject_to(QDict
, obj
);
3147 qdict_flatten(qdict
);
3149 /* bdrv_open_inherit() defaults to the values in bdrv_flags (for
3150 * compatibility with other callers) rather than what we want as the
3151 * real defaults. Apply the defaults here instead. */
3152 qdict_set_default_str(qdict
, BDRV_OPT_CACHE_DIRECT
, "off");
3153 qdict_set_default_str(qdict
, BDRV_OPT_CACHE_NO_FLUSH
, "off");
3154 qdict_set_default_str(qdict
, BDRV_OPT_READ_ONLY
, "off");
3155 qdict_set_default_str(qdict
, BDRV_OPT_AUTO_READ_ONLY
, "off");
3159 bs
= bdrv_open_inherit(NULL
, reference
, qdict
, 0, NULL
, NULL
, 0, errp
);
3166 static BlockDriverState
*bdrv_append_temp_snapshot(BlockDriverState
*bs
,
3168 QDict
*snapshot_options
,
3171 /* TODO: extra byte is a hack to ensure MAX_PATH space on Windows. */
3172 char *tmp_filename
= g_malloc0(PATH_MAX
+ 1);
3174 QemuOpts
*opts
= NULL
;
3175 BlockDriverState
*bs_snapshot
= NULL
;
3178 /* if snapshot, we create a temporary backing file and open it
3179 instead of opening 'filename' directly */
3181 /* Get the required size from the image */
3182 total_size
= bdrv_getlength(bs
);
3183 if (total_size
< 0) {
3184 error_setg_errno(errp
, -total_size
, "Could not get image size");
3188 /* Create the temporary image */
3189 ret
= get_tmp_filename(tmp_filename
, PATH_MAX
+ 1);
3191 error_setg_errno(errp
, -ret
, "Could not get temporary filename");
3195 opts
= qemu_opts_create(bdrv_qcow2
.create_opts
, NULL
, 0,
3197 qemu_opt_set_number(opts
, BLOCK_OPT_SIZE
, total_size
, &error_abort
);
3198 ret
= bdrv_create(&bdrv_qcow2
, tmp_filename
, opts
, errp
);
3199 qemu_opts_del(opts
);
3201 error_prepend(errp
, "Could not create temporary overlay '%s': ",
3206 /* Prepare options QDict for the temporary file */
3207 qdict_put_str(snapshot_options
, "file.driver", "file");
3208 qdict_put_str(snapshot_options
, "file.filename", tmp_filename
);
3209 qdict_put_str(snapshot_options
, "driver", "qcow2");
3211 bs_snapshot
= bdrv_open(NULL
, NULL
, snapshot_options
, flags
, errp
);
3212 snapshot_options
= NULL
;
3217 /* bdrv_append() consumes a strong reference to bs_snapshot
3218 * (i.e. it will call bdrv_unref() on it) even on error, so in
3219 * order to be able to return one, we have to increase
3220 * bs_snapshot's refcount here */
3221 bdrv_ref(bs_snapshot
);
3222 ret
= bdrv_append(bs_snapshot
, bs
, errp
);
3229 qobject_unref(snapshot_options
);
3230 g_free(tmp_filename
);
3235 * Opens a disk image (raw, qcow2, vmdk, ...)
3237 * options is a QDict of options to pass to the block drivers, or NULL for an
3238 * empty set of options. The reference to the QDict belongs to the block layer
3239 * after the call (even on failure), so if the caller intends to reuse the
3240 * dictionary, it needs to use qobject_ref() before calling bdrv_open.
3242 * If *pbs is NULL, a new BDS will be created with a pointer to it stored there.
3243 * If it is not NULL, the referenced BDS will be reused.
3245 * The reference parameter may be used to specify an existing block device which
3246 * should be opened. If specified, neither options nor a filename may be given,
3247 * nor can an existing BDS be reused (that is, *pbs has to be NULL).
3249 static BlockDriverState
*bdrv_open_inherit(const char *filename
,
3250 const char *reference
,
3251 QDict
*options
, int flags
,
3252 BlockDriverState
*parent
,
3253 const BdrvChildClass
*child_class
,
3254 BdrvChildRole child_role
,
3258 BlockBackend
*file
= NULL
;
3259 BlockDriverState
*bs
;
3260 BlockDriver
*drv
= NULL
;
3262 const char *drvname
;
3263 const char *backing
;
3264 Error
*local_err
= NULL
;
3265 QDict
*snapshot_options
= NULL
;
3266 int snapshot_flags
= 0;
3268 assert(!child_class
|| !flags
);
3269 assert(!child_class
== !parent
);
3272 bool options_non_empty
= options
? qdict_size(options
) : false;
3273 qobject_unref(options
);
3275 if (filename
|| options_non_empty
) {
3276 error_setg(errp
, "Cannot reference an existing block device with "
3277 "additional options or a new filename");
3281 bs
= bdrv_lookup_bs(reference
, reference
, errp
);
3292 /* NULL means an empty set of options */
3293 if (options
== NULL
) {
3294 options
= qdict_new();
3297 /* json: syntax counts as explicit options, as if in the QDict */
3298 parse_json_protocol(options
, &filename
, &local_err
);
3303 bs
->explicit_options
= qdict_clone_shallow(options
);
3306 bool parent_is_format
;
3309 parent_is_format
= parent
->drv
->is_format
;
3312 * parent->drv is not set yet because this node is opened for
3313 * (potential) format probing. That means that @parent is going
3314 * to be a format node.
3316 parent_is_format
= true;
3319 bs
->inherits_from
= parent
;
3320 child_class
->inherit_options(child_role
, parent_is_format
,
3322 parent
->open_flags
, parent
->options
);
3325 ret
= bdrv_fill_options(&options
, filename
, &flags
, &local_err
);
3331 * Set the BDRV_O_RDWR and BDRV_O_ALLOW_RDWR flags.
3332 * Caution: getting a boolean member of @options requires care.
3333 * When @options come from -blockdev or blockdev_add, members are
3334 * typed according to the QAPI schema, but when they come from
3335 * -drive, they're all QString.
3337 if (g_strcmp0(qdict_get_try_str(options
, BDRV_OPT_READ_ONLY
), "on") &&
3338 !qdict_get_try_bool(options
, BDRV_OPT_READ_ONLY
, false)) {
3339 flags
|= (BDRV_O_RDWR
| BDRV_O_ALLOW_RDWR
);
3341 flags
&= ~BDRV_O_RDWR
;
3344 if (flags
& BDRV_O_SNAPSHOT
) {
3345 snapshot_options
= qdict_new();
3346 bdrv_temp_snapshot_options(&snapshot_flags
, snapshot_options
,
3348 /* Let bdrv_backing_options() override "read-only" */
3349 qdict_del(options
, BDRV_OPT_READ_ONLY
);
3350 bdrv_inherited_options(BDRV_CHILD_COW
, true,
3351 &flags
, options
, flags
, options
);
3354 bs
->open_flags
= flags
;
3355 bs
->options
= options
;
3356 options
= qdict_clone_shallow(options
);
3358 /* Find the right image format driver */
3359 /* See cautionary note on accessing @options above */
3360 drvname
= qdict_get_try_str(options
, "driver");
3362 drv
= bdrv_find_format(drvname
);
3364 error_setg(errp
, "Unknown driver: '%s'", drvname
);
3369 assert(drvname
|| !(flags
& BDRV_O_PROTOCOL
));
3371 /* See cautionary note on accessing @options above */
3372 backing
= qdict_get_try_str(options
, "backing");
3373 if (qobject_to(QNull
, qdict_get(options
, "backing")) != NULL
||
3374 (backing
&& *backing
== '\0'))
3377 warn_report("Use of \"backing\": \"\" is deprecated; "
3378 "use \"backing\": null instead");
3380 flags
|= BDRV_O_NO_BACKING
;
3381 qdict_del(bs
->explicit_options
, "backing");
3382 qdict_del(bs
->options
, "backing");
3383 qdict_del(options
, "backing");
3386 /* Open image file without format layer. This BlockBackend is only used for
3387 * probing, the block drivers will do their own bdrv_open_child() for the
3388 * same BDS, which is why we put the node name back into options. */
3389 if ((flags
& BDRV_O_PROTOCOL
) == 0) {
3390 BlockDriverState
*file_bs
;
3392 file_bs
= bdrv_open_child_bs(filename
, options
, "file", bs
,
3393 &child_of_bds
, BDRV_CHILD_IMAGE
,
3398 if (file_bs
!= NULL
) {
3399 /* Not requesting BLK_PERM_CONSISTENT_READ because we're only
3400 * looking at the header to guess the image format. This works even
3401 * in cases where a guest would not see a consistent state. */
3402 file
= blk_new(bdrv_get_aio_context(file_bs
), 0, BLK_PERM_ALL
);
3403 blk_insert_bs(file
, file_bs
, &local_err
);
3404 bdrv_unref(file_bs
);
3409 qdict_put_str(options
, "file", bdrv_get_node_name(file_bs
));
3413 /* Image format probing */
3416 ret
= find_image_format(file
, filename
, &drv
, &local_err
);
3421 * This option update would logically belong in bdrv_fill_options(),
3422 * but we first need to open bs->file for the probing to work, while
3423 * opening bs->file already requires the (mostly) final set of options
3424 * so that cache mode etc. can be inherited.
3426 * Adding the driver later is somewhat ugly, but it's not an option
3427 * that would ever be inherited, so it's correct. We just need to make
3428 * sure to update both bs->options (which has the full effective
3429 * options for bs) and options (which has file.* already removed).
3431 qdict_put_str(bs
->options
, "driver", drv
->format_name
);
3432 qdict_put_str(options
, "driver", drv
->format_name
);
3434 error_setg(errp
, "Must specify either driver or file");
3438 /* BDRV_O_PROTOCOL must be set iff a protocol BDS is about to be created */
3439 assert(!!(flags
& BDRV_O_PROTOCOL
) == !!drv
->bdrv_file_open
);
3440 /* file must be NULL if a protocol BDS is about to be created
3441 * (the inverse results in an error message from bdrv_open_common()) */
3442 assert(!(flags
& BDRV_O_PROTOCOL
) || !file
);
3444 /* Open the image */
3445 ret
= bdrv_open_common(bs
, file
, options
, &local_err
);
3455 /* If there is a backing file, use it */
3456 if ((flags
& BDRV_O_NO_BACKING
) == 0) {
3457 ret
= bdrv_open_backing_file(bs
, options
, "backing", &local_err
);
3459 goto close_and_fail
;
3463 /* Remove all children options and references
3464 * from bs->options and bs->explicit_options */
3465 QLIST_FOREACH(child
, &bs
->children
, next
) {
3466 char *child_key_dot
;
3467 child_key_dot
= g_strdup_printf("%s.", child
->name
);
3468 qdict_extract_subqdict(bs
->explicit_options
, NULL
, child_key_dot
);
3469 qdict_extract_subqdict(bs
->options
, NULL
, child_key_dot
);
3470 qdict_del(bs
->explicit_options
, child
->name
);
3471 qdict_del(bs
->options
, child
->name
);
3472 g_free(child_key_dot
);
3475 /* Check if any unknown options were used */
3476 if (qdict_size(options
) != 0) {
3477 const QDictEntry
*entry
= qdict_first(options
);
3478 if (flags
& BDRV_O_PROTOCOL
) {
3479 error_setg(errp
, "Block protocol '%s' doesn't support the option "
3480 "'%s'", drv
->format_name
, entry
->key
);
3483 "Block format '%s' does not support the option '%s'",
3484 drv
->format_name
, entry
->key
);
3487 goto close_and_fail
;
3490 bdrv_parent_cb_change_media(bs
, true);
3492 qobject_unref(options
);
3495 /* For snapshot=on, create a temporary qcow2 overlay. bs points to the
3496 * temporary snapshot afterwards. */
3497 if (snapshot_flags
) {
3498 BlockDriverState
*snapshot_bs
;
3499 snapshot_bs
= bdrv_append_temp_snapshot(bs
, snapshot_flags
,
3500 snapshot_options
, &local_err
);
3501 snapshot_options
= NULL
;
3503 goto close_and_fail
;
3505 /* We are not going to return bs but the overlay on top of it
3506 * (snapshot_bs); thus, we have to drop the strong reference to bs
3507 * (which we obtained by calling bdrv_new()). bs will not be deleted,
3508 * though, because the overlay still has a reference to it. */
3517 qobject_unref(snapshot_options
);
3518 qobject_unref(bs
->explicit_options
);
3519 qobject_unref(bs
->options
);
3520 qobject_unref(options
);
3522 bs
->explicit_options
= NULL
;
3524 error_propagate(errp
, local_err
);
3529 qobject_unref(snapshot_options
);
3530 qobject_unref(options
);
3531 error_propagate(errp
, local_err
);
3535 BlockDriverState
*bdrv_open(const char *filename
, const char *reference
,
3536 QDict
*options
, int flags
, Error
**errp
)
3538 return bdrv_open_inherit(filename
, reference
, options
, flags
, NULL
,
3542 /* Return true if the NULL-terminated @list contains @str */
3543 static bool is_str_in_list(const char *str
, const char *const *list
)
3547 for (i
= 0; list
[i
] != NULL
; i
++) {
3548 if (!strcmp(str
, list
[i
])) {
3557 * Check that every option set in @bs->options is also set in
3560 * Options listed in the common_options list and in
3561 * @bs->drv->mutable_opts are skipped.
3563 * Return 0 on success, otherwise return -EINVAL and set @errp.
3565 static int bdrv_reset_options_allowed(BlockDriverState
*bs
,
3566 const QDict
*new_opts
, Error
**errp
)
3568 const QDictEntry
*e
;
3569 /* These options are common to all block drivers and are handled
3570 * in bdrv_reopen_prepare() so they can be left out of @new_opts */
3571 const char *const common_options
[] = {
3572 "node-name", "discard", "cache.direct", "cache.no-flush",
3573 "read-only", "auto-read-only", "detect-zeroes", NULL
3576 for (e
= qdict_first(bs
->options
); e
; e
= qdict_next(bs
->options
, e
)) {
3577 if (!qdict_haskey(new_opts
, e
->key
) &&
3578 !is_str_in_list(e
->key
, common_options
) &&
3579 !is_str_in_list(e
->key
, bs
->drv
->mutable_opts
)) {
3580 error_setg(errp
, "Option '%s' cannot be reset "
3581 "to its default value", e
->key
);
3590 * Returns true if @child can be reached recursively from @bs
3592 static bool bdrv_recurse_has_child(BlockDriverState
*bs
,
3593 BlockDriverState
*child
)
3601 QLIST_FOREACH(c
, &bs
->children
, next
) {
3602 if (bdrv_recurse_has_child(c
->bs
, child
)) {
3611 * Adds a BlockDriverState to a simple queue for an atomic, transactional
3612 * reopen of multiple devices.
3614 * bs_queue can either be an existing BlockReopenQueue that has had QTAILQ_INIT
3615 * already performed, or alternatively may be NULL a new BlockReopenQueue will
3616 * be created and initialized. This newly created BlockReopenQueue should be
3617 * passed back in for subsequent calls that are intended to be of the same
3620 * bs is the BlockDriverState to add to the reopen queue.
3622 * options contains the changed options for the associated bs
3623 * (the BlockReopenQueue takes ownership)
3625 * flags contains the open flags for the associated bs
3627 * returns a pointer to bs_queue, which is either the newly allocated
3628 * bs_queue, or the existing bs_queue being used.
3630 * bs must be drained between bdrv_reopen_queue() and bdrv_reopen_multiple().
3632 static BlockReopenQueue
*bdrv_reopen_queue_child(BlockReopenQueue
*bs_queue
,
3633 BlockDriverState
*bs
,
3635 const BdrvChildClass
*klass
,
3637 bool parent_is_format
,
3638 QDict
*parent_options
,
3644 BlockReopenQueueEntry
*bs_entry
;
3646 QDict
*old_options
, *explicit_options
, *options_copy
;
3650 /* Make sure that the caller remembered to use a drained section. This is
3651 * important to avoid graph changes between the recursive queuing here and
3652 * bdrv_reopen_multiple(). */
3653 assert(bs
->quiesce_counter
> 0);
3655 if (bs_queue
== NULL
) {
3656 bs_queue
= g_new0(BlockReopenQueue
, 1);
3657 QTAILQ_INIT(bs_queue
);
3661 options
= qdict_new();
3664 /* Check if this BlockDriverState is already in the queue */
3665 QTAILQ_FOREACH(bs_entry
, bs_queue
, entry
) {
3666 if (bs
== bs_entry
->state
.bs
) {
3672 * Precedence of options:
3673 * 1. Explicitly passed in options (highest)
3674 * 2. Retained from explicitly set options of bs
3675 * 3. Inherited from parent node
3676 * 4. Retained from effective options of bs
3679 /* Old explicitly set values (don't overwrite by inherited value) */
3680 if (bs_entry
|| keep_old_opts
) {
3681 old_options
= qdict_clone_shallow(bs_entry
?
3682 bs_entry
->state
.explicit_options
:
3683 bs
->explicit_options
);
3684 bdrv_join_options(bs
, options
, old_options
);
3685 qobject_unref(old_options
);
3688 explicit_options
= qdict_clone_shallow(options
);
3690 /* Inherit from parent node */
3691 if (parent_options
) {
3693 klass
->inherit_options(role
, parent_is_format
, &flags
, options
,
3694 parent_flags
, parent_options
);
3696 flags
= bdrv_get_flags(bs
);
3699 if (keep_old_opts
) {
3700 /* Old values are used for options that aren't set yet */
3701 old_options
= qdict_clone_shallow(bs
->options
);
3702 bdrv_join_options(bs
, options
, old_options
);
3703 qobject_unref(old_options
);
3706 /* We have the final set of options so let's update the flags */
3707 options_copy
= qdict_clone_shallow(options
);
3708 opts
= qemu_opts_create(&bdrv_runtime_opts
, NULL
, 0, &error_abort
);
3709 qemu_opts_absorb_qdict(opts
, options_copy
, NULL
);
3710 update_flags_from_options(&flags
, opts
);
3711 qemu_opts_del(opts
);
3712 qobject_unref(options_copy
);
3714 /* bdrv_open_inherit() sets and clears some additional flags internally */
3715 flags
&= ~BDRV_O_PROTOCOL
;
3716 if (flags
& BDRV_O_RDWR
) {
3717 flags
|= BDRV_O_ALLOW_RDWR
;
3721 bs_entry
= g_new0(BlockReopenQueueEntry
, 1);
3722 QTAILQ_INSERT_TAIL(bs_queue
, bs_entry
, entry
);
3724 qobject_unref(bs_entry
->state
.options
);
3725 qobject_unref(bs_entry
->state
.explicit_options
);
3728 bs_entry
->state
.bs
= bs
;
3729 bs_entry
->state
.options
= options
;
3730 bs_entry
->state
.explicit_options
= explicit_options
;
3731 bs_entry
->state
.flags
= flags
;
3733 /* This needs to be overwritten in bdrv_reopen_prepare() */
3734 bs_entry
->state
.perm
= UINT64_MAX
;
3735 bs_entry
->state
.shared_perm
= 0;
3738 * If keep_old_opts is false then it means that unspecified
3739 * options must be reset to their original value. We don't allow
3740 * resetting 'backing' but we need to know if the option is
3741 * missing in order to decide if we have to return an error.
3743 if (!keep_old_opts
) {
3744 bs_entry
->state
.backing_missing
=
3745 !qdict_haskey(options
, "backing") &&
3746 !qdict_haskey(options
, "backing.driver");
3749 QLIST_FOREACH(child
, &bs
->children
, next
) {
3750 QDict
*new_child_options
= NULL
;
3751 bool child_keep_old
= keep_old_opts
;
3753 /* reopen can only change the options of block devices that were
3754 * implicitly created and inherited options. For other (referenced)
3755 * block devices, a syntax like "backing.foo" results in an error. */
3756 if (child
->bs
->inherits_from
!= bs
) {
3760 /* Check if the options contain a child reference */
3761 if (qdict_haskey(options
, child
->name
)) {
3762 const char *childref
= qdict_get_try_str(options
, child
->name
);
3764 * The current child must not be reopened if the child
3765 * reference is null or points to a different node.
3767 if (g_strcmp0(childref
, child
->bs
->node_name
)) {
3771 * If the child reference points to the current child then
3772 * reopen it with its existing set of options (note that
3773 * it can still inherit new options from the parent).
3775 child_keep_old
= true;
3777 /* Extract child options ("child-name.*") */
3778 char *child_key_dot
= g_strdup_printf("%s.", child
->name
);
3779 qdict_extract_subqdict(explicit_options
, NULL
, child_key_dot
);
3780 qdict_extract_subqdict(options
, &new_child_options
, child_key_dot
);
3781 g_free(child_key_dot
);
3784 bdrv_reopen_queue_child(bs_queue
, child
->bs
, new_child_options
,
3785 child
->klass
, child
->role
, bs
->drv
->is_format
,
3786 options
, flags
, child_keep_old
);
3792 BlockReopenQueue
*bdrv_reopen_queue(BlockReopenQueue
*bs_queue
,
3793 BlockDriverState
*bs
,
3794 QDict
*options
, bool keep_old_opts
)
3796 return bdrv_reopen_queue_child(bs_queue
, bs
, options
, NULL
, 0, false,
3797 NULL
, 0, keep_old_opts
);
3801 * Reopen multiple BlockDriverStates atomically & transactionally.
3803 * The queue passed in (bs_queue) must have been built up previous
3804 * via bdrv_reopen_queue().
3806 * Reopens all BDS specified in the queue, with the appropriate
3807 * flags. All devices are prepared for reopen, and failure of any
3808 * device will cause all device changes to be abandoned, and intermediate
3811 * If all devices prepare successfully, then the changes are committed
3814 * All affected nodes must be drained between bdrv_reopen_queue() and
3815 * bdrv_reopen_multiple().
3817 int bdrv_reopen_multiple(BlockReopenQueue
*bs_queue
, Error
**errp
)
3820 BlockReopenQueueEntry
*bs_entry
, *next
;
3822 assert(bs_queue
!= NULL
);
3824 QTAILQ_FOREACH(bs_entry
, bs_queue
, entry
) {
3825 assert(bs_entry
->state
.bs
->quiesce_counter
> 0);
3826 if (bdrv_reopen_prepare(&bs_entry
->state
, bs_queue
, errp
)) {
3829 bs_entry
->prepared
= true;
3832 QTAILQ_FOREACH(bs_entry
, bs_queue
, entry
) {
3833 BDRVReopenState
*state
= &bs_entry
->state
;
3834 ret
= bdrv_check_perm(state
->bs
, bs_queue
, state
->perm
,
3835 state
->shared_perm
, NULL
, errp
);
3839 /* Check if new_backing_bs would accept the new permissions */
3840 if (state
->replace_backing_bs
&& state
->new_backing_bs
) {
3841 uint64_t nperm
, nshared
;
3842 bdrv_child_perm(state
->bs
, state
->new_backing_bs
,
3843 NULL
, bdrv_backing_role(state
->bs
),
3844 bs_queue
, state
->perm
, state
->shared_perm
,
3846 ret
= bdrv_check_update_perm(state
->new_backing_bs
, NULL
,
3847 nperm
, nshared
, NULL
, errp
);
3852 bs_entry
->perms_checked
= true;
3856 * If we reach this point, we have success and just need to apply the
3859 * Reverse order is used to comfort qcow2 driver: on commit it need to write
3860 * IN_USE flag to the image, to mark bitmaps in the image as invalid. But
3861 * children are usually goes after parents in reopen-queue, so go from last
3864 QTAILQ_FOREACH_REVERSE(bs_entry
, bs_queue
, entry
) {
3865 bdrv_reopen_commit(&bs_entry
->state
);
3870 QTAILQ_FOREACH_SAFE(bs_entry
, bs_queue
, entry
, next
) {
3871 BDRVReopenState
*state
= &bs_entry
->state
;
3873 if (!bs_entry
->perms_checked
) {
3878 uint64_t perm
, shared
;
3880 bdrv_get_cumulative_perm(state
->bs
, &perm
, &shared
);
3881 assert(perm
== state
->perm
);
3882 assert(shared
== state
->shared_perm
);
3884 bdrv_set_perm(state
->bs
);
3886 bdrv_abort_perm_update(state
->bs
);
3887 if (state
->replace_backing_bs
&& state
->new_backing_bs
) {
3888 bdrv_abort_perm_update(state
->new_backing_bs
);
3894 QTAILQ_FOREACH_REVERSE(bs_entry
, bs_queue
, entry
) {
3895 BlockDriverState
*bs
= bs_entry
->state
.bs
;
3897 if (bs
->drv
->bdrv_reopen_commit_post
)
3898 bs
->drv
->bdrv_reopen_commit_post(&bs_entry
->state
);
3902 QTAILQ_FOREACH_SAFE(bs_entry
, bs_queue
, entry
, next
) {
3904 if (bs_entry
->prepared
) {
3905 bdrv_reopen_abort(&bs_entry
->state
);
3907 qobject_unref(bs_entry
->state
.explicit_options
);
3908 qobject_unref(bs_entry
->state
.options
);
3910 if (bs_entry
->state
.new_backing_bs
) {
3911 bdrv_unref(bs_entry
->state
.new_backing_bs
);
3920 int bdrv_reopen_set_read_only(BlockDriverState
*bs
, bool read_only
,
3924 BlockReopenQueue
*queue
;
3925 QDict
*opts
= qdict_new();
3927 qdict_put_bool(opts
, BDRV_OPT_READ_ONLY
, read_only
);
3929 bdrv_subtree_drained_begin(bs
);
3930 queue
= bdrv_reopen_queue(NULL
, bs
, opts
, true);
3931 ret
= bdrv_reopen_multiple(queue
, errp
);
3932 bdrv_subtree_drained_end(bs
);
3937 static BlockReopenQueueEntry
*find_parent_in_reopen_queue(BlockReopenQueue
*q
,
3940 BlockReopenQueueEntry
*entry
;
3942 QTAILQ_FOREACH(entry
, q
, entry
) {
3943 BlockDriverState
*bs
= entry
->state
.bs
;
3946 QLIST_FOREACH(child
, &bs
->children
, next
) {
3956 static void bdrv_reopen_perm(BlockReopenQueue
*q
, BlockDriverState
*bs
,
3957 uint64_t *perm
, uint64_t *shared
)
3960 BlockReopenQueueEntry
*parent
;
3961 uint64_t cumulative_perms
= 0;
3962 uint64_t cumulative_shared_perms
= BLK_PERM_ALL
;
3964 QLIST_FOREACH(c
, &bs
->parents
, next_parent
) {
3965 parent
= find_parent_in_reopen_queue(q
, c
);
3967 cumulative_perms
|= c
->perm
;
3968 cumulative_shared_perms
&= c
->shared_perm
;
3970 uint64_t nperm
, nshared
;
3972 bdrv_child_perm(parent
->state
.bs
, bs
, c
, c
->role
, q
,
3973 parent
->state
.perm
, parent
->state
.shared_perm
,
3976 cumulative_perms
|= nperm
;
3977 cumulative_shared_perms
&= nshared
;
3980 *perm
= cumulative_perms
;
3981 *shared
= cumulative_shared_perms
;
3984 static bool bdrv_reopen_can_attach(BlockDriverState
*parent
,
3986 BlockDriverState
*new_child
,
3989 AioContext
*parent_ctx
= bdrv_get_aio_context(parent
);
3990 AioContext
*child_ctx
= bdrv_get_aio_context(new_child
);
3994 ignore
= g_slist_prepend(NULL
, child
);
3995 ret
= bdrv_can_set_aio_context(new_child
, parent_ctx
, &ignore
, NULL
);
3996 g_slist_free(ignore
);
4001 ignore
= g_slist_prepend(NULL
, child
);
4002 ret
= bdrv_can_set_aio_context(parent
, child_ctx
, &ignore
, errp
);
4003 g_slist_free(ignore
);
4008 * Take a BDRVReopenState and check if the value of 'backing' in the
4009 * reopen_state->options QDict is valid or not.
4011 * If 'backing' is missing from the QDict then return 0.
4013 * If 'backing' contains the node name of the backing file of
4014 * reopen_state->bs then return 0.
4016 * If 'backing' contains a different node name (or is null) then check
4017 * whether the current backing file can be replaced with the new one.
4018 * If that's the case then reopen_state->replace_backing_bs is set to
4019 * true and reopen_state->new_backing_bs contains a pointer to the new
4020 * backing BlockDriverState (or NULL).
4022 * Return 0 on success, otherwise return < 0 and set @errp.
4024 static int bdrv_reopen_parse_backing(BDRVReopenState
*reopen_state
,
4027 BlockDriverState
*bs
= reopen_state
->bs
;
4028 BlockDriverState
*overlay_bs
, *below_bs
, *new_backing_bs
;
4032 value
= qdict_get(reopen_state
->options
, "backing");
4033 if (value
== NULL
) {
4037 switch (qobject_type(value
)) {
4039 new_backing_bs
= NULL
;
4042 str
= qstring_get_str(qobject_to(QString
, value
));
4043 new_backing_bs
= bdrv_lookup_bs(NULL
, str
, errp
);
4044 if (new_backing_bs
== NULL
) {
4046 } else if (bdrv_recurse_has_child(new_backing_bs
, bs
)) {
4047 error_setg(errp
, "Making '%s' a backing file of '%s' "
4048 "would create a cycle", str
, bs
->node_name
);
4053 /* 'backing' does not allow any other data type */
4054 g_assert_not_reached();
4058 * Check AioContext compatibility so that the bdrv_set_backing_hd() call in
4059 * bdrv_reopen_commit() won't fail.
4061 if (new_backing_bs
) {
4062 if (!bdrv_reopen_can_attach(bs
, bs
->backing
, new_backing_bs
, errp
)) {
4068 * Ensure that @bs can really handle backing files, because we are
4069 * about to give it one (or swap the existing one)
4071 if (bs
->drv
->is_filter
) {
4072 /* Filters always have a file or a backing child */
4074 error_setg(errp
, "'%s' is a %s filter node that does not support a "
4075 "backing child", bs
->node_name
, bs
->drv
->format_name
);
4078 } else if (!bs
->drv
->supports_backing
) {
4079 error_setg(errp
, "Driver '%s' of node '%s' does not support backing "
4080 "files", bs
->drv
->format_name
, bs
->node_name
);
4085 * Find the "actual" backing file by skipping all links that point
4086 * to an implicit node, if any (e.g. a commit filter node).
4087 * We cannot use any of the bdrv_skip_*() functions here because
4088 * those return the first explicit node, while we are looking for
4092 for (below_bs
= bdrv_filter_or_cow_bs(overlay_bs
);
4093 below_bs
&& below_bs
->implicit
;
4094 below_bs
= bdrv_filter_or_cow_bs(overlay_bs
))
4096 overlay_bs
= below_bs
;
4099 /* If we want to replace the backing file we need some extra checks */
4100 if (new_backing_bs
!= bdrv_filter_or_cow_bs(overlay_bs
)) {
4101 /* Check for implicit nodes between bs and its backing file */
4102 if (bs
!= overlay_bs
) {
4103 error_setg(errp
, "Cannot change backing link if '%s' has "
4104 "an implicit backing file", bs
->node_name
);
4108 * Check if the backing link that we want to replace is frozen.
4110 * bdrv_filter_or_cow_child(overlay_bs) == overlay_bs->backing,
4111 * because we know that overlay_bs == bs, and that @bs
4112 * either is a filter that uses ->backing or a COW format BDS
4113 * with bs->drv->supports_backing == true.
4115 if (bdrv_is_backing_chain_frozen(overlay_bs
,
4116 child_bs(overlay_bs
->backing
), errp
))
4120 reopen_state
->replace_backing_bs
= true;
4121 if (new_backing_bs
) {
4122 bdrv_ref(new_backing_bs
);
4123 reopen_state
->new_backing_bs
= new_backing_bs
;
4131 * Prepares a BlockDriverState for reopen. All changes are staged in the
4132 * 'opaque' field of the BDRVReopenState, which is used and allocated by
4133 * the block driver layer .bdrv_reopen_prepare()
4135 * bs is the BlockDriverState to reopen
4136 * flags are the new open flags
4137 * queue is the reopen queue
4139 * Returns 0 on success, non-zero on error. On error errp will be set
4142 * On failure, bdrv_reopen_abort() will be called to clean up any data.
4143 * It is the responsibility of the caller to then call the abort() or
4144 * commit() for any other BDS that have been left in a prepare() state
4147 int bdrv_reopen_prepare(BDRVReopenState
*reopen_state
, BlockReopenQueue
*queue
,
4152 Error
*local_err
= NULL
;
4155 QDict
*orig_reopen_opts
;
4156 char *discard
= NULL
;
4158 bool drv_prepared
= false;
4160 assert(reopen_state
!= NULL
);
4161 assert(reopen_state
->bs
->drv
!= NULL
);
4162 drv
= reopen_state
->bs
->drv
;
4164 /* This function and each driver's bdrv_reopen_prepare() remove
4165 * entries from reopen_state->options as they are processed, so
4166 * we need to make a copy of the original QDict. */
4167 orig_reopen_opts
= qdict_clone_shallow(reopen_state
->options
);
4169 /* Process generic block layer options */
4170 opts
= qemu_opts_create(&bdrv_runtime_opts
, NULL
, 0, &error_abort
);
4171 if (!qemu_opts_absorb_qdict(opts
, reopen_state
->options
, errp
)) {
4176 /* This was already called in bdrv_reopen_queue_child() so the flags
4177 * are up-to-date. This time we simply want to remove the options from
4178 * QemuOpts in order to indicate that they have been processed. */
4179 old_flags
= reopen_state
->flags
;
4180 update_flags_from_options(&reopen_state
->flags
, opts
);
4181 assert(old_flags
== reopen_state
->flags
);
4183 discard
= qemu_opt_get_del(opts
, BDRV_OPT_DISCARD
);
4184 if (discard
!= NULL
) {
4185 if (bdrv_parse_discard_flags(discard
, &reopen_state
->flags
) != 0) {
4186 error_setg(errp
, "Invalid discard option");
4192 reopen_state
->detect_zeroes
=
4193 bdrv_parse_detect_zeroes(opts
, reopen_state
->flags
, &local_err
);
4195 error_propagate(errp
, local_err
);
4200 /* All other options (including node-name and driver) must be unchanged.
4201 * Put them back into the QDict, so that they are checked at the end
4202 * of this function. */
4203 qemu_opts_to_qdict(opts
, reopen_state
->options
);
4205 /* If we are to stay read-only, do not allow permission change
4206 * to r/w. Attempting to set to r/w may fail if either BDRV_O_ALLOW_RDWR is
4207 * not set, or if the BDS still has copy_on_read enabled */
4208 read_only
= !(reopen_state
->flags
& BDRV_O_RDWR
);
4209 ret
= bdrv_can_set_read_only(reopen_state
->bs
, read_only
, true, &local_err
);
4211 error_propagate(errp
, local_err
);
4215 /* Calculate required permissions after reopening */
4216 bdrv_reopen_perm(queue
, reopen_state
->bs
,
4217 &reopen_state
->perm
, &reopen_state
->shared_perm
);
4219 ret
= bdrv_flush(reopen_state
->bs
);
4221 error_setg_errno(errp
, -ret
, "Error flushing drive");
4225 if (drv
->bdrv_reopen_prepare
) {
4227 * If a driver-specific option is missing, it means that we
4228 * should reset it to its default value.
4229 * But not all options allow that, so we need to check it first.
4231 ret
= bdrv_reset_options_allowed(reopen_state
->bs
,
4232 reopen_state
->options
, errp
);
4237 ret
= drv
->bdrv_reopen_prepare(reopen_state
, queue
, &local_err
);
4239 if (local_err
!= NULL
) {
4240 error_propagate(errp
, local_err
);
4242 bdrv_refresh_filename(reopen_state
->bs
);
4243 error_setg(errp
, "failed while preparing to reopen image '%s'",
4244 reopen_state
->bs
->filename
);
4249 /* It is currently mandatory to have a bdrv_reopen_prepare()
4250 * handler for each supported drv. */
4251 error_setg(errp
, "Block format '%s' used by node '%s' "
4252 "does not support reopening files", drv
->format_name
,
4253 bdrv_get_device_or_node_name(reopen_state
->bs
));
4258 drv_prepared
= true;
4261 * We must provide the 'backing' option if the BDS has a backing
4262 * file or if the image file has a backing file name as part of
4263 * its metadata. Otherwise the 'backing' option can be omitted.
4265 if (drv
->supports_backing
&& reopen_state
->backing_missing
&&
4266 (reopen_state
->bs
->backing
|| reopen_state
->bs
->backing_file
[0])) {
4267 error_setg(errp
, "backing is missing for '%s'",
4268 reopen_state
->bs
->node_name
);
4274 * Allow changing the 'backing' option. The new value can be
4275 * either a reference to an existing node (using its node name)
4276 * or NULL to simply detach the current backing file.
4278 ret
= bdrv_reopen_parse_backing(reopen_state
, errp
);
4282 qdict_del(reopen_state
->options
, "backing");
4284 /* Options that are not handled are only okay if they are unchanged
4285 * compared to the old state. It is expected that some options are only
4286 * used for the initial open, but not reopen (e.g. filename) */
4287 if (qdict_size(reopen_state
->options
)) {
4288 const QDictEntry
*entry
= qdict_first(reopen_state
->options
);
4291 QObject
*new = entry
->value
;
4292 QObject
*old
= qdict_get(reopen_state
->bs
->options
, entry
->key
);
4294 /* Allow child references (child_name=node_name) as long as they
4295 * point to the current child (i.e. everything stays the same). */
4296 if (qobject_type(new) == QTYPE_QSTRING
) {
4298 QLIST_FOREACH(child
, &reopen_state
->bs
->children
, next
) {
4299 if (!strcmp(child
->name
, entry
->key
)) {
4305 if (!strcmp(child
->bs
->node_name
,
4306 qstring_get_str(qobject_to(QString
, new)))) {
4307 continue; /* Found child with this name, skip option */
4313 * TODO: When using -drive to specify blockdev options, all values
4314 * will be strings; however, when using -blockdev, blockdev-add or
4315 * filenames using the json:{} pseudo-protocol, they will be
4317 * In contrast, reopening options are (currently) always strings
4318 * (because you can only specify them through qemu-io; all other
4319 * callers do not specify any options).
4320 * Therefore, when using anything other than -drive to create a BDS,
4321 * this cannot detect non-string options as unchanged, because
4322 * qobject_is_equal() always returns false for objects of different
4323 * type. In the future, this should be remedied by correctly typing
4324 * all options. For now, this is not too big of an issue because
4325 * the user can simply omit options which cannot be changed anyway,
4326 * so they will stay unchanged.
4328 if (!qobject_is_equal(new, old
)) {
4329 error_setg(errp
, "Cannot change the option '%s'", entry
->key
);
4333 } while ((entry
= qdict_next(reopen_state
->options
, entry
)));
4338 /* Restore the original reopen_state->options QDict */
4339 qobject_unref(reopen_state
->options
);
4340 reopen_state
->options
= qobject_ref(orig_reopen_opts
);
4343 if (ret
< 0 && drv_prepared
) {
4344 /* drv->bdrv_reopen_prepare() has succeeded, so we need to
4345 * call drv->bdrv_reopen_abort() before signaling an error
4346 * (bdrv_reopen_multiple() will not call bdrv_reopen_abort()
4347 * when the respective bdrv_reopen_prepare() has failed) */
4348 if (drv
->bdrv_reopen_abort
) {
4349 drv
->bdrv_reopen_abort(reopen_state
);
4352 qemu_opts_del(opts
);
4353 qobject_unref(orig_reopen_opts
);
4359 * Takes the staged changes for the reopen from bdrv_reopen_prepare(), and
4360 * makes them final by swapping the staging BlockDriverState contents into
4361 * the active BlockDriverState contents.
4363 void bdrv_reopen_commit(BDRVReopenState
*reopen_state
)
4366 BlockDriverState
*bs
;
4369 assert(reopen_state
!= NULL
);
4370 bs
= reopen_state
->bs
;
4372 assert(drv
!= NULL
);
4374 /* If there are any driver level actions to take */
4375 if (drv
->bdrv_reopen_commit
) {
4376 drv
->bdrv_reopen_commit(reopen_state
);
4379 /* set BDS specific flags now */
4380 qobject_unref(bs
->explicit_options
);
4381 qobject_unref(bs
->options
);
4383 bs
->explicit_options
= reopen_state
->explicit_options
;
4384 bs
->options
= reopen_state
->options
;
4385 bs
->open_flags
= reopen_state
->flags
;
4386 bs
->read_only
= !(reopen_state
->flags
& BDRV_O_RDWR
);
4387 bs
->detect_zeroes
= reopen_state
->detect_zeroes
;
4389 if (reopen_state
->replace_backing_bs
) {
4390 qdict_del(bs
->explicit_options
, "backing");
4391 qdict_del(bs
->options
, "backing");
4394 /* Remove child references from bs->options and bs->explicit_options.
4395 * Child options were already removed in bdrv_reopen_queue_child() */
4396 QLIST_FOREACH(child
, &bs
->children
, next
) {
4397 qdict_del(bs
->explicit_options
, child
->name
);
4398 qdict_del(bs
->options
, child
->name
);
4402 * Change the backing file if a new one was specified. We do this
4403 * after updating bs->options, so bdrv_refresh_filename() (called
4404 * from bdrv_set_backing_hd()) has the new values.
4406 if (reopen_state
->replace_backing_bs
) {
4407 BlockDriverState
*old_backing_bs
= child_bs(bs
->backing
);
4408 assert(!old_backing_bs
|| !old_backing_bs
->implicit
);
4409 /* Abort the permission update on the backing bs we're detaching */
4410 if (old_backing_bs
) {
4411 bdrv_abort_perm_update(old_backing_bs
);
4413 bdrv_set_backing_hd(bs
, reopen_state
->new_backing_bs
, &error_abort
);
4416 bdrv_refresh_limits(bs
, NULL
);
4420 * Abort the reopen, and delete and free the staged changes in
4423 void bdrv_reopen_abort(BDRVReopenState
*reopen_state
)
4427 assert(reopen_state
!= NULL
);
4428 drv
= reopen_state
->bs
->drv
;
4429 assert(drv
!= NULL
);
4431 if (drv
->bdrv_reopen_abort
) {
4432 drv
->bdrv_reopen_abort(reopen_state
);
4437 static void bdrv_close(BlockDriverState
*bs
)
4439 BdrvAioNotifier
*ban
, *ban_next
;
4440 BdrvChild
*child
, *next
;
4442 assert(!bs
->refcnt
);
4444 bdrv_drained_begin(bs
); /* complete I/O */
4446 bdrv_drain(bs
); /* in case flush left pending I/O */
4449 if (bs
->drv
->bdrv_close
) {
4450 /* Must unfreeze all children, so bdrv_unref_child() works */
4451 bs
->drv
->bdrv_close(bs
);
4456 QLIST_FOREACH_SAFE(child
, &bs
->children
, next
, next
) {
4457 bdrv_unref_child(bs
, child
);
4464 qatomic_set(&bs
->copy_on_read
, 0);
4465 bs
->backing_file
[0] = '\0';
4466 bs
->backing_format
[0] = '\0';
4467 bs
->total_sectors
= 0;
4468 bs
->encrypted
= false;
4470 qobject_unref(bs
->options
);
4471 qobject_unref(bs
->explicit_options
);
4473 bs
->explicit_options
= NULL
;
4474 qobject_unref(bs
->full_open_options
);
4475 bs
->full_open_options
= NULL
;
4477 bdrv_release_named_dirty_bitmaps(bs
);
4478 assert(QLIST_EMPTY(&bs
->dirty_bitmaps
));
4480 QLIST_FOREACH_SAFE(ban
, &bs
->aio_notifiers
, list
, ban_next
) {
4483 QLIST_INIT(&bs
->aio_notifiers
);
4484 bdrv_drained_end(bs
);
4487 * If we're still inside some bdrv_drain_all_begin()/end() sections, end
4488 * them now since this BDS won't exist anymore when bdrv_drain_all_end()
4491 if (bs
->quiesce_counter
) {
4492 bdrv_drain_all_end_quiesce(bs
);
4496 void bdrv_close_all(void)
4498 assert(job_next(NULL
) == NULL
);
4500 /* Drop references from requests still in flight, such as canceled block
4501 * jobs whose AIO context has not been polled yet */
4504 blk_remove_all_bs();
4505 blockdev_close_all_bdrv_states();
4507 assert(QTAILQ_EMPTY(&all_bdrv_states
));
4510 static bool should_update_child(BdrvChild
*c
, BlockDriverState
*to
)
4516 if (c
->klass
->stay_at_node
) {
4520 /* If the child @c belongs to the BDS @to, replacing the current
4521 * c->bs by @to would mean to create a loop.
4523 * Such a case occurs when appending a BDS to a backing chain.
4524 * For instance, imagine the following chain:
4526 * guest device -> node A -> further backing chain...
4528 * Now we create a new BDS B which we want to put on top of this
4529 * chain, so we first attach A as its backing node:
4534 * guest device -> node A -> further backing chain...
4536 * Finally we want to replace A by B. When doing that, we want to
4537 * replace all pointers to A by pointers to B -- except for the
4538 * pointer from B because (1) that would create a loop, and (2)
4539 * that pointer should simply stay intact:
4541 * guest device -> node B
4544 * node A -> further backing chain...
4546 * In general, when replacing a node A (c->bs) by a node B (@to),
4547 * if A is a child of B, that means we cannot replace A by B there
4548 * because that would create a loop. Silently detaching A from B
4549 * is also not really an option. So overall just leaving A in
4550 * place there is the most sensible choice.
4552 * We would also create a loop in any cases where @c is only
4553 * indirectly referenced by @to. Prevent this by returning false
4554 * if @c is found (by breadth-first search) anywhere in the whole
4559 found
= g_hash_table_new(NULL
, NULL
);
4560 g_hash_table_add(found
, to
);
4561 queue
= g_queue_new();
4562 g_queue_push_tail(queue
, to
);
4564 while (!g_queue_is_empty(queue
)) {
4565 BlockDriverState
*v
= g_queue_pop_head(queue
);
4568 QLIST_FOREACH(c2
, &v
->children
, next
) {
4574 if (g_hash_table_contains(found
, c2
->bs
)) {
4578 g_queue_push_tail(queue
, c2
->bs
);
4579 g_hash_table_add(found
, c2
->bs
);
4583 g_queue_free(queue
);
4584 g_hash_table_destroy(found
);
4590 * With auto_skip=true bdrv_replace_node_common skips updating from parents
4591 * if it creates a parent-child relation loop or if parent is block-job.
4593 * With auto_skip=false the error is returned if from has a parent which should
4596 static int bdrv_replace_node_common(BlockDriverState
*from
,
4597 BlockDriverState
*to
,
4598 bool auto_skip
, Error
**errp
)
4600 BdrvChild
*c
, *next
;
4601 GSList
*list
= NULL
, *p
;
4602 uint64_t perm
= 0, shared
= BLK_PERM_ALL
;
4605 /* Make sure that @from doesn't go away until we have successfully attached
4606 * all of its parents to @to. */
4609 assert(qemu_get_current_aio_context() == qemu_get_aio_context());
4610 assert(bdrv_get_aio_context(from
) == bdrv_get_aio_context(to
));
4611 bdrv_drained_begin(from
);
4613 /* Put all parents into @list and calculate their cumulative permissions */
4614 QLIST_FOREACH_SAFE(c
, &from
->parents
, next_parent
, next
) {
4615 assert(c
->bs
== from
);
4616 if (!should_update_child(c
, to
)) {
4621 error_setg(errp
, "Should not change '%s' link to '%s'",
4622 c
->name
, from
->node_name
);
4627 error_setg(errp
, "Cannot change '%s' link to '%s'",
4628 c
->name
, from
->node_name
);
4631 list
= g_slist_prepend(list
, c
);
4633 shared
&= c
->shared_perm
;
4636 /* Check whether the required permissions can be granted on @to, ignoring
4637 * all BdrvChild in @list so that they can't block themselves. */
4638 ret
= bdrv_check_update_perm(to
, NULL
, perm
, shared
, list
, errp
);
4640 bdrv_abort_perm_update(to
);
4644 /* Now actually perform the change. We performed the permission check for
4645 * all elements of @list at once, so set the permissions all at once at the
4647 for (p
= list
; p
!= NULL
; p
= p
->next
) {
4651 bdrv_replace_child_noperm(c
, to
);
4661 bdrv_drained_end(from
);
4667 int bdrv_replace_node(BlockDriverState
*from
, BlockDriverState
*to
,
4670 return bdrv_replace_node_common(from
, to
, true, errp
);
4674 * Add new bs contents at the top of an image chain while the chain is
4675 * live, while keeping required fields on the top layer.
4677 * This will modify the BlockDriverState fields, and swap contents
4678 * between bs_new and bs_top. Both bs_new and bs_top are modified.
4680 * bs_new must not be attached to a BlockBackend.
4682 * This function does not create any image files.
4684 * bdrv_append() takes ownership of a bs_new reference and unrefs it because
4685 * that's what the callers commonly need. bs_new will be referenced by the old
4686 * parents of bs_top after bdrv_append() returns. If the caller needs to keep a
4687 * reference of its own, it must call bdrv_ref().
4689 int bdrv_append(BlockDriverState
*bs_new
, BlockDriverState
*bs_top
,
4692 int ret
= bdrv_set_backing_hd(bs_new
, bs_top
, errp
);
4697 ret
= bdrv_replace_node(bs_top
, bs_new
, errp
);
4699 bdrv_set_backing_hd(bs_new
, NULL
, &error_abort
);
4707 * bs_new is now referenced by its new parents, we don't need the
4708 * additional reference any more.
4715 static void bdrv_delete(BlockDriverState
*bs
)
4717 assert(bdrv_op_blocker_is_empty(bs
));
4718 assert(!bs
->refcnt
);
4720 /* remove from list, if necessary */
4721 if (bs
->node_name
[0] != '\0') {
4722 QTAILQ_REMOVE(&graph_bdrv_states
, bs
, node_list
);
4724 QTAILQ_REMOVE(&all_bdrv_states
, bs
, bs_list
);
4731 BlockDriverState
*bdrv_insert_node(BlockDriverState
*bs
, QDict
*node_options
,
4732 int flags
, Error
**errp
)
4734 BlockDriverState
*new_node_bs
;
4735 Error
*local_err
= NULL
;
4737 new_node_bs
= bdrv_open(NULL
, NULL
, node_options
, flags
, errp
);
4738 if (new_node_bs
== NULL
) {
4739 error_prepend(errp
, "Could not create node: ");
4743 bdrv_drained_begin(bs
);
4744 bdrv_replace_node(bs
, new_node_bs
, &local_err
);
4745 bdrv_drained_end(bs
);
4748 bdrv_unref(new_node_bs
);
4749 error_propagate(errp
, local_err
);
4757 * Run consistency checks on an image
4759 * Returns 0 if the check could be completed (it doesn't mean that the image is
4760 * free of errors) or -errno when an internal error occurred. The results of the
4761 * check are stored in res.
4763 int coroutine_fn
bdrv_co_check(BlockDriverState
*bs
,
4764 BdrvCheckResult
*res
, BdrvCheckMode fix
)
4766 if (bs
->drv
== NULL
) {
4769 if (bs
->drv
->bdrv_co_check
== NULL
) {
4773 memset(res
, 0, sizeof(*res
));
4774 return bs
->drv
->bdrv_co_check(bs
, res
, fix
);
4780 * -EINVAL - backing format specified, but no file
4781 * -ENOSPC - can't update the backing file because no space is left in the
4783 * -ENOTSUP - format driver doesn't support changing the backing file
4785 int bdrv_change_backing_file(BlockDriverState
*bs
, const char *backing_file
,
4786 const char *backing_fmt
, bool warn
)
4788 BlockDriver
*drv
= bs
->drv
;
4795 /* Backing file format doesn't make sense without a backing file */
4796 if (backing_fmt
&& !backing_file
) {
4800 if (warn
&& backing_file
&& !backing_fmt
) {
4801 warn_report("Deprecated use of backing file without explicit "
4802 "backing format, use of this image requires "
4803 "potentially unsafe format probing");
4806 if (drv
->bdrv_change_backing_file
!= NULL
) {
4807 ret
= drv
->bdrv_change_backing_file(bs
, backing_file
, backing_fmt
);
4813 pstrcpy(bs
->backing_file
, sizeof(bs
->backing_file
), backing_file
?: "");
4814 pstrcpy(bs
->backing_format
, sizeof(bs
->backing_format
), backing_fmt
?: "");
4815 pstrcpy(bs
->auto_backing_file
, sizeof(bs
->auto_backing_file
),
4816 backing_file
?: "");
4822 * Finds the first non-filter node above bs in the chain between
4823 * active and bs. The returned node is either an immediate parent of
4824 * bs, or there are only filter nodes between the two.
4826 * Returns NULL if bs is not found in active's image chain,
4827 * or if active == bs.
4829 * Returns the bottommost base image if bs == NULL.
4831 BlockDriverState
*bdrv_find_overlay(BlockDriverState
*active
,
4832 BlockDriverState
*bs
)
4834 bs
= bdrv_skip_filters(bs
);
4835 active
= bdrv_skip_filters(active
);
4838 BlockDriverState
*next
= bdrv_backing_chain_next(active
);
4848 /* Given a BDS, searches for the base layer. */
4849 BlockDriverState
*bdrv_find_base(BlockDriverState
*bs
)
4851 return bdrv_find_overlay(bs
, NULL
);
4855 * Return true if at least one of the COW (backing) and filter links
4856 * between @bs and @base is frozen. @errp is set if that's the case.
4857 * @base must be reachable from @bs, or NULL.
4859 bool bdrv_is_backing_chain_frozen(BlockDriverState
*bs
, BlockDriverState
*base
,
4862 BlockDriverState
*i
;
4865 for (i
= bs
; i
!= base
; i
= child_bs(child
)) {
4866 child
= bdrv_filter_or_cow_child(i
);
4868 if (child
&& child
->frozen
) {
4869 error_setg(errp
, "Cannot change '%s' link from '%s' to '%s'",
4870 child
->name
, i
->node_name
, child
->bs
->node_name
);
4879 * Freeze all COW (backing) and filter links between @bs and @base.
4880 * If any of the links is already frozen the operation is aborted and
4881 * none of the links are modified.
4882 * @base must be reachable from @bs, or NULL.
4883 * Returns 0 on success. On failure returns < 0 and sets @errp.
4885 int bdrv_freeze_backing_chain(BlockDriverState
*bs
, BlockDriverState
*base
,
4888 BlockDriverState
*i
;
4891 if (bdrv_is_backing_chain_frozen(bs
, base
, errp
)) {
4895 for (i
= bs
; i
!= base
; i
= child_bs(child
)) {
4896 child
= bdrv_filter_or_cow_child(i
);
4897 if (child
&& child
->bs
->never_freeze
) {
4898 error_setg(errp
, "Cannot freeze '%s' link to '%s'",
4899 child
->name
, child
->bs
->node_name
);
4904 for (i
= bs
; i
!= base
; i
= child_bs(child
)) {
4905 child
= bdrv_filter_or_cow_child(i
);
4907 child
->frozen
= true;
4915 * Unfreeze all COW (backing) and filter links between @bs and @base.
4916 * The caller must ensure that all links are frozen before using this
4918 * @base must be reachable from @bs, or NULL.
4920 void bdrv_unfreeze_backing_chain(BlockDriverState
*bs
, BlockDriverState
*base
)
4922 BlockDriverState
*i
;
4925 for (i
= bs
; i
!= base
; i
= child_bs(child
)) {
4926 child
= bdrv_filter_or_cow_child(i
);
4928 assert(child
->frozen
);
4929 child
->frozen
= false;
4935 * Drops images above 'base' up to and including 'top', and sets the image
4936 * above 'top' to have base as its backing file.
4938 * Requires that the overlay to 'top' is opened r/w, so that the backing file
4939 * information in 'bs' can be properly updated.
4941 * E.g., this will convert the following chain:
4942 * bottom <- base <- intermediate <- top <- active
4946 * bottom <- base <- active
4948 * It is allowed for bottom==base, in which case it converts:
4950 * base <- intermediate <- top <- active
4956 * If backing_file_str is non-NULL, it will be used when modifying top's
4957 * overlay image metadata.
4960 * if active == top, that is considered an error
4963 int bdrv_drop_intermediate(BlockDriverState
*top
, BlockDriverState
*base
,
4964 const char *backing_file_str
)
4966 BlockDriverState
*explicit_top
= top
;
4967 bool update_inherits_from
;
4969 Error
*local_err
= NULL
;
4971 g_autoptr(GSList
) updated_children
= NULL
;
4975 bdrv_subtree_drained_begin(top
);
4977 if (!top
->drv
|| !base
->drv
) {
4981 /* Make sure that base is in the backing chain of top */
4982 if (!bdrv_chain_contains(top
, base
)) {
4986 /* If 'base' recursively inherits from 'top' then we should set
4987 * base->inherits_from to top->inherits_from after 'top' and all
4988 * other intermediate nodes have been dropped.
4989 * If 'top' is an implicit node (e.g. "commit_top") we should skip
4990 * it because no one inherits from it. We use explicit_top for that. */
4991 explicit_top
= bdrv_skip_implicit_filters(explicit_top
);
4992 update_inherits_from
= bdrv_inherits_from_recursive(base
, explicit_top
);
4994 /* success - we can delete the intermediate states, and link top->base */
4995 /* TODO Check graph modification op blockers (BLK_PERM_GRAPH_MOD) once
4996 * we've figured out how they should work. */
4997 if (!backing_file_str
) {
4998 bdrv_refresh_filename(base
);
4999 backing_file_str
= base
->filename
;
5002 QLIST_FOREACH(c
, &top
->parents
, next_parent
) {
5003 updated_children
= g_slist_prepend(updated_children
, c
);
5006 bdrv_replace_node_common(top
, base
, false, &local_err
);
5008 error_report_err(local_err
);
5012 for (p
= updated_children
; p
; p
= p
->next
) {
5015 if (c
->klass
->update_filename
) {
5016 ret
= c
->klass
->update_filename(c
, base
, backing_file_str
,
5020 * TODO: Actually, we want to rollback all previous iterations
5021 * of this loop, and (which is almost impossible) previous
5022 * bdrv_replace_node()...
5024 * Note, that c->klass->update_filename may lead to permission
5025 * update, so it's a bad idea to call it inside permission
5026 * update transaction of bdrv_replace_node.
5028 error_report_err(local_err
);
5034 if (update_inherits_from
) {
5035 base
->inherits_from
= explicit_top
->inherits_from
;
5040 bdrv_subtree_drained_end(top
);
5046 * Implementation of BlockDriver.bdrv_get_allocated_file_size() that
5047 * sums the size of all data-bearing children. (This excludes backing
5050 static int64_t bdrv_sum_allocated_file_size(BlockDriverState
*bs
)
5053 int64_t child_size
, sum
= 0;
5055 QLIST_FOREACH(child
, &bs
->children
, next
) {
5056 if (child
->role
& (BDRV_CHILD_DATA
| BDRV_CHILD_METADATA
|
5057 BDRV_CHILD_FILTERED
))
5059 child_size
= bdrv_get_allocated_file_size(child
->bs
);
5060 if (child_size
< 0) {
5071 * Length of a allocated file in bytes. Sparse files are counted by actual
5072 * allocated space. Return < 0 if error or unknown.
5074 int64_t bdrv_get_allocated_file_size(BlockDriverState
*bs
)
5076 BlockDriver
*drv
= bs
->drv
;
5080 if (drv
->bdrv_get_allocated_file_size
) {
5081 return drv
->bdrv_get_allocated_file_size(bs
);
5084 if (drv
->bdrv_file_open
) {
5086 * Protocol drivers default to -ENOTSUP (most of their data is
5087 * not stored in any of their children (if they even have any),
5088 * so there is no generic way to figure it out).
5091 } else if (drv
->is_filter
) {
5092 /* Filter drivers default to the size of their filtered child */
5093 return bdrv_get_allocated_file_size(bdrv_filter_bs(bs
));
5095 /* Other drivers default to summing their children's sizes */
5096 return bdrv_sum_allocated_file_size(bs
);
5102 * @drv: Format driver
5103 * @opts: Creation options for new image
5104 * @in_bs: Existing image containing data for new image (may be NULL)
5105 * @errp: Error object
5106 * Returns: A #BlockMeasureInfo (free using qapi_free_BlockMeasureInfo())
5109 * Calculate file size required to create a new image.
5111 * If @in_bs is given then space for allocated clusters and zero clusters
5112 * from that image are included in the calculation. If @opts contains a
5113 * backing file that is shared by @in_bs then backing clusters may be omitted
5114 * from the calculation.
5116 * If @in_bs is NULL then the calculation includes no allocated clusters
5117 * unless a preallocation option is given in @opts.
5119 * Note that @in_bs may use a different BlockDriver from @drv.
5121 * If an error occurs the @errp pointer is set.
5123 BlockMeasureInfo
*bdrv_measure(BlockDriver
*drv
, QemuOpts
*opts
,
5124 BlockDriverState
*in_bs
, Error
**errp
)
5126 if (!drv
->bdrv_measure
) {
5127 error_setg(errp
, "Block driver '%s' does not support size measurement",
5132 return drv
->bdrv_measure(opts
, in_bs
, errp
);
5136 * Return number of sectors on success, -errno on error.
5138 int64_t bdrv_nb_sectors(BlockDriverState
*bs
)
5140 BlockDriver
*drv
= bs
->drv
;
5145 if (drv
->has_variable_length
) {
5146 int ret
= refresh_total_sectors(bs
, bs
->total_sectors
);
5151 return bs
->total_sectors
;
5155 * Return length in bytes on success, -errno on error.
5156 * The length is always a multiple of BDRV_SECTOR_SIZE.
5158 int64_t bdrv_getlength(BlockDriverState
*bs
)
5160 int64_t ret
= bdrv_nb_sectors(bs
);
5165 if (ret
> INT64_MAX
/ BDRV_SECTOR_SIZE
) {
5168 return ret
* BDRV_SECTOR_SIZE
;
5171 /* return 0 as number of sectors if no device present or error */
5172 void bdrv_get_geometry(BlockDriverState
*bs
, uint64_t *nb_sectors_ptr
)
5174 int64_t nb_sectors
= bdrv_nb_sectors(bs
);
5176 *nb_sectors_ptr
= nb_sectors
< 0 ? 0 : nb_sectors
;
5179 bool bdrv_is_sg(BlockDriverState
*bs
)
5185 * Return whether the given node supports compressed writes.
5187 bool bdrv_supports_compressed_writes(BlockDriverState
*bs
)
5189 BlockDriverState
*filtered
;
5191 if (!bs
->drv
|| !block_driver_can_compress(bs
->drv
)) {
5195 filtered
= bdrv_filter_bs(bs
);
5198 * Filters can only forward compressed writes, so we have to
5201 return bdrv_supports_compressed_writes(filtered
);
5207 const char *bdrv_get_format_name(BlockDriverState
*bs
)
5209 return bs
->drv
? bs
->drv
->format_name
: NULL
;
5212 static int qsort_strcmp(const void *a
, const void *b
)
5214 return strcmp(*(char *const *)a
, *(char *const *)b
);
5217 void bdrv_iterate_format(void (*it
)(void *opaque
, const char *name
),
5218 void *opaque
, bool read_only
)
5223 const char **formats
= NULL
;
5225 QLIST_FOREACH(drv
, &bdrv_drivers
, list
) {
5226 if (drv
->format_name
) {
5230 if (use_bdrv_whitelist
&& !bdrv_is_whitelisted(drv
, read_only
)) {
5234 while (formats
&& i
&& !found
) {
5235 found
= !strcmp(formats
[--i
], drv
->format_name
);
5239 formats
= g_renew(const char *, formats
, count
+ 1);
5240 formats
[count
++] = drv
->format_name
;
5245 for (i
= 0; i
< (int)ARRAY_SIZE(block_driver_modules
); i
++) {
5246 const char *format_name
= block_driver_modules
[i
].format_name
;
5252 if (use_bdrv_whitelist
&&
5253 !bdrv_format_is_whitelisted(format_name
, read_only
)) {
5257 while (formats
&& j
&& !found
) {
5258 found
= !strcmp(formats
[--j
], format_name
);
5262 formats
= g_renew(const char *, formats
, count
+ 1);
5263 formats
[count
++] = format_name
;
5268 qsort(formats
, count
, sizeof(formats
[0]), qsort_strcmp
);
5270 for (i
= 0; i
< count
; i
++) {
5271 it(opaque
, formats
[i
]);
5277 /* This function is to find a node in the bs graph */
5278 BlockDriverState
*bdrv_find_node(const char *node_name
)
5280 BlockDriverState
*bs
;
5284 QTAILQ_FOREACH(bs
, &graph_bdrv_states
, node_list
) {
5285 if (!strcmp(node_name
, bs
->node_name
)) {
5292 /* Put this QMP function here so it can access the static graph_bdrv_states. */
5293 BlockDeviceInfoList
*bdrv_named_nodes_list(bool flat
,
5296 BlockDeviceInfoList
*list
;
5297 BlockDriverState
*bs
;
5300 QTAILQ_FOREACH(bs
, &graph_bdrv_states
, node_list
) {
5301 BlockDeviceInfo
*info
= bdrv_block_device_info(NULL
, bs
, flat
, errp
);
5303 qapi_free_BlockDeviceInfoList(list
);
5306 QAPI_LIST_PREPEND(list
, info
);
5312 typedef struct XDbgBlockGraphConstructor
{
5313 XDbgBlockGraph
*graph
;
5314 GHashTable
*graph_nodes
;
5315 } XDbgBlockGraphConstructor
;
5317 static XDbgBlockGraphConstructor
*xdbg_graph_new(void)
5319 XDbgBlockGraphConstructor
*gr
= g_new(XDbgBlockGraphConstructor
, 1);
5321 gr
->graph
= g_new0(XDbgBlockGraph
, 1);
5322 gr
->graph_nodes
= g_hash_table_new(NULL
, NULL
);
5327 static XDbgBlockGraph
*xdbg_graph_finalize(XDbgBlockGraphConstructor
*gr
)
5329 XDbgBlockGraph
*graph
= gr
->graph
;
5331 g_hash_table_destroy(gr
->graph_nodes
);
5337 static uintptr_t xdbg_graph_node_num(XDbgBlockGraphConstructor
*gr
, void *node
)
5339 uintptr_t ret
= (uintptr_t)g_hash_table_lookup(gr
->graph_nodes
, node
);
5346 * Start counting from 1, not 0, because 0 interferes with not-found (NULL)
5347 * answer of g_hash_table_lookup.
5349 ret
= g_hash_table_size(gr
->graph_nodes
) + 1;
5350 g_hash_table_insert(gr
->graph_nodes
, node
, (void *)ret
);
5355 static void xdbg_graph_add_node(XDbgBlockGraphConstructor
*gr
, void *node
,
5356 XDbgBlockGraphNodeType type
, const char *name
)
5358 XDbgBlockGraphNode
*n
;
5360 n
= g_new0(XDbgBlockGraphNode
, 1);
5362 n
->id
= xdbg_graph_node_num(gr
, node
);
5364 n
->name
= g_strdup(name
);
5366 QAPI_LIST_PREPEND(gr
->graph
->nodes
, n
);
5369 static void xdbg_graph_add_edge(XDbgBlockGraphConstructor
*gr
, void *parent
,
5370 const BdrvChild
*child
)
5372 BlockPermission qapi_perm
;
5373 XDbgBlockGraphEdge
*edge
;
5375 edge
= g_new0(XDbgBlockGraphEdge
, 1);
5377 edge
->parent
= xdbg_graph_node_num(gr
, parent
);
5378 edge
->child
= xdbg_graph_node_num(gr
, child
->bs
);
5379 edge
->name
= g_strdup(child
->name
);
5381 for (qapi_perm
= 0; qapi_perm
< BLOCK_PERMISSION__MAX
; qapi_perm
++) {
5382 uint64_t flag
= bdrv_qapi_perm_to_blk_perm(qapi_perm
);
5384 if (flag
& child
->perm
) {
5385 QAPI_LIST_PREPEND(edge
->perm
, qapi_perm
);
5387 if (flag
& child
->shared_perm
) {
5388 QAPI_LIST_PREPEND(edge
->shared_perm
, qapi_perm
);
5392 QAPI_LIST_PREPEND(gr
->graph
->edges
, edge
);
5396 XDbgBlockGraph
*bdrv_get_xdbg_block_graph(Error
**errp
)
5400 BlockDriverState
*bs
;
5402 XDbgBlockGraphConstructor
*gr
= xdbg_graph_new();
5404 for (blk
= blk_all_next(NULL
); blk
; blk
= blk_all_next(blk
)) {
5405 char *allocated_name
= NULL
;
5406 const char *name
= blk_name(blk
);
5409 name
= allocated_name
= blk_get_attached_dev_id(blk
);
5411 xdbg_graph_add_node(gr
, blk
, X_DBG_BLOCK_GRAPH_NODE_TYPE_BLOCK_BACKEND
,
5413 g_free(allocated_name
);
5414 if (blk_root(blk
)) {
5415 xdbg_graph_add_edge(gr
, blk
, blk_root(blk
));
5419 for (job
= block_job_next(NULL
); job
; job
= block_job_next(job
)) {
5422 xdbg_graph_add_node(gr
, job
, X_DBG_BLOCK_GRAPH_NODE_TYPE_BLOCK_JOB
,
5424 for (el
= job
->nodes
; el
; el
= el
->next
) {
5425 xdbg_graph_add_edge(gr
, job
, (BdrvChild
*)el
->data
);
5429 QTAILQ_FOREACH(bs
, &graph_bdrv_states
, node_list
) {
5430 xdbg_graph_add_node(gr
, bs
, X_DBG_BLOCK_GRAPH_NODE_TYPE_BLOCK_DRIVER
,
5432 QLIST_FOREACH(child
, &bs
->children
, next
) {
5433 xdbg_graph_add_edge(gr
, bs
, child
);
5437 return xdbg_graph_finalize(gr
);
5440 BlockDriverState
*bdrv_lookup_bs(const char *device
,
5441 const char *node_name
,
5445 BlockDriverState
*bs
;
5448 blk
= blk_by_name(device
);
5453 error_setg(errp
, "Device '%s' has no medium", device
);
5461 bs
= bdrv_find_node(node_name
);
5468 error_setg(errp
, "Cannot find device=\'%s\' nor node-name=\'%s\'",
5469 device
? device
: "",
5470 node_name
? node_name
: "");
5474 /* If 'base' is in the same chain as 'top', return true. Otherwise,
5475 * return false. If either argument is NULL, return false. */
5476 bool bdrv_chain_contains(BlockDriverState
*top
, BlockDriverState
*base
)
5478 while (top
&& top
!= base
) {
5479 top
= bdrv_filter_or_cow_bs(top
);
5485 BlockDriverState
*bdrv_next_node(BlockDriverState
*bs
)
5488 return QTAILQ_FIRST(&graph_bdrv_states
);
5490 return QTAILQ_NEXT(bs
, node_list
);
5493 BlockDriverState
*bdrv_next_all_states(BlockDriverState
*bs
)
5496 return QTAILQ_FIRST(&all_bdrv_states
);
5498 return QTAILQ_NEXT(bs
, bs_list
);
5501 const char *bdrv_get_node_name(const BlockDriverState
*bs
)
5503 return bs
->node_name
;
5506 const char *bdrv_get_parent_name(const BlockDriverState
*bs
)
5511 /* If multiple parents have a name, just pick the first one. */
5512 QLIST_FOREACH(c
, &bs
->parents
, next_parent
) {
5513 if (c
->klass
->get_name
) {
5514 name
= c
->klass
->get_name(c
);
5515 if (name
&& *name
) {
5524 /* TODO check what callers really want: bs->node_name or blk_name() */
5525 const char *bdrv_get_device_name(const BlockDriverState
*bs
)
5527 return bdrv_get_parent_name(bs
) ?: "";
5530 /* This can be used to identify nodes that might not have a device
5531 * name associated. Since node and device names live in the same
5532 * namespace, the result is unambiguous. The exception is if both are
5533 * absent, then this returns an empty (non-null) string. */
5534 const char *bdrv_get_device_or_node_name(const BlockDriverState
*bs
)
5536 return bdrv_get_parent_name(bs
) ?: bs
->node_name
;
5539 int bdrv_get_flags(BlockDriverState
*bs
)
5541 return bs
->open_flags
;
5544 int bdrv_has_zero_init_1(BlockDriverState
*bs
)
5549 int bdrv_has_zero_init(BlockDriverState
*bs
)
5551 BlockDriverState
*filtered
;
5557 /* If BS is a copy on write image, it is initialized to
5558 the contents of the base image, which may not be zeroes. */
5559 if (bdrv_cow_child(bs
)) {
5562 if (bs
->drv
->bdrv_has_zero_init
) {
5563 return bs
->drv
->bdrv_has_zero_init(bs
);
5566 filtered
= bdrv_filter_bs(bs
);
5568 return bdrv_has_zero_init(filtered
);
5575 bool bdrv_can_write_zeroes_with_unmap(BlockDriverState
*bs
)
5577 if (!(bs
->open_flags
& BDRV_O_UNMAP
)) {
5581 return bs
->supported_zero_flags
& BDRV_REQ_MAY_UNMAP
;
5584 void bdrv_get_backing_filename(BlockDriverState
*bs
,
5585 char *filename
, int filename_size
)
5587 pstrcpy(filename
, filename_size
, bs
->backing_file
);
5590 int bdrv_get_info(BlockDriverState
*bs
, BlockDriverInfo
*bdi
)
5593 BlockDriver
*drv
= bs
->drv
;
5594 /* if bs->drv == NULL, bs is closed, so there's nothing to do here */
5598 if (!drv
->bdrv_get_info
) {
5599 BlockDriverState
*filtered
= bdrv_filter_bs(bs
);
5601 return bdrv_get_info(filtered
, bdi
);
5605 memset(bdi
, 0, sizeof(*bdi
));
5606 ret
= drv
->bdrv_get_info(bs
, bdi
);
5611 if (bdi
->cluster_size
> BDRV_MAX_ALIGNMENT
) {
5618 ImageInfoSpecific
*bdrv_get_specific_info(BlockDriverState
*bs
,
5621 BlockDriver
*drv
= bs
->drv
;
5622 if (drv
&& drv
->bdrv_get_specific_info
) {
5623 return drv
->bdrv_get_specific_info(bs
, errp
);
5628 BlockStatsSpecific
*bdrv_get_specific_stats(BlockDriverState
*bs
)
5630 BlockDriver
*drv
= bs
->drv
;
5631 if (!drv
|| !drv
->bdrv_get_specific_stats
) {
5634 return drv
->bdrv_get_specific_stats(bs
);
5637 void bdrv_debug_event(BlockDriverState
*bs
, BlkdebugEvent event
)
5639 if (!bs
|| !bs
->drv
|| !bs
->drv
->bdrv_debug_event
) {
5643 bs
->drv
->bdrv_debug_event(bs
, event
);
5646 static BlockDriverState
*bdrv_find_debug_node(BlockDriverState
*bs
)
5648 while (bs
&& bs
->drv
&& !bs
->drv
->bdrv_debug_breakpoint
) {
5649 bs
= bdrv_primary_bs(bs
);
5652 if (bs
&& bs
->drv
&& bs
->drv
->bdrv_debug_breakpoint
) {
5653 assert(bs
->drv
->bdrv_debug_remove_breakpoint
);
5660 int bdrv_debug_breakpoint(BlockDriverState
*bs
, const char *event
,
5663 bs
= bdrv_find_debug_node(bs
);
5665 return bs
->drv
->bdrv_debug_breakpoint(bs
, event
, tag
);
5671 int bdrv_debug_remove_breakpoint(BlockDriverState
*bs
, const char *tag
)
5673 bs
= bdrv_find_debug_node(bs
);
5675 return bs
->drv
->bdrv_debug_remove_breakpoint(bs
, tag
);
5681 int bdrv_debug_resume(BlockDriverState
*bs
, const char *tag
)
5683 while (bs
&& (!bs
->drv
|| !bs
->drv
->bdrv_debug_resume
)) {
5684 bs
= bdrv_primary_bs(bs
);
5687 if (bs
&& bs
->drv
&& bs
->drv
->bdrv_debug_resume
) {
5688 return bs
->drv
->bdrv_debug_resume(bs
, tag
);
5694 bool bdrv_debug_is_suspended(BlockDriverState
*bs
, const char *tag
)
5696 while (bs
&& bs
->drv
&& !bs
->drv
->bdrv_debug_is_suspended
) {
5697 bs
= bdrv_primary_bs(bs
);
5700 if (bs
&& bs
->drv
&& bs
->drv
->bdrv_debug_is_suspended
) {
5701 return bs
->drv
->bdrv_debug_is_suspended(bs
, tag
);
5707 /* backing_file can either be relative, or absolute, or a protocol. If it is
5708 * relative, it must be relative to the chain. So, passing in bs->filename
5709 * from a BDS as backing_file should not be done, as that may be relative to
5710 * the CWD rather than the chain. */
5711 BlockDriverState
*bdrv_find_backing_image(BlockDriverState
*bs
,
5712 const char *backing_file
)
5714 char *filename_full
= NULL
;
5715 char *backing_file_full
= NULL
;
5716 char *filename_tmp
= NULL
;
5717 int is_protocol
= 0;
5718 bool filenames_refreshed
= false;
5719 BlockDriverState
*curr_bs
= NULL
;
5720 BlockDriverState
*retval
= NULL
;
5721 BlockDriverState
*bs_below
;
5723 if (!bs
|| !bs
->drv
|| !backing_file
) {
5727 filename_full
= g_malloc(PATH_MAX
);
5728 backing_file_full
= g_malloc(PATH_MAX
);
5730 is_protocol
= path_has_protocol(backing_file
);
5733 * Being largely a legacy function, skip any filters here
5734 * (because filters do not have normal filenames, so they cannot
5735 * match anyway; and allowing json:{} filenames is a bit out of
5738 for (curr_bs
= bdrv_skip_filters(bs
);
5739 bdrv_cow_child(curr_bs
) != NULL
;
5742 bs_below
= bdrv_backing_chain_next(curr_bs
);
5744 if (bdrv_backing_overridden(curr_bs
)) {
5746 * If the backing file was overridden, we can only compare
5747 * directly against the backing node's filename.
5750 if (!filenames_refreshed
) {
5752 * This will automatically refresh all of the
5753 * filenames in the rest of the backing chain, so we
5754 * only need to do this once.
5756 bdrv_refresh_filename(bs_below
);
5757 filenames_refreshed
= true;
5760 if (strcmp(backing_file
, bs_below
->filename
) == 0) {
5764 } else if (is_protocol
|| path_has_protocol(curr_bs
->backing_file
)) {
5766 * If either of the filename paths is actually a protocol, then
5767 * compare unmodified paths; otherwise make paths relative.
5769 char *backing_file_full_ret
;
5771 if (strcmp(backing_file
, curr_bs
->backing_file
) == 0) {
5775 /* Also check against the full backing filename for the image */
5776 backing_file_full_ret
= bdrv_get_full_backing_filename(curr_bs
,
5778 if (backing_file_full_ret
) {
5779 bool equal
= strcmp(backing_file
, backing_file_full_ret
) == 0;
5780 g_free(backing_file_full_ret
);
5787 /* If not an absolute filename path, make it relative to the current
5788 * image's filename path */
5789 filename_tmp
= bdrv_make_absolute_filename(curr_bs
, backing_file
,
5791 /* We are going to compare canonicalized absolute pathnames */
5792 if (!filename_tmp
|| !realpath(filename_tmp
, filename_full
)) {
5793 g_free(filename_tmp
);
5796 g_free(filename_tmp
);
5798 /* We need to make sure the backing filename we are comparing against
5799 * is relative to the current image filename (or absolute) */
5800 filename_tmp
= bdrv_get_full_backing_filename(curr_bs
, NULL
);
5801 if (!filename_tmp
|| !realpath(filename_tmp
, backing_file_full
)) {
5802 g_free(filename_tmp
);
5805 g_free(filename_tmp
);
5807 if (strcmp(backing_file_full
, filename_full
) == 0) {
5814 g_free(filename_full
);
5815 g_free(backing_file_full
);
5819 void bdrv_init(void)
5821 module_call_init(MODULE_INIT_BLOCK
);
5824 void bdrv_init_with_whitelist(void)
5826 use_bdrv_whitelist
= 1;
5830 int coroutine_fn
bdrv_co_invalidate_cache(BlockDriverState
*bs
, Error
**errp
)
5832 BdrvChild
*child
, *parent
;
5833 Error
*local_err
= NULL
;
5835 BdrvDirtyBitmap
*bm
;
5841 QLIST_FOREACH(child
, &bs
->children
, next
) {
5842 bdrv_co_invalidate_cache(child
->bs
, &local_err
);
5844 error_propagate(errp
, local_err
);
5850 * Update permissions, they may differ for inactive nodes.
5852 * Note that the required permissions of inactive images are always a
5853 * subset of the permissions required after activating the image. This
5854 * allows us to just get the permissions upfront without restricting
5855 * drv->bdrv_invalidate_cache().
5857 * It also means that in error cases, we don't have to try and revert to
5858 * the old permissions (which is an operation that could fail, too). We can
5859 * just keep the extended permissions for the next time that an activation
5860 * of the image is tried.
5862 if (bs
->open_flags
& BDRV_O_INACTIVE
) {
5863 bs
->open_flags
&= ~BDRV_O_INACTIVE
;
5864 ret
= bdrv_refresh_perms(bs
, errp
);
5866 bs
->open_flags
|= BDRV_O_INACTIVE
;
5870 if (bs
->drv
->bdrv_co_invalidate_cache
) {
5871 bs
->drv
->bdrv_co_invalidate_cache(bs
, &local_err
);
5873 bs
->open_flags
|= BDRV_O_INACTIVE
;
5874 error_propagate(errp
, local_err
);
5879 FOR_EACH_DIRTY_BITMAP(bs
, bm
) {
5880 bdrv_dirty_bitmap_skip_store(bm
, false);
5883 ret
= refresh_total_sectors(bs
, bs
->total_sectors
);
5885 bs
->open_flags
|= BDRV_O_INACTIVE
;
5886 error_setg_errno(errp
, -ret
, "Could not refresh total sector count");
5891 QLIST_FOREACH(parent
, &bs
->parents
, next_parent
) {
5892 if (parent
->klass
->activate
) {
5893 parent
->klass
->activate(parent
, &local_err
);
5895 bs
->open_flags
|= BDRV_O_INACTIVE
;
5896 error_propagate(errp
, local_err
);
5905 void bdrv_invalidate_cache_all(Error
**errp
)
5907 BlockDriverState
*bs
;
5908 BdrvNextIterator it
;
5910 for (bs
= bdrv_first(&it
); bs
; bs
= bdrv_next(&it
)) {
5911 AioContext
*aio_context
= bdrv_get_aio_context(bs
);
5914 aio_context_acquire(aio_context
);
5915 ret
= bdrv_invalidate_cache(bs
, errp
);
5916 aio_context_release(aio_context
);
5918 bdrv_next_cleanup(&it
);
5924 static bool bdrv_has_bds_parent(BlockDriverState
*bs
, bool only_active
)
5928 QLIST_FOREACH(parent
, &bs
->parents
, next_parent
) {
5929 if (parent
->klass
->parent_is_bds
) {
5930 BlockDriverState
*parent_bs
= parent
->opaque
;
5931 if (!only_active
|| !(parent_bs
->open_flags
& BDRV_O_INACTIVE
)) {
5940 static int bdrv_inactivate_recurse(BlockDriverState
*bs
)
5942 BdrvChild
*child
, *parent
;
5949 /* Make sure that we don't inactivate a child before its parent.
5950 * It will be covered by recursion from the yet active parent. */
5951 if (bdrv_has_bds_parent(bs
, true)) {
5955 assert(!(bs
->open_flags
& BDRV_O_INACTIVE
));
5957 /* Inactivate this node */
5958 if (bs
->drv
->bdrv_inactivate
) {
5959 ret
= bs
->drv
->bdrv_inactivate(bs
);
5965 QLIST_FOREACH(parent
, &bs
->parents
, next_parent
) {
5966 if (parent
->klass
->inactivate
) {
5967 ret
= parent
->klass
->inactivate(parent
);
5974 bs
->open_flags
|= BDRV_O_INACTIVE
;
5977 * Update permissions, they may differ for inactive nodes.
5978 * We only tried to loosen restrictions, so errors are not fatal, ignore
5981 bdrv_refresh_perms(bs
, NULL
);
5983 /* Recursively inactivate children */
5984 QLIST_FOREACH(child
, &bs
->children
, next
) {
5985 ret
= bdrv_inactivate_recurse(child
->bs
);
5994 int bdrv_inactivate_all(void)
5996 BlockDriverState
*bs
= NULL
;
5997 BdrvNextIterator it
;
5999 GSList
*aio_ctxs
= NULL
, *ctx
;
6001 for (bs
= bdrv_first(&it
); bs
; bs
= bdrv_next(&it
)) {
6002 AioContext
*aio_context
= bdrv_get_aio_context(bs
);
6004 if (!g_slist_find(aio_ctxs
, aio_context
)) {
6005 aio_ctxs
= g_slist_prepend(aio_ctxs
, aio_context
);
6006 aio_context_acquire(aio_context
);
6010 for (bs
= bdrv_first(&it
); bs
; bs
= bdrv_next(&it
)) {
6011 /* Nodes with BDS parents are covered by recursion from the last
6012 * parent that gets inactivated. Don't inactivate them a second
6013 * time if that has already happened. */
6014 if (bdrv_has_bds_parent(bs
, false)) {
6017 ret
= bdrv_inactivate_recurse(bs
);
6019 bdrv_next_cleanup(&it
);
6025 for (ctx
= aio_ctxs
; ctx
!= NULL
; ctx
= ctx
->next
) {
6026 AioContext
*aio_context
= ctx
->data
;
6027 aio_context_release(aio_context
);
6029 g_slist_free(aio_ctxs
);
6034 /**************************************************************/
6035 /* removable device support */
6038 * Return TRUE if the media is present
6040 bool bdrv_is_inserted(BlockDriverState
*bs
)
6042 BlockDriver
*drv
= bs
->drv
;
6048 if (drv
->bdrv_is_inserted
) {
6049 return drv
->bdrv_is_inserted(bs
);
6051 QLIST_FOREACH(child
, &bs
->children
, next
) {
6052 if (!bdrv_is_inserted(child
->bs
)) {
6060 * If eject_flag is TRUE, eject the media. Otherwise, close the tray
6062 void bdrv_eject(BlockDriverState
*bs
, bool eject_flag
)
6064 BlockDriver
*drv
= bs
->drv
;
6066 if (drv
&& drv
->bdrv_eject
) {
6067 drv
->bdrv_eject(bs
, eject_flag
);
6072 * Lock or unlock the media (if it is locked, the user won't be able
6073 * to eject it manually).
6075 void bdrv_lock_medium(BlockDriverState
*bs
, bool locked
)
6077 BlockDriver
*drv
= bs
->drv
;
6079 trace_bdrv_lock_medium(bs
, locked
);
6081 if (drv
&& drv
->bdrv_lock_medium
) {
6082 drv
->bdrv_lock_medium(bs
, locked
);
6086 /* Get a reference to bs */
6087 void bdrv_ref(BlockDriverState
*bs
)
6092 /* Release a previously grabbed reference to bs.
6093 * If after releasing, reference count is zero, the BlockDriverState is
6095 void bdrv_unref(BlockDriverState
*bs
)
6100 assert(bs
->refcnt
> 0);
6101 if (--bs
->refcnt
== 0) {
6106 struct BdrvOpBlocker
{
6108 QLIST_ENTRY(BdrvOpBlocker
) list
;
6111 bool bdrv_op_is_blocked(BlockDriverState
*bs
, BlockOpType op
, Error
**errp
)
6113 BdrvOpBlocker
*blocker
;
6114 assert((int) op
>= 0 && op
< BLOCK_OP_TYPE_MAX
);
6115 if (!QLIST_EMPTY(&bs
->op_blockers
[op
])) {
6116 blocker
= QLIST_FIRST(&bs
->op_blockers
[op
]);
6117 error_propagate_prepend(errp
, error_copy(blocker
->reason
),
6118 "Node '%s' is busy: ",
6119 bdrv_get_device_or_node_name(bs
));
6125 void bdrv_op_block(BlockDriverState
*bs
, BlockOpType op
, Error
*reason
)
6127 BdrvOpBlocker
*blocker
;
6128 assert((int) op
>= 0 && op
< BLOCK_OP_TYPE_MAX
);
6130 blocker
= g_new0(BdrvOpBlocker
, 1);
6131 blocker
->reason
= reason
;
6132 QLIST_INSERT_HEAD(&bs
->op_blockers
[op
], blocker
, list
);
6135 void bdrv_op_unblock(BlockDriverState
*bs
, BlockOpType op
, Error
*reason
)
6137 BdrvOpBlocker
*blocker
, *next
;
6138 assert((int) op
>= 0 && op
< BLOCK_OP_TYPE_MAX
);
6139 QLIST_FOREACH_SAFE(blocker
, &bs
->op_blockers
[op
], list
, next
) {
6140 if (blocker
->reason
== reason
) {
6141 QLIST_REMOVE(blocker
, list
);
6147 void bdrv_op_block_all(BlockDriverState
*bs
, Error
*reason
)
6150 for (i
= 0; i
< BLOCK_OP_TYPE_MAX
; i
++) {
6151 bdrv_op_block(bs
, i
, reason
);
6155 void bdrv_op_unblock_all(BlockDriverState
*bs
, Error
*reason
)
6158 for (i
= 0; i
< BLOCK_OP_TYPE_MAX
; i
++) {
6159 bdrv_op_unblock(bs
, i
, reason
);
6163 bool bdrv_op_blocker_is_empty(BlockDriverState
*bs
)
6167 for (i
= 0; i
< BLOCK_OP_TYPE_MAX
; i
++) {
6168 if (!QLIST_EMPTY(&bs
->op_blockers
[i
])) {
6175 void bdrv_img_create(const char *filename
, const char *fmt
,
6176 const char *base_filename
, const char *base_fmt
,
6177 char *options
, uint64_t img_size
, int flags
, bool quiet
,
6180 QemuOptsList
*create_opts
= NULL
;
6181 QemuOpts
*opts
= NULL
;
6182 const char *backing_fmt
, *backing_file
;
6184 BlockDriver
*drv
, *proto_drv
;
6185 Error
*local_err
= NULL
;
6188 /* Find driver and parse its options */
6189 drv
= bdrv_find_format(fmt
);
6191 error_setg(errp
, "Unknown file format '%s'", fmt
);
6195 proto_drv
= bdrv_find_protocol(filename
, true, errp
);
6200 if (!drv
->create_opts
) {
6201 error_setg(errp
, "Format driver '%s' does not support image creation",
6206 if (!proto_drv
->create_opts
) {
6207 error_setg(errp
, "Protocol driver '%s' does not support image creation",
6208 proto_drv
->format_name
);
6212 /* Create parameter list */
6213 create_opts
= qemu_opts_append(create_opts
, drv
->create_opts
);
6214 create_opts
= qemu_opts_append(create_opts
, proto_drv
->create_opts
);
6216 opts
= qemu_opts_create(create_opts
, NULL
, 0, &error_abort
);
6218 /* Parse -o options */
6220 if (!qemu_opts_do_parse(opts
, options
, NULL
, errp
)) {
6225 if (!qemu_opt_get(opts
, BLOCK_OPT_SIZE
)) {
6226 qemu_opt_set_number(opts
, BLOCK_OPT_SIZE
, img_size
, &error_abort
);
6227 } else if (img_size
!= UINT64_C(-1)) {
6228 error_setg(errp
, "The image size must be specified only once");
6232 if (base_filename
) {
6233 if (!qemu_opt_set(opts
, BLOCK_OPT_BACKING_FILE
, base_filename
,
6235 error_setg(errp
, "Backing file not supported for file format '%s'",
6242 if (!qemu_opt_set(opts
, BLOCK_OPT_BACKING_FMT
, base_fmt
, NULL
)) {
6243 error_setg(errp
, "Backing file format not supported for file "
6244 "format '%s'", fmt
);
6249 backing_file
= qemu_opt_get(opts
, BLOCK_OPT_BACKING_FILE
);
6251 if (!strcmp(filename
, backing_file
)) {
6252 error_setg(errp
, "Error: Trying to create an image with the "
6253 "same filename as the backing file");
6256 if (backing_file
[0] == '\0') {
6257 error_setg(errp
, "Expected backing file name, got empty string");
6262 backing_fmt
= qemu_opt_get(opts
, BLOCK_OPT_BACKING_FMT
);
6264 /* The size for the image must always be specified, unless we have a backing
6265 * file and we have not been forbidden from opening it. */
6266 size
= qemu_opt_get_size(opts
, BLOCK_OPT_SIZE
, img_size
);
6267 if (backing_file
&& !(flags
& BDRV_O_NO_BACKING
)) {
6268 BlockDriverState
*bs
;
6271 QDict
*backing_options
= NULL
;
6274 bdrv_get_full_backing_filename_from_filename(filename
, backing_file
,
6279 assert(full_backing
);
6281 /* backing files always opened read-only */
6283 back_flags
&= ~(BDRV_O_RDWR
| BDRV_O_SNAPSHOT
| BDRV_O_NO_BACKING
);
6285 backing_options
= qdict_new();
6287 qdict_put_str(backing_options
, "driver", backing_fmt
);
6289 qdict_put_bool(backing_options
, BDRV_OPT_FORCE_SHARE
, true);
6291 bs
= bdrv_open(full_backing
, NULL
, backing_options
, back_flags
,
6293 g_free(full_backing
);
6295 error_append_hint(&local_err
, "Could not open backing image.\n");
6299 warn_report("Deprecated use of backing file without explicit "
6300 "backing format (detected format of %s)",
6301 bs
->drv
->format_name
);
6302 if (bs
->drv
!= &bdrv_raw
) {
6304 * A probe of raw deserves the most attention:
6305 * leaving the backing format out of the image
6306 * will ensure bs->probed is set (ensuring we
6307 * don't accidentally commit into the backing
6308 * file), and allow more spots to warn the users
6309 * to fix their toolchain when opening this image
6310 * later. For other images, we can safely record
6311 * the format that we probed.
6313 backing_fmt
= bs
->drv
->format_name
;
6314 qemu_opt_set(opts
, BLOCK_OPT_BACKING_FMT
, backing_fmt
,
6319 /* Opened BS, have no size */
6320 size
= bdrv_getlength(bs
);
6322 error_setg_errno(errp
, -size
, "Could not get size of '%s'",
6327 qemu_opt_set_number(opts
, BLOCK_OPT_SIZE
, size
, &error_abort
);
6331 /* (backing_file && !(flags & BDRV_O_NO_BACKING)) */
6332 } else if (backing_file
&& !backing_fmt
) {
6333 warn_report("Deprecated use of unopened backing file without "
6334 "explicit backing format, use of this image requires "
6335 "potentially unsafe format probing");
6339 error_setg(errp
, "Image creation needs a size parameter");
6344 printf("Formatting '%s', fmt=%s ", filename
, fmt
);
6345 qemu_opts_print(opts
, " ");
6350 ret
= bdrv_create(drv
, filename
, opts
, &local_err
);
6352 if (ret
== -EFBIG
) {
6353 /* This is generally a better message than whatever the driver would
6354 * deliver (especially because of the cluster_size_hint), since that
6355 * is most probably not much different from "image too large". */
6356 const char *cluster_size_hint
= "";
6357 if (qemu_opt_get_size(opts
, BLOCK_OPT_CLUSTER_SIZE
, 0)) {
6358 cluster_size_hint
= " (try using a larger cluster size)";
6360 error_setg(errp
, "The image size is too large for file format '%s'"
6361 "%s", fmt
, cluster_size_hint
);
6362 error_free(local_err
);
6367 qemu_opts_del(opts
);
6368 qemu_opts_free(create_opts
);
6369 error_propagate(errp
, local_err
);
6372 AioContext
*bdrv_get_aio_context(BlockDriverState
*bs
)
6374 return bs
? bs
->aio_context
: qemu_get_aio_context();
6377 AioContext
*coroutine_fn
bdrv_co_enter(BlockDriverState
*bs
)
6379 Coroutine
*self
= qemu_coroutine_self();
6380 AioContext
*old_ctx
= qemu_coroutine_get_aio_context(self
);
6381 AioContext
*new_ctx
;
6384 * Increase bs->in_flight to ensure that this operation is completed before
6385 * moving the node to a different AioContext. Read new_ctx only afterwards.
6387 bdrv_inc_in_flight(bs
);
6389 new_ctx
= bdrv_get_aio_context(bs
);
6390 aio_co_reschedule_self(new_ctx
);
6394 void coroutine_fn
bdrv_co_leave(BlockDriverState
*bs
, AioContext
*old_ctx
)
6396 aio_co_reschedule_self(old_ctx
);
6397 bdrv_dec_in_flight(bs
);
6400 void coroutine_fn
bdrv_co_lock(BlockDriverState
*bs
)
6402 AioContext
*ctx
= bdrv_get_aio_context(bs
);
6404 /* In the main thread, bs->aio_context won't change concurrently */
6405 assert(qemu_get_current_aio_context() == qemu_get_aio_context());
6408 * We're in coroutine context, so we already hold the lock of the main
6409 * loop AioContext. Don't lock it twice to avoid deadlocks.
6411 assert(qemu_in_coroutine());
6412 if (ctx
!= qemu_get_aio_context()) {
6413 aio_context_acquire(ctx
);
6417 void coroutine_fn
bdrv_co_unlock(BlockDriverState
*bs
)
6419 AioContext
*ctx
= bdrv_get_aio_context(bs
);
6421 assert(qemu_in_coroutine());
6422 if (ctx
!= qemu_get_aio_context()) {
6423 aio_context_release(ctx
);
6427 void bdrv_coroutine_enter(BlockDriverState
*bs
, Coroutine
*co
)
6429 aio_co_enter(bdrv_get_aio_context(bs
), co
);
6432 static void bdrv_do_remove_aio_context_notifier(BdrvAioNotifier
*ban
)
6434 QLIST_REMOVE(ban
, list
);
6438 static void bdrv_detach_aio_context(BlockDriverState
*bs
)
6440 BdrvAioNotifier
*baf
, *baf_tmp
;
6442 assert(!bs
->walking_aio_notifiers
);
6443 bs
->walking_aio_notifiers
= true;
6444 QLIST_FOREACH_SAFE(baf
, &bs
->aio_notifiers
, list
, baf_tmp
) {
6446 bdrv_do_remove_aio_context_notifier(baf
);
6448 baf
->detach_aio_context(baf
->opaque
);
6451 /* Never mind iterating again to check for ->deleted. bdrv_close() will
6452 * remove remaining aio notifiers if we aren't called again.
6454 bs
->walking_aio_notifiers
= false;
6456 if (bs
->drv
&& bs
->drv
->bdrv_detach_aio_context
) {
6457 bs
->drv
->bdrv_detach_aio_context(bs
);
6460 if (bs
->quiesce_counter
) {
6461 aio_enable_external(bs
->aio_context
);
6463 bs
->aio_context
= NULL
;
6466 static void bdrv_attach_aio_context(BlockDriverState
*bs
,
6467 AioContext
*new_context
)
6469 BdrvAioNotifier
*ban
, *ban_tmp
;
6471 if (bs
->quiesce_counter
) {
6472 aio_disable_external(new_context
);
6475 bs
->aio_context
= new_context
;
6477 if (bs
->drv
&& bs
->drv
->bdrv_attach_aio_context
) {
6478 bs
->drv
->bdrv_attach_aio_context(bs
, new_context
);
6481 assert(!bs
->walking_aio_notifiers
);
6482 bs
->walking_aio_notifiers
= true;
6483 QLIST_FOREACH_SAFE(ban
, &bs
->aio_notifiers
, list
, ban_tmp
) {
6485 bdrv_do_remove_aio_context_notifier(ban
);
6487 ban
->attached_aio_context(new_context
, ban
->opaque
);
6490 bs
->walking_aio_notifiers
= false;
6494 * Changes the AioContext used for fd handlers, timers, and BHs by this
6495 * BlockDriverState and all its children and parents.
6497 * Must be called from the main AioContext.
6499 * The caller must own the AioContext lock for the old AioContext of bs, but it
6500 * must not own the AioContext lock for new_context (unless new_context is the
6501 * same as the current context of bs).
6503 * @ignore will accumulate all visited BdrvChild object. The caller is
6504 * responsible for freeing the list afterwards.
6506 void bdrv_set_aio_context_ignore(BlockDriverState
*bs
,
6507 AioContext
*new_context
, GSList
**ignore
)
6509 AioContext
*old_context
= bdrv_get_aio_context(bs
);
6510 GSList
*children_to_process
= NULL
;
6511 GSList
*parents_to_process
= NULL
;
6513 BdrvChild
*child
, *parent
;
6515 g_assert(qemu_get_current_aio_context() == qemu_get_aio_context());
6517 if (old_context
== new_context
) {
6521 bdrv_drained_begin(bs
);
6523 QLIST_FOREACH(child
, &bs
->children
, next
) {
6524 if (g_slist_find(*ignore
, child
)) {
6527 *ignore
= g_slist_prepend(*ignore
, child
);
6528 children_to_process
= g_slist_prepend(children_to_process
, child
);
6531 QLIST_FOREACH(parent
, &bs
->parents
, next_parent
) {
6532 if (g_slist_find(*ignore
, parent
)) {
6535 *ignore
= g_slist_prepend(*ignore
, parent
);
6536 parents_to_process
= g_slist_prepend(parents_to_process
, parent
);
6539 for (entry
= children_to_process
;
6541 entry
= g_slist_next(entry
)) {
6542 child
= entry
->data
;
6543 bdrv_set_aio_context_ignore(child
->bs
, new_context
, ignore
);
6545 g_slist_free(children_to_process
);
6547 for (entry
= parents_to_process
;
6549 entry
= g_slist_next(entry
)) {
6550 parent
= entry
->data
;
6551 assert(parent
->klass
->set_aio_ctx
);
6552 parent
->klass
->set_aio_ctx(parent
, new_context
, ignore
);
6554 g_slist_free(parents_to_process
);
6556 bdrv_detach_aio_context(bs
);
6558 /* Acquire the new context, if necessary */
6559 if (qemu_get_aio_context() != new_context
) {
6560 aio_context_acquire(new_context
);
6563 bdrv_attach_aio_context(bs
, new_context
);
6566 * If this function was recursively called from
6567 * bdrv_set_aio_context_ignore(), there may be nodes in the
6568 * subtree that have not yet been moved to the new AioContext.
6569 * Release the old one so bdrv_drained_end() can poll them.
6571 if (qemu_get_aio_context() != old_context
) {
6572 aio_context_release(old_context
);
6575 bdrv_drained_end(bs
);
6577 if (qemu_get_aio_context() != old_context
) {
6578 aio_context_acquire(old_context
);
6580 if (qemu_get_aio_context() != new_context
) {
6581 aio_context_release(new_context
);
6585 static bool bdrv_parent_can_set_aio_context(BdrvChild
*c
, AioContext
*ctx
,
6586 GSList
**ignore
, Error
**errp
)
6588 if (g_slist_find(*ignore
, c
)) {
6591 *ignore
= g_slist_prepend(*ignore
, c
);
6594 * A BdrvChildClass that doesn't handle AioContext changes cannot
6595 * tolerate any AioContext changes
6597 if (!c
->klass
->can_set_aio_ctx
) {
6598 char *user
= bdrv_child_user_desc(c
);
6599 error_setg(errp
, "Changing iothreads is not supported by %s", user
);
6603 if (!c
->klass
->can_set_aio_ctx(c
, ctx
, ignore
, errp
)) {
6604 assert(!errp
|| *errp
);
6610 bool bdrv_child_can_set_aio_context(BdrvChild
*c
, AioContext
*ctx
,
6611 GSList
**ignore
, Error
**errp
)
6613 if (g_slist_find(*ignore
, c
)) {
6616 *ignore
= g_slist_prepend(*ignore
, c
);
6617 return bdrv_can_set_aio_context(c
->bs
, ctx
, ignore
, errp
);
6620 /* @ignore will accumulate all visited BdrvChild object. The caller is
6621 * responsible for freeing the list afterwards. */
6622 bool bdrv_can_set_aio_context(BlockDriverState
*bs
, AioContext
*ctx
,
6623 GSList
**ignore
, Error
**errp
)
6627 if (bdrv_get_aio_context(bs
) == ctx
) {
6631 QLIST_FOREACH(c
, &bs
->parents
, next_parent
) {
6632 if (!bdrv_parent_can_set_aio_context(c
, ctx
, ignore
, errp
)) {
6636 QLIST_FOREACH(c
, &bs
->children
, next
) {
6637 if (!bdrv_child_can_set_aio_context(c
, ctx
, ignore
, errp
)) {
6645 int bdrv_child_try_set_aio_context(BlockDriverState
*bs
, AioContext
*ctx
,
6646 BdrvChild
*ignore_child
, Error
**errp
)
6651 ignore
= ignore_child
? g_slist_prepend(NULL
, ignore_child
) : NULL
;
6652 ret
= bdrv_can_set_aio_context(bs
, ctx
, &ignore
, errp
);
6653 g_slist_free(ignore
);
6659 ignore
= ignore_child
? g_slist_prepend(NULL
, ignore_child
) : NULL
;
6660 bdrv_set_aio_context_ignore(bs
, ctx
, &ignore
);
6661 g_slist_free(ignore
);
6666 int bdrv_try_set_aio_context(BlockDriverState
*bs
, AioContext
*ctx
,
6669 return bdrv_child_try_set_aio_context(bs
, ctx
, NULL
, errp
);
6672 void bdrv_add_aio_context_notifier(BlockDriverState
*bs
,
6673 void (*attached_aio_context
)(AioContext
*new_context
, void *opaque
),
6674 void (*detach_aio_context
)(void *opaque
), void *opaque
)
6676 BdrvAioNotifier
*ban
= g_new(BdrvAioNotifier
, 1);
6677 *ban
= (BdrvAioNotifier
){
6678 .attached_aio_context
= attached_aio_context
,
6679 .detach_aio_context
= detach_aio_context
,
6683 QLIST_INSERT_HEAD(&bs
->aio_notifiers
, ban
, list
);
6686 void bdrv_remove_aio_context_notifier(BlockDriverState
*bs
,
6687 void (*attached_aio_context
)(AioContext
*,
6689 void (*detach_aio_context
)(void *),
6692 BdrvAioNotifier
*ban
, *ban_next
;
6694 QLIST_FOREACH_SAFE(ban
, &bs
->aio_notifiers
, list
, ban_next
) {
6695 if (ban
->attached_aio_context
== attached_aio_context
&&
6696 ban
->detach_aio_context
== detach_aio_context
&&
6697 ban
->opaque
== opaque
&&
6698 ban
->deleted
== false)
6700 if (bs
->walking_aio_notifiers
) {
6701 ban
->deleted
= true;
6703 bdrv_do_remove_aio_context_notifier(ban
);
6712 int bdrv_amend_options(BlockDriverState
*bs
, QemuOpts
*opts
,
6713 BlockDriverAmendStatusCB
*status_cb
, void *cb_opaque
,
6718 error_setg(errp
, "Node is ejected");
6721 if (!bs
->drv
->bdrv_amend_options
) {
6722 error_setg(errp
, "Block driver '%s' does not support option amendment",
6723 bs
->drv
->format_name
);
6726 return bs
->drv
->bdrv_amend_options(bs
, opts
, status_cb
,
6727 cb_opaque
, force
, errp
);
6731 * This function checks whether the given @to_replace is allowed to be
6732 * replaced by a node that always shows the same data as @bs. This is
6733 * used for example to verify whether the mirror job can replace
6734 * @to_replace by the target mirrored from @bs.
6735 * To be replaceable, @bs and @to_replace may either be guaranteed to
6736 * always show the same data (because they are only connected through
6737 * filters), or some driver may allow replacing one of its children
6738 * because it can guarantee that this child's data is not visible at
6739 * all (for example, for dissenting quorum children that have no other
6742 bool bdrv_recurse_can_replace(BlockDriverState
*bs
,
6743 BlockDriverState
*to_replace
)
6745 BlockDriverState
*filtered
;
6747 if (!bs
|| !bs
->drv
) {
6751 if (bs
== to_replace
) {
6755 /* See what the driver can do */
6756 if (bs
->drv
->bdrv_recurse_can_replace
) {
6757 return bs
->drv
->bdrv_recurse_can_replace(bs
, to_replace
);
6760 /* For filters without an own implementation, we can recurse on our own */
6761 filtered
= bdrv_filter_bs(bs
);
6763 return bdrv_recurse_can_replace(filtered
, to_replace
);
6771 * Check whether the given @node_name can be replaced by a node that
6772 * has the same data as @parent_bs. If so, return @node_name's BDS;
6775 * @node_name must be a (recursive) *child of @parent_bs (or this
6776 * function will return NULL).
6778 * The result (whether the node can be replaced or not) is only valid
6779 * for as long as no graph or permission changes occur.
6781 BlockDriverState
*check_to_replace_node(BlockDriverState
*parent_bs
,
6782 const char *node_name
, Error
**errp
)
6784 BlockDriverState
*to_replace_bs
= bdrv_find_node(node_name
);
6785 AioContext
*aio_context
;
6787 if (!to_replace_bs
) {
6788 error_setg(errp
, "Failed to find node with node-name='%s'", node_name
);
6792 aio_context
= bdrv_get_aio_context(to_replace_bs
);
6793 aio_context_acquire(aio_context
);
6795 if (bdrv_op_is_blocked(to_replace_bs
, BLOCK_OP_TYPE_REPLACE
, errp
)) {
6796 to_replace_bs
= NULL
;
6800 /* We don't want arbitrary node of the BDS chain to be replaced only the top
6801 * most non filter in order to prevent data corruption.
6802 * Another benefit is that this tests exclude backing files which are
6803 * blocked by the backing blockers.
6805 if (!bdrv_recurse_can_replace(parent_bs
, to_replace_bs
)) {
6806 error_setg(errp
, "Cannot replace '%s' by a node mirrored from '%s', "
6807 "because it cannot be guaranteed that doing so would not "
6808 "lead to an abrupt change of visible data",
6809 node_name
, parent_bs
->node_name
);
6810 to_replace_bs
= NULL
;
6815 aio_context_release(aio_context
);
6816 return to_replace_bs
;
6820 * Iterates through the list of runtime option keys that are said to
6821 * be "strong" for a BDS. An option is called "strong" if it changes
6822 * a BDS's data. For example, the null block driver's "size" and
6823 * "read-zeroes" options are strong, but its "latency-ns" option is
6826 * If a key returned by this function ends with a dot, all options
6827 * starting with that prefix are strong.
6829 static const char *const *strong_options(BlockDriverState
*bs
,
6830 const char *const *curopt
)
6832 static const char *const global_options
[] = {
6833 "driver", "filename", NULL
6837 return &global_options
[0];
6841 if (curopt
== &global_options
[ARRAY_SIZE(global_options
) - 1] && bs
->drv
) {
6842 curopt
= bs
->drv
->strong_runtime_opts
;
6845 return (curopt
&& *curopt
) ? curopt
: NULL
;
6849 * Copies all strong runtime options from bs->options to the given
6850 * QDict. The set of strong option keys is determined by invoking
6853 * Returns true iff any strong option was present in bs->options (and
6854 * thus copied to the target QDict) with the exception of "filename"
6855 * and "driver". The caller is expected to use this value to decide
6856 * whether the existence of strong options prevents the generation of
6859 static bool append_strong_runtime_options(QDict
*d
, BlockDriverState
*bs
)
6861 bool found_any
= false;
6862 const char *const *option_name
= NULL
;
6868 while ((option_name
= strong_options(bs
, option_name
))) {
6869 bool option_given
= false;
6871 assert(strlen(*option_name
) > 0);
6872 if ((*option_name
)[strlen(*option_name
) - 1] != '.') {
6873 QObject
*entry
= qdict_get(bs
->options
, *option_name
);
6878 qdict_put_obj(d
, *option_name
, qobject_ref(entry
));
6879 option_given
= true;
6881 const QDictEntry
*entry
;
6882 for (entry
= qdict_first(bs
->options
); entry
;
6883 entry
= qdict_next(bs
->options
, entry
))
6885 if (strstart(qdict_entry_key(entry
), *option_name
, NULL
)) {
6886 qdict_put_obj(d
, qdict_entry_key(entry
),
6887 qobject_ref(qdict_entry_value(entry
)));
6888 option_given
= true;
6893 /* While "driver" and "filename" need to be included in a JSON filename,
6894 * their existence does not prohibit generation of a plain filename. */
6895 if (!found_any
&& option_given
&&
6896 strcmp(*option_name
, "driver") && strcmp(*option_name
, "filename"))
6902 if (!qdict_haskey(d
, "driver")) {
6903 /* Drivers created with bdrv_new_open_driver() may not have a
6904 * @driver option. Add it here. */
6905 qdict_put_str(d
, "driver", bs
->drv
->format_name
);
6911 /* Note: This function may return false positives; it may return true
6912 * even if opening the backing file specified by bs's image header
6913 * would result in exactly bs->backing. */
6914 bool bdrv_backing_overridden(BlockDriverState
*bs
)
6917 return strcmp(bs
->auto_backing_file
,
6918 bs
->backing
->bs
->filename
);
6920 /* No backing BDS, so if the image header reports any backing
6921 * file, it must have been suppressed */
6922 return bs
->auto_backing_file
[0] != '\0';
6926 /* Updates the following BDS fields:
6927 * - exact_filename: A filename which may be used for opening a block device
6928 * which (mostly) equals the given BDS (even without any
6929 * other options; so reading and writing must return the same
6930 * results, but caching etc. may be different)
6931 * - full_open_options: Options which, when given when opening a block device
6932 * (without a filename), result in a BDS (mostly)
6933 * equalling the given one
6934 * - filename: If exact_filename is set, it is copied here. Otherwise,
6935 * full_open_options is converted to a JSON object, prefixed with
6936 * "json:" (for use through the JSON pseudo protocol) and put here.
6938 void bdrv_refresh_filename(BlockDriverState
*bs
)
6940 BlockDriver
*drv
= bs
->drv
;
6942 BlockDriverState
*primary_child_bs
;
6944 bool backing_overridden
;
6945 bool generate_json_filename
; /* Whether our default implementation should
6946 fill exact_filename (false) or not (true) */
6952 /* This BDS's file name may depend on any of its children's file names, so
6953 * refresh those first */
6954 QLIST_FOREACH(child
, &bs
->children
, next
) {
6955 bdrv_refresh_filename(child
->bs
);
6959 /* For implicit nodes, just copy everything from the single child */
6960 child
= QLIST_FIRST(&bs
->children
);
6961 assert(QLIST_NEXT(child
, next
) == NULL
);
6963 pstrcpy(bs
->exact_filename
, sizeof(bs
->exact_filename
),
6964 child
->bs
->exact_filename
);
6965 pstrcpy(bs
->filename
, sizeof(bs
->filename
), child
->bs
->filename
);
6967 qobject_unref(bs
->full_open_options
);
6968 bs
->full_open_options
= qobject_ref(child
->bs
->full_open_options
);
6973 backing_overridden
= bdrv_backing_overridden(bs
);
6975 if (bs
->open_flags
& BDRV_O_NO_IO
) {
6976 /* Without I/O, the backing file does not change anything.
6977 * Therefore, in such a case (primarily qemu-img), we can
6978 * pretend the backing file has not been overridden even if
6979 * it technically has been. */
6980 backing_overridden
= false;
6983 /* Gather the options QDict */
6985 generate_json_filename
= append_strong_runtime_options(opts
, bs
);
6986 generate_json_filename
|= backing_overridden
;
6988 if (drv
->bdrv_gather_child_options
) {
6989 /* Some block drivers may not want to present all of their children's
6990 * options, or name them differently from BdrvChild.name */
6991 drv
->bdrv_gather_child_options(bs
, opts
, backing_overridden
);
6993 QLIST_FOREACH(child
, &bs
->children
, next
) {
6994 if (child
== bs
->backing
&& !backing_overridden
) {
6995 /* We can skip the backing BDS if it has not been overridden */
6999 qdict_put(opts
, child
->name
,
7000 qobject_ref(child
->bs
->full_open_options
));
7003 if (backing_overridden
&& !bs
->backing
) {
7004 /* Force no backing file */
7005 qdict_put_null(opts
, "backing");
7009 qobject_unref(bs
->full_open_options
);
7010 bs
->full_open_options
= opts
;
7012 primary_child_bs
= bdrv_primary_bs(bs
);
7014 if (drv
->bdrv_refresh_filename
) {
7015 /* Obsolete information is of no use here, so drop the old file name
7016 * information before refreshing it */
7017 bs
->exact_filename
[0] = '\0';
7019 drv
->bdrv_refresh_filename(bs
);
7020 } else if (primary_child_bs
) {
7022 * Try to reconstruct valid information from the underlying
7023 * file -- this only works for format nodes (filter nodes
7024 * cannot be probed and as such must be selected by the user
7025 * either through an options dict, or through a special
7026 * filename which the filter driver must construct in its
7027 * .bdrv_refresh_filename() implementation).
7030 bs
->exact_filename
[0] = '\0';
7033 * We can use the underlying file's filename if:
7034 * - it has a filename,
7035 * - the current BDS is not a filter,
7036 * - the file is a protocol BDS, and
7037 * - opening that file (as this BDS's format) will automatically create
7038 * the BDS tree we have right now, that is:
7039 * - the user did not significantly change this BDS's behavior with
7040 * some explicit (strong) options
7041 * - no non-file child of this BDS has been overridden by the user
7042 * Both of these conditions are represented by generate_json_filename.
7044 if (primary_child_bs
->exact_filename
[0] &&
7045 primary_child_bs
->drv
->bdrv_file_open
&&
7046 !drv
->is_filter
&& !generate_json_filename
)
7048 strcpy(bs
->exact_filename
, primary_child_bs
->exact_filename
);
7052 if (bs
->exact_filename
[0]) {
7053 pstrcpy(bs
->filename
, sizeof(bs
->filename
), bs
->exact_filename
);
7055 GString
*json
= qobject_to_json(QOBJECT(bs
->full_open_options
));
7056 if (snprintf(bs
->filename
, sizeof(bs
->filename
), "json:%s",
7057 json
->str
) >= sizeof(bs
->filename
)) {
7058 /* Give user a hint if we truncated things. */
7059 strcpy(bs
->filename
+ sizeof(bs
->filename
) - 4, "...");
7061 g_string_free(json
, true);
7065 char *bdrv_dirname(BlockDriverState
*bs
, Error
**errp
)
7067 BlockDriver
*drv
= bs
->drv
;
7068 BlockDriverState
*child_bs
;
7071 error_setg(errp
, "Node '%s' is ejected", bs
->node_name
);
7075 if (drv
->bdrv_dirname
) {
7076 return drv
->bdrv_dirname(bs
, errp
);
7079 child_bs
= bdrv_primary_bs(bs
);
7081 return bdrv_dirname(child_bs
, errp
);
7084 bdrv_refresh_filename(bs
);
7085 if (bs
->exact_filename
[0] != '\0') {
7086 return path_combine(bs
->exact_filename
, "");
7089 error_setg(errp
, "Cannot generate a base directory for %s nodes",
7095 * Hot add/remove a BDS's child. So the user can take a child offline when
7096 * it is broken and take a new child online
7098 void bdrv_add_child(BlockDriverState
*parent_bs
, BlockDriverState
*child_bs
,
7102 if (!parent_bs
->drv
|| !parent_bs
->drv
->bdrv_add_child
) {
7103 error_setg(errp
, "The node %s does not support adding a child",
7104 bdrv_get_device_or_node_name(parent_bs
));
7108 if (!QLIST_EMPTY(&child_bs
->parents
)) {
7109 error_setg(errp
, "The node %s already has a parent",
7110 child_bs
->node_name
);
7114 parent_bs
->drv
->bdrv_add_child(parent_bs
, child_bs
, errp
);
7117 void bdrv_del_child(BlockDriverState
*parent_bs
, BdrvChild
*child
, Error
**errp
)
7121 if (!parent_bs
->drv
|| !parent_bs
->drv
->bdrv_del_child
) {
7122 error_setg(errp
, "The node %s does not support removing a child",
7123 bdrv_get_device_or_node_name(parent_bs
));
7127 QLIST_FOREACH(tmp
, &parent_bs
->children
, next
) {
7134 error_setg(errp
, "The node %s does not have a child named %s",
7135 bdrv_get_device_or_node_name(parent_bs
),
7136 bdrv_get_device_or_node_name(child
->bs
));
7140 parent_bs
->drv
->bdrv_del_child(parent_bs
, child
, errp
);
7143 int bdrv_make_empty(BdrvChild
*c
, Error
**errp
)
7145 BlockDriver
*drv
= c
->bs
->drv
;
7148 assert(c
->perm
& (BLK_PERM_WRITE
| BLK_PERM_WRITE_UNCHANGED
));
7150 if (!drv
->bdrv_make_empty
) {
7151 error_setg(errp
, "%s does not support emptying nodes",
7156 ret
= drv
->bdrv_make_empty(c
->bs
);
7158 error_setg_errno(errp
, -ret
, "Failed to empty %s",
7167 * Return the child that @bs acts as an overlay for, and from which data may be
7168 * copied in COW or COR operations. Usually this is the backing file.
7170 BdrvChild
*bdrv_cow_child(BlockDriverState
*bs
)
7172 if (!bs
|| !bs
->drv
) {
7176 if (bs
->drv
->is_filter
) {
7184 assert(bs
->backing
->role
& BDRV_CHILD_COW
);
7189 * If @bs acts as a filter for exactly one of its children, return
7192 BdrvChild
*bdrv_filter_child(BlockDriverState
*bs
)
7196 if (!bs
|| !bs
->drv
) {
7200 if (!bs
->drv
->is_filter
) {
7204 /* Only one of @backing or @file may be used */
7205 assert(!(bs
->backing
&& bs
->file
));
7207 c
= bs
->backing
?: bs
->file
;
7212 assert(c
->role
& BDRV_CHILD_FILTERED
);
7217 * Return either the result of bdrv_cow_child() or bdrv_filter_child(),
7218 * whichever is non-NULL.
7220 * Return NULL if both are NULL.
7222 BdrvChild
*bdrv_filter_or_cow_child(BlockDriverState
*bs
)
7224 BdrvChild
*cow_child
= bdrv_cow_child(bs
);
7225 BdrvChild
*filter_child
= bdrv_filter_child(bs
);
7227 /* Filter nodes cannot have COW backing files */
7228 assert(!(cow_child
&& filter_child
));
7230 return cow_child
?: filter_child
;
7234 * Return the primary child of this node: For filters, that is the
7235 * filtered child. For other nodes, that is usually the child storing
7237 * (A generally more helpful description is that this is (usually) the
7238 * child that has the same filename as @bs.)
7240 * Drivers do not necessarily have a primary child; for example quorum
7243 BdrvChild
*bdrv_primary_child(BlockDriverState
*bs
)
7245 BdrvChild
*c
, *found
= NULL
;
7247 QLIST_FOREACH(c
, &bs
->children
, next
) {
7248 if (c
->role
& BDRV_CHILD_PRIMARY
) {
7257 static BlockDriverState
*bdrv_do_skip_filters(BlockDriverState
*bs
,
7258 bool stop_on_explicit_filter
)
7266 while (!(stop_on_explicit_filter
&& !bs
->implicit
)) {
7267 c
= bdrv_filter_child(bs
);
7270 * A filter that is embedded in a working block graph must
7271 * have a child. Assert this here so this function does
7272 * not return a filter node that is not expected by the
7275 assert(!bs
->drv
|| !bs
->drv
->is_filter
);
7281 * Note that this treats nodes with bs->drv == NULL as not being
7282 * filters (bs->drv == NULL should be replaced by something else
7284 * The advantage of this behavior is that this function will thus
7285 * always return a non-NULL value (given a non-NULL @bs).
7292 * Return the first BDS that has not been added implicitly or that
7293 * does not have a filtered child down the chain starting from @bs
7294 * (including @bs itself).
7296 BlockDriverState
*bdrv_skip_implicit_filters(BlockDriverState
*bs
)
7298 return bdrv_do_skip_filters(bs
, true);
7302 * Return the first BDS that does not have a filtered child down the
7303 * chain starting from @bs (including @bs itself).
7305 BlockDriverState
*bdrv_skip_filters(BlockDriverState
*bs
)
7307 return bdrv_do_skip_filters(bs
, false);
7311 * For a backing chain, return the first non-filter backing image of
7312 * the first non-filter image.
7314 BlockDriverState
*bdrv_backing_chain_next(BlockDriverState
*bs
)
7316 return bdrv_skip_filters(bdrv_cow_bs(bdrv_skip_filters(bs
)));