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/nbd.h"
30 #include "block/qdict.h"
31 #include "qemu/error-report.h"
32 #include "block/module_block.h"
33 #include "qemu/main-loop.h"
34 #include "qemu/module.h"
35 #include "qapi/error.h"
36 #include "qapi/qmp/qdict.h"
37 #include "qapi/qmp/qjson.h"
38 #include "qapi/qmp/qnull.h"
39 #include "qapi/qmp/qstring.h"
40 #include "qapi/qobject-output-visitor.h"
41 #include "qapi/qapi-visit-block-core.h"
42 #include "sysemu/block-backend.h"
43 #include "sysemu/sysemu.h"
44 #include "qemu/notify.h"
45 #include "qemu/option.h"
46 #include "qemu/coroutine.h"
47 #include "block/qapi.h"
48 #include "qemu/timer.h"
49 #include "qemu/cutils.h"
51 #include "block/coroutines.h"
54 #include <sys/ioctl.h>
55 #include <sys/queue.h>
65 #define NOT_DONE 0x7fffffff /* used while emulated sync operation in progress */
67 static QTAILQ_HEAD(, BlockDriverState
) graph_bdrv_states
=
68 QTAILQ_HEAD_INITIALIZER(graph_bdrv_states
);
70 static QTAILQ_HEAD(, BlockDriverState
) all_bdrv_states
=
71 QTAILQ_HEAD_INITIALIZER(all_bdrv_states
);
73 static QLIST_HEAD(, BlockDriver
) bdrv_drivers
=
74 QLIST_HEAD_INITIALIZER(bdrv_drivers
);
76 static BlockDriverState
*bdrv_open_inherit(const char *filename
,
77 const char *reference
,
78 QDict
*options
, int flags
,
79 BlockDriverState
*parent
,
80 const BdrvChildClass
*child_class
,
81 BdrvChildRole child_role
,
84 /* If non-zero, use only whitelisted block drivers */
85 static int use_bdrv_whitelist
;
88 static int is_windows_drive_prefix(const char *filename
)
90 return (((filename
[0] >= 'a' && filename
[0] <= 'z') ||
91 (filename
[0] >= 'A' && filename
[0] <= 'Z')) &&
95 int is_windows_drive(const char *filename
)
97 if (is_windows_drive_prefix(filename
) &&
100 if (strstart(filename
, "\\\\.\\", NULL
) ||
101 strstart(filename
, "//./", NULL
))
107 size_t bdrv_opt_mem_align(BlockDriverState
*bs
)
109 if (!bs
|| !bs
->drv
) {
110 /* page size or 4k (hdd sector size) should be on the safe side */
111 return MAX(4096, qemu_real_host_page_size
);
114 return bs
->bl
.opt_mem_alignment
;
117 size_t bdrv_min_mem_align(BlockDriverState
*bs
)
119 if (!bs
|| !bs
->drv
) {
120 /* page size or 4k (hdd sector size) should be on the safe side */
121 return MAX(4096, qemu_real_host_page_size
);
124 return bs
->bl
.min_mem_alignment
;
127 /* check if the path starts with "<protocol>:" */
128 int path_has_protocol(const char *path
)
133 if (is_windows_drive(path
) ||
134 is_windows_drive_prefix(path
)) {
137 p
= path
+ strcspn(path
, ":/\\");
139 p
= path
+ strcspn(path
, ":/");
145 int path_is_absolute(const char *path
)
148 /* specific case for names like: "\\.\d:" */
149 if (is_windows_drive(path
) || is_windows_drive_prefix(path
)) {
152 return (*path
== '/' || *path
== '\\');
154 return (*path
== '/');
158 /* if filename is absolute, just return its duplicate. Otherwise, build a
159 path to it by considering it is relative to base_path. URL are
161 char *path_combine(const char *base_path
, const char *filename
)
163 const char *protocol_stripped
= NULL
;
168 if (path_is_absolute(filename
)) {
169 return g_strdup(filename
);
172 if (path_has_protocol(base_path
)) {
173 protocol_stripped
= strchr(base_path
, ':');
174 if (protocol_stripped
) {
178 p
= protocol_stripped
?: base_path
;
180 p1
= strrchr(base_path
, '/');
184 p2
= strrchr(base_path
, '\\');
185 if (!p1
|| p2
> p1
) {
200 result
= g_malloc(len
+ strlen(filename
) + 1);
201 memcpy(result
, base_path
, len
);
202 strcpy(result
+ len
, filename
);
208 * Helper function for bdrv_parse_filename() implementations to remove optional
209 * protocol prefixes (especially "file:") from a filename and for putting the
210 * stripped filename into the options QDict if there is such a prefix.
212 void bdrv_parse_filename_strip_prefix(const char *filename
, const char *prefix
,
215 if (strstart(filename
, prefix
, &filename
)) {
216 /* Stripping the explicit protocol prefix may result in a protocol
217 * prefix being (wrongly) detected (if the filename contains a colon) */
218 if (path_has_protocol(filename
)) {
219 QString
*fat_filename
;
221 /* This means there is some colon before the first slash; therefore,
222 * this cannot be an absolute path */
223 assert(!path_is_absolute(filename
));
225 /* And we can thus fix the protocol detection issue by prefixing it
227 fat_filename
= qstring_from_str("./");
228 qstring_append(fat_filename
, filename
);
230 assert(!path_has_protocol(qstring_get_str(fat_filename
)));
232 qdict_put(options
, "filename", fat_filename
);
234 /* If no protocol prefix was detected, we can use the shortened
236 qdict_put_str(options
, "filename", filename
);
242 /* Returns whether the image file is opened as read-only. Note that this can
243 * return false and writing to the image file is still not possible because the
244 * image is inactivated. */
245 bool bdrv_is_read_only(BlockDriverState
*bs
)
247 return bs
->read_only
;
250 int bdrv_can_set_read_only(BlockDriverState
*bs
, bool read_only
,
251 bool ignore_allow_rdw
, Error
**errp
)
253 /* Do not set read_only if copy_on_read is enabled */
254 if (bs
->copy_on_read
&& read_only
) {
255 error_setg(errp
, "Can't set node '%s' to r/o with copy-on-read enabled",
256 bdrv_get_device_or_node_name(bs
));
260 /* Do not clear read_only if it is prohibited */
261 if (!read_only
&& !(bs
->open_flags
& BDRV_O_ALLOW_RDWR
) &&
264 error_setg(errp
, "Node '%s' is read only",
265 bdrv_get_device_or_node_name(bs
));
273 * Called by a driver that can only provide a read-only image.
275 * Returns 0 if the node is already read-only or it could switch the node to
276 * read-only because BDRV_O_AUTO_RDONLY is set.
278 * Returns -EACCES if the node is read-write and BDRV_O_AUTO_RDONLY is not set
279 * or bdrv_can_set_read_only() forbids making the node read-only. If @errmsg
280 * is not NULL, it is used as the error message for the Error object.
282 int bdrv_apply_auto_read_only(BlockDriverState
*bs
, const char *errmsg
,
287 if (!(bs
->open_flags
& BDRV_O_RDWR
)) {
290 if (!(bs
->open_flags
& BDRV_O_AUTO_RDONLY
)) {
294 ret
= bdrv_can_set_read_only(bs
, true, false, NULL
);
299 bs
->read_only
= true;
300 bs
->open_flags
&= ~BDRV_O_RDWR
;
305 error_setg(errp
, "%s", errmsg
?: "Image is read-only");
310 * If @backing is empty, this function returns NULL without setting
311 * @errp. In all other cases, NULL will only be returned with @errp
314 * Therefore, a return value of NULL without @errp set means that
315 * there is no backing file; if @errp is set, there is one but its
316 * absolute filename cannot be generated.
318 char *bdrv_get_full_backing_filename_from_filename(const char *backed
,
322 if (backing
[0] == '\0') {
324 } else if (path_has_protocol(backing
) || path_is_absolute(backing
)) {
325 return g_strdup(backing
);
326 } else if (backed
[0] == '\0' || strstart(backed
, "json:", NULL
)) {
327 error_setg(errp
, "Cannot use relative backing file names for '%s'",
331 return path_combine(backed
, backing
);
336 * If @filename is empty or NULL, this function returns NULL without
337 * setting @errp. In all other cases, NULL will only be returned with
340 static char *bdrv_make_absolute_filename(BlockDriverState
*relative_to
,
341 const char *filename
, Error
**errp
)
343 char *dir
, *full_name
;
345 if (!filename
|| filename
[0] == '\0') {
347 } else if (path_has_protocol(filename
) || path_is_absolute(filename
)) {
348 return g_strdup(filename
);
351 dir
= bdrv_dirname(relative_to
, errp
);
356 full_name
= g_strconcat(dir
, filename
, NULL
);
361 char *bdrv_get_full_backing_filename(BlockDriverState
*bs
, Error
**errp
)
363 return bdrv_make_absolute_filename(bs
, bs
->backing_file
, errp
);
366 void bdrv_register(BlockDriver
*bdrv
)
368 assert(bdrv
->format_name
);
369 QLIST_INSERT_HEAD(&bdrv_drivers
, bdrv
, list
);
372 BlockDriverState
*bdrv_new(void)
374 BlockDriverState
*bs
;
377 bs
= g_new0(BlockDriverState
, 1);
378 QLIST_INIT(&bs
->dirty_bitmaps
);
379 for (i
= 0; i
< BLOCK_OP_TYPE_MAX
; i
++) {
380 QLIST_INIT(&bs
->op_blockers
[i
]);
382 notifier_with_return_list_init(&bs
->before_write_notifiers
);
383 qemu_co_mutex_init(&bs
->reqs_lock
);
384 qemu_mutex_init(&bs
->dirty_bitmap_mutex
);
386 bs
->aio_context
= qemu_get_aio_context();
388 qemu_co_queue_init(&bs
->flush_queue
);
390 for (i
= 0; i
< bdrv_drain_all_count
; i
++) {
391 bdrv_drained_begin(bs
);
394 QTAILQ_INSERT_TAIL(&all_bdrv_states
, bs
, bs_list
);
399 static BlockDriver
*bdrv_do_find_format(const char *format_name
)
403 QLIST_FOREACH(drv1
, &bdrv_drivers
, list
) {
404 if (!strcmp(drv1
->format_name
, format_name
)) {
412 BlockDriver
*bdrv_find_format(const char *format_name
)
417 drv1
= bdrv_do_find_format(format_name
);
422 /* The driver isn't registered, maybe we need to load a module */
423 for (i
= 0; i
< (int)ARRAY_SIZE(block_driver_modules
); ++i
) {
424 if (!strcmp(block_driver_modules
[i
].format_name
, format_name
)) {
425 block_module_load_one(block_driver_modules
[i
].library_name
);
430 return bdrv_do_find_format(format_name
);
433 static int bdrv_format_is_whitelisted(const char *format_name
, bool read_only
)
435 static const char *whitelist_rw
[] = {
436 CONFIG_BDRV_RW_WHITELIST
439 static const char *whitelist_ro
[] = {
440 CONFIG_BDRV_RO_WHITELIST
445 if (!whitelist_rw
[0] && !whitelist_ro
[0]) {
446 return 1; /* no whitelist, anything goes */
449 for (p
= whitelist_rw
; *p
; p
++) {
450 if (!strcmp(format_name
, *p
)) {
455 for (p
= whitelist_ro
; *p
; p
++) {
456 if (!strcmp(format_name
, *p
)) {
464 int bdrv_is_whitelisted(BlockDriver
*drv
, bool read_only
)
466 return bdrv_format_is_whitelisted(drv
->format_name
, read_only
);
469 bool bdrv_uses_whitelist(void)
471 return use_bdrv_whitelist
;
474 typedef struct CreateCo
{
482 static void coroutine_fn
bdrv_create_co_entry(void *opaque
)
484 Error
*local_err
= NULL
;
487 CreateCo
*cco
= opaque
;
490 ret
= cco
->drv
->bdrv_co_create_opts(cco
->drv
,
491 cco
->filename
, cco
->opts
, &local_err
);
492 error_propagate(&cco
->err
, local_err
);
496 int bdrv_create(BlockDriver
*drv
, const char* filename
,
497 QemuOpts
*opts
, Error
**errp
)
504 .filename
= g_strdup(filename
),
510 if (!drv
->bdrv_co_create_opts
) {
511 error_setg(errp
, "Driver '%s' does not support image creation", drv
->format_name
);
516 if (qemu_in_coroutine()) {
517 /* Fast-path if already in coroutine context */
518 bdrv_create_co_entry(&cco
);
520 co
= qemu_coroutine_create(bdrv_create_co_entry
, &cco
);
521 qemu_coroutine_enter(co
);
522 while (cco
.ret
== NOT_DONE
) {
523 aio_poll(qemu_get_aio_context(), true);
530 error_propagate(errp
, cco
.err
);
532 error_setg_errno(errp
, -ret
, "Could not create image");
537 g_free(cco
.filename
);
542 * Helper function for bdrv_create_file_fallback(): Resize @blk to at
543 * least the given @minimum_size.
545 * On success, return @blk's actual length.
546 * Otherwise, return -errno.
548 static int64_t create_file_fallback_truncate(BlockBackend
*blk
,
549 int64_t minimum_size
, Error
**errp
)
551 Error
*local_err
= NULL
;
555 ret
= blk_truncate(blk
, minimum_size
, false, PREALLOC_MODE_OFF
, 0,
557 if (ret
< 0 && ret
!= -ENOTSUP
) {
558 error_propagate(errp
, local_err
);
562 size
= blk_getlength(blk
);
564 error_free(local_err
);
565 error_setg_errno(errp
, -size
,
566 "Failed to inquire the new image file's length");
570 if (size
< minimum_size
) {
571 /* Need to grow the image, but we failed to do that */
572 error_propagate(errp
, local_err
);
576 error_free(local_err
);
583 * Helper function for bdrv_create_file_fallback(): Zero the first
584 * sector to remove any potentially pre-existing image header.
586 static int create_file_fallback_zero_first_sector(BlockBackend
*blk
,
587 int64_t current_size
,
590 int64_t bytes_to_clear
;
593 bytes_to_clear
= MIN(current_size
, BDRV_SECTOR_SIZE
);
594 if (bytes_to_clear
) {
595 ret
= blk_pwrite_zeroes(blk
, 0, bytes_to_clear
, BDRV_REQ_MAY_UNMAP
);
597 error_setg_errno(errp
, -ret
,
598 "Failed to clear the new image's first sector");
607 * Simple implementation of bdrv_co_create_opts for protocol drivers
608 * which only support creation via opening a file
609 * (usually existing raw storage device)
611 int coroutine_fn
bdrv_co_create_opts_simple(BlockDriver
*drv
,
612 const char *filename
,
620 PreallocMode prealloc
;
621 Error
*local_err
= NULL
;
624 size
= qemu_opt_get_size_del(opts
, BLOCK_OPT_SIZE
, 0);
625 buf
= qemu_opt_get_del(opts
, BLOCK_OPT_PREALLOC
);
626 prealloc
= qapi_enum_parse(&PreallocMode_lookup
, buf
,
627 PREALLOC_MODE_OFF
, &local_err
);
630 error_propagate(errp
, local_err
);
634 if (prealloc
!= PREALLOC_MODE_OFF
) {
635 error_setg(errp
, "Unsupported preallocation mode '%s'",
636 PreallocMode_str(prealloc
));
640 options
= qdict_new();
641 qdict_put_str(options
, "driver", drv
->format_name
);
643 blk
= blk_new_open(filename
, NULL
, options
,
644 BDRV_O_RDWR
| BDRV_O_RESIZE
, errp
);
646 error_prepend(errp
, "Protocol driver '%s' does not support image "
647 "creation, and opening the image failed: ",
652 size
= create_file_fallback_truncate(blk
, size
, errp
);
658 ret
= create_file_fallback_zero_first_sector(blk
, size
, errp
);
669 int bdrv_create_file(const char *filename
, QemuOpts
*opts
, Error
**errp
)
673 drv
= bdrv_find_protocol(filename
, true, errp
);
678 return bdrv_create(drv
, filename
, opts
, errp
);
681 int coroutine_fn
bdrv_co_delete_file(BlockDriverState
*bs
, Error
**errp
)
683 Error
*local_err
= NULL
;
689 error_setg(errp
, "Block node '%s' is not opened", bs
->filename
);
693 if (!bs
->drv
->bdrv_co_delete_file
) {
694 error_setg(errp
, "Driver '%s' does not support image deletion",
695 bs
->drv
->format_name
);
699 ret
= bs
->drv
->bdrv_co_delete_file(bs
, &local_err
);
701 error_propagate(errp
, local_err
);
708 * Try to get @bs's logical and physical block size.
709 * On success, store them in @bsz struct and return 0.
710 * On failure return -errno.
711 * @bs must not be empty.
713 int bdrv_probe_blocksizes(BlockDriverState
*bs
, BlockSizes
*bsz
)
715 BlockDriver
*drv
= bs
->drv
;
716 BlockDriverState
*filtered
= bdrv_filter_bs(bs
);
718 if (drv
&& drv
->bdrv_probe_blocksizes
) {
719 return drv
->bdrv_probe_blocksizes(bs
, bsz
);
720 } else if (filtered
) {
721 return bdrv_probe_blocksizes(filtered
, bsz
);
728 * Try to get @bs's geometry (cyls, heads, sectors).
729 * On success, store them in @geo struct and return 0.
730 * On failure return -errno.
731 * @bs must not be empty.
733 int bdrv_probe_geometry(BlockDriverState
*bs
, HDGeometry
*geo
)
735 BlockDriver
*drv
= bs
->drv
;
736 BlockDriverState
*filtered
= bdrv_filter_bs(bs
);
738 if (drv
&& drv
->bdrv_probe_geometry
) {
739 return drv
->bdrv_probe_geometry(bs
, geo
);
740 } else if (filtered
) {
741 return bdrv_probe_geometry(filtered
, geo
);
748 * Create a uniquely-named empty temporary file.
749 * Return 0 upon success, otherwise a negative errno value.
751 int get_tmp_filename(char *filename
, int size
)
754 char temp_dir
[MAX_PATH
];
755 /* GetTempFileName requires that its output buffer (4th param)
756 have length MAX_PATH or greater. */
757 assert(size
>= MAX_PATH
);
758 return (GetTempPath(MAX_PATH
, temp_dir
)
759 && GetTempFileName(temp_dir
, "qem", 0, filename
)
760 ? 0 : -GetLastError());
764 tmpdir
= getenv("TMPDIR");
768 if (snprintf(filename
, size
, "%s/vl.XXXXXX", tmpdir
) >= size
) {
771 fd
= mkstemp(filename
);
775 if (close(fd
) != 0) {
784 * Detect host devices. By convention, /dev/cdrom[N] is always
785 * recognized as a host CDROM.
787 static BlockDriver
*find_hdev_driver(const char *filename
)
789 int score_max
= 0, score
;
790 BlockDriver
*drv
= NULL
, *d
;
792 QLIST_FOREACH(d
, &bdrv_drivers
, list
) {
793 if (d
->bdrv_probe_device
) {
794 score
= d
->bdrv_probe_device(filename
);
795 if (score
> score_max
) {
805 static BlockDriver
*bdrv_do_find_protocol(const char *protocol
)
809 QLIST_FOREACH(drv1
, &bdrv_drivers
, list
) {
810 if (drv1
->protocol_name
&& !strcmp(drv1
->protocol_name
, protocol
)) {
818 BlockDriver
*bdrv_find_protocol(const char *filename
,
819 bool allow_protocol_prefix
,
828 /* TODO Drivers without bdrv_file_open must be specified explicitly */
831 * XXX(hch): we really should not let host device detection
832 * override an explicit protocol specification, but moving this
833 * later breaks access to device names with colons in them.
834 * Thanks to the brain-dead persistent naming schemes on udev-
835 * based Linux systems those actually are quite common.
837 drv1
= find_hdev_driver(filename
);
842 if (!path_has_protocol(filename
) || !allow_protocol_prefix
) {
846 p
= strchr(filename
, ':');
849 if (len
> sizeof(protocol
) - 1)
850 len
= sizeof(protocol
) - 1;
851 memcpy(protocol
, filename
, len
);
852 protocol
[len
] = '\0';
854 drv1
= bdrv_do_find_protocol(protocol
);
859 for (i
= 0; i
< (int)ARRAY_SIZE(block_driver_modules
); ++i
) {
860 if (block_driver_modules
[i
].protocol_name
&&
861 !strcmp(block_driver_modules
[i
].protocol_name
, protocol
)) {
862 block_module_load_one(block_driver_modules
[i
].library_name
);
867 drv1
= bdrv_do_find_protocol(protocol
);
869 error_setg(errp
, "Unknown protocol '%s'", protocol
);
875 * Guess image format by probing its contents.
876 * This is not a good idea when your image is raw (CVE-2008-2004), but
877 * we do it anyway for backward compatibility.
879 * @buf contains the image's first @buf_size bytes.
880 * @buf_size is the buffer size in bytes (generally BLOCK_PROBE_BUF_SIZE,
881 * but can be smaller if the image file is smaller)
882 * @filename is its filename.
884 * For all block drivers, call the bdrv_probe() method to get its
886 * Return the first block driver with the highest probing score.
888 BlockDriver
*bdrv_probe_all(const uint8_t *buf
, int buf_size
,
889 const char *filename
)
891 int score_max
= 0, score
;
892 BlockDriver
*drv
= NULL
, *d
;
894 QLIST_FOREACH(d
, &bdrv_drivers
, list
) {
896 score
= d
->bdrv_probe(buf
, buf_size
, filename
);
897 if (score
> score_max
) {
907 static int find_image_format(BlockBackend
*file
, const char *filename
,
908 BlockDriver
**pdrv
, Error
**errp
)
911 uint8_t buf
[BLOCK_PROBE_BUF_SIZE
];
914 /* Return the raw BlockDriver * to scsi-generic devices or empty drives */
915 if (blk_is_sg(file
) || !blk_is_inserted(file
) || blk_getlength(file
) == 0) {
920 ret
= blk_pread(file
, 0, buf
, sizeof(buf
));
922 error_setg_errno(errp
, -ret
, "Could not read image for determining its "
928 drv
= bdrv_probe_all(buf
, ret
, filename
);
930 error_setg(errp
, "Could not determine image format: No compatible "
939 * Set the current 'total_sectors' value
940 * Return 0 on success, -errno on error.
942 int refresh_total_sectors(BlockDriverState
*bs
, int64_t hint
)
944 BlockDriver
*drv
= bs
->drv
;
950 /* Do not attempt drv->bdrv_getlength() on scsi-generic devices */
954 /* query actual device if possible, otherwise just trust the hint */
955 if (drv
->bdrv_getlength
) {
956 int64_t length
= drv
->bdrv_getlength(bs
);
960 hint
= DIV_ROUND_UP(length
, BDRV_SECTOR_SIZE
);
963 bs
->total_sectors
= hint
;
968 * Combines a QDict of new block driver @options with any missing options taken
969 * from @old_options, so that leaving out an option defaults to its old value.
971 static void bdrv_join_options(BlockDriverState
*bs
, QDict
*options
,
974 if (bs
->drv
&& bs
->drv
->bdrv_join_options
) {
975 bs
->drv
->bdrv_join_options(options
, old_options
);
977 qdict_join(options
, old_options
, false);
981 static BlockdevDetectZeroesOptions
bdrv_parse_detect_zeroes(QemuOpts
*opts
,
985 Error
*local_err
= NULL
;
986 char *value
= qemu_opt_get_del(opts
, "detect-zeroes");
987 BlockdevDetectZeroesOptions detect_zeroes
=
988 qapi_enum_parse(&BlockdevDetectZeroesOptions_lookup
, value
,
989 BLOCKDEV_DETECT_ZEROES_OPTIONS_OFF
, &local_err
);
992 error_propagate(errp
, local_err
);
993 return detect_zeroes
;
996 if (detect_zeroes
== BLOCKDEV_DETECT_ZEROES_OPTIONS_UNMAP
&&
997 !(open_flags
& BDRV_O_UNMAP
))
999 error_setg(errp
, "setting detect-zeroes to unmap is not allowed "
1000 "without setting discard operation to unmap");
1003 return detect_zeroes
;
1007 * Set open flags for aio engine
1009 * Return 0 on success, -1 if the engine specified is invalid
1011 int bdrv_parse_aio(const char *mode
, int *flags
)
1013 if (!strcmp(mode
, "threads")) {
1014 /* do nothing, default */
1015 } else if (!strcmp(mode
, "native")) {
1016 *flags
|= BDRV_O_NATIVE_AIO
;
1017 #ifdef CONFIG_LINUX_IO_URING
1018 } else if (!strcmp(mode
, "io_uring")) {
1019 *flags
|= BDRV_O_IO_URING
;
1029 * Set open flags for a given discard mode
1031 * Return 0 on success, -1 if the discard mode was invalid.
1033 int bdrv_parse_discard_flags(const char *mode
, int *flags
)
1035 *flags
&= ~BDRV_O_UNMAP
;
1037 if (!strcmp(mode
, "off") || !strcmp(mode
, "ignore")) {
1039 } else if (!strcmp(mode
, "on") || !strcmp(mode
, "unmap")) {
1040 *flags
|= BDRV_O_UNMAP
;
1049 * Set open flags for a given cache mode
1051 * Return 0 on success, -1 if the cache mode was invalid.
1053 int bdrv_parse_cache_mode(const char *mode
, int *flags
, bool *writethrough
)
1055 *flags
&= ~BDRV_O_CACHE_MASK
;
1057 if (!strcmp(mode
, "off") || !strcmp(mode
, "none")) {
1058 *writethrough
= false;
1059 *flags
|= BDRV_O_NOCACHE
;
1060 } else if (!strcmp(mode
, "directsync")) {
1061 *writethrough
= true;
1062 *flags
|= BDRV_O_NOCACHE
;
1063 } else if (!strcmp(mode
, "writeback")) {
1064 *writethrough
= false;
1065 } else if (!strcmp(mode
, "unsafe")) {
1066 *writethrough
= false;
1067 *flags
|= BDRV_O_NO_FLUSH
;
1068 } else if (!strcmp(mode
, "writethrough")) {
1069 *writethrough
= true;
1077 static char *bdrv_child_get_parent_desc(BdrvChild
*c
)
1079 BlockDriverState
*parent
= c
->opaque
;
1080 return g_strdup(bdrv_get_device_or_node_name(parent
));
1083 static void bdrv_child_cb_drained_begin(BdrvChild
*child
)
1085 BlockDriverState
*bs
= child
->opaque
;
1086 bdrv_do_drained_begin_quiesce(bs
, NULL
, false);
1089 static bool bdrv_child_cb_drained_poll(BdrvChild
*child
)
1091 BlockDriverState
*bs
= child
->opaque
;
1092 return bdrv_drain_poll(bs
, false, NULL
, false);
1095 static void bdrv_child_cb_drained_end(BdrvChild
*child
,
1096 int *drained_end_counter
)
1098 BlockDriverState
*bs
= child
->opaque
;
1099 bdrv_drained_end_no_poll(bs
, drained_end_counter
);
1102 static int bdrv_child_cb_inactivate(BdrvChild
*child
)
1104 BlockDriverState
*bs
= child
->opaque
;
1105 assert(bs
->open_flags
& BDRV_O_INACTIVE
);
1109 static bool bdrv_child_cb_can_set_aio_ctx(BdrvChild
*child
, AioContext
*ctx
,
1110 GSList
**ignore
, Error
**errp
)
1112 BlockDriverState
*bs
= child
->opaque
;
1113 return bdrv_can_set_aio_context(bs
, ctx
, ignore
, errp
);
1116 static void bdrv_child_cb_set_aio_ctx(BdrvChild
*child
, AioContext
*ctx
,
1119 BlockDriverState
*bs
= child
->opaque
;
1120 return bdrv_set_aio_context_ignore(bs
, ctx
, ignore
);
1124 * Returns the options and flags that a temporary snapshot should get, based on
1125 * the originally requested flags (the originally requested image will have
1126 * flags like a backing file)
1128 static void bdrv_temp_snapshot_options(int *child_flags
, QDict
*child_options
,
1129 int parent_flags
, QDict
*parent_options
)
1131 *child_flags
= (parent_flags
& ~BDRV_O_SNAPSHOT
) | BDRV_O_TEMPORARY
;
1133 /* For temporary files, unconditional cache=unsafe is fine */
1134 qdict_set_default_str(child_options
, BDRV_OPT_CACHE_DIRECT
, "off");
1135 qdict_set_default_str(child_options
, BDRV_OPT_CACHE_NO_FLUSH
, "on");
1137 /* Copy the read-only and discard options from the parent */
1138 qdict_copy_default(child_options
, parent_options
, BDRV_OPT_READ_ONLY
);
1139 qdict_copy_default(child_options
, parent_options
, BDRV_OPT_DISCARD
);
1141 /* aio=native doesn't work for cache.direct=off, so disable it for the
1142 * temporary snapshot */
1143 *child_flags
&= ~BDRV_O_NATIVE_AIO
;
1146 static void bdrv_backing_attach(BdrvChild
*c
)
1148 BlockDriverState
*parent
= c
->opaque
;
1149 BlockDriverState
*backing_hd
= c
->bs
;
1151 assert(!parent
->backing_blocker
);
1152 error_setg(&parent
->backing_blocker
,
1153 "node is used as backing hd of '%s'",
1154 bdrv_get_device_or_node_name(parent
));
1156 bdrv_refresh_filename(backing_hd
);
1158 parent
->open_flags
&= ~BDRV_O_NO_BACKING
;
1160 bdrv_op_block_all(backing_hd
, parent
->backing_blocker
);
1161 /* Otherwise we won't be able to commit or stream */
1162 bdrv_op_unblock(backing_hd
, BLOCK_OP_TYPE_COMMIT_TARGET
,
1163 parent
->backing_blocker
);
1164 bdrv_op_unblock(backing_hd
, BLOCK_OP_TYPE_STREAM
,
1165 parent
->backing_blocker
);
1167 * We do backup in 3 ways:
1169 * The target bs is new opened, and the source is top BDS
1170 * 2. blockdev backup
1171 * Both the source and the target are top BDSes.
1172 * 3. internal backup(used for block replication)
1173 * Both the source and the target are backing file
1175 * In case 1 and 2, neither the source nor the target is the backing file.
1176 * In case 3, we will block the top BDS, so there is only one block job
1177 * for the top BDS and its backing chain.
1179 bdrv_op_unblock(backing_hd
, BLOCK_OP_TYPE_BACKUP_SOURCE
,
1180 parent
->backing_blocker
);
1181 bdrv_op_unblock(backing_hd
, BLOCK_OP_TYPE_BACKUP_TARGET
,
1182 parent
->backing_blocker
);
1185 static void bdrv_backing_detach(BdrvChild
*c
)
1187 BlockDriverState
*parent
= c
->opaque
;
1189 assert(parent
->backing_blocker
);
1190 bdrv_op_unblock_all(c
->bs
, parent
->backing_blocker
);
1191 error_free(parent
->backing_blocker
);
1192 parent
->backing_blocker
= NULL
;
1195 static int bdrv_backing_update_filename(BdrvChild
*c
, BlockDriverState
*base
,
1196 const char *filename
, Error
**errp
)
1198 BlockDriverState
*parent
= c
->opaque
;
1199 bool read_only
= bdrv_is_read_only(parent
);
1203 ret
= bdrv_reopen_set_read_only(parent
, false, errp
);
1209 ret
= bdrv_change_backing_file(parent
, filename
,
1210 base
->drv
? base
->drv
->format_name
: "",
1213 error_setg_errno(errp
, -ret
, "Could not update backing file link");
1217 bdrv_reopen_set_read_only(parent
, true, NULL
);
1224 * Returns the options and flags that a generic child of a BDS should
1225 * get, based on the given options and flags for the parent BDS.
1227 static void bdrv_inherited_options(BdrvChildRole role
, bool parent_is_format
,
1228 int *child_flags
, QDict
*child_options
,
1229 int parent_flags
, QDict
*parent_options
)
1231 int flags
= parent_flags
;
1234 * First, decide whether to set, clear, or leave BDRV_O_PROTOCOL.
1235 * Generally, the question to answer is: Should this child be
1236 * format-probed by default?
1240 * Pure and non-filtered data children of non-format nodes should
1241 * be probed by default (even when the node itself has BDRV_O_PROTOCOL
1242 * set). This only affects a very limited set of drivers (namely
1243 * quorum and blkverify when this comment was written).
1244 * Force-clear BDRV_O_PROTOCOL then.
1246 if (!parent_is_format
&&
1247 (role
& BDRV_CHILD_DATA
) &&
1248 !(role
& (BDRV_CHILD_METADATA
| BDRV_CHILD_FILTERED
)))
1250 flags
&= ~BDRV_O_PROTOCOL
;
1254 * All children of format nodes (except for COW children) and all
1255 * metadata children in general should never be format-probed.
1256 * Force-set BDRV_O_PROTOCOL then.
1258 if ((parent_is_format
&& !(role
& BDRV_CHILD_COW
)) ||
1259 (role
& BDRV_CHILD_METADATA
))
1261 flags
|= BDRV_O_PROTOCOL
;
1265 * If the cache mode isn't explicitly set, inherit direct and no-flush from
1268 qdict_copy_default(child_options
, parent_options
, BDRV_OPT_CACHE_DIRECT
);
1269 qdict_copy_default(child_options
, parent_options
, BDRV_OPT_CACHE_NO_FLUSH
);
1270 qdict_copy_default(child_options
, parent_options
, BDRV_OPT_FORCE_SHARE
);
1272 if (role
& BDRV_CHILD_COW
) {
1273 /* backing files are opened read-only by default */
1274 qdict_set_default_str(child_options
, BDRV_OPT_READ_ONLY
, "on");
1275 qdict_set_default_str(child_options
, BDRV_OPT_AUTO_READ_ONLY
, "off");
1277 /* Inherit the read-only option from the parent if it's not set */
1278 qdict_copy_default(child_options
, parent_options
, BDRV_OPT_READ_ONLY
);
1279 qdict_copy_default(child_options
, parent_options
,
1280 BDRV_OPT_AUTO_READ_ONLY
);
1284 * bdrv_co_pdiscard() respects unmap policy for the parent, so we
1285 * can default to enable it on lower layers regardless of the
1288 qdict_set_default_str(child_options
, BDRV_OPT_DISCARD
, "unmap");
1290 /* Clear flags that only apply to the top layer */
1291 flags
&= ~(BDRV_O_SNAPSHOT
| BDRV_O_NO_BACKING
| BDRV_O_COPY_ON_READ
);
1293 if (role
& BDRV_CHILD_METADATA
) {
1294 flags
&= ~BDRV_O_NO_IO
;
1296 if (role
& BDRV_CHILD_COW
) {
1297 flags
&= ~BDRV_O_TEMPORARY
;
1300 *child_flags
= flags
;
1303 static void bdrv_child_cb_attach(BdrvChild
*child
)
1305 BlockDriverState
*bs
= child
->opaque
;
1307 if (child
->role
& BDRV_CHILD_COW
) {
1308 bdrv_backing_attach(child
);
1311 bdrv_apply_subtree_drain(child
, bs
);
1314 static void bdrv_child_cb_detach(BdrvChild
*child
)
1316 BlockDriverState
*bs
= child
->opaque
;
1318 if (child
->role
& BDRV_CHILD_COW
) {
1319 bdrv_backing_detach(child
);
1322 bdrv_unapply_subtree_drain(child
, bs
);
1325 static int bdrv_child_cb_update_filename(BdrvChild
*c
, BlockDriverState
*base
,
1326 const char *filename
, Error
**errp
)
1328 if (c
->role
& BDRV_CHILD_COW
) {
1329 return bdrv_backing_update_filename(c
, base
, filename
, errp
);
1334 const BdrvChildClass child_of_bds
= {
1335 .parent_is_bds
= true,
1336 .get_parent_desc
= bdrv_child_get_parent_desc
,
1337 .inherit_options
= bdrv_inherited_options
,
1338 .drained_begin
= bdrv_child_cb_drained_begin
,
1339 .drained_poll
= bdrv_child_cb_drained_poll
,
1340 .drained_end
= bdrv_child_cb_drained_end
,
1341 .attach
= bdrv_child_cb_attach
,
1342 .detach
= bdrv_child_cb_detach
,
1343 .inactivate
= bdrv_child_cb_inactivate
,
1344 .can_set_aio_ctx
= bdrv_child_cb_can_set_aio_ctx
,
1345 .set_aio_ctx
= bdrv_child_cb_set_aio_ctx
,
1346 .update_filename
= bdrv_child_cb_update_filename
,
1349 static int bdrv_open_flags(BlockDriverState
*bs
, int flags
)
1351 int open_flags
= flags
;
1354 * Clear flags that are internal to the block layer before opening the
1357 open_flags
&= ~(BDRV_O_SNAPSHOT
| BDRV_O_NO_BACKING
| BDRV_O_PROTOCOL
);
1362 static void update_flags_from_options(int *flags
, QemuOpts
*opts
)
1364 *flags
&= ~(BDRV_O_CACHE_MASK
| BDRV_O_RDWR
| BDRV_O_AUTO_RDONLY
);
1366 if (qemu_opt_get_bool_del(opts
, BDRV_OPT_CACHE_NO_FLUSH
, false)) {
1367 *flags
|= BDRV_O_NO_FLUSH
;
1370 if (qemu_opt_get_bool_del(opts
, BDRV_OPT_CACHE_DIRECT
, false)) {
1371 *flags
|= BDRV_O_NOCACHE
;
1374 if (!qemu_opt_get_bool_del(opts
, BDRV_OPT_READ_ONLY
, false)) {
1375 *flags
|= BDRV_O_RDWR
;
1378 if (qemu_opt_get_bool_del(opts
, BDRV_OPT_AUTO_READ_ONLY
, false)) {
1379 *flags
|= BDRV_O_AUTO_RDONLY
;
1383 static void update_options_from_flags(QDict
*options
, int flags
)
1385 if (!qdict_haskey(options
, BDRV_OPT_CACHE_DIRECT
)) {
1386 qdict_put_bool(options
, BDRV_OPT_CACHE_DIRECT
, flags
& BDRV_O_NOCACHE
);
1388 if (!qdict_haskey(options
, BDRV_OPT_CACHE_NO_FLUSH
)) {
1389 qdict_put_bool(options
, BDRV_OPT_CACHE_NO_FLUSH
,
1390 flags
& BDRV_O_NO_FLUSH
);
1392 if (!qdict_haskey(options
, BDRV_OPT_READ_ONLY
)) {
1393 qdict_put_bool(options
, BDRV_OPT_READ_ONLY
, !(flags
& BDRV_O_RDWR
));
1395 if (!qdict_haskey(options
, BDRV_OPT_AUTO_READ_ONLY
)) {
1396 qdict_put_bool(options
, BDRV_OPT_AUTO_READ_ONLY
,
1397 flags
& BDRV_O_AUTO_RDONLY
);
1401 static void bdrv_assign_node_name(BlockDriverState
*bs
,
1402 const char *node_name
,
1405 char *gen_node_name
= NULL
;
1408 node_name
= gen_node_name
= id_generate(ID_BLOCK
);
1409 } else if (!id_wellformed(node_name
)) {
1411 * Check for empty string or invalid characters, but not if it is
1412 * generated (generated names use characters not available to the user)
1414 error_setg(errp
, "Invalid node name");
1418 /* takes care of avoiding namespaces collisions */
1419 if (blk_by_name(node_name
)) {
1420 error_setg(errp
, "node-name=%s is conflicting with a device id",
1425 /* takes care of avoiding duplicates node names */
1426 if (bdrv_find_node(node_name
)) {
1427 error_setg(errp
, "Duplicate node name");
1431 /* Make sure that the node name isn't truncated */
1432 if (strlen(node_name
) >= sizeof(bs
->node_name
)) {
1433 error_setg(errp
, "Node name too long");
1437 /* copy node name into the bs and insert it into the graph list */
1438 pstrcpy(bs
->node_name
, sizeof(bs
->node_name
), node_name
);
1439 QTAILQ_INSERT_TAIL(&graph_bdrv_states
, bs
, node_list
);
1441 g_free(gen_node_name
);
1444 static int bdrv_open_driver(BlockDriverState
*bs
, BlockDriver
*drv
,
1445 const char *node_name
, QDict
*options
,
1446 int open_flags
, Error
**errp
)
1448 Error
*local_err
= NULL
;
1451 bdrv_assign_node_name(bs
, node_name
, &local_err
);
1453 error_propagate(errp
, local_err
);
1458 bs
->read_only
= !(bs
->open_flags
& BDRV_O_RDWR
);
1459 bs
->opaque
= g_malloc0(drv
->instance_size
);
1461 if (drv
->bdrv_file_open
) {
1462 assert(!drv
->bdrv_needs_filename
|| bs
->filename
[0]);
1463 ret
= drv
->bdrv_file_open(bs
, options
, open_flags
, &local_err
);
1464 } else if (drv
->bdrv_open
) {
1465 ret
= drv
->bdrv_open(bs
, options
, open_flags
, &local_err
);
1472 error_propagate(errp
, local_err
);
1473 } else if (bs
->filename
[0]) {
1474 error_setg_errno(errp
, -ret
, "Could not open '%s'", bs
->filename
);
1476 error_setg_errno(errp
, -ret
, "Could not open image");
1481 ret
= refresh_total_sectors(bs
, bs
->total_sectors
);
1483 error_setg_errno(errp
, -ret
, "Could not refresh total sector count");
1487 bdrv_refresh_limits(bs
, &local_err
);
1489 error_propagate(errp
, local_err
);
1493 assert(bdrv_opt_mem_align(bs
) != 0);
1494 assert(bdrv_min_mem_align(bs
) != 0);
1495 assert(is_power_of_2(bs
->bl
.request_alignment
));
1497 for (i
= 0; i
< bs
->quiesce_counter
; i
++) {
1498 if (drv
->bdrv_co_drain_begin
) {
1499 drv
->bdrv_co_drain_begin(bs
);
1506 if (bs
->file
!= NULL
) {
1507 bdrv_unref_child(bs
, bs
->file
);
1515 BlockDriverState
*bdrv_new_open_driver(BlockDriver
*drv
, const char *node_name
,
1516 int flags
, Error
**errp
)
1518 BlockDriverState
*bs
;
1522 bs
->open_flags
= flags
;
1523 bs
->explicit_options
= qdict_new();
1524 bs
->options
= qdict_new();
1527 update_options_from_flags(bs
->options
, flags
);
1529 ret
= bdrv_open_driver(bs
, drv
, node_name
, bs
->options
, flags
, errp
);
1531 qobject_unref(bs
->explicit_options
);
1532 bs
->explicit_options
= NULL
;
1533 qobject_unref(bs
->options
);
1542 QemuOptsList bdrv_runtime_opts
= {
1543 .name
= "bdrv_common",
1544 .head
= QTAILQ_HEAD_INITIALIZER(bdrv_runtime_opts
.head
),
1547 .name
= "node-name",
1548 .type
= QEMU_OPT_STRING
,
1549 .help
= "Node name of the block device node",
1553 .type
= QEMU_OPT_STRING
,
1554 .help
= "Block driver to use for the node",
1557 .name
= BDRV_OPT_CACHE_DIRECT
,
1558 .type
= QEMU_OPT_BOOL
,
1559 .help
= "Bypass software writeback cache on the host",
1562 .name
= BDRV_OPT_CACHE_NO_FLUSH
,
1563 .type
= QEMU_OPT_BOOL
,
1564 .help
= "Ignore flush requests",
1567 .name
= BDRV_OPT_READ_ONLY
,
1568 .type
= QEMU_OPT_BOOL
,
1569 .help
= "Node is opened in read-only mode",
1572 .name
= BDRV_OPT_AUTO_READ_ONLY
,
1573 .type
= QEMU_OPT_BOOL
,
1574 .help
= "Node can become read-only if opening read-write fails",
1577 .name
= "detect-zeroes",
1578 .type
= QEMU_OPT_STRING
,
1579 .help
= "try to optimize zero writes (off, on, unmap)",
1582 .name
= BDRV_OPT_DISCARD
,
1583 .type
= QEMU_OPT_STRING
,
1584 .help
= "discard operation (ignore/off, unmap/on)",
1587 .name
= BDRV_OPT_FORCE_SHARE
,
1588 .type
= QEMU_OPT_BOOL
,
1589 .help
= "always accept other writers (default: off)",
1591 { /* end of list */ }
1595 QemuOptsList bdrv_create_opts_simple
= {
1596 .name
= "simple-create-opts",
1597 .head
= QTAILQ_HEAD_INITIALIZER(bdrv_create_opts_simple
.head
),
1600 .name
= BLOCK_OPT_SIZE
,
1601 .type
= QEMU_OPT_SIZE
,
1602 .help
= "Virtual disk size"
1605 .name
= BLOCK_OPT_PREALLOC
,
1606 .type
= QEMU_OPT_STRING
,
1607 .help
= "Preallocation mode (allowed values: off)"
1609 { /* end of list */ }
1614 * Common part for opening disk images and files
1616 * Removes all processed options from *options.
1618 static int bdrv_open_common(BlockDriverState
*bs
, BlockBackend
*file
,
1619 QDict
*options
, Error
**errp
)
1621 int ret
, open_flags
;
1622 const char *filename
;
1623 const char *driver_name
= NULL
;
1624 const char *node_name
= NULL
;
1625 const char *discard
;
1628 Error
*local_err
= NULL
;
1630 assert(bs
->file
== NULL
);
1631 assert(options
!= NULL
&& bs
->options
!= options
);
1633 opts
= qemu_opts_create(&bdrv_runtime_opts
, NULL
, 0, &error_abort
);
1634 if (!qemu_opts_absorb_qdict(opts
, options
, errp
)) {
1639 update_flags_from_options(&bs
->open_flags
, opts
);
1641 driver_name
= qemu_opt_get(opts
, "driver");
1642 drv
= bdrv_find_format(driver_name
);
1643 assert(drv
!= NULL
);
1645 bs
->force_share
= qemu_opt_get_bool(opts
, BDRV_OPT_FORCE_SHARE
, false);
1647 if (bs
->force_share
&& (bs
->open_flags
& BDRV_O_RDWR
)) {
1649 BDRV_OPT_FORCE_SHARE
1650 "=on can only be used with read-only images");
1656 bdrv_refresh_filename(blk_bs(file
));
1657 filename
= blk_bs(file
)->filename
;
1660 * Caution: while qdict_get_try_str() is fine, getting
1661 * non-string types would require more care. When @options
1662 * come from -blockdev or blockdev_add, its members are typed
1663 * according to the QAPI schema, but when they come from
1664 * -drive, they're all QString.
1666 filename
= qdict_get_try_str(options
, "filename");
1669 if (drv
->bdrv_needs_filename
&& (!filename
|| !filename
[0])) {
1670 error_setg(errp
, "The '%s' block driver requires a file name",
1676 trace_bdrv_open_common(bs
, filename
?: "", bs
->open_flags
,
1679 bs
->read_only
= !(bs
->open_flags
& BDRV_O_RDWR
);
1681 if (use_bdrv_whitelist
&& !bdrv_is_whitelisted(drv
, bs
->read_only
)) {
1682 if (!bs
->read_only
&& bdrv_is_whitelisted(drv
, true)) {
1683 ret
= bdrv_apply_auto_read_only(bs
, NULL
, NULL
);
1689 !bs
->read_only
&& bdrv_is_whitelisted(drv
, true)
1690 ? "Driver '%s' can only be used for read-only devices"
1691 : "Driver '%s' is not whitelisted",
1697 /* bdrv_new() and bdrv_close() make it so */
1698 assert(qatomic_read(&bs
->copy_on_read
) == 0);
1700 if (bs
->open_flags
& BDRV_O_COPY_ON_READ
) {
1701 if (!bs
->read_only
) {
1702 bdrv_enable_copy_on_read(bs
);
1704 error_setg(errp
, "Can't use copy-on-read on read-only device");
1710 discard
= qemu_opt_get(opts
, BDRV_OPT_DISCARD
);
1711 if (discard
!= NULL
) {
1712 if (bdrv_parse_discard_flags(discard
, &bs
->open_flags
) != 0) {
1713 error_setg(errp
, "Invalid discard option");
1720 bdrv_parse_detect_zeroes(opts
, bs
->open_flags
, &local_err
);
1722 error_propagate(errp
, local_err
);
1727 if (filename
!= NULL
) {
1728 pstrcpy(bs
->filename
, sizeof(bs
->filename
), filename
);
1730 bs
->filename
[0] = '\0';
1732 pstrcpy(bs
->exact_filename
, sizeof(bs
->exact_filename
), bs
->filename
);
1734 /* Open the image, either directly or using a protocol */
1735 open_flags
= bdrv_open_flags(bs
, bs
->open_flags
);
1736 node_name
= qemu_opt_get(opts
, "node-name");
1738 assert(!drv
->bdrv_file_open
|| file
== NULL
);
1739 ret
= bdrv_open_driver(bs
, drv
, node_name
, options
, open_flags
, errp
);
1744 qemu_opts_del(opts
);
1748 qemu_opts_del(opts
);
1752 static QDict
*parse_json_filename(const char *filename
, Error
**errp
)
1754 QObject
*options_obj
;
1758 ret
= strstart(filename
, "json:", &filename
);
1761 options_obj
= qobject_from_json(filename
, errp
);
1763 error_prepend(errp
, "Could not parse the JSON options: ");
1767 options
= qobject_to(QDict
, options_obj
);
1769 qobject_unref(options_obj
);
1770 error_setg(errp
, "Invalid JSON object given");
1774 qdict_flatten(options
);
1779 static void parse_json_protocol(QDict
*options
, const char **pfilename
,
1782 QDict
*json_options
;
1783 Error
*local_err
= NULL
;
1785 /* Parse json: pseudo-protocol */
1786 if (!*pfilename
|| !g_str_has_prefix(*pfilename
, "json:")) {
1790 json_options
= parse_json_filename(*pfilename
, &local_err
);
1792 error_propagate(errp
, local_err
);
1796 /* Options given in the filename have lower priority than options
1797 * specified directly */
1798 qdict_join(options
, json_options
, false);
1799 qobject_unref(json_options
);
1804 * Fills in default options for opening images and converts the legacy
1805 * filename/flags pair to option QDict entries.
1806 * The BDRV_O_PROTOCOL flag in *flags will be set or cleared accordingly if a
1807 * block driver has been specified explicitly.
1809 static int bdrv_fill_options(QDict
**options
, const char *filename
,
1810 int *flags
, Error
**errp
)
1812 const char *drvname
;
1813 bool protocol
= *flags
& BDRV_O_PROTOCOL
;
1814 bool parse_filename
= false;
1815 BlockDriver
*drv
= NULL
;
1816 Error
*local_err
= NULL
;
1819 * Caution: while qdict_get_try_str() is fine, getting non-string
1820 * types would require more care. When @options come from
1821 * -blockdev or blockdev_add, its members are typed according to
1822 * the QAPI schema, but when they come from -drive, they're all
1825 drvname
= qdict_get_try_str(*options
, "driver");
1827 drv
= bdrv_find_format(drvname
);
1829 error_setg(errp
, "Unknown driver '%s'", drvname
);
1832 /* If the user has explicitly specified the driver, this choice should
1833 * override the BDRV_O_PROTOCOL flag */
1834 protocol
= drv
->bdrv_file_open
;
1838 *flags
|= BDRV_O_PROTOCOL
;
1840 *flags
&= ~BDRV_O_PROTOCOL
;
1843 /* Translate cache options from flags into options */
1844 update_options_from_flags(*options
, *flags
);
1846 /* Fetch the file name from the options QDict if necessary */
1847 if (protocol
&& filename
) {
1848 if (!qdict_haskey(*options
, "filename")) {
1849 qdict_put_str(*options
, "filename", filename
);
1850 parse_filename
= true;
1852 error_setg(errp
, "Can't specify 'file' and 'filename' options at "
1858 /* Find the right block driver */
1859 /* See cautionary note on accessing @options above */
1860 filename
= qdict_get_try_str(*options
, "filename");
1862 if (!drvname
&& protocol
) {
1864 drv
= bdrv_find_protocol(filename
, parse_filename
, errp
);
1869 drvname
= drv
->format_name
;
1870 qdict_put_str(*options
, "driver", drvname
);
1872 error_setg(errp
, "Must specify either driver or file");
1877 assert(drv
|| !protocol
);
1879 /* Driver-specific filename parsing */
1880 if (drv
&& drv
->bdrv_parse_filename
&& parse_filename
) {
1881 drv
->bdrv_parse_filename(filename
, *options
, &local_err
);
1883 error_propagate(errp
, local_err
);
1887 if (!drv
->bdrv_needs_filename
) {
1888 qdict_del(*options
, "filename");
1895 static int bdrv_child_check_perm(BdrvChild
*c
, BlockReopenQueue
*q
,
1896 uint64_t perm
, uint64_t shared
,
1897 GSList
*ignore_children
,
1898 bool *tighten_restrictions
, Error
**errp
);
1899 static void bdrv_child_abort_perm_update(BdrvChild
*c
);
1900 static void bdrv_child_set_perm(BdrvChild
*c
, uint64_t perm
, uint64_t shared
);
1902 typedef struct BlockReopenQueueEntry
{
1905 BDRVReopenState state
;
1906 QTAILQ_ENTRY(BlockReopenQueueEntry
) entry
;
1907 } BlockReopenQueueEntry
;
1910 * Return the flags that @bs will have after the reopens in @q have
1911 * successfully completed. If @q is NULL (or @bs is not contained in @q),
1912 * return the current flags.
1914 static int bdrv_reopen_get_flags(BlockReopenQueue
*q
, BlockDriverState
*bs
)
1916 BlockReopenQueueEntry
*entry
;
1919 QTAILQ_FOREACH(entry
, q
, entry
) {
1920 if (entry
->state
.bs
== bs
) {
1921 return entry
->state
.flags
;
1926 return bs
->open_flags
;
1929 /* Returns whether the image file can be written to after the reopen queue @q
1930 * has been successfully applied, or right now if @q is NULL. */
1931 static bool bdrv_is_writable_after_reopen(BlockDriverState
*bs
,
1932 BlockReopenQueue
*q
)
1934 int flags
= bdrv_reopen_get_flags(q
, bs
);
1936 return (flags
& (BDRV_O_RDWR
| BDRV_O_INACTIVE
)) == BDRV_O_RDWR
;
1940 * Return whether the BDS can be written to. This is not necessarily
1941 * the same as !bdrv_is_read_only(bs), as inactivated images may not
1942 * be written to but do not count as read-only images.
1944 bool bdrv_is_writable(BlockDriverState
*bs
)
1946 return bdrv_is_writable_after_reopen(bs
, NULL
);
1949 static void bdrv_child_perm(BlockDriverState
*bs
, BlockDriverState
*child_bs
,
1950 BdrvChild
*c
, BdrvChildRole role
,
1951 BlockReopenQueue
*reopen_queue
,
1952 uint64_t parent_perm
, uint64_t parent_shared
,
1953 uint64_t *nperm
, uint64_t *nshared
)
1955 assert(bs
->drv
&& bs
->drv
->bdrv_child_perm
);
1956 bs
->drv
->bdrv_child_perm(bs
, c
, role
, reopen_queue
,
1957 parent_perm
, parent_shared
,
1959 /* TODO Take force_share from reopen_queue */
1960 if (child_bs
&& child_bs
->force_share
) {
1961 *nshared
= BLK_PERM_ALL
;
1966 * Check whether permissions on this node can be changed in a way that
1967 * @cumulative_perms and @cumulative_shared_perms are the new cumulative
1968 * permissions of all its parents. This involves checking whether all necessary
1969 * permission changes to child nodes can be performed.
1971 * Will set *tighten_restrictions to true if and only if new permissions have to
1972 * be taken or currently shared permissions are to be unshared. Otherwise,
1973 * errors are not fatal as long as the caller accepts that the restrictions
1974 * remain tighter than they need to be. The caller still has to abort the
1976 * @tighten_restrictions cannot be used together with @q: When reopening, we may
1977 * encounter fatal errors even though no restrictions are to be tightened. For
1978 * example, changing a node from RW to RO will fail if the WRITE permission is
1981 * A call to this function must always be followed by a call to bdrv_set_perm()
1982 * or bdrv_abort_perm_update().
1984 static int bdrv_check_perm(BlockDriverState
*bs
, BlockReopenQueue
*q
,
1985 uint64_t cumulative_perms
,
1986 uint64_t cumulative_shared_perms
,
1987 GSList
*ignore_children
,
1988 bool *tighten_restrictions
, Error
**errp
)
1990 BlockDriver
*drv
= bs
->drv
;
1994 assert(!q
|| !tighten_restrictions
);
1996 if (tighten_restrictions
) {
1997 uint64_t current_perms
, current_shared
;
1998 uint64_t added_perms
, removed_shared_perms
;
2000 bdrv_get_cumulative_perm(bs
, ¤t_perms
, ¤t_shared
);
2002 added_perms
= cumulative_perms
& ~current_perms
;
2003 removed_shared_perms
= current_shared
& ~cumulative_shared_perms
;
2005 *tighten_restrictions
= added_perms
|| removed_shared_perms
;
2008 /* Write permissions never work with read-only images */
2009 if ((cumulative_perms
& (BLK_PERM_WRITE
| BLK_PERM_WRITE_UNCHANGED
)) &&
2010 !bdrv_is_writable_after_reopen(bs
, q
))
2012 if (!bdrv_is_writable_after_reopen(bs
, NULL
)) {
2013 error_setg(errp
, "Block node is read-only");
2015 uint64_t current_perms
, current_shared
;
2016 bdrv_get_cumulative_perm(bs
, ¤t_perms
, ¤t_shared
);
2017 if (current_perms
& (BLK_PERM_WRITE
| BLK_PERM_WRITE_UNCHANGED
)) {
2018 error_setg(errp
, "Cannot make block node read-only, there is "
2021 error_setg(errp
, "Cannot make block node read-only and create "
2030 * Unaligned requests will automatically be aligned to bl.request_alignment
2031 * and without RESIZE we can't extend requests to write to space beyond the
2032 * end of the image, so it's required that the image size is aligned.
2034 if ((cumulative_perms
& (BLK_PERM_WRITE
| BLK_PERM_WRITE_UNCHANGED
)) &&
2035 !(cumulative_perms
& BLK_PERM_RESIZE
))
2037 if ((bs
->total_sectors
* BDRV_SECTOR_SIZE
) % bs
->bl
.request_alignment
) {
2038 error_setg(errp
, "Cannot get 'write' permission without 'resize': "
2039 "Image size is not a multiple of request "
2045 /* Check this node */
2050 if (drv
->bdrv_check_perm
) {
2051 return drv
->bdrv_check_perm(bs
, cumulative_perms
,
2052 cumulative_shared_perms
, errp
);
2055 /* Drivers that never have children can omit .bdrv_child_perm() */
2056 if (!drv
->bdrv_child_perm
) {
2057 assert(QLIST_EMPTY(&bs
->children
));
2061 /* Check all children */
2062 QLIST_FOREACH(c
, &bs
->children
, next
) {
2063 uint64_t cur_perm
, cur_shared
;
2064 bool child_tighten_restr
;
2066 bdrv_child_perm(bs
, c
->bs
, c
, c
->role
, q
,
2067 cumulative_perms
, cumulative_shared_perms
,
2068 &cur_perm
, &cur_shared
);
2069 ret
= bdrv_child_check_perm(c
, q
, cur_perm
, cur_shared
, ignore_children
,
2070 tighten_restrictions
? &child_tighten_restr
2073 if (tighten_restrictions
) {
2074 *tighten_restrictions
|= child_tighten_restr
;
2085 * Notifies drivers that after a previous bdrv_check_perm() call, the
2086 * permission update is not performed and any preparations made for it (e.g.
2087 * taken file locks) need to be undone.
2089 * This function recursively notifies all child nodes.
2091 static void bdrv_abort_perm_update(BlockDriverState
*bs
)
2093 BlockDriver
*drv
= bs
->drv
;
2100 if (drv
->bdrv_abort_perm_update
) {
2101 drv
->bdrv_abort_perm_update(bs
);
2104 QLIST_FOREACH(c
, &bs
->children
, next
) {
2105 bdrv_child_abort_perm_update(c
);
2109 static void bdrv_set_perm(BlockDriverState
*bs
, uint64_t cumulative_perms
,
2110 uint64_t cumulative_shared_perms
)
2112 BlockDriver
*drv
= bs
->drv
;
2119 /* Update this node */
2120 if (drv
->bdrv_set_perm
) {
2121 drv
->bdrv_set_perm(bs
, cumulative_perms
, cumulative_shared_perms
);
2124 /* Drivers that never have children can omit .bdrv_child_perm() */
2125 if (!drv
->bdrv_child_perm
) {
2126 assert(QLIST_EMPTY(&bs
->children
));
2130 /* Update all children */
2131 QLIST_FOREACH(c
, &bs
->children
, next
) {
2132 uint64_t cur_perm
, cur_shared
;
2133 bdrv_child_perm(bs
, c
->bs
, c
, c
->role
, NULL
,
2134 cumulative_perms
, cumulative_shared_perms
,
2135 &cur_perm
, &cur_shared
);
2136 bdrv_child_set_perm(c
, cur_perm
, cur_shared
);
2140 void bdrv_get_cumulative_perm(BlockDriverState
*bs
, uint64_t *perm
,
2141 uint64_t *shared_perm
)
2144 uint64_t cumulative_perms
= 0;
2145 uint64_t cumulative_shared_perms
= BLK_PERM_ALL
;
2147 QLIST_FOREACH(c
, &bs
->parents
, next_parent
) {
2148 cumulative_perms
|= c
->perm
;
2149 cumulative_shared_perms
&= c
->shared_perm
;
2152 *perm
= cumulative_perms
;
2153 *shared_perm
= cumulative_shared_perms
;
2156 static char *bdrv_child_user_desc(BdrvChild
*c
)
2158 if (c
->klass
->get_parent_desc
) {
2159 return c
->klass
->get_parent_desc(c
);
2162 return g_strdup("another user");
2165 char *bdrv_perm_names(uint64_t perm
)
2171 { BLK_PERM_CONSISTENT_READ
, "consistent read" },
2172 { BLK_PERM_WRITE
, "write" },
2173 { BLK_PERM_WRITE_UNCHANGED
, "write unchanged" },
2174 { BLK_PERM_RESIZE
, "resize" },
2175 { BLK_PERM_GRAPH_MOD
, "change children" },
2179 GString
*result
= g_string_sized_new(30);
2180 struct perm_name
*p
;
2182 for (p
= permissions
; p
->name
; p
++) {
2183 if (perm
& p
->perm
) {
2184 if (result
->len
> 0) {
2185 g_string_append(result
, ", ");
2187 g_string_append(result
, p
->name
);
2191 return g_string_free(result
, FALSE
);
2195 * Checks whether a new reference to @bs can be added if the new user requires
2196 * @new_used_perm/@new_shared_perm as its permissions. If @ignore_children is
2197 * set, the BdrvChild objects in this list are ignored in the calculations;
2198 * this allows checking permission updates for an existing reference.
2200 * See bdrv_check_perm() for the semantics of @tighten_restrictions.
2202 * Needs to be followed by a call to either bdrv_set_perm() or
2203 * bdrv_abort_perm_update(). */
2204 static int bdrv_check_update_perm(BlockDriverState
*bs
, BlockReopenQueue
*q
,
2205 uint64_t new_used_perm
,
2206 uint64_t new_shared_perm
,
2207 GSList
*ignore_children
,
2208 bool *tighten_restrictions
,
2212 uint64_t cumulative_perms
= new_used_perm
;
2213 uint64_t cumulative_shared_perms
= new_shared_perm
;
2215 assert(!q
|| !tighten_restrictions
);
2217 /* There is no reason why anyone couldn't tolerate write_unchanged */
2218 assert(new_shared_perm
& BLK_PERM_WRITE_UNCHANGED
);
2220 QLIST_FOREACH(c
, &bs
->parents
, next_parent
) {
2221 if (g_slist_find(ignore_children
, c
)) {
2225 if ((new_used_perm
& c
->shared_perm
) != new_used_perm
) {
2226 char *user
= bdrv_child_user_desc(c
);
2227 char *perm_names
= bdrv_perm_names(new_used_perm
& ~c
->shared_perm
);
2229 if (tighten_restrictions
) {
2230 *tighten_restrictions
= true;
2233 error_setg(errp
, "Conflicts with use by %s as '%s', which does not "
2235 user
, c
->name
, perm_names
, bdrv_get_node_name(c
->bs
));
2241 if ((c
->perm
& new_shared_perm
) != c
->perm
) {
2242 char *user
= bdrv_child_user_desc(c
);
2243 char *perm_names
= bdrv_perm_names(c
->perm
& ~new_shared_perm
);
2245 if (tighten_restrictions
) {
2246 *tighten_restrictions
= true;
2249 error_setg(errp
, "Conflicts with use by %s as '%s', which uses "
2251 user
, c
->name
, perm_names
, bdrv_get_node_name(c
->bs
));
2257 cumulative_perms
|= c
->perm
;
2258 cumulative_shared_perms
&= c
->shared_perm
;
2261 return bdrv_check_perm(bs
, q
, cumulative_perms
, cumulative_shared_perms
,
2262 ignore_children
, tighten_restrictions
, errp
);
2265 /* Needs to be followed by a call to either bdrv_child_set_perm() or
2266 * bdrv_child_abort_perm_update(). */
2267 static int bdrv_child_check_perm(BdrvChild
*c
, BlockReopenQueue
*q
,
2268 uint64_t perm
, uint64_t shared
,
2269 GSList
*ignore_children
,
2270 bool *tighten_restrictions
, Error
**errp
)
2274 ignore_children
= g_slist_prepend(g_slist_copy(ignore_children
), c
);
2275 ret
= bdrv_check_update_perm(c
->bs
, q
, perm
, shared
, ignore_children
,
2276 tighten_restrictions
, errp
);
2277 g_slist_free(ignore_children
);
2283 if (!c
->has_backup_perm
) {
2284 c
->has_backup_perm
= true;
2285 c
->backup_perm
= c
->perm
;
2286 c
->backup_shared_perm
= c
->shared_perm
;
2289 * Note: it's OK if c->has_backup_perm was already set, as we can find the
2290 * same child twice during check_perm procedure
2294 c
->shared_perm
= shared
;
2299 static void bdrv_child_set_perm(BdrvChild
*c
, uint64_t perm
, uint64_t shared
)
2301 uint64_t cumulative_perms
, cumulative_shared_perms
;
2303 c
->has_backup_perm
= false;
2306 c
->shared_perm
= shared
;
2308 bdrv_get_cumulative_perm(c
->bs
, &cumulative_perms
,
2309 &cumulative_shared_perms
);
2310 bdrv_set_perm(c
->bs
, cumulative_perms
, cumulative_shared_perms
);
2313 static void bdrv_child_abort_perm_update(BdrvChild
*c
)
2315 if (c
->has_backup_perm
) {
2316 c
->perm
= c
->backup_perm
;
2317 c
->shared_perm
= c
->backup_shared_perm
;
2318 c
->has_backup_perm
= false;
2321 bdrv_abort_perm_update(c
->bs
);
2324 int bdrv_child_try_set_perm(BdrvChild
*c
, uint64_t perm
, uint64_t shared
,
2327 Error
*local_err
= NULL
;
2329 bool tighten_restrictions
;
2331 ret
= bdrv_child_check_perm(c
, NULL
, perm
, shared
, NULL
,
2332 &tighten_restrictions
, &local_err
);
2334 bdrv_child_abort_perm_update(c
);
2335 if (tighten_restrictions
) {
2336 error_propagate(errp
, local_err
);
2339 * Our caller may intend to only loosen restrictions and
2340 * does not expect this function to fail. Errors are not
2341 * fatal in such a case, so we can just hide them from our
2344 error_free(local_err
);
2350 bdrv_child_set_perm(c
, perm
, shared
);
2355 int bdrv_child_refresh_perms(BlockDriverState
*bs
, BdrvChild
*c
, Error
**errp
)
2357 uint64_t parent_perms
, parent_shared
;
2358 uint64_t perms
, shared
;
2360 bdrv_get_cumulative_perm(bs
, &parent_perms
, &parent_shared
);
2361 bdrv_child_perm(bs
, c
->bs
, c
, c
->role
, NULL
,
2362 parent_perms
, parent_shared
, &perms
, &shared
);
2364 return bdrv_child_try_set_perm(c
, perms
, shared
, errp
);
2368 * Default implementation for .bdrv_child_perm() for block filters:
2369 * Forward CONSISTENT_READ, WRITE, WRITE_UNCHANGED, and RESIZE to the
2372 static void bdrv_filter_default_perms(BlockDriverState
*bs
, BdrvChild
*c
,
2374 BlockReopenQueue
*reopen_queue
,
2375 uint64_t perm
, uint64_t shared
,
2376 uint64_t *nperm
, uint64_t *nshared
)
2378 *nperm
= perm
& DEFAULT_PERM_PASSTHROUGH
;
2379 *nshared
= (shared
& DEFAULT_PERM_PASSTHROUGH
) | DEFAULT_PERM_UNCHANGED
;
2382 static void bdrv_default_perms_for_cow(BlockDriverState
*bs
, BdrvChild
*c
,
2384 BlockReopenQueue
*reopen_queue
,
2385 uint64_t perm
, uint64_t shared
,
2386 uint64_t *nperm
, uint64_t *nshared
)
2388 assert(role
& BDRV_CHILD_COW
);
2391 * We want consistent read from backing files if the parent needs it.
2392 * No other operations are performed on backing files.
2394 perm
&= BLK_PERM_CONSISTENT_READ
;
2397 * If the parent can deal with changing data, we're okay with a
2398 * writable and resizable backing file.
2399 * TODO Require !(perm & BLK_PERM_CONSISTENT_READ), too?
2401 if (shared
& BLK_PERM_WRITE
) {
2402 shared
= BLK_PERM_WRITE
| BLK_PERM_RESIZE
;
2407 shared
|= BLK_PERM_CONSISTENT_READ
| BLK_PERM_GRAPH_MOD
|
2408 BLK_PERM_WRITE_UNCHANGED
;
2410 if (bs
->open_flags
& BDRV_O_INACTIVE
) {
2411 shared
|= BLK_PERM_WRITE
| BLK_PERM_RESIZE
;
2418 static void bdrv_default_perms_for_storage(BlockDriverState
*bs
, BdrvChild
*c
,
2420 BlockReopenQueue
*reopen_queue
,
2421 uint64_t perm
, uint64_t shared
,
2422 uint64_t *nperm
, uint64_t *nshared
)
2426 assert(role
& (BDRV_CHILD_METADATA
| BDRV_CHILD_DATA
));
2428 flags
= bdrv_reopen_get_flags(reopen_queue
, bs
);
2431 * Apart from the modifications below, the same permissions are
2432 * forwarded and left alone as for filters
2434 bdrv_filter_default_perms(bs
, c
, role
, reopen_queue
,
2435 perm
, shared
, &perm
, &shared
);
2437 if (role
& BDRV_CHILD_METADATA
) {
2438 /* Format drivers may touch metadata even if the guest doesn't write */
2439 if (bdrv_is_writable_after_reopen(bs
, reopen_queue
)) {
2440 perm
|= BLK_PERM_WRITE
| BLK_PERM_RESIZE
;
2444 * bs->file always needs to be consistent because of the
2445 * metadata. We can never allow other users to resize or write
2448 if (!(flags
& BDRV_O_NO_IO
)) {
2449 perm
|= BLK_PERM_CONSISTENT_READ
;
2451 shared
&= ~(BLK_PERM_WRITE
| BLK_PERM_RESIZE
);
2454 if (role
& BDRV_CHILD_DATA
) {
2456 * Technically, everything in this block is a subset of the
2457 * BDRV_CHILD_METADATA path taken above, and so this could
2458 * be an "else if" branch. However, that is not obvious, and
2459 * this function is not performance critical, therefore we let
2460 * this be an independent "if".
2464 * We cannot allow other users to resize the file because the
2465 * format driver might have some assumptions about the size
2466 * (e.g. because it is stored in metadata, or because the file
2467 * is split into fixed-size data files).
2469 shared
&= ~BLK_PERM_RESIZE
;
2472 * WRITE_UNCHANGED often cannot be performed as such on the
2473 * data file. For example, the qcow2 driver may still need to
2474 * write copied clusters on copy-on-read.
2476 if (perm
& BLK_PERM_WRITE_UNCHANGED
) {
2477 perm
|= BLK_PERM_WRITE
;
2481 * If the data file is written to, the format driver may
2482 * expect to be able to resize it by writing beyond the EOF.
2484 if (perm
& BLK_PERM_WRITE
) {
2485 perm
|= BLK_PERM_RESIZE
;
2489 if (bs
->open_flags
& BDRV_O_INACTIVE
) {
2490 shared
|= BLK_PERM_WRITE
| BLK_PERM_RESIZE
;
2497 void bdrv_default_perms(BlockDriverState
*bs
, BdrvChild
*c
,
2498 BdrvChildRole role
, BlockReopenQueue
*reopen_queue
,
2499 uint64_t perm
, uint64_t shared
,
2500 uint64_t *nperm
, uint64_t *nshared
)
2502 if (role
& BDRV_CHILD_FILTERED
) {
2503 assert(!(role
& (BDRV_CHILD_DATA
| BDRV_CHILD_METADATA
|
2505 bdrv_filter_default_perms(bs
, c
, role
, reopen_queue
,
2506 perm
, shared
, nperm
, nshared
);
2507 } else if (role
& BDRV_CHILD_COW
) {
2508 assert(!(role
& (BDRV_CHILD_DATA
| BDRV_CHILD_METADATA
)));
2509 bdrv_default_perms_for_cow(bs
, c
, role
, reopen_queue
,
2510 perm
, shared
, nperm
, nshared
);
2511 } else if (role
& (BDRV_CHILD_METADATA
| BDRV_CHILD_DATA
)) {
2512 bdrv_default_perms_for_storage(bs
, c
, role
, reopen_queue
,
2513 perm
, shared
, nperm
, nshared
);
2515 g_assert_not_reached();
2519 uint64_t bdrv_qapi_perm_to_blk_perm(BlockPermission qapi_perm
)
2521 static const uint64_t permissions
[] = {
2522 [BLOCK_PERMISSION_CONSISTENT_READ
] = BLK_PERM_CONSISTENT_READ
,
2523 [BLOCK_PERMISSION_WRITE
] = BLK_PERM_WRITE
,
2524 [BLOCK_PERMISSION_WRITE_UNCHANGED
] = BLK_PERM_WRITE_UNCHANGED
,
2525 [BLOCK_PERMISSION_RESIZE
] = BLK_PERM_RESIZE
,
2526 [BLOCK_PERMISSION_GRAPH_MOD
] = BLK_PERM_GRAPH_MOD
,
2529 QEMU_BUILD_BUG_ON(ARRAY_SIZE(permissions
) != BLOCK_PERMISSION__MAX
);
2530 QEMU_BUILD_BUG_ON(1UL << ARRAY_SIZE(permissions
) != BLK_PERM_ALL
+ 1);
2532 assert(qapi_perm
< BLOCK_PERMISSION__MAX
);
2534 return permissions
[qapi_perm
];
2537 static void bdrv_replace_child_noperm(BdrvChild
*child
,
2538 BlockDriverState
*new_bs
)
2540 BlockDriverState
*old_bs
= child
->bs
;
2541 int new_bs_quiesce_counter
;
2544 assert(!child
->frozen
);
2546 if (old_bs
&& new_bs
) {
2547 assert(bdrv_get_aio_context(old_bs
) == bdrv_get_aio_context(new_bs
));
2550 new_bs_quiesce_counter
= (new_bs
? new_bs
->quiesce_counter
: 0);
2551 drain_saldo
= new_bs_quiesce_counter
- child
->parent_quiesce_counter
;
2554 * If the new child node is drained but the old one was not, flush
2555 * all outstanding requests to the old child node.
2557 while (drain_saldo
> 0 && child
->klass
->drained_begin
) {
2558 bdrv_parent_drained_begin_single(child
, true);
2563 /* Detach first so that the recursive drain sections coming from @child
2564 * are already gone and we only end the drain sections that came from
2566 if (child
->klass
->detach
) {
2567 child
->klass
->detach(child
);
2569 QLIST_REMOVE(child
, next_parent
);
2575 QLIST_INSERT_HEAD(&new_bs
->parents
, child
, next_parent
);
2578 * Detaching the old node may have led to the new node's
2579 * quiesce_counter having been decreased. Not a problem, we
2580 * just need to recognize this here and then invoke
2581 * drained_end appropriately more often.
2583 assert(new_bs
->quiesce_counter
<= new_bs_quiesce_counter
);
2584 drain_saldo
+= new_bs
->quiesce_counter
- new_bs_quiesce_counter
;
2586 /* Attach only after starting new drained sections, so that recursive
2587 * drain sections coming from @child don't get an extra .drained_begin
2589 if (child
->klass
->attach
) {
2590 child
->klass
->attach(child
);
2595 * If the old child node was drained but the new one is not, allow
2596 * requests to come in only after the new node has been attached.
2598 while (drain_saldo
< 0 && child
->klass
->drained_end
) {
2599 bdrv_parent_drained_end_single(child
);
2605 * Updates @child to change its reference to point to @new_bs, including
2606 * checking and applying the necessary permission updates both to the old node
2609 * NULL is passed as @new_bs for removing the reference before freeing @child.
2611 * If @new_bs is not NULL, bdrv_check_perm() must be called beforehand, as this
2612 * function uses bdrv_set_perm() to update the permissions according to the new
2613 * reference that @new_bs gets.
2615 * Callers must ensure that child->frozen is false.
2617 static void bdrv_replace_child(BdrvChild
*child
, BlockDriverState
*new_bs
)
2619 BlockDriverState
*old_bs
= child
->bs
;
2620 uint64_t perm
, shared_perm
;
2622 /* Asserts that child->frozen == false */
2623 bdrv_replace_child_noperm(child
, new_bs
);
2626 * Start with the new node's permissions. If @new_bs is a (direct
2627 * or indirect) child of @old_bs, we must complete the permission
2628 * update on @new_bs before we loosen the restrictions on @old_bs.
2629 * Otherwise, bdrv_check_perm() on @old_bs would re-initiate
2630 * updating the permissions of @new_bs, and thus not purely loosen
2634 bdrv_get_cumulative_perm(new_bs
, &perm
, &shared_perm
);
2635 bdrv_set_perm(new_bs
, perm
, shared_perm
);
2639 /* Update permissions for old node. This is guaranteed to succeed
2640 * because we're just taking a parent away, so we're loosening
2642 bool tighten_restrictions
;
2645 bdrv_get_cumulative_perm(old_bs
, &perm
, &shared_perm
);
2646 ret
= bdrv_check_perm(old_bs
, NULL
, perm
, shared_perm
, NULL
,
2647 &tighten_restrictions
, NULL
);
2648 assert(tighten_restrictions
== false);
2650 /* We only tried to loosen restrictions, so errors are not fatal */
2651 bdrv_abort_perm_update(old_bs
);
2653 bdrv_set_perm(old_bs
, perm
, shared_perm
);
2656 /* When the parent requiring a non-default AioContext is removed, the
2657 * node moves back to the main AioContext */
2658 bdrv_try_set_aio_context(old_bs
, qemu_get_aio_context(), NULL
);
2663 * This function steals the reference to child_bs from the caller.
2664 * That reference is later dropped by bdrv_root_unref_child().
2666 * On failure NULL is returned, errp is set and the reference to
2667 * child_bs is also dropped.
2669 * The caller must hold the AioContext lock @child_bs, but not that of @ctx
2670 * (unless @child_bs is already in @ctx).
2672 BdrvChild
*bdrv_root_attach_child(BlockDriverState
*child_bs
,
2673 const char *child_name
,
2674 const BdrvChildClass
*child_class
,
2675 BdrvChildRole child_role
,
2677 uint64_t perm
, uint64_t shared_perm
,
2678 void *opaque
, Error
**errp
)
2681 Error
*local_err
= NULL
;
2684 ret
= bdrv_check_update_perm(child_bs
, NULL
, perm
, shared_perm
, NULL
, NULL
,
2687 bdrv_abort_perm_update(child_bs
);
2688 bdrv_unref(child_bs
);
2692 child
= g_new(BdrvChild
, 1);
2693 *child
= (BdrvChild
) {
2695 .name
= g_strdup(child_name
),
2696 .klass
= child_class
,
2699 .shared_perm
= shared_perm
,
2703 /* If the AioContexts don't match, first try to move the subtree of
2704 * child_bs into the AioContext of the new parent. If this doesn't work,
2705 * try moving the parent into the AioContext of child_bs instead. */
2706 if (bdrv_get_aio_context(child_bs
) != ctx
) {
2707 ret
= bdrv_try_set_aio_context(child_bs
, ctx
, &local_err
);
2708 if (ret
< 0 && child_class
->can_set_aio_ctx
) {
2709 GSList
*ignore
= g_slist_prepend(NULL
, child
);
2710 ctx
= bdrv_get_aio_context(child_bs
);
2711 if (child_class
->can_set_aio_ctx(child
, ctx
, &ignore
, NULL
)) {
2712 error_free(local_err
);
2714 g_slist_free(ignore
);
2715 ignore
= g_slist_prepend(NULL
, child
);
2716 child_class
->set_aio_ctx(child
, ctx
, &ignore
);
2718 g_slist_free(ignore
);
2721 error_propagate(errp
, local_err
);
2723 bdrv_abort_perm_update(child_bs
);
2724 bdrv_unref(child_bs
);
2729 /* This performs the matching bdrv_set_perm() for the above check. */
2730 bdrv_replace_child(child
, child_bs
);
2736 * This function transfers the reference to child_bs from the caller
2737 * to parent_bs. That reference is later dropped by parent_bs on
2738 * bdrv_close() or if someone calls bdrv_unref_child().
2740 * On failure NULL is returned, errp is set and the reference to
2741 * child_bs is also dropped.
2743 * If @parent_bs and @child_bs are in different AioContexts, the caller must
2744 * hold the AioContext lock for @child_bs, but not for @parent_bs.
2746 BdrvChild
*bdrv_attach_child(BlockDriverState
*parent_bs
,
2747 BlockDriverState
*child_bs
,
2748 const char *child_name
,
2749 const BdrvChildClass
*child_class
,
2750 BdrvChildRole child_role
,
2754 uint64_t perm
, shared_perm
;
2756 bdrv_get_cumulative_perm(parent_bs
, &perm
, &shared_perm
);
2758 assert(parent_bs
->drv
);
2759 bdrv_child_perm(parent_bs
, child_bs
, NULL
, child_role
, NULL
,
2760 perm
, shared_perm
, &perm
, &shared_perm
);
2762 child
= bdrv_root_attach_child(child_bs
, child_name
, child_class
,
2763 child_role
, bdrv_get_aio_context(parent_bs
),
2764 perm
, shared_perm
, parent_bs
, errp
);
2765 if (child
== NULL
) {
2769 QLIST_INSERT_HEAD(&parent_bs
->children
, child
, next
);
2773 static void bdrv_detach_child(BdrvChild
*child
)
2775 QLIST_SAFE_REMOVE(child
, next
);
2777 bdrv_replace_child(child
, NULL
);
2779 g_free(child
->name
);
2783 /* Callers must ensure that child->frozen is false. */
2784 void bdrv_root_unref_child(BdrvChild
*child
)
2786 BlockDriverState
*child_bs
;
2788 child_bs
= child
->bs
;
2789 bdrv_detach_child(child
);
2790 bdrv_unref(child_bs
);
2794 * Clear all inherits_from pointers from children and grandchildren of
2795 * @root that point to @root, where necessary.
2797 static void bdrv_unset_inherits_from(BlockDriverState
*root
, BdrvChild
*child
)
2801 if (child
->bs
->inherits_from
== root
) {
2803 * Remove inherits_from only when the last reference between root and
2804 * child->bs goes away.
2806 QLIST_FOREACH(c
, &root
->children
, next
) {
2807 if (c
!= child
&& c
->bs
== child
->bs
) {
2812 child
->bs
->inherits_from
= NULL
;
2816 QLIST_FOREACH(c
, &child
->bs
->children
, next
) {
2817 bdrv_unset_inherits_from(root
, c
);
2821 /* Callers must ensure that child->frozen is false. */
2822 void bdrv_unref_child(BlockDriverState
*parent
, BdrvChild
*child
)
2824 if (child
== NULL
) {
2828 bdrv_unset_inherits_from(parent
, child
);
2829 bdrv_root_unref_child(child
);
2833 static void bdrv_parent_cb_change_media(BlockDriverState
*bs
, bool load
)
2836 QLIST_FOREACH(c
, &bs
->parents
, next_parent
) {
2837 if (c
->klass
->change_media
) {
2838 c
->klass
->change_media(c
, load
);
2843 /* Return true if you can reach parent going through child->inherits_from
2844 * recursively. If parent or child are NULL, return false */
2845 static bool bdrv_inherits_from_recursive(BlockDriverState
*child
,
2846 BlockDriverState
*parent
)
2848 while (child
&& child
!= parent
) {
2849 child
= child
->inherits_from
;
2852 return child
!= NULL
;
2856 * Return the BdrvChildRole for @bs's backing child. bs->backing is
2857 * mostly used for COW backing children (role = COW), but also for
2858 * filtered children (role = FILTERED | PRIMARY).
2860 static BdrvChildRole
bdrv_backing_role(BlockDriverState
*bs
)
2862 if (bs
->drv
&& bs
->drv
->is_filter
) {
2863 return BDRV_CHILD_FILTERED
| BDRV_CHILD_PRIMARY
;
2865 return BDRV_CHILD_COW
;
2870 * Sets the bs->backing link of a BDS. A new reference is created; callers
2871 * which don't need their own reference any more must call bdrv_unref().
2873 void bdrv_set_backing_hd(BlockDriverState
*bs
, BlockDriverState
*backing_hd
,
2876 bool update_inherits_from
= bdrv_chain_contains(bs
, backing_hd
) &&
2877 bdrv_inherits_from_recursive(backing_hd
, bs
);
2879 if (bdrv_is_backing_chain_frozen(bs
, child_bs(bs
->backing
), errp
)) {
2884 bdrv_ref(backing_hd
);
2888 /* Cannot be frozen, we checked that above */
2889 bdrv_unref_child(bs
, bs
->backing
);
2897 bs
->backing
= bdrv_attach_child(bs
, backing_hd
, "backing", &child_of_bds
,
2898 bdrv_backing_role(bs
), errp
);
2899 /* If backing_hd was already part of bs's backing chain, and
2900 * inherits_from pointed recursively to bs then let's update it to
2901 * point directly to bs (else it will become NULL). */
2902 if (bs
->backing
&& update_inherits_from
) {
2903 backing_hd
->inherits_from
= bs
;
2907 bdrv_refresh_limits(bs
, NULL
);
2911 * Opens the backing file for a BlockDriverState if not yet open
2913 * bdref_key specifies the key for the image's BlockdevRef in the options QDict.
2914 * That QDict has to be flattened; therefore, if the BlockdevRef is a QDict
2915 * itself, all options starting with "${bdref_key}." are considered part of the
2918 * TODO Can this be unified with bdrv_open_image()?
2920 int bdrv_open_backing_file(BlockDriverState
*bs
, QDict
*parent_options
,
2921 const char *bdref_key
, Error
**errp
)
2923 char *backing_filename
= NULL
;
2924 char *bdref_key_dot
;
2925 const char *reference
= NULL
;
2927 bool implicit_backing
= false;
2928 BlockDriverState
*backing_hd
;
2930 QDict
*tmp_parent_options
= NULL
;
2931 Error
*local_err
= NULL
;
2933 if (bs
->backing
!= NULL
) {
2937 /* NULL means an empty set of options */
2938 if (parent_options
== NULL
) {
2939 tmp_parent_options
= qdict_new();
2940 parent_options
= tmp_parent_options
;
2943 bs
->open_flags
&= ~BDRV_O_NO_BACKING
;
2945 bdref_key_dot
= g_strdup_printf("%s.", bdref_key
);
2946 qdict_extract_subqdict(parent_options
, &options
, bdref_key_dot
);
2947 g_free(bdref_key_dot
);
2950 * Caution: while qdict_get_try_str() is fine, getting non-string
2951 * types would require more care. When @parent_options come from
2952 * -blockdev or blockdev_add, its members are typed according to
2953 * the QAPI schema, but when they come from -drive, they're all
2956 reference
= qdict_get_try_str(parent_options
, bdref_key
);
2957 if (reference
|| qdict_haskey(options
, "file.filename")) {
2958 /* keep backing_filename NULL */
2959 } else if (bs
->backing_file
[0] == '\0' && qdict_size(options
) == 0) {
2960 qobject_unref(options
);
2963 if (qdict_size(options
) == 0) {
2964 /* If the user specifies options that do not modify the
2965 * backing file's behavior, we might still consider it the
2966 * implicit backing file. But it's easier this way, and
2967 * just specifying some of the backing BDS's options is
2968 * only possible with -drive anyway (otherwise the QAPI
2969 * schema forces the user to specify everything). */
2970 implicit_backing
= !strcmp(bs
->auto_backing_file
, bs
->backing_file
);
2973 backing_filename
= bdrv_get_full_backing_filename(bs
, &local_err
);
2976 error_propagate(errp
, local_err
);
2977 qobject_unref(options
);
2982 if (!bs
->drv
|| !bs
->drv
->supports_backing
) {
2984 error_setg(errp
, "Driver doesn't support backing files");
2985 qobject_unref(options
);
2990 bs
->backing_format
[0] != '\0' && !qdict_haskey(options
, "driver")) {
2991 qdict_put_str(options
, "driver", bs
->backing_format
);
2994 backing_hd
= bdrv_open_inherit(backing_filename
, reference
, options
, 0, bs
,
2995 &child_of_bds
, bdrv_backing_role(bs
), errp
);
2997 bs
->open_flags
|= BDRV_O_NO_BACKING
;
2998 error_prepend(errp
, "Could not open backing file: ");
3003 if (implicit_backing
) {
3004 bdrv_refresh_filename(backing_hd
);
3005 pstrcpy(bs
->auto_backing_file
, sizeof(bs
->auto_backing_file
),
3006 backing_hd
->filename
);
3009 /* Hook up the backing file link; drop our reference, bs owns the
3010 * backing_hd reference now */
3011 bdrv_set_backing_hd(bs
, backing_hd
, &local_err
);
3012 bdrv_unref(backing_hd
);
3014 error_propagate(errp
, local_err
);
3019 qdict_del(parent_options
, bdref_key
);
3022 g_free(backing_filename
);
3023 qobject_unref(tmp_parent_options
);
3027 static BlockDriverState
*
3028 bdrv_open_child_bs(const char *filename
, QDict
*options
, const char *bdref_key
,
3029 BlockDriverState
*parent
, const BdrvChildClass
*child_class
,
3030 BdrvChildRole child_role
, bool allow_none
, Error
**errp
)
3032 BlockDriverState
*bs
= NULL
;
3033 QDict
*image_options
;
3034 char *bdref_key_dot
;
3035 const char *reference
;
3037 assert(child_class
!= NULL
);
3039 bdref_key_dot
= g_strdup_printf("%s.", bdref_key
);
3040 qdict_extract_subqdict(options
, &image_options
, bdref_key_dot
);
3041 g_free(bdref_key_dot
);
3044 * Caution: while qdict_get_try_str() is fine, getting non-string
3045 * types would require more care. When @options come from
3046 * -blockdev or blockdev_add, its members are typed according to
3047 * the QAPI schema, but when they come from -drive, they're all
3050 reference
= qdict_get_try_str(options
, bdref_key
);
3051 if (!filename
&& !reference
&& !qdict_size(image_options
)) {
3053 error_setg(errp
, "A block device must be specified for \"%s\"",
3056 qobject_unref(image_options
);
3060 bs
= bdrv_open_inherit(filename
, reference
, image_options
, 0,
3061 parent
, child_class
, child_role
, errp
);
3067 qdict_del(options
, bdref_key
);
3072 * Opens a disk image whose options are given as BlockdevRef in another block
3075 * If allow_none is true, no image will be opened if filename is false and no
3076 * BlockdevRef is given. NULL will be returned, but errp remains unset.
3078 * bdrev_key specifies the key for the image's BlockdevRef in the options QDict.
3079 * That QDict has to be flattened; therefore, if the BlockdevRef is a QDict
3080 * itself, all options starting with "${bdref_key}." are considered part of the
3083 * The BlockdevRef will be removed from the options QDict.
3085 BdrvChild
*bdrv_open_child(const char *filename
,
3086 QDict
*options
, const char *bdref_key
,
3087 BlockDriverState
*parent
,
3088 const BdrvChildClass
*child_class
,
3089 BdrvChildRole child_role
,
3090 bool allow_none
, Error
**errp
)
3092 BlockDriverState
*bs
;
3094 bs
= bdrv_open_child_bs(filename
, options
, bdref_key
, parent
, child_class
,
3095 child_role
, allow_none
, errp
);
3100 return bdrv_attach_child(parent
, bs
, bdref_key
, child_class
, child_role
,
3105 * TODO Future callers may need to specify parent/child_class in order for
3106 * option inheritance to work. Existing callers use it for the root node.
3108 BlockDriverState
*bdrv_open_blockdev_ref(BlockdevRef
*ref
, Error
**errp
)
3110 BlockDriverState
*bs
= NULL
;
3111 QObject
*obj
= NULL
;
3112 QDict
*qdict
= NULL
;
3113 const char *reference
= NULL
;
3116 if (ref
->type
== QTYPE_QSTRING
) {
3117 reference
= ref
->u
.reference
;
3119 BlockdevOptions
*options
= &ref
->u
.definition
;
3120 assert(ref
->type
== QTYPE_QDICT
);
3122 v
= qobject_output_visitor_new(&obj
);
3123 visit_type_BlockdevOptions(v
, NULL
, &options
, &error_abort
);
3124 visit_complete(v
, &obj
);
3126 qdict
= qobject_to(QDict
, obj
);
3127 qdict_flatten(qdict
);
3129 /* bdrv_open_inherit() defaults to the values in bdrv_flags (for
3130 * compatibility with other callers) rather than what we want as the
3131 * real defaults. Apply the defaults here instead. */
3132 qdict_set_default_str(qdict
, BDRV_OPT_CACHE_DIRECT
, "off");
3133 qdict_set_default_str(qdict
, BDRV_OPT_CACHE_NO_FLUSH
, "off");
3134 qdict_set_default_str(qdict
, BDRV_OPT_READ_ONLY
, "off");
3135 qdict_set_default_str(qdict
, BDRV_OPT_AUTO_READ_ONLY
, "off");
3139 bs
= bdrv_open_inherit(NULL
, reference
, qdict
, 0, NULL
, NULL
, 0, errp
);
3146 static BlockDriverState
*bdrv_append_temp_snapshot(BlockDriverState
*bs
,
3148 QDict
*snapshot_options
,
3151 /* TODO: extra byte is a hack to ensure MAX_PATH space on Windows. */
3152 char *tmp_filename
= g_malloc0(PATH_MAX
+ 1);
3154 QemuOpts
*opts
= NULL
;
3155 BlockDriverState
*bs_snapshot
= NULL
;
3156 Error
*local_err
= NULL
;
3159 /* if snapshot, we create a temporary backing file and open it
3160 instead of opening 'filename' directly */
3162 /* Get the required size from the image */
3163 total_size
= bdrv_getlength(bs
);
3164 if (total_size
< 0) {
3165 error_setg_errno(errp
, -total_size
, "Could not get image size");
3169 /* Create the temporary image */
3170 ret
= get_tmp_filename(tmp_filename
, PATH_MAX
+ 1);
3172 error_setg_errno(errp
, -ret
, "Could not get temporary filename");
3176 opts
= qemu_opts_create(bdrv_qcow2
.create_opts
, NULL
, 0,
3178 qemu_opt_set_number(opts
, BLOCK_OPT_SIZE
, total_size
, &error_abort
);
3179 ret
= bdrv_create(&bdrv_qcow2
, tmp_filename
, opts
, errp
);
3180 qemu_opts_del(opts
);
3182 error_prepend(errp
, "Could not create temporary overlay '%s': ",
3187 /* Prepare options QDict for the temporary file */
3188 qdict_put_str(snapshot_options
, "file.driver", "file");
3189 qdict_put_str(snapshot_options
, "file.filename", tmp_filename
);
3190 qdict_put_str(snapshot_options
, "driver", "qcow2");
3192 bs_snapshot
= bdrv_open(NULL
, NULL
, snapshot_options
, flags
, errp
);
3193 snapshot_options
= NULL
;
3198 /* bdrv_append() consumes a strong reference to bs_snapshot
3199 * (i.e. it will call bdrv_unref() on it) even on error, so in
3200 * order to be able to return one, we have to increase
3201 * bs_snapshot's refcount here */
3202 bdrv_ref(bs_snapshot
);
3203 bdrv_append(bs_snapshot
, bs
, &local_err
);
3205 error_propagate(errp
, local_err
);
3211 qobject_unref(snapshot_options
);
3212 g_free(tmp_filename
);
3217 * Opens a disk image (raw, qcow2, vmdk, ...)
3219 * options is a QDict of options to pass to the block drivers, or NULL for an
3220 * empty set of options. The reference to the QDict belongs to the block layer
3221 * after the call (even on failure), so if the caller intends to reuse the
3222 * dictionary, it needs to use qobject_ref() before calling bdrv_open.
3224 * If *pbs is NULL, a new BDS will be created with a pointer to it stored there.
3225 * If it is not NULL, the referenced BDS will be reused.
3227 * The reference parameter may be used to specify an existing block device which
3228 * should be opened. If specified, neither options nor a filename may be given,
3229 * nor can an existing BDS be reused (that is, *pbs has to be NULL).
3231 static BlockDriverState
*bdrv_open_inherit(const char *filename
,
3232 const char *reference
,
3233 QDict
*options
, int flags
,
3234 BlockDriverState
*parent
,
3235 const BdrvChildClass
*child_class
,
3236 BdrvChildRole child_role
,
3240 BlockBackend
*file
= NULL
;
3241 BlockDriverState
*bs
;
3242 BlockDriver
*drv
= NULL
;
3244 const char *drvname
;
3245 const char *backing
;
3246 Error
*local_err
= NULL
;
3247 QDict
*snapshot_options
= NULL
;
3248 int snapshot_flags
= 0;
3250 assert(!child_class
|| !flags
);
3251 assert(!child_class
== !parent
);
3254 bool options_non_empty
= options
? qdict_size(options
) : false;
3255 qobject_unref(options
);
3257 if (filename
|| options_non_empty
) {
3258 error_setg(errp
, "Cannot reference an existing block device with "
3259 "additional options or a new filename");
3263 bs
= bdrv_lookup_bs(reference
, reference
, errp
);
3274 /* NULL means an empty set of options */
3275 if (options
== NULL
) {
3276 options
= qdict_new();
3279 /* json: syntax counts as explicit options, as if in the QDict */
3280 parse_json_protocol(options
, &filename
, &local_err
);
3285 bs
->explicit_options
= qdict_clone_shallow(options
);
3288 bool parent_is_format
;
3291 parent_is_format
= parent
->drv
->is_format
;
3294 * parent->drv is not set yet because this node is opened for
3295 * (potential) format probing. That means that @parent is going
3296 * to be a format node.
3298 parent_is_format
= true;
3301 bs
->inherits_from
= parent
;
3302 child_class
->inherit_options(child_role
, parent_is_format
,
3304 parent
->open_flags
, parent
->options
);
3307 ret
= bdrv_fill_options(&options
, filename
, &flags
, &local_err
);
3313 * Set the BDRV_O_RDWR and BDRV_O_ALLOW_RDWR flags.
3314 * Caution: getting a boolean member of @options requires care.
3315 * When @options come from -blockdev or blockdev_add, members are
3316 * typed according to the QAPI schema, but when they come from
3317 * -drive, they're all QString.
3319 if (g_strcmp0(qdict_get_try_str(options
, BDRV_OPT_READ_ONLY
), "on") &&
3320 !qdict_get_try_bool(options
, BDRV_OPT_READ_ONLY
, false)) {
3321 flags
|= (BDRV_O_RDWR
| BDRV_O_ALLOW_RDWR
);
3323 flags
&= ~BDRV_O_RDWR
;
3326 if (flags
& BDRV_O_SNAPSHOT
) {
3327 snapshot_options
= qdict_new();
3328 bdrv_temp_snapshot_options(&snapshot_flags
, snapshot_options
,
3330 /* Let bdrv_backing_options() override "read-only" */
3331 qdict_del(options
, BDRV_OPT_READ_ONLY
);
3332 bdrv_inherited_options(BDRV_CHILD_COW
, true,
3333 &flags
, options
, flags
, options
);
3336 bs
->open_flags
= flags
;
3337 bs
->options
= options
;
3338 options
= qdict_clone_shallow(options
);
3340 /* Find the right image format driver */
3341 /* See cautionary note on accessing @options above */
3342 drvname
= qdict_get_try_str(options
, "driver");
3344 drv
= bdrv_find_format(drvname
);
3346 error_setg(errp
, "Unknown driver: '%s'", drvname
);
3351 assert(drvname
|| !(flags
& BDRV_O_PROTOCOL
));
3353 /* See cautionary note on accessing @options above */
3354 backing
= qdict_get_try_str(options
, "backing");
3355 if (qobject_to(QNull
, qdict_get(options
, "backing")) != NULL
||
3356 (backing
&& *backing
== '\0'))
3359 warn_report("Use of \"backing\": \"\" is deprecated; "
3360 "use \"backing\": null instead");
3362 flags
|= BDRV_O_NO_BACKING
;
3363 qdict_del(bs
->explicit_options
, "backing");
3364 qdict_del(bs
->options
, "backing");
3365 qdict_del(options
, "backing");
3368 /* Open image file without format layer. This BlockBackend is only used for
3369 * probing, the block drivers will do their own bdrv_open_child() for the
3370 * same BDS, which is why we put the node name back into options. */
3371 if ((flags
& BDRV_O_PROTOCOL
) == 0) {
3372 BlockDriverState
*file_bs
;
3374 file_bs
= bdrv_open_child_bs(filename
, options
, "file", bs
,
3375 &child_of_bds
, BDRV_CHILD_IMAGE
,
3380 if (file_bs
!= NULL
) {
3381 /* Not requesting BLK_PERM_CONSISTENT_READ because we're only
3382 * looking at the header to guess the image format. This works even
3383 * in cases where a guest would not see a consistent state. */
3384 file
= blk_new(bdrv_get_aio_context(file_bs
), 0, BLK_PERM_ALL
);
3385 blk_insert_bs(file
, file_bs
, &local_err
);
3386 bdrv_unref(file_bs
);
3391 qdict_put_str(options
, "file", bdrv_get_node_name(file_bs
));
3395 /* Image format probing */
3398 ret
= find_image_format(file
, filename
, &drv
, &local_err
);
3403 * This option update would logically belong in bdrv_fill_options(),
3404 * but we first need to open bs->file for the probing to work, while
3405 * opening bs->file already requires the (mostly) final set of options
3406 * so that cache mode etc. can be inherited.
3408 * Adding the driver later is somewhat ugly, but it's not an option
3409 * that would ever be inherited, so it's correct. We just need to make
3410 * sure to update both bs->options (which has the full effective
3411 * options for bs) and options (which has file.* already removed).
3413 qdict_put_str(bs
->options
, "driver", drv
->format_name
);
3414 qdict_put_str(options
, "driver", drv
->format_name
);
3416 error_setg(errp
, "Must specify either driver or file");
3420 /* BDRV_O_PROTOCOL must be set iff a protocol BDS is about to be created */
3421 assert(!!(flags
& BDRV_O_PROTOCOL
) == !!drv
->bdrv_file_open
);
3422 /* file must be NULL if a protocol BDS is about to be created
3423 * (the inverse results in an error message from bdrv_open_common()) */
3424 assert(!(flags
& BDRV_O_PROTOCOL
) || !file
);
3426 /* Open the image */
3427 ret
= bdrv_open_common(bs
, file
, options
, &local_err
);
3437 /* If there is a backing file, use it */
3438 if ((flags
& BDRV_O_NO_BACKING
) == 0) {
3439 ret
= bdrv_open_backing_file(bs
, options
, "backing", &local_err
);
3441 goto close_and_fail
;
3445 /* Remove all children options and references
3446 * from bs->options and bs->explicit_options */
3447 QLIST_FOREACH(child
, &bs
->children
, next
) {
3448 char *child_key_dot
;
3449 child_key_dot
= g_strdup_printf("%s.", child
->name
);
3450 qdict_extract_subqdict(bs
->explicit_options
, NULL
, child_key_dot
);
3451 qdict_extract_subqdict(bs
->options
, NULL
, child_key_dot
);
3452 qdict_del(bs
->explicit_options
, child
->name
);
3453 qdict_del(bs
->options
, child
->name
);
3454 g_free(child_key_dot
);
3457 /* Check if any unknown options were used */
3458 if (qdict_size(options
) != 0) {
3459 const QDictEntry
*entry
= qdict_first(options
);
3460 if (flags
& BDRV_O_PROTOCOL
) {
3461 error_setg(errp
, "Block protocol '%s' doesn't support the option "
3462 "'%s'", drv
->format_name
, entry
->key
);
3465 "Block format '%s' does not support the option '%s'",
3466 drv
->format_name
, entry
->key
);
3469 goto close_and_fail
;
3472 bdrv_parent_cb_change_media(bs
, true);
3474 qobject_unref(options
);
3477 /* For snapshot=on, create a temporary qcow2 overlay. bs points to the
3478 * temporary snapshot afterwards. */
3479 if (snapshot_flags
) {
3480 BlockDriverState
*snapshot_bs
;
3481 snapshot_bs
= bdrv_append_temp_snapshot(bs
, snapshot_flags
,
3482 snapshot_options
, &local_err
);
3483 snapshot_options
= NULL
;
3485 goto close_and_fail
;
3487 /* We are not going to return bs but the overlay on top of it
3488 * (snapshot_bs); thus, we have to drop the strong reference to bs
3489 * (which we obtained by calling bdrv_new()). bs will not be deleted,
3490 * though, because the overlay still has a reference to it. */
3499 qobject_unref(snapshot_options
);
3500 qobject_unref(bs
->explicit_options
);
3501 qobject_unref(bs
->options
);
3502 qobject_unref(options
);
3504 bs
->explicit_options
= NULL
;
3506 error_propagate(errp
, local_err
);
3511 qobject_unref(snapshot_options
);
3512 qobject_unref(options
);
3513 error_propagate(errp
, local_err
);
3517 BlockDriverState
*bdrv_open(const char *filename
, const char *reference
,
3518 QDict
*options
, int flags
, Error
**errp
)
3520 return bdrv_open_inherit(filename
, reference
, options
, flags
, NULL
,
3524 /* Return true if the NULL-terminated @list contains @str */
3525 static bool is_str_in_list(const char *str
, const char *const *list
)
3529 for (i
= 0; list
[i
] != NULL
; i
++) {
3530 if (!strcmp(str
, list
[i
])) {
3539 * Check that every option set in @bs->options is also set in
3542 * Options listed in the common_options list and in
3543 * @bs->drv->mutable_opts are skipped.
3545 * Return 0 on success, otherwise return -EINVAL and set @errp.
3547 static int bdrv_reset_options_allowed(BlockDriverState
*bs
,
3548 const QDict
*new_opts
, Error
**errp
)
3550 const QDictEntry
*e
;
3551 /* These options are common to all block drivers and are handled
3552 * in bdrv_reopen_prepare() so they can be left out of @new_opts */
3553 const char *const common_options
[] = {
3554 "node-name", "discard", "cache.direct", "cache.no-flush",
3555 "read-only", "auto-read-only", "detect-zeroes", NULL
3558 for (e
= qdict_first(bs
->options
); e
; e
= qdict_next(bs
->options
, e
)) {
3559 if (!qdict_haskey(new_opts
, e
->key
) &&
3560 !is_str_in_list(e
->key
, common_options
) &&
3561 !is_str_in_list(e
->key
, bs
->drv
->mutable_opts
)) {
3562 error_setg(errp
, "Option '%s' cannot be reset "
3563 "to its default value", e
->key
);
3572 * Returns true if @child can be reached recursively from @bs
3574 static bool bdrv_recurse_has_child(BlockDriverState
*bs
,
3575 BlockDriverState
*child
)
3583 QLIST_FOREACH(c
, &bs
->children
, next
) {
3584 if (bdrv_recurse_has_child(c
->bs
, child
)) {
3593 * Adds a BlockDriverState to a simple queue for an atomic, transactional
3594 * reopen of multiple devices.
3596 * bs_queue can either be an existing BlockReopenQueue that has had QTAILQ_INIT
3597 * already performed, or alternatively may be NULL a new BlockReopenQueue will
3598 * be created and initialized. This newly created BlockReopenQueue should be
3599 * passed back in for subsequent calls that are intended to be of the same
3602 * bs is the BlockDriverState to add to the reopen queue.
3604 * options contains the changed options for the associated bs
3605 * (the BlockReopenQueue takes ownership)
3607 * flags contains the open flags for the associated bs
3609 * returns a pointer to bs_queue, which is either the newly allocated
3610 * bs_queue, or the existing bs_queue being used.
3612 * bs must be drained between bdrv_reopen_queue() and bdrv_reopen_multiple().
3614 static BlockReopenQueue
*bdrv_reopen_queue_child(BlockReopenQueue
*bs_queue
,
3615 BlockDriverState
*bs
,
3617 const BdrvChildClass
*klass
,
3619 bool parent_is_format
,
3620 QDict
*parent_options
,
3626 BlockReopenQueueEntry
*bs_entry
;
3628 QDict
*old_options
, *explicit_options
, *options_copy
;
3632 /* Make sure that the caller remembered to use a drained section. This is
3633 * important to avoid graph changes between the recursive queuing here and
3634 * bdrv_reopen_multiple(). */
3635 assert(bs
->quiesce_counter
> 0);
3637 if (bs_queue
== NULL
) {
3638 bs_queue
= g_new0(BlockReopenQueue
, 1);
3639 QTAILQ_INIT(bs_queue
);
3643 options
= qdict_new();
3646 /* Check if this BlockDriverState is already in the queue */
3647 QTAILQ_FOREACH(bs_entry
, bs_queue
, entry
) {
3648 if (bs
== bs_entry
->state
.bs
) {
3654 * Precedence of options:
3655 * 1. Explicitly passed in options (highest)
3656 * 2. Retained from explicitly set options of bs
3657 * 3. Inherited from parent node
3658 * 4. Retained from effective options of bs
3661 /* Old explicitly set values (don't overwrite by inherited value) */
3662 if (bs_entry
|| keep_old_opts
) {
3663 old_options
= qdict_clone_shallow(bs_entry
?
3664 bs_entry
->state
.explicit_options
:
3665 bs
->explicit_options
);
3666 bdrv_join_options(bs
, options
, old_options
);
3667 qobject_unref(old_options
);
3670 explicit_options
= qdict_clone_shallow(options
);
3672 /* Inherit from parent node */
3673 if (parent_options
) {
3675 klass
->inherit_options(role
, parent_is_format
, &flags
, options
,
3676 parent_flags
, parent_options
);
3678 flags
= bdrv_get_flags(bs
);
3681 if (keep_old_opts
) {
3682 /* Old values are used for options that aren't set yet */
3683 old_options
= qdict_clone_shallow(bs
->options
);
3684 bdrv_join_options(bs
, options
, old_options
);
3685 qobject_unref(old_options
);
3688 /* We have the final set of options so let's update the flags */
3689 options_copy
= qdict_clone_shallow(options
);
3690 opts
= qemu_opts_create(&bdrv_runtime_opts
, NULL
, 0, &error_abort
);
3691 qemu_opts_absorb_qdict(opts
, options_copy
, NULL
);
3692 update_flags_from_options(&flags
, opts
);
3693 qemu_opts_del(opts
);
3694 qobject_unref(options_copy
);
3696 /* bdrv_open_inherit() sets and clears some additional flags internally */
3697 flags
&= ~BDRV_O_PROTOCOL
;
3698 if (flags
& BDRV_O_RDWR
) {
3699 flags
|= BDRV_O_ALLOW_RDWR
;
3703 bs_entry
= g_new0(BlockReopenQueueEntry
, 1);
3704 QTAILQ_INSERT_TAIL(bs_queue
, bs_entry
, entry
);
3706 qobject_unref(bs_entry
->state
.options
);
3707 qobject_unref(bs_entry
->state
.explicit_options
);
3710 bs_entry
->state
.bs
= bs
;
3711 bs_entry
->state
.options
= options
;
3712 bs_entry
->state
.explicit_options
= explicit_options
;
3713 bs_entry
->state
.flags
= flags
;
3715 /* This needs to be overwritten in bdrv_reopen_prepare() */
3716 bs_entry
->state
.perm
= UINT64_MAX
;
3717 bs_entry
->state
.shared_perm
= 0;
3720 * If keep_old_opts is false then it means that unspecified
3721 * options must be reset to their original value. We don't allow
3722 * resetting 'backing' but we need to know if the option is
3723 * missing in order to decide if we have to return an error.
3725 if (!keep_old_opts
) {
3726 bs_entry
->state
.backing_missing
=
3727 !qdict_haskey(options
, "backing") &&
3728 !qdict_haskey(options
, "backing.driver");
3731 QLIST_FOREACH(child
, &bs
->children
, next
) {
3732 QDict
*new_child_options
= NULL
;
3733 bool child_keep_old
= keep_old_opts
;
3735 /* reopen can only change the options of block devices that were
3736 * implicitly created and inherited options. For other (referenced)
3737 * block devices, a syntax like "backing.foo" results in an error. */
3738 if (child
->bs
->inherits_from
!= bs
) {
3742 /* Check if the options contain a child reference */
3743 if (qdict_haskey(options
, child
->name
)) {
3744 const char *childref
= qdict_get_try_str(options
, child
->name
);
3746 * The current child must not be reopened if the child
3747 * reference is null or points to a different node.
3749 if (g_strcmp0(childref
, child
->bs
->node_name
)) {
3753 * If the child reference points to the current child then
3754 * reopen it with its existing set of options (note that
3755 * it can still inherit new options from the parent).
3757 child_keep_old
= true;
3759 /* Extract child options ("child-name.*") */
3760 char *child_key_dot
= g_strdup_printf("%s.", child
->name
);
3761 qdict_extract_subqdict(explicit_options
, NULL
, child_key_dot
);
3762 qdict_extract_subqdict(options
, &new_child_options
, child_key_dot
);
3763 g_free(child_key_dot
);
3766 bdrv_reopen_queue_child(bs_queue
, child
->bs
, new_child_options
,
3767 child
->klass
, child
->role
, bs
->drv
->is_format
,
3768 options
, flags
, child_keep_old
);
3774 BlockReopenQueue
*bdrv_reopen_queue(BlockReopenQueue
*bs_queue
,
3775 BlockDriverState
*bs
,
3776 QDict
*options
, bool keep_old_opts
)
3778 return bdrv_reopen_queue_child(bs_queue
, bs
, options
, NULL
, 0, false,
3779 NULL
, 0, keep_old_opts
);
3783 * Reopen multiple BlockDriverStates atomically & transactionally.
3785 * The queue passed in (bs_queue) must have been built up previous
3786 * via bdrv_reopen_queue().
3788 * Reopens all BDS specified in the queue, with the appropriate
3789 * flags. All devices are prepared for reopen, and failure of any
3790 * device will cause all device changes to be abandoned, and intermediate
3793 * If all devices prepare successfully, then the changes are committed
3796 * All affected nodes must be drained between bdrv_reopen_queue() and
3797 * bdrv_reopen_multiple().
3799 int bdrv_reopen_multiple(BlockReopenQueue
*bs_queue
, Error
**errp
)
3802 BlockReopenQueueEntry
*bs_entry
, *next
;
3804 assert(bs_queue
!= NULL
);
3806 QTAILQ_FOREACH(bs_entry
, bs_queue
, entry
) {
3807 assert(bs_entry
->state
.bs
->quiesce_counter
> 0);
3808 if (bdrv_reopen_prepare(&bs_entry
->state
, bs_queue
, errp
)) {
3811 bs_entry
->prepared
= true;
3814 QTAILQ_FOREACH(bs_entry
, bs_queue
, entry
) {
3815 BDRVReopenState
*state
= &bs_entry
->state
;
3816 ret
= bdrv_check_perm(state
->bs
, bs_queue
, state
->perm
,
3817 state
->shared_perm
, NULL
, NULL
, errp
);
3821 /* Check if new_backing_bs would accept the new permissions */
3822 if (state
->replace_backing_bs
&& state
->new_backing_bs
) {
3823 uint64_t nperm
, nshared
;
3824 bdrv_child_perm(state
->bs
, state
->new_backing_bs
,
3825 NULL
, bdrv_backing_role(state
->bs
),
3826 bs_queue
, state
->perm
, state
->shared_perm
,
3828 ret
= bdrv_check_update_perm(state
->new_backing_bs
, NULL
,
3829 nperm
, nshared
, NULL
, NULL
, errp
);
3834 bs_entry
->perms_checked
= true;
3838 * If we reach this point, we have success and just need to apply the
3841 * Reverse order is used to comfort qcow2 driver: on commit it need to write
3842 * IN_USE flag to the image, to mark bitmaps in the image as invalid. But
3843 * children are usually goes after parents in reopen-queue, so go from last
3846 QTAILQ_FOREACH_REVERSE(bs_entry
, bs_queue
, entry
) {
3847 bdrv_reopen_commit(&bs_entry
->state
);
3852 QTAILQ_FOREACH_SAFE(bs_entry
, bs_queue
, entry
, next
) {
3853 BDRVReopenState
*state
= &bs_entry
->state
;
3855 if (!bs_entry
->perms_checked
) {
3860 bdrv_set_perm(state
->bs
, state
->perm
, state
->shared_perm
);
3862 bdrv_abort_perm_update(state
->bs
);
3863 if (state
->replace_backing_bs
&& state
->new_backing_bs
) {
3864 bdrv_abort_perm_update(state
->new_backing_bs
);
3870 QTAILQ_FOREACH_REVERSE(bs_entry
, bs_queue
, entry
) {
3871 BlockDriverState
*bs
= bs_entry
->state
.bs
;
3873 if (bs
->drv
->bdrv_reopen_commit_post
)
3874 bs
->drv
->bdrv_reopen_commit_post(&bs_entry
->state
);
3878 QTAILQ_FOREACH_SAFE(bs_entry
, bs_queue
, entry
, next
) {
3880 if (bs_entry
->prepared
) {
3881 bdrv_reopen_abort(&bs_entry
->state
);
3883 qobject_unref(bs_entry
->state
.explicit_options
);
3884 qobject_unref(bs_entry
->state
.options
);
3886 if (bs_entry
->state
.new_backing_bs
) {
3887 bdrv_unref(bs_entry
->state
.new_backing_bs
);
3896 int bdrv_reopen_set_read_only(BlockDriverState
*bs
, bool read_only
,
3900 BlockReopenQueue
*queue
;
3901 QDict
*opts
= qdict_new();
3903 qdict_put_bool(opts
, BDRV_OPT_READ_ONLY
, read_only
);
3905 bdrv_subtree_drained_begin(bs
);
3906 queue
= bdrv_reopen_queue(NULL
, bs
, opts
, true);
3907 ret
= bdrv_reopen_multiple(queue
, errp
);
3908 bdrv_subtree_drained_end(bs
);
3913 static BlockReopenQueueEntry
*find_parent_in_reopen_queue(BlockReopenQueue
*q
,
3916 BlockReopenQueueEntry
*entry
;
3918 QTAILQ_FOREACH(entry
, q
, entry
) {
3919 BlockDriverState
*bs
= entry
->state
.bs
;
3922 QLIST_FOREACH(child
, &bs
->children
, next
) {
3932 static void bdrv_reopen_perm(BlockReopenQueue
*q
, BlockDriverState
*bs
,
3933 uint64_t *perm
, uint64_t *shared
)
3936 BlockReopenQueueEntry
*parent
;
3937 uint64_t cumulative_perms
= 0;
3938 uint64_t cumulative_shared_perms
= BLK_PERM_ALL
;
3940 QLIST_FOREACH(c
, &bs
->parents
, next_parent
) {
3941 parent
= find_parent_in_reopen_queue(q
, c
);
3943 cumulative_perms
|= c
->perm
;
3944 cumulative_shared_perms
&= c
->shared_perm
;
3946 uint64_t nperm
, nshared
;
3948 bdrv_child_perm(parent
->state
.bs
, bs
, c
, c
->role
, q
,
3949 parent
->state
.perm
, parent
->state
.shared_perm
,
3952 cumulative_perms
|= nperm
;
3953 cumulative_shared_perms
&= nshared
;
3956 *perm
= cumulative_perms
;
3957 *shared
= cumulative_shared_perms
;
3960 static bool bdrv_reopen_can_attach(BlockDriverState
*parent
,
3962 BlockDriverState
*new_child
,
3965 AioContext
*parent_ctx
= bdrv_get_aio_context(parent
);
3966 AioContext
*child_ctx
= bdrv_get_aio_context(new_child
);
3970 ignore
= g_slist_prepend(NULL
, child
);
3971 ret
= bdrv_can_set_aio_context(new_child
, parent_ctx
, &ignore
, NULL
);
3972 g_slist_free(ignore
);
3977 ignore
= g_slist_prepend(NULL
, child
);
3978 ret
= bdrv_can_set_aio_context(parent
, child_ctx
, &ignore
, errp
);
3979 g_slist_free(ignore
);
3984 * Take a BDRVReopenState and check if the value of 'backing' in the
3985 * reopen_state->options QDict is valid or not.
3987 * If 'backing' is missing from the QDict then return 0.
3989 * If 'backing' contains the node name of the backing file of
3990 * reopen_state->bs then return 0.
3992 * If 'backing' contains a different node name (or is null) then check
3993 * whether the current backing file can be replaced with the new one.
3994 * If that's the case then reopen_state->replace_backing_bs is set to
3995 * true and reopen_state->new_backing_bs contains a pointer to the new
3996 * backing BlockDriverState (or NULL).
3998 * Return 0 on success, otherwise return < 0 and set @errp.
4000 static int bdrv_reopen_parse_backing(BDRVReopenState
*reopen_state
,
4003 BlockDriverState
*bs
= reopen_state
->bs
;
4004 BlockDriverState
*overlay_bs
, *below_bs
, *new_backing_bs
;
4008 value
= qdict_get(reopen_state
->options
, "backing");
4009 if (value
== NULL
) {
4013 switch (qobject_type(value
)) {
4015 new_backing_bs
= NULL
;
4018 str
= qobject_get_try_str(value
);
4019 new_backing_bs
= bdrv_lookup_bs(NULL
, str
, errp
);
4020 if (new_backing_bs
== NULL
) {
4022 } else if (bdrv_recurse_has_child(new_backing_bs
, bs
)) {
4023 error_setg(errp
, "Making '%s' a backing file of '%s' "
4024 "would create a cycle", str
, bs
->node_name
);
4029 /* 'backing' does not allow any other data type */
4030 g_assert_not_reached();
4034 * Check AioContext compatibility so that the bdrv_set_backing_hd() call in
4035 * bdrv_reopen_commit() won't fail.
4037 if (new_backing_bs
) {
4038 if (!bdrv_reopen_can_attach(bs
, bs
->backing
, new_backing_bs
, errp
)) {
4044 * Ensure that @bs can really handle backing files, because we are
4045 * about to give it one (or swap the existing one)
4047 if (bs
->drv
->is_filter
) {
4048 /* Filters always have a file or a backing child */
4050 error_setg(errp
, "'%s' is a %s filter node that does not support a "
4051 "backing child", bs
->node_name
, bs
->drv
->format_name
);
4054 } else if (!bs
->drv
->supports_backing
) {
4055 error_setg(errp
, "Driver '%s' of node '%s' does not support backing "
4056 "files", bs
->drv
->format_name
, bs
->node_name
);
4061 * Find the "actual" backing file by skipping all links that point
4062 * to an implicit node, if any (e.g. a commit filter node).
4063 * We cannot use any of the bdrv_skip_*() functions here because
4064 * those return the first explicit node, while we are looking for
4068 for (below_bs
= bdrv_filter_or_cow_bs(overlay_bs
);
4069 below_bs
&& below_bs
->implicit
;
4070 below_bs
= bdrv_filter_or_cow_bs(overlay_bs
))
4072 overlay_bs
= below_bs
;
4075 /* If we want to replace the backing file we need some extra checks */
4076 if (new_backing_bs
!= bdrv_filter_or_cow_bs(overlay_bs
)) {
4077 /* Check for implicit nodes between bs and its backing file */
4078 if (bs
!= overlay_bs
) {
4079 error_setg(errp
, "Cannot change backing link if '%s' has "
4080 "an implicit backing file", bs
->node_name
);
4084 * Check if the backing link that we want to replace is frozen.
4086 * bdrv_filter_or_cow_child(overlay_bs) == overlay_bs->backing,
4087 * because we know that overlay_bs == bs, and that @bs
4088 * either is a filter that uses ->backing or a COW format BDS
4089 * with bs->drv->supports_backing == true.
4091 if (bdrv_is_backing_chain_frozen(overlay_bs
,
4092 child_bs(overlay_bs
->backing
), errp
))
4096 reopen_state
->replace_backing_bs
= true;
4097 if (new_backing_bs
) {
4098 bdrv_ref(new_backing_bs
);
4099 reopen_state
->new_backing_bs
= new_backing_bs
;
4107 * Prepares a BlockDriverState for reopen. All changes are staged in the
4108 * 'opaque' field of the BDRVReopenState, which is used and allocated by
4109 * the block driver layer .bdrv_reopen_prepare()
4111 * bs is the BlockDriverState to reopen
4112 * flags are the new open flags
4113 * queue is the reopen queue
4115 * Returns 0 on success, non-zero on error. On error errp will be set
4118 * On failure, bdrv_reopen_abort() will be called to clean up any data.
4119 * It is the responsibility of the caller to then call the abort() or
4120 * commit() for any other BDS that have been left in a prepare() state
4123 int bdrv_reopen_prepare(BDRVReopenState
*reopen_state
, BlockReopenQueue
*queue
,
4128 Error
*local_err
= NULL
;
4131 QDict
*orig_reopen_opts
;
4132 char *discard
= NULL
;
4134 bool drv_prepared
= false;
4136 assert(reopen_state
!= NULL
);
4137 assert(reopen_state
->bs
->drv
!= NULL
);
4138 drv
= reopen_state
->bs
->drv
;
4140 /* This function and each driver's bdrv_reopen_prepare() remove
4141 * entries from reopen_state->options as they are processed, so
4142 * we need to make a copy of the original QDict. */
4143 orig_reopen_opts
= qdict_clone_shallow(reopen_state
->options
);
4145 /* Process generic block layer options */
4146 opts
= qemu_opts_create(&bdrv_runtime_opts
, NULL
, 0, &error_abort
);
4147 if (!qemu_opts_absorb_qdict(opts
, reopen_state
->options
, errp
)) {
4152 /* This was already called in bdrv_reopen_queue_child() so the flags
4153 * are up-to-date. This time we simply want to remove the options from
4154 * QemuOpts in order to indicate that they have been processed. */
4155 old_flags
= reopen_state
->flags
;
4156 update_flags_from_options(&reopen_state
->flags
, opts
);
4157 assert(old_flags
== reopen_state
->flags
);
4159 discard
= qemu_opt_get_del(opts
, BDRV_OPT_DISCARD
);
4160 if (discard
!= NULL
) {
4161 if (bdrv_parse_discard_flags(discard
, &reopen_state
->flags
) != 0) {
4162 error_setg(errp
, "Invalid discard option");
4168 reopen_state
->detect_zeroes
=
4169 bdrv_parse_detect_zeroes(opts
, reopen_state
->flags
, &local_err
);
4171 error_propagate(errp
, local_err
);
4176 /* All other options (including node-name and driver) must be unchanged.
4177 * Put them back into the QDict, so that they are checked at the end
4178 * of this function. */
4179 qemu_opts_to_qdict(opts
, reopen_state
->options
);
4181 /* If we are to stay read-only, do not allow permission change
4182 * to r/w. Attempting to set to r/w may fail if either BDRV_O_ALLOW_RDWR is
4183 * not set, or if the BDS still has copy_on_read enabled */
4184 read_only
= !(reopen_state
->flags
& BDRV_O_RDWR
);
4185 ret
= bdrv_can_set_read_only(reopen_state
->bs
, read_only
, true, &local_err
);
4187 error_propagate(errp
, local_err
);
4191 /* Calculate required permissions after reopening */
4192 bdrv_reopen_perm(queue
, reopen_state
->bs
,
4193 &reopen_state
->perm
, &reopen_state
->shared_perm
);
4195 ret
= bdrv_flush(reopen_state
->bs
);
4197 error_setg_errno(errp
, -ret
, "Error flushing drive");
4201 if (drv
->bdrv_reopen_prepare
) {
4203 * If a driver-specific option is missing, it means that we
4204 * should reset it to its default value.
4205 * But not all options allow that, so we need to check it first.
4207 ret
= bdrv_reset_options_allowed(reopen_state
->bs
,
4208 reopen_state
->options
, errp
);
4213 ret
= drv
->bdrv_reopen_prepare(reopen_state
, queue
, &local_err
);
4215 if (local_err
!= NULL
) {
4216 error_propagate(errp
, local_err
);
4218 bdrv_refresh_filename(reopen_state
->bs
);
4219 error_setg(errp
, "failed while preparing to reopen image '%s'",
4220 reopen_state
->bs
->filename
);
4225 /* It is currently mandatory to have a bdrv_reopen_prepare()
4226 * handler for each supported drv. */
4227 error_setg(errp
, "Block format '%s' used by node '%s' "
4228 "does not support reopening files", drv
->format_name
,
4229 bdrv_get_device_or_node_name(reopen_state
->bs
));
4234 drv_prepared
= true;
4237 * We must provide the 'backing' option if the BDS has a backing
4238 * file or if the image file has a backing file name as part of
4239 * its metadata. Otherwise the 'backing' option can be omitted.
4241 if (drv
->supports_backing
&& reopen_state
->backing_missing
&&
4242 (reopen_state
->bs
->backing
|| reopen_state
->bs
->backing_file
[0])) {
4243 error_setg(errp
, "backing is missing for '%s'",
4244 reopen_state
->bs
->node_name
);
4250 * Allow changing the 'backing' option. The new value can be
4251 * either a reference to an existing node (using its node name)
4252 * or NULL to simply detach the current backing file.
4254 ret
= bdrv_reopen_parse_backing(reopen_state
, errp
);
4258 qdict_del(reopen_state
->options
, "backing");
4260 /* Options that are not handled are only okay if they are unchanged
4261 * compared to the old state. It is expected that some options are only
4262 * used for the initial open, but not reopen (e.g. filename) */
4263 if (qdict_size(reopen_state
->options
)) {
4264 const QDictEntry
*entry
= qdict_first(reopen_state
->options
);
4267 QObject
*new = entry
->value
;
4268 QObject
*old
= qdict_get(reopen_state
->bs
->options
, entry
->key
);
4270 /* Allow child references (child_name=node_name) as long as they
4271 * point to the current child (i.e. everything stays the same). */
4272 if (qobject_type(new) == QTYPE_QSTRING
) {
4274 QLIST_FOREACH(child
, &reopen_state
->bs
->children
, next
) {
4275 if (!strcmp(child
->name
, entry
->key
)) {
4281 const char *str
= qobject_get_try_str(new);
4282 if (!strcmp(child
->bs
->node_name
, str
)) {
4283 continue; /* Found child with this name, skip option */
4289 * TODO: When using -drive to specify blockdev options, all values
4290 * will be strings; however, when using -blockdev, blockdev-add or
4291 * filenames using the json:{} pseudo-protocol, they will be
4293 * In contrast, reopening options are (currently) always strings
4294 * (because you can only specify them through qemu-io; all other
4295 * callers do not specify any options).
4296 * Therefore, when using anything other than -drive to create a BDS,
4297 * this cannot detect non-string options as unchanged, because
4298 * qobject_is_equal() always returns false for objects of different
4299 * type. In the future, this should be remedied by correctly typing
4300 * all options. For now, this is not too big of an issue because
4301 * the user can simply omit options which cannot be changed anyway,
4302 * so they will stay unchanged.
4304 if (!qobject_is_equal(new, old
)) {
4305 error_setg(errp
, "Cannot change the option '%s'", entry
->key
);
4309 } while ((entry
= qdict_next(reopen_state
->options
, entry
)));
4314 /* Restore the original reopen_state->options QDict */
4315 qobject_unref(reopen_state
->options
);
4316 reopen_state
->options
= qobject_ref(orig_reopen_opts
);
4319 if (ret
< 0 && drv_prepared
) {
4320 /* drv->bdrv_reopen_prepare() has succeeded, so we need to
4321 * call drv->bdrv_reopen_abort() before signaling an error
4322 * (bdrv_reopen_multiple() will not call bdrv_reopen_abort()
4323 * when the respective bdrv_reopen_prepare() has failed) */
4324 if (drv
->bdrv_reopen_abort
) {
4325 drv
->bdrv_reopen_abort(reopen_state
);
4328 qemu_opts_del(opts
);
4329 qobject_unref(orig_reopen_opts
);
4335 * Takes the staged changes for the reopen from bdrv_reopen_prepare(), and
4336 * makes them final by swapping the staging BlockDriverState contents into
4337 * the active BlockDriverState contents.
4339 void bdrv_reopen_commit(BDRVReopenState
*reopen_state
)
4342 BlockDriverState
*bs
;
4345 assert(reopen_state
!= NULL
);
4346 bs
= reopen_state
->bs
;
4348 assert(drv
!= NULL
);
4350 /* If there are any driver level actions to take */
4351 if (drv
->bdrv_reopen_commit
) {
4352 drv
->bdrv_reopen_commit(reopen_state
);
4355 /* set BDS specific flags now */
4356 qobject_unref(bs
->explicit_options
);
4357 qobject_unref(bs
->options
);
4359 bs
->explicit_options
= reopen_state
->explicit_options
;
4360 bs
->options
= reopen_state
->options
;
4361 bs
->open_flags
= reopen_state
->flags
;
4362 bs
->read_only
= !(reopen_state
->flags
& BDRV_O_RDWR
);
4363 bs
->detect_zeroes
= reopen_state
->detect_zeroes
;
4365 if (reopen_state
->replace_backing_bs
) {
4366 qdict_del(bs
->explicit_options
, "backing");
4367 qdict_del(bs
->options
, "backing");
4370 /* Remove child references from bs->options and bs->explicit_options.
4371 * Child options were already removed in bdrv_reopen_queue_child() */
4372 QLIST_FOREACH(child
, &bs
->children
, next
) {
4373 qdict_del(bs
->explicit_options
, child
->name
);
4374 qdict_del(bs
->options
, child
->name
);
4378 * Change the backing file if a new one was specified. We do this
4379 * after updating bs->options, so bdrv_refresh_filename() (called
4380 * from bdrv_set_backing_hd()) has the new values.
4382 if (reopen_state
->replace_backing_bs
) {
4383 BlockDriverState
*old_backing_bs
= child_bs(bs
->backing
);
4384 assert(!old_backing_bs
|| !old_backing_bs
->implicit
);
4385 /* Abort the permission update on the backing bs we're detaching */
4386 if (old_backing_bs
) {
4387 bdrv_abort_perm_update(old_backing_bs
);
4389 bdrv_set_backing_hd(bs
, reopen_state
->new_backing_bs
, &error_abort
);
4392 bdrv_refresh_limits(bs
, NULL
);
4396 * Abort the reopen, and delete and free the staged changes in
4399 void bdrv_reopen_abort(BDRVReopenState
*reopen_state
)
4403 assert(reopen_state
!= NULL
);
4404 drv
= reopen_state
->bs
->drv
;
4405 assert(drv
!= NULL
);
4407 if (drv
->bdrv_reopen_abort
) {
4408 drv
->bdrv_reopen_abort(reopen_state
);
4413 static void bdrv_close(BlockDriverState
*bs
)
4415 BdrvAioNotifier
*ban
, *ban_next
;
4416 BdrvChild
*child
, *next
;
4418 assert(!bs
->refcnt
);
4420 bdrv_drained_begin(bs
); /* complete I/O */
4422 bdrv_drain(bs
); /* in case flush left pending I/O */
4425 if (bs
->drv
->bdrv_close
) {
4426 /* Must unfreeze all children, so bdrv_unref_child() works */
4427 bs
->drv
->bdrv_close(bs
);
4432 QLIST_FOREACH_SAFE(child
, &bs
->children
, next
, next
) {
4433 bdrv_unref_child(bs
, child
);
4440 qatomic_set(&bs
->copy_on_read
, 0);
4441 bs
->backing_file
[0] = '\0';
4442 bs
->backing_format
[0] = '\0';
4443 bs
->total_sectors
= 0;
4444 bs
->encrypted
= false;
4446 qobject_unref(bs
->options
);
4447 qobject_unref(bs
->explicit_options
);
4449 bs
->explicit_options
= NULL
;
4450 qobject_unref(bs
->full_open_options
);
4451 bs
->full_open_options
= NULL
;
4453 bdrv_release_named_dirty_bitmaps(bs
);
4454 assert(QLIST_EMPTY(&bs
->dirty_bitmaps
));
4456 QLIST_FOREACH_SAFE(ban
, &bs
->aio_notifiers
, list
, ban_next
) {
4459 QLIST_INIT(&bs
->aio_notifiers
);
4460 bdrv_drained_end(bs
);
4463 * If we're still inside some bdrv_drain_all_begin()/end() sections, end
4464 * them now since this BDS won't exist anymore when bdrv_drain_all_end()
4467 if (bs
->quiesce_counter
) {
4468 bdrv_drain_all_end_quiesce(bs
);
4472 void bdrv_close_all(void)
4474 assert(job_next(NULL
) == NULL
);
4475 blk_exp_close_all();
4477 /* Drop references from requests still in flight, such as canceled block
4478 * jobs whose AIO context has not been polled yet */
4481 blk_remove_all_bs();
4482 blockdev_close_all_bdrv_states();
4484 assert(QTAILQ_EMPTY(&all_bdrv_states
));
4487 static bool should_update_child(BdrvChild
*c
, BlockDriverState
*to
)
4493 if (c
->klass
->stay_at_node
) {
4497 /* If the child @c belongs to the BDS @to, replacing the current
4498 * c->bs by @to would mean to create a loop.
4500 * Such a case occurs when appending a BDS to a backing chain.
4501 * For instance, imagine the following chain:
4503 * guest device -> node A -> further backing chain...
4505 * Now we create a new BDS B which we want to put on top of this
4506 * chain, so we first attach A as its backing node:
4511 * guest device -> node A -> further backing chain...
4513 * Finally we want to replace A by B. When doing that, we want to
4514 * replace all pointers to A by pointers to B -- except for the
4515 * pointer from B because (1) that would create a loop, and (2)
4516 * that pointer should simply stay intact:
4518 * guest device -> node B
4521 * node A -> further backing chain...
4523 * In general, when replacing a node A (c->bs) by a node B (@to),
4524 * if A is a child of B, that means we cannot replace A by B there
4525 * because that would create a loop. Silently detaching A from B
4526 * is also not really an option. So overall just leaving A in
4527 * place there is the most sensible choice.
4529 * We would also create a loop in any cases where @c is only
4530 * indirectly referenced by @to. Prevent this by returning false
4531 * if @c is found (by breadth-first search) anywhere in the whole
4536 found
= g_hash_table_new(NULL
, NULL
);
4537 g_hash_table_add(found
, to
);
4538 queue
= g_queue_new();
4539 g_queue_push_tail(queue
, to
);
4541 while (!g_queue_is_empty(queue
)) {
4542 BlockDriverState
*v
= g_queue_pop_head(queue
);
4545 QLIST_FOREACH(c2
, &v
->children
, next
) {
4551 if (g_hash_table_contains(found
, c2
->bs
)) {
4555 g_queue_push_tail(queue
, c2
->bs
);
4556 g_hash_table_add(found
, c2
->bs
);
4560 g_queue_free(queue
);
4561 g_hash_table_destroy(found
);
4566 void bdrv_replace_node(BlockDriverState
*from
, BlockDriverState
*to
,
4569 BdrvChild
*c
, *next
;
4570 GSList
*list
= NULL
, *p
;
4571 uint64_t perm
= 0, shared
= BLK_PERM_ALL
;
4574 /* Make sure that @from doesn't go away until we have successfully attached
4575 * all of its parents to @to. */
4578 assert(qemu_get_current_aio_context() == qemu_get_aio_context());
4579 assert(bdrv_get_aio_context(from
) == bdrv_get_aio_context(to
));
4580 bdrv_drained_begin(from
);
4582 /* Put all parents into @list and calculate their cumulative permissions */
4583 QLIST_FOREACH_SAFE(c
, &from
->parents
, next_parent
, next
) {
4584 assert(c
->bs
== from
);
4585 if (!should_update_child(c
, to
)) {
4589 error_setg(errp
, "Cannot change '%s' link to '%s'",
4590 c
->name
, from
->node_name
);
4593 list
= g_slist_prepend(list
, c
);
4595 shared
&= c
->shared_perm
;
4598 /* Check whether the required permissions can be granted on @to, ignoring
4599 * all BdrvChild in @list so that they can't block themselves. */
4600 ret
= bdrv_check_update_perm(to
, NULL
, perm
, shared
, list
, NULL
, errp
);
4602 bdrv_abort_perm_update(to
);
4606 /* Now actually perform the change. We performed the permission check for
4607 * all elements of @list at once, so set the permissions all at once at the
4609 for (p
= list
; p
!= NULL
; p
= p
->next
) {
4613 bdrv_replace_child_noperm(c
, to
);
4617 bdrv_get_cumulative_perm(to
, &perm
, &shared
);
4618 bdrv_set_perm(to
, perm
, shared
);
4622 bdrv_drained_end(from
);
4627 * Add new bs contents at the top of an image chain while the chain is
4628 * live, while keeping required fields on the top layer.
4630 * This will modify the BlockDriverState fields, and swap contents
4631 * between bs_new and bs_top. Both bs_new and bs_top are modified.
4633 * bs_new must not be attached to a BlockBackend.
4635 * This function does not create any image files.
4637 * bdrv_append() takes ownership of a bs_new reference and unrefs it because
4638 * that's what the callers commonly need. bs_new will be referenced by the old
4639 * parents of bs_top after bdrv_append() returns. If the caller needs to keep a
4640 * reference of its own, it must call bdrv_ref().
4642 void bdrv_append(BlockDriverState
*bs_new
, BlockDriverState
*bs_top
,
4645 Error
*local_err
= NULL
;
4647 bdrv_set_backing_hd(bs_new
, bs_top
, &local_err
);
4649 error_propagate(errp
, local_err
);
4653 bdrv_replace_node(bs_top
, bs_new
, &local_err
);
4655 error_propagate(errp
, local_err
);
4656 bdrv_set_backing_hd(bs_new
, NULL
, &error_abort
);
4660 /* bs_new is now referenced by its new parents, we don't need the
4661 * additional reference any more. */
4666 static void bdrv_delete(BlockDriverState
*bs
)
4668 assert(bdrv_op_blocker_is_empty(bs
));
4669 assert(!bs
->refcnt
);
4671 /* remove from list, if necessary */
4672 if (bs
->node_name
[0] != '\0') {
4673 QTAILQ_REMOVE(&graph_bdrv_states
, bs
, node_list
);
4675 QTAILQ_REMOVE(&all_bdrv_states
, bs
, bs_list
);
4683 * Run consistency checks on an image
4685 * Returns 0 if the check could be completed (it doesn't mean that the image is
4686 * free of errors) or -errno when an internal error occurred. The results of the
4687 * check are stored in res.
4689 int coroutine_fn
bdrv_co_check(BlockDriverState
*bs
,
4690 BdrvCheckResult
*res
, BdrvCheckMode fix
)
4692 if (bs
->drv
== NULL
) {
4695 if (bs
->drv
->bdrv_co_check
== NULL
) {
4699 memset(res
, 0, sizeof(*res
));
4700 return bs
->drv
->bdrv_co_check(bs
, res
, fix
);
4706 * -EINVAL - backing format specified, but no file
4707 * -ENOSPC - can't update the backing file because no space is left in the
4709 * -ENOTSUP - format driver doesn't support changing the backing file
4711 int bdrv_change_backing_file(BlockDriverState
*bs
, const char *backing_file
,
4712 const char *backing_fmt
, bool warn
)
4714 BlockDriver
*drv
= bs
->drv
;
4721 /* Backing file format doesn't make sense without a backing file */
4722 if (backing_fmt
&& !backing_file
) {
4726 if (warn
&& backing_file
&& !backing_fmt
) {
4727 warn_report("Deprecated use of backing file without explicit "
4728 "backing format, use of this image requires "
4729 "potentially unsafe format probing");
4732 if (drv
->bdrv_change_backing_file
!= NULL
) {
4733 ret
= drv
->bdrv_change_backing_file(bs
, backing_file
, backing_fmt
);
4739 pstrcpy(bs
->backing_file
, sizeof(bs
->backing_file
), backing_file
?: "");
4740 pstrcpy(bs
->backing_format
, sizeof(bs
->backing_format
), backing_fmt
?: "");
4741 pstrcpy(bs
->auto_backing_file
, sizeof(bs
->auto_backing_file
),
4742 backing_file
?: "");
4748 * Finds the first non-filter node above bs in the chain between
4749 * active and bs. The returned node is either an immediate parent of
4750 * bs, or there are only filter nodes between the two.
4752 * Returns NULL if bs is not found in active's image chain,
4753 * or if active == bs.
4755 * Returns the bottommost base image if bs == NULL.
4757 BlockDriverState
*bdrv_find_overlay(BlockDriverState
*active
,
4758 BlockDriverState
*bs
)
4760 bs
= bdrv_skip_filters(bs
);
4761 active
= bdrv_skip_filters(active
);
4764 BlockDriverState
*next
= bdrv_backing_chain_next(active
);
4774 /* Given a BDS, searches for the base layer. */
4775 BlockDriverState
*bdrv_find_base(BlockDriverState
*bs
)
4777 return bdrv_find_overlay(bs
, NULL
);
4781 * Return true if at least one of the COW (backing) and filter links
4782 * between @bs and @base is frozen. @errp is set if that's the case.
4783 * @base must be reachable from @bs, or NULL.
4785 bool bdrv_is_backing_chain_frozen(BlockDriverState
*bs
, BlockDriverState
*base
,
4788 BlockDriverState
*i
;
4791 for (i
= bs
; i
!= base
; i
= child_bs(child
)) {
4792 child
= bdrv_filter_or_cow_child(i
);
4794 if (child
&& child
->frozen
) {
4795 error_setg(errp
, "Cannot change '%s' link from '%s' to '%s'",
4796 child
->name
, i
->node_name
, child
->bs
->node_name
);
4805 * Freeze all COW (backing) and filter links between @bs and @base.
4806 * If any of the links is already frozen the operation is aborted and
4807 * none of the links are modified.
4808 * @base must be reachable from @bs, or NULL.
4809 * Returns 0 on success. On failure returns < 0 and sets @errp.
4811 int bdrv_freeze_backing_chain(BlockDriverState
*bs
, BlockDriverState
*base
,
4814 BlockDriverState
*i
;
4817 if (bdrv_is_backing_chain_frozen(bs
, base
, errp
)) {
4821 for (i
= bs
; i
!= base
; i
= child_bs(child
)) {
4822 child
= bdrv_filter_or_cow_child(i
);
4823 if (child
&& child
->bs
->never_freeze
) {
4824 error_setg(errp
, "Cannot freeze '%s' link to '%s'",
4825 child
->name
, child
->bs
->node_name
);
4830 for (i
= bs
; i
!= base
; i
= child_bs(child
)) {
4831 child
= bdrv_filter_or_cow_child(i
);
4833 child
->frozen
= true;
4841 * Unfreeze all COW (backing) and filter links between @bs and @base.
4842 * The caller must ensure that all links are frozen before using this
4844 * @base must be reachable from @bs, or NULL.
4846 void bdrv_unfreeze_backing_chain(BlockDriverState
*bs
, BlockDriverState
*base
)
4848 BlockDriverState
*i
;
4851 for (i
= bs
; i
!= base
; i
= child_bs(child
)) {
4852 child
= bdrv_filter_or_cow_child(i
);
4854 assert(child
->frozen
);
4855 child
->frozen
= false;
4861 * Drops images above 'base' up to and including 'top', and sets the image
4862 * above 'top' to have base as its backing file.
4864 * Requires that the overlay to 'top' is opened r/w, so that the backing file
4865 * information in 'bs' can be properly updated.
4867 * E.g., this will convert the following chain:
4868 * bottom <- base <- intermediate <- top <- active
4872 * bottom <- base <- active
4874 * It is allowed for bottom==base, in which case it converts:
4876 * base <- intermediate <- top <- active
4882 * If backing_file_str is non-NULL, it will be used when modifying top's
4883 * overlay image metadata.
4886 * if active == top, that is considered an error
4889 int bdrv_drop_intermediate(BlockDriverState
*top
, BlockDriverState
*base
,
4890 const char *backing_file_str
)
4892 BlockDriverState
*explicit_top
= top
;
4893 bool update_inherits_from
;
4894 BdrvChild
*c
, *next
;
4895 Error
*local_err
= NULL
;
4899 bdrv_subtree_drained_begin(top
);
4901 if (!top
->drv
|| !base
->drv
) {
4905 /* Make sure that base is in the backing chain of top */
4906 if (!bdrv_chain_contains(top
, base
)) {
4910 /* This function changes all links that point to top and makes
4911 * them point to base. Check that none of them is frozen. */
4912 QLIST_FOREACH(c
, &top
->parents
, next_parent
) {
4918 /* If 'base' recursively inherits from 'top' then we should set
4919 * base->inherits_from to top->inherits_from after 'top' and all
4920 * other intermediate nodes have been dropped.
4921 * If 'top' is an implicit node (e.g. "commit_top") we should skip
4922 * it because no one inherits from it. We use explicit_top for that. */
4923 explicit_top
= bdrv_skip_implicit_filters(explicit_top
);
4924 update_inherits_from
= bdrv_inherits_from_recursive(base
, explicit_top
);
4926 /* success - we can delete the intermediate states, and link top->base */
4927 /* TODO Check graph modification op blockers (BLK_PERM_GRAPH_MOD) once
4928 * we've figured out how they should work. */
4929 if (!backing_file_str
) {
4930 bdrv_refresh_filename(base
);
4931 backing_file_str
= base
->filename
;
4934 QLIST_FOREACH_SAFE(c
, &top
->parents
, next_parent
, next
) {
4935 /* Check whether we are allowed to switch c from top to base */
4936 GSList
*ignore_children
= g_slist_prepend(NULL
, c
);
4937 ret
= bdrv_check_update_perm(base
, NULL
, c
->perm
, c
->shared_perm
,
4938 ignore_children
, NULL
, &local_err
);
4939 g_slist_free(ignore_children
);
4941 error_report_err(local_err
);
4945 /* If so, update the backing file path in the image file */
4946 if (c
->klass
->update_filename
) {
4947 ret
= c
->klass
->update_filename(c
, base
, backing_file_str
,
4950 bdrv_abort_perm_update(base
);
4951 error_report_err(local_err
);
4957 * Do the actual switch in the in-memory graph.
4958 * Completes bdrv_check_update_perm() transaction internally.
4959 * c->frozen is false, we have checked that above.
4962 bdrv_replace_child(c
, base
);
4966 if (update_inherits_from
) {
4967 base
->inherits_from
= explicit_top
->inherits_from
;
4972 bdrv_subtree_drained_end(top
);
4978 * Implementation of BlockDriver.bdrv_get_allocated_file_size() that
4979 * sums the size of all data-bearing children. (This excludes backing
4982 static int64_t bdrv_sum_allocated_file_size(BlockDriverState
*bs
)
4985 int64_t child_size
, sum
= 0;
4987 QLIST_FOREACH(child
, &bs
->children
, next
) {
4988 if (child
->role
& (BDRV_CHILD_DATA
| BDRV_CHILD_METADATA
|
4989 BDRV_CHILD_FILTERED
))
4991 child_size
= bdrv_get_allocated_file_size(child
->bs
);
4992 if (child_size
< 0) {
5003 * Length of a allocated file in bytes. Sparse files are counted by actual
5004 * allocated space. Return < 0 if error or unknown.
5006 int64_t bdrv_get_allocated_file_size(BlockDriverState
*bs
)
5008 BlockDriver
*drv
= bs
->drv
;
5012 if (drv
->bdrv_get_allocated_file_size
) {
5013 return drv
->bdrv_get_allocated_file_size(bs
);
5016 if (drv
->bdrv_file_open
) {
5018 * Protocol drivers default to -ENOTSUP (most of their data is
5019 * not stored in any of their children (if they even have any),
5020 * so there is no generic way to figure it out).
5023 } else if (drv
->is_filter
) {
5024 /* Filter drivers default to the size of their filtered child */
5025 return bdrv_get_allocated_file_size(bdrv_filter_bs(bs
));
5027 /* Other drivers default to summing their children's sizes */
5028 return bdrv_sum_allocated_file_size(bs
);
5034 * @drv: Format driver
5035 * @opts: Creation options for new image
5036 * @in_bs: Existing image containing data for new image (may be NULL)
5037 * @errp: Error object
5038 * Returns: A #BlockMeasureInfo (free using qapi_free_BlockMeasureInfo())
5041 * Calculate file size required to create a new image.
5043 * If @in_bs is given then space for allocated clusters and zero clusters
5044 * from that image are included in the calculation. If @opts contains a
5045 * backing file that is shared by @in_bs then backing clusters may be omitted
5046 * from the calculation.
5048 * If @in_bs is NULL then the calculation includes no allocated clusters
5049 * unless a preallocation option is given in @opts.
5051 * Note that @in_bs may use a different BlockDriver from @drv.
5053 * If an error occurs the @errp pointer is set.
5055 BlockMeasureInfo
*bdrv_measure(BlockDriver
*drv
, QemuOpts
*opts
,
5056 BlockDriverState
*in_bs
, Error
**errp
)
5058 if (!drv
->bdrv_measure
) {
5059 error_setg(errp
, "Block driver '%s' does not support size measurement",
5064 return drv
->bdrv_measure(opts
, in_bs
, errp
);
5068 * Return number of sectors on success, -errno on error.
5070 int64_t bdrv_nb_sectors(BlockDriverState
*bs
)
5072 BlockDriver
*drv
= bs
->drv
;
5077 if (drv
->has_variable_length
) {
5078 int ret
= refresh_total_sectors(bs
, bs
->total_sectors
);
5083 return bs
->total_sectors
;
5087 * Return length in bytes on success, -errno on error.
5088 * The length is always a multiple of BDRV_SECTOR_SIZE.
5090 int64_t bdrv_getlength(BlockDriverState
*bs
)
5092 int64_t ret
= bdrv_nb_sectors(bs
);
5097 if (ret
> INT64_MAX
/ BDRV_SECTOR_SIZE
) {
5100 return ret
* BDRV_SECTOR_SIZE
;
5103 /* return 0 as number of sectors if no device present or error */
5104 void bdrv_get_geometry(BlockDriverState
*bs
, uint64_t *nb_sectors_ptr
)
5106 int64_t nb_sectors
= bdrv_nb_sectors(bs
);
5108 *nb_sectors_ptr
= nb_sectors
< 0 ? 0 : nb_sectors
;
5111 bool bdrv_is_sg(BlockDriverState
*bs
)
5117 * Return whether the given node supports compressed writes.
5119 bool bdrv_supports_compressed_writes(BlockDriverState
*bs
)
5121 BlockDriverState
*filtered
;
5123 if (!bs
->drv
|| !block_driver_can_compress(bs
->drv
)) {
5127 filtered
= bdrv_filter_bs(bs
);
5130 * Filters can only forward compressed writes, so we have to
5133 return bdrv_supports_compressed_writes(filtered
);
5139 const char *bdrv_get_format_name(BlockDriverState
*bs
)
5141 return bs
->drv
? bs
->drv
->format_name
: NULL
;
5144 static int qsort_strcmp(const void *a
, const void *b
)
5146 return strcmp(*(char *const *)a
, *(char *const *)b
);
5149 void bdrv_iterate_format(void (*it
)(void *opaque
, const char *name
),
5150 void *opaque
, bool read_only
)
5155 const char **formats
= NULL
;
5157 QLIST_FOREACH(drv
, &bdrv_drivers
, list
) {
5158 if (drv
->format_name
) {
5162 if (use_bdrv_whitelist
&& !bdrv_is_whitelisted(drv
, read_only
)) {
5166 while (formats
&& i
&& !found
) {
5167 found
= !strcmp(formats
[--i
], drv
->format_name
);
5171 formats
= g_renew(const char *, formats
, count
+ 1);
5172 formats
[count
++] = drv
->format_name
;
5177 for (i
= 0; i
< (int)ARRAY_SIZE(block_driver_modules
); i
++) {
5178 const char *format_name
= block_driver_modules
[i
].format_name
;
5184 if (use_bdrv_whitelist
&&
5185 !bdrv_format_is_whitelisted(format_name
, read_only
)) {
5189 while (formats
&& j
&& !found
) {
5190 found
= !strcmp(formats
[--j
], format_name
);
5194 formats
= g_renew(const char *, formats
, count
+ 1);
5195 formats
[count
++] = format_name
;
5200 qsort(formats
, count
, sizeof(formats
[0]), qsort_strcmp
);
5202 for (i
= 0; i
< count
; i
++) {
5203 it(opaque
, formats
[i
]);
5209 /* This function is to find a node in the bs graph */
5210 BlockDriverState
*bdrv_find_node(const char *node_name
)
5212 BlockDriverState
*bs
;
5216 QTAILQ_FOREACH(bs
, &graph_bdrv_states
, node_list
) {
5217 if (!strcmp(node_name
, bs
->node_name
)) {
5224 /* Put this QMP function here so it can access the static graph_bdrv_states. */
5225 BlockDeviceInfoList
*bdrv_named_nodes_list(bool flat
,
5228 BlockDeviceInfoList
*list
;
5229 BlockDriverState
*bs
;
5232 QTAILQ_FOREACH(bs
, &graph_bdrv_states
, node_list
) {
5233 BlockDeviceInfo
*info
= bdrv_block_device_info(NULL
, bs
, flat
, errp
);
5235 qapi_free_BlockDeviceInfoList(list
);
5238 QAPI_LIST_PREPEND(list
, info
);
5244 typedef struct XDbgBlockGraphConstructor
{
5245 XDbgBlockGraph
*graph
;
5246 GHashTable
*graph_nodes
;
5247 } XDbgBlockGraphConstructor
;
5249 static XDbgBlockGraphConstructor
*xdbg_graph_new(void)
5251 XDbgBlockGraphConstructor
*gr
= g_new(XDbgBlockGraphConstructor
, 1);
5253 gr
->graph
= g_new0(XDbgBlockGraph
, 1);
5254 gr
->graph_nodes
= g_hash_table_new(NULL
, NULL
);
5259 static XDbgBlockGraph
*xdbg_graph_finalize(XDbgBlockGraphConstructor
*gr
)
5261 XDbgBlockGraph
*graph
= gr
->graph
;
5263 g_hash_table_destroy(gr
->graph_nodes
);
5269 static uintptr_t xdbg_graph_node_num(XDbgBlockGraphConstructor
*gr
, void *node
)
5271 uintptr_t ret
= (uintptr_t)g_hash_table_lookup(gr
->graph_nodes
, node
);
5278 * Start counting from 1, not 0, because 0 interferes with not-found (NULL)
5279 * answer of g_hash_table_lookup.
5281 ret
= g_hash_table_size(gr
->graph_nodes
) + 1;
5282 g_hash_table_insert(gr
->graph_nodes
, node
, (void *)ret
);
5287 static void xdbg_graph_add_node(XDbgBlockGraphConstructor
*gr
, void *node
,
5288 XDbgBlockGraphNodeType type
, const char *name
)
5290 XDbgBlockGraphNode
*n
;
5292 n
= g_new0(XDbgBlockGraphNode
, 1);
5294 n
->id
= xdbg_graph_node_num(gr
, node
);
5296 n
->name
= g_strdup(name
);
5298 QAPI_LIST_PREPEND(gr
->graph
->nodes
, n
);
5301 static void xdbg_graph_add_edge(XDbgBlockGraphConstructor
*gr
, void *parent
,
5302 const BdrvChild
*child
)
5304 BlockPermission qapi_perm
;
5305 XDbgBlockGraphEdge
*edge
;
5307 edge
= g_new0(XDbgBlockGraphEdge
, 1);
5309 edge
->parent
= xdbg_graph_node_num(gr
, parent
);
5310 edge
->child
= xdbg_graph_node_num(gr
, child
->bs
);
5311 edge
->name
= g_strdup(child
->name
);
5313 for (qapi_perm
= 0; qapi_perm
< BLOCK_PERMISSION__MAX
; qapi_perm
++) {
5314 uint64_t flag
= bdrv_qapi_perm_to_blk_perm(qapi_perm
);
5316 if (flag
& child
->perm
) {
5317 QAPI_LIST_PREPEND(edge
->perm
, qapi_perm
);
5319 if (flag
& child
->shared_perm
) {
5320 QAPI_LIST_PREPEND(edge
->shared_perm
, qapi_perm
);
5324 QAPI_LIST_PREPEND(gr
->graph
->edges
, edge
);
5328 XDbgBlockGraph
*bdrv_get_xdbg_block_graph(Error
**errp
)
5332 BlockDriverState
*bs
;
5334 XDbgBlockGraphConstructor
*gr
= xdbg_graph_new();
5336 for (blk
= blk_all_next(NULL
); blk
; blk
= blk_all_next(blk
)) {
5337 char *allocated_name
= NULL
;
5338 const char *name
= blk_name(blk
);
5341 name
= allocated_name
= blk_get_attached_dev_id(blk
);
5343 xdbg_graph_add_node(gr
, blk
, X_DBG_BLOCK_GRAPH_NODE_TYPE_BLOCK_BACKEND
,
5345 g_free(allocated_name
);
5346 if (blk_root(blk
)) {
5347 xdbg_graph_add_edge(gr
, blk
, blk_root(blk
));
5351 for (job
= block_job_next(NULL
); job
; job
= block_job_next(job
)) {
5354 xdbg_graph_add_node(gr
, job
, X_DBG_BLOCK_GRAPH_NODE_TYPE_BLOCK_JOB
,
5356 for (el
= job
->nodes
; el
; el
= el
->next
) {
5357 xdbg_graph_add_edge(gr
, job
, (BdrvChild
*)el
->data
);
5361 QTAILQ_FOREACH(bs
, &graph_bdrv_states
, node_list
) {
5362 xdbg_graph_add_node(gr
, bs
, X_DBG_BLOCK_GRAPH_NODE_TYPE_BLOCK_DRIVER
,
5364 QLIST_FOREACH(child
, &bs
->children
, next
) {
5365 xdbg_graph_add_edge(gr
, bs
, child
);
5369 return xdbg_graph_finalize(gr
);
5372 BlockDriverState
*bdrv_lookup_bs(const char *device
,
5373 const char *node_name
,
5377 BlockDriverState
*bs
;
5380 blk
= blk_by_name(device
);
5385 error_setg(errp
, "Device '%s' has no medium", device
);
5393 bs
= bdrv_find_node(node_name
);
5400 error_setg(errp
, "Cannot find device=%s nor node_name=%s",
5401 device
? device
: "",
5402 node_name
? node_name
: "");
5406 /* If 'base' is in the same chain as 'top', return true. Otherwise,
5407 * return false. If either argument is NULL, return false. */
5408 bool bdrv_chain_contains(BlockDriverState
*top
, BlockDriverState
*base
)
5410 while (top
&& top
!= base
) {
5411 top
= bdrv_filter_or_cow_bs(top
);
5417 BlockDriverState
*bdrv_next_node(BlockDriverState
*bs
)
5420 return QTAILQ_FIRST(&graph_bdrv_states
);
5422 return QTAILQ_NEXT(bs
, node_list
);
5425 BlockDriverState
*bdrv_next_all_states(BlockDriverState
*bs
)
5428 return QTAILQ_FIRST(&all_bdrv_states
);
5430 return QTAILQ_NEXT(bs
, bs_list
);
5433 const char *bdrv_get_node_name(const BlockDriverState
*bs
)
5435 return bs
->node_name
;
5438 const char *bdrv_get_parent_name(const BlockDriverState
*bs
)
5443 /* If multiple parents have a name, just pick the first one. */
5444 QLIST_FOREACH(c
, &bs
->parents
, next_parent
) {
5445 if (c
->klass
->get_name
) {
5446 name
= c
->klass
->get_name(c
);
5447 if (name
&& *name
) {
5456 /* TODO check what callers really want: bs->node_name or blk_name() */
5457 const char *bdrv_get_device_name(const BlockDriverState
*bs
)
5459 return bdrv_get_parent_name(bs
) ?: "";
5462 /* This can be used to identify nodes that might not have a device
5463 * name associated. Since node and device names live in the same
5464 * namespace, the result is unambiguous. The exception is if both are
5465 * absent, then this returns an empty (non-null) string. */
5466 const char *bdrv_get_device_or_node_name(const BlockDriverState
*bs
)
5468 return bdrv_get_parent_name(bs
) ?: bs
->node_name
;
5471 int bdrv_get_flags(BlockDriverState
*bs
)
5473 return bs
->open_flags
;
5476 int bdrv_has_zero_init_1(BlockDriverState
*bs
)
5481 int bdrv_has_zero_init(BlockDriverState
*bs
)
5483 BlockDriverState
*filtered
;
5489 /* If BS is a copy on write image, it is initialized to
5490 the contents of the base image, which may not be zeroes. */
5491 if (bdrv_cow_child(bs
)) {
5494 if (bs
->drv
->bdrv_has_zero_init
) {
5495 return bs
->drv
->bdrv_has_zero_init(bs
);
5498 filtered
= bdrv_filter_bs(bs
);
5500 return bdrv_has_zero_init(filtered
);
5507 bool bdrv_can_write_zeroes_with_unmap(BlockDriverState
*bs
)
5509 if (!(bs
->open_flags
& BDRV_O_UNMAP
)) {
5513 return bs
->supported_zero_flags
& BDRV_REQ_MAY_UNMAP
;
5516 void bdrv_get_backing_filename(BlockDriverState
*bs
,
5517 char *filename
, int filename_size
)
5519 pstrcpy(filename
, filename_size
, bs
->backing_file
);
5522 int bdrv_get_info(BlockDriverState
*bs
, BlockDriverInfo
*bdi
)
5524 BlockDriver
*drv
= bs
->drv
;
5525 /* if bs->drv == NULL, bs is closed, so there's nothing to do here */
5529 if (!drv
->bdrv_get_info
) {
5530 BlockDriverState
*filtered
= bdrv_filter_bs(bs
);
5532 return bdrv_get_info(filtered
, bdi
);
5536 memset(bdi
, 0, sizeof(*bdi
));
5537 return drv
->bdrv_get_info(bs
, bdi
);
5540 ImageInfoSpecific
*bdrv_get_specific_info(BlockDriverState
*bs
,
5543 BlockDriver
*drv
= bs
->drv
;
5544 if (drv
&& drv
->bdrv_get_specific_info
) {
5545 return drv
->bdrv_get_specific_info(bs
, errp
);
5550 BlockStatsSpecific
*bdrv_get_specific_stats(BlockDriverState
*bs
)
5552 BlockDriver
*drv
= bs
->drv
;
5553 if (!drv
|| !drv
->bdrv_get_specific_stats
) {
5556 return drv
->bdrv_get_specific_stats(bs
);
5559 void bdrv_debug_event(BlockDriverState
*bs
, BlkdebugEvent event
)
5561 if (!bs
|| !bs
->drv
|| !bs
->drv
->bdrv_debug_event
) {
5565 bs
->drv
->bdrv_debug_event(bs
, event
);
5568 static BlockDriverState
*bdrv_find_debug_node(BlockDriverState
*bs
)
5570 while (bs
&& bs
->drv
&& !bs
->drv
->bdrv_debug_breakpoint
) {
5571 bs
= bdrv_primary_bs(bs
);
5574 if (bs
&& bs
->drv
&& bs
->drv
->bdrv_debug_breakpoint
) {
5575 assert(bs
->drv
->bdrv_debug_remove_breakpoint
);
5582 int bdrv_debug_breakpoint(BlockDriverState
*bs
, const char *event
,
5585 bs
= bdrv_find_debug_node(bs
);
5587 return bs
->drv
->bdrv_debug_breakpoint(bs
, event
, tag
);
5593 int bdrv_debug_remove_breakpoint(BlockDriverState
*bs
, const char *tag
)
5595 bs
= bdrv_find_debug_node(bs
);
5597 return bs
->drv
->bdrv_debug_remove_breakpoint(bs
, tag
);
5603 int bdrv_debug_resume(BlockDriverState
*bs
, const char *tag
)
5605 while (bs
&& (!bs
->drv
|| !bs
->drv
->bdrv_debug_resume
)) {
5606 bs
= bdrv_primary_bs(bs
);
5609 if (bs
&& bs
->drv
&& bs
->drv
->bdrv_debug_resume
) {
5610 return bs
->drv
->bdrv_debug_resume(bs
, tag
);
5616 bool bdrv_debug_is_suspended(BlockDriverState
*bs
, const char *tag
)
5618 while (bs
&& bs
->drv
&& !bs
->drv
->bdrv_debug_is_suspended
) {
5619 bs
= bdrv_primary_bs(bs
);
5622 if (bs
&& bs
->drv
&& bs
->drv
->bdrv_debug_is_suspended
) {
5623 return bs
->drv
->bdrv_debug_is_suspended(bs
, tag
);
5629 /* backing_file can either be relative, or absolute, or a protocol. If it is
5630 * relative, it must be relative to the chain. So, passing in bs->filename
5631 * from a BDS as backing_file should not be done, as that may be relative to
5632 * the CWD rather than the chain. */
5633 BlockDriverState
*bdrv_find_backing_image(BlockDriverState
*bs
,
5634 const char *backing_file
)
5636 char *filename_full
= NULL
;
5637 char *backing_file_full
= NULL
;
5638 char *filename_tmp
= NULL
;
5639 int is_protocol
= 0;
5640 bool filenames_refreshed
= false;
5641 BlockDriverState
*curr_bs
= NULL
;
5642 BlockDriverState
*retval
= NULL
;
5643 BlockDriverState
*bs_below
;
5645 if (!bs
|| !bs
->drv
|| !backing_file
) {
5649 filename_full
= g_malloc(PATH_MAX
);
5650 backing_file_full
= g_malloc(PATH_MAX
);
5652 is_protocol
= path_has_protocol(backing_file
);
5655 * Being largely a legacy function, skip any filters here
5656 * (because filters do not have normal filenames, so they cannot
5657 * match anyway; and allowing json:{} filenames is a bit out of
5660 for (curr_bs
= bdrv_skip_filters(bs
);
5661 bdrv_cow_child(curr_bs
) != NULL
;
5664 bs_below
= bdrv_backing_chain_next(curr_bs
);
5666 if (bdrv_backing_overridden(curr_bs
)) {
5668 * If the backing file was overridden, we can only compare
5669 * directly against the backing node's filename.
5672 if (!filenames_refreshed
) {
5674 * This will automatically refresh all of the
5675 * filenames in the rest of the backing chain, so we
5676 * only need to do this once.
5678 bdrv_refresh_filename(bs_below
);
5679 filenames_refreshed
= true;
5682 if (strcmp(backing_file
, bs_below
->filename
) == 0) {
5686 } else if (is_protocol
|| path_has_protocol(curr_bs
->backing_file
)) {
5688 * If either of the filename paths is actually a protocol, then
5689 * compare unmodified paths; otherwise make paths relative.
5691 char *backing_file_full_ret
;
5693 if (strcmp(backing_file
, curr_bs
->backing_file
) == 0) {
5697 /* Also check against the full backing filename for the image */
5698 backing_file_full_ret
= bdrv_get_full_backing_filename(curr_bs
,
5700 if (backing_file_full_ret
) {
5701 bool equal
= strcmp(backing_file
, backing_file_full_ret
) == 0;
5702 g_free(backing_file_full_ret
);
5709 /* If not an absolute filename path, make it relative to the current
5710 * image's filename path */
5711 filename_tmp
= bdrv_make_absolute_filename(curr_bs
, backing_file
,
5713 /* We are going to compare canonicalized absolute pathnames */
5714 if (!filename_tmp
|| !realpath(filename_tmp
, filename_full
)) {
5715 g_free(filename_tmp
);
5718 g_free(filename_tmp
);
5720 /* We need to make sure the backing filename we are comparing against
5721 * is relative to the current image filename (or absolute) */
5722 filename_tmp
= bdrv_get_full_backing_filename(curr_bs
, NULL
);
5723 if (!filename_tmp
|| !realpath(filename_tmp
, backing_file_full
)) {
5724 g_free(filename_tmp
);
5727 g_free(filename_tmp
);
5729 if (strcmp(backing_file_full
, filename_full
) == 0) {
5736 g_free(filename_full
);
5737 g_free(backing_file_full
);
5741 void bdrv_init(void)
5743 module_call_init(MODULE_INIT_BLOCK
);
5746 void bdrv_init_with_whitelist(void)
5748 use_bdrv_whitelist
= 1;
5752 int coroutine_fn
bdrv_co_invalidate_cache(BlockDriverState
*bs
, Error
**errp
)
5754 BdrvChild
*child
, *parent
;
5755 uint64_t perm
, shared_perm
;
5756 Error
*local_err
= NULL
;
5758 BdrvDirtyBitmap
*bm
;
5764 QLIST_FOREACH(child
, &bs
->children
, next
) {
5765 bdrv_co_invalidate_cache(child
->bs
, &local_err
);
5767 error_propagate(errp
, local_err
);
5773 * Update permissions, they may differ for inactive nodes.
5775 * Note that the required permissions of inactive images are always a
5776 * subset of the permissions required after activating the image. This
5777 * allows us to just get the permissions upfront without restricting
5778 * drv->bdrv_invalidate_cache().
5780 * It also means that in error cases, we don't have to try and revert to
5781 * the old permissions (which is an operation that could fail, too). We can
5782 * just keep the extended permissions for the next time that an activation
5783 * of the image is tried.
5785 if (bs
->open_flags
& BDRV_O_INACTIVE
) {
5786 bs
->open_flags
&= ~BDRV_O_INACTIVE
;
5787 bdrv_get_cumulative_perm(bs
, &perm
, &shared_perm
);
5788 ret
= bdrv_check_perm(bs
, NULL
, perm
, shared_perm
, NULL
, NULL
, errp
);
5790 bs
->open_flags
|= BDRV_O_INACTIVE
;
5793 bdrv_set_perm(bs
, perm
, shared_perm
);
5795 if (bs
->drv
->bdrv_co_invalidate_cache
) {
5796 bs
->drv
->bdrv_co_invalidate_cache(bs
, &local_err
);
5798 bs
->open_flags
|= BDRV_O_INACTIVE
;
5799 error_propagate(errp
, local_err
);
5804 FOR_EACH_DIRTY_BITMAP(bs
, bm
) {
5805 bdrv_dirty_bitmap_skip_store(bm
, false);
5808 ret
= refresh_total_sectors(bs
, bs
->total_sectors
);
5810 bs
->open_flags
|= BDRV_O_INACTIVE
;
5811 error_setg_errno(errp
, -ret
, "Could not refresh total sector count");
5816 QLIST_FOREACH(parent
, &bs
->parents
, next_parent
) {
5817 if (parent
->klass
->activate
) {
5818 parent
->klass
->activate(parent
, &local_err
);
5820 bs
->open_flags
|= BDRV_O_INACTIVE
;
5821 error_propagate(errp
, local_err
);
5830 void bdrv_invalidate_cache_all(Error
**errp
)
5832 BlockDriverState
*bs
;
5833 BdrvNextIterator it
;
5835 for (bs
= bdrv_first(&it
); bs
; bs
= bdrv_next(&it
)) {
5836 AioContext
*aio_context
= bdrv_get_aio_context(bs
);
5839 aio_context_acquire(aio_context
);
5840 ret
= bdrv_invalidate_cache(bs
, errp
);
5841 aio_context_release(aio_context
);
5843 bdrv_next_cleanup(&it
);
5849 static bool bdrv_has_bds_parent(BlockDriverState
*bs
, bool only_active
)
5853 QLIST_FOREACH(parent
, &bs
->parents
, next_parent
) {
5854 if (parent
->klass
->parent_is_bds
) {
5855 BlockDriverState
*parent_bs
= parent
->opaque
;
5856 if (!only_active
|| !(parent_bs
->open_flags
& BDRV_O_INACTIVE
)) {
5865 static int bdrv_inactivate_recurse(BlockDriverState
*bs
)
5867 BdrvChild
*child
, *parent
;
5868 bool tighten_restrictions
;
5869 uint64_t perm
, shared_perm
;
5876 /* Make sure that we don't inactivate a child before its parent.
5877 * It will be covered by recursion from the yet active parent. */
5878 if (bdrv_has_bds_parent(bs
, true)) {
5882 assert(!(bs
->open_flags
& BDRV_O_INACTIVE
));
5884 /* Inactivate this node */
5885 if (bs
->drv
->bdrv_inactivate
) {
5886 ret
= bs
->drv
->bdrv_inactivate(bs
);
5892 QLIST_FOREACH(parent
, &bs
->parents
, next_parent
) {
5893 if (parent
->klass
->inactivate
) {
5894 ret
= parent
->klass
->inactivate(parent
);
5901 bs
->open_flags
|= BDRV_O_INACTIVE
;
5903 /* Update permissions, they may differ for inactive nodes */
5904 bdrv_get_cumulative_perm(bs
, &perm
, &shared_perm
);
5905 ret
= bdrv_check_perm(bs
, NULL
, perm
, shared_perm
, NULL
,
5906 &tighten_restrictions
, NULL
);
5907 assert(tighten_restrictions
== false);
5909 /* We only tried to loosen restrictions, so errors are not fatal */
5910 bdrv_abort_perm_update(bs
);
5912 bdrv_set_perm(bs
, perm
, shared_perm
);
5916 /* Recursively inactivate children */
5917 QLIST_FOREACH(child
, &bs
->children
, next
) {
5918 ret
= bdrv_inactivate_recurse(child
->bs
);
5927 int bdrv_inactivate_all(void)
5929 BlockDriverState
*bs
= NULL
;
5930 BdrvNextIterator it
;
5932 GSList
*aio_ctxs
= NULL
, *ctx
;
5934 for (bs
= bdrv_first(&it
); bs
; bs
= bdrv_next(&it
)) {
5935 AioContext
*aio_context
= bdrv_get_aio_context(bs
);
5937 if (!g_slist_find(aio_ctxs
, aio_context
)) {
5938 aio_ctxs
= g_slist_prepend(aio_ctxs
, aio_context
);
5939 aio_context_acquire(aio_context
);
5943 for (bs
= bdrv_first(&it
); bs
; bs
= bdrv_next(&it
)) {
5944 /* Nodes with BDS parents are covered by recursion from the last
5945 * parent that gets inactivated. Don't inactivate them a second
5946 * time if that has already happened. */
5947 if (bdrv_has_bds_parent(bs
, false)) {
5950 ret
= bdrv_inactivate_recurse(bs
);
5952 bdrv_next_cleanup(&it
);
5958 for (ctx
= aio_ctxs
; ctx
!= NULL
; ctx
= ctx
->next
) {
5959 AioContext
*aio_context
= ctx
->data
;
5960 aio_context_release(aio_context
);
5962 g_slist_free(aio_ctxs
);
5967 /**************************************************************/
5968 /* removable device support */
5971 * Return TRUE if the media is present
5973 bool bdrv_is_inserted(BlockDriverState
*bs
)
5975 BlockDriver
*drv
= bs
->drv
;
5981 if (drv
->bdrv_is_inserted
) {
5982 return drv
->bdrv_is_inserted(bs
);
5984 QLIST_FOREACH(child
, &bs
->children
, next
) {
5985 if (!bdrv_is_inserted(child
->bs
)) {
5993 * If eject_flag is TRUE, eject the media. Otherwise, close the tray
5995 void bdrv_eject(BlockDriverState
*bs
, bool eject_flag
)
5997 BlockDriver
*drv
= bs
->drv
;
5999 if (drv
&& drv
->bdrv_eject
) {
6000 drv
->bdrv_eject(bs
, eject_flag
);
6005 * Lock or unlock the media (if it is locked, the user won't be able
6006 * to eject it manually).
6008 void bdrv_lock_medium(BlockDriverState
*bs
, bool locked
)
6010 BlockDriver
*drv
= bs
->drv
;
6012 trace_bdrv_lock_medium(bs
, locked
);
6014 if (drv
&& drv
->bdrv_lock_medium
) {
6015 drv
->bdrv_lock_medium(bs
, locked
);
6019 /* Get a reference to bs */
6020 void bdrv_ref(BlockDriverState
*bs
)
6025 /* Release a previously grabbed reference to bs.
6026 * If after releasing, reference count is zero, the BlockDriverState is
6028 void bdrv_unref(BlockDriverState
*bs
)
6033 assert(bs
->refcnt
> 0);
6034 if (--bs
->refcnt
== 0) {
6039 struct BdrvOpBlocker
{
6041 QLIST_ENTRY(BdrvOpBlocker
) list
;
6044 bool bdrv_op_is_blocked(BlockDriverState
*bs
, BlockOpType op
, Error
**errp
)
6046 BdrvOpBlocker
*blocker
;
6047 assert((int) op
>= 0 && op
< BLOCK_OP_TYPE_MAX
);
6048 if (!QLIST_EMPTY(&bs
->op_blockers
[op
])) {
6049 blocker
= QLIST_FIRST(&bs
->op_blockers
[op
]);
6050 error_propagate_prepend(errp
, error_copy(blocker
->reason
),
6051 "Node '%s' is busy: ",
6052 bdrv_get_device_or_node_name(bs
));
6058 void bdrv_op_block(BlockDriverState
*bs
, BlockOpType op
, Error
*reason
)
6060 BdrvOpBlocker
*blocker
;
6061 assert((int) op
>= 0 && op
< BLOCK_OP_TYPE_MAX
);
6063 blocker
= g_new0(BdrvOpBlocker
, 1);
6064 blocker
->reason
= reason
;
6065 QLIST_INSERT_HEAD(&bs
->op_blockers
[op
], blocker
, list
);
6068 void bdrv_op_unblock(BlockDriverState
*bs
, BlockOpType op
, Error
*reason
)
6070 BdrvOpBlocker
*blocker
, *next
;
6071 assert((int) op
>= 0 && op
< BLOCK_OP_TYPE_MAX
);
6072 QLIST_FOREACH_SAFE(blocker
, &bs
->op_blockers
[op
], list
, next
) {
6073 if (blocker
->reason
== reason
) {
6074 QLIST_REMOVE(blocker
, list
);
6080 void bdrv_op_block_all(BlockDriverState
*bs
, Error
*reason
)
6083 for (i
= 0; i
< BLOCK_OP_TYPE_MAX
; i
++) {
6084 bdrv_op_block(bs
, i
, reason
);
6088 void bdrv_op_unblock_all(BlockDriverState
*bs
, Error
*reason
)
6091 for (i
= 0; i
< BLOCK_OP_TYPE_MAX
; i
++) {
6092 bdrv_op_unblock(bs
, i
, reason
);
6096 bool bdrv_op_blocker_is_empty(BlockDriverState
*bs
)
6100 for (i
= 0; i
< BLOCK_OP_TYPE_MAX
; i
++) {
6101 if (!QLIST_EMPTY(&bs
->op_blockers
[i
])) {
6108 void bdrv_img_create(const char *filename
, const char *fmt
,
6109 const char *base_filename
, const char *base_fmt
,
6110 char *options
, uint64_t img_size
, int flags
, bool quiet
,
6113 QemuOptsList
*create_opts
= NULL
;
6114 QemuOpts
*opts
= NULL
;
6115 const char *backing_fmt
, *backing_file
;
6117 BlockDriver
*drv
, *proto_drv
;
6118 Error
*local_err
= NULL
;
6121 /* Find driver and parse its options */
6122 drv
= bdrv_find_format(fmt
);
6124 error_setg(errp
, "Unknown file format '%s'", fmt
);
6128 proto_drv
= bdrv_find_protocol(filename
, true, errp
);
6133 if (!drv
->create_opts
) {
6134 error_setg(errp
, "Format driver '%s' does not support image creation",
6139 if (!proto_drv
->create_opts
) {
6140 error_setg(errp
, "Protocol driver '%s' does not support image creation",
6141 proto_drv
->format_name
);
6145 /* Create parameter list */
6146 create_opts
= qemu_opts_append(create_opts
, drv
->create_opts
);
6147 create_opts
= qemu_opts_append(create_opts
, proto_drv
->create_opts
);
6149 opts
= qemu_opts_create(create_opts
, NULL
, 0, &error_abort
);
6151 /* Parse -o options */
6153 if (!qemu_opts_do_parse(opts
, options
, NULL
, errp
)) {
6158 if (!qemu_opt_get(opts
, BLOCK_OPT_SIZE
)) {
6159 qemu_opt_set_number(opts
, BLOCK_OPT_SIZE
, img_size
, &error_abort
);
6160 } else if (img_size
!= UINT64_C(-1)) {
6161 error_setg(errp
, "The image size must be specified only once");
6165 if (base_filename
) {
6166 if (!qemu_opt_set(opts
, BLOCK_OPT_BACKING_FILE
, base_filename
,
6168 error_setg(errp
, "Backing file not supported for file format '%s'",
6175 if (!qemu_opt_set(opts
, BLOCK_OPT_BACKING_FMT
, base_fmt
, NULL
)) {
6176 error_setg(errp
, "Backing file format not supported for file "
6177 "format '%s'", fmt
);
6182 backing_file
= qemu_opt_get(opts
, BLOCK_OPT_BACKING_FILE
);
6184 if (!strcmp(filename
, backing_file
)) {
6185 error_setg(errp
, "Error: Trying to create an image with the "
6186 "same filename as the backing file");
6189 if (backing_file
[0] == '\0') {
6190 error_setg(errp
, "Expected backing file name, got empty string");
6195 backing_fmt
= qemu_opt_get(opts
, BLOCK_OPT_BACKING_FMT
);
6197 /* The size for the image must always be specified, unless we have a backing
6198 * file and we have not been forbidden from opening it. */
6199 size
= qemu_opt_get_size(opts
, BLOCK_OPT_SIZE
, img_size
);
6200 if (backing_file
&& !(flags
& BDRV_O_NO_BACKING
)) {
6201 BlockDriverState
*bs
;
6204 QDict
*backing_options
= NULL
;
6207 bdrv_get_full_backing_filename_from_filename(filename
, backing_file
,
6212 assert(full_backing
);
6214 /* backing files always opened read-only */
6216 back_flags
&= ~(BDRV_O_RDWR
| BDRV_O_SNAPSHOT
| BDRV_O_NO_BACKING
);
6218 backing_options
= qdict_new();
6220 qdict_put_str(backing_options
, "driver", backing_fmt
);
6222 qdict_put_bool(backing_options
, BDRV_OPT_FORCE_SHARE
, true);
6224 bs
= bdrv_open(full_backing
, NULL
, backing_options
, back_flags
,
6226 g_free(full_backing
);
6228 error_append_hint(&local_err
, "Could not open backing image.\n");
6232 warn_report("Deprecated use of backing file without explicit "
6233 "backing format (detected format of %s)",
6234 bs
->drv
->format_name
);
6235 if (bs
->drv
!= &bdrv_raw
) {
6237 * A probe of raw deserves the most attention:
6238 * leaving the backing format out of the image
6239 * will ensure bs->probed is set (ensuring we
6240 * don't accidentally commit into the backing
6241 * file), and allow more spots to warn the users
6242 * to fix their toolchain when opening this image
6243 * later. For other images, we can safely record
6244 * the format that we probed.
6246 backing_fmt
= bs
->drv
->format_name
;
6247 qemu_opt_set(opts
, BLOCK_OPT_BACKING_FMT
, backing_fmt
,
6252 /* Opened BS, have no size */
6253 size
= bdrv_getlength(bs
);
6255 error_setg_errno(errp
, -size
, "Could not get size of '%s'",
6260 qemu_opt_set_number(opts
, BLOCK_OPT_SIZE
, size
, &error_abort
);
6264 /* (backing_file && !(flags & BDRV_O_NO_BACKING)) */
6265 } else if (backing_file
&& !backing_fmt
) {
6266 warn_report("Deprecated use of unopened backing file without "
6267 "explicit backing format, use of this image requires "
6268 "potentially unsafe format probing");
6272 error_setg(errp
, "Image creation needs a size parameter");
6277 printf("Formatting '%s', fmt=%s ", filename
, fmt
);
6278 qemu_opts_print(opts
, " ");
6283 ret
= bdrv_create(drv
, filename
, opts
, &local_err
);
6285 if (ret
== -EFBIG
) {
6286 /* This is generally a better message than whatever the driver would
6287 * deliver (especially because of the cluster_size_hint), since that
6288 * is most probably not much different from "image too large". */
6289 const char *cluster_size_hint
= "";
6290 if (qemu_opt_get_size(opts
, BLOCK_OPT_CLUSTER_SIZE
, 0)) {
6291 cluster_size_hint
= " (try using a larger cluster size)";
6293 error_setg(errp
, "The image size is too large for file format '%s'"
6294 "%s", fmt
, cluster_size_hint
);
6295 error_free(local_err
);
6300 qemu_opts_del(opts
);
6301 qemu_opts_free(create_opts
);
6302 error_propagate(errp
, local_err
);
6305 AioContext
*bdrv_get_aio_context(BlockDriverState
*bs
)
6307 return bs
? bs
->aio_context
: qemu_get_aio_context();
6310 AioContext
*coroutine_fn
bdrv_co_enter(BlockDriverState
*bs
)
6312 Coroutine
*self
= qemu_coroutine_self();
6313 AioContext
*old_ctx
= qemu_coroutine_get_aio_context(self
);
6314 AioContext
*new_ctx
;
6317 * Increase bs->in_flight to ensure that this operation is completed before
6318 * moving the node to a different AioContext. Read new_ctx only afterwards.
6320 bdrv_inc_in_flight(bs
);
6322 new_ctx
= bdrv_get_aio_context(bs
);
6323 aio_co_reschedule_self(new_ctx
);
6327 void coroutine_fn
bdrv_co_leave(BlockDriverState
*bs
, AioContext
*old_ctx
)
6329 aio_co_reschedule_self(old_ctx
);
6330 bdrv_dec_in_flight(bs
);
6333 void coroutine_fn
bdrv_co_lock(BlockDriverState
*bs
)
6335 AioContext
*ctx
= bdrv_get_aio_context(bs
);
6337 /* In the main thread, bs->aio_context won't change concurrently */
6338 assert(qemu_get_current_aio_context() == qemu_get_aio_context());
6341 * We're in coroutine context, so we already hold the lock of the main
6342 * loop AioContext. Don't lock it twice to avoid deadlocks.
6344 assert(qemu_in_coroutine());
6345 if (ctx
!= qemu_get_aio_context()) {
6346 aio_context_acquire(ctx
);
6350 void coroutine_fn
bdrv_co_unlock(BlockDriverState
*bs
)
6352 AioContext
*ctx
= bdrv_get_aio_context(bs
);
6354 assert(qemu_in_coroutine());
6355 if (ctx
!= qemu_get_aio_context()) {
6356 aio_context_release(ctx
);
6360 void bdrv_coroutine_enter(BlockDriverState
*bs
, Coroutine
*co
)
6362 aio_co_enter(bdrv_get_aio_context(bs
), co
);
6365 static void bdrv_do_remove_aio_context_notifier(BdrvAioNotifier
*ban
)
6367 QLIST_REMOVE(ban
, list
);
6371 static void bdrv_detach_aio_context(BlockDriverState
*bs
)
6373 BdrvAioNotifier
*baf
, *baf_tmp
;
6375 assert(!bs
->walking_aio_notifiers
);
6376 bs
->walking_aio_notifiers
= true;
6377 QLIST_FOREACH_SAFE(baf
, &bs
->aio_notifiers
, list
, baf_tmp
) {
6379 bdrv_do_remove_aio_context_notifier(baf
);
6381 baf
->detach_aio_context(baf
->opaque
);
6384 /* Never mind iterating again to check for ->deleted. bdrv_close() will
6385 * remove remaining aio notifiers if we aren't called again.
6387 bs
->walking_aio_notifiers
= false;
6389 if (bs
->drv
&& bs
->drv
->bdrv_detach_aio_context
) {
6390 bs
->drv
->bdrv_detach_aio_context(bs
);
6393 if (bs
->quiesce_counter
) {
6394 aio_enable_external(bs
->aio_context
);
6396 bs
->aio_context
= NULL
;
6399 static void bdrv_attach_aio_context(BlockDriverState
*bs
,
6400 AioContext
*new_context
)
6402 BdrvAioNotifier
*ban
, *ban_tmp
;
6404 if (bs
->quiesce_counter
) {
6405 aio_disable_external(new_context
);
6408 bs
->aio_context
= new_context
;
6410 if (bs
->drv
&& bs
->drv
->bdrv_attach_aio_context
) {
6411 bs
->drv
->bdrv_attach_aio_context(bs
, new_context
);
6414 assert(!bs
->walking_aio_notifiers
);
6415 bs
->walking_aio_notifiers
= true;
6416 QLIST_FOREACH_SAFE(ban
, &bs
->aio_notifiers
, list
, ban_tmp
) {
6418 bdrv_do_remove_aio_context_notifier(ban
);
6420 ban
->attached_aio_context(new_context
, ban
->opaque
);
6423 bs
->walking_aio_notifiers
= false;
6427 * Changes the AioContext used for fd handlers, timers, and BHs by this
6428 * BlockDriverState and all its children and parents.
6430 * Must be called from the main AioContext.
6432 * The caller must own the AioContext lock for the old AioContext of bs, but it
6433 * must not own the AioContext lock for new_context (unless new_context is the
6434 * same as the current context of bs).
6436 * @ignore will accumulate all visited BdrvChild object. The caller is
6437 * responsible for freeing the list afterwards.
6439 void bdrv_set_aio_context_ignore(BlockDriverState
*bs
,
6440 AioContext
*new_context
, GSList
**ignore
)
6442 AioContext
*old_context
= bdrv_get_aio_context(bs
);
6445 g_assert(qemu_get_current_aio_context() == qemu_get_aio_context());
6447 if (old_context
== new_context
) {
6451 bdrv_drained_begin(bs
);
6453 QLIST_FOREACH(child
, &bs
->children
, next
) {
6454 if (g_slist_find(*ignore
, child
)) {
6457 *ignore
= g_slist_prepend(*ignore
, child
);
6458 bdrv_set_aio_context_ignore(child
->bs
, new_context
, ignore
);
6460 QLIST_FOREACH(child
, &bs
->parents
, next_parent
) {
6461 if (g_slist_find(*ignore
, child
)) {
6464 assert(child
->klass
->set_aio_ctx
);
6465 *ignore
= g_slist_prepend(*ignore
, child
);
6466 child
->klass
->set_aio_ctx(child
, new_context
, ignore
);
6469 bdrv_detach_aio_context(bs
);
6471 /* Acquire the new context, if necessary */
6472 if (qemu_get_aio_context() != new_context
) {
6473 aio_context_acquire(new_context
);
6476 bdrv_attach_aio_context(bs
, new_context
);
6479 * If this function was recursively called from
6480 * bdrv_set_aio_context_ignore(), there may be nodes in the
6481 * subtree that have not yet been moved to the new AioContext.
6482 * Release the old one so bdrv_drained_end() can poll them.
6484 if (qemu_get_aio_context() != old_context
) {
6485 aio_context_release(old_context
);
6488 bdrv_drained_end(bs
);
6490 if (qemu_get_aio_context() != old_context
) {
6491 aio_context_acquire(old_context
);
6493 if (qemu_get_aio_context() != new_context
) {
6494 aio_context_release(new_context
);
6498 static bool bdrv_parent_can_set_aio_context(BdrvChild
*c
, AioContext
*ctx
,
6499 GSList
**ignore
, Error
**errp
)
6501 if (g_slist_find(*ignore
, c
)) {
6504 *ignore
= g_slist_prepend(*ignore
, c
);
6507 * A BdrvChildClass that doesn't handle AioContext changes cannot
6508 * tolerate any AioContext changes
6510 if (!c
->klass
->can_set_aio_ctx
) {
6511 char *user
= bdrv_child_user_desc(c
);
6512 error_setg(errp
, "Changing iothreads is not supported by %s", user
);
6516 if (!c
->klass
->can_set_aio_ctx(c
, ctx
, ignore
, errp
)) {
6517 assert(!errp
|| *errp
);
6523 bool bdrv_child_can_set_aio_context(BdrvChild
*c
, AioContext
*ctx
,
6524 GSList
**ignore
, Error
**errp
)
6526 if (g_slist_find(*ignore
, c
)) {
6529 *ignore
= g_slist_prepend(*ignore
, c
);
6530 return bdrv_can_set_aio_context(c
->bs
, ctx
, ignore
, errp
);
6533 /* @ignore will accumulate all visited BdrvChild object. The caller is
6534 * responsible for freeing the list afterwards. */
6535 bool bdrv_can_set_aio_context(BlockDriverState
*bs
, AioContext
*ctx
,
6536 GSList
**ignore
, Error
**errp
)
6540 if (bdrv_get_aio_context(bs
) == ctx
) {
6544 QLIST_FOREACH(c
, &bs
->parents
, next_parent
) {
6545 if (!bdrv_parent_can_set_aio_context(c
, ctx
, ignore
, errp
)) {
6549 QLIST_FOREACH(c
, &bs
->children
, next
) {
6550 if (!bdrv_child_can_set_aio_context(c
, ctx
, ignore
, errp
)) {
6558 int bdrv_child_try_set_aio_context(BlockDriverState
*bs
, AioContext
*ctx
,
6559 BdrvChild
*ignore_child
, Error
**errp
)
6564 ignore
= ignore_child
? g_slist_prepend(NULL
, ignore_child
) : NULL
;
6565 ret
= bdrv_can_set_aio_context(bs
, ctx
, &ignore
, errp
);
6566 g_slist_free(ignore
);
6572 ignore
= ignore_child
? g_slist_prepend(NULL
, ignore_child
) : NULL
;
6573 bdrv_set_aio_context_ignore(bs
, ctx
, &ignore
);
6574 g_slist_free(ignore
);
6579 int bdrv_try_set_aio_context(BlockDriverState
*bs
, AioContext
*ctx
,
6582 return bdrv_child_try_set_aio_context(bs
, ctx
, NULL
, errp
);
6585 void bdrv_add_aio_context_notifier(BlockDriverState
*bs
,
6586 void (*attached_aio_context
)(AioContext
*new_context
, void *opaque
),
6587 void (*detach_aio_context
)(void *opaque
), void *opaque
)
6589 BdrvAioNotifier
*ban
= g_new(BdrvAioNotifier
, 1);
6590 *ban
= (BdrvAioNotifier
){
6591 .attached_aio_context
= attached_aio_context
,
6592 .detach_aio_context
= detach_aio_context
,
6596 QLIST_INSERT_HEAD(&bs
->aio_notifiers
, ban
, list
);
6599 void bdrv_remove_aio_context_notifier(BlockDriverState
*bs
,
6600 void (*attached_aio_context
)(AioContext
*,
6602 void (*detach_aio_context
)(void *),
6605 BdrvAioNotifier
*ban
, *ban_next
;
6607 QLIST_FOREACH_SAFE(ban
, &bs
->aio_notifiers
, list
, ban_next
) {
6608 if (ban
->attached_aio_context
== attached_aio_context
&&
6609 ban
->detach_aio_context
== detach_aio_context
&&
6610 ban
->opaque
== opaque
&&
6611 ban
->deleted
== false)
6613 if (bs
->walking_aio_notifiers
) {
6614 ban
->deleted
= true;
6616 bdrv_do_remove_aio_context_notifier(ban
);
6625 int bdrv_amend_options(BlockDriverState
*bs
, QemuOpts
*opts
,
6626 BlockDriverAmendStatusCB
*status_cb
, void *cb_opaque
,
6631 error_setg(errp
, "Node is ejected");
6634 if (!bs
->drv
->bdrv_amend_options
) {
6635 error_setg(errp
, "Block driver '%s' does not support option amendment",
6636 bs
->drv
->format_name
);
6639 return bs
->drv
->bdrv_amend_options(bs
, opts
, status_cb
,
6640 cb_opaque
, force
, errp
);
6644 * This function checks whether the given @to_replace is allowed to be
6645 * replaced by a node that always shows the same data as @bs. This is
6646 * used for example to verify whether the mirror job can replace
6647 * @to_replace by the target mirrored from @bs.
6648 * To be replaceable, @bs and @to_replace may either be guaranteed to
6649 * always show the same data (because they are only connected through
6650 * filters), or some driver may allow replacing one of its children
6651 * because it can guarantee that this child's data is not visible at
6652 * all (for example, for dissenting quorum children that have no other
6655 bool bdrv_recurse_can_replace(BlockDriverState
*bs
,
6656 BlockDriverState
*to_replace
)
6658 BlockDriverState
*filtered
;
6660 if (!bs
|| !bs
->drv
) {
6664 if (bs
== to_replace
) {
6668 /* See what the driver can do */
6669 if (bs
->drv
->bdrv_recurse_can_replace
) {
6670 return bs
->drv
->bdrv_recurse_can_replace(bs
, to_replace
);
6673 /* For filters without an own implementation, we can recurse on our own */
6674 filtered
= bdrv_filter_bs(bs
);
6676 return bdrv_recurse_can_replace(filtered
, to_replace
);
6684 * Check whether the given @node_name can be replaced by a node that
6685 * has the same data as @parent_bs. If so, return @node_name's BDS;
6688 * @node_name must be a (recursive) *child of @parent_bs (or this
6689 * function will return NULL).
6691 * The result (whether the node can be replaced or not) is only valid
6692 * for as long as no graph or permission changes occur.
6694 BlockDriverState
*check_to_replace_node(BlockDriverState
*parent_bs
,
6695 const char *node_name
, Error
**errp
)
6697 BlockDriverState
*to_replace_bs
= bdrv_find_node(node_name
);
6698 AioContext
*aio_context
;
6700 if (!to_replace_bs
) {
6701 error_setg(errp
, "Node name '%s' not found", node_name
);
6705 aio_context
= bdrv_get_aio_context(to_replace_bs
);
6706 aio_context_acquire(aio_context
);
6708 if (bdrv_op_is_blocked(to_replace_bs
, BLOCK_OP_TYPE_REPLACE
, errp
)) {
6709 to_replace_bs
= NULL
;
6713 /* We don't want arbitrary node of the BDS chain to be replaced only the top
6714 * most non filter in order to prevent data corruption.
6715 * Another benefit is that this tests exclude backing files which are
6716 * blocked by the backing blockers.
6718 if (!bdrv_recurse_can_replace(parent_bs
, to_replace_bs
)) {
6719 error_setg(errp
, "Cannot replace '%s' by a node mirrored from '%s', "
6720 "because it cannot be guaranteed that doing so would not "
6721 "lead to an abrupt change of visible data",
6722 node_name
, parent_bs
->node_name
);
6723 to_replace_bs
= NULL
;
6728 aio_context_release(aio_context
);
6729 return to_replace_bs
;
6733 * Iterates through the list of runtime option keys that are said to
6734 * be "strong" for a BDS. An option is called "strong" if it changes
6735 * a BDS's data. For example, the null block driver's "size" and
6736 * "read-zeroes" options are strong, but its "latency-ns" option is
6739 * If a key returned by this function ends with a dot, all options
6740 * starting with that prefix are strong.
6742 static const char *const *strong_options(BlockDriverState
*bs
,
6743 const char *const *curopt
)
6745 static const char *const global_options
[] = {
6746 "driver", "filename", NULL
6750 return &global_options
[0];
6754 if (curopt
== &global_options
[ARRAY_SIZE(global_options
) - 1] && bs
->drv
) {
6755 curopt
= bs
->drv
->strong_runtime_opts
;
6758 return (curopt
&& *curopt
) ? curopt
: NULL
;
6762 * Copies all strong runtime options from bs->options to the given
6763 * QDict. The set of strong option keys is determined by invoking
6766 * Returns true iff any strong option was present in bs->options (and
6767 * thus copied to the target QDict) with the exception of "filename"
6768 * and "driver". The caller is expected to use this value to decide
6769 * whether the existence of strong options prevents the generation of
6772 static bool append_strong_runtime_options(QDict
*d
, BlockDriverState
*bs
)
6774 bool found_any
= false;
6775 const char *const *option_name
= NULL
;
6781 while ((option_name
= strong_options(bs
, option_name
))) {
6782 bool option_given
= false;
6784 assert(strlen(*option_name
) > 0);
6785 if ((*option_name
)[strlen(*option_name
) - 1] != '.') {
6786 QObject
*entry
= qdict_get(bs
->options
, *option_name
);
6791 qdict_put_obj(d
, *option_name
, qobject_ref(entry
));
6792 option_given
= true;
6794 const QDictEntry
*entry
;
6795 for (entry
= qdict_first(bs
->options
); entry
;
6796 entry
= qdict_next(bs
->options
, entry
))
6798 if (strstart(qdict_entry_key(entry
), *option_name
, NULL
)) {
6799 qdict_put_obj(d
, qdict_entry_key(entry
),
6800 qobject_ref(qdict_entry_value(entry
)));
6801 option_given
= true;
6806 /* While "driver" and "filename" need to be included in a JSON filename,
6807 * their existence does not prohibit generation of a plain filename. */
6808 if (!found_any
&& option_given
&&
6809 strcmp(*option_name
, "driver") && strcmp(*option_name
, "filename"))
6815 if (!qdict_haskey(d
, "driver")) {
6816 /* Drivers created with bdrv_new_open_driver() may not have a
6817 * @driver option. Add it here. */
6818 qdict_put_str(d
, "driver", bs
->drv
->format_name
);
6824 /* Note: This function may return false positives; it may return true
6825 * even if opening the backing file specified by bs's image header
6826 * would result in exactly bs->backing. */
6827 bool bdrv_backing_overridden(BlockDriverState
*bs
)
6830 return strcmp(bs
->auto_backing_file
,
6831 bs
->backing
->bs
->filename
);
6833 /* No backing BDS, so if the image header reports any backing
6834 * file, it must have been suppressed */
6835 return bs
->auto_backing_file
[0] != '\0';
6839 /* Updates the following BDS fields:
6840 * - exact_filename: A filename which may be used for opening a block device
6841 * which (mostly) equals the given BDS (even without any
6842 * other options; so reading and writing must return the same
6843 * results, but caching etc. may be different)
6844 * - full_open_options: Options which, when given when opening a block device
6845 * (without a filename), result in a BDS (mostly)
6846 * equalling the given one
6847 * - filename: If exact_filename is set, it is copied here. Otherwise,
6848 * full_open_options is converted to a JSON object, prefixed with
6849 * "json:" (for use through the JSON pseudo protocol) and put here.
6851 void bdrv_refresh_filename(BlockDriverState
*bs
)
6853 BlockDriver
*drv
= bs
->drv
;
6855 BlockDriverState
*primary_child_bs
;
6857 bool backing_overridden
;
6858 bool generate_json_filename
; /* Whether our default implementation should
6859 fill exact_filename (false) or not (true) */
6865 /* This BDS's file name may depend on any of its children's file names, so
6866 * refresh those first */
6867 QLIST_FOREACH(child
, &bs
->children
, next
) {
6868 bdrv_refresh_filename(child
->bs
);
6872 /* For implicit nodes, just copy everything from the single child */
6873 child
= QLIST_FIRST(&bs
->children
);
6874 assert(QLIST_NEXT(child
, next
) == NULL
);
6876 pstrcpy(bs
->exact_filename
, sizeof(bs
->exact_filename
),
6877 child
->bs
->exact_filename
);
6878 pstrcpy(bs
->filename
, sizeof(bs
->filename
), child
->bs
->filename
);
6880 qobject_unref(bs
->full_open_options
);
6881 bs
->full_open_options
= qobject_ref(child
->bs
->full_open_options
);
6886 backing_overridden
= bdrv_backing_overridden(bs
);
6888 if (bs
->open_flags
& BDRV_O_NO_IO
) {
6889 /* Without I/O, the backing file does not change anything.
6890 * Therefore, in such a case (primarily qemu-img), we can
6891 * pretend the backing file has not been overridden even if
6892 * it technically has been. */
6893 backing_overridden
= false;
6896 /* Gather the options QDict */
6898 generate_json_filename
= append_strong_runtime_options(opts
, bs
);
6899 generate_json_filename
|= backing_overridden
;
6901 if (drv
->bdrv_gather_child_options
) {
6902 /* Some block drivers may not want to present all of their children's
6903 * options, or name them differently from BdrvChild.name */
6904 drv
->bdrv_gather_child_options(bs
, opts
, backing_overridden
);
6906 QLIST_FOREACH(child
, &bs
->children
, next
) {
6907 if (child
== bs
->backing
&& !backing_overridden
) {
6908 /* We can skip the backing BDS if it has not been overridden */
6912 qdict_put(opts
, child
->name
,
6913 qobject_ref(child
->bs
->full_open_options
));
6916 if (backing_overridden
&& !bs
->backing
) {
6917 /* Force no backing file */
6918 qdict_put_null(opts
, "backing");
6922 qobject_unref(bs
->full_open_options
);
6923 bs
->full_open_options
= opts
;
6925 primary_child_bs
= bdrv_primary_bs(bs
);
6927 if (drv
->bdrv_refresh_filename
) {
6928 /* Obsolete information is of no use here, so drop the old file name
6929 * information before refreshing it */
6930 bs
->exact_filename
[0] = '\0';
6932 drv
->bdrv_refresh_filename(bs
);
6933 } else if (primary_child_bs
) {
6935 * Try to reconstruct valid information from the underlying
6936 * file -- this only works for format nodes (filter nodes
6937 * cannot be probed and as such must be selected by the user
6938 * either through an options dict, or through a special
6939 * filename which the filter driver must construct in its
6940 * .bdrv_refresh_filename() implementation).
6943 bs
->exact_filename
[0] = '\0';
6946 * We can use the underlying file's filename if:
6947 * - it has a filename,
6948 * - the current BDS is not a filter,
6949 * - the file is a protocol BDS, and
6950 * - opening that file (as this BDS's format) will automatically create
6951 * the BDS tree we have right now, that is:
6952 * - the user did not significantly change this BDS's behavior with
6953 * some explicit (strong) options
6954 * - no non-file child of this BDS has been overridden by the user
6955 * Both of these conditions are represented by generate_json_filename.
6957 if (primary_child_bs
->exact_filename
[0] &&
6958 primary_child_bs
->drv
->bdrv_file_open
&&
6959 !drv
->is_filter
&& !generate_json_filename
)
6961 strcpy(bs
->exact_filename
, primary_child_bs
->exact_filename
);
6965 if (bs
->exact_filename
[0]) {
6966 pstrcpy(bs
->filename
, sizeof(bs
->filename
), bs
->exact_filename
);
6968 QString
*json
= qobject_to_json(QOBJECT(bs
->full_open_options
));
6969 if (snprintf(bs
->filename
, sizeof(bs
->filename
), "json:%s",
6970 qstring_get_str(json
)) >= sizeof(bs
->filename
)) {
6971 /* Give user a hint if we truncated things. */
6972 strcpy(bs
->filename
+ sizeof(bs
->filename
) - 4, "...");
6974 qobject_unref(json
);
6978 char *bdrv_dirname(BlockDriverState
*bs
, Error
**errp
)
6980 BlockDriver
*drv
= bs
->drv
;
6981 BlockDriverState
*child_bs
;
6984 error_setg(errp
, "Node '%s' is ejected", bs
->node_name
);
6988 if (drv
->bdrv_dirname
) {
6989 return drv
->bdrv_dirname(bs
, errp
);
6992 child_bs
= bdrv_primary_bs(bs
);
6994 return bdrv_dirname(child_bs
, errp
);
6997 bdrv_refresh_filename(bs
);
6998 if (bs
->exact_filename
[0] != '\0') {
6999 return path_combine(bs
->exact_filename
, "");
7002 error_setg(errp
, "Cannot generate a base directory for %s nodes",
7008 * Hot add/remove a BDS's child. So the user can take a child offline when
7009 * it is broken and take a new child online
7011 void bdrv_add_child(BlockDriverState
*parent_bs
, BlockDriverState
*child_bs
,
7015 if (!parent_bs
->drv
|| !parent_bs
->drv
->bdrv_add_child
) {
7016 error_setg(errp
, "The node %s does not support adding a child",
7017 bdrv_get_device_or_node_name(parent_bs
));
7021 if (!QLIST_EMPTY(&child_bs
->parents
)) {
7022 error_setg(errp
, "The node %s already has a parent",
7023 child_bs
->node_name
);
7027 parent_bs
->drv
->bdrv_add_child(parent_bs
, child_bs
, errp
);
7030 void bdrv_del_child(BlockDriverState
*parent_bs
, BdrvChild
*child
, Error
**errp
)
7034 if (!parent_bs
->drv
|| !parent_bs
->drv
->bdrv_del_child
) {
7035 error_setg(errp
, "The node %s does not support removing a child",
7036 bdrv_get_device_or_node_name(parent_bs
));
7040 QLIST_FOREACH(tmp
, &parent_bs
->children
, next
) {
7047 error_setg(errp
, "The node %s does not have a child named %s",
7048 bdrv_get_device_or_node_name(parent_bs
),
7049 bdrv_get_device_or_node_name(child
->bs
));
7053 parent_bs
->drv
->bdrv_del_child(parent_bs
, child
, errp
);
7056 int bdrv_make_empty(BdrvChild
*c
, Error
**errp
)
7058 BlockDriver
*drv
= c
->bs
->drv
;
7061 assert(c
->perm
& (BLK_PERM_WRITE
| BLK_PERM_WRITE_UNCHANGED
));
7063 if (!drv
->bdrv_make_empty
) {
7064 error_setg(errp
, "%s does not support emptying nodes",
7069 ret
= drv
->bdrv_make_empty(c
->bs
);
7071 error_setg_errno(errp
, -ret
, "Failed to empty %s",
7080 * Return the child that @bs acts as an overlay for, and from which data may be
7081 * copied in COW or COR operations. Usually this is the backing file.
7083 BdrvChild
*bdrv_cow_child(BlockDriverState
*bs
)
7085 if (!bs
|| !bs
->drv
) {
7089 if (bs
->drv
->is_filter
) {
7097 assert(bs
->backing
->role
& BDRV_CHILD_COW
);
7102 * If @bs acts as a filter for exactly one of its children, return
7105 BdrvChild
*bdrv_filter_child(BlockDriverState
*bs
)
7109 if (!bs
|| !bs
->drv
) {
7113 if (!bs
->drv
->is_filter
) {
7117 /* Only one of @backing or @file may be used */
7118 assert(!(bs
->backing
&& bs
->file
));
7120 c
= bs
->backing
?: bs
->file
;
7125 assert(c
->role
& BDRV_CHILD_FILTERED
);
7130 * Return either the result of bdrv_cow_child() or bdrv_filter_child(),
7131 * whichever is non-NULL.
7133 * Return NULL if both are NULL.
7135 BdrvChild
*bdrv_filter_or_cow_child(BlockDriverState
*bs
)
7137 BdrvChild
*cow_child
= bdrv_cow_child(bs
);
7138 BdrvChild
*filter_child
= bdrv_filter_child(bs
);
7140 /* Filter nodes cannot have COW backing files */
7141 assert(!(cow_child
&& filter_child
));
7143 return cow_child
?: filter_child
;
7147 * Return the primary child of this node: For filters, that is the
7148 * filtered child. For other nodes, that is usually the child storing
7150 * (A generally more helpful description is that this is (usually) the
7151 * child that has the same filename as @bs.)
7153 * Drivers do not necessarily have a primary child; for example quorum
7156 BdrvChild
*bdrv_primary_child(BlockDriverState
*bs
)
7158 BdrvChild
*c
, *found
= NULL
;
7160 QLIST_FOREACH(c
, &bs
->children
, next
) {
7161 if (c
->role
& BDRV_CHILD_PRIMARY
) {
7170 static BlockDriverState
*bdrv_do_skip_filters(BlockDriverState
*bs
,
7171 bool stop_on_explicit_filter
)
7179 while (!(stop_on_explicit_filter
&& !bs
->implicit
)) {
7180 c
= bdrv_filter_child(bs
);
7183 * A filter that is embedded in a working block graph must
7184 * have a child. Assert this here so this function does
7185 * not return a filter node that is not expected by the
7188 assert(!bs
->drv
|| !bs
->drv
->is_filter
);
7194 * Note that this treats nodes with bs->drv == NULL as not being
7195 * filters (bs->drv == NULL should be replaced by something else
7197 * The advantage of this behavior is that this function will thus
7198 * always return a non-NULL value (given a non-NULL @bs).
7205 * Return the first BDS that has not been added implicitly or that
7206 * does not have a filtered child down the chain starting from @bs
7207 * (including @bs itself).
7209 BlockDriverState
*bdrv_skip_implicit_filters(BlockDriverState
*bs
)
7211 return bdrv_do_skip_filters(bs
, true);
7215 * Return the first BDS that does not have a filtered child down the
7216 * chain starting from @bs (including @bs itself).
7218 BlockDriverState
*bdrv_skip_filters(BlockDriverState
*bs
)
7220 return bdrv_do_skip_filters(bs
, false);
7224 * For a backing chain, return the first non-filter backing image of
7225 * the first non-filter image.
7227 BlockDriverState
*bdrv_backing_chain_next(BlockDriverState
*bs
)
7229 return bdrv_skip_filters(bdrv_cow_bs(bdrv_skip_filters(bs
)));